code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Main (main) where import qualified Text.Uniqhash as U import System.IO main :: IO () main = do hSetBuffering stdin LineBuffering hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering U.main
sordina/uniqhash
Uniqhash.hs
mit
224
0
7
39
66
34
32
9
1
{-# LANGUAGE DataKinds #-} module Data.FixedSize.MatrixSpec (spec) where import Test.Hspec import Data.Utils spec :: Spec spec = do mulSpec rowSpec columnSpec indexSpec transposeSpec apSpec generateSpec mulSpec :: Spec mulSpec = describe "(<%%>)" $ it "should multiply a matrix by a vector" $ do let v = generate succ :: Vector 3 Int m <%%> v `shouldBe` cons 14 (cons 32 nil) rowSpec :: Spec rowSpec = describe "row" $ do it "should give the specified row of the matrix if the index is valid" $ do row m 0 `shouldBe` (Just $ cons 1 (cons 2 (cons 3 nil))) row m 1 `shouldBe` (Just $ cons 4 (cons 5 (cons 6 nil))) it "should return Nothing for an invalid row index" $ do row m (-1) `shouldBe` Nothing row m 2 `shouldBe` Nothing columnSpec :: Spec columnSpec = describe "column" $ do it "should give the specified column of the matrix if the index is valid" $ do column m 0 `shouldBe` (Just $ cons 1 (cons 4 nil)) column m 2 `shouldBe` (Just $ cons 3 (cons 6 nil)) it "should return Nothing for an invalid column index" $ do column m (-1) `shouldBe` Nothing column m 3 `shouldBe` Nothing indexSpec :: Spec indexSpec = describe "(!?)" $ do it "should give the specified element of the matrix if the index is valid" $ do m !? (0, 0) `shouldBe` Just 1 m !? (1, 2) `shouldBe` Just 6 it "should return Nothing for an invalid index" $ do m !? (2, 0) `shouldBe` Nothing m !? (0, 3) `shouldBe` Nothing transposeSpec :: Spec transposeSpec = describe "transpose" $ it "should transpose the matrix" $ transpose m `shouldBe` generate (\(i, j) -> 3 * j + i + 1) apSpec :: Spec apSpec = describe "(<*>)" $ it "should be component-wise application" $ (-) <$> m <*> m `shouldBe` pure 0 generateSpec :: Spec generateSpec = describe "generate" $ it "should generate a matrix" $ do let n = generate id :: Matrix 1 2 (Int, Int) show n `shouldBe` "Matrix [[(0,0),(0,1)]]" m :: Matrix 2 3 Int m = generate $ \(i, j) -> 3 * i + j + 1 -- 1 2 3 -- 4 5 6
brunjlar/neural
test/Data/FixedSize/MatrixSpec.hs
mit
2,206
0
18
651
750
383
367
57
1
{-# LANGUAGE TypeFamilies, QuasiQuotes, MultiParamTypeClasses, TemplateHaskell, OverloadedStrings, TypeSynonymInstances #-} import Yesod import Commands import Term import Interpreter import System.IO.Unsafe import Data.Text (Text,unpack) import Control.Applicative ((<$>), (<*>)) import Yesod.Form.Jquery import Parse import Debug.Trace import MyError main :: IO () main = warpDebug 3000 Signs data Signs = Signs mkYesod "Signs" [parseRoutes| /expr ExprR POST / RootR GET |] instance Yesod Signs instance YesodJquery Signs instance RenderMessage Signs FormMessage where renderMessage _ _ = defaultFormMessage data InputExpr = InputExpr { getExpr :: Text } deriving Show exprForm :: Html -> MForm Signs Signs (FormResult InputExpr, Widget) exprForm = renderDivs $ InputExpr <$> areq textField "Expr" Nothing string = show (unsafePerformIO (run [Load "opt.signs",Listing ""])) getRootR :: Handler RepHtml getRootR = do -- Generate the form to be displayed (widget, enctype) <- generateFormPost exprForm defaultLayout [whamlet| <p>Enter an expression to evaluate it: <form method=post action=@{ExprR} enctype=#{enctype}> ^{widget} <input type=submit> |] {- getHomeR :: forall sub. GHandler sub a0 RepHtml getHomeR = defaultLayout $ do [whamlet|<h1>#{string}|] -} parseITerm :: InputExpr -> Either ParseError Term parseITerm input = let result = parse term "" (unpack $ getExpr input) in trace ("result " ++ show result) result postExprR :: Handler RepHtml postExprR = do ((result, widget), enctype) <- runFormPost exprForm case result of FormSuccess expr -> defaultLayout [whamlet|<p>#{show $ parseITerm expr}|] _ -> defaultLayout [whamlet| <p>Invalid input, let's try again. <form method=post action=@{ExprR} enctype=#{enctype}> ^{widget} <input type=submit> |]
ChrisBlom/Signs
src/Signs/Main.hs
mit
1,907
0
12
378
412
224
188
41
2
{-# LANGUAGE CPP #-} {- Copyright (C) 2010-2014 John MacFarlane <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.UTF8 Copyright : Copyright (C) 2010-2014 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable UTF-8 aware string IO functions that will work with GHC 6.10, 6.12, or 7. -} module Text.Pandoc.UTF8 ( readFile , writeFile , getContents , putStr , putStrLn , hPutStr , hPutStrLn , hGetContents , toString , fromString , toStringLazy , fromStringLazy , encodePath , decodeArg ) where import System.IO hiding (readFile, writeFile, getContents, putStr, putStrLn, hPutStr, hPutStrLn, hGetContents) #if MIN_VERSION_base(4,6,0) import Prelude hiding (readFile, writeFile, getContents, putStr, putStrLn) #else import Prelude hiding (readFile, writeFile, getContents, putStr, putStrLn) #endif import qualified System.IO as IO import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy as BL import qualified Data.Text.Encoding as T import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL readFile :: FilePath -> IO String readFile f = do h <- openFile (encodePath f) ReadMode hGetContents h writeFile :: FilePath -> String -> IO () writeFile f s = withFile (encodePath f) WriteMode $ \h -> hPutStr h s getContents :: IO String getContents = hGetContents stdin putStr :: String -> IO () putStr s = hPutStr stdout s putStrLn :: String -> IO () putStrLn s = hPutStrLn stdout s hPutStr :: Handle -> String -> IO () hPutStr h s = hSetEncoding h utf8 >> IO.hPutStr h s hPutStrLn :: Handle -> String -> IO () hPutStrLn h s = hSetEncoding h utf8 >> IO.hPutStrLn h s hGetContents :: Handle -> IO String hGetContents = fmap toString . B.hGetContents -- hGetContents h = hSetEncoding h utf8_bom -- >> hSetNewlineMode h universalNewlineMode -- >> IO.hGetContents h -- | Drop BOM (byte order marker) if present at beginning of string. -- Note that Data.Text converts the BOM to code point FEFF, zero-width -- no-break space, so if the string begins with this we strip it off. dropBOM :: String -> String dropBOM ('\xFEFF':xs) = xs dropBOM xs = xs -- | Convert UTF8-encoded ByteString to String, also -- removing '\r' characters. toString :: B.ByteString -> String toString = filter (/='\r') . dropBOM . T.unpack . T.decodeUtf8 fromString :: String -> B.ByteString fromString = T.encodeUtf8 . T.pack -- | Convert UTF8-encoded ByteString to String, also -- removing '\r' characters. toStringLazy :: BL.ByteString -> String toStringLazy = filter (/='\r') . dropBOM . TL.unpack . TL.decodeUtf8 fromStringLazy :: String -> BL.ByteString fromStringLazy = TL.encodeUtf8 . TL.pack encodePath :: FilePath -> FilePath decodeArg :: String -> String #if MIN_VERSION_base(4,4,0) encodePath = id decodeArg = id #else encodePath = B.unpack . fromString decodeArg = toString . B.pack #endif
nickbart1980/pandoc
src/Text/Pandoc/UTF8.hs
gpl-2.0
4,066
0
10
1,023
652
372
280
58
1
-- -- Copyright (c) 2012 Citrix Systems, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- {-# LANGUAGE ScopedTypeVariables, PatternGuards #-} module Firewall ( FirewallConfig (..) , Firewall , createFirewall ) where import Data.Maybe import Data.String import Data.Map (Map) import qualified Data.Map as Map import Data.IORef import qualified Data.Text.Lazy as TL import Control.Applicative import Control.Monad import Control.Concurrent import qualified Control.Exception as E import Text.Printf import Rules import RulesCache import Msg.DBus import Types import Tools.Log import DBus.Message ( Message(..), ReceivedMessage(..), Serial, receivedSerial, receivedSender , MethodCall(..),Signal(..),MethodReturn(..),Error(..), firstSerial, nextSerial ) import DBus.Types ( strBusName, strInterfaceName, strObjectPath, strMemberName, toVariant ) import qualified DBus.Types as DT import Rpc.Core ( Proxy (..), fromVariant, RemoteObject (..), ObjectPath, remote, Dispatcher, mkObjectPath_, Variable (..) ) type Firewall = Msg -> IO Bool data FirewallConfig = FirewallConfig { fireActive :: Bool , fireRules :: RulesCache , fireVerbose :: Bool , fireDirection :: Direction , fireSource :: ArtefactSource , fireDestination :: DomID } -- The dbus received messages are artefacts we can filter upon data MsgAndSource = MAS !ArtefactSource !Msg instance Artefact MsgAndSource where artefactType (MAS _ (Msg ReceivedMethodCall {} _)) = TagMethodCall artefactType (MAS _ (Msg ReceivedMethodReturn {} _)) = TagMethodReturn artefactType (MAS _ (Msg ReceivedSignal {} _)) = TagSignal artefactType (MAS _ (Msg ReceivedError {} _)) = TagError artefactType (MAS _ (Msg ReceivedUnknown {} _)) = undefined artefactSource (MAS src _) = src artefactSender (MAS _ (Msg m _)) = fmap strBusName $ receivedSender m artefactDestination (MAS _ (Msg (ReceivedMethodCall _ _ m) _)) = fmap strBusName $ methodCallDestination m artefactDestination (MAS _ (Msg (ReceivedMethodReturn _ _ m) _)) = fmap strBusName $ methodReturnDestination m artefactDestination (MAS _ (Msg (ReceivedError _ _ m) _)) = fmap strBusName $ errorDestination m artefactDestination (MAS _ (Msg (ReceivedSignal _ _ m) _)) = fmap strBusName $ signalDestination m artefactDestination _ = Nothing artefactInterface (MAS _ (Msg (ReceivedMethodCall _ _ m) _)) = fmap strInterfaceName $ methodCallInterface m artefactInterface (MAS _ (Msg (ReceivedSignal _ _ m) _)) = Just . strInterfaceName $ signalInterface m artefactInterface _ = Nothing artefactMember (MAS _ (Msg (ReceivedMethodCall _ _ m) _)) = Just . strMemberName $ methodCallMember m artefactMember (MAS _ (Msg (ReceivedSignal _ _ m) _)) = Just . strMemberName $ signalMember m artefactMember _ = Nothing artefactPropertyInterface (MAS _ (Msg (ReceivedMethodCall _ _ m) _)) | methodCallInterface m == Just (fromString "org.freedesktop.DBus.Properties") , methodCallMember m `elem` [fromString "Get", fromString "Set", fromString "GetAll"] = case methodCallBody m of (v : _) -> DT.fromVariant v _ -> Nothing artefactPropertyInterface _ = Nothing type PropertyMap = Map (Uuid, String) PropertyValue data PropertyValue = PV_Bool Bool | PV_String String type Env = (Dispatcher, Maybe Uuid, MVar PropertyMap) -- fills additional per-rule data augmentRule :: Env -> Rule -> IO Rule augmentRule (_, Nothing, _) rule = return rule augmentRule (client, Just uuid, pmap) rule@Rule { match = match } = do p <- mapM augmentPropertyMatch (properties match) return $ rule {match = match { properties = p }} where augmentPropertyMatch (PropertyMatchB pname expected _) = PropertyMatchB pname expected . Just . extrBool <$> getCachedValue pname PV_Bool augmentPropertyMatch (PropertyMatchS pname expected _) = PropertyMatchS pname expected . Just . extrString <$> getCachedValue pname PV_String extrBool (PV_Bool v) = v extrBool _ = error "boolean expected" extrString (PV_String v) = v extrString _ = error "string expected" getCachedValue :: (Show a, Variable a) => String -> (a -> PropertyValue) -> IO PropertyValue getCachedValue pname cons = modifyMVar pmap $ \pm -> case Map.lookup (uuid, pname) pm of Just v -> return (pm, v) Nothing -> do -- query current property value via xenmgr access v <- testVm (vmPath uuid) pname debug $ "assuming (" ++ show uuid ++ "," ++ pname ++ ") = " ++ show v return ( Map.insert (uuid,pname) (cons v) pm , cons v ) testVm :: Variable a => ObjectPath -> String -> IO a testVm path = liftM (fromMaybe (error "testVm: bad variant") . fromVariant) . mustSucceed . remote client (xenmgrVmProxy path) "Get" "com.citrix.xenclient.xenmgr.vm.unrestricted" createFirewall :: Dispatcher -> FirewallConfig -> IO Firewall createFirewall client c = do pmap <- newMVar Map.empty return $ \msg@(Msg rm _) -> do let artefact = MAS (fireSource c) msg let domid = sourceDomainID (fireSource c) uuid = sourceUuid (fireSource c) em = TL.pack "<none>" typ = artefactType artefact sndr = fromMaybe em $ artefactSender artefact -- why this is usually null dest = fromMaybe em $ artefactDestination artefact intf = fromMaybe em $ artefactInterface artefact memb = fromMaybe em $ artefactMember artefact reply_serial = case rm of ( ReceivedMethodReturn _ _ m ) -> Just $ methodReturnSerial m ( ReceivedError _ _ m ) -> Just $ errorSerial m _ -> Nothing description rulet = printf "(%d->%d) %s %s { sender='%s' dest='%s' intf='%s' member='%s' serial='%s' reply-to='%s' }" domid (fireDestination c) rulet (show typ) (TL.unpack sndr) (TL.unpack dest) (TL.unpack intf) (TL.unpack memb) (show $ receivedSerial rm) (show reply_serial) access <- if fireActive c && domid /= 0 then testAugmented (fireRules c) (augmentRule (client,uuid,pmap)) artefact (subjectFor (fireDirection c) rm) else return True unless access $ warn $ description "DENY" when (fireVerbose c && access) $ info (description "ALLOW") return access subjectFor :: Direction -> ReceivedMessage -> RuleSubject subjectFor d ReceivedMethodCall {} = RuleSubject d TagMethodCall subjectFor d ReceivedSignal {} = RuleSubject d TagSignal subjectFor d ReceivedMethodReturn {} = RuleSubject d TagMethodReturn subjectFor d ReceivedError {} = RuleSubject d TagError subjectFor d _ = RuleSubject d TagAny xenmgrProxy :: Proxy xenmgrProxy = Proxy obj (fromString "com.citrix.xenclient.xenmgr") where obj = RemoteObject (fromString "com.citrix.xenclient.xenmgr") (fromString "/") xenmgrVmProxy :: ObjectPath -> Proxy xenmgrVmProxy objp = Proxy obj (fromString "org.freedesktop.DBus.Properties") where obj = RemoteObject (fromString "com.citrix.xenclient.xenmgr") objp vmPath :: Uuid -> ObjectPath vmPath uuid = mkObjectPath_ $ fromString "/vm/" `TL.append` TL.map replaceMinus (uuidText uuid) where replaceMinus '-' = '_' replaceMinus x = x mustSucceed :: IO a -> IO a mustSucceed action = action `E.catch` err where err (e :: E.SomeException) = warn ("error: " ++ show e) >> threadDelay (10^6) >> mustSucceed action
OpenXT/manager
rpc-proxy/Firewall.hs
gpl-2.0
8,678
0
19
2,257
2,409
1,246
1,163
147
5
{-# LANGUAGE TemplateHaskell, FlexibleContexts, FlexibleInstances #-} {-# language UndecidableInstances, DeriveDataTypeable #-} {-# language DatatypeContexts #-} module SCS.Data where import Autolib.ToDoc import Autolib.Reader import Autolib.Set import Data.Typeable import Autolib.Xml class ( Ord a, ToDoc a, Reader a, Typeable a, ToDoc [a], Reader [a] ) => InstanceC a instance ( Ord a, ToDoc a, Reader a, Typeable a, ToDoc [a], Reader [a] ) => InstanceC a data ( InstanceC a ) => Instance a = Instance { contents :: [[a]] , max_length :: Int } deriving ( Typeable ) $(derives [makeReader, makeToDoc] [''Instance]) example :: Instance Char example = Instance { contents = [ "ABCABBA", "CBABAC" ] , max_length = 10 } -- Local Variables: -- mode: haskell -- End:
marcellussiegburg/autotool
collection/src/SCS/Data.hs
gpl-2.0
826
10
10
181
251
143
108
-1
-1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} {- | Module : $Header$ Copyright : (c) Felix Gabriel Mance License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable Instances for some of the functions used in OWL 2 -} module OWL2.Function where import OWL2.AS import OWL2.MS import OWL2.Sign import OWL2.Symbols import Data.Maybe import qualified Data.Map as Map import qualified Data.Set as Set {- | this class contains general functions which operate on the ontology document, such as prefix renaming, IRI expansion or Morphism mapping -} class Function a where function :: Action -> AMap -> a -> a data Action = Rename | Expand deriving (Show, Eq, Ord) type StringMap = Map.Map String String type MorphMap = Map.Map Entity IRI data AMap = StringMap StringMap | MorphMap MorphMap deriving (Show, Eq, Ord) maybeDo :: (Function a) => Action -> AMap -> Maybe a -> Maybe a maybeDo t mp = fmap $ function t mp getIri :: EntityType -> IRI -> Map.Map Entity IRI -> IRI getIri ty u = fromMaybe u . Map.lookup (Entity ty u) cutWith :: EntityType -> Action -> AMap -> IRI -> IRI cutWith ty t s iri = cutIRI $ function t s $ Entity ty iri err :: t err = error "operation not allowed" instance Function PrefixMap where function a m oldPs = case m of StringMap mp -> case a of Rename -> foldl (\ ns (pre, ouri) -> Map.insert (Map.findWithDefault pre pre mp) ouri ns) Map.empty $ Map.toList oldPs Expand -> oldPs _ -> err instance Function IRI where function a m qn = case m of StringMap pm -> case a of Rename -> let pre = namePrefix qn in qn { namePrefix = Map.findWithDefault pre pre pm} Expand -> let np = namePrefix qn lp = localPart qn iri = case iriType qn of Full -> qn {expandedIRI = np ++ ":" ++ lp} NodeID -> qn {expandedIRI = lp} _ -> let miri = Map.lookup np $ Map.union pm predefPrefixes in case miri of Just expn -> qn {expandedIRI = expn ++ lp} Nothing -> error $ np ++ ": prefix not found" in setReservedPrefix iri _ -> qn instance Function Sign where function t mp (Sign p1 p2 p3 p4 p5 p6 p7) = case mp of StringMap _ -> Sign (Set.map (function t mp) p1) (Set.map (function t mp) p2) (Set.map (function t mp) p3) (Set.map (function t mp) p4) (Set.map (function t mp) p5) (Set.map (function t mp) p6) (function t mp p7) _ -> err instance Function Entity where function t pm (Entity ty ent) = case pm of StringMap _ -> Entity ty $ function t pm ent MorphMap m -> Entity ty $ getIri ty ent m instance Function Literal where function t pm l = case l of Literal lf (Typed dt) -> Literal lf $ Typed $ cutWith Datatype t pm dt _ -> l instance Function ObjectPropertyExpression where function t s opr = case opr of ObjectProp op -> ObjectProp $ cutWith ObjectProperty t s op ObjectInverseOf op -> ObjectInverseOf $ function t s op instance Function DataRange where function t s dra = case dra of DataType dt ls -> DataType (cutWith Datatype t s dt) $ map (\ (cf, rv) -> (function t s cf, function t s rv)) ls DataJunction jt drl -> DataJunction jt $ map (function t s) drl DataComplementOf dr -> DataComplementOf $ function t s dr DataOneOf ll -> DataOneOf $ map (function t s) ll instance Function ClassExpression where function t s cle = case cle of Expression c -> Expression $ cutWith Class t s c ObjectJunction jt cel -> ObjectJunction jt $ map (function t s) cel ObjectComplementOf ce -> ObjectComplementOf $ function t s ce ObjectOneOf il -> ObjectOneOf $ map (cutWith NamedIndividual t s) il ObjectValuesFrom qt op ce -> ObjectValuesFrom qt (function t s op) $ function t s ce ObjectHasValue op i -> ObjectHasValue (function t s op) $ cutWith NamedIndividual t s i ObjectHasSelf op -> ObjectHasSelf $ function t s op ObjectCardinality (Cardinality ct i op mce) -> ObjectCardinality $ Cardinality ct i (function t s op) $ maybeDo t s mce DataValuesFrom qt dp dr -> DataValuesFrom qt (cutWith DataProperty t s dp) $ function t s dr DataHasValue dp l -> DataHasValue (cutWith DataProperty t s dp) $ function t s l DataCardinality (Cardinality ct i dp mdr) -> DataCardinality $ Cardinality ct i (cutWith DataProperty t s dp) $ maybeDo t s mdr instance Function Annotation where function t s (Annotation al ap av) = Annotation (map (function t s) al) (cutWith AnnotationProperty t s ap) $ function t s av instance Function AnnotationValue where function t s av = case av of AnnValue iri -> AnnValue $ function t s iri AnnValLit l -> AnnValLit $ function t s l instance Function Annotations where function t pm = map (function t pm) -- | only for non-IRI AnnotatedLists instance Function a => Function (AnnotatedList a) where function t s = map (\ (ans, a) -> (map (function t s) ans, function t s a)) -- | only for IRI AnnotatedLists mapAnnList :: EntityType -> Action -> AMap -> AnnotatedList IRI -> AnnotatedList IRI mapAnnList ty t m anl = let ans = map fst anl l = map snd anl in zip (map (function t m) ans) $ map (cutWith ty t m) l instance Function Fact where function t s f = case f of ObjectPropertyFact pn op i -> ObjectPropertyFact pn (function t s op) $ cutWith NamedIndividual t s i DataPropertyFact pn dp l -> DataPropertyFact pn (cutWith DataProperty t s dp) $ function t s l instance Function ListFrameBit where function t s lfb = case lfb of AnnotationBit al -> AnnotationBit $ mapAnnList AnnotationProperty t s al ExpressionBit al -> ExpressionBit $ function t s al ObjectBit al -> ObjectBit $ function t s al DataBit al -> DataBit $ mapAnnList DataProperty t s al IndividualSameOrDifferent al -> IndividualSameOrDifferent $ mapAnnList NamedIndividual t s al DataPropRange al -> DataPropRange $ function t s al IndividualFacts al -> IndividualFacts $ function t s al _ -> lfb instance Function AnnFrameBit where function t s afb = case afb of DatatypeBit dr -> DatatypeBit $ function t s dr ClassDisjointUnion cel -> ClassDisjointUnion $ map (function t s) cel ClassHasKey opl dpl -> ClassHasKey (map (function t s) opl) $ map (cutWith DataProperty t s) dpl ObjectSubPropertyChain opl -> ObjectSubPropertyChain $ map (function t s) opl _ -> afb instance Function FrameBit where function t s fb = case fb of ListFrameBit mr lfb -> ListFrameBit mr $ function t s lfb AnnFrameBit ans afb -> AnnFrameBit (function t s ans) (function t s afb) instance Function Extended where function t mp ex = case ex of Misc ans -> Misc $ function t mp ans SimpleEntity ent -> SimpleEntity $ function t mp ent ClassEntity ce -> ClassEntity $ function t mp ce ObjectEntity op -> ObjectEntity $ function t mp op instance Function Frame where function t mp (Frame ex fbl) = Frame (function t mp ex) (map (function t mp) fbl) instance Function Axiom where function t mp (PlainAxiom ex fb) = PlainAxiom (function t mp ex) (function t mp fb) instance Function Ontology where function t mp (Ontology ouri impList anList f) = Ontology (function t mp ouri) (map (function t mp) impList) (map (function t mp) anList) (map (function t mp) f) instance Function OntologyDocument where function t mp (OntologyDocument pm onto) = OntologyDocument (function t mp pm) (function t mp onto) instance Function RawSymb where function t mp rs = case rs of ASymbol e -> ASymbol $ function t mp e AnUri i -> AnUri $ function t mp i p -> p
nevrenato/HetsAlloy
OWL2/Function.hs
gpl-2.0
8,383
1
26
2,494
2,947
1,430
1,517
175
1
module Probability.Distribution.ExpTransform where import Probability.Random import Probability.Distribution.Normal import Probability.Distribution.Exponential import Probability.Distribution.Gamma import Probability.Distribution.Laplace import Probability.Distribution.Cauchy -- This contains exp-transformed functions expTransform dist@(Distribution name d q s r) = Distribution name' pdf' q' s' r' where pdf' x = do ds <- d x return $ (doubleToLogDouble 1.0/ doubleToLogDouble x):ds q' = exp . q s' = do v <- dist return $ exp v r' = expTransformRange r name' = "log_"++name log_normal mu sigma = expTransform $ normal mu sigma log_exponential mu = expTransform $ exponential mu log_gamma a b = expTransform $ gamma a b log_laplace m s = expTransform $ laplace m s log_cauchy m s = expTransform $ cauchy m s
bredelings/BAli-Phy
haskell/Probability/Distribution/ExpTransform.hs
gpl-2.0
852
0
13
155
262
134
128
21
1
-- grid is a game written in Haskell -- Copyright (C) 2018 [email protected] -- -- This file is part of grid. -- -- grid is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- grid is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with grid. If not, see <http://www.gnu.org/licenses/>. -- module File.IOS ( fileStaticData, fileDynamicData, fileUser, fileTmp, ) where import MyPrelude import Foreign.Ptr import Foreign.C.Types import Foreign.C.String import Foreign.Marshal.Array -- | fixme: do not use fixed arrays, instead peek foreign values -- as in MEnv.Players.IOS ! valueMaxFilePathLength :: UInt valueMaxFilePathLength = 255 foreign import ccall unsafe "ios_fileStaticData" ios_fileStaticData :: CString -> CString -> CUInt -> IO CUInt -- | full path to read-only application data fileStaticData :: FilePath -> IO FilePath fileStaticData path = withCString path $ \ptrNameExt -> allocaArray0 (fI valueMaxFilePathLength) $ \ptrDst -> do ios_fileStaticData ptrNameExt ptrDst (fI $ valueMaxFilePathLength + 1) >>= \value -> case value of 0 -> error $ "fileStaticData: no file '" ++ path ++ "'" _ -> peekCString ptrDst foreign import ccall unsafe "ios_fileDynamicData" ios_fileDynamicData :: CString -> CString -> CUInt -> IO CUInt -- | full path to read-write application data fileDynamicData :: FilePath -> IO FilePath fileDynamicData path = withCString path $ \ptrNameExt -> allocaArray0 (fI valueMaxFilePathLength) $ \ptrDst -> do ios_fileDynamicData ptrNameExt ptrDst (fI $ valueMaxFilePathLength + 1) >>= \value -> case value of 0 -> error $ "fileDynamicData: no file '" ++ path ++ "'" _ -> peekCString ptrDst foreign import ccall unsafe "ios_fileUser" ios_fileUser :: CString -> CString -> CUInt -> IO CUInt -- | full path to user file directory fileUser :: FilePath -> IO FilePath fileUser path = withCString path $ \ptrNameExt -> allocaArray0 (fI valueMaxFilePathLength) $ \ptrDst -> do ios_fileUser ptrNameExt ptrDst (fI valueMaxFilePathLength) >>= \value -> case value of 0 -> error $ "fileUser: no file '" ++ path ++ "'" _ -> peekCString ptrDst foreign import ccall unsafe "ios_fileTmp" ios_fileTmp :: CString -> CString -> CUInt -> IO CUInt -- | full path to tmp file directory fileTmp :: FilePath -> IO FilePath fileTmp path = withCString path $ \ptrNameExt -> allocaArray0 (fI valueMaxFilePathLength) $ \ptrDst -> do ios_fileTmp ptrNameExt ptrDst (fI valueMaxFilePathLength) >>= \value -> case value of 0 -> error $ "fileTmp: no file '" ++ path ++ "'" _ -> peekCString ptrDst
karamellpelle/grid
source/File/IOS.hs
gpl-3.0
3,412
0
18
926
631
335
296
57
2
module Types (Compiled(..)) where import System.IO data Compiled = Compiled FilePath | CompileError String
tehmatt/Chankillo
src/types.hs
gpl-3.0
115
0
6
22
32
20
12
4
0
module Eval (evalExpr) where import ErrorHandling (AssemblyState(..)) import Parser (Expr(..), getOp) import Pass2 (SymbolTable) import Data.Bits (complement) import Text.ParserCombinators.Parsec (parse) evalExpr :: SymbolTable -> Int -> Expr -> AssemblyState Integer evalExpr symTable lineNum e = case e of Str s -> fail' $ "unexpected string literal" Symbol s -> case lookup s symTable of Nothing -> fail' $ "undefined symbol " ++ s Just v -> eval v Register r -> fail' $ "unexpected register " ++ (show r) Num _ n -> return n OffsetBase _ _ -> fail' "unexpected offset base pair" Negate e' -> do x <- eval e' return $ -x Comp e' -> do x <- eval e' return $ complement x BinOp e1 e2 op -> do e1' <- eval e1 e2' <- eval e2 return $ (getOp op) e1' e2' where eval = evalExpr symTable lineNum fail' s = Error s (Just lineNum)
adamsmasher/EMA
Eval.hs
gpl-3.0
951
0
13
277
348
170
178
24
9
{- All the Flow You’d Expect Python knows the usual control flow statements that other languages speak — if, for, while and range — with some of its own twists, of course. # For loop on a list >>> numbers = [2, 4, 6, 8] >>> product = 1 >>> for number in numbers: ... product = product * number ... >>> print('The product is:', product) The product is: 384 -} main = do -- For loop on a list let numbers = [2, 4, 6, 8] product <- var 1 for numbers `by` \number -> product *= number print("The product is:", product) -- The product is: 384
cblp/python5
examples/control.hs
gpl-3.0
626
0
10
190
73
39
34
6
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DuplicateRecordFields #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} ------------------------------------------------------------------------------- -- | -- Module : OpenSandbox.Protocol.Types -- Copyright : (c) 2016 Michael Carpenter -- License : GPL3 -- Maintainer : Michael Carpenter <[email protected]> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module OpenSandbox.Protocol.Types ( Chat (..) , Short , Angle , Position , Session (..) , ProtocolState (..) , Difficulty (..) , Dimension (..) , GameMode (..) , Animation (..) , BlockAction (..) , InstrumentType (..) , NotePitch (..) , PistonState (..) , PistonDirection (..) , BossBarAction (..) , EntityMetadataEntry (..) , ValueField (..) , EntityMetadata , MetadataType (..) , PlayerProperty (..) , PlayerListEntries (..) , PlayerListAdd (..) , PlayerListUpdateGameMode (..) , PlayerListUpdateLatency (..) , PlayerListUpdateDisplayName (..) , PlayerListRemovePlayer (..) , Statistic (..) , StatusPayload (..) , Players (..) , Version (..) , Description (..) , BlockChange (..) , Icon (..) , CombatEvent (..) , WorldBorderAction (..) , TeamMode (..) , TitleAction (..) , Slot (..) , SlotData (..) , EntityProperty (..) , VarInt , VarLong , UpdateBlockEntityAction (..) , EntityStatus (..) , GameChangeReason (..) , NBT (..) , UpdatedColumns (..) , UpdateScoreAction (..) , UseEntityType (..) , EntityHand (..) , ScoreboardMode (..) , mkSlot , encodeStatusPayload , putText , getText , putVarInt , getVarInt , putVarLong , getVarLong , putEntityMetadata , getEntityMetadata , putNetcodeByteString , getNetcodeByteString , putPosition , getPosition , putAngle , getAngle , putUUID , getUUID , putUUID' , getUUID' ) where import Control.DeepSeq import Control.Monad import Crypto.PubKey.RSA import qualified Data.Aeson as A import Data.Bits import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import Data.Int import Data.List import Data.Maybe import Data.NBT import Data.Serialize import qualified Data.Text as T import Data.Text.Encoding import Data.UUID import qualified Data.Vector as V import Data.Word import GHC.Generics import Prelude hiding (max) type Short = Int16 putText :: T.Text -> Put putText t = do putVarInt . B.length . encodeUtf8 $ t putByteString . encodeUtf8 $ t getText :: Get T.Text getText = do ln <- getVarInt bs <- getBytes ln return $ decodeUtf8 bs data Chat = Chat { text :: T.Text } deriving (Show,Eq,Generic) instance A.ToJSON Chat instance A.FromJSON Chat instance Serialize Chat where put = putNetcodeByteString . BL.toStrict . A.encode get = do bs <- getNetcodeByteString case A.eitherDecodeStrict bs of Left err -> fail err Right chat -> return chat type VarInt = Int putVarInt :: Int -> Put putVarInt i | i < 0 = putVarInt (abs i + (2^31 :: Int)) | i < 0x80 = putWord8 (fromIntegral i) | otherwise = putWord8 (fromIntegral (i .&. 0x7F) .|. 0x80) >> putVarInt (i `shiftR` 7) getVarInt :: Get Int getVarInt = do w <- getWord8 if testBit w 7 then do result <- go 7 (fromIntegral (w .&. 0x7F)) if result <= (2^31) then return result else return (negate (result - (2^31))) else return (fromIntegral w) where go n val = do w' <- getWord8 if testBit w' 7 then go (n+7) (val .|. ((fromIntegral (w' .&. 0x7F)) `shiftL` n)) else return (val .|. ((fromIntegral w') `shiftL` n)) type VarLong = Int64 putVarLong :: Int64 -> Put putVarLong i | i < 0 = putVarLong (abs i + (2^62 :: Int64)) | i < 0x80 = putWord8 (fromIntegral i) | otherwise = putWord8 (fromIntegral (i .&. 0x7F) .|. 0x80) >> putVarLong (i `shiftR` 7) getVarLong :: Get Int64 getVarLong = do w <- getWord8 if testBit w 7 then do result <- go 7 (fromIntegral (w .&. 0x7F)) if result <= (2^62) then return result else return (negate (result - (2^62 :: Int64))) else return (fromIntegral w) where go n val = do w' <- getWord8 if testBit w' 7 then go (n+7) (val .|. (fromIntegral (w' .&. 0x7F) `shiftL` n)) else return (val .|. (fromIntegral w' `shiftL` n)) type EntityMetadata = V.Vector EntityMetadataEntry putEntityMetadata :: EntityMetadata -> Put putEntityMetadata e = do putVarInt . V.length $ e V.mapM_ put e getEntityMetadata :: Get EntityMetadata getEntityMetadata = do ln <- getVarInt V.replicateM ln get data EntityMetadataEntry = MetadataEnd | Entry !Word8 !Int8 !MetadataType deriving (Show,Eq,Generic) instance Serialize EntityMetadataEntry where put MetadataEnd = do putWord8 0xff put (Entry i t v) = do putWord8 i put t put v get = do i <- getWord8 case i of 0xff -> return MetadataEnd _ -> do t <- getInt8 v <- get return $ Entry i t v data MetadataType = MetadataByte | MetadataVarInt | MetadataFloat | MetadataString | MetadataChat | MetadataSlot | MetadataBool | MetadataRotation | MetadataPosition | MetadataOptPosition | MetadataDirection | MetadataOptUUID | MetadataBlockID deriving (Show,Eq,Enum,Generic) instance Serialize MetadataType where put m = putWord8 (toEnum . fromEnum $ m) get = (toEnum . fromEnum) <$> getWord8 data Slot = Slot { blockID :: !Int16 , slotData :: !(Maybe SlotData) } deriving (Show,Eq,Generic) instance Serialize Slot where put (Slot bid sd) = do put bid case bid of (-1) -> return () _ -> do let sd' = fromJust sd put sd' get = do blockID <- getInt16be case blockID of (-1) -> return $ Slot blockID Nothing _ -> do slotData <- get return $ Slot blockID (Just slotData) data SlotData = SlotData { itemCount :: !Int8 , itemDamage :: !Int16 , nbt :: !NBT } deriving (Show,Eq,Generic) instance Serialize SlotData where put (SlotData itemCount' itemDamage' nbt') = do put itemCount' put itemDamage' put nbt' get = SlotData <$> get <*> get <*> get mkSlot :: Int16 -> Int8 -> Int16 -> NBT -> Slot mkSlot blockID itemCount itemDamage nbt = case blockID of -1 -> Slot blockID Nothing _ -> Slot blockID (Just (SlotData itemCount itemDamage nbt)) type Position = Word64 putPosition :: Position -> Put putPosition = putWord64be getPosition :: Get Position getPosition = getWord64be type Angle = Word8 putAngle :: Angle -> Put putAngle = putWord8 getAngle :: Get Angle getAngle = getWord8 putUUID :: UUID -> Put putUUID uuid = putText (toText uuid) getUUID :: Get UUID getUUID = do txt <- getText case fromText txt of Just uuid -> return uuid Nothing -> fail "Error: Could not deserialize UUID!" putUUID' :: UUID -> Put putUUID' uuid = putByteString (BL.toStrict . toByteString $ uuid) getUUID' :: Get UUID getUUID' = do bs <- getBytes 16 case (fromByteString . BL.fromStrict $ bs) of Just uuid -> return uuid Nothing -> fail "Error: Could not decode UUID!" putNetcodeByteString :: B.ByteString -> Put putNetcodeByteString b = do putVarInt . B.length $ b putByteString b getNetcodeByteString :: Get B.ByteString getNetcodeByteString = do ln <- getVarInt bs <- getBytes ln return bs data Animation = SwingArm | TakeDamage | LeaveBed | EatFood | CriticalEffect | MagicCriticalEffect deriving (Show,Eq,Enum,Generic) instance Serialize Animation where put = putWord8 . toEnum . fromEnum get = (toEnum . fromEnum) <$> getWord8 data BlockAction = NoteBlockAction !InstrumentType !NotePitch | PistonBlockAction !PistonState !PistonDirection | ChestBlockAction !Word8 deriving (Show,Eq,Generic) instance Serialize BlockAction where put (NoteBlockAction i n) = do putWord8 . toEnum . fromEnum $ i putWord8 . toEnum . fromEnum $ n putVarInt 25 put (PistonBlockAction ps pd) = do putWord8 . toEnum . fromEnum $ ps putWord8 . toEnum . fromEnum $ pd putVarInt 33 put (ChestBlockAction b) = do putWord8 1 putWord8 b putVarInt 54 get = do byte1 <- getWord8 byte2 <- getWord8 blockType <- getVarInt case blockType of 25 -> return $ NoteBlockAction (toEnum . fromEnum $ byte1) (toEnum . fromEnum $ byte2) 33 -> return $ PistonBlockAction (toEnum . fromEnum $ byte1) (toEnum . fromEnum $ byte2) 54 -> return $ ChestBlockAction byte2 err -> fail $ "Error: invalid BlockAction type: " ++ show err data InstrumentType = Harp | DoubleBass | SnareDrum | Clicks | BassDrum deriving (Show,Eq,Enum,Generic) data NotePitch = FSharp | G | GSharp | A | ASharp | B | C | CSharp | D | DSharp | E | F | FSharp2 | G2 | GSharp2 | A2 | ASharp2 | B2 | C2 | CSharp2 | D2 | DSharp2 | E2 | F2 | FSharp3 deriving (Show,Eq,Enum,Generic) data PistonState = PistonPushing | PistonPulling deriving (Show,Eq,Enum,Generic) data PistonDirection = PistonDown | PistonUp | PistonSouth | PistonWest | PistonNorth | PistonEast deriving (Show,Eq,Enum,Generic) data BlockChange = BlockChange { hPosition :: !Word8 , yCoord :: !Word8 , blockId :: !Int } deriving (Show,Eq,Generic) instance Serialize BlockChange where put (BlockChange h y b) = do putWord8 h putWord8 y putVarInt b get = do h <- getWord8 y <- getWord8 b <- getVarInt return $ BlockChange h y b data BossBarAction = BossBarAdd !Chat !Float !Int !Int !Word8 | BossBarRemove | BossBarUpdateHealth !Float | BossBarUpdateTitle !Chat | BossBarUpdateStyle !Int !Int | BossBarUpdateFlags !Word8 deriving (Show,Eq,Generic) instance Serialize BossBarAction where put (BossBarAdd title health color division flags) = do putVarInt 0 put title putFloat32be health putVarInt color putVarInt division putWord8 flags put BossBarRemove = do putVarInt 1 put (BossBarUpdateHealth health) = do putVarInt 2 putFloat32be health put (BossBarUpdateTitle title) = do putVarInt 3 put title put (BossBarUpdateStyle color dividers) = do putVarInt 4 putVarInt . toEnum $ color putVarInt . toEnum $ dividers put (BossBarUpdateFlags flags) = do putVarInt 5 putWord8 flags get = do action <- getVarInt case action of 0 -> do title <- get health <- getFloat32be color <- getVarInt division <- getVarInt flags <- getWord8 return $ BossBarAdd title health color division flags 1 -> return $ BossBarRemove 2 -> do health <- getFloat32be return $ BossBarUpdateHealth health 3 -> do title <- get return $ BossBarUpdateTitle title 4 -> do color <- getVarInt dividers <- getVarInt return $ BossBarUpdateStyle color dividers 5 -> do flags <- getWord8 return $ BossBarUpdateFlags flags err -> fail $ "Error: Invalid BossBar action byte: " ++ show err data Difficulty = Peaceful | Easy | Normal | Hard deriving (Show,Enum,Eq,Generic) instance A.FromJSON Difficulty instance A.ToJSON Difficulty instance NFData Difficulty instance Serialize Difficulty where put = putWord8 . toEnum . fromEnum get = (toEnum . fromEnum) <$> getWord8 data Dimension = Overworld | Nether | End deriving (Show,Eq,Generic) instance Enum Dimension where fromEnum Overworld = 0 fromEnum Nether = -1 fromEnum End = 1 toEnum 0 = Overworld toEnum (-1) = Nether toEnum 1 = End toEnum _ = undefined instance A.ToJSON Dimension instance A.FromJSON Dimension instance NFData Dimension instance Serialize Dimension where put d = put (toEnum . fromEnum $ d :: Int32) get = (toEnum . fromEnum) <$> getInt32be data GameMode = Survival | Creative | Adventure | Spectator deriving (Show,Enum,Eq,Generic) instance A.FromJSON GameMode instance A.ToJSON GameMode instance NFData GameMode instance Serialize GameMode where put = putWord8 . toEnum . fromEnum get = (toEnum . fromEnum) <$> getWord8 data Session = Session { sessionProtoState :: ProtocolState , sessionUsername :: Maybe T.Text , sessionSharedSecret :: Maybe B.ByteString , sessionVerifyToken :: B.ByteString , sessionCompressionIsEnabled :: Bool , sessionEncryptionIsEnabled :: Bool , sessionCompressionIsActive :: Bool , sessionEncryptionIsActive :: Bool } deriving (Show,Eq) data ProtocolState = ProtocolHandshake | ProtocolStatus | ProtocolLogin | ProtocolPlay deriving (Show,Eq,Enum,Generic) instance Serialize ProtocolState where put = putWord8 . toEnum . fromEnum get = (toEnum . fromEnum) <$> getWord8 data UpdateBlockEntityAction = SetSpawnPotentials | SetCommandBlockText | SetBeacon | SetModHead | SetFlower | SetBanner | SetStuctureTileEntity | SetGateway | SetSign deriving (Show,Eq,Generic) instance Enum UpdateBlockEntityAction where fromEnum SetSpawnPotentials = 1 fromEnum SetCommandBlockText = 2 fromEnum SetBeacon = 3 fromEnum SetModHead = 4 fromEnum SetFlower = 5 fromEnum SetBanner = 6 fromEnum SetStuctureTileEntity = 7 fromEnum SetGateway = 8 fromEnum SetSign = 9 toEnum 1 = SetSpawnPotentials toEnum 2 = SetCommandBlockText toEnum 3 = SetBeacon toEnum 4 = SetModHead toEnum 5 = SetFlower toEnum 6 = SetBanner toEnum 7 = SetStuctureTileEntity toEnum 8 = SetGateway toEnum 9 = SetSign toEnum _ = undefined instance Serialize UpdateBlockEntityAction where put ubea = putWord8 (toEnum . fromEnum $ ubea) get = (toEnum . fromEnum) <$> getWord8 data EntityStatus = TippedArrowParticles | ResetMobSpawnerMinecartTimer | RabbitRunningParticles | EntityHurt | EntityDied | IronGolemThrowingUpArms | SpawnTamingParticles | SpawnTamedParticles | WolfShakingWater | FinishItemUse | SheepEatingGrass | IgniteTNTMinecart | IronGolemHandingOverRose | VillageMating | AngryVillagerParticles | HappyVillagerParticles | WitchAnimation | ZombieConvertingToVillager | FireworkExploding | AnimalInLove | ResetSquidRotation | SpawnExplosionParticles | PlayGuardianSound | EnableReducedDebug | DisableReducedDebug | SetOpPermissionLvl0 | SetOpPermissionLvl1 | SetOpPermissionLvl2 | SetOpPermissionLvl3 | SetOpPermissionLvl4 | ShieldBlockSound | ShieldBreakSound | FishingRodBobber | ArmorstandHitSound | EntityHurtFromThorns deriving (Show,Eq,Enum,Generic) instance Serialize EntityStatus where put es = put (toEnum . fromEnum $ es :: Int8) get = (toEnum . fromEnum) <$> getInt8 data GameChangeReason = InvalidBed | EndRaining | BeginRaining | ChangeGameMode | ExitEnd | DemoMessage | ArrowHittingPlayer | FadeValue | FateTime | PlayElderGuardianAppearance deriving (Show,Eq,Generic) instance Enum GameChangeReason where fromEnum InvalidBed = 0 fromEnum EndRaining = 1 fromEnum BeginRaining = 2 fromEnum ChangeGameMode = 3 fromEnum ExitEnd = 4 fromEnum DemoMessage = 5 fromEnum ArrowHittingPlayer = 6 fromEnum FadeValue = 7 fromEnum FateTime = 8 fromEnum PlayElderGuardianAppearance = 10 toEnum 0 = InvalidBed toEnum 1 = EndRaining toEnum 2 = BeginRaining toEnum 3 = ChangeGameMode toEnum 4 = ExitEnd toEnum 5 = DemoMessage toEnum 6 = ArrowHittingPlayer toEnum 7 = FadeValue toEnum 8 = FateTime toEnum 10 = PlayElderGuardianAppearance toEnum _ = undefined instance Serialize GameChangeReason where put gcr = putWord8 (toEnum . fromEnum $ gcr) get = (toEnum . fromEnum) <$> getWord8 data EffectID = DispenserDispenses | DispenserFails | DispenserShoots | EnderEyeLaunched | FireworkShot | IronDoorOpened | WoodenDoorOpened | WoodenTrapdoorOpened | FenceGateOpened | FireExtinguished | PlayRecord | IronDoorClosed | WoodenDoorClosed | WoodenTrapdoorClosed | FenceGateClosed | GhastWarns | GhastShoots | EnderdragonShoots | BlazeShoots deriving (Show,Eq,Generic) data SmokeDirection = SouthEast | South | SouthWest | East | Up | West | NorthEast | North | NorthWest deriving (Show,Eq,Enum,Generic) data ParticleID = Explode | LargeExplosion | HugeExplosion | FireworksSpark | Bubble | Splash | Wake | Suspended | DepthSuspend | Crit | MagicCrit | Smoke | LargeSmoke | Spell | InstantSpell | MobSpell | MobSpellAmbient | WitchMagic | DripWater | DripLava | AngryVillager | HappyVillager | TownAura | Note | Portal | EnchantmentTable | Flame | Lava | Footstep | Cloud | RedDust | SnowballPoof | SnowShovel | Slime | Heart | Barrier | IconCrack | BlockCrack | BlockDust | Droplet | Take | MobAppearance | DragonBreath | Endrod | DamageIndicator | SweepAttack deriving (Show,Eq,Enum,Generic) data ValueField = ByteField | VarIntField | FloatField | StringField | ChatField | SlotField | BoolField | Vector3FField | PositionField | OptPositionField | DirectionField | OptUUIDField | BlockIDField deriving (Show,Eq,Enum,Generic) data StatusPayload = StatusPayload { version :: !Version , players :: !Players , description :: !Description } deriving (Generic,Show,Eq,Read) instance A.ToJSON StatusPayload instance A.FromJSON StatusPayload data Version = Version { name :: !T.Text , protocol :: !Word8 } deriving (Generic,Eq,Show,Read) instance A.ToJSON Version instance A.FromJSON Version data Players = Players { max :: !Word8 , online :: !Word8 } deriving (Generic,Eq,Show,Read) instance A.ToJSON Players instance A.FromJSON Players data Description = Description { text :: !T.Text } deriving (Generic,Eq,Show,Read) instance A.ToJSON Description instance A.FromJSON Description data Statistic = Statistic !T.Text !VarInt deriving (Show,Eq,Generic) instance Serialize Statistic where put (Statistic t val) = do putText t putVarInt val get = do t <- getText v <- getVarInt return $ Statistic t v data PlayerListEntries = PlayerListAdds (V.Vector PlayerListAdd) | PlayerListUpdateGameModes (V.Vector PlayerListUpdateGameMode) | PlayerListUpdateLatencies (V.Vector PlayerListUpdateLatency) | PlayerListUpdateDisplayNames (V.Vector PlayerListUpdateDisplayName) | PlayerListRemovePlayers (V.Vector PlayerListRemovePlayer) deriving (Show,Eq,Generic) instance Serialize PlayerListEntries where put (PlayerListAdds lst) = do putVarInt 0 putVarInt . V.length $ lst V.mapM_ put lst put (PlayerListUpdateGameModes lst) = do putVarInt 1 putVarInt . V.length $ lst V.mapM_ put lst put (PlayerListUpdateLatencies lst) = do putVarInt 2 putVarInt . V.length $ lst V.mapM_ put lst put (PlayerListUpdateDisplayNames lst) = do putVarInt 3 putVarInt . V.length $ lst V.mapM_ put lst put (PlayerListRemovePlayers lst) = do putVarInt 4 putVarInt . V.length $ lst V.mapM_ put lst get = do action <- getVarInt ln <- getVarInt case action of 0 -> PlayerListAdds <$> V.replicateM ln get 1 -> PlayerListUpdateGameModes <$> V.replicateM ln get 2 -> PlayerListUpdateLatencies <$> V.replicateM ln get 3 -> PlayerListUpdateDisplayNames <$> V.replicateM ln get 4 -> PlayerListRemovePlayers <$> V.replicateM ln get err -> fail $ "Error: Invaid PlayerList action " ++ show err data PlayerListAdd = PlayerListAdd !UUID !T.Text !(V.Vector PlayerProperty) !GameMode !Int !(Maybe T.Text) deriving (Show,Eq,Generic) instance Serialize PlayerListAdd where put (PlayerListAdd uuid name properties gamemode ping maybeDisplayName) = do putUUID' uuid putText name putVarInt . V.length $ properties V.mapM_ put properties putVarInt (fromEnum gamemode) putVarInt ping case maybeDisplayName of Just displayName -> do put True putText displayName Nothing -> do put False get = do uuid <- getUUID' name <- getText count <- getVarInt properties <- V.replicateM count get gameMode <- toEnum <$> getVarInt ping <- getVarInt hasDisplayName <- get if hasDisplayName then do displayName <- getText return $ PlayerListAdd uuid name properties gameMode ping (Just displayName) else return $ PlayerListAdd uuid name properties gameMode ping Nothing data PlayerListUpdateGameMode = PlayerListUpdateGameMode !UUID !GameMode deriving (Show,Eq,Generic) instance Serialize PlayerListUpdateGameMode where put (PlayerListUpdateGameMode uuid gameMode) = do putUUID' uuid putVarInt . fromEnum $ gameMode get = do uuid <- getUUID' gameMode <- toEnum <$> getVarInt return $ PlayerListUpdateGameMode uuid gameMode data PlayerListUpdateLatency = PlayerListUpdateLatency !UUID !Int deriving (Show,Eq,Generic) instance Serialize PlayerListUpdateLatency where put (PlayerListUpdateLatency uuid ping) = do putUUID' uuid putVarInt ping get = do uuid <- getUUID' ping <- getVarInt return $ PlayerListUpdateLatency uuid ping data PlayerListUpdateDisplayName = PlayerListUpdateDisplayName !UUID !(Maybe T.Text) deriving (Show,Eq,Generic) instance Serialize PlayerListUpdateDisplayName where put (PlayerListUpdateDisplayName uuid maybeDisplayName) = do putUUID' uuid case maybeDisplayName of Nothing -> put False Just displayName -> do put True putText displayName get = do uuid <- getUUID' hasDisplayName <- get if hasDisplayName then do displayName <- getText return $ PlayerListUpdateDisplayName uuid (Just displayName) else return $ PlayerListUpdateDisplayName uuid Nothing data PlayerListRemovePlayer = PlayerListRemovePlayer !UUID deriving (Show,Eq,Generic) instance Serialize PlayerListRemovePlayer where put (PlayerListRemovePlayer uuid) = putUUID' uuid get = PlayerListRemovePlayer <$> getUUID' data PlayerProperty = PlayerProperty { playerName :: !T.Text , playerValue :: !T.Text , playerSig :: !(Maybe T.Text) } deriving (Show,Eq,Generic) instance Serialize PlayerProperty where put (PlayerProperty name val maybeSig) = do putText name putText val case maybeSig of Nothing -> put False Just sig -> do put True putText sig get = do name <- getText value <- getText isSigned <- get if isSigned then do sig <- getText return $ PlayerProperty name value (Just sig) else return $ PlayerProperty name value Nothing data Icon = Icon { directionAndType :: !Word8 , x :: !Word8 , z :: !Word8 } deriving (Show,Eq,Generic) instance Serialize Icon where put (Icon directionAndType' x' z') = do putWord8 directionAndType' putWord8 x' putWord8 z' get = Icon <$> getWord8 <*> getWord8 <*> getWord8 data CombatEvent = EnterCombat | EndCombat !Int !Int32 | EntityDead !Int !Int32 !Chat deriving (Show,Eq,Generic) instance Serialize CombatEvent where put EnterCombat = do putVarInt 0 put (EndCombat duration entityID) = do putVarInt 1 putVarInt duration put entityID put (EntityDead playerID entityID message) = do putVarInt 2 putVarInt playerID put entityID put message get = do event <- getVarInt case event of 0 -> return EnterCombat 1 -> do duration <- getVarInt entityID <- getInt32be return $ EndCombat duration entityID 2 -> do playerID <- getVarInt entityID <- getInt32be message <- get return $ EntityDead playerID entityID message err -> fail $ "Error: Unrecognized combat event: " ++ show err data WorldBorderAction = SetSize !Double | LerpSize !Double !Double !Int64 | SetCenter !Double !Double | Initialize !Double !Double !Double !Double !Int64 !Int !Int !Int | SetWarningTime !Int | SetWarningBlocks !Int deriving (Show,Eq,Generic) instance Serialize WorldBorderAction where put (SetSize diameter) = do putVarInt 0 putFloat64be diameter put (LerpSize oldDiameter newDiameter speed) = do putVarInt 1 putFloat64be oldDiameter putFloat64be newDiameter putVarLong speed put (SetCenter x z) = do putVarInt 2 putFloat64be x putFloat64be z put (Initialize x z oldDiameter newDiameter speed portalBoundary warningTime warningBlocks) = do putVarInt 3 putFloat64be x putFloat64be z putFloat64be oldDiameter putFloat64be newDiameter putVarLong speed putVarInt portalBoundary putVarInt warningTime putVarInt warningBlocks put (SetWarningTime warningTime) = do putVarInt 4 putVarInt . toEnum $ warningTime put (SetWarningBlocks warningBlocks) = do putVarInt 5 putVarInt . toEnum $ warningBlocks get = do action <- getVarInt case action of 0 -> do diameter <- getFloat64be return $ SetSize diameter 1 -> do oldDiameter <- getFloat64be newDiameter <- getFloat64be speed <- getVarLong return $ LerpSize oldDiameter newDiameter speed 2 -> do x <- getFloat64be z <- getFloat64be return $ SetCenter x z 3 -> do x <- getFloat64be z <- getFloat64be oldDiameter <- getFloat64be newDiameter <- getFloat64be speed <- getVarLong portalBoundary <- getVarInt warningTime <- getVarInt warningBlocks <- getVarInt return $ Initialize x z oldDiameter newDiameter speed portalBoundary warningTime warningBlocks 4 -> do warningTime <- getVarInt return $ SetWarningTime warningTime 5 -> do warningBlocks <- getVarInt return $ SetWarningBlocks warningBlocks err -> fail $ "Error: Unrecognized world border action: " ++ show err data TeamMode = CreateTeam !T.Text !T.Text !T.Text !Int8 !T.Text !T.Text !Int8 !(V.Vector T.Text) | RemoveTeam | UpdateTeamInfo !T.Text !T.Text !T.Text !Int8 !T.Text !T.Text !Int8 | AddPlayers !(V.Vector T.Text) | RemovePlayers !(V.Vector T.Text) deriving (Show,Eq,Generic) instance Serialize TeamMode where put (CreateTeam displayName prefix suffix flags tagVisibility collision color players) = do put (0 :: Int8) putText displayName putText prefix putText suffix put flags putText tagVisibility putText collision put color putVarInt . V.length $ players mapM_ putText players put RemoveTeam = put (1 :: Int8) put (UpdateTeamInfo displayName prefix suffix flags tagVisibility collision color) = do put (2 :: Int8) putText displayName putText prefix putText suffix put flags putText tagVisibility putText collision put color put (AddPlayers players) = do put (3 :: Int8) putVarInt . V.length $ players mapM_ putText players put (RemovePlayers players) = do put (4 :: Int8) putVarInt . V.length $ players mapM_ putText players get = do mode <- getInt8 case mode of 0 -> do displayName <- getText prefix <- getText suffix <- getText flags <- getInt8 tagVisibility <- getText collision <- getText color <- getInt8 count <- getVarInt players <- V.replicateM count getText return $ CreateTeam displayName prefix suffix flags tagVisibility collision color players 1 -> return RemoveTeam 2 -> do displayName <- getText prefix <- getText suffix <- getText flags <- getInt8 tagVisibility <- getText collision <- getText color <- getInt8 return $ UpdateTeamInfo displayName prefix suffix flags tagVisibility collision color 3 -> do count <- getVarInt players <- V.replicateM count getText return $ AddPlayers players 4 -> do count <- getVarInt players <- V.replicateM count getText return $ RemovePlayers players err -> fail $ "Unrecognized team mode: " ++ show err data TitleAction = SetTitle !Chat | SetSubtitle !Chat | SetTimesAndDisplay !Int32 !Int32 !Int32 | Hide | Reset deriving (Show,Eq,Generic) instance Serialize TitleAction where put (SetTitle titleText) = do putVarInt 0 put titleText put (SetSubtitle subtitleText) = do putVarInt 1 put subtitleText put (SetTimesAndDisplay fadeIn stay fadeOut) = do putVarInt 2 put fadeIn put stay put fadeOut put Hide = putVarInt 3 put Reset = putVarInt 4 get = do action <- getVarInt case action of 0 -> do titleText <- get return $ SetTitle titleText 1 -> do subtitleText <- get return $ SetSubtitle subtitleText 2 -> do fadeIn <- getInt32be stay <- getInt32be fadeOut <- getInt32be return $ SetTimesAndDisplay fadeIn stay fadeOut 3 -> return Hide 4 -> return Reset err -> fail $ "Unrecognized title action: " ++ show err data EntityProperty = EntityProperty { key :: !T.Text , value :: !Double , numOfModifiers :: !Int , modifiers :: !Int } deriving (Show,Eq,Generic) instance Serialize EntityProperty where put (EntityProperty k v n m) = do putText k putFloat64be v putVarInt n putVarInt m get = do k <- getText v <- getFloat64be n <- getVarInt m <- getVarInt return $ EntityProperty k v n m encodeStatusPayload :: T.Text -> Word8 -> Word8 -> Word8 -> T.Text -> Put encodeStatusPayload mcVersion versionID currentPlayers maxPlayers motd = putNetcodeByteString . BL.toStrict . A.encode $ StatusPayload (Version mcVersion versionID) (Players maxPlayers currentPlayers) (Description motd) data UpdatedColumns = NoUpdatedColumns | UpdatedColumns !Int8 !Int8 !Int8 !Int8 !B.ByteString deriving (Show,Eq,Generic) instance Serialize UpdatedColumns where put NoUpdatedColumns = do put (0 :: Int8) put (UpdatedColumns col rows x z dat) = do put col put rows put x put z putNetcodeByteString dat get = do columns <- getInt8 if columns > 0 then do rows <- getInt8 x <- getInt8 z <- getInt8 dat <- getNetcodeByteString return $ UpdatedColumns columns rows x z dat else return NoUpdatedColumns data UpdateScoreAction = CreateOrUpdateScoreItem !T.Text !T.Text !VarInt | RemoveScoreItem !T.Text !T.Text deriving (Show,Eq,Generic) instance Serialize UpdateScoreAction where put (CreateOrUpdateScoreItem scoreName objectiveName val) = do putText scoreName put (0 :: Int8) putText objectiveName putVarInt val put (RemoveScoreItem scoreName objectiveName) = do putText scoreName put (1 :: Int8) putText objectiveName get = do scoreName <- getText action <- getInt8 objectiveName <- getText case action of 0 -> do value <- getVarInt return $ CreateOrUpdateScoreItem scoreName objectiveName value 1 -> return $ RemoveScoreItem scoreName objectiveName err -> fail $ "Error: Invalid UpdateScoreAction byte: " ++ show err data UseEntityType = InteractWithEntity !VarInt | AttackEntity | InteractAtEntity !Float !Float !Float !EntityHand deriving (Show,Eq,Generic) instance Serialize UseEntityType where put (InteractWithEntity h) = do putVarInt 0 putVarInt h put AttackEntity = putVarInt 1 put (InteractAtEntity tX tY tZ h) = do putVarInt 2 putFloat32be tX putFloat32be tY putFloat32be tZ putVarInt (fromEnum h) get = do t <- getVarInt case t of 0 -> InteractWithEntity <$> getVarInt 1 -> return AttackEntity 2 -> InteractAtEntity <$> getFloat32be <*> getFloat32be <*> getFloat32be <*> get err -> fail $ "Error: Could not get UseEntityType type: " ++ show err data EntityHand = MainHand | OffHand deriving (Show,Eq,Enum,Generic) instance Serialize EntityHand where put = putWord8 . toEnum . fromEnum get = (toEnum . fromEnum) <$> getWord8 data ScoreboardMode = CreateScoreboard !T.Text !T.Text | RemoveScoreboard | UpdateDisplayText !T.Text !T.Text deriving (Show,Eq,Generic) instance Serialize ScoreboardMode where put (CreateScoreboard ov t) = do put (0 :: Int8) putText ov putText t put RemoveScoreboard = put (1 :: Int8) put (UpdateDisplayText ov t) = do put (2 :: Int8) putText ov putText t get = do mode <- getInt8 case mode of 0 -> do objectiveValue <- getText t <- getText return $ CreateScoreboard objectiveValue t 1 -> return RemoveScoreboard 2 -> do objectiveValue <- getText t <- getText return $ UpdateDisplayText objectiveValue t err -> fail $ "Error: Invalid ScoreboardMode byte: " ++ show err
oldmanmike/opensandbox
src/OpenSandbox/Protocol/Types.hs
gpl-3.0
33,551
0
18
8,302
10,218
5,106
5,112
1,441
4
--problem 36 {-- The decimal number, 585 = 1001001001_(2) (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. --} import Numeric import Char showBin x = showIntAtBase 2 intToDigit x "" palindrome x = x == (reverse x) palindrome2 = palindrome . showBin palindrome10 = palindrome . show --optimize out even numbers (no leading 0's count) main = print $ sum $ filter palindromic [1..999999] where palindromic x = (odd x) && (palindrome2 x) && (palindrome10 x)
goalieca/haskelling
036.hs
gpl-3.0
549
0
10
100
122
64
58
8
1
module Cegt.Syntax where -- import Control.Monad.State.Lazy -- import Control.Monad.Reader import Data.Char import qualified Data.Set as S import Data.List hiding (partition) import Text.Parsec import Text.Parsec.Pos type Name = String -- merge prog, kind, type into one syntactic category. data Exp = Var Name | Const Name | Constr Name | App Exp Exp | Lambda Name Exp | Pos SourcePos Exp | Imply Exp Exp | Arrow Exp Exp | Forall Name Exp deriving (Show, Eq, Ord) data Module = Module [Decl] deriving (Show) data Decl = Rule Exp Exp deriving Show -- freeVar :: Exp -> S.Set Name -- freeVar (Var x) = S.insert x S.empty -- freeVar (Const x) = S.empty -- freeVar (Constr x) = S.empty -- freeVar (Arrow f1 f2) = (freeVar f1) `S.union` (freeVar f2) -- freeVar (App f1 f2) = (freeVar f1) `S.union` (freeVar f2) -- freeVar (Forall x f) = S.delete x (freeVar f) -- freeVar (Imply bds h) = S.unions (map freeVar bds) `S.union` freeVar h -- freeKVar :: Exp -> S.Set Name -- freeKVar Star = S.empty -- freeKVar (KVar x) = S.insert x S.empty -- freeKVar (KArrow f1 f2) = (freeKVar f1) `S.union` (freeKVar f2) -- note that this is a naive version of getting -- free variable, since fv will consider data -- type constructors and program definitions as -- free variables. So one would need to aware -- of this when using fv. -- type Subst = [(Name, Exp)] -- fv :: Exp -> S.Set Name -- fv (Con x) = S.empty -- fv (EVar x) = S.insert x S.empty -- fv (App f1 f2) = fv f1 `S.union` fv f2 -- fv (Lambda x s) = S.delete x (fv s) -- fv (Let bs p) = -- let binds = S.fromList $ map fst bs -- tvars = S.unions $ map fv $ map snd bs -- pvar = fv p in -- S.difference (S.union pvar tvars) binds -- fv (Match p cases) = -- S.unions (map fvCase cases) `S.union` fv p -- where fvCase (c, params, t) = -- S.difference (fv t) (S.fromList params) -- fv (Pos _ t) = fv t -- -- applyQ currently only used at freshInst -- applyQ :: Subst -> QType -> QType -- applyQ subs (DArrow fs f) = -- let fs' = map (applyE subs) fs -- f' = applyE subs f in -- DArrow fs' f' -- applyE :: Subst -> Exp -> Exp -- applyE subs a@(Con x) = a -- applyE subs (EVar x) = -- case lookup x subs of -- Just x1 -> x1 -- Nothing -> EVar x -- applyE subs (Arrow f1 f2) = -- let a1 = applyE subs f1 -- a2 = applyE subs f2 in -- Arrow a1 a2 -- applyE subs (Forall y f) = -- let subs' = filter (\(x, _) -> not (x == y)) subs in -- Forall y (applyE subs' f) -- applyE subs (FApp f1 f2) = -- let a1 = applyE subs f1 -- a2 = applyE subs f2 in -- FApp a1 a2 -- applyE subs (Imply bs h) = -- let a1 = applyE subs h -- a2 = map (applyE subs) bs in -- Imply a2 a1 -- -- substituting term -- applyE subs (App a b) = App (applyE subs a) (applyE subs b) -- applyE subs (Lambda x p) = Lambda x (applyE subs p) -- applyE subs (Match p branches) = -- Match (applyE subs p) $ map (helper subs) branches -- where helper subs (c, xs, p) = (c, xs, applyE subs p) -- applyE subs (Let xs p) = -- Let (map (helper subs) xs) (applyE subs p) -- where helper subs (x, def) = (x, applyE subs def) -- applyE subs (Pos _ p) = applyE subs p -- firstline (Inst a xs) = Inst a [head xs] -- apply :: Exp -> Name -> Exp -> Exp -- apply a x (Con t) = Con t -- apply a x (EVar t) = if x == t then a else (EVar t) -- apply a x (App t1 t2) = App (apply a x t1) (apply a x t2) -- apply a x t1@(Lambda y t) = -- if x == y then t1 -- else Lambda y (apply a x t) -- apply a x (Match t branches) = Match (apply a x t) $ map (helper a x) branches -- where helper b y (c, args, p) = if y `elem` args then (c, args, p) else (c, args, apply b y p) -- apply a x (Let branches p) = -- let binds = map fst branches in -- if x `elem` binds then (Let branches p) -- else Let (map (\ (e,d) -> (e, apply a x d)) branches) (apply a x p) -- apply a x t1@(Forall y t) = -- if x == y then t1 -- else Forall y (apply a x t) -- apply a x (FApp p1 p2) = FApp (apply a x p1) (apply a x p2) -- apply a x (Imply bds h) = Imply (map (apply a x) bds) (apply a x h) -- apply a x (Pos _ p) = apply a x p -- applyK :: [(Name, Exp)] -> Exp -> Exp -- applyK _ Star = Star -- applyK subs (KVar x) = -- case lookup x subs of -- Just x1 -> x1 -- Nothing -> KVar x -- applyK subs (KArrow f1 f2) = -- let a1 = applyK subs f1 -- a2 = applyK subs f2 in -- KArrow a1 a2 -- flatApp (Pos _ p) = flatApp p -- flatApp (App t1 t2) = flatApp t1 ++ [t2] -- flatApp (FApp t1 t2) = flatApp t1 ++ [t2] -- flatApp t = [t] -- makeName name = do -- m <- get -- modify (+1) -- return $ name ++ show m -- inst (Forall x t) = do -- newVar <- makeName "x" -- t' <- inst t -- return $ apply (EVar newVar) x t' -- inst a = return a -- quantify t = -- let fs = S.toList $ freeVar t in -- foldr (\ z x -> Forall z x) t fs -- flatten :: Exp -> [Exp] -- flatten (Pos _ f) = flatten f -- flatten (Arrow f1 f2) = f1 : flatten f2 -- flatten (KArrow f1 f2) = f1 : flatten f2 -- flatten _ = []
Fermat/CEGT
src/Cegt/Syntax.hs
gpl-3.0
5,184
0
7
1,437
280
217
63
20
0
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Main where import Control.Monad import Control.Monad.State import Control.Applicative((<$>),(<*>)) import Control.Arrow import Data.Maybe import Data.List as L import Data.Map as M import Data.Set as S import qualified Data.ByteString as B import Data.Function import System.Process import Control.Arrow import Debug.Trace import Data.Generics import Test.QuickCheck import Data.Monoid import Text.PrettyPrint.ANSI.Leijen import System.Exit import Text.Regex.PCRE.Light.Char8 import Common import SimpleArgs import Codec.TPTP infilename = getArgs parseRes = return . parse =<< readFile =<< infilename --main = forever $ quickCheck prop_test_ie --iei_i --main = stressTestParser main = stressTestParser stressTestParser = replicateM 100 $ do n <- getArgs x <- head `fmap` sample' (resize n arbitrary) :: IO TPTP_Input let tptp = toTPTP' [x] putStrLn tptp putStrLn (prettySimple (parse tptp))
DanielSchuessler/logic-TPTP
testing/ParseRandom.hs
gpl-3.0
967
0
12
138
255
150
105
34
1
module PriorityQueue ( PriorityQueue(Empty), makeNode, peek, enqueue, enqueueList, dequeue ) where import Data.Maybe data PriorityQueue a = PQNode a (PriorityQueue a) (PriorityQueue a) Int Int | Empty deriving (Show,Eq) makeNode :: (Ord a) => a -> (PriorityQueue a) -> (PriorityQueue a) -> (PriorityQueue a) makeNode x left right = PQNode x left right (1 + (max (maxHeight left) (maxHeight right))) (1 + (min (minHeight left) (minHeight right))) -- Return the largest element in the queue without changing it peek :: (Ord a) => (PriorityQueue a) -> (Maybe a) peek Empty = Nothing peek (PQNode v x y _ _) = Just v maxHeight :: (Num b) => (PriorityQueue a) -> b maxHeight (PQNode _ _ _ maxHeight _) = fromIntegral maxHeight maxHeight Empty = 0 minHeight :: (Num b) => (PriorityQueue a) -> b minHeight (PQNode _ _ _ _ minHeight) = fromIntegral minHeight minHeight Empty = 0 left :: (PriorityQueue a) -> (PriorityQueue a) left Empty = Empty left (PQNode _ l _ _ _) = l right :: (PriorityQueue a) -> (PriorityQueue a) right Empty = Empty right (PQNode _ _ r _ _) = r enqueue :: (Ord a) => (PriorityQueue a) -> a -> (PriorityQueue a) enqueue Empty x = PQNode x Empty Empty 1 1 enqueue (PQNode top left right _ _) x = makeNode top' left' right' where top' = max top x leftFull = maxHeight left == minHeight left allFull = minHeight right == maxHeight left left' = if allFull || not leftFull then enqueue left $ min top x else left right' = if leftFull && not allFull then enqueue right $ min top x else right enqueueList :: (Ord a) => (PriorityQueue a) -> [a] -> (PriorityQueue a) enqueueList = foldl enqueue removeRightmost :: (Ord a) => (PriorityQueue a) -> (Maybe a, (PriorityQueue a)) removeRightmost (PQNode top Empty Empty 1 1) = (Just top, Empty) removeRightmost (PQNode top left right mx mn) = (rm, makeNode top left' right') where targetLeft = (maxHeight left > minHeight left) || (maxHeight left > maxHeight right) (leftRm, left') = if targetLeft then removeRightmost left else (Nothing, left) (rightRm, right') = if targetLeft then (Nothing, right) else removeRightmost right rm = max leftRm rightRm dequeue :: (Ord a) => (PriorityQueue a) -> (PriorityQueue a) dequeue Empty = Empty dequeue (PQNode _ _ _ 1 _) = Empty dequeue (PQNode top left Empty _ _) = left dequeue (PQNode top left right 2 2) = makeNode top' left' Empty where top' = (max (fromJust $ peek left) (fromJust $ peek right)) left' = makeNode (min (fromJust $ peek left) (fromJust $ peek right)) Empty Empty dequeue pq = makeNode top' left' right' where ((Just rm),pq') = removeRightmost pq leftMax = peek $ left pq' rightMax = peek $ right pq' top' = fromJust $ max leftMax rightMax targetLeft = leftMax > rightMax left' = if targetLeft then enqueue (dequeue $ left pq') rm else left pq' right'= if targetLeft then right pq' else enqueue (dequeue $ right pq') rm
joelwilliamson/Haskell_Learning
PriorityQueue.hs
gpl-3.0
2,936
62
13
605
1,221
648
573
74
3
-- The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. -- Find the sum of all the primes below two million. main :: IO () main = putStrLn $ show . sum $ takeWhile (<2000000) primes primes :: [Int] primes = filter isPrime (2:[3,5..]) divides :: Int -> Int -> Bool divides x d = (mod x d) == 0 isPrime :: Int -> Bool isPrime x = not $ any (divides x) [2,3..(floor $ sqrt (fromIntegral x))]
peri4n/projecteuler
haskell/problem10.hs
gpl-3.0
394
0
12
90
161
86
75
8
1
lucky :: (Integral a) => a -> String --pattern matching lucky 7 = "Lucky number seven!" lucky x = "Better luck next time..." identityBoundFive :: (Integral a) => a -> String identityBoundFive 1 = "One" identityBoundFive 2 = "Two" identityBoundFive 3 = "Three" identityBoundFive 4 = "Four" identityBoundFive 5 = "Five" identityBoundFive x = "Out of bounds 1-5" --catchall must be at the end factorial :: (Integral a) => a -> a factorial 0 = 1 factorial n = n * factorial (n - 1) addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a) addVectors a b = (fst a + fst b, snd a + snd b) addVectors' :: (Num a) => (a, a) -> (a, a) -> (a, a) addVectors' (x1, y1) (x2, y2) = (x1 + x2, y1 + y2) --triple tuple extraction functions first :: (a, b, c) -> a first (x, _, _) = x second :: (a, b, c) -> b second (_, y, _) = y third :: (a, b, c) -> c third (_, _, z) = z --underscores indicate a lack of caring about the input element at that position head' :: [a] -> a head' [] = error "Empty list" head' (x:_) = x tell :: (Show a) => [a] -> String tell [] = "Empty list" tell (x:[]) = "Single element: " ++ show x tell (x:y:[]) = "Two elements: " ++ show x ++ " and " ++ show y tell (x:y:_) = "More than 2 elements" length' :: (Num b) => [a] -> b length' [] = 0 length' (_:xs) = 1 + length' xs sum' :: (Num a) => [a] -> a sum' [] = 0 sum' (x:xs) = x + sum' xs capital :: String -> String capital "" = "Empty string" capital all@(x:xs) = "The first letter of " ++ all ++ " is " ++ [x] --Guards bmiBerate :: (RealFloat a) => a -> String bmiBerate bmi | bmi <= 18.5 = "Underweight" | bmi <= 25.0 = "Normal" | bmi <= 30.0 = "Fat" | otherwise = "Ham planet" bmiBerateOne :: (RealFloat a) => a -> a -> String bmiBerateOne weight height | weight / height ^ 2 <= 18.5 = "Underweight" | weight / height ^ 2 <= 25.0 = "Normal" | weight / height ^ 2 <= 30.0 = "Fat" | otherwise = "Ham planet" max' :: (Ord a) => a -> a -> a max' a b | a > b = a | otherwise = b compare' :: (Ord a) => a -> a -> Ordering a `compare'` b | a > b = GT | a == b = EQ | otherwise = LT --Where bmiBerateTwo :: (RealFloat a) => a -> a -> String bmiBerateTwo weight height | bmi <= skinny = "Underweight" | bmi <= normal = "Normal" | bmi <= fat = "Fat" | otherwise = "Ham planet" where bmi = weight / height ^ 2 skinny = 18.5 normal = 25.0 fat = 30.0 --(skinny, normal, fat) = (18.5, 25.0, 30.0) initials :: String -> String-> String initials first last = [f] ++ ". " ++ [l] ++ "." where (f:_) = first (l:_) = last calcBmi :: (RealFloat a) => [(a, a)] -> [a] calcBmi xs = [bmi w h | (w, h) <- xs] where bmi weight height = weight / height ^ 2 --let cylinder :: (RealFloat a) => a -> a -> a cylinder r h = let sideArea = 2 * pi * r * h topArea = pi * r ^ 2 in sideArea + 2 * topArea meaning = 4 * (let a = 9 in a + 1) + 2 localScopeFunc = [let square x = x * x in (square 5, square 3, square 2)] inlineBind = (let a = 100; b = 200; c = 300 in a * b * c, let foo = "Hey "; bar = "there!" in foo ++ bar) --inline let uses semicolons tupleBind = (let (a, b, c) = (1, 2, 3) in a + b + c) * 100 calcBmi' :: (RealFloat a) => [(a, a)] -> [a] calcBmi' xs = [bmi | (w, h) <- xs, let bmi = w / h ^ 2, bmi >= 25.0] --case expressions headOne :: [a] -> a headOne xs = case xs of [] -> error "Empty list!" (x:_) -> x describeList :: [a] -> String describeList xs = "The list is " ++ case xs of [] -> "empty." [x] -> "a singleton list." xs -> "greater than 1 element." describeList' :: [a] -> String describeList' xs = "The list is " ++ what xs where what [] = "empty." what [x] = "a singleton list." what xs = "greater than 1 element."
torchhound/projects
haskell/syntaxInFunctions.hs
gpl-3.0
3,713
11
11
945
1,788
947
841
101
3
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} module GUI.RSCoin.WalletTab ( createWalletTab , initWalletTab , updateWalletTab ) where import Control.Monad (join, void, when) import qualified Data.IntMap.Strict as M import Data.Maybe (mapMaybe) import Data.Monoid ((<>)) import qualified Data.Text as T import Data.Text.Buildable (Buildable (build)) import qualified Data.Text.Lazy.Builder as B import Formatting (sformat, (%)) import qualified Formatting as F (build) import Graphics.UI.Gtk (AttrOp ((:=)), on) import qualified Graphics.UI.Gtk as G import Serokell.Util.Text (show') import qualified RSCoin.Core as C import RSCoin.Timed (runRealModeUntrusted) import RSCoin.User (RSCoinUserState, TxHStatus (..), TxHistoryRecord (..)) import qualified RSCoin.User as U import GUI.RSCoin.ExplicitTransaction (ExplicitTransaction (..), fromTransaction, getTransactionAmount) import GUI.RSCoin.Glade (GladeMainWindow (..)) import GUI.RSCoin.GUIAcid (GUIState, replaceWithName) import GUI.RSCoin.MainWindow (WalletModelNode (..), WalletTab (..)) import qualified GUI.RSCoin.MainWindow as M type Model = G.ListStore WalletModelNode createWalletTab :: GladeMainWindow -> IO WalletTab createWalletTab GladeMainWindow{..} = do makeHeaderRed containerSeparatorColor gBoxRSCoinLogo redColor containerSeparatorColor gBoxWalletHeader whiteColor model <- createWalletModel gTreeViewWallet return $ WalletTab gTreeViewWallet model gBoxWalletHeader gLabelCurrentBalance gLabelUnconfirmedBalance gLabelTransactionsNumber gLabelCurrentAccount where makeHeaderRed = do G.widgetModifyBg gBoxWalletHeaderWrapper G.StateNormal redColor G.widgetModifyFg gBoxWalletHeaderWrapper G.StateNormal whiteColor containerSeparatorColor widget color = join $ mapM_ (\w -> G.widgetModifyBg w G.StateNormal color) . map snd . filter (odd . fst) . zip [(0 :: Integer) ..] <$> G.containerGetChildren widget whiteColor = G.Color 65535 65535 65535 redColor = G.Color 52685 9252 9252 -- What's that? Not used anywhere. -- addStyle widget css' = do -- ctx <- G.widgetGetStyleContext widget -- css <- cssProviderGetDefault -- cssProviderLoadFromString css css' -- styleContextAddProvider ctx css 1 createWalletModel :: G.TreeView -> IO Model createWalletModel view = do model <- G.listStoreNew [] appendPixbufColumn model False (sid "In/out") isSendSetter appendTextColumn model True (sid "Status") statusSetter appendTextColumn model True (sid "At height") heightSetter appendTextColumn model True (sid "Address") addrSetter appendTextColumn model True (sid "Amount") amountSetter G.treeViewSetModel view model return model where sid :: String -> String sid = id -- overloaded strings... appendPixbufColumn model expand title attributesSetter = do renderer <- G.cellRendererPixbufNew appendColumn renderer model expand title attributesSetter appendTextColumn model expand title attributesSetter = do renderer <- G.cellRendererTextNew appendColumn renderer model expand title attributesSetter appendColumn renderer model expand title attributesSetter = do column <- G.treeViewColumnNew G.treeViewColumnSetTitle column title G.treeViewColumnSetExpand column expand G.cellLayoutPackStart column renderer False G.cellLayoutSetAttributes column renderer model attributesSetter void $ G.treeViewAppendColumn view column isSendSetter node = [ G.cellPixbufStockId := if wIsSend node then sid "withdraw" else "deposit"] statusSetter node = [ G.cellText := case wStatus node of U.TxHConfirmed -> sid "Confirmed" U.TxHUnconfirmed -> "Unconfirmed" U.TxHRejected -> "Rejected" ] heightSetter node = [G.cellText := show (wHeight node)] addrSetter node = [G.cellText := wAddress node] amountSetter node = [G.cellText := showSigned (wAmount node)] showSigned a | a > 0 = "+" ++ show a | otherwise = show a instance Buildable TxHStatus where build TxHConfirmed = B.fromString "Confirmed" build TxHUnconfirmed = B.fromString "Unconfirmed" build TxHRejected = B.fromString "Rejected" buildTransactionIndent :: C.Transaction -> B.Builder buildTransactionIndent C.Transaction{..} = mconcat [ "Inputs: " , mconcat $ map (\x -> "\n-> " <> build x) txInputs , "\nOutputs: " , mconcat $ map (\(a,c) -> "\n<- " <> build a <> ", " <> build c) txOutputs ] instance Buildable TxHistoryRecord where build TxHistoryRecord{..} = mconcat [ "Transaction: \n" , buildTransactionIndent txhTransaction , "\nAt height: " , build txhHeight , "\nStatus: " , build txhStatus] initWalletTab :: Maybe FilePath -> RSCoinUserState -> GUIState -> M.MainWindow -> IO () initWalletTab confPath st gst [email protected]{..} = do void ((M.treeViewWallet tabWallet) `on` G.rowActivated $ \l _ -> case l of (i:_) -> do sz <- G.listStoreGetSize $ M.walletModel tabWallet when (i < sz) $ dialogWithIndex i _ -> return ()) updateWalletTab confPath st gst mw where sid = (id :: String -> String) dialogWithIndex i = do dialog <- G.dialogNew node <- G.listStoreGetValue (M.walletModel tabWallet) i void $ G.dialogAddButton dialog (sid "Ok") G.ResponseOk upbox <- G.castToBox <$> G.dialogGetContentArea dialog scrolled <- G.scrolledWindowNew Nothing Nothing label <- G.labelNew (Nothing :: Maybe String) G.scrolledWindowAddWithViewport scrolled label G.set label [ G.labelText := sformat ("Information about transaction: \n" % F.build) (wTxHR node) , G.labelSelectable := True , G.labelWrap := True ] G.set upbox [ G.widgetMarginLeft := 5 , G.widgetMarginRight := 5 , G.widgetMarginTop := 5 , G.widgetMarginBottom := 5 ] G.set scrolled [ G.scrolledWindowMinContentHeight := 300 , G.scrolledWindowMinContentWidth := 500 ] G.boxPackStart upbox scrolled G.PackNatural 0 G.set dialog [ G.windowTitle := sid "Transaction info" , G.windowResizable := False ] G.widgetShowAll upbox void $ G.dialogRun dialog void $ G.widgetDestroy dialog toNodeMapper :: Maybe FilePath -> RSCoinUserState -> GUIState -> U.TxHistoryRecord -> IO WalletModelNode toNodeMapper confPath st gst [email protected]{..} = do eTx <- runRealModeUntrusted C.userLoggerName confPath $ fromTransaction gst txhTransaction addrs <- U.getAllAddresses st C.defaultNodeContext let amountDiff = C.getAmount $ getTransactionAmount addrs eTx isIncome = amountDiff > 0 headMaybe [] = Nothing headMaybe (x:_) = Just x firstFromAddress = headMaybe $ filter (`notElem` addrs) $ mapMaybe fst $ vtInputs eTx outputs = (map fst $ vtOutputs eTx) firstOutAddress = head $ filter (`notElem` addrs) outputs ++ filter (`elem` addrs) outputs if isIncome then do (from :: T.Text) <- case firstFromAddress of Nothing -> return "Emission/Fees" Just addr -> do name <- replaceWithName gst addr return $ sformat (maybe (F.build % F.build) (const $ F.build % " (" % F.build % ")") name) name firstOutAddress return $ WalletModelNode False txhStatus txhHeight from amountDiff txhr else do (out :: T.Text) <- do name <- if firstOutAddress `elem` addrs then return (Just "To you") else replaceWithName gst firstOutAddress return $ sformat (maybe (F.build % F.build) (const $ F.build % " (" % F.build % ")") name) name firstOutAddress return $ WalletModelNode True txhStatus txhHeight out amountDiff txhr updateWalletTab :: Maybe FilePath -> RSCoinUserState -> GUIState -> M.MainWindow -> IO () updateWalletTab confPath st gst M.MainWindow{..} = do let WalletTab{..} = tabWallet addrs <- U.getAllAddresses st C.defaultNodeContext transactionsHist <- runRealModeUntrusted C.userLoggerName confPath $ U.getTransactionsHistory st userAmount <- runRealModeUntrusted C.userLoggerName confPath (M.findWithDefault 0 0 <$> U.getUserTotalAmount False st) let unconfirmed = filter (\U.TxHistoryRecord{..} -> txhStatus == U.TxHUnconfirmed) transactionsHist unconfirmedSum = do txs <- mapM (runRealModeUntrusted C.userLoggerName confPath . fromTransaction gst . U.txhTransaction) unconfirmed return $ sum $ map (getTransactionAmount addrs) txs G.labelSetText labelCurrentBalance $ show $ C.getCoin userAmount G.labelSetText labelTransactionsNumber $ show $ length unconfirmed G.labelSetText labelUnconfirmedBalance . show =<< unconfirmedSum G.labelSetText labelCurrentAccount $ show' $ head addrs nodes <- mapM (toNodeMapper confPath st gst) transactionsHist G.listStoreClear walletModel mapM_ (G.listStoreAppend walletModel) $ reverse nodes return ()
input-output-hk/rscoin-haskell
src/User/GUI/RSCoin/WalletTab.hs
gpl-3.0
10,890
0
25
3,729
2,655
1,337
1,318
-1
-1
{- Copyright (C) 2014 Albert Krewinkel <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. -} -- | Tests for Rundoc and Metropolis module Main where import Test.Tasty import qualified Metropolis.Worker.Tests as MW main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Metropolis" [ MW.tests ]
tarleb/rundoc
tests/rundoc-tests.hs
agpl-3.0
940
0
7
158
58
35
23
8
1
-- | Module for logging. module Text.Logging ( LogLevel(..), logg, loggUnsafe, setLogFile, ) where import Data.IORef import qualified Data.ByteString as SBS import qualified Data.ByteString.UTF8 as SBS import Control.Monad import Control.Monad.IO.Class import System.Info import System.FilePath import System.Environment import System.IO import System.IO.Unsafe import Utils.Scripting data LogLevel = Debug | Info | Warning | Error deriving (Eq, Ord, Show) printLogLevel = Warning -- | Logs a message with the given log level. -- Prints to stdout on unix, uses a logFile on windows. logg :: (MonadIO m) => LogLevel -> String -> m () logg ll msg = liftIO $ when (ll >= printLogLevel) $ inner $ mkMsg ll msg where inner msg = do mLogHandle <- readIORef _logHandle case mLogHandle of Just logHandle -> SBS.hPutStr logHandle msg >> hFlush logHandle Nothing -> case System.Info.os of "mingw32" -> windowsLogging msg _ -> SBS.putStr msg >> hFlush stdout mkMsg :: LogLevel -> String -> SBS.ByteString mkMsg ll msg = SBS.fromString (show ll ++ ": " ++ msg ++ "\n") windowsLogging :: SBS.ByteString -> IO () windowsLogging msg = do progPath <- getProgPathOrCurrentDirectory progName <- getProgName SBS.appendFile (progPath </> progName <.> "log") msg loggUnsafe :: LogLevel -> String -> a -> a loggUnsafe ll msg a = unsafePerformIO $ do logg ll msg return a -- * log file {-# noinline _logHandle #-} _logHandle :: IORef (Maybe Handle) _logHandle = unsafePerformIO $ newIORef Nothing setLogFile :: FilePath -> IO () setLogFile logFile = openFile logFile AppendMode >>= writeIORef _logHandle . Just
cstrahan/nikki
src/Text/Logging.hs
lgpl-3.0
1,752
0
17
409
503
264
239
51
3
module Git.Index ( Index(..), loadIndex, indexTree ) where import System.IO import System.FilePath import Control.Monad import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import Control.Applicative import Data.Attoparsec import qualified Data.Attoparsec.ByteString as AP (take, skip, takeTill) import Data.Attoparsec.Binary import Data.ByteString.Internal (c2w, w2c) import Data.Bits import Data.Word import Data.List import Text.Printf import System.Posix.Types (EpochTime) import Git.Hash import Git.Object.Tree import Git.Object.Blob -- | The index is a list of entries and optional extensions. We currently -- ignore the extensions. data Index = Index { indexEntries :: [IndexEntry] } deriving Show -- | An IndexEntry is a single entry in an Index, representing a single -- file along with its hash, mode, as well as stat()-related info used to -- decide whether an on-disk file has changed. data IndexEntry = IndexEntry { hash :: Hash, name :: String, flags :: Int, -- These attributes are currently not used for anythign. ctime :: EpochTime, mtime :: EpochTime, dev :: Int, ino :: Int, mode :: Int, uid :: Int, gid :: Int, size :: Int } deriving Show -- * Parser -- | The index consists of a header, followed by a number of entries, followed -- by a number of extensions. We currently ignore any extensions. indexParser :: Parser Index indexParser = do num <- header; entries <- sequence $ replicate num entry return Index { indexEntries = entries } -- | The index header starts with "DIRE", followed by the version number -- (currently 2), followed by the number of entries in the index. header :: Parser Int header = fromIntegral <$ word32be 0x44495243 <* word32be 2 <*> anyWord32be -- | sec + nsec, where nsec always appears to be zero. cacheTime :: Parser EpochTime cacheTime = fromIntegral <$> anyWord32be <* word32be 0 entry :: Parser IndexEntry entry = do ctime <- cacheTime mtime <- cacheTime dev <- anyWord32be ino <- anyWord32be mode <- anyWord32be uid <- anyWord32be gid <- anyWord32be size <- anyWord32be hash <- binaryHash flagsword <- anyWord16be let namemask = 0xFFF let namelen = flagsword .&. namemask namebytes <- if namelen == namemask then fail "long name in index" else AP.take (fromIntegral namelen) -- TODO: parse flags. let flags = fromIntegral $ flagsword `shiftR` 12 -- Need to read remaining pad bytes. -- (offsetof(struct cache_entry,name) + (len) + 8) & ~7 -- It appears to waste 8 bytes if we're at an even multiple of 8? let padbytes = 8 - ((8+8+6*4+20+2+namelen) `mod` 8) AP.take $ fromIntegral padbytes let name = map w2c $ B.unpack namebytes return $ IndexEntry { ctime=ctime, mtime=mtime, dev = fromIntegral dev, ino = fromIntegral ino, mode = fromIntegral mode, uid = fromIntegral uid, gid = fromIntegral gid, size = fromIntegral size, hash=hash, flags=flags, name=name } -- | Load and parse the git index file. loadIndex :: IO Index loadIndex = do handle <- openFile ".git/index" ReadMode hSetBinaryMode handle True contents <- B.hGetContents handle -- Last 20 bytes are SHA1, we ignore that. let raw = B.take (B.length contents - 20) contents case parseOnly indexParser raw of Right a -> return a otherwise -> error "Failed to parse the index" -- This down below here is ugly. Don't look at it. It works sortof though, but -- is probably not the fastest due to the heavy use of length, !! etc. -- | Build a tree out of entries in the index with the given prefix. indexTreePrefix :: Index -> String -> Tree indexTreePrefix index prefix = emptyTree { treeEntries = fmap (toTreeEntry index prefix) input } where input = unique . (fmap (mapIndexEntry prefix)) $ entries entries = filter (\x -> prefix `isPrefixOf` (name x)) (indexEntries index) unique = nubBy (\x y -> fst x == fst y) -- | Given a prefix and an index entry, figure out if the entry is a directory -- or a blob. If it's a directory we know we have to build a tree and descend -- into it, otherwise we can insert it into the resulting tree. mapIndexEntry :: String -> IndexEntry -> (String, Maybe IndexEntry) mapIndexEntry prefix entry = if '/' `elem` rest then (init $ nameComponents !! prefixLength, Nothing) else (nameComponents !! prefixLength, Just entry) where rest = drop (length prefix) (name entry) nameComponents = splitPath (name entry) prefixComponents = splitPath prefix prefixLength = length prefixComponents -- | If the index entry is a directory, we have to descend into it and -- generate a tree to get the hash. When we do that we also have to write the -- tree to the disk, or at least collect all the trees we generate along the -- way so someone else can do it. toTreeEntry :: Index -> String -> (String, Maybe IndexEntry) -> Entry toTreeEntry index prefix (name, Nothing) = Entry 0o040000 name (treeHash $ indexTreePrefix index (prefix ++ name ++ "/")) toTreeEntry index prefix (name, Just ie) = Entry (mode ie) name (hash ie) -- | Convert an index into a tree. indexTree :: Index -> Tree indexTree index = indexTreePrefix index ""
wereHamster/yag
Git/Index.hs
unlicense
5,343
0
19
1,183
1,221
667
554
95
2
module KthDifferences.A999996 () where import External.A174344 (a174344) import Miscellaneous.A268038 (a268038) import Data.Set (Set) import qualified Data.Set as Set import Data.Maybe (Maybe, mapMaybe) import Data.Ratio (Ratio, (%)) import Sandbox.SegmentIntersection (intersects, pointIsOnLine) -- type KthDifferences = [((Integer, Integer), Set (Integer, Integer))] type Point = (Integer, Integer) type Status = (Point, [Point], Set (Integer, Integer)) -- Starting at (0,0) and using the spiral defined by A174344 and A268038, go to -- the first value in (A174344(n), A268038(n)) such that the polygonal chain -- does not self-intersect and all first differences are distinct. -- Each list of k-th differences distinct. -- a999996_list :: [(Integer, Integer)] a999996_list = (0,0) : recurse ((0,0), [(0,0)], Set.empty) where -- recurse kthDifferences = n : recurse ds where -- recurse kthDifferences = x : recurse ds where recurse status = p_0 : recurse status' where status'@(p_0, _, _) = nextDifferences status -- -- -- a999996 :: Int -> (Integer, Integer) -- -- a999996 n = a999996_list !! (n - 1) -- -- nextDifferences :: Status -> Status nextDifferences ds = head $ mapMaybe (`updateStatus` ds) spiral -- findNext (s, a, b) = fmap (\x-> (s,x)) $ (a, b) `updateDifferences` ds -- spiral :: [Point] spiral = map (\i -> (a174344 i, -a268038 i)) [1..] -- updateStatus :: Point -> Status -> Maybe Status updateStatus p_1 (p_0, points@(point:_), firstDifferences) | p_1 `elem` points = Nothing | intersectsPolygonalChain p_1 points = Nothing | fd `Set.member` firstDifferences = Nothing | otherwise = Just (p_1, p_1:points, firstDifferences') where fd = firstDiff p_0 p_1 firstDifferences' = fd `Set.insert` firstDifferences firstDiff :: Point -> Point -> (Integer, Integer) firstDiff (x0, y0) (x1, y1) = (x0 - x1, y0 - y1) intersectsPolygonalChain :: Point -> [Point] -> Bool intersectsPolygonalChain _ [] = False intersectsPolygonalChain x [p] = x == p intersectsPolygonalChain x ps'@(p:ps) = pointIsOnLine x s || any (intersects (x, p)) segments where (s:segments) = ps' `zip` ps
peterokagey/haskellOEIS
src/Sandbox/GreedySpiralSequences/FirstDifferencesNonintersecting.hs
apache-2.0
2,171
1
10
399
604
351
253
32
1
{- Copyright 2010-2012 Cognimeta Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE ScopedTypeVariables #-} module Database.Perdure.TestStoreFile ( testStoreFile ) where import Data.Word import Database.Perdure import Database.Perdure.Internal import Cgm.Data.Either import Cgm.System.Endian import Control.Exception import Control.Monad.Error import Control.Applicative testStoreFile :: [String] -> IO () testStoreFile _ = fmap fromRight $ runErrorT $ withFileStoreFile "testStoreFile.dag" $ (. (ReplicatedFile . pure)) $ \f -> do let a :: PrimArray Pinned Word32 = mkArrayWith 130000 $ fromIntegral . getLen r <- storeFileWrite f 0 platformWordEndianness [a] storeFileFullBarrier f ma <- await1 $ storeFileRead f r platformWordEndianness Validator0 assert (ma == Just (fullArrayRange a)) $ return ()
bitemyapp/perdure
exe-src/Database/Perdure/TestStoreFile.hs
apache-2.0
1,378
0
15
263
227
118
109
19
1
{- Copyright 2014 David Farrell <[email protected]> - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -} module Join where import Data.List (nub) import Data.Maybe (fromMaybe) import qualified Data.Map as M import qualified Data.IntMap as IM import IRC.Message import IRC.Numeric import IRC.Action import qualified IRC.Server.Client as Client import qualified IRC.Server.Channel as Chan import IRC.Server.Client.Helper import IRC.Server.Channel.Helper import IRC.Server.Environment (whenRegistered) import qualified IRC.Server.Environment as Env import Config import Plugin plugin = defaultPlugin {handlers=[CommandHandler "JOIN" join]} join :: CommandHSpec join env (Message _ _ (chan@('#':_):_)) = whenRegistered env $ env {Env.actions=a:Env.actions env} where cp = Env.config env defChanModes = nub $ getConfigString cp "channel" "default_modes" serverName = getConfigString cp "info" "name" channels = Client.channels (Env.client env) aJoin e = do sendChannelFromClient cli e newChan $ "JOIN " ++ chan sendClientFrom serverName cli $ "MODE " ++ chan ++ " +" ++ Chan.modes newChan sendNumeric e numRPL_NAMREPLY ["=", chan, unwords nicks] sendNumeric e numRPL_ENDOFNAMES [chan, "End of /NAMES list"] return e { Env.client = cli {Client.channels=chan:(Client.channels cli)} , Env.local = l {Env.channels=newChans} } where l = Env.local e lcs = Env.channels l cli = Env.client e Just uid = Client.uid cli newChans = if M.member chan lcs then M.adjust (\c@(Chan.Channel {Chan.uids=us}) -> c {Chan.uids=uid:us}) chan lcs else M.insert chan (Chan.Channel chan [uid] defChanModes) lcs nicks = map (fromMaybe "*" . Client.nick . (Env.clients l IM.!)) $ Chan.uids (newChans M.! chan) newChan = newChans M.! chan aAlready e = sendNumeric e numERR_USERONCHANNEL [nick, chan, "is already on channel"] >> return e where Just nick = Client.nick (Env.client e) a = if notElem chan channels then ChanAction "Join" chan aJoin else GenericAction aAlready join env (Message _ _ (chan:_)) = whenRegistered env $ env {Env.actions=a:Env.actions env} where a = GenericAction $ \e -> sendNumeric e numERR_BADCHANNAME [chan, "Illegal channel name"] >> return e join env _ = whenRegistered env $ env {Env.actions=a:Env.actions env} where a = GenericAction $ \e -> sendNumeric e numERR_NEEDMOREPARAMS ["JOIN", "Not enough parameters"] >> return e
shockkolate/lambdircd
plugins.old/Join.hs
apache-2.0
3,055
0
17
646
858
461
397
50
3
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE TypeFamilies #-} -- | Alias analysis for bind expressions. -- This is used by the interpreter to ensure consistent modification -- of alias variables following the interpretation of a bind expression. module Language.K3.Analysis.Interpreter.BindAlias ( labelBindAliases , labelBindAliasesExpr ) where import Control.Arrow ( (&&&) ) import Data.Maybe import Data.Tree import Language.K3.Core.Annotation import Language.K3.Core.Annotation.Analysis import Language.K3.Core.Common import Language.K3.Core.Expression import Language.K3.Core.Declaration import Language.K3.Core.Utils labelBindAliases :: K3 Declaration -> K3 Declaration labelBindAliases prog = snd $ labelDecl 0 prog where threadCntChildren cnt ch ch_f f = f $ (\(x,y) -> (maxCnt cnt x, y)) . unzip $ foldl (threadCnt ch_f cnt) [] ch withDeclChildren cnt ch = threadCntChildren cnt ch labelDecl withAnnMems cnt mems = threadCntChildren cnt mems labelAnnMem id labelDecl :: Int -> K3 Declaration -> (Int, K3 Declaration) labelDecl cnt d@(tag &&& children -> (DGlobal n t eOpt, ch)) = withDeclChildren cnt ch (\(ncnt,nch) -> let (ncnt2, neOpt) = maybe (ncnt, Nothing) (fmap Just . labelBindAliasesExpr ncnt) eOpt in (ncnt2, Node (DGlobal n t neOpt :@: annotations d) nch)) labelDecl cnt d@(tag &&& children -> (DTrigger n t e, ch)) = withDeclChildren cnt ch (\(ncnt,nch) -> let (ncnt2, ne) = labelBindAliasesExpr ncnt e in (ncnt2, Node (DTrigger n t ne :@: annotations d) nch)) labelDecl cnt d@(tag &&& children -> (DDataAnnotation n tVars annMems, ch)) = withDeclChildren cnt ch (\(ncnt,nch) -> let (ncnt2, nAnnMems) = withAnnMems ncnt annMems in (ncnt2, Node (DDataAnnotation n tVars nAnnMems :@: annotations d) nch)) labelDecl cnt (Node t ch) = withDeclChildren cnt ch (\(ncnt,nch) -> (ncnt, Node t nch)) labelAnnMem :: Int -> AnnMemDecl -> (Int, AnnMemDecl) labelAnnMem cnt (Lifted p n t eOpt memAnns) = let (ncnt, neOpt) = maybe (cnt, Nothing) (fmap Just . labelBindAliasesExpr cnt) eOpt in (ncnt, (Lifted p n t neOpt memAnns)) labelAnnMem cnt (Attribute p n t eOpt memAnns) = let (ncnt, neOpt) = maybe (cnt, Nothing) (fmap Just . labelBindAliasesExpr cnt) eOpt in (ncnt, (Attribute p n t neOpt memAnns)) labelAnnMem cnt annMem = (cnt, annMem) threadCnt f cnt acc c = acc++[f (maxCnt cnt $ map fst acc) c] maxCnt i l = if l == [] then i else last l labelBindAliasesExpr :: Int -> K3 Expression -> (Int, K3 Expression) labelBindAliasesExpr counter expr = labelExpr counter expr where labelExpr cnt e@(tag &&& children -> (EBindAs b, [s, t])) = (ncnt2, Node (EBindAs b :@: annotations e) [ns, nt]) where (ncnt, ns) = labelProxyPath $ labelExpr cnt s (ncnt2, nt) = labelExpr ncnt t labelExpr cnt e@(tag &&& children -> (ECaseOf i, [c, s, n])) = (ncnt3, Node (ECaseOf i :@: annotations e) [nc, ns, nn]) where (ncnt, nc) = labelProxyPath $ labelExpr cnt c (ncnt2, ns) = labelExpr ncnt s (ncnt3, nn) = labelExpr ncnt2 n -- Recur through all other operations. labelExpr cnt (Node t cs) = (\(x,y) -> (maxCnt cnt x, Node t y)) $ unzip $ foldl (threadCnt labelExpr cnt) [] cs labelProxyPath (i, e) = annotateAliases i (exprUIDs $ extractReturns e) e where exprUIDs = concatMap asUID . mapMaybe (@~ isEUID) asUID (EUID x) = [x] asUID _ = [] threadCnt f cnt acc c = acc++[f (maxCnt cnt $ map fst acc) c] maxCnt i l = if l == [] then i else last l -- | Returns subexpression UIDs for return values of the argument expression. extractReturns :: K3 Expression -> [K3 Expression] extractReturns (tag &&& children -> (EOperate OSeq, [_, r])) = extractReturns r extractReturns e@(tag &&& children -> (EProject _, [r])) = [e] ++ extractReturns r extractReturns e@(tag &&& children -> (ELetIn i, [_, b])) = let r = filter (notElem i . freeVariables) $ extractReturns b in if r == [] then [e] else r extractReturns e@(tag &&& children -> (ECaseOf i, [_, s, n])) = let r = extractReturns s depR = filter (notElem i . freeVariables) r in (if r /= depR then [e] else r ++ extractReturns n) extractReturns e@(tag &&& children -> (EBindAs b, [_, f])) = let r = filter (and . map (`notElem` (bindingVariables b)) . freeVariables) $ extractReturns f in if r == [] then [e] else r extractReturns (tag &&& children -> (EIfThenElse, [_, t, e])) = concatMap extractReturns [t, e] -- Structural error cases. extractReturns (tag -> EProject _) = error "Invalid project expression" extractReturns (tag -> ELetIn _) = error "Invalid let expression" extractReturns (tag -> ECaseOf _) = error "Invalid case expression" extractReturns (tag -> EBindAs _) = error "Invalid bind expression" extractReturns (tag -> EIfThenElse) = error "Invalid branch expression" extractReturns e = [e] -- | Annotates variables and temporaries in the candidate expressions as -- alias points in the argument K3 expression. annotateAliases :: Int -> [UID] -> K3 Expression -> (Int, K3 Expression) annotateAliases i candidateExprs expr = (\((j, _), ne) -> (j, ne)) $ annotate i expr where annotate :: Int -> K3 Expression -> ((Int, Bool), K3 Expression) annotate cnt e@(tag -> EVariable v) = withEUID e (\x -> if x `elem` candidateExprs then ((cnt, True), e @+ (EAnalysis $ BindAlias v)) else ((cnt, False), e)) annotate cnt e@(tag &&& children -> (EProject f, [r])) = withEUID e (\x -> if not(x `elem` candidateExprs && subAlias) then ((ncnt, subAlias), newExpr) else ((ncnt, True), newExpr @+ (EAnalysis $ BindAliasExtension f))) where newExpr = Node (EProject f :@: annotations e) [subExpr] ((ncnt, subAlias), subExpr) = annotate cnt r annotate cnt e@(Node t cs) = withEUID e (\uid -> if uid `elem` candidateExprs then ((ncnt+1, True), (Node t subExprs) @+ (EAnalysis . BindFreshAlias $ "tmp"++(show ncnt))) else ((ncnt, subAlias), Node t subExprs)) where (ncnt, subAlias) = (if x == [] then cnt else fst $ last x, or $ map snd x) (x,subExprs) = unzip $ foldl threadCnt [] cs threadCnt acc c = acc++[annotate (if acc == [] then cnt else (fst . fst . last $ acc)) c] withEUID e f = case e @~ isEUID of Just (EUID x) -> f x Just _ -> error "Invalid EUID annotation match" Nothing -> error "No UID found on variable expression"
yliu120/K3
src/Language/K3/Analysis/Interpreter/BindAlias.hs
apache-2.0
6,665
0
17
1,595
2,639
1,417
1,222
106
10
{-# LANGUAGE CPP #-} #ifndef MIN_VERSION_integer_gmp #define MIN_VERSION_integer_gmp(a,b,c) 0 #endif #if MIN_VERSION_integer_gmp(0,5,1) {-# LANGUAGE MagicHash, UnboxedTuples, BangPatterns #-} #endif -- | -- Module : Crypto.Number.Serialize -- License : BSD-style -- Maintainer : Vincent Hanquez <[email protected]> -- Stability : experimental -- Portability : Good -- -- fast serialization primitives for integer module Crypto.Number.Serialize ( i2osp , os2ip , i2ospOf , i2ospOf_ , lengthBytes ) where import Data.ByteString (ByteString) import qualified Data.ByteString.Internal as B import qualified Data.ByteString as B import Foreign.Ptr #if MIN_VERSION_integer_gmp(0,5,1) #if __GLASGOW_HASKELL__ >= 710 import Control.Monad (void) #endif import GHC.Integer.GMP.Internals import GHC.Base import GHC.Ptr import System.IO.Unsafe import Foreign.ForeignPtr #else import Foreign.Storable import Data.Bits #endif #if !MIN_VERSION_integer_gmp(0,5,1) {-# INLINE divMod256 #-} divMod256 :: Integer -> (Integer, Integer) divMod256 n = (n `shiftR` 8, n .&. 0xff) #endif -- | os2ip converts a byte string into a positive integer os2ip :: ByteString -> Integer #if MIN_VERSION_integer_gmp(0,5,1) os2ip bs = unsafePerformIO $ withForeignPtr fptr $ \ptr -> let !(Ptr ad) = (ptr `plusPtr` ofs) #if __GLASGOW_HASKELL__ >= 710 in importIntegerFromAddr ad (int2Word# n) 1# #else in IO $ \s -> importIntegerFromAddr ad (int2Word# n) 1# s #endif where !(fptr, ofs, !(I# n)) = B.toForeignPtr bs {-# NOINLINE os2ip #-} #else os2ip = B.foldl' (\a b -> (256 * a) .|. (fromIntegral b)) 0 {-# INLINE os2ip #-} #endif -- | i2osp converts a positive integer into a byte string i2osp :: Integer -> ByteString #if MIN_VERSION_integer_gmp(0,5,1) i2osp 0 = B.singleton 0 i2osp m = B.unsafeCreate (I# (word2Int# sz)) fillPtr where !sz = sizeInBaseInteger m 256# #if __GLASGOW_HASKELL__ >= 710 fillPtr (Ptr srcAddr) = void $ exportIntegerToAddr m srcAddr 1# #else fillPtr (Ptr srcAddr) = IO $ \s -> case exportIntegerToAddr m srcAddr 1# s of (# s2, _ #) -> (# s2, () #) #endif {-# NOINLINE i2osp #-} #else i2osp m | m < 0 = error "i2osp: cannot convert a negative integer to a bytestring" | otherwise = B.reverse $ B.unfoldr fdivMod256 m where fdivMod256 0 = Nothing fdivMod256 n = Just (fromIntegral a,b) where (b,a) = divMod256 n #endif -- | just like i2osp, but take an extra parameter for size. -- if the number is too big to fit in @len bytes, nothing is returned -- otherwise the number is padded with 0 to fit the @len required. -- -- FIXME: use unsafeCreate to fill the bytestring i2ospOf :: Int -> Integer -> Maybe ByteString #if MIN_VERSION_integer_gmp(0,5,1) i2ospOf len m | sz <= len = Just $ i2ospOf_ len m | otherwise = Nothing where !sz = I# (word2Int# (sizeInBaseInteger m 256#)) #else i2ospOf len m | lenbytes < len = Just $ B.replicate (len - lenbytes) 0 `B.append` bytes | lenbytes == len = Just bytes | otherwise = Nothing where lenbytes = B.length bytes bytes = i2osp m #endif -- | just like i2ospOf except that it doesn't expect a failure: i.e. -- an integer larger than the number of output bytes requested -- -- for example if you just took a modulo of the number that represent -- the size (example the RSA modulo n). i2ospOf_ :: Int -> Integer -> ByteString #if MIN_VERSION_integer_gmp(0,5,1) i2ospOf_ len m = unsafePerformIO $ B.create len fillPtr where !sz = (sizeInBaseInteger m 256#) isz = I# (word2Int# sz) fillPtr ptr | len < isz = error "cannot compute i2ospOf_ with integer larger than output bytes" | len == isz = let !(Ptr srcAddr) = ptr in #if __GLASGOW_HASKELL__ >= 710 void (exportIntegerToAddr m srcAddr 1#) #else IO $ \s -> case exportIntegerToAddr m srcAddr 1# s of (# s2, _ #) -> (# s2, () #) #endif | otherwise = do let z = len-isz _ <- B.memset ptr 0 (fromIntegral len) let !(Ptr addr) = ptr `plusPtr` z #if __GLASGOW_HASKELL__ >= 710 void (exportIntegerToAddr m addr 1#) #else IO $ \s -> case exportIntegerToAddr m addr 1# s of (# s2, _ #) -> (# s2, () #) #endif {-# NOINLINE i2ospOf_ #-} #else i2ospOf_ len m = B.unsafeCreate len fillPtr where fillPtr srcPtr = loop m (srcPtr `plusPtr` (len-1)) where loop n ptr = do let (nn,a) = divMod256 n poke ptr (fromIntegral a) if ptr == srcPtr then return () else (if nn == 0 then fillerLoop else loop nn) (ptr `plusPtr` (-1)) fillerLoop ptr = do poke ptr 0 if ptr == srcPtr then return () else fillerLoop (ptr `plusPtr` (-1)) {-# INLINE i2ospOf_ #-} #endif -- | returns the number of bytes to store an integer with i2osp -- -- with integer-simple, this function is really slow. lengthBytes :: Integer -> Int #if MIN_VERSION_integer_gmp(0,5,1) lengthBytes n = I# (word2Int# (sizeInBaseInteger n 256#)) #else lengthBytes n | n < 256 = 1 | otherwise = 1 + lengthBytes (n `shiftR` 8) #endif
vincenthz/hs-crypto-numbers
Crypto/Number/Serialize.hs
bsd-2-clause
5,446
0
15
1,487
721
400
321
51
4
module Core.Topology where -- base import Data.List (nub, delete, minimumBy, maximumBy) import Data.Ord (comparing) import Control.Monad -- fgl import Data.Graph.Inductive.Internal.Queue -- Classes class Reversible a where rev :: a -> a rev = id undir :: Reversible a => [a] -> [a] undir as = as ++ map rev as spanQualified :: String -> (String, String) spanQualified txt = case span (/= '.') txt of (ls, rs) | not $ null rs -> (ls, tail rs) | otherwise -> ([], ls) dequalify :: String -> String dequalify = snd . spanQualified qualifier :: String -> String qualifier = fst . spanQualified -- Data type Graph lab = [Edge lab] type Path lab = [Edge lab] type PointName = String type EdgeName = String data Fletching = Reverse | Normal | Common deriving (Eq, Ord, Show) data Edge lab = Edge { origPoint :: PointName, destPoint' :: PointName, origFletching :: Fletching, destFletching' :: Fletching, edgeLabel :: lab } deriving (Eq, Ord, Show) points :: Graph lab -> [PointName] points = nub . concatMap (\ (Edge p p' _ _ _) -> [p, p']) edgeToPoints :: Edge lab -> [(PointName, Fletching)] edgeToPoints (Edge p p' k k' _) = [(p, k), (p', k')] pathToPoints :: Path a -> [(PointName, Fletching)] pathToPoints = filter ((/= Common) . snd) . tail . init . concatMap edgeToPoints instance Reversible lab => Reversible (Edge lab) where rev (Edge p p' k k' lab) = Edge p' p k' k (rev lab) -- Algorithms canonicalizeHome :: [Path lab] -> Path lab canonicalizeHome = canonicalize' flip canonicalizeStart :: [Path lab] -> Path lab canonicalizeStart = canonicalize' id canonicalize' f pss = minimumBy (f $ comparing (map snd . pathToPoints)) $ filter ((== min) . numOfReverse) pss where numOfReverse = length . filter (\ x -> Reverse == snd x) . pathToPoints min = minimum (map numOfReverse pss) findPaths :: Eq lab => (Edge lab -> Bool) -> Graph lab -> Edge lab -> Edge lab-> [Path lab] findPaths isStop g e s | s == e = return [s] | otherwise = do n <- suc g s guard (not (isStop n) || n == e) liftM (s:) $ findPaths isStop (delete s g) e n reachableFromDir :: (Eq lab) => Graph lab -> Edge lab -> [Edge lab] reachableFromDir g e | elem e g = bfenInternal (queuePut e mkQueue) g | otherwise = [] reachable :: Eq lab => (Graph lab -> b -> [Edge lab]) -> Graph lab -> b -> [Edge lab] reachable fromSomething g s = nub $ concatMap (reachableFromDir g) (fromSomething g s) bfenInternal :: (Eq lab) => Queue (Edge lab) -> Graph lab -> [Edge lab] bfenInternal q g | queueEmpty q || null g = [] | otherwise = case match e g of (Just e, g') -> e:bfenInternal (queuePutList (suc g e) q') g' (Nothing, g') -> bfenInternal q' g' where (e,q') = queueGet q match :: Eq lab => Edge lab -> Graph lab -> (Maybe (Edge lab), Graph lab) match e g | elem e g = (Just e, delete e g) | otherwise = (Nothing, g) suc :: Graph lab -> Edge lab -> [Edge lab] suc g (Edge _ p _ Common _) = filter f g where f (Edge q q' k k' lab) = p == q && k /= Common suc g (Edge _ p _ _ _) = filter f g where f (Edge q q' k k' lab) = p == q && k == Common -- Checker fromEdges :: (Reversible lab) => [Edge lab] -> Either String (Graph lab) -- won't consume any input fromEdges = isGraph . undir isGraph :: Graph lab -> Either String (Graph lab) -- won't consume any input isGraph g = mapM_ checkPoint (points g) >> return g where checkPoint :: PointName -> Either String () checkPoint p = do checkNumOf Normal checkNumOf Reverse checkNumOf Common where ks = map origFletching $ filter ((p ==) . origPoint) g checkNumOf k | n > 1 = fail $ show p ++ " have " ++ show n ++ " number of " ++ show k | otherwise = return () where n = length $ filter (k ==) ks
wkoiking/fieldequip
src/Core/Topology.hs
bsd-3-clause
3,873
0
15
976
1,732
886
846
88
2
module Import ( module Import ) where import ClassyPrelude as Import hiding (parseTime) import Yesod as Import hiding (Route (..)) import Yesod.Auth as Import import Text.Julius as Import (rawJS) import Foundation as Import import Model as Import import Settings as Import import Settings.Development as Import import Settings.StaticFiles as Import import Utils as Import myFormSettings :: MyForm App AppMessage res myFormSettings = MyForm { mfTitle = MsgUnknown , mfEnctype = UrlEncoded , mfInfoMsg = (MsgFormOneError, MsgFormNErrors, MsgFormSuccess) , mfRoute = HomeR , mfFields = [whamlet|Unitialized form! This should not happen.|] , mfActions = [whamlet|<input type=submit>|] , mfResult = error "Unitialized result for MyForm" }
SimSaladin/rnfssp
Import.hs
bsd-3-clause
1,057
0
7
426
170
118
52
-1
-1
-- (c) The University of Glasgow 2006 -- (c) The GRASP/AQUA Project, Glasgow University, 1998 -- -- Type - public interface {-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | Main functions for manipulating types and type-related things module Type ( -- Note some of this is just re-exports from TyCon.. -- * Main data types representing Types -- $type_classification -- $representation_types TyThing(..), Type, KindOrType, PredType, ThetaType, Var, TyVar, isTyVar, -- ** Constructing and deconstructing types mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, mkAppTy, mkAppTys, splitAppTy, splitAppTys, splitAppTy_maybe, repSplitAppTy_maybe, mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe, splitFunTys, splitFunTysN, funResultTy, funArgTy, zipFunTys, mkTyConApp, mkTyConTy, tyConAppTyCon_maybe, tyConAppArgs_maybe, tyConAppTyCon, tyConAppArgs, splitTyConApp_maybe, splitTyConApp, tyConAppArgN, nextRole, mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys, mkPiKinds, mkPiType, mkPiTypes, applyTy, applyTys, applyTysD, applyTysX, dropForAlls, mkNumLitTy, isNumLitTy, mkStrLitTy, isStrLitTy, coAxNthLHS, -- (Newtypes) newTyConInstRhs, -- Pred types mkFamilyTyConApp, isDictLikeTy, mkEqPred, mkCoerciblePred, mkPrimEqPred, mkReprPrimEqPred, mkClassPred, isClassPred, isEqPred, isIPPred, isIPPred_maybe, isIPTyCon, isIPClass, -- Deconstructing predicate types PredTree(..), EqRel(..), eqRelRole, classifyPredType, getClassPredTys, getClassPredTys_maybe, getEqPredTys, getEqPredTys_maybe, getEqPredRole, predTypeEqRel, -- ** Common type constructors funTyCon, -- ** Predicates on types isTypeVar, isKindVar, allDistinctTyVars, isForAllTy, isTyVarTy, isFunTy, isDictTy, isPredTy, isVoidTy, -- (Lifting and boxity) isUnLiftedType, isUnboxedTupleType, isAlgType, isClosedAlgType, isPrimitiveType, isStrictType, -- * Main data types representing Kinds -- $kind_subtyping Kind, SimpleKind, MetaKindVar, -- ** Finding the kind of a type typeKind, -- ** Common Kinds and SuperKinds anyKind, liftedTypeKind, unliftedTypeKind, openTypeKind, constraintKind, superKind, -- ** Common Kind type constructors liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon, constraintKindTyCon, anyKindTyCon, -- * Type free variables tyVarsOfType, tyVarsOfTypes, closeOverKinds, expandTypeSynonyms, typeSize, varSetElemsKvsFirst, -- * Type comparison eqType, eqTypeX, eqTypes, cmpType, cmpTypes, eqPred, eqPredX, cmpPred, eqKind, eqTyVarBndrs, -- * Forcing evaluation of types seqType, seqTypes, -- * Other views onto Types coreView, tcView, UnaryType, RepType(..), flattenRepType, repType, tyConsOfType, -- * Type representation for the code generator typePrimRep, typeRepArity, -- * Main type substitution data types TvSubstEnv, -- Representation widely visible TvSubst(..), -- Representation visible to a few friends -- ** Manipulating type substitutions emptyTvSubstEnv, emptyTvSubst, mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst, getTvSubstEnv, setTvSubstEnv, zapTvSubstEnv, getTvInScope, extendTvInScope, extendTvInScopeList, extendTvSubst, extendTvSubstList, isInScope, composeTvSubst, zipTyEnv, isEmptyTvSubst, unionTvSubst, -- ** Performing substitution on types and kinds substTy, substTys, substTyWith, substTysWith, substTheta, substTyVar, substTyVars, substTyVarBndr, cloneTyVarBndr, deShadowTy, lookupTyVar, substKiWith, substKisWith, -- * Pretty-printing pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing, pprTvBndr, pprTvBndrs, pprForAll, pprUserForAll, pprSigmaType, pprTheta, pprThetaArrowTy, pprClassPred, pprKind, pprParendKind, pprSourceTyCon, TyPrec(..), maybeParen, pprSigmaTypeExtraCts, -- * Tidying type related things up for printing tidyType, tidyTypes, tidyOpenType, tidyOpenTypes, tidyOpenKind, tidyTyVarBndr, tidyTyVarBndrs, tidyFreeTyVars, tidyOpenTyVar, tidyOpenTyVars, tidyTyVarOcc, tidyTopType, tidyKind, ) where #include "HsVersions.h" -- We import the representation and primitive functions from TypeRep. -- Many things are reexported, but not the representation! import Kind import TypeRep -- friends: import Var import VarEnv import VarSet import NameEnv import Class import TyCon import TysPrim import {-# SOURCE #-} TysWiredIn ( eqTyCon, coercibleTyCon, typeNatKind, typeSymbolKind ) import PrelNames ( eqTyConKey, coercibleTyConKey, ipClassNameKey, openTypeKindTyConKey, constraintKindTyConKey, liftedTypeKindTyConKey ) import CoAxiom -- others import Unique ( Unique, hasKey ) import BasicTypes ( Arity, RepArity ) import Util import ListSetOps ( getNth ) import Outputable import FastString import Maybes ( orElse ) import Data.Maybe ( isJust ) import Control.Monad ( guard ) infixr 3 `mkFunTy` -- Associates to the right -- $type_classification -- #type_classification# -- -- Types are one of: -- -- [Unboxed] Iff its representation is other than a pointer -- Unboxed types are also unlifted. -- -- [Lifted] Iff it has bottom as an element. -- Closures always have lifted types: i.e. any -- let-bound identifier in Core must have a lifted -- type. Operationally, a lifted object is one that -- can be entered. -- Only lifted types may be unified with a type variable. -- -- [Algebraic] Iff it is a type with one or more constructors, whether -- declared with @data@ or @newtype@. -- An algebraic type is one that can be deconstructed -- with a case expression. This is /not/ the same as -- lifted types, because we also include unboxed -- tuples in this classification. -- -- [Data] Iff it is a type declared with @data@, or a boxed tuple. -- -- [Primitive] Iff it is a built-in type that can't be expressed in Haskell. -- -- Currently, all primitive types are unlifted, but that's not necessarily -- the case: for example, @Int@ could be primitive. -- -- Some primitive types are unboxed, such as @Int#@, whereas some are boxed -- but unlifted (such as @ByteArray#@). The only primitive types that we -- classify as algebraic are the unboxed tuples. -- -- Some examples of type classifications that may make this a bit clearer are: -- -- @ -- Type primitive boxed lifted algebraic -- ----------------------------------------------------------------------------- -- Int# Yes No No No -- ByteArray# Yes Yes No No -- (\# a, b \#) Yes No No Yes -- ( a, b ) No Yes Yes Yes -- [a] No Yes Yes Yes -- @ -- $representation_types -- A /source type/ is a type that is a separate type as far as the type checker is -- concerned, but which has a more low-level representation as far as Core-to-Core -- passes and the rest of the back end is concerned. -- -- You don't normally have to worry about this, as the utility functions in -- this module will automatically convert a source into a representation type -- if they are spotted, to the best of it's abilities. If you don't want this -- to happen, use the equivalent functions from the "TcType" module. {- ************************************************************************ * * Type representation * * ************************************************************************ -} {-# INLINE coreView #-} coreView :: Type -> Maybe Type -- ^ This function Strips off the /top layer only/ of a type synonym -- application (if any) its underlying representation type. -- Returns Nothing if there is nothing to look through. -- -- By being non-recursive and inlined, this case analysis gets efficiently -- joined onto the case analysis that the caller is already doing coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc tys = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys') -- Its important to use mkAppTys, rather than (foldl AppTy), -- because the function part might well return a -- partially-applied type constructor; indeed, usually will! coreView _ = Nothing ----------------------------------------------- {-# INLINE tcView #-} tcView :: Type -> Maybe Type -- ^ Historical only; 'tcView' and 'coreView' used to differ, but don't any more tcView = coreView -- ToDo: get rid of tcView altogether -- You might think that tcView belows in TcType rather than Type, but unfortunately -- it is needed by Unify, which is turn imported by Coercion (for MatchEnv and matchList). -- So we will leave it here to avoid module loops. ----------------------------------------------- expandTypeSynonyms :: Type -> Type -- ^ Expand out all type synonyms. Actually, it'd suffice to expand out -- just the ones that discard type variables (e.g. type Funny a = Int) -- But we don't know which those are currently, so we just expand all. expandTypeSynonyms ty = go ty where go (TyConApp tc tys) | Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc tys = go (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys') | otherwise = TyConApp tc (map go tys) go (LitTy l) = LitTy l go (TyVarTy tv) = TyVarTy tv go (AppTy t1 t2) = mkAppTy (go t1) (go t2) go (FunTy t1 t2) = FunTy (go t1) (go t2) go (ForAllTy tv t) = ForAllTy tv (go t) {- ************************************************************************ * * \subsection{Constructor-specific functions} * * ************************************************************************ --------------------------------------------------------------------- TyVarTy ~~~~~~~ -} -- | Attempts to obtain the type variable underlying a 'Type', and panics with the -- given message if this is not a type variable type. See also 'getTyVar_maybe' getTyVar :: String -> Type -> TyVar getTyVar msg ty = case getTyVar_maybe ty of Just tv -> tv Nothing -> panic ("getTyVar: " ++ msg) isTyVarTy :: Type -> Bool isTyVarTy ty = isJust (getTyVar_maybe ty) -- | Attempts to obtain the type variable underlying a 'Type' getTyVar_maybe :: Type -> Maybe TyVar getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty' getTyVar_maybe (TyVarTy tv) = Just tv getTyVar_maybe _ = Nothing allDistinctTyVars :: [KindOrType] -> Bool allDistinctTyVars tkvs = go emptyVarSet tkvs where go _ [] = True go so_far (ty : tys) = case getTyVar_maybe ty of Nothing -> False Just tv | tv `elemVarSet` so_far -> False | otherwise -> go (so_far `extendVarSet` tv) tys {- --------------------------------------------------------------------- AppTy ~~~~~ We need to be pretty careful with AppTy to make sure we obey the invariant that a TyConApp is always visibly so. mkAppTy maintains the invariant: use it. Note [Decomposing fat arrow c=>t] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Can we unify (a b) with (Eq a => ty)? If we do so, we end up with a partial application like ((=>) Eq a) which doesn't make sense in source Haskell. In constrast, we *can* unify (a b) with (t1 -> t2). Here's an example (Trac #9858) of how you might do it: i :: (Typeable a, Typeable b) => Proxy (a b) -> TypeRep i p = typeRep p j = i (Proxy :: Proxy (Eq Int => Int)) The type (Proxy (Eq Int => Int)) is only accepted with -XImpredicativeTypes, but suppose we want that. But then in the call to 'i', we end up decomposing (Eq Int => Int), and we definitely don't want that. This really only applies to the type checker; in Core, '=>' and '->' are the same, as are 'Constraint' and '*'. But for now I've put the test in repSplitAppTy_maybe, which applies throughout, because the other calls to splitAppTy are in Unify, which is also used by the type checker (e.g. when matching type-function equations). -} -- | Applies a type to another, as in e.g. @k a@ mkAppTy :: Type -> Type -> Type mkAppTy (TyConApp tc tys) ty2 = mkTyConApp tc (tys ++ [ty2]) mkAppTy ty1 ty2 = AppTy ty1 ty2 -- Note that the TyConApp could be an -- under-saturated type synonym. GHC allows that; e.g. -- type Foo k = k a -> k a -- type Id x = x -- foo :: Foo Id -> Foo Id -- -- Here Id is partially applied in the type sig for Foo, -- but once the type synonyms are expanded all is well mkAppTys :: Type -> [Type] -> Type mkAppTys ty1 [] = ty1 mkAppTys (TyConApp tc tys1) tys2 = mkTyConApp tc (tys1 ++ tys2) mkAppTys ty1 tys2 = foldl AppTy ty1 tys2 ------------- splitAppTy_maybe :: Type -> Maybe (Type, Type) -- ^ Attempt to take a type application apart, whether it is a -- function, type constructor, or plain type application. Note -- that type family applications are NEVER unsaturated by this! splitAppTy_maybe ty | Just ty' <- coreView ty = splitAppTy_maybe ty' splitAppTy_maybe ty = repSplitAppTy_maybe ty ------------- repSplitAppTy_maybe :: Type -> Maybe (Type,Type) -- ^ Does the AppTy split as in 'splitAppTy_maybe', but assumes that -- any Core view stuff is already done repSplitAppTy_maybe (FunTy ty1 ty2) | isConstraintKind (typeKind ty1) = Nothing -- See Note [Decomposing fat arrow c=>t] | otherwise = Just (TyConApp funTyCon [ty1], ty2) repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2) repSplitAppTy_maybe (TyConApp tc tys) | isDecomposableTyCon tc || tys `lengthExceeds` tyConArity tc , Just (tys', ty') <- snocView tys = Just (TyConApp tc tys', ty') -- Never create unsaturated type family apps! repSplitAppTy_maybe _other = Nothing ------------- splitAppTy :: Type -> (Type, Type) -- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe', -- and panics if this is not possible splitAppTy ty = case splitAppTy_maybe ty of Just pr -> pr Nothing -> panic "splitAppTy" ------------- splitAppTys :: Type -> (Type, [Type]) -- ^ Recursively splits a type as far as is possible, leaving a residual -- type being applied to and the type arguments applied to it. Never fails, -- even if that means returning an empty list of type applications. splitAppTys ty = split ty ty [] where split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args split _ (AppTy ty arg) args = split ty ty (arg:args) split _ (TyConApp tc tc_args) args = let -- keep type families saturated n | isDecomposableTyCon tc = 0 | otherwise = tyConArity tc (tc_args1, tc_args2) = splitAt n tc_args in (TyConApp tc tc_args1, tc_args2 ++ args) split _ (FunTy ty1 ty2) args = ASSERT( null args ) (TyConApp funTyCon [], [ty1,ty2]) split orig_ty _ args = (orig_ty, args) {- LitTy ~~~~~ -} mkNumLitTy :: Integer -> Type mkNumLitTy n = LitTy (NumTyLit n) -- | Is this a numeric literal. We also look through type synonyms. isNumLitTy :: Type -> Maybe Integer isNumLitTy ty | Just ty1 <- tcView ty = isNumLitTy ty1 isNumLitTy (LitTy (NumTyLit n)) = Just n isNumLitTy _ = Nothing mkStrLitTy :: FastString -> Type mkStrLitTy s = LitTy (StrTyLit s) -- | Is this a symbol literal. We also look through type synonyms. isStrLitTy :: Type -> Maybe FastString isStrLitTy ty | Just ty1 <- tcView ty = isStrLitTy ty1 isStrLitTy (LitTy (StrTyLit s)) = Just s isStrLitTy _ = Nothing {- --------------------------------------------------------------------- FunTy ~~~~~ -} mkFunTy :: Type -> Type -> Type -- ^ Creates a function type from the given argument and result type mkFunTy arg res = FunTy arg res mkFunTys :: [Type] -> Type -> Type mkFunTys tys ty = foldr mkFunTy ty tys isFunTy :: Type -> Bool isFunTy ty = isJust (splitFunTy_maybe ty) splitFunTy :: Type -> (Type, Type) -- ^ Attempts to extract the argument and result types from a type, and -- panics if that is not possible. See also 'splitFunTy_maybe' splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty' splitFunTy (FunTy arg res) = (arg, res) splitFunTy other = pprPanic "splitFunTy" (ppr other) splitFunTy_maybe :: Type -> Maybe (Type, Type) -- ^ Attempts to extract the argument and result types from a type splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty' splitFunTy_maybe (FunTy arg res) = Just (arg, res) splitFunTy_maybe _ = Nothing splitFunTys :: Type -> ([Type], Type) splitFunTys ty = split [] ty ty where split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty' split args _ (FunTy arg res) = split (arg:args) res res split args orig_ty _ = (reverse args, orig_ty) splitFunTysN :: Int -> Type -> ([Type], Type) -- ^ Split off exactly the given number argument types, and panics if that is not possible splitFunTysN 0 ty = ([], ty) splitFunTysN n ty = ASSERT2( isFunTy ty, int n <+> ppr ty ) case splitFunTy ty of { (arg, res) -> case splitFunTysN (n-1) res of { (args, res) -> (arg:args, res) }} -- | Splits off argument types from the given type and associating -- them with the things in the input list from left to right. The -- final result type is returned, along with the resulting pairs of -- objects and types, albeit with the list of pairs in reverse order. -- Panics if there are not enough argument types for the input list. zipFunTys :: Outputable a => [a] -> Type -> ([(a, Type)], Type) zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty where split acc [] nty _ = (reverse acc, nty) split acc xs nty ty | Just ty' <- coreView ty = split acc xs nty ty' split acc (x:xs) _ (FunTy arg res) = split ((x,arg):acc) xs res res split _ _ _ _ = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty) funResultTy :: Type -> Type -- ^ Extract the function result type and panic if that is not possible funResultTy ty | Just ty' <- coreView ty = funResultTy ty' funResultTy (FunTy _arg res) = res funResultTy ty = pprPanic "funResultTy" (ppr ty) funArgTy :: Type -> Type -- ^ Extract the function argument type and panic if that is not possible funArgTy ty | Just ty' <- coreView ty = funArgTy ty' funArgTy (FunTy arg _res) = arg funArgTy ty = pprPanic "funArgTy" (ppr ty) {- --------------------------------------------------------------------- TyConApp ~~~~~~~~ -} -- | A key function: builds a 'TyConApp' or 'FunTy' as appropriate to -- its arguments. Applies its arguments to the constructor from left to right. mkTyConApp :: TyCon -> [Type] -> Type mkTyConApp tycon tys | isFunTyCon tycon, [ty1,ty2] <- tys = FunTy ty1 ty2 | otherwise = TyConApp tycon tys -- splitTyConApp "looks through" synonyms, because they don't -- mean a distinct type, but all other type-constructor applications -- including functions are returned as Just .. -- | The same as @fst . splitTyConApp@ tyConAppTyCon_maybe :: Type -> Maybe TyCon tyConAppTyCon_maybe ty | Just ty' <- coreView ty = tyConAppTyCon_maybe ty' tyConAppTyCon_maybe (TyConApp tc _) = Just tc tyConAppTyCon_maybe (FunTy {}) = Just funTyCon tyConAppTyCon_maybe _ = Nothing tyConAppTyCon :: Type -> TyCon tyConAppTyCon ty = tyConAppTyCon_maybe ty `orElse` pprPanic "tyConAppTyCon" (ppr ty) -- | The same as @snd . splitTyConApp@ tyConAppArgs_maybe :: Type -> Maybe [Type] tyConAppArgs_maybe ty | Just ty' <- coreView ty = tyConAppArgs_maybe ty' tyConAppArgs_maybe (TyConApp _ tys) = Just tys tyConAppArgs_maybe (FunTy arg res) = Just [arg,res] tyConAppArgs_maybe _ = Nothing tyConAppArgs :: Type -> [Type] tyConAppArgs ty = tyConAppArgs_maybe ty `orElse` pprPanic "tyConAppArgs" (ppr ty) tyConAppArgN :: Int -> Type -> Type -- Executing Nth tyConAppArgN n ty = case tyConAppArgs_maybe ty of Just tys -> ASSERT2( n < length tys, ppr n <+> ppr tys ) tys !! n Nothing -> pprPanic "tyConAppArgN" (ppr n <+> ppr ty) -- | Attempts to tease a type apart into a type constructor and the application -- of a number of arguments to that constructor. Panics if that is not possible. -- See also 'splitTyConApp_maybe' splitTyConApp :: Type -> (TyCon, [Type]) splitTyConApp ty = case splitTyConApp_maybe ty of Just stuff -> stuff Nothing -> pprPanic "splitTyConApp" (ppr ty) -- | Attempts to tease a type apart into a type constructor and the application -- of a number of arguments to that constructor splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type]) splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty' splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys) splitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res]) splitTyConApp_maybe _ = Nothing -- | What is the role assigned to the next parameter of this type? Usually, -- this will be 'Nominal', but if the type is a 'TyConApp', we may be able to -- do better. The type does *not* have to be well-kinded when applied for this -- to work! nextRole :: Type -> Role nextRole ty | Just (tc, tys) <- splitTyConApp_maybe ty , let num_tys = length tys , num_tys < tyConArity tc = tyConRoles tc `getNth` num_tys | otherwise = Nominal newTyConInstRhs :: TyCon -> [Type] -> Type -- ^ Unwrap one 'layer' of newtype on a type constructor and its -- arguments, using an eta-reduced version of the @newtype@ if possible. -- This requires tys to have at least @newTyConInstArity tycon@ elements. newTyConInstRhs tycon tys = ASSERT2( tvs `leLength` tys, ppr tycon $$ ppr tys $$ ppr tvs ) applyTysX tvs rhs tys where (tvs, rhs) = newTyConEtadRhs tycon {- --------------------------------------------------------------------- SynTy ~~~~~ Notes on type synonyms ~~~~~~~~~~~~~~~~~~~~~~ The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try to return type synonyms wherever possible. Thus type Foo a = a -> a we want splitFunTys (a -> Foo a) = ([a], Foo a) not ([a], a -> a) The reason is that we then get better (shorter) type signatures in interfaces. Notably this plays a role in tcTySigs in TcBinds.hs. Representation types ~~~~~~~~~~~~~~~~~~~~ Note [Nullary unboxed tuple] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We represent the nullary unboxed tuple as the unary (but void) type Void#. The reason for this is that the ReprArity is never less than the Arity (as it would otherwise be for a function type like (# #) -> Int). As a result, ReprArity is always strictly positive if Arity is. This is important because it allows us to distinguish at runtime between a thunk and a function takes a nullary unboxed tuple as an argument! -} type UnaryType = Type data RepType = UbxTupleRep [UnaryType] -- INVARIANT: never an empty list (see Note [Nullary unboxed tuple]) | UnaryRep UnaryType flattenRepType :: RepType -> [UnaryType] flattenRepType (UbxTupleRep tys) = tys flattenRepType (UnaryRep ty) = [ty] -- | Looks through: -- -- 1. For-alls -- 2. Synonyms -- 3. Predicates -- 4. All newtypes, including recursive ones, but not newtype families -- -- It's useful in the back end of the compiler. repType :: Type -> RepType repType ty = go initRecTc ty where go :: RecTcChecker -> Type -> RepType go rec_nts ty -- Expand predicates and synonyms | Just ty' <- coreView ty = go rec_nts ty' go rec_nts (ForAllTy _ ty) -- Drop foralls = go rec_nts ty go rec_nts (TyConApp tc tys) -- Expand newtypes | isNewTyCon tc , tys `lengthAtLeast` tyConArity tc , Just rec_nts' <- checkRecTc rec_nts tc -- See Note [Expanding newtypes] in TyCon = go rec_nts' (newTyConInstRhs tc tys) | isUnboxedTupleTyCon tc = if null tys then UnaryRep voidPrimTy -- See Note [Nullary unboxed tuple] else UbxTupleRep (concatMap (flattenRepType . go rec_nts) tys) go _ ty = UnaryRep ty -- | All type constructors occurring in the type; looking through type -- synonyms, but not newtypes. -- When it finds a Class, it returns the class TyCon. tyConsOfType :: Type -> NameEnv TyCon tyConsOfType ty = go ty where go :: Type -> NameEnv TyCon -- The NameEnv does duplicate elim go ty | Just ty' <- tcView ty = go ty' go (TyVarTy {}) = emptyNameEnv go (LitTy {}) = emptyNameEnv go (TyConApp tc tys) = go_tc tc tys go (AppTy a b) = go a `plusNameEnv` go b go (FunTy a b) = go a `plusNameEnv` go b go (ForAllTy _ ty) = go ty go_tc tc tys = extendNameEnv (go_s tys) (tyConName tc) tc go_s tys = foldr (plusNameEnv . go) emptyNameEnv tys -- ToDo: this could be moved to the code generator, using splitTyConApp instead -- of inspecting the type directly. -- | Discovers the primitive representation of a more abstract 'UnaryType' typePrimRep :: UnaryType -> PrimRep typePrimRep ty = case repType ty of UbxTupleRep _ -> pprPanic "typePrimRep: UbxTupleRep" (ppr ty) UnaryRep rep -> case rep of TyConApp tc _ -> tyConPrimRep tc FunTy _ _ -> PtrRep AppTy _ _ -> PtrRep -- See Note [AppTy rep] TyVarTy _ -> PtrRep _ -> pprPanic "typePrimRep: UnaryRep" (ppr ty) typeRepArity :: Arity -> Type -> RepArity typeRepArity 0 _ = 0 typeRepArity n ty = case repType ty of UnaryRep (FunTy ty1 ty2) -> length (flattenRepType (repType ty1)) + typeRepArity (n - 1) ty2 _ -> pprPanic "typeRepArity: arity greater than type can handle" (ppr (n, ty)) isVoidTy :: Type -> Bool -- True if the type has zero width isVoidTy ty = case repType ty of UnaryRep (TyConApp tc _) -> isVoidRep (tyConPrimRep tc) _ -> False {- Note [AppTy rep] ~~~~~~~~~~~~~~~~ Types of the form 'f a' must be of kind *, not #, so we are guaranteed that they are represented by pointers. The reason is that f must have kind (kk -> kk) and kk cannot be unlifted; see Note [The kind invariant] in TypeRep. --------------------------------------------------------------------- ForAllTy ~~~~~~~~ -} mkForAllTy :: TyVar -> Type -> Type mkForAllTy tyvar ty = ForAllTy tyvar ty -- | Wraps foralls over the type using the provided 'TyVar's from left to right mkForAllTys :: [TyVar] -> Type -> Type mkForAllTys tyvars ty = foldr ForAllTy ty tyvars mkPiKinds :: [TyVar] -> Kind -> Kind -- mkPiKinds [k1, k2, (a:k1 -> *)] k2 -- returns forall k1 k2. (k1 -> *) -> k2 mkPiKinds [] res = res mkPiKinds (tv:tvs) res | isKindVar tv = ForAllTy tv (mkPiKinds tvs res) | otherwise = FunTy (tyVarKind tv) (mkPiKinds tvs res) mkPiType :: Var -> Type -> Type -- ^ Makes a @(->)@ type or a forall type, depending -- on whether it is given a type variable or a term variable. mkPiTypes :: [Var] -> Type -> Type -- ^ 'mkPiType' for multiple type or value arguments mkPiType v ty | isId v = mkFunTy (varType v) ty | otherwise = mkForAllTy v ty mkPiTypes vs ty = foldr mkPiType ty vs isForAllTy :: Type -> Bool isForAllTy (ForAllTy _ _) = True isForAllTy _ = False -- | Attempts to take a forall type apart, returning the bound type variable -- and the remainder of the type splitForAllTy_maybe :: Type -> Maybe (TyVar, Type) splitForAllTy_maybe ty = splitFAT_m ty where splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty' splitFAT_m (ForAllTy tyvar ty) = Just(tyvar, ty) splitFAT_m _ = Nothing -- | Attempts to take a forall type apart, returning all the immediate such bound -- type variables and the remainder of the type. Always suceeds, even if that means -- returning an empty list of 'TyVar's splitForAllTys :: Type -> ([TyVar], Type) splitForAllTys ty = split ty ty [] where split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs split _ (ForAllTy tv ty) tvs = split ty ty (tv:tvs) split orig_ty _ tvs = (reverse tvs, orig_ty) -- | Equivalent to @snd . splitForAllTys@ dropForAlls :: Type -> Type dropForAlls ty = snd (splitForAllTys ty) {- -- (mkPiType now in CoreUtils) applyTy, applyTys ~~~~~~~~~~~~~~~~~ -} -- | Instantiate a forall type with one or more type arguments. -- Used when we have a polymorphic function applied to type args: -- -- > f t1 t2 -- -- We use @applyTys type-of-f [t1,t2]@ to compute the type of the expression. -- Panics if no application is possible. applyTy :: Type -> KindOrType -> Type applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty applyTy _ _ = panic "applyTy" applyTys :: Type -> [KindOrType] -> Type -- ^ This function is interesting because: -- -- 1. The function may have more for-alls than there are args -- -- 2. Less obviously, it may have fewer for-alls -- -- For case 2. think of: -- -- > applyTys (forall a.a) [forall b.b, Int] -- -- This really can happen, but only (I think) in situations involving -- undefined. For example: -- undefined :: forall a. a -- Term: undefined @(forall b. b->b) @Int -- This term should have type (Int -> Int), but notice that -- there are more type args than foralls in 'undefined's type. -- If you edit this function, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs applyTys ty args = applyTysD empty ty args applyTysD :: SDoc -> Type -> [Type] -> Type -- Debug version applyTysD _ orig_fun_ty [] = orig_fun_ty applyTysD doc orig_fun_ty arg_tys | n_tvs == n_args -- The vastly common case = substTyWith tvs arg_tys rho_ty | n_tvs > n_args -- Too many for-alls = substTyWith (take n_args tvs) arg_tys (mkForAllTys (drop n_args tvs) rho_ty) | otherwise -- Too many type args = ASSERT2( n_tvs > 0, doc $$ ppr orig_fun_ty $$ ppr arg_tys ) -- Zero case gives infinite loop! applyTysD doc (substTyWith tvs (take n_tvs arg_tys) rho_ty) (drop n_tvs arg_tys) where (tvs, rho_ty) = splitForAllTys orig_fun_ty n_tvs = length tvs n_args = length arg_tys applyTysX :: [TyVar] -> Type -> [Type] -> Type -- applyTyxX beta-reduces (/\tvs. body_ty) arg_tys applyTysX tvs body_ty arg_tys = ASSERT2( length arg_tys >= n_tvs, ppr tvs $$ ppr body_ty $$ ppr arg_tys ) mkAppTys (substTyWith tvs (take n_tvs arg_tys) body_ty) (drop n_tvs arg_tys) where n_tvs = length tvs {- ************************************************************************ * * Pred * * ************************************************************************ Predicates on PredType -} isPredTy :: Type -> Bool -- NB: isPredTy is used when printing types, which can happen in debug printing -- during type checking of not-fully-zonked types. So it's not cool to say -- isConstraintKind (typeKind ty) because absent zonking the type might -- be ill-kinded, and typeKind crashes -- Hence the rather tiresome story here isPredTy ty = go ty [] where go :: Type -> [KindOrType] -> Bool go (AppTy ty1 ty2) args = go ty1 (ty2 : args) go (TyConApp tc tys) args = go_k (tyConKind tc) (tys ++ args) go (TyVarTy tv) args = go_k (tyVarKind tv) args go _ _ = False go_k :: Kind -> [KindOrType] -> Bool -- True <=> kind is k1 -> .. -> kn -> Constraint go_k k [] = isConstraintKind k go_k (FunTy _ k1) (_ :args) = go_k k1 args go_k (ForAllTy kv k1) (k2:args) = go_k (substKiWith [kv] [k2] k1) args go_k _ _ = False -- Typeable * Int :: Constraint isClassPred, isEqPred, isIPPred :: PredType -> Bool isClassPred ty = case tyConAppTyCon_maybe ty of Just tyCon | isClassTyCon tyCon -> True _ -> False isEqPred ty = case tyConAppTyCon_maybe ty of Just tyCon -> tyCon `hasKey` eqTyConKey _ -> False isIPPred ty = case tyConAppTyCon_maybe ty of Just tc -> isIPTyCon tc _ -> False isIPTyCon :: TyCon -> Bool isIPTyCon tc = tc `hasKey` ipClassNameKey isIPClass :: Class -> Bool isIPClass cls = cls `hasKey` ipClassNameKey -- Class and it corresponding TyCon have the same Unique isIPPred_maybe :: Type -> Maybe (FastString, Type) isIPPred_maybe ty = do (tc,[t1,t2]) <- splitTyConApp_maybe ty guard (isIPTyCon tc) x <- isStrLitTy t1 return (x,t2) {- Make PredTypes --------------------- Equality types --------------------------------- -} -- | Creates a type equality predicate mkEqPred :: Type -> Type -> PredType mkEqPred ty1 ty2 = WARN( not (k `eqKind` typeKind ty2), ppr ty1 $$ ppr ty2 $$ ppr k $$ ppr (typeKind ty2) ) TyConApp eqTyCon [k, ty1, ty2] where k = typeKind ty1 mkCoerciblePred :: Type -> Type -> PredType mkCoerciblePred ty1 ty2 = WARN( not (k `eqKind` typeKind ty2), ppr ty1 $$ ppr ty2 $$ ppr k $$ ppr (typeKind ty2) ) TyConApp coercibleTyCon [k, ty1, ty2] where k = typeKind ty1 mkPrimEqPred :: Type -> Type -> Type mkPrimEqPred ty1 ty2 = WARN( not (k `eqKind` typeKind ty2), ppr ty1 $$ ppr ty2 ) TyConApp eqPrimTyCon [k, ty1, ty2] where k = typeKind ty1 mkReprPrimEqPred :: Type -> Type -> Type mkReprPrimEqPred ty1 ty2 = WARN( not (k `eqKind` typeKind ty2), ppr ty1 $$ ppr ty2 ) TyConApp eqReprPrimTyCon [k, ty1, ty2] where k = typeKind ty1 -- --------------------- Dictionary types --------------------------------- mkClassPred :: Class -> [Type] -> PredType mkClassPred clas tys = TyConApp (classTyCon clas) tys isDictTy :: Type -> Bool isDictTy = isClassPred isDictLikeTy :: Type -> Bool -- Note [Dictionary-like types] isDictLikeTy ty | Just ty' <- coreView ty = isDictLikeTy ty' isDictLikeTy ty = case splitTyConApp_maybe ty of Just (tc, tys) | isClassTyCon tc -> True | isTupleTyCon tc -> all isDictLikeTy tys _other -> False {- Note [Dictionary-like types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Being "dictionary-like" means either a dictionary type or a tuple thereof. In GHC 6.10 we build implication constraints which construct such tuples, and if we land up with a binding t :: (C [a], Eq [a]) t = blah then we want to treat t as cheap under "-fdicts-cheap" for example. (Implication constraints are normally inlined, but sadly not if the occurrence is itself inside an INLINE function! Until we revise the handling of implication constraints, that is.) This turned out to be important in getting good arities in DPH code. Example: class C a class D a where { foo :: a -> a } instance C a => D (Maybe a) where { foo x = x } bar :: (C a, C b) => a -> b -> (Maybe a, Maybe b) {-# INLINE bar #-} bar x y = (foo (Just x), foo (Just y)) Then 'bar' should jolly well have arity 4 (two dicts, two args), but we ended up with something like bar = __inline_me__ (\d1,d2. let t :: (D (Maybe a), D (Maybe b)) = ... in \x,y. <blah>) This is all a bit ad-hoc; eg it relies on knowing that implication constraints build tuples. Decomposing PredType -} -- | A choice of equality relation. This is separate from the type 'Role' -- because 'Phantom' does not define a (non-trivial) equality relation. data EqRel = NomEq | ReprEq deriving (Eq, Ord) instance Outputable EqRel where ppr NomEq = text "nominal equality" ppr ReprEq = text "representational equality" eqRelRole :: EqRel -> Role eqRelRole NomEq = Nominal eqRelRole ReprEq = Representational data PredTree = ClassPred Class [Type] | EqPred EqRel Type Type | TuplePred [PredType] | IrredPred PredType classifyPredType :: PredType -> PredTree classifyPredType ev_ty = case splitTyConApp_maybe ev_ty of Just (tc, tys) | tc `hasKey` coercibleTyConKey , let [_, ty1, ty2] = tys -> EqPred ReprEq ty1 ty2 Just (tc, tys) | tc `hasKey` eqTyConKey , let [_, ty1, ty2] = tys -> EqPred NomEq ty1 ty2 -- NB: Coercible is also a class, so this check must come *after* -- the Coercible check Just (tc, tys) | Just clas <- tyConClass_maybe tc -> ClassPred clas tys Just (tc, tys) | isTupleTyCon tc -> TuplePred tys _ -> IrredPred ev_ty getClassPredTys :: PredType -> (Class, [Type]) getClassPredTys ty = case getClassPredTys_maybe ty of Just (clas, tys) -> (clas, tys) Nothing -> pprPanic "getClassPredTys" (ppr ty) getClassPredTys_maybe :: PredType -> Maybe (Class, [Type]) getClassPredTys_maybe ty = case splitTyConApp_maybe ty of Just (tc, tys) | Just clas <- tyConClass_maybe tc -> Just (clas, tys) _ -> Nothing getEqPredTys :: PredType -> (Type, Type) getEqPredTys ty = case splitTyConApp_maybe ty of Just (tc, (_ : ty1 : ty2 : tys)) -> ASSERT( null tys && (tc `hasKey` eqTyConKey || tc `hasKey` coercibleTyConKey) ) (ty1, ty2) _ -> pprPanic "getEqPredTys" (ppr ty) getEqPredTys_maybe :: PredType -> Maybe (Role, Type, Type) getEqPredTys_maybe ty = case splitTyConApp_maybe ty of Just (tc, [_, ty1, ty2]) | tc `hasKey` eqTyConKey -> Just (Nominal, ty1, ty2) | tc `hasKey` coercibleTyConKey -> Just (Representational, ty1, ty2) _ -> Nothing getEqPredRole :: PredType -> Role getEqPredRole ty = case splitTyConApp_maybe ty of Just (tc, [_, _, _]) | tc `hasKey` eqTyConKey -> Nominal | tc `hasKey` coercibleTyConKey -> Representational _ -> pprPanic "getEqPredRole" (ppr ty) -- | Get the equality relation relevant for a pred type. predTypeEqRel :: PredType -> EqRel predTypeEqRel ty | Just (tc, _) <- splitTyConApp_maybe ty , tc `hasKey` coercibleTyConKey = ReprEq | otherwise = NomEq {- %************************************************************************ %* * Size * * ************************************************************************ -} typeSize :: Type -> Int typeSize (LitTy {}) = 1 typeSize (TyVarTy {}) = 1 typeSize (AppTy t1 t2) = typeSize t1 + typeSize t2 typeSize (FunTy t1 t2) = typeSize t1 + typeSize t2 typeSize (ForAllTy _ t) = 1 + typeSize t typeSize (TyConApp _ ts) = 1 + sum (map typeSize ts) {- ************************************************************************ * * \subsection{Type families} * * ************************************************************************ -} mkFamilyTyConApp :: TyCon -> [Type] -> Type -- ^ Given a family instance TyCon and its arg types, return the -- corresponding family type. E.g: -- -- > data family T a -- > data instance T (Maybe b) = MkT b -- -- Where the instance tycon is :RTL, so: -- -- > mkFamilyTyConApp :RTL Int = T (Maybe Int) mkFamilyTyConApp tc tys | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc , let tvs = tyConTyVars tc fam_subst = ASSERT2( length tvs == length tys, ppr tc <+> ppr tys ) zipTopTvSubst tvs tys = mkTyConApp fam_tc (substTys fam_subst fam_tys) | otherwise = mkTyConApp tc tys -- | Get the type on the LHS of a coercion induced by a type/data -- family instance. coAxNthLHS :: CoAxiom br -> Int -> Type coAxNthLHS ax ind = mkTyConApp (coAxiomTyCon ax) (coAxBranchLHS (coAxiomNthBranch ax ind)) -- | Pretty prints a 'TyCon', using the family instance in case of a -- representation tycon. For example: -- -- > data T [a] = ... -- -- In that case we want to print @T [a]@, where @T@ is the family 'TyCon' pprSourceTyCon :: TyCon -> SDoc pprSourceTyCon tycon | Just (fam_tc, tys) <- tyConFamInst_maybe tycon = ppr $ fam_tc `TyConApp` tys -- can't be FunTyCon | otherwise = ppr tycon {- ************************************************************************ * * \subsection{Liftedness} * * ************************************************************************ -} -- | See "Type#type_classification" for what an unlifted type is isUnLiftedType :: Type -> Bool -- isUnLiftedType returns True for forall'd unlifted types: -- x :: forall a. Int# -- I found bindings like these were getting floated to the top level. -- They are pretty bogus types, mind you. It would be better never to -- construct them isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty' isUnLiftedType (ForAllTy _ ty) = isUnLiftedType ty isUnLiftedType (TyConApp tc _) = isUnLiftedTyCon tc isUnLiftedType _ = False isUnboxedTupleType :: Type -> Bool isUnboxedTupleType ty = case tyConAppTyCon_maybe ty of Just tc -> isUnboxedTupleTyCon tc _ -> False -- | See "Type#type_classification" for what an algebraic type is. -- Should only be applied to /types/, as opposed to e.g. partially -- saturated type constructors isAlgType :: Type -> Bool isAlgType ty = case splitTyConApp_maybe ty of Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc ) isAlgTyCon tc _other -> False -- | See "Type#type_classification" for what an algebraic type is. -- Should only be applied to /types/, as opposed to e.g. partially -- saturated type constructors. Closed type constructors are those -- with a fixed right hand side, as opposed to e.g. associated types isClosedAlgType :: Type -> Bool isClosedAlgType ty = case splitTyConApp_maybe ty of Just (tc, ty_args) | isAlgTyCon tc && not (isFamilyTyCon tc) -> ASSERT2( ty_args `lengthIs` tyConArity tc, ppr ty ) True _other -> False -- | Computes whether an argument (or let right hand side) should -- be computed strictly or lazily, based only on its type. -- Currently, it's just 'isUnLiftedType'. isStrictType :: Type -> Bool isStrictType = isUnLiftedType isPrimitiveType :: Type -> Bool -- ^ Returns true of types that are opaque to Haskell. isPrimitiveType ty = case splitTyConApp_maybe ty of Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc ) isPrimTyCon tc _ -> False {- ************************************************************************ * * \subsection{Sequencing on types} * * ************************************************************************ -} seqType :: Type -> () seqType (LitTy n) = n `seq` () seqType (TyVarTy tv) = tv `seq` () seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2 seqType (FunTy t1 t2) = seqType t1 `seq` seqType t2 seqType (TyConApp tc tys) = tc `seq` seqTypes tys seqType (ForAllTy tv ty) = seqType (tyVarKind tv) `seq` seqType ty seqTypes :: [Type] -> () seqTypes [] = () seqTypes (ty:tys) = seqType ty `seq` seqTypes tys {- ************************************************************************ * * Comparison for types (We don't use instances so that we know where it happens) * * ************************************************************************ -} eqKind :: Kind -> Kind -> Bool -- Watch out for horrible hack: See Note [Comparison with OpenTypeKind] eqKind = eqType eqType :: Type -> Type -> Bool -- ^ Type equality on source types. Does not look through @newtypes@ or -- 'PredType's, but it does look through type synonyms. -- Watch out for horrible hack: See Note [Comparison with OpenTypeKind] eqType t1 t2 = isEqual $ cmpType t1 t2 instance Eq Type where (==) = eqType eqTypeX :: RnEnv2 -> Type -> Type -> Bool eqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2 eqTypes :: [Type] -> [Type] -> Bool eqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2 eqPred :: PredType -> PredType -> Bool eqPred = eqType eqPredX :: RnEnv2 -> PredType -> PredType -> Bool eqPredX env p1 p2 = isEqual $ cmpTypeX env p1 p2 eqTyVarBndrs :: RnEnv2 -> [TyVar] -> [TyVar] -> Maybe RnEnv2 -- Check that the tyvar lists are the same length -- and have matching kinds; if so, extend the RnEnv2 -- Returns Nothing if they don't match eqTyVarBndrs env [] [] = Just env eqTyVarBndrs env (tv1:tvs1) (tv2:tvs2) | eqTypeX env (tyVarKind tv1) (tyVarKind tv2) = eqTyVarBndrs (rnBndr2 env tv1 tv2) tvs1 tvs2 eqTyVarBndrs _ _ _= Nothing -- Now here comes the real worker cmpType :: Type -> Type -> Ordering -- Watch out for horrible hack: See Note [Comparison with OpenTypeKind] cmpType t1 t2 = cmpTypeX rn_env t1 t2 where rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2)) cmpTypes :: [Type] -> [Type] -> Ordering cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2 where rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2)) cmpPred :: PredType -> PredType -> Ordering cmpPred p1 p2 = cmpTypeX rn_env p1 p2 where rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType p1 `unionVarSet` tyVarsOfType p2)) cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse cmpTypeX env t1 t2 | Just t1' <- coreView t1 = cmpTypeX env t1' t2 | Just t2' <- coreView t2 = cmpTypeX env t1 t2' -- We expand predicate types, because in Core-land we have -- lots of definitions like -- fOrdBool :: Ord Bool -- fOrdBool = D:Ord .. .. .. -- So the RHS has a data type cmpTypeX env (TyVarTy tv1) (TyVarTy tv2) = rnOccL env tv1 `compare` rnOccR env tv2 cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2) = cmpTypeX env (tyVarKind tv1) (tyVarKind tv2) `thenCmp` cmpTypeX (rnBndr2 env tv1 tv2) t1 t2 cmpTypeX env (AppTy s1 t1) (AppTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2 cmpTypeX env (FunTy s1 t1) (FunTy s2 t2) = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `cmpTc` tc2) `thenCmp` cmpTypesX env tys1 tys2 cmpTypeX _ (LitTy l1) (LitTy l2) = compare l1 l2 -- Deal with the rest: TyVarTy < AppTy < FunTy < LitTy < TyConApp < ForAllTy < PredTy cmpTypeX _ (AppTy _ _) (TyVarTy _) = GT cmpTypeX _ (FunTy _ _) (TyVarTy _) = GT cmpTypeX _ (FunTy _ _) (AppTy _ _) = GT cmpTypeX _ (LitTy _) (TyVarTy _) = GT cmpTypeX _ (LitTy _) (AppTy _ _) = GT cmpTypeX _ (LitTy _) (FunTy _ _) = GT cmpTypeX _ (TyConApp _ _) (TyVarTy _) = GT cmpTypeX _ (TyConApp _ _) (AppTy _ _) = GT cmpTypeX _ (TyConApp _ _) (FunTy _ _) = GT cmpTypeX _ (TyConApp _ _) (LitTy _) = GT cmpTypeX _ (ForAllTy _ _) (TyVarTy _) = GT cmpTypeX _ (ForAllTy _ _) (AppTy _ _) = GT cmpTypeX _ (ForAllTy _ _) (FunTy _ _) = GT cmpTypeX _ (ForAllTy _ _) (LitTy _) = GT cmpTypeX _ (ForAllTy _ _) (TyConApp _ _) = GT cmpTypeX _ _ _ = LT ------------- cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering cmpTypesX _ [] [] = EQ cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2 cmpTypesX _ [] _ = LT cmpTypesX _ _ [] = GT ------------- cmpTc :: TyCon -> TyCon -> Ordering -- Here we treat * and Constraint as equal -- See Note [Kind Constraint and kind *] in Kinds.hs -- -- Also we treat OpenTypeKind as equal to either * or # -- See Note [Comparison with OpenTypeKind] cmpTc tc1 tc2 | u1 == openTypeKindTyConKey, isSubOpenTypeKindKey u2 = EQ | u2 == openTypeKindTyConKey, isSubOpenTypeKindKey u1 = EQ | otherwise = nu1 `compare` nu2 where u1 = tyConUnique tc1 nu1 = if u1==constraintKindTyConKey then liftedTypeKindTyConKey else u1 u2 = tyConUnique tc2 nu2 = if u2==constraintKindTyConKey then liftedTypeKindTyConKey else u2 {- Note [Comparison with OpenTypeKind] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In PrimOpWrappers we have things like PrimOpWrappers.mkWeak# = /\ a b c. Prim.mkWeak# a b c where Prim.mkWeak# :: forall (a:Open) b c. a -> b -> c -> State# RealWorld -> (# State# RealWorld, Weak# b #) Now, eta reduction will turn the definition into PrimOpWrappers.mkWeak# = Prim.mkWeak# which is kind-of OK, but now the types aren't really equal. So HACK HACK we pretend (in Core) that Open is equal to * or #. I hate this. Note [cmpTypeX] ~~~~~~~~~~~~~~~ When we compare foralls, we should look at the kinds. But if we do so, we get a corelint error like the following (in libraries/ghc-prim/GHC/PrimopWrappers.hs): Binder's type: forall (o_abY :: *). o_abY -> GHC.Prim.State# GHC.Prim.RealWorld -> GHC.Prim.State# GHC.Prim.RealWorld Rhs type: forall (a_12 :: ?). a_12 -> GHC.Prim.State# GHC.Prim.RealWorld -> GHC.Prim.State# GHC.Prim.RealWorld This is why we don't look at the kind. Maybe we should look if the kinds are compatible. -- cmpTypeX env (ForAllTy tv1 t1) (ForAllTy tv2 t2) -- = cmpTypeX env (tyVarKind tv1) (tyVarKind tv2) `thenCmp` -- cmpTypeX (rnBndr2 env tv1 tv2) t1 t2 ************************************************************************ * * Type substitutions * * ************************************************************************ -} emptyTvSubstEnv :: TvSubstEnv emptyTvSubstEnv = emptyVarEnv composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv -- ^ @(compose env1 env2)(x)@ is @env1(env2(x))@; i.e. apply @env2@ then @env1@. -- It assumes that both are idempotent. -- Typically, @env1@ is the refinement to a base substitution @env2@ composeTvSubst in_scope env1 env2 = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2 -- First apply env1 to the range of env2 -- Then combine the two, making sure that env1 loses if -- both bind the same variable; that's why env1 is the -- *left* argument to plusVarEnv, because the right arg wins where subst1 = TvSubst in_scope env1 emptyTvSubst :: TvSubst emptyTvSubst = TvSubst emptyInScopeSet emptyTvSubstEnv isEmptyTvSubst :: TvSubst -> Bool -- See Note [Extending the TvSubstEnv] in TypeRep isEmptyTvSubst (TvSubst _ tenv) = isEmptyVarEnv tenv mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst mkTvSubst = TvSubst getTvSubstEnv :: TvSubst -> TvSubstEnv getTvSubstEnv (TvSubst _ env) = env getTvInScope :: TvSubst -> InScopeSet getTvInScope (TvSubst in_scope _) = in_scope isInScope :: Var -> TvSubst -> Bool isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope notElemTvSubst :: CoVar -> TvSubst -> Bool notElemTvSubst v (TvSubst _ tenv) = not (v `elemVarEnv` tenv) setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst setTvSubstEnv (TvSubst in_scope _) tenv = TvSubst in_scope tenv zapTvSubstEnv :: TvSubst -> TvSubst zapTvSubstEnv (TvSubst in_scope _) = TvSubst in_scope emptyVarEnv extendTvInScope :: TvSubst -> Var -> TvSubst extendTvInScope (TvSubst in_scope tenv) var = TvSubst (extendInScopeSet in_scope var) tenv extendTvInScopeList :: TvSubst -> [Var] -> TvSubst extendTvInScopeList (TvSubst in_scope tenv) vars = TvSubst (extendInScopeSetList in_scope vars) tenv extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst extendTvSubst (TvSubst in_scope tenv) tv ty = TvSubst in_scope (extendVarEnv tenv tv ty) extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst extendTvSubstList (TvSubst in_scope tenv) tvs tys = TvSubst in_scope (extendVarEnvList tenv (tvs `zip` tys)) unionTvSubst :: TvSubst -> TvSubst -> TvSubst -- Works when the ranges are disjoint unionTvSubst (TvSubst in_scope1 tenv1) (TvSubst in_scope2 tenv2) = ASSERT( not (tenv1 `intersectsVarEnv` tenv2) ) TvSubst (in_scope1 `unionInScope` in_scope2) (tenv1 `plusVarEnv` tenv2) -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from -- the types given; but it's just a thunk so with a bit of luck -- it'll never be evaluated -- Note [Generating the in-scope set for a substitution] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- If we want to substitute [a -> ty1, b -> ty2] I used to -- think it was enough to generate an in-scope set that includes -- fv(ty1,ty2). But that's not enough; we really should also take the -- free vars of the type we are substituting into! Example: -- (forall b. (a,b,x)) [a -> List b] -- Then if we use the in-scope set {b}, there is a danger we will rename -- the forall'd variable to 'x' by mistake, getting this: -- (forall x. (List b, x, x) -- Urk! This means looking at all the calls to mkOpenTvSubst.... -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming -- environment, hence "open" mkOpenTvSubst :: TvSubstEnv -> TvSubst mkOpenTvSubst tenv = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts tenv))) tenv -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming -- environment, hence "open" zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst zipOpenTvSubst tyvars tys | debugIsOn && (length tyvars /= length tys) = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst | otherwise = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys) -- | Called when doing top-level substitutions. Here we expect that the -- free vars of the range of the substitution will be empty. mkTopTvSubst :: [(TyVar, Type)] -> TvSubst mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs) zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst zipTopTvSubst tyvars tys | debugIsOn && (length tyvars /= length tys) = pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst | otherwise = TvSubst emptyInScopeSet (zipTyEnv tyvars tys) zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv zipTyEnv tyvars tys | debugIsOn && (length tyvars /= length tys) = pprTrace "zipTyEnv" (ppr tyvars $$ ppr tys) emptyVarEnv | otherwise = zip_ty_env tyvars tys emptyVarEnv -- Later substitutions in the list over-ride earlier ones, -- but there should be no loops zip_ty_env :: [TyVar] -> [Type] -> TvSubstEnv -> TvSubstEnv zip_ty_env [] [] env = env zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty) -- There used to be a special case for when -- ty == TyVarTy tv -- (a not-uncommon case) in which case the substitution was dropped. -- But the type-tidier changes the print-name of a type variable without -- changing the unique, and that led to a bug. Why? Pre-tidying, we had -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype. -- And it happened that t was the type variable of the class. Post-tiding, -- it got turned into {Foo t2}. The ext-core printer expanded this using -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique, -- and so generated a rep type mentioning t not t2. -- -- Simplest fix is to nuke the "optimisation" zip_ty_env tvs tys env = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env -- zip_ty_env _ _ env = env instance Outputable TvSubst where ppr (TvSubst ins tenv) = brackets $ sep[ ptext (sLit "TvSubst"), nest 2 (ptext (sLit "In scope:") <+> ppr ins), nest 2 (ptext (sLit "Type env:") <+> ppr tenv) ] {- ************************************************************************ * * Performing type or kind substitutions * * ************************************************************************ -} -- | Type substitution making use of an 'TvSubst' that -- is assumed to be open, see 'zipOpenTvSubst' substTyWith :: [TyVar] -> [Type] -> Type -> Type substTyWith tvs tys = ASSERT( length tvs == length tys ) substTy (zipOpenTvSubst tvs tys) substKiWith :: [KindVar] -> [Kind] -> Kind -> Kind substKiWith = substTyWith -- | Type substitution making use of an 'TvSubst' that -- is assumed to be open, see 'zipOpenTvSubst' substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type] substTysWith tvs tys = ASSERT( length tvs == length tys ) substTys (zipOpenTvSubst tvs tys) substKisWith :: [KindVar] -> [Kind] -> [Kind] -> [Kind] substKisWith = substTysWith -- | Substitute within a 'Type' substTy :: TvSubst -> Type -> Type substTy subst ty | isEmptyTvSubst subst = ty | otherwise = subst_ty subst ty -- | Substitute within several 'Type's substTys :: TvSubst -> [Type] -> [Type] substTys subst tys | isEmptyTvSubst subst = tys | otherwise = map (subst_ty subst) tys -- | Substitute within a 'ThetaType' substTheta :: TvSubst -> ThetaType -> ThetaType substTheta subst theta | isEmptyTvSubst subst = theta | otherwise = map (substTy subst) theta -- | Remove any nested binders mentioning the 'TyVar's in the 'TyVarSet' deShadowTy :: TyVarSet -> Type -> Type deShadowTy tvs ty = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty where in_scope = mkInScopeSet tvs subst_ty :: TvSubst -> Type -> Type -- subst_ty is the main workhorse for type substitution -- -- Note that the in_scope set is poked only if we hit a forall -- so it may often never be fully computed subst_ty subst ty = go ty where go (LitTy n) = n `seq` LitTy n go (TyVarTy tv) = substTyVar subst tv go (TyConApp tc tys) = let args = map go tys in args `seqList` TyConApp tc args go (FunTy arg res) = (FunTy $! (go arg)) $! (go res) go (AppTy fun arg) = mkAppTy (go fun) $! (go arg) -- The mkAppTy smart constructor is important -- we might be replacing (a Int), represented with App -- by [Int], represented with TyConApp go (ForAllTy tv ty) = case substTyVarBndr subst tv of (subst', tv') -> ForAllTy tv' $! (subst_ty subst' ty) substTyVar :: TvSubst -> TyVar -> Type substTyVar (TvSubst _ tenv) tv | Just ty <- lookupVarEnv tenv tv = ty -- See Note [Apply Once] | otherwise = ASSERT( isTyVar tv ) TyVarTy tv -- in TypeRep -- We do not require that the tyvar is in scope -- Reason: we do quite a bit of (substTyWith [tv] [ty] tau) -- and it's a nuisance to bring all the free vars of tau into -- scope --- and then force that thunk at every tyvar -- Instead we have an ASSERT in substTyVarBndr to check for capture substTyVars :: TvSubst -> [TyVar] -> [Type] substTyVars subst tvs = map (substTyVar subst) tvs lookupTyVar :: TvSubst -> TyVar -> Maybe Type -- See Note [Extending the TvSubst] in TypeRep lookupTyVar (TvSubst _ tenv) tv = lookupVarEnv tenv tv substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar) substTyVarBndr subst@(TvSubst in_scope tenv) old_var = ASSERT2( _no_capture, ppr old_var $$ ppr subst ) (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var) where new_env | no_change = delVarEnv tenv old_var | otherwise = extendVarEnv tenv old_var (TyVarTy new_var) _no_capture = not (new_var `elemVarSet` tyVarsOfTypes (varEnvElts tenv)) -- Assertion check that we are not capturing something in the substitution old_ki = tyVarKind old_var no_kind_change = isEmptyVarSet (tyVarsOfType old_ki) -- verify that kind is closed no_change = no_kind_change && (new_var == old_var) -- no_change means that the new_var is identical in -- all respects to the old_var (same unique, same kind) -- See Note [Extending the TvSubst] in TypeRep -- -- In that case we don't need to extend the substitution -- to map old to new. But instead we must zap any -- current substitution for the variable. For example: -- (\x.e) with id_subst = [x |-> e'] -- Here we must simply zap the substitution for x new_var | no_kind_change = uniqAway in_scope old_var | otherwise = uniqAway in_scope $ updateTyVarKind (substTy subst) old_var -- The uniqAway part makes sure the new variable is not already in scope cloneTyVarBndr :: TvSubst -> TyVar -> Unique -> (TvSubst, TyVar) cloneTyVarBndr (TvSubst in_scope tv_env) tv uniq = (TvSubst (extendInScopeSet in_scope tv') (extendVarEnv tv_env tv (mkTyVarTy tv')), tv') where tv' = setVarUnique tv uniq -- Simply set the unique; the kind -- has no type variables to worry about {- ---------------------------------------------------- -- Kind Stuff Kinds ~~~~~ For the description of subkinding in GHC, see http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/TypeType#Kinds -} type MetaKindVar = TyVar -- invariant: MetaKindVar will always be a -- TcTyVar with details MetaTv (TauTv ...) ... -- meta kind var constructors and functions are in TcType type SimpleKind = Kind {- ************************************************************************ * * The kind of a type * * ************************************************************************ -} typeKind :: Type -> Kind typeKind orig_ty = go orig_ty where go ty@(TyConApp tc tys) | isPromotedTyCon tc = ASSERT( tyConArity tc == length tys ) superKind | otherwise = kindAppResult (ptext (sLit "typeKind 1") <+> ppr ty $$ ppr orig_ty) (tyConKind tc) tys go ty@(AppTy fun arg) = kindAppResult (ptext (sLit "typeKind 2") <+> ppr ty $$ ppr orig_ty) (go fun) [arg] go (LitTy l) = typeLiteralKind l go (ForAllTy _ ty) = go ty go (TyVarTy tyvar) = tyVarKind tyvar go _ty@(FunTy _arg res) -- Hack alert. The kind of (Int -> Int#) is liftedTypeKind (*), -- not unliftedTypeKind (#) -- The only things that can be after a function arrow are -- (a) types (of kind openTypeKind or its sub-kinds) -- (b) kinds (of super-kind TY) (e.g. * -> (* -> *)) | isSuperKind k = k | otherwise = ASSERT2( isSubOpenTypeKind k, ppr _ty $$ ppr k ) liftedTypeKind where k = go res typeLiteralKind :: TyLit -> Kind typeLiteralKind l = case l of NumTyLit _ -> typeNatKind StrTyLit _ -> typeSymbolKind {- Kind inference ~~~~~~~~~~~~~~ During kind inference, a kind variable unifies only with a "simple kind", sk sk ::= * | sk1 -> sk2 For example data T a = MkT a (T Int#) fails. We give T the kind (k -> *), and the kind variable k won't unify with # (the kind of Int#). Type inference ~~~~~~~~~~~~~~ When creating a fresh internal type variable, we give it a kind to express constraints on it. E.g. in (\x->e) we make up a fresh type variable for x, with kind ??. During unification we only bind an internal type variable to a type whose kind is lower in the sub-kind hierarchy than the kind of the tyvar. When unifying two internal type variables, we collect their kind constraints by finding the GLB of the two. Since the partial order is a tree, they only have a glb if one is a sub-kind of the other. In that case, we bind the less-informative one to the more informative one. Neat, eh? -}
christiaanb/ghc
compiler/types/Type.hs
bsd-3-clause
66,842
0
14
18,137
13,095
6,884
6,211
-1
-1
{-# LANGUAGE NoMonomorphismRestriction #-} module Diagrams.Swimunit.Axis where import Diagrams.Prelude import Diagrams.Backend.SVG.CmdLine import Diagrams.Swimunit.Base {-| Constructs the vertical baseline of height height. -} verticaxis :: Double -> Diagram B verticaxis hght = vrule hght -- Setting line color here would override color setting of resulting diagram. -- # lc lime # alignX (-1.00) # alignY (-1.00) {-| Constructs the horizontal baseline of width width. -} horizaxis :: Double -> Diagram B horizaxis wdth = hrule wdth -- Setting line color here would override color setting of resulting diagram. -- # lc lime # alignX (-1.00) # alignY (-1.00) {-| Constructs horizontal ticks for the vertical axis. -} verticticks :: [Double] -- ^ List of y-values for ticks. -> Double -- ^ Horizontal width covered by each tick. -> Double -- ^ -1.0 fully in ... 0.0 centered ... +1.0 fully out. -> Diagram B -- ^ Resulting diagram. verticticks ylist wdth inout = ( if (length ylist > 0) then position (zip (map (\y -> p2(0.0, y)) ylist) (repeat (hrule wdth # alignX inout)) ) else emptyd ) {- Constructs vertical labels. -} verticlabel :: [String] -- ^ List of y-labels. -> Double -- ^ Text size. -> Diagram B -- ^ Resulting diagram. verticlabel ylabel sze = ( verticlabel' ylabel -- list of y-labels (map (\s -> p2(0.0, read s)) ylabel) -- list of P2-positions from y-labels sze -- size ) {-| Constructs vertical labels from position and string. -} verticlabel' :: [String] -- ^ List of y-labels. -> [P2 Double] -- ^ List of positions. -> Double -- ^ Text size. -> Diagram B -- ^ Resulting diagram. verticlabel' ylabel xypos sze = ( if (length ylabel > 0) then position (zip xypos -- list of P2-positions (map (\s -> (verticlabeltext s sze)) ylabel) -- list of labeling diagrams ) else emptyd ) {-| Constructs the visual representation of one vertical grid label. -} verticlabeltext :: String -- ^ List of y-labels. -> Double -- ^ Text size. -> Diagram B -- ^ Resulting diagram. verticlabeltext label sze = ( alignedText 1.0 0.5 label # scale sze <> hrule sze ) -- ---- --
wherkendell/diagrams-contrib
src/Diagrams/Swimunit/Axis.hs
bsd-3-clause
3,275
0
15
1,557
477
264
213
48
2
{-# LANGUAGE InstanceSigs #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} -- | Alternative applicative presentation -- -- http://blog.ezyang.com/2012/08/applicative-functors/ module Applicative where class Applicative' f where unit :: f () (***) :: f a -> f b -> f (a, b) instance (Functor f, Applicative' f) => Applicative f where pure :: a -> f a pure x = const x <$> unit (<*>) :: f (a -> b) -> f a -> f b f <*> x = (\(l, r) -> l r) <$> (f *** x)
sleexyz/haskell-fun
Applicative.hs
bsd-3-clause
501
0
10
111
179
96
83
12
0
module Test.BigOh.Fit.Naive ( Order , fit , polyOrder , deriv ) where import Test.BigOh.Fit.Base type Order = Int -- ahahaha -- | Estimate the polynomial order for some points, given -- a margin of error. -- polyOrder :: Double -> [Point] -> Maybe Order polyOrder epsilon points@(_:_:_:_) | isConstant points = Just 0 | otherwise = fmap succ $ polyOrder epsilon $ deriv points where isConstant derivs = sd (fmap snd derivs) < epsilon polyOrder _ _ = Nothing deriv :: [Point] -> [Point] deriv points = let gs = zipWith gradient points (drop 1 points) in zip (fmap fst points) gs gradient :: Point -> Point -> Double gradient (x1, y1) (x2, y2) = (y2 - y1) / (x2 - x1) -- doesn't work very well, just use polyOrder fit :: Order -> [Point] -> Bool fit order points = go (100 :: Int) startEpsilon where startEpsilon = 2.1e-6 -- 0.1 * sd (fmap snd points) go 0 _ = False go n e = case polyOrder e points of -- haven't found an order Nothing -> go (n - 1) (e * 2 / 3) -- found an order Just order' -- but it's not the right one, it's less | order' < order -> go (n - 1) (e * 2) -- but it's not the right one, it's more | order' > order -> go (n - 1) (e * 2 / 3) -- bingo | otherwise -> True
tranma/big-oh
src/Test/BigOh/Fit/Naive.hs
bsd-3-clause
1,434
0
14
493
466
246
220
41
3
-- | Results of application of the production rules of a grammar. {-# LANGUAGE ScopedTypeVariables #-} module Data.Cfg.RuleApplication( language, yields, directlyYields ) where import Control.Monad(liftM, msum) import Control.Monad.Omega import Data.Cfg.Cfg import qualified Data.DList as DL import qualified Data.Map.Strict as M import qualified Data.Set as S -- | Given a grammar and a string of symbols, returns the strings -- yielded by application of a production rule; that is, by expanding -- one nonterminal in the string. directlyYields :: (Cfg cfg t nt) => cfg t nt -> Vs t nt -> [Vs t nt] directlyYields cfg vs = do i <- [0..length vs - 1] let (pre, NT nt : post) = splitAt i vs expansion <- S.toList $ productionRules cfg nt return (pre ++ expansion ++ post) -- | Given a grammar, returns all strings yielded by application of -- production rules. yields :: forall cfg t nt . (Cfg cfg t nt, Ord nt) => cfg t nt -> [Vs t nt] yields cfg = map DL.toList $ runOmega $ yieldNT (startSymbol cfg) where yieldNT :: nt -> Omega (DL.DList (V t nt)) yieldNT nt = memoMap M.! nt where memoMap :: M.Map nt (Omega (DL.DList (V t nt))) memoMap = M.fromList [(nt', yieldNT' nt') | nt' <- S.toList $ nonterminals cfg] yieldNT' :: nt -> Omega (DL.DList (V t nt)) yieldNT' nt' = msum (return (DL.singleton (NT nt')) : map yieldVs rhss) where rhss = S.toList $ productionRules cfg nt' yieldV :: V t nt -> Omega (DL.DList (V t nt)) yieldV v = case v of NT nt -> yieldNT nt t -> return $ DL.singleton t yieldVs :: Vs t nt -> Omega (DL.DList (V t nt)) yieldVs = liftM DL.concat . mapM yieldV -- NOTE: you shouldn't get symbol strings repeating if the grammar is -- unambiguous. -- | Given a grammar, returns all strings of terminals yielded by -- application of the production rules to the start symbol. This is -- the /language/ of the grammar. language :: (Cfg cfg t nt, Ord nt) => cfg t nt -> [Vs t nt] -- TODO There's certainly a more efficient way to do this. language = filter (all isT) . yields
nedervold/context-free-grammar
src/Data/Cfg/RuleApplication.hs
bsd-3-clause
2,256
0
16
632
681
355
326
38
2
{-# LANGUAGE OverloadedStrings,RecordWildCards,TypeSynonymInstances,DeriveDataTypeable #-} module Data.CrawlerParameters ( CrawlParams(..),MongoParams(..), _PROGRAM_NAME,_PROGRAM_VERSION,_PROGRAM_INFO,_PROGRAM_ABOUT,_COPYRIGHT, processParams ) where import Control.Monad import Data.Maybe import Data.Text (Text) import qualified Data.Text as T import Data.Time (Day,NominalDiffTime) import Data.Word (Word16) import qualified Database.Persist.MongoDB as Mongo import Network (PortID (PortNumber)) import System.Console.CmdArgs.Implicit import System.Exit (ExitCode(..),exitWith) data CrawlParams = CrawlParams { courtesyPeriod :: Int, -- ^Courtesy period in micro seconds pdfPath :: FilePath, publishedFrom :: Maybe Day, publishedUntil :: Maybe Day} deriving (Show) data MongoParams = MongoParams { db :: Mongo.Database, host :: Mongo.HostName, port :: PortID, auth :: Maybe Mongo.MongoAuth, dt :: NominalDiffTime, mode :: Mongo.AccessMode} deriving Show data AppParams = AppParams { paramCourtesyPeriod :: Int, paramFrom :: String, paramUntil :: String, paramPdfPath :: FilePath, paramMongoDb :: String, paramMongoHost :: String, paramMongoPort :: Word16, paramMongoUser :: String, paramMongoPassword :: String, paramMongoNominalDiffTime :: Int } deriving (Show,Data,Typeable) instance Default Mongo.Database where def = "" appParams = AppParams { paramCourtesyPeriod = def &= help "Courtesy period in micro seconds between successive accesses to the web site (default 2s)" &= explicit &= name "courtesyperiod", paramFrom = def &= help "Only report publications not before this date (default: no restriction, format: YYYY-MM-DD)" &= typ "DAY" &= explicit &= name "from" &= name "f", paramUntil = def &= help "Only report publications not after this date (default: no restriction, format: YYYY-MM-DD)" &= typ "DAY" &= explicit &= name "until" &= name "u", paramPdfPath = def &= help "Output path for pdf files (default ./)" &= typDir &= explicit &= name "pdfpath" &= name "p", paramMongoDb = def &= help "Name of the MongoDB database where to write the publications to (default 'BIS')" &= explicit &= name "db", paramMongoHost = def &= help "Host of the MongoDB database (default 127.0.0.1)" &= explicit &= name "host", paramMongoPort = def &= help "Port of the MongoDB host (default 27017)" &= explicit &= name "port", paramMongoUser = def &= help "User name for MongoDB (default: no authentication)" &= explicit &= name "user", paramMongoPassword = def &= help "Password for MongoDB" &= explicit &= name "password", paramMongoNominalDiffTime = def &= help "Time a connection is left idle before closing (default 2000)" &= explicit &= name "nominaldifftime" } &= versionArg [explicit, name "version", name "v", summary _PROGRAM_INFO] &= summary (_PROGRAM_INFO ++ ", " ++ _COPYRIGHT) &= help _PROGRAM_ABOUT &= helpArg [explicit, name "help", name "h"] &= program _PROGRAM_NAME _PROGRAM_NAME = "bcbs-crawl" _PROGRAM_VERSION = "0.2" _PROGRAM_INFO = _PROGRAM_NAME ++ " version " ++ _PROGRAM_VERSION _PROGRAM_ABOUT = "Crawls the BCBS publications at www.bis.org" _COPYRIGHT = "(C) Torsten Kemps-Benedix 2014" fromString :: Read a => String -> Maybe a fromString s = if s=="" then Nothing else let prs = reads s in if null prs then Nothing else Just (fst (head prs)) processParams :: IO (MongoParams, CrawlParams) processParams = do params <- cmdArgs appParams let ct = let x = paramCourtesyPeriod params in if x==0 then 2000000 else fromIntegral x let t0 = fromString (paramFrom params) :: Maybe Day let t1 = fromString (paramUntil params) :: Maybe Day let db = T.pack $ let x = paramMongoDb params in if null x then "BCBS" else x let host = let h = paramMongoHost params in if null h then "127.0.0.1" else h let port = let p = fromIntegral $ paramMongoPort params in if p==0 then PortNumber 27017 else PortNumber p let auth = if null (paramMongoUser params) then Nothing else Just (Mongo.MongoAuth (T.pack $ paramMongoUser params) (T.pack $ paramMongoPassword params)) let dt = let x = paramMongoNominalDiffTime params in if x==0 then 2000 else fromIntegral x when (dt<=0) $ do putStrLn "Nominal diff time must be positive!" exitWith (ExitFailure 1) putStr "Crawl www.bis.org for publications" case t0 of Just t0' -> case t1 of Just t1' -> putStrLn $ " between "++show t0'++" and "++show t1' Nothing -> putStrLn $ " after "++show t0' Nothing -> case t1 of Just t1' -> putStrLn $ " before "++show t1' Nothing -> putStrLn "" putStrLn $ "Courtesy period: "++show (1e-6*fromIntegral ct)++"s" putStrLn "" putStrLn $ "Connect to MongoDB "++T.unpack db++" at "++host++":"++show port putStrLn $ "MongoDB authentication: "++show auth putStrLn $ "Nomminal diff time: "++show dt putStrLn "" let mongoP = MongoParams{mode=Mongo.master,..} let crawlP = CrawlParams{courtesyPeriod=ct, pdfPath=paramPdfPath params, publishedFrom=t0, publishedUntil=t1} return (mongoP,crawlP)
tkemps/bcbs-crawler
src/Data/CrawlerParameters.hs
bsd-3-clause
5,604
0
17
1,443
1,480
766
714
136
10
{-# LANGUAGE GeneralizedNewtypeDeriving, ConstraintKinds, PatternGuards #-} {-# OPTIONS_GHC -O0 #-} module Idris.Parser(module Idris.Parser, module Idris.ParseExpr, module Idris.ParseData, module Idris.ParseHelpers, module Idris.ParseOps) where import Prelude hiding (pi) import qualified System.Directory as Dir (makeAbsolute) import Text.Trifecta.Delta import Text.Trifecta hiding (span, stringLiteral, charLiteral, natural, symbol, char, string, whiteSpace, Err) import Text.Parser.LookAhead import Text.Parser.Expression import qualified Text.Parser.Token as Tok import qualified Text.Parser.Char as Chr import qualified Text.Parser.Token.Highlight as Hi import Text.PrettyPrint.ANSI.Leijen (Doc, plain) import qualified Text.PrettyPrint.ANSI.Leijen as ANSI import Idris.AbsSyntax hiding (namespace, params) import Idris.DSL import Idris.Imports import Idris.Delaborate import Idris.Error import Idris.Elab.Value import Idris.Elab.Term import Idris.ElabDecls import Idris.Coverage import Idris.IBC import Idris.Unlit import Idris.Providers import Idris.Output import Idris.ParseHelpers import Idris.ParseOps import Idris.ParseExpr import Idris.ParseData import Idris.Docstrings hiding (Unchecked) import Paths_idris import Util.DynamicLinker import Util.System (readSource, writeSource) import qualified Util.Pretty as P import Idris.Core.TT import Idris.Core.Evaluate import Control.Applicative hiding (Const) import Control.Monad import Control.Monad.State.Strict import Data.Function import Data.Maybe import qualified Data.List.Split as Spl import Data.List import Data.Monoid import Data.Char import Data.Ord import Data.Generics.Uniplate.Data (descendM) import qualified Data.Map as M import qualified Data.HashSet as HS import qualified Data.Text as T import qualified Data.ByteString.UTF8 as UTF8 import qualified Data.Set as S import Debug.Trace import System.FilePath import System.IO {- @ grammar shortcut notation: ~CHARSEQ = complement of char sequence (i.e. any character except CHARSEQ) RULE? = optional rule (i.e. RULE or nothing) RULE* = repeated rule (i.e. RULE zero or more times) RULE+ = repeated rule with at least one match (i.e. RULE one or more times) RULE! = invalid rule (i.e. rule that is not valid in context, report meaningful error in case) RULE{n} = rule repeated n times @ -} {- * Main grammar -} {- | Parses module definition @ ModuleHeader ::= DocComment_t? 'module' Identifier_t ';'?; @ -} moduleHeader :: IdrisParser (Maybe (Docstring ()), [String], [(FC, OutputAnnotation)]) moduleHeader = try (do docs <- optional docComment noArgs docs reserved "module" (i, ifc) <- identifier option ';' (lchar ';') let modName = moduleName i return (fmap fst docs, modName, [(ifc, AnnNamespace (map T.pack modName) Nothing)])) <|> try (do lchar '%'; reserved "unqualified" return (Nothing, [], [])) <|> return (Nothing, moduleName "Main", []) where moduleName x = case span (/='.') x of (x, "") -> [x] (x, '.':y) -> x : moduleName y noArgs (Just (_, args)) | not (null args) = fail "Modules do not take arguments" noArgs _ = return () data ImportInfo = ImportInfo { import_reexport :: Bool , import_path :: FilePath , import_rename :: Maybe (String, FC) , import_namespace :: [T.Text] , import_location :: FC , import_modname_location :: FC } {- | Parses an import statement @ Import ::= 'import' Identifier_t ';'?; @ -} import_ :: IdrisParser ImportInfo import_ = do fc <- getFC reserved "import" reexport <- option False (do reserved "public"; return True) (id, idfc) <- identifier newName <- optional (reserved "as" *> identifier) option ';' (lchar ';') return $ ImportInfo reexport (toPath id) (fmap (\(n, fc) -> (toPath n, fc)) newName) (map T.pack $ ns id) fc idfc <?> "import statement" where ns = Spl.splitOn "." toPath = foldl1' (</>) . ns {- | Parses program source @ Prog ::= Decl* EOF; @ -} prog :: SyntaxInfo -> IdrisParser [PDecl] prog syn = do whiteSpace decls <- many (decl syn) let c = (concat decls) case maxline syn of Nothing -> do notOpenBraces; eof _ -> return () ist <- get fc <- getFC put ist { idris_parsedSpan = Just (FC (fc_fname fc) (0,0) (fc_end fc)), ibc_write = IBCParsedRegion fc : ibc_write ist } return c {-| Parses a top-level declaration @ Decl ::= Decl' | Using | Params | Mutual | Namespace | Class | Instance | DSL | Directive | Provider | Transform | Import! ; @ -} decl :: SyntaxInfo -> IdrisParser [PDecl] decl syn = do fc <- getFC -- if we're after maxline, stop here let continue = case maxline syn of Nothing -> True Just l -> if fst (fc_end fc) > l then mut_nesting syn /= 0 else True if continue then do notEndBlock declBody else fail "End of readable input" where declBody :: IdrisParser [PDecl] declBody = declBody' <|> using_ syn <|> params syn <|> mutual syn <|> namespace syn <|> class_ syn <|> instance_ syn <|> do d <- dsl syn; return [d] <|> directive syn <|> provider syn <|> transform syn <|> do import_; fail "imports must be at top of file" <?> "declaration" declBody' :: IdrisParser [PDecl] declBody' = do d <- decl' syn i <- get let d' = fmap (debindApp syn . (desugar syn i)) d return [d'] {- | Parses a top-level declaration with possible syntax sugar @ Decl' ::= Fixity | FunDecl' | Data | Record | SyntaxDecl ; @ -} decl' :: SyntaxInfo -> IdrisParser PDecl decl' syn = fixity <|> syntaxDecl syn <|> fnDecl' syn <|> data_ syn <|> record syn <?> "declaration" {- | Parses a syntax extension declaration (and adds the rule to parser state) @ SyntaxDecl ::= SyntaxRule; @ -} syntaxDecl :: SyntaxInfo -> IdrisParser PDecl syntaxDecl syn = do s <- syntaxRule syn i <- get put (i `addSyntax` s) fc <- getFC return (PSyntax fc s) -- | Extend an 'IState' with a new syntax extension. See also 'addReplSyntax'. addSyntax :: IState -> Syntax -> IState addSyntax i s = i { syntax_rules = updateSyntaxRules [s] rs, syntax_keywords = ks ++ ns, ibc_write = IBCSyntax s : map IBCKeyword ks ++ ibc } where rs = syntax_rules i ns = syntax_keywords i ibc = ibc_write i ks = map show (syntaxNames s) -- | Like 'addSyntax', but no effect on the IBC. addReplSyntax :: IState -> Syntax -> IState addReplSyntax i s = i { syntax_rules = updateSyntaxRules [s] rs, syntax_keywords = ks ++ ns } where rs = syntax_rules i ns = syntax_keywords i ks = map show (syntaxNames s) {- | Parses a syntax extension declaration @ SyntaxRuleOpts ::= 'term' | 'pattern'; @ @ SyntaxRule ::= SyntaxRuleOpts? 'syntax' SyntaxSym+ '=' TypeExpr Terminator; @ @ SyntaxSym ::= '[' Name_t ']' | '{' Name_t '}' | Name_t | StringLiteral_t ; @ -} syntaxRule :: SyntaxInfo -> IdrisParser Syntax syntaxRule syn = do sty <- try (do pushIndent sty <- option AnySyntax (do reserved "term"; return TermSyntax <|> do reserved "pattern"; return PatternSyntax) reserved "syntax" return sty) syms <- some syntaxSym when (all isExpr syms) $ unexpected "missing keywords in syntax rule" let ns = mapMaybe getName syms when (length ns /= length (nub ns)) $ unexpected "repeated variable in syntax rule" lchar '=' tm <- typeExpr (allowImp syn) >>= uniquifyBinders [n | Binding n <- syms] terminator return (Rule (mkSimple syms) tm sty) where isExpr (Expr _) = True isExpr _ = False getName (Expr n) = Just n getName _ = Nothing -- Can't parse two full expressions (i.e. expressions with application) in a row -- so change them both to a simple expression mkSimple (Expr e : es) = SimpleExpr e : mkSimple' es mkSimple xs = mkSimple' xs mkSimple' (Expr e : Expr e1 : es) = SimpleExpr e : SimpleExpr e1 : mkSimple es -- Can't parse a full expression followed by operator like characters due to ambiguity mkSimple' (Expr e : Symbol s : es) | takeWhile (`elem` opChars) ts /= "" && ts `notElem` invalidOperators = SimpleExpr e : Symbol s : mkSimple' es where ts = dropWhile isSpace . dropWhileEnd isSpace $ s mkSimple' (e : es) = e : mkSimple' es mkSimple' [] = [] -- Prevent syntax variable capture by making all binders under syntax unique -- (the ol' Common Lisp GENSYM approach) uniquifyBinders :: [Name] -> PTerm -> IdrisParser PTerm uniquifyBinders userNames = fixBind [] where fixBind :: [(Name, Name)] -> PTerm -> IdrisParser PTerm fixBind rens (PRef fc n) | Just n' <- lookup n rens = return $ PRef fc n' fixBind rens (PPatvar fc n) | Just n' <- lookup n rens = return $ PPatvar fc n' fixBind rens (PLam fc n nfc ty body) | n `elem` userNames = liftM2 (PLam fc n nfc) (fixBind rens ty) (fixBind rens body) | otherwise = do ty' <- fixBind rens ty n' <- gensym n body' <- fixBind ((n,n'):rens) body return $ PLam fc n' nfc ty' body' fixBind rens (PPi plic n nfc argTy body) | n `elem` userNames = liftM2 (PPi plic n nfc) (fixBind rens argTy) (fixBind rens body) | otherwise = do ty' <- fixBind rens argTy n' <- gensym n body' <- fixBind ((n,n'):rens) body return $ (PPi plic n' nfc ty' body') fixBind rens (PLet fc n nfc ty val body) | n `elem` userNames = liftM3 (PLet fc n nfc) (fixBind rens ty) (fixBind rens val) (fixBind rens body) | otherwise = do ty' <- fixBind rens ty val' <- fixBind rens val n' <- gensym n body' <- fixBind ((n,n'):rens) body return $ PLet fc n' nfc ty' val' body' fixBind rens (PMatchApp fc n) | Just n' <- lookup n rens = return $ PMatchApp fc n' fixBind rens x = descendM (fixBind rens) x gensym :: Name -> IdrisParser Name gensym n = do ist <- get let idx = idris_name ist put ist { idris_name = idx + 1 } return $ sMN idx (show n) {- | Parses a syntax symbol (either binding variable, keyword or expression) @ SyntaxSym ::= '[' Name_t ']' | '{' Name_t '}' | Name_t | StringLiteral_t ; @ -} syntaxSym :: IdrisParser SSymbol syntaxSym = try (do lchar '['; n <- fst <$> name; lchar ']' return (Expr n)) <|> try (do lchar '{'; n <- fst <$> name; lchar '}' return (Binding n)) <|> do n <- fst <$> iName [] return (Keyword n) <|> do sym <- fmap fst stringLiteral return (Symbol sym) <?> "syntax symbol" {- | Parses a function declaration with possible syntax sugar @ FunDecl ::= FunDecl'; @ -} fnDecl :: SyntaxInfo -> IdrisParser [PDecl] fnDecl syn = try (do notEndBlock d <- fnDecl' syn i <- get let d' = fmap (desugar syn i) d return [d']) <?> "function declaration" {-| Parses a function declaration @ FunDecl' ::= DocComment_t? FnOpts* Accessibility? FnOpts* FnName TypeSig Terminator | Postulate | Pattern | CAF ; @ -} fnDecl' :: SyntaxInfo -> IdrisParser PDecl fnDecl' syn = checkFixity $ do (doc, argDocs, fc, opts', n, nfc, acc) <- try (do pushIndent (doc, argDocs) <- docstring syn ist <- get let initOpts = if default_total ist then [TotalFn] else [] opts <- fnOpts initOpts acc <- optional accessibility opts' <- fnOpts opts (n_in, nfc) <- fnName let n = expandNS syn n_in fc <- getFC lchar ':' return (doc, argDocs, fc, opts', n, nfc, acc)) ty <- typeExpr (allowImp syn) terminator addAcc n acc return (PTy doc argDocs syn fc opts' n nfc ty) <|> postulate syn <|> caf syn <|> pattern syn <?> "function declaration" where checkFixity :: IdrisParser PDecl -> IdrisParser PDecl checkFixity p = do decl <- p case getName decl of Nothing -> return decl Just n -> do fOk <- fixityOK n unless fOk . fail $ "Missing fixity declaration for " ++ show n return decl getName (PTy _ _ _ _ _ n _ _) = Just n getName _ = Nothing fixityOK (NS n _) = fixityOK n fixityOK (UN n) | all (flip elem opChars) (str n) = do fixities <- fmap idris_infixes get return . elem (str n) . map (\ (Fix _ op) -> op) $ fixities | otherwise = return True fixityOK _ = return True {-| Parses function options given initial options @ FnOpts ::= 'total' | 'partial' | 'covering' | 'implicit' | '%' 'no_implicit' | '%' 'assert_total' | '%' 'error_handler' | '%' 'reflection' | '%' 'specialise' '[' NameTimesList? ']' ; @ @ NameTimes ::= FnName Natural?; @ @ NameTimesList ::= NameTimes | NameTimes ',' NameTimesList ; @ -} -- FIXME: Check compatability for function options (i.e. partal/total) -- -- Issue #1574 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1574 fnOpts :: [FnOpt] -> IdrisParser [FnOpt] fnOpts opts = do reserved "total"; fnOpts (TotalFn : opts) <|> do reserved "partial"; fnOpts (PartialFn : (opts \\ [TotalFn])) <|> do reserved "covering"; fnOpts (CoveringFn : (opts \\ [TotalFn])) <|> do try (lchar '%' *> reserved "export"); c <- fmap fst stringLiteral; fnOpts (CExport c : opts) <|> do try (lchar '%' *> reserved "no_implicit"); fnOpts (NoImplicit : opts) <|> do try (lchar '%' *> reserved "inline"); fnOpts (Inlinable : opts) <|> do try (lchar '%' *> reserved "assert_total"); fnOpts (AssertTotal : opts) <|> do try (lchar '%' *> reserved "error_handler"); fnOpts (ErrorHandler : opts) <|> do try (lchar '%' *> reserved "error_reverse"); fnOpts (ErrorReverse : opts) <|> do try (lchar '%' *> reserved "reflection"); fnOpts (Reflection : opts) <|> do try (lchar '%' *> reserved "hint"); fnOpts (AutoHint : opts) <|> do lchar '%'; reserved "specialise"; lchar '['; ns <- sepBy nameTimes (lchar ','); lchar ']' fnOpts (Specialise ns : opts) <|> do reserved "implicit"; fnOpts (Implicit : opts) <|> return opts <?> "function modifier" where nameTimes :: IdrisParser (Name, Maybe Int) nameTimes = do n <- fst <$> fnName t <- option Nothing (do reds <- fmap fst natural return (Just (fromInteger reds))) return (n, t) {- | Parses a postulate @ Postulate ::= DocComment_t? 'postulate' FnOpts* Accesibility? FnOpts* FnName TypeSig Terminator ; @ -} postulate :: SyntaxInfo -> IdrisParser PDecl postulate syn = do (doc, ext) <- try $ do (doc, _) <- docstring syn pushIndent ext <- ppostDecl return (doc, ext) ist <- get let initOpts = if default_total ist then [TotalFn] else [] opts <- fnOpts initOpts acc <- optional accessibility opts' <- fnOpts opts n_in <- fst <$> fnName let n = expandNS syn n_in lchar ':' ty <- typeExpr (allowImp syn) fc <- getFC terminator addAcc n acc return (PPostulate ext doc syn fc opts' n ty) <?> "postulate" where ppostDecl = do reserved "postulate"; return False <|> do lchar '%'; reserved "extern"; return True {- | Parses a using declaration @ Using ::= 'using' '(' UsingDeclList ')' OpenBlock Decl* CloseBlock ; @ -} using_ :: SyntaxInfo -> IdrisParser [PDecl] using_ syn = do reserved "using"; lchar '('; ns <- usingDeclList syn; lchar ')' openBlock let uvars = using syn ds <- many (decl (syn { using = uvars ++ ns })) closeBlock return (concat ds) <?> "using declaration" {- | Parses a parameters declaration @ Params ::= 'parameters' '(' TypeDeclList ')' OpenBlock Decl* CloseBlock ; @ -} params :: SyntaxInfo -> IdrisParser [PDecl] params syn = do reserved "parameters"; lchar '('; ns <- typeDeclList syn; lchar ')' let ns' = [(n, ty) | (n, _, ty) <- ns] openBlock let pvars = syn_params syn ds <- many (decl syn { syn_params = pvars ++ ns' }) closeBlock fc <- getFC return [PParams fc ns' (concat ds)] <?> "parameters declaration" {- | Parses a mutual declaration (for mutually recursive functions) @ Mutual ::= 'mutual' OpenBlock Decl* CloseBlock ; @ -} mutual :: SyntaxInfo -> IdrisParser [PDecl] mutual syn = do reserved "mutual" openBlock let pvars = syn_params syn ds <- many (decl (syn { mut_nesting = mut_nesting syn + 1 } )) closeBlock fc <- getFC return [PMutual fc (concat ds)] <?> "mutual block" {-| Parses a namespace declaration @ Namespace ::= 'namespace' identifier OpenBlock Decl+ CloseBlock ; @ -} namespace :: SyntaxInfo -> IdrisParser [PDecl] namespace syn = do reserved "namespace" (n, nfc) <- identifier openBlock ds <- some (decl syn { syn_namespace = n : syn_namespace syn }) closeBlock return [PNamespace n nfc (concat ds)] <?> "namespace declaration" {- | Parses a methods block (for instances) @ InstanceBlock ::= 'where' OpenBlock FnDecl* CloseBlock @ -} instanceBlock :: SyntaxInfo -> IdrisParser [PDecl] instanceBlock syn = do reserved "where" openBlock ds <- many (fnDecl syn) closeBlock return (concat ds) <?> "instance block" {- | Parses a methods and instances block (for type classes) @ MethodOrInstance ::= FnDecl | Instance ; @ @ ClassBlock ::= 'where' OpenBlock Constructor? MethodOrInstance* CloseBlock ; @ -} classBlock :: SyntaxInfo -> IdrisParser (Maybe (Name, FC), Docstring (Either Err PTerm), [PDecl]) classBlock syn = do reserved "where" openBlock (cn, cd) <- option (Nothing, emptyDocstring) $ try (do (doc, _) <- option noDocs docComment n <- constructor return (Just n, doc)) ist <- get let cd' = annotate syn ist cd ds <- many (notEndBlock >> instance_ syn <|> fnDecl syn) closeBlock return (cn, cd', concat ds) <?> "class block" where constructor :: IdrisParser (Name, FC) constructor = reserved "constructor" *> fnName annotate :: SyntaxInfo -> IState -> Docstring () -> Docstring (Either Err PTerm) annotate syn ist = annotCode $ tryFullExpr syn ist {-| Parses a type class declaration @ ClassArgument ::= Name | '(' Name ':' Expr ')' ; @ @ Class ::= DocComment_t? Accessibility? 'class' ConstraintList? Name ClassArgument* ClassBlock? ; @ -} class_ :: SyntaxInfo -> IdrisParser [PDecl] class_ syn = do (doc, argDocs, acc) <- try (do (doc, argDocs) <- docstring syn acc <- optional accessibility reserved "class" return (doc, argDocs, acc)) fc <- getFC cons <- constraintList syn let cons' = [(c, ty) | (c, _, ty) <- cons] (n_in, nfc) <- fnName let n = expandNS syn n_in cs <- many carg fds <- option [(cn, NoFC) | (cn, _, _) <- cs] fundeps (cn, cd, ds) <- option (Nothing, fst noDocs, []) (classBlock syn) accData acc n (concatMap declared ds) return [PClass doc syn fc cons' n nfc cs argDocs fds ds cn cd] <?> "type-class declaration" where fundeps :: IdrisParser [(Name, FC)] fundeps = do lchar '|'; sepBy name (lchar ',') carg :: IdrisParser (Name, FC, PTerm) carg = do lchar '('; (i, ifc) <- name; lchar ':'; ty <- expr syn; lchar ')' return (i, ifc, ty) <|> do (i, ifc) <- name fc <- getFC return (i, ifc, PType fc) {- | Parses a type class instance declaration @ Instance ::= DocComment_t? 'instance' InstanceName? ConstraintList? Name SimpleExpr* InstanceBlock? ; @ @ InstanceName ::= '[' Name ']'; @ -} instance_ :: SyntaxInfo -> IdrisParser [PDecl] instance_ syn = do (doc, argDocs) <- try (docstring syn <* reserved "instance") fc <- getFC en <- optional instanceName cs <- constraintList syn let cs' = [(c, ty) | (c, _, ty) <- cs] (cn, cnfc) <- fnName args <- many (simpleExpr syn) let sc = PApp fc (PRef cnfc cn) (map pexp args) let t = bindList (PPi constraint) cs sc ds <- option [] (instanceBlock syn) return [PInstance doc argDocs syn fc cs' cn cnfc args t en ds] <?> "instance declaration" where instanceName :: IdrisParser Name instanceName = do lchar '['; n_in <- fst <$> fnName; lchar ']' let n = expandNS syn n_in return n <?> "instance name" -- | Parse a docstring docstring :: SyntaxInfo -> IdrisParser (Docstring (Either Err PTerm), [(Name,Docstring (Either Err PTerm))]) docstring syn = do (doc, argDocs) <- option noDocs docComment ist <- get let doc' = annotCode (tryFullExpr syn ist) doc argDocs' = [ (n, annotCode (tryFullExpr syn ist) d) | (n, d) <- argDocs ] return (doc', argDocs') {- | Parses a using declaration list @ UsingDeclList ::= UsingDeclList' | NameList TypeSig ; @ @ UsingDeclList' ::= UsingDecl | UsingDecl ',' UsingDeclList' ; @ @ NameList ::= Name | Name ',' NameList ; @ -} usingDeclList :: SyntaxInfo -> IdrisParser [Using] usingDeclList syn = try (sepBy1 (usingDecl syn) (lchar ',')) <|> do ns <- sepBy1 (fst <$> name) (lchar ',') lchar ':' t <- typeExpr (disallowImp syn) return (map (\x -> UImplicit x t) ns) <?> "using declaration list" {- |Parses a using declaration @ UsingDecl ::= FnName TypeSig | FnName FnName+ ; @ -} usingDecl :: SyntaxInfo -> IdrisParser Using usingDecl syn = try (do x <- fst <$> fnName lchar ':' t <- typeExpr (disallowImp syn) return (UImplicit x t)) <|> do c <- fst <$> fnName xs <- some (fst <$> fnName) return (UConstraint c xs) <?> "using declaration" {- | Parse a clause with patterns @ Pattern ::= Clause; @ -} pattern :: SyntaxInfo -> IdrisParser PDecl pattern syn = do fc <- getFC clause <- clause syn return (PClauses fc [] (sMN 2 "_") [clause]) -- collect together later <?> "pattern" {- | Parse a constant applicative form declaration @ CAF ::= 'let' FnName '=' Expr Terminator; @ -} caf :: SyntaxInfo -> IdrisParser PDecl caf syn = do reserved "let" n_in <- fst <$> fnName; let n = expandNS syn n_in lchar '=' t <- expr syn terminator fc <- getFC return (PCAF fc n t) <?> "constant applicative form declaration" {- | Parse an argument expression @ ArgExpr ::= HSimpleExpr | {- In Pattern External (User-defined) Expression -}; @ -} argExpr :: SyntaxInfo -> IdrisParser PTerm argExpr syn = let syn' = syn { inPattern = True } in try (hsimpleExpr syn') <|> simpleExternalExpr syn' <?> "argument expression" {- | Parse a right hand side of a function @ RHS ::= '=' Expr | '?=' RHSName? Expr | Impossible ; @ @ RHSName ::= '{' FnName '}'; @ -} rhs :: SyntaxInfo -> Name -> IdrisParser PTerm rhs syn n = do lchar '='; expr syn <|> do symbol "?="; fc <- getFC name <- option n' (do symbol "{"; n <- fst <$> fnName; symbol "}"; return n) r <- expr syn return (addLet fc name r) <|> impossible <?> "function right hand side" where mkN :: Name -> Name mkN (UN x) = if (tnull x || not (isAlpha (thead x))) then sUN "infix_op_lemma_1" else sUN (str x++"_lemma_1") mkN (NS x n) = NS (mkN x) n n' :: Name n' = mkN n addLet :: FC -> Name -> PTerm -> PTerm addLet fc nm (PLet fc' n nfc ty val r) = PLet fc' n nfc ty val (addLet fc nm r) addLet fc nm (PCase fc' t cs) = PCase fc' t (map addLetC cs) where addLetC (l, r) = (l, addLet fc nm r) addLet fc nm r = (PLet fc (sUN "value") NoFC Placeholder r (PMetavar NoFC nm)) {- |Parses a function clause @ RHSOrWithBlock ::= RHS WhereOrTerminator | 'with' SimpleExpr OpenBlock FnDecl+ CloseBlock ; @ @ Clause ::= WExpr+ RHSOrWithBlock | SimpleExpr '<==' FnName RHS WhereOrTerminator | ArgExpr Operator ArgExpr WExpr* RHSOrWithBlock {- Except "=" and "?=" operators to avoid ambiguity -} | FnName ConstraintArg* ImplicitOrArgExpr* WExpr* RHSOrWithBlock ; @ @ ImplicitOrArgExpr ::= ImplicitArg | ArgExpr; @ @ WhereOrTerminator ::= WhereBlock | Terminator; @ -} clause :: SyntaxInfo -> IdrisParser PClause clause syn = do wargs <- try (do pushIndent; some (wExpr syn)) fc <- getFC ist <- get n <- case lastParse ist of Just t -> return t Nothing -> fail "Invalid clause" (do r <- rhs syn n let ctxt = tt_ctxt ist let wsyn = syn { syn_namespace = [] } (wheres, nmap) <- choice [do x <- whereBlock n wsyn popIndent return x, do terminator return ([], [])] return $ PClauseR fc wargs r wheres) <|> (do popIndent reserved "with" wval <- simpleExpr syn pn <- optProof openBlock ds <- some $ fnDecl syn let withs = concat ds closeBlock return $ PWithR fc wargs wval pn withs) <|> do ty <- try (do pushIndent ty <- simpleExpr syn symbol "<==" return ty) fc <- getFC n_in <- fst <$> fnName; let n = expandNS syn n_in r <- rhs syn n ist <- get let ctxt = tt_ctxt ist let wsyn = syn { syn_namespace = [] } (wheres, nmap) <- choice [do x <- whereBlock n wsyn popIndent return x, do terminator return ([], [])] let capp = PLet fc (sMN 0 "match") NoFC ty (PMatchApp fc n) (PRef fc (sMN 0 "match")) ist <- get put (ist { lastParse = Just n }) return $ PClause fc n capp [] r wheres <|> do (l, op, nfc) <- try (do pushIndent l <- argExpr syn (op, nfc) <- operatorFC when (op == "=" || op == "?=" ) $ fail "infix clause definition with \"=\" and \"?=\" not supported " return (l, op, nfc)) let n = expandNS syn (sUN op) r <- argExpr syn fc <- getFC wargs <- many (wExpr syn) (do rs <- rhs syn n let wsyn = syn { syn_namespace = [] } (wheres, nmap) <- choice [do x <- whereBlock n wsyn popIndent return x, do terminator return ([], [])] ist <- get let capp = PApp fc (PRef nfc n) [pexp l, pexp r] put (ist { lastParse = Just n }) return $ PClause fc n capp wargs rs wheres) <|> (do popIndent reserved "with" wval <- bracketed syn pn <- optProof openBlock ds <- some $ fnDecl syn closeBlock ist <- get let capp = PApp fc (PRef fc n) [pexp l, pexp r] let withs = map (fillLHSD n capp wargs) $ concat ds put (ist { lastParse = Just n }) return $ PWith fc n capp wargs wval pn withs) <|> do pushIndent (n_in, nfc) <- fnName; let n = expandNS syn n_in cargs <- many (constraintArg syn) fc <- getFC args <- many (try (implicitArg (syn { inPattern = True } )) <|> (fmap pexp (argExpr syn))) wargs <- many (wExpr syn) let capp = PApp fc (PRef nfc n) (cargs ++ args) (do r <- rhs syn n ist <- get let ctxt = tt_ctxt ist let wsyn = syn { syn_namespace = [] } (wheres, nmap) <- choice [do x <- whereBlock n wsyn popIndent return x, do terminator return ([], [])] ist <- get put (ist { lastParse = Just n }) return $ PClause fc n capp wargs r wheres) <|> (do reserved "with" ist <- get put (ist { lastParse = Just n }) wval <- bracketed syn pn <- optProof openBlock ds <- some $ fnDecl syn let withs = map (fillLHSD n capp wargs) $ concat ds closeBlock popIndent return $ PWith fc n capp wargs wval pn withs) <?> "function clause" where optProof = option Nothing (do reserved "proof" n <- fnName return (Just n)) fillLHS :: Name -> PTerm -> [PTerm] -> PClause -> PClause fillLHS n capp owargs (PClauseR fc wargs v ws) = PClause fc n capp (owargs ++ wargs) v ws fillLHS n capp owargs (PWithR fc wargs v pn ws) = PWith fc n capp (owargs ++ wargs) v pn (map (fillLHSD n capp (owargs ++ wargs)) ws) fillLHS _ _ _ c = c fillLHSD :: Name -> PTerm -> [PTerm] -> PDecl -> PDecl fillLHSD n c a (PClauses fc o fn cs) = PClauses fc o fn (map (fillLHS n c a) cs) fillLHSD n c a x = x {-| Parses with pattern @ WExpr ::= '|' Expr'; @ -} wExpr :: SyntaxInfo -> IdrisParser PTerm wExpr syn = do lchar '|' expr' (syn { inPattern = True }) <?> "with pattern" {- | Parses a where block @ WhereBlock ::= 'where' OpenBlock Decl+ CloseBlock; @ -} whereBlock :: Name -> SyntaxInfo -> IdrisParser ([PDecl], [(Name, Name)]) whereBlock n syn = do reserved "where" ds <- indentedBlock1 (decl syn) let dns = concatMap (concatMap declared) ds return (concat ds, map (\x -> (x, decoration syn x)) dns) <?> "where block" {- |Parses a code generation target language name @ Codegen ::= 'C' | 'Java' | 'JavaScript' | 'Node' | 'LLVM' | 'Bytecode' ; @ -} codegen_ :: IdrisParser Codegen codegen_ = do n <- fst <$> identifier return (Via (map toLower n)) <|> do reserved "Bytecode"; return Bytecode <?> "code generation language" {- |Parses a compiler directive @ StringList ::= String | String ',' StringList ; @ @ Directive ::= '%' Directive'; @ @ Directive' ::= 'lib' CodeGen String_t | 'link' CodeGen String_t | 'flag' CodeGen String_t | 'include' CodeGen String_t | 'hide' Name | 'freeze' Name | 'access' Accessibility | 'default' Totality | 'logging' Natural | 'dynamic' StringList | 'name' Name NameList | 'error_handlers' Name NameList | 'language' 'TypeProviders' | 'language' 'ErrorReflection' ; @ -} directive :: SyntaxInfo -> IdrisParser [PDecl] directive syn = do try (lchar '%' *> reserved "lib") cgn <- codegen_ lib <- fmap fst stringLiteral return [PDirective (DLib cgn lib)] <|> do try (lchar '%' *> reserved "link") cgn <- codegen_; obj <- fst <$> stringLiteral return [PDirective (DLink cgn obj)] <|> do try (lchar '%' *> reserved "flag") cgn <- codegen_; flag <- fst <$> stringLiteral return [PDirective (DFlag cgn flag)] <|> do try (lchar '%' *> reserved "include") cgn <- codegen_ hdr <- fst <$> stringLiteral return [PDirective (DInclude cgn hdr)] <|> do try (lchar '%' *> reserved "hide"); n <- fst <$> fnName return [PDirective (DHide n)] <|> do try (lchar '%' *> reserved "freeze"); n <- fst <$> iName [] return [PDirective (DFreeze n)] <|> do try (lchar '%' *> reserved "access"); acc <- accessibility return [PDirective (DAccess acc)] <|> do try (lchar '%' *> reserved "default"); tot <- totality i <- get put (i { default_total = tot } ) return [PDirective (DDefault tot)] <|> do try (lchar '%' *> reserved "logging") i <- fst <$> natural return [PDirective (DLogging i)] <|> do try (lchar '%' *> reserved "dynamic") libs <- sepBy1 (fmap fst stringLiteral) (lchar ',') return [PDirective (DDynamicLibs libs)] <|> do try (lchar '%' *> reserved "name") ty <- fst <$> fnName ns <- sepBy1 (fst <$> name) (lchar ',') return [PDirective (DNameHint ty ns)] <|> do try (lchar '%' *> reserved "error_handlers") fn <- fst <$> fnName arg <- fst <$> fnName ns <- sepBy1 (fst <$> name) (lchar ',') return [PDirective (DErrorHandlers fn arg ns) ] <|> do try (lchar '%' *> reserved "language"); ext <- pLangExt; return [PDirective (DLanguage ext)] <|> do fc <- getFC try (lchar '%' *> reserved "used") fn <- fst <$> fnName arg <- fst <$> iName [] return [PDirective (DUsed fc fn arg)] <?> "directive" pLangExt :: IdrisParser LanguageExt pLangExt = (reserved "TypeProviders" >> return TypeProviders) <|> (reserved "ErrorReflection" >> return ErrorReflection) {- | Parses a totality @ Totality ::= 'partial' | 'total' @ -} totality :: IdrisParser Bool totality = do reserved "total"; return True <|> do reserved "partial"; return False {- | Parses a type provider @ Provider ::= DocComment_t? '%' 'provide' Provider_What? '(' FnName TypeSig ')' 'with' Expr; ProviderWhat ::= 'proof' | 'term' | 'type' | 'postulate' @ -} provider :: SyntaxInfo -> IdrisParser [PDecl] provider syn = do doc <- try (do (doc, _) <- docstring syn lchar '%' reserved "provide" return doc) provideTerm doc <|> providePostulate doc <?> "type provider" where provideTerm doc = do lchar '('; n <- fst <$> fnName; lchar ':'; t <- typeExpr syn; lchar ')' fc <- getFC reserved "with" e <- expr syn <?> "provider expression" return [PProvider doc syn fc (ProvTerm t e) n] providePostulate doc = do reserved "postulate" n <- fst <$> fnName fc <- getFC reserved "with" e <- expr syn <?> "provider expression" return [PProvider doc syn fc (ProvPostulate e) n] {- | Parses a transform @ Transform ::= '%' 'transform' Expr '==>' Expr @ -} transform :: SyntaxInfo -> IdrisParser [PDecl] transform syn = do try (lchar '%' *> reserved "transform") -- leave it unchecked, until we work out what this should -- actually mean... -- safety <- option True (do reserved "unsafe" -- return False) l <- expr syn fc <- getFC symbol "==>" r <- expr syn return [PTransform fc False l r] <?> "transform" {- * Loading and parsing -} {- | Parses an expression from input -} parseExpr :: IState -> String -> Result PTerm parseExpr st = runparser (fullExpr defaultSyntax) st "(input)" {- | Parses a constant form input -} parseConst :: IState -> String -> Result Const parseConst st = runparser (fmap fst constant) st "(input)" {- | Parses a tactic from input -} parseTactic :: IState -> String -> Result PTactic parseTactic st = runparser (fullTactic defaultSyntax) st "(input)" -- | Parse module header and imports parseImports :: FilePath -> String -> Idris (Maybe (Docstring ()), [String], [ImportInfo], Maybe Delta) parseImports fname input = do i <- getIState case parseString (runInnerParser (evalStateT imports i)) (Directed (UTF8.fromString fname) 0 0 0 0) input of Failure err -> fail (show err) Success (x, annots, i) -> do putIState i fname' <- runIO $ Dir.makeAbsolute fname sendHighlighting $ addPath annots fname' return x where imports :: IdrisParser ((Maybe (Docstring ()), [String], [ImportInfo], Maybe Delta), [(FC, OutputAnnotation)], IState) imports = do whiteSpace (mdoc, mname, annots) <- moduleHeader ps <- many import_ mrk <- mark isEof <- lookAheadMatches eof let mrk' = if isEof then Nothing else Just mrk i <- get return ((mdoc, mname, ps, mrk'), annots, i) addPath :: [(FC, OutputAnnotation)] -> FilePath -> [(FC, OutputAnnotation)] addPath [] _ = [] addPath ((fc, AnnNamespace ns Nothing) : annots) path = (fc, AnnNamespace ns (Just path)) : addPath annots path addPath (annot:annots) path = annot : addPath annots path -- | There should be a better way of doing this... findFC :: Doc -> (FC, String) findFC x = let s = show (plain x) in case span (/= ':') s of (failname, ':':rest) -> case span isDigit rest of (line, ':':rest') -> case span isDigit rest' of (col, ':':msg) -> let pos = (read line, read col) in (FC failname pos pos, msg) -- | Check if the coloring matches the options and corrects if necessary fixColour :: Bool -> ANSI.Doc -> ANSI.Doc fixColour False doc = ANSI.plain doc fixColour True doc = doc -- | A program is a list of declarations, possibly with associated -- documentation strings. parseProg :: SyntaxInfo -> FilePath -> String -> Maybe Delta -> Idris [PDecl] parseProg syn fname input mrk = do i <- getIState case runparser mainProg i fname input of Failure doc -> do -- FIXME: Get error location from trifecta -- this can't be the solution! -- Issue #1575 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1575 let (fc, msg) = findFC doc i <- getIState case idris_outputmode i of RawOutput h -> iputStrLn (show $ fixColour (idris_colourRepl i) doc) IdeMode n h -> iWarn fc (P.text msg) putIState (i { errSpan = Just fc }) return [] Success (x, i) -> do putIState i reportParserWarnings return $ collect x where mainProg :: IdrisParser ([PDecl], IState) mainProg = case mrk of Nothing -> do i <- get; return ([], i) Just mrk -> do release mrk ds <- prog syn i' <- get return (ds, i') {- | Load idris module and show error if something wrong happens -} loadModule :: FilePath -> Idris (Maybe String) loadModule f = idrisCatch (loadModule' f) (\e -> do setErrSpan (getErrSpan e) ist <- getIState iWarn (getErrSpan e) $ pprintErr ist e return Nothing) {- | Load idris module -} loadModule' :: FilePath -> Idris (Maybe String) loadModule' f = do i <- getIState let file = takeWhile (/= ' ') f ibcsd <- valIBCSubDir i ids <- allImportDirs fp <- findImport ids ibcsd file if file `elem` imported i then do iLOG $ "Already read " ++ file return Nothing else do putIState (i { imported = file : imported i }) case fp of IDR fn -> loadSource False fn Nothing LIDR fn -> loadSource True fn Nothing IBC fn src -> idrisCatch (loadIBC True fn) (\c -> do iLOG $ fn ++ " failed " ++ pshow i c case src of IDR sfn -> loadSource False sfn Nothing LIDR sfn -> loadSource True sfn Nothing) return $ Just file {- | Load idris code from file -} loadFromIFile :: Bool -> IFileType -> Maybe Int -> Idris () loadFromIFile reexp i@(IBC fn src) maxline = do iLOG $ "Skipping " ++ getSrcFile i idrisCatch (loadIBC reexp fn) (\err -> ierror $ LoadingFailed fn err) where getSrcFile (IDR fn) = fn getSrcFile (LIDR fn) = fn getSrcFile (IBC f src) = getSrcFile src loadFromIFile _ (IDR fn) maxline = loadSource' False fn maxline loadFromIFile _ (LIDR fn) maxline = loadSource' True fn maxline {-| Load idris source code and show error if something wrong happens -} loadSource' :: Bool -> FilePath -> Maybe Int -> Idris () loadSource' lidr r maxline = idrisCatch (loadSource lidr r maxline) (\e -> do setErrSpan (getErrSpan e) ist <- getIState case e of At f e' -> iWarn f (pprintErr ist e') _ -> iWarn (getErrSpan e) (pprintErr ist e)) {- | Load Idris source code-} loadSource :: Bool -> FilePath -> Maybe Int -> Idris () loadSource lidr f toline = do iLOG ("Reading " ++ f) i <- getIState let def_total = default_total i file_in <- runIO $ readSource f file <- if lidr then tclift $ unlit f file_in else return file_in (mdocs, mname, imports_in, pos) <- parseImports f file ai <- getAutoImports let imports = map (\n -> ImportInfo True n Nothing [] NoFC NoFC) ai ++ imports_in ids <- allImportDirs ibcsd <- valIBCSubDir i mapM_ (\(re, f, ns, nfc) -> do fp <- findImport ids ibcsd f case fp of LIDR fn -> ifail $ "No ibc for " ++ f IDR fn -> ifail $ "No ibc for " ++ f IBC fn src -> do loadIBC True fn let srcFn = case src of IDR fn -> Just fn LIDR fn -> Just fn _ -> Nothing srcFnAbs <- case srcFn of Just fn -> fmap Just (runIO $ Dir.makeAbsolute fn) Nothing -> return Nothing sendHighlighting [(nfc, AnnNamespace ns srcFnAbs)]) [(re, fn, ns, nfc) | ImportInfo re fn _ ns _ nfc <- imports] reportParserWarnings -- process and check module aliases let modAliases = M.fromList [ (prep alias, prep realName) | ImportInfo { import_reexport = reexport , import_path = realName , import_rename = Just (alias, _) , import_location = fc } <- imports ] prep = map T.pack . reverse . Spl.splitOn [pathSeparator] aliasNames = [ (alias, fc) | ImportInfo { import_rename = Just (alias, _) , import_location = fc } <- imports ] histogram = groupBy ((==) `on` fst) . sortBy (comparing fst) $ aliasNames case map head . filter ((/= 1) . length) $ histogram of [] -> logLvl 3 $ "Module aliases: " ++ show (M.toList modAliases) (n,fc):_ -> throwError . At fc . Msg $ "import alias not unique: " ++ show n i <- getIState putIState (i { default_access = Hidden, module_aliases = modAliases }) clearIBC -- start a new .ibc file -- record package info in .ibc imps <- allImportDirs mapM_ addIBC (map IBCImportDir imps) mapM_ (addIBC . IBCImport) [ (reexport, realName) | ImportInfo { import_reexport = reexport , import_path = realName } <- imports ] let syntax = defaultSyntax{ syn_namespace = reverse mname, maxline = toline } ist <- getIState -- Save the span from parsing the module header, because -- an empty program parse might obliterate it. let oldSpan = idris_parsedSpan ist ds' <- parseProg syntax f file pos case (ds', oldSpan) of ([], Just fc) -> -- If no program elements were parsed, we dind't -- get a loaded region in the IBC file. That -- means we need to add it back. do ist <- getIState putIState ist { idris_parsedSpan = oldSpan , ibc_write = IBCParsedRegion fc : ibc_write ist } _ -> return () -- Parsing done, now process declarations let ds = namespaces mname ds' logLvl 3 (show $ showDecls verbosePPOption ds) i <- getIState logLvl 10 (show (toAlist (idris_implicits i))) logLvl 3 (show (idris_infixes i)) -- Now add all the declarations to the context v <- verbose when v $ iputStrLn $ "Type checking " ++ f -- we totality check after every Mutual block, so if -- anything is a single definition, wrap it in a -- mutual block on its own elabDecls toplevel (map toMutual ds) i <- getIState -- simplify every definition do give the totality checker -- a better chance mapM_ (\n -> do logLvl 5 $ "Simplifying " ++ show n updateContext (simplifyCasedef n $ getErasureInfo i)) (map snd (idris_totcheck i)) -- build size change graph from simplified definitions iLOG "Totality checking" i <- getIState mapM_ buildSCG (idris_totcheck i) mapM_ checkDeclTotality (idris_totcheck i) -- Redo totality check for deferred names let deftots = idris_defertotcheck i iLOG $ "Totality checking " ++ show deftots mapM_ (\x -> do tot <- getTotality x case tot of Total _ -> setTotality x Unchecked _ -> return ()) (map snd deftots) mapM_ buildSCG deftots mapM_ checkDeclTotality deftots iLOG ("Finished " ++ f) ibcsd <- valIBCSubDir i iLOG "Universe checking" iucheck let ibc = ibcPathNoFallback ibcsd f i <- getIState addHides (hide_list i) -- Save module documentation if applicable i <- getIState case mdocs of Nothing -> return () Just docs -> addModDoc syntax mname docs -- Finally, write an ibc if checking was successful ok <- noErrors when ok $ idrisCatch (do writeIBC f ibc; clearIBC) (\c -> return ()) -- failure is harmless i <- getIState putIState (i { default_total = def_total, hide_list = [] }) return () where namespaces :: [String] -> [PDecl] -> [PDecl] namespaces [] ds = ds namespaces (x:xs) ds = [PNamespace x NoFC (namespaces xs ds)] toMutual :: PDecl -> PDecl toMutual m@(PMutual _ d) = m toMutual (PNamespace x fc ds) = PNamespace x fc (map toMutual ds) toMutual x = let r = PMutual (fileFC "single mutual") [x] in case x of PClauses{} -> r PClass{} -> r PData{} -> r PInstance{} -> r _ -> x addModDoc :: SyntaxInfo -> [String] -> Docstring () -> Idris () addModDoc syn mname docs = do ist <- getIState docs' <- elabDocTerms recinfo (parsedDocs ist) let modDocs' = addDef docName docs' (idris_moduledocs ist) putIState ist { idris_moduledocs = modDocs' } addIBC (IBCModDocs docName) where docName = NS modDocName (map T.pack (reverse mname)) parsedDocs ist = annotCode (tryFullExpr syn ist) docs {- | Adds names to hide list -} addHides :: [(Name, Maybe Accessibility)] -> Idris () addHides xs = do i <- getIState let defh = default_access i let (hs, as) = partition isNothing xs unless (null as) $ mapM_ doHide (map (\ (n, _) -> (n, defh)) hs ++ map (\ (n, Just a) -> (n, a)) as) where isNothing (_, Nothing) = True isNothing _ = False doHide (n, a) = do setAccessibility n a addIBC (IBCAccess n a)
BartAdv/Idris-dev
src/Idris/Parser.hs
bsd-3-clause
57,138
439
33
24,104
12,130
6,514
5,616
1,006
18
module TagSoupHelpers where import Data.Maybe import qualified Data.Map as M import Text.HTML.TagSoup import Text.StringLike justSections a = Just . sections a maybeFirstText :: StringLike str => [Tag str] -> Maybe String maybeFirstText tags = do let a1 = sections isTagText tags a2 <- maybeHead a1 let a3 = ((\(TagText x) -> x) . head) a2 let a4 = toString a3 return a4 maybeN :: Int -> [a] -> Maybe a maybeN n list = if length list > n then Just (list !! n) else Nothing maybeText :: Tag String -> Maybe String maybeText (TagText text) = Just text maybeText _ = Nothing maybeAttribute :: String -> Tag String -> Maybe String maybeAttribute key (TagOpen _ attrs) = M.lookup key (M.fromList attrs) maybeAttribute _ _ = Nothing maybeHead :: [a] -> Maybe a maybeHead = listToMaybe maybeLast :: [a] -> Maybe a maybeLast = listToMaybe . reverse
rickardlindberg/alldoc
src/TagSoupHelpers.hs
bsd-3-clause
900
0
16
206
351
177
174
25
2
{-# LANGUAGE Arrows #-} module Control.Arrow.ArrEff where import Prelude hiding ((.), id) import Control.Category import Control.Arrow import Control.Monad.Free type Prod eff b c = (c, ArrEff eff b c) newtype ArrEff eff b c = ArrEff (b -> eff (Prod eff b c)) instance Monad eff => Category (ArrEff eff) where id = ArrEff (\b -> return (b, id)) ArrEff g . ArrEff f = ArrEff arrFG where arrFG a = do fa <- f a feededF fa feededF (b, arr1) = do gb <- g b feededG arr1 gb feededG arr1 (c, arr2) = return (c, arr2 . arr1) instance Monad eff => Arrow (ArrEff eff) where arr f = ArrEff (\b -> return (f b, arr f)) first (ArrEff f) = ArrEff arrF where arrF (b, d) = do fb <- f b feededF fb d feededF (c, arr1) d = return ((c, d), first arr1) instance Monad eff => Functor (ArrEff eff b) where fmap f (ArrEff r) = ArrEff (\b -> do (c, next) <- r b return (f c, fmap f next)) mArr mf = ArrEff (\b -> do c <- mf b return (c, mArr mf)) mConst mf = ArrEff (\_ -> do c <- mf return (c, mConst mf)) aConst c = arr (const c) runArrEffList :: Monad m => [c] -> ArrEff m b c -> [b] -> m [c] runArrEffList accum (ArrEff f) [] = return accum runArrEffList accum (ArrEff f) (b:bs) = do (c, next) <- f b runArrEffList (c:accum) next bs runArrEff :: Monad m => ArrEff m b c -> [b] -> m [c] runArrEff = runArrEffList [] runArrEff1 :: Monad m => ArrEff m b c -> b -> m (c, ArrEff m b c) runArrEff1 (ArrEff f) b = f b timesA :: Monad m => Int -> ArrEff m b c -> ArrEff m b [c] timesA 0 _ = aConst [] timesA n ar = ArrEff (\b -> do (c, next) <- runArrEff1 ar b (cs, next') <- runArrEff1 (timesA (n-1) next) b return (c:cs, next')) forEachA :: Monad m => ArrEff m b () -> ArrEff m [b] () forEachA ar = ArrEff (\bs -> do mapM_ (runArrEff1 ar) bs return ((), aConst ())) ------ Arrow for Free language -------------------------------------------------- type ArrEffFree f b c = ArrEff (Free f) b c -- :t says: -- (Monad m1, Monad m) -- => (m (c, ArrEff m b c) -> m1 (b1, t)) -- -> ArrEff m b c -- -> b -- -> m1 b1 runFreeArr interpret ar v = do let p = runArrEff1 ar v (c, next) <- interpret p -- TODO: what to do with next? return c
graninas/Andromeda
lib/Control/Arrow/ArrEff.hs
bsd-3-clause
2,364
0
15
708
1,111
564
547
60
1
---------------------------------------------------------------------------- -- | -- Module : MainModule -- Copyright : (c) Sergey Vinokurov 2018 -- License : BSD3-style (see LICENSE) -- Maintainer : [email protected] ---------------------------------------------------------------------------- module MainModule where import DependencyMatchingConstructorsTypes import DependencyShiftedConstructorsTypes
sergv/tags-server
test-data/0011hide_constructor_named_as_type/MainModule.hs
bsd-3-clause
423
0
3
50
17
14
3
3
0
{-# LANGUAGE FlexibleContexts #-} -- | Module for UCI protocol. -- -- This module drives the engine (starts the search) in response to the GUI, -- and provides the communication between the GUI and the engine using the UCI -- v2 protocol. module Chess.UCI ( uci ) where ------------------------------------------------------------------------------ import Control.Concurrent import Control.Concurrent.STM import Control.Monad import Data.IORef import Data.List import Data.Maybe import System.Exit import System.IO import Control.Lens ((.~), (^.), (%~)) import Data.Default import Text.ParserCombinators.Parsec import Chess.Board hiding (hash) import Chess.Move import Chess.Search import qualified Chess.Search as S (aborted) import Chess.TimeControl ------------------------------------------------------------------------------ -- | The main IO () UCI loop. Talks to an UCI interface and drives the engine uci :: IO () uci = do hSetBuffering stdout NoBuffering a <- newTVarIO False p <- newTVarIO False st <- newIORef $ mkSearchState a p def forever $ do line <- getLine case parse uciCmdParser "" line of Right cmd -> do s <- readIORef st atomically $ do av <- readTVar (s^.aborted) when av retry execute cmd st Left err -> putStrLn $ "info string parse error : " ++ show err ----------------------- -- Parser data types -- ----------------------- data Command = CmdUci | CmdIsReady | CmdUciNewGame | CmdPosition Board | CmdGo Bool TimeControl | CmdStop | CmdQuit | CmdPonderHit deriving (Show) data Response = RspId String String | RspUciOk | RspReadyOk | RspBestMove Move (Maybe Move) | RspNullMove | RspInfo String | RspOption String ------------------------------------------------------------------------------ instance Show Response where show RspUciOk = "uciok" show RspReadyOk = "readyok" show (RspInfo info) = "info " ++ info show (RspId name value) = "id " ++ name ++ " " ++ value show (RspBestMove move mp) = "bestmove " ++ renderShortMove move ++ case mp of Just p -> " ponder " ++ renderShortMove p Nothing -> "" show RspNullMove = "bestmove 0000" show (RspOption text) = "option " ++ text ------------- -- parsers -- ------------- ------------------------------------------------------------------------------ uciUciParser :: Parser Command uciUciParser = string "uci" >> return CmdUci ------------------------------------------------------------------------------ uciIsReadyParser :: Parser Command uciIsReadyParser = string "isready" >> return CmdIsReady ------------------------------------------------------------------------------ uciNewGameParser :: Parser Command uciNewGameParser = try (string "ucinewgame") >> return CmdUciNewGame ------------------------------------------------------------------------------ uciStopParser :: Parser Command uciStopParser = string "stop" >> return CmdStop ------------------------------------------------------------------------------ uciQuitParser :: Parser Command uciQuitParser = string "quit" >> return CmdQuit ------------------------------------------------------------------------------ uciIntParser :: Parser Int uciIntParser = do sign <- optionMaybe $ char '-' digits <- many1 digit return $ read digits * if isJust sign then (-1) else 1 ------------------------------------------------------------------------------ -- The time control parser uciTimeControlParser :: Parser (Bool, TimeControl -> TimeControl) uciTimeControlParser = do opts <- singleOption `sepBy` spaces return $ foldr (\(a, f) (b, g) -> (a || b, f . g)) (False, id) opts where singleOption = funcIntParser "movetime" (const . TimeSpecified) <|> funcIntParser "depth" (const . DepthSpecified) <|> funcParser "infinite" (const Infinite) <|> funcIntParser "wtime" setWhiteTime <|> funcIntParser "btime" setBlackTime <|> funcIntParser "winc" setWhiteInc <|> funcIntParser "binc" setBlackInc <|> funcIntParser "movestogo" setMovesToGo <|> (string "ponder" >> return (True, id)) funcIntParser n f = do _ <- try $ string n spaces i <- uciIntParser return (False, f i) funcParser n f = string n >> return (False, f) ------------------------------------------------------------------------------ uciGoParser :: Parser Command uciGoParser = do string "go" >> spaces (ponder, f) <- uciTimeControlParser return $ CmdGo ponder $ f Infinite ------------------------------------------------------------------------------ uciPositionParser :: Parser Command uciPositionParser = do _ <- try $ string "position" >> many1 (char ' ') posType <- string "fen" <|> string "startpos" spaces (FEN pos _ _) <- if posType == "fen" then fenParser else return $ FEN initialBoard 0 0 spaces liftM CmdPosition $ option pos (string "moves" >> parserMoveList pos) where parserMoveList pos = do mm <- optionMaybe (spaces >> moveParser pos) case mm of Just m -> parserMoveList $ makeMove m pos Nothing -> return pos ------------------------------------------------------------------------------ uciPonderHitParser :: Parser Command uciPonderHitParser = string "ponderhit" >> return CmdPonderHit ------------------------------------------------------------------------------ uciCmdParser :: Parser Command uciCmdParser = uciNewGameParser <|> uciUciParser <|> uciIsReadyParser <|> uciStopParser <|> uciQuitParser <|> uciGoParser <|> uciPositionParser <|> uciPonderHitParser ------------------------------------------------------------------------------ display :: [ Response ] -> IO () display rsps = let output = intercalate "\n" $ map show rsps in putStrLn output ------------------------------------------------------------------------------ execute :: Command -> IORef SearchState -> IO () execute CmdUci _ = display [ RspId "name" "Chess" , RspId "author" "Paul Sonkoly" , RspOption "name Ponder type check default true" , RspUciOk ] execute CmdIsReady _ = display [ RspReadyOk ] execute CmdUciNewGame _ = return () execute CmdQuit _ = exitSuccess execute CmdStop st = do s <- readIORef st atomically $ writeTVar (s^.aborted) True execute (CmdPosition pos) st = modifyIORef st (board .~ pos) execute (CmdPonderHit) st = do s <- readIORef st atomically $ writeTVar (s^.pondering) False execute (CmdGo ponder tc) st = void $ forkIO $ do p <- readIORef st atomically $ writeTVar (p^.pondering) ponder (r, p') <- runSearch (search tc) p let mbMove = join $ first <$> r rsp <- case mbMove of Just m -> do let p'' = (board %~ makeMove m) p' writeIORef st p'' return [ RspBestMove m (join $ second <$> r) ] Nothing -> do writeIORef st p' return [ RspNullMove ] display rsp atomically $ writeTVar (p'^.S.aborted) False
phaul/chess
Chess/UCI.hs
bsd-3-clause
7,959
0
21
2,296
1,821
913
908
163
3
{-# LANGUAGE DeriveDataTypeable, FlexibleContexts, MultiParamTypeClasses, TypeSynonymInstances, PatternGuards #-} ---------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.Hidden -- Copyright : (c) Peter Jones 2015 -- License : BSD3-style (see LICENSE) -- -- Maintainer : [email protected] -- Stability : unstable -- Portability : not portable -- -- Similar to "XMonad.Layout.Minimize" but completely removes windows -- from the window set so "XMonad.Layout.BoringWindows" isn't -- necessary. Perfect companion to -- "XMonad.Layout.BinarySpacePartition" since it can be used to move -- windows to another part of the BSP tree. -- ----------------------------------------------------------------------------- module XMonad.Layout.Hidden ( -- * Usage -- $usage HiddenMsg (..) , hiddenWindows , hideWindow , popOldestHiddenWindow , popNewestHiddenWindow ) where -------------------------------------------------------------------------------- import XMonad import XMonad.Layout.LayoutModifier import qualified XMonad.StackSet as W -------------------------------------------------------------------------------- -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Layout.Hidden -- -- Then edit your @layoutHook@ by adding the @HiddenWindows@ layout modifier: -- -- > myLayout = hiddenWindows (Tall 1 (3/100) (1/2)) ||| Full ||| etc.. -- > main = xmonad def { layoutHook = myLayout } -- -- For more detailed instructions on editing the layoutHook see: -- -- "XMonad.Doc.Extending#Editing_the_layout_hook" -- -- In the key bindings, do something like: -- -- > , ((modMask, xK_backslash), withFocused hideWindow) -- > , ((modMask .|. shiftMask, xK_backslash), popOldestHiddenWindow) -- > ... -- -- For detailed instruction on editing the key bindings see: -- -- "XMonad.Doc.Extending#Editing_key_bindings". -------------------------------------------------------------------------------- data HiddenWindows a = HiddenWindows [Window] deriving (Show, Read) -------------------------------------------------------------------------------- -- | Messages for the @HiddenWindows@ layout modifier. data HiddenMsg = HideWindow Window -- ^ Hide a window. | PopNewestHiddenWindow -- ^ Restore window (FILO). | PopOldestHiddenWindow -- ^ Restore window (FIFO). deriving (Typeable, Eq) instance Message HiddenMsg -------------------------------------------------------------------------------- instance LayoutModifier HiddenWindows Window where handleMess h@(HiddenWindows hidden) mess | Just (HideWindow win) <- fromMessage mess = hideWindowMsg h win | Just (PopNewestHiddenWindow) <- fromMessage mess = popNewestMsg h | Just (PopOldestHiddenWindow) <- fromMessage mess = popOldestMsg h | Just ReleaseResources <- fromMessage mess = doUnhook | otherwise = return Nothing where doUnhook = do mapM_ restoreWindow hidden return Nothing modifierDescription _ = "Hidden" -------------------------------------------------------------------------------- -- | Apply the @HiddenWindows@ layout modifier. hiddenWindows :: LayoutClass l Window => l Window -> ModifiedLayout HiddenWindows l Window hiddenWindows = ModifiedLayout $ HiddenWindows [] -------------------------------------------------------------------------------- -- | Remove the given window from the current layout. It is placed in -- list of hidden windows so it can be restored later. hideWindow :: Window -> X () hideWindow = sendMessage . HideWindow -------------------------------------------------------------------------------- -- | Restore a previously hidden window. Using this function will -- treat the list of hidden windows as a FIFO queue. That is, the -- first window hidden will be restored. popOldestHiddenWindow :: X () popOldestHiddenWindow = sendMessage PopOldestHiddenWindow -------------------------------------------------------------------------------- -- | Restore a previously hidden window. Using this function will -- treat the list of hidden windows as a FILO queue. That is, the -- most recently hidden window will be restored. popNewestHiddenWindow :: X () popNewestHiddenWindow = sendMessage PopNewestHiddenWindow -------------------------------------------------------------------------------- hideWindowMsg :: HiddenWindows a -> Window -> X (Maybe (HiddenWindows a)) hideWindowMsg (HiddenWindows hidden) win = do modify (\s -> s { windowset = W.delete' win $ windowset s }) return . Just . HiddenWindows $ hidden ++ [win] -------------------------------------------------------------------------------- popNewestMsg :: HiddenWindows a -> X (Maybe (HiddenWindows a)) popNewestMsg (HiddenWindows []) = return Nothing popNewestMsg (HiddenWindows hidden) = do let (win, rest) = (last hidden, init hidden) restoreWindow win return . Just . HiddenWindows $ rest -------------------------------------------------------------------------------- popOldestMsg :: HiddenWindows a -> X (Maybe (HiddenWindows a)) popOldestMsg (HiddenWindows []) = return Nothing popOldestMsg (HiddenWindows (win:rest)) = do restoreWindow win return . Just . HiddenWindows $ rest -------------------------------------------------------------------------------- restoreWindow :: Window -> X () restoreWindow win = modify (\s -> s { windowset = W.insertUp win $ windowset s })
f1u77y/xmonad-contrib
XMonad/Layout/Hidden.hs
bsd-3-clause
5,638
0
14
930
791
428
363
53
1
----------------------------------------------------------------------------- -- | -- Module : System.Mem -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Memory-related system things. -- ----------------------------------------------------------------------------- module System.Mem ( performGC -- :: IO () ) where import Prelude import Hugs.IOExts
OS2World/DEV-UTIL-HUGS
libraries/System/Mem.hs
bsd-3-clause
547
2
4
93
35
27
8
4
0
{-# LANGUAGE GADTs, ExistentialQuantification #-} {-# LANGUAGE RankNTypes, EmptyDataDecls #-} import Text.PrettyPrint.Leijen hiding (pretty, list) {-- GADT TEST: from "Fun with Phantom Types" - http://www.cs.ox.ac.uk/ralf.hinze/publications/With.pdf code translated to gadt syntax @ https://github.com/cutsea110/fun-of-phantom-type/blob/master/PhantomType.hs --} type Name = String type Age = Int data Person = Person Name Age deriving Show rString :: Type String rString = RList RChar -- a heterogeneous list data HList as where Nil :: HList () Cons, (:*:) :: a -> HList as -> HList (a, as) data Type t where RInt :: Type Int RChar :: Type Char RList :: Show a => Type a -> Type [a] RPair :: (Show a, Show b) => Type a -> Type b -> Type (a, b) RPerson :: Type Person RDyn :: Type Dynamic RFunc :: Type a -> Type b -> Type (a -> b) RProp :: Type Property -- RSList :: Type (HList (Type a)) data Dynamic where Dyn :: (Show t) => Type t -> t -> Dynamic --data Dynamic = forall t. Show t => Dyn (Type t) t -- pretty (RList RDyn) [Dyn RInt 60,Dyn rString "Bird"] -- pretty (RList RDyn) [Dyn RInt 60,Dyn rString "Bird"] data Property = PropSize Int | PropDate Char deriving Show type Traversal = forall t. Type t -> t -> t type Query s = forall t. Type t -> t -> s instance Show (Type t) where show (RInt) = "RInt" show (RChar) = "RChar" show (RList ra) = "(RList " ++ show ra ++ ")" show (RPair ra rb) = "(RPair " ++ show ra ++ " " ++ show rb ++ ")" show (RDyn) = "RDyn" instance Show Dynamic where show (Dyn ra a) = "Dyn " ++ show ra ++ " " ++ show a tick :: Name -> Traversal tick s (RPerson) (Person n a) | s == n = Person n (a + 1) tick s rt t = t copy :: Traversal copy rt = id (<*>) :: Traversal -> Traversal -> Traversal (f <*> g) rt = f rt . g rt imap :: Traversal -> Traversal imap f (RInt) i = i imap f (RChar) c = c imap f (RList ra) [] = [] imap f (RList ra) (a:as) = f ra a:f (RList ra) as imap f (RPair ra rb) (a, b) = (f ra a, f rb b) imap f (RPerson) (Person n a) = Person (f rString n) (f RInt a) everywhere, everywhere' :: Traversal -> Traversal everywhere f = f <*> imap (everywhere f) everywhere' f = imap (everywhere' f) <*> f age :: Query Age age (RPerson) (Person n a) = a age _ _ = 0 sizeof :: Query Int sizeof (RInt) _ = 2 sizeof (RChar) _ = 2 sizeof (RList ra) [] = 0 sizeof (RList ra) (_:_) = 3 sizeof (RPair ra rb) _ = 3 sizeof (RPerson) _ = 3 isum :: Query Int -> Query Int isum f (RInt) i = 0 isum f (RChar) c = 0 isum f (RList ra) [] = 0 isum f (RList ra) (a:as) = f ra a + f (RList ra) as isum f (RPair ra rb) (a, b) = f ra a + f rb b isum f (RPerson ) (Person n a) = f rString n + f RInt a total :: Query Int -> Query Int total f rt t = f rt t + isum (total f) rt t data Rep = forall t. Show t => Rep (Type t) instance Show Rep where show (Rep r) = "Rep " ++ show r prettyRep :: Rep -> Doc prettyRep (Rep (RInt)) = text "RInt" prettyRep (Rep (RChar)) = text "RChar" prettyRep (Rep (RList ra)) = lparen <> text "RList" <+> prettyRep (Rep ra) <> rparen prettyRep (Rep (RPair ra rb)) = align $ cat [lparen, text "RPair", prettyRep (Rep ra), prettyRep (Rep rb), rparen] prettyRep (Rep (RDyn)) = text "RDyn" prettyDynamic :: Dynamic -> Doc prettyDynamic (Dyn ra a) = text "Dyn" <+> prettyRep (Rep ra) <+> (align $ pretty ra a) pretty :: forall t. Type t -> t -> Doc pretty (RInt) i = prettyInt i where prettyInt = text . show pretty (RChar) c = prettyChar c where prettyChar = text . show pretty (RList RChar) s = prettyString s where prettyString = text . show pretty (RList ra) [] = text "[]" pretty (RList ra) (a:as) = block 1 (text "[" <> pretty ra a <> prettyL as) where prettyL [] = text "]" prettyL (a:as) = text "," <> line <> pretty ra a <> prettyL as pretty (RPair ra rb) (a, b) = block 1 (text "(" <> pretty ra a <> text "," <> line <> pretty rb b <> text ")") pretty (RPerson) p = prettyPerson p where prettyPerson = text . show pretty (RProp) p = prettyProp p where prettyProp = text . show pretty (RDyn) a = prettyDynamic a block :: Int -> Doc -> Doc block i d = group (nest i d) ps = [Person "Norma" 50, Person "Richard" 59] ps'= everywhere (tick "Richard") (RList RPerson) ps ta = total age (RList RPerson) ps' {-- End TEST --} -- Must get this to work data Date data Prop instance Show Prop where show a = "Prop" data Expr a where I :: Int -> Expr Int B :: Bool -> Expr Bool EChar :: Char -> Expr Char PpRotation :: Prop -> Expr Int -> Expr Int PpDate :: Prop -> String -> Expr Prop EList :: [a] -> Expr [a] Pair :: Expr a -> Expr b -> Expr (a, b) -- a standard list (homogeneous type) data SList a where SNil :: SList a SCons, (:@) :: a -> SList a -> SList a infixr 5 :@ infixr 5 :*: -- test the hlist sl = 1 :@ 1 :@ SNil hl = "HI" :*: 1 :*: Nil -- basics reString :: Expr String reString = EList "HELLO" rPropList' :: Expr [Expr Int] rPropList' = EList [I 3, I 4] -- <- homogeneous -- what do I do with this guy?!? -- rPropList :: Expr [Expr Prop] -- rPropList = EList [PpDate (undefined::Prop) "1.1.2012", PpRotation (undefined::Prop) (I 3)] eval :: Expr a -> a eval (I i) = i eval (B t) = t eval (EChar c) = c eval (PpRotation p r) = eval r eval (Pair a b) = (eval a, eval b) {-- eval (PpRotation p r) = p eval (PpDate p d) = d --} -- similar to above... [AnyExpr (I 3), AnyExpr (B True)]... data AnyExpr where AnyExpr :: Expr a -> AnyExpr main = print "Hello World!" {-- RHlNil :: Type RNil RHCons :: Type a -> Type b -> Type (a, b) --}
gregor-samsa/hs.test
gadt.hs
bsd-3-clause
5,671
59
12
1,417
2,446
1,250
1,196
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE FlexibleContexts #-} module Main (main) where import Control.DeepSeq import Criterion.Types import Criterion.Main import qualified Data.Vector.Generic as VG import qualified Data.Vector.Unboxed as VU import qualified Data.Vector.Storable as VS import Data.Primitive.SIMD import System.Random (mkStdGen, randomRs) ------------------------------------------------------------------------------- -- config veclen :: Int veclen = 16384 critConfig :: Config critConfig = defaultConfig { csvFile = Just $ "summary" ++ shows veclen ".csv" ,reportFile = Just $ "report" ++ shows veclen ".html" } ------------------------------------------------------------------------------- -- main main :: IO () main = do ----------------------------------- -- initialize single vectors putStrLn "constructing vectors" let lf1 = take veclen $ randomRs (-10000, 10000) $ mkStdGen 1 :: [Float] lf2 = take veclen $ randomRs (-10000, 10000) $ mkStdGen 2 :: [Float] ld1 = take veclen $ randomRs (-10000, 10000) $ mkStdGen 1 :: [Double] ld2 = take veclen $ randomRs (-10000, 10000) $ mkStdGen 2 :: [Double] let vuf1 = VU.fromList lf1 :: VU.Vector Float vuf2 = VU.fromList lf2 :: VU.Vector Float deepseq vuf1 $ deepseq vuf2 $ return () let vud1 = VU.fromList ld1 :: VU.Vector Double vud2 = VU.fromList ld2 :: VU.Vector Double deepseq vud1 $ deepseq vud2 $ return () let vsf1 = VS.fromList lf1 :: VS.Vector Float vsf2 = VS.fromList lf2 :: VS.Vector Float deepseq vsf1 $ deepseq vsf2 $ return () let vsd1 = VS.fromList ld1 :: VS.Vector Double vsd2 = VS.fromList ld2 :: VS.Vector Double deepseq vsd1 $ deepseq vsd2 $ return () let vsf1_4 = VS.unsafeCast vsf1 :: VS.Vector FloatX4 vsf2_4 = VS.unsafeCast vsf2 :: VS.Vector FloatX4 deepseq vsf1_4 $ deepseq vsf2_4 $ return () let vsf1_8 = VS.unsafeCast vsf1 :: VS.Vector FloatX8 vsf2_8 = VS.unsafeCast vsf2 :: VS.Vector FloatX8 deepseq vsf1_8 $ deepseq vsf2_8 $ return () let vsf1_16 = VS.unsafeCast vsf1 :: VS.Vector FloatX16 vsf2_16 = VS.unsafeCast vsf2 :: VS.Vector FloatX16 deepseq vsf1_16 $ deepseq vsf2_16 $ return () let vsd1_2 = VS.unsafeCast vsd1 :: VS.Vector DoubleX2 vsd2_2 = VS.unsafeCast vsd2 :: VS.Vector DoubleX2 deepseq vsd1_2 $ deepseq vsd2_2 $ return () let vsd1_4 = VS.unsafeCast vsd1 :: VS.Vector DoubleX4 vsd2_4 = VS.unsafeCast vsd2 :: VS.Vector DoubleX4 deepseq vsd1_4 $ deepseq vsd2_4 $ return () let vsd1_8 = VS.unsafeCast vsd1 :: VS.Vector DoubleX8 vsd2_8 = VS.unsafeCast vsd2 :: VS.Vector DoubleX8 deepseq vsd1_8 $ deepseq vsd2_8 $ return () let vuf1_4 = VU.convert vsf1_4 :: VU.Vector FloatX4 vuf2_4 = VU.convert vsf2_4 :: VU.Vector FloatX4 deepseq vuf1_4 $ deepseq vuf2_4 $ return () let vuf1_8 = VU.convert vsf1_8 :: VU.Vector FloatX8 vuf2_8 = VU.convert vsf2_8 :: VU.Vector FloatX8 deepseq vuf1_8 $ deepseq vuf2_8 $ return () let vuf1_16 = VU.convert vsf1_16 :: VU.Vector FloatX16 vuf2_16 = VU.convert vsf2_16 :: VU.Vector FloatX16 deepseq vuf1_16 $ deepseq vuf2_16 $ return () let vud1_2 = VU.convert vsd1_2 :: VU.Vector DoubleX2 vud2_2 = VU.convert vsd2_2 :: VU.Vector DoubleX2 deepseq vud1_2 $ deepseq vud2_2 $ return () let vud1_4 = VU.convert vsd1_4 :: VU.Vector DoubleX4 vud2_4 = VU.convert vsd2_4 :: VU.Vector DoubleX4 deepseq vud1_4 $ deepseq vud2_4 $ return () let vud1_8 = VU.convert vsd1_8 :: VU.Vector DoubleX8 vud2_8 = VU.convert vsd2_8 :: VU.Vector DoubleX8 deepseq vud1_8 $ deepseq vud2_8 $ return () ----------------------------------- -- tests putStrLn "starting criterion" defaultMainWith critConfig [ bgroup "VU" [ bgroup "Float" [ bench "diff1" $ nf (distanceDiff1 vuf1) vuf2 , bench "diff2" $ nf (distanceDiff2 vuf1) vuf2 , bench "diff4" $ nf (distanceDiff4 vuf1) vuf2 , bench "diff8" $ nf (distanceDiff8 vuf1) vuf2 , bench "simd4-1" $ nf (distanceSimd1 vuf1_4) vuf2_4 , bench "simd8-1" $ nf (distanceSimd1 vuf1_8) vuf2_8 , bench "simd16-1" $ nf (distanceSimd1 vuf1_16) vuf2_16 , bench "simd4-2" $ nf (distanceSimd2 vuf1_4) vuf2_4 , bench "simd8-2" $ nf (distanceSimd2 vuf1_8) vuf2_8 , bench "simd16-2" $ nf (distanceSimd2 vuf1_16) vuf2_16 , bench "simd4-4" $ nf (distanceSimd4 vuf1_4) vuf2_4 , bench "simd8-4" $ nf (distanceSimd4 vuf1_8) vuf2_8 , bench "simd16-4" $ nf (distanceSimd4 vuf1_16) vuf2_16 , bench "simd4-8" $ nf (distanceSimd8 vuf1_4) vuf2_4 , bench "simd8-8" $ nf (distanceSimd8 vuf1_8) vuf2_8 , bench "simd16-8" $ nf (distanceSimd8 vuf1_16) vuf2_16 ] , bgroup "Double" [ bench "diff1" $ nf (distanceDiff1 vud1) vud2 , bench "diff2" $ nf (distanceDiff2 vud1) vud2 , bench "diff4" $ nf (distanceDiff4 vud1) vud2 , bench "diff8" $ nf (distanceDiff8 vud1) vud2 , bench "simd2-1" $ nf (distanceSimd1 vud1_2) vud2_2 , bench "simd4-1" $ nf (distanceSimd1 vud1_4) vud2_4 , bench "simd8-1" $ nf (distanceSimd1 vud1_8) vud2_8 , bench "simd2-2" $ nf (distanceSimd2 vud1_2) vud2_2 , bench "simd4-2" $ nf (distanceSimd2 vud1_4) vud2_4 , bench "simd8-2" $ nf (distanceSimd2 vud1_8) vud2_8 , bench "simd2-4" $ nf (distanceSimd4 vud1_2) vud2_2 , bench "simd4-4" $ nf (distanceSimd4 vud1_4) vud2_4 , bench "simd8-4" $ nf (distanceSimd4 vud1_8) vud2_8 , bench "simd2-8" $ nf (distanceSimd8 vud1_2) vud2_2 , bench "simd4-8" $ nf (distanceSimd8 vud1_4) vud2_4 , bench "simd8-8" $ nf (distanceSimd8 vud1_8) vud2_8 ] ] , bgroup "VS" [ bgroup "Float" [ bench "diff1" $ nf (distanceDiff1 vsf1) vsf2 , bench "diff2" $ nf (distanceDiff2 vsf1) vsf2 , bench "diff4" $ nf (distanceDiff4 vsf1) vsf2 , bench "diff8" $ nf (distanceDiff8 vsf1) vsf2 , bench "simd4-1" $ nf (distanceSimd1 vsf1_4) vsf2_4 , bench "simd8-1" $ nf (distanceSimd1 vsf1_8) vsf2_8 , bench "simd16-1" $ nf (distanceSimd1 vsf1_16) vsf2_16 , bench "simd4-2" $ nf (distanceSimd2 vsf1_4) vsf2_4 , bench "simd8-2" $ nf (distanceSimd2 vsf1_8) vsf2_8 , bench "simd16-2" $ nf (distanceSimd2 vsf1_16) vsf2_16 , bench "simd4-4" $ nf (distanceSimd4 vsf1_4) vsf2_4 , bench "simd8-4" $ nf (distanceSimd4 vsf1_8) vsf2_8 , bench "simd16-4" $ nf (distanceSimd4 vsf1_16) vsf2_16 , bench "simd4-8" $ nf (distanceSimd8 vsf1_4) vsf2_4 , bench "simd8-8" $ nf (distanceSimd8 vsf1_8) vsf2_8 , bench "simd16-8" $ nf (distanceSimd8 vsf1_16) vsf2_16 ] , bgroup "Double" [ bench "diff1" $ nf (distanceDiff1 vsd1) vsd2 , bench "diff2" $ nf (distanceDiff2 vsd1) vsd2 , bench "diff4" $ nf (distanceDiff4 vsd1) vsd2 , bench "diff8" $ nf (distanceDiff8 vsd1) vsd2 , bench "simd2-1" $ nf (distanceSimd1 vsd1_2) vsd2_2 , bench "simd4-1" $ nf (distanceSimd1 vsd1_4) vsd2_4 , bench "simd8-1" $ nf (distanceSimd1 vsd1_8) vsd2_8 , bench "simd2-2" $ nf (distanceSimd2 vsd1_2) vsd2_2 , bench "simd4-2" $ nf (distanceSimd2 vsd1_4) vsd2_4 , bench "simd8-2" $ nf (distanceSimd2 vsd1_8) vsd2_8 , bench "simd2-4" $ nf (distanceSimd4 vsd1_2) vsd2_2 , bench "simd4-4" $ nf (distanceSimd4 vsd1_4) vsd2_4 , bench "simd8-4" $ nf (distanceSimd4 vsd1_8) vsd2_8 , bench "simd2-8" $ nf (distanceSimd8 vsd1_2) vsd2_2 , bench "simd4-8" $ nf (distanceSimd8 vsd1_4) vsd2_4 , bench "simd8-8" $ nf (distanceSimd8 vsd1_8) vsd2_8 ] ] ] putStrLn "reference values - float" mapM_ print [distanceDiff1 vuf1 vuf2 ,distanceDiff2 vuf1 vuf2 ,distanceDiff4 vuf1 vuf2 ,distanceDiff8 vuf1 vuf2 ,distanceSimd1 vuf1_4 vuf2_4 ,distanceSimd1 vuf1_8 vuf2_8 ,distanceSimd1 vuf1_16 vuf2_16 ,distanceSimd2 vuf1_4 vuf2_4 ,distanceSimd2 vuf1_8 vuf2_8 ,distanceSimd2 vuf1_16 vuf2_16 ,distanceSimd4 vuf1_4 vuf2_4 ,distanceSimd4 vuf1_8 vuf2_8 ,distanceSimd4 vuf1_16 vuf2_16 ,distanceSimd8 vuf1_4 vuf2_4 ,distanceSimd8 vuf1_8 vuf2_8 ,distanceSimd8 vuf1_16 vuf2_16 ,distanceDiff1 vsf1 vsf2 ,distanceDiff2 vsf1 vsf2 ,distanceDiff4 vsf1 vsf2 ,distanceDiff8 vsf1 vsf2 ,distanceSimd1 vsf1_4 vsf2_4 ,distanceSimd1 vsf1_8 vsf2_8 ,distanceSimd1 vsf1_16 vsf2_16 ,distanceSimd2 vsf1_4 vsf2_4 ,distanceSimd2 vsf1_8 vsf2_8 ,distanceSimd2 vsf1_16 vsf2_16 ,distanceSimd4 vsf1_4 vsf2_4 ,distanceSimd4 vsf1_8 vsf2_8 ,distanceSimd4 vsf1_16 vsf2_16 ,distanceSimd8 vsf1_4 vsf2_4 ,distanceSimd8 vsf1_8 vsf2_8 ,distanceSimd8 vsf1_16 vsf2_16 ] putStrLn "reference values - double" mapM_ print [distanceDiff1 vud1 vud2 ,distanceDiff2 vud1 vud2 ,distanceDiff4 vud1 vud2 ,distanceDiff8 vud1 vud2 ,distanceSimd1 vud1_2 vud2_2 ,distanceSimd1 vud1_4 vud2_4 ,distanceSimd1 vud1_8 vud2_8 ,distanceSimd2 vud1_2 vud2_2 ,distanceSimd2 vud1_4 vud2_4 ,distanceSimd2 vud1_8 vud2_8 ,distanceSimd4 vud1_2 vud2_2 ,distanceSimd4 vud1_4 vud2_4 ,distanceSimd4 vud1_8 vud2_8 ,distanceSimd8 vud1_2 vud2_2 ,distanceSimd8 vud1_4 vud2_4 ,distanceSimd8 vud1_8 vud2_8 ,distanceDiff1 vsd1 vsd2 ,distanceDiff2 vsd1 vsd2 ,distanceDiff4 vsd1 vsd2 ,distanceDiff8 vsd1 vsd2 ,distanceSimd1 vsd1_2 vsd2_2 ,distanceSimd1 vsd1_4 vsd2_4 ,distanceSimd1 vsd1_8 vsd2_8 ,distanceSimd2 vsd1_2 vsd2_2 ,distanceSimd2 vsd1_4 vsd2_4 ,distanceSimd2 vsd1_8 vsd2_8 ,distanceSimd4 vsd1_2 vsd2_2 ,distanceSimd4 vsd1_4 vsd2_4 ,distanceSimd4 vsd1_8 vsd2_8 ,distanceSimd8 vsd1_2 vsd2_2 ,distanceSimd8 vsd1_4 vsd2_4 ,distanceSimd8 vsd1_8 vsd2_8 ] ------------------------------------------------------------------------------- -- distance functions distanceDiff1 :: (VG.Vector v f, Floating f) => v f -> v f -> f distanceDiff1 = distanceDiff1Helper sqrt distanceDiff2 :: (VG.Vector v f, Floating f) => v f -> v f -> f distanceDiff2 = distanceDiff2Helper sqrt distanceDiff4 :: (VG.Vector v f, Floating f) => v f -> v f -> f distanceDiff4 = distanceDiff4Helper sqrt distanceDiff8 :: (VG.Vector v f, Floating f) => v f -> v f -> f distanceDiff8 = distanceDiff8Helper sqrt distanceSimd1 :: (VG.Vector v f, SIMDVector f, Num f, Floating (Elem f)) => v f -> v f -> Elem f distanceSimd1 = distanceDiff1Helper (sqrt . sumVector) distanceSimd2 :: (VG.Vector v f, SIMDVector f, Num f, Floating (Elem f)) => v f -> v f -> Elem f distanceSimd2 = distanceDiff2Helper (sqrt . sumVector) distanceSimd4 :: (VG.Vector v f, SIMDVector f, Num f, Floating (Elem f)) => v f -> v f -> Elem f distanceSimd4 = distanceDiff4Helper (sqrt . sumVector) distanceSimd8 :: (VG.Vector v f, SIMDVector f, Num f, Floating (Elem f)) => v f -> v f -> Elem f distanceSimd8 = distanceDiff8Helper (sqrt . sumVector) -- helpers sqr :: Num a => a -> a sqr a = a * a {-# INLINE zipVecsWith #-} zipVecsWith :: VG.Vector v a => (a -> a -> b -> b) -> b -> v a -> v a -> b zipVecsWith f z v1 v2 = VG.ifoldl' (\ acc i a -> f a (VG.unsafeIndex v2 i) acc) z v1 distanceDiff1Helper :: (VG.Vector v a, Num a) => (a -> r) -> v a -> v a -> r distanceDiff1Helper f v1 v2 = f $ zipVecsWith (\ a b acc -> acc + sqr (a - b)) 0 v1 v2 distanceDiff2Helper :: (VG.Vector v a, Num a) => (a -> r) -> v a -> v a -> r distanceDiff2Helper f v1 v2 = f $ go 0 (VG.length v1-1) where go acc (-1) = acc go acc i = go acc' (i-2) where acc' = acc+diff1*diff1 +diff2*diff2 diff1 = v1 `VG.unsafeIndex` i - v2 `VG.unsafeIndex` i diff2 = v1 `VG.unsafeIndex` (i-1) - v2 `VG.unsafeIndex` (i-1) distanceDiff4Helper :: (VG.Vector v a, Num a) => (a -> r) -> v a -> v a -> r distanceDiff4Helper f v1 v2 = f $ go 0 (VG.length v1-1) where go acc (-1) = acc go acc i = go acc' (i-4) where acc' = acc+diff1*diff1 +diff2*diff2 +diff3*diff3 +diff4*diff4 diff1 = diff 0 diff2 = diff 1 diff j = v1 `VG.unsafeIndex` (i-j) - v2 `VG.unsafeIndex` (i-j) diff3 = diff 2 diff4 = diff 3 distanceDiff8Helper :: (VG.Vector v a, Num a) => (a -> r) -> v a -> v a -> r distanceDiff8Helper f v1 v2 = f $ go 0 (VG.length v1-1) where go acc (-1) = acc go acc i = go acc' (i-8) where acc' = acc+diff1*diff1 +diff2*diff2 +diff3*diff3 +diff4*diff4 +diff5*diff5 +diff6*diff6 +diff7*diff7 +diff8*diff8 diff1 = diff 0 diff2 = diff 1 diff3 = diff 2 diff4 = diff 3 diff5 = diff 4 diff6 = diff 5 diff7 = diff 6 diff8 = diff 7 diff j = v1 `VG.unsafeIndex` (i-j) - v2 `VG.unsafeIndex` (i-j)
ajscholl/primitive-simd
bench/Bench.hs
bsd-3-clause
16,900
0
24
7,069
4,706
2,309
2,397
277
2
module Main where import Control.Monad import Control.Monad.State import Control.Monad.Exception import Data.Maybe import Data.List import YaLedger.Types import YaLedger.Kernel import YaLedger.Main import YaLedger.Exceptions import YaLedger.Tests.Instances import YaLedger.Tests.Correspondence import qualified YaLedger.Tests.Main as Test main :: IO () main = Test.main "-c ./examples/tests.yaml"
portnov/yaledger
yaledger-tests.hs
bsd-3-clause
406
0
6
48
92
57
35
16
1
{-# LANGUAGE MagicHash, GADTs, RankNTypes #-} module Main where import GHC.Exts -- Obvious case for contification. case1_yes :: () -> Int# case1_yes () = let {-# NOINLINE k #-} k x = 1# +# x in k 3# -- Can contify by floating in toward the one call site. case2_yes :: () -> Int# case2_yes () = let {-# NOINLINE k #-} k x = case x of { 0# -> True; _ -> False } in if k 3# then 1# else 2# -- Can't contify because one calls are in different continuations' scopes. case3_no :: Bool case3_no = let {-# NOINLINE k #-} k x = case x of { 0# -> True; _ -> False } in k (if k 3# then 1# else 2#) {-# NOINLINE flag #-} flag :: Bool flag = False -- Can contify g but not k case4_mixed :: Bool case4_mixed = let {-# NOINLINE k #-} k x = case x of { 0# -> True; _ -> False } {-# NOINLINE g #-} g y = k (y 5#) in if flag && k 3# then True else g (+# 1#) -- Can contify; tail-called from one branch and not used in the other case5_yes :: Bool case5_yes = let {-# NOINLINE k #-} k x = case x of { 0# -> True; _ -> False } in if flag then True else k 1# -- Can't contify only one among mutually recursive functions; also, can't float -- into recursive RHS case6_no :: Int# -> Int# case6_no x = let {-# NOINLINE k #-} k y = if tagToEnum# (y <# 0#) then 0# else y +# f (y -# 1#) {-# NOINLINE f #-} f y = k (y -# 1#) in f x -- We would like to handle this case, but seems to require abstract -- interpretation: We need to fix the type argument to h but it's only ever -- called with an inner-bound tyvar as the type. case7_yes_someday :: [Bool] -> [Bool] case7_yes_someday bs = let k, h :: [a] -> [a] -> [a] {-# NOINLINE k #-} k xs acc = case xs of [] -> acc _ : xs' -> h xs' acc {-# NOINLINE h #-} h xs acc = case xs of [] -> acc x : xs' -> k xs' (x : x : acc) in k bs [] -- If a contified function is unsaturated, its free variables *do* escape case8_mixed :: Int# -> Int# case8_mixed = let f :: Int# -> Int# -> Int# {-# NOINLINE f #-} f x y = x +# y k, h :: Int# -> Int# {-# NOINLINE k #-} k = f 5# {-# NOINLINE h #-} h = \x -> k (x +# 1#) -- Not a tail call! Outer context wants Int# -> Int# in h case9_yes :: Int -> Int case9_yes x = let k, h :: Int -> Int {-# NOINLINE k #-} k y = if y == 0 then 1 else h (y-1) {-# NOINLINE h #-} h y = if y == 0 then 0 else k (y-1) in k x -- Can float recursive groups inward case10_yes :: Int -> Int case10_yes x = let k, h :: Int -> Bool {-# NOINLINE k #-} k y = if y == 0 then True else h (y-1) {-# NOINLINE h #-} h y = if y == 0 then False else k (y-1) in if k x then 1 else 0 -- Don't wreck sharing by floating a thunk inward case11_no :: Int -> Int case11_no x = let {-# NOINLINE y #-} y = x + 1 {-# NOINLINE f #-} f 0 = 1 f z = f (z-1) * y -- Could float into argument and contify (but shouldn't!) in f x main :: IO () main = return ()
lukemaurer/sequent-core
examples/FullContification.hs
bsd-3-clause
3,209
0
15
1,096
960
518
442
87
4
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Sig.Tool.Hackage where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>)) #endif import Control.Monad.Catch (MonadThrow, throwM) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Trans.Control (MonadBaseControl) import Data.Aeson (eitherDecode) import Data.Aeson.TH (deriveFromJSON, defaultOptions) import Data.List.Split (splitOn) import Data.Maybe (mapMaybe) import Data.Monoid ((<>)) import Distribution.Package (PackageIdentifier) import Distribution.Text (simpleParse) import Network.HTTP.Conduit (parseUrl, newManager, httpLbs, requestHeaders, responseBody, tlsManagerSettings) import Sig.Tool.Types data UserDetail = UserDetail { groups :: [String] , username :: String , userid :: Integer } deriving (Show,Eq) $(deriveFromJSON defaultOptions ''UserDetail) packagesForMaintainer :: (MonadBaseControl IO m, MonadIO m, MonadThrow m) => String -> m [PackageIdentifier] packagesForMaintainer uname = do mgr <- liftIO (newManager tlsManagerSettings) req <- parseUrl ("https://hackage.haskell.org/user/" <> uname) res <- liftIO (httpLbs (req { requestHeaders = [("Accept", "application/json")] }) mgr) case (fmap packageNamesForUser <$> eitherDecode) (responseBody res) of Left err -> throwM (HackageAPIException ("Cloudn't retrieve packages for user " <> uname <> ": " <> show err)) Right pkgs -> return pkgs packageNamesForUser :: UserDetail -> [PackageIdentifier] packageNamesForUser = mapMaybe packageNameFromGroup . groups where packageNameFromGroup grp = case filter ("" /=) (splitOn "/" grp) of ["package",pkg,"maintainers"] -> simpleParse pkg _ -> Nothing
commercialhaskell/sig-tool
src/Sig/Tool/Hackage.hs
bsd-3-clause
2,005
0
16
472
500
282
218
51
2
{-# LANGUAGE MultiParamTypeClasses, ScopedTypeVariables, FlexibleInstances, GADTs , RecordWildCards, FunctionalDependencies, CPP, TemplateHaskell #-} module Llvm.Hir.Cast where import Llvm.Hir.Data.Inst import Llvm.Hir.Data.Type import Llvm.Hir.Data.Module import Data.Int import Llvm.ErrorLoc #define FLC (FileLoc $(srcLoc)) {- This module contains the functions to cast one Ir data type to another. Only compatable data types should be involved in casting. In some cases, casting is statically safe, which is normally known as up casting (or denoted as Ucast). In some cases, casting can only be decided at runtime, which is normally known as down casting (or denoted as Dcast). Dcast might throw out irrefutable fatal errors if incompatible types are involved. In such a situation, your code should filter out incompatible types before feeding them to Dcast. -} {- up casting -} class Ucast l1 l2 where ucast :: l1 -> l2 {- down casting -} class Dcast l1 l2 where dcast :: FileLoc -> l1 -> l2 instance Ucast l l where ucast = id instance Dcast l l where dcast _ = id {- A datum that can be casted to a constant -} class Cvalue x where toConst :: x -> Const g instance Cvalue Int32 where toConst = C_s32 instance Cvalue Int64 where toConst = C_s64 instance Cvalue Word32 where toConst = C_u32 instance Cvalue Word64 where toConst = C_u64 {- A data that can be casted to a value -} class Rvalue x where toRvalue :: x -> Value g instance Rvalue Lname where toRvalue = Val_ssa {- instance Rvalue (GlobalId g) g where toRvalue g = Val_const (C_globalAddr g) instance Rvalue (Const g) g where toRvalue = Val_const -} instance Rvalue Int32 where toRvalue = Val_const . C_s32 instance Rvalue Word32 where toRvalue = Val_const . C_u32 instance Rvalue Word64 where toRvalue = Val_const . C_u64 {- Typed Integer Constant, Typed Integer Constants are often used in indexing memory elements. -} class TC x where toTC :: x -> T (Type ScalarB I) (Const g) instance TC Word32 where toTC x = T (TpI 32) (toConst x) instance TC Word64 where toTC x = T (TpI 64) (toConst x) instance TC Int32 where toTC x = T (TpI 32) (toConst x) {- Typed Integer Value. -} class TV x where toTV :: x -> T (Type ScalarB I) (Value g) instance TV Word32 where toTV x = T (TpI 32) (toRvalue x) instance TV Int32 where toTV x = T (TpI 32) (toRvalue x) toTVs :: TV x => [x] -> [T (Type ScalarB I) (Value g)] toTVs l = fmap toTV l toTCs :: TC x => [x] -> [T (Type ScalarB I) (Const g)] toTCs l = fmap toTC l i32sToTvs :: [Int32] -> [T (Type ScalarB I) (Value g)] i32sToTvs = toTVs i32sToTcs :: [Int32] -> [T (Type ScalarB I) (Const g)] i32sToTcs = toTCs u32sToTvs :: [Word32] -> [T (Type ScalarB I) (Value g)] u32sToTvs = toTVs u32sToTcs :: [Word32] -> [T (Type ScalarB I) (Const g)] u32sToTcs = toTCs i32ToTv :: Int32 -> T (Type ScalarB I) (Value g) i32ToTv = toTV u32ToTv :: Word32 -> T (Type ScalarB I) (Value g) u32ToTv = toTV instance Ucast (Const g) (Value g) where ucast = Val_const instance Show g => Dcast (Value g) (Const g) where dcast lc x = case x of Val_const v -> v _ -> dcastError lc "Const" x instance (Ucast t s, Ucast u v) => Ucast (T t u) (T s v) where ucast (T t u) = T (ucast t) (ucast u) instance (Dcast s t, Dcast v u) => Dcast (T s v) (T t u) where dcast lc (T s v) = T (dcast lc s) (dcast lc v) {- Type s r, which represents all types, ucast to Utype -} instance Ucast (Type s r) Utype where ucast x = case x of TpI _ -> UtypeScalarI x TpF _ -> UtypeScalarF x TpV _ -> UtypeScalarI x Tvoid -> UtypeVoidU x TpHalf -> UtypeScalarF x TpFloat -> UtypeScalarF x TpDouble -> UtypeScalarF x TpFp128 -> UtypeScalarF x TpX86Fp80 -> UtypeScalarF x TpPpcFp128 -> UtypeScalarF x TpX86Mmx -> UtypeScalarI x TpNull -> UtypeScalarI x TpLabel -> UtypeLabelX x Topaque -> UtypeOpaqueD x TvectorI _ _ -> UtypeVectorI x TvectorF _ _ -> UtypeVectorF x TvectorP _ _ -> UtypeVectorP x Tfirst_class_array _ _ -> UtypeFirstClassD x Tfirst_class_struct _ _ -> UtypeFirstClassD x Tfirst_class_name _ -> UtypeFirstClassD x Tarray _ _ -> UtypeRecordD x Tstruct _ _ -> UtypeRecordD x Topaque_struct _ _ -> UtypeOpaqueD x Topaque_array _ _ -> UtypeOpaqueD x Tpointer _ _ -> UtypeScalarP x Tfunction _ _ _ -> UtypeFunX x {- Scalar -} TnameScalarI _ -> UtypeScalarI x TnameScalarF _ -> UtypeScalarF x TnameScalarP _ -> UtypeScalarP x {- Vector -} TnameVectorI _ -> UtypeVectorI x TnameVectorF _ -> UtypeVectorF x TnameVectorP _ -> UtypeVectorP x {- Large -} TnameRecordD _ -> UtypeRecordD x {- Code -} TnameCodeFunX _ -> UtypeFunX x {- Opaque -} TnameOpaqueD _ -> UtypeOpaqueD x instance Dcast Utype (Type ScalarB I) where dcast lc e = case e of UtypeScalarI x -> x _ -> dcastError lc "Type ScalarB I" e instance Dcast Utype (Type ScalarB F) where dcast lc e = case e of UtypeScalarF x -> x _ -> dcastError lc "Type ScalarB F" e instance Dcast Utype (Type ScalarB P) where dcast lc e = case e of UtypeScalarP x -> x _ -> dcastError lc "Type ScalarB P" e instance Dcast Utype (Type VectorB I) where dcast lc e = case e of UtypeVectorI x -> x _ -> dcastError lc "Type VectorB I" e instance Dcast Utype (Type VectorB F) where dcast lc e = case e of UtypeVectorF x -> x _ -> dcastError lc "Type VectorB F" e instance Dcast Utype (Type VectorB P) where dcast lc e = case e of UtypeVectorP x -> x _ -> dcastError lc "Type VectorB P" e instance Dcast Utype (Type FirstClassB D) where dcast lc e = case e of UtypeFirstClassD x -> x _ -> dcastError lc "Type FirstClassB D" e instance Dcast Utype (Type RecordB D) where dcast lc e = case e of UtypeRecordD x -> x _ -> dcastError lc "Type RecordB D" e instance Dcast Utype (Type CodeFunB X) where dcast lc e = case e of UtypeFunX x -> x _ -> dcastError lc "Type CodeFunB X" e instance Dcast Utype (Type CodeLabelB X) where dcast lc e = case e of UtypeLabelX x -> x _ -> dcastError lc "Type CodeLabelB X" e instance Dcast Utype (Type OpaqueB D) where dcast lc e = case e of UtypeOpaqueD x -> x _ -> dcastError lc "Type OpaqueB D" e {- Etype's dcast, ucast, dcast -} instance Dcast Utype Etype where dcast lc x = case x of UtypeScalarI e -> EtypeScalarI e UtypeScalarF e -> EtypeScalarF e UtypeScalarP e -> EtypeScalarP e UtypeVectorI e -> EtypeVectorI e UtypeVectorF e -> EtypeVectorF e UtypeVectorP e -> EtypeVectorP e UtypeFirstClassD e -> EtypeFirstClassD e UtypeRecordD e -> EtypeRecordD e UtypeOpaqueD e -> EtypeOpaqueD e UtypeFunX e -> EtypeFunX e _ -> dcastError lc "Etype" x instance Ucast Etype Utype where ucast x = case x of EtypeScalarI e -> UtypeScalarI e EtypeScalarF e -> UtypeScalarF e EtypeScalarP e -> UtypeScalarP e EtypeVectorI e -> UtypeVectorI e EtypeVectorF e -> UtypeVectorF e EtypeVectorP e -> UtypeVectorP e EtypeFirstClassD e -> UtypeFirstClassD e EtypeRecordD e -> UtypeRecordD e EtypeOpaqueD e -> UtypeOpaqueD e EtypeFunX e -> UtypeFunX e instance Dcast Etype Dtype where dcast lc x = case x of EtypeScalarI e -> DtypeScalarI e EtypeScalarF e -> DtypeScalarF e EtypeScalarP e -> DtypeScalarP e EtypeVectorI e -> DtypeVectorI e EtypeVectorF e -> DtypeVectorF e EtypeVectorP e -> DtypeVectorP e EtypeFirstClassD e -> DtypeFirstClassD e EtypeRecordD e -> DtypeRecordD e _ -> dcastError lc "Dtype" x instance Dcast (Type s r) Etype where dcast lc x = let (x1::Utype) = ucast x in dcast lc x1 instance Ucast (Type x I) Etype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type x F) Etype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type x P) Etype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type FirstClassB x) Etype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type RecordB D) Etype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type CodeFunB X) Etype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 {- Rtype's dcast, ucast, dcast -} instance Dcast Utype Rtype where dcast lc x = case x of UtypeScalarI e -> RtypeScalarI e UtypeScalarF e -> RtypeScalarF e UtypeScalarP e -> RtypeScalarP e UtypeVectorI e -> RtypeVectorI e UtypeVectorF e -> RtypeVectorF e UtypeVectorP e -> RtypeVectorP e UtypeRecordD e -> RtypeRecordD e UtypeVoidU e -> RtypeVoidU e _ -> dcastError lc "Rtype" x instance Ucast Rtype Utype where ucast x = case x of RtypeScalarI e -> UtypeScalarI e RtypeScalarF e -> UtypeScalarF e RtypeScalarP e -> UtypeScalarP e RtypeVectorI e -> UtypeVectorI e RtypeVectorF e -> UtypeVectorF e RtypeVectorP e -> UtypeVectorP e RtypeRecordD e -> UtypeRecordD e RtypeFirstClassD e -> UtypeFirstClassD e RtypeVoidU e -> UtypeVoidU e instance Dcast Rtype Dtype where dcast lc x = case x of RtypeScalarI e -> DtypeScalarI e RtypeScalarF e -> DtypeScalarF e RtypeScalarP e -> DtypeScalarP e RtypeVectorI e -> DtypeVectorI e RtypeVectorF e -> DtypeVectorF e RtypeVectorP e -> DtypeVectorP e RtypeRecordD e -> DtypeRecordD e _ -> dcastError lc "Rtype" x instance Dcast (Type s r) Rtype where dcast lc x = let (x1::Utype) = ucast x in dcast lc x1 instance Ucast (Type x I) Rtype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type x F) Rtype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type x P) Rtype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type FirstClassB D) Rtype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type RecordB D) Rtype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type NoB U) Rtype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 {- Dtype's dcast, ucast, dcast -} instance Dcast Utype Dtype where dcast lc x = case x of UtypeScalarI e -> DtypeScalarI e UtypeScalarF e -> DtypeScalarF e UtypeScalarP e -> DtypeScalarP e UtypeVectorI e -> DtypeVectorI e UtypeVectorF e -> DtypeVectorF e UtypeVectorP e -> DtypeVectorP e UtypeFirstClassD e -> DtypeFirstClassD e UtypeRecordD e -> DtypeRecordD e _ -> dcastError lc "Dtype" x instance Ucast Dtype Utype where ucast x = case x of DtypeScalarI e -> UtypeScalarI e DtypeScalarF e -> UtypeScalarF e DtypeScalarP e -> UtypeScalarP e DtypeVectorI e -> UtypeVectorI e DtypeVectorF e -> UtypeVectorF e DtypeVectorP e -> UtypeVectorP e DtypeFirstClassD e -> UtypeFirstClassD e DtypeRecordD e -> UtypeRecordD e instance Ucast Dtype Etype where ucast x = case x of DtypeScalarI e -> EtypeScalarI e DtypeScalarF e -> EtypeScalarF e DtypeScalarP e -> EtypeScalarP e DtypeVectorI e -> EtypeVectorI e DtypeVectorF e -> EtypeVectorF e DtypeVectorP e -> EtypeVectorP e DtypeFirstClassD e -> EtypeFirstClassD e DtypeRecordD e -> EtypeRecordD e instance Ucast Dtype Rtype where ucast x = case x of DtypeScalarI e -> RtypeScalarI e DtypeScalarF e -> RtypeScalarF e DtypeScalarP e -> RtypeScalarP e DtypeVectorI e -> RtypeVectorI e DtypeVectorF e -> RtypeVectorF e DtypeVectorP e -> RtypeVectorP e DtypeFirstClassD e -> RtypeFirstClassD e DtypeRecordD e -> RtypeRecordD e instance Dcast (Type s r) Dtype where dcast lc x = let (x1::Utype) = ucast x in dcast lc x1 instance Ucast (Type x I) Dtype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type x F) Dtype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type x P) Dtype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type RecordB D) Dtype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type FirstClassB D) Dtype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Dcast Dtype (Type ScalarB P) where dcast lc x = case x of DtypeScalarP e -> e _ -> dcastError lc "Type ScalarB P" x instance Dcast Dtype (Type ScalarB I) where dcast lc x = case x of DtypeScalarI e -> e _ -> dcastError lc "Type ScalarB I" x instance Dcast Dtype (Type RecordB D) where dcast lc x = case x of DtypeRecordD e -> e _ -> dcastError lc "Type RecordB D" x {- Ftype's dcast, ucast, dcast -} instance Dcast Utype Ftype where dcast lc x = case x of UtypeScalarI e -> FtypeScalarI e UtypeScalarF e -> FtypeScalarF e UtypeScalarP e -> FtypeScalarP e UtypeVectorI e -> FtypeVectorI e UtypeVectorF e -> FtypeVectorF e UtypeVectorP e -> FtypeVectorP e UtypeFirstClassD e -> FtypeFirstClassD e _ -> dcastError lc "Ftype" x instance Ucast Ftype Utype where ucast x = case x of FtypeScalarI e -> UtypeScalarI e FtypeScalarF e -> UtypeScalarF e FtypeScalarP e -> UtypeScalarP e FtypeVectorI e -> UtypeVectorI e FtypeVectorF e -> UtypeVectorF e FtypeVectorP e -> UtypeVectorP e FtypeFirstClassD e -> UtypeFirstClassD e instance Ucast Ftype Dtype where ucast x = case x of FtypeScalarI e -> DtypeScalarI e FtypeScalarF e -> DtypeScalarF e FtypeScalarP e -> DtypeScalarP e FtypeVectorI e -> DtypeVectorI e FtypeVectorF e -> DtypeVectorF e FtypeVectorP e -> DtypeVectorP e FtypeFirstClassD e -> DtypeFirstClassD e instance Dcast (Type s r) Ftype where dcast lc x = let (x1::Utype) = ucast x in dcast lc x1 instance Ucast (Type x I) Ftype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type x F) Ftype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type x P) Ftype where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 {- ScalarType's dcast, ucast, dcast -} instance Dcast Utype ScalarType where dcast lc x = case x of UtypeScalarI e -> ScalarTypeI e UtypeScalarF e -> ScalarTypeF e UtypeScalarP e -> ScalarTypeP e _ -> dcastError lc "ScalarType" x instance Ucast ScalarType Utype where ucast x = case x of ScalarTypeI e -> UtypeScalarI e ScalarTypeF e -> UtypeScalarF e ScalarTypeP e -> UtypeScalarP e instance Dcast Dtype ScalarType where dcast lc x = case x of DtypeScalarI e -> ScalarTypeI e DtypeScalarF e -> ScalarTypeF e DtypeScalarP e -> ScalarTypeP e _ -> dcastError lc "ScalarType" x instance Ucast ScalarType Dtype where ucast x = case x of ScalarTypeI e -> DtypeScalarI e ScalarTypeF e -> DtypeScalarF e ScalarTypeP e -> DtypeScalarP e instance Dcast (Type s r) ScalarType where dcast lc x = let (x1::Utype) = ucast x in dcast lc x1 instance Ucast (Type x I) ScalarType where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type x F) ScalarType where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type x P) ScalarType where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 {- IntOrPtrType's dcast, ucast, dcast -} instance Dcast Utype (IntOrPtrType ScalarB) where dcast lc x = case x of UtypeScalarI e -> IntOrPtrTypeI e UtypeScalarP e -> IntOrPtrTypeP e _ -> dcastError lc "IntOrPtrType ScalarB" x instance Dcast Utype (IntOrPtrType VectorB) where dcast lc x = case x of UtypeVectorI e -> IntOrPtrTypeI e UtypeVectorP e -> IntOrPtrTypeP e _ -> dcastError lc "IntOrPtrType VectorB" x instance Ucast (IntOrPtrType ScalarB) Utype where ucast x = case x of IntOrPtrTypeI e -> UtypeScalarI e IntOrPtrTypeP e -> UtypeScalarP e instance Ucast (IntOrPtrType VectorB) Utype where ucast x = case x of IntOrPtrTypeI e -> UtypeVectorI e IntOrPtrTypeP e -> UtypeVectorP e instance Dcast (Type s r) (IntOrPtrType ScalarB) where dcast lc x = let (x1::Utype) = ucast x in dcast lc x1 instance Dcast (Type s r) (IntOrPtrType VectorB) where dcast lc x = let (x1::Utype) = ucast x in dcast lc x1 instance Ucast (Type ScalarB I) (IntOrPtrType ScalarB) where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type ScalarB P) (IntOrPtrType ScalarB) where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type VectorB I) (IntOrPtrType VectorB) where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 instance Ucast (Type VectorB P) (IntOrPtrType VectorB) where ucast x = let (x1::Utype) = ucast x in dcast (FileLoc "irrefutable") x1 squeeze :: FileLoc -> Type RecordB D -> Type FirstClassB D squeeze loc x = case x of Tstruct pk dl -> Tfirst_class_struct pk (fmap (dcast loc) dl) Tarray n el -> Tfirst_class_array n (dcast loc el) TnameRecordD e -> Tfirst_class_name e uc :: Ucast a b => a -> b uc x = ucast x dc :: Dcast a b => FileLoc -> String -> a -> b dc lc s x = dcast lc x mapUtype :: (Type CodeFunB X -> Type CodeFunB X) -> Dtype -> Dtype mapUtype f x = case x of DtypeScalarI n -> x DtypeScalarF n -> x DtypeScalarP n -> DtypeScalarP $ mapType f n DtypeVectorI n -> x DtypeVectorF n -> x DtypeVectorP n -> DtypeVectorP $ mapType f n DtypeFirstClassD n -> DtypeFirstClassD $ mapType f n DtypeRecordD n -> DtypeRecordD $ mapType f n mapEtype :: (Type CodeFunB X -> Type CodeFunB X) -> Etype -> Etype mapEtype f x = case x of EtypeScalarI n -> x EtypeScalarF n -> x EtypeScalarP n -> EtypeScalarP $ mapType f n EtypeVectorI n -> x EtypeVectorF n -> x EtypeVectorP n -> EtypeVectorP $ mapType f n EtypeFirstClassD n -> EtypeFirstClassD $ mapType f n EtypeRecordD n -> EtypeRecordD $ mapType f n EtypeOpaqueD n -> x EtypeFunX n -> EtypeFunX $ mapType f n mapRtype :: (Type CodeFunB X -> Type CodeFunB X) -> Rtype -> Rtype mapRtype f x = case x of RtypeScalarI n -> x RtypeScalarF n -> x RtypeScalarP n -> RtypeScalarP $ mapType f n RtypeVectorI n -> x RtypeVectorF n -> x RtypeVectorP n -> RtypeVectorP $ mapType f n RtypeFirstClassD n -> RtypeFirstClassD $ mapType f n RtypeRecordD n -> RtypeRecordD $ mapType f n RtypeVoidU n -> x mapMtype :: (Type CodeFunB X -> Type CodeFunB X) -> Mtype -> Mtype mapMtype f x = case x of MtypeAsRet n -> MtypeAsRet (mapUtype f n) MtypeData n -> MtypeData (mapUtype f n) MtypeByVal n -> MtypeByVal (mapUtype f n) MtypeExt e n -> MtypeExt e (mapUtype f n) MtypeLabel ft -> MtypeLabel ft mapStype :: (Type CodeFunB X -> Type CodeFunB X) -> ScalarType -> ScalarType mapStype f x = case x of ScalarTypeI n -> x ScalarTypeF n -> x ScalarTypeP n -> ScalarTypeP $ mapType f n mapType :: (Type CodeFunB X -> Type CodeFunB X) -> Type s r -> Type s r mapType f x = case x of TpI n -> x TpF n -> x TpV n -> x Tvoid -> x TpHalf -> x TpFloat -> x TpDouble -> x TpFp128 -> x TpX86Fp80 -> x TpPpcFp128 -> x TpX86Mmx -> x TpNull -> x TpLabel -> x Topaque -> x Tarray n d -> Tarray n (mapUtype f d) TvectorI n d -> x TvectorF n d -> x TvectorP n d -> TvectorP n (mapType f d) Tstruct p ds -> Tstruct p (fmap (mapUtype f) ds) Tpointer e as -> Tpointer (mapEtype f e) as Tfunction (rt,ra) tp mv -> let t = Tfunction (mapRtype f rt, ra) (fmap (\(mt, ma) -> (mapMtype f mt, ma)) tp) mv in f t {- Scalar -} TnameScalarI s -> x TnameScalarF s -> x TnameScalarP s -> x {- Vector -} TnameVectorI s -> x TnameVectorF s -> x TnameVectorP s -> x {- Large -} TnameRecordD s -> x {- Code -} TnameCodeFunX s -> x {- Opaque -} TnameOpaqueD s -> x Topaque_struct pk l -> x Topaque_array n e -> x Tfirst_class_array n e -> Tfirst_class_array n (mapStype f e) Tfirst_class_struct pk l -> Tfirst_class_struct pk (fmap (mapStype f) l) Tfirst_class_name s -> x
mlite/hLLVM
src/Llvm/Hir/Cast.hs
bsd-3-clause
21,068
0
18
5,413
7,878
3,696
4,182
-1
-1
-- Copyright 2013 Kevin Backhouse. {-| The 'OrdCons' instrument uses two passes to implement hash-consing. The values are added to the table during the first pass and a unique index for each value is returned during the second pass. 'OrdCons' is implemented using 'Data.Map', so it can be used on any datatype which is an instance of 'Ord'. -} module Control.Monad.MultiPass.Instrument.OrdCons ( OrdCons , initOrdCons, ordCons, getOrdConsTable , OrdConsTable , lookupOrdConsTable, insertOrdConsTable, growOrdConsTable ) where import Control.Exception ( assert ) import Control.Monad.ST2 import Control.Monad.Writer.Strict import Control.Monad.MultiPass import Control.Monad.MultiPass.ThreadContext.MonoidTC import qualified Data.Map as FM import Data.Maybe ( isJust, fromJust ) -- | Abstract datatype for the instrument. data OrdCons a r w p1 p2 tc = OrdCons { initInternal :: !(p1 (OrdConsTable a) -> MultiPassPrologue r w tc ()) , ordConsInternal :: !(p1 a -> MultiPass r w tc (p2 Int)) , getOrdConsTableInternal :: !(MultiPassEpilogue r w tc (p2 (OrdConsTable a))) } -- | Initialise the 'OrdCons' instrument with an 'OrdConsTable'. This -- method is optional. Ff this method is not used then the instrument -- will be initialised with an empty 'OrdConsTable'. initOrdCons :: (Ord a, Monad p1, Monad p2) => OrdCons a r w p1 p2 tc -- ^ Instrument -> p1 (OrdConsTable a) -- ^ Initial table -> MultiPassPrologue r w tc () initOrdCons = initInternal -- | Get a unique index for the value. ordCons :: (Ord a, Monad p1, Monad p2) => OrdCons a r w p1 p2 tc -- ^ Instrument -> p1 a -- ^ Value -> MultiPass r w tc (p2 Int) -- ^ Unique index ordCons = ordConsInternal -- | Get the final 'OrdConsTable'. getOrdConsTable :: OrdCons a r w p1 p2 tc -> MultiPassEpilogue r w tc (p2 (OrdConsTable a)) getOrdConsTable = getOrdConsTableInternal -- | This datatype is a newtype around @'FM.Map' a 'Int'@. It maps its -- keys (of type @a@) to a permutation of the integers @0..n-1@, where -- @n@ is the number of keys. newtype OrdConsTable a = OrdConsTable (FM.Map a Int) -- | Empty 'OrdConsTable'. emptyOrdConsTable :: OrdConsTable a emptyOrdConsTable = OrdConsTable FM.empty -- | Lookup an element. lookupOrdConsTable :: Ord a => OrdConsTable a -> a -> Maybe Int lookupOrdConsTable (OrdConsTable table) x = FM.lookup x table -- | Insert an element. If the element is not in the map yet, then it -- is assigned index @n@, where @n@ is the original size of the table. insertOrdConsTable :: Ord a => OrdConsTable a -> a -> OrdConsTable a insertOrdConsTable (OrdConsTable table) x = if FM.member x table then OrdConsTable table else OrdConsTable $ FM.insert x (FM.size table) table -- | Add multiple elements. The new elements are assigned indices -- @n..n+k-1@, where @n@ is the original size of the table and @k@ is -- the number of new elements to be added. This function will assert -- if any of the new elements are already in the table. growOrdConsTable :: Ord a => OrdConsTable a -> FM.Map a () -> OrdConsTable a growOrdConsTable (OrdConsTable table) xs = assert (FM.null (FM.intersection table xs)) $ let n = FM.size table in let xs' = snd $ FM.mapAccum (\i () -> (i+1, i)) n xs in OrdConsTable $ FM.union table xs' newtype GC1 r w a = GC1 (ST2Ref r w (OrdConsTable a)) newtype OrdConsTC a = OrdConsTC (FM.Map a ()) instance Ord a => Monoid (OrdConsTC a) where mempty = OrdConsTC FM.empty mappend (OrdConsTC xs) (OrdConsTC ys) = OrdConsTC (FM.union xs ys) instance Instrument tc () () (OrdCons a r w Off Off tc) where createInstrument _ _ () = wrapInstrument $ OrdCons { initInternal = \Off -> return () , ordConsInternal = \Off -> return Off , getOrdConsTableInternal = return Off } instance Ord a => Instrument tc (MonoidTC (OrdConsTC a)) (GC1 r w a) (OrdCons a r w On Off tc) where createInstrument st2ToMP updateCtx (GC1 initTableRef) = wrapInstrument $ OrdCons { initInternal = \(On initTable) -> mkMultiPassPrologue $ do -- Check that the initTableRef has not been initialised -- already. OrdConsTable xs <- st2ToMP $ readST2Ref initTableRef assert (FM.null xs) $ return () st2ToMP $ writeST2Ref initTableRef initTable , ordConsInternal = \(On x) -> let updateTable initTable (MonoidTC (OrdConsTC table)) = MonoidTC $ OrdConsTC $ if isJust (lookupOrdConsTable initTable x) then table else FM.insert x () table in mkMultiPass $ do initTable <- st2ToMP $ readST2Ref initTableRef _ <- updateCtx (updateTable initTable) return Off , getOrdConsTableInternal = return Off } -- The gc2_newTable field is a superset of gc2_initTable. (The -- initTable is only used if back-tracking occurs.) data GC2 a = GC2 { gc2_initTable :: !(OrdConsTable a) , gc2_newTable :: !(OrdConsTable a) } instance Ord a => Instrument tc () (GC2 a) (OrdCons a r w On On tc) where createInstrument _ _ gc = let newTable = gc2_newTable gc in wrapInstrument $ OrdCons { initInternal = \(On _) -> return () , ordConsInternal = \(On x) -> let m = lookupOrdConsTable newTable x in assert (isJust m) $ return $ On $ fromJust m , getOrdConsTableInternal = return (On newTable) } -- This instrument never needs to back-track. instance BackTrack r w tc (GC1 r w a) instance BackTrack r w () (GC2 a) instance NextGlobalContext r w () () (GC1 r w a) where nextGlobalContext _ _ () () = do initTableRef <- newST2Ref emptyOrdConsTable return (GC1 initTableRef) instance NextGlobalContext r w tc (GC1 r w a) (GC1 r w a) where nextGlobalContext _ _ _ gc = return gc instance Ord a => NextGlobalContext r w (MonoidTC (OrdConsTC a)) (GC1 r w a) (GC2 a) where nextGlobalContext _ _ tc gc = let GC1 initTableRef = gc in let MonoidTC (OrdConsTC table) = tc in do initTable <- readST2Ref initTableRef return $ GC2 { gc2_initTable = initTable , gc2_newTable = growOrdConsTable initTable table } instance NextGlobalContext r w tc (GC2 a) (GC2 a) where nextGlobalContext _ _ _ gc = return gc instance NextGlobalContext r w tc (GC2 a) (GC1 r w a) where nextGlobalContext _ _ _ gc = do initTableRef <- newST2Ref (gc2_initTable gc) return (GC1 initTableRef)
kevinbackhouse/Control-Monad-MultiPass
src/Control/Monad/MultiPass/Instrument/OrdCons.hs
bsd-3-clause
6,785
0
19
1,801
1,865
956
909
-1
-1
module RomanNumbersKata.Day5Spec (spec) where import Test.Hspec import RomanNumbersKata.Day5 (toRomanNumber) spec :: Spec spec = do it "returns an empty string when given 0" (toRomanNumber 0 == "") it "returns \"I\" when given 1" (toRomanNumber 1 == "I") it "returns \"V\" when given 5" (toRomanNumber 5 == "V") it "returns \"IV\" when given 4" (toRomanNumber 4 == "IV") it "returns \"III\" when given 3" (toRomanNumber 3 == "III") it "returns \"X\" when given 10" (toRomanNumber 10 == "X") it "returns \"XIV\" when given 14" (toRomanNumber 14 == "XIV") it "returns \"L\" when given 50" (toRomanNumber 50 == "L") it "returns \"IX\" when given 9" (toRomanNumber 9 == "IX")
Alex-Diez/haskell-tdd-kata
old-katas/test/RomanNumbersKata/Day5Spec.hs
bsd-3-clause
878
0
10
313
198
94
104
23
1
{-# LANGUAGE InstanceSigs #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} module Metas ( goodTeamRatioArbitaryMeta , goodTeamRatioTwoToLeftMeta , GoodTeamRatio(..) ) where import qualified Data.List as L import Data.Monoid import System.Environment -- Notes: -- - Round indices are 0-indexed -- | A seating arrangement. A player is represented as True for good, False for bad type Seating = [Bool] data GoodTeamRatio = GoodTeamRatio Int Int deriving (Eq) instance Show GoodTeamRatio where show :: GoodTeamRatio -> String show (GoodTeamRatio a b) = "# good teams: " ++ (show a) ++ " | # teams: " ++ (show b) ++ " | (" ++ (show . roundToKDigits 2 $ ((fromIntegral a) / (fromIntegral b))) ++ ")" where roundToKDigits :: (Fractional a, RealFrac r) => Int -> r -> a roundToKDigits k n = (fromInteger . round $ n * (10^k)) / (10.0^^k) instance Monoid GoodTeamRatio where mempty :: GoodTeamRatio mempty = GoodTeamRatio 0 0 -- | Sum number of good teams and total number of teams respectively mappend :: GoodTeamRatio -> GoodTeamRatio -> GoodTeamRatio mappend (GoodTeamRatio a b) (GoodTeamRatio c d) = GoodTeamRatio (a + c) (b + d) -- | /O(2^k)/ Generates all subsets of the given list of size /k/. subsetsOfSize :: [a] -> Int -> [[a]] subsetsOfSize l size = subsetsOfSizeRec l [] size where subsetsOfSizeRec :: [a] -> [a] -> Int -> [[a]] subsetsOfSizeRec _ soFar 0 = [soFar] subsetsOfSizeRec [] _ _ = [] subsetsOfSizeRec (s:src') soFar size = without ++ with where without = subsetsOfSizeRec src' soFar size with = subsetsOfSizeRec src' (s : soFar) (size - 1) -- | Utility function on lists -- counts the number of `a`s in the given list count :: (Eq a) => a -> [a] -> Int count a = length . filter (== a) -- | A constant defined by the game numMissions :: Int numMissions = 5 -- | A constant defined by the game numMissionProposals :: Int numMissionProposals = 5 -- | Given (respectively) the number of players in the game, and which round it is, -- calculates the mission size. These numbers are constants defined by the game. getMissionSize :: Int -> Int -> Int getMissionSize 5 0 = 2 getMissionSize 5 1 = 3 getMissionSize 5 2 = 2 getMissionSize 5 3 = 3 getMissionSize 5 4 = 3 getMissionSize 6 0 = 2 getMissionSize 6 1 = 3 getMissionSize 6 2 = 4 getMissionSize 6 3 = 3 getMissionSize 6 4 = 4 getMissionSize 7 0 = 2 getMissionSize 7 1 = 3 getMissionSize 7 2 = 3 getMissionSize 7 3 = 4 getMissionSize 7 4 = 4 getMissionSize 8 0 = 2 getMissionSize 8 1 = 3 getMissionSize 8 2 = 3 getMissionSize 8 3 = 4 getMissionSize 8 4 = 4 getMissionSize 9 0 = 3 getMissionSize 9 1 = 4 getMissionSize 9 2 = 4 getMissionSize 9 3 = 5 getMissionSize 9 4 = 5 getMissionSize 10 0 = 3 getMissionSize 10 1 = 4 getMissionSize 10 2 = 4 getMissionSize 10 3 = 5 getMissionSize 10 4 = 5 getMissionSize numPlayers roundIndex = error $ "Fatal: illegal (mission size)-round pairing: " ++ (show (numPlayers, roundIndex)) -- | Determines which player starts the mission proposals for round `roundIndex` in a -- game with `numPlayers` many players startingKingIndex :: Int -> Int -> Int startingKingIndex numPlayers roundIndex = roundIndex * numMissions `mod` numPlayers -- | Under the arbitrary team selection meta, determines whether `teamSelection` made by -- king `kingIndex` with the seating arrangement `seating` yields a team of all Good -- (returns False if teamSelection doesn't contain kingIndex) isGoodTeamArbitraryMeta :: Seating -> Int -> [Int] -> Bool isGoodTeamArbitraryMeta seating kingIndex teamSelection | not (kingIndex `elem` teamSelection) = False | otherwise = and . map (seating !!) $ teamSelection -- | Under the two-to-the-left team selection meta, determines whether the team of size -- `missionSize` made by king `kingIndex` with the seating arrangement `seating` yields -- a team of all Good isGoodTeamTwoToLeftMeta :: Seating -> Int -> Int -> Bool isGoodTeamTwoToLeftMeta seating missionSize kingIndex = and . take missionSize . drop kingIndex $ (seating ++ seating) -- | Under the two-to-the-left team selection meta, what how many teams are all Good, -- in round `roundIndex` with seating arrangement `seating` in a game of `numPlayers` -- many people? Note that we calculate a ratio -- this is because different metas will -- have different numbers of possible teams, and we are interested in the percentage -- of good teams selected. Hence, we need the total number of teams considered goodTeamRatioInRoundTwoToLeftMeta :: Int -> Seating -> Int -> GoodTeamRatio goodTeamRatioInRoundTwoToLeftMeta numPlayers seating roundIndex = (\l -> GoodTeamRatio (count True l) (length l)) . map (isGoodTeamTwoToLeftMeta seating (getMissionSize numPlayers roundIndex)) $ [kingIndex .. (kingIndex + numMissionProposals - 1)] -- inclusive => -1 where -- | Which player is the initial king kingIndex :: Int kingIndex = startingKingIndex numPlayers roundIndex -- | Under the arbitrary team selection meta, what how many teams are all Good, -- in round `roundIndex` with seating arrangement `seating` in a game of `numPlayers` -- many people? Note that we calculate a ratio -- this is because different metas will -- have different numbers of possible teams, and we are interested in the percentage -- of good teams selected. Hence, we need the total number of teams considered goodTeamRatioInRoundArbitaryMeta :: Int -> Seating -> Int -> GoodTeamRatio goodTeamRatioInRoundArbitaryMeta numPlayers seating roundIndex = (\l -> GoodTeamRatio (count True l) (length l)) $ (isGoodTeamArbitraryMeta seating) <$> [kingIndex .. (kingIndex + numMissionProposals - 1)] -- inclusive => -1 <*> teamSelections where -- | When evaluating the arbitrary team selection meta, we need to consider all -- possible team selections (as opposed to the two-to-the-left meta, in which -- there is only one possible team selection each time). teamSelections :: [[Int]] teamSelections = subsetsOfSize [0 .. (numPlayers - 1)] (getMissionSize numPlayers roundIndex) -- -1 for 0-indexing -- | Which player is the initial king kingIndex :: Int kingIndex = startingKingIndex numPlayers roundIndex -- | Under the two-to-the-left team selection meta, given seating `seating` in a game -- with `numPlayers` many players, how many teams are good? Note that we calculate a -- ratio -- this is because different metas will have different numbers of possible -- teams, and we are interested in the percentage of good teams selected. Hence, we need -- the total number of teams considered goodTeamRatioTwoToLeftMeta :: Int -> Seating -> GoodTeamRatio goodTeamRatioTwoToLeftMeta numPlayers seating = foldl1 (<>) . map (goodTeamRatioInRoundTwoToLeftMeta numPlayers seating) $ [0 .. (numMissions - 1)] -- | Under the two-to-the-left team selection meta, given seating `seating` in a game -- with `numPlayers` many players, how many teams are good? Note that we calculate a -- ratio -- this is because different metas will have different numbers of possible -- teams, and we are interested in the percentage of good teams selected. Hence, we need -- the total number of teams considered goodTeamRatioArbitaryMeta :: Int -> Seating -> GoodTeamRatio goodTeamRatioArbitaryMeta numPlayers seating = foldl1 (<>) . map (goodTeamRatioInRoundArbitaryMeta numPlayers seating) $ [0 .. (numMissions - 1)] test :: IO () test = do putStrLn "two-to-the-left meta tests" putStrLn "--------------------------" putStr "number of good teams (two-to-the-left meta) 8 (should be 8): " print $ goodTeamRatioTwoToLeftMeta 8 [False, False, False, True, True, True, True, True] putStr "number of good teams (two-to-the-left meta) 9 (should be 8): " print $ goodTeamRatioTwoToLeftMeta 9 [False, False, False, True, True, True, True, True, True] putStr "number of good teams (two-to-the-left meta) 10 (should be 6): " print $ goodTeamRatioTwoToLeftMeta 10 [False, False, False, False, True, True, True, True, True, True] evaluateMetasForNumPlayers :: Int -> IO () evaluateMetasForNumPlayers numPlayers = do let numBad = case numPlayers of { 5 -> 2; 6 -> 2; 7 -> 3; 8 -> 3; 9 -> 3; -- with Mordred 10 -> 4; } let numGood = numPlayers - numBad let allSeatings = L.permutations $ replicate numBad False ++ replicate numGood True -- can discard length of groupings becaues each grouping will be the same -- length (by symmetry) let seatings = map head . L.group . L.sort $ allSeatings putStrLn $ "All possible games with " ++ (show numPlayers) ++ " players, modded out by symmetry:" putStrLn "" putStr "Arbitrary meta: " print $ foldl1 (<>) . map (goodTeamRatioArbitaryMeta numPlayers) $ seatings putStr "Two-to-the-left meta: " print $ foldl1 (<>) . map (goodTeamRatioTwoToLeftMeta numPlayers) $ seatings putStrLn "-------------------------------------------------------------------" main :: IO () main = mapM_ evaluateMetasForNumPlayers [5..10]
bgwines/avalon-meta-comparison
src/Metas.hs
bsd-3-clause
9,315
0
13
1,945
1,932
1,034
898
141
6
module Emission (makeEmissionVec, makePolyMap) where import Prelude hiding (map, elem, product, foldr, zip, (++), length, filter, (!!), iterate, concatMap, all, sum) import Data.Function (on) import Data.List.Stream import Data.Monoid (getAll, All) import Numeric.Container import GenoEquiv import Control.Arrow ((&&&)) import Math.Polynomial import Data.Bits (testBit) import Common import Control.Monad.Reader import qualified Data.Map as Map import Data.Maybe makeEmissionVec :: ModelNode -> ModelR (Vector Double) makeEmissionVec (ModelNode mark alleleData mc) = do sts <- asks states n <- asks nStates phm <- asks phaseMode let the_map = emitMap mark let ep = if '0' `elem` alleleData then constant 1.0 n else fromMaybe (error $ "Bad data!: " ++ alleleData) $ Map.lookup alleleData the_map let rawVec = case phm of Phased -> ep Unphased mat -> mat <> ep return $ maybe rawVec (mul rawVec . deBool) mc -- | Creates a lookup map for SNP genotype strings whose entries are lists -- of Poly, corresponding to an emission vector (takes an error rate and -- length of the data vectors ) makePolyMap :: Double -> Int -> Map.Map String [Poly Double] makePolyMap e n = Map.fromList $ map poly_list (allAlleleData n) where poly_list str = (str, map (getPoly e str) (allStates n)) -- | Poly of a string and an IBD state given error rate, as a function of allele frequency getPoly :: Double -> String -> IbdState -> Poly Double getPoly e str state = foldl1' multPoly $ collapseOnLabel (classPoly e) state str -- | Poly for a string given error rate, as a function of allele frequency classPoly :: Double -> String -> Poly Double classPoly e xs = scalePoly (pr (1-e)) x `addPoly` scalePoly (pr e) (poly LE [1, -1]) where pr p = (p ^ k) * ((1 - p) ^ (n - k)) n = length xs k = (length . filter (=='1')) xs -- group values into lists by label, then apply a function to each list collapseOnLabel :: Ord k => ([a] -> b) -> [k] -> [a] -> [b] collapseOnLabel f labels values = map f (Map.elems $ groupOnLabel labels values) -- given e error and p0 prob the true class allele is 0, prob of a string of 1's and 2's classProb :: Double -> Double -> String -> Double classProb e p0 xs = p0 * pr (1-e) + (1-p0) * pr e where pr p = (p ^ k) * ((1 - p) ^ (n - k)) n = length xs k = (length . filter (=='1')) xs allAlleleData n = (!!(n-1)) $ iterate (concatMap f) ["1","2"] where f xs = map (:xs) "12" deBool :: Constraint -> Vector Double deBool (Constraint x) = buildVector magicFifteen (\ i -> if testBit x i then 1 else 0)
cglazner/ibd_stitch
src/Emission.hs
bsd-3-clause
2,726
0
15
675
948
508
440
48
3
module Jade.Decode.Val ( getName , hasIdent , isLit , getIndexedName ) where import Jade.Decode.Types getName (ValIndex n _) = n getName (Lit _) = "" -- this is also no good. this should be a Maybe String. getIndexedName (ValIndex n idx) = n ++ show idx getIndexedName (Lit _) = "" -- this is no good. hasIdent (ValIndex n _) ident = n == ident hasIdent _ _ = False isLit (Lit _) = True isLit _ = False
drhodes/jade2hdl
jade-decode/src/Jade/Decode/Val.hs
bsd-3-clause
501
0
7
177
150
80
70
13
1
-- | -- Module : Control.Optimization.Bits -- License : BSD3 -- Copyright: [2015..2015] Michael Vollmer, Bo Joel Svensson -- Maintainer : Michael Vollmer <[email protected]> -- -- module Control.Optimization.Bits where
vollmerm/comb-opt-hs
Control/Optimization/Bits.hs
bsd-3-clause
224
0
3
31
14
12
2
1
0
----------------------------------------------------------------------------- -- | -- Module : Berp.Base.StdTypes.Dictionary -- Copyright : (c) 2010 Bernie Pope -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : ghc -- -- The standard dictionary type. -- ----------------------------------------------------------------------------- module Berp.Base.StdTypes.Dictionary (emptyDictionary, dictionary, dictionaryClass) where import Data.List (intersperse) import Berp.Base.Prims (primitive, showObject, raise) import Berp.Base.Monad (constantIO) import Berp.Base.SemanticTypes (Procedure, Object (..), Eval) import Berp.Base.Identity (newIdentity) import Berp.Base.HashTable as Hash (fromList, empty, mappings, lookup) import Berp.Base.Attributes (mkAttributesList) import {-# SOURCE #-} Berp.Base.Builtins.Exceptions (keyError) import Berp.Base.StdNames import {-# SOURCE #-} Berp.Base.StdTypes.Type (newType) import Berp.Base.StdTypes.ObjectBase (objectBase) import Berp.Base.StdTypes.String (string) emptyDictionary :: IO Object emptyDictionary = do identity <- newIdentity hashTable <- Hash.empty return $ Dictionary { object_identity = identity , object_hashTable = hashTable } dictionary :: [(Object, Object)] -> Eval Object dictionary elements = do identity <- newIdentity hashTable <- fromList elements return $ Dictionary { object_identity = identity , object_hashTable = hashTable } {-# NOINLINE dictionaryClass #-} dictionaryClass :: Object dictionaryClass = constantIO $ do dict <- attributes newType [string "dict", objectBase, dict] attributes :: IO Object attributes = mkAttributesList [ (specialEqName, primitive 2 eq) , (specialStrName, primitive 1 str) , (specialGetItemName, primitive 2 getItem) ] eq :: Procedure eq = error "== on dict not defined" str :: Procedure str (obj:_) = do ms <- mappings $ object_hashTable obj strs <- mapM dictEntryString ms return $ string ("{" ++ concat (intersperse ", " strs) ++ "}") where dictEntryString :: (Object, Object) -> Eval String dictEntryString (obj1, obj2) = do objStr1 <- showObject obj1 objStr2 <- showObject obj2 return (objStr1 ++ ": " ++ objStr2) str _other = error "str conversion on dictionary applied to wrong number of arguments" getItem :: Procedure getItem (obj:index:_) = do let ht = object_hashTable obj maybeVal <- Hash.lookup index ht case maybeVal of Nothing -> raise keyError Just val -> return val getItem _other = error "getItem on dictionary applied to wrong number of arguments"
bjpop/berp
libs/src/Berp/Base/StdTypes/Dictionary.hs
bsd-3-clause
2,688
0
14
489
667
369
298
60
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE UnicodeSyntax #-} {-| [@ISO639-1@] - [@ISO639-2@] - [@ISO639-3@] zpl [@Native name@] East Sola de Vega Zapotec [@English name@] Lachixío Zapotec -} module Text.Numeral.Language.ZPL.TestData (cardinals) where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- import "base" Prelude ( Num ) import "numerals" Text.Numeral.Grammar.Reified ( defaultInflection ) import "this" Text.Numeral.Test ( TestData ) -------------------------------------------------------------------------------- -- Test data -------------------------------------------------------------------------------- {- Sources: http://www.languagesandnumbers.com/how-to-count-in-lachixio-zapotec/en/zpl/ -} cardinals ∷ (Num i) ⇒ TestData i cardinals = [ ( "default" , defaultInflection , [ (1, "tucu") , (2, "chiucu") , (3, "chuna") , (4, "tacu") , (5, "ayu’") , (6, "xu’cu") , (7, "achi") , (8, "xunu") , (9, "quie’") , (10, "chi’i") , (11, "chi’i tucu") , (12, "chi’i chiucu") , (13, "chi’i chuna") , (14, "chi’i tacu") , (15, "chi’i ayu’") , (16, "chi’i xu’cu") , (17, "chi’i achi") , (18, "chi’i xunu") , (19, "chi’i quie’") , (20, "ala") , (21, "ala tucu") , (22, "ala chiucu") , (23, "ala chuna") , (24, "ala tacu") , (25, "ala ayu’") , (26, "ala xu’cu") , (27, "ala achi") , (28, "ala xunu") , (29, "ala quie’") , (30, "ala llichi’i") , (31, "ala llichi’i tucu") , (32, "ala llichi’i chiucu") , (33, "ala llichi’i chuna") , (34, "ala llichi’i tacu") , (35, "ala llichi’i ayu’") , (36, "ala llichi’i xu’cu") , (37, "ala llichi’i achi") , (38, "ala llichi’i xunu") , (39, "ala llichi’i quie’") , (40, "chiu’a") , (41, "chiu’a tucu") , (42, "chiu’a chiucu") , (43, "chiu’a chuna") , (44, "chiu’a tacu") , (45, "chiu’a ayu’") , (46, "chiu’a xu’cu") , (47, "chiu’a achi") , (48, "chiu’a xunu") , (49, "chiu’a quie’") , (50, "chiu’a nu’ chi’i") , (51, "chiu’a nu’ chi’i tucu") , (52, "chiu’a nu’ chi’i chiucu") , (53, "chiu’a nu’ chi’i chuna") , (54, "chiu’a nu’ chi’i tacu") , (55, "chiu’a nu’ chi’i ayu’") , (56, "chiu’a nu’ chi’i xu’cu") , (57, "chiu’a nu’ chi’i achi") , (58, "chiu’a nu’ chi’i xunu") , (59, "chiu’a nu’ chi’i quie’") , (60, "ayuna") , (61, "ayuna tucu") , (62, "ayuna chiucu") , (63, "ayuna chuna") , (64, "ayuna tacu") , (65, "ayuna ayu’") , (66, "ayuna xu’cu") , (67, "ayuna achi") , (68, "ayuna xunu") , (69, "ayuna quie’") , (70, "ayuna nu’ chi’i") , (71, "ayuna nu’ chi’i tucu") , (72, "ayuna nu’ chi’i chiucu") , (73, "ayuna nu’ chi’i chuna") , (74, "ayuna nu’ chi’i tacu") , (75, "ayuna nu’ chi’i ayu’") , (76, "ayuna nu’ chi’i xu’cu") , (77, "ayuna nu’ chi’i achi") , (78, "ayuna nu’ chi’i xunu") , (79, "ayuna nu’ chi’i quie’") , (80, "tacu nu’ ala") , (81, "tacu nu’ ala tucu") , (82, "tacu nu’ ala chiucu") , (83, "tacu nu’ ala chuna") , (84, "tacu nu’ ala tacu") , (85, "tacu nu’ ala ayu’") , (86, "tacu nu’ ala xu’cu") , (87, "tacu nu’ ala achi") , (88, "tacu nu’ ala xunu") , (89, "tacu nu’ ala quie’") , (90, "chuna ala lli chi’i") , (91, "chuna ala lli chi’i tucu") , (92, "chuna ala lli chi’i chiucu") , (93, "chuna ala lli chi’i chuna") , (94, "chuna ala lli chi’i tacu") , (95, "chuna ala lli chi’i ayu’") , (96, "chuna ala lli chi’i xu’cu") , (97, "chuna ala lli chi’i achi") , (98, "chuna ala lli chi’i xunu") , (99, "chuna ala lli chi’i quie’") , (100, "tucu ayu’u") , (101, "tucu ayu’u tucu") , (102, "tucu ayu’u chiucu") , (103, "tucu ayu’u chuna") , (104, "tucu ayu’u tacu") , (105, "tucu ayu’u ayu’") , (106, "tucu ayu’u xu’cu") , (107, "tucu ayu’u achi") , (108, "tucu ayu’u xunu") , (109, "tucu ayu’u quie’") , (110, "tucu ayu’u chi’i") , (123, "tucu ayu’u ala chuna") , (200, "chiucu ayu’u") , (300, "chuna ayu’u") , (321, "chuna ayu’u ala tucu") , (400, "tacu ayu’u") , (500, "ayu’ ayu’u") , (600, "xu’cu ayu’u") , (700, "achi ayu’u") , (800, "xunu ayu’u") , (900, "quie’ ayu’u") , (909, "quie’ ayu’u quie’") , (990, "quie’ ayu’u chuna ala lli chi’i") , (999, "quie’ ayu’u chuna ala lli chi’i quie’") ] ) ]
telser/numerals
src-test/Text/Numeral/Language/ZPL/TestData.hs
bsd-3-clause
5,302
0
8
1,489
1,201
803
398
135
1
{-# OPTIONS_GHC -Wall #-} module Reporting.Error.Type where import qualified Data.Char as Char import Text.PrettyPrint ((<+>)) import qualified Text.PrettyPrint as P import qualified AST.Helpers as Help import qualified AST.Type as Type import qualified AST.Variable as Var import qualified Reporting.PrettyPrint as P import qualified Reporting.Region as Region import qualified Reporting.Report as Report data Error = Mismatch Mismatch | InfiniteType InfiniteType | BadMain Type.Canonical data Mismatch = MismatchInfo { _hint :: Hint , _leftType :: Type.Canonical , _rightType :: Type.Canonical , _note :: Maybe String } data InfiniteType = InfiniteTypeInfo { _name :: String , _var :: Type.Canonical , _type :: Type.Canonical } data Hint = CaseBranch Int Region.Region | Case | IfBranches | MultiIfBranch Int Region.Region | If | List | ListElement Int Region.Region | BinopLeft Var.Canonical Region.Region | BinopRight Var.Canonical Region.Region | Binop Var.Canonical | Function (Maybe Var.Canonical) | UnexpectedArg (Maybe Var.Canonical) Int Region.Region | FunctionArity (Maybe Var.Canonical) Int Int Region.Region | BadTypeAnnotation String | Instance String | Literal String | Pattern Pattern | Shader | Range | Lambda | Record data Pattern = PVar String | PAlias String | PData String | PRecord -- TO REPORT toReport :: P.Dealiaser -> Error -> Report.Report toReport dealiaser err = case err of Mismatch (MismatchInfo hint leftType rightType note) -> let (subRegion, preHint, maybePostHint) = hintToString hint postHint = maybe "" (++"\n\n") note ++ maybe "" (++"\n\n") maybePostHint ++ "As I infer the types of values flowing through your program, I see a conflict\n" ++ "between these two types:\n\n" ++ P.render (P.nest 4 (P.pretty dealiaser False leftType)) ++ "\n\n" ++ P.render (P.nest 4 (P.pretty dealiaser False rightType)) in Report.Report "TYPE MISMATCH" subRegion preHint postHint InfiniteType (InfiniteTypeInfo name var tipe) -> let prettyVar = P.pretty dealiaser False var prettyType = P.pretty dealiaser False tipe in Report.simple "INFINITE TYPE" ( "I am inferring weird self-referential type for `" ++ name ++ "`" ) ( "The bit of the type that is self-referential looks like this:\n\n" ++ P.render (P.nest 4 (prettyVar <+> P.equals <+> prettyType)) ++ "\n\nThe cause is often that the usage of `" ++ name ++ "` is flipped around.\n\n" ++ "Maybe you are inserting a data structure into an element? Maybe you are giving\n" ++ "a function to an argument? Either way, something is probably backwards!\n\n" ++ "Try breaking the code related to `" ++ name ++ "` into smaller pieces.\n" ++ "Give each piece a name and try to write down its type." ) BadMain tipe -> Report.simple "BAD MAIN TYPE" "The 'main' value has an unsupported type." $ "I need an Element, Html, (Signal Element), or (Signal Html) so I can render it\n" ++ "on screen, but you gave me:\n\n" ++ P.render (P.nest 4 (P.pretty dealiaser False tipe)) hintToString :: Hint -> (Maybe Region.Region, String, Maybe String) hintToString hint = case hint of CaseBranch branchNumber region -> ( Just region , "The " ++ ordinalize branchNumber ++ " branch of this `case` results in an unexpected type of value." , Just "All branches should match so that no matter which one we take, we always get\nback the same type of value." ) Case -> ( Nothing , "All the branches of this case-expression are consistent, but the overall\n" ++ "type does not match how it is used elsewhere." , Nothing ) IfBranches -> ( Nothing , "The branches of this `if` result in different types of values." , Just "All branches should match so that no matter which one we take, we always get\nback the same type of value." ) MultiIfBranch branchNumber region -> ( Just region , "The " ++ ordinalize branchNumber ++ " branch of this `if` results in an unexpected type of value." , Just "All branches should match so that no matter which one we take, we always get\nback the same type of value." ) If -> ( Nothing , "All the branches of this if-expression are consistent, but the overall\n" ++ "type does not match how it is used elsewhere." , Nothing ) ListElement elementNumber region -> ( Just region , "The " ++ ordinalize elementNumber ++ " element of this list is an unexpected type of value." , Just "All elements should be the same type of value so that we can iterate over the\nlist without running into unexpected values." ) List -> ( Nothing , "All the elements in this list are the same type, but the overall\n" ++ "type does not match how it is used elsewhere." , Nothing ) BinopLeft op region -> ( Just region , "The left argument of " ++ prettyOperator op ++ " is causing a type mismatch." , Nothing ) BinopRight op region -> ( Just region , "The right argument of " ++ prettyOperator op ++ " is causing a type mismatch." , Nothing ) Binop op -> ( Nothing , "The two arguments to " ++ prettyOperator op ++ " are fine, but the overall type of this expression\n" ++ "does not match how it is used elsewhere." , Nothing ) Function maybeName -> ( Nothing , "The return type of " ++ funcName maybeName ++ " is being used in unexpected ways." , Nothing ) UnexpectedArg maybeName index region -> ( Just region , "The " ++ ordinalize index ++ " argument to " ++ funcName maybeName ++ " has an unexpected type." , Nothing ) FunctionArity maybeName expected actual region -> let s = if expected <= 1 then "" else "s" in ( Just region , capitalize (funcName maybeName) ++ " is expecting " ++ show expected ++ " argument" ++ s ++ ", but was given " ++ show actual ++ "." , Nothing ) BadTypeAnnotation name -> ( Nothing , "The type annotation for `" ++ name ++ "` does not match its definition." , Nothing ) Instance name -> ( Nothing , "Given how `" ++ name ++ "` is defined, this use will not work out." , Nothing ) Literal name -> ( Nothing , "This " ++ name ++ " value is being used as if it is some other type of value." , Nothing ) Pattern patErr -> let thing = case patErr of PVar name -> "variable `" ++ name ++ "`" PAlias name -> "alias `" ++ name ++ "`" PData name -> "`" ++ name ++ "`" PRecord -> "a record" in ( Nothing , "Problem with " ++ thing ++ " in this pattern match." , Nothing ) Shader -> ( Nothing , "There is some problem with this GLSL shader." , Nothing ) Range -> ( Nothing , "The low and high members of this list range are not the same type of value." , Nothing ) Lambda -> ( Nothing , "This anonymous function is being used in an unexpected way." , Nothing ) Record -> ( Nothing , "This record is being used in an unexpected way." , Nothing ) prettyOperator :: Var.Canonical -> String prettyOperator (Var.Canonical _ opName) = if Help.isOp opName then "(" ++ opName ++ ")" else "`" ++ opName ++ "`" funcName :: Maybe Var.Canonical -> String funcName maybeVar = case maybeVar of Nothing -> "this function" Just var -> "function " ++ prettyOperator var capitalize :: String -> String capitalize string = case string of [] -> [] c : cs -> Char.toUpper c : cs ordinalize :: Int -> String ordinalize number = let remainder10 = number `mod` 10 remainder100 = number `mod` 100 ending | remainder100 `elem` [11..13] = "th" | remainder10 == 1 = "st" | remainder10 == 2 = "nd" | remainder10 == 3 = "rd" | otherwise = "th" in show number ++ ending
MaxGabriel/elm-compiler
src/Reporting/Error/Type.hs
bsd-3-clause
8,898
0
28
2,948
1,755
931
824
220
25
module Codex.Lib.Game.Player ( Player (..), PlayerType (..), HumanT (..), ComputerT (..) ) where import Codex.Lib.Science.Gender (Gender (..)) import Codex.Lib.Game.Match (Stats (..)) data Player a = Player { _id :: Int, _type :: PlayerType, _stats :: Stats, _history :: [a] } deriving (Show, Read, Eq) data PlayerType = Human HumanT | Computer ComputerT deriving (Show, Read, Eq) data HumanT = HumanT { _nickName :: String, _gender :: Gender } deriving (Show, Read, Eq) data ComputerT = ComputerT { _nodeName :: String } deriving (Show, Read, Eq)
adarqui/Codex
src/Codex/Lib/Game/Player.hs
bsd-3-clause
569
0
9
106
217
135
82
25
0
module System.Build ( module System.Build.Access , module System.Build.Compile , module System.Build.Data , module System.Build.Java ) where import System.Build.Access import System.Build.Compile import System.Build.Data import System.Build.Java
tonymorris/lastik
System/Build.hs
bsd-3-clause
249
0
5
27
60
41
19
10
0
{-# LANGUAGE ConstraintKinds #-} -- | Common internal things (no other internal deps) module Analyze.Common where import Control.Exception import Control.Monad (forM_, unless) import Control.Monad.Catch (MonadThrow (..)) import Data.Hashable (Hashable) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HM import Data.HashSet (HashSet) import qualified Data.HashSet as HS import Data.Typeable (Typeable) import Data.Vector (Vector) import qualified Data.Vector as V -- | Column keys need to have equality and hashability. type Data k = (Eq k, Hashable k, Show k, Typeable k) -- | flip <$> (<&>) :: Functor f => f a -> (a -> b) -> f b (<&>) x f = f <$> x {-# INLINE (<&>) #-} infixl 1 <&> -- | Exception for when a column is missing from a frame. data MissingKeyError k = MissingKeyError k deriving (Show, Eq, Typeable) instance (Show k, Typeable k) => Exception (MissingKeyError k) -- | Exception for when a column is duplicated in a frame. data DuplicateKeyError k = DuplicateKeyError k deriving (Show, Eq, Typeable) instance (Show k, Typeable k) => Exception (DuplicateKeyError k) -- | Exception for when frame column sizes don't match. data ColSizeMismatch = ColSizeMismatch Int Int deriving (Show, Eq, Typeable) instance Exception ColSizeMismatch -- | Exception for when frame row sizes don't match. data RowSizeMismatch = RowSizeMismatch Int Int deriving (Show, Eq, Typeable) instance Exception RowSizeMismatch -- | Throws when duplicate keys are present in a vector. checkForDupes :: (Data k, MonadThrow m) => Vector k -> m () checkForDupes vs = go HS.empty (V.toList vs) where go _ [] = pure () go s (k:ks) = if HS.member k s then throwM (DuplicateKeyError k) else go (HS.insert k s) ks -- | Throws when one vector is not a reordering of the other. checkReorder :: (Data k, MonadThrow m) => Vector k -> Vector k -> m () checkReorder xs ys = let xSize = V.length xs ySize = V.length ys in if xSize /= ySize then throwM (ColSizeMismatch xSize ySize) else checkSubset (V.toList xs) (HS.fromList (V.toList ys)) -- | Throws when any key is not present in the set. checkSubset :: (Data k, MonadThrow m) => [k] -> HashSet k -> m () checkSubset qs ks = forM_ qs (\q -> unless (HS.member q ks) (throwM (MissingKeyError q))) -- | Builds a reverse lookup for the vector. makeLookup :: Data k => Vector k -> HashMap k Int makeLookup = HM.fromList . flip zip [0..] . V.toList -- | Indexes into the vector of values, throwing on key missing or bad index. runLookup :: (Data k, MonadThrow m) => HashMap k Int -> Vector v -> k -> m v runLookup look vs k = case HM.lookup k look >>= (vs V.!?) of Nothing -> throwM (MissingKeyError k) Just v -> pure v -- | Reorders the vector of values by a new key order and an old lookup. reorder :: Data k => Vector k -> HashMap k Int -> Vector v -> Vector v reorder ks look vs = pick <$> ks where pick k = vs V.! (look HM.! k) -- | Merges two key vectors and tags each with its provenance (favoring the second). mergeKeys :: Data k => Vector k -> Vector k -> Vector (k, Int, Int) mergeKeys xs ys = let m = HM.fromList (V.toList (V.imap (\i x -> (x, (0, i))) xs)) n = HM.fromList (V.toList (V.imap (\i x -> (x, (1, i))) ys)) -- Ties go to the first argument, in this case favoring the update o = HM.union n m p = (\x -> let (a, b) = o HM.! x in (x, a, b)) <$> xs q = (\x -> let (a, b) = n HM.! x in (x, a, b)) <$> V.filter (\x -> not (HM.member x m)) ys in p V.++ q -- | Uses a merged key vector to select values. runIndexedLookup :: Vector (k, Int, Int) -> Vector v -> Vector v -> Vector v runIndexedLookup ks xs ys = (\(k, i, j) -> (if i == 0 then xs else ys) V.! j) <$> ks
ejconlon/analyze
src/Analyze/Common.hs
bsd-3-clause
3,874
0
17
920
1,361
724
637
62
3
----------------------------------------------------------------------------- -- -- Code generation for foreign calls. -- -- (c) The University of Glasgow 2004-2006 -- ----------------------------------------------------------------------------- module StgCmmForeign ( cgForeignCall, loadThreadState, saveThreadState, emitPrimCall, emitCCall, emitSaveThreadState, -- will be needed by the Cmm parser emitLoadThreadState, -- ditto emitOpenNursery, ) where #include "HsVersions.h" import StgSyn import StgCmmProf import StgCmmEnv import StgCmmMonad import StgCmmUtils import StgCmmClosure import StgCmmLayout import BlockId import Cmm import CmmUtils import OldCmm ( CmmReturnInfo(..) ) import MkGraph import Type import TysPrim import CLabel import SMRep import ForeignCall import Constants import DynFlags import Maybes import Outputable import BasicTypes import Control.Monad import Prelude hiding( succ ) ----------------------------------------------------------------------------- -- Code generation for Foreign Calls ----------------------------------------------------------------------------- -- | emit code for a foreign call, and return the results to the sequel. -- cgForeignCall :: ForeignCall -- the op -> [StgArg] -- x,y arguments -> Type -- result type -> FCode ReturnKind cgForeignCall (CCall (CCallSpec target cconv safety)) stg_args res_ty = do { cmm_args <- getFCallArgs stg_args ; (res_regs, res_hints) <- newUnboxedTupleRegs res_ty ; let ((call_args, arg_hints), cmm_target) = case target of StaticTarget _ _ False -> panic "cgForeignCall: unexpected FFI value import" StaticTarget lbl mPkgId True -> let labelSource = case mPkgId of Nothing -> ForeignLabelInThisPackage Just pkgId -> ForeignLabelInPackage pkgId size = call_size cmm_args in ( unzip cmm_args , CmmLit (CmmLabel (mkForeignLabel lbl size labelSource IsFunction))) DynamicTarget -> case cmm_args of (fn,_):rest -> (unzip rest, fn) [] -> panic "cgForeignCall []" fc = ForeignConvention cconv arg_hints res_hints call_target = ForeignTarget cmm_target fc -- we want to emit code for the call, and then emitReturn. -- However, if the sequel is AssignTo, we shortcut a little -- and generate a foreign call that assigns the results -- directly. Otherwise we end up generating a bunch of -- useless "r = r" assignments, which are not merely annoying: -- they prevent the common block elimination from working correctly -- in the case of a safe foreign call. -- See Note [safe foreign call convention] -- ; sequel <- getSequel ; case sequel of AssignTo assign_to_these _ -> emitForeignCall safety assign_to_these call_target call_args CmmMayReturn _something_else -> do { _ <- emitForeignCall safety res_regs call_target call_args CmmMayReturn ; emitReturn (map (CmmReg . CmmLocal) res_regs) } } where -- in the stdcall calling convention, the symbol needs @size appended -- to it, where size is the total number of bytes of arguments. We -- attach this info to the CLabel here, and the CLabel pretty printer -- will generate the suffix when the label is printed. call_size args | StdCallConv <- cconv = Just (sum (map arg_size args)) | otherwise = Nothing -- ToDo: this might not be correct for 64-bit API arg_size (arg, _) = max (widthInBytes $ typeWidth $ cmmExprType arg) wORD_SIZE {- Note [safe foreign call convention] The simple thing to do for a safe foreign call would be the same as an unsafe one: just emitForeignCall ... emitReturn ... but consider what happens in this case case foo x y z of (# s, r #) -> ... The sequel is AssignTo [r]. The call to newUnboxedTupleRegs picks [r] as the result reg, and we generate r = foo(x,y,z) returns to L1 -- emitForeignCall L1: r = r -- emitReturn goto L2 L2: ... Now L1 is a proc point (by definition, it is the continuation of the safe foreign call). If L2 does a heap check, then L2 will also be a proc point. Furthermore, the stack layout algorithm has to arrange to save r somewhere between the call and the jump to L1, which is annoying: we would have to treat r differently from the other live variables, which have to be saved *before* the call. So we adopt a special convention for safe foreign calls: the results are copied out according to the NativeReturn convention by the call, and the continuation of the call should copyIn the results. (The copyOut code is actually inserted when the safe foreign call is lowered later). The result regs attached to the safe foreign call are only used temporarily to hold the results before they are copied out. We will now generate this: r = foo(x,y,z) returns to L1 L1: r = R1 -- copyIn, inserted by mkSafeCall goto L2 L2: ... r ... And when the safe foreign call is lowered later (see Note [lower safe foreign calls]) we get this: suspendThread() r = foo(x,y,z) resumeThread() R1 = r -- copyOut, inserted by lowerSafeForeignCall jump L1 L1: r = R1 -- copyIn, inserted by mkSafeCall goto L2 L2: ... r ... Now consider what happens if L2 does a heap check: the Adams optimisation kicks in and commons up L1 with the heap-check continuation, resulting in just one proc point instead of two. Yay! -} emitCCall :: [(CmmFormal,ForeignHint)] -> CmmExpr -> [(CmmActual,ForeignHint)] -> FCode () emitCCall hinted_results fn hinted_args = void $ emitForeignCall PlayRisky results target args CmmMayReturn where (args, arg_hints) = unzip hinted_args (results, result_hints) = unzip hinted_results target = ForeignTarget fn fc fc = ForeignConvention CCallConv arg_hints result_hints emitPrimCall :: [CmmFormal] -> CallishMachOp -> [CmmActual] -> FCode () emitPrimCall res op args = void $ emitForeignCall PlayRisky res (PrimTarget op) args CmmMayReturn -- alternative entry point, used by CmmParse emitForeignCall :: Safety -> [CmmFormal] -- where to put the results -> ForeignTarget -- the op -> [CmmActual] -- arguments -> CmmReturnInfo -- This can say "never returns" -- only RTS procedures do this -> FCode ReturnKind emitForeignCall safety results target args _ret | not (playSafe safety) = do dflags <- getDynFlags let (caller_save, caller_load) = callerSaveVolatileRegs dflags emit caller_save emit $ mkUnsafeCall target results args emit caller_load return AssignedDirectly | otherwise = do dflags <- getDynFlags updfr_off <- getUpdFrameOff temp_target <- load_target_into_temp target k <- newLabelC let (off, copyout) = copyInOflow dflags NativeReturn (Young k) results -- see Note [safe foreign call convention] emit $ ( mkStore (CmmStackSlot (Young k) (widthInBytes wordWidth)) (CmmLit (CmmBlock k)) <*> mkLast (CmmForeignCall { tgt = temp_target , res = results , args = args , succ = k , updfr = updfr_off , intrbl = playInterruptible safety }) <*> mkLabel k <*> copyout ) return (ReturnedTo k off) {- -- THINK ABOUT THIS (used to happen) -- we might need to load arguments into temporaries before -- making the call, because certain global registers might -- overlap with registers that the C calling convention uses -- for passing arguments. -- -- This is a HACK; really it should be done in the back end, but -- it's easier to generate the temporaries here. load_args_into_temps = mapM arg_assign_temp where arg_assign_temp (e,hint) = do tmp <- maybe_assign_temp e return (tmp,hint) -} load_target_into_temp :: ForeignTarget -> FCode ForeignTarget load_target_into_temp (ForeignTarget expr conv) = do tmp <- maybe_assign_temp expr return (ForeignTarget tmp conv) load_target_into_temp other_target@(PrimTarget _) = return other_target maybe_assign_temp :: CmmExpr -> FCode CmmExpr maybe_assign_temp e | hasNoGlobalRegs e = return e | otherwise = do -- don't use assignTemp, it uses its own notion of "trivial" -- expressions, which are wrong here. -- this is a NonPtr because it only duplicates an existing reg <- newTemp (cmmExprType e) --TODO FIXME NOW emitAssign (CmmLocal reg) e return (CmmReg (CmmLocal reg)) -- ----------------------------------------------------------------------------- -- Save/restore the thread state in the TSO -- This stuff can't be done in suspendThread/resumeThread, because it -- refers to global registers which aren't available in the C world. saveThreadState :: DynFlags -> CmmAGraph saveThreadState dflags = -- CurrentTSO->stackobj->sp = Sp; mkStore (cmmOffset (CmmLoad (cmmOffset stgCurrentTSO (tso_stackobj dflags)) bWord) (stack_SP dflags)) stgSp <*> closeNursery -- and save the current cost centre stack in the TSO when profiling: <*> if dopt Opt_SccProfilingOn dflags then mkStore (cmmOffset stgCurrentTSO (tso_CCCS dflags)) curCCS else mkNop emitSaveThreadState :: BlockId -> FCode () emitSaveThreadState bid = do dflags <- getDynFlags -- CurrentTSO->stackobj->sp = Sp; emitStore (cmmOffset (CmmLoad (cmmOffset stgCurrentTSO (tso_stackobj dflags)) bWord) (stack_SP dflags)) (CmmStackSlot (Young bid) (widthInBytes (typeWidth gcWord))) emit closeNursery -- and save the current cost centre stack in the TSO when profiling: when (dopt Opt_SccProfilingOn dflags) $ emitStore (cmmOffset stgCurrentTSO (tso_CCCS dflags)) curCCS -- CurrentNursery->free = Hp+1; closeNursery :: CmmAGraph closeNursery = mkStore nursery_bdescr_free (cmmOffsetW stgHp 1) loadThreadState :: DynFlags -> LocalReg -> LocalReg -> CmmAGraph loadThreadState dflags tso stack = do -- tso <- newTemp gcWord -- TODO FIXME NOW -- stack <- newTemp gcWord -- TODO FIXME NOW catAGraphs [ -- tso = CurrentTSO; mkAssign (CmmLocal tso) stgCurrentTSO, -- stack = tso->stackobj; mkAssign (CmmLocal stack) (CmmLoad (cmmOffset (CmmReg (CmmLocal tso)) (tso_stackobj dflags)) bWord), -- Sp = stack->sp; mkAssign sp (CmmLoad (cmmOffset (CmmReg (CmmLocal stack)) (stack_SP dflags)) bWord), -- SpLim = stack->stack + RESERVED_STACK_WORDS; mkAssign spLim (cmmOffsetW (cmmOffset (CmmReg (CmmLocal stack)) (stack_STACK dflags)) rESERVED_STACK_WORDS), openNursery, -- and load the current cost centre stack from the TSO when profiling: if dopt Opt_SccProfilingOn dflags then storeCurCCS (CmmLoad (cmmOffset (CmmReg (CmmLocal tso)) (tso_CCCS dflags)) ccsType) else mkNop] emitLoadThreadState :: LocalReg -> LocalReg -> FCode () emitLoadThreadState tso stack = do dflags <- getDynFlags emit $ loadThreadState dflags tso stack openNursery :: CmmAGraph openNursery = catAGraphs [ -- Hp = CurrentNursery->free - 1; mkAssign hp (cmmOffsetW (CmmLoad nursery_bdescr_free bWord) (-1)), -- HpLim = CurrentNursery->start + -- CurrentNursery->blocks*BLOCK_SIZE_W - 1; mkAssign hpLim (cmmOffsetExpr (CmmLoad nursery_bdescr_start bWord) (cmmOffset (CmmMachOp mo_wordMul [ CmmMachOp (MO_SS_Conv W32 wordWidth) [CmmLoad nursery_bdescr_blocks b32], CmmLit (mkIntCLit bLOCK_SIZE) ]) (-1) ) ) ] emitOpenNursery :: FCode () emitOpenNursery = emit openNursery nursery_bdescr_free, nursery_bdescr_start, nursery_bdescr_blocks :: CmmExpr nursery_bdescr_free = cmmOffset stgCurrentNursery oFFSET_bdescr_free nursery_bdescr_start = cmmOffset stgCurrentNursery oFFSET_bdescr_start nursery_bdescr_blocks = cmmOffset stgCurrentNursery oFFSET_bdescr_blocks tso_stackobj, tso_CCCS, stack_STACK, stack_SP :: DynFlags -> ByteOff tso_stackobj dflags = closureField dflags oFFSET_StgTSO_stackobj tso_CCCS dflags = closureField dflags oFFSET_StgTSO_cccs stack_STACK dflags = closureField dflags oFFSET_StgStack_stack stack_SP dflags = closureField dflags oFFSET_StgStack_sp closureField :: DynFlags -> ByteOff -> ByteOff closureField dflags off = off + fixedHdrSize dflags * wORD_SIZE stgSp, stgHp, stgCurrentTSO, stgCurrentNursery :: CmmExpr stgSp = CmmReg sp stgHp = CmmReg hp stgCurrentTSO = CmmReg currentTSO stgCurrentNursery = CmmReg currentNursery sp, spLim, hp, hpLim, currentTSO, currentNursery :: CmmReg sp = CmmGlobal Sp spLim = CmmGlobal SpLim hp = CmmGlobal Hp hpLim = CmmGlobal HpLim currentTSO = CmmGlobal CurrentTSO currentNursery = CmmGlobal CurrentNursery -- ----------------------------------------------------------------------------- -- For certain types passed to foreign calls, we adjust the actual -- value passed to the call. For ByteArray#/Array# we pass the -- address of the actual array, not the address of the heap object. getFCallArgs :: [StgArg] -> FCode [(CmmExpr, ForeignHint)] -- (a) Drop void args -- (b) Add foreign-call shim code -- It's (b) that makes this differ from getNonVoidArgAmodes getFCallArgs args = do { mb_cmms <- mapM get args ; return (catMaybes mb_cmms) } where get arg | isVoidRep arg_rep = return Nothing | otherwise = do { cmm <- getArgAmode (NonVoid arg) ; dflags <- getDynFlags ; return (Just (add_shim dflags arg_ty cmm, hint)) } where arg_ty = stgArgType arg arg_rep = typePrimRep arg_ty hint = typeForeignHint arg_ty add_shim :: DynFlags -> Type -> CmmExpr -> CmmExpr add_shim dflags arg_ty expr | tycon == arrayPrimTyCon || tycon == mutableArrayPrimTyCon = cmmOffsetB expr (arrPtrsHdrSize dflags) | tycon == byteArrayPrimTyCon || tycon == mutableByteArrayPrimTyCon = cmmOffsetB expr (arrWordsHdrSize dflags) | otherwise = expr where UnaryRep rep_ty = repType arg_ty tycon = tyConAppTyCon rep_ty -- should be a tycon app, since this is a foreign call
nomeata/ghc
compiler/codeGen/StgCmmForeign.hs
bsd-3-clause
15,454
0
20
4,359
2,517
1,309
1,208
220
6
{-| Module : Idris.Erasure Description : Utilities to erase stuff not necessary for runtime. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE PatternGuards #-} module Idris.Erasure (performUsageAnalysis, mkFieldName) where import Idris.AbsSyntax import Idris.ASTUtils import Idris.Core.CaseTree import Idris.Core.Evaluate import Idris.Core.TT import Idris.Error import Idris.Options import Idris.Primitives import Prelude hiding (id, (.)) import Control.Arrow import Control.Category import Control.Monad.State import Data.IntMap (IntMap) import qualified Data.IntMap as IM import Data.IntSet (IntSet) import qualified Data.IntSet as IS import Data.List import Data.Map (Map) import qualified Data.Map as M import Data.Maybe import Data.Set (Set) import qualified Data.Set as S import Data.Text (pack) import qualified Data.Text as T -- | UseMap maps names to the set of used (reachable) argument -- positions. type UseMap = Map Name (IntMap (Set Reason)) data Arg = Arg Int | Result deriving (Eq, Ord) instance Show Arg where show (Arg i) = show i show Result = "*" type Node = (Name, Arg) type Deps = Map Cond DepSet type Reason = (Name, Int) -- function name, argument index -- | Nodes along with sets of reasons for every one. type DepSet = Map Node (Set Reason) -- | "Condition" is the conjunction of elementary assumptions along -- the path from the root. Elementary assumption (f, i) means that -- "function f uses the argument i". type Cond = Set Node -- | Variables carry certain information with them. data VarInfo = VI { viDeps :: DepSet -- ^ dependencies drawn in by the variable , viFunArg :: Maybe Int -- ^ which function argument this variable came from (defined only for patvars) , viMethod :: Maybe Name -- ^ name of the metamethod represented by the var, if any } deriving Show type Vars = Map Name VarInfo -- | Perform usage analysis, write the relevant information in the -- internal structures, returning the list of reachable names. performUsageAnalysis :: [Name] -> Idris [Name] performUsageAnalysis startNames = do ctx <- tt_ctxt <$> getIState case startNames of [] -> return [] -- no main -> not compiling -> reachability irrelevant main -> do ci <- idris_interfaces <$> getIState cg <- idris_callgraph <$> getIState opt <- idris_optimisation <$> getIState used <- idris_erasureUsed <$> getIState externs <- idris_externs <$> getIState -- Build the dependency graph. let depMap = buildDepMap ci used (S.toList externs) ctx main -- Search for reachable nodes in the graph. let (residDeps, (reachableNames, minUse)) = minimalUsage depMap usage = M.toList minUse -- Print some debug info. logErasure 5 $ "Original deps:\n" ++ unlines (map fmtItem . M.toList $ depMap) logErasure 3 $ "Reachable names:\n" ++ unlines (map (indent . show) . S.toList $ reachableNames) logErasure 4 $ "Minimal usage:\n" ++ fmtUseMap usage logErasure 5 $ "Residual deps:\n" ++ unlines (map fmtItem . M.toList $ residDeps) -- Check that everything reachable is accessible. checkEnabled <- (WarnReach `elem`) . opt_cmdline . idris_options <$> getIState when checkEnabled $ mapM_ (checkAccessibility opt) usage -- Check that no postulates are reachable. reachablePostulates <- S.intersection reachableNames . idris_postulates <$> getIState when (not . S.null $ reachablePostulates) $ ifail ("reachable postulates:\n" ++ intercalate "\n" [" " ++ show n | n <- S.toList reachablePostulates]) -- Store the usage info in the internal state. mapM_ storeUsage usage return $ S.toList reachableNames where indent = (" " ++) fmtItem :: (Cond, DepSet) -> String fmtItem (cond, deps) = indent $ show (S.toList cond) ++ " -> " ++ show (M.toList deps) fmtUseMap :: [(Name, IntMap (Set Reason))] -> String fmtUseMap = unlines . map (\(n,is) -> indent $ show n ++ " -> " ++ fmtIxs is) fmtIxs :: IntMap (Set Reason) -> String fmtIxs = intercalate ", " . map fmtArg . IM.toList where fmtArg (i, rs) | S.null rs = show i | otherwise = show i ++ " from " ++ intercalate ", " (map show $ S.toList rs) storeUsage :: (Name, IntMap (Set Reason)) -> Idris () storeUsage (n, args) = fputState (cg_usedpos . ist_callgraph n) flat where flat = [(i, S.toList rs) | (i,rs) <- IM.toList args] checkAccessibility :: Ctxt OptInfo -> (Name, IntMap (Set Reason)) -> Idris () checkAccessibility opt (n, reachable) | Just (Optimise inaccessible dt force) <- lookupCtxtExact n opt , eargs@(_:_) <- [fmt n (S.toList rs) | (i,n) <- inaccessible, rs <- maybeToList $ IM.lookup i reachable] = warn $ show n ++ ": inaccessible arguments reachable:\n " ++ intercalate "\n " eargs | otherwise = return () where fmt n [] = show n ++ " (no more information available)" fmt n rs = show n ++ " from " ++ intercalate ", " [show rn ++ " arg# " ++ show ri | (rn,ri) <- rs] warn = logErasure 0 type Constraint = (Cond, DepSet) -- | Find the minimal consistent usage by forward chaining. -- -- We use a cleverer implementation that: -- 1. First transforms Deps into a collection of numbered constraints -- 2. For each node, we remember the numbers of constraints -- that contain that node among their preconditions. -- 3. When performing forward chaining, we perform unit propagation -- only on the relevant constraints, not all constraints. -- -- Typical numbers from the current version of Blodwen: -- * 56 iterations until fixpoint -- * out of 20k constraints total, 5-1000 are relevant per iteration minimalUsage :: Deps -> (Deps, (Set Name, UseMap)) minimalUsage deps = fromNumbered *** gather $ forwardChain (index numbered) seedDeps seedDeps numbered where numbered = toNumbered deps -- The initial solution. Consists of nodes that are -- reachable immediately, without any preconditions. seedDeps :: DepSet seedDeps = M.unionsWith S.union [ds | (cond, ds) <- IM.elems numbered, S.null cond] toNumbered :: Deps -> IntMap Constraint toNumbered = IM.fromList . zip [0..] . M.toList fromNumbered :: IntMap Constraint -> Deps fromNumbered = IM.foldr addConstraint M.empty where addConstraint (ns, vs) = M.insertWith (M.unionWith S.union) ns vs -- Build an index that maps every node to the set of constraints -- where the node appears among the preconditions. index :: IntMap Constraint -> Map Node IntSet index = IM.foldrWithKey ( -- for each clause (i. ns --> _ds) \i (ns, _ds) ix -> foldr ( -- for each node `n` in `ns` \n ix' -> M.insertWith IS.union n (IS.singleton i) ix' ) ix (S.toList ns) ) M.empty -- Convert a solution of constraints into: -- 1. the list of names used in the program -- 2. the list of arguments used, together with their reasons gather :: DepSet -> (Set Name, UseMap) gather = foldr ins (S.empty, M.empty) . M.toList where ins :: (Node, Set Reason) -> (Set Name, UseMap) -> (Set Name, UseMap) ins ((n, Result), rs) (ns, umap) = (S.insert n ns, umap) ins ((n, Arg i ), rs) (ns, umap) = (ns, M.insertWith (IM.unionWith S.union) n (IM.singleton i rs) umap) -- | In each iteration, we find the set of nodes immediately reachable -- from the current set of constraints, and then reduce the set of constraints -- based on that knowledge. -- -- In the implementation, this is phase-shifted. We first reduce the set -- of constraints, given the newly reachable nodes from the previous iteration, -- and then compute the set of currently reachable nodes. -- Then we decide whether to iterate further. forwardChain :: Map Node IntSet -- ^ node index -> DepSet -- ^ all reachable nodes found so far -> DepSet -- ^ nodes reached in the previous iteration -> IntMap Constraint -- ^ numbered constraints -> (IntMap Constraint, DepSet) forwardChain index solution previouslyNew constrs -- no newly reachable nodes, fixed point has been reached | M.null currentlyNew = (constrs, solution) -- some newly reachable nodes, iterate more | otherwise = forwardChain index (M.unionWith S.union solution currentlyNew) currentlyNew constrs' where -- which constraints could give new results, -- given that `previouslyNew` has been derived in the last iteration affectedIxs = IS.unions [ M.findWithDefault IS.empty n index | n <- M.keys previouslyNew ] -- traverse all (potentially) affected constraints, building: -- 1. a set of newly reached nodes -- 2. updated set of constraints where the previously -- reached nodes have been removed (currentlyNew, constrs') = IS.foldr (reduceConstraint $ M.keysSet previouslyNew) (M.empty, constrs) affectedIxs -- Update the pair (newly reached nodes, numbered constraint set) -- by reducing the constraint with the given number. reduceConstraint :: Set Node -- ^ nodes reached in the previous iteration -> Int -- ^ constraint number -> (DepSet, IntMap (Cond, DepSet)) -> (DepSet, IntMap (Cond, DepSet)) reduceConstraint previouslyNew i (news, constrs) | Just (cond, deps) <- IM.lookup i constrs = case cond S.\\ previouslyNew of cond' -- This constraint's set of preconditions has shrunk -- to the empty set. We can add its RHS to the set of newly -- reached nodes, and remove the constraint altogether. | S.null cond' -> (M.unionWith S.union news deps, IM.delete i constrs) -- This constraint's set of preconditions has shrunk -- so we need to overwrite the numbered slot -- with the updated constraint. | S.size cond' < S.size cond -> (news, IM.insert i (cond', deps) constrs) -- This constraint's set of preconditions hasn't changed -- so we do not do anything about it. | otherwise -> (news, constrs) -- Constraint number present in index but not found -- among the constraints. This happens more and more frequently -- as we delete constraints from the set. | otherwise = (news, constrs) -- | Build the dependency graph, starting the depth-first search from -- a list of Names. buildDepMap :: Ctxt InterfaceInfo -> [(Name, Int)] -> [(Name, Int)] -> Context -> [Name] -> Deps buildDepMap ci used externs ctx startNames = addPostulates used $ dfs S.empty M.empty startNames where -- mark the result of Main.main as used with the empty assumption addPostulates :: [(Name, Int)] -> Deps -> Deps addPostulates used deps = foldr (\(ds, rs) -> M.insertWith (M.unionWith S.union) ds rs) deps (postulates used) where -- mini-DSL for postulates (==>) ds rs = (S.fromList ds, M.fromList [(r, S.empty) | r <- rs]) it n is = [(sUN n, Arg i) | i <- is] -- believe_me is special because it does not use all its arguments specialPrims = S.fromList [sUN "prim__believe_me"] usedNames = allNames deps S.\\ specialPrims usedPrims = [(p_name p, p_arity p) | p <- primitives, p_name p `S.member` usedNames] postulates used = [ [] ==> concat -- Main.main ( + export lists) and run__IO, are always evaluated -- but they elude analysis since they come from the seed term. [(map (\n -> (n, Result)) startNames) ,[(sUN "run__IO", Result), (sUN "run__IO", Arg 1)] ,[(sUN "call__IO", Result), (sUN "call__IO", Arg 2)] -- Explicit usage declarations from a %used pragma , map (\(n, i) -> (n, Arg i)) used -- MkIO is read by run__IO, -- but this cannot be observed in the source code of programs. , it "MkIO" [2] , it "prim__IO" [1] -- Foreign calls are built with pairs, but mkForeign doesn't -- have an implementation so analysis won't see them , [(pairCon, Arg 2), (pairCon, Arg 3)] -- Used in foreign calls -- these have been discovered as builtins but are not listed -- among Idris.Primitives.primitives --, mn "__MkPair" [2,3] , it "prim_fork" [0] , it "unsafePerformPrimIO" [1] -- believe_me is a primitive but it only uses its third argument -- it is special-cased in usedNames above , it "prim__believe_me" [2] -- in general, all other primitives use all their arguments , [(n, Arg i) | (n,arity) <- usedPrims, i <- [0..arity-1]] -- %externs are assumed to use all their arguments , [(n, Arg i) | (n,arity) <- externs, i <- [0..arity-1]] -- mkForeign* functions are special-cased below ] ] -- perform depth-first search -- to discover all the names used in the program -- and call getDeps for every name dfs :: Set Name -> Deps -> [Name] -> Deps dfs visited deps [] = deps dfs visited deps (n : ns) | n `S.member` visited = dfs visited deps ns | otherwise = dfs (S.insert n visited) (M.unionWith (M.unionWith S.union) deps' deps) (next ++ ns) where next = [n | n <- S.toList depn, n `S.notMember` visited] depn = S.delete n $ allNames deps' deps' = getDeps n -- extract all names that a function depends on -- from the Deps of the function allNames :: Deps -> Set Name allNames = S.unions . map names . M.toList where names (cs, ns) = S.map fst cs `S.union` S.map fst (M.keysSet ns) -- get Deps for a Name getDeps :: Name -> Deps getDeps (SN (WhereN i (SN (ImplementationCtorN interfaceN)) (MN i' field))) = M.empty -- these deps are created when applying implementation ctors getDeps n = case lookupDefExact n ctx of Just def -> getDepsDef n def Nothing -> error $ "erasure checker: unknown reference: " ++ show n getDepsDef :: Name -> Def -> Deps getDepsDef fn (Function ty t) = error "a function encountered" -- TODO getDepsDef fn (TyDecl ty t) = M.empty getDepsDef fn (Operator ty n' f) = M.empty -- TODO: what's this? getDepsDef fn (CaseOp ci ty tys def tot cdefs) = getDepsSC fn etaVars (etaMap `M.union` varMap) sc where -- we must eta-expand the definition with fresh variables -- to capture these dependencies as well etaIdx = [length vars .. length tys - 1] etaVars = [eta i | i <- etaIdx] etaMap = M.fromList [varPair (eta i) i | i <- etaIdx] eta i = MN i (pack "eta") -- the variables that arose as function arguments only depend on (n, i) varMap = M.fromList [varPair v i | (v,i) <- zip vars [0..]] varPair n argNo = (n, VI { viDeps = M.singleton (fn, Arg argNo) S.empty , viFunArg = Just argNo , viMethod = Nothing }) (vars, sc) = cases_runtime cdefs -- we use cases_runtime in order to have case-blocks -- resolved to top-level functions before our analysis etaExpand :: [Name] -> Term -> Term etaExpand [] t = t etaExpand (n : ns) t = etaExpand ns (App Complete t (P Ref n Erased)) getDepsSC :: Name -> [Name] -> Vars -> SC -> Deps getDepsSC fn es vs ImpossibleCase = M.empty getDepsSC fn es vs (UnmatchedCase msg) = M.empty -- for the purposes of erasure, we can disregard the projection getDepsSC fn es vs (ProjCase (Proj t i) alts) = getDepsSC fn es vs (ProjCase t alts) -- step getDepsSC fn es vs (ProjCase (P _ n _) alts) = getDepsSC fn es vs (Case Shared n alts) -- base -- other ProjCase's are not supported getDepsSC fn es vs (ProjCase t alts) = error $ "ProjCase not supported:\n" ++ show (ProjCase t alts) getDepsSC fn es vs (STerm t) = getDepsTerm vs [] (S.singleton (fn, Result)) (etaExpand es t) getDepsSC fn es vs (Case sh n alts) -- we case-split on this variable, which marks it as used -- (unless there is exactly one case branch) -- hence we add a new dependency, whose only precondition is -- that the result of this function is used at all = addTagDep $ unionMap (getDepsAlt fn es vs casedVar) alts -- coming from the whole subtree where addTagDep = case alts of [_] -> id -- single branch, tag not used _ -> M.insertWith (M.unionWith S.union) (S.singleton (fn, Result)) (viDeps casedVar) casedVar = fromMaybe (error $ "nonpatvar in case: " ++ show n) (M.lookup n vs) getDepsAlt :: Name -> [Name] -> Vars -> VarInfo -> CaseAlt -> Deps getDepsAlt fn es vs var (FnCase n ns sc) = M.empty -- can't use FnCase at runtime getDepsAlt fn es vs var (ConstCase c sc) = getDepsSC fn es vs sc getDepsAlt fn es vs var (DefaultCase sc) = getDepsSC fn es vs sc getDepsAlt fn es vs var (SucCase n sc) = getDepsSC fn es (M.insert n var vs) sc -- we're not inserting the S-dependency here because it's special-cased -- data constructors getDepsAlt fn es vs var (ConCase n cnt ns sc) = getDepsSC fn es (vs' `M.union` vs) sc -- left-biased union where -- Here we insert dependencies that arose from pattern matching on a constructor. -- n = ctor name, j = ctor arg#, i = fun arg# of the cased var, cs = ctors of the cased var vs' = M.fromList [(v, VI { viDeps = M.insertWith S.union (n, Arg j) (S.singleton (fn, varIdx)) (viDeps var) , viFunArg = viFunArg var , viMethod = meth j }) | (v, j) <- zip ns [0..]] -- this is safe because it's certainly a patvar varIdx = fromJust (viFunArg var) -- generate metamethod names, "n" is the implementation ctor meth :: Int -> Maybe Name meth | SN (ImplementationCtorN interfaceName) <- n = \j -> Just (mkFieldName n j) | otherwise = \j -> Nothing -- Named variables -> DeBruijn variables -> Conds/guards -> Term -> Deps getDepsTerm :: Vars -> [(Name, Cond -> Deps)] -> Cond -> Term -> Deps -- named variables introduce dependencies as described in `vs' getDepsTerm vs bs cd (P _ n _) -- de bruijns (lambda-bound, let-bound vars) | Just deps <- lookup n bs = deps cd -- ctor-bound/arg-bound variables | Just var <- M.lookup n vs = M.singleton cd (viDeps var) -- sanity check: machine-generated names shouldn't occur at top-level | MN _ _ <- n = error $ "erasure analysis: variable " ++ show n ++ " unbound in " ++ show (S.toList cd) -- assumed to be a global reference | otherwise = M.singleton cd (M.singleton (n, Result) S.empty) -- dependencies of de bruijn variables are described in `bs' getDepsTerm vs bs cd (V i) = snd (bs !! i) cd getDepsTerm vs bs cd (Bind n bdr body) -- here we just push IM.empty on the de bruijn stack -- the args will be marked as used at the usage site | Lam _ ty <- bdr = getDepsTerm vs ((n, const M.empty) : bs) cd body | Pi _ _ ty _ <- bdr = getDepsTerm vs ((n, const M.empty) : bs) cd body -- let-bound variables can get partially evaluated -- it is sufficient just to plug the Cond in when the bound names are used | Let rig ty t <- bdr = var t cd `union` getDepsTerm vs ((n, const M.empty) : bs) cd body | NLet ty t <- bdr = var t cd `union` getDepsTerm vs ((n, const M.empty) : bs) cd body where var t cd = getDepsTerm vs bs cd t -- applications may add items to Cond getDepsTerm vs bs cd app@(App _ _ _) | (fun, args) <- unApply app = case fun of -- implementation constructors -> create metamethod deps P (DCon _ _ _) ctorName@(SN (ImplementationCtorN interfaceName)) _ -> conditionalDeps ctorName args -- regular data ctor stuff `union` unionMap (methodDeps ctorName) (zip [0..] args) -- method-specific stuff -- ordinary constructors P (TCon _ _) n _ -> unconditionalDeps args -- does not depend on anything P (DCon _ _ _) n _ -> conditionalDeps n args -- depends on whether (n,#) is used -- mkForeign* calls must be special-cased because they are variadic -- All arguments must be marked as used, except for the first four, -- which define the call type and are not needed at runtime. P _ (UN n) _ | n == T.pack "mkForeignPrim" -> unconditionalDeps $ drop 4 args -- a bound variable might draw in additional dependencies, -- think: f x = x 0 <-- here, `x' _is_ used P _ n _ -- debruijn-bound name | Just deps <- lookup n bs -> deps cd `union` unconditionalDeps args -- local name that refers to a method | Just var <- M.lookup n vs , Just meth <- viMethod var -> viDeps var `ins` conditionalDeps meth args -- use the method instead -- local name | Just var <- M.lookup n vs -- unconditional use -> viDeps var `ins` unconditionalDeps args -- global name | otherwise -- depends on whether the referred thing uses its argument -> conditionalDeps n args -- TODO: could we somehow infer how bound variables use their arguments? V i -> snd (bs !! i) cd `union` unconditionalDeps args -- we interpret applied lambdas as lets in order to reuse code here Bind n (Lam _ ty) t -> getDepsTerm vs bs cd (lamToLet app) -- and we interpret applied lets as lambdas Bind n (Let _ ty t') t -> getDepsTerm vs bs cd (App Complete (Bind n (Lam RigW ty) t) t') Bind n (NLet ty t') t -> getDepsTerm vs bs cd (App Complete (Bind n (Lam RigW ty) t) t') Proj t i -> error $ "cannot[0] analyse projection !" ++ show i ++ " of " ++ show t Erased -> M.empty _ -> error $ "cannot analyse application of " ++ show fun ++ " to " ++ show args where union = M.unionWith $ M.unionWith S.union ins = M.insertWith (M.unionWith S.union) cd unconditionalDeps :: [Term] -> Deps unconditionalDeps = unionMap (getDepsTerm vs bs cd) conditionalDeps :: Name -> [Term] -> Deps conditionalDeps n = ins (M.singleton (n, Result) S.empty) . unionMap (getDepsArgs n) . zip indices where indices = map Just [0 .. getArity n - 1] ++ repeat Nothing getDepsArgs n (Just i, t) = getDepsTerm vs bs (S.insert (n, Arg i) cd) t -- conditional getDepsArgs n (Nothing, t) = getDepsTerm vs bs cd t -- unconditional methodDeps :: Name -> (Int, Term) -> Deps methodDeps ctorName (methNo, t) = getDepsTerm (vars `M.union` vs) (bruijns ++ bs) cond body where vars = M.fromList [(v, VI { viDeps = deps i , viFunArg = Just i , viMethod = Nothing }) | (v, i) <- zip args [0..]] deps i = M.singleton (metameth, Arg i) S.empty bruijns = reverse [(n, \cd -> M.singleton cd (deps i)) | (i, n) <- zip [0..] args] cond = S.singleton (metameth, Result) metameth = mkFieldName ctorName methNo (args, body) = unfoldLams t -- projections getDepsTerm vs bs cd (Proj t (-1)) = getDepsTerm vs bs cd t -- naturals, (S n) -> n getDepsTerm vs bs cd (Proj t i) = error $ "cannot[1] analyse projection !" ++ show i ++ " of " ++ show t -- the easy cases getDepsTerm vs bs cd (Constant _) = M.empty getDepsTerm vs bs cd (TType _) = M.empty getDepsTerm vs bs cd (UType _) = M.empty getDepsTerm vs bs cd Erased = M.empty getDepsTerm vs bs cd Impossible = M.empty getDepsTerm vs bs cd t = error $ "cannot get deps of: " ++ show t -- Get the number of arguments that might be considered for erasure. getArity :: Name -> Int getArity (SN (WhereN i' ctorName (MN i field))) | Just (TyDecl (DCon _ _ _) ty) <- lookupDefExact ctorName ctx = let argTys = map snd $ getArgTys ty in if i <= length argTys then length $ getArgTys (argTys !! i) else error $ "invalid field number " ++ show i ++ " for " ++ show ctorName | otherwise = error $ "unknown implementation constructor: " ++ show ctorName getArity n = case lookupDefExact n ctx of Just (CaseOp ci ty tys def tot cdefs) -> length tys Just (TyDecl (DCon tag arity _) _) -> arity Just (TyDecl (Ref) ty) -> length $ getArgTys ty Just (Operator ty arity op) -> arity Just df -> error $ "Erasure/getArity: unrecognised entity '" ++ show n ++ "' with definition: " ++ show df Nothing -> error $ "Erasure/getArity: definition not found for " ++ show n -- convert applications of lambdas to lets -- note that this transformation preserves de bruijn numbering lamToLet :: Term -> Term lamToLet tm = lamToLet' args f where (f, args) = unApply tm lamToLet' :: [Term] -> Term -> Term lamToLet' (v:vs) (Bind n (Lam rig ty) tm) = Bind n (Let rig ty v) $ lamToLet' vs tm lamToLet' [] tm = tm lamToLet' vs tm = error $ "Erasure.hs:lamToLet': unexpected input: " ++ "vs = " ++ show vs ++ ", tm = " ++ show tm -- split "\x_i -> T(x_i)" into [x_i] and T unfoldLams :: Term -> ([Name], Term) unfoldLams (Bind n (Lam _ ty) t) = let (ns,t') = unfoldLams t in (n:ns, t') unfoldLams t = ([], t) union :: Deps -> Deps -> Deps union = M.unionWith (M.unionWith S.union) unionMap :: (a -> Deps) -> [a] -> Deps unionMap f = M.unionsWith (M.unionWith S.union) . map f -- | Make a field name out of a data constructor name and field number. mkFieldName :: Name -> Int -> Name mkFieldName ctorName fieldNo = SN (WhereN fieldNo ctorName $ sMN fieldNo "field")
uuhan/Idris-dev
src/Idris/Erasure.hs
bsd-3-clause
27,202
627
14
8,210
6,728
3,692
3,036
353
52
module Hate.Events ( initialEventsState , setCallbacks , fetchEvents , allowedEvent , module Hate.Events.Types ) where import qualified Graphics.UI.GLFW as GLFW import Control.Concurrent.STM (TQueue, atomically, newTQueueIO, tryReadTQueue, writeTQueue) import Hate.Events.Types import Hate.Common.Types import Control.Monad.IO.Class (liftIO) import Control.Monad.State.Class (gets) import Control.Applicative import Data.Maybe import GHC.Float (double2Float) initialEventsState :: IO EventsState initialEventsState = newTQueueIO :: IO (TQueue TimedEvent) {- The code has been borrowed from GLFW-b-demo; thanks @bsl -} -- I assume only one window can be used by the framework time = fromJust <$> GLFW.getTime writeWithTime :: TQueue TimedEvent -> Event -> IO () writeWithTime tc e = time >>= \t -> atomically . writeTQueue tc $ (t, e) errorCallback :: TQueue TimedEvent -> GLFW.Error -> String -> IO () windowPosCallback :: TQueue TimedEvent -> GLFW.Window -> Int -> Int -> IO () windowSizeCallback :: TQueue TimedEvent -> GLFW.Window -> Int -> Int -> IO () windowCloseCallback :: TQueue TimedEvent -> GLFW.Window -> IO () windowRefreshCallback :: TQueue TimedEvent -> GLFW.Window -> IO () windowFocusCallback :: TQueue TimedEvent -> GLFW.Window -> GLFW.FocusState -> IO () windowIconifyCallback :: TQueue TimedEvent -> GLFW.Window -> GLFW.IconifyState -> IO () framebufferSizeCallback :: TQueue TimedEvent -> GLFW.Window -> Int -> Int -> IO () mouseButtonCallback :: TQueue TimedEvent -> GLFW.Window -> GLFW.MouseButton -> GLFW.MouseButtonState -> GLFW.ModifierKeys -> IO () cursorPosCallback :: TQueue TimedEvent -> GLFW.Window -> Double -> Double -> IO () cursorEnterCallback :: TQueue TimedEvent -> GLFW.Window -> GLFW.CursorState -> IO () scrollCallback :: TQueue TimedEvent -> GLFW.Window -> Double -> Double -> IO () keyCallback :: TQueue TimedEvent -> GLFW.Window -> GLFW.Key -> Int -> GLFW.KeyState -> GLFW.ModifierKeys -> IO () charCallback :: TQueue TimedEvent -> GLFW.Window -> Char -> IO () errorCallback tc e s = writeWithTime tc $ EventError e s windowPosCallback tc _ x y = writeWithTime tc $ EventWindowPos x y windowSizeCallback tc _ w h = writeWithTime tc $ EventWindowSize w h windowCloseCallback tc _ = writeWithTime tc $ EventWindowClose windowRefreshCallback tc _ = writeWithTime tc $ EventWindowRefresh windowFocusCallback tc _ fa = writeWithTime tc $ EventWindowFocus fa windowIconifyCallback tc _ ia = writeWithTime tc $ EventWindowIconify ia framebufferSizeCallback tc _ w h = writeWithTime tc $ EventFramebufferSize w h mouseButtonCallback tc _ mb mba mk = writeWithTime tc $ EventMouseButton mb mba mk cursorPosCallback tc _ x y = writeWithTime tc $ EventCursorPos (double2Float x) (double2Float y) cursorEnterCallback tc _ ca = writeWithTime tc $ EventCursorEnter ca scrollCallback tc _ x y = writeWithTime tc $ EventScroll x y keyCallback tc _ k sc ka mk = writeWithTime tc $ EventKey k sc ka mk charCallback tc _ c = writeWithTime tc $ EventChar c setErrorCallback :: TQueue TimedEvent -> IO () setErrorCallback eventsChan = GLFW.setErrorCallback $ Just $ errorCallback eventsChan setCallbacks :: EventsState -> GLFW.Window -> IO () setCallbacks eventsChan win = do GLFW.setWindowPosCallback win $ Just $ windowPosCallback eventsChan GLFW.setWindowSizeCallback win $ Just $ windowSizeCallback eventsChan GLFW.setWindowCloseCallback win $ Just $ windowCloseCallback eventsChan GLFW.setWindowRefreshCallback win $ Just $ windowRefreshCallback eventsChan GLFW.setWindowFocusCallback win $ Just $ windowFocusCallback eventsChan GLFW.setWindowIconifyCallback win $ Just $ windowIconifyCallback eventsChan GLFW.setFramebufferSizeCallback win $ Just $ framebufferSizeCallback eventsChan GLFW.setMouseButtonCallback win $ Just $ mouseButtonCallback eventsChan GLFW.setCursorPosCallback win $ Just $ cursorPosCallback eventsChan GLFW.setCursorEnterCallback win $ Just $ cursorEnterCallback eventsChan GLFW.setScrollCallback win $ Just $ scrollCallback eventsChan GLFW.setKeyCallback win $ Just $ keyCallback eventsChan GLFW.setCharCallback win $ Just $ charCallback eventsChan fetchEvents :: HateInner us [TimedEvent] fetchEvents = fetchEvents' [] where fetchEvents' :: [TimedEvent] -> HateInner us [TimedEvent] fetchEvents' xs = do tc <- gets (eventsState . libraryState) me <- liftIO $ atomically $ tryReadTQueue tc case me of Just e -> fetchEvents' (e:xs) Nothing -> return xs -- | Some events aren't meant to impact the user, and should be handled -- internally by framework instead. allowedEvent :: Event -> Bool allowedEvent (EventWindowClose) = True allowedEvent (EventWindowFocus _) = True allowedEvent (EventMouseButton _ _ _) = True allowedEvent (EventCursorPos _ _) = True allowedEvent (EventScroll _ _) = True allowedEvent (EventKey _ _ _ _) = True allowedEvent (EventChar _) = True allowedEvent _ = False
bananu7/Hate
src/Hate/Events.hs
mit
6,335
0
14
2,167
1,556
759
797
83
2
module Data.Wright.CIE.Illuminant.F11 (f11) where import Data.Wright.Types (Model) import Data.Wright.CIE.Illuminant.Environment (environment) f11 :: Model f11 = environment (0.38052, 0.37713)
fmap-archive/wright
src/Data/Wright/CIE/Illuminant/F11.hs
mit
194
0
6
19
57
37
20
5
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.OpsWorks.DescribeMyUserProfile -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Describes a user\'s SSH information. -- -- __Required Permissions__: To use this action, an IAM user must have -- self-management enabled or an attached policy that explicitly grants -- permissions. For more information on user permissions, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing User Permissions>. -- -- /See:/ <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_DescribeMyUserProfile.html AWS API Reference> for DescribeMyUserProfile. module Network.AWS.OpsWorks.DescribeMyUserProfile ( -- * Creating a Request describeMyUserProfile , DescribeMyUserProfile -- * Destructuring the Response , describeMyUserProfileResponse , DescribeMyUserProfileResponse -- * Response Lenses , dmuprsUserProfile , dmuprsResponseStatus ) where import Network.AWS.OpsWorks.Types import Network.AWS.OpsWorks.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'describeMyUserProfile' smart constructor. data DescribeMyUserProfile = DescribeMyUserProfile' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeMyUserProfile' with the minimum fields required to make a request. -- describeMyUserProfile :: DescribeMyUserProfile describeMyUserProfile = DescribeMyUserProfile' instance AWSRequest DescribeMyUserProfile where type Rs DescribeMyUserProfile = DescribeMyUserProfileResponse request = postJSON opsWorks response = receiveJSON (\ s h x -> DescribeMyUserProfileResponse' <$> (x .?> "UserProfile") <*> (pure (fromEnum s))) instance ToHeaders DescribeMyUserProfile where toHeaders = const (mconcat ["X-Amz-Target" =# ("OpsWorks_20130218.DescribeMyUserProfile" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON DescribeMyUserProfile where toJSON = const (Object mempty) instance ToPath DescribeMyUserProfile where toPath = const "/" instance ToQuery DescribeMyUserProfile where toQuery = const mempty -- | Contains the response to a 'DescribeMyUserProfile' request. -- -- /See:/ 'describeMyUserProfileResponse' smart constructor. data DescribeMyUserProfileResponse = DescribeMyUserProfileResponse' { _dmuprsUserProfile :: !(Maybe SelfUserProfile) , _dmuprsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeMyUserProfileResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dmuprsUserProfile' -- -- * 'dmuprsResponseStatus' describeMyUserProfileResponse :: Int -- ^ 'dmuprsResponseStatus' -> DescribeMyUserProfileResponse describeMyUserProfileResponse pResponseStatus_ = DescribeMyUserProfileResponse' { _dmuprsUserProfile = Nothing , _dmuprsResponseStatus = pResponseStatus_ } -- | A 'UserProfile' object that describes the user\'s SSH information. dmuprsUserProfile :: Lens' DescribeMyUserProfileResponse (Maybe SelfUserProfile) dmuprsUserProfile = lens _dmuprsUserProfile (\ s a -> s{_dmuprsUserProfile = a}); -- | The response status code. dmuprsResponseStatus :: Lens' DescribeMyUserProfileResponse Int dmuprsResponseStatus = lens _dmuprsResponseStatus (\ s a -> s{_dmuprsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/DescribeMyUserProfile.hs
mpl-2.0
4,318
0
13
865
494
297
197
70
1
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Network.Riak.Protocol.GetClientIDRequest (GetClientIDRequest(..)) 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 GetClientIDRequest = GetClientIDRequest{} deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic) instance P'.Mergeable GetClientIDRequest where mergeAppend GetClientIDRequest GetClientIDRequest = GetClientIDRequest instance P'.Default GetClientIDRequest where defaultValue = GetClientIDRequest instance P'.Wire GetClientIDRequest where wireSize ft' self'@(GetClientIDRequest) = case ft' of 10 -> calc'Size 11 -> P'.prependMessageSize calc'Size _ -> P'.wireSizeErr ft' self' where calc'Size = 0 wirePutWithSize ft' self'@(GetClientIDRequest) = case ft' of 10 -> put'Fields 11 -> put'FieldsSized _ -> P'.wirePutErr ft' self' where put'Fields = P'.sequencePutWithSize [] put'FieldsSized = let size' = Prelude'.fst (P'.runPutM put'Fields) put'Size = do P'.putSize size' Prelude'.return (P'.size'WireSize size') in P'.sequencePutWithSize [put'Size, put'Fields] wireGet ft' = case ft' of 10 -> P'.getBareMessageWith (P'.catch'Unknown' P'.discardUnknown update'Self) 11 -> P'.getMessageWith (P'.catch'Unknown' P'.discardUnknown update'Self) _ -> P'.wireGetErr ft' where update'Self wire'Tag old'Self = case wire'Tag of _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self instance P'.MessageAPI msg' (msg' -> GetClientIDRequest) GetClientIDRequest where getVal m' f' = f' m' instance P'.GPB GetClientIDRequest instance P'.ReflectDescriptor GetClientIDRequest where getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList []) reflectDescriptorInfo _ = Prelude'.read "DescriptorInfo {descName = ProtoName {protobufName = FIName \".Protocol.GetClientIDRequest\", haskellPrefix = [MName \"Network\",MName \"Riak\"], parentModule = [MName \"Protocol\"], baseName = MName \"GetClientIDRequest\"}, descFilePath = [\"Network\",\"Riak\",\"Protocol\",\"GetClientIDRequest.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False, jsonInstances = False}" instance P'.TextType GetClientIDRequest where tellT = P'.tellSubMessage getT = P'.getSubMessage instance P'.TextMsg GetClientIDRequest where textPut msg = Prelude'.return () textGet = Prelude'.return P'.defaultValue where
tmcgilchrist/riak-haskell-client
protobuf/src/Network/Riak/Protocol/GetClientIDRequest.hs
apache-2.0
3,139
1
17
605
648
344
304
58
0
{-# LANGUAGE ScopedTypeVariables, DataKinds, FlexibleInstances, FlexibleContexts, MultiParamTypeClasses, UndecidableInstances, TemplateHaskell #-} {-| This module defines a routine for determining structural containment on a type variable and set of constraints. This routine is used to define the "within" operator used in annotation concatenation. -} module Language.K3.TypeSystem.Within ( mutuallyWithin , isWithin , proveMutuallyWithin , proveWithin , WithinAlignable(..) ) where import Control.Applicative import Control.Arrow import Control.Monad import Control.Monad.Trans import Control.Monad.Trans.State import qualified Data.Map as Map import Data.Map (Map) import Data.Monoid import qualified Data.Set as Set import Data.Set (Set) import qualified Language.K3.TypeSystem.ConstraintSetLike as CSL import Language.K3.TypeSystem.Data import Language.K3.Utils.Logger import Language.K3.Utils.Pretty $(loggingFunctions) -- PERF: This whole thing uses a naive set exploration. Just indexing the -- constraints before the work is done could speed things up a bit. This -- improvement will probably be achieved just by creating a sensible -- ConstraintSet data structure. (To be fair, this kind of operation is -- easily worst-case exponential; K3, however, tends not to generate many -- union types and so it shouldn't be bad in practice.) -- |Determines whether or not two constrained types are structurally equivalent. mutuallyWithin :: forall c el q. ( Pretty c, Ord el, WithinAlignable el , WithinAlignable (TVar q) , CSL.ConstraintSetLike el c , CSL.ConstraintSetLikePromotable ConstraintSet c) => (TVar q,c) -> (TVar q,c) -> Bool mutuallyWithin ct1 ct2 = not $ null $ proveMutuallyWithin ct1 ct2 -- |Determines whether or not one constrained type is contained by another. isWithin :: forall c el q. ( Pretty c, Ord el, WithinAlignable el , WithinAlignable (TVar q) , CSL.ConstraintSetLike el c , CSL.ConstraintSetLikePromotable ConstraintSet c) => (TVar q,c) -> (TVar q,c) -> Bool isWithin = isWithinUnder (Map.empty, Map.empty) -- |Determines whether or not one constrained type is contained by another under -- some set of alignment constraints. All proofs will use the provided -- alignment mapping. isWithinUnder :: forall c el q. ( Pretty c, Ord el, WithinAlignable el , WithinAlignable (TVar q) , CSL.ConstraintSetLike el c , CSL.ConstraintSetLikePromotable ConstraintSet c) => WithinMap -> (TVar q,c) -> (TVar q,c) -> Bool isWithinUnder m ct1 ct2 = not $ null $ proveWithinUnder m ct1 ct2 -- |Proves that two constrained types are structurally equivalent. proveMutuallyWithin :: forall c el q. ( Pretty c, Ord el, WithinAlignable el , WithinAlignable (TVar q) , CSL.ConstraintSetLike el c , CSL.ConstraintSetLikePromotable ConstraintSet c) => (TVar q,c) -> (TVar q,c) -> [WithinMap] proveMutuallyWithin ct1 ct2 = concat $ do proof <- proveWithin ct1 ct2 return $ proveWithinUnder proof ct2 ct1 -- |Proves that a constrained type is structurally contained within another. -- The result of this function is a list of variable mapping pairs that align -- the variables from the first set with the variables from the second set. -- Each variable mapping that appears is a separate proof. proveWithin :: forall c el q. ( Pretty c, Ord el, WithinAlignable el , WithinAlignable (TVar q) , CSL.ConstraintSetLike el c , CSL.ConstraintSetLikePromotable ConstraintSet c) => (TVar q,c) -> (TVar q,c) -> [WithinMap] proveWithin = proveWithinUnder (Map.empty, Map.empty) -- |Proves that a constrained type is structurally contained within another. -- The result of this function is a list of variable mapping pairs that align -- the variables from the first set with the variables from the second set. -- Each variable mapping that appears is a separate proof. proveWithinUnder :: forall c el q. ( Pretty c, Ord el, WithinAlignable el , WithinAlignable (TVar q) , CSL.ConstraintSetLike el c , CSL.ConstraintSetLikePromotable ConstraintSet c) => WithinMap -> (TVar q,c) -> (TVar q,c) -> [WithinMap] proveWithinUnder initMap (v,cs) (v',cs') = bracketLog _debugI (boxToString $ ["Checking "] %+ prettyLines v %+ ["\\"] %+ prettyLines cs %$ [" within "] %+ prettyLines v' %+ ["\\"] %+ prettyLines cs') (\answer -> boxToString $ ["Checking "] %+ prettyLines v %+ ["\\"] %+ prettyLines cs %$ [" within "] %+ prettyLines v' %+ ["\\"] %+ prettyLines cs' %$ [" was: "] %+ if null answer then ["unsuccessful"] else ["successful"]) $ let initState = (Set.fromList $ CSL.toList cs', initMap) in map (snd . snd) $ runStateT (withinAlign v v' >> mconcat <$> mapM deduct (CSL.toList cs)) initState where -- |Given one element, find its match and remove it. Each step should also -- force alignment of the variable mapping. deduct :: el -> WithinM el () deduct e = do e' <- withinStep e modify $ first $ Set.delete e' return () where withinStep el = do el' <- lift =<< Set.toList . fst <$> get withinAlign el el' return el' -- |A data type for the mappings used to align variables during the @isWithin@ -- test. type WithinMap = (Map QVar QVar, Map UVar UVar) -- |A monad used during the within test. The state contains the set of -- unmatched constraints from the right side of the relation as well as a -- variable alignment map. (The unmatched constraints from the left side of -- the relation are handled in the @isWithin@ check itself.) The overall monad -- is the list monad, which models disjunctive computation over all suitable -- alignment maps. type WithinM el = StateT (Set el, WithinMap) [] success :: (Monad m) => m () success = return () class WithinAlignable t where withinAlign :: t -> t -> WithinM e () instance WithinAlignable Constraint where withinAlign c c' = case (c,c') of (IntermediateConstraint ta1 ta2, IntermediateConstraint ta1' ta2') -> withinAlign ta1 ta1' >> withinAlign ta2 ta2' (IntermediateConstraint _ _, _) -> mzero (QualifiedLowerConstraint ta qa, QualifiedLowerConstraint ta' qa') -> withinAlign ta ta' >> withinAlign qa qa' (QualifiedLowerConstraint _ _, _) -> mzero (QualifiedUpperConstraint qa ta, QualifiedUpperConstraint qa' ta') -> withinAlign qa qa' >> withinAlign ta ta' (QualifiedUpperConstraint _ _, _) -> mzero ( QualifiedIntermediateConstraint qv1 qv2 ,QualifiedIntermediateConstraint qv1' qv2' ) -> withinAlign qv1 qv1' >> withinAlign qv2 qv2' (QualifiedIntermediateConstraint _ _, _) -> mzero ( MonomorphicQualifiedUpperConstraint qa qs ,MonomorphicQualifiedUpperConstraint qa' qs' ) -> guard (qs == qs') >> withinAlign qa qa' (MonomorphicQualifiedUpperConstraint _ _, _) -> mzero ( PolyinstantiationLineageConstraint qa1 qa2 ,PolyinstantiationLineageConstraint qa1' qa2' ) -> withinAlign qa1 qa1' >> withinAlign qa2 qa2' (PolyinstantiationLineageConstraint _ _, _) -> mzero (OpaqueBoundConstraint oa t1 t2, OpaqueBoundConstraint oa' t1' t2') -> guard (oa == oa') >> withinAlign t1 t1' >> withinAlign t2 t2' (OpaqueBoundConstraint _ _ _, _) -> mzero instance WithinAlignable TypeOrVar where withinAlign ta ta' = case (ta, ta') of (CLeft t, CLeft t') -> withinAlign t t' (CRight a, CRight a') -> withinAlign a a' (CLeft _, CRight _) -> mzero (CRight _, CLeft _) -> mzero instance WithinAlignable QualOrVar where withinAlign qv qv' = case (qv, qv') of (CLeft q, CLeft q') -> guard $ q == q' (CRight qa, CRight qa') -> withinAlign qa qa' (CLeft _, CRight _) -> mzero (CRight _, CLeft _) -> mzero instance WithinAlignable QVar where withinAlign qa qa' = do mqa'' <- Map.lookup qa . fst . snd <$> get case mqa'' of Nothing -> modify $ second $ first $ Map.insert qa qa' Just qa'' -> guard $ qa' == qa'' instance WithinAlignable UVar where withinAlign a a' = do ma'' <- Map.lookup a . snd . snd <$> get case ma'' of Nothing -> modify $ second $ second $ Map.insert a a' Just a'' -> guard $ a' == a'' instance WithinAlignable ShallowType where withinAlign t t' = case (t,t') of (SFunction a1 a2, SFunction a1' a2') -> withinAlign a1 a1' >> withinAlign a2 a2' (SFunction _ _, _) -> mzero (STrigger a, STrigger a') -> withinAlign a a' (STrigger _, _) -> mzero (SBool, SBool) -> success (SBool, _) -> mzero (SInt, SInt) -> success (SInt, _) -> mzero (SReal, SReal) -> success (SReal, _) -> mzero (SNumber, SNumber) -> success (SNumber, _) -> mzero (SString, SString) -> success (SString, _) -> mzero (SAddress, SAddress) -> success (SAddress, _) -> mzero (SOption qa, SOption qa') -> withinAlign qa qa' (SOption _, _) -> mzero (SIndirection qa, SIndirection qa') -> withinAlign qa qa' (SIndirection _, _) -> mzero (STuple qas, STuple qas') -> do guard $ length qas == length qas' mconcat <$> zipWithM withinAlign qas qas' (STuple _, _) -> mzero (SRecord m oas _, SRecord m' oas' _) -> do guard $ oas == oas' guard $ Map.keys m == Map.keys m' mconcat <$> mapM (uncurry withinAlign) (Map.elems $ Map.intersectionWith (,) m m') (SRecord _ _ _, _) -> mzero (STop, STop) -> success (STop, _) -> mzero (SBottom, SBottom) -> success (SBottom, _) -> mzero (SOpaque oa, SOpaque oa') -> guard $ oa == oa' (SOpaque _, _) -> mzero
DaMSL/K3
src/Language/K3/TypeSystem/Within.hs
apache-2.0
10,449
0
19
2,911
2,764
1,450
1,314
215
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -- | Make changes to the stack yaml file module Stack.ConfigCmd (ConfigCmdSet(..) ,cfgCmdSet ,cfgCmdSetName ,cfgCmdName) where import Control.Monad.Catch (MonadMask, throwM) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Control (MonadBaseControl) import qualified Data.ByteString as S import qualified Data.HashMap.Strict as HMap import qualified Data.Yaml.Extra as Yaml import Network.HTTP.Client.Conduit (HasHttpManager) import Path import Stack.BuildPlan import Stack.Config (makeConcreteResolver) import Stack.Types.BuildPlan import Stack.Types.Config data ConfigCmdSet = ConfigCmdSetResolver AbstractResolver cfgCmdSet :: ( MonadIO m , MonadBaseControl IO m , MonadMask m , MonadReader env m , HasBuildConfig env , HasHttpManager env , HasGHCVariant env , MonadLogger m) => ConfigCmdSet -> m () cfgCmdSet (ConfigCmdSetResolver newResolver) = do stackYaml <- fmap bcStackYaml (asks getBuildConfig) let stackYamlFp = toFilePath stackYaml -- We don't need to worry about checking for a valid yaml here (projectYamlConfig :: Yaml.Object) <- liftIO (Yaml.decodeFileEither stackYamlFp) >>= either throwM return -- TODO: custom snapshot support? newResolverText <- fmap resolverName (makeConcreteResolver newResolver) -- We checking here that the snapshot actually exists snap <- parseSnapName newResolverText _ <- loadMiniBuildPlan snap let projectYamlConfig' = HMap.insert "resolver" (Yaml.String newResolverText) projectYamlConfig liftIO (S.writeFile stackYamlFp (Yaml.encode projectYamlConfig')) return () cfgCmdName :: String cfgCmdName = "config" cfgCmdSetName :: String cfgCmdSetName = "set"
AndrewRademacher/stack
src/Stack/ConfigCmd.hs
bsd-3-clause
2,210
0
13
625
426
236
190
56
1
module B1.Program.Chart.Dirty ( Dirty(..) ) where type Dirty = Bool
madjestic/b1
src/B1/Program/Chart/Dirty.hs
bsd-3-clause
73
0
5
15
23
16
7
3
0
{-# LANGUAGE DeriveGeneric #-} -- | The type of kinds of game modes. module Game.LambdaHack.Content.ModeKind ( Caves, Roster(..), Player(..), ModeKind(..), LeaderMode(..), AutoLeader(..) , Outcome(..), HiIndeterminant(..), HiCondPoly, HiSummand, HiPolynomial , validateSingleModeKind, validateAllModeKind ) where import Data.Binary import qualified Data.EnumMap.Strict as EM import qualified Data.IntMap.Strict as IM import Data.Text (Text) import qualified Data.Text as T import GHC.Generics (Generic) import qualified NLP.Miniutter.English as MU () import Game.LambdaHack.Common.Ability import qualified Game.LambdaHack.Common.Dice as Dice import Game.LambdaHack.Common.Misc import Game.LambdaHack.Common.Msg import Game.LambdaHack.Content.CaveKind import Game.LambdaHack.Content.ItemKind (ItemKind) -- | Game mode specification. data ModeKind = ModeKind { msymbol :: !Char -- ^ a symbol (matches the keypress, if any) , mname :: !Text -- ^ short description , mfreq :: !(Freqs ModeKind) -- ^ frequency within groups , mroster :: !Roster -- ^ players taking part in the game , mcaves :: !Caves -- ^ arena of the game , mdesc :: !Text -- ^ description } deriving Show -- | Requested cave groups for particular levels. The second component -- is the @Escape@ feature on the level. @True@ means it's represented -- by @<@, @False@, by @>@. type Caves = IM.IntMap (GroupName CaveKind, Maybe Bool) -- | The specification of players for the game mode. data Roster = Roster { rosterList :: ![Player Dice.Dice] -- ^ players in the particular team , rosterEnemy :: ![(Text, Text)] -- ^ the initial enmity matrix , rosterAlly :: ![(Text, Text)] -- ^ the initial aliance matrix } deriving (Show, Eq) -- | Outcome of a game. data Outcome = Killed -- ^ the faction was eliminated | Defeated -- ^ the faction lost the game in another way | Camping -- ^ game is supended | Conquer -- ^ the player won by eliminating all rivals | Escape -- ^ the player escaped the dungeon alive | Restart -- ^ game is restarted deriving (Show, Eq, Ord, Enum, Bounded, Generic) instance Binary Outcome data HiIndeterminant = HiConst | HiLoot | HiBlitz | HiSurvival | HiKill | HiLoss deriving (Show, Eq, Ord, Generic) instance Binary HiIndeterminant type HiPolynomial = [(HiIndeterminant, Double)] type HiSummand = (HiPolynomial, [Outcome]) -- | Conditional polynomial representing score calculation for this player. type HiCondPoly = [HiSummand] -- | Properties of a particular player. data Player a = Player { fname :: !Text -- ^ name of the player , fgroup :: !(GroupName ItemKind) -- ^ name of the monster group to control , fskillsOther :: !Skills -- ^ fixed skill modifiers to the non-leader -- actors; also summed with skills implied -- by ftactic (which is not fixed) , fcanEscape :: !Bool -- ^ the player can escape the dungeon , fneverEmpty :: !Bool -- ^ the faction declared killed if no actors , fhiCondPoly :: !HiCondPoly -- ^ score polynomial for the player , fhasNumbers :: !Bool -- ^ whether actors have numbers, not symbols , fhasGender :: !Bool -- ^ whether actors have gender , ftactic :: !Tactic -- ^ non-leader behave according to this -- tactic; can be changed during the game , fentryLevel :: !a -- ^ level where the initial members start , finitialActors :: !a -- ^ number of initial members , fleaderMode :: !LeaderMode -- ^ the mode of switching the leader , fhasUI :: !Bool -- ^ does the faction have a UI client -- (for control or passive observation) } deriving (Show, Eq, Ord, Generic) instance Binary a => Binary (Player a) -- | If a faction with @LeaderUI@ and @LeaderAI@ has any actor, it has a leader. data LeaderMode = LeaderNull -- ^ faction can have no leader, is whole under AI control | LeaderAI AutoLeader -- ^ leader under AI control | LeaderUI AutoLeader -- ^ leader under UI control, assumes @fhasUI@ deriving (Show, Eq, Ord, Generic) instance Binary LeaderMode data AutoLeader = AutoLeader { autoDungeon :: !Bool -- ^ leader switching between levels is automatically done by the server -- and client is not permitted to change to leaders from other levels -- (the frequency of leader level switching done by the server -- is controlled by @RuleKind.rleadLevelClips@); -- if the flag is @False@, server still does a subset -- of the automatic switching, e.g., when the old leader dies -- and no other actor of the faction resides on his level, -- but the client (particularly UI) is expected to do changes as well , autoLevel :: !Bool -- ^ leader switching within a level is automatically done by the server -- and client is not permitted to change leaders -- (server is guaranteed to switch leader within a level very rarely, -- e.g., when the old leader dies); -- if the flag is @False@, server still does a subset -- of the automatic switching, but the client is permitted to do more } deriving (Show, Eq, Ord, Generic) instance Binary AutoLeader -- TODO: (spans multiple contents) Check that caves with the given groups exist. -- | Catch invalid game mode kind definitions. validateSingleModeKind :: ModeKind -> [Text] validateSingleModeKind ModeKind{..} = [ "mname longer than 20" | T.length mname > 20 ] ++ validateSingleRoster mcaves mroster -- TODO: if the diplomacy system stays in, check no teams are at once -- in war and alliance, taking into account symmetry (but not transitvity) -- | Checks, in particular, that there is at least one faction with fneverEmpty -- or the game could get stuck when the dungeon is devoid of actors validateSingleRoster :: Caves -> Roster -> [Text] validateSingleRoster caves Roster{..} = [ "no player keeps the dungeon alive" | all (not . fneverEmpty) rosterList ] ++ concatMap (validateSinglePlayer caves) rosterList ++ let checkPl field pl = [ pl <+> "is not a player name in" <+> field | all ((/= pl) . fname) rosterList ] checkDipl field (pl1, pl2) = [ "self-diplomacy in" <+> field | pl1 == pl2 ] ++ checkPl field pl1 ++ checkPl field pl2 in concatMap (checkDipl "rosterEnemy") rosterEnemy ++ concatMap (checkDipl "rosterAlly") rosterAlly validateSinglePlayer :: Caves -> Player Dice.Dice -> [Text] validateSinglePlayer caves Player{..} = [ "fname empty:" <+> fname | T.null fname ] ++ [ "first word of fname longer than 15:" <+> fname | T.length (head $ T.words fname) > 15 ] ++ [ "no UI client, but UI leader:" <+> fname | not fhasUI && case fleaderMode of LeaderUI _ -> True _ -> False ] ++ [ "fentryLevel value not among cave numbers:" <+> fname | any (`notElem` IM.keys caves) [Dice.minDice fentryLevel .. Dice.maxDice fentryLevel] ] -- simplification ++ [ "fskillsOther not negative:" <+> fname | any (>= 0) $ EM.elems fskillsOther ] -- | Validate all game mode kinds. Currently always valid. validateAllModeKind :: [ModeKind] -> [Text] validateAllModeKind _ = []
Concomitant/LambdaHack
Game/LambdaHack/Content/ModeKind.hs
bsd-3-clause
7,476
0
16
1,852
1,265
743
522
-1
-1
----------------------------------------------------------------------------- -- | -- Module : Plugins.Monitors.MPD -- Copyright : (c) Jose A Ortega Ruiz -- License : BSD-style (see LICENSE) -- -- Maintainer : Jose A Ortega Ruiz <[email protected]> -- Stability : unstable -- Portability : unportable -- -- MPD status and song -- ----------------------------------------------------------------------------- module Plugins.Monitors.MPD ( mpdConfig, runMPD, mpdWait, mpdReady ) where import Data.List import Data.Maybe (fromMaybe) import Plugins.Monitors.Common import System.Console.GetOpt import qualified Network.MPD as M import Control.Concurrent (threadDelay) mpdConfig :: IO MConfig mpdConfig = mkMConfig "MPD: <state>" [ "bar", "vbar", "ipat", "state", "statei", "volume", "length" , "lapsed", "remaining", "plength", "ppos", "flags", "file" , "name", "artist", "composer", "performer" , "album", "title", "track", "genre" ] data MOpts = MOpts { mPlaying :: String , mStopped :: String , mPaused :: String , mLapsedIconPattern :: Maybe IconPattern } defaultOpts :: MOpts defaultOpts = MOpts { mPlaying = ">>" , mStopped = "><" , mPaused = "||" , mLapsedIconPattern = Nothing } options :: [OptDescr (MOpts -> MOpts)] options = [ Option "P" ["playing"] (ReqArg (\x o -> o { mPlaying = x }) "") "" , Option "S" ["stopped"] (ReqArg (\x o -> o { mStopped = x }) "") "" , Option "Z" ["paused"] (ReqArg (\x o -> o { mPaused = x }) "") "" , Option "" ["lapsed-icon-pattern"] (ReqArg (\x o -> o { mLapsedIconPattern = Just $ parseIconPattern x }) "") "" ] runMPD :: [String] -> Monitor String runMPD args = do opts <- io $ mopts args status <- io $ M.withMPD M.status song <- io $ M.withMPD M.currentSong s <- parseMPD status song opts parseTemplate s mpdWait :: IO () mpdWait = do status <- M.withMPD $ M.idle [M.PlayerS, M.MixerS, M.OptionsS] case status of Left _ -> threadDelay 10000000 _ -> return () mpdReady :: [String] -> Monitor Bool mpdReady _ = do response <- io $ M.withMPD M.ping case response of Right _ -> return True -- Only cases where MPD isn't responding is an issue; bogus information at -- least won't hold xmobar up. Left M.NoMPD -> return False Left (M.ConnectionError _) -> return False Left _ -> return True mopts :: [String] -> IO MOpts mopts argv = case getOpt Permute options argv of (o, _, []) -> return $ foldr id defaultOpts o (_, _, errs) -> ioError . userError $ concat errs parseMPD :: M.Response M.Status -> M.Response (Maybe M.Song) -> MOpts -> Monitor [String] parseMPD (Left e) _ _ = return $ show e:replicate 19 "" parseMPD (Right st) song opts = do songData <- parseSong song bar <- showPercentBar (100 * b) b vbar <- showVerticalBar (100 * b) b ipat <- showIconPattern (mLapsedIconPattern opts) b return $ [bar, vbar, ipat, ss, si, vol, len, lap, remain, plen, ppos, flags] ++ songData where s = M.stState st ss = show s si = stateGlyph s opts vol = int2str $ fromMaybe 0 (M.stVolume st) (p, t) = fromMaybe (0, 0) (M.stTime st) [lap, len, remain] = map showTime [floor p, t, max 0 (t - floor p)] b = if t > 0 then realToFrac $ p / fromIntegral t else 0 plen = int2str $ M.stPlaylistLength st ppos = maybe "" (int2str . (+1)) $ M.stSongPos st flags = playbackMode st stateGlyph :: M.State -> MOpts -> String stateGlyph s o = case s of M.Playing -> mPlaying o M.Paused -> mPaused o M.Stopped -> mStopped o playbackMode :: M.Status -> String playbackMode s = concat [if p s then f else "-" | (p,f) <- [(M.stRepeat,"r"), (M.stRandom,"z"), (M.stSingle,"s"), (M.stConsume,"c")]] parseSong :: M.Response (Maybe M.Song) -> Monitor [String] parseSong (Left _) = return $ repeat "" parseSong (Right Nothing) = return $ repeat "" parseSong (Right (Just s)) = let str sel = maybe "" (intercalate ", " . map M.toString) (M.sgGetTag sel s) sels = [ M.Name, M.Artist, M.Composer, M.Performer , M.Album, M.Title, M.Track, M.Genre ] fields = M.toString (M.sgFilePath s) : map str sels in mapM showWithPadding fields showTime :: Integer -> String showTime t = int2str minutes ++ ":" ++ int2str seconds where minutes = t `div` 60 seconds = t `mod` 60 int2str :: (Show a, Num a, Ord a) => a -> String int2str x = if x < 10 then '0':sx else sx where sx = show x
bysy/xmobar
src/Plugins/Monitors/MPD.hs
bsd-3-clause
4,616
0
14
1,153
1,699
907
792
104
4
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} module RedBlackSet where import Test.SmartCheck(SubTypes) import GHC.Generics import Data.Typeable import Prelude hiding (max) data Color = R -- red | B -- black | BB -- double black | NB -- negative black deriving (Show, Read, Typeable, Generic) data RBSet a = E -- black leaf | EE -- double black leaf | T Color (RBSet a) a (RBSet a) deriving (Show, Read, Typeable, Generic) -- Private auxiliary functions -- redden :: RBSet a -> RBSet a redden E = error "cannot redden empty tree" redden EE = error "cannot redden empty tree" redden (T _ a x b) = T R a x b blacken :: RBSet a -> RBSet a blacken E = E blacken EE = E blacken (T _ a x b) = T B a x b isBB :: RBSet a -> Bool isBB EE = True isBB (T BB _ _ _) = True isBB _ = False blacker :: Color -> Color blacker NB = R blacker R = B blacker B = BB blacker BB = error "too black" redder :: Color -> Color redder NB = error "not black enough" redder R = NB redder B = R redder BB = B blacker' :: RBSet a -> RBSet a blacker' E = EE blacker' (T c l x r) = T (blacker c) l x r redder' :: RBSet a -> RBSet a redder' EE = E redder' (T c l x r) = T (redder c) l x r -- `balance` rotates away coloring conflicts: balance :: Color -> RBSet a -> a -> RBSet a -> RBSet a -- Okasaki's original cases: balance B (T R (T R a x b) y c) z d = T R (T B a x b) y (T B c z d) balance B (T R a x (T R b y c)) z d = T R (T B a x b) y (T B c z d) balance B a x (T R (T R b y c) z d) = T R (T B a x b) y (T B c z d) balance B a x (T R b y (T R c z d)) = T R (T B a x b) y (T B c z d) -- Six cases for deletion: balance BB (T R (T R a x b) y c) z d = T B (T B a x b) y (T B c z d) balance BB (T R a x (T R b y c)) z d = T B (T B a x b) y (T B c z d) balance BB a x (T R (T R b y c) z d) = T B (T B a x b) y (T B c z d) balance BB a x (T R b y (T R c z d)) = T B (T B a x b) y (T B c z d) balance BB a x (T NB (T B b y c) z d@(T B _ _ _)) = T B (T B a x b) y (balance B c z (redden d)) balance BB (T NB a@(T B _ _ _) x (T B b y c)) z d = T B (balance B (redden a) x b) y (T B c z d) balance color a x b = T color a x b -- `bubble` "bubbles" double-blackness upward: bubble :: Color -> RBSet a -> a -> RBSet a -> RBSet a bubble color l x r | isBB(l) || isBB(r) = balance (blacker color) (redder' l) x (redder' r) | otherwise = balance color l x r -- Public operations -- empty :: RBSet a empty = E member :: (Ord a) => a -> RBSet a -> Bool member x E = False member x (T _ l y r) | x < y = member x l | x > y = member x r | otherwise = True max :: RBSet a -> a max E = error "no largest element" max (T _ _ x E) = x max (T _ _ x r) = max r -- Insertion: insert :: (Ord a) => a -> RBSet a -> RBSet a insert x s = blacken (ins s) where ins E = T R E x E ins s@(T color a y b) | x < y = balance color (ins a) y b | x > y = balance color a y (ins b) | otherwise = s -- Deletion: delete :: (Ord a,Show a) => a -> RBSet a -> RBSet a delete x s = blacken(del s) where del E = E del s@(T color a y b) | x < y = bubble color (del a) y b | x > y = bubble color a y (del b) | otherwise = remove s remove :: RBSet a -> RBSet a remove E = E remove (T R E _ E) = E remove (T B E _ E) = EE remove (T B E _ (T R a x b)) = T B a x b remove (T B (T R a x b) _ E) = T B a x b remove (T color l y r) = bubble color l' mx r where mx = max l l' = removeMax l removeMax :: RBSet a -> RBSet a removeMax E = error "no maximum to remove" removeMax s@(T _ _ _ E) = remove s removeMax s@(T color l x r) = bubble color l x (removeMax r) -- Conversion: toAscList :: RBSet a -> [a] toAscList E = [] toAscList (T _ l x r) = (toAscList l) ++ [x] ++ (toAscList r) -- Equality instance Eq a => Eq (RBSet a) where rb == rb' = (toAscList rb) == (toAscList rb')
markus1189/SmartCheck
examples/RedBlackTrees/RedBlackSet.hs
bsd-3-clause
4,031
0
10
1,304
2,311
1,147
1,164
105
2
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "dist/dist-sandbox-261cd265/build/System/Posix/User.hs" #-} {-# LINE 1 "System/Posix/User.hsc" #-} {-# LANGUAGE Trustworthy, CApiFFI #-} {-# LINE 2 "System/Posix/User.hsc" #-} ----------------------------------------------------------------------------- -- | -- Module : System.Posix.User -- Copyright : (c) The University of Glasgow 2002 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : non-portable (requires POSIX) -- -- POSIX user\/group support -- ----------------------------------------------------------------------------- module System.Posix.User ( -- * User environment -- ** Querying the user environment getRealUserID, getRealGroupID, getEffectiveUserID, getEffectiveGroupID, getGroups, getLoginName, getEffectiveUserName, -- *** The group database GroupEntry(..), getGroupEntryForID, getGroupEntryForName, getAllGroupEntries, -- *** The user database UserEntry(..), getUserEntryForID, getUserEntryForName, getAllUserEntries, -- ** Modifying the user environment setUserID, setGroupID, setEffectiveUserID, setEffectiveGroupID, setGroups ) where {-# LINE 49 "System/Posix/User.hsc" #-} import System.Posix.Types import System.IO.Unsafe (unsafePerformIO) import Foreign.C import Foreign.Ptr import Foreign.Marshal import Foreign.Storable {-# LINE 58 "System/Posix/User.hsc" #-} import Control.Concurrent.MVar ( MVar, newMVar, withMVar ) {-# LINE 60 "System/Posix/User.hsc" #-} {-# LINE 61 "System/Posix/User.hsc" #-} import Control.Exception {-# LINE 63 "System/Posix/User.hsc" #-} import Control.Monad import System.IO.Error -- internal types data {-# CTYPE "struct passwd" #-} CPasswd data {-# CTYPE "struct group" #-} CGroup -- ----------------------------------------------------------------------------- -- user environemnt -- | @getRealUserID@ calls @getuid@ to obtain the real @UserID@ -- associated with the current process. getRealUserID :: IO UserID getRealUserID = c_getuid foreign import ccall unsafe "getuid" c_getuid :: IO CUid -- | @getRealGroupID@ calls @getgid@ to obtain the real @GroupID@ -- associated with the current process. getRealGroupID :: IO GroupID getRealGroupID = c_getgid foreign import ccall unsafe "getgid" c_getgid :: IO CGid -- | @getEffectiveUserID@ calls @geteuid@ to obtain the effective -- @UserID@ associated with the current process. getEffectiveUserID :: IO UserID getEffectiveUserID = c_geteuid foreign import ccall unsafe "geteuid" c_geteuid :: IO CUid -- | @getEffectiveGroupID@ calls @getegid@ to obtain the effective -- @GroupID@ associated with the current process. getEffectiveGroupID :: IO GroupID getEffectiveGroupID = c_getegid foreign import ccall unsafe "getegid" c_getegid :: IO CGid -- | @getGroups@ calls @getgroups@ to obtain the list of -- supplementary @GroupID@s associated with the current process. getGroups :: IO [GroupID] getGroups = do ngroups <- c_getgroups 0 nullPtr allocaArray (fromIntegral ngroups) $ \arr -> do throwErrnoIfMinus1_ "getGroups" (c_getgroups ngroups arr) groups <- peekArray (fromIntegral ngroups) arr return groups foreign import ccall unsafe "getgroups" c_getgroups :: CInt -> Ptr CGid -> IO CInt -- | @setGroups@ calls @setgroups@ to set the list of -- supplementary @GroupID@s associated with the current process. setGroups :: [GroupID] -> IO () setGroups groups = do withArrayLen groups $ \ ngroups arr -> throwErrnoIfMinus1_ "setGroups" (c_setgroups (fromIntegral ngroups) arr) foreign import ccall unsafe "setgroups" c_setgroups :: CInt -> Ptr CGid -> IO CInt -- | @getLoginName@ calls @getlogin@ to obtain the login name -- associated with the current process. getLoginName :: IO String getLoginName = do -- ToDo: use getlogin_r str <- throwErrnoIfNull "getLoginName" c_getlogin peekCAString str foreign import ccall unsafe "getlogin" c_getlogin :: IO CString -- | @setUserID uid@ calls @setuid@ to set the real, effective, and -- saved set-user-id associated with the current process to @uid@. setUserID :: UserID -> IO () setUserID uid = throwErrnoIfMinus1_ "setUserID" (c_setuid uid) foreign import ccall unsafe "setuid" c_setuid :: CUid -> IO CInt -- | @setEffectiveUserID uid@ calls @seteuid@ to set the effective -- user-id associated with the current process to @uid@. This -- does not update the real user-id or set-user-id. setEffectiveUserID :: UserID -> IO () setEffectiveUserID uid = throwErrnoIfMinus1_ "setEffectiveUserID" (c_seteuid uid) foreign import ccall unsafe "seteuid" c_seteuid :: CUid -> IO CInt -- | @setGroupID gid@ calls @setgid@ to set the real, effective, and -- saved set-group-id associated with the current process to @gid@. setGroupID :: GroupID -> IO () setGroupID gid = throwErrnoIfMinus1_ "setGroupID" (c_setgid gid) foreign import ccall unsafe "setgid" c_setgid :: CGid -> IO CInt -- | @setEffectiveGroupID uid@ calls @setegid@ to set the effective -- group-id associated with the current process to @gid@. This -- does not update the real group-id or set-group-id. setEffectiveGroupID :: GroupID -> IO () setEffectiveGroupID gid = throwErrnoIfMinus1_ "setEffectiveGroupID" (c_setegid gid) foreign import ccall unsafe "setegid" c_setegid :: CGid -> IO CInt -- ----------------------------------------------------------------------------- -- User names -- | @getEffectiveUserName@ gets the name -- associated with the effective @UserID@ of the process. getEffectiveUserName :: IO String getEffectiveUserName = do euid <- getEffectiveUserID pw <- getUserEntryForID euid return (userName pw) -- ----------------------------------------------------------------------------- -- The group database (grp.h) data GroupEntry = GroupEntry { groupName :: String, -- ^ The name of this group (gr_name) groupPassword :: String, -- ^ The password for this group (gr_passwd) groupID :: GroupID, -- ^ The unique numeric ID for this group (gr_gid) groupMembers :: [String] -- ^ A list of zero or more usernames that are members (gr_mem) } deriving (Show, Read, Eq) -- | @getGroupEntryForID gid@ calls @getgrgid_r@ to obtain -- the @GroupEntry@ information associated with @GroupID@ -- @gid@. This operation may fail with 'isDoesNotExistError' -- if no such group exists. getGroupEntryForID :: GroupID -> IO GroupEntry {-# LINE 206 "System/Posix/User.hsc" #-} getGroupEntryForID gid = allocaBytes (32) $ \pgr -> {-# LINE 208 "System/Posix/User.hsc" #-} doubleAllocWhileERANGE "getGroupEntryForID" "group" grBufSize unpackGroupEntry $ c_getgrgid_r gid pgr foreign import capi unsafe "HsUnix.h getgrgid_r" c_getgrgid_r :: CGid -> Ptr CGroup -> CString -> CSize -> Ptr (Ptr CGroup) -> IO CInt {-# LINE 217 "System/Posix/User.hsc" #-} -- | @getGroupEntryForName name@ calls @getgrnam_r@ to obtain -- the @GroupEntry@ information associated with the group called -- @name@. This operation may fail with 'isDoesNotExistError' -- if no such group exists. getGroupEntryForName :: String -> IO GroupEntry {-# LINE 224 "System/Posix/User.hsc" #-} getGroupEntryForName name = allocaBytes (32) $ \pgr -> {-# LINE 226 "System/Posix/User.hsc" #-} withCAString name $ \ pstr -> doubleAllocWhileERANGE "getGroupEntryForName" "group" grBufSize unpackGroupEntry $ c_getgrnam_r pstr pgr foreign import capi unsafe "HsUnix.h getgrnam_r" c_getgrnam_r :: CString -> Ptr CGroup -> CString -> CSize -> Ptr (Ptr CGroup) -> IO CInt {-# LINE 236 "System/Posix/User.hsc" #-} -- | @getAllGroupEntries@ returns all group entries on the system by -- repeatedly calling @getgrent@ -- -- getAllGroupEntries may fail with isDoesNotExistError on Linux due to -- this bug in glibc: -- http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=466647 -- getAllGroupEntries :: IO [GroupEntry] {-# LINE 247 "System/Posix/User.hsc" #-} getAllGroupEntries = withMVar lock $ \_ -> bracket_ c_setgrent c_endgrent $ worker [] where worker accum = do resetErrno ppw <- throwErrnoIfNullAndError "getAllGroupEntries" $ c_getgrent if ppw == nullPtr then return (reverse accum) else do thisentry <- unpackGroupEntry ppw worker (thisentry : accum) foreign import ccall unsafe "getgrent" c_getgrent :: IO (Ptr CGroup) foreign import ccall unsafe "setgrent" c_setgrent :: IO () foreign import ccall unsafe "endgrent" c_endgrent :: IO () {-# LINE 267 "System/Posix/User.hsc" #-} {-# LINE 269 "System/Posix/User.hsc" #-} grBufSize :: Int {-# LINE 271 "System/Posix/User.hsc" #-} grBufSize = sysconfWithDefault 1024 (69) {-# LINE 272 "System/Posix/User.hsc" #-} {-# LINE 275 "System/Posix/User.hsc" #-} {-# LINE 276 "System/Posix/User.hsc" #-} unpackGroupEntry :: Ptr CGroup -> IO GroupEntry unpackGroupEntry ptr = do name <- ((\hsc_ptr -> peekByteOff hsc_ptr 0)) ptr >>= peekCAString {-# LINE 280 "System/Posix/User.hsc" #-} passwd <- ((\hsc_ptr -> peekByteOff hsc_ptr 8)) ptr >>= peekCAString {-# LINE 281 "System/Posix/User.hsc" #-} gid <- ((\hsc_ptr -> peekByteOff hsc_ptr 16)) ptr {-# LINE 282 "System/Posix/User.hsc" #-} mem <- ((\hsc_ptr -> peekByteOff hsc_ptr 24)) ptr {-# LINE 283 "System/Posix/User.hsc" #-} members <- peekArray0 nullPtr mem >>= mapM peekCAString return (GroupEntry name passwd gid members) -- ----------------------------------------------------------------------------- -- The user database (pwd.h) data UserEntry = UserEntry { userName :: String, -- ^ Textual name of this user (pw_name) userPassword :: String, -- ^ Password -- may be empty or fake if shadow is in use (pw_passwd) userID :: UserID, -- ^ Numeric ID for this user (pw_uid) userGroupID :: GroupID, -- ^ Primary group ID (pw_gid) userGecos :: String, -- ^ Usually the real name for the user (pw_gecos) homeDirectory :: String, -- ^ Home directory (pw_dir) userShell :: String -- ^ Default shell (pw_shell) } deriving (Show, Read, Eq) -- -- getpwuid and getpwnam leave results in a static object. Subsequent -- calls modify the same object, which isn't threadsafe. We attempt to -- mitigate this issue, on platforms that don't provide the safe _r versions -- -- Also, getpwent/setpwent require a global lock since they maintain -- an internal file position pointer. {-# LINE 308 "System/Posix/User.hsc" #-} lock :: MVar () lock = unsafePerformIO $ newMVar () {-# NOINLINE lock #-} {-# LINE 312 "System/Posix/User.hsc" #-} -- | @getUserEntryForID gid@ calls @getpwuid_r@ to obtain -- the @UserEntry@ information associated with @UserID@ -- @uid@. This operation may fail with 'isDoesNotExistError' -- if no such user exists. getUserEntryForID :: UserID -> IO UserEntry {-# LINE 319 "System/Posix/User.hsc" #-} getUserEntryForID uid = allocaBytes (48) $ \ppw -> {-# LINE 321 "System/Posix/User.hsc" #-} doubleAllocWhileERANGE "getUserEntryForID" "user" pwBufSize unpackUserEntry $ c_getpwuid_r uid ppw foreign import capi unsafe "HsUnix.h getpwuid_r" c_getpwuid_r :: CUid -> Ptr CPasswd -> CString -> CSize -> Ptr (Ptr CPasswd) -> IO CInt {-# LINE 338 "System/Posix/User.hsc" #-} -- | @getUserEntryForName name@ calls @getpwnam_r@ to obtain -- the @UserEntry@ information associated with the user login -- @name@. This operation may fail with 'isDoesNotExistError' -- if no such user exists. getUserEntryForName :: String -> IO UserEntry {-# LINE 345 "System/Posix/User.hsc" #-} getUserEntryForName name = allocaBytes (48) $ \ppw -> {-# LINE 347 "System/Posix/User.hsc" #-} withCAString name $ \ pstr -> doubleAllocWhileERANGE "getUserEntryForName" "user" pwBufSize unpackUserEntry $ c_getpwnam_r pstr ppw foreign import capi unsafe "HsUnix.h getpwnam_r" c_getpwnam_r :: CString -> Ptr CPasswd -> CString -> CSize -> Ptr (Ptr CPasswd) -> IO CInt {-# LINE 366 "System/Posix/User.hsc" #-} -- | @getAllUserEntries@ returns all user entries on the system by -- repeatedly calling @getpwent@ getAllUserEntries :: IO [UserEntry] {-# LINE 371 "System/Posix/User.hsc" #-} getAllUserEntries = withMVar lock $ \_ -> bracket_ c_setpwent c_endpwent $ worker [] where worker accum = do resetErrno ppw <- throwErrnoIfNullAndError "getAllUserEntries" $ c_getpwent if ppw == nullPtr then return (reverse accum) else do thisentry <- unpackUserEntry ppw worker (thisentry : accum) foreign import capi unsafe "HsUnix.h getpwent" c_getpwent :: IO (Ptr CPasswd) foreign import capi unsafe "HsUnix.h setpwent" c_setpwent :: IO () foreign import capi unsafe "HsUnix.h endpwent" c_endpwent :: IO () {-# LINE 391 "System/Posix/User.hsc" #-} {-# LINE 393 "System/Posix/User.hsc" #-} pwBufSize :: Int {-# LINE 395 "System/Posix/User.hsc" #-} pwBufSize = sysconfWithDefault 1024 (70) {-# LINE 396 "System/Posix/User.hsc" #-} {-# LINE 399 "System/Posix/User.hsc" #-} {-# LINE 400 "System/Posix/User.hsc" #-} {-# LINE 402 "System/Posix/User.hsc" #-} foreign import ccall unsafe "sysconf" c_sysconf :: CInt -> IO CLong -- We need a default value since sysconf can fail and return -1 -- even when the parameter name is defined in unistd.h. -- One example of this is _SC_GETPW_R_SIZE_MAX under -- Mac OS X 10.4.9 on i386. sysconfWithDefault :: Int -> CInt -> Int sysconfWithDefault def sc = unsafePerformIO $ do v <- fmap fromIntegral $ c_sysconf sc return $ if v == (-1) then def else v {-# LINE 414 "System/Posix/User.hsc" #-} -- The following function is used by the getgr*_r, c_getpw*_r -- families of functions. These functions return their result -- in a struct that contains strings and they need a buffer -- that they can use to store those strings. We have to be -- careful to unpack the struct containing the result before -- the buffer is deallocated. doubleAllocWhileERANGE :: String -> String -- entry type: "user" or "group" -> Int -> (Ptr r -> IO a) -> (Ptr b -> CSize -> Ptr (Ptr r) -> IO CInt) -> IO a doubleAllocWhileERANGE loc enttype initlen unpack action = alloca $ go initlen where go len res = do r <- allocaBytes len $ \buf -> do rc <- action buf (fromIntegral len) res if rc /= 0 then return (Left rc) else do p <- peek res when (p == nullPtr) $ notFoundErr fmap Right (unpack p) case r of Right x -> return x Left rc | Errno rc == eRANGE -> -- ERANGE means this is not an error -- we just have to try again with a larger buffer go (2 * len) res Left rc -> ioError (errnoToIOError loc (Errno rc) Nothing Nothing) notFoundErr = ioError $ flip ioeSetErrorString ("no such " ++ enttype) $ mkIOError doesNotExistErrorType loc Nothing Nothing unpackUserEntry :: Ptr CPasswd -> IO UserEntry unpackUserEntry ptr = do name <- ((\hsc_ptr -> peekByteOff hsc_ptr 0)) ptr >>= peekCAString {-# LINE 454 "System/Posix/User.hsc" #-} passwd <- ((\hsc_ptr -> peekByteOff hsc_ptr 8)) ptr >>= peekCAString {-# LINE 455 "System/Posix/User.hsc" #-} uid <- ((\hsc_ptr -> peekByteOff hsc_ptr 16)) ptr {-# LINE 456 "System/Posix/User.hsc" #-} gid <- ((\hsc_ptr -> peekByteOff hsc_ptr 20)) ptr {-# LINE 457 "System/Posix/User.hsc" #-} {-# LINE 460 "System/Posix/User.hsc" #-} gecos <- ((\hsc_ptr -> peekByteOff hsc_ptr 24)) ptr >>= peekCAString {-# LINE 461 "System/Posix/User.hsc" #-} {-# LINE 462 "System/Posix/User.hsc" #-} dir <- ((\hsc_ptr -> peekByteOff hsc_ptr 32)) ptr >>= peekCAString {-# LINE 463 "System/Posix/User.hsc" #-} shell <- ((\hsc_ptr -> peekByteOff hsc_ptr 40)) ptr >>= peekCAString {-# LINE 464 "System/Posix/User.hsc" #-} return (UserEntry name passwd uid gid gecos dir shell) -- Used when a function returns NULL to indicate either an error or -- EOF, depending on whether the global errno is nonzero. throwErrnoIfNullAndError :: String -> IO (Ptr a) -> IO (Ptr a) throwErrnoIfNullAndError loc act = do rc <- act errno <- getErrno if rc == nullPtr && errno /= eOK then throwErrno loc else return rc
phischu/fragnix
tests/packages/scotty/System.Posix.User.hs
bsd-3-clause
16,733
10
20
3,457
2,835
1,515
1,320
-1
-1
module TestData where import Data.IntMap as IMap import Data.Map.Strict as Map import Data.Set as Set data Codegen = C | JS deriving (Show, Eq, Ord) type Index = Int data CompatCodegen = ANY | C_CG | NODE_CG | NONE -- A TestFamily groups tests that share the same theme data TestFamily = TestFamily { -- A shorter lowcase name to use in filenames id :: String, -- A proper name for the test family that will be displayed name :: String, -- A map of test metadata: -- - The key is the index (>=1 && <1000) -- - The value is the set of compatible code generators, -- or Nothing if the test doesn't depend on a code generator tests :: IntMap (Maybe (Set Codegen)) } deriving (Show) toCodegenSet :: CompatCodegen -> Maybe (Set Codegen) toCodegenSet compatCodegen = fmap Set.fromList mList where mList = case compatCodegen of ANY -> Just [ C, JS ] C_CG -> Just [ C ] NODE_CG -> Just [ JS ] NONE -> Nothing testFamilies :: [TestFamily] testFamilies = fmap instantiate testFamiliesData where instantiate (id, name, testsData) = TestFamily id name tests where tests = IMap.fromList (fmap makeSetCodegen testsData) makeSetCodegen (index, codegens) = (index, toCodegenSet codegens) testFamiliesForCodegen :: Codegen -> [TestFamily] testFamiliesForCodegen codegen = fmap (\testFamily -> testFamily {tests = IMap.filter f (tests testFamily)}) testFamilies where f mCodegens = case mCodegens of Just codegens -> Set.member codegen codegens Nothing -> True -- The data to instanciate testFamilies -- The first column is the id -- The second column is the proper name (the prefix of the subfolders) -- The third column is the data for each test testFamiliesData :: [(String, String, [(Index, CompatCodegen)])] testFamiliesData = [ ("base", "Base", [ ( 1, C_CG )]), ("basic", "Basic", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, C_CG ), ( 8, ANY ), ( 9, ANY ), ( 10, ANY ), ( 11, C_CG ), ( 12, ANY ), ( 13, ANY ), ( 14, ANY ), ( 15, ANY ), ( 16, ANY ), ( 17, ANY ), ( 18, ANY ), ( 19, ANY )]), ("bignum", "Bignum", [ ( 1, ANY ), ( 2, ANY )]), ("bounded", "Bounded", [ ( 1, ANY )]), ("buffer", "Buffer", [ ( 1, C_CG )]), ("corecords", "Corecords", [ ( 1, ANY ), ( 2, ANY )]), ("delab", "De-elaboration", [ ( 1, ANY )]), ("directives", "Directives", [ ( 1, ANY ), ( 2, ANY )]), ("disambig", "Disambiguation", [ ( 2, ANY )]), ("docs", "Documentation", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY )]), ("dsl", "DSL", [ ( 1, ANY ), ( 2, C_CG ), ( 3, ANY ), ( 4, ANY )]), ("effects", "Effects", [ ( 1, C_CG ), ( 2, C_CG ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY )]), ("error", "Errors", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY )]), ("ffi", "FFI", [ ( 1, ANY ) , ( 2, ANY ) , ( 3, ANY ) , ( 4, ANY ) , ( 5, ANY ) , ( 6, C_CG ) , ( 7, C_CG ) , ( 8, C_CG ) , ( 9, C_CG ) , ( 10, NODE_CG ) ]), ("folding", "Folding", [ ( 1, ANY )]), ("idrisdoc", "Idris documentation", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY )]), ("interactive", "Interactive editing", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY ), ( 10, ANY ), ( 11, ANY ), ( 12, ANY ), ( 13, ANY ), ( 14, C_CG ), ( 15, ANY ), ( 16, ANY )]), ("interfaces", "Interfaces", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), -- ( 5, ANY ), ( 6, ANY ), ( 7, ANY )]), ("interpret", "Interpret", [ ( 1, ANY ), ( 2, ANY )]), ("io", "IO monad", [ ( 1, C_CG ), ( 2, ANY ), ( 3, C_CG )]), ("layout", "Layout", [ ( 1, ANY )]), ("literate", "Literate programming", [ ( 1, ANY )]), ("meta", "Meta-programming", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY )]), ("pkg", "Packages", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY )]), ("prelude", "Prelude", [ ( 1, ANY )]), ("primitives", "Primitive types", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 5, C_CG ), ( 6, C_CG )]), ("proof", "Theorem proving", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY ), ( 10, ANY ), ( 11, ANY )]), ("proofsearch", "Proof search", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY )]), ("pruviloj", "Pruviloj", [ ( 1, ANY )]), ("quasiquote", "Quasiquotations", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY )]), ("records", "Records", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY )]), ("reg", "Regressions", [ ( 1, ANY ), ( 2, ANY ), ( 4, ANY ), ( 5, ANY ), ( 13, ANY ), ( 16, ANY ), ( 17, ANY ), ( 20, ANY ), ( 24, ANY ), ( 25, ANY ), ( 27, ANY ), ( 29, C_CG ), ( 31, ANY ), ( 32, ANY ), ( 39, ANY ), ( 40, ANY ), ( 41, ANY ), ( 42, ANY ), ( 45, ANY ), ( 48, ANY ), ( 52, C_CG ), ( 67, ANY ), ( 75, ANY ), ( 76, ANY ), ( 77, ANY )]), ("regression", "Regression", [ ( 1 , ANY ), ( 2 , ANY ), ( 3 , ANY )]), ("sourceLocation", "Source location", [ ( 1 , ANY )]), ("sugar", "Syntactic sugar", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, C_CG ), ( 5, ANY )]), ("syntax", "Syntax extensions", [ ( 1, ANY ), ( 2, ANY )]), ("tactics", "Tactics", [ ( 1, ANY )]), ("totality", "Totality checking", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY ), ( 10, ANY ), ( 11, ANY ), ( 12, ANY ), ( 13, ANY ), ( 14, ANY ), ( 15, ANY ), ( 16, ANY ), ( 17, ANY ), ( 18, ANY ), ( 19, ANY ), ( 20, ANY ), ( 21, ANY ), ( 22, ANY ), ( 23, ANY )]), ("tutorial", "Tutorial examples", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, C_CG )]), ("unique", "Uniqueness types", [ ( 1, ANY ), ( 4, ANY )]), ("universes", "Universes", [ ( 1, ANY ), ( 2, ANY )]), ("views", "Views", [ ( 1, ANY ), ( 2, ANY ), ( 3, C_CG )])]
markuspf/Idris-dev
test/TestData.hs
bsd-3-clause
7,947
0
13
3,512
2,924
1,907
1,017
296
4
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE CPP #-} module Control.Distributed.Process.Serializable ( Serializable , encodeFingerprint , decodeFingerprint , fingerprint , sizeOfFingerprint , Fingerprint , showFingerprint , SerializableDict(SerializableDict) , TypeableDict(TypeableDict) ) where import Data.Binary (Binary) #if MIN_VERSION_base(4,7,0) import Data.Typeable (Typeable) import Data.Typeable.Internal (TypeRep(TypeRep), typeOf) #else import Data.Typeable (Typeable(..)) import Data.Typeable.Internal (TypeRep(TypeRep)) #endif import Numeric (showHex) import Control.Exception (throw) import GHC.Fingerprint.Type (Fingerprint(..)) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Internal as BSI ( unsafeCreate , inlinePerformIO , toForeignPtr ) import Foreign.Storable (pokeByteOff, peekByteOff, sizeOf) import Foreign.ForeignPtr (withForeignPtr) -- | Reification of 'Serializable' (see "Control.Distributed.Process.Closure") data SerializableDict a where SerializableDict :: Serializable a => SerializableDict a deriving (Typeable) -- | Reification of 'Typeable'. data TypeableDict a where TypeableDict :: Typeable a => TypeableDict a deriving (Typeable) -- | Objects that can be sent across the network class (Binary a, Typeable a) => Serializable a instance (Binary a, Typeable a) => Serializable a -- | Encode type representation as a bytestring encodeFingerprint :: Fingerprint -> ByteString encodeFingerprint fp = -- Since all CH nodes will run precisely the same binary, we don't have to -- worry about cross-arch issues here (like endianness) BSI.unsafeCreate sizeOfFingerprint $ \p -> pokeByteOff p 0 fp -- | Decode a bytestring into a fingerprint. Throws an IO exception on failure decodeFingerprint :: ByteString -> Fingerprint decodeFingerprint bs | BS.length bs /= sizeOfFingerprint = throw $ userError "decodeFingerprint: Invalid length" | otherwise = BSI.inlinePerformIO $ do let (fp, offset, _) = BSI.toForeignPtr bs withForeignPtr fp $ \p -> peekByteOff p offset -- | Size of a fingerprint sizeOfFingerprint :: Int sizeOfFingerprint = sizeOf (undefined :: Fingerprint) -- | The fingerprint of the typeRep of the argument fingerprint :: Typeable a => a -> Fingerprint #if MIN_VERSION_base(4,8,0) fingerprint a = let TypeRep fp _ _ _ = typeOf a in fp #else fingerprint a = let TypeRep fp _ _ = typeOf a in fp #endif -- | Show fingerprint (for debugging purposes) showFingerprint :: Fingerprint -> ShowS showFingerprint (Fingerprint hi lo) = showString "(" . showHex hi . showString "," . showHex lo . showString ")"
qnikst/distributed-process
src/Control/Distributed/Process/Serializable.hs
bsd-3-clause
2,930
1
13
587
557
313
244
-1
-1
----------------------------------------------------------------------------- -- | -- Module : Plugins.BufferedPipeReader -- Copyright : (c) Jochen Keil -- License : BSD-style (see LICENSE) -- -- Maintainer : Jochen Keil <jochen dot keil at gmail dot com> -- Stability : unstable -- Portability : unportable -- -- A plugin for reading (temporarily) from named pipes with reset -- ----------------------------------------------------------------------------- module Plugins.BufferedPipeReader where import Control.Monad(forM_, when) import Control.Concurrent import Control.Concurrent.STM import System.IO import System.IO.Unsafe(unsafePerformIO) import Plugins import Signal data BufferedPipeReader = BufferedPipeReader String [(Int, Bool, String)] deriving (Read, Show) signal :: MVar SignalType signal = unsafePerformIO newEmptyMVar instance Exec BufferedPipeReader where alias ( BufferedPipeReader a _ ) = a trigger br@( BufferedPipeReader _ _ ) sh = takeMVar signal >>= sh . Just >> trigger br sh start ( BufferedPipeReader _ ps ) cb = do (chan, str, rst) <- initV forM_ ps $ \p -> forkIO $ reader p chan writer chan str rst where initV :: IO ( TChan (Int, Bool, String), TVar (Maybe String), TVar Bool ) initV = atomically $ do tc <- newTChan ts <- newTVar Nothing tb <- newTVar False return (tc, ts, tb) reader :: (Int, Bool, FilePath) -> TChan (Int, Bool, String) -> IO () reader p@(to, tg, fp) tc = do openFile fp ReadWriteMode >>= hGetLineSafe >>= \dt -> atomically $ writeTChan tc (to, tg, dt) reader p tc writer :: TChan (Int, Bool, String) -> TVar (Maybe String) -> TVar Bool -> IO () writer tc ts otb = do (to, tg, dt, ntb) <- update cb dt when tg $ putMVar signal $ Reveal 0 when (to /= 0) $ sfork $ reset to tg ts ntb writer tc ts ntb where sfork :: IO () -> IO () sfork f = forkIO f >> return () update :: IO (Int, Bool, String, TVar Bool) update = atomically $ do (to, tg, dt) <- readTChan tc when (to == 0) $ writeTVar ts $ Just dt writeTVar otb False tb <- newTVar True return (to, tg, dt, tb) reset :: Int -> Bool -> TVar (Maybe String) -> TVar Bool -> IO () reset to tg ts tb = do threadDelay ( to * 100 * 1000 ) readTVarIO tb >>= \b -> when b $ do when tg $ putMVar signal $ Hide 0 atomically (readTVar ts) >>= maybe (return ()) cb
tsiliakis/xmobar
src/Plugins/BufferedPipeReader.hs
bsd-3-clause
2,783
0
19
917
888
452
436
54
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sr-CS"> <title>Directory List v1.0</title> <maps> <homeID>directorylistv1</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/directorylistv1/src/main/javahelp/help_sr_CS/helpset_sr_CS.hs
apache-2.0
976
78
66
157
412
209
203
-1
-1
module Abs where import PointlessP.Combinators import PointlessP.Functors import PointlessP.Isomorphisms import PointlessP.RecursionPatterns fun = app . (((curry (curry (curry ((snd . fst) . fst)))) . bang) /\ id)
kmate/HaRe
old/testing/pointwiseToPointfree/AbsAST.hs
bsd-3-clause
238
6
19
51
85
48
37
9
1
import StackTest main :: IO () main = do stack ["--version"] stack ["--help"] stack ["unpack", "acme-missiles-0.2"] stack ["unpack", "acme-missiles"] stackErr ["command-does-not-exist"] stackErr ["unpack", "invalid-package-name-"] stackErr ["build"] doesNotExist "stack.yaml" stack [defaultResolverArg, "exec", "./foo.bat"]
phadej/stack
test/integration/tests/sanity/Main.hs
bsd-3-clause
362
0
8
70
112
54
58
12
1
-- File : Card.hs -- Author : Peter Schachte -- Purpose : An implementation of a playing card type -- | This code implements a playing card type, including types for -- ranks and suits. All three types are in the Eq, Ord, Bounded, -- Enum, Show, and Read classes. Note that we use a compact -- format for showing and reading ranks and suits: one character -- each for rank and suit. module Card (Suit(..), Rank(..), Card(..)) where import Data.List -- | A playing card suit. Suits are ordered alphabetically, in the -- standard order used for Bridge. data Suit = Club | Diamond | Heart | Spade deriving (Eq, Ord, Bounded, Enum) suitchars = "CDHS" -- | A playing card rank. Ranks are ordered 2 - 10, followed by -- Jack, Queen, King and Ace. data Rank = R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9 | R10 | Jack | Queen | King | Ace deriving (Eq, Ord, Bounded, Enum) rankchars = "23456789TJQKA" -- | A standard western playing card. Jokers are not supported. -- Cards are not in the Ord class, but for convenience they are in -- Bounded and Enum, to make it convenient to enumerate all the -- cards in a deck. Cards are enumerated with all clubs first, -- then diamonds, hearts, and spades, and each suit is enumerated -- from lowest to highest rank. data Card = Card {suit::Suit, rank::Rank} deriving (Eq, Bounded) instance Ord Card where compare (Card s1 r1) (Card s2 r2) = let suitorder = compare s1 s2 in if suitorder == EQ then compare r1 r2 else suitorder instance Enum Card where fromEnum (Card s r) = (fromEnum s)*13 + (fromEnum r) toEnum n | 0 <= n && n <= 51 = Card s r | otherwise = error $ "toEnum{Card}: " ++ show n ++ " is outside enumeration's range (0,51)" where s = toEnum (n `div` 13) r = toEnum (n `mod` 13) instance Show Rank where show r = [rankchars !! fromEnum r] instance Show Suit where show r = [suitchars !! fromEnum r] instance Show Card where show (Card s r) = show r ++ show s instance Read Rank where readsPrec _ = readSingleCharEnum rankchars instance Read Suit where readsPrec _ = readSingleCharEnum suitchars readSingleCharEnum :: Enum e => String -> String -> [(e,String)] readSingleCharEnum str (c:cs) = case elemIndex c str of Nothing -> [] Just i -> [(toEnum i, cs)] instance Read Card where readsPrec _ string = [(Card s r,rest) | (r,rest0) <- reads string, (s,rest) <- reads rest0]
CIS-UoM/assignments
COMP90048 Declarative Programming/haskell/2/Card.hs
mit
2,600
0
11
723
665
363
302
43
2
import Primes nmax = 1000000 factorizer = makeFactorizer nmax factorize = runFactorization factorizer phi = map (phiFold . factorize) [2..nmax] answer = sum phi
arekfu/project_euler
p0072/p0072.hs
mit
166
0
7
29
55
29
26
6
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} -- syslogclient module Main where import Control.Monad import Data.Bits import Data.ByteString hiding (head, pack, unpack) import Data.ByteString.Char8 hiding (head, length) import Network.BSD import Network.Socket hiding (sendTo) import Network.Socket.ByteString import Prelude hiding (concat, drop, length) import SyslogTypes import System.Random data SyslogHandle = SyslogHandle {slSocket :: Socket, slProgram :: String, slAddress :: SockAddr} openlog :: HostName -- ^ Remote hostname, or localhost -> String -- ^ Port number or name; 514 is default -> String -- ^ Name to log under -> IO SyslogHandle -- ^ Handle to use for logging openlog hostname port progname = do -- Look up the hostname and port. Either raises an exception -- or returns a nonempty list. First element in that list -- is supposed to be the best option. addrinfos <- getAddrInfo Nothing (Just hostname) (Just port) let serveraddr = head addrinfos -- Establish a socket for communication sock <- socket (addrFamily serveraddr) Datagram defaultProtocol -- Save off the socket, program name, and server address in a handle return $ SyslogHandle sock progname (addrAddress serveraddr) syslog :: SyslogHandle -> Facility -> Priority -> ByteString -> IO () syslog syslogh fac pri msg = sendstr sendmsg where code = makeCode fac pri sendmsg = concat ["<", pack $ show code, ">", pack $ slProgram syslogh, ": ", msg] -- Send until everything is done sendstr :: ByteString -> IO () sendstr omsg = if length omsg == 0 then return () else do sent <- sendTo (slSocket syslogh) omsg (slAddress syslogh) sendstr (drop sent omsg) syslogBlaster :: SyslogHandle -> Facility -> Priority -> ByteString -> IO () syslogBlaster h fac pri msg = run g where g = mkStdGen 0 run g = let (x, g') = next g in do syslog h fac pri (concat [msg, (pack . show) x]) run g' closelog :: SyslogHandle -> IO () closelog syslogh = close (slSocket syslogh) {- | Convert a facility and a priority into a syslog code -} makeCode :: Facility -> Priority -> Int makeCode fac pri = let faccode = codeOfFac fac pricode = fromEnum pri in (faccode `shiftL` 3) .|. pricode main :: IO () main = undefined
JoshuaGross/haskell-learning-log
Code/SyslogClient/src/Main.hs
mit
2,748
0
17
911
645
341
304
55
2
module DP where
vladfi1/hs-misc
DP.hs
mit
18
0
2
5
4
3
1
1
0
module Util.Monad where -- | Apply monadic computations to a value in sequence, returning the final result of passing the value through the pipeline (~>) :: (Monad m) => a -> [(a -> m a)] -> m a (~>) a [] = return a a ~> (f:fs) = do f a >>= (~> fs) unfoldrM :: (Monad m) => (b -> m (Maybe (a, b))) -> b -> m [a] unfoldrM f state = do result <- f state case result of Nothing -> return [] Just (val, state') -> do vals <- unfoldrM f state' return $ (val:vals) untilM :: (Monad m) => (a -> m Bool) -> (a -> m a) -> a -> m a untilM pred f x = do break <- pred x if break then return x else f x >>= untilM pred f
sgord512/Utilities
Util/Monad.hs
mit
664
0
14
195
322
163
159
18
2
module Compiler.Rum.Compiler.Emitter where import Control.Monad.Except (ExceptT, forM_, runExceptT, (>=>)) import Control.Monad.State import Data.Char (isUpper, ord) import Data.Map (Map) import qualified Data.Map as Map (fromList, lookup) import qualified Data.Text as T import qualified LLVM.AST as AST (Operand(..), Type(..), Module(..), Name(..), Operand(..)) import qualified LLVM.AST.Constant as C (Constant(..)) import qualified LLVM.AST.Type as Ty import LLVM.Context (withContext) import LLVM.Module (moduleLLVMAssembly, withModuleFromAST) import Compiler.Rum.Compiler.CodeGen import qualified Compiler.Rum.Internal.AST as Rum toSig :: [Rum.Variable] -> [(AST.Type, AST.Name)] toSig = let nm = T.unpack . Rum.varName in map (\x -> (if isUpper $ head (nm x) then Ty.ptr Ty.i8 else iType, AST.Name (nm x))) -- Fun declarations + main body codeGenAll :: Rum.Program -> LLVM () codeGenAll pr = let (funs, main) = span isFunDeclSt pr in codeGenTops funs >> codeGenMain main where isFunDeclSt :: Rum.Statement -> Bool isFunDeclSt Rum.Fun{} = True isFunDeclSt _ = False -- Deal with std funs codegenProgram :: Rum.Program -> LLVM () codegenProgram program = do -- defineIOStrVariable ".scanf_str" "%d\0" -- defineIOStrVariable ".printf_str" "%d\n\0" codeGenAll program declareExtFun Ty.i32 "rumRead" [] False declareExtFun Ty.i32 "rumWrite" [(Ty.i32, AST.Name "")] False declareExtFun Ty.i32 "rumStrlen" [(Ty.ptr Ty.i8, AST.Name "")] False declareExtFun Ty.i32 "rumStrget" [(Ty.ptr Ty.i8, AST.Name ""), (Ty.i32, AST.Name "")] False declareExtFun Ty.i32 "rumStrcmp" [(Ty.ptr Ty.i8, AST.Name ""), (Ty.ptr Ty.i8, AST.Name "")] False declareExtFun (Ty.ptr Ty.i8) "rumStrsub" [(Ty.ptr Ty.i8, AST.Name ""), (Ty.i32, AST.Name ""), (Ty.i32, AST.Name "")] False declareExtFun (Ty.ptr Ty.i8) "rumStrdup" [(Ty.ptr Ty.i8, AST.Name "")] False declareExtFun (Ty.ptr Ty.i8) "rumStrset" [(Ty.ptr Ty.i8, AST.Name ""), (Ty.i32, AST.Name ""), (Ty.i8, AST.Name "")] False declareExtFun (Ty.ptr Ty.i8) "rumStrcat" [(Ty.ptr Ty.i8, AST.Name ""), (Ty.ptr Ty.i8, AST.Name "")] False declareExtFun (Ty.ptr Ty.i8) "rumStrmake" [(Ty.i32, AST.Name ""), (Ty.i8, AST.Name "")] False -- declareExtFun Ty.i32 "scanf" [(Ty.ptr Ty.i8, AST.Name "")] True -- declareExtFun Ty.i32 "printf" [(Ty.ptr Ty.i8, AST.Name "")] True -- declareExtFun Ty.i64 "strlen" [(Ty.ptr Ty.i8, AST.Name "")] False -- Declaration of many funs codeGenTops :: Rum.Program -> LLVM AST.Operand codeGenTops = foldr ((>>) . codeGenTop) (return iZero) -- Deal with one fun declaration in the beginning of the file codeGenTop :: Rum.Statement -> LLVM () codeGenTop Rum.Fun{..} = defineFun iType (Rum.varName funName) fnargs bls where fnargs = toSig params bls = createBlocks $ execCodegen $ do entr <- addBlock entryBlockName setBlock entr forM_ params $ \a -> do let aName = T.unpack $ Rum.varName a -- let aType = typeOfOperand a let t = if isUpper $ head aName then Ty.ptr Ty.i8 else iType var <- alloca t () <$ store var (local t (AST.Name aName)) assign aName var codeGenFunProg funBody >>= ret codeGenTop _ = error "Impossible happened in CodeGenTop. Only fun Declarations allowed!" -- Deal with stmts after all fun declarations (main) codeGenMain :: Rum.Program -> LLVM () codeGenMain pr = defineFun iType "main" [] bls where bls = createBlocks $ execCodegen $ do entr <- addBlock "main" setBlock entr codeGenProg pr ret iZero -- This one is for Fun declarations (should have return value) codeGenFunProg :: Rum.Program -> Codegen AST.Operand codeGenFunProg [] = pure iZero codeGenFunProg (Rum.Return{..}:_) = cgenExpr retExp codeGenFunProg (s:stmts) = codeGenStmt s >> codeGenFunProg stmts -- Main prog codeGenProg :: Rum.Program -> Codegen () codeGenProg [] = pure () codeGenProg (Rum.Return{..}:_) = cgenExpr retExp >>= ret >> pure () codeGenProg (s:stmts) = codeGenStmt s >> codeGenProg stmts codeGenStmt :: Rum.Statement -> Codegen () codeGenStmt Rum.Skip = return () codeGenStmt Rum.Return{..} = cgenExpr retExp >>= ret >> return () codeGenStmt Rum.AssignmentVar{..} = do cgenedVal <- cgenExpr value symTabl <- gets symTable let vars = map fst symTabl let vName = T.unpack $ Rum.varName var if vName `elem` vars then do oldV <- getVar vName () <$ store oldV cgenedVal else do v <- alloca (typeOfOperand cgenedVal) () <$ store v cgenedVal assign vName v codeGenStmt (Rum.FunCallStmt f) = void $ codeGenFunCall f codeGenStmt Rum.IfElse{..} = do ifTrueBlock <- addBlock "if.then" elseBlock <- addBlock "if.else" ifExitBlock <- addBlock "if.exit" -- %entry cond <- cgenExpr ifCond test <- isTrue cond cbr test ifTrueBlock elseBlock -- Branch based on the condition -- if.then setBlock ifTrueBlock codeGenProg trueAct -- Generate code for the true branch br ifExitBlock -- Branch to the merge block -- if.else setBlock elseBlock codeGenProg falseAct -- Generate code for the false branch br ifExitBlock -- Branch to the merge block -- if.exit setBlock ifExitBlock return () codeGenStmt Rum.RepeatUntil{..} = do repeatBlock <- addBlock "repeat.loop" condBlock <- addBlock "repeat.cond" exitBlock <- addBlock "repeat.exit" br repeatBlock -- repeat-body setBlock repeatBlock codeGenProg act br condBlock -- repeat-cond setBlock condBlock cond <- cgenExpr repCond test <- isFalse cond cbr test repeatBlock exitBlock -- exit block setBlock exitBlock return () codeGenStmt Rum.WhileDo{..} = do condBlock <- addBlock "while.cond" whileBlock <- addBlock "while.loop" exitBlock <- addBlock "while.exit" br condBlock -- while-cond setBlock condBlock cond <- cgenExpr whileCond test <- isTrue cond cbr test whileBlock exitBlock -- while-true setBlock whileBlock codeGenProg act br condBlock -- Exit block setBlock exitBlock return () codeGenStmt Rum.For{..} = do startBlock <- addBlock "for.start" condBlock <- addBlock "for.cond" doUpdateBlock <- addBlock "for.loop" exitBlock <- addBlock "for.end" br startBlock -- Starting point setBlock startBlock codeGenProg start br condBlock -- Condition block setBlock condBlock cond <- cgenExpr expr test <- isTrue cond cbr test doUpdateBlock exitBlock -- for Body + Update block setBlock doUpdateBlock codeGenProg body >> codeGenProg update br condBlock -- Exit block setBlock exitBlock return () binOps :: Map Rum.BinOp (AST.Operand -> AST.Operand -> Codegen AST.Operand) binOps = Map.fromList [ (Rum.Add, iAdd), (Rum.Sub, iSub) , (Rum.Mul, iMul), (Rum.Div, iDiv) , (Rum.Mod, iMod)] logicOps :: Map Rum.LogicOp (AST.Operand -> AST.Operand -> Codegen AST.Operand) logicOps = Map.fromList [(Rum.And, lAnd), (Rum.Or, lOr)] compOps :: Map Rum.CompOp (AST.Operand -> AST.Operand -> Codegen AST.Operand) compOps = Map.fromList [ (Rum.Eq, iEq), (Rum.NotEq, iNeq) , (Rum.Lt, iLt), (Rum.Gt, iGt) , (Rum.NotGt, iNotGt), (Rum.NotLt, iNotLt) ] cgenExpr :: Rum.Expression -> Codegen AST.Operand cgenExpr (Rum.Const (Rum.Number c)) = return $ cons (C.Int iBits (fromIntegral c)) cgenExpr (Rum.Const (Rum.Ch c)) = pure $ cons (C.Int 8 (fromIntegral $ ord c)) cgenExpr (Rum.Const (Rum.Str s)) = pure $ cons $ C.Array Ty.i8 $ map (C.Int 8 . fromIntegral . ord) (T.unpack s) ++ [C.Int 8 0] cgenExpr (Rum.Var x) = let nm = T.unpack $ Rum.varName x in getVar nm >>= \v -> gets varTypes >>= \tps -> case Map.lookup nm tps of Just Ty.ArrayType{..} -> getElementPtr v Just _ -> load v Nothing -> error "variable type is unknown" cgenExpr (Rum.Neg e) = cgenExpr e >>= \x -> iSub iZero x cgenExpr Rum.BinOper{..} = case Map.lookup bop binOps of Just f -> cgenExpr l >>= \x -> cgenExpr r >>= \y -> f x y Nothing -> error "No such binary operator" cgenExpr Rum.LogicOper{..} = case Map.lookup lop logicOps of Just f -> cgenExpr l >>= \x -> cgenExpr r >>= \y -> f x y Nothing -> error "No such logic operator" cgenExpr Rum.CompOper{..} = case Map.lookup cop compOps of Just f -> cgenExpr l >>= \x -> cgenExpr r >>= \y -> f x y Nothing -> error "No such logic operator" cgenExpr (Rum.FunCallExp f) = codeGenFunCall f rumFunNamesMap :: Map String (String, Ty.Type) rumFunNamesMap = Map.fromList [ ("write", ("rumWrite", iType)), ("read", ("rumRead", iType)) , ("strlen", ("rumStrlen", iType)), ("strget", ("rumStrget", iType)) , ("strsub", ("rumStrsub", Ty.ptr Ty.i8)), ("strdup", ("rumStrdup", Ty.ptr Ty.i8)) , ("strset", ("rumStrset", Ty.ptr Ty.i8)), ("strcat", ("rumStrcat", Ty.ptr Ty.i8)) , ("strcmp", ("rumStrcmp", iType)), ("strmake", ("rumStrmake", Ty.ptr Ty.i8)) ] codeGenFunCall :: Rum.FunCall -> Codegen AST.Operand codeGenFunCall Rum.FunCall{..} = let funNm = T.unpack $ Rum.varName fName in mapM modifiedCgenExpr args >>= \largs -> case Map.lookup funNm rumFunNamesMap of Just (n, t) -> call (externf t (AST.Name n)) largs Nothing -> call (externf iType (AST.Name funNm)) largs modifiedCgenExpr :: Rum.Expression -> Codegen AST.Operand modifiedCgenExpr str@(Rum.Const (Rum.Str _)) = do codeGenStmt (Rum.AssignmentVar "T@" str) getVar "T@" >>= getElementPtr modifiedCgenExpr x = cgenExpr x ------------------------------------------------------------------------------- -- Compilation ------------------------------------------------------------------------------- liftError :: ExceptT String IO a -> IO a liftError = runExceptT >=> either fail return codeGenMaybeWorks :: String -> Rum.Program -> IO AST.Module codeGenMaybeWorks moduleName program = withContext $ \context -> liftError $ withModuleFromAST context llvmAST $ \m -> do llstr <- moduleLLVMAssembly m writeFile "local_example.ll" llstr return llvmAST where llvmModule = emptyModule moduleName generatedLLVM = codegenProgram program llvmAST = runLLVM llvmModule generatedLLVM
vrom911/Compiler
src/Compiler/Rum/Compiler/Emitter.hs
mit
10,858
0
20
2,703
3,665
1,834
1,831
-1
-1
-- Copyright (c) 2011 Alexander Poluektov ([email protected]) -- -- Use, modification and distribution are subject to the MIT license -- (See accompanying file MIT-LICENSE) import Domino.Game import Domino.GameState import Domino.Read import Domino.Strategy import Domino.Strategy.Simple import Domino.Strategy.Counting import Control.Monad.State data GameResult = GRDraw | GRWin Player deriving (Show, Eq) main = do result <- game putStrLn $ show result game :: IO GameResult game = do putStrLn "What is my hand?" hand <- readHand putStrLn "Which tiles nobody has (revealed during negotiation)?" nobodyHas <- readHand putStrLn "What is the opening move?" firstMove <- readTile putStrLn "Whose move is the first?" -- TODO: it can be deduced from revealed first <- readFirst let e = (first, EBegin hand first nobodyHas firstMove) evalStateT (e >>> loop first) (initialState, counting) type StateGameState = StateT (GameState, Strategy) IO loop :: Player -> StateGameState GameResult loop Opponent = do lift $ putStrLn "What is opponent's move?" (st,_) <- get move <- lift $ readMove case move of EDraw Unknown -> (Opponent,move) >>> loop Opponent EPass | head (events st) == (Me,EPass) -> return GRDraw | otherwise -> (Opponent,move) >>> loop Me EMove m | not (isCorrectMove (line st) m) -> do lift $ putStrLn "Move is not correct; try again:" loop Opponent | checkWin Opponent (updateGameState (Opponent,move) st) -> return (GRWin Opponent) | otherwise -> (Opponent,move) >>> loop Me loop Me = do (st, s) <- get let evt = next s lift $ putStrLn $ show evt case evt of EDraw Unknown -> do lift $ putStrLn "What did I get from the stock?" tile <- lift $ readTile (Me,EDraw $ Known tile) >>> loop Me EPass | head (events st) == (Opponent,EPass) -> return GRDraw | otherwise -> (Me,evt) >>> loop Opponent EMove m | checkWin Me (updateGameState (Me,evt) st) -> return (GRWin Me) | otherwise -> (Me,evt) >>> loop Opponent (>>>) :: (Player,Event) -> StateGameState GameResult -> StateGameState GameResult evt >>> st = (modify $ \(st,s) -> (updateGameState evt st, notify s evt)) >> st checkWin :: Player -> GameState -> Bool checkWin p st = numTiles p st == 0 where numTiles Me = length . hand numTiles Opponent = opponentHand
apoluektov/domino
src/Main.hs
mit
2,474
0
17
601
823
404
419
58
5
{-# LANGUAGE QuasiQuotes #-} module WordTests where import Test.Framework import qualified Grammar.Greek.Morph.Phoneme.Round as Round import Grammar.Greek.Morph.QuasiQuoters import Grammar.Greek.Morph.Types import Grammar.Test.Round coreWordPhonemeRound = testGroup "coreWordPhonemeRound" $ fmap (uncurry $ testRoundId Round.phoneme) [coreWordPairs| ἀντί διά κατά ὑπό δέ οὐδέ τοῦτο φυγῆς γλῶττῃ |]
ancientlanguage/haskell-analysis
greek-morph/test/WordTests.hs
mit
446
0
10
46
74
48
26
9
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE CPP #-} {-# OPTIONS_GHC -Wall #-} ----------------------------------------------------------------------------- -- | -- module : Data.GF2 -- Copyright : (c) 2017 Naoyuki MORITA -- License : MIT -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (DeriveDataTypeable) -- ----------------------------------------------------------------------------- module Data.GF2 ( GF2 , fromGF2 ) where import Data.Ratio import Data.Bits ( xor, (.&.) ) #if defined(InstanceOfFiniteField) import Data.FiniteField (FiniteField(..)) #endif import Data.Typeable -- | Finite field of order 2. -- -- Its elements are \(\{0, 1\}\). -- -- Arithmetic rules are shown in the following equations: -- -- \(0 + 0 = 0\), \(0 + 1 = 1\), \(1 + 0 = 1\), \(1 + 1 = 0\) -- -- \(0 * 0 = 0\), \(0 * 1 = 0\), \(1 * 0 = 0\), \(1 * 1 = 1\) newtype GF2 = GF2 Bool deriving (Eq, Typeable) boolToInteger :: Bool -> Integer boolToInteger False = 0 boolToInteger True = 1 -- | Conversion to other `Num` class type. fromGF2 :: (Num a) => GF2 -> a fromGF2 (GF2 x) = fromInteger $ boolToInteger x instance Show GF2 where showsPrec n (GF2 x) = showsPrec n $ boolToInteger x instance Num GF2 where (GF2 x) + (GF2 y) = GF2 $ x `xor` y (GF2 x) * (GF2 y) = GF2 $ x .&. y x - y = x + y negate x = x abs x = x signum x = x fromInteger x = GF2 $ (x `mod` 2) == 1 instance Fractional GF2 where fromRational r = fromInteger (numerator r) / fromInteger (denominator r) recip 0 = error "divide by zero" recip x = x instance Enum GF2 where toEnum x = GF2 $ toEnum x fromEnum (GF2 x) = fromEnum x instance Ord GF2 where compare (GF2 x) (GF2 y) = compare x y instance Bounded GF2 where minBound = 0 maxBound = 1 #if defined(InstanceOfFiniteField) instance FiniteField GF2 where order _ = 2 char _ = 2 pthRoot x = x allValues = [0,1] #endif -- EOF
naohaq/gf256-hs
src/Data/GF2.hs
mit
1,968
0
9
425
528
288
240
37
1
{-# LANGUAGE OverloadedStrings #-} module FaveGraph(recommendPhotographer, recordFave, recordFollow, FaveRecord, PhotographerId, FavedById, FaveRating, PhotoId, FollowRecord, perform) where import WeightedSlopeOne import Database.Neo4j import qualified Data.HashMap.Lazy as M import qualified Data.Text as T import Data.Int (Int64) import qualified Data.Aeson.Types as DAT import Data.Maybe (listToMaybe) import qualified Database.Neo4j.Transactional.Cypher as TC type FaveRating = Int64 type PhotographerId = T.Text type FollowerId = PhotographerId type PhotoId = T.Text type NodeId = T.Text type FavedById = PhotographerId type FaveRecord = (FavedById, FaveRating, PhotographerId, PhotoId) type FollowRecord = (FollowerId, PhotographerId) photographerLabel :: Label photographerLabel = "Photographer" photoLabel :: Label photoLabel = "Photo" recordFave :: FaveRecord -> IO Relationship recordFave (favedBy, rating, photographerId, photoId) = perform $ do by <- savePhotographer favedBy photo <- savePhoto photoId photographerId favePhoto rating by photo recordFollow :: FollowRecord -> IO Relationship recordFollow (followerId, photographerId) = perform $ do follower <- savePhotographer followerId photographer <- savePhotographer photographerId updateOrCreate "Follow" follower photographer M.empty recommendPhotographer :: PhotographerId -> IO [PhotographerId] recommendPhotographer userId = perform $ do res <- TC.runTransaction $ do result <- TC.cypher "MATCH (n:Photographer)-[f1:Fave]-> (:Photo) <- [:Takes] - (:Photographer) - [:Fave] -> (:Photo) <- [:Takes] - (target: Photographer) \ \ WHERE n.id={photographerId} and NOT (n)-[:Follow]->(target) \ \ RETURN target.id, count(f1) as c \ \ ORDER BY c DESC" $ M.fromList [("photographerId", TC.newparam userId)] let vals = TC.vals result return $ fmap head vals let (Right pidVals) = res return $ fmap getPid pidVals where getPid (DAT.String pid) = pid findById :: Label -> NodeId -> Neo4j (Maybe Node) findById label nid = fmap listToMaybe $ getNodesByLabelAndProperty label $ Just ("id" |: nid) create :: Label -> NodeId -> Neo4j Node create label nid = do node <- createNode $ M.fromList [ "id" |: nid ] addLabels [label] node return node findOrCreate :: Label -> NodeId -> Neo4j Node findOrCreate label nid = do node <- findById label nid case node of Just n -> return n Nothing -> create label nid updateOrCreate :: RelationshipType -> Node -> Node -> Properties -> Neo4j Relationship updateOrCreate relType fromNode toNode props = do fromRels <- getRelationships fromNode Outgoing [relType] toRels <- getRelationships toNode Incoming [relType] case common fromRels toRels of [] -> createRelationship relType props fromNode toNode x : _ -> return x savePhotographer :: PhotographerId -> Neo4j Node savePhotographer = findOrCreate photographerLabel savePhoto :: PhotoId -> PhotographerId -> Neo4j Node savePhoto photoId photographerId = do maybePhoto <- findById photoLabel photoId case maybePhoto of Just p -> return p Nothing -> createPhoto photoId photographerId createPhoto :: PhotoId -> PhotographerId -> Neo4j Node createPhoto photoId photographerId = do photo <- create photoLabel photoId photographer <- savePhotographer photographerId createRelationship "Takes" M.empty photographer photo return photo favePhoto :: FaveRating -> Node -> Node -> Neo4j Relationship favePhoto rating by photo = do updateOrCreate "Fave" by photo (M.fromList [ "rating" |: rating]) -- find the common elements common :: (Eq a) => [a] -> [a] -> [a] common xs ys = [ x | x <- xs , y <- ys, x == y] perform :: Neo4j a -> IO a perform = withConnection "127.0.0.1" 7474
kailuowang/BeautifulMinds
src/FaveGraph.hs
mit
3,967
0
18
857
1,085
554
531
81
2
module Render where import SDL
wowofbob/circles
src/Render.hs
mit
34
0
3
8
7
5
2
2
0
{-# LANGUAGE UnicodeSyntax #-} module Main where infixr 9 █ type Proc = IO () (█) ∷ (a → b) → a → b identity ∷ a → a dump ∷ String → Proc hello ∷ Proc main ∷ Proc a █ b = a b identity = id dump "" = putStrLn "" dump x = putStrLn x hello = identity █ dump █ identity █ "你好世界" main = do foo ← hello bar ← hello let dump = undefined (█) ← return $ undefined dump hello
sgtest/haskell-simple-tests
src/Main.hs
mit
433
0
9
107
176
92
84
20
1
{-# LANGUAGE OverloadedStrings, ViewPatterns #-} module Y2017.M11.D07.Solution where {-- Yesterday's exercise we read in a set of scored documents; the exercise before, we parsed a set of keywords associated with articles. Today continues the parsing exercises. This time we're parsing JSON, so it 'should' be easy. Right? Given the structure at recommend.json parse in that structure --} import Control.Arrow ((&&&), (***)) import Data.Aeson hiding (Value) import Data.Aeson.Encode.Pretty import qualified Data.ByteString.Lazy.Char8 as BL import Data.List (isInfixOf) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromJust, mapMaybe) import Data.Time -- below import available via 1HaskellADay git repository import Store.SQL.Util.Indexed import Y2017.M11.D06.Solution hiding (title) import Y2017.M11.D03.Solution recommendFile :: FilePath recommendFile = "Y2017/M11/D07/recommend.json" data Recommend = Rec { recIdx, title :: String, text, author :: Maybe String, published :: Day, viewCnt :: Maybe Integer } deriving (Eq, Show) instance FromJSON Recommend where parseJSON (Object o) = Rec <$> o .: "id" <*> o .: "title" <*> o .:? "full_text" <*> o .:? "author" <*> o .: "publish_dt" <*> o .: "view_count" instance Indexed Recommend where idx (Rec i _ _ _ _ _) = read i data RecommendSet = RS { unrecs :: [Recommend] } instance FromJSON RecommendSet where parseJSON (Object o) = RS <$> o .: "recommend" readRecs :: FilePath -> IO (Map Integer Recommend) readRecs = fmap (Map.fromList . map (read . recIdx &&& id) . unrecs . fromJust . decode) . BL.readFile -- How many recommendations are there? How many title have the word 'Trump' in -- them? {-- >>> recs <- readRecs "Y2017/M11/D07/recommend.json" >>> length recs 30 >>> length . filter (isInfixOf "Trump" . title) $ Map.elems recs 24 --} {-- BONUS ----------------------------------------------------------------- From yesterday's exercise you loaded in a set of scores. Today you have a set of recommendations ... without scores. Marry the two. Now, output JSON in the following format: article_id: <<- make this an integer, not a string, smh article_title: article_body: article_date: article_keywords: <<- a list, leave empty for now article_score: <<- score goes here article_author: <<- if present --} data Recommendation = Scored { scoreIdx :: Integer, scoreTitle :: String, scoreText :: Maybe String, scoreDate :: Day, scoreAuthor :: Maybe String, scoreKWs :: [Keyphrase], scoreViewCnt :: Maybe Integer, scoreScore :: Double } deriving (Eq, Show) marry :: Map Integer Recommend -> Map Integer Score -> [Recommendation] marry recs = mapMaybe (\(idx, val2float . score -> scr) -> Map.lookup idx recs >>= \rec -> return (Scored idx (title rec) (text rec) (published rec) (author rec) [] (viewCnt rec) scr)) . Map.toList -- how many recommendations did you get from that marriage? {-- >>> scores <- readScoreFile scoreFile >>> length scores 30 >>> marriage = marry recs scores >>> length marriage 30 --} -- now, save out the recommendations as JSON: instance ToJSON Recommendation where toJSON rec = object ["article_id" .= scoreIdx rec, "article_title" .= scoreTitle rec, "article_body" .= scoreText rec, "article_date" .= scoreDate rec, "article_keywords" .= scoreKWs rec, "article_score" .= scoreScore rec, "article_view_count" .= scoreViewCnt rec, "article_author" .= scoreAuthor rec] -- Of course, we need keyword JSON instance, but leave that undefined for now instance ToJSON Keyphrase where toJSON (KW strength (SQS str)) = object ["strength" .= strength, "keyphrase" .= str] writeRecs :: FilePath -> [Recommendation] -> IO () writeRecs outputFile = BL.writeFile outputFile . encodePretty {-- >>> writeRecs "Y2017/M11/D07/recs_with_scores.json" marriage ... and you see the pprinted json of the recommendations with their scores. Tomorrow, we will add the keywords for these specific articles and output this as JSON. --}
geophf/1HaskellADay
exercises/HAD/Y2017/M11/D07/Solution.hs
mit
4,380
0
17
1,039
824
459
365
-1
-1
{-# LANGUAGE TupleSections #-} module Pd.Master ( Score , Steps , playN , play2 , table ) where import Control.Arrow (second) import Data.Function (on) import Data.List (foldl') import Data.Map.Strict ((!)) import qualified Data.Map.Strict as M import Pd.Agents.Core type Id = Int type Score = Int type Steps = Int playN :: Steps -> [Agent] -> [Score] playN steps agents = sumScores $ foldl' playN' buildMap pairs where sumScores :: M.Map Id (Agent, Score) -> [Score] sumScores = map (snd . snd) . M.toAscList buildMap :: M.Map Id (Agent, Score) buildMap = M.fromDistinctAscList . zip [0..] . zip agents $ repeat 0 pairs = [(i, j) | i <- [0..n], j <- [i+1..n]] n = length agents - 1 playN' :: M.Map Id (Agent, Score) -> (Id, Id) -> M.Map Id (Agent, Score) playN' m (i1, i2) = M.adjust (addScore s1) i1 $ M.adjust (addScore s2) i2 m where (s1, s2) = play2 steps (getAgent i1, getAgent i2) getAgent = fst . (m !) addScore s' = second (+s') play2 :: Steps -> (Agent, Agent) -> (Score, Score) play2 steps agents = extractScores $ iterate play2' (agents, (0, 0), Nothing) !! steps where extractScores (_, s, _) = s play2' :: ((Agent, Agent), (Score, Score), Maybe (Action, Action)) -> ((Agent, Agent), (Score, Score), Maybe (Action, Action)) play2' ((agent1, agent2), scores, actions) = (agents', scores', Just actions') where agents' = (nextAgent decision1, nextAgent decision2) scores' = scores `addScores` table actions' actions' = (action decision1, action decision2) decision1 = runAgent agent1 action2 decision2 = runAgent agent2 action1 (action1, action2) = spreadMaybe actions addScores (s1a, s2a) (s1b, s2b) = (s1a+s1b, s2a+s2b) spreadMaybe Nothing = (Nothing, Nothing) spreadMaybe (Just (a, b)) = (Just a, Just b) table :: (Action, Action) -> (Score, Score) table (Cooperate, Cooperate) = (2, 2) table (Cooperate, Defect ) = (0, 3) table (Defect, Cooperate) = (3, 0) table (Defect, Defect ) = (1, 1)
atlaua/prisoners-dilemma
Pd/Master.hs
mit
2,076
0
11
485
899
513
386
48
2
{-# OPTIONS_GHC -ddump-splices #-} module Types where import SqlFieldTypes import Control.Applicative import qualified Data.Csv as Csv import Data.Csv ((.:)) import Data.Text import Database.Persist import Database.Persist.Class import Database.Persist.Types import Database.Persist.TH (mkPersist, mkMigrate, persistLowerCase, share, sqlSettings, derivePersistField) share [mkPersist sqlSettings, mkMigrate "migrateTables"] [persistLowerCase| District sid Int name Text Primary sid MEAPScore meapDistrict DistrictId grade Int subject Subject subgroup Subgroup numTested Int level1Proficient Proficiency level2Proficient Proficiency level3Proficient Proficiency level4Proficient Proficiency totalProficient Proficiency deriving Show SchoolStaff staffDistrict DistrictId teachers Double librarians Double librarySupport Double |] instance Csv.FromField Subject where parseField "Math" = pure Math parseField "Reading" = pure Reading parseField "Writing" = pure Writing parseField "Science" = pure Science parseField "SocialStudies" = pure SocialStudies parseField _ = Control.Applicative.empty instance Csv.FromField Subgroup where parseField "Two or More Races" = pure MultiRace parseField "White, n:ot of Hispanic origin" = pure White parseField "Students with Disabilities" = pure Disabled parseField "Migrant" = pure Migrant parseField "Asian" = pure Asian parseField "Native Hawaiian or Other Pacific Islander" = pure PacificIslander parseField "Male" = pure Male parseField "Hispanic" = pure Hispanic parseField "Female" = pure Female parseField "All Students" = pure All parseField "Economically Disadvantaged" = pure EconomicallyDisadvantaged parseField "English Language Learners" = pure ESL parseField "American Indian or Alaskan Native" = pure Native parseField "Black, not of Hispanic origin" = pure Black parseField _ = Control.Applicative.empty instance Csv.FromField Proficiency where parseField "< 5%" = pure $ Proficiency 5 parseField "> 95%" = pure $ Proficiency 95 parseField f = Proficiency <$> Csv.parseField f instance Csv.FromNamedRecord (Maybe (District, MEAPScore)) where parseNamedRecord r = optional $ (,) <$> (District <$> r .: "DistrictCode" <*> r .: "DistrictName") <*> (MEAPScore <$> r .: "DistrictCode" <*> r .: "Grade" <*> r .: "Subject Name" <*> r .: "Subgroup" <*> r .: "Number Tested" <*> r .: "Level 1 Proficient" <*> r .: "Level 2 Proficient" <*> r .: "Level 3 Proficient" <*> r .: "Level 4 Proficient" <*> r .: "Percent Proficient")
rdlester/meap-analysis
failed_src/Types.hs
mit
2,770
0
27
620
560
287
273
-1
-1
-- | A data type representing the Bower.json package description file, together -- with a parser and related functions. -- -- This code is based on the specification at -- <https://github.com/bower/bower.json-spec>. module Web.Bower.PackageMeta ( -- * Data types PackageMeta(..) , PackageName , runPackageName , mkPackageName , Author(..) , ModuleType(..) , moduleTypes , Repository(..) , Version(..) , VersionRange(..) , BowerError(..) , showBowerError , PackageNameError(..) , showPackageNameError -- * Parsing , decodeFile , displayError , asPackageMeta , parseModuleType , parsePackageName , asAuthor , asRepository ) where import Web.Bower.PackageMeta.Internal
hdgarrood/bower-json
src/Web/Bower/PackageMeta.hs
mit
719
0
5
138
118
84
34
24
0
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveGeneric #-} module Codec.Xlsx.Types.SheetViews ( -- * Structured type to construct 'SheetViews' SheetView(..) , Selection(..) , Pane(..) , SheetViewType(..) , PaneType(..) , PaneState(..) -- * Lenses -- ** SheetView , sheetViewColorId , sheetViewDefaultGridColor , sheetViewRightToLeft , sheetViewShowFormulas , sheetViewShowGridLines , sheetViewShowOutlineSymbols , sheetViewShowRowColHeaders , sheetViewShowRuler , sheetViewShowWhiteSpace , sheetViewShowZeros , sheetViewTabSelected , sheetViewTopLeftCell , sheetViewType , sheetViewWindowProtection , sheetViewWorkbookViewId , sheetViewZoomScale , sheetViewZoomScaleNormal , sheetViewZoomScalePageLayoutView , sheetViewZoomScaleSheetLayoutView , sheetViewPane , sheetViewSelection -- ** Selection , selectionActiveCell , selectionActiveCellId , selectionPane , selectionSqref -- ** Pane , paneActivePane , paneState , paneTopLeftCell , paneXSplit , paneYSplit ) where import GHC.Generics (Generic) #ifdef USE_MICROLENS import Lens.Micro.TH (makeLenses) #else import Control.Lens (makeLenses) #endif import Control.DeepSeq (NFData) import Data.Default import Data.Maybe (catMaybes, maybeToList, listToMaybe) import Text.XML import Text.XML.Cursor import qualified Data.Map as Map import Codec.Xlsx.Types.Common import Codec.Xlsx.Parser.Internal import Codec.Xlsx.Writer.Internal {------------------------------------------------------------------------------- Main types -------------------------------------------------------------------------------} -- | Worksheet view -- -- A single sheet view definition. When more than one sheet view is defined in -- the file, it means that when opening the workbook, each sheet view -- corresponds to a separate window within the spreadsheet application, where -- each window is showing the particular sheet containing the same -- workbookViewId value, the last sheetView definition is loaded, and the others -- are discarded. When multiple windows are viewing the same sheet, multiple -- sheetView elements (with corresponding workbookView entries) are saved. -- -- TODO: The @pivotSelection@ and @extLst@ child elements are unsupported. -- -- See Section 18.3.1.87 "sheetView (Worksheet View)" (p. 1880) data SheetView = SheetView { -- | Index to the color value for row/column text headings and gridlines. -- This is an 'index color value' (ICV) rather than rgb value. _sheetViewColorId :: Maybe Int -- | Flag indicating that the consuming application should use the default -- grid lines color (system dependent). Overrides any color specified in -- colorId. , _sheetViewDefaultGridColor :: Maybe Bool -- | Flag indicating whether the sheet is in 'right to left' display mode. -- When in this mode, Column A is on the far right, Column B ;is one column -- left of Column A, and so on. Also, information in cells is displayed in -- the Right to Left format. , _sheetViewRightToLeft :: Maybe Bool -- | Flag indicating whether this sheet should display formulas. , _sheetViewShowFormulas :: Maybe Bool -- | Flag indicating whether this sheet should display gridlines. , _sheetViewShowGridLines :: Maybe Bool -- | Flag indicating whether the sheet has outline symbols visible. This -- flag shall always override SheetPr element's outlinePr child element -- whose attribute is named showOutlineSymbols when there is a conflict. , _sheetViewShowOutlineSymbols :: Maybe Bool -- | Flag indicating whether the sheet should display row and column headings. , _sheetViewShowRowColHeaders :: Maybe Bool -- | Show the ruler in Page Layout View. , _sheetViewShowRuler :: Maybe Bool -- | Flag indicating whether page layout view shall display margins. False -- means do not display left, right, top (header), and bottom (footer) -- margins (even when there is data in the header or footer). , _sheetViewShowWhiteSpace :: Maybe Bool -- | Flag indicating whether the window should show 0 (zero) in cells -- containing zero value. When false, cells with zero value appear blank -- instead of showing the number zero. , _sheetViewShowZeros :: Maybe Bool -- | Flag indicating whether this sheet is selected. When only 1 sheet is -- selected and active, this value should be in synch with the activeTab -- value. In case of a conflict, the Start Part setting wins and sets the -- active sheet tab. -- -- Multiple sheets can be selected, but only one sheet shall be active at -- one time. , _sheetViewTabSelected :: Maybe Bool -- | Location of the top left visible cell Location of the top left visible -- cell in the bottom right pane (when in Left-to-Right mode). , _sheetViewTopLeftCell :: Maybe CellRef -- | Indicates the view type. , _sheetViewType :: Maybe SheetViewType -- | Flag indicating whether the panes in the window are locked due to -- workbook protection. This is an option when the workbook structure is -- protected. , _sheetViewWindowProtection :: Maybe Bool -- | Zero-based index of this workbook view, pointing to a workbookView -- element in the bookViews collection. -- -- NOTE: This attribute is required. , _sheetViewWorkbookViewId :: Int -- | Window zoom magnification for current view representing percent values. -- This attribute is restricted to values ranging from 10 to 400. Horizontal & -- Vertical scale together. , _sheetViewZoomScale :: Maybe Int -- | Zoom magnification to use when in normal view, representing percent -- values. This attribute is restricted to values ranging from 10 to 400. -- Horizontal & Vertical scale together. , _sheetViewZoomScaleNormal :: Maybe Int -- | Zoom magnification to use when in page layout view, representing -- percent values. This attribute is restricted to values ranging from 10 to -- 400. Horizontal & Vertical scale together. , _sheetViewZoomScalePageLayoutView :: Maybe Int -- | Zoom magnification to use when in page break preview, representing -- percent values. This attribute is restricted to values ranging from 10 to -- 400. Horizontal & Vertical scale together. , _sheetViewZoomScaleSheetLayoutView :: Maybe Int -- | Worksheet view pane , _sheetViewPane :: Maybe Pane -- | Worksheet view selection -- -- Minimum of 0, maximum of 4 elements , _sheetViewSelection :: [Selection] } deriving (Eq, Ord, Show, Generic) instance NFData SheetView -- | Worksheet view selection. -- -- Section 18.3.1.78 "selection (Selection)" (p. 1864) data Selection = Selection { -- | Location of the active cell _selectionActiveCell :: Maybe CellRef -- | 0-based index of the range reference (in the array of references listed -- in sqref) containing the active cell. Only used when the selection in -- sqref is not contiguous. Therefore, this value needs to be aware of the -- order in which the range references are written in sqref. -- -- When this value is out of range then activeCell can be used. , _selectionActiveCellId :: Maybe Int -- | The pane to which this selection belongs. , _selectionPane :: Maybe PaneType -- | Range of the selection. Can be non-contiguous set of ranges. , _selectionSqref :: Maybe SqRef } deriving (Eq, Ord, Show, Generic) instance NFData Selection -- | Worksheet view pane -- -- Section 18.3.1.66 "pane (View Pane)" (p. 1843) data Pane = Pane { -- | The pane that is active. _paneActivePane :: Maybe PaneType -- | Indicates whether the pane has horizontal / vertical splits, and -- whether those splits are frozen. , _paneState :: Maybe PaneState -- | Location of the top left visible cell in the bottom right pane (when in -- Left-To-Right mode). , _paneTopLeftCell :: Maybe CellRef -- | Horizontal position of the split, in 1/20th of a point; 0 (zero) if -- none. If the pane is frozen, this value indicates the number of columns -- visible in the top pane. , _paneXSplit :: Maybe Double -- | Vertical position of the split, in 1/20th of a point; 0 (zero) if none. -- If the pane is frozen, this value indicates the number of rows visible in -- the left pane. , _paneYSplit :: Maybe Double } deriving (Eq, Ord, Show, Generic) instance NFData Pane {------------------------------------------------------------------------------- Enumerations -------------------------------------------------------------------------------} -- | View setting of the sheet -- -- Section 18.18.69 "ST_SheetViewType (Sheet View Type)" (p. 2726) data SheetViewType = -- | Normal view SheetViewTypeNormal -- | Page break preview | SheetViewTypePageBreakPreview -- | Page layout view | SheetViewTypePageLayout deriving (Eq, Ord, Show, Generic) instance NFData SheetViewType -- | Pane type -- -- Section 18.18.52 "ST_Pane (Pane Types)" (p. 2710) data PaneType = -- | Bottom left pane, when both vertical and horizontal splits are applied. -- -- This value is also used when only a horizontal split has been applied, -- dividing the pane into upper and lower regions. In that case, this value -- specifies the bottom pane. PaneTypeBottomLeft -- Bottom right pane, when both vertical and horizontal splits are applied. | PaneTypeBottomRight -- | Top left pane, when both vertical and horizontal splits are applied. -- -- This value is also used when only a horizontal split has been applied, -- dividing the pane into upper and lower regions. In that case, this value -- specifies the top pane. -- -- This value is also used when only a vertical split has been applied, -- dividing the pane into right and left regions. In that case, this value -- specifies the left pane | PaneTypeTopLeft -- | Top right pane, when both vertical and horizontal splits are applied. -- -- This value is also used when only a vertical split has been applied, -- dividing the pane into right and left regions. In that case, this value -- specifies the right pane. | PaneTypeTopRight deriving (Eq, Ord, Show, Generic) instance NFData PaneType -- | State of the sheet's pane. -- -- Section 18.18.53 "ST_PaneState (Pane State)" (p. 2711) data PaneState = -- | Panes are frozen, but were not split being frozen. In this state, when -- the panes are unfrozen again, a single pane results, with no split. In -- this state, the split bars are not adjustable. PaneStateFrozen -- | Panes are frozen and were split before being frozen. In this state, -- when the panes are unfrozen again, the split remains, but is adjustable. | PaneStateFrozenSplit -- | Panes are split, but not frozen. In this state, the split bars are -- adjustable by the user. | PaneStateSplit deriving (Eq, Ord, Show, Generic) instance NFData PaneState {------------------------------------------------------------------------------- Lenses -------------------------------------------------------------------------------} makeLenses ''SheetView makeLenses ''Selection makeLenses ''Pane {------------------------------------------------------------------------------- Default instances -------------------------------------------------------------------------------} -- | NOTE: The 'Default' instance for 'SheetView' sets the required attribute -- '_sheetViewWorkbookViewId' to @0@. instance Default SheetView where def = SheetView { _sheetViewColorId = Nothing , _sheetViewDefaultGridColor = Nothing , _sheetViewRightToLeft = Nothing , _sheetViewShowFormulas = Nothing , _sheetViewShowGridLines = Nothing , _sheetViewShowOutlineSymbols = Nothing , _sheetViewShowRowColHeaders = Nothing , _sheetViewShowRuler = Nothing , _sheetViewShowWhiteSpace = Nothing , _sheetViewShowZeros = Nothing , _sheetViewTabSelected = Nothing , _sheetViewTopLeftCell = Nothing , _sheetViewType = Nothing , _sheetViewWindowProtection = Nothing , _sheetViewWorkbookViewId = 0 , _sheetViewZoomScale = Nothing , _sheetViewZoomScaleNormal = Nothing , _sheetViewZoomScalePageLayoutView = Nothing , _sheetViewZoomScaleSheetLayoutView = Nothing , _sheetViewPane = Nothing , _sheetViewSelection = [] } instance Default Selection where def = Selection { _selectionActiveCell = Nothing , _selectionActiveCellId = Nothing , _selectionPane = Nothing , _selectionSqref = Nothing } instance Default Pane where def = Pane { _paneActivePane = Nothing , _paneState = Nothing , _paneTopLeftCell = Nothing , _paneXSplit = Nothing , _paneYSplit = Nothing } {------------------------------------------------------------------------------- Rendering -------------------------------------------------------------------------------} -- | See @CT_SheetView@, p. 3913 instance ToElement SheetView where toElement nm SheetView{..} = Element { elementName = nm , elementNodes = map NodeElement . concat $ [ map (toElement "pane") (maybeToList _sheetViewPane) , map (toElement "selection") _sheetViewSelection -- TODO: pivotSelection -- TODO: extLst ] , elementAttributes = Map.fromList . catMaybes $ [ "windowProtection" .=? _sheetViewWindowProtection , "showFormulas" .=? _sheetViewShowFormulas , "showGridLines" .=? _sheetViewShowGridLines , "showRowColHeaders" .=? _sheetViewShowRowColHeaders , "showZeros" .=? _sheetViewShowZeros , "rightToLeft" .=? _sheetViewRightToLeft , "tabSelected" .=? _sheetViewTabSelected , "showRuler" .=? _sheetViewShowRuler , "showOutlineSymbols" .=? _sheetViewShowOutlineSymbols , "defaultGridColor" .=? _sheetViewDefaultGridColor , "showWhiteSpace" .=? _sheetViewShowWhiteSpace , "view" .=? _sheetViewType , "topLeftCell" .=? _sheetViewTopLeftCell , "colorId" .=? _sheetViewColorId , "zoomScale" .=? _sheetViewZoomScale , "zoomScaleNormal" .=? _sheetViewZoomScaleNormal , "zoomScaleSheetLayoutView" .=? _sheetViewZoomScaleSheetLayoutView , "zoomScalePageLayoutView" .=? _sheetViewZoomScalePageLayoutView , Just $ "workbookViewId" .= _sheetViewWorkbookViewId ] } -- | See @CT_Selection@, p. 3914 instance ToElement Selection where toElement nm Selection{..} = Element { elementName = nm , elementNodes = [] , elementAttributes = Map.fromList . catMaybes $ [ "pane" .=? _selectionPane , "activeCell" .=? _selectionActiveCell , "activeCellId" .=? _selectionActiveCellId , "sqref" .=? _selectionSqref ] } -- | See @CT_Pane@, p. 3913 instance ToElement Pane where toElement nm Pane{..} = Element { elementName = nm , elementNodes = [] , elementAttributes = Map.fromList . catMaybes $ [ "xSplit" .=? _paneXSplit , "ySplit" .=? _paneYSplit , "topLeftCell" .=? _paneTopLeftCell , "activePane" .=? _paneActivePane , "state" .=? _paneState ] } -- | See @ST_SheetViewType@, p. 3913 instance ToAttrVal SheetViewType where toAttrVal SheetViewTypeNormal = "normal" toAttrVal SheetViewTypePageBreakPreview = "pageBreakPreview" toAttrVal SheetViewTypePageLayout = "pageLayout" -- | See @ST_Pane@, p. 3914 instance ToAttrVal PaneType where toAttrVal PaneTypeBottomRight = "bottomRight" toAttrVal PaneTypeTopRight = "topRight" toAttrVal PaneTypeBottomLeft = "bottomLeft" toAttrVal PaneTypeTopLeft = "topLeft" -- | See @ST_PaneState@, p. 3929 instance ToAttrVal PaneState where toAttrVal PaneStateSplit = "split" toAttrVal PaneStateFrozen = "frozen" toAttrVal PaneStateFrozenSplit = "frozenSplit" {------------------------------------------------------------------------------- Parsing -------------------------------------------------------------------------------} -- | See @CT_SheetView@, p. 3913 instance FromCursor SheetView where fromCursor cur = do _sheetViewWindowProtection <- maybeAttribute "windowProtection" cur _sheetViewShowFormulas <- maybeAttribute "showFormulas" cur _sheetViewShowGridLines <- maybeAttribute "showGridLines" cur _sheetViewShowRowColHeaders <- maybeAttribute "showRowColHeaders"cur _sheetViewShowZeros <- maybeAttribute "showZeros" cur _sheetViewRightToLeft <- maybeAttribute "rightToLeft" cur _sheetViewTabSelected <- maybeAttribute "tabSelected" cur _sheetViewShowRuler <- maybeAttribute "showRuler" cur _sheetViewShowOutlineSymbols <- maybeAttribute "showOutlineSymbols" cur _sheetViewDefaultGridColor <- maybeAttribute "defaultGridColor" cur _sheetViewShowWhiteSpace <- maybeAttribute "showWhiteSpace" cur _sheetViewType <- maybeAttribute "view" cur _sheetViewTopLeftCell <- maybeAttribute "topLeftCell" cur _sheetViewColorId <- maybeAttribute "colorId" cur _sheetViewZoomScale <- maybeAttribute "zoomScale" cur _sheetViewZoomScaleNormal <- maybeAttribute "zoomScaleNormal" cur _sheetViewZoomScaleSheetLayoutView <- maybeAttribute "zoomScaleSheetLayoutView" cur _sheetViewZoomScalePageLayoutView <- maybeAttribute "zoomScalePageLayoutView" cur _sheetViewWorkbookViewId <- fromAttribute "workbookViewId" cur let _sheetViewPane = listToMaybe $ cur $/ element (n_ "pane") >=> fromCursor _sheetViewSelection = cur $/ element (n_ "selection") >=> fromCursor return SheetView{..} instance FromXenoNode SheetView where fromXenoNode root = parseAttributes root $ do _sheetViewWindowProtection <- maybeAttr "windowProtection" _sheetViewShowFormulas <- maybeAttr "showFormulas" _sheetViewShowGridLines <- maybeAttr "showGridLines" _sheetViewShowRowColHeaders <- maybeAttr "showRowColHeaders" _sheetViewShowZeros <- maybeAttr "showZeros" _sheetViewRightToLeft <- maybeAttr "rightToLeft" _sheetViewTabSelected <- maybeAttr "tabSelected" _sheetViewShowRuler <- maybeAttr "showRuler" _sheetViewShowOutlineSymbols <- maybeAttr "showOutlineSymbols" _sheetViewDefaultGridColor <- maybeAttr "defaultGridColor" _sheetViewShowWhiteSpace <- maybeAttr "showWhiteSpace" _sheetViewType <- maybeAttr "view" _sheetViewTopLeftCell <- maybeAttr "topLeftCell" _sheetViewColorId <- maybeAttr "colorId" _sheetViewZoomScale <- maybeAttr "zoomScale" _sheetViewZoomScaleNormal <- maybeAttr "zoomScaleNormal" _sheetViewZoomScaleSheetLayoutView <- maybeAttr "zoomScaleSheetLayoutView" _sheetViewZoomScalePageLayoutView <- maybeAttr "zoomScalePageLayoutView" _sheetViewWorkbookViewId <- fromAttr "workbookViewId" (_sheetViewPane, _sheetViewSelection) <- toAttrParser . collectChildren root $ (,) <$> maybeFromChild "pane" <*> fromChildList "selection" return SheetView {..} -- | See @CT_Pane@, p. 3913 instance FromCursor Pane where fromCursor cur = do _paneXSplit <- maybeAttribute "xSplit" cur _paneYSplit <- maybeAttribute "ySplit" cur _paneTopLeftCell <- maybeAttribute "topLeftCell" cur _paneActivePane <- maybeAttribute "activePane" cur _paneState <- maybeAttribute "state" cur return Pane{..} instance FromXenoNode Pane where fromXenoNode root = parseAttributes root $ do _paneXSplit <- maybeAttr "xSplit" _paneYSplit <- maybeAttr "ySplit" _paneTopLeftCell <- maybeAttr "topLeftCell" _paneActivePane <- maybeAttr "activePane" _paneState <- maybeAttr "state" return Pane {..} -- | See @CT_Selection@, p. 3914 instance FromCursor Selection where fromCursor cur = do _selectionPane <- maybeAttribute "pane" cur _selectionActiveCell <- maybeAttribute "activeCell" cur _selectionActiveCellId <- maybeAttribute "activeCellId" cur _selectionSqref <- maybeAttribute "sqref" cur return Selection{..} instance FromXenoNode Selection where fromXenoNode root = parseAttributes root $ do _selectionPane <- maybeAttr "pane" _selectionActiveCell <- maybeAttr "activeCell" _selectionActiveCellId <- maybeAttr "activeCellId" _selectionSqref <- maybeAttr "sqref" return Selection {..} -- | See @ST_SheetViewType@, p. 3913 instance FromAttrVal SheetViewType where fromAttrVal "normal" = readSuccess SheetViewTypeNormal fromAttrVal "pageBreakPreview" = readSuccess SheetViewTypePageBreakPreview fromAttrVal "pageLayout" = readSuccess SheetViewTypePageLayout fromAttrVal t = invalidText "SheetViewType" t instance FromAttrBs SheetViewType where fromAttrBs "normal" = return SheetViewTypeNormal fromAttrBs "pageBreakPreview" = return SheetViewTypePageBreakPreview fromAttrBs "pageLayout" = return SheetViewTypePageLayout fromAttrBs x = unexpectedAttrBs "SheetViewType" x -- | See @ST_Pane@, p. 3914 instance FromAttrVal PaneType where fromAttrVal "bottomRight" = readSuccess PaneTypeBottomRight fromAttrVal "topRight" = readSuccess PaneTypeTopRight fromAttrVal "bottomLeft" = readSuccess PaneTypeBottomLeft fromAttrVal "topLeft" = readSuccess PaneTypeTopLeft fromAttrVal t = invalidText "PaneType" t instance FromAttrBs PaneType where fromAttrBs "bottomRight" = return PaneTypeBottomRight fromAttrBs "topRight" = return PaneTypeTopRight fromAttrBs "bottomLeft" = return PaneTypeBottomLeft fromAttrBs "topLeft" = return PaneTypeTopLeft fromAttrBs x = unexpectedAttrBs "PaneType" x -- | See @ST_PaneState@, p. 3929 instance FromAttrVal PaneState where fromAttrVal "split" = readSuccess PaneStateSplit fromAttrVal "frozen" = readSuccess PaneStateFrozen fromAttrVal "frozenSplit" = readSuccess PaneStateFrozenSplit fromAttrVal t = invalidText "PaneState" t instance FromAttrBs PaneState where fromAttrBs "split" = return PaneStateSplit fromAttrBs "frozen" = return PaneStateFrozen fromAttrBs "frozenSplit" = return PaneStateFrozenSplit fromAttrBs x = unexpectedAttrBs "PaneState" x
qrilka/xlsx
src/Codec/Xlsx/Types/SheetViews.hs
mit
23,436
0
15
5,421
2,898
1,572
1,326
321
0
{- | module: $Header$ description: Names in a hierarchical namespace license: MIT maintainer: Joe Leslie-Hurd <[email protected]> stability: provisional portability: portable -} module HOL.Name where import qualified Data.Char as Char import qualified Data.List as List import qualified Data.Maybe as Maybe import Data.Set (Set) import qualified Data.Set as Set ------------------------------------------------------------------------------- -- Namespaces ------------------------------------------------------------------------------- newtype Namespace = Namespace [String] deriving (Eq,Ord,Show) ------------------------------------------------------------------------------- -- Names ------------------------------------------------------------------------------- data Name = Name Namespace String deriving (Eq,Ord,Show) ------------------------------------------------------------------------------- -- The global namespace (contains all type and term variable names) ------------------------------------------------------------------------------- global :: Namespace global = Namespace [] mkGlobal :: String -> Name mkGlobal = Name global destGlobal :: Name -> Maybe String destGlobal (Name ns s) = if ns == global then Just s else Nothing isGlobal :: Name -> Bool isGlobal = Maybe.isJust . destGlobal ------------------------------------------------------------------------------- -- Fresh names ------------------------------------------------------------------------------- variantAvoiding :: Set Name -> Name -> Name variantAvoiding avoid n = if Set.notMember n avoid then n else variant 0 where Name ns bx = n b = List.dropWhileEnd isDigitOrPrime bx isDigitOrPrime :: Char -> Bool isDigitOrPrime c = Char.isDigit c || c == '\'' variant :: Int -> Name variant i = if Set.notMember ni avoid then ni else variant (i + 1) where ni = Name ns bi bi = b ++ show i freshSupply :: [Name] freshSupply = map mkGlobal (stem ++ concat (map add [(0 :: Int) ..])) where add n = map (++ show n) stem stem = map (: []) "abcdefghijklmnpqrstuvwxyz" ------------------------------------------------------------------------------- -- Standard namespaces ------------------------------------------------------------------------------- -- Booleans boolNamespace :: Namespace boolNamespace = Namespace ["Data","Bool"] -- Lists listNamespace :: Namespace listNamespace = Namespace ["Data","List"] -- Products pairNamespace :: Namespace pairNamespace = Namespace ["Data","Pair"] -- Sums sumNamespace :: Namespace sumNamespace = Namespace ["Data","Sum"] -- Functions functionNamespace :: Namespace functionNamespace = Namespace ["Function"] -- Natural numbers naturalNamespace :: Namespace naturalNamespace = Namespace ["Number","Natural"] -- Real numbers realNamespace :: Namespace realNamespace = Namespace ["Number","Real"] -- Sets setNamespace :: Namespace setNamespace = Namespace ["Set"]
gilith/hol
src/HOL/Name.hs
mit
2,990
0
12
437
614
350
264
52
3
import Control.Monad (msum) import Control.Applicative ((<$>)) import Data.Maybe (fromJust) import Data.List (nub) import Memoize (memoize) import Data.Functor ((<$)) smallestInt :: Int -> Int smallestInt size = fromJust . msum $ map keepIfDecomposable [size ..] where keepIfDecomposable n = n <$ decompose size n decompose :: Int -> Int -> Maybe [Int] decompose size n = decompose' size n n decompose' :: Int -> Int -> Int -> Maybe [Int] decompose' size prod sum' | sum' < size = Nothing | prod == 1 && size == sum' = Just (replicate size 1) | prod == 1 && size /= sum' = Nothing | otherwise = msum $ map f (memoize factors prod) where f d = (d:) <$> decompose' (size - 1) (prod `div` d) (sum' - d) factors :: Int -> [Int] factors n = lower ++ upper' where lower = filter ((0 ==) . mod n) (takeWhile (<= maxFactor) [2..]) maxFactor = truncate (sqrt (fromIntegral n :: Double)) upper = map (div n) (reverse lower) ++ [n] upper' = if maxFactor == head upper then tail upper else upper main :: IO () main = print $ sum . nub $ map smallestInt [2..12000]
afiodorov/projectEuler
88.hs
mit
1,144
0
11
288
501
264
237
26
2
{-# LANGUAGE DeriveDataTypeable #-} -- | We use our own functions for throwing exceptions in order to get -- the actual error message via 'zmq_strerror'. 0MQ defines additional -- error numbers besides those defined by the operating system, so -- 'zmq_strerror' should be used in preference to 'strerror' which is -- used by the standard throw* functions in 'Foreign.C.Error'. -- -- /Warning/: This is an internal module and subject -- to change without notice. module System.ZMQ4.Internal.Error where import Control.Applicative import Control.Monad import Control.Exception import Text.Printf import Data.Typeable (Typeable) import Foreign hiding (throwIf, throwIf_, void) import Foreign.C.Error import Foreign.C.String import Foreign.C.Types (CInt) import Prelude import System.ZMQ4.Internal.Base -- | ZMQError encapsulates information about errors, which occur -- when using the native 0MQ API, such as error number and message. data ZMQError = ZMQError { errno :: Int -- ^ Error number value. , source :: String -- ^ Source where this error originates from. , message :: String -- ^ Actual error message. } deriving (Eq, Ord, Typeable) instance Show ZMQError where show e = printf "ZMQError { errno = %d, source = \"%s\", message = \"%s\" }" (errno e) (source e) (message e) instance Exception ZMQError throwError :: String -> IO a throwError src = do (Errno e) <- zmqErrno msg <- zmqErrnoMessage e throwIO $ ZMQError (fromIntegral e) src msg throwIf :: (a -> Bool) -> String -> IO a -> IO a throwIf p src act = do r <- act if p r then throwError src else return r throwIf_ :: (a -> Bool) -> String -> IO a -> IO () throwIf_ p src act = void $ throwIf p src act throwIfRetry :: (a -> Bool) -> String -> IO a -> IO a throwIfRetry p src act = do r <- act if p r then zmqErrno >>= k else return r where k e | e == eINTR = throwIfRetry p src act | otherwise = throwError src throwIfRetry_ :: (a -> Bool) -> String -> IO a -> IO () throwIfRetry_ p src act = void $ throwIfRetry p src act throwIfMinus1 :: (Eq a, Num a) => String -> IO a -> IO a throwIfMinus1 = throwIf (== -1) throwIfMinus1_ :: (Eq a, Num a) => String -> IO a -> IO () throwIfMinus1_ = throwIf_ (== -1) throwIfNull :: String -> IO (Ptr a) -> IO (Ptr a) throwIfNull = throwIf (== nullPtr) throwIfMinus1Retry :: (Eq a, Num a) => String -> IO a -> IO a throwIfMinus1Retry = throwIfRetry (== -1) throwIfMinus1Retry_ :: (Eq a, Num a) => String -> IO a -> IO () throwIfMinus1Retry_ = throwIfRetry_ (== -1) throwIfRetryMayBlock :: (a -> Bool) -> String -> IO a -> IO b -> IO a throwIfRetryMayBlock p src f on_block = do r <- f if p r then zmqErrno >>= k else return r where k e | e == eINTR = throwIfRetryMayBlock p src f on_block | e == eWOULDBLOCK || e == eAGAIN = on_block >> throwIfRetryMayBlock p src f on_block | otherwise = throwError src throwIfRetryMayBlock_ :: (a -> Bool) -> String -> IO a -> IO b -> IO () throwIfRetryMayBlock_ p src f on_block = void $ throwIfRetryMayBlock p src f on_block throwIfMinus1RetryMayBlock :: (Eq a, Num a) => String -> IO a -> IO b -> IO a throwIfMinus1RetryMayBlock = throwIfRetryMayBlock (== -1) throwIfMinus1RetryMayBlock_ :: (Eq a, Num a) => String -> IO a -> IO b -> IO () throwIfMinus1RetryMayBlock_ = throwIfRetryMayBlock_ (== -1) zmqErrnoMessage :: CInt -> IO String zmqErrnoMessage e = c_zmq_strerror e >>= peekCString zmqErrno :: IO Errno zmqErrno = Errno <$> c_zmq_errno
twittner/zeromq-haskell
src/System/ZMQ4/Internal/Error.hs
mit
3,573
0
12
795
1,158
593
565
68
2