code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Napm.Types( Domain(..) , PasswordLength(..) , Passphrase(..) , ContextMap ) where import Control.Applicative import Data.Map (Map) import Data.Text (Text) import qualified Data.Text as T import Test.QuickCheck -- FIXME: unicode text :: Gen Text text = fmap T.pack $ listOf1 textChar where textChar = elements . concat $ [ ['a'..'z'] , ['A'..'Z'] , ['0'..'9'] , [' '..'/'] ] {- Password domain/textual context, e.g., "bob@example.com". Mostly-freeform, but can't contain whitespace or colons (':'). -} newtype Domain = Domain { unDomain :: Text } deriving (Eq, Show, Ord) -- FIXME: unicode instance Arbitrary Domain where arbitrary = Domain <$> text {- Length of a generated password. -} newtype PasswordLength = PasswordLength { unPasswordLength :: Int } deriving (Eq, Show, Ord, Num) instance Arbitrary PasswordLength where arbitrary = PasswordLength <$> positive where positive = arbitrary `suchThat` (\l -> l > 0 && l <= 64) newtype Passphrase = Passphrase { unPassphrase :: Text } deriving (Eq, Show, Ord) instance Arbitrary Passphrase where arbitrary = Passphrase <$> text {- The context in which passwords are generated. Consists of a password domain/textual context that's not secret and easy for the user to remember (hostname, URL, whatever), plus the length of the generated password. Revealing a context should not compromise the password, but they're considered non-public. -} type ContextMap = Map Domain PasswordLength
fractalcat/napm
lib/Napm/Types.hs
Haskell
mit
1,750
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>Passive Scan Rules - Beta | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Индекс</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Поиск</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/pscanrulesBeta/src/main/javahelp/org/zaproxy/zap/extension/pscanrulesBeta/resources/help_ru_RU/helpset_ru_RU.hs
Haskell
apache-2.0
998
#!/usr/bin/env runhaskell {-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-} {-# OPTIONS -Wall #-} import Data.Dynamic import Data.Tensor.TypeLevel import qualified Data.Text.IO as T import Language.Paraiso.Annotation (Annotation) import Language.Paraiso.Generator (generateIO) import qualified Language.Paraiso.Generator.Native as Native import Language.Paraiso.Name import Language.Paraiso.OM import Language.Paraiso.OM.Builder import Language.Paraiso.OM.DynValue as DVal import Language.Paraiso.OM.PrettyPrint import Language.Paraiso.OM.Realm import qualified Language.Paraiso.OM.Reduce as Reduce import Language.Paraiso.Optimization import NumericPrelude import System.Process (system) bind :: (Monad m, Functor m) => m a -> m (m a) bind = fmap return initialize :: Builder Vec1 Int Annotation () initialize = do i <- bind $ loadIndex (0::Double) $ Axis 0 n <- bind $ loadSize TLocal (0::Double) $ Axis 0 x <- bind $ 2 * pi / n * (i + 0.5) store fieldF $ sin(x) store fieldG $ cos(3*x) proceed :: Builder Vec1 Int Annotation () proceed = do c <- bind $ imm 3.43 n <- bind $ loadSize TLocal (0::Double) $ Axis 0 f0 <- bind $ load TLocal (0::Double) $ fieldF g0 <- bind $ load TLocal (0::Double) $ fieldG dx <- bind $ 2 * pi / n dt <- bind $ dx / c f1 <- bind $ f0 + dt * g0 fR <- bind $ shift (Vec:~ -1) f1 fL <- bind $ shift (Vec:~ 1) f1 g1 <- bind $ g0 + dt * c^2 / dx^2 * (fL + fR - 2 * f1) store fieldF f1 store fieldG g1 dfdx <- bind $ (fR - fL) / (2*dx) store energy $ reduce Reduce.Sum $ 0.5 * (c^2 * dfdx^2 + ((g0+g1)/2)^2) * dx fieldF, fieldG, energy :: Name fieldF = mkName "fieldF" fieldG = mkName "fieldG" energy = mkName "energy" myVars :: [Named DynValue] myVars = [Named fieldF DynValue{DVal.realm = Local, typeRep = typeOf (0::Double)}, Named fieldG DynValue{DVal.realm = Local, typeRep = typeOf (0::Double)}, Named energy DynValue{DVal.realm = Global, typeRep = typeOf (0::Double)} ] myOM :: OM Vec1 Int Annotation myOM = optimize O3 $ makeOM (mkName "LinearWave") [] myVars [(mkName "initialize", initialize), (mkName "proceed", proceed)] mySetup :: Int -> Native.Setup Vec1 Int mySetup n = (Native.defaultSetup $ Vec :~ n) { Native.directory = "./dist/" } mainTest :: Int -> IO () mainTest n = do _ <- system "mkdir -p output" T.writeFile "output/OM.txt" $ prettyPrintA1 $ myOM _ <- generateIO (mySetup n) myOM _ <- system "make" _ <- system "./a.out" return () main :: IO () main = mapM_ mainTest $ concat $ [[2*2^n, 3*2^n]| n <- [2..10]]
drmaruyama/Paraiso
examples-old/LinearWave/Convergence.hs
Haskell
bsd-3-clause
2,761
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {- | Module : Verifier.SAW.Prelude Copyright : Galois, Inc. 2012-2015 License : BSD3 Maintainer : jhendrix@galois.com Stability : experimental Portability : non-portable (language extensions) -} module Verifier.SAW.Prelude ( Module , module Verifier.SAW.Prelude , module Verifier.SAW.Prelude.Constants ) where import qualified Data.Map as Map import Verifier.SAW.ParserUtils import Verifier.SAW.Prelude.Constants import Verifier.SAW.SharedTerm import Verifier.SAW.FiniteValue import Verifier.SAW.Simulator.Concrete (evalSharedTerm) import Verifier.SAW.Simulator.Value (asFirstOrderTypeValue) $(defineModuleFromFileWithFns "preludeModule" "scLoadPreludeModule" "prelude/Prelude.sawcore") -- | Given two terms, compute a term representing a decidable -- equality test between them. The terms are assumed to -- be of the same type, which must be a first-order type. -- The returned term will be of type @Bool@. scEq :: SharedContext -> Term -> Term -> IO Term scEq sc x y = do xty <- scTypeOf sc x mmap <- scGetModuleMap sc case asFirstOrderTypeValue (evalSharedTerm mmap mempty mempty xty) of Just fot -> scDecEq sc fot (Just (x,y)) Nothing -> fail ("scEq: expected first order type, but got: " ++ showTerm xty) -- | Given a first-order type, return the decidable equality -- operation on that type. If arguments are provided, they -- will be applied, returning a value of type @Bool@. If no -- arguments are provided a function of type @tp -> tp -> Bool@ -- will be returned. scDecEq :: SharedContext -> FirstOrderType {- ^ Type of elements to test for equality -} -> Maybe (Term,Term) {- ^ optional arguments to apply -} -> IO Term scDecEq sc fot args = case fot of FOTBit -> do fn <- scGlobalDef sc "Prelude.boolEq" case args of Nothing -> return fn Just (x,y) -> scApplyAll sc fn [x,y] FOTInt -> do fn <- scGlobalDef sc "Prelude.intEq" case args of Nothing -> return fn Just (x,y) -> scApplyAll sc fn [x,y] FOTIntMod m -> do fn <- scGlobalDef sc "Prelude.intModEq" m' <- scNat sc m case args of Nothing -> scApply sc fn m' Just (x,y) -> scApplyAll sc fn [m',x,y] FOTVec w FOTBit -> do fn <- scGlobalDef sc "Prelude.bvEq" w' <- scNat sc w case args of Nothing -> scApply sc fn w' Just (x,y) -> scApplyAll sc fn [w',x,y] FOTVec w t -> do fn <- scGlobalDef sc "Prelude.vecEq" w' <- scNat sc w t' <- scFirstOrderType sc t subFn <- scDecEq sc t Nothing case args of Nothing -> scApplyAll sc fn [w',t',subFn] Just (x,y) -> scApplyAll sc fn [w',t',subFn,x,y] FOTArray a b -> do a' <- scFirstOrderType sc a b' <- scFirstOrderType sc b fn <- scGlobalDef sc "Prelude.arrayEq" case args of Nothing -> scApplyAll sc fn [a',b'] Just (x,y) -> scApplyAll sc fn [a',b',x,y] FOTTuple [] -> case args of Nothing -> scGlobalDef sc "Prelude.unitEq" Just _ -> scBool sc True FOTTuple [t] -> scDecEq sc t args FOTTuple (t:ts) -> do fnLeft <- scDecEq sc t Nothing fnRight <- scDecEq sc (FOTTuple ts) Nothing fn <- scGlobalDef sc "Prelude.pairEq" t' <- scFirstOrderType sc t ts' <- scFirstOrderType sc (FOTTuple ts) case args of Nothing -> scApplyAll sc fn [t',ts',fnLeft,fnRight] Just (x,y) -> scApplyAll sc fn [t',ts',fnLeft,fnRight,x,y] FOTRec fs -> case args of Just (x,y) -> mkRecordEqBody (Map.toList fs) x y Nothing -> do x <- scLocalVar sc 1 y <- scLocalVar sc 0 tp <- scFirstOrderType sc fot body <- mkRecordEqBody (Map.toList fs) x y scLambdaList sc [("x",tp),("y",tp)] body where mkRecordEqBody [] _x _y = scBool sc True mkRecordEqBody [(f,tp)] x y = do xf <- scRecordSelect sc x f yf <- scRecordSelect sc y f scDecEq sc tp (Just (xf,yf)) mkRecordEqBody ((f,tp):fs) x y = do xf <- scRecordSelect sc x f yf <- scRecordSelect sc y f fp <- scDecEq sc tp (Just (xf,yf)) fsp <- mkRecordEqBody fs x y scAnd sc fp fsp -- | For backwards compatibility: @Bool@ used to be a datatype, and so its -- creation function was called @scPrelude_Bool@ instead of -- @scApplyPrelude_Bool@ scPrelude_Bool :: SharedContext -> IO Term scPrelude_Bool = scApplyPrelude_Bool
GaloisInc/saw-script
saw-core/src/Verifier/SAW/Prelude.hs
Haskell
bsd-3-clause
4,624
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[HsLit]{Abstract syntax: source-language literals} -} {-# LANGUAGE CPP, DeriveDataTypeable #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types] -- in module PlaceHolder {-# LANGUAGE ConstraintKinds #-} module HsLit where #include "HsVersions.h" import {-# SOURCE #-} HsExpr( HsExpr, pprExpr ) import BasicTypes ( FractionalLit(..),SourceText ) import Type ( Type ) import Outputable import FastString import PlaceHolder ( PostTc,PostRn,DataId,OutputableBndrId ) import Data.ByteString (ByteString) import Data.Data hiding ( Fixity ) {- ************************************************************************ * * \subsection[HsLit]{Literals} * * ************************************************************************ -} -- Note [Literal source text] in BasicTypes for SourceText fields in -- the following data HsLit = HsChar SourceText Char -- Character | HsCharPrim SourceText Char -- Unboxed character | HsString SourceText FastString -- String | HsStringPrim SourceText ByteString -- Packed bytes | HsInt SourceText Integer -- Genuinely an Int; arises from -- TcGenDeriv, and from TRANSLATION | HsIntPrim SourceText Integer -- literal Int# | HsWordPrim SourceText Integer -- literal Word# | HsInt64Prim SourceText Integer -- literal Int64# | HsWord64Prim SourceText Integer -- literal Word64# | HsInteger SourceText Integer Type -- Genuinely an integer; arises only -- from TRANSLATION (overloaded -- literals are done with HsOverLit) | HsRat FractionalLit Type -- Genuinely a rational; arises only from -- TRANSLATION (overloaded literals are -- done with HsOverLit) | HsFloatPrim FractionalLit -- Unboxed Float | HsDoublePrim FractionalLit -- Unboxed Double deriving Data instance Eq HsLit where (HsChar _ x1) == (HsChar _ x2) = x1==x2 (HsCharPrim _ x1) == (HsCharPrim _ x2) = x1==x2 (HsString _ x1) == (HsString _ x2) = x1==x2 (HsStringPrim _ x1) == (HsStringPrim _ x2) = x1==x2 (HsInt _ x1) == (HsInt _ x2) = x1==x2 (HsIntPrim _ x1) == (HsIntPrim _ x2) = x1==x2 (HsWordPrim _ x1) == (HsWordPrim _ x2) = x1==x2 (HsInt64Prim _ x1) == (HsInt64Prim _ x2) = x1==x2 (HsWord64Prim _ x1) == (HsWord64Prim _ x2) = x1==x2 (HsInteger _ x1 _) == (HsInteger _ x2 _) = x1==x2 (HsRat x1 _) == (HsRat x2 _) = x1==x2 (HsFloatPrim x1) == (HsFloatPrim x2) = x1==x2 (HsDoublePrim x1) == (HsDoublePrim x2) = x1==x2 _ == _ = False data HsOverLit id -- An overloaded literal = OverLit { ol_val :: OverLitVal, ol_rebindable :: PostRn id Bool, -- Note [ol_rebindable] ol_witness :: HsExpr id, -- Note [Overloaded literal witnesses] ol_type :: PostTc id Type } deriving instance (DataId id) => Data (HsOverLit id) -- Note [Literal source text] in BasicTypes for SourceText fields in -- the following data OverLitVal = HsIntegral !SourceText !Integer -- Integer-looking literals; | HsFractional !FractionalLit -- Frac-looking literals | HsIsString !SourceText !FastString -- String-looking literals deriving Data overLitType :: HsOverLit a -> PostTc a Type overLitType = ol_type {- Note [ol_rebindable] ~~~~~~~~~~~~~~~~~~~~ The ol_rebindable field is True if this literal is actually using rebindable syntax. Specifically: False iff ol_witness is the standard one True iff ol_witness is non-standard Equivalently it's True if a) RebindableSyntax is on b) the witness for fromInteger/fromRational/fromString that happens to be in scope isn't the standard one Note [Overloaded literal witnesses] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *Before* type checking, the HsExpr in an HsOverLit is the name of the coercion function, 'fromInteger' or 'fromRational'. *After* type checking, it is a witness for the literal, such as (fromInteger 3) or lit_78 This witness should replace the literal. This dual role is unusual, because we're replacing 'fromInteger' with a call to fromInteger. Reason: it allows commoning up of the fromInteger calls, which wouldn't be possible if the desguarar made the application. The PostTcType in each branch records the type the overload literal is found to have. -} -- Comparison operations are needed when grouping literals -- for compiling pattern-matching (module MatchLit) instance Eq (HsOverLit id) where (OverLit {ol_val = val1}) == (OverLit {ol_val=val2}) = val1 == val2 instance Eq OverLitVal where (HsIntegral _ i1) == (HsIntegral _ i2) = i1 == i2 (HsFractional f1) == (HsFractional f2) = f1 == f2 (HsIsString _ s1) == (HsIsString _ s2) = s1 == s2 _ == _ = False instance Ord (HsOverLit id) where compare (OverLit {ol_val=val1}) (OverLit {ol_val=val2}) = val1 `compare` val2 instance Ord OverLitVal where compare (HsIntegral _ i1) (HsIntegral _ i2) = i1 `compare` i2 compare (HsIntegral _ _) (HsFractional _) = LT compare (HsIntegral _ _) (HsIsString _ _) = LT compare (HsFractional f1) (HsFractional f2) = f1 `compare` f2 compare (HsFractional _) (HsIntegral _ _) = GT compare (HsFractional _) (HsIsString _ _) = LT compare (HsIsString _ s1) (HsIsString _ s2) = s1 `compare` s2 compare (HsIsString _ _) (HsIntegral _ _) = GT compare (HsIsString _ _) (HsFractional _) = GT instance Outputable HsLit where ppr (HsChar _ c) = pprHsChar c ppr (HsCharPrim _ c) = pprPrimChar c ppr (HsString _ s) = pprHsString s ppr (HsStringPrim _ s) = pprHsBytes s ppr (HsInt _ i) = integer i ppr (HsInteger _ i _) = integer i ppr (HsRat f _) = ppr f ppr (HsFloatPrim f) = ppr f <> primFloatSuffix ppr (HsDoublePrim d) = ppr d <> primDoubleSuffix ppr (HsIntPrim _ i) = pprPrimInt i ppr (HsWordPrim _ w) = pprPrimWord w ppr (HsInt64Prim _ i) = pprPrimInt64 i ppr (HsWord64Prim _ w) = pprPrimWord64 w -- in debug mode, print the expression that it's resolved to, too instance (OutputableBndrId id) => Outputable (HsOverLit id) where ppr (OverLit {ol_val=val, ol_witness=witness}) = ppr val <+> (ifPprDebug (parens (pprExpr witness))) instance Outputable OverLitVal where ppr (HsIntegral _ i) = integer i ppr (HsFractional f) = ppr f ppr (HsIsString _ s) = pprHsString s -- | pmPprHsLit pretty prints literals and is used when pretty printing pattern -- match warnings. All are printed the same (i.e., without hashes if they are -- primitive and not wrapped in constructors if they are boxed). This happens -- mainly for too reasons: -- * We do not want to expose their internal representation -- * The warnings become too messy pmPprHsLit :: HsLit -> SDoc pmPprHsLit (HsChar _ c) = pprHsChar c pmPprHsLit (HsCharPrim _ c) = pprHsChar c pmPprHsLit (HsString _ s) = pprHsString s pmPprHsLit (HsStringPrim _ s) = pprHsBytes s pmPprHsLit (HsInt _ i) = integer i pmPprHsLit (HsIntPrim _ i) = integer i pmPprHsLit (HsWordPrim _ w) = integer w pmPprHsLit (HsInt64Prim _ i) = integer i pmPprHsLit (HsWord64Prim _ w) = integer w pmPprHsLit (HsInteger _ i _) = integer i pmPprHsLit (HsRat f _) = ppr f pmPprHsLit (HsFloatPrim f) = ppr f pmPprHsLit (HsDoublePrim d) = ppr d
sgillespie/ghc
compiler/hsSyn/HsLit.hs
Haskell
bsd-3-clause
8,103
-- | Spawn subprocesses and interact with them using "Pipes" -- -- The interface in this module deliberately resembles the interface -- in "System.Process". However, one consequence of this is that you -- will not want to have unqualified names from this module and from -- "System.Process" in scope at the same time. -- -- As in "System.Process", you create a subprocess by creating a -- 'CreateProcess' record and then applying a function to that -- record. Unlike "System.Process", you use functions such as -- 'pipeInput' or 'pipeInputOutput' to specify what streams you want -- to use a 'Proxy' for and what streams you wish to be 'Inherit'ed -- or if you want to 'UseHandle'. You then send or receive -- information using one or more 'Proxy'. -- -- __Use the @-threaded@ GHC option__ when compiling your programs or -- when using GHCi. Internally, this module uses -- 'System.Process.waitForProcess' from the "System.Process" module. -- As the documentation for 'waitForProcess' states, you must use the -- @-threaded@ option to prevent every thread in the system from -- suspending when 'waitForProcess' is used. So, if your program -- experiences deadlocks, be sure you used the @-threaded@ option. -- -- This module relies on the "Pipes", "Pipes.Safe", -- "Control.Concurrent.Async", and "System.Process" modules. You will -- want to have basic familiarity with what all of those modules do -- before using this module. -- -- All communcation with subprocesses is done with strict -- 'ByteString's. If you are dealing with textual data, the @text@ -- library has functions to convert a 'ByteString' to a @Text@; you -- will want to look at @Data.Text.Encoding@. -- -- Nobody would mistake this module for a shell; nothing beats the -- shell as a language for starting other programs, as the shell is -- designed for that. This module allows you to perform simple -- streaming with subprocesses without leaving the comfort of Haskell. -- Take a look at the README.md file, which is distributed with the -- tarball or is available at Github at -- -- <https://github.com/massysett/pipes-cliff> -- -- There you will find references to other libraries that you might -- find more useful than this one. -- -- You will want to consult "Pipes.Cliff.Examples" for some examples -- before getting started. There are some important notes in there -- about how to run pipelines. module Pipes.Cliff ( -- * Specifying a subprocess's properties CmdSpec(..) , NonPipe(..) , CreateProcess(..) , procSpec , squelch -- * Creating processes -- $process , pipeInput , pipeOutput , pipeError , pipeInputOutput , pipeInputError , pipeOutputError , pipeInputOutputError -- * 'Proxy' combinators , conveyor , safeEffect -- * Querying and terminating the process , ProcessHandle , originalCreateProcess , isStillRunning , waitForProcess , terminateProcess -- * Exception safety -- | These are some simple combinators built with -- 'Control.Exception.bracket'; feel free to use your own favorite -- idioms for exception safety. , withProcess , withConveyor -- * Errors and warnings -- | You will only need what's in this section if you want to -- examine errors more closely. , Activity(..) , Outbound(..) , HandleDesc(..) , Oopsie(..) -- * Re-exports -- $reexports , module Control.Concurrent.Async , module Pipes , module Pipes.Safe , module System.Exit -- * Some design notes -- $designNotes ) where import Control.Concurrent.Async import Pipes.Cliff.Core import Pipes import Pipes.Safe (runSafeT) import System.Exit {- $process Each of these functions creates a process. The process begins running immediately in a separate process while your Haskell program continues concurrently. A function is provided for each possible combination of standard input, standard output, and standard error. Use the 'NonPipe' type to describe what you want to do with streams you do NOT want to create a stream for. For example, to create a subprocess that creates a 'Proxy' for standard input and standard output, use 'pipeInputOutput'. You must describe what you want done with standard error. A 'Producer' is returned for standard output and a 'Consumer' for standard input. Each function also returns a 'ProcessHandle'; this is not the same 'ProcessHandle' that you will find in "System.Process". You can use this 'ProcessHandle' to obtain some information about the process that is created and to get the eventual 'ExitCode'. Every time you create a process with one of these functions, some additional behind-the-scenes resources are created, such as some threads to move data to and from the process. In normal usage, these threads will be cleaned up after the process exits. However, if exceptions are thrown, there could be resource leaks. Applying 'terminateProcess' to a 'ProcessHandle' makes a best effort to clean up all the resources that Cliff may create, including the process itself and any additional threads. To guard against resource leaks, use the functions found in "Control.Exception" or in "Control.Monad.Catch". "Control.Monad.Catch" provides operations that are the same as those in "Control.Exception", but they are not limited to 'IO'. I say that 'terminateProcess' \"makes a best effort\" to release resources because in UNIX it merely sends a @SIGTERM@ to the process. That should kill well-behaved processes, but 'terminateProcess' does not send a @SIGKILL@. 'terminateProcess' always closes all handles associated with the process and it kills all Haskell threads that were moving data to and from the process. ('terminateProcess' does not kill threads it does not know about, such as threads you created with 'conveyor'.) There is no function that will create a process that has no 'Proxy' at all. For that, just use 'System.Process.createProcess' in "System.Process". -} {- $reexports * "Control.Concurrent.Async" reexports all bindings * "Pipes" reexports all bindings * "Pipes.Safe" reexports 'runSafeT' * "System.Exit" reexports all bindings -} {- $designNotes Two overarching principles guided the design of this library. First, I wanted the interface to use simple ByteStrings. That most closely represents what a UNIX process sees. If the user wants to use Text or String, it's easy enough to convert between those types and a ByteString. Then the user has to pay explicit attention to encoding issues--as she should, because not all UNIX processes deal with encoded textual data. Second, I paid meticulous attention to resource management. Resources are deterministically destroyed immediately after use. This eliminates many bugs. Even so, I decided to leave it up to the user to use something like 'Control.Exception.bracket' to ensure that all resources are cleaned up if there is an exception. Originally I tried to have the library do this, but that turned out not to be very composable. There are already many exception-handling mechanisms available in "Control.Exception", "Pipes.Safe", and "Control.Monad.Catch", and it seems best to let the user choose how to handle this issue; she can just perform a 'Control.Exception.bracket' and may combine this with the @ContT@ monad in @transformers@ or @mtl@ if she wishes, or perhaps with the @managed@ library. An earlier version of this library (see version 0.8.0.0) tried to use the return value of a 'Proxy' to indicate the return value of both processes in the pipeline, not just one. I removed this because it interfered heavily with composability. You might wonder why, if you are using an external process as a pipeline, why can't you create, well, a 'Pipe'? Wouldn't that be an obvious choice? Well, if such an interface is possible using Pipes in its current incarnation, nobody has figured it out yet. I don't think it's possible. See also <https://groups.google.com/d/msg/haskell-pipes/JFfyquj5HAg/Lxz7p50JOh4J> for a discussion about this. -}
massysett/pipes-cliff
pipes-cliff/lib/Pipes/Cliff.hs
Haskell
bsd-3-clause
7,997
module Reinforce.Agents ( runLearner , clockEpisodes , clockSteps ) where import Control.Monad import Control.Monad.IO.Class import Control.MonadEnv import qualified Control.MonadEnv as Env (reset) runLearner :: MonadEnv m o a r => MonadIO m => Maybe Integer -> Maybe Integer -> (Maybe Integer -> o -> m ()) -> m () runLearner maxEps maxSteps rollout = clockEpisodes maxEps 0 maxSteps rollout clockEpisodes :: forall m o a r . MonadEnv m o a r => Maybe Integer -> Integer -> Maybe Integer -> (Maybe Integer -> o -> m ()) -> m () clockEpisodes maxEps epn maxSteps rollout = do case maxEps of Nothing -> tick Just mx -> unless (epn > mx) tick where tick :: m () tick = Env.reset >>= \case EmptyEpisode -> pure () Initial s -> do rollout maxSteps s clockEpisodes maxEps (epn+1) maxSteps rollout clockSteps :: Monad m => Maybe Integer -> Integer -> (Integer -> m ()) -> m () clockSteps Nothing st tickAct = tickAct st clockSteps (Just mx) st tickAct = unless (st >= mx) (tickAct st)
stites/reinforce
reinforce-algorithms/src/Reinforce/Agents.hs
Haskell
bsd-3-clause
1,073
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Lens.Internal -- Copyright : (C) 2012-16 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : Rank2Types -- -- These are some of the explicit 'Functor' instances that leak into the -- type signatures of @Control.Lens@. You shouldn't need to import this -- module directly for most use-cases. -- ---------------------------------------------------------------------------- module Control.Lens.Internal ( module Control.Lens.Internal.Bazaar , module Control.Lens.Internal.Context , module Control.Lens.Internal.Fold , module Control.Lens.Internal.Getter , module Control.Lens.Internal.Indexed , module Control.Lens.Internal.Iso , module Control.Lens.Internal.Level , module Control.Lens.Internal.Magma , module Control.Lens.Internal.Prism , module Control.Lens.Internal.Review , module Control.Lens.Internal.Setter , module Control.Lens.Internal.Zoom ) where import Control.Lens.Internal.Bazaar import Control.Lens.Internal.Context import Control.Lens.Internal.Fold import Control.Lens.Internal.Getter import Control.Lens.Internal.Indexed import Control.Lens.Internal.Instances () import Control.Lens.Internal.Iso import Control.Lens.Internal.Level import Control.Lens.Internal.Magma import Control.Lens.Internal.Prism import Control.Lens.Internal.Review import Control.Lens.Internal.Setter import Control.Lens.Internal.Zoom #ifdef HLINT {-# ANN module "HLint: ignore Use import/export shortcut" #-} #endif
ddssff/lens
src/Control/Lens/Internal.hs
Haskell
bsd-3-clause
1,676
{-# LANGUAGE OverloadedStrings #-} module Yesod.Form.I18n.English where import Yesod.Form.Types (FormMessage (..)) import Data.Monoid (mappend) import Data.Text (Text) englishFormMessage :: FormMessage -> Text englishFormMessage (MsgInvalidInteger t) = "Invalid integer: " `Data.Monoid.mappend` t englishFormMessage (MsgInvalidNumber t) = "Invalid number: " `mappend` t englishFormMessage (MsgInvalidEntry t) = "Invalid entry: " `mappend` t englishFormMessage MsgInvalidTimeFormat = "Invalid time, must be in HH:MM[:SS] format" englishFormMessage MsgInvalidDay = "Invalid day, must be in YYYY-MM-DD format" englishFormMessage (MsgInvalidUrl t) = "Invalid URL: " `mappend` t englishFormMessage (MsgInvalidEmail t) = "Invalid e-mail address: " `mappend` t englishFormMessage (MsgInvalidHour t) = "Invalid hour: " `mappend` t englishFormMessage (MsgInvalidMinute t) = "Invalid minute: " `mappend` t englishFormMessage (MsgInvalidSecond t) = "Invalid second: " `mappend` t englishFormMessage MsgCsrfWarning = "As a protection against cross-site request forgery attacks, please confirm your form submission." englishFormMessage MsgValueRequired = "Value is required" englishFormMessage (MsgInputNotFound t) = "Input not found: " `mappend` t englishFormMessage MsgSelectNone = "<None>" englishFormMessage (MsgInvalidBool t) = "Invalid boolean: " `mappend` t englishFormMessage MsgBoolYes = "Yes" englishFormMessage MsgBoolNo = "No" englishFormMessage MsgDelete = "Delete?"
s9gf4ult/yesod
yesod-form/Yesod/Form/I18n/English.hs
Haskell
mit
1,469
module RefacGenCache where import TypeCheck import PrettyPrint import PosSyntax import AbstractIO import Data.Maybe import TypedIds import UniqueNames hiding (srcLoc) import PNT import TiPNT import Data.List import RefacUtils hiding (getParams) import PFE0 (findFile, allFiles, allModules) import MUtils (( # )) import RefacLocUtils -- import System import System.IO import Relations import Ents import Data.Set (toList) import Data.List import System.IO.Unsafe import System.Cmd import LocalSettings (genFoldPath) -- allows the selection of a function equation to -- be outputted as AST representation to a file. genFoldCache args = do let fileName = args!!0 begin = read (args!!1)::Int end = read (args!!2)::Int (inscps, exps, mod, tokList) <- parseSourceFile fileName case checkCursor fileName begin end mod of Left errMsg -> do error errMsg Right decl -> do AbstractIO.writeFile genFoldPath (show decl) AbstractIO.putStrLn "refacGenFoldCache" checkCursor :: String -> Int -> Int -> HsModuleP -> Either String HsDeclP checkCursor fileName row col mod = case locToPName of Nothing -> Left ("Invalid cursor position. Please place cursor at the beginning of the definition!") Just decl -> Right decl where locToPName = case res of Nothing -> find (definesPNT (locToPNT fileName (row, col) mod)) (hsDecls mod) _ -> res res = find (defines (locToPN fileName (row, col) mod)) (concat (map hsDecls (hsModDecls mod))) definesPNT pnt d@(Dec (HsPatBind loc p e ds)) = findPNT pnt d definesPNT pnt d@(Dec (HsFunBind loc ms)) = findPNT pnt d definesPNT _ _ = False
kmate/HaRe
old/refactorer/RefacGenCache.hs
Haskell
bsd-3-clause
1,783
{-# NOINLINE f #-} f :: Int -> Int f = {-# SCC f #-} g {-# NOINLINE g #-} g :: Int -> Int g x = {-# SCC g #-} x + 1 main = {-# SCC main #-} return $! f 3
urbanslug/ghc
testsuite/tests/profiling/should_run/scc004.hs
Haskell
bsd-3-clause
157
-- #hide, prune, ignore-exports -- |Module description module A where
siddhanathan/ghc
testsuite/tests/haddock/should_compile_noflag_haddock/haddockC016.hs
Haskell
bsd-3-clause
71
------------------------------------------------------------ -- Card ! Made by Mega Chan ! ------------------------------------------------------------ card_valid :: String -> Bool card_valid str = if ((card_value str) `mod` 10 == 0) then True else False card_value :: String -> Int card_value str = (add_even (map mul_2 (get_arr_even str ((length str) - 2)))) + (add_odd (get_arr_even str ((length str) - 1))) add_odd :: [Int] -> Int add_odd [] = 0 add_odd (x:xs) = x + (add_odd xs) add_even :: [Int] -> Int add_even [] = 0 add_even (x:xs) = (sum_digit x) + (add_even xs) sum_digit :: Int -> Int sum_digit 0 = 0 sum_digit x = (x `mod` 10) + (sum_digit (x `div` 10)) get_arr_even :: String -> Int -> [Int] get_arr_even xs (-1) = [] get_arr_even xs (-2) = [] get_arr_even xs x = (read [(xs!!x)] :: Int) : (get_arr_even xs (x-2)) mul_2 :: Int -> Int mul_2 x = x * 2 -- 下面乱七八糟 -- isValid :: Integer -> Bool isValid x = card_valid (show x) numValid :: [Integer] -> Integer numValid xs = sum . map (\_ -> 1) $ filter isValid xs creditcards :: [Integer] creditcards = [ 4716347184862961, 4532899082537349, 4485429517622493, 4320635998241421, 4929778869082405, 5256283618614517, 5507514403575522, 5191806267524120, 5396452857080331, 5567798501168013, 6011798764103720, 6011970953092861, 6011486447384806, 6011337752144550, 6011442159205994, 4916188093226163, 4916699537435624, 4024607115319476, 4556945538735693, 4532818294886666, 5349308918130507, 5156469512589415, 5210896944802939, 5442782486960998, 5385907818416901, 6011920409800508, 6011978316213975, 6011221666280064, 6011285399268094, 6011111757787451, 4024007106747875, 4916148692391990, 4916918116659358, 4024007109091313, 4716815014741522, 5370975221279675, 5586822747605880, 5446122675080587, 5361718970369004, 5543878863367027, 6011996932510178, 6011475323876084, 6011358905586117, 6011672107152563, 6011660634944997, 4532917110736356, 4485548499291791, 4532098581822262, 4018626753711468, 4454290525773941, 5593710059099297, 5275213041261476, 5244162726358685, 5583726743957726, 5108718020905086, 6011887079002610, 6011119104045333, 6011296087222376, 6011183539053619, 6011067418196187, 4532462702719400, 4420029044272063, 4716494048062261, 4916853817750471, 4327554795485824, 5138477489321723, 5452898762612993, 5246310677063212, 5211257116158320, 5230793016257272, 6011265295282522, 6011034443437754, 6011582769987164, 6011821695998586, 6011420220198992, 4716625186530516, 4485290399115271, 4556449305907296, 4532036228186543, 4916950537496300, 5188481717181072, 5535021441100707, 5331217916806887, 5212754109160056, 5580039541241472, 6011450326200252, 6011141461689343, 6011886911067144, 6011835735645726, 6011063209139742, 379517444387209, 377250784667541, 347171902952673, 379852678889749, 345449316207827, 349968440887576, 347727987370269, 370147776002793, 374465794689268, 340860752032008, 349569393937707, 379610201376008, 346590844560212, 376638943222680, 378753384029375, 348159548355291, 345714137642682, 347556554119626, 370919740116903, 375059255910682, 373129538038460, 346734548488728, 370697814213115, 377968192654740, 379127496780069, 375213257576161, 379055805946370, 345835454524671, 377851536227201, 345763240913232 ]
MegaShow/college-programming
Homework/Haskell Function Programming/card.hs
Haskell
mit
5,136
{-# OPTIONS_GHC -fno-warn-type-defaults #-} import Test.Hspec (Spec, describe, it, shouldBe) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) import Robot ( Bearing ( East , North , South , West ) , bearing , coordinates , mkRobot , move ) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = do describe "mkRobot" $ do -- The function described by the reference file -- as `create` is called `mkRobot` in this track. it "Create robot at origin facing north" $ do let robot = mkRobot North (0, 0) coordinates robot `shouldBe` (0, 0) bearing robot `shouldBe` North it "Create robot at negative position facing south" $ do let robot = mkRobot South (-1, -1) coordinates robot `shouldBe` (-1, -1) bearing robot `shouldBe` South let turnTest inst dir dir2 = let robot = mkRobot dir (0, 0) in describe ("from " ++ show dir) $ do it "should change direction" $ bearing (move robot inst) `shouldBe` dir2 it "shouldn't change position" $ coordinates (move robot inst) `shouldBe` (0, 0) describe "Rotating clockwise" $ do let rightTest = turnTest "R" rightTest North East rightTest East South rightTest South West rightTest West North describe "Rotating counter-clockwise" $ do let leftTest = turnTest "L" leftTest North West leftTest West South leftTest South East leftTest East North describe "Moving forward one" $ do let dir `from` pos = move (mkRobot dir pos) "A" let test desc dir pos = describe (show dir ++ " from " ++ show pos) $ do it "shouldn't change direction" $ bearing (dir `from` (0, 0)) `shouldBe` dir it desc $ coordinates (dir `from` (0, 0)) `shouldBe` pos test "facing north increments Y" North (0, 1) test "facing south decrements Y" South (0, -1) test "facing east increments X" East (1, 0) test "facing west decrements X" West (-1, 0) describe "Follow series of instructions" $ do let simulation pos dir = move (mkRobot dir pos) it "moving east and north from README" $ do let robot = simulation (7, 3) North "RAALAL" coordinates robot `shouldBe` (9, 4) bearing robot `shouldBe` West it "moving west and north" $ do let robot = simulation (0, 0) North "LAAARALA" coordinates robot `shouldBe` (-4, 1) bearing robot `shouldBe` West it "moving west and south" $ do let robot = simulation (2, -7) East "RRAAAAALA" coordinates robot `shouldBe` (-3, -8) bearing robot `shouldBe` South it "moving east and north" $ do let robot = simulation (8, 4) South "LAAARRRALLLL" coordinates robot `shouldBe` (11, 5) bearing robot `shouldBe` North -- 7b07324f0a901c9234e9ffbb0beb889e9421e187
exercism/xhaskell
exercises/practice/robot-simulator/test/Tests.hs
Haskell
mit
3,120
{-# LANGUAGE NoImplicitPrelude #-} module Typeclasses where import Prelude (not, Bool(..)) data Animal = Dog | Cat class EqClass t where equal :: t -> t -> Bool neq :: t -> t -> Bool neq a b = not (equal a b) instance EqClass Animal where equal Dog Dog = True equal Cat Cat = True equal _ _ = False data EqDict t = EqDict { equal' :: t -> t -> Bool } equalAnimal Dog Dog = True equalAnimal Cat Cat = True equalAnimal _ _ = False animalEq :: EqDict Animal animalEq = EqDict equalAnimal neqAnimal :: EqClass t => t -> t -> Bool neqAnimal a b = neq a b neqAnimal' :: EqDict t -> t -> t -> Bool neqAnimal' dict a b = not (equal' dict a b)
riwsky/wiwinwlh
src/dictionaries.hs
Haskell
mit
661
module Euler.E54 where import Data.List (sort, nub) import Data.Maybe import Euler.Lib (rotations) data Rank = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace deriving (Eq, Ord, Show, Enum) data Suit = Hearts | Spades | Diamonds | Clubs deriving (Eq, Ord, Show) data Card = Card { rank :: Rank , suit :: Suit } deriving (Eq, Ord) data HandVal = HighCard [Rank] | OnePair Rank HandVal | TwoPairs Rank Rank HandVal | ThreeOfAKind Rank HandVal | Straight Rank | Flush Suit HandVal | FullHouse Rank Rank | FourOfAKind Rank HandVal | StraightFlush Rank | RoyalFlush Suit deriving (Eq, Ord, Show) type Hand = [Card] instance Read Rank where readsPrec x (' ':s) = readsPrec x s readsPrec _ ('2':s) = [(Two, s)] readsPrec _ ('3':s) = [(Three, s)] readsPrec _ ('4':s) = [(Four, s)] readsPrec _ ('5':s) = [(Five, s)] readsPrec _ ('6':s) = [(Six, s)] readsPrec _ ('7':s) = [(Seven, s)] readsPrec _ ('8':s) = [(Eight, s)] readsPrec _ ('9':s) = [(Nine, s)] readsPrec _ ('T':s) = [(Ten, s)] readsPrec _ ('J':s) = [(Jack, s)] readsPrec _ ('Q':s) = [(Queen, s)] readsPrec _ ('K':s) = [(King, s)] readsPrec _ ('A':s) = [(Ace, s)] readsPrec _ s = error $ "read Rank: could not parse string '" ++ s ++ "'." instance Read Suit where readsPrec x (' ':s) = readsPrec x s readsPrec _ ('H':s) = [(Hearts, s)] readsPrec _ ('S':s) = [(Spades, s)] readsPrec _ ('D':s) = [(Diamonds, s)] readsPrec _ ('C':s) = [(Clubs, s)] readsPrec _ s = error $ "read Suit: could not parse string '" ++ s ++ "'." instance Show Card where show (Card r s) = show r ++ " of " ++ show s instance Read Card where readsPrec x (' ':s) = readsPrec x s readsPrec _ (r:s:x) = [(Card (read [r]) (read [s]), x)] readsPrec _ s = error $ "read Card: could not parse string '" ++ s ++ "'." instance Enum Card where toEnum i = Card (toEnum i :: Rank) Spades fromEnum (Card r _) = fromEnum r euler54 :: [String] -> Int euler54 ss = length $ filter isWinnerPlayer1 ss debug :: String -> String debug s = s ++ " -> " ++ (show v1) ++ " | " ++ (show v2) ++ " | " ++ (show $ v1 > v2) where (h1, h2) = mkHands 5 s v1 = getHandVal h1 v2 = getHandVal h2 isWinnerPlayer1 :: String -> Bool isWinnerPlayer1 s = v1 > v2 where (h1, h2) = mkHands 5 s v1 = getHandVal h1 v2 = getHandVal h2 mkHands :: Int -> String -> (Hand, Hand) mkHands n s = readHands n $ words s readHands :: Int -> [String] -> (Hand, Hand) readHands n ss = (h1, h2) where cs = map (\s -> read s :: Card) ss h1 = sort $ take n cs h2 = sort $ take n $ drop n cs getHandVal :: Hand -> HandVal getHandVal h | isJust $ rf = RoyalFlush (fromJust rf) | isJust $ sf = StraightFlush (fromJust sf) | isJust $ fk = FourOfAKind (fst $ fromJust fk) (HighCard $ s' $snd $ fromJust fk) | isJust $ fh = FullHouse (fst $ fromJust fh) (snd $ fromJust fh) | isJust $ f = Flush (fromJust f) (HighCard $ s' rs) | isJust $ s = Straight (fromJust s) | isJust $ tk = ThreeOfAKind (fst $ fromJust tk) (HighCard $ s' $ snd $ fromJust tk) | isJust $ tp = TwoPairs (head $ fst $ fromJust tp) (last $ fst $ fromJust tp) (HighCard $ s' $snd $ fromJust tp) | isJust $ p = OnePair (fst $ fromJust p) (HighCard $ s' $snd $ fromJust p) | otherwise = HighCard (s' rs) where rs = map rank h ss = map suit h rf = isRoyalFlush h sf = isStraightFlush h fk = isFourOfAKind rs fh = isFullHouse rs f = isFlush ss s = isStraight rs tk = isThreeOfAKind rs tp = isTwoPairs rs p = isPair rs s' = reverse . sort isU :: Eq a => [a] -> Bool isU xs = (length $ nub xs) == 1 -- This one works with any size of hand! isNSame :: Int -> [Rank] -> Maybe (Rank,[Rank]) isNSame n r | not $ null ps = Just (head $ head ps, sort $ drop n $ head ps) | otherwise = Nothing where ps = filter (isU . (take n)) $ rotations r isPair :: [Rank] -> Maybe (Rank,[Rank]) isPair r = isNSame 2 r isTwoPairs :: [Rank] -> Maybe ([Rank], [Rank]) isTwoPairs r | and [ isJust p1, isJust p2 ] = Just ([fst $ fromJust p1, fst $ fromJust p2], snd $ fromJust p2) | otherwise = Nothing where p1 = isPair r p2 = isPair (snd $ fromJust p1) isThreeOfAKind :: [Rank] -> Maybe (Rank,[Rank]) isThreeOfAKind r = isNSame 3 r isStraight :: [Rank] -> Maybe Rank isStraight r | r == [head r .. last r] = Just $ head r | otherwise = Nothing isFlush :: [Suit] -> Maybe Suit isFlush s | (isU s) = Just (head s) | otherwise = Nothing isFullHouse :: [Rank] -> Maybe (Rank,Rank) isFullHouse r | and [ isJust tk, isJust $ isPair r' ] = Just (r1, r'!!0) | otherwise = Nothing where tk = isThreeOfAKind r (r1,r') = fromJust tk isFourOfAKind :: [Rank] -> Maybe (Rank, [Rank]) isFourOfAKind r = isNSame 4 r isStraightFlush :: Hand -> Maybe Rank isStraightFlush h | and [isJust $ isStraight r, isJust $ isFlush s] = Just $ head r | otherwise = Nothing where r = map rank h s = map suit h isRoyal :: [Rank] -> Bool isRoyal r = r == [Ten, Jack, Queen, King, Ace] isRoyalFlush :: Hand -> Maybe Suit isRoyalFlush h | and [isJust $ isFlush s, isRoyal r] = Just $ suit $ head h | otherwise = Nothing where r = map rank h s = map suit h main :: IO () main = interact $ show . euler54 . lines
D4r1/project-euler
Euler/E54.hs
Haskell
mit
5,208
{-# LANGUAGE MagicHash, UnboxedTuples, Rank2Types, BangPatterns, ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-full-laziness -fno-warn-name-shadowing #-} module Data.TrieVector.ArrayArray ( A.run , A.sizeof , A.thaw , A.unsafeThaw , A.write , ptrEq , update , modify , noCopyModify , index , new , newM , init1 , init2 , foldr , map , mapInitLast , foldl' , rfoldl' , rfoldr , read , AArray , MAArray ) where import Prelude hiding (foldr, read, map) import GHC.Prim import qualified Data.TrieVector.ArrayPrimWrap as A type AArray = A.Array Any type MAArray s = A.MArray s Any -- ThawArray should be preferably given a statically known length parameter, -- hence the length param in every function that calls it. update :: Int# -> AArray -> Int# -> AArray -> AArray update size arr i a = A.run $ \s -> case A.thaw arr 0# size s of (# s, marr #) -> case write marr i a s of s -> A.unsafeFreeze marr s {-# INLINE update #-} ptrEq :: AArray -> AArray -> Int# ptrEq a b = reallyUnsafePtrEquality# (unsafeCoerce# a :: Any) (unsafeCoerce# b :: Any) {-# INLINE ptrEq #-} modify :: Int# -> AArray -> Int# -> (AArray -> AArray) -> AArray modify size arr i f = A.run $ \s -> case A.thaw arr 0# size s of (# s, marr #) -> case read marr i s of (# s, a #) -> case write marr i (f a) s of s -> A.unsafeFreeze marr s {-# INLINE modify #-} noCopyModify :: Int# -> AArray -> Int# -> (AArray -> AArray) -> AArray noCopyModify size arr i f = let a = index arr i a' = f a in case reallyUnsafePtrEquality# (unsafeCoerce# a :: Any) (unsafeCoerce# a' :: Any) of 1# -> arr _ -> update size arr i a' {-# INLINE noCopyModify #-} map :: Int# -> (AArray -> AArray) -> AArray -> AArray map size f = \arr -> let go :: Int# -> MAArray s -> Int# -> State# s -> State# s go i marr size s = case i <# size of 1# -> case write marr i (f (index arr i)) s of s -> go (i +# 1#) marr size s _ -> s in A.run $ \s -> case newM size arr s of (# s, marr #) -> case go 0# marr size s of s -> A.unsafeFreeze marr s {-# INLINE map #-} mapInitLast :: Int# -> (AArray -> AArray) -> (AArray -> AArray) -> AArray -> AArray mapInitLast lasti f g = \arr -> let go :: Int# -> MAArray s -> Int# -> State# s -> State# s go i marr lasti s = case i <# lasti of 1# -> case write marr i (f (index arr i)) s of s -> go (i +# 1#) marr lasti s _ -> write marr lasti (g (index arr lasti)) s in A.run $ \s -> case newM (lasti +# 1#) arr s of (# s, marr #) -> case go 0# marr lasti s of s -> A.unsafeFreeze marr s {-# INLINE mapInitLast #-} foldr :: Int# -> (AArray -> b -> b) -> b -> AArray -> b foldr size f = \z arr -> go 0# size z arr where go i s z arr = case i <# s of 1# -> f (index arr i) (go (i +# 1#) s z arr) _ -> z {-# INLINE foldr #-} rfoldr :: Int# -> (AArray -> b -> b) -> b -> AArray -> b rfoldr size f = \z arr -> go (size -# 1#) z arr where go i z arr = case i >=# 0# of 1# -> f (index arr i) (go (i -# 1#) z arr) _ -> z {-# INLINE rfoldr #-} foldl' :: Int# -> (b -> AArray -> b) -> b -> AArray -> b foldl' size f = \z arr -> go 0# size z arr where go i s !z arr = case i <# s of 1# -> go (i +# 1#) s (f z (index arr i)) arr _ -> z {-# INLINE foldl' #-} rfoldl' :: Int# -> (b -> AArray -> b) -> b -> AArray -> b rfoldl' size f = \z arr -> go (size -# 1#) z arr where go i !z arr = case i >=# 0# of 1# -> go (i -# 1#) (f z (index arr i)) arr _ -> z {-# INLINE rfoldl' #-} index :: AArray -> Int# -> AArray index arr i = case A.index arr i of (# a #) -> unsafeCoerce# a {-# INLINE index #-} read :: MAArray s -> Int# -> State# s -> (# State# s, AArray #) read marr i s = unsafeCoerce# (A.read marr i s) {-# INLINE read #-} write :: MAArray s -> Int# -> AArray -> State# s -> State# s write marr i a s = A.write marr i (unsafeCoerce# a) s {-# INLINE write #-} new :: Int# -> a -> AArray new size def = A.run $ \s -> case A.new size def s of (# s, marr #) -> A.unsafeFreeze (unsafeCoerce# marr) s {-# INLINE new #-} newM :: Int# -> AArray -> State# s -> (# State# s, MAArray s #) newM size def s = A.new size (unsafeCoerce# def) s {-# INLINE newM #-} -- | Create a new array with a given element in the front and the rest filled with a default element. -- Here we allow an "a" default parameter mainly for error-throwing undefined elements. init1 :: Int# -> AArray -> AArray -> AArray init1 size arr def = A.run $ \s -> case newM size (unsafeCoerce# def) s of (# s, marr #) -> case write marr 0# arr s of s -> A.unsafeFreeze marr s {-# INLINE init1 #-} -- | Create a new array with a two given elements in the front and the rest filled with a default element. -- Here we allow an "a" default parameter mainly for error-throwing undefined elements. init2 :: Int# -> AArray -> AArray -> AArray -> AArray init2 size a1 a2 def = A.run $ \s -> case newM size (unsafeCoerce# def) s of (# s, marr #) -> case write marr 0# a1 s of s -> case write marr 1# a2 s of s -> A.unsafeFreeze marr s {-# INLINE init2 #-}
AndrasKovacs/trie-vector
Data/TrieVector/ArrayArray.hs
Haskell
mit
5,418
{-# LANGUAGE TupleSections #-} module Data.Tuple.Extra where import Data.Tuple (uncurry) import Data.Functor uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d uncurry3 f (x,y,z) = f x y z uncurry4 :: (a -> b -> c -> d -> e) -> (a, b, c, d) -> e uncurry4 f (w,x,y,z) = f w x y z uncurry5 :: (a -> b -> c -> d -> e -> f) -> (a, b, c, d, e) -> f uncurry5 f (v, w,x,y,z) = f v w x y z uncurry6 :: (a -> b -> c -> d -> e -> f -> g) -> (a, b, c, d, e, f) -> g uncurry6 f (u,v,w,x,y,z) = f u v w x y z sequenceFst :: (Functor f) => (f a, b) -> f (a, b) sequenceFst (a,b) = fmap (,b) a sequenceSnd :: (Functor f) => (a, f b) -> f (a, b) sequenceSnd (a,b) = fmap (a,) b uncurryProduct :: (a -> b -> c) -> (a, b) -> c uncurryProduct = uncurry uncurryProduct3 :: (a -> b -> c -> d) -> (a, (b, c)) -> d uncurryProduct3 f (x,(y,z)) = f x y z uncurryProduct4 :: (a -> b -> c -> d -> e) -> (a, (b, (c, d))) -> e uncurryProduct4 f (w,(x,(y,z))) = f w x y z uncurryProduct5 :: (a -> b -> c -> d -> e -> f) -> (a, (b, (c, (d, e)))) -> f uncurryProduct5 f (v,(w,(x,(y,z)))) = f v w x y z uncurryProduct6 :: (a -> b -> c -> d -> e -> f -> g) -> (a, (b, (c, (d, (e, f))))) -> g uncurryProduct6 f (u,(v,(w,(x,(y,z))))) = f u v w x y z
circuithub/circuithub-prelude
Data/Tuple/Extra.hs
Haskell
mit
1,223
{-# LANGUAGE QuasiQuotes, TypeFamilies, TemplateHaskell, MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleInstances #-} module YesodCoreTest.CleanPath (cleanPathTest, Widget) where import Test.Hspec import Yesod.Core hiding (Request) import Network.Wai import Network.Wai.Test import Network.HTTP.Types (status200, decodePathSegments) import qualified Data.ByteString.Lazy.Char8 as L8 import qualified Data.Text as TS import qualified Data.Text.Encoding as TE import Control.Arrow ((***)) import Network.HTTP.Types (encodePath) import Data.Monoid (mappend) import Blaze.ByteString.Builder.Char.Utf8 (fromText) data Subsite = Subsite getSubsite :: a -> Subsite getSubsite = const Subsite instance RenderRoute Subsite where data Route Subsite = SubsiteRoute [TS.Text] deriving (Eq, Show, Read) renderRoute (SubsiteRoute x) = (x, []) instance YesodDispatch Subsite master where yesodDispatch _ _ _ _ _ _ _ pieces _ _ = return $ responseLBS status200 [ ("Content-Type", "SUBSITE") ] $ L8.pack $ show pieces data Y = Y mkYesod "Y" [parseRoutes| /foo FooR GET /foo/#String FooStringR GET /bar BarR GET /subsite SubsiteR Subsite getSubsite /plain PlainR GET |] instance Yesod Y where approot = ApprootStatic "http://test" cleanPath _ s@("subsite":_) = Right s cleanPath _ ["bar", ""] = Right ["bar"] cleanPath _ ["bar"] = Left ["bar", ""] cleanPath _ s = if corrected == s then Right s else Left corrected where corrected = filter (not . TS.null) s joinPath Y ar pieces' qs' = fromText ar `mappend` encodePath pieces qs where pieces = if null pieces' then [""] else pieces' qs = map (TE.encodeUtf8 *** go) qs' go "" = Nothing go x = Just $ TE.encodeUtf8 x getFooR :: Handler RepPlain getFooR = return $ RepPlain "foo" getFooStringR :: String -> Handler RepPlain getFooStringR = return . RepPlain . toContent getBarR, getPlainR :: Handler RepPlain getBarR = return $ RepPlain "bar" getPlainR = return $ RepPlain "plain" cleanPathTest :: Spec cleanPathTest = describe "Test.CleanPath" $ do it "remove trailing slash" removeTrailingSlash it "noTrailingSlash" noTrailingSlash it "add trailing slash" addTrailingSlash it "has trailing slash" hasTrailingSlash it "/foo/something" fooSomething it "subsite dispatch" subsiteDispatch it "redirect with query string" redQueryString runner :: Session () -> IO () runner f = toWaiApp Y >>= runSession f removeTrailingSlash :: IO () removeTrailingSlash = runner $ do res <- request defaultRequest { pathInfo = decodePathSegments "/foo/" } assertStatus 301 res assertHeader "Location" "http://test/foo" res noTrailingSlash :: IO () noTrailingSlash = runner $ do res <- request defaultRequest { pathInfo = decodePathSegments "/foo" } assertStatus 200 res assertContentType "text/plain; charset=utf-8" res assertBody "foo" res addTrailingSlash :: IO () addTrailingSlash = runner $ do res <- request defaultRequest { pathInfo = decodePathSegments "/bar" } assertStatus 301 res assertHeader "Location" "http://test/bar/" res hasTrailingSlash :: IO () hasTrailingSlash = runner $ do res <- request defaultRequest { pathInfo = decodePathSegments "/bar/" } assertStatus 200 res assertContentType "text/plain; charset=utf-8" res assertBody "bar" res fooSomething :: IO () fooSomething = runner $ do res <- request defaultRequest { pathInfo = decodePathSegments "/foo/something" } assertStatus 200 res assertContentType "text/plain; charset=utf-8" res assertBody "something" res subsiteDispatch :: IO () subsiteDispatch = runner $ do res <- request defaultRequest { pathInfo = decodePathSegments "/subsite/1/2/3/" } assertStatus 200 res assertContentType "SUBSITE" res assertBody "[\"1\",\"2\",\"3\",\"\"]" res redQueryString :: IO () redQueryString = runner $ do res <- request defaultRequest { pathInfo = decodePathSegments "/plain/" , rawQueryString = "?foo=bar" } assertStatus 301 res assertHeader "Location" "http://test/plain?foo=bar" res
piyush-kurur/yesod
yesod-core/test/YesodCoreTest/CleanPath.hs
Haskell
mit
4,465
module Main where import qualified Labyrinth.Helpers import qualified Labyrinth.Models import qualified Labyrinth.Game import qualified Labyrinth.Factory import qualified Labyrinth.Board import qualified Labyrinth.Parser import qualified Data.List import qualified System.Random import qualified System.Environment createNewGame :: IO Labyrinth.Models.Game createNewGame = do putStrLn "Hello and welcome to Labyrinth! How many players will be playing today?" numberOfPlayersAsString <- getLine let numberOfPlayers = read numberOfPlayersAsString :: Int generator <- System.Random.getStdGen return $ Labyrinth.Factory.createNewGame numberOfPlayers generator openExistingGame :: String -> IO Labyrinth.Models.Game openExistingGame gameFileName = do gameFileContents <- readFile gameFileName let game = (fst . head) $ Labyrinth.Parser.apply Labyrinth.Parser.labyrinth gameFileContents return game startGame :: Labyrinth.Models.Game -> IO() startGame game = do Labyrinth.Game.takeTurn game return () main :: IO () main = do args <- System.Environment.getArgs case args of [] -> createNewGame >>= startGame [file] -> openExistingGame file >>= startGame _ -> putStrLn "Wrong number of arguments. Pass in zero arguments to start a new game, or pass in a file name to resume an existing game."
amoerie/labyrinth
Main.hs
Haskell
mit
1,335
module Y2016.M12.D26.Exercise where import Data.Array import Data.Map (Map) -- below imports available via 1HaskellADay git repository import Data.SAIPE.USCounties import Graph.KMeans import Graph.ScoreCard import Graph.ScoreCard.Clusters import Y2016.M12.D15.Exercise import Y2016.M12.D21.Exercise {-- Good morning, all. Happy Boxing Day! So, last week we clustered SAIPE/poverty data for Counties of the US, and saw some interesting things that we'll explore later this week, and associate back to US States. But that later. The K-means algorithm is a good classifier, no doubt; I mean, it's way better than going through a spreadsheet, row-by-row... ... and guess how most companies look at their data-sets? Yup, in a spreadsheet, row-by-row. But K-means is not the only way to look at a data-set, by no means. It's a good one, but not the only one, and issues with k-means, particularly the time- cost of classification as the data-sets get larger, as you saw when you classified the SAIPE-data. That took a bit of time to do. So, other forms of classification? What are your recommendations, Haskellers? Tweet me and we can look at those. For today, we're going to do an eh-classification. That is to say, we're going to use the old eyeballs or our seats-of-the-pants method of classification to divvy up these data into one of five categories: --} data Size = Tiny | Small | Medium | Large | YUGE deriving (Eq, Ord, Enum, Bounded, Ix, Show, Read) {-- Today's Haskell problem: take the data at Y2016/M12/D15/SAIPESNC_15DEC16_11_35_13_00.csv.gz read it in, and, using a classification method of your choice, partition these data in to the groups of your choosing. How do divvy up these data? Well, you have population, you have poverty, and you have the ratio of the two, don't you? So, you choose which attribute you use to partition the data. --} partitionSAIPEBySize :: SAIPEData -> Map Size SAIPERow partitionSAIPEBySize saipe = undefined {-- There is a more general activity you are doing here, however, and that is, you are partitioning any kind of data by some measure of their size. We do have a container-type for 'any kind of measured data,' and that is the ScoreCard. Partition the ScoreCards of SAIPE data by size. I mean USE the SAIPE data set but, more generally, partition ANY ScoreCard-type by Size: --} partitionBySize :: RealFrac c => [ScoreCard a b c] -> Map Size [ScoreCard a b c] partitionBySize scorecards = undefined {-- BONUS ----------------------------------------------------------------- Display your partitioned-by-size data-set using the charting tool of your choice --} drawSizedPartitions :: (Show a, Show b, Show c) => Map Size [ScoreCard a b c] -> IO () drawSizedPartitions partitions = undefined {-- HINT ------------------------------------------------------------------ You can use the Clusters-type, you know. kmeans doesn't own that type, and each cluster is identified by its corresponding Size-value. If you reorganize the Map Size [ScoreCard a b c] as Graph.KMeans.Clusters value with a little Map.map-magic, then the resulting value draws itself, as you saw from the solution from the Y2016.M12.D23 solution. --} {-- BONUS-BONUS ----------------------------------------------------------- Now that we have size information in the graphed data set, re-lable each of the Cell nodes with Size information, so that, e.g.: small nodes show visually as small and YUGE nodes show as YUGE! YUGE, adj.: means YUGE, ICYMI --} relableNodesBySize :: (Show a, Show b, Show c) => Map Size [ScoreCard a b c] -> IO () relableNodesBySize sizeddata = undefined {-- MOTIVATION ------------------------------------------------------------ This relable function comes from me asking the Neo Tech folks how I could programatically resize nodes from their attributed data. I didn't get a satisifactory answer. Is this, here a satifactory way programatically to resize data nodes? We shall see, shan't we! --}
geophf/1HaskellADay
exercises/HAD/Y2016/M12/D26/Exercise.hs
Haskell
mit
3,973
module Main where import Test.Tasty (defaultMain,testGroup,TestTree) import AlgorithmsAtHandHaskell.Swallow.Test import AlgorithmsAtHandHaskell.Coconut.Test main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "All Tests" [ swallowSuite , coconutSuite ]
antonlogvinenko/algorithms-at-hand
algorithms-at-hand-haskell/test/Test.hs
Haskell
mit
316
{-# LANGUAGE NoMonomorphismRestriction #-} import Diagrams.Prelude import Diagrams.Backend.SVG.CmdLine h = hexagon 1 # fc lightgreen sOrigin = showOrigin' (with & oScale .~ 0.04) diagram :: Diagram B diagram = h # snugBL # sOrigin main = mainWith $ frame 0.1 diagram
jeffreyrosenbluth/NYC-meetup
meetup/SnugBL.hs
Haskell
mit
292
module Chapter05.Sing where fstString :: [Char] -> [Char] fstString x = x ++ " in the rain" sndString :: [Char] -> [Char] sndString x = x ++ " over the rainbow" sing :: Ord a => a -> a -> [Char] sing x y = if (x > y) then fstString "Signin" else sndString "Somewhere"
brodyberg/LearnHaskell
HaskellProgramming.hsproj/Chapter05/Sing.hs
Haskell
mit
300
module Heuristics where import Data.Array import Data.List import NPuzzle manhattan :: NPuzzle.Grid -> NPuzzle.Grid -> Int manhattan end start = sum $ map go (indices start) where manhattan' (gx, gy) (cx, cy) = abs (gx - cx) + abs (gy - cy) go i = manhattan' (end!i) (start!i)
Shakadak/n-puzzle
Heuristics.hs
Haskell
mit
298
module FileTools ( find, ls, cat ) where import System.Directory import System.IO.Error import qualified Data.ByteString.Lazy.Char8 as B cat :: FilePath -> IO B.ByteString cat file = catchIOError (B.readFile file) (\e -> return $ B.pack []) ls :: String -> IO [FilePath] ls dir = getDirectoryContents dir >>= return . filter (`notElem` [".",".."]) find :: FilePath -> IO [FilePath] find dir = ls dir >>= mapM (\x -> return $ dir ++ "/" ++ x) >>= mapM find' >>= return . concat find' :: FilePath -> IO [FilePath] find' path = do b <- doesDirectoryExist path if b then find path else return [path]
ryuichiueda/UspMagazineHaskell
Study1_Q3/FileTools.hs
Haskell
mit
653
module GitStatus where import GitWorkflow type GitStatus = (Char, Char, String, Maybe String) pathStatuses :: IO (Either String [GitStatus]) pathStatuses = do r <- runGitProcess ["status", "-s"] case r of Left err -> return (Left err) Right ss -> return $Right $map readStatus $lines ss where readStatus (i:w:xs) = case words xs of (path:[]) -> (i,w,path,Nothing) (path1:"->":path2:[]) -> (i,w,path1,Just path2) statusToString :: GitStatus -> String statusToString (i,w,p,Nothing) = i:w:' ':p statusToString (i,w,p1,Just p2) = i:w:' ':(p1 ++ " -> " ++ p2) pathFromStatus :: GitStatus -> String pathFromStatus (_,_,p,_) = p
yamamotoj/alfred-git-workflow
src/GitStatus.hs
Haskell
mit
711
module Lib where import Data.List as List import Data.List.Split import Data.Map.Strict as Map data BinSize = Small | Large deriving Show data ShelfDifficulty = Normal | Level3 | Level4 deriving Show data Bin = Bin { warehouse :: String, room :: String, bay :: String, shelf :: String, number :: String, size :: BinSize, difficulty :: ShelfDifficulty } deriving Show type ProductId = String type Quantity = Int parseBinSize :: String -> BinSize parseBinSize "S" = Small parseBinSize "L" = Large parseShelfDifficulty :: String -> ShelfDifficulty parseShelfDifficulty "S01" = Normal parseShelfDifficulty "S02" = Normal parseShelfDifficulty "S03" = Level3 parseShelfDifficulty "S04" = Level4 parseBin :: String -> Bin parseBin binStr = let [w, r, b, s, n, sz] = splitOn "-" binStr in Bin w r b s n (parseBinSize sz) (parseShelfDifficulty s) parseLine :: String -> (ProductId, [(Bin, Quantity)]) parseLine line = let [b, p, q] = splitOn "\t" line in (p, [(parseBin b, read q)]) parseFile :: String -> Map.Map ProductId [(Bin, Quantity)] parseFile f = Map.fromListWith (++) $ List.map parseLine (lines f)
NashFP/pick-and-grin
mark_wutka+hakan+kate+haskell/src/Lib.hs
Haskell
mit
1,261
{-# LANGUAGE OverloadedStrings #-} {-| Module : Utils.NuxmvCode Description : Utilities for producing nuXmv code Copyright : (c) Tessa Belder 2015-2016 This module contains useful functions for producing nuXmv code. -} module Utils.NuxmvCode where import Data.List (intersperse) import Utils.Concatable as C -- * Declarations -- | INVAR declaration nuxmv_invar :: (IsString a, Monoid a) => a -> a nuxmv_invar = nuxmv_keyword "INVAR" -- | INVARSPEC declaration nuxmv_invarspec :: (IsString a, Monoid a) => a -> a nuxmv_invarspec = nuxmv_keyword "INVARSPEC" -- | NuXmv keyword declarations nuxmv_keyword :: (IsString a, Monoid a) => a -> a -> a nuxmv_keyword keyword assignment = C.unwords[keyword,assignment] -- | CONSTANTS declaration nuxmv_constants :: (IsString a, Monoid a) => [a] -> a nuxmv_constants consts = "CONSTANTS " <> C.intercalate ", " consts <> ";" -- | NuXmv variable types data NuxmvVariableType = Input -- ^ Input variable (IVAR) | State -- ^ State variable (VAR) | Frozen -- ^ Frozen variable (FROZENVAR) -- | Boolean variable declaration nuxmv_bool :: (IsString a, Monoid a) => NuxmvVariableType -> a -> a nuxmv_bool varType = nuxmv_var varType bool_type -- | Integer variable declaration nuxmv_int :: (IsString a, Monoid a) => NuxmvVariableType -> Int -> a -> a nuxmv_int varType n = nuxmv_var varType (int_type n) -- | Enumeration declaration nuxmv_enum :: (IsString a, Monoid a) => NuxmvVariableType -> [a] -> a -> a nuxmv_enum varType vals = nuxmv_var varType (enum_type vals) -- | Array declaration nuxmv_array :: (IsString a, Monoid a) => NuxmvVariableType -> a -> a -> a -> a nuxmv_array varType t t' name = nuxmv_var varType (array_type t t') name -- | NuXmv keyword for nuXmv variable types nuxmv_var :: (IsString a, Monoid a) => NuxmvVariableType -> a -> a -> a nuxmv_var State = nuxmv_declaration "VAR" nuxmv_var Input = nuxmv_declaration "IVAR" nuxmv_var Frozen = nuxmv_declaration "FROZENVAR" -- | General nuXmv declaration nuxmv_declaration :: (IsString a, Monoid a) => a -> a -> a -> a nuxmv_declaration keyword t name = nuxmv_keyword keyword $ name <> ": " <> t <> ";" -- * Types -- | NuXmv boolean type bool_type :: IsString a => a bool_type = "boolean" -- | nuXmv integer type int_type :: (IsString a, Monoid a) => Int -> a int_type n = range_type 0 (n-1) -- | nuXmv range type range_type :: (IsString a, Monoid a) => Int -> Int -> a range_type n m = C.show n <> ".." <> C.show m -- | nuXmv enumeration type enum_type :: (IsString a, Monoid a) => [a] -> a enum_type [] = "{no_values}" -- empty enumerations are not allowed enum_type vals = "{" <> C.intercalate ", " vals <> "}" -- | nuXmv array type array_type :: (IsString a, Monoid a) => a -> a -> a array_type t t' = "array " <> t <> " of " <> t' -- | Position in an array nuxmv_array_pos :: (IsString a, Monoid a) => a -> Int -> a nuxmv_array_pos arr pos = arr <> "[" <> (C.show pos) <> "]" -- * Constants -- | True nuxmv_true :: IsString a => a nuxmv_true = "TRUE" -- | False nuxmv_false :: IsString a => a nuxmv_false = "FALSE" -- * Operators -- ** Unary operators -- | Boolean negation nuxmv_negate :: (IsString a, Monoid a) => a -> a nuxmv_negate = nuxmv_un_operator "!" -- | General unary operator nuxmv_un_operator :: (IsString a, Monoid a) => a -> a -> a nuxmv_un_operator op arg = "(" <> op <> arg <> ")" -- ** Binary operators -- | Equality operator nuxmv_equals :: (IsString a, Monoid a) => a -> a -> a nuxmv_equals = nuxmv_bin_operator "=" -- | Inequality operator nuxmv_unequal :: (IsString a, Monoid a) => a -> a -> a nuxmv_unequal = nuxmv_bin_operator "!=" -- | At most operator nuxmv_atmost :: (IsString a, Monoid a) => a -> a -> a nuxmv_atmost = nuxmv_bin_operator "<=" -- | Greater than operator nuxmv_gt :: (IsString a, Monoid a) => a -> a -> a nuxmv_gt = nuxmv_bin_operator ">" -- | Set inclusion ("in") operator nuxmv_in :: (IsString a, Monoid a) => a -> a -> a nuxmv_in = nuxmv_bin_operator "in" -- | Addition nuxmv_add_bin :: (IsString a, Monoid a) => a -> a -> a nuxmv_add_bin x y = nuxmv_add [x, y] -- | Multiplication nuxmv_mult_bin :: (IsString a, Monoid a) => a -> a -> a nuxmv_mult_bin x y = nuxmv_mult [x, y] -- | Subtraction nuxmv_minus :: (IsString a, Monoid a) => a -> a -> a nuxmv_minus = nuxmv_bin_operator "-" -- | Modulo nuxmv_mod :: (IsString a, Monoid a) => a -> a -> a nuxmv_mod = nuxmv_bin_operator "mod" -- | Disjunction nuxmv_or_bin :: (IsString a, Monoid a) => a -> a -> a nuxmv_or_bin x y = nuxmv_or [x, y] -- | Conjunction nuxmv_and_bin :: (IsString a, Monoid a) => a -> a -> a nuxmv_and_bin x y = nuxmv_and [x, y] -- | General binary operator nuxmv_bin_operator :: (IsString a, Monoid a) => a -> a -> a -> a nuxmv_bin_operator op arg1 arg2 = "(" <> C.unwords [arg1, op, arg2] <> ")" -- ** Tertiary operators -- | In range operator (at least "low" and at most "high") nuxmv_inrange :: (IsString a, Monoid a) => a -> (Int, Int) -> a nuxmv_inrange val (l, h) = nuxmv_and[nuxmv_atmost (C.show l) val, nuxmv_atmost val (C.show h)] -- ** N-ary operators -- | Addition nuxmv_add :: (IsString a, Monoid a) => [a] -> a nuxmv_add = nuxmv_n_operator "+" -- | Multiplication nuxmv_mult :: (IsString a, Monoid a) => [a] -> a nuxmv_mult = nuxmv_n_operator "*" -- | Disjunction nuxmv_or :: (IsString a, Monoid a) => [a] -> a nuxmv_or = nuxmv_n_operator "|" -- | Conjunction nuxmv_and :: (IsString a, Monoid a) => [a] -> a nuxmv_and = nuxmv_n_operator "&" -- | General n-ary operator nuxmv_n_operator :: (IsString a, Monoid a) => a -> [a] -> a nuxmv_n_operator _ [] = "" nuxmv_n_operator _ [x] = x nuxmv_n_operator op xs = "(" <> C.unwords (intersperse op xs) <> ")" -- * Functions -- | Cast to integer nuxmv_toint :: (IsString a, Monoid a) => a -> a nuxmv_toint = nuxmv_function "toint" . (:[]) -- | Count function nuxmv_count :: (IsString a, Monoid a) => [a] -> a nuxmv_count = nuxmv_function "count" -- | General function application nuxmv_function :: (IsString a, Monoid a) => a -> [a] -> a nuxmv_function fun args = fun <> "(" <> C.intercalate ", " args <> ")" -- * Assignments -- | Init assignment nuxmv_init :: (IsString a, Monoid a) => a -> a -> a nuxmv_init var = head . nuxmv_assignment (nuxmv_function "init" [var]) . (:[]) -- | Next assignment nuxmv_next :: (IsString a, Monoid a) => a -> [a] -> [a] nuxmv_next var = nuxmv_assignment $ nuxmv_function "next" [var] -- | General assignment nuxmv_assignment :: (IsString a, Monoid a) => a -> [a] -> [a] nuxmv_assignment _ [] = fatal (513::Int) "Empty assignment not allowed" where fatal i s = error ("Fatal " ++ Prelude.show i ++ " in " ++ fileName ++ ":\n " ++ s) fileName = "Utils.NuxmvCode" nuxmv_assignment name [assignment] = [name <> " := " <> assignment <> ";"] nuxmv_assignment name (asg:asgs) = [name <> " := " <> asg] ++ init asgs ++ [last asgs <> ";"] -- * Case distinction -- | Switch statement nuxmv_switch :: (IsString a, Monoid a) => [(a, a)] -> [a] nuxmv_switch cases = ["case"] ++ nuxmv_indent (map (uncurry nuxmv_case) cases) ++ ["esac"] where -- | A single switch case nuxmv_case :: (IsString a, Monoid a) => a -> a -> a nuxmv_case ifval thenval = ifval <> ": " <> thenval <> ";" -- | If-then-else statement nuxmv_ite :: (IsString a, Monoid a) => a -> a -> a -> a nuxmv_ite ifval thenval elseval = "(" <> C.unwords[ifval, "?", thenval, ":", elseval] <> ")" -- * File generation -- | "MODULE" block nuxmv_module :: (IsString a, Monoid a) => a -> [a] -> [a] nuxmv_module name = nuxmv_file_block (C.unwords["MODULE",name]) -- | "ASSIGN" block nuxmv_assign :: (IsString a, Monoid a) => [a] -> [a] nuxmv_assign = nuxmv_file_block "ASSIGN" -- | General block nuxmv_file_block :: (IsString a, Monoid a) => a -> [a] -> [a] nuxmv_file_block header contents = if null contents then [] else header:(nuxmv_indent contents) -- | Indent 2 spaces nuxmv_indent :: (IsString a, Monoid a) => [a] -> [a] nuxmv_indent = map (" " <>)
julienschmaltz/madl
src/Utils/NuxmvCode.hs
Haskell
mit
7,873
module Network.Mosquitto ( -- * Data structure Mosquitto , Event(..) -- * Mosquitto , initializeMosquittoLib , cleanupMosquittoLib , newMosquitto , destroyMosquitto , setWill , clearWill , connect , disconnect , getNextEvents , subscribe , publish -- * Helper , withInit , withMosquitto , withConnect -- * Utility , strerror ) where import Network.Mosquitto.C.Interface import Network.Mosquitto.C.Types import Control.Monad import Control.Monad.IO.Class import Data.IORef import qualified Data.ByteString as BS import Data.ByteString.Internal(toForeignPtr) import Control.Exception(bracket, bracket_, throwIO, AssertionFailed(..)) import Foreign.Ptr(Ptr, FunPtr, nullPtr, plusPtr, castFunPtr, freeHaskellFunPtr) import Foreign.ForeignPtr(withForeignPtr) import Foreign.Storable(peek) import Foreign.C.String(withCString, peekCString) import Foreign.C.Types(CInt(..)) import Foreign.Marshal.Array(peekArray) import Foreign.Marshal.Utils(fromBool) import Foreign.Marshal.Alloc(malloc, free) data Mosquitto = Mosquitto { mosquittoObject :: !Mosq , mosquittoEvents :: IORef [Event] , mosquittoCallbacks :: ![FunPtr ()] } data Event = Message { messageID :: !Int , messageTopic :: !String , messagePayload :: !BS.ByteString , messageQos :: !Int , messageRetain :: !Bool } | ConnectResult { connectResultCode :: !Int , connectResultString :: !String } | DisconnectResult { disconnectResultCode :: !Int , disconnectResultString :: !String } | Published { messageID :: !Int } deriving Show initializeMosquittoLib :: IO () initializeMosquittoLib = do result <- c_mosquitto_lib_init when (result /= 0) $ do msg <- strerror $ fromIntegral result throwIO $ AssertionFailed $ "initializeMosquitto: " ++ msg cleanupMosquittoLib :: IO () cleanupMosquittoLib = do result <- c_mosquitto_lib_cleanup when (result /= 0) $ do msg <- strerror $ fromIntegral result throwIO $ AssertionFailed $ "cleanupMosquittoLib: " ++ msg newMosquitto :: Maybe String -> IO Mosquitto newMosquitto Nothing = c_mosquitto_new nullPtr 1 nullPtr >>= newMosquitto' newMosquitto (Just s) = (withCString s $ \sC -> c_mosquitto_new sC 1 nullPtr) >>= newMosquitto' newMosquitto' :: Mosq -> IO Mosquitto newMosquitto' mosq = if mosq == nullPtr then throwIO $ AssertionFailed "invalid mosq object" else do events <- newIORef ([] :: [Event]) connectCallbackC <- wrapOnConnectCallback (connectCallback events) c_mosquitto_connect_callback_set mosq connectCallbackC messageCallbackC <- wrapOnMessageCallback (messageCallback events) c_mosquitto_message_callback_set mosq messageCallbackC disconnectCallbackC <- wrapOnDisconnectCallback (disconnectCallback events) c_mosquitto_disconnect_callback_set mosq disconnectCallbackC publishCallbackC <- wrapOnPublishCallback (publishCallback events) c_mosquitto_publish_callback_set mosq publishCallbackC return Mosquitto { mosquittoObject = mosq , mosquittoEvents = events , mosquittoCallbacks = [ castFunPtr connectCallbackC , castFunPtr messageCallbackC , castFunPtr disconnectCallbackC , castFunPtr publishCallbackC ] } where connectCallback :: IORef [Event] -> Mosq -> Ptr () -> CInt -> IO () connectCallback events _mosq _ result = do let code = fromIntegral result str <- strerror code pushEvent events $ ConnectResult code str messageCallback :: IORef [Event] -> Mosq -> Ptr () -> Ptr MessageC -> IO () messageCallback events _mosq _ messageC = do msg <- peek messageC topic <- peekCString (messageCTopic msg) payload <- peekArray (fromIntegral $ messageCPayloadLen msg) (messageCPayload msg) pushEvent events $ Message (fromIntegral $ messageCID msg) topic (BS.pack payload) (fromIntegral $ messageCQos msg) (messageCRetain msg) disconnectCallback :: IORef [Event] -> Mosq -> Ptr () -> CInt -> IO () disconnectCallback events _mosq _ result = do let code = fromIntegral result str <- strerror code pushEvent events $ DisconnectResult code str publishCallback :: IORef [Event] -> Mosq -> Ptr () -> CInt -> IO () publishCallback events _mosq _ mid = do pushEvent events $ Published (fromIntegral mid) pushEvent :: IORef [Event] -> Event -> IO () pushEvent ref e = do es <- readIORef ref writeIORef ref (e:es) destroyMosquitto :: Mosquitto -> IO () destroyMosquitto mosquitto = do mapM_ freeHaskellFunPtr (mosquittoCallbacks mosquitto) writeIORef (mosquittoEvents mosquitto) [] c_mosquitto_destroy (mosquittoObject mosquitto) setWill :: Mosquitto -> String -> BS.ByteString -> Int -> Bool -> IO Int setWill mosquitto topicName payload qos retain = do let (payloadFP, off, _len) = toForeignPtr payload fmap fromIntegral $ withCString topicName $ \topicNameC -> withForeignPtr payloadFP $ \payloadP -> do c_mosquitto_will_set (mosquittoObject mosquitto) topicNameC (fromIntegral (BS.length payload)) (payloadP `plusPtr` off) (fromIntegral qos) (fromBool retain) clearWill :: Mosquitto -> IO Int clearWill mosquitto = c_mosquitto_will_clear (mosquittoObject mosquitto) >>= return . fromIntegral connect :: Mosquitto -> String -> Int -> Int -> IO Int connect mosquitto hostname port keepAlive = fmap fromIntegral . withCString hostname $ \hostnameC -> c_mosquitto_connect (mosquittoObject mosquitto) hostnameC (fromIntegral port) (fromIntegral keepAlive) disconnect :: Mosquitto -> IO Int disconnect mosquitto = fmap fromIntegral . c_mosquitto_disconnect $ mosquittoObject mosquitto getNextEvents :: Mosquitto -> Int -> IO (Int, [Event]) getNextEvents mosquitto timeout = do result <- fmap fromIntegral . liftIO $ c_mosquitto_loop (mosquittoObject mosquitto) (fromIntegral timeout) 1 if result == 0 then do events <- liftIO . fmap reverse $ readIORef (mosquittoEvents mosquitto) writeIORef (mosquittoEvents mosquitto) [] return (result, events) else return (result, []) subscribe :: Mosquitto -> String -> Int -> IO Int subscribe mosquitto topicName qos = do fmap fromIntegral . withCString topicName $ \topicNameC -> c_mosquitto_subscribe (mosquittoObject mosquitto) nullPtr topicNameC (fromIntegral qos) publish :: Mosquitto -> String -> BS.ByteString -> Int -> Bool -> IO (Int, Int) publish mosquitto topicName payload qos retain = do midC <- (malloc :: IO (Ptr CInt)) let (payloadFP, off, _len) = toForeignPtr payload res <- fmap fromIntegral $ withCString topicName $ \topicNameC -> withForeignPtr payloadFP $ \payloadP -> c_mosquitto_publish (mosquittoObject mosquitto) midC topicNameC (fromIntegral (BS.length payload)) (payloadP `plusPtr` off) (fromIntegral qos) (fromBool retain) mid <- fromIntegral <$> peek midC free midC return (res, mid) -- Utility strerror :: Int -> IO String strerror err = c_mosquitto_strerror (fromIntegral err) >>= peekCString -- Helper withInit :: IO a -> IO a withInit = bracket_ initializeMosquittoLib cleanupMosquittoLib withMosquitto :: Maybe String -> (Mosquitto -> IO a) -> IO a withMosquitto clientId = bracket (newMosquitto clientId) destroyMosquitto withConnect :: Mosquitto -> String -> Int -> Int -> IO a -> IO a withConnect mosquitto hostname port keepAlive = bracket_ connectI (disconnect mosquitto) where connectI :: IO () connectI = do result <- connect mosquitto hostname (fromIntegral port) (fromIntegral keepAlive) when (result /= 0) $ do err <- strerror result throwIO $ AssertionFailed $ "withConnect:" ++ (show result) ++ ": " ++ err
uwitty/mosquitto
src/Network/Mosquitto.hs
Haskell
mit
9,202
-- Get the difference between the sum of squares and the square of sum for the numbers between 1 and 100 main = print getProblem6Value getProblem6Value :: Integer getProblem6Value = getSquareOfSumMinusSumOfSquares [1..100] getSquareOfSumMinusSumOfSquares :: [Integer] -> Integer getSquareOfSumMinusSumOfSquares nums = (getSquareOfSum nums) - (getSumOfSquares nums) getSquareOfSum :: [Integer] -> Integer getSquareOfSum nums = (sum nums) ^ 2 getSumOfSquares :: [Integer] -> Integer getSumOfSquares nums = sum $ map (^2) nums
jchitel/ProjectEuler.hs
Problems/Problem0006.hs
Haskell
mit
529
module Data.NameSupply ( NameSupply (..), mkNameSupply, getFreshName , NS, runNS , newName, findName, withName ) where import Common import Control.Monad.Reader import Control.Monad.State import qualified Data.Map as M import qualified Data.Set as S newtype NameSupply = NameSupply { getNames :: [Name] } mkNameSupply :: S.Set Name -> NameSupply mkNameSupply usedNames = NameSupply freeNames where mkName suffix = map (:suffix) ['a'..'z'] allNames = concatMap mkName ("":map show [1..]) freeNames = filter (\name -> S.notMember name usedNames) allNames getFreshName :: NameSupply -> (Name, NameSupply) getFreshName (NameSupply (name:xs)) = (name, NameSupply xs) type NS = ReaderT (M.Map Name Name) (State NameSupply) runNS :: NS a -> NameSupply -> (a, NameSupply) runNS ns supply = runState (runReaderT ns M.empty) supply newName :: NS Name newName = do (name, supply) <- gets getFreshName put supply return name findName :: Name -> NS Name findName name = reader (M.findWithDefault name name) withName :: Name -> Name -> NS a -> NS a withName name name1 = local (M.insert name name1)
meimisaki/Rin
src/Data/NameSupply.hs
Haskell
mit
1,119
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleContexts #-} module EC.ES where import qualified Control.Monad.Primitive as Prim --import qualified System.Random.MWC as MWC import System.Random.MWC import Control.Monad.ST import Control.Monad import Control.Monad.State newtype S s a = S { runS :: StateT (GenST s) (ST s) a } deriving (Monad, MonadState (GenST s)) --init :: S s () --init :: (MonadTrans t, Prim.PrimMonad (ST s), MonadState (GenST s) (t (ST s))) => t (ST s) () --init = lift create >>= put --a :: ST s [Int] --a = do -- gen <- create -- i <- replicateM 10 $ uniform gen -- return (i :: [Int]) --b = do -- i <- a -- j <- a -- return $ i ++ j
banacorn/evolutionary-computation
EC/es.hs
Haskell
mit
705
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} module HepMC.Parse ( module X , tuple, vector, eol , hmcvers, hmcend , xyzt ) where import Control.Applicative as X (many, (<|>)) import Control.Applicative (liftA2) import Control.Monad as X (void) import Data.Attoparsec.ByteString.Char8 as X hiding (parse) import Data.ByteString (ByteString) import Data.HEP.LorentzVector import Data.Vector as X (Vector) import Data.Vector tuple :: Applicative f => f a -> f b -> f (a, b) tuple = liftA2 (,) vector :: Parser a -> Parser (Vector a) vector p = do n <- decimal <* skipSpace replicateM n p eol :: Char -> Bool eol = isEndOfLine . toEnum . fromEnum hmcvers :: Parser (Int, Int, Int) hmcvers = do skipSpace string "HepMC::Version" *> skipSpace x <- decimal <* char '.' y <- decimal <* char '.' z <- decimal <* skipSpace string "HepMC::IO_GenEvent-START_EVENT_LISTING" *> skipSpace return (x, y, z) hmcend :: Parser ByteString hmcend = do _ <- string "HepMC::IO_GenEvent-END_EVENT_LISTING" skipSpace return "end" xyzt :: Parser XYZT xyzt = XYZT <$> double <* skipSpace <*> double <* skipSpace <*> double <* skipSpace <*> double
cspollard/HHepMC
src/HepMC/Parse.hs
Haskell
apache-2.0
1,380
{-# language CPP #-} -- No documentation found for Chapter "ViewStateFlagBits" module OpenXR.Core10.Enums.ViewStateFlagBits ( ViewStateFlags , ViewStateFlagBits( VIEW_STATE_ORIENTATION_VALID_BIT , VIEW_STATE_POSITION_VALID_BIT , VIEW_STATE_ORIENTATION_TRACKED_BIT , VIEW_STATE_POSITION_TRACKED_BIT , .. ) ) where import OpenXR.Internal.Utils (enumReadPrec) import OpenXR.Internal.Utils (enumShowsPrec) import GHC.Show (showString) import Numeric (showHex) import OpenXR.Zero (Zero) import Data.Bits (Bits) import Data.Bits (FiniteBits) import Foreign.Storable (Storable) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) import OpenXR.Core10.FundamentalTypes (Flags64) type ViewStateFlags = ViewStateFlagBits -- No documentation found for TopLevel "XrViewStateFlagBits" newtype ViewStateFlagBits = ViewStateFlagBits Flags64 deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits) -- No documentation found for Nested "XrViewStateFlagBits" "XR_VIEW_STATE_ORIENTATION_VALID_BIT" pattern VIEW_STATE_ORIENTATION_VALID_BIT = ViewStateFlagBits 0x0000000000000001 -- No documentation found for Nested "XrViewStateFlagBits" "XR_VIEW_STATE_POSITION_VALID_BIT" pattern VIEW_STATE_POSITION_VALID_BIT = ViewStateFlagBits 0x0000000000000002 -- No documentation found for Nested "XrViewStateFlagBits" "XR_VIEW_STATE_ORIENTATION_TRACKED_BIT" pattern VIEW_STATE_ORIENTATION_TRACKED_BIT = ViewStateFlagBits 0x0000000000000004 -- No documentation found for Nested "XrViewStateFlagBits" "XR_VIEW_STATE_POSITION_TRACKED_BIT" pattern VIEW_STATE_POSITION_TRACKED_BIT = ViewStateFlagBits 0x0000000000000008 conNameViewStateFlagBits :: String conNameViewStateFlagBits = "ViewStateFlagBits" enumPrefixViewStateFlagBits :: String enumPrefixViewStateFlagBits = "VIEW_STATE_" showTableViewStateFlagBits :: [(ViewStateFlagBits, String)] showTableViewStateFlagBits = [ (VIEW_STATE_ORIENTATION_VALID_BIT , "ORIENTATION_VALID_BIT") , (VIEW_STATE_POSITION_VALID_BIT , "POSITION_VALID_BIT") , (VIEW_STATE_ORIENTATION_TRACKED_BIT, "ORIENTATION_TRACKED_BIT") , (VIEW_STATE_POSITION_TRACKED_BIT , "POSITION_TRACKED_BIT") ] instance Show ViewStateFlagBits where showsPrec = enumShowsPrec enumPrefixViewStateFlagBits showTableViewStateFlagBits conNameViewStateFlagBits (\(ViewStateFlagBits x) -> x) (\x -> showString "0x" . showHex x) instance Read ViewStateFlagBits where readPrec = enumReadPrec enumPrefixViewStateFlagBits showTableViewStateFlagBits conNameViewStateFlagBits ViewStateFlagBits
expipiplus1/vulkan
openxr/src/OpenXR/Core10/Enums/ViewStateFlagBits.hs
Haskell
bsd-3-clause
3,054
-- -- @file -- -- @brief Normalizes RegexTypes -- -- Normalizes a RegexType by applying commutativity of intersection. -- -- @copyright BSD License (see LICENSE.md or https://www.libelektra.org) -- {-# LANGUAGE LambdaCase #-} module Elektra.Normalize (normalize) where import Control.Monad (foldM) import Data.Maybe (maybe, fromJust, fromMaybe) import Data.Either (either) import Data.List (nub, sortBy) import Data.Function (on) import Elektra.Types import qualified FiniteAutomata as FA -- Set intersection is associative and commutative -- Thus we can intersect all concrete regexes in advance -- and leave the remaining intersections in the order that -- variable intersections are first, then a concrete regex -- follows (or another variable) normalize :: RegexType -> IO RegexType normalize i@(RegexIntersection _ _) = either return fold $ collect i ([], []) where fold (ts, ss) = do b <- (\(Right r) -> r) <$> FA.compile ".*" e <- FA.makeBasic FA.Empty s <- case length ss of 0 -> return Nothing 1 -> return . Just $ head ss _ -> let ss' = map (\(Regex _ r) -> r) ss in do s' <- foldM (FA.intersect) (head ss') (tail ss') FA.minimize s' isEmpty <- (\case x | x <= 0 -> False | otherwise -> True) <$> FA.equals e s' if isEmpty then return $ Just EmptyRegex else Just . maybe EmptyRegex (flip Regex s') . rightToMaybe <$> FA.asRegexp s' return $ finalize (sortBy (compare `on` \(RegexVar v) -> v) ts, s) finalize (_, Just EmptyRegex) = EmptyRegex finalize ([], Just sr) = sr finalize (ts, Nothing) = foldTyVars ts finalize (ts, Just sr) = RegexIntersection (foldTyVars ts) sr foldTyVars [] = EmptyRegex foldTyVars [x] = x foldTyVars (t:ts) = RegexIntersection t (foldTyVars ts) collect (RegexIntersection l r) p = collect r =<< collect l p collect r@(Regex _ _) (ts, ss) = Right (ts, r : ss) collect v@(RegexVar _) (ts, ss) = Right (v : ts, ss) collect EmptyRegex _ = Left EmptyRegex normalize r = return r fromRight :: Either a b -> b fromRight (Right b) = b fromRight _ = error "fromRight without right value"
e1528532/libelektra
src/libs/typesystem/specelektra/Elektra/Normalize.hs
Haskell
bsd-3-clause
2,296
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-} module Youtube.Channel ( getChannelId ) where import Network.Wreq import Control.Lens import GHC.Generics import Data.Aeson import Data.Maybe import Prelude hiding (id) import qualified Data.Text as T data ChannelItem = ChannelItem { id :: String } deriving (Show, Generic) data ChannelItemArray = ChannelItemArray { items :: [ChannelItem] } deriving (Show, Generic) instance FromJSON ChannelItem instance FromJSON ChannelItemArray -- todo cache id with name into txt getChannelId :: String -> IO (Maybe String) getChannelId channelName = do let opts = defaults & param "part" .~ ["id"] & param "forUsername" .~ [T.pack channelName] & param "fields" .~ ["items/id"] & param "key" .~ ["AIzaSyClRz-XU6gAt4h-_JRdIA2UIQn8TroxTIk"] r <- asJSON =<< getWith opts "https://www.googleapis.com/youtube/v3/channels" let is = items $ (r ^. responseBody) if length is == 1 then return (Just ((id.head) is)) else return (Nothing)
kelvinlouis/spotell
src/Youtube/Channel.hs
Haskell
bsd-3-clause
1,082
module Utils ( isqrt , numFactors , dataFile ) where import Paths_project_euler isqrt :: Integral i => i -> i isqrt = floor . sqrt . fromIntegral numFactors :: Int -> Int numFactors x = let top = isqrt x nonSquareFactors = [i | i <- [1 .. top], i < top, x `mod` i == 0] addSquareFactor y = if y `mod` top == 0 then y + 1 else y in addSquareFactor . (* 2) . length $ nonSquareFactors dataFile :: String -> IO String dataFile file = do fullPath <- getDataFileName $ "data/" ++ file ++ ".txt" readFile fullPath
anup-2s/project-euler
src/Utils.hs
Haskell
bsd-3-clause
572
{-# LANGUAGE Arrows #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE TypeOperators #-} module Spanout.Gameplay (game) where import Prelude hiding (id, (.)) import Spanout.Common import Spanout.Graphics import Spanout.Level import qualified Spanout.Wire as Wire import Control.Applicative import Control.Arrow import Control.Category import Control.Lens import Control.Monad import Data.Either import Data.Maybe import Data.Monoid import qualified Data.Set as Set import qualified Graphics.Gloss.Interface.IO.Game as Gloss import Linear -- The reactive view of the game game :: a ->> Gloss.Picture game = Wire.bindW gsInit gameBegin where gsInit = do bricks <- generateBricks return GameState { _gsBall = ballInit , _gsBatX = 0 , _gsBricks = bricks } -- Displays the level and a countdown before the actual gameplay gameBegin :: GameState -> a ->> Gloss.Picture gameBegin gsInit = Wire.switch $ proc _ -> do batX <- view _x ^<< mousePos -< () time <- Wire.time -< () let gs = set gsBatX batX gsInit remainingTime = countdownTime - time returnA -< if | remainingTime > 0 -> Right $ gamePic gs <> countdownPic remainingTime | otherwise -> Left $ gameLevel gs -- Gameplay from an initial game state gameLevel :: GameState -> a ->> Gloss.Picture gameLevel gsInit = Wire.switch $ proc _ -> do batX <- view _x ^<< mousePos -< () rec -- Binding previous values ball' <- Wire.delay $ view gsBall gsInit -< ball bricks' <- Wire.delay $ view gsBricks gsInit -< bricks -- Current position pos <- Wire.accum (\dt p v -> p + dt *^ v) $ view (gsBall . ballPos) gsInit -< view ballVel ball' -- Collision and its normal let edgeNormal = ballEdgeNormal pos batNormal = ballBatNormal batX pos ballBrickColl = ballBrickCollision (ball' {_ballPos = pos}) bricks' brickNormals = fst <$> ballBrickColl normal = mfilter (faceAway $ view ballVel ball') . mergeNormalEvents $ maybeToList edgeNormal ++ maybeToList batNormal ++ fromMaybe [] brickNormals -- Current velocity vel <- Wire.accumE reflect $ view (gsBall . ballVel) gsInit -< normal -- Binding current values let ball = Ball pos vel bricks = fromMaybe bricks' (snd <$> ballBrickColl) let gs = GameState {_gsBall = ball, _gsBatX = batX, _gsBricks = bricks} spacePressed <- keyPressed $ Gloss.SpecialKey Gloss.KeySpace -< () returnA -< if | spacePressed -> Left game | null bricks -> Left $ levelEnd gs | view (ballPos . _y) ball <= -screenBoundY - ballRadius -> Left $ gameBegin gsInit | otherwise -> Right $ gamePic gs -- Displays the final game state for some time after the end of the level levelEnd :: GameState -> a ->> Gloss.Picture levelEnd gs = Wire.switch $ Wire.forThen levelEndTime game . pure pic where pic = gamePic gs <> levelEndPic -- The sum of zero or more normals mergeNormalEvents :: (Floating a, Epsilon a) => [V2 a] -> Maybe (V2 a) mergeNormalEvents [] = Nothing mergeNormalEvents normals = Just . normalize $ sum normals -- Collision between the ball and the screen edges ballEdgeNormal :: V2 Float -> Maybe (V2 Float) ballEdgeNormal (V2 px py) | px <= -screenBoundX + ballRadius = Just $ unit _x | px >= screenBoundX - ballRadius = Just $ -unit _x | py >= screenBoundY - ballRadius = Just $ -unit _y | otherwise = Nothing -- Collision between the ball and the bat ballBatNormal :: Float -> V2 Float -> Maybe (V2 Float) ballBatNormal batX (V2 px py) | bxl && bxr && by = Just $ batNormalAt px batX | otherwise = Nothing where bxl = px >= batX - batWidth / 2 bxr = px <= batX + batWidth / 2 by = py <= batPositionY + batHeight / 2 + ballRadius -- Collision between the ball and the bricks. -- Calculates the resulting normals and the remaining bricks. ballBrickCollision :: Ball -> [Brick] -> Maybe ([V2 Float], [Brick]) ballBrickCollision ball bricks = case collisionNormals of [] -> Nothing _ -> Just (collisionNormals, remBricks) where check brick = case ballBrickNormal brick ball of Just normal -> Right normal _ -> Left brick (remBricks, collisionNormals) = partitionEithers . map check $ bricks -- Collision between the ball and a brick ballBrickNormal :: Brick -> Ball -> Maybe (V2 Float) ballBrickNormal (Brick pos (Circle radius)) (Ball bpos _) | hit = Just . normalize $ bpos - pos | otherwise = Nothing where hit = distance bpos pos <= radius + ballRadius ballBrickNormal (Brick pos@(V2 x y) (Rectangle width height)) (Ball bpos bvel) | tooFar = Nothing | hitX = Just normalX | hitY = Just normalY | hitCorner = listToMaybe . filter (faceAway bvel) $ [normalX, normalY] | otherwise = Nothing where dist = bpos - pos V2 distAbsX distAbsY = abs <$> dist V2 ballX ballY = bpos tooFar = distAbsX > width / 2 + ballRadius || distAbsY > height / 2 + ballRadius hitX = distAbsX <= width / 2 hitY = distAbsY <= height / 2 hitCorner = quadrance (V2 (distAbsX - width / 2) (distAbsY - height / 2)) <= ballRadius ^ (2 :: Int) normalX = signum (ballY - y) *^ unit _y normalY = signum (ballX - x) *^ unit _x -- The normal at a point of the bat batNormalAt :: Float -> Float -> V2 Float batNormalAt x batX = perp . angle $ batSpread * relX where relX = (batX - x) / (batWidth / 2) -- Checks if two vectors face away from each other faceAway :: (Num a, Ord a) => V2 a -> V2 a -> Bool faceAway u v = u `dot` v < 0 -- The reflection of a vector based on a normal reflect :: Num a => V2 a -> V2 a -> V2 a reflect v normal = v - (2 * v `dot` normal) *^ normal -- The reactive position of the mouse mousePos :: a ->> V2 Float mousePos = Wire.constM $ view envMouse -- The reactive state of a keyboard button keyPressed :: Gloss.Key -> a ->> Bool keyPressed key = Wire.constM $ views envKeys (Set.member key)
vtan/spanout
src/Spanout/Gameplay.hs
Haskell
bsd-3-clause
6,047
{-# OPTIONS_GHC -fno-warn-orphans -fsimpl-tick-factor=500 #-} module Macro.PkgCereal where import Macro.Types import Data.Serialize as Cereal import Data.ByteString.Lazy as BS serialise :: [GenericPackageDescription] -> BS.ByteString serialise pkgs = Cereal.encodeLazy pkgs deserialise :: BS.ByteString -> [GenericPackageDescription] deserialise = (\(Right x) -> x) . Cereal.decodeLazy deserialiseNull :: BS.ByteString -> () deserialiseNull bs = case Cereal.runGetLazy decodeListNull bs of Right () -> () where decodeListNull = do n <- get :: Get Int go n go 0 = return () go i = do x <- get :: Get GenericPackageDescription x `seq` go (i-1) instance Serialize Version instance Serialize PackageName instance Serialize PackageId instance Serialize VersionRange instance Serialize Dependency instance Serialize CompilerFlavor instance Serialize License instance Serialize SourceRepo instance Serialize RepoKind instance Serialize RepoType instance Serialize BuildType instance Serialize Library instance Serialize Executable instance Serialize TestSuite instance Serialize TestSuiteInterface instance Serialize TestType instance Serialize Benchmark instance Serialize BenchmarkInterface instance Serialize BenchmarkType instance Serialize BuildInfo instance Serialize ModuleName instance Serialize Language instance Serialize Extension instance Serialize KnownExtension instance Serialize PackageDescription instance Serialize OS instance Serialize Arch instance Serialize Flag instance Serialize FlagName instance (Serialize a, Serialize b, Serialize c) => Serialize (CondTree a b c) instance Serialize ConfVar instance Serialize a => Serialize (Condition a) instance Serialize GenericPackageDescription
arianvp/binary-serialise-cbor
bench/Macro/PkgCereal.hs
Haskell
bsd-3-clause
1,759
module Data.SequentialIndex.Open ( SequentialIndex , mantissa , exponent , sequentialIndex , tryFromBools , toClosed , fromClosed , root , leftChild , rightChild , parent , prefixBits , toByteString , fromByteString ) where import Control.Monad import Data.Bits import Data.Maybe import Prelude hiding (exponent) import qualified Data.ByteString as B import qualified Data.SequentialIndex as Closed newtype SequentialIndex = OSI Closed.SequentialIndex deriving (Eq, Ord) mantissa :: SequentialIndex -> Integer mantissa = Closed.mantissa . toClosed exponent :: SequentialIndex -> Int exponent = Closed.exponent . toClosed sequentialIndex :: Int -> Integer -> SequentialIndex sequentialIndex eb me = OSI $ Closed.prefixBits eb me Closed.one tryFromBools :: [Bool] -> Maybe SequentialIndex tryFromBools = fromClosed <=< Closed.tryFromBools toClosed :: SequentialIndex -> Closed.SequentialIndex toClosed (OSI si) = si fromClosed :: Closed.SequentialIndex -> Maybe SequentialIndex fromClosed si = case () of _ | si == Closed.zero -> Nothing | si == Closed.one -> Nothing | otherwise -> Just $ OSI si root :: SequentialIndex root = OSI Closed.root leftChild :: SequentialIndex -> SequentialIndex leftChild = OSI . fromJust . Closed.leftChild . toClosed rightChild :: SequentialIndex -> SequentialIndex rightChild = OSI . fromJust . Closed.rightChild . toClosed parent :: SequentialIndex -> Maybe SequentialIndex parent = fmap OSI . Closed.parent . toClosed prefixBits :: Int -> Integer -> SequentialIndex -> SequentialIndex prefixBits eb mb = OSI . Closed.prefixBits eb mb . toClosed toByteString :: SequentialIndex -> B.ByteString toByteString = Closed.toByteString . toClosed fromByteString :: B.ByteString -> Maybe SequentialIndex fromByteString = fromClosed <=< Closed.fromByteString instance Show SequentialIndex where show si = '*' : map (\i -> if testBit m i then 'R' else 'L') [e - 2, e - 3 .. 1] where m = mantissa si e = exponent si
aristidb/sequential-index
Data/SequentialIndex/Open.hs
Haskell
bsd-3-clause
2,111
module Data.Vhd.Bitmap ( Bitmap (..) , bitmapGet , bitmapSet , bitmapSetRange , bitmapClear ) where import Data.Bits import Data.Word import Foreign.Ptr import Foreign.Storable data Bitmap = Bitmap (Ptr Word8) bitmapGet :: Bitmap -> Int -> IO Bool bitmapGet (Bitmap ptr) n = test `fmap` peekByteOff ptr offset where test :: Word8 -> Bool test = flip testBit (7 - bit) (offset, bit) = n `divMod` 8 bitmapModify :: Bitmap -> Int -> (Int -> Word8 -> Word8) -> IO () bitmapModify (Bitmap bptr) n f = peek ptr >>= poke ptr . f (7 - bit) where ptr = bptr `plusPtr` offset (offset, bit) = n `divMod` 8 bitmapSet :: Bitmap -> Int -> IO () bitmapSet bitmap n = bitmapModify bitmap n (flip setBit) bitmapSetRange :: Bitmap -> Int -> Int -> IO () bitmapSetRange bitmap start end | start < end = bitmapSet bitmap start >> bitmapSetRange bitmap (start + 1) end | otherwise = return () bitmapClear :: Bitmap -> Int -> IO () bitmapClear bitmap n = bitmapModify bitmap n (flip clearBit)
jonathanknowles/hs-vhd
Data/Vhd/Bitmap.hs
Haskell
bsd-3-clause
1,000
module Main where import Test.Framework (defaultMain, testGroup) import qualified Tests.Database.Cassandra.CQL.Protocol as Protocol import qualified Tests.Database.Cassandra.CQL.Protocol.Properties as Properties main :: IO () main = defaultMain tests where tests = [ testGroup "Tests.Database.Cassandra.CQL.Protocol" Protocol.tests , testGroup "Tests.Database.Cassandra.CQL.Protocol.Properties" Properties.tests ]
romanb/cassandra-cql-protocol
test/TestSuite.hs
Haskell
bsd-3-clause
446
-- | Checks for a `Square` being attacked by one of the players. -- -- https://chessprogramming.wikispaces.com/Square+Attacked+By module Chess.Board.Attacks ( isAttacked , attackedFromBB , inCheck , inCheckWithNoFriendly ) where import Data.Monoid import Chess.Board.Board import Chess.Magic import Data.BitBoard import Data.ChessTypes import qualified Data.ChessTypes as T (opponent) import Data.Square ------------------------------------------------------------------------------ -- | are any of the given player's pieces attacking the given square? -- -- Boolean test with sliding piece occupancy testing (magic look up). isAttacked :: Board -> Colour -> Square -> Bool isAttacked b c s = isAttackedWithOccupancy b (occupancy b) c s ------------------------------------------------------------------------------ -- | is the specified player in check? inCheck :: Board -> Colour -> Bool inCheck b c = let kP = head $ toList $ piecesOf b c King in isAttacked b (T.opponent c) kP ------------------------------------------------------------------------------ -- | is the specified player in check with the friendly pieces removed? inCheckWithNoFriendly :: Board -> Colour -> Bool inCheckWithNoFriendly b c = let occ = piecesByColour b (T.opponent c) kP = head $ toList $ piecesOf b c King in isAttackedWithOccupancy b occ (T.opponent c) kP ------------------------------------------------------------------------------ -- Short circuit the Boolean condition. isAttackedWithOccupancy :: Board -> BitBoard -> Colour -> Square -> Bool isAttackedWithOccupancy b occ c s = any (/= mempty) $ attackList [Pawn, Knight, King, Queen, Bishop, Rook] b occ c s ------------------------------------------------------------------------------ -- | Bitboard with the position of the attacking pieces set. Occupancy can be -- specified, ie. we can remove pieces from the board. attackedFromBB :: Board -> BitBoard -> Colour -> Square -> BitBoard attackedFromBB b occ c s = foldr1 (<>) $ attackList [ Queen, Bishop, Rook, Knight, King, Pawn ] b occ c s ------------------------------------------------------------------------------ attackList :: [PieceType] -> Board -> BitBoard -> Colour -> Square -> [BitBoard] attackList l b occ c s = [ attackBitBoard pt s occ c .&. piecesOf b c pt | pt <- l ] ------------------------------------------------------------------------------ attackBitBoard :: PieceType -> Square -> BitBoard -> Colour -> BitBoard attackBitBoard Bishop pos occ _ = {-# SCC attackBitBoardBishop #-} magic Bishop pos occ attackBitBoard Rook pos occ _ = {-# SCC attackBitBoardRook #-} magic Rook pos occ attackBitBoard Queen pos occ c = {-# SCC attackBitBoardQueen #-} attackBitBoard Bishop pos occ c <> attackBitBoard Rook pos occ c attackBitBoard Knight pos _ _ = {-# SCC attackBitBoardKnight #-} knightAttackBB pos attackBitBoard King pos _ _ = {-# SCC attackBitBoardKing #-} kingAttackBB pos attackBitBoard Pawn pos _ c = {-# SCC attackBitBoardPawn #-} pawnAttackBB pos (T.opponent c)
phaul/chess
Chess/Board/Attacks.hs
Haskell
bsd-3-clause
3,121
module Control.ConstraintClasses.KeyZip ( -- * Constraint KeyZip CKeyZip (..) ) where import Control.ConstraintClasses.Domain import Control.ConstraintClasses.Key import Control.ConstraintClasses.KeyFunctor import Control.ConstraintClasses.Zip import Data.Key -- base import Data.Functor.Product import Data.Functor.Sum import Data.Functor.Compose -- vector import qualified Data.Vector as Vector import qualified Data.Vector.Storable as VectorStorable import qualified Data.Vector.Unboxed as VectorUnboxed -------------------------------------------------------------------------------- -- CLASS -------------------------------------------------------------------------------- -- | Equivalent to the @Zip@ class. class (CKeyFunctor f, CZip f) => CKeyZip f where _izipWith :: (Dom f a, Dom f b, Dom f c) => (CKey f -> a -> b -> c) -> f a -> f b -> f c -------------------------------------------------------------------------------- -- INSTANCES -------------------------------------------------------------------------------- -- base -- vector instance CKeyZip VectorStorable.Vector where _izipWith = VectorStorable.izipWith {-# INLINE _izipWith #-} instance CKeyZip VectorUnboxed.Vector where _izipWith = VectorUnboxed.izipWith {-# INLINE _izipWith #-}
guaraqe/constraint-classes
src/Control/ConstraintClasses/KeyZip.hs
Haskell
bsd-3-clause
1,293
module Drones where import qualified Test.HUnit as H import NPNTool.PetriNet import NPNTool.PTConstr import NPNTool.NPNConstr (arcExpr, liftPTC, liftElemNet, addElemNet, NPNConstrM) import qualified NPNTool.NPNConstr as NPC import NPNTool.Graphviz import NPNTool.Bisimilarity import NPNTool.Liveness import NPNTool.AlphaTrail import NPNTool.NPNet import NPNTool.CTL import Control.Monad import Data.List import Data.Maybe data DroneLabels = Leave | Orbit | Attack deriving (Show,Eq,Ord) data V = X | Y | Z deriving (Show,Ord,Eq) drone :: PTConstrM DroneLabels () drone = do [station,air,searching,orbiting,attacking,fin,avoid] <- replicateM 7 mkPlace [leave,orbit,startSearch,start,finish,returnBack,tooClose,continue] <- replicateM 8 mkTrans label leave Leave label orbit Orbit label start Attack arc station leave arc leave air arc air startSearch arc startSearch searching arc searching orbit arc orbit orbiting arc orbiting tooClose arc tooClose avoid arc avoid continue arc continue orbiting arc orbiting start arc start attacking arc attacking finish arc finish fin arc fin returnBack arc returnBack station mark station return () x = Var X y = Var Y z = Var Z droneSystem :: NPNConstrM DroneLabels V [PTPlace] droneSystem = do let n = 3 basePs <- replicateM n NPC.mkPlace leaveTs <- replicateM n NPC.mkTrans airPs <- replicateM n NPC.mkPlace orbitTs <- replicateM n NPC.mkTrans orbitingPs <- replicateM n NPC.mkPlace attack <- NPC.mkTrans finPs <- replicateM n NPC.mkPlace retTs <- replicateM n NPC.mkTrans drones <- replicateM n (NPC.liftElemNet drone) NPC.label attack Attack forM orbitTs (flip NPC.label Orbit) forM leaveTs (flip NPC.label Leave) forM_ (zip basePs drones) $ \(b,d) -> NPC.mark b (Right d) forM_ (zip5 basePs leaveTs airPs orbitTs orbitingPs) $ \(b,l,a,o,orbiting) -> do arcExpr b x l arcExpr l x a arcExpr a x o arcExpr o x orbiting forM_ (zip3 [x,y,z] orbitingPs finPs) $ \(v,orbiting,fin) -> do arcExpr orbiting v attack arcExpr attack v fin forM_ (zip3 finPs retTs basePs) $ \(fin,ret,base) -> do arcExpr fin x ret arcExpr ret x base return basePs droneNet :: NPNet DroneLabels V Int bases :: [PTPlace] (bases,droneNet) = NPC.run (droneSystem) NPC.new sn = net droneNet ss = reachabilityGraph sn ((),droneElemNet, droneL) = runL drone new (atN,atL) = alphaTrail droneNet 1 (nm,rg) = reachabilityGraph' atN droneTest = H.TestCase $ do H.assertBool "Normal agent liveness" $ isLive (reachabilityGraph droneElemNet) droneElemNet H.assertBool "System net liveness" $ isLive ss sn mapM_ (H.assertBool "Agent is m-bisimilar to the alpha-trail net" . isJust . isMBisim (droneElemNet,droneL) . alphaTrail droneNet) bases return () droneTestXML = H.TestCase $ do npn <- runConstr "./test/Drones.npnets" -- [base,air,orbiting,fin] <- replicateM 4 NPC.mkPlace -- [leave,orbit,attack,ret] <- replicateM 4 NPC.mkTrans -- arcExpr base x leave -- arcExpr leave x air -- arcExpr air x orbit -- arcExpr orbit x orbiting -- arcExpr orbiting x attack -- arcExpr attack x fin -- arcExpr fin x ret -- arcExpr ret x base -- NPC.label attack Attack -- d1 <- NPC.liftElemNet drone -- NPC.mark base (Right d1) -- return [base] -- if (null nodes) then do -- trace "sim1" $ return () -- traceShow l $ return () -- traceShow m1 $ traceShow m2 $ return () -- else return ()
co-dan/NPNTool
tests/Drones.hs
Haskell
bsd-3-clause
3,560
-- | The code that powers the searchbox. module Guide.Search ( SearchResult(..), search, ) where import Imports -- Text import qualified Data.Text.All as T -- Sets import qualified Data.Set as S import Guide.Types import Guide.State import Guide.Markdown -- | A search result. data SearchResult -- | Category's title matches the query = SRCategory Category -- | Item's name matches the query | SRItem Category Item -- | Item's ecosystem matches the query | SRItemEcosystem Category Item deriving (Show, Generic) {- | Find things matching a simple text query, and return results ranked by importance. Categories are considered more important than items. Currently 'search' doesn't do any fuzzy search whatsoever – only direct word matches are considered. See 'match' for the description of the matching algorithm. -} search :: Text -> GlobalState -> [SearchResult] search query gs = -- category titles sortByRank [(SRCategory cat, rank) | cat <- gs^.categories , let rank = match query (cat^.title) , rank > 0 ] ++ -- item names sortByRank [(SRItem cat item, rank) | cat <- gs^.categories , item <- cat^.items , let rank = match query (item^.name) , rank > 0 ] ++ -- item ecosystems sortByRank [(SRItemEcosystem cat item, rank) | cat <- gs^.categories , item <- cat^.items , let rank = match query (item^.ecosystem.mdSource) , rank > 0 ] where sortByRank :: [(a, Int)] -> [a] sortByRank = map fst . sortOn (Down . snd) {- | How many words in two strings match? Words are defined as sequences of letters, digits and characters like “-”; separators are everything else. Comparisons are case-insensitive. -} match :: Text -> Text -> Int match a b = common (getWords a) (getWords b) where isWordPart c = isLetter c || isDigit c || c == '-' getWords = map T.toTitle . filter (not . T.null) . T.split (not . isWordPart) -- | Find how many elements two lists have in common. common :: Ord a => [a] -> [a] -> Int common a b = S.size (S.intersection (S.fromList a) (S.fromList b))
aelve/hslibs
src/Guide/Search.hs
Haskell
bsd-3-clause
2,257
{- (c) The University of Glasgow, 2006 \section[HscTypes]{Types for the per-module compiler} -} {-# LANGUAGE CPP, ScopedTypeVariables #-} -- | Types for the per-module compiler module HscTypes ( -- * compilation state HscEnv(..), hscEPS, FinderCache, FindResult(..), Target(..), TargetId(..), pprTarget, pprTargetId, ModuleGraph, emptyMG, HscStatus(..), #ifdef GHCI IServ(..), #endif -- * Hsc monad Hsc(..), runHsc, runInteractiveHsc, -- * Information about modules ModDetails(..), emptyModDetails, ModGuts(..), CgGuts(..), ForeignStubs(..), appendStubC, ImportedMods, ImportedModsVal(..), ModSummary(..), ms_imps, ms_mod_name, showModMsg, isBootSummary, msHsFilePath, msHiFilePath, msObjFilePath, SourceModified(..), -- * Information about the module being compiled -- (re-exported from DriverPhases) HscSource(..), isHsBootOrSig, hscSourceString, -- * State relating to modules in this package HomePackageTable, HomeModInfo(..), emptyHomePackageTable, hptInstances, hptRules, hptVectInfo, pprHPT, hptObjs, -- * State relating to known packages ExternalPackageState(..), EpsStats(..), addEpsInStats, PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable, lookupIfaceByModule, emptyModIface, lookupHptByModule, PackageInstEnv, PackageFamInstEnv, PackageRuleBase, mkSOName, mkHsSOName, soExt, -- * Metaprogramming MetaRequest(..), MetaResult, -- data constructors not exported to ensure correct response type metaRequestE, metaRequestP, metaRequestT, metaRequestD, metaRequestAW, MetaHook, -- * Annotations prepareAnnotations, -- * Interactive context InteractiveContext(..), emptyInteractiveContext, icPrintUnqual, icInScopeTTs, icExtendGblRdrEnv, extendInteractiveContext, extendInteractiveContextWithIds, substInteractiveContext, setInteractivePrintName, icInteractiveModule, InteractiveImport(..), setInteractivePackage, mkPrintUnqualified, pprModulePrefix, mkQualPackage, mkQualModule, pkgQual, -- * Interfaces ModIface(..), mkIfaceWarnCache, mkIfaceHashCache, mkIfaceFixCache, emptyIfaceWarnCache, mi_boot, mi_fix, -- * Fixity FixityEnv, FixItem(..), lookupFixity, emptyFixityEnv, -- * TyThings and type environments TyThing(..), tyThingAvailInfo, tyThingTyCon, tyThingDataCon, tyThingId, tyThingCoAxiom, tyThingParent_maybe, tyThingsTyCoVars, implicitTyThings, implicitTyConThings, implicitClassThings, isImplicitTyThing, TypeEnv, lookupType, lookupTypeHscEnv, mkTypeEnv, emptyTypeEnv, typeEnvFromEntities, mkTypeEnvWithImplicits, extendTypeEnv, extendTypeEnvList, extendTypeEnvWithIds, lookupTypeEnv, typeEnvElts, typeEnvTyCons, typeEnvIds, typeEnvPatSyns, typeEnvDataCons, typeEnvCoAxioms, typeEnvClasses, -- * MonadThings MonadThings(..), -- * Information on imports and exports WhetherHasOrphans, IsBootInterface, Usage(..), Dependencies(..), noDependencies, NameCache(..), OrigNameCache, updNameCacheIO, IfaceExport, -- * Warnings Warnings(..), WarningTxt(..), plusWarns, -- * Linker stuff Linkable(..), isObjectLinkable, linkableObjs, Unlinked(..), CompiledByteCode, isObject, nameOfObject, isInterpretable, byteCodeOfObject, -- * Program coverage HpcInfo(..), emptyHpcInfo, isHpcUsed, AnyHpcUsage, -- * Breakpoints ModBreaks (..), emptyModBreaks, -- * Vectorisation information VectInfo(..), IfaceVectInfo(..), noVectInfo, plusVectInfo, noIfaceVectInfo, isNoIfaceVectInfo, -- * Safe Haskell information IfaceTrustInfo, getSafeMode, setSafeMode, noIfaceTrustInfo, trustInfoToNum, numToTrustInfo, IsSafeImport, -- * result of the parser HsParsedModule(..), -- * Compilation errors and warnings SourceError, GhcApiError, mkSrcErr, srcErrorMessages, mkApiErr, throwOneError, handleSourceError, handleFlagWarnings, printOrThrowWarnings, ) where #include "HsVersions.h" #ifdef GHCI import ByteCodeTypes import InteractiveEvalTypes ( Resume ) import GHCi.Message ( Pipe ) import GHCi.RemoteTypes #endif import HsSyn import RdrName import Avail import Module import InstEnv ( InstEnv, ClsInst, identicalClsInstHead ) import FamInstEnv import CoreSyn ( CoreProgram, RuleBase ) import Name import NameEnv import NameSet import VarEnv import VarSet import Var import Id import IdInfo ( IdDetails(..), RecSelParent(..)) import Type import ApiAnnotation ( ApiAnns ) import Annotations ( Annotation, AnnEnv, mkAnnEnv, plusAnnEnv ) import Class import TyCon import CoAxiom import ConLike import DataCon import PatSyn import PrelNames ( gHC_PRIM, ioTyConName, printName, mkInteractiveModule , eqTyConName ) import TysWiredIn import Packages hiding ( Version(..) ) import DynFlags import DriverPhases ( Phase, HscSource(..), isHsBootOrSig, hscSourceString ) import BasicTypes import IfaceSyn import CoreSyn ( CoreRule, CoreVect ) import Maybes import Outputable import SrcLoc -- import Unique import UniqFM import UniqSupply import FastString import StringBuffer ( StringBuffer ) import Fingerprint import MonadUtils import Bag import Binary import ErrUtils import Platform import Util import GHC.Serialized ( Serialized ) import Foreign import Control.Monad ( guard, liftM, when, ap ) import Data.IORef import Data.Time import Exception import System.FilePath #ifdef GHCI import Control.Concurrent import System.Process ( ProcessHandle ) #endif -- ----------------------------------------------------------------------------- -- Compilation state -- ----------------------------------------------------------------------------- -- | Status of a compilation to hard-code data HscStatus = HscNotGeneratingCode | HscUpToDate | HscUpdateBoot | HscUpdateSig | HscRecomp CgGuts ModSummary -- ----------------------------------------------------------------------------- -- The Hsc monad: Passing an environment and warning state newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages)) instance Functor Hsc where fmap = liftM instance Applicative Hsc where pure a = Hsc $ \_ w -> return (a, w) (<*>) = ap instance Monad Hsc where Hsc m >>= k = Hsc $ \e w -> do (a, w1) <- m e w case k a of Hsc k' -> k' e w1 instance MonadIO Hsc where liftIO io = Hsc $ \_ w -> do a <- io; return (a, w) instance HasDynFlags Hsc where getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w) runHsc :: HscEnv -> Hsc a -> IO a runHsc hsc_env (Hsc hsc) = do (a, w) <- hsc hsc_env emptyBag printOrThrowWarnings (hsc_dflags hsc_env) w return a runInteractiveHsc :: HscEnv -> Hsc a -> IO a -- A variant of runHsc that switches in the DynFlags from the -- InteractiveContext before running the Hsc computation. runInteractiveHsc hsc_env = runHsc (hsc_env { hsc_dflags = interactive_dflags }) where interactive_dflags = ic_dflags (hsc_IC hsc_env) -- ----------------------------------------------------------------------------- -- Source Errors -- When the compiler (HscMain) discovers errors, it throws an -- exception in the IO monad. mkSrcErr :: ErrorMessages -> SourceError mkSrcErr = SourceError srcErrorMessages :: SourceError -> ErrorMessages srcErrorMessages (SourceError msgs) = msgs mkApiErr :: DynFlags -> SDoc -> GhcApiError mkApiErr dflags msg = GhcApiError (showSDoc dflags msg) throwOneError :: MonadIO m => ErrMsg -> m ab throwOneError err = liftIO $ throwIO $ mkSrcErr $ unitBag err -- | A source error is an error that is caused by one or more errors in the -- source code. A 'SourceError' is thrown by many functions in the -- compilation pipeline. Inside GHC these errors are merely printed via -- 'log_action', but API clients may treat them differently, for example, -- insert them into a list box. If you want the default behaviour, use the -- idiom: -- -- > handleSourceError printExceptionAndWarnings $ do -- > ... api calls that may fail ... -- -- The 'SourceError's error messages can be accessed via 'srcErrorMessages'. -- This list may be empty if the compiler failed due to @-Werror@ -- ('Opt_WarnIsError'). -- -- See 'printExceptionAndWarnings' for more information on what to take care -- of when writing a custom error handler. newtype SourceError = SourceError ErrorMessages instance Show SourceError where show (SourceError msgs) = unlines . map show . bagToList $ msgs instance Exception SourceError -- | Perform the given action and call the exception handler if the action -- throws a 'SourceError'. See 'SourceError' for more information. handleSourceError :: (ExceptionMonad m) => (SourceError -> m a) -- ^ exception handler -> m a -- ^ action to perform -> m a handleSourceError handler act = gcatch act (\(e :: SourceError) -> handler e) -- | An error thrown if the GHC API is used in an incorrect fashion. newtype GhcApiError = GhcApiError String instance Show GhcApiError where show (GhcApiError msg) = msg instance Exception GhcApiError -- | Given a bag of warnings, turn them into an exception if -- -Werror is enabled, or print them out otherwise. printOrThrowWarnings :: DynFlags -> Bag WarnMsg -> IO () printOrThrowWarnings dflags warns | gopt Opt_WarnIsError dflags = when (not (isEmptyBag warns)) $ do throwIO $ mkSrcErr $ warns `snocBag` warnIsErrorMsg dflags | otherwise = printBagOfErrors dflags warns handleFlagWarnings :: DynFlags -> [Located String] -> IO () handleFlagWarnings dflags warns = when (wopt Opt_WarnDeprecatedFlags dflags) $ do -- It would be nicer if warns :: [Located MsgDoc], but that -- has circular import problems. let bag = listToBag [ mkPlainWarnMsg dflags loc (text warn) | L loc warn <- warns ] printOrThrowWarnings dflags bag {- ************************************************************************ * * \subsection{HscEnv} * * ************************************************************************ -} -- | HscEnv is like 'Session', except that some of the fields are immutable. -- An HscEnv is used to compile a single module from plain Haskell source -- code (after preprocessing) to either C, assembly or C--. Things like -- the module graph don't change during a single compilation. -- -- Historical note: \"hsc\" used to be the name of the compiler binary, -- when there was a separate driver and compiler. To compile a single -- module, the driver would invoke hsc on the source code... so nowadays -- we think of hsc as the layer of the compiler that deals with compiling -- a single module. data HscEnv = HscEnv { hsc_dflags :: DynFlags, -- ^ The dynamic flag settings hsc_targets :: [Target], -- ^ The targets (or roots) of the current session hsc_mod_graph :: ModuleGraph, -- ^ The module graph of the current session hsc_IC :: InteractiveContext, -- ^ The context for evaluating interactive statements hsc_HPT :: HomePackageTable, -- ^ The home package table describes already-compiled -- home-package modules, /excluding/ the module we -- are compiling right now. -- (In one-shot mode the current module is the only -- home-package module, so hsc_HPT is empty. All other -- modules count as \"external-package\" modules. -- However, even in GHCi mode, hi-boot interfaces are -- demand-loaded into the external-package table.) -- -- 'hsc_HPT' is not mutable because we only demand-load -- external packages; the home package is eagerly -- loaded, module by module, by the compilation manager. -- -- The HPT may contain modules compiled earlier by @--make@ -- but not actually below the current module in the dependency -- graph. -- -- (This changes a previous invariant: changed Jan 05.) hsc_EPS :: {-# UNPACK #-} !(IORef ExternalPackageState), -- ^ Information about the currently loaded external packages. -- This is mutable because packages will be demand-loaded during -- a compilation run as required. hsc_NC :: {-# UNPACK #-} !(IORef NameCache), -- ^ As with 'hsc_EPS', this is side-effected by compiling to -- reflect sucking in interface files. They cache the state of -- external interface files, in effect. hsc_FC :: {-# UNPACK #-} !(IORef FinderCache), -- ^ The cached result of performing finding in the file system hsc_type_env_var :: Maybe (Module, IORef TypeEnv) -- ^ Used for one-shot compilation only, to initialise -- the 'IfGblEnv'. See 'TcRnTypes.tcg_type_env_var' for -- 'TcRnTypes.TcGblEnv' #ifdef GHCI , hsc_iserv :: MVar (Maybe IServ) -- ^ interactive server process. Created the first -- time it is needed. #endif } #ifdef GHCI data IServ = IServ { iservPipe :: Pipe , iservProcess :: ProcessHandle , iservLookupSymbolCache :: IORef (UniqFM (Ptr ())) , iservPendingFrees :: [HValueRef] } #endif -- | Retrieve the ExternalPackageState cache. hscEPS :: HscEnv -> IO ExternalPackageState hscEPS hsc_env = readIORef (hsc_EPS hsc_env) -- | A compilation target. -- -- A target may be supplied with the actual text of the -- module. If so, use this instead of the file contents (this -- is for use in an IDE where the file hasn't been saved by -- the user yet). data Target = Target { targetId :: TargetId, -- ^ module or filename targetAllowObjCode :: Bool, -- ^ object code allowed? targetContents :: Maybe (StringBuffer,UTCTime) -- ^ in-memory text buffer? } data TargetId = TargetModule ModuleName -- ^ A module name: search for the file | TargetFile FilePath (Maybe Phase) -- ^ A filename: preprocess & parse it to find the module name. -- If specified, the Phase indicates how to compile this file -- (which phase to start from). Nothing indicates the starting phase -- should be determined from the suffix of the filename. deriving Eq pprTarget :: Target -> SDoc pprTarget (Target id obj _) = (if obj then char '*' else empty) <> pprTargetId id instance Outputable Target where ppr = pprTarget pprTargetId :: TargetId -> SDoc pprTargetId (TargetModule m) = ppr m pprTargetId (TargetFile f _) = text f instance Outputable TargetId where ppr = pprTargetId {- ************************************************************************ * * \subsection{Package and Module Tables} * * ************************************************************************ -} -- | Helps us find information about modules in the home package type HomePackageTable = ModuleNameEnv HomeModInfo -- Domain = modules in the home package that have been fully compiled -- "home" unit id cached here for convenience -- | Helps us find information about modules in the imported packages type PackageIfaceTable = ModuleEnv ModIface -- Domain = modules in the imported packages -- | Constructs an empty HomePackageTable emptyHomePackageTable :: HomePackageTable emptyHomePackageTable = emptyUFM -- | Constructs an empty PackageIfaceTable emptyPackageIfaceTable :: PackageIfaceTable emptyPackageIfaceTable = emptyModuleEnv pprHPT :: HomePackageTable -> SDoc -- A bit aribitrary for now pprHPT hpt = pprUFM hpt $ \hms -> vcat [ hang (ppr (mi_module (hm_iface hm))) 2 (ppr (md_types (hm_details hm))) | hm <- hms ] lookupHptByModule :: HomePackageTable -> Module -> Maybe HomeModInfo -- The HPT is indexed by ModuleName, not Module, -- we must check for a hit on the right Module lookupHptByModule hpt mod = case lookupUFM hpt (moduleName mod) of Just hm | mi_module (hm_iface hm) == mod -> Just hm _otherwise -> Nothing -- | Information about modules in the package being compiled data HomeModInfo = HomeModInfo { hm_iface :: !ModIface, -- ^ The basic loaded interface file: every loaded module has one of -- these, even if it is imported from another package hm_details :: !ModDetails, -- ^ Extra information that has been created from the 'ModIface' for -- the module, typically during typechecking hm_linkable :: !(Maybe Linkable) -- ^ The actual artifact we would like to link to access things in -- this module. -- -- 'hm_linkable' might be Nothing: -- -- 1. If this is an .hs-boot module -- -- 2. Temporarily during compilation if we pruned away -- the old linkable because it was out of date. -- -- After a complete compilation ('GHC.load'), all 'hm_linkable' fields -- in the 'HomePackageTable' will be @Just@. -- -- When re-linking a module ('HscMain.HscNoRecomp'), we construct the -- 'HomeModInfo' by building a new 'ModDetails' from the old -- 'ModIface' (only). } -- | Find the 'ModIface' for a 'Module', searching in both the loaded home -- and external package module information lookupIfaceByModule :: DynFlags -> HomePackageTable -> PackageIfaceTable -> Module -> Maybe ModIface lookupIfaceByModule _dflags hpt pit mod = case lookupHptByModule hpt mod of Just hm -> Just (hm_iface hm) Nothing -> lookupModuleEnv pit mod -- If the module does come from the home package, why do we look in the PIT as well? -- (a) In OneShot mode, even home-package modules accumulate in the PIT -- (b) Even in Batch (--make) mode, there is *one* case where a home-package -- module is in the PIT, namely GHC.Prim when compiling the base package. -- We could eliminate (b) if we wanted, by making GHC.Prim belong to a package -- of its own, but it doesn't seem worth the bother. -- | Find all the instance declarations (of classes and families) from -- the Home Package Table filtered by the provided predicate function. -- Used in @tcRnImports@, to select the instances that are in the -- transitive closure of imports from the currently compiled module. hptInstances :: HscEnv -> (ModuleName -> Bool) -> ([ClsInst], [FamInst]) hptInstances hsc_env want_this_module = let (insts, famInsts) = unzip $ flip hptAllThings hsc_env $ \mod_info -> do guard (want_this_module (moduleName (mi_module (hm_iface mod_info)))) let details = hm_details mod_info return (md_insts details, md_fam_insts details) in (concat insts, concat famInsts) -- | Get the combined VectInfo of all modules in the home package table. In -- contrast to instances and rules, we don't care whether the modules are -- "below" us in the dependency sense. The VectInfo of those modules not "below" -- us does not affect the compilation of the current module. hptVectInfo :: HscEnv -> VectInfo hptVectInfo = concatVectInfo . hptAllThings ((: []) . md_vect_info . hm_details) -- | Get rules from modules "below" this one (in the dependency sense) hptRules :: HscEnv -> [(ModuleName, IsBootInterface)] -> [CoreRule] hptRules = hptSomeThingsBelowUs (md_rules . hm_details) False -- | Get annotations from modules "below" this one (in the dependency sense) hptAnns :: HscEnv -> Maybe [(ModuleName, IsBootInterface)] -> [Annotation] hptAnns hsc_env (Just deps) = hptSomeThingsBelowUs (md_anns . hm_details) False hsc_env deps hptAnns hsc_env Nothing = hptAllThings (md_anns . hm_details) hsc_env hptAllThings :: (HomeModInfo -> [a]) -> HscEnv -> [a] hptAllThings extract hsc_env = concatMap extract (eltsUFM (hsc_HPT hsc_env)) -- | Get things from modules "below" this one (in the dependency sense) -- C.f Inst.hptInstances hptSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> HscEnv -> [(ModuleName, IsBootInterface)] -> [a] hptSomeThingsBelowUs extract include_hi_boot hsc_env deps | isOneShot (ghcMode (hsc_dflags hsc_env)) = [] | otherwise = let hpt = hsc_HPT hsc_env in [ thing | -- Find each non-hi-boot module below me (mod, is_boot_mod) <- deps , include_hi_boot || not is_boot_mod -- unsavoury: when compiling the base package with --make, we -- sometimes try to look up RULES etc for GHC.Prim. GHC.Prim won't -- be in the HPT, because we never compile it; it's in the EPT -- instead. ToDo: clean up, and remove this slightly bogus filter: , mod /= moduleName gHC_PRIM -- Look it up in the HPT , let things = case lookupUFM hpt mod of Just info -> extract info Nothing -> pprTrace "WARNING in hptSomeThingsBelowUs" msg [] msg = vcat [text "missing module" <+> ppr mod, text "Probable cause: out-of-date interface files"] -- This really shouldn't happen, but see Trac #962 -- And get its dfuns , thing <- things ] hptObjs :: HomePackageTable -> [FilePath] hptObjs hpt = concat (map (maybe [] linkableObjs . hm_linkable) (eltsUFM hpt)) {- ************************************************************************ * * \subsection{Metaprogramming} * * ************************************************************************ -} -- | The supported metaprogramming result types data MetaRequest = MetaE (LHsExpr RdrName -> MetaResult) | MetaP (LPat RdrName -> MetaResult) | MetaT (LHsType RdrName -> MetaResult) | MetaD ([LHsDecl RdrName] -> MetaResult) | MetaAW (Serialized -> MetaResult) -- | data constructors not exported to ensure correct result type data MetaResult = MetaResE { unMetaResE :: LHsExpr RdrName } | MetaResP { unMetaResP :: LPat RdrName } | MetaResT { unMetaResT :: LHsType RdrName } | MetaResD { unMetaResD :: [LHsDecl RdrName] } | MetaResAW { unMetaResAW :: Serialized } type MetaHook f = MetaRequest -> LHsExpr Id -> f MetaResult metaRequestE :: Functor f => MetaHook f -> LHsExpr Id -> f (LHsExpr RdrName) metaRequestE h = fmap unMetaResE . h (MetaE MetaResE) metaRequestP :: Functor f => MetaHook f -> LHsExpr Id -> f (LPat RdrName) metaRequestP h = fmap unMetaResP . h (MetaP MetaResP) metaRequestT :: Functor f => MetaHook f -> LHsExpr Id -> f (LHsType RdrName) metaRequestT h = fmap unMetaResT . h (MetaT MetaResT) metaRequestD :: Functor f => MetaHook f -> LHsExpr Id -> f [LHsDecl RdrName] metaRequestD h = fmap unMetaResD . h (MetaD MetaResD) metaRequestAW :: Functor f => MetaHook f -> LHsExpr Id -> f Serialized metaRequestAW h = fmap unMetaResAW . h (MetaAW MetaResAW) {- ************************************************************************ * * \subsection{Dealing with Annotations} * * ************************************************************************ -} -- | Deal with gathering annotations in from all possible places -- and combining them into a single 'AnnEnv' prepareAnnotations :: HscEnv -> Maybe ModGuts -> IO AnnEnv prepareAnnotations hsc_env mb_guts = do eps <- hscEPS hsc_env let -- Extract annotations from the module being compiled if supplied one mb_this_module_anns = fmap (mkAnnEnv . mg_anns) mb_guts -- Extract dependencies of the module if we are supplied one, -- otherwise load annotations from all home package table -- entries regardless of dependency ordering. home_pkg_anns = (mkAnnEnv . hptAnns hsc_env) $ fmap (dep_mods . mg_deps) mb_guts other_pkg_anns = eps_ann_env eps ann_env = foldl1' plusAnnEnv $ catMaybes [mb_this_module_anns, Just home_pkg_anns, Just other_pkg_anns] return ann_env {- ************************************************************************ * * \subsection{The Finder cache} * * ************************************************************************ -} -- | The 'FinderCache' maps modules to the result of -- searching for that module. It records the results of searching for -- modules along the search path. On @:load@, we flush the entire -- contents of this cache. -- -- Although the @FinderCache@ range is 'FindResult' for convenience, -- in fact it will only ever contain 'Found' or 'NotFound' entries. -- type FinderCache = ModuleEnv FindResult -- | The result of searching for an imported module. data FindResult = Found ModLocation Module -- ^ The module was found | NoPackage UnitId -- ^ The requested package was not found | FoundMultiple [(Module, ModuleOrigin)] -- ^ _Error_: both in multiple packages -- | Not found | NotFound { fr_paths :: [FilePath] -- Places where I looked , fr_pkg :: Maybe UnitId -- Just p => module is in this package's -- manifest, but couldn't find -- the .hi file , fr_mods_hidden :: [UnitId] -- Module is in these packages, -- but the *module* is hidden , fr_pkgs_hidden :: [UnitId] -- Module is in these packages, -- but the *package* is hidden , fr_suggestions :: [ModuleSuggestion] -- Possible mis-spelled modules } {- ************************************************************************ * * \subsection{Symbol tables and Module details} * * ************************************************************************ -} -- | A 'ModIface' plus a 'ModDetails' summarises everything we know -- about a compiled module. The 'ModIface' is the stuff *before* linking, -- and can be written out to an interface file. The 'ModDetails is after -- linking and can be completely recovered from just the 'ModIface'. -- -- When we read an interface file, we also construct a 'ModIface' from it, -- except that we explicitly make the 'mi_decls' and a few other fields empty; -- as when reading we consolidate the declarations etc. into a number of indexed -- maps and environments in the 'ExternalPackageState'. data ModIface = ModIface { mi_module :: !Module, -- ^ Name of the module we are for mi_sig_of :: !(Maybe Module), -- ^ Are we a sig of another mod? mi_iface_hash :: !Fingerprint, -- ^ Hash of the whole interface mi_mod_hash :: !Fingerprint, -- ^ Hash of the ABI only mi_flag_hash :: !Fingerprint, -- ^ Hash of the important flags -- used when compiling this module mi_orphan :: !WhetherHasOrphans, -- ^ Whether this module has orphans mi_finsts :: !WhetherHasFamInst, -- ^ Whether this module has family instances mi_hsc_src :: !HscSource, -- ^ Boot? Signature? mi_deps :: Dependencies, -- ^ The dependencies of the module. This is -- consulted for directly-imported modules, but not -- for anything else (hence lazy) mi_usages :: [Usage], -- ^ Usages; kept sorted so that it's easy to decide -- whether to write a new iface file (changing usages -- doesn't affect the hash of this module) -- NOT STRICT! we read this field lazily from the interface file -- It is *only* consulted by the recompilation checker mi_exports :: ![IfaceExport], -- ^ Exports -- Kept sorted by (mod,occ), to make version comparisons easier -- Records the modules that are the declaration points for things -- exported by this module, and the 'OccName's of those things mi_exp_hash :: !Fingerprint, -- ^ Hash of export list mi_used_th :: !Bool, -- ^ Module required TH splices when it was compiled. -- This disables recompilation avoidance (see #481). mi_fixities :: [(OccName,Fixity)], -- ^ Fixities -- NOT STRICT! we read this field lazily from the interface file mi_warns :: Warnings, -- ^ Warnings -- NOT STRICT! we read this field lazily from the interface file mi_anns :: [IfaceAnnotation], -- ^ Annotations -- NOT STRICT! we read this field lazily from the interface file mi_decls :: [(Fingerprint,IfaceDecl)], -- ^ Type, class and variable declarations -- The hash of an Id changes if its fixity or deprecations change -- (as well as its type of course) -- Ditto data constructors, class operations, except that -- the hash of the parent class/tycon changes mi_globals :: !(Maybe GlobalRdrEnv), -- ^ Binds all the things defined at the top level in -- the /original source/ code for this module. which -- is NOT the same as mi_exports, nor mi_decls (which -- may contains declarations for things not actually -- defined by the user). Used for GHCi and for inspecting -- the contents of modules via the GHC API only. -- -- (We need the source file to figure out the -- top-level environment, if we didn't compile this module -- from source then this field contains @Nothing@). -- -- Strictly speaking this field should live in the -- 'HomeModInfo', but that leads to more plumbing. -- Instance declarations and rules mi_insts :: [IfaceClsInst], -- ^ Sorted class instance mi_fam_insts :: [IfaceFamInst], -- ^ Sorted family instances mi_rules :: [IfaceRule], -- ^ Sorted rules mi_orphan_hash :: !Fingerprint, -- ^ Hash for orphan rules, class and family -- instances, and vectorise pragmas combined mi_vect_info :: !IfaceVectInfo, -- ^ Vectorisation information -- Cached environments for easy lookup -- These are computed (lazily) from other fields -- and are not put into the interface file mi_warn_fn :: OccName -> Maybe WarningTxt, -- ^ Cached lookup for 'mi_warns' mi_fix_fn :: OccName -> Maybe Fixity, -- ^ Cached lookup for 'mi_fixities' mi_hash_fn :: OccName -> Maybe (OccName, Fingerprint), -- ^ Cached lookup for 'mi_decls'. -- The @Nothing@ in 'mi_hash_fn' means that the thing -- isn't in decls. It's useful to know that when -- seeing if we are up to date wrt. the old interface. -- The 'OccName' is the parent of the name, if it has one. mi_hpc :: !AnyHpcUsage, -- ^ True if this program uses Hpc at any point in the program. mi_trust :: !IfaceTrustInfo, -- ^ Safe Haskell Trust information for this module. mi_trust_pkg :: !Bool -- ^ Do we require the package this module resides in be trusted -- to trust this module? This is used for the situation where a -- module is Safe (so doesn't require the package be trusted -- itself) but imports some trustworthy modules from its own -- package (which does require its own package be trusted). -- See Note [RnNames . Trust Own Package] } -- | Old-style accessor for whether or not the ModIface came from an hs-boot -- file. mi_boot :: ModIface -> Bool mi_boot iface = mi_hsc_src iface == HsBootFile -- | Lookups up a (possibly cached) fixity from a 'ModIface'. If one cannot be -- found, 'defaultFixity' is returned instead. mi_fix :: ModIface -> OccName -> Fixity mi_fix iface name = mi_fix_fn iface name `orElse` defaultFixity instance Binary ModIface where put_ bh (ModIface { mi_module = mod, mi_sig_of = sig_of, mi_hsc_src = hsc_src, mi_iface_hash= iface_hash, mi_mod_hash = mod_hash, mi_flag_hash = flag_hash, mi_orphan = orphan, mi_finsts = hasFamInsts, mi_deps = deps, mi_usages = usages, mi_exports = exports, mi_exp_hash = exp_hash, mi_used_th = used_th, mi_fixities = fixities, mi_warns = warns, mi_anns = anns, mi_decls = decls, mi_insts = insts, mi_fam_insts = fam_insts, mi_rules = rules, mi_orphan_hash = orphan_hash, mi_vect_info = vect_info, mi_hpc = hpc_info, mi_trust = trust, mi_trust_pkg = trust_pkg }) = do put_ bh mod put_ bh hsc_src put_ bh iface_hash put_ bh mod_hash put_ bh flag_hash put_ bh orphan put_ bh hasFamInsts lazyPut bh deps lazyPut bh usages put_ bh exports put_ bh exp_hash put_ bh used_th put_ bh fixities lazyPut bh warns lazyPut bh anns put_ bh decls put_ bh insts put_ bh fam_insts lazyPut bh rules put_ bh orphan_hash put_ bh vect_info put_ bh hpc_info put_ bh trust put_ bh trust_pkg put_ bh sig_of get bh = do mod_name <- get bh hsc_src <- get bh iface_hash <- get bh mod_hash <- get bh flag_hash <- get bh orphan <- get bh hasFamInsts <- get bh deps <- lazyGet bh usages <- {-# SCC "bin_usages" #-} lazyGet bh exports <- {-# SCC "bin_exports" #-} get bh exp_hash <- get bh used_th <- get bh fixities <- {-# SCC "bin_fixities" #-} get bh warns <- {-# SCC "bin_warns" #-} lazyGet bh anns <- {-# SCC "bin_anns" #-} lazyGet bh decls <- {-# SCC "bin_tycldecls" #-} get bh insts <- {-# SCC "bin_insts" #-} get bh fam_insts <- {-# SCC "bin_fam_insts" #-} get bh rules <- {-# SCC "bin_rules" #-} lazyGet bh orphan_hash <- get bh vect_info <- get bh hpc_info <- get bh trust <- get bh trust_pkg <- get bh sig_of <- get bh return (ModIface { mi_module = mod_name, mi_sig_of = sig_of, mi_hsc_src = hsc_src, mi_iface_hash = iface_hash, mi_mod_hash = mod_hash, mi_flag_hash = flag_hash, mi_orphan = orphan, mi_finsts = hasFamInsts, mi_deps = deps, mi_usages = usages, mi_exports = exports, mi_exp_hash = exp_hash, mi_used_th = used_th, mi_anns = anns, mi_fixities = fixities, mi_warns = warns, mi_decls = decls, mi_globals = Nothing, mi_insts = insts, mi_fam_insts = fam_insts, mi_rules = rules, mi_orphan_hash = orphan_hash, mi_vect_info = vect_info, mi_hpc = hpc_info, mi_trust = trust, mi_trust_pkg = trust_pkg, -- And build the cached values mi_warn_fn = mkIfaceWarnCache warns, mi_fix_fn = mkIfaceFixCache fixities, mi_hash_fn = mkIfaceHashCache decls }) -- | The original names declared of a certain module that are exported type IfaceExport = AvailInfo -- | Constructs an empty ModIface emptyModIface :: Module -> ModIface emptyModIface mod = ModIface { mi_module = mod, mi_sig_of = Nothing, mi_iface_hash = fingerprint0, mi_mod_hash = fingerprint0, mi_flag_hash = fingerprint0, mi_orphan = False, mi_finsts = False, mi_hsc_src = HsSrcFile, mi_deps = noDependencies, mi_usages = [], mi_exports = [], mi_exp_hash = fingerprint0, mi_used_th = False, mi_fixities = [], mi_warns = NoWarnings, mi_anns = [], mi_insts = [], mi_fam_insts = [], mi_rules = [], mi_decls = [], mi_globals = Nothing, mi_orphan_hash = fingerprint0, mi_vect_info = noIfaceVectInfo, mi_warn_fn = emptyIfaceWarnCache, mi_fix_fn = emptyIfaceFixCache, mi_hash_fn = emptyIfaceHashCache, mi_hpc = False, mi_trust = noIfaceTrustInfo, mi_trust_pkg = False } -- | Constructs cache for the 'mi_hash_fn' field of a 'ModIface' mkIfaceHashCache :: [(Fingerprint,IfaceDecl)] -> (OccName -> Maybe (OccName, Fingerprint)) mkIfaceHashCache pairs = \occ -> lookupOccEnv env occ where env = foldr add_decl emptyOccEnv pairs add_decl (v,d) env0 = foldr add env0 (ifaceDeclFingerprints v d) where add (occ,hash) env0 = extendOccEnv env0 occ (occ,hash) emptyIfaceHashCache :: OccName -> Maybe (OccName, Fingerprint) emptyIfaceHashCache _occ = Nothing -- | The 'ModDetails' is essentially a cache for information in the 'ModIface' -- for home modules only. Information relating to packages will be loaded into -- global environments in 'ExternalPackageState'. data ModDetails = ModDetails { -- The next two fields are created by the typechecker md_exports :: [AvailInfo], md_types :: !TypeEnv, -- ^ Local type environment for this particular module -- Includes Ids, TyCons, PatSyns md_insts :: ![ClsInst], -- ^ 'DFunId's for the instances in this module md_fam_insts :: ![FamInst], md_rules :: ![CoreRule], -- ^ Domain may include 'Id's from other modules md_anns :: ![Annotation], -- ^ Annotations present in this module: currently -- they only annotate things also declared in this module md_vect_info :: !VectInfo -- ^ Module vectorisation information } -- | Constructs an empty ModDetails emptyModDetails :: ModDetails emptyModDetails = ModDetails { md_types = emptyTypeEnv, md_exports = [], md_insts = [], md_rules = [], md_fam_insts = [], md_anns = [], md_vect_info = noVectInfo } -- | Records the modules directly imported by a module for extracting e.g. -- usage information, and also to give better error message type ImportedMods = ModuleEnv [ImportedModsVal] data ImportedModsVal = ImportedModsVal { imv_name :: ModuleName, -- ^ The name the module is imported with imv_span :: SrcSpan, -- ^ the source span of the whole import imv_is_safe :: IsSafeImport, -- ^ whether this is a safe import imv_is_hiding :: Bool, -- ^ whether this is an "hiding" import imv_all_exports :: GlobalRdrEnv, -- ^ all the things the module could provide imv_qualified :: Bool -- ^ whether this is a qualified import } -- | A ModGuts is carried through the compiler, accumulating stuff as it goes -- There is only one ModGuts at any time, the one for the module -- being compiled right now. Once it is compiled, a 'ModIface' and -- 'ModDetails' are extracted and the ModGuts is discarded. data ModGuts = ModGuts { mg_module :: !Module, -- ^ Module being compiled mg_hsc_src :: HscSource, -- ^ Whether it's an hs-boot module mg_loc :: SrcSpan, -- ^ For error messages from inner passes mg_exports :: ![AvailInfo], -- ^ What it exports mg_deps :: !Dependencies, -- ^ What it depends on, directly or -- otherwise mg_usages :: ![Usage], -- ^ What was used? Used for interfaces. mg_used_th :: !Bool, -- ^ Did we run a TH splice? mg_rdr_env :: !GlobalRdrEnv, -- ^ Top-level lexical environment -- These fields all describe the things **declared in this module** mg_fix_env :: !FixityEnv, -- ^ Fixities declared in this module. -- Used for creating interface files. mg_tcs :: ![TyCon], -- ^ TyCons declared in this module -- (includes TyCons for classes) mg_insts :: ![ClsInst], -- ^ Class instances declared in this module mg_fam_insts :: ![FamInst], -- ^ Family instances declared in this module mg_patsyns :: ![PatSyn], -- ^ Pattern synonyms declared in this module mg_rules :: ![CoreRule], -- ^ Before the core pipeline starts, contains -- See Note [Overall plumbing for rules] in Rules.hs mg_binds :: !CoreProgram, -- ^ Bindings for this module mg_foreign :: !ForeignStubs, -- ^ Foreign exports declared in this module mg_warns :: !Warnings, -- ^ Warnings declared in the module mg_anns :: [Annotation], -- ^ Annotations declared in this module mg_hpc_info :: !HpcInfo, -- ^ Coverage tick boxes in the module mg_modBreaks :: !(Maybe ModBreaks), -- ^ Breakpoints for the module mg_vect_decls:: ![CoreVect], -- ^ Vectorisation declarations in this module -- (produced by desugarer & consumed by vectoriser) mg_vect_info :: !VectInfo, -- ^ Pool of vectorised declarations in the module -- The next two fields are unusual, because they give instance -- environments for *all* modules in the home package, including -- this module, rather than for *just* this module. -- Reason: when looking up an instance we don't want to have to -- look at each module in the home package in turn mg_inst_env :: InstEnv, -- ^ Class instance environment for -- /home-package/ modules (including this -- one); c.f. 'tcg_inst_env' mg_fam_inst_env :: FamInstEnv, -- ^ Type-family instance environment for -- /home-package/ modules (including this -- one); c.f. 'tcg_fam_inst_env' mg_safe_haskell :: SafeHaskellMode, -- ^ Safe Haskell mode mg_trust_pkg :: Bool -- ^ Do we need to trust our -- own package for Safe Haskell? -- See Note [RnNames . Trust Own Package] } -- The ModGuts takes on several slightly different forms: -- -- After simplification, the following fields change slightly: -- mg_rules Orphan rules only (local ones now attached to binds) -- mg_binds With rules attached --------------------------------------------------------- -- The Tidy pass forks the information about this module: -- * one lot goes to interface file generation (ModIface) -- and later compilations (ModDetails) -- * the other lot goes to code generation (CgGuts) -- | A restricted form of 'ModGuts' for code generation purposes data CgGuts = CgGuts { cg_module :: !Module, -- ^ Module being compiled cg_tycons :: [TyCon], -- ^ Algebraic data types (including ones that started -- life as classes); generate constructors and info -- tables. Includes newtypes, just for the benefit of -- External Core cg_binds :: CoreProgram, -- ^ The tidied main bindings, including -- previously-implicit bindings for record and class -- selectors, and data constructor wrappers. But *not* -- data constructor workers; reason: we we regard them -- as part of the code-gen of tycons cg_foreign :: !ForeignStubs, -- ^ Foreign export stubs cg_dep_pkgs :: ![UnitId], -- ^ Dependent packages, used to -- generate #includes for C code gen cg_hpc_info :: !HpcInfo, -- ^ Program coverage tick box information cg_modBreaks :: !(Maybe ModBreaks) -- ^ Module breakpoints } ----------------------------------- -- | Foreign export stubs data ForeignStubs = NoStubs -- ^ We don't have any stubs | ForeignStubs SDoc SDoc -- ^ There are some stubs. Parameters: -- -- 1) Header file prototypes for -- "foreign exported" functions -- -- 2) C stubs to use when calling -- "foreign exported" functions appendStubC :: ForeignStubs -> SDoc -> ForeignStubs appendStubC NoStubs c_code = ForeignStubs empty c_code appendStubC (ForeignStubs h c) c_code = ForeignStubs h (c $$ c_code) {- ************************************************************************ * * The interactive context * * ************************************************************************ Note [The interactive package] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Type, class, and value declarations at the command prompt are treated as if they were defined in modules interactive:Ghci1 interactive:Ghci2 ...etc... with each bunch of declarations using a new module, all sharing a common package 'interactive' (see Module.interactiveUnitId, and PrelNames.mkInteractiveModule). This scheme deals well with shadowing. For example: ghci> data T = A ghci> data T = B ghci> :i A data Ghci1.T = A -- Defined at <interactive>:2:10 Here we must display info about constructor A, but its type T has been shadowed by the second declaration. But it has a respectable qualified name (Ghci1.T), and its source location says where it was defined. So the main invariant continues to hold, that in any session an original name M.T only refers to one unique thing. (In a previous iteration both the T's above were called :Interactive.T, albeit with different uniques, which gave rise to all sorts of trouble.) The details are a bit tricky though: * The field ic_mod_index counts which Ghci module we've got up to. It is incremented when extending ic_tythings * ic_tythings contains only things from the 'interactive' package. * Module from the 'interactive' package (Ghci1, Ghci2 etc) never go in the Home Package Table (HPT). When you say :load, that's when we extend the HPT. * The 'thisPackage' field of DynFlags is *not* set to 'interactive'. It stays as 'main' (or whatever -this-unit-id says), and is the package to which :load'ed modules are added to. * So how do we arrange that declarations at the command prompt get to be in the 'interactive' package? Simply by setting the tcg_mod field of the TcGblEnv to "interactive:Ghci1". This is done by the call to initTc in initTcInteractive, which in turn get the module from it 'icInteractiveModule' field of the interactive context. The 'thisPackage' field stays as 'main' (or whatever -this-unit-id says. * The main trickiness is that the type environment (tcg_type_env) and fixity envt (tcg_fix_env), now contain entities from all the interactive-package modules (Ghci1, Ghci2, ...) together, rather than just a single module as is usually the case. So you can't use "nameIsLocalOrFrom" to decide whether to look in the TcGblEnv vs the HPT/PTE. This is a change, but not a problem provided you know. * However, the tcg_binds, tcg_sigs, tcg_insts, tcg_fam_insts, etc fields of the TcGblEnv, which collect "things defined in this module", all refer to stuff define in a single GHCi command, *not* all the commands so far. In contrast, tcg_inst_env, tcg_fam_inst_env, have instances from all GhciN modules, which makes sense -- they are all "home package" modules. Note [Interactively-bound Ids in GHCi] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Ids bound by previous Stmts in GHCi are currently a) GlobalIds, with b) An External Name, like Ghci4.foo See Note [The interactive package] above c) A tidied type (a) They must be GlobalIds (not LocalIds) otherwise when we come to compile an expression using these ids later, the byte code generator will consider the occurrences to be free rather than global. (b) Having an External Name is important because of Note [GlobalRdrEnv shadowing] in RdrName (c) Their types are tidied. This is important, because :info may ask to look at them, and :info expects the things it looks up to have tidy types Where do interactively-bound Ids come from? - GHCi REPL Stmts e.g. ghci> let foo x = x+1 These start with an Internal Name because a Stmt is a local construct, so the renamer naturally builds an Internal name for each of its binders. Then in tcRnStmt they are externalised via TcRnDriver.externaliseAndTidyId, so they get Names like Ghic4.foo. - Ids bound by the debugger etc have Names constructed by IfaceEnv.newInteractiveBinder; at the call sites it is followed by mkVanillaGlobal or mkVanillaGlobalWithInfo. So again, they are all Global, External. - TyCons, Classes, and Ids bound by other top-level declarations in GHCi (eg foreign import, record selectors) also get External Names, with Ghci9 (or 8, or 7, etc) as the module name. Note [ic_tythings] ~~~~~~~~~~~~~~~~~~ The ic_tythings field contains * The TyThings declared by the user at the command prompt (eg Ids, TyCons, Classes) * The user-visible Ids that arise from such things, which *don't* come from 'implicitTyThings', notably: - record selectors - class ops The implicitTyThings are readily obtained from the TyThings but record selectors etc are not It does *not* contain * DFunIds (they can be gotten from ic_instances) * CoAxioms (ditto) See also Note [Interactively-bound Ids in GHCi] Note [Override identical instances in GHCi] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you declare a new instance in GHCi that is identical to a previous one, we simply override the previous one; we don't regard it as overlapping. e.g. Prelude> data T = A | B Prelude> instance Eq T where ... Prelude> instance Eq T where ... -- This one overrides It's exactly the same for type-family instances. See Trac #7102 -} -- | Interactive context, recording information about the state of the -- context in which statements are executed in a GHC session. data InteractiveContext = InteractiveContext { ic_dflags :: DynFlags, -- ^ The 'DynFlags' used to evaluate interative expressions -- and statements. ic_mod_index :: Int, -- ^ Each GHCi stmt or declaration brings some new things into -- scope. We give them names like interactive:Ghci9.T, -- where the ic_index is the '9'. The ic_mod_index is -- incremented whenever we add something to ic_tythings -- See Note [The interactive package] ic_imports :: [InteractiveImport], -- ^ The GHCi top-level scope (ic_rn_gbl_env) is extended with -- these imports -- -- This field is only stored here so that the client -- can retrieve it with GHC.getContext. GHC itself doesn't -- use it, but does reset it to empty sometimes (such -- as before a GHC.load). The context is set with GHC.setContext. ic_tythings :: [TyThing], -- ^ TyThings defined by the user, in reverse order of -- definition (ie most recent at the front) -- See Note [ic_tythings] ic_rn_gbl_env :: GlobalRdrEnv, -- ^ The cached 'GlobalRdrEnv', built by -- 'InteractiveEval.setContext' and updated regularly -- It contains everything in scope at the command line, -- including everything in ic_tythings ic_instances :: ([ClsInst], [FamInst]), -- ^ All instances and family instances created during -- this session. These are grabbed en masse after each -- update to be sure that proper overlapping is retained. -- That is, rather than re-check the overlapping each -- time we update the context, we just take the results -- from the instance code that already does that. ic_fix_env :: FixityEnv, -- ^ Fixities declared in let statements ic_default :: Maybe [Type], -- ^ The current default types, set by a 'default' declaration #ifdef GHCI ic_resume :: [Resume], -- ^ The stack of breakpoint contexts #endif ic_monad :: Name, -- ^ The monad that GHCi is executing in ic_int_print :: Name, -- ^ The function that is used for printing results -- of expressions in ghci and -e mode. ic_cwd :: Maybe FilePath -- virtual CWD of the program } data InteractiveImport = IIDecl (ImportDecl RdrName) -- ^ Bring the exports of a particular module -- (filtered by an import decl) into scope | IIModule ModuleName -- ^ Bring into scope the entire top-level envt of -- of this module, including the things imported -- into it. -- | Constructs an empty InteractiveContext. emptyInteractiveContext :: DynFlags -> InteractiveContext emptyInteractiveContext dflags = InteractiveContext { ic_dflags = dflags, ic_imports = [], ic_rn_gbl_env = emptyGlobalRdrEnv, ic_mod_index = 1, ic_tythings = [], ic_instances = ([],[]), ic_fix_env = emptyNameEnv, ic_monad = ioTyConName, -- IO monad by default ic_int_print = printName, -- System.IO.print by default ic_default = Nothing, #ifdef GHCI ic_resume = [], #endif ic_cwd = Nothing } icInteractiveModule :: InteractiveContext -> Module icInteractiveModule (InteractiveContext { ic_mod_index = index }) = mkInteractiveModule index -- | This function returns the list of visible TyThings (useful for -- e.g. showBindings) icInScopeTTs :: InteractiveContext -> [TyThing] icInScopeTTs = ic_tythings -- | Get the PrintUnqualified function based on the flags and this InteractiveContext icPrintUnqual :: DynFlags -> InteractiveContext -> PrintUnqualified icPrintUnqual dflags InteractiveContext{ ic_rn_gbl_env = grenv } = mkPrintUnqualified dflags grenv -- | extendInteractiveContext is called with new TyThings recently defined to update the -- InteractiveContext to include them. Ids are easily removed when shadowed, -- but Classes and TyCons are not. Some work could be done to determine -- whether they are entirely shadowed, but as you could still have references -- to them (e.g. instances for classes or values of the type for TyCons), it's -- not clear whether removing them is even the appropriate behavior. extendInteractiveContext :: InteractiveContext -> [TyThing] -> [ClsInst] -> [FamInst] -> Maybe [Type] -> FixityEnv -> InteractiveContext extendInteractiveContext ictxt new_tythings new_cls_insts new_fam_insts defaults fix_env = ictxt { ic_mod_index = ic_mod_index ictxt + 1 -- Always bump this; even instances should create -- a new mod_index (Trac #9426) , ic_tythings = new_tythings ++ old_tythings , ic_rn_gbl_env = ic_rn_gbl_env ictxt `icExtendGblRdrEnv` new_tythings , ic_instances = ( new_cls_insts ++ old_cls_insts , new_fam_insts ++ old_fam_insts ) , ic_default = defaults , ic_fix_env = fix_env -- See Note [Fixity declarations in GHCi] } where new_ids = [id | AnId id <- new_tythings] old_tythings = filterOut (shadowed_by new_ids) (ic_tythings ictxt) -- Discard old instances that have been fully overrridden -- See Note [Override identical instances in GHCi] (cls_insts, fam_insts) = ic_instances ictxt old_cls_insts = filterOut (\i -> any (identicalClsInstHead i) new_cls_insts) cls_insts old_fam_insts = filterOut (\i -> any (identicalFamInstHead i) new_fam_insts) fam_insts extendInteractiveContextWithIds :: InteractiveContext -> [Id] -> InteractiveContext -- Just a specialised version extendInteractiveContextWithIds ictxt new_ids | null new_ids = ictxt | otherwise = ictxt { ic_mod_index = ic_mod_index ictxt + 1 , ic_tythings = new_tythings ++ old_tythings , ic_rn_gbl_env = ic_rn_gbl_env ictxt `icExtendGblRdrEnv` new_tythings } where new_tythings = map AnId new_ids old_tythings = filterOut (shadowed_by new_ids) (ic_tythings ictxt) shadowed_by :: [Id] -> TyThing -> Bool shadowed_by ids = shadowed where shadowed id = getOccName id `elemOccSet` new_occs new_occs = mkOccSet (map getOccName ids) setInteractivePackage :: HscEnv -> HscEnv -- Set the 'thisPackage' DynFlag to 'interactive' setInteractivePackage hsc_env = hsc_env { hsc_dflags = (hsc_dflags hsc_env) { thisPackage = interactiveUnitId } } setInteractivePrintName :: InteractiveContext -> Name -> InteractiveContext setInteractivePrintName ic n = ic{ic_int_print = n} -- ToDo: should not add Ids to the gbl env here -- | Add TyThings to the GlobalRdrEnv, earlier ones in the list shadowing -- later ones, and shadowing existing entries in the GlobalRdrEnv. icExtendGblRdrEnv :: GlobalRdrEnv -> [TyThing] -> GlobalRdrEnv icExtendGblRdrEnv env tythings = foldr add env tythings -- Foldr makes things in the front of -- the list shadow things at the back where -- One at a time, to ensure each shadows the previous ones add thing env | is_sub_bndr thing = env | otherwise = foldl extendGlobalRdrEnv env1 (concatMap localGREsFromAvail avail) where env1 = shadowNames env (concatMap availNames avail) avail = tyThingAvailInfo thing -- Ugh! The new_tythings may include record selectors, since they -- are not implicit-ids, and must appear in the TypeEnv. But they -- will also be brought into scope by the corresponding (ATyCon -- tc). And we want the latter, because that has the correct -- parent (Trac #10520) is_sub_bndr (AnId f) = case idDetails f of RecSelId {} -> True ClassOpId {} -> True _ -> False is_sub_bndr _ = False substInteractiveContext :: InteractiveContext -> TCvSubst -> InteractiveContext substInteractiveContext ictxt@InteractiveContext{ ic_tythings = tts } subst | isEmptyTCvSubst subst = ictxt | otherwise = ictxt { ic_tythings = map subst_ty tts } where subst_ty (AnId id) = AnId $ id `setIdType` substTyUnchecked subst (idType id) subst_ty tt = tt instance Outputable InteractiveImport where ppr (IIModule m) = char '*' <> ppr m ppr (IIDecl d) = ppr d {- ************************************************************************ * * Building a PrintUnqualified * * ************************************************************************ Note [Printing original names] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Deciding how to print names is pretty tricky. We are given a name P:M.T, where P is the package name, M is the defining module, and T is the occurrence name, and we have to decide in which form to display the name given a GlobalRdrEnv describing the current scope. Ideally we want to display the name in the form in which it is in scope. However, the name might not be in scope at all, and that's where it gets tricky. Here are the cases: 1. T uniquely maps to P:M.T ---> "T" NameUnqual 2. There is an X for which X.T uniquely maps to P:M.T ---> "X.T" NameQual X 3. There is no binding for "M.T" ---> "M.T" NameNotInScope1 4. Otherwise ---> "P:M.T" NameNotInScope2 (3) and (4) apply when the entity P:M.T is not in the GlobalRdrEnv at all. In these cases we still want to refer to the name as "M.T", *but* "M.T" might mean something else in the current scope (e.g. if there's an "import X as M"), so to avoid confusion we avoid using "M.T" if there's already a binding for it. Instead we write P:M.T. There's one further subtlety: in case (3), what if there are two things around, P1:M.T and P2:M.T? Then we don't want to print both of them as M.T! However only one of the modules P1:M and P2:M can be exposed (say P2), so we use M.T for that, and P1:M.T for the other one. This is handled by the qual_mod component of PrintUnqualified, inside the (ppr mod) of case (3), in Name.pprModulePrefix Note [Printing unit ids] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the old days, original names were tied to PackageIds, which directly corresponded to the entities that users wrote in Cabal files, and were perfectly suitable for printing when we need to disambiguate packages. However, with UnitId, the situation can be different: if the key is instantiated with some holes, we should try to give the user some more useful information. -} -- | Creates some functions that work out the best ways to format -- names for the user according to a set of heuristics. mkPrintUnqualified :: DynFlags -> GlobalRdrEnv -> PrintUnqualified mkPrintUnqualified dflags env = QueryQualify qual_name (mkQualModule dflags) (mkQualPackage dflags) where qual_name mod occ | [gre] <- unqual_gres , right_name gre = NameUnqual -- If there's a unique entity that's in scope -- unqualified with 'occ' AND that entity is -- the right one, then we can use the unqualified name | [] <- unqual_gres , any is_name forceUnqualNames , not (isDerivedOccName occ) = NameUnqual -- Don't qualify names that come from modules -- that come with GHC, often appear in error messages, -- but aren't typically in scope. Doing this does not -- cause ambiguity, and it reduces the amount of -- qualification in error messages thus improving -- readability. -- -- A motivating example is 'Constraint'. It's often not -- in scope, but printing GHC.Prim.Constraint seems -- overkill. | [gre] <- qual_gres = NameQual (greQualModName gre) | null qual_gres = if null (lookupGRE_RdrName (mkRdrQual (moduleName mod) occ) env) then NameNotInScope1 else NameNotInScope2 | otherwise = NameNotInScope1 -- Can happen if 'f' is bound twice in the module -- Eg f = True; g = 0; f = False where is_name :: Name -> Bool is_name name = nameModule name == mod && nameOccName name == occ forceUnqualNames :: [Name] forceUnqualNames = map tyConName [ constraintKindTyCon, heqTyCon, coercibleTyCon , starKindTyCon, unicodeStarKindTyCon ] ++ [ eqTyConName ] right_name gre = nameModule_maybe (gre_name gre) == Just mod unqual_gres = lookupGRE_RdrName (mkRdrUnqual occ) env qual_gres = filter right_name (lookupGlobalRdrEnv env occ) -- we can mention a module P:M without the P: qualifier iff -- "import M" would resolve unambiguously to P:M. (if P is the -- current package we can just assume it is unqualified). -- | Creates a function for formatting modules based on two heuristics: -- (1) if the module is the current module, don't qualify, and (2) if there -- is only one exposed package which exports this module, don't qualify. mkQualModule :: DynFlags -> QueryQualifyModule mkQualModule dflags mod | moduleUnitId mod == thisPackage dflags = False | [(_, pkgconfig)] <- lookup, packageConfigId pkgconfig == moduleUnitId mod -- this says: we are given a module P:M, is there just one exposed package -- that exposes a module M, and is it package P? = False | otherwise = True where lookup = lookupModuleInAllPackages dflags (moduleName mod) -- | Creates a function for formatting packages based on two heuristics: -- (1) don't qualify if the package in question is "main", and (2) only qualify -- with a unit id if the package ID would be ambiguous. mkQualPackage :: DynFlags -> QueryQualifyPackage mkQualPackage dflags pkg_key | pkg_key == mainUnitId || pkg_key == interactiveUnitId -- Skip the lookup if it's main, since it won't be in the package -- database! = False | Just pkgid <- mb_pkgid , searchPackageId dflags pkgid `lengthIs` 1 -- this says: we are given a package pkg-0.1@MMM, are there only one -- exposed packages whose package ID is pkg-0.1? = False | otherwise = True where mb_pkgid = fmap sourcePackageId (lookupPackage dflags pkg_key) -- | A function which only qualifies package names if necessary; but -- qualifies all other identifiers. pkgQual :: DynFlags -> PrintUnqualified pkgQual dflags = alwaysQualify { queryQualifyPackage = mkQualPackage dflags } {- ************************************************************************ * * Implicit TyThings * * ************************************************************************ Note [Implicit TyThings] ~~~~~~~~~~~~~~~~~~~~~~~~ DEFINITION: An "implicit" TyThing is one that does not have its own IfaceDecl in an interface file. Instead, its binding in the type environment is created as part of typechecking the IfaceDecl for some other thing. Examples: * All DataCons are implicit, because they are generated from the IfaceDecl for the data/newtype. Ditto class methods. * Record selectors are *not* implicit, because they get their own free-standing IfaceDecl. * Associated data/type families are implicit because they are included in the IfaceDecl of the parent class. (NB: the IfaceClass decl happens to use IfaceDecl recursively for the associated types, but that's irrelevant here.) * Dictionary function Ids are not implicit. * Axioms for newtypes are implicit (same as above), but axioms for data/type family instances are *not* implicit (like DFunIds). -} -- | Determine the 'TyThing's brought into scope by another 'TyThing' -- /other/ than itself. For example, Id's don't have any implicit TyThings -- as they just bring themselves into scope, but classes bring their -- dictionary datatype, type constructor and some selector functions into -- scope, just for a start! -- N.B. the set of TyThings returned here *must* match the set of -- names returned by LoadIface.ifaceDeclImplicitBndrs, in the sense that -- TyThing.getOccName should define a bijection between the two lists. -- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop]) -- The order of the list does not matter. implicitTyThings :: TyThing -> [TyThing] implicitTyThings (AnId _) = [] implicitTyThings (ACoAxiom _cc) = [] implicitTyThings (ATyCon tc) = implicitTyConThings tc implicitTyThings (AConLike cl) = implicitConLikeThings cl implicitConLikeThings :: ConLike -> [TyThing] implicitConLikeThings (RealDataCon dc) = dataConImplicitTyThings dc implicitConLikeThings (PatSynCon {}) = [] -- Pattern synonyms have no implicit Ids; the wrapper and matcher -- are not "implicit"; they are simply new top-level bindings, -- and they have their own declaration in an interface file -- Unless a record pat syn when there are implicit selectors -- They are still not included here as `implicitConLikeThings` is -- used by `tcTyClsDecls` whilst pattern synonyms are typed checked -- by `tcTopValBinds`. implicitClassThings :: Class -> [TyThing] implicitClassThings cl = -- Does not include default methods, because those Ids may have -- their own pragmas, unfoldings etc, not derived from the Class object -- associated types -- No recursive call for the classATs, because they -- are only the family decls; they have no implicit things map ATyCon (classATs cl) ++ -- superclass and operation selectors map AnId (classAllSelIds cl) implicitTyConThings :: TyCon -> [TyThing] implicitTyConThings tc = class_stuff ++ -- fields (names of selectors) -- (possibly) implicit newtype axioms -- or type family axioms implicitCoTyCon tc ++ -- for each data constructor in order, -- the contructor, worker, and (possibly) wrapper [ thing | dc <- tyConDataCons tc , thing <- AConLike (RealDataCon dc) : dataConImplicitTyThings dc ] -- NB. record selectors are *not* implicit, they have fully-fledged -- bindings that pass through the compilation pipeline as normal. where class_stuff = case tyConClass_maybe tc of Nothing -> [] Just cl -> implicitClassThings cl -- For newtypes and closed type families (only) add the implicit coercion tycon implicitCoTyCon :: TyCon -> [TyThing] implicitCoTyCon tc | Just co <- newTyConCo_maybe tc = [ACoAxiom $ toBranchedAxiom co] | Just co <- isClosedSynFamilyTyConWithAxiom_maybe tc = [ACoAxiom co] | otherwise = [] -- | Returns @True@ if there should be no interface-file declaration -- for this thing on its own: either it is built-in, or it is part -- of some other declaration, or it is generated implicitly by some -- other declaration. isImplicitTyThing :: TyThing -> Bool isImplicitTyThing (AConLike cl) = case cl of RealDataCon {} -> True PatSynCon {} -> False isImplicitTyThing (AnId id) = isImplicitId id isImplicitTyThing (ATyCon tc) = isImplicitTyCon tc isImplicitTyThing (ACoAxiom ax) = isImplicitCoAxiom ax -- | tyThingParent_maybe x returns (Just p) -- when pprTyThingInContext sould print a declaration for p -- (albeit with some "..." in it) when asked to show x -- It returns the *immediate* parent. So a datacon returns its tycon -- but the tycon could be the associated type of a class, so it in turn -- might have a parent. tyThingParent_maybe :: TyThing -> Maybe TyThing tyThingParent_maybe (AConLike cl) = case cl of RealDataCon dc -> Just (ATyCon (dataConTyCon dc)) PatSynCon{} -> Nothing tyThingParent_maybe (ATyCon tc) = case tyConAssoc_maybe tc of Just cls -> Just (ATyCon (classTyCon cls)) Nothing -> Nothing tyThingParent_maybe (AnId id) = case idDetails id of RecSelId { sel_tycon = RecSelData tc } -> Just (ATyCon tc) ClassOpId cls -> Just (ATyCon (classTyCon cls)) _other -> Nothing tyThingParent_maybe _other = Nothing tyThingsTyCoVars :: [TyThing] -> TyCoVarSet tyThingsTyCoVars tts = unionVarSets $ map ttToVarSet tts where ttToVarSet (AnId id) = tyCoVarsOfType $ idType id ttToVarSet (AConLike cl) = case cl of RealDataCon dc -> tyCoVarsOfType $ dataConRepType dc PatSynCon{} -> emptyVarSet ttToVarSet (ATyCon tc) = case tyConClass_maybe tc of Just cls -> (mkVarSet . fst . classTvsFds) cls Nothing -> tyCoVarsOfType $ tyConKind tc ttToVarSet (ACoAxiom _) = emptyVarSet -- | The Names that a TyThing should bring into scope. Used to build -- the GlobalRdrEnv for the InteractiveContext. tyThingAvailInfo :: TyThing -> [AvailInfo] tyThingAvailInfo (ATyCon t) = case tyConClass_maybe t of Just c -> [AvailTC n (n : map getName (classMethods c) ++ map getName (classATs c)) [] ] where n = getName c Nothing -> [AvailTC n (n : map getName dcs) flds] where n = getName t dcs = tyConDataCons t flds = tyConFieldLabels t tyThingAvailInfo (AConLike (PatSynCon p)) = map patSynAvail ((getName p) : map flSelector (patSynFieldLabels p)) tyThingAvailInfo t = [avail (getName t)] {- ************************************************************************ * * TypeEnv * * ************************************************************************ -} -- | A map from 'Name's to 'TyThing's, constructed by typechecking -- local declarations or interface files type TypeEnv = NameEnv TyThing emptyTypeEnv :: TypeEnv typeEnvElts :: TypeEnv -> [TyThing] typeEnvTyCons :: TypeEnv -> [TyCon] typeEnvCoAxioms :: TypeEnv -> [CoAxiom Branched] typeEnvIds :: TypeEnv -> [Id] typeEnvPatSyns :: TypeEnv -> [PatSyn] typeEnvDataCons :: TypeEnv -> [DataCon] typeEnvClasses :: TypeEnv -> [Class] lookupTypeEnv :: TypeEnv -> Name -> Maybe TyThing emptyTypeEnv = emptyNameEnv typeEnvElts env = nameEnvElts env typeEnvTyCons env = [tc | ATyCon tc <- typeEnvElts env] typeEnvCoAxioms env = [ax | ACoAxiom ax <- typeEnvElts env] typeEnvIds env = [id | AnId id <- typeEnvElts env] typeEnvPatSyns env = [ps | AConLike (PatSynCon ps) <- typeEnvElts env] typeEnvDataCons env = [dc | AConLike (RealDataCon dc) <- typeEnvElts env] typeEnvClasses env = [cl | tc <- typeEnvTyCons env, Just cl <- [tyConClass_maybe tc]] mkTypeEnv :: [TyThing] -> TypeEnv mkTypeEnv things = extendTypeEnvList emptyTypeEnv things mkTypeEnvWithImplicits :: [TyThing] -> TypeEnv mkTypeEnvWithImplicits things = mkTypeEnv things `plusNameEnv` mkTypeEnv (concatMap implicitTyThings things) typeEnvFromEntities :: [Id] -> [TyCon] -> [FamInst] -> TypeEnv typeEnvFromEntities ids tcs famInsts = mkTypeEnv ( map AnId ids ++ map ATyCon all_tcs ++ concatMap implicitTyConThings all_tcs ++ map (ACoAxiom . toBranchedAxiom . famInstAxiom) famInsts ) where all_tcs = tcs ++ famInstsRepTyCons famInsts lookupTypeEnv = lookupNameEnv -- Extend the type environment extendTypeEnv :: TypeEnv -> TyThing -> TypeEnv extendTypeEnv env thing = extendNameEnv env (getName thing) thing extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv extendTypeEnvList env things = foldl extendTypeEnv env things extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv extendTypeEnvWithIds env ids = extendNameEnvList env [(getName id, AnId id) | id <- ids] -- | Find the 'TyThing' for the given 'Name' by using all the resources -- at our disposal: the compiled modules in the 'HomePackageTable' and the -- compiled modules in other packages that live in 'PackageTypeEnv'. Note -- that this does NOT look up the 'TyThing' in the module being compiled: you -- have to do that yourself, if desired lookupType :: DynFlags -> HomePackageTable -> PackageTypeEnv -> Name -> Maybe TyThing lookupType dflags hpt pte name | isOneShot (ghcMode dflags) -- in one-shot, we don't use the HPT = lookupNameEnv pte name | otherwise = case lookupHptByModule hpt mod of Just hm -> lookupNameEnv (md_types (hm_details hm)) name Nothing -> lookupNameEnv pte name where mod = ASSERT2( isExternalName name, ppr name ) nameModule name -- | As 'lookupType', but with a marginally easier-to-use interface -- if you have a 'HscEnv' lookupTypeHscEnv :: HscEnv -> Name -> IO (Maybe TyThing) lookupTypeHscEnv hsc_env name = do eps <- readIORef (hsc_EPS hsc_env) return $! lookupType dflags hpt (eps_PTE eps) name where dflags = hsc_dflags hsc_env hpt = hsc_HPT hsc_env -- | Get the 'TyCon' from a 'TyThing' if it is a type constructor thing. Panics otherwise tyThingTyCon :: TyThing -> TyCon tyThingTyCon (ATyCon tc) = tc tyThingTyCon other = pprPanic "tyThingTyCon" (pprTyThing other) -- | Get the 'CoAxiom' from a 'TyThing' if it is a coercion axiom thing. Panics otherwise tyThingCoAxiom :: TyThing -> CoAxiom Branched tyThingCoAxiom (ACoAxiom ax) = ax tyThingCoAxiom other = pprPanic "tyThingCoAxiom" (pprTyThing other) -- | Get the 'DataCon' from a 'TyThing' if it is a data constructor thing. Panics otherwise tyThingDataCon :: TyThing -> DataCon tyThingDataCon (AConLike (RealDataCon dc)) = dc tyThingDataCon other = pprPanic "tyThingDataCon" (pprTyThing other) -- | Get the 'Id' from a 'TyThing' if it is a id *or* data constructor thing. Panics otherwise tyThingId :: TyThing -> Id tyThingId (AnId id) = id tyThingId (AConLike (RealDataCon dc)) = dataConWrapId dc tyThingId other = pprPanic "tyThingId" (pprTyThing other) {- ************************************************************************ * * \subsection{MonadThings and friends} * * ************************************************************************ -} -- | Class that abstracts out the common ability of the monads in GHC -- to lookup a 'TyThing' in the monadic environment by 'Name'. Provides -- a number of related convenience functions for accessing particular -- kinds of 'TyThing' class Monad m => MonadThings m where lookupThing :: Name -> m TyThing lookupId :: Name -> m Id lookupId = liftM tyThingId . lookupThing lookupDataCon :: Name -> m DataCon lookupDataCon = liftM tyThingDataCon . lookupThing lookupTyCon :: Name -> m TyCon lookupTyCon = liftM tyThingTyCon . lookupThing {- ************************************************************************ * * \subsection{Auxiliary types} * * ************************************************************************ These types are defined here because they are mentioned in ModDetails, but they are mostly elaborated elsewhere -} ------------------ Warnings ------------------------- -- | Warning information for a module data Warnings = NoWarnings -- ^ Nothing deprecated | WarnAll WarningTxt -- ^ Whole module deprecated | WarnSome [(OccName,WarningTxt)] -- ^ Some specific things deprecated -- Only an OccName is needed because -- (1) a deprecation always applies to a binding -- defined in the module in which the deprecation appears. -- (2) deprecations are only reported outside the defining module. -- this is important because, otherwise, if we saw something like -- -- {-# DEPRECATED f "" #-} -- f = ... -- h = f -- g = let f = undefined in f -- -- we'd need more information than an OccName to know to say something -- about the use of f in h but not the use of the locally bound f in g -- -- however, because we only report about deprecations from the outside, -- and a module can only export one value called f, -- an OccName suffices. -- -- this is in contrast with fixity declarations, where we need to map -- a Name to its fixity declaration. deriving( Eq ) instance Binary Warnings where put_ bh NoWarnings = putByte bh 0 put_ bh (WarnAll t) = do putByte bh 1 put_ bh t put_ bh (WarnSome ts) = do putByte bh 2 put_ bh ts get bh = do h <- getByte bh case h of 0 -> return NoWarnings 1 -> do aa <- get bh return (WarnAll aa) _ -> do aa <- get bh return (WarnSome aa) -- | Constructs the cache for the 'mi_warn_fn' field of a 'ModIface' mkIfaceWarnCache :: Warnings -> OccName -> Maybe WarningTxt mkIfaceWarnCache NoWarnings = \_ -> Nothing mkIfaceWarnCache (WarnAll t) = \_ -> Just t mkIfaceWarnCache (WarnSome pairs) = lookupOccEnv (mkOccEnv pairs) emptyIfaceWarnCache :: OccName -> Maybe WarningTxt emptyIfaceWarnCache _ = Nothing plusWarns :: Warnings -> Warnings -> Warnings plusWarns d NoWarnings = d plusWarns NoWarnings d = d plusWarns _ (WarnAll t) = WarnAll t plusWarns (WarnAll t) _ = WarnAll t plusWarns (WarnSome v1) (WarnSome v2) = WarnSome (v1 ++ v2) -- | Creates cached lookup for the 'mi_fix_fn' field of 'ModIface' mkIfaceFixCache :: [(OccName, Fixity)] -> OccName -> Maybe Fixity mkIfaceFixCache pairs = \n -> lookupOccEnv env n where env = mkOccEnv pairs emptyIfaceFixCache :: OccName -> Maybe Fixity emptyIfaceFixCache _ = Nothing -- | Fixity environment mapping names to their fixities type FixityEnv = NameEnv FixItem -- | Fixity information for an 'Name'. We keep the OccName in the range -- so that we can generate an interface from it data FixItem = FixItem OccName Fixity instance Outputable FixItem where ppr (FixItem occ fix) = ppr fix <+> ppr occ emptyFixityEnv :: FixityEnv emptyFixityEnv = emptyNameEnv lookupFixity :: FixityEnv -> Name -> Fixity lookupFixity env n = case lookupNameEnv env n of Just (FixItem _ fix) -> fix Nothing -> defaultFixity {- ************************************************************************ * * \subsection{WhatsImported} * * ************************************************************************ -} -- | Records whether a module has orphans. An \"orphan\" is one of: -- -- * An instance declaration in a module other than the definition -- module for one of the type constructors or classes in the instance head -- -- * A transformation rule in a module other than the one defining -- the function in the head of the rule -- -- * A vectorisation pragma type WhetherHasOrphans = Bool -- | Does this module define family instances? type WhetherHasFamInst = Bool -- | Did this module originate from a *-boot file? type IsBootInterface = Bool -- | Dependency information about ALL modules and packages below this one -- in the import hierarchy. -- -- Invariant: the dependencies of a module @M@ never includes @M@. -- -- Invariant: none of the lists contain duplicates. data Dependencies = Deps { dep_mods :: [(ModuleName, IsBootInterface)] -- ^ All home-package modules transitively below this one -- I.e. modules that this one imports, or that are in the -- dep_mods of those directly-imported modules , dep_pkgs :: [(UnitId, Bool)] -- ^ All packages transitively below this module -- I.e. packages to which this module's direct imports belong, -- or that are in the dep_pkgs of those modules -- The bool indicates if the package is required to be -- trusted when the module is imported as a safe import -- (Safe Haskell). See Note [RnNames . Tracking Trust Transitively] , dep_orphs :: [Module] -- ^ Transitive closure of orphan modules (whether -- home or external pkg). -- -- (Possible optimization: don't include family -- instance orphans as they are anyway included in -- 'dep_finsts'. But then be careful about code -- which relies on dep_orphs having the complete list!) , dep_finsts :: [Module] -- ^ Modules that contain family instances (whether the -- instances are from the home or an external package) } deriving( Eq ) -- Equality used only for old/new comparison in MkIface.addFingerprints -- See 'TcRnTypes.ImportAvails' for details on dependencies. instance Binary Dependencies where put_ bh deps = do put_ bh (dep_mods deps) put_ bh (dep_pkgs deps) put_ bh (dep_orphs deps) put_ bh (dep_finsts deps) get bh = do ms <- get bh ps <- get bh os <- get bh fis <- get bh return (Deps { dep_mods = ms, dep_pkgs = ps, dep_orphs = os, dep_finsts = fis }) noDependencies :: Dependencies noDependencies = Deps [] [] [] [] -- | Records modules for which changes may force recompilation of this module -- See wiki: http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance -- -- This differs from Dependencies. A module X may be in the dep_mods of this -- module (via an import chain) but if we don't use anything from X it won't -- appear in our Usage data Usage -- | Module from another package = UsagePackageModule { usg_mod :: Module, -- ^ External package module depended on usg_mod_hash :: Fingerprint, -- ^ Cached module fingerprint usg_safe :: IsSafeImport -- ^ Was this module imported as a safe import } -- | Module from the current package | UsageHomeModule { usg_mod_name :: ModuleName, -- ^ Name of the module usg_mod_hash :: Fingerprint, -- ^ Cached module fingerprint usg_entities :: [(OccName,Fingerprint)], -- ^ Entities we depend on, sorted by occurrence name and fingerprinted. -- NB: usages are for parent names only, e.g. type constructors -- but not the associated data constructors. usg_exports :: Maybe Fingerprint, -- ^ Fingerprint for the export list of this module, -- if we directly imported it (and hence we depend on its export list) usg_safe :: IsSafeImport -- ^ Was this module imported as a safe import } -- ^ Module from the current package -- | A file upon which the module depends, e.g. a CPP #include, or using TH's -- 'addDependentFile' | UsageFile { usg_file_path :: FilePath, -- ^ External file dependency. From a CPP #include or TH -- addDependentFile. Should be absolute. usg_file_hash :: Fingerprint -- ^ 'Fingerprint' of the file contents. -- Note: We don't consider things like modification timestamps -- here, because there's no reason to recompile if the actual -- contents don't change. This previously lead to odd -- recompilation behaviors; see #8114 } deriving( Eq ) -- The export list field is (Just v) if we depend on the export list: -- i.e. we imported the module directly, whether or not we -- enumerated the things we imported, or just imported -- everything -- We need to recompile if M's exports change, because -- if the import was import M, we might now have a name clash -- in the importing module. -- if the import was import M(x) M might no longer export x -- The only way we don't depend on the export list is if we have -- import M() -- And of course, for modules that aren't imported directly we don't -- depend on their export lists instance Binary Usage where put_ bh usg@UsagePackageModule{} = do putByte bh 0 put_ bh (usg_mod usg) put_ bh (usg_mod_hash usg) put_ bh (usg_safe usg) put_ bh usg@UsageHomeModule{} = do putByte bh 1 put_ bh (usg_mod_name usg) put_ bh (usg_mod_hash usg) put_ bh (usg_exports usg) put_ bh (usg_entities usg) put_ bh (usg_safe usg) put_ bh usg@UsageFile{} = do putByte bh 2 put_ bh (usg_file_path usg) put_ bh (usg_file_hash usg) get bh = do h <- getByte bh case h of 0 -> do nm <- get bh mod <- get bh safe <- get bh return UsagePackageModule { usg_mod = nm, usg_mod_hash = mod, usg_safe = safe } 1 -> do nm <- get bh mod <- get bh exps <- get bh ents <- get bh safe <- get bh return UsageHomeModule { usg_mod_name = nm, usg_mod_hash = mod, usg_exports = exps, usg_entities = ents, usg_safe = safe } 2 -> do fp <- get bh hash <- get bh return UsageFile { usg_file_path = fp, usg_file_hash = hash } i -> error ("Binary.get(Usage): " ++ show i) {- ************************************************************************ * * The External Package State * * ************************************************************************ -} type PackageTypeEnv = TypeEnv type PackageRuleBase = RuleBase type PackageInstEnv = InstEnv type PackageFamInstEnv = FamInstEnv type PackageVectInfo = VectInfo type PackageAnnEnv = AnnEnv -- | Information about other packages that we have slurped in by reading -- their interface files data ExternalPackageState = EPS { eps_is_boot :: !(ModuleNameEnv (ModuleName, IsBootInterface)), -- ^ In OneShot mode (only), home-package modules -- accumulate in the external package state, and are -- sucked in lazily. For these home-pkg modules -- (only) we need to record which are boot modules. -- We set this field after loading all the -- explicitly-imported interfaces, but before doing -- anything else -- -- The 'ModuleName' part is not necessary, but it's useful for -- debug prints, and it's convenient because this field comes -- direct from 'TcRnTypes.imp_dep_mods' eps_PIT :: !PackageIfaceTable, -- ^ The 'ModIface's for modules in external packages -- whose interfaces we have opened. -- The declarations in these interface files are held in the -- 'eps_decls', 'eps_inst_env', 'eps_fam_inst_env' and 'eps_rules' -- fields of this record, not in the 'mi_decls' fields of the -- interface we have sucked in. -- -- What /is/ in the PIT is: -- -- * The Module -- -- * Fingerprint info -- -- * Its exports -- -- * Fixities -- -- * Deprecations and warnings eps_PTE :: !PackageTypeEnv, -- ^ Result of typechecking all the external package -- interface files we have sucked in. The domain of -- the mapping is external-package modules eps_inst_env :: !PackageInstEnv, -- ^ The total 'InstEnv' accumulated -- from all the external-package modules eps_fam_inst_env :: !PackageFamInstEnv,-- ^ The total 'FamInstEnv' accumulated -- from all the external-package modules eps_rule_base :: !PackageRuleBase, -- ^ The total 'RuleEnv' accumulated -- from all the external-package modules eps_vect_info :: !PackageVectInfo, -- ^ The total 'VectInfo' accumulated -- from all the external-package modules eps_ann_env :: !PackageAnnEnv, -- ^ The total 'AnnEnv' accumulated -- from all the external-package modules eps_mod_fam_inst_env :: !(ModuleEnv FamInstEnv), -- ^ The family instances accumulated from external -- packages, keyed off the module that declared them eps_stats :: !EpsStats -- ^ Stastics about what was loaded from external packages } -- | Accumulated statistics about what we are putting into the 'ExternalPackageState'. -- \"In\" means stuff that is just /read/ from interface files, -- \"Out\" means actually sucked in and type-checked data EpsStats = EpsStats { n_ifaces_in , n_decls_in, n_decls_out , n_rules_in, n_rules_out , n_insts_in, n_insts_out :: !Int } addEpsInStats :: EpsStats -> Int -> Int -> Int -> EpsStats -- ^ Add stats for one newly-read interface addEpsInStats stats n_decls n_insts n_rules = stats { n_ifaces_in = n_ifaces_in stats + 1 , n_decls_in = n_decls_in stats + n_decls , n_insts_in = n_insts_in stats + n_insts , n_rules_in = n_rules_in stats + n_rules } {- Names in a NameCache are always stored as a Global, and have the SrcLoc of their binding locations. Actually that's not quite right. When we first encounter the original name, we might not be at its binding site (e.g. we are reading an interface file); so we give it 'noSrcLoc' then. Later, when we find its binding site, we fix it up. -} -- | The NameCache makes sure that there is just one Unique assigned for -- each original name; i.e. (module-name, occ-name) pair and provides -- something of a lookup mechanism for those names. data NameCache = NameCache { nsUniqs :: !UniqSupply, -- ^ Supply of uniques nsNames :: !OrigNameCache -- ^ Ensures that one original name gets one unique } updNameCacheIO :: HscEnv -> (NameCache -> (NameCache, c)) -- The updating function -> IO c updNameCacheIO hsc_env upd_fn = atomicModifyIORef' (hsc_NC hsc_env) upd_fn -- | Per-module cache of original 'OccName's given 'Name's type OrigNameCache = ModuleEnv (OccEnv Name) mkSOName :: Platform -> FilePath -> FilePath mkSOName platform root = case platformOS platform of OSDarwin -> ("lib" ++ root) <.> "dylib" OSMinGW32 -> root <.> "dll" _ -> ("lib" ++ root) <.> "so" mkHsSOName :: Platform -> FilePath -> FilePath mkHsSOName platform root = ("lib" ++ root) <.> soExt platform soExt :: Platform -> FilePath soExt platform = case platformOS platform of OSDarwin -> "dylib" OSMinGW32 -> "dll" _ -> "so" {- ************************************************************************ * * The module graph and ModSummary type A ModSummary is a node in the compilation manager's dependency graph, and it's also passed to hscMain * * ************************************************************************ -} -- | A ModuleGraph contains all the nodes from the home package (only). -- There will be a node for each source module, plus a node for each hi-boot -- module. -- -- The graph is not necessarily stored in topologically-sorted order. Use -- 'GHC.topSortModuleGraph' and 'Digraph.flattenSCC' to achieve this. type ModuleGraph = [ModSummary] emptyMG :: ModuleGraph emptyMG = [] -- | A single node in a 'ModuleGraph'. The nodes of the module graph -- are one of: -- -- * A regular Haskell source module -- * A hi-boot source module -- data ModSummary = ModSummary { ms_mod :: Module, -- ^ Identity of the module ms_hsc_src :: HscSource, -- ^ The module source either plain Haskell or hs-boot ms_location :: ModLocation, -- ^ Location of the various files belonging to the module ms_hs_date :: UTCTime, -- ^ Timestamp of source file ms_obj_date :: Maybe UTCTime, -- ^ Timestamp of object, if we have one ms_iface_date :: Maybe UTCTime, -- ^ Timestamp of hi file, if we *only* are typechecking (it is -- 'Nothing' otherwise. -- See Note [Recompilation checking when typechecking only] and #9243 ms_srcimps :: [(Maybe FastString, Located ModuleName)], -- ^ Source imports of the module ms_textual_imps :: [(Maybe FastString, Located ModuleName)], -- ^ Non-source imports of the module from the module *text* ms_hspp_file :: FilePath, -- ^ Filename of preprocessed source file ms_hspp_opts :: DynFlags, -- ^ Cached flags from @OPTIONS@, @INCLUDE@ and @LANGUAGE@ -- pragmas in the modules source code ms_hspp_buf :: Maybe StringBuffer -- ^ The actual preprocessed source, if we have it } ms_mod_name :: ModSummary -> ModuleName ms_mod_name = moduleName . ms_mod ms_imps :: ModSummary -> [(Maybe FastString, Located ModuleName)] ms_imps ms = ms_textual_imps ms ++ map mk_additional_import (dynFlagDependencies (ms_hspp_opts ms)) where mk_additional_import mod_nm = (Nothing, noLoc mod_nm) -- The ModLocation contains both the original source filename and the -- filename of the cleaned-up source file after all preprocessing has been -- done. The point is that the summariser will have to cpp/unlit/whatever -- all files anyway, and there's no point in doing this twice -- just -- park the result in a temp file, put the name of it in the location, -- and let @compile@ read from that file on the way back up. -- The ModLocation is stable over successive up-sweeps in GHCi, wheres -- the ms_hs_date and imports can, of course, change msHsFilePath, msHiFilePath, msObjFilePath :: ModSummary -> FilePath msHsFilePath ms = expectJust "msHsFilePath" (ml_hs_file (ms_location ms)) msHiFilePath ms = ml_hi_file (ms_location ms) msObjFilePath ms = ml_obj_file (ms_location ms) -- | Did this 'ModSummary' originate from a hs-boot file? isBootSummary :: ModSummary -> Bool isBootSummary ms = ms_hsc_src ms == HsBootFile instance Outputable ModSummary where ppr ms = sep [text "ModSummary {", nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)), text "ms_mod =" <+> ppr (ms_mod ms) <> text (hscSourceString (ms_hsc_src ms)) <> comma, text "ms_textual_imps =" <+> ppr (ms_textual_imps ms), text "ms_srcimps =" <+> ppr (ms_srcimps ms)]), char '}' ] showModMsg :: DynFlags -> HscTarget -> Bool -> ModSummary -> String showModMsg dflags target recomp mod_summary = showSDoc dflags $ hsep [text (mod_str ++ replicate (max 0 (16 - length mod_str)) ' '), char '(', text (normalise $ msHsFilePath mod_summary) <> comma, case target of HscInterpreted | recomp -> text "interpreted" HscNothing -> text "nothing" _ | HsigFile == ms_hsc_src mod_summary -> text "nothing" | otherwise -> text (normalise $ msObjFilePath mod_summary), char ')'] where mod = moduleName (ms_mod mod_summary) mod_str = showPpr dflags mod ++ hscSourceString' dflags mod (ms_hsc_src mod_summary) -- | Variant of hscSourceString which prints more information for signatures. -- This can't live in DriverPhases because this would cause a module loop. hscSourceString' :: DynFlags -> ModuleName -> HscSource -> String hscSourceString' _ _ HsSrcFile = "" hscSourceString' _ _ HsBootFile = "[boot]" hscSourceString' dflags mod HsigFile = "[" ++ (maybe "abstract sig" (("sig of "++).showPpr dflags) (getSigOf dflags mod)) ++ "]" -- NB: -sig-of could be missing if we're just typechecking {- ************************************************************************ * * \subsection{Recmpilation} * * ************************************************************************ -} -- | Indicates whether a given module's source has been modified since it -- was last compiled. data SourceModified = SourceModified -- ^ the source has been modified | SourceUnmodified -- ^ the source has not been modified. Compilation may or may -- not be necessary, depending on whether any dependencies have -- changed since we last compiled. | SourceUnmodifiedAndStable -- ^ the source has not been modified, and furthermore all of -- its (transitive) dependencies are up to date; it definitely -- does not need to be recompiled. This is important for two -- reasons: (a) we can omit the version check in checkOldIface, -- and (b) if the module used TH splices we don't need to force -- recompilation. {- ************************************************************************ * * \subsection{Hpc Support} * * ************************************************************************ -} -- | Information about a modules use of Haskell Program Coverage data HpcInfo = HpcInfo { hpcInfoTickCount :: Int , hpcInfoHash :: Int } | NoHpcInfo { hpcUsed :: AnyHpcUsage -- ^ Is hpc used anywhere on the module \*tree\*? } -- | This is used to signal if one of my imports used HPC instrumentation -- even if there is no module-local HPC usage type AnyHpcUsage = Bool emptyHpcInfo :: AnyHpcUsage -> HpcInfo emptyHpcInfo = NoHpcInfo -- | Find out if HPC is used by this module or any of the modules -- it depends upon isHpcUsed :: HpcInfo -> AnyHpcUsage isHpcUsed (HpcInfo {}) = True isHpcUsed (NoHpcInfo { hpcUsed = used }) = used {- ************************************************************************ * * \subsection{Vectorisation Support} * * ************************************************************************ The following information is generated and consumed by the vectorisation subsystem. It communicates the vectorisation status of declarations from one module to another. Why do we need both f and f_v in the ModGuts/ModDetails/EPS version VectInfo below? We need to know `f' when converting to IfaceVectInfo. However, during vectorisation, we need to know `f_v', whose `Var' we cannot lookup based on just the OccName easily in a Core pass. -} -- |Vectorisation information for 'ModGuts', 'ModDetails' and 'ExternalPackageState'; see also -- documentation at 'Vectorise.Env.GlobalEnv'. -- -- NB: The following tables may also include 'Var's, 'TyCon's and 'DataCon's from imported modules, -- which have been subsequently vectorised in the current module. -- data VectInfo = VectInfo { vectInfoVar :: VarEnv (Var , Var ) -- ^ @(f, f_v)@ keyed on @f@ , vectInfoTyCon :: NameEnv (TyCon , TyCon) -- ^ @(T, T_v)@ keyed on @T@ , vectInfoDataCon :: NameEnv (DataCon, DataCon) -- ^ @(C, C_v)@ keyed on @C@ , vectInfoParallelVars :: VarSet -- ^ set of parallel variables , vectInfoParallelTyCons :: NameSet -- ^ set of parallel type constructors } -- |Vectorisation information for 'ModIface'; i.e, the vectorisation information propagated -- across module boundaries. -- -- NB: The field 'ifaceVectInfoVar' explicitly contains the workers of data constructors as well as -- class selectors — i.e., their mappings are /not/ implicitly generated from the data types. -- Moreover, whether the worker of a data constructor is in 'ifaceVectInfoVar' determines -- whether that data constructor was vectorised (or is part of an abstractly vectorised type -- constructor). -- data IfaceVectInfo = IfaceVectInfo { ifaceVectInfoVar :: [Name] -- ^ All variables in here have a vectorised variant , ifaceVectInfoTyCon :: [Name] -- ^ All 'TyCon's in here have a vectorised variant; -- the name of the vectorised variant and those of its -- data constructors are determined by -- 'OccName.mkVectTyConOcc' and -- 'OccName.mkVectDataConOcc'; the names of the -- isomorphisms are determined by 'OccName.mkVectIsoOcc' , ifaceVectInfoTyConReuse :: [Name] -- ^ The vectorised form of all the 'TyCon's in here -- coincides with the unconverted form; the name of the -- isomorphisms is determined by 'OccName.mkVectIsoOcc' , ifaceVectInfoParallelVars :: [Name] -- iface version of 'vectInfoParallelVar' , ifaceVectInfoParallelTyCons :: [Name] -- iface version of 'vectInfoParallelTyCon' } noVectInfo :: VectInfo noVectInfo = VectInfo emptyVarEnv emptyNameEnv emptyNameEnv emptyVarSet emptyNameSet plusVectInfo :: VectInfo -> VectInfo -> VectInfo plusVectInfo vi1 vi2 = VectInfo (vectInfoVar vi1 `plusVarEnv` vectInfoVar vi2) (vectInfoTyCon vi1 `plusNameEnv` vectInfoTyCon vi2) (vectInfoDataCon vi1 `plusNameEnv` vectInfoDataCon vi2) (vectInfoParallelVars vi1 `unionVarSet` vectInfoParallelVars vi2) (vectInfoParallelTyCons vi1 `unionNameSet` vectInfoParallelTyCons vi2) concatVectInfo :: [VectInfo] -> VectInfo concatVectInfo = foldr plusVectInfo noVectInfo noIfaceVectInfo :: IfaceVectInfo noIfaceVectInfo = IfaceVectInfo [] [] [] [] [] isNoIfaceVectInfo :: IfaceVectInfo -> Bool isNoIfaceVectInfo (IfaceVectInfo l1 l2 l3 l4 l5) = null l1 && null l2 && null l3 && null l4 && null l5 instance Outputable VectInfo where ppr info = vcat [ text "variables :" <+> ppr (vectInfoVar info) , text "tycons :" <+> ppr (vectInfoTyCon info) , text "datacons :" <+> ppr (vectInfoDataCon info) , text "parallel vars :" <+> ppr (vectInfoParallelVars info) , text "parallel tycons :" <+> ppr (vectInfoParallelTyCons info) ] instance Outputable IfaceVectInfo where ppr info = vcat [ text "variables :" <+> ppr (ifaceVectInfoVar info) , text "tycons :" <+> ppr (ifaceVectInfoTyCon info) , text "tycons reuse :" <+> ppr (ifaceVectInfoTyConReuse info) , text "parallel vars :" <+> ppr (ifaceVectInfoParallelVars info) , text "parallel tycons :" <+> ppr (ifaceVectInfoParallelTyCons info) ] instance Binary IfaceVectInfo where put_ bh (IfaceVectInfo a1 a2 a3 a4 a5) = do put_ bh a1 put_ bh a2 put_ bh a3 put_ bh a4 put_ bh a5 get bh = do a1 <- get bh a2 <- get bh a3 <- get bh a4 <- get bh a5 <- get bh return (IfaceVectInfo a1 a2 a3 a4 a5) {- ************************************************************************ * * \subsection{Safe Haskell Support} * * ************************************************************************ This stuff here is related to supporting the Safe Haskell extension, primarily about storing under what trust type a module has been compiled. -} -- | Is an import a safe import? type IsSafeImport = Bool -- | Safe Haskell information for 'ModIface' -- Simply a wrapper around SafeHaskellMode to sepperate iface and flags newtype IfaceTrustInfo = TrustInfo SafeHaskellMode getSafeMode :: IfaceTrustInfo -> SafeHaskellMode getSafeMode (TrustInfo x) = x setSafeMode :: SafeHaskellMode -> IfaceTrustInfo setSafeMode = TrustInfo noIfaceTrustInfo :: IfaceTrustInfo noIfaceTrustInfo = setSafeMode Sf_None trustInfoToNum :: IfaceTrustInfo -> Word8 trustInfoToNum it = case getSafeMode it of Sf_None -> 0 Sf_Unsafe -> 1 Sf_Trustworthy -> 2 Sf_Safe -> 3 numToTrustInfo :: Word8 -> IfaceTrustInfo numToTrustInfo 0 = setSafeMode Sf_None numToTrustInfo 1 = setSafeMode Sf_Unsafe numToTrustInfo 2 = setSafeMode Sf_Trustworthy numToTrustInfo 3 = setSafeMode Sf_Safe numToTrustInfo 4 = setSafeMode Sf_Safe -- retained for backwards compat, used -- to be Sf_SafeInfered but we no longer -- differentiate. numToTrustInfo n = error $ "numToTrustInfo: bad input number! (" ++ show n ++ ")" instance Outputable IfaceTrustInfo where ppr (TrustInfo Sf_None) = text "none" ppr (TrustInfo Sf_Unsafe) = text "unsafe" ppr (TrustInfo Sf_Trustworthy) = text "trustworthy" ppr (TrustInfo Sf_Safe) = text "safe" instance Binary IfaceTrustInfo where put_ bh iftrust = putByte bh $ trustInfoToNum iftrust get bh = getByte bh >>= (return . numToTrustInfo) {- ************************************************************************ * * \subsection{Parser result} * * ************************************************************************ -} data HsParsedModule = HsParsedModule { hpm_module :: Located (HsModule RdrName), hpm_src_files :: [FilePath], -- ^ extra source files (e.g. from #includes). The lexer collects -- these from '# <file> <line>' pragmas, which the C preprocessor -- leaves behind. These files and their timestamps are stored in -- the .hi file, so that we can force recompilation if any of -- them change (#3589) hpm_annotations :: ApiAnns -- See note [Api annotations] in ApiAnnotation.hs } {- ************************************************************************ * * \subsection{Linkable stuff} * * ************************************************************************ This stuff is in here, rather than (say) in Linker.hs, because the Linker.hs stuff is the *dynamic* linker, and isn't present in a stage-1 compiler -} -- | Information we can use to dynamically link modules into the compiler data Linkable = LM { linkableTime :: UTCTime, -- ^ Time at which this linkable was built -- (i.e. when the bytecodes were produced, -- or the mod date on the files) linkableModule :: Module, -- ^ The linkable module itself linkableUnlinked :: [Unlinked] -- ^ Those files and chunks of code we have yet to link. -- -- INVARIANT: A valid linkable always has at least one 'Unlinked' item. -- If this list is empty, the Linkable represents a fake linkable, which -- is generated in HscNothing mode to avoid recompiling modules. -- -- ToDo: Do items get removed from this list when they get linked? } isObjectLinkable :: Linkable -> Bool isObjectLinkable l = not (null unlinked) && all isObject unlinked where unlinked = linkableUnlinked l -- A linkable with no Unlinked's is treated as a BCO. We can -- generate a linkable with no Unlinked's as a result of -- compiling a module in HscNothing mode, and this choice -- happens to work well with checkStability in module GHC. linkableObjs :: Linkable -> [FilePath] linkableObjs l = [ f | DotO f <- linkableUnlinked l ] instance Outputable Linkable where ppr (LM when_made mod unlinkeds) = (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod) $$ nest 3 (ppr unlinkeds) ------------------------------------------- -- | Objects which have yet to be linked by the compiler data Unlinked = DotO FilePath -- ^ An object file (.o) | DotA FilePath -- ^ Static archive file (.a) | DotDLL FilePath -- ^ Dynamically linked library file (.so, .dll, .dylib) | BCOs CompiledByteCode -- ^ A byte-code object, lives only in memory #ifndef GHCI data CompiledByteCode = CompiledByteCodeUndefined _unusedCompiledByteCode :: CompiledByteCode _unusedCompiledByteCode = CompiledByteCodeUndefined data ModBreaks = ModBreaksUndefined emptyModBreaks :: ModBreaks emptyModBreaks = ModBreaksUndefined #endif instance Outputable Unlinked where ppr (DotO path) = text "DotO" <+> text path ppr (DotA path) = text "DotA" <+> text path ppr (DotDLL path) = text "DotDLL" <+> text path #ifdef GHCI ppr (BCOs bcos) = text "BCOs" <+> ppr bcos #else ppr (BCOs _) = text "No byte code" #endif -- | Is this an actual file on disk we can link in somehow? isObject :: Unlinked -> Bool isObject (DotO _) = True isObject (DotA _) = True isObject (DotDLL _) = True isObject _ = False -- | Is this a bytecode linkable with no file on disk? isInterpretable :: Unlinked -> Bool isInterpretable = not . isObject -- | Retrieve the filename of the linkable if possible. Panic if it is a byte-code object nameOfObject :: Unlinked -> FilePath nameOfObject (DotO fn) = fn nameOfObject (DotA fn) = fn nameOfObject (DotDLL fn) = fn nameOfObject other = pprPanic "nameOfObject" (ppr other) -- | Retrieve the compiled byte-code if possible. Panic if it is a file-based linkable byteCodeOfObject :: Unlinked -> CompiledByteCode byteCodeOfObject (BCOs bc) = bc byteCodeOfObject other = pprPanic "byteCodeOfObject" (ppr other)
vikraman/ghc
compiler/main/HscTypes.hs
Haskell
bsd-3-clause
119,276
module Module2.Task4 where doItYourself = f . g . h f = logBase 2 g = (^ 3) h = max 42
dstarcev/stepic-haskell
src/Module2/Task4.hs
Haskell
bsd-3-clause
91
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} module Database.Relational.Schema.OracleDataDictionary.ConsColumns where import Data.Int (Int32) import Database.Record.TH (derivingShow) import Database.Relational.Query.TH (defineTableTypesAndRecordDefault) $(defineTableTypesAndRecordDefault "SYS" "dba_cons_columns" -- Column NULL? Datatype -- ----------------------------------------- -------- ---------------------------- -- OWNER NOT NULL VARCHAR2(30) [ ("owner", [t|String|]) -- CONSTRAINT_NAME NOT NULL VARCHAR2(30) , ("constraint_name", [t|String|]) -- TABLE_NAME NOT NULL VARCHAR2(30) , ("table_name", [t|String|]) -- COLUMN_NAME VARCHAR2(4000) , ("column_name", [t|Maybe String|]) -- POSITION NUMBER , ("position", [t|Maybe Int32|]) ] [derivingShow])
amutake/haskell-relational-record-driver-oracle
src/Database/Relational/Schema/OracleDataDictionary/ConsColumns.hs
Haskell
bsd-3-clause
1,052
module Import.NoFoundation ( module Import ) where import ClassyPrelude.Yesod as Import import Control.Concurrent.STM.TBMQueue as Import import Lens as Import import Model as Import import RPC as Import import Settings as Import import Settings.StaticFiles as Import import Types as Import import Yesod.Auth as Import import Yesod.Core.Types as Import (loggerSet) import Yesod.Default.Config2 as Import
konn/leport
leport-web/Import/NoFoundation.hs
Haskell
bsd-3-clause
611
module OIS ( module OIS.OISEvents , module OIS.OISFactoryCreator , module OIS.OISInputManager , module OIS.OISInterface , module OIS.OISJoyStick , module OIS.OISKeyboard , module OIS.OISMouse , module OIS.OISMultiTouch , module OIS.OISObject , module OIS.OISPrereqs ) where import OIS.OISEvents import OIS.OISFactoryCreator import OIS.OISInputManager import OIS.OISInterface import OIS.OISJoyStick import OIS.OISKeyboard import OIS.OISMouse import OIS.OISMultiTouch import OIS.OISObject import OIS.OISPrereqs
ghorn/hois
OIS.hs
Haskell
bsd-3-clause
620
{-# LANGUAGE PackageImports #-} {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MonoLocalBinds #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Generics.Product.Any -- Copyright : (C) 2020 Csongor Kiss -- License : BSD3 -- Maintainer : Csongor Kiss <kiss.csongor.kiss@gmail.com> -- Stability : experimental -- Portability : non-portable -- -- Derive a variety of lenses generically. -- ----------------------------------------------------------------------------- module Data.Generics.Product.Any ( -- *Lenses -- -- $setup HasAny (..) ) where import "this" Data.Generics.Internal.VL.Lens import "this" Data.Generics.Product.Fields import "this" Data.Generics.Product.Positions import "this" Data.Generics.Product.Typed -- $setup -- == /Running example:/ -- -- >>> :set -XTypeApplications -- >>> :set -XDataKinds -- >>> :set -XDeriveGeneric -- >>> import GHC.Generics -- >>> :m +Data.Generics.Internal.VL.Lens -- >>> :{ -- data Human = Human -- { name :: String -- , age :: Int -- , address :: String -- } -- deriving (Generic, Show) -- human :: Human -- human = Human "Tunyasz" 50 "London" -- :} class HasAny sel s t a b | s sel -> a where -- |A lens that focuses on a part of a product as identified by some -- selector. Currently supported selectors are field names, positions and -- unique types. Compatible with the lens package's 'Control.Lens.Lens' -- type. -- -- >>> human ^. the @Int -- 50 -- -- >>> human ^. the @"name" -- "Tunyasz" -- -- >>> human ^. the @3 -- "London" the :: Lens s t a b instance HasPosition i s t a b => HasAny i s t a b where the = position @i instance HasField field s t a b => HasAny field s t a b where the = field @field instance (HasType a s, t ~ s, a ~ b) => HasAny a s t a b where the = typed @a
kcsongor/generic-lens
generic-lens/src/Data/Generics/Product/Any.hs
Haskell
bsd-3-clause
2,226
----------------------------------------------------------------------------- -- | -- Copyright : (C) 2015 Dimitri Sabadie -- License : BSD3 -- -- Maintainer : Dimitri Sabadie <dimitri.sabadie@gmail.com> -- Stability : experimental -- Portability : portable ----------------------------------------------------------------------------- module Graphics.Luminance.Tuple where import Foreign.Storable ( Storable(..) ) import Foreign.Ptr ( castPtr, plusPtr ) -- |A tuple of types, right-associated. -- -- The Storable instance is used for foreign packing. data a :. b = a :. b deriving (Eq,Functor,Ord,Show) infixr 6 :. instance (Storable a,Storable b) => Storable (a :. b) where sizeOf (a :. b) = sizeOf a + sizeOf b alignment _ = 4 -- packed data peek p = do a <- peek $ castPtr p b <- peek . castPtr $ p `plusPtr` sizeOf (undefined :: a) pure $ a :. b poke p (a :. b) = do poke (castPtr p) a poke (castPtr $ p `plusPtr` sizeOf (undefined :: a)) b
apriori/luminance
src/Graphics/Luminance/Tuple.hs
Haskell
bsd-3-clause
988
{-# LANGUAGE CPP, OverloadedStrings #-} -- | Serve static files, subject to a policy that can filter or -- modify incoming URIs. The flow is: -- -- incoming request URI ==> policies ==> exists? ==> respond -- -- If any of the polices fail, or the file doesn't -- exist, then the middleware gives up and calls the inner application. -- If the file is found, the middleware chooses a content type based -- on the file extension and returns the file contents as the response. module Network.Wai.Middleware.Static ( -- * Middlewares static, staticPolicy, unsafeStaticPolicy , static', staticPolicy', unsafeStaticPolicy' , -- * Cache Control CachingStrategy(..), FileMeta(..), initCaching, CacheContainer , -- * Policies Policy, (<|>), (>->), policy, predicate , addBase, addSlash, contains, hasPrefix, hasSuffix, noDots, isNotAbsolute, only , -- * Utilities tryPolicy , -- * MIME types getMimeType ) where import Caching.ExpiringCacheMap.HashECM (newECMIO, lookupECM, CacheSettings(..), consistentDuration) import Control.Monad.Trans (liftIO) import Data.List import Data.Maybe (fromMaybe) #if !(MIN_VERSION_base(4,8,0)) import Data.Monoid #endif import Data.Time import Data.Time.Clock.POSIX import Network.HTTP.Types (status200, status304) import Network.HTTP.Types.Header (RequestHeaders) import Network.Wai import System.Directory (doesFileExist, getModificationTime) #if !(MIN_VERSION_time(1,5,0)) import System.Locale #endif import qualified Crypto.Hash.SHA1 as SHA1 import qualified Data.ByteString as B import qualified Data.ByteString as BS import qualified Data.ByteString.Base16 as B16 import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Lazy as BSL import qualified Data.Map as M import qualified Data.Text as T import qualified System.FilePath as FP -- | Take an incoming URI and optionally modify or filter it. -- The result will be treated as a filepath. newtype Policy = Policy { tryPolicy :: String -> Maybe String -- ^ Run a policy } -- | A cache strategy which should be used to -- serve content matching a policy. Meta information is cached for a maxium of -- 100 seconds before being recomputed. data CachingStrategy -- | Do not send any caching headers = NoCaching -- | Send common caching headers for public (non dynamic) static files | PublicStaticCaching -- | Compute caching headers using the user specified function. -- See <http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/> for a detailed guide | CustomCaching (FileMeta -> RequestHeaders) -- | Note: -- 'mempty' == @policy Just@ (the always accepting policy) -- 'mappend' == @>->@ (policy sequencing) instance Monoid Policy where mempty = policy Just mappend p1 p2 = policy (maybe Nothing (tryPolicy p2) . tryPolicy p1) -- | Lift a function into a 'Policy' policy :: (String -> Maybe String) -> Policy policy = Policy -- | Lift a predicate into a 'Policy' predicate :: (String -> Bool) -> Policy predicate p = policy (\s -> if p s then Just s else Nothing) -- | Sequence two policies. They are run from left to right. (Note: this is `mappend`) infixr 5 >-> (>->) :: Policy -> Policy -> Policy (>->) = mappend -- | Choose between two policies. If the first fails, run the second. infixr 4 <|> (<|>) :: Policy -> Policy -> Policy p1 <|> p2 = policy (\s -> maybe (tryPolicy p2 s) Just (tryPolicy p1 s)) -- | Add a base path to the URI -- -- > staticPolicy (addBase "/home/user/files") -- -- GET \"foo\/bar\" looks for \"\/home\/user\/files\/foo\/bar\" -- addBase :: String -> Policy addBase b = policy (Just . (b FP.</>)) -- | Add an initial slash to to the URI, if not already present. -- -- > staticPolicy addSlash -- -- GET \"foo\/bar\" looks for \"\/foo\/bar\" addSlash :: Policy addSlash = policy slashOpt where slashOpt s@('/':_) = Just s slashOpt s = Just ('/':s) -- | Accept only URIs with given suffix hasSuffix :: String -> Policy hasSuffix = predicate . isSuffixOf -- | Accept only URIs with given prefix hasPrefix :: String -> Policy hasPrefix = predicate . isPrefixOf -- | Accept only URIs containing given string contains :: String -> Policy contains = predicate . isInfixOf -- | Reject URIs containing \"..\" noDots :: Policy noDots = predicate (not . isInfixOf "..") -- | Reject URIs that are absolute paths isNotAbsolute :: Policy isNotAbsolute = predicate $ not . FP.isAbsolute -- | Use URI as the key to an association list, rejecting those not found. -- The policy result is the matching value. -- -- > staticPolicy (only [("foo/bar", "/home/user/files/bar")]) -- -- GET \"foo\/bar\" looks for \"\/home\/user\/files\/bar\" -- GET \"baz\/bar\" doesn't match anything -- only :: [(String,String)] -> Policy only al = policy (flip lookup al) -- | Serve static files out of the application root (current directory). -- If file is found, it is streamed to the client and no further middleware is run. Disables caching. -- -- Note: for security reasons, this uses the 'noDots' and 'isNotAbsolute' policy by default. static :: Middleware static = staticPolicy mempty -- | Serve static files out of the application root (current directory). -- If file is found, it is streamed to the client and no further middleware is run. Allows a 'CachingStrategy'. -- -- Note: for security reasons, this uses the 'noDots' and 'isNotAbsolute' policy by default. static' :: CacheContainer -> Middleware static' cc = staticPolicy' cc mempty -- | Serve static files subject to a 'Policy'. Disables caching. -- -- Note: for security reasons, this uses the 'noDots' and 'isNotAbsolute' policy by default. staticPolicy :: Policy -> Middleware staticPolicy = staticPolicy' CacheContainerEmpty -- | Serve static files subject to a 'Policy' using a specified 'CachingStrategy' -- -- Note: for security reasons, this uses the 'noDots' and 'isNotAbsolute' policy by default. staticPolicy' :: CacheContainer -> Policy -> Middleware staticPolicy' cc p = unsafeStaticPolicy' cc $ noDots >-> isNotAbsolute >-> p -- | Serve static files subject to a 'Policy'. Unlike 'static' and 'staticPolicy', this -- has no policies enabled by default, and is hence insecure. Disables caching. unsafeStaticPolicy :: Policy -> Middleware unsafeStaticPolicy = unsafeStaticPolicy' CacheContainerEmpty -- | Serve static files subject to a 'Policy'. Unlike 'static' and 'staticPolicy', this -- has no policies enabled by default, and is hence insecure. Also allows to set a 'CachingStrategy'. unsafeStaticPolicy' :: CacheContainer -> Policy -> Middleware unsafeStaticPolicy' cacheContainer p app req callback = maybe (app req callback) (\fp -> do exists <- liftIO $ doesFileExist fp if exists then case cacheContainer of CacheContainerEmpty -> sendFile fp [] CacheContainer _ NoCaching -> sendFile fp [] CacheContainer getFileMeta strategy -> do fileMeta <- getFileMeta fp if checkNotModified fileMeta (readHeader "If-Modified-Since") (readHeader "If-None-Match") then sendNotModified fileMeta strategy else sendFile fp (computeHeaders fileMeta strategy) else app req callback) (tryPolicy p $ T.unpack $ T.intercalate "/" $ pathInfo req) where readHeader header = lookup header $ requestHeaders req checkNotModified fm modSince etag = or [ Just (fm_lastModified fm) == modSince , Just (fm_etag fm) == etag ] computeHeaders fm cs = case cs of NoCaching -> [] PublicStaticCaching -> [ ("Cache-Control", "no-transform,public,max-age=300,s-maxage=900") , ("Last-Modified", fm_lastModified fm) , ("ETag", fm_etag fm) , ("Vary", "Accept-Encoding") ] CustomCaching f -> f fm sendNotModified fm cs = do let cacheHeaders = computeHeaders fm cs callback $ responseLBS status304 cacheHeaders BSL.empty sendFile fp extraHeaders = do let basicHeaders = [ ("Content-Type", getMimeType fp) ] headers = basicHeaders ++ extraHeaders callback $ responseFile status200 headers fp Nothing -- | Container caching file meta information. Create using 'initCaching' data CacheContainer = CacheContainerEmpty | CacheContainer (FilePath -> IO FileMeta) CachingStrategy -- | Meta information about a file to calculate cache headers data FileMeta = FileMeta { fm_lastModified :: !BS.ByteString , fm_etag :: !BS.ByteString , fm_fileName :: FilePath } deriving (Show, Eq) -- | Initialize caching. This should only be done once per application launch. initCaching :: CachingStrategy -> IO CacheContainer initCaching cs = do let cacheAccess = consistentDuration 100 $ \state fp -> do fileMeta <- computeFileMeta fp return $! (state, fileMeta) cacheTick = do time <- getPOSIXTime return (round (time * 100)) cacheFreq = 1 cacheLRU = CacheWithLRUList 100 100 200 filecache <- newECMIO cacheAccess cacheTick cacheFreq cacheLRU return (CacheContainer (lookupECM filecache) cs) computeFileMeta :: FilePath -> IO FileMeta computeFileMeta fp = do mtime <- getModificationTime fp ct <- BSL.readFile fp return $ FileMeta { fm_lastModified = BSC.pack $ formatTime defaultTimeLocale "%a, %d-%b-%Y %X %Z" mtime , fm_etag = B16.encode (SHA1.hashlazy ct) , fm_fileName = fp } type Ascii = B.ByteString -- | Guess MIME type from file extension getMimeType :: FilePath -> B.ByteString getMimeType = go . extensions where go [] = defaultMimeType go (ext:exts) = fromMaybe (go exts) $ M.lookup ext defaultMimeTypes extensions :: FilePath -> [String] extensions [] = [] extensions fp = case dropWhile (/= '.') fp of [] -> [] s -> let ext = tail s in ext : extensions ext defaultMimeType :: Ascii defaultMimeType = "application/octet-stream" -- This list taken from snap-core's Snap.Util.FileServe defaultMimeTypes :: M.Map String Ascii defaultMimeTypes = M.fromList [ ( "asc" , "text/plain" ), ( "asf" , "video/x-ms-asf" ), ( "asx" , "video/x-ms-asf" ), ( "avi" , "video/x-msvideo" ), ( "bz2" , "application/x-bzip" ), ( "c" , "text/plain" ), ( "class" , "application/octet-stream" ), ( "conf" , "text/plain" ), ( "cpp" , "text/plain" ), ( "css" , "text/css" ), ( "cxx" , "text/plain" ), ( "dtd" , "text/xml" ), ( "dvi" , "application/x-dvi" ), ( "gif" , "image/gif" ), ( "gz" , "application/x-gzip" ), ( "hs" , "text/plain" ), ( "htm" , "text/html" ), ( "html" , "text/html" ), ( "jar" , "application/x-java-archive" ), ( "jpeg" , "image/jpeg" ), ( "jpg" , "image/jpeg" ), ( "js" , "text/javascript" ), ( "json" , "application/json" ), ( "log" , "text/plain" ), ( "m3u" , "audio/x-mpegurl" ), ( "mov" , "video/quicktime" ), ( "mp3" , "audio/mpeg" ), ( "mp4" , "video/mp4" ), ( "mpeg" , "video/mpeg" ), ( "mpg" , "video/mpeg" ), ( "ogg" , "application/ogg" ), ( "ogv" , "video/ogg" ), ( "pac" , "application/x-ns-proxy-autoconfig" ), ( "pdf" , "application/pdf" ), ( "png" , "image/png" ), ( "ps" , "application/postscript" ), ( "qt" , "video/quicktime" ), ( "sig" , "application/pgp-signature" ), ( "spl" , "application/futuresplash" ), ( "svg" , "image/svg+xml" ), ( "swf" , "application/x-shockwave-flash" ), ( "tar" , "application/x-tar" ), ( "tar.bz2" , "application/x-bzip-compressed-tar" ), ( "tar.gz" , "application/x-tgz" ), ( "tbz" , "application/x-bzip-compressed-tar" ), ( "text" , "text/plain" ), ( "tgz" , "application/x-tgz" ), ( "torrent" , "application/x-bittorrent" ), ( "ttf" , "application/x-font-truetype" ), ( "txt" , "text/plain" ), ( "wav" , "audio/x-wav" ), ( "wax" , "audio/x-ms-wax" ), ( "wma" , "audio/x-ms-wma" ), ( "wmv" , "video/x-ms-wmv" ), ( "woff" , "application/font-woff" ), ( "xbm" , "image/x-xbitmap" ), ( "xml" , "text/xml" ), ( "xpm" , "image/x-xpixmap" ), ( "xwd" , "image/x-xwindowdump" ), ( "zip" , "application/zip" ) ]
Shimuuar/wai-middleware-static
Network/Wai/Middleware/Static.hs
Haskell
bsd-3-clause
14,041
module JFP.Threads where import Control.Concurrent import Control.Concurrent.STM import Control.Monad -- | Makes asynchronous message handler for handling hard tasks. Messages sent -- while handling previous message are dropped except last one. Last message is -- always handled. makeSequencer :: (a -> IO ()) -> IO (a -> IO ()) makeSequencer handler = do msgVar <- newEmptyTMVarIO let sender msg = atomically $ do done <- tryPutTMVar msgVar msg unless done $ void $ swapTMVar msgVar msg worker = forever $ do msg <- atomically $ takeTMVar msgVar handler msg void $ forkIO worker return sender
s9gf4ult/jfprrd
src/JFP/Threads.hs
Haskell
bsd-3-clause
640
{-# LANGUAGE QuasiQuotes #-} module Text.Parakeet ( parakeet , templateTeX , templateHTML , OutputFormat (..) , module Parakeet.Types.Options ) where import Control.Monad.Parakeet (runParakeet, SomeException) import Data.Text.Lazy (unpack) import Text.QuasiEmbedFile (rfile) import Parakeet.Parser.Parser (parse) import Parakeet.Printer.TeX (tex) import Parakeet.Printer.HTML (html) import Parakeet.Types.Options data OutputFormat = TeXFormat | HTMLFormat parakeet :: Options -> OutputFormat -> Either SomeException String parakeet opts format = runParakeet opts $ do parsed <- parse let printer = case format of TeXFormat -> tex HTMLFormat -> html unpack <$> printer parsed templateTeX :: String templateTeX = [rfile|template.tex|] templateHTML :: String templateHTML = [rfile|template.html|]
foreverbell/parakeet
src/Text/Parakeet.hs
Haskell
mit
846
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ViewPatterns#-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -ddump-splices #-} import Test.Hspec import Test.HUnit ((@?=)) import Data.Text (Text, pack, unpack, singleton) import Yesod.Routes.Class hiding (Route) import qualified Yesod.Routes.Class as YRC import Yesod.Routes.Parse (parseRoutesNoCheck, parseTypeTree, TypeTree (..)) import Yesod.Routes.Overlap (findOverlapNames) import Yesod.Routes.TH hiding (Dispatch) import Language.Haskell.TH.Syntax import Hierarchy import qualified Data.ByteString.Char8 as S8 import qualified Data.Set as Set data MyApp = MyApp data MySub = MySub instance RenderRoute MySub where data #if MIN_VERSION_base(4,5,0) Route #else YRC.Route #endif MySub = MySubRoute ([Text], [(Text, Text)]) deriving (Show, Eq, Read) renderRoute (MySubRoute x) = x instance ParseRoute MySub where parseRoute = Just . MySubRoute getMySub :: MyApp -> MySub getMySub MyApp = MySub data MySubParam = MySubParam Int instance RenderRoute MySubParam where data #if MIN_VERSION_base(4,5,0) Route #else YRC.Route #endif MySubParam = ParamRoute Char deriving (Show, Eq, Read) renderRoute (ParamRoute x) = ([singleton x], []) instance ParseRoute MySubParam where parseRoute ([unpack -> [x]], _) = Just $ ParamRoute x parseRoute _ = Nothing getMySubParam :: MyApp -> Int -> MySubParam getMySubParam _ = MySubParam do texts <- [t|[Text]|] let resLeaves = map ResourceLeaf [ Resource "RootR" [] (Methods Nothing ["GET"]) ["foo", "bar"] True , Resource "BlogPostR" [Static "blog", Dynamic $ ConT ''Text] (Methods Nothing ["GET", "POST"]) [] True , Resource "WikiR" [Static "wiki"] (Methods (Just texts) []) [] True , Resource "SubsiteR" [Static "subsite"] (Subsite (ConT ''MySub) "getMySub") [] True , Resource "SubparamR" [Static "subparam", Dynamic $ ConT ''Int] (Subsite (ConT ''MySubParam) "getMySubParam") [] True ] resParent = ResourceParent "ParentR" True [ Static "foo" , Dynamic $ ConT ''Text ] [ ResourceLeaf $ Resource "ChildR" [] (Methods Nothing ["GET"]) ["child"] True ] ress = resParent : resLeaves rrinst <- mkRenderRouteInstance (ConT ''MyApp) ress rainst <- mkRouteAttrsInstance (ConT ''MyApp) ress prinst <- mkParseRouteInstance (ConT ''MyApp) ress dispatch <- mkDispatchClause MkDispatchSettings { mdsRunHandler = [|runHandler|] , mdsSubDispatcher = [|subDispatch dispatcher|] , mdsGetPathInfo = [|fst|] , mdsMethod = [|snd|] , mdsSetPathInfo = [|\p (_, m) -> (p, m)|] , mds404 = [|pack "404"|] , mds405 = [|pack "405"|] , mdsGetHandler = defaultGetHandler , mdsUnwrapper = return } ress return #if MIN_VERSION_template_haskell(2,11,0) $ InstanceD Nothing #else $ InstanceD #endif [] (ConT ''Dispatcher `AppT` ConT ''MyApp `AppT` ConT ''MyApp) [FunD (mkName "dispatcher") [dispatch]] : prinst : rainst : rrinst instance Dispatcher MySub master where dispatcher env (pieces, _method) = ( pack $ "subsite: " ++ show pieces , Just $ envToMaster env route ) where route = MySubRoute (pieces, []) instance Dispatcher MySubParam master where dispatcher env (pieces, method) = case map unpack pieces of [[c]] -> let route = ParamRoute c toMaster = envToMaster env MySubParam i = envSub env in ( pack $ "subparam " ++ show i ++ ' ' : [c] , Just $ toMaster route ) _ -> (pack "404", Nothing) {- thDispatchAlias :: (master ~ MyApp, sub ~ MyApp, handler ~ String, app ~ (String, Maybe (YRC.Route MyApp))) => master -> sub -> (YRC.Route sub -> YRC.Route master) -> app -- ^ 404 page -> handler -- ^ 405 page -> Text -- ^ method -> [Text] -> app --thDispatchAlias = thDispatch thDispatchAlias master sub toMaster app404 handler405 method0 pieces0 = case dispatch pieces0 of Just f -> f master sub toMaster app404 handler405 method0 Nothing -> app404 where dispatch = toDispatch [ Route [] False $ \pieces -> case pieces of [] -> do Just $ \master' sub' toMaster' _app404' handler405' method -> let handler = case Map.lookup method methodsRootR of Just f -> f Nothing -> handler405' in runHandler handler master' sub' RootR toMaster' _ -> error "Invariant violated" , Route [D.Static "blog", D.Dynamic] False $ \pieces -> case pieces of [_, x2] -> do y2 <- fromPathPiece x2 Just $ \master' sub' toMaster' _app404' handler405' method -> let handler = case Map.lookup method methodsBlogPostR of Just f -> f y2 Nothing -> handler405' in runHandler handler master' sub' (BlogPostR y2) toMaster' _ -> error "Invariant violated" , Route [D.Static "wiki"] True $ \pieces -> case pieces of _:x2 -> do y2 <- fromPathMultiPiece x2 Just $ \master' sub' toMaster' _app404' _handler405' _method -> let handler = handleWikiR y2 in runHandler handler master' sub' (WikiR y2) toMaster' _ -> error "Invariant violated" , Route [D.Static "subsite"] True $ \pieces -> case pieces of _:x2 -> do Just $ \master' sub' toMaster' app404' handler405' method -> dispatcher master' (getMySub sub') (toMaster' . SubsiteR) app404' handler405' method x2 _ -> error "Invariant violated" , Route [D.Static "subparam", D.Dynamic] True $ \pieces -> case pieces of _:x2:x3 -> do y2 <- fromPathPiece x2 Just $ \master' sub' toMaster' app404' handler405' method -> dispatcher master' (getMySubParam sub' y2) (toMaster' . SubparamR y2) app404' handler405' method x3 _ -> error "Invariant violated" ] methodsRootR = Map.fromList [("GET", getRootR)] methodsBlogPostR = Map.fromList [("GET", getBlogPostR), ("POST", postBlogPostR)] -} main :: IO () main = hspec $ do describe "RenderRoute instance" $ do it "renders root correctly" $ renderRoute RootR @?= ([], []) it "renders blog post correctly" $ renderRoute (BlogPostR $ pack "foo") @?= (map pack ["blog", "foo"], []) it "renders wiki correctly" $ renderRoute (WikiR $ map pack ["foo", "bar"]) @?= (map pack ["wiki", "foo", "bar"], []) it "renders subsite correctly" $ renderRoute (SubsiteR $ MySubRoute (map pack ["foo", "bar"], [(pack "baz", pack "bin")])) @?= (map pack ["subsite", "foo", "bar"], [(pack "baz", pack "bin")]) it "renders subsite param correctly" $ renderRoute (SubparamR 6 $ ParamRoute 'c') @?= (map pack ["subparam", "6", "c"], []) describe "thDispatch" $ do let disp m ps = dispatcher (Env { envToMaster = id , envMaster = MyApp , envSub = MyApp }) (map pack ps, S8.pack m) it "routes to root" $ disp "GET" [] @?= (pack "this is the root", Just RootR) it "POST root is 405" $ disp "POST" [] @?= (pack "405", Just RootR) it "invalid page is a 404" $ disp "GET" ["not-found"] @?= (pack "404", Nothing :: Maybe (YRC.Route MyApp)) it "routes to blog post" $ disp "GET" ["blog", "somepost"] @?= (pack "some blog post: somepost", Just $ BlogPostR $ pack "somepost") it "routes to blog post, POST method" $ disp "POST" ["blog", "somepost2"] @?= (pack "POST some blog post: somepost2", Just $ BlogPostR $ pack "somepost2") it "routes to wiki" $ disp "DELETE" ["wiki", "foo", "bar"] @?= (pack "the wiki: [\"foo\",\"bar\"]", Just $ WikiR $ map pack ["foo", "bar"]) it "routes to subsite" $ disp "PUT" ["subsite", "baz"] @?= (pack "subsite: [\"baz\"]", Just $ SubsiteR $ MySubRoute ([pack "baz"], [])) it "routes to subparam" $ disp "PUT" ["subparam", "6", "q"] @?= (pack "subparam 6 q", Just $ SubparamR 6 $ ParamRoute 'q') describe "parsing" $ do it "subsites work" $ do parseRoute ([pack "subsite", pack "foo"], [(pack "bar", pack "baz")]) @?= Just (SubsiteR $ MySubRoute ([pack "foo"], [(pack "bar", pack "baz")])) describe "overlap checking" $ do it "catches overlapping statics" $ do let routes = [parseRoutesNoCheck| /foo Foo1 /foo Foo2 |] findOverlapNames routes @?= [("Foo1", "Foo2")] it "catches overlapping dynamics" $ do let routes = [parseRoutesNoCheck| /#Int Foo1 /#String Foo2 |] findOverlapNames routes @?= [("Foo1", "Foo2")] it "catches overlapping statics and dynamics" $ do let routes = [parseRoutesNoCheck| /foo Foo1 /#String Foo2 |] findOverlapNames routes @?= [("Foo1", "Foo2")] it "catches overlapping multi" $ do let routes = [parseRoutesNoCheck| /foo Foo1 /##*Strings Foo2 |] findOverlapNames routes @?= [("Foo1", "Foo2")] it "catches overlapping subsite" $ do let routes = [parseRoutesNoCheck| /foo Foo1 /foo Foo2 Subsite getSubsite |] findOverlapNames routes @?= [("Foo1", "Foo2")] it "no false positives" $ do let routes = [parseRoutesNoCheck| /foo Foo1 /bar/#String Foo2 |] findOverlapNames routes @?= [] it "obeys ignore rules" $ do let routes = [parseRoutesNoCheck| /foo Foo1 /#!String Foo2 /!foo Foo3 |] findOverlapNames routes @?= [] it "obeys multipiece ignore rules #779" $ do let routes = [parseRoutesNoCheck| /foo Foo1 /+![String] Foo2 |] findOverlapNames routes @?= [] it "ignore rules for entire route #779" $ do let routes = [parseRoutesNoCheck| /foo Foo1 !/+[String] Foo2 !/#String Foo3 !/foo Foo4 |] findOverlapNames routes @?= [] it "ignore rules for hierarchy" $ do let routes = [parseRoutesNoCheck| /+[String] Foo1 !/foo Foo2: /foo Foo3 /foo Foo4: /!#foo Foo5 |] findOverlapNames routes @?= [] it "proper boolean logic" $ do let routes = [parseRoutesNoCheck| /foo/bar Foo1 /foo/baz Foo2 /bar/baz Foo3 |] findOverlapNames routes @?= [] describe "routeAttrs" $ do it "works" $ do routeAttrs RootR @?= Set.fromList [pack "foo", pack "bar"] it "hierarchy" $ do routeAttrs (ParentR (pack "ignored") ChildR) @?= Set.singleton (pack "child") hierarchy describe "parseRouteTyoe" $ do let success s t = it s $ parseTypeTree s @?= Just t failure s = it s $ parseTypeTree s @?= Nothing success "Int" $ TTTerm "Int" success "(Int)" $ TTTerm "Int" failure "(Int" failure "(Int))" failure "[Int" failure "[Int]]" success "[Int]" $ TTList $ TTTerm "Int" success "Foo-Bar" $ TTApp (TTTerm "Foo") (TTTerm "Bar") success "Foo-Bar-Baz" $ TTApp (TTTerm "Foo") (TTTerm "Bar") `TTApp` TTTerm "Baz" getRootR :: Text getRootR = pack "this is the root" getBlogPostR :: Text -> String getBlogPostR t = "some blog post: " ++ unpack t postBlogPostR :: Text -> Text postBlogPostR t = pack $ "POST some blog post: " ++ unpack t handleWikiR :: [Text] -> String handleWikiR ts = "the wiki: " ++ show ts getChildR :: Text -> Text getChildR = id
tolysz/yesod
yesod-core/test/RouteSpec.hs
Haskell
mit
12,733
-- -- -- ------------------ -- Exercise 11.32. ------------------ -- -- -- module E'11'32 where -- Notes: -- -- - Use/See templates for proofs by structural induction. -- - Note: Re/-member/-think/-view the definitions of "++", "." and "foldr". -- --------------- -- 1. Proposition: -- --------------- -- -- foldr f st (xs ++ ys) = f (foldr f st xs) (foldr f st ys) -- -- -- Assumption 1: "f" is associative -- -- Assumption 2: "st" is an identity for "f" -- -- -- Proof By Structural Induction: -- ------------------------------ -- -- -- 1. Induction Beginning (1. I.B.): -- --------------------------------- -- -- -- (Base case 1.) :<=> xs := [] -- -- => (left) := foldr f st (xs ++ ys) -- | (Base case 1.) -- = foldr f st ([] ++ ys) -- | ++ -- = foldr f st ys -- -- -- (right) := f (foldr f st xs) (foldr f st ys) -- | (Base case 1.) -- = f (foldr f st []) (foldr f st ys) -- | (Assumption 1) -- | foldr -- = f st (foldr f st ys) -- | (Assumption 2) -- | st -- = foldr f st ys -- -- -- => (left) = (right) -- -- ✔ -- -- -- 1. Induction Hypothesis (1. I.H.): -- ---------------------------------- -- -- For all lists "ys" and for an arbitrary, but fixed "xs", the statement ... -- -- foldr f st (xs ++ ys) = f (foldr f st xs) (foldr f st ys) -- -- ... holds. -- -- -- 1. Induction Step (1. I.S.): -- ---------------------------- -- -- -- (left) := foldr f st ( (x : xs) ++ ys ) -- | ++ -- = foldr f st ( x : (xs ++ ys) ) -- | (Assumption 1) -- | foldr -- = x `f` foldr f st (xs ++ ys) -- | (1. I.H.) -- = x `f` f (foldr f st xs) (foldr f st ys) -- -- = x `f` (foldr f st xs) `f` (foldr f st ys) -- -- = ( x `f` (foldr f st xs) ) `f` (foldr f st ys) -- | General rule of function application (left associativity) -- = ( foldr f st (x : xs) ) `f` (foldr f st ys) -- -- -- (right) := f ( foldr f st (x : xs) ) (foldr f st ys) -- -- = ( foldr f st (x : xs) ) `f` (foldr f st ys) -- -- -- => (left) = (right) -- -- -- ■ (1. Proof) -- Question: Is "foldr f st ( foldr (++) [] ls ) = foldr ( f . (foldr f st) ) st ls" true?
pascal-knodel/haskell-craft
_/links/E'11'32.hs
Haskell
mit
3,008
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module %PACKAGE%.%MODEL% ( module Export )where import %PACKAGE%.%MODEL%.Import import %PACKAGE%.%MODEL%.Foundation as Export import %PACKAGE%.%MODEL%.Models as Export import %PACKAGE%.%MODEL%.Handler.%MODEL% as Export instance %PACKAGE%%MODEL% master => YesodSubDispatch %MODEL%Admin (HandlerT master IO) where yesodSubDispatch = $(mkYesodSubDispatch resources%MODEL%Admin)
lambdacms/lambdacms
scaffold-extension/PACKAGE/MODEL.hs
Haskell
mit
649
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} module Database.Persist.Postgresql.Internal ( P(..) , PgInterval(..) , getGetter ) where import qualified Database.PostgreSQL.Simple as PG import qualified Database.PostgreSQL.Simple.FromField as PGFF import qualified Database.PostgreSQL.Simple.Internal as PG import qualified Database.PostgreSQL.Simple.ToField as PGTF import qualified Database.PostgreSQL.Simple.TypeInfo.Static as PS import qualified Database.PostgreSQL.Simple.Types as PG import qualified Blaze.ByteString.Builder.Char8 as BBB import qualified Data.Attoparsec.ByteString.Char8 as P import Data.Bits ((.&.)) import Data.ByteString (ByteString) import qualified Data.ByteString.Builder as BB import qualified Data.ByteString.Char8 as B8 import Data.Char (ord) import Data.Data (Typeable) import Data.Fixed (Fixed(..), Pico) import Data.Int (Int64) import qualified Data.IntMap as I import Data.Maybe (fromMaybe) import Data.String.Conversions.Monomorphic (toStrictByteString) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import Data.Time (NominalDiffTime, localTimeToUTC, utc) import Database.Persist.Sql -- | Newtype used to avoid orphan instances for @postgresql-simple@ classes. -- -- @since 2.13.2.0 newtype P = P { unP :: PersistValue } instance PGTF.ToField P where toField (P (PersistText t)) = PGTF.toField t toField (P (PersistByteString bs)) = PGTF.toField (PG.Binary bs) toField (P (PersistInt64 i)) = PGTF.toField i toField (P (PersistDouble d)) = PGTF.toField d toField (P (PersistRational r)) = PGTF.Plain $ BBB.fromString $ show (fromRational r :: Pico) -- FIXME: Too Ambigous, can not select precision without information about field toField (P (PersistBool b)) = PGTF.toField b toField (P (PersistDay d)) = PGTF.toField d toField (P (PersistTimeOfDay t)) = PGTF.toField t toField (P (PersistUTCTime t)) = PGTF.toField t toField (P PersistNull) = PGTF.toField PG.Null toField (P (PersistList l)) = PGTF.toField $ listToJSON l toField (P (PersistMap m)) = PGTF.toField $ mapToJSON m toField (P (PersistLiteral_ DbSpecific s)) = PGTF.toField (Unknown s) toField (P (PersistLiteral_ Unescaped l)) = PGTF.toField (UnknownLiteral l) toField (P (PersistLiteral_ Escaped e)) = PGTF.toField (Unknown e) toField (P (PersistArray a)) = PGTF.toField $ PG.PGArray $ P <$> a toField (P (PersistObjectId _)) = error "Refusing to serialize a PersistObjectId to a PostgreSQL value" instance PGFF.FromField P where fromField field mdata = fmap P $ case mdata of -- If we try to simply decode based on oid, we will hit unexpected null -- errors. Nothing -> pure PersistNull data' -> getGetter (PGFF.typeOid field) field data' newtype Unknown = Unknown { unUnknown :: ByteString } deriving (Eq, Show, Read, Ord) instance PGFF.FromField Unknown where fromField f mdata = case mdata of Nothing -> PGFF.returnError PGFF.UnexpectedNull f "Database.Persist.Postgresql/PGFF.FromField Unknown" Just dat -> return (Unknown dat) instance PGTF.ToField Unknown where toField (Unknown a) = PGTF.Escape a newtype UnknownLiteral = UnknownLiteral { unUnknownLiteral :: ByteString } deriving (Eq, Show, Read, Ord, Typeable) instance PGFF.FromField UnknownLiteral where fromField f mdata = case mdata of Nothing -> PGFF.returnError PGFF.UnexpectedNull f "Database.Persist.Postgresql/PGFF.FromField UnknownLiteral" Just dat -> return (UnknownLiteral dat) instance PGTF.ToField UnknownLiteral where toField (UnknownLiteral a) = PGTF.Plain $ BB.byteString a type Getter a = PGFF.FieldParser a convertPV :: PGFF.FromField a => (a -> b) -> Getter b convertPV f = (fmap f .) . PGFF.fromField builtinGetters :: I.IntMap (Getter PersistValue) builtinGetters = I.fromList [ (k PS.bool, convertPV PersistBool) , (k PS.bytea, convertPV (PersistByteString . unBinary)) , (k PS.char, convertPV PersistText) , (k PS.name, convertPV PersistText) , (k PS.int8, convertPV PersistInt64) , (k PS.int2, convertPV PersistInt64) , (k PS.int4, convertPV PersistInt64) , (k PS.text, convertPV PersistText) , (k PS.xml, convertPV (PersistByteString . unUnknown)) , (k PS.float4, convertPV PersistDouble) , (k PS.float8, convertPV PersistDouble) , (k PS.money, convertPV PersistRational) , (k PS.bpchar, convertPV PersistText) , (k PS.varchar, convertPV PersistText) , (k PS.date, convertPV PersistDay) , (k PS.time, convertPV PersistTimeOfDay) , (k PS.timestamp, convertPV (PersistUTCTime. localTimeToUTC utc)) , (k PS.timestamptz, convertPV PersistUTCTime) , (k PS.interval, convertPV (PersistLiteralEscaped . pgIntervalToBs)) , (k PS.bit, convertPV PersistInt64) , (k PS.varbit, convertPV PersistInt64) , (k PS.numeric, convertPV PersistRational) , (k PS.void, \_ _ -> return PersistNull) , (k PS.json, convertPV (PersistByteString . unUnknown)) , (k PS.jsonb, convertPV (PersistByteString . unUnknown)) , (k PS.unknown, convertPV (PersistByteString . unUnknown)) -- Array types: same order as above. -- The OIDs were taken from pg_type. , (1000, listOf PersistBool) , (1001, listOf (PersistByteString . unBinary)) , (1002, listOf PersistText) , (1003, listOf PersistText) , (1016, listOf PersistInt64) , (1005, listOf PersistInt64) , (1007, listOf PersistInt64) , (1009, listOf PersistText) , (143, listOf (PersistByteString . unUnknown)) , (1021, listOf PersistDouble) , (1022, listOf PersistDouble) , (1023, listOf PersistUTCTime) , (1024, listOf PersistUTCTime) , (791, listOf PersistRational) , (1014, listOf PersistText) , (1015, listOf PersistText) , (1182, listOf PersistDay) , (1183, listOf PersistTimeOfDay) , (1115, listOf PersistUTCTime) , (1185, listOf PersistUTCTime) , (1187, listOf (PersistLiteralEscaped . pgIntervalToBs)) , (1561, listOf PersistInt64) , (1563, listOf PersistInt64) , (1231, listOf PersistRational) -- no array(void) type , (2951, listOf (PersistLiteralEscaped . unUnknown)) , (199, listOf (PersistByteString . unUnknown)) , (3807, listOf (PersistByteString . unUnknown)) -- no array(unknown) either ] where k (PGFF.typoid -> i) = PG.oid2int i -- A @listOf f@ will use a @PGArray (Maybe T)@ to convert -- the values to Haskell-land. The @Maybe@ is important -- because the usual way of checking NULLs -- (c.f. withStmt') won't check for NULL inside -- arrays---or any other compound structure for that matter. listOf f = convertPV (PersistList . map (nullable f) . PG.fromPGArray) where nullable = maybe PersistNull -- | Get the field parser corresponding to the given 'PG.Oid'. -- -- For example, pass in the 'PG.Oid' of 'PS.bool', and you will get back a -- field parser which parses boolean values in the table into 'PersistBool's. -- -- @since 2.13.2.0 getGetter :: PG.Oid -> Getter PersistValue getGetter oid = fromMaybe defaultGetter $ I.lookup (PG.oid2int oid) builtinGetters where defaultGetter = convertPV (PersistLiteralEscaped . unUnknown) unBinary :: PG.Binary a -> a unBinary (PG.Binary x) = x -- | Represent Postgres interval using NominalDiffTime -- -- @since 2.11.0.0 newtype PgInterval = PgInterval { getPgInterval :: NominalDiffTime } deriving (Eq, Show) pgIntervalToBs :: PgInterval -> ByteString pgIntervalToBs = toStrictByteString . show . getPgInterval instance PGTF.ToField PgInterval where toField (PgInterval t) = PGTF.toField t instance PGFF.FromField PgInterval where fromField f mdata = if PGFF.typeOid f /= PS.typoid PS.interval then PGFF.returnError PGFF.Incompatible f "" else case mdata of Nothing -> PGFF.returnError PGFF.UnexpectedNull f "" Just dat -> case P.parseOnly (nominalDiffTime <* P.endOfInput) dat of Left msg -> PGFF.returnError PGFF.ConversionFailed f msg Right t -> return $ PgInterval t where toPico :: Integer -> Pico toPico = MkFixed -- Taken from Database.PostgreSQL.Simple.Time.Internal.Parser twoDigits :: P.Parser Int twoDigits = do a <- P.digit b <- P.digit let c2d c = ord c .&. 15 return $! c2d a * 10 + c2d b -- Taken from Database.PostgreSQL.Simple.Time.Internal.Parser seconds :: P.Parser Pico seconds = do real <- twoDigits mc <- P.peekChar case mc of Just '.' -> do t <- P.anyChar *> P.takeWhile1 P.isDigit return $! parsePicos (fromIntegral real) t _ -> return $! fromIntegral real where parsePicos :: Int64 -> B8.ByteString -> Pico parsePicos a0 t = toPico (fromIntegral (t' * 10^n)) where n = max 0 (12 - B8.length t) t' = B8.foldl' (\a c -> 10 * a + fromIntegral (ord c .&. 15)) a0 (B8.take 12 t) parseSign :: P.Parser Bool parseSign = P.choice [P.char '-' >> return True, return False] -- Db stores it in [-]HHH:MM:SS.[SSSS] -- For example, nominalDay is stored as 24:00:00 interval :: P.Parser (Bool, Int, Int, Pico) interval = do s <- parseSign h <- P.decimal <* P.char ':' m <- twoDigits <* P.char ':' ss <- seconds if m < 60 && ss <= 60 then return (s, h, m, ss) else fail "Invalid interval" nominalDiffTime :: P.Parser NominalDiffTime nominalDiffTime = do (s, h, m, ss) <- interval let pico = ss + 60 * (fromIntegral m) + 60 * 60 * (fromIntegral (abs h)) return . fromRational . toRational $ if s then (-pico) else pico fromPersistValueError :: Text -- ^ Haskell type, should match Haskell name exactly, e.g. "Int64" -> Text -- ^ Database type(s), should appear different from Haskell name, e.g. "integer" or "INT", not "Int". -> PersistValue -- ^ Incorrect value -> Text -- ^ Error message fromPersistValueError haskellType databaseType received = T.concat [ "Failed to parse Haskell type `" , haskellType , "`; expected " , databaseType , " from database, but received: " , T.pack (show received) , ". Potential solution: Check that your database schema matches your Persistent model definitions." ] instance PersistField PgInterval where toPersistValue = PersistLiteralEscaped . pgIntervalToBs fromPersistValue (PersistLiteral_ DbSpecific bs) = fromPersistValue (PersistLiteralEscaped bs) fromPersistValue x@(PersistLiteral_ Escaped bs) = case P.parseOnly (P.signed P.rational <* P.char 's' <* P.endOfInput) bs of Left _ -> Left $ fromPersistValueError "PgInterval" "Interval" x Right i -> Right $ PgInterval i fromPersistValue x = Left $ fromPersistValueError "PgInterval" "Interval" x instance PersistFieldSql PgInterval where sqlType _ = SqlOther "interval"
paul-rouse/persistent
persistent-postgresql/Database/Persist/Postgresql/Internal.hs
Haskell
mit
11,983
import Data.Time.Calendar import Data.Time.Calendar.WeekDate ans = length [(y,m,d) | y <- [1901..2000], m <- [1..12], let (_, _, d) = toWeekDate $ fromGregorian y m 1, d == 7]
stefan-j/ProjectEuler
q19.hs
Haskell
mit
271
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Snap.Internal.Http.Server.Socket.Tests (tests) where ------------------------------------------------------------------------------ import Control.Applicative ((<$>)) import qualified Network.Socket as N ------------------------------------------------------------------------------ import Control.Concurrent (forkIO, killThread, newEmptyMVar, putMVar, readMVar, takeMVar) import qualified Control.Exception as E import Data.IORef (newIORef, readIORef, writeIORef) import Test.Framework (Test) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (assertEqual) ------------------------------------------------------------------------------ import qualified Snap.Internal.Http.Server.Socket as Sock import Snap.Test.Common (eatException, expectException, withSock) ------------------------------------------------------------------------------ #ifdef HAS_UNIX_SOCKETS import System.Directory (getTemporaryDirectory) import System.FilePath ((</>)) import qualified System.Posix as Posix # if !MIN_VERSION_unix(2,6,0) import Control.Monad.State (replicateM) import Control.Monad.Trans.State.Strict as State import qualified Data.Vector.Unboxed as V import System.Directory (createDirectoryIfMissing) import System.Random (StdGen, newStdGen, randomR) # endif #else import Snap.Internal.Http.Server.Address (AddressNotSupportedException) #endif ------------------------------------------------------------------------------ #ifdef HAS_UNIX_SOCKETS mkdtemp :: String -> IO FilePath # if MIN_VERSION_unix(2,6,0) mkdtemp = Posix.mkdtemp # else tMPCHARS :: V.Vector Char tMPCHARS = V.fromList $! ['a'..'z'] ++ ['0'..'9'] mkdtemp template = do suffix <- newStdGen >>= return . State.evalState (chooseN 8 tMPCHARS) let dir = template ++ suffix createDirectoryIfMissing False dir return dir where choose :: V.Vector Char -> State.State StdGen Char choose v = do let sz = V.length v idx <- State.state $ randomR (0, sz - 1) return $! (V.!) v idx chooseN :: Int -> V.Vector Char -> State.State StdGen String chooseN n v = replicateM n $ choose v #endif #endif ------------------------------------------------------------------------------ tests :: [Test] tests = [ testSockClosedOnListenException , testAcceptFailure , testUnixSocketBind ] ------------------------------------------------------------------------------ testSockClosedOnListenException :: Test testSockClosedOnListenException = testCase "socket/closedOnListenException" $ do ref <- newIORef Nothing expectException $ Sock.bindSocketImpl (sso ref) bs ls "127.0.0.1" 4444 (Just sock) <- readIORef ref let (N.MkSocket _ _ _ _ mvar) = sock readMVar mvar >>= assertEqual "socket closed" N.Closed where sso ref sock _ _ = do let (N.MkSocket _ _ _ _ mvar) = sock readMVar mvar >>= assertEqual "socket not connected" N.NotConnected writeIORef ref (Just sock) >> fail "set socket option" bs _ _ = fail "bindsocket" ls _ _ = fail "listen" ------------------------------------------------------------------------------ testAcceptFailure :: Test testAcceptFailure = testCase "socket/acceptAndInitialize" $ do sockmvar <- newEmptyMVar donemvar <- newEmptyMVar E.bracket (Sock.bindSocket "127.0.0.1" $ fromIntegral N.aNY_PORT) (N.close) (\s -> do p <- fromIntegral <$> N.socketPort s forkIO $ server s sockmvar donemvar E.bracket (forkIO $ client p) (killThread) (\_ -> do csock <- takeMVar sockmvar takeMVar donemvar N.isConnected csock >>= assertEqual "closed" False ) ) where server sock sockmvar donemvar = serve `E.finally` putMVar donemvar () where serve = eatException $ E.mask $ \restore -> Sock.acceptAndInitialize sock restore $ \(csock, _) -> do putMVar sockmvar csock fail "error" client port = withSock port (const $ return ()) testUnixSocketBind :: Test #ifdef HAS_UNIX_SOCKETS testUnixSocketBind = testCase "socket/unixSocketBind" $ withSocketPath $ \path -> do E.bracket (Sock.bindUnixSocket Nothing path) N.close $ \sock -> do N.isListening sock >>= assertEqual "listening" True expectException $ E.bracket (Sock.bindUnixSocket Nothing "a/relative/path") N.close doNothing expectException $ E.bracket (Sock.bindUnixSocket Nothing "/relative/../path") N.close doNothing expectException $ E.bracket (Sock.bindUnixSocket Nothing "/hopefully/not/existing/path") N.close doNothing #ifdef LINUX -- Most (all?) BSD systems ignore access mode on unix sockets. -- Should we still check it? -- This is pretty much for 100% coverage expectException $ E.bracket (Sock.bindUnixSocket Nothing "/") N.close doNothing let mode = 0o766 E.bracket (Sock.bindUnixSocket (Just mode) path) N.close $ \_ -> do -- Should check sockFd instead of path? sockMode <- fmap Posix.fileMode $ Posix.getFileStatus path assertEqual "access mode" (fromIntegral mode) $ Posix.intersectFileModes Posix.accessModes sockMode #endif where doNothing _ = return () withSocketPath act = do tmpRoot <- getTemporaryDirectory tmpDir <- mkdtemp $ tmpRoot </> "snap-server-test-" let path = tmpDir </> "unixSocketBind.sock" E.finally (act path) $ do eatException $ Posix.removeLink path eatException $ Posix.removeDirectory tmpDir #else testUnixSocketBind = testCase "socket/unixSocketBind" $ do caught <- E.catch (Sock.bindUnixSocket Nothing "/tmp/snap-sock.sock" >> return False) $ \(e :: AddressNotSupportedException) -> length (show e) `seq` return True assertEqual "not supported" True caught #endif
23Skidoo/snap-server
test/Snap/Internal/Http/Server/Socket/Tests.hs
Haskell
bsd-3-clause
6,678
module BootImport where data Foo = Foo Int
mpickering/ghc-exactprint
tests/examples/ghc710/BootImport.hs
Haskell
bsd-3-clause
44
module Propellor.Property.HostingProvider.CloudAtCost where import Propellor import qualified Propellor.Property.Hostname as Hostname import qualified Propellor.Property.File as File import qualified Propellor.Property.User as User -- Clean up a system as installed by cloudatcost.com decruft :: Property NoInfo decruft = propertyList "cloudatcost cleanup" [ Hostname.sane , "worked around grub/lvm boot bug #743126" ==> "/etc/default/grub" `File.containsLine` "GRUB_DISABLE_LINUX_UUID=true" `onChange` cmdProperty "update-grub" [] `onChange` cmdProperty "update-initramfs" ["-u"] , combineProperties "nuked cloudatcost cruft" [ File.notPresent "/etc/rc.local" , File.notPresent "/etc/init.d/S97-setup.sh" , File.notPresent "/zang-debian.sh" , User.nuked "user" User.YesReallyDeleteHome ] ]
avengerpenguin/propellor
src/Propellor/Property/HostingProvider/CloudAtCost.hs
Haskell
bsd-2-clause
814
{- | The public face of Template Haskell For other documentation, refer to: <http://www.haskell.org/haskellwiki/Template_Haskell> -} module Language.Haskell.TH( -- * The monad and its operations Q, runQ, -- ** Administration: errors, locations and IO reportError, -- :: String -> Q () reportWarning, -- :: String -> Q () report, -- :: Bool -> String -> Q () recover, -- :: Q a -> Q a -> Q a location, -- :: Q Loc Loc(..), runIO, -- :: IO a -> Q a -- ** Querying the compiler -- *** Reify reify, -- :: Name -> Q Info reifyModule, thisModule, Info(..), ModuleInfo(..), InstanceDec, ParentName, Arity, Unlifted, -- *** Language extension lookup Extension(..), extsEnabled, isExtEnabled, -- *** Name lookup lookupTypeName, -- :: String -> Q (Maybe Name) lookupValueName, -- :: String -> Q (Maybe Name) -- *** Fixity lookup reifyFixity, -- *** Instance lookup reifyInstances, isInstance, -- *** Roles lookup reifyRoles, -- *** Annotation lookup reifyAnnotations, AnnLookup(..), -- *** Constructor strictness lookup reifyConStrictness, -- * Typed expressions TExp, unType, -- * Names Name, NameSpace, -- Abstract -- ** Constructing names mkName, -- :: String -> Name newName, -- :: String -> Q Name -- ** Deconstructing names nameBase, -- :: Name -> String nameModule, -- :: Name -> Maybe String namePackage, -- :: Name -> Maybe String nameSpace, -- :: Name -> Maybe NameSpace -- ** Built-in names tupleTypeName, tupleDataName, -- Int -> Name unboxedTupleTypeName, unboxedTupleDataName, -- :: Int -> Name -- * The algebraic data types -- | The lowercase versions (/syntax operators/) of these constructors are -- preferred to these constructors, since they compose better with -- quotations (@[| |]@) and splices (@$( ... )@) -- ** Declarations Dec(..), Con(..), Clause(..), SourceUnpackedness(..), SourceStrictness(..), DecidedStrictness(..), Bang(..), Strict, Foreign(..), Callconv(..), Safety(..), Pragma(..), Inline(..), RuleMatch(..), Phases(..), RuleBndr(..), AnnTarget(..), FunDep(..), FamFlavour(..), TySynEqn(..), TypeFamilyHead(..), Fixity(..), FixityDirection(..), defaultFixity, maxPrecedence, PatSynDir(..), PatSynArgs(..), -- ** Expressions Exp(..), Match(..), Body(..), Guard(..), Stmt(..), Range(..), Lit(..), -- ** Patterns Pat(..), FieldExp, FieldPat, -- ** Types Type(..), TyVarBndr(..), TyLit(..), Kind, Cxt, Pred, Syntax.Role(..), FamilyResultSig(..), Syntax.InjectivityAnn(..), PatSynType, -- * Library functions -- ** Abbreviations InfoQ, ExpQ, DecQ, DecsQ, ConQ, TypeQ, TyLitQ, CxtQ, PredQ, MatchQ, ClauseQ, BodyQ, GuardQ, StmtQ, RangeQ, SourceStrictnessQ, SourceUnpackednessQ, BangTypeQ, VarBangTypeQ, StrictTypeQ, VarStrictTypeQ, PatQ, FieldPatQ, RuleBndrQ, TySynEqnQ, PatSynDirQ, PatSynArgsQ, -- ** Constructors lifted to 'Q' -- *** Literals intPrimL, wordPrimL, floatPrimL, doublePrimL, integerL, rationalL, charL, stringL, stringPrimL, charPrimL, -- *** Patterns litP, varP, tupP, conP, uInfixP, parensP, infixP, tildeP, bangP, asP, wildP, recP, listP, sigP, viewP, fieldPat, -- *** Pattern Guards normalB, guardedB, normalG, normalGE, patG, patGE, match, clause, -- *** Expressions dyn, varE, conE, litE, appE, uInfixE, parensE, staticE, infixE, infixApp, sectionL, sectionR, lamE, lam1E, lamCaseE, tupE, condE, multiIfE, letE, caseE, appsE, listE, sigE, recConE, recUpdE, stringE, fieldExp, -- **** Ranges fromE, fromThenE, fromToE, fromThenToE, -- ***** Ranges with more indirection arithSeqE, fromR, fromThenR, fromToR, fromThenToR, -- **** Statements doE, compE, bindS, letS, noBindS, parS, -- *** Types forallT, varT, conT, appT, arrowT, infixT, uInfixT, parensT, equalityT, listT, tupleT, sigT, litT, promotedT, promotedTupleT, promotedNilT, promotedConsT, -- **** Type literals numTyLit, strTyLit, -- **** Strictness noSourceUnpackedness, sourceNoUnpack, sourceUnpack, noSourceStrictness, sourceLazy, sourceStrict, isStrict, notStrict, unpacked, bang, bangType, varBangType, strictType, varStrictType, -- **** Class Contexts cxt, classP, equalP, -- **** Constructors normalC, recC, infixC, forallC, gadtC, recGadtC, -- *** Kinds varK, conK, tupleK, arrowK, listK, appK, starK, constraintK, -- *** Roles nominalR, representationalR, phantomR, inferR, -- *** Top Level Declarations -- **** Data valD, funD, tySynD, dataD, newtypeD, -- **** Class classD, instanceD, instanceWithOverlapD, Overlap(..), sigD, standaloneDerivD, defaultSigD, -- **** Role annotations roleAnnotD, -- **** Type Family / Data Family dataFamilyD, openTypeFamilyD, closedTypeFamilyD, dataInstD, familyNoKindD, familyKindD, closedTypeFamilyNoKindD, closedTypeFamilyKindD, newtypeInstD, tySynInstD, typeFam, dataFam, tySynEqn, injectivityAnn, noSig, kindSig, tyVarSig, -- **** Foreign Function Interface (FFI) cCall, stdCall, cApi, prim, javaScript, unsafe, safe, forImpD, -- **** Pragmas ruleVar, typedRuleVar, pragInlD, pragSpecD, pragSpecInlD, pragSpecInstD, pragRuleD, pragAnnD, pragLineD, -- **** Pattern Synonyms patSynD, patSynSigD, unidir, implBidir, explBidir, prefixPatSyn, infixPatSyn, recordPatSyn, -- * Pretty-printer Ppr(..), pprint, pprExp, pprLit, pprPat, pprParendType ) where import Language.Haskell.TH.Syntax as Syntax import Language.Haskell.TH.Lib import Language.Haskell.TH.Ppr
vikraman/ghc
libraries/template-haskell/Language/Haskell/TH.hs
Haskell
bsd-3-clause
6,267
module Test14 where f = let x = 45 in (x, 45)
kmate/HaRe
old/testing/refacRedunDec/Test14AST.hs
Haskell
bsd-3-clause
47
{-# OPTIONS -fglasgow-exts #-} -- This code defines a default method with a highly dubious type, -- because 'v' is not mentioned, and there are no fundeps -- -- However, arguably the instance declaration should be accepted, -- beause it's equivalent to -- instance Baz Int Int where { foo x = x } -- which *does* typecheck -- GHC does not actually macro-expand the instance decl. Instead, it -- defines a default method function, thus -- -- $dmfoo :: Baz v x => x -> x -- $dmfoo y = y -- -- Notice that this is an ambiguous type: you can't call $dmfoo -- without triggering an error. And when you write an instance decl, -- it calls the default method: -- -- instance Baz Int Int where foo = $dmfoo -- -- I'd never thought of that. You might think that we should just -- *infer* the type of the default method (here forall a. a->a), but -- in the presence of higher rank types etc we can't necessarily do -- that. module Foo1 where class Baz v x where foo :: x -> x foo y = y instance Baz Int Int
hvr/jhc
regress/tests/1_typecheck/2_pass/ghc/uncat/tc199.hs
Haskell
mit
1,013
module Foo where {-@ type Range Lo Hi = {v:Int | Lo <= v && v < Hi} @-} {-@ bow :: Range 0 100 @-} bow :: Int bow = 12
mightymoose/liquidhaskell
tests/pos/tyExpr.hs
Haskell
bsd-3-clause
121
module OverD where -- Tests that we verify consistency of type families between -- transitive imports. import OverB import OverC
ezyang/ghc
testsuite/tests/indexed-types/should_fail/OverD.hs
Haskell
bsd-3-clause
129
{-# LANGUAGE TemplateHaskell, FlexibleInstances, ScopedTypeVariables, GADTs, RankNTypes, FlexibleContexts, TypeSynonymInstances, MultiParamTypeClasses, DeriveDataTypeable, PatternGuards, OverlappingInstances, UndecidableInstances, CPP #-} module T1735_Help.Xml (Element(..), Xml, fromXml) where import T1735_Help.Basics import T1735_Help.Instances () import T1735_Help.State data Element = Elem String [Element] | CData String | Attr String String fromXml :: Xml a => [Element] -> Maybe a fromXml xs = case readXml xs of Just (_, v) -> return v Nothing -> error "XXX" class (Data XmlD a) => Xml a where toXml :: a -> [Element] toXml = defaultToXml readXml :: [Element] -> Maybe ([Element], a) readXml = defaultReadXml readXml' :: [Element] -> Maybe ([Element], a) readXml' = defaultReadXml' instance (Data XmlD t, Show t) => Xml t data XmlD a = XmlD { toXmlD :: a -> [Element], readMXmlD :: ReadM Maybe a } xmlProxy :: Proxy XmlD xmlProxy = error "xmlProxy" instance Xml t => Sat (XmlD t) where dict = XmlD { toXmlD = toXml, readMXmlD = readMXml } defaultToXml :: Xml t => t -> [Element] defaultToXml x = [Elem (constring $ toConstr xmlProxy x) (transparentToXml x)] transparentToXml :: Xml t => t -> [Element] transparentToXml x = concat $ gmapQ xmlProxy (toXmlD dict) x -- Don't do any defaulting here, as these functions can be implemented -- differently by the user. We do the defaulting elsewhere instead. -- The t' type is thus not used. defaultReadXml :: Xml t => [Element] -> Maybe ([Element], t) defaultReadXml es = readXml' es defaultReadXml' :: Xml t => [Element] -> Maybe ([Element], t) defaultReadXml' = readXmlWith readVersionedElement readXmlWith :: Xml t => (Element -> Maybe t) -> [Element] -> Maybe ([Element], t) readXmlWith f es = case es of e : es' -> case f e of Just v -> Just (es', v) Nothing -> Nothing [] -> Nothing readVersionedElement :: forall t . Xml t => Element -> Maybe t readVersionedElement e = readElement e readElement :: forall t . Xml t => Element -> Maybe t readElement (Elem n es) = res where resType :: t resType = typeNotValue resType resDataType = dataTypeOf xmlProxy resType con = readConstr resDataType n res = case con of Just c -> f c Nothing -> Nothing f c = let m :: Maybe ([Element], t) m = constrFromElements c es in case m of Just ([], x) -> Just x _ -> Nothing readElement _ = Nothing constrFromElements :: forall t . Xml t => Constr -> [Element] -> Maybe ([Element], t) constrFromElements c es = do let st = ReadState { xmls = es } m :: ReadM Maybe t m = fromConstrM xmlProxy (readMXmlD dict) c -- XXX Should we flip the result order? (x, st') <- runStateT m st return (xmls st', x) type ReadM m = StateT ReadState m data ReadState = ReadState { xmls :: [Element] } getXmls :: Monad m => ReadM m [Element] getXmls = do st <- get return $ xmls st putXmls :: Monad m => [Element] -> ReadM m () putXmls xs = do st <- get put $ st { xmls = xs } readMXml :: Xml a => ReadM Maybe a readMXml = do xs <- getXmls case readXml xs of Nothing -> fail "Cannot read value" Just (xs', v) -> do putXmls xs' return v typeNotValue :: Xml a => a -> a typeNotValue t = error ("Type used as value: " ++ typeName) where typeName = dataTypeName (dataTypeOf xmlProxy t) -- The Xml [a] context is a bit scary, but if we don't have it then -- GHC complains about overlapping instances instance (Xml a {-, Xml [a] -}) => Xml [a] where toXml = concatMap toXml readXml = f [] [] where f acc_xs acc_vs [] = Just (reverse acc_xs, reverse acc_vs) f acc_xs acc_vs (x:xs) = case readXml [x] of Just ([], v) -> f acc_xs (v:acc_vs) xs _ -> f (x:acc_xs) acc_vs xs instance Xml String where toXml x = [CData x] readXml = readXmlWith f where f (CData x) = Just x f _ = Nothing
ezyang/ghc
testsuite/tests/typecheck/should_run/T1735_Help/Xml.hs
Haskell
bsd-3-clause
4,655
{-# LANGUAGE TemplateHaskell #-} module AFM where class Functor f where fmap :: (a -> b) -> f a -> f b fmap id x == x fmap f . fmap g == fmap (f . g) class Functor f => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b -- LiftA fmap f x == liftA f x liftA id x == x liftA3 (.) f g x == f <*> (g <*> x) liftA f (pure x) == pure (f x) data State s a = State (s -> (a, s)) runState :: State s a -> s -> (a, s) runState (State f) = f data Writer msg b = Writer (b, msg) runWriter :: Write msg b -> (b, msg) runWriter (Writer a) = a class Monad m where (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b return :: a -> ma fail :: String -> m a -- return a >>= k = k a -- m >>= return -- m >>= (\x -> k x >>= h) = (m >>= k) >>= h
mortum5/programming
haskell/usefull/AMP.hs
Haskell
mit
800
module Main () where import Data.List (elemIndex) type Header = String type Row a = [a] data Table a = Table { headers :: [Header] , rows :: [Row a] } create :: Table a -> Row a -> Table a create (Table headers rows) newRow = Table headers $ [newRow] ++ rows type Predicate a = (Row a -> Bool) readRow :: Table a -> Predicate a -> [Row a] readRow (Table _ rows) predicate = filter predicate rows readColumn :: Header -> Table a -> Predicate a -> [a] readColumn headerName table@(Table headers rows) predicate = maybeGetColumn $ readRow table predicate maybeGetColumn headerName headers = fmap (flip (!!)) $ elemIndex headerName headers
bmuk/PipeDBHs
Main.hs
Haskell
mit
687
{-# LANGUAGE OverloadedStrings #-} -------------------------------------------------------------------------------- -- | -- Module : Network.MQTT.Broker.RetainedMessages -- Copyright : (c) Lars Petersen 2016 -- License : MIT -- -- Maintainer : info@lars-petersen.net -- Stability : experimental -------------------------------------------------------------------------------- module Network.MQTT.Broker.RetainedMessages where import Control.Applicative hiding (empty) import Control.Concurrent.MVar import qualified Data.ByteString.Lazy as BSL import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.Map.Strict as M import Data.Maybe import qualified Data.Set as S import Prelude hiding (null) import qualified Network.MQTT.Message as Message import qualified Network.MQTT.Message.Topic as Topic newtype RetainedStore = RetainedStore { unstore :: MVar RetainedTree } newtype RetainedTree = RetainedTree { untree :: M.Map Topic.Level RetainedNode } data RetainedNode = RetainedNode !RetainedTree !(Maybe Message.Message) new :: IO RetainedStore new = RetainedStore <$> newMVar empty store :: Message.Message -> RetainedStore -> IO () store msg (RetainedStore mvar) | retain = modifyMVar_ mvar $ \tree-> -- The seq ($!) is important for not leaking memory! pure $! if BSL.null body then delete msg tree else insert msg tree | otherwise = pure () where Message.Payload body = Message.msgPayload msg Message.Retain retain = Message.msgRetain msg retrieve :: Topic.Filter -> RetainedStore -> IO (S.Set Message.Message) retrieve filtr (RetainedStore mvar) = lookupFilter filtr <$> readMVar mvar empty :: RetainedTree empty = RetainedTree mempty null :: RetainedTree -> Bool null = M.null . untree insert :: Message.Message -> RetainedTree -> RetainedTree insert msg = union (singleton msg) delete :: Message.Message -> RetainedTree -> RetainedTree delete msg = flip difference (singleton msg) singleton :: Message.Message -> RetainedTree singleton msg = let l :| ls = Topic.topicLevels (Message.msgTopic msg) in RetainedTree (M.singleton l $ node ls) where node [] = RetainedNode empty $! Just $! msg node (x:xs) = RetainedNode (RetainedTree $ M.singleton x $ node xs) Nothing -- | The expression `union t1 t2` takes the left-biased union of `t1` and `t2`. union :: RetainedTree -> RetainedTree -> RetainedTree union (RetainedTree m1) (RetainedTree m2) = RetainedTree $ M.unionWith merge m1 m2 where merge (RetainedNode t1 mm1) (RetainedNode t2 mm2) = RetainedNode (t1 `union` t2) $! case mm1 <|> mm2 of Nothing -> Nothing Just mm -> Just $! mm difference :: RetainedTree -> RetainedTree -> RetainedTree difference (RetainedTree m1) (RetainedTree m2) = RetainedTree $ M.differenceWith diff m1 m2 where diff (RetainedNode t1 mm1) (RetainedNode t2 mm2) | null t3 && isNothing mm3 = Nothing | otherwise = Just (RetainedNode t3 mm3) where t3 = difference t1 t2 mm3 = case mm2 of Just _ -> Nothing Nothing -> mm1 lookupFilter :: Topic.Filter -> RetainedTree -> S.Set Message.Message lookupFilter filtr t = let l :| ls = Topic.filterLevels filtr in collect l ls t where collect l ls tree@(RetainedTree m) = case l of "#" -> allTree tree "+" -> M.foldl (\s node-> s `S.union` pathNode ls node) S.empty m _ -> fromMaybe S.empty $ pathNode ls <$> M.lookup l m allTree (RetainedTree branches) = M.foldl (\s node-> s `S.union` allNode node) S.empty branches allNode (RetainedNode subtree mmsg) = case mmsg of Nothing -> allTree subtree Just msg -> S.insert msg (allTree subtree) pathNode [] (RetainedNode _ mmsg) = fromMaybe S.empty $ S.singleton <$> mmsg pathNode (x:xs) (RetainedNode subtree mmsg) = case x of "#"-> fromMaybe id (S.insert <$> mmsg) (collect x xs subtree) _ -> collect x xs subtree
lpeterse/haskell-mqtt
src/Network/MQTT/Broker/RetainedMessages.hs
Haskell
mit
4,172
module Main where import Parser import Control.Monad.Trans import System.Console.Haskeline process line = do let res = parseTopLevel line case res of Left err -> print err Right ex -> mapM_ print ex main = runInputT defaultSettings loop where loop = do minput <- getInputLine "ready> " case minput of Nothing -> outputStrLn "Goodbye." Just input -> (liftIO $ process input) >> loop
waterlink/hgo
ParserRepl.hs
Haskell
mit
432
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Control.Monad.Zipkin ( Identifier, parseIdentifier , TraceInfo(..), fromHeaders, toHeaders, newTraceInfo , TraceT, getTraceInfo, forkTraceInfo, runTraceT ) where import Control.Monad.State.Strict import System.Random.Mersenne.Pure64 import Data.Zipkin.Types import qualified Data.Zipkin.Context as Ctx newtype TraceT m a = TraceT { run :: StateT Ctx.TraceContext m a } deriving (Functor, Applicative, Monad, MonadTrans) newTraceInfo :: IO TraceInfo newTraceInfo = evalState Ctx.newTraceInfo <$> newPureMT getTraceInfo :: Monad m => TraceT m TraceInfo getTraceInfo = TraceT Ctx.getTraceInfo forkTraceInfo :: Monad m => TraceT m TraceInfo forkTraceInfo = TraceT Ctx.forkTraceInfo runTraceT :: Monad m => TraceT m a -> TraceInfo -> m a runTraceT m = evalStateT (run m) . Ctx.mkContext
srijs/haskell-zipkin
src/Control/Monad/Zipkin.hs
Haskell
mit
851
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RebindableSyntax #-} {-# LANGUAGE RankNTypes #-} module Web.Stripe.Test.Subscription where import Data.Either import Data.Maybe import Test.Hspec import Web.Stripe.Test.Prelude import Web.Stripe.Test.Util import Web.Stripe.Subscription import Web.Stripe.Customer import Web.Stripe.Plan import Web.Stripe.Coupon subscriptionTests :: StripeSpec subscriptionTests stripe = do describe "Subscription tests" $ do it "Succesfully creates a Subscription" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") sub <- createSubscription cid planid void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight it "Succesfully retrieves a Subscription" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") Subscription { subscriptionId = sid } <- createSubscription cid planid sub <- getSubscription cid sid void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight it "Succesfully retrieves a Subscription expanded" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") Subscription { subscriptionId = sid } <- createSubscription cid planid sub <- getSubscription cid sid -&- ExpandParams ["customer"] void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight it "Succesfully retrieves a Customer's Subscriptions expanded" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") void $ createSubscription cid planid sub <- getSubscriptionsByCustomerId cid -&- ExpandParams ["data.customer"] void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight it "Succesfully retrieves a Customer's Subscriptions" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") void $ createSubscription cid planid sub <- getSubscriptionsByCustomerId cid void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight it "Succesfully retrieves all Subscriptions expanded" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") void $ createSubscription cid planid sub <- getSubscriptions -&- ExpandParams ["data.customer"] void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight it "Succesfully retrieves all Subscriptions" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") void $ createSubscription cid planid sub <- getSubscriptions void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight it "Succesfully updates a Customer's Subscriptions" $ do planid <- makePlanId secondPlanid <- makePlanId couponid <- makeCouponId result <- stripe $ do Coupon { } <- createCoupon (Just couponid) Once -&- (AmountOff 1) -&- USD Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") Subscription { subscriptionId = sid } <- createSubscription cid planid sub <- updateSubscription cid sid -&- couponid -&- MetaData [("hi","there")] void $ deleteCustomer cid return sub result `shouldSatisfy` isRight let Right Subscription {..} = result subscriptionMetaData `shouldBe` (MetaData [("hi", "there")]) subscriptionDiscount `shouldSatisfy` isJust it "Succesfully cancels a Customer's Subscription" $ do planid <- makePlanId result <- stripe $ do Customer { customerId = cid } <- createCustomer void $ createPlan planid (Amount 0) -- free plan USD Month (PlanName "sample plan") Subscription { subscriptionId = sid } <- createSubscription cid planid sub <- cancelSubscription cid sid -&- AtPeriodEnd False void $ deletePlan planid void $ deleteCustomer cid return sub result `shouldSatisfy` isRight let Right Subscription {..} = result subscriptionStatus `shouldBe` Canceled
dmjio/stripe
stripe-tests/tests/Web/Stripe/Test/Subscription.hs
Haskell
mit
6,399
{-# LANGUAGE OverloadedStrings #-} -- we infect all the other modules with instances from -- this module, so they don't appear orphaned. {-# OPTIONS_GHC -fno-warn-orphans #-} module Network.Datadog.Internal ( prependMaybe , prependBool , datadogHttp , decodeDatadog , baseRequest , defaultMonitorOptions , DatadogCredentials(..) , module Network.Datadog.Lens , module Network.Datadog.Types ) where import Control.Arrow (first) import Control.Exception import Control.Lens hiding ((.=), cons) import Data.Aeson hiding (Series, Success, Error) import Data.Aeson.Types (modifyFailure, typeMismatch) import qualified Data.ByteString.Lazy as LBS (ByteString, empty) import qualified Data.DList as D import qualified Data.HashMap.Strict as HM import Data.Maybe import Data.Text (Text, pack, append, splitAt, findIndex, cons) import Data.Text.Lazy (unpack) import Data.Text.Encoding (encodeUtf8) import Data.Text.Lazy.Encoding (decodeUtf8) import Data.Time.Clock import Data.Time.Clock.POSIX import Data.Vector ((!?)) import Network.HTTP.Client hiding (host) import Network.HTTP.Types import Network.Datadog.Types import Network.Datadog.Lens import Prelude hiding (splitAt) prependMaybe :: (a -> b) -> Maybe a -> [b] -> [b] prependMaybe f = maybe id ((:) . f) prependBool :: Bool -> b -> [b] -> [b] prependBool p a = if p then (a :) else id datadogHttp :: Environment-> String -> [(String, String)] -> StdMethod -> Maybe LBS.ByteString -> IO LBS.ByteString datadogHttp (Environment keys baseUrl manager) endpoint q httpMethod content = do initReq <- parseUrlThrow $ baseUrl ++ endpoint let body = RequestBodyLBS $ fromMaybe LBS.empty content headers = [("Content-type", "application/json") | isJust content] apiQuery = [("api_key", apiKey keys) ,("application_key", appKey keys)] fullQuery = map (\(a,b) -> (encodeUtf8 (pack a), Just (encodeUtf8 (pack b)))) $ apiQuery ++ q request = setQueryString fullQuery $ initReq { method = renderStdMethod httpMethod , requestBody = body , requestHeaders = headers } responseBody <$> httpLbs request manager decodeDatadog :: FromJSON a => String -> LBS.ByteString -> IO a decodeDatadog funcname body = either (throwIO . AssertionFailed . failstring) return $ eitherDecode body where failstring e = "Datadog Library decoding failure in \"" ++ funcname ++ "\": " ++ e ++ ": " ++ unpack (decodeUtf8 body) baseRequest :: Request baseRequest = fromJust $ parseUrlThrow "https://api.datadoghq.com" class DatadogCredentials s where signRequest :: s -> Request -> Request instance DatadogCredentials Write where signRequest (Write k) = setQueryString [("api_key", Just k)] instance DatadogCredentials ReadWrite where signRequest (ReadWrite w r) = setQueryString [("api_key", Just w), ("application_key", Just r)] instance ToJSON DowntimeSpec where toJSON ds = object $ prependMaybe (\a -> "start" .= (ceiling (utcTimeToPOSIXSeconds a) :: Integer)) (ds ^. start) $ prependMaybe (\a -> "end" .= (floor (utcTimeToPOSIXSeconds a) :: Integer)) (ds ^. end) ["scope" .= (ds ^. scope)] instance FromJSON DowntimeSpec where parseJSON (Object v) = modifyFailure ("DowntimeSpec: " ++) $ DowntimeSpec <$> (maybe (return Nothing) (withScientific "Integer" (\t -> return (Just (posixSecondsToUTCTime (fromIntegral (floor t :: Integer)))))) =<< (v .:? "start")) <*> (maybe (return Nothing) (withScientific "Integer" (\t -> return (Just (posixSecondsToUTCTime (fromIntegral (floor t :: Integer)))))) =<< (v .:? "end")) <*> v .:? "message" .!= Nothing <*> (withArray "Text" (\t -> maybe (fail "\"scope\" Array is too short") parseJSON (t !? 0)) =<< v .: "scope") parseJSON a = modifyFailure ("DowntimeSpec: " ++) $ typeMismatch "Object" a instance ToJSON Tag where toJSON (KeyValueTag k v) = Data.Aeson.String $ k `append` (':' `cons` v) toJSON (LabelTag t) = Data.Aeson.String t instance FromJSON Tag where parseJSON (String s) = return $ maybe (LabelTag s) (\i -> uncurry KeyValueTag (splitAt i s)) $ findIndex (==':') s parseJSON a = modifyFailure ("Tag: " ++) $ typeMismatch "String" a instance ToJSON CheckStatus where toJSON CheckOk = Number 0 toJSON CheckWarning = Number 1 toJSON CheckCritical = Number 2 toJSON CheckUnknown = Number 3 instance FromJSON CheckStatus where parseJSON (Number 0) = return CheckOk parseJSON (Number 1) = return CheckWarning parseJSON (Number 2) = return CheckCritical parseJSON (Number 3) = return CheckUnknown parseJSON (Number n) = fail $ "CheckStatus: Number \"" ++ show n ++ "\" is not a valid CheckStatus" parseJSON a = modifyFailure ("MonitorType: " ++) $ typeMismatch "Number" a instance ToJSON CheckResult where toJSON cr = object $ prependMaybe (\a -> "timestamp" .= (floor (utcTimeToPOSIXSeconds a) :: Integer)) (cr ^. timestamp) $ prependMaybe (\a -> "message" .= a) (cr ^. message) ["check" .= (cr ^. check) ,"host_name" .= (cr ^. hostName) ,"status" .= (cr ^. status) ,"tags" .= (cr ^. tags) ] instance FromJSON CheckResult where parseJSON (Object v) = modifyFailure ("CheckResult: " ++) $ CheckResult <$> v .: "check" <*> v .: "host_name" <*> v .: "status" <*> v .:? "timestamp" .!= Nothing <*> v .:? "message" .!= Nothing <*> v .: "tags" .!= [] parseJSON a = modifyFailure ("CheckResult: " ++) $ typeMismatch "Object" a instance ToJSON Downtime where toJSON downtime = Object $ HM.insert "id" (toJSON $ downtime ^. id') basemap where (Object basemap) = toJSON (downtime ^. spec) instance FromJSON Downtime where parseJSON (Object v) = modifyFailure ("Downtime: " ++) $ Downtime <$> v .: "id" <*> parseJSON (Object v) parseJSON a = modifyFailure ("Downtime: " ++) $ typeMismatch "Object" a instance ToJSON EventPriority where toJSON NormalPriority = Data.Aeson.String "normal" toJSON LowPriority = Data.Aeson.String "low" instance FromJSON EventPriority where parseJSON (Data.Aeson.String "normal") = return NormalPriority parseJSON (Data.Aeson.String "low") = return LowPriority parseJSON (Data.Aeson.String s) = fail $ "EventPriority: String " ++ show s ++ " is not a valid EventPriority" parseJSON a = modifyFailure ("EventPriority: " ++) $ typeMismatch "String" a instance ToJSON AlertType where toJSON Error = Data.Aeson.String "error" toJSON Warning = Data.Aeson.String "warning" toJSON Info = Data.Aeson.String "info" toJSON Success = Data.Aeson.String "success" instance FromJSON AlertType where parseJSON (Data.Aeson.String "error") = return Error parseJSON (Data.Aeson.String "warning") = return Warning parseJSON (Data.Aeson.String "info") = return Info parseJSON (Data.Aeson.String "success") = return Success parseJSON (Data.Aeson.String s) = fail $ "AlertType: String " ++ show s ++ " is not a valid AlertType" parseJSON a = modifyFailure ("AlertType: " ++) $ typeMismatch "String" a instance ToJSON SourceType where toJSON Nagios = Data.Aeson.String "nagios" toJSON Hudson = Data.Aeson.String "hudson" toJSON Jenkins = Data.Aeson.String "jenkins" toJSON User = Data.Aeson.String "user" toJSON MyApps = Data.Aeson.String "my apps" toJSON Feed = Data.Aeson.String "feed" toJSON Chef = Data.Aeson.String "chef" toJSON Puppet = Data.Aeson.String "puppet" toJSON Git = Data.Aeson.String "git" toJSON BitBucket = Data.Aeson.String "bitbucket" toJSON Fabric = Data.Aeson.String "fabric" toJSON Capistrano = Data.Aeson.String "capistrano" instance FromJSON SourceType where parseJSON (Data.Aeson.String "nagios") = return Nagios parseJSON (Data.Aeson.String "hudson") = return Hudson parseJSON (Data.Aeson.String "jenkins") = return Jenkins parseJSON (Data.Aeson.String "user") = return User parseJSON (Data.Aeson.String "my apps") = return MyApps parseJSON (Data.Aeson.String "feed") = return Feed parseJSON (Data.Aeson.String "chef") = return Chef parseJSON (Data.Aeson.String "puppet") = return Puppet parseJSON (Data.Aeson.String "git") = return Git parseJSON (Data.Aeson.String "bitbucket") = return BitBucket parseJSON (Data.Aeson.String "fabric") = return Fabric parseJSON (Data.Aeson.String "capistrano") = return Capistrano parseJSON (Data.Aeson.String s) = fail $ "SourceType: String " ++ show s ++ " is not a valid SourceType" parseJSON a = modifyFailure ("SourceType: " ++) $ typeMismatch "String" a instance ToJSON EventSpec where toJSON ed = object $ prependMaybe (\a -> "host" .= a) (ed ^. host) $ prependMaybe (\a -> "source_type_name" .= pack (show a)) (ed ^. sourceType) ["title" .= (ed ^. title) ,"text" .= (ed ^. text) ,"date_happened" .= (floor (utcTimeToPOSIXSeconds (ed ^. dateHappened)) :: Integer) ,"priority" .= pack (show (ed ^. priority)) ,"alert_type" .= pack (show (ed ^. alertType)) ,"tags" .= (ed ^. tags) ] instance FromJSON EventSpec where parseJSON (Object v) = modifyFailure ("EventSpec: " ++) $ EventSpec <$> v .: "title" <*> v .: "text" <*> (withScientific "Integer" (\t -> return (posixSecondsToUTCTime (fromIntegral (floor t :: Integer)))) =<< v .: "date_happened") <*> v .: "priority" <*> v .:? "host" .!= Nothing <*> v .:? "tags" .!= [] <*> v .:? "alert_type" .!= Info <*> v .:? "source_type" .!= Nothing parseJSON a = modifyFailure ("EventSpec: " ++) $ typeMismatch "Object" a instance ToJSON Event where toJSON event = Object $ HM.insert "id" (toJSON (event ^. id')) basemap where (Object basemap) = toJSON (event ^. details) instance FromJSON Event where parseJSON (Object v) = modifyFailure ("Event: " ++) $ Event <$> v .: "id" <*> parseJSON (Object v) parseJSON a = modifyFailure ("Event: " ++) $ typeMismatch "Object" a instance FromJSON WrappedEvent where parseJSON (Object v) = modifyFailure ("WrappedEvent: " ++) $ WrappedEvent <$> v .: "event" parseJSON a = modifyFailure ("WrappedEvent: " ++) $ typeMismatch "Object" a instance FromJSON WrappedEvents where parseJSON (Object v) = modifyFailure ("WrappedEvents: " ++) $ WrappedEvents <$> v .: "events" parseJSON a = modifyFailure ("WrappedEvents: " ++) $ typeMismatch "Object" a instance ToJSON Series where toJSON s = object [ "series" .= D.toList (fromSeries s) ] instance ToJSON Timestamp where toJSON = toJSON . (round :: NominalDiffTime -> Int) . fromTimestamp instance ToJSON MetricPoints where toJSON (Gauge ps) = toJSON $ fmap (first Timestamp) ps toJSON (Counter ps) = toJSON $ fmap (first Timestamp) ps instance ToJSON Metric where toJSON m = object ks where f = maybe id (\x y -> ("host" .= x) : y) $ metricHost m ks = f [ "metric" .= metricName m , "points" .= metricPoints m , "tags" .= metricTags m , "type" .= case metricPoints m of Gauge _ -> "gauge" :: Text Counter _ -> "counter" :: Text ] instance ToJSON MonitorType where toJSON MetricAlert = Data.Aeson.String "metric alert" toJSON ServiceCheck = Data.Aeson.String "service check" toJSON EventAlert = Data.Aeson.String "event alert" instance FromJSON MonitorType where parseJSON (Data.Aeson.String "metric alert") = return MetricAlert -- TODO figure out what "query alert" actually is parseJSON (Data.Aeson.String "query alert") = return MetricAlert parseJSON (Data.Aeson.String "service check") = return ServiceCheck parseJSON (Data.Aeson.String "event alert") = return EventAlert parseJSON (Data.Aeson.String s) = fail $ "MonitorType: String " ++ show s ++ " is not a valid MonitorType" parseJSON a = modifyFailure ("MonitorType: " ++) $ typeMismatch "String" a instance ToJSON MonitorOptions where toJSON opts = Object $ HM.fromList [ ("silenced", toJSON (opts ^. silenced)) , ("notify_no_data", Bool (opts ^. notifyNoData)) , ("no_data_timeframe", maybe Null (Number . fromIntegral) (opts ^. noDataTimeframe)) , ("timeout_h", maybe Null (Number . fromIntegral) (opts ^. timeoutH)) , ("renotify_interval", maybe Null (Number . fromIntegral) (opts ^. renotifyInterval)) , ("escalation_message", Data.Aeson.String (opts ^. escalationMessage)) , ("notify_audit", Bool (opts ^. notifyAudit)) ] instance FromJSON MonitorOptions where parseJSON (Object v) = modifyFailure ("MonitorOptions: " ++) $ MonitorOptions <$> v .:? "silenced" .!= HM.empty <*> v .:? "notify_no_data" .!= False <*> v .:? "no_data_timeframe" .!= Nothing <*> v .:? "timeout_h" .!= Nothing <*> v .:? "renotify_interval" .!= Nothing <*> v .:? "escalation_message" .!= "" <*> v .:? "notify_audit" .!= False parseJSON a = modifyFailure ("MonitorOptions: " ++) $ typeMismatch "Object" a instance ToJSON MonitorSpec where toJSON ms = Object $ HM.insert "options" (toJSON (ms ^. options)) hmap where (Object hmap) = object $ prependMaybe ("name" .=) (ms ^. name) $ prependMaybe ("message" .=) (ms ^. message) [ "type" .= pack (show (ms ^. type')) , "query" .= (ms ^. query) ] -- | Creates the most basic specification required by a monitor, containing the -- type of monitor and the query string used to detect the monitor's state. -- -- Generates a set of "default" Monitor options, which specify as little -- optional configuration as possible. This includes: -- -- * No silencing of any part of the monitor -- * No notification when data related to the monitor is missing -- * No alert timeout after the monitor is triggeredn -- * No renotification when the monitor is triggered -- * No notification when the monitor is modified -- -- In production situations, it is /not safe/ to rely on this documented -- default behaviour for critical setitngs; use the helper functions to -- introspect the MonitorOptions instance provided by this function. This also -- protects against future modifications to this API. defaultMonitorOptions :: MonitorOptions defaultMonitorOptions = MonitorOptions { monitorOptionsSilenced = HM.empty , monitorOptionsNotifyNoData = False , monitorOptionsNoDataTimeframe = Nothing , monitorOptionsTimeoutH = Nothing , monitorOptionsRenotifyInterval = Nothing , monitorOptionsEscalationMessage = "" , monitorOptionsNotifyAudit = False } instance FromJSON MonitorSpec where parseJSON (Object v) = modifyFailure ("MonitorSpec: " ++) $ MonitorSpec <$> v .: "type" <*> v .: "query" <*> v .:? "name" .!= Nothing <*> v .:? "message" .!= Nothing <*> v .:? "options" .!= defaultMonitorOptions parseJSON a = modifyFailure ("MonitorSpec: " ++) $ typeMismatch "Object" a instance ToJSON Monitor where toJSON monitor = Object $ HM.insert "id" (toJSON (monitor ^. id')) basemap where (Object basemap) = toJSON (monitor ^. spec) instance FromJSON Monitor where parseJSON (Object v) = modifyFailure ("Monitor: " ++ ) $ Monitor <$> v .: "id" <*> parseJSON (Object v) parseJSON a = modifyFailure ("Monitor: " ++) $ typeMismatch "Object" a
iand675/datadog
src/Network/Datadog/Internal.hs
Haskell
mit
16,829
-- | Module for providing various functionals used in calculations involving -- quantum mathematics. This includes the fidelity and trace norm. module Hoqus.Fidelity where import Numeric.LinearAlgebra.Data import Numeric.LinearAlgebra import Hoqus.MtxFun -- | Function 'fidelity' calculates the fidelity between two quantum states (or -- any two square matrices) --fidelity :: Matrix C -> Matrix C -> C --fidelity a b = (sum $ map sqrt $ toList $ eigenvalues $ a <> b ) ** 2 -- | Function 'superFidelity' calculates an upper bound for the fidelity using -- only trace of the products of input matrices. superFidelity :: Matrix C -> Matrix C -> C superFidelity a b = (trace (a <> b)) + (sqrt (1 - trace (a <> a))) * (sqrt (1 - trace (b <> b))) -- | Function 'subFidelity' calculates a lower bound for the fidelity using only -- race of the products of input matrices. subFidelity :: Matrix C -> Matrix C -> C subFidelity a b = (trace p) + (sqrt 2) * (sqrt ((trace p)*(trace p) - trace (p <> p))) where p = a <> b
jmiszczak/hoqus
Hoqus/Fidelity.hs
Haskell
mit
1,022
module Pretty where -- see: http://stackoverflow.com/questions/5929377/format-list-output-in-haskell import Data.List ( transpose, intercalate ) -- a type for fill functions type Filler = Int -> String -> String -- a type for describing table columns data ColDesc t = ColDesc { colTitleFill :: Filler , colTitle :: String , colValueFill :: Filler , colValue :: t -> String } -- functions that fill a string (s) to a given width (n) by adding pad -- character (c) to align left, right, or center fillLeft, fillRight, fillCenter :: a -> Int -> [a] -> [a] fillLeft c n s = s ++ replicate (n - length s) c fillRight c n s = replicate (n - length s) c ++ s fillCenter c n s = replicate l c ++ s ++ replicate r c where x = n - length s l = x `div` 2 r = x - l -- functions that fill with spaces left, right, center :: Int -> String -> String left = fillLeft ' ' right = fillRight ' ' center = fillCenter ' ' -- converts a list of items into a table according to a list -- of column descriptors ppTable :: [ColDesc t] -> [t] -> String ppTable cs ts = let header = map colTitle cs rows = [[colValue c t | c <- cs] | t <- ts] widths = [maximum $ map length col | col <- transpose $ header : rows] separator = intercalate "-+-" [replicate width '-' | width <- widths] fillCols fill cols = intercalate " | " [fill c width col | (c, width, col) <- zip3 cs widths cols] in unlines $ fillCols colTitleFill header : separator : map (fillCols colValueFill) rows renderTable :: [ColDesc t] -> [t] -> IO () renderTable cs = putStrLn . ppTable cs
nyorem/skemmtun
src/Pretty.hs
Haskell
mit
1,773
module TestSafePrelude where import Test.HUnit import SafePrelude testSafeHeadForEmptyList :: Test testSafeHeadForEmptyList = TestCase $ assertEqual "Should return Nothing for empty list" Nothing (safeHead ([]::[Int])) testSafeHeadForNonEmptyList :: Test testSafeHeadForNonEmptyList = TestCase $ assertEqual "Should return (Just head) for non empty list" (Just 1) (safeHead ([1]::[Int])) main :: IO Counts main = runTestTT $ TestList [testSafeHeadForEmptyList, testSafeHeadForNonEmptyList]
Muzietto/transformerz
haskell/hunit/TestSafePrelude.hs
Haskell
mit
572
-- ref: https://en.wikibooks.org/wiki/Haskell/Arrow_tutorial {-# LANGUAGE Arrows #-} module Main where import Control.Arrow import Control.Monad import qualified Control.Category as Cat import Data.List import Data.Maybe import System.Random -- Arrows which can save state newtype Circuit a b = Circuit { unCircuit :: a -> (Circuit a b, b) } instance Cat.Category Circuit where id = Circuit $ \a -> (Cat.id, a) (.) = dot where (Circuit cir2) `dot` (Circuit cir1) = Circuit $ \a -> let (cir1', b) = cir1 a (cir2', c) = cir2 b in (cir2' `dot` cir1', c) instance Arrow Circuit where arr f = Circuit $ \a -> (arr f, f a) first (Circuit cir) = Circuit $ \(b, d) -> let (cir', c) = cir b in (first cir', (c, d)) runCircuit :: Circuit a b -> [a] -> [b] runCircuit _ [] = [] runCircuit cir (x:xs) = let (cir',x') = unCircuit cir x in x' : runCircuit cir' xs -- or runCircuit cir = snd . mapAccumL unCircuit cir -- | Accumulator that outputs a value determined by the supplied function. accum :: acc -> (a -> acc -> (b, acc)) -> Circuit a b accum acc f = Circuit $ \input -> let (output, acc') = input `f` acc in (accum acc' f, output) -- | Accumulator that outputs the accumulator value. accum' :: b -> (a -> b -> b) -> Circuit a b accum' acc f = accum acc (\a b -> let b' = a `f` b in (b', b')) total :: Num a => Circuit a a total = accum' 0 (+) mean1 :: Fractional a => Circuit a a mean1 = (total &&& (const 1 ^>> total)) >>> arr (uncurry (/)) mean2 :: Fractional a => Circuit a a mean2 = proc value -> do t <- total -< value n <- total -< 1 returnA -< t / n mean3 :: Fractional a => Circuit a a mean3 = proc value -> do (t, n) <- (| (&&&) (total -< value) (total -< 1) |) returnA -< t / n mean4 :: Fractional a => Circuit a a mean4 = proc value -> do (t, n) <- (total -< value) &&& (total -< 1) returnA -< t / n mean5 :: Fractional a => Circuit a a mean5 = proc value -> do rec (lastTot, lastN) <- delay (0,0) -< (tot, n) let (tot, n) = (lastTot + value, lastN + 1) let mean = tot / n returnA -< mean -- proc {- proc is the keyword that introduces arrow notation, and it binds the arrow input to a pattern (value in this example). Arrow statements in a do block take one of these forms: variable binding pattern <- arrow -< pure expression giving arrow input arrow -< pure expression giving arrow input -} instance ArrowLoop Circuit where loop (Circuit cir) = Circuit $ \b -> let (cir', (c,d)) = cir (b,d) in (loop cir', c)
Airtnp/Freshman_Simple_Haskell_Lib
Intro/WIW/Circuit_and_Arrow.hs
Haskell
mit
2,639
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Applicative import Control.Arrow import qualified Data.Attoparsec.Text.Lazy as A import Data.List import Data.Maybe import Data.Monoid import qualified Data.String as S import qualified Data.Text.Lazy as T main :: IO () main = print ("Hi!" :: String) data Term = Var Char | Lam Char Term | App Term Term deriving Show instance S.IsString Term where fromString = parse . T.pack pretty :: Term -> String pretty (Var x) = [x] pretty (Lam x s) = "(\\" ++ [x] ++ ". " ++ pretty s ++ ")" pretty (App s t) = "(" ++ pretty s ++ " " ++ pretty t ++ ")" term :: A.Parser Term term = (parens app <|> parens lam <|> var) where var = Var <$> A.letter lam = Lam <$> (A.char '\\' *> A.letter) <* A.string ". " <*> term app = App <$> term <* A.char ' ' <*> term parens p = id <$> (A.char '(' *> p) <* A.char ')' parse :: T.Text -> Term parse t = case A.parse (term <* A.endOfInput) t of A.Fail _ _ _ -> error "parsing failed" A.Done _ r -> r subst :: (Char, Term) -> Term -> Term subst (x, r) s@(Var y) = if x == y then r else s subst p@(x, _) s@(Lam y t) = if x == y then s else Lam y (subst p t) subst p (App s t) = App (subst p s) (subst p t) leftmostReduction :: Term -> Maybe Term leftmostReduction (Var _) = Nothing leftmostReduction (Lam x s) = fmap (Lam x) $ leftmostReduction s leftmostReduction (App (Lam x s) t) = Just $ subst (x, t) s leftmostReduction (App s t) = case leftmostReduction s of Nothing -> fmap (App s) (leftmostReduction t) Just s' -> Just $ App s' t reduce :: Term -> Term reduce t = if j < 100 then n else error $ "Stopped after 100 reductions: " ++ pretty n where iterations = zip ([1..] :: [Integer]) $ iterate (>>= leftmostReduction) (Just t) (j, Just n) = last $ takeWhile (\(i,m) -> i <= 100 && isJust m) iterations data Signature = SVar String | SFun String [Signature] deriving Eq instance Show Signature where show (SVar c) = c show (SFun n vs) = "(" ++ n ++ " " ++ (intercalate " " $ map show vs) ++ ")" unify :: [(Signature, Signature)] -> Either String (Signature -> Signature) unify = fmap apply . foldrEither (\(s1, s2) sub -> unify' sub s1 s2) (Right emptySub) where unify' :: (String -> Signature) -> Signature -> Signature -> Either String (String -> Signature) unify' sub s1@(SVar v) s2 = if s1' == s1 then extend sub v s2' else unify' sub s1' s2' where s1' = apply sub s1 s2' = apply sub s2 unify' sub s@(SFun _ _) v@(SVar _) = unify' sub v s unify' sub t1@(SFun n1 ss1) t2@(SFun n2 ss2) = if n1 /= n2 then Left $ "Failed to unify " ++ show t1 ++ " with " ++ show t2 else foldrEither (\(s1, s2) s -> unify' s s1 s2) (Right sub) (zip ss1 ss2) foldrEither :: (a -> b -> Either e b) -> Either e b -> [a] -> Either e b foldrEither f = foldr mf where mf _ (Left e) = Left e mf a (Right b) = f a b vars :: Signature -> [String] vars (SVar c) = [c] vars (SFun _ ss) = concatMap vars ss emptySub :: String -> Signature emptySub = SVar extend :: (String -> Signature) -> String -> Signature -> Either String (String -> Signature) extend sub c s = if s == SVar c then Right sub else if c `elem` vars s then Left "cycle" else Right $ (delta c s) `scomp` sub delta c s c' = if c == c' then s else SVar c' scomp sub1 sub2 c = apply sub1 (sub2 c) apply :: (String -> Signature) -> Signature -> Signature apply sub (SVar v) = sub v apply sub (SFun n ss) = SFun n $ map (apply sub) ss data Type = TVar String | TArrow Type Type instance Show Type where show (TVar c) = c show (TArrow t1 t2) = "(" ++ show t1 ++ " -> " ++ show t2 ++ ")" toType :: Signature -> Type toType (SVar s) = TVar s toType (SFun _ (a:b:[])) = TArrow (toType a) (toType b) toType _ = error "unexpected signature" typeEquations :: String -> Term -> [(Signature, Signature)] typeEquations n (Var x) = [(SVar n, SVar $ "T" ++ [x])] typeEquations n (App a b) = typeEquations (n ++ "_l") a ++ typeEquations (n ++ "_r") b ++ [(SVar $ n ++ "_l", SFun "->" [SVar $ n ++ "_r", SVar n])] typeEquations n (Lam x b) = map (replaceBoundVar *** replaceBoundVar) (typeEquations (n ++ "_b") b) ++ [(SVar n, SFun "->" [SVar $ n ++ "_x", SVar $ n ++ "_b"])] where replaceBoundVar = replaceVar ("T" ++ [x]) (n ++ "_x") replaceVar a a' (SVar v) = if v == a then SVar a' else SVar v replaceVar a a' (SFun name ss) = SFun name $ map (replaceVar a a') ss typeOf :: Term -> Either String Type typeOf t = fmap (\u -> toType $ u (SVar "M")) (unify $ typeEquations "M" t) eval :: T.Text -> Either String (Type, Term) eval s = case typeOf t of Left e -> Left e Right ty -> Right (ty, reduce t) where t = parse s -- Testing _I, _K, _S, _Y :: T.Text _I = "(\\a. a)" _K = "(\\a. (\\b. a))" _S = "(\\a. (\\b. (\\c. ((a c) (b c)))))" _Y = "(\\f. ((\\w. (f (w w))) (\\w. (f (w w)))))" (<.>) :: T.Text -> T.Text -> T.Text a <.> b = "(" <> a <> " " <> b <> ")" infixl 6 <.> red :: Int -> Term -> IO () red n t = putStr $ unlines $ fmap show $ (fmap . fmap) pretty $ take n $ iterate (>>= leftmostReduction) (Just t) -- (a, b, c, f) = (SVar "a", SVar "b", SVar "c", \a b -> SFun "f" [a, b])
andregrigon/Lambda
executable/Main.hs
Haskell
mit
5,389
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} module PostgREST.DbStructure ( getDbStructure , accessibleTables ) where import qualified Hasql.Decoders as HD import qualified Hasql.Encoders as HE import qualified Hasql.Query as H import Control.Applicative import Data.List (elemIndex) import Data.Maybe (fromJust) import Data.Text (split, strip, breakOn, dropAround) import qualified Data.Text as T import qualified Hasql.Session as H import PostgREST.Types import Text.InterpolatedString.Perl6 (q) import GHC.Exts (groupWith) import Protolude import Unsafe (unsafeHead) getDbStructure :: Schema -> H.Session DbStructure getDbStructure schema = do tabs <- H.query () allTables cols <- H.query () $ allColumns tabs syns <- H.query () $ allSynonyms cols rels <- H.query () $ allRelations tabs cols keys <- H.query () $ allPrimaryKeys tabs procs <- H.query schema accessibleProcs let rels' = (addManyToManyRelations . raiseRelations schema syns . addParentRelations . addSynonymousRelations syns) rels cols' = addForeignKeys rels' cols keys' = synonymousPrimaryKeys syns keys return DbStructure { dbTables = tabs , dbColumns = cols' , dbRelations = rels' , dbPrimaryKeys = keys' , dbProcs = procs } decodeTables :: HD.Result [Table] decodeTables = HD.rowsList tblRow where tblRow = Table <$> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.bool decodeColumns :: [Table] -> HD.Result [Column] decodeColumns tables = mapMaybe (columnFromRow tables) <$> HD.rowsList colRow where colRow = (,,,,,,,,,,) <$> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.int4 <*> HD.value HD.bool <*> HD.value HD.text <*> HD.value HD.bool <*> HD.nullableValue HD.int4 <*> HD.nullableValue HD.int4 <*> HD.nullableValue HD.text <*> HD.nullableValue HD.text decodeRelations :: [Table] -> [Column] -> HD.Result [Relation] decodeRelations tables cols = mapMaybe (relationFromRow tables cols) <$> HD.rowsList relRow where relRow = (,,,,,) <$> HD.value HD.text <*> HD.value HD.text <*> HD.value (HD.array (HD.arrayDimension replicateM (HD.arrayValue HD.text))) <*> HD.value HD.text <*> HD.value HD.text <*> HD.value (HD.array (HD.arrayDimension replicateM (HD.arrayValue HD.text))) decodePks :: [Table] -> HD.Result [PrimaryKey] decodePks tables = mapMaybe (pkFromRow tables) <$> HD.rowsList pkRow where pkRow = (,,) <$> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.text decodeSynonyms :: [Column] -> HD.Result [(Column,Column)] decodeSynonyms cols = mapMaybe (synonymFromRow cols) <$> HD.rowsList synRow where synRow = (,,,,,) <$> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.text accessibleProcs :: H.Query Schema [(Text, ProcDescription)] accessibleProcs = H.statement sql (HE.value HE.text) (map addName <$> HD.rowsList (ProcDescription <$> HD.value HD.text <*> (parseArgs <$> HD.value HD.text) <*> HD.value HD.text)) True where addName :: ProcDescription -> (Text, ProcDescription) addName pd = (pdName pd, pd) parseArgs :: Text -> [PgArg] parseArgs = mapMaybe (parseArg . strip) . split (==',') parseArg :: Text -> Maybe PgArg parseArg a = let (body, def) = breakOn " DEFAULT " a (name, typ) = breakOn " " body in if T.null typ then Nothing else Just $ PgArg (dropAround (== '"') name) (strip typ) (T.null def) sql = [q| SELECT p.proname as "proc_name", pg_get_function_arguments(p.oid) as "args", pg_get_function_result(p.oid) as "return_type" FROM pg_namespace n JOIN pg_proc p ON pronamespace = n.oid WHERE n.nspname = $1|] accessibleTables :: H.Query Schema [Table] accessibleTables = H.statement sql (HE.value HE.text) decodeTables True where sql = [q| select n.nspname as table_schema, relname as table_name, c.relkind = 'r' or (c.relkind IN ('v', 'f')) and (pg_relation_is_updatable(c.oid::regclass, false) & 8) = 8 or (exists ( select 1 from pg_trigger where pg_trigger.tgrelid = c.oid and (pg_trigger.tgtype::integer & 69) = 69) ) as insertable from pg_class c join pg_namespace n on n.oid = c.relnamespace where c.relkind in ('v', 'r', 'm') and n.nspname = $1 and ( pg_has_role(c.relowner, 'USAGE'::text) or has_table_privilege(c.oid, 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'::text) or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES'::text) ) order by relname |] synonymousColumns :: [(Column,Column)] -> [Column] -> [[Column]] synonymousColumns allSyns cols = synCols' where syns = case headMay cols of Just firstCol -> sort $ filter ((== colTable firstCol) . colTable . fst) allSyns Nothing -> [] synCols  = transpose $ map (\c -> map snd $ filter ((== c) . fst) syns) cols synCols' = (filter sameTable . filter matchLength) synCols matchLength cs = length cols == length cs sameTable (c:cs) = all (\cc -> colTable c == colTable cc) (c:cs) sameTable [] = False addForeignKeys :: [Relation] -> [Column] -> [Column] addForeignKeys rels = map addFk where addFk col = col { colFK = fk col } fk col = join $ relToFk col <$> find (lookupFn col) rels lookupFn :: Column -> Relation -> Bool lookupFn c Relation{relColumns=cs, relType=rty} = c `elem` cs && rty==Child relToFk col Relation{relColumns=cols, relFColumns=colsF} = do pos <- elemIndex col cols colF <- atMay colsF pos return $ ForeignKey colF addSynonymousRelations :: [(Column,Column)] -> [Relation] -> [Relation] addSynonymousRelations _ [] = [] addSynonymousRelations syns (rel:rels) = rel : synRelsP ++ synRelsF ++ addSynonymousRelations syns rels where synRelsP = synRels (relColumns rel) (\t cs -> rel{relTable=t,relColumns=cs}) synRelsF = synRels (relFColumns rel) (\t cs -> rel{relFTable=t,relFColumns=cs}) synRels cols mapFn = map (\cs -> mapFn (colTable $ unsafeHead cs) cs) $ synonymousColumns syns cols addParentRelations :: [Relation] -> [Relation] addParentRelations [] = [] addParentRelations (rel@(Relation t c ft fc _ _ _ _):rels) = Relation ft fc t c Parent Nothing Nothing Nothing : rel : addParentRelations rels addManyToManyRelations :: [Relation] -> [Relation] addManyToManyRelations rels = rels ++ addMirrorRelation (mapMaybe link2Relation links) where links = join $ map (combinations 2) $ filter (not . null) $ groupWith groupFn $ filter ( (==Child). relType) rels groupFn :: Relation -> Text groupFn Relation{relTable=Table{tableSchema=s, tableName=t}} = s<>"_"<>t combinations k ns = filter ((k==).length) (subsequences ns) addMirrorRelation [] = [] addMirrorRelation (rel@(Relation t c ft fc _ lt lc1 lc2):rels') = Relation ft fc t c Many lt lc2 lc1 : rel : addMirrorRelation rels' link2Relation [ Relation{relTable=lt, relColumns=lc1, relFTable=t, relFColumns=c}, Relation{ relColumns=lc2, relFTable=ft, relFColumns=fc} ] | lc1 /= lc2 && length lc1 == 1 && length lc2 == 1 = Just $ Relation t c ft fc Many (Just lt) (Just lc1) (Just lc2) | otherwise = Nothing link2Relation _ = Nothing raiseRelations :: Schema -> [(Column,Column)] -> [Relation] -> [Relation] raiseRelations schema syns = map raiseRel where raiseRel rel | tableSchema table == schema = rel | isJust newCols = rel{relFTable=fromJust newTable,relFColumns=fromJust newCols} | otherwise = rel where cols = relFColumns rel table = relFTable rel newCols = listToMaybe $ filter ((== schema) . tableSchema . colTable . unsafeHead) (synonymousColumns syns cols) newTable = (colTable . unsafeHead) <$> newCols synonymousPrimaryKeys :: [(Column,Column)] -> [PrimaryKey] -> [PrimaryKey] synonymousPrimaryKeys _ [] = [] synonymousPrimaryKeys syns (key:keys) = key : newKeys ++ synonymousPrimaryKeys syns keys where keySyns = filter ((\c -> colTable c == pkTable key && colName c == pkName key) . fst) syns newKeys = map ((\c -> PrimaryKey{pkTable=colTable c,pkName=colName c}) . snd) keySyns allTables :: H.Query () [Table] allTables = H.statement sql HE.unit decodeTables True where sql = [q| SELECT n.nspname AS table_schema, c.relname AS table_name, c.relkind = 'r' OR (c.relkind IN ('v','f')) AND (pg_relation_is_updatable(c.oid::regclass, FALSE) & 8) = 8 OR (EXISTS ( SELECT 1 FROM pg_trigger WHERE pg_trigger.tgrelid = c.oid AND (pg_trigger.tgtype::integer & 69) = 69) ) AS insertable FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('v','r','m') AND n.nspname NOT IN ('pg_catalog', 'information_schema') GROUP BY table_schema, table_name, insertable ORDER BY table_schema, table_name |] allColumns :: [Table] -> H.Query () [Column] allColumns tabs = H.statement sql HE.unit (decodeColumns tabs) True where sql = [q| SELECT DISTINCT info.table_schema AS schema, info.table_name AS table_name, info.column_name AS name, info.ordinal_position AS position, info.is_nullable::boolean AS nullable, info.data_type AS col_type, info.is_updatable::boolean AS updatable, info.character_maximum_length AS max_len, info.numeric_precision AS precision, info.column_default AS default_value, array_to_string(enum_info.vals, ',') AS enum FROM ( /* -- CTE based on information_schema.columns to remove the owner filter */ WITH columns AS ( SELECT current_database()::information_schema.sql_identifier AS table_catalog, nc.nspname::information_schema.sql_identifier AS table_schema, c.relname::information_schema.sql_identifier AS table_name, a.attname::information_schema.sql_identifier AS column_name, a.attnum::information_schema.cardinal_number AS ordinal_position, pg_get_expr(ad.adbin, ad.adrelid)::information_schema.character_data AS column_default, CASE WHEN a.attnotnull OR t.typtype = 'd'::"char" AND t.typnotnull THEN 'NO'::text ELSE 'YES'::text END::information_schema.yes_or_no AS is_nullable, CASE WHEN t.typtype = 'd'::"char" THEN CASE WHEN bt.typelem <> 0::oid AND bt.typlen = (-1) THEN 'ARRAY'::text WHEN nbt.nspname = 'pg_catalog'::name THEN format_type(t.typbasetype, NULL::integer) ELSE format_type(a.atttypid, a.atttypmod) END ELSE CASE WHEN t.typelem <> 0::oid AND t.typlen = (-1) THEN 'ARRAY'::text WHEN nt.nspname = 'pg_catalog'::name THEN format_type(a.atttypid, NULL::integer) ELSE format_type(a.atttypid, a.atttypmod) END END::information_schema.character_data AS data_type, information_schema._pg_char_max_length(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS character_maximum_length, information_schema._pg_char_octet_length(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS character_octet_length, information_schema._pg_numeric_precision(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS numeric_precision, information_schema._pg_numeric_precision_radix(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS numeric_precision_radix, information_schema._pg_numeric_scale(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS numeric_scale, information_schema._pg_datetime_precision(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS datetime_precision, information_schema._pg_interval_type(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.character_data AS interval_type, NULL::integer::information_schema.cardinal_number AS interval_precision, NULL::character varying::information_schema.sql_identifier AS character_set_catalog, NULL::character varying::information_schema.sql_identifier AS character_set_schema, NULL::character varying::information_schema.sql_identifier AS character_set_name, CASE WHEN nco.nspname IS NOT NULL THEN current_database() ELSE NULL::name END::information_schema.sql_identifier AS collation_catalog, nco.nspname::information_schema.sql_identifier AS collation_schema, co.collname::information_schema.sql_identifier AS collation_name, CASE WHEN t.typtype = 'd'::"char" THEN current_database() ELSE NULL::name END::information_schema.sql_identifier AS domain_catalog, CASE WHEN t.typtype = 'd'::"char" THEN nt.nspname ELSE NULL::name END::information_schema.sql_identifier AS domain_schema, CASE WHEN t.typtype = 'd'::"char" THEN t.typname ELSE NULL::name END::information_schema.sql_identifier AS domain_name, current_database()::information_schema.sql_identifier AS udt_catalog, COALESCE(nbt.nspname, nt.nspname)::information_schema.sql_identifier AS udt_schema, COALESCE(bt.typname, t.typname)::information_schema.sql_identifier AS udt_name, NULL::character varying::information_schema.sql_identifier AS scope_catalog, NULL::character varying::information_schema.sql_identifier AS scope_schema, NULL::character varying::information_schema.sql_identifier AS scope_name, NULL::integer::information_schema.cardinal_number AS maximum_cardinality, a.attnum::information_schema.sql_identifier AS dtd_identifier, 'NO'::character varying::information_schema.yes_or_no AS is_self_referencing, 'NO'::character varying::information_schema.yes_or_no AS is_identity, NULL::character varying::information_schema.character_data AS identity_generation, NULL::character varying::information_schema.character_data AS identity_start, NULL::character varying::information_schema.character_data AS identity_increment, NULL::character varying::information_schema.character_data AS identity_maximum, NULL::character varying::information_schema.character_data AS identity_minimum, NULL::character varying::information_schema.yes_or_no AS identity_cycle, 'NEVER'::character varying::information_schema.character_data AS is_generated, NULL::character varying::information_schema.character_data AS generation_expression, CASE WHEN c.relkind = 'r'::"char" OR (c.relkind = ANY (ARRAY['v'::"char", 'f'::"char"])) AND pg_column_is_updatable(c.oid::regclass, a.attnum, false) THEN 'YES'::text ELSE 'NO'::text END::information_schema.yes_or_no AS is_updatable FROM pg_attribute a LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum JOIN (pg_class c JOIN pg_namespace nc ON c.relnamespace = nc.oid) ON a.attrelid = c.oid JOIN (pg_type t JOIN pg_namespace nt ON t.typnamespace = nt.oid) ON a.atttypid = t.oid LEFT JOIN (pg_type bt JOIN pg_namespace nbt ON bt.typnamespace = nbt.oid) ON t.typtype = 'd'::"char" AND t.typbasetype = bt.oid LEFT JOIN (pg_collation co JOIN pg_namespace nco ON co.collnamespace = nco.oid) ON a.attcollation = co.oid AND (nco.nspname <> 'pg_catalog'::name OR co.collname <> 'default'::name) WHERE NOT pg_is_other_temp_schema(nc.oid) AND a.attnum > 0 AND NOT a.attisdropped AND (c.relkind = ANY (ARRAY['r'::"char", 'v'::"char", 'f'::"char"])) /*--AND (pg_has_role(c.relowner, 'USAGE'::text) OR has_column_privilege(c.oid, a.attnum, 'SELECT, INSERT, UPDATE, REFERENCES'::text))*/ ) SELECT table_schema, table_name, column_name, ordinal_position, is_nullable, data_type, is_updatable, character_maximum_length, numeric_precision, column_default, udt_name /*-- FROM information_schema.columns*/ FROM columns WHERE table_schema NOT IN ('pg_catalog', 'information_schema') ) AS info LEFT OUTER JOIN ( SELECT n.nspname AS s, t.typname AS n, array_agg(e.enumlabel ORDER BY e.enumsortorder) AS vals FROM pg_type t JOIN pg_enum e ON t.oid = e.enumtypid JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace GROUP BY s,n ) AS enum_info ON (info.udt_name = enum_info.n) ORDER BY schema, position |] columnFromRow :: [Table] -> (Text, Text, Text, Int32, Bool, Text, Bool, Maybe Int32, Maybe Int32, Maybe Text, Maybe Text) -> Maybe Column columnFromRow tabs (s, t, n, pos, nul, typ, u, l, p, d, e) = buildColumn <$> table where buildColumn tbl = Column tbl n pos nul typ u l p d (parseEnum e) Nothing table = find (\tbl -> tableSchema tbl == s && tableName tbl == t) tabs parseEnum :: Maybe Text -> [Text] parseEnum str = fromMaybe [] $ split (==',') <$> str allRelations :: [Table] -> [Column] -> H.Query () [Relation] allRelations tabs cols = H.statement sql HE.unit (decodeRelations tabs cols) True where sql = [q| SELECT ns1.nspname AS table_schema, tab.relname AS table_name, column_info.cols AS columns, ns2.nspname AS foreign_table_schema, other.relname AS foreign_table_name, column_info.refs AS foreign_columns FROM pg_constraint, LATERAL (SELECT array_agg(cols.attname) AS cols, array_agg(cols.attnum) AS nums, array_agg(refs.attname) AS refs FROM ( SELECT unnest(conkey) AS col, unnest(confkey) AS ref) k, LATERAL (SELECT * FROM pg_attribute WHERE attrelid = conrelid AND attnum = col) AS cols, LATERAL (SELECT * FROM pg_attribute WHERE attrelid = confrelid AND attnum = ref) AS refs) AS column_info, LATERAL (SELECT * FROM pg_namespace WHERE pg_namespace.oid = connamespace) AS ns1, LATERAL (SELECT * FROM pg_class WHERE pg_class.oid = conrelid) AS tab, LATERAL (SELECT * FROM pg_class WHERE pg_class.oid = confrelid) AS other, LATERAL (SELECT * FROM pg_namespace WHERE pg_namespace.oid = other.relnamespace) AS ns2 WHERE confrelid != 0 ORDER BY (conrelid, column_info.nums) |] relationFromRow :: [Table] -> [Column] -> (Text, Text, [Text], Text, Text, [Text]) -> Maybe Relation relationFromRow allTabs allCols (rs, rt, rcs, frs, frt, frcs) = Relation <$> table <*> cols <*> tableF <*> colsF <*> pure Child <*> pure Nothing <*> pure Nothing <*> pure Nothing where findTable s t = find (\tbl -> tableSchema tbl == s && tableName tbl == t) allTabs findCol s t c = find (\col -> tableSchema (colTable col) == s && tableName (colTable col) == t && colName col == c) allCols table = findTable rs rt tableF = findTable frs frt cols = mapM (findCol rs rt) rcs colsF = mapM (findCol frs frt) frcs allPrimaryKeys :: [Table] -> H.Query () [PrimaryKey] allPrimaryKeys tabs = H.statement sql HE.unit (decodePks tabs) True where sql = [q| /* -- CTE to replace information_schema.table_constraints to remove owner limit */ WITH tc AS ( SELECT current_database()::information_schema.sql_identifier AS constraint_catalog, nc.nspname::information_schema.sql_identifier AS constraint_schema, c.conname::information_schema.sql_identifier AS constraint_name, current_database()::information_schema.sql_identifier AS table_catalog, nr.nspname::information_schema.sql_identifier AS table_schema, r.relname::information_schema.sql_identifier AS table_name, CASE c.contype WHEN 'c'::"char" THEN 'CHECK'::text WHEN 'f'::"char" THEN 'FOREIGN KEY'::text WHEN 'p'::"char" THEN 'PRIMARY KEY'::text WHEN 'u'::"char" THEN 'UNIQUE'::text ELSE NULL::text END::information_schema.character_data AS constraint_type, CASE WHEN c.condeferrable THEN 'YES'::text ELSE 'NO'::text END::information_schema.yes_or_no AS is_deferrable, CASE WHEN c.condeferred THEN 'YES'::text ELSE 'NO'::text END::information_schema.yes_or_no AS initially_deferred FROM pg_namespace nc, pg_namespace nr, pg_constraint c, pg_class r WHERE nc.oid = c.connamespace AND nr.oid = r.relnamespace AND c.conrelid = r.oid AND (c.contype <> ALL (ARRAY['t'::"char", 'x'::"char"])) AND r.relkind = 'r'::"char" AND NOT pg_is_other_temp_schema(nr.oid) /*--AND (pg_has_role(r.relowner, 'USAGE'::text) OR has_table_privilege(r.oid, 'INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'::text) OR has_any_column_privilege(r.oid, 'INSERT, UPDATE, REFERENCES'::text))*/ UNION ALL SELECT current_database()::information_schema.sql_identifier AS constraint_catalog, nr.nspname::information_schema.sql_identifier AS constraint_schema, (((((nr.oid::text || '_'::text) || r.oid::text) || '_'::text) || a.attnum::text) || '_not_null'::text)::information_schema.sql_identifier AS constraint_name, current_database()::information_schema.sql_identifier AS table_catalog, nr.nspname::information_schema.sql_identifier AS table_schema, r.relname::information_schema.sql_identifier AS table_name, 'CHECK'::character varying::information_schema.character_data AS constraint_type, 'NO'::character varying::information_schema.yes_or_no AS is_deferrable, 'NO'::character varying::information_schema.yes_or_no AS initially_deferred FROM pg_namespace nr, pg_class r, pg_attribute a WHERE nr.oid = r.relnamespace AND r.oid = a.attrelid AND a.attnotnull AND a.attnum > 0 AND NOT a.attisdropped AND r.relkind = 'r'::"char" AND NOT pg_is_other_temp_schema(nr.oid) /*--AND (pg_has_role(r.relowner, 'USAGE'::text) OR has_table_privilege(r.oid, 'INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'::text) OR has_any_column_privilege(r.oid, 'INSERT, UPDATE, REFERENCES'::text))*/ ), /* -- CTE to replace information_schema.key_column_usage to remove owner limit */ kc AS ( SELECT current_database()::information_schema.sql_identifier AS constraint_catalog, ss.nc_nspname::information_schema.sql_identifier AS constraint_schema, ss.conname::information_schema.sql_identifier AS constraint_name, current_database()::information_schema.sql_identifier AS table_catalog, ss.nr_nspname::information_schema.sql_identifier AS table_schema, ss.relname::information_schema.sql_identifier AS table_name, a.attname::information_schema.sql_identifier AS column_name, (ss.x).n::information_schema.cardinal_number AS ordinal_position, CASE WHEN ss.contype = 'f'::"char" THEN information_schema._pg_index_position(ss.conindid, ss.confkey[(ss.x).n]) ELSE NULL::integer END::information_schema.cardinal_number AS position_in_unique_constraint FROM pg_attribute a, ( SELECT r.oid AS roid, r.relname, r.relowner, nc.nspname AS nc_nspname, nr.nspname AS nr_nspname, c.oid AS coid, c.conname, c.contype, c.conindid, c.confkey, c.confrelid, information_schema._pg_expandarray(c.conkey) AS x FROM pg_namespace nr, pg_class r, pg_namespace nc, pg_constraint c WHERE nr.oid = r.relnamespace AND r.oid = c.conrelid AND nc.oid = c.connamespace AND (c.contype = ANY (ARRAY['p'::"char", 'u'::"char", 'f'::"char"])) AND r.relkind = 'r'::"char" AND NOT pg_is_other_temp_schema(nr.oid)) ss WHERE ss.roid = a.attrelid AND a.attnum = (ss.x).x AND NOT a.attisdropped /*--AND (pg_has_role(ss.relowner, 'USAGE'::text) OR has_column_privilege(ss.roid, a.attnum, 'SELECT, INSERT, UPDATE, REFERENCES'::text))*/ ) SELECT kc.table_schema, kc.table_name, kc.column_name FROM /* --information_schema.table_constraints tc, --information_schema.key_column_usage kc */ tc, kc WHERE tc.constraint_type = 'PRIMARY KEY' AND kc.table_name = tc.table_name AND kc.table_schema = tc.table_schema AND kc.constraint_name = tc.constraint_name AND kc.table_schema NOT IN ('pg_catalog', 'information_schema') |] pkFromRow :: [Table] -> (Schema, Text, Text) -> Maybe PrimaryKey pkFromRow tabs (s, t, n) = PrimaryKey <$> table <*> pure n where table = find (\tbl -> tableSchema tbl == s && tableName tbl == t) tabs allSynonyms :: [Column] -> H.Query () [(Column,Column)] allSynonyms cols = H.statement sql HE.unit (decodeSynonyms cols) True where -- query explanation at https://gist.github.com/ruslantalpa/2eab8c930a65e8043d8f sql = [q| with view_columns as ( select c.oid as view_oid, a.attname::information_schema.sql_identifier as column_name from pg_attribute a join pg_class c on a.attrelid = c.oid join pg_namespace nc on c.relnamespace = nc.oid where not pg_is_other_temp_schema(nc.oid) and a.attnum > 0 and not a.attisdropped and (c.relkind = 'v'::"char") and nc.nspname not in ('information_schema', 'pg_catalog') ), view_column_usage as ( select distinct v.oid as view_oid, nv.nspname::information_schema.sql_identifier as view_schema, v.relname::information_schema.sql_identifier as view_name, nt.nspname::information_schema.sql_identifier as table_schema, t.relname::information_schema.sql_identifier as table_name, a.attname::information_schema.sql_identifier as column_name, pg_get_viewdef(v.oid)::information_schema.character_data as view_definition from pg_namespace nv join pg_class v on nv.oid = v.relnamespace join pg_depend dv on v.oid = dv.refobjid join pg_depend dt on dv.objid = dt.objid join pg_class t on dt.refobjid = t.oid join pg_namespace nt on t.relnamespace = nt.oid join pg_attribute a on t.oid = a.attrelid and dt.refobjsubid = a.attnum where nv.nspname not in ('information_schema', 'pg_catalog') and v.relkind = 'v'::"char" and dv.refclassid = 'pg_class'::regclass::oid and dv.classid = 'pg_rewrite'::regclass::oid and dv.deptype = 'i'::"char" and dv.refobjid <> dt.refobjid and dt.classid = 'pg_rewrite'::regclass::oid and dt.refclassid = 'pg_class'::regclass::oid and (t.relkind = any (array['r'::"char", 'v'::"char", 'f'::"char"])) ), candidates as ( select vcu.*, ( select case when match is not null then coalesce(match[8], match[7], match[4]) end from regexp_matches( CONCAT('SELECT ', SPLIT_PART(vcu.view_definition, 'SELECT', 2)), CONCAT('SELECT.*?((',vcu.table_name,')|(\w+))\.(', vcu.column_name, ')(\s+AS\s+("([^"]+)"|([^, \n\t]+)))?.*?FROM.*?',vcu.table_schema,'\.(\2|',vcu.table_name,'\s+(as\s)?\3)'), 'nsi' ) match ) as view_column_name from view_column_usage as vcu ) select c.table_schema, c.table_name, c.column_name as table_column_name, c.view_schema, c.view_name, c.view_column_name from view_columns as vc, candidates as c where vc.view_oid = c.view_oid and vc.column_name = c.view_column_name order by c.view_schema, c.view_name, c.table_name, c.view_column_name |] synonymFromRow :: [Column] -> (Text,Text,Text,Text,Text,Text) -> Maybe (Column,Column) synonymFromRow allCols (s1,t1,c1,s2,t2,c2) = (,) <$> col1 <*> col2 where col1 = findCol s1 t1 c1 col2 = findCol s2 t2 c2 findCol s t c = find (\col -> (tableSchema . colTable) col == s && (tableName . colTable) col == t && colName col == c) allCols
NotBrianZach/postgrest
src/PostgREST/DbStructure.hs
Haskell
mit
31,146
module GHCJS.DOM.SVGViewElement ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/SVGViewElement.hs
Haskell
mit
44
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-spend.html module Stratosphere.ResourceProperties.BudgetsBudgetSpend where import Stratosphere.ResourceImports -- | Full data type definition for BudgetsBudgetSpend. See -- 'budgetsBudgetSpend' for a more convenient constructor. data BudgetsBudgetSpend = BudgetsBudgetSpend { _budgetsBudgetSpendAmount :: Val Double , _budgetsBudgetSpendUnit :: Val Text } deriving (Show, Eq) instance ToJSON BudgetsBudgetSpend where toJSON BudgetsBudgetSpend{..} = object $ catMaybes [ (Just . ("Amount",) . toJSON) _budgetsBudgetSpendAmount , (Just . ("Unit",) . toJSON) _budgetsBudgetSpendUnit ] -- | Constructor for 'BudgetsBudgetSpend' containing required fields as -- arguments. budgetsBudgetSpend :: Val Double -- ^ 'bbsAmount' -> Val Text -- ^ 'bbsUnit' -> BudgetsBudgetSpend budgetsBudgetSpend amountarg unitarg = BudgetsBudgetSpend { _budgetsBudgetSpendAmount = amountarg , _budgetsBudgetSpendUnit = unitarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-spend.html#cfn-budgets-budget-spend-amount bbsAmount :: Lens' BudgetsBudgetSpend (Val Double) bbsAmount = lens _budgetsBudgetSpendAmount (\s a -> s { _budgetsBudgetSpendAmount = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-spend.html#cfn-budgets-budget-spend-unit bbsUnit :: Lens' BudgetsBudgetSpend (Val Text) bbsUnit = lens _budgetsBudgetSpendUnit (\s a -> s { _budgetsBudgetSpendUnit = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/BudgetsBudgetSpend.hs
Haskell
mit
1,728
module Pos.Infra.Binary () where import Pos.Infra.Binary.DHTModel ()
input-output-hk/pos-haskell-prototype
infra/src/Pos/Infra/Binary.hs
Haskell
mit
80
module Text.Spoonerize ( spoonerize ) where import System.Random import Data.Array.IO import Control.Monad import Data.List (sort) import Data.Char (isLower, toLower, toUpper) type Sequence = Int type Word = String type IsSpoonerizable = Bool data WordInfo = WordInfo Sequence Word IsSpoonerizable deriving (Show) instance Ord WordInfo where (WordInfo seq1 _ _) `compare` (WordInfo seq2 _ _) = seq1 `compare` seq2 instance Eq WordInfo where (WordInfo seq1 word1 bool1) == (WordInfo seq2 word2 bool2) = seq1 == seq2 && word1 == word2 && bool1 == bool2 type AnnotatedSentence = [WordInfo] alphabet = ['A'..'Z'] ++ ['a'..'z'] vowels = "AEIOUaeiou" -- | Randomly shuffle a list -- /O(N)/ -- From http://www.haskell.org/haskellwiki/Random_shuffle#Imperative_algorithm shuffle :: [a] -> IO [a] shuffle xs = do ar <- newArray n xs forM [1..n] $ \i -> do j <- randomRIO (i,n) vi <- readArray ar i vj <- readArray ar j writeArray ar j vi return vj where n = length xs newArray :: Int -> [a] -> IO (IOArray Int a) newArray n = newListArray (1, n) annotatedSentence :: String -> AnnotatedSentence annotatedSentence sent = map (\(x, y, z) -> (WordInfo x y z)) wordTuples where sentence = words sent wordTuples = zip3 [1..] sentence $ cycle [True] caseFunction :: Char -> (Char -> Char) caseFunction char = if isLower char then toLower else toUpper isTooShort :: Word -> Bool isTooShort word = length word <= 1 hasLeadingVowel :: Word -> Bool hasLeadingVowel word = not (null word) && head word `elem` vowels isSpoonerizableWord :: Word -> Bool isSpoonerizableWord word = not (isTooShort word) && not (hasLeadingVowel word) && not (isAllConsonants word) markSpoonerizableWords :: AnnotatedSentence -> AnnotatedSentence markSpoonerizableWords = map (\(WordInfo x y z) -> (WordInfo x y (z && isSpoonerizableWord y))) spoonerizableWords :: AnnotatedSentence -> AnnotatedSentence spoonerizableWords = filter (\(WordInfo _ _ isSpoonerizable) -> isSpoonerizable) wordBeginning :: String -> String wordBeginning = takeWhile isConsonant wordEnding :: String -> String wordEnding = dropWhile isConsonant isConsonant :: Char -> Bool isConsonant l = l `notElem` vowels isAllConsonants :: Word -> Bool isAllConsonants = all isConsonant applyCase :: Char -> Char -> Char applyCase sourceCharacter destCharacter = (caseFunction sourceCharacter) destCharacter swapWordCase :: (Word, Word) -> (Word, Word) swapWordCase (wordA, wordB) = ([newLtrA] ++ tail wordA, [newLtrB] ++ tail wordB) where firstLtrA = head wordA firstLtrB = head wordB newLtrA = applyCase firstLtrB firstLtrA newLtrB = applyCase firstLtrA firstLtrB swapWordBeginnings :: (Word, Word) -> (Word, Word) swapWordBeginnings (wordA, wordB) = (wordBeginning bCaseFlipped ++ wordEnding wordA, wordBeginning aCaseFlipped ++ wordEnding wordB) where (aCaseFlipped, bCaseFlipped) = swapWordCase (wordA, wordB) spoonerizeWords :: (WordInfo, WordInfo) -> (WordInfo, WordInfo) spoonerizeWords (WordInfo seqA wordA boolA, WordInfo seqB wordB boolB) = (WordInfo seqA newWordA boolA, WordInfo seqB newWordB boolB) where (newWordA, newWordB) = swapWordBeginnings(wordA, wordB) wordSequenceNumbers :: [WordInfo] -> [Int] wordSequenceNumbers = map (\(WordInfo sequenceNumber _ _) -> sequenceNumber) substituteWords :: ([WordInfo], WordInfo, WordInfo) -> String substituteWords (oldsentence, toSpoonerizeA, toSpoonerizeB) = unwords $ map (\(WordInfo _ word _) -> word) orderedWords where sequencesToReplace = wordSequenceNumbers [spoonerizedA, spoonerizedB] minusSpoonerized = filter (\(WordInfo seq _ _) -> (seq `notElem` sequencesToReplace)) oldsentence (spoonerizedA, spoonerizedB) = spoonerizeWords(toSpoonerizeA, toSpoonerizeB) newSentence = minusSpoonerized ++ [spoonerizedA, spoonerizedB] orderedWords = sort newSentence spoonerize :: String -> IO String spoonerize str = let markedWords = markSpoonerizableWords $ annotatedSentence str in do shuffled <- shuffle $ spoonerizableWords markedWords let [toSpoonerizeA, toSpoonerizeB] = take 2 shuffled in return $ substituteWords(markedWords, toSpoonerizeA, toSpoonerizeB)
jsl/spoonerize
Text/Spoonerize.hs
Haskell
mit
4,556
{-# LANGUAGE GADTs,RankNTypes,DeriveFunctor #-} module Faceted.FIORef ( FIORef, newFIORef, readFIORef, writeFIORef, ) where import Faceted.Internal import Data.IORef -- | Variables of type 'FIORef a' are faceted 'IORef's data FIORef a = FIORef (IORef (Faceted a)) -- | Allocate a new 'FIORef' newFIORef :: Faceted a -> FIO (FIORef a) newFIORef init = FIO newFIORefForPC where newFIORefForPC pc = do var <- newIORef (pcF pc init undefined) return (FIORef var) -- | Read an 'FIORef' readFIORef :: FIORef a -> FIO (Faceted a) readFIORef (FIORef var) = FIO readFIORefForPC where readFIORefForPC pc = do faceted <- readIORef var return faceted -- | Write an 'FIORef' writeFIORef :: FIORef a -> Faceted a -> FIO () writeFIORef (FIORef var) newValue = FIO writeFIORefForPC where writeFIORefForPC pc = do oldValue <- readIORef var writeIORef var (pcF pc newValue oldValue)
haskell-faceted/haskell-faceted
Faceted/FIORef.hs
Haskell
apache-2.0
986
#!/usr/bin/env stack {- stack --install-ghc runghc --package Command --package text --package hflags -} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} import Control.Monad import Data.Version import HFlags import System.Command import Text.ParserCombinators.ReadP defineFlag "version" ("0.0.1" :: String) "version." defineFlag "name" ("Indiana Jones" :: String) "Who to greet." systemOrDie :: String -> IO () systemOrDie cmd = do result <- system cmd when (isFailure result) $ error $ "Failed: " ++ cmd return () packages :: [String] packages = [ "ethereum-analyzer" , "ethereum-analyzer-deps" , "ethereum-analyzer-webui" , "ethereum-analyzer-cli" ] main :: IO () main = do _ <- $initHFlags "release_to_hackage.hs" case reverse $ readP_to_S parseVersion flags_version of (Version v@[_, _, _] [], ""):_ -> do putStrLn $ "Updating to version " ++ show v systemOrDie "git checkout master" systemOrDie "git stash" _ <- mapM (\package -> do systemOrDie $ "sed -i'' " ++ "'s/^version:\\([[:blank:]]*\\)[[:digit:]]\\+.[[:digit:]]\\+.[[:digit:]]\\+" ++ "/version:\\1" ++ flags_version ++ "/' " ++ package ++ "/" ++ package ++ ".cabal" systemOrDie $ "sed -i'' " ++ "'s/^ tag:\\([[:blank:]]*\\)v[[:digit:]]\\+.[[:digit:]]\\+.[[:digit:]]\\+" ++ "/ tag:\\1v" ++ flags_version ++ "/' " ++ package ++ "/" ++ package ++ ".cabal" systemOrDie $ "stack upload --no-signature " ++ package) packages systemOrDie $ "git commit . -m 'tagging v" ++ flags_version ++ "'" systemOrDie $ "git tag v" ++ flags_version systemOrDie "git push origin --tags" other -> error $ "malformed version: " ++ flags_version ++ " " ++ show other return ()
zchn/ethereum-analyzer
scripts/release_to_hackage.hs
Haskell
apache-2.0
1,919
{-# LANGUAGE OverloadedStrings #-} -- | NSIS (Nullsoft Scriptable Install System, <http://nsis.sourceforge.net/>) is a tool that allows programmers -- to create installers for Windows. -- This library provides an alternative syntax for NSIS scripts, as an embedded Haskell language, removing much -- of the hard work in developing an install script. Simple NSIS installers should look mostly the same, complex ones should -- be significantly more maintainable. -- -- As a simple example of using this library: -- -- @ --import "Development.NSIS" -- --main = writeFile \"example1.nsi\" $ 'nsis' $ do -- 'name' \"Example1\" -- The name of the installer -- 'outFile' \"example1.exe\" -- Where to produce the installer -- 'installDir' \"$DESKTOP/Example1\" -- The default installation directory -- 'requestExecutionLevel' 'User' -- Request application privileges for Windows Vista -- -- Pages to display -- 'page' 'Directory' -- Pick where to install -- 'page' 'InstFiles' -- Give a progress bar while installing -- -- Groups fo files to install -- 'section' \"\" [] $ do -- 'setOutPath' \"$INSTDIR\" -- Where to install files in this section -- 'file' [] \"Example1.hs\" -- File to put into this section -- @ -- -- The file @example1.nsi@ can now be processed with @makensis@ to produce the installer @example1.exe@. -- For more examples, see the @Examples@ source directory. -- -- Much of the documentation from the Installer section is taken from the NSIS documentation. module Development.NSIS ( -- * Core types nsis, nsisNoOptimise, Action, Exp, Value, -- * Scripting -- ** Variables share, scope, constant, constant_, mutable, mutable_, (@=), -- ** Typed variables mutableInt, constantInt, mutableInt_, constantInt_, mutableStr, constantStr, mutableStr_, constantStr_, -- ** Control Flow iff, iff_, while, loop, onError, (?), (%&&), (%||), Label, newLabel, label, goto, -- ** Expressions str, int, bool, (%==), (%/=), (%<=), (%<), (%>=), (%>), true, false, not_, strRead, strShow, (&), strConcat, strLength, strTake, strDrop, strReplace, strIsPrefixOf, strIsSuffixOf, strUnlines, strCheck, -- ** File system manipulation FileHandle, fileOpen, fileWrite, fileClose, withFile', writeFile', writeFileLines, rmdir, delete, copyFiles, getFileTime, fileExists, findEach, createDirectory, createShortcut, -- ** Registry manipulation readRegStr, deleteRegKey, deleteRegValue, writeRegStr, writeRegExpandStr, writeRegDWORD, -- ** Environment variables envVar, -- ** Process execution exec, execWait, execShell, sleep, abort, -- ** Windows HWND, hwndParent, findWindow, getDlgItem, sendMessage, -- ** Plugins plugin, push, pop, exp_, addPluginDir, -- * Installer -- ** Global installer options name, outFile, installDir, setCompressor, installIcon, uninstallIcon, headerImage, installDirRegKey, allowRootDirInstall, caption, showInstDetails, showUninstDetails, unicode, -- ** Sections SectionId, section, sectionGroup, newSectionId, sectionSetText, sectionGetText, sectionSet, sectionGet, uninstall, page, unpage, finishOptions, -- ** Events event, onSelChange, onPageShow, onPagePre, onPageLeave, -- ** Section commands file, alwaysNonFatal, writeUninstaller, alert, setOutPath, messageBox, requestExecutionLevel, hideProgress, detailPrint, setDetailsPrint, -- * Escape hatch unsafeInject, unsafeInjectGlobal, -- * Settings Compressor(..), HKEY(..), MessageBoxType(..), Attrib(..), Page(..), Level(..), Visibility(..), FileMode(..), SectionFlag(..), ShowWindow(..), FinishOptions(..), DetailsPrint(..) ) where import Control.Monad import Development.NSIS.Sugar import Development.NSIS.Show import Development.NSIS.Optimise import Development.NSIS.Library -- | Create the contents of an NSIS script from an installer specification. -- -- Beware, 'unsafeInject' and 'unsafeInjectGlobal' may break 'nsis'. The -- optimizer relies on invariants that may not hold when arbitrary lines are -- injected. Consider using 'nsisNoOptimise' if problems arise. nsis :: Action a -> String nsis = unlines . showNSIS . optimise . runAction . void -- | Like 'nsis', but don't try and optimise the resulting NSIS script. -- -- Useful to figure out how the underlying installer works, or if you believe -- the optimisations are introducing bugs. Please do report any such bugs, -- especially if you aren't using 'unsafeInject' or 'unsafeInjectGlobal'! nsisNoOptimise :: Action a -> String nsisNoOptimise = unlines . showNSIS . runAction . void
idleberg/NSIS
Development/NSIS.hs
Haskell
apache-2.0
4,801
-------------------------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} import Data.Monoid (mappend) import Hakyll type RenderingFunction = FeedConfiguration -> Context String -> [Item String] -> Compiler (Item String) myFeedConfiguration :: FeedConfiguration myFeedConfiguration = FeedConfiguration { feedTitle = "Haskell without remorse" , feedDescription = "Blog about Haskell development" , feedAuthorName = "Anton Gushcha" , feedAuthorEmail = "ncrashed@gmail.com" , feedRoot = "http://ncrashed.github.io/blog" } createFeed :: Identifier -> RenderingFunction -> Rules () createFeed name renderingFunction = create [name] $ do route idRoute compile $ do let feedCtx = postCtx `mappend` bodyField "description" posts <- fmap (take 10) . recentFirst =<< loadAllSnapshots "posts/*" "content" renderingFunction myFeedConfiguration feedCtx posts -------------------------------------------------------------------------------- main :: IO () main = hakyll $ do match "images/*" $ do route idRoute compile copyFileCompiler match "fonts/*" $ do route idRoute compile copyFileCompiler match "css/*" $ do route idRoute compile compressCssCompiler match (fromList ["about.markdown", "contact.markdown"]) $ do route $ setExtension "html" compile $ pandocCompiler >>= loadAndApplyTemplate "templates/default.html" defaultContext >>= relativizeUrls match "posts/*" $ do route $ setExtension "html" compile $ pandocCompiler >>= loadAndApplyTemplate "templates/post.html" postCtx >>= saveSnapshot "content" >>= loadAndApplyTemplate "templates/default.html" postCtx >>= relativizeUrls -- create ["archive.html"] $ do -- route idRoute -- compile $ do -- posts <- recentFirst =<< loadAll "posts/*" -- let archiveCtx = -- listField "posts" postCtx (return posts) `mappend` -- constField "title" "Archives" `mappend` -- defaultContext -- -- makeItem "" -- >>= loadAndApplyTemplate "templates/archive.html" archiveCtx -- >>= loadAndApplyTemplate "templates/default.html" archiveCtx -- >>= relativizeUrls match "index.html" $ do route idRoute compile $ do posts <- recentFirst =<< loadAll "posts/*" let indexCtx = listField "posts" postCtx (return posts) `mappend` constField "title" "Home" `mappend` defaultContext getResourceBody >>= applyAsTemplate indexCtx >>= loadAndApplyTemplate "templates/default.html" indexCtx >>= relativizeUrls match "templates/*" $ compile templateBodyCompiler createFeed "feed.xml" renderRss createFeed "atom.xml" renderAtom -------------------------------------------------------------------------------- postCtx :: Context String postCtx = dateField "date" "%B %e, %Y" `mappend` defaultContext
NCrashed/blog
src/site.hs
Haskell
apache-2.0
3,002
-- 1 -- 2, 1 -- 6, 2, 1 -- 24, 9, 2, 1 -- 120, 44, 13, ?, 1 type Board = [(Int, Int)] -- patternAvoidingPermutations board n = ??? -- Not smart, since it doesn't use the results from (k-1) to help compute k. -- Also, not tail recursive. nonAttackingRookCount 0 _ = 1 nonAttackingRookCount _ [] = 0 nonAttackingRookCount k ((x,y):rs) = nonAttackingRookCount (k - 1) rs' + nonAttackingRookCount k rs where rs' = filter (\(a, b) -> a /= x && b /= y) rs
peterokagey/haskellOEIS
src/Sandbox/Richard/table.hs
Haskell
apache-2.0
467
{-# LANGUAGE TemplateHaskell #-} module TH.HSCs where import Language.Haskell.TH import TH.API import TH.APIs import TH.HSC $(do runIO $ putStrLn "HSC generation" apis <- generateAPIs "apis" generateHSCs apis runIO $ putStrLn "..Done" return [] )
fabianbergmark/APIs
src/TH/HSCs.hs
Haskell
bsd-2-clause
277
{-# LANGUAGE DeriveDataTypeable #-} module Application.DiagramDrawer.ProgType where import System.Console.CmdArgs data Diagdrawer = Test deriving (Show,Data,Typeable) test :: Diagdrawer test = Test mode = modes [test]
wavewave/diagdrawer
lib/Application/DiagramDrawer/ProgType.hs
Haskell
bsd-2-clause
241
{-| Module : Idris.Elab.Interface Description : Code to elaborate interfaces. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE PatternGuards #-} {-# OPTIONS_GHC -fwarn-missing-signatures #-} module Idris.Elab.Interface(elabInterface) 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.DeepSeq import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting) import IRTS.Lang import Idris.Elab.Type import Idris.Elab.Data 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 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 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 Data.Generics.Uniplate.Data (transform) import Util.Pretty(pretty, text) data MArgTy = IA Name | EA Name | CA deriving Show elabInterface :: ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm) -> FC -> [(Name, PTerm)] -> Name -> FC -> [(Name, FC, PTerm)] -> [(Name, Docstring (Either Err PTerm))] -> [(Name, FC)] -- ^ determining params -> [PDecl] -- ^ interface body -> Maybe (Name, FC) -- ^ implementation ctor name and location -> Docstring (Either Err PTerm) -- ^ implementation ctor docs -> Idris () elabInterface info syn_in doc fc constraints tn tnfc ps pDocs fds ds mcn cd = do let cn = fromMaybe (SN (ImplementationCtorN tn)) (fst <$> mcn) let tty = pibind (map (\(n, _, ty) -> (n, ty)) ps) (PType fc) let constraint = PApp fc (PRef fc [] tn) (map (pexp . PRef fc []) (map (\(n, _, _) -> n) ps)) let syn = syn_in { using = addToUsing (using syn_in) [(pn, pt) | (pn, _, pt) <- ps] } -- build data declaration let mdecls = filter tydecl ds -- method declarations let idecls = filter impldecl ds -- default super interface implementation declarations mapM_ checkDefaultSuperInterfaceImplementation idecls let mnames = map getMName mdecls ist <- getIState let constraintNames = nub $ concatMap (namesIn [] ist) (map snd constraints) mapM_ (checkConstraintName (map (\(x, _, _) -> x) ps)) constraintNames logElab 2 $ "Building methods " ++ show mnames ims <- mapM (tdecl mnames) mdecls defs <- mapM (defdecl (map (\ (x,y,z) -> z) ims) constraint) (filter clause ds) let (methods, imethods) = unzip (map (\ (x, y, z) -> (x, y)) ims) let defaults = map (\ (x, (y, z)) -> (x,y)) defs -- build implementation constructor type let cty = impbind [(pn, pt) | (pn, _, pt) <- ps] $ conbind constraints $ pibind (map (\ (n, ty) -> (nsroot n, ty)) methods) constraint let cons = [(cd, pDocs ++ mapMaybe memberDocs ds, cn, NoFC, cty, fc, [])] let ddecl = PDatadecl tn NoFC tty cons logElab 5 $ "Interface data " ++ show (showDImp verbosePPOption ddecl) -- Elaborate the data declaration elabData info (syn { no_imp = no_imp syn ++ mnames, imp_methods = mnames }) doc pDocs fc [] ddecl dets <- findDets cn (map fst fds) addInterface tn (CI cn (map nodoc imethods) defaults idecls (map (\(n, _, _) -> n) ps) [] dets) -- for each constraint, build a top level function to chase it cfns <- mapM (cfun cn constraint syn (map fst imethods)) constraints mapM_ (rec_elabDecl info EAll info) (concat cfns) -- for each method, build a top level function fns <- mapM (tfun cn constraint (syn { imp_methods = mnames }) (map fst imethods)) imethods logElab 5 $ "Functions " ++ show fns -- Elaborate the the top level methods mapM_ (rec_elabDecl info EAll info) (concat fns) -- Flag all the top level data declarations as injective mapM_ (\n -> do setInjectivity n True addIBC (IBCInjective n True)) (map fst (filter (\(_, (inj, _, _, _, _)) -> inj) imethods)) -- add the default definitions mapM_ (rec_elabDecl info EAll info) (concatMap (snd.snd) defs) addIBC (IBCInterface tn) sendHighlighting $ [(tnfc, AnnName tn Nothing Nothing Nothing)] ++ [(pnfc, AnnBoundName pn False) | (pn, pnfc, _) <- ps] ++ [(fdfc, AnnBoundName fc False) | (fc, fdfc) <- fds] ++ maybe [] (\(conN, conNFC) -> [(conNFC, AnnName conN Nothing Nothing Nothing)]) mcn where nodoc (n, (inj, _, _, o, t)) = (n, (inj, o, t)) pibind [] x = x pibind ((n, ty): ns) x = PPi expl n NoFC ty (pibind ns (chkUniq ty x)) -- To make sure the type constructor of the interface is in the appropriate -- uniqueness hierarchy chkUniq u@(PUniverse _ _) (PType _) = u chkUniq (PUniverse _ l) (PUniverse _ r) = PUniverse NoFC (min l r) chkUniq (PPi _ _ _ _ sc) t = chkUniq sc t chkUniq _ t = t -- TODO: probably should normalise checkDefaultSuperInterfaceImplementation :: PDecl -> Idris () checkDefaultSuperInterfaceImplementation (PImplementation _ _ _ fc cs _ _ _ n _ ps _ _ _ _) = do when (not $ null cs) . tclift $ tfail (At fc (Msg "Default super interface implementations can't have constraints.")) i <- getIState let t = PApp fc (PRef fc [] n) (map pexp ps) let isConstrained = any (== t) (map snd constraints) when (not isConstrained) . tclift $ tfail (At fc (Msg "Default implementations must be for a super interface constraint on the containing interface.")) return () checkConstraintName :: [Name] -> Name -> Idris () checkConstraintName bound cname | cname `notElem` bound = tclift $ tfail (At fc (Msg $ "Name " ++ show cname ++ " is not bound in interface " ++ show tn ++ " " ++ showSep " " (map show bound))) | otherwise = return () impbind :: [(Name, PTerm)] -> PTerm -> PTerm impbind [] x = x impbind ((n, ty): ns) x = PPi impl n NoFC ty (impbind ns x) conbind :: [(Name, PTerm)] -> PTerm -> PTerm conbind ((c, ty) : ns) x = PPi constraint c NoFC ty (conbind ns x) conbind [] x = x getMName (PTy _ _ _ _ _ n nfc _) = nsroot n getMName (PData _ _ _ _ _ (PLaterdecl n nfc _)) = nsroot n tdecl allmeths (PTy doc _ syn _ o n nfc t) = do t' <- implicit' info syn (map (\(n, _, _) -> n) ps ++ allmeths) n t logElab 2 $ "Method " ++ show n ++ " : " ++ showTmImpls t' return ( (n, (toExp (map (\(pn, _, _) -> pn) ps) Exp t')), (n, (False, nfc, doc, o, (toExp (map (\(pn, _, _) -> pn) ps) (\ l s p -> Imp l s p Nothing True) t'))), (n, (nfc, syn, o, t) ) ) tdecl allmeths (PData doc _ syn _ _ (PLaterdecl n nfc t)) = do let o = [] t' <- implicit' info syn (map (\(n, _, _) -> n) ps ++ allmeths) n t logElab 2 $ "Data method " ++ show n ++ " : " ++ showTmImpls t' return ( (n, (toExp (map (\(pn, _, _) -> pn) ps) Exp t')), (n, (True, nfc, doc, o, (toExp (map (\(pn, _, _) -> pn) ps) (\ l s p -> Imp l s p Nothing True) t'))), (n, (nfc, syn, o, t) ) ) tdecl allmeths (PData doc _ syn _ _ _) = ierror $ At fc (Msg "Data definitions not allowed in an interface declaration") tdecl _ _ = ierror $ At fc (Msg "Not allowed in an interface declaration") -- Create default definitions defdecl mtys c d@(PClauses fc opts n cs) = case lookup n mtys of Just (nfc, syn, o, ty) -> do let ty' = insertConstraint c (map fst mtys) ty let ds = map (decorateid defaultdec) [PTy emptyDocstring [] syn fc [] n nfc ty', PClauses fc (o ++ opts) n cs] logElab 1 (show ds) return (n, ((defaultdec n, ds!!1), ds)) _ -> ierror $ At fc (Msg (show n ++ " is not a method")) defdecl _ _ _ = ifail "Can't happen (defdecl)" defaultdec (UN n) = sUN ("default#" ++ str n) defaultdec (NS n ns) = NS (defaultdec n) ns tydecl (PTy{}) = True tydecl (PData _ _ _ _ _ _) = True tydecl _ = False impldecl (PImplementation{}) = True impldecl _ = False clause (PClauses{}) = True clause _ = False -- Generate a function for chasing a dictionary constraint cfun :: Name -> PTerm -> SyntaxInfo -> [a] -> (Name, PTerm) -> Idris [PDecl' PTerm] cfun cn c syn all (cnm, con) = do let cfn = SN (ParentN cn (txt (show con))) let mnames = take (length all) $ map (\x -> sMN x "meth") [0..] let capp = PApp fc (PRef fc [] cn) (map (pexp . PRef fc []) mnames) let lhs = PApp fc (PRef fc [] cfn) [pconst capp] let rhs = PResolveTC (fileFC "HACK") let ty = PPi constraint cnm NoFC c con logElab 2 ("Dictionary constraint: " ++ showTmImpls ty) logElab 2 (showTmImpls lhs ++ " = " ++ showTmImpls rhs) i <- getIState let conn = case con of PRef _ _ n -> n PApp _ (PRef _ _ n) _ -> n let conn' = case lookupCtxtName conn (idris_interfaces i) of [(n, _)] -> n _ -> conn addImplementation False True conn' cfn addIBC (IBCImplementation False True conn' cfn) -- iputStrLn ("Added " ++ show (conn, cfn, ty)) return [PTy emptyDocstring [] syn fc [] cfn NoFC ty, PClauses fc [Inlinable, Dictionary] cfn [PClause fc cfn lhs [] rhs []]] -- | Generate a top level function which looks up a method in a given -- dictionary (this is inlinable, always) tfun :: Name -- ^ The name of the interface -> PTerm -- ^ A constraint for the interface, to be inserted under the implicit bindings -> SyntaxInfo -> [Name] -- ^ All the method names -> (Name, (Bool, FC, Docstring (Either Err PTerm), FnOpts, PTerm)) -- ^ The present declaration -> Idris [PDecl] tfun cn c syn all (m, (isdata, mfc, doc, o, ty)) = do let ty' = expandMethNS syn (insertConstraint c all ty) let mnames = take (length all) $ map (\x -> sMN x "meth") [0..] let capp = PApp fc (PRef fc [] cn) (map (pexp . PRef fc []) mnames) let margs = getMArgs ty let anames = map (\x -> sMN x "arg") [0..] let lhs = PApp fc (PRef fc [] m) (pconst capp : lhsArgs margs anames) let rhs = PApp fc (getMeth mnames all m) (rhsArgs margs anames) logElab 2 ("Top level type: " ++ showTmImpls ty') logElab 1 (show (m, ty', capp, margs)) logElab 2 ("Definition: " ++ showTmImpls lhs ++ " = " ++ showTmImpls rhs) return [PTy doc [] syn fc o m mfc ty', PClauses fc [Inlinable] m [PClause fc m lhs [] rhs []]] getMArgs (PPi (Imp _ _ _ _ _) n _ ty sc) = IA n : getMArgs sc getMArgs (PPi (Exp _ _ _) n _ ty sc) = EA n : getMArgs sc getMArgs (PPi (Constraint _ _) n _ ty sc) = CA : getMArgs sc getMArgs _ = [] getMeth :: [Name] -> [Name] -> Name -> PTerm getMeth (m:ms) (a:as) x | x == a = PRef fc [] m | otherwise = getMeth ms as x lhsArgs (EA _ : xs) (n : ns) = [] -- pexp (PRef fc n) : lhsArgs xs ns lhsArgs (IA n : xs) ns = pimp n (PRef fc [] n) False : lhsArgs xs ns lhsArgs (CA : xs) ns = lhsArgs xs ns lhsArgs [] _ = [] rhsArgs (EA _ : xs) (n : ns) = [] -- pexp (PRef fc n) : rhsArgs xs ns rhsArgs (IA n : xs) ns = pexp (PRef fc [] n) : rhsArgs xs ns rhsArgs (CA : xs) ns = pconst (PResolveTC fc) : rhsArgs xs ns rhsArgs [] _ = [] -- Add the top level constraint. Put it first - elaboration will resolve -- the order of the implicits if there are dependencies. -- Also ensure the dictionary is used for lookup of any methods that -- are used in the type insertConstraint :: PTerm -> [Name] -> PTerm -> PTerm insertConstraint c all sc = let dictN = sMN 0 "__interface" in PPi (constraint { pstatic = Static }) dictN NoFC c (constrainMeths (map basename all) dictN sc) where -- After we insert the constraint into the lookup, we need to -- ensure that the same dictionary is used to resolve lookups -- to the other methods in the interface constrainMeths :: [Name] -> Name -> PTerm -> PTerm constrainMeths allM dictN tm = transform (addC allM dictN) tm addC allM dictN m@(PRef fc hls n) | n `elem` allM = PApp NoFC m [pconst (PRef NoFC hls dictN)] | otherwise = m addC _ _ tm = tm -- make arguments explicit and don't bind interface parameters toExp ns e (PPi (Imp l s p _ _) n fc ty sc) | n `elem` ns = toExp ns e sc | otherwise = PPi (e l s p) n fc ty (toExp ns e sc) toExp ns e (PPi p n fc ty sc) = PPi p n fc ty (toExp ns e sc) toExp ns e sc = sc -- | Get the method declaration name corresponding to a user-provided name mdec :: Name -> Name mdec (UN n) = SN (MethodN (UN n)) mdec (NS x n) = NS (mdec x) n mdec x = x -- | Get the docstring corresponding to a member, if one exists memberDocs :: PDecl -> Maybe (Name, Docstring (Either Err PTerm)) memberDocs (PTy d _ _ _ _ n _ _) = Just (basename n, d) memberDocs (PPostulate _ d _ _ _ _ n _) = Just (basename n, d) memberDocs (PData d _ _ _ _ pdata) = Just (basename $ d_name pdata, d) memberDocs (PRecord d _ _ _ n _ _ _ _ _ _ _ ) = Just (basename n, d) memberDocs (PInterface d _ _ _ n _ _ _ _ _ _ _) = Just (basename n, d) memberDocs _ = Nothing -- | In a top level type for a method, expand all the method names' namespaces -- so that we don't have to disambiguate later expandMethNS :: SyntaxInfo -> PTerm -> PTerm expandMethNS syn = mapPT expand where expand (PRef fc hls n) | n `elem` imp_methods syn = PRef fc hls $ expandNS syn n expand t = t -- | Find the determining parameter locations findDets :: Name -> [Name] -> Idris [Int] findDets n ns = do i <- getIState return $ case lookupTyExact n (tt_ctxt i) of Just ty -> getDetPos 0 ns ty Nothing -> [] where getDetPos i ns (Bind n (Pi _ _ _) sc) | n `elem` ns = i : getDetPos (i + 1) ns sc | otherwise = getDetPos (i + 1) ns sc getDetPos _ _ _ = []
enolan/Idris-dev
src/Idris/Elab/Interface.hs
Haskell
bsd-3-clause
15,877
-- | This module reexport everything which is needed for message -- definition in generated code. There is no need import this module -- in user code. module Data.Protobuf.Imports ( -- * Data types Word32 , Word64 , Int32 , Int64 , Bool , Double , Float , String , Maybe(..) , Seq , ByteString -- * Functions , singleton , undefined , comparing , ap , mapM , mapM_ -- ** Converwsion , checkMaybe , checkMaybeMsg , checkRequired , checkRequiredMsg -- * Classes , Show(..) , Eq(..) , Ord(..) , Enum(..) , Bounded(..) , Functor(..) , Monad(..) , Monoid(..) , Typeable(..) , Data(..) , LoopType -- * Modules , module P' , module Data.Serialize.VarInt ) where import Control.Monad (ap, liftM) import Data.Data (Data(..),Typeable(..)) import Data.Word (Word32, Word64) import Data.Int (Int32, Int64) import Data.Ord import Data.Monoid (Monoid(..)) import Data.Sequence (Seq,singleton) import Data.ByteString (ByteString) import Data.Foldable (mapM_) import Data.Traversable (mapM) import Data.Protobuf.Classes as P' import Data.Serialize as P' import Data.Serialize.Protobuf as P' import Data.Serialize.VarInt import Prelude hiding (mapM,mapM_) -- | Type of worker function in the generated code. type LoopType v = v Unchecked -> Get (v Unchecked) -- | Check optional value checkMaybe :: Monad m => a -> Maybe a -> m (Maybe a) checkMaybe x Nothing = return (Just x) checkMaybe _ x = return x {-# INLINE checkMaybe #-} -- | Check optional value checkMaybeMsg :: (Message a, Monad m) => Maybe (a Unchecked) -> m (Maybe (a Checked)) checkMaybeMsg Nothing = return Nothing checkMaybeMsg (Just x) = liftM Just (checkReq x) {-# INLINE checkMaybeMsg #-} -- | Check required value checkRequired :: Monad m => Required a -> m a checkRequired NotSet = fail "Field is not set!" checkRequired (Present x) = return x {-# INLINE checkRequired #-} -- | Check required message checkRequiredMsg :: (Message a, Monad m) => Required (a Unchecked) -> m (a Checked) checkRequiredMsg NotSet = fail "Field is not set!" checkRequiredMsg (Present x) = checkReq x {-# INLINE checkRequiredMsg #-}
Shimuuar/protobuf
protobuf-lib/Data/Protobuf/Imports.hs
Haskell
bsd-3-clause
2,306
module Hackage.Twitter.Bot.Types where import Data.Time () import Data.Time.Clock data FullPost = FullPost { fullPostAuthor :: String, fullPostDescription :: String, fullPostTime :: UTCTime, fullPostTitle :: String, fullPostLink :: String} deriving (Show) data PartialPost = PartialPost {author :: String , description :: String, postTime :: UTCTime} deriving (Show)
KevinCotrone/hackage-twitter-bot
src/Hackage/Twitter/Bot/Types.hs
Haskell
bsd-3-clause
396
module Main(main) where import System.Environment (getArgs, getProgName) import Web.Zenfolio.API import qualified Web.Zenfolio.Categories as Categories dumpCategories :: ZM () dumpCategories = do categories <- Categories.getCategories liftIO $ putStrLn ("Categories: " ++ show categories) main :: IO () main = do ls <- getArgs case ls of [] -> zenfolio $ dumpCategories _ -> do prg <- getProgName putStrLn ("Usage: " ++ prg)
md5/hs-zenfolio
examples/GetCategories.hs
Haskell
bsd-3-clause
506
{-# LANGUAGE TupleSections, OverloadedStrings, QuasiQuotes, TemplateHaskell, TypeFamilies, RecordWildCards, DeriveGeneric ,MultiParamTypeClasses ,FlexibleInstances #-} module Protocol.ROC.PointTypes.PointType121 where import GHC.Generics import qualified Data.ByteString as BS import Data.Word import Data.Binary import Data.Binary.Get data PointType121 = PointType121 { pointType121TagID :: !PointType121TagID ,pointType121SlaveAddress1 :: !PointType121SlaveAddress1 ,pointType121FunctionCode1 :: !PointType121FunctionCode1 ,pointType121SlaveRegister1 :: !PointType121SlaveRegister1 ,pointType121MasterRegister1 :: !PointType121MasterRegister1 ,pointType121NumOfRegisters1 :: !PointType121NumOfRegisters1 ,pointType121CommStatus1 :: !PointType121CommStatus1 ,pointType121SlaveAddress2 :: !PointType121SlaveAddress2 ,pointType121FunctionCode2 :: !PointType121FunctionCode2 ,pointType121SlaveRegister2 :: !PointType121SlaveRegister2 ,pointType121MasterRegister2 :: !PointType121MasterRegister2 ,pointType121NumOfRegisters2 :: !PointType121NumOfRegisters2 ,pointType121CommStatus2 :: !PointType121CommStatus2 ,pointType121SlaveAddress3 :: !PointType121SlaveAddress3 ,pointType121FunctionCode3 :: !PointType121FunctionCode3 ,pointType121SlaveRegister3 :: !PointType121SlaveRegister3 ,pointType121MasterRegister3 :: !PointType121MasterRegister3 ,pointType121NumOfRegisters3 :: !PointType121NumOfRegisters3 ,pointType121CommStatus3 :: !PointType121CommStatus3 ,pointType121SlaveAddress4 :: !PointType121SlaveAddress4 ,pointType121FunctionCode4 :: !PointType121FunctionCode4 ,pointType121SlaveRegister4 :: !PointType121SlaveRegister4 ,pointType121MasterRegister4 :: !PointType121MasterRegister4 ,pointType121NumOfRegisters4 :: !PointType121NumOfRegisters4 ,pointType121CommStatus4 :: !PointType121CommStatus4 ,pointType121SlaveAddress5 :: !PointType121SlaveAddress5 ,pointType121FunctionCode5 :: !PointType121FunctionCode5 ,pointType121SlaveRegister5 :: !PointType121SlaveRegister5 ,pointType121MasterRegister5 :: !PointType121MasterRegister5 ,pointType121NumOfRegisters5 :: !PointType121NumOfRegisters5 ,pointType121CommStatus5 :: !PointType121CommStatus5 ,pointType121SlaveAddress6 :: !PointType121SlaveAddress6 ,pointType121FunctionCode6 :: !PointType121FunctionCode6 ,pointType121SlaveRegister6 :: !PointType121SlaveRegister6 ,pointType121MasterRegister6 :: !PointType121MasterRegister6 ,pointType121NumOfRegisters6 :: !PointType121NumOfRegisters6 ,pointType121CommStatus6 :: !PointType121CommStatus6 ,pointType121SlaveAddress7 :: !PointType121SlaveAddress7 ,pointType121FunctionCode7 :: !PointType121FunctionCode7 ,pointType121SlaveRegister7 :: !PointType121SlaveRegister7 ,pointType121MasterRegister7 :: !PointType121MasterRegister7 ,pointType121NumOfRegisters7 :: !PointType121NumOfRegisters7 ,pointType121CommStatus7 :: !PointType121CommStatus7 ,pointType121SlaveAddress8 :: !PointType121SlaveAddress8 ,pointType121FunctionCode8 :: !PointType121FunctionCode8 ,pointType121SlaveRegister8 :: !PointType121SlaveRegister8 ,pointType121MasterRegister8 :: !PointType121MasterRegister8 ,pointType121NumOfRegisters8 :: !PointType121NumOfRegisters8 ,pointType121CommStatus8 :: !PointType121CommStatus8 ,pointType121SlaveAddress9 :: !PointType121SlaveAddress9 ,pointType121FunctionCode9 :: !PointType121FunctionCode9 ,pointType121SlaveRegister9 :: !PointType121SlaveRegister9 ,pointType121MasterRegister9 :: !PointType121MasterRegister9 ,pointType121NumOfRegisters9 :: !PointType121NumOfRegisters9 ,pointType121CommStatus9 :: !PointType121CommStatus9 ,pointType121SlaveAddress10 :: !PointType121SlaveAddress10 ,pointType121FunctionCode10 :: !PointType121FunctionCode10 ,pointType121SlaveRegister10 :: !PointType121SlaveRegister10 ,pointType121MasterRegister10 :: !PointType121MasterRegister10 ,pointType121NumOfRegisters10 :: !PointType121NumOfRegisters10 ,pointType121CommStatus10 :: !PointType121CommStatus10 ,pointType121SlaveAddress11 :: !PointType121SlaveAddress11 ,pointType121FunctionCode11 :: !PointType121FunctionCode11 ,pointType121SlaveRegister11 :: !PointType121SlaveRegister11 ,pointType121MasterRegister11 :: !PointType121MasterRegister11 ,pointType121NumOfRegisters11 :: !PointType121NumOfRegisters11 ,pointType121CommStatus11 :: !PointType121CommStatus11 ,pointType121SlaveAddress12 :: !PointType121SlaveAddress12 ,pointType121FunctionCode12 :: !PointType121FunctionCode12 ,pointType121SlaveRegister12 :: !PointType121SlaveRegister12 ,pointType121MasterRegister12 :: !PointType121MasterRegister12 ,pointType121NumOfRegisters12 :: !PointType121NumOfRegisters12 ,pointType121CommStatus12 :: !PointType121CommStatus12 ,pointType121SlaveAddress13 :: !PointType121SlaveAddress13 ,pointType121FunctionCode13 :: !PointType121FunctionCode13 ,pointType121SlaveRegister13 :: !PointType121SlaveRegister13 ,pointType121MasterRegister13 :: !PointType121MasterRegister13 ,pointType121NumOfRegisters13 :: !PointType121NumOfRegisters13 ,pointType121CommStatus13 :: !PointType121CommStatus13 ,pointType121SlaveAddress14 :: !PointType121SlaveAddress14 ,pointType121FunctionCode14 :: !PointType121FunctionCode14 ,pointType121SlaveRegister14 :: !PointType121SlaveRegister14 ,pointType121MasterRegister14 :: !PointType121MasterRegister14 ,pointType121NumOfRegisters14 :: !PointType121NumOfRegisters14 ,pointType121CommStatus14 :: !PointType121CommStatus14 ,pointType121SlaveAddress15 :: !PointType121SlaveAddress15 ,pointType121FunctionCode15 :: !PointType121FunctionCode15 ,pointType121SlaveRegister15 :: !PointType121SlaveRegister15 ,pointType121MasterRegister15 :: !PointType121MasterRegister15 ,pointType121NumOfRegisters15 :: !PointType121NumOfRegisters15 ,pointType121CommStatus15 :: !PointType121CommStatus15 ,pointType121SlaveAddress16 :: !PointType121SlaveAddress16 ,pointType121FunctionCode16 :: !PointType121FunctionCode16 ,pointType121SlaveRegister16 :: !PointType121SlaveRegister16 ,pointType121MasterRegister16 :: !PointType121MasterRegister16 ,pointType121NumOfRegisters16 :: !PointType121NumOfRegisters16 ,pointType121CommStatus16 :: !PointType121CommStatus16 ,pointType121SlaveAddress17 :: !PointType121SlaveAddress17 ,pointType121FunctionCode17 :: !PointType121FunctionCode17 ,pointType121SlaveRegister17 :: !PointType121SlaveRegister17 ,pointType121MasterRegister17 :: !PointType121MasterRegister17 ,pointType121NumOfRegisters17 :: !PointType121NumOfRegisters17 ,pointType121CommStatus17 :: !PointType121CommStatus17 ,pointType121SlaveAddress18 :: !PointType121SlaveAddress18 ,pointType121FunctionCode18 :: !PointType121FunctionCode18 ,pointType121SlaveRegister18 :: !PointType121SlaveRegister18 ,pointType121MasterRegister18 :: !PointType121MasterRegister18 ,pointType121NumOfRegisters18 :: !PointType121NumOfRegisters18 ,pointType121CommStatus18 :: !PointType121CommStatus18 ,pointType121SlaveAddress19 :: !PointType121SlaveAddress19 ,pointType121FunctionCode19 :: !PointType121FunctionCode19 ,pointType121SlaveRegister19 :: !PointType121SlaveRegister19 ,pointType121MasterRegister19 :: !PointType121MasterRegister19 ,pointType121NumOfRegisters19 :: !PointType121NumOfRegisters19 ,pointType121CommStatus19 :: !PointType121CommStatus19 ,pointType121SlaveAddress20 :: !PointType121SlaveAddress20 ,pointType121FunctionCode20 :: !PointType121FunctionCode20 ,pointType121SlaveRegister20 :: !PointType121SlaveRegister20 ,pointType121MasterRegister20 :: !PointType121MasterRegister20 ,pointType121NumOfRegisters20 :: !PointType121NumOfRegisters20 ,pointType121CommStatus20 :: !PointType121CommStatus20 ,pointType121SlaveAddress21 :: !PointType121SlaveAddress21 ,pointType121FunctionCode21 :: !PointType121FunctionCode21 ,pointType121SlaveRegister21 :: !PointType121SlaveRegister21 ,pointType121MasterRegister21 :: !PointType121MasterRegister21 ,pointType121NumOfRegisters21 :: !PointType121NumOfRegisters21 ,pointType121CommStatus21 :: !PointType121CommStatus21 ,pointType121SlaveAddress22 :: !PointType121SlaveAddress22 ,pointType121FunctionCode22 :: !PointType121FunctionCode22 ,pointType121SlaveRegister22 :: !PointType121SlaveRegister22 ,pointType121MasterRegister22 :: !PointType121MasterRegister22 ,pointType121NumOfRegisters22 :: !PointType121NumOfRegisters22 ,pointType121CommStatus22 :: !PointType121CommStatus22 ,pointType121SlaveAddress23 :: !PointType121SlaveAddress23 ,pointType121FunctionCode23 :: !PointType121FunctionCode23 ,pointType121SlaveRegister23 :: !PointType121SlaveRegister23 ,pointType121MasterRegister23 :: !PointType121MasterRegister23 ,pointType121NumOfRegisters23 :: !PointType121NumOfRegisters23 ,pointType121CommStatus23 :: !PointType121CommStatus23 ,pointType121SlaveAddress24 :: !PointType121SlaveAddress24 ,pointType121FunctionCode24 :: !PointType121FunctionCode24 ,pointType121SlaveRegister24 :: !PointType121SlaveRegister24 ,pointType121MasterRegister24 :: !PointType121MasterRegister24 ,pointType121NumOfRegisters24 :: !PointType121NumOfRegisters24 ,pointType121CommStatus24 :: !PointType121CommStatus24 ,pointType121SlaveAddress25 :: !PointType121SlaveAddress25 ,pointType121FunctionCode25 :: !PointType121FunctionCode25 ,pointType121SlaveRegister25 :: !PointType121SlaveRegister25 ,pointType121MasterRegister25 :: !PointType121MasterRegister25 ,pointType121NumOfRegisters25 :: !PointType121NumOfRegisters25 ,pointType121CommStatus25 :: !PointType121CommStatus25 } deriving (Read,Eq, Show, Generic) type PointType121TagID = BS.ByteString type PointType121SlaveAddress1 = Word8 type PointType121FunctionCode1 = Word8 type PointType121SlaveRegister1 = Word16 type PointType121MasterRegister1 = Word16 type PointType121NumOfRegisters1 = Word8 type PointType121CommStatus1 = Word8 type PointType121SlaveAddress2 = Word8 type PointType121FunctionCode2 = Word8 type PointType121SlaveRegister2 = Word16 type PointType121MasterRegister2 = Word16 type PointType121NumOfRegisters2 = Word8 type PointType121CommStatus2 = Word8 type PointType121SlaveAddress3 = Word8 type PointType121FunctionCode3 = Word8 type PointType121SlaveRegister3 = Word16 type PointType121MasterRegister3 = Word16 type PointType121NumOfRegisters3 = Word8 type PointType121CommStatus3 = Word8 type PointType121SlaveAddress4 = Word8 type PointType121FunctionCode4 = Word8 type PointType121SlaveRegister4 = Word16 type PointType121MasterRegister4 = Word16 type PointType121NumOfRegisters4 = Word8 type PointType121CommStatus4 = Word8 type PointType121SlaveAddress5 = Word8 type PointType121FunctionCode5 = Word8 type PointType121SlaveRegister5 = Word16 type PointType121MasterRegister5 = Word16 type PointType121NumOfRegisters5 = Word8 type PointType121CommStatus5 = Word8 type PointType121SlaveAddress6 = Word8 type PointType121FunctionCode6 = Word8 type PointType121SlaveRegister6 = Word16 type PointType121MasterRegister6 = Word16 type PointType121NumOfRegisters6 = Word8 type PointType121CommStatus6 = Word8 type PointType121SlaveAddress7 = Word8 type PointType121FunctionCode7 = Word8 type PointType121SlaveRegister7 = Word16 type PointType121MasterRegister7 = Word16 type PointType121NumOfRegisters7 = Word8 type PointType121CommStatus7 = Word8 type PointType121SlaveAddress8 = Word8 type PointType121FunctionCode8 = Word8 type PointType121SlaveRegister8 = Word16 type PointType121MasterRegister8 = Word16 type PointType121NumOfRegisters8 = Word8 type PointType121CommStatus8 = Word8 type PointType121SlaveAddress9 = Word8 type PointType121FunctionCode9 = Word8 type PointType121SlaveRegister9 = Word16 type PointType121MasterRegister9 = Word16 type PointType121NumOfRegisters9 = Word8 type PointType121CommStatus9 = Word8 type PointType121SlaveAddress10 = Word8 type PointType121FunctionCode10 = Word8 type PointType121SlaveRegister10 = Word16 type PointType121MasterRegister10 = Word16 type PointType121NumOfRegisters10 = Word8 type PointType121CommStatus10 = Word8 type PointType121SlaveAddress11 = Word8 type PointType121FunctionCode11 = Word8 type PointType121SlaveRegister11 = Word16 type PointType121MasterRegister11 = Word16 type PointType121NumOfRegisters11 = Word8 type PointType121CommStatus11 = Word8 type PointType121SlaveAddress12 = Word8 type PointType121FunctionCode12 = Word8 type PointType121SlaveRegister12 = Word16 type PointType121MasterRegister12 = Word16 type PointType121NumOfRegisters12 = Word8 type PointType121CommStatus12 = Word8 type PointType121SlaveAddress13 = Word8 type PointType121FunctionCode13 = Word8 type PointType121SlaveRegister13 = Word16 type PointType121MasterRegister13 = Word16 type PointType121NumOfRegisters13 = Word8 type PointType121CommStatus13 = Word8 type PointType121SlaveAddress14 = Word8 type PointType121FunctionCode14 = Word8 type PointType121SlaveRegister14 = Word16 type PointType121MasterRegister14 = Word16 type PointType121NumOfRegisters14 = Word8 type PointType121CommStatus14 = Word8 type PointType121SlaveAddress15 = Word8 type PointType121FunctionCode15 = Word8 type PointType121SlaveRegister15 = Word16 type PointType121MasterRegister15 = Word16 type PointType121NumOfRegisters15 = Word8 type PointType121CommStatus15 = Word8 type PointType121SlaveAddress16 = Word8 type PointType121FunctionCode16 = Word8 type PointType121SlaveRegister16 = Word16 type PointType121MasterRegister16 = Word16 type PointType121NumOfRegisters16 = Word8 type PointType121CommStatus16 = Word8 type PointType121SlaveAddress17 = Word8 type PointType121FunctionCode17 = Word8 type PointType121SlaveRegister17 = Word16 type PointType121MasterRegister17 = Word16 type PointType121NumOfRegisters17 = Word8 type PointType121CommStatus17 = Word8 type PointType121SlaveAddress18 = Word8 type PointType121FunctionCode18 = Word8 type PointType121SlaveRegister18 = Word16 type PointType121MasterRegister18 = Word16 type PointType121NumOfRegisters18 = Word8 type PointType121CommStatus18 = Word8 type PointType121SlaveAddress19 = Word8 type PointType121FunctionCode19 = Word8 type PointType121SlaveRegister19 = Word16 type PointType121MasterRegister19 = Word16 type PointType121NumOfRegisters19 = Word8 type PointType121CommStatus19 = Word8 type PointType121SlaveAddress20 = Word8 type PointType121FunctionCode20 = Word8 type PointType121SlaveRegister20 = Word16 type PointType121MasterRegister20 = Word16 type PointType121NumOfRegisters20 = Word8 type PointType121CommStatus20 = Word8 type PointType121SlaveAddress21 = Word8 type PointType121FunctionCode21 = Word8 type PointType121SlaveRegister21 = Word16 type PointType121MasterRegister21 = Word16 type PointType121NumOfRegisters21 = Word8 type PointType121CommStatus21 = Word8 type PointType121SlaveAddress22 = Word8 type PointType121FunctionCode22 = Word8 type PointType121SlaveRegister22 = Word16 type PointType121MasterRegister22 = Word16 type PointType121NumOfRegisters22 = Word8 type PointType121CommStatus22 = Word8 type PointType121SlaveAddress23 = Word8 type PointType121FunctionCode23 = Word8 type PointType121SlaveRegister23 = Word16 type PointType121MasterRegister23 = Word16 type PointType121NumOfRegisters23 = Word8 type PointType121CommStatus23 = Word8 type PointType121SlaveAddress24 = Word8 type PointType121FunctionCode24 = Word8 type PointType121SlaveRegister24 = Word16 type PointType121MasterRegister24 = Word16 type PointType121NumOfRegisters24 = Word8 type PointType121CommStatus24 = Word8 type PointType121SlaveAddress25 = Word8 type PointType121FunctionCode25 = Word8 type PointType121SlaveRegister25 = Word16 type PointType121MasterRegister25 = Word16 type PointType121NumOfRegisters25 = Word8 type PointType121CommStatus25 = Word8 pointType121Parser :: Get PointType121 pointType121Parser = do tagID <- getByteString 10 slaveAddress1 <- getWord8 functionCode1 <- getWord8 slaveRegister1 <- getWord16le masterRegister1 <- getWord16le numOfRegisters1 <- getWord8 commStatus1 <- getWord8 slaveAddress2 <- getWord8 functionCode2 <- getWord8 slaveRegister2 <- getWord16le masterRegister2 <- getWord16le numOfRegisters2 <- getWord8 commStatus2 <- getWord8 slaveAddress3 <- getWord8 functionCode3 <- getWord8 slaveRegister3 <- getWord16le masterRegister3 <- getWord16le numOfRegisters3 <- getWord8 commStatus3 <- getWord8 slaveAddress4 <- getWord8 functionCode4 <- getWord8 slaveRegister4 <- getWord16le masterRegister4 <- getWord16le numOfRegisters4 <- getWord8 commStatus4 <- getWord8 slaveAddress5 <- getWord8 functionCode5 <- getWord8 slaveRegister5 <- getWord16le masterRegister5 <- getWord16le numOfRegisters5 <- getWord8 commStatus5 <- getWord8 slaveAddress6 <- getWord8 functionCode6 <- getWord8 slaveRegister6 <- getWord16le masterRegister6 <- getWord16le numOfRegisters6 <- getWord8 commStatus6 <- getWord8 slaveAddress7 <- getWord8 functionCode7 <- getWord8 slaveRegister7 <- getWord16le masterRegister7 <- getWord16le numOfRegisters7 <- getWord8 commStatus7 <- getWord8 slaveAddress8 <- getWord8 functionCode8 <- getWord8 slaveRegister8 <- getWord16le masterRegister8 <- getWord16le numOfRegisters8 <- getWord8 commStatus8 <- getWord8 slaveAddress9 <- getWord8 functionCode9 <- getWord8 slaveRegister9 <- getWord16le masterRegister9 <- getWord16le numOfRegisters9 <- getWord8 commStatus9 <- getWord8 slaveAddress10 <- getWord8 functionCode10 <- getWord8 slaveRegister10 <- getWord16le masterRegister10 <- getWord16le numOfRegisters10 <- getWord8 commStatus10 <- getWord8 slaveAddress11 <- getWord8 functionCode11 <- getWord8 slaveRegister11 <- getWord16le masterRegister11 <- getWord16le numOfRegisters11 <- getWord8 commStatus11 <- getWord8 slaveAddress12 <- getWord8 functionCode12 <- getWord8 slaveRegister12 <- getWord16le masterRegister12 <- getWord16le numOfRegisters12 <- getWord8 commStatus12 <- getWord8 slaveAddress13 <- getWord8 functionCode13 <- getWord8 slaveRegister13 <- getWord16le masterRegister13 <- getWord16le numOfRegisters13 <- getWord8 commStatus13 <- getWord8 slaveAddress14 <- getWord8 functionCode14 <- getWord8 slaveRegister14 <- getWord16le masterRegister14 <- getWord16le numOfRegisters14 <- getWord8 commStatus14 <- getWord8 slaveAddress15 <- getWord8 functionCode15 <- getWord8 slaveRegister15 <- getWord16le masterRegister15 <- getWord16le numOfRegisters15 <- getWord8 commStatus15 <- getWord8 slaveAddress16 <- getWord8 functionCode16 <- getWord8 slaveRegister16 <- getWord16le masterRegister16 <- getWord16le numOfRegisters16 <- getWord8 commStatus16 <- getWord8 slaveAddress17 <- getWord8 functionCode17 <- getWord8 slaveRegister17 <- getWord16le masterRegister17 <- getWord16le numOfRegisters17 <- getWord8 commStatus17 <- getWord8 slaveAddress18 <- getWord8 functionCode18 <- getWord8 slaveRegister18 <- getWord16le masterRegister18 <- getWord16le numOfRegisters18 <- getWord8 commStatus18 <- getWord8 slaveAddress19 <- getWord8 functionCode19 <- getWord8 slaveRegister19 <- getWord16le masterRegister19 <- getWord16le numOfRegisters19 <- getWord8 commStatus19 <- getWord8 slaveAddress20 <- getWord8 functionCode20 <- getWord8 slaveRegister20 <- getWord16le masterRegister20 <- getWord16le numOfRegisters20 <- getWord8 commStatus20 <- getWord8 slaveAddress21 <- getWord8 functionCode21 <- getWord8 slaveRegister21 <- getWord16le masterRegister21 <- getWord16le numOfRegisters21 <- getWord8 commStatus21 <- getWord8 slaveAddress22 <- getWord8 functionCode22 <- getWord8 slaveRegister22 <- getWord16le masterRegister22 <- getWord16le numOfRegisters22 <- getWord8 commStatus22 <- getWord8 slaveAddress23 <- getWord8 functionCode23 <- getWord8 slaveRegister23 <- getWord16le masterRegister23 <- getWord16le numOfRegisters23 <- getWord8 commStatus23 <- getWord8 slaveAddress24 <- getWord8 functionCode24 <- getWord8 slaveRegister24 <- getWord16le masterRegister24 <- getWord16le numOfRegisters24 <- getWord8 commStatus24 <- getWord8 slaveAddress25 <- getWord8 functionCode25 <- getWord8 slaveRegister25 <- getWord16le masterRegister25 <- getWord16le numOfRegisters25 <- getWord8 commStatus25 <- getWord8 return $ PointType121 tagID slaveAddress1 functionCode1 slaveRegister1 masterRegister1 numOfRegisters1 commStatus1 slaveAddress2 functionCode2 slaveRegister2 masterRegister2 numOfRegisters2 commStatus2 slaveAddress3 functionCode3 slaveRegister3 masterRegister3 numOfRegisters3 commStatus3 slaveAddress4 functionCode4 slaveRegister4 masterRegister4 numOfRegisters4 commStatus4 slaveAddress5 functionCode5 slaveRegister5 masterRegister5 numOfRegisters5 commStatus5 slaveAddress6 functionCode6 slaveRegister6 masterRegister6 numOfRegisters6 commStatus6 slaveAddress7 functionCode7 slaveRegister7 masterRegister7 numOfRegisters7 commStatus7 slaveAddress8 functionCode8 slaveRegister8 masterRegister8 numOfRegisters8 commStatus8 slaveAddress9 functionCode9 slaveRegister9 masterRegister9 numOfRegisters9 commStatus9 slaveAddress10 functionCode10 slaveRegister10 masterRegister10 numOfRegisters10 commStatus10 slaveAddress11 functionCode11 slaveRegister11 masterRegister11 numOfRegisters11 commStatus11 slaveAddress12 functionCode12 slaveRegister12 masterRegister12 numOfRegisters12 commStatus12 slaveAddress13 functionCode13 slaveRegister13 masterRegister13 numOfRegisters13 commStatus13 slaveAddress14 functionCode14 slaveRegister14 masterRegister14 numOfRegisters14 commStatus14 slaveAddress15 functionCode15 slaveRegister15 masterRegister15 numOfRegisters15 commStatus15 slaveAddress16 functionCode16 slaveRegister16 masterRegister16 numOfRegisters16 commStatus16 slaveAddress17 functionCode17 slaveRegister17 masterRegister17 numOfRegisters17 commStatus17 slaveAddress18 functionCode18 slaveRegister18 masterRegister18 numOfRegisters18 commStatus18 slaveAddress19 functionCode19 slaveRegister19 masterRegister19 numOfRegisters19 commStatus19 slaveAddress20 functionCode20 slaveRegister20 masterRegister20 numOfRegisters20 commStatus20 slaveAddress21 functionCode21 slaveRegister21 masterRegister21 numOfRegisters21 commStatus21 slaveAddress22 functionCode22 slaveRegister22 masterRegister22 numOfRegisters22 commStatus22 slaveAddress23 functionCode23 slaveRegister23 masterRegister23 numOfRegisters23 commStatus23 slaveAddress24 functionCode24 slaveRegister24 masterRegister24 numOfRegisters24 commStatus24 slaveAddress25 functionCode25 slaveRegister25 masterRegister25 numOfRegisters25 commStatus25
jqpeterson/roc-translator
src/Protocol/ROC/PointTypes/PointType121.hs
Haskell
bsd-3-clause
30,295