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
import Control.Monad import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import Data.Char import Data.IORef import Data.Vhd import Data.Vhd.Bat import qualified Data.Vhd.Block as Block import Data.Vhd.Checksum import Data.Vhd.Node import Data.Vhd.Types import System.Environment (getArgs) import System.IO import Text.Printf cmdConvert [fileRaw, fileVhd, size] = convert =<< rawSizeBytes where vhdSizeMiB = read size vhdSizeBytes = vhdSizeMiB * 1024 * 1024 rawSizeBytes = fmap fromIntegral $ withFile fileRaw ReadMode hFileSize convert rawSizeBytes | vhdSizeMiB `mod` 2 /= 0 = error "specified VHD size is not a multiple of 2 MiB." | vhdSizeBytes < rawSizeBytes = error "specified VHD size is not large enough to contain raw data." | otherwise = do create fileVhd $ defaultCreateParameters { createVirtualSize = vhdSizeBytes } withVhd fileVhd $ \vhd -> BL.readFile fileRaw >>= writeDataRange vhd 0 cmdConvert _ = error "usage: convert <raw file> <vhd file> <size MiB>" cmdCreate [name, size] = create name $ defaultCreateParameters { createVirtualSize = read size * 1024 * 1024 } cmdCreate _ = error "usage: create <name> <size MiB>" cmdExtract [fileVhd, fileRaw] = withVhd fileVhd $ readData >=> BL.writeFile fileRaw cmdExtract _ = error "usage: extract <vhd file> <raw file>" cmdPropGet [file, key] = withVhdNode file $ \node -> do case map toLower key of "max-table-entries" -> putStrLn $ show $ headerMaxTableEntries $ nodeHeader node "blocksize" -> putStrLn $ show $ headerBlockSize $ nodeHeader node "disk-type" -> putStrLn $ show $ footerDiskType $ nodeFooter node "current-size" -> putStrLn $ show $ footerCurrentSize $ nodeFooter node "uuid" -> putStrLn $ show $ footerUniqueId $ nodeFooter node "parent-uuid" -> putStrLn $ show $ headerParentUniqueId $ nodeHeader node "parent-timestamp" -> putStrLn $ show $ headerParentTimeStamp $ nodeHeader node "parent-filepath" -> putStrLn $ show $ headerParentUnicodeName $ nodeHeader node "timestamp" -> putStrLn $ show $ footerTimeStamp $ nodeFooter node _ -> error "unknown key" cmdPropGet _ = error "usage: prop-get <file> <key>" cmdRead [file] = withVhdNode file $ \node -> do let hdr = nodeHeader node let ftr = nodeFooter node mapM_ (\(f, s) -> putStrLn (f ++ " : " ++ s)) [ ("cookie ", show $ headerCookie hdr) , ("version ", show $ headerVersion hdr) , ("max-table-entries", show $ headerMaxTableEntries hdr) , ("block-size ", showBlockSize $ headerBlockSize hdr) , ("header-checksum ", showChecksum (headerChecksum hdr) (verifyHeaderChecksum hdr)) , ("parent-uuid ", show $ headerParentUniqueId hdr) , ("parent-filepath ", show $ headerParentUnicodeName hdr) , ("parent-timestamp ", show $ headerParentTimeStamp hdr) ] mapM_ (\(f, s) -> putStrLn (f ++ " : " ++ s)) [ ("disk-geometry ", show $ footerDiskGeometry ftr) , ("original-size ", showBlockSize $ footerOriginalSize ftr) , ("current-size ", showBlockSize $ footerOriginalSize ftr) , ("type ", show $ footerDiskType ftr) , ("footer-checksum ", showChecksum (footerChecksum ftr) (verifyFooterChecksum ftr)) , ("uuid ", show $ footerUniqueId ftr) , ("timestamp ", show $ footerTimeStamp ftr) ] allocated <- newIORef 0 batIterate (nodeBat node) (fromIntegral $ headerMaxTableEntries hdr) $ \i n -> do unless (n == 0xffffffff) $ modifyIORef allocated ((+) 1) >> printf "BAT[%.5x] = %08x\n" i n nb <- readIORef allocated putStrLn ("blocks allocated : " ++ show nb ++ "/" ++ show (headerMaxTableEntries hdr)) cmdRead _ = error "usage: read <file>" cmdSnapshot [fileVhdParent, fileVhdChild] = withVhd fileVhdParent $ \vhdParent -> snapshot vhdParent fileVhdChild cmdSnapshot _ = error "usage: snapshot <parent vhd file> <child vhd file>" showBlockSize i | i < 1024 = printf "%d bytes" i | i < (1024^2) = printf "%d KiB" (i `div` 1024) | i < (1024^3) = printf "%d MiB" (i `div` (1024^2)) | otherwise = printf "%d GiB" (i `div` (1024^3)) showChecksum checksum isValid = printf "%08x (%s)" checksum (if isValid then "valid" else "invalid") main = do args <- getArgs case args of "convert" : xs -> cmdConvert xs "create" : xs -> cmdCreate xs "extract" : xs -> cmdExtract xs "prop-get" : xs -> cmdPropGet xs "read" : xs -> cmdRead xs "snapshot" : xs -> cmdSnapshot xs
jonathanknowles/hs-vhd
Vhd.hs
Haskell
bsd-3-clause
4,579
([(16, ("long double", 16, [])), (15, ("double", 8, [])), (14, ("float", 4, [])), (13, ("unsigned long long", 8, [])), (12, ("unsigned long", 8, [])), (11, ("unsigned int", 4, [])), (10, ("unsigned short", 2, [])), (9, ( "long long", 8, [])), (8, ("long", 8, [])), (7, ("int", 4, [])), (6, ("short", 2, [])), (5, ( "unsigned char", 1, [])), (4, ("signed char", 1, [])), (3, ("char", 1, [])), (2, ("_Bool", 1, [])), (0, ("void", 1, [])), (1, ("void (void)", 1, []))], [("galois'find'Q", [ ("__galois_return_variable", 7, 0, 4), ( "a_old", 7, 1, 8), ( "size_old", 7, 0, 4), ( "x_old", 7, 0, 4)]), ( "galois'find'P", [ ("a", 7, 1, 8), ( "size", 7, 0, 4), ( "x", 7, 0, 4)]), ( "galois'find'I1", [ ("a_old", 7, 1, 8), ( "size_old", 7, 0, 4), ( "x_old", 7, 0, 4), ( "__retres", 7, 0, 4), ( "i", 7, 0, 4), ( "a", 7, 1, 8), ( "size", 7, 0, 4), ( "x", 7, 0, 4)])])
GaloisInc/verification-game
web-prover/demo-levels/find/types.hs
Haskell
bsd-3-clause
1,940
module Environment where import Graphics.Rendering.OpenGL hiding (($=)) import Graphics.UI.GLUT import Control.Applicative import Data.IORef import System.Exit import Graphics.UI.GLUT.Callbacks.Window import Control.Concurrent import Control.Concurrent.MVar import System.Random import System.IO.Unsafe type Cor = (GLfloat, GLfloat, GLfloat) type Vertice = (GLfloat, GLfloat) type Damage = Int type Life = Int type Objeto = (String, Damage, Cor) vertice :: GLfloat -> GLfloat -> Vertice vertice x y = (x, y) cor :: GLfloat -> GLfloat -> GLfloat -> Cor cor r g b = (r, g, b) objetos :: [Objeto] objetos = [ ("Ground", 0, (0.625,0.269, 0.07)), ("ThornTrap", 15, (0.542, 0, 0)), ("ArrowTrap", 25, (0,1,0)), ("FireTrap", 40, (0,0,1)), ("Hole", 60, (1,1,0)) ] getObjetos:: [[Int]] -> [[Objeto]] getObjetos [] = [] getObjetos (linha:ls) = [objetos!!c | c <- linha ] : getObjetos ls
jailson-dias/Arca
src/Environment.hs
Haskell
bsd-3-clause
907
{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, StandaloneDeriving, TypeSynonymInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Atomo.Pretty (Pretty(..), Prettied) where import Data.Char (isUpper) import Data.IORef import Data.Maybe (isNothing) import Data.Ratio import Data.Typeable import System.IO.Unsafe import Text.PrettyPrint hiding (braces) import qualified Data.Vector as V import Atomo.Method import Atomo.Types hiding (keyword) import Atomo.Lexer.Base (isOperator, Token(..), TaggedToken(..)) data Context = CNone | CDefine | CKeyword | CSingle | CArgs | CPattern | CList type Prettied = Doc deriving instance Typeable Prettied class Pretty a where -- | Pretty-print a value into a Doc. Typically this should be parseable -- back into the original value, or just a nice user-friendly output form. pretty :: a -> Prettied prettyFrom :: Context -> a -> Prettied pretty = prettyFrom CNone instance Pretty Value where prettyFrom _ (Block _ ps es) | null ps = braces exprs | otherwise = braces $ sep (map (prettyFrom CArgs) ps) <+> char '|' <+> exprs where exprs = sep . punctuate (text ";") $ map pretty es prettyFrom _ (Boolean b) = text $ show b prettyFrom _ (Character c) = char '$' <> (text . tail . init $ show c) prettyFrom _ (Continuation _) = internal "continuation" empty prettyFrom _ (Double d) = double d prettyFrom _ (Expression e) = char '\'' <> parens (pretty e) prettyFrom _ (Haskell v) = internal "haskell" $ text (show v) prettyFrom _ (Integer i) = integer i prettyFrom _ (List l) = brackets . hsep . punctuate comma $ map (prettyFrom CList) vs where vs = V.toList l prettyFrom _ (Tuple l) = parens . hsep . punctuate comma $ map (prettyFrom CList) vs where vs = V.toList l prettyFrom _ (Message m) = internal "message" $ pretty m prettyFrom _ (Method (Slot p _)) = internal "slot" $ parens (pretty p) prettyFrom _ (Method (Responder p _ _)) = internal "responder" $ parens (pretty p) prettyFrom _ (Method (Macro p _)) = internal "macro" $ parens (pretty p) prettyFrom _ (Particle p) = char '@' <> pretty p prettyFrom _ (Pattern p) = internal "pattern" $ pretty p prettyFrom _ (Process _ tid) = internal "process" $ text (words (show tid) !! 1) prettyFrom CNone (Object { oDelegates = ds, oMethods = ms }) = internal "object" (parens (text "delegates to" <+> pretty ds)) $$ nest 2 (pretty ms) prettyFrom _ (Rational r) = integer (numerator r) <> char '/' <> integer (denominator r) prettyFrom _ (Object {}) = internal "object" empty prettyFrom _ (String s) = text (show s) prettyFrom _ (Regexp _ s o _) = text "r{" <> text (macroEscape s) <> char '}' <> text o instance Pretty Methods where prettyFrom _ ms = vcat [ if not (nullMap ss) then vcat (map (vcat . map prettyMethod) (elemsMap ss)) <> if not (nullMap ks) then char '\n' else empty else empty , if not (nullMap ks) then vcat $ flip map (elemsMap ks) $ \ps -> vcat (map prettyMethod ps) <> char '\n' else empty ] where (ss, ks) = unsafePerformIO (readIORef ms) prettyMethod (Slot { mPattern = p, mValue = v }) = prettyFrom CDefine p <+> text ":=" <++> prettyFrom CDefine v prettyMethod (Responder { mPattern = p, mExpr = e }) = prettyFrom CDefine p <+> text ":=" <++> prettyFrom CDefine e prettyMethod (Macro { mPattern = p, mExpr = e }) = text "macro" <+> parens (pretty p) <++> prettyFrom CDefine e instance Pretty Pattern where prettyFrom _ PAny = text "_" prettyFrom _ (PHeadTail h t) = parens $ pretty h <+> text "." <+> pretty t prettyFrom c (PMessage m) = prettyFrom c m prettyFrom _ (PList ps) = brackets . sep $ punctuate comma (map (prettyFrom CList) ps) prettyFrom _ (PTuple ps) = parens . sep $ punctuate comma (map (prettyFrom CList) ps) prettyFrom _ (PMatch v) = prettyFrom CPattern v prettyFrom _ (PNamed n PAny) = text n prettyFrom _ (PNamed n p) = parens $ text n <> colon <+> pretty p prettyFrom _ (PObject e@(EDispatch { eMessage = msg })) | capitalized msg = pretty e | isParticular msg = pretty block where capitalized (Single { mName = n, mTarget = ETop {} }) = isUpper (head n) capitalized (Single { mTarget = EDispatch { eMessage = t@(Single {}) } }) = capitalized t capitalized _ = False isParticular (Keyword { mNames = ["call-in"], mTargets = [EBlock {}, ETop {}] }) = True isParticular _ = False block = head (mTargets msg) prettyFrom _ (PObject e) = parens $ pretty e prettyFrom _ (PInstance p) = parens $ text "->" <+> pretty p prettyFrom _ (PStrict p) = parens $ text "==" <+> pretty p prettyFrom _ (PVariable p) = parens $ text "..." <+> pretty p prettyFrom _ (PPMKeyword ns ps) | all isAny ps = char '@' <> text (concatMap keyword ns) | isAny (head ps) = char '@' <> parens (headlessKeywords ns (tail ps)) | otherwise = char '@' <> parens (keywords ns ps) where isAny PAny = True isAny _ = False prettyFrom _ (PExpr e) = pretty (EQuote Nothing e) prettyFrom _ PThis = text "<this>" prettyFrom _ PEDispatch = text "Dispatch" prettyFrom _ PEOperator = text "Operator" prettyFrom _ PEPrimitive = text "Primitive" prettyFrom _ PEBlock = text "Block" prettyFrom _ PEList = text "List" prettyFrom _ PETuple = text "Tuple" prettyFrom _ PEMacro = text "Macro" prettyFrom _ PEForMacro = text "ForMacro" prettyFrom _ PEParticle = text "Particle" prettyFrom _ PETop = text "Top" prettyFrom _ PEQuote = text "Quote" prettyFrom _ PEUnquote = text "Unquote" prettyFrom _ PEMacroQuote = text "MacroQuote" prettyFrom _ PEMatch = text "Match" instance Pretty Expr where prettyFrom _ (EDefine _ p v) = prettyFrom CDefine p <+> text ":=" <++> prettyFrom CDefine v prettyFrom _ (ESet _ p v) = prettyFrom CDefine p <+> text "=" <++> prettyFrom CDefine v prettyFrom CKeyword (EDispatch _ m@(Keyword {})) = parens $ pretty m prettyFrom CSingle (EDispatch _ m@(Keyword {})) = parens $ pretty m prettyFrom c (EDispatch _ m) = prettyFrom c m prettyFrom _ (EOperator _ ns a i) = text "operator" <+> assoc a <+> integer i <+> sep (map text ns) where assoc ALeft = text "left" assoc ARight = text "right" prettyFrom c (EPrimitive _ v) = prettyFrom c v prettyFrom _ (EBlock _ ps es) | null ps = braces exprs | otherwise = braces $ sep (map pretty ps) <+> char '|' <+> exprs where exprs = sep . punctuate (text ";") $ map pretty es prettyFrom CDefine (EVM {}) = text "..." prettyFrom _ (EVM {}) = text "<vm>" prettyFrom _ (EList _ es) = brackets . sep . punctuate comma $ map (prettyFrom CList) es prettyFrom _ (ETuple _ es) = parens . sep . punctuate comma $ map (prettyFrom CList) es prettyFrom _ (EMacro _ p e) = text "macro" <+> parens (pretty p) <++> pretty e prettyFrom _ (EForMacro { eExpr = e }) = text "for-macro" <+> pretty e prettyFrom c (EParticle _ p) = char '@' <> prettyFrom c p prettyFrom _ (ETop {}) = text "this" prettyFrom c (EQuote _ e) = char '`' <> prettySpacedExpr c e prettyFrom c (EUnquote _ e) = char '~' <> prettySpacedExpr c e prettyFrom _ (ENewDynamic {}) = internal "new-dynamic" empty prettyFrom _ (EDefineDynamic { eName = n, eExpr = e }) = internal "define-dynamic" $ text n <+> pretty e prettyFrom _ (ESetDynamic { eName = n, eExpr = e }) = internal "set-dynamic" $ text n <+> pretty e prettyFrom _ (EGetDynamic { eName = n }) = internal "get-dynamic" $ text n prettyFrom _ (EMacroQuote _ n r f) = text n <> char '{' <> text (macroEscape r) <> char '}' <> text f prettyFrom _ (EMatch _ t bs) = prettyFrom CKeyword t <+> text "match:" <+> branches where branches = braces . sep . punctuate (text ";") $ flip map bs $ \(p, e) -> pretty p <+> text "->" <+> pretty e instance Pretty [Expr] where prettyFrom _ es = sep . punctuate (text ";") $ map pretty es instance Pretty x => Pretty (Option x) where prettyFrom _ (Option _ n x) = char '&' <> text n <> char ':' <+> pretty x instance Pretty (Message Pattern) where prettyFrom _ (Single { mName = n, mTarget = PThis, mOptionals = os }) = text n <+> sep (map pretty os) prettyFrom _ (Single { mName = n, mTarget = (PObject ETop {}), mOptionals = os }) = text n <+> sep (map pretty os) prettyFrom _ (Single { mName = n, mTarget = p, mOptionals = os }) = pretty p <+> text n <+> sep (map pretty os) prettyFrom _ (Keyword { mNames = ns, mTargets = (PThis:vs), mOptionals = os }) = headlessKeywords ns vs <+> sep (map pretty os) prettyFrom _ (Keyword { mNames = ns, mTargets = (PObject ETop {}:vs), mOptionals = os }) = headlessKeywords ns vs <+> sep (map pretty os) prettyFrom _ (Keyword { mNames = ns, mTargets = vs, mOptionals = os }) = keywords ns vs <+> sep (map pretty os) instance Pretty (Message Value) where prettyFrom _ (Single { mName = n, mTarget = t, mOptionals = os }) = prettyFrom CSingle t <+> text n <+> sep (map pretty os) prettyFrom _ (Keyword { mNames = ns, mTargets = vs, mOptionals = os }) = keywords ns vs <+> sep (map pretty os) instance Pretty (Message Expr) where prettyFrom _ (Single { mName = n, mTarget = ETop {}, mOptionals = os }) = text n <+> sep (map pretty os) prettyFrom _ (Single { mName = n, mTarget = t, mOptionals = os }) = prettyFrom CSingle t <+> text n <+> sep (map pretty os) prettyFrom _ (Keyword { mNames = ns, mTargets = (ETop {}:es), mOptionals = os }) = headlessKeywords ns es <+> sep (map pretty os) prettyFrom _ (Keyword { mNames = ns, mTargets = es, mOptionals = os }) = keywords ns es <+> sep (map pretty os) instance Pretty x => Pretty (Particle x) where prettyFrom _ (Single { mName = n, mTarget = Nothing, mOptionals = [] }) = text n prettyFrom _ (Single { mName = n, mTarget = Nothing, mOptionals = os }) = parens (text n <+> sep (map pretty os)) prettyFrom _ (Single { mName = n, mTarget = Just t, mOptionals = os }) = parens (pretty t <+> text n <+> sep (map pretty os)) prettyFrom _ (Keyword { mNames = ns, mTargets = vs, mOptionals = os }) | all isNothing vs && null os = text . concat $ map keyword ns | isNothing (head vs) = parens $ headlessKeywords ns (tail vs) <+> sep (map pretty os) | otherwise = parens $ keywords ns vs <+> sep (map pretty os) instance Pretty x => Pretty (Maybe x) where prettyFrom _ Nothing = text "_" prettyFrom c (Just v) = prettyFrom c v instance Pretty Delegates where prettyFrom _ [] = internal "bottom" empty prettyFrom _ [_] = text "1 object" prettyFrom _ ds = text $ show (length ds) ++ " objects" instance Pretty Token where prettyFrom _ (TokKeyword k) = text k <> char ':' prettyFrom _ (TokOptional o) = char '&' <> text o <> char ':' prettyFrom _ (TokOptionalFlag o) = char '&' <> text o prettyFrom _ (TokOperator o) = text o prettyFrom _ (TokMacroQuote n r f) = text n <> char '{' <> text (macroEscape r) <> char '}' <> text f prettyFrom _ (TokIdentifier i) = text i prettyFrom _ (TokParticle ks) = char '@' <> hcat (map (text . keyword) ks) prettyFrom _ (TokPrimitive p) = pretty p prettyFrom _ (TokPunctuation c) = char c prettyFrom _ (TokOpen c) = char c prettyFrom _ (TokClose c) = char c prettyFrom _ (TokReserved r) = text r prettyFrom _ TokEnd = char ';' instance Pretty TaggedToken where prettyFrom c tt = prettyFrom c (tToken tt) type Tokens = [TaggedToken] instance Pretty Tokens where prettyFrom _ ts = hsep (map pretty ts) instance Pretty AtomoError where prettyFrom _ (Error v) = text "error:" <+> pretty v prettyFrom _ (ParseError e) = text "parse error:" <+> text (show e) prettyFrom _ (DidNotUnderstand m) = text "message not understood:" <+> pretty m prettyFrom _ (Mismatch a b) = text "mismatch:" $$ nest 2 (pretty a $$ pretty b) prettyFrom _ (ImportError e) = text "haskell interpreter:" <+> text (show e) prettyFrom _ (FileNotFound fn) = text "file not found:" <+> text fn prettyFrom _ (ParticleArity e g) = text ("particle needed " ++ show e ++ " values to complete, given " ++ show g) prettyFrom _ (BlockArity e g) = text ("block expected " ++ show e ++ " arguments, given " ++ show g) prettyFrom _ NoExpressions = text "no expressions to evaluate" prettyFrom _ (ValueNotFound d v) = text "could not find a" <+> text d <+> text "in" <+> pretty v prettyFrom _ (DynamicNeeded t) = text "expected dynamic value of type" <+> text t internal :: String -> Doc -> Doc internal n d = char '<' <> text n <+> d <> char '>' braces :: Doc -> Doc braces d = char '{' <+> d <+> char '}' macroEscape :: String -> String macroEscape "" = "" macroEscape ('{':cs) = "\\{" ++ macroEscape cs macroEscape ('}':cs) = "\\}" ++ macroEscape cs macroEscape (c:cs) = c : macroEscape cs headlessKeywords' :: (a -> Doc) -> [String] -> [a] -> Doc headlessKeywords' p (k:ks) (v:vs) = text (keyword k) <+> p v <++> headlessKeywords'' p ks vs headlessKeywords' _ _ _ = empty headlessKeywords'' :: (a -> Doc) -> [String] -> [a] -> Doc headlessKeywords'' p (k:ks) (v:vs) = text (keyword k) <+> p v <+++> headlessKeywords'' p ks vs headlessKeywords'' _ _ _ = empty keywords' :: (a -> Doc) -> [String] -> [a] -> Doc keywords' p ks (v:vs) = p v <+> headlessKeywords' p ks vs keywords' _ _ _ = empty headlessKeywords :: Pretty a => [String] -> [a] -> Doc headlessKeywords = headlessKeywords' (prettyFrom CKeyword) keywords :: Pretty a => [String] -> [a] -> Doc keywords = keywords' (prettyFrom CKeyword) keyword :: String -> String keyword k | isOperator k = k | otherwise = k ++ ":" prettySpacedExpr :: Context -> Expr -> Doc prettySpacedExpr c e | needsParens e = parens (prettyFrom c e) | otherwise = prettyFrom c e where needsParens (EDefine {}) = True needsParens (ESet {}) = True needsParens (EDispatch { eMessage = Keyword {} }) = True needsParens (EDispatch { eMessage = Single { mTarget = ETop {} } }) = False needsParens (EDispatch { eMessage = Single {} }) = True needsParens _ = False infixr 4 <++>, <+++> -- similar to <+>, but the second half will be nested to prevent long lines (<++>) :: Doc -> Doc -> Doc (<++>) a b | length (show a ++ show b) > 80 = a $$ nest 2 b | otherwise = a <+> b -- similar to <++>, but without nesting (<+++>) :: Doc -> Doc -> Doc (<+++>) a b | length (show a ++ show b) > 80 = a $$ b | otherwise = a <+> b
vito/atomo
src/Atomo/Pretty.hs
Haskell
bsd-3-clause
15,361
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. module Duckling.Temperature.JA.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Temperature.JA.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "JA Tests" [ makeCorpusTest [This Temperature] corpus ]
rfranek/duckling
tests/Duckling/Temperature/JA/Tests.hs
Haskell
bsd-3-clause
612
{-# LANGUAGE DeriveDataTypeable #-} module Sgf.XMonad.Restartable.Firefox ( FirefoxProfile (..) , FirefoxArgs , firefoxProfile , firefoxNoRemote , firefoxNewInstance , Firefox , defaultFirefox ) where import Data.Typeable import Data.Function (on) import Sgf.Data.List import Sgf.Control.Lens import Sgf.XMonad.Restartable data FirefoxProfile = FfProfileManager | FfProfile String deriving (Show, Read, Typeable, Eq) data FirefoxArgs = FirefoxArgs { _firefoxProfile :: FirefoxProfile , _firefoxNoRemote :: Bool , _firefoxNewInstance :: Bool } deriving (Show, Read, Typeable) firefoxProfile :: LensA FirefoxArgs FirefoxProfile firefoxProfile f z@FirefoxArgs {_firefoxProfile = x} = fmap (\x' -> z{_firefoxProfile = x'}) (f x) firefoxNoRemote :: LensA FirefoxArgs Bool firefoxNoRemote f z@FirefoxArgs {_firefoxNoRemote = x} = fmap (\x' -> z{_firefoxNoRemote = x'}) (f x) firefoxNewInstance :: LensA FirefoxArgs Bool firefoxNewInstance f z@FirefoxArgs {_firefoxNewInstance = x} = fmap (\x' -> z{_firefoxNewInstance = x'}) (f x) instance Eq FirefoxArgs where (==) = (==) `on` viewA firefoxProfile instance Arguments FirefoxArgs where serialize x = do let xr = viewA firefoxNoRemote x xi = viewA firefoxNewInstance x xp = case (viewA firefoxProfile x) of FfProfile p -> unless' (null p) ["-P", p] FfProfileManager -> ["-ProfileManager"] fmap concat . sequence $ [ return xp , when' xr (return ["--no-remote"]) , when' xi (return ["--new-instance"]) ] defaultArgs = FirefoxArgs { _firefoxProfile = FfProfile "default" , _firefoxNoRemote = False , _firefoxNewInstance = True } type Firefox = Program FirefoxArgs defaultFirefox :: Firefox defaultFirefox = setA progBin "firefox" defaultProgram
sgf-dma/sgf-xmonad-modules
src/Sgf/XMonad/Restartable/Firefox.hs
Haskell
bsd-3-clause
2,369
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-} module Commi.Task where import Haste.Serialize import Haste.JSON import Data.Typeable import Data.Maybe import Control.Applicative import Genetic.Options data Input = Input { inputCityMatrix :: [[Int]] , inputCityN :: Int , inputIndividLength :: Int , inputGeneticOptions :: GeneticOptions } deriving (Typeable, Show) instance Serialize Input where toJSON i = Dict [ ("inputCityMatrix", toJSON $ inputCityMatrix i) , ("inputCityN", toJSON $ inputCityN i) , ("inputIndividLength", toJSON $ inputIndividLength i) , ("inputGeneticOptions", toJSON $ inputGeneticOptions i) ] parseJSON j = Input <$> j .: "inputCityMatrix" <*> j .: "inputCityN" <*> j .: "inputIndividLength" <*> j .: "inputGeneticOptions" initialInput :: Input initialInput = Input { inputCityMatrix = [[-1000, -5, -10, -30, -25, -40, -15, -10, -25, -5, -15, -10], [-5, -1000, -20, -40, -18, -20, -30, -5, -15, -10, -25, -15], [-10, -20, -1000, -15, -40, -15, -5, -15, -5, -40, -20, -40], [-30, -40, -15, -1000, -15, -35, -25, -50, -10, -25, -5, -30], [-25, -18, -40, -15, -1000, -25, -10, -20, -15, -50, -10, -25], [-40, -20, -15, -35, -25, -1000, -5, -30, -30, -70, -5, -35], [-15, -30, -5, -25, -10, -5, -1000, -10, -20, -15, -30, -5], [-10, -5, -15, -50, -20, -30, -10, -1000, -25, -30, -40, -5], [-25, -15, -5, -10, -15, -30, -20, -25, -1000, -15, -10, -18], [-5, -10, -40, -25, -50, -70, -15, -30, -15, -1000, -20, -20], [-15, -25, -20, -5, -10, -5, -30, -40, -10, -20, -1000, -5], [-10, -15, -40, -30, -25, -35, -5, -5, -18, -20, -5, -1000]] , inputGeneticOptions = initialOptions , inputCityN = 2 , inputIndividLength = 5 } data Output = Output { outputSolution :: [Int], outputCost :: Int, outputFitness :: Double } deriving (Typeable, Show) data PlotState = PlotState{ values :: [(Double, Double)] -- ^ Points: x - generation number, y - fitness value } deriving (Typeable, Show) initialPlotState :: PlotState initialPlotState = PlotState []
Teaspot-Studio/bmstu-commi-genetics-haste
Commi/Task.hs
Haskell
bsd-3-clause
2,431
----------------------------------------------------------------------------- -- | -- Module : Language.C.Syntax.ParserMonad -- Copyright : (c) [1999..2004] Manuel M T Chakravarty -- (c) 2005-2007 Duncan Coutts -- License : BSD-style -- Maintainer : benedikt.huber@gmail.com -- Portability : portable -- -- Monad for the C lexer and parser -- -- This monad has to be usable with Alex and Happy. Some things in it are -- dictated by that, eg having to be able to remember the last token. -- -- The monad also provides a unique name supply (via the Name module) -- -- For parsing C we have to maintain a set of identifiers that we know to be -- typedef'ed type identifiers. We also must deal correctly with scope so we -- keep a list of sets of identifiers so we can save the outer scope when we -- enter an inner scope. module Language.C.Parser.ParserMonad ( P, execParser, failP, getNewName, -- :: P Name addTypedef, -- :: Ident -> P () shadowTypedef, -- :: Ident -> P () isTypeIdent, -- :: Ident -> P Bool enterScope, -- :: P () leaveScope, -- :: P () setPos, -- :: Position -> P () getPos, -- :: P Position getInput, -- :: P String setInput, -- :: String -> P () getLastToken, -- :: P CToken getSavedToken, -- :: P CToken setLastToken, -- :: CToken -> P () handleEofToken, -- :: P () getCurrentPosition,-- :: P Position ParseError(..), ) where import Language.C.Data.Error (internalErr, showErrorInfo,ErrorInfo(..),ErrorLevel(..)) import Language.C.Data.Position (Position(..)) import Language.C.Data.InputStream import Language.C.Data.Name (Name) import Language.C.Data.Ident (Ident) import Language.C.Parser.Tokens (CToken(CTokEof)) import Control.Applicative (Applicative(..)) import Control.Monad (liftM, ap) import Data.Set (Set) import qualified Data.Set as Set (fromList, insert, member, delete) newtype ParseError = ParseError ([String],Position) instance Show ParseError where show (ParseError (msgs,pos)) = showErrorInfo "Syntax Error !" (ErrorInfo LevelError pos msgs) data ParseResult a = POk !PState a | PFailed [String] Position -- The error message and position data PState = PState { curPos :: !Position, -- position at current input location curInput :: !InputStream, -- the current input prevToken :: CToken, -- the previous token savedToken :: CToken, -- and the token before that namesupply :: ![Name], -- the name unique supply tyidents :: !(Set Ident), -- the set of typedef'ed identifiers scopes :: ![Set Ident] -- the tyident sets for outer scopes } newtype P a = P { unP :: PState -> ParseResult a } instance Functor P where fmap = liftM instance Applicative P where pure = return (<*>) = ap instance Monad P where return = returnP (>>=) = thenP fail m = getPos >>= \pos -> failP pos [m] -- | execute the given parser on the supplied input stream. -- returns 'ParseError' if the parser failed, and a pair of -- result and remaining name supply otherwise -- -- Synopsis: @execParser parser inputStream initialPos predefinedTypedefs uniqNameSupply@ execParser :: P a -> InputStream -> Position -> [Ident] -> [Name] -> Either ParseError (a,[Name]) execParser (P parser) input pos builtins names = case parser initialState of PFailed message errpos -> Left (ParseError (message,errpos)) POk st result -> Right (result, namesupply st) where initialState = PState { curPos = pos, curInput = input, prevToken = internalErr "CLexer.execParser: Touched undefined token!", savedToken = internalErr "CLexer.execParser: Touched undefined token (safed token)!", namesupply = names, tyidents = Set.fromList builtins, scopes = [] } {-# INLINE returnP #-} returnP :: a -> P a returnP a = P $ \s -> POk s a {-# INLINE thenP #-} thenP :: P a -> (a -> P b) -> P b (P m) `thenP` k = P $ \s -> case m s of POk s' a -> (unP (k a)) s' PFailed err pos -> PFailed err pos failP :: Position -> [String] -> P a failP pos msg = P $ \_ -> PFailed msg pos getNewName :: P Name getNewName = P $ \s@PState{namesupply=(n:ns)} -> n `seq` POk s{namesupply=ns} n setPos :: Position -> P () setPos pos = P $ \s -> POk s{curPos=pos} () getPos :: P Position getPos = P $ \s@PState{curPos=pos} -> POk s pos addTypedef :: Ident -> P () addTypedef ident = (P $ \s@PState{tyidents=tyids} -> POk s{tyidents = ident `Set.insert` tyids} ()) shadowTypedef :: Ident -> P () shadowTypedef ident = (P $ \s@PState{tyidents=tyids} -> -- optimisation: mostly the ident will not be in -- the tyident set so do a member lookup to avoid -- churn induced by calling delete POk s{tyidents = if ident `Set.member` tyids then ident `Set.delete` tyids else tyids } ()) isTypeIdent :: Ident -> P Bool isTypeIdent ident = P $ \s@PState{tyidents=tyids} -> POk s $! Set.member ident tyids enterScope :: P () enterScope = P $ \s@PState{tyidents=tyids,scopes=ss} -> POk s{scopes=tyids:ss} () leaveScope :: P () leaveScope = P $ \s@PState{scopes=ss} -> case ss of [] -> error "leaveScope: already in global scope" (tyids:ss') -> POk s{tyidents=tyids, scopes=ss'} () getInput :: P InputStream getInput = P $ \s@PState{curInput=i} -> POk s i setInput :: InputStream -> P () setInput i = P $ \s -> POk s{curInput=i} () getLastToken :: P CToken getLastToken = P $ \s@PState{prevToken=tok} -> POk s tok getSavedToken :: P CToken getSavedToken = P $ \s@PState{savedToken=tok} -> POk s tok -- | @setLastToken modifyCache tok@ setLastToken :: CToken -> P () setLastToken CTokEof = P $ \s -> POk s{savedToken=(prevToken s)} () setLastToken tok = P $ \s -> POk s{prevToken=tok,savedToken=(prevToken s)} () -- | handle an End-Of-File token (changes savedToken) handleEofToken :: P () handleEofToken = P $ \s -> POk s{savedToken=(prevToken s)} () getCurrentPosition :: P Position getCurrentPosition = P $ \s@PState{curPos=pos} -> POk s pos
ian-ross/language-c
src/Language/C/Parser/ParserMonad.hs
Haskell
bsd-3-clause
6,570
{-# LANGUAGE RebindableSyntax #-} {-# LANGUAGE ViewPatterns #-} module Init where import Options import Type import Data.Array.Accelerate as A hiding ( fromInteger, V3 ) import Data.Array.Accelerate.Linear as A import Prelude ( fromInteger ) import qualified Prelude as P -- | Deposit some energy at the origin. The simulation is symmetric so we only -- simulate one quadrant, being sure to maintain the boundary conditions. -- initEnergy :: Int -> Acc (Field Energy) initEnergy numElem = let sh = constant (Z :. numElem :. numElem :. numElem) f :: Exp Ix -> Exp Energy f (unlift -> Z :. z :. y :. x) = if z == 0 && y == 0 && x == 0 then 3.948746e+7 else 0 in A.generate sh f -- | Initialise the nodal coordinates to a regular hexahedron mesh. The -- coordinates of the mesh nodes will change as the simulation progresses. -- -- We don't need the nodal point lattice to record the indices of our neighbours -- because we have native multidimensional arrays. -- initMesh :: Int -> Acc (Field Position) initMesh numElem = let numNode = numElem + 1 sh = constant (Z :. numNode :. numNode :. numNode) n = P.fromIntegral numElem f :: Exp Ix -> Exp Position f (unlift -> Z :. k :. j :. i) = let x = _WIDTH * A.fromIntegral i / n y = _HEIGHT * A.fromIntegral j / n z = _DEPTH * A.fromIntegral k / n in lift (V3 x y z) in A.generate sh f -- | Initialise the volume of each element. -- -- Since we begin with a regular hexahedral mesh we just compute the volume -- directly and initialise all elements to that value. -- initElemVolume :: Int -> Acc (Field Volume) initElemVolume numElem = let sh = constant (Z :. numElem :. numElem :. numElem) w = _WIDTH / P.fromIntegral numElem h = _HEIGHT / P.fromIntegral numElem d = _DEPTH / P.fromIntegral numElem v = w * h * d in A.fill sh v -- | Initialise the mass at each node. This is the average of the contribution -- of each of the surrounding elements. -- -- Again, since we begin with a regular mesh, we just compute this value -- directly, but we could equivalently read from the array of element volumes. -- initNodeMass :: Int -> Acc (Field Mass) initNodeMass numElem = let numNode = numElem + 1 sh = constant (Z :. numNode :. numNode :. numNode) w = _WIDTH / P.fromIntegral numElem h = _HEIGHT / P.fromIntegral numElem d = _DEPTH / P.fromIntegral numElem v = w * h * d at z y x = if 0 <= z && z < constant numElem && 0 <= y && y < constant numElem && 0 <= x && x < constant numElem then v else 0 -- This corresponds to the node -> surrounding elements index mapping neighbours :: Exp Ix -> Exp Mass neighbours (unlift -> Z :. z :. y :. x) = ( at z y x + at z y (x-1) + at z (y-1) (x-1) + at z (y-1) x + at (z-1) y x + at (z-1) y (x-1) + at (z-1) (y-1) (x-1) + at (z-1) (y-1) x ) / 8 in generate sh neighbours
tmcdonell/accelerate-lulesh
src/Init.hs
Haskell
bsd-3-clause
3,314
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 This module defines interface types and binders -} {-# LANGUAGE CPP, FlexibleInstances, BangPatterns #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE LambdaCase #-} -- FlexibleInstances for Binary (DefMethSpec IfaceType) module GHC.Iface.Type ( IfExtName, IfLclName, IfaceType(..), IfacePredType, IfaceKind, IfaceCoercion(..), IfaceMCoercion(..), IfaceUnivCoProv(..), IfaceTyCon(..), IfaceTyConInfo(..), IfaceTyConSort(..), IfaceTyLit(..), IfaceAppArgs(..), IfaceContext, IfaceBndr(..), IfaceOneShot(..), IfaceLamBndr, IfaceTvBndr, IfaceIdBndr, IfaceTyConBinder, IfaceForAllBndr, ArgFlag(..), AnonArgFlag(..), ForallVisFlag(..), ShowForAllFlag(..), mkIfaceForAllTvBndr, mkIfaceTyConKind, ifForAllBndrVar, ifForAllBndrName, ifaceBndrName, ifTyConBinderVar, ifTyConBinderName, -- Equality testing isIfaceLiftedTypeKind, -- Conversion from IfaceAppArgs to IfaceTypes/ArgFlags appArgsIfaceTypes, appArgsIfaceTypesArgFlags, -- Printing SuppressBndrSig(..), UseBndrParens(..), pprIfaceType, pprParendIfaceType, pprPrecIfaceType, pprIfaceContext, pprIfaceContextArr, pprIfaceIdBndr, pprIfaceLamBndr, pprIfaceTvBndr, pprIfaceTyConBinders, pprIfaceBndrs, pprIfaceAppArgs, pprParendIfaceAppArgs, pprIfaceForAllPart, pprIfaceForAllPartMust, pprIfaceForAll, pprIfaceSigmaType, pprIfaceTyLit, pprIfaceCoercion, pprParendIfaceCoercion, splitIfaceSigmaTy, pprIfaceTypeApp, pprUserIfaceForAll, pprIfaceCoTcApp, pprTyTcApp, pprIfacePrefixApp, isIfaceTauType, suppressIfaceInvisibles, stripIfaceInvisVars, stripInvisArgs, mkIfaceTySubst, substIfaceTyVar, substIfaceAppArgs, inDomIfaceTySubst ) where #include "HsVersions.h" import GhcPrelude import {-# SOURCE #-} TysWiredIn ( coercibleTyCon, heqTyCon , liftedRepDataConTyCon, tupleTyConName ) import {-# SOURCE #-} Type ( isRuntimeRepTy ) import DynFlags import TyCon hiding ( pprPromotionQuote ) import CoAxiom import Var import PrelNames import Name import BasicTypes import Binary import Outputable import FastString import FastStringEnv import Util import Data.Maybe( isJust ) import qualified Data.Semigroup as Semi import Control.DeepSeq {- ************************************************************************ * * Local (nested) binders * * ************************************************************************ -} type IfLclName = FastString -- A local name in iface syntax type IfExtName = Name -- An External or WiredIn Name can appear in Iface syntax -- (However Internal or System Names never should) data IfaceBndr -- Local (non-top-level) binders = IfaceIdBndr {-# UNPACK #-} !IfaceIdBndr | IfaceTvBndr {-# UNPACK #-} !IfaceTvBndr type IfaceIdBndr = (IfLclName, IfaceType) type IfaceTvBndr = (IfLclName, IfaceKind) ifaceTvBndrName :: IfaceTvBndr -> IfLclName ifaceTvBndrName (n,_) = n ifaceIdBndrName :: IfaceIdBndr -> IfLclName ifaceIdBndrName (n,_) = n ifaceBndrName :: IfaceBndr -> IfLclName ifaceBndrName (IfaceTvBndr bndr) = ifaceTvBndrName bndr ifaceBndrName (IfaceIdBndr bndr) = ifaceIdBndrName bndr ifaceBndrType :: IfaceBndr -> IfaceType ifaceBndrType (IfaceIdBndr (_, t)) = t ifaceBndrType (IfaceTvBndr (_, t)) = t type IfaceLamBndr = (IfaceBndr, IfaceOneShot) data IfaceOneShot -- See Note [Preserve OneShotInfo] in CoreTicy = IfaceNoOneShot -- and Note [The oneShot function] in MkId | IfaceOneShot {- %************************************************************************ %* * IfaceType %* * %************************************************************************ -} ------------------------------- type IfaceKind = IfaceType -- | A kind of universal type, used for types and kinds. -- -- Any time a 'Type' is pretty-printed, it is first converted to an 'IfaceType' -- before being printed. See Note [Pretty printing via Iface syntax] in PprTyThing data IfaceType = IfaceFreeTyVar TyVar -- See Note [Free tyvars in IfaceType] | IfaceTyVar IfLclName -- Type/coercion variable only, not tycon | IfaceLitTy IfaceTyLit | IfaceAppTy IfaceType IfaceAppArgs -- See Note [Suppressing invisible arguments] for -- an explanation of why the second field isn't -- IfaceType, analogous to AppTy. | IfaceFunTy AnonArgFlag IfaceType IfaceType | IfaceForAllTy IfaceForAllBndr IfaceType | IfaceTyConApp IfaceTyCon IfaceAppArgs -- Not necessarily saturated -- Includes newtypes, synonyms, tuples | IfaceCastTy IfaceType IfaceCoercion | IfaceCoercionTy IfaceCoercion | IfaceTupleTy -- Saturated tuples (unsaturated ones use IfaceTyConApp) TupleSort -- What sort of tuple? PromotionFlag -- A bit like IfaceTyCon IfaceAppArgs -- arity = length args -- For promoted data cons, the kind args are omitted type IfacePredType = IfaceType type IfaceContext = [IfacePredType] data IfaceTyLit = IfaceNumTyLit Integer | IfaceStrTyLit FastString deriving (Eq) type IfaceTyConBinder = VarBndr IfaceBndr TyConBndrVis type IfaceForAllBndr = VarBndr IfaceBndr ArgFlag -- | Make an 'IfaceForAllBndr' from an 'IfaceTvBndr'. mkIfaceForAllTvBndr :: ArgFlag -> IfaceTvBndr -> IfaceForAllBndr mkIfaceForAllTvBndr vis var = Bndr (IfaceTvBndr var) vis -- | Build the 'tyConKind' from the binders and the result kind. -- Keep in sync with 'mkTyConKind' in types/TyCon. mkIfaceTyConKind :: [IfaceTyConBinder] -> IfaceKind -> IfaceKind mkIfaceTyConKind bndrs res_kind = foldr mk res_kind bndrs where mk :: IfaceTyConBinder -> IfaceKind -> IfaceKind mk (Bndr tv (AnonTCB af)) k = IfaceFunTy af (ifaceBndrType tv) k mk (Bndr tv (NamedTCB vis)) k = IfaceForAllTy (Bndr tv vis) k -- | Stores the arguments in a type application as a list. -- See @Note [Suppressing invisible arguments]@. data IfaceAppArgs = IA_Nil | IA_Arg IfaceType -- The type argument ArgFlag -- The argument's visibility. We store this here so -- that we can: -- -- 1. Avoid pretty-printing invisible (i.e., specified -- or inferred) arguments when -- -fprint-explicit-kinds isn't enabled, or -- 2. When -fprint-explicit-kinds *is*, enabled, print -- specified arguments in @(...) and inferred -- arguments in @{...}. IfaceAppArgs -- The rest of the arguments instance Semi.Semigroup IfaceAppArgs where IA_Nil <> xs = xs IA_Arg ty argf rest <> xs = IA_Arg ty argf (rest Semi.<> xs) instance Monoid IfaceAppArgs where mempty = IA_Nil mappend = (Semi.<>) -- Encodes type constructors, kind constructors, -- coercion constructors, the lot. -- We have to tag them in order to pretty print them -- properly. data IfaceTyCon = IfaceTyCon { ifaceTyConName :: IfExtName , ifaceTyConInfo :: IfaceTyConInfo } deriving (Eq) -- | The various types of TyCons which have special, built-in syntax. data IfaceTyConSort = IfaceNormalTyCon -- ^ a regular tycon | IfaceTupleTyCon !Arity !TupleSort -- ^ e.g. @(a, b, c)@ or @(#a, b, c#)@. -- The arity is the tuple width, not the tycon arity -- (which is twice the width in the case of unboxed -- tuples). | IfaceSumTyCon !Arity -- ^ e.g. @(a | b | c)@ | IfaceEqualityTyCon -- ^ A heterogeneous equality TyCon -- (i.e. eqPrimTyCon, eqReprPrimTyCon, heqTyCon) -- that is actually being applied to two types -- of the same kind. This affects pretty-printing -- only: see Note [Equality predicates in IfaceType] deriving (Eq) {- Note [Free tyvars in IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Nowadays (since Nov 16, 2016) we pretty-print a Type by converting to an IfaceType and pretty printing that. This eliminates a lot of pretty-print duplication, and it matches what we do with pretty- printing TyThings. See Note [Pretty printing via Iface syntax] in PprTyThing. It works fine for closed types, but when printing debug traces (e.g. when using -ddump-tc-trace) we print a lot of /open/ types. These types are full of TcTyVars, and it's absolutely crucial to print them in their full glory, with their unique, TcTyVarDetails etc. So we simply embed a TyVar in IfaceType with the IfaceFreeTyVar constructor. Note that: * We never expect to serialise an IfaceFreeTyVar into an interface file, nor to deserialise one. IfaceFreeTyVar is used only in the "convert to IfaceType and then pretty-print" pipeline. We do the same for covars, naturally. Note [Equality predicates in IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GHC has several varieties of type equality (see Note [The equality types story] in TysPrim for details). In an effort to avoid confusing users, we suppress the differences during pretty printing unless certain flags are enabled. Here is how each equality predicate* is printed in homogeneous and heterogeneous contexts, depending on which combination of the -fprint-explicit-kinds and -fprint-equality-relations flags is used: -------------------------------------------------------------------------------------------- | Predicate | Neither flag | -fprint-explicit-kinds | |-------------------------------|----------------------------|-----------------------------| | a ~ b (homogeneous) | a ~ b | (a :: Type) ~ (b :: Type) | | a ~~ b, homogeneously | a ~ b | (a :: Type) ~ (b :: Type) | | a ~~ b, heterogeneously | a ~~ c | (a :: Type) ~~ (c :: k) | | a ~# b, homogeneously | a ~ b | (a :: Type) ~ (b :: Type) | | a ~# b, heterogeneously | a ~~ c | (a :: Type) ~~ (c :: k) | | Coercible a b (homogeneous) | Coercible a b | Coercible @Type a b | | a ~R# b, homogeneously | Coercible a b | Coercible @Type a b | | a ~R# b, heterogeneously | a ~R# b | (a :: Type) ~R# (c :: k) | |-------------------------------|----------------------------|-----------------------------| | Predicate | -fprint-equality-relations | Both flags | |-------------------------------|----------------------------|-----------------------------| | a ~ b (homogeneous) | a ~ b | (a :: Type) ~ (b :: Type) | | a ~~ b, homogeneously | a ~~ b | (a :: Type) ~~ (b :: Type) | | a ~~ b, heterogeneously | a ~~ c | (a :: Type) ~~ (c :: k) | | a ~# b, homogeneously | a ~# b | (a :: Type) ~# (b :: Type) | | a ~# b, heterogeneously | a ~# c | (a :: Type) ~# (c :: k) | | Coercible a b (homogeneous) | Coercible a b | Coercible @Type a b | | a ~R# b, homogeneously | a ~R# b | (a :: Type) ~R# (b :: Type) | | a ~R# b, heterogeneously | a ~R# b | (a :: Type) ~R# (c :: k) | -------------------------------------------------------------------------------------------- (* There is no heterogeneous, representational, lifted equality counterpart to (~~). There could be, but there seems to be no use for it.) This table adheres to the following rules: A. With -fprint-equality-relations, print the true equality relation. B. Without -fprint-equality-relations: i. If the equality is representational and homogeneous, use Coercible. ii. Otherwise, if the equality is representational, use ~R#. iii. If the equality is nominal and homogeneous, use ~. iv. Otherwise, if the equality is nominal, use ~~. C. With -fprint-explicit-kinds, print kinds on both sides of an infix operator, as above; or print the kind with Coercible. D. Without -fprint-explicit-kinds, don't print kinds. A hetero-kinded equality is used homogeneously when it is applied to two identical kinds. Unfortunately, determining this from an IfaceType isn't possible since we can't see through type synonyms. Consequently, we need to record whether this particular application is homogeneous in IfaceTyConSort for the purposes of pretty-printing. See Note [The equality types story] in TysPrim. -} data IfaceTyConInfo -- Used to guide pretty-printing -- and to disambiguate D from 'D (they share a name) = IfaceTyConInfo { ifaceTyConIsPromoted :: PromotionFlag , ifaceTyConSort :: IfaceTyConSort } deriving (Eq) data IfaceMCoercion = IfaceMRefl | IfaceMCo IfaceCoercion data IfaceCoercion = IfaceReflCo IfaceType | IfaceGReflCo Role IfaceType (IfaceMCoercion) | IfaceFunCo Role IfaceCoercion IfaceCoercion | IfaceTyConAppCo Role IfaceTyCon [IfaceCoercion] | IfaceAppCo IfaceCoercion IfaceCoercion | IfaceForAllCo IfaceBndr IfaceCoercion IfaceCoercion | IfaceCoVarCo IfLclName | IfaceAxiomInstCo IfExtName BranchIndex [IfaceCoercion] | IfaceAxiomRuleCo IfLclName [IfaceCoercion] -- There are only a fixed number of CoAxiomRules, so it suffices -- to use an IfaceLclName to distinguish them. -- See Note [Adding built-in type families] in TcTypeNats | IfaceUnivCo IfaceUnivCoProv Role IfaceType IfaceType | IfaceSymCo IfaceCoercion | IfaceTransCo IfaceCoercion IfaceCoercion | IfaceNthCo Int IfaceCoercion | IfaceLRCo LeftOrRight IfaceCoercion | IfaceInstCo IfaceCoercion IfaceCoercion | IfaceKindCo IfaceCoercion | IfaceSubCo IfaceCoercion | IfaceFreeCoVar CoVar -- See Note [Free tyvars in IfaceType] | IfaceHoleCo CoVar -- ^ See Note [Holes in IfaceCoercion] data IfaceUnivCoProv = IfaceUnsafeCoerceProv | IfacePhantomProv IfaceCoercion | IfaceProofIrrelProv IfaceCoercion | IfacePluginProv String {- Note [Holes in IfaceCoercion] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When typechecking fails the typechecker will produce a HoleCo to stand in place of the unproven assertion. While we generally don't want to let these unproven assertions leak into interface files, we still need to be able to pretty-print them as we use IfaceType's pretty-printer to render Types. For this reason IfaceCoercion has a IfaceHoleCo constructor; however, we fails when asked to serialize to a IfaceHoleCo to ensure that they don't end up in an interface file. %************************************************************************ %* * Functions over IFaceTypes * * ************************************************************************ -} ifaceTyConHasKey :: IfaceTyCon -> Unique -> Bool ifaceTyConHasKey tc key = ifaceTyConName tc `hasKey` key isIfaceLiftedTypeKind :: IfaceKind -> Bool isIfaceLiftedTypeKind (IfaceTyConApp tc IA_Nil) = isLiftedTypeKindTyConName (ifaceTyConName tc) isIfaceLiftedTypeKind (IfaceTyConApp tc (IA_Arg (IfaceTyConApp ptr_rep_lifted IA_Nil) Required IA_Nil)) = tc `ifaceTyConHasKey` tYPETyConKey && ptr_rep_lifted `ifaceTyConHasKey` liftedRepDataConKey isIfaceLiftedTypeKind _ = False splitIfaceSigmaTy :: IfaceType -> ([IfaceForAllBndr], [IfacePredType], IfaceType) -- Mainly for printing purposes -- -- Here we split nested IfaceSigmaTy properly. -- -- @ -- forall t. T t => forall m a b. M m => (a -> m b) -> t a -> m (t b) -- @ -- -- If you called @splitIfaceSigmaTy@ on this type: -- -- @ -- ([t, m, a, b], [T t, M m], (a -> m b) -> t a -> m (t b)) -- @ splitIfaceSigmaTy ty = case (bndrs, theta) of ([], []) -> (bndrs, theta, tau) _ -> let (bndrs', theta', tau') = splitIfaceSigmaTy tau in (bndrs ++ bndrs', theta ++ theta', tau') where (bndrs, rho) = split_foralls ty (theta, tau) = split_rho rho split_foralls (IfaceForAllTy bndr ty) = case split_foralls ty of { (bndrs, rho) -> (bndr:bndrs, rho) } split_foralls rho = ([], rho) split_rho (IfaceFunTy InvisArg ty1 ty2) = case split_rho ty2 of { (ps, tau) -> (ty1:ps, tau) } split_rho tau = ([], tau) suppressIfaceInvisibles :: DynFlags -> [IfaceTyConBinder] -> [a] -> [a] suppressIfaceInvisibles dflags tys xs | gopt Opt_PrintExplicitKinds dflags = xs | otherwise = suppress tys xs where suppress _ [] = [] suppress [] a = a suppress (k:ks) (x:xs) | isInvisibleTyConBinder k = suppress ks xs | otherwise = x : suppress ks xs stripIfaceInvisVars :: DynFlags -> [IfaceTyConBinder] -> [IfaceTyConBinder] stripIfaceInvisVars dflags tyvars | gopt Opt_PrintExplicitKinds dflags = tyvars | otherwise = filterOut isInvisibleTyConBinder tyvars -- | Extract an 'IfaceBndr' from an 'IfaceForAllBndr'. ifForAllBndrVar :: IfaceForAllBndr -> IfaceBndr ifForAllBndrVar = binderVar -- | Extract the variable name from an 'IfaceForAllBndr'. ifForAllBndrName :: IfaceForAllBndr -> IfLclName ifForAllBndrName fab = ifaceBndrName (ifForAllBndrVar fab) -- | Extract an 'IfaceBndr' from an 'IfaceTyConBinder'. ifTyConBinderVar :: IfaceTyConBinder -> IfaceBndr ifTyConBinderVar = binderVar -- | Extract the variable name from an 'IfaceTyConBinder'. ifTyConBinderName :: IfaceTyConBinder -> IfLclName ifTyConBinderName tcb = ifaceBndrName (ifTyConBinderVar tcb) ifTypeIsVarFree :: IfaceType -> Bool -- Returns True if the type definitely has no variables at all -- Just used to control pretty printing ifTypeIsVarFree ty = go ty where go (IfaceTyVar {}) = False go (IfaceFreeTyVar {}) = False go (IfaceAppTy fun args) = go fun && go_args args go (IfaceFunTy _ arg res) = go arg && go res go (IfaceForAllTy {}) = False go (IfaceTyConApp _ args) = go_args args go (IfaceTupleTy _ _ args) = go_args args go (IfaceLitTy _) = True go (IfaceCastTy {}) = False -- Safe go (IfaceCoercionTy {}) = False -- Safe go_args IA_Nil = True go_args (IA_Arg arg _ args) = go arg && go_args args {- Note [Substitution on IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Substitutions on IfaceType are done only during pretty-printing to construct the result type of a GADT, and does not deal with binders (eg IfaceForAll), so it doesn't need fancy capture stuff. -} type IfaceTySubst = FastStringEnv IfaceType -- Note [Substitution on IfaceType] mkIfaceTySubst :: [(IfLclName,IfaceType)] -> IfaceTySubst -- See Note [Substitution on IfaceType] mkIfaceTySubst eq_spec = mkFsEnv eq_spec inDomIfaceTySubst :: IfaceTySubst -> IfaceTvBndr -> Bool -- See Note [Substitution on IfaceType] inDomIfaceTySubst subst (fs, _) = isJust (lookupFsEnv subst fs) substIfaceType :: IfaceTySubst -> IfaceType -> IfaceType -- See Note [Substitution on IfaceType] substIfaceType env ty = go ty where go (IfaceFreeTyVar tv) = IfaceFreeTyVar tv go (IfaceTyVar tv) = substIfaceTyVar env tv go (IfaceAppTy t ts) = IfaceAppTy (go t) (substIfaceAppArgs env ts) go (IfaceFunTy af t1 t2) = IfaceFunTy af (go t1) (go t2) go ty@(IfaceLitTy {}) = ty go (IfaceTyConApp tc tys) = IfaceTyConApp tc (substIfaceAppArgs env tys) go (IfaceTupleTy s i tys) = IfaceTupleTy s i (substIfaceAppArgs env tys) go (IfaceForAllTy {}) = pprPanic "substIfaceType" (ppr ty) go (IfaceCastTy ty co) = IfaceCastTy (go ty) (go_co co) go (IfaceCoercionTy co) = IfaceCoercionTy (go_co co) go_mco IfaceMRefl = IfaceMRefl go_mco (IfaceMCo co) = IfaceMCo $ go_co co go_co (IfaceReflCo ty) = IfaceReflCo (go ty) go_co (IfaceGReflCo r ty mco) = IfaceGReflCo r (go ty) (go_mco mco) go_co (IfaceFunCo r c1 c2) = IfaceFunCo r (go_co c1) (go_co c2) go_co (IfaceTyConAppCo r tc cos) = IfaceTyConAppCo r tc (go_cos cos) go_co (IfaceAppCo c1 c2) = IfaceAppCo (go_co c1) (go_co c2) go_co (IfaceForAllCo {}) = pprPanic "substIfaceCoercion" (ppr ty) go_co (IfaceFreeCoVar cv) = IfaceFreeCoVar cv go_co (IfaceCoVarCo cv) = IfaceCoVarCo cv go_co (IfaceHoleCo cv) = IfaceHoleCo cv go_co (IfaceAxiomInstCo a i cos) = IfaceAxiomInstCo a i (go_cos cos) go_co (IfaceUnivCo prov r t1 t2) = IfaceUnivCo (go_prov prov) r (go t1) (go t2) go_co (IfaceSymCo co) = IfaceSymCo (go_co co) go_co (IfaceTransCo co1 co2) = IfaceTransCo (go_co co1) (go_co co2) go_co (IfaceNthCo n co) = IfaceNthCo n (go_co co) go_co (IfaceLRCo lr co) = IfaceLRCo lr (go_co co) go_co (IfaceInstCo c1 c2) = IfaceInstCo (go_co c1) (go_co c2) go_co (IfaceKindCo co) = IfaceKindCo (go_co co) go_co (IfaceSubCo co) = IfaceSubCo (go_co co) go_co (IfaceAxiomRuleCo n cos) = IfaceAxiomRuleCo n (go_cos cos) go_cos = map go_co go_prov IfaceUnsafeCoerceProv = IfaceUnsafeCoerceProv go_prov (IfacePhantomProv co) = IfacePhantomProv (go_co co) go_prov (IfaceProofIrrelProv co) = IfaceProofIrrelProv (go_co co) go_prov (IfacePluginProv str) = IfacePluginProv str substIfaceAppArgs :: IfaceTySubst -> IfaceAppArgs -> IfaceAppArgs substIfaceAppArgs env args = go args where go IA_Nil = IA_Nil go (IA_Arg ty arg tys) = IA_Arg (substIfaceType env ty) arg (go tys) substIfaceTyVar :: IfaceTySubst -> IfLclName -> IfaceType substIfaceTyVar env tv | Just ty <- lookupFsEnv env tv = ty | otherwise = IfaceTyVar tv {- ************************************************************************ * * Functions over IfaceAppArgs * * ************************************************************************ -} stripInvisArgs :: DynFlags -> IfaceAppArgs -> IfaceAppArgs stripInvisArgs dflags tys | gopt Opt_PrintExplicitKinds dflags = tys | otherwise = suppress_invis tys where suppress_invis c = case c of IA_Nil -> IA_Nil IA_Arg t argf ts | isVisibleArgFlag argf -> IA_Arg t argf $ suppress_invis ts -- Keep recursing through the remainder of the arguments, as it's -- possible that there are remaining invisible ones. -- See the "In type declarations" section of Note [VarBndrs, -- TyCoVarBinders, TyConBinders, and visibility] in TyCoRep. | otherwise -> suppress_invis ts appArgsIfaceTypes :: IfaceAppArgs -> [IfaceType] appArgsIfaceTypes IA_Nil = [] appArgsIfaceTypes (IA_Arg t _ ts) = t : appArgsIfaceTypes ts appArgsIfaceTypesArgFlags :: IfaceAppArgs -> [(IfaceType, ArgFlag)] appArgsIfaceTypesArgFlags IA_Nil = [] appArgsIfaceTypesArgFlags (IA_Arg t a ts) = (t, a) : appArgsIfaceTypesArgFlags ts ifaceVisAppArgsLength :: IfaceAppArgs -> Int ifaceVisAppArgsLength = go 0 where go !n IA_Nil = n go n (IA_Arg _ argf rest) | isVisibleArgFlag argf = go (n+1) rest | otherwise = go n rest {- Note [Suppressing invisible arguments] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use the IfaceAppArgs data type to specify which of the arguments to a type should be displayed when pretty-printing, under the control of -fprint-explicit-kinds. See also Type.filterOutInvisibleTypes. For example, given T :: forall k. (k->*) -> k -> * -- Ordinary kind polymorphism 'Just :: forall k. k -> 'Maybe k -- Promoted we want T * Tree Int prints as T Tree Int 'Just * prints as Just * For type constructors (IfaceTyConApp), IfaceAppArgs is a quite natural fit, since the corresponding Core constructor: data Type = ... | TyConApp TyCon [Type] Already puts all of its arguments into a list. So when converting a Type to an IfaceType (see toIfaceAppArgsX in GHC.Core.ToIface), we simply use the kind of the TyCon (which is cached) to guide the process of converting the argument Types into an IfaceAppArgs list. We also want this behavior for IfaceAppTy, since given: data Proxy (a :: k) f :: forall (t :: forall a. a -> Type). Proxy Type (t Bool True) We want to print the return type as `Proxy (t True)` without the use of -fprint-explicit-kinds (#15330). Accomplishing this is trickier than in the tycon case, because the corresponding Core constructor for IfaceAppTy: data Type = ... | AppTy Type Type Only stores one argument at a time. Therefore, when converting an AppTy to an IfaceAppTy (in toIfaceTypeX in GHC.CoreToIface), we: 1. Flatten the chain of AppTys down as much as possible 2. Use typeKind to determine the function Type's kind 3. Use this kind to guide the process of converting the argument Types into an IfaceAppArgs list. By flattening the arguments like this, we obtain two benefits: (a) We can reuse the same machinery to pretty-print IfaceTyConApp arguments as we do IfaceTyApp arguments, which means that we only need to implement the logic to filter out invisible arguments once. (b) Unlike for tycons, finding the kind of a type in general (through typeKind) is not a constant-time operation, so by flattening the arguments first, we decrease the number of times we have to call typeKind. Note [Pretty-printing invisible arguments] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Note [Suppressing invisible arguments] is all about how to avoid printing invisible arguments when the -fprint-explicit-kinds flag is disables. Well, what about when it's enabled? Then we can and should print invisible kind arguments, and this Note explains how we do it. As two running examples, consider the following code: {-# LANGUAGE PolyKinds #-} data T1 a data T2 (a :: k) When displaying these types (with -fprint-explicit-kinds on), we could just do the following: T1 k a T2 k a That certainly gets the job done. But it lacks a crucial piece of information: is the `k` argument inferred or specified? To communicate this, we use visible kind application syntax to distinguish the two cases: T1 @{k} a T2 @k a Here, @{k} indicates that `k` is an inferred argument, and @k indicates that `k` is a specified argument. (See Note [VarBndrs, TyCoVarBinders, TyConBinders, and visibility] in TyCoRep for a lengthier explanation on what "inferred" and "specified" mean.) ************************************************************************ * * Pretty-printing * * ************************************************************************ -} if_print_coercions :: SDoc -- ^ if printing coercions -> SDoc -- ^ otherwise -> SDoc if_print_coercions yes no = sdocWithDynFlags $ \dflags -> getPprStyle $ \style -> if gopt Opt_PrintExplicitCoercions dflags || dumpStyle style || debugStyle style then yes else no pprIfaceInfixApp :: PprPrec -> SDoc -> SDoc -> SDoc -> SDoc pprIfaceInfixApp ctxt_prec pp_tc pp_ty1 pp_ty2 = maybeParen ctxt_prec opPrec $ sep [pp_ty1, pp_tc <+> pp_ty2] pprIfacePrefixApp :: PprPrec -> SDoc -> [SDoc] -> SDoc pprIfacePrefixApp ctxt_prec pp_fun pp_tys | null pp_tys = pp_fun | otherwise = maybeParen ctxt_prec appPrec $ hang pp_fun 2 (sep pp_tys) isIfaceTauType :: IfaceType -> Bool isIfaceTauType (IfaceForAllTy _ _) = False isIfaceTauType (IfaceFunTy InvisArg _ _) = False isIfaceTauType _ = True -- ----------------------------- Printing binders ------------------------------------ instance Outputable IfaceBndr where ppr (IfaceIdBndr bndr) = pprIfaceIdBndr bndr ppr (IfaceTvBndr bndr) = char '@' <> pprIfaceTvBndr bndr (SuppressBndrSig False) (UseBndrParens False) pprIfaceBndrs :: [IfaceBndr] -> SDoc pprIfaceBndrs bs = sep (map ppr bs) pprIfaceLamBndr :: IfaceLamBndr -> SDoc pprIfaceLamBndr (b, IfaceNoOneShot) = ppr b pprIfaceLamBndr (b, IfaceOneShot) = ppr b <> text "[OneShot]" pprIfaceIdBndr :: IfaceIdBndr -> SDoc pprIfaceIdBndr (name, ty) = parens (ppr name <+> dcolon <+> ppr ty) {- Note [Suppressing binder signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When printing the binders in a 'forall', we want to keep the kind annotations: forall (a :: k). blah ^^^^ good On the other hand, when we print the binders of a data declaration in :info, the kind information would be redundant due to the standalone kind signature: type F :: Symbol -> Type type F (s :: Symbol) = blah ^^^^^^^^^ redundant Here we'd like to omit the kind annotation: type F :: Symbol -> Type type F s = blah -} -- | Do we want to suppress kind annotations on binders? -- See Note [Suppressing binder signatures] newtype SuppressBndrSig = SuppressBndrSig Bool newtype UseBndrParens = UseBndrParens Bool pprIfaceTvBndr :: IfaceTvBndr -> SuppressBndrSig -> UseBndrParens -> SDoc pprIfaceTvBndr (tv, ki) (SuppressBndrSig suppress_sig) (UseBndrParens use_parens) | suppress_sig = ppr tv | isIfaceLiftedTypeKind ki = ppr tv | otherwise = maybe_parens (ppr tv <+> dcolon <+> ppr ki) where maybe_parens | use_parens = parens | otherwise = id pprIfaceTyConBinders :: SuppressBndrSig -> [IfaceTyConBinder] -> SDoc pprIfaceTyConBinders suppress_sig = sep . map go where go :: IfaceTyConBinder -> SDoc go (Bndr (IfaceIdBndr bndr) _) = pprIfaceIdBndr bndr go (Bndr (IfaceTvBndr bndr) vis) = -- See Note [Pretty-printing invisible arguments] case vis of AnonTCB VisArg -> ppr_bndr (UseBndrParens True) AnonTCB InvisArg -> char '@' <> braces (ppr_bndr (UseBndrParens False)) -- The above case is rare. (See Note [AnonTCB InvisArg] in TyCon.) -- Should we print these differently? NamedTCB Required -> ppr_bndr (UseBndrParens True) NamedTCB Specified -> char '@' <> ppr_bndr (UseBndrParens True) NamedTCB Inferred -> char '@' <> braces (ppr_bndr (UseBndrParens False)) where ppr_bndr = pprIfaceTvBndr bndr suppress_sig instance Binary IfaceBndr where put_ bh (IfaceIdBndr aa) = do putByte bh 0 put_ bh aa put_ bh (IfaceTvBndr ab) = do putByte bh 1 put_ bh ab get bh = do h <- getByte bh case h of 0 -> do aa <- get bh return (IfaceIdBndr aa) _ -> do ab <- get bh return (IfaceTvBndr ab) instance Binary IfaceOneShot where put_ bh IfaceNoOneShot = do putByte bh 0 put_ bh IfaceOneShot = do putByte bh 1 get bh = do h <- getByte bh case h of 0 -> do return IfaceNoOneShot _ -> do return IfaceOneShot -- ----------------------------- Printing IfaceType ------------------------------------ --------------------------------- instance Outputable IfaceType where ppr ty = pprIfaceType ty pprIfaceType, pprParendIfaceType :: IfaceType -> SDoc pprIfaceType = pprPrecIfaceType topPrec pprParendIfaceType = pprPrecIfaceType appPrec pprPrecIfaceType :: PprPrec -> IfaceType -> SDoc -- We still need `eliminateRuntimeRep`, since the `pprPrecIfaceType` maybe -- called from other places, besides `:type` and `:info`. pprPrecIfaceType prec ty = eliminateRuntimeRep (ppr_ty prec) ty ppr_sigma :: PprPrec -> IfaceType -> SDoc ppr_sigma ctxt_prec ty = maybeParen ctxt_prec funPrec (pprIfaceSigmaType ShowForAllMust ty) ppr_ty :: PprPrec -> IfaceType -> SDoc ppr_ty ctxt_prec ty@(IfaceForAllTy {}) = ppr_sigma ctxt_prec ty ppr_ty ctxt_prec ty@(IfaceFunTy InvisArg _ _) = ppr_sigma ctxt_prec ty ppr_ty _ (IfaceFreeTyVar tyvar) = ppr tyvar -- This is the main reason for IfaceFreeTyVar! ppr_ty _ (IfaceTyVar tyvar) = ppr tyvar -- See Note [TcTyVars in IfaceType] ppr_ty ctxt_prec (IfaceTyConApp tc tys) = pprTyTcApp ctxt_prec tc tys ppr_ty ctxt_prec (IfaceTupleTy i p tys) = pprTuple ctxt_prec i p tys ppr_ty _ (IfaceLitTy n) = pprIfaceTyLit n -- Function types ppr_ty ctxt_prec (IfaceFunTy _ ty1 ty2) -- Should be VisArg = -- We don't want to lose synonyms, so we mustn't use splitFunTys here. maybeParen ctxt_prec funPrec $ sep [ppr_ty funPrec ty1, sep (ppr_fun_tail ty2)] where ppr_fun_tail (IfaceFunTy VisArg ty1 ty2) = (arrow <+> ppr_ty funPrec ty1) : ppr_fun_tail ty2 ppr_fun_tail other_ty = [arrow <+> pprIfaceType other_ty] ppr_ty ctxt_prec (IfaceAppTy t ts) = if_print_coercions ppr_app_ty ppr_app_ty_no_casts where ppr_app_ty = sdocWithDynFlags $ \dflags -> pprIfacePrefixApp ctxt_prec (ppr_ty funPrec t) (map (ppr_app_arg appPrec) (tys_wo_kinds dflags)) tys_wo_kinds dflags = appArgsIfaceTypesArgFlags $ stripInvisArgs dflags ts -- Strip any casts from the head of the application ppr_app_ty_no_casts = case t of IfaceCastTy head _ -> ppr_ty ctxt_prec (mk_app_tys head ts) _ -> ppr_app_ty mk_app_tys :: IfaceType -> IfaceAppArgs -> IfaceType mk_app_tys (IfaceTyConApp tc tys1) tys2 = IfaceTyConApp tc (tys1 `mappend` tys2) mk_app_tys t1 tys2 = IfaceAppTy t1 tys2 ppr_ty ctxt_prec (IfaceCastTy ty co) = if_print_coercions (parens (ppr_ty topPrec ty <+> text "|>" <+> ppr co)) (ppr_ty ctxt_prec ty) ppr_ty ctxt_prec (IfaceCoercionTy co) = if_print_coercions (ppr_co ctxt_prec co) (text "<>") {- Note [Defaulting RuntimeRep variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RuntimeRep variables are considered by many (most?) users to be little more than syntactic noise. When the notion was introduced there was a significant and understandable push-back from those with pedagogy in mind, which argued that RuntimeRep variables would throw a wrench into nearly any teach approach since they appear in even the lowly ($) function's type, ($) :: forall (w :: RuntimeRep) a (b :: TYPE w). (a -> b) -> a -> b which is significantly less readable than its non RuntimeRep-polymorphic type of ($) :: (a -> b) -> a -> b Moreover, unboxed types don't appear all that often in run-of-the-mill Haskell programs, so it makes little sense to make all users pay this syntactic overhead. For this reason it was decided that we would hide RuntimeRep variables for now (see #11549). We do this by defaulting all type variables of kind RuntimeRep to LiftedRep. This is done in a pass right before pretty-printing (defaultRuntimeRepVars, controlled by -fprint-explicit-runtime-reps) This applies to /quantified/ variables like 'w' above. What about variables that are /free/ in the type being printed, which certainly happens in error messages. Suppose (#16074) we are reporting a mismatch between two skolems (a :: RuntimeRep) ~ (b :: RuntimeRep) We certainly don't want to say "Can't match LiftedRep ~ LiftedRep"! But if we are printing the type (forall (a :: Type r). blah we do want to turn that (free) r into LiftedRep, so it prints as (forall a. blah) Conclusion: keep track of whether we we are in the kind of a binder; ohly if so, convert free RuntimeRep variables to LiftedRep. -} -- | Default 'RuntimeRep' variables to 'LiftedPtr'. e.g. -- -- @ -- ($) :: forall (r :: GHC.Types.RuntimeRep) a (b :: TYPE r). -- (a -> b) -> a -> b -- @ -- -- turns in to, -- -- @ ($) :: forall a (b :: *). (a -> b) -> a -> b @ -- -- We do this to prevent RuntimeRep variables from incurring a significant -- syntactic overhead in otherwise simple type signatures (e.g. ($)). See -- Note [Defaulting RuntimeRep variables] and #11549 for further discussion. -- defaultRuntimeRepVars :: IfaceType -> IfaceType defaultRuntimeRepVars ty = go False emptyFsEnv ty where go :: Bool -- True <=> Inside the kind of a binder -> FastStringEnv () -- Set of enclosing forall-ed RuntimeRep variables -> IfaceType -- (replace them with LiftedRep) -> IfaceType go ink subs (IfaceForAllTy (Bndr (IfaceTvBndr (var, var_kind)) argf) ty) | isRuntimeRep var_kind , isInvisibleArgFlag argf -- Don't default *visible* quantification -- or we get the mess in #13963 = let subs' = extendFsEnv subs var () -- Record that we should replace it with LiftedRep, -- and recurse, discarding the forall in go ink subs' ty go ink subs (IfaceForAllTy bndr ty) = IfaceForAllTy (go_ifacebndr subs bndr) (go ink subs ty) go _ subs ty@(IfaceTyVar tv) | tv `elemFsEnv` subs = IfaceTyConApp liftedRep IA_Nil | otherwise = ty go in_kind _ ty@(IfaceFreeTyVar tv) -- See Note [Defaulting RuntimeRep variables], about free vars | in_kind && Type.isRuntimeRepTy (tyVarKind tv) = IfaceTyConApp liftedRep IA_Nil | otherwise = ty go ink subs (IfaceTyConApp tc tc_args) = IfaceTyConApp tc (go_args ink subs tc_args) go ink subs (IfaceTupleTy sort is_prom tc_args) = IfaceTupleTy sort is_prom (go_args ink subs tc_args) go ink subs (IfaceFunTy af arg res) = IfaceFunTy af (go ink subs arg) (go ink subs res) go ink subs (IfaceAppTy t ts) = IfaceAppTy (go ink subs t) (go_args ink subs ts) go ink subs (IfaceCastTy x co) = IfaceCastTy (go ink subs x) co go _ _ ty@(IfaceLitTy {}) = ty go _ _ ty@(IfaceCoercionTy {}) = ty go_ifacebndr :: FastStringEnv () -> IfaceForAllBndr -> IfaceForAllBndr go_ifacebndr subs (Bndr (IfaceIdBndr (n, t)) argf) = Bndr (IfaceIdBndr (n, go True subs t)) argf go_ifacebndr subs (Bndr (IfaceTvBndr (n, t)) argf) = Bndr (IfaceTvBndr (n, go True subs t)) argf go_args :: Bool -> FastStringEnv () -> IfaceAppArgs -> IfaceAppArgs go_args _ _ IA_Nil = IA_Nil go_args ink subs (IA_Arg ty argf args) = IA_Arg (go ink subs ty) argf (go_args ink subs args) liftedRep :: IfaceTyCon liftedRep = IfaceTyCon dc_name (IfaceTyConInfo IsPromoted IfaceNormalTyCon) where dc_name = getName liftedRepDataConTyCon isRuntimeRep :: IfaceType -> Bool isRuntimeRep (IfaceTyConApp tc _) = tc `ifaceTyConHasKey` runtimeRepTyConKey isRuntimeRep _ = False eliminateRuntimeRep :: (IfaceType -> SDoc) -> IfaceType -> SDoc eliminateRuntimeRep f ty = sdocWithDynFlags $ \dflags -> getPprStyle $ \sty -> if userStyle sty && not (gopt Opt_PrintExplicitRuntimeReps dflags) then f (defaultRuntimeRepVars ty) else f ty instance Outputable IfaceAppArgs where ppr tca = pprIfaceAppArgs tca pprIfaceAppArgs, pprParendIfaceAppArgs :: IfaceAppArgs -> SDoc pprIfaceAppArgs = ppr_app_args topPrec pprParendIfaceAppArgs = ppr_app_args appPrec ppr_app_args :: PprPrec -> IfaceAppArgs -> SDoc ppr_app_args ctx_prec = go where go :: IfaceAppArgs -> SDoc go IA_Nil = empty go (IA_Arg t argf ts) = ppr_app_arg ctx_prec (t, argf) <+> go ts -- See Note [Pretty-printing invisible arguments] ppr_app_arg :: PprPrec -> (IfaceType, ArgFlag) -> SDoc ppr_app_arg ctx_prec (t, argf) = sdocWithDynFlags $ \dflags -> let print_kinds = gopt Opt_PrintExplicitKinds dflags in case argf of Required -> ppr_ty ctx_prec t Specified | print_kinds -> char '@' <> ppr_ty appPrec t Inferred | print_kinds -> char '@' <> braces (ppr_ty topPrec t) _ -> empty ------------------- pprIfaceForAllPart :: [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc pprIfaceForAllPart tvs ctxt sdoc = ppr_iface_forall_part ShowForAllWhen tvs ctxt sdoc -- | Like 'pprIfaceForAllPart', but always uses an explicit @forall@. pprIfaceForAllPartMust :: [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc pprIfaceForAllPartMust tvs ctxt sdoc = ppr_iface_forall_part ShowForAllMust tvs ctxt sdoc pprIfaceForAllCoPart :: [(IfLclName, IfaceCoercion)] -> SDoc -> SDoc pprIfaceForAllCoPart tvs sdoc = sep [ pprIfaceForAllCo tvs, sdoc ] ppr_iface_forall_part :: ShowForAllFlag -> [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc ppr_iface_forall_part show_forall tvs ctxt sdoc = sep [ case show_forall of ShowForAllMust -> pprIfaceForAll tvs ShowForAllWhen -> pprUserIfaceForAll tvs , pprIfaceContextArr ctxt , sdoc] -- | Render the "forall ... ." or "forall ... ->" bit of a type. pprIfaceForAll :: [IfaceForAllBndr] -> SDoc pprIfaceForAll [] = empty pprIfaceForAll bndrs@(Bndr _ vis : _) = sep [ add_separator (forAllLit <+> fsep docs) , pprIfaceForAll bndrs' ] where (bndrs', docs) = ppr_itv_bndrs bndrs vis add_separator stuff = case vis of Required -> stuff <+> arrow _inv -> stuff <> dot -- | Render the ... in @(forall ... .)@ or @(forall ... ->)@. -- Returns both the list of not-yet-rendered binders and the doc. -- No anonymous binders here! ppr_itv_bndrs :: [IfaceForAllBndr] -> ArgFlag -- ^ visibility of the first binder in the list -> ([IfaceForAllBndr], [SDoc]) ppr_itv_bndrs all_bndrs@(bndr@(Bndr _ vis) : bndrs) vis1 | vis `sameVis` vis1 = let (bndrs', doc) = ppr_itv_bndrs bndrs vis1 in (bndrs', pprIfaceForAllBndr bndr : doc) | otherwise = (all_bndrs, []) ppr_itv_bndrs [] _ = ([], []) pprIfaceForAllCo :: [(IfLclName, IfaceCoercion)] -> SDoc pprIfaceForAllCo [] = empty pprIfaceForAllCo tvs = text "forall" <+> pprIfaceForAllCoBndrs tvs <> dot pprIfaceForAllCoBndrs :: [(IfLclName, IfaceCoercion)] -> SDoc pprIfaceForAllCoBndrs bndrs = hsep $ map pprIfaceForAllCoBndr bndrs pprIfaceForAllBndr :: IfaceForAllBndr -> SDoc pprIfaceForAllBndr bndr = case bndr of Bndr (IfaceTvBndr tv) Inferred -> sdocWithDynFlags $ \dflags -> if gopt Opt_PrintExplicitForalls dflags then braces $ pprIfaceTvBndr tv suppress_sig (UseBndrParens False) else pprIfaceTvBndr tv suppress_sig (UseBndrParens True) Bndr (IfaceTvBndr tv) _ -> pprIfaceTvBndr tv suppress_sig (UseBndrParens True) Bndr (IfaceIdBndr idv) _ -> pprIfaceIdBndr idv where -- See Note [Suppressing binder signatures] suppress_sig = SuppressBndrSig False pprIfaceForAllCoBndr :: (IfLclName, IfaceCoercion) -> SDoc pprIfaceForAllCoBndr (tv, kind_co) = parens (ppr tv <+> dcolon <+> pprIfaceCoercion kind_co) -- | Show forall flag -- -- Unconditionally show the forall quantifier with ('ShowForAllMust') -- or when ('ShowForAllWhen') the names used are free in the binder -- or when compiling with -fprint-explicit-foralls. data ShowForAllFlag = ShowForAllMust | ShowForAllWhen pprIfaceSigmaType :: ShowForAllFlag -> IfaceType -> SDoc pprIfaceSigmaType show_forall ty = eliminateRuntimeRep ppr_fn ty where ppr_fn iface_ty = let (tvs, theta, tau) = splitIfaceSigmaTy iface_ty in ppr_iface_forall_part show_forall tvs theta (ppr tau) pprUserIfaceForAll :: [IfaceForAllBndr] -> SDoc pprUserIfaceForAll tvs = sdocWithDynFlags $ \dflags -> -- See Note [When to print foralls] in this module. ppWhen (any tv_has_kind_var tvs || any tv_is_required tvs || gopt Opt_PrintExplicitForalls dflags) $ pprIfaceForAll tvs where tv_has_kind_var (Bndr (IfaceTvBndr (_,kind)) _) = not (ifTypeIsVarFree kind) tv_has_kind_var _ = False tv_is_required = isVisibleArgFlag . binderArgFlag {- Note [When to print foralls] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We opt to explicitly pretty-print `forall`s if any of the following criteria are met: 1. -fprint-explicit-foralls is on. 2. A bound type variable has a polymorphic kind. E.g., forall k (a::k). Proxy a -> Proxy a Since a's kind mentions a variable k, we print the foralls. 3. A bound type variable is a visible argument (#14238). Suppose we are printing the kind of: T :: forall k -> k -> Type The "forall k ->" notation means that this kind argument is required. That is, it must be supplied at uses of T. E.g., f :: T (Type->Type) Monad -> Int So we print an explicit "T :: forall k -> k -> Type", because omitting it and printing "T :: k -> Type" would be utterly misleading. See Note [VarBndrs, TyCoVarBinders, TyConBinders, and visibility] in TyCoRep. N.B. Until now (Aug 2018) we didn't check anything for coercion variables. Note [Printing foralls in type family instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use the same criteria as in Note [When to print foralls] to determine whether a type family instance should be pretty-printed with an explicit `forall`. Example: type family Foo (a :: k) :: k where Foo Maybe = [] Foo (a :: Type) = Int Foo a = a Without -fprint-explicit-foralls enabled, this will be pretty-printed as: type family Foo (a :: k) :: k where Foo Maybe = [] Foo a = Int forall k (a :: k). Foo a = a Note that only the third equation has an explicit forall, since it has a type variable with a non-Type kind. (If -fprint-explicit-foralls were enabled, then the second equation would be preceded with `forall a.`.) There is one tricky point in the implementation: what visibility do we give the type variables in a type family instance? Type family instances only store type *variables*, not type variable *binders*, and only the latter has visibility information. We opt to default the visibility of each of these type variables to Specified because users can't ever instantiate these variables manually, so the choice of visibility is only relevant to pretty-printing. (This is why the `k` in `forall k (a :: k). ...` above is printed the way it is, even though it wasn't written explicitly in the original source code.) We adopt the same strategy for data family instances. Example: data family DF (a :: k) data instance DF '[a, b] = DFList That data family instance is pretty-printed as: data instance forall j (a :: j) (b :: j). DF '[a, b] = DFList This is despite that the representation tycon for this data instance (call it $DF:List) actually has different visibilities for its binders. However, the visibilities of these binders are utterly irrelevant to the programmer, who cares only about the specificity of variables in `DF`'s type, not $DF:List's type. Therefore, we opt to pretty-print all variables in data family instances as Specified. Note [Printing promoted type constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this GHCi session (#14343) > _ :: Proxy '[ 'True ] error: Found hole: _ :: Proxy '['True] This would be bad, because the '[' looks like a character literal. Solution: in type-level lists and tuples, add a leading space if the first type is itself promoted. See pprSpaceIfPromotedTyCon. -} ------------------- -- | Prefix a space if the given 'IfaceType' is a promoted 'TyCon'. -- See Note [Printing promoted type constructors] pprSpaceIfPromotedTyCon :: IfaceType -> SDoc -> SDoc pprSpaceIfPromotedTyCon (IfaceTyConApp tyCon _) = case ifaceTyConIsPromoted (ifaceTyConInfo tyCon) of IsPromoted -> (space <>) _ -> id pprSpaceIfPromotedTyCon _ = id -- See equivalent function in TyCoRep.hs pprIfaceTyList :: PprPrec -> IfaceType -> IfaceType -> SDoc -- Given a type-level list (t1 ': t2), see if we can print -- it in list notation [t1, ...]. -- Precondition: Opt_PrintExplicitKinds is off pprIfaceTyList ctxt_prec ty1 ty2 = case gather ty2 of (arg_tys, Nothing) -> char '\'' <> brackets (pprSpaceIfPromotedTyCon ty1 (fsep (punctuate comma (map (ppr_ty topPrec) (ty1:arg_tys))))) (arg_tys, Just tl) -> maybeParen ctxt_prec funPrec $ hang (ppr_ty funPrec ty1) 2 (fsep [ colon <+> ppr_ty funPrec ty | ty <- arg_tys ++ [tl]]) where gather :: IfaceType -> ([IfaceType], Maybe IfaceType) -- (gather ty) = (tys, Nothing) means ty is a list [t1, .., tn] -- = (tys, Just tl) means ty is of form t1:t2:...tn:tl gather (IfaceTyConApp tc tys) | tc `ifaceTyConHasKey` consDataConKey , IA_Arg _ argf (IA_Arg ty1 Required (IA_Arg ty2 Required IA_Nil)) <- tys , isInvisibleArgFlag argf , (args, tl) <- gather ty2 = (ty1:args, tl) | tc `ifaceTyConHasKey` nilDataConKey = ([], Nothing) gather ty = ([], Just ty) pprIfaceTypeApp :: PprPrec -> IfaceTyCon -> IfaceAppArgs -> SDoc pprIfaceTypeApp prec tc args = pprTyTcApp prec tc args pprTyTcApp :: PprPrec -> IfaceTyCon -> IfaceAppArgs -> SDoc pprTyTcApp ctxt_prec tc tys = sdocWithDynFlags $ \dflags -> getPprStyle $ \style -> pprTyTcApp' ctxt_prec tc tys dflags style pprTyTcApp' :: PprPrec -> IfaceTyCon -> IfaceAppArgs -> DynFlags -> PprStyle -> SDoc pprTyTcApp' ctxt_prec tc tys dflags style | ifaceTyConName tc `hasKey` ipClassKey , IA_Arg (IfaceLitTy (IfaceStrTyLit n)) Required (IA_Arg ty Required IA_Nil) <- tys = maybeParen ctxt_prec funPrec $ char '?' <> ftext n <> text "::" <> ppr_ty topPrec ty | IfaceTupleTyCon arity sort <- ifaceTyConSort info , not (debugStyle style) , arity == ifaceVisAppArgsLength tys = pprTuple ctxt_prec sort (ifaceTyConIsPromoted info) tys | IfaceSumTyCon arity <- ifaceTyConSort info = pprSum arity (ifaceTyConIsPromoted info) tys | tc `ifaceTyConHasKey` consDataConKey , not (gopt Opt_PrintExplicitKinds dflags) , IA_Arg _ argf (IA_Arg ty1 Required (IA_Arg ty2 Required IA_Nil)) <- tys , isInvisibleArgFlag argf = pprIfaceTyList ctxt_prec ty1 ty2 | tc `ifaceTyConHasKey` tYPETyConKey , IA_Arg (IfaceTyConApp rep IA_Nil) Required IA_Nil <- tys , rep `ifaceTyConHasKey` liftedRepDataConKey = ppr_kind_type ctxt_prec | otherwise = getPprDebug $ \dbg -> if | not dbg && tc `ifaceTyConHasKey` errorMessageTypeErrorFamKey -- Suppress detail unless you _really_ want to see -> text "(TypeError ...)" | Just doc <- ppr_equality ctxt_prec tc (appArgsIfaceTypes tys) -> doc | otherwise -> ppr_iface_tc_app ppr_app_arg ctxt_prec tc tys_wo_kinds where info = ifaceTyConInfo tc tys_wo_kinds = appArgsIfaceTypesArgFlags $ stripInvisArgs dflags tys ppr_kind_type :: PprPrec -> SDoc ppr_kind_type ctxt_prec = sdocWithDynFlags $ \dflags -> if useStarIsType dflags then maybeParen ctxt_prec starPrec $ unicodeSyntax (char '★') (char '*') else text "Type" -- | Pretty-print a type-level equality. -- Returns (Just doc) if the argument is a /saturated/ application -- of eqTyCon (~) -- eqPrimTyCon (~#) -- eqReprPrimTyCon (~R#) -- heqTyCon (~~) -- -- See Note [Equality predicates in IfaceType] -- and Note [The equality types story] in TysPrim ppr_equality :: PprPrec -> IfaceTyCon -> [IfaceType] -> Maybe SDoc ppr_equality ctxt_prec tc args | hetero_eq_tc , [k1, k2, t1, t2] <- args = Just $ print_equality (k1, k2, t1, t2) | hom_eq_tc , [k, t1, t2] <- args = Just $ print_equality (k, k, t1, t2) | otherwise = Nothing where homogeneous = tc_name `hasKey` eqTyConKey -- (~) || hetero_tc_used_homogeneously where hetero_tc_used_homogeneously = case ifaceTyConSort $ ifaceTyConInfo tc of IfaceEqualityTyCon -> True _other -> False -- True <=> a heterogeneous equality whose arguments -- are (in this case) of the same kind tc_name = ifaceTyConName tc pp = ppr_ty hom_eq_tc = tc_name `hasKey` eqTyConKey -- (~) hetero_eq_tc = tc_name `hasKey` eqPrimTyConKey -- (~#) || tc_name `hasKey` eqReprPrimTyConKey -- (~R#) || tc_name `hasKey` heqTyConKey -- (~~) nominal_eq_tc = tc_name `hasKey` heqTyConKey -- (~~) || tc_name `hasKey` eqPrimTyConKey -- (~#) print_equality args = sdocWithDynFlags $ \dflags -> getPprStyle $ \style -> print_equality' args style dflags print_equality' (ki1, ki2, ty1, ty2) style dflags | -- If -fprint-equality-relations is on, just print the original TyCon print_eqs = ppr_infix_eq (ppr tc) | -- Homogeneous use of heterogeneous equality (ty1 ~~ ty2) -- or unlifted equality (ty1 ~# ty2) nominal_eq_tc, homogeneous = ppr_infix_eq (text "~") | -- Heterogeneous use of unlifted equality (ty1 ~# ty2) not homogeneous = ppr_infix_eq (ppr heqTyCon) | -- Homogeneous use of representational unlifted equality (ty1 ~R# ty2) tc_name `hasKey` eqReprPrimTyConKey, homogeneous = let ki | print_kinds = [pp appPrec ki1] | otherwise = [] in pprIfacePrefixApp ctxt_prec (ppr coercibleTyCon) (ki ++ [pp appPrec ty1, pp appPrec ty2]) -- The other cases work as you'd expect | otherwise = ppr_infix_eq (ppr tc) where ppr_infix_eq :: SDoc -> SDoc ppr_infix_eq eq_op = pprIfaceInfixApp ctxt_prec eq_op (pp_ty_ki ty1 ki1) (pp_ty_ki ty2 ki2) where pp_ty_ki ty ki | print_kinds = parens (pp topPrec ty <+> dcolon <+> pp opPrec ki) | otherwise = pp opPrec ty print_kinds = gopt Opt_PrintExplicitKinds dflags print_eqs = gopt Opt_PrintEqualityRelations dflags || dumpStyle style || debugStyle style pprIfaceCoTcApp :: PprPrec -> IfaceTyCon -> [IfaceCoercion] -> SDoc pprIfaceCoTcApp ctxt_prec tc tys = ppr_iface_tc_app (\prec (co, _) -> ppr_co prec co) ctxt_prec tc (map (, Required) tys) -- We are trying to re-use ppr_iface_tc_app here, which requires its -- arguments to be accompanied by visibilities. But visibility is -- irrelevant when printing coercions, so just default everything to -- Required. -- | Pretty-prints an application of a type constructor to some arguments -- (whose visibilities are known). This is polymorphic (over @a@) since we use -- this function to pretty-print two different things: -- -- 1. Types (from `pprTyTcApp'`) -- -- 2. Coercions (from 'pprIfaceCoTcApp') ppr_iface_tc_app :: (PprPrec -> (a, ArgFlag) -> SDoc) -> PprPrec -> IfaceTyCon -> [(a, ArgFlag)] -> SDoc ppr_iface_tc_app pp _ tc [ty] | tc `ifaceTyConHasKey` listTyConKey = pprPromotionQuote tc <> brackets (pp topPrec ty) ppr_iface_tc_app pp ctxt_prec tc tys | tc `ifaceTyConHasKey` liftedTypeKindTyConKey = ppr_kind_type ctxt_prec | not (isSymOcc (nameOccName (ifaceTyConName tc))) = pprIfacePrefixApp ctxt_prec (ppr tc) (map (pp appPrec) tys) | [ ty1@(_, Required) , ty2@(_, Required) ] <- tys -- Infix, two visible arguments (we know nothing of precedence though). -- Don't apply this special case if one of the arguments is invisible, -- lest we print something like (@LiftedRep -> @LiftedRep) (#15941). = pprIfaceInfixApp ctxt_prec (ppr tc) (pp opPrec ty1) (pp opPrec ty2) | otherwise = pprIfacePrefixApp ctxt_prec (parens (ppr tc)) (map (pp appPrec) tys) pprSum :: Arity -> PromotionFlag -> IfaceAppArgs -> SDoc pprSum _arity is_promoted args = -- drop the RuntimeRep vars. -- See Note [Unboxed tuple RuntimeRep vars] in TyCon let tys = appArgsIfaceTypes args args' = drop (length tys `div` 2) tys in pprPromotionQuoteI is_promoted <> sumParens (pprWithBars (ppr_ty topPrec) args') pprTuple :: PprPrec -> TupleSort -> PromotionFlag -> IfaceAppArgs -> SDoc pprTuple ctxt_prec sort promoted args = case promoted of IsPromoted -> let tys = appArgsIfaceTypes args args' = drop (length tys `div` 2) tys spaceIfPromoted = case args' of arg0:_ -> pprSpaceIfPromotedTyCon arg0 _ -> id in ppr_tuple_app args' $ pprPromotionQuoteI IsPromoted <> tupleParens sort (spaceIfPromoted (pprWithCommas pprIfaceType args')) NotPromoted | ConstraintTuple <- sort , IA_Nil <- args -> maybeParen ctxt_prec sigPrec $ text "() :: Constraint" | otherwise -> -- drop the RuntimeRep vars. -- See Note [Unboxed tuple RuntimeRep vars] in TyCon let tys = appArgsIfaceTypes args args' = case sort of UnboxedTuple -> drop (length tys `div` 2) tys _ -> tys in ppr_tuple_app args' $ pprPromotionQuoteI promoted <> tupleParens sort (pprWithCommas pprIfaceType args') where ppr_tuple_app :: [IfaceType] -> SDoc -> SDoc ppr_tuple_app args_wo_runtime_reps ppr_args_w_parens -- Special-case unary boxed tuples so that they are pretty-printed as -- `Unit x`, not `(x)` | [_] <- args_wo_runtime_reps , BoxedTuple <- sort = let unit_tc_info = IfaceTyConInfo promoted IfaceNormalTyCon unit_tc = IfaceTyCon (tupleTyConName sort 1) unit_tc_info in pprPrecIfaceType ctxt_prec $ IfaceTyConApp unit_tc args | otherwise = ppr_args_w_parens pprIfaceTyLit :: IfaceTyLit -> SDoc pprIfaceTyLit (IfaceNumTyLit n) = integer n pprIfaceTyLit (IfaceStrTyLit n) = text (show n) pprIfaceCoercion, pprParendIfaceCoercion :: IfaceCoercion -> SDoc pprIfaceCoercion = ppr_co topPrec pprParendIfaceCoercion = ppr_co appPrec ppr_co :: PprPrec -> IfaceCoercion -> SDoc ppr_co _ (IfaceReflCo ty) = angleBrackets (ppr ty) <> ppr_role Nominal ppr_co _ (IfaceGReflCo r ty IfaceMRefl) = angleBrackets (ppr ty) <> ppr_role r ppr_co ctxt_prec (IfaceGReflCo r ty (IfaceMCo co)) = ppr_special_co ctxt_prec (text "GRefl" <+> ppr r <+> pprParendIfaceType ty) [co] ppr_co ctxt_prec (IfaceFunCo r co1 co2) = maybeParen ctxt_prec funPrec $ sep (ppr_co funPrec co1 : ppr_fun_tail co2) where ppr_fun_tail (IfaceFunCo r co1 co2) = (arrow <> ppr_role r <+> ppr_co funPrec co1) : ppr_fun_tail co2 ppr_fun_tail other_co = [arrow <> ppr_role r <+> pprIfaceCoercion other_co] ppr_co _ (IfaceTyConAppCo r tc cos) = parens (pprIfaceCoTcApp topPrec tc cos) <> ppr_role r ppr_co ctxt_prec (IfaceAppCo co1 co2) = maybeParen ctxt_prec appPrec $ ppr_co funPrec co1 <+> pprParendIfaceCoercion co2 ppr_co ctxt_prec co@(IfaceForAllCo {}) = maybeParen ctxt_prec funPrec $ pprIfaceForAllCoPart tvs (pprIfaceCoercion inner_co) where (tvs, inner_co) = split_co co split_co (IfaceForAllCo (IfaceTvBndr (name, _)) kind_co co') = let (tvs, co'') = split_co co' in ((name,kind_co):tvs,co'') split_co (IfaceForAllCo (IfaceIdBndr (name, _)) kind_co co') = let (tvs, co'') = split_co co' in ((name,kind_co):tvs,co'') split_co co' = ([], co') -- Why these three? See Note [TcTyVars in IfaceType] ppr_co _ (IfaceFreeCoVar covar) = ppr covar ppr_co _ (IfaceCoVarCo covar) = ppr covar ppr_co _ (IfaceHoleCo covar) = braces (ppr covar) ppr_co ctxt_prec (IfaceUnivCo IfaceUnsafeCoerceProv r ty1 ty2) = maybeParen ctxt_prec appPrec $ text "UnsafeCo" <+> ppr r <+> pprParendIfaceType ty1 <+> pprParendIfaceType ty2 ppr_co _ (IfaceUnivCo prov role ty1 ty2) = text "Univ" <> (parens $ sep [ ppr role <+> pprIfaceUnivCoProv prov , dcolon <+> ppr ty1 <> comma <+> ppr ty2 ]) ppr_co ctxt_prec (IfaceInstCo co ty) = maybeParen ctxt_prec appPrec $ text "Inst" <+> pprParendIfaceCoercion co <+> pprParendIfaceCoercion ty ppr_co ctxt_prec (IfaceAxiomRuleCo tc cos) = maybeParen ctxt_prec appPrec $ ppr tc <+> parens (interpp'SP cos) ppr_co ctxt_prec (IfaceAxiomInstCo n i cos) = ppr_special_co ctxt_prec (ppr n <> brackets (ppr i)) cos ppr_co ctxt_prec (IfaceSymCo co) = ppr_special_co ctxt_prec (text "Sym") [co] ppr_co ctxt_prec (IfaceTransCo co1 co2) = maybeParen ctxt_prec opPrec $ ppr_co opPrec co1 <+> semi <+> ppr_co opPrec co2 ppr_co ctxt_prec (IfaceNthCo d co) = ppr_special_co ctxt_prec (text "Nth:" <> int d) [co] ppr_co ctxt_prec (IfaceLRCo lr co) = ppr_special_co ctxt_prec (ppr lr) [co] ppr_co ctxt_prec (IfaceSubCo co) = ppr_special_co ctxt_prec (text "Sub") [co] ppr_co ctxt_prec (IfaceKindCo co) = ppr_special_co ctxt_prec (text "Kind") [co] ppr_special_co :: PprPrec -> SDoc -> [IfaceCoercion] -> SDoc ppr_special_co ctxt_prec doc cos = maybeParen ctxt_prec appPrec (sep [doc, nest 4 (sep (map pprParendIfaceCoercion cos))]) ppr_role :: Role -> SDoc ppr_role r = underscore <> pp_role where pp_role = case r of Nominal -> char 'N' Representational -> char 'R' Phantom -> char 'P' ------------------ pprIfaceUnivCoProv :: IfaceUnivCoProv -> SDoc pprIfaceUnivCoProv IfaceUnsafeCoerceProv = text "unsafe" pprIfaceUnivCoProv (IfacePhantomProv co) = text "phantom" <+> pprParendIfaceCoercion co pprIfaceUnivCoProv (IfaceProofIrrelProv co) = text "irrel" <+> pprParendIfaceCoercion co pprIfaceUnivCoProv (IfacePluginProv s) = text "plugin" <+> doubleQuotes (text s) ------------------- instance Outputable IfaceTyCon where ppr tc = pprPromotionQuote tc <> ppr (ifaceTyConName tc) pprPromotionQuote :: IfaceTyCon -> SDoc pprPromotionQuote tc = pprPromotionQuoteI $ ifaceTyConIsPromoted $ ifaceTyConInfo tc pprPromotionQuoteI :: PromotionFlag -> SDoc pprPromotionQuoteI NotPromoted = empty pprPromotionQuoteI IsPromoted = char '\'' instance Outputable IfaceCoercion where ppr = pprIfaceCoercion instance Binary IfaceTyCon where put_ bh (IfaceTyCon n i) = put_ bh n >> put_ bh i get bh = do n <- get bh i <- get bh return (IfaceTyCon n i) instance Binary IfaceTyConSort where put_ bh IfaceNormalTyCon = putByte bh 0 put_ bh (IfaceTupleTyCon arity sort) = putByte bh 1 >> put_ bh arity >> put_ bh sort put_ bh (IfaceSumTyCon arity) = putByte bh 2 >> put_ bh arity put_ bh IfaceEqualityTyCon = putByte bh 3 get bh = do n <- getByte bh case n of 0 -> return IfaceNormalTyCon 1 -> IfaceTupleTyCon <$> get bh <*> get bh 2 -> IfaceSumTyCon <$> get bh _ -> return IfaceEqualityTyCon instance Binary IfaceTyConInfo where put_ bh (IfaceTyConInfo i s) = put_ bh i >> put_ bh s get bh = IfaceTyConInfo <$> get bh <*> get bh instance Outputable IfaceTyLit where ppr = pprIfaceTyLit instance Binary IfaceTyLit where put_ bh (IfaceNumTyLit n) = putByte bh 1 >> put_ bh n put_ bh (IfaceStrTyLit n) = putByte bh 2 >> put_ bh n get bh = do tag <- getByte bh case tag of 1 -> do { n <- get bh ; return (IfaceNumTyLit n) } 2 -> do { n <- get bh ; return (IfaceStrTyLit n) } _ -> panic ("get IfaceTyLit " ++ show tag) instance Binary IfaceAppArgs where put_ bh tk = case tk of IA_Arg t a ts -> putByte bh 0 >> put_ bh t >> put_ bh a >> put_ bh ts IA_Nil -> putByte bh 1 get bh = do c <- getByte bh case c of 0 -> do t <- get bh a <- get bh ts <- get bh return $! IA_Arg t a ts 1 -> return IA_Nil _ -> panic ("get IfaceAppArgs " ++ show c) ------------------- -- Some notes about printing contexts -- -- In the event that we are printing a singleton context (e.g. @Eq a@) we can -- omit parentheses. However, we must take care to set the precedence correctly -- to opPrec, since something like @a :~: b@ must be parenthesized (see -- #9658). -- -- When printing a larger context we use 'fsep' instead of 'sep' so that -- the context doesn't get displayed as a giant column. Rather than, -- instance (Eq a, -- Eq b, -- Eq c, -- Eq d, -- Eq e, -- Eq f, -- Eq g, -- Eq h, -- Eq i, -- Eq j, -- Eq k, -- Eq l) => -- Eq (a, b, c, d, e, f, g, h, i, j, k, l) -- -- we want -- -- instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, -- Eq j, Eq k, Eq l) => -- Eq (a, b, c, d, e, f, g, h, i, j, k, l) -- | Prints "(C a, D b) =>", including the arrow. -- Used when we want to print a context in a type, so we -- use 'funPrec' to decide whether to parenthesise a singleton -- predicate; e.g. Num a => a -> a pprIfaceContextArr :: [IfacePredType] -> SDoc pprIfaceContextArr [] = empty pprIfaceContextArr [pred] = ppr_ty funPrec pred <+> darrow pprIfaceContextArr preds = ppr_parend_preds preds <+> darrow -- | Prints a context or @()@ if empty -- You give it the context precedence pprIfaceContext :: PprPrec -> [IfacePredType] -> SDoc pprIfaceContext _ [] = text "()" pprIfaceContext prec [pred] = ppr_ty prec pred pprIfaceContext _ preds = ppr_parend_preds preds ppr_parend_preds :: [IfacePredType] -> SDoc ppr_parend_preds preds = parens (fsep (punctuate comma (map ppr preds))) instance Binary IfaceType where put_ _ (IfaceFreeTyVar tv) = pprPanic "Can't serialise IfaceFreeTyVar" (ppr tv) put_ bh (IfaceForAllTy aa ab) = do putByte bh 0 put_ bh aa put_ bh ab put_ bh (IfaceTyVar ad) = do putByte bh 1 put_ bh ad put_ bh (IfaceAppTy ae af) = do putByte bh 2 put_ bh ae put_ bh af put_ bh (IfaceFunTy af ag ah) = do putByte bh 3 put_ bh af put_ bh ag put_ bh ah put_ bh (IfaceTyConApp tc tys) = do { putByte bh 5; put_ bh tc; put_ bh tys } put_ bh (IfaceCastTy a b) = do { putByte bh 6; put_ bh a; put_ bh b } put_ bh (IfaceCoercionTy a) = do { putByte bh 7; put_ bh a } put_ bh (IfaceTupleTy s i tys) = do { putByte bh 8; put_ bh s; put_ bh i; put_ bh tys } put_ bh (IfaceLitTy n) = do { putByte bh 9; put_ bh n } get bh = do h <- getByte bh case h of 0 -> do aa <- get bh ab <- get bh return (IfaceForAllTy aa ab) 1 -> do ad <- get bh return (IfaceTyVar ad) 2 -> do ae <- get bh af <- get bh return (IfaceAppTy ae af) 3 -> do af <- get bh ag <- get bh ah <- get bh return (IfaceFunTy af ag ah) 5 -> do { tc <- get bh; tys <- get bh ; return (IfaceTyConApp tc tys) } 6 -> do { a <- get bh; b <- get bh ; return (IfaceCastTy a b) } 7 -> do { a <- get bh ; return (IfaceCoercionTy a) } 8 -> do { s <- get bh; i <- get bh; tys <- get bh ; return (IfaceTupleTy s i tys) } _ -> do n <- get bh return (IfaceLitTy n) instance Binary IfaceMCoercion where put_ bh IfaceMRefl = do putByte bh 1 put_ bh (IfaceMCo co) = do putByte bh 2 put_ bh co get bh = do tag <- getByte bh case tag of 1 -> return IfaceMRefl 2 -> do a <- get bh return $ IfaceMCo a _ -> panic ("get IfaceMCoercion " ++ show tag) instance Binary IfaceCoercion where put_ bh (IfaceReflCo a) = do putByte bh 1 put_ bh a put_ bh (IfaceGReflCo a b c) = do putByte bh 2 put_ bh a put_ bh b put_ bh c put_ bh (IfaceFunCo a b c) = do putByte bh 3 put_ bh a put_ bh b put_ bh c put_ bh (IfaceTyConAppCo a b c) = do putByte bh 4 put_ bh a put_ bh b put_ bh c put_ bh (IfaceAppCo a b) = do putByte bh 5 put_ bh a put_ bh b put_ bh (IfaceForAllCo a b c) = do putByte bh 6 put_ bh a put_ bh b put_ bh c put_ bh (IfaceCoVarCo a) = do putByte bh 7 put_ bh a put_ bh (IfaceAxiomInstCo a b c) = do putByte bh 8 put_ bh a put_ bh b put_ bh c put_ bh (IfaceUnivCo a b c d) = do putByte bh 9 put_ bh a put_ bh b put_ bh c put_ bh d put_ bh (IfaceSymCo a) = do putByte bh 10 put_ bh a put_ bh (IfaceTransCo a b) = do putByte bh 11 put_ bh a put_ bh b put_ bh (IfaceNthCo a b) = do putByte bh 12 put_ bh a put_ bh b put_ bh (IfaceLRCo a b) = do putByte bh 13 put_ bh a put_ bh b put_ bh (IfaceInstCo a b) = do putByte bh 14 put_ bh a put_ bh b put_ bh (IfaceKindCo a) = do putByte bh 15 put_ bh a put_ bh (IfaceSubCo a) = do putByte bh 16 put_ bh a put_ bh (IfaceAxiomRuleCo a b) = do putByte bh 17 put_ bh a put_ bh b put_ _ (IfaceFreeCoVar cv) = pprPanic "Can't serialise IfaceFreeCoVar" (ppr cv) put_ _ (IfaceHoleCo cv) = pprPanic "Can't serialise IfaceHoleCo" (ppr cv) -- See Note [Holes in IfaceCoercion] get bh = do tag <- getByte bh case tag of 1 -> do a <- get bh return $ IfaceReflCo a 2 -> do a <- get bh b <- get bh c <- get bh return $ IfaceGReflCo a b c 3 -> do a <- get bh b <- get bh c <- get bh return $ IfaceFunCo a b c 4 -> do a <- get bh b <- get bh c <- get bh return $ IfaceTyConAppCo a b c 5 -> do a <- get bh b <- get bh return $ IfaceAppCo a b 6 -> do a <- get bh b <- get bh c <- get bh return $ IfaceForAllCo a b c 7 -> do a <- get bh return $ IfaceCoVarCo a 8 -> do a <- get bh b <- get bh c <- get bh return $ IfaceAxiomInstCo a b c 9 -> do a <- get bh b <- get bh c <- get bh d <- get bh return $ IfaceUnivCo a b c d 10-> do a <- get bh return $ IfaceSymCo a 11-> do a <- get bh b <- get bh return $ IfaceTransCo a b 12-> do a <- get bh b <- get bh return $ IfaceNthCo a b 13-> do a <- get bh b <- get bh return $ IfaceLRCo a b 14-> do a <- get bh b <- get bh return $ IfaceInstCo a b 15-> do a <- get bh return $ IfaceKindCo a 16-> do a <- get bh return $ IfaceSubCo a 17-> do a <- get bh b <- get bh return $ IfaceAxiomRuleCo a b _ -> panic ("get IfaceCoercion " ++ show tag) instance Binary IfaceUnivCoProv where put_ bh IfaceUnsafeCoerceProv = putByte bh 1 put_ bh (IfacePhantomProv a) = do putByte bh 2 put_ bh a put_ bh (IfaceProofIrrelProv a) = do putByte bh 3 put_ bh a put_ bh (IfacePluginProv a) = do putByte bh 4 put_ bh a get bh = do tag <- getByte bh case tag of 1 -> return $ IfaceUnsafeCoerceProv 2 -> do a <- get bh return $ IfacePhantomProv a 3 -> do a <- get bh return $ IfaceProofIrrelProv a 4 -> do a <- get bh return $ IfacePluginProv a _ -> panic ("get IfaceUnivCoProv " ++ show tag) instance Binary (DefMethSpec IfaceType) where put_ bh VanillaDM = putByte bh 0 put_ bh (GenericDM t) = putByte bh 1 >> put_ bh t get bh = do h <- getByte bh case h of 0 -> return VanillaDM _ -> do { t <- get bh; return (GenericDM t) } instance NFData IfaceType where rnf = \case IfaceFreeTyVar f1 -> f1 `seq` () IfaceTyVar f1 -> rnf f1 IfaceLitTy f1 -> rnf f1 IfaceAppTy f1 f2 -> rnf f1 `seq` rnf f2 IfaceFunTy f1 f2 f3 -> f1 `seq` rnf f2 `seq` rnf f3 IfaceForAllTy f1 f2 -> f1 `seq` rnf f2 IfaceTyConApp f1 f2 -> rnf f1 `seq` rnf f2 IfaceCastTy f1 f2 -> rnf f1 `seq` rnf f2 IfaceCoercionTy f1 -> rnf f1 IfaceTupleTy f1 f2 f3 -> f1 `seq` f2 `seq` rnf f3 instance NFData IfaceTyLit where rnf = \case IfaceNumTyLit f1 -> rnf f1 IfaceStrTyLit f1 -> rnf f1 instance NFData IfaceCoercion where rnf = \case IfaceReflCo f1 -> rnf f1 IfaceGReflCo f1 f2 f3 -> f1 `seq` rnf f2 `seq` rnf f3 IfaceFunCo f1 f2 f3 -> f1 `seq` rnf f2 `seq` rnf f3 IfaceTyConAppCo f1 f2 f3 -> f1 `seq` rnf f2 `seq` rnf f3 IfaceAppCo f1 f2 -> rnf f1 `seq` rnf f2 IfaceForAllCo f1 f2 f3 -> rnf f1 `seq` rnf f2 `seq` rnf f3 IfaceCoVarCo f1 -> rnf f1 IfaceAxiomInstCo f1 f2 f3 -> rnf f1 `seq` rnf f2 `seq` rnf f3 IfaceAxiomRuleCo f1 f2 -> rnf f1 `seq` rnf f2 IfaceUnivCo f1 f2 f3 f4 -> rnf f1 `seq` f2 `seq` rnf f3 `seq` rnf f4 IfaceSymCo f1 -> rnf f1 IfaceTransCo f1 f2 -> rnf f1 `seq` rnf f2 IfaceNthCo f1 f2 -> rnf f1 `seq` rnf f2 IfaceLRCo f1 f2 -> f1 `seq` rnf f2 IfaceInstCo f1 f2 -> rnf f1 `seq` rnf f2 IfaceKindCo f1 -> rnf f1 IfaceSubCo f1 -> rnf f1 IfaceFreeCoVar f1 -> f1 `seq` () IfaceHoleCo f1 -> f1 `seq` () instance NFData IfaceUnivCoProv where rnf x = seq x () instance NFData IfaceMCoercion where rnf x = seq x () instance NFData IfaceOneShot where rnf x = seq x () instance NFData IfaceTyConSort where rnf = \case IfaceNormalTyCon -> () IfaceTupleTyCon arity sort -> rnf arity `seq` sort `seq` () IfaceSumTyCon arity -> rnf arity IfaceEqualityTyCon -> () instance NFData IfaceTyConInfo where rnf (IfaceTyConInfo f s) = f `seq` rnf s instance NFData IfaceTyCon where rnf (IfaceTyCon nm info) = rnf nm `seq` rnf info instance NFData IfaceBndr where rnf = \case IfaceIdBndr id_bndr -> rnf id_bndr IfaceTvBndr tv_bndr -> rnf tv_bndr instance NFData IfaceAppArgs where rnf = \case IA_Nil -> () IA_Arg f1 f2 f3 -> rnf f1 `seq` f2 `seq` rnf f3
sdiehl/ghc
compiler/GHC/Iface/Type.hs
Haskell
bsd-3-clause
76,725
module Module4.Task29 where import Prelude hiding (lookup) class MapLike m where empty :: m k v lookup :: Ord k => k -> m k v -> Maybe v insert :: Ord k => k -> v -> m k v -> m k v delete :: Ord k => k -> m k v -> m k v fromList :: Ord k => [(k,v)] -> m k v fromList [] = empty fromList ((k,v):xs) = insert k v (fromList xs) newtype ArrowMap k v = ArrowMap { getArrowMap :: k -> Maybe v } instance MapLike ArrowMap where empty = ArrowMap $ const Nothing lookup key (ArrowMap map) = map key insert key value (ArrowMap map) = ArrowMap (\k -> if k == key then Just value else map k) delete key (ArrowMap map) = ArrowMap (\k -> if k == key then Nothing else map k)
dstarcev/stepic-haskell
src/Module4/Task29.hs
Haskell
bsd-3-clause
717
module Main where import Hexdump main :: IO () main = hexPrint
wangbj/hexdump
app/Main.hs
Haskell
bsd-3-clause
65
module Valkyria.Client where import Valkyria.Env import Prelude ()
nfjinjing/source-code-server
src/Valkyria/Client.hs
Haskell
bsd-3-clause
71
{-# LANGUAGE PackageImports #-} module Data.Function (module M) where import "base" Data.Function as M
silkapp/base-noprelude
src/Data/Function.hs
Haskell
bsd-3-clause
108
module BCalib.Imports ( module X ) where import Control.Lens as X hiding (Empty) import Data.Atlas.Histogramming as X import Data.Monoid as X hiding (First (..), Last (..), (<>)) import Data.Semigroup as X import Data.TTree as X
cspollard/bcalib
src/BCalib/Imports.hs
Haskell
bsd-3-clause
381
{-# LANGUAGE ViewPatterns, OverloadedStrings #-} module Text.XML.PList ( {-| This module is like `Text.XML.ToJSON', but it handles plist xml file. -} parseXML , xmlToJSON , tokensToJSON , elementToJSON , plistValue , module Text.XML.ToJSON ) where import Control.Monad (liftM) import Data.Text (Text) import qualified Data.Text as T import qualified Data.ByteString.Lazy as L import qualified Data.HashMap.Strict as HM import qualified Data.Vector as V import Data.Aeson (Value(..), FromJSON, fromJSON, Result(Error, Success)) import Data.Attoparsec.Text (parseOnly, number) import Data.Conduit (($=), ($$), MonadThrow(monadThrow)) import qualified Data.Conduit.List as C import Text.XML.ToJSON.Builder (Element(..)) import qualified Text.XML.ToJSON as ToJSON import qualified Text.HTML.TagStream.Text as T import Text.XML.ToJSON hiding (parseXML, xmlToJSON, tokensToJSON, elementToJSON) -- | parse xml to haskell data type by using aeson's `FromJSON'. parseXML :: (MonadThrow m, FromJSON a) => L.ByteString -> m a parseXML s = xmlToJSON s >>= convert where convert v = case fromJSON v of Error err -> monadThrow (JSONParseError err) Success a -> return a -- | Convert plist lazy bytestring to aeson `Value' xmlToJSON :: MonadThrow m => L.ByteString -> m Value xmlToJSON s = liftM (elementToJSON . tokensToElement) $ C.sourceList (L.toChunks s) $= T.tokenStreamBS $$ C.consume -- | Convert plist `Element' to aeson `Value' elementToJSON :: Element -> Value elementToJSON (Element _ _ [("plist", Element _ _ (item : _))]) = plistValue item elementToJSON _ = error "invalid plist root element." -- |Convert plist xml format of `T.Token's to aeson `Value', combining of `tokensToElement' and `elementToJSON' tokensToJSON :: [T.Token] -> Value tokensToJSON = elementToJSON . tokensToElement plistValue :: (Text, Element) -> Value plistValue (t, elm) = case t of "string" -> String (getText elm) "data" -> String (getText elm) "integer" -> parseNumber (getText elm) "float" -> parseNumber (getText elm) "real" -> parseNumber (getText elm) "dict" -> plistObject elm "true" -> Bool True "false" -> Bool False "date" -> error "date support is not implemented" "array" -> Array $ V.fromList $ map plistValue (elChildren elm) _ -> Object $ HM.fromList [("type", String t), ("value", ToJSON.elementToJSON elm)] where parseNumber :: Text -> Value parseNumber "" = Null parseNumber s = either (error . ("parse number failed:"++)) Number $ parseOnly number s plistObject :: Element -> Value plistObject (Element _ _ cs) = Object $ HM.fromList $ mergeKeyValues cs mergeKeyValues :: [(Text, Element)] -> [(Text, Value)] mergeKeyValues xs = loop xs [] where loop [] kv = kv loop ((isKey -> True, getText -> key) : rest) kv = case rest of (item@(isKey -> False, _) : rest') -> loop rest' ((key, plistValue item) : kv) _ -> loop rest ((key, Null) : kv) loop ((tag,_):_) _ = error $ "expect <key> but got <"++T.unpack tag++">" isKey s = s == "key" getText :: Element -> Text getText (Element [] vs []) = T.concat vs getText _ = error "not a text node [getValue]"
yihuang/xml2json
Text/XML/PList.hs
Haskell
bsd-3-clause
3,395
{-# LANGUAGE ScopedTypeVariables #-} import Prelude hiding (sequence, mapM, foldl) import Data.Traversable import Data.Foldable import Control.Monad (void) import Control.Monad.Trans.Either import Control.Monad.IO.Class import qualified Data.Vector as V import qualified Data.Vector.Generic as VG import Data.Vector.Algorithms.Heap (sort) import Options.Applicative import Linear import Control.Lens hiding (argument) import Graphics.Rendering.Chart hiding (Point) import Graphics.Rendering.Chart.Backend.Cairo import Data.Default import Data.Colour import Data.Colour.Names import ModelFit.Model.Named import ModelFit.Types (Point, ptX, ptY, withVar) import ModelFit.Fit import ModelFit.FitExpr import ModelFit.Models.Lifetime import CsvUtils data Opts = Opts { irfPath :: FilePath , fluorPath :: [FilePath] , components :: Int } opts :: Parser Opts opts = Opts <$> strOption (long "irf" <> metavar "FILE" <> help "IRF curve path") <*> many (strArgument (metavar "FILE" <> help "Fluorescence curve path")) <*> option auto (long "components" <> short 'n' <> value 1 <> metavar "N" <> help "Number of components") printing :: EitherT String IO () -> IO () printing action = runEitherT action >>= either print return jiffy :: Double jiffy = 8 dropLast n v = V.take (V.length v - n) v mode :: (VG.Vector v a, Ord a, Eq a) => v a -> Maybe a mode v | VG.null v = Nothing mode v = go (VG.head v', 1) $ VG.tail v' where v' = sorted v sorted :: (VG.Vector v a, Ord a) => v a -> v a sorted v = VG.create $ do v' <- VG.thaw v sort v' return v' go (a,n) v | VG.null v = Just a | n' > n = go (a', n') y | otherwise = go (a, n) y where (x,y) = VG.span (== a') v n' = VG.length x a' = VG.head v sumModels :: (Applicative f, Num a) => [f (b -> a)] -> f (b -> a) sumModels = foldl (\accum m->liftOp (+) <$> accum <*> m) (pure $ const 0) main :: IO () main = printing $ do args <- liftIO $ execParser $ info (helper <*> opts) (fullDesc <> progDesc "Fit fluorescence decays") let withPoissonVar = withVar id irfPts <- V.take 4090 . V.map withPoissonVar <$> readPoints (irfPath args) fluorPts <- mapM (\fname->V.take 3200 . V.map withPoissonVar <$> readPoints fname) (fluorPath args) let Just irfBg = mode $ V.map (^. ptY) $ V.take 1500 irfPts -- HACK let irfHist = V.convert $ V.map (subtract irfBg) $ V.drop offset $ V.map (^. ptY) irfPts offset = 0 --period = round $ 1/80e6 / (jiffy * 1e-12) period = findPeriod irfHist irfLength = round $ 2.0 * realToFrac period liftIO $ putStrLn $ "Period: "++show period liftIO $ putStrLn $ "IRF background: "++show irfBg let irf = mkIrf irfHist irfLength let fitFluor :: String -- ^ Curve name -> [FitExprM Double Double] -- ^ lifetimes -> V.Vector (Point Double Double) -- ^ points -> GlobalFitM Double Double Double (FitDesc Double Double Double) fitFluor name taus pts = do let fluorBg = V.head pts ^. ptY Just fluorAmp = maximumOf (each . ptY) pts fitPts = V.convert $ V.take period pts let component :: Int -> FitExprM Double Double -> FitExprM Double (Double -> Double) component i tau = lifetimeModel <$> p where p = sequenceA $ LifetimeP { _decayTime = tau , _amplitude = param (name++"-amp"++show i) (fluorAmp / 2) } decayModel <- expr $ sumModels $ zipWith component [1..] taus --background <- expr $ const <$> param "bg" fluorBg let background = return $ const 0 convolved <- expr $ convolvedModel irf (V.length pts) jiffy <$> hoist decayModel m <- expr $ liftOp (+) <$> hoist convolved <*> hoist background fit fitPts $ hoist m let (fds, curves, p0, params) = runGlobalFitM $ do taus <- mapM (\i->globalParam ("tau"++show i) (realToFrac $ i*1000)) [1..components args] forM (zip ["curve"++show i | i <- [1..]] fluorPts) $ \(name,pts) -> fitFluor name taus pts let fit = either (error . show) id $ leastSquares curves p0 liftIO $ print $ fmap (flip evalParam p0 . Param) params liftIO $ print $ fmap (flip evalParam fit . Param) params forM_ (zip3 (fluorPath args) fluorPts fds) $ \(fname,pts,fd) -> do let path = fname++".png" ts = V.toList $ V.map (^. ptX) pts liftIO $ void $ renderableToFile def path $ toRenderable $ plotFit ts pts (fitEval fd fit) liftIO $ putStrLn $ "Reduced Chi squared: "++show (reducedChiSquared fd fit) return () plotFit :: forall x y. (Show x, Show y, RealFloat y, Fractional x, PlotValue x, PlotValue y) => [x] -> V.Vector (Point x y) -> (x -> y) -> StackedLayouts x plotFit ts pts fit = def & slayouts_layouts .~ [StackedLayout layout] where layout = def & layout_plots .~ plots & layout_y_axis . laxis_generate .~ autoScaledLogAxis def plots :: [Plot x y] plots = [ toPlot $ def & plot_points_values .~ zip [realToFrac $ jiffy*i | i <- [0..]] (toListOf (each . ptY) pts) & plot_points_style . point_color .~ opaque green & plot_points_title .~ "Observed" , toPlot $ def & plot_lines_values .~ [map (\x->(x, fit x)) ts] & plot_lines_style . line_color .~ opaque red & plot_lines_title .~ "Fit" ]
bgamari/model-fit
LifetimeFit.hs
Haskell
bsd-3-clause
5,723
module Pos.Infra.Slotting.Class ( module X ) where import Pos.Core.Slotting as X
input-output-hk/pos-haskell-prototype
infra/src/Pos/Infra/Slotting/Class.hs
Haskell
mit
106
{-# LANGUAGE CPP, MultiParamTypeClasses, FunctionalDependencies #-} {-# LANGUAGE FlexibleInstances #-} module Language.Haskell.GhcMod.FillSig ( sig , refine , auto ) where import Data.Char (isSymbol) import Data.Function (on) import Data.List (find, nub, sortBy) import qualified Data.Map as M import Data.Maybe (isJust, catMaybes) import Exception (ghandle, SomeException(..)) import GHC (GhcMonad, Id, ParsedModule(..), TypecheckedModule(..), DynFlags, SrcSpan, Type, GenLocated(L)) import qualified GHC as G import qualified Name as G import qualified Language.Haskell.GhcMod.Gap as Gap import Language.Haskell.GhcMod.Convert import Language.Haskell.GhcMod.Monad import Language.Haskell.GhcMod.SrcUtils import Language.Haskell.GhcMod.Types import Outputable (PprStyle) import qualified Type as Ty import qualified HsBinds as Ty import qualified Class as Ty import qualified Var as Ty import qualified HsPat as Ty import qualified Language.Haskell.Exts.Annotated as HE import Djinn.GHC ---------------------------------------------------------------- -- INTIAL CODE FROM FUNCTION OR INSTANCE SIGNATURE ---------------------------------------------------------------- -- Possible signatures we can find: function or instance data SigInfo = Signature SrcSpan [G.RdrName] (G.HsType G.RdrName) | InstanceDecl SrcSpan G.Class | TyFamDecl SrcSpan G.RdrName TyFamType {- True if closed -} [G.RdrName] -- Signature for fallback operation via haskell-src-exts data HESigInfo = HESignature HE.SrcSpan [HE.Name HE.SrcSpanInfo] (HE.Type HE.SrcSpanInfo) | HEFamSignature HE.SrcSpan TyFamType (HE.Name HE.SrcSpanInfo) [HE.Name HE.SrcSpanInfo] data TyFamType = Closed | Open | Data initialTyFamString :: TyFamType -> (String, String) initialTyFamString Closed = ("instance", "") initialTyFamString Open = ("function", "type instance ") initialTyFamString Data = ("function", "data instance ") -- | Create a initial body from a signature. sig :: IOish m => FilePath -- ^ A target file. -> Int -- ^ Line number. -> Int -- ^ Column number. -> GhcModT m String sig file lineNo colNo = ghandle handler body where body = inModuleContext file $ \dflag style -> do opt <- options modSum <- Gap.fileModSummary file whenFound opt (getSignature modSum lineNo colNo) $ \s -> case s of Signature loc names ty -> ("function", fourInts loc, map (initialBody dflag style ty) names) InstanceDecl loc cls -> ("instance", fourInts loc, map (\x -> initialBody dflag style (G.idType x) x) (Ty.classMethods cls)) TyFamDecl loc name flavour vars -> let (rTy, initial) = initialTyFamString flavour in (rTy, fourInts loc, [initial ++ initialFamBody dflag style name vars]) handler (SomeException _) = do opt <- options -- Code cannot be parsed by ghc module -- Fallback: try to get information via haskell-src-exts whenFound opt (getSignatureFromHE file lineNo colNo) $ \x -> case x of HESignature loc names ty -> ("function", fourIntsHE loc, map (initialBody undefined undefined ty) names) HEFamSignature loc flavour name vars -> let (rTy, initial) = initialTyFamString flavour in (rTy, fourIntsHE loc, [initial ++ initialFamBody undefined undefined name vars]) ---------------------------------------------------------------- -- a. Code for getting the information -- Get signature from ghc parsing and typechecking getSignature :: GhcMonad m => G.ModSummary -> Int -> Int -> m (Maybe SigInfo) getSignature modSum lineNo colNo = do p@ParsedModule{pm_parsed_source = ps} <- G.parseModule modSum -- Inspect the parse tree to find the signature case listifyParsedSpans ps (lineNo, colNo) :: [G.LHsDecl G.RdrName] of [L loc (G.SigD (Ty.TypeSig names (L _ ty)))] -> -- We found a type signature return $ Just $ Signature loc (map G.unLoc names) ty [L _ (G.InstD _)] -> do -- We found an instance declaration TypecheckedModule{tm_renamed_source = Just tcs ,tm_checked_module_info = minfo} <- G.typecheckModule p let lst = listifyRenamedSpans tcs (lineNo, colNo) case Gap.getClass lst of Just (clsName,loc) -> obtainClassInfo minfo clsName loc _ -> return Nothing #if __GLASGOW_HASKELL__ >= 708 [L loc (G.TyClD (G.FamDecl (G.FamilyDecl info (L _ name) (G.HsQTvs _ vars) _)))] -> do #elif __GLASGOW_HASKELL__ >= 706 [L loc (G.TyClD (G.TyFamily info (L _ name) (G.HsQTvs _ vars) _))] -> do #else [L loc (G.TyClD (G.TyFamily info (L _ name) vars _))] -> do #endif #if __GLASGOW_HASKELL__ >= 708 let flavour = case info of G.ClosedTypeFamily _ -> Closed G.OpenTypeFamily -> Open G.DataFamily -> Data #else let flavour = case info of -- Closed type families where introduced in GHC 7.8 G.TypeFamily -> Open G.DataFamily -> Data #endif #if __GLASGOW_HASKELL__ >= 706 getTyFamVarName x = case x of L _ (G.UserTyVar n) -> n L _ (G.KindedTyVar n _) -> n #else getTyFamVarName x = case x of -- In GHC 7.4, HsTyVarBndr's have an extra arg L _ (G.UserTyVar n _) -> n L _ (G.KindedTyVar n _ _) -> n #endif in return $ Just (TyFamDecl loc name flavour $ map getTyFamVarName vars) _ -> return Nothing where obtainClassInfo :: GhcMonad m => G.ModuleInfo -> G.Name -> SrcSpan -> m (Maybe SigInfo) obtainClassInfo minfo clsName loc = do tyThing <- G.modInfoLookupName minfo clsName return $ do Ty.ATyCon clsCon <- tyThing -- In Maybe cls <- G.tyConClass_maybe clsCon return $ InstanceDecl loc cls -- Get signature from haskell-src-exts getSignatureFromHE :: GhcMonad m => FilePath -> Int -> Int -> m (Maybe HESigInfo) getSignatureFromHE file lineNo colNo = do presult <- liftIO $ HE.parseFile file return $ case presult of HE.ParseOk (HE.Module _ _ _ _ mdecls) -> do decl <- find (typeSigInRangeHE lineNo colNo) mdecls case decl of HE.TypeSig (HE.SrcSpanInfo s _) names ty -> return $ HESignature s names ty HE.TypeFamDecl (HE.SrcSpanInfo s _) declHead _ -> let (name, tys) = dHeadTyVars declHead in return $ HEFamSignature s Open name (map cleanTyVarBind tys) HE.DataFamDecl (HE.SrcSpanInfo s _) _ declHead _ -> let (name, tys) = dHeadTyVars declHead in return $ HEFamSignature s Open name (map cleanTyVarBind tys) _ -> fail "" _ -> Nothing where cleanTyVarBind (HE.KindedVar _ n _) = n cleanTyVarBind (HE.UnkindedVar _ n) = n #if MIN_VERSION_haskell_src_exts(1,16,0) dHeadTyVars :: HE.DeclHead l -> (HE.Name l, [HE.TyVarBind l]) dHeadTyVars (HE.DHead _ name) = (name, []) dHeadTyVars (HE.DHApp _ r ty) = (++[ty]) `fmap` (dHeadTyVars r) dHeadTyVars (HE.DHInfix _ ty name) = (name, [ty]) dHeadTyVars (HE.DHParen _ r) = dHeadTyVars r #else dHeadTyVars :: HE.DeclHead l -> (HE.Name l, [HE.TyVarBind l]) dHeadTyVars (HE.DHead _ n tys) = (n, tys) #endif ---------------------------------------------------------------- -- b. Code for generating initial code -- A list of function arguments, and whether they are functions or normal -- arguments is built from either a function signature or an instance signature data FnArg = FnArgFunction | FnArgNormal | FnExplicitName String initialBody :: FnArgsInfo ty name => DynFlags -> PprStyle -> ty -> name -> String initialBody dflag style ty name = initialBody' (getFnName dflag style name) (getFnArgs ty) initialBody' :: String -> [FnArg] -> String initialBody' fname args = initialHead fname args ++ " = " ++ n ++ "_body" where n = if isSymbolName fname then "" else '_':fname initialFamBody :: FnArgsInfo ty name => DynFlags -> PprStyle -> name -> [name] -> String initialFamBody dflag style name args = initialHead fnName fnArgs ++ " = ()" where fnName = getFnName dflag style name fnArgs = map (FnExplicitName . getFnName dflag style) args initialHead :: String -> [FnArg] -> String initialHead fname args = case initialBodyArgs args infiniteVars infiniteFns of [] -> fname arglist -> if isSymbolName fname then head arglist ++ " " ++ fname ++ " " ++ unwords (tail arglist) else fname ++ " " ++ unwords arglist initialBodyArgs :: [FnArg] -> [String] -> [String] -> [String] initialBodyArgs [] _ _ = [] initialBodyArgs (FnArgFunction:xs) vs (f:fs) = f : initialBodyArgs xs vs fs initialBodyArgs (FnArgNormal:xs) (v:vs) fs = v : initialBodyArgs xs vs fs initialBodyArgs (FnExplicitName n:xs) vs fs = n : initialBodyArgs xs vs fs initialBodyArgs _ _ _ = error "initialBodyArgs: This should never happen" -- Lists are infinite initialHead1 :: String -> [FnArg] -> [String] -> String initialHead1 fname args elts = case initialBodyArgs1 args elts of [] -> fname arglist -> if isSymbolName fname then head arglist ++ " " ++ fname ++ " " ++ unwords (tail arglist) else fname ++ " " ++ unwords arglist initialBodyArgs1 :: [FnArg] -> [String] -> [String] initialBodyArgs1 args elts = take (length args) elts -- Getting the initial body of function and instances differ -- This is because for functions we only use the parsed file -- (so the full file doesn't have to be type correct) -- but for instances we need to get information about the class class FnArgsInfo ty name | ty -> name, name -> ty where getFnName :: DynFlags -> PprStyle -> name -> String getFnArgs :: ty -> [FnArg] instance FnArgsInfo (G.HsType G.RdrName) (G.RdrName) where getFnName dflag style name = showOccName dflag style $ Gap.occName name getFnArgs (G.HsForAllTy _ _ _ (L _ iTy)) = getFnArgs iTy getFnArgs (G.HsParTy (L _ iTy)) = getFnArgs iTy getFnArgs (G.HsFunTy (L _ lTy) (L _ rTy)) = (if fnarg lTy then FnArgFunction else FnArgNormal):getFnArgs rTy where fnarg ty = case ty of (G.HsForAllTy _ _ _ (L _ iTy)) -> fnarg iTy (G.HsParTy (L _ iTy)) -> fnarg iTy (G.HsFunTy _ _) -> True _ -> False getFnArgs _ = [] instance FnArgsInfo (HE.Type HE.SrcSpanInfo) (HE.Name HE.SrcSpanInfo) where getFnName _ _ (HE.Ident _ s) = s getFnName _ _ (HE.Symbol _ s) = s getFnArgs (HE.TyForall _ _ _ iTy) = getFnArgs iTy getFnArgs (HE.TyParen _ iTy) = getFnArgs iTy getFnArgs (HE.TyFun _ lTy rTy) = (if fnarg lTy then FnArgFunction else FnArgNormal):getFnArgs rTy where fnarg ty = case ty of (HE.TyForall _ _ _ iTy) -> fnarg iTy (HE.TyParen _ iTy) -> fnarg iTy (HE.TyFun _ _ _) -> True _ -> False getFnArgs _ = [] instance FnArgsInfo Type Id where getFnName dflag style method = showOccName dflag style $ G.getOccName method getFnArgs = getFnArgs' . Ty.dropForAlls where getFnArgs' ty | Just (lTy,rTy) <- Ty.splitFunTy_maybe ty = maybe (if Ty.isPredTy lTy then getFnArgs' rTy else FnArgNormal:getFnArgs' rTy) (\_ -> FnArgFunction:getFnArgs' rTy) $ Ty.splitFunTy_maybe lTy getFnArgs' ty | Just (_,iTy) <- Ty.splitForAllTy_maybe ty = getFnArgs' iTy getFnArgs' _ = [] -- Infinite supply of variable and function variable names infiniteVars, infiniteFns :: [String] infiniteVars = infiniteSupply ["x","y","z","t","u","v","w"] infiniteFns = infiniteSupply ["f","g","h"] infiniteSupply :: [String] -> [String] infiniteSupply initialSupply = initialSupply ++ concatMap (\n -> map (\v -> v ++ show n) initialSupply) ([1 .. ] :: [Integer]) -- Check whether a String is a symbol name isSymbolName :: String -> Bool isSymbolName (c:_) = c `elem` "!#$%&*+./<=>?@\\^|-~" || isSymbol c isSymbolName [] = error "This should never happen" ---------------------------------------------------------------- -- REWRITE A HOLE / UNDEFINED VIA A FUNCTION ---------------------------------------------------------------- refine :: IOish m => FilePath -- ^ A target file. -> Int -- ^ Line number. -> Int -- ^ Column number. -> Expression -- ^ A Haskell expression. -> GhcModT m String refine file lineNo colNo expr = ghandle handler body where body = inModuleContext file $ \dflag style -> do opt <- options modSum <- Gap.fileModSummary file p <- G.parseModule modSum tcm@TypecheckedModule{tm_typechecked_source = tcs} <- G.typecheckModule p ety <- G.exprType expr whenFound opt (findVar dflag style tcm tcs lineNo colNo) $ \(loc, name, rty, paren) -> let eArgs = getFnArgs ety rArgs = getFnArgs rty diffArgs' = length eArgs - length rArgs diffArgs = if diffArgs' < 0 then 0 else diffArgs' iArgs = take diffArgs eArgs text = initialHead1 expr iArgs (infinitePrefixSupply name) in (fourInts loc, doParen paren text) handler (SomeException _) = emptyResult =<< options -- Look for the variable in the specified position findVar :: GhcMonad m => DynFlags -> PprStyle -> G.TypecheckedModule -> G.TypecheckedSource -> Int -> Int -> m (Maybe (SrcSpan, String, Type, Bool)) findVar dflag style tcm tcs lineNo colNo = let lst = sortBy (cmp `on` G.getLoc) $ listifySpans tcs (lineNo, colNo) :: [G.LHsExpr Id] in case lst of e@(L _ (G.HsVar i)):others -> do tyInfo <- Gap.getType tcm e let name = getFnName dflag style i if (name == "undefined" || head name == '_') && isJust tyInfo then let Just (s,t) = tyInfo b = case others of -- If inside an App, we need -- parenthesis [] -> False L _ (G.HsApp (L _ a1) (L _ a2)):_ -> isSearchedVar i a1 || isSearchedVar i a2 _ -> False in return $ Just (s, name, t, b) else return Nothing _ -> return Nothing infinitePrefixSupply :: String -> [String] infinitePrefixSupply "undefined" = repeat "undefined" infinitePrefixSupply p = map (\n -> p ++ "_" ++ show n) ([1 ..] :: [Integer]) doParen :: Bool -> String -> String doParen False s = s doParen True s = if ' ' `elem` s then '(':s ++ ")" else s isSearchedVar :: Id -> G.HsExpr Id -> Bool isSearchedVar i (G.HsVar i2) = i == i2 isSearchedVar _ _ = False ---------------------------------------------------------------- -- REFINE AUTOMATICALLY ---------------------------------------------------------------- auto :: IOish m => FilePath -- ^ A target file. -> Int -- ^ Line number. -> Int -- ^ Column number. -> GhcModT m String auto file lineNo colNo = ghandle handler body where body = inModuleContext file $ \dflag style -> do opt <- options modSum <- Gap.fileModSummary file p <- G.parseModule modSum tcm@TypecheckedModule { tm_typechecked_source = tcs , tm_checked_module_info = minfo } <- G.typecheckModule p whenFound' opt (findVar dflag style tcm tcs lineNo colNo) $ \(loc, _name, rty, paren) -> do topLevel <- getEverythingInTopLevel minfo let (f,pats) = getPatsForVariable tcs (lineNo,colNo) -- Remove self function to prevent recursion, and id to trim -- cases filterFn (n,_) = let funName = G.getOccString n recName = G.getOccString (G.getName f) in funName `notElem` recName:notWantedFuns -- Find without using other functions in top-level localBnds = M.unions $ map (\(L _ pat) -> getBindingsForPat pat) pats lbn = filter filterFn (M.toList localBnds) djinnsEmpty <- djinn True (Just minfo) lbn rty (Max 10) 100000 let -- Find with the entire top-level almostEnv = M.toList $ M.union localBnds topLevel env = filter filterFn almostEnv djinns <- djinn True (Just minfo) env rty (Max 10) 100000 return ( fourInts loc , map (doParen paren) $ nub (djinnsEmpty ++ djinns)) handler (SomeException _) = emptyResult =<< options -- Functions we do not want in completions notWantedFuns :: [String] notWantedFuns = ["id", "asTypeOf", "const"] -- Get all things defined in top-level getEverythingInTopLevel :: GhcMonad m => G.ModuleInfo -> m (M.Map G.Name Type) getEverythingInTopLevel m = do let modInfo = tyThingsToInfo (G.modInfoTyThings m) topNames = G.modInfoTopLevelScope m case topNames of Just topNames' -> do topThings <- mapM G.lookupGlobalName topNames' let topThings' = catMaybes topThings topInfo = tyThingsToInfo topThings' return $ M.union modInfo topInfo Nothing -> return modInfo tyThingsToInfo :: [Ty.TyThing] -> M.Map G.Name Type tyThingsToInfo [] = M.empty tyThingsToInfo (G.AnId i : xs) = M.insert (G.getName i) (Ty.varType i) (tyThingsToInfo xs) -- Getting information about constructors is not needed -- because they will be added by djinn-ghc when traversing types -- #if __GLASGOW_HASKELL__ >= 708 -- tyThingToInfo (G.AConLike (G.RealDataCon con)) = return [(Ty.dataConName con, Ty.dataConUserType con)] -- #else -- tyThingToInfo (G.AConLike con) = return [(Ty.dataConName con, Ty.dataConUserType con)] -- #endif tyThingsToInfo (_:xs) = tyThingsToInfo xs -- Find the Id of the function and the pattern where the hole is located getPatsForVariable :: G.TypecheckedSource -> (Int,Int) -> (Id, [Ty.LPat Id]) getPatsForVariable tcs (lineNo, colNo) = let (L _ bnd:_) = sortBy (cmp `on` G.getLoc) $ listifySpans tcs (lineNo, colNo) :: [G.LHsBind Id] in case bnd of G.PatBind { Ty.pat_lhs = L ploc pat } -> case pat of Ty.ConPatIn (L _ i) _ -> (i, [L ploc pat]) _ -> (error "This should never happen", []) G.FunBind { Ty.fun_id = L _ funId } -> let m = sortBy (cmp `on` G.getLoc) $ listifySpans tcs (lineNo, colNo) #if __GLASGOW_HASKELL__ >= 708 :: [G.LMatch Id (G.LHsExpr Id)] #else :: [G.LMatch Id] #endif (L _ (G.Match pats _ _):_) = m in (funId, pats) _ -> (error "This should never happen", []) getBindingsForPat :: Ty.Pat Id -> M.Map G.Name Type getBindingsForPat (Ty.VarPat i) = M.singleton (G.getName i) (Ty.varType i) getBindingsForPat (Ty.LazyPat (L _ l)) = getBindingsForPat l getBindingsForPat (Ty.BangPat (L _ b)) = getBindingsForPat b getBindingsForPat (Ty.AsPat (L _ a) (L _ i)) = M.insert (G.getName a) (Ty.varType a) (getBindingsForPat i) #if __GLASGOW_HASKELL__ >= 708 getBindingsForPat (Ty.ListPat l _ _) = M.unions $ map (\(L _ i) -> getBindingsForPat i) l #else getBindingsForPat (Ty.ListPat l _) = M.unions $ map (\(L _ i) -> getBindingsForPat i) l #endif getBindingsForPat (Ty.TuplePat l _ _) = M.unions $ map (\(L _ i) -> getBindingsForPat i) l getBindingsForPat (Ty.PArrPat l _) = M.unions $ map (\(L _ i) -> getBindingsForPat i) l getBindingsForPat (Ty.ViewPat _ (L _ i) _) = getBindingsForPat i getBindingsForPat (Ty.SigPatIn (L _ i) _) = getBindingsForPat i getBindingsForPat (Ty.SigPatOut (L _ i) _) = getBindingsForPat i getBindingsForPat (Ty.ConPatIn (L _ i) d) = M.insert (G.getName i) (Ty.varType i) (getBindingsForRecPat d) getBindingsForPat (Ty.ConPatOut { Ty.pat_args = d }) = getBindingsForRecPat d getBindingsForPat _ = M.empty getBindingsForRecPat :: Ty.HsConPatDetails Id -> M.Map G.Name Type getBindingsForRecPat (Ty.PrefixCon args) = M.unions $ map (\(L _ i) -> getBindingsForPat i) args getBindingsForRecPat (Ty.InfixCon (L _ a1) (L _ a2)) = M.union (getBindingsForPat a1) (getBindingsForPat a2) getBindingsForRecPat (Ty.RecCon (Ty.HsRecFields { Ty.rec_flds = fields })) = getBindingsForRecFields fields where getBindingsForRecFields [] = M.empty getBindingsForRecFields (Ty.HsRecField {Ty.hsRecFieldArg = (L _ a)}:fs) = M.union (getBindingsForPat a) (getBindingsForRecFields fs)
cabrera/ghc-mod
Language/Haskell/GhcMod/FillSig.hs
Haskell
bsd-3-clause
21,204
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ViewPatterns #-} -- | Parsing command line targets module Stack.Build.Target ( -- * Types ComponentName , UnresolvedComponent (..) , RawTarget (..) , LocalPackageView (..) , SimpleTarget (..) , NeedTargets (..) -- * Parsers , parseRawTarget , parseTargets ) where import Control.Applicative import Control.Arrow (second) import Control.Monad.Catch (MonadCatch, throwM) import Control.Monad.IO.Class import Data.Either (partitionEithers) import Data.Foldable import Data.List.Extra (groupSort) import Data.List.NonEmpty (NonEmpty((:|))) import qualified Data.List.NonEmpty as NonEmpty import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (mapMaybe) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Path import Path.Extra (rejectMissingDir) import Path.IO import Prelude hiding (concat, concatMap) -- Fix redundant import warnings import Stack.Types.PackageIdentifier import Stack.Types.PackageName import Stack.Types.Version import Stack.Types.Config import Stack.Types.Build import Stack.Types.Package -- | The name of a component, which applies to executables, test suites, and benchmarks type ComponentName = Text newtype RawInput = RawInput { unRawInput :: Text } -- | Either a fully resolved component, or a component name that could be -- either an executable, test, or benchmark data UnresolvedComponent = ResolvedComponent !NamedComponent | UnresolvedComponent !ComponentName deriving (Show, Eq, Ord) -- | Raw command line input, without checking against any databases or list of -- locals. Does not deal with directories data RawTarget (a :: RawTargetType) where RTPackageComponent :: !PackageName -> !UnresolvedComponent -> RawTarget a RTComponent :: !ComponentName -> RawTarget a RTPackage :: !PackageName -> RawTarget a RTPackageIdentifier :: !PackageIdentifier -> RawTarget 'HasIdents deriving instance Show (RawTarget a) deriving instance Eq (RawTarget a) deriving instance Ord (RawTarget a) data RawTargetType = HasIdents | NoIdents -- | If this function returns @Nothing@, the input should be treated as a -- directory. parseRawTarget :: Text -> Maybe (RawTarget 'HasIdents) parseRawTarget t = (RTPackageIdentifier <$> parsePackageIdentifierFromString s) <|> (RTPackage <$> parsePackageNameFromString s) <|> (RTComponent <$> T.stripPrefix ":" t) <|> parsePackageComponent where s = T.unpack t parsePackageComponent = case T.splitOn ":" t of [pname, "lib"] | Just pname' <- parsePackageNameFromString (T.unpack pname) -> Just $ RTPackageComponent pname' $ ResolvedComponent CLib [pname, cname] | Just pname' <- parsePackageNameFromString (T.unpack pname) -> Just $ RTPackageComponent pname' $ UnresolvedComponent cname [pname, typ, cname] | Just pname' <- parsePackageNameFromString (T.unpack pname) , Just wrapper <- parseCompType typ -> Just $ RTPackageComponent pname' $ ResolvedComponent $ wrapper cname _ -> Nothing parseCompType t' = case t' of "exe" -> Just CExe "test" -> Just CTest "bench" -> Just CBench _ -> Nothing -- | A view of a local package needed for resolving components data LocalPackageView = LocalPackageView { lpvVersion :: !Version , lpvRoot :: !(Path Abs Dir) , lpvCabalFP :: !(Path Abs File) , lpvComponents :: !(Set NamedComponent) , lpvExtraDep :: !TreatLikeExtraDep } -- | Same as @parseRawTarget@, but also takes directories into account. parseRawTargetDirs :: (MonadIO m, MonadCatch m) => Path Abs Dir -- ^ current directory -> Map PackageName LocalPackageView -> Text -> m (Either Text [(RawInput, RawTarget 'HasIdents)]) parseRawTargetDirs root locals t = case parseRawTarget t of Just rt -> return $ Right [(ri, rt)] Nothing -> do mdir <- forgivingAbsence (resolveDir root (T.unpack t)) >>= rejectMissingDir case mdir of Nothing -> return $ Left $ "Directory not found: " `T.append` t Just dir -> case mapMaybe (childOf dir) $ Map.toList locals of [] -> return $ Left $ "No local directories found as children of " `T.append` t names -> return $ Right $ map ((ri, ) . RTPackage) names where ri = RawInput t childOf dir (name, lpv) = if (dir == lpvRoot lpv || isParentOf dir (lpvRoot lpv)) && not (lpvExtraDep lpv) then Just name else Nothing data SimpleTarget = STUnknown | STNonLocal | STLocalComps !(Set NamedComponent) | STLocalAll deriving (Show, Eq, Ord) resolveIdents :: Map PackageName Version -- ^ snapshot -> Map PackageName Version -- ^ extra deps -> Map PackageName LocalPackageView -> (RawInput, RawTarget 'HasIdents) -> Either Text ((RawInput, RawTarget 'NoIdents), Map PackageName Version) resolveIdents _ _ _ (ri, RTPackageComponent x y) = Right ((ri, RTPackageComponent x y), Map.empty) resolveIdents _ _ _ (ri, RTComponent x) = Right ((ri, RTComponent x), Map.empty) resolveIdents _ _ _ (ri, RTPackage x) = Right ((ri, RTPackage x), Map.empty) resolveIdents snap extras locals (ri, RTPackageIdentifier (PackageIdentifier name version)) = fmap ((ri, RTPackage name), ) newExtras where newExtras = case (Map.lookup name locals, mfound) of -- Error if it matches a local package, pkg idents not -- supported for local. (Just _, _) -> Left $ T.concat [ packageNameText name , " target has a specific version number, but it is a local package." , "\nTo avoid confusion, we will not install the specified version or build the local one." , "\nTo build the local package, specify the target without an explicit version." ] -- If the found version matches, no need for an extra-dep. (_, Just foundVersion) | foundVersion == version -> Right Map.empty -- Otherwise, if there is no specified version or a -- mismatch, add an extra-dep. _ -> Right $ Map.singleton name version mfound = asum (map (Map.lookup name) [extras, snap]) resolveRawTarget :: Map PackageName Version -- ^ snapshot -> Map PackageName Version -- ^ extra deps -> Map PackageName LocalPackageView -> (RawInput, RawTarget 'NoIdents) -> Either Text (PackageName, (RawInput, SimpleTarget)) resolveRawTarget snap extras locals (ri, rt) = go rt where go (RTPackageComponent name ucomp) = case Map.lookup name locals of Nothing -> Left $ T.pack $ "Unknown local package: " ++ packageNameString name Just lpv -> case ucomp of ResolvedComponent comp | comp `Set.member` lpvComponents lpv -> Right (name, (ri, STLocalComps $ Set.singleton comp)) | otherwise -> Left $ T.pack $ concat [ "Component " , show comp , " does not exist in package " , packageNameString name ] UnresolvedComponent comp -> case filter (isCompNamed comp) $ Set.toList $ lpvComponents lpv of [] -> Left $ T.concat [ "Component " , comp , " does not exist in package " , T.pack $ packageNameString name ] [x] -> Right (name, (ri, STLocalComps $ Set.singleton x)) matches -> Left $ T.concat [ "Ambiguous component name " , comp , " for package " , T.pack $ packageNameString name , ": " , T.pack $ show matches ] go (RTComponent cname) = let allPairs = concatMap (\(name, lpv) -> map (name,) $ Set.toList $ lpvComponents lpv) (Map.toList locals) in case filter (isCompNamed cname . snd) allPairs of [] -> Left $ "Could not find a component named " `T.append` cname [(name, comp)] -> Right (name, (ri, STLocalComps $ Set.singleton comp)) matches -> Left $ T.concat [ "Ambiugous component name " , cname , ", matches: " , T.pack $ show matches ] go (RTPackage name) = case Map.lookup name locals of Just _lpv -> Right (name, (ri, STLocalAll)) Nothing -> case Map.lookup name extras of Just _ -> Right (name, (ri, STNonLocal)) Nothing -> case Map.lookup name snap of Just _ -> Right (name, (ri, STNonLocal)) Nothing -> Right (name, (ri, STUnknown)) isCompNamed :: Text -> NamedComponent -> Bool isCompNamed _ CLib = False isCompNamed t1 (CExe t2) = t1 == t2 isCompNamed t1 (CTest t2) = t1 == t2 isCompNamed t1 (CBench t2) = t1 == t2 simplifyTargets :: [(PackageName, (RawInput, SimpleTarget))] -> ([Text], Map PackageName SimpleTarget) simplifyTargets = foldMap go . collect where go :: (PackageName, NonEmpty (RawInput, SimpleTarget)) -> ([Text], Map PackageName SimpleTarget) go (name, (_, st) :| []) = ([], Map.singleton name st) go (name, pairs) = case partitionEithers $ map (getLocalComp . snd) (NonEmpty.toList pairs) of ([], comps) -> ([], Map.singleton name $ STLocalComps $ Set.unions comps) _ -> let err = T.pack $ concat [ "Overlapping targets provided for package " , packageNameString name , ": " , show $ map (unRawInput . fst) (NonEmpty.toList pairs) ] in ([err], Map.empty) collect :: Ord a => [(a, b)] -> [(a, NonEmpty b)] collect = map (second NonEmpty.fromList) . groupSort getLocalComp (STLocalComps comps) = Right comps getLocalComp _ = Left () -- | Need targets, e.g. `stack build` or allow none? data NeedTargets = NeedTargets | AllowNoTargets parseTargets :: (MonadCatch m, MonadIO m) => NeedTargets -- ^ need at least one target -> Bool -- ^ using implicit global project? -> Map PackageName Version -- ^ snapshot -> Map PackageName Version -- ^ extra deps -> Map PackageName LocalPackageView -> Path Abs Dir -- ^ current directory -> [Text] -- ^ command line targets -> m (Map PackageName Version, Map PackageName SimpleTarget) parseTargets needTargets implicitGlobal snap extras locals currDir textTargets' = do let nonExtraDeps = Map.keys $ Map.filter (not . lpvExtraDep) locals textTargets = if null textTargets' then map (T.pack . packageNameString) nonExtraDeps else textTargets' erawTargets <- mapM (parseRawTargetDirs currDir locals) textTargets let (errs1, rawTargets) = partitionEithers erawTargets (errs2, unzip -> (rawTargets', newExtras)) = partitionEithers $ map (resolveIdents snap extras locals) $ concat rawTargets (errs3, targetTypes) = partitionEithers $ map (resolveRawTarget snap extras locals) rawTargets' (errs4, targets) = simplifyTargets targetTypes errs = concat [errs1, errs2, errs3, errs4] if null errs then if Map.null targets then case needTargets of AllowNoTargets -> return (Map.empty, Map.empty) NeedTargets | null textTargets' && implicitGlobal -> throwM $ TargetParseException ["The specified targets matched no packages.\nPerhaps you need to run 'stack init'?"] | null textTargets' && null nonExtraDeps -> throwM $ TargetParseException ["The project contains no local packages (packages not marked with 'extra-dep')"] | otherwise -> throwM $ TargetParseException ["The specified targets matched no packages"] else return (Map.unions newExtras, targets) else throwM $ TargetParseException errs
AndrewRademacher/stack
src/Stack/Build/Target.hs
Haskell
bsd-3-clause
13,848
{-#LANGUAGE ForeignFunctionInterface #-} module Cudd.GC ( cuddEnableGarbageCollection, cuddDisableGarbageCollection, cuddGarbageCollectionEnabled, c_preGCHook_sample, c_postGCHook_sample, regPreGCHook, regPostGCHook ) where import System.IO import Foreign import Foreign.Ptr import Foreign.C.Types import Foreign.C.String import Foreign.ForeignPtr import Control.Monad import Control.Monad.ST import Control.Monad.ST.Unsafe import Cudd.Hook import Cudd.C import Cudd.Imperative foreign import ccall safe "Cudd_EnableGarbageCollection" c_cuddEnableGarbageCollection :: Ptr CDDManager -> IO () cuddEnableGarbageCollection :: DDManager s u -> ST s () cuddEnableGarbageCollection (DDManager m) = unsafeIOToST $ c_cuddEnableGarbageCollection m foreign import ccall safe "Cudd_DisableGarbageCollection" c_cuddDisableGarbageCollection :: Ptr CDDManager -> IO () cuddDisableGarbageCollection :: DDManager s u -> ST s () cuddDisableGarbageCollection (DDManager m) = unsafeIOToST $ c_cuddDisableGarbageCollection m foreign import ccall safe "Cudd_GarbageCollectionEnabled" c_cuddGarbageCollectionEnabled :: Ptr CDDManager -> IO CInt cuddGarbageCollectionEnabled :: DDManager s u -> ST s Int cuddGarbageCollectionEnabled (DDManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddGarbageCollectionEnabled m foreign import ccall safe "&preGCHook_sample" c_preGCHook_sample :: HookFP foreign import ccall safe "&postGCHook_sample" c_postGCHook_sample :: HookFP regPreGCHook :: DDManager s u -> HookFP -> ST s Int regPreGCHook m func = cuddAddHook m func CuddPreGcHook regPostGCHook :: DDManager s u -> HookFP -> ST s Int regPostGCHook m func = cuddAddHook m func CuddPostGcHook
maweki/haskell_cudd
Cudd/GC.hs
Haskell
bsd-3-clause
1,715
-- | Process utilities module Haskus.System.Process ( threadDelaySec , threadDelayMilliSec , threadDelayMicroSec , threadWaitRead , threadWaitWrite , yield , sysFork ) where import Haskus.System.Sys import Haskus.System.Linux.Handle import Haskus.Utils.Flow import Haskus.Format.Text (Text) import System.Posix.Types (Fd(..)) import qualified Control.Concurrent as CC -- | Delay the thread (seconds) threadDelaySec :: MonadIO m => Word -> m () threadDelaySec = threadDelayMicroSec . (*1000000) -- | Delay the thread (milliseconds) threadDelayMilliSec :: MonadIO m => Word -> m () threadDelayMilliSec = threadDelayMicroSec . (*1000) -- | Delay the thread (microseconds) threadDelayMicroSec :: MonadIO m => Word -> m () threadDelayMicroSec = liftIO . CC.threadDelay . fromIntegral -- | Wait until a handle is readable threadWaitRead :: MonadIO m => Handle -> m () threadWaitRead h = liftIO (CC.threadWaitRead (handleToFd h)) -- | Wait until a handle is writeable threadWaitWrite :: MonadIO m => Handle -> m () threadWaitWrite h = liftIO (CC.threadWaitWrite (handleToFd h)) -- | Convert a handle into an Fd handleToFd :: Handle -> Fd handleToFd (Handle fd) = Fd (fromIntegral fd) -- | Switch to another thread cooperatively yield :: MonadIO m => m () yield = liftIO CC.yield -- | Fork a thread sysFork :: Text -> Sys () -> Sys () sysFork name f = do act <- forkSys name f void $ liftIO $ CC.forkIO act
hsyl20/ViperVM
haskus-system/src/lib/Haskus/System/Process.hs
Haskell
bsd-3-clause
1,439
{-# LANGUAGE OverloadedStrings, CPP #-} -- | High-ish level bindings to the HTML5 audio tag and JS API. module Haste.Audio ( module Events, Audio, AudioSettings (..), AudioType (..), AudioSource (..), AudioPreload (..), AudioState (..), Seek (..), defaultAudioSettings, mkSource, newAudio, setSource, getState, setMute, isMute, toggleMute, setLooping, isLooping, toggleLooping, getVolume, setVolume, modVolume, play, pause, stop, togglePlaying, seek, getDuration, getCurrentTime ) where import Haste.Audio.Events as Events import Haste.DOM.JSString import Haste.Foreign import Haste.JSType import Haste.Prim #if __GLASGOW_HASKELL__ < 710 import Control.Applicative #endif import Control.Monad import Control.Monad.IO.Class import Data.String -- | Represents an audio player. data Audio = Audio Elem instance IsElem Audio where elemOf (Audio e) = e fromElem e = do tn <- getProp e "tagName" return $ case tn of "AUDIO" -> Just $ Audio e _ -> Nothing data AudioState = Playing | Paused | Ended deriving (Show, Eq) data AudioType = MP3 | OGG | WAV deriving (Show, Eq) data AudioSource = AudioSource !AudioType !JSString deriving (Show, Eq) data AudioPreload = None | Metadata | Auto deriving Eq data Seek = Start | End | Seconds Double deriving Eq instance JSType AudioPreload where toJSString None = "none" toJSString Metadata = "metadata" toJSString Auto = "auto" fromJSString "none" = Just None fromJSString "metadata" = Just Metadata fromJSString "auto" = Just Auto fromJSString _ = Nothing data AudioSettings = AudioSettings { -- | Show controls? -- Default: False audioControls :: !Bool, -- | Immediately start playing? -- Default: False audioAutoplay :: !Bool, -- | Initially looping? -- Default: False audioLooping :: !Bool, -- | How much audio to preload. -- Default: Auto audioPreload :: !AudioPreload, -- | Initially muted? -- Default: False audioMuted :: !Bool, -- | Initial volume -- Default: 0 audioVolume :: !Double } defaultAudioSettings :: AudioSettings defaultAudioSettings = AudioSettings { audioControls = False, audioAutoplay = False, audioLooping = False, audioPreload = Auto, audioMuted = False, audioVolume = 0 } -- | Create an audio source with automatically detected media type, based on -- the given URL's file extension. -- Returns Nothing if the given URL has an unrecognized media type. mkSource :: JSString -> Maybe AudioSource mkSource url = case take 3 $ reverse $ fromJSStr url of "3pm" -> Just $ AudioSource MP3 url "ggo" -> Just $ AudioSource OGG url "vaw" -> Just $ AudioSource WAV url _ -> Nothing instance IsString AudioSource where fromString s = case mkSource $ Data.String.fromString s of Just src -> src _ -> error $ "Not a valid audio source: " ++ s mimeStr :: AudioType -> JSString mimeStr MP3 = "audio/mpeg" mimeStr OGG = "audio/ogg" mimeStr WAV = "audio/wav" -- | Create a new audio element. newAudio :: MonadIO m => AudioSettings -> [AudioSource] -> m Audio newAudio cfg sources = liftIO $ do srcs <- forM sources $ \(AudioSource t url) -> do newElem "source" `with` ["type" =: mimeStr t, "src" =: toJSString url] Audio <$> newElem "audio" `with` [ "controls" =: falseAsEmpty (audioControls cfg), "autoplay" =: falseAsEmpty (audioAutoplay cfg), "loop" =: falseAsEmpty (audioLooping cfg), "muted" =: falseAsEmpty (audioMuted cfg), "volume" =: toJSString (audioVolume cfg), "preload" =: toJSString (audioPreload cfg), children srcs ] -- | Returns "true" or "", depending on the given boolean. falseAsEmpty :: Bool -> JSString falseAsEmpty True = "true" falseAsEmpty _ = "" -- | (Un)mute the given audio object. setMute :: MonadIO m => Audio -> Bool -> m () setMute (Audio e) = setAttr e "muted" . falseAsEmpty -- | Is the given audio object muted? isMute :: MonadIO m => Audio -> m Bool isMute (Audio e) = liftIO $ maybe False id . fromJSString <$> getProp e "muted" -- | Mute/unmute. toggleMute :: MonadIO m => Audio -> m () toggleMute a = isMute a >>= setMute a . not -- | Set whether the given sound should loop upon completion or not. setLooping :: MonadIO m => Audio -> Bool -> m () setLooping (Audio e) = setAttr e "loop" . falseAsEmpty -- | Is the given audio object looping? isLooping :: MonadIO m => Audio -> m Bool isLooping (Audio e) = liftIO $ maybe False id . fromJSString <$> getProp e "looping" -- | Toggle looping on/off. toggleLooping :: MonadIO m => Audio -> m () toggleLooping a = isLooping a >>= setLooping a . not -- | Starts playing audio from the given element. play :: MonadIO m => Audio -> m () play a@(Audio e) = do st <- getState a when (st == Ended) $ seek a Start liftIO $ play' e where play' :: Elem -> IO () play' = ffi "(function(x){x.play();})" -- | Get the current state of the given audio object. getState :: MonadIO m => Audio -> m AudioState getState (Audio e) = liftIO $ do ended <- maybe False id . fromJSString <$> getProp e "ended" if ended then return Ended else maybe Playing paused . fromJSString <$> getProp e "paused" where paused True = Paused paused _ = Playing -- | Pause the given audio element. pause :: MonadIO m => Audio -> m () pause (Audio e) = liftIO $ pause' e pause' :: Elem -> IO () pause' = ffi "(function(x){x.pause();})" -- | If playing, stop. Otherwise, start playing. togglePlaying :: MonadIO m => Audio -> m () togglePlaying a = do st <- getState a case st of Playing -> pause a Ended -> seek a Start >> play a Paused -> play a -- | Stop playing a track, and seek back to its beginning. stop :: MonadIO m => Audio -> m () stop a = pause a >> seek a Start -- | Get the volume for the given audio element as a value between 0 and 1. getVolume :: MonadIO m => Audio -> m Double getVolume (Audio e) = liftIO $ maybe 0 id . fromJSString <$> getProp e "volume" -- | Set the volume for the given audio element. The value will be clamped to -- [0, 1]. setVolume :: MonadIO m => Audio -> Double -> m () setVolume (Audio e) = setProp e "volume" . toJSString . clamp -- | Modify the volume for the given audio element. The resulting volume will -- be clamped to [0, 1]. modVolume :: MonadIO m => Audio -> Double -> m () modVolume a diff = getVolume a >>= setVolume a . (+ diff) -- | Clamp a value to [0, 1]. clamp :: Double -> Double clamp = max 0 . min 1 -- | Seek to the specified time. seek :: MonadIO m => Audio -> Seek -> m () seek a@(Audio e) st = liftIO $ do case st of Start -> seek' e 0 End -> getDuration a >>= seek' e Seconds s -> seek' e s where seek' :: Elem -> Double -> IO () seek' = ffi "(function(e,t) {e.currentTime = t;})" -- | Get the duration of the loaded sound, in seconds. getDuration :: MonadIO m => Audio -> m Double getDuration (Audio e) = do dur <- getProp e "duration" case fromJSString dur of Just d -> return d _ -> return 0 -- | Get the current play time of the loaded sound, in seconds. getCurrentTime :: MonadIO m => Audio -> m Double getCurrentTime (Audio e) = do dur <- getProp e "currentTime" case fromJSString dur of Just d -> return d _ -> return 0 -- | Set the source of the given audio element. setSource :: MonadIO m => Audio -> AudioSource -> m () setSource (Audio e) (AudioSource _ url) = setProp e "src" (toJSString url)
akru/haste-compiler
libraries/haste-lib/src/Haste/Audio.hs
Haskell
bsd-3-clause
7,613
{-# LANGUAGE QuasiQuotes #-} module Objc (objcTests) where import Test.Framework import Test.Framework.Providers.HUnit import Test.HUnit (Assertion, (@?=)) import Language.C.Quote.ObjC objcTests :: Test objcTests = testGroup "Objective-C" [ testCase "Objective-C params" objcProp , testCase "Objective-C property" objcDict , testCase "Objective-C method parameters" objcParam , testCase "Objective-C method definition" objcMethodDefinition , testCase "Objective-C classmethod" objcArgumentCls , testCase "Objective-C argument" objcArgument , testCase "Objective-C arguments" objcArguments , testCase "Objective-C varargument" objcVarArgument , testCase "Objective-C literals" objcLits ] where objcDict :: Assertion objcDict = [cexp| @{$dictelems:(elems [("a","b"),("c", "d")])} |] @?= [cexp| @{@"a" : @"b",@"c": @"d"}|] where elems = map (\(k,v) -> [objcdictelem|$exp:(objcLit k) : $exp:(objcLit v)|] ) objcProp :: Assertion objcProp = [cedecl| @interface Foo - (void) foo; $prop:propdec1 $props:propdec2 $prop:propdec3 @end |] @?= [cedecl| @interface Foo - (void) foo; @property (nonatomic, retain) int i; @property (nonatomic, retain) float j; @property (nonatomic, retain) char k; @property (nonatomic) double l; @end |] where propdec n typ = [objcprop|@property ($propattrs:r) $ty:typ $id:n;|] propdec' n typ = [objcprop|@property ($propattr:p) $ty:typ $id:n;|] p = [objcpropattr|nonatomic|] q = [objcpropattr|retain|] r = [p,q] propdec1 = propdec "i" [cty|int|] propdec2 = map (\(n,t) -> propdec n t) [("j", [cty|float|]), ("k", [cty|char|])] propdec3 = propdec' "l" [cty|double|] objcParam :: Assertion objcParam = [cedecl| @interface Foo - (void) $methparams:paramNew ; $methproto:val ; @end |] @?= [cedecl| @interface Foo - (void) foo:(int)str fo:(int)str1; + (int) test1:(int)str2; @end |] where paramNew1 = [objcmethparam|$id:("foo"):(int)str |] paramNew2 = [objcmethparam|fo:(int)str1 |] paramNew3 = [objcmethparam|test1:(int)str2 |] paramNew = [paramNew1, paramNew2] val = [objcmethproto|+ (int) $methparam:paramNew3|] objcMethodDefinition :: Assertion objcMethodDefinition = [cedecl| @implementation fooclass $methdefs:(val) $methdef:(val3) @end |] @?= [cedecl| @implementation fooclass + (int) test1:(int)foo { } - (char) test2:(char)bar { } + (float) test3:(double)baz { } @end |] where val3 = [objcmethdef|+ (float) $methparam:paramNew5 {} |] paramNew5 = [objcmethparam|test3:(double)baz |] val2 = [objcmethdef|+ (int) $methparam:paramNew3 {} |] paramNew3 = [objcmethparam|test1:(int)foo |] val1 = [objcmethdef|- (char) $methparam:paramNew4 {} |] paramNew4 = [objcmethparam|test2:(char)bar |] val = [val2, val1] objcArgumentCls :: Assertion objcArgumentCls = [citem|[somename test];|] @?= [citem|[$recv:(k) $id:("test")];|] where k = [objcmethrecv|somename|] objcArgument :: Assertion objcArgument = [citem|[$recv:(k) $kwarg:(p)];|] @?= [citem|[somename doSome:@"string"];|] where k = [objcmethrecv|somename|] p = [objcarg|doSome:@"string"|] objcArguments :: Assertion objcArguments = [citem|[$recv:(k) $kwargs:(r)];|] @?= [citem|[somename doSome:@"string" doSomeMore:@"moreStrings"];|] where k = [objcmethrecv|somename|] p = [objcarg|doSome:@"string"|] q = [objcarg|doSomeMore:@"moreStrings"|] r = [p,q] objcVarArgument :: Assertion objcVarArgument = [citem|[$recv:(k) $kwarg:(r) $args:(p)];|] @?= [citem|[NSString stringWithFormat:@"A string: %@, a float: %1.2f", @"string", 31415.9265];|] where k = [objcmethrecv|NSString|] r = [objcarg|stringWithFormat:@"A string: %@, a float: %1.2f"|] p = [a, b] a = [cexp|@"string"|] b = [cexp|31415.9265|] objcLits :: Assertion objcLits = [cexp|@[$(objcLit "foo"), $(objcLit True), $(objcLit False), $(objcLit 'a'), nil]|] @?= [cexp|@[@"foo", @YES, @NO, @'a', nil]|]
mwu-tow/language-c-quote
tests/unit/Objc.hs
Haskell
bsd-3-clause
4,607
{-# LANGUAGE CPP #-} -- Vectorise a modules type and class declarations. -- -- This produces new type constructors and family instances top be included in the module toplevel -- as well as bindings for worker functions, dfuns, and the like. module Vectorise.Type.Env ( vectTypeEnv, ) where #include "HsVersions.h" import GhcPrelude import Vectorise.Env import Vectorise.Vect import Vectorise.Monad import Vectorise.Builtins import Vectorise.Type.TyConDecl import Vectorise.Type.Classify import Vectorise.Generic.PADict import Vectorise.Generic.PAMethods import Vectorise.Generic.PData import Vectorise.Generic.Description import Vectorise.Utils import CoreSyn import CoreUtils import CoreUnfold import DataCon import TyCon import CoAxiom import Type import FamInstEnv import Id import MkId import NameEnv import NameSet import UniqFM import OccName import Unique import Util import Outputable import DynFlags import FastString import MonadUtils import Control.Monad import Data.Maybe import Data.List -- Note [Pragmas to vectorise tycons] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- All imported type constructors that are not mapped to a vectorised type in the vectorisation map -- (possibly because the defining module was not compiled with vectorisation) may be used in scalar -- code encapsulated in vectorised code. If a such a type constructor 'T' is a member of the -- 'Scalar' class (and hence also of 'PData' and 'PRepr'), it may also be used in vectorised code, -- where 'T' represents itself, but the representation of 'T' still remains opaque in vectorised -- code (i.e., it can only be used in scalar code). -- -- An example is the treatment of 'Int'. 'Int's can be used in vectorised code and remain unchanged -- by vectorisation. However, the representation of 'Int' by the 'I#' data constructor wrapping an -- 'Int#' is not exposed in vectorised code. Instead, computations involving the representation need -- to be confined to scalar code. -- -- VECTORISE pragmas for type constructors cover four different flavours of vectorising data type -- constructors: -- -- (1) Data type constructor 'T' that together with its constructors 'Cn' may be used in vectorised -- code, where 'T' and the 'Cn' are automatically vectorised in the same manner as data types -- declared in a vectorised module. This includes the case where the vectoriser determines that -- the original representation of 'T' may be used in vectorised code (as it does not embed any -- parallel arrays.) This case is for type constructors that are *imported* from a non- -- vectorised module, but that we want to use with full vectorisation support. -- -- An example is the treatment of 'Ordering' and '[]'. The former remains unchanged by -- vectorisation, whereas the latter is fully vectorised. -- -- 'PData' and 'PRepr' instances are automatically generated by the vectoriser. -- -- Type constructors declared with {-# VECTORISE type T #-} are treated in this manner. -- -- (2) Data type constructor 'T' that may be used in vectorised code, where 'T' is represented by an -- explicitly given 'Tv', but the representation of 'T' is opaque in vectorised code (i.e., the -- constructors of 'T' may not occur in vectorised code). -- -- An example is the treatment of '[::]'. The type '[::]' can be used in vectorised code and is -- vectorised to 'PArray'. However, the representation of '[::]' is not exposed in vectorised -- code. Instead, computations involving the representation need to be confined to scalar code. -- -- 'PData' and 'PRepr' instances need to be explicitly supplied for 'T' (they are not generated -- by the vectoriser). -- -- Type constructors declared with {-# VECTORISE type T = Tv #-} are treated in this manner -- manner. (The vectoriser never treats a type constructor automatically in this manner.) -- -- (3) Data type constructor 'T' that does not contain any parallel arrays and has explicitly -- provided 'PData' and 'PRepr' instances (and maybe also a 'Scalar' instance), which together -- with the type's constructors 'Cn' may be used in vectorised code. The type 'T' and its -- constructors 'Cn' are represented by themselves in vectorised code. -- -- An example is 'Bool', which is represented by itself in vectorised code (as it cannot embed -- any parallel arrays). However, we do not want any automatic generation of class and family -- instances, which is why Case (1) does not apply. -- -- 'PData' and 'PRepr' instances need to be explicitly supplied for 'T' (they are not generated -- by the vectoriser). -- -- Type constructors declared with {-# VECTORISE SCALAR type T #-} are treated in this manner. -- -- (4) Data type constructor 'T' that does not contain any parallel arrays and that, in vectorised -- code, is represented by an explicitly given 'Tv', but the representation of 'T' is opaque in -- vectorised code and 'T' is regarded to be scalar — i.e., it may be used in encapsulated -- scalar subcomputations. -- -- An example is the treatment of '(->)'. Types '(->)' can be used in vectorised code and are -- vectorised to '(:->)'. However, the representation of '(->)' is not exposed in vectorised -- code. Instead, computations involving the representation need to be confined to scalar code -- and may be part of encapsulated scalar computations. -- -- 'PData' and 'PRepr' instances need to be explicitly supplied for 'T' (they are not generated -- by the vectoriser). -- -- Type constructors declared with {-# VECTORISE SCALAR type T = Tv #-} are treated in this -- manner. (The vectoriser never treats a type constructor automatically in this manner.) -- -- In addition, we have also got a single pragma form for type classes: {-# VECTORISE class C #-}. -- It implies that the class type constructor may be used in vectorised code together with its data -- constructor. We generally produce a vectorised version of the data type and data constructor. -- We do not generate 'PData' and 'PRepr' instances for class type constructors. This pragma is the -- default for all type classes declared in a vectorised module, but the pragma can also be used -- explitly on imported classes. -- Note [Vectorising classes] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- We vectorise classes essentially by just vectorising their desugared Core representation, but we -- do generate a 'Class' structure along the way (see 'Vectorise.Type.TyConDecl.vectTyConDecl'). -- -- Here is an example illustrating the mapping — assume -- -- class Num a where -- (+) :: a -> a -> a -- -- It desugars to -- -- data Num a = D:Num { (+) :: a -> a -> a } -- -- which we vectorise to -- -- data V:Num a = D:V:Num { ($v+) :: PArray a :-> PArray a :-> PArray a } -- -- while adding the following entries to the vectorisation map: -- -- tycon : Num --> V:Num -- datacon: D:Num --> D:V:Num -- var : (+) --> ($v+) -- |Vectorise type constructor including class type constructors. -- vectTypeEnv :: [TyCon] -- Type constructors defined in this module -> [CoreVect] -- All 'VECTORISE [SCALAR] type' declarations in this module -> [CoreVect] -- All 'VECTORISE class' declarations in this module -> VM ( [TyCon] -- old TyCons ++ new TyCons , [FamInst] -- New type family instances. , [(Var, CoreExpr)]) -- New top level bindings. vectTypeEnv tycons vectTypeDecls vectClassDecls = do { traceVt "** vectTypeEnv" $ ppr tycons ; let -- {-# VECTORISE type T -#} (ONLY the imported tycons) impVectTyCons = ( [tycon | VectType False tycon Nothing <- vectTypeDecls] ++ [tycon | VectClass tycon <- vectClassDecls]) \\ tycons -- {-# VECTORISE type T = Tv -#} (imported & local tycons with an /RHS/) vectTyConsWithRHS = [ (tycon, rhs) | VectType False tycon (Just rhs) <- vectTypeDecls] -- {-# VECTORISE SCALAR type T = Tv -#} (imported & local tycons with an /RHS/) scalarTyConsWithRHS = [ (tycon, rhs) | VectType True tycon (Just rhs) <- vectTypeDecls] -- {-# VECTORISE SCALAR type T -#} (imported & local /scalar/ tycons without an RHS) scalarTyConsNoRHS = [tycon | VectType True tycon Nothing <- vectTypeDecls] -- Check that is not a VECTORISE SCALAR tycon nor VECTORISE tycons with explicit rhs? vectSpecialTyConNames = mkNameSet . map tyConName $ scalarTyConsNoRHS ++ map fst (vectTyConsWithRHS ++ scalarTyConsWithRHS) notVectSpecialTyCon tc = not $ (tyConName tc) `elemNameSet` vectSpecialTyConNames -- Build a map containing all vectorised type constructor. If the vectorised type -- constructor differs from the original one, then it is mapped to 'True'; if they are -- both the same, then it maps to 'False'. ; vectTyCons <- globalVectTyCons ; let vectTyConBase = mapUFM_Directly isDistinct vectTyCons -- 'True' iff tc /= V[[tc]] isDistinct u tc = u /= getUnique tc vectTyConFlavour = vectTyConBase `plusNameEnv` mkNameEnv [ (tyConName tycon, True) | (tycon, _) <- vectTyConsWithRHS ++ scalarTyConsWithRHS] `plusNameEnv` mkNameEnv [ (tyConName tycon, False) -- original representation | tycon <- scalarTyConsNoRHS] -- Split the list of 'TyCons' into the ones (1) that we must vectorise and those (2) -- that we could, but don't need to vectorise. Type constructors that are not data -- type constructors or use non-Haskell98 features are being dropped. They may not -- appear in vectorised code. (We also drop the local type constructors appearing in a -- VECTORISE SCALAR pragma or a VECTORISE pragma with an explicit right-hand side, as -- these are being handled separately. NB: Some type constructors may be marked SCALAR -- /and/ have an explicit right-hand side.) -- -- Furthermore, 'par_tcs' are those type constructors (converted or not) whose -- definition, directly or indirectly, depends on parallel arrays. Finally, 'drop_tcs' -- are all type constructors that cannot be vectorised. ; parallelTyCons <- (`extendNameSetList` map (tyConName . fst) vectTyConsWithRHS) <$> globalParallelTyCons ; let maybeVectoriseTyCons = filter notVectSpecialTyCon tycons ++ impVectTyCons (conv_tcs, keep_tcs, par_tcs, drop_tcs) = classifyTyCons vectTyConFlavour parallelTyCons maybeVectoriseTyCons ; traceVt " known parallel : " $ ppr parallelTyCons ; traceVt " VECT SCALAR : " $ ppr (scalarTyConsNoRHS ++ map fst scalarTyConsWithRHS) ; traceVt " VECT [class] : " $ ppr impVectTyCons ; traceVt " VECT with rhs : " $ ppr (map fst (vectTyConsWithRHS ++ scalarTyConsWithRHS)) ; traceVt " -- after classification (local and VECT [class] tycons) --" Outputable.empty ; traceVt " reuse : " $ ppr keep_tcs ; traceVt " convert : " $ ppr conv_tcs -- warn the user about unvectorised type constructors ; let explanation = text "(They use unsupported language extensions" $$ text "or depend on type constructors that are" <+> text "not vectorised)" drop_tcs_nosyn = filter (not . isTypeFamilyTyCon) . filter (not . isTypeSynonymTyCon) $ drop_tcs ; unless (null drop_tcs_nosyn) $ emitVt "Warning: cannot vectorise these type constructors:" $ pprQuotedList drop_tcs_nosyn $$ explanation ; mapM_ addParallelTyConAndCons $ par_tcs ++ map fst vectTyConsWithRHS ; let mapping = -- Type constructors that we found we don't need to vectorise and those -- declared VECTORISE SCALAR /without/ an explicit right-hand side, use the same -- representation in both unvectorised and vectorised code; they are not -- abstract. [(tycon, tycon, False) | tycon <- keep_tcs ++ scalarTyConsNoRHS] -- We do the same for type constructors declared VECTORISE SCALAR /without/ -- an explicit right-hand side ++ [(tycon, vTycon, True) | (tycon, vTycon) <- vectTyConsWithRHS ++ scalarTyConsWithRHS] ; syn_tcs <- catMaybes <$> mapM defTyConDataCons mapping -- Vectorise all the data type declarations that we can and must vectorise (enter the -- type and data constructors into the vectorisation map on-the-fly.) ; new_tcs <- vectTyConDecls conv_tcs ; let dumpTc tc vTc = traceVt "---" (ppr tc <+> text "::" <+> ppr (dataConSig tc) $$ ppr vTc <+> text "::" <+> ppr (dataConSig vTc)) dataConSig tc | Just dc <- tyConSingleDataCon_maybe tc = dataConRepType dc | otherwise = panic "dataConSig" ; zipWithM_ dumpTc (filter isClassTyCon conv_tcs) (filter isClassTyCon new_tcs) -- We don't need new representation types for dictionary constructors. The constructors -- are always fully applied, and we don't need to lift them to arrays as a dictionary -- of a particular type always has the same value. ; let orig_tcs = filter (not . isClassTyCon) $ keep_tcs ++ conv_tcs vect_tcs = filter (not . isClassTyCon) $ keep_tcs ++ new_tcs -- Build 'PRepr' and 'PData' instance type constructors and family instances for all -- type constructors with vectorised representations. ; reprs <- mapM tyConRepr vect_tcs ; repr_fis <- zipWith3M buildPReprTyCon orig_tcs vect_tcs reprs ; pdata_fis <- zipWith3M buildPDataTyCon orig_tcs vect_tcs reprs ; pdatas_fis <- zipWith3M buildPDatasTyCon orig_tcs vect_tcs reprs ; let fam_insts = repr_fis ++ pdata_fis ++ pdatas_fis repr_axs = map famInstAxiom repr_fis pdata_tcs = famInstsRepTyCons pdata_fis pdatas_tcs = famInstsRepTyCons pdatas_fis ; updGEnv $ extendFamEnv fam_insts -- Generate workers for the vectorised data constructors, dfuns for the 'PA' instances of -- the vectorised type constructors, and associate the type constructors with their dfuns -- in the global environment. We get back the dfun bindings (which we will subsequently -- inject into the modules toplevel). ; (_, binds) <- fixV $ \ ~(dfuns, _) -> do { defTyConPAs (zipLazy vect_tcs dfuns) -- Query the 'PData' instance type constructors for type constructors that have a -- VECTORISE SCALAR type pragma without an explicit right-hand side (this is Item -- (3) of "Note [Pragmas to vectorise tycons]" above). ; pdata_scalar_tcs <- mapM pdataReprTyConExact scalarTyConsNoRHS -- Build workers for all vectorised data constructors (except abstract ones) ; sequence_ $ zipWith3 vectDataConWorkers (orig_tcs ++ scalarTyConsNoRHS) (vect_tcs ++ scalarTyConsNoRHS) (pdata_tcs ++ pdata_scalar_tcs) -- Build a 'PA' dictionary for all type constructors (except abstract ones & those -- defined with an explicit right-hand side where the dictionary is user-supplied) ; dfuns <- sequence $ zipWith4 buildTyConPADict vect_tcs repr_axs pdata_tcs pdatas_tcs ; binds <- takeHoisted ; return (dfuns, binds) } -- Return the vectorised variants of type constructors as well as the generated instance -- type constructors, family instances, and dfun bindings. ; return ( new_tcs ++ pdata_tcs ++ pdatas_tcs ++ syn_tcs , fam_insts, binds) } where addParallelTyConAndCons tycon = do { addGlobalParallelTyCon tycon ; mapM_ addGlobalParallelVar [ id | dc <- tyConDataCons tycon , AnId id <- dataConImplicitTyThings dc ] -- Ignoring the promoted tycon; hope that's ok } -- Add a mapping from the original to vectorised type constructor to the vectorisation map. -- Unless the type constructor is abstract, also mappings from the original's data constructors -- to the vectorised type's data constructors. -- -- We have three cases: (1) original and vectorised type constructor are the same, (2) the -- name of the vectorised type constructor is canonical (as prescribed by 'mkVectTyConOcc'), or -- (3) the name is not canonical. In the third case, we additionally introduce a type synonym -- with the canonical name that is set equal to the non-canonical name (so that we find the -- right type constructor when reading vectorisation information from interface files). -- defTyConDataCons (origTyCon, vectTyCon, isAbstract) = do { canonName <- mkLocalisedName mkVectTyConOcc origName ; if origName == vectName -- Case (1) || vectName == canonName -- Case (2) then do { defTyCon origTyCon vectTyCon -- T --> vT ; defDataCons -- Ci --> vCi ; return Nothing } else do -- Case (3) { let synTyCon = mkSyn canonName (mkTyConTy vectTyCon) -- type S = vT ; defTyCon origTyCon synTyCon -- T --> S ; defDataCons -- Ci --> vCi ; return $ Just synTyCon } } where origName = tyConName origTyCon vectName = tyConName vectTyCon mkSyn canonName ty = buildSynTyCon canonName [] (typeKind ty) [] ty defDataCons | isAbstract = return () | otherwise = do { MASSERT(tyConDataCons origTyCon `equalLength` tyConDataCons vectTyCon) ; zipWithM_ defDataCon (tyConDataCons origTyCon) (tyConDataCons vectTyCon) } -- Helpers -------------------------------------------------------------------- buildTyConPADict :: TyCon -> CoAxiom Unbranched -> TyCon -> TyCon -> VM Var buildTyConPADict vect_tc prepr_ax pdata_tc pdatas_tc = tyConRepr vect_tc >>= buildPADict vect_tc prepr_ax pdata_tc pdatas_tc -- Produce a custom-made worker for the data constructors of a vectorised data type. This includes -- all data constructors that may be used in vectorised code — i.e., all data constructors of data -- types with 'VECTORISE [SCALAR] type' pragmas with an explicit right-hand side. Also adds a mapping -- from the original to vectorised worker into the vectorisation map. -- -- FIXME: It's not nice that we need create a special worker after the data constructors has -- already been constructed. Also, I don't think the worker is properly added to the data -- constructor. Seems messy. vectDataConWorkers :: TyCon -> TyCon -> TyCon -> VM () vectDataConWorkers orig_tc vect_tc arr_tc = do { traceVt "Building vectorised worker for datatype" (ppr orig_tc) ; bs <- sequence . zipWith3 def_worker (tyConDataCons orig_tc) rep_tys $ zipWith4 mk_data_con (tyConDataCons vect_tc) rep_tys (inits rep_tys) (tail $ tails rep_tys) ; mapM_ (uncurry hoistBinding) bs } where tyvars = tyConTyVars vect_tc var_tys = mkTyVarTys tyvars ty_args = map Type var_tys res_ty = mkTyConApp vect_tc var_tys cons = tyConDataCons vect_tc arity = length cons [arr_dc] = tyConDataCons arr_tc rep_tys = map dataConRepArgTys $ tyConDataCons vect_tc mk_data_con con tys pre post = do dflags <- getDynFlags liftM2 (,) (vect_data_con con) (lift_data_con tys pre post (mkDataConTag dflags con)) sel_replicate len tag | arity > 1 = do rep <- builtin (selReplicate arity) return [rep `mkApps` [len, tag]] | otherwise = return [] vect_data_con con = return $ mkConApp con ty_args lift_data_con tys pre_tys post_tys tag = do len <- builtin liftingContext args <- mapM (newLocalVar (fsLit "xs")) =<< mapM mkPDataType tys sel <- sel_replicate (Var len) tag pre <- mapM emptyPD (concat pre_tys) post <- mapM emptyPD (concat post_tys) return . mkLams (len : args) . wrapFamInstBody arr_tc var_tys . mkConApp arr_dc $ ty_args ++ sel ++ pre ++ map Var args ++ post def_worker data_con arg_tys mk_body = do arity <- polyArity tyvars body <- closedV . inBind orig_worker . polyAbstract tyvars $ \args -> liftM (mkLams (tyvars ++ args) . vectorised) $ buildClosures tyvars [] [] arg_tys res_ty mk_body raw_worker <- mkVectId orig_worker (exprType body) let vect_worker = raw_worker `setIdUnfolding` mkInlineUnfoldingWithArity arity body defGlobalVar orig_worker vect_worker return (vect_worker, body) where orig_worker = dataConWorkId data_con
shlevy/ghc
compiler/vectorise/Vectorise/Type/Env.hs
Haskell
bsd-3-clause
22,699
module Propellor.Gpg where import Control.Applicative import System.IO import System.FilePath import System.Directory import Data.Maybe import Data.List.Utils import Propellor.PrivData.Paths import Propellor.Message import Utility.SafeCommand import Utility.Process import Utility.Monad import Utility.Misc import Utility.Tmp type KeyId = String keyring :: FilePath keyring = privDataDir </> "keyring.gpg" -- Lists the keys in propellor's keyring. listPubKeys :: IO [KeyId] listPubKeys = parse . lines <$> readProcess "gpg" listopts where listopts = useKeyringOpts ++ ["--with-colons", "--list-public-keys"] parse = mapMaybe (keyIdField . split ":") keyIdField ("pub":_:_:_:f:_) = Just f keyIdField _ = Nothing useKeyringOpts :: [String] useKeyringOpts = [ "--options" , "/dev/null" , "--no-default-keyring" , "--keyring", keyring ] addKey :: KeyId -> IO () addKey keyid = exitBool =<< allM (uncurry actionMessage) [ ("adding key to propellor's keyring", addkeyring) , ("staging propellor's keyring", gitadd keyring) , ("updating encryption of any privdata", reencryptprivdata) , ("configuring git signing to use key", gitconfig) , ("committing changes", gitcommit) ] where addkeyring = do createDirectoryIfMissing True privDataDir boolSystem "sh" [ Param "-c" , Param $ "gpg --export " ++ keyid ++ " | gpg " ++ unwords (useKeyringOpts ++ ["--import"]) ] reencryptprivdata = ifM (doesFileExist privDataFile) ( do gpgEncrypt privDataFile =<< gpgDecrypt privDataFile gitadd privDataFile , return True ) gitadd f = boolSystem "git" [ Param "add" , File f ] gitconfig = ifM (snd <$> processTranscript "gpg" ["--list-secret-keys", keyid] Nothing) ( boolSystem "git" [ Param "config" , Param "user.signingkey" , Param keyid ] , do warningMessage $ "Cannot find a secret key for key " ++ keyid ++ ", so not configuring git user.signingkey to use this key." return True ) gitcommit = gitCommit [ File keyring , Param "-m" , Param "propellor addkey" ] -- Adds --gpg-sign if there's a keyring. gpgSignParams :: [CommandParam] -> IO [CommandParam] gpgSignParams ps = ifM (doesFileExist keyring) ( return (ps ++ [Param "--gpg-sign"]) , return ps ) -- Automatically sign the commit if there'a a keyring. gitCommit :: [CommandParam] -> IO Bool gitCommit ps = do ps' <- gpgSignParams ps boolSystem "git" (Param "commit" : ps') gpgDecrypt :: FilePath -> IO String gpgDecrypt f = ifM (doesFileExist f) ( readProcess "gpg" ["--decrypt", f] , return "" ) -- Encrypt file to all keys in propellor's keyring. gpgEncrypt :: FilePath -> String -> IO () gpgEncrypt f s = do keyids <- listPubKeys let opts = [ "--default-recipient-self" , "--armor" , "--encrypt" , "--trust-model", "always" ] ++ concatMap (\k -> ["--recipient", k]) keyids encrypted <- writeReadProcessEnv "gpg" opts Nothing (Just $ flip hPutStr s) Nothing viaTmp writeFile f encrypted
sjfloat/propellor
src/Propellor/Gpg.hs
Haskell
bsd-2-clause
2,962
module MergePullRequest where import qualified Github.PullRequests as Github import Github.Auth import Github.Data main :: IO () main = do mergeResult <- Github.updatePullRequest (GithubOAuth "authtoken") "repoOwner" "repoName" 22 (EditPullRequest { editPullRequestTitle = Just "Brand new title", editPullRequestBody = Nothing, editPullRequestState = Just EditPullRequestStateClosed }) case mergeResult of (Left err) -> putStrLn $ "Error: " ++ (show err) (Right dpr) -> putStrLn . show $ dpr
bitemyapp/github
samples/Pulls/UpdatePull.hs
Haskell
bsd-3-clause
513
{-# OPTIONS_GHC -fwarn-unused-binds #-} module ShouldCompile() where -- Trac #2497; test should compile without language -- pragmas to swith on the forall {-# RULES "id" forall (x :: a). id x = x #-} -- Trac #2213; eq should not be reported as unused eq,beq :: Eq a => a -> a -> Bool eq = (==) -- Used beq = (==) -- Unused {-# RULES "rule 1" forall x y. x == y = y `eq` x #-}
hvr/jhc
regress/tests/1_typecheck/2_pass/ghc/T2497.hs
Haskell
mit
402
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Category -- Copyright : (c) Ashley Yakeley 2007 -- License : BSD-style (see the LICENSE file in the distribution) -- -- Maintainer : ashley@semantic.org -- Stability : experimental -- Portability : portable -- http://hackage.haskell.org/trac/ghc/ticket/1773 module Control.Category where import qualified Prelude infixr 9 . infixr 1 >>>, <<< -- | A class for categories. -- id and (.) must form a monoid. class Category cat where -- | the identity morphism id :: cat a a -- | morphism composition (.) :: cat b c -> cat a b -> cat a c {-# RULES "identity/left" forall p . id . p = p "identity/right" forall p . p . id = p "association" forall p q r . (p . q) . r = p . (q . r) #-} instance Category (->) where id = Prelude.id (.) = (Prelude..) -- | Right-to-left composition (<<<) :: Category cat => cat b c -> cat a b -> cat a c (<<<) = (.) -- | Left-to-right composition (>>>) :: Category cat => cat a b -> cat b c -> cat a c f >>> g = g . f
szatkus/haste-compiler
libraries/ghc-7.8/base/Control/Category.hs
Haskell
bsd-3-clause
1,211
{- | Module : System.JBI.Config Description : Run-time configuration settings Copyright : (c) Ivan Lazar Miljenovic License : MIT Maintainer : Ivan.Miljenovic@gmail.com -} module System.JBI.Config where -------------------------------------------------------------------------------- newtype Config = Config { debugMode :: Bool } deriving (Eq, Show, Read) defaultConfig :: Config defaultConfig = Config { debugMode = False }
ivan-m/jbi
lib/System/JBI/Config.hs
Haskell
mit
467
import System.Environment import System.Exit import System.Process import Data.IORef import Control.Monad import System.Timeout import Data.Maybe import GetFullProgName import Syntax import NarrowingSearch import SearchControl import Check import PrintProof import TPTPSyntax hiding (App, Var, Implies, Forall) import ParseGlue import Parser import Translate import Transform import ProofExport import ProofExportTPTP -- --------------------------------- getProb :: String -> String -> IO (ParseResult [ThfAnnotated]) getProb axiomspath filename = do file <- readFile filename case parse file 1 of FailP err -> return $ FailP err OkP prob -> expand prob where expand [] = return $ OkP [] expand (Include axfile : xs) = do axprob <- getProb axiomspath (axiomspath ++ axfile) case axprob of FailP err -> return $ FailP $ "in " ++ axiomspath ++ axfile ++ ": " ++ err OkP axprob -> do xs <- expand xs case xs of FailP err -> return $ FailP err OkP xs -> return $ OkP (axprob ++ xs) expand (AnnotatedFormula x : xs) = do xs <- expand xs case xs of FailP err -> return $ FailP err OkP xs -> return $ OkP (x : xs) -- --------------------------------- itdeepSearch :: (a -> IO Bool) -> Int -> Int -> (Int -> IO a) -> IO () itdeepSearch stop depth step f = do res <- f depth b <- stop res when (not b) $ itdeepSearch stop (depth + step) step f solveProb :: Bool -> Maybe Int -> Maybe Int -> Problem -> IO (Maybe [(String, MetaProof)]) solveProb saveproofs inter mdepth prob = do prfs <- newIORef [] let doconjs [] = do prfs <- readIORef prfs return $ Just prfs doconjs ((name, conj) : conjs) = do ticks <- newIORef 0 nsol <- newIORef 1 prf <- initMeta let hsol = when saveproofs $ do prfcpy <- expandmetas prf modifyIORef prfs ((name, prfcpy) :) p d = andp (checkProof d [] (cl conj) prf) (sidecontrol prf (SCState {scsCtx = 0, scsHyps = [], scsNewHyp = NewGlobHyps})) stop res = do nsol' <- readIORef nsol return $ nsol' == 0 || res == False ss d di = topSearch (isJust inter) ticks nsol hsol (BIEnv (prGlobHyps prob)) (p d) d di case mdepth of Just depth -> ss depth (depth + 1) >> return () Nothing -> case isJust inter of True -> ss 100000000 (100000000 + 1) >> return () False -> itdeepSearch stop 999 1000 (\d -> ss d 1000) nsol <- readIORef nsol if nsol == 0 then doconjs conjs else return Nothing case inter of Just idx -> doconjs [prConjectures prob !! idx] Nothing -> doconjs (prConjectures prob) -- --------------------------------- data CLArgs = CLArgs { problemfile :: String, fproof :: Bool, finteractive :: Maybe Int, fnotransform :: Bool, fagdaproof :: Bool, ftptpproof :: Bool, ftimeout :: Maybe Int, fcheck :: Bool, fdepth :: Maybe Int, fincludedir :: String, fshowproblem :: Bool } doit args = do tptpprob <- getProb (fincludedir args) (problemfile args) case tptpprob of FailP err -> do szs_status args "Error" "parse error" putStrLn err OkP tptpprob -> do let probname = (reverse . takeWhile (/= '/') . drop 2 . reverse) (problemfile args) prob = translateProb probname tptpprob trprob = transformProb (not (fnotransform args)) prob when (fshowproblem args) $ do when (not (fnotransform args)) $ do pprob <- prProblem prob putStrLn $ "non-transformed problem:\n" ++ pprob ptrprob <- prProblem trprob putStrLn $ "problem:\n" ++ ptrprob case fcheck args of False -> case prConjectures trprob of [] -> szs_status args "Error" "no conjecture to prove" _ -> do res <- solveProb (fproof args || (fagdaproof args && isNothing (finteractive args)) || ftptpproof args) (finteractive args) (fdepth args) trprob case res of Just prfs -> do szs_status args "Theorem" "" -- solution found when (fproof args) $ do putStrLn $ "% SZS output start Proof for " ++ problemfile args putStrLn $ "The transformed problem consists of the following conjectures:" putStrLn $ concatMap (\x -> ' ' : fst x) (reverse prfs) mapM_ (\(name, prf) -> putStrLn ("\nProof for " ++ name ++ ":") >> prProof 0 prf >>= putStrLn ) $ reverse prfs putStrLn $ "% SZS output end Proof for " ++ problemfile args when (fagdaproof args && isNothing (finteractive args)) $ do putStrLn $ "The following top-level files were created:" mapM_ (\(name, prf) -> agdaProof trprob name prf ) $ reverse prfs when (ftptpproof args) $ tptpproof tptpprob prob trprob (reverse prfs) Nothing -> szs_status args "GaveUp" "" -- exhaustive search True -> do when (fshowproblem args) $ putStrLn "checking globhyps:" okhyps <- mapM (\gh -> do res <- runProp (checkForm [] typeBool $ ghForm gh) when (fshowproblem args) $ putStrLn $ ghName gh ++ pres res return $ noerrors res ) (prGlobHyps trprob) when (fshowproblem args) $ putStrLn "checking conjectures:" okconjs <- mapM (\(cname, form) -> do res <- runProp (checkForm [] typeBool form) when (fshowproblem args) $ putStrLn $ cname ++ pres res return $ noerrors res ) (prConjectures trprob) case and (okhyps ++ okconjs) of True -> putStrLn "check OK" False -> putStrLn "check FAILED" where noerrors res = not $ '\"' `elem` res pres res = if '\"' `elem` res then error $ " error: " ++ res else " ok" szs_status args status comment = putStrLn $ "% SZS status " ++ status ++ " for " ++ problemfile args ++ (if null comment then "" else (" : " ++ comment)) main = do args <- getArgs case consume "--safe-mode" args of Nothing -> case ["--help"] == args of False -> case parseargs args of Just args -> case ftimeout args of Nothing -> doit args Just seconds -> do res <- timeout (seconds * 1000000) $ doit args case res of Just () -> return () Nothing -> szs_status args "Timeout" "" Nothing -> do putStrLn "command argument error\n" printusage True -> printusage Just args -> case parseargs args of Nothing -> do putStrLn "command argument error\n" printusage Just pargs -> do prgname <- getFullProgName (exitcode, out, err) <- readProcessWithExitCode prgname args "" case exitcode of ExitSuccess -> return () ExitFailure code -> szs_status pargs "Error" ("program stopped abnormally, exitcode: " ++ show code) putStrLn out putStrLn err parseargs = g (CLArgs {problemfile = "", fproof = False, finteractive = Nothing, fnotransform = False, fagdaproof = False, ftptpproof = False, ftimeout = Nothing, fcheck = False, fdepth = Nothing, fincludedir = "", fshowproblem = False}) where g a [] = if null (problemfile a) then Nothing else Just a g a ("--proof" : xs) = g (a {fproof = True}) xs g a ("--interactive" : n : xs) = g (a {finteractive = Just (read n)}) xs g a ("--no-transform" : xs) = g (a {fnotransform = True}) xs g a ("--agda-proof" : xs) = g (a {fagdaproof = True}) xs g a ("--tptp-proof" : xs) = g (a {ftptpproof = True}) xs g a ("--time-out" : n : xs) = g (a {ftimeout = Just (read n)}) xs g a ("--check" : xs) = g (a {fcheck = True}) xs g a ("--depth" : n : xs) = g (a {fdepth = Just (read n)}) xs g a ("--include-dir" : s : xs) = if null (fincludedir a) then g (a {fincludedir = s}) xs else Nothing g a ("--show-problem" : xs) = g (a {fshowproblem = True}) xs g a (x : xs) = if null (problemfile a) then g (a {problemfile = x}) xs else Nothing consume y [] = Nothing consume y (x : xs) | x == y = Just xs consume y (x : xs) | otherwise = case consume y xs of Just xs -> Just (x : xs) Nothing -> Nothing printusage = putStr $ "usage:\n" ++ "agsyHOL <flags> file <flags>\n" ++ " file is a TPTP THF problem file.\n" ++ " flags:\n" ++ " --safe-mode Catches unhandled errors.\n" ++ " --proof Output a proof (in internal format, one proof for each conjecture\n" ++ " of the transformed problem).\n" ++ " --interactive n Do interactive search for subproblem n (n=0,1,2..).\n" ++ " Use --show-problem to see the list of subproblems.\n" ++ " --no-transform Do not transform problem. (Normally the number of negations is minimized.)\n" ++ " --agda-proof Save agda proof files named Proof-<problem_name>-<conjecture_name>.agda and\n" ++ " Proof-<problem_name>-<conjecture_name>-<nn>.agda in current directory.\n" ++ " In order to check the proof with agda, run it on all files listed in the output.\n" ++ " Note that the agda files in the soundness directory must be in scope.\n" ++ " --time-out n Set timeout in seconds. (default: no time out)\n" ++ " --check Just check the problem for well formedness.\n" ++ " --depth n Set search depth. (default: iterated deepening for auto mode (start depth: 999, step: 1000),\n" ++ " unlimited depth for interactive mode)\n" ++ " --include-dir p Set path to axiom files.\n" ++ " --show-problem Display original and transformed problem in internal format.\n" ++ " Combined with --check also show check failure details.\n" ++ " +RTS .. -RTS Give general ghc run time system options, e.g. -t which outputs time and memory usage information.\n" ++ " --help Show this help.\n"
frelindb/agsyHOL
Main.hs
Haskell
mit
9,758
import qualified System.Environment f s@(x:xs) = x:s sign x | x > 0 = 1 | x == 0 = 0 | x < 0 = -1 test (x:xs) | x == -1 = True | x > 0 = False test [] = False testc xs = case xs of (x:xs) -> x [] -> 0 foo xs = case xs of (x:xs) -> x [] -> [] bar :: Int -> Either [Char] Int bar x = if x > 2 then Right x else Left "Number less than two" -- getArgs usage main :: IO () -- main = do args <- System.Environment.getArgs -- putStrLn $ concat args -- main = foo2 foo2 = putStrLn "Enter the name: " >> getLine >>= \name -> putStrLn $ "You Entered: " ++ name class BasicEq a where isEqual :: a -> a -> Bool instance BasicEq Bool where isEqual True True = True isEqual False False = True isEqual _ _ = False data Date = Date Int Int Int deriving (Show) data Time = Time Int Int Int deriving (Show) data Reading = Reading Int deriving (Show) data Day = Day String String deriving (Show) data BloodReading = BloodReading Date Time Reading Day deriving (Show) getReading :: BloodReading -> Reading getReading (BloodReading _ _ x _) = x getInt :: Reading -> Int getInt (Reading x) = x class BasicEq3 a where isEqual1, isNotEqual1 :: a -> a -> Bool isEqual1 x y = not (isNotEqual1 x y ) isNotEqual1 x y = not (isEqual1 x y) instance BasicEq3 Bool where isEqual1 True True = True isEqual1 False False = True isEqual1 _ _ = False data Color = Red | Green | Blue deriving (Show, Read) instance BasicEq3 Color where isEqual1 Red Red = True isEqual1 Green Green = True isEqual1 Blue Blue = True isEqual1 _ _ = False -- main = do putStrLn "Enter the number: " -- inpStr <- getLine -- let inpDouble = (read inpStr)::Color -- putStrLn $ " square of number is " ++ show inpDouble -- Serialization using read and show typeclasses main = do putStrLn "Enter the data:" inpStr <- getLine putStrLn "Writing to File..." writeFile "test" inpStr putStrLn "Reading File..." fileString <- readFile "test" let x = (read fileString)::[Maybe Int] putStrLn (show x) data MyType = MyType (Int -> Bool) foo1 x = x < 5 data CannotShow = CannotShow deriving (Show) data CannotDeriveShow = CannotDeriveShow CannotShow deriving (Show) g :: a -> () -> a g x () = x sumList xs ys = map add $ zip xs ys where add (x, y) = x + y listComb xs ys = do x <- xs y <- ys return (x, y) mymap f = foldl (\x -> f x) 0 mi x = [(1, 2), (4, 5)]
gitrookie/functionalcode
code/Haskell/snippets/test.hs
Haskell
mit
2,619
{-# LANGUAGE TemplateHaskell #-} {- Copyright (C) 2012-2017 Luke Brown <http://gsd.uwaterloo.ca> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} import Language.Clafer.IG.ClaferIG import Language.Clafer.IG.ClaferModel import Language.Clafer.IG.CommandLine import Control.Monad import Control.Monad.IO.Class import Data.Maybe import Data.IORef import System.Directory import System.FilePath import System.Console.CmdArgs import Prelude hiding (all) import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.TH tg_testsuite :: TestTree tg_testsuite = $(testGroupGenerator) main :: IO () main = defaultMain $ testGroup "Tests" [ tg_testsuite ] claferIGArgsDef :: IGArgs claferIGArgsDef = IGArgs { all = def, saveDir = def, claferModelFile = def, alloySolution = def, bitwidth = 4, maxInt = 7, useUids = False, addTypes = False, json = False, flatten_inheritance_comp = False, no_layout_comp = False, check_duplicates_comp = False, skip_resolver_comp = False, scope_strategy_comp = def } &= summary claferIGVersion defaultIGArgs :: FilePath -> IGArgs --defaultIGArgs fPath = IGArgs Nothing Nothing fPath False 4 False False False defaultIGArgs fPath = claferIGArgsDef{claferModelFile = fPath} --getModel :: MonadIO m => FilePath -> ClaferIGT m (Either Language.ClaferT.ClaferErrs Instance) getModel fPath = runClaferIGT (defaultIGArgs fPath) $ do setGlobalScope (fromMaybe 1 $ all $ defaultIGArgs fPath) solve counterRef <- liftIO $ newIORef 1 let saveDirectory = fromMaybe return $ underDirectory `liftM` saveDir (defaultIGArgs fPath) let nextFile = savePath fPath counterRef >>= saveDirectory file <- liftIO nextFile liftIO $ createDirectoryIfMissing True $ takeDirectory file next where savePath :: FilePath -> IORef Int -> IO FilePath savePath fPath' counterRef = do counter <- readIORef counterRef writeIORef counterRef (counter + 1) return $ fPath' ++ "." ++ (show counter) ++ ".data" underDirectory :: FilePath -> FilePath -> IO FilePath underDirectory dir file = do createDirectoryIfMissing True dir return $ joinPath [dir, file] fromRight (Right x) = x fromRight _ = error "fromRight received Left _. Should never happen." case_strMapCheck :: Assertion case_strMapCheck = do --let claferModel = Right $ Instance (ClaferModel [(Clafer (Id "" 0) (Just (StringValue "")) [])]) "" claferModel' <- getModel "test/positive/i220.cfr" (valueCheck $ c_value $ head $ c_topLevel $ modelInstance $ fromRight $ claferModel') @? "Mapping Int back to String Failed!" where valueCheck Nothing = False valueCheck (Just (AliasValue _)) = False valueCheck (Just (IntValue _)) = False valueCheck (Just (StringValue _)) = True case_pickLargerScope :: Assertion case_pickLargerScope = do let oldScopes = [ ("c0_1", 1), ("c1_b", 2), ("c0_x", 5) ] newScopes = [ ("c0_1", 2), ("c0_b", 2), ("c1_b", 1)] mergedScopes = map (pickLargerScope oldScopes) newScopes mergedScopes @?= [ ("c0_1", 2), ("c0_b", 2), ("c1_b", 2)]
gsdlab/claferIG
test/test-suite.hs
Haskell
mit
4,322
module Job.Activation ( sendActivationMail ) where import Import import qualified Data.ByteString.Lazy.Char8 as C import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Network.HTTP.Simple as HTTP import Job.Common data MailchimpActivate = MailchimpActivate Text Text deriving Show instance ToJSON MailchimpActivate where toJSON (MailchimpActivate email activationLink) = object [ "email_address" .= email -- ^ Mailchimp user email address , "status" .= ("subscribed" :: Text) -- ^ Mailchimp user status (i.e. subscribed, pending etc) , "merge_fields" .= object [ "MMERGE15" .= activationLink -- ^ Activation link mailchimp merge field , "MMERGE18" .= ("Ja" :: Text) -- ^ Add the user to the "Signed Up" group ] ] -- | Add the user to mailchimp list. sendActivationMail :: Key Job -> JobValue -> HandlerT App IO () sendActivationMail jobId (JobValueUserMail mail') = do let mail = T.toLower mail' $logInfo $ "Running sendActivationMail job for " <> mail master <- getYesod maybeUser <- runDB . getBy $ UniqueEmail mail case maybeUser of Nothing -> return () Just (Entity _ signup) -> do now <- liftIO getCurrentTime render <- getUrlRender let lang = signupLanguage signup -- Add analytics tracking to the URL if it is set. let utms = case appAnalytics $ appSettings master of Nothing -> "" Just _ -> "?utm_medium=email&utm_campaign=activation" let activationUrl = render (ActivateSignupIR lang (signupActivationToken signup)) <> utms let subscriber = MailchimpActivate mail activationUrl let postRequest = mailchimpPostRequest master lang subscriber postResponse <- liftIO $ HTTP.httpLBS postRequest let postResp = T.decodeUtf8 . C.toStrict $ HTTP.getResponseBody postResponse -- Check if the API call was successful or not case HTTP.getResponseStatusCode postResponse of -- Status code 200 indicates the user was successfully added. 200 -> runDB $ update jobId [JobFinished =. True, JobUpdated =. now, JobResult =. Just postResp] -- If we get a status code 400, the user already exists and we need to -- send a PATCH request instead to update their information. 400 -> do let patchRequest = mailchimpPatchRequest master lang subscriber mail patchResponse <- liftIO $ HTTP.httpLBS patchRequest let patchResp = T.decodeUtf8 . C.toStrict $ HTTP.getResponseBody patchResponse -- Check if the API call was successful or not. case HTTP.getResponseStatusCode patchResponse of 200 -> runDB $ update jobId [JobFinished =. True, JobUpdated =. now, JobResult =. Just patchResp] _ -> runDB $ update jobId [JobUpdated =. now, JobResult =. Just patchResp] -- Any other status code and the job is marked as failed. _ -> runDB $ update jobId [JobUpdated =. now, JobResult =. Just "Failed"] return () sendActivationMail _ _ = return ()
Tehnix/campaigns
Job/Activation.hs
Haskell
mit
3,248
-- https://howistart.org/posts/haskell/1 module Main where import qualified Data.ByteString.Lazy as BL import qualified Data.Vector as V -- from cassava import Data.Csv -- a simple type alias for data type BaseballStats = (BL.ByteString, Int, BL.ByteString, Int) fourth :: (a, b, c, d) -> d fourth (_, _, _, d) = d baseballStats :: BL.ByteString -> Either String (V.Vector BaseballStats) baseballStats = decode NoHeader main :: IO () main = do csvData <- BL.readFile "batting.csv" let summed = fmap (V.foldr summer 0) (baseballStats csvData) putStrLn $ "Total atBats was: " ++ (show summed) where summer = (+) . fourth
aitoroses/haskell-starter-repo
src/Main.hs
Haskell
mit
633
{-# LANGUAGE MultiParamTypeClasses, TypeOperators , TypeFamilies, UndecidableInstances, CPP , FlexibleContexts #-} type Time = Float --data Time deriving (Ord) --data R = NegInf | R Float | PosInf deriving (Eq,Ord) --data Time = T R | AtLeast R -- semantically, a behavior is a time dependant function type Behavior a = Time -> a -- semantically, an event is a list of time value pairs type Event a = (Time,a) -- interpretation of a behavior at a point in time -- this gives the denotation (semantic function) at :: Behavior a -> Time -> a at b t = b t -- interpretation of an event occ :: Event a -> (Time,a) occ = id occs :: Event a -> [(Time,a)] occs e = undefined time :: Behavior Time time = at id fmap :: (a -> b) -> Behavior a -> Behavior b fmap f b t = f (b t) always :: a -> Behavior a always = const ap :: Behavior (a -> b) -> Behavior a -> Behavior b ap bf ba = \t -> (bf t) (ba t) lift :: (a -> b) -> Behavior a -> Behavior b lift f a = always f `ap` a lift2 :: (a -> b -> c) -> Behavior a -> Behavior b -> Behavior c lift2 f a b = always f `ap` a `ap` b lift3 :: (a -> b -> c -> d) -> Behavior a -> Behavior b -> Behavior c -> Behavior d lift3 f a b c = always f `ap` a `ap` b `ap` c -- time transformtion timeX :: Behavior a -> Behavior Time -> Behavior a timeX ba bt = ba . bt -- timeX b time = b -- timeX b (time/2) -- slows down animation by factor of 2 -- timeX b (time - 2) -- delays by 2 seconds class AdditiveGroup v where zeroV :: v (^+^) :: v -> v -> v negateV :: v -> v (^-^) :: v -> v -> v class AdditiveGroup v => VectorSpace v where type Scalar v :: * (*^) :: Scalar v -> v -> v -- ∫{t,t0} b -- can be used to specify velocity and acceleration -- creates a behavior which sums all values of the argument behavior starting with -- the initial time up to the argument time -- the vector space implements the summation integral :: VectorSpace a => Behavior a -> Time -> Behavior a integral b t0 t = b t ^+^ b t0 -- returns values of argument behavior until event occurs -- after which the values of the behavior produced by the event are returned untilB :: Behavior a -> Event (Behavior a) -> Behavior a untilB b e t = if t <= te then b t else b' t where (te,b') = occ e (+=>) :: Event a -> (Time -> a -> b) -> Event b e +=> f = (te,f te a) where (te,a) = occ e (==>) :: Event a -> (a -> b) -> Event b e ==> f = (te,f a) where (te,a) = occ e (*=>) :: Event a -> (Time -> b) -> Event b e *=> f = e +=> \t _ -> f t (-=>) :: Event a -> b -> Event b e -=> b = e +=> \_ _ -> b constEv :: Time -> a -> Event a constEv t a = (t,a) lbp :: Time -> Event (Event ()) lbp = undefined rbp :: Time -> Event (Event ()) rbp = undefined -- b1 untilB (lbp t0) ==> \e -> b2 untilB e -=> b3 -- b1 until left button pressed then b2 until left button is released then finally b3 predicate :: Behavior Bool -> Time -> Event () predicate b t = (undefined,()) -- choose the earlier of two events (*|*) :: Event a -> Event a -> Event a a *|* b = undefined snapshot :: Event a -> Behavior b -> Event (a,b) snapshot = undefined main :: IO () main = return ()
eulerfx/learnfp
functional_reactive_animation.hs
Haskell
mit
3,136
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} module Language.PureScript.Linter.Imports (findUnusedImports, Name(..), UsedImports()) where import Prelude () import Prelude.Compat import qualified Data.Map as M import Data.Maybe (mapMaybe) import Data.List ((\\), find) import Control.Monad.Error.Class (MonadError(..)) import Control.Monad.Writer.Class import Control.Monad(unless,when) import Data.Foldable (forM_) import Language.PureScript.AST.Declarations import Language.PureScript.AST.SourcePos import Language.PureScript.Names as P import Language.PureScript.Errors import Language.PureScript.Sugar.Names.Env import Language.PureScript.Sugar.Names.Imports import qualified Language.PureScript.Constants as C -- | Imported name used in some type or expression. data Name = IdentName (Qualified Ident) | IsProperName (Qualified ProperName) | DctorName (Qualified ProperName) -- | Map of module name to list of imported names from that module which have been used. type UsedImports = M.Map ModuleName [Name] -- | -- Find and warn on any unused import statements (qualified or unqualified) -- or references in an explicit import list. -- findUnusedImports :: forall m. (Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) => Module -> Env -> UsedImports -> m () findUnusedImports (Module _ _ _ mdecls _) env usedImps = do imps <- findImports mdecls forM_ (M.toAscList imps) $ \(mni, decls) -> unless (mni `elem` autoIncludes) $ forM_ decls $ \(ss, declType, qualifierName) -> censor (onErrorMessages $ addModuleLocError ss) $ let usedNames = mapMaybe (matchName (typeForDCtor mni) qualifierName) $ sugarNames ++ M.findWithDefault [] mni usedImps in case declType of Implicit -> when (null usedNames) $ tell $ errorMessage $ UnusedImport mni Explicit declrefs -> do let idents = mapMaybe runDeclRef declrefs let diff = idents \\ usedNames unless (null diff) $ tell $ errorMessage $ UnusedExplicitImport mni diff _ -> return () where sugarNames :: [ Name ] sugarNames = [ IdentName $ Qualified Nothing (Ident C.bind) ] autoIncludes :: [ ModuleName ] autoIncludes = [ ModuleName [ProperName C.prim] ] typeForDCtor :: ModuleName -> ProperName -> Maybe ProperName typeForDCtor mn pn = getTy <$> find matches tys where matches ((_, ctors), _) = pn `elem` ctors getTy ((ty, _), _) = ty tys :: [((ProperName, [ProperName]), ModuleName)] tys = maybe [] exportedTypes $ envModuleExports <$> mn `M.lookup` env matchName :: (ProperName -> Maybe ProperName) -> Maybe ModuleName -> Name -> Maybe String matchName _ qual (IdentName (Qualified q x)) | q == qual = Just $ showIdent x matchName _ qual (IsProperName (Qualified q x)) | q == qual = Just $ runProperName x matchName lookupDc qual (DctorName (Qualified q x)) | q == qual = runProperName <$> lookupDc x matchName _ _ _ = Nothing runDeclRef :: DeclarationRef -> Maybe String runDeclRef (PositionedDeclarationRef _ _ ref) = runDeclRef ref runDeclRef (ValueRef ident) = Just $ showIdent ident runDeclRef (TypeRef pn _) = Just $ runProperName pn runDeclRef _ = Nothing addModuleLocError :: Maybe SourceSpan -> ErrorMessage -> ErrorMessage addModuleLocError sp err = case sp of Just pos -> withPosition pos err _ -> err
michaelficarra/purescript
src/Language/PureScript/Linter/Imports.hs
Haskell
mit
3,353
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} module Y2017.M12.D12.Exercise where {-- Okay, I came across an error when I was filtering articles with indexed keywords: time cold_filtered 6495 trump cold_filtered: UnexpectedNull {errSQLType = "text", errSQLTableOid = Just (Oid 50231), errSQLField = "summary", errHaskellType = "Text", errMessage = ""} What this is saying is that there are articles that do not have summaries, and so the type for summary, String, is not appropriate. I changed the type to Maybe String, and that fixes the error, but now we are recommending articles that do not have summaries. That's not good. So, today's Haskell problem is to filter out articles that do not have summaries... shoot! Which I already did, since a brief, intrinsic to its type needs a summary. So, instead we have a different problem. Filtering by keyword is slow, not because the filtering is slow, but when we go back to assign a ranking we fetch the key-phrase strength for each of the articles, ... one-by-one. See: --} import Y2017.M11.D20.Exercise hiding (keyphrasesStmt, keyphrase4) {-- We do not want to make separate SQL calls for each article id. Instead, we want to batch all our article ids into one query. So, let's rewrite the query so that we send all the SQL in one shot. --} import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.SqlQQ -- below imports available via 1HaskellADay git repository import Store.SQL.Connection import Store.SQL.Util.Indexed import Y2017.M11.D03.Exercise -- for Keyphrase import Y2017.M11.D07.Exercise -- for Recommendation import Y2017.M11.D13.Exercise -- for KeyWord import Y2017.M11.D17.Exercise -- for KWtable keyphrasesStmt :: Query keyphrasesStmt = [sql|SELECT a.article_id,a.keyphrase_id,k.strength,k.keyphrase FROM keyphrase k LEFT JOIN article_keyphrase a ON a.keyphrase_id = k.id WHERE a.article_id IN ?|] keyphrase4 :: Connection -> [Integer] -> IO [(Integer, Integer, Double, String)] keyphrase4 conn artids = undefined {-- BONUS ----------------------------------------------------------------- So, with the new one-query keyphrase-fetch, let's rebuild the app using that instead. That is to say: rebuild recs' --} recs' :: Connection -> [KeyWord] -> KWtable -> IO [Recommendation] recs' conn kws table = undefined main' :: [String] -> IO () main' (artid:keywords) = undefined -- hints: -- look at Y2017.M11.D20 for definition of recs' -- look at Y2017.M12.D06 for filtered on article id keyword searches -- time the old filtered approach (see Y2017.M12.D06) verses this approach for -- article_id 6495 and the sole keyword: mars -- now time both approaches for article_id 6495 and the sole keyword: trump
geophf/1HaskellADay
exercises/HAD/Y2017/M12/D12/Exercise.hs
Haskell
mit
2,742
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE OverloadedStrings #-} module Yesod.Devel.Capture ( Capture , startCapture , logMessage , outputChunk , waitCaptured ) where import Data.Text (Text) import Data.ByteString (ByteString) import Control.Concurrent.STM import Data.Time (UTCTime, getCurrentTime) import Control.Applicative ((<$>), (<|>)) import qualified Data.ByteString as S data Capture = Capture { logMessage :: Text -> IO () , outputChunk :: ByteString -> IO () , waitCaptured :: STM (Either (UTCTime, Text) ByteString) } startCapture :: IO Capture startCapture = do logMessages <- atomically newTChan chunks <- atomically newTChan return Capture { logMessage = \msg -> do now <- getCurrentTime atomically $ writeTChan logMessages (now, msg) , outputChunk = atomically . writeTChan chunks . stripColorCodes , waitCaptured = (Left <$> readTChan logMessages) <|> (Right <$> readTChan chunks) } where wdel = 27 wm = 109 stripColorCodes bs = case S.breakByte wdel bs of (_, "") -> bs (x, S.drop 1 . snd . S.breakByte wm -> y) | S.null y -> bs | otherwise -> S.append x $ stripColorCodes y
snoyberg/yesod-devel-beta
Yesod/Devel/Capture.hs
Haskell
mit
1,351
-- | Chan with size module Control.Concurrent.SizedChan (SizedChan, newSizedChan, writeSizedChan, readSizedChan, tryReadSizedChan, peekSizedChan, tryPeekSizedChan, isEmptySizedChan) where import Control.Concurrent.Chan import Data.IORef data SizedChan a = SizedChan (Chan a) -- ^ The channel (IORef Int) -- ^ Its size (IORef (Maybe a)) -- ^ Peeked payload -- | Build and returns a new instance of 'SizedChan'. newSizedChan :: IO (SizedChan a) newSizedChan = SizedChan <$> newChan <*> newIORef 0 <*> newIORef Nothing -- | Write a value to a 'SizedChan'. writeSizedChan :: SizedChan a -> a -> IO () writeSizedChan (SizedChan chan sizeIORef _) val = do writeChan chan val modifyIORef' sizeIORef succ -- | Read the next value from the 'SizedChan'. Blocks when the channel is empty. readSizedChan :: SizedChan a -> IO a readSizedChan (SizedChan chan sizeIORef peekedIORef) = do peeked <- readIORef peekedIORef case peeked of -- return and remove the peeked value Just val -> do writeIORef peekedIORef Nothing modifyIORef' sizeIORef pred return val -- else read from the channel Nothing -> do val <- readChan chan modifyIORef' sizeIORef pred return val -- | A version of `readSizedChan` which does not block. Instead it returns Nothing if no value is available. tryReadSizedChan :: SizedChan a -> IO (Maybe a) tryReadSizedChan (SizedChan chan sizeIORef peekedIORef) = do peeked <- readIORef peekedIORef case peeked of -- return and remove the peeked value Just val -> do writeIORef peekedIORef Nothing modifyIORef' sizeIORef pred return $ Just val -- check the size before reading from the channel, to prevent blocking Nothing -> do size <- readIORef sizeIORef if size == 0 then return Nothing else do val <- readChan chan modifyIORef' sizeIORef pred return $ Just val -- | Peek the next value from the 'SizedChan' without removing it. Blocks when the channel is empty. peekSizedChan :: SizedChan a -> IO a peekSizedChan (SizedChan chan _ peekedIORef) = do peeked <- readIORef peekedIORef case peeked of -- return the peeked value Just val -> return val -- read from the channel instead Nothing -> do val <- readChan chan writeIORef peekedIORef (Just val) return val -- | A version of `peekSizedChan` which does not block. Instead it returns Nothing if no value is available. tryPeekSizedChan :: SizedChan a -> IO (Maybe a) tryPeekSizedChan (SizedChan chan sizeIORef peekedIORef) = do peeked <- readIORef peekedIORef case peeked of -- return the peeked value Just val -> return $ Just val -- check the size before reading from the channel, to prevent blocking Nothing -> do size <- readIORef sizeIORef if size == 0 then return Nothing else do val <- readChan chan writeIORef peekedIORef (Just val) return $ Just val measureSizedChan :: SizedChan a -> IO Int measureSizedChan (SizedChan _ sizeIORef _) = readIORef sizeIORef isEmptySizedChan :: SizedChan a -> IO Bool isEmptySizedChan chan = do size <- measureSizedChan chan return $ size == 0
banacorn/agda-language-server
src/Control/Concurrent/SizedChan.hs
Haskell
mit
3,254
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Com.Mysql.Cj.Mysqlx.Protobuf.ViewSqlSecurity (ViewSqlSecurity(..)) where import Prelude ((+), (/), (.)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified GHC.Generics as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data ViewSqlSecurity = INVOKER | DEFINER deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic) instance P'.Mergeable ViewSqlSecurity instance Prelude'.Bounded ViewSqlSecurity where minBound = INVOKER maxBound = DEFINER instance P'.Default ViewSqlSecurity where defaultValue = INVOKER toMaybe'Enum :: Prelude'.Int -> P'.Maybe ViewSqlSecurity toMaybe'Enum 1 = Prelude'.Just INVOKER toMaybe'Enum 2 = Prelude'.Just DEFINER toMaybe'Enum _ = Prelude'.Nothing instance Prelude'.Enum ViewSqlSecurity where fromEnum INVOKER = 1 fromEnum DEFINER = 2 toEnum = P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Com.Mysql.Cj.Mysqlx.Protobuf.ViewSqlSecurity") . toMaybe'Enum succ INVOKER = DEFINER succ _ = Prelude'.error "hprotoc generated code: succ failure for type Com.Mysql.Cj.Mysqlx.Protobuf.ViewSqlSecurity" pred DEFINER = INVOKER pred _ = Prelude'.error "hprotoc generated code: pred failure for type Com.Mysql.Cj.Mysqlx.Protobuf.ViewSqlSecurity" instance P'.Wire ViewSqlSecurity where wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum) wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum) wireGet 14 = P'.wireGetEnum toMaybe'Enum wireGet ft' = P'.wireGetErr ft' wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum wireGetPacked ft' = P'.wireGetErr ft' instance P'.GPB ViewSqlSecurity instance P'.MessageAPI msg' (msg' -> ViewSqlSecurity) ViewSqlSecurity where getVal m' f' = f' m' instance P'.ReflectEnum ViewSqlSecurity where reflectEnum = [(1, "INVOKER", INVOKER), (2, "DEFINER", DEFINER)] reflectEnumInfo _ = P'.EnumInfo (P'.makePNF (P'.pack ".Mysqlx.Crud.ViewSqlSecurity") [] ["Com", "Mysql", "Cj", "Mysqlx", "Protobuf"] "ViewSqlSecurity") ["Com", "Mysql", "Cj", "Mysqlx", "Protobuf", "ViewSqlSecurity.hs"] [(1, "INVOKER"), (2, "DEFINER")] instance P'.TextType ViewSqlSecurity where tellT = P'.tellShow getT = P'.getRead
naoto-ogawa/h-xproto-mysql
src/Com/Mysql/Cj/Mysqlx/Protobuf/ViewSqlSecurity.hs
Haskell
mit
2,561
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html module Stratosphere.Resources.SSMPatchBaseline where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.SSMPatchBaselineRuleGroup import Stratosphere.ResourceProperties.SSMPatchBaselinePatchFilterGroup import Stratosphere.ResourceProperties.SSMPatchBaselinePatchSource -- | Full data type definition for SSMPatchBaseline. See 'ssmPatchBaseline' -- for a more convenient constructor. data SSMPatchBaseline = SSMPatchBaseline { _sSMPatchBaselineApprovalRules :: Maybe SSMPatchBaselineRuleGroup , _sSMPatchBaselineApprovedPatches :: Maybe (ValList Text) , _sSMPatchBaselineApprovedPatchesComplianceLevel :: Maybe (Val Text) , _sSMPatchBaselineApprovedPatchesEnableNonSecurity :: Maybe (Val Bool) , _sSMPatchBaselineDescription :: Maybe (Val Text) , _sSMPatchBaselineGlobalFilters :: Maybe SSMPatchBaselinePatchFilterGroup , _sSMPatchBaselineName :: Val Text , _sSMPatchBaselineOperatingSystem :: Maybe (Val Text) , _sSMPatchBaselinePatchGroups :: Maybe (ValList Text) , _sSMPatchBaselineRejectedPatches :: Maybe (ValList Text) , _sSMPatchBaselineRejectedPatchesAction :: Maybe (Val Text) , _sSMPatchBaselineSources :: Maybe [SSMPatchBaselinePatchSource] } deriving (Show, Eq) instance ToResourceProperties SSMPatchBaseline where toResourceProperties SSMPatchBaseline{..} = ResourceProperties { resourcePropertiesType = "AWS::SSM::PatchBaseline" , resourcePropertiesProperties = hashMapFromList $ catMaybes [ fmap (("ApprovalRules",) . toJSON) _sSMPatchBaselineApprovalRules , fmap (("ApprovedPatches",) . toJSON) _sSMPatchBaselineApprovedPatches , fmap (("ApprovedPatchesComplianceLevel",) . toJSON) _sSMPatchBaselineApprovedPatchesComplianceLevel , fmap (("ApprovedPatchesEnableNonSecurity",) . toJSON) _sSMPatchBaselineApprovedPatchesEnableNonSecurity , fmap (("Description",) . toJSON) _sSMPatchBaselineDescription , fmap (("GlobalFilters",) . toJSON) _sSMPatchBaselineGlobalFilters , (Just . ("Name",) . toJSON) _sSMPatchBaselineName , fmap (("OperatingSystem",) . toJSON) _sSMPatchBaselineOperatingSystem , fmap (("PatchGroups",) . toJSON) _sSMPatchBaselinePatchGroups , fmap (("RejectedPatches",) . toJSON) _sSMPatchBaselineRejectedPatches , fmap (("RejectedPatchesAction",) . toJSON) _sSMPatchBaselineRejectedPatchesAction , fmap (("Sources",) . toJSON) _sSMPatchBaselineSources ] } -- | Constructor for 'SSMPatchBaseline' containing required fields as -- arguments. ssmPatchBaseline :: Val Text -- ^ 'ssmpbName' -> SSMPatchBaseline ssmPatchBaseline namearg = SSMPatchBaseline { _sSMPatchBaselineApprovalRules = Nothing , _sSMPatchBaselineApprovedPatches = Nothing , _sSMPatchBaselineApprovedPatchesComplianceLevel = Nothing , _sSMPatchBaselineApprovedPatchesEnableNonSecurity = Nothing , _sSMPatchBaselineDescription = Nothing , _sSMPatchBaselineGlobalFilters = Nothing , _sSMPatchBaselineName = namearg , _sSMPatchBaselineOperatingSystem = Nothing , _sSMPatchBaselinePatchGroups = Nothing , _sSMPatchBaselineRejectedPatches = Nothing , _sSMPatchBaselineRejectedPatchesAction = Nothing , _sSMPatchBaselineSources = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-approvalrules ssmpbApprovalRules :: Lens' SSMPatchBaseline (Maybe SSMPatchBaselineRuleGroup) ssmpbApprovalRules = lens _sSMPatchBaselineApprovalRules (\s a -> s { _sSMPatchBaselineApprovalRules = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-approvedpatches ssmpbApprovedPatches :: Lens' SSMPatchBaseline (Maybe (ValList Text)) ssmpbApprovedPatches = lens _sSMPatchBaselineApprovedPatches (\s a -> s { _sSMPatchBaselineApprovedPatches = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-approvedpatchescompliancelevel ssmpbApprovedPatchesComplianceLevel :: Lens' SSMPatchBaseline (Maybe (Val Text)) ssmpbApprovedPatchesComplianceLevel = lens _sSMPatchBaselineApprovedPatchesComplianceLevel (\s a -> s { _sSMPatchBaselineApprovedPatchesComplianceLevel = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-approvedpatchesenablenonsecurity ssmpbApprovedPatchesEnableNonSecurity :: Lens' SSMPatchBaseline (Maybe (Val Bool)) ssmpbApprovedPatchesEnableNonSecurity = lens _sSMPatchBaselineApprovedPatchesEnableNonSecurity (\s a -> s { _sSMPatchBaselineApprovedPatchesEnableNonSecurity = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-description ssmpbDescription :: Lens' SSMPatchBaseline (Maybe (Val Text)) ssmpbDescription = lens _sSMPatchBaselineDescription (\s a -> s { _sSMPatchBaselineDescription = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-globalfilters ssmpbGlobalFilters :: Lens' SSMPatchBaseline (Maybe SSMPatchBaselinePatchFilterGroup) ssmpbGlobalFilters = lens _sSMPatchBaselineGlobalFilters (\s a -> s { _sSMPatchBaselineGlobalFilters = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-name ssmpbName :: Lens' SSMPatchBaseline (Val Text) ssmpbName = lens _sSMPatchBaselineName (\s a -> s { _sSMPatchBaselineName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-operatingsystem ssmpbOperatingSystem :: Lens' SSMPatchBaseline (Maybe (Val Text)) ssmpbOperatingSystem = lens _sSMPatchBaselineOperatingSystem (\s a -> s { _sSMPatchBaselineOperatingSystem = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-patchgroups ssmpbPatchGroups :: Lens' SSMPatchBaseline (Maybe (ValList Text)) ssmpbPatchGroups = lens _sSMPatchBaselinePatchGroups (\s a -> s { _sSMPatchBaselinePatchGroups = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-rejectedpatches ssmpbRejectedPatches :: Lens' SSMPatchBaseline (Maybe (ValList Text)) ssmpbRejectedPatches = lens _sSMPatchBaselineRejectedPatches (\s a -> s { _sSMPatchBaselineRejectedPatches = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-rejectedpatchesaction ssmpbRejectedPatchesAction :: Lens' SSMPatchBaseline (Maybe (Val Text)) ssmpbRejectedPatchesAction = lens _sSMPatchBaselineRejectedPatchesAction (\s a -> s { _sSMPatchBaselineRejectedPatchesAction = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-sources ssmpbSources :: Lens' SSMPatchBaseline (Maybe [SSMPatchBaselinePatchSource]) ssmpbSources = lens _sSMPatchBaselineSources (\s a -> s { _sSMPatchBaselineSources = a })
frontrowed/stratosphere
library-gen/Stratosphere/Resources/SSMPatchBaseline.hs
Haskell
mit
7,439
qs1 [] = [] qs1 (x : xs) = qs1 larger ++ [x] ++ qs1 smaller where smaller = [a | a <- xs, a <= x] larger = [b | b <- xs, b > x] qs2 [] = [] qs2 (x : xs) = reverse (qs2 smaller ++ [x] ++ qs2 larger) where smaller = [a | a <- xs, a <= x] larger = [b | b <- xs, b > x] qs4 [] = [] qs4 (x : xs) = reverse (qs4 smaller) ++ [x] ++ reverse(qs4 larger) where smaller = [a | a <- xs, a <= x] larger = [b | b <- xs, b > x] qs5 [] = [] qs5 (x : xs) = qs5 larger ++ [x] ++ qs5 smaller where smaller = [a | a <- xs, a < x] larger = [b | b <- xs, b > x || b == x] qs6 [] = [] qs6 (x : xs) = qs6 larger ++ [x] ++ qs6 smaller where smaller = [a | a <- xs, a < x] larger = [b | b <- xs, b > x] main = do let one = [1] let many = [4, 1, 2, 1, 7, 3, 5, 4, 5, 5, 7, 7] print("### qs1") print(qs1 one) print(qs1 many) print("### qs2") print(qs2 one) print(qs2 many) print("### qs4") print(qs4 one) print(qs4 many) print("### qs5") print(qs5 one) print(qs5 many) print("### qs6") print(qs6 one) print(qs6 many)
rabbitonweb/fp101x
w01/qs.hs
Haskell
apache-2.0
1,250
{-# LANGUAGE CPP #-} module System.Console.Hawk.PackageDbs.TH ( compileTimeEnvVar , compileTimeWorkingDirectory ) where import Language.Haskell.TH.Syntax (TExp(TExp), Q, lift, runIO) #if MIN_VERSION_template_haskell(2,17,0) import Language.Haskell.TH.Syntax (Code, liftCode) #endif import System.Directory (getCurrentDirectory) import System.Environment (getEnvironment) #if !MIN_VERSION_template_haskell(2,17,0) type Code m a = m (TExp a) liftCode :: m (TExp a) -> Code m a liftCode = id #endif compileTimeEnvVar :: String -> Code Q (Maybe String) compileTimeEnvVar varname = liftCode $ do env <- runIO getEnvironment let r :: Maybe String r = lookup varname env TExp <$> lift r compileTimeWorkingDirectory :: Code Q String compileTimeWorkingDirectory = liftCode $ do pwd <- runIO getCurrentDirectory TExp <$> lift pwd
gelisam/hawk
src/System/Console/Hawk/PackageDbs/TH.hs
Haskell
apache-2.0
854
module TextToys.Utils ( takeTo ) where import Control.Arrow (first) takeTo :: (a -> Bool) -> [a] -> ([a], [a]) takeTo _ [] = ([], []) takeTo p (x:xs) | p x = ([x], xs) | otherwise = first (x:) $ takeTo p xs
erochest/text-toys
src/TextToys/Utils.hs
Haskell
apache-2.0
263
module Main where import Test.Hspec import Test.Hspec.Contrib.HUnit import Test.HUnit -- (1) Import your test module qualified here. import qualified System.IO.FileSync.Tests.Join as Join import qualified System.IO.FileSync.Tests.Tree as Tree import qualified System.IO.FileSync.Tests.TreeT as TreeT -- (2) Insert its test list qualified here. main :: IO () main = runTests [Join.tests, Tree.tests, TreeT.tests] runTests :: [Test] -> IO () runTests ts = hspec . fromHUnitTest . TestList $ ts
jtapolczai/FileSync
tests/System/IO/FileSync/Tests.hs
Haskell
apache-2.0
530
module Main (main) where import Control.Applicative ((<$>)) import Control.Monad (forever) import Data.Data (toConstr) import Data.Function (on) import Data.List (groupBy) import System.IO (hFlush, hPutStrLn, stdout) import Poker.Cards import Poker.Hands main :: IO () main = do let ghs = groupBy (\h1 h2 -> h1 `compare` h2 == EQ) $ map fst $ hands deck putStrLn $ show $ length ghs let gghs = groupBy ((==) `on` (toConstr . head)) ghs putStrLn $ show $ length gghs putHand :: Hand -> IO () putHand h = do hPutStrLn stdout $ unwords $ map show $ cardList h hFlush stdout getCards :: IO [Card] getCards = map read . words <$> getLine bestThree :: [Card] -> (Hand, Hand, Hand) bestThree = head . allThrees allThrees :: [Card] -> [(Hand, Hand, Hand)] allThrees cs = do (h1, cs') <- hands cs (h2, cs'') <- hands cs' (h3, _) <- hands cs'' return (h1, h2, h3)
mkscrg/chinese-poker
smart-player/main.hs
Haskell
bsd-2-clause
882
{-# LANGUAGE BangPatterns, CPP, MagicHash, Rank2Types, RecordWildCards, UnboxedTuples, UnliftedFFITypes #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- | -- Module : Data.Text.Array -- Copyright : (c) 2009, 2010, 2011 Bryan O'Sullivan -- -- License : BSD-style -- Maintainer : bos@serpentine.com -- Portability : portable -- -- Packed, unboxed, heap-resident arrays. Suitable for performance -- critical use, both in terms of large data quantities and high -- speed. -- -- This module is intended to be imported @qualified@, to avoid name -- clashes with "Prelude" functions, e.g. -- -- > import qualified Data.Text.Array as A -- -- The names in this module resemble those in the 'Data.Array' family -- of modules, but are shorter due to the assumption of qualified -- naming. module Data.Text.Array ( -- * Types Array(..) , MArray(..) -- * Functions , copyM , copyI , empty , equal , run , run2 , toList , unsafeFreeze , unsafeIndex , new , unsafeWrite ) where #if defined(ASSERTS) import Control.Exception (assert) #endif #if MIN_VERSION_base(4,4,0) import Control.Monad.ST.Unsafe (unsafeIOToST) #else import Control.Monad.ST (unsafeIOToST) #endif import Data.Bits ((.&.), xor) import Data.Text.Internal.Unsafe (inlinePerformIO) import Data.Text.Internal.Unsafe.Shift (shiftL, shiftR) #if MIN_VERSION_base(4,5,0) import Foreign.C.Types (CInt(CInt), CSize(CSize)) #else import Foreign.C.Types (CInt, CSize) #endif import GHC.Base (ByteArray#, MutableByteArray#, Int(..), indexWord16Array#, newByteArray#, unsafeFreezeByteArray#, writeWord16Array#, sizeofByteArray#, sizeofMutableByteArray#) import GHC.ST (ST(..), runST) import GHC.Word (Word16(..)) import Prelude hiding (length, read) -- | Immutable array type. -- -- The 'Array' constructor is exposed since @text-1.1.1.3@ data Array = Array { aBA :: ByteArray# } -- | Mutable array type, for use in the ST monad. -- -- The 'MArray' constructor is exposed since @text-1.1.1.3@ data MArray s = MArray { maBA :: MutableByteArray# s } -- | Create an uninitialized mutable array. new :: forall s. Int -> ST s (MArray s) new n | n < 0 || n .&. highBit /= 0 = array_size_error | otherwise = ST $ \s1# -> case newByteArray# len# s1# of (# s2#, marr# #) -> (# s2#, MArray marr# #) where !(I# len#) = bytesInArray n highBit = maxBound `xor` (maxBound `shiftR` 1) {-# INLINE new #-} array_size_error :: a array_size_error = error "Data.Text.Array.new: size overflow" -- | Freeze a mutable array. Do not mutate the 'MArray' afterwards! unsafeFreeze :: MArray s -> ST s Array unsafeFreeze MArray{..} = ST $ \s1# -> case unsafeFreezeByteArray# maBA s1# of (# s2#, ba# #) -> (# s2#, Array ba# #) {-# INLINE unsafeFreeze #-} -- | Indicate how many bytes would be used for an array of the given -- size. bytesInArray :: Int -> Int bytesInArray n = n `shiftL` 1 {-# INLINE bytesInArray #-} -- | Unchecked read of an immutable array. May return garbage or -- crash on an out-of-bounds access. unsafeIndex :: Array -> Int -> Word16 unsafeIndex a@Array{..} i@(I# i#) = #if defined(ASSERTS) let word16len = I# (sizeofByteArray# aBA) `quot` 2 in if i < 0 || i >= word16len then error ("Data.Text.Array.unsafeIndex: bounds error, offset " ++ show i ++ ", length " ++ show word16len) else #endif case indexWord16Array# aBA i# of r# -> (W16# r#) {-# INLINE unsafeIndex #-} -- | Unchecked write of a mutable array. May return garbage or crash -- on an out-of-bounds access. unsafeWrite :: MArray s -> Int -> Word16 -> ST s () unsafeWrite ma@MArray{..} i@(I# i#) (W16# e#) = ST $ \s1# -> #if defined(ASSERTS) let word16len = I# (sizeofMutableByteArray# maBA) `quot` 2 in if i < 0 || i >= word16len then error ("Data.Text.Array.unsafeWrite: bounds error, offset " ++ show i ++ ", length " ++ show word16len) else #endif case writeWord16Array# maBA i# e# s1# of s2# -> (# s2#, () #) {-# INLINE unsafeWrite #-} -- | Convert an immutable array to a list. toList :: Array -> Int -> Int -> [Word16] toList ary off len = loop 0 where loop i | i < len = unsafeIndex ary (off+i) : loop (i+1) | otherwise = [] -- | An empty immutable array. empty :: Array empty = runST (new 0 >>= unsafeFreeze) -- | Run an action in the ST monad and return an immutable array of -- its result. run :: (forall s. ST s (MArray s)) -> Array run k = runST (k >>= unsafeFreeze) -- | Run an action in the ST monad and return an immutable array of -- its result paired with whatever else the action returns. run2 :: (forall s. ST s (MArray s, a)) -> (Array, a) run2 k = runST (do (marr,b) <- k arr <- unsafeFreeze marr return (arr,b)) {-# INLINE run2 #-} -- | Copy some elements of a mutable array. copyM :: MArray s -- ^ Destination -> Int -- ^ Destination offset -> MArray s -- ^ Source -> Int -- ^ Source offset -> Int -- ^ Count -> ST s () copyM dest didx src sidx count | count <= 0 = return () | otherwise = #if defined(ASSERTS) assert (sidx + count <= I# (sizeofMutableByteArray# (maBA src)) `quot` 2) . assert (didx + count <= I# (sizeofMutableByteArray# (maBA dest)) `quot` 2) . #endif unsafeIOToST $ memcpyM (maBA dest) (fromIntegral didx) (maBA src) (fromIntegral sidx) (fromIntegral count) {-# INLINE copyM #-} -- | Copy some elements of an immutable array. copyI :: MArray s -- ^ Destination -> Int -- ^ Destination offset -> Array -- ^ Source -> Int -- ^ Source offset -> Int -- ^ First offset in destination /not/ to -- copy (i.e. /not/ length) -> ST s () copyI dest i0 src j0 top | i0 >= top = return () | otherwise = unsafeIOToST $ memcpyI (maBA dest) (fromIntegral i0) (aBA src) (fromIntegral j0) (fromIntegral (top-i0)) {-# INLINE copyI #-} -- | Compare portions of two arrays for equality. No bounds checking -- is performed. equal :: Array -- ^ First -> Int -- ^ Offset into first -> Array -- ^ Second -> Int -- ^ Offset into second -> Int -- ^ Count -> Bool equal arrA offA arrB offB count = inlinePerformIO $ do i <- memcmp (aBA arrA) (fromIntegral offA) (aBA arrB) (fromIntegral offB) (fromIntegral count) return $! i == 0 {-# INLINE equal #-} foreign import ccall unsafe "_hs_text_memcpy" memcpyI :: MutableByteArray# s -> CSize -> ByteArray# -> CSize -> CSize -> IO () foreign import ccall unsafe "_hs_text_memcmp" memcmp :: ByteArray# -> CSize -> ByteArray# -> CSize -> CSize -> IO CInt foreign import ccall unsafe "_hs_text_memcpy" memcpyM :: MutableByteArray# s -> CSize -> MutableByteArray# s -> CSize -> CSize -> IO ()
bos/text
src/Data/Text/Array.hs
Haskell
bsd-2-clause
7,210
-- | -- Module : Data.Packer.Endian -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown -- -- Simple module to handle endianness swapping, -- but GHC should provide (some day) primitives to call -- into a cpu optimised version (e.g. bswap for x86) -- {-# LANGUAGE CPP #-} module Data.Packer.Endian ( le16Host , le32Host , le64Host , be16Host , be32Host , be64Host ) where import Data.Bits import Data.Word #if MIN_VERSION_base(4,7,0) -- | swap endianness on a Word16 swap16 :: Word16 -> Word16 swap16 = byteSwap16 -- | Transform a 32 bit value bytes from a.b.c.d to d.c.b.a swap32 :: Word32 -> Word32 swap32 = byteSwap32 -- | Transform a 64 bit value bytes from a.b.c.d.e.f.g.h to h.g.f.e.d.c.b.a swap64 :: Word64 -> Word64 swap64 = byteSwap64 #else #if BITS_IS_OLD shr :: Bits a => a -> Int -> a shr = shiftR shl :: Bits a => a -> Int -> a shl = shiftL #else shr :: Bits a => a -> Int -> a shr = unsafeShiftR shl :: Bits a => a -> Int -> a shl = unsafeShiftL #endif -- | swap endianness on a Word64 -- 56 48 40 32 24 16 8 0 -- a b c d e f g h -- h g f e d c b a swap64 :: Word64 -> Word64 swap64 w = (w `shr` 56) .|. (w `shl` 56) .|. ((w `shr` 40) .&. 0xff00) .|. ((w .&. 0xff00) `shl` 40) .|. ((w `shr` 24) .&. 0xff0000) .|. ((w .&. 0xff0000) `shl` 24) .|. ((w `shr` 8) .&. 0xff000000) .|. ((w .&. 0xff000000) `shl` 8) -- | swap endianness on a Word32 swap32 :: Word32 -> Word32 swap32 w = (w `shr` 24) .|. (w `shl` 24) .|. ((w `shr` 8) .&. 0xff00) .|. ((w .&. 0xff00) `shl` 8) -- | swap endianness on a Word16 swap16 :: Word16 -> Word16 swap16 w = (w `shr` 8) .|. (w `shl` 8) #endif #ifdef CPU_BIG_ENDIAN -- | 16 bit big endian to host endian {-# INLINE be16Host #-} be16Host :: Word16 -> Word16 be16Host = id -- | 32 bit big endian to host endian {-# INLINE be32Host #-} be32Host :: Word32 -> Word32 be32Host = id -- | 64 bit big endian to host endian {-# INLINE be64Host #-} be64Host :: Word64 -> Word64 be64Host = id -- | 16 bit little endian to host endian le16Host :: Word16 -> Word16 le16Host w = swap16 w -- | 32 bit little endian to host endian le32Host :: Word32 -> Word32 le32Host w = swap32 w -- | 64 bit little endian to host endian le64Host :: Word64 -> Word64 le64Host w = swap64 w #else -- | 16 bit little endian to host endian {-# INLINE le16Host #-} le16Host :: Word16 -> Word16 le16Host = id -- | 32 bit little endian to host endian {-# INLINE le32Host #-} le32Host :: Word32 -> Word32 le32Host = id -- | 64 bit little endian to host endian {-# INLINE le64Host #-} le64Host :: Word64 -> Word64 le64Host = id -- | 16 bit big endian to host endian be16Host :: Word16 -> Word16 be16Host w = swap16 w -- | 32 bit big endian to host endian be32Host :: Word32 -> Word32 be32Host w = swap32 w -- | 64 bit big endian to host endian be64Host :: Word64 -> Word64 be64Host w = swap64 w #endif
vincenthz/hs-packer
Data/Packer/Endian.hs
Haskell
bsd-2-clause
3,015
{-# LANGUAGE TypeOperators, DataKinds, PolyKinds, TypeFamilies, TemplateHaskell, GADTs, UndecidableInstances, RankNTypes, ScopedTypeVariables, MultiWayIf #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Promotion.Prelude.List -- Copyright : (C) 2014 Jan Stolarek -- License : BSD-style (see LICENSE) -- Maintainer : Jan Stolarek (jan.stolarek@p.lodz.pl) -- Stability : experimental -- Portability : non-portable -- -- Defines promoted functions and datatypes relating to 'List', -- including a promoted version of all the definitions in @Data.List@. -- -- Because many of these definitions are produced by Template Haskell, -- it is not possible to create proper Haddock documentation. Please look -- up the corresponding operation in @Data.List@. Also, please excuse -- the apparent repeated variable names. This is due to an interaction -- between Template Haskell and Haddock. -- ---------------------------------------------------------------------------- module Data.Promotion.Prelude.List ( -- * Basic functions (:++), Head, Last, Tail, Init, Null, Length, -- * List transformations Map, Reverse, Intersperse, Intercalate, Transpose, Subsequences, Permutations, -- * Reducing lists (folds) Foldl, Foldl', Foldl1, Foldl1', Foldr, Foldr1, -- ** Special folds Concat, ConcatMap, And, Or, Any_, All, Sum, Product, Maximum, Minimum, any_, -- equivalent of Data.List `any`. Avoids name clash with Any type -- * Building lists -- ** Scans Scanl, Scanl1, Scanr, Scanr1, -- ** Accumulating maps MapAccumL, MapAccumR, -- ** Infinite lists Replicate, -- ** Unfolding Unfoldr, -- * Sublists -- ** Extracting sublists Take, Drop, SplitAt, TakeWhile, DropWhile, DropWhileEnd, Span, Break, StripPrefix, Group, Inits, Tails, -- ** Predicates IsPrefixOf, IsSuffixOf, IsInfixOf, -- * Searching lists -- ** Searching by equality Elem, NotElem, Lookup, -- ** Searching with a predicate Find, Filter, Partition, -- * Indexing lists (:!!), ElemIndex, ElemIndices, FindIndex, FindIndices, -- * Zipping and unzipping lists Zip, Zip3, Zip4, Zip5, Zip6, Zip7, ZipWith, ZipWith3, ZipWith4, ZipWith5, ZipWith6, ZipWith7, Unzip, Unzip3, Unzip4, Unzip5, Unzip6, Unzip7, -- * Special lists -- ** \"Set\" operations Nub, Delete, (:\\), Union, Intersect, -- ** Ordered lists Sort, Insert, -- * Generalized functions -- ** The \"@By@\" operations -- *** User-supplied equality (replacing an @Eq@ context) NubBy, DeleteBy, DeleteFirstsBy, UnionBy, GroupBy, IntersectBy, -- *** User-supplied comparison (replacing an @Ord@ context) SortBy, InsertBy, MaximumBy, MinimumBy, -- ** The \"@generic@\" operations GenericLength, GenericTake, GenericDrop, GenericSplitAt, GenericIndex, GenericReplicate, -- * Defunctionalization symbols NilSym0, (:$), (:$$), (:$$$), (:++$$$), (:++$$), (:++$), HeadSym0, HeadSym1, LastSym0, LastSym1, TailSym0, TailSym1, InitSym0, InitSym1, NullSym0, NullSym1, MapSym0, MapSym1, MapSym2, ReverseSym0, ReverseSym1, IntersperseSym0, IntersperseSym1, IntersperseSym2, IntercalateSym0, IntercalateSym1, IntercalateSym2, SubsequencesSym0, SubsequencesSym1, PermutationsSym0, PermutationsSym1, FoldlSym0, FoldlSym1, FoldlSym2, FoldlSym3, Foldl'Sym0, Foldl'Sym1, Foldl'Sym2, Foldl'Sym3, Foldl1Sym0, Foldl1Sym1, Foldl1Sym2, Foldl1'Sym0, Foldl1'Sym1, Foldl1'Sym2, FoldrSym0, FoldrSym1, FoldrSym2, FoldrSym3, Foldr1Sym0, Foldr1Sym1, Foldr1Sym2, ConcatSym0, ConcatSym1, ConcatMapSym0, ConcatMapSym1, ConcatMapSym2, AndSym0, AndSym1, OrSym0, OrSym1, Any_Sym0, Any_Sym1, Any_Sym2, AllSym0, AllSym1, AllSym2, ScanlSym0, ScanlSym1, ScanlSym2, ScanlSym3, Scanl1Sym0, Scanl1Sym1, Scanl1Sym2, ScanrSym0, ScanrSym1, ScanrSym2, ScanrSym3, Scanr1Sym0, Scanr1Sym1, Scanr1Sym2, MapAccumLSym0, MapAccumLSym1, MapAccumLSym2, MapAccumLSym3, MapAccumRSym0, MapAccumRSym1, MapAccumRSym2, MapAccumRSym3, UnfoldrSym0, UnfoldrSym1, UnfoldrSym2, InitsSym0, InitsSym1, TailsSym0, TailsSym1, IsPrefixOfSym0, IsPrefixOfSym1, IsPrefixOfSym2, IsSuffixOfSym0, IsSuffixOfSym1, IsSuffixOfSym2, IsInfixOfSym0, IsInfixOfSym1, IsInfixOfSym2, ElemSym0, ElemSym1, ElemSym2, NotElemSym0, NotElemSym1, NotElemSym2, ZipSym0, ZipSym1, ZipSym2, Zip3Sym0, Zip3Sym1, Zip3Sym2, Zip3Sym3, ZipWithSym0, ZipWithSym1, ZipWithSym2, ZipWithSym3, ZipWith3Sym0, ZipWith3Sym1, ZipWith3Sym2, ZipWith3Sym3, ZipWith3Sym4, UnzipSym0, UnzipSym1, Unzip3Sym0, Unzip3Sym1, Unzip4Sym0, Unzip4Sym1, Unzip5Sym0, Unzip5Sym1, Unzip6Sym0, Unzip6Sym1, Unzip7Sym0, Unzip7Sym1, DeleteSym0, DeleteSym1, DeleteSym2, (:\\$), (:\\$$), (:\\$$$), IntersectSym0, IntersectSym1, IntersectSym2, InsertSym0, InsertSym1, InsertSym2, SortSym0, SortSym1, DeleteBySym0, DeleteBySym1, DeleteBySym2, DeleteBySym3, DeleteFirstsBySym0, DeleteFirstsBySym1, DeleteFirstsBySym2, DeleteFirstsBySym3, IntersectBySym0, IntersectBySym1, IntersectBySym2, SortBySym0, SortBySym1, SortBySym2, InsertBySym0, InsertBySym1, InsertBySym2, InsertBySym3, MaximumBySym0, MaximumBySym1, MaximumBySym2, MinimumBySym0, MinimumBySym1, MinimumBySym2, LengthSym0, LengthSym1, SumSym0, SumSym1, ProductSym0, ProductSym1, ReplicateSym0, ReplicateSym1, ReplicateSym2, TransposeSym0, TransposeSym1, TakeSym0, TakeSym1, TakeSym2, DropSym0, DropSym1, DropSym2, SplitAtSym0, SplitAtSym1, SplitAtSym2, TakeWhileSym0, TakeWhileSym1, TakeWhileSym2, DropWhileSym0, DropWhileSym1, DropWhileSym2, DropWhileEndSym0, DropWhileEndSym1, DropWhileEndSym2, SpanSym0, SpanSym1, SpanSym2, BreakSym0, BreakSym1, BreakSym2, StripPrefixSym0, StripPrefixSym1, StripPrefixSym2, MaximumSym0, MaximumSym1, MinimumSym0, MinimumSym1, GroupSym0, GroupSym1, GroupBySym0, GroupBySym1, GroupBySym2, LookupSym0, LookupSym1, LookupSym2, FindSym0, FindSym1, FindSym2, FilterSym0, FilterSym1, FilterSym2, PartitionSym0, PartitionSym1, PartitionSym2, (:!!$), (:!!$$), (:!!$$$), ElemIndexSym0, ElemIndexSym1, ElemIndexSym2, ElemIndicesSym0, ElemIndicesSym1, ElemIndicesSym2, FindIndexSym0, FindIndexSym1, FindIndexSym2, FindIndicesSym0, FindIndicesSym1, FindIndicesSym2, Zip4Sym0, Zip4Sym1, Zip4Sym2, Zip4Sym3, Zip4Sym4, Zip5Sym0, Zip5Sym1, Zip5Sym2, Zip5Sym3, Zip5Sym4, Zip5Sym5, Zip6Sym0, Zip6Sym1, Zip6Sym2, Zip6Sym3, Zip6Sym4, Zip6Sym5, Zip6Sym6, Zip7Sym0, Zip7Sym1, Zip7Sym2, Zip7Sym3, Zip7Sym4, Zip7Sym5, Zip7Sym6, Zip7Sym7, ZipWith4Sym0, ZipWith4Sym1, ZipWith4Sym2, ZipWith4Sym3, ZipWith4Sym4, ZipWith4Sym5, ZipWith5Sym0, ZipWith5Sym1, ZipWith5Sym2, ZipWith5Sym3, ZipWith5Sym4, ZipWith5Sym5, ZipWith5Sym6, ZipWith6Sym0, ZipWith6Sym1, ZipWith6Sym2, ZipWith6Sym3, ZipWith6Sym4, ZipWith6Sym5, ZipWith6Sym6, ZipWith6Sym7, ZipWith7Sym0, ZipWith7Sym1, ZipWith7Sym2, ZipWith7Sym3, ZipWith7Sym4, ZipWith7Sym5, ZipWith7Sym6, ZipWith7Sym7, ZipWith7Sym8, NubSym0, NubSym1, NubBySym0, NubBySym1, NubBySym2, UnionSym0, UnionSym1, UnionSym2, UnionBySym0, UnionBySym1, UnionBySym2, UnionBySym3, GenericLengthSym0, GenericLengthSym1, GenericTakeSym0, GenericTakeSym1, GenericTakeSym2, GenericDropSym0, GenericDropSym1, GenericDropSym2, GenericSplitAtSym0, GenericSplitAtSym1, GenericSplitAtSym2, GenericIndexSym0, GenericIndexSym1, GenericIndexSym2, GenericReplicateSym0, GenericReplicateSym1, GenericReplicateSym2, ) where import Data.Singletons.Prelude.Base import Data.Singletons.Prelude.Eq import Data.Singletons.Prelude.List import Data.Singletons.Prelude.Maybe import Data.Singletons.TH $(promoteOnly [d| -- Overlapping patterns don't singletonize stripPrefix :: Eq a => [a] -> [a] -> Maybe [a] stripPrefix [] ys = Just ys stripPrefix (x:xs) (y:ys) | x == y = stripPrefix xs ys stripPrefix _ _ = Nothing -- To singletonize these we would need to rewrite all patterns -- as non-overlapping. This means 2^7 equations for zipWith7. zip4 :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)] zip4 = zipWith4 (,,,) zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)] zip5 = zipWith5 (,,,,) zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a,b,c,d,e,f)] zip6 = zipWith6 (,,,,,) zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a,b,c,d,e,f,g)] zip7 = zipWith7 (,,,,,,) zipWith4 :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e] zipWith4 z (a:as) (b:bs) (c:cs) (d:ds) = z a b c d : zipWith4 z as bs cs ds zipWith4 _ _ _ _ _ = [] zipWith5 :: (a->b->c->d->e->f) -> [a]->[b]->[c]->[d]->[e]->[f] zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) = z a b c d e : zipWith5 z as bs cs ds es zipWith5 _ _ _ _ _ _ = [] zipWith6 :: (a->b->c->d->e->f->g) -> [a]->[b]->[c]->[d]->[e]->[f]->[g] zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) = z a b c d e f : zipWith6 z as bs cs ds es fs zipWith6 _ _ _ _ _ _ _ = [] zipWith7 :: (a->b->c->d->e->f->g->h) -> [a]->[b]->[c]->[d]->[e]->[f]->[g]->[h] zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs) = z a b c d e f g : zipWith7 z as bs cs ds es fs gs zipWith7 _ _ _ _ _ _ _ _ = [] -- These functions use Integral or Num typeclass instead of Int. -- -- genericLength, genericTake, genericDrop, genericSplitAt, genericIndex -- genericReplicate -- -- We provide aliases below to improve compatibility genericTake :: (Integral i) => i -> [a] -> [a] genericTake = take genericDrop :: (Integral i) => i -> [a] -> [a] genericDrop = drop genericSplitAt :: (Integral i) => i -> [a] -> ([a], [a]) genericSplitAt = splitAt genericIndex :: (Integral i) => [a] -> i -> a genericIndex = (!!) genericReplicate :: (Integral i) => i -> a -> [a] genericReplicate = replicate |])
int-index/singletons
src/Data/Promotion/Prelude/List.hs
Haskell
bsd-3-clause
10,266
module Horbits.UI.Camera.Zoom (ZoomModel(..), linearZoom, geometricZoom, maxZoom) where import Control.Applicative import Control.Lens import Control.Monad import Data.List.NonEmpty as NE newtype ZoomModel a = ZoomModel (NonEmpty a) deriving (Show, Eq) maxZoom :: Getting a (ZoomModel a) a maxZoom = to $ \(ZoomModel zooms) -> NE.last zooms linearZoom :: (Num a, Ord a) => a -> (a, a) -> ZoomModel a linearZoom step = ZoomModel . unfoldZooms (+ step) geometricZoom :: (Num a, Ord a) => a -> (a, a) -> ZoomModel a geometricZoom step = ZoomModel . unfoldZooms (* step) unfoldZooms :: Ord a => (a -> a) -> (a, a) -> NonEmpty a unfoldZooms nextScale (minScale, maxScale) = NE.unfold f minScale where f s = (s, nextScale <$> mfilter (< maxScale) (Just s))
chwthewke/horbits
src/horbits/Horbits/UI/Camera/Zoom.hs
Haskell
bsd-3-clause
805
{-# LANGUAGE OverloadedStrings #-} import System.FilePath.FindCompat((||?),always,extension,find,(==?)) import qualified Data.ByteString as BS import Control.Applicative((<$>)) import qualified Data.ByteString.Char8 as BSC import Text.Regex import Maybe(isJust,fromJust) import System(getArgs) import qualified Data.List as L import Data.List(foldl') import Data.Char(toLower) (=~) :: String -> String -> Bool (=~) inp pat = isJust $ matchRegex (mkRegex pat) inp headerFiles = find always (extension ==? ".h") headerAndSourceFiles = find always (extension ==? ".h" ||? extension ==? ".c") main = do (p:ws:_) <- getArgs hss <- headerFiles ws headersAndSources <- headerAndSourceFiles p mapM_ (fixIncludes hss) headersAndSources fixIncludes :: [FilePath] -> FilePath -> IO () fixIncludes allPaths p = do allLines <- BSC.lines <$> BS.readFile p BS.writeFile p (BSC.unlines $ map fixLine allLines) where fixLine x = if BSC.unpack x =~ "^#include\\s" then correctCases x else x correctCases x = let include = (BSC.unpack . head . tail . BSC.splitWith (== '"')) x in BSC.pack $ "#include \"" ++ findMatching include ++ "\"" findMatching :: FilePath -> FilePath findMatching i = let mm = L.findIndex (== cI) cAllPaths in if isJust mm then allPaths!!fromJust mm else i where cI = map toLower i cAllPaths = [map toLower p | p <- allPaths]
marcmo/includeSpellChecker
old/checker_old.hs
Haskell
bsd-3-clause
1,497
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Temperature.TR.Rules ( rules ) where import Data.Maybe import Prelude import Data.String import Duckling.Dimensions.Types import Duckling.Temperature.Helpers import qualified Duckling.Temperature.Types as TTemperature import Duckling.Temperature.Types (TemperatureData(..)) import Duckling.Types ruleTemperatureDegrees :: Rule ruleTemperatureDegrees = Rule { name = "<latent temp> degrees" , pattern = [ Predicate $ isValueOnly False , regex "derece|°" ] , prod = \case (Token Temperature td:_) -> Just . Token Temperature $ withUnit TTemperature.Degree td _ -> Nothing } ruleTemperatureCelsius :: Rule ruleTemperatureCelsius = Rule { name = "<temp> Celsius" , pattern = [ Predicate $ isValueOnly True , regex "c|santigrat" ] , prod = \case (Token Temperature td:_) -> Just . Token Temperature $ withUnit TTemperature.Celsius td _ -> Nothing } ruleTemperatureFahrenheit :: Rule ruleTemperatureFahrenheit = Rule { name = "<temp> Fahrenheit" , pattern = [ Predicate $ isValueOnly True , regex "f(ahrenh?ayt)?" ] , prod = \case (Token Temperature td:_) -> Just . Token Temperature $ withUnit TTemperature.Fahrenheit td _ -> Nothing } ruleTemperatureBelowZero :: Rule ruleTemperatureBelowZero = Rule { name = "below zero <temp>" , pattern = [ regex "s\305f\305r\305n alt\305nda" , Predicate $ isValueOnly True ] , prod = \case (_:Token Temperature td@TemperatureData{TTemperature.value = Just v}:_) -> case TTemperature.unit td of Nothing -> Just . Token Temperature . withUnit TTemperature.Degree $ td {TTemperature.value = Just (- v)} _ -> Just . Token Temperature $ td {TTemperature.value = Just (- v)} _ -> Nothing } ruleTemperatureBelowZeroReverse :: Rule ruleTemperatureBelowZeroReverse = Rule { name = "<temp> below zero" , pattern = [ Predicate $ isValueOnly True , regex "s\305f\305r\305n alt\305nda" ] , prod = \case (Token Temperature td@TemperatureData{TTemperature.value = Just v}:_) -> case TTemperature.unit td of Nothing -> Just . Token Temperature . withUnit TTemperature.Degree $ td {TTemperature.value = Just (- v)} _ -> Just . Token Temperature $ td {TTemperature.value = Just (- v)} _ -> Nothing } rules :: [Rule] rules = [ ruleTemperatureDegrees , ruleTemperatureCelsius , ruleTemperatureFahrenheit , ruleTemperatureBelowZero , ruleTemperatureBelowZeroReverse ]
facebookincubator/duckling
Duckling/Temperature/TR/Rules.hs
Haskell
bsd-3-clause
2,859
{-# LANGUAGE QuasiQuotes #-} module ApiSpecSpec (main,spec) where import Control.Lens hiding ((.=)) import Data.Aeson import Data.Aeson.QQ import qualified Data.ByteString.Lazy as LazyBytes import qualified Data.HashMap.Strict as Map import Data.Text (Text) import Lib.Swagger.ApiSpec import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do petStoreJson <- runIO $ LazyBytes.readFile "test/pet-store-1.2.json" let Right v = eitherDecode' petStoreJson describe "meh" $ do let o = object [ "code" .= (400 :: Int) , "message" .= ("message" :: Text) , "responseModel" .= ("model" :: Text) ] Success resp = fromJSON o :: Result ApiSpecResponseMessage it "does something" $ resp ^. apiSpecResponseMessageCode `shouldBe` 400 it "does something" $ resp ^. apiSpecResponseMessageMessage `shouldBe` "message" it "does something" $ resp ^. apiSpecResponseMessageResponseModel `shouldBe` Just "model" describe "meh" $ do it "does something" $ fromJSON respMessageJson `shouldBe` Success respVal describe "api spec" $ do it "parses swagger version" $ v ^. apiSpecSwaggerVersion `shouldBe` "1.2" it "parses api version" $ v ^. apiSpecApiVersion `shouldBe` Just "1.0.0" it "parses api base path" $ v ^. apiSpecBasePath `shouldBe` "http://petstore.swagger.wordnik.com/api" it "parses resource path" $ v ^. apiSpecResourcePath `shouldBe` Just "/pet" it "parses what api consumes" $ v ^. apiSpecConsumes `shouldBe` Nothing it "parses what api produces" $ v ^. apiSpecProduces `shouldBe` Just [ "application/json" , "application/xml" , "text/plain" , "text/html"] describe "api spec - apis" $ it "parses apis" $ v ^. apiSpecApis ^.. each . apiSpecApiPath `shouldBe` [ "/pet/{petId}" , "/pet" , "/pet/findByStatus" , "/pet/findByTags" , "/pet/uploadImage"] describe "api spec - /pet/{petId} endpoint" $ do let api = v ^. apiSpecApis ^.. folded . filtered (\ x -> x ^. apiSpecApiPath == "/pet/{petId}") ^. singular _head it "has correct path" $ api ^. apiSpecApiPath `shouldBe` "/pet/{petId}" it "has correct description" $ api ^. apiSpecApiDescription `shouldBe` Nothing context "operations - GET" $ do let getOp = api ^. apiSpecOperation ^.. folded . filtered (\ x -> x ^. apiSpecOperationMethod == "GET") ^. singular _head it "has correct method" $ getOp ^. apiSpecOperationMethod `shouldBe` "GET" it "has correct summary" $ getOp ^. apiSpecOperationSummary `shouldBe` Just "Find pet by ID" it "has correct notes" $ getOp ^. apiSpecOperationNotes `shouldBe` Just "Returns a pet based on ID" it "has correct nickname" $ getOp ^. apiSpecOperationNickname `shouldBe` "getPetById" it "has correct authorizations" $ getOp ^. apiSpecOperationAuthorizations `shouldBe` Just Map.empty context "parameters" $ do let params = getOp ^. apiSpecOperationParameters context "petId" $ do let petIdParam = params ^.. folded . filtered (\ x -> x ^. apiSpecParameterName == "petId") ^. singular _head it "has correct param type" $ petIdParam ^. apiSpecParameterParamType `shouldBe` "path" it "has correct name" $ petIdParam ^. apiSpecParameterName `shouldBe` "petId" it "has correct description" $ petIdParam ^. apiSpecParameterDescription `shouldBe` Just "ID of pet that needs to be fetched" it "has correct required attribute" $ petIdParam ^. apiSpecParameterRequired `shouldBe` Just True it "has correct allowMultiple attribute" $ petIdParam ^. apiSpecParameterAllowMultiple `shouldBe` Just False it "has correct field type" $ petIdParam ^. apiSpecParameterDataTypeFieldType `shouldBe` Just "integer" it "has correct field format" $ petIdParam ^. apiSpecParameterDataTypeFieldFormat `shouldBe` Just "int64" it "has correct field default value" $ petIdParam ^. apiSpecParameterDataTypeFieldDefaultValue `shouldBe` Nothing it "has correct field enum" $ petIdParam ^. apiSpecParameterDataTypeFieldEnum `shouldBe` Nothing it "has correct field minimum" $ petIdParam ^. apiSpecParameterDataTypeFieldMinimum `shouldBe` Just "1.0" it "has correct field maximum" $ petIdParam ^. apiSpecParameterDataTypeFieldMaximum `shouldBe` Just "100000.0" context "response messages" $ do context "400" $ do let resp400 = getOp ^. apiSpecOperationResponseMessages ^. _Just ^.. folded . filtered (\ x -> x ^. apiSpecResponseMessageCode == 400) ^. singular _head it "has correct code" $ resp400 ^. apiSpecResponseMessageCode `shouldBe` 400 it "has correct message" $ resp400 ^. apiSpecResponseMessageMessage `shouldBe` "Invalid ID supplied" it "has correct model" $ resp400 ^. apiSpecResponseMessageResponseModel `shouldBe` Nothing context "404" $ do let resp404 = getOp ^. apiSpecOperationResponseMessages ^. _Just ^.. folded . filtered (\ x -> x ^. apiSpecResponseMessageCode == 404) ^. singular _head it "has correct code" $ resp404 ^. apiSpecResponseMessageCode `shouldBe` 404 it "has correct message" $ resp404 ^. apiSpecResponseMessageMessage `shouldBe` "Pet not found" it "has correct model" $ resp404 ^. apiSpecResponseMessageResponseModel `shouldBe` Nothing respVal :: ApiSpecResponseMessage respVal = mempty & apiSpecResponseMessageCode .~ 400 & apiSpecResponseMessageMessage .~ "Invalid ID supplied" & apiSpecResponseMessageResponseModel .~ Nothing respMessageJson :: Value respMessageJson = [aesonQQ| { "code": 400, "message": "Invalid ID supplied" } |]
pbogdan/swagger
test/ApiSpecSpec.hs
Haskell
bsd-3-clause
7,996
{-# LANGUAGE QuasiQuotes #-} import LiquidHaskell import Prelude hiding (reverse) foo :: Int -> Int -> Int [lq| foo :: n:Nat -> m:Nat -> Nat /[n+m] |] foo n m | cond 1 = 0 | cond 2 && n > 1 = foo (n-1) m | cond 3 && m > 2 = foo (n+1) (m-2) [lq| cond :: Int -> Bool |] cond :: Int -> Bool cond _ = undefined data L a = N | C a (L a) [lq| data L [llen] |] [lq| measure llen :: (L a) -> Int llen(N) = 0 llen(C x xs) = 1 + (llen xs) |] [lq| invariant {v: L a | (llen v) >= 0} |] [lq| reverse :: xs: L a -> ys : L a -> L a / [(llen ys)] |] reverse :: L a -> L a -> L a reverse xs N = xs reverse xs (C y ys) = reverse (C y xs) ys merge :: Ord a => L a -> L a -> L a [lq| merge :: Ord a => xs:L a -> ys:L a -> L a /[(llen xs) + (llen ys)]|] merge (C x xs) (C y ys) | x > y = C x $ merge xs (C y ys) | otherwise = C y $ merge (C x xs) ys
spinda/liquidhaskell
tests/gsoc15/unknown/pos/GeneralizedTermination.hs
Haskell
bsd-3-clause
898
module Main (main) where import Criterion.Main (bgroup, defaultMain) import qualified MVC.ServiceBench main :: IO () main = defaultMain [ bgroup "MVC.Service" MVC.ServiceBench.benchmarks ]
cmahon/mvc-service
benchmark/Bench.hs
Haskell
bsd-3-clause
209
-- | {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} module WebApi.Schema where import Data.Proxy import WebApi.Docs import Language.Haskell.TH.Quote import Language.Haskell.TH import Data.Text (Text) discovery :: Proxy api -> () discovery = undefined
byteally/webapi
webapi-docs/src/WebApi/Schema.hs
Haskell
bsd-3-clause
339
{-# Language OverloadedStrings #-} -------------------------------------------------------------------- -- | -- Module : Utils.Katt.Utils -- -- Contains shared type declarations and various utility functions. -- module Utils.Katt.Utils where import Control.Error hiding (tryIO) import qualified Control.Exception as E import Control.Lens import Control.Monad (liftM) import Control.Monad.Trans (lift) import qualified Control.Monad.State as S import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as BL import Data.Monoid ((<>)) import qualified Network.Wreq as W import qualified Network.Wreq.Session as WS import System.Exit (exitFailure) import System.IO (stderr) -- | Configuration layer consisting of configuration state. type ConfigEnvInternal m = S.StateT ConfigState m -- | Configuration layer wrapped with error handling. type ConfigEnv m = EitherT ErrorDesc (ConfigEnvInternal m) -- | Submissions consist of a problem identifier and a set of file paths. type Submission = (KattisProblem, [FilePath]) -- | Error description alias. type ErrorDesc = B.ByteString -- | Submissions are identified with an integer id. type SubmissionId = Integer -- -- | Problem sessions are identified with an integer id. type ProblemSession = Integer -- | Project-specific state consists of the problem name. type ProjectState = (KattisProblem) -- | Global configuration, initialized from the /.kattisrc/ file. data ConfigState = ConfigState { -- | Username. user :: B.ByteString, -- | API token (hash). apiKey :: B.ByteString, -- | Host to be considered as service. host :: B.ByteString, -- | URL to login page, relative 'host'. loginPage :: B.ByteString, -- | URL to submit page, relative 'host'. submitPage :: B.ByteString, -- | Project-specific state, optionally loaded. project :: Maybe ProjectState } deriving Show -- | HTTP client session and the host path. type Session = (WS.Session, B.ByteString) -- | A Kattis problem. data KattisProblem -- | Problem ID, unique. = ProblemId Integer -- | Associated name of the problem. | ProblemName B.ByteString deriving (Eq, Show) -- | Language used in submission. data KattisLanguage -- | C++. = LangCplusplus -- | Java. | LangJava -- | C. | LangC -- | Haskell. | LangHaskell deriving (Eq, Show) -- | Server response indicating successful login. loginSuccess :: B.ByteString loginSuccess = "Login successful" -- | Extension of input test files. inputTestExtension :: FilePath inputTestExtension = ".in" -- | Extension of reference ouput test files. outputTestExtension :: FilePath outputTestExtension = ".ans" -- | Name of this program. programName :: B.ByteString programName = "katt" -- | Relative path to project-specific configuration directory. configDir :: B.ByteString configDir = "." <> programName -- | Relative path to folder containing tests. testFolder :: FilePath testFolder = "tests" -- | URL to page with problem information, relative to 'host'. problemAddress :: B.ByteString problemAddress = "/problems/" -- | Lift some error monad one layer. unWrapTrans :: (Monad m, S.MonadTrans t) => EitherT e m a -> EitherT e (t m) a unWrapTrans = EitherT . lift . runEitherT -- | Execute an IO action and catch any exceptions. tryIO :: S.MonadIO m => IO a -> EitherT ErrorDesc m a tryIO = EitherT . S.liftIO . liftM (fmapL (B.pack . show)) . (E.try :: (IO a -> IO (Either E.SomeException a))) -- | Execute an IO action and catch any exceptions, tagged with description. tryIOMsg :: S.MonadIO m => B.ByteString -> IO a -> EitherT ErrorDesc m a tryIOMsg msg = EitherT . S.liftIO . liftM (fmapL $ const msg) . (E.try :: (IO a -> IO (Either E.SomeException a))) -- | Evaluate an error action and terminate process upon failure. terminateOnFailure :: S.MonadIO m => ErrorDesc -> EitherT ErrorDesc m a -> m a terminateOnFailure msg state = do res <- runEitherT state S.liftIO $ case res of Left errorMessage -> do B.hPutStrLn stderr $ msg <> ", error: " <> errorMessage exitFailure Right success -> return success -- | Default HTTP options. defaultOpts :: W.Options defaultOpts = W.defaults & W.header "User-Agent" .~ [programName] -- | Retrieve a publicly available page, using HTTP GET. retrievePublicPage :: B.ByteString -> ConfigEnv IO B.ByteString retrievePublicPage path = do host' <- S.gets host reply <- tryIO $ W.getWith defaultOpts $ buildURL host' path return . B.concat . BL.toChunks $ reply ^. W.responseBody -- | Retrieve a page requiring authentication, using HTTP GET. retrievePrivatePage :: Session -> B.ByteString -> EitherT ErrorDesc IO B.ByteString retrievePrivatePage (sess, host') page = do reply <- tryIO $ WS.getWith defaultOpts sess (buildURL host' page) return . B.concat . BL.toChunks $ reply ^. W.responseBody -- | Construct URL from host path (e.g. /http:\/\/x.com\/) and path (e.g. //). buildURL :: B.ByteString -> B.ByteString -> String buildURL host' path = B.unpack $ host' <> "/" <> path -- | Authenticate and run the provided action. withAuth :: (WS.Session -> EitherT ErrorDesc IO a) -> ConfigEnv IO a withAuth action = do conf <- S.get EitherT . S.liftIO . WS.withSession $ \sess -> runEitherT $ do let formData = [("token" :: B.ByteString, apiKey conf), ("user", user conf), ("script", "true")] url = buildURL (host conf) (loginPage conf) reply <- tryIO $ WS.postWith defaultOpts sess url formData let response = B.concat . BL.toChunks $ reply ^. W.responseBody tryAssert ("Login failure. Server returned: '" <> response <> "'") (response == loginSuccess) action sess -- | Retrieve problem ID of a Kattis problem. retrieveProblemId :: KattisProblem -> IO Integer retrieveProblemId (ProblemId id') = return id' retrieveProblemId (ProblemName _) = undefined -- | Retrieve problem name of a Kattis problem. retrieveProblemName :: KattisProblem -> IO B.ByteString retrieveProblemName (ProblemId _) = undefined retrieveProblemName (ProblemName name) = return name
davnils/katt
katt-lib/src/Utils/Katt/Utils.hs
Haskell
bsd-3-clause
6,195
module Day12 (part1,part2,test1) where import Control.Applicative import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Text.Trifecta type Register = Char data Instruction = CpyI Integer Register | CpyR Register Register | Inc Register | Dec Register | JnzR Register Integer | JnzI Integer Integer deriving (Eq, Ord, Show) type CurrentPosition = Int data ProgramState = ProgramState CurrentPosition [Instruction] (Map Register Integer) deriving (Eq, Ord, Show) startState :: [Instruction] -> ProgramState startState is = ProgramState 0 is Map.empty startState2 :: [Instruction] -> ProgramState startState2 is = ProgramState 0 is $ Map.fromList [('c',1)] instructionParser :: Parser Instruction instructionParser = try cpyIParser <|> try cpyRParser <|> try incParser <|> try decParser <|> try jnzRParser <|> jnzIParser where cpyIParser = string "cpy " *> (CpyI <$> integer <*> letter) cpyRParser = string "cpy " *> (CpyR <$> letter <*> (space *> letter)) incParser = string "inc " *> (Inc <$> letter) decParser = string "dec " *> (Dec <$> letter) jnzRParser = string "jnz " *> (JnzR <$> letter <*> (space *> integer )) jnzIParser = string "jnz " *> (JnzI <$> integer <*> integer) fromSuccess :: Result x -> x fromSuccess (Success x) = x fromSuccess (Failure x) = error (show x) parseInput :: String -> [Instruction] parseInput = fromSuccess . parseString (some (instructionParser <* skipOptional windowsNewLine)) mempty where windowsNewLine = const () <$ skipOptional newline <*> skipOptional (char '\r') doNextInstruction :: ProgramState -> ProgramState doNextInstruction ps@(ProgramState i instructions rMap) | i >= length instructions = ps | otherwise = ProgramState (newI currInstruction) instructions (newMap currInstruction) where currInstruction = instructions !! i newI (JnzR r x) | currVal r > 0 = i + fromIntegral x | otherwise = i+1 newI (JnzI x y) | x > 0 = i + fromIntegral y | otherwise = i+1 newI _ = i+1 currVal r = Map.findWithDefault 0 r rMap newMap (CpyI x r) = Map.insert r x rMap newMap (CpyR x y) = Map.insert y (currVal x) rMap newMap (Inc r) = Map.insert r (currVal r + 1) rMap newMap (Dec r) = Map.insert r (currVal r - 1) rMap newMap (JnzR _ _) = rMap newMap (JnzI _ _) = rMap endOfInstruction :: ProgramState -> Bool endOfInstruction (ProgramState i instructions _) = i >= length instructions getRegister :: Register -> ProgramState -> Integer getRegister r (ProgramState _ _ rMap) = Map.findWithDefault 0 r rMap part1 :: Char -> String -> Integer part1 c = getRegister c . last . takeWhile (not . endOfInstruction) . iterate doNextInstruction . startState . parseInput part2 :: Char -> String -> Integer part2 c = getRegister c . last . takeWhile (not . endOfInstruction) . iterate doNextInstruction . startState2 . parseInput part1Solution :: IO Integer part1Solution = part1 'a' <$> readFile "./data/Day12.txt" part2Solution :: IO Integer part2Solution = part2 'a' <$> readFile "./data/Day12.txt" test1 :: String test1="cpy 41 a\ninc a\ninc a\ndec a\njnz a 2\ndec a"
z0isch/aoc2016
src/Day12.hs
Haskell
bsd-3-clause
3,240
#!/usr/bin/runhaskell module Main where import GameLoader import Data.String.Utils import Website main = do putStrLn "Welcome to the HSB.\nPlease standby..." putStrLn "Loading Team Info" teamInfos <- loadTeams writeFile "teamdata.csv" . join "\n" . map show $ teamInfos --Write the main team info out for AO putStrLn "Finished loading team info. CSV was written to 'teamdata.csv'" --Build Website-- putStrLn "Building the Static Website..." generateSite teamInfos
TheGreenMachine/Scouting-Backend
src/Main.hs
Haskell
bsd-3-clause
479
{-# LANGUAGE TemplateHaskell #-} ----------------------------------------------------------------------------- -- | -- Licence : BSD-style (see LICENSE) -- -- Embeded driver assembly that helps in generating bindings. -- ----------------------------------------------------------------------------- module Foreign.Salsa.Driver (driverData) where import qualified Data.ByteString.Char8 as B import Data.FileEmbed {-# NOINLINE driverData #-} driverData :: B.ByteString driverData = $(embedFile "Driver/Salsa.dll")
tim-m89/Salsa
Foreign/Salsa/Driver.hs
Haskell
bsd-3-clause
524
module Language.Haskell.Stepeval (Scope, eval, itereval, printeval, stepeval) where import Control.Arrow (first) import Control.Applicative ((<$), (<$>), (<*>), (<|>)) import Control.Monad (guard, join, replicateM) import Data.Foldable (foldMap) import Data.List (delete, find, partition, unfoldr) import Data.Maybe (fromMaybe, mapMaybe) import Data.Monoid (Endo (Endo, appEndo)) import Data.Generics (Data, Typeable, everything, everywhereBut, extQ, extT, gmapQ, gmapT, listify, mkQ, mkT) import qualified Data.Set as Set (fromList, toList) import Language.Haskell.Exts ( Alt (Alt), Binds (BDecls), Boxed (Boxed), Decl (PatBind, FunBind, InfixDecl), Exp (App, Case, Con, Do, If, InfixApp, Lambda, LeftSection, Let, List, Lit, Paren, RightSection, Tuple, TupleSection, Var), GuardedAlt (GuardedAlt), GuardedAlts (UnGuardedAlt, GuardedAlts), Literal (Char, Frac, Int, String), Match (Match), Op (ConOp, VarOp), Pat (PApp, PAsPat, PInfixApp, PList, PLit, PParen, PTuple, PVar, PWildCard), Name (Ident, Symbol), QName (Special, Qual, UnQual), QOp (QConOp, QVarOp), Rhs (UnGuardedRhs), SpecialCon (Cons, TupleCon), SrcLoc (), -- (SrcLoc), Stmt (Generator, LetStmt, Qualifier), preludeFixities, prettyPrint) import Parenthise (deparen, enparenWith, scopeToFixities) -- | Evaluate an expression as completely as possible. eval :: Scope -> Exp -> Exp eval s = last . itereval s -- | Print each step of the evaluation of an expression. printeval :: Scope -> Exp -> IO () printeval s = mapM_ (putStrLn . prettyPrint) . itereval s -- | Make a list of the evaluation steps of an expression. -- Note that @head (itereval s exp) == exp@ itereval :: Scope -> Exp -> [Exp] itereval s e = e : unfoldr (fmap (join (,)) . stepeval s) e -- The use of preludeFixities here is questionable, since we don't use -- prelude functions, but it's more convenient in general. -- When we grow a proper Prelude of our own, it would be nice to use that -- instead. -- | Evaluate an expression by a single step, or give 'Nothing' if the -- evaluation failed (either because an error ocurred, or the expression was -- already as evaluated as possible) stepeval :: Scope -> Exp -> Maybe Exp stepeval s e = case step [s] e of Step (Eval e') -> Just (enparenWith fixes . deparen $ e') _ -> Nothing where fixes = scopeToFixities s ++ preludeFixities data Eval = EnvEval Decl | Eval Exp deriving Show data EvalStep = Failure | Done | Step Eval deriving Show data PatternMatch = NoMatch | MatchEval Eval | Matched [MatchResult] deriving Show -- | The result of a successful pattern match. The third field is meant to -- put the 'Exp' that was matched back into the context it came from, e.g. -- if you matched @[a,b,c]@ against @[1,2,3]@ then one of the 'MatchResult's -- would be approximately @'MatchResult' \"b\" 2 (\x -> [1,x,3])@ data MatchResult = MatchResult { mrName :: Name, mrExp :: Exp, mrFunc :: (Exp -> Exp) } type Scope = [Decl] type Env = [Scope] -- Involves an evil hack, but only useful for debugging anyway. instance Show MatchResult where showsPrec p (MatchResult n e f) = showParen (p >= 11) $ showString "MatchResult " . showN . sp . showE . sp . showF where sp = showString " " showN = showsPrec 11 n showE = showsPrec 11 e -- We assume a sensible function would not produce variables with -- empty names showF = showParen True $ showString "\\arg -> " . fixVar . shows (f (Var (UnQual (Ident "")))) -- Find and replace all instances of the empty variable with 'arg' fixVar s = case break (`elem` "(V") s of (r, "") -> r (r, '(':s') -> r ++ dropEq s' "Var (UnQual (Ident \"\")))" ('(':) (r, 'V':s') -> r ++ dropEq s' "ar (UnQual (Ident \"\"))" ('V':) _ -> error "MatchResult.Show: hack a splode" dropEq s "" _ = "arg" ++ fixVar s dropEq (x:xs) (d:ds) f | x == d = dropEq xs ds (f . (x:)) dropEq s _ f = f (fixVar s) -- | Map over e in @'Step' ('Eval' e)@ liftE :: (Exp -> Exp) -> EvalStep -> EvalStep liftE f (Step (Eval e)) = Step (Eval (f e)) liftE _ e = e -- | If either argument is a 'Step', return it, otherwise return the first. orE :: EvalStep -> EvalStep -> EvalStep orE r@(Step _) _ = r orE _ r@(Step _) = r orE r _ = r infixr 3 `orE` -- | Infix liftE. (|$|) :: (Exp -> Exp) -> EvalStep -> EvalStep (|$|) = liftE infix 4 |$| -- | @'Step' . 'Eval'@ yield :: Exp -> EvalStep yield = Step . Eval -- | The basic workhorse of the module - step the given expression in the -- given environment. step :: Env -> Exp -> EvalStep -- Variables step v (Var n) = need v (fromQName n) -- Function application step v e@(App f x) = magic v e `orE` case argList e of LeftSection e o : x : xs -> yield $ unArgList (InfixApp e o x) xs RightSection o e : x : xs -> yield $ unArgList (InfixApp x o e) xs f@(TupleSection _) : xs -> yield $ unArgList f xs f@(Con (Special (TupleCon _ _))) : xs -> yield $ unArgList f xs -- note that since we matched against an App, es should be non-empty Lambda s ps e : es -> applyLambda s ps e es where applyLambda _ [] _ _ = error "Lambda with no patterns?" applyLambda s ps e [] = yield $ Lambda s ps e applyLambda s ps@(p:qs) e (x:xs) = case patternMatch v p x of NoMatch -> Failure MatchEval r -> (\x -> unArgList (Lambda s ps e) $ x : xs) |$| Step r Matched ms -> case qs of [] -> yield $ unArgList (applyMatches ms e) xs qs | anywhere (`elem` mnames) qs -> yield . unArgList newLambda $ x : xs | otherwise -> applyLambda s qs (applyMatches ms e) xs where newLambda = Lambda s (fixNames ps) (fixNames e) fixNames :: Data a => a -> a -- the DMR strikes again -- The first pattern in the lambda is about to be gobbled. -- Rename every other pattern that will conflict with any of the -- names introduced by the pattern match. We avoid names already -- existing in the lambda, except for the one we're in the process -- of renaming (that would be silly) fixNames = appEndo $ foldMap (\n -> Endo $ alpha n (delete n lnames ++ mnames)) (freeNames qs) lnames = freeNames ps ++ freeNames e mnames = Set.toList . foldMap (Set.fromList . freeNames . mrExp) $ ms f@(Var q) : es -> case envLookup v (fromQName q) of Nothing -> Done Just (PatBind _ _ _ _ _) -> (\f' -> unArgList f' es) |$| step v f Just (FunBind ms) | null . drop (pred arity) $ es -> fallback | otherwise -> foldr (orE . app) fallback ms where arity = funArity ms (xs, r) = splitAt arity es app (Match _ _ ps _ (UnGuardedRhs e') (BDecls ds)) = case matches v ps xs (unArgList f) of NoMatch -> Failure MatchEval (Eval e') -> yield $ unArgList e' r MatchEval e -> Step e Matched ms -> yield . applyMatches ms . mkLet ds $ unArgList e' r app m = todo "step App Var app" m Just d -> todo "step App Var" d l@(Let (BDecls bs) f) : e : es -> foldr (orE . alphaBind) fallback incomingNames where incomingNames = freeNames e avoidNames = incomingNames ++ freeNames f alphaBind n | shadows n l = flip unArgList (e : es) |$| yield (uncurry mkLet (alpha n avoidNames (tidyBinds f bs, f))) | otherwise = yield $ unArgList (Let (BDecls bs) (App f e)) es _ -> fallback where fallback = flip app x |$| step v f `orE` app f |$| step v x step v e@(InfixApp p o q) = case o of QVarOp n -> magic v e `orE` step v (App (App (Var n) p) q) QConOp _ -> (\p' -> InfixApp p' o q) |$| step v p `orE` InfixApp p o |$| step v q -- Case step _ (Case _ []) = error "Case with no branches?" step v (Case e alts@(Alt l p a bs@(BDecls ds) : as)) = case patternMatch v p e of Matched rs -> case a of UnGuardedAlt x -> yield . applyMatches rs $ mkLet ds x -- here we apply the matches over all the guard bodies, which may not -- always have the most intuitive results GuardedAlts (GuardedAlt m ss x : gs) -> case ss of [] -> error "GuardedAlt with no body?" [Qualifier (Con (UnQual (Ident s)))] | s == "True" -> yield . applyMatches rs $ mkLet ds x | s == "False" -> if null gs -- no more guards, drop this alt then if not (null as) then yield $ Case e as else Failure -- drop this guard and move to the next else yield $ mkCase (GuardedAlts gs) | otherwise -> Failure -- Okay this is a bit evil. Basically we pretend the guard is being -- evaluated in a let-scope generated from the result of the pattern -- match. This allows us to use the same code that is supposed to -- implement sharing to work out if the scrutinee needs evaluation. -- If it does then we can step the bit that matched specifically -- (rather than the whole expression) and then use the laboriously- -- (but, with any luck, lazily-) constructed third field of -- MatchResult to recreate the rest of the scrutinee around it. [Qualifier q] -> case step (matchesToScope rs:ds:v) q of Step (Eval q') -> yield . mkCase . newAlt $ q' -- pattern matching nested this deeply is bad for readability r@(Step (EnvEval b@(PatBind _ (PVar n) _ (UnGuardedRhs e) (BDecls [])))) -> case mlookup n rs of Nothing -> case updateBind b ds of Nothing -> r Just ds' -> yield $ Case e (Alt l p a (BDecls ds') : as) Just (MatchResult _ _ r) -> yield $ Case (r e) alts r -> r a -> todo "step Case GuardedAlts" a where newAlt q = GuardedAlts (GuardedAlt m [Qualifier q] x : gs) mkCase a = Case e (Alt l p a bs : as) GuardedAlts [] -> error "Case branch with no expression?" MatchEval e -> case e of Eval e' -> yield $ Case e' alts r -> Step r NoMatch | null as -> Failure | otherwise -> yield $ Case e as step _ e@(Case _ _) = todo "step Case" e -- Let step _ (Let (BDecls []) e) = yield e step v (Let (BDecls bs) e) = case step (bs : v) e of Step (Eval e') -> yield $ mkLet bs e' Step (EnvEval e') -> Step $ tryUpdateBind e' e bs r -> r -- If step _ (If (Con (UnQual (Ident i))) t f) = case i of "True" -> yield t "False" -> yield f _ -> Failure step v (If e t f) = (\e -> If e t f) |$| step v e -- Desugarings step _ (Do []) = error "Empty do?" step _ (Do [Qualifier e]) = yield e step _ (Do [_]) = Failure step _ (Do (s:ss)) = case s of Qualifier e -> yield $ InfixApp e (op ">>") (Do ss) Generator s p e -> yield $ InfixApp e (op ">>=") (Lambda s [p] (Do ss)) LetStmt bs -> yield $ Let bs (Do ss) s -> todo "step Do" s where op = QVarOp . UnQual . Symbol -- Trivialities step v (Paren p) = step v p step v (Tuple xs) = case xs of [] -> error "Empty tuple?" [_] -> error "Singleton tuple?" es -> liststep v Tuple es -- Base cases step _ (LeftSection _ _) = Done step _ (RightSection _ _) = Done step _ (TupleSection _) = Done step _ (Lit _) = Done step _ (List []) = Done step _ (Con _) = Done step _ (Lambda _ _ _) = Done step _ e = todo "step _" e -- | Apply the function to the argument as neatly as possible - i.e. infix -- or make a section if the function's an operator app :: Exp -> Exp -> Exp app (Con q) x | isOperator q = LeftSection x (QConOp q) app (Var q) x | isOperator q = LeftSection x (QVarOp q) app (LeftSection x op) y = InfixApp x op y app (RightSection op y) x = InfixApp x op y app (TupleSection es) x = go es id where go (Nothing : es) f = case sequence es of Just es' -> Tuple $ f (x : es') Nothing -> TupleSection $ map Just (f [x]) ++ es go (Just e : es) f = go es (f . (e :)) go [] _ = error "app TupleSection: full section" app (Con (Special (TupleCon b i))) x | i <= 1 = error "app TupleCon: i <= 0" | b /= Boxed = todo "app TupleCon" b | otherwise = TupleSection (Just x : replicate (i - 1) Nothing) app f x = App f x -- | 'True' if the name refers to a non-tuple operator. Tuples are excluded -- because they're "mixfix" and therefore need to be considered separately -- anyway. isOperator :: QName -> Bool isOperator (Special Cons) = True isOperator (UnQual (Symbol _)) = True isOperator (Qual _ (Symbol _)) = True isOperator _ = False -- | Given a list of expressions, evaluate the first one that isn't already -- evaluated and then recombine them with the given function. liststep :: Env -> ([Exp] -> Exp) -> [Exp] -> EvalStep liststep v f es = go es id where go es g = case es of [] -> Done e:es -> case step v e of Step (Eval e') -> yield . f . g $ e':es Done -> go es (g . (e:)) r -> r -- | Make a let-expression from a list of bindings and an expression. The -- list of bindings has unused members removed; if this results in an empty -- list, the expression is returned unaltered. mkLet :: Scope -> Exp -> Exp mkLet ds x = case tidyBinds x ds of [] -> x ds' -> Let (BDecls ds') x -- | Create a list of 'Decl' that bind the patterns of the 'MatchResult's -- to their corresponding expressions. matchesToScope :: [MatchResult] -> Scope matchesToScope = map $ \(MatchResult n e _) -> PatBind nowhere (PVar n) Nothing (UnGuardedRhs e) (BDecls []) -- this shouldn't really exist nowhere :: SrcLoc nowhere = undefined -- nowhere = SrcLoc "<nowhere>" 0 0 -- for when Show needs to not choke -- This code isn't very nice, largely because I anticipate it all being -- replaced eventually anyway. -- | Implements primitives like addition and comparison. magic :: Env -> Exp -> EvalStep magic v e = case e of App (App (Var p) x) y -> rhs (fromQName p) x y InfixApp x (QVarOp o) y -> rhs (fromQName o) x y _ -> Done where rhs p x y = case lookup p primitives of Just (+*) -> case (step v x, step v y) of (Done, Done) -> x +* y (Done, y') -> InfixApp x op |$| y' (x', _) -> (\e -> InfixApp e op y) |$| x' where op = QVarOp (UnQual p) Nothing -> Done lit x = case properFraction (toRational x) of (i, 0) -> Lit (Int i) (i, r) -> Lit (Frac (toRational i + r)) con = Con . UnQual . Ident unlit (Lit (Int i)) = Just $ toRational i unlit (Lit (Frac r)) = Just r unlit _ = Nothing primitives = map (first Symbol) ops ++ map (first Ident) funs ops = [ ("+", num (+)), ("*", num (*)), ("-", num (-)), ("<", bool (<)), ("<=", bool (<=)), (">", bool (>)), (">=", bool (>=)), ("==", bool (==)), ("/=", bool (/=))] funs = [ ("div", mkOp (Lit . Int . floor) (/))] num op = mkOp lit op bool op = mkOp (con . show) op mkOp f g m n = maybe Done (yield . f) $ g <$> unlit m <*> unlit n -- | Given an expression and a list of bindings, filter out bindings that -- aren't used in the expression. tidyBinds :: Exp -> Scope -> Scope tidyBinds e v = filter (`elem` keep) v where keep = go (usedIn e) v go p ds = case partition p ds of ([], _) -> [] (ys, xs) -> ys ++ go ((||) <$> p <*> usedIn ys) xs binds (PatBind _ (PVar n) _ _ _) = [n] binds (FunBind ms) = [funName ms] -- FIXME: an InfixDecl can specify multiple ops, and we keep all or -- none - should drop the ones we no longer need binds (InfixDecl _ _ _ os) = map unOp os binds l = todo "tidyBinds binds" l usedIn es d = any (\n -> isFreeIn n es) (binds d) unOp (VarOp n) = n unOp (ConOp n) = n -- | Continuing evaluation requires the value of the given name from the -- environment, so try to look it up and step it or substitute it. need :: Env -> Name -> EvalStep need v n = case envBreak ((Just n ==) . declName) v of (_, _, [], _) -> Done (as, bs, c : cs, ds) -> case c of PatBind s (PVar n) t (UnGuardedRhs e) (BDecls []) -> case step ((bs ++ cs) : ds) e of Done -> case mapMaybe (envLookup as) $ freeNames e of [] -> yield e xs -> todo "panic" xs Step (Eval e') -> Step . EnvEval $ PatBind s (PVar n) t (UnGuardedRhs e') (BDecls []) f -> f FunBind _ -> Done b -> todo "need case" b -- | Name bound by the equations. Error if not all the matches are for the -- same function. funName :: [Match] -> Name funName [] = error "No matches?" funName (Match _ n _ _ _ _ : ms) = foldr match n ms where match (Match _ m _ _ _ _) n | m == n = n match m n = error $ "Match names don't? " ++ show (m, n) -- | Counts the number of patterns on the LHS of function equations. -- Error if the patterns have different numbers of arguments funArity :: [Match] -> Int funArity [] = error "No matches?" funArity (Match _ n ps _ _ _ : ms) = foldr match (length ps) ms where match (Match _ _ ps _ _ _) l | length ps == l = l match _ _ = error $ "Matches of different arity? " ++ show n {- Doubtful if this is useful, but I'm keeping it anyway funToCase :: [Match] -> Exp funToCase [] = error "No matches?" -- unsure of whether this is the right SrcLoc funToCase [Match s _ ps _ (UnGuardedRhs e) (BDecls [])] = Lambda s ps e funToCase ms@(Match s _ ps _ _ _ : _) = Lambda s qs $ Case e as where qs = map (PVar . Ident) names e = tuple $ map (Var . UnQual . Ident) names as = map matchToAlt ms tuple [] = error "No patterns in match?" tuple [x] = x tuple xs = Tuple xs names = zipWith const (concatMap (\i -> nameslen i) [1 ..]) ps nameslen i = replicateM i ['a' .. 'z'] matchToAlt (Match s _ ps _ r bs) = Alt s (ptuple ps) (rhsToAlt r) bs ptuple [] = error "No patterns in match?" ptuple [x] = x ptuple xs = PTuple xs rhsToAlt (UnGuardedRhs e) = UnGuardedAlt e rhsToAlt (GuardedRhss rs) = GuardedAlts $ map (\(GuardedRhs s t e) -> GuardedAlt s t e) rs -} -- | Given a pattern binding, an expression, and a scope, try to update the -- scope with the binding (cf. 'updateBind') - if succesful construct an -- updated let-expression, otherwise produce an EnvEval with the binding. tryUpdateBind :: Decl -> Exp -> Scope -> Eval tryUpdateBind e' e = maybe (EnvEval e') (Eval . flip mkLet e) . updateBind e' -- | Given a pattern binding, replace one of the same name in the given -- scope, or 'Nothing' if it wasn't there. updateBind :: Decl -> Scope -> Maybe Scope updateBind p@(PatBind _ (PVar n) _ _ _) v = case break match v of (_, []) -> Nothing (h, _ : t) -> Just $ h ++ p : t where match (PatBind _ (PVar m) _ _ _) = n == m match (FunBind _) = False match (InfixDecl _ _ _ _) = False match d = todo "updateBind match" d updateBind l _ = todo "updateBind" l -- | Find a declaration in the environment by matching on its 'declName'. envLookup :: Env -> Name -> Maybe Decl envLookup v n = case envBreak ((Just n ==) . declName) v of (_, _, [], _) -> Nothing (_, _, c : _, _) -> Just c -- | If the decl binds a pattern or function, return its name. declName :: Decl -> Maybe Name declName (PatBind _ (PVar m) _ _ _) = Just m declName (FunBind ms) = Just (funName ms) declName (InfixDecl _ _ _ _) = Nothing declName d = todo "declName" d -- | Given a list of lists, find the first item matching the predicate and -- return -- (lists with no match, takeWhile p list, dropWhile p list, lists remaining) envBreak :: (a -> Bool) -> [[a]] -> ([[a]], [a], [a], [[a]]) envBreak _ [] = ([], [], [], []) envBreak p (x:xs) = case break p x of (_, []) -> (x:as, bs, cs, ds) (ys, zs) -> ([], ys, zs, xs) where (as, bs, cs, ds) = envBreak p xs -- | Assume the name is unqualified, and fetch the name in that case. -- Error otherwise. fromQName :: QName -> Name fromQName (UnQual n) = n fromQName q = error $ "fromQName: " ++ show q -- | Given a list of 'MatchResult', substitute the bindings wherever they -- are not shadowed. applyMatches :: Data a => [MatchResult] -> a -> a -- If it's not an Exp, just recurse into it, otherwise try to substitute... applyMatches ms x = recurse `extT` replaceOne $ x where replaceOne e@(Var (UnQual m)) = maybe e mrExp $ mlookup m ms replaceOne (InfixApp x o@(QVarOp (UnQual m)) y) = fromMaybe (InfixApp rx o ry) (mkApp . mrExp <$> mlookup m ms) where (rx, ry) = (replaceOne x, replaceOne y) mkApp f = app (app f rx) ry -- ...or else recurse anyway replaceOne e = recurse e recurse e = gmapT (applyMatches (notShadowed e)) e -- Parameter here might be redundant - it's only called on x anyway notShadowed e = filter (not . flip shadows e . mrName) ms -- | Find a 'MatchResult' by name. mlookup :: Name -> [MatchResult] -> Maybe MatchResult mlookup m = foldr (\x r -> x <$ guard (m == mrName x) <|> r) Nothing -- | Produce a 'GenericT' that renames all instances of the given 'Name' to -- something else that isn't any of the given @['Name']@. Does not apply the -- rename where the name is shadowed. alpha :: Data a => Name -> [Name] -> a -> a alpha n avoid = everywhereBut (shadows n) (mkT $ replaceOne n m) where -- genNames produces an infinite list, so find cannot give Nothing Just m = find (`notElem` avoid) $ case n of Ident i -> map Ident $ genNames i ['0' .. '9'] 1 Symbol s -> map Symbol $ genNames s "!?*#+&$%@." 1 genNames n xs i = map (n ++) (replicateM i xs) ++ genNames n xs (succ i) replaceOne n m r | n == r = m | otherwise = r -- | Returns 'True' if the 'Name' appears without a corresponding binding -- anywhere in the structure. -- Always returns 'True' for @>>=@ and @>>@ if there are any do-expressions -- present. isFreeIn :: Data a => Name -> a -> Bool isFreeIn n x = not (shadows n x) && (is n x || or (gmapQ (isFreeIn n) x)) where is n@(Symbol s) | s == ">>" || s == ">>=" = mkQ False (== n) `extQ` isDo is n = mkQ False (== n) isDo (Do _) = True isDo _ = False -- | Fetches a list of all 'Name's present but not bound in the argument. freeNames :: Data a => a -> [Name] freeNames e = filter (`isFreeIn` e) . Set.toList . Set.fromList $ listify (const True) e -- | If the argument is 'Step', turn it into a 'MatchEval', else 'NoMatch'. peval :: EvalStep -> PatternMatch peval (Step e) = MatchEval e peval _ = NoMatch -- | Match a single pattern against a single expression. patternMatch :: Env -> Pat -> Exp -> PatternMatch -- Strip parentheses patternMatch v (PParen p) x = patternMatch v p x patternMatch v p (Paren x) = patternMatch v p x -- Patterns that always match patternMatch _ (PWildCard) _ = Matched [] patternMatch _ (PVar n) x = Matched [MatchResult n x id] -- As-patterns patternMatch v (PAsPat n p) x = case patternMatch v p x of Matched ms -> Matched (MatchResult n x id : ms) r -> r -- Let-expressions should skip right to the interesting bit patternMatch v p (Let (BDecls ds) x) = case patternMatch (ds:v) p x of MatchEval (Eval e) -> MatchEval . Eval $ mkLet ds e MatchEval (EnvEval e) -> MatchEval $ tryUpdateBind e x ds r -> r patternMatch _ _ (Let bs _) = todo "patternMatch Let" bs -- Variables can only match trivial patterns patternMatch v p (Var q) = case envBreak ((Just n ==) . declName) v of (_, _, [], _) -> NoMatch (_, xs, y : ys, zs) -> case y of PatBind s q t (UnGuardedRhs e) bs -> case patternMatch v' p e of MatchEval (Eval e') -> MatchEval (EnvEval (PatBind s q t (UnGuardedRhs e') bs)) Matched _ -> MatchEval (Eval e) r -> r where v' = (xs ++ ys) : zs FunBind _ -> NoMatch l -> todo "patternMatch Var" l where n = fromQName q -- Desugar infix applications and lists patternMatch v (PInfixApp p q r) s = patternMatch v (PApp q [p, r]) s patternMatch v p e@(InfixApp a n b) = case n of QVarOp _ -> peval $ step v e QConOp q -> patternMatch v p (App (App (Con q) a) b) patternMatch _ _ (List (x:xs)) = MatchEval . Eval $ InfixApp x (QConOp (Special Cons)) (List xs) patternMatch _ _ (Lit (String (x:xs))) = MatchEval . Eval $ InfixApp (Lit (Char x)) (QConOp (Special Cons)) (Lit (String xs)) -- Literal match patternMatch _ (PLit p) (Lit q) | p == q = Matched [] | otherwise = NoMatch patternMatch v (PLit _) s = peval $ step v s patternMatch v (PList []) x = case argList x of [List []] -> Matched [] [List _] -> NoMatch Con _ : _ -> NoMatch _ -> peval $ step v x -- Lists of patterns patternMatch v (PList (p:ps)) q = patternMatch v (PApp (Special Cons) [p, PList ps]) q -- Tuples patternMatch v (PTuple ps) q = case q of Tuple qs -> matches v ps qs Tuple _ -> peval $ step v q -- Constructor matches patternMatch v (PApp n ps) q = case argList q of (Con c:xs) | c == n -> matches v ps xs (unArgList (Con c)) | otherwise -> NoMatch _ -> peval $ step v q -- Fallback case patternMatch _ p q = todo "patternMatch _" (p, q) -- | Map over the function field of a 'MatchResult'. onMRFunc :: ((Exp -> Exp) -> (Exp -> Exp)) -> MatchResult -> MatchResult onMRFunc f m@(MatchResult { mrFunc = g }) = m { mrFunc = f g } -- The tricky part about this is the third field of PatternMatch, which -- contains a function to put the matchresult - perhaps after some -- modification - back into its original context. -- This is something that is mostly best understood by example. Luckily I've -- provided an evil Show instance for Exp -> Exp so you should be able to -- see its purpose in a bit of mucking about with ghci :) -- Obviously it starts off as id. -- | Carry out several simultaneous pattern matches, e.g. for lists or -- tuples of patterns. The given function is used to restore the list of -- expressions to their original context if necessary (so it might be the -- Tuple constructor, for example). matches :: Env -> [Pat] -> [Exp] -> ([Exp] -> Exp) -> PatternMatch matches _ [] [] _ = Matched [] matches v ps xs f = go v ps xs id where go _ [] [] _ = Matched [] go v (p:ps) (e:es) g = -- We rely on laziness here to not recurse if the first match fails. -- If we do recurse, then the reconstruction function needs to -- put the current expression on the end. case (patternMatch v p e, go v ps es (g . (e:))) of (NoMatch, _) -> NoMatch (MatchEval (Eval e'), _) -> MatchEval . Eval . f . g $ e' : es (r@(MatchEval _), _) -> r (Matched xs, Matched ys) -> -- great, everything worked fine. Now we assume the recursive case -- has everything worked out and we just need to apply the final -- touches to the reconstruction function. -- So far it'll be a [Exp] -> [Exp] that basically consists of -- everything we've skipped to get this far in the pattern match. -- We want to also append everything we haven't met yet (making -- an Exp -> [Exp]) and then apply the combination function given -- as a parameter (making Exp -> Exp, which is what we need). We -- do this for every pattern match item. Matched (map (onMRFunc ((f . g . (: es)) .)) xs ++ ys) (_, r) -> r -- Ran out of patterns before expressions or vice versa, fail -- TODO: matches should get a [(Pat, Exp)] so the equality of length -- is statically enforced. go _ _ _ _ = NoMatch -- | Deconstruct an infix or prefix application into -- @[function, arg1, arg2, ...]@. Spine-strict by the nature of application. argList :: Exp -> [Exp] argList = reverse . atl where atl (App f x) = x : atl f atl (Paren p) = atl p atl (InfixApp p o q) = [q, p, case o of QVarOp n -> Var n QConOp n -> Con n] atl e = [e] -- This could be optimised because app checks for atomic functions but we -- know after the first app that none of the subsequent functions are so. -- | @'foldl' 'app'@. Apply a function to a list of arguments, neatly. unArgList :: Exp -> [Exp] -> Exp unArgList = foldl app -- | Return 'True' if the argument binds the given 'Name' shadows :: Typeable a => Name -> a -> Bool shadows n = mkQ False exprS `extQ` altS `extQ` matchS where exprS (Lambda _ ps _) = any patS ps exprS (Let (BDecls bs) _) = any letS bs exprS _ = False altS (Alt _ p _ (BDecls bs)) = patS p || any letS bs altS a = todo "shadows altS" a matchS (Match _ _ ps _ _ _) = any patS ps patS (PVar m) = m == n patS (PAsPat m p) = m == n || patS p patS p = or $ gmapQ (mkQ False patS) p letS (PatBind _ p _ _ _) = patS p letS _ = False -- | 'True' if the predicate holds anywhere inside the structure. anywhere :: (Typeable a, Data b) => (a -> Bool) -> b -> Bool anywhere p = everything (||) (mkQ False p) todo :: (Show s) => String -> s -> a todo s = error . (s ++) . (": Not implemented: " ++) . show
bmillwood/stepeval
src/Language/Haskell/Stepeval.hs
Haskell
bsd-3-clause
28,500
-- ^ -- Handlers for Lono endpoints module Handlers.Lono where import Api.Lono import Handlers.Common import qualified Handlers.RssReaders.Feeds as F import qualified Handlers.RssReaders.Subscriptions as S import qualified Handlers.RssReaders.UserPosts as U import Persistence.Lono.Common import Persistence.RssReaders.Common import Servant import Types.Common -- ^ -- Create an application containing all Lono API endpoints app :: ApiConfig -> Application app = app' apiProxy handlers -- ^ -- Lono API handlers handlers :: ServerT LonoApi Api handlers = userHandlers :<|> feedHandlers :<|> postHandlers :<|> subscriptionHandlers :<|> userPostHandlers :<|> postQueryHandlers :<|> tagsHandlers where userHandlers :: ServerT LonoUserApi Api userHandlers = mkHandlers userDefinition mkUserGetSingleLink mkUserGetMultipleLink postHandlers :: ServerT LonoPostApi Api postHandlers = mkHandlers postDefinition mkPostGetSingleLink mkPostGetMultipleLink postQueryHandlers :: ServerT LonoPostQueryApi Api postQueryHandlers = mkHandlers postQueryDefinition mkPostQueryGetSingleLink mkPostQueryGetMultipleLink tagsHandlers :: ServerT LonoTagsApi Api tagsHandlers = mkHandlers tagsDefinition mkTagsGetSingleLink mkTagsGetMultipleLink mkHandlers def mkGetSingleLink mkGetMultipleLink = getMultiple mkGetMultipleLink def :<|> getSingle def :<|> deleteSingle def :<|> createSingleOrMultiple def mkGetSingleLink :<|> replaceSingle def :<|> replaceMultiple def :<|> modifySingle def :<|> modifyMultiple def :<|> optionsSingle :<|> optionsMultiple feedHandlers = getMultiple mkFeedGetMultipleLink feedDefinition :<|> getSingle feedDefinition :<|> F.deleteSingle :<|> createSingleOrMultiple feedDefinition mkFeedGetSingleLink :<|> replaceSingle feedDefinition :<|> replaceMultiple feedDefinition :<|> modifySingle feedDefinition :<|> modifyMultiple feedDefinition :<|> optionsSingle :<|> optionsMultiple userPostHandlers = U.getMultiple mkUserPostGetMultipleLink :<|> U.getSingle :<|> U.deleteSingle :<|> U.createSingleOrMultiple mkUserPostGetSingleLink :<|> U.replaceSingle :<|> U.replaceMultiple :<|> U.modifySingle :<|> U.modifyMultiple :<|> U.optionsSingle :<|> U.optionsMultiple subscriptionHandlers :: ServerT LonoSubscriptionApi Api subscriptionHandlers = S.getMultiple mkSubscriptionGetMultipleLink :<|> S.getSingle :<|> S.deleteSingle :<|> S.createSingleOrMultiple mkSubscriptionGetSingleLink :<|> S.replaceSingle :<|> S.replaceMultiple :<|> S.modifySingle :<|> S.modifyMultiple :<|> optionsSingle :<|> optionsMultiple -- ^ -- Perform any initialization to be done on server start appInit :: ApiConfig -> IO () appInit = addDbIndices userIndices >> addDbIndices feedIndices >> addDbIndices postIndices >> addDbIndices subscriptionIndices >> addDbIndices postQueryIndices >> addDbIndices tagsIndices
gabesoft/kapi
src/Handlers/Lono.hs
Haskell
bsd-3-clause
3,126
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE Trustworthy #-} module Sigym4.Units.Accelerate ( (*~) , (/~) , module Sigym4.Units.Meteo , module Sigym4.Units ) where import Sigym4.Units.Accelerate.Internal ( (*~), (/~) ) import Sigym4.Units hiding ( (*~), (/~) ) import Sigym4.Units.Meteo
meteogrid/sigym4-units-accelerate
src/Sigym4/Units/Accelerate.hs
Haskell
bsd-3-clause
679
-- | -- This module contains functions which help when unmarshalling query responses module Network.TableStorage.Query ( edmBinary, edmBoolean, edmDateTime, edmDouble, edmGuid, edmInt32, edmInt64, edmString ) where import Data.Time ( UTCTime ) import Network.TableStorage.Types ( Entity(entityColumns), EntityColumn(EdmBinary, EdmBoolean, EdmDateTime, EdmDouble, EdmGuid, EdmInt32, EdmInt64, EdmString) ) -- | -- Find the value in a binary-valued column or return Nothing if no such column exists edmBinary :: String -> Entity -> Maybe String edmBinary key en = do col <- lookup key $ entityColumns en case col of EdmBinary s -> s _ -> Nothing -- | -- Find the value in a string-valued column or return Nothing if no such column exists edmString :: String -> Entity -> Maybe String edmString key en = do col <- lookup key $ entityColumns en case col of EdmString s -> s _ -> Nothing -- | -- Find the value in a boolean-valued column or return Nothing if no such column exists edmBoolean :: String -> Entity -> Maybe Bool edmBoolean key en = do col <- lookup key $ entityColumns en case col of EdmBoolean s -> s _ -> Nothing -- | -- Find the value in a date-valued column or return Nothing if no such column exists edmDateTime :: String -> Entity -> Maybe UTCTime edmDateTime key en = do col <- lookup key $ entityColumns en case col of EdmDateTime s -> s _ -> Nothing -- | -- Find the value in a double-valued column or return Nothing if no such column exists edmDouble :: String -> Entity -> Maybe Double edmDouble key en = do col <- lookup key $ entityColumns en case col of EdmDouble s -> s _ -> Nothing -- | -- Find the value in a Guid-valued column or return Nothing if no such column exists edmGuid :: String -> Entity -> Maybe String edmGuid key en = do col <- lookup key $ entityColumns en case col of EdmGuid s -> s _ -> Nothing -- | -- Find the value in an integer-valued column or return Nothing if no such column exists edmInt32 :: String -> Entity -> Maybe Int edmInt32 key en = do col <- lookup key $ entityColumns en case col of EdmInt32 s -> s _ -> Nothing -- | -- Find the value in an integer-valued column or return Nothing if no such column exists edmInt64 :: String -> Entity -> Maybe Int edmInt64 key en = do col <- lookup key $ entityColumns en case col of EdmInt64 s -> s _ -> Nothing
paf31/tablestorage
src/Network/TableStorage/Query.hs
Haskell
bsd-3-clause
2,446
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, TypeFamilies #-} import qualified Common.Matrix.Matrix as M import Common.NumMod.MkNumMod mkNumMod True 100000000 type Zn = Int100000000 solve :: Integer -> Zn solve n = (((mat `M.power` p) `M.multiply` initial) M.! (1, 1)) - 1 where p = 987654321 :: Int mat = M.fromList 3 3 [0, 1, 0, 0, 0, 1, fromInteger $ -n, 0, 2^n] initial = M.fromList 3 1 [3, 2^n, 4^n] main = print $ sum [ solve i | i <- [1 .. 30] ]
foreverbell/project-euler-solutions
src/356.hs
Haskell
bsd-3-clause
490
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Network -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/network/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : provisional -- Portability : portable -- -- This module is kept for backwards-compatibility. New users are -- encouraged to use "Network.Socket" instead. -- -- "Network" was intended as a \"higher-level\" interface to networking -- facilities, and only supports TCP. -- ----------------------------------------------------------------------------- #include "HsNetworkConfig.h" #ifdef HAVE_GETADDRINFO -- Use IPv6-capable function definitions if the OS supports it. #define IPV6_SOCKET_SUPPORT 1 #endif module Network ( -- * Basic data types Socket , PortID(..) , HostName , PortNumber -- * Initialisation , withSocketsDo -- * Server-side connections , listenOn , accept , sClose -- * Client-side connections , connectTo -- * Simple sending and receiving {-$sendrecv-} , sendTo , recvFrom -- * Miscellaneous , socketPort -- * Networking Issues -- ** Buffering {-$buffering-} -- ** Improving I\/O Performance over sockets {-$performance-} -- ** @SIGPIPE@ {-$sigpipe-} ) where import Control.Monad (liftM) import Data.Maybe (fromJust) import Network.BSD import Network.Socket hiding (accept, socketPort, recvFrom, sendTo, PortNumber, sClose) import qualified Network.Socket as Socket (accept) import System.IO import Prelude import qualified Control.Exception as Exception -- --------------------------------------------------------------------------- -- High Level ``Setup'' functions -- If the @PortID@ specifies a unix family socket and the @Hostname@ -- differs from that returned by @getHostname@ then an error is -- raised. Alternatively an empty string may be given to @connectTo@ -- signalling that the current hostname applies. data PortID = Service String -- Service Name eg "ftp" | PortNumber PortNumber -- User defined Port Number #if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32) | UnixSocket String -- Unix family socket in file system #endif deriving (Show, Eq) -- | Calling 'connectTo' creates a client side socket which is -- connected to the given host and port. The Protocol and socket type is -- derived from the given port identifier. If a port number is given -- then the result is always an internet family 'Stream' socket. connectTo :: HostName -- Hostname -> PortID -- Port Identifier -> IO Handle -- Connected Socket #if defined(IPV6_SOCKET_SUPPORT) -- IPv6 and IPv4. connectTo hostname (Service serv) = connect' hostname serv connectTo hostname (PortNumber port) = connect' hostname (show port) #else -- IPv4 only. connectTo hostname (Service serv) = do proto <- getProtocolNumber "tcp" bracketOnError (socket AF_INET Stream proto) (sClose) -- only done if there's an error (\sock -> do port <- getServicePortNumber serv he <- getHostByName hostname connect sock (SockAddrInet port (hostAddress he)) socketToHandle sock ReadWriteMode ) connectTo hostname (PortNumber port) = do proto <- getProtocolNumber "tcp" bracketOnError (socket AF_INET Stream proto) (sClose) -- only done if there's an error (\sock -> do he <- getHostByName hostname connect sock (SockAddrInet port (hostAddress he)) socketToHandle sock ReadWriteMode ) #endif #if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32) connectTo _ (UnixSocket path) = do bracketOnError (socket AF_UNIX Stream 0) (sClose) (\sock -> do connect sock (SockAddrUnix path) socketToHandle sock ReadWriteMode ) #endif #if defined(IPV6_SOCKET_SUPPORT) connect' :: HostName -> ServiceName -> IO Handle connect' host serv = do proto <- getProtocolNumber "tcp" let hints = defaultHints { addrFlags = [AI_ADDRCONFIG] , addrProtocol = proto , addrSocketType = Stream } addrs <- getAddrInfo (Just hints) (Just host) (Just serv) firstSuccessful $ map tryToConnect addrs where tryToConnect addr = bracketOnError (socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)) (sClose) -- only done if there's an error (\sock -> do connect sock (addrAddress addr) socketToHandle sock ReadWriteMode ) #endif -- | Creates the server side socket which has been bound to the -- specified port. -- -- 'maxListenQueue' (typically 128) is specified to the listen queue. -- This is good enough for normal network servers but is too small -- for high performance servers. -- -- To avoid the \"Address already in use\" problems, -- the 'ReuseAddr' socket option is set on the listening socket. -- -- If available, the 'IPv6Only' socket option is set to 0 -- so that both IPv4 and IPv6 can be accepted with this socket. -- -- If you don't like the behavior above, please use the lower level -- 'Network.Socket.listen' instead. listenOn :: PortID -- ^ Port Identifier -> IO Socket -- ^ Listening Socket #if defined(IPV6_SOCKET_SUPPORT) -- IPv6 and IPv4. listenOn (Service serv) = listen' serv listenOn (PortNumber port) = listen' (show port) #else -- IPv4 only. listenOn (Service serv) = do proto <- getProtocolNumber "tcp" bracketOnError (socket AF_INET Stream proto) (sClose) (\sock -> do port <- getServicePortNumber serv setSocketOption sock ReuseAddr 1 bindSocket sock (SockAddrInet port iNADDR_ANY) listen sock maxListenQueue return sock ) listenOn (PortNumber port) = do proto <- getProtocolNumber "tcp" bracketOnError (socket AF_INET Stream proto) (sClose) (\sock -> do setSocketOption sock ReuseAddr 1 bindSocket sock (SockAddrInet port iNADDR_ANY) listen sock maxListenQueue return sock ) #endif #if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32) listenOn (UnixSocket path) = bracketOnError (socket AF_UNIX Stream 0) (sClose) (\sock -> do setSocketOption sock ReuseAddr 1 bindSocket sock (SockAddrUnix path) listen sock maxListenQueue return sock ) #endif #if defined(IPV6_SOCKET_SUPPORT) listen' :: ServiceName -> IO Socket listen' serv = do proto <- getProtocolNumber "tcp" -- We should probably specify addrFamily = AF_INET6 and the filter -- code below should be removed. AI_ADDRCONFIG is probably not -- necessary. But this code is well-tested. So, let's keep it. let hints = defaultHints { addrFlags = [AI_ADDRCONFIG, AI_PASSIVE] , addrSocketType = Stream , addrProtocol = proto } addrs <- getAddrInfo (Just hints) Nothing (Just serv) -- Choose an IPv6 socket if exists. This ensures the socket can -- handle both IPv4 and IPv6 if v6only is false. let addrs' = filter (\x -> addrFamily x == AF_INET6) addrs addr = if null addrs' then head addrs else head addrs' bracketOnError (socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)) (sClose) (\sock -> do setSocketOption sock ReuseAddr 1 bindSocket sock (addrAddress addr) listen sock maxListenQueue return sock ) #endif -- ----------------------------------------------------------------------------- -- accept -- | Accept a connection on a socket created by 'listenOn'. Normal -- I\/O operations (see "System.IO") can be used on the 'Handle' -- returned to communicate with the client. -- Notice that although you can pass any Socket to Network.accept, -- only sockets of either AF_UNIX, AF_INET, or AF_INET6 will work -- (this shouldn't be a problem, though). When using AF_UNIX, HostName -- will be set to the path of the socket and PortNumber to -1. -- accept :: Socket -- ^ Listening Socket -> IO (Handle, HostName, PortNumber) -- ^ Triple of: read\/write 'Handle' for -- communicating with the client, -- the 'HostName' of the peer socket, and -- the 'PortNumber' of the remote connection. accept sock@(MkSocket _ AF_INET _ _ _) = do ~(sock', (SockAddrInet port haddr)) <- Socket.accept sock peer <- catchIO (do (HostEntry peer _ _ _) <- getHostByAddr AF_INET haddr return peer ) (\_e -> inet_ntoa haddr) -- if getHostByName fails, we fall back to the IP address handle <- socketToHandle sock' ReadWriteMode return (handle, peer, port) #if defined(IPV6_SOCKET_SUPPORT) accept sock@(MkSocket _ AF_INET6 _ _ _) = do (sock', addr) <- Socket.accept sock peer <- catchIO ((fromJust . fst) `liftM` getNameInfo [] True False addr) $ \_ -> case addr of SockAddrInet _ a -> inet_ntoa a SockAddrInet6 _ _ a _ -> return (show a) # if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32) SockAddrUnix a -> return a # endif handle <- socketToHandle sock' ReadWriteMode let port = case addr of SockAddrInet p _ -> p SockAddrInet6 p _ _ _ -> p _ -> -1 return (handle, peer, port) #endif #if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32) accept sock@(MkSocket _ AF_UNIX _ _ _) = do ~(sock', (SockAddrUnix path)) <- Socket.accept sock handle <- socketToHandle sock' ReadWriteMode return (handle, path, -1) #endif accept (MkSocket _ family _ _ _) = error $ "Sorry, address family " ++ (show family) ++ " is not supported!" -- | Close the socket. All future operations on the socket object will fail. -- The remote end will receive no more data (after queued data is flushed). sClose :: Socket -> IO () sClose = close -- Explicit redefinition because Network.sClose is deperecated, -- hence the re-export would also be marked as such. -- ----------------------------------------------------------------------------- -- sendTo/recvFrom {-$sendrecv Send and receive data from\/to the given host and port number. These should normally only be used where the socket will not be required for further calls. Also, note that due to the use of 'hGetContents' in 'recvFrom' the socket will remain open (i.e. not available) even if the function already returned. Their use is strongly discouraged except for small test-applications or invocations from the command line. -} sendTo :: HostName -- Hostname -> PortID -- Port Number -> String -- Message to send -> IO () sendTo h p msg = do s <- connectTo h p hPutStr s msg hClose s recvFrom :: HostName -- Hostname -> PortID -- Port Number -> IO String -- Received Data #if defined(IPV6_SOCKET_SUPPORT) recvFrom host port = do proto <- getProtocolNumber "tcp" let hints = defaultHints { addrFlags = [AI_ADDRCONFIG] , addrProtocol = proto , addrSocketType = Stream } allowed <- map addrAddress `liftM` getAddrInfo (Just hints) (Just host) Nothing s <- listenOn port let waiting = do (s', addr) <- Socket.accept s if not (addr `oneOf` allowed) then sClose s' >> waiting else socketToHandle s' ReadMode >>= hGetContents waiting where a@(SockAddrInet _ ha) `oneOf` ((SockAddrInet _ hb):bs) | ha == hb = True | otherwise = a `oneOf` bs a@(SockAddrInet6 _ _ ha _) `oneOf` ((SockAddrInet6 _ _ hb _):bs) | ha == hb = True | otherwise = a `oneOf` bs _ `oneOf` _ = False #else recvFrom host port = do ip <- getHostByName host let ipHs = hostAddresses ip s <- listenOn port let waiting = do ~(s', SockAddrInet _ haddr) <- Socket.accept s he <- getHostByAddr AF_INET haddr if not (any (`elem` ipHs) (hostAddresses he)) then do sClose s' waiting else do h <- socketToHandle s' ReadMode msg <- hGetContents h return msg message <- waiting return message #endif -- --------------------------------------------------------------------------- -- Access function returning the port type/id of socket. -- | Returns the 'PortID' associated with a given socket. socketPort :: Socket -> IO PortID socketPort s = do sockaddr <- getSocketName s return (portID sockaddr) where portID sa = case sa of SockAddrInet port _ -> PortNumber port #if defined(IPV6_SOCKET_SUPPORT) SockAddrInet6 port _ _ _ -> PortNumber port #endif #if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32) SockAddrUnix path -> UnixSocket path #endif -- --------------------------------------------------------------------------- -- Utils -- Like bracket, but only performs the final action if there was an -- exception raised by the middle bit. bracketOnError :: IO a -- ^ computation to run first (\"acquire resource\") -> (a -> IO b) -- ^ computation to run last (\"release resource\") -> (a -> IO c) -- ^ computation to run in-between -> IO c -- returns the value from the in-between computation bracketOnError = Exception.bracketOnError ----------------------------------------------------------------------------- -- Extra documentation {-$buffering The 'Handle' returned by 'connectTo' and 'accept' is block-buffered by default. For an interactive application you may want to set the buffering mode on the 'Handle' to 'LineBuffering' or 'NoBuffering', like so: > h <- connectTo host port > hSetBuffering h LineBuffering -} {-$performance For really fast I\/O, it might be worth looking at the 'hGetBuf' and 'hPutBuf' family of functions in "System.IO". -} {-$sigpipe On Unix, when writing to a socket and the reading end is closed by the remote client, the program is normally sent a @SIGPIPE@ signal by the operating system. The default behaviour when a @SIGPIPE@ is received is to terminate the program silently, which can be somewhat confusing if you haven't encountered this before. The solution is to specify that @SIGPIPE@ is to be ignored, using the POSIX library: > import Posix > main = do installHandler sigPIPE Ignore Nothing; ... -} catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a #if MIN_VERSION_base(4,0,0) catchIO = Exception.catch #else catchIO = Exception.catchJust Exception.ioErrors #endif -- Returns the first action from a list which does not throw an exception. -- If all the actions throw exceptions (and the list of actions is not empty), -- the last exception is thrown. firstSuccessful :: [IO a] -> IO a firstSuccessful [] = error "firstSuccessful: empty list" firstSuccessful (p:ps) = catchIO p $ \e -> case ps of [] -> Exception.throwIO e _ -> firstSuccessful ps
bjornbm/network
Network.hs
Haskell
bsd-3-clause
15,722
module Chp84 where {-- Functor typeclass --} {-- And now, we're going to take a look at the Functor typeclass, which is basically for things that can be mapped over. You're probably thinking about lists now, since mapping over lists is such a dominant idiom in Haskell. And you're right, the list type is part of the Functor typeclass. class Functor f where fmap :: (a -> b) -> f a -> f b quick refresher example: Maybe Int is a concrete type, but Maybe is a type constructor that takes one type as the parameter. Anyway, we see that fmap takes a function from one type to another, a functor applied with one type, and returns a functor applied with another type. --} {-- this type declaration for fmap reminds me of something. If you don't know what the type signature of map is, it's: map :: (a -> b) -> [a] -> [b] map is just a fmap that works only on lists. Here's how the list is an instance of the Functor typeclass: instance Functor [] where fmap = map --} {-- What happens when we map or fmap over an empty list? Well, of course, we get an empty list. It just turns an empty list of type [a] into an empty list of type [b]. --} {-- Types that can act like a box can be functors. You can think of a list as a box that has an infinite amount of little compartments and they can all be empty, one can be full and the others empty or a number of them can be full. So, what else has the properties of being like a box? For one, the "Maybe a" type. instance Functor Maybe where fmap f (Just x) = Just (f x) fmap f Nothing = Nothing --} res1 = fmap (++ " HEY GUYS IM INSIDE THE JUST") (Just "Something serious.") {-- Again, notice how we wrote instance Functor Maybe where instead of instance Functor (Maybe m) where, like we did when we were dealing with Maybe and YesNo. Then Functor wants a type constructor that takes one type and not a concrete type. class Functor f where fmap :: (a -> b) -> f a -> f b If you mentally replace the f to Maybe, fmap acts like a (a -> b) -> Maybe a -> Maybe b for this particular type, which looks OK. But if you replace f with (Maybe m), then it would seem to act like a (a -> b) -> Maybe m a -> Maybe m b, which doesn't make any damn sense because Maybe takes just one type parameter. invalid instance Functor (Maybe m) where fmap ??? fmap ??? --} {-- If you look at fmap as if it were a function made only for Tree, its type signature would look like (a -> b) -> Tree a -> Tree b. We're going to use recursion on this one. 1. Mapping over an empty tree will produce an empty tree. 2. Mapping over a non-empty tree will be a tree consisting of our function applied to the root value and its left and right sub-trees will be the previous sub-trees, only our function will be mapped over them. --} data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq) singleton :: a -> Tree a singleton x = Node x EmptyTree EmptyTree treeInsert :: (Ord a) => a -> Tree a -> Tree a treeInsert x EmptyTree = singleton x treeInsert x (Node a left right) | x == a = Node x left right | x < a = Node a (treeInsert x left) right | x > a = Node a left (treeInsert x right) instance Functor Tree where fmap f EmptyTree = EmptyTree fmap f (Node x leftsub rightsub) = Node (f x) (fmap f leftsub) (fmap f rightsub) {-- Now how about Either a b? Can this be made a functor? The Functor typeclass wants a type constructor that takes only one type parameter but Either takes two. Hmmm! I know, we'll partially apply Either by feeding it only one parameter so that it has one free parameter. Here's how Either a is a functor in the standard libraries: instance Functor (Either a) where fmap f (Right x) = Right (f x) fmap f (Left x) = Left x --} {-- Functors should obey some laws so that they may have some properties that we can depend on and not think about too much. If we use fmap (+1) over the list [1,2,3,4], we expect the result to be [2,3,4,5] and not its reverse, [5,4,3,2]. If we use fmap (\a -> a) (the identity function, which just returns its parameter) over some list, we expect to get back the same list as a result. --} {-- Kinds and some type-foo Type constructors take other types as parameters to eventually produce concrete types. That kind of reminds me of functions, which take values as parameters to produce values. We've seen that type constructors can be partially applied (Either String is a type that takes one type and produces a concrete type, like Either String Int), just like functions can. --} {-- So, values like 3, "YEAH" or takeWhile (functions are also values, because we can pass them around and such) each have their own type. Types are little labels that values carry so that we can reason about the values. But types have their own little labels, called kinds. A kind is more or less the type of a type. let's examine the kind of a type by using the :k command in GHCI. ghci> :k Int Int :: * A * means that the type is a concrete type. A concrete type is a type that doesn't take any type parameters and values can only have types that are concrete types. ghci> :k Maybe Maybe :: * -> * The Maybe type constructor takes one concrete type (like Int) and then returns a concrete type like Maybe Int. And that's what this kind tells us. Just like Int -> Int means that a function takes an Int and returns an Int, * -> * means that the type constructor takes one concrete type and returns a concrete type. ghci> :k Maybe Int Maybe Int :: * We applied the type parameter to Maybe and got back a concrete type (that's what * -> * means. A parallel (although not equivalent, types and kinds are two different things) to this is if we do :t isUpper and :t isUpper 'A'. isUpper has a type of Char -> Bool and isUpper 'A' has a type of Bool, We used :k on a type to get its kind, just like we can use :t on a value to get its type. Like we said, types are the labels of values and kinds are the labels of types and there are parallels between the two. --} {-- ghci> :k Either Either :: * -> * -> * It also looks kind of like a type declaration of a function that takes two values and returns something. Type constructors are curried (just like functions), so we can partially apply them. ghci> :k Either String Either String :: * -> * ghci> :k Either String Int Either String Int :: * --} {-- When we wanted to make Either a part of the Functor typeclass, we had to partially apply it because Functor wants types that take only one parameter while Either takes two. In other words, Functor wants types of kind * -> * and so we had to partially apply Either to get a type of kind * -> * instead of its original kind * -> * -> *. If we look at the definition of Functor again class Functor f where fmap :: (a -> b) -> f a -> f b we see that the f type variable is used as a type that takes one concrete type to produce a concrete type. We know it has to produce a concrete type because it's used as the type of a value in a function. And from that, we can deduce that types that want to be friends with Functor have to be of kind * -> *. (imply by f a, or f b) --} {-- class Tofu t where tofu :: j a -> t a j Because j a is used as the type of a value that the tofu function takes as its parameter, j a has to have a kind of * So kind: j :: * -> * t :: * -> (* -> *) -> * We assume * for a and so we can infer that j has to have a kind of * -> *. We see that t has to produce a concrete value too and that it takes two types. And knowing that a has a kind of * and j has a kind of * -> *, we infer that t has to have a kind of * -> (* -> *) -> *. So it takes a concrete type (a), a type constructor that takes one concrete type (j), and produces a concrete type. so let's make a type with a kind of * -> (* -> *) -> *. Here's one way of going about it. data Frank a b = Frank {frankField :: b a} deriving (Show) How do we know this type has a kind of * -> (* -> *) - > *? Well, fields in ADTs are made to hold values, so they must be of kind *, obviously. We assume * for a, which means that b takes one type parameter and so its kind is * -> *. Now we know the kinds of both a and b and because they're parameters for Frank, we see that Frank has a kind of * -> (* -> *) -> * The first * represents a and the (* -> *) represents b. Let's make some Frank values and check out their types. :t Frank {frankField = Just "HAHA"} -- Frank {frankField = Just "HAHA"} :: Frank [Char] Maybe :t Frank {frankField = "YES"} -- Frank {frankField = "YES"} :: Frank Char [] --} {-- Making Frank an instance of Tofu is pretty simple. We see that tofu takes a "j a" (so an example type of that form would be Maybe Int) and returns a "t a j". So if we replace Frank with j, the result type would be Frank Int Maybe. instance Tofu Frank where tofu x = Frank x ghci> tofu (Just 'a') :: Frank Char Maybe Frank {frankField = Just 'a'} ghci> tofu ["HELLO"] :: Frank [Char] [] Frank {frankField = ["HELLO"]} --} {-- Example: data Barry t k p = Barry { yabba :: p, dabba :: t k } ghci> :k Barry Barry :: (* -> *) -> * -> * -> * Now, to make this type a part of Functor we have to partially apply the first two type parameters so that we're left with * -> *. That means that the start of the instance declaration will be: instance Functor (Barry a b) where. If we look at fmap as if it was made specifically for Barry, it would have a type of fmap :: (a -> b) -> Barry c d a -> Barry c d b, because we just replace the Functor's "f" with "Barry c d". The third type parameter from Barry will have to change and we see that it's conviniently in its own field. instance Functor (Barry a b) where fmap f (Barry {yabba = x, dabba = y}) = Barry {yabba = f x, dabba = y} --}
jamesyang124/haskell-playground
src/Chp84.hs
Haskell
bsd-3-clause
9,801
{-# LANGUAGE FlexibleContexts #-} module Cloud.AWS.RDS.Event ( describeEvents , describeEventCategories ) where import Cloud.AWS.Lib.Parser.Unordered (XmlElement, (.<), content) import Control.Applicative import Control.Monad.Trans.Resource (MonadThrow, MonadResource, MonadBaseControl) import Data.Text (Text) import Data.Time (UTCTime) import Cloud.AWS.Lib.Query import Cloud.AWS.RDS.Internal import Cloud.AWS.RDS.Types describeEvents :: (MonadBaseControl IO m, MonadResource m) => Maybe Text -- ^ SourceIdentifier -> Maybe SourceType -- ^ SourceType -> Maybe Int -- ^ Duration -> Maybe UTCTime -- ^ StartTime -> Maybe UTCTime -- ^ EndTime -> [Text] -- ^ EventCategories.member -> Maybe Text -- ^ Marker -> Maybe Int -- ^ MaxRecords -> RDS m [Event] describeEvents sid stype d start end categories marker maxRecords = rdsQuery "DescribeEvents" params $ elements "Event" eventSink where params = [ "SourceIdentifier" |=? sid , "SourceType" |=? stype , "Duration" |=? d , "StartTime" |=? start , "EndTime" |=? end , "EventCategories" |.+ "member" |.#= categories , "Marker" |=? marker , "MaxRecords" |=? maxRecords ] eventSink :: (MonadThrow m, Applicative m) => XmlElement -> m Event eventSink xml = Event <$> xml .< "Message" <*> xml .< "SourceType" <*> elements' "EventCategories" "EventCategory" content xml <*> xml .< "Date" <*> xml .< "SourceIdentifier" describeEventCategories :: (MonadBaseControl IO m, MonadResource m) => Maybe SourceType -- ^ SourceType -> RDS m [EventCategoriesMap] describeEventCategories stype = rdsQuery "DescribeEventCategories" params $ elements' "EventCategoriesMapList" "EventCategoriesMap" eventCategoriesMapSink where params = [ "SourceType" |=? stype ] eventCategoriesMapSink :: (MonadThrow m, Applicative m) => XmlElement -> m EventCategoriesMap eventCategoriesMapSink xml = EventCategoriesMap <$> xml .< "SourceType" <*> elements' "EventCategories" "EventCategory" content xml
worksap-ate/aws-sdk
Cloud/AWS/RDS/Event.hs
Haskell
bsd-3-clause
2,140
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.NV.PixelDataRange -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/NV/pixel_data_range.txt NV_pixel_data_range> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.NV.PixelDataRange ( -- * Enums gl_READ_PIXEL_DATA_RANGE_LENGTH_NV, gl_READ_PIXEL_DATA_RANGE_NV, gl_READ_PIXEL_DATA_RANGE_POINTER_NV, gl_WRITE_PIXEL_DATA_RANGE_LENGTH_NV, gl_WRITE_PIXEL_DATA_RANGE_NV, gl_WRITE_PIXEL_DATA_RANGE_POINTER_NV, -- * Functions glFlushPixelDataRangeNV, glPixelDataRangeNV ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/NV/PixelDataRange.hs
Haskell
bsd-3-clause
963
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} -- | -- Module: Graphics.ChalkBoard.Types -- Copyright: (c) 2009 Andy Gill -- License: BSD3 -- -- Maintainer: Andy Gill <andygill@ku.edu> -- Stability: unstable -- Portability: ghc -- -- This module contains the types used by chalkboard, except Board itself. -- module Graphics.ChalkBoard.Types ( -- * Basic types UI, R, Point, Radian, -- * Overlaying Over(..), stack, -- * Scaling Scale(..), -- * Linear Interpolation Lerp(..), -- * Averaging Average(..), {- -- * Alpha Channel support Alpha(..), alpha, transparent, withAlpha, unAlpha, -- * Z buffer support Z(..), -} -- * Constants nearZero -- * Colors , Gray , RGB(..) , RGBA(..) ) where import Data.Binary import Control.Monad import Data.Ratio -- | A real number. type R = Float -- | Unit Interval: value between 0 and 1, inclusive. type UI = R -- | A point in R2. type Point = (R,R) -- | Angle units type Radian = Float -- | Close to zero; needed for @Over (Alpha c)@ instance. nearZero :: R nearZero = 0.0000001 ------------------------------------------------------------------------------ infixr 5 `over` -- | For placing a value literally /over/ another value. The 2nd value /might/ shine through. -- The operation /must/ be associative. class Over c where over :: c -> c -> c instance Over Bool where over = (||) instance Over (a -> a) where over = (.) instance Over (Maybe a) where (Just a) `over` _ = Just a Nothing `over` other = other -- | 'stack' stacks a list of things over each other, -- where earlier elements are 'over' later elements. -- Requires non empty lists, which can be satisfied by using an explicitly -- transparent @Board@ as one of the elements. stack :: (Over c) => [c] -> c stack = foldr1 over ------------------------------------------------------------------------------ -- | 'Scale' something by a value. scaling value can be bigger than 1. class Scale c where scale :: R -> c -> c instance Scale R where scale u v = u * v instance (Scale a,Scale b) => Scale (a,b) where scale u (x,y) = (scale u x,scale u y) instance Scale Rational where scale u r = toRational u * r ------------------------------------------------------------------------------ -- | Linear interpolation between two values. class Lerp a where lerp :: UI -> a -> a -> a instance Lerp R where lerp s v v' = v + (s * (v' - v)) instance Lerp Rational where lerp s v v' = v + (toRational s * (v' - v)) -- | 'Lerp' over pairs instance (Lerp a,Lerp b) => Lerp (a,b) where lerp s (a,b) (a',b') = (lerp s a a',lerp s b b') instance (Lerp a) => Lerp (Maybe a) where lerp _ Nothing Nothing = Nothing lerp _ (Just a) Nothing = Just a lerp _ Nothing (Just b) = Just b lerp s (Just a) (Just b) = Just (lerp s a b) ------------------------------------------------------------------------------ -- | 'Average' a set of values. weighting can be achived using multiple entries. class Average a where -- | average is not defined for empty list average :: [a] -> a instance Average R where average xs = sum xs / fromIntegral (length xs) instance (Average a,Average b) => Average (a,b) where average xs = (average $ map fst xs,average $ map snd xs) ------------------------------------------------------------------------------ -- | 'Gray' is just a value between 0 and 1, inclusive. -- Be careful to consider if this is pre or post gamma. type Gray = UI instance Over Gray where over r _ = r ------------------------------------------------------------------------------ -- Simple colors -- | 'RGB' is our color, with values between 0 and 1, inclusive. data RGB = RGB !UI !UI !UI deriving Show instance Over RGB where -- simple overwriting over x _y = x instance Lerp RGB where lerp s (RGB r g b) (RGB r' g' b') = RGB (lerp s r r') (lerp s g g') (lerp s b b') instance Scale RGB where scale s (RGB r g b) = RGB (scale s r) (scale s g) (scale s b) instance Average RGB where average cs = RGB (average reds) (average greens) (average blues) where reds = [ r | RGB r _ _ <- cs ] greens = [ g | RGB _ g _ <- cs ] blues = [ b | RGB _ _ b <- cs ] -- Consider using 4 bytes for color, rather than 32 bytes for the double (or are they floats?) instance Binary RGB where put (RGB r g b) = put r >> put g >> put b get = liftM3 RGB get get get ------------------------------------------------------------------------------------------ -- Colors with alpha -- | 'RGBA' is our color, with values between 0 and 1, inclusive. -- These values are *not* prenormalized data RGBA = RGBA !UI !UI !UI !UI deriving Show -- Todo: rethink what this means instance Over RGBA where over (RGBA r g b a) (RGBA r' g' b' a') = RGBA (f r r') -- (SrcAlpha, OneMinusSrcAlpha) (f g g') (f b b') (a + a' * (1 - a)) -- (One, OneMinusSrcAlpha) where f x y = a * y + (1 - a) * x {- -- An associative algorithm for handling the alpha channel -- Associative; please reinstate later | a <= nearZero = RGBA r' g' b' a_new | otherwise = RGBA (lerp r' (scale (1/a) r) a) (lerp g' (scale (1/a) g) a) (lerp b' (scale (1/a) b) a) a_new where -- can a_new be 0? only if a == 0 and a' == 0 a_new = a + a' * (1 - a) -} instance Binary RGBA where put (RGBA r g b a) = put r >> put g >> put b >> put a get = liftM4 RGBA get get get get
andygill/chalkboard2
Graphics/ChalkBoard/Types.hs
Haskell
bsd-3-clause
5,487
-- | Tools to build and access an AO dictionary. module AO.Dict ( AODef, AODictMap, AODict , buildAODict, cleanAODict, emptyAODict , readAODict, updateAODict, unsafeUpdateAODict , AODictIssue(..) ) where import Control.Monad ((>=>)) import Data.Maybe (fromJust) import qualified Data.List as L import qualified Data.Map as M import qualified Data.Set as Set import AO.InnerDict import AO.Code -- | An AO definition is a trivial pairing of a word with the AO code -- that is inlined wherever the word is used. In practice, we want some -- extra metadata with each definition (e.g. source location). type AODef meta = (Word,(AO_Code,meta)) -- | A dictionary map is simply a map formed of AO definitions. type AODictMap meta = M.Map Word (AO_Code,meta) -- | Access the clean definitions within an AO dictionary. readAODict :: AODict meta -> AODictMap meta readAODict (AODict d) = d -- | update metadata for a word (if it exists) updateAODict :: (AO_Code -> meta -> meta) -> Word -> AODict meta -> AODict meta updateAODict fn w (AODict d) = case M.lookup w d of Nothing -> (AODict d) Just (code,meta) -> let meta' = fn code meta in AODict (M.insert w (code,meta') d) -- | allow arbitrary manipulations if we really want them -- but at least mark them clearly. Try to use safely - i.e. -- adding annotations, inlining and partial evaluations, etc. unsafeUpdateAODict :: (AODictMap m -> AODictMap m) -> (AODict m -> AODict m) unsafeUpdateAODict f (AODict d) = AODict (f d) -- | useful for initializations emptyAODict :: AODict meta emptyAODict = AODict (M.empty) -- | to report problems with a dictionary while cleaning it up. -- -- Override: multiple definitions are provided for a word, in the -- order given. The last definition in this list is kept in the -- dictionary, unless there's some other issue with it. -- -- Cycle: a word is transitively part of a cycle, and thus its -- definition cannot be fully inlined (as per AO semantics). Where -- conventional languages use recursion, AO uses explicit fixpoint. -- A good fixpoint combinator is: %r [%^'wol] %rwo^'wol -- -- Cycles are removed from the dictionary after being recognized, -- such that any given word is recognized as part of at most one -- cycle. This may result in missing definition warnings. -- -- Missing: a definition uses words that are not part of the -- dictionary. All such definitions are removed from the dictionary. -- data AODictIssue meta = AODefOverride Word [(AO_Code,meta)] -- multiple definitions for one word. | AODefCycle [AODef meta] -- a cycle of words | AODefMissing (AODef meta) [Word] -- definition is missing words in list -- a warning capability type ReportIssue m meta = AODictIssue meta -> m () -- | given a list of definitions, produce a 'clean' dictionary (no cycles, -- no incompletely defined words) and also generate some warnings or errors. buildAODict :: (Monad m) => ReportIssue m meta -> [AODef meta] -> m (AODict meta) buildAODict warn = getFinalDefs warn >=> cleanAODict warn -- build a map and report overrides getFinalDefs :: (Monad m) => ReportIssue m meta -> [AODef meta] -> m (AODictMap meta) getFinalDefs warn defs = let mdict = L.foldl mmins M.empty defs in -- (word,(cm,[cm])) let dictOfFinalDefs = fmap fst mdict in -- (word,cm) let lOverrides = M.toList $ fmap (L.reverse . uncurry (:)) $ M.filter (not . null . snd) mdict in mapM_ (warn . uncurry AODefOverride) lOverrides >> return dictOfFinalDefs mmins :: (Ord k) => M.Map k (a,[a]) -> (k,a) -> M.Map k (a,[a]) mmins d (k,a) = M.alter (mmcons a) k d where mmcons a0 Nothing = Just (a0,[]) mmcons a0 (Just (a1,as)) = Just (a0,(a1:as)) -- | cleanup a map by removing words with cyclic or incomplete definitions cleanAODict :: (Monad m) => ReportIssue m meta -> AODictMap meta -> m (AODict meta) cleanAODict warn = clearCycles warn >=> clearMissing warn >=> return . AODict clearCycles :: (Monad m) => ReportIssue m meta -> AODictMap meta -> m (AODictMap meta) clearCycles warn d0 = emitErrors >> return cycleFree where g0 = fmap (aoWords . fst) d0 -- M.Map Word [Word] cycles = detectCycles g0 -- [[Word]] cycleFree = L.foldr M.delete d0 (L.concat cycles) emitErrors = mapM_ reportCycle cycles reportCycle = warn . AODefCycle . fmap getData getData w = (w, fromJust (M.lookup w d0)) -- recover def & meta -- by nature, any word in a cycle must be defined -- so 'fromJust' is safe here -- detect cycles in an abstract directed graph -- using a depth-first search detectCycles :: (Ord v) => M.Map v [v] -> [[v]] detectCycles = deforest where deforest g = case M.minViewWithKey g of Nothing -> [] Just ((v0,vs),_) -> let (visited, cycles) = dfs g [v0] [v0] vs in let g' = L.foldr M.delete g visited in cycles ++ deforest g' dfs _ cx _ [] = (cx, []) dfs g cx p (v:vs) = case (L.elemIndex v p) of Nothing -> -- no loop; may need to visit 'v' if L.elem v cx then dfs g cx p vs else let (cxd,cycd) = dfs g (v:cx) (v:p) (edgesFrom g v) in let (cxw,cycw) = dfs g cxd p vs in (cxw, cycd ++ cycw) Just n -> -- loop found; 'v' necessarily has been visited let cyc0 = L.reverse (L.take (n + 1) p) in let (cxw,cycw) = dfs g cx p vs in (cxw,(cyc0:cycw)) edgesFrom g v = maybe [] id $ M.lookup v g -- keep only words whose definitions are transitively fully defined clearMissing :: (Monad m) => ReportIssue m meta -> AODictMap meta -> m (AODictMap meta) clearMissing warn d0 = emitErrors >> return fullyDefined where g0 = fmap (aoWords . fst) d0 -- mwMap = incompleteWords g0 fullyDefined = L.foldr M.delete d0 (M.keys mwMap) emitErrors = mapM_ reportError (M.toList mwMap) reportError = warn . mkWarning mkWarning (w,mws) = -- w is in dictionary; mws aren't let defW = fromJust (M.lookup w d0) in AODefMissing (w,defW) mws -- find incomplete words based on missing transitive dependencies -- the result is a map of word -> missing words. incompleteWords :: (Ord w) => M.Map w [w] -> M.Map w [w] incompleteWords dict = dictMW where (dictMW, _okSet) = L.foldl cw (M.empty, Set.empty) (M.keys dict) cw r w = if (M.member w (fst r) || Set.member w (snd r)) then r else case M.lookup w dict of Nothing -> r -- w is missing word; will capture in 'mdeps' below Just deps -> let (dmw, dok) = L.foldl cw r deps in let mdeps = L.filter (`Set.notMember` dok) deps in if null mdeps then (dmw, Set.insert w dok) -- add word to OK set else (M.insert w mdeps dmw, dok) -- add word to missing words map
dmbarbour/awelon
hsrc/AO/Dict.hs
Haskell
bsd-3-clause
6,940
-- Tests for Statistics.Test.NonParametric module Tests.NonParametric (tests) where import Statistics.Distribution.Normal (standard) import Statistics.Test.KolmogorovSmirnov import Statistics.Test.MannWhitneyU import Statistics.Test.KruskalWallis import Statistics.Test.WilcoxonT import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit import Test.HUnit (assertEqual) import Tests.ApproxEq (eq) import Tests.Helpers (testAssertion, testEquality) import Tests.NonParametric.Table (tableKSD, tableKS2D) import qualified Data.Vector.Unboxed as U tests :: Test tests = testGroup "Nonparametric tests" $ concat [ mannWhitneyTests , wilcoxonSumTests , wilcoxonPairTests , kruskalWallisRankTests , kruskalWallisTests , kolmogorovSmirnovDTest ] ---------------------------------------------------------------- mannWhitneyTests :: [Test] mannWhitneyTests = zipWith test [(0::Int)..] testData ++ [ testEquality "Mann-Whitney U Critical Values, m=1" (replicate (20*3) Nothing) [mannWhitneyUCriticalValue (1,x) p | x <- [1..20], p <- [0.005,0.01,0.025]] , testEquality "Mann-Whitney U Critical Values, m=2, p=0.025" (replicate 7 Nothing ++ map Just [0,0,0,0,1,1,1,1,1,2,2,2,2]) [mannWhitneyUCriticalValue (2,x) 0.025 | x <- [1..20]] , testEquality "Mann-Whitney U Critical Values, m=6, p=0.05" (replicate 1 Nothing ++ map Just [0, 2,3,5,7,8,10,12,14,16,17,19,21,23,25,26,28,30,32]) [mannWhitneyUCriticalValue (6,x) 0.05 | x <- [1..20]] , testEquality "Mann-Whitney U Critical Values, m=20, p=0.025" (replicate 1 Nothing ++ map Just [2,8,14,20,27,34,41,48,55,62,69,76,83,90,98,105,112,119,127]) [mannWhitneyUCriticalValue (20,x) 0.025 | x <- [1..20]] ] where test n (a, b, c, d) = testCase "Mann-Whitney" $ do assertEqual ("Mann-Whitney U " ++ show n) c us assertEqual ("Mann-Whitney U Sig " ++ show n) d ss where us = mannWhitneyU (U.fromList a) (U.fromList b) ss = mannWhitneyUSignificant TwoTailed (length a, length b) 0.05 us -- List of (Sample A, Sample B, (Positive Rank, Negative Rank)) testData :: [([Double], [Double], (Double, Double), Maybe TestResult)] testData = [ ( [3,4,2,6,2,5] , [9,7,5,10,6,8] , (2, 34) , Just Significant ) , ( [540,480,600,590,605] , [760,890,1105,595,940] , (2, 23) , Just Significant ) , ( [19,22,16,29,24] , [20,11,17,12] , (17, 3) , Just NotSignificant ) , ( [126,148,85,61, 179,93, 45,189,85,93] , [194,128,69,135,171,149,89,248,79,137] , (35,65) , Just NotSignificant ) , ( [1..30] , [1..30] , (450,450) , Just NotSignificant ) , ( [1 .. 30] , [11.5 .. 40 ] , (190.0,710.0) , Just Significant ) ] wilcoxonSumTests :: [Test] wilcoxonSumTests = zipWith test [(0::Int)..] testData where test n (a, b, c) = testCase "Wilcoxon Sum" $ assertEqual ("Wilcoxon Sum " ++ show n) c (wilcoxonRankSums (U.fromList a) (U.fromList b)) -- List of (Sample A, Sample B, (Positive Rank, Negative Rank)) testData :: [([Double], [Double], (Double, Double))] testData = [ ( [8.50,9.48,8.65,8.16,8.83,7.76,8.63] , [8.27,8.20,8.25,8.14,9.00,8.10,7.20,8.32,7.70] , (75, 61) ) , ( [0.45,0.50,0.61,0.63,0.75,0.85,0.93] , [0.44,0.45,0.52,0.53,0.56,0.58,0.58,0.65,0.79] , (71.5, 64.5) ) ] wilcoxonPairTests :: [Test] wilcoxonPairTests = zipWith test [(0::Int)..] testData ++ -- Taken from the Mitic paper: [ testAssertion "Sig 16, 35" (to4dp 0.0467 $ wilcoxonMatchedPairSignificance 16 35) , testAssertion "Sig 16, 36" (to4dp 0.0523 $ wilcoxonMatchedPairSignificance 16 36) , testEquality "Wilcoxon critical values, p=0.05" (replicate 4 Nothing ++ map Just [0,2,3,5,8,10,13,17,21,25,30,35,41,47,53,60,67,75,83,91,100,110,119]) [wilcoxonMatchedPairCriticalValue x 0.05 | x <- [1..27]] , testEquality "Wilcoxon critical values, p=0.025" (replicate 5 Nothing ++ map Just [0,2,3,5,8,10,13,17,21,25,29,34,40,46,52,58,65,73,81,89,98,107]) [wilcoxonMatchedPairCriticalValue x 0.025 | x <- [1..27]] , testEquality "Wilcoxon critical values, p=0.01" (replicate 6 Nothing ++ map Just [0,1,3,5,7,9,12,15,19,23,27,32,37,43,49,55,62,69,76,84,92]) [wilcoxonMatchedPairCriticalValue x 0.01 | x <- [1..27]] , testEquality "Wilcoxon critical values, p=0.005" (replicate 7 Nothing ++ map Just [0,1,3,5,7,9,12,15,19,23,27,32,37,42,48,54,61,68,75,83]) [wilcoxonMatchedPairCriticalValue x 0.005 | x <- [1..27]] ] where test n (a, b, c) = testEquality ("Wilcoxon Paired " ++ show n) c res where res = (wilcoxonMatchedPairSignedRank (U.fromList a) (U.fromList b)) -- List of (Sample A, Sample B, (Positive Rank, Negative Rank)) testData :: [([Double], [Double], (Double, Double))] testData = [ ([1..10], [1..10], (0, 0 )) , ([1..5], [6..10], (0, 5*(-3))) -- Worked example from the Internet: , ( [125,115,130,140,140,115,140,125,140,135] , [110,122,125,120,140,124,123,137,135,145] , ( sum $ filter (> 0) [7,-3,1.5,9,0,-4,8,-6,1.5,-5] , sum $ filter (< 0) [7,-3,1.5,9,0,-4,8,-6,1.5,-5] ) ) -- Worked examples from books/papers: , ( [2.4,1.9,2.3,1.9,2.4,2.5] , [2.0,2.1,2.0,2.0,1.8,2.0] , (18, -3) ) , ( [130,170,125,170,130,130,145,160] , [120,163,120,135,143,136,144,120] , (27, -9) ) , ( [540,580,600,680,430,740,600,690,605,520] , [760,710,1105,880,500,990,1050,640,595,520] , (3, -42) ) ] to4dp tgt x = x >= tgt - 0.00005 && x < tgt + 0.00005 ---------------------------------------------------------------- kruskalWallisRankTests :: [Test] kruskalWallisRankTests = zipWith test [(0::Int)..] testData where test n (a, b) = testCase "Kruskal-Wallis Ranking" $ assertEqual ("Kruskal-Wallis " ++ show n) (map U.fromList b) (kruskalWallisRank $ map U.fromList a) testData = [ ( [ [68,93,123,83,108,122] , [119,116,101,103,113,84] , [70,68,54,73,81,68] , [61,54,59,67,59,70] ] , [ [8.0,14.0,16.0,19.0,23.0,24.0] , [15.0,17.0,18.0,20.0,21.0,22.0] , [1.5,8.0,8.0,10.5,12.0,13.0] , [1.5,3.5,3.5,5.0,6.0,10.5] ] ) ] kruskalWallisTests :: [Test] kruskalWallisTests = zipWith test [(0::Int)..] testData where test n (a, b, c) = testCase "Kruskal-Wallis" $ do assertEqual ("Kruskal-Wallis " ++ show n) (round100 b) (round100 kw) assertEqual ("Kruskal-Wallis Sig " ++ show n) c kwt where kw = kruskalWallis $ map U.fromList a kwt = kruskalWallisTest 0.05 $ map U.fromList a round100 :: Double -> Integer round100 = round . (*100) testData = [ ( [ [68,93,123,83,108,122] , [119,116,101,103,113,84] , [70,68,54,73,81,68] , [61,54,59,67,59,70] ] , 16.03 , Just Significant ) , ( [ [5,5,3,5,5,5,5] , [5,5,5,5,7,5,5] , [5,5,6,5,5,5,5] , [4,5,5,5,6,5,5] ] , 2.24 , Just NotSignificant ) , ( [ [36,48,5,67,53] , [49,33,60,2,55] , [71,31,140,59,42] ] , 1.22 , Just NotSignificant ) , ( [ [6,38,3,17,11,30,15,16,25,5] , [34,28,42,13,40,31,9,32,39,27] , [13,35,19,4,29,0,7,33,18,24] ] , 6.10 , Just Significant ) ] ---------------------------------------------------------------- -- K-S test ---------------------------------------------------------------- kolmogorovSmirnovDTest :: [Test] kolmogorovSmirnovDTest = [ testAssertion "K-S D statistics" $ and [ eq 1e-6 (kolmogorovSmirnovD standard (toU sample)) reference | (reference,sample) <- tableKSD ] , testAssertion "K-S 2-sample statistics" $ and [ eq 1e-6 (kolmogorovSmirnov2D (toU xs) (toU ys)) reference | (reference,xs,ys) <- tableKS2D ] , testAssertion "K-S probability" $ and [ eq 1e-14 (kolmogorovSmirnovProbability n d) p | (d,n,p) <- testData ] ] where toU = U.fromList -- Test data for the calculation of cumulative probability -- P(D[n] < d). -- -- Test data is: -- (D[n], n, p) -- Table is generated using sample program from paper testData :: [(Double,Int,Double)] testData = [ (0.09 , 3, 0 ) , (0.2 , 3, 0.00177777777777778 ) , (0.301 , 3, 0.116357025777778 ) , (0.392 , 3, 0.383127210666667 ) , (0.5003 , 3, 0.667366306558667 ) , (0.604 , 3, 0.861569877333333 ) , (0.699 , 3, 0.945458198 ) , (0.802 , 3, 0.984475216 ) , (0.9 , 3, 0.998 ) , (0.09 , 5, 0 ) , (0.2 , 5, 0.0384 ) , (0.301 , 5, 0.33993786080016 ) , (0.392 , 5, 0.66931908083712 ) , (0.5003 , 5, 0.888397260183794 ) , (0.604 , 5, 0.971609957879808 ) , (0.699 , 5, 0.994331075994008 ) , (0.802 , 5, 0.999391366368064 ) , (0.9 , 5, 0.99998 ) , (0.09 , 8, 3.37615237575e-06 ) , (0.2 , 8, 0.151622071801758 ) , (0.301 , 8, 0.613891042670582 ) , (0.392 , 8, 0.871491561427005 ) , (0.5003 , 8, 0.977534089199071 ) , (0.604 , 8, 0.997473116268255 ) , (0.699 , 8, 0.999806082005123 ) , (0.802 , 8, 0.999995133786947 ) , (0.9 , 8, 0.99999998 ) , (0.09 , 10, 3.89639433093119e-05) , (0.2 , 10, 0.25128096 ) , (0.301 , 10, 0.732913126355935 ) , (0.392 , 10, 0.932185254518767 ) , (0.5003 , 10, 0.992276179340446 ) , (0.604 , 10, 0.999495533516769 ) , (0.699 , 10, 0.999979691783985 ) , (0.802 , 10, 0.999999801409237 ) , (0.09 , 20, 0.00794502217168886 ) , (0.2 , 20, 0.647279826376584 ) , (0.301 , 20, 0.958017466965765 ) , (0.392 , 20, 0.997206424843499 ) , (0.5003 , 20, 0.999962641414228 ) , (0.09 , 30, 0.0498147538075168 ) , (0.2 , 30, 0.842030838984526 ) , (0.301 , 30, 0.993403560017612 ) , (0.392 , 30, 0.99988478803318 ) , (0.09 , 100, 0.629367974413669 ) ]
fpco/statistics
tests/Tests/NonParametric.hs
Haskell
bsd-2-clause
12,172
-- %************************************************************************ -- %* * -- The known-key names for Template Haskell -- %* * -- %************************************************************************ module THNames where import PrelNames( mk_known_key_name ) import Module( Module, mkModuleNameFS, mkModule, thPackageKey ) import Name( Name ) import OccName( tcName, clsName, dataName, varName ) import RdrName( RdrName, nameRdrName ) import Unique import FastString -- To add a name, do three things -- -- 1) Allocate a key -- 2) Make a "Name" -- 3) Add the name to templateHaskellNames templateHaskellNames :: [Name] -- The names that are implicitly mentioned by ``bracket'' -- Should stay in sync with the import list of DsMeta templateHaskellNames = [ returnQName, bindQName, sequenceQName, newNameName, liftName, mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName, liftStringName, unTypeName, unTypeQName, unsafeTExpCoerceName, -- Lit charLName, stringLName, integerLName, intPrimLName, wordPrimLName, floatPrimLName, doublePrimLName, rationalLName, stringPrimLName, charPrimLName, -- Pat litPName, varPName, tupPName, unboxedTupPName, conPName, tildePName, bangPName, infixPName, asPName, wildPName, recPName, listPName, sigPName, viewPName, -- FieldPat fieldPatName, -- Match matchName, -- Clause clauseName, -- Exp varEName, conEName, litEName, appEName, infixEName, infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName, tupEName, unboxedTupEName, condEName, multiIfEName, letEName, caseEName, doEName, compEName, fromEName, fromThenEName, fromToEName, fromThenToEName, listEName, sigEName, recConEName, recUpdEName, staticEName, -- FieldExp fieldExpName, -- Body guardedBName, normalBName, -- Guard normalGEName, patGEName, -- Stmt bindSName, letSName, noBindSName, parSName, -- Dec funDName, valDName, dataDName, newtypeDName, tySynDName, classDName, instanceDName, standaloneDerivDName, sigDName, forImpDName, pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName, pragRuleDName, pragAnnDName, defaultSigDName, dataFamilyDName, openTypeFamilyDName, closedTypeFamilyDName, dataInstDName, newtypeInstDName, tySynInstDName, infixLDName, infixRDName, infixNDName, roleAnnotDName, -- Cxt cxtName, -- Strict isStrictName, notStrictName, unpackedName, -- Con normalCName, recCName, infixCName, forallCName, -- StrictType strictTypeName, -- VarStrictType varStrictTypeName, -- Type forallTName, varTName, conTName, appTName, equalityTName, tupleTName, unboxedTupleTName, arrowTName, listTName, sigTName, litTName, promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName, wildCardTName, namedWildCardTName, -- TyLit numTyLitName, strTyLitName, -- TyVarBndr plainTVName, kindedTVName, -- Role nominalRName, representationalRName, phantomRName, inferRName, -- Kind varKName, conKName, tupleKName, arrowKName, listKName, appKName, starKName, constraintKName, -- FamilyResultSig noSigName, kindSigName, tyVarSigName, -- InjectivityAnn injectivityAnnName, -- Callconv cCallName, stdCallName, cApiCallName, primCallName, javaScriptCallName, -- Safety unsafeName, safeName, interruptibleName, -- Inline noInlineDataConName, inlineDataConName, inlinableDataConName, -- RuleMatch conLikeDataConName, funLikeDataConName, -- Phases allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName, -- TExp tExpDataConName, -- RuleBndr ruleVarName, typedRuleVarName, -- FunDep funDepName, -- FamFlavour typeFamName, dataFamName, -- TySynEqn tySynEqnName, -- AnnTarget valueAnnotationName, typeAnnotationName, moduleAnnotationName, -- The type classes liftClassName, -- And the tycons qTyConName, nameTyConName, patTyConName, fieldPatTyConName, matchQTyConName, clauseQTyConName, expQTyConName, fieldExpTyConName, predTyConName, stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName, varStrictTypeQTyConName, typeQTyConName, expTyConName, decTyConName, typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName, patQTyConName, fieldPatQTyConName, fieldExpQTyConName, funDepTyConName, predQTyConName, decsQTyConName, ruleBndrQTyConName, tySynEqnQTyConName, roleTyConName, tExpTyConName, injAnnTyConName, kindTyConName, -- Quasiquoting quoteDecName, quoteTypeName, quoteExpName, quotePatName] thSyn, thLib, qqLib :: Module thSyn = mkTHModule (fsLit "Language.Haskell.TH.Syntax") thLib = mkTHModule (fsLit "Language.Haskell.TH.Lib") qqLib = mkTHModule (fsLit "Language.Haskell.TH.Quote") mkTHModule :: FastString -> Module mkTHModule m = mkModule thPackageKey (mkModuleNameFS m) libFun, libTc, thFun, thTc, thCls, thCon, qqFun :: FastString -> Unique -> Name libFun = mk_known_key_name OccName.varName thLib libTc = mk_known_key_name OccName.tcName thLib thFun = mk_known_key_name OccName.varName thSyn thTc = mk_known_key_name OccName.tcName thSyn thCls = mk_known_key_name OccName.clsName thSyn thCon = mk_known_key_name OccName.dataName thSyn qqFun = mk_known_key_name OccName.varName qqLib -------------------- TH.Syntax ----------------------- liftClassName :: Name liftClassName = thCls (fsLit "Lift") liftClassKey qTyConName, nameTyConName, fieldExpTyConName, patTyConName, fieldPatTyConName, expTyConName, decTyConName, typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName, funDepTyConName, predTyConName, tExpTyConName, injAnnTyConName, kindTyConName :: Name qTyConName = thTc (fsLit "Q") qTyConKey nameTyConName = thTc (fsLit "Name") nameTyConKey fieldExpTyConName = thTc (fsLit "FieldExp") fieldExpTyConKey patTyConName = thTc (fsLit "Pat") patTyConKey fieldPatTyConName = thTc (fsLit "FieldPat") fieldPatTyConKey expTyConName = thTc (fsLit "Exp") expTyConKey decTyConName = thTc (fsLit "Dec") decTyConKey typeTyConName = thTc (fsLit "Type") typeTyConKey tyVarBndrTyConName= thTc (fsLit "TyVarBndr") tyVarBndrTyConKey matchTyConName = thTc (fsLit "Match") matchTyConKey clauseTyConName = thTc (fsLit "Clause") clauseTyConKey funDepTyConName = thTc (fsLit "FunDep") funDepTyConKey predTyConName = thTc (fsLit "Pred") predTyConKey tExpTyConName = thTc (fsLit "TExp") tExpTyConKey injAnnTyConName = thTc (fsLit "InjectivityAnn") injAnnTyConKey kindTyConName = thTc (fsLit "Kind") kindTyConKey returnQName, bindQName, sequenceQName, newNameName, liftName, mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName, liftStringName, unTypeName, unTypeQName, unsafeTExpCoerceName :: Name returnQName = thFun (fsLit "returnQ") returnQIdKey bindQName = thFun (fsLit "bindQ") bindQIdKey sequenceQName = thFun (fsLit "sequenceQ") sequenceQIdKey newNameName = thFun (fsLit "newName") newNameIdKey liftName = thFun (fsLit "lift") liftIdKey liftStringName = thFun (fsLit "liftString") liftStringIdKey mkNameName = thFun (fsLit "mkName") mkNameIdKey mkNameG_vName = thFun (fsLit "mkNameG_v") mkNameG_vIdKey mkNameG_dName = thFun (fsLit "mkNameG_d") mkNameG_dIdKey mkNameG_tcName = thFun (fsLit "mkNameG_tc") mkNameG_tcIdKey mkNameLName = thFun (fsLit "mkNameL") mkNameLIdKey unTypeName = thFun (fsLit "unType") unTypeIdKey unTypeQName = thFun (fsLit "unTypeQ") unTypeQIdKey unsafeTExpCoerceName = thFun (fsLit "unsafeTExpCoerce") unsafeTExpCoerceIdKey -------------------- TH.Lib ----------------------- -- data Lit = ... charLName, stringLName, integerLName, intPrimLName, wordPrimLName, floatPrimLName, doublePrimLName, rationalLName, stringPrimLName, charPrimLName :: Name charLName = libFun (fsLit "charL") charLIdKey stringLName = libFun (fsLit "stringL") stringLIdKey integerLName = libFun (fsLit "integerL") integerLIdKey intPrimLName = libFun (fsLit "intPrimL") intPrimLIdKey wordPrimLName = libFun (fsLit "wordPrimL") wordPrimLIdKey floatPrimLName = libFun (fsLit "floatPrimL") floatPrimLIdKey doublePrimLName = libFun (fsLit "doublePrimL") doublePrimLIdKey rationalLName = libFun (fsLit "rationalL") rationalLIdKey stringPrimLName = libFun (fsLit "stringPrimL") stringPrimLIdKey charPrimLName = libFun (fsLit "charPrimL") charPrimLIdKey -- data Pat = ... litPName, varPName, tupPName, unboxedTupPName, conPName, infixPName, tildePName, bangPName, asPName, wildPName, recPName, listPName, sigPName, viewPName :: Name litPName = libFun (fsLit "litP") litPIdKey varPName = libFun (fsLit "varP") varPIdKey tupPName = libFun (fsLit "tupP") tupPIdKey unboxedTupPName = libFun (fsLit "unboxedTupP") unboxedTupPIdKey conPName = libFun (fsLit "conP") conPIdKey infixPName = libFun (fsLit "infixP") infixPIdKey tildePName = libFun (fsLit "tildeP") tildePIdKey bangPName = libFun (fsLit "bangP") bangPIdKey asPName = libFun (fsLit "asP") asPIdKey wildPName = libFun (fsLit "wildP") wildPIdKey recPName = libFun (fsLit "recP") recPIdKey listPName = libFun (fsLit "listP") listPIdKey sigPName = libFun (fsLit "sigP") sigPIdKey viewPName = libFun (fsLit "viewP") viewPIdKey -- type FieldPat = ... fieldPatName :: Name fieldPatName = libFun (fsLit "fieldPat") fieldPatIdKey -- data Match = ... matchName :: Name matchName = libFun (fsLit "match") matchIdKey -- data Clause = ... clauseName :: Name clauseName = libFun (fsLit "clause") clauseIdKey -- data Exp = ... varEName, conEName, litEName, appEName, infixEName, infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName, tupEName, unboxedTupEName, condEName, multiIfEName, letEName, caseEName, doEName, compEName, staticEName :: Name varEName = libFun (fsLit "varE") varEIdKey conEName = libFun (fsLit "conE") conEIdKey litEName = libFun (fsLit "litE") litEIdKey appEName = libFun (fsLit "appE") appEIdKey infixEName = libFun (fsLit "infixE") infixEIdKey infixAppName = libFun (fsLit "infixApp") infixAppIdKey sectionLName = libFun (fsLit "sectionL") sectionLIdKey sectionRName = libFun (fsLit "sectionR") sectionRIdKey lamEName = libFun (fsLit "lamE") lamEIdKey lamCaseEName = libFun (fsLit "lamCaseE") lamCaseEIdKey tupEName = libFun (fsLit "tupE") tupEIdKey unboxedTupEName = libFun (fsLit "unboxedTupE") unboxedTupEIdKey condEName = libFun (fsLit "condE") condEIdKey multiIfEName = libFun (fsLit "multiIfE") multiIfEIdKey letEName = libFun (fsLit "letE") letEIdKey caseEName = libFun (fsLit "caseE") caseEIdKey doEName = libFun (fsLit "doE") doEIdKey compEName = libFun (fsLit "compE") compEIdKey -- ArithSeq skips a level fromEName, fromThenEName, fromToEName, fromThenToEName :: Name fromEName = libFun (fsLit "fromE") fromEIdKey fromThenEName = libFun (fsLit "fromThenE") fromThenEIdKey fromToEName = libFun (fsLit "fromToE") fromToEIdKey fromThenToEName = libFun (fsLit "fromThenToE") fromThenToEIdKey -- end ArithSeq listEName, sigEName, recConEName, recUpdEName :: Name listEName = libFun (fsLit "listE") listEIdKey sigEName = libFun (fsLit "sigE") sigEIdKey recConEName = libFun (fsLit "recConE") recConEIdKey recUpdEName = libFun (fsLit "recUpdE") recUpdEIdKey staticEName = libFun (fsLit "staticE") staticEIdKey -- type FieldExp = ... fieldExpName :: Name fieldExpName = libFun (fsLit "fieldExp") fieldExpIdKey -- data Body = ... guardedBName, normalBName :: Name guardedBName = libFun (fsLit "guardedB") guardedBIdKey normalBName = libFun (fsLit "normalB") normalBIdKey -- data Guard = ... normalGEName, patGEName :: Name normalGEName = libFun (fsLit "normalGE") normalGEIdKey patGEName = libFun (fsLit "patGE") patGEIdKey -- data Stmt = ... bindSName, letSName, noBindSName, parSName :: Name bindSName = libFun (fsLit "bindS") bindSIdKey letSName = libFun (fsLit "letS") letSIdKey noBindSName = libFun (fsLit "noBindS") noBindSIdKey parSName = libFun (fsLit "parS") parSIdKey -- data Dec = ... funDName, valDName, dataDName, newtypeDName, tySynDName, classDName, instanceDName, sigDName, forImpDName, pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName, pragRuleDName, pragAnnDName, standaloneDerivDName, defaultSigDName, dataInstDName, newtypeInstDName, tySynInstDName, dataFamilyDName, openTypeFamilyDName, closedTypeFamilyDName, infixLDName, infixRDName, infixNDName, roleAnnotDName :: Name funDName = libFun (fsLit "funD") funDIdKey valDName = libFun (fsLit "valD") valDIdKey dataDName = libFun (fsLit "dataD") dataDIdKey newtypeDName = libFun (fsLit "newtypeD") newtypeDIdKey tySynDName = libFun (fsLit "tySynD") tySynDIdKey classDName = libFun (fsLit "classD") classDIdKey instanceDName = libFun (fsLit "instanceD") instanceDIdKey standaloneDerivDName = libFun (fsLit "standaloneDerivD") standaloneDerivDIdKey sigDName = libFun (fsLit "sigD") sigDIdKey defaultSigDName = libFun (fsLit "defaultSigD") defaultSigDIdKey forImpDName = libFun (fsLit "forImpD") forImpDIdKey pragInlDName = libFun (fsLit "pragInlD") pragInlDIdKey pragSpecDName = libFun (fsLit "pragSpecD") pragSpecDIdKey pragSpecInlDName = libFun (fsLit "pragSpecInlD") pragSpecInlDIdKey pragSpecInstDName = libFun (fsLit "pragSpecInstD") pragSpecInstDIdKey pragRuleDName = libFun (fsLit "pragRuleD") pragRuleDIdKey pragAnnDName = libFun (fsLit "pragAnnD") pragAnnDIdKey dataInstDName = libFun (fsLit "dataInstD") dataInstDIdKey newtypeInstDName = libFun (fsLit "newtypeInstD") newtypeInstDIdKey tySynInstDName = libFun (fsLit "tySynInstD") tySynInstDIdKey openTypeFamilyDName = libFun (fsLit "openTypeFamilyD") openTypeFamilyDIdKey closedTypeFamilyDName= libFun (fsLit "closedTypeFamilyD") closedTypeFamilyDIdKey dataFamilyDName = libFun (fsLit "dataFamilyD") dataFamilyDIdKey infixLDName = libFun (fsLit "infixLD") infixLDIdKey infixRDName = libFun (fsLit "infixRD") infixRDIdKey infixNDName = libFun (fsLit "infixND") infixNDIdKey roleAnnotDName = libFun (fsLit "roleAnnotD") roleAnnotDIdKey -- type Ctxt = ... cxtName :: Name cxtName = libFun (fsLit "cxt") cxtIdKey -- data Strict = ... isStrictName, notStrictName, unpackedName :: Name isStrictName = libFun (fsLit "isStrict") isStrictKey notStrictName = libFun (fsLit "notStrict") notStrictKey unpackedName = libFun (fsLit "unpacked") unpackedKey -- data Con = ... normalCName, recCName, infixCName, forallCName :: Name normalCName = libFun (fsLit "normalC") normalCIdKey recCName = libFun (fsLit "recC") recCIdKey infixCName = libFun (fsLit "infixC") infixCIdKey forallCName = libFun (fsLit "forallC") forallCIdKey -- type StrictType = ... strictTypeName :: Name strictTypeName = libFun (fsLit "strictType") strictTKey -- type VarStrictType = ... varStrictTypeName :: Name varStrictTypeName = libFun (fsLit "varStrictType") varStrictTKey -- data Type = ... forallTName, varTName, conTName, tupleTName, unboxedTupleTName, arrowTName, listTName, appTName, sigTName, equalityTName, litTName, promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName, wildCardTName, namedWildCardTName :: Name forallTName = libFun (fsLit "forallT") forallTIdKey varTName = libFun (fsLit "varT") varTIdKey conTName = libFun (fsLit "conT") conTIdKey tupleTName = libFun (fsLit "tupleT") tupleTIdKey unboxedTupleTName = libFun (fsLit "unboxedTupleT") unboxedTupleTIdKey arrowTName = libFun (fsLit "arrowT") arrowTIdKey listTName = libFun (fsLit "listT") listTIdKey appTName = libFun (fsLit "appT") appTIdKey sigTName = libFun (fsLit "sigT") sigTIdKey equalityTName = libFun (fsLit "equalityT") equalityTIdKey litTName = libFun (fsLit "litT") litTIdKey promotedTName = libFun (fsLit "promotedT") promotedTIdKey promotedTupleTName = libFun (fsLit "promotedTupleT") promotedTupleTIdKey promotedNilTName = libFun (fsLit "promotedNilT") promotedNilTIdKey promotedConsTName = libFun (fsLit "promotedConsT") promotedConsTIdKey wildCardTName = libFun (fsLit "wildCardT") wildCardTIdKey namedWildCardTName = libFun (fsLit "namedWildCardT") namedWildCardTIdKey -- data TyLit = ... numTyLitName, strTyLitName :: Name numTyLitName = libFun (fsLit "numTyLit") numTyLitIdKey strTyLitName = libFun (fsLit "strTyLit") strTyLitIdKey -- data TyVarBndr = ... plainTVName, kindedTVName :: Name plainTVName = libFun (fsLit "plainTV") plainTVIdKey kindedTVName = libFun (fsLit "kindedTV") kindedTVIdKey -- data Role = ... nominalRName, representationalRName, phantomRName, inferRName :: Name nominalRName = libFun (fsLit "nominalR") nominalRIdKey representationalRName = libFun (fsLit "representationalR") representationalRIdKey phantomRName = libFun (fsLit "phantomR") phantomRIdKey inferRName = libFun (fsLit "inferR") inferRIdKey -- data Kind = ... varKName, conKName, tupleKName, arrowKName, listKName, appKName, starKName, constraintKName :: Name varKName = libFun (fsLit "varK") varKIdKey conKName = libFun (fsLit "conK") conKIdKey tupleKName = libFun (fsLit "tupleK") tupleKIdKey arrowKName = libFun (fsLit "arrowK") arrowKIdKey listKName = libFun (fsLit "listK") listKIdKey appKName = libFun (fsLit "appK") appKIdKey starKName = libFun (fsLit "starK") starKIdKey constraintKName = libFun (fsLit "constraintK") constraintKIdKey -- data FamilyResultSig = ... noSigName, kindSigName, tyVarSigName :: Name noSigName = libFun (fsLit "noSig") noSigIdKey kindSigName = libFun (fsLit "kindSig") kindSigIdKey tyVarSigName = libFun (fsLit "tyVarSig") tyVarSigIdKey -- data InjectivityAnn = ... injectivityAnnName :: Name injectivityAnnName = libFun (fsLit "injectivityAnn") injectivityAnnIdKey -- data Callconv = ... cCallName, stdCallName, cApiCallName, primCallName, javaScriptCallName :: Name cCallName = libFun (fsLit "cCall") cCallIdKey stdCallName = libFun (fsLit "stdCall") stdCallIdKey cApiCallName = libFun (fsLit "cApi") cApiCallIdKey primCallName = libFun (fsLit "prim") primCallIdKey javaScriptCallName = libFun (fsLit "javaScript") javaScriptCallIdKey -- data Safety = ... unsafeName, safeName, interruptibleName :: Name unsafeName = libFun (fsLit "unsafe") unsafeIdKey safeName = libFun (fsLit "safe") safeIdKey interruptibleName = libFun (fsLit "interruptible") interruptibleIdKey -- data Inline = ... noInlineDataConName, inlineDataConName, inlinableDataConName :: Name noInlineDataConName = thCon (fsLit "NoInline") noInlineDataConKey inlineDataConName = thCon (fsLit "Inline") inlineDataConKey inlinableDataConName = thCon (fsLit "Inlinable") inlinableDataConKey -- data RuleMatch = ... conLikeDataConName, funLikeDataConName :: Name conLikeDataConName = thCon (fsLit "ConLike") conLikeDataConKey funLikeDataConName = thCon (fsLit "FunLike") funLikeDataConKey -- data Phases = ... allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName :: Name allPhasesDataConName = thCon (fsLit "AllPhases") allPhasesDataConKey fromPhaseDataConName = thCon (fsLit "FromPhase") fromPhaseDataConKey beforePhaseDataConName = thCon (fsLit "BeforePhase") beforePhaseDataConKey -- newtype TExp a = ... tExpDataConName :: Name tExpDataConName = thCon (fsLit "TExp") tExpDataConKey -- data RuleBndr = ... ruleVarName, typedRuleVarName :: Name ruleVarName = libFun (fsLit ("ruleVar")) ruleVarIdKey typedRuleVarName = libFun (fsLit ("typedRuleVar")) typedRuleVarIdKey -- data FunDep = ... funDepName :: Name funDepName = libFun (fsLit "funDep") funDepIdKey -- data FamFlavour = ... typeFamName, dataFamName :: Name typeFamName = libFun (fsLit "typeFam") typeFamIdKey dataFamName = libFun (fsLit "dataFam") dataFamIdKey -- data TySynEqn = ... tySynEqnName :: Name tySynEqnName = libFun (fsLit "tySynEqn") tySynEqnIdKey -- data AnnTarget = ... valueAnnotationName, typeAnnotationName, moduleAnnotationName :: Name valueAnnotationName = libFun (fsLit "valueAnnotation") valueAnnotationIdKey typeAnnotationName = libFun (fsLit "typeAnnotation") typeAnnotationIdKey moduleAnnotationName = libFun (fsLit "moduleAnnotation") moduleAnnotationIdKey matchQTyConName, clauseQTyConName, expQTyConName, stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName, varStrictTypeQTyConName, typeQTyConName, fieldExpQTyConName, patQTyConName, fieldPatQTyConName, predQTyConName, decsQTyConName, ruleBndrQTyConName, tySynEqnQTyConName, roleTyConName :: Name matchQTyConName = libTc (fsLit "MatchQ") matchQTyConKey clauseQTyConName = libTc (fsLit "ClauseQ") clauseQTyConKey expQTyConName = libTc (fsLit "ExpQ") expQTyConKey stmtQTyConName = libTc (fsLit "StmtQ") stmtQTyConKey decQTyConName = libTc (fsLit "DecQ") decQTyConKey decsQTyConName = libTc (fsLit "DecsQ") decsQTyConKey -- Q [Dec] conQTyConName = libTc (fsLit "ConQ") conQTyConKey strictTypeQTyConName = libTc (fsLit "StrictTypeQ") strictTypeQTyConKey varStrictTypeQTyConName = libTc (fsLit "VarStrictTypeQ") varStrictTypeQTyConKey typeQTyConName = libTc (fsLit "TypeQ") typeQTyConKey fieldExpQTyConName = libTc (fsLit "FieldExpQ") fieldExpQTyConKey patQTyConName = libTc (fsLit "PatQ") patQTyConKey fieldPatQTyConName = libTc (fsLit "FieldPatQ") fieldPatQTyConKey predQTyConName = libTc (fsLit "PredQ") predQTyConKey ruleBndrQTyConName = libTc (fsLit "RuleBndrQ") ruleBndrQTyConKey tySynEqnQTyConName = libTc (fsLit "TySynEqnQ") tySynEqnQTyConKey roleTyConName = libTc (fsLit "Role") roleTyConKey -- quasiquoting quoteExpName, quotePatName, quoteDecName, quoteTypeName :: Name quoteExpName = qqFun (fsLit "quoteExp") quoteExpKey quotePatName = qqFun (fsLit "quotePat") quotePatKey quoteDecName = qqFun (fsLit "quoteDec") quoteDecKey quoteTypeName = qqFun (fsLit "quoteType") quoteTypeKey -- ClassUniques available: 200-299 -- Check in PrelNames if you want to change this liftClassKey :: Unique liftClassKey = mkPreludeClassUnique 200 -- TyConUniques available: 200-299 -- Check in PrelNames if you want to change this expTyConKey, matchTyConKey, clauseTyConKey, qTyConKey, expQTyConKey, decQTyConKey, patTyConKey, matchQTyConKey, clauseQTyConKey, stmtQTyConKey, conQTyConKey, typeQTyConKey, typeTyConKey, tyVarBndrTyConKey, decTyConKey, varStrictTypeQTyConKey, strictTypeQTyConKey, fieldExpTyConKey, fieldPatTyConKey, nameTyConKey, patQTyConKey, fieldPatQTyConKey, fieldExpQTyConKey, funDepTyConKey, predTyConKey, predQTyConKey, decsQTyConKey, ruleBndrQTyConKey, tySynEqnQTyConKey, roleTyConKey, tExpTyConKey, injAnnTyConKey, kindTyConKey :: Unique expTyConKey = mkPreludeTyConUnique 200 matchTyConKey = mkPreludeTyConUnique 201 clauseTyConKey = mkPreludeTyConUnique 202 qTyConKey = mkPreludeTyConUnique 203 expQTyConKey = mkPreludeTyConUnique 204 decQTyConKey = mkPreludeTyConUnique 205 patTyConKey = mkPreludeTyConUnique 206 matchQTyConKey = mkPreludeTyConUnique 207 clauseQTyConKey = mkPreludeTyConUnique 208 stmtQTyConKey = mkPreludeTyConUnique 209 conQTyConKey = mkPreludeTyConUnique 210 typeQTyConKey = mkPreludeTyConUnique 211 typeTyConKey = mkPreludeTyConUnique 212 decTyConKey = mkPreludeTyConUnique 213 varStrictTypeQTyConKey = mkPreludeTyConUnique 214 strictTypeQTyConKey = mkPreludeTyConUnique 215 fieldExpTyConKey = mkPreludeTyConUnique 216 fieldPatTyConKey = mkPreludeTyConUnique 217 nameTyConKey = mkPreludeTyConUnique 218 patQTyConKey = mkPreludeTyConUnique 219 fieldPatQTyConKey = mkPreludeTyConUnique 220 fieldExpQTyConKey = mkPreludeTyConUnique 221 funDepTyConKey = mkPreludeTyConUnique 222 predTyConKey = mkPreludeTyConUnique 223 predQTyConKey = mkPreludeTyConUnique 224 tyVarBndrTyConKey = mkPreludeTyConUnique 225 decsQTyConKey = mkPreludeTyConUnique 226 ruleBndrQTyConKey = mkPreludeTyConUnique 227 tySynEqnQTyConKey = mkPreludeTyConUnique 228 roleTyConKey = mkPreludeTyConUnique 229 tExpTyConKey = mkPreludeTyConUnique 230 injAnnTyConKey = mkPreludeTyConUnique 231 kindTyConKey = mkPreludeTyConUnique 232 -- IdUniques available: 200-499 -- If you want to change this, make sure you check in PrelNames returnQIdKey, bindQIdKey, sequenceQIdKey, liftIdKey, newNameIdKey, mkNameIdKey, mkNameG_vIdKey, mkNameG_dIdKey, mkNameG_tcIdKey, mkNameLIdKey, unTypeIdKey, unTypeQIdKey, unsafeTExpCoerceIdKey :: Unique returnQIdKey = mkPreludeMiscIdUnique 200 bindQIdKey = mkPreludeMiscIdUnique 201 sequenceQIdKey = mkPreludeMiscIdUnique 202 liftIdKey = mkPreludeMiscIdUnique 203 newNameIdKey = mkPreludeMiscIdUnique 204 mkNameIdKey = mkPreludeMiscIdUnique 205 mkNameG_vIdKey = mkPreludeMiscIdUnique 206 mkNameG_dIdKey = mkPreludeMiscIdUnique 207 mkNameG_tcIdKey = mkPreludeMiscIdUnique 208 mkNameLIdKey = mkPreludeMiscIdUnique 209 unTypeIdKey = mkPreludeMiscIdUnique 210 unTypeQIdKey = mkPreludeMiscIdUnique 211 unsafeTExpCoerceIdKey = mkPreludeMiscIdUnique 212 -- data Lit = ... charLIdKey, stringLIdKey, integerLIdKey, intPrimLIdKey, wordPrimLIdKey, floatPrimLIdKey, doublePrimLIdKey, rationalLIdKey, stringPrimLIdKey, charPrimLIdKey:: Unique charLIdKey = mkPreludeMiscIdUnique 220 stringLIdKey = mkPreludeMiscIdUnique 221 integerLIdKey = mkPreludeMiscIdUnique 222 intPrimLIdKey = mkPreludeMiscIdUnique 223 wordPrimLIdKey = mkPreludeMiscIdUnique 224 floatPrimLIdKey = mkPreludeMiscIdUnique 225 doublePrimLIdKey = mkPreludeMiscIdUnique 226 rationalLIdKey = mkPreludeMiscIdUnique 227 stringPrimLIdKey = mkPreludeMiscIdUnique 228 charPrimLIdKey = mkPreludeMiscIdUnique 229 liftStringIdKey :: Unique liftStringIdKey = mkPreludeMiscIdUnique 230 -- data Pat = ... litPIdKey, varPIdKey, tupPIdKey, unboxedTupPIdKey, conPIdKey, infixPIdKey, tildePIdKey, bangPIdKey, asPIdKey, wildPIdKey, recPIdKey, listPIdKey, sigPIdKey, viewPIdKey :: Unique litPIdKey = mkPreludeMiscIdUnique 240 varPIdKey = mkPreludeMiscIdUnique 241 tupPIdKey = mkPreludeMiscIdUnique 242 unboxedTupPIdKey = mkPreludeMiscIdUnique 243 conPIdKey = mkPreludeMiscIdUnique 244 infixPIdKey = mkPreludeMiscIdUnique 245 tildePIdKey = mkPreludeMiscIdUnique 246 bangPIdKey = mkPreludeMiscIdUnique 247 asPIdKey = mkPreludeMiscIdUnique 248 wildPIdKey = mkPreludeMiscIdUnique 249 recPIdKey = mkPreludeMiscIdUnique 250 listPIdKey = mkPreludeMiscIdUnique 251 sigPIdKey = mkPreludeMiscIdUnique 252 viewPIdKey = mkPreludeMiscIdUnique 253 -- type FieldPat = ... fieldPatIdKey :: Unique fieldPatIdKey = mkPreludeMiscIdUnique 260 -- data Match = ... matchIdKey :: Unique matchIdKey = mkPreludeMiscIdUnique 261 -- data Clause = ... clauseIdKey :: Unique clauseIdKey = mkPreludeMiscIdUnique 262 -- data Exp = ... varEIdKey, conEIdKey, litEIdKey, appEIdKey, infixEIdKey, infixAppIdKey, sectionLIdKey, sectionRIdKey, lamEIdKey, lamCaseEIdKey, tupEIdKey, unboxedTupEIdKey, condEIdKey, multiIfEIdKey, letEIdKey, caseEIdKey, doEIdKey, compEIdKey, fromEIdKey, fromThenEIdKey, fromToEIdKey, fromThenToEIdKey, listEIdKey, sigEIdKey, recConEIdKey, recUpdEIdKey, staticEIdKey :: Unique varEIdKey = mkPreludeMiscIdUnique 270 conEIdKey = mkPreludeMiscIdUnique 271 litEIdKey = mkPreludeMiscIdUnique 272 appEIdKey = mkPreludeMiscIdUnique 273 infixEIdKey = mkPreludeMiscIdUnique 274 infixAppIdKey = mkPreludeMiscIdUnique 275 sectionLIdKey = mkPreludeMiscIdUnique 276 sectionRIdKey = mkPreludeMiscIdUnique 277 lamEIdKey = mkPreludeMiscIdUnique 278 lamCaseEIdKey = mkPreludeMiscIdUnique 279 tupEIdKey = mkPreludeMiscIdUnique 280 unboxedTupEIdKey = mkPreludeMiscIdUnique 281 condEIdKey = mkPreludeMiscIdUnique 282 multiIfEIdKey = mkPreludeMiscIdUnique 283 letEIdKey = mkPreludeMiscIdUnique 284 caseEIdKey = mkPreludeMiscIdUnique 285 doEIdKey = mkPreludeMiscIdUnique 286 compEIdKey = mkPreludeMiscIdUnique 287 fromEIdKey = mkPreludeMiscIdUnique 288 fromThenEIdKey = mkPreludeMiscIdUnique 289 fromToEIdKey = mkPreludeMiscIdUnique 290 fromThenToEIdKey = mkPreludeMiscIdUnique 291 listEIdKey = mkPreludeMiscIdUnique 292 sigEIdKey = mkPreludeMiscIdUnique 293 recConEIdKey = mkPreludeMiscIdUnique 294 recUpdEIdKey = mkPreludeMiscIdUnique 295 staticEIdKey = mkPreludeMiscIdUnique 296 -- type FieldExp = ... fieldExpIdKey :: Unique fieldExpIdKey = mkPreludeMiscIdUnique 310 -- data Body = ... guardedBIdKey, normalBIdKey :: Unique guardedBIdKey = mkPreludeMiscIdUnique 311 normalBIdKey = mkPreludeMiscIdUnique 312 -- data Guard = ... normalGEIdKey, patGEIdKey :: Unique normalGEIdKey = mkPreludeMiscIdUnique 313 patGEIdKey = mkPreludeMiscIdUnique 314 -- data Stmt = ... bindSIdKey, letSIdKey, noBindSIdKey, parSIdKey :: Unique bindSIdKey = mkPreludeMiscIdUnique 320 letSIdKey = mkPreludeMiscIdUnique 321 noBindSIdKey = mkPreludeMiscIdUnique 322 parSIdKey = mkPreludeMiscIdUnique 323 -- data Dec = ... funDIdKey, valDIdKey, dataDIdKey, newtypeDIdKey, tySynDIdKey, classDIdKey, instanceDIdKey, sigDIdKey, forImpDIdKey, pragInlDIdKey, pragSpecDIdKey, pragSpecInlDIdKey, pragSpecInstDIdKey, pragRuleDIdKey, pragAnnDIdKey, defaultSigDIdKey, dataFamilyDIdKey, openTypeFamilyDIdKey, closedTypeFamilyDIdKey, dataInstDIdKey, newtypeInstDIdKey, tySynInstDIdKey, standaloneDerivDIdKey, infixLDIdKey, infixRDIdKey, infixNDIdKey, roleAnnotDIdKey :: Unique funDIdKey = mkPreludeMiscIdUnique 330 valDIdKey = mkPreludeMiscIdUnique 331 dataDIdKey = mkPreludeMiscIdUnique 332 newtypeDIdKey = mkPreludeMiscIdUnique 333 tySynDIdKey = mkPreludeMiscIdUnique 334 classDIdKey = mkPreludeMiscIdUnique 335 instanceDIdKey = mkPreludeMiscIdUnique 336 sigDIdKey = mkPreludeMiscIdUnique 337 forImpDIdKey = mkPreludeMiscIdUnique 338 pragInlDIdKey = mkPreludeMiscIdUnique 339 pragSpecDIdKey = mkPreludeMiscIdUnique 340 pragSpecInlDIdKey = mkPreludeMiscIdUnique 341 pragSpecInstDIdKey = mkPreludeMiscIdUnique 342 pragRuleDIdKey = mkPreludeMiscIdUnique 343 pragAnnDIdKey = mkPreludeMiscIdUnique 344 dataFamilyDIdKey = mkPreludeMiscIdUnique 345 openTypeFamilyDIdKey = mkPreludeMiscIdUnique 346 dataInstDIdKey = mkPreludeMiscIdUnique 347 newtypeInstDIdKey = mkPreludeMiscIdUnique 348 tySynInstDIdKey = mkPreludeMiscIdUnique 349 closedTypeFamilyDIdKey = mkPreludeMiscIdUnique 350 infixLDIdKey = mkPreludeMiscIdUnique 352 infixRDIdKey = mkPreludeMiscIdUnique 353 infixNDIdKey = mkPreludeMiscIdUnique 354 roleAnnotDIdKey = mkPreludeMiscIdUnique 355 standaloneDerivDIdKey = mkPreludeMiscIdUnique 356 defaultSigDIdKey = mkPreludeMiscIdUnique 357 -- type Cxt = ... cxtIdKey :: Unique cxtIdKey = mkPreludeMiscIdUnique 360 -- data Strict = ... isStrictKey, notStrictKey, unpackedKey :: Unique isStrictKey = mkPreludeMiscIdUnique 363 notStrictKey = mkPreludeMiscIdUnique 364 unpackedKey = mkPreludeMiscIdUnique 365 -- data Con = ... normalCIdKey, recCIdKey, infixCIdKey, forallCIdKey :: Unique normalCIdKey = mkPreludeMiscIdUnique 370 recCIdKey = mkPreludeMiscIdUnique 371 infixCIdKey = mkPreludeMiscIdUnique 372 forallCIdKey = mkPreludeMiscIdUnique 373 -- type StrictType = ... strictTKey :: Unique strictTKey = mkPreludeMiscIdUnique 374 -- type VarStrictType = ... varStrictTKey :: Unique varStrictTKey = mkPreludeMiscIdUnique 375 -- data Type = ... forallTIdKey, varTIdKey, conTIdKey, tupleTIdKey, unboxedTupleTIdKey, arrowTIdKey, listTIdKey, appTIdKey, sigTIdKey, equalityTIdKey, litTIdKey, promotedTIdKey, promotedTupleTIdKey, promotedNilTIdKey, promotedConsTIdKey, wildCardTIdKey, namedWildCardTIdKey :: Unique forallTIdKey = mkPreludeMiscIdUnique 380 varTIdKey = mkPreludeMiscIdUnique 381 conTIdKey = mkPreludeMiscIdUnique 382 tupleTIdKey = mkPreludeMiscIdUnique 383 unboxedTupleTIdKey = mkPreludeMiscIdUnique 384 arrowTIdKey = mkPreludeMiscIdUnique 385 listTIdKey = mkPreludeMiscIdUnique 386 appTIdKey = mkPreludeMiscIdUnique 387 sigTIdKey = mkPreludeMiscIdUnique 388 equalityTIdKey = mkPreludeMiscIdUnique 389 litTIdKey = mkPreludeMiscIdUnique 390 promotedTIdKey = mkPreludeMiscIdUnique 391 promotedTupleTIdKey = mkPreludeMiscIdUnique 392 promotedNilTIdKey = mkPreludeMiscIdUnique 393 promotedConsTIdKey = mkPreludeMiscIdUnique 394 wildCardTIdKey = mkPreludeMiscIdUnique 395 namedWildCardTIdKey = mkPreludeMiscIdUnique 396 -- data TyLit = ... numTyLitIdKey, strTyLitIdKey :: Unique numTyLitIdKey = mkPreludeMiscIdUnique 400 strTyLitIdKey = mkPreludeMiscIdUnique 401 -- data TyVarBndr = ... plainTVIdKey, kindedTVIdKey :: Unique plainTVIdKey = mkPreludeMiscIdUnique 402 kindedTVIdKey = mkPreludeMiscIdUnique 403 -- data Role = ... nominalRIdKey, representationalRIdKey, phantomRIdKey, inferRIdKey :: Unique nominalRIdKey = mkPreludeMiscIdUnique 404 representationalRIdKey = mkPreludeMiscIdUnique 405 phantomRIdKey = mkPreludeMiscIdUnique 406 inferRIdKey = mkPreludeMiscIdUnique 407 -- data Kind = ... varKIdKey, conKIdKey, tupleKIdKey, arrowKIdKey, listKIdKey, appKIdKey, starKIdKey, constraintKIdKey :: Unique varKIdKey = mkPreludeMiscIdUnique 408 conKIdKey = mkPreludeMiscIdUnique 409 tupleKIdKey = mkPreludeMiscIdUnique 410 arrowKIdKey = mkPreludeMiscIdUnique 411 listKIdKey = mkPreludeMiscIdUnique 412 appKIdKey = mkPreludeMiscIdUnique 413 starKIdKey = mkPreludeMiscIdUnique 414 constraintKIdKey = mkPreludeMiscIdUnique 415 -- data FamilyResultSig = ... noSigIdKey, kindSigIdKey, tyVarSigIdKey :: Unique noSigIdKey = mkPreludeMiscIdUnique 416 kindSigIdKey = mkPreludeMiscIdUnique 417 tyVarSigIdKey = mkPreludeMiscIdUnique 418 -- data InjectivityAnn = ... injectivityAnnIdKey :: Unique injectivityAnnIdKey = mkPreludeMiscIdUnique 419 -- data Callconv = ... cCallIdKey, stdCallIdKey, cApiCallIdKey, primCallIdKey, javaScriptCallIdKey :: Unique cCallIdKey = mkPreludeMiscIdUnique 420 stdCallIdKey = mkPreludeMiscIdUnique 421 cApiCallIdKey = mkPreludeMiscIdUnique 422 primCallIdKey = mkPreludeMiscIdUnique 423 javaScriptCallIdKey = mkPreludeMiscIdUnique 424 -- data Safety = ... unsafeIdKey, safeIdKey, interruptibleIdKey :: Unique unsafeIdKey = mkPreludeMiscIdUnique 430 safeIdKey = mkPreludeMiscIdUnique 431 interruptibleIdKey = mkPreludeMiscIdUnique 432 -- data Inline = ... noInlineDataConKey, inlineDataConKey, inlinableDataConKey :: Unique noInlineDataConKey = mkPreludeDataConUnique 40 inlineDataConKey = mkPreludeDataConUnique 41 inlinableDataConKey = mkPreludeDataConUnique 42 -- data RuleMatch = ... conLikeDataConKey, funLikeDataConKey :: Unique conLikeDataConKey = mkPreludeDataConUnique 43 funLikeDataConKey = mkPreludeDataConUnique 44 -- data Phases = ... allPhasesDataConKey, fromPhaseDataConKey, beforePhaseDataConKey :: Unique allPhasesDataConKey = mkPreludeDataConUnique 45 fromPhaseDataConKey = mkPreludeDataConUnique 46 beforePhaseDataConKey = mkPreludeDataConUnique 47 -- newtype TExp a = ... tExpDataConKey :: Unique tExpDataConKey = mkPreludeDataConUnique 48 -- data FunDep = ... funDepIdKey :: Unique funDepIdKey = mkPreludeMiscIdUnique 440 -- data FamFlavour = ... typeFamIdKey, dataFamIdKey :: Unique typeFamIdKey = mkPreludeMiscIdUnique 450 dataFamIdKey = mkPreludeMiscIdUnique 451 -- data TySynEqn = ... tySynEqnIdKey :: Unique tySynEqnIdKey = mkPreludeMiscIdUnique 460 -- quasiquoting quoteExpKey, quotePatKey, quoteDecKey, quoteTypeKey :: Unique quoteExpKey = mkPreludeMiscIdUnique 470 quotePatKey = mkPreludeMiscIdUnique 471 quoteDecKey = mkPreludeMiscIdUnique 472 quoteTypeKey = mkPreludeMiscIdUnique 473 -- data RuleBndr = ... ruleVarIdKey, typedRuleVarIdKey :: Unique ruleVarIdKey = mkPreludeMiscIdUnique 480 typedRuleVarIdKey = mkPreludeMiscIdUnique 481 -- data AnnTarget = ... valueAnnotationIdKey, typeAnnotationIdKey, moduleAnnotationIdKey :: Unique valueAnnotationIdKey = mkPreludeMiscIdUnique 490 typeAnnotationIdKey = mkPreludeMiscIdUnique 491 moduleAnnotationIdKey = mkPreludeMiscIdUnique 492 {- ************************************************************************ * * RdrNames * * ************************************************************************ -} lift_RDR, mkNameG_dRDR, mkNameG_vRDR :: RdrName lift_RDR = nameRdrName liftName mkNameG_dRDR = nameRdrName mkNameG_dName mkNameG_vRDR = nameRdrName mkNameG_vName -- data Exp = ... conE_RDR, litE_RDR, appE_RDR, infixApp_RDR :: RdrName conE_RDR = nameRdrName conEName litE_RDR = nameRdrName litEName appE_RDR = nameRdrName appEName infixApp_RDR = nameRdrName infixAppName -- data Lit = ... stringL_RDR, intPrimL_RDR, wordPrimL_RDR, floatPrimL_RDR, doublePrimL_RDR, stringPrimL_RDR, charPrimL_RDR :: RdrName stringL_RDR = nameRdrName stringLName intPrimL_RDR = nameRdrName intPrimLName wordPrimL_RDR = nameRdrName wordPrimLName floatPrimL_RDR = nameRdrName floatPrimLName doublePrimL_RDR = nameRdrName doublePrimLName stringPrimL_RDR = nameRdrName stringPrimLName charPrimL_RDR = nameRdrName charPrimLName
ml9951/ghc
compiler/prelude/THNames.hs
Haskell
bsd-3-clause
39,682
{-# LANGUAGE MagicHash #-} ----------------------------------------------------------------------------- -- -- GHCi Interactive debugging commands -- -- Pepe Iborra (supported by Google SoC) 2006 -- -- ToDo: lots of violation of layering here. This module should -- decide whether it is above the GHC API (import GHC and nothing -- else) or below it. -- ----------------------------------------------------------------------------- module ETA.Interactive.Debugger where --(pprintClosureCommand, showTerm, pprTypeAndContents) where -- import ETA.Interactive.Linker -- import ETA.Interactive.RtClosureInspect -- -- import ETA.Main.GhcMonad -- import ETA.Main.HscTypes -- import ETA.BasicTypes.Id -- import ETA.BasicTypes.Name -- import ETA.BasicTypes.Var hiding ( varName ) -- import ETA.BasicTypes.VarSet -- import ETA.BasicTypes.UniqSupply -- import ETA.Types.Type -- import ETA.Types.Kind -- import ETA.Main.GHC -- import qualified ETA.Main.GHC as GHC -- import ETA.Utils.Outputable -- import ETA.Main.PprTyThing -- import ETA.Main.ErrUtils -- import ETA.Utils.MonadUtils -- import ETA.Main.DynFlags -- import ETA.Utils.Exception -- -- import Control.Monad -- import Data.List -- import Data.Maybe -- import Data.IORef -- -- import GHC.Exts -- ------------------------------------- -- -- | The :print & friends commands -- ------------------------------------- -- pprintClosureCommand :: GhcMonad m => Bool -> Bool -> String -> m () -- pprintClosureCommand bindThings force str = do -- tythings <- (catMaybes . concat) `liftM` -- mapM (\w -> GHC.parseName w >>= -- mapM GHC.lookupName) -- (words str) -- let ids = [id | AnId id <- tythings] -- -- Obtain the terms and the recovered type information -- (subst, terms) <- mapAccumLM go emptyTvSubst ids -- -- Apply the substitutions obtained after recovering the types -- modifySession $ \hsc_env -> -- hsc_env{hsc_IC = substInteractiveContext (hsc_IC hsc_env) subst} -- -- Finally, print the Terms -- unqual <- GHC.getPrintUnqual -- docterms <- mapM showTerm terms -- dflags <- getDynFlags -- liftIO $ (printOutputForUser dflags unqual . vcat) -- (zipWith (\id docterm -> ppr id <+> char '=' <+> docterm) -- ids -- docterms) -- where -- -- Do the obtainTerm--bindSuspensions-computeSubstitution dance -- go :: GhcMonad m => TvSubst -> Id -> m (TvSubst, Term) -- go subst id = do -- let id' = id `setIdType` substTy subst (idType id) -- term_ <- GHC.obtainTermFromId maxBound force id' -- term <- tidyTermTyVars term_ -- term' <- if bindThings && -- False == isUnliftedTypeKind (termType term) -- then bindSuspensions term -- else return term -- -- Before leaving, we compare the type obtained to see if it's more specific -- -- Then, we extract a substitution, -- -- mapping the old tyvars to the reconstructed types. -- let reconstructed_type = termType term -- hsc_env <- getSession -- case (improveRTTIType hsc_env (idType id) (reconstructed_type)) of -- Nothing -> return (subst, term') -- Just subst' -> do { traceOptIf Opt_D_dump_rtti -- (fsep $ [text "RTTI Improvement for", ppr id, -- text "is the substitution:" , ppr subst']) -- ; return (subst `unionTvSubst` subst', term')} -- tidyTermTyVars :: GhcMonad m => Term -> m Term -- tidyTermTyVars t = -- withSession $ \hsc_env -> do -- let env_tvs = tyThingsTyVars $ ic_tythings $ hsc_IC hsc_env -- my_tvs = termTyVars t -- tvs = env_tvs `minusVarSet` my_tvs -- tyvarOccName = nameOccName . tyVarName -- tidyEnv = (initTidyOccEnv (map tyvarOccName (varSetElems tvs)) -- , env_tvs `intersectVarSet` my_tvs) -- return$ mapTermType (snd . tidyOpenType tidyEnv) t -- -- | Give names, and bind in the interactive environment, to all the suspensions -- -- included (inductively) in a term -- bindSuspensions :: GhcMonad m => Term -> m Term -- bindSuspensions t = do -- hsc_env <- getSession -- inScope <- GHC.getBindings -- let ictxt = hsc_IC hsc_env -- prefix = "_t" -- alreadyUsedNames = map (occNameString . nameOccName . getName) inScope -- availNames = map ((prefix++) . show) [(1::Int)..] \\ alreadyUsedNames -- availNames_var <- liftIO $ newIORef availNames -- (t', stuff) <- liftIO $ foldTerm (nameSuspensionsAndGetInfos availNames_var) t -- let (names, tys, hvals) = unzip3 stuff -- let ids = [ mkVanillaGlobal name ty -- | (name,ty) <- zip names tys] -- new_ic = extendInteractiveContextWithIds ictxt ids -- liftIO $ extendLinkEnv (zip names hvals) -- modifySession $ \_ -> hsc_env {hsc_IC = new_ic } -- return t' -- where -- -- Processing suspensions. Give names and recopilate info -- nameSuspensionsAndGetInfos :: IORef [String] -> -- TermFold (IO (Term, [(Name,Type,HValue)])) -- nameSuspensionsAndGetInfos freeNames = TermFold -- { -- fSuspension = doSuspension freeNames -- , fTerm = \ty dc v tt -> do -- tt' <- sequence tt -- let (terms,names) = unzip tt' -- return (Term ty dc v terms, concat names) -- , fPrim = \ty n ->return (Prim ty n,[]) -- , fNewtypeWrap = -- \ty dc t -> do -- (term, names) <- t -- return (NewtypeWrap ty dc term, names) -- , fRefWrap = \ty t -> do -- (term, names) <- t -- return (RefWrap ty term, names) -- } -- doSuspension freeNames ct ty hval _name = do -- name <- atomicModifyIORef freeNames (\x->(tail x, head x)) -- n <- newGrimName name -- return (Suspension ct ty hval (Just n), [(n,ty,hval)]) -- -- A custom Term printer to enable the use of Show instances -- showTerm :: GhcMonad m => Term -> m SDoc -- showTerm term = do -- dflags <- GHC.getSessionDynFlags -- if gopt Opt_PrintEvldWithShow dflags -- then cPprTerm (liftM2 (++) (\_y->[cPprShowable]) cPprTermBase) term -- else cPprTerm cPprTermBase term -- where -- cPprShowable prec t@Term{ty=ty, val=val} = -- if not (isFullyEvaluatedTerm t) -- then return Nothing -- else do -- hsc_env <- getSession -- dflags <- GHC.getSessionDynFlags -- do -- (new_env, bname) <- bindToFreshName hsc_env ty "showme" -- setSession new_env -- -- XXX: this tries to disable logging of errors -- -- does this still do what it is intended to do -- -- with the changed error handling and logging? -- let noop_log _ _ _ _ _ = return () -- expr = "show " ++ showPpr dflags bname -- _ <- GHC.setSessionDynFlags dflags{log_action=noop_log} -- txt_ <- withExtendedLinkEnv [(bname, val)] -- (GHC.compileExpr expr) -- let myprec = 10 -- application precedence. TODO Infix constructors -- let txt = unsafeCoerce# txt_ :: [a] -- if not (null txt) then -- return $ Just $ cparen (prec >= myprec && needsParens txt) -- (text txt) -- else return Nothing -- `gfinally` do -- setSession hsc_env -- GHC.setSessionDynFlags dflags -- cPprShowable prec NewtypeWrap{ty=new_ty,wrapped_term=t} = -- cPprShowable prec t{ty=new_ty} -- cPprShowable _ _ = return Nothing -- needsParens ('"':_) = False -- some simple heuristics to see whether parens -- -- are redundant in an arbitrary Show output -- needsParens ('(':_) = False -- needsParens txt = ' ' `elem` txt -- bindToFreshName hsc_env ty userName = do -- name <- newGrimName userName -- let id = mkVanillaGlobal name ty -- new_ic = extendInteractiveContextWithIds (hsc_IC hsc_env) [id] -- return (hsc_env {hsc_IC = new_ic }, name) -- -- Create new uniques and give them sequentially numbered names -- newGrimName :: MonadIO m => String -> m Name -- newGrimName userName = do -- us <- liftIO $ mkSplitUniqSupply 'b' -- let unique = uniqFromSupply us -- occname = mkOccName varName userName -- name = mkInternalName unique occname noSrcSpan -- return name -- pprTypeAndContents :: GhcMonad m => Id -> m SDoc -- pprTypeAndContents id = do -- dflags <- GHC.getSessionDynFlags -- let pcontents = gopt Opt_PrintBindContents dflags -- pprdId = (PprTyThing.pprTyThing . AnId) id -- if pcontents -- then do -- let depthBound = 100 -- -- If the value is an exception, make sure we catch it and -- -- show the exception, rather than propagating the exception out. -- e_term <- gtry $ GHC.obtainTermFromId depthBound False id -- docs_term <- case e_term of -- Right term -> showTerm term -- Left exn -> return (text "*** Exception:" <+> -- text (show (exn :: SomeException))) -- return $ pprdId <+> equals <+> docs_term -- else return pprdId -- -------------------------------------------------------------- -- -- Utils -- traceOptIf :: GhcMonad m => DumpFlag -> SDoc -> m () -- traceOptIf flag doc = do -- dflags <- GHC.getSessionDynFlags -- when (dopt flag dflags) $ liftIO $ printInfoForUser dflags alwaysQualify doc
pparkkin/eta
compiler/ETA/Interactive/Debugger.hs
Haskell
bsd-3-clause
10,188
{-# LANGUAGE BangPatterns, GeneralizedNewtypeDeriving, StandaloneDeriving #-} import Prelude hiding (mapM) import Options.Applicative import Data.Monoid ((<>)) import Control.Monad.Trans.Class import Data.Vector (Vector) import qualified Data.Vector.Unboxed as VU import qualified Data.Vector.Generic as V import Statistics.Sample (mean) import Data.Traversable (mapM) import qualified Data.Set as S import Data.Set (Set) import qualified Data.Map as M import ReadData import SerializeText import qualified RunSampler as Sampler import BayesStack.DirMulti import BayesStack.Models.Topic.CitationInfluence import BayesStack.UniqueKey import qualified Data.Text as T import qualified Data.Text.IO as TIO import System.FilePath.Posix ((</>)) import Data.Binary import qualified Data.ByteString as BS import Text.Printf import Data.Random import System.Random.MWC data RunOpts = RunOpts { arcsFile :: FilePath , nodesFile :: FilePath , stopwords :: Maybe FilePath , nTopics :: Int , samplerOpts :: Sampler.SamplerOpts , hyperParams :: HyperParams , noClean :: Bool } runOpts = RunOpts <$> strOption ( long "arcs" <> short 'a' <> metavar "FILE" <> help "File containing arcs" ) <*> strOption ( long "nodes" <> short 'n' <> metavar "FILE" <> help "File containing nodes' items" ) <*> nullOption ( long "stopwords" <> short 's' <> metavar "FILE" <> reader (pure . Just) <> value Nothing <> help "Stop words list" ) <*> option ( long "topics" <> short 't' <> metavar "N" <> value 20 <> help "Number of topics" ) <*> Sampler.samplerOpts <*> hyperOpts <*> flag False True ( long "no-clean" <> short 'c' <> help "Don't attempt to sanitize input data. Among other things, nodes without friends will not be discarded" ) hyperOpts = HyperParams <$> option ( long "prior-psi" <> value 1 <> help "Dirichlet parameter for prior on psi" ) <*> option ( long "prior-lambda" <> value 0.1 <> help "Dirichlet parameter for prior on lambda" ) <*> option ( long "prior-phi" <> value 0.01 <> help "Dirichlet parameter for prior on phi" ) <*> option ( long "prior-omega" <> value 0.01 <> help "Dirichlet parameter for prior on omega" ) <*> option ( long "prior-gamma-shared" <> value 0.9 <> help "Beta parameter for prior on gamma (shared)" ) <*> option ( long "prior-gamma-own" <> value 0.1 <> help "Beta parameter for prior on gamma (own)" ) mapMKeys :: (Ord k, Ord k', Monad m, Applicative m) => (a -> m a') -> (k -> m k') -> M.Map k a -> m (M.Map k' a') mapMKeys f g x = M.fromList <$> (mapM (\(k,v)->(,) <$> g k <*> f v) $ M.assocs x) termsToItems :: M.Map NodeName [Term] -> Set (NodeName, NodeName) -> ( (M.Map Node [Item], Set (Node, Node)) , (M.Map Item Term, M.Map Node NodeName)) termsToItems nodes arcs = let ((d', nodeMap), itemMap) = runUniqueKey' [Item i | i <- [0..]] $ runUniqueKeyT' [Node i | i <- [0..]] $ do a <- mapMKeys (mapM (lift . getUniqueKey)) getUniqueKey nodes b <- S.fromList <$> mapM (\(x,y)->(,) <$> getUniqueKey x <*> getUniqueKey y) (S.toList arcs) return (a,b) in (d', (itemMap, nodeMap)) makeNetData :: HyperParams -> M.Map Node [Item] -> Set Arc -> Int -> NetData makeNetData hp nodeItems arcs nTopics = netData hp arcs nodeItems' topics where topics = S.fromList [Topic i | i <- [1..nTopics]] nodeItems' = M.fromList $ zip [NodeItem i | i <- [0..]] $ do (n,items) <- M.assocs nodeItems item <- items return (n, item) opts = info runOpts ( fullDesc <> progDesc "Learn citation influence model" <> header "run-ci - learn citation influence model" ) edgesToArcs :: Set (Node, Node) -> Set Arc edgesToArcs = S.map (\(a,b)->Arc (Citing a) (Cited b)) instance Sampler.SamplerModel MState where estimateHypers = id -- reestimate -- FIXME modelLikelihood = modelLikelihood summarizeHypers ms = "" -- FIXME main = do args <- execParser opts stopWords <- case stopwords args of Just f -> S.fromList . T.words <$> TIO.readFile f Nothing -> return S.empty printf "Read %d stopwords\n" (S.size stopWords) ((nodeItems, a), (itemMap, nodeMap)) <- termsToItems <$> readNodeItems stopWords (nodesFile args) <*> readEdges (arcsFile args) let arcs = edgesToArcs a Sampler.createSweeps $ samplerOpts args let sweepsDir = Sampler.sweepsDir $ samplerOpts args encodeFile (sweepsDir </> "item-map") itemMap encodeFile (sweepsDir </> "node-map") nodeMap let termCounts = V.fromListN (M.size nodeItems) $ map length $ M.elems nodeItems :: Vector Int printf "Read %d arcs, %d nodes, %d node-items\n" (S.size arcs) (M.size nodeItems) (V.sum termCounts) printf "Mean items per node: %1.2f\n" (mean $ V.map realToFrac termCounts) withSystemRandom $ \mwc->do let nd = (if noClean args then id else cleanNetData) $ makeNetData (hyperParams args) nodeItems arcs (nTopics args) mapM_ putStrLn $ verifyNetData (\n->maybe (show n) show $ M.lookup n nodeMap) nd let nCitingNodes = VU.fromList $ M.elems $ M.unionsWith (+) $ map (\a->M.singleton (citingNode a) 1) $ S.toList $ dArcs nd nCitedNodes = VU.fromList $ M.elems $ M.unionsWith (+) $ map (\a->M.singleton (citedNode a) 1) $ S.toList $ dArcs nd printf "After cleaning: %d cited nodes, %d citing nodes, %d arcs, %d node-items\n" (S.size $ S.map citedNode $ dArcs nd) (S.size $ S.map citingNode $ dArcs nd) (S.size $ dArcs nd) (M.size $ dNodeItems nd) printf "In degree: mean=%3.1f, maximum=%3.1f\n" (mean nCitedNodes) (V.maximum nCitedNodes) printf "Out degree: mean=%3.1f, maximum=%3.1f\n" (mean nCitingNodes) (V.maximum nCitingNodes) encodeFile (sweepsDir </> "data") nd mInit <- runRVar (randomInitialize nd) mwc let m = model nd mInit Sampler.runSampler (samplerOpts args) m (updateUnits nd) return ()
beni55/bayes-stack
network-topic-models/RunCI.hs
Haskell
bsd-3-clause
7,455
module Boo where {-@ incr :: Int -> Bool @-} incr :: Int -> Int incr x = x + 1
ssaavedra/liquidhaskell
tests/crash/errmsg-mismatch.hs
Haskell
bsd-3-clause
81
-- | -- This module contains the Relapse type expression. module Data.Katydid.Relapse.Exprs.Type ( mkTypeExpr , typeExpr ) where import Data.Katydid.Relapse.Expr -- | -- mkTypeExpr is used by the parser to create a type expression for the specific input type. mkTypeExpr :: [AnyExpr] -> Either String AnyExpr mkTypeExpr es = do e <- assertArgs1 "type" es case e of (AnyExpr _ (BoolFunc _)) -> mkBoolExpr . typeExpr <$> assertBool e (AnyExpr _ (IntFunc _)) -> mkBoolExpr . typeExpr <$> assertInt e (AnyExpr _ (UintFunc _)) -> mkBoolExpr . typeExpr <$> assertUint e (AnyExpr _ (DoubleFunc _)) -> mkBoolExpr . typeExpr <$> assertDouble e (AnyExpr _ (StringFunc _)) -> mkBoolExpr . typeExpr <$> assertString e (AnyExpr _ (BytesFunc _)) -> mkBoolExpr . typeExpr <$> assertBytes e -- | -- typeExpr creates an expression that returns true if the containing expression does not return an error. -- For example: `(typeExpr varBoolExpr)` will ony return true is the field value is a bool. typeExpr :: Expr a -> Expr Bool typeExpr e = Expr { desc = mkDesc "type" [desc e] , eval = \v -> case eval e v of (Left _) -> return False (Right _) -> return True }
katydid/haslapse
src/Data/Katydid/Relapse/Exprs/Type.hs
Haskell
bsd-3-clause
1,218
{-# LANGUAGE TemplateHaskell, Rank2Types, CPP #-} #ifndef NO_SAFE_HASKELL {-# LANGUAGE Trustworthy #-} #endif -- | Test all properties in the current module, using Template Haskell. -- You need to have a @{-\# LANGUAGE TemplateHaskell \#-}@ pragma in -- your module for any of these to work. module Test.QuickCheck.All( -- ** Testing all properties in a module quickCheckAll, verboseCheckAll, forAllProperties, -- ** Testing polymorphic properties polyQuickCheck, polyVerboseCheck, monomorphic) where import Language.Haskell.TH import Test.QuickCheck.Property hiding (Result) import Test.QuickCheck.Test import Data.Char import Data.List import Control.Monad import qualified System.IO as S -- | Test a polymorphic property, defaulting all type variables to 'Integer'. -- -- Invoke as @$('polyQuickCheck' 'prop)@, where @prop@ is a property. -- Note that just evaluating @'quickCheck' prop@ in GHCi will seem to -- work, but will silently default all type variables to @()@! -- -- @$('polyQuickCheck' \'prop)@ means the same as -- @'quickCheck' $('monomorphic' \'prop)@. -- If you want to supply custom arguments to 'polyQuickCheck', -- you will have to combine 'quickCheckWith' and 'monomorphic' yourself. -- -- If you want to use 'polyQuickCheck' in the same file where you defined the -- property, the same scoping problems pop up as in 'quickCheckAll': -- see the note there about @return []@. polyQuickCheck :: Name -> ExpQ polyQuickCheck x = [| quickCheck $(monomorphic x) |] -- | Test a polymorphic property, defaulting all type variables to 'Integer'. -- This is just a convenience function that combines 'verboseCheck' and 'monomorphic'. -- -- If you want to use 'polyVerboseCheck' in the same file where you defined the -- property, the same scoping problems pop up as in 'quickCheckAll': -- see the note there about @return []@. polyVerboseCheck :: Name -> ExpQ polyVerboseCheck x = [| verboseCheck $(monomorphic x) |] type Error = forall a. String -> a -- | Monomorphise an arbitrary property by defaulting all type variables to 'Integer'. -- -- For example, if @f@ has type @'Ord' a => [a] -> [a]@ -- then @$('monomorphic' 'f)@ has type @['Integer'] -> ['Integer']@. -- -- If you want to use 'monomorphic' in the same file where you defined the -- property, the same scoping problems pop up as in 'quickCheckAll': -- see the note there about @return []@. monomorphic :: Name -> ExpQ monomorphic t = do ty0 <- fmap infoType (reify t) let err msg = error $ msg ++ ": " ++ pprint ty0 (polys, ctx, ty) <- deconstructType err ty0 case polys of [] -> return (VarE t) _ -> do integer <- [t| Integer |] ty' <- monomorphiseType err integer ty return (SigE (VarE t) ty') infoType :: Info -> Type infoType (ClassOpI _ ty _ _) = ty infoType (DataConI _ ty _ _) = ty infoType (VarI _ ty _ _) = ty deconstructType :: Error -> Type -> Q ([Name], Cxt, Type) deconstructType err ty0@(ForallT xs ctx ty) = do let plain (PlainTV _) = True #ifndef MIN_VERSION_template_haskell plain (KindedTV _ StarT) = True #else #if MIN_VERSION_template_haskell(2,8,0) plain (KindedTV _ StarT) = True #else plain (KindedTV _ StarK) = True #endif #endif plain _ = False unless (all plain xs) $ err "Higher-kinded type variables in type" return (map (\(PlainTV x) -> x) xs, ctx, ty) deconstructType _ ty = return ([], [], ty) monomorphiseType :: Error -> Type -> Type -> TypeQ monomorphiseType err mono ty@(VarT n) = return mono monomorphiseType err mono (AppT t1 t2) = liftM2 AppT (monomorphiseType err mono t1) (monomorphiseType err mono t2) monomorphiseType err mono ty@(ForallT _ _ _) = err $ "Higher-ranked type" monomorphiseType err mono ty = return ty -- | Test all properties in the current module, using a custom -- 'quickCheck' function. The same caveats as with 'quickCheckAll' -- apply. -- -- @$'forAllProperties'@ has type @('Property' -> 'IO' 'Result') -> 'IO' 'Bool'@. -- An example invocation is @$'forAllProperties' 'quickCheckResult'@, -- which does the same thing as @$'quickCheckAll'@. -- -- 'forAllProperties' has the same issue with scoping as 'quickCheckAll': -- see the note there about @return []@. forAllProperties :: Q Exp -- :: (Property -> IO Result) -> IO Bool forAllProperties = do Loc { loc_filename = filename } <- location when (filename == "<interactive>") $ error "don't run this interactively" ls <- runIO (fmap lines (readUTF8File filename)) let prefixes = map (takeWhile (\c -> isAlphaNum c || c == '_' || c == '\'') . dropWhile (\c -> isSpace c || c == '>')) ls idents = nubBy (\x y -> snd x == snd y) (filter (("prop_" `isPrefixOf`) . snd) (zip [1..] prefixes)) #if __GLASGOW_HASKELL__ > 705 warning x = reportWarning ("Name " ++ x ++ " found in source file but was not in scope") #else warning x = report False ("Name " ++ x ++ " found in source file but was not in scope") #endif quickCheckOne :: (Int, String) -> Q [Exp] quickCheckOne (l, x) = do exists <- (warning x >> return False) `recover` (reify (mkName x) >> return True) if exists then sequence [ [| ($(stringE $ x ++ " from " ++ filename ++ ":" ++ show l), property $(monomorphic (mkName x))) |] ] else return [] [| runQuickCheckAll $(fmap (ListE . concat) (mapM quickCheckOne idents)) |] readUTF8File name = S.openFile name S.ReadMode >>= set_utf8_io_enc >>= S.hGetContents -- Deal with UTF-8 input and output. set_utf8_io_enc :: S.Handle -> IO S.Handle #if __GLASGOW_HASKELL__ > 611 -- possibly if MIN_VERSION_base(4,2,0) set_utf8_io_enc h = do S.hSetEncoding h S.utf8; return h #else set_utf8_io_enc h = return h #endif -- | Test all properties in the current module. -- The name of the property must begin with @prop_@. -- Polymorphic properties will be defaulted to 'Integer'. -- Returns 'True' if all tests succeeded, 'False' otherwise. -- -- To use 'quickCheckAll', add a definition to your module along -- the lines of -- -- > return [] -- > runTests = $quickCheckAll -- -- and then execute @runTests@. -- -- Note: the bizarre @return []@ in the example above is needed on -- GHC 7.8; without it, 'quickCheckAll' will not be able to find -- any of the properties. For the curious, the @return []@ is a -- Template Haskell splice that makes GHC insert the empty list -- of declarations at that point in the program; GHC typechecks -- everything before the @return []@ before it starts on the rest -- of the module, which means that the later call to 'quickCheckAll' -- can see everything that was defined before the @return []@. Yikes! quickCheckAll :: Q Exp quickCheckAll = [| $(forAllProperties) quickCheckResult |] -- | Test all properties in the current module. -- This is just a convenience function that combines 'quickCheckAll' and 'verbose'. -- -- 'verboseCheckAll' has the same issue with scoping as 'quickCheckAll': -- see the note there about @return []@. verboseCheckAll :: Q Exp verboseCheckAll = [| $(forAllProperties) verboseCheckResult |] runQuickCheckAll :: [(String, Property)] -> (Property -> IO Result) -> IO Bool runQuickCheckAll ps qc = fmap and . forM ps $ \(xs, p) -> do putStrLn $ "=== " ++ xs ++ " ===" r <- qc p putStrLn "" return $ case r of Success { } -> True Failure { } -> False NoExpectedFailure { } -> False GaveUp { } -> False InsufficientCoverage { } -> False
soenkehahn/quickcheck
Test/QuickCheck/All.hs
Haskell
bsd-3-clause
7,492
{-# LANGUAGE CPP #-} import Data.Function import System.Environment import System.FilePath import Test.Haddock import Test.Haddock.Utils checkConfig :: CheckConfig String checkConfig = CheckConfig { ccfgRead = Just , ccfgClean = \_ -> id , ccfgDump = id , ccfgEqual = (==) `on` crlfToLf } dirConfig :: DirConfig dirConfig = defaultDirConfig $ takeDirectory __FILE__ main :: IO () main = do cfg <- parseArgs checkConfig dirConfig =<< getArgs runAndCheck $ cfg { cfgHaddockArgs = cfgHaddockArgs cfg ++ ["--latex"] }
Fuuzetsu/haddock
latex-test/Main.hs
Haskell
bsd-2-clause
567
{-| ConstantUtils contains the helper functions for constants This module cannot be merged with 'Ganeti.Utils' because it would create a circular dependency if imported, for example, from 'Ganeti.Constants'. -} {- Copyright (C) 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.ConstantUtils where import Prelude () import Ganeti.Prelude import Data.Char (ord) import Data.Set (Set) import qualified Data.Set as Set (difference, fromList, toList, union) import Ganeti.PyValue -- | 'PythonChar' wraps a Python 'char' newtype PythonChar = PythonChar { unPythonChar :: Char } deriving (Show) instance PyValue PythonChar where showValue c = "chr(" ++ show (ord (unPythonChar c)) ++ ")" -- | 'PythonNone' wraps Python 'None' data PythonNone = PythonNone instance PyValue PythonNone where showValue _ = "None" -- | FrozenSet wraps a Haskell 'Set' -- -- See 'PyValue' instance for 'FrozenSet'. newtype FrozenSet a = FrozenSet { unFrozenSet :: Set a } deriving (Eq, Ord, Show) instance (Ord a) => Monoid (FrozenSet a) where mempty = FrozenSet mempty mappend (FrozenSet s) (FrozenSet t) = FrozenSet (mappend s t) -- | Converts a Haskell 'Set' into a Python 'frozenset' -- -- This instance was supposed to be for 'Set' instead of 'FrozenSet'. -- However, 'ghc-6.12.1' seems to be crashing with 'segmentation -- fault' due to the presence of more than one instance of 'Set', -- namely, this one and the one in 'Ganeti.OpCodes'. For this reason, -- we wrap 'Set' into 'FrozenSet'. instance PyValue a => PyValue (FrozenSet a) where showValue s = "frozenset(" ++ showValue (Set.toList (unFrozenSet s)) ++ ")" mkSet :: Ord a => [a] -> FrozenSet a mkSet = FrozenSet . Set.fromList toList :: FrozenSet a -> [a] toList = Set.toList . unFrozenSet union :: Ord a => FrozenSet a -> FrozenSet a -> FrozenSet a union x y = FrozenSet (unFrozenSet x `Set.union` unFrozenSet y) difference :: Ord a => FrozenSet a -> FrozenSet a -> FrozenSet a difference x y = FrozenSet (unFrozenSet x `Set.difference` unFrozenSet y) -- | 'Protocol' represents the protocols used by the daemons data Protocol = Tcp | Udp deriving (Show) -- | 'PyValue' instance of 'Protocol' -- -- This instance is used by the Haskell to Python constants instance PyValue Protocol where showValue Tcp = "\"tcp\"" showValue Udp = "\"udp\"" -- | Failure exit code -- -- These are defined here and not in 'Ganeti.Constants' together with -- the other exit codes in order to avoid a circular dependency -- between 'Ganeti.Constants' and 'Ganeti.Runtime' exitFailure :: Int exitFailure = 1 -- | Console device -- -- This is defined here and not in 'Ganeti.Constants' order to avoid a -- circular dependency between 'Ganeti.Constants' and 'Ganeti.Logging' devConsole :: String devConsole = "/dev/console" -- | Random uuid generator -- -- This is defined here and not in 'Ganeti.Constants' order to avoid a -- circular dependendy between 'Ganeti.Constants' and 'Ganeti.Types' randomUuidFile :: String randomUuidFile = "/proc/sys/kernel/random/uuid" -- * Priority levels -- -- This is defined here and not in 'Ganeti.Types' in order to avoid a -- GHC stage restriction and because there is no suitable 'declareADT' -- variant that handles integer values directly. priorityLow :: Int priorityLow = 10 priorityNormal :: Int priorityNormal = 0 priorityHigh :: Int priorityHigh = -10 -- | Calculates int version number from major, minor and revision -- numbers. buildVersion :: Int -> Int -> Int -> Int buildVersion major minor revision = 1000000 * major + 10000 * minor + 1 * revision -- | Confd protocol version -- -- This is defined here in order to avoid a circular dependency -- between 'Ganeti.Confd.Types' and 'Ganeti.Constants'. confdProtocolVersion :: Int confdProtocolVersion = 1 -- * Confd request query fields -- -- These are defined here and not in 'Ganeti.Types' due to GHC stage -- restrictions concerning Template Haskell. They are also not -- defined in 'Ganeti.Constants' in order to avoid a circular -- dependency between that module and 'Ganeti.Types'. confdReqqLink :: String confdReqqLink = "0" confdReqqIp :: String confdReqqIp = "1" confdReqqIplist :: String confdReqqIplist = "2" confdReqqFields :: String confdReqqFields = "3" -- * ISpec ispecMemSize :: String ispecMemSize = "memory-size" ispecCpuCount :: String ispecCpuCount = "cpu-count" ispecDiskCount :: String ispecDiskCount = "disk-count" ispecDiskSize :: String ispecDiskSize = "disk-size" ispecNicCount :: String ispecNicCount = "nic-count" ispecSpindleUse :: String ispecSpindleUse = "spindle-use" ispecsMinmax :: String ispecsMinmax = "minmax" ispecsStd :: String ispecsStd = "std" ipolicyDts :: String ipolicyDts = "disk-templates" ipolicyVcpuRatio :: String ipolicyVcpuRatio = "vcpu-ratio" ipolicySpindleRatio :: String ipolicySpindleRatio = "spindle-ratio" ipolicyMemoryRatio :: String ipolicyMemoryRatio = "memory-ratio" ipolicyDefaultsVcpuRatio :: Double ipolicyDefaultsVcpuRatio = 4.0 ipolicyDefaultsSpindleRatio :: Double ipolicyDefaultsSpindleRatio = 32.0 ipolicyDefaultsMemoryRatio :: Double ipolicyDefaultsMemoryRatio = 1.0 -- * Hypervisor state default parameters hvstDefaultCpuNode :: Int hvstDefaultCpuNode = 1 hvstDefaultCpuTotal :: Int hvstDefaultCpuTotal = 1 hvstDefaultMemoryHv :: Int hvstDefaultMemoryHv = 1024 hvstDefaultMemoryTotal :: Int hvstDefaultMemoryTotal = 1024 hvstDefaultMemoryNode :: Int hvstDefaultMemoryNode = 4096
andir/ganeti
src/Ganeti/ConstantUtils.hs
Haskell
bsd-2-clause
6,686
module Models.NRS where import BasicPrelude ( Show ) import Data.Aeson ( ToJSON ) import Data.Time ( Day ) import GHC.Generics ( Generic ) import Models.Tree import Year data NRS = NRS { statuteTree :: Tree, nominalDate :: Year, -- The "date" of this edition dateAccessed :: Day } deriving (Generic, Show) instance ToJSON NRS
dogweather/nevada-revised-statutes-parser
src/Models/NRS.hs
Haskell
bsd-3-clause
489
module WhereBind where main :: Fay () main = let x = 10 :: Int in print $ x + y where y = 20
fpco/fay
tests/whereBind.hs
Haskell
bsd-3-clause
104
{-# LANGUAGE UnboxedTuples, CPP #-} module State where #if __GLASGOW_HASKELL__ < 709 import Control.Applicative #endif newtype State s a = State { runState' :: s -> (# a, s #) } instance Functor (State s) where fmap f m = State $ \s -> case runState' m s of (# r, s' #) -> (# f r, s' #) instance Applicative (State s) where pure x = State $ \s -> (# x, s #) m <*> n = State $ \s -> case runState' m s of (# f, s' #) -> case runState' n s' of (# x, s'' #) -> (# f x, s'' #) instance Monad (State s) where return = pure m >>= n = State $ \s -> case runState' m s of (# r, s' #) -> runState' (n r) s' get :: State s s get = State $ \s -> (# s, s #) gets :: (s -> a) -> State s a gets f = State $ \s -> (# f s, s #) put :: s -> State s () put s' = State $ \_ -> (# (), s' #) modify :: (s -> s) -> State s () modify f = State $ \s -> (# (), f s #) evalState :: State s a -> s -> a evalState s i = case runState' s i of (# a, _ #) -> a execState :: State s a -> s -> s execState s i = case runState' s i of (# _, s' #) -> s' runState :: State s a -> s -> (a, s) runState s i = case runState' s i of (# a, s' #) -> (a, s')
siddhanathan/ghc
compiler/utils/State.hs
Haskell
bsd-3-clause
1,332
{-# LANGUAGE Trustworthy #-} -- ---------------------------------------------------------------------------- -- | This module provides scalable event notification for file -- descriptors and timeouts. -- -- This module should be considered GHC internal. -- -- ---------------------------------------------------------------------------- module GHC.Event ( -- * Types EventManager , TimerManager -- * Creation , getSystemEventManager , new , getSystemTimerManager -- * Registering interest in I/O events , Event , evtRead , evtWrite , IOCallback , FdKey(keyFd) , registerFd , registerFd_ , unregisterFd , unregisterFd_ , closeFd -- * Registering interest in timeout events , TimeoutCallback , TimeoutKey , registerTimeout , updateTimeout , unregisterTimeout ) where import GHC.Event.Manager import GHC.Event.TimerManager (TimeoutCallback, TimeoutKey, registerTimeout, updateTimeout, unregisterTimeout, TimerManager) import GHC.Event.Thread (getSystemEventManager, getSystemTimerManager)
spacekitteh/smcghc
libraries/base/GHC/Event.hs
Haskell
bsd-3-clause
1,132
----------------------------------------------------------------------------- -- | -- Module : XMonad.Actions.TagWindows -- Copyright : (c) Karsten Schoelzel <kuser@gmx.de> -- License : BSD -- -- Maintainer : Karsten Schoelzel <kuser@gmx.de> -- Stability : unstable -- Portability : unportable -- -- Functions for tagging windows and selecting them by tags. ----------------------------------------------------------------------------- module XMonad.Actions.TagWindows ( -- * Usage -- $usage addTag, delTag, unTag, setTags, getTags, hasTag, withTaggedP, withTaggedGlobalP, withFocusedP, withTagged , withTaggedGlobal , focusUpTagged, focusUpTaggedGlobal, focusDownTagged, focusDownTaggedGlobal, shiftHere, shiftToScreen, tagPrompt, tagDelPrompt, TagPrompt, ) where import Data.List (nub,sortBy) import Control.Monad import Control.Exception as E import XMonad.StackSet hiding (filter) import XMonad.Prompt import XMonad hiding (workspaces) econst :: Monad m => a -> IOException -> m a econst = const . return -- $usage -- -- To use window tags, import this module into your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Actions.TagWindows -- > import XMonad.Prompt -- to use tagPrompt -- -- and add keybindings such as the following: -- -- > , ((modm, xK_f ), withFocused (addTag "abc")) -- > , ((modm .|. controlMask, xK_f ), withFocused (delTag "abc")) -- > , ((modm .|. shiftMask, xK_f ), withTaggedGlobalP "abc" W.sink) -- > , ((modm, xK_d ), withTaggedP "abc" (W.shiftWin "2")) -- > , ((modm .|. shiftMask, xK_d ), withTaggedGlobalP "abc" shiftHere) -- > , ((modm .|. controlMask, xK_d ), focusUpTaggedGlobal "abc") -- > , ((modm, xK_g ), tagPrompt def (\s -> withFocused (addTag s))) -- > , ((modm .|. controlMask, xK_g ), tagDelPrompt def) -- > , ((modm .|. shiftMask, xK_g ), tagPrompt def (\s -> withTaggedGlobal s float)) -- > , ((modWinMask, xK_g ), tagPrompt def (\s -> withTaggedP s (W.shiftWin "2"))) -- > , ((modWinMask .|. shiftMask, xK_g ), tagPrompt def (\s -> withTaggedGlobalP s shiftHere)) -- > , ((modWinMask .|. controlMask, xK_g ), tagPrompt def (\s -> focusUpTaggedGlobal s)) -- -- NOTE: Tags are saved as space separated strings and split with -- 'unwords'. Thus if you add a tag \"a b\" the window will have -- the tags \"a\" and \"b\" but not \"a b\". -- -- For detailed instructions on editing your key bindings, see -- "XMonad.Doc.Extending#Editing_key_bindings". -- | set multiple tags for a window at once (overriding any previous tags) setTags :: [String] -> Window -> X () setTags = setTag . unwords -- | set a tag for a window (overriding any previous tags) -- writes it to the \"_XMONAD_TAGS\" window property setTag :: String -> Window -> X () setTag s w = withDisplay $ \d -> io $ internAtom d "_XMONAD_TAGS" False >>= setTextProperty d w s -- | read all tags of a window -- reads from the \"_XMONAD_TAGS\" window property getTags :: Window -> X [String] getTags w = withDisplay $ \d -> io $ E.catch (internAtom d "_XMONAD_TAGS" False >>= getTextProperty d w >>= wcTextPropertyToTextList d) (econst [[]]) >>= return . words . unwords -- | check a window for the given tag hasTag :: String -> Window -> X Bool hasTag s w = (s `elem`) `fmap` getTags w -- | add a tag to the existing ones addTag :: String -> Window -> X () addTag s w = do tags <- getTags w if (s `notElem` tags) then setTags (s:tags) w else return () -- | remove a tag from a window, if it exists delTag :: String -> Window -> X () delTag s w = do tags <- getTags w setTags (filter (/= s) tags) w -- | remove all tags unTag :: Window -> X () unTag = setTag "" -- | Move the focus in a group of windows, which share the same given tag. -- The Global variants move through all workspaces, whereas the other -- ones operate only on the current workspace focusUpTagged, focusDownTagged, focusUpTaggedGlobal, focusDownTaggedGlobal :: String -> X () focusUpTagged = focusTagged' (reverse . wsToList) focusDownTagged = focusTagged' wsToList focusUpTaggedGlobal = focusTagged' (reverse . wsToListGlobal) focusDownTaggedGlobal = focusTagged' wsToListGlobal wsToList :: (Ord i) => StackSet i l a s sd -> [a] wsToList ws = crs ++ cls where (crs, cls) = (cms down, cms (reverse . up)) cms f = maybe [] f (stack . workspace . current $ ws) wsToListGlobal :: (Ord i) => StackSet i l a s sd -> [a] wsToListGlobal ws = concat ([crs] ++ rws ++ lws ++ [cls]) where curtag = currentTag ws (crs, cls) = (cms down, cms (reverse . up)) cms f = maybe [] f (stack . workspace . current $ ws) (lws, rws) = (mws (<), mws (>)) mws cmp = map (integrate' . stack) . sortByTag . filter (\w -> tag w `cmp` curtag) . workspaces $ ws sortByTag = sortBy (\x y -> compare (tag x) (tag y)) focusTagged' :: (WindowSet -> [Window]) -> String -> X () focusTagged' wl t = gets windowset >>= findM (hasTag t) . wl >>= maybe (return ()) (windows . focusWindow) findM :: (Monad m) => (a -> m Bool) -> [a] -> m (Maybe a) findM _ [] = return Nothing findM p (x:xs) = do b <- p x if b then return (Just x) else findM p xs -- | apply a pure function to windows with a tag withTaggedP, withTaggedGlobalP :: String -> (Window -> WindowSet -> WindowSet) -> X () withTaggedP t f = withTagged' t (winMap f) withTaggedGlobalP t f = withTaggedGlobal' t (winMap f) winMap :: (Window -> WindowSet -> WindowSet) -> [Window] -> X () winMap f tw = when (tw /= []) (windows $ foldl1 (.) (map f tw)) withTagged, withTaggedGlobal :: String -> (Window -> X ()) -> X () withTagged t f = withTagged' t (mapM_ f) withTaggedGlobal t f = withTaggedGlobal' t (mapM_ f) withTagged' :: String -> ([Window] -> X ()) -> X () withTagged' t m = gets windowset >>= filterM (hasTag t) . index >>= m withTaggedGlobal' :: String -> ([Window] -> X ()) -> X () withTaggedGlobal' t m = gets windowset >>= filterM (hasTag t) . concat . map (integrate' . stack) . workspaces >>= m withFocusedP :: (Window -> WindowSet -> WindowSet) -> X () withFocusedP f = withFocused $ windows . f shiftHere :: (Ord a, Eq s, Eq i) => a -> StackSet i l a s sd -> StackSet i l a s sd shiftHere w s = shiftWin (currentTag s) w s shiftToScreen :: (Ord a, Eq s, Eq i) => s -> a -> StackSet i l a s sd -> StackSet i l a s sd shiftToScreen sid w s = case filter (\m -> sid /= screen m) ((current s):(visible s)) of [] -> s (t:_) -> shiftWin (tag . workspace $ t) w s data TagPrompt = TagPrompt instance XPrompt TagPrompt where showXPrompt TagPrompt = "Select Tag: " tagPrompt :: XPConfig -> (String -> X ()) -> X () tagPrompt c f = do sc <- tagComplList mkXPrompt TagPrompt c (mkComplFunFromList' sc) f tagComplList :: X [String] tagComplList = gets (concat . map (integrate' . stack) . workspaces . windowset) >>= mapM getTags >>= return . nub . concat tagDelPrompt :: XPConfig -> X () tagDelPrompt c = do sc <- tagDelComplList if (sc /= []) then mkXPrompt TagPrompt c (mkComplFunFromList' sc) (\s -> withFocused (delTag s)) else return () tagDelComplList :: X [String] tagDelComplList = gets windowset >>= maybe (return []) getTags . peek
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Actions/TagWindows.hs
Haskell
bsd-2-clause
7,669
----------------------------------------------------------------------------- -- | -- Module : Distribution.ParseUtils -- Copyright : (c) The University of Glasgow 2004 -- License : BSD3 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- Utilities for parsing 'PackageDescription' and 'InstalledPackageInfo'. -- -- The @.cabal@ file format is not trivial, especially with the introduction -- of configurations and the section syntax that goes with that. This module -- has a bunch of parsing functions that is used by the @.cabal@ parser and a -- couple others. It has the parsing framework code and also little parsers for -- many of the formats we get in various @.cabal@ file fields, like module -- names, comma separated lists etc. -- This module is meant to be local-only to Distribution... {-# OPTIONS_HADDOCK hide #-} module Distribution.ParseUtils ( LineNo, PError(..), PWarning(..), locatedErrorMsg, syntaxError, warning, runP, runE, ParseResult(..), catchParseError, parseFail, showPWarning, Field(..), fName, lineNo, FieldDescr(..), ppField, ppFields, readFields, readFieldsFlat, showFields, showSingleNamedField, showSimpleSingleNamedField, parseFields, parseFieldsFlat, parseFilePathQ, parseTokenQ, parseTokenQ', parseModuleNameQ, parseBuildTool, parsePkgconfigDependency, parseOptVersion, parsePackageNameQ, parseVersionRangeQ, parseTestedWithQ, parseLicenseQ, parseLanguageQ, parseExtensionQ, parseSepList, parseCommaList, parseOptCommaList, showFilePath, showToken, showTestedWith, showFreeText, parseFreeText, field, simpleField, listField, listFieldWithSep, spaceListField, commaListField, commaListFieldWithSep, commaNewLineListField, optsField, liftField, boolField, parseQuoted, indentWith, UnrecFieldParser, warnUnrec, ignoreUnrec, ) where import Distribution.Compiler import Distribution.License import Distribution.Version import Distribution.Package import Distribution.ModuleName import qualified Distribution.Compat.MonadFail as Fail import Distribution.Compat.ReadP as ReadP hiding (get) import Distribution.ReadE import Distribution.Text import Distribution.Simple.Utils import Language.Haskell.Extension import Text.PrettyPrint hiding (braces) import Data.Char (isSpace, toLower, isAlphaNum, isDigit) import Data.Maybe (fromMaybe) import Data.Tree as Tree (Tree(..), flatten) import qualified Data.Map as Map import Control.Monad (foldM, ap) import Control.Applicative as AP (Applicative(..)) import System.FilePath (normalise) import Data.List (sortBy) -- ----------------------------------------------------------------------------- type LineNo = Int type Separator = ([Doc] -> Doc) data PError = AmbiguousParse String LineNo | NoParse String LineNo | TabsError LineNo | FromString String (Maybe LineNo) deriving (Eq, Show) data PWarning = PWarning String | UTFWarning LineNo String deriving (Eq, Show) showPWarning :: FilePath -> PWarning -> String showPWarning fpath (PWarning msg) = normalise fpath ++ ": " ++ msg showPWarning fpath (UTFWarning line fname) = normalise fpath ++ ":" ++ show line ++ ": Invalid UTF-8 text in the '" ++ fname ++ "' field." data ParseResult a = ParseFailed PError | ParseOk [PWarning] a deriving Show instance Functor ParseResult where fmap _ (ParseFailed err) = ParseFailed err fmap f (ParseOk ws x) = ParseOk ws $ f x instance Applicative ParseResult where pure = ParseOk [] (<*>) = ap instance Monad ParseResult where return = AP.pure ParseFailed err >>= _ = ParseFailed err ParseOk ws x >>= f = case f x of ParseFailed err -> ParseFailed err ParseOk ws' x' -> ParseOk (ws'++ws) x' fail = Fail.fail instance Fail.MonadFail ParseResult where fail s = ParseFailed (FromString s Nothing) catchParseError :: ParseResult a -> (PError -> ParseResult a) -> ParseResult a p@(ParseOk _ _) `catchParseError` _ = p ParseFailed e `catchParseError` k = k e parseFail :: PError -> ParseResult a parseFail = ParseFailed runP :: LineNo -> String -> ReadP a a -> String -> ParseResult a runP line fieldname p s = case [ x | (x,"") <- results ] of [a] -> ParseOk (utf8Warnings line fieldname s) a --TODO: what is this double parse thing all about? -- Can't we just do the all isSpace test the first time? [] -> case [ x | (x,ys) <- results, all isSpace ys ] of [a] -> ParseOk (utf8Warnings line fieldname s) a [] -> ParseFailed (NoParse fieldname line) _ -> ParseFailed (AmbiguousParse fieldname line) _ -> ParseFailed (AmbiguousParse fieldname line) where results = readP_to_S p s runE :: LineNo -> String -> ReadE a -> String -> ParseResult a runE line fieldname p s = case runReadE p s of Right a -> ParseOk (utf8Warnings line fieldname s) a Left e -> syntaxError line $ "Parse of field '" ++ fieldname ++ "' failed (" ++ e ++ "): " ++ s utf8Warnings :: LineNo -> String -> String -> [PWarning] utf8Warnings line fieldname s = take 1 [ UTFWarning n fieldname | (n,l) <- zip [line..] (lines s) , '\xfffd' `elem` l ] locatedErrorMsg :: PError -> (Maybe LineNo, String) locatedErrorMsg (AmbiguousParse f n) = (Just n, "Ambiguous parse in field '"++f++"'.") locatedErrorMsg (NoParse f n) = (Just n, "Parse of field '"++f++"' failed.") locatedErrorMsg (TabsError n) = (Just n, "Tab used as indentation.") locatedErrorMsg (FromString s n) = (n, s) syntaxError :: LineNo -> String -> ParseResult a syntaxError n s = ParseFailed $ FromString s (Just n) tabsError :: LineNo -> ParseResult a tabsError ln = ParseFailed $ TabsError ln warning :: String -> ParseResult () warning s = ParseOk [PWarning s] () -- | Field descriptor. The parameter @a@ parameterizes over where the field's -- value is stored in. data FieldDescr a = FieldDescr { fieldName :: String , fieldGet :: a -> Doc , fieldSet :: LineNo -> String -> a -> ParseResult a -- ^ @fieldSet n str x@ Parses the field value from the given input -- string @str@ and stores the result in @x@ if the parse was -- successful. Otherwise, reports an error on line number @n@. } field :: String -> (a -> Doc) -> ReadP a a -> FieldDescr a field name showF readF = FieldDescr name showF (\line val _st -> runP line name readF val) -- Lift a field descriptor storing into an 'a' to a field descriptor storing -- into a 'b'. liftField :: (b -> a) -> (a -> b -> b) -> FieldDescr a -> FieldDescr b liftField get set (FieldDescr name showF parseF) = FieldDescr name (showF . get) (\line str b -> do a <- parseF line str (get b) return (set a b)) -- Parser combinator for simple fields. Takes a field name, a pretty printer, -- a parser function, an accessor, and a setter, returns a FieldDescr over the -- compoid structure. simpleField :: String -> (a -> Doc) -> ReadP a a -> (b -> a) -> (a -> b -> b) -> FieldDescr b simpleField name showF readF get set = liftField get set $ field name showF readF commaListFieldWithSep :: Separator -> String -> (a -> Doc) -> ReadP [a] a -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b commaListFieldWithSep separator name showF readF get set = liftField get set' $ field name showF' (parseCommaList readF) where set' xs b = set (get b ++ xs) b showF' = separator . punctuate comma . map showF commaListField :: String -> (a -> Doc) -> ReadP [a] a -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b commaListField = commaListFieldWithSep fsep commaNewLineListField :: String -> (a -> Doc) -> ReadP [a] a -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b commaNewLineListField = commaListFieldWithSep sep spaceListField :: String -> (a -> Doc) -> ReadP [a] a -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b spaceListField name showF readF get set = liftField get set' $ field name showF' (parseSpaceList readF) where set' xs b = set (get b ++ xs) b showF' = fsep . map showF listFieldWithSep :: Separator -> String -> (a -> Doc) -> ReadP [a] a -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b listFieldWithSep separator name showF readF get set = liftField get set' $ field name showF' (parseOptCommaList readF) where set' xs b = set (get b ++ xs) b showF' = separator . map showF listField :: String -> (a -> Doc) -> ReadP [a] a -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b listField = listFieldWithSep fsep optsField :: String -> CompilerFlavor -> (b -> [(CompilerFlavor,[String])]) -> ([(CompilerFlavor,[String])] -> b -> b) -> FieldDescr b optsField name flavor get set = liftField (fromMaybe [] . lookup flavor . get) (\opts b -> set (reorder (update flavor opts (get b))) b) $ field name showF (sepBy parseTokenQ' (munch1 isSpace)) where update _ opts l | all null opts = l --empty opts as if no opts update f opts [] = [(f,opts)] update f opts ((f',opts'):rest) | f == f' = (f, opts' ++ opts) : rest | otherwise = (f',opts') : update f opts rest reorder = sortBy (comparing fst) showF = hsep . map text -- TODO: this is a bit smelly hack. It's because we want to parse bool fields -- liberally but not accept new parses. We cannot do that with ReadP -- because it does not support warnings. We need a new parser framework! boolField :: String -> (b -> Bool) -> (Bool -> b -> b) -> FieldDescr b boolField name get set = liftField get set (FieldDescr name showF readF) where showF = text . show readF line str _ | str == "True" = ParseOk [] True | str == "False" = ParseOk [] False | lstr == "true" = ParseOk [caseWarning] True | lstr == "false" = ParseOk [caseWarning] False | otherwise = ParseFailed (NoParse name line) where lstr = lowercase str caseWarning = PWarning $ "The '" ++ name ++ "' field is case sensitive, use 'True' or 'False'." ppFields :: [FieldDescr a] -> a -> Doc ppFields fields x = vcat [ ppField name (getter x) | FieldDescr name getter _ <- fields ] ppField :: String -> Doc -> Doc ppField name fielddoc | isEmpty fielddoc = empty | name `elem` nestedFields = text name <> colon $+$ nest indentWith fielddoc | otherwise = text name <> colon <+> fielddoc where nestedFields = [ "description" , "build-depends" , "data-files" , "extra-source-files" , "extra-tmp-files" , "exposed-modules" , "c-sources" , "js-sources" , "extra-libraries" , "includes" , "install-includes" , "other-modules" , "depends" ] showFields :: [FieldDescr a] -> a -> String showFields fields = render . ($+$ text "") . ppFields fields showSingleNamedField :: [FieldDescr a] -> String -> Maybe (a -> String) showSingleNamedField fields f = case [ get | (FieldDescr f' get _) <- fields, f' == f ] of [] -> Nothing (get:_) -> Just (render . ppField f . get) showSimpleSingleNamedField :: [FieldDescr a] -> String -> Maybe (a -> String) showSimpleSingleNamedField fields f = case [ get | (FieldDescr f' get _) <- fields, f' == f ] of [] -> Nothing (get:_) -> Just (renderStyle myStyle . get) where myStyle = style { mode = LeftMode } parseFields :: [FieldDescr a] -> a -> String -> ParseResult a parseFields fields initial str = readFields str >>= accumFields fields initial parseFieldsFlat :: [FieldDescr a] -> a -> String -> ParseResult a parseFieldsFlat fields initial str = readFieldsFlat str >>= accumFields fields initial accumFields :: [FieldDescr a] -> a -> [Field] -> ParseResult a accumFields fields = foldM setField where fieldMap = Map.fromList [ (name, f) | f@(FieldDescr name _ _) <- fields ] setField accum (F line name value) = case Map.lookup name fieldMap of Just (FieldDescr _ _ set) -> set line value accum Nothing -> do warning ("Unrecognized field " ++ name ++ " on line " ++ show line) return accum setField accum f = do warning ("Unrecognized stanza on line " ++ show (lineNo f)) return accum -- | The type of a function which, given a name-value pair of an -- unrecognized field, and the current structure being built, -- decides whether to incorporate the unrecognized field -- (by returning Just x, where x is a possibly modified version -- of the structure being built), or not (by returning Nothing). type UnrecFieldParser a = (String,String) -> a -> Maybe a -- | A default unrecognized field parser which simply returns Nothing, -- i.e. ignores all unrecognized fields, so warnings will be generated. warnUnrec :: UnrecFieldParser a warnUnrec _ _ = Nothing -- | A default unrecognized field parser which silently (i.e. no -- warnings will be generated) ignores unrecognized fields, by -- returning the structure being built unmodified. ignoreUnrec :: UnrecFieldParser a ignoreUnrec _ = Just ------------------------------------------------------------------------------ -- The data type for our three syntactic categories data Field = F LineNo String String -- ^ A regular @<property>: <value>@ field | Section LineNo String String [Field] -- ^ A section with a name and possible parameter. The syntactic -- structure is: -- -- @ -- <sectionname> <arg> { -- <field>* -- } -- @ | IfBlock LineNo String [Field] [Field] -- ^ A conditional block with an optional else branch: -- -- @ -- if <condition> { -- <field>* -- } else { -- <field>* -- } -- @ deriving (Show ,Eq) -- for testing lineNo :: Field -> LineNo lineNo (F n _ _) = n lineNo (Section n _ _ _) = n lineNo (IfBlock n _ _ _) = n fName :: Field -> String fName (F _ n _) = n fName (Section _ n _ _) = n fName _ = error "fname: not a field or section" readFields :: String -> ParseResult [Field] readFields input = ifelse =<< mapM (mkField 0) =<< mkTree tokens where ls = (lines . normaliseLineEndings) input tokens = (concatMap tokeniseLine . trimLines) ls readFieldsFlat :: String -> ParseResult [Field] readFieldsFlat input = mapM (mkField 0) =<< mkTree tokens where ls = (lines . normaliseLineEndings) input tokens = (concatMap tokeniseLineFlat . trimLines) ls -- attach line number and determine indentation trimLines :: [String] -> [(LineNo, Indent, HasTabs, String)] trimLines ls = [ (lineno, indent, hastabs, trimTrailing l') | (lineno, l) <- zip [1..] ls , let (sps, l') = span isSpace l indent = length sps hastabs = '\t' `elem` sps , validLine l' ] where validLine ('-':'-':_) = False -- Comment validLine [] = False -- blank line validLine _ = True -- | We parse generically based on indent level and braces '{' '}'. To do that -- we split into lines and then '{' '}' tokens and other spans within a line. data Token = -- | The 'Line' token is for bits that /start/ a line, eg: -- -- > "\n blah blah { blah" -- -- tokenises to: -- -- > [Line n 2 False "blah blah", OpenBracket, Span n "blah"] -- -- so lines are the only ones that can have nested layout, since they -- have a known indentation level. -- -- eg: we can't have this: -- -- > if ... { -- > } else -- > other -- -- because other cannot nest under else, since else doesn't start a line -- so cannot have nested layout. It'd have to be: -- -- > if ... { -- > } -- > else -- > other -- -- but that's not so common, people would normally use layout or -- brackets not both in a single @if else@ construct. -- -- > if ... { foo : bar } -- > else -- > other -- -- this is OK Line LineNo Indent HasTabs String | Span LineNo String -- ^ span in a line, following brackets | OpenBracket LineNo | CloseBracket LineNo type Indent = Int type HasTabs = Bool -- | Tokenise a single line, splitting on '{' '}' and the spans in between. -- Also trims leading & trailing space on those spans within the line. tokeniseLine :: (LineNo, Indent, HasTabs, String) -> [Token] tokeniseLine (n0, i, t, l) = case split n0 l of (Span _ l':ss) -> Line n0 i t l' :ss cs -> cs where split _ "" = [] split n s = case span (\c -> c /='}' && c /= '{') s of ("", '{' : s') -> OpenBracket n : split n s' (w , '{' : s') -> mkspan n w (OpenBracket n : split n s') ("", '}' : s') -> CloseBracket n : split n s' (w , '}' : s') -> mkspan n w (CloseBracket n : split n s') (w , _) -> mkspan n w [] mkspan n s ss | null s' = ss | otherwise = Span n s' : ss where s' = trimTrailing (trimLeading s) tokeniseLineFlat :: (LineNo, Indent, HasTabs, String) -> [Token] tokeniseLineFlat (n0, i, t, l) | null l' = [] | otherwise = [Line n0 i t l'] where l' = trimTrailing (trimLeading l) trimLeading, trimTrailing :: String -> String trimLeading = dropWhile isSpace trimTrailing = dropWhileEndLE isSpace type SyntaxTree = Tree (LineNo, HasTabs, String) -- | Parse the stream of tokens into a tree of them, based on indent \/ layout mkTree :: [Token] -> ParseResult [SyntaxTree] mkTree toks = layout 0 [] toks >>= \(trees, trailing) -> case trailing of [] -> return trees OpenBracket n:_ -> syntaxError n "mismatched brackets, unexpected {" CloseBracket n:_ -> syntaxError n "mismatched brackets, unexpected }" -- the following two should never happen: Span n l :_ -> syntaxError n $ "unexpected span: " ++ show l Line n _ _ l :_ -> syntaxError n $ "unexpected line: " ++ show l -- | Parse the stream of tokens into a tree of them, based on indent -- This parse state expect to be in a layout context, though possibly -- nested within a braces context so we may still encounter closing braces. layout :: Indent -- ^ indent level of the parent\/previous line -> [SyntaxTree] -- ^ accumulating param, trees in this level -> [Token] -- ^ remaining tokens -> ParseResult ([SyntaxTree], [Token]) -- ^ collected trees on this level and trailing tokens layout _ a [] = return (reverse a, []) layout i a (s@(Line _ i' _ _):ss) | i' < i = return (reverse a, s:ss) layout i a (Line n _ t l:OpenBracket n':ss) = do (sub, ss') <- braces n' [] ss layout i (Node (n,t,l) sub:a) ss' layout i a (Span n l:OpenBracket n':ss) = do (sub, ss') <- braces n' [] ss layout i (Node (n,False,l) sub:a) ss' -- look ahead to see if following lines are more indented, giving a sub-tree layout i a (Line n i' t l:ss) = do lookahead <- layout (i'+1) [] ss case lookahead of ([], _) -> layout i (Node (n,t,l) [] :a) ss (ts, ss') -> layout i (Node (n,t,l) ts :a) ss' layout _ _ ( OpenBracket n :_) = syntaxError n "unexpected '{'" layout _ a (s@(CloseBracket _):ss) = return (reverse a, s:ss) layout _ _ ( Span n l : _) = syntaxError n $ "unexpected span: " ++ show l -- | Parse the stream of tokens into a tree of them, based on explicit braces -- This parse state expects to find a closing bracket. braces :: LineNo -- ^ line of the '{', used for error messages -> [SyntaxTree] -- ^ accumulating param, trees in this level -> [Token] -- ^ remaining tokens -> ParseResult ([SyntaxTree],[Token]) -- ^ collected trees on this level and trailing tokens braces m a (Line n _ t l:OpenBracket n':ss) = do (sub, ss') <- braces n' [] ss braces m (Node (n,t,l) sub:a) ss' braces m a (Span n l:OpenBracket n':ss) = do (sub, ss') <- braces n' [] ss braces m (Node (n,False,l) sub:a) ss' braces m a (Line n i t l:ss) = do lookahead <- layout (i+1) [] ss case lookahead of ([], _) -> braces m (Node (n,t,l) [] :a) ss (ts, ss') -> braces m (Node (n,t,l) ts :a) ss' braces m a (Span n l:ss) = braces m (Node (n,False,l) []:a) ss braces _ a (CloseBracket _:ss) = return (reverse a, ss) braces n _ [] = syntaxError n $ "opening brace '{'" ++ "has no matching closing brace '}'" braces _ _ (OpenBracket n:_) = syntaxError n "unexpected '{'" -- | Convert the parse tree into the Field AST -- Also check for dodgy uses of tabs in indentation. mkField :: Int -> SyntaxTree -> ParseResult Field mkField d (Node (n,t,_) _) | d >= 1 && t = tabsError n mkField d (Node (n,_,l) ts) = case span (\c -> isAlphaNum c || c == '-') l of ([], _) -> syntaxError n $ "unrecognised field or section: " ++ show l (name, rest) -> case trimLeading rest of (':':rest') -> do let followingLines = concatMap Tree.flatten ts tabs = not (null [()| (_,True,_) <- followingLines ]) if tabs && d >= 1 then tabsError n else return $ F n (map toLower name) (fieldValue rest' followingLines) rest' -> do ts' <- mapM (mkField (d+1)) ts return (Section n (map toLower name) rest' ts') where fieldValue firstLine followingLines = let firstLine' = trimLeading firstLine followingLines' = map (\(_,_,s) -> stripDot s) followingLines allLines | null firstLine' = followingLines' | otherwise = firstLine' : followingLines' in intercalate "\n" allLines stripDot "." = "" stripDot s = s -- | Convert if/then/else 'Section's to 'IfBlock's ifelse :: [Field] -> ParseResult [Field] ifelse [] = return [] ifelse (Section n "if" cond thenpart :Section _ "else" as elsepart:fs) | null cond = syntaxError n "'if' with missing condition" | null thenpart = syntaxError n "'then' branch of 'if' is empty" | not (null as) = syntaxError n "'else' takes no arguments" | null elsepart = syntaxError n "'else' branch of 'if' is empty" | otherwise = do tp <- ifelse thenpart ep <- ifelse elsepart fs' <- ifelse fs return (IfBlock n cond tp ep:fs') ifelse (Section n "if" cond thenpart:fs) | null cond = syntaxError n "'if' with missing condition" | null thenpart = syntaxError n "'then' branch of 'if' is empty" | otherwise = do tp <- ifelse thenpart fs' <- ifelse fs return (IfBlock n cond tp []:fs') ifelse (Section n "else" _ _:_) = syntaxError n "stray 'else' with no preceding 'if'" ifelse (Section n s a fs':fs) = do fs'' <- ifelse fs' fs''' <- ifelse fs return (Section n s a fs'' : fs''') ifelse (f:fs) = do fs' <- ifelse fs return (f : fs') ------------------------------------------------------------------------------ -- |parse a module name parseModuleNameQ :: ReadP r ModuleName parseModuleNameQ = parseQuoted parse <++ parse parseFilePathQ :: ReadP r FilePath parseFilePathQ = parseTokenQ -- removed until normalise is no longer broken, was: -- liftM normalise parseTokenQ betweenSpaces :: ReadP r a -> ReadP r a betweenSpaces act = do skipSpaces res <- act skipSpaces return res parseBuildTool :: ReadP r Dependency parseBuildTool = do name <- parseBuildToolNameQ ver <- betweenSpaces $ parseVersionRangeQ <++ return anyVersion return $ Dependency name ver parseBuildToolNameQ :: ReadP r PackageName parseBuildToolNameQ = parseQuoted parseBuildToolName <++ parseBuildToolName -- like parsePackageName but accepts symbols in components parseBuildToolName :: ReadP r PackageName parseBuildToolName = do ns <- sepBy1 component (ReadP.char '-') return (PackageName (intercalate "-" ns)) where component = do cs <- munch1 (\c -> isAlphaNum c || c == '+' || c == '_') if all isDigit cs then pfail else return cs -- pkg-config allows versions and other letters in package names, -- eg "gtk+-2.0" is a valid pkg-config package _name_. -- It then has a package version number like 2.10.13 parsePkgconfigDependency :: ReadP r Dependency parsePkgconfigDependency = do name <- munch1 (\c -> isAlphaNum c || c `elem` "+-._") ver <- betweenSpaces $ parseVersionRangeQ <++ return anyVersion return $ Dependency (PackageName name) ver parsePackageNameQ :: ReadP r PackageName parsePackageNameQ = parseQuoted parse <++ parse parseVersionRangeQ :: ReadP r VersionRange parseVersionRangeQ = parseQuoted parse <++ parse parseOptVersion :: ReadP r Version parseOptVersion = parseQuoted ver <++ ver where ver :: ReadP r Version ver = parse <++ return (Version [] []) parseTestedWithQ :: ReadP r (CompilerFlavor,VersionRange) parseTestedWithQ = parseQuoted tw <++ tw where tw :: ReadP r (CompilerFlavor,VersionRange) tw = do compiler <- parseCompilerFlavorCompat version <- betweenSpaces $ parse <++ return anyVersion return (compiler,version) parseLicenseQ :: ReadP r License parseLicenseQ = parseQuoted parse <++ parse -- urgh, we can't define optQuotes :: ReadP r a -> ReadP r a -- because the "compat" version of ReadP isn't quite powerful enough. In -- particular, the type of <++ is ReadP r r -> ReadP r a -> ReadP r a -- Hence the trick above to make 'lic' polymorphic. parseLanguageQ :: ReadP r Language parseLanguageQ = parseQuoted parse <++ parse parseExtensionQ :: ReadP r Extension parseExtensionQ = parseQuoted parse <++ parse parseHaskellString :: ReadP r String parseHaskellString = readS_to_P reads parseTokenQ :: ReadP r String parseTokenQ = parseHaskellString <++ munch1 (\x -> not (isSpace x) && x /= ',') parseTokenQ' :: ReadP r String parseTokenQ' = parseHaskellString <++ munch1 (not . isSpace) parseSepList :: ReadP r b -> ReadP r a -- ^The parser for the stuff between commas -> ReadP r [a] parseSepList sepr p = sepBy p separator where separator = betweenSpaces sepr parseSpaceList :: ReadP r a -- ^The parser for the stuff between commas -> ReadP r [a] parseSpaceList p = sepBy p skipSpaces parseCommaList :: ReadP r a -- ^The parser for the stuff between commas -> ReadP r [a] parseCommaList = parseSepList (ReadP.char ',') parseOptCommaList :: ReadP r a -- ^The parser for the stuff between commas -> ReadP r [a] parseOptCommaList = parseSepList (optional (ReadP.char ',')) parseQuoted :: ReadP r a -> ReadP r a parseQuoted = between (ReadP.char '"') (ReadP.char '"') parseFreeText :: ReadP.ReadP s String parseFreeText = ReadP.munch (const True) -- -------------------------------------------- -- ** Pretty printing showFilePath :: FilePath -> Doc showFilePath "" = empty showFilePath x = showToken x showToken :: String -> Doc showToken str | not (any dodgy str) && not (null str) = text str | otherwise = text (show str) where dodgy c = isSpace c || c == ',' showTestedWith :: (CompilerFlavor,VersionRange) -> Doc showTestedWith (compiler, version) = text (show compiler) <+> disp version -- | Pretty-print free-format text, ensuring that it is vertically aligned, -- and with blank lines replaced by dots for correct re-parsing. showFreeText :: String -> Doc showFreeText "" = empty showFreeText s = vcat [text (if null l then "." else l) | l <- lines_ s] -- | 'lines_' breaks a string up into a list of strings at newline -- characters. The resulting strings do not contain newlines. lines_ :: String -> [String] lines_ [] = [""] lines_ s = let (l, s') = break (== '\n') s in l : case s' of [] -> [] (_:s'') -> lines_ s'' -- | the indentation used for pretty printing indentWith :: Int indentWith = 4
tolysz/prepare-ghcjs
spec-lts8/cabal/Cabal/Distribution/ParseUtils.hs
Haskell
bsd-3-clause
29,528
-- Test case of known literal with wraparound test = case 1 :: Int of 0x10000000000000001 -> "A" _ -> "B" test2 = case 0x10000000000000001 :: Int of 1 -> "A" _ -> "B" main = putStrLn $ test ++ test2
ezyang/ghc
testsuite/tests/codeGen/should_run/T9533b.hs
Haskell
bsd-3-clause
237
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP , NoImplicitPrelude , MagicHash , UnboxedTuples #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.TopHandler -- Copyright : (c) The University of Glasgow, 2001-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- Support for catching exceptions raised during top-level computations -- (e.g. @Main.main@, 'Control.Concurrent.forkIO', and foreign exports) -- ----------------------------------------------------------------------------- module GHC.TopHandler ( runMainIO, runIO, runIOFastExit, runNonIO, topHandler, topHandlerFastExit, reportStackOverflow, reportError, flushStdHandles ) where #include "HsBaseConfig.h" import Control.Exception import Data.Maybe import Foreign import Foreign.C import GHC.Base import GHC.Conc hiding (throwTo) import GHC.Real import GHC.IO import GHC.IO.Handle.FD import GHC.IO.Handle import GHC.IO.Exception import GHC.Weak #if defined(mingw32_HOST_OS) import GHC.ConsoleHandler #else import Data.Dynamic (toDyn) #endif -- | 'runMainIO' is wrapped around 'Main.main' (or whatever main is -- called in the program). It catches otherwise uncaught exceptions, -- and also flushes stdout\/stderr before exiting. runMainIO :: IO a -> IO a runMainIO main = do main_thread_id <- myThreadId weak_tid <- mkWeakThreadId main_thread_id install_interrupt_handler $ do m <- deRefWeak weak_tid case m of Nothing -> return () Just tid -> throwTo tid (toException UserInterrupt) main -- hs_exit() will flush `catch` topHandler install_interrupt_handler :: IO () -> IO () #ifdef mingw32_HOST_OS install_interrupt_handler handler = do _ <- GHC.ConsoleHandler.installHandler $ Catch $ \event -> case event of ControlC -> handler Break -> handler Close -> handler _ -> return () return () #else #include "rts/Signals.h" -- specialised version of System.Posix.Signals.installHandler, which -- isn't available here. install_interrupt_handler handler = do let sig = CONST_SIGINT :: CInt _ <- setHandler sig (Just (const handler, toDyn handler)) _ <- stg_sig_install sig STG_SIG_RST nullPtr -- STG_SIG_RST: the second ^C kills us for real, just in case the -- RTS or program is unresponsive. return () foreign import ccall unsafe stg_sig_install :: CInt -- sig no. -> CInt -- action code (STG_SIG_HAN etc.) -> Ptr () -- (in, out) blocked -> IO CInt -- (ret) old action code #endif -- | 'runIO' is wrapped around every @foreign export@ and @foreign -- import \"wrapper\"@ to mop up any uncaught exceptions. Thus, the -- result of running 'System.Exit.exitWith' in a foreign-exported -- function is the same as in the main thread: it terminates the -- program. -- runIO :: IO a -> IO a runIO main = catch main topHandler -- | Like 'runIO', but in the event of an exception that causes an exit, -- we don't shut down the system cleanly, we just exit. This is -- useful in some cases, because the safe exit version will give other -- threads a chance to clean up first, which might shut down the -- system in a different way. For example, try -- -- main = forkIO (runIO (exitWith (ExitFailure 1))) >> threadDelay 10000 -- -- This will sometimes exit with "interrupted" and code 0, because the -- main thread is given a chance to shut down when the child thread calls -- safeExit. There is a race to shut down between the main and child threads. -- runIOFastExit :: IO a -> IO a runIOFastExit main = catch main topHandlerFastExit -- NB. this is used by the testsuite driver -- | The same as 'runIO', but for non-IO computations. Used for -- wrapping @foreign export@ and @foreign import \"wrapper\"@ when these -- are used to export Haskell functions with non-IO types. -- runNonIO :: a -> IO a runNonIO a = catch (a `seq` return a) topHandler topHandler :: SomeException -> IO a topHandler err = catch (real_handler safeExit err) topHandler topHandlerFastExit :: SomeException -> IO a topHandlerFastExit err = catchException (real_handler fastExit err) topHandlerFastExit -- Make sure we handle errors while reporting the error! -- (e.g. evaluating the string passed to 'error' might generate -- another error, etc.) -- real_handler :: (Int -> IO a) -> SomeException -> IO a real_handler exit se = do flushStdHandles -- before any error output case fromException se of Just StackOverflow -> do reportStackOverflow exit 2 Just UserInterrupt -> exitInterrupted _ -> case fromException se of -- only the main thread gets ExitException exceptions Just ExitSuccess -> exit 0 Just (ExitFailure n) -> exit n -- EPIPE errors received for stdout are ignored (#2699) _ -> catch (case fromException se of Just IOError{ ioe_type = ResourceVanished, ioe_errno = Just ioe, ioe_handle = Just hdl } | Errno ioe == ePIPE, hdl == stdout -> exit 0 _ -> do reportError se exit 1 ) (disasterHandler exit) -- See Note [Disaster with iconv] -- don't use errorBelch() directly, because we cannot call varargs functions -- using the FFI. foreign import ccall unsafe "HsBase.h errorBelch2" errorBelch :: CString -> CString -> IO () disasterHandler :: (Int -> IO a) -> IOError -> IO a disasterHandler exit _ = withCAString "%s" $ \fmt -> withCAString msgStr $ \msg -> errorBelch fmt msg >> exit 1 where msgStr = "encountered an exception while trying to report an exception." ++ "One possible reason for this is that we failed while trying to " ++ "encode an error message. Check that your locale is configured " ++ "properly." {- Note [Disaster with iconv] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When using iconv, it's possible for things like iconv_open to fail in restricted environments (like an initram or restricted container), but when this happens the error raised inevitably calls `peekCString`, which depends on the users locale, which depends on using `iconv_open`... which causes an infinite loop. This occurrence is also known as tickets #10298 and #7695. So to work around it we just set _another_ error handler and bail directly by calling the RTS, without iconv at all. -} -- try to flush stdout/stderr, but don't worry if we fail -- (these handles might have errors, and we don't want to go into -- an infinite loop). flushStdHandles :: IO () flushStdHandles = do hFlush stdout `catchAny` \_ -> return () hFlush stderr `catchAny` \_ -> return () safeExit, fastExit :: Int -> IO a safeExit = exitHelper useSafeExit fastExit = exitHelper useFastExit unreachable :: IO a unreachable = fail "If you can read this, shutdownHaskellAndExit did not exit." exitHelper :: CInt -> Int -> IO a #ifdef mingw32_HOST_OS exitHelper exitKind r = shutdownHaskellAndExit (fromIntegral r) exitKind >> unreachable #else -- On Unix we use an encoding for the ExitCode: -- 0 -- 255 normal exit code -- -127 -- -1 exit by signal -- For any invalid encoding we just use a replacement (0xff). exitHelper exitKind r | r >= 0 && r <= 255 = shutdownHaskellAndExit (fromIntegral r) exitKind >> unreachable | r >= -127 && r <= -1 = shutdownHaskellAndSignal (fromIntegral (-r)) exitKind >> unreachable | otherwise = shutdownHaskellAndExit 0xff exitKind >> unreachable foreign import ccall "shutdownHaskellAndSignal" shutdownHaskellAndSignal :: CInt -> CInt -> IO () #endif exitInterrupted :: IO a exitInterrupted = #ifdef mingw32_HOST_OS safeExit 252 #else -- we must exit via the default action for SIGINT, so that the -- parent of this process can take appropriate action (see #2301) safeExit (-CONST_SIGINT) #endif -- NOTE: shutdownHaskellAndExit must be called "safe", because it *can* -- re-enter Haskell land through finalizers. foreign import ccall "Rts.h shutdownHaskellAndExit" shutdownHaskellAndExit :: CInt -> CInt -> IO () useFastExit, useSafeExit :: CInt useFastExit = 1 useSafeExit = 0
urbanslug/ghc
libraries/base/GHC/TopHandler.hs
Haskell
bsd-3-clause
8,607
{-# LANGUAGE DataKinds #-} module T8455 where ty = [t| 5 |]
ghc-android/ghc
testsuite/tests/quotes/T8455.hs
Haskell
bsd-3-clause
62
import System.Environment import System.IO import System.Directory import Control.Monad import Shake import JsonSettings import RevReport import WithLatestLogs import Summary import GraphReport import BenchNames import GraphSummaries import GHC.IO.Encoding {- We want to build everything into one executable, bit still treat it as multiple tools. Hence the main function here calls the various real main functions, defaulting to the shake tool. -} main :: IO () main = do -- Make us locale-independent setLocaleEncoding utf8 args <- getArgs ex <- doesFileExist "gipeda.yaml" unless ex $ do hPutStr stderr "Please run this from the same directory as the gipeda.yaml file.\n" case args of "JsonSettings":_ -> jsonSettingsMain "Summary":opts -> summaryMain opts "RevReport":opts -> revReportMain opts "BranchReport":opts -> branchReportMain opts "GraphReport":opts -> graphReportMain opts "WithLatestLogs":opts -> withLatestLogsMain opts "BenchNames":opts -> benchNamesMain opts "GraphSummaries":opts -> graphSummaries opts _ -> shakeMain -- shake will take the arguments from getArgs
nomeata/gipeda
src/gipeda.hs
Haskell
mit
1,225
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-table-pointintimerecoveryspecification.html module Stratosphere.ResourceProperties.DynamoDBTablePointInTimeRecoverySpecification where import Stratosphere.ResourceImports -- | Full data type definition for -- DynamoDBTablePointInTimeRecoverySpecification. See -- 'dynamoDBTablePointInTimeRecoverySpecification' for a more convenient -- constructor. data DynamoDBTablePointInTimeRecoverySpecification = DynamoDBTablePointInTimeRecoverySpecification { _dynamoDBTablePointInTimeRecoverySpecificationPointInTimeRecoveryEnabled :: Maybe (Val Bool) } deriving (Show, Eq) instance ToJSON DynamoDBTablePointInTimeRecoverySpecification where toJSON DynamoDBTablePointInTimeRecoverySpecification{..} = object $ catMaybes [ fmap (("PointInTimeRecoveryEnabled",) . toJSON) _dynamoDBTablePointInTimeRecoverySpecificationPointInTimeRecoveryEnabled ] -- | Constructor for 'DynamoDBTablePointInTimeRecoverySpecification' -- containing required fields as arguments. dynamoDBTablePointInTimeRecoverySpecification :: DynamoDBTablePointInTimeRecoverySpecification dynamoDBTablePointInTimeRecoverySpecification = DynamoDBTablePointInTimeRecoverySpecification { _dynamoDBTablePointInTimeRecoverySpecificationPointInTimeRecoveryEnabled = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-table-pointintimerecoveryspecification.html#cfn-dynamodb-table-pointintimerecoveryspecification-pointintimerecoveryenabled ddbtpitrsPointInTimeRecoveryEnabled :: Lens' DynamoDBTablePointInTimeRecoverySpecification (Maybe (Val Bool)) ddbtpitrsPointInTimeRecoveryEnabled = lens _dynamoDBTablePointInTimeRecoverySpecificationPointInTimeRecoveryEnabled (\s a -> s { _dynamoDBTablePointInTimeRecoverySpecificationPointInTimeRecoveryEnabled = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/DynamoDBTablePointInTimeRecoverySpecification.hs
Haskell
mit
2,017
-- This file is part of the 'union-find-array' library. It is licensed -- under an MIT license. See the accompanying 'LICENSE' file for details. -- -- Authors: Bertram Felgenhauer {-# LANGUAGE RankNTypes, FlexibleContexts, CPP #-} -- | -- Low-level interface for managing a disjoint set data structure, based on -- 'Control.Monad.ST'. For a higher level convenience interface, look at -- 'Control.Monad.Union'. module Data.Union.ST ( UnionST, runUnionST, new, grow, copy, lookup, annotate, merge, flatten, size, unsafeFreeze, ) where import qualified Data.Union.Type as U import Prelude hiding (lookup) import Control.Monad.ST import Control.Monad import Control.Applicative import Data.Array.Base hiding (unsafeFreeze) import Data.Array.ST hiding (unsafeFreeze) import qualified Data.Array.Base as A (unsafeFreeze) -- | A disjoint set forest, with nodes numbered from 0, which can carry labels. data UnionST s l = UnionST { up :: STUArray s Int Int, rank :: STUArray s Int Int, label :: STArray s Int l, size :: !Int, def :: l } #if __GLASGOW_HASKELL__ < 702 instance Applicative (ST s) where (<*>) = ap pure = return #endif -- Use http://www.haskell.org/pipermail/libraries/2008-March/009465.html ? -- | Analogous to 'Data.Array.ST.runSTArray'. runUnionST :: (forall s. ST s (UnionST s l)) -> U.Union l runUnionST a = runST $ a >>= unsafeFreeze -- | Analogous to 'Data.Array.Base.unsafeFreeze' unsafeFreeze :: UnionST s l -> ST s (U.Union l) unsafeFreeze u = U.Union (size u) <$> A.unsafeFreeze (up u) <*> A.unsafeFreeze (label u) -- What about thawing? -- | Create a new disjoint set forest, of given capacity. new :: Int -> l -> ST s (UnionST s l) new size def = do up <- newListArray (0, size-1) [0..] rank <- newArray (0, size-1) 0 label <- newArray (0, size-1) def return UnionST{ up = up, rank = rank, label = label, size = size, def = def } -- | Grow the capacity of a disjoint set forest. Shrinking is not possible. -- Trying to shrink a disjoint set forest will return the same forest -- unmodified. grow :: UnionST s l -> Int -> ST s (UnionST s l) grow u size' | size' <= size u = return u grow u size' = grow' u size' -- | Copy a disjoint set forest. copy :: UnionST s l -> ST s (UnionST s l) copy u = grow' u (size u) grow' :: UnionST s l -> Int -> ST s (UnionST s l) grow' u size' = do up' <- newListArray (0, size'-1) [0..] rank' <- newArray (0, size'-1) 0 label' <- newArray (0, size'-1) (def u) forM_ [0..size u - 1] $ \i -> do readArray (up u) i >>= writeArray up' i readArray (rank u) i >>= writeArray rank' i readArray (label u) i >>= writeArray label' i return u{ up = up', rank = rank', label = label', size = size' } -- | Annotate a node with a new label. annotate :: UnionST s l -> Int -> l -> ST s () annotate u i v = writeArray (label u) i v -- | Look up the representative of a given node. -- -- lookup' does path compression. lookup' :: UnionST s l -> Int -> ST s Int lookup' u i = do i' <- readArray (up u) i if i == i' then return i else do i'' <- lookup' u i' writeArray (up u) i i'' return i'' -- | Look up the representative of a given node and its label. lookup :: UnionST s l -> Int -> ST s (Int, l) lookup u i = do i' <- lookup' u i l' <- readArray (label u) i' return (i', l') -- | Check whether two nodes are in the same set. equals :: UnionST s l -> Int -> Int -> ST s Bool equals u a b = do a' <- lookup' u a b' <- lookup' u b return (a' == b') -- | Merge two nodes if they are in distinct equivalence classes. The -- passed function is used to combine labels, if a merge happens. merge :: UnionST s l -> (l -> l -> (l, a)) -> Int -> Int -> ST s (Maybe a) merge u f a b = do (a', va) <- lookup u a (b', vb) <- lookup u b if a' == b' then return Nothing else do ra <- readArray (rank u) a' rb <- readArray (rank u) b' let cont x vx y vy = do writeArray (label u) y (error "invalid entry") let (v, w) = f vx vy writeArray (label u) x v return (Just w) case ra `compare` rb of LT -> do writeArray (up u) a' b' cont b' vb a' va GT -> do writeArray (up u) b' a' cont a' va b' vb EQ -> do writeArray (up u) a' b' writeArray (rank u) b' (ra + 1) cont b' vb a' va -- | Flatten a disjoint set forest, for faster lookups. flatten :: UnionST s l -> ST s () flatten u = forM_ [0..size u - 1] $ lookup' u
haskell-rewriting/union-find-array
src/Data/Union/ST.hs
Haskell
mit
4,700
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE RankNTypes #-} module Crud.Core where -- import Data.Generics import qualified Language.Haskell.TH as TH -- import Language.Haskell.TH.Quote -- import Data.Data import Import import Yesod.Form.Bootstrap3 import Text.Blaze {- Este conjunto de operaciones permite al programador realizar las operaciones de crear -} getNewRoute :: String -> String -> TH.Q [TH.Dec] getNewRoute name formName = do let method = TH.mkName $ "get" ++ name ++ "NewR" getNew name formName method getNewMethod :: String -> String -> TH.Q [TH.Dec] getNewMethod name formName = do let method = TH.mkName $ "get" ++ name ++ "New" getNew name formName method postNewRoute :: String -> String -> String -> TH.Q [TH.Dec] postNewRoute name formName redirectName = do let method = TH.mkName $ "post" ++ name ++ "NewR" postNew name formName redirectName method postNewMethod :: String -> String -> String -> TH.Q [TH.Dec] postNewMethod name formName redirectName = do let method = TH.mkName $ "post" ++ name ++ "New" postNew name formName redirectName method {- Este conjunto de operaciones permite al programador realizar las operaciones de Editar -} getEditRoute :: String -> String -> TH.Q [TH.Dec] getEditRoute name formName = do let method = TH.mkName $ "get" ++ name ++ "EditR" getEdit name formName method getEditMethod :: String -> String -> TH.Q [TH.Dec] getEditMethod name formName = do let method = TH.mkName $ "get" ++ name ++ "Edit" getEdit name formName method postEditRoute :: String -> String -> String -> TH.Q [TH.Dec] postEditRoute name formName redirectName = do let method = TH.mkName $ "post" ++ name ++ "EditR" postEdit name formName redirectName method postEditMethod :: String -> String -> String -> TH.Q [TH.Dec] postEditMethod name formName redirectName = do let method = TH.mkName $ "post" ++ name ++ "Edit" postEdit name formName redirectName method {- Este conjunto de operaciones permite al programador realizar las operaciones de eliminar -} deleteCrudRoute :: String -> String -> TH.Q [TH.Dec] deleteCrudRoute name redirectName = do let method = TH.mkName $ "delete" ++ name ++ "DeleteR" deleteCrud name redirectName method deleteCrudMethod :: String -> String -> TH.Q [TH.Dec] deleteCrudMethod name redirectName = do let method = TH.mkName $ "delete" ++ name ++ "Delete" deleteCrud name redirectName method {- Este conjunto de operaciones permite al programador realizar las operaciones de listar -} listCrudRoute :: String -> String -> TH.Q [TH.Dec] listCrudRoute name fieldListName = do let method = TH.mkName $ "get" ++ name ++ "ListR" listCrud name fieldListName method listCrudMethod :: String -> String -> TH.Q [TH.Dec] listCrudMethod name fieldListName = do let method = TH.mkName $ "get" ++ name ++ "List" listCrud name fieldListName method {- Este conjunto de operaciones desarrolla la logica de los hamlet -} getNew :: String -> String -> TH.Name -> TH.Q [TH.Dec] getNew name formName method = do let form = TH.varE $ TH.mkName formName action = TH.conE $ TH.mkName $ name ++ "NewR" body = [| do (widget, encoding) <- generateFormPost $ renderBootstrap3 BootstrapBasicForm $ $form Nothing defaultLayout $ do let actionR = $action formHamlet widget encoding actionR |] typ <- TH.sigD method [t| HandlerT App IO Html |] fun <- TH.funD method [TH.clause [] (TH.normalB body) []] return [typ,fun] postNew :: String -> String -> String -> TH.Name -> TH.Q [TH.Dec] postNew name formName redirectName method = do let form = TH.varE $ TH.mkName formName action = TH.conE $ TH.mkName $ name ++ "NewR" redirectAction = TH.conE $ TH.mkName redirectName body = [| do ((result,widget), encoding) <- runFormPost $ renderBootstrap3 BootstrapBasicForm $ $form Nothing case result of FormSuccess entity -> do _ <- runDB $ insert entity redirect $redirectAction _ -> defaultLayout $ do let actionR = $action formHamlet widget encoding actionR|] typ <- TH.sigD method [t| HandlerT App IO Html |] fun <- TH.funD method [TH.clause [] (TH.normalB body) []] return [typ,fun] getEdit :: String -> String -> TH.Name -> TH.Q [TH.Dec] getEdit name formName method = do entityName <- TH.newName "eId" let form = TH.varE $ TH.mkName formName action = TH.conE $ TH.mkName $ name ++ "EditR" entityId = TH.varE entityName entityParam = TH.varP entityName entityType = TH.conT $ TH.mkName $ name ++ "Id" body = [| do entity <- runDB $ get404 $entityId (widget, encoding) <- generateFormPost $ renderBootstrap3 BootstrapBasicForm $ $form (Just entity) defaultLayout $ do let actionR = $action $entityId formHamlet widget encoding actionR |] typ <- TH.sigD method [t| $entityType -> HandlerT App IO Html |] fun <- TH.funD method [TH.clause [entityParam] (TH.normalB body) []] return [typ,fun] postEdit :: String -> String -> String -> TH.Name -> TH.Q [TH.Dec] postEdit name formName redirectName method= do entityName <- TH.newName "eId" let form = TH.varE $ TH.mkName formName action = TH.conE $ TH.mkName $ name ++ "EditR" entityId = TH.varE entityName entityParam = TH.varP entityName entityType = TH.conT $ TH.mkName $ name ++ "Id" redirectAction = TH.conE $ TH.mkName redirectName body = [| do entity <- runDB $ get404 $entityId ((result,widget), encoding) <- runFormPost $ renderBootstrap3 BootstrapBasicForm $ $form (Just entity) case result of FormSuccess resultForm -> do _ <- runDB $ replace $entityId resultForm redirect $redirectAction _ -> defaultLayout $ do let actionR = $action $entityId formHamlet widget encoding actionR |] typ <- TH.sigD method [t| $entityType -> HandlerT App IO Html |] fun <- TH.funD method [TH.clause [entityParam] (TH.normalB body) []] return [typ,fun] deleteCrud :: String -> String -> TH.Name -> TH.Q [TH.Dec] deleteCrud name redirectName method= do entityName <- TH.newName "eId" let entityId = TH.varE entityName entityParam = TH.varP entityName entityType = TH.conT $ TH.mkName $ name ++ "Id" redirectAction = TH.conE $ TH.mkName redirectName body = [| do runDB $ delete $entityId redirect $redirectAction |] typ <- TH.sigD method [t| $entityType -> HandlerT App IO Html |] fun <- TH.funD method [TH.clause [entityParam] (TH.normalB body) []] return [typ,fun] listCrud :: String -> String -> TH.Name -> TH.Q [TH.Dec] listCrud name fieldListName method= do let fieldList = TH.varE $ TH.mkName fieldListName newAction = TH.conE $ TH.mkName (name ++ "NewR") editAction = TH.conE $ TH.mkName (name ++ "EditR") deleteAction = TH.conE $ TH.mkName (name ++ "DeleteR") body = [| do list <- runDB $ selectList [] [] defaultLayout $ do listHamlet list $fieldList $newAction $editAction $deleteAction toWidgetBody deleteJulius|] typ <- TH.sigD method [t| HandlerT App IO Html |] fun <- TH.funD method [TH.clause [] (TH.normalB body) []] return [typ,fun] {- Este conjunto de operaciones general lo interfaz para crear editar y listar y el javascript para eliminar -} formHamlet :: forall site (m :: * -> *) a a1. (ToMarkup a, MonadThrow m, MonadBaseControl IO m, MonadIO m, ToWidget site a1) => a1 -> a -> Route site -> WidgetT site m () formHamlet widget encoding actionR = [whamlet| <div .container> <form method=post action=@{actionR} encType=#{encoding}> <div .row> ^{widget} <div .row .clearfix .visible-xs-block> <button .btn .btn-success> <span .glyphicon .glyphicon-floppy-saved> submit |] listHamlet :: forall site (m :: * -> *) (t :: * -> *) t1 a. (ToMarkup a, MonadThrow m, MonadBaseControl IO m, MonoFoldable (t (Entity t1)), MonadIO m, Foldable t) => t (Entity t1) -> (t1 -> a) -> Route site -> (Key t1 -> Route site) -> (Key t1 -> Route site) -> WidgetT site m () listHamlet list identificateAtribute new edit deleteRoute= [whamlet| <div> <h1> DATA $if null list <p> There are no data $else <table .table .table-responsive .table-hover> <thead> <th> identificate <th> edit <th> delete $forall Entity entityId entity <- list <tbody> <tr> <td> #{identificateAtribute entity} <td > <button onclick=deletePost('@{deleteRoute entityId}') .btn .btn-danger> <span .glyphicon .glyphicon-trash> delete <td> <a href=@{edit entityId} .btn .btn-warning .pull-right> <span .glyphicon .glyphicon-edit> edit <a href=@{new} .btn .btn-primary .pull-right> <span .glyphicon .glyphicon-plus> create |] deleteJulius :: forall url. JavascriptUrl url deleteJulius = [julius| function deletePost(deleteUrl) { $.ajax({ url: deleteUrl, type: 'DELETE', success: function(result) { location.reload(); } }); } |] -- formParam :: [String] -> [(TH.Exp, TH.Pat,TH.Type)] {- formParam [] = [] formParam (x:[]) = do entityName <- TH.newName $ "e" ++ x let entityId = TH.varE entityName entityParam = TH.varP entityName entityType = TH.conT $ TH.mkName $ x [(entityId,entityParam,entityType)] formParam (x:xs) = [] -}
jairoGilC/Yesod-CRUD-Generator
Crud/Core.hs
Haskell
mit
10,805
module GUBS.Solver.Formula where import Data.Foldable (toList) import GUBS.Algebra data Atom e = Geq e e | Eq e e deriving (Functor, Foldable, Traversable) data BoolLit l = BoolLit l | NegBoolLit l deriving (Functor, Foldable, Traversable) -- TODO gadtify data Formula l e = Top | Bot | Lit (BoolLit l) | Atom (Atom e) | Or (Formula l e) (Formula l e) | And (Formula l e) (Formula l e) | Iff (Formula l e) (Formula l e) | LetB (Formula l e) (l -> Formula l e) subst :: (Atom e -> Formula l e') -> Formula l e -> Formula l e' subst _ Top = Top subst _ Bot = Bot subst _ (Lit l) = Lit l subst f (Atom a) = f a subst f (Or e1 e2) = Or (subst f e1) (subst f e2) subst f (And e1 e2) = And (subst f e1) (subst f e2) subst f (LetB e1 e2) = LetB (subst f e1) (subst f . e2) subst f (Iff e1 e2) = Iff (subst f e1) (subst f e2) literal :: l -> Formula l e literal = Lit . BoolLit atoms :: Formula l e -> [Atom e] atoms (Atom a) = [a] atoms Top = [] atoms Bot = [] atoms Lit{} = [] atoms (Or f1 f2) = atoms f1 ++ atoms f2 atoms (And f1 f2) = atoms f1 ++ atoms f2 atoms (Iff f1 f2) = atoms f1 ++ atoms f2 atoms (LetB f1 f2) = atoms f1 ++ atoms (f2 undefined) negLiteral :: l -> Formula l e negLiteral = Lit . NegBoolLit gtA,eqA,geqA :: (IsNat e, Additive e) => e -> e -> Formula l e gtA e1 e2 = Atom (Geq e1 (e2 .+ fromNatural 1)) eqA e1 e2 = Atom (Eq e1 e2) geqA e1 e2 = Atom (Geq e1 e2) smtTop, smtBot :: Formula b e smtTop = Top smtBot = Bot smtBool :: Bool -> Formula b e smtBool True = Top smtBool False = Bot -- smtNot :: (IsNat e, Additive e) => Formula l e -> Formula l e -- smtNot Top = Bot -- smtNot Bot = Top -- smtNot (Lit (BoolLit l)) = smtNot (Lit (NegBoolLit l)) -- smtNot (Lit (NegBoolLit l)) = smtNot (Lit (BoolLit l)) -- smtNot (Atom (Geq e1 e2)) = e2 `gtA` e1 -- smtNot (Atom (Eq e1 e2)) = Or (e1 `gtA` e2) (e2 `gtA` e1) -- smtNot (Or f1 f2) = And (smtNot f1) (smtNot f2) -- smtNot (And f1 f2) = Or (smtNot f1) (smtNot f2) -- smtNot (Iff f1 f2) = Iff (smtNot f1) f2 -- smtNot (LetB f1 f2) = LetB f1 (smtNot . f2) smtAnd, smtOr :: Formula l e -> Formula l e -> Formula l e Top `smtAnd` f2 = f2 f1 `smtAnd` Top = f1 Bot `smtAnd` _ = Bot _ `smtAnd` Bot = Bot f1 `smtAnd` f2 = And f1 f2 Bot `smtOr` f2 = f2 f1 `smtOr` Bot = f1 Top `smtOr` _ = Top _ `smtOr` Top = Top f1 `smtOr` f2 = Or f1 f2 smtBigOr, smtBigAnd :: [Formula l e] -> Formula l e smtBigOr = foldr smtOr smtBot smtBigAnd = foldr smtAnd smtTop smtAll, smtAny :: Foldable t => (a -> Formula l e) -> t a -> Formula l e smtAll f t = smtBigAnd [ f a | a <- toList t] smtAny f t = smtBigOr [ f a | a <- toList t] letB :: Formula l e -> (l -> Formula l e) -> Formula l e letB = LetB letB' :: [Formula l e] -> ([l] -> Formula l e) -> Formula l e letB' = walk [] where walk ls [] f = f (reverse ls) walk ls (e:es) f = LetB e (\ l -> walk (l:ls) es f)
mzini/gubs
src/GUBS/Solver/Formula.hs
Haskell
mit
2,876
-- The sum of the squares of the first ten natural numbers is, -- 1^2 + 2^2 + ... + 10^2 = 385 -- The square of the sum of the first ten natural numbers is, -- (1 + 2 + ... + 10)^2 = 55^2 = 3025 -- Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. -- Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. calc :: Integer calc = ((sum [1..100]) ^ 2) - (sum [x^2 | x <- [1..100]]) main :: IO () main = print calc
daniel-beard/projecteulerhaskell
Problems/p6.hs
Haskell
mit
565
data MyType = MyType deriving (Show)
zhangjiji/real-world-haskell
ch6/ch6.hs
Haskell
mit
49
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.EXTsRGB (pattern SRGB_EXT, pattern SRGB_ALPHA_EXT, pattern SRGB8_ALPHA8_EXT, pattern FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT, EXTsRGB, castToEXTsRGB, gTypeEXTsRGB) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums pattern SRGB_EXT = 35904 pattern SRGB_ALPHA_EXT = 35906 pattern SRGB8_ALPHA8_EXT = 35907 pattern FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT = 33296
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/EXTsRGB.hs
Haskell
mit
1,204
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.HTMLEmbedElement (js_getSVGDocument, getSVGDocument, js_setAlign, setAlign, js_getAlign, getAlign, js_setHeight, setHeight, js_getHeight, getHeight, js_setName, setName, js_getName, getName, js_setSrc, setSrc, js_getSrc, getSrc, js_setType, setType, js_getType, getType, js_setWidth, setWidth, js_getWidth, getWidth, HTMLEmbedElement, castToHTMLEmbedElement, gTypeHTMLEmbedElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"getSVGDocument\"]()" js_getSVGDocument :: HTMLEmbedElement -> IO (Nullable SVGDocument) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.getSVGDocument Mozilla HTMLEmbedElement.getSVGDocument documentation> getSVGDocument :: (MonadIO m) => HTMLEmbedElement -> m (Maybe SVGDocument) getSVGDocument self = liftIO (nullableToMaybe <$> (js_getSVGDocument (self))) foreign import javascript unsafe "$1[\"align\"] = $2;" js_setAlign :: HTMLEmbedElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.align Mozilla HTMLEmbedElement.align documentation> setAlign :: (MonadIO m, ToJSString val) => HTMLEmbedElement -> val -> m () setAlign self val = liftIO (js_setAlign (self) (toJSString val)) foreign import javascript unsafe "$1[\"align\"]" js_getAlign :: HTMLEmbedElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.align Mozilla HTMLEmbedElement.align documentation> getAlign :: (MonadIO m, FromJSString result) => HTMLEmbedElement -> m result getAlign self = liftIO (fromJSString <$> (js_getAlign (self))) foreign import javascript unsafe "$1[\"height\"] = $2;" js_setHeight :: HTMLEmbedElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.height Mozilla HTMLEmbedElement.height documentation> setHeight :: (MonadIO m, ToJSString val) => HTMLEmbedElement -> val -> m () setHeight self val = liftIO (js_setHeight (self) (toJSString val)) foreign import javascript unsafe "$1[\"height\"]" js_getHeight :: HTMLEmbedElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.height Mozilla HTMLEmbedElement.height documentation> getHeight :: (MonadIO m, FromJSString result) => HTMLEmbedElement -> m result getHeight self = liftIO (fromJSString <$> (js_getHeight (self))) foreign import javascript unsafe "$1[\"name\"] = $2;" js_setName :: HTMLEmbedElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.name Mozilla HTMLEmbedElement.name documentation> setName :: (MonadIO m, ToJSString val) => HTMLEmbedElement -> val -> m () setName self val = liftIO (js_setName (self) (toJSString val)) foreign import javascript unsafe "$1[\"name\"]" js_getName :: HTMLEmbedElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.name Mozilla HTMLEmbedElement.name documentation> getName :: (MonadIO m, FromJSString result) => HTMLEmbedElement -> m result getName self = liftIO (fromJSString <$> (js_getName (self))) foreign import javascript unsafe "$1[\"src\"] = $2;" js_setSrc :: HTMLEmbedElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.src Mozilla HTMLEmbedElement.src documentation> setSrc :: (MonadIO m, ToJSString val) => HTMLEmbedElement -> val -> m () setSrc self val = liftIO (js_setSrc (self) (toJSString val)) foreign import javascript unsafe "$1[\"src\"]" js_getSrc :: HTMLEmbedElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.src Mozilla HTMLEmbedElement.src documentation> getSrc :: (MonadIO m, FromJSString result) => HTMLEmbedElement -> m result getSrc self = liftIO (fromJSString <$> (js_getSrc (self))) foreign import javascript unsafe "$1[\"type\"] = $2;" js_setType :: HTMLEmbedElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.type Mozilla HTMLEmbedElement.type documentation> setType :: (MonadIO m, ToJSString val) => HTMLEmbedElement -> val -> m () setType self val = liftIO (js_setType (self) (toJSString val)) foreign import javascript unsafe "$1[\"type\"]" js_getType :: HTMLEmbedElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.type Mozilla HTMLEmbedElement.type documentation> getType :: (MonadIO m, FromJSString result) => HTMLEmbedElement -> m result getType self = liftIO (fromJSString <$> (js_getType (self))) foreign import javascript unsafe "$1[\"width\"] = $2;" js_setWidth :: HTMLEmbedElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.width Mozilla HTMLEmbedElement.width documentation> setWidth :: (MonadIO m, ToJSString val) => HTMLEmbedElement -> val -> m () setWidth self val = liftIO (js_setWidth (self) (toJSString val)) foreign import javascript unsafe "$1[\"width\"]" js_getWidth :: HTMLEmbedElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement.width Mozilla HTMLEmbedElement.width documentation> getWidth :: (MonadIO m, FromJSString result) => HTMLEmbedElement -> m result getWidth self = liftIO (fromJSString <$> (js_getWidth (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/HTMLEmbedElement.hs
Haskell
mit
6,343
module GetOpt.Declarative.UtilSpec (spec) where import Prelude () import Helper import System.Console.GetOpt import GetOpt.Declarative.Util spec :: Spec spec = do describe "mkUsageInfo" $ do it "restricts output size to 80 characters" $ do let options = [ Option "" ["color"] (NoArg ()) (unwords $ replicate 3 "some very long and verbose help text") ] mkUsageInfo "" options `shouldBe` unlines [ "" , " --color some very long and verbose help text some very long and verbose" , " help text some very long and verbose help text" ] it "condenses help for --no-options" $ do let options = [ Option "" ["color"] (NoArg ()) "some help" , Option "" ["no-color"] (NoArg ()) "some other help" ] mkUsageInfo "" options `shouldBe` unlines [ "" , " --[no-]color some help" ]
hspec/hspec
hspec-core/test/GetOpt/Declarative/UtilSpec.hs
Haskell
mit
987