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
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, GeneralizedNewtypeDeriving, StandaloneDeriving #-} -- Implements "Indentation Senstivie Parsing" for Trifecta module Text.Trifecta.Indentation ( I.IndentationRel(..), I.Indentation, I.infIndentation, I.mkIndentationState, I.IndentationState, IndentationParsing(..), Token, IndentationParserT, runIndentationParserT, evalIndentationParserT, execIndentationParserT, ) where import Control.Applicative import Control.Monad.State.Lazy as LazyState import Control.Monad.State.Strict as StrictState import Text.Parser.Combinators (Parsing(..)) import Text.Parser.Token (TokenParsing(..)) import Text.Parser.Char (CharParsing(..)) import Text.Parser.LookAhead (LookAheadParsing(..)) import Text.Trifecta.Combinators (DeltaParsing(..), MarkParsing(..)) import Text.Trifecta.Delta (Delta, column) import Text.Parser.Indentation.Implementation (IndentationState(..), IndentationRel(..), LocalState) import qualified Text.Parser.Indentation.Implementation as I -------------- -- User API -- -------------- class IndentationParsing m where localTokenMode :: (IndentationRel -> IndentationRel) -> m a -> m a localIndentation :: IndentationRel -> m a -> m a absoluteIndentation :: m a -> m a ignoreAbsoluteIndentation :: m a -> m a localAbsoluteIndentation :: m a -> m a localAbsoluteIndentation = ignoreAbsoluteIndentation . absoluteIndentation ---------------------- -- Lifted Instances -- ---------------------- {- TODO: Applicative Functor MonadWriter w m MonadError e m Monad m MonadReader r m MonadTrans (StateT s) Monad m Monad m MonadFix m MonadPlus m MonadIO m MonadCont m #-} {-# INLINE liftLazyStateT2 #-} liftLazyStateT2 :: (m (a, s) -> m (a, s)) -> LazyState.StateT s m a -> LazyState.StateT s m a liftLazyStateT2 f m = LazyState.StateT $ \s -> f (LazyState.runStateT m s) instance (IndentationParsing i) => IndentationParsing (LazyState.StateT s i) where localTokenMode f = liftLazyStateT2 (localTokenMode f) localIndentation r = liftLazyStateT2 (localIndentation r) absoluteIndentation = liftLazyStateT2 absoluteIndentation ignoreAbsoluteIndentation = liftLazyStateT2 ignoreAbsoluteIndentation localAbsoluteIndentation = liftLazyStateT2 localAbsoluteIndentation {-# INLINE liftStrictStateT2 #-} liftStrictStateT2 :: (m (a, s) -> m (a, s)) -> StrictState.StateT s m a -> StrictState.StateT s m a liftStrictStateT2 f m = StrictState.StateT $ \s -> f (StrictState.runStateT m s) instance (IndentationParsing i) => IndentationParsing (StrictState.StateT s i) where localTokenMode f = liftStrictStateT2 (localTokenMode f) localIndentation r = liftStrictStateT2 (localIndentation r) absoluteIndentation = liftStrictStateT2 absoluteIndentation ignoreAbsoluteIndentation = liftStrictStateT2 ignoreAbsoluteIndentation localAbsoluteIndentation = liftStrictStateT2 localAbsoluteIndentation --------------- -- Data Type -- --------------- -- TODO: do we need a strict version of this? newtype IndentationParserT t m a = IndentationParserT { unIndentationParserT :: LazyState.StateT IndentationState m a } deriving (Functor, Applicative, Monad, MonadTrans, MonadPlus, Alternative) deriving instance (Parsing m, MonadPlus m) => Parsing (IndentationParserT t m) deriving instance (DeltaParsing m) => DeltaParsing (IndentationParserT Char m) deriving instance (MarkParsing Delta m) => MarkParsing Delta (IndentationParserT Char m) deriving instance (DeltaParsing m) => DeltaParsing (IndentationParserT Token m) deriving instance (MarkParsing Delta m) => MarkParsing Delta (IndentationParserT Token m) {-# INLINE runIndentationParserT #-} runIndentationParserT :: IndentationParserT t m a -> IndentationState -> m (a, IndentationState) runIndentationParserT (IndentationParserT m) = LazyState.runStateT m {-# INLINE evalIndentationParserT #-} evalIndentationParserT :: (Monad m) => IndentationParserT t m a -> IndentationState -> m a evalIndentationParserT (IndentationParserT m) = LazyState.evalStateT m {-# INLINE execIndentationParserT #-} execIndentationParserT :: (Monad m) => IndentationParserT t m a -> IndentationState -> m IndentationState execIndentationParserT (IndentationParserT m) = LazyState.execStateT m --------------------- -- Class Instances -- --------------------- -- Putting the check in CharParsing -- instance (DeltaParsing m) => CharParsing (IndentationParserT Char m) where satisfy f = checkIndentation (satisfy f) instance (DeltaParsing m) => TokenParsing (IndentationParserT Char m) where someSpace = IndentationParserT $ someSpace -- Ignore indentation of whitespace -- Putting the check in TokenParsing -- data Token instance (DeltaParsing m) => CharParsing (IndentationParserT Token m) where satisfy f = IndentationParserT $ satisfy f instance (DeltaParsing m) => TokenParsing (IndentationParserT Token m) where token p = checkIndentation (token (unIndentationParserT p)) -------- instance (LookAheadParsing m, MonadPlus m) => LookAheadParsing (IndentationParserT t m) where lookAhead m = IndentationParserT $ do s <- get x <- lookAhead (unIndentationParserT m) put s return x -------- instance (Monad m) => IndentationParsing (IndentationParserT t m) where {-# INLINE localTokenMode #-} localTokenMode = I.localTokenMode localState {-# INLINE localIndentation #-} localIndentation = I.localIndentation localStateUnlessAbsMode {-# INLINE absoluteIndentation #-} absoluteIndentation = I.absoluteIndentation localState {-# INLINE ignoreAbsoluteIndentation #-} ignoreAbsoluteIndentation = I.ignoreAbsoluteIndentation localState {-# INLINE localAbsoluteIndentation #-} localAbsoluteIndentation = I.localAbsoluteIndentation localState --------------------- -- Private Helpers -- --------------------- {-# INLINE localState #-} localState :: (Monad m) => LocalState (IndentationParserT t m a) localState pre post m = IndentationParserT $ do is <- get put (pre is) x <- unIndentationParserT m is' <- get put (post is is') return x {-# INLINE localStateUnlessAbsMode #-} localStateUnlessAbsMode :: (Monad m) => LocalState (IndentationParserT t m a) localStateUnlessAbsMode pre post m = IndentationParserT $ do a <- gets I.indentationStateAbsMode unIndentationParserT $ if a then m else localState pre post m {-# INLINE checkIndentation #-} checkIndentation :: (DeltaParsing m) => LazyState.StateT IndentationState m a -> IndentationParserT t m a checkIndentation m = IndentationParserT $ do is <- get p <- position let ok is' = do x <- m; put is'; return x err msg = fail msg I.updateIndentation is (fromIntegral $ column p + 1) ok err
lambdageek/indentation
indentation-trifecta/src/Text/Trifecta/Indentation.hs
bsd-3-clause
6,694
0
13
946
1,680
891
789
-1
-1
-- J.S. Bach - Choral prelude F-moll 'Ich ruf zu dir Herr Jesu Christ' import System.Cmd(system) import Temporal.Music.Western.P12 import Temporal.Music.Demo.GeneralMidi pedal = sustainT trill n a b = loop n $ mel [a, b] -- alto dynamics type Score12 = Score (Note ()) up :: Double -> [Score12] -> Score12 up x = withAccentRel [x, x + accDiap] . mel . map sn down :: Double -> [Score12] -> Score12 down x = withAccentRel [x + accDiap, x] . mel . map sn upDown :: Double -> [Score12] -> Score12 upDown x = withAccentRel [x, x + accDiap, x] . mel . map sn downUp :: Double -> [Score12] -> Score12 downUp x = withAccentRel [x, x-accDiap, x] . mel . map sn flat :: Double -> [Score12] -> Score12 flat x = accent x . mel . map sn accDiap = 0.5 -------------------------------------------------- -- solo -- Part I solo0 = qn $ high c solo1 = mel [ -- 1 bar qn af, qn bf, den af, sn g, den f, sn g, -- 2 bar withAccentRel [0, 0.4, 0] $ mel [mel $ map sn [af, bf, af, bf], dim 1.5 $ hn $ trill 6 (accent 0.2 $ tn $ high c) (tn bf), tn af, tn bf], high $ mel [accent 0.2 $ qn $ c, den c, sn df, -- 3 bar qn ef, tn df, str (1/4 - 3/32) $ wn c, sn $ low bf, qn $ low af, en $ low bf, en c] ] solo11 = high $ mel [ str (1/4 + 1/16) $ wn df, mel $ map tn [ef, f, ef, df], sn c, qn c, qn c] solo12 = high $ mel [ qn df, sn df, mel $ map tn [ef, f, ef, df],sn c, qn c, qn ef] soloI = mel [solo0, reprise solo1 solo11 solo12] -- Part II solo21 = high $ mel [ -- 1 bar qn f, en ef, tn df, tn c, sn df, low $ mel $ map en [high c, bf, af, bf], -- 2 bar qn c, qn c, qn $ low bf, qn $ low af, -- 3 bar low $ mel [hn g, hn f, -- 4 bar qn af, qn g, hn f] ] solo22 = mel [ -- 5 bar dhn ef, qn ef, -- 6 bar qn af, qn af, qn bf, qn bf, -- 7 bar high $ mel [dhn c, qn df], -- 8 bar high $ qn c, qn bf, qn af, den f, sn g, -- 9 bar qn af, qn g, qn f ] soloII = solo21 +:+ solo22 solo = pedal (1/64) $ soloI +:+ soloII --------------------------------------------------- -- alto -- Part I alto0 = high $ up 0 [low af, c, f, e] alto1 = mel [ -- 1 bar high $ down 0.5 [f, c, low af, low f], upDown 0 [g, bf, high df, high c], upDown 0 [f, af, high c, bf], downUp 0 [af, f, af, high c], -- 2 bar high $ downUp 0.2 [f, e, f, af], high $ down 0 [g, f, e, f], high $ downUp 0 [e, c, low g, low bf, low af, c, f, af], -- 3 bar high $ flat 0 [g, ef, af, g], high $ up 0 [af, ef, f, gf, f, df, f, af, g, df, c, gf] ] alto11 = high $ mel [ upDown 0 [f, low bf, df, f, bf, af, g, af, g, c, e, low bf], upDown 0 [low f, c, f, e] ] alto12 = high $ mel [ upDown 0 [f, low bf, df, f, bf, af, g, af], down 0 [g, low bf, low af, f, low g, df, low af, c] ] altoI = mel [alto0, reprise alto1 alto11 alto12] -- Part II alto21 = high $ mel [ -- 1 bar upDown 0 [ low af, c, low bf, df, low bf, df, af, g, af, ef, df, g, c, f, af, g], -- 2 bar down (-accDiap) [ af, ef, low af, gf, f, low af, low g, df, c, low af, c, ef, g, c, low bf, g, -- 3 bar df, f, g, f], up (-accDiap) [ e, low bf, df, c, low af, c, f, e, f, c, low af, low f], -- 4 bar flat 0 [ low bf, f, g, f, low bf, ef, f, ef, c, ef, f, ef, d, low g, low b, d ] ] alto22 = high $ mel [ -- 5 bar down (-accDiap) $ [ low g, c, ef, df, low g, low bf, df, c] ++ map low [ef, af, high c, bf, high df, bf, c, high df, -- 6 bar f, af, high df, high c, f, af, high c, bf, f, af, bf, af, g, bf, high df, high c], -- 7 bar up (-accDiap) [ low af, c, ef, af, ef, bf, high c, bf, a, ef, gf, low a, low bf, g, low af, f ], -- 8 bar down (-accDiap) [ low af, ef, d, ef, low f, df, ef, df, low ef, c, df, c, low bf, f, g, f, -- 9 bar d, f, g, f, e, df, low bf, low g, low a, c] ] alto23 = en $ high f altoII = mel [alto21, alto22, alto23] alto = pedal (1/128) $ lower 3 $ mel [altoI, altoII] ---------------------------------------------------------- -- bass -- Part I bass0 = lower 1 $ mel [en f, en f] bass1 = (mel $ map en [ -- 1 bar f, f, f, e, f, f, f, ef, -- 2 bar df, df, df, df, c, c, f, f]) +:+ -- 3 bar (high $ mel $ map en [c, c, c, c, c, c, low bf, low a]) bass11 = mel $ map en [bf, af, g, f, e, c, low f, low f] bass12 = mel $ map en [bf, af, g, f, e, f, c, c] bassI = mel [bass0, reprise bass1 bass11 bass12] -- Part II bass21 = mel $ map en [ -- 1 bar df, df, ef, ef, af, ef, f, df, -- 2 bar low f, low f, f, f, d, e, f, df, -- 3 bar low bf, low g, c, c, df, df, df , df, -- 4 bar d, d, d, d, low a, low a, low b, low b ] bass22 = low $ mel $ map en [ -- 5 bar high c, high c, bf, bf, af, af, g, g, -- 6 bar f, f, ef, ef, d, d, ef, ef, -- 7 bar af, af, gf, gf, f, f, bf, bf, -- 8 bar bf, af, af, g, g, f, high df, high df, -- 9 bar b, b, high c, high c ] bass23 = qn $ low f bassII = mel [bass21, bass22, bass23] bass = lower 3 $ mel [bassI, bassII] sco = del (-4) $ bpm (lento $ -0.2) $ har [ solo, mp' $ higher 2 alto, accent 0.2 $ p' $ higher 2 $ bass, rest 0 ] file = "out.csd" flags = "-d" out = acousticGrandPiano sco main = do exportMidi "choral.mid" $ out system "timidity choral.mid"
spell-music/temporal-music-notation-demo
examples/choral.hs
bsd-3-clause
5,742
2
15
2,049
3,011
1,680
1,331
128
1
{-# OPTIONS_HADDOCK hide #-} -- Implementation of the PLAIN Simple Authentication and Security Layer (SASL) -- Mechanism, http://tools.ietf.org/html/rfc4616. {-# LANGUAGE OverloadedStrings #-} module Network.Xmpp.Sasl.Mechanisms.Plain ( plain ) where import Control.Monad.Error import Control.Monad.State.Strict import qualified Data.ByteString as BS import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Network.Xmpp.Sasl.Common import Network.Xmpp.Sasl.Types import Network.Xmpp.Types -- TODO: stringprep xmppPlain :: Text.Text -- ^ Password -> Maybe Text.Text -- ^ Authorization identity (authzid) -> Text.Text -- ^ Authentication identity (authcid) -> ErrorT AuthFailure (StateT StreamState IO) () xmppPlain authcid' authzid' password = do (ac, az, pw) <- prepCredentials authcid' authzid' password _ <- saslInit "PLAIN" ( Just $ plainMessage ac az pw) _ <- pullSuccess return () where -- Converts an optional authorization identity, an authentication identity, -- and a password to a \NUL-separated PLAIN message. plainMessage :: Text.Text -- Authorization identity (authzid) -> Maybe Text.Text -- Authentication identity (authcid) -> Text.Text -- Password -> BS.ByteString -- The PLAIN message plainMessage authcid _authzid passwd = BS.concat $ [ authzid'' , "\NUL" , Text.encodeUtf8 $ authcid , "\NUL" , Text.encodeUtf8 $ passwd ] where authzid'' = maybe "" Text.encodeUtf8 authzid' plain :: Username -- ^ authentication ID (username) -> Maybe AuthZID -- ^ authorization ID -> Password -- ^ password -> SaslHandler plain authcid authzid passwd = ( "PLAIN" , do r <- runErrorT $ xmppPlain authcid authzid passwd case r of Left (AuthStreamFailure e) -> return $ Left e Left e -> return $ Right $ Just e Right () -> return $ Right Nothing )
Philonous/pontarius-xmpp
source/Network/Xmpp/Sasl/Mechanisms/Plain.hs
bsd-3-clause
2,332
0
13
808
422
232
190
44
3
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} ----------------------------------------------------------------------------- -- | -- Module : -- Copyright : -- License : -- -- Maintainer : -- Stability : experimental -- -- An operational run layer that either passes commands on to hadoop -- or runs things locally. ---------------------------------------------------------------------------- module Hadron.Run ( RunContext (..) , L.LocalRunSettings (..) , H.HadoopEnv (..) , H.clouderaDemo , H.amazonEMR , H.PartitionStrategy (..) , H.numSegs , H.eqSegs , H.Comparator (..) , H.HadoopRunOpts (..) , H.mrSettings , H.Codec , H.gzipCodec , H.snappyCodec , launchMapReduce , hdfsTempFilePath , hdfsFileExists , hdfsDeletePath , hdfsLs , hdfsPut , hdfsMkdir , hdfsCat , hdfsGet , hdfsLocalStream , randomRemoteFile , randomLocalFile , L.LocalFile (..) , L.randomFileName , withLocalFile , withRandomLocalFile , module Hadron.Run.FanOut , hdfsFanOut ) where ------------------------------------------------------------------------------- import Control.Error import Control.Lens import Control.Monad import Control.Monad.Morph import Control.Monad.Trans import Control.Monad.Trans.Resource import qualified Data.ByteString.Char8 as B import Data.Conduit import Data.Conduit.Binary (sourceFile) import System.Directory import System.FilePath.Posix ------------------------------------------------------------------------------- import Hadron.Run.FanOut import qualified Hadron.Run.Hadoop as H import Hadron.Run.Local (LocalFile (..)) import qualified Hadron.Run.Local as L import Hadron.Utils ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- | Dispatch on the type of run data RunContext = LocalRun L.LocalRunSettings -- ^ Development mode: Emulate a hadoop run locally on this -- machine | HadoopRun H.HadoopEnv L.LocalRunSettings -- ^ Production mode: Actually run on hadoop. However, some -- utilites use local facilities so we still force you to have a -- local policy. makePrisms ''RunContext lset :: RunContext -> L.LocalRunSettings lset (LocalRun s) = s lset (HadoopRun _ s) = s ------------------------------------------------------------------------------- launchMapReduce :: MonadIO m => RunContext -> String -> String -> H.HadoopRunOpts -> ExceptT String m () launchMapReduce (LocalRun env) mrKey token opts = ExceptT . L.runLocal env . runExceptT $ (L.localMapReduce env mrKey token opts) launchMapReduce (HadoopRun env _) mrKey token opts = H.hadoopMapReduce env mrKey token opts ------------------------------------------------------------------------------- hdfsFileExists :: RunContext -> FilePath -> IO Bool hdfsFileExists (LocalRun env) fp = L.runLocal env (L.hdfsFileExists (LocalFile fp)) hdfsFileExists (HadoopRun env _) fp = H.hdfsFileExists env fp ------------------------------------------------------------------------------- hdfsDeletePath :: RunContext -> FilePath -> IO () hdfsDeletePath rc fp = case rc of LocalRun lrs -> L.runLocal lrs (L.hdfsDeletePath (LocalFile fp)) HadoopRun he _ -> H.hdfsDeletePath he fp ------------------------------------------------------------------------------- hdfsLs :: RunContext -> FilePath -> IO [File] hdfsLs rc fp = case rc of LocalRun lrs -> L.runLocal lrs (L.hdfsLs (LocalFile fp)) HadoopRun he _ -> H.hdfsLs he fp ------------------------------------------------------------------------------- hdfsPut :: RunContext -> L.LocalFile -> FilePath -> IO () hdfsPut rc f1 f2 = case rc of LocalRun lrs -> L.runLocal lrs (L.hdfsPut f1 (LocalFile f2)) HadoopRun e _ -> withLocalFile rc f1 $ \ lf -> H.hdfsPut e lf f2 ------------------------------------------------------------------------------- hdfsFanOut :: RunContext -> FilePath -- ^ A temporary folder where in-progress files can be placed -> IO FanOut hdfsFanOut rc tmp = case rc of LocalRun lcs -> L.runLocal lcs $ L.hdfsFanOut tmp HadoopRun e _ -> H.hdfsFanOut e tmp ------------------------------------------------------------------------------- hdfsMkdir :: RunContext -> FilePath -> IO () hdfsMkdir rc fp = case rc of LocalRun lcs -> L.runLocal lcs (L.hdfsMkdir (LocalFile fp)) HadoopRun he _ -> H.hdfsMkdir he fp ------------------------------------------------------------------------------- hdfsCat :: RunContext -> FilePath -> Producer (ResourceT IO) B.ByteString hdfsCat rc fp = case rc of LocalRun lcs -> hoist (hoist (L.runLocal lcs)) $ L.hdfsCat (LocalFile fp) HadoopRun{} -> hdfsLocalStream rc fp ------------------------------------------------------------------------------- -- | Copy a file from HDFS into local. hdfsGet :: RunContext -> FilePath -> IO LocalFile hdfsGet rc fp = do local <- L.randomFileName case rc of LocalRun _ -> return (LocalFile fp) HadoopRun h _ -> do withLocalFile rc local $ \ lf -> H.hdfsGet h fp lf return local ------------------------------------------------------------------------------- -- | Copy a file down to local FS, then stream its content. hdfsLocalStream :: RunContext -> FilePath -> Producer (ResourceT IO) B.ByteString hdfsLocalStream env fp = case env of LocalRun{} -> hdfsCat env fp HadoopRun _ _ -> do random <- liftIO $ hdfsGet env fp withLocalFile env random $ \ local -> do register $ removeFile local sourceFile local -- ------------------------------------------------------------------------------- -- -- | Stream contents of a folder one by one from HDFS. -- hdfsLocalStreamMulti -- :: (MonadIO m, MonadThrow m, MonadBase base m, PrimMonad base) -- => HadoopEnv -- -> FilePath -- -- ^ Location / glob pattern -- -> (FilePath -> Bool) -- -- ^ File filter based on name -- -> Source m ByteString -- hdfsLocalStreamMulti hs loc chk = do -- fs <- liftIO $ hdfsLs hs loc <&> filter chk -- lfs <- liftIO $ mapConcurrently (hdfsGet hs) fs -- forM_ (zip lfs fs) $ \ (local, fp) -> do -- h <- liftIO $ catching _IOException -- (openFile local ReadMode) -- (\e -> error $ "hdfsLocalStream failed with open file: " <> show e) -- let getFile = sourceHandle h -- if isSuffixOf "gz" fp -- then getFile =$= ungzip -- else getFile -- liftIO $ do -- hClose h -- removeFile local randomLocalFile :: MonadIO m => m LocalFile randomLocalFile = L.randomFileName randomRemoteFile :: RunContext -> IO FilePath randomRemoteFile env = case env of LocalRun{} -> _unLocalFile `liftM` L.randomFileName HadoopRun e _ -> H.randomFilename e ------------------------------------------------------------------------------- -- | Given a filename, produce an HDFS path for me in our temporary folder. hdfsTempFilePath :: MonadIO m => RunContext -> FilePath -> m FilePath hdfsTempFilePath env fp = case env of LocalRun{} -> return fp HadoopRun{} -> return $ H.tmpRoot </> fp ------------------------------------------------------------------------------- -- | Helper to work with relative paths using Haskell functions like -- 'readFile' and 'writeFile'. withLocalFile :: MonadIO m => RunContext -> LocalFile -> (FilePath -> m b) -> m b withLocalFile rs fp f = L.withLocalFile (lset rs) fp f ------------------------------------------------------------------------------- withRandomLocalFile :: MonadIO m => RunContext -> (FilePath -> m b) -> m LocalFile withRandomLocalFile rc f = do fp <- randomLocalFile withLocalFile rc fp f return fp
dmjio/hadron
src/Hadron/Run.hs
bsd-3-clause
8,278
0
15
1,783
1,635
870
765
143
2
module ElmFormat.Operation (Operation, OperationF(..), deprecatedIO) where import Prelude hiding (readFile, writeFile) import Control.Monad.Free import ElmFormat.FileStore import Messages.Formatter.Format class (FileStore f, InfoFormatter f) => Operation f where deprecatedIO :: IO a -> f a data OperationF a = InFileStore (FileStoreF a) | InInfoFormatter (InfoFormatterF a) | DeprecatedIO (IO a) instance Operation OperationF where deprecatedIO = DeprecatedIO instance FileStore OperationF where readFile path = InFileStore $ readFile path stat path = InFileStore $ stat path listDirectory path = InFileStore $ listDirectory path instance InfoFormatter OperationF where onInfo msg = InInfoFormatter $ onInfo msg instance Functor OperationF where fmap f (InFileStore op) = InFileStore (fmap f op) fmap f (InInfoFormatter op) = InInfoFormatter (fmap f op) fmap f (DeprecatedIO io) = DeprecatedIO (fmap f io) instance Operation f => Operation (Free f) where deprecatedIO io = liftF (deprecatedIO io)
nukisman/elm-format-short
src/ElmFormat/Operation.hs
bsd-3-clause
1,065
0
8
203
343
177
166
25
0
module Sharc.Instruments.ClarinetEflat (clarinetEflat) where import Sharc.Types clarinetEflat :: Instr clarinetEflat = Instr "Eb_clarinet" "Clarinet (E-flat)" (Legend "McGill" "2" "11") (Range (InstrRange (HarmonicFreq 1 (Pitch 195.99 43 "g3")) (Pitch 195.99 43 "g3") (Amplitude 9418.51 (HarmonicFreq 18 (Pitch 523.251 60 "c5")) 0.18)) (InstrRange (HarmonicFreq 51 (Pitch 9995.89 43 "g3")) (Pitch 1174.66 74 "d6") (Amplitude 261.62 (HarmonicFreq 1 (Pitch 261.626 48 "c4")) 5886.0))) [note0 ,note1 ,note2 ,note3 ,note4 ,note5 ,note6 ,note7 ,note8 ,note9 ,note10 ,note11 ,note12 ,note13 ,note14 ,note15 ,note16 ,note17 ,note18 ,note19 ,note20 ,note21 ,note22 ,note23 ,note24 ,note25 ,note26 ,note27 ,note28 ,note29 ,note30 ,note31] note0 :: Note note0 = Note (Pitch 195.998 43 "g3") 1 (Range (NoteRange (NoteRangeAmplitude 8231.91 42 0.35) (NoteRangeHarmonicFreq 1 195.99)) (NoteRange (NoteRangeAmplitude 195.99 1 3636.0) (NoteRangeHarmonicFreq 51 9995.89))) [Harmonic 1 (-2.023) 3636.0 ,Harmonic 2 (-2.523) 197.27 ,Harmonic 3 (-0.112) 258.32 ,Harmonic 4 2.595 112.14 ,Harmonic 5 (-1.08) 3037.32 ,Harmonic 6 (-0.993) 1005.01 ,Harmonic 7 3.06 1022.67 ,Harmonic 8 1.235 112.48 ,Harmonic 9 (-8.4e-2) 295.64 ,Harmonic 10 1.929 269.28 ,Harmonic 11 2.111 151.72 ,Harmonic 12 0.349 189.27 ,Harmonic 13 0.641 59.87 ,Harmonic 14 (-3.125) 6.97 ,Harmonic 15 (-2.301) 159.33 ,Harmonic 16 (-1.969) 63.82 ,Harmonic 17 2.322 86.06 ,Harmonic 18 (-1.94) 63.1 ,Harmonic 19 (-1.604) 11.65 ,Harmonic 20 (-2.292) 47.94 ,Harmonic 21 (-1.795) 29.7 ,Harmonic 22 (-2.7) 17.88 ,Harmonic 23 2.829 9.14 ,Harmonic 24 (-0.247) 3.48 ,Harmonic 25 (-0.184) 13.12 ,Harmonic 26 (-0.887) 16.03 ,Harmonic 27 (-1.886) 12.2 ,Harmonic 28 3.141 7.1 ,Harmonic 29 2.732 11.48 ,Harmonic 30 0.521 9.28 ,Harmonic 31 (-0.249) 10.61 ,Harmonic 32 2.9e-2 1.01 ,Harmonic 33 (-2.577) 5.4 ,Harmonic 34 (-2.78) 5.25 ,Harmonic 35 (-0.443) 0.6 ,Harmonic 36 0.818 5.22 ,Harmonic 37 (-0.653) 1.85 ,Harmonic 38 (-1.414) 2.84 ,Harmonic 39 (-2.218) 2.67 ,Harmonic 40 (-0.376) 0.35 ,Harmonic 41 (-0.785) 1.13 ,Harmonic 42 (-2.278) 0.35 ,Harmonic 43 0.74 1.33 ,Harmonic 44 (-1.85) 0.56 ,Harmonic 45 (-1.207) 0.92 ,Harmonic 46 (-0.492) 0.59 ,Harmonic 47 (-0.305) 0.85 ,Harmonic 48 2.999 1.55 ,Harmonic 49 0.729 0.96 ,Harmonic 50 (-0.668) 1.22 ,Harmonic 51 1.411 0.43] note1 :: Note note1 = Note (Pitch 207.652 44 "g#3") 2 (Range (NoteRange (NoteRangeAmplitude 8513.73 41 0.91) (NoteRangeHarmonicFreq 1 207.65)) (NoteRange (NoteRangeAmplitude 1038.26 5 5745.0) (NoteRangeHarmonicFreq 48 9967.29))) [Harmonic 1 1.9e-2 4383.22 ,Harmonic 2 1.469 135.74 ,Harmonic 3 (-2.018) 1473.53 ,Harmonic 4 (-1.528) 195.09 ,Harmonic 5 3.123 5745.0 ,Harmonic 6 (-1.347) 571.6 ,Harmonic 7 (-1.443) 3593.44 ,Harmonic 8 0.823 232.09 ,Harmonic 9 (-0.847) 1205.13 ,Harmonic 10 1.414 560.27 ,Harmonic 11 0.896 1005.4 ,Harmonic 12 3.017 558.5 ,Harmonic 13 2.499 431.71 ,Harmonic 14 (-1.047) 305.59 ,Harmonic 15 (-2.384) 85.8 ,Harmonic 16 1.394 158.48 ,Harmonic 17 (-0.921) 99.9 ,Harmonic 18 1.273 109.14 ,Harmonic 19 (-2.75) 22.8 ,Harmonic 20 2.97 27.8 ,Harmonic 21 (-0.225) 27.37 ,Harmonic 22 (-4.3e-2) 40.64 ,Harmonic 23 2.267 26.42 ,Harmonic 24 2.174 41.45 ,Harmonic 25 (-1.952) 13.05 ,Harmonic 26 2.552 17.37 ,Harmonic 27 (-2.293) 28.48 ,Harmonic 28 (-2.821) 2.75 ,Harmonic 29 1.186 10.77 ,Harmonic 30 (-0.757) 12.87 ,Harmonic 31 2.459 23.24 ,Harmonic 32 (-1.654) 5.35 ,Harmonic 33 2.649 20.73 ,Harmonic 34 (-1.525) 17.75 ,Harmonic 35 (-1.414) 5.15 ,Harmonic 36 1.489 8.59 ,Harmonic 37 2.393 2.6 ,Harmonic 38 1.78 3.15 ,Harmonic 39 3.12 2.89 ,Harmonic 40 (-2.838) 2.38 ,Harmonic 41 (-7.5e-2) 0.91 ,Harmonic 42 (-1.206) 1.83 ,Harmonic 43 (-1.042) 1.95 ,Harmonic 44 (-1.128) 3.03 ,Harmonic 45 (-1.236) 4.28 ,Harmonic 46 (-1.409) 2.44 ,Harmonic 47 (-1.125) 3.03 ,Harmonic 48 (-1.932) 1.42] note2 :: Note note2 = Note (Pitch 220.0 45 "a3") 3 (Range (NoteRange (NoteRangeAmplitude 7260.0 33 0.77) (NoteRangeHarmonicFreq 1 220.0)) (NoteRange (NoteRangeAmplitude 220.0 1 4081.0) (NoteRangeHarmonicFreq 45 9900.0))) [Harmonic 1 1.395 4081.0 ,Harmonic 2 (-2.428) 44.92 ,Harmonic 3 0.465 1128.07 ,Harmonic 4 2.655 48.84 ,Harmonic 5 2.752 962.08 ,Harmonic 6 0.92 134.47 ,Harmonic 7 1.002 1285.24 ,Harmonic 8 (-2.917) 364.12 ,Harmonic 9 (-2.866) 1167.06 ,Harmonic 10 1.246 357.35 ,Harmonic 11 1.041 413.63 ,Harmonic 12 (-2.067) 185.43 ,Harmonic 13 (-1.205) 162.63 ,Harmonic 14 1.54 153.89 ,Harmonic 15 1.035 169.61 ,Harmonic 16 (-1.251) 430.68 ,Harmonic 17 (-2.398) 97.92 ,Harmonic 18 (-2.778) 174.84 ,Harmonic 19 0.223 38.87 ,Harmonic 20 0.598 55.11 ,Harmonic 21 2.795 29.93 ,Harmonic 22 (-1.657) 78.69 ,Harmonic 23 0.75 35.76 ,Harmonic 24 2.554 49.38 ,Harmonic 25 2.6e-2 19.45 ,Harmonic 26 2.851 3.62 ,Harmonic 27 (-2.739) 12.42 ,Harmonic 28 2.69 14.18 ,Harmonic 29 (-8.0e-3) 49.42 ,Harmonic 30 2.21 2.75 ,Harmonic 31 3.066 4.1 ,Harmonic 32 (-1.243) 7.94 ,Harmonic 33 1.608 0.77 ,Harmonic 34 1.233 2.31 ,Harmonic 35 1.691 2.37 ,Harmonic 36 1.081 4.36 ,Harmonic 37 (-2.359) 1.1 ,Harmonic 38 (-0.305) 3.24 ,Harmonic 39 1.867 3.22 ,Harmonic 40 2.715 5.03 ,Harmonic 41 (-1.458) 5.7 ,Harmonic 42 (-0.706) 2.12 ,Harmonic 43 0.971 3.75 ,Harmonic 44 2.07 2.04 ,Harmonic 45 (-2.672) 4.0] note3 :: Note note3 = Note (Pitch 233.082 46 "a#3") 4 (Range (NoteRange (NoteRangeAmplitude 7458.62 32 1.16) (NoteRangeHarmonicFreq 1 233.08)) (NoteRange (NoteRangeAmplitude 233.08 1 4197.0) (NoteRangeHarmonicFreq 42 9789.44))) [Harmonic 1 (-0.366) 4197.0 ,Harmonic 2 0.417 40.0 ,Harmonic 3 2.735 3144.3 ,Harmonic 4 (-2.243) 54.77 ,Harmonic 5 1.191 361.18 ,Harmonic 6 (-2.559) 232.01 ,Harmonic 7 1.064 1463.45 ,Harmonic 8 (-3.101) 583.99 ,Harmonic 9 1.113 654.95 ,Harmonic 10 3.116 158.0 ,Harmonic 11 1.319 481.48 ,Harmonic 12 (-2.27) 158.93 ,Harmonic 13 2.047 122.66 ,Harmonic 14 (-1.413) 123.39 ,Harmonic 15 2.42 118.99 ,Harmonic 16 (-2.048) 203.14 ,Harmonic 17 (-1.365) 17.28 ,Harmonic 18 (-0.801) 5.59 ,Harmonic 19 (-0.19) 47.1 ,Harmonic 20 4.9e-2 53.98 ,Harmonic 21 1.198 17.75 ,Harmonic 22 1.842 16.38 ,Harmonic 23 (-2.469) 5.51 ,Harmonic 24 2.905 18.92 ,Harmonic 25 2.81 14.87 ,Harmonic 26 2.13 42.84 ,Harmonic 27 (-2.173) 37.99 ,Harmonic 28 3.011 34.99 ,Harmonic 29 (-2.519) 25.27 ,Harmonic 30 1.334 1.97 ,Harmonic 31 3.107 10.92 ,Harmonic 32 (-2.931) 1.16 ,Harmonic 33 (-2.649) 7.62 ,Harmonic 34 (-1.133) 3.55 ,Harmonic 35 (-0.38) 2.79 ,Harmonic 36 2.855 2.39 ,Harmonic 37 (-0.571) 1.72 ,Harmonic 38 (-2.62) 4.71 ,Harmonic 39 2.997 4.63 ,Harmonic 40 3.064 5.94 ,Harmonic 41 3.003 2.28 ,Harmonic 42 2.37 3.71] note4 :: Note note4 = Note (Pitch 246.942 47 "b3") 5 (Range (NoteRange (NoteRangeAmplitude 9383.79 38 1.67) (NoteRangeHarmonicFreq 1 246.94)) (NoteRange (NoteRangeAmplitude 246.94 1 5301.0) (NoteRangeHarmonicFreq 40 9877.68))) [Harmonic 1 1.469 5301.0 ,Harmonic 2 (-2.383) 40.76 ,Harmonic 3 1.15 1630.43 ,Harmonic 4 (-0.521) 23.65 ,Harmonic 5 2.497 288.45 ,Harmonic 6 1.386 82.45 ,Harmonic 7 2.609 1204.47 ,Harmonic 8 (-0.494) 602.11 ,Harmonic 9 (-0.542) 287.49 ,Harmonic 10 2.859 144.39 ,Harmonic 11 (-2.795) 372.51 ,Harmonic 12 1.545 150.05 ,Harmonic 13 2.375 203.58 ,Harmonic 14 0.173 315.71 ,Harmonic 15 0.234 38.34 ,Harmonic 16 1.55 126.51 ,Harmonic 17 3.116 51.03 ,Harmonic 18 1.118 140.74 ,Harmonic 19 (-2.917) 47.35 ,Harmonic 20 (-9.5e-2) 51.29 ,Harmonic 21 1.451 20.2 ,Harmonic 22 (-1.886) 19.1 ,Harmonic 23 (-0.255) 19.12 ,Harmonic 24 2.198 43.38 ,Harmonic 25 (-1.213) 2.81 ,Harmonic 26 5.5e-2 31.66 ,Harmonic 27 (-2.221) 21.14 ,Harmonic 28 (-2.309) 24.68 ,Harmonic 29 0.148 15.39 ,Harmonic 30 1.913 9.89 ,Harmonic 31 (-1.14) 13.62 ,Harmonic 32 0.697 4.18 ,Harmonic 33 1.81 4.49 ,Harmonic 34 (-1.053) 3.86 ,Harmonic 35 1.529 3.45 ,Harmonic 36 1.775 2.58 ,Harmonic 37 (-2.356) 4.96 ,Harmonic 38 (-1.921) 1.67 ,Harmonic 39 0.72 4.28 ,Harmonic 40 1.36 1.72] note5 :: Note note5 = Note (Pitch 261.626 48 "c4") 6 (Range (NoteRange (NoteRangeAmplitude 9156.91 35 2.71) (NoteRangeHarmonicFreq 1 261.62)) (NoteRange (NoteRangeAmplitude 261.62 1 5886.0) (NoteRangeHarmonicFreq 38 9941.78))) [Harmonic 1 2.834 5886.0 ,Harmonic 2 2.782 66.3 ,Harmonic 3 0.798 2399.7 ,Harmonic 4 1.153 174.07 ,Harmonic 5 (-0.944) 1843.27 ,Harmonic 6 (-2.087) 857.81 ,Harmonic 7 (-0.791) 2396.06 ,Harmonic 8 (-2.465) 241.87 ,Harmonic 9 (-0.721) 1064.87 ,Harmonic 10 (-1.846) 219.92 ,Harmonic 11 0.804 205.56 ,Harmonic 12 (-1.719) 121.65 ,Harmonic 13 0.401 134.77 ,Harmonic 14 0.214 202.92 ,Harmonic 15 (-1.551) 25.46 ,Harmonic 16 (-0.335) 26.1 ,Harmonic 17 (-1.05) 49.75 ,Harmonic 18 2.421 72.63 ,Harmonic 19 0.557 32.65 ,Harmonic 20 (-2.197) 8.36 ,Harmonic 21 1.045 16.63 ,Harmonic 22 (-2.127) 66.88 ,Harmonic 23 2.693 11.87 ,Harmonic 24 (-0.745) 20.15 ,Harmonic 25 2.913 26.27 ,Harmonic 26 (-0.69) 23.38 ,Harmonic 27 (-2.943) 51.23 ,Harmonic 28 0.884 17.15 ,Harmonic 29 (-2.823) 25.54 ,Harmonic 30 1.924 12.21 ,Harmonic 31 (-1.059) 3.83 ,Harmonic 32 2.004 5.24 ,Harmonic 33 (-1.366) 5.77 ,Harmonic 34 1.751 3.67 ,Harmonic 35 (-0.156) 2.71 ,Harmonic 36 2.005 4.18 ,Harmonic 37 (-1.302) 3.14 ,Harmonic 38 2.055 2.92] note6 :: Note note6 = Note (Pitch 277.183 49 "c#4") 7 (Range (NoteRange (NoteRangeAmplitude 9424.22 34 0.51) (NoteRangeHarmonicFreq 1 277.18)) (NoteRange (NoteRangeAmplitude 277.18 1 4980.0) (NoteRangeHarmonicFreq 36 9978.58))) [Harmonic 1 (-1.948) 4980.0 ,Harmonic 2 (-0.486) 26.48 ,Harmonic 3 (-1.453) 2486.44 ,Harmonic 4 (-0.562) 114.56 ,Harmonic 5 (-1.146) 1140.18 ,Harmonic 6 (-1.28) 251.61 ,Harmonic 7 1.55 798.8 ,Harmonic 8 0.683 184.81 ,Harmonic 9 (-2.691) 506.57 ,Harmonic 10 (-2.662) 5.56 ,Harmonic 11 (-4.9e-2) 243.18 ,Harmonic 12 1.904 201.33 ,Harmonic 13 (-0.749) 148.63 ,Harmonic 14 0.865 127.69 ,Harmonic 15 (-0.759) 76.04 ,Harmonic 16 2.0e-2 81.03 ,Harmonic 17 (-1.245) 65.71 ,Harmonic 18 (-1.111) 122.3 ,Harmonic 19 (-1.864) 21.98 ,Harmonic 20 1.274 32.9 ,Harmonic 21 (-0.372) 61.53 ,Harmonic 22 (-1.61) 55.96 ,Harmonic 23 2.702 8.16 ,Harmonic 24 1.357 37.35 ,Harmonic 25 0.492 18.92 ,Harmonic 26 (-1.647) 25.48 ,Harmonic 27 (-2.153) 15.64 ,Harmonic 28 1.233 8.07 ,Harmonic 29 (-2.2e-2) 10.75 ,Harmonic 30 (-1.686) 6.01 ,Harmonic 31 2.079 2.26 ,Harmonic 32 (-0.235) 2.83 ,Harmonic 33 (-0.591) 4.48 ,Harmonic 34 1.9e-2 0.51 ,Harmonic 35 3.119 3.43 ,Harmonic 36 (-5.3e-2) 2.77] note7 :: Note note7 = Note (Pitch 293.665 50 "d4") 8 (Range (NoteRange (NoteRangeAmplitude 8516.28 29 1.28) (NoteRangeHarmonicFreq 1 293.66)) (NoteRange (NoteRangeAmplitude 293.66 1 4676.0) (NoteRangeHarmonicFreq 34 9984.61))) [Harmonic 1 (-2.114) 4676.0 ,Harmonic 2 (-0.456) 41.94 ,Harmonic 3 (-1.049) 1771.6 ,Harmonic 4 (-0.322) 115.32 ,Harmonic 5 (-1.897) 810.77 ,Harmonic 6 (-1.976) 327.24 ,Harmonic 7 (-1.186) 1122.27 ,Harmonic 8 (-1.315) 292.99 ,Harmonic 9 (-5.0e-2) 112.73 ,Harmonic 10 0.288 142.13 ,Harmonic 11 (-1.725) 406.84 ,Harmonic 12 (-1.129) 304.11 ,Harmonic 13 (-2.656) 35.87 ,Harmonic 14 (-0.636) 105.75 ,Harmonic 15 (-1.265) 41.73 ,Harmonic 16 3.116 91.53 ,Harmonic 17 1.55 24.04 ,Harmonic 18 (-2.26) 12.62 ,Harmonic 19 3.101 5.69 ,Harmonic 20 0.791 19.31 ,Harmonic 21 2.9 4.35 ,Harmonic 22 0.18 21.7 ,Harmonic 23 (-0.205) 12.33 ,Harmonic 24 2.232 4.96 ,Harmonic 25 1.109 22.86 ,Harmonic 26 0.598 2.59 ,Harmonic 27 (-3.009) 3.99 ,Harmonic 28 2.098 3.77 ,Harmonic 29 0.151 1.28 ,Harmonic 30 0.93 1.92 ,Harmonic 31 0.765 2.56 ,Harmonic 32 (-1.085) 3.84 ,Harmonic 33 1.943 1.38 ,Harmonic 34 0.413 3.98] note8 :: Note note8 = Note (Pitch 311.127 51 "d#4") 9 (Range (NoteRange (NoteRangeAmplitude 9956.06 32 2.99) (NoteRangeHarmonicFreq 1 311.12)) (NoteRange (NoteRangeAmplitude 311.12 1 4460.0) (NoteRangeHarmonicFreq 32 9956.06))) [Harmonic 1 2.427 4460.0 ,Harmonic 2 2.784 141.09 ,Harmonic 3 (-2.7e-2) 4090.4 ,Harmonic 4 (-1.264) 78.98 ,Harmonic 5 1.36 1770.33 ,Harmonic 6 (-2.571) 798.64 ,Harmonic 7 (-1.948) 1525.01 ,Harmonic 8 1.015 164.68 ,Harmonic 9 1.745 141.89 ,Harmonic 10 0.578 277.92 ,Harmonic 11 1.349 485.17 ,Harmonic 12 0.516 308.01 ,Harmonic 13 (-2.365) 7.35 ,Harmonic 14 (-3.064) 105.6 ,Harmonic 15 1.569 55.09 ,Harmonic 16 (-1.931) 105.37 ,Harmonic 17 (-2.31) 10.39 ,Harmonic 18 2.484 56.57 ,Harmonic 19 4.0e-2 23.47 ,Harmonic 20 1.831 52.51 ,Harmonic 21 (-0.725) 77.94 ,Harmonic 22 (-0.322) 55.79 ,Harmonic 23 2.941 80.99 ,Harmonic 24 (-1.614) 10.64 ,Harmonic 25 2.08 38.52 ,Harmonic 26 (-1.537) 18.52 ,Harmonic 27 0.7 3.93 ,Harmonic 28 (-1.655) 4.66 ,Harmonic 29 1.975 4.05 ,Harmonic 30 (-1.797) 16.1 ,Harmonic 31 0.142 4.6 ,Harmonic 32 (-2.114) 2.99] note9 :: Note note9 = Note (Pitch 329.628 52 "e4") 10 (Range (NoteRange (NoteRangeAmplitude 9559.21 29 0.89) (NoteRangeHarmonicFreq 1 329.62)) (NoteRange (NoteRangeAmplitude 329.62 1 5292.0) (NoteRangeHarmonicFreq 30 9888.84))) [Harmonic 1 (-1.938) 5292.0 ,Harmonic 2 (-0.796) 101.52 ,Harmonic 3 (-0.534) 3009.7 ,Harmonic 4 0.676 139.9 ,Harmonic 5 (-2.509) 702.77 ,Harmonic 6 1.555 331.63 ,Harmonic 7 (-2.831) 766.68 ,Harmonic 8 1.743 174.19 ,Harmonic 9 (-1.028) 505.89 ,Harmonic 10 (-0.298) 238.86 ,Harmonic 11 2.806 77.95 ,Harmonic 12 2.705 30.73 ,Harmonic 13 2.434 40.8 ,Harmonic 14 3.028 152.3 ,Harmonic 15 1.801 62.84 ,Harmonic 16 1.795 25.29 ,Harmonic 17 (-2.619) 8.55 ,Harmonic 18 1.008 21.05 ,Harmonic 19 2.012 2.01 ,Harmonic 20 (-1.105) 33.78 ,Harmonic 21 (-2.502) 8.44 ,Harmonic 22 (-0.725) 16.31 ,Harmonic 23 0.57 6.46 ,Harmonic 24 (-8.5e-2) 5.23 ,Harmonic 25 0.538 7.67 ,Harmonic 26 0.226 3.98 ,Harmonic 27 (-1.141) 8.92 ,Harmonic 28 (-2.845) 6.07 ,Harmonic 29 2.612 0.89 ,Harmonic 30 (-0.18) 3.5] note10 :: Note note10 = Note (Pitch 349.228 53 "f4") 11 (Range (NoteRange (NoteRangeAmplitude 9429.15 27 6.04) (NoteRangeHarmonicFreq 1 349.22)) (NoteRange (NoteRangeAmplitude 1047.68 3 5404.0) (NoteRangeHarmonicFreq 28 9778.38))) [Harmonic 1 (-1.072) 5070.66 ,Harmonic 2 2.024 106.85 ,Harmonic 3 2.23 5404.0 ,Harmonic 4 (-1.105) 123.13 ,Harmonic 5 0.389 1352.72 ,Harmonic 6 0.78 167.58 ,Harmonic 7 2.071 754.42 ,Harmonic 8 (-1.989) 44.1 ,Harmonic 9 0.156 394.29 ,Harmonic 10 2.503 267.89 ,Harmonic 11 (-0.531) 337.34 ,Harmonic 12 2.071 103.73 ,Harmonic 13 1.059 74.65 ,Harmonic 14 1.112 99.35 ,Harmonic 15 (-3.8e-2) 29.36 ,Harmonic 16 (-2.495) 46.42 ,Harmonic 17 2.679 16.82 ,Harmonic 18 (-2.482) 6.95 ,Harmonic 19 0.226 51.07 ,Harmonic 20 0.138 50.28 ,Harmonic 21 2.316 22.06 ,Harmonic 22 (-1.99) 16.36 ,Harmonic 23 2.601 10.46 ,Harmonic 24 (-2.135) 9.22 ,Harmonic 25 3.068 7.88 ,Harmonic 26 2.963 8.7 ,Harmonic 27 1.36 6.04 ,Harmonic 28 1.16 8.58] note11 :: Note note11 = Note (Pitch 369.994 54 "f#4") 12 (Range (NoteRange (NoteRangeAmplitude 9989.83 27 2.19) (NoteRangeHarmonicFreq 1 369.99)) (NoteRange (NoteRangeAmplitude 369.99 1 5826.0) (NoteRangeHarmonicFreq 27 9989.83))) [Harmonic 1 1.239 5826.0 ,Harmonic 2 (-1.225) 33.96 ,Harmonic 3 1.635 2948.71 ,Harmonic 4 1.499 100.41 ,Harmonic 5 (-2.585) 1286.78 ,Harmonic 6 (-1.158) 219.2 ,Harmonic 7 2.57 258.17 ,Harmonic 8 1.152 288.82 ,Harmonic 9 (-1.045) 419.08 ,Harmonic 10 1.893 194.37 ,Harmonic 11 2.807 53.98 ,Harmonic 12 0.954 78.92 ,Harmonic 13 0.439 110.24 ,Harmonic 14 (-2.749) 19.27 ,Harmonic 15 8.4e-2 20.33 ,Harmonic 16 2.55 12.25 ,Harmonic 17 (-2.816) 14.82 ,Harmonic 18 0.108 35.2 ,Harmonic 19 (-2.244) 6.5 ,Harmonic 20 (-0.551) 14.92 ,Harmonic 21 (-1.505) 7.74 ,Harmonic 22 (-1.149) 8.3 ,Harmonic 23 1.228 4.85 ,Harmonic 24 2.757 4.65 ,Harmonic 25 (-1.622) 6.61 ,Harmonic 26 0.286 3.67 ,Harmonic 27 0.505 2.19] note12 :: Note note12 = Note (Pitch 391.995 55 "g4") 13 (Range (NoteRange (NoteRangeAmplitude 9799.87 25 1.7) (NoteRangeHarmonicFreq 1 391.99)) (NoteRange (NoteRangeAmplitude 391.99 1 5073.0) (NoteRangeHarmonicFreq 25 9799.87))) [Harmonic 1 1.152 5073.0 ,Harmonic 2 (-4.3e-2) 75.8 ,Harmonic 3 2.176 1967.94 ,Harmonic 4 0.439 53.21 ,Harmonic 5 2.113 587.03 ,Harmonic 6 2.447 131.96 ,Harmonic 7 0.741 351.85 ,Harmonic 8 2.308 31.57 ,Harmonic 9 2.13 213.73 ,Harmonic 10 1.086 23.06 ,Harmonic 11 0.617 113.8 ,Harmonic 12 2.748 81.19 ,Harmonic 13 2.935 23.45 ,Harmonic 14 1.584 7.38 ,Harmonic 15 1.444 14.11 ,Harmonic 16 0.886 22.59 ,Harmonic 17 (-2.073) 12.93 ,Harmonic 18 (-0.183) 31.32 ,Harmonic 19 1.609 4.17 ,Harmonic 20 0.887 42.8 ,Harmonic 21 (-2.242) 8.52 ,Harmonic 22 (-2.449) 9.22 ,Harmonic 23 (-0.751) 7.45 ,Harmonic 24 1.737 5.09 ,Harmonic 25 (-3.028) 1.7] note13 :: Note note13 = Note (Pitch 415.305 56 "g#4") 14 (Range (NoteRange (NoteRangeAmplitude 8721.4 21 3.87) (NoteRangeHarmonicFreq 1 415.3)) (NoteRange (NoteRangeAmplitude 415.3 1 3937.0) (NoteRangeHarmonicFreq 24 9967.32))) [Harmonic 1 (-2.047) 3937.0 ,Harmonic 2 0.755 65.1 ,Harmonic 3 (-0.669) 818.68 ,Harmonic 4 (-2.019) 101.99 ,Harmonic 5 (-1.029) 545.13 ,Harmonic 6 (-1.624) 41.49 ,Harmonic 7 (-1.42) 242.81 ,Harmonic 8 (-0.548) 19.77 ,Harmonic 9 0.762 243.48 ,Harmonic 10 1.368 62.67 ,Harmonic 11 (-1.819) 104.81 ,Harmonic 12 (-2.605) 5.89 ,Harmonic 13 (-1.126) 4.53 ,Harmonic 14 (-1.353) 13.72 ,Harmonic 15 (-2.718) 23.87 ,Harmonic 16 (-2.13) 14.57 ,Harmonic 17 3.044 20.4 ,Harmonic 18 (-0.68) 7.74 ,Harmonic 19 2.517 21.24 ,Harmonic 20 2.41 9.9 ,Harmonic 21 (-0.266) 3.87 ,Harmonic 22 9.7e-2 5.96 ,Harmonic 23 (-1.032) 4.08 ,Harmonic 24 1.296 4.51] note14 :: Note note14 = Note (Pitch 440.0 57 "a4") 15 (Range (NoteRange (NoteRangeAmplitude 9240.0 21 3.15) (NoteRangeHarmonicFreq 1 440.0)) (NoteRange (NoteRangeAmplitude 440.0 1 5337.0) (NoteRangeHarmonicFreq 22 9680.0))) [Harmonic 1 1.473 5337.0 ,Harmonic 2 1.442 169.23 ,Harmonic 3 (-1.647) 3149.26 ,Harmonic 4 (-1.366) 357.72 ,Harmonic 5 1.628 957.15 ,Harmonic 6 1.476 92.36 ,Harmonic 7 1.522 973.87 ,Harmonic 8 (-0.228) 402.32 ,Harmonic 9 (-0.766) 259.01 ,Harmonic 10 2.506 138.52 ,Harmonic 11 2.622 187.05 ,Harmonic 12 1.773 40.68 ,Harmonic 13 2.935 32.83 ,Harmonic 14 2.106 60.59 ,Harmonic 15 (-1.817) 44.17 ,Harmonic 16 0.677 15.08 ,Harmonic 17 (-2.964) 6.95 ,Harmonic 18 (-1.369) 24.23 ,Harmonic 19 1.184 9.72 ,Harmonic 20 3.031 14.3 ,Harmonic 21 (-1.217) 3.15 ,Harmonic 22 0.406 17.96] note15 :: Note note15 = Note (Pitch 466.164 58 "a#4") 16 (Range (NoteRange (NoteRangeAmplitude 8857.11 19 1.91) (NoteRangeHarmonicFreq 1 466.16)) (NoteRange (NoteRangeAmplitude 466.16 1 3174.0) (NoteRangeHarmonicFreq 21 9789.44))) [Harmonic 1 1.289 3174.0 ,Harmonic 2 1.23 116.21 ,Harmonic 3 (-3.031) 587.41 ,Harmonic 4 2.196 195.65 ,Harmonic 5 1.791 437.95 ,Harmonic 6 1.43 97.13 ,Harmonic 7 1.923 144.39 ,Harmonic 8 0.837 218.67 ,Harmonic 9 (-0.909) 189.75 ,Harmonic 10 2.683 87.79 ,Harmonic 11 0.884 108.72 ,Harmonic 12 0.208 22.05 ,Harmonic 13 (-0.547) 46.15 ,Harmonic 14 (-0.618) 30.4 ,Harmonic 15 0.711 31.52 ,Harmonic 16 (-0.707) 9.8 ,Harmonic 17 0.0 23.74 ,Harmonic 18 (-3.127) 8.59 ,Harmonic 19 (-1.256) 1.91 ,Harmonic 20 (-1.828) 4.65 ,Harmonic 21 (-0.571) 7.72] note16 :: Note note16 = Note (Pitch 493.883 59 "b4") 17 (Range (NoteRange (NoteRangeAmplitude 9383.77 19 0.76) (NoteRangeHarmonicFreq 1 493.88)) (NoteRange (NoteRangeAmplitude 493.88 1 2704.0) (NoteRangeHarmonicFreq 20 9877.66))) [Harmonic 1 1.23 2704.0 ,Harmonic 2 9.6e-2 66.92 ,Harmonic 3 2.1 688.09 ,Harmonic 4 0.351 158.02 ,Harmonic 5 3.066 351.58 ,Harmonic 6 (-3.011) 264.68 ,Harmonic 7 (-0.245) 299.96 ,Harmonic 8 1.38 36.37 ,Harmonic 9 (-0.238) 169.84 ,Harmonic 10 (-2.135) 20.2 ,Harmonic 11 2.85 7.56 ,Harmonic 12 5.6e-2 21.19 ,Harmonic 13 1.425 10.35 ,Harmonic 14 2.656 3.74 ,Harmonic 15 (-0.937) 8.02 ,Harmonic 16 (-0.472) 5.23 ,Harmonic 17 2.854 12.78 ,Harmonic 18 (-0.299) 2.02 ,Harmonic 19 0.197 0.76 ,Harmonic 20 (-2.275) 2.84] note17 :: Note note17 = Note (Pitch 523.251 60 "c5") 18 (Range (NoteRange (NoteRangeAmplitude 9418.51 18 0.18) (NoteRangeHarmonicFreq 1 523.25)) (NoteRange (NoteRangeAmplitude 523.25 1 4027.0) (NoteRangeHarmonicFreq 19 9941.76))) [Harmonic 1 (-1.808) 4027.0 ,Harmonic 2 1.097 71.89 ,Harmonic 3 0.618 936.87 ,Harmonic 4 (-1.022) 143.84 ,Harmonic 5 0.948 207.16 ,Harmonic 6 2.835 126.33 ,Harmonic 7 (-1.898) 153.81 ,Harmonic 8 2.49 30.76 ,Harmonic 9 (-0.958) 42.31 ,Harmonic 10 2.354 3.39 ,Harmonic 11 2.594 34.0 ,Harmonic 12 (-2.495) 3.53 ,Harmonic 13 (-0.315) 7.31 ,Harmonic 14 (-0.441) 5.15 ,Harmonic 15 2.673 9.76 ,Harmonic 16 (-2.06) 7.33 ,Harmonic 17 (-0.612) 1.78 ,Harmonic 18 (-0.93) 0.18 ,Harmonic 19 (-2.856) 0.82] note18 :: Note note18 = Note (Pitch 554.365 61 "c#5") 19 (Range (NoteRange (NoteRangeAmplitude 9978.57 18 4.11) (NoteRangeHarmonicFreq 1 554.36)) (NoteRange (NoteRangeAmplitude 554.36 1 4162.0) (NoteRangeHarmonicFreq 18 9978.57))) [Harmonic 1 (-1.555) 4162.0 ,Harmonic 2 1.179 94.84 ,Harmonic 3 1.005 545.7 ,Harmonic 4 (-1.873) 245.53 ,Harmonic 5 (-2.901) 377.38 ,Harmonic 6 1.718 199.66 ,Harmonic 7 (-1.2) 90.06 ,Harmonic 8 2.88 100.44 ,Harmonic 9 (-0.308) 33.05 ,Harmonic 10 (-0.351) 22.38 ,Harmonic 11 (-2.352) 10.34 ,Harmonic 12 (-1.5e-2) 19.15 ,Harmonic 13 (-2.465) 7.25 ,Harmonic 14 3.8e-2 5.77 ,Harmonic 15 1.878 9.44 ,Harmonic 16 0.535 13.78 ,Harmonic 17 (-0.903) 6.37 ,Harmonic 18 2.101 4.11] note19 :: Note note19 = Note (Pitch 587.33 62 "d5") 20 (Range (NoteRange (NoteRangeAmplitude 9984.61 17 2.03) (NoteRangeHarmonicFreq 1 587.33)) (NoteRange (NoteRangeAmplitude 1761.99 3 2877.0) (NoteRangeHarmonicFreq 17 9984.61))) [Harmonic 1 (-1.087) 2667.45 ,Harmonic 2 3.131 2022.62 ,Harmonic 3 (-1.335) 2877.0 ,Harmonic 4 2.025 280.87 ,Harmonic 5 2.472 452.76 ,Harmonic 6 1.053 271.44 ,Harmonic 7 0.587 70.55 ,Harmonic 8 (-1.745) 28.65 ,Harmonic 9 0.531 24.45 ,Harmonic 10 (-0.104) 17.6 ,Harmonic 11 (-2.472) 15.09 ,Harmonic 12 2.328 22.62 ,Harmonic 13 (-0.596) 3.69 ,Harmonic 14 2.25 14.27 ,Harmonic 15 1.106 10.61 ,Harmonic 16 0.841 4.79 ,Harmonic 17 (-0.206) 2.03] note20 :: Note note20 = Note (Pitch 622.254 63 "d#5") 21 (Range (NoteRange (NoteRangeAmplitude 8711.55 14 0.6) (NoteRangeHarmonicFreq 1 622.25)) (NoteRange (NoteRangeAmplitude 622.25 1 2326.0) (NoteRangeHarmonicFreq 16 9956.06))) [Harmonic 1 (-1.231) 2326.0 ,Harmonic 2 (-0.103) 315.62 ,Harmonic 3 (-3.033) 1097.07 ,Harmonic 4 0.823 78.37 ,Harmonic 5 (-2.255) 262.45 ,Harmonic 6 (-2.563) 202.94 ,Harmonic 7 1.031 17.18 ,Harmonic 8 (-0.438) 8.82 ,Harmonic 9 2.13 7.73 ,Harmonic 10 2.234 37.4 ,Harmonic 11 0.576 9.07 ,Harmonic 12 1.927 4.54 ,Harmonic 13 (-0.145) 0.69 ,Harmonic 14 (-0.331) 0.6 ,Harmonic 15 1.213 2.55 ,Harmonic 16 1.626 2.71] note21 :: Note note21 = Note (Pitch 659.255 64 "e5") 22 (Range (NoteRange (NoteRangeAmplitude 9229.57 14 2.66) (NoteRangeHarmonicFreq 1 659.25)) (NoteRange (NoteRangeAmplitude 1977.76 3 2372.0) (NoteRangeHarmonicFreq 15 9888.82))) [Harmonic 1 (-2.838) 948.66 ,Harmonic 2 (-1.175) 70.66 ,Harmonic 3 (-1.31) 2372.0 ,Harmonic 4 (-0.437) 50.47 ,Harmonic 5 2.285 459.52 ,Harmonic 6 (-0.488) 198.82 ,Harmonic 7 1.172 57.19 ,Harmonic 8 2.508 4.92 ,Harmonic 9 0.31 8.33 ,Harmonic 10 1.446 23.73 ,Harmonic 11 (-3.058) 3.08 ,Harmonic 12 2.984 13.54 ,Harmonic 13 1.899 2.79 ,Harmonic 14 1.533 2.66 ,Harmonic 15 (-0.814) 2.68] note22 :: Note note22 = Note (Pitch 698.456 65 "f5") 23 (Range (NoteRange (NoteRangeAmplitude 9778.38 14 2.37) (NoteRangeHarmonicFreq 1 698.45)) (NoteRange (NoteRangeAmplitude 698.45 1 4698.0) (NoteRangeHarmonicFreq 14 9778.38))) [Harmonic 1 (-1.276) 4698.0 ,Harmonic 2 (-3.014) 75.07 ,Harmonic 3 2.693 1441.37 ,Harmonic 4 (-1.702) 374.09 ,Harmonic 5 (-3.015) 177.76 ,Harmonic 6 1.459 48.8 ,Harmonic 7 (-1.119) 41.08 ,Harmonic 8 (-1.169) 10.84 ,Harmonic 9 (-1.183) 40.68 ,Harmonic 10 (-2.158) 3.81 ,Harmonic 11 0.806 8.96 ,Harmonic 12 2.099 9.54 ,Harmonic 13 (-0.785) 4.57 ,Harmonic 14 (-0.126) 2.37] note23 :: Note note23 = Note (Pitch 739.989 66 "f#5") 24 (Range (NoteRange (NoteRangeAmplitude 8139.87 11 6.34) (NoteRangeHarmonicFreq 1 739.98)) (NoteRange (NoteRangeAmplitude 739.98 1 3277.0) (NoteRangeHarmonicFreq 13 9619.85))) [Harmonic 1 (-1.678) 3277.0 ,Harmonic 2 2.794 315.68 ,Harmonic 3 (-1.428) 324.72 ,Harmonic 4 (-0.506) 210.33 ,Harmonic 5 (-3.127) 233.21 ,Harmonic 6 0.571 330.06 ,Harmonic 7 (-0.197) 30.57 ,Harmonic 8 (-0.843) 56.36 ,Harmonic 9 (-0.943) 128.08 ,Harmonic 10 (-1.332) 38.85 ,Harmonic 11 (-0.936) 6.34 ,Harmonic 12 2.869 18.58 ,Harmonic 13 0.635 16.71] note24 :: Note note24 = Note (Pitch 783.991 67 "g5") 25 (Range (NoteRange (NoteRangeAmplitude 9407.89 12 17.34) (NoteRangeHarmonicFreq 1 783.99)) (NoteRange (NoteRangeAmplitude 783.99 1 3813.0) (NoteRangeHarmonicFreq 12 9407.89))) [Harmonic 1 (-2.072) 3813.0 ,Harmonic 2 (-0.922) 1651.17 ,Harmonic 3 (-1.67) 2217.22 ,Harmonic 4 2.517 911.03 ,Harmonic 5 (-0.6) 241.23 ,Harmonic 6 0.522 122.83 ,Harmonic 7 (-1.021) 158.38 ,Harmonic 8 2.594 130.94 ,Harmonic 9 (-0.417) 63.93 ,Harmonic 10 (-2.536) 28.38 ,Harmonic 11 0.622 29.13 ,Harmonic 12 (-3.029) 17.34] note25 :: Note note25 = Note (Pitch 830.609 68 "g#5") 26 (Range (NoteRange (NoteRangeAmplitude 9967.3 12 0.45) (NoteRangeHarmonicFreq 1 830.6)) (NoteRange (NoteRangeAmplitude 830.6 1 2787.0) (NoteRangeHarmonicFreq 12 9967.3))) [Harmonic 1 1.583 2787.0 ,Harmonic 2 (-0.71) 617.07 ,Harmonic 3 0.644 659.12 ,Harmonic 4 2.704 395.43 ,Harmonic 5 3.131 44.91 ,Harmonic 6 1.109 12.43 ,Harmonic 7 0.563 17.29 ,Harmonic 8 2.946 90.74 ,Harmonic 9 2.08 33.58 ,Harmonic 10 2.679 5.91 ,Harmonic 11 2.989 2.85 ,Harmonic 12 (-1.771) 0.45] note26 :: Note note26 = Note (Pitch 880.0 69 "a5") 27 (Range (NoteRange (NoteRangeAmplitude 9680.0 11 5.46) (NoteRangeHarmonicFreq 1 880.0)) (NoteRange (NoteRangeAmplitude 880.0 1 1703.0) (NoteRangeHarmonicFreq 11 9680.0))) [Harmonic 1 (-1.927) 1703.0 ,Harmonic 2 (-2.741) 134.66 ,Harmonic 3 (-0.754) 464.25 ,Harmonic 4 (-0.827) 110.06 ,Harmonic 5 1.216 12.57 ,Harmonic 6 1.917 9.07 ,Harmonic 7 (-1.921) 10.51 ,Harmonic 8 (-9.3e-2) 36.56 ,Harmonic 9 1.321 9.43 ,Harmonic 10 (-2.351) 9.09 ,Harmonic 11 (-1.101) 5.46] note27 :: Note note27 = Note (Pitch 932.328 70 "a#5") 28 (Range (NoteRange (NoteRangeAmplitude 8390.95 9 8.79) (NoteRangeHarmonicFreq 1 932.32)) (NoteRange (NoteRangeAmplitude 932.32 1 3644.0) (NoteRangeHarmonicFreq 10 9323.27))) [Harmonic 1 1.298 3644.0 ,Harmonic 2 1.237 426.47 ,Harmonic 3 2.349 515.0 ,Harmonic 4 (-2.862) 36.64 ,Harmonic 5 0.815 9.37 ,Harmonic 6 1.842 25.47 ,Harmonic 7 (-2.559) 21.61 ,Harmonic 8 2.655 36.29 ,Harmonic 9 0.627 8.79 ,Harmonic 10 (-0.603) 14.99] note28 :: Note note28 = Note (Pitch 987.767 71 "b5") 29 (Range (NoteRange (NoteRangeAmplitude 9877.67 10 11.1) (NoteRangeHarmonicFreq 1 987.76)) (NoteRange (NoteRangeAmplitude 987.76 1 3440.0) (NoteRangeHarmonicFreq 10 9877.67))) [Harmonic 1 (-1.843) 3440.0 ,Harmonic 2 (-0.219) 952.35 ,Harmonic 3 2.102 748.2 ,Harmonic 4 (-2.254) 67.26 ,Harmonic 5 (-1.705) 21.03 ,Harmonic 6 (-2.63) 93.53 ,Harmonic 7 (-0.985) 84.86 ,Harmonic 8 (-0.884) 17.7 ,Harmonic 9 1.383 19.16 ,Harmonic 10 (-3.031) 11.1] note29 :: Note note29 = Note (Pitch 1046.5 72 "c6") 30 (Range (NoteRange (NoteRangeAmplitude 9418.5 9 11.06) (NoteRangeHarmonicFreq 1 1046.5)) (NoteRange (NoteRangeAmplitude 1046.5 1 3606.0) (NoteRangeHarmonicFreq 9 9418.5))) [Harmonic 1 (-1.745) 3606.0 ,Harmonic 2 (-0.387) 188.41 ,Harmonic 3 2.498 251.1 ,Harmonic 4 0.634 217.12 ,Harmonic 5 (-1.74) 44.29 ,Harmonic 6 4.3e-2 58.2 ,Harmonic 7 1.966 20.0 ,Harmonic 8 (-1.984) 13.68 ,Harmonic 9 2.088 11.06] note30 :: Note note30 = Note (Pitch 1108.73 73 "c#6") 31 (Range (NoteRange (NoteRangeAmplitude 7761.11 7 9.21) (NoteRangeHarmonicFreq 1 1108.73)) (NoteRange (NoteRangeAmplitude 1108.73 1 2929.0) (NoteRangeHarmonicFreq 8 8869.84))) [Harmonic 1 1.657 2929.0 ,Harmonic 2 (-0.823) 258.78 ,Harmonic 3 (-9.9e-2) 387.14 ,Harmonic 4 0.582 128.99 ,Harmonic 5 (-0.676) 46.35 ,Harmonic 6 1.986 92.29 ,Harmonic 7 2.85 9.21 ,Harmonic 8 (-1.599) 19.17] note31 :: Note note31 = Note (Pitch 1174.66 74 "d6") 32 (Range (NoteRange (NoteRangeAmplitude 9397.28 8 13.07) (NoteRangeHarmonicFreq 1 1174.66)) (NoteRange (NoteRangeAmplitude 1174.66 1 3358.0) (NoteRangeHarmonicFreq 8 9397.28))) [Harmonic 1 (-1.807) 3358.0 ,Harmonic 2 (-2.241) 190.38 ,Harmonic 3 (-0.585) 375.92 ,Harmonic 4 3.116 118.28 ,Harmonic 5 (-1.844) 17.27 ,Harmonic 6 2.257 76.68 ,Harmonic 7 (-2.761) 64.3 ,Harmonic 8 (-1.217) 13.07]
anton-k/sharc-timbre
src/Sharc/Instruments/ClarinetEflat.hs
bsd-3-clause
33,465
0
15
9,725
12,562
6,504
6,058
1,155
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Time.RO.Corpus ( corpus , negativeCorpus ) where import Data.String import Prelude import Duckling.Locale import Duckling.Resolve import Duckling.Time.Corpus import Duckling.TimeGrain.Types hiding (add) import Duckling.Testing.Types hiding (examples) negativeCorpus :: NegativeCorpus negativeCorpus = (testContext, testOptions, examples) where examples = [ "sa" ] corpus :: Corpus corpus = (testContext {locale = makeLocale RO Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (datetime (2013, 2, 12, 4, 30, 0) Second) [ "acum" , "chiar acum" ] , examples (datetime (2013, 2, 12, 0, 0, 0) Day) [ "azi" , "astazi" , "astăzi" ] , examples (datetime (2013, 2, 11, 0, 0, 0) Day) [ "ieri" ] , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "maine" , "mâine" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Day) [ "luni" , "lunea asta" , "lunea aceasta" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Day) [ "Luni, 18 Feb" , "Luni, 18 Februarie" ] , examples (datetime (2013, 2, 19, 0, 0, 0) Day) [ "marti" , "marți" , "Marti 19" , "Marti pe 19" , "Marți 19" ] , examples (datetime (2013, 2, 14, 0, 0, 0) Day) [ "joi" , "jo" ] , examples (datetime (2013, 2, 15, 0, 0, 0) Day) [ "vineri" , "vi" ] , examples (datetime (2013, 2, 16, 0, 0, 0) Day) [ "sambata" , "sâmbătă" , "sam" ] , examples (datetime (2013, 2, 17, 0, 0, 0) Day) [ "duminica" , "duminică" , "du" , "dum" ] , examples (datetime (2013, 3, 1, 0, 0, 0) Day) [ "1 martie" , "intai martie" ] , examples (datetimeInterval ((2013, 6, 19, 0, 0, 0), (2013, 6, 21, 0, 0, 0)) Day) [ "iunie 19-20" ] , examples (datetime (2013, 12, 25, 0, 0, 0) Day) [ "ziua de craciun" , "crăciun" ] , examples (datetime (2013, 2, 14, 0, 0, 0) Day) [ "poimaine" , "poimâine" ] ]
facebookincubator/duckling
Duckling/Time/RO/Corpus.hs
bsd-3-clause
2,744
0
11
1,085
789
482
307
70
1
{-# LANGUAGE ExistentialQuantification, Rank2Types, PolyKinds #-} module Data.GADT.Untagged where -- | Existential type, representing GADT, abstracted from typelevel tag (first type parameter). data Untagged con = forall a. Tagged (con a) -- | Function to untag values. -- -- > f :: [Term A] -> [Term B] -> [Untagged Term] -- > f xs ys = map untag xs ++ map untag ys untag :: con a -> Untagged con untag = Tagged -- | Processes untagged value by unpacking it from existential wrapper and feeding result to rank2-typed funarg. -- -- > f :: Untagged Term -> Integer -- > f term = match term $ \case -- > Var ... -> ... -- > Lam ... -> ... match :: Untagged con -> (forall a. con a -> r) -> r match (Tagged x) f = f x -- | Existential type, representing GADT, abstracted from two typelevel tags (first two type parameters). data Untagged2 con = forall a b. Tagged2 (con a b) untag2 :: con a b -> Untagged2 con untag2 = Tagged2 match2 :: Untagged2 con -> (forall a b. con a b -> r) -> r match2 (Tagged2 x) f = f x -- | Existential type, representing GADT, abstracted from three typelevel tags (first three type parameters). data Untagged3 con = forall a b c. Tagged3 (con a b c) untag3 :: con a b c -> Untagged3 con untag3 = Tagged3 match3 :: Untagged3 con -> (forall a b c. con a b c -> r) -> r match3 (Tagged3 x) f = f x
apsk/ungadtagger
src/Data/GADT/Untagged.hs
bsd-3-clause
1,376
0
10
320
318
175
143
17
1
----------------------------------------------------------------------------- -- StaticThih: Static environment for Thih -- -- 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 Thih.Static.Thih (module Thih.Static.Prim, module Thih.Static.Prelude, module Thih.Static.List, module Thih.Static.Monad, module Thih.Static.Thih) where import Thih.Static.Prim import Thih.Static.Prelude import Thih.Static.List import Thih.Static.Monad ----------------------------------------------------------------------------- -- Thih types: tId = TAp tList tChar tKind = TCon (Tycon "Kind" Star) starCfun = "Star" :>: (Forall [] ([] :=> tKind)) kfunCfun = "Kfun" :>: (Forall [] ([] :=> (tKind `fn` tKind `fn` tKind))) tType = TCon (Tycon "Type" Star) tVarCfun = "TVar" :>: (Forall [] ([] :=> (tTyvar `fn` tType))) tConCfun = "TCon" :>: (Forall [] ([] :=> (tTycon `fn` tType))) tApCfun = "TAp" :>: (Forall [] ([] :=> (tType `fn` tType `fn` tType))) tGenCfun = "TGen" :>: (Forall [] ([] :=> (tInt `fn` tType))) tTyvar = TCon (Tycon "Tyvar" Star) tyvarCfun = "Tyvar" :>: (Forall [] ([] :=> (tId `fn` tKind `fn` tTyvar))) tTycon = TCon (Tycon "Tycon" Star) tyconCfun = "Tycon" :>: (Forall [] ([] :=> (tId `fn` tKind `fn` tTycon))) tSubst = TAp tList (TAp (TAp tTuple2 tTyvar) tType) tQual = TCon (Tycon "Qual" (Kfun Star Star)) qualifyCfun = ":=>" :>: (Forall [Star] ([] :=> (TAp tList tPred `fn` TGen 0 `fn` TAp tQual (TGen 0)))) tPred = TCon (Tycon "Pred" Star) isInCfun = "IsIn" :>: (Forall [] ([] :=> (tId `fn` tType `fn` tPred))) tClass = TAp (TAp tTuple2 (TAp tList (TAp tList tChar))) (TAp tList (TAp tQual tPred)) tInst = TAp tQual tPred tClassEnv = TCon (Tycon "ClassEnv" Star) classEnvCfun = "ClassEnv" :>: (Forall [] ([] :=> ((tId `fn` TAp tMaybe tClass) `fn` TAp tList tType `fn` tClassEnv))) classesSfun = "classes" :>: (Forall [] ([] :=> (tClassEnv `fn` tId `fn` TAp tMaybe tClass))) defaultsSfun = "defaults" :>: (Forall [] ([] :=> (tClassEnv `fn` TAp tList tType))) tEnvTransformer = tClassEnv `fn` TAp tMaybe tClassEnv tScheme = TCon (Tycon "Scheme" Star) forallCfun = "Forall" :>: (Forall [] ([] :=> (TAp tList tKind `fn` TAp tQual tType `fn` tScheme))) tAssump = TCon (Tycon "Assump" Star) assumeCfun = ":>:" :>: (Forall [] ([] :=> (tId `fn` tScheme `fn` tAssump))) tTI = TCon (Tycon "TI" (Kfun Star Star)) tICfun = "TI" :>: (Forall [Star] ([] :=> ((tSubst `fn` tInt `fn` TAp (TAp (TAp tTuple3 tSubst) tInt) (TGen 0)) `fn` TAp tTI (TGen 0)))) tInfer a b = tClassEnv `fn` TAp tList tAssump `fn` a `fn` TAp tTI (TAp (TAp tTuple2 (TAp tList tPred)) b) tLiteral = TCon (Tycon "Literal" Star) litIntCfun = "LitInt" :>: (Forall [] ([] :=> (tInteger `fn` tLiteral))) litCharCfun = "LitChar" :>: (Forall [] ([] :=> (tChar `fn` tLiteral))) litRatCfun = "LitRat" :>: (Forall [] ([] :=> (tRational `fn` tLiteral))) litStrCfun = "LitStr" :>: (Forall [] ([] :=> (tString `fn` tLiteral))) tPat = TCon (Tycon "Pat" Star) pVarCfun = "PVar" :>: (Forall [] ([] :=> (tId `fn` tPat))) pWildcardCfun = "PWildcard" :>: (Forall [] ([] :=> tPat)) pAsCfun = "PAs" :>: (Forall [] ([] :=> (tId `fn` tPat `fn` tPat))) pLitCfun = "PLit" :>: (Forall [] ([] :=> (tLiteral `fn` tPat))) pNpkCfun = "PNpk" :>: (Forall [] ([] :=> (tId `fn` tInteger `fn` tPat))) pConCfun = "PCon" :>: (Forall [] ([] :=> (tAssump `fn` TAp tList tPat `fn` tPat))) tExpr = TCon (Tycon "Expr" Star) varCfun = "Var" :>: (Forall [] ([] :=> (tId `fn` tExpr))) litCfun = "Lit" :>: (Forall [] ([] :=> (tLiteral `fn` tExpr))) constCfun = "Const" :>: (Forall [] ([] :=> (tAssump `fn` tExpr))) apCfun = "Ap" :>: (Forall [] ([] :=> (tExpr `fn` tExpr `fn` tExpr))) letCfun = "Let" :>: (Forall [] ([] :=> (tBindGroup `fn` tExpr `fn` tExpr))) tAlt = TAp (TAp tTuple2 (TAp tList tPat)) tExpr tAmbiguity = TAp (TAp tTuple2 tTyvar) (TAp tList tPred) tExpl = TAp (TAp (TAp tTuple3 (TAp tList tChar)) tScheme) (TAp tList (TAp (TAp tTuple2 (TAp tList tPat)) tExpr)) tImpl = TAp (TAp tTuple2 (TAp tList tChar)) (TAp tList (TAp (TAp tTuple2 (TAp tList tPat)) tExpr)) tBindGroup = TAp (TAp tTuple2 (TAp tList (TAp (TAp (TAp tTuple3 (TAp tList tChar)) tScheme) (TAp tList (TAp (TAp tTuple2 (TAp tList tPat)) tExpr))))) (TAp tList (TAp tList (TAp (TAp tTuple2 (TAp tList tChar)) (TAp tList (TAp (TAp tTuple2 (TAp tList tPat)) tExpr))))) tProgram = TAp tList (TAp (TAp tTuple2 (TAp tList (TAp (TAp (TAp tTuple3 (TAp tList tChar)) tScheme) (TAp tList (TAp (TAp tTuple2 (TAp tList tPat)) tExpr))))) (TAp tList (TAp tList (TAp (TAp tTuple2 (TAp tList tChar)) (TAp tList (TAp (TAp tTuple2 (TAp tList tPat)) tExpr)))))) ----------------------------------------------------------------------------- thihClasses = addClass cHasKind [] <:> addClass cTypes [] <:> addClass cInstantiate [] <:> instances instsThih instsThih = [mkInst [] ([] :=> isIn1 cEq tKind), mkInst [] ([] :=> isIn1 cEq tType), mkInst [] ([] :=> isIn1 cEq tTyvar), mkInst [] ([] :=> isIn1 cEq tTycon), mkInst [Star] ([isIn1 cEq (TGen 0)] :=> isIn1 cEq (TAp tQual (TGen 0))), mkInst [] ([] :=> isIn1 cEq tPred), mkInst [] ([] :=> isIn1 cEq tScheme), mkInst [] ([] :=> isIn1 cMonad tTI), mkInst [] ([] :=> isIn1 cHasKind tTyvar), mkInst [] ([] :=> isIn1 cHasKind tTycon), mkInst [] ([] :=> isIn1 cHasKind tType), mkInst [] ([] :=> isIn1 cTypes tType), mkInst [Star] ([isIn1 cTypes (TGen 0)] :=> isIn1 cTypes (TAp tList (TGen 0))), mkInst [Star] ([isIn1 cTypes (TGen 0)] :=> isIn1 cTypes (TAp tQual (TGen 0))), mkInst [] ([] :=> isIn1 cTypes tPred), mkInst [] ([] :=> isIn1 cTypes tScheme), mkInst [] ([] :=> isIn1 cTypes tAssump), mkInst [] ([] :=> isIn1 cInstantiate tType), mkInst [Star] ([isIn1 cInstantiate (TGen 0)] :=> isIn1 cInstantiate (TAp tList (TGen 0))), mkInst [Star] ([isIn1 cInstantiate (TGen 0)] :=> isIn1 cInstantiate (TAp tQual (TGen 0))), mkInst [] ([] :=> isIn1 cInstantiate tPred)] cHasKind = "HasKind" kindMfun = "kind" :>: (Forall [Star] ([isIn1 cHasKind (TGen 0)] :=> (TGen 0 `fn` tKind))) cTypes = "Types" applyMfun = "apply" :>: (Forall [Star] ([isIn1 cTypes (TGen 0)] :=> (tSubst `fn` TGen 0 `fn` TGen 0))) tvMfun = "tv" :>: (Forall [Star] ([isIn1 cTypes (TGen 0)] :=> (TGen 0 `fn` TAp tList tTyvar))) cInstantiate = "Instantiate" instMfun = "inst" :>: (Forall [Star] ([isIn1 cInstantiate (TGen 0)] :=> (TAp tList tType `fn` TGen 0 `fn` TGen 0))) -----------------------------------------------------------------------------
yu-i9/thih
src/Thih/Static/Thih.hs
bsd-3-clause
7,441
0
21
1,745
3,268
1,760
1,508
144
1
{-# LANGUAGE Arrows #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveGeneric #-} module Database where import Prelude hiding (sum) import Opaleye (Column, Nullable, matchNullable, isNull, Table(Table), required, queryTable, Query, QueryArr, restrict, (.==), (.<=), (.&&), (.<), (.===), (.++), ifThenElse, pgString, aggregate, groupBy, count, avg, sum, leftJoin, runQuery, showSqlForPostgres, Unpackspec, PGInt4, PGInt8, PGText, PGDate, PGFloat8, PGBool) import Data.Profunctor.Product (p2, p3,p4) import Data.Profunctor.Product.Default (Default) import Data.Profunctor.Product.TH (makeAdaptorAndInstance) import Data.Time.Calendar (Day) import Control.Arrow (returnA, (<<<)) import Data.Aeson import Data.Time.Calendar import GHC.Generics import qualified Database.PostgreSQL.Simple as PGS --types data Card' a b c d = Card' { idcard :: a, question :: b, answer :: c, iddeck :: d} deriving (Show, Generic) type Card = Card' Int String String Int type CardColumn = Card' (Column PGInt4) (Column PGText) (Column PGText) (Column PGInt4) $(makeAdaptorAndInstance "pCard" ''Card') cardTable :: Table CardColumn CardColumn cardTable = Table "Card" (pCard Card' { idcard = required "idcard", question = required "question", answer = required "answer", iddeck = required "iddeck"} ) select :: Query CardColumn select = queryTable cardTable -- runSelectQuery :: IO [Card] runSelectQuery = do conn <- PGS.connect PGS.defaultConnectInfo { PGS.connectHost = "192.168.1.45", PGS.connectUser = "readapp", PGS.connectPassword = "readapp", PGS.connectDatabase = "flashcards" } runSelectQuery' conn select runSelectQuery' :: PGS.Connection -> Query CardColumn -> IO [Card] runSelectQuery' conn q = runQuery conn q
vavans/Flashcard
server/app/Database.hs
bsd-3-clause
1,952
0
10
364
540
327
213
41
1
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.SGIX.Subsample -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.SGIX.Subsample ( -- * Extension Support glGetSGIXSubsample, gl_SGIX_subsample, -- * Enums pattern GL_PACK_SUBSAMPLE_RATE_SGIX, pattern GL_PIXEL_SUBSAMPLE_2424_SGIX, pattern GL_PIXEL_SUBSAMPLE_4242_SGIX, pattern GL_PIXEL_SUBSAMPLE_4444_SGIX, pattern GL_UNPACK_SUBSAMPLE_RATE_SGIX ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens
haskell-opengl/OpenGLRaw
src/Graphics/GL/SGIX/Subsample.hs
bsd-3-clause
806
0
5
107
67
48
19
11
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module Templates.Config where import Text.InterpolatedString.Perl6 (q) import Types configTemplate :: Template configTemplate = Template ".generate-component.yaml" config where config = [q|# Type of the current project; determines what files will be # generated for a component. # Valid values: React | ReactNative projectType: ReactNative # Default directory in which to generate components. defaultDirectory: app/components # Style of components to generate # Valid values: CreateClass | ES6Class | Functional componentType: ES6Class |]
tpoulsen/generate-component
src/Templates/Config.hs
bsd-3-clause
635
0
6
110
48
31
17
8
1
{-# OPTIONS -fglasgow-exts -fth #-} -- Typechecker to GADT -- Implementing a typed DSL *compiler* with the typed evaluator and the -- the typechecker from untyped terms to typed ones -- We use TH later on to lift TypedTerms to true top-level typed terms. -- That is, if we have a value (TypedTerm tp tm) of the type -- TypedTerm defined below, where tp is of the type Typ t and tm -- of of the type Term t for some type t, then -- $(lift'self tm) is the same as tm -- only with the real rather than -- existential type. module TypecheckedDSLTH where import Language.Haskell.TH hiding (Exp) import Language.Haskell.TH.Syntax hiding (Exp) import qualified Language.Haskell.TH as TH (Exp(..)) import Language.Haskell.TH.Ppr -- Untyped terms (what I get from my parser): data Exp = EDouble Double | EString String | EPrim String | EApp Exp Exp deriving (Show) -- Typed terms: data Term a where Num :: Double -> Term Double Str :: String -> Term String App :: Term (a->b) -> Term a -> Term b -- If we don't care about TH, we should use -- Fun :: (a->b) -> Term (a->b) -- Since we don't seem to have cross-stage persistent values in TH -- (only global variables) and attempt to emulate causes GHC to panic, -- we use the safe way, and keep track of the name of the primitive -- function, along with its value. Fun :: Name -> (a->b) -> Term (a->b) -- Typed evaluator eval :: Term a -> a eval (Num x) = x eval (Str x) = x eval (Fun _ x) = x eval (App e1 e2) = (eval e1) (eval e2) -- Types and type comparison data Typ a where TDouble :: Typ Double TString :: Typ String TFun :: Typ a -> Typ b -> Typ (a->b) data EQ a b where Refl :: EQ a a -- checking that two types are the same. If so, give the witness eqt :: Typ a -> Typ b -> Maybe (EQ a b) eqt TDouble TDouble = Just $ Refl eqt TString TString = Just $ Refl eqt (TFun ta1 tb1) (TFun ta2 tb2) = eqt' (eqt ta1 ta2) (eqt tb1 tb2) where eqt' :: (Maybe (EQ ta1 ta2)) -> Maybe (EQ tb1 tb2) -> Maybe (EQ (ta1 -> tb1) (ta2 -> tb2)) eqt' (Just Refl) (Just Refl) = Just Refl eqt' _ _ = Nothing eqt _ _ = Nothing instance Show (Typ a) where show TDouble = "Double" show TString = "String" show (TFun ta tb) = "(" ++ show ta ++ "->" ++ show tb ++ ")" -- Type checking data TypedTerm = forall t. TypedTerm (Typ t) (Term t) -- Typing environment type Gamma = [(String,TypedTerm)] -- Initial environment (the types of primitives) env0 = [("rev", TypedTerm (TFun TString TString) (Fun 'reverse reverse)), -- sorry, no polymorphism! ("show", TypedTerm (TFun TDouble TString) (Fun 'show show)), ("inc", TypedTerm (TFun TDouble TDouble) (Fun 'inc inc)), ("+", TypedTerm (TFun TDouble (TFun TDouble TDouble)) (Fun '(+) (+))) ] inc x = x + 1.0 typecheck :: Gamma -> Exp -> Either String TypedTerm -- literals typecheck _ (EDouble x) = Right $ TypedTerm TDouble (Num x) typecheck _ (EString x) = Right $ TypedTerm TString (Str x) typecheck env (EPrim x) = maybe err Right $ lookup x env where err = Left $ "unknown primitive " ++ x typecheck env (EApp e1 e2) = case (typecheck env e1, typecheck env e2) of (Right e1, Right e2) -> typechecka e1 e2 (Left err, Right _) -> Left err (Right _, Left err) -> Left err (Left e1, Left e2) -> Left (e1 ++ " and " ++ e2) -- typecheck the application typechecka (TypedTerm (TFun ta tb) e1) (TypedTerm t2 e2) = (typechecka' (eqt ta t2) tb e1 e2) :: (Either String TypedTerm) where typechecka' :: Maybe (EQ ta t2) -> Typ tb -> Term (ta->tb) -> Term t2 -> Either String TypedTerm typechecka' (Just Refl) tb e1 e2 = Right $ TypedTerm tb (App e1 e2) typechecka' _ tb e1 e2 = Left $ unwords ["incompatible type of the application:", show (TFun ta tb), "and", show t2] typechecka (TypedTerm t1 e1) _ = Left $ "Trying to apply not-a-function: " ++ show t1 -- tests te1 = EApp (EPrim "inc") (EDouble 10.0) te2 = EApp (EDouble 10.0) (EPrim "inc") te3 = EApp (EApp (EPrim "+") (EApp (EPrim "inc") (EDouble 10.0))) (EApp (EPrim "inc") (EDouble 20.0)) te4 = EApp (EPrim "rev") te3 te5 = EApp (EPrim "rev") (EApp (EPrim "show") te3) -- typecheck-and-eval teval :: Exp -> String teval exp = either (terror) (ev) (typecheck env0 exp) where terror err = "Type error: " ++ err ev (TypedTerm t e) = "type " ++ show t ++ ", value " ++ (tryshow (eqt t TString) (eqt t TDouble) (eval e)) tryshow :: Maybe (EQ t String) -> Maybe (EQ t Double) -> t -> String tryshow (Just Refl) _ t = t tryshow _ (Just Refl) t = show t tryshow _ _ _ = "<fun>" -- evaluation tests ev_te1 = teval te1 -- "type Double, value 11.0" ev_te2 = teval te2 -- "Type error: Trying to apply not-a-function: Double" ev_te3 = teval te3 -- "type Double, value 32.0" ev_te4 = teval te4 -- "Type error: incompatible type of the application: (String->String) and Double" ev_te5 = teval te5 -- "type String, value 0.23" -- The drawback of the existential type: the following does not work {- testr = either (error) (ev) (typecheck env0 te3) where ev (TypedTerm t e) = sin (eval e) Inferred type is less polymorphic than expected Quantified type variable `t' escapes -} -- TH stuff {- we'd like a function lift'self :: Term a -> Q TH.Exp such that $(lift'self term) == term for any term :: Term a In other words, we would like to convert any term to the code of itself. Evaluating (i.e., `running', or `splicing') that code should recover the original term. Because we deal with typed terms, the splicing should not raise any type error. -} lift'self :: Term a -> ExpQ lift'self (Num x) = [e| Num $(litE . rationalL . toRational $ x) |] lift'self (Str x) = [e| Str $(litE . stringL $ x) |] lift'self (Fun n _) = [e| Fun $(reifyName n) $(varE $ n) |] lift'self (App e1 e2) = [e| App $(lift'self e1) $(lift'self e2) |] -- Obtain the Name that corresponds to a top-level (Prelude-level) -- Haskell identifier. -- Given an expression such as '(+) we return the expression -- that is the application of mkNameG_v to the correct strings. -- That expression, when spliced in, will compute exactly the same -- name that corresponds to the one we started with, that is, (+). -- Note that (+) was the identifier, not the name. -- We essentially apply the TH to itself and emulate more than one stage -- of computation. reifyName (Name occname (NameG VarName pn mn)) = [e| mkNameG_v $(litE . stringL . pkgString $ pn) $(litE . stringL . modString $ mn) $(litE . stringL . occString $ occname)|] show_code cde = runQ cde >>= putStrLn . pprint -- typecheck-and-lift. Type errors are thrown immediately tevall :: Exp -> ExpQ tevall exp = either (terror) (ev) (typecheck env0 exp) where terror err = error $ "Type error: " ++ err ev (TypedTerm t e) = lift'self e ts1 = show_code $ tevall te1 ts3 = show_code $ tevall te3 ts5 = show_code $ tevall te5
rosenbergdm/language-r
src/Language/R/sketches/TypecheckedDSLTH.hs
bsd-3-clause
6,988
24
13
1,604
2,020
1,067
953
-1
-1
{-# LANGUAGE Safe #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} ------------------------------------------------------------------------ -- | -- Module : AI.Rete.State -- Copyright : (c) 2015 Konrad Grzanek -- License : BSD-style (see the file LICENSE) -- Created : 2015-03-10 -- Maintainer : [email protected] -- Stability : experimental ------------------------------------------------------------------------ module AI.Rete.State ( -- * State manipulation viewS , setS , overS -- * Evaluation , run , eval ) where import AI.Rete.Data import qualified Control.Monad.Trans.State.Strict as S import qualified Data.HashMap.Strict as Map import Data.Hashable (Hashable) import Kask.Control.Lens class State a s where -- | Reads a state of the argument in Rete monad. viewS :: a -> ReteM s -- | Sets a state of the argument in Rete monad. setS :: a -> s -> ReteM () -- | Changes a state of the argument using a function in Rete monad. overS :: State a s => (s -> s) -> a -> ReteM () overS f obj = viewS obj >>= setS obj . f {-# INLINE overS #-} -- | Runs the computation in the Rete state-monad. run :: ReteState -> ReteM a -> (a, ReteState) run = flip S.runState {-# INLINE run #-} -- | Evaluates the Rete state-monad value. eval :: ReteState -> ReteM a -> a eval = flip S.evalState {-# INLINE eval #-} instance State Rete ReteState where viewS _ = S.get setS _ = S.put {-# INLINE viewS #-} {-# INLINE setS #-} instance State Amem AmemState where viewS amem = fmap (lookupState amem . view reteAmemStates) (viewS Rete) setS amem s = viewS Rete >>= setS Rete . over reteAmemStates (Map.insert amem s) {-# INLINE viewS #-} {-# INLINE setS #-} instance State Bmem BmemState where viewS bmem = fmap (lookupState bmem . view reteBmemStates) (viewS Rete) setS bmem s = viewS Rete >>= setS Rete . over reteBmemStates (Map.insert bmem s) {-# INLINE viewS #-} {-# INLINE setS #-} instance State Join JoinState where viewS bmem = fmap (lookupState bmem . view reteJoinStates) (viewS Rete) setS bmem s = viewS Rete >>= setS Rete . over reteJoinStates (Map.insert bmem s) {-# INLINE viewS #-} {-# INLINE setS #-} lookupState :: (Hashable k, Eq k, Show k) => k -> Map.HashMap k v -> v lookupState k = Map.lookupDefault (error ("rete PANIC (1): STATE NOT FOUND FOR " ++ show k)) k {-# INLINE lookupState #-}
kongra/rete
AI/Rete/State.hs
bsd-3-clause
2,521
0
10
598
599
320
279
51
1
{-# LANGUAGE FlexibleContexts #-} -- | -- Module : Core.DFA -- Copyright : (c) Radek Micek 2009, 2010 -- License : BSD3 -- Stability : experimental -- -- Deterministic finite state automaton. -- module Core.DFA ( DFA , State , StateData(..) , Transitions , updateWhatMatches , updateReachablePrio , kMinimize , buildDFA ) where import qualified Data.Map as M import Data.Array import qualified Data.Array.Unboxed as U import Data.Array.Unboxed (UArray) import Core.Rule import Core.RE import Data.Maybe (fromJust) import Data.List (mapAccumL) import Core.Partition import Data.Graph (SCC(..), stronglyConnCompR) import Control.Arrow (second) import Data.List (partition) import Core.Utils (sortAndGroupBySnd) infixl 9 !!! (!!!) :: (U.IArray UArray b, Ix a) => UArray a b -> a -> b (!!!) = (U.!) (///) :: (U.IArray UArray b, Ix a) => UArray a b -> [(a, b)] -> UArray a b (///) = (U.//) data StateData a = SD { -- | List of the rules which match in this state. sdMatches :: [RuNum] -- | Priority of the maximal rule which match in this state. , sdMatchPrio :: Maybe Priority -- | Priority of the maximal rule which is reachable from this state -- by some non-empty word. , sdReachablePrio :: Maybe Priority -- | Transition table of the state is represented as partition -- of the alphabet. Block ids represent destination states. , sdTrans :: Transitions a } -- | Transitions of one state. type Transitions a = Pa a -- | Deterministic finite state automaton. -- -- Initial state has index 0. type DFA a = Array State (StateData a) -- | State number. type State = Int -- --------------------------------------------------------------------------- -- Computation of the highest reachable priority and highest matching rule -- | Updates 'sdMatches' and 'sdMatchPrio' of the given automaton. -- -- Parameter @rules@ is same list of the rules which was used when -- building automaton. updateWhatMatches :: [Rule a] -> DFA a -> DFA a updateWhatMatches rules dfa = listArray (bounds dfa) $ map updateSD $ elems dfa where ru2Prio :: UArray RuNum Priority ru2Prio = U.listArray (RuN 0, RuN $ pred $ length rules) $ map (\(Rule _ p _ _ _) -> p) rules updateSD (SD matches _ rp ts) = case matches of [] -> SD [] Nothing rp ts _ -> SD newMatches (Just maxPrio) rp ts where maxPrio = maximum $ map (ru2Prio!!!) matches newMatches = filter ((== maxPrio) . (ru2Prio!!!)) matches -- | Updates 'sReachablePrio' of the given automaton. -- -- 'sdMatchPrio' must be already updated. updateReachablePrio :: Symbol a => DFA a -> DFA a updateReachablePrio dfa = array (bounds dfa) $ map updateState $ assocs dfa where updateState (st, sd) = (st, sd {sdReachablePrio = toMPrio $ finReachablePrioArr!!!st}) finReachablePrioArr = foldl maxOfSCC initReachablePrioArr $ scc dfa -- Maps each state to the highest priority which can be reached -- by non-empty word. @minBound@ means that no priority can be reached. initReachablePrioArr :: UArray State Priority initReachablePrioArr = U.accumArray const minBound (bounds dfa) [] -- Adds states from one strongly connected component into the map -- of reachable priorities. maxOfSCC :: UArray State Priority -> SCC (Maybe Priority, State, Neighbours) -> UArray State Priority maxOfSCC reachablePrioArr (CyclicSCC xs) = reachablePrioArr /// zip (map (\(_, st, _) -> st) xs) (repeat maxPrio) where maxPrio = maximum $ map maxOfState xs maxOfState (pr, _, ns) = max (fromMPrio pr) (maxOfNeighbours reachablePrioArr ns) maxOfSCC reachablePrioArr (AcyclicSCC (_, st, ns)) = reachablePrioArr /// [(st, maxOfNeighbours reachablePrioArr ns)] maxOfNeighbours :: UArray State Priority -> Neighbours -> Priority maxOfNeighbours reachablePrioArr neighbours = maximum $ map maxOfNeighbour neighbours where maxOfNeighbour nst = max (fromMPrio $ sdMatchPrio $ dfa!nst) (reachablePrioArr!!!nst) fromMPrio (Just p) = p fromMPrio _ = minBound toMPrio p | p /= minBound = Just p | otherwise = Nothing type Neighbours = [State] -- | Returns strongly connected components topologically sorted. scc :: Symbol a => DFA a -> [SCC (Maybe Priority, State, Neighbours)] scc = stronglyConnCompR . map convertState . assocs where convertState (i, sd) = (sdMatchPrio sd, i, map fst $ representatives $ sdTrans sd) -- --------------------------------------------------------------------------- -- Automaton minimization -- | Moore's minimization. kMinimize :: Symbol a => Int -> DFA a -> DFA a kMinimize k dfa = mergeEquivStates (kthEquivalence k dfa) dfa -- | Equivalence class. type EqClass = [State] -- | Equivalence is a list of equivalence classes. type Equivalence = [EqClass] -- | Maps each state to equivalence class id. type EqArray = UArray State EqClsId -- | Id of quivalence class. type EqClsId = Int -- | States are grouped by 'sdMatches'. initialEquivalence :: DFA a -> Equivalence initialEquivalence = map (map fst) . sortAndGroupBySnd . map (second sdMatches) . assocs -- | Refine equivalence. -- -- If not refined then returned equivalence is same as original equivalence. nextEquivalence :: Symbol a => Equivalence -> DFA a -> Equivalence nextEquivalence eq dfa = concatMap refineEqClass eq where -- IMPORTANT: Order of states is preserved when class is not subdidived. refineEqClass :: EqClass -> [[State]] refineEqClass = map (map fst) . sortAndGroupBySnd . map (second $ pmap (eqArr!!!)) -- Pairs (state, transitions). . map (\st -> (st, sdTrans $ dfa!st)) eqArr = equivalenceToEqArray (succ $ snd $ bounds dfa) eq -- | If @k@ is negative number we loop until equivalence is refined. kthEquivalence :: Symbol a => Int -> DFA a -> Equivalence kthEquivalence k dfa = iter 0 (initialEquivalence dfa) where -- @equiv@ is @nIter@-th equivalence iter nIter equiv | nIter == k = equiv | equiv == nextEquiv = equiv | otherwise = iter (succ nIter) nextEquiv where nextEquiv = nextEquivalence equiv dfa -- | Every equivalence class is replaced by one state. mergeEquivStates :: Symbol a => Equivalence -> DFA a -> DFA a mergeEquivStates eq dfa = removeNotGivenStates reprStates newDFA where -- Equivalence where state 0 is in the first equivalence class. -- State 0 will be first state in the class. eq' = let ([x], xs) = partition ((== 0) . head) eq in x:xs -- Each eq. class is represented by one state. reprStates = map head eq' -- Transitions of @reprStates@ lead only to other @reprStates@. newDFA = dfa // map (\st -> (st, updateTransitions stateToReprState $ dfa!st)) reprStates stateToReprState = U.array (bounds dfa) (concatMap (\eqCls -> zip eqCls (repeat $ head eqCls)) eq') -- | States not present in the given list will be removed. removeNotGivenStates :: Symbol a => [State] -> DFA a -> DFA a removeNotGivenStates states dfa = listArray (0, pred $ length states) (map (updateTransitions oldToNewSt . (dfa!)) states) where oldToNewSt :: UArray State State oldToNewSt = U.array (bounds dfa) (zip states [0..]) -- | Maps old state numbers in transition table to new state numbers. updateTransitions ::Symbol a => UArray State State -> StateData a -> StateData a updateTransitions oldToNewStMap (SD m mp rp ts) = SD m mp rp $ pmap (oldToNewStMap!!!) ts -- | Conversion between representations of equivalence. equivalenceToEqArray :: Int -> Equivalence -> EqArray equivalenceToEqArray nStates eq = U.array (0, pred nStates) $ concat $ stateId where stateId :: [[(State, EqClsId)]] stateId = zipWith (\states clsId -> zip states $ repeat clsId) eq [0..] -- --------------------------------------------------------------------------- -- DFA construction Brzozowski -- -- We use idea described in article -- "Regular-expression derivatives reexamined" by Scott Owens, John Reppy -- and Aaron Turon. -- | Vector representing state. type Vector = [Int] -- | States are represented by vectors of regular expressions. -- We map regular expressions to integers and vectors of integers to state -- numbers and so we represent state by numbers. data BDFA a = BDFA { bRegex2Num :: M.Map (RE a) Int , bVector2State :: M.Map Vector State , bStates :: [(State, StateData a)] } -- | Builds automaton recognizing given rules. buildDFA :: Symbol a => [Rule a] -> DFA a buildDFA = toDFA . fst . constructState emptyBDFA . reList where reList = map (\(Rule _ _ _ re _) -> toRE re) emptyBDFA = BDFA M.empty M.empty [] toDFA bdfa = array (0, pred $ M.size $ bVector2State bdfa) (bStates bdfa) addRE :: Symbol a => M.Map (RE a) Int -> RE a -> (M.Map (RE a) Int, Int) addRE m re = case M.insertLookupWithKey f key newVal m of (Just reNum, _) -> (m, reNum) (Nothing, newMap) -> (newMap, newVal) where f _key _newVal oldVal = oldVal key = re newVal = M.size m addVector :: Vector -> M.Map Vector State -> (State, Maybe (M.Map Vector State)) addVector vect m = case M.insertLookupWithKey f key newVal m of (Just st, _) -> (st, Nothing) (Nothing, newMap) -> (newVal, Just newMap) where f _key _newVal oldVal = oldVal key = vect newVal = M.size m -- | Function @'constructState' bdfa reList@ returns new automaton with -- state given by @reList@. constructState :: Symbol a => BDFA a -> [RE a] -> (BDFA a, State) constructState bdfa reList = case maybeVect2State of Nothing -> (bdfa, st) -- State is already in automaton. Just _ -> (bdfa'' { bStates = (st, stateData):(bStates bdfa'') }, st) where -- Map regular expressions. (regex2Num, vector) = mapAccumL addRE (bRegex2Num bdfa) reList -- Map vector. (st, maybeVect2State) = addVector vector (bVector2State bdfa) bdfa' = BDFA regex2Num (fromJust maybeVect2State) (bStates bdfa) (transitions, bdfa'') = buildTransitions reList bdfa' stateData = SD whatMatches Nothing Nothing transitions whatMatches = map fst $ filter snd $ zip [RuN 0..] $ map nullable reList -- | Function @'buildTransitions' reList bdfa@ returns transitions -- for the state given by @reList@ and new automaton @bdfa'@ where all -- states reachable from state given by @reList@ are constructed. -- -- @bdfa@ contains state given by @reList@. That means that regular -- expressions in @reList@ are also in @'bRegex2Num' bdfa@ and vector -- representing state is in @'bVector2Num' bdfa@. buildTransitions :: Symbol a => [RE a] -> BDFA a -> (Transitions a, BDFA a) buildTransitions reList bdfa = (transitions, bdfa') where pa = partitionAlphabetByDerivativesMany reList (blocks, symbols) = unzip $ representatives pa -- @states@ is list with destination states. (bdfa', states) = mapAccumL (\dfa s -> constructState dfa $ map (derivative s) reList) bdfa symbols block2State :: UArray BlockId State block2State = U.array (0, maximum blocks) (zip blocks states) -- Replace block ids by states. transitions = pmap (block2State!!!) pa
radekm/crep
Core/DFA.hs
bsd-3-clause
11,918
0
15
3,082
3,020
1,622
1,398
-1
-1
module Data.Unums.Ubound ( Ubound (..) ) where import Data.Unums.Unum -- | An ubound is an interval (open or closed) data Ubound ess fss = Ubound (Unum ess fss) (Unum ess fss)
hsyl20/unums
src/Data/Unums/Ubound.hs
bsd-3-clause
184
0
8
39
52
32
20
4
0
{-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE BangPatterns #-} module TestChapter4DP ( testChapter4 )where import Control.Concurrent import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.State import Data.Configurator import Data.Configurator.Types import Data.List.Split (chunksOf) import Data.Foldable (toList) import Data.Random import Data.Random.Distribution import Data.Random.Distribution.Poisson import Data.Sequence (Seq) import qualified Data.Sequence as Seq import Data.Text (Text) import qualified Data.Vector.Unboxed as VU import Graphics.Matplotlib hiding (def) import Numeric.LinearAlgebra (Vector, Matrix) import qualified Numeric.LinearAlgebra as LA import System.Console.AsciiProgress(Options(..), Stats(..), displayConsoleRegions, complete, getProgressStats, def, newProgressBar, tickN) import Text.Printf -- project import Utils import Chapter4DP testChapter4 :: FilePath -> IO () testChapter4 configPath = do print "Chapter 4 Experiment Starting " (config, _) <- autoReload autoConfig [Required configPath] (bCarRental :: Bool) <- require config "enable.bCarRental" when bCarRental (doCarRentalTest config) (bGambler :: Bool) <- require config "enable.bGamblerProblem" when bGambler (doGamblerTest config) ---------------------------------------------------------------------------------------------------- -- Car Rental Test doCarRentalTest :: Config -> IO () doCarRentalTest config = do (experimentName::String) <- require config "carRental.experiment" (theTheta::Double) <- require config "carRental.theta" (discountGamma::Double) <- require config "carRental.discount" (maxCars::[Int]) <- require config "carRental.maxCars" (rentalCredit::[Double]) <- require config "carRental.rentalCredit" (transCost::[Double]) <- require config "carRental.transferCost" (maxTransferCars::[Int]) <- require config "carRental.maxTransferCars" (freeParkingLimit::[Int]) <- require config "carRental.freeParkingLimit" (additionalParkingCost::[Double]) <- require config "carRental.additionalParkingCost" (additionalTransferSaving::[Double]) <- require config "carRental.additionalTransferSaving" (rentalCars::[Double]) <- require config "carRental.rentalCars" (returnCars::[Double]) <- require config "carRental.returnCars" let carRental = mkCarRental (length maxCars) theTheta discountGamma maxCars rentalCredit transCost maxTransferCars freeParkingLimit additionalParkingCost additionalTransferSaving rentalCars returnCars -- do experiments carRental' <- goLoop carRental when (_locationNum carRental == 2) (drawTwoLocationCarRental carRental' experimentName) threadDelay 100000 where goLoop carRental = displayConsoleRegions $ do putStrLn "Will do car rental experiment " >> putStrLn (show carRental) pg <- newProgressBar def { pgWidth = 80 , pgTotal = 100 , pgOnCompletion = Just "Done :percent after :elapsed seconds" } carRental' <- loop pg carRental putStrLn "car rental experiment finish. Final Results: " putStrLn $ showCarRentalResult carRental' pure carRental' where loop pg carRental = do let (!(bFinish, percent), !carRental') = runState carRentalStep carRental case bFinish of False -> do stat <- getProgressStats pg let ticked = fromInteger $ stCompleted stat willTick = percent - ticked if (willTick > 0) then(tickN pg willTick) else print ("Finish One Improvement " ++ show percent) loop pg carRental' True -> complete pg >> pure carRental' drawTwoLocationCarRental :: CarRental -> String -> IO () drawTwoLocationCarRental carRental experimentName = do putStrLn "Draw Two Location Car Rental Result Graph" -- dataX is the second location, whereas dataY is the first location let dataX = toList $ fmap (\ (f:s:[]) -> s) (_states carRental) dataY = toList $ fmap (\ (f:s:[]) -> f) (_states carRental) (dataZ::[Int]) = toList (Seq.zipWith (\ i saPair -> calcZ . foldl (zipWith (+)) [0, 0] $ Seq.index saPair i) (_actions carRental) (_possibleActions carRental)) dataValue = toList $ _stateValues carRental maxZ = maximum dataZ figure = readData ([dataX], [dataY], [dataZ]) % mp # "ax = plot.gca(projection='3d')" % mp # "ax.scatter(np.array(data[" # 0 # "]), np.array(data[" # 1 # "]), np.array(data[" # 2 # "]))" % xlabel "#Cars at second location" % ylabel "#Cars at first location" % zlabel "#Cars to move (action)" % xticks [0, 1..(_maxCars carRental !! 1)] % yticks [0, 1..(_maxCars carRental !! 0)] % zticks [negate maxZ, (negate $ maxZ - 1)..maxZ] % title experimentName valueFigure = readData ([dataX], [dataY], [dataValue]) % mp # "ax = plot.gca(projection='3d')" % mp # "ax.scatter(np.array(data[" # 0 # "]), np.array(data[" # 1 # "]), np.array(data[" # 2 # "]))" % xlabel "#Cars at second location" % ylabel "#Cars at first location" % zlabel "State Values" % xticks [0, 1..(_maxCars carRental !! 1)] % yticks [0, 1..(_maxCars carRental !! 0)] % title (experimentName ++ " - State Values") -- avoid Matplotlib's bug code figure >> code valueFigure >> onscreen figure >> onscreen valueFigure threadDelay 100000 -- also output table format let moveResult = showAsTable [0..(_maxCars carRental)!!0] [0..(_maxCars carRental)!!1] (map fromIntegral dataZ) False stateResult = showAsTable [0..(_maxCars carRental)!!0] [0..(_maxCars carRental)!!1] dataValue True putStrLn moveResult putStrLn stateResult where calcZ :: [Int] -> Int calcZ (firstLocation:secondLocation:[]) = (firstLocation > 0) ? (negate firstLocation, secondLocation) calcZ _ = error "Not correct action move" -- output in github markdown format showAsTable :: [Int] -> [Int] -> [Double] -> Bool -> String showAsTable col row vals bFloat = let colLen = length col header = "|First/second| " ++ (concat $ map ((++ "|") . show) col) ++ "\n" alignHeader = (concat . take (colLen + 1) $ repeat "|:-----:") ++ "|\n" showRows = concat $ map (go colLen vals) row in header ++ alignHeader ++ showRows where go len vals rowIdx = let first = show rowIdx ++ "|" rows = take len $ drop (len * rowIdx) vals format = bFloat ? ("%7.2f", "%7.0f") in first ++ (concat $ map (\ x -> (printf format x :: String) ++ "|") rows) ++ "|\n" ---------------------------------------------------------------------------------------------------- -- Gambler Problem Test doGamblerTest :: Config -> IO () doGamblerTest config = do (prob::Double) <- require config "gambler.headProb" (gamblerGoal::Int) <- require config "gambler.goal" (theTheta::Double) <- require config "gambler.theta" let gambler = mkGambler prob theTheta gamblerGoal (_, !gambler') = runState gamblerStep gambler drawGamblerGraph gambler' threadDelay 100000 pure () drawGamblerGraph :: Gambler -> IO () drawGamblerGraph gambler = do putStrLn "Draw Gambler Problem Result Graph" -- dataX is the second location, whereas dataY is the first location let policyFigure = plot [0..(goal gambler)] (stateVals gambler) % xlabel ("Capital (head probability = " ++ (show $ headProb gambler) ++ ")") % ylabel "Value Estimates" % xticks [0, 10..(goal gambler)] % title ("Figure 4.3 - State Values") valueFigure = scatter [0..(goal gambler - 1)] (stateActs gambler) % xlabel ("Capital (head probability = " ++ (show $ headProb gambler) ++ ")") % ylabel "Final Policy (Stack)" % xticks [0, 10..(goal gambler)] % title ("Figure 4.3 - Optimal Actions") -- avoid Matplotlib's bug code policyFigure >> code valueFigure >> onscreen policyFigure >> onscreen valueFigure threadDelay 100000
Xingtao/RLHask
test/TestChapter4DP.hs
bsd-3-clause
8,895
0
29
2,422
2,370
1,210
1,160
156
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} module Qi.Program.Config.Lang where import Control.Monad.Freer import Data.Aeson (FromJSON, ToJSON) import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy.Char8 as LBS import Data.Default (Default, def) import Protolude import Qi.Config.AWS (Config) {- import Qi.Config.AWS.ApiGw -} {- import Qi.Config.AWS.ApiGw.ApiMethod.Profile (ApiMethodProfile) -} import Qi.Config.AWS.CF import Qi.Config.AWS.CW {- import Qi.Config.AWS.DDB -} import Qi.Config.AWS.CfCustomResource (CfCustomResourceLambdaProgram) import Qi.Config.AWS.Lambda (LambdaProfile) import Qi.Config.AWS.S3 (S3BucketProfile) import Qi.Config.Identifier import Qi.Core.Curry {- import Qi.Program.Lambda.Cf.Lang (CfCustomResourceLambdaProgram) -} {- import Qi.Program.Lambda.Cw.Lang (CwLambdaProgram) -} {- import Qi.Program.Lambda.Ddb.Lang (DdbStreamLambdaProgram) -} import Qi.Program.Gen.Lang {- import Qi.Program.Lambda.Lang (LbdEff) -} import Qi.Program.S3.Lang data ConfigEff r where GetConfig :: ConfigEff Config RegGenericLambda :: forall a b . (FromJSON a, ToJSON b) => Proxy a -> Proxy b -> Text -> (forall effs . (Member GenEff effs, Member S3Eff effs) => a -> Eff effs b) -> LambdaProfile -> ConfigEff LambdaId -- S3 RegS3Bucket :: Text -> S3BucketProfile -> ConfigEff S3BucketId RegS3BucketLambda :: Text -> S3BucketId -> (forall effs . (Member GenEff effs, Member S3Eff effs) => S3LambdaProgram effs) -> LambdaProfile -> ConfigEff LambdaId {- -- DDB RDdbTable :: Text -> DdbAttrDef -> DdbTableProfile -> ConfigEff DdbTableId RDdbStreamLambda :: Text -> DdbTableId -> (forall effs . Member DdbEff effs => a -> effs b) -> LambdaProfile -> ConfigEff LambdaId -} -- SQS RegSqsQueue :: Text -> ConfigEff SqsQueueId -- Custom RegCustomResource :: Text -> (forall effs . (Member GenEff effs) => CfCustomResourceLambdaProgram effs) -> LambdaProfile -> ConfigEff CfCustomResourceId -- CloudWatch Logs RegCwEventLambda :: Text -> CwEventsRuleProfile -> (forall effs . (Member GenEff effs) => CwLambdaProgram effs) -> LambdaProfile -> ConfigEff LambdaId {- -- Api RApi :: Text -> ConfigEff ApiId RApiAuthorizer :: Text -> CfCustomResourceId -> ApiId -> ConfigEff ApiAuthorizerId RApiResource :: ParentResource a => Text -> a -> ConfigEff ApiResourceId RApiMethodLambda :: Text -> ApiVerb -> ApiResourceId -> ApiMethodProfile -> ApiLambdaProgram -> LambdaProfile -> ConfigEff LambdaId -} getConfig :: forall effs . (Member ConfigEff effs) => Eff effs Config getConfig = send GetConfig {- getNextId :: forall effs a . (Member ConfigEff effs, FromInt a) => Eff effs a getNextId = send GetNextId -} genericLambda :: forall a b resEffs . (Member ConfigEff resEffs, FromJSON a, ToJSON b) => Text -> (forall effs . (Member GenEff effs, Member S3Eff effs) => a -> Eff effs b) -> LambdaProfile -> Eff resEffs LambdaId genericLambda name f = send . RegGenericLambda (Proxy :: Proxy a) (Proxy :: Proxy b) name f s3Bucket :: (Member ConfigEff effs) => Text -> S3BucketProfile -> Eff effs S3BucketId s3Bucket = send .: RegS3Bucket s3BucketLambda :: forall resEffs . (Member ConfigEff resEffs) => Text -> S3BucketId -> (forall effs . (Member GenEff effs, Member S3Eff effs) => S3LambdaProgram effs) -> LambdaProfile -> Eff resEffs LambdaId s3BucketLambda name bucketId f = send . RegS3BucketLambda name bucketId f {- ddbTable :: (Member ConfigEff effs) => Text -> DdbAttrDef -> DdbTableProfile -> Eff effs DdbTableId ddbTable = send .:: RDdbTable ddbStreamLambda :: (Member ConfigEff effs) => Text -> DdbTableId -> DdbStreamLambdaProgram -> LambdaProfile -> Eff effs LambdaId ddbStreamLambda = send .::: RDdbStreamLambda -} sqsQueue :: (Member ConfigEff effs) => Text -> Eff effs SqsQueueId sqsQueue = send . RegSqsQueue customResource :: forall resEffs . (Member ConfigEff resEffs) => Text -> (forall effs . (Member GenEff effs) => CfCustomResourceLambdaProgram effs) -> LambdaProfile -> Eff resEffs CfCustomResourceId customResource name f = send . RegCustomResource name f cwEventLambda :: forall resEffs . (Member ConfigEff resEffs) => Text -> CwEventsRuleProfile -> (forall effs . (Member GenEff effs) => CwLambdaProgram effs) -> LambdaProfile -> Eff resEffs LambdaId cwEventLambda name profile f = send . RegCwEventLambda name profile f {- api :: Text -> ConfigProgram ApiId api = singleton . RApi apiAuthorizer :: Text -> CfCustomResourceId -> ApiId -> ConfigProgram ApiAuthorizerId apiAuthorizer = singleton .:: RApiAuthorizer apiResource :: ParentResource a => Text -> a -> ConfigProgram ApiResourceId apiResource = singleton .: RApiResource apiMethodLambda :: Text -> ApiVerb -> ApiResourceId -> ApiMethodProfile -> ApiLambdaProgram -> LambdaProfile -> ConfigProgram LambdaId apiMethodLambda = singleton .::::: RApiMethodLambda -}
qmuli/qmuli
library/Qi/Program/Config/Lang.hs
mit
5,809
0
14
1,505
945
528
417
118
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} -- | -- Module: BDCS.Export.Ostree -- Copyright: (c) 2017 Red Hat, Inc. -- License: LGPL -- -- Maintainer: https://github.com/weldr -- Stability: alpha -- Portability: portable -- -- Functions for exporting objects from the BDCS into an ostree repo. module BDCS.Export.Ostree(ostreeSink) where import Conduit(Conduit, Consumer, Producer, (.|), bracketP, runConduit, sourceDirectory, yield) import Control.Conditional(condM, otherwiseM, whenM) import qualified Control.Exception.Lifted as CEL import Control.Monad(void) import Control.Monad.Except(MonadError) import Control.Monad.IO.Class(MonadIO, liftIO) import Control.Monad.Logger(MonadLoggerIO, logDebugN, logInfoN) import Control.Monad.Trans(lift) import Control.Monad.Trans.Control(MonadBaseControl, liftBaseOp) import Control.Monad.Trans.Resource(MonadResource, runResourceT) import Crypto.Hash(SHA256(..), hashInitWith, hashFinalize, hashUpdate) import qualified Data.ByteString as BS (readFile) import qualified Data.Conduit.List as CL import Data.List(isPrefixOf, stripPrefix) import Data.Maybe(fromJust) import qualified Data.Text as T import System.Directory import System.FilePath((</>), takeDirectory, takeFileName) import System.IO.Temp(createTempDirectory) import System.Posix.Files(createSymbolicLink, fileGroup, fileMode, fileOwner, getFileStatus, readSymbolicLink) import Text.Printf(printf) import GI.Gio(File, fileNewForPath, noCancellable) import GI.OSTree import qualified BDCS.CS as CS import BDCS.DB(Files) import BDCS.Export.Directory(directorySink) import BDCS.Export.Utils(runHacks) import BDCS.Utils.Conduit(awaitWith) import BDCS.Utils.Process(callProcessLogged) import Paths_bdcs(getDataFileName) -- Disable a hint in replaceDirs that just makes thing look confusing {-# ANN ostreeSink ("HLint: ignore Use ." :: String) #-} -- | A 'Consumer' that writes objects into a provided ostree repo. A very large amount of work -- required to make the destination a valid ostree repo is also done by this function - setting up -- symlinks and directories, pruning unneeded directories, installing an initrd, building an -- RPM database, and so forth. ostreeSink :: (MonadBaseControl IO m, MonadError String m, MonadLoggerIO m, MonadResource m) => FilePath -> Consumer (Files, CS.Object) m () ostreeSink outPath = do -- While it's possible to copy objects from one OstreeRepo to another, we can't create our own objects, meaning -- we can't add the dirtree objects we would need to tie all of the files together. So to export to a new -- ostree repo, first export to a directory, then import that file to a new repo. -- -- Note that writing and importing a tar file does not work, because ostree chokes on paths with symlinks -- (e.g., /lib64/libaudit.so.1) dst_repo <- liftIO $ open outPath void $ bracketP (createTempDirectory (takeDirectory outPath) "export") removePathForcibly (\tmpDir -> do -- Run the sink to export to a directory logDebugN "Exporting to directory" directorySink tmpDir -- Add the standard hacks logDebugN "Running standard hacks" lift $ runHacks tmpDir -- Compile the locale-archive file let localeDir = tmpDir </> "usr" </> "lib" </> "locale" whenM (liftIO $ doesFileExist $ localeDir </> "locale-archive.tmpl") $ lift $ callProcessLogged "chroot" [tmpDir, "/usr/sbin/build-locale-archive"] -- Add the kernel and initramfs lift $ installKernelInitrd tmpDir -- Replace /etc/nsswitch.conf with the altfiles version logDebugN "Modifying /etc files" liftIO $ getDataFileName "data/nsswitch-altfiles.conf" >>= readFile >>= writeFile (tmpDir </> "etc" </> "nsswitch.conf") -- Remove the fstab stub liftIO $ removeFile $ tmpDir </> "etc" </> "fstab" -- Move things around how rpm-ostree wants them liftIO $ renameDirs tmpDir -- Enable some systemd service logDebugN "Enabling systemd services" doSystemd tmpDir -- Convert /var to a tmpfiles entry logDebugN "Running tmpfiles and creating symlinks" liftIO $ convertVar tmpDir -- Add more tmpfiles entries let tmpfilesDir = tmpDir </> "usr" </> "lib" </> "tmpfiles.d" liftIO $ getDataFileName "data/tmpfiles-ostree.conf" >>= readFile >>= writeFile (tmpfilesDir </> "weldr-ostree.conf") -- Replace a bunch of top-level directories with symlinks liftIO $ replaceDirs tmpDir -- Create a /sysroot directory liftIO $ createDirectory (tmpDir </> "sysroot") -- Replace /usr/local with a symlink for some reason liftIO $ do removePathForcibly $ tmpDir </> "usr" </> "local" createSymbolicLink "../var/usrlocal" $ tmpDir </> "usr" </> "local" -- rpm-ostree moves /var/lib/rpm to /usr/share/rpm. We don't have a rpmdb to begin -- with, so create an empty one at /usr/share/rpm. -- rpmdb treats every path as absolute rpmdbDir <- liftIO $ makeAbsolute $ tmpDir </> "usr" </> "share" </> "rpm" liftIO $ createDirectoryIfMissing True rpmdbDir lift $ callProcessLogged "rpmdb" ["--initdb", "--dbpath=" ++ rpmdbDir] -- import the directory as a new commit logDebugN "Storing results as a new commit" liftIO $ withTransaction dst_repo $ \r -> do f <- storeDirectory r tmpDir commit r f "Export commit" Nothing) -- Regenerate the summary, necessary for mirroring repoRegenerateSummary dst_repo Nothing noCancellable where convertVar :: FilePath -> IO () convertVar exportDir = do -- /var needs to be empty except for a couple of symlinks we add at the end -- Convert every directory and symlink we find to a tmpfiles entry. For everything -- else, warn and remove. let tmpfilesDir = exportDir </> "usr" </> "lib" </> "tmpfiles.d" createDirectoryIfMissing True tmpfilesDir let varDir = exportDir </> "var" writeFile (tmpfilesDir </> "weldr-var.conf") =<< unlines <$> runResourceT (runConduit $ convertToTmp "/var" varDir .| CL.consume) -- basePath is the directory we use for the paths in the tmpfiles lines (e.g., /var/lib) -- realPath is the actual path we are traversing (e.g., /tmp/export.XXXX/var/lib) convertToTmp :: MonadResource m => FilePath -> FilePath -> Producer m String convertToTmp basePath realPath = sourceDirectory realPath .| recurseAndEmit where recurseAndEmit :: MonadResource m => Conduit FilePath m String recurseAndEmit = awaitWith $ \path -> do let baseFilePath = basePath </> takeFileName path -- if it's a directory, recurse into it first whenM (liftIO $ doesDirectoryExist path) (convertToTmp baseFilePath path) -- Emit a tmpfiles line condM [(liftIO $ pathIsSymbolicLink path, yieldLink baseFilePath path), (liftIO $ doesDirectoryExist path, yieldDir baseFilePath path), -- If not something we can represent as a tmpfile, warn and continue (otherwiseM, liftIO $ putStrLn $ "Warning: Unable to convert " ++ baseFilePath ++ " to a tmpfile")] -- Remove it liftIO $ removePathForcibly path -- Repeat recurseAndEmit yieldLink :: MonadIO m => FilePath -> FilePath -> Producer m String yieldLink baseFilePath realFilePath = do target <- liftIO $ readSymbolicLink realFilePath yield $ printf "L %s - - - - %s" baseFilePath target yieldDir :: MonadIO m => FilePath -> FilePath -> Producer m String yieldDir baseDirPath realDirPath = do stat <- liftIO $ getFileStatus realDirPath -- coerce the stat fields into a type that implements PrintfArg let mode = fromIntegral $ fileMode stat :: Integer let userId = fromIntegral $ fileOwner stat :: Integer let groupId = fromIntegral $ fileGroup stat :: Integer yield $ printf "d %s %#o %d %d - -" baseDirPath mode userId groupId installKernelInitrd :: (MonadBaseControl IO m, MonadLoggerIO m) => FilePath -> m () installKernelInitrd exportDir = do -- The kernel and initramfs need to be named /boot/vmlinuz-<CHECKSUM> -- and /boot/initramfs-<CHECKSUM>, where CHECKSUM is the sha256 -- of the kernel+initramfs. let bootDir = exportDir </> "boot" -- Find a vmlinuz- file. kernelList <- filter ("vmlinuz-" `isPrefixOf`) <$> liftIO (listDirectory bootDir) let (kernel, kver) = case kernelList of -- Using fromJust is fine here - we've ensured they all have that -- prefix with the filter above. hd:_ -> (bootDir </> hd, fromJust $ stripPrefix "vmlinuz-" hd) _ -> error "No kernel found" -- Create the initramfs let initramfs = bootDir </> "initramfs-" ++ kver logInfoN $ "Installing kernel " `T.append` T.pack kernel logInfoN $ "Installing initrd " `T.append` T.pack initramfs withTempDirectory' exportDir "dracut" $ \tmpDir -> callProcessLogged "chroot" [exportDir, "dracut", "--add", "ostree", "--no-hostonly", "--tmpdir=/" ++ takeFileName tmpDir, "-f", "/boot/" ++ takeFileName initramfs, kver] -- Append the checksum to the filenames kernelData <- liftIO $ BS.readFile kernel initramfsData <- liftIO $ BS.readFile initramfs let ctx = hashInitWith SHA256 let update1 = hashUpdate ctx kernelData let update2 = hashUpdate update1 initramfsData let digest = show $ hashFinalize update2 liftIO $ renameFile kernel (kernel ++ "-" ++ digest) liftIO $ renameFile initramfs (initramfs ++ "-" ++ digest) -- This is like withTempDirectory from the temporary package, but without the requirement on -- MonadThrow and MonadMask. This allows logging the call to dracut like we do everything -- else without having to think about adding those constraints to quite a lot of code. withTempDirectory' :: MonadBaseControl IO m => FilePath -> String -> (FilePath -> m a) -> m a withTempDirectory' target template = liftBaseOp $ CEL.bracket (createTempDirectory target template) (\path -> removePathForcibly path `CEL.catch` (\(_ :: CEL.SomeException) -> return ())) renameDirs :: FilePath -> IO () renameDirs exportDir = do -- ostree mandates /usr/etc, and fails if /etc also exists. -- There is an empty /usr/etc owned by filesystem, so get rid of that and move /etc to /usr/etc let etcPath = exportDir </> "etc" let usrEtcPath = exportDir </> "usr" </> "etc" removePathForcibly usrEtcPath renameDirectory etcPath usrEtcPath -- usr/etc/passwd and usr/etc/group are supposed to be empty (except root and wheel) -- the real ones go in /usr/lib/{passwd,group} let usrLibPath = exportDir </> "usr" </> "lib" renameFile (usrEtcPath </> "passwd") (usrLibPath </> "passwd") renameFile (usrEtcPath </> "group") (usrLibPath </> "group") writeFile (usrEtcPath </> "passwd") "root:x:0:0:root:/root:/bin/bash\n" writeFile (usrEtcPath </> "group") "root:x:0:\nwheel:x:10:\n" -- NB: rpm-ostree also requires that /var/lib/rpm be moved to /usr/share/rpm, but we don't have any -- real RPM data to move. replaceDirs :: FilePath -> IO () replaceDirs exportDir = do -- Clear out anything that's already there. -- removeDirectory will fail if not directory exists but is not empty mapM_ (\dir -> whenM (doesPathExist dir) (removeDirectory dir)) (map (exportDir </>) ["home", "media", "mnt", "opt", "root", "srv", "tmp"]) -- And replace (plus one new one, /ostree) createSymbolicLink "var/home" (exportDir </> "home") createSymbolicLink "run/media" (exportDir </> "media") createSymbolicLink "var/mnt" (exportDir </> "mnt") createSymbolicLink "var/opt" (exportDir </> "opt") createSymbolicLink "sysroot/ostree" (exportDir </> "ostree") createSymbolicLink "var/roothome" (exportDir </> "root") createSymbolicLink "var/srv" (exportDir </> "srv") createSymbolicLink "sysroot/tmp" (exportDir </> "tmp") doSystemd :: MonadLoggerIO m => FilePath -> m () doSystemd exportDir = do let systemdDir = exportDir </> "usr" </> "etc" </> "systemd" </> "system" liftIO $ createDirectoryIfMissing True systemdDir -- Set the default target to multi-user liftIO $ createSymbolicLink "/usr/lib/systemd/system/multi-user.target" $ systemdDir </> "default.target" -- Add some services that look important liftIO $ do createDirectoryIfMissing True $ systemdDir </> "getty.target.wants" createDirectoryIfMissing True $ systemdDir </> "local-fs.target.wants" createSymbolicLink "/usr/lib/systemd/system/[email protected]" $ systemdDir </> "getty.target.wants" </> "[email protected]" createSymbolicLink "/usr/lib/systemd/system/ostree-remount.service" $ systemdDir </> "local-fs.target.wants" </> "ostree-remount.service" -- Write the commit metadata object to an opened ostree repo, given the results of calling store. This -- function also requires a commit subject and optionally a commit body. The subject and body are -- visible if you use "ostree log master". Returns the checksum of the commit. commit :: IsRepo a => a -> File -> T.Text -> Maybe T.Text -> IO T.Text commit repo repoFile subject body = unsafeCastTo RepoFile repoFile >>= \root -> do -- Get the parent, which should always be whatever "master" points to. If there is no parent -- (likely because nothing has been imported into this repo before), just return Nothing. -- ostree will know what to do. parent <- parentCommit repo "master" checksum <- repoWriteCommit repo parent (Just subject) body Nothing root noCancellable repoTransactionSetRef repo Nothing "master" (Just checksum) return checksum -- Open the named ostree repo. If the repo does not already exist, it will first be created. -- It is created in Z2 mode because that can be modified without being root. open :: FilePath -> IO Repo open fp = do path <- fileNewForPath fp repo <- repoNew path doesDirectoryExist fp >>= \case True -> repoOpen repo noCancellable >> return repo False -> repoCreate repo RepoModeArchiveZ2 noCancellable >> return repo -- Given a commit, return the parent of it or Nothing if no parent exists. parentCommit :: IsRepo a => a -> T.Text -> IO (Maybe T.Text) parentCommit repo commitSum = CEL.catch (Just <$> repoResolveRev repo commitSum False) (\(_ :: CEL.SomeException) -> return Nothing) -- Same as store, but takes a path to a directory to import storeDirectory :: IsRepo a => a -> FilePath -> IO File storeDirectory repo path = do importFile <- fileNewForPath path mtree <- mutableTreeNew repoWriteDirectoryToMtree repo importFile mtree Nothing noCancellable repoWriteMtree repo mtree noCancellable -- Wrap some repo-manipulating function in a transaction, committing it if the function succeeds. -- Returns the checksum of the commit. withTransaction :: IsRepo a => a -> (a -> IO b) -> IO b withTransaction repo fn = CEL.bracket_ (repoPrepareTransaction repo noCancellable) (repoCommitTransaction repo noCancellable) (fn repo)
atodorov/bdcs
src/BDCS/Export/Ostree.hs
lgpl-2.1
16,661
0
19
4,522
3,008
1,544
1,464
-1
-1
{-# LANGUAGE TemplateHaskell, CPP, ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for ganeti-htools. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Test.Ganeti.Utils (testUtils) where import Test.QuickCheck hiding (Result) import Test.HUnit import Data.Char (isSpace) import qualified Data.Either as Either import Data.List import Data.Maybe (listToMaybe) import qualified Data.Set as S import System.Time import qualified Text.JSON as J #ifdef VERSION_regex_pcre import Text.Regex.PCRE #endif import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Ganeti.BasicTypes import qualified Ganeti.Constants as C import qualified Ganeti.JSON as JSON import Ganeti.Utils {-# ANN module "HLint: ignore Use camelCase" #-} -- | Helper to generate a small string that doesn't contain commas. genNonCommaString :: Gen String genNonCommaString = do size <- choose (0, 20) -- arbitrary max size vectorOf size (arbitrary `suchThat` (/=) ',') -- | If the list is not just an empty element, and if the elements do -- not contain commas, then join+split should be idempotent. prop_commaJoinSplit :: Property prop_commaJoinSplit = forAll (choose (0, 20)) $ \llen -> forAll (vectorOf llen genNonCommaString `suchThat` (/=) [""]) $ \lst -> sepSplit ',' (commaJoin lst) ==? lst -- | Split and join should always be idempotent. prop_commaSplitJoin :: String -> Property prop_commaSplitJoin s = commaJoin (sepSplit ',' s) ==? s -- | Test 'findFirst' on several possible inputs. prop_findFirst :: Property prop_findFirst = forAll (genSublist [0..5 :: Int]) $ \xs -> forAll (choose (-2, 7)) $ \base -> counterexample "findFirst utility function" $ let r = findFirst base (S.fromList xs) (ss, es) = partition (< r) $ dropWhile (< base) xs -- the prefix must be a range of numbers -- and the suffix must not start with 'r' in conjoin [ and $ zipWith ((==) . (+ 1)) ss (drop 1 ss) , maybe True (> r) (listToMaybe es) ] -- | fromObjWithDefault, we test using the Maybe monad and an integer -- value. prop_fromObjWithDefault :: Integer -> String -> Bool prop_fromObjWithDefault def_value random_key = -- a missing key will be returned with the default JSON.fromObjWithDefault [] random_key def_value == Just def_value && -- a found key will be returned as is, not with default JSON.fromObjWithDefault [(random_key, J.showJSON def_value)] random_key (def_value+1) == Just def_value -- | Test that functional if' behaves like the syntactic sugar if. prop_if'if :: Bool -> Int -> Int -> Property prop_if'if cnd a b = if' cnd a b ==? if cnd then a else b -- | Test basic select functionality prop_select :: Int -- ^ Default result -> [Int] -- ^ List of False values -> [Int] -- ^ List of True values -> Property -- ^ Test result prop_select def lst1 lst2 = select def (flist ++ tlist) ==? expectedresult where expectedresult = defaultHead def lst2 flist = zip (repeat False) lst1 tlist = zip (repeat True) lst2 {-# ANN prop_select_undefd "HLint: ignore Use alternative" #-} -- | Test basic select functionality with undefined default prop_select_undefd :: [Int] -- ^ List of False values -> NonEmptyList Int -- ^ List of True values -> Property -- ^ Test result prop_select_undefd lst1 (NonEmpty lst2) = -- head is fine as NonEmpty "guarantees" a non-empty list, but not -- via types select undefined (flist ++ tlist) ==? head lst2 where flist = zip (repeat False) lst1 tlist = zip (repeat True) lst2 {-# ANN prop_select_undefv "HLint: ignore Use alternative" #-} -- | Test basic select functionality with undefined list values prop_select_undefv :: [Int] -- ^ List of False values -> NonEmptyList Int -- ^ List of True values -> Property -- ^ Test result prop_select_undefv lst1 (NonEmpty lst2) = -- head is fine as NonEmpty "guarantees" a non-empty list, but not -- via types select undefined cndlist ==? head lst2 where flist = zip (repeat False) lst1 tlist = zip (repeat True) lst2 cndlist = flist ++ tlist ++ [undefined] prop_parseUnit :: NonNegative Int -> Property prop_parseUnit (NonNegative n) = conjoin [ parseUnit (show n) ==? (Ok n::Result Int) , parseUnit (show n ++ "m") ==? (Ok n::Result Int) , parseUnit (show n ++ "M") ==? (Ok (truncate n_mb)::Result Int) , parseUnit (show n ++ "g") ==? (Ok (n*1024)::Result Int) , parseUnit (show n ++ "G") ==? (Ok (truncate n_gb)::Result Int) , parseUnit (show n ++ "t") ==? (Ok (n*1048576)::Result Int) , parseUnit (show n ++ "T") ==? (Ok (truncate n_tb)::Result Int) , counterexample "Internal error/overflow?" (n_mb >=0 && n_gb >= 0 && n_tb >= 0) , property (isBad (parseUnit (show n ++ "x")::Result Int)) ] where n_mb = (fromIntegral n::Rational) * 1000 * 1000 / 1024 / 1024 n_gb = n_mb * 1000 n_tb = n_gb * 1000 {-# ANN case_niceSort_static "HLint: ignore Use camelCase" #-} case_niceSort_static :: Assertion case_niceSort_static = do assertEqual "empty list" [] $ niceSort [] assertEqual "punctuation" [",", "."] $ niceSort [",", "."] assertEqual "decimal numbers" ["0.1", "0.2"] $ niceSort ["0.1", "0.2"] assertEqual "various numbers" ["0,099", "0.1", "0.2", "0;099"] $ niceSort ["0;099", "0,099", "0.1", "0.2"] assertEqual "simple concat" ["0000", "a0", "a1", "a2", "a20", "a99", "b00", "b10", "b70"] $ niceSort ["a0", "a1", "a99", "a20", "a2", "b10", "b70", "b00", "0000"] assertEqual "ranges" ["A", "Z", "a0-0", "a0-4", "a1-0", "a9-1", "a09-2", "a20-3", "a99-3", "a99-10", "b"] $ niceSort ["a0-0", "a1-0", "a99-10", "a20-3", "a0-4", "a99-3", "a09-2", "Z", "a9-1", "A", "b"] assertEqual "large" ["3jTwJPtrXOY22bwL2YoW", "Eegah9ei", "KOt7vn1dWXi", "KVQqLPDjcPjf8T3oyzjcOsfkb", "WvNJd91OoXvLzdEiEXa6", "Z8Ljf1Pf5eBfNg171wJR", "a07h8feON165N67PIE", "bH4Q7aCu3PUPjK3JtH", "cPRi0lM7HLnSuWA2G9", "guKJkXnkULealVC8CyF1xefym", "pqF8dkU5B1cMnyZuREaSOADYx", "uHXAyYYftCSG1o7qcCqe", "xij88brTulHYAv8IEOyU", "xpIUJeVT1Rp"] $ niceSort ["Eegah9ei", "xij88brTulHYAv8IEOyU", "3jTwJPtrXOY22bwL2YoW", "Z8Ljf1Pf5eBfNg171wJR", "WvNJd91OoXvLzdEiEXa6", "uHXAyYYftCSG1o7qcCqe", "xpIUJeVT1Rp", "KOt7vn1dWXi", "a07h8feON165N67PIE", "bH4Q7aCu3PUPjK3JtH", "cPRi0lM7HLnSuWA2G9", "KVQqLPDjcPjf8T3oyzjcOsfkb", "guKJkXnkULealVC8CyF1xefym", "pqF8dkU5B1cMnyZuREaSOADYx"] assertEqual "hostnames" ["host1.example.com", "host2.example.com", "host03.example.com", "host11.example.com", "host255.example.com"] $ niceSort ["host2.example.com", "host11.example.com", "host03.example.com", "host1.example.com", "host255.example.com"] -- | Tests single-string behaviour of 'niceSort'. prop_niceSort_single :: Property prop_niceSort_single = forAll genName $ \name -> conjoin [ counterexample "single string" $ [name] ==? niceSort [name] , counterexample "single plus empty" $ ["", name] ==? niceSort [name, ""] ] -- | Tests some generic 'niceSort' properties. Note that the last test -- must add a non-digit prefix; a digit one might change ordering. prop_niceSort_generic :: Property prop_niceSort_generic = forAll (resize 20 arbitrary) $ \names -> let n_sorted = niceSort names in conjoin [ counterexample "length" $ length names ==? length n_sorted , counterexample "same strings" $ sort names ==? sort n_sorted , counterexample "idempotence" $ n_sorted ==? niceSort n_sorted , counterexample "static prefix" $ n_sorted ==? map tail (niceSort $ map (" "++) names) ] -- | Tests that niceSorting numbers is identical to actual sorting -- them (in numeric form). prop_niceSort_numbers :: Property prop_niceSort_numbers = forAll (listOf (arbitrary::Gen (NonNegative Int))) $ \numbers -> map show (sort numbers) ==? niceSort (map show numbers) -- | Tests that 'niceSort' and 'niceSortKey' are equivalent. prop_niceSortKey_equiv :: Property prop_niceSortKey_equiv = forAll (resize 20 arbitrary) $ \names -> forAll (vectorOf (length names) (arbitrary::Gen Int)) $ \numbers -> let n_sorted = niceSort names in conjoin [ counterexample "key id" $ n_sorted ==? niceSortKey id names , counterexample "key rev" $ niceSort (map reverse names) ==? map reverse (niceSortKey reverse names) , counterexample "key snd" $ n_sorted ==? map snd (niceSortKey snd $ zip numbers names) ] -- | Tests 'rStripSpace'. prop_rStripSpace :: NonEmptyList Char -> Property prop_rStripSpace (NonEmpty str) = forAll (resize 50 $ listOf1 (arbitrary `suchThat` isSpace)) $ \whitespace -> conjoin [ counterexample "arb. string last char is not space" $ case rStripSpace str of [] -> True xs -> not . isSpace $ last xs , counterexample "whitespace suffix is stripped" $ rStripSpace str ==? rStripSpace (str ++ whitespace) , counterexample "whitespace reduced to null" $ rStripSpace whitespace ==? "" , counterexample "idempotent on empty strings" $ rStripSpace "" ==? "" ] -- | Tests that the newUUID function produces valid UUIDs. case_new_uuid :: Assertion case_new_uuid = do uuid <- newUUID assertBool "newUUID" $ isUUID uuid #ifdef VERSION_regex_pcre {-# ANN case_new_uuid_regex "HLint: ignore Use camelCase" #-} -- | Tests that the newUUID function produces valid UUIDs. case_new_uuid_regex :: Assertion case_new_uuid_regex = do uuid <- newUUID assertBool "newUUID" $ uuid =~ C.uuidRegex #endif prop_clockTimeToString :: Integer -> Integer -> Property prop_clockTimeToString ts pico = clockTimeToString (TOD ts pico) ==? show ts instance Arbitrary ClockTime where arbitrary = TOD <$> choose (946681200, 2082754800) <*> choose (0, 99999999999) -- | Verify our work-around for ghc bug #2519. Taking `diffClockTimes` form -- `System.Time`, this test fails with an exception. prop_timediffAdd :: ClockTime -> ClockTime -> ClockTime -> Property prop_timediffAdd a b c = let fwd = Ganeti.Utils.diffClockTimes a b back = Ganeti.Utils.diffClockTimes b a in addToClockTime fwd (addToClockTime back c) ==? c -- | Test normal operation for 'chompPrefix'. -- -- Any random prefix of a string must be stripped correctly, including the empty -- prefix, and the whole string. prop_chompPrefix_normal :: String -> Property prop_chompPrefix_normal str = forAll (choose (0, length str)) $ \size -> chompPrefix (take size str) str ==? (Just $ drop size str) -- | Test that 'chompPrefix' correctly allows the last char (the separator) to -- be absent if the string terminates there. prop_chompPrefix_last :: Property prop_chompPrefix_last = forAll (choose (1, 20)) $ \len -> forAll (vectorOf len arbitrary) $ \pfx -> chompPrefix pfx pfx ==? Just "" .&&. chompPrefix pfx (init pfx) ==? Just "" -- | Test that chompPrefix on the empty string always returns Nothing for -- prefixes of length 2 or more. prop_chompPrefix_empty_string :: Property prop_chompPrefix_empty_string = forAll (choose (2, 20)) $ \len -> forAll (vectorOf len arbitrary) $ \pfx -> chompPrefix pfx "" ==? Nothing -- | Test 'chompPrefix' returns Nothing when the prefix doesn't match. prop_chompPrefix_nothing :: Property prop_chompPrefix_nothing = forAll (choose (1, 20)) $ \len -> forAll (vectorOf len arbitrary) $ \pfx -> forAll (arbitrary `suchThat` (\s -> not (pfx `isPrefixOf` s) && s /= init pfx)) $ \str -> chompPrefix pfx str ==? Nothing -- | Tests 'trim'. prop_trim :: NonEmptyList Char -> Property prop_trim (NonEmpty str) = forAll (listOf1 $ elements " \t\n\r\f") $ \whitespace -> forAll (choose (0, length whitespace)) $ \n -> let (preWS, postWS) = splitAt n whitespace in conjoin [ counterexample "arb. string first and last char are not space" $ case trim str of [] -> True xs -> (not . isSpace . head) xs && (not . isSpace . last) xs , counterexample "whitespace is striped" $ trim str ==? trim (preWS ++ str ++ postWS) , counterexample "whitespace reduced to null" $ trim whitespace ==? "" , counterexample "idempotent on empty strings" $ trim "" ==? "" ] -- | Tests 'splitEithers' and 'recombineEithers'. prop_splitRecombineEithers :: [Either Int Int] -> Property prop_splitRecombineEithers es = conjoin [ counterexample "only lefts are mapped correctly" $ splitEithers (map Left lefts) ==? (reverse lefts, emptylist, falses) , counterexample "only rights are mapped correctly" $ splitEithers (map Right rights) ==? (emptylist, reverse rights, trues) , counterexample "recombination is no-op" $ recombineEithers splitleft splitright trail ==? Ok es , counterexample "fail on too long lefts" $ isBad (recombineEithers (0:splitleft) splitright trail) , counterexample "fail on too long rights" $ isBad (recombineEithers splitleft (0:splitright) trail) , counterexample "fail on too long trail" $ isBad (recombineEithers splitleft splitright (True:trail)) ] where (lefts, rights) = Either.partitionEithers es falses = map (const False) lefts trues = map (const True) rights (splitleft, splitright, trail) = splitEithers es emptylist = []::[Int] testSuite "Utils" [ 'prop_commaJoinSplit , 'prop_commaSplitJoin , 'prop_findFirst , 'prop_fromObjWithDefault , 'prop_if'if , 'prop_select , 'prop_select_undefd , 'prop_select_undefv , 'prop_parseUnit , 'case_niceSort_static , 'prop_niceSort_single , 'prop_niceSort_generic , 'prop_niceSort_numbers , 'prop_niceSortKey_equiv , 'prop_rStripSpace , 'prop_trim , 'case_new_uuid #ifdef VERSION_regex_pcre , 'case_new_uuid_regex #endif , 'prop_clockTimeToString , 'prop_timediffAdd , 'prop_chompPrefix_normal , 'prop_chompPrefix_last , 'prop_chompPrefix_empty_string , 'prop_chompPrefix_nothing , 'prop_splitRecombineEithers ]
mbakke/ganeti
test/hs/Test/Ganeti/Utils.hs
bsd-2-clause
15,928
0
21
3,600
3,583
1,926
1,657
262
2
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-2006 RnEnv contains functions which convert RdrNames into Names. -} {-# LANGUAGE CPP, MultiWayIf, NamedFieldPuns #-} module RnEnv ( newTopSrcBinder, lookupLocatedTopBndrRn, lookupTopBndrRn, lookupLocatedOccRn, lookupOccRn, lookupOccRn_maybe, lookupLocalOccRn_maybe, lookupInfoOccRn, lookupLocalOccThLvl_maybe, lookupLocalOccRn, lookupTypeOccRn, lookupKindOccRn, lookupGlobalOccRn, lookupGlobalOccRn_maybe, lookupOccRn_overloaded, lookupGlobalOccRn_overloaded, lookupExactOcc, ChildLookupResult(..), lookupSubBndrOcc_helper, combineChildLookupResult, -- Called by lookupChildrenExport HsSigCtxt(..), lookupLocalTcNames, lookupSigOccRn, lookupSigCtxtOccRn, lookupInstDeclBndr, lookupRecFieldOcc, lookupFamInstName, lookupConstructorFields, lookupGreAvailRn, -- Rebindable Syntax lookupSyntaxName, lookupSyntaxName', lookupSyntaxNames, lookupIfThenElse, -- Constructing usage information addUsedGRE, addUsedGREs, addUsedDataCons, dataTcOccs, --TODO: Move this somewhere, into utils? ) where #include "HsVersions.h" import GhcPrelude import LoadIface ( loadInterfaceForName, loadSrcInterface_maybe ) import IfaceEnv import HsSyn import RdrName import HscTypes import TcEnv import TcRnMonad import RdrHsSyn ( setRdrNameSpace ) import TysWiredIn import Name import NameSet import NameEnv import Avail import Module import ConLike import DataCon import TyCon import ErrUtils ( MsgDoc ) import PrelNames ( rOOT_MAIN ) import BasicTypes ( pprWarningTxtForMsg, TopLevelFlag(..)) import SrcLoc import Outputable import Util import Maybes import DynFlags import FastString import Control.Monad import ListSetOps ( minusList ) import qualified GHC.LanguageExtensions as LangExt import RnUnbound import RnUtils import Data.Maybe (isJust) import qualified Data.Semigroup as Semi {- ********************************************************* * * Source-code binders * * ********************************************************* Note [Signature lazy interface loading] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GHC's lazy interface loading can be a bit confusing, so this Note is an empirical description of what happens in one interesting case. When compiling a signature module against an its implementation, we do NOT load interface files associated with its names until after the type checking phase. For example: module ASig where data T f :: T -> T Suppose we compile this with -sig-of "A is ASig": module B where data T = T f T = T module A(module B) where import B During type checking, we'll load A.hi because we need to know what the RdrEnv for the module is, but we DO NOT load the interface for B.hi! It's wholly unnecessary: our local definition 'data T' in ASig is all the information we need to finish type checking. This is contrast to type checking of ordinary Haskell files, in which we would not have the local definition "data T" and would need to consult B.hi immediately. (Also, this situation never occurs for hs-boot files, since you're not allowed to reexport from another module.) After type checking, we then check that the types we provided are consistent with the backing implementation (in checkHiBootOrHsigIface). At this point, B.hi is loaded, because we need something to compare against. I discovered this behavior when trying to figure out why type class instances for Data.Map weren't in the EPS when I was type checking a test very much like ASig (sigof02dm): the associated interface hadn't been loaded yet! (The larger issue is a moot point, since an instance declared in a signature can never be a duplicate.) This behavior might change in the future. Consider this alternate module B: module B where {-# DEPRECATED T, f "Don't use" #-} data T = T f T = T One might conceivably want to report deprecation warnings when compiling ASig with -sig-of B, in which case we need to look at B.hi to find the deprecation warnings during renaming. At the moment, you don't get any warning until you use the identifier further downstream. This would require adjusting addUsedGRE so that during signature compilation, we do not report deprecation warnings for LocalDef. See also Note [Handling of deprecations] -} newTopSrcBinder :: Located RdrName -> RnM Name newTopSrcBinder (L loc rdr_name) | Just name <- isExact_maybe rdr_name = -- This is here to catch -- (a) Exact-name binders created by Template Haskell -- (b) The PrelBase defn of (say) [] and similar, for which -- the parser reads the special syntax and returns an Exact RdrName -- We are at a binding site for the name, so check first that it -- the current module is the correct one; otherwise GHC can get -- very confused indeed. This test rejects code like -- data T = (,) Int Int -- unless we are in GHC.Tup if isExternalName name then do { this_mod <- getModule ; unless (this_mod == nameModule name) (addErrAt loc (badOrigBinding rdr_name)) ; return name } else -- See Note [Binders in Template Haskell] in Convert.hs do { this_mod <- getModule ; externaliseName this_mod name } | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name = do { this_mod <- getModule ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN) (addErrAt loc (badOrigBinding rdr_name)) -- When reading External Core we get Orig names as binders, -- but they should agree with the module gotten from the monad -- -- We can get built-in syntax showing up here too, sadly. If you type -- data T = (,,,) -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon -- uses setRdrNameSpace to make it into a data constructors. At that point -- the nice Exact name for the TyCon gets swizzled to an Orig name. -- Hence the badOrigBinding error message. -- -- Except for the ":Main.main = ..." definition inserted into -- the Main module; ugh! -- Because of this latter case, we call newGlobalBinder with a module from -- the RdrName, not from the environment. In principle, it'd be fine to -- have an arbitrary mixture of external core definitions in a single module, -- (apart from module-initialisation issues, perhaps). ; newGlobalBinder rdr_mod rdr_occ loc } | otherwise = do { when (isQual rdr_name) (addErrAt loc (badQualBndrErr rdr_name)) -- Binders should not be qualified; if they are, and with a different -- module name, we get a confusing "M.T is not in scope" error later ; stage <- getStage ; if isBrackStage stage then -- We are inside a TH bracket, so make an *Internal* name -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames do { uniq <- newUnique ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) } else do { this_mod <- getModule ; traceRn "newTopSrcBinder" (ppr this_mod $$ ppr rdr_name $$ ppr loc) ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc } } {- ********************************************************* * * Source code occurrences * * ********************************************************* Looking up a name in the RnEnv. Note [Type and class operator definitions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We want to reject all of these unless we have -XTypeOperators (Trac #3265) data a :*: b = ... class a :*: b where ... data (:*:) a b = .... class (:*:) a b where ... The latter two mean that we are not just looking for a *syntactically-infix* declaration, but one that uses an operator OccName. We use OccName.isSymOcc to detect that case, which isn't terribly efficient, but there seems to be no better way. -} -- Can be made to not be exposed -- Only used unwrapped in rnAnnProvenance lookupTopBndrRn :: RdrName -> RnM Name lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n case nopt of Just n' -> return n' Nothing -> do traceRn "lookupTopBndrRn fail" (ppr n) unboundName WL_LocalTop n lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name) lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name) -- Look up a top-level source-code binder. We may be looking up an unqualified 'f', -- and there may be several imported 'f's too, which must not confuse us. -- For example, this is OK: -- import Foo( f ) -- infix 9 f -- The 'f' here does not need to be qualified -- f x = x -- Nor here, of course -- So we have to filter out the non-local ones. -- -- A separate function (importsFromLocalDecls) reports duplicate top level -- decls, so here it's safe just to choose an arbitrary one. -- -- There should never be a qualified name in a binding position in Haskell, -- but there can be if we have read in an external-Core file. -- The Haskell parser checks for the illegal qualified name in Haskell -- source files, so we don't need to do so here. lookupTopBndrRn_maybe rdr_name = lookupExactOrOrig rdr_name Just $ do { -- Check for operators in type or class declarations -- See Note [Type and class operator definitions] let occ = rdrNameOcc rdr_name ; when (isTcOcc occ && isSymOcc occ) (do { op_ok <- xoptM LangExt.TypeOperators ; unless op_ok (addErr (opDeclErr rdr_name)) }) ; env <- getGlobalRdrEnv ; case filter isLocalGRE (lookupGRE_RdrName rdr_name env) of [gre] -> return (Just (gre_name gre)) _ -> return Nothing -- Ambiguous (can't happen) or unbound } ----------------------------------------------- -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames]. -- This adds an error if the name cannot be found. lookupExactOcc :: Name -> RnM Name lookupExactOcc name = do { result <- lookupExactOcc_either name ; case result of Left err -> do { addErr err ; return name } Right name' -> return name' } -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames]. -- This never adds an error, but it may return one. lookupExactOcc_either :: Name -> RnM (Either MsgDoc Name) -- See Note [Looking up Exact RdrNames] lookupExactOcc_either name | Just thing <- wiredInNameTyThing_maybe name , Just tycon <- case thing of ATyCon tc -> Just tc AConLike (RealDataCon dc) -> Just (dataConTyCon dc) _ -> Nothing , isTupleTyCon tycon = do { checkTupSize (tyConArity tycon) ; return (Right name) } | isExternalName name = return (Right name) | otherwise = do { env <- getGlobalRdrEnv ; let -- See Note [Splicing Exact names] main_occ = nameOccName name demoted_occs = case demoteOccName main_occ of Just occ -> [occ] Nothing -> [] gres = [ gre | occ <- main_occ : demoted_occs , gre <- lookupGlobalRdrEnv env occ , gre_name gre == name ] ; case gres of [gre] -> return (Right (gre_name gre)) [] -> -- See Note [Splicing Exact names] do { lcl_env <- getLocalRdrEnv ; if name `inLocalRdrEnvScope` lcl_env then return (Right name) else do { th_topnames_var <- fmap tcg_th_topnames getGblEnv ; th_topnames <- readTcRef th_topnames_var ; if name `elemNameSet` th_topnames then return (Right name) else return (Left exact_nm_err) } } gres -> return (Left (sameNameErr gres)) -- Ugh! See Note [Template Haskell ambiguity] } where exact_nm_err = hang (text "The exact Name" <+> quotes (ppr name) <+> ptext (sLit "is not in scope")) 2 (vcat [ text "Probable cause: you used a unique Template Haskell name (NameU), " , text "perhaps via newName, but did not bind it" , text "If that's it, then -ddump-splices might be useful" ]) sameNameErr :: [GlobalRdrElt] -> MsgDoc sameNameErr [] = panic "addSameNameErr: empty list" sameNameErr gres@(_ : _) = hang (text "Same exact name in multiple name-spaces:") 2 (vcat (map pp_one sorted_names) $$ th_hint) where sorted_names = sortWith nameSrcLoc (map gre_name gres) pp_one name = hang (pprNameSpace (occNameSpace (getOccName name)) <+> quotes (ppr name) <> comma) 2 (text "declared at:" <+> ppr (nameSrcLoc name)) th_hint = vcat [ text "Probable cause: you bound a unique Template Haskell name (NameU)," , text "perhaps via newName, in different name-spaces." , text "If that's it, then -ddump-splices might be useful" ] ----------------------------------------------- lookupInstDeclBndr :: Name -> SDoc -> RdrName -> RnM Name -- This is called on the method name on the left-hand side of an -- instance declaration binding. eg. instance Functor T where -- fmap = ... -- ^^^^ called on this -- Regardless of how many unqualified fmaps are in scope, we want -- the one that comes from the Functor class. -- -- Furthermore, note that we take no account of whether the -- name is only in scope qualified. I.e. even if method op is -- in scope as M.op, we still allow plain 'op' on the LHS of -- an instance decl -- -- The "what" parameter says "method" or "associated type", -- depending on what we are looking up lookupInstDeclBndr cls what rdr = do { when (isQual rdr) (addErr (badQualBndrErr rdr)) -- In an instance decl you aren't allowed -- to use a qualified name for the method -- (Although it'd make perfect sense.) ; mb_name <- lookupSubBndrOcc False -- False => we don't give deprecated -- warnings when a deprecated class -- method is defined. We only warn -- when it's used cls doc rdr ; case mb_name of Left err -> do { addErr err; return (mkUnboundNameRdr rdr) } Right nm -> return nm } where doc = what <+> text "of class" <+> quotes (ppr cls) ----------------------------------------------- lookupFamInstName :: Maybe Name -> Located RdrName -> RnM (Located Name) -- Used for TyData and TySynonym family instances only, -- See Note [Family instance binders] lookupFamInstName (Just cls) tc_rdr -- Associated type; c.f RnBinds.rnMethodBind = wrapLocM (lookupInstDeclBndr cls (text "associated type")) tc_rdr lookupFamInstName Nothing tc_rdr -- Family instance; tc_rdr is an *occurrence* = lookupLocatedOccRn tc_rdr ----------------------------------------------- lookupConstructorFields :: Name -> RnM [FieldLabel] -- Look up the fields of a given constructor -- * For constructors from this module, use the record field env, -- which is itself gathered from the (as yet un-typechecked) -- data type decls -- -- * For constructors from imported modules, use the *type* environment -- since imported modles are already compiled, the info is conveniently -- right there lookupConstructorFields con_name = do { this_mod <- getModule ; if nameIsLocalOrFrom this_mod con_name then do { field_env <- getRecFieldEnv ; traceTc "lookupCF" (ppr con_name $$ ppr (lookupNameEnv field_env con_name) $$ ppr field_env) ; return (lookupNameEnv field_env con_name `orElse` []) } else do { con <- tcLookupConLike con_name ; traceTc "lookupCF 2" (ppr con) ; return (conLikeFieldLabels con) } } -- In CPS style as `RnM r` is monadic lookupExactOrOrig :: RdrName -> (Name -> r) -> RnM r -> RnM r lookupExactOrOrig rdr_name res k | Just n <- isExact_maybe rdr_name -- This happens in derived code = res <$> lookupExactOcc n | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name = res <$> lookupOrig rdr_mod rdr_occ | otherwise = k ----------------------------------------------- -- Used for record construction and pattern matching -- When the -XDisambiguateRecordFields flag is on, take account of the -- constructor name to disambiguate which field to use; it's just the -- same as for instance decls -- -- NB: Consider this: -- module Foo where { data R = R { fld :: Int } } -- module Odd where { import Foo; fld x = x { fld = 3 } } -- Arguably this should work, because the reference to 'fld' is -- unambiguous because there is only one field id 'fld' in scope. -- But currently it's rejected. lookupRecFieldOcc :: Maybe Name -- Nothing => just look it up as usual -- Just tycon => use tycon to disambiguate -> SDoc -> RdrName -> RnM Name lookupRecFieldOcc parent doc rdr_name | Just tc_name <- parent = do { mb_name <- lookupSubBndrOcc True tc_name doc rdr_name ; case mb_name of Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) } Right n -> return n } | otherwise -- This use of Global is right as we are looking up a selector which -- can only be defined at the top level. = lookupGlobalOccRn rdr_name -- | Used in export lists to lookup the children. lookupSubBndrOcc_helper :: Bool -> Bool -> Name -> RdrName -> RnM ChildLookupResult lookupSubBndrOcc_helper must_have_parent warn_if_deprec parent rdr_name | isUnboundName parent -- Avoid an error cascade = return (FoundName NoParent (mkUnboundNameRdr rdr_name)) | otherwise = do gre_env <- getGlobalRdrEnv let original_gres = lookupGlobalRdrEnv gre_env (rdrNameOcc rdr_name) -- Disambiguate the lookup based on the parent information. -- The remaining GREs are things that we *could* export here, note that -- this includes things which have `NoParent`. Those are sorted in -- `checkPatSynParent`. traceRn "parent" (ppr parent) traceRn "lookupExportChild original_gres:" (ppr original_gres) traceRn "lookupExportChild picked_gres:" (ppr $ picked_gres original_gres) case picked_gres original_gres of NoOccurrence -> noMatchingParentErr original_gres UniqueOccurrence g -> if must_have_parent then noMatchingParentErr original_gres else checkFld g DisambiguatedOccurrence g -> checkFld g AmbiguousOccurrence gres -> mkNameClashErr gres where -- Convert into FieldLabel if necessary checkFld :: GlobalRdrElt -> RnM ChildLookupResult checkFld g@GRE{gre_name, gre_par} = do addUsedGRE warn_if_deprec g return $ case gre_par of FldParent _ mfs -> FoundFL (fldParentToFieldLabel gre_name mfs) _ -> FoundName gre_par gre_name fldParentToFieldLabel :: Name -> Maybe FastString -> FieldLabel fldParentToFieldLabel name mfs = case mfs of Nothing -> let fs = occNameFS (nameOccName name) in FieldLabel fs False name Just fs -> FieldLabel fs True name -- Called when we find no matching GREs after disambiguation but -- there are three situations where this happens. -- 1. There were none to begin with. -- 2. None of the matching ones were the parent but -- a. They were from an overloaded record field so we can report -- a better error -- b. The original lookup was actually ambiguous. -- For example, the case where overloading is off and two -- record fields are in scope from different record -- constructors, neither of which is the parent. noMatchingParentErr :: [GlobalRdrElt] -> RnM ChildLookupResult noMatchingParentErr original_gres = do overload_ok <- xoptM LangExt.DuplicateRecordFields case original_gres of [] -> return NameNotFound [g] -> return $ IncorrectParent parent (gre_name g) (ppr $ gre_name g) [p | Just p <- [getParent g]] gss@(g:_:_) -> if all isRecFldGRE gss && overload_ok then return $ IncorrectParent parent (gre_name g) (ppr $ expectJust "noMatchingParentErr" (greLabel g)) [p | x <- gss, Just p <- [getParent x]] else mkNameClashErr gss mkNameClashErr :: [GlobalRdrElt] -> RnM ChildLookupResult mkNameClashErr gres = do addNameClashErrRn rdr_name gres return (FoundName (gre_par (head gres)) (gre_name (head gres))) getParent :: GlobalRdrElt -> Maybe Name getParent (GRE { gre_par = p } ) = case p of ParentIs cur_parent -> Just cur_parent FldParent { par_is = cur_parent } -> Just cur_parent NoParent -> Nothing picked_gres :: [GlobalRdrElt] -> DisambigInfo picked_gres gres | isUnqual rdr_name = mconcat (map right_parent gres) | otherwise = mconcat (map right_parent (pickGREs rdr_name gres)) right_parent :: GlobalRdrElt -> DisambigInfo right_parent p | Just cur_parent <- getParent p = if parent == cur_parent then DisambiguatedOccurrence p else NoOccurrence | otherwise = UniqueOccurrence p -- This domain specific datatype is used to record why we decided it was -- possible that a GRE could be exported with a parent. data DisambigInfo = NoOccurrence -- The GRE could never be exported. It has the wrong parent. | UniqueOccurrence GlobalRdrElt -- The GRE has no parent. It could be a pattern synonym. | DisambiguatedOccurrence GlobalRdrElt -- The parent of the GRE is the correct parent | AmbiguousOccurrence [GlobalRdrElt] -- For example, two normal identifiers with the same name are in -- scope. They will both be resolved to "UniqueOccurrence" and the -- monoid will combine them to this failing case. instance Outputable DisambigInfo where ppr NoOccurrence = text "NoOccurence" ppr (UniqueOccurrence gre) = text "UniqueOccurrence:" <+> ppr gre ppr (DisambiguatedOccurrence gre) = text "DiambiguatedOccurrence:" <+> ppr gre ppr (AmbiguousOccurrence gres) = text "Ambiguous:" <+> ppr gres instance Semi.Semigroup DisambigInfo where -- This is the key line: We prefer disambiguated occurrences to other -- names. _ <> DisambiguatedOccurrence g' = DisambiguatedOccurrence g' DisambiguatedOccurrence g' <> _ = DisambiguatedOccurrence g' NoOccurrence <> m = m m <> NoOccurrence = m UniqueOccurrence g <> UniqueOccurrence g' = AmbiguousOccurrence [g, g'] UniqueOccurrence g <> AmbiguousOccurrence gs = AmbiguousOccurrence (g:gs) AmbiguousOccurrence gs <> UniqueOccurrence g' = AmbiguousOccurrence (g':gs) AmbiguousOccurrence gs <> AmbiguousOccurrence gs' = AmbiguousOccurrence (gs ++ gs') instance Monoid DisambigInfo where mempty = NoOccurrence mappend = (Semi.<>) -- Lookup SubBndrOcc can never be ambiguous -- -- Records the result of looking up a child. data ChildLookupResult = NameNotFound -- We couldn't find a suitable name | IncorrectParent Name -- Parent Name -- Name of thing we were looking for SDoc -- How to print the name [Name] -- List of possible parents | FoundName Parent Name -- We resolved to a normal name | FoundFL FieldLabel -- We resolved to a FL -- | Specialised version of msum for RnM ChildLookupResult combineChildLookupResult :: [RnM ChildLookupResult] -> RnM ChildLookupResult combineChildLookupResult [] = return NameNotFound combineChildLookupResult (x:xs) = do res <- x case res of NameNotFound -> combineChildLookupResult xs _ -> return res instance Outputable ChildLookupResult where ppr NameNotFound = text "NameNotFound" ppr (FoundName p n) = text "Found:" <+> ppr p <+> ppr n ppr (FoundFL fls) = text "FoundFL:" <+> ppr fls ppr (IncorrectParent p n td ns) = text "IncorrectParent" <+> hsep [ppr p, ppr n, td, ppr ns] lookupSubBndrOcc :: Bool -> Name -- Parent -> SDoc -> RdrName -> RnM (Either MsgDoc Name) -- Find all the things the rdr-name maps to -- and pick the one with the right parent namep lookupSubBndrOcc warn_if_deprec the_parent doc rdr_name = do res <- lookupExactOrOrig rdr_name (FoundName NoParent) $ -- This happens for built-in classes, see mod052 for example lookupSubBndrOcc_helper True warn_if_deprec the_parent rdr_name case res of NameNotFound -> return (Left (unknownSubordinateErr doc rdr_name)) FoundName _p n -> return (Right n) FoundFL fl -> return (Right (flSelector fl)) IncorrectParent {} -> return $ Left (unknownSubordinateErr doc rdr_name) {- Note [Family instance binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data family F a data instance F T = X1 | X2 The 'data instance' decl has an *occurrence* of F (and T), and *binds* X1 and X2. (This is unlike a normal data type declaration which would bind F too.) So we want an AvailTC F [X1,X2]. Now consider a similar pair: class C a where data G a instance C S where data G S = Y1 | Y2 The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G. But there is a small complication: in an instance decl, we don't use qualified names on the LHS; instead we use the class to disambiguate. Thus: module M where import Blib( G ) class C a where data G a instance C S where data G S = Y1 | Y2 Even though there are two G's in scope (M.G and Blib.G), the occurrence of 'G' in the 'instance C S' decl is unambiguous, because C has only one associated type called G. This is exactly what happens for methods, and it is only consistent to do the same thing for types. That's the role of the function lookupTcdName; the (Maybe Name) give the class of the encloseing instance decl, if any. Note [Looking up Exact RdrNames] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Exact RdrNames are generated by Template Haskell. See Note [Binders in Template Haskell] in Convert. For data types and classes have Exact system Names in the binding positions for constructors, TyCons etc. For example [d| data T = MkT Int |] when we splice in and Convert to HsSyn RdrName, we'll get data (Exact (system Name "T")) = (Exact (system Name "MkT")) ... These System names are generated by Convert.thRdrName But, constructors and the like need External Names, not System Names! So we do the following * In RnEnv.newTopSrcBinder we spot Exact RdrNames that wrap a non-External Name, and make an External name for it. This is the name that goes in the GlobalRdrEnv * When looking up an occurrence of an Exact name, done in RnEnv.lookupExactOcc, we find the Name with the right unique in the GlobalRdrEnv, and use the one from the envt -- it will be an External Name in the case of the data type/constructor above. * Exact names are also use for purely local binders generated by TH, such as \x_33. x_33 Both binder and occurrence are Exact RdrNames. The occurrence gets looked up in the LocalRdrEnv by RnEnv.lookupOccRn, and misses, because lookupLocalRdrEnv always returns Nothing for an Exact Name. Now we fall through to lookupExactOcc, which will find the Name is not in the GlobalRdrEnv, so we just use the Exact supplied Name. Note [Splicing Exact names] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider the splice $(do { x <- newName "x"; return (VarE x) }) This will generate a (HsExpr RdrName) term that mentions the Exact RdrName "x_56" (or whatever), but does not bind it. So when looking such Exact names we want to check that it's in scope, otherwise the type checker will get confused. To do this we need to keep track of all the Names in scope, and the LocalRdrEnv does just that; we consult it with RdrName.inLocalRdrEnvScope. There is another wrinkle. With TH and -XDataKinds, consider $( [d| data Nat = Zero data T = MkT (Proxy 'Zero) |] ) After splicing, but before renaming we get this: data Nat_77{tc} = Zero_78{d} data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc}) |] ) The occurrence of 'Zero in the data type for T has the right unique, but it has a TcClsName name-space in its OccName. (This is set by the ctxt_ns argument of Convert.thRdrName.) When we check that is in scope in the GlobalRdrEnv, we need to look up the DataName namespace too. (An alternative would be to make the GlobalRdrEnv also have a Name -> GRE mapping.) Note [Template Haskell ambiguity] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The GlobalRdrEnv invariant says that if occ -> [gre1, ..., gren] then the gres have distinct Names (INVARIANT 1 of GlobalRdrEnv). This is guaranteed by extendGlobalRdrEnvRn (the dups check in add_gre). So how can we get multiple gres in lookupExactOcc_maybe? Because in TH we might use the same TH NameU in two different name spaces. eg (Trac #7241): $(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]]) Here we generate a type constructor and data constructor with the same unique, but different name spaces. It'd be nicer to rule this out in extendGlobalRdrEnvRn, but that would mean looking up the OccName in every name-space, just in case, and that seems a bit brutal. So it's just done here on lookup. But we might need to revisit that choice. Note [Usage for sub-bndrs] ~~~~~~~~~~~~~~~~~~~~~~~~~~ If you have this import qualified M( C( f ) ) instance M.C T where f x = x then is the qualified import M.f used? Obviously yes. But the RdrName used in the instance decl is unqualified. In effect, we fill in the qualification by looking for f's whose class is M.C But when adding to the UsedRdrNames we must make that qualification explicit (saying "used M.f"), otherwise we get "Redundant import of M.f". So we make up a suitable (fake) RdrName. But be careful import qualified M import M( C(f) ) instance C T where f x = x Here we want to record a use of 'f', not of 'M.f', otherwise we'll miss the fact that the qualified import is redundant. -------------------------------------------------- -- Occurrences -------------------------------------------------- -} lookupLocatedOccRn :: Located RdrName -> RnM (Located Name) lookupLocatedOccRn = wrapLocM lookupOccRn lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name) -- Just look in the local environment lookupLocalOccRn_maybe rdr_name = do { local_env <- getLocalRdrEnv ; return (lookupLocalRdrEnv local_env rdr_name) } lookupLocalOccThLvl_maybe :: Name -> RnM (Maybe (TopLevelFlag, ThLevel)) -- Just look in the local environment lookupLocalOccThLvl_maybe name = do { lcl_env <- getLclEnv ; return (lookupNameEnv (tcl_th_bndrs lcl_env) name) } -- lookupOccRn looks up an occurrence of a RdrName lookupOccRn :: RdrName -> RnM Name lookupOccRn rdr_name = do { mb_name <- lookupOccRn_maybe rdr_name ; case mb_name of Just name -> return name Nothing -> reportUnboundName rdr_name } -- Only used in one place, to rename pattern synonym binders. -- See Note [Renaming pattern synonym variables] in RnBinds lookupLocalOccRn :: RdrName -> RnM Name lookupLocalOccRn rdr_name = do { mb_name <- lookupLocalOccRn_maybe rdr_name ; case mb_name of Just name -> return name Nothing -> unboundName WL_LocalOnly rdr_name } lookupKindOccRn :: RdrName -> RnM Name -- Looking up a name occurring in a kind lookupKindOccRn rdr_name | isVarOcc (rdrNameOcc rdr_name) -- See Note [Promoted variables in types] = badVarInType rdr_name | otherwise = do { typeintype <- xoptM LangExt.TypeInType ; if | typeintype -> lookupTypeOccRn rdr_name -- With -XNoTypeInType, treat any usage of * in kinds as in scope -- this is a dirty hack, but then again so was the old * kind. | isStar rdr_name -> return starKindTyConName | isUniStar rdr_name -> return unicodeStarKindTyConName | otherwise -> lookupOccRn rdr_name } -- lookupPromotedOccRn looks up an optionally promoted RdrName. lookupTypeOccRn :: RdrName -> RnM Name -- see Note [Demotion] lookupTypeOccRn rdr_name | isVarOcc (rdrNameOcc rdr_name) -- See Note [Promoted variables in types] = badVarInType rdr_name | otherwise = do { mb_name <- lookupOccRn_maybe rdr_name ; case mb_name of { Just name -> return name ; Nothing -> do { dflags <- getDynFlags ; lookup_demoted rdr_name dflags } } } lookup_demoted :: RdrName -> DynFlags -> RnM Name lookup_demoted rdr_name dflags | Just demoted_rdr <- demoteRdrName rdr_name -- Maybe it's the name of a *data* constructor = do { data_kinds <- xoptM LangExt.DataKinds ; if data_kinds then do { mb_demoted_name <- lookupOccRn_maybe demoted_rdr ; case mb_demoted_name of Nothing -> unboundNameX WL_Any rdr_name star_info Just demoted_name -> do { whenWOptM Opt_WarnUntickedPromotedConstructors $ addWarn (Reason Opt_WarnUntickedPromotedConstructors) (untickedPromConstrWarn demoted_name) ; return demoted_name } } else do { -- We need to check if a data constructor of this name is -- in scope to give good error messages. However, we do -- not want to give an additional error if the data -- constructor happens to be out of scope! See #13947. mb_demoted_name <- discardErrs $ lookupOccRn_maybe demoted_rdr ; let suggestion | isJust mb_demoted_name = suggest_dk | otherwise = star_info ; unboundNameX WL_Any rdr_name suggestion } } | otherwise = reportUnboundName rdr_name where suggest_dk = text "A data constructor of that name is in scope; did you mean DataKinds?" untickedPromConstrWarn name = text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot $$ hsep [ text "Use" , quotes (char '\'' <> ppr name) , text "instead of" , quotes (ppr name) <> dot ] star_info | isStar rdr_name || isUniStar rdr_name = if xopt LangExt.TypeInType dflags then text "NB: With TypeInType, you must import" <+> ppr rdr_name <+> text "from Data.Kind" else empty | otherwise = empty badVarInType :: RdrName -> RnM Name badVarInType rdr_name = do { addErr (text "Illegal promoted term variable in a type:" <+> ppr rdr_name) ; return (mkUnboundNameRdr rdr_name) } {- Note [Promoted variables in types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this (Trac #12686): x = True data Bad = Bad 'x The parser treats the quote in 'x as saying "use the term namespace", so we'll get (Bad x{v}), with 'x' in the VarName namespace. If we don't test for this, the renamer will happily rename it to the x bound at top level, and then the typecheck falls over because it doesn't have 'x' in scope when kind-checking. Note [Demotion] ~~~~~~~~~~~~~~~ When the user writes: data Nat = Zero | Succ Nat foo :: f Zero -> Int 'Zero' in the type signature of 'foo' is parsed as: HsTyVar ("Zero", TcClsName) When the renamer hits this occurrence of 'Zero' it's going to realise that it's not in scope. But because it is renaming a type, it knows that 'Zero' might be a promoted data constructor, so it will demote its namespace to DataName and do a second lookup. The final result (after the renamer) will be: HsTyVar ("Zero", DataName) -} lookupOccRnX_maybe :: (RdrName -> RnM (Maybe r)) -> (Name -> r) -> RdrName -> RnM (Maybe r) lookupOccRnX_maybe globalLookup wrapper rdr_name = runMaybeT . msum . map MaybeT $ [ fmap wrapper <$> lookupLocalOccRn_maybe rdr_name , globalLookup rdr_name ] lookupOccRn_maybe :: RdrName -> RnM (Maybe Name) lookupOccRn_maybe = lookupOccRnX_maybe lookupGlobalOccRn_maybe id lookupOccRn_overloaded :: Bool -> RdrName -> RnM (Maybe (Either Name [Name])) lookupOccRn_overloaded overload_ok = lookupOccRnX_maybe global_lookup Left where global_lookup :: RdrName -> RnM (Maybe (Either Name [Name])) global_lookup n = runMaybeT . msum . map MaybeT $ [ lookupGlobalOccRn_overloaded overload_ok n , fmap Left . listToMaybe <$> lookupQualifiedNameGHCi n ] lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name) -- Looks up a RdrName occurrence in the top-level -- environment, including using lookupQualifiedNameGHCi -- for the GHCi case -- No filter function; does not report an error on failure -- Uses addUsedRdrName to record use and deprecations lookupGlobalOccRn_maybe rdr_name = lookupExactOrOrig rdr_name Just $ runMaybeT . msum . map MaybeT $ [ fmap gre_name <$> lookupGreRn_maybe rdr_name , listToMaybe <$> lookupQualifiedNameGHCi rdr_name ] -- This test is not expensive, -- and only happens for failed lookups lookupGlobalOccRn :: RdrName -> RnM Name -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global -- environment. Adds an error message if the RdrName is not in scope. -- You usually want to use "lookupOccRn" which also looks in the local -- environment. lookupGlobalOccRn rdr_name = do { mb_name <- lookupGlobalOccRn_maybe rdr_name ; case mb_name of Just n -> return n Nothing -> do { traceRn "lookupGlobalOccRn" (ppr rdr_name) ; unboundName WL_Global rdr_name } } lookupInfoOccRn :: RdrName -> RnM [Name] -- lookupInfoOccRn is intended for use in GHCi's ":info" command -- It finds all the GREs that RdrName could mean, not complaining -- about ambiguity, but rather returning them all -- C.f. Trac #9881 lookupInfoOccRn rdr_name = lookupExactOrOrig rdr_name (:[]) $ do { rdr_env <- getGlobalRdrEnv ; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env) ; qual_ns <- lookupQualifiedNameGHCi rdr_name ; return (ns ++ (qual_ns `minusList` ns)) } -- | Like 'lookupOccRn_maybe', but with a more informative result if -- the 'RdrName' happens to be a record selector: -- -- * Nothing -> name not in scope (no error reported) -- * Just (Left x) -> name uniquely refers to x, -- or there is a name clash (reported) -- * Just (Right xs) -> name refers to one or more record selectors; -- if overload_ok was False, this list will be -- a singleton. lookupGlobalOccRn_overloaded :: Bool -> RdrName -> RnM (Maybe (Either Name [Name])) lookupGlobalOccRn_overloaded overload_ok rdr_name = lookupExactOrOrig rdr_name (Just . Left) $ do { res <- lookupGreRn_helper rdr_name ; case res of GreNotFound -> return Nothing OneNameMatch gre -> do let wrapper = if isRecFldGRE gre then Right . (:[]) else Left return $ Just (wrapper (gre_name gre)) MultipleNames gres | all isRecFldGRE gres && overload_ok -> -- Don't record usage for ambiguous selectors -- until we know which is meant return $ Just (Right (map gre_name gres)) MultipleNames gres -> do addNameClashErrRn rdr_name gres return (Just (Left (gre_name (head gres)))) } -------------------------------------------------- -- Lookup in the Global RdrEnv of the module -------------------------------------------------- data GreLookupResult = GreNotFound | OneNameMatch GlobalRdrElt | MultipleNames [GlobalRdrElt] lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt) -- Look up the RdrName in the GlobalRdrEnv -- Exactly one binding: records it as "used", return (Just gre) -- No bindings: return Nothing -- Many bindings: report "ambiguous", return an arbitrary (Just gre) -- Uses addUsedRdrName to record use and deprecations lookupGreRn_maybe rdr_name = do res <- lookupGreRn_helper rdr_name case res of OneNameMatch gre -> return $ Just gre MultipleNames gres -> do traceRn "lookupGreRn_maybe:NameClash" (ppr gres) addNameClashErrRn rdr_name gres return $ Just (head gres) GreNotFound -> return Nothing {- Note [ Unbound vs Ambiguous Names ] lookupGreRn_maybe deals with failures in two different ways. If a name is unbound then we return a `Nothing` but if the name is ambiguous then we raise an error and return a dummy name. The reason for this is that when we call `lookupGreRn_maybe` we are speculatively looking for whatever we are looking up. If we don't find it, then we might have been looking for the wrong thing and can keep trying. On the other hand, if we find a clash then there is no way to recover as we found the thing we were looking for but can no longer resolve which the correct one is. One example of this is in `lookupTypeOccRn` which first looks in the type constructor namespace before looking in the data constructor namespace to deal with `DataKinds`. There is however, as always, one exception to this scheme. If we find an ambiguous occurence of a record selector and DuplicateRecordFields is enabled then we defer the selection until the typechecker. -} -- Internal Function lookupGreRn_helper :: RdrName -> RnM GreLookupResult lookupGreRn_helper rdr_name = do { env <- getGlobalRdrEnv ; case lookupGRE_RdrName rdr_name env of [] -> return GreNotFound [gre] -> do { addUsedGRE True gre ; return (OneNameMatch gre) } gres -> return (MultipleNames gres) } lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo) -- Used in export lists -- If not found or ambiguous, add error message, and fake with UnboundName -- Uses addUsedRdrName to record use and deprecations lookupGreAvailRn rdr_name = do mb_gre <- lookupGreRn_helper rdr_name case mb_gre of GreNotFound -> do traceRn "lookupGreAvailRn" (ppr rdr_name) name <- unboundName WL_Global rdr_name return (name, avail name) MultipleNames gres -> do addNameClashErrRn rdr_name gres let unbound_name = mkUnboundNameRdr rdr_name return (unbound_name, avail unbound_name) -- Returning an unbound name here prevents an error -- cascade OneNameMatch gre -> return (gre_name gre, availFromGRE gre) {- ********************************************************* * * Deprecations * * ********************************************************* Note [Handling of deprecations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * We report deprecations at each *occurrence* of the deprecated thing (see Trac #5867) * We do not report deprecations for locally-defined names. For a start, we may be exporting a deprecated thing. Also we may use a deprecated thing in the defn of another deprecated things. We may even use a deprecated thing in the defn of a non-deprecated thing, when changing a module's interface. * addUsedGREs: we do not report deprecations for sub-binders: - the ".." completion for records - the ".." in an export item 'T(..)' - the things exported by a module export 'module M' -} addUsedDataCons :: GlobalRdrEnv -> TyCon -> RnM () -- Remember use of in-scope data constructors (Trac #7969) addUsedDataCons rdr_env tycon = addUsedGREs [ gre | dc <- tyConDataCons tycon , Just gre <- [lookupGRE_Name rdr_env (dataConName dc)] ] addUsedGRE :: Bool -> GlobalRdrElt -> RnM () -- Called for both local and imported things -- Add usage *and* warn if deprecated addUsedGRE warn_if_deprec gre = do { when warn_if_deprec (warnIfDeprecated gre) ; unless (isLocalGRE gre) $ do { env <- getGblEnv ; traceRn "addUsedGRE" (ppr gre) ; updMutVar (tcg_used_gres env) (gre :) } } addUsedGREs :: [GlobalRdrElt] -> RnM () -- Record uses of any *imported* GREs -- Used for recording used sub-bndrs -- NB: no call to warnIfDeprecated; see Note [Handling of deprecations] addUsedGREs gres | null imp_gres = return () | otherwise = do { env <- getGblEnv ; traceRn "addUsedGREs" (ppr imp_gres) ; updMutVar (tcg_used_gres env) (imp_gres ++) } where imp_gres = filterOut isLocalGRE gres warnIfDeprecated :: GlobalRdrElt -> RnM () warnIfDeprecated gre@(GRE { gre_name = name, gre_imp = iss }) | (imp_spec : _) <- iss = do { dflags <- getDynFlags ; this_mod <- getModule ; when (wopt Opt_WarnWarningsDeprecations dflags && not (nameIsLocalOrFrom this_mod name)) $ -- See Note [Handling of deprecations] do { iface <- loadInterfaceForName doc name ; case lookupImpDeprec iface gre of Just txt -> addWarn (Reason Opt_WarnWarningsDeprecations) (mk_msg imp_spec txt) Nothing -> return () } } | otherwise = return () where occ = greOccName gre name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name doc = text "The name" <+> quotes (ppr occ) <+> ptext (sLit "is mentioned explicitly") mk_msg imp_spec txt = sep [ sep [ text "In the use of" <+> pprNonVarNameSpace (occNameSpace occ) <+> quotes (ppr occ) , parens imp_msg <> colon ] , pprWarningTxtForMsg txt ] where imp_mod = importSpecModule imp_spec imp_msg = text "imported from" <+> ppr imp_mod <> extra extra | imp_mod == moduleName name_mod = Outputable.empty | otherwise = text ", but defined in" <+> ppr name_mod lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt lookupImpDeprec iface gre = mi_warn_fn iface (greOccName gre) `mplus` -- Bleat if the thing, case gre_par gre of -- or its parent, is warn'd ParentIs p -> mi_warn_fn iface (nameOccName p) FldParent { par_is = p } -> mi_warn_fn iface (nameOccName p) NoParent -> Nothing {- Note [Used names with interface not loaded] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's (just) possible to find a used Name whose interface hasn't been loaded: a) It might be a WiredInName; in that case we may not load its interface (although we could). b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger These are seen as "used" by the renamer (if -XRebindableSyntax) is on), but the typechecker may discard their uses if in fact the in-scope fromRational is GHC.Read.fromRational, (see tcPat.tcOverloadedLit), and the typechecker sees that the type is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst). In that obscure case it won't force the interface in. In both cases we simply don't permit deprecations; this is, after all, wired-in stuff. ********************************************************* * * GHCi support * * ********************************************************* A qualified name on the command line can refer to any module at all: we try to load the interface if we don't already have it, just as if there was an "import qualified M" declaration for every module. For example, writing `Data.List.sort` will load the interface file for `Data.List` as if the user had written `import qualified Data.List`. If we fail we just return Nothing, rather than bleating about "attempting to use module ‘D’ (./D.hs) which is not loaded" which is what loadSrcInterface does. It is enabled by default and disabled by the flag `-fno-implicit-import-qualified`. Note [Safe Haskell and GHCi] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We DON'T do this Safe Haskell as we need to check imports. We can and should instead check the qualified import but at the moment this requires some refactoring so leave as a TODO -} lookupQualifiedNameGHCi :: RdrName -> RnM [Name] lookupQualifiedNameGHCi rdr_name = -- We want to behave as we would for a source file import here, -- and respect hiddenness of modules/packages, hence loadSrcInterface. do { dflags <- getDynFlags ; is_ghci <- getIsGHCi ; go_for_it dflags is_ghci } where go_for_it dflags is_ghci | Just (mod,occ) <- isQual_maybe rdr_name , is_ghci , gopt Opt_ImplicitImportQualified dflags -- Enables this GHCi behaviour , not (safeDirectImpsReq dflags) -- See Note [Safe Haskell and GHCi] = do { res <- loadSrcInterface_maybe doc mod False Nothing ; case res of Succeeded iface -> return [ name | avail <- mi_exports iface , name <- availNames avail , nameOccName name == occ ] _ -> -- Either we couldn't load the interface, or -- we could but we didn't find the name in it do { traceRn "lookupQualifiedNameGHCi" (ppr rdr_name) ; return [] } } | otherwise = do { traceRn "lookupQualifiedNameGHCi: off" (ppr rdr_name) ; return [] } doc = text "Need to find" <+> ppr rdr_name {- Note [Looking up signature names] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ lookupSigOccRn is used for type signatures and pragmas Is this valid? module A import M( f ) f :: Int -> Int f x = x It's clear that the 'f' in the signature must refer to A.f The Haskell98 report does not stipulate this, but it will! So we must treat the 'f' in the signature in the same way as the binding occurrence of 'f', using lookupBndrRn However, consider this case: import M( f ) f :: Int -> Int g x = x We don't want to say 'f' is out of scope; instead, we want to return the imported 'f', so that later on the reanamer will correctly report "misplaced type sig". Note [Signatures for top level things] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ data HsSigCtxt = ... | TopSigCtxt NameSet | .... * The NameSet says what is bound in this group of bindings. We can't use isLocalGRE from the GlobalRdrEnv, because of this: f x = x $( ...some TH splice... ) f :: Int -> Int When we encounter the signature for 'f', the binding for 'f' will be in the GlobalRdrEnv, and will be a LocalDef. Yet the signature is mis-placed * For type signatures the NameSet should be the names bound by the value bindings; for fixity declarations, the NameSet should also include class sigs and record selectors infix 3 `f` -- Yes, ok f :: C a => a -> a -- No, not ok class C a where f :: a -> a -} data HsSigCtxt = TopSigCtxt NameSet -- At top level, binding these names -- See Note [Signatures for top level things] | LocalBindCtxt NameSet -- In a local binding, binding these names | ClsDeclCtxt Name -- Class decl for this class | InstDeclCtxt NameSet -- Instance decl whose user-written method -- bindings are for these methods | HsBootCtxt NameSet -- Top level of a hs-boot file, binding these names | RoleAnnotCtxt NameSet -- A role annotation, with the names of all types -- in the group instance Outputable HsSigCtxt where ppr (TopSigCtxt ns) = text "TopSigCtxt" <+> ppr ns ppr (LocalBindCtxt ns) = text "LocalBindCtxt" <+> ppr ns ppr (ClsDeclCtxt n) = text "ClsDeclCtxt" <+> ppr n ppr (InstDeclCtxt ns) = text "InstDeclCtxt" <+> ppr ns ppr (HsBootCtxt ns) = text "HsBootCtxt" <+> ppr ns ppr (RoleAnnotCtxt ns) = text "RoleAnnotCtxt" <+> ppr ns lookupSigOccRn :: HsSigCtxt -> Sig GhcPs -> Located RdrName -> RnM (Located Name) lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig) -- | Lookup a name in relation to the names in a 'HsSigCtxt' lookupSigCtxtOccRn :: HsSigCtxt -> SDoc -- ^ description of thing we're looking up, -- like "type family" -> Located RdrName -> RnM (Located Name) lookupSigCtxtOccRn ctxt what = wrapLocM $ \ rdr_name -> do { mb_name <- lookupBindGroupOcc ctxt what rdr_name ; case mb_name of Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) } Right name -> return name } lookupBindGroupOcc :: HsSigCtxt -> SDoc -> RdrName -> RnM (Either MsgDoc Name) -- Looks up the RdrName, expecting it to resolve to one of the -- bound names passed in. If not, return an appropriate error message -- -- See Note [Looking up signature names] lookupBindGroupOcc ctxt what rdr_name | Just n <- isExact_maybe rdr_name = lookupExactOcc_either n -- allow for the possibility of missing Exacts; -- see Note [dataTcOccs and Exact Names] -- Maybe we should check the side conditions -- but it's a pain, and Exact things only show -- up when you know what you are doing | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name = do { n' <- lookupOrig rdr_mod rdr_occ ; return (Right n') } | otherwise = case ctxt of HsBootCtxt ns -> lookup_top (`elemNameSet` ns) TopSigCtxt ns -> lookup_top (`elemNameSet` ns) RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns) LocalBindCtxt ns -> lookup_group ns ClsDeclCtxt cls -> lookup_cls_op cls InstDeclCtxt ns -> lookup_top (`elemNameSet` ns) where lookup_cls_op cls = lookupSubBndrOcc True cls doc rdr_name where doc = text "method of class" <+> quotes (ppr cls) lookup_top keep_me = do { env <- getGlobalRdrEnv ; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name) ; case filter (keep_me . gre_name) all_gres of [] | null all_gres -> bale_out_with Outputable.empty | otherwise -> bale_out_with local_msg (gre:_) -> return (Right (gre_name gre)) } lookup_group bound_names -- Look in the local envt (not top level) = do { mname <- lookupLocalOccRn_maybe rdr_name ; case mname of Just n | n `elemNameSet` bound_names -> return (Right n) | otherwise -> bale_out_with local_msg Nothing -> bale_out_with Outputable.empty } bale_out_with msg = return (Left (sep [ text "The" <+> what <+> text "for" <+> quotes (ppr rdr_name) , nest 2 $ text "lacks an accompanying binding"] $$ nest 2 msg)) local_msg = parens $ text "The" <+> what <+> ptext (sLit "must be given where") <+> quotes (ppr rdr_name) <+> text "is declared" --------------- lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [(RdrName, Name)] -- GHC extension: look up both the tycon and data con or variable. -- Used for top-level fixity signatures and deprecations. -- Complain if neither is in scope. -- See Note [Fixity signature lookup] lookupLocalTcNames ctxt what rdr_name = do { mb_gres <- mapM lookup (dataTcOccs rdr_name) ; let (errs, names) = splitEithers mb_gres ; when (null names) $ addErr (head errs) -- Bleat about one only ; return names } where lookup rdr = do { name <- lookupBindGroupOcc ctxt what rdr ; return (fmap ((,) rdr) name) } dataTcOccs :: RdrName -> [RdrName] -- Return both the given name and the same name promoted to the TcClsName -- namespace. This is useful when we aren't sure which we are looking at. -- See also Note [dataTcOccs and Exact Names] dataTcOccs rdr_name | isDataOcc occ || isVarOcc occ = [rdr_name, rdr_name_tc] | otherwise = [rdr_name] where occ = rdrNameOcc rdr_name rdr_name_tc = setRdrNameSpace rdr_name tcName {- Note [dataTcOccs and Exact Names] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Exact RdrNames can occur in code generated by Template Haskell, and generally those references are, well, exact. However, the TH `Name` type isn't expressive enough to always track the correct namespace information, so we sometimes get the right Unique but wrong namespace. Thus, we still have to do the double-lookup for Exact RdrNames. There is also an awkward situation for built-in syntax. Example in GHCi :info [] This parses as the Exact RdrName for nilDataCon, but we also want the list type constructor. Note that setRdrNameSpace on an Exact name requires the Name to be External, which it always is for built in syntax. -} {- ************************************************************************ * * Rebindable names Dealing with rebindable syntax is driven by the Opt_RebindableSyntax dynamic flag. In "deriving" code we don't want to use rebindable syntax so we switch off the flag locally * * ************************************************************************ Haskell 98 says that when you say "3" you get the "fromInteger" from the Standard Prelude, regardless of what is in scope. However, to experiment with having a language that is less coupled to the standard prelude, we're trying a non-standard extension that instead gives you whatever "Prelude.fromInteger" happens to be in scope. Then you can import Prelude () import MyPrelude as Prelude to get the desired effect. At the moment this just happens for * fromInteger, fromRational on literals (in expressions and patterns) * negate (in expressions) * minus (arising from n+k patterns) * "do" notation We store the relevant Name in the HsSyn tree, in * HsIntegral/HsFractional/HsIsString * NegApp * NPlusKPat * HsDo respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName, fromRationalName etc), but the renamer changes this to the appropriate user name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does. We treat the original (standard) names as free-vars too, because the type checker checks the type of the user thing against the type of the standard thing. -} lookupIfThenElse :: RnM (Maybe (SyntaxExpr GhcRn), FreeVars) -- Different to lookupSyntaxName because in the non-rebindable -- case we desugar directly rather than calling an existing function -- Hence the (Maybe (SyntaxExpr GhcRn)) return type lookupIfThenElse = do { rebindable_on <- xoptM LangExt.RebindableSyntax ; if not rebindable_on then return (Nothing, emptyFVs) else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse")) ; return ( Just (mkRnSyntaxExpr ite) , unitFV ite ) } } lookupSyntaxName' :: Name -- ^ The standard name -> RnM Name -- ^ Possibly a non-standard name lookupSyntaxName' std_name = do { rebindable_on <- xoptM LangExt.RebindableSyntax ; if not rebindable_on then return std_name else -- Get the similarly named thing from the local environment lookupOccRn (mkRdrUnqual (nameOccName std_name)) } lookupSyntaxName :: Name -- The standard name -> RnM (SyntaxExpr GhcRn, FreeVars) -- Possibly a non-standard -- name lookupSyntaxName std_name = do { rebindable_on <- xoptM LangExt.RebindableSyntax ; if not rebindable_on then return (mkRnSyntaxExpr std_name, emptyFVs) else -- Get the similarly named thing from the local environment do { usr_name <- lookupOccRn (mkRdrUnqual (nameOccName std_name)) ; return (mkRnSyntaxExpr usr_name, unitFV usr_name) } } lookupSyntaxNames :: [Name] -- Standard names -> RnM ([HsExpr GhcRn], FreeVars) -- See comments with HsExpr.ReboundNames -- this works with CmdTop, which wants HsExprs, not SyntaxExprs lookupSyntaxNames std_names = do { rebindable_on <- xoptM LangExt.RebindableSyntax ; if not rebindable_on then return (map (HsVar . noLoc) std_names, emptyFVs) else do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names ; return (map (HsVar . noLoc) usr_names, mkFVs usr_names) } } -- Error messages opDeclErr :: RdrName -> SDoc opDeclErr n = hang (text "Illegal declaration of a type or class operator" <+> quotes (ppr n)) 2 (text "Use TypeOperators to declare operators in type and declarations") badOrigBinding :: RdrName -> SDoc badOrigBinding name | Just _ <- isBuiltInOcc_maybe occ = text "Illegal binding of built-in syntax:" <+> ppr occ -- Use an OccName here because we don't want to print Prelude.(,) | otherwise = text "Cannot redefine a Name retrieved by a Template Haskell quote:" <+> ppr name -- This can happen when one tries to use a Template Haskell splice to -- define a top-level identifier with an already existing name, e.g., -- -- $(pure [ValD (VarP 'succ) (NormalB (ConE 'True)) []]) -- -- (See Trac #13968.) where occ = rdrNameOcc name
shlevy/ghc
compiler/rename/RnEnv.hs
bsd-3-clause
64,163
61
22
17,960
8,684
4,447
4,237
721
13
{- Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE PackageImports #-} {-# LANGUAGE NoImplicitPrelude #-} module GHC.Err (module M) where import "base" GHC.Err as M
d191562687/codeworld
codeworld-base/src/GHC/Err.hs
apache-2.0
729
0
4
136
23
17
6
4
0
-- 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 FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} import Data.Int (Int32, Int64) import Data.List (genericLength) import Test.Framework (defaultMain) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.HUnit ((@=?)) import Test.QuickCheck (Arbitrary(..), Property, choose, vectorOf) import Test.QuickCheck.Monadic (monadicIO, run) import qualified Data.Vector as V import qualified TensorFlow.GenOps.Core as CoreOps import qualified TensorFlow.Ops as TF import qualified TensorFlow.Core as TF -- DynamicSplit is undone with DynamicStitch to get the original input -- back. testDynamicPartitionStitchInverse :: forall a. (TF.TensorDataType V.Vector a, Show a, Eq a) => StitchExample a -> Property testDynamicPartitionStitchInverse (StitchExample numParts values partitions) = let splitParts :: [TF.Tensor TF.Build a] = CoreOps.dynamicPartition numParts (TF.vector values) partTensor partTensor = TF.vector partitions restitchIndices = CoreOps.dynamicPartition numParts (TF.vector [0..genericLength values-1]) partTensor -- drop (numParts - 2) from both args to expose b/27343984 restitch = CoreOps.dynamicStitch restitchIndices splitParts in monadicIO $ run $ do fromIntegral numParts @=? length splitParts valuesOut <- TF.runSession $ TF.run restitch V.fromList values @=? valuesOut data StitchExample a = StitchExample Int64 [a] [Int32] deriving Show instance Arbitrary a => Arbitrary (StitchExample a) where arbitrary = do -- Limits the size of the vector. size <- choose (1, 100) values <- vectorOf size arbitrary numParts <- choose (2, 15) partitions <- vectorOf size (choose (0, fromIntegral numParts - 1)) return $ StitchExample numParts values partitions main :: IO () main = defaultMain [ testProperty "DynamicPartitionStitchInverse" (testDynamicPartitionStitchInverse :: StitchExample Int64 -> Property) ]
tensorflow/haskell
tensorflow-ops/tests/DataFlowOpsTest.hs
apache-2.0
2,667
0
14
541
538
296
242
40
1
{-# LANGUAGE PatternGuards #-} module Idris.Elab.Clause where import Idris.AbsSyntax import Idris.ASTUtils import Idris.DSL import Idris.Error import Idris.Delaborate import Idris.Imports import Idris.Elab.Term import Idris.Coverage import Idris.DataOpts import Idris.Providers import Idris.Primitives import Idris.Inliner import Idris.PartialEval import Idris.Transforms import Idris.DeepSeq import Idris.Output (iputStrLn, pshow, iWarn, iRenderResult, sendHighlighting) import IRTS.Lang import Idris.Elab.AsPat import Idris.Elab.Type import Idris.Elab.Transform import Idris.Elab.Utils import Idris.Core.TT import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate import Idris.Core.Execute import Idris.Core.Typecheck import Idris.Core.CaseTree import Idris.Docstrings hiding (Unchecked) import Util.Pretty hiding ((<$>)) import Prelude hiding (id, (.)) import Control.Category import Control.Applicative hiding (Const) import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict as State import qualified Control.Monad.State.Lazy as LState import Data.List import Data.Maybe import Debug.Trace import qualified Data.Map as Map import qualified Data.Set as S import qualified Data.Text as T import Data.Char(isLetter, toLower) import Data.List.Split (splitOn) import Util.Pretty(pretty, text) import Numeric -- | Elaborate a collection of left-hand and right-hand pairs - that is, a -- top-level definition. elabClauses :: ElabInfo -> FC -> FnOpts -> Name -> [PClause] -> Idris () elabClauses info' fc opts n_in cs = do let n = liftname info n_in info = info' { elabFC = Just fc } ctxt <- getContext ist <- getIState optimise <- getOptimise let petrans = PETransform `elem` optimise inacc <- map fst <$> fgetState (opt_inaccessible . ist_optimisation n) -- Check n actually exists, with no definition yet let tys = lookupTy n ctxt let reflect = Reflection `elem` opts checkUndefined n ctxt unless (length tys > 1) $ do fty <- case tys of [] -> -- TODO: turn into a CAF if there's no arguments -- question: CAFs in where blocks? tclift $ tfail $ At fc (NoTypeDecl n) [ty] -> return ty let atys = map snd (getArgTys fty) cs_elab <- mapM (elabClause info opts) (zip [0..] cs) -- pats_raw is the version we'll work with at compile time: -- no simplification or PE let (pats_in, cs_full) = unzip cs_elab let pats_raw = map (simple_lhs (tt_ctxt ist)) pats_in logLvl 3 $ "Elaborated patterns:\n" ++ show pats_raw solveDeferred n -- just ensure that the structure exists fmodifyState (ist_optimisation n) id addIBC (IBCOpt n) ist <- getIState -- Don't apply rules if this is a partial evaluation definition, -- or we'll make something that just runs itself! let tpats = case specNames opts of Nothing -> transformPats ist pats_in _ -> pats_in -- If the definition is specialisable, this reduces the -- RHS pe_tm <- doPartialEval ist tpats let pats_pe = if petrans then map (simple_lhs (tt_ctxt ist)) pe_tm else pats_raw let tcase = opt_typecase (idris_options ist) -- Look for 'static' names and generate new specialised -- definitions for them, as well as generating rewrite rules -- for partially evaluated definitions newrules <- if petrans then mapM (\ e -> case e of Left _ -> return [] Right (l, r) -> elabPE info fc n r) pats_pe else return [] -- Redo transforms with the newly generated transformations, so -- that the specialised application we've just made gets -- used in place of the general one ist <- getIState let pats_transformed = if petrans then transformPats ist pats_pe else pats_pe -- Summary of what's about to happen: Definitions go: -- -- pats_in -> pats -> pdef -> pdef' -- addCaseDef builds case trees from <pdef> and <pdef'> -- pdef is the compile-time pattern definition. -- This will get further inlined to help with totality checking. let pdef = map debind pats_raw -- pdef_pe is the one which will get further optimised -- for run-time, and, partially evaluated let pdef_pe = map debind pats_transformed logLvl 5 $ "Initial typechecked patterns:\n" ++ show pats_raw logLvl 5 $ "Initial typechecked pattern def:\n" ++ show pdef -- NOTE: Need to store original definition so that proofs which -- rely on its structure aren't affected by any changes to the -- inliner. Just use the inlined version to generate pdef' and to -- help with later inlinings. ist <- getIState let pdef_inl = inlineDef ist pdef numArgs <- tclift $ sameLength pdef case specNames opts of Just _ -> do logLvl 3 $ "Partially evaluated:\n" ++ show pats_pe _ -> return () logLvl 3 $ "Transformed:\n" ++ show pats_transformed erInfo <- getErasureInfo <$> getIState tree@(CaseDef scargs sc _) <- tclift $ simpleCase tcase (UnmatchedCase "Error") reflect CompileTime fc inacc atys pdef erInfo cov <- coverage pmissing <- if cov && not (hasDefault pats_raw) then do missing <- genClauses fc n (map getLHS pdef) cs_full -- missing <- genMissing n scargs sc missing' <- filterM (checkPossible info fc True n) missing let clhs = map getLHS pdef logLvl 2 $ "Must be unreachable:\n" ++ showSep "\n" (map showTmImpls missing') ++ "\nAgainst: " ++ showSep "\n" (map (\t -> showTmImpls (delab ist t)) (map getLHS pdef)) -- filter out anything in missing' which is -- matched by any of clhs. This might happen since -- unification may force a variable to take a -- particular form, rather than force a case -- to be impossible. return (filter (noMatch ist clhs) missing') else return [] let pcover = null pmissing -- pdef' is the version that gets compiled for run-time, -- so we start from the partially evaluated version pdef_in' <- applyOpts pdef_pe let pdef' = map (simple_rt (tt_ctxt ist)) pdef_in' logLvl 5 $ "After data structure transformations:\n" ++ show pdef' ist <- getIState -- let wf = wellFounded ist n sc let tot | pcover || AssertTotal `elem` opts = Unchecked -- finish later | PEGenerated `elem` opts = Generated | otherwise = Partial NotCovering -- already know it's not total -- case lookupCtxt (namespace info) n (idris_flags ist) of -- [fs] -> if TotalFn `elem` fs -- then case tot of -- Total _ -> return () -- t -> tclift $ tfail (At fc (Msg (show n ++ " is " ++ show t))) -- _ -> return () case tree of CaseDef _ _ [] -> return () CaseDef _ _ xs -> mapM_ (\x -> iputStrLn $ show fc ++ ":warning - Unreachable case: " ++ show (delab ist x)) xs let knowncovering = (pcover && cov) || AssertTotal `elem` opts let defaultcase = if knowncovering then STerm Erased else UnmatchedCase $ "*** " ++ show fc ++ ":unmatched case in " ++ show n ++ " ***" tree' <- tclift $ simpleCase tcase defaultcase reflect RunTime fc inacc atys pdef' erInfo logLvl 3 $ "Unoptimised " ++ show n ++ ": " ++ show tree logLvl 3 $ "Optimised: " ++ show tree' ctxt <- getContext ist <- getIState let opt = idris_optimisation ist putIState (ist { idris_patdefs = addDef n (force pdef_pe, force pmissing) (idris_patdefs ist) }) let caseInfo = CaseInfo (inlinable opts) (inlinable opts) (dictionary opts) case lookupTyExact n ctxt of Just ty -> do ctxt' <- do ctxt <- getContext tclift $ addCasedef n erInfo caseInfo tcase defaultcase reflect (AssertTotal `elem` opts) atys inacc pats_pe pdef pdef -- compile time pdef_inl -- inlined pdef' ty ctxt setContext ctxt' addIBC (IBCDef n) setTotality n tot when (not reflect && PEGenerated `notElem` opts) $ do totcheck (fc, n) defer_totcheck (fc, n) when (tot /= Unchecked) $ addIBC (IBCTotal n tot) i <- getIState case lookupDef n (tt_ctxt i) of (CaseOp _ _ _ _ _ cd : _) -> let (scargs, sc) = cases_compiletime cd (scargs', sc') = cases_runtime cd in do let calls = findCalls sc' scargs' let used = findUsedArgs sc' scargs' -- let scg = buildSCG i sc scargs -- add SCG later, when checking totality let cg = CGInfo scargs' calls [] used [] -- TODO: remove this, not needed anymore logLvl 2 $ "Called names: " ++ show cg addToCG n cg addToCalledG n (nub (map fst calls)) -- plus names in type! addIBC (IBCCG n) _ -> return () return () -- addIBC (IBCTotal n tot) _ -> return () -- Check it's covering, if 'covering' option is used. Chase -- all called functions, and fail if any of them are also -- 'Partial NotCovering' when (CoveringFn `elem` opts) $ checkAllCovering fc [] n n where noMatch i cs tm = all (\x -> case trim_matchClause i (delab' i x True True) tm of Right _ -> False Left miss -> True) cs where trim_matchClause i (PApp fcl fl ls) (PApp fcr fr rs) = let args = min (length ls) (length rs) in matchClause i (PApp fcl fl (take args ls)) (PApp fcr fr (take args rs)) checkUndefined n ctxt = case lookupDef n ctxt of [] -> return () [TyDecl _ _] -> return () _ -> tclift $ tfail (At fc (AlreadyDefined n)) debind (Right (x, y)) = let (vs, x') = depat [] x (_, y') = depat [] y in (vs, x', y') debind (Left x) = let (vs, x') = depat [] x in (vs, x', Impossible) depat acc (Bind n (PVar t) sc) = depat (n : acc) (instantiate (P Bound n t) sc) depat acc x = (acc, x) getPVs (Bind x (PVar _) tm) = let (vs, tm') = getPVs tm in (x:vs, tm') getPVs tm = ([], tm) isPatVar vs (P Bound n _) = n `elem` vs isPatVar _ _ = False hasDefault cs | (Right (lhs, rhs) : _) <- reverse cs , (pvs, tm) <- getPVs (explicitNames lhs) , (f, args) <- unApply tm = all (isPatVar pvs) args hasDefault _ = False getLHS (_, l, _) = l simple_lhs ctxt (Right (x, y)) = Right (normalise ctxt [] x, y) simple_lhs ctxt t = t simple_rt ctxt (p, x, y) = (p, x, force (uniqueBinders p (rt_simplify ctxt [] y))) specNames [] = Nothing specNames (Specialise ns : _) = Just ns specNames (_ : xs) = specNames xs sameLength ((_, x, _) : xs) = do l <- sameLength xs let (f, as) = unApply x if (null xs || l == length as) then return (length as) else tfail (At fc (Msg "Clauses have differing numbers of arguments ")) sameLength [] = return 0 -- Partially evaluate, if the definition is marked as specialisable doPartialEval ist pats = case specNames opts of Nothing -> return pats Just ns -> case partial_eval (tt_ctxt ist) ns pats of Just t -> return t Nothing -> ierror (At fc (Msg "No specialisation achieved")) -- | Find 'static' applications in a term and partially evaluate them. -- Return any new transformation rules elabPE :: ElabInfo -> FC -> Name -> Term -> Idris [(Term, Term)] elabPE info fc caller r = do ist <- getIState let sa = filter (\ap -> fst ap /= caller) $ getSpecApps ist [] r rules <- mapM mkSpecialised sa return $ concat rules where -- Make a specialised version of the application, and -- add a PTerm level transformation rule, which is basically the -- new definition in reverse (before specialising it). -- RHS => LHS where implicit arguments are left blank in the -- transformation. -- Transformation rules are applied after every PClause elaboration mkSpecialised :: (Name, [(PEArgType, Term)]) -> Idris [(Term, Term)] mkSpecialised specapp_in = do ist <- getIState let (specTy, specapp) = getSpecTy ist specapp_in let (n, newnm, specdecl) = getSpecClause ist specapp let lhs = pe_app specdecl let rhs = pe_def specdecl let undef = case lookupDefExact newnm (tt_ctxt ist) of Nothing -> True _ -> False logLvl 5 $ show (newnm, undef, map (concreteArg ist) (snd specapp)) idrisCatch (if (undef && all (concreteArg ist) (snd specapp)) then do cgns <- getAllNames n -- on the RHS of the new definition, we should reduce -- everything that's not itself static (because we'll -- want to be a PE version of those next) let cgns' = filter (\x -> x /= n && notStatic ist x) cgns -- set small reduction limit on partial/productive things let maxred = case lookupTotal n (tt_ctxt ist) of [Total _] -> 65536 [Productive] -> 16 _ -> 1 let opts = [Specialise ((if pe_simple specdecl then map (\x -> (x, Nothing)) cgns' else []) ++ (n, Just maxred) : mapMaybe (specName (pe_simple specdecl)) (snd specapp))] logLvl 3 $ "Specialising application: " ++ show specapp ++ " in " ++ show caller ++ " with " ++ show opts logLvl 3 $ "New name: " ++ show newnm logLvl 3 $ "PE definition type : " ++ (show specTy) ++ "\n" ++ show opts logLvl 3 $ "PE definition " ++ show newnm ++ ":\n" ++ showSep "\n" (map (\ (lhs, rhs) -> (showTmImpls lhs ++ " = " ++ showTmImpls rhs)) (pe_clauses specdecl)) logLvl 2 $ show n ++ " transformation rule: " ++ showTmImpls rhs ++ " ==> " ++ showTmImpls lhs elabType info defaultSyntax emptyDocstring [] fc opts newnm NoFC specTy let def = map (\(lhs, rhs) -> let lhs' = mapPT hiddenToPH $ stripUnmatchable ist lhs in PClause fc newnm lhs' [] rhs []) (pe_clauses specdecl) trans <- elabTransform info fc False rhs lhs elabClauses info fc (PEGenerated:opts) newnm def return [trans] else return []) -- if it doesn't work, just don't specialise. Could happen for lots -- of valid reasons (e.g. local variables in scope which can't be -- lifted out). (\e -> do logLvl 3 $ "Couldn't specialise: " ++ (pshow ist e) return []) hiddenToPH (PHidden _) = Placeholder hiddenToPH x = x specName simpl (ImplicitS, tm) | (P Ref n _, _) <- unApply tm = Just (n, Just (if simpl then 1 else 0)) specName simpl (ExplicitS, tm) | (P Ref n _, _) <- unApply tm = Just (n, Just (if simpl then 1 else 0)) specName simpl _ = Nothing notStatic ist n = case lookupCtxtExact n (idris_statics ist) of Just s -> not (or s) _ -> True concreteArg ist (ImplicitS, tm) = concreteTm ist tm concreteArg ist (ExplicitS, tm) = concreteTm ist tm concreteArg ist _ = True concreteTm ist tm | (P _ n _, _) <- unApply tm = case lookupTy n (tt_ctxt ist) of [] -> False _ -> True concreteTm ist (Constant _) = True concreteTm ist (Bind n (Lam _) sc) = True concreteTm ist (Bind n (Pi _ _ _) sc) = True concreteTm ist (Bind n (Let _ _) sc) = concreteTm ist sc concreteTm ist _ = False -- get the type of a specialised application getSpecTy ist (n, args) = case lookupTy n (tt_ctxt ist) of [ty] -> let (specty_in, args') = specType args (explicitNames ty) specty = normalise (tt_ctxt ist) [] (finalise specty_in) t = mkPE_TyDecl ist args' (explicitNames specty) in (t, (n, args')) -- (normalise (tt_ctxt ist) [] (specType args ty)) _ -> error "Can't happen (getSpecTy)" -- get the clause of a specialised application getSpecClause ist (n, args) = let newnm = sUN ("PE_" ++ show (nsroot n) ++ "_" ++ qhash 5381 (showSep "_" (map showArg args))) in -- UN (show n ++ show (map snd args)) in (n, newnm, mkPE_TermDecl ist newnm n args) where showArg (ExplicitS, n) = qshow n showArg (ImplicitS, n) = qshow n showArg _ = "" qshow (Bind _ _ _) = "fn" qshow (App _ f a) = qshow f ++ qshow a qshow (P _ n _) = show n qshow (Constant c) = show c qshow _ = "" -- Simple but effective string hashing... -- Keep it to 32 bits for readability/debuggability qhash :: Int -> String -> String qhash hash [] = showHex (abs hash `mod` 0xffffffff) "" qhash hash (x:xs) = qhash (hash * 33 + fromEnum x) xs -- | Checks if the clause is a possible left hand side. checkPossible :: ElabInfo -> FC -> Bool -> Name -> PTerm -> Idris Bool checkPossible info fc tcgen fname lhs_in = do ctxt <- getContext i <- getIState let lhs = addImplPat i lhs_in -- if the LHS type checks, it is possible case elaborate ctxt (idris_datatypes i) (sMN 0 "patLHS") infP initEState (erun fc (buildTC i info ELHS [] fname (allNamesIn lhs_in) (infTerm lhs))) of OK (ElabResult lhs' _ _ ctxt' newDecls highlights, _) -> do setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights let lhs_tm = orderPats (getInferTerm lhs') case recheck ctxt [] (forget lhs_tm) lhs_tm of OK _ -> return True err -> return False -- if it's a recoverable error, the case may become possible Error err -> if tcgen then return (recoverableCoverage ctxt err) else return (validCoverageCase ctxt err || recoverableCoverage ctxt err) propagateParams :: IState -> [Name] -> Type -> [Name] -> PTerm -> PTerm propagateParams i ps t bound tm@(PApp _ (PRef fc hls n) args) = PApp fc (PRef fc hls n) (addP t args) where addP (Bind n _ sc) (t : ts) | Placeholder <- getTm t, n `elem` ps, not (n `elem` bound) = t { getTm = PPatvar NoFC n } : addP sc ts addP (Bind n _ sc) (t : ts) = t : addP sc ts addP _ ts = ts propagateParams i ps t bound (PApp fc ap args) = PApp fc (propagateParams i ps t bound ap) args propagateParams i ps t bound (PRef fc hls n) = case lookupCtxt n (idris_implicits i) of [is] -> let ps' = filter (isImplicit is) ps in PApp fc (PRef fc hls n) (map (\x -> pimp x (PRef fc [] x) True) ps') _ -> PRef fc hls n where isImplicit [] n = False isImplicit (PImp _ _ _ x _ : is) n | x == n = True isImplicit (_ : is) n = isImplicit is n propagateParams i ps t bound x = x findUnique :: Context -> Env -> Term -> [Name] findUnique ctxt env (Bind n b sc) = let rawTy = forgetEnv (map fst env) (binderTy b) uniq = case check ctxt env rawTy of OK (_, UType UniqueType) -> True OK (_, UType NullType) -> True OK (_, UType AllTypes) -> True _ -> False in if uniq then n : findUnique ctxt ((n, b) : env) sc else findUnique ctxt ((n, b) : env) sc findUnique _ _ _ = [] -- Return the elaborated LHS/RHS, and the original LHS with implicits added elabClause :: ElabInfo -> FnOpts -> (Int, PClause) -> Idris (Either Term (Term, Term), PTerm) elabClause info opts (_, PClause fc fname lhs_in [] PImpossible []) = do let tcgen = Dictionary `elem` opts i <- get let lhs = addImpl [] i lhs_in b <- checkPossible info fc tcgen fname lhs_in case b of True -> tclift $ tfail (At fc (Msg $ show lhs_in ++ " is a valid case")) False -> do ptm <- mkPatTm lhs_in return (Left ptm, lhs) elabClause info opts (cnum, PClause fc fname lhs_in_as withs rhs_in_as whereblock) = do let tcgen = Dictionary `elem` opts push_estack fname False ctxt <- getContext let (lhs_in, rhs_in) = desugarAs lhs_in_as rhs_in_as -- Build the LHS as an "Infer", and pull out its type and -- pattern bindings i <- getIState inf <- isTyInferred fname -- Check if we have "with" patterns outside of "with" block when (isOutsideWith lhs_in && (not $ null withs)) $ ierror $ (At fc (Elaborating "left hand side of " fname Nothing (Msg "unexpected patterns outside of \"with\" block"))) -- get the parameters first, to pass through to any where block let fn_ty = case lookupTy fname (tt_ctxt i) of [t] -> t _ -> error "Can't happen (elabClause function type)" let fn_is = case lookupCtxt fname (idris_implicits i) of [t] -> t _ -> [] let norm_ty = normalise ctxt [] fn_ty let params = getParamsInType i [] fn_is norm_ty let tcparams = getTCParamsInType i [] fn_is norm_ty let lhs = mkLHSapp $ stripLinear i $ stripUnmatchable i $ propagateParams i params norm_ty (allNamesIn lhs_in) (addImplPat i lhs_in) -- let lhs = mkLHSapp $ -- propagateParams i params fn_ty (addImplPat i lhs_in) logLvl 10 (show (params, fn_ty) ++ " " ++ showTmImpls (addImplPat i lhs_in)) logLvl 5 ("LHS: " ++ show fc ++ " " ++ showTmImpls lhs) logLvl 4 ("Fixed parameters: " ++ show params ++ " from " ++ show lhs_in ++ "\n" ++ show (fn_ty, fn_is)) ((ElabResult lhs' dlhs [] ctxt' newDecls highlights, probs, inj), _) <- tclift $ elaborate ctxt (idris_datatypes i) (sMN 0 "patLHS") infP initEState (do res <- errAt "left hand side of " fname Nothing (erun fc (buildTC i info ELHS opts fname (allNamesIn lhs_in) (infTerm lhs))) probs <- get_probs inj <- get_inj return (res, probs, inj)) setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights when inf $ addTyInfConstraints fc (map (\(x,y,_,_,_,_,_) -> (x,y)) probs) let lhs_tm = orderPats (getInferTerm lhs') let lhs_ty = getInferType lhs' let static_names = getStaticNames i lhs_tm logLvl 3 ("Elaborated: " ++ show lhs_tm) logLvl 3 ("Elaborated type: " ++ show lhs_ty) logLvl 5 ("Injective: " ++ show fname ++ " " ++ show inj) -- If we're inferring metavariables in the type, don't recheck, -- because we're only doing this to try to work out those metavariables (clhs_c, clhsty) <- if not inf then recheckC_borrowing False (PEGenerated `notElem` opts) [] fc id [] lhs_tm else return (lhs_tm, lhs_ty) let clhs = normalise ctxt [] clhs_c let borrowed = borrowedNames [] clhs -- These are the names we're not allowed to use on the RHS, because -- they're UniqueTypes and borrowed from another function. -- FIXME: There is surely a nicer way than this... -- Issue #1615 on the Issue Tracker. -- https://github.com/idris-lang/Idris-dev/issues/1615 when (not (null borrowed)) $ logLvl 5 ("Borrowed names on LHS: " ++ show borrowed) logLvl 3 ("Normalised LHS: " ++ showTmImpls (delabMV i clhs)) rep <- useREPL when rep $ do addInternalApp (fc_fname fc) (fst . fc_start $ fc) (delabMV i clhs) -- TODO: Should use span instead of line and filename? addIBC (IBCLineApp (fc_fname fc) (fst . fc_start $ fc) (delabMV i clhs)) logLvl 5 ("Checked " ++ show clhs ++ "\n" ++ show clhsty) -- Elaborate where block ist <- getIState windex <- getName let decls = nub (concatMap declared whereblock) let defs = nub (decls ++ concatMap defined whereblock) let newargs_all = pvars ist lhs_tm -- Unique arguments must be passed to the where block explicitly -- (since we can't control "usage" easlily otherwise). Remove them -- from newargs here let uniqargs = findUnique (tt_ctxt ist) [] lhs_tm let newargs = filter (\(n,_) -> n `notElem` uniqargs) newargs_all let winfo = (pinfo info newargs defs windex) { elabFC = Just fc } let wb = map (mkStatic static_names) $ map (expandParamsD False ist decorate newargs defs) whereblock -- Split the where block into declarations with a type, and those -- without -- Elaborate those with a type *before* RHS, those without *after* let (wbefore, wafter) = sepBlocks wb logLvl 2 $ "Where block:\n " ++ show wbefore ++ "\n" ++ show wafter mapM_ (rec_elabDecl info EAll winfo) wbefore -- Now build the RHS, using the type of the LHS as the goal. i <- getIState -- new implicits from where block logLvl 5 (showTmImpls (expandParams decorate newargs defs (defs \\ decls) rhs_in)) let rhs = addImplBoundInf i (map fst newargs_all) (defs \\ decls) (expandParams decorate newargs defs (defs \\ decls) rhs_in) logLvl 2 $ "RHS: " ++ show (map fst newargs_all) ++ " " ++ showTmImpls rhs ctxt <- getContext -- new context with where block added logLvl 5 "STARTING CHECK" ((rhs', defer, is, probs, ctxt', newDecls, highlights), _) <- tclift $ elaborate ctxt (idris_datatypes i) (sMN 0 "patRHS") clhsty initEState (do pbinds ist lhs_tm -- proof search can use explicitly written names mapM_ addPSname (allNamesIn lhs_in) mapM_ setinj (nub (tcparams ++ inj)) setNextName (ElabResult _ _ is ctxt' newDecls highlights) <- errAt "right hand side of " fname (Just clhsty) (erun fc (build i winfo ERHS opts fname rhs)) errAt "right hand side of " fname (Just clhsty) (erun fc $ psolve lhs_tm) hs <- get_holes mapM_ (elabCaseHole is) hs tt <- get_term aux <- getAux let (tm, ds) = runState (collectDeferred (Just fname) (map fst $ case_decls aux) ctxt tt) [] probs <- get_probs return (tm, ds, is, probs, ctxt', newDecls, highlights)) setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights when inf $ addTyInfConstraints fc (map (\(x,y,_,_,_,_,_) -> (x,y)) probs) logLvl 5 "DONE CHECK" logLvl 4 $ "---> " ++ show rhs' when (not (null defer)) $ logLvl 1 $ "DEFERRED " ++ show (map (\ (n, (_,_,t,_)) -> (n, t)) defer) def' <- checkDef fc (\n -> Elaborating "deferred type of " n Nothing) defer let def'' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, False))) def' addDeferred def'' mapM_ (\(n, _) -> addIBC (IBCDef n)) def'' when (not (null def')) $ do mapM_ defer_totcheck (map (\x -> (fc, fst x)) def'') -- Now the remaining deferred (i.e. no type declarations) clauses -- from the where block mapM_ (rec_elabDecl info EAll winfo) wafter mapM_ (elabCaseBlock winfo opts) is ctxt <- getContext logLvl 5 $ "Rechecking" logLvl 6 $ " ==> " ++ show (forget rhs') (crhs, crhsty) <- if not inf then recheckC_borrowing True (PEGenerated `notElem` opts) borrowed fc id [] rhs' else return (rhs', clhsty) logLvl 6 $ " ==> " ++ showEnvDbg [] crhsty ++ " against " ++ showEnvDbg [] clhsty ctxt <- getContext let constv = next_tvar ctxt case LState.runStateT (convertsC ctxt [] crhsty clhsty) (constv, []) of OK (_, cs) -> when (PEGenerated `notElem` opts) $ do addConstraints fc cs logLvl 6 $ "CONSTRAINTS ADDED: " ++ show cs ++ "\n" ++ show (clhsty, crhsty) return () Error e -> ierror (At fc (CantUnify False (clhsty, Nothing) (crhsty, Nothing) e [] 0)) i <- getIState checkInferred fc (delab' i crhs True True) rhs -- if the function is declared '%error_reverse', or its type, -- then we'll try running it in reverse to improve error messages let (ret_fam, _) = unApply (getRetTy crhsty) rev <- case ret_fam of P _ rfamn _ -> case lookupCtxt rfamn (idris_datatypes i) of [TI _ _ dopts _ _] -> return (DataErrRev `elem` dopts) _ -> return False _ -> return False when (rev || ErrorReverse `elem` opts) $ do addIBC (IBCErrRev (crhs, clhs)) addErrRev (crhs, clhs) pop_estack return $ (Right (clhs, crhs), lhs) where pinfo :: ElabInfo -> [(Name, PTerm)] -> [Name] -> Int -> ElabInfo pinfo info ns ds i = let newps = params info ++ ns dsParams = map (\n -> (n, map fst newps)) ds newb = addAlist dsParams (inblock info) l = liftname info in info { params = newps, inblock = newb, liftname = id -- (\n -> case lookupCtxt n newb of -- Nothing -> n -- _ -> MN i (show n)) . l } -- Find the variable names which appear under a 'Ownership.Read' so that -- we know they can't be used on the RHS borrowedNames :: [Name] -> Term -> [Name] borrowedNames env (App _ (App _ (P _ (NS (UN lend) [owner]) _) _) arg) | owner == txt "Ownership" && (lend == txt "lend" || lend == txt "Read") = getVs arg where getVs (V i) = [env!!i] getVs (App _ f a) = nub $ getVs f ++ getVs a getVs _ = [] borrowedNames env (App _ f a) = nub $ borrowedNames env f ++ borrowedNames env a borrowedNames env (Bind n b sc) = nub $ borrowedB b ++ borrowedNames (n:env) sc where borrowedB (Let t v) = nub $ borrowedNames env t ++ borrowedNames env v borrowedB b = borrowedNames env (binderTy b) borrowedNames _ _ = [] mkLHSapp t@(PRef _ _ _) = PApp fc t [] mkLHSapp t = t decorate (NS x ns) = NS (SN (WhereN cnum fname x)) ns -- ++ [show cnum]) -- = NS (UN ('#':show x)) (ns ++ [show cnum, show fname]) decorate x = SN (WhereN cnum fname x) -- = NS (SN (WhereN cnum fname x)) [show cnum] -- = NS (UN ('#':show x)) [show cnum, show fname] sepBlocks bs = sepBlocks' [] bs where sepBlocks' ns (d@(PTy _ _ _ _ _ n _ t) : bs) = let (bf, af) = sepBlocks' (n : ns) bs in (d : bf, af) sepBlocks' ns (d@(PClauses _ _ n _) : bs) | not (n `elem` ns) = let (bf, af) = sepBlocks' ns bs in (bf, d : af) sepBlocks' ns (b : bs) = let (bf, af) = sepBlocks' ns bs in (b : bf, af) sepBlocks' ns [] = ([], []) -- if a hole is just an argument/result of a case block, treat it as -- the unit type. Hack to help elaborate case in do blocks. elabCaseHole aux h = do focus h g <- goal case g of TType _ -> when (any (isArg h) aux) $ do apply (Var unitTy) []; solve _ -> return () -- Is the name a pattern argument in the declaration isArg :: Name -> PDecl -> Bool isArg n (PClauses _ _ _ cs) = any isArg' cs where isArg' (PClause _ _ (PApp _ _ args) _ _ _) = any (\x -> case x of PRef _ _ n' -> n == n' _ -> False) (map getTm args) isArg' _ = False isArg _ _ = False -- term is not within "with" block isOutsideWith :: PTerm -> Bool isOutsideWith (PApp _ (PRef _ _ (SN (WithN _ _))) _) = False isOutsideWith _ = True elabClause info opts (_, PWith fc fname lhs_in withs wval_in pn_in withblock) = do let tcgen = Dictionary `elem` opts ctxt <- getContext -- Build the LHS as an "Infer", and pull out its type and -- pattern bindings i <- getIState -- get the parameters first, to pass through to any where block let fn_ty = case lookupTy fname (tt_ctxt i) of [t] -> t _ -> error "Can't happen (elabClause function type)" let fn_is = case lookupCtxt fname (idris_implicits i) of [t] -> t _ -> [] let params = getParamsInType i [] fn_is (normalise ctxt [] fn_ty) let lhs = stripLinear i $ stripUnmatchable i $ propagateParams i params fn_ty (allNamesIn lhs_in) (addImplPat i lhs_in) logLvl 2 ("LHS: " ++ show lhs) (ElabResult lhs' dlhs [] ctxt' newDecls highlights, _) <- tclift $ elaborate ctxt (idris_datatypes i) (sMN 0 "patLHS") infP initEState (errAt "left hand side of with in " fname Nothing (erun fc (buildTC i info ELHS opts fname (allNamesIn lhs_in) (infTerm lhs))) ) setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights let lhs_tm = orderPats (getInferTerm lhs') let lhs_ty = getInferType lhs' let ret_ty = getRetTy (explicitNames (normalise ctxt [] lhs_ty)) let static_names = getStaticNames i lhs_tm logLvl 5 (show lhs_tm ++ "\n" ++ show static_names) (clhs, clhsty) <- recheckC fc id [] lhs_tm logLvl 5 ("Checked " ++ show clhs) let bargs = getPBtys (explicitNames (normalise ctxt [] lhs_tm)) let wval = addImplBound i (map fst bargs) wval_in logLvl 5 ("Checking " ++ showTmImpls wval) -- Elaborate wval in this context ((wval', defer, is, ctxt', newDecls, highlights), _) <- tclift $ elaborate ctxt (idris_datatypes i) (sMN 0 "withRHS") (bindTyArgs PVTy bargs infP) initEState (do pbinds i lhs_tm -- proof search can use explicitly written names mapM_ addPSname (allNamesIn lhs_in) setNextName -- TODO: may want where here - see winfo abpve (ElabResult _ d is ctxt' newDecls highlights) <- errAt "with value in " fname Nothing (erun fc (build i info ERHS opts fname (infTerm wval))) erun fc $ psolve lhs_tm tt <- get_term return (tt, d, is, ctxt', newDecls, highlights)) setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights def' <- checkDef fc iderr defer let def'' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, False))) def' addDeferred def'' mapM_ (elabCaseBlock info opts) is logLvl 5 ("Checked wval " ++ show wval') (cwval, cwvalty) <- recheckC fc id [] (getInferTerm wval') let cwvaltyN = explicitNames (normalise ctxt [] cwvalty) let cwvalN = explicitNames (normalise ctxt [] cwval) logLvl 3 ("With type " ++ show cwvalty ++ "\nRet type " ++ show ret_ty) -- We're going to assume the with type is not a function shortly, -- so report an error if it is (you can't match on a function anyway -- so this doesn't lose anything) case getArgTys cwvaltyN of [] -> return () (_:_) -> ierror $ At fc (WithFnType cwvalty) let pvars = map fst (getPBtys cwvalty) -- we need the unelaborated term to get the names it depends on -- rather than a de Bruijn index. let pdeps = usedNamesIn pvars i (delab i cwvalty) let (bargs_pre, bargs_post) = split pdeps bargs [] let mpn = case pn_in of Nothing -> Nothing Just (n, nfc) -> Just (uniqueName n (map fst bargs)) -- Highlight explicit proofs sendHighlighting $ [(fc, AnnBoundName n False) | (n, fc) <- maybeToList pn_in] logLvl 10 ("With type " ++ show (getRetTy cwvaltyN) ++ " depends on " ++ show pdeps ++ " from " ++ show pvars) logLvl 10 ("Pre " ++ show bargs_pre ++ "\nPost " ++ show bargs_post) windex <- getName -- build a type declaration for the new function: -- (ps : Xs) -> (withval : cwvalty) -> (ps' : Xs') -> ret_ty let wargval = getRetTy cwvalN let wargtype = getRetTy cwvaltyN let wargname = sMN windex "warg" logLvl 5 ("Abstract over " ++ show wargval ++ " in " ++ show wargtype) let wtype = bindTyArgs (flip (Pi Nothing) (TType (UVar 0))) (bargs_pre ++ (wargname, wargtype) : map (abstract wargname wargval wargtype) bargs_post ++ case mpn of Just pn -> [(pn, mkApp (P Ref eqTy Erased) [wargtype, wargtype, P Bound wargname Erased, wargval])] Nothing -> []) (substTerm wargval (P Bound wargname wargtype) ret_ty) logLvl 3 ("New function type " ++ show wtype) let wname = SN (WithN windex fname) let imps = getImps wtype -- add to implicits context putIState (i { idris_implicits = addDef wname imps (idris_implicits i) }) let statics = getStatics static_names wtype logLvl 5 ("Static positions " ++ show statics) i <- getIState putIState (i { idris_statics = addDef wname statics (idris_statics i) }) addIBC (IBCDef wname) addIBC (IBCImp wname) addIBC (IBCStatic wname) def' <- checkDef fc iderr [(wname, (-1, Nothing, wtype, []))] let def'' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, False))) def' addDeferred def'' -- in the subdecls, lhs becomes: -- fname pats | wpat [rest] -- ==> fname' ps wpat [rest], match pats against toplevel for ps wb <- mapM (mkAuxC mpn wname lhs (map fst bargs_pre) (map fst bargs_post)) withblock logLvl 3 ("with block " ++ show wb) -- propagate totality assertion to the new definitions when (AssertTotal `elem` opts) $ setFlags wname [AssertTotal] mapM_ (rec_elabDecl info EAll info) wb -- rhs becomes: fname' ps_pre wval ps_post Refl let rhs = PApp fc (PRef fc [] wname) (map (pexp . (PRef fc []) . fst) bargs_pre ++ pexp wval : (map (pexp . (PRef fc []) . fst) bargs_post) ++ case mpn of Nothing -> [] Just _ -> [pexp (PApp NoFC (PRef NoFC [] eqCon) [ pimp (sUN "A") Placeholder False , pimp (sUN "x") Placeholder False ])]) logLvl 5 ("New RHS " ++ showTmImpls rhs) ctxt <- getContext -- New context with block added i <- getIState ((rhs', defer, is, ctxt', newDecls, highlights), _) <- tclift $ elaborate ctxt (idris_datatypes i) (sMN 0 "wpatRHS") clhsty initEState (do pbinds i lhs_tm setNextName (ElabResult _ d is ctxt' newDecls highlights) <- erun fc (build i info ERHS opts fname rhs) psolve lhs_tm tt <- get_term return (tt, d, is, ctxt', newDecls, highlights)) setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights def' <- checkDef fc iderr defer let def'' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, False))) def' addDeferred def'' mapM_ (elabCaseBlock info opts) is logLvl 5 ("Checked RHS " ++ show rhs') (crhs, crhsty) <- recheckC fc id [] rhs' return $ (Right (clhs, crhs), lhs) where getImps (Bind n (Pi _ _ _) t) = pexp Placeholder : getImps t getImps _ = [] mkAuxC pn wname lhs ns ns' (PClauses fc o n cs) | True = do cs' <- mapM (mkAux pn wname lhs ns ns') cs return $ PClauses fc o wname cs' | otherwise = ifail $ show fc ++ "with clause uses wrong function name " ++ show n mkAuxC pn wname lhs ns ns' d = return $ d mkAux pn wname toplhs ns ns' (PClause fc n tm_in (w:ws) rhs wheres) = do i <- getIState let tm = addImplPat i tm_in logLvl 2 ("Matching " ++ showTmImpls tm ++ " against " ++ showTmImpls toplhs) case matchClause i toplhs tm of Left (a,b) -> ifail $ show fc ++ ":with clause does not match top level" Right mvars -> do logLvl 3 ("Match vars : " ++ show mvars) lhs <- updateLHS n pn wname mvars ns ns' (fullApp tm) w return $ PClause fc wname lhs ws rhs wheres mkAux pn wname toplhs ns ns' (PWith fc n tm_in (w:ws) wval pn' withs) = do i <- getIState let tm = addImplPat i tm_in logLvl 2 ("Matching " ++ showTmImpls tm ++ " against " ++ showTmImpls toplhs) withs' <- mapM (mkAuxC pn wname toplhs ns ns') withs case matchClause i toplhs tm of Left (a,b) -> trace ("matchClause: " ++ show a ++ " =/= " ++ show b) (ifail $ show fc ++ "with clause does not match top level") Right mvars -> do lhs <- updateLHS n pn wname mvars ns ns' (fullApp tm) w return $ PWith fc wname lhs ws wval pn' withs' mkAux pn wname toplhs ns ns' c = ifail $ show fc ++ ":badly formed with clause" addArg (PApp fc f args) w = PApp fc f (args ++ [pexp w]) addArg (PRef fc hls f) w = PApp fc (PRef fc hls f) [pexp w] updateLHS n pn wname mvars ns_in ns_in' (PApp fc (PRef fc' hls' n') args) w = let ns = map (keepMvar (map fst mvars) fc') ns_in ns' = map (keepMvar (map fst mvars) fc') ns_in' in return $ substMatches mvars $ PApp fc (PRef fc' [] wname) (map pexp ns ++ pexp w : (map pexp ns') ++ case pn of Nothing -> [] Just pnm -> [pexp (PRef fc [] pnm)]) updateLHS n pn wname mvars ns_in ns_in' tm w = updateLHS n pn wname mvars ns_in ns_in' (PApp fc tm []) w keepMvar mvs fc v | v `elem` mvs = PRef fc [] v | otherwise = Placeholder fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs)) fullApp x = x split [] rest pre = (reverse pre, rest) split deps ((n, ty) : rest) pre | n `elem` deps = split (deps \\ [n]) rest ((n, ty) : pre) | otherwise = split deps rest ((n, ty) : pre) split deps [] pre = (reverse pre, []) abstract wn wv wty (n, argty) = (n, substTerm wv (P Bound wn wty) argty)
adnelson/Idris-dev
src/Idris/Elab/Clause.hs
bsd-3-clause
49,068
10
28
19,802
14,141
7,011
7,130
786
43
{-# LANGUAGE RankNTypes, ScopedTypeVariables, FlexibleInstances, MultiParamTypeClasses, FunctionalDependencies #-} -- This tests scoped type variables, used in an expression -- type signature in t1 and t2 module Foo7 where import Control.Monad import Control.Monad.ST import Data.Array.MArray import Data.Array.ST import Data.STRef import Data.Set hiding (map,filter) -- a store that allows to mark keys class Mark m store key | store -> key m where new :: (key,key) -> m store mark :: store -> key -> m () markQ :: store -> key -> m Bool seen :: store -> m [ key ] -- implementation 1 instance Ord key => Mark (ST s) (STRef s (Set key)) key where new _ = newSTRef empty mark s k = modifySTRef s (insert k) markQ s k = liftM (member k) (readSTRef s) seen s = liftM elems (readSTRef s) -- implementation 2 instance Ix key => Mark (ST s) (STUArray s key Bool) key where new bnd = newArray bnd False mark s k = writeArray s k True markQ = readArray seen s = liftM (map fst . filter snd) (getAssocs s) -- traversing the hull suc^*(start) with loop detection -- trav :: forall f f2 m store key. -- (Foldable f, Foldable f2, Mark m store key, Monad m) -- => (key -> f key) -> f2 key -> (key, key) -> m store trav suc start i = new i >>= \ c -> mapM_ (compo c) start >> return c where -- compo :: (Monad m, Mark m store' key) => store' -> key -> m () compo c x = markQ c x >>= flip unless (visit c x) -- visit :: (Monad m, Mark m store' key) => store' -> key -> m () visit c x = mark c x >> mapM_ (compo c) (suc x) -- sample graph f 1 = 1 : [] f n = n : f (if even n then div n 2 else 3*n+1) t1 = runST ( (trav f [1..10] (1,52) >>= \ (s::STRef s (Set Int)) -> seen s) :: forall s. ST s [Int] ) t2 = runST ( (trav f [1..10] (1,52) >>= \ (s::STUArray s Int Bool) -> seen s) :: forall s. ST s [Int] )
sdiehl/ghc
testsuite/tests/typecheck/should_compile/tc213.hs
bsd-3-clause
1,969
0
14
550
685
357
328
33
2
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Install -- Copyright : Isaac Jones 2003-2004 -- License : BSD3 -- -- Maintainer : [email protected] -- Portability : portable -- -- This is the entry point into installing a built package. Performs the -- \"@.\/setup install@\" and \"@.\/setup copy@\" actions. It moves files into -- place based on the prefix argument. It does the generic bits and then calls -- compiler-specific functions to do the rest. module Distribution.Simple.Install ( install, ) where import Distribution.PackageDescription import Distribution.Package (Package(..)) import Distribution.Simple.LocalBuildInfo import Distribution.Simple.BuildPaths (haddockName, haddockPref) import Distribution.Simple.Utils ( createDirectoryIfMissingVerbose , installDirectoryContents, installOrdinaryFile, isInSearchPath , die, info, notice, warn, matchDirFileGlob ) import Distribution.Simple.Compiler ( CompilerFlavor(..), compilerFlavor ) import Distribution.Simple.Setup (CopyFlags(..), fromFlag) import qualified Distribution.Simple.GHC as GHC import qualified Distribution.Simple.GHCJS as GHCJS import qualified Distribution.Simple.JHC as JHC import qualified Distribution.Simple.LHC as LHC import qualified Distribution.Simple.UHC as UHC import qualified Distribution.Simple.HaskellSuite as HaskellSuite import Control.Monad (when, unless) import System.Directory ( doesDirectoryExist, doesFileExist ) import System.FilePath ( takeFileName, takeDirectory, (</>), isAbsolute ) import Distribution.Verbosity import Distribution.Text ( display ) -- |Perform the \"@.\/setup install@\" and \"@.\/setup copy@\" -- actions. Move files into place based on the prefix argument. install :: PackageDescription -- ^information from the .cabal file -> LocalBuildInfo -- ^information from the configure step -> CopyFlags -- ^flags sent to copy or install -> IO () install pkg_descr lbi flags = do let distPref = fromFlag (copyDistPref flags) verbosity = fromFlag (copyVerbosity flags) copydest = fromFlag (copyDest flags) installDirs@(InstallDirs { bindir = binPref, libdir = libPref, -- dynlibdir = dynlibPref, --see TODO below datadir = dataPref, docdir = docPref, htmldir = htmlPref, haddockdir = interfacePref, includedir = incPref}) -- Using the library clbi for binPref is a hack; -- binPref should be computed per executable = absoluteInstallDirs pkg_descr lbi copydest --TODO: decide if we need the user to be able to control the libdir -- for shared libs independently of the one for static libs. If so -- it should also have a flag in the command line UI -- For the moment use dynlibdir = libdir dynlibPref = libPref progPrefixPref = substPathTemplate (packageId pkg_descr) lbi (progPrefix lbi) progSuffixPref = substPathTemplate (packageId pkg_descr) lbi (progSuffix lbi) unless (hasLibs pkg_descr || hasExes pkg_descr) $ die "No executables and no library found. Nothing to do." docExists <- doesDirectoryExist $ haddockPref distPref pkg_descr info verbosity ("directory " ++ haddockPref distPref pkg_descr ++ " does exist: " ++ show docExists) installDataFiles verbosity pkg_descr dataPref when docExists $ do createDirectoryIfMissingVerbose verbosity True htmlPref installDirectoryContents verbosity (haddockPref distPref pkg_descr) htmlPref -- setPermissionsRecursive [Read] htmlPref -- The haddock interface file actually already got installed -- in the recursive copy, but now we install it where we actually -- want it to be (normally the same place). We could remove the -- copy in htmlPref first. let haddockInterfaceFileSrc = haddockPref distPref pkg_descr </> haddockName pkg_descr haddockInterfaceFileDest = interfacePref </> haddockName pkg_descr -- We only generate the haddock interface file for libs, So if the -- package consists only of executables there will not be one: exists <- doesFileExist haddockInterfaceFileSrc when exists $ do createDirectoryIfMissingVerbose verbosity True interfacePref installOrdinaryFile verbosity haddockInterfaceFileSrc haddockInterfaceFileDest let lfiles = licenseFiles pkg_descr unless (null lfiles) $ do createDirectoryIfMissingVerbose verbosity True docPref sequence_ [ installOrdinaryFile verbosity lfile (docPref </> takeFileName lfile) | lfile <- lfiles ] let buildPref = buildDir lbi when (hasLibs pkg_descr) $ notice verbosity ("Installing library in " ++ libPref) when (hasExes pkg_descr) $ do notice verbosity ("Installing executable(s) in " ++ binPref) inPath <- isInSearchPath binPref when (not inPath) $ warn verbosity ("The directory " ++ binPref ++ " is not in the system search path.") -- install include files for all compilers - they may be needed to compile -- haskell files (using the CPP extension) -- when (hasLibs pkg_descr) $ installIncludeFiles verbosity pkg_descr incPref withLibLBI pkg_descr lbi $ case compilerFlavor (compiler lbi) of GHC -> GHC.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr GHCJS -> GHCJS.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr LHC -> LHC.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr JHC -> JHC.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr UHC -> UHC.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr HaskellSuite _ -> HaskellSuite.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr _ -> \_ _ -> die $ "installing with " ++ display (compilerFlavor (compiler lbi)) ++ " is not implemented" withExe pkg_descr $ case compilerFlavor (compiler lbi) of GHC -> GHC.installExe verbosity lbi installDirs buildPref (progPrefixPref, progSuffixPref) pkg_descr GHCJS -> GHCJS.installExe verbosity lbi installDirs buildPref (progPrefixPref, progSuffixPref) pkg_descr LHC -> LHC.installExe verbosity lbi installDirs buildPref (progPrefixPref, progSuffixPref) pkg_descr JHC -> JHC.installExe verbosity binPref buildPref (progPrefixPref, progSuffixPref) pkg_descr UHC -> \_ -> return () HaskellSuite {} -> \_ -> return () _ -> \_ -> die $ "installing with " ++ display (compilerFlavor (compiler lbi)) ++ " is not implemented" -- register step should be performed by caller. -- | Install the files listed in data-files -- installDataFiles :: Verbosity -> PackageDescription -> FilePath -> IO () installDataFiles verbosity pkg_descr destDataDir = flip mapM_ (dataFiles pkg_descr) $ \ file -> do let srcDataDir = dataDir pkg_descr files <- matchDirFileGlob srcDataDir file let dir = takeDirectory file createDirectoryIfMissingVerbose verbosity True (destDataDir </> dir) sequence_ [ installOrdinaryFile verbosity (srcDataDir </> file') (destDataDir </> file') | file' <- files ] -- | Install the files listed in install-includes -- installIncludeFiles :: Verbosity -> PackageDescription -> FilePath -> IO () installIncludeFiles verbosity PackageDescription { library = Just lib } destIncludeDir = do incs <- mapM (findInc relincdirs) (installIncludes lbi) sequence_ [ do createDirectoryIfMissingVerbose verbosity True destDir installOrdinaryFile verbosity srcFile destFile | (relFile, srcFile) <- incs , let destFile = destIncludeDir </> relFile destDir = takeDirectory destFile ] where relincdirs = "." : filter (not.isAbsolute) (includeDirs lbi) lbi = libBuildInfo lib findInc [] file = die ("can't find include file " ++ file) findInc (dir:dirs) file = do let path = dir </> file exists <- doesFileExist path if exists then return (file, path) else findInc dirs file installIncludeFiles _ _ _ = die "installIncludeFiles: Can't happen?"
edsko/cabal
Cabal/src/Distribution/Simple/Install.hs
bsd-3-clause
8,561
0
18
2,044
1,692
879
813
132
13
module Backend.AST ( module Backend.AST , module Frontend.Types ) where import Data.Map (Map) import qualified Data.Map as M import Frontend.Types import Frontend.Values import Frontend.Primitives import Internal -- SSA-like lowlevel IR type Label = Name type LType = Type type LTypeEnv = Map Name LType type LBinder = (Name, LType) type LProgram = [LDecl] data LDecl = LFunDecl Type Name [LBinder] [LBlock] -- | LConstDecl data LBlock = LBlock Label [LBinder] [LStatement] LTransfur type LStatement = (LBinder, LInst) data LInst = LVar Name | LValue Value | LCall Name [Name] | LOp PrimOp [Name] | LCon Int [Name] | LTuple [Name] | LProj Int Name | LExtCall String [Name] | LCast LType Name data LTransfur = LReturn Name | LIf CmpOp Name Name Label Label | LMatch Name [(Int, Label)] (Maybe Label) | LGoto Label [Name] | LTailCall Name [Name]
alpicola/mel
src/Backend/AST.hs
mit
1,022
0
8
317
298
181
117
31
0
import qualified Test.Algorithms as Algorithms import qualified Test.Attributes as Attributes import qualified Test.Basic as Basic import Test.Tasty main :: IO () main = defaultMain $ testGroup "Haskell-igraph Tests" [ Basic.tests , Algorithms.tests , Attributes.tests ]
kaizhang/haskell-igraph
tests/test.hs
mit
303
0
8
67
69
42
27
9
1
-- | Defines an abstract evaluation context. module Nix.Evaluator.AbstractContext where import Nix.Common import Nix.Evaluator.Errors -- | Types of directories, as defined in the nix manual. data FileType = RegularType | DirectoryType | SymlinkType | UnknownType deriving (Show, Eq, Ord, Enum) -- | A representation of directory structure. Directory contents are -- wrapped in some monadic action, which means we don't need to parse -- an entire (potentially huge) directory. data FileSystemRep m = File Text -- ^ A file, with its contents. | Symlink FilePath -- ^ A symlink, with some path referenced. | Directory (Map Text (m DirRep)) -- ^ A directory. -- | Return the type of a filesystem representation. fileTypeOf :: FileSystemRep m -> FileType fileTypeOf = \case File _ -> RegularType Symlink _ -> SymlinkType Directory _ -> DirectoryType class Monad m => ReadFileSystem m where -- | Given a file path, return an abstract representation of its -- contents, if it exists. Otherwise, return 'Nothing'. readPath :: FilePath -> m (Maybe (FileSystemRep m)) -- | If the given file path exists, return its type (else 'Nothing'). typeOfPath :: ReadFileSystem m => FilePath -> m (Maybe FileType) typeOfPath = map fileTypeOf . readPath class Monad m => -- | An abstraction of the operations we'll need to perform during -- evaluation, in particular performing effectful actions. class (MonadError EvalError m, WriteMessage m) => Nix m where -- | Read a file. If the file doesn't exist, throw 'FileDoesNotExist'. readFileFromDisk :: FilePath -> m Text -- | Read directory, and return its contents as map of (name -> type). listDirectory :: FilePath -> m (Record FileType) -- | Write a file to the nix store. writeFileToStore :: FilePath -> Text
adnelson/nix-eval
src/Nix/Evaluator/AbstractContext.hs
mit
1,789
1
12
331
303
164
139
-1
-1
{-# OPTIONS_GHC -Wall #-} import System.Directory import System.FilePath import System.Environment import Data.List hiding(find) main :: IO () main = do [s, d] <- getArgs r <- find s d print r find :: String -> FilePath -> IO (Maybe FilePath) find s d = do fs <- getDirectoryContents d let fs' = sort $ filter (`notElem` [".", ".."]) fs if s `elem` fs' then return (Just (d </> s)) else loop fs' where loop [] = return Nothing loop (f: fs) = do let d' = d </> f isdir <- doesDirectoryExist d' if isdir then do r <- find s d' case r of Just _ -> return r Nothing -> loop fs else loop fs find' :: String -> FilePath -> IO [FilePath] find' s d = do fs <- getDirectoryContents d let fs' = sort $ filter (`notElem` [".", ".."]) fs (recurssiveMatch, _) <- foldl' dealJoin (return ([], d)) fs' return recurssiveMatch where dealJoin :: IO ([FilePath], FilePath) -> String -> IO ([FilePath], FilePath) dealJoin tuple name = do (acc, root) <- tuple if s == name then return ((root </> name):acc, root) else do let path = root </> name isdir <- doesDirectoryExist path if isdir then do rec <- find' s path return (rec++acc, root) else return (acc, root)
Forec/learn
2017.3/Parallel Haskell/ch13/findseq.hs
mit
1,364
1
17
435
567
287
280
44
5
module Abc.DeepSeq () where import Control.DeepSeq import Abc.Def instance NFData Abc where rnf (Abc a b c d e f g h i j k l m) = a `deepseq` b `deepseq` c `deepseq` d `deepseq` e `deepseq` f `deepseq` g `deepseq` h `deepseq` i `deepseq` j `deepseq` k `deepseq` l `deepseq` m `deepseq` () instance NFData NSInfo where rnf (NSInfo_Namespace a) = a `deepseq` () rnf (NSInfo_PackageNamespace a) = a `deepseq` () rnf (NSInfo_PackageInternalNs a) = a `deepseq` () rnf (NSInfo_ProtectedNamespace a) = a `deepseq` () rnf (NSInfo_ExplicitNamespace a) = a `deepseq` () rnf (NSInfo_StaticProtectedNs a) = a `deepseq` () rnf (NSInfo_PrivateNs a) = a `deepseq` () rnf _ = () instance NFData Multiname where rnf (Multiname_QName a b) = a `deepseq` b `deepseq` () rnf (Multiname_QNameA a b) = a `deepseq` b `deepseq` () rnf (Multiname_RTQName a) = a `deepseq` () rnf (Multiname_RTQNameA a) = a `deepseq` () rnf (Multiname_Multiname a b) = a `deepseq` b `deepseq` () rnf (Multiname_MultinameA a b) = a `deepseq` b `deepseq` () rnf (Multiname_MultinameL a) = a `deepseq` () rnf (Multiname_MultinameLA a) = a `deepseq` () rnf Multiname_Any = () instance NFData MethodSignature where rnf (MethodSignature a b c d e f) = a `deepseq` b `deepseq` c `deepseq` d `deepseq` e `deepseq` f `deepseq` () instance NFData CPC where --rnf (CPC_Undefined) = a `deepseq` () rnf (CPC_Utf8 a) = a `deepseq` () rnf (CPC_Decimal a) = a `deepseq` () rnf (CPC_Int a) = a `deepseq` () rnf (CPC_Uint a) = a `deepseq` () rnf (CPC_PrivateNamespace a) = a `deepseq` () rnf (CPC_Double a) = a `deepseq` () rnf (CPC_QName a) = a `deepseq` () rnf (CPC_Namespace a) = a `deepseq` () rnf (CPC_Multiname a) = a `deepseq` () --rnf (CPC_False) = a `deepseq` () --rnf (CPC_True) = a `deepseq` () --rnf (CPC_Null) = a `deepseq` () rnf (CPC_QNameA a) = a `deepseq` () rnf (CPC_MultinameA a) = a `deepseq` () rnf (CPC_RTQName a) = a `deepseq` () rnf (CPC_RTQNameA a) = a `deepseq` () rnf (CPC_RTQNameL a) = a `deepseq` () rnf (CPC_RTQNameLA a) = a `deepseq` () rnf (CPC_NameL a) = a `deepseq` () rnf (CPC_NameLA a) = a `deepseq` () rnf (CPC_NamespaceSet a) = a `deepseq` () rnf (CPC_PackageNamespace a) = a `deepseq` () rnf (CPC_PackageInternalNs a) = a `deepseq` () rnf (CPC_ProtectedNamespace a) = a `deepseq` () rnf (CPC_ExplicitNamespace a) = a `deepseq` () rnf (CPC_StaticProtectedNs a) = a `deepseq` () rnf (CPC_MultinameL a) = a `deepseq` () rnf (CPC_MultinameLA a) = a `deepseq` () rnf _ = () instance NFData Metadata where rnf (Metadata a b) = a `deepseq` b `deepseq` () instance NFData InstanceInfo where rnf (InstanceInfo a b c d e f g) = a `deepseq` b `deepseq` c `deepseq` d `deepseq` e `deepseq` f `deepseq` g `deepseq` () instance NFData TraitsInfo where rnf (TraitsInfo a b c d e) = a `deepseq` b `deepseq` c `deepseq` d `deepseq` e `deepseq` () instance NFData TraitType where rnf (TraitVar a b c d) = a `deepseq` b `deepseq` c `deepseq` d `deepseq` () rnf (TraitConst a b c d) = a `deepseq` b `deepseq` c `deepseq` d `deepseq` () rnf (TraitMethod a b) = a `deepseq` b `deepseq` () rnf (TraitGetter a b) = a `deepseq` b `deepseq` () rnf (TraitSetter a b) = a `deepseq` b `deepseq` () rnf (TraitClass a b) = a `deepseq` b `deepseq` () rnf (TraitFunction a b) = a `deepseq` b `deepseq` () instance NFData ClassInfo where rnf (ClassInfo a b) = a `deepseq` b `deepseq` () instance NFData ScriptInfo where rnf (ScriptInfo a b) = a `deepseq` b `deepseq` () instance NFData MethodBody where rnf (MethodBody a b c d e f g h) = a `deepseq` b `deepseq` c `deepseq` d `deepseq` e `deepseq` f `deepseq` g `deepseq` h `deepseq` () instance NFData Exception where rnf (Exception a b c d e) = a `deepseq` b `deepseq` c `deepseq` d `deepseq` e `deepseq` () instance NFData OpCode where {- 0x01 -} {-Breakpoint-} {- 0x02 -} {-Nop-} {- 0x03 -} {-Throw-} {- 0x04 -} rnf (GetSuper a) = a `deepseq` () {- 0x05 -} rnf (SetSuper a) = a `deepseq` () {- 0x06 -} rnf (DefaultXmlNamespace a) = a `deepseq` () {- 0x07 -} {-DefaultXmlNamespaceL-} {- 0x08 -} rnf (Kill a) = a `deepseq` () {- 0x09 -} {-Label-} {- 0x0A -} {- 0x0B -} {- 0x0C -} rnf (IfNotLessThan a) = a `deepseq` () {- 0x0D -} rnf (IfNotLessEqual a) = a `deepseq` () {- 0x0E -} rnf (IfNotGreaterThan a) = a `deepseq` () {- 0x0F -} rnf (IfNotGreaterEqual a) = a `deepseq` () {- 0x10 -} rnf (Jump a) = a `deepseq` () {- 0x11 -} rnf (IfTrue a) = a `deepseq` () {- 0x12 -} rnf (IfFalse a) = a `deepseq` () {- 0x13 -} rnf (IfEqual a) = a `deepseq` () {- 0x14 -} rnf (IfNotEqual a) = a `deepseq` () {- 0x15 -} rnf (IfLessThan a) = a `deepseq` () {- 0x16 -} rnf (IfLessEqual a) = a `deepseq` () {- 0x17 -} rnf (IfGreaterThan a) = a `deepseq` () {- 0x18 -} rnf (IfGreaterEqual a) = a `deepseq` () {- 0x19 -} rnf (IfStrictEqual a) = a `deepseq` () {- 0x1A -} rnf (IfStrictNotEqual a) = a `deepseq` () {- 0x1B -} rnf (LookupSwitch a b) = a `deepseq` b `deepseq` () {- 0x1C -} {-PushWith-} {- 0x1D -} {-PopScope-} {- 0x1E -} {-NextName-} {- 0x1F -} {-HasNext-} {- 0x20 -} {-PushNull-} {- 0x21 -} {-PushUndefined-} {- 0x22 -} {-PushConstant-} {- 0x23 -} {-NextValue-} {- 0x24 -} rnf (PushByte a) = a `deepseq` () {- 0x25 -} rnf (PushShort a) = a `deepseq` () {- 0x26 -} {-PushTrue-} {- 0x27 -} {-PushFalse-} {- 0x28 -} {-PushNaN-} {- 0x29 -} {-Pop-} {- 0x2A -} {-Dup-} {- 0x2B -} {-Swap-} {- 0x2C -} rnf (PushString a) = a `deepseq` () {- 0x2D -} rnf (PushInt a) = a `deepseq` () {- 0x2E -} rnf (PushUInt a) = a `deepseq` () {- 0x2F -} rnf (PushDouble a) = a `deepseq` () {- 0x30 -} {-PushScope-} {- 0x31 -} rnf (PushNamespace a) = a `deepseq` () {- 0x32 -} rnf (HasNext2 a b) = a `deepseq` b `deepseq` () {- 0x33 -} {-PushDecimal-} {- 0x34 -} {-PushDNaN-} {- 0x35 -} {- 0x36 -} {- 0x37 -} {- 0x38 -} {- 0x39 -} {- 0x3A -} {- 0x3B -} {- 0x3C -} {- 0x3D -} {- 0x3E -} {- 0x3F -} {- 0x40 -} rnf (NewFunction a) = a `deepseq` () {- 0x41 -} rnf (Call a) = a `deepseq` () {- 0x42 -} rnf (Construct a) = a `deepseq` () {- 0x43 -} rnf (CallMethod a b) = a `deepseq` b `deepseq` () {- 0x44 -} rnf (CallStatic a b) = a `deepseq` b `deepseq` () {- 0x45 -} rnf (CallSuper a b) = a `deepseq` b `deepseq` () {- 0x46 -} rnf (CallProperty a b) = a `deepseq` b `deepseq` () {- 0x47 -} {-ReturnVoid-} {- 0x48 -} {-ReturnValue-} {- 0x49 -} rnf (ConstructSuper a) = a `deepseq` () {- 0x4A -} rnf (ConstructProp a b) = a `deepseq` b `deepseq` () {- 0x4B -} {-CallSuperId-} {- 0x4C -} rnf (CallPropLex a b) = a `deepseq` b `deepseq` () {- 0x4D -} {-CallInterface-} {- 0x4E -} rnf (CallSuperVoid a b) = a `deepseq` b `deepseq` () {- 0x4F -} rnf (CallPropVoid a b) = a `deepseq` b `deepseq` () {- 0x50 -} {- 0x51 -} {- 0x52 -} {- 0x53 -} {-ApplyType-} {- 0x55 -} rnf (NewObject a) = a `deepseq` () {- 0x56 -} rnf (NewArray a) = a `deepseq` () {- 0x57 -} {-NewActivation-} {- 0x58 -} rnf (NewClass a) = a `deepseq` () {- 0x59 -} rnf (GetDescendants a) = a `deepseq` () {- 0x5A -} rnf (NewCatch a) = a `deepseq` () {- 0x5B -} {-FindPropGlobalStrict-} {- 0x5C -} {-FindPropGlobal-} {- 0x5D -} rnf (FindPropStrict a) = a `deepseq` () {- 0x5E -} rnf (FindProperty a) = a `deepseq` () {- 0x5F -} {-FindDef-} {- 0x60 -} rnf (GetLex a) = a `deepseq` () {- 0x61 -} rnf (SetProperty a) = a `deepseq` () {- 0x62 -} rnf (GetLocal a) = a `deepseq` () {- 0x63 -} rnf (SetLocal a) = a `deepseq` () {- 0x64 -} {-GetGlobalScope-} {- 0x65 -} rnf (GetScopeObject a) = a `deepseq` () {- 0x66 -} rnf (GetProperty a) = a `deepseq` () {- 0x67 -} {-GetPropertyLate-} {- 0x68 -} rnf (InitProperty a) = a `deepseq` () {- 0x69 -} {-SetPropertyLate-} {- 0x6A -} rnf (DeleteProperty a) = a `deepseq` () {- 0x6B -} {-DeletePropertyLate-} {- 0x6C -} rnf (GetSlot a) = a `deepseq` () {- 0x6D -} rnf (SetSlot a) = a `deepseq` () {- 0x6E -} rnf (GetGlobalSlot a) = a `deepseq` () {- 0x6F -} rnf (SetGlobalSlot a) = a `deepseq` () {- 0x70 -} {-ConvertString-} {- 0x71 -} {-EscXmlElem-} {- 0x72 -} {-EscXmlAttr-} {- 0x73 -} {-ConvertInt-} {- 0x74 -} {-ConvertUInt-} {- 0x75 -} {-ConvertDouble-} {- 0x76 -} {-ConvertBoolean-} {- 0x77 -} {-ConvertObject-} {- 0x78 -} {-CheckFilter-} {- 0x79 -} {- 0x7A -} {- 0x7B -} {- 0x7C -} {- 0x7D -} {- 0x7E -} {- 0x7F -} {- 0x80 -} rnf (Coerce a) = a `deepseq` () {- 0x81 -} {-CoerceBoolean-} {- 0x82 -} {-CoerceAny-} {- 0x83 -} {-CoerceInt-} {- 0x84 -} {-CoerceDouble-} {- 0x85 -} {-CoerceString-} {- 0x86 -} rnf (AsType a) = a `deepseq` () {- 0x87 -} {-AsTypeLate-} {- 0x88 -} {-CoerceUInt-} {- 0x89 -} {-CoerceObject-} {- 0x8A -} {- 0x8B -} {- 0x8C -} {- 0x8D -} {- 0x8E -} {- 0x8F -} {- 0x90 -} {-Negate-} {- 0x91 -} {-Increment-} {- 0x92 -} {-IncLocal-} {- 0x93 -} {-Decrement-} {- 0x94 -} rnf (DecLocal a) = a `deepseq` () {- 0x95 -} {-TypeOf-} {- 0x96 -} {-Not-} {- 0x97 -} {-BitNot-} {- 0x98 -} {- 0x99 -} {- 0x9A -} {-Concat-} {- 0x9B -} {-AddDouble-} {- 0x9C -} {- 0x9D -} {- 0x9E -} {- 0x9F -} {- 0xA0 -} {-Add-} {- 0xA1 -} {-Subtract-} {- 0xA2 -} {-Multiply-} {- 0xA3 -} {-Divide-} {- 0xA4 -} {-Modulo-} {- 0xA5 -} {-ShiftLeft-} {- 0xA6 -} {-ShiftRight-} {- 0xA7 -} {-ShiftRightUnsigned-} {- 0xA8 -} {-BitAnd-} {- 0xA9 -} {-BitOr-} {- 0xAA -} {-BitXor-} {- 0xAB -} {-Equals-} {- 0xAC -} {-StrictEquals-} {- 0xAD -} {-LessThan-} {- 0xAE -} {-LessEquals-} {- 0xAF -} {-GreaterThan-} {- 0xB0 -} {-GreaterEquals-} {- 0xB1 -} {-InstanceOf-} {- 0xB2 -} rnf (IsType a) = a `deepseq` () {- 0xB3 -} {-IsTypeLate-} {- 0xB4 -} {-In-} {- 0xB5 -} {- 0xB6 -} {- 0xB7 -} {- 0xB8 -} {- 0xB9 -} {- 0xBA -} {- 0xBB -} {- 0xBC -} {- 0xBD -} {- 0xBE -} {- 0xBF -} {- 0xC0 -} {-IncrementInt-} {- 0xC1 -} {-DecrementInt-} {- 0xC2 -} rnf (IncLocalInt a) = a `deepseq` () {- 0xC3 -} rnf (DecLocalInt a) = a `deepseq` () {- 0xC4 -} {-NegateInt-} {- 0xC5 -} {-AddInt-} {- 0xC6 -} {-SubtractInt-} {- 0xC7 -} {-MultiplyInt-} {- 0xC8 -} {- 0xC9 -} {- 0xCA -} {- 0xCB -} {- 0xCC -} {- 0xCD -} {- 0xCE -} {- 0xCF -} {- 0xD0 -} {-GetLocal0-} {- 0xD1 -} {-GetLocal1-} {- 0xD2 -} {-GetLocal2-} {- 0xD3 -} {-GetLocal3-} {- 0xD4 -} {-SetLocal0-} {- 0xD5 -} {-SetLocal1-} {- 0xD6 -} {-SetLocal2-} {- 0xD7 -} {-SetLocal3-} {- 0xD8 -} {- 0xD9 -} {- 0xDA -} {- 0xDB -} {- 0xDC -} {- 0xDD -} {- 0xDE -} {- 0xDF -} {- 0xE0 -} {- 0xE1 -} {- 0xE2 -} {- 0xE3 -} {- 0xE4 -} {- 0xE5 -} {- 0xE6 -} {- 0xE7 -} {- 0xE8 -} {- 0xE9 -} {- 0xEA -} {- 0xEB -} {- 0xEC -} {- 0xED -} {- 0xEE -} {- 0xEF -} rnf (Debug a b c d) = a `deepseq` b `deepseq` c `deepseq` d `deepseq` () {- 0xF0 -} rnf (DebugLine a) = a `deepseq` () {- 0xF1 -} rnf (DebugFile a) = a `deepseq` () {- 0xF2 -} {-BreakpointLine-} {- 0xF3 -} {- 0xF5 -} {- 0xF6 -} {- 0xF7 -} {- 0xF8 -} {- 0xF9 -} {- 0xFA -} {- 0xFB -} {- 0xFC -} {- 0xFD -} {- 0xFE -} {- 0xFF -} rnf _ = ()
phylake/avm3
abc/deepseq.hs
mit
10,955
0
18
2,426
3,804
2,274
1,530
193
0
module Euler.Problem021Test (suite) where import Test.Tasty (testGroup, TestTree) import Test.Tasty.HUnit import Euler.Problem021 suite :: TestTree suite = testGroup "Problem021" [ testCase "unamicability of 6" testUnamicability6 , testCase "amicability of 220" testAmicability220 , testCase "amicability of 284" testAmicability284 ] testUnamicability6 :: Assertion testUnamicability6 = False @=? amicable 6 testAmicability220 :: Assertion testAmicability220 = True @=? amicable 220 testAmicability284 :: Assertion testAmicability284 = True @=? amicable 284
whittle/euler
test/Euler/Problem021Test.hs
mit
596
0
7
103
125
69
56
15
1
{-# LANGUAGE OverloadedStrings #-} module Day4 (day4, day4', run, decrypt, RoomData(..)) where import Data.Char (chr, isLower, ord) import Data.Either (rights) import Data.List (group, sort, sortOn) import Text.Parsec ( ParseError , between , char , digit , endBy1 , lower , many1 , parse ) data RoomData = RoomData [String] Int String deriving (Eq, Ord, Show) parseRoomData :: String -> Either ParseError RoomData parseRoomData = parse parseImpl "" where parseImpl = do encryptedName <- endBy1 (many1 lower) (char '-') sectorId <- read <$> many1 digit checksum <- between (char '[') (char ']') (many1 lower) return $ RoomData encryptedName sectorId checksum isValid :: RoomData -> Bool isValid (RoomData name _ checksum) = (take 5 . map head . sortOn (negate . length) . group . sort . concat $ name) == checksum decrypt :: RoomData -> String decrypt (RoomData name sectorId _) = unwords . map (map (toChar . shift . toInt)) $ name where toInt = subtract 97 . ord toChar = chr . (+) 97 shift x = (x + sectorId) `mod` 26 sectorId :: RoomData -> Int sectorId (RoomData _ s _) = s -- Final, top-level exports day4 :: String -> Int day4 = sum . map (\(RoomData _ i _) -> i) . filter isValid . rights . map parseRoomData . lines day4' :: String -> Int day4' = sectorId . head . filter ((==) "northpole object storage" . decrypt) . filter isValid . rights . map parseRoomData . lines -- Read from input file run :: IO () run = do putStrLn "Day 4 results: " input <- readFile "inputs/day4.txt" putStrLn $ " " ++ show (day4 input) putStrLn $ " " ++ show (day4' input)
brianshourd/adventOfCode2016
src/Day4.hs
mit
1,676
0
14
395
643
336
307
41
1
module Main where import Control.Monad.Logger (runStdoutLoggingT) import Database.Persist.Postgresql (createPostgresqlPool) import Network.Wai.Handler.Warp (run) import Network.Wai.Middleware.RequestLogger (logStdoutDev) import App (app) import Models (connStr) main :: IO () main = do pool <- runStdoutLoggingT $ createPostgresqlPool connStr 5 application <- app pool run 8080 $ logStdoutDev application
houli/distributed-file-system
directory-service/app/Main.hs
mit
414
0
9
53
120
67
53
12
1
-- file: ch04/EfficientList.hs myDumbExample xs = if length xs > 0 then head xs else 'Z' -- no good, because length needs to traverse the entire list -- Better: mySmartExample xs = if not (null xs) then head xs else 'Z' -- Or let pattern matching to the work: myOtherExample (x:_) = x myOtherExample [] = 'Z'
supermitch/learn-haskell
real-world-haskell/ch04/EfficientList.hs
mit
400
0
8
148
84
44
40
8
2
import Test.HTTP import Data.List (isInfixOf) main = defaultMain $ httpTestCase "BayesHive landing page" "https://bayeshive.com" $ do landing <- get "/" assert "Correct blog link" $ "href=\"https://bayeshive.com/blog\"" `isInfixOf` landing loginResult <- postForm "/auth/page/email/login" [("email", "[email protected]"), ("password", "secret")] doclist <- getJSON "/doclist" debug $ show (doclist:: [String]) return ()
openbrainsrc/http-test
test.hs
mit
471
0
11
100
127
64
63
11
1
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} module Y2017.M09.D28.Solution where {-- Yesterday, and the two days prior, we focused on ETL for names, a tricky subject that deserve 3 (or even more) days of exercises. Today, we're going back to the reified article concept from the days prior and store those articles into the database. So, we're storing articles with metadata, raw names, and then parsing the names. Looks like we've got an ETL for articles on our hands! --} import Data.Aeson import Data.Aeson.Encode.Pretty import Data.ByteString.Lazy.Char8 (ByteString) import qualified Data.ByteString.Lazy.Char8 as BL import Data.Map (Map) import qualified Data.Map as Map import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.SqlQQ import Database.PostgreSQL.Simple.ToRow import Database.PostgreSQL.Simple.ToField import Network.HTTP.Conduit -- below imports available via 1HaskellADay git repository import Store.SQL.Connection (connectInfo) import Store.SQL.Util.Indexed import Store.SQL.Util.Inserts (look, byt, byteStr, inserter) import Y2017.M09.D22.Exercise (dir, arts) import Y2017.M09.D25.Solution import Y2017.M09.D26.Solution (extractArticles) insertArtsStmt :: Query insertArtsStmt = [sql|INSERT INTO article (src_id,title,author,publish_dt,url, abstract,full_text,people,locations) VALUES (?,?,?,?,?,?,?,?,?) returning id|] -- create a ToRow instance of the Article type: instance ToRow Article where toRow art = [toField (srcId art),toField (title art), toField (author art), lookm "Publication date" art, toField (url art), byt abstract art, byt fullText art, lookm "People" art, lookm "Location" art] where lookm r = look r metadata -- Now, extract the articles from the compressed archive (extractArticles), -- and insert the articles into the database: insertArts :: Connection -> [Article] -> IO [Index] insertArts = insertRows insertArtsStmt -- Then say: YAY! and throw confetti! {-- >>> articles <- extractArticles <$> BL.readFile (dir ++ arts) >>> connectInfo ConnectInfo {connectHost = "...",...} >>> conn <- connect it >>> insertArts conn articles >>> close conn $ SELECT count(1) FROM article; 11 YAY! $ SELECT abstract FROM article WHERE id in (SELECT max(id) FROM article); In a poem called "Three Modes of History and Culture," from 1969, a kind of updated Muddy Waters blues, ... YAY! THROWS CONFETTI! --}
geophf/1HaskellADay
exercises/HAD/Y2017/M09/D28/Solution.hs
mit
2,500
0
9
453
337
207
130
29
1
{-# LANGUAGE MultiParamTypeClasses #-} -- | This module provides the 'Buffer' type class that abstracts the array type that is being used for I\/O. Inspired by hsndfile. module Sound.PortAudio.Buffer where import Sound.PortAudio import qualified Sound.PortAudio.Base as Base import Foreign.C.Types (CULong) import Foreign.ForeignPtr (ForeignPtr, newForeignPtr_) -- | Buffer class for I\/O on PortAudio Buffers. class Buffer a e where -- | Construct a buffer from a 'ForeignPtr' and the element count. fromForeignPtr :: ForeignPtr e -> Int -> IO (a e) -- | Retrieve from a buffer a 'ForeignPtr' pointing to its data and an element count. toForeignPtr :: a e -> IO (ForeignPtr e, Int) -- | Type of callbacks that will be called with input samples that should provide output samples. -- This can work with arbitrary user specified buffers, as opposed to raw C arrays (ForeignPtr). -- See @StreamCallback@ for the more information. type BuffStreamCallback input output a b = Base.PaStreamCallbackTimeInfo -- ^ Timing information for the input and output -> [StreamCallbackFlag] -- ^ Status flags -> CULong -- ^ # of input samples -> a input -- ^ input samples -> b output -- ^ where to write output samples -> IO StreamResult -- ^ What to do with the stream, plus the output to stream -- | Wrap a buffer callback into the generic stream callback type. buffCBtoRawCB :: (StreamFormat input, StreamFormat output, Buffer a input, Buffer b output) => BuffStreamCallback input output a b -> Stream input output -> StreamCallback input output buffCBtoRawCB func strm = \a b c d e -> do fpA <- newForeignPtr_ d -- We will not free, as callback system will do that for us fpB <- newForeignPtr_ e -- We will not free, as callback system will do that for us storeInp <- fromForeignPtr fpA (fromIntegral $ numInputChannels strm * c) storeOut <- fromForeignPtr fpB (fromIntegral $ numOutputChannels strm * c) func a b c storeInp storeOut -- | This Function is a high level version of @readStream@ which does not deal with Pointers -- and can operate on any type which is an instance of @Buffer@, possible a storable vector. It is assumed that -- the buffer is correctly sized, its length must be the number of frames times the channels in the underlying output stream. readBufferStream :: (Buffer a input, StreamFormat input, StreamFormat output) => Stream input output -> CULong -> a input -> IO (Maybe Error) readBufferStream a b c = do (c', _) <- toForeignPtr c readStream a b c' -- | This Function is a high level version of @writeStream@ which does not deal with Pointers -- and can operate on any type which is an instance of @Buffer@, possible a storable vector. It is assumed that -- the buffer is correctly sized, its length must be the number of frames times the channels in the underlying output stream. writeBufferStream :: (Buffer a output, StreamFormat input, StreamFormat output) => Stream input output -> CULong -> a output -> IO (Maybe Error) writeBufferStream a b c = do (c', _) <- toForeignPtr c writeStream a b c'
sw17ch/portaudio
src/Sound/PortAudio/Buffer.hs
mit
3,244
0
13
738
534
279
255
32
1
{-# htermination foldM_ :: (a -> b -> IO a) -> a -> [b] -> IO () #-} import Monad
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Monad_foldM__4.hs
mit
82
0
3
20
5
3
2
1
0
-- List length. Tail Recursion with "foldl'". module Length where import Prelude hiding (length) import Data.List (foldl') length :: [t] -> Integer length = foldl' (\lengthAccumulator item -> lengthAccumulator + 1) 0 {- GHCi> length "" length "1" length "12" -} -- 0 -- 1 -- 2 -- foldl :: (b -> a -> b) -> b -> [a] -> b -- foldl f z0 xs0 -- -- = lgo z0 xs0 -- -- where -- -- lgo z [] = z -- lgo z (x:xs) = lgo (z `f` x) xs -- length "123" -- = foldl (\lengthAccumulator item -> lengthAccumulator + 1) 0 "123" -- = lgo 0 "123" -- -- where f = \lengthAccumulator item -> lengthAccumulator + 1 -- -- = lgo 0 ('1' : "23") -- ~> lgo ( 0 `f` '1' ) "23" -- = lgo ( 0 `f` '1' ) ('2' : "3") -- ~> lgo ( (0 `f` '1') `f` '2' ) "3" -- = lgo ( (0 `f` '1') `f` '2' ) ('3' : []) -- ~> lgo ( ( (0 `f` '1') `f` '2' ) `f` '3' ) [] -- -- ~> ( ( (0 `f` '1') `f` '2' ) `f` '3' ) -- -- ~> ( ( (0 + 1) `f` '2' ) `f` '3' ) -- ~> ( ( 1 `f` '2' ) `f` '3' ) -- ~> ( ( 1 + 1 ) `f` '3' ) -- ~> ( 2 `f` '3' ) -- ~> ( 2 + 1 ) -- ~> 3 -- Results of "length" on a list that increases at each element by a power of 10 in an infinite list: samples :: [Integer] samples = [ length [1 .. 10^n] | n <- [1 ..] ] -- "sample n" represents the application of "length" to a list that contains 10^n elements: sample :: Int -> Integer sample number = samples !! number -- Helper, that formats numbers in scientific notation with powers of 10: format :: Integer -> String format 10 = "10" format integer = "10^" ++ (show $ truncate $ log (fromIntegral integer :: Float) / log 10) {- GHCi> :{ let count n = do putStrLn $ format $ sample n count (n + 1) in count 0 :} -} -- 10 -- 10^2 -- 10^3 -- 10^4 -- 10^5 -- 10^6 -- 10^7 -- -- Note: After little time there will be serious indications (system becomes slower) that -- the program runs out of memory. And we know why. -- The problem is the growing 'accumulator thunk' - the bigger the -- input size, the more memory is needed to store this not yet evaluated expression: -- -- ( ( ... ( (0 `f` "1") `f` "2" ) `f` ... ) `f` "N" ) -- -- N denotes the last element in a list of length N. Well on my computer this approach -- came with an improvement: 10^7 is in the result list of tail recursion, while -- primitive recursion got until 10^6. -- Profiling time and allocation for "length" at an input list that contains 10^5 elements: ------------------------------------------------------------------------------------------- profile :: IO () profile = print $ length [1 .. 10^5] -- -- System : Windows 8.1 Pro 64 Bit (6.3, Build 9600) -- Intel(R) Core(TM) i5 CPU M 460 @ 2.53 GHz (4 CPUs), ~2.5 GHz -- 4096 MB RAM -- -- Antivirus / ... : deactivated -- -- Compiler : GHC 7.8.3 -- -- -- Result: -- -------------------------------------------------------------------------------------------
pascal-knodel/haskell-craft
Examples/· Folds/length/foldl'/Length.hs
mit
3,339
0
11
1,131
284
189
95
14
1
{-# LANGUAGE DeriveDataTypeable #-} module RAM.State where -- $Id$ import RAM.Type import RAM.Memory import Machine.History import Autolib.ToDoc import Data.Typeable data State = State { schritt :: Int , memory :: Memory , todo :: Program -- noch auszuführen , past :: [State] -- vorige zustände } deriving ( Eq, Ord, Typeable ) instance ToDoc State where toDoc s = text "State" <+> dutch_record [ text "schritt" <+> equals <+> toDoc ( schritt s ) , text "memory" <+> equals <+> toDoc ( memory s ) , text "todo" <+> equals <+> clipped_dutch_list 1 ( map toDoc $ todo s ) ] instance History State where history = past
Erdwolf/autotool-bonn
src/RAM/State.hs
gpl-2.0
695
6
13
184
209
113
96
21
0
{- Copyright (C) 2017 WATANABE Yuki <[email protected]> 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, see <http://www.gnu.org/licenses/>. -} {-# LANGUAGE Trustworthy #-} module Flesh.Language.Parser.Syntax_RedirSpec (spec) where import Data.List.NonEmpty (NonEmpty((:|))) import Flesh.Language.Parser.Error import Flesh.Language.Parser.HereDoc import Flesh.Language.Parser.Syntax import Flesh.Language.Parser.TestUtil import Test.Hspec (Spec, context, describe, parallel) spec :: Spec spec = parallel $ do describe "redirect" $ do context "parses < operator" $ do expectPositionEof "29< foo" (fileOpPos <$> fill redirect) 0 expectSuccessEof "29< foo" "" (fileOpFd <$> fill redirect) 29 expectSuccessEof "29< foo" "" (fileOp <$> fill redirect) In expectShowEof "29< foo" "" (fileOpTarget <$> fill redirect) "foo" context "parses <> operator" $ do expectPositionEof "9<> foo" (fileOpPos <$> fill redirect) 0 expectSuccessEof "9<> foo" "" (fileOpFd <$> fill redirect) 9 expectSuccessEof "9<> foo" "" (fileOp <$> fill redirect) InOut expectShowEof "9<> foo" "" (fileOpTarget <$> fill redirect) "foo" context "parses > operator" $ do expectPositionEof "2> foo" (fileOpPos <$> fill redirect) 0 expectSuccessEof "2> foo" "" (fileOpFd <$> fill redirect) 2 expectSuccessEof "2> foo" "" (fileOp <$> fill redirect) Out expectShowEof "2> foo" "" (fileOpTarget <$> fill redirect) "foo" context "parses >> operator" $ do expectPositionEof "29>>foo" (fileOpPos <$> fill redirect) 0 expectSuccessEof "29>>foo" "" (fileOpFd <$> fill redirect) 29 expectSuccessEof "29>>foo" "" (fileOp <$> fill redirect) Append expectShowEof "29>>foo" "" (fileOpTarget <$> fill redirect) "foo" context "parses >| operator" $ do expectPositionEof "29>| bar" (fileOpPos <$> fill redirect) 0 expectSuccessEof "29>| bar" "" (fileOpFd <$> fill redirect) 29 expectSuccessEof "29>| bar" "" (fileOp <$> fill redirect) Clobber expectShowEof "29>| bar" "" (fileOpTarget <$> fill redirect) "bar" context "parses <& operator" $ do expectPositionEof "29<& foo" (fileOpPos <$> fill redirect) 0 expectSuccessEof "29<& foo" "" (fileOpFd <$> fill redirect) 29 expectSuccessEof "29<& foo" "" (fileOp <$> fill redirect) DupIn expectShowEof "29<& foo" "" (fileOpTarget <$> fill redirect) "foo" context "parses >& operator" $ do expectPositionEof "29>& foo" (fileOpPos <$> fill redirect) 0 expectSuccessEof "29>& foo" "" (fileOpFd <$> fill redirect) 29 expectSuccessEof "29>& foo" "" (fileOp <$> fill redirect) DupOut expectShowEof "29>& foo" "" (fileOpTarget <$> fill redirect) "foo" let yieldDummyContent = HereDocT $ return () <$ (drainOperators >> yieldContent []) rTester = hereDocOp <$> fill (redirect <* yieldDummyContent) context "parses << operator" $ do expectPositionEof "12<< END" (hereDocOpPos <$> rTester) 0 expectSuccessEof "12<< END" "" (hereDocFd <$> rTester) 12 expectSuccessEof "12<< END" "" (isTabbed <$> rTester) False expectShowEof "12<< END" "" (delimiter <$> rTester) "END" context "rejects quoted FD" $ do expectFailure "1\\2" (fill redirect) Soft UnknownReason 0 describe "hereDocLine" $ do context "contains expansions for unquoted delimiter" $ do expectShow "<<X\n$foo\\\nX\nX\n" "" completeLine "0<<X" context "does not contain expansions for quoted delimiter" $ do expectShow "<<\\X\n$foo\\\nX\n" "" completeLine "0<<\\X" expectShow "<<\"X\"\n$foo\\\nX\n" "" completeLine "0<<\"X\"" expectShow "<<'X'\n$foo\\\nX\n" "" completeLine "0<<'X'" expectShow "<<''\n$foo\\\n\n" "" completeLine "0<<''" describe "hereDocDelimiter" $ do context "is a token followed by a newline" $ do expectShow "<<X\nX\n" "" completeLine "0<<X" context "matches an unquoted token" $ do expectShow "<<\\X\nX\n" "" completeLine "0<<\\X" expectShow "<<\"X\"\nX\n" "" completeLine "0<<\"X\"" expectShow "<<'X'\nX\n" "" completeLine "0<<'X'" expectShow "<<''\n\n" "" completeLine "0<<''" context "can be indented for <<-" $ do expectShow "<<-X\nX\n" "" completeLine "0<<-X" expectShow "<<-X\n\tX\n" "" completeLine "0<<-X" expectShow "<<-X\n\t\t\tX\n" "" completeLine "0<<-X" describe "hereDocContent" $ do context "ends with delimiter" $ do expectShow "<<-X\nX\n" "" completeLine "0<<-X" let isExpectedReason (UnclosedHereDocContent (HereDocOp _ 0 True d)) | show d == "X" = True isExpectedReason _ = False in expectFailureEof' "<<-X\nfoo\n" completeLine Hard isExpectedReason 9 context "accumulates results" $ do let t = Token $ (undefined, Unquoted (Char 'E')) :| [] op = HereDocOp undefined 0 False t p = fill $ HereDocT $ fmap return $ hereDocContent op >> fmap (fmap (map snd)) drainContents expectShow "E\n" "" p "[]" expectShow "EE\nE\n" "" p "[EE\n]" expectShow "foo\nbar\nE\n" "" p "[foo\nbar\n]" describe "pendingHereDocContents" $ do context "parses 1 pending content" $ do expectShow "<<A\nA\n" "" completeLine "0<<A" context "parses 2 pending contents" $ do expectShow "<<A 1<<B\nA\nB\n" "" completeLine "0<<A 1<<B" context "leaves no pending contents" $ return () -- Nothing to test here because 'completeLine' would fail if any contents -- are left pending. describe "newlineHD" $ do context "parses newline" $ do expectSuccess "\n" "" (snd <$> fill newlineHD) '\n' expectPosition "\n" (fst <$> fill newlineHD) 0 context "parses pending here doc contents after newline" $ return () -- This property is tested in test cases for other properties. -- vim: set et sw=2 sts=2 tw=78:
magicant/flesh
hspec-src/Flesh/Language/Parser/Syntax_RedirSpec.hs
gpl-2.0
6,644
0
22
1,590
1,555
711
844
102
2
{- Copyright (C) 2007-2010 John MacFarlane <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Writers.Man Copyright : Copyright (C) 2007-2010 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable Conversion of 'Pandoc' documents to groff man page format. -} module Text.Pandoc.Writers.Man ( writeMan) where import Text.Pandoc.Definition import Text.Pandoc.Templates import Text.Pandoc.Shared import Text.Pandoc.Readers.TeXMath import Text.Printf ( printf ) import Data.List ( isPrefixOf, intersperse, intercalate ) import Text.Pandoc.Pretty import Control.Monad.State type Notes = [[Block]] data WriterState = WriterState { stNotes :: Notes , stHasTables :: Bool } -- | Convert Pandoc to Man. writeMan :: WriterOptions -> Pandoc -> String writeMan opts document = evalState (pandocToMan opts document) (WriterState [] False) -- | Return groff man representation of document. pandocToMan :: WriterOptions -> Pandoc -> State WriterState String pandocToMan opts (Pandoc (Meta title authors date) blocks) = do titleText <- inlineListToMan opts title authors' <- mapM (inlineListToMan opts) authors date' <- inlineListToMan opts date let colwidth = if writerWrapText opts then Just $ writerColumns opts else Nothing let render' = render colwidth let (cmdName, rest) = break (== ' ') $ render' titleText let (title', section) = case reverse cmdName of (')':d:'(':xs) | d `elem` ['0'..'9'] -> (text (reverse xs), char d) xs -> (text (reverse xs), doubleQuotes empty) let description = hsep $ map (doubleQuotes . text . removeLeadingTrailingSpace) $ splitBy (== '|') rest body <- blockListToMan opts blocks notes <- liftM stNotes get notes' <- notesToMan opts (reverse notes) let main = render' $ body $$ notes' $$ text "" hasTables <- liftM stHasTables get let context = writerVariables opts ++ [ ("body", main) , ("title", render' title') , ("section", render' section) , ("date", render' date') , ("description", render' description) ] ++ [ ("has-tables", "yes") | hasTables ] ++ [ ("author", render' a) | a <- authors' ] if writerStandalone opts then return $ renderTemplate context $ writerTemplate opts else return main -- | Return man representation of notes. notesToMan :: WriterOptions -> [[Block]] -> State WriterState Doc notesToMan opts notes = if null notes then return empty else mapM (\(num, note) -> noteToMan opts num note) (zip [1..] notes) >>= return . (text ".SH NOTES" $$) . vcat -- | Return man representation of a note. noteToMan :: WriterOptions -> Int -> [Block] -> State WriterState Doc noteToMan opts num note = do contents <- blockListToMan opts note let marker = cr <> text ".SS " <> brackets (text (show num)) return $ marker $$ contents -- | Association list of characters to escape. manEscapes :: [(Char, String)] manEscapes = [ ('\160', "\\ ") , ('\'', "\\[aq]") , ('’', "'") , ('\x2014', "\\[em]") , ('\x2013', "\\[en]") , ('\x2026', "\\&...") ] ++ backslashEscapes "@\\" -- | Escape special characters for Man. escapeString :: String -> String escapeString = escapeStringUsing manEscapes -- | Escape a literal (code) section for Man. escapeCode :: String -> String escapeCode = concat . intersperse "\n" . map escapeLine . lines where escapeLine codeline = case escapeStringUsing (manEscapes ++ backslashEscapes "\t ") codeline of a@('.':_) -> "\\&" ++ a b -> b -- We split inline lists into sentences, and print one sentence per -- line. groff/troff treats the line-ending period differently. -- See http://code.google.com/p/pandoc/issues/detail?id=148. -- | Returns the first sentence in a list of inlines, and the rest. breakSentence :: [Inline] -> ([Inline], [Inline]) breakSentence [] = ([],[]) breakSentence xs = let isSentenceEndInline (Str ys@(_:_)) | last ys == '.' = True isSentenceEndInline (Str ys@(_:_)) | last ys == '?' = True isSentenceEndInline (LineBreak) = True isSentenceEndInline _ = False (as, bs) = break isSentenceEndInline xs in case bs of [] -> (as, []) [c] -> (as ++ [c], []) (c:Space:cs) -> (as ++ [c], cs) (Str ".":Str (')':ys):cs) -> (as ++ [Str ".", Str (')':ys)], cs) (x@(Str ('.':')':_)):cs) -> (as ++ [x], cs) (LineBreak:x@(Str ('.':_)):cs) -> (as ++[LineBreak], x:cs) (c:cs) -> (as ++ [c] ++ ds, es) where (ds, es) = breakSentence cs -- | Split a list of inlines into sentences. splitSentences :: [Inline] -> [[Inline]] splitSentences xs = let (sent, rest) = breakSentence xs in if null rest then [sent] else sent : splitSentences rest -- | Convert Pandoc block element to man. blockToMan :: WriterOptions -- ^ Options -> Block -- ^ Block element -> State WriterState Doc blockToMan _ Null = return empty blockToMan opts (Plain inlines) = liftM vcat $ mapM (inlineListToMan opts) $ splitSentences inlines blockToMan opts (Para inlines) = do contents <- liftM vcat $ mapM (inlineListToMan opts) $ splitSentences inlines return $ text ".PP" $$ contents blockToMan _ (RawBlock "man" str) = return $ text str blockToMan _ (RawBlock _ _) = return empty blockToMan _ HorizontalRule = return $ text ".PP" $$ text " * * * * *" blockToMan opts (Header level inlines) = do contents <- inlineListToMan opts inlines let heading = case level of 1 -> ".SH " _ -> ".SS " return $ text heading <> contents blockToMan _ (CodeBlock _ str) = return $ text ".IP" $$ text ".nf" $$ text "\\f[C]" $$ text (escapeCode str) $$ text "\\f[]" $$ text ".fi" blockToMan opts (BlockQuote blocks) = do contents <- blockListToMan opts blocks return $ text ".RS" $$ contents $$ text ".RE" blockToMan opts (Table caption alignments widths headers rows) = let aligncode AlignLeft = "l" aligncode AlignRight = "r" aligncode AlignCenter = "c" aligncode AlignDefault = "l" in do caption' <- inlineListToMan opts caption modify $ \st -> st{ stHasTables = True } let iwidths = if all (== 0) widths then repeat "" else map (printf "w(%0.2fn)" . (70 *)) widths -- 78n default width - 8n indent = 70n let coldescriptions = text $ intercalate " " (zipWith (\align width -> aligncode align ++ width) alignments iwidths) ++ "." colheadings <- mapM (blockListToMan opts) headers let makeRow cols = text "T{" $$ (vcat $ intersperse (text "T}@T{") cols) $$ text "T}" let colheadings' = if all null headers then empty else makeRow colheadings $$ char '_' body <- mapM (\row -> do cols <- mapM (blockListToMan opts) row return $ makeRow cols) rows return $ text ".PP" $$ caption' $$ text ".TS" $$ text "tab(@);" $$ coldescriptions $$ colheadings' $$ vcat body $$ text ".TE" blockToMan opts (BulletList items) = do contents <- mapM (bulletListItemToMan opts) items return (vcat contents) blockToMan opts (OrderedList attribs items) = do let markers = take (length items) $ orderedListMarkers attribs let indent = 1 + (maximum $ map length markers) contents <- mapM (\(num, item) -> orderedListItemToMan opts num indent item) $ zip markers items return (vcat contents) blockToMan opts (DefinitionList items) = do contents <- mapM (definitionListItemToMan opts) items return (vcat contents) -- | Convert bullet list item (list of blocks) to man. bulletListItemToMan :: WriterOptions -> [Block] -> State WriterState Doc bulletListItemToMan _ [] = return empty bulletListItemToMan opts ((Para first):rest) = bulletListItemToMan opts ((Plain first):rest) bulletListItemToMan opts ((Plain first):rest) = do first' <- blockToMan opts (Plain first) rest' <- blockListToMan opts rest let first'' = text ".IP \\[bu] 2" $$ first' let rest'' = if null rest then empty else text ".RS 2" $$ rest' $$ text ".RE" return (first'' $$ rest'') bulletListItemToMan opts (first:rest) = do first' <- blockToMan opts first rest' <- blockListToMan opts rest return $ text "\\[bu] .RS 2" $$ first' $$ rest' $$ text ".RE" -- | Convert ordered list item (a list of blocks) to man. orderedListItemToMan :: WriterOptions -- ^ options -> String -- ^ order marker for list item -> Int -- ^ number of spaces to indent -> [Block] -- ^ list item (list of blocks) -> State WriterState Doc orderedListItemToMan _ _ _ [] = return empty orderedListItemToMan opts num indent ((Para first):rest) = orderedListItemToMan opts num indent ((Plain first):rest) orderedListItemToMan opts num indent (first:rest) = do first' <- blockToMan opts first rest' <- blockListToMan opts rest let num' = printf ("%" ++ show (indent - 1) ++ "s") num let first'' = text (".IP \"" ++ num' ++ "\" " ++ show indent) $$ first' let rest'' = if null rest then empty else text ".RS 4" $$ rest' $$ text ".RE" return $ first'' $$ rest'' -- | Convert definition list item (label, list of blocks) to man. definitionListItemToMan :: WriterOptions -> ([Inline],[[Block]]) -> State WriterState Doc definitionListItemToMan opts (label, defs) = do labelText <- inlineListToMan opts label contents <- if null defs then return empty else liftM vcat $ forM defs $ \blocks -> do let (first, rest) = case blocks of ((Para x):y) -> (Plain x,y) (x:y) -> (x,y) [] -> error "blocks is null" rest' <- liftM vcat $ mapM (\item -> blockToMan opts item) rest first' <- blockToMan opts first return $ first' $$ text ".RS" $$ rest' $$ text ".RE" return $ text ".TP" $$ text ".B " <> labelText $$ contents -- | Convert list of Pandoc block elements to man. blockListToMan :: WriterOptions -- ^ Options -> [Block] -- ^ List of block elements -> State WriterState Doc blockListToMan opts blocks = mapM (blockToMan opts) blocks >>= (return . vcat) -- | Convert list of Pandoc inline elements to man. inlineListToMan :: WriterOptions -> [Inline] -> State WriterState Doc -- if list starts with ., insert a zero-width character \& so it -- won't be interpreted as markup if it falls at the beginning of a line. inlineListToMan opts lst@(Str ('.':_) : _) = mapM (inlineToMan opts) lst >>= (return . (text "\\&" <>) . hcat) inlineListToMan opts lst = mapM (inlineToMan opts) lst >>= (return . hcat) -- | Convert Pandoc inline element to man. inlineToMan :: WriterOptions -> Inline -> State WriterState Doc inlineToMan opts (Emph lst) = do contents <- inlineListToMan opts lst return $ text "\\f[I]" <> contents <> text "\\f[]" inlineToMan opts (Strong lst) = do contents <- inlineListToMan opts lst return $ text "\\f[B]" <> contents <> text "\\f[]" inlineToMan opts (Strikeout lst) = do contents <- inlineListToMan opts lst return $ text "[STRIKEOUT:" <> contents <> char ']' inlineToMan opts (Superscript lst) = do contents <- inlineListToMan opts lst return $ char '^' <> contents <> char '^' inlineToMan opts (Subscript lst) = do contents <- inlineListToMan opts lst return $ char '~' <> contents <> char '~' inlineToMan opts (SmallCaps lst) = inlineListToMan opts lst -- not supported inlineToMan opts (Quoted SingleQuote lst) = do contents <- inlineListToMan opts lst return $ char '`' <> contents <> char '\'' inlineToMan opts (Quoted DoubleQuote lst) = do contents <- inlineListToMan opts lst return $ text "\\[lq]" <> contents <> text "\\[rq]" inlineToMan opts (Cite _ lst) = inlineListToMan opts lst inlineToMan _ (Code _ str) = return $ text $ "\\f[C]" ++ escapeCode str ++ "\\f[]" inlineToMan _ (Str str) = return $ text $ escapeString str inlineToMan opts (Math InlineMath str) = inlineListToMan opts $ readTeXMath str inlineToMan opts (Math DisplayMath str) = do contents <- inlineListToMan opts $ readTeXMath str return $ cr <> text ".RS" $$ contents $$ text ".RE" inlineToMan _ (RawInline "man" str) = return $ text str inlineToMan _ (RawInline _ _) = return empty inlineToMan _ (LineBreak) = return $ cr <> text ".PD 0" $$ text ".P" $$ text ".PD" <> cr inlineToMan _ Space = return space inlineToMan opts (Link txt (src, _)) = do linktext <- inlineListToMan opts txt let srcSuffix = if isPrefixOf "mailto:" src then drop 7 src else src return $ case txt of [Code _ s] | s == srcSuffix -> char '<' <> text srcSuffix <> char '>' _ -> linktext <> text " (" <> text src <> char ')' inlineToMan opts (Image alternate (source, tit)) = do let txt = if (null alternate) || (alternate == [Str ""]) || (alternate == [Str source]) -- to prevent autolinks then [Str "image"] else alternate linkPart <- inlineToMan opts (Link txt (source, tit)) return $ char '[' <> text "IMAGE: " <> linkPart <> char ']' inlineToMan _ (Note contents) = do -- add to notes in state modify $ \st -> st{ stNotes = contents : stNotes st } notes <- liftM stNotes get let ref = show $ (length notes) return $ char '[' <> text ref <> char ']'
castaway/pandoc
src/Text/Pandoc/Writers/Man.hs
gpl-2.0
14,967
0
22
4,121
4,589
2,283
2,306
278
10
module FQuoter.Serialize.GroupingSpec(main, spec) where import Test.Hspec import Database.HDBC import FQuoter.Serialize.Grouping import FQuoter.Serialize.SerializedTypes ------------- -- Test data ------------- main :: IO() main = hspec spec single' = Single . toSql testData = [["1","page 3", "quote", "", "title", "publisher", "random", "tag", "John", "Doe", ""] ,["1","page 3", "quote", "", "title", "publisher", "random", "tag1", "John", "Doe", ""] ,["1","page 3", "quote", "", "title", "publisher", "random", "tag", "Jane", "Doe", ""] ,["1","page 3", "quote", "", "title", "publisher", "random", "tag1", "Jane", "Doe", ""] ,["2","page 42", "another quote", "comment", "title2", "", "", "", "Bill", "Doe", ""]] exempleInput = map (map toSql) testData expectedOutut = [[Grouped [Grouped [single' "publisher", single' "random"]] ,Grouped [single' "tag", single' "tag1"] ,Grouped [Grouped [single' "John", single' "Doe", single' ""] ,Grouped [single' "Jane", single' "Doe", single' ""]] ,single' "1", single' "page 3", single' "quote", single' "", single' "title"] ,[Grouped [Grouped [single' "", single' ""]] ,Grouped [single' ""] ,Grouped [Grouped [single' "Bill", single' "Doe", single' ""]] ,single' "2", single' "page 42", single' "another quote", single' "comment" ,single' "title2"]] spec = do describe "Gropuping" $ do context "Grouping a list of 4 results containing 2 quotes, one having 2 authors" $ do it "Return a table of length 2" $ do groupSql DBQuote exempleInput `shouldSatisfy` ((==2) . length) it "Return a array with grouped metadatas, tags, authors" $ do groupSql DBQuote exempleInput `shouldBe` expectedOutut
Raveline/FQuoter
testsuite/FQuoter/Serialize/GroupingSpec.hs
gpl-3.0
1,836
0
19
420
585
330
255
32
1
{-# LANGUAGE OverloadedStrings #-} module Lang.PrettyUtils where import Text.PrettyPrint -- | Pretty printing kit. -- First component for variable bindings, -- second for binding variables -- (to be able to say where to print types and where to ignore it) type Kit a = (a -> Doc,a -> Doc) parensIf :: Bool -> Doc -> Doc parensIf True = parens parensIf False = id csv :: [Doc] -> Doc csv = inside "(" "," ")" inside :: Doc -> Doc -> Doc -> [Doc] -> Doc inside _ _ _ [] = empty inside l p r (x:xs) = cat (go (l <> x) xs) where go y [] = [y,r] go y (z:zs) = y : go (p <> z) zs
danr/tfp1
Lang/PrettyUtils.hs
gpl-3.0
605
0
10
153
222
122
100
14
2
module Kopia.Model.Snapshot ( Snapshot(..) , getLocalTime ) where import Data.Time ( UTCTime , LocalTime , getCurrentTimeZone , utcToLocalTime ) import Kopia.Model.Bridge (Bridge) data Snapshot = Snapshot { getEvent :: String , getBridge :: Bridge , getTime :: UTCTime } deriving (Eq, Show) getLocalTime :: Snapshot -> IO LocalTime getLocalTime snapshot = do let time = getTime snapshot timezone <- getCurrentTimeZone return $ utcToLocalTime timezone time
Jefffrey/Kopia
src/Kopia/Model/Snapshot.hs
gpl-3.0
543
0
10
152
138
78
60
20
1
-- nonlinear least-squares fitting import Numeric.GSL.Fitting import Numeric.LinearAlgebra xs = map return [0 .. 39] sigma = 0.1 ys = map return $ toList $ fromList (map (head . expModel [5,0.1,1]) xs) + scalar sigma * (randomVector 0 Gaussian 40) dat :: [([Double],([Double],Double))] dat = zip xs (zip ys (repeat sigma)) expModel [a,lambda,b] [t] = [a * exp (-lambda * t) + b] expModelDer [a,lambda,b] [t] = [[exp (-lambda * t), -t * a * exp(-lambda*t) , 1]] (sol,path) = fitModelScaled 1E-4 1E-4 20 (expModel, expModelDer) dat [1,0,0] main = do print dat print path print sol
dkensinger/haskell
linear_alg.hs
gpl-3.0
617
0
14
135
327
178
149
15
1
module HEP.Automation.MadGraph.Dataset.Set20110718set1ATLAS where import HEP.Storage.WebDAV.Type import HEP.Automation.MadGraph.Model import HEP.Automation.MadGraph.Machine import HEP.Automation.MadGraph.UserCut import HEP.Automation.MadGraph.SetupType import HEP.Automation.MadGraph.Model.SChanC8V import HEP.Automation.MadGraph.Dataset.Processes import HEP.Automation.JobQueue.JobType processSetup :: ProcessSetup SChanC8V processSetup = PS { model = SChanC8V , process = preDefProcess TTBar0or1J , processBrief = "TTBar0or1J" , workname = "718_SChanC8V_TTBar0or1J_LHC" } paramSet :: [ModelParam SChanC8V] paramSet = [ SChanC8VParam { mnp = m, gnpqR = -1.0, gnpqL = 1.0, gnpbR = g, gnpbL = -g, gnptR = g, gnptL = -g } | m <- [1600,1800,2000,2200,2400] , g <- [3.0,3.5..5.0] ] sets :: [Int] sets = [1] ucut :: UserCut ucut = UserCut { uc_metcut = 15.0 , uc_etacutlep = 2.7 , uc_etcutlep = 18.0 , uc_etacutjet = 2.7 , uc_etcutjet = 15.0 } eventsets :: [EventSet] eventsets = [ EventSet processSetup (RS { param = p , numevent = 100000 , machine = LHC7 ATLAS , rgrun = Fixed , rgscale = 200.0 , match = MLM , cut = DefCut , pythia = RunPYTHIA , usercut = UserCutDef ucut -- NoUserCutDef -- , pgs = RunPGS , jetalgo = AntiKTJet 0.4 , uploadhep = NoUploadHEP , setnum = num }) | p <- paramSet , num <- sets ] webdavdir :: WebDAVRemoteDir webdavdir = WebDAVRemoteDir "paper3/ttbar_LHC_schanc8v_pgsscan"
wavewave/madgraph-auto-dataset
src/HEP/Automation/MadGraph/Dataset/Set20110718set1ATLAS.hs
gpl-3.0
1,808
0
10
610
418
263
155
49
1
{- The Delve Programming Language Copyright 2009 John Morrice Distributed under the terms of the GNU General Public License v3, or ( at your option ) any later version. This file is part of Delve. Delve is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Delve 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 Delve. If not, see <http://www.gnu.org/licenses/>. -} -- The Elgin Delve Compiler module Main ( extend , main , bytecode_compile ) where import Phases import Data.Maybe import Data.List.Stream as L import Control.Arrow import System.Environment -- Get the args, check if they're empty, if not we might be in business. main = do args <- getArgs if L.null args then usage else obey_args args -- For when folk are stuck usage = do n <- getProgName putStrLn $ "____Elgin Delve Compiler Help____\n" L.++ "\n***To compile Delve source into dcode***\n" L.++ '\n' : n L.++ " source_file+ edc_option*\n" L.++ "\nBy default, the output file is named corresponding to the name of the last source_file given.\n" L.++ "\nFor example, for the command:\n" L.++ n L.++ " HTTP.delve httpd.delve\n" L.++ "The output file would be called 'httpd.dcode'\n" L.++ "\nAvailable edc_options:\n" L.++ "\n-o output_file\n" L.++ "-o allows the user to choose the name of the output file.\n" L.++ "Arguments specified after the name of the output file are silently ignored. ( Because of laziness on the part of the author )\n" L.++ "\n***To extend the virtual machine***\n" L.++ '\n' : n L.++ " extend source_file+ [-g ghc_option*]\n" L.++ "\nThe file 'edvm.hs' is expected to be in the current directory, as the virtual machine extension will be compiled against it.\n" L.++ "\nExample:\n" L.++ n L.++ " Object.edelve Bool.edelve Int.edelve -g -O2\n" L.++ "Creates a virtual machine from the embedded delve files Object.edelve, Bool.edelve and Int.edelve, and optimizes with O2.\n" L.++ meaning_of_symbols L.++ "\n\nPlease be advised that this is an in development version of Delve: it doesn't have a type-system yet!\nBut you can still have a lot of fun :)" -- Describing the meaning of symbols in usage meaning_of_symbols = "\nMeaning of symbols:\n" L.++ "term+ denotes one or more of term\n" L.++ "term* denotes zero or more of term\n" L.++ "[ term ] denotes that the term is optional - the term occurs only once OR not at all." -- Carry out the instructions given! promptly! no mucking about! obey_args args = let cmd = L.head args in case cmd of "extend" -> extend $ L.tail args _ -> bytecode_compile args -- if 'extend' is not specified, then assume bytecode compilation -- Compile to bytecode bytecode_compile args = let ( fs , output_file_list ) = L.span ((/=) "-o" ) args in dcode fs $ listToMaybe $ L.drop 1 output_file_list -- Extend the virtual machine with embedded delve extend args = if L.null args then do putStrLn "ERROR:\n'extend' requires one or more filenames as arguments.\n" usage else let ( fs , ghc_opts ) = second ( intercalate " " . L.drop 1 ) $ L.span ((/=) "-g" ) args in do embedded ghc_opts fs return ( )
elginer/Delve
src/edc.hs
gpl-3.0
3,814
0
31
948
475
242
233
55
2
data Effect = E String Int data Cast a = C Effect (Cast a) type Capability a = Cast a -> a data Object a = O (Cast a) (Capability a) mkActor :: Capability a -> Object a -> Object a mkActor caps = \(O c1 _) -> O c1 caps takeBuff :: Int -> (Cast Int, String) -> Int takeBuff i (C (E "" eVal) _, _) = i takeBuff i (C (E eName eVal) c, buffName) | eName == buffName = takeBuff (i + eVal) (c, buffName) | otherwise = takeBuff i (c, buffName) (<~) = takeBuff ------------------------------ warmable :: Capability Int warmable c = 10 <~ (c, "warm") frozenable c = 80 <~ (c, "cold") -- WTF?!! How does it work?!!! box = mkActor $ do warmable frozenable
graninas/Haskell-Algorithms
Tests/DoNotationTest.hs
gpl-3.0
720
0
9
206
312
164
148
17
1
{-| Module : Language.Untyped.Context Description : Definition of the Context of evaluation and some useful functions. Copyright : (c) Juan Gabriel Bono, 2016 License : BSD3 Maintainer : [email protected] -} module Language.Untyped.Context ( Context , Binding (..) , CtxException (..) , Name , addName , toIndex , fromIndex , emptyContext , pickFreshName , termSubstTop ) where import Control.Exception import Data.Either import Data.Typeable import Language.Untyped.Syntax -- == Definitions -- | The variable's names are just an alias for 'String' type Name = String -- | It doesn't carry any useful information. data Binding = NameBind deriving (Show, Eq) data CtxException = NotFound | Unbound Name deriving (Typeable) instance Show CtxException where show NotFound = "Variable lookup failure" show (Unbound name) = "UnboundException: Identifier " ++ name ++ " is unbound." instance Exception CtxException -- | It's represented by a list of names and associated bindings. type Context = [(Name, Binding)] -- == Context's Management -- | An empty context. emptyContext :: Context emptyContext = [] -- | Appends the ('Name', 'Binding') tuple to the 'Context'. addBinding :: Context -> Name -> Binding -> Context addBinding ctx x bind = (x, bind) : ctx -- | Adds a 'Name' to a given 'Context' addName :: Context -> Name -> Context addName ctx name = if isNameBound ctx name -- otra def addBinding ctx name NameBind then ctx else addBinding ctx name NameBind -- | Checks if a given 'Name' is bound within a 'Context'. isNameBound :: Context -> Name -> Bool isNameBound ctx name = elem name . map fst $ ctx -- | Checks if a given 'Context' contains a 'Name', in that case appends one or more "'". -- In any other case returns a tuple containing the context with the new name and the name as 2nd component. pickFreshName :: Context -> Name -> (Context, Name) pickFreshName ctx x | isNameBound ctx x = pickFreshName ctx (x ++ "'") | otherwise = (addName ctx x, x) -- | fromIndex :: Context -> Int -> Either CtxException Name fromIndex ctx index | length ctx < index = Left NotFound | otherwise = Right $ fst (ctx !! index) -- | toIndex :: Context -> Name -> Either CtxException Int toIndex [] name = throw $ Unbound name toIndex ((y, _):rest) name | name == y = Right 0 | otherwise = (+1) <$> toIndex rest name -- * -- -- removeNames :: Context -> Term -> NamelessTerm removeNames = undefined restoreNames :: Context -> NamelessTerm -> Term restoreNames = undefined -- -- == Shifting -- | termMap :: Num t => (t -> Int -> NamelessTerm) -> t -> NamelessTerm -> NamelessTerm termMap onvar c term = let walk c (NmVar index) = onvar c index walk c (NmAbs name term) = NmAbs name (walk (c + 1) term) walk c (NmApp t1 t2) = NmApp (walk c t1) (walk c t2) in walk c term -- | termShiftAbove :: Int -> Int -> NamelessTerm -> NamelessTerm termShiftAbove d c term = termMap f c term where f c x | x >= c = NmVar (x + d) | otherwise = NmVar x -- | termShift :: Int -> NamelessTerm -> NamelessTerm termShift d term = termShiftAbove d 0 term -- * -- -- == Substitution -- | termSubst :: Int -> NamelessTerm -> NamelessTerm -> NamelessTerm termSubst j t1 t2 = termMap f 0 t2 where f c x | x == j + c = termShift c t1 | otherwise = NmVar x -- | termSubstTop :: NamelessTerm -> NamelessTerm -> NamelessTerm termSubstTop t1 t2 = termShift (-1) $ termSubst 0 (termShift 1 t1) t2 -- * --
juanbono/tapl-haskell
untyped/src/Language/Untyped/Context.hs
gpl-3.0
3,602
0
13
846
994
522
472
75
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Directory.Customers.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates a customer. -- -- /See:/ <https://developers.google.com/admin-sdk/ Admin SDK API Reference> for @directory.customers.update@. module Network.Google.Resource.Directory.Customers.Update ( -- * REST Resource CustomersUpdateResource -- * Creating a Request , customersUpdate , CustomersUpdate -- * Request Lenses , cuXgafv , cuUploadProtocol , cuAccessToken , cuCustomerKey , cuUploadType , cuPayload , cuCallback ) where import Network.Google.Directory.Types import Network.Google.Prelude -- | A resource alias for @directory.customers.update@ method which the -- 'CustomersUpdate' request conforms to. type CustomersUpdateResource = "admin" :> "directory" :> "v1" :> "customers" :> Capture "customerKey" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Customer :> Put '[JSON] Customer -- | Updates a customer. -- -- /See:/ 'customersUpdate' smart constructor. data CustomersUpdate = CustomersUpdate' { _cuXgafv :: !(Maybe Xgafv) , _cuUploadProtocol :: !(Maybe Text) , _cuAccessToken :: !(Maybe Text) , _cuCustomerKey :: !Text , _cuUploadType :: !(Maybe Text) , _cuPayload :: !Customer , _cuCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CustomersUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cuXgafv' -- -- * 'cuUploadProtocol' -- -- * 'cuAccessToken' -- -- * 'cuCustomerKey' -- -- * 'cuUploadType' -- -- * 'cuPayload' -- -- * 'cuCallback' customersUpdate :: Text -- ^ 'cuCustomerKey' -> Customer -- ^ 'cuPayload' -> CustomersUpdate customersUpdate pCuCustomerKey_ pCuPayload_ = CustomersUpdate' { _cuXgafv = Nothing , _cuUploadProtocol = Nothing , _cuAccessToken = Nothing , _cuCustomerKey = pCuCustomerKey_ , _cuUploadType = Nothing , _cuPayload = pCuPayload_ , _cuCallback = Nothing } -- | V1 error format. cuXgafv :: Lens' CustomersUpdate (Maybe Xgafv) cuXgafv = lens _cuXgafv (\ s a -> s{_cuXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). cuUploadProtocol :: Lens' CustomersUpdate (Maybe Text) cuUploadProtocol = lens _cuUploadProtocol (\ s a -> s{_cuUploadProtocol = a}) -- | OAuth access token. cuAccessToken :: Lens' CustomersUpdate (Maybe Text) cuAccessToken = lens _cuAccessToken (\ s a -> s{_cuAccessToken = a}) -- | Id of the customer to be updated cuCustomerKey :: Lens' CustomersUpdate Text cuCustomerKey = lens _cuCustomerKey (\ s a -> s{_cuCustomerKey = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). cuUploadType :: Lens' CustomersUpdate (Maybe Text) cuUploadType = lens _cuUploadType (\ s a -> s{_cuUploadType = a}) -- | Multipart request metadata. cuPayload :: Lens' CustomersUpdate Customer cuPayload = lens _cuPayload (\ s a -> s{_cuPayload = a}) -- | JSONP cuCallback :: Lens' CustomersUpdate (Maybe Text) cuCallback = lens _cuCallback (\ s a -> s{_cuCallback = a}) instance GoogleRequest CustomersUpdate where type Rs CustomersUpdate = Customer type Scopes CustomersUpdate = '["https://www.googleapis.com/auth/admin.directory.customer"] requestClient CustomersUpdate'{..} = go _cuCustomerKey _cuXgafv _cuUploadProtocol _cuAccessToken _cuUploadType _cuCallback (Just AltJSON) _cuPayload directoryService where go = buildClient (Proxy :: Proxy CustomersUpdateResource) mempty
brendanhay/gogol
gogol-admin-directory/gen/Network/Google/Resource/Directory/Customers/Update.hs
mpl-2.0
4,831
0
19
1,202
786
457
329
115
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.CloudBilling.BillingAccounts.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets information about a billing account. The current authenticated user -- must be a [viewer of the billing -- account](https:\/\/cloud.google.com\/billing\/docs\/how-to\/billing-access). -- -- /See:/ <https://cloud.google.com/billing/ Cloud Billing API Reference> for @cloudbilling.billingAccounts.get@. module Network.Google.Resource.CloudBilling.BillingAccounts.Get ( -- * REST Resource BillingAccountsGetResource -- * Creating a Request , billingAccountsGet , BillingAccountsGet -- * Request Lenses , bagXgafv , bagUploadProtocol , bagAccessToken , bagUploadType , bagName , bagCallback ) where import Network.Google.Billing.Types import Network.Google.Prelude -- | A resource alias for @cloudbilling.billingAccounts.get@ method which the -- 'BillingAccountsGet' request conforms to. type BillingAccountsGetResource = "v1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] BillingAccount -- | Gets information about a billing account. The current authenticated user -- must be a [viewer of the billing -- account](https:\/\/cloud.google.com\/billing\/docs\/how-to\/billing-access). -- -- /See:/ 'billingAccountsGet' smart constructor. data BillingAccountsGet = BillingAccountsGet' { _bagXgafv :: !(Maybe Xgafv) , _bagUploadProtocol :: !(Maybe Text) , _bagAccessToken :: !(Maybe Text) , _bagUploadType :: !(Maybe Text) , _bagName :: !Text , _bagCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BillingAccountsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bagXgafv' -- -- * 'bagUploadProtocol' -- -- * 'bagAccessToken' -- -- * 'bagUploadType' -- -- * 'bagName' -- -- * 'bagCallback' billingAccountsGet :: Text -- ^ 'bagName' -> BillingAccountsGet billingAccountsGet pBagName_ = BillingAccountsGet' { _bagXgafv = Nothing , _bagUploadProtocol = Nothing , _bagAccessToken = Nothing , _bagUploadType = Nothing , _bagName = pBagName_ , _bagCallback = Nothing } -- | V1 error format. bagXgafv :: Lens' BillingAccountsGet (Maybe Xgafv) bagXgafv = lens _bagXgafv (\ s a -> s{_bagXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). bagUploadProtocol :: Lens' BillingAccountsGet (Maybe Text) bagUploadProtocol = lens _bagUploadProtocol (\ s a -> s{_bagUploadProtocol = a}) -- | OAuth access token. bagAccessToken :: Lens' BillingAccountsGet (Maybe Text) bagAccessToken = lens _bagAccessToken (\ s a -> s{_bagAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). bagUploadType :: Lens' BillingAccountsGet (Maybe Text) bagUploadType = lens _bagUploadType (\ s a -> s{_bagUploadType = a}) -- | Required. The resource name of the billing account to retrieve. For -- example, \`billingAccounts\/012345-567890-ABCDEF\`. bagName :: Lens' BillingAccountsGet Text bagName = lens _bagName (\ s a -> s{_bagName = a}) -- | JSONP bagCallback :: Lens' BillingAccountsGet (Maybe Text) bagCallback = lens _bagCallback (\ s a -> s{_bagCallback = a}) instance GoogleRequest BillingAccountsGet where type Rs BillingAccountsGet = BillingAccount type Scopes BillingAccountsGet = '["https://www.googleapis.com/auth/cloud-billing", "https://www.googleapis.com/auth/cloud-billing.readonly", "https://www.googleapis.com/auth/cloud-platform"] requestClient BillingAccountsGet'{..} = go _bagName _bagXgafv _bagUploadProtocol _bagAccessToken _bagUploadType _bagCallback (Just AltJSON) billingService where go = buildClient (Proxy :: Proxy BillingAccountsGetResource) mempty
brendanhay/gogol
gogol-billing/gen/Network/Google/Resource/CloudBilling/BillingAccounts/Get.hs
mpl-2.0
5,003
0
15
1,113
705
414
291
103
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.YouTubeReporting.Types -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.YouTubeReporting.Types ( -- * Service Configuration youTubeReportingService -- * OAuth Scopes , youTubeAnalyticsReadOnlyScope , youTubeAnalyticsMonetaryReadOnlyScope -- * ListReportsResponse , ListReportsResponse , listReportsResponse , lrrNextPageToken , lrrReports -- * GDataDiffChecksumsResponse , GDataDiffChecksumsResponse , gDataDiffChecksumsResponse , gddcrChecksumsLocation , gddcrObjectSizeBytes , gddcrChunkSizeBytes , gddcrObjectVersion , gddcrObjectLocation -- * GDataObjectId , GDataObjectId , gDataObjectId , gdoiObjectName , gdoiBucketName , gdoiGeneration -- * Empty , Empty , empty -- * GDataCompositeMediaReferenceType , GDataCompositeMediaReferenceType (..) -- * GDataMediaReferenceType , GDataMediaReferenceType (..) -- * GDataContentTypeInfo , GDataContentTypeInfo , gDataContentTypeInfo , gdctiFromBytes , gdctiFromFileName , gdctiFromHeader , gdctiBestGuess , gdctiFromURLPath -- * GDataMedia , GDataMedia , gDataMedia , gdmLength , gdmDiffVersionResponse , gdmDiffUploadRequest , gdmBigstoreObjectRef , gdmHash , gdmIsPotentialRetry , gdmCrc32cHash , gdmBlobRef , gdmPath , gdmObjectId , gdmToken , gdmInline , gdmMediaId , gdmSha1Hash , gdmHashVerified , gdmContentTypeInfo , gdmAlgorithm , gdmDiffDownloadResponse , gdmDiffUploadResponse , gdmDiffChecksumsResponse , gdmBlobstore2Info , gdmReferenceType , gdmTimestamp , gdmMD5Hash , gdmDownloadParameters , gdmCosmoBinaryReference , gdmFilename , gdmSha256Hash , gdmContentType , gdmCompositeMedia -- * Report , Report , report , rJobId , rStartTime , rDownloadURL , rEndTime , rId , rCreateTime , rJobExpireTime -- * GDataCompositeMedia , GDataCompositeMedia , gDataCompositeMedia , gdcmLength , gdcmCrc32cHash , gdcmBlobRef , gdcmPath , gdcmObjectId , gdcmInline , gdcmSha1Hash , gdcmBlobstore2Info , gdcmReferenceType , gdcmMD5Hash , gdcmCosmoBinaryReference -- * GDataDownloadParameters , GDataDownloadParameters , gDataDownloadParameters , gddpIgnoreRange , gddpAllowGzipCompression -- * ListReportTypesResponse , ListReportTypesResponse , listReportTypesResponse , lrtrNextPageToken , lrtrReportTypes -- * GDataBlobstore2Info , GDataBlobstore2Info , gDataBlobstore2Info , gdbiBlobGeneration , gdbiBlobId , gdbiReadToken , gdbiDownloadReadHandle , gdbiUploadMetadataContainer -- * Job , Job , job , jName , jId , jSystemManaged , jReportTypeId , jExpireTime , jCreateTime -- * GDataDiffUploadResponse , GDataDiffUploadResponse , gDataDiffUploadResponse , gddurOriginalObject , gddurObjectVersion -- * Xgafv , Xgafv (..) -- * GDataDiffDownloadResponse , GDataDiffDownloadResponse , gDataDiffDownloadResponse , gdddrObjectLocation -- * ListJobsResponse , ListJobsResponse , listJobsResponse , ljrNextPageToken , ljrJobs -- * GDataDiffUploadRequest , GDataDiffUploadRequest , gDataDiffUploadRequest , gChecksumsInfo , gObjectVersion , gObjectInfo -- * GDataDiffVersionResponse , GDataDiffVersionResponse , gDataDiffVersionResponse , gddvrObjectSizeBytes , gddvrObjectVersion -- * ReportType , ReportType , reportType , rtName , rtId , rtDeprecateTime , rtSystemManaged ) where import Network.Google.Prelude import Network.Google.YouTubeReporting.Types.Product import Network.Google.YouTubeReporting.Types.Sum -- | Default request referring to version 'v1' of the YouTube Reporting API. This contains the host and root path used as a starting point for constructing service requests. youTubeReportingService :: ServiceConfig youTubeReportingService = defaultService (ServiceId "youtubereporting:v1") "youtubereporting.googleapis.com" -- | View YouTube Analytics reports for your YouTube content youTubeAnalyticsReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/yt-analytics.readonly"] youTubeAnalyticsReadOnlyScope = Proxy -- | View monetary and non-monetary YouTube Analytics reports for your -- YouTube content youTubeAnalyticsMonetaryReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/yt-analytics-monetary.readonly"] youTubeAnalyticsMonetaryReadOnlyScope = Proxy
brendanhay/gogol
gogol-youtube-reporting/gen/Network/Google/YouTubeReporting/Types.hs
mpl-2.0
5,170
0
7
1,194
544
372
172
153
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.CognitoIdentity.GetCredentialsForIdentity -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Returns credentials for the the provided identity ID. Any provided logins -- will be validated against supported login providers. If the token is for -- cognito-identity.amazonaws.com, it will be passed through to AWS Security -- Token Service with the appropriate role for the token. -- -- <http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html> module Network.AWS.CognitoIdentity.GetCredentialsForIdentity ( -- * Request GetCredentialsForIdentity -- ** Request constructor , getCredentialsForIdentity -- ** Request lenses , gcfiIdentityId , gcfiLogins -- * Response , GetCredentialsForIdentityResponse -- ** Response constructor , getCredentialsForIdentityResponse -- ** Response lenses , gcfirCredentials , gcfirIdentityId ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.CognitoIdentity.Types import qualified GHC.Exts data GetCredentialsForIdentity = GetCredentialsForIdentity { _gcfiIdentityId :: Text , _gcfiLogins :: Map Text Text } deriving (Eq, Read, Show) -- | 'GetCredentialsForIdentity' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gcfiIdentityId' @::@ 'Text' -- -- * 'gcfiLogins' @::@ 'HashMap' 'Text' 'Text' -- getCredentialsForIdentity :: Text -- ^ 'gcfiIdentityId' -> GetCredentialsForIdentity getCredentialsForIdentity p1 = GetCredentialsForIdentity { _gcfiIdentityId = p1 , _gcfiLogins = mempty } -- | A unique identifier in the format REGION:GUID. gcfiIdentityId :: Lens' GetCredentialsForIdentity Text gcfiIdentityId = lens _gcfiIdentityId (\s a -> s { _gcfiIdentityId = a }) -- | A set of optional name-value pairs that map provider names to provider tokens. gcfiLogins :: Lens' GetCredentialsForIdentity (HashMap Text Text) gcfiLogins = lens _gcfiLogins (\s a -> s { _gcfiLogins = a }) . _Map data GetCredentialsForIdentityResponse = GetCredentialsForIdentityResponse { _gcfirCredentials :: Maybe Credentials , _gcfirIdentityId :: Maybe Text } deriving (Eq, Read, Show) -- | 'GetCredentialsForIdentityResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gcfirCredentials' @::@ 'Maybe' 'Credentials' -- -- * 'gcfirIdentityId' @::@ 'Maybe' 'Text' -- getCredentialsForIdentityResponse :: GetCredentialsForIdentityResponse getCredentialsForIdentityResponse = GetCredentialsForIdentityResponse { _gcfirIdentityId = Nothing , _gcfirCredentials = Nothing } -- | Credentials for the the provided identity ID. gcfirCredentials :: Lens' GetCredentialsForIdentityResponse (Maybe Credentials) gcfirCredentials = lens _gcfirCredentials (\s a -> s { _gcfirCredentials = a }) -- | A unique identifier in the format REGION:GUID. gcfirIdentityId :: Lens' GetCredentialsForIdentityResponse (Maybe Text) gcfirIdentityId = lens _gcfirIdentityId (\s a -> s { _gcfirIdentityId = a }) instance ToPath GetCredentialsForIdentity where toPath = const "/" instance ToQuery GetCredentialsForIdentity where toQuery = const mempty instance ToHeaders GetCredentialsForIdentity instance ToJSON GetCredentialsForIdentity where toJSON GetCredentialsForIdentity{..} = object [ "IdentityId" .= _gcfiIdentityId , "Logins" .= _gcfiLogins ] instance AWSRequest GetCredentialsForIdentity where type Sv GetCredentialsForIdentity = CognitoIdentity type Rs GetCredentialsForIdentity = GetCredentialsForIdentityResponse request = post "GetCredentialsForIdentity" response = jsonResponse instance FromJSON GetCredentialsForIdentityResponse where parseJSON = withObject "GetCredentialsForIdentityResponse" $ \o -> GetCredentialsForIdentityResponse <$> o .:? "Credentials" <*> o .:? "IdentityId"
dysinger/amazonka
amazonka-cognito-identity/gen/Network/AWS/CognitoIdentity/GetCredentialsForIdentity.hs
mpl-2.0
4,936
0
11
957
586
351
235
67
1
{-# LANGUAGE TemplateHaskell #-} module XTag.Config ( readConfig , repositories , cacheRoot , port , redisConnectInfo , Port , Config ) where import Control.Applicative import Control.Lens import Control.Monad.State import Control.Monad.Trans.Either import Data.Map.Lens import Data.Maybe import XTag.Config.Parser import System.Directory import Text.Parsec.Error import qualified Data.ByteString.UTF8 as U import Database.Redis.Simple (ConnectInfo (..), PortID (..), defaultConnectInfo) import Data.List (unlines) type Port = Int data Config = Config { _repositories :: [ FilePath ] , _cacheRoot :: FilePath , _port :: Port , _redisConnectInfo :: ConnectInfo } defaultConfig = Config ["../data"] "../cache" 3000 defaultConnectInfo makeLenses ''Config makeLensesFor [ ("connectHost", "connectHostL") , ("connectPort", "connectPortL") , ("connectAuth", "connectAuthL") , ("connectMaxConnections", "connectMaxConnectionsL") , ("connectMaxIdleTime", "connectMaxIdelTimeL") ] ''ConnectInfo readConfig file = do exists <- doesFileExist file if exists then do result <- flip runStateT defaultConfig $ runEitherT $ do result <- EitherT $ liftIO $ parseConfig file let repos = result ^. at "repositories" val x = read . head <$> result ^. at x portN = val "server_port" cache = val "thumbnail_cache_root" cHost = val "redis_connect_host" cPort = PortNumber <$> fromIntegral <$> val "redis_connect_port" cAuth = Just <$> (U.fromString . head) <$> result ^. at "redis_authentication" maxConn = val "redis_max_connection" maxIdle = fromIntegral <$> val "redis_max_idle_seconds" update repositories repos update cacheRoot cache update port portN update (redisConnectInfo . connectHostL) cHost update (redisConnectInfo . connectPortL) cPort update (redisConnectInfo . connectAuthL) cAuth update (redisConnectInfo . connectMaxConnectionsL) maxConn update (redisConnectInfo . connectMaxIdelTimeL) maxIdle return $ _1 . _Left %~ show $ result else return (Left fileNotFound, defaultConfig) where update lens v = do case v of Nothing -> return () Just vl -> lens .= vl fileNotFound = "Could not found configuration file \"" ++ file ++ "\""
yeyan/xtag
src/XTag/Config.hs
lgpl-3.0
2,906
0
22
1,060
628
336
292
-1
-1
{-# OPTIONS_GHC -Wall -Werror #-} module ChapterExercises_1 where import Text.Trifecta import Data.List import Data.Char import Control.Applicative -- Relevant to precedence/ordering, -- cannot sort numbers like strings. data NumberOrString = NOSS String | NOSI Integer deriving (Show, Eq) instance Ord NumberOrString where (<=) (NOSI _) (NOSS _) = True (<=) (NOSS _) (NOSI _) = False (<=) (NOSI x) (NOSI y) = x <= y (<=) (NOSS x) (NOSS y) = x <= y type Major = Integer type Minor = Integer type Patch = Integer type Release = [NumberOrString] type Metadata = [NumberOrString] data SemVer = SemVer Major Minor Patch Release Metadata deriving (Show, Eq) instance Ord SemVer where (<=) (SemVer maj1 min1 p1 rel1 _) (SemVer maj2 min2 p2 rel2 _) | maj1 /= maj2 = maj1 <= maj2 | min1 /= min2 = min1 <= min2 | p1 /= p2 = p1 <= p2 | p1 /= p2 = p1 <= p2 | rel1 == [] = False | rel1 /= rel2 = rel1 <= rel2 (<=) (SemVer _ _ _ _ _) (SemVer _ _ _ _ _) = undefined parseSemVer :: Parser SemVer parseSemVer = do major <- decimal minor <- char '.' >> decimal patch <- char '.' >> decimal release' <- try $ ((char '-' >> parseNumberOrStringList) <|> return []) metadata <- try $ ((char '+' >> parseNumberOrStringList) <|> return []) eof return $ SemVer major minor patch release' metadata parseNumberOrString :: Parser NumberOrString parseNumberOrString = (try decimal >>= return . NOSI) <|> (try $ some (satisfy isAlphaNum) >>= return . NOSS) parseNumberOrStringList :: Parser [NumberOrString] parseNumberOrStringList = sepBy parseNumberOrString (char '.') -- Tests ver1 :: SemVer ver1 = SemVer 2 1 1 [] [] ver2 :: SemVer ver2 = SemVer 2 1 0 [] [] -- Main runs a series of tests main :: IO () main = do putStrLn "\nTesting parser" parseSuccessCase "2.1.1" $ SemVer 2 1 1 [] [] parseFailCase "1" parseFailCase "1.0" parseSuccessCase "1.0.0" $ SemVer 1 0 0 [] [] parseSuccessCase "1.0.0-1.alpha" $ SemVer 1 0 0 [NOSI 1, NOSS "alpha"] [] parseSuccessCase "1.0.0-1.beta+patch.here" $ SemVer 1 0 0 [NOSI 1, NOSS "beta"] [NOSS "patch", NOSS "here"] parseSuccessCase "1.0.0+patch.here" $ SemVer 1 0 0 [] [NOSS "patch", NOSS "here"] --case parseString parseSemVer mempty case1 of -- Failure _ -> return () -- Success _ -> putStrLn $ case1 ++ " should not parse." putStrLn "\nTesting order" verifyGreaterThan ver1 ver2 putStrLn "\nSorting versions" print $ sort [ver1, ver2, ver1, ver1] print $ sort [ SemVer 9 9 9 [] [NOSS "wow", NOSI 1000] , SemVer 1 0 0 [NOSS "alpha"] [] , SemVer 1 0 0 [NOSS "alpha", NOSI 1] [] , SemVer 1 0 0 [NOSS "beta"] [] , SemVer 1 0 0 [] [] , SemVer 1 0 0 [NOSS "beta", NOSI 2] [] , SemVer 1 0 0 [NOSS "beta", NOSI 11] [] , SemVer 1 0 0 [NOSS "rc", NOSI 1] [] , SemVer 1 0 0 [NOSS "alpha", NOSS "beta"] [] ] putStrLn "\nExpected Results" print $ parseString parseSemVer mempty "2.1.1" print $ parseString parseSemVer mempty "1.0.0-x.7.z.92" print $ SemVer 2 1 1 [] [] > SemVer 2 1 0 [] [] parseSuccessCase :: String -> SemVer -> IO () parseSuccessCase c expected' = do putStr $ c ++ ": " case parseString parseSemVer mempty c of Success m -> do putStrLn "\x1b[32m" >> print (Success m) if (m == expected') then return () else putStr "\x1b[31mexpected: " >> print expected' f -> print f putStr "\x1b[0m" parseFailCase :: String -> IO () parseFailCase c = do putStr $ c ++ ": " case parseString parseSemVer mempty c of Failure _ -> putStr "\x1b[32mdoesn't parse as expected." Success _ -> putStr "\x1b[31mshould not parse but did." putStrLn "\x1b[0m" verifyGreaterThan :: SemVer -> SemVer -> IO () verifyGreaterThan v1 v2 = do putStr $ (show v1) ++ " > " ++ (show v2) ++ ": " if v1 > v2 then putStr "\x1b[32mTrue" else putStr "\x1b[31mFalse" putStrLn "\x1b[0m"
dmp1ce/Haskell-Programming-Exercises
Chapter 24/src/ChapterExercises_1.hs
unlicense
4,064
0
15
1,063
1,532
752
780
99
3
{- Copyrights (c) 2016. Samsung Electronics Ltd. All right reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE FlexibleContexts #-} module Util where import Data.Graph.Inductive import Control.Monad.Except import Data.List import Data.Maybe import Data.Bits import Pos import Name if' :: Bool -> a -> a -> a if' True x _ = x if' False _ y = y err :: (MonadError String me) => Pos -> String -> me a err p e = throwError $ spos p ++ ": " ++ e assert :: (MonadError String me) => Bool -> Pos -> String -> me () assert b p m = if b then return () else err p m -- Tuples mapFst :: (a -> b) -> (a, c) -> (b, c) mapFst f (x,y) = (f x,y) mapSnd :: (a -> b) -> (c, a) -> (c, b) mapSnd f (x,y) = (x,f y) -- Check for duplicate declarations uniq :: (MonadError String me, WithPos a, Ord b) => (a -> b) -> (a -> String) -> [a] -> me () uniq = uniq' pos uniq' :: (MonadError String me, Ord b) => (a -> Pos) -> (a -> b) -> (a -> String) -> [a] -> me () uniq' fpos ford msgfunc xs = do case filter ((>1) . length) $ groupBy (\x1 x2 -> compare (ford x1) (ford x2) == EQ) $ sortBy (\x1 x2 -> compare (ford x1) (ford x2)) xs of g@(x:_):_ -> err (fpos x) $ msgfunc x ++ " at the following locations:\n " ++ (intercalate "\n " $ map (spos . fpos) g) _ -> return () uniqNames :: (MonadError String me, WithPos a, WithName a) => (String -> String) -> [a] -> me () uniqNames msgfunc = uniq name (\x -> msgfunc (name x)) -- Find a cycle in a graph grCycle :: Graph gr => gr a b -> Maybe [LNode a] grCycle g = case mapMaybe nodeCycle (nodes g) of [] -> Nothing c:_ -> Just c where nodeCycle n = listToMaybe $ map (\s -> map (\i -> (i, fromJust $ lab g i)) (n:(esp s n g))) $ filter (\s -> elem n (reachable s g)) $ suc g n --Logarithm to base 2. Equivalent to floor(log2(x)) log2 :: Integer -> Int log2 0 = 0 log2 1 = 0 log2 n | n>1 = 1 + log2 (n `div` 2) | otherwise = error "log2: negative argument" -- The number of bits required to encode range [0..i] bitWidth :: (Integral a) => a -> Int bitWidth i = 1 + log2 (fromIntegral i) mapIdx :: (a -> Int -> b) -> [a] -> [b] mapIdx f xs = map (uncurry f) $ zip xs [0..] mapIdxM :: (Monad m) => (a -> Int -> m b) -> [a] -> m [b] mapIdxM f xs = mapM (uncurry f) $ zip xs [0..] mapIdxM_ :: (Monad m) => (a -> Int -> m ()) -> [a] -> m () mapIdxM_ f xs = mapM_ (uncurry f) $ zip xs [0..] foldIdx :: (a -> b -> Int -> a) -> a -> [b] -> a foldIdx f acc xs = foldl' (\acc' (x,idx) -> f acc' x idx) acc $ zip xs [0..] foldIdxM :: (Monad m) => (a -> b -> Int -> m a) -> a -> [b] -> m a foldIdxM f acc xs = foldM (\acc' (x,idx) -> f acc' x idx) acc $ zip xs [0..] -- parse binary number readBin :: String -> Integer readBin s = foldl' (\acc c -> (acc `shiftL` 1) + case c of '0' -> 0 '1' -> 1 _ -> error $ "readBin" ++ s) 0 s -- Determine the most significant set bit of a non-negative number -- (returns 0 if not bits are set) msb :: (Bits b, Num b) => b -> Int msb 0 = 0 msb 1 = 0 msb n = 1 + (msb $ n `shiftR` 1) bitSlice :: (Bits a, Num a) => a -> Int -> Int -> a bitSlice v h l = (v `shiftR` l) .&. (2^(h-l+1) - 1)
ryzhyk/cocoon
cocoon/Util.hs
apache-2.0
3,861
0
18
1,098
1,636
860
776
69
3
module CostasLikeArrays.A320574Spec (main, spec) where import Test.Hspec import CostasLikeArrays.A320574 (a320574) main :: IO () main = hspec spec spec :: Spec spec = describe "A320574" $ it "correctly computes the first 6 elements" $ map a320574 [1..6] `shouldBe` expectedValue where expectedValue = [1, 1, 2, 1, 1, 3]
peterokagey/haskellOEIS
test/CostasLikeArrays/A320574Spec.hs
apache-2.0
334
0
8
62
112
64
48
10
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module CI.ProcSpec ( test ) where import CI.Proc import Test.Tasty import Test.Tasty.HUnit import Control.Monad.Eff import Control.Monad.Eff.Exception import Control.Monad.Eff.Lift import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.ByteString as BS test :: TestTree test = testGroup "ProcSpec Tests" [ stackVersionTest ] -- | NB: This test ACTUALLY occurs in IO. stackVersionTest :: TestTree stackVersionTest = testCase "invoke proc to get stack version" testAction where testAction :: IO () testAction = do r <- action case r of Left _ -> assertFailure "Expected: \"Version\"..." Right str -> assertBool "Expected: \"Version\"..." $ T.isPrefixOf "Version" str return () action :: IO (Either ProcEx Text) action = runLift $ runException $ runProc getStackVersion getStackVersion :: ( Member Proc r, Member (Exception ProcEx) r ) => Eff r Text getStackVersion = do (_, stdout, _) <- proc "stack" ["--version"] (Stdin BS.empty) return $ T.decodeUtf8 $ unStdout stdout
lancelet/bored-robot
test/CI/ProcSpec.hs
apache-2.0
1,284
0
14
337
314
172
142
35
2
module Forms where import Prelude hiding (writeFile, readFile, head, tail, init, last) import Yesod hiding (Route(..)) import Foundation import Data.Monoid (Monoid (mappend, mempty, mconcat), (<>)) import Control.Applicative ((<$>), (<*>), pure) import Control.Arrow ((&&&)) import Data.Text (Text) import qualified Data.Text as T -- Enum系の型のドロップダウンのための関数 enumFieldList = selectFieldList enumPairs enumPairs = map (T.pack . show &&& id ) $ [minBound..maxBound] guestForm :: Form Guest guestForm = guestForm' Nothing guestForm' :: Maybe Guest -> Form Guest guestForm' mguest = renderDivs $ Guest <$> areq textField "Name" (guestName <$> mguest) <*> areq intField "Age" (guestAge <$> mguest) <*> areq boolField "Attend" (guestAttend <$> mguest) <*> areq enumFieldList "Blood" (guestBlood <$> mguest) data ItemForm = ItemForm { itemFormName :: Text , itemFormPrice :: Int , itemFormAvailable :: Bool , itemFormMemo :: Maybe Text } deriving Show itemForm :: Form ItemForm itemForm = renderBootstrap $ ItemForm <$> areq textField "Name" Nothing <*> areq intField "Price" Nothing <*> areq boolField "Available" Nothing <*> aopt textField "Memo" Nothing
seizans/yesod-tutorial
Forms.hs
bsd-2-clause
1,278
0
11
257
371
212
159
-1
-1
import Data.Function.ArrayMemoize import Criterion.Main -- Compiled with: ghc -O2 --make heat-benchmark.hs -- Run with: ./benchmark -o heat-benchmark-results.html foo x = undefined -- discretize delx (continuize delx x) alpha = 0.23 delt = 0.05 :: Float delx = 0.1 :: Float nt = 5 :: Float nx = 3 :: Float heat' :: ((Float, Float) -> Float) -> (Float, Float) -> Float heat' _ (0.0, t) = 1 heat' _ (3, t) = 0 heat' _ (x, 0.0) = 0 heat' h (x, t) = (h' x) + r * (h' (x - delx) - 2 * (h' x) + h' (x + delx)) where h' x = h (x, t - delt) r = alpha * (delt / (delx * delx)) -- Discrete heat function (requires writing unfixed version (or used macro), semantically easy) heatD :: (Int, Int) -> Float heatD = discreteMemoFix ((0, 0), (nx, nt)) (delx, delt) heat' -- Quantized heat function (as above, but semantically can be tricky around edges) heatQ :: (Float, Float) -> Float heatQ = quantizedMemoFix ((0, 0), (nx, nt)) (delx, delt) heat' heat'' :: (Float, Float) -> Float heat'' (0.0, t) = 1 heat'' (3, t) = 0 heat'' (x, 0.0) = 0 heat'' (x, t) = (h' x) + r * (h' (x - delx) - 2 * (h' x) + h' (x + delx)) where h' x = heatQB (x, t - delt) r = alpha * (delt / (delx * delx)) -- Discrete heat function (via quantization) (syntactically the easiest, but slower than D) heatQB = quantizedMemo ((0, 0), (nx, nt)) (delx, delt) heat'' heatD2 :: (Int, Int) -> Float heatD2 = heatQB . (continuize (delx,delt)) -- Alternate discrete definition using fixed-point outside of the library (a bit cumbersome- manual discretization used) heatA :: (Float, Float) -> Float heatA (0.0, t) = 1 heatA (3, t) = 0 heatA (x, 0.0) = 0 heatA (x, t) = (h' x) + r * (h' (x - delx) - 2 * (h' x) + h' (x + delx)) where h' x = heatD3 (discretize delx x, (discretize delt t) - 1) r = alpha * (delt / (delx * delx)) heatD3 :: (Int, Int) -> Float heatD3 = discreteMemo ((0, 0), (nx, nt)) (delx, delt) heatA -- The following is a nice style for writing it all together- and reasonably fast - faster than D2 heat :: (Int, Int) -> Float heat = let -- Parameter setup alpha = 0.23 dt = 0.05 dx = 0.1 nt = 5 nx = 3 r = alpha * (dt / (dx * dx)) -- Continuous heat equation h :: (Float, Float) -> Float h (x, t) | x == 0.0 = 1 | x == nx = 0 | t == 0.0 = 0 | otherwise = h'(x, t-dt) + r * (h'(x-dx, t-dt) - 2*(h'(x, t-dt)) + h'(x+dx, t-dt)) -- Faster quantized heat equation h' = quantizedMemo ((0, 0), (nx, nt)) (dx, dt) h -- Finally return discrete version in discrete h' (dx, dt) heatDub :: (Int, Int) -> Double heatDub = let -- Parameter setup alpha = 0.23 dt = 0.05 dx = 0.1 nt = 5 nx = 3 r = alpha * (dt / (dx * dx)) -- Continuous heat equation h :: (Double, Double) -> Double h (x, t) | x == 0.0 = 1 | x == nx = 0 | t == 0.0 = 0 | otherwise = h'(x, t-dt) + r * (h'(x-dx, t-dt) - 2*(h'(x, t-dt)) + h'(x+dx, t-dt)) -- Faster quantized heat equation h' = quantizedMemo ((0, 0), (nx, nt)) (dx, dt) h -- Finally return discrete version in discrete h' (dx, dt) fix f = f (fix f) main = defaultMain [ bcompare[ bench "heat fix (0.2,0.1)" $ whnf (fix heat') (0.2,0.1), -- These reults turn out as the same as the previous as the -- memoization memoizes the whole thing -- bench "heatD '(0.2, 0.1)'" $ whnf heatD (2,2), -- bench "heatQ (0.2,0.1)" $ whnf heatQ (0.2,0.1), -- bench "heatQB (0.2,0.1)" $ whnf heatQB (0.2,0.1), -- bench "heatD2 '(0.2,0.1)'" $ whnf heatD2 (2,2), -- bench "heatD3 '(0.2,0.1)'" $ whnf heatD3 (2,2), bench "heat '(1.5, 2.5)'" $ whnf heat (15,50), bench "heat double '(1.5, 2.5)'" $ whnf heatDub (15,50), bench "heatD '(1.5, 2.5)'" $ whnf heatD (15,50), bench "heatQ (1.5,2.5)" $ whnf heatQ (1.5,2.5), bench "heatQB (1.5,2.5)" $ whnf heatQB (1.5,2.5), bench "heatD2 '(1.5,2.5)'" $ whnf heatD2 (15,50), bench "heatD3 '(1.5,2.5)'" $ whnf heatD3 (15,50)] ]
dorchard/array-memoize
heat-benchmark.hs
bsd-2-clause
4,701
0
17
1,714
1,626
907
719
78
1
matchMarker :: String -> String -> (Bool,String) matchMarker [] xs = (True, xs) matchMarker (c:cs) (x:xs) = if c == x then matchMarker cs xs else (False, (x:xs) ) dropUntilMarker :: String -> String -> (String,String) dropUntilMarker [] xs = ([],xs) dropUntilMarker cs [] = ([],[]) dropUntilMarker mkr@(c:cs) str = let str' = dropWhile (/= c) str (ismatched,str'') = matchMarker mkr str' in if ismatched then (mkr,str'') else dropUntilMarker mkr (tail str'') takeUntilMarker :: String -> String -> (String,String) takeUntilMarker [] xs = ([],xs) takeUntilMarker cs [] = ([],[]) takeUntilMarker mkr@(c:cs) str = let (strpass,strremain) = break (==c) str (ismatched,strremain2) = matchMarker mkr strremain in if ismatched then (strpass,strremain2) else takeUntilMarker mkr (tail strremain2) --readheader :: String -> (String, String) --readheader str = let str2 = dropWhile (/= '<') str -- in if (str2 !! 1) == '?' -- then takeWhile (/= '?') str2 readheadertest str = let (_,str') = dropUntilMarker "<?" str in takeUntilMarker "?>" str' readtag str = let (_,str') = dropUntilMarker "<" str in takeUntilMarker ">" str' readxojtest :: String -> IO (String,String) readxojtest filename = do handle <- openFile filename ReadMode str <- hGetContents handle let (str1,str2) = readheadertest str (str3,str4) = readtag str2 return $ (str1,str3) readxoj :: String -> IO ((Double,Double),[Stroke]) readxoj filename = do handle <- openFile filename ReadMode str <- hGetContents handle let strs = lines str pagesizestr = words (strs !! 0) width = read $ pagesizestr !! 0 height = read $ pagesizestr !! 1 strokesstr = tail strs strokes = map (parseOneStroke.words) strokesstr return ((width,height),strokes) parseOneStroke :: [String] -> Stroke parseOneStroke [] = [] parseOneStroke (x:y:xs) = (read x, read y) : parseOneStroke xs
wavewave/hournal
trash.hs
bsd-2-clause
2,430
0
12
889
769
406
363
46
2
{-# LANGUAGE FlexibleContexts, Rank2Types #-} module Day14 where import Data.List (maximumBy) import Control.Monad (forM_) import qualified Data.Map.Strict as M import qualified Control.Monad.State.Lazy as S import qualified Text.Parsec as P import qualified Text.Parsec.Char as PC type Parsec s u m b = P.Stream s m Char => P.ParsecT s u m b type Rate = Int type Period = Int type Time = Int type Distance = Int bestDeer :: Int -> [(String, [(Rate, Time)])] -> [(String, Int)] bestDeer time rates = winner where deer = map fst rates map0 = M.fromList $ zip deer $ repeat 0 (winner, _) = S.runState (constructRun time) (map (fmap cycle) rates, map0, map0) constructRun :: (S.MonadState ([(String, [(Rate, Period)])], M.Map String Int, M.Map String Int) m) => Int -> m [(String, Int)] constructRun time = do forM_ [1..time] $ \_ -> do (rates, distances, totals) <- S.get -- :: ((String, rates), M.Map String Distance, M.Map String Int let deerRateAdvances = map (fmap advanceClock) rates let (rates', advances) = unzip $ map (\(x, (r, d)) -> ((x, r), (x, d))) deerRateAdvances let distances' = foldr (\(n, v) d -> advanceValue v n d) distances advances let leaders = map fst $ lead distances' let totals' = foldr (\x acc -> advanceWinner x acc) totals leaders S.put (rates', distances', totals') (_, _, points) <- S.get -- :: ((String, rates), M.Map String Distance, M.Map String Int return $ lead points lead :: M.Map String Int -> [(String, Int)] lead = M.foldrWithKey lead' [] lead' :: String -> Int -> [(String, Int)] -> [(String, Int)] lead' k2 a2 [] = [(k2, a2)] lead' k2 a2 xxs@((_, a1):_) | a1 == a2 = (k2, a2):xxs | a2 > a1 = [(k2, a2)] | a2 < a1 = xxs advanceClock :: [(Rate, Period)] -> ([(Rate, Period)], Distance) advanceClock ((_, 0):xs) = advanceClock xs advanceClock ((x, y):xs) = ((x, y - 1):xs, x) advanceValue :: Int -> String -> M.Map String Int -> M.Map String Int advanceValue x = M.adjust (x+) advanceWinner :: String -> M.Map String Int -> M.Map String Int advanceWinner = advanceValue 1 -- Part 1 leadingDeer :: Time -> [(String, [(Rate, Period)])] -> (String, Distance) leadingDeer time = maximumBy (\(_, x) (_, y) -> compare x y) . map (fmap (distance time)) distance :: Time -> [(Rate, Period)] -> Distance distance 0 _ = 0 distance time xxs@((rate, period):xs) = iterations * (distancePerIteration xxs) + periodTime * rate + distance (time - iterationsTime - periodTime) xs where totalTime = foldr (\x acc -> acc + snd x) 0 xxs iterations = time `div` totalTime iterationsTime = iterations * timePerIteration xxs periodTime = min (time - iterationsTime) period distancePerIteration :: [(Rate, Period)] -> Distance distancePerIteration = sum . uncurry (zipWith (*)) . unzip timePerIteration :: [(Rate, Period)] -> Time timePerIteration = sum . map snd -------------------------------------------------------------------------------- -- Parsing -------------------------------------------------------------------------------- parse :: String -> Either P.ParseError (String, [(Distance, Rate)]) parse = P.parse parseDistance "(string)" parseDistance :: Parsec s u m (String, [(Distance, Rate)]) parseDistance = do name <- parseIdentifier PC.string " can fly " rate <- parseInt PC.string " km/s for " duration <- parseInt PC.string " seconds, but then must rest for " restTime <- parseInt PC.string " seconds." return (name, [(rate, duration), (0, restTime)]) parseInt :: Parsec s u m Int parseInt = read <$> P.many1 P.digit parseIdentifier :: Parsec s u m String parseIdentifier = P.many PC.letter
taylor1791/adventofcode
2015/src/Day14.hs
bsd-2-clause
3,645
0
19
683
1,508
830
678
78
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : Network.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:32 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Classes.Network ( QconnectToHost(..) , QconnectToHostImplementation(..) , QcurrentId(..) , QdisconnectFromHostImplementation(..) , Qqget(..) , QhostName(..) , QmajorVersion(..) , QminorVersion(..) , Qparse(..) , QparseLine(..) , Qproxy(..) , QsetHostName(..) , QsetLocalAddress(..) , QsetLocalPort(..) , QsetPeerAddress(..) , QsetPeerName(..) , QsetPeerPort(..) , QsetProxy(..) , QsetSocketDescriptor(..) , QsetSocketError(..) , QsetSocketState(..) , QsetUser(..) , QsocketDescriptor(..) ) where import Foreign.C.Types import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.ClassTypes.Network class QconnectToHost a b c | a -> c where connectToHost :: a -> b -> c class QconnectToHostImplementation a b where connectToHostImplementation :: a -> b -> IO () class QcurrentId a b where currentId :: a -> b -> IO (Int) class QdisconnectFromHostImplementation a b where disconnectFromHostImplementation :: a -> b -> IO () class Qqget a b where qget :: a -> b -> IO (Int) class QhostName a b where hostName :: a -> b -> IO (String) class QmajorVersion a b where majorVersion :: a -> b -> IO (Int) class QminorVersion a b where minorVersion :: a -> b -> IO (Int) class Qparse a b where parse :: a -> b -> IO (Bool) class QparseLine a b where parseLine :: a -> b -> IO (Bool) class Qproxy a b where proxy :: a -> b -> IO (QNetworkProxy ()) class QsetHostName a b where setHostName :: a -> b -> IO () class QsetLocalAddress a b where setLocalAddress :: a -> b -> IO () class QsetLocalPort a b where setLocalPort :: a -> b -> IO () class QsetPeerAddress a b where setPeerAddress :: a -> b -> IO () class QsetPeerName a b where setPeerName :: a -> b -> IO () class QsetPeerPort a b where setPeerPort :: a -> b -> IO () class QsetProxy a b c | a -> c where setProxy :: a -> b -> c class QsetSocketDescriptor a b where setSocketDescriptor :: a -> b -> IO (Bool) class QsetSocketError a b where setSocketError :: a -> b -> IO () class QsetSocketState a b where setSocketState :: a -> b -> IO () class QsetUser a b c | a -> c where setUser :: a -> b -> c class QsocketDescriptor a b where socketDescriptor :: a -> b -> IO (Int)
keera-studios/hsQt
Qtc/Classes/Network.hs
bsd-2-clause
2,640
0
12
540
889
484
405
-1
-1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QHBoxLayout_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:25 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QHBoxLayout_h where import Qtc.Enums.Base import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs_h import Qtc.Classes.Core_h import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui_h import Qtc.ClassTypes.Gui import Foreign.Marshal.Array instance QunSetUserMethod (QHBoxLayout ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QHBoxLayout_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QHBoxLayout_unSetUserMethod" qtc_QHBoxLayout_unSetUserMethod :: Ptr (TQHBoxLayout a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QHBoxLayoutSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QHBoxLayout_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QHBoxLayout ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QHBoxLayout_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QHBoxLayoutSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QHBoxLayout_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QHBoxLayout ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QHBoxLayout_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QHBoxLayoutSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QHBoxLayout_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QHBoxLayout ()) (QHBoxLayout x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QHBoxLayout setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QHBoxLayout_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QHBoxLayout_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setUserMethod" qtc_QHBoxLayout_setUserMethod :: Ptr (TQHBoxLayout a) -> CInt -> Ptr (Ptr (TQHBoxLayout x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QHBoxLayout :: (Ptr (TQHBoxLayout x0) -> IO ()) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QHBoxLayout_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QHBoxLayoutSc a) (QHBoxLayout x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QHBoxLayout setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QHBoxLayout_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QHBoxLayout_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetUserMethod (QHBoxLayout ()) (QHBoxLayout x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QHBoxLayout setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QHBoxLayout_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QHBoxLayout_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setUserMethodVariant" qtc_QHBoxLayout_setUserMethodVariant :: Ptr (TQHBoxLayout a) -> CInt -> Ptr (Ptr (TQHBoxLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QHBoxLayout :: (Ptr (TQHBoxLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QHBoxLayout_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QHBoxLayoutSc a) (QHBoxLayout x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QHBoxLayout setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QHBoxLayout_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QHBoxLayout_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QunSetHandler (QHBoxLayout ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QHBoxLayout_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QHBoxLayout_unSetHandler" qtc_QHBoxLayout_unSetHandler :: Ptr (TQHBoxLayout a) -> CWString -> IO (CBool) instance QunSetHandler (QHBoxLayoutSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QHBoxLayout_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> QLayoutItem t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> Ptr (TQLayoutItem t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qHBoxLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler1" qtc_QHBoxLayout_setHandler1 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> Ptr (TQLayoutItem t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout1 :: (Ptr (TQHBoxLayout x0) -> Ptr (TQLayoutItem t1) -> IO ()) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> Ptr (TQLayoutItem t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> QLayoutItem t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> Ptr (TQLayoutItem t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qHBoxLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QaddItem_h (QHBoxLayout ()) ((QLayoutItem t1)) where addItem_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHBoxLayout_addItem cobj_x0 cobj_x1 foreign import ccall "qtc_QHBoxLayout_addItem" qtc_QHBoxLayout_addItem :: Ptr (TQHBoxLayout a) -> Ptr (TQLayoutItem t1) -> IO () instance QaddItem_h (QHBoxLayoutSc a) ((QLayoutItem t1)) where addItem_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHBoxLayout_addItem cobj_x0 cobj_x1 instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler2" qtc_QHBoxLayout_setHandler2 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout2 :: (Ptr (TQHBoxLayout x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qcount_h (QHBoxLayout ()) (()) where count_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_count cobj_x0 foreign import ccall "qtc_QHBoxLayout_count" qtc_QHBoxLayout_count :: Ptr (TQHBoxLayout a) -> IO CInt instance Qcount_h (QHBoxLayoutSc a) (()) where count_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_count cobj_x0 instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> IO (Orientations)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO (CLong) setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then withQFlagsResult $ return $ toCLong 0 else _handler x0obj rvf <- rv return (toCLong $ qFlags_toInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler3" qtc_QHBoxLayout_setHandler3 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> IO (CLong)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout3 :: (Ptr (TQHBoxLayout x0) -> IO (CLong)) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> IO (CLong))) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> IO (Orientations)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO (CLong) setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then withQFlagsResult $ return $ toCLong 0 else _handler x0obj rvf <- rv return (toCLong $ qFlags_toInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QexpandingDirections_h (QHBoxLayout ()) (()) where expandingDirections_h x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_expandingDirections cobj_x0 foreign import ccall "qtc_QHBoxLayout_expandingDirections" qtc_QHBoxLayout_expandingDirections :: Ptr (TQHBoxLayout a) -> IO CLong instance QexpandingDirections_h (QHBoxLayoutSc a) (()) where expandingDirections_h x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_expandingDirections cobj_x0 instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO (CBool) setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return False else _handler x0obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler4" qtc_QHBoxLayout_setHandler4 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout4 :: (Ptr (TQHBoxLayout x0) -> IO (CBool)) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO (CBool) setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return False else _handler x0obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QhasHeightForWidth_h (QHBoxLayout ()) (()) where hasHeightForWidth_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_hasHeightForWidth cobj_x0 foreign import ccall "qtc_QHBoxLayout_hasHeightForWidth" qtc_QHBoxLayout_hasHeightForWidth :: Ptr (TQHBoxLayout a) -> IO CBool instance QhasHeightForWidth_h (QHBoxLayoutSc a) (()) where hasHeightForWidth_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_hasHeightForWidth cobj_x0 instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qHBoxLayoutFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler5" qtc_QHBoxLayout_setHandler5 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout5 :: (Ptr (TQHBoxLayout x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> CInt -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qHBoxLayoutFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QheightForWidth_h (QHBoxLayout ()) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_heightForWidth cobj_x0 (toCInt x1) foreign import ccall "qtc_QHBoxLayout_heightForWidth" qtc_QHBoxLayout_heightForWidth :: Ptr (TQHBoxLayout a) -> CInt -> IO CInt instance QheightForWidth_h (QHBoxLayoutSc a) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_heightForWidth cobj_x0 (toCInt x1) instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO () setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler6" qtc_QHBoxLayout_setHandler6 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout6 :: (Ptr (TQHBoxLayout x0) -> IO ()) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO () setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qinvalidate_h (QHBoxLayout ()) (()) where invalidate_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_invalidate cobj_x0 foreign import ccall "qtc_QHBoxLayout_invalidate" qtc_QHBoxLayout_invalidate :: Ptr (TQHBoxLayout a) -> IO () instance Qinvalidate_h (QHBoxLayoutSc a) (()) where invalidate_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_invalidate cobj_x0 instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> Int -> IO (QLayoutItem t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0)) setHandlerWrapper x0 x1 = do x0obj <- qHBoxLayoutFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler7" qtc_QHBoxLayout_setHandler7 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout7 :: (Ptr (TQHBoxLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0))) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0)))) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> Int -> IO (QLayoutItem t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> CInt -> IO (Ptr (TQLayoutItem t0)) setHandlerWrapper x0 x1 = do x0obj <- qHBoxLayoutFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QitemAt_h (QHBoxLayout ()) ((Int)) where itemAt_h x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_itemAt cobj_x0 (toCInt x1) foreign import ccall "qtc_QHBoxLayout_itemAt" qtc_QHBoxLayout_itemAt :: Ptr (TQHBoxLayout a) -> CInt -> IO (Ptr (TQLayoutItem ())) instance QitemAt_h (QHBoxLayoutSc a) ((Int)) where itemAt_h x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_itemAt cobj_x0 (toCInt x1) instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler8" qtc_QHBoxLayout_setHandler8 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout8 :: (Ptr (TQHBoxLayout x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> IO (Ptr (TQSize t0)))) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QqmaximumSize_h (QHBoxLayout ()) (()) where qmaximumSize_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_maximumSize cobj_x0 foreign import ccall "qtc_QHBoxLayout_maximumSize" qtc_QHBoxLayout_maximumSize :: Ptr (TQHBoxLayout a) -> IO (Ptr (TQSize ())) instance QqmaximumSize_h (QHBoxLayoutSc a) (()) where qmaximumSize_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_maximumSize cobj_x0 instance QmaximumSize_h (QHBoxLayout ()) (()) where maximumSize_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_maximumSize_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QHBoxLayout_maximumSize_qth" qtc_QHBoxLayout_maximumSize_qth :: Ptr (TQHBoxLayout a) -> Ptr CInt -> Ptr CInt -> IO () instance QmaximumSize_h (QHBoxLayoutSc a) (()) where maximumSize_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_maximumSize_qth cobj_x0 csize_ret_w csize_ret_h instance QminimumHeightForWidth_h (QHBoxLayout ()) ((Int)) where minimumHeightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_minimumHeightForWidth cobj_x0 (toCInt x1) foreign import ccall "qtc_QHBoxLayout_minimumHeightForWidth" qtc_QHBoxLayout_minimumHeightForWidth :: Ptr (TQHBoxLayout a) -> CInt -> IO CInt instance QminimumHeightForWidth_h (QHBoxLayoutSc a) ((Int)) where minimumHeightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_minimumHeightForWidth cobj_x0 (toCInt x1) instance QqminimumSize_h (QHBoxLayout ()) (()) where qminimumSize_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_minimumSize cobj_x0 foreign import ccall "qtc_QHBoxLayout_minimumSize" qtc_QHBoxLayout_minimumSize :: Ptr (TQHBoxLayout a) -> IO (Ptr (TQSize ())) instance QqminimumSize_h (QHBoxLayoutSc a) (()) where qminimumSize_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_minimumSize cobj_x0 instance QminimumSize_h (QHBoxLayout ()) (()) where minimumSize_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_minimumSize_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QHBoxLayout_minimumSize_qth" qtc_QHBoxLayout_minimumSize_qth :: Ptr (TQHBoxLayout a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSize_h (QHBoxLayoutSc a) (()) where minimumSize_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_minimumSize_qth cobj_x0 csize_ret_w csize_ret_h instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> QRect t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> Ptr (TQRect t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qHBoxLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler9" qtc_QHBoxLayout_setHandler9 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> Ptr (TQRect t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout9 :: (Ptr (TQHBoxLayout x0) -> Ptr (TQRect t1) -> IO ()) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> Ptr (TQRect t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> QRect t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> Ptr (TQRect t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qHBoxLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QqsetGeometry_h (QHBoxLayout ()) ((QRect t1)) where qsetGeometry_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHBoxLayout_setGeometry cobj_x0 cobj_x1 foreign import ccall "qtc_QHBoxLayout_setGeometry" qtc_QHBoxLayout_setGeometry :: Ptr (TQHBoxLayout a) -> Ptr (TQRect t1) -> IO () instance QqsetGeometry_h (QHBoxLayoutSc a) ((QRect t1)) where qsetGeometry_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHBoxLayout_setGeometry cobj_x0 cobj_x1 instance QsetGeometry_h (QHBoxLayout ()) ((Rect)) where setGeometry_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QHBoxLayout_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QHBoxLayout_setGeometry_qth" qtc_QHBoxLayout_setGeometry_qth :: Ptr (TQHBoxLayout a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry_h (QHBoxLayoutSc a) ((Rect)) where setGeometry_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QHBoxLayout_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QqsizeHint_h (QHBoxLayout ()) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_sizeHint cobj_x0 foreign import ccall "qtc_QHBoxLayout_sizeHint" qtc_QHBoxLayout_sizeHint :: Ptr (TQHBoxLayout a) -> IO (Ptr (TQSize ())) instance QqsizeHint_h (QHBoxLayoutSc a) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_sizeHint cobj_x0 instance QsizeHint_h (QHBoxLayout ()) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QHBoxLayout_sizeHint_qth" qtc_QHBoxLayout_sizeHint_qth :: Ptr (TQHBoxLayout a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint_h (QHBoxLayoutSc a) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance QtakeAt_h (QHBoxLayout ()) ((Int)) where takeAt_h x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_takeAt cobj_x0 (toCInt x1) foreign import ccall "qtc_QHBoxLayout_takeAt" qtc_QHBoxLayout_takeAt :: Ptr (TQHBoxLayout a) -> CInt -> IO (Ptr (TQLayoutItem ())) instance QtakeAt_h (QHBoxLayoutSc a) ((Int)) where takeAt_h x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_takeAt cobj_x0 (toCInt x1) instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> QObject t1 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> Ptr (TQObject t1) -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qHBoxLayoutFromPtr x0 x1obj <- qObjectFromPtr x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler10" qtc_QHBoxLayout_setHandler10 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> Ptr (TQObject t1) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout10 :: (Ptr (TQHBoxLayout x0) -> Ptr (TQObject t1) -> IO (CInt)) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> Ptr (TQObject t1) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> QObject t1 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> Ptr (TQObject t1) -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qHBoxLayoutFromPtr x0 x1obj <- qObjectFromPtr x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QindexOf_h (QHBoxLayout ()) ((QWidget t1)) where indexOf_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHBoxLayout_indexOf cobj_x0 cobj_x1 foreign import ccall "qtc_QHBoxLayout_indexOf" qtc_QHBoxLayout_indexOf :: Ptr (TQHBoxLayout a) -> Ptr (TQWidget t1) -> IO CInt instance QindexOf_h (QHBoxLayoutSc a) ((QWidget t1)) where indexOf_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHBoxLayout_indexOf cobj_x0 cobj_x1 instance QqisEmpty_h (QHBoxLayout ()) (()) where qisEmpty_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_isEmpty cobj_x0 foreign import ccall "qtc_QHBoxLayout_isEmpty" qtc_QHBoxLayout_isEmpty :: Ptr (TQHBoxLayout a) -> IO CBool instance QqisEmpty_h (QHBoxLayoutSc a) (()) where qisEmpty_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_isEmpty cobj_x0 instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> IO (QObject t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout11 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout11_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO (Ptr (TQObject t0)) setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler11" qtc_QHBoxLayout_setHandler11 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> IO (Ptr (TQObject t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout11 :: (Ptr (TQHBoxLayout x0) -> IO (Ptr (TQObject t0))) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> IO (Ptr (TQObject t0)))) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> IO (QObject t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout11 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout11_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO (Ptr (TQObject t0)) setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qlayout_h (QHBoxLayout ()) (()) where layout_h x0 () = withQLayoutResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_layout cobj_x0 foreign import ccall "qtc_QHBoxLayout_layout" qtc_QHBoxLayout_layout :: Ptr (TQHBoxLayout a) -> IO (Ptr (TQLayout ())) instance Qlayout_h (QHBoxLayoutSc a) (()) where layout_h x0 () = withQLayoutResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_layout cobj_x0 instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> IO (QRect t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout12 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout12_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO (Ptr (TQRect t0)) setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler12" qtc_QHBoxLayout_setHandler12 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> IO (Ptr (TQRect t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout12 :: (Ptr (TQHBoxLayout x0) -> IO (Ptr (TQRect t0))) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> IO (Ptr (TQRect t0)))) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> IO (QRect t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout12 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout12_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO (Ptr (TQRect t0)) setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qqgeometry_h (QHBoxLayout ()) (()) where qgeometry_h x0 () = withQRectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_geometry cobj_x0 foreign import ccall "qtc_QHBoxLayout_geometry" qtc_QHBoxLayout_geometry :: Ptr (TQHBoxLayout a) -> IO (Ptr (TQRect ())) instance Qqgeometry_h (QHBoxLayoutSc a) (()) where qgeometry_h x0 () = withQRectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_geometry cobj_x0 instance Qgeometry_h (QHBoxLayout ()) (()) where geometry_h x0 () = withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_geometry_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h foreign import ccall "qtc_QHBoxLayout_geometry_qth" qtc_QHBoxLayout_geometry_qth :: Ptr (TQHBoxLayout a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO () instance Qgeometry_h (QHBoxLayoutSc a) (()) where geometry_h x0 () = withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_geometry_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> IO (QLayoutItem t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout13 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout13_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO (Ptr (TQLayoutItem t0)) setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler13" qtc_QHBoxLayout_setHandler13 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> IO (Ptr (TQLayoutItem t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout13 :: (Ptr (TQHBoxLayout x0) -> IO (Ptr (TQLayoutItem t0))) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> IO (Ptr (TQLayoutItem t0)))) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> IO (QLayoutItem t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout13 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout13_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> IO (Ptr (TQLayoutItem t0)) setHandlerWrapper x0 = do x0obj <- qHBoxLayoutFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QspacerItem_h (QHBoxLayout ()) (()) where spacerItem_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_spacerItem cobj_x0 foreign import ccall "qtc_QHBoxLayout_spacerItem" qtc_QHBoxLayout_spacerItem :: Ptr (TQHBoxLayout a) -> IO (Ptr (TQSpacerItem ())) instance QspacerItem_h (QHBoxLayoutSc a) (()) where spacerItem_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_spacerItem cobj_x0 instance Qwidget_h (QHBoxLayout ()) (()) where widget_h x0 () = withQWidgetResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_widget cobj_x0 foreign import ccall "qtc_QHBoxLayout_widget" qtc_QHBoxLayout_widget :: Ptr (TQHBoxLayout a) -> IO (Ptr (TQWidget ())) instance Qwidget_h (QHBoxLayoutSc a) (()) where widget_h x0 () = withQWidgetResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QHBoxLayout_widget cobj_x0 instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout14 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout14_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qHBoxLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler14" qtc_QHBoxLayout_setHandler14 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout14 :: (Ptr (TQHBoxLayout x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout14 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout14_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qHBoxLayoutFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qevent_h (QHBoxLayout ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHBoxLayout_event cobj_x0 cobj_x1 foreign import ccall "qtc_QHBoxLayout_event" qtc_QHBoxLayout_event :: Ptr (TQHBoxLayout a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QHBoxLayoutSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QHBoxLayout_event cobj_x0 cobj_x1 instance QsetHandler (QHBoxLayout ()) (QHBoxLayout x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout15 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout15_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qHBoxLayoutFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QHBoxLayout_setHandler15" qtc_QHBoxLayout_setHandler15 :: Ptr (TQHBoxLayout a) -> CWString -> Ptr (Ptr (TQHBoxLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout15 :: (Ptr (TQHBoxLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQHBoxLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QHBoxLayout15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QHBoxLayoutSc a) (QHBoxLayout x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QHBoxLayout15 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QHBoxLayout15_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QHBoxLayout_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQHBoxLayout x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qHBoxLayoutFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QeventFilter_h (QHBoxLayout ()) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QHBoxLayout_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QHBoxLayout_eventFilter" qtc_QHBoxLayout_eventFilter :: Ptr (TQHBoxLayout a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter_h (QHBoxLayoutSc a) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QHBoxLayout_eventFilter cobj_x0 cobj_x1 cobj_x2
uduki/hsQt
Qtc/Gui/QHBoxLayout_h.hs
bsd-2-clause
69,572
239
19
15,999
22,998
10,985
12,013
-1
-1
{-| User Interface and Compilation process for L-System and Turtle movement student: Carlos Gomez date: Sat May 15 22:51:57 BOT 2010 -} module Main where import Graphics.UI.WXCore import Graphics.UI.WX import GenSequences import Process import ParserLS import SistemaL main :: IO() main = start gui -- | GUI for L-system gui :: IO() gui = do -- read the data base file of l-system db <- readDataBase -- variables dbls <- variable [value := db] -- lista of l-systems points <- variable [value := []] -- list of point draw lines lsystem <- variable [value := head db] -- actual l-system to use f <- frame [text := "L-System And Turtle Movement"] screen <- panel f [on paint := onScreenPaint points] -- screen is the place where to draw the lines -- state turtle spanel <- panel f [] xs <- entry spanel [text := "200"] ys <- entry spanel [text := "200"] as <- entry spanel [text := "0"] ds <- entry spanel [text := "10"] bs <- entry spanel [text := "90"] nl <- entry spanel [text := "1"] brender <- button f [text := "Render", on command := render lsystem points xs ys as ds bs nl screen] bclear <- button f [text := "Clear" , on command := set points [value := []] >> repaint screen] let opts = map getNombre db lstB <- choice spanel [items := opts, selection := 0] set lstB [on select := chgSystem lsystem lstB dbls] updateDB <- button spanel [text := "Update DB", on command := updateDataBase lstB dbls lsystem] set spanel [layout := row 5 $ [ boxed "state turtle" (column 5 [ row 5 [label "x:", widget xs, label "y:", widget ys, label "angle a:", widget as] , row 5 [label "distance:", widget ds, label "angle b:", widget bs]]) , hfill $ boxed "L-System" (row 5 [label "L-System", widget lstB, label "Nro-Iterations", widget nl, widget updateDB]) ]] set f [layout := column 5 [ hfill $ widget spanel , fill $ widget screen , row 5 [hfill $ widget brender, hfill $ widget bclear]]] return () updateDataBase lstB dbls lsystem = do db <- readDataBase set dbls [value := db] let opts = map getNombre db set lstB [items := opts] set lsystem [value := head db] return () readDataBase = do lss <- catch (parseFileSistemasL "./db/db.sl") (\err -> putStrLn (show err) >> return []) let defaultLS = SistemaL "Single Line" [Simbolo "F"] [Simbolo "F"] [(Simbolo "F",[Simbolo "F"])] return $ defaultLS : lss -- | change the actual L-System to another chgSystem lsystem chc dbls = do n <- get chc selection db <- get dbls value let ls = db !! n set lsystem [value := ls] -- | generate a sequence and then render the sequence on screen render lsystem points xs ys an ds bn nl screen = do x <- get xs text y <- get ys text a <- get an text d <- get ds text b <- get bn text ns <- get nl text ls <- get lsystem value let c = black -- default init color -- we generate the sequense let sequence = generate ls (toInt ns) let tortuga = ((toDouble x, toDouble y, toRad (toDouble a)), toDouble d, toRad (toDouble b), c) listPoints <- get points value let newPoints = processSequence sequence tortuga listPoints set points [value := newPoints] repaint screen -- | draw lines on screen according to the list of points onScreenPaint points dc (Rect rx ry dx dy) = do lst <- get points value mapM_ drawP lst where drawP ((x,y), (x',y'), c) = line dc (pt x (dy-y)) (pt x' (dy-y')) [color := c] -- | Converts to Radians toRad :: Double -> Double toRad n = n / 360 * 2 * pi -- | Converts to Int toInt :: String -> Int toInt = read -- | Converts to Double toDouble :: String -> Double toDouble = read . fix where fix xss@(x:xs) = if x == '.' then '0':xss else let (tr, sr) = splitAt 2 xss in if tr == "-." then "-0."++sr else xss
carliros/lsystem
src/Main.hs
bsd-3-clause
4,521
0
17
1,605
1,511
740
771
83
3
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.EXT.IndexFunc -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/EXT/index_func.txt EXT_index_func> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.EXT.IndexFunc ( -- * Enums gl_INDEX_TEST_EXT, gl_INDEX_TEST_FUNC_EXT, gl_INDEX_TEST_REF_EXT, -- * Functions glIndexFuncEXT ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/EXT/IndexFunc.hs
bsd-3-clause
767
0
4
94
55
44
11
7
0
module Crypto.Blockchain.Mempool where import Data.Set (Set) import qualified Data.Set as Set import Data.Foldable (toList) newtype Mempool tx = Mempool { fromMempool :: Set tx } deriving (Show, Monoid) addTx :: Ord tx => tx -> Mempool tx -> Mempool tx addTx tx (Mempool txs) = Mempool (Set.insert tx txs) addTxs :: (Ord tx, Foldable t) => t tx -> Mempool tx -> Mempool tx addTxs txs' (Mempool txs) = Mempool $ Set.union txs (Set.fromList (toList txs')) removeTxs :: (Ord tx, Foldable t) => t tx -> Mempool tx -> Mempool tx removeTxs txs' (Mempool txs) = Mempool $ Set.difference (Set.fromList (toList txs')) txs
cloudhead/cryptocurrency
src/Crypto/Blockchain/Mempool.hs
bsd-3-clause
650
0
10
140
274
142
132
14
1
{-# LANGUAGE FlexibleInstances #-} module Types where data OutputStyle = LispStyle | PlainStyle data Options = Options { outputStyle :: OutputStyle , hlintOpts :: [String] , ghcOpts :: [String] , operators :: Bool , detailed :: Bool , expandSplice :: Bool , sandbox :: Maybe String } defaultOptions :: Options defaultOptions = Options { outputStyle = PlainStyle , hlintOpts = [] , ghcOpts = [] , operators = False , detailed = False , expandSplice = False , sandbox = Nothing } ---------------------------------------------------------------- convert :: ToString a => Options -> a -> String convert Options{ outputStyle = LispStyle } = toLisp convert Options{ outputStyle = PlainStyle } = toPlain class ToString a where toLisp :: a -> String toPlain :: a -> String instance ToString [String] where toLisp = addNewLine . toSexp True toPlain = unlines instance ToString [((Int,Int,Int,Int),String)] where toLisp = addNewLine . toSexp False . map toS where toS x = "(" ++ tupToString x ++ ")" toPlain = unlines . map tupToString toSexp :: Bool -> [String] -> String toSexp False ss = "(" ++ unwords ss ++ ")" toSexp True ss = "(" ++ unwords (map quote ss) ++ ")" tupToString :: ((Int,Int,Int,Int),String) -> String tupToString ((a,b,c,d),s) = show a ++ " " ++ show b ++ " " ++ show c ++ " " ++ show d ++ " " ++ quote s quote :: String -> String quote x = "\"" ++ x ++ "\"" addNewLine :: String -> String addNewLine = (++ "\n") ---------------------------------------------------------------- data Cradle = Cradle { cradleCurrentDir :: FilePath , cradleCabalDir :: Maybe FilePath , cradleCabalFile :: Maybe FilePath , cradlePackageConf :: Maybe FilePath } deriving (Eq, Show) ---------------------------------------------------------------- type GHCOption = String type IncludeDir = FilePath type Package = String
eagletmt/ghc-mod
Types.hs
bsd-3-clause
2,070
0
13
551
606
341
265
55
1
----------------------------------------------------------------------------- -- | -- Module : Data.Geometry.Instances.RealFloat -- Copyright : Copyright (C) 2015 Artem M. Chirkin <[email protected]> -- License : BSD3 -- -- Maintainer : Artem M. Chirkin <[email protected]> -- Stability : Experimental -- Portability : -- -- ----------------------------------------------------------------------------- module Data.Geometry.Instances.RealFloat () where
achirkin/fastvec
src/Data/Geometry/Instances/RealFloat.hs
bsd-3-clause
482
0
3
66
23
20
3
1
0
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Marshalling where import Control.Monad import Control.Applicative import Test.Tasty.QuickCheck import Network.TLS.Internal import Network.TLS import qualified Data.ByteString as B import Data.Word import Data.X509 import Certificate genByteString :: Int -> Gen B.ByteString genByteString i = B.pack <$> vector i instance Arbitrary Version where arbitrary = elements [ SSL2, SSL3, TLS10, TLS11, TLS12 ] instance Arbitrary ProtocolType where arbitrary = elements [ ProtocolType_ChangeCipherSpec , ProtocolType_Alert , ProtocolType_Handshake , ProtocolType_AppData ] instance Arbitrary Header where arbitrary = Header <$> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary ClientRandom where arbitrary = ClientRandom <$> (genByteString 32) instance Arbitrary ServerRandom where arbitrary = ServerRandom <$> (genByteString 32) instance Arbitrary Session where arbitrary = do i <- choose (1,2) :: Gen Int case i of 2 -> liftM (Session . Just) (genByteString 32) _ -> return $ Session Nothing instance Arbitrary DigitallySigned where arbitrary = DigitallySigned Nothing <$> genByteString 32 arbitraryCiphersIDs :: Gen [Word16] arbitraryCiphersIDs = choose (0,200) >>= vector arbitraryCompressionIDs :: Gen [Word8] arbitraryCompressionIDs = choose (0,200) >>= vector someWords8 :: Int -> Gen [Word8] someWords8 i = replicateM i (fromIntegral <$> (choose (0,255) :: Gen Int)) instance Arbitrary CertificateType where arbitrary = elements [ CertificateType_RSA_Sign, CertificateType_DSS_Sign , CertificateType_RSA_Fixed_DH, CertificateType_DSS_Fixed_DH , CertificateType_RSA_Ephemeral_DH, CertificateType_DSS_Ephemeral_DH , CertificateType_fortezza_dms ] instance Arbitrary Handshake where arbitrary = oneof [ ClientHello <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitraryCiphersIDs <*> arbitraryCompressionIDs <*> (return []) <*> (return Nothing) , ServerHello <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> (return []) , liftM Certificates (CertificateChain <$> (resize 2 $ listOf $ arbitraryX509)) , pure HelloRequest , pure ServerHelloDone , ClientKeyXchg . CKX_RSA <$> genByteString 48 --, liftM ServerKeyXchg , liftM3 CertRequest arbitrary (return Nothing) (return []) , CertVerify <$> arbitrary , Finished <$> (genByteString 12) ] {- quickcheck property -} prop_header_marshalling_id :: Header -> Bool prop_header_marshalling_id x = (decodeHeader $ encodeHeader x) == Right x prop_handshake_marshalling_id :: Handshake -> Bool prop_handshake_marshalling_id x = (decodeHs $ encodeHandshake x) == Right x where decodeHs b = case decodeHandshakeRecord b of GotPartial _ -> error "got partial" GotError e -> error ("got error: " ++ show e) GotSuccessRemaining _ _ -> error "got remaining byte left" GotSuccess (ty, content) -> decodeHandshake cp ty content cp = CurrentParams { cParamsVersion = TLS10, cParamsKeyXchgType = Just CipherKeyExchange_RSA }
erikd/hs-tls
core/Tests/Marshalling.hs
bsd-3-clause
3,589
0
14
1,018
841
444
397
82
4
{-# LANGUAGE OverloadedStrings #-} module Bot where import Data.Maybe (fromJust) import Data.List (find) import Control.Applicative ((<$>), (<*>), pure) import Control.Monad (forM, liftM) import qualified Data.Aeson as Aeson import qualified Data.Aeson.Types as Aeson import qualified Data.Text as T import qualified Data.Text.IO as T import Data.Aeson ((.=), FromJSON, parseJSON, ToJSON, toJSON, object, encode, decode) import Data.Aeson.Types ((.:)) import Text.Regex.Posix ((=~)) data Self = Self { getSelfID :: String, getSelfName :: String } deriving (Show, Read) data User = User { getUserID :: String, getUserName :: String } deriving (Show, Read) -- data that need to be modified and retreived between threads -- are not maintained here. see (MVar KernelState) in Main.hs data Bot = Bot { getSelf :: Self, getUsers :: [User], getServerHost :: String, getServerPath :: String } deriving (Show, Read) instance FromJSON Self where parseJSON (Aeson.Object v) = Self <$> (v .: "id") <*> (v .: "name") instance FromJSON User where parseJSON (Aeson.Object v) = User <$> (v .: "id") <*> (v .: "name") instance FromJSON Bot where parseJSON (Aeson.Object v) = Bot <$> self <*> users <*> (pure host) <*> (pure path) where self = v .: "self" :: Aeson.Parser Self users = v .: "users" :: Aeson.Parser [User] Aeson.Success (host, path) = flip Aeson.parse v $ \obj -> do url <- obj .: "url" :: Aeson.Parser String let (h1, h2, h3) = url =~ (".com" :: String) :: (String, String, String) return (drop 6 $ h1++h2, h3) -- from bot to slack data SendMessage = Message { id :: Int, channel :: String, text :: String } deriving Show instance ToJSON SendMessage where toJSON (Message id chan txt) = object ["id" .= id, "channel" .= chan, "text" .= txt, "type" .= ("message" :: String)] -- from slack to bot data ReceiveMessage = ReceiveSimpleMessage { receiveMessage_channel :: String, receiveMessage_user :: String, receiveMessage_text :: String } deriving Show -- parsing utils getProp :: Aeson.Object -> String -> String getProp json prop = case getPropParser json prop of Aeson.Success v -> v Aeson.Error _ -> undefined hasProp :: Aeson.Object -> String -> Bool hasProp json prop = case getPropParser json prop of Aeson.Success v -> True Aeson.Error _ -> False getPropParser :: Aeson.Object -> String -> Aeson.Result String getPropParser json prop = flip Aeson.parse json $ \obj -> obj .: (T.pack prop) :: Aeson.Parser String getUserWithID bot userID = fromJust $ find f (getUsers bot) where f (User id name) = id == userID getUserWithName bot userName = find f (getUsers bot) where f (User id name) = name == userName parseMessage json = ReceiveSimpleMessage { receiveMessage_channel = getProp json "channel" :: String, receiveMessage_user = getProp json "user" :: String, receiveMessage_text = getProp json "text" :: String }
clug-kr/democracy_bot
src/Bot.hs
bsd-3-clause
2,889
44
16
518
1,053
586
467
74
2
module Util where import GHC import Outputable import Data.Text (Text) import qualified Data.Text as T sdocToText :: Outputable a => DynFlags -> a -> Text sdocToText dflags doc = T.pack (show (runSDoc (ppr doc) (initSDocContext dflags defaultUserStyle))) instance Outputable SDoc where ppr = id pprPrec _ sdoc = sdoc
monto-editor/services-haskell
src/Util.hs
bsd-3-clause
356
0
11
88
114
62
52
10
1
module Ordering where import System.Environment import System.Exit import System.IO import System.Random import Control.Monad.Random import Control.Monad (replicateM) import Data.Ord import Data.Function (on) import Data.List import qualified Data.Set as Set import qualified Data.Map as Map import Data.Map ((!)) import Util type Paper = String type Email = String type Conflicts = Map.Map Paper [Email] type Schedule = [[String]] with :: Conflicts -> Paper -> [Email] with c p = sort $ Map.findWithDefault [] p c overlap :: [String] -> [String] -> Int overlap xs ys = length $ xs `intersect` ys bestChoice :: Paper -> [Paper] -> Conflicts -> (Paper,[Paper]) bestChoice paper papers conflicts = let conflicted = conflicts `with` paper in let options = map (\p -> (p,Down $ conflicted `overlap` (conflicts `with` p))) papers in let (best:rest) = map fst $ sortBy (compare `on` snd) options in (best,rest) greedySearch :: Paper -> [Paper] -> Conflicts -> Schedule greedySearch paper [] conflicts = [paper : (conflicts `with` paper)] greedySearch paper papers conflicts = let (next,papers') = bestChoice paper papers conflicts in (paper : (conflicts `with` paper)) : greedySearch next papers' conflicts greedyOrdering :: RandomGen g => [Paper] -> Conflicts -> Rand g Schedule greedyOrdering papers conflicts = do let n = length papers r <- getRandomR (0,n-1) let pivot = papers !! r let papers' = take r papers ++ drop (r+1) papers return $ greedySearch pivot papers' conflicts cost :: [[String]] -> Int cost [] = 0 cost [(_:cs)] = length cs cost ((_:cs1):p2@(_:cs2):papers) = length cs1 - (cs1 `overlap` cs2) + cost (p2:papers) repeatedGreedyOrderings :: RandomGen g => [Paper] -> Conflicts -> Int -> Rand g Schedule repeatedGreedyOrderings papers conflicts runs = do orderings <- replicateM runs (greedyOrdering papers conflicts) return $ minimumBy (compare `on` cost) orderings optimalGreedyOrdering :: [Paper] -> Conflicts -> (Schedule,[Int]) optimalGreedyOrdering papers conflicts = (optimal,map snd costs) where optimal = fst $ minimumBy (compare `on` snd) costs costs = map (\s -> (s,cost s)) orderings orderings = map (\(pivot,ps) -> greedySearch pivot ps conflicts) pivots pivots = [(papers !! i,take i papers ++ drop (i+1) papers) | i <- [0..length papers-1]] main :: IO () main = do args <- getArgs case args of [paperFile,conflictFile,pcFile] -> do -- read in the data paperCSV <- readCSV paperFile paperHeaders let papers = concat paperCSV rawConflicts <- readCSV conflictFile conflictHeaders pc <- readCSV pcFile pcHeaders -- pc members let emails = Set.fromList $ map (\[_,_,email,_] -> email) pc -- filter out conflicts for non-papers and non-pc members let realConflicts = filter (\[paper,_,email,_] -> paper `elem` papers && email `Set.member` emails) rawConflicts let conflicts = Map.fromListWith (\cs1 cs2 -> sort $ cs1 ++ cs2) $ map (\[paper,_,email,_] -> (paper,[email])) realConflicts -- reorder the papers -- schedule <- evalRandIO $ repeatedGreedyOrderings papers conflicts 10 let (schedule,costs) = optimalGreedyOrdering papers conflicts hPutStr stderr $ "Schedule has " ++ show (length schedule) ++ " papers under discussion.\n" -- hPutStr stderr $ "Chose schedule with minimal cost " ++ show (cost schedule) ++ " out of " ++ show costs putStr $ intercalate "\n" $ map (intercalate ",") schedule exitSuccess _ -> do name <- getProgName putStrLn $ "Usage: " ++ name ++ " [paper list] [conflict CSV] [pc list]" exitFailure
mgree/conflict
ordering.hs
bsd-3-clause
3,945
7
17
1,027
1,340
726
614
78
2
module Language.StreamIt.Compile ( Embedding (..), compile, ) where import Data.ByteString.Lazy (ByteString) import Data.Word import Data.Typeable import qualified Data.ByteString.Lazy as L import qualified Data.Text as DT (replace, pack, unpack) -- import qualified Data.ByteString as B import Control.Exception import Control.Monad import qualified Control.Monad.State as S import Control.Monad.Trans (MonadIO(..)) import Codec.Compression.GZip import Foreign.Ptr import Foreign.C.Types import Foreign.C.String import System.Cmd import System.Exit import System.Directory import System.IO.Temp import System.Posix.Files import Language.Haskell.TH hiding (Exp) import Language.Haskell.TH.Syntax hiding (Exp) import qualified Language.Haskell.TH.Syntax as THS import Language.Haskell.TH.Lift.Extras import Language.StreamIt.Backend import Language.StreamIt.Core import Language.StreamIt.Graph $(deriveLiftAbstract ''Word8 'fromInteger 'toInteger) $(deriveLiftAbstract ''ByteString 'L.pack 'L.unpack) foreign import ccall smain :: CInt -> Ptr CString -> IO CInt data Embedding = EmbBinary L.ByteString | DynLink L.ByteString | DynLoad L.ByteString -- | Compiles the given StreamIt file (using strc) to an executable and -- returns the directory in which the file was generated. callStrc :: FilePath -> IO (FilePath) callStrc file = do fp <- createTempDirectory "." "streamit.d" bracket getCurrentDirectory setCurrentDirectory (\_ -> do setCurrentDirectory fp exitCode <- rawSystem "strc" ["../" ++ file] S.when (exitCode /= ExitSuccess) $ fail "strc failed.") return fp -- | Compile a generated TBB C++ file (using g++) and returns the directory -- in which the file was generated callTbb file = do fp <- createTempDirectory "." "streamit.d" bracket getCurrentDirectory setCurrentDirectory (\_ -> do setCurrentDirectory fp exitCode <- rawSystem "g++" ["-O2 -DNDEBUG", "../" ++ file, "-ltbb -lrt"] S.when (exitCode /= ExitSuccess) $ fail "g++ failed.") return fp generateSharedLib :: FilePath -> IO String generateSharedLib tdir = do bracket getCurrentDirectory setCurrentDirectory (\_ -> do setCurrentDirectory tdir txt <- readFile "combined_threads.cpp" writeFile "combined_threads.cpp" $ DT.unpack (DT.replace (DT.pack "int main(int argc") (DT.pack "extern \"C\" int smain(int argc") (DT.pack txt)) exist <- fileExist "combined_threads.o" when exist $ removeFile "combined_threads.o" exitCode <- rawSystem "g++" ["-O3 -fPIC -I$STREAMIT_HOME/library/cluster", "-c -o combined_threads.o" , "combined_threads.cpp"] when (exitCode /= ExitSuccess) $ fail "g++ failed." exitCode <- rawSystem "g++" ["-O3 -fPIC -shared -Wl,-soname,libaout.so -o ../libaout.so", "combined_threads.o", "-L$STREAMIT_HOME/library/cluster", "-lpthread -lcluster -lstdc++"] when (exitCode /= ExitSuccess) $ fail "g++ failed.") return "libaout.so" -- Compile and embed the resulting executable as a lazy bytestring compileEmbed :: (Elt a, Elt b, Typeable a, Typeable b) => Target -> StreamIt a b () -> Q THS.Exp compileEmbed target s = do f <- liftIO $ codeGen target s dir <- case target of StreamIt -> liftIO $ callStrc f TBB -> liftIO $ callTbb f bs <- liftIO $ L.readFile $ dir ++ "/a.out" liftIO $ removeDirectoryRecursive dir [| EmbBinary (L.pack $(lift (L.unpack $ compress bs)))|] instance MonadIO Q where liftIO = runIO -- Compile as a shared library and dynamically link to it compileDynLink :: (Elt a, Elt b, Typeable a, Typeable b) => Target -> StreamIt a b () -> Q THS.Exp compileDynLink target s = do f <- liftIO $ codeGen target s dir <- case target of StreamIt -> liftIO $ callStrc f TBB -> liftIO $ callTbb f shlib <- liftIO $ generateSharedLib dir liftIO $ removeDirectoryRecursive dir -- dynamically link libaout.so [| DynLink (L.pack $(lift shlib))|] -- Compile as a shared library and load it using `dlsym` at runtime compileDynLoad :: (Elt a, Elt b, Typeable a, Typeable b) => Target -> StreamIt a b () -> Q THS.Exp compileDynLoad target s = do f <- liftIO $ codeGen target s dir <- case target of StreamIt -> liftIO $ callStrc f TBB -> liftIO $ callTbb f shlib <- liftIO $ generateSharedLib dir liftIO $ removeDirectoryRecursive dir [| DynLoad (L.pack $(lift shlib))|] -- Default compilation method compile :: (Elt a, Elt b, Typeable a, Typeable b) => Target -> StreamIt a b () -> Q THS.Exp compile = compileEmbed
iu-parfunc/haskell-streamit
Language/StreamIt/Compile.hs
bsd-3-clause
4,617
0
18
912
1,255
648
607
-1
-1
import Test.Hspec import Test.ProductionRule main :: IO () main = do Test.ProductionRule.test
YLiLarry/parser241-production-rule
test/Spec.hs
bsd-3-clause
99
0
7
17
32
17
15
5
1
-- | -- Module : Prose.Normalization -- Copyright : (c) 2014–2015 Antonio Nikishaev -- -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- -- module Prose.Normalization where import qualified Prose.Properties.DecompD as NFD import qualified Prose.Properties.DecompKD as NFKD import qualified Prose.Properties.CombiningClass as CC import qualified Prose.Properties.Comp as Comp import qualified Data.Map as M import qualified Data.Set as S import qualified Data.List.Sequences as ListSeq import Control.Monad (ap) import Control.Applicative ((<$>)) import Data.List import Data.Ord import Data.Tuple (swap) import Data.Monoid type DecompMap = M.Map Char [Char] type CompMap = M.Map [Char] Char newtype Decomposed = Decomposed { unDecomposed :: [Char] } decomposeChar :: DecompMap -> Char -> [Char] decomposeChar mp c = M.findWithDefault [c] c mp decomposeFully :: DecompMap -> Char -> Decomposed decomposeFully mp = Decomposed . fst . head . dropWhile (uncurry (/=)) . ap zip tail . iterate (concatMap (decomposeChar mp)) . (:[]) composeChars :: CompMap -> [Char] -> Maybe Char composeChars mp cs = M.lookup cs mp composeOneChar mp c = composeChars mp [c] composeTwoChars mp a b = composeChars mp [a,b] combiningClassOf :: Char -> Int combiningClassOf c = M.findWithDefault 0 c CC.combiningclass decomposeD, decomposeKD :: [Char] -> [Char] decomposeD = decompose NFD.decompd decomposeKD = decompose NFKD.decompkd splitToCCClusters :: [Char] -> [[(Char,Int)]] splitToCCClusters = ListSeq.splitSeq brk . map (ap (,) combiningClassOf) where brk _ (_,0) = False brk _ _ = True decompose :: DecompMap -> [Char] -> [Char] decompose mp = map fst . concatMap (sortBy (comparing snd)) . splitToCCClusters . concatMap (unDecomposed . decomposeFully mp) -- | try to compose a and b in sequence <a … pv b> -- see Unicode7.0:3.11:D115 canCompose :: Char -> Char -> Char -> Maybe Char canCompose a b pv | bcc==0 && pvcc==0 = composed | pvcc < bcc = composed | otherwise = Nothing where composed = composeTwoChars Comp.comp a b bcc = combiningClassOf b pvcc = combiningClassOf pv composeC :: [Char] -> [Char] composeC = M.elems . compose0 . decomposeD compose0 :: [Char] -> M.Map Int Char compose0 [] = M.empty compose0 s = go 1 2 . M.fromList . zip [1..] $ s where -- Unicode Standard, 3.11:D117 -- Canonical Composition Algorithm -- current starter current char go :: Int -> Int -> M.Map Int Char -> M.Map Int Char go _ i str | i > max = str where (max,_) = M.findMax str go s i str = case canCompose sc ic pc of -- we can compose <Ic, Sc> with X: -- change Ic to X, remove Sc Just x -> go s (i+1) . M.adjust (const x) s . M.delete i $ str -- cannot compose, but see if we have a new starter (ccc==0) Nothing -> go s' (i+1) str where s' | combiningClassOf ic == 0 = i | otherwise = s where sc = str M.! s ic = str M.! i Just (_,pc) = M.lookupLT i str {- compose' [] = [] compose' s = map fst $ go ss (Just 1) ss' where (ss:ss') = map mapFromList . splitToCCClusters $ decomposeD s mapFromList = M.fromList . zip [1..] mapToList = M.elems go clu (Just i) rest = case co c p Nothing of Just x -> go (x : (cs\\[p])) i' rest Nothing -> go clu i' rest where Just (c,cs) = M.minView clu i' = fst <$> M.lookupGT i clu p = clu M.! i go clu Nothing rest@(ls0:ls') = case co c l Nothing of Just x -> go ([x] <> cs <> ls) ls ls' Nothing -> clu <> go ls0 ls0 ls' where Just (c,cs) = M.minView clu go clu Nothing [] = mapToList clu -}
llelf/prose
Prose/Normalization.hs
bsd-3-clause
4,298
0
16
1,464
1,034
559
475
67
3
{-# LANGUAGE DataKinds, DeriveGeneric, TypeApplications #-} module Test62 (example, example_) where import Data.Generics.Product (field, field_, position, position_) import Optics.Core import GHC.Generics (Generic) data Foo a = Foo { bar :: Bar a } deriving Generic data Bar a = Bar { x :: a, y :: a } deriving Generic example :: Foo () example = set (field @"bar" % position @1) () . set (position @1 % field @"y") () $ Foo{ bar = Bar{ x = (), y = () } } example_ :: Foo () example_ = set (field_ @"bar" % position_ @1) () . set (position_ @1 % field_ @"y") () $ Foo{ bar = Bar{ x = (), y = () } }
kcsongor/generic-lens
generic-optics/test/Test62.hs
bsd-3-clause
614
0
11
133
289
160
129
17
1
{-# LANGUAGE TypeOperators, ScopedTypeVariables #-} module Data.Fin where import Data.Nat newtype Fin n = Fin Int deriving (Show, Eq, Ord) zero :: Fin (S n) zero = Fin 0 succ :: Fin n -> Fin (S n) succ (Fin n) = Fin (n + 1) pred :: Fin n -> Fin n pred (Fin 0) = Fin 0 pred (Fin n) = Fin (n - 1) addFin :: Fin x -> Fin y -> Fin (x :+: y) addFin (Fin x) (Fin y) = Fin $ x + y mulFin :: Fin x -> Fin y -> Fin (x :*: y) mulFin (Fin x) (Fin y) = Fin $ x * y -- 5 * Fin 13 is at most 5 * 12 = 60, or Fin 61. Is this too tight? mulNatFin :: Nat x => x -> Fin (S y) -> Fin (S (x :*: y)) mulNatFin x (Fin y) = Fin $ natToInt x * y raise :: k -> Fin n -> Fin (n :+: k) raise _ (Fin i) = Fin i intToFin :: forall n. Nat n => Int -> n -> Maybe (Fin n) intToFin i n | i >= natToInt n || i < 0 = Nothing | otherwise = Just (Fin i) finToInt :: Fin n -> Int finToInt (Fin i) = i natToFin :: Nat n => n -> Fin (S n) natToFin = Fin . natToInt
copumpkin/vector-static
Data/Fin.hs
bsd-3-clause
951
0
12
263
538
267
271
27
1
{-# LANGUAGE OverloadedStrings #-} -- | A format developed as part of the snappy-java library. -- -- From the docs: -- -- > SnappyOutputStream and SnappyInputStream use `[magic header:16 -- > bytes]([block size:int32][compressed data:byte array])*` format -- -- The following example encoding was produced on an x86 machine, yet the -- "block size" int32 appears to be big-endian. Therefore, I'm assuming -- that this is an unwritten part of the spec. -- -- Example encoding of the string "foobar\\n": -- -- > 00000000 82 53 4e 41 50 50 59 00 00 00 00 01 00 00 00 01 |.SNAPPY.........| -- > 00000010 00 00 00 09 07 18 66 6f 6f 62 61 72 0a |......foobar.| -- -- Reference: http://code.google.com/p/snappy-java/ module Codec.Compression.Snappy.Framed.SnappyJava ( parseHeader , parseBlock ) where import qualified Codec.Compression.Snappy as Snappy import Control.Monad import qualified Data.Attoparsec.Binary as AP import Data.Attoparsec.ByteString (Parser) import qualified Data.Attoparsec.ByteString as AP import Data.ByteString (ByteString) import Data.Int -- | Attempt to parse the header. If the header exists, it will be -- consumed. If not, the parser will fail. parseHeader :: Parser () parseHeader = do void $ AP.string "\x82SNAPPY\x00" -- 8-byte magic header void $ AP.string "\x00\x00\x00\x01" -- 4-byte version number void $ AP.string "\x00\x00\x00\x01" -- 4-byte min-compatible version -- | Parse a single block of the compressed bytestream, returning a segment -- of the uncompressed stream. parseBlock :: Parser ByteString parseBlock = do blockLen <- anyInt32be blockData <- AP.take (fromIntegral blockLen) return $ Snappy.decompress blockData ------------------------------------------------------------------------------- -- Helpers {-# INLINE anyInt32be #-} anyInt32be :: Parser Int32 anyInt32be = fromIntegral <$> AP.anyWord32be
asayers/snappy-framed
src/Codec/Compression/Snappy/Framed/SnappyJava.hs
bsd-3-clause
1,909
0
10
322
223
136
87
24
1
{-# LANGUAGE OverloadedStrings #-} module Pudding.Words where import Data.ByteString.Char8 as BC (ByteString, pack, append) import Data.List (intercalate) import Data.Vector (fromList) import Pudding.Core import Pudding.Imports -- pudding procedure ok :: Monad m => ByteString -> PProc m ok msg = tell . pure $ append "> " msg ng :: Monad m => ByteString -> PProc m ng msg = tell . pure $ append "*** " msg showTop :: Monad m => PProc m showTop = ok . pack . showPV =<< pop showStack :: Monad m => PProc m showStack = ok . pack . ('[':) . (++"]") . intercalate ", " . map showPV . stack =<< get showCallStack :: Monad m => PProc m showCallStack = ok . pack . show . map word . callStack =<< get numericOp2 :: Monad m => (a -> PValue) -> String -> (Double -> Double -> a) -> PProc m numericOp2 ctor name op = transaction (const msg) $ do [PVNumber a, PVNumber b] <- popN 2 push . ctor $ op b a where msg = name ++ " needs 2 Numbers" booleanOp2 :: Monad m => (a -> PValue) -> String -> (Bool -> Bool -> a) -> PProc m booleanOp2 ctor name op = transaction (const msg) $ do [PVBool a, PVBool b] <- popN 2 push . ctor $ op b a where msg = name ++ " needs 2 Booleans" booleanOp1 :: Monad m => (a -> PValue) -> String -> (Bool -> a) -> PProc m booleanOp1 ctor name op = transaction (const msg) $ do PVBool a <- pop push . ctor $ op a where msg = name ++ " needs 1 Boolean" pdrop :: Monad m => PProc m pdrop = pop >> return () nip :: Monad m => PProc m nip = do [a, _] <- popN 2 push a dup :: Monad m => PProc m dup = replicateM_ 2 . push =<< pop over :: Monad m => PProc m over = do [w2, w1] <- popN 2 mapM_ push [w1, w2, w1] tuck :: Monad m => PProc m tuck = do [w2, w1] <- popN 2 mapM_ push [w2, w1, w2] dup2 :: Monad m => PProc m dup2 = do [x, y] <- popN 2 mapM_ push [y, x, y, x] pswap :: Monad m => PProc m pswap = do [a, b] <- popN 2 mapM_ push [b, a] jump :: Monad m => PProc m jump = jump' `catchError` return (throwError "stack top is not Boolean") where jump' :: Monad m => PProc m jump' = do PVNumber a <- pop PVBool cond <- pop unless cond $ modifyPc (+ floor a) fjump :: Monad m => PProc m fjump = do PVNumber a <- pop modifyPc (+ floor a) nop :: Monad m => PProc m nop = return () -- | -- >>> cthen (PWord "then") [PNumber 1, PNumber 2, PWord "if", PBool True] -- Right [PNumber 1.0,PNumber 2.0,PWord "jump",PNumber 2.0,PBool True] -- >>> cthen (PWord "then") [PNumber 1, PWord "else", PNumber 2, PWord "if", PBool True] -- Right [PNumber 1.0,PWord "fjump",PNumber 1.0,PNumber 2.0,PWord "jump",PNumber 3.0,PBool True] -- >>> cthen (PWord "then") [PNumber 1, PNumber 1, PNumber 1, PWord "else", PNumber 2, PWord "if", PBool True] -- Right [PNumber 1.0,PNumber 1.0,PNumber 1.0,PWord "fjump",PNumber 3.0,PNumber 2.0,PWord "jump",PNumber 3.0,PBool True] -- >>> cthen (PWord "then") [PNumber 1, PWord "else", PNumber 2, PNumber 2, PNumber 2, PWord "if", PBool True] -- Right [PNumber 1.0,PWord "fjump",PNumber 1.0,PNumber 2.0,PNumber 2.0,PNumber 2.0,PWord "jump",PNumber 5.0,PBool True] cthen :: CompileProc cthen _ a = case break (== PWord "if") a of (_,[]) -> Left "then requires if" (b,_:c) -> case break (== PWord "else") b of (_,[]) -> Right $ b ++ [PWord "jump", PNumber . fromIntegral $ length b] ++ c (d,_:e) -> Right $ d ++ [PWord "fjump", PNumber . fromIntegral $ length d] ++ e ++ [PWord "jump", PNumber . fromIntegral $ length e + 2] ++ c startCompile :: Monad m => PProc m startCompile = setState NewWord endCompile :: Monad m => PProc m endCompile = do Compile name tokens <- getState setState Run insertWord name . UserDefinedWord name . fromList $ reverse tokens
masaedw/PuddingX
src/Pudding/Words.hs
bsd-3-clause
3,727
0
17
847
1,392
698
694
84
3
{-# LANGUAGE OverloadedStrings #-} module Text.Lorem.Words (latin) where import qualified Data.Text as DT -- embedding this word list with file-embed introduces template -- haskell and takes longer to compile. latin :: [DT.Text] latin = [ "a" , "ab" , "abditioribus" , "abditis" , "abesset" , "abiciam" , "abiciendum" , "abigo" , "aboleatur" , "abs" , "absconderem" , "absconditi" , "abscondo" , "absentia" , "absit" , "absorbui" , "absorbuit" , "absorpta" , "abstinentia" , "abstrusioribus" , "absunt" , "absurdissimum" , "abundabimus" , "abundantiore" , "abundare" , "abyssos" , "abyssus" , "ac" , "accedam" , "accedimus" , "accedit" , "accende" , "accepimus" , "accepisse" , "acceptabilia" , "acceptam" , "accidit" , "accipiat" , "actione" , "actiones" , "actionibus" , "ad" , "adamavi" , "addiderunt" , "adducor" , "adduxerunt" , "aderat" , "adesset" , "adest" , "adflatu" , "adhaesit" , "adhibemus" , "adhuc" , "adipiscendae" , "adipisci" , "aditu" , "aditum" , "adiungit" , "adlapsu" , "admiratio" , "admittantur" , "admitti" , "admoneas" , "admonente" , "admoniti" , "adparere" , "adparet" , "adpellata" , "adpetere" , "adprehendit" , "adprobamus" , "adprobandi" , "adpropinquet" , "adquiescat" , "adquiesco" , "adsensum" , "adsit" , "adsuefacta" , "adsunt" , "adsurgat" , "adsurgere" , "adtendi" , "adveriarius" , "adversa" , "adversis" , "adversitas" , "adversitatibus" , "adversitatis" , "adversus" , "advertenti" , "advertimus" , "aedificasti" , "aeger" , "aegre" , "aegrotantes" , "aenigmate" , "aequalis" , "aequo" , "aer" , "aeris" , "aerumnosis" , "aerumnosum" , "aestimanda" , "aestimantur" , "aestimare" , "aestimem" , "aestus" , "aetate" , "affectent" , "affectio" , "affectiones" , "affectionum" , "affectu" , "affectum" , "affectus" , "afficior" , "afficit" , "afuerit" , "agam" , "agantur" , "agatur" , "agebam" , "agenti" , "agerem" , "agit" , "agitaveram" , "agitis" , "agito" , "agnoscendo" , "agnoscere" , "agnoscerem" , "agnosceremus" , "agnoscerent" , "agnoscimus" , "agnosco" , "agnovi" , "ago" , "agro" , "ait" , "alas" , "album" , "alexandrino" , "alia" , "aliae" , "aliam" , "alias" , "alibi" , "alicui" , "alienam" , "alieni" , "alieno" , "alienorum" , "alii" , "aliis" , "alimenta" , "alimentorum" , "alio" , "alioquin" , "alios" , "aliqua" , "aliquam" , "aliquando" , "aliquantulum" , "aliquantum" , "aliquid" , "aliquo" , "aliquod" , "alis" , "aliter" , "aliterque" , "aliud" , "alium" , "alius" , "alta" , "alter" , "altera" , "alteram" , "alteri" , "alterum" , "altius" , "amamus" , "amandum" , "amant" , "amare" , "amaremus" , "amarent" , "amari" , "amaris" , "amaritudo" , "amarus" , "amasti" , "amat" , "amatoribus" , "amatur" , "amavi" , "ambiendum" , "ambitione" , "ambitiones" , "ambitum" , "ambulasti" , "ambulent" , "amem" , "amemur" , "amet" , "ametur" , "amicum" , "amisi" , "amissum" , "amittere" , "amo" , "amoenos" , "amor" , "amore" , "amorem" , "amplexibus" , "amplexum" , "amplior" , "amplitudines" , "amplius" , "amplum" , "an" , "anaximenes" , "angelos" , "angelum" , "angustus" , "anhelo" , "anima" , "animadvertendo" , "animadverterunt" , "animae" , "animales" , "animalia" , "animalibus" , "animam" , "animant" , "animarum" , "animas" , "animi" , "animo" , "animos" , "animum" , "animus" , "ante" , "antepono" , "antequam" , "antiqua" , "antiquis" , "antris" , "aperit" , "appareat" , "apparens" , "apparet" , "apparuit" , "appetam" , "appetitu" , "appetitum" , "approbare" , "approbat" , "approbavi" , "approbet" , "apud" , "aqua" , "aquae" , "aquilone" , "aranea" , "araneae" , "arbitratus" , "ardentius" , "ardes" , "arguitur" , "aromatum" , "arrogantis" , "artes" , "artibus" , "artificiosas" , "artificosa" , "ascendam" , "ascendant" , "ascendens" , "aspectui" , "aspernatione" , "aspero" , "asperum" , "assecutus" , "assequitur" , "assuescere" , "assuescunt" , "assumunt" , "assumuntur" , "assunt" , "at" , "athanasio" , "atque" , "attamen" , "attigerit" , "attigi" , "attingam" , "attingere" , "attingi" , "audeo" , "audi" , "audiam" , "audiant" , "audiar" , "audiat" , "audiebam" , "audierint" , "audieris" , "audierit" , "audierunt" , "audio" , "audire" , "audis" , "audit" , "audito" , "auditur" , "audiunt" , "audiuntur" , "audivi" , "audivimus" , "aufer" , "augebis" , "augendo" , "augeret" , "auget" , "aula" , "auram" , "auras" , "aurem" , "aures" , "auri" , "auribus" , "auris" , "aurium" , "aut" , "autem" , "avaritiam" , "avertat" , "avertit" , "avertitur" , "aves" , "avide" , "beares" , "beata" , "beatae" , "beatam" , "beati" , "beatitudinis" , "beatos" , "beatum" , "beatus" , "bellum" , "bene" , "benedicendo" , "benedicere" , "benedicis" , "benedicitur" , "bestiae" , "bibendi" , "bibendo" , "bibo" , "blanditur" , "bona" , "bonae" , "bonam" , "bone" , "boni" , "bonis" , "bono" , "bonorumque" , "bonos" , "bonum" , "cadavere" , "cadere" , "cadunt" , "caecis" , "caecitatem" , "caecus" , "caelestium" , "caeli" , "caelo" , "caelum" , "calamitas" , "calciamentis" , "calidum" , "calumnientur" , "campis" , "campos" , "candorem" , "canem" , "canenti" , "canitur" , "canora" , "canoris" , "cantandi" , "cantantem" , "cantantur" , "cantarentur" , "cantilenarum" , "canto" , "cantu" , "cantus" , "capacitas" , "caperetur" , "capiamur" , "capiar" , "capiendum" , "capio" , "capior" , "capit" , "capiuntur" , "captans" , "captus" , "caput" , "careamus" , "carent" , "carentes" , "careo" , "carere" , "caritas" , "caritatis" , "carne" , "carneis" , "carnem" , "carneo" , "carnes" , "carnis" , "caro" , "carthaginem" , "carthaginis" , "castam" , "caste" , "castissime" , "casto" , "castrorum" , "casu" , "catervas" , "catervatim" , "causa" , "caveam" , "cavens" , "cavernis" , "cavis" , "cedendo" , "cedentibus" , "cedunt" , "celeritate" , "cellis" , "cepit" , "cernimus" , "certa" , "certe" , "certissimum" , "certissimus" , "certo" , "certum" , "certus" , "cervicem" , "cessant" , "cessare" , "cessas" , "cessatione" , "cessavit" , "cetera" , "ceterarumque" , "ceteri" , "ceteris" , "ceterorum" , "ceteros" , "christus" , "cibo" , "cibum" , "cibus" , "cinerem" , "circo" , "circumquaque" , "circumstant" , "circumstrepant" , "cito" , "civium" , "clamasti" , "clamat" , "clamore" , "claudicans" , "clauditur" , "coapta" , "coegerit" , "coepisti" , "coepta" , "cogenda" , "cogens" , "cogeremur" , "cogit" , "cogitamus" , "cogitando" , "cogitare" , "cogitarem" , "cogitari" , "cogitatione" , "cogitationibus" , "cogitationis" , "cogitetur" , "cogito" , "cogitur" , "cognitionis" , "cognitor" , "cognituri" , "cognitus" , "cognoscam" , "cognoscendam" , "cognoscendi" , "cognoscendum" , "cognoscere" , "cognosceremus" , "cognoscet" , "cognovi" , "cognovit" , "cogo" , "cohibeamus" , "cohiberi" , "colligantur" , "colligenda" , "colligere" , "colligimur" , "colligimus" , "colligitur" , "colligo" , "coloratae" , "colores" , "colorum" , "colunt" , "comes" , "comitatum" , "comitatur" , "comitum" , "commemini" , "commemoro" , "commendantur" , "commendata" , "commendatum" , "commendavi" , "commendavit" , "commune" , "commutantur" , "compagem" , "comprehendet" , "conantes" , "conatur" , "conatus" , "conceptaculum" , "concessisti" , "concludamus" , "concordiam" , "concubitu" , "concupiscentia" , "concupiscentiae" , "concupiscentiam" , "concupiscentias" , "concupiscit" , "concurrunt" , "condit" , "conduntur" , "conectitur" , "conexos" , "confecta" , "conferamus" , "conferunt" , "confessa" , "confessio" , "confessione" , "confessiones" , "confessionum" , "confitear" , "confitente" , "confitentem" , "confiteor" , "confiteri" , "confitetur" , "conforta" , "confortasti" , "confortat" , "congesta" , "congoscam" , "congratulari" , "congruentem" , "coniugio" , "coniunctam" , "coniunctione" , "conmemoravi" , "conmendat" , "conmixta" , "conmoniti" , "conmunem" , "conor" , "conperero" , "conprehendant" , "conprehenditur" , "conpressisti" , "conscientia" , "conscientiae" , "conscius" , "conscribebat" , "consensio" , "consensionem" , "consentiat" , "consequentibus" , "consequentium" , "considerabo" , "considerationem" , "consideravi" , "considero" , "consilium" , "consolatione" , "consonant" , "consonarent" , "consortium" , "conspectu" , "conspectum" , "conspiciant" , "conspiciatur" , "conspirantes" , "constans" , "constrictione" , "consuetudine" , "consuetudinem" , "consuetudinis" , "consuetudo" , "consuevit" , "consulebam" , "consulens" , "consulentibus" , "consulerem" , "consulunt" , "consumma" , "contemnat" , "contemnenda" , "contemnere" , "contemnit" , "contemptibilibus" , "contemptu" , "contendunt" , "contenti" , "conterritus" , "contexo" , "contineam" , "continebat" , "continens" , "continentiam" , "continet" , "contra" , "contractando" , "contrahit" , "contraria" , "contrario" , "contrectatae" , "contrectavi" , "contremunt" , "contristamur" , "contristari" , "contristat" , "contristatur" , "contristentur" , "contristor" , "contumelia" , "convenientissima" , "convertit" , "convinci" , "copia" , "copiarum" , "copiosae" , "copiosum" , "cor" , "coram" , "corda" , "corde" , "cordi" , "cordibus" , "cordis" , "corones" , "corpora" , "corporales" , "corporalis" , "corporalium" , "corpore" , "corpori" , "corporis" , "corporum" , "corpulentum" , "corpus" , "corrigebat" , "corrigendam" , "corruptelarum" , "corruptible" , "corruptione" , "coruscasti" , "cotidiana" , "cotidianam" , "cotidianas" , "cotidianum" , "cotidie" , "crapula" , "creator" , "creatorem" , "creaturam" , "crebro" , "credendum" , "credentium" , "credidi" , "credimus" , "credit" , "credita" , "creditarum" , "credituri" , "credunt" , "crucis" , "cubile" , "cubilia" , "cui" , "cuius" , "cuiuscemodi" , "cuiuslibet" , "cuiusquam" , "cuiusque" , "cum" , "cuncta" , "cupiant" , "cupidatatium" , "cupiditas" , "cupiditate" , "cupiditatem" , "cupiditatis" , "cupientem" , "cupimus" , "cupio" , "cupiunt" , "cur" , "cura" , "curam" , "curare" , "curiosa" , "curiosarum" , "curiositas" , "curiositate" , "curiositatis" , "curiosum" , "curo" , "currentem" , "custodiant" , "custodis" , "da" , "dabis" , "damnante" , "damnetur" , "dare" , "dari" , "das" , "datur" , "david" , "daviticum" , "de" , "debeo" , "debet" , "debui" , "deceptum" , "decernam" , "decet" , "deciperentur" , "decus" , "dedisti" , "deerat" , "deerit" , "defectus" , "defenditur" , "defluximus" , "deformis" , "defrito" , "defuissent" , "dei" , "deinde" , "delectamur" , "delectarentur" , "delectari" , "delectat" , "delectati" , "delectatio" , "delectatione" , "delectationem" , "delectatur" , "delectatus" , "delector" , "delet" , "deliciae" , "deliciosas" , "delicta" , "dementia" , "demerguntur" , "demetimur" , "demonstrare" , "demonstrasti" , "demonstrata" , "demonstratus" , "denuo" , "deo" , "depereunt" , "deponamus" , "depromi" , "deputabimus" , "des" , "deserens" , "deseri" , "desiderans" , "desiderant" , "desideraris" , "desiderata" , "desideravit" , "desiderem" , "desideriis" , "desiderio" , "desiderium" , "desidero" , "desidiosum" , "desivero" , "desperare" , "desperarem" , "desperatione" , "despiciam" , "destruas" , "desuper" , "det" , "deterior" , "deteriore" , "detestetur" , "detestor" , "detruncata" , "deum" , "deus" , "deviare" , "dextera" , "dexteram" , "diabolus" , "dicam" , "dicant" , "dicat" , "dicatur" , "dicebam" , "dicens" , "dicentem" , "dicentia" , "dicentium" , "dicere" , "dicerem" , "diceremus" , "dicerentur" , "diceretur" , "dici" , "dicimur" , "dicimus" , "dicis" , "dicit" , "dicite" , "dico" , "dictis" , "dictum" , "dicturus" , "dicunt" , "dicuntur" , "didicerim" , "didici" , "didicisse" , "didicissem" , "die" , "diebus" , "diei" , "diem" , "differens" , "difficultates" , "difficultatis" , "difiniendo" , "digna" , "dignaris" , "dignationem" , "dignatus" , "digni" , "dignitatibus" , "dignitatis" , "diiudicas" , "diiudico" , "dilabuntur" , "dilexisti" , "diligentius" , "diligi" , "diligit" , "dimensionumque" , "dimitti" , "dinoscens" , "dinumerans" , "direxi" , "discendi" , "discere" , "discerem" , "discerent" , "discernebat" , "discernens" , "discernere" , "discernerem" , "discernitur" , "discerno" , "discrevisse" , "discurro" , "dispensator" , "dispersione" , "displiceant" , "displicens" , "displicent" , "displiceo" , "displicere" , "dispulerim" , "disputandi" , "disputando" , "disputante" , "disputantur" , "disputare" , "dissentire" , "disseritur" , "dissimile" , "dissimilia" , "distantia" , "distincte" , "distinguere" , "distorta" , "diu" , "diutius" , "divellit" , "diversa" , "diversisque" , "diversitate" , "diverso" , "divexas" , "dividendo" , "divino" , "divitiae" , "dixeris" , "dixerit" , "dixi" , "dixit" , "doce" , "docebat" , "docens" , "docentem" , "doces" , "doctrinae" , "doctrinis" , "docuisti" , "doleam" , "doleamus" , "doleat" , "dolendum" , "dolet" , "dolor" , "dolore" , "dolorem" , "dolores" , "domi" , "dominaris" , "domine" , "domino" , "dominos" , "dominum" , "dominus" , "dona" , "donasti" , "donec" , "donum" , "dormiat" , "dormienti" , "dormientis" , "dormies" , "dormitabis" , "drachmam" , "duabus" , "dubia" , "dubitant" , "dubitatione" , "ducere" , "dulce" , "dulcedine" , "dulcedinem" , "dulcedo" , "dulces" , "dulcidine" , "dulcis" , "dum" , "duobus" , "dura" , "durum" , "duxi" , "e" , "ea" , "eadem" , "eam" , "eant" , "earum" , "eas" , "ebrietas" , "ebrietate" , "ebriosos" , "ebriosus" , "ecce" , "ecclesia" , "ecclesiae" , "edacitas" , "edendi" , "edendo" , "edunt" , "efficeret" , "egenus" , "egerim" , "ego" , "ei" , "eis" , "eius" , "elapsum" , "elati" , "elian" , "eligam" , "eliqua" , "eloquentes" , "eloquentiam" , "eloquia" , "eloquio" , "eloquiorum" , "emendicata" , "en" , "enervandam" , "enim" , "enubiletur" , "enumerat" , "eo" , "eodem" , "eoque" , "eorum" , "eos" , "eosdem" , "episcopo" , "equus" , "eram" , "erant" , "eras" , "erat" , "ergo" , "ergone" , "erigo" , "eripe" , "eripietur" , "eris" , "erit" , "erogo" , "errans" , "erro" , "erubescam" , "eruens" , "eruerentur" , "eruuntur" , "es" , "esau" , "esca" , "escae" , "escam" , "escas" , "esse" , "essem" , "essent" , "esset" , "est" , "estis" , "esto" , "esurio" , "et" , "etiam" , "etiamne" , "etiamsi" , "etsi" , "euge" , "eum" , "eundem" , "eunt" , "evacuaret" , "evellas" , "evellere" , "evelles" , "eventa" , "evidentius" , "evigilantes" , "evigilet" , "ex" , "exarsi" , "exaudi" , "excellentiam" , "exciderat" , "exciderunt" , "excipiens" , "excitant" , "excitentur" , "exclamaverunt" , "excogitanda" , "excusatio" , "excusationis" , "exemplo" , "exhibentur" , "exhorreas" , "existimet" , "exitum" , "expavi" , "expedita" , "experiamur" , "experiendi" , "experientia" , "experientiam" , "experimentum" , "experimur" , "experta" , "expertarum" , "expertum" , "expertus" , "expetuntur" , "explorandi" , "explorant" , "exsecror" , "exserentes" , "exteriora" , "exterioris" , "exteriorum" , "exterius" , "exterminantes" , "extinguere" , "extingueris" , "extra" , "extraneus" , "extrinsecus" , "exultans" , "exultatione" , "fabricasti" , "fabricatae" , "fabricationibus" , "fabricavit" , "fabrorum" , "fac" , "facere" , "faciam" , "faciant" , "faciat" , "facie" , "faciebat" , "faciei" , "faciem" , "faciendo" , "faciens" , "faciente" , "facies" , "faciet" , "facile" , "faciliter" , "facio" , "facis" , "facit" , "faciunt" , "facta" , "facti" , "factis" , "factito" , "factos" , "factum" , "factumque" , "factus" , "facultas" , "fallacia" , "fallaciam" , "fallar" , "fallax" , "fallere" , "falli" , "fallit" , "fallitur" , "falsa" , "falsi" , "falsis" , "falsissime" , "falsitate" , "falsum" , "fama" , "fames" , "familiari" , "familiaritate" , "famulatum" , "fastu" , "fatemur" , "fateor" , "febris" , "fecisse" , "fecisti" , "fecit" , "ferre" , "fiant" , "fias" , "fiat" , "fide" , "fidei" , "fidelis" , "fidem" , "fiducia" , "fierem" , "fierent" , "fieret" , "fieri" , "figmentis" , "filiis" , "filio" , "filiorum" , "filios" , "filium" , "filum" , "fine" , "finis" , "firma" , "fit" , "fixit" , "flabiles" , "flagitabat" , "flagitantur" , "flammam" , "flatus" , "flenda" , "flendae" , "fleo" , "flete" , "fletur" , "fletus" , "flexu" , "florum" , "fluctuo" , "fluctus" , "flumina" , "fluminum" , "fluxum" , "foeda" , "foras" , "fores" , "foribus" , "foris" , "forma" , "formaeque" , "formas" , "formosa" , "fornax" , "forsitan" , "fortasse" , "fortassis" , "forte" , "fortitudinem" , "fortius" , "fragrasti" , "frangat" , "fraternae" , "fraternis" , "fraternus" , "fratres" , "fratribus" , "freni" , "frequentatur" , "frigidique" , "frigidumve" , "fructu" , "fructum" , "fructus" , "fudi" , "fueram" , "fueramus" , "fuerim" , "fuerimus" , "fueris" , "fuerit" , "fuero" , "fuerunt" , "fugam" , "fugasti" , "fugiamus" , "fui" , "fuimus" , "fuisse" , "fuit" , "fulgeat" , "fulget" , "fundamenta" , "fundum" , "furens" , "futurae" , "futuras" , "futuri" , "gaudeam" , "gaudeant" , "gaudeat" , "gaudebit" , "gaudens" , "gaudent" , "gaudentes" , "gaudeo" , "gaudere" , "gaudet" , "gaudii" , "gaudiis" , "gaudio" , "gaudium" , "gavisum" , "gemitu" , "gemitum" , "gemitus" , "genera" , "generalis" , "generatimque" , "genere" , "generibus" , "generis" , "genuit" , "genus" , "gerit" , "geritur" , "gero" , "gestat" , "gloria" , "gloriae" , "gloriatur" , "gradibus" , "graeca" , "graecae" , "graece" , "graeci" , "graecus" , "grandi" , "grandis" , "gratia" , "gratiae" , "gratiam" , "gratiarum" , "gratias" , "gratis" , "grave" , "graventur" , "gressum" , "grex" , "gusta" , "gustandi" , "gustando" , "gustatae" , "gustavi" , "gutture" , "gutturis" , "gyros" , "habeas" , "habeat" , "habeatur" , "habebunt" , "habemus" , "habendum" , "habens" , "habent" , "habere" , "haberent" , "haberet" , "habes" , "habet" , "habitaculum" , "habitare" , "habitaret" , "habitas" , "habites" , "habiti" , "habito" , "hac" , "hae" , "haec" , "haeream" , "haereo" , "haeret" , "hanc" , "has" , "haurimus" , "haustum" , "hebesco" , "heremo" , "hi" , "hic" , "hierusalem" , "hilarescit" , "hinc" , "his" , "hoc" , "homine" , "hominem" , "homines" , "homini" , "hominibus" , "hominis" , "hominum" , "homo" , "honestis" , "honoris" , "horrendum" , "horum" , "hos" , "huc" , "huic" , "huius" , "huiuscemodi" , "humana" , "humanae" , "humanus" , "humilem" , "humilibus" , "humilitatem" , "hymno" , "hymnum" , "hymnus" , "iaceat" , "iacitur" , "iacob" , "iactantia" , "iacto" , "iam" , "iamque" , "ianua" , "ianuas" , "ibi" , "id" , "idem" , "ideo" , "ideoque" , "idoneus" , "ieiuniis" , "iesus" , "igitur" , "ignorat" , "illa" , "illac" , "illae" , "illam" , "ille" , "illi" , "illic" , "illico" , "illinc" , "illis" , "illius" , "illo" , "illos" , "illuc" , "illud" , "illum" , "imaginatur" , "imagine" , "imaginem" , "imagines" , "imaginesque" , "imaginibus" , "imaginis" , "imaginum" , "imago" , "imitanti" , "immaniter" , "immensa" , "immo" , "immortalis" , "imnagines" , "imperas" , "imperasti" , "imperfecta" , "impium" , "imples" , "imposuit" , "impressum" , "imprimi" , "imprimitur" , "improbat" , "improbet" , "in" , "inaequaliter" , "inanescunt" , "incaute" , "incertum" , "incertus" , "incideram" , "inciderunt" , "incipio" , "inclinatione" , "incognitam" , "incolis" , "incommutabilis" , "incomprehensibilis" , "inconcussus" , "inconsummatus" , "incorruptione" , "incurrunt" , "indagabit" , "inde" , "indecens" , "indica" , "indicabo" , "indicat" , "indicatae" , "indicavi" , "indidem" , "indigentiae" , "indigentiam" , "indisposite" , "indueris" , "ineffabiles" , "inesse" , "inest" , "inexcusabiles" , "inexplicabilis" , "infelix" , "inferiora" , "inferiore" , "infinita" , "infinitum" , "infirma" , "infirmior" , "infirmitas" , "infirmitate" , "infirmitatem" , "infirmitati" , "infirmitatis" , "infirmos" , "infirmus" , "infligi" , "influxit" , "ingemescentem" , "ingentes" , "ingenti" , "ingentibus" , "ingerantur" , "ingesta" , "ingredior" , "ingressae" , "ingressus" , "inhaerere" , "inhaereri" , "inhaeseram" , "inhaesero" , "inhiant" , "inimicus" , "iniqua" , "iniquitate" , "iniquitatibus" , "iniquitatis" , "iniuste" , "inlaqueantur" , "inlecebra" , "inlecebras" , "inlecebris" , "inlecebrosa" , "inlexit" , "inludi" , "inluminatio" , "inlusio" , "inlusionibus" , "inlustratori" , "inmemor" , "inmensa" , "inmoderatius" , "inmortalem" , "inmortali" , "inmunditiam" , "innecto" , "innocentia" , "innotescunt" , "innumerabiles" , "innumerabilia" , "innumerabilibus" , "innumerabiliter" , "innumerabilium" , "inperfectum" , "inperitiam" , "inperturbata" , "inpiis" , "inpinguandum" , "inpiorum" , "inplicans" , "inplicaverant" , "inplicentur" , "inpressa" , "inpressas" , "inpressit" , "inprobari" , "inquit" , "inquiunt" , "inretractabilem" , "inruebam" , "inruentes" , "inruentibus" , "insania" , "insaniam" , "insidiarum" , "insidiatur" , "insidiis" , "insinuat" , "inspirationis" , "instat" , "instituta" , "instituti" , "integer" , "intellecta" , "intellectus" , "intellegentis" , "intellegimus" , "intellegitur" , "intellego" , "intellegunt" , "intellexisse" , "intendere" , "intendimus" , "intentio" , "intentioni" , "intentionis" , "intentum" , "intentus" , "inter" , "interdum" , "interest" , "interfui" , "interior" , "interiora" , "interiore" , "interioris" , "interius" , "interiusque" , "interpellante" , "interpellat" , "interponunt" , "interrogans" , "interrogantibus" , "interrogare" , "interrogarentur" , "interrogari" , "interrogatio" , "interrogavi" , "interrogem" , "interroges" , "interroget" , "interrogo" , "interrumpunt" , "interrumpuntur" , "interstitio" , "intervalla" , "intervallis" , "intime" , "intonas" , "intra" , "intrant" , "intraverint" , "intraverunt" , "intravi" , "intrinsecus" , "intromittis" , "intromittuntur" , "introrsus" , "intuerer" , "intuetur" , "intus" , "inusitatum" , "invectarum" , "inveni" , "inveniam" , "inveniebam" , "invenimus" , "invenio" , "invenirem" , "inveniremus" , "inveniret" , "invenisse" , "invenit" , "inventa" , "inventor" , "inventum" , "inventus" , "invidentes" , "invisibiles" , "invisibilia" , "invocari" , "invoco" , "iohannem" , "ioseph" , "ipsa" , "ipsae" , "ipsam" , "ipsaque" , "ipsarum" , "ipsas" , "ipse" , "ipsi" , "ipsis" , "ipsius" , "ipso" , "ipsos" , "ipsosque" , "ipsum" , "israel" , "issac" , "ista" , "istae" , "istam" , "istarum" , "istas" , "iste" , "isti" , "istis" , "isto" , "istorum" , "istuc" , "istum" , "ita" , "itaque" , "item" , "iterum" , "itidem" , "iube" , "iubens" , "iubentem" , "iubentis" , "iubes" , "iucundiora" , "iucunditas" , "iudex" , "iudicante" , "iudicanti" , "iudicantibus" , "iudicare" , "iudicet" , "iudicia" , "iugo" , "iumenti" , "iussisti" , "iustificas" , "iustificatorum" , "iustitiae" , "iustitiam" , "iustum" , "iustus" , "labamur" , "labor" , "laboribus" , "laboro" , "lacrimas" , "laetamur" , "laetandis" , "laetatum" , "laetatus" , "laetitia" , "laetitiae" , "laetitiam" , "laetus" , "laetusque" , "languidus" , "languor" , "languores" , "laniato" , "lapidem" , "lapsus" , "laqueis" , "laqueo" , "laqueus" , "lascivos" , "lassitudines" , "lata" , "lateant" , "lateat" , "latere" , "latet" , "latina" , "latinae" , "latine" , "latinique" , "latis" , "latissimos" , "latitabant" , "laudabunt" , "laudandum" , "laudantur" , "laudare" , "laudari" , "laudatio" , "laudatorem" , "laudatur" , "laudatus" , "laudavit" , "laude" , "laudem" , "laudes" , "laudibus" , "laudis" , "laudor" , "lectorem" , "lege" , "leges" , "leguntur" , "lene" , "lenia" , "lenticulae" , "leporem" , "leve" , "levia" , "libeat" , "libeatque" , "libenter" , "liber" , "liberalibus" , "liberamenta" , "liberasti" , "libet" , "libidine" , "libro" , "licet" , "liliorum" , "lineas" , "lingua" , "linguarum" , "liquida" , "liquide" , "litteras" , "litteratura" , "loca" , "loco" , "locorum" , "locum" , "locuntur" , "locus" , "locutum" , "locutus" , "longe" , "longius" , "longum" , "loquebar" , "loquendo" , "loquens" , "loqueremur" , "loqueretur" , "loquitur" , "loquor" , "lucem" , "lucente" , "lucentem" , "lucerna" , "lucet" , "lucis" , "lucustis" , "lugens" , "lumen" , "luminibus" , "luminoso" , "lunam" , "lustravi" , "lux" , "machinationibus" , "macula" , "maerere" , "maerore" , "maerores" , "maeroribus" , "maestitiae" , "magicas" , "magis" , "magisque" , "magistro" , "magna" , "magnam" , "magni" , "magnificet" , "magnifico" , "magnum" , "magnus" , "maior" , "mala" , "male" , "mali" , "malim" , "malint" , "malis" , "malitia" , "malle" , "mallem" , "malo" , "malorum" , "malum" , "malus" , "mandamus" , "manducandi" , "manducantem" , "manducare" , "manducat" , "manducaverimus" , "manduco" , "maneas" , "manes" , "manet" , "manifesta" , "manifestari" , "manifestet" , "manifestetur" , "manifestus" , "manna" , "mansuefecisti" , "manu" , "manum" , "manus" , "mare" , "maris" , "mavult" , "maxime" , "me" , "mea" , "meae" , "meam" , "mearum" , "meas" , "mecum" , "mediator" , "mediatorem" , "medicamenta" , "medice" , "medicina" , "medicus" , "meditatusque" , "meditor" , "medium" , "medius" , "mei" , "meis" , "mel" , "melior" , "meliore" , "meliores" , "melius" , "mella" , "melodias" , "melos" , "membra" , "memento" , "meminerim" , "meminerimus" , "meminerunt" , "memini" , "meminimus" , "meminisse" , "meminissem" , "meminissemus" , "meminit" , "memor" , "memores" , "memoria" , "memoriae" , "memoriam" , "memoriter" , "mendacio" , "mendacium" , "mentem" , "mentiatur" , "mentiri" , "mentitur" , "meo" , "meorum" , "meos" , "meque" , "meretur" , "meridies" , "meritatem" , "meritis" , "merito" , "meruit" , "metas" , "metuebam" , "metuimus" , "metum" , "metumve" , "meum" , "meus" , "mihi" , "miles" , "militare" , "minister" , "ministerium" , "minor" , "minora" , "minuendo" , "minuit" , "minus" , "minusve" , "minutissimis" , "mira" , "mirabili" , "mirabilia" , "mirabiliter" , "miracula" , "mirandum" , "mirantur" , "mirari" , "mirifica" , "mirificum" , "miris" , "mirum" , "miser" , "misera" , "miserabiliter" , "miseratione" , "misereberis" , "miserere" , "miseria" , "miseriae" , "misericordia" , "misericordiae" , "misericordiam" , "misericordias" , "misericorditer" , "misericors" , "miseros" , "misertus" , "misisti" , "mittere" , "moderationi" , "moderatum" , "modestis" , "modi" , "modico" , "modicum" , "modis" , "modo" , "modos" , "modulatione" , "modum" , "modus" , "mole" , "molem" , "moles" , "molesta" , "molestia" , "molestiam" , "molestias" , "molestum" , "molle" , "momentum" , "montes" , "montium" , "monuisti" , "morbo" , "mordeor" , "mors" , "mortales" , "mortalis" , "mortalitatis" , "mortaliter" , "mortem" , "mortilitate" , "mortui" , "mortuis" , "mortuus" , "motus" , "moveat" , "movent" , "moveor" , "moveri" , "mulier" , "multa" , "multi" , "multimoda" , "multimodo" , "multiplices" , "multiplicitas" , "multiplicius" , "multique" , "multis" , "multos" , "multum" , "mulus" , "munda" , "mundatior" , "mundi" , "mundis" , "mundum" , "munera" , "munere" , "munerum" , "murmuravit" , "muscas" , "muta" , "mutans" , "mutant" , "mutare" , "mutaveris" , "mystice" , "nam" , "nares" , "narium" , "narrantes" , "narro" , "nascendo" , "nati" , "natura" , "naturae" , "naturam" , "ne" , "nec" , "necant" , "necessaria" , "necessarium" , "necesse" , "necessitas" , "necessitatis" , "neglecta" , "negotium" , "neminem" , "nemo" , "nepotibus" , "nequaquam" , "neque" , "nequeunt" , "nesciam" , "nesciat" , "nesciebam" , "nescio" , "nescirem" , "nescit" , "nidosve" , "nigrum" , "nihil" , "nihilo" , "nihilque" , "nimia" , "nimii" , "nimirum" , "nimis" , "nisi" , "niteat" , "nitidos" , "nituntur" , "nobis" , "nocte" , "noe" , "nolentes" , "nolit" , "nolle" , "nollem" , "nollent" , "nolo" , "nolunt" , "nomen" , "nominamus" , "nominata" , "nominatur" , "nomine" , "nominis" , "nomino" , "nominum" , "non" , "nondum" , "nonne" , "nonnullius" , "nonnumquam" , "norunt" , "nos" , "noscendi" , "noscendique" , "noscendum" , "nosse" , "nossemus" , "nosti" , "nostra" , "nostrae" , "nostram" , "nostri" , "nostrique" , "nostros" , "nostrum" , "nota" , "notatum" , "notiones" , "notitia" , "notus" , "nova" , "noverit" , "noverunt" , "novi" , "novit" , "novum" , "nuda" , "nugatoriis" , "nulla" , "nullam" , "nullo" , "nullum" , "num" , "numeramus" , "numerans" , "numerorum" , "numeros" , "numquam" , "numquid" , "nunc" , "nuntiantibus" , "nuntiata" , "nuntiavimus" , "nuntiavit" , "nuntii" , "nuntios" , "nusquam" , "nutantibus" , "nutu" , "o" , "ob" , "oblectamenta" , "oblectandi" , "obliti" , "oblitos" , "oblitum" , "oblitumque" , "oblitus" , "oblivio" , "oblivionem" , "oblivionis" , "obliviscamur" , "obliviscar" , "oblivisceremur" , "obliviscimur" , "oboritur" , "obruitur" , "obsecro" , "obsonii" , "obtentu" , "obumbret" , "occideris" , "occulta" , "occulto" , "occultum" , "occupantur" , "occurrant" , "occurrat" , "occurrerit" , "occurrit" , "occurro" , "occursantur" , "oceani" , "oceanum" , "oculi" , "oculis" , "oculo" , "oculorum" , "oculos" , "oculum" , "oculus" , "oderunt" , "odium" , "odor" , "odoratus" , "odore" , "odorem" , "odores" , "odorum" , "offendamus" , "offensionem" , "offeratur" , "offeretur" , "officia" , "officiis" , "officium" , "oleat" , "olefac" , "olent" , "olet" , "oleum" , "olfaciens" , "olfactum" , "olorem" , "oluerunt" , "omne" , "omnem" , "omnes" , "omnesque" , "omni" , "omnia" , "omnibus" , "omnimodarum" , "omnino" , "omnipotens" , "omnipotenti" , "omnis" , "omnium" , "oneri" , "operata" , "operatores" , "opertis" , "operum" , "opibus" , "opificiis" , "oportebat" , "oportere" , "oportet" , "optare" , "optimus" , "opus" , "orantibus" , "orare" , "oraremus" , "orationes" , "oraturis" , "ordinatorem" , "ore" , "oris" , "os" , "ostentet" , "pacem" , "pacto" , "paene" , "palleant" , "palliata" , "palpa" , "pane" , "paratus" , "parit" , "pars" , "parte" , "partes" , "parum" , "parva" , "parvulus" , "parvus" , "passim" , "passionis" , "passionum" , "pater" , "pati" , "patienter" , "patitur" , "patriam" , "patrocinium" , "paucis" , "paulatim" , "pauper" , "paupertatem" , "pax" , "peccare" , "peccati" , "peccatis" , "peccato" , "peccator" , "peccatores" , "peccatoris" , "peccatorum" , "peccatum" , "peccavit" , "pecco" , "pecora" , "pectora" , "pede" , "pedes" , "pedisequa" , "pelluntur" , "pendenda" , "penetrale" , "penetralia" , "penetro" , "penitus" , "penuriam" , "pepercisti" , "per" , "peragravi" , "percepta" , "percipitur" , "percurro" , "percussisti" , "perdiderat" , "perdit" , "perdita" , "perdite" , "perditum" , "peregrinor" , "peregrinorum" , "perfecturum" , "perficiatur" , "perfundens" , "perfusus" , "pergo" , "periculis" , "periculo" , "periculorum" , "periculosa" , "periculosissimam" , "periculum" , "perierat" , "perit" , "peritia" , "permanens" , "permanentes" , "permissum" , "perpetret" , "perscrutanda" , "persentiscere" , "persequi" , "persuadeant" , "persuaserit" , "pertendam" , "pertinet" , "pertractans" , "perturbant" , "perturbatione" , "perturbationes" , "perturbor" , "pervenire" , "pervenit" , "perversa" , "perversae" , "peste" , "petam" , "petat" , "petimus" , "petitur" , "piae" , "piam" , "picturis" , "pietatis" , "pius" , "placeam" , "placeant" , "placent" , "placentes" , "placere" , "places" , "placet" , "placuit" , "plagas" , "plangendae" , "plena" , "plenariam" , "plenas" , "plenis" , "pleno" , "plenus" , "plerumque" , "pluris" , "plus" , "poenaliter" , "pollutum" , "ponamus" , "pondere" , "ponderibus" , "ponendi" , "ponere" , "populi" , "populus" , "porro" , "portat" , "porto" , "posco" , "poscuntur" , "posita" , "positus" , "posse" , "possem" , "possemus" , "possent" , "posside" , "possideas" , "possidere" , "possideri" , "possim" , "possimus" , "possint" , "possit" , "possum" , "possumus" , "possunt" , "post" , "postea" , "posterior" , "potens" , "potentias" , "poterimus" , "poterunt" , "potes" , "potest" , "potestatem" , "potestates" , "potius" , "potu" , "potuere" , "potuero" , "potui" , "potuimus" , "potuit" , "prae" , "praebens" , "praebeo" , "praecedentia" , "praecedentium" , "praecidere" , "praeciderim" , "praeciditur" , "praeciperet" , "praecurrere" , "praedicans" , "praeditum" , "praegravatis" , "praeibat" , "praeire" , "praeiret" , "praeparat" , "praeposita" , "praesentes" , "praesentia" , "praesentiam" , "praesentior" , "praesidens" , "praesidenti" , "praesides" , "praesignata" , "praestabis" , "praestat" , "praesto" , "praetende" , "praeter" , "praeterierit" , "praeterita" , "praeteritae" , "praeteritam" , "praeteritis" , "praeteritorum" , "praeteritum" , "praetoria" , "prece" , "pretium" , "primatum" , "primitus" , "primo" , "primordiis" , "primus" , "principes" , "pristinae" , "pristinum" , "prius" , "priusquam" , "privatam" , "privatio" , "pro" , "probet" , "procedens" , "proceditur" , "procedunt" , "processura" , "prodeat" , "prodest" , "prodeunt" , "prodigia" , "proferatur" , "proferens" , "profero" , "proferrem" , "proferuntur" , "profunda" , "prohibuisti" , "proiectus" , "promisisti" , "promissio" , "pronuntianti" , "propinquius" , "propitius" , "proponatur" , "propositi" , "propria" , "proprie" , "proprios" , "propter" , "propterea" , "prorsus" , "proruunt" , "prosiliunt" , "prospera" , "prosperis" , "prosperitatibus" , "prosperitatis" , "prout" , "provectu" , "proximi" , "proximum" , "psalmi" , "psalterium" , "pugno" , "pulchra" , "pulchras" , "pulchris" , "pulchritudine" , "pulchritudinis" , "pulchritudinum" , "pulchritudo" , "pulsant" , "pulsatori" , "pulvere" , "pulvis" , "purgarentur" , "pusilla" , "pusillus" , "putant" , "putare" , "putem" , "qua" , "quadam" , "quadrupedibus" , "quae" , "quaecumque" , "quaedam" , "quaeque" , "quaeram" , "quaeratur" , "quaere" , "quaerebam" , "quaerebant" , "quaerebatur" , "quaerens" , "quaerentes" , "quaerere" , "quaererem" , "quaerimus" , "quaeris" , "quaerit" , "quaeritur" , "quaero" , "quaerunt" , "quaesisse" , "quaesitionum" , "quaesiveram" , "quaesivit" , "quaeso" , "quaestio" , "quaestionum" , "quale" , "qualibus" , "qualis" , "qualiscumque" , "quam" , "quamdiu" , "quamquam" , "quamvis" , "quandam" , "quando" , "quandoquidem" , "quanta" , "quanti" , "quantis" , "quanto" , "quantulum" , "quantum" , "quare" , "quarum" , "quas" , "quasi" , "quattuor" , "quem" , "quemadmodum" , "quendam" , "qui" , "quia" , "quibus" , "quibusdam" , "quibusve" , "quicquam" , "quicumque" , "quid" , "quidam" , "quidem" , "quidquid" , "quiescente" , "quietem" , "quippe" , "quis" , "quisquam" , "quisque" , "quisquis" , "quo" , "quocirca" , "quocumque" , "quod" , "quodam" , "quomodo" , "quoniam" , "quoque" , "quoquo" , "quorum" , "quos" , "quot" , "quotiens" , "quousque" , "radiavit" , "radios" , "rapiatur" , "rapinam" , "rapit" , "rapiunt" , "raptae" , "ratio" , "rationes" , "rationi" , "re" , "rebellis" , "rebus" , "reccido" , "recedat" , "recedimus" , "receptaculis" , "recessus" , "recipit" , "recognoscimus" , "recognoscitur" , "recognovi" , "recolenda" , "recolere" , "recolerentur" , "recoleretur" , "recolo" , "reconcilearet" , "reconciliare" , "recondens" , "recondi" , "recondidi" , "reconditae" , "reconditum" , "recondo" , "recordabor" , "recordando" , "recordans" , "recordantes" , "recordarer" , "recordationem" , "recordationis" , "recordemur" , "recordentur" , "recorder" , "recordor" , "recti" , "recuperatae" , "redarguentem" , "reddatur" , "reddi" , "redditur" , "redducet" , "redeamus" , "redemit" , "redigens" , "redigimur" , "redimas" , "redire" , "refectum" , "refero" , "referrem" , "reficiatur" , "reficimus" , "refrenare" , "refugio" , "refulges" , "regem" , "regina" , "regio" , "rei" , "relaxari" , "relaxatione" , "religione" , "religiosius" , "relinquentes" , "relinquunt" , "reliquerim" , "rem" , "reminiscendo" , "reminiscente" , "reminiscenti" , "reminiscentis" , "reminiscerer" , "reminisci" , "reminiscimur" , "reminiscor" , "remisisti" , "remota" , "remotiora" , "remotum" , "removeri" , "renuntiabant" , "repente" , "repercussus" , "reperiamus" , "reperio" , "reperiret" , "reperta" , "repetamus" , "repeterent" , "repleo" , "reponens" , "reponuntur" , "repositi" , "repositum" , "reprehensum" , "reptilia" , "requiem" , "requies" , "requiramus" , "requiratur" , "requiro" , "requirunt" , "requiruntur" , "rerum" , "res" , "resistere" , "resistimus" , "resistis" , "resistit" , "resisto" , "resolvisti" , "resorbeor" , "respice" , "respiciens" , "respirent" , "respondeat" , "respondent" , "responderent" , "responderunt" , "respondes" , "respondi" , "respondit" , "responsa" , "responsio" , "responsionibus" , "respuimus" , "respuitur" , "respuo" , "restat" , "retarder" , "retenta" , "retibus" , "retinemus" , "retinetur" , "retinuit" , "retractanda" , "retractarem" , "retractarentur" , "retractatur" , "retranseo" , "retribuet" , "retrusa" , "rideat" , "ridentem" , "ridiculum" , "rogantem" , "rogeris" , "rogo" , "ruga" , "ruinas" , "ruminando" , "rupisti" , "rursus" , "rutilet" , "sacerdos" , "sacramenta" , "sacramenti" , "sacramentis" , "sacramento" , "sacrificatori" , "sacrificium" , "sacrifico" , "sacrilega" , "saeculi" , "saeculum" , "saepe" , "saepius" , "salubritatis" , "salus" , "salute" , "salutem" , "saluti" , "salutis" , "salvi" , "salvus" , "sana" , "sanabis" , "sanare" , "sanari" , "sanas" , "sanaturi" , "sanctae" , "sancte" , "sancti" , "sanctis" , "sanctuarium" , "sane" , "sanes" , "sanguine" , "sanum" , "sapere" , "sapiat" , "sapida" , "sapientiae" , "sapientiorem" , "sapit" , "sapor" , "sapores" , "sarcina" , "sat" , "satago" , "saties" , "satietas" , "satietate" , "satietatis" , "satis" , "saturantur" , "saturari" , "saucio" , "saucium" , "sciam" , "scientiae" , "scierim" , "scio" , "scire" , "scirem" , "scirent" , "sciret" , "sciri" , "scis" , "scit" , "sciunt" , "scribentur" , "scrutamur" , "se" , "secreta" , "secreti" , "secreto" , "sectantur" , "sectatores" , "sectatur" , "secum" , "secundum" , "secura" , "securior" , "securus" , "sed" , "sedem" , "sedentem" , "sedet" , "sedibus" , "seducam" , "seductionibus" , "semel" , "semper" , "sempiterna" , "senectute" , "sensarum" , "sensibus" , "sensifico" , "sensis" , "sensu" , "sensum" , "sensus" , "sensusque" , "sententia" , "sententiam" , "sententiis" , "sentiebat" , "sentiens" , "sentientem" , "sentio" , "sentire" , "sentitur" , "sentiunt" , "seorsum" , "separatum" , "separavit" , "sepelivit" , "sequatur" , "sequentes" , "sequi" , "sequitur" , "serie" , "sermo" , "sero" , "servata" , "servi" , "serviam" , "serviant" , "serviendo" , "servientes" , "servirent" , "servis" , "servitutem" , "serviunt" , "servo" , "sese" , "seu" , "severitate" , "si" , "sibi" , "sibimet" , "sic" , "sicubi" , "sicut" , "sicuti" , "sidera" , "siderum" , "signa" , "significantur" , "significaret" , "significat" , "significationem" , "significatur" , "signum" , "silente" , "silentio" , "silva" , "sim" , "simile" , "similes" , "similia" , "similis" , "similitudine" , "similitudinem" , "similitudines" , "simillimum" , "simplicem" , "simul" , "simulque" , "simus" , "sine" , "singillatim" , "singula" , "sinis" , "sint" , "sinu" , "sinus" , "sit" , "sitio" , "sitis" , "sive" , "sobrios" , "socialiter" , "socias" , "societatis" , "sociorum" , "sola" , "solae" , "solam" , "solebat" , "solem" , "solet" , "soli" , "solis" , "solitis" , "solitudinem" , "solo" , "solum" , "solus" , "somnis" , "somno" , "sonant" , "sonare" , "sonaret" , "sonat" , "sonet" , "soni" , "sonis" , "sono" , "sonorum" , "sonos" , "sonuerit" , "sonuerunt" , "sonum" , "sonus" , "sopitur" , "soporem" , "soporis" , "spargant" , "spargens" , "spargit" , "sparsa" , "sparsis" , "spatiatus" , "spatiis" , "spe" , "speciem" , "species" , "spectaculis" , "spectandum" , "specto" , "speculum" , "spem" , "sperans" , "spernat" , "spes" , "spiritum" , "spiritus" , "splendeat" , "splendorem" , "splenduisti" , "stat" , "statim" , "statuit" , "stelio" , "stellas" , "stet" , "stilo" , "stipendium" , "strepitu" , "stupor" , "sua" , "suae" , "suam" , "suarum" , "suaveolentiam" , "suavi" , "suavia" , "suavis" , "suavitas" , "suavitatem" , "suavium" , "sub" , "subdita" , "subditi" , "subditus" , "subduntur" , "subeundam" , "subinde" , "subintrat" , "subire" , "subiugaverant" , "sublevas" , "subrepsit" , "subsidium" , "subtrahatur" , "succurrat" , "sudoris" , "sufficiat" , "sufficiens" , "suffragatio" , "suffragia" , "suggeruntur" , "suggestionibus" , "suggestionum" , "sui" , "suis" , "sum" , "sumendi" , "sumpturus" , "sumus" , "sunt" , "suo" , "super" , "superbam" , "superbi" , "superbia" , "superbiae" , "superbiam" , "superbis" , "superindui" , "supervacuanea" , "suppetat" , "supplicii" , "supra" , "surdis" , "surditatem" , "surgam" , "surgere" , "suspensus" , "suspirat" , "suspirent" , "sustinere" , "tacet" , "tacite" , "tactus" , "tale" , "tali" , "talia" , "talibus" , "talium" , "tam" , "tamdiu" , "tamen" , "tamenetsi" , "tametsi" , "tamquam" , "tandem" , "tangendo" , "tangunt" , "tanta" , "tantarum" , "tanto" , "tantulum" , "tantum" , "te" , "tecum" , "tegitur" , "temperata" , "templi" , "tempore" , "temporis" , "temporum" , "temptamur" , "temptandi" , "temptari" , "temptat" , "temptatio" , "temptatione" , "temptationem" , "temptationes" , "temptationibus" , "temptationis" , "temptationum" , "temptatum" , "temptatur" , "temptaverunt" , "temptetur" , "tempus" , "tenacius" , "teneam" , "teneant" , "teneat" , "tenebant" , "tenebatur" , "tenebrae" , "tenebris" , "tenebrosi" , "tenendi" , "tenent" , "teneo" , "teneor" , "teneretur" , "teneri" , "tenet" , "tenetur" , "tenuissimas" , "tenuiter" , "teque" , "terra" , "terrae" , "terram" , "tertio" , "tertium" , "testibus" , "testis" , "tetigi" , "tetigisti" , "texisti" , "theatra" , "thesauri" , "thesauro" , "thesaurus" , "tibi" , "timeamur" , "timent" , "timeo" , "timere" , "timeri" , "timore" , "timuisse" , "tobis" , "toleramus" , "tolerantiam" , "tolerare" , "tolerari" , "tolerat" , "toleret" , "tot" , "tota" , "totiens" , "totis" , "totius" , "toto" , "totum" , "tradidisti" , "trahunt" , "traicit" , "traiecta" , "transactam" , "transcendi" , "transeam" , "transeatur" , "transeo" , "transfigurans" , "transgredientibus" , "transibo" , "transierunt" , "transire" , "transisse" , "transit" , "transitu" , "transitus" , "tremore" , "tremorem" , "tria" , "tribuere" , "tribuis" , "triplici" , "tristis" , "tristitia" , "tristitiam" , "trium" , "tu" , "tua" , "tuae" , "tuam" , "tuas" , "tuetur" , "tui" , "tuis" , "tum" , "tunc" , "tundentes" , "tuo" , "tuorum" , "tuos" , "turbantur" , "turibulis" , "turpibus" , "turpis" , "turpitudines" , "tutiusque" , "tutor" , "tutum" , "tuum" , "tuus" , "typho" , "ubi" , "ubique" , "ubiubi" , "ulla" , "ullis" , "ullo" , "ulterius" , "umbrarum" , "umquam" , "una" , "unde" , "undique" , "ungentorum" , "unico" , "unicus" , "universus" , "unum" , "unus" , "urunt" , "uspiam" , "usque" , "usui" , "usum" , "usurpant" , "ut" , "utcumque" , "utendi" , "uterque" , "utilitate" , "utilitatem" , "utimur" , "utinam" , "utique" , "utrique" , "utriusque" , "utroque" , "utrubique" , "utrum" , "utrumque" , "vae" , "valde" , "valeam" , "valeant" , "valent" , "valentes" , "valeo" , "valerem" , "valerent" , "valeret" , "vales" , "valet" , "valetudinis" , "valida" , "vana" , "vanae" , "vanescit" , "vanias" , "vanitatem" , "vanitatis" , "vanus" , "varia" , "variando" , "varias" , "variis" , "vasis" , "vegetas" , "vehementer" , "vel" , "velim" , "velint" , "velit" , "velle" , "vellem" , "vellemus" , "vellent" , "velut" , "veluti" , "venatio" , "veni" , "venio" , "venit" , "veniunt" , "venter" , "ventos" , "ventre" , "ventrem" , "ventris" , "vera" , "verae" , "verax" , "verba" , "verbis" , "verbo" , "verborum" , "verbum" , "vere" , "veris" , "veritas" , "veritate" , "veritatem" , "vero" , "verum" , "verus" , "vestibus" , "vestigio" , "vestra" , "vetare" , "vi" , "via" , "viae" , "viam" , "vicinior" , "vicit" , "victima" , "victor" , "victoria" , "victoriam" , "vide" , "videam" , "videant" , "videat" , "videbam" , "videbat" , "videmus" , "videndi" , "videndo" , "videns" , "vident" , "video" , "videor" , "videre" , "viderem" , "videri" , "viderunt" , "vides" , "videt" , "videtur" , "vidi" , "vigilans" , "vigilantem" , "vigilantes" , "vigilanti" , "vim" , "vindicandi" , "vindicavit" , "violari" , "violis" , "viribus" , "virtus" , "vis" , "visa" , "visco" , "visione" , "visionum" , "vita" , "vitae" , "vitaliter" , "vitam" , "vituperante" , "vituperare" , "vituperari" , "vituperatio" , "vituperetur" , "viva" , "vivam" , "vivant" , "vivarum" , "vivat" , "vivendum" , "vivente" , "viventis" , "vivere" , "vivifico" , "vivit" , "vivunt" , "vix" , "vobiscum" , "vocant" , "vocantes" , "vocantur" , "vocasti" , "vocatur" , "voce" , "vocem" , "vocibus" , "vocis" , "volatibus" , "volebant" , "volens" , "volito" , "volo" , "voluerit" , "voluero" , "volui" , "voluisti" , "voluit" , "volumus" , "volunt" , "voluntas" , "voluntate" , "voluptaria" , "voluptas" , "voluptate" , "voluptatem" , "voluptates" , "voluptatibus" , "voluptatis" , "voluptatum" , "volvere" , "vos" , "vox" , "vulnera" , "vult" , "vultu" ]
drhodes/hs-lorem
src/Text/Lorem/Words.hs
bsd-3-clause
72,889
0
6
35,459
10,664
7,110
3,554
3,546
1
{-# LANGUAGE TemplateHaskell #-} module Game.PushedT where import Control.Lens (makeLenses) import Linear (V3(..)) import Types makeLenses ''PushedT newPushedT :: PushedT newPushedT = PushedT { _pEnt = Nothing , _pOrigin = V3 0 0 0 , _pAngles = V3 0 0 0 , _pDeltaYaw = 0 }
ksaveljev/hake-2
src/Game/PushedT.hs
bsd-3-clause
341
0
7
114
90
53
37
12
1
{-# LANGUAGE OverloadedStrings #-} import Network.Wai import Network.HTTP.Types import Network.Wai.Handler.Hope as Hope (run) import Network.Wai.Handler.Warp as Warp (run) import qualified Data.ByteString.Char8 as C8 import qualified Data.ByteString as B import Control.Monad.IO.Class (liftIO) import Network.Wai.Application.Static import System.Environment import Control.Concurrent ( forkIO ) import Data.CaseInsensitive ( mk ) import Data.Monoid import Web.Scotty app :: Application app _ = do liftIO $ putStrLn "I've done some IO here" return $ responseLBS status200 [("Content-Type", "text/plain")] "Hello, Web!" form :: IO Application form = scottyApp $ do get "/:word" $ do beam <- param "word" html $ mconcat ["<h1>Scotty, ", beam, " me up!</h1>"] html $ mconcat ["<form name=\"input\" action=\"form\" method=\"post\"> First name: <input type=\"text\" name=\"firstname\" /><br /> Last name: <input type=\"text\" name=\"lastname\" /> <input type=\"submit\" value=\"Submit\" /></form>"] post "/form" $ do fname <- param "firstname" lname <- param "lastname" html $ mconcat ["Hello ", fname, " ", lname] main :: IO () main = do args <- getArgs port <- case args of [portS] -> return portS [] -> return "2000" putStrLn $ "http://localhost:" ++ port app <- form mergedRun port app mergedRun port app = do let spdyPort = show (read port + 1) forkIO $ Hope.run spdyPort app Warp.run (read port) (advertiseSPDY spdyPort app) return () advertiseSPDY :: String -> Application -> Application advertiseSPDY spdyPort app request = do resp <- app request return $ case resp of ResponseFile s h fpath fpart -> ResponseFile s (alternateProtocol:h) fpath fpart ResponseBuilder s h builder -> ResponseBuilder s (alternateProtocol:h) builder ResponseSource s h source -> ResponseSource s (alternateProtocol:h) source where alternateProtocol = (mk "Alternate-Protocol", B.concat [C8.pack spdyPort, ":npn-spdy/2"])
kolmodin/spdy
example/app.hs
bsd-3-clause
2,018
0
13
379
602
308
294
53
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE RebindableSyntax #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE NoMonomorphismRestriction #-} module Language.Haskell.Rebind.Do where import qualified Control.Monad.Indexed as P import Prelude hiding ((>>), (>>=), return, Monad) import qualified Prelude as P import Data.Default data Monad = Monad { return :: forall a m. (P.Monad m) => a -> m a , (>>=) :: forall a b m. (P.Monad m) => m a -> (a -> m b) -> m b , (>>) :: forall a b m. (P.Monad m) => m a -> m b -> m b } data IxMonad = IxMonad { return :: forall a i m. (P.IxMonad m) => a -> m i i a , (>>=) :: forall a b i j k m. (P.IxMonad m) => m i j a -> (a -> m j k b) -> m i k b , (>>) :: forall a b i j k m. (P.IxMonad m) => m i j a -> m j k b -> m i k b } instance Default Monad where def = Monad { return = P.return , (>>=) = (P.>>=) , (>>) = (P.>>) } instance Default IxMonad where def = IxMonad { return = P.ireturn , (>>=) = (P.>>>=) , (>>) = \a b -> a P.>>>= (\_ -> b) }
sleexyz/haskell-fun
Language/Haskell/Rebind/Do.hs
bsd-3-clause
1,121
12
20
291
475
284
191
30
0
{-# LANGUAGE FlexibleInstances, GADTs, TemplateHaskell, TypeFamilies, NoImplicitPrelude #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module DataFamilies.Instances where import BasePrelude hiding (Product) import Json import DataFamilies.Types import Test.QuickCheck (Arbitrary(..), elements, oneof) instance (Arbitrary a) => Arbitrary (Approx a) where arbitrary = Approx <$> arbitrary instance Arbitrary (Nullary Int) where arbitrary = elements [C1, C2, C3] instance Arbitrary a => Arbitrary (SomeType c () a) where arbitrary = oneof [ pure Nullary , Unary <$> arbitrary , Product <$> arbitrary <*> arbitrary <*> arbitrary , Record <$> arbitrary <*> arbitrary <*> arbitrary ] instance Arbitrary (GADT String) where arbitrary = GADT <$> arbitrary deriveJson defaultOptions 'C1 deriveJson defaultOptions 'Nullary deriveJson defaultOptions 'Approx deriveToJson defaultOptions 'GADT -- We must write the FromJson instance head ourselves -- due to the refined GADT return type instance FromJson (GADT String) where parseJson = $(mkParseJson defaultOptions 'GADT)
aelve/json-x
tests/DataFamilies/Instances.hs
bsd-3-clause
1,178
0
10
261
276
149
127
-1
-1
-- | -- Module : $Header$ -- Copyright : (c) 2013-2014 Galois, Inc. -- License : BSD3 -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- This module implements a transformation, which tries to avoid exponential -- slow down in some cases. What's the problem? Consider the following (common) -- patterns: -- -- fibs = [0,1] # [ x + y | x <- fibs, y <- drop`{1} fibs ] -- -- The type of `fibs` is: -- -- {a} (a >= 1, fin a) => [inf][a] -- -- Here `a` is the number of bits to be used in the values computed by `fibs`. -- When we evaluate `fibs`, `a` becomes a parameter to `fibs`, which works -- except that now `fibs` is a function, and we don't get any of the memoization -- we might expect! What looked like an efficient implementation has all -- of a sudden become exponential! -- -- Note that this is only a problem for polymorphic values: if `fibs` was -- already a function, it would not be that surprising that it does not -- get cached. -- -- So, to avoid this, we try to spot recursive polymorphic values, -- where the recursive occurrences have the exact same type parameters -- as the definition. For example, this is the case in `fibs`: each -- recursive call to `fibs` is instantiated with exactly the same -- type parameter (i.e., `a`). The rewrite we do is as follows: -- -- fibs : {a} (a >= 1, fin a) => [inf][a] -- fibs = \{a} (a >= 1, fin a) -> fibs' -- where fibs' : [inf][a] -- fibs' = [0,1] # [ x + y | x <- fibs', y <- drop`{1} fibs' ] -- -- After the rewrite, the recursion is monomorphic (i.e., we are always using -- the same type). As a result, `fibs'` is an ordinary recursive value, -- where we get the benefit of caching. -- -- The rewrite is a bit more complex, when there are multiple mutually -- recursive functions. Here is an example: -- -- zig : {a} (a >= 2, fin a) => [inf][a] -- zig = [1] # zag -- -- zag : {a} (a >= 2, fin a) => [inf][a] -- zag = [2] # zig -- -- This gets rewritten to: -- -- newName : {a} (a >= 2, fin a) => ([inf][a], [inf][a]) -- newName = \{a} (a >= 2, fin a) -> (zig', zag') -- where -- zig' : [inf][a] -- zig' = [1] # zag' -- -- zag' : [inf][a] -- zag' = [2] # zig' -- -- zig : {a} (a >= 2, fin a) => [inf][a] -- zig = \{a} (a >= 2, fin a) -> (newName a <> <> ).1 -- -- zag : {a} (a >= 2, fin a) => [inf][a] -- zag = \{a} (a >= 2, fin a) -> (newName a <> <> ).2 -- -- NOTE: We are assuming that no capture would occur with binders. -- For values, this is because we replaces things with freshly chosen variables. -- For types, this should be because there should be no shadowing in the types. -- XXX: Make sure that this really is the case for types!! {-# LANGUAGE PatternGuards, FlexibleInstances, MultiParamTypeClasses #-} module Cryptol.Transform.MonoValues (rewModule) where import Cryptol.Parser.AST (Pass(MonoValues)) import Cryptol.TypeCheck.AST import Cryptol.TypeCheck.TypeMap import Control.Applicative import Data.List(sortBy,groupBy) import Data.Either(partitionEithers) import Data.Map (Map) import MonadLib {- (f,t,n) |--> x means that when we spot instantiations of `f` with `ts` and `n` proof argument, we should replace them with `Var x` -} newtype RewMap' a = RM (Map QName (TypesMap (Map Int a))) type RewMap = RewMap' QName instance TrieMap RewMap' (QName,[Type],Int) where emptyTM = RM emptyTM lookupTM (x,ts,n) (RM m) = do tM <- lookupTM x m tP <- lookupTM ts tM lookupTM n tP alterTM (x,ts,n) f (RM m) = RM (alterTM x f1 m) where f1 Nothing = do a <- f Nothing return (insertTM ts (insertTM n a emptyTM) emptyTM) f1 (Just tM) = Just (alterTM ts f2 tM) f2 Nothing = do a <- f Nothing return (insertTM n a emptyTM) f2 (Just pM) = Just (alterTM n f pM) toListTM (RM m) = [ ((x,ts,n),y) | (x,tM) <- toListTM m , (ts,pM) <- toListTM tM , (n,y) <- toListTM pM ] -- | Note that this assumes that this pass will be run only once for each -- module, otherwise we will get name collisions. rewModule :: Module -> Module rewModule m = fst $ runId $ runStateT 0 $ runReaderT (Just (mName m)) $ do ds <- mapM (rewDeclGroup emptyTM) (mDecls m) return m { mDecls = ds } -------------------------------------------------------------------------------- type M = ReaderT RO (StateT RW Id) type RO = Maybe ModName -- are we at the top level? type RW = Int -- to generate names newName :: M QName newName = do n <- sets $ \s -> (s, s + 1) seq n $ return (QName Nothing (NewName MonoValues n)) newTopOrLocalName :: M QName newTopOrLocalName = do mb <- ask n <- sets $ \s -> (s, s + 1) seq n $ return (QName mb (NewName MonoValues n)) inLocal :: M a -> M a inLocal = local Nothing -------------------------------------------------------------------------------- rewE :: RewMap -> Expr -> M Expr -- XXX: not IO rewE rews = go where tryRewrite (EVar x,tps,n) = do y <- lookupTM (x,tps,n) rews return (EVar y) tryRewrite _ = Nothing go expr = case expr of -- Interesting cases ETApp e t -> case tryRewrite (splitTApp expr 0) of Nothing -> ETApp <$> go e <*> return t Just yes -> return yes EProofApp e -> case tryRewrite (splitTApp e 1) of Nothing -> EProofApp <$> go e Just yes -> return yes ECon {} -> return expr EList es t -> EList <$> mapM go es <*> return t ETuple es -> ETuple <$> mapM go es ERec fs -> ERec <$> (forM fs $ \(f,e) -> do e1 <- go e return (f,e1)) ESel e s -> ESel <$> go e <*> return s EIf e1 e2 e3 -> EIf <$> go e1 <*> go e2 <*> go e3 EComp t e mss -> EComp t <$> go e <*> mapM (mapM (rewM rews)) mss EVar _ -> return expr ETAbs x e -> ETAbs x <$> go e EApp e1 e2 -> EApp <$> go e1 <*> go e2 EAbs x t e -> EAbs x t <$> go e EProofAbs x e -> EProofAbs x <$> go e ECast e t -> ECast <$> go e <*> return t EWhere e dgs -> EWhere <$> go e <*> inLocal (mapM (rewDeclGroup rews) dgs) rewM :: RewMap -> Match -> M Match rewM rews ma = case ma of From x t e -> From x t <$> rewE rews e -- These are not recursive. Let d -> Let <$> rewD rews d rewD :: RewMap -> Decl -> M Decl rewD rews d = do e <- rewE rews (dDefinition d) return d { dDefinition = e } rewDeclGroup :: RewMap -> DeclGroup -> M DeclGroup rewDeclGroup rews dg = case dg of NonRecursive d -> NonRecursive <$> rewD rews d Recursive ds -> do let (leave,rew) = partitionEithers (map consider ds) rewGroups = groupBy sameTParams $ sortBy compareTParams rew ds1 <- mapM (rewD rews) leave ds2 <- mapM rewSame rewGroups return $ Recursive (ds1 ++ concat ds2) where sameTParams (_,tps1,x,_) (_,tps2,y,_) = tps1 == tps2 && x == y compareTParams (_,tps1,x,_) (_,tps2,y,_) = compare (x,tps1) (y,tps2) consider d = let (tps,props,e) = splitTParams (dDefinition d) in if not (null tps) && notFun e then Right (d, tps, props, e) else Left d rewSame ds = do new <- forM ds $ \(d,_,_,e) -> do x <- newName return (d, x, e) let (_,tps,props,_) : _ = ds tys = map (TVar . tpVar) tps proofNum = length props addRew (d,x,_) = insertTM (dName d,tys,proofNum) x newRews = foldr addRew rews new newDs <- forM new $ \(d,newN,e) -> do e1 <- rewE newRews e return ( d , d { dName = newN , dSignature = (dSignature d) { sVars = [], sProps = [] } , dDefinition = e1 } ) case newDs of [(f,f')] -> return [ f { dDefinition = let newBody = EVar (dName f') newE = EWhere newBody [ Recursive [f'] ] in foldr ETAbs (foldr EProofAbs newE props) tps } ] _ -> do tupName <- newTopOrLocalName let (polyDs,monoDs) = unzip newDs tupAr = length monoDs addTPs = flip (foldr ETAbs) tps . flip (foldr EProofAbs) props -- tuple = \{a} p -> (f',g') -- where f' = ... -- g' = ... tupD = Decl { dName = tupName , dSignature = Forall tps props $ TCon (TC (TCTuple tupAr)) (map (sType . dSignature) monoDs) , dDefinition = addTPs $ EWhere (ETuple [ EVar (dName d) | d <- monoDs ]) [ Recursive monoDs ] , dPragmas = [] -- ? } mkProof e _ = EProofApp e -- f = \{a} (p) -> (tuple @a p). n mkFunDef n f = f { dDefinition = addTPs $ ESel ( flip (foldl mkProof) props $ flip (foldl ETApp) tys $ EVar tupName ) (TupleSel n (Just tupAr)) } return (tupD : zipWith mkFunDef [ 0 .. ] polyDs) -------------------------------------------------------------------------------- splitTParams :: Expr -> ([TParam], [Prop], Expr) splitTParams e = let (tps, e1) = splitWhile splitTAbs e (props, e2) = splitWhile splitProofAbs e1 in (tps,props,e2) -- returns type instantitaion and how many "proofs" were there splitTApp :: Expr -> Int -> (Expr, [Type], Int) splitTApp (EProofApp e) n = splitTApp e $! (n + 1) splitTApp e0 n = let (e1,ts) = splitTy e0 [] in (e1, ts, n) where splitTy (ETApp e t) ts = splitTy e (t:ts) splitTy e ts = (e,ts) notFun :: Expr -> Bool notFun (EAbs {}) = False notFun (EProofAbs _ e) = notFun e notFun _ = True
TomMD/cryptol
src/Cryptol/Transform/MonoValues.hs
bsd-3-clause
11,305
0
26
4,431
2,823
1,470
1,353
165
19
{-# LANGUAGE RecordWildCards , OverloadedStrings #-} module Vaultaire.Collectors.Twitter.Process where import Control.Applicative import Control.Monad.Logger import Control.Monad.State import Data.Aeson import Data.Attoparsec.Text import qualified Data.HashMap.Strict as HashMap(fromList) import Data.Monoid import Data.Text(Text) import Data.Text.Encoding import Data.Time.Format import Network.HTTP.Client import Network.HTTP.Client.TLS import System.Locale import Web.Authenticate.OAuth import Marquise.Client import Vaultaire.Types import Vaultaire.Collectors.Twitter.Types getSourceDict :: [(Text, Text)] -> Either String SourceDict getSourceDict = makeSourceDict . HashMap.fromList processPepito :: CollectorMonad () processPepito = do CollectorState{..} <- get req <- parseUrl "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=PepitoTheCat&count=50" signedReq <- signOAuth collectorAuth collectorCred req res <- liftIO $ withManager tlsManagerSettings $ \m -> httpLbs signedReq m let tweets = decode $ responseBody res case tweets of Nothing -> return () Just ts -> forM_ ts $ \Tweet{..} -> do logInfoStr $ "id = " ++ show tweet_id let pepitoStatus = case maybeResult $ parse pepitoParser text of Nothing -> Nothing Just "back home" -> Just PepitoIsBack Just "out" -> Just PepitoIsOut Just _ -> Nothing let time = parseTime defaultTimeLocale "%a %b %d %X %z %Y" created_at case (pepitoStatus, time) of (Just status, Just t) -> do payload <- case status of PepitoIsBack -> return 1 PepitoIsOut -> return 0 let ts = convertToTimeStamp t let tagList = [("source", "twitter"), ("twitter_account", "PepitoTheCat"), ("_event", "1")] let addressString = mconcat $ map (\(a, b) -> encodeUtf8 (mconcat [a, ": ", b, ", "])) tagList let addr = hashIdentifier addressString case getSourceDict tagList of Left _ -> return () Right sd -> do logInfoStr $ "Queuing simple point with payload " ++ show payload liftIO $ queueSimple collectorSpoolFiles addr ts payload logInfoStr $ "Queuing sd: " ++ show sd liftIO $ queueSourceDictUpdate collectorSpoolFiles addr sd logInfoStr $ "Timestamp: " ++ show ts _ -> return () pepitoParser :: Parser Text pepitoParser = string "Pépito is " *> (string "back home" <|> string "out")
anchor/vaultaire-collector-twitter
lib/Vaultaire/Collectors/Twitter/Process.hs
bsd-3-clause
3,068
20
30
1,131
689
359
330
62
8
{-# LANGUAGE OverloadedStrings #-} module Text.KarverSpec (spec) where import Text.Karver import Prelude hiding (unlines, concat) import Data.Text (Text, append, concat, empty, unlines) import qualified Data.Text.IO as TI import System.IO.Unsafe (unsafePerformIO) import Test.Hspec renderer :: Text -> Text renderer t = let json = unsafePerformIO $ TI.readFile "test/json/test-data.json" in renderTemplate' json t spec :: Spec spec = do describe "renderTemplate" $ do it "should render template with identity at the end" $ do let endText = "Template engine named {{ project }}" value = renderer endText expected = "Template engine named karver" value `shouldBe` expected it "should render template with identity at the beginning" $ do let beginText = "{{ language }} is what we are written in." value = renderer beginText expected = "haskell is what we are written in." value `shouldBe` expected it "should render template with identity in the middle" $ do let middleText = "All kept in a {{ ver-control }} repo, on Github." value = renderer middleText expected = "All kept in a git repo, on Github." value `shouldBe` expected it "should render template with multiple identities" $ do let multiText = append "{{ project }} is written in {{ language }}" ", held in {{ ver-control }}." value = renderer multiText expected = "karver is written in haskell, held in git." value `shouldBe` expected it "should render template with multiple lines of identities" $ do let multiText = unlines [ "{{ project }} is the name" , "making template is my game" , "if need something done faster" , "you need something written in {{ language }}" ] value = renderer multiText expected = unlines [ "karver is the name" , "making template is my game" , "if need something done faster" , "you need something written in haskell" ] value `shouldBe` expected it "should render template with object identity" $ do let objText = "Templating with {{ template.name }} is easy." value = renderer objText expected = "Templating with karver is easy." value `shouldBe` expected it "should render template with a mix of object and identity #1" $ do let mixText = "My {{ project }} is your {{ template.name }}." value = renderer mixText expected = "My karver is your karver." value `shouldBe` expected it "should render template with a mix of object and identity #2" $ do let mixText = "My {{ template.name }} is your {{ project }}." value = renderer mixText expected = "My karver is your karver." value `shouldBe` expected it "should render template with a list identity" $ do let arrText = "karver uses {{ libraries[0] }} for parsing." value = renderer arrText expected = "karver uses attoparsec for parsing." value `shouldBe` expected it "should render template with a mix of list and identity" $ do let arrText = "{{ project }} uses {{ libraries[1] }} for testing." value = renderer arrText expected = "karver uses hspec for testing." value `shouldBe` expected it "should render template with a mix of list and object" $ do let arrText = append "{{ template.name }} uses" " {{ libraries[1] }} for testing." value = renderer arrText expected = "karver uses hspec for testing." value `shouldBe` expected it "should render template with true evaluated if" $ do let trueText = "{% if project %}{{ project }}{% endif %} is true" value = renderer trueText expected = "karver is true" value `shouldBe` expected it "should not render template with false evaluated if" $ do let falseText = concat [ "{% if closed %}" , " karver is closed source" , "{% endif %}" ] value = renderer falseText expected = empty value `shouldBe` expected it "should check if object element exists" $ do let elemText = concat [ "{% if template.name %}" , " {{ template.name }} is the template." , "{% endif %}" ] value = renderer elemText expected = " karver is the template." value `shouldBe` expected it "should check if list element exists" $ do let elemText = concat [ "{% if libraries[1] %}" , concat [ " {{ libraries[1] }} makes" , " testing enjoyable!" ] , "{% endif %}" ] value = renderer elemText expected = " hspec makes testing enjoyable!" value `shouldBe` expected it "should render template of false evaluated if else" $ do let falseText = concat [ "{% if closed %}" , " karver is closed source" , "{% else %}" , " karver is open source" , "{% endif %}" ] value = renderer falseText expected = " karver is open source" value `shouldBe` expected it "should render template of false evaluated if else, for objects" $ do let elemText = concat [ "{% if template.license %}" , " {{ template.license }} is the license." , "{% else %}" , " BSD3 is the license." , "{% endif %}" ] value = renderer elemText expected = " BSD3 is the license." value `shouldBe` expected it "should render template looping over an array #1" $ do let loopText = concat [ "Some libraries used: " , "{% for library in libraries %}" , "{{ library }} " , "{% endfor %}." ] value = renderer loopText expected = "Some libraries used: attoparsec hspec ." value `shouldBe` expected it "should render template looping over an array #2" $ do let loopText = unlines [ "Some libraries used:" , "{% for library in libraries %}" , " * {{ library }}" , "{% endfor %}" ] value = renderer loopText expected = unlines [ "Some libraries used:" , " * attoparsec" , " * hspec" ] value `shouldBe` expected it "should render template looping over an array with objects #1" $ do let withObj = concat [ "{% for title in titles %}" , "<a id=\"{{ title.id }}\">" , "{{ title.name }}</a>" , "{% endfor %}" ] value = renderer withObj expected = concat [ "<a id=\"karver_the_template\">" , "Karver the Template</a>" , "<a id=\"bdd_with_hspec\">BDD with Hspec</a>" , "<a id=\"attoparsec_the_parser\">" , "Attoparsec the Parser</a>" ] value `shouldBe` expected it "should render template looping over an array with objects #2" $ do let withObj = unlines [ "{% for title in titles %}" , concat [ "<a id=\"{{ title.id }}\">" , "{{ title.name }}</a>" ] , "{% endfor %}" ] value = renderer withObj expected = unlines [ concat [ "<a id=\"karver_the_template\">" , "Karver the Template</a>" ] , "<a id=\"bdd_with_hspec\">BDD with Hspec</a>" , concat [ "<a id=\"attoparsec_the_parser\">" , "Attoparsec the Parser</a>" ] ] value `shouldBe` expected it "should include a template alone" $ do let includeText = "{% include 'test/template/text.html' %}" value = renderer includeText expected = "Content in the file." value `shouldBe` expected it "should include a template surrounded by markup #1" $ do let includeText = concat [ "<footer>" , "{% include 'test/template/text.html' %}" , "</footer>" ] value = renderer includeText expected = "<footer>Content in the file.</footer>" value `shouldBe` expected it "should include a template surrounded by markup #2" $ do let includeText = unlines [ "<ul>" , concat [ "{% include " , "'test/template/template.html" , "' %}</ul>" ] ] value = renderer includeText expected = unlines [ "<ul>" , " <li>attoparsec</li>" , " <li>hspec</li>" , "</ul>" ] value `shouldBe` expected
sourrust/karver
test/Text/KarverSpec.hs
bsd-3-clause
10,337
0
19
4,524
1,417
732
685
190
1
{-# LANGUAGE QuasiQuotes #-} module Test.Euler.Data.Data79 where import MPS data79 = strip [$here| 319 680 180 690 129 620 762 689 762 318 368 710 720 710 629 168 160 689 716 731 736 729 316 729 729 710 769 290 719 680 318 389 162 289 162 718 729 319 790 680 890 362 319 760 316 729 380 319 728 716 |]
nfjinjing/bench-euler
src/Test/Euler/Data/Data79.hs
bsd-3-clause
365
1
8
127
129
67
62
4
1
module Geordi.TableBuilder ( -- * The 'TableBuilder' Type TableBuilder -- * Prefixes and Suffixes , prefix , suffix , monadSuffix -- * Adding handlers , add , handle , get , post , request -- * Running the builder , buildTable ) where import Geordi.TableBuilder.Internal
liamoc/geordi
Geordi/TableBuilder.hs
bsd-3-clause
658
0
4
432
48
33
15
12
0
import Language.NoiseFunge import Control.Lens import Text.Printf import Control.Monad main :: IO () main = void $ flip traverse stdOps $ \o -> do printf "%16s %c %s\n" (o^.opName) (o^.opChar) (o^.opDesc)
wolfspyre/noisefunge
nfops/nfops.hs
gpl-3.0
212
0
11
37
87
46
41
7
1
import NLP.FrenchTAG.Parse main :: IO () -- main = printGrammar "/users/waszczuk/annex-top/annex/work/resources/grammars/FrenchTAG/valuation.xml" main = printGrammar "/users/waszczuk/annex-top/annex/work/resources/grammars/FrenchTAG/part.xml"
kawu/partage4xmg
src/parse-grammar.hs
bsd-2-clause
245
0
6
17
26
14
12
3
1
{-# LANGUAGE ExistentialQuantification, RankNTypes, GADTs, OverloadedStrings #-} ----------------------------------------------------------------------------- -- Copyright 2017, GRACeFUL project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files -- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. ----------------------------------------------------------------------------- -- | -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable (depends on ghc) -- -- A small data type for expressing components. -- ----------------------------------------------------------------------------- module Library ( module Types , Library(..) , Item(..), item , insert, combine, combineList -- Re export , module GCM , module CP , module Sign ) where import GCM hiding (Item) import CP import Sign import Types import Utils import Data.Aeson import qualified Data.Text as T import qualified Data.List as L type Id = String type URL = String data Library = Library { libraryId :: Id , items :: [Item] } deriving Show instance ToJSON Library where toJSON (Library n is) = object [ "library" .= toJSONList is] data Item = Item { itemId :: Id , annotations :: [String] , f :: TypedValue } deriving Show item :: Id -> TypedValue -> Item item n = Item n [] instance ToJSON Item where toJSON (Item n as (f ::: t)) = object $ [ "name" .= n , "parameters" .= parameters t , "interface" .= ports [] t ] ++ jsonAnnotations as jsonAnnotations :: [String] -> [(T.Text, Value)] jsonAnnotations as = map (\(k,v) -> (T.pack k) .= (drop 2 v)) kvs where kvs = map (break (== ':')) as parameters :: Type a -> Value parameters = toJSONList . rec where rec :: Type a -> [Value] rec tp = case tp of t@(Tag n t1) :-> t2 -> tagParam t : rec t2 _ -> [] -- We want to annotate the actual types, not the types they are isomorphic to. prettyShow :: Type a -> String prettyShow t = case t of Iso _ (t1 :|: Unit) -> "Maybe " ++ prettyShow t1 Iso _ tInt -> "Sign" List t1 -> "[" ++ prettyShow t1 ++ "]" Port' t1 -> "Port " ++ "(" ++ prettyShow t1 ++ ")" tp@(Pair t1 t2) -> "(" ++ L.intercalate "," (prettyCollect tp) ++ ")" _ -> show t where prettyCollect :: Type t -> [String] prettyCollect (Pair t1 t2) = prettyCollect t1 ++ prettyCollect t2 prettyCollect t = [prettyShow t] tagParam :: Type a -> Value tagParam (Tag n t) = object [ "name" .= n , "type" .= prettyShow t ] tagParam _ = Null ports :: [String] -> Type a -> [Value] ports as tp = case tp of -- base Tag n x -> case x of Port' _ -> [tagPort as tp] Pair (Port' _) (Port' _) -> [tagPort as tp] List (Port' _) -> [tagPort as tp] List (Pair (Port' _) (Port' _)) -> [tagPort as tp] Tag _ _ -> ports (as ++ [n]) x _ -> [] -- recurse GCM t -> ports as t List t -> ports as t Pair t1 t2 -> ports as t1 ++ ports as t2 _ :-> t2 -> ports as t2 Iso _ t -> ports as t _ -> [] tagPort :: [String] -> Type a -> Value tagPort as (Tag n t) = object $ [ "name" .= n , "type" .= prettyShow t , "description" .= n , "imgURL" .= T.concat ["./data/interfaces/", T.pack n, ".png"] , "label" .= head n] ++ jsonAnnotations as tagPort _ _ = Null -- | Insert new items into a library insert :: [Item] -> Library -> Library insert its (Library n is) = Library n (is ++ its) -- | Combine 2 libraries combine :: String -> Library -> Library -> Library combine n l1 l2 = Library n (items l1 ++ items l2) -- | Combine any number of libraries combineList :: String -> [Library] -> Library combineList n libs = Library n $ foldl (++) [] (map items libs)
GRACeFUL-project/GRACe
src/Library.hs
bsd-3-clause
4,115
0
15
1,217
1,316
695
621
94
12
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-} {- | Module : $Header$ Description : Instances of Logic and other classes for the logic Framework Copyright : (c) Kristina Sojakova, DFKI Bremen 2009 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : portable Signatures of this logic are composed of a logical framework name (currently one of LF, Isabelle, or Maude) to be used as a meta-logic, and a tuple of signature and morphism names which determine the object logic. As such the logic Framework does not have any sentences and only identity signature morphisms. For reference see Integrating Logical Frameworks in Hets by M. Codescu et al (WADT10). -} module Framework.Logic_Framework where import Framework.AS import Framework.ATC_Framework () import Logic.Logic import Data.Monoid import Common.DefaultMorphism type Morphism = DefaultMorphism LogicDef -- lid for logical frameworks data Framework = Framework deriving Show instance Language Framework where description _ = "A framework allowing to add logics dynamically." instance Monoid LogicDef where mempty = error "Framework.Logic_Framework: Monoid LogicDef" mappend _ _ = mempty -- syntax for Framework instance Syntax Framework LogicDef () () () -- sentences for Framework instance Sentences Framework () LogicDef Morphism () -- static analysis for Framework instance StaticAnalysis Framework LogicDef () () () LogicDef Morphism () () where empty_signature Framework = error "Logic Framework does not have an empty signature." -- instance of logic for Framework instance Logic Framework () LogicDef () () () LogicDef Morphism () () () {- ------------------------------------------------------------------------------ FrameworkCom - logical framework for the analysis of comorphisms -} type MorphismCom = DefaultMorphism ComorphismDef data FrameworkCom = FrameworkCom deriving Show instance Language FrameworkCom where description _ = "A framework allowing to add comorphisms between " ++ "logics dynamically." instance Monoid ComorphismDef where mempty = error "Framework.Logic_Framework Monoid ComorphismDef" mappend _ _ = mempty -- syntax for Framework instance Syntax FrameworkCom ComorphismDef () () () -- sentences for Framework instance Sentences FrameworkCom () ComorphismDef MorphismCom () -- static analysis for Framework instance StaticAnalysis FrameworkCom ComorphismDef () () () ComorphismDef MorphismCom () () where empty_signature FrameworkCom = error "Logic FrameworkCom does not have an empty signature." -- instance of logic for Framework instance Logic FrameworkCom () ComorphismDef () () () ComorphismDef MorphismCom () () ()
keithodulaigh/Hets
Framework/Logic_Framework.hs
gpl-2.0
2,873
0
6
525
424
221
203
37
0
module Dotnet.System.IO.TextReader where import Dotnet import qualified Dotnet.System.MarshalByRefObject import qualified Dotnet.System.Array data TextReader_ a type TextReader a = Dotnet.System.MarshalByRefObject.MarshalByRefObject (TextReader_ a) foreign import dotnet "method System.IO.TextReader.ReadLine" readLine :: TextReader obj -> IO (String) foreign import dotnet "method System.IO.TextReader.ReadBlock" readBlock :: Dotnet.System.Array.Array (Char) -> Int -> Int -> TextReader obj -> IO (Int) foreign import dotnet "method System.IO.TextReader.ReadToEnd" readToEnd :: TextReader obj -> IO (String) foreign import dotnet "method System.IO.TextReader.Read" read :: Dotnet.System.Array.Array (Char) -> Int -> Int -> TextReader obj -> IO (Int) foreign import dotnet "method System.IO.TextReader.Read" read_1 :: TextReader obj -> IO (Int) foreign import dotnet "method System.IO.TextReader.Peek" peek :: TextReader obj -> IO (Int) foreign import dotnet "method System.IO.TextReader.Close" close :: TextReader obj -> IO (()) foreign import dotnet "static method System.IO.TextReader.Synchronized" synchronized :: Dotnet.System.IO.TextReader.TextReader a0 -> IO (Dotnet.System.IO.TextReader.TextReader a1) foreign import dotnet "static field System.IO.TextReader.Null" get_Null :: IO (Dotnet.System.IO.TextReader.TextReader a0)
alekar/hugs
dotnet/lib/Dotnet/System/IO/TextReader.hs
bsd-3-clause
1,381
0
11
193
334
186
148
-1
-1
{- wrapper executable that captures arguments to ghc, ar or ld -} {-# LANGUAGE CPP #-} module Main where import Control.Monad (when) import Data.Maybe (fromMaybe) import Distribution.Compiler (CompilerFlavor (..)) import Distribution.Simple.Configure (configCompiler) import Distribution.Simple.Program (arProgram, defaultProgramConfiguration, ghcProgram, ldProgram, programPath) import Distribution.Simple.Program.Db (configureAllKnownPrograms, lookupProgram) import Distribution.Simple.Program.Types (Program (..)) import Distribution.Verbosity (silent) import System.Directory (doesDirectoryExist) import System.Environment (getArgs) import System.Exit (ExitCode (..), exitWith) import System.IO (hPutStrLn, stderr) import System.Process (rawSystem, readProcess) #ifdef LDCMD cmd :: Program cmd = ldProgram outFile = "yesod-devel/ldargs.txt" #else #ifdef ARCMD cmd :: Program cmd = arProgram outFile ="yesod-devel/arargs.txt" #else cmd :: Program cmd = ghcProgram outFile = "yesod-devel/ghcargs.txt" #endif #endif runProgram :: Program -> [String] -> IO ExitCode runProgram pgm args = do (comp, pgmc) <- configCompiler (Just GHC) Nothing Nothing defaultProgramConfiguration silent pgmc' <- configureAllKnownPrograms silent pgmc case lookupProgram pgm pgmc' of Nothing -> do hPutStrLn stderr ("cannot find program '" ++ programName pgm ++ "'") return (ExitFailure 1) Just p -> rawSystem (programPath p) args main :: IO () main = do args <- getArgs e <- doesDirectoryExist "yesod-devel" when e $ writeFile outFile (show args ++ "\n") ex <- runProgram cmd args exitWith ex
ygale/yesod
yesod-bin/ghcwrapper.hs
mit
2,133
0
16
750
415
227
188
38
2
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TemplateHaskell #-} module Diagrams.TwoD.Path.Metafont.Types where import Control.Lens hiding (( # )) #if __GLASGOW_HASKELL__ < 710 import Data.Monoid #endif import Data.Semigroup import Diagrams.Direction import Diagrams.TwoD.Types -- | A @PathJoin@ specifies the directions at both ends of a segment, -- and a join which describes the control points explicitly or implicitly. data PathJoin d j = PJ { _d1 :: d, _j :: j, _d2 :: d } deriving (Functor, Show) makeLenses ''PathJoin -- | A direction can be specified at any point of a path. A /curl/ -- should only be specified at the endpoints. The endpoints default -- to curl 1 if not set. data PathDir n = PathDirCurl n | PathDirDir (Dir n) deriving Show -- | A predicate to determine the constructor used. isCurl :: PathDir n -> Bool isCurl (PathDirDir _) = False isCurl (PathDirCurl _) = True type Curl n = n type Dir n = Direction V2 n type BasicJoin n = Either (TensionJoin n) (ControlJoin n) -- | Higher /Tension/ brings the path closer to a straight line -- between segments. Equivalently, it brings the control points -- closer to the endpoints. @TensionAmt@ introduces a fixed tension. -- @TensionAtLeast@ introduces a tension which will be increased if by -- so doing, an inflection point can be eliminated. data Tension n = TensionAmt n | TensionAtLeast n deriving Show getTension :: Tension n -> n getTension (TensionAmt t) = t getTension (TensionAtLeast t) = t -- | Two tensions and two directions completely determine the control -- points of a segment. data TensionJoin n = TJ { _t1 :: Tension n, _t2 :: Tension n } deriving Show -- | The two intermediate control points of a segment, specified directly. data ControlJoin n = CJ { _c1 :: P2 n, _c2 :: P2 n} deriving Show makeLenses ''TensionJoin makeLenses ''ControlJoin data P data J -- | @MFPathData@ is the type manipulated by the metafont combinators. data MFPathData a n where MFPathCycle:: MFPathData P n MFPathEnd :: P2 n -> MFPathData P n MFPathPt :: P2 n -> MFPathData J n -> MFPathData P n MFPathJoin :: PathJoin (Maybe (PathDir n)) (Maybe (BasicJoin n)) -> MFPathData P n -> MFPathData J n -- | @MetafontSegment@ is used internally in solving the metafont -- equations. It represents a segment with two known endpoints, and a -- /join/, which may be specified in various ways. data MetafontSegment d j n = MFS { _x1 :: P2 n, _pj :: (PathJoin d j ), _x2 :: P2 n } deriving (Functor, Show) -- | @MFPath@ is the type used internally in solving the metafont -- equations. The direction and join types are progressively refined -- until all control points are known. The @loop@ flag affects both -- the equations to be solved and the type of 'Trail' in the result. -- If constructing an @MFPath@ in new code, the responsibility rests -- on the user to ensure that successive @MetafontSegment@s share an -- endpoint. If this is not true, the result is undefined. data MFPath d j n = MFP { _loop :: Bool, _segs :: [MetafontSegment d j n] } deriving Show -- | MFP is a type synonym to clarify signatures in Metafont.Internal. -- Note that the type permits segments which are \"overspecified\", -- having one or both directions specified, and also a 'ControlJoin'. -- In this case, "Metafont.Internal" ignores the directions. type MFP n = MFPath (Maybe (PathDir n)) (BasicJoin n) n -- | MFS is a type synonym to clarify signatures in "Metafont.Internal". type MFS n = MetafontSegment (Maybe (PathDir n)) (BasicJoin n) n makeLenses ''MetafontSegment makeLenses ''MFPath instance Monoid (PathJoin (Maybe (PathDir n)) (Maybe (BasicJoin n))) where -- | The default join, with no directions specified, and both tensions 1. mempty = PJ Nothing Nothing Nothing l `mappend` r = PJ (c (l^.d1) (r^.d1)) (c (l^.j) (r^.j)) (c (l^.d2) (r^.d2)) where c a b = case b of Nothing -> a Just _ -> b instance Semigroup (PathJoin (Maybe (PathDir n)) (Maybe (BasicJoin n))) where (<>) = mappend
wherkendell/diagrams-contrib
src/Diagrams/TwoD/Path/Metafont/Types.hs
bsd-3-clause
4,283
0
11
933
878
494
384
-1
-1
{-# LANGUAGE CPP #-} module TcSimplify( simplifyInfer, pickQuantifiablePreds, growThetaTyVars, simplifyAmbiguityCheck, simplifyDefault, simplifyTop, simplifyInteractive, solveWantedsTcM, -- For Rules we need these two solveWanteds, runTcS ) where #include "HsVersions.h" import Bag import Class ( classKey ) import Class ( Class ) import DynFlags ( ExtensionFlag( Opt_AllowAmbiguousTypes ) , WarningFlag ( Opt_WarnMonomorphism ) , DynFlags( solverIterations ) ) import Inst import Id ( idType ) import Kind ( isKind, isSubKind, defaultKind_maybe ) import ListSetOps import Maybes ( isNothing ) import Name import Outputable import PrelInfo import PrelNames import TcErrors import TcEvidence import TcInteract import TcMType as TcM import TcRnMonad as TcRn import TcSMonad as TcS import TcType import TrieMap () -- DV: for now import TyCon ( isTypeFamilyTyCon ) import Type ( classifyPredType, isIPClass, PredTree(..) , getClassPredTys_maybe, EqRel(..) ) import Unify ( tcMatchTy ) import Util import Var import VarSet import BasicTypes ( IntWithInf, intGtLimit ) import ErrUtils ( emptyMessages ) import FastString import Control.Monad ( unless ) import Data.List ( partition ) {- ********************************************************************************* * * * External interface * * * ********************************************************************************* -} simplifyTop :: WantedConstraints -> TcM (Bag EvBind) -- Simplify top-level constraints -- Usually these will be implications, -- but when there is nothing to quantify we don't wrap -- in a degenerate implication, so we do that here instead simplifyTop wanteds = do { traceTc "simplifyTop {" $ text "wanted = " <+> ppr wanteds ; ((final_wc, unsafe_ol), binds1) <- runTcS $ simpl_top wanteds ; traceTc "End simplifyTop }" empty ; traceTc "reportUnsolved {" empty ; binds2 <- reportUnsolved final_wc ; traceTc "reportUnsolved }" empty ; traceTc "reportUnsolved (unsafe overlapping) {" empty ; unless (isEmptyCts unsafe_ol) $ do { -- grab current error messages and clear, warnAllUnsolved will -- update error messages which we'll grab and then restore saved -- messages. ; errs_var <- getErrsVar ; saved_msg <- TcRn.readTcRef errs_var ; TcRn.writeTcRef errs_var emptyMessages ; warnAllUnsolved $ WC { wc_simple = unsafe_ol , wc_insol = emptyCts , wc_impl = emptyBag } ; whyUnsafe <- fst <$> TcRn.readTcRef errs_var ; TcRn.writeTcRef errs_var saved_msg ; recordUnsafeInfer whyUnsafe } ; traceTc "reportUnsolved (unsafe overlapping) }" empty ; return (binds1 `unionBags` binds2) } type SafeOverlapFailures = Cts -- ^ See Note [Safe Haskell Overlapping Instances Implementation] type FinalConstraints = (WantedConstraints, SafeOverlapFailures) simpl_top :: WantedConstraints -> TcS FinalConstraints -- See Note [Top-level Defaulting Plan] simpl_top wanteds = do { wc_first_go <- nestTcS (solveWantedsAndDrop wanteds) -- This is where the main work happens ; wc_final <- try_tyvar_defaulting wc_first_go ; unsafe_ol <- getSafeOverlapFailures ; return (wc_final, unsafe_ol) } where try_tyvar_defaulting :: WantedConstraints -> TcS WantedConstraints try_tyvar_defaulting wc | isEmptyWC wc = return wc | otherwise = do { free_tvs <- TcS.zonkTyVarsAndFV (tyVarsOfWC wc) ; let meta_tvs = varSetElems (filterVarSet isMetaTyVar free_tvs) -- zonkTyVarsAndFV: the wc_first_go is not yet zonked -- filter isMetaTyVar: we might have runtime-skolems in GHCi, -- and we definitely don't want to try to assign to those! ; meta_tvs' <- mapM defaultTyVar meta_tvs -- Has unification side effects ; if meta_tvs' == meta_tvs -- No defaulting took place; -- (defaulting returns fresh vars) then try_class_defaulting wc else do { wc_residual <- nestTcS (solveWantedsAndDrop wc) -- See Note [Must simplify after defaulting] ; try_class_defaulting wc_residual } } try_class_defaulting :: WantedConstraints -> TcS WantedConstraints try_class_defaulting wc | isEmptyWC wc = return wc | otherwise -- See Note [When to do type-class defaulting] = do { something_happened <- applyDefaultingRules wc -- See Note [Top-level Defaulting Plan] ; if something_happened then do { wc_residual <- nestTcS (solveWantedsAndDrop wc) ; try_class_defaulting wc_residual } else return wc } {- Note [When to do type-class defaulting] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In GHC 7.6 and 7.8.2, we did type-class defaulting only if insolubleWC was false, on the grounds that defaulting can't help solve insoluble constraints. But if we *don't* do defaulting we may report a whole lot of errors that would be solved by defaulting; these errors are quite spurious because fixing the single insoluble error means that defaulting happens again, which makes all the other errors go away. This is jolly confusing: Trac #9033. So it seems better to always do type-class defaulting. However, always doing defaulting does mean that we'll do it in situations like this (Trac #5934): run :: (forall s. GenST s) -> Int run = fromInteger 0 We don't unify the return type of fromInteger with the given function type, because the latter involves foralls. So we're left with (Num alpha, alpha ~ (forall s. GenST s) -> Int) Now we do defaulting, get alpha := Integer, and report that we can't match Integer with (forall s. GenST s) -> Int. That's not totally stupid, but perhaps a little strange. Another potential alternative would be to suppress *all* non-insoluble errors if there are *any* insoluble errors, anywhere, but that seems too drastic. Note [Must simplify after defaulting] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We may have a deeply buried constraint (t:*) ~ (a:Open) which we couldn't solve because of the kind incompatibility, and 'a' is free. Then when we default 'a' we can solve the constraint. And we want to do that before starting in on type classes. We MUST do it before reporting errors, because it isn't an error! Trac #7967 was due to this. Note [Top-level Defaulting Plan] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We have considered two design choices for where/when to apply defaulting. (i) Do it in SimplCheck mode only /whenever/ you try to solve some simple constraints, maybe deep inside the context of implications. This used to be the case in GHC 7.4.1. (ii) Do it in a tight loop at simplifyTop, once all other constraints have finished. This is the current story. Option (i) had many disadvantages: a) Firstly, it was deep inside the actual solver. b) Secondly, it was dependent on the context (Infer a type signature, or Check a type signature, or Interactive) since we did not want to always start defaulting when inferring (though there is an exception to this, see Note [Default while Inferring]). c) It plainly did not work. Consider typecheck/should_compile/DfltProb2.hs: f :: Int -> Bool f x = const True (\y -> let w :: a -> a w a = const a (y+1) in w y) We will get an implication constraint (for beta the type of y): [untch=beta] forall a. 0 => Num beta which we really cannot default /while solving/ the implication, since beta is untouchable. Instead our new defaulting story is to pull defaulting out of the solver loop and go with option (i), implemented at SimplifyTop. Namely: - First, have a go at solving the residual constraint of the whole program - Try to approximate it with a simple constraint - Figure out derived defaulting equations for that simple constraint - Go round the loop again if you did manage to get some equations Now, that has to do with class defaulting. However there exists type variable /kind/ defaulting. Again this is done at the top-level and the plan is: - At the top-level, once you had a go at solving the constraint, do figure out /all/ the touchable unification variables of the wanted constraints. - Apply defaulting to their kinds More details in Note [DefaultTyVar]. Note [Safe Haskell Overlapping Instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In Safe Haskell, we apply an extra restriction to overlapping instances. The motive is to prevent untrusted code provided by a third-party, changing the behavior of trusted code through type-classes. This is due to the global and implicit nature of type-classes that can hide the source of the dictionary. Another way to state this is: if a module M compiles without importing another module N, changing M to import N shouldn't change the behavior of M. Overlapping instances with type-classes can violate this principle. However, overlapping instances aren't always unsafe. They are just unsafe when the most selected dictionary comes from untrusted code (code compiled with -XSafe) and overlaps instances provided by other modules. In particular, in Safe Haskell at a call site with overlapping instances, we apply the following rule to determine if it is a 'unsafe' overlap: 1) Most specific instance, I1, defined in an `-XSafe` compiled module. 2) I1 is an orphan instance or a MPTC. 3) At least one overlapped instance, Ix, is both: A) from a different module than I1 B) Ix is not marked `OVERLAPPABLE` This is a slightly involved heuristic, but captures the situation of an imported module N changing the behavior of existing code. For example, if condition (2) isn't violated, then the module author M must depend either on a type-class or type defined in N. Secondly, when should these heuristics be enforced? We enforced them when the type-class method call site is in a module marked `-XSafe` or `-XTrustworthy`. This allows `-XUnsafe` modules to operate without restriction, and for Safe Haskell inferrence to infer modules with unsafe overlaps as unsafe. One alternative design would be to also consider if an instance was imported as a `safe` import or not and only apply the restriction to instances imported safely. However, since instances are global and can be imported through more than one path, this alternative doesn't work. Note [Safe Haskell Overlapping Instances Implementation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ How is this implemented? It's complicated! So we'll step through it all: 1) `InstEnv.lookupInstEnv` -- Performs instance resolution, so this is where we check if a particular type-class method call is safe or unsafe. We do this through the return type, `ClsInstLookupResult`, where the last parameter is a list of instances that are unsafe to overlap. When the method call is safe, the list is null. 2) `TcInteract.matchClassInst` -- This module drives the instance resolution / dictionary generation. The return type is `LookupInstResult`, which either says no instance matched, or one found, and if it was a safe or unsafe overlap. 3) `TcInteract.doTopReactDict` -- Takes a dictionary / class constraint and tries to resolve it by calling (in part) `matchClassInst`. The resolving mechanism has a work list (of constraints) that it process one at a time. If the constraint can't be resolved, it's added to an inert set. When compiling an `-XSafe` or `-XTrustworthy` module, we follow this approach as we know compilation should fail. These are handled as normal constraint resolution failures from here-on (see step 6). Otherwise, we may be inferring safety (or using `-fwarn-unsafe`), and compilation should succeed, but print warnings and/or mark the compiled module as `-XUnsafe`. In this case, we call `insertSafeOverlapFailureTcS` which adds the unsafe (but resolved!) constraint to the `inert_safehask` field of `InertCans`. 4) `TcSimplify.simpl_top` -- Top-level function for driving the simplifier for constraint resolution. Once finished, we call `getSafeOverlapFailures` to retrieve the list of overlapping instances that were successfully resolved, but unsafe. Remember, this is only applicable for generating warnings (`-fwarn-unsafe`) or inferring a module unsafe. `-XSafe` and `-XTrustworthy` cause compilation failure by not resolving the unsafe constraint at all. `simpl_top` returns a list of unresolved constraints (all types), and resolved (but unsafe) resolved dictionary constraints. 5) `TcSimplify.simplifyTop` -- Is the caller of `simpl_top`. For unresolved constraints, it calls `TcErrors.reportUnsolved`, while for unsafe overlapping instance constraints, it calls `TcErrors.warnAllUnsolved`. Both functions convert constraints into a warning message for the user. 6) `TcErrors.*Unsolved` -- Generates error messages for constraints by actually calling `InstEnv.lookupInstEnv` again! Yes, confusing, but all we know is the constraint that is unresolved or unsafe. For dictionary, all we know is that we need a dictionary of type C, but not what instances are available and how they overlap. So we once again call `lookupInstEnv` to figure that out so we can generate a helpful error message. 7) `TcSimplify.simplifyTop` -- In the case of `warnAllUnsolved` for resolved, but unsafe dictionary constraints, we collect the generated warning message (pop it) and call `TcRnMonad.recordUnsafeInfer` to mark the module we are compiling as unsafe, passing the warning message along as the reason. 8) `TcRnMonad.recordUnsafeInfer` -- Save the unsafe result and reason in an IORef called `tcg_safeInfer`. 9) `HscMain.tcRnModule'` -- Reads `tcg_safeInfer` after type-checking, calling `HscMain.markUnsafeInfer` (passing the reason along) when safe-inferrence failed. -} ------------------ simplifyAmbiguityCheck :: Type -> WantedConstraints -> TcM () simplifyAmbiguityCheck ty wanteds = do { traceTc "simplifyAmbiguityCheck {" (text "type = " <+> ppr ty $$ text "wanted = " <+> ppr wanteds) ; ((final_wc, _), _binds) <- runTcS $ simpl_top wanteds ; traceTc "End simplifyAmbiguityCheck }" empty -- Normally report all errors; but with -XAllowAmbiguousTypes -- report only insoluble ones, since they represent genuinely -- inaccessible code ; allow_ambiguous <- xoptM Opt_AllowAmbiguousTypes ; traceTc "reportUnsolved(ambig) {" empty ; tc_lvl <- TcRn.getTcLevel ; unless (allow_ambiguous && not (insolubleWC tc_lvl final_wc)) (discardResult (reportUnsolved final_wc)) ; traceTc "reportUnsolved(ambig) }" empty ; return () } ------------------ simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind) simplifyInteractive wanteds = traceTc "simplifyInteractive" empty >> simplifyTop wanteds ------------------ simplifyDefault :: ThetaType -- Wanted; has no type variables in it -> TcM () -- Succeeds if the constraint is soluble simplifyDefault theta = do { traceTc "simplifyInteractive" empty ; wanted <- newWanteds DefaultOrigin theta ; unsolved <- solveWantedsTcM wanted ; traceTc "reportUnsolved {" empty -- See Note [Deferring coercion errors to runtime] ; reportAllUnsolved unsolved ; traceTc "reportUnsolved }" empty ; return () } {- ********************************************************************************* * * * Inference * * *********************************************************************************** Note [Inferring the type of a let-bound variable] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f x = rhs To infer f's type we do the following: * Gather the constraints for the RHS with ambient level *one more than* the current one. This is done by the call pushLevelAndCaptureConstraints (tcMonoBinds...) in TcBinds.tcPolyInfer * Call simplifyInfer to simplify the constraints and decide what to quantify over. We pass in the level used for the RHS constraints, here called rhs_tclvl. This ensures that the implication constraint we generate, if any, has a strictly-increased level compared to the ambient level outside the let binding. -} simplifyInfer :: TcLevel -- Used when generating the constraints -> Bool -- Apply monomorphism restriction -> [TcTyVar] -- The quantified tyvars of any signatures -- see Note [Which type variables to quantify] -> [(Name, TcTauType)] -- Variables to be generalised, -- and their tau-types -> WantedConstraints -> TcM ([TcTyVar], -- Quantify over these type variables [EvVar], -- ... and these constraints (fully zonked) TcEvBinds) -- ... binding these evidence variables simplifyInfer rhs_tclvl apply_mr sig_qtvs name_taus wanteds | isEmptyWC wanteds = do { gbl_tvs <- tcGetGlobalTyVars ; qtkvs <- quantifyTyVars gbl_tvs (tyVarsOfTypes (map snd name_taus)) ; traceTc "simplifyInfer: empty WC" (ppr name_taus $$ ppr qtkvs) ; return (qtkvs, [], emptyTcEvBinds) } | otherwise = do { traceTc "simplifyInfer {" $ vcat [ ptext (sLit "binds =") <+> ppr name_taus , ptext (sLit "rhs_tclvl =") <+> ppr rhs_tclvl , ptext (sLit "apply_mr =") <+> ppr apply_mr , ptext (sLit "(unzonked) wanted =") <+> ppr wanteds ] -- Historical note: Before step 2 we used to have a -- HORRIBLE HACK described in Note [Avoid unnecessary -- constraint simplification] but, as described in Trac -- #4361, we have taken in out now. That's why we start -- with step 2! -- Step 2) First try full-blown solving -- NB: we must gather up all the bindings from doing -- this solving; hence (runTcSWithEvBinds ev_binds_var). -- And note that since there are nested implications, -- calling solveWanteds will side-effect their evidence -- bindings, so we can't just revert to the input -- constraint. ; ev_binds_var <- TcM.newTcEvBinds ; wanted_transformed_incl_derivs <- setTcLevel rhs_tclvl $ runTcSWithEvBinds ev_binds_var (solveWanteds wanteds) ; wanted_transformed_incl_derivs <- TcM.zonkWC wanted_transformed_incl_derivs -- Step 4) Candidates for quantification are an approximation of wanted_transformed -- NB: Already the fixpoint of any unifications that may have happened -- NB: We do not do any defaulting when inferring a type, this can lead -- to less polymorphic types, see Note [Default while Inferring] ; tc_lcl_env <- TcRn.getLclEnv ; null_ev_binds_var <- TcM.newTcEvBinds ; let wanted_transformed = dropDerivedWC wanted_transformed_incl_derivs ; quant_pred_candidates -- Fully zonked <- if insolubleWC rhs_tclvl wanted_transformed_incl_derivs then return [] -- See Note [Quantification with errors] -- NB: must include derived errors in this test, -- hence "incl_derivs" else do { let quant_cand = approximateWC wanted_transformed meta_tvs = filter isMetaTyVar (varSetElems (tyVarsOfCts quant_cand)) ; gbl_tvs <- tcGetGlobalTyVars -- Miminise quant_cand. We are not interested in any evidence -- produced, because we are going to simplify wanted_transformed -- again later. All we want here are the predicates over which to -- quantify. -- -- If any meta-tyvar unifications take place (unlikely), we'll -- pick that up later. ; WC { wc_simple = simples } <- setTcLevel rhs_tclvl $ runTcSWithEvBinds null_ev_binds_var $ do { mapM_ (promoteAndDefaultTyVar rhs_tclvl gbl_tvs) meta_tvs -- See Note [Promote _and_ default when inferring] ; solveSimpleWanteds quant_cand } ; return [ ctEvPred ev | ct <- bagToList simples , let ev = ctEvidence ct , isWanted ev ] } -- NB: quant_pred_candidates is already fully zonked -- Decide what type variables and constraints to quantify ; zonked_taus <- mapM (TcM.zonkTcType . snd) name_taus ; let zonked_tau_tvs = tyVarsOfTypes zonked_taus ; (qtvs, bound_theta) <- decideQuantification apply_mr sig_qtvs name_taus quant_pred_candidates zonked_tau_tvs -- Emit an implication constraint for the -- remaining constraints from the RHS ; bound_ev_vars <- mapM TcM.newEvVar bound_theta ; let skol_info = InferSkol [ (name, mkSigmaTy [] bound_theta ty) | (name, ty) <- name_taus ] -- Don't add the quantified variables here, because -- they are also bound in ic_skols and we want them -- to be tidied uniformly implic = Implic { ic_tclvl = rhs_tclvl , ic_skols = qtvs , ic_no_eqs = False , ic_given = bound_ev_vars , ic_wanted = wanted_transformed , ic_status = IC_Unsolved , ic_binds = ev_binds_var , ic_info = skol_info , ic_env = tc_lcl_env } ; emitImplication implic -- Promote any type variables that are free in the inferred type -- of the function: -- f :: forall qtvs. bound_theta => zonked_tau -- These variables now become free in the envt, and hence will show -- up whenever 'f' is called. They may currently at rhs_tclvl, but -- they had better be unifiable at the outer_tclvl! -- Example: envt mentions alpha[1] -- tau_ty = beta[2] -> beta[2] -- consraints = alpha ~ [beta] -- we don't quantify over beta (since it is fixed by envt) -- so we must promote it! The inferred type is just -- f :: beta -> beta ; outer_tclvl <- TcRn.getTcLevel ; zonked_tau_tvs <- TcM.zonkTyVarsAndFV zonked_tau_tvs -- decideQuantification turned some meta tyvars into -- quantified skolems, so we have to zonk again ; let phi_tvs = tyVarsOfTypes bound_theta `unionVarSet` zonked_tau_tvs promote_tvs = varSetElems (closeOverKinds phi_tvs `delVarSetList` qtvs) ; runTcSWithEvBinds null_ev_binds_var $ -- runTcS just to get the types right :-( mapM_ (promoteTyVar outer_tclvl) promote_tvs -- All done! ; traceTc "} simplifyInfer/produced residual implication for quantification" $ vcat [ ptext (sLit "quant_pred_candidates =") <+> ppr quant_pred_candidates , ptext (sLit "zonked_taus") <+> ppr zonked_taus , ptext (sLit "zonked_tau_tvs=") <+> ppr zonked_tau_tvs , ptext (sLit "promote_tvs=") <+> ppr promote_tvs , ptext (sLit "bound_theta =") <+> vcat [ ppr v <+> dcolon <+> ppr (idType v) | v <- bound_ev_vars] , ptext (sLit "qtvs =") <+> ppr qtvs , ptext (sLit "implic =") <+> ppr implic ] ; return ( qtvs, bound_ev_vars, TcEvBinds ev_binds_var) } {- ************************************************************************ * * Quantification * * ************************************************************************ Note [Deciding quantification] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the monomorphism restriction does not apply, then we quantify as follows: * Take the global tyvars, and "grow" them using the equality constraints E.g. if x:alpha is in the environment, and alpha ~ [beta] (which can happen because alpha is untouchable here) then do not quantify over beta, because alpha fixes beta, and beta is effectively free in the environment too These are the mono_tvs * Take the free vars of the tau-type (zonked_tau_tvs) and "grow" them using all the constraints. These are tau_tvs_plus * Use quantifyTyVars to quantify over (tau_tvs_plus - mono_tvs), being careful to close over kinds, and to skolemise the quantified tyvars. (This actually unifies each quantifies meta-tyvar with a fresh skolem.) Result is qtvs. * Filter the constraints using pickQuantifyablePreds and the qtvs. We have to zonk the constraints first, so they "see" the freshly created skolems. If the MR does apply, mono_tvs includes all the constrained tyvars, and the quantified constraints are empty/insoluble -} decideQuantification :: Bool -- Apply monomorphism restriction -> [TcTyVar] -> [(Name, TcTauType)] -- Variables to be generalised (just for error msg) -> [PredType] -> TcTyVarSet -- Constraints and type variables from RHS -> TcM ( [TcTyVar] -- Quantify over these tyvars (skolems) , [PredType]) -- and this context (fully zonked) -- See Note [Deciding quantification] decideQuantification apply_mr sig_qtvs name_taus constraints zonked_tau_tvs | apply_mr -- Apply the Monomorphism restriction = do { gbl_tvs <- tcGetGlobalTyVars ; let constrained_tvs = tyVarsOfTypes constraints mono_tvs = gbl_tvs `unionVarSet` constrained_tvs mr_bites = constrained_tvs `intersectsVarSet` zonked_tau_tvs ; qtvs <- quantify_tvs mono_tvs zonked_tau_tvs ; traceTc "decideQuantification 1" (vcat [ppr constraints, ppr gbl_tvs, ppr mono_tvs , ppr qtvs, ppr mr_bites]) -- Warn about the monomorphism restriction ; warn_mono <- woptM Opt_WarnMonomorphism ; warnTc (warn_mono && mr_bites) $ hang (ptext (sLit "The Monomorphism Restriction applies to the binding") <> plural bndrs <+> ptext (sLit "for") <+> pp_bndrs) 2 (ptext (sLit "Consider giving a type signature for") <+> if isSingleton bndrs then pp_bndrs else ptext (sLit "these binders")) ; return (qtvs, []) } | otherwise = do { gbl_tvs <- tcGetGlobalTyVars ; let mono_tvs = growThetaTyVars (filter isEqPred constraints) gbl_tvs tau_tvs_plus = growThetaTyVars constraints zonked_tau_tvs ; qtvs <- quantify_tvs mono_tvs tau_tvs_plus ; constraints <- zonkTcThetaType constraints -- quantifyTyVars turned some meta tyvars into -- quantified skolems, so we have to zonk again ; theta <- pickQuantifiablePreds (mkVarSet qtvs) constraints ; let min_theta = mkMinimalBySCs theta -- See Note [Minimize by Superclasses] ; traceTc "decideQuantification 2" (vcat [ppr constraints, ppr gbl_tvs, ppr mono_tvs , ppr tau_tvs_plus, ppr qtvs, ppr min_theta]) ; return (qtvs, min_theta) } where bndrs = map fst name_taus pp_bndrs = pprWithCommas (quotes . ppr) bndrs quantify_tvs mono_tvs tau_tvs -- See Note [Which type variable to quantify] | null sig_qtvs = quantifyTyVars mono_tvs tau_tvs | otherwise = quantifyTyVars (mono_tvs `delVarSetList` sig_qtvs) (tau_tvs `extendVarSetList` sig_qtvs) ------------------ pickQuantifiablePreds :: TyVarSet -- Quantifying over these -> TcThetaType -- Proposed constraints to quantify -> TcM TcThetaType -- A subset that we can actually quantify -- This function decides whether a particular constraint should be -- quantified over, given the type variables that are being quantified pickQuantifiablePreds qtvs theta = do { let flex_ctxt = True -- Quantify over non-tyvar constraints, even without -- -XFlexibleContexts: see Trac #10608, #10351 -- flex_ctxt <- xoptM Opt_FlexibleContexts ; return (filter (pick_me flex_ctxt) theta) } where pick_me flex_ctxt pred = case classifyPredType pred of ClassPred cls tys | isIPClass cls -> True -- See note [Inheriting implicit parameters] | otherwise -> pick_cls_pred flex_ctxt tys EqPred ReprEq ty1 ty2 -> pick_cls_pred flex_ctxt [ty1, ty2] -- Representational equality is like a class constraint EqPred NomEq ty1 ty2 -> quant_fun ty1 || quant_fun ty2 IrredPred ty -> tyVarsOfType ty `intersectsVarSet` qtvs pick_cls_pred flex_ctxt tys = tyVarsOfTypes tys `intersectsVarSet` qtvs && (checkValidClsArgs flex_ctxt tys) -- Only quantify over predicates that checkValidType -- will pass! See Trac #10351. -- See Note [Quantifying over equality constraints] quant_fun ty = case tcSplitTyConApp_maybe ty of Just (tc, tys) | isTypeFamilyTyCon tc -> tyVarsOfTypes tys `intersectsVarSet` qtvs _ -> False ------------------ growThetaTyVars :: ThetaType -> TyVarSet -> TyVarSet -- See Note [Growing the tau-tvs using constraints] growThetaTyVars theta tvs | null theta = tvs | otherwise = transCloVarSet mk_next seed_tvs where seed_tvs = tvs `unionVarSet` tyVarsOfTypes ips (ips, non_ips) = partition isIPPred theta -- See note [Inheriting implicit parameters] mk_next :: VarSet -> VarSet -- Maps current set to newly-grown ones mk_next so_far = foldr (grow_one so_far) emptyVarSet non_ips grow_one so_far pred tvs | pred_tvs `intersectsVarSet` so_far = tvs `unionVarSet` pred_tvs | otherwise = tvs where pred_tvs = tyVarsOfType pred {- Note [Which type variables to quantify] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When choosing type variables to quantify, the basic plan is to quantify over all type variables that are * free in the tau_tvs, and * not forced to be monomorphic (mono_tvs), for example by being free in the environment. However, for a pattern binding, or with wildcards, we might be doing inference *in the presence of a type signature*. Mostly, if there is a signature, we use CheckGen, not InferGen, but with pattern bindings or wildcards we might do inference and still have a type signature. For example: f :: _ -> a f x = ... or p :: a -> a (p,q) = e In both cases we use plan InferGen, and hence call simplifyInfer. But those 'a' variables are skolems, and we should be sure to quantify over them, regardless of the monomorphism restriction etc. If we don't, when reporting a type error we panic when we find that a skolem isn't bound by any enclosing implication. That's why we pass sig_qtvs to simplifyInfer, and make sure (in quantify_tvs) that we do quantify over them. Trac #10615 is a case in point. Note [Quantifying over equality constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Should we quantify over an equality constraint (s ~ t)? In general, we don't. Doing so may simply postpone a type error from the function definition site to its call site. (At worst, imagine (Int ~ Bool)). However, consider this forall a. (F [a] ~ Int) => blah Should we quantify over the (F [a] ~ Int)? Perhaps yes, because at the call site we will know 'a', and perhaps we have instance F [Bool] = Int. So we *do* quantify over a type-family equality where the arguments mention the quantified variables. Note [Growing the tau-tvs using constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (growThetaTyVars insts tvs) is the result of extending the set of tyvars, tvs, using all conceivable links from pred E.g. tvs = {a}, preds = {H [a] b, K (b,Int) c, Eq e} Then growThetaTyVars preds tvs = {a,b,c} Notice that growThetaTyVars is conservative if v might be fixed by vs => v `elem` grow(vs,C) Note [Inheriting implicit parameters] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this: f x = (x::Int) + ?y where f is *not* a top-level binding. From the RHS of f we'll get the constraint (?y::Int). There are two types we might infer for f: f :: Int -> Int (so we get ?y from the context of f's definition), or f :: (?y::Int) => Int -> Int At first you might think the first was better, because then ?y behaves like a free variable of the definition, rather than having to be passed at each call site. But of course, the WHOLE IDEA is that ?y should be passed at each call site (that's what dynamic binding means) so we'd better infer the second. BOTTOM LINE: when *inferring types* you must quantify over implicit parameters, *even if* they don't mention the bound type variables. Reason: because implicit parameters, uniquely, have local instance declarations. See the pickQuantifiablePreds. Note [Quantification with errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we find that the RHS of the definition has some absolutely-insoluble constraints, we abandon all attempts to find a context to quantify over, and instead make the function fully-polymorphic in whatever type we have found. For two reasons a) Minimise downstream errors b) Avoid spurious errors from this function But NB that we must include *derived* errors in the check. Example: (a::*) ~ Int# We get an insoluble derived error *~#, and we don't want to discard it before doing the isInsolubleWC test! (Trac #8262) Note [Default while Inferring] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Our current plan is that defaulting only happens at simplifyTop and not simplifyInfer. This may lead to some insoluble deferred constraints. Example: instance D g => C g Int b constraint inferred = (forall b. 0 => C gamma alpha b) /\ Num alpha type inferred = gamma -> gamma Now, if we try to default (alpha := Int) we will be able to refine the implication to (forall b. 0 => C gamma Int b) which can then be simplified further to (forall b. 0 => D gamma) Finally, we /can/ approximate this implication with (D gamma) and infer the quantified type: forall g. D g => g -> g Instead what will currently happen is that we will get a quantified type (forall g. g -> g) and an implication: forall g. 0 => (forall b. 0 => C g alpha b) /\ Num alpha Which, even if the simplifyTop defaults (alpha := Int) we will still be left with an unsolvable implication: forall g. 0 => (forall b. 0 => D g) The concrete example would be: h :: C g a s => g -> a -> ST s a f (x::gamma) = (\_ -> x) (runST (h x (undefined::alpha)) + 1) But it is quite tedious to do defaulting and resolve the implication constraints, and we have not observed code breaking because of the lack of defaulting in inference, so we don't do it for now. Note [Minimize by Superclasses] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we quantify over a constraint, in simplifyInfer we need to quantify over a constraint that is minimal in some sense: For instance, if the final wanted constraint is (Eq alpha, Ord alpha), we'd like to quantify over Ord alpha, because we can just get Eq alpha from superclass selection from Ord alpha. This minimization is what mkMinimalBySCs does. Then, simplifyInfer uses the minimal constraint to check the original wanted. Note [Avoid unnecessary constraint simplification] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------- NB NB NB (Jun 12) ------------- This note not longer applies; see the notes with Trac #4361. But I'm leaving it in here so we remember the issue.) ---------------------------------------- When inferring the type of a let-binding, with simplifyInfer, try to avoid unnecessarily simplifying class constraints. Doing so aids sharing, but it also helps with delicate situations like instance C t => C [t] where .. f :: C [t] => .... f x = let g y = ...(constraint C [t])... in ... When inferring a type for 'g', we don't want to apply the instance decl, because then we can't satisfy (C t). So we just notice that g isn't quantified over 't' and partition the constraints before simplifying. This only half-works, but then let-generalisation only half-works. ********************************************************************************* * * * Main Simplifier * * * *********************************************************************************** Note [Deferring coercion errors to runtime] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ While developing, sometimes it is desirable to allow compilation to succeed even if there are type errors in the code. Consider the following case: module Main where a :: Int a = 'a' main = print "b" Even though `a` is ill-typed, it is not used in the end, so if all that we're interested in is `main` it is handy to be able to ignore the problems in `a`. Since we treat type equalities as evidence, this is relatively simple. Whenever we run into a type mismatch in TcUnify, we normally just emit an error. But it is always safe to defer the mismatch to the main constraint solver. If we do that, `a` will get transformed into co :: Int ~ Char co = ... a :: Int a = 'a' `cast` co The constraint solver would realize that `co` is an insoluble constraint, and emit an error with `reportUnsolved`. But we can also replace the right-hand side of `co` with `error "Deferred type error: Int ~ Char"`. This allows the program to compile, and it will run fine unless we evaluate `a`. This is what `deferErrorsToRuntime` does. It does this by keeping track of which errors correspond to which coercion in TcErrors (with ErrEnv). TcErrors.reportTidyWanteds does not print the errors, and does not fail if -fdefer-type-errors is on, so that we can continue compilation. The errors are turned into warnings in `reportUnsolved`. -} solveWantedsTcM :: [CtEvidence] -> TcM WantedConstraints -- Simplify the input constraints -- Discard the evidence binds -- Discards all Derived stuff in result -- Result is /not/ guaranteed zonked solveWantedsTcM wanted = do { (wanted1, _binds) <- runTcS (solveWantedsAndDrop (mkSimpleWC wanted)) ; return wanted1 } solveWantedsAndDrop :: WantedConstraints -> TcS WantedConstraints -- Since solveWanteds returns the residual WantedConstraints, -- it should always be called within a runTcS or something similar, -- Result is not zonked solveWantedsAndDrop wanted = do { wc <- solveWanteds wanted ; return (dropDerivedWC wc) } solveWanteds :: WantedConstraints -> TcS WantedConstraints -- so that the inert set doesn't mindlessly propagate. -- NB: wc_simples may be wanted /or/ derived now solveWanteds wc@(WC { wc_simple = simples, wc_insol = insols, wc_impl = implics }) = do { traceTcS "solveWanteds {" (ppr wc) -- Try the simple bit, including insolubles. Solving insolubles a -- second time round is a bit of a waste; but the code is simple -- and the program is wrong anyway, and we don't run the danger -- of adding Derived insolubles twice; see -- TcSMonad Note [Do not add duplicate derived insolubles] ; wc1 <- solveSimpleWanteds simples ; let WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 } = wc1 ; (floated_eqs, implics2) <- solveNestedImplications (implics `unionBags` implics1) ; dflags <- getDynFlags ; final_wc <- simpl_loop 0 (solverIterations dflags) floated_eqs (WC { wc_simple = simples1, wc_impl = implics2 , wc_insol = insols `unionBags` insols1 }) ; bb <- getTcEvBindsMap ; traceTcS "solveWanteds }" $ vcat [ text "final wc =" <+> ppr final_wc , text "current evbinds =" <+> ppr (evBindMapBinds bb) ] ; return final_wc } simpl_loop :: Int -> IntWithInf -> Cts -> WantedConstraints -> TcS WantedConstraints simpl_loop n limit floated_eqs wc@(WC { wc_simple = simples, wc_insol = insols, wc_impl = implics }) | n `intGtLimit` limit = failTcS (hang (ptext (sLit "solveWanteds: too many iterations") <+> parens (ptext (sLit "limit =") <+> ppr limit)) 2 (vcat [ ptext (sLit "Set limit with -fsolver-iterations=n; n=0 for no limit") , ppr wc ] )) | no_floated_eqs = return wc -- Done! | otherwise = do { traceTcS "simpl_loop, iteration" (int n) -- solveSimples may make progress if either float_eqs hold ; (unifs1, wc1) <- reportUnifications $ solveSimpleWanteds (floated_eqs `unionBags` simples) -- Put floated_eqs first so they get solved first -- NB: the floated_eqs may include /derived/ equalities -- arising from fundeps inside an implication ; let WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 } = wc1 -- solveImplications may make progress only if unifs2 holds ; (floated_eqs2, implics2) <- if unifs1 == 0 && isEmptyBag implics1 then return (emptyBag, implics) else solveNestedImplications (implics `unionBags` implics1) ; simpl_loop (n+1) limit floated_eqs2 (WC { wc_simple = simples1, wc_impl = implics2 , wc_insol = insols `unionBags` insols1 }) } where no_floated_eqs = isEmptyBag floated_eqs solveNestedImplications :: Bag Implication -> TcS (Cts, Bag Implication) -- Precondition: the TcS inerts may contain unsolved simples which have -- to be converted to givens before we go inside a nested implication. solveNestedImplications implics | isEmptyBag implics = return (emptyBag, emptyBag) | otherwise = do { traceTcS "solveNestedImplications starting {" empty ; (floated_eqs_s, unsolved_implics) <- mapAndUnzipBagM solveImplication implics ; let floated_eqs = concatBag floated_eqs_s -- ... and we are back in the original TcS inerts -- Notice that the original includes the _insoluble_simples so it was safe to ignore -- them in the beginning of this function. ; traceTcS "solveNestedImplications end }" $ vcat [ text "all floated_eqs =" <+> ppr floated_eqs , text "unsolved_implics =" <+> ppr unsolved_implics ] ; return (floated_eqs, catBagMaybes unsolved_implics) } solveImplication :: Implication -- Wanted -> TcS (Cts, -- All wanted or derived floated equalities: var = type Maybe Implication) -- Simplified implication (empty or singleton) -- Precondition: The TcS monad contains an empty worklist and given-only inerts -- which after trying to solve this implication we must restore to their original value solveImplication imp@(Implic { ic_tclvl = tclvl , ic_binds = ev_binds , ic_skols = skols , ic_given = givens , ic_wanted = wanteds , ic_info = info , ic_status = status , ic_env = env }) | IC_Solved {} <- status = return (emptyCts, Just imp) -- Do nothing | otherwise -- Even for IC_Insoluble it is worth doing more work -- The insoluble stuff might be in one sub-implication -- and other unsolved goals in another; and we want to -- solve the latter as much as possible = do { inerts <- getTcSInerts ; traceTcS "solveImplication {" (ppr imp $$ text "Inerts" <+> ppr inerts) -- Solve the nested constraints ; (no_given_eqs, given_insols, residual_wanted) <- nestImplicTcS ev_binds tclvl $ do { given_insols <- solveSimpleGivens (mkGivenLoc tclvl info env) givens ; no_eqs <- getNoGivenEqs tclvl skols ; residual_wanted <- solveWanteds wanteds -- solveWanteds, *not* solveWantedsAndDrop, because -- we want to retain derived equalities so we can float -- them out in floatEqualities ; return (no_eqs, given_insols, residual_wanted) } ; (floated_eqs, residual_wanted) <- floatEqualities skols no_given_eqs residual_wanted ; traceTcS "solveImplication 2" (ppr given_insols $$ ppr residual_wanted) ; let final_wanted = residual_wanted `addInsols` given_insols ; res_implic <- setImplicationStatus (imp { ic_no_eqs = no_given_eqs , ic_wanted = final_wanted }) ; evbinds <- getTcEvBindsMap ; traceTcS "solveImplication end }" $ vcat [ text "no_given_eqs =" <+> ppr no_given_eqs , text "floated_eqs =" <+> ppr floated_eqs , text "res_implic =" <+> ppr res_implic , text "implication evbinds = " <+> ppr (evBindMapBinds evbinds) ] ; return (floated_eqs, res_implic) } ---------------------- setImplicationStatus :: Implication -> TcS (Maybe Implication) -- Finalise the implication returned from solveImplication: -- * Set the ic_status field -- * Trim the ic_wanted field to remove Derived constraints -- Return Nothing if we can discard the implication altogether setImplicationStatus implic@(Implic { ic_binds = EvBindsVar ev_binds_var _ , ic_info = info , ic_tclvl = tc_lvl , ic_wanted = wc , ic_given = givens }) | some_insoluble = return $ Just $ implic { ic_status = IC_Insoluble , ic_wanted = wc { wc_simple = pruned_simples , wc_insol = pruned_insols } } | some_unsolved = return $ Just $ implic { ic_status = IC_Unsolved , ic_wanted = wc { wc_simple = pruned_simples , wc_insol = pruned_insols } } | otherwise -- Everything is solved; look at the implications -- See Note [Tracking redundant constraints] = do { ev_binds <- TcS.readTcRef ev_binds_var ; let all_needs = neededEvVars ev_binds implic_needs dead_givens | warnRedundantGivens info = filterOut (`elemVarSet` all_needs) givens | otherwise = [] -- None to report final_needs = all_needs `delVarSetList` givens discard_entire_implication -- Can we discard the entire implication? = null dead_givens -- No warning from this implication && isEmptyBag pruned_implics -- No live children && isEmptyVarSet final_needs -- No needed vars to pass up to parent final_status = IC_Solved { ics_need = final_needs , ics_dead = dead_givens } final_implic = implic { ic_status = final_status , ic_wanted = wc { wc_simple = pruned_simples , wc_insol = pruned_insols , wc_impl = pruned_implics } } -- We can only prune the child implications (pruned_implics) -- in the IC_Solved status case, because only then we can -- accumulate their needed evidence variales into the -- IC_Solved final_status field of the parent implication. ; return $ if discard_entire_implication then Nothing else Just final_implic } where WC { wc_simple = simples, wc_impl = implics, wc_insol = insols } = wc some_insoluble = insolubleWC tc_lvl wc some_unsolved = not (isEmptyBag simples && isEmptyBag insols) || isNothing mb_implic_needs pruned_simples = dropDerivedSimples simples pruned_insols = dropDerivedInsols insols pruned_implics = filterBag need_to_keep_implic implics mb_implic_needs :: Maybe VarSet -- Just vs => all implics are IC_Solved, with 'vs' needed -- Nothing => at least one implic is not IC_Solved mb_implic_needs = foldrBag add_implic (Just emptyVarSet) implics Just implic_needs = mb_implic_needs add_implic implic acc | Just vs_acc <- acc , IC_Solved { ics_need = vs } <- ic_status implic = Just (vs `unionVarSet` vs_acc) | otherwise = Nothing need_to_keep_implic ic | IC_Solved { ics_dead = [] } <- ic_status ic -- Fully solved, and no redundant givens to report , isEmptyBag (wc_impl (ic_wanted ic)) -- And no children that might have things to report = False | otherwise = True warnRedundantGivens :: SkolemInfo -> Bool warnRedundantGivens (SigSkol ctxt _) = case ctxt of FunSigCtxt _ warn_redundant -> warn_redundant ExprSigCtxt -> True _ -> False -- To think about: do we want to report redundant givens for -- pattern synonyms, PatSynCtxt? c.f Trac #9953, comment:21. warnRedundantGivens (InstSkol {}) = True warnRedundantGivens _ = False neededEvVars :: EvBindMap -> VarSet -> VarSet -- Find all the evidence variables that are "needed", -- and then delete all those bound by the evidence bindings -- A variable is "needed" if -- a) it is free in the RHS of a Wanted EvBind (add_wanted), -- b) it is free in the RHS of an EvBind whose LHS is needed (transClo), -- c) it is in the ic_need_evs of a nested implication (initial_seeds) -- (after removing the givens). neededEvVars ev_binds initial_seeds = needed `minusVarSet` bndrs where seeds = foldEvBindMap add_wanted initial_seeds ev_binds needed = transCloVarSet also_needs seeds bndrs = foldEvBindMap add_bndr emptyVarSet ev_binds add_wanted :: EvBind -> VarSet -> VarSet add_wanted (EvBind { eb_is_given = is_given, eb_rhs = rhs }) needs | is_given = needs -- Add the rhs vars of the Wanted bindings only | otherwise = evVarsOfTerm rhs `unionVarSet` needs also_needs :: VarSet -> VarSet also_needs needs = foldVarSet add emptyVarSet needs where add v needs | Just ev_bind <- lookupEvBind ev_binds v , EvBind { eb_is_given = is_given, eb_rhs = rhs } <- ev_bind , is_given = evVarsOfTerm rhs `unionVarSet` needs | otherwise = needs add_bndr :: EvBind -> VarSet -> VarSet add_bndr (EvBind { eb_lhs = v }) vs = extendVarSet vs v {- Note [Tracking redundant constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With Opt_WarnRedundantConstraints, GHC can report which constraints of a type signature (or instance declaration) are redundant, and can be omitted. Here is an overview of how it works: ----- What is a redundant constraint? * The things that can be redundant are precisely the Given constraints of an implication. * A constraint can be redundant in two different ways: a) It is implied by other givens. E.g. f :: (Eq a, Ord a) => blah -- Eq a unnecessary g :: (Eq a, a~b, Eq b) => blah -- Either Eq a or Eq b unnecessary b) It is not needed by the Wanted constraints covered by the implication E.g. f :: Eq a => a -> Bool f x = True -- Equality not used * To find (a), when we have two Given constraints, we must be careful to drop the one that is a naked variable (if poss). So if we have f :: (Eq a, Ord a) => blah then we may find [G] sc_sel (d1::Ord a) :: Eq a [G] d2 :: Eq a We want to discard d2 in favour of the superclass selection from the Ord dictionary. This is done by TcInteract.solveOneFromTheOther See Note [Replacement vs keeping]. * To find (b) we need to know which evidence bindings are 'wanted'; hence the eb_is_given field on an EvBind. ----- How tracking works * When the constraint solver finishes solving all the wanteds in an implication, it sets its status to IC_Solved - The ics_dead field, of IC_Solved, records the subset of this implication's ic_given that are redundant (not needed). - The ics_need field of IC_Solved then records all the in-scope (given) evidence variables bound by the context, that were needed to solve this implication, including all its nested implications. (We remove the ic_given of this implication from the set, of course.) * We compute which evidence variables are needed by an implication in setImplicationStatus. A variable is needed if a) it is free in the RHS of a Wanted EvBind, b) it is free in the RHS of an EvBind whose LHS is needed, c) it is in the ics_need of a nested implication. * We need to be careful not to discard an implication prematurely, even one that is fully solved, because we might thereby forget which variables it needs, and hence wrongly report a constraint as redundant. But we can discard it once its free vars have been incorporated into its parent; or if it simply has no free vars. This careful discarding is also handled in setImplicationStatus. ----- Reporting redundant constraints * TcErrors does the actual warning, in warnRedundantConstraints. * We don't report redundant givens for *every* implication; only for those which reply True to TcSimplify.warnRedundantGivens: - For example, in a class declaration, the default method *can* use the class constraint, but it certainly doesn't *have* to, and we don't want to report an error there. - More subtly, in a function definition f :: (Ord a, Ord a, Ix a) => a -> a f x = rhs we do an ambiguity check on the type (which would find that one of the Ord a constraints was redundant), and then we check that the definition has that type (which might find that both are redundant). We don't want to report the same error twice, so we disable it for the ambiguity check. Hence using two different FunSigCtxts, one with the warn-redundant field set True, and the other set False in - TcBinds.tcSpecPrag - TcBinds.tcTySig This decision is taken in setImplicationStatus, rather than TcErrors so that we can discard implication constraints that we don't need. So ics_dead consists only of the *reportable* redundant givens. ----- Shortcomings Consider (see Trac #9939) f2 :: (Eq a, Ord a) => a -> a -> Bool -- Ord a redundant, but Eq a is reported f2 x y = (x == y) We report (Eq a) as redundant, whereas actually (Ord a) is. But it's really not easy to detect that! Note [Cutting off simpl_loop] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is very important not to iterate in simpl_loop unless there is a chance of progress. Trac #8474 is a classic example: * There's a deeply-nested chain of implication constraints. ?x:alpha => ?y1:beta1 => ... ?yn:betan => [W] ?x:Int * From the innermost one we get a [D] alpha ~ Int, but alpha is untouchable until we get out to the outermost one * We float [D] alpha~Int out (it is in floated_eqs), but since alpha is untouchable, the solveInteract in simpl_loop makes no progress * So there is no point in attempting to re-solve ?yn:betan => [W] ?x:Int because we'll just get the same [D] again * If we *do* re-solve, we'll get an ininite loop. It is cut off by the fixed bound of 10, but solving the next takes 10*10*...*10 (ie exponentially many) iterations! Conclusion: we should iterate simpl_loop iff we will get more 'givens' in the inert set when solving the nested implications. That is the result of prepareInertsForImplications is larger. How can we tell this? Consider floated_eqs (all wanted or derived): (a) [W/D] CTyEqCan (a ~ ty). This can give rise to a new given only by causing a unification. So we count those unifications. (b) [W] CFunEqCan (F tys ~ xi). Even though these are wanted, they are pushed in as givens by prepareInertsForImplications. See Note [Preparing inert set for implications] in TcSMonad. But because of that very fact, we won't generate another copy if we iterate simpl_loop. So we iterate if there any of these -} promoteTyVar :: TcLevel -> TcTyVar -> TcS TcTyVar -- When we float a constraint out of an implication we must restore -- invariant (MetaTvInv) in Note [TcLevel and untouchable type variables] in TcType -- See Note [Promoting unification variables] promoteTyVar tclvl tv | isFloatedTouchableMetaTyVar tclvl tv = do { cloned_tv <- TcS.cloneMetaTyVar tv ; let rhs_tv = setMetaTyVarTcLevel cloned_tv tclvl ; unifyTyVar tv (mkTyVarTy rhs_tv) ; return rhs_tv } | otherwise = return tv promoteAndDefaultTyVar :: TcLevel -> TcTyVarSet -> TcTyVar -> TcS TcTyVar -- See Note [Promote _and_ default when inferring] promoteAndDefaultTyVar tclvl gbl_tvs tv = do { tv1 <- if tv `elemVarSet` gbl_tvs then return tv else defaultTyVar tv ; promoteTyVar tclvl tv1 } defaultTyVar :: TcTyVar -> TcS TcTyVar -- Precondition: MetaTyVars only -- See Note [DefaultTyVar] defaultTyVar the_tv | Just default_k <- defaultKind_maybe (tyVarKind the_tv) = do { tv' <- TcS.cloneMetaTyVar the_tv ; let new_tv = setTyVarKind tv' default_k ; traceTcS "defaultTyVar" (ppr the_tv <+> ppr new_tv) ; unifyTyVar the_tv (mkTyVarTy new_tv) ; return new_tv } -- Why not directly derived_pred = mkTcEqPred k default_k? -- See Note [DefaultTyVar] -- We keep the same TcLevel on tv' | otherwise = return the_tv -- The common case approximateWC :: WantedConstraints -> Cts -- Postcondition: Wanted or Derived Cts -- See Note [ApproximateWC] approximateWC wc = float_wc emptyVarSet wc where float_wc :: TcTyVarSet -> WantedConstraints -> Cts float_wc trapping_tvs (WC { wc_simple = simples, wc_impl = implics }) = filterBag is_floatable simples `unionBags` do_bag (float_implic new_trapping_tvs) implics where is_floatable ct = tyVarsOfCt ct `disjointVarSet` new_trapping_tvs new_trapping_tvs = transCloVarSet grow trapping_tvs grow :: VarSet -> VarSet -- Maps current trapped tyvars to newly-trapped ones grow so_far = foldrBag (grow_one so_far) emptyVarSet simples grow_one so_far ct tvs | ct_tvs `intersectsVarSet` so_far = tvs `unionVarSet` ct_tvs | otherwise = tvs where ct_tvs = tyVarsOfCt ct float_implic :: TcTyVarSet -> Implication -> Cts float_implic trapping_tvs imp | ic_no_eqs imp -- No equalities, so float = float_wc new_trapping_tvs (ic_wanted imp) | otherwise -- Don't float out of equalities = emptyCts -- See Note [ApproximateWC] where new_trapping_tvs = trapping_tvs `extendVarSetList` ic_skols imp do_bag :: (a -> Bag c) -> Bag a -> Bag c do_bag f = foldrBag (unionBags.f) emptyBag {- Note [ApproximateWC] ~~~~~~~~~~~~~~~~~~~~ approximateWC takes a constraint, typically arising from the RHS of a let-binding whose type we are *inferring*, and extracts from it some *simple* constraints that we might plausibly abstract over. Of course the top-level simple constraints are plausible, but we also float constraints out from inside, if they are not captured by skolems. The same function is used when doing type-class defaulting (see the call to applyDefaultingRules) to extract constraints that that might be defaulted. There are two caveats: 1. We do *not* float anything out if the implication binds equality constraints, because that defeats the OutsideIn story. Consider data T a where TInt :: T Int MkT :: T a f TInt = 3::Int We get the implication (a ~ Int => res ~ Int), where so far we've decided f :: T a -> res We don't want to float (res~Int) out because then we'll infer f :: T a -> Int which is only on of the possible types. (GHC 7.6 accidentally *did* float out of such implications, which meant it would happily infer non-principal types.) 2. We do not float out an inner constraint that shares a type variable (transitively) with one that is trapped by a skolem. Eg forall a. F a ~ beta, Integral beta We don't want to float out (Integral beta). Doing so would be bad when defaulting, because then we'll default beta:=Integer, and that makes the error message much worse; we'd get Can't solve F a ~ Integer rather than Can't solve Integral (F a) Moreover, floating out these "contaminated" constraints doesn't help when generalising either. If we generalise over (Integral b), we still can't solve the retained implication (forall a. F a ~ b). Indeed, arguably that too would be a harder error to understand. Note [DefaultTyVar] ~~~~~~~~~~~~~~~~~~~ defaultTyVar is used on any un-instantiated meta type variables to default the kind of OpenKind and ArgKind etc to *. This is important to ensure that instance declarations match. For example consider instance Show (a->b) foo x = show (\_ -> True) Then we'll get a constraint (Show (p ->q)) where p has kind ArgKind, and that won't match the typeKind (*) in the instance decl. See tests tc217 and tc175. We look only at touchable type variables. No further constraints are going to affect these type variables, so it's time to do it by hand. However we aren't ready to default them fully to () or whatever, because the type-class defaulting rules have yet to run. An important point is that if the type variable tv has kind k and the default is default_k we do not simply generate [D] (k ~ default_k) because: (1) k may be ArgKind and default_k may be * so we will fail (2) We need to rewrite all occurrences of the tv to be a type variable with the right kind and we choose to do this by rewriting the type variable /itself/ by a new variable which does have the right kind. Note [Promote _and_ default when inferring] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we are inferring a type, we simplify the constraint, and then use approximateWC to produce a list of candidate constraints. Then we MUST a) Promote any meta-tyvars that have been floated out by approximateWC, to restore invariant (MetaTvInv) described in Note [TcLevel and untouchable type variables] in TcType. b) Default the kind of any meta-tyyvars that are not mentioned in in the environment. To see (b), suppose the constraint is (C ((a :: OpenKind) -> Int)), and we have an instance (C ((x:*) -> Int)). The instance doesn't match -- but it should! If we don't solve the constraint, we'll stupidly quantify over (C (a->Int)) and, worse, in doing so zonkQuantifiedTyVar will quantify over (b:*) instead of (a:OpenKind), which can lead to disaster; see Trac #7332. Trac #7641 is a simpler example. Note [Promoting unification variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we float an equality out of an implication we must "promote" free unification variables of the equality, in order to maintain Invariant (MetaTvInv) from Note [TcLevel and untouchable type variables] in TcType. for the leftover implication. This is absolutely necessary. Consider the following example. We start with two implications and a class with a functional dependency. class C x y | x -> y instance C [a] [a] (I1) [untch=beta]forall b. 0 => F Int ~ [beta] (I2) [untch=beta]forall c. 0 => F Int ~ [[alpha]] /\ C beta [c] We float (F Int ~ [beta]) out of I1, and we float (F Int ~ [[alpha]]) out of I2. They may react to yield that (beta := [alpha]) which can then be pushed inwards the leftover of I2 to get (C [alpha] [a]) which, using the FunDep, will mean that (alpha := a). In the end we will have the skolem 'b' escaping in the untouchable beta! Concrete example is in indexed_types/should_fail/ExtraTcsUntch.hs: class C x y | x -> y where op :: x -> y -> () instance C [a] [a] type family F a :: * h :: F Int -> () h = undefined data TEx where TEx :: a -> TEx f (x::beta) = let g1 :: forall b. b -> () g1 _ = h [x] g2 z = case z of TEx y -> (h [[undefined]], op x [y]) in (g1 '3', g2 undefined) Note [Solving Family Equations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ After we are done with simplification we may be left with constraints of the form: [Wanted] F xis ~ beta If 'beta' is a touchable unification variable not already bound in the TyBinds then we'd like to create a binding for it, effectively "defaulting" it to be 'F xis'. When is it ok to do so? 1) 'beta' must not already be defaulted to something. Example: [Wanted] F Int ~ beta <~ Will default [beta := F Int] [Wanted] F Char ~ beta <~ Already defaulted, can't default again. We have to report this as unsolved. 2) However, we must still do an occurs check when defaulting (F xis ~ beta), to set [beta := F xis] only if beta is not among the free variables of xis. 3) Notice that 'beta' can't be bound in ty binds already because we rewrite RHS of type family equations. See Inert Set invariants in TcInteract. This solving is now happening during zonking, see Note [Unflattening while zonking] in TcMType. ********************************************************************************* * * * Floating equalities * * * ********************************************************************************* Note [Float Equalities out of Implications] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For ordinary pattern matches (including existentials) we float equalities out of implications, for instance: data T where MkT :: Eq a => a -> T f x y = case x of MkT _ -> (y::Int) We get the implication constraint (x::T) (y::alpha): forall a. [untouchable=alpha] Eq a => alpha ~ Int We want to float out the equality into a scope where alpha is no longer untouchable, to solve the implication! But we cannot float equalities out of implications whose givens may yield or contain equalities: data T a where T1 :: T Int T2 :: T Bool T3 :: T a h :: T a -> a -> Int f x y = case x of T1 -> y::Int T2 -> y::Bool T3 -> h x y We generate constraint, for (x::T alpha) and (y :: beta): [untouchables = beta] (alpha ~ Int => beta ~ Int) -- From 1st branch [untouchables = beta] (alpha ~ Bool => beta ~ Bool) -- From 2nd branch (alpha ~ beta) -- From 3rd branch If we float the equality (beta ~ Int) outside of the first implication and the equality (beta ~ Bool) out of the second we get an insoluble constraint. But if we just leave them inside the implications, we unify alpha := beta and solve everything. Principle: We do not want to float equalities out which may need the given *evidence* to become soluble. Consequence: classes with functional dependencies don't matter (since there is no evidence for a fundep equality), but equality superclasses do matter (since they carry evidence). -} floatEqualities :: [TcTyVar] -> Bool -> WantedConstraints -> TcS (Cts, WantedConstraints) -- Main idea: see Note [Float Equalities out of Implications] -- -- Precondition: the wc_simple of the incoming WantedConstraints are -- fully zonked, so that we can see their free variables -- -- Postcondition: The returned floated constraints (Cts) are only -- Wanted or Derived and come from the input wanted -- ev vars or deriveds -- -- Also performs some unifications (via promoteTyVar), adding to -- monadically-carried ty_binds. These will be used when processing -- floated_eqs later -- -- Subtleties: Note [Float equalities from under a skolem binding] -- Note [Skolem escape] floatEqualities skols no_given_eqs wanteds@(WC { wc_simple = simples }) | not no_given_eqs -- There are some given equalities, so don't float = return (emptyBag, wanteds) -- Note [Float Equalities out of Implications] | otherwise = do { outer_tclvl <- TcS.getTcLevel ; mapM_ (promoteTyVar outer_tclvl) (varSetElems (tyVarsOfCts float_eqs)) -- See Note [Promoting unification variables] ; traceTcS "floatEqualities" (vcat [ text "Skols =" <+> ppr skols , text "Simples =" <+> ppr simples , text "Floated eqs =" <+> ppr float_eqs ]) ; return (float_eqs, wanteds { wc_simple = remaining_simples }) } where skol_set = mkVarSet skols (float_eqs, remaining_simples) = partitionBag (usefulToFloat is_useful) simples is_useful pred = tyVarsOfType pred `disjointVarSet` skol_set usefulToFloat :: (TcPredType -> Bool) -> Ct -> Bool usefulToFloat is_useful_pred ct -- The constraint is un-flattened and de-canonicalised = is_meta_var_eq pred && is_useful_pred pred where pred = ctPred ct -- Float out alpha ~ ty, or ty ~ alpha -- which might be unified outside -- See Note [Which equalities to float] is_meta_var_eq pred | EqPred NomEq ty1 ty2 <- classifyPredType pred = case (tcGetTyVar_maybe ty1, tcGetTyVar_maybe ty2) of (Just tv1, _) -> float_tv_eq tv1 ty2 (_, Just tv2) -> float_tv_eq tv2 ty1 _ -> False | otherwise = False float_tv_eq tv1 ty2 -- See Note [Which equalities to float] = isMetaTyVar tv1 && typeKind ty2 `isSubKind` tyVarKind tv1 && (not (isSigTyVar tv1) || isTyVarTy ty2) {- Note [Float equalities from under a skolem binding] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Which of the simple equalities can we float out? Obviously, only ones that don't mention the skolem-bound variables. But that is over-eager. Consider [2] forall a. F a beta[1] ~ gamma[2], G beta[1] gamma[2] ~ Int The second constraint doesn't mention 'a'. But if we float it, we'll promote gamma[2] to gamma'[1]. Now suppose that we learn that beta := Bool, and F a Bool = a, and G Bool _ = Int. Then we'll we left with the constraint [2] forall a. a ~ gamma'[1] which is insoluble because gamma became untouchable. Solution: float only constraints that stand a jolly good chance of being soluble simply by being floated, namely ones of form a ~ ty where 'a' is a currently-untouchable unification variable, but may become touchable by being floated (perhaps by more than one level). We had a very complicated rule previously, but this is nice and simple. (To see the notes, look at this Note in a version of TcSimplify prior to Oct 2014). Note [Which equalities to float] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Which equalities should we float? We want to float ones where there is a decent chance that floating outwards will allow unification to happen. In particular: Float out equalities of form (alpaha ~ ty) or (ty ~ alpha), where * alpha is a meta-tyvar. * And the equality is kind-compatible e.g. Consider (alpha:*) ~ (s:*->*) From this we already get a Derived insoluble equality. If we floated it, we'll get *another* Derived insoluble equality one level out, so the same error will be reported twice. * And 'alpha' is not a SigTv with 'ty' being a non-tyvar. In that case, floating out won't help either, and it may affect grouping of error messages. Note [Skolem escape] ~~~~~~~~~~~~~~~~~~~~ You might worry about skolem escape with all this floating. For example, consider [2] forall a. (a ~ F beta[2] delta, Maybe beta[2] ~ gamma[1]) The (Maybe beta ~ gamma) doesn't mention 'a', so we float it, and solve with gamma := beta. But what if later delta:=Int, and F b Int = b. Then we'd get a ~ beta[2], and solve to get beta:=a, and now the skolem has escaped! But it's ok: when we float (Maybe beta[2] ~ gamma[1]), we promote beta[2] to beta[1], and that means the (a ~ beta[1]) will be stuck, as it should be. ********************************************************************************* * * * Defaulting and disamgiguation * * * ********************************************************************************* -} applyDefaultingRules :: WantedConstraints -> TcS Bool -- True <=> I did some defaulting, by unifying a meta-tyvar -- Imput WantedConstraints are not necessarily zonked applyDefaultingRules wanteds | isEmptyWC wanteds = return False | otherwise = do { info@(default_tys, _) <- getDefaultInfo ; wanteds <- TcS.zonkWC wanteds ; let groups = findDefaultableGroups info wanteds ; traceTcS "applyDefaultingRules {" $ vcat [ text "wanteds =" <+> ppr wanteds , text "groups =" <+> ppr groups , text "info =" <+> ppr info ] ; something_happeneds <- mapM (disambigGroup default_tys) groups ; traceTcS "applyDefaultingRules }" (ppr something_happeneds) ; return (or something_happeneds) } findDefaultableGroups :: ( [Type] , (Bool,Bool) ) -- (Overloaded strings, extended default rules) -> WantedConstraints -- Unsolved (wanted or derived) -> [(TyVar, [Ct])] findDefaultableGroups (default_tys, (ovl_strings, extended_defaults)) wanteds | null default_tys = [] | otherwise = [ (tv, map fstOf3 group) | group@((_,_,tv):_) <- unary_groups , defaultable_tyvar tv , defaultable_classes (map sndOf3 group) ] where simples = approximateWC wanteds (unaries, non_unaries) = partitionWith find_unary (bagToList simples) unary_groups = equivClasses cmp_tv unaries unary_groups :: [[(Ct, Class, TcTyVar)]] -- (C tv) constraints unaries :: [(Ct, Class, TcTyVar)] -- (C tv) constraints non_unaries :: [Ct] -- and *other* constraints -- Finds unary type-class constraints -- But take account of polykinded classes like Typeable, -- which may look like (Typeable * (a:*)) (Trac #8931) find_unary cc | Just (cls,tys) <- getClassPredTys_maybe (ctPred cc) , Just (kinds, ty) <- snocView tys -- Ignore kind arguments , all isKind kinds -- for this purpose , Just tv <- tcGetTyVar_maybe ty , isMetaTyVar tv -- We might have runtime-skolems in GHCi, and -- we definitely don't want to try to assign to those! = Left (cc, cls, tv) find_unary cc = Right cc -- Non unary or non dictionary bad_tvs :: TcTyVarSet -- TyVars mentioned by non-unaries bad_tvs = mapUnionVarSet tyVarsOfCt non_unaries cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2 defaultable_tyvar tv = let b1 = isTyConableTyVar tv -- Note [Avoiding spurious errors] b2 = not (tv `elemVarSet` bad_tvs) in b1 && b2 defaultable_classes clss | extended_defaults = any isInteractiveClass clss | otherwise = all is_std_class clss && (any is_num_class clss) -- In interactive mode, or with -XExtendedDefaultRules, -- we default Show a to Show () to avoid graututious errors on "show []" isInteractiveClass cls = is_num_class cls || (classKey cls `elem` [showClassKey, eqClassKey , ordClassKey, foldableClassKey , traversableClassKey]) is_num_class cls = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey)) -- is_num_class adds IsString to the standard numeric classes, -- when -foverloaded-strings is enabled is_std_class cls = isStandardClass cls || (ovl_strings && (cls `hasKey` isStringClassKey)) -- Similarly is_std_class ------------------------------ disambigGroup :: [Type] -- The default types -> (TcTyVar, [Ct]) -- All classes of the form (C a) -- sharing same type variable -> TcS Bool -- True <=> something happened, reflected in ty_binds disambigGroup [] _ = return False disambigGroup (default_ty:default_tys) group@(the_tv, wanteds) = do { traceTcS "disambigGroup {" (vcat [ ppr default_ty, ppr the_tv, ppr wanteds ]) ; fake_ev_binds_var <- TcS.newTcEvBinds ; tclvl <- TcS.getTcLevel ; success <- nestImplicTcS fake_ev_binds_var (pushTcLevel tclvl) try_group ; if success then -- Success: record the type variable binding, and return do { unifyTyVar the_tv default_ty ; wrapWarnTcS $ warnDefaulting wanteds default_ty ; traceTcS "disambigGroup succeeded }" (ppr default_ty) ; return True } else -- Failure: try with the next type do { traceTcS "disambigGroup failed, will try other default types }" (ppr default_ty) ; disambigGroup default_tys group } } where try_group | Just subst <- mb_subst = do { lcl_env <- TcS.getLclEnv ; let loc = CtLoc { ctl_origin = GivenOrigin UnkSkol , ctl_env = lcl_env , ctl_depth = initialSubGoalDepth } ; wanted_evs <- mapM (newWantedEvVarNC loc . substTy subst . ctPred) wanteds ; residual_wanted <- solveSimpleWanteds $ listToBag $ map mkNonCanonical wanted_evs ; return (isEmptyWC residual_wanted) } | otherwise = return False tmpl_tvs = extendVarSet (tyVarsOfType (tyVarKind the_tv)) the_tv mb_subst = tcMatchTy tmpl_tvs (mkTyVarTy the_tv) default_ty -- Make sure the kinds match too; hence this call to tcMatchTy -- E.g. suppose the only constraint was (Typeable k (a::k)) -- With the addition of polykinded defaulting we also want to reject -- ill-kinded defaulting attempts like (Eq []) or (Foldable Int) here. {- Note [Avoiding spurious errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When doing the unification for defaulting, we check for skolem type variables, and simply don't default them. For example: f = (*) -- Monomorphic g :: Num a => a -> a g x = f x x Here, we get a complaint when checking the type signature for g, that g isn't polymorphic enough; but then we get another one when dealing with the (Num a) context arising from f's definition; we try to unify a with Int (to default it), but find that it's already been unified with the rigid variable from g's type sig. -}
AlexanderPankiv/ghc
compiler/typecheck/TcSimplify.hs
bsd-3-clause
81,946
1
19
22,678
7,858
4,147
3,711
623
5