code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE OverloadedStrings #-} module Main where import Common import Web.Twitter.Conduit import Web.Twitter.Types.Lens import Control.Lens import qualified Data.Text as T import System.Environment main :: IO () main = do [keyword] <- getArgs twInfo <- getTWInfoFromEnv mgr <- newManager tlsManagerSettings res <- call twInfo mgr $ search $ T.pack keyword let metadata = res ^. searchResultSearchMetadata putStrLn $ "search completed in: " ++ metadata ^. searchMetadataCompletedIn . to show putStrLn $ "search result max id: " ++ metadata ^. searchMetadataMaxId . to show print $ res ^. searchResultStatuses
himura/twitter-conduit
sample/search.hs
bsd-2-clause
650
0
10
125
174
89
85
-1
-1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Numeral.Tests (tests) where import Data.String import Prelude import Test.Tasty import qualified Duckling.Numeral.AF.Tests as AF import qualified Duckling.Numeral.AR.Tests as AR import qualified Duckling.Numeral.BG.Tests as BG import qualified Duckling.Numeral.BN.Tests as BN import qualified Duckling.Numeral.CA.Tests as CA import qualified Duckling.Numeral.CS.Tests as CS import qualified Duckling.Numeral.DA.Tests as DA import qualified Duckling.Numeral.DE.Tests as DE import qualified Duckling.Numeral.EL.Tests as EL import qualified Duckling.Numeral.EN.Tests as EN import qualified Duckling.Numeral.ES.Tests as ES import qualified Duckling.Numeral.ET.Tests as ET import qualified Duckling.Numeral.FI.Tests as FI import qualified Duckling.Numeral.FA.Tests as FA import qualified Duckling.Numeral.FR.Tests as FR import qualified Duckling.Numeral.GA.Tests as GA import qualified Duckling.Numeral.HE.Tests as HE import qualified Duckling.Numeral.HI.Tests as HI import qualified Duckling.Numeral.HR.Tests as HR import qualified Duckling.Numeral.HU.Tests as HU import qualified Duckling.Numeral.ID.Tests as ID import qualified Duckling.Numeral.IS.Tests as IS import qualified Duckling.Numeral.IT.Tests as IT import qualified Duckling.Numeral.JA.Tests as JA import qualified Duckling.Numeral.KA.Tests as KA import qualified Duckling.Numeral.KM.Tests as KM import qualified Duckling.Numeral.KN.Tests as KN import qualified Duckling.Numeral.KO.Tests as KO import qualified Duckling.Numeral.LO.Tests as LO import qualified Duckling.Numeral.ML.Tests as ML import qualified Duckling.Numeral.MN.Tests as MN import qualified Duckling.Numeral.MY.Tests as MY import qualified Duckling.Numeral.NB.Tests as NB import qualified Duckling.Numeral.NE.Tests as NE import qualified Duckling.Numeral.NL.Tests as NL import qualified Duckling.Numeral.PL.Tests as PL import qualified Duckling.Numeral.PT.Tests as PT import qualified Duckling.Numeral.RO.Tests as RO import qualified Duckling.Numeral.RU.Tests as RU import qualified Duckling.Numeral.SK.Tests as SK import qualified Duckling.Numeral.SV.Tests as SV import qualified Duckling.Numeral.SW.Tests as SW import qualified Duckling.Numeral.TA.Tests as TA import qualified Duckling.Numeral.TE.Tests as TE import qualified Duckling.Numeral.TH.Tests as TH import qualified Duckling.Numeral.TR.Tests as TR import qualified Duckling.Numeral.UK.Tests as UK import qualified Duckling.Numeral.VI.Tests as VI import qualified Duckling.Numeral.ZH.Tests as ZH tests :: TestTree tests = testGroup "Numeral Tests" [ AF.tests , AR.tests , BG.tests , BN.tests , CA.tests , CS.tests , DA.tests , DE.tests , EL.tests , EN.tests , ES.tests , ET.tests , FA.tests , FR.tests , FI.tests , GA.tests , HE.tests , HI.tests , HR.tests , HU.tests , ID.tests , IS.tests , IT.tests , JA.tests , KA.tests , KM.tests , KN.tests , KO.tests , LO.tests , ML.tests , MN.tests , MY.tests , NB.tests , NE.tests , NL.tests , PL.tests , PT.tests , RO.tests , RU.tests , SK.tests , SV.tests , SW.tests , TA.tests , TE.tests , TH.tests , TR.tests , UK.tests , VI.tests , ZH.tests ]
facebookincubator/duckling
tests/Duckling/Numeral/Tests.hs
bsd-3-clause
3,400
0
7
502
780
568
212
104
1
module Turbinado.Environment.CodeStore ( addCodeStoreToEnvironment, retrieveCode, ) where import Control.Concurrent.MVar import Control.Exception ( catch, throwIO) import Control.Monad ( when, foldM) import Data.Map hiding (map) import Data.List (isPrefixOf, intersperse) import Data.Maybe import Data.Time import Data.Time.Clock.POSIX import Data.Typeable import qualified Network.HTTP as HTTP import Prelude hiding (lookup,catch) import System.Directory import System.FilePath import System.IO import System.Plugins import System.Plugins.Utils import System.Time import Config.Master import qualified Turbinado.Server.Exception as Ex import Turbinado.Environment.Logger import Turbinado.Environment.Types import Turbinado.Environment.Request import Turbinado.Environment.Response import Turbinado.Utility.Data import Turbinado.View.Monad hiding (liftIO) import Turbinado.View.XML import Turbinado.Controller.Monad -- | Create a new store for Code data addCodeStoreToEnvironment :: (HasEnvironment m) => m () addCodeStoreToEnvironment = do e <- getEnvironment mv <- liftIO $ newMVar $ empty setEnvironment $ e {getCodeStore = Just $ CodeStore mv} -- | This function attempts to pull a function from a pre-loaded cache or, if -- the function doesn't exist or is out-of-date, loads the code from disk. retrieveCode :: (HasEnvironment m) => CodeType -> CodeLocation -> m CodeStatus retrieveCode ct cl' = do e <- getEnvironment let (CodeStore mv) = fromJust' "CodeStore: retrieveCode" $ getCodeStore e path = getDir ct cl <- return (addExtension (joinPath $ map normalise [path, dropExtension $ fst cl']) "hs", snd cl') debugM $ " CodeStore : retrieveCode : loading " ++ (fst cl) ++ " - " ++ (snd cl) cmap <- liftIO $ takeMVar mv let c= lookup cl cmap cmap' <- case c of Nothing -> do debugM ((fst cl) ++ " : " ++ (snd cl) ++ " : fresh load") loadCode ct cmap cl Just (CodeLoadFailure _) -> do debugM ((fst cl) ++ " : " ++ (snd cl) ++ " : previous failure; try load") loadCode ct cmap cl _ -> do debugM ((fst cl) ++ " : " ++ (snd cl) ++ " : checking reload") checkReloadCode ct cmap (fromJust' "CodeStore: retrieveCode2" c) cl liftIO $ putMVar mv cmap' -- We _definitely_ have a code entry now, though it may have a MakeFailure let c' = lookup cl cmap' case c' of Nothing -> do debugM (fst cl ++ " : Not found in CodeStore") return CodeLoadMissing Just CodeLoadMissing -> do debugM (fst cl ++ " : Not found in CodeStore") return CodeLoadMissing Just (CodeLoadFailure e) -> do debugM (fst cl ++ " : CodeLoadFailure " ) return (CodeLoadFailure e) Just clc@(CodeLoadController _ _) -> do debugM (fst cl ++ " : CodeLoadController " ) return clc Just clv@(CodeLoadView _ _) -> do debugM (fst cl ++ " : CodeLoadView" ) return clv Just clc@(CodeLoadComponentController _ _) -> do debugM (fst cl ++ " : CodeLoadComponentController " ) return clc Just clv@(CodeLoadComponentView _ _) -> do debugM (fst cl ++ " : CodeLoadComponentView" ) return clv -- | Checks to see if the file exists and if the file is newer than the loaded function. If the -- code needs to be reloaded, then 'loadCode' will be called. checkReloadCode :: (HasEnvironment m) => CodeType -> CodeMap -> CodeStatus -> CodeLocation -> m CodeMap checkReloadCode ct cmap (CodeLoadFailure e) cl = error "ERROR: checkReloadCode was called with a CodeLoadFailure" checkReloadCode ct cmap cstat cl = do debugM $ " CodeStore : checkReloadCode : loading " ++ (fst cl) ++ " - " ++ (snd cl) (exists, reload) <- needReloadCode (fst cl) (getDate cstat) case (exists, reload) of (False, _) -> do debugM $ " CodeStore : checkReloadCode : Code missing" return $ insert cl CodeLoadMissing cmap (True, False) -> do debugM $ " CodeStore : checkReloadCode : No reload neeeded" return cmap (True, True) -> do debugM $ " CodeStore : checkReloadCode : Need reload" loadCode ct cmap cl where needReloadCode :: (HasEnvironment m) => FilePath -> CodeDate -> m (Bool, Bool) needReloadCode fp fd = do fe <- liftIO $ doesFileExist fp case fe of True -> do TOD mt _ <- liftIO $ getModificationTime fp return $ (True, fromIntegral mt > utcTimeToPOSIXSeconds fd) False-> return (False, True) -------------------------------------------------------------------------- -- The beast -------------------------------------------------------------------------- -- | Begins the code load process, which comprises merging the code with -- the appropriate Stub (in Turbinado/Stubs) to the tmp/compiled directory, -- making the code, and loading it. loadCode :: (HasEnvironment m) => CodeType -> CodeMap -> CodeLocation -> m CodeMap loadCode ct cmap cl = do debugM $ "\tCodeStore : loadCode : loading " ++ (fst cl) ++ " - " ++ (snd cl) mergeCode ct cmap cl -- | Merges the application code with the appropriate Stub, places the merged -- file into @tmp/compiled@, then calls 'makeCode'. mergeCode :: (HasEnvironment m) => CodeType -> CodeMap -> CodeLocation -> m CodeMap mergeCode ct cmap cl = do debugM $ "\tMerging " ++ (fst cl) ms <- customMergeToDir (joinPath [normalise $ getStub ct]) (fst cl) compiledDir case ms of MergeFailure err -> do debugM ("\tMerge error : " ++ (show err)) return $ insert cl (CodeLoadFailure $ unlines err) cmap MergeSuccess NotReq _ _ -> do debugM ("\tMerge success (No recompilation required) : " ++ (fst cl)) return cmap MergeSuccess _ args fp -> do debugM ("\tMerge success : " ++ (fst cl)) makeCode ct cmap cl args fp -- | Attempt to make the code, then call the loader appropriate for the 'CodeType' (e.g. @View@ -> '_loadView'). makeCode :: (HasEnvironment m) => CodeType -> CodeMap -> CodeLocation -> [Arg] -> FilePath -> m CodeMap makeCode ct cmap cl args fp = do ms <- liftIO $ makeAll fp (compileArgs++args) case ms of MakeFailure err -> do debugM ("\tMake error : " ++ (show err)) return (insert cl (CodeLoadFailure $ unlines err) cmap) MakeSuccess NotReq _ -> do debugM ("\tMake success : No recomp required") return cmap MakeSuccess _ fp -> do debugM ("\tMake success : " ++ fp) case ct of CTLayout -> _loadView ct cmap cl args fp CTView -> _loadView ct cmap cl args fp CTComponentView -> _loadView ct cmap cl args fp CTController -> _loadController ct cmap cl args fp CTComponentController -> _loadController ct cmap cl args fp -- | Attempt to load the code and return the 'CodeMap' with the newly loaded code in it. This -- function is specialized for Views. _loadView :: (HasEnvironment m) => CodeType -> CodeMap -> CodeLocation -> [Arg] -> FilePath -> m CodeMap _loadView ct cmap cl args fp = do debugM ("_load : " ++ (show ct) ++ " : " ++ (fst cl) ++ " : " ++ (snd cl)) ls <- liftIO $ load_ fp [compiledDir] (snd cl) case ls of LoadFailure err -> do debugM ("LoadFailure : " ++ (show err)) return (insert cl (CodeLoadFailure $ unlines err) cmap) LoadSuccess m f -> do debugM ("LoadSuccess : " ++ fst cl ) liftIO $ unload m t <- liftIO $ getCurrentTime case ct of CTLayout -> return (insert cl (CodeLoadView f t) cmap) CTView -> return (insert cl (CodeLoadView f t) cmap) CTComponentView -> return (insert cl (CodeLoadComponentView f t) cmap) _ -> error $ "_loadView: passed an invalid CodeType (" ++ (show ct) -- | Attempt to load the code and return the 'CodeMap' with the newly loaded code in it. This -- function is specialized for Controllers. _loadController :: (HasEnvironment m) => CodeType -> CodeMap -> CodeLocation -> [Arg] -> FilePath -> m CodeMap _loadController ct cmap cl args fp = do debugM ("_load : " ++ (show ct) ++ " : " ++ (fst cl) ++ " : " ++ (snd cl)) ls <- liftIO $ load_ fp [compiledDir] (snd cl) case ls of LoadFailure err -> do debugM ("LoadFailure : " ++ (show err)) return (insert cl (CodeLoadFailure $ unlines err) cmap) LoadSuccess m f -> do debugM ("LoadSuccess : " ++ fst cl ) liftIO $ unload m t <- liftIO $ getCurrentTime case ct of CTController -> return (insert cl (CodeLoadController f t) cmap) CTComponentController -> return (insert cl (CodeLoadComponentController f t) cmap) _ -> error $ "_loadController: passed an invalid CodeType (" ++ (show ct) ++ ")" ------------------------------------------------------------------------------------------------- -- Utility functions ------------------------------------------------------------------------------------------------- -- | Custom merge function because I don't want to have to use a custom -- version of Plugins (with HSX enabled) customMergeToDir :: (HasEnvironment m) => FilePath -> FilePath -> FilePath -> m MergeStatus customMergeToDir stb src dir = do src_exists <- liftIO $ doesFileExist src stb_exists <- liftIO $ doesFileExist stb let outFile = joinPath [dir, src] outDir = joinPath $ init $ splitDirectories outFile outMod = concat $ intersperse "." $ splitDirectories $ dropExtension src outTitle = "module " ++ outMod ++ " where \n\n" case (src_exists, stb_exists) of (False, _) -> return $ MergeFailure ["Source file does not exist : "++src] (_, False) -> return $ MergeFailure ["Source file does not exist : "++stb] _ -> do src_str <- liftIO $ readFile src stb_str <- liftIO $ readFile stb let (stbimps, stbdecls) = span ( not . isPrefixOf "-- SPLIT HERE") $ lines stb_str mrg_str = outTitle ++ (unlines stbimps) ++ src_str ++ (unlines stbdecls) liftIO $ createDirectoryIfMissing True outDir hdl <- liftIO $ openFile outFile WriteMode -- overwrite! liftIO $ hPutStr hdl mrg_str liftIO $ hClose hdl return $ MergeSuccess ReComp [] outFile -- must have recreated file -- | Given a 'CodeType', return the base path to the code (e.g. @CTController@ -> @App/Controllers@). getDir :: CodeType -> FilePath getDir ct = case ct of CTLayout -> layoutDir CTController -> controllerDir CTView -> viewDir CTComponentController -> componentControllerDir CTComponentView -> componentViewDir getStub :: CodeType -> FilePath getStub ct = case ct of CTLayout -> layoutStub CTController -> controllerStub CTView -> viewStub CTComponentController -> controllerStub CTComponentView -> viewStub getDate (CodeLoadMissing) = error "getDate called with CodeLoadMissing" getDate (CodeLoadFailure e) = error "getDate called with CodeLoadFailure" getDate (CodeLoadView _ d) = d getDate (CodeLoadController _ d) = d getDate (CodeLoadComponentView _ d) = d getDate (CodeLoadComponentController _ d) = d
abuiles/turbinado-blog
Turbinado/Environment/CodeStore.hs
bsd-3-clause
13,002
0
19
4,481
3,168
1,562
1,606
188
9
{-# LANGUAGE CPP, TypeSynonymInstances, DeriveDataTypeable, FlexibleInstances, GeneralizedNewtypeDeriving, OverloadedStrings, FlexibleContexts #-} {-# OPTIONS_HADDOCK not-home #-} -- |A type for profile preferences. These preference values are used by both -- Firefox and Opera profiles. module Test.WebDriver.Common.Profile ( -- *Profiles and profile preferences Profile(..), PreparedProfile(..), ProfilePref(..), ToPref(..) -- * Preferences , getPref, addPref, deletePref -- * Extensions , addExtension, deleteExtension, hasExtension -- * Other files and directories , addFile, deleteFile, hasFile -- * Miscellaneous profile operations , unionProfiles, onProfileFiles, onProfilePrefs -- *Preparing profiles from disk , prepareLoadedProfile_ -- *Preparing zipped profiles , prepareZippedProfile, prepareZipArchive, prepareRawZip -- *Profile errors , ProfileParseError(..) ) where import System.Directory import System.FilePath hiding (addExtension, hasExtension) import Codec.Archive.Zip import Data.Aeson import Data.Aeson.Types import Data.Attoparsec.Number (Number(..)) import qualified Data.HashMap.Strict as HM import Data.Text (Text, pack) import Data.ByteString.Lazy (ByteString) --import qualified Data.ByteString as SBS import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Base64.Lazy as B64 import Data.Fixed import Data.Ratio import Data.Int import Data.Word import Data.Typeable import Control.Exception import Control.Applicative import Control.Monad.Base -- |This structure allows you to construct and manipulate profiles in pure code, -- deferring execution of IO operations until the profile is \"prepared\". This -- type is shared by both Firefox and Opera profiles; when a distinction -- must be made, the phantom type parameter is used to differentiate. data Profile b = Profile { -- |A mapping from relative destination filepaths to source -- filepaths found on the filesystem. When the profile is -- prepared, these source filepaths will be moved to their -- destinations within the profile directory. -- -- Using the destination path as the key ensures that -- there is one unique source path going to each -- destination path. profileFiles :: HM.HashMap FilePath FilePath -- |A map of profile preferences. These are the settings -- found in the profile's prefs.js, and entries found in -- about:config , profilePrefs :: HM.HashMap Text ProfilePref } deriving (Eq, Show) -- |Represents a profile that has been prepared for -- network transmission. The profile cannot be modified in this form. newtype PreparedProfile b = PreparedProfile ByteString deriving (Eq, Show) instance FromJSON (PreparedProfile s) where parseJSON v = PreparedProfile <$> parseJSON v instance ToJSON (PreparedProfile s) where toJSON (PreparedProfile s) = toJSON s -- |A profile preference value. This is the subset of JSON values that excludes -- arrays, objects, and null. data ProfilePref = PrefInteger !Integer | PrefDouble !Double | PrefString !Text | PrefBool !Bool deriving (Eq, Show) instance ToJSON ProfilePref where toJSON v = case v of PrefInteger i -> toJSON i PrefDouble d -> toJSON d PrefString s -> toJSON s PrefBool b -> toJSON b instance FromJSON ProfilePref where parseJSON (String s) = return $ PrefString s parseJSON (Bool b) = return $ PrefBool b parseJSON (Number (I i)) = return $ PrefInteger i parseJSON (Number (D d)) = return $ PrefDouble d parseJSON other = typeMismatch "ProfilePref" other instance Exception ProfileParseError -- |An error occured while attempting to parse a profile's preference file. newtype ProfileParseError = ProfileParseError String deriving (Eq, Show, Read, Typeable) -- |A typeclass to convert types to profile preference values class ToPref a where toPref :: a -> ProfilePref instance ToPref Text where toPref = PrefString instance ToPref String where toPref = toPref . pack instance ToPref Bool where toPref = PrefBool instance ToPref Integer where toPref = PrefInteger #define I(t) instance ToPref t where toPref = PrefInteger . toInteger I(Int) I(Int8) I(Int16) I(Int32) I(Int64) I(Word) I(Word8) I(Word16) I(Word32) I(Word64) instance ToPref Double where toPref = PrefDouble instance ToPref Float where toPref = PrefDouble . realToFrac instance (Integral a) => ToPref (Ratio a) where toPref = PrefDouble . realToFrac instance (HasResolution r) => ToPref (Fixed r) where toPref = PrefDouble . realToFrac -- |Retrieve a preference from a profile by key name. getPref :: Text -> Profile b -> Maybe ProfilePref getPref k (Profile _ m) = HM.lookup k m -- |Add a new preference entry to a profile, overwriting any existing entry -- with the same key. addPref :: ToPref a => Text -> a -> Profile b -> Profile b addPref k v p = onProfilePrefs p $ HM.insert k (toPref v) -- |Delete an existing preference entry from a profile. This operation is -- silent if the preference wasn't found. deletePref :: Text -> Profile b -> Profile b deletePref k p = onProfilePrefs p $ HM.delete k -- |Add a file to the profile directory. The first argument is the source -- of the file on the local filesystem. The second argument is the destination -- as a path relative to a profile directory. Overwrites any file that -- previously pointed to the same destination addFile :: FilePath -> FilePath -> Profile b -> Profile b addFile src dest p = onProfileFiles p $ HM.insert dest src -- |Delete a file from the profile directory. The first argument is the name of -- file within the profile directory. deleteFile :: FilePath -> Profile b -> Profile b deleteFile path prof = onProfileFiles prof $ HM.delete path -- |Determines if a profile contains the given file, specified as a path -- relative to the profile directory. hasFile :: String -> Profile b -> Bool hasFile path (Profile files _) = path `HM.member` files -- |Add a new extension to the profile. The file path should refer to -- a .xpi file or an extension directory on the filesystem. addExtension :: FilePath -> Profile b -> Profile b addExtension path = addFile path ("extensions" </> name) where (_, name) = splitFileName path -- |Delete an existing extension from the profile. The string parameter -- should refer to an .xpi file or directory located within the extensions -- directory of the profile. This operation has no effect if the extension was -- never added to the profile. deleteExtension :: String -> Profile b -> Profile b deleteExtension name = deleteFile ("extensions" </> name) -- |Determines if a profile contains the given extension. specified as an -- .xpi file or directory name hasExtension :: String -> Profile b -> Bool hasExtension name prof = hasFile ("extensions" </> name) prof -- |Takes the union of two profiles. This is the union of their 'HashMap' -- fields. unionProfiles :: Profile b -> Profile b -> Profile b unionProfiles (Profile f1 p1) (Profile f2 p2) = Profile (f1 `HM.union` f2) (p1 `HM.union` p2) -- |Modifies the 'profilePrefs' field of a profile. onProfilePrefs :: Profile b -> (HM.HashMap Text ProfilePref -> HM.HashMap Text ProfilePref) -> Profile b onProfilePrefs (Profile hs hm) f = Profile hs (f hm) -- |Modifies the 'profileFiles' field of a profile onProfileFiles :: Profile b -> (HM.HashMap FilePath FilePath -> HM.HashMap FilePath FilePath) -> Profile b onProfileFiles (Profile ls hm) f = Profile (f ls) hm -- |Efficiently load an existing profile from disk and prepare it for network -- transmission. prepareLoadedProfile_ :: MonadBase IO m => FilePath -> m (PreparedProfile a) prepareLoadedProfile_ path = liftBase $ do oldWd <- getCurrentDirectory setCurrentDirectory path prepareZipArchive <$> liftBase (addFilesToArchive [OptRecursive] emptyArchive ["."]) <* setCurrentDirectory oldWd -- |Prepare a zip file of a profile on disk for network transmission. -- This function is very efficient at loading large profiles from disk. prepareZippedProfile :: MonadBase IO m => FilePath -> m (PreparedProfile a) prepareZippedProfile path = prepareRawZip <$> liftBase (LBS.readFile path) -- |Prepare a zip archive of a profile for network transmission. prepareZipArchive :: Archive -> PreparedProfile a prepareZipArchive = prepareRawZip . fromArchive -- |Prepare a ByteString of raw zip data for network transmission prepareRawZip :: ByteString -> PreparedProfile a prepareRawZip = PreparedProfile . B64.encode
fpco/hs-webdriver
src/Test/WebDriver/Common/Profile.hs
bsd-3-clause
9,106
0
13
2,079
1,748
935
813
-1
-1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.ARB.CLEvent -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/ARB/cl_event.txt ARB_cl_event> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.ARB.CLEvent ( -- * Enums gl_SYNC_CL_EVENT_ARB, gl_SYNC_CL_EVENT_COMPLETE_ARB, -- * Functions glCreateSyncFromCLeventARB ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/ARB/CLEvent.hs
bsd-3-clause
756
0
4
91
52
42
10
6
0
import Network.WebSockets (shakeHands, getFrame, putFrame) import Network (listenOn, PortID(PortNumber), accept, withSocketsDo) import System.IO (Handle, hClose) import qualified Data.ByteString as B (append, null) import Data.ByteString.UTF8 (fromString) -- this is from utf8-string import Control.Monad (forever) import Control.Concurrent (forkIO) -- Accepts clients, spawns a single handler for each one. main :: IO () main = withSocketsDo $ do socket <- listenOn (PortNumber 8088) putStrLn "Listening on port 8088." forever $ do (h, _, _) <- accept socket forkIO (talkTo h) -- Shakes hands with client. If no error, starts talking. talkTo :: Handle -> IO () talkTo h = do request <- shakeHands h case request of Left err -> print err Right _ -> do putFrame h (fromString "Do you read me, Lieutenant Bowie?") putStrLn "Shook hands, sent welcome message." talkLoop h -- Talks to the client (by echoing messages back) until EOF. talkLoop :: Handle -> IO () talkLoop h = do msg <- getFrame h if B.null msg then do putStrLn "EOF encountered. Closing handle." hClose h else do putFrame h $ B.append msg (fromString ", meow.") talkLoop h
quelgar/haskell-websockets
example.hs
bsd-3-clause
1,261
13
13
304
337
176
161
-1
-1
module Blog.FrontEnd.Feeds ( Feed ( AllPosts, ByTag, ByTags, PostComments, AllComments, tag, tags, permalink), DiscoverableFeed ( feed_title, feed_url ), Feedable ( items, categories, build_id, title, self_url, home_url, discoverable_feed ), articles_feed, all_comments_feed, comments_feed, tags_feed ) where import qualified Blog.FrontEnd.Urls as U import qualified Blog.Constants as C import qualified Blog.Model.Entry as B import List (intersperse) data Feed = AllPosts | ByTag { tag :: String } | ByTags { tags :: [String] } | PostComments { permalink :: String } | AllComments deriving ( Show, Eq ) type Iri = String data DiscoverableFeed = DiscoverableFeed { feed_title :: String, feed_url :: String } deriving ( Show ) class Feedable f where -- | construct the posts for the feed from a list of all visible posts in time-sorted order items :: f -> B.Model -> [B.Item] -- | construct a set of categories, potentially empty categories :: f -> [String] -- | construct the @rel="self"@ URL for the feed self_url :: f -> String -- | construct the home URL for the feed home_url :: f -> String -- | construct the @atom:id@ for the feed build_id :: f -> Iri -- | construct the title for the feed title :: f -> String -- | construct the autodiscovery feed for this feed discoverable_feed :: f -> DiscoverableFeed discoverable_feed f = DiscoverableFeed { feed_title = title f, feed_url = self_url f} instance Feedable Feed where items AllPosts m = (take C.feed_length) . B.all_posts $ m items (ByTag t) m = (take C.feed_length) . (B.tag_filter t) . B.all_posts $ m items (ByTags t) m = (take C.feed_length) . (B.tags_filter t) . B.all_posts $ m items AllComments m = ((take C.feed_length) . (B.concat_comments m) . B.all_posts) m items (PostComments t) m = ((take C.feed_length) . (B.concat_comments m) . (B.plink_filter t) . B.all_posts) m categories (AllPosts) = [] categories (ByTag t) = [t] categories (ByTags t) = t categories (AllComments) = [] categories (PostComments _) = [] self_url AllPosts = feed_ "a" self_url (ByTag t) = feed_ ("t/" ++ t) self_url (ByTags t) = feed_ ("t/" ++ (U.tags_fragment t)) self_url (PostComments t) = feed_ ("c/p/" ++ t) self_url AllComments = feed_ "c" home_url AllPosts = U.all_posts home_url (ByTag t) = U.posts_by_tag t home_url (ByTags t) = U.posts_by_tags t home_url (PostComments t) = U.post t home_url AllComments = U.all_posts title AllPosts = C.blog_title ++ " - All Posts" title (ByTags t) = C.blog_title ++ " - Posts Tagged {" ++ (concat $ intersperse ", " t) ++ "}" title (ByTag t) = C.blog_title ++ " - Posts Tagged {" ++ t ++ "}" title (PostComments t) = C.blog_title ++ " - Comments on " ++ t title AllComments = C.blog_title ++ " - Comments on Recent Posts" build_id AllPosts = ppp_urn ++ "posts:atom:all" build_id (ByTags t) = ppp_urn ++ "posts:atom:by_tags(" ++ (U.tags_fragment t) ++ ")" build_id (ByTag t) = ppp_urn ++ "posts:atom:by_tags(" ++ t ++ ")" build_id (PostComments t) = ppp_urn ++ "comments:atom:by_permatitle(" ++ t ++ ")" build_id AllComments = ppp_urn ++ "comments:atom:all" ppp_urn :: String ppp_urn = "urn:perpubplat:" ++ C.blog_title_for_urn ++ ":" feed_ :: String -> String feed_ s = C.base_url ++ "/f/" ++ s ++ "/atom.xml" articles_feed :: DiscoverableFeed articles_feed = discoverable_feed AllPosts all_comments_feed :: DiscoverableFeed all_comments_feed = discoverable_feed AllComments comments_feed :: String -> DiscoverableFeed comments_feed = discoverable_feed . PostComments tags_feed :: [String] -> DiscoverableFeed tags_feed = discoverable_feed . ByTags -- tag_feed :: String -> DiscoverableFeed -- tag_feed = discoverable_feed . ByTag
prb/perpubplat
src/Blog/FrontEnd/Feeds.hs
bsd-3-clause
3,970
0
13
917
1,146
627
519
77
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} import Test.Hspec import Test.Hspec.Expectations import Test.QuickCheck -- import Test.QuickCheck.Instances import Control.Exception (evaluate) import Data.Time.Clock.POSIX import qualified Data.Time -- (UTCTime,) import System.Posix.Types import Data.UnixTime import Frames.Time.CTime.UnixTS import Data.Time.Calendar import Data.Maybe (isJust,isNothing) import Frames.Diff import Frames import Data.Text import Data.Proxy import qualified Pipes as P import Control.Monad.IO.Class import qualified Data.Foldable as F timeParseUTCTimeFromSecondsThenShow = show . posixSecondsToUTCTime . realToFrac . utcTimeToPOSIXSeconds instance Arbitrary Data.Time.Day where arbitrary = Data.Time.ModifiedJulianDay <$> (unixEpochJulian +) <$> arbitrary where unixEpochJulian = 40587 shrink = (Data.Time.ModifiedJulianDay <$>) . shrink . Data.Time.toModifiedJulianDay instance Arbitrary Data.Time.DiffTime where arbitrary = arbitrarySizedFractional shrink = (fromRational <$>) . shrink . toRational instance Arbitrary Data.Time.UTCTime where arbitrary = Data.Time.UTCTime <$> arbitrary <*> (fromRational . toRational <$> choose (0::Double,0)) shrink ut@(Data.Time.UTCTime day dayTime) = [ ut { Data.Time.utctDay = d' } | d' <- shrink day ] ++ [ ut { Data.Time.utctDayTime = t' } | t' <- shrink dayTime ] type Customer = Record '[CustomerId, "CustomerName" :-> Text, "ContactName" :-> Text, "Address" :-> Text, "City" :-> Text, "PostalCode" :-> Int, "Country" :-> Text] type Order = Record '["OrderId" :-> Int, CustomerId, "EmployeeID" :-> Int, "OrderDate" :-> Text, "ShipperID" :-> Int] type CustomerId = "customerID" :-> Int customerId :: forall f rs. (Functor f, CustomerId ∈ rs) => (Int -> f Int) -> Record rs -> f (Record rs) customerId = rlens (Proxy :: Proxy CustomerId) type UserId = "userId" :-> Int type Simple1 = Record '["auto" :-> Int, UserId] type Simple2 = Record '[UserId, "uslessCol" :-> Text] userId :: forall f rs. (Functor f, UserId ∈ rs) => (Int -> f Int) -> Record rs -> f (Record rs) userId = rlens (Proxy :: Proxy UserId) main :: IO () main = do let simple1 :: [Simple1] simple1 = [ 0 &: 100 &: Nil , 1 &: 100 &: Nil , 2 &: 100 &: Nil , 3 &: 100 &: Nil ] simple2 :: [Simple2] simple2 = [ 100 &: "usless" &: Nil] joinedSimple <- F.toList <$> innerJoin (P.each simple1) userId (P.each simple2) userId joinedSimpleFlipped <- F.toList <$> innerJoin (P.each simple2) userId (P.each simple1) userId hspec $ do describe "UnixTS" $ do it "unixToUTC and utcToUnix are isomorphic" $ property $ \utctm -> (unixToUTC . utcToUnix $ (utctm :: Data.Time.UTCTime) :: Data.Time.UTCTime) `shouldBe` (utctm :: Data.Time.UTCTime) it "unixTS show instance is exactly the same as UTCTime show instance" $ property $ \x -> show (utcToUnixTS (x :: Data.Time.UTCTime) :: UnixTS) == timeParseUTCTimeFromSecondsThenShow (x :: Data.Time.UTCTime) it "parses valid time text 1" $ parseUTCTime "2017-01-06 00:00:00 +0000 UTC" `shouldSatisfy` isJust it "parses valid time text 2" $ parseUTCTime "2017-01-06 00:00:00" `shouldSatisfy` isJust it "parses valid time text 3" $ parseUTCTime "2017-01-06" `shouldSatisfy` isJust it "does not parse a date with no spaces" $ parseUTCTime "20170106" `shouldSatisfy` isNothing it "does not parse an empty string" $ parseUTCTime "" `shouldSatisfy` isNothing describe "innerJoin" $ do {- -- an inner join on simple1/simple2 data in sqlite cody@zentop:~/source/frames-diff/test$ sqlite3 test.sqlite SQLite version 3.11.0 2016-02-15 17:29:24 Enter ".help" for usage hints. sqlite> create table simple1(auto,uid); sqlite> create table simple2(uid,uselessCol); sqlite> insert into simple1(auto,uid) values(1,100); sqlite> insert into simple1(auto,uid) values(2,100); sqlite> insert into simple1(auto,uid) values(3,100); sqlite> insert into simple2(uid,uselessCol) values(100,"useless"); sqlite> select * from simple1 inner join simple2 on simple1.uid = simple2.uid; 0|100|100|useless 1|100|100|useless 2|100|100|useless 3|100|100|useless sqlite> select * from simple2 inner join simple1 on simple2.uid = simple1.uid; 100|useless|1|100 100|useless|2|100 100|useless|3|100 -} it "gives multiple results back when one table contains only one row and there are multiple matches" $ do joinedSimple `shouldBe` [ 0 &: 100 &: 100 &: "usless" &: Nil , 1 &: 100 &: 100 &: "usless" &: Nil , 2 &: 100 &: 100 &: "usless" &: Nil , 3 &: 100 &: 100 &: "usless" &: Nil ] -- TOOD this matches what sqlite does, but it could cause complications for callers who expect a specific "type" (or in vinyl's case collection of coolumns in a certain order) it "sadly it has a flipped type when you reorder arguments" $ do joinedSimpleFlipped `shouldBe` [ 100 &: "usless" &: 0 &: 100 &: Nil , 100 &: "usless" &: 1 &: 100 &: Nil , 100 &: "usless" &: 2 &: 100 &: Nil , 100 &: "usless" &: 3 &: 100 &: Nil ] -- TODO -- tableTypes' rowGen { rowTypeName = "A"} "data/a.txt" -- tableTypes' rowGen { rowTypeName = "B"} "data/b.txt" -- as :: Producer A IO () -- as = readTable "data/a.txt" -- bs :: Producer B IO () -- bs = readTable "data/b.txt" -- singA = head . F.toList <$> inCoreAoS as -- singB = head . F.toList <$> inCoreAoS bs -- TODO complete these northwind tests/examples -- northwind data sample {- =============================================== Customers =============================================== CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country 1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany 2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico 3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico ========================================================================================================= =============================================== Orders =============================================== OrderID | CustomerID | EmployeeID | OrderDate | ShipperID 10308 | 2 | 7 | 1996-09-18 | 3 10309 | 37 | 3 | 1996-09-19 | 1 10310 | 77 | 8 | 1996-09-20 | 2 ========================================================================================================= -} -- let customers :: [Customer] -- customers = [ 1 &: "Alfreds Futterkiste" &: "Maria Anders" &: "Obere Strr. 57" &: "Berlin" &: 12209 &: "Germany" &: Nil -- , 2 &: "Ana Trujillo Emparedados y helados" &: "Ana Trujillo" &: "Avda. de la Constitución 2222" &: "México D.F." &: 05021 &: "Mexico" &: Nil -- , 3 &: "Antonio Moreno Taquería" &: "Antonio Moreno" &: "Mataderos 2312" &: "México D.F." &: 05023 &: "Mexico" &: Nil -- ] -- orders :: [Order] -- orders = [ 10308 &: 2 &: 7 &: "1996-09-18" &: 3 &: Nil -- , 10309 &: 3 &: 3 &: "1996-09-19" &: 1 &: Nil -- , 10310 &: 77 &: 8 &: "1996-09-20" &: 2 &: Nil -- ] -- orders' :: [Order] -- orders' = [ 10308 &: 2 &: 7 &: "1996-09-18" &: 3 &: Nil ] -- it "gives correct result regardless of left/right tables with 3 customers rows and 3 orders" $ do -- joinedCustomersLeft1 `shouldBe` -- [ 2 &: "Ana Trujillo Emparedados y helados" &: "Ana Trujillo" &: "Avda. de la Constitución 2222" &: "México D.F." &: 05021 &: "Mexico" &: 10308 &: 2 &: 7 &: "1996-09-18" &: 3 &: Nil -- ] -- it "gives correct result regardless of left/right tables with 3 customers rows and 1 order" $ do -- joinedOrdersLeft1 `shouldBe` -- [ 10308 &: 2 &: 7 &: "1996-09-18" &: 3 &: 2 &: "Ana Trujillo Emparedados y helados" &: "Ana Trujillo" &: "Avda. de la Constitución 2222" &: "México D.F." &: 05021 &: "Mexico" &: Nil -- ] -- joinedCustomersLeft3 <- F.toList <$> innerJoin (P.each customers) customerId (P.each orders) customerId -- joinedOrdersLeft3 <- F.toList <$> innerJoin (P.each orders) customerId (P.each customers) customerId -- joinedCustomersLeft1 <- F.toList <$> innerJoin (P.each customers) customerId (P.each orders') customerId -- joinedOrdersLeft1 <- F.toList <$> innerJoin (P.each orders') customerId (P.each customers) customerId
codygman/frames-diff
test/Test.hs
bsd-3-clause
9,134
0
24
2,291
1,312
735
577
94
1
-------------------------------------------------------------------------------- -- Copyright © 2011 National Institute of Aerospace / Galois, Inc. -------------------------------------------------------------------------------- {-# LANGUAGE GADTs #-} module Copilot.Compile.C99.Test.Driver ( driver -- , ExtVars ) where import Copilot.Core ( Spec(..), Trigger(..), UExpr(..), Type(..), UType(..), Name , Expr(..), Stream(..) ) import Copilot.Core.Error (impossible) import Copilot.Core.Type (Typed, typeOf) import Copilot.Core.Type.Dynamic (DynamicF (..), toDynF) import Copilot.Core.Type.Show (showWithType, ShowType (..)) --import Copilot.Core.Interpret.Eval (ExtEnv(..)) import Data.List (intersperse, nubBy) import Data.Text (Text) import Data.Text (pack) import Text.PrettyPrint ( Doc, ($$), (<>), (<+>), nest, text, empty, render, vcat , hcat, space, equals, semi, lbrack, rbrack, comma , punctuate, hsep, lbrace, rbrace) -------------------------------------------------------------------------------- driver :: Int -> Spec -> Text driver numIterations Spec { specTriggers = trigs , specStreams = streams } = pack . render $ ppHeader $$ ppEnvDecls numIterations env $$ ppMain numIterations env $$ ppTriggers trigs where env :: [ExtVars] env = nubBy (\(name0,_) (name1,_) -> name0 == name1) (concatMap extractExts exprs) exprs = map strmExpr streams ++ concatMap triggerArgs trigs ++ map uexpr (map triggerGuard trigs) strmExpr Stream { streamExpr = expr } = uexpr expr uexpr :: Typed a => Expr a -> UExpr uexpr e = UExpr { uExprType = typeOf , uExprExpr = e } -------------------------------------------------------------------------------- -- XXX will need to be generalized to external arrays and functions at some -- point. type ExtVars = (Name, DynamicF [] Type) extractExts :: UExpr -> [ExtVars] extractExts UExpr { uExprExpr = expr } = go expr where go :: Expr a -> [ExtVars] go e = case e of Const _ _ -> [] Drop _ _ _ -> [] Local _ _ _ e0 e1 -> go e0 ++ go e1 Var _ _ -> [] ExternVar t name mvals -> case mvals of Nothing -> impossible "extractExts" "copilot-c99/Test" Just vals -> [(name, toDynF t vals)] ExternFun _ _ es _ _ -> concatMap extractExts es ExternArray _ _ _ _ idx _ _ -> go idx Op1 _ e0 -> go e0 Op2 _ e0 e1 -> go e0 ++ go e1 Op3 _ e0 e1 e2 -> go e0 ++ go e1 ++ go e2 -------------------------------------------------------------------------------- ppHeader :: Doc ppHeader = vcat $ [ text "#include <stdint.h>" , text "#include <inttypes.h>" , text "#include <stdio.h>" , text "#include \"copilot.h\"" ] -------------------------------------------------------------------------------- ppEnvDecls :: Int -> [ExtVars] -> Doc ppEnvDecls numIterations vars = vcat $ [ space , text "// External variables" , vcat $ map ppEnvDecl vars , space , text "// External values" , vcat $ map ppVals vars , space , space ] where ppEnvDecl :: (Name, DynamicF [] Type) -> Doc ppEnvDecl (name, DynamicF _ t) = cType <+> text name <> semi where cType = ppUType UType { uTypeType = t } ppVals :: (Name, DynamicF [] Type) -> Doc ppVals (name, DynamicF vals t) = cType <+> valsName name <> lbrack <> (text . show) numIterations <> rbrack <+> equals <+> lbrace <+> arrVals <+> rbrace <> semi where cType = ppUType UType { uTypeType = t } arrVals = hsep $ punctuate comma $ map text showVals showVals = map (showWithType C t) vals -------------------------------------------------------------------------------- valsName :: Name -> Doc valsName name = text name <> text "_vals" -------------------------------------------------------------------------------- ppMain :: Int -> [ExtVars] -> Doc ppMain numIterations vars = vcat $ [ text "int main(int argc, char const *argv[]) {" , text " int i;" , text " for (i = 0; i < " <> rnds <> text "; i++) {" , space , vcat $ map (nest 3) $ map assignVals vars , space , text " if (i > 0) printf(\"#\\n\");" , text " " <> text "step();" , text " }" , text " return 0;" , text "}" , space ] where rnds = text $ show numIterations assignVals :: (Name, DynamicF [] Type) -> Doc assignVals (name, _) = text name <+> equals <+> valsName name <> lbrack <> text "i" <> rbrack <> semi -------------------------------------------------------------------------------- ppTriggers :: [Trigger] -> Doc ppTriggers = foldr ($$) empty . map ppTrigger ppTrigger :: Trigger -> Doc ppTrigger Trigger { triggerName = name , triggerArgs = args } = hcat $ [ text "void" <+> text name <+> text "(" <> ppPars args <> text ")" , text "{" , nest 2 $ ppPrintf name args <> text ";" , text "}" ] -------------------------------------------------------------------------------- ppPrintf :: String -> [UExpr] -> Doc ppPrintf name args = text "printf(\"" <> text name <> text "," <> ppFormats args <> text "\"\\n\"," <+> ppArgs args <> text ")" -------------------------------------------------------------------------------- ppFormats :: [UExpr] -> Doc ppFormats = vcat . intersperse (text ",") . map (text "%\"" <>) . map ppFormat -------------------------------------------------------------------------------- ppPars :: [UExpr] -> Doc ppPars = vcat . intersperse (text ", ") . map ppPar . zip [0..] where ppPar :: (Int, UExpr) -> Doc ppPar (k, par) = case par of UExpr { uExprType = t } -> ppUType (UType t) <+> text ("t" ++ show k) -------------------------------------------------------------------------------- ppArgs :: [UExpr] -> Doc ppArgs args = vcat $ intersperse (text ", ") $ map ppArg $ [0..length args-1] where ppArg :: Int -> Doc ppArg k = text ("t" ++ show k) -------------------------------------------------------------------------------- ppUType :: UType -> Doc ppUType UType { uTypeType = t } = text $ typeSpec' t where typeSpec' Bool = "bool" typeSpec' Int8 = "int8_t" typeSpec' Int16 = "int16_t" typeSpec' Int32 = "int32_t" typeSpec' Int64 = "int64_t" typeSpec' Word8 = "uint8_t" typeSpec' Word16 = "uint16_t" typeSpec' Word32 = "uint32_t" typeSpec' Word64 = "uint64_t" typeSpec' Float = "float" typeSpec' Double = "double" -------------------------------------------------------------------------------- ppFormat :: UExpr -> Doc ppFormat UExpr { uExprType = t } = text $ case t of Bool -> "PRIu8" Int8 -> "PRIi8" Int16 -> "PRIi16" Int32 -> "PRIi32" Int64 -> "PRIi64" Word8 -> "PRIu8" Word16 -> "PRIu16" Word32 -> "PRIu32" Word64 -> "PRIu64" Float -> "\"f\"" Double -> "\"lf\"" --------------------------------------------------------------------------------
niswegmann/copilot-c99
src/Copilot/Compile/C99/Test/Driver.hs
bsd-3-clause
7,250
0
16
1,816
2,066
1,095
971
182
11
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow 2006 -- -- The purpose of this module is to transform an HsExpr into a CoreExpr which -- when evaluated, returns a (Meta.Q Meta.Exp) computation analogous to the -- input HsExpr. We do this in the DsM monad, which supplies access to -- CoreExpr's of the "smart constructors" of the Meta.Exp datatype. -- -- It also defines a bunch of knownKeyNames, in the same way as is done -- in prelude/PrelNames. It's much more convenient to do it here, because -- otherwise we have to recompile PrelNames whenever we add a Name, which is -- a Royal Pain (triggers other recompilation). ----------------------------------------------------------------------------- module DsMeta( dsBracket ) where #include "HsVersions.h" import {-# SOURCE #-} DsExpr ( dsExpr ) import MatchLit import DsMonad import qualified Language.Haskell.TH as TH import HsSyn import Class import PrelNames -- To avoid clashes with DsMeta.varName we must make a local alias for -- OccName.varName we do this by removing varName from the import of -- OccName above, making a qualified instance of OccName and using -- OccNameAlias.varName where varName ws previously used in this file. import qualified OccName( isDataOcc, isVarOcc, isTcOcc ) import Module import Id import Name hiding( isVarOcc, isTcOcc, varName, tcName ) import THNames import NameEnv import NameSet import TcType import TyCon import TysWiredIn import CoreSyn import MkCore import CoreUtils import SrcLoc import Unique import BasicTypes import Outputable import Bag import DynFlags import FastString import ForeignCall import Util import Maybes import MonadUtils import Data.ByteString ( unpack ) import Control.Monad import Data.List ----------------------------------------------------------------------------- dsBracket :: HsBracket Name -> [PendingTcSplice] -> DsM CoreExpr -- Returns a CoreExpr of type TH.ExpQ -- The quoted thing is parameterised over Name, even though it has -- been type checked. We don't want all those type decorations! dsBracket brack splices = dsExtendMetaEnv new_bit (do_brack brack) where new_bit = mkNameEnv [(n, DsSplice (unLoc e)) | PendingTcSplice n e <- splices] do_brack (VarBr _ n) = do { MkC e1 <- lookupOcc n ; return e1 } do_brack (ExpBr e) = do { MkC e1 <- repLE e ; return e1 } do_brack (PatBr p) = do { MkC p1 <- repTopP p ; return p1 } do_brack (TypBr t) = do { MkC t1 <- repLTy t ; return t1 } do_brack (DecBrG gp) = do { MkC ds1 <- repTopDs gp ; return ds1 } do_brack (DecBrL _) = panic "dsBracket: unexpected DecBrL" do_brack (TExpBr e) = do { MkC e1 <- repLE e ; return e1 } {- -------------- Examples -------------------- [| \x -> x |] ====> gensym (unpackString "x"#) `bindQ` \ x1::String -> lam (pvar x1) (var x1) [| \x -> $(f [| x |]) |] ====> gensym (unpackString "x"#) `bindQ` \ x1::String -> lam (pvar x1) (f (var x1)) -} ------------------------------------------------------- -- Declarations ------------------------------------------------------- repTopP :: LPat Name -> DsM (Core TH.PatQ) repTopP pat = do { ss <- mkGenSyms (collectPatBinders pat) ; pat' <- addBinds ss (repLP pat) ; wrapGenSyms ss pat' } repTopDs :: HsGroup Name -> DsM (Core (TH.Q [TH.Dec])) repTopDs group@(HsGroup { hs_valds = valds , hs_splcds = splcds , hs_tyclds = tyclds , hs_instds = instds , hs_derivds = derivds , hs_fixds = fixds , hs_defds = defds , hs_fords = fords , hs_warnds = warnds , hs_annds = annds , hs_ruleds = ruleds , hs_vects = vects , hs_docs = docs }) = do { let { tv_bndrs = hsSigTvBinders valds ; bndrs = tv_bndrs ++ hsGroupBinders group } ; ss <- mkGenSyms bndrs ; -- Bind all the names mainly to avoid repeated use of explicit strings. -- Thus we get -- do { t :: String <- genSym "T" ; -- return (Data t [] ...more t's... } -- The other important reason is that the output must mention -- only "T", not "Foo:T" where Foo is the current module decls <- addBinds ss ( do { val_ds <- rep_val_binds valds ; _ <- mapM no_splice splcds ; tycl_ds <- mapM repTyClD (tyClGroupConcat tyclds) ; role_ds <- mapM repRoleD (concatMap group_roles tyclds) ; inst_ds <- mapM repInstD instds ; deriv_ds <- mapM repStandaloneDerivD derivds ; fix_ds <- mapM repFixD fixds ; _ <- mapM no_default_decl defds ; for_ds <- mapM repForD fords ; _ <- mapM no_warn (concatMap (wd_warnings . unLoc) warnds) ; ann_ds <- mapM repAnnD annds ; rule_ds <- mapM repRuleD (concatMap (rds_rules . unLoc) ruleds) ; _ <- mapM no_vect vects ; _ <- mapM no_doc docs -- more needed ; return (de_loc $ sort_by_loc $ val_ds ++ catMaybes tycl_ds ++ role_ds ++ (concat fix_ds) ++ inst_ds ++ rule_ds ++ for_ds ++ ann_ds ++ deriv_ds) }) ; decl_ty <- lookupType decQTyConName ; let { core_list = coreList' decl_ty decls } ; dec_ty <- lookupType decTyConName ; q_decs <- repSequenceQ dec_ty core_list ; wrapGenSyms ss q_decs } where no_splice (L loc _) = notHandledL loc "Splices within declaration brackets" empty no_default_decl (L loc decl) = notHandledL loc "Default declarations" (ppr decl) no_warn (L loc (Warning thing _)) = notHandledL loc "WARNING and DEPRECATION pragmas" $ text "Pragma for declaration of" <+> ppr thing no_vect (L loc decl) = notHandledL loc "Vectorisation pragmas" (ppr decl) no_doc (L loc _) = notHandledL loc "Haddock documentation" empty hsSigTvBinders :: HsValBinds Name -> [Name] -- See Note [Scoped type variables in bindings] hsSigTvBinders binds = concatMap get_scoped_tvs sigs where get_scoped_tvs :: LSig Name -> [Name] -- Both implicit and explicit quantified variables -- We need the implicit ones for f :: forall (a::k). blah -- here 'k' scopes too get_scoped_tvs (L _ (TypeSig _ sig)) | HsIB { hsib_vars = implicit_vars , hsib_body = sig1 } <- sig , (explicit_vars, _) <- splitLHsForAllTy (hswc_body sig1) = implicit_vars ++ map hsLTyVarName explicit_vars get_scoped_tvs _ = [] sigs = case binds of ValBindsIn _ sigs -> sigs ValBindsOut _ sigs -> sigs {- Notes Note [Scoped type variables in bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: forall a. a -> a f x = x::a Here the 'forall a' brings 'a' into scope over the binding group. To achieve this we a) Gensym a binding for 'a' at the same time as we do one for 'f' collecting the relevant binders with hsSigTvBinders b) When processing the 'forall', don't gensym The relevant places are signposted with references to this Note Note [Binders and occurrences] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we desugar [d| data T = MkT |] we want to get Data "T" [] [Con "MkT" []] [] and *not* Data "Foo:T" [] [Con "Foo:MkT" []] [] That is, the new data decl should fit into whatever new module it is asked to fit in. We do *not* clone, though; no need for this: Data "T79" .... But if we see this: data T = MkT foo = reifyDecl T then we must desugar to foo = Data "Foo:T" [] [Con "Foo:MkT" []] [] So in repTopDs we bring the binders into scope with mkGenSyms and addBinds. And we use lookupOcc, rather than lookupBinder in repTyClD and repC. -} -- represent associated family instances -- repTyClD :: LTyClDecl Name -> DsM (Maybe (SrcSpan, Core TH.DecQ)) repTyClD (L loc (FamDecl { tcdFam = fam })) = liftM Just $ repFamilyDecl (L loc fam) repTyClD (L loc (SynDecl { tcdLName = tc, tcdTyVars = tvs, tcdRhs = rhs })) = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] ; dec <- addTyClTyVarBinds tvs $ \bndrs -> repSynDecl tc1 bndrs rhs ; return (Just (loc, dec)) } repTyClD (L loc (DataDecl { tcdLName = tc, tcdTyVars = tvs, tcdDataDefn = defn })) = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] ; dec <- addTyClTyVarBinds tvs $ \bndrs -> repDataDefn tc1 bndrs Nothing defn ; return (Just (loc, dec)) } repTyClD (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls, tcdTyVars = tvs, tcdFDs = fds, tcdSigs = sigs, tcdMeths = meth_binds, tcdATs = ats, tcdATDefs = atds })) = do { cls1 <- lookupLOcc cls -- See note [Binders and occurrences] ; dec <- addTyVarBinds tvs $ \bndrs -> do { cxt1 <- repLContext cxt ; sigs1 <- rep_sigs sigs ; binds1 <- rep_binds meth_binds ; fds1 <- repLFunDeps fds ; ats1 <- repFamilyDecls ats ; atds1 <- repAssocTyFamDefaults atds ; decls1 <- coreList decQTyConName (ats1 ++ atds1 ++ sigs1 ++ binds1) ; repClass cxt1 cls1 bndrs fds1 decls1 } ; return $ Just (loc, dec) } ------------------------- repRoleD :: LRoleAnnotDecl Name -> DsM (SrcSpan, Core TH.DecQ) repRoleD (L loc (RoleAnnotDecl tycon roles)) = do { tycon1 <- lookupLOcc tycon ; roles1 <- mapM repRole roles ; roles2 <- coreList roleTyConName roles1 ; dec <- repRoleAnnotD tycon1 roles2 ; return (loc, dec) } ------------------------- repDataDefn :: Core TH.Name -> Core [TH.TyVarBndr] -> Maybe (Core [TH.TypeQ]) -> HsDataDefn Name -> DsM (Core TH.DecQ) repDataDefn tc bndrs opt_tys (HsDataDefn { dd_ND = new_or_data, dd_ctxt = cxt, dd_kindSig = ksig , dd_cons = cons, dd_derivs = mb_derivs }) = do { cxt1 <- repLContext cxt ; derivs1 <- repDerivs mb_derivs ; case (new_or_data, cons) of (NewType, [con]) -> do { con' <- repC con ; ksig' <- repMaybeLKind ksig ; repNewtype cxt1 tc bndrs opt_tys ksig' con' derivs1 } (NewType, _) -> failWithDs (text "Multiple constructors for newtype:" <+> pprQuotedList (getConNames $ unLoc $ head cons)) (DataType, _) -> do { ksig' <- repMaybeLKind ksig ; consL <- mapM repC cons ; cons1 <- coreList conQTyConName consL ; repData cxt1 tc bndrs opt_tys ksig' cons1 derivs1 } } repSynDecl :: Core TH.Name -> Core [TH.TyVarBndr] -> LHsType Name -> DsM (Core TH.DecQ) repSynDecl tc bndrs ty = do { ty1 <- repLTy ty ; repTySyn tc bndrs ty1 } repFamilyDecl :: LFamilyDecl Name -> DsM (SrcSpan, Core TH.DecQ) repFamilyDecl decl@(L loc (FamilyDecl { fdInfo = info, fdLName = tc, fdTyVars = tvs, fdResultSig = L _ resultSig, fdInjectivityAnn = injectivity })) = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] ; let mkHsQTvs :: [LHsTyVarBndr Name] -> LHsQTyVars Name mkHsQTvs tvs = HsQTvs { hsq_implicit = [], hsq_explicit = tvs , hsq_dependent = emptyNameSet } resTyVar = case resultSig of TyVarSig bndr -> mkHsQTvs [bndr] _ -> mkHsQTvs [] ; dec <- addTyClTyVarBinds tvs $ \bndrs -> addTyClTyVarBinds resTyVar $ \_ -> case info of ClosedTypeFamily Nothing -> notHandled "abstract closed type family" (ppr decl) ClosedTypeFamily (Just eqns) -> do { eqns1 <- mapM repTyFamEqn eqns ; eqns2 <- coreList tySynEqnQTyConName eqns1 ; result <- repFamilyResultSig resultSig ; inj <- repInjectivityAnn injectivity ; repClosedFamilyD tc1 bndrs result inj eqns2 } OpenTypeFamily -> do { result <- repFamilyResultSig resultSig ; inj <- repInjectivityAnn injectivity ; repOpenFamilyD tc1 bndrs result inj } DataFamily -> do { kind <- repFamilyResultSigToMaybeKind resultSig ; repDataFamilyD tc1 bndrs kind } ; return (loc, dec) } -- | Represent result signature of a type family repFamilyResultSig :: FamilyResultSig Name -> DsM (Core TH.FamilyResultSig) repFamilyResultSig NoSig = repNoSig repFamilyResultSig (KindSig ki) = do { ki' <- repLKind ki ; repKindSig ki' } repFamilyResultSig (TyVarSig bndr) = do { bndr' <- repTyVarBndr bndr ; repTyVarSig bndr' } -- | Represent result signature using a Maybe Kind. Used with data families, -- where the result signature can be either missing or a kind but never a named -- result variable. repFamilyResultSigToMaybeKind :: FamilyResultSig Name -> DsM (Core (Maybe TH.Kind)) repFamilyResultSigToMaybeKind NoSig = do { coreNothing kindTyConName } repFamilyResultSigToMaybeKind (KindSig ki) = do { ki' <- repLKind ki ; coreJust kindTyConName ki' } repFamilyResultSigToMaybeKind _ = panic "repFamilyResultSigToMaybeKind" -- | Represent injectivity annotation of a type family repInjectivityAnn :: Maybe (LInjectivityAnn Name) -> DsM (Core (Maybe TH.InjectivityAnn)) repInjectivityAnn Nothing = do { coreNothing injAnnTyConName } repInjectivityAnn (Just (L _ (InjectivityAnn lhs rhs))) = do { lhs' <- lookupBinder (unLoc lhs) ; rhs1 <- mapM (lookupBinder . unLoc) rhs ; rhs2 <- coreList nameTyConName rhs1 ; injAnn <- rep2 injectivityAnnName [unC lhs', unC rhs2] ; coreJust injAnnTyConName injAnn } repFamilyDecls :: [LFamilyDecl Name] -> DsM [Core TH.DecQ] repFamilyDecls fds = liftM de_loc (mapM repFamilyDecl fds) repAssocTyFamDefaults :: [LTyFamDefltEqn Name] -> DsM [Core TH.DecQ] repAssocTyFamDefaults = mapM rep_deflt where -- very like repTyFamEqn, but different in the details rep_deflt :: LTyFamDefltEqn Name -> DsM (Core TH.DecQ) rep_deflt (L _ (TyFamEqn { tfe_tycon = tc , tfe_pats = bndrs , tfe_rhs = rhs })) = addTyClTyVarBinds bndrs $ \ _ -> do { tc1 <- lookupLOcc tc ; tys1 <- repLTys (hsLTyVarBndrsToTypes bndrs) ; tys2 <- coreList typeQTyConName tys1 ; rhs1 <- repLTy rhs ; eqn1 <- repTySynEqn tys2 rhs1 ; repTySynInst tc1 eqn1 } ------------------------- -- represent fundeps -- repLFunDeps :: [Located (FunDep (Located Name))] -> DsM (Core [TH.FunDep]) repLFunDeps fds = repList funDepTyConName repLFunDep fds repLFunDep :: Located (FunDep (Located Name)) -> DsM (Core TH.FunDep) repLFunDep (L _ (xs, ys)) = do xs' <- repList nameTyConName (lookupBinder . unLoc) xs ys' <- repList nameTyConName (lookupBinder . unLoc) ys repFunDep xs' ys' -- Represent instance declarations -- repInstD :: LInstDecl Name -> DsM (SrcSpan, Core TH.DecQ) repInstD (L loc (TyFamInstD { tfid_inst = fi_decl })) = do { dec <- repTyFamInstD fi_decl ; return (loc, dec) } repInstD (L loc (DataFamInstD { dfid_inst = fi_decl })) = do { dec <- repDataFamInstD fi_decl ; return (loc, dec) } repInstD (L loc (ClsInstD { cid_inst = cls_decl })) = do { dec <- repClsInstD cls_decl ; return (loc, dec) } repClsInstD :: ClsInstDecl Name -> DsM (Core TH.DecQ) repClsInstD (ClsInstDecl { cid_poly_ty = ty, cid_binds = binds , cid_sigs = prags, cid_tyfam_insts = ats , cid_datafam_insts = adts , cid_overlap_mode = overlap }) = addSimpleTyVarBinds tvs $ -- We must bring the type variables into scope, so their -- occurrences don't fail, even though the binders don't -- appear in the resulting data structure -- -- But we do NOT bring the binders of 'binds' into scope -- because they are properly regarded as occurrences -- For example, the method names should be bound to -- the selector Ids, not to fresh names (Trac #5410) -- do { cxt1 <- repLContext cxt ; inst_ty1 <- repLTy inst_ty ; binds1 <- rep_binds binds ; prags1 <- rep_sigs prags ; ats1 <- mapM (repTyFamInstD . unLoc) ats ; adts1 <- mapM (repDataFamInstD . unLoc) adts ; decls <- coreList decQTyConName (ats1 ++ adts1 ++ binds1 ++ prags1) ; rOver <- repOverlap (fmap unLoc overlap) ; repInst rOver cxt1 inst_ty1 decls } where (tvs, cxt, inst_ty) = splitLHsInstDeclTy ty repStandaloneDerivD :: LDerivDecl Name -> DsM (SrcSpan, Core TH.DecQ) repStandaloneDerivD (L loc (DerivDecl { deriv_type = ty })) = do { dec <- addSimpleTyVarBinds tvs $ do { cxt' <- repLContext cxt ; inst_ty' <- repLTy inst_ty ; repDeriv cxt' inst_ty' } ; return (loc, dec) } where (tvs, cxt, inst_ty) = splitLHsInstDeclTy ty repTyFamInstD :: TyFamInstDecl Name -> DsM (Core TH.DecQ) repTyFamInstD decl@(TyFamInstDecl { tfid_eqn = eqn }) = do { let tc_name = tyFamInstDeclLName decl ; tc <- lookupLOcc tc_name -- See note [Binders and occurrences] ; eqn1 <- repTyFamEqn eqn ; repTySynInst tc eqn1 } repTyFamEqn :: LTyFamInstEqn Name -> DsM (Core TH.TySynEqnQ) repTyFamEqn (L _ (TyFamEqn { tfe_pats = HsIB { hsib_body = tys , hsib_vars = var_names } , tfe_rhs = rhs })) = do { let hs_tvs = HsQTvs { hsq_implicit = var_names , hsq_explicit = [] , hsq_dependent = emptyNameSet } -- Yuk ; addTyClTyVarBinds hs_tvs $ \ _ -> do { tys1 <- repLTys tys ; tys2 <- coreList typeQTyConName tys1 ; rhs1 <- repLTy rhs ; repTySynEqn tys2 rhs1 } } repDataFamInstD :: DataFamInstDecl Name -> DsM (Core TH.DecQ) repDataFamInstD (DataFamInstDecl { dfid_tycon = tc_name , dfid_pats = HsIB { hsib_body = tys, hsib_vars = var_names } , dfid_defn = defn }) = do { tc <- lookupLOcc tc_name -- See note [Binders and occurrences] ; let hs_tvs = HsQTvs { hsq_implicit = var_names , hsq_explicit = [] , hsq_dependent = emptyNameSet } -- Yuk ; addTyClTyVarBinds hs_tvs $ \ bndrs -> do { tys1 <- repList typeQTyConName repLTy tys ; repDataDefn tc bndrs (Just tys1) defn } } repForD :: Located (ForeignDecl Name) -> DsM (SrcSpan, Core TH.DecQ) repForD (L loc (ForeignImport { fd_name = name, fd_sig_ty = typ , fd_fi = CImport (L _ cc) (L _ s) mch cis _ })) = do MkC name' <- lookupLOcc name MkC typ' <- repHsSigType typ MkC cc' <- repCCallConv cc MkC s' <- repSafety s cis' <- conv_cimportspec cis MkC str <- coreStringLit (static ++ chStr ++ cis') dec <- rep2 forImpDName [cc', s', str, name', typ'] return (loc, dec) where conv_cimportspec (CLabel cls) = notHandled "Foreign label" (doubleQuotes (ppr cls)) conv_cimportspec (CFunction DynamicTarget) = return "dynamic" conv_cimportspec (CFunction (StaticTarget _ fs _ True)) = return (unpackFS fs) conv_cimportspec (CFunction (StaticTarget _ _ _ False)) = panic "conv_cimportspec: values not supported yet" conv_cimportspec CWrapper = return "wrapper" -- these calling conventions do not support headers and the static keyword raw_cconv = cc == PrimCallConv || cc == JavaScriptCallConv static = case cis of CFunction (StaticTarget _ _ _ _) | not raw_cconv -> "static " _ -> "" chStr = case mch of Just (Header _ h) | not raw_cconv -> unpackFS h ++ " " _ -> "" repForD decl = notHandled "Foreign declaration" (ppr decl) repCCallConv :: CCallConv -> DsM (Core TH.Callconv) repCCallConv CCallConv = rep2 cCallName [] repCCallConv StdCallConv = rep2 stdCallName [] repCCallConv CApiConv = rep2 cApiCallName [] repCCallConv PrimCallConv = rep2 primCallName [] repCCallConv JavaScriptCallConv = rep2 javaScriptCallName [] repSafety :: Safety -> DsM (Core TH.Safety) repSafety PlayRisky = rep2 unsafeName [] repSafety PlayInterruptible = rep2 interruptibleName [] repSafety PlaySafe = rep2 safeName [] repFixD :: LFixitySig Name -> DsM [(SrcSpan, Core TH.DecQ)] repFixD (L loc (FixitySig names (Fixity _ prec dir))) = do { MkC prec' <- coreIntLit prec ; let rep_fn = case dir of InfixL -> infixLDName InfixR -> infixRDName InfixN -> infixNDName ; let do_one name = do { MkC name' <- lookupLOcc name ; dec <- rep2 rep_fn [prec', name'] ; return (loc,dec) } ; mapM do_one names } repRuleD :: LRuleDecl Name -> DsM (SrcSpan, Core TH.DecQ) repRuleD (L loc (HsRule n act bndrs lhs _ rhs _)) = do { let bndr_names = concatMap ruleBndrNames bndrs ; ss <- mkGenSyms bndr_names ; rule1 <- addBinds ss $ do { bndrs' <- repList ruleBndrQTyConName repRuleBndr bndrs ; n' <- coreStringLit $ unpackFS $ snd $ unLoc n ; act' <- repPhases act ; lhs' <- repLE lhs ; rhs' <- repLE rhs ; repPragRule n' bndrs' lhs' rhs' act' } ; rule2 <- wrapGenSyms ss rule1 ; return (loc, rule2) } ruleBndrNames :: LRuleBndr Name -> [Name] ruleBndrNames (L _ (RuleBndr n)) = [unLoc n] ruleBndrNames (L _ (RuleBndrSig n sig)) | HsIB { hsib_vars = vars } <- sig = unLoc n : vars repRuleBndr :: LRuleBndr Name -> DsM (Core TH.RuleBndrQ) repRuleBndr (L _ (RuleBndr n)) = do { MkC n' <- lookupLBinder n ; rep2 ruleVarName [n'] } repRuleBndr (L _ (RuleBndrSig n sig)) = do { MkC n' <- lookupLBinder n ; MkC ty' <- repLTy (hsSigWcType sig) ; rep2 typedRuleVarName [n', ty'] } repAnnD :: LAnnDecl Name -> DsM (SrcSpan, Core TH.DecQ) repAnnD (L loc (HsAnnotation _ ann_prov (L _ exp))) = do { target <- repAnnProv ann_prov ; exp' <- repE exp ; dec <- repPragAnn target exp' ; return (loc, dec) } repAnnProv :: AnnProvenance Name -> DsM (Core TH.AnnTarget) repAnnProv (ValueAnnProvenance (L _ n)) = do { MkC n' <- globalVar n -- ANNs are allowed only at top-level ; rep2 valueAnnotationName [ n' ] } repAnnProv (TypeAnnProvenance (L _ n)) = do { MkC n' <- globalVar n ; rep2 typeAnnotationName [ n' ] } repAnnProv ModuleAnnProvenance = rep2 moduleAnnotationName [] ------------------------------------------------------- -- Constructors ------------------------------------------------------- repC :: LConDecl Name -> DsM (Core TH.ConQ) repC (L _ (ConDeclH98 { con_name = con , con_qvars = Nothing, con_cxt = Nothing , con_details = details })) = repDataCon con details repC (L _ (ConDeclH98 { con_name = con , con_qvars = mcon_tvs, con_cxt = mcxt , con_details = details })) = do { let con_tvs = fromMaybe emptyLHsQTvs mcon_tvs ctxt = unLoc $ fromMaybe (noLoc []) mcxt ; addTyVarBinds con_tvs $ \ ex_bndrs -> do { c' <- repDataCon con details ; ctxt' <- repContext ctxt ; if isEmptyLHsQTvs con_tvs && null ctxt then return c' else rep2 forallCName ([unC ex_bndrs, unC ctxt', unC c']) } } repC (L _ (ConDeclGADT { con_names = cons , con_type = res_ty@(HsIB { hsib_vars = con_vars })})) | (details, res_ty', L _ [] , []) <- gadtDetails , [] <- con_vars -- no implicit or explicit variables, no context = no need for a forall = do { let doc = text "In the constructor for " <+> ppr (head cons) ; (hs_details, gadt_res_ty) <- updateGadtResult failWithDs doc details res_ty' ; repGadtDataCons cons hs_details gadt_res_ty } | (details,res_ty',ctxt, tvs) <- gadtDetails = do { let doc = text "In the constructor for " <+> ppr (head cons) con_tvs = HsQTvs { hsq_implicit = [] , hsq_explicit = (map (noLoc . UserTyVar . noLoc) con_vars) ++ tvs , hsq_dependent = emptyNameSet } ; addTyVarBinds con_tvs $ \ ex_bndrs -> do { (hs_details, gadt_res_ty) <- updateGadtResult failWithDs doc details res_ty' ; c' <- repGadtDataCons cons hs_details gadt_res_ty ; ctxt' <- repContext (unLoc ctxt) ; rep2 forallCName ([unC ex_bndrs, unC ctxt', unC c']) } } where gadtDetails = gadtDeclDetails res_ty repSrcUnpackedness :: SrcUnpackedness -> DsM (Core TH.SourceUnpackednessQ) repSrcUnpackedness SrcUnpack = rep2 sourceUnpackName [] repSrcUnpackedness SrcNoUnpack = rep2 sourceNoUnpackName [] repSrcUnpackedness NoSrcUnpack = rep2 noSourceUnpackednessName [] repSrcStrictness :: SrcStrictness -> DsM (Core TH.SourceStrictnessQ) repSrcStrictness SrcLazy = rep2 sourceLazyName [] repSrcStrictness SrcStrict = rep2 sourceStrictName [] repSrcStrictness NoSrcStrict = rep2 noSourceStrictnessName [] repBangTy :: LBangType Name -> DsM (Core (TH.BangTypeQ)) repBangTy ty = do MkC u <- repSrcUnpackedness su' MkC s <- repSrcStrictness ss' MkC b <- rep2 bangName [u, s] MkC t <- repLTy ty' rep2 bangTypeName [b, t] where (su', ss', ty') = case ty of L _ (HsBangTy (HsSrcBang _ su ss) ty) -> (su, ss, ty) _ -> (NoSrcUnpack, NoSrcStrict, ty) ------------------------------------------------------- -- Deriving clause ------------------------------------------------------- repDerivs :: HsDeriving Name -> DsM (Core TH.CxtQ) repDerivs deriv = do let clauses = case deriv of Nothing -> [] Just (L _ ctxt) -> ctxt tys <- repList typeQTyConName (rep_deriv . hsSigType) clauses :: DsM (Core [TH.PredQ]) repCtxt tys where rep_deriv :: LHsType Name -> DsM (Core TH.TypeQ) rep_deriv (L _ ty) = repTy ty ------------------------------------------------------- -- Signatures in a class decl, or a group of bindings ------------------------------------------------------- rep_sigs :: [LSig Name] -> DsM [Core TH.DecQ] rep_sigs sigs = do locs_cores <- rep_sigs' sigs return $ de_loc $ sort_by_loc locs_cores rep_sigs' :: [LSig Name] -> DsM [(SrcSpan, Core TH.DecQ)] -- We silently ignore ones we don't recognise rep_sigs' sigs = do { sigs1 <- mapM rep_sig sigs ; return (concat sigs1) } rep_sig :: LSig Name -> DsM [(SrcSpan, Core TH.DecQ)] rep_sig (L loc (TypeSig nms ty)) = mapM (rep_wc_ty_sig sigDName loc ty) nms rep_sig (L _ (PatSynSig {})) = notHandled "Pattern type signatures" empty rep_sig (L loc (ClassOpSig is_deflt nms ty)) | is_deflt = mapM (rep_ty_sig defaultSigDName loc ty) nms | otherwise = mapM (rep_ty_sig sigDName loc ty) nms rep_sig d@(L _ (IdSig {})) = pprPanic "rep_sig IdSig" (ppr d) rep_sig (L _ (FixSig {})) = return [] -- fixity sigs at top level rep_sig (L loc (InlineSig nm ispec)) = rep_inline nm ispec loc rep_sig (L loc (SpecSig nm tys ispec)) = concatMapM (\t -> rep_specialise nm t ispec loc) tys rep_sig (L loc (SpecInstSig _ ty)) = rep_specialiseInst ty loc rep_sig (L _ (MinimalSig {})) = notHandled "MINIMAL pragmas" empty rep_ty_sig :: Name -> SrcSpan -> LHsSigType Name -> Located Name -> DsM (SrcSpan, Core TH.DecQ) rep_ty_sig mk_sig loc sig_ty nm = do { nm1 <- lookupLOcc nm ; ty1 <- repHsSigType sig_ty ; sig <- repProto mk_sig nm1 ty1 ; return (loc, sig) } rep_wc_ty_sig :: Name -> SrcSpan -> LHsSigWcType Name -> Located Name -> DsM (SrcSpan, Core TH.DecQ) -- We must special-case the top-level explicit for-all of a TypeSig -- See Note [Scoped type variables in bindings] rep_wc_ty_sig mk_sig loc sig_ty nm | HsIB { hsib_vars = implicit_tvs, hsib_body = sig1 } <- sig_ty , (explicit_tvs, ctxt, ty) <- splitLHsSigmaTy (hswc_body sig1) = do { nm1 <- lookupLOcc nm ; let rep_in_scope_tv tv = do { name <- lookupBinder (hsLTyVarName tv) ; repTyVarBndrWithKind tv name } all_tvs = map (noLoc . UserTyVar . noLoc) implicit_tvs ++ explicit_tvs ; th_tvs <- repList tyVarBndrTyConName rep_in_scope_tv all_tvs ; th_ctxt <- repLContext ctxt ; th_ty <- repLTy ty ; ty1 <- if null all_tvs && null (unLoc ctxt) then return th_ty else repTForall th_tvs th_ctxt th_ty ; sig <- repProto mk_sig nm1 ty1 ; return (loc, sig) } rep_inline :: Located Name -> InlinePragma -- Never defaultInlinePragma -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)] rep_inline nm ispec loc = do { nm1 <- lookupLOcc nm ; inline <- repInline $ inl_inline ispec ; rm <- repRuleMatch $ inl_rule ispec ; phases <- repPhases $ inl_act ispec ; pragma <- repPragInl nm1 inline rm phases ; return [(loc, pragma)] } rep_specialise :: Located Name -> LHsSigType Name -> InlinePragma -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)] rep_specialise nm ty ispec loc = do { nm1 <- lookupLOcc nm ; ty1 <- repHsSigType ty ; phases <- repPhases $ inl_act ispec ; let inline = inl_inline ispec ; pragma <- if isEmptyInlineSpec inline then -- SPECIALISE repPragSpec nm1 ty1 phases else -- SPECIALISE INLINE do { inline1 <- repInline inline ; repPragSpecInl nm1 ty1 inline1 phases } ; return [(loc, pragma)] } rep_specialiseInst :: LHsSigType Name -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)] rep_specialiseInst ty loc = do { ty1 <- repHsSigType ty ; pragma <- repPragSpecInst ty1 ; return [(loc, pragma)] } repInline :: InlineSpec -> DsM (Core TH.Inline) repInline NoInline = dataCon noInlineDataConName repInline Inline = dataCon inlineDataConName repInline Inlinable = dataCon inlinableDataConName repInline spec = notHandled "repInline" (ppr spec) repRuleMatch :: RuleMatchInfo -> DsM (Core TH.RuleMatch) repRuleMatch ConLike = dataCon conLikeDataConName repRuleMatch FunLike = dataCon funLikeDataConName repPhases :: Activation -> DsM (Core TH.Phases) repPhases (ActiveBefore _ i) = do { MkC arg <- coreIntLit i ; dataCon' beforePhaseDataConName [arg] } repPhases (ActiveAfter _ i) = do { MkC arg <- coreIntLit i ; dataCon' fromPhaseDataConName [arg] } repPhases _ = dataCon allPhasesDataConName ------------------------------------------------------- -- Types ------------------------------------------------------- addSimpleTyVarBinds :: [Name] -- the binders to be added -> DsM (Core (TH.Q a)) -- action in the ext env -> DsM (Core (TH.Q a)) addSimpleTyVarBinds names thing_inside = do { fresh_names <- mkGenSyms names ; term <- addBinds fresh_names thing_inside ; wrapGenSyms fresh_names term } addTyVarBinds :: LHsQTyVars Name -- the binders to be added -> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a))) -- action in the ext env -> DsM (Core (TH.Q a)) -- gensym a list of type variables and enter them into the meta environment; -- the computations passed as the second argument is executed in that extended -- meta environment and gets the *new* names on Core-level as an argument addTyVarBinds (HsQTvs { hsq_implicit = imp_tvs, hsq_explicit = exp_tvs }) m = do { fresh_imp_names <- mkGenSyms imp_tvs ; fresh_exp_names <- mkGenSyms (map hsLTyVarName exp_tvs) ; let fresh_names = fresh_imp_names ++ fresh_exp_names ; term <- addBinds fresh_names $ do { kbs <- repList tyVarBndrTyConName mk_tv_bndr (exp_tvs `zip` fresh_exp_names) ; m kbs } ; wrapGenSyms fresh_names term } where mk_tv_bndr (tv, (_,v)) = repTyVarBndrWithKind tv (coreVar v) addTyClTyVarBinds :: LHsQTyVars Name -> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a))) -> DsM (Core (TH.Q a)) -- Used for data/newtype declarations, and family instances, -- so that the nested type variables work right -- instance C (T a) where -- type W (T a) = blah -- The 'a' in the type instance is the one bound by the instance decl addTyClTyVarBinds tvs m = do { let tv_names = hsAllLTyVarNames tvs ; env <- dsGetMetaEnv ; freshNames <- mkGenSyms (filterOut (`elemNameEnv` env) tv_names) -- Make fresh names for the ones that are not already in scope -- This makes things work for family declarations ; term <- addBinds freshNames $ do { kbs <- repList tyVarBndrTyConName mk_tv_bndr (hsQTvExplicit tvs) ; m kbs } ; wrapGenSyms freshNames term } where mk_tv_bndr tv = do { v <- lookupBinder (hsLTyVarName tv) ; repTyVarBndrWithKind tv v } -- Produce kinded binder constructors from the Haskell tyvar binders -- repTyVarBndrWithKind :: LHsTyVarBndr Name -> Core TH.Name -> DsM (Core TH.TyVarBndr) repTyVarBndrWithKind (L _ (UserTyVar _)) nm = repPlainTV nm repTyVarBndrWithKind (L _ (KindedTyVar _ ki)) nm = repLKind ki >>= repKindedTV nm -- | Represent a type variable binder repTyVarBndr :: LHsTyVarBndr Name -> DsM (Core TH.TyVarBndr) repTyVarBndr (L _ (UserTyVar (L _ nm)) )= do { nm' <- lookupBinder nm ; repPlainTV nm' } repTyVarBndr (L _ (KindedTyVar (L _ nm) ki)) = do { nm' <- lookupBinder nm ; ki' <- repLKind ki ; repKindedTV nm' ki' } -- represent a type context -- repLContext :: LHsContext Name -> DsM (Core TH.CxtQ) repLContext (L _ ctxt) = repContext ctxt repContext :: HsContext Name -> DsM (Core TH.CxtQ) repContext ctxt = do preds <- repList typeQTyConName repLTy ctxt repCtxt preds repHsSigType :: LHsSigType Name -> DsM (Core TH.TypeQ) repHsSigType (HsIB { hsib_vars = vars , hsib_body = body }) | (explicit_tvs, ctxt, ty) <- splitLHsSigmaTy body = addTyVarBinds (HsQTvs { hsq_implicit = [] , hsq_explicit = map (noLoc . UserTyVar . noLoc) vars ++ explicit_tvs , hsq_dependent = emptyNameSet }) $ \ th_tvs -> do { th_ctxt <- repLContext ctxt ; th_ty <- repLTy ty ; if null vars && null explicit_tvs && null (unLoc ctxt) then return th_ty else repTForall th_tvs th_ctxt th_ty } repHsSigWcType :: LHsSigWcType Name -> DsM (Core TH.TypeQ) repHsSigWcType ib_ty@(HsIB { hsib_body = sig1 }) = repHsSigType (ib_ty { hsib_body = hswc_body sig1 }) -- yield the representation of a list of types -- repLTys :: [LHsType Name] -> DsM [Core TH.TypeQ] repLTys tys = mapM repLTy tys -- represent a type -- repLTy :: LHsType Name -> DsM (Core TH.TypeQ) repLTy (L _ ty) = repTy ty repForall :: HsType Name -> DsM (Core TH.TypeQ) -- Arg of repForall is always HsForAllTy or HsQualTy repForall ty | (tvs, ctxt, tau) <- splitLHsSigmaTy (noLoc ty) = addTyVarBinds (HsQTvs { hsq_implicit = [], hsq_explicit = tvs , hsq_dependent = emptyNameSet }) $ \bndrs -> do { ctxt1 <- repLContext ctxt ; ty1 <- repLTy tau ; repTForall bndrs ctxt1 ty1 } repTy :: HsType Name -> DsM (Core TH.TypeQ) repTy ty@(HsForAllTy {}) = repForall ty repTy ty@(HsQualTy {}) = repForall ty repTy (HsTyVar (L _ n)) | isTvOcc occ = do tv1 <- lookupOcc n repTvar tv1 | isDataOcc occ = do tc1 <- lookupOcc n repPromotedDataCon tc1 | n == eqTyConName = repTequality | otherwise = do tc1 <- lookupOcc n repNamedTyCon tc1 where occ = nameOccName n repTy (HsAppTy f a) = do f1 <- repLTy f a1 <- repLTy a repTapp f1 a1 repTy (HsFunTy f a) = do f1 <- repLTy f a1 <- repLTy a tcon <- repArrowTyCon repTapps tcon [f1, a1] repTy (HsListTy t) = do t1 <- repLTy t tcon <- repListTyCon repTapp tcon t1 repTy (HsPArrTy t) = do t1 <- repLTy t tcon <- repTy (HsTyVar (noLoc (tyConName parrTyCon))) repTapp tcon t1 repTy (HsTupleTy HsUnboxedTuple tys) = do tys1 <- repLTys tys tcon <- repUnboxedTupleTyCon (length tys) repTapps tcon tys1 repTy (HsTupleTy _ tys) = do tys1 <- repLTys tys tcon <- repTupleTyCon (length tys) repTapps tcon tys1 repTy (HsOpTy ty1 n ty2) = repLTy ((nlHsTyVar (unLoc n) `nlHsAppTy` ty1) `nlHsAppTy` ty2) repTy (HsParTy t) = repLTy t repTy (HsEqTy t1 t2) = do t1' <- repLTy t1 t2' <- repLTy t2 eq <- repTequality repTapps eq [t1', t2'] repTy (HsKindSig t k) = do t1 <- repLTy t k1 <- repLKind k repTSig t1 k1 repTy (HsSpliceTy splice _) = repSplice splice repTy (HsExplicitListTy _ tys) = do tys1 <- repLTys tys repTPromotedList tys1 repTy (HsExplicitTupleTy _ tys) = do tys1 <- repLTys tys tcon <- repPromotedTupleTyCon (length tys) repTapps tcon tys1 repTy (HsTyLit lit) = do lit' <- repTyLit lit repTLit lit' repTy (HsWildCardTy (AnonWildCard _)) = repTWildCard repTy ty = notHandled "Exotic form of type" (ppr ty) repTyLit :: HsTyLit -> DsM (Core TH.TyLitQ) repTyLit (HsNumTy _ i) = do iExpr <- mkIntegerExpr i rep2 numTyLitName [iExpr] repTyLit (HsStrTy _ s) = do { s' <- mkStringExprFS s ; rep2 strTyLitName [s'] } -- represent a kind -- repLKind :: LHsKind Name -> DsM (Core TH.Kind) repLKind ki = do { let (kis, ki') = splitHsFunType ki ; kis_rep <- mapM repLKind kis ; ki'_rep <- repNonArrowLKind ki' ; kcon <- repKArrow ; let f k1 k2 = repKApp kcon k1 >>= flip repKApp k2 ; foldrM f ki'_rep kis_rep } -- | Represent a kind wrapped in a Maybe repMaybeLKind :: Maybe (LHsKind Name) -> DsM (Core (Maybe TH.Kind)) repMaybeLKind Nothing = do { coreNothing kindTyConName } repMaybeLKind (Just ki) = do { ki' <- repLKind ki ; coreJust kindTyConName ki' } repNonArrowLKind :: LHsKind Name -> DsM (Core TH.Kind) repNonArrowLKind (L _ ki) = repNonArrowKind ki repNonArrowKind :: HsKind Name -> DsM (Core TH.Kind) repNonArrowKind (HsTyVar (L _ name)) | isLiftedTypeKindTyConName name = repKStar | name `hasKey` constraintKindTyConKey = repKConstraint | isTvOcc (nameOccName name) = lookupOcc name >>= repKVar | otherwise = lookupOcc name >>= repKCon repNonArrowKind (HsAppTy f a) = do { f' <- repLKind f ; a' <- repLKind a ; repKApp f' a' } repNonArrowKind (HsListTy k) = do { k' <- repLKind k ; kcon <- repKList ; repKApp kcon k' } repNonArrowKind (HsTupleTy _ ks) = do { ks' <- mapM repLKind ks ; kcon <- repKTuple (length ks) ; repKApps kcon ks' } repNonArrowKind k = notHandled "Exotic form of kind" (ppr k) repRole :: Located (Maybe Role) -> DsM (Core TH.Role) repRole (L _ (Just Nominal)) = rep2 nominalRName [] repRole (L _ (Just Representational)) = rep2 representationalRName [] repRole (L _ (Just Phantom)) = rep2 phantomRName [] repRole (L _ Nothing) = rep2 inferRName [] ----------------------------------------------------------------------------- -- Splices ----------------------------------------------------------------------------- repSplice :: HsSplice Name -> DsM (Core a) -- See Note [How brackets and nested splices are handled] in TcSplice -- We return a CoreExpr of any old type; the context should know repSplice (HsTypedSplice n _) = rep_splice n repSplice (HsUntypedSplice n _) = rep_splice n repSplice (HsQuasiQuote n _ _ _) = rep_splice n repSplice e@(HsSpliced _ _) = pprPanic "repSplice" (ppr e) rep_splice :: Name -> DsM (Core a) rep_splice splice_name = do { mb_val <- dsLookupMetaEnv splice_name ; case mb_val of Just (DsSplice e) -> do { e' <- dsExpr e ; return (MkC e') } _ -> pprPanic "HsSplice" (ppr splice_name) } -- Should not happen; statically checked ----------------------------------------------------------------------------- -- Expressions ----------------------------------------------------------------------------- repLEs :: [LHsExpr Name] -> DsM (Core [TH.ExpQ]) repLEs es = repList expQTyConName repLE es -- FIXME: some of these panics should be converted into proper error messages -- unless we can make sure that constructs, which are plainly not -- supported in TH already lead to error messages at an earlier stage repLE :: LHsExpr Name -> DsM (Core TH.ExpQ) repLE (L loc e) = putSrcSpanDs loc (repE e) repE :: HsExpr Name -> DsM (Core TH.ExpQ) repE (HsVar (L _ x)) = do { mb_val <- dsLookupMetaEnv x ; case mb_val of Nothing -> do { str <- globalVar x ; repVarOrCon x str } Just (DsBound y) -> repVarOrCon x (coreVar y) Just (DsSplice e) -> do { e' <- dsExpr e ; return (MkC e') } } repE e@(HsIPVar _) = notHandled "Implicit parameters" (ppr e) repE e@(HsOverLabel _) = notHandled "Overloaded labels" (ppr e) repE e@(HsRecFld f) = case f of Unambiguous _ x -> repE (HsVar (noLoc x)) Ambiguous{} -> notHandled "Ambiguous record selectors" (ppr e) -- Remember, we're desugaring renamer output here, so -- HsOverlit can definitely occur repE (HsOverLit l) = do { a <- repOverloadedLiteral l; repLit a } repE (HsLit l) = do { a <- repLiteral l; repLit a } repE (HsLam (MG { mg_alts = L _ [m] })) = repLambda m repE (HsLamCase _ (MG { mg_alts = L _ ms })) = do { ms' <- mapM repMatchTup ms ; core_ms <- coreList matchQTyConName ms' ; repLamCase core_ms } repE (HsApp x y) = do {a <- repLE x; b <- repLE y; repApp a b} repE (OpApp e1 op _ e2) = do { arg1 <- repLE e1; arg2 <- repLE e2; the_op <- repLE op ; repInfixApp arg1 the_op arg2 } repE (NegApp x _) = do a <- repLE x negateVar <- lookupOcc negateName >>= repVar negateVar `repApp` a repE (HsPar x) = repLE x repE (SectionL x y) = do { a <- repLE x; b <- repLE y; repSectionL a b } repE (SectionR x y) = do { a <- repLE x; b <- repLE y; repSectionR a b } repE (HsCase e (MG { mg_alts = L _ ms })) = do { arg <- repLE e ; ms2 <- mapM repMatchTup ms ; core_ms2 <- coreList matchQTyConName ms2 ; repCaseE arg core_ms2 } repE (HsIf _ x y z) = do a <- repLE x b <- repLE y c <- repLE z repCond a b c repE (HsMultiIf _ alts) = do { (binds, alts') <- liftM unzip $ mapM repLGRHS alts ; expr' <- repMultiIf (nonEmptyCoreList alts') ; wrapGenSyms (concat binds) expr' } repE (HsLet (L _ bs) e) = do { (ss,ds) <- repBinds bs ; e2 <- addBinds ss (repLE e) ; z <- repLetE ds e2 ; wrapGenSyms ss z } -- FIXME: I haven't got the types here right yet repE e@(HsDo ctxt (L _ sts) _) | case ctxt of { DoExpr -> True; GhciStmtCtxt -> True; _ -> False } = do { (ss,zs) <- repLSts sts; e' <- repDoE (nonEmptyCoreList zs); wrapGenSyms ss e' } | ListComp <- ctxt = do { (ss,zs) <- repLSts sts; e' <- repComp (nonEmptyCoreList zs); wrapGenSyms ss e' } | otherwise = notHandled "mdo, monad comprehension and [: :]" (ppr e) repE (ExplicitList _ _ es) = do { xs <- repLEs es; repListExp xs } repE e@(ExplicitPArr _ _) = notHandled "Parallel arrays" (ppr e) repE e@(ExplicitTuple es boxed) | not (all tupArgPresent es) = notHandled "Tuple sections" (ppr e) | isBoxed boxed = do { xs <- repLEs [e | L _ (Present e) <- es]; repTup xs } | otherwise = do { xs <- repLEs [e | L _ (Present e) <- es] ; repUnboxedTup xs } repE (RecordCon { rcon_con_name = c, rcon_flds = flds }) = do { x <- lookupLOcc c; fs <- repFields flds; repRecCon x fs } repE (RecordUpd { rupd_expr = e, rupd_flds = flds }) = do { x <- repLE e; fs <- repUpdFields flds; repRecUpd x fs } repE (ExprWithTySig e ty) = do { e1 <- repLE e ; t1 <- repHsSigWcType ty ; repSigExp e1 t1 } repE (ArithSeq _ _ aseq) = case aseq of From e -> do { ds1 <- repLE e; repFrom ds1 } FromThen e1 e2 -> do ds1 <- repLE e1 ds2 <- repLE e2 repFromThen ds1 ds2 FromTo e1 e2 -> do ds1 <- repLE e1 ds2 <- repLE e2 repFromTo ds1 ds2 FromThenTo e1 e2 e3 -> do ds1 <- repLE e1 ds2 <- repLE e2 ds3 <- repLE e3 repFromThenTo ds1 ds2 ds3 repE (HsSpliceE splice) = repSplice splice repE (HsStatic e) = repLE e >>= rep2 staticEName . (:[]) . unC repE (HsUnboundVar uv) = do occ <- occNameLit (unboundVarOcc uv) sname <- repNameS occ repUnboundVar sname repE e@(PArrSeq {}) = notHandled "Parallel arrays" (ppr e) repE e@(HsCoreAnn {}) = notHandled "Core annotations" (ppr e) repE e@(HsSCC {}) = notHandled "Cost centres" (ppr e) repE e@(HsTickPragma {}) = notHandled "Tick Pragma" (ppr e) repE e@(HsTcBracketOut {}) = notHandled "TH brackets" (ppr e) repE e = notHandled "Expression form" (ppr e) ----------------------------------------------------------------------------- -- Building representations of auxillary structures like Match, Clause, Stmt, repMatchTup :: LMatch Name (LHsExpr Name) -> DsM (Core TH.MatchQ) repMatchTup (L _ (Match _ [p] _ (GRHSs guards (L _ wheres)))) = do { ss1 <- mkGenSyms (collectPatBinders p) ; addBinds ss1 $ do { ; p1 <- repLP p ; (ss2,ds) <- repBinds wheres ; addBinds ss2 $ do { ; gs <- repGuards guards ; match <- repMatch p1 gs ds ; wrapGenSyms (ss1++ss2) match }}} repMatchTup _ = panic "repMatchTup: case alt with more than one arg" repClauseTup :: LMatch Name (LHsExpr Name) -> DsM (Core TH.ClauseQ) repClauseTup (L _ (Match _ ps _ (GRHSs guards (L _ wheres)))) = do { ss1 <- mkGenSyms (collectPatsBinders ps) ; addBinds ss1 $ do { ps1 <- repLPs ps ; (ss2,ds) <- repBinds wheres ; addBinds ss2 $ do { gs <- repGuards guards ; clause <- repClause ps1 gs ds ; wrapGenSyms (ss1++ss2) clause }}} repGuards :: [LGRHS Name (LHsExpr Name)] -> DsM (Core TH.BodyQ) repGuards [L _ (GRHS [] e)] = do {a <- repLE e; repNormal a } repGuards other = do { zs <- mapM repLGRHS other ; let (xs, ys) = unzip zs ; gd <- repGuarded (nonEmptyCoreList ys) ; wrapGenSyms (concat xs) gd } repLGRHS :: LGRHS Name (LHsExpr Name) -> DsM ([GenSymBind], (Core (TH.Q (TH.Guard, TH.Exp)))) repLGRHS (L _ (GRHS [L _ (BodyStmt e1 _ _ _)] e2)) = do { guarded <- repLNormalGE e1 e2 ; return ([], guarded) } repLGRHS (L _ (GRHS ss rhs)) = do { (gs, ss') <- repLSts ss ; rhs' <- addBinds gs $ repLE rhs ; guarded <- repPatGE (nonEmptyCoreList ss') rhs' ; return (gs, guarded) } repFields :: HsRecordBinds Name -> DsM (Core [TH.Q TH.FieldExp]) repFields (HsRecFields { rec_flds = flds }) = repList fieldExpQTyConName rep_fld flds where rep_fld :: LHsRecField Name (LHsExpr Name) -> DsM (Core (TH.Q TH.FieldExp)) rep_fld (L _ fld) = do { fn <- lookupLOcc (hsRecFieldSel fld) ; e <- repLE (hsRecFieldArg fld) ; repFieldExp fn e } repUpdFields :: [LHsRecUpdField Name] -> DsM (Core [TH.Q TH.FieldExp]) repUpdFields = repList fieldExpQTyConName rep_fld where rep_fld :: LHsRecUpdField Name -> DsM (Core (TH.Q TH.FieldExp)) rep_fld (L l fld) = case unLoc (hsRecFieldLbl fld) of Unambiguous _ sel_name -> do { fn <- lookupLOcc (L l sel_name) ; e <- repLE (hsRecFieldArg fld) ; repFieldExp fn e } _ -> notHandled "Ambiguous record updates" (ppr fld) ----------------------------------------------------------------------------- -- Representing Stmt's is tricky, especially if bound variables -- shadow each other. Consider: [| do { x <- f 1; x <- f x; g x } |] -- First gensym new names for every variable in any of the patterns. -- both static (x'1 and x'2), and dynamic ((gensym "x") and (gensym "y")) -- if variables didn't shaddow, the static gensym wouldn't be necessary -- and we could reuse the original names (x and x). -- -- do { x'1 <- gensym "x" -- ; x'2 <- gensym "x" -- ; doE [ BindSt (pvar x'1) [| f 1 |] -- , BindSt (pvar x'2) [| f x |] -- , NoBindSt [| g x |] -- ] -- } -- The strategy is to translate a whole list of do-bindings by building a -- bigger environment, and a bigger set of meta bindings -- (like: x'1 <- gensym "x" ) and then combining these with the translations -- of the expressions within the Do ----------------------------------------------------------------------------- -- The helper function repSts computes the translation of each sub expression -- and a bunch of prefix bindings denoting the dynamic renaming. repLSts :: [LStmt Name (LHsExpr Name)] -> DsM ([GenSymBind], [Core TH.StmtQ]) repLSts stmts = repSts (map unLoc stmts) repSts :: [Stmt Name (LHsExpr Name)] -> DsM ([GenSymBind], [Core TH.StmtQ]) repSts (BindStmt p e _ _ _ : ss) = do { e2 <- repLE e ; ss1 <- mkGenSyms (collectPatBinders p) ; addBinds ss1 $ do { ; p1 <- repLP p; ; (ss2,zs) <- repSts ss ; z <- repBindSt p1 e2 ; return (ss1++ss2, z : zs) }} repSts (LetStmt (L _ bs) : ss) = do { (ss1,ds) <- repBinds bs ; z <- repLetSt ds ; (ss2,zs) <- addBinds ss1 (repSts ss) ; return (ss1++ss2, z : zs) } repSts (BodyStmt e _ _ _ : ss) = do { e2 <- repLE e ; z <- repNoBindSt e2 ; (ss2,zs) <- repSts ss ; return (ss2, z : zs) } repSts (ParStmt stmt_blocks _ _ _ : ss) = do { (ss_s, stmt_blocks1) <- mapAndUnzipM rep_stmt_block stmt_blocks ; let stmt_blocks2 = nonEmptyCoreList stmt_blocks1 ss1 = concat ss_s ; z <- repParSt stmt_blocks2 ; (ss2, zs) <- addBinds ss1 (repSts ss) ; return (ss1++ss2, z : zs) } where rep_stmt_block :: ParStmtBlock Name Name -> DsM ([GenSymBind], Core [TH.StmtQ]) rep_stmt_block (ParStmtBlock stmts _ _) = do { (ss1, zs) <- repSts (map unLoc stmts) ; zs1 <- coreList stmtQTyConName zs ; return (ss1, zs1) } repSts [LastStmt e _ _] = do { e2 <- repLE e ; z <- repNoBindSt e2 ; return ([], [z]) } repSts [] = return ([],[]) repSts other = notHandled "Exotic statement" (ppr other) ----------------------------------------------------------- -- Bindings ----------------------------------------------------------- repBinds :: HsLocalBinds Name -> DsM ([GenSymBind], Core [TH.DecQ]) repBinds EmptyLocalBinds = do { core_list <- coreList decQTyConName [] ; return ([], core_list) } repBinds b@(HsIPBinds _) = notHandled "Implicit parameters" (ppr b) repBinds (HsValBinds decs) = do { let { bndrs = hsSigTvBinders decs ++ collectHsValBinders decs } -- No need to worrry about detailed scopes within -- the binding group, because we are talking Names -- here, so we can safely treat it as a mutually -- recursive group -- For hsSigTvBinders see Note [Scoped type variables in bindings] ; ss <- mkGenSyms bndrs ; prs <- addBinds ss (rep_val_binds decs) ; core_list <- coreList decQTyConName (de_loc (sort_by_loc prs)) ; return (ss, core_list) } rep_val_binds :: HsValBinds Name -> DsM [(SrcSpan, Core TH.DecQ)] -- Assumes: all the binders of the binding are alrady in the meta-env rep_val_binds (ValBindsOut binds sigs) = do { core1 <- rep_binds' (unionManyBags (map snd binds)) ; core2 <- rep_sigs' sigs ; return (core1 ++ core2) } rep_val_binds (ValBindsIn _ _) = panic "rep_val_binds: ValBindsIn" rep_binds :: LHsBinds Name -> DsM [Core TH.DecQ] rep_binds binds = do { binds_w_locs <- rep_binds' binds ; return (de_loc (sort_by_loc binds_w_locs)) } rep_binds' :: LHsBinds Name -> DsM [(SrcSpan, Core TH.DecQ)] rep_binds' = mapM rep_bind . bagToList rep_bind :: LHsBind Name -> DsM (SrcSpan, Core TH.DecQ) -- Assumes: all the binders of the binding are alrady in the meta-env -- Note GHC treats declarations of a variable (not a pattern) -- e.g. x = g 5 as a Fun MonoBinds. This is indicated by a single match -- with an empty list of patterns rep_bind (L loc (FunBind { fun_id = fn, fun_matches = MG { mg_alts = L _ [L _ (Match _ [] _ (GRHSs guards (L _ wheres)))] } })) = do { (ss,wherecore) <- repBinds wheres ; guardcore <- addBinds ss (repGuards guards) ; fn' <- lookupLBinder fn ; p <- repPvar fn' ; ans <- repVal p guardcore wherecore ; ans' <- wrapGenSyms ss ans ; return (loc, ans') } rep_bind (L loc (FunBind { fun_id = fn , fun_matches = MG { mg_alts = L _ ms } })) = do { ms1 <- mapM repClauseTup ms ; fn' <- lookupLBinder fn ; ans <- repFun fn' (nonEmptyCoreList ms1) ; return (loc, ans) } rep_bind (L loc (PatBind { pat_lhs = pat , pat_rhs = GRHSs guards (L _ wheres) })) = do { patcore <- repLP pat ; (ss,wherecore) <- repBinds wheres ; guardcore <- addBinds ss (repGuards guards) ; ans <- repVal patcore guardcore wherecore ; ans' <- wrapGenSyms ss ans ; return (loc, ans') } rep_bind (L _ (VarBind { var_id = v, var_rhs = e})) = do { v' <- lookupBinder v ; e2 <- repLE e ; x <- repNormal e2 ; patcore <- repPvar v' ; empty_decls <- coreList decQTyConName [] ; ans <- repVal patcore x empty_decls ; return (srcLocSpan (getSrcLoc v), ans) } rep_bind (L _ (AbsBinds {})) = panic "rep_bind: AbsBinds" rep_bind (L _ (AbsBindsSig {})) = panic "rep_bind: AbsBindsSig" rep_bind (L _ dec@(PatSynBind {})) = notHandled "pattern synonyms" (ppr dec) ----------------------------------------------------------------------------- -- Since everything in a Bind is mutually recursive we need rename all -- all the variables simultaneously. For example: -- [| AndMonoBinds (f x = x + g 2) (g x = f 1 + 2) |] would translate to -- do { f'1 <- gensym "f" -- ; g'2 <- gensym "g" -- ; [ do { x'3 <- gensym "x"; fun f'1 [pvar x'3] [| x + g2 |]}, -- do { x'4 <- gensym "x"; fun g'2 [pvar x'4] [| f 1 + 2 |]} -- ]} -- This requires collecting the bindings (f'1 <- gensym "f"), and the -- environment ( f |-> f'1 ) from each binding, and then unioning them -- together. As we do this we collect GenSymBinds's which represent the renamed -- variables bound by the Bindings. In order not to lose track of these -- representations we build a shadow datatype MB with the same structure as -- MonoBinds, but which has slots for the representations ----------------------------------------------------------------------------- -- GHC allows a more general form of lambda abstraction than specified -- by Haskell 98. In particular it allows guarded lambda's like : -- (\ x | even x -> 0 | odd x -> 1) at the moment we can't represent this in -- Haskell Template's Meta.Exp type so we punt if it isn't a simple thing like -- (\ p1 .. pn -> exp) by causing an error. repLambda :: LMatch Name (LHsExpr Name) -> DsM (Core TH.ExpQ) repLambda (L _ (Match _ ps _ (GRHSs [L _ (GRHS [] e)] (L _ EmptyLocalBinds)))) = do { let bndrs = collectPatsBinders ps ; ; ss <- mkGenSyms bndrs ; lam <- addBinds ss ( do { xs <- repLPs ps; body <- repLE e; repLam xs body }) ; wrapGenSyms ss lam } repLambda (L _ m) = notHandled "Guarded labmdas" (pprMatch (LambdaExpr :: HsMatchContext Name) m) ----------------------------------------------------------------------------- -- Patterns -- repP deals with patterns. It assumes that we have already -- walked over the pattern(s) once to collect the binders, and -- have extended the environment. So every pattern-bound -- variable should already appear in the environment. -- Process a list of patterns repLPs :: [LPat Name] -> DsM (Core [TH.PatQ]) repLPs ps = repList patQTyConName repLP ps repLP :: LPat Name -> DsM (Core TH.PatQ) repLP (L _ p) = repP p repP :: Pat Name -> DsM (Core TH.PatQ) repP (WildPat _) = repPwild repP (LitPat l) = do { l2 <- repLiteral l; repPlit l2 } repP (VarPat (L _ x)) = do { x' <- lookupBinder x; repPvar x' } repP (LazyPat p) = do { p1 <- repLP p; repPtilde p1 } repP (BangPat p) = do { p1 <- repLP p; repPbang p1 } repP (AsPat x p) = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 } repP (ParPat p) = repLP p repP (ListPat ps _ Nothing) = do { qs <- repLPs ps; repPlist qs } repP (ListPat ps ty1 (Just (_,e))) = do { p <- repP (ListPat ps ty1 Nothing); e' <- repE (syn_expr e); repPview e' p} repP (TuplePat ps boxed _) | isBoxed boxed = do { qs <- repLPs ps; repPtup qs } | otherwise = do { qs <- repLPs ps; repPunboxedTup qs } repP (ConPatIn dc details) = do { con_str <- lookupLOcc dc ; case details of PrefixCon ps -> do { qs <- repLPs ps; repPcon con_str qs } RecCon rec -> do { fps <- repList fieldPatQTyConName rep_fld (rec_flds rec) ; repPrec con_str fps } InfixCon p1 p2 -> do { p1' <- repLP p1; p2' <- repLP p2; repPinfix p1' con_str p2' } } where rep_fld :: LHsRecField Name (LPat Name) -> DsM (Core (TH.Name,TH.PatQ)) rep_fld (L _ fld) = do { MkC v <- lookupLOcc (hsRecFieldSel fld) ; MkC p <- repLP (hsRecFieldArg fld) ; rep2 fieldPatName [v,p] } repP (NPat (L _ l) Nothing _ _) = do { a <- repOverloadedLiteral l; repPlit a } repP (ViewPat e p _) = do { e' <- repLE e; p' <- repLP p; repPview e' p' } repP p@(NPat _ (Just _) _ _) = notHandled "Negative overloaded patterns" (ppr p) repP p@(SigPatIn {}) = notHandled "Type signatures in patterns" (ppr p) -- The problem is to do with scoped type variables. -- To implement them, we have to implement the scoping rules -- here in DsMeta, and I don't want to do that today! -- do { p' <- repLP p; t' <- repLTy t; repPsig p' t' } -- repPsig :: Core TH.PatQ -> Core TH.TypeQ -> DsM (Core TH.PatQ) -- repPsig (MkC p) (MkC t) = rep2 sigPName [p, t] repP (SplicePat splice) = repSplice splice repP other = notHandled "Exotic pattern" (ppr other) ---------------------------------------------------------- -- Declaration ordering helpers sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)] sort_by_loc xs = sortBy comp xs where comp x y = compare (fst x) (fst y) de_loc :: [(a, b)] -> [b] de_loc = map snd ---------------------------------------------------------- -- The meta-environment -- A name/identifier association for fresh names of locally bound entities type GenSymBind = (Name, Id) -- Gensym the string and bind it to the Id -- I.e. (x, x_id) means -- let x_id = gensym "x" in ... -- Generate a fresh name for a locally bound entity mkGenSyms :: [Name] -> DsM [GenSymBind] -- We can use the existing name. For example: -- [| \x_77 -> x_77 + x_77 |] -- desugars to -- do { x_77 <- genSym "x"; .... } -- We use the same x_77 in the desugared program, but with the type Bndr -- instead of Int -- -- We do make it an Internal name, though (hence localiseName) -- -- Nevertheless, it's monadic because we have to generate nameTy mkGenSyms ns = do { var_ty <- lookupType nameTyConName ; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] } addBinds :: [GenSymBind] -> DsM a -> DsM a -- Add a list of fresh names for locally bound entities to the -- meta environment (which is part of the state carried around -- by the desugarer monad) addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,DsBound id) | (n,id) <- bs]) m -- Look up a locally bound name -- lookupLBinder :: Located Name -> DsM (Core TH.Name) lookupLBinder (L _ n) = lookupBinder n lookupBinder :: Name -> DsM (Core TH.Name) lookupBinder = lookupOcc -- Binders are brought into scope before the pattern or what-not is -- desugared. Moreover, in instance declaration the binder of a method -- will be the selector Id and hence a global; so we need the -- globalVar case of lookupOcc -- Look up a name that is either locally bound or a global name -- -- * If it is a global name, generate the "original name" representation (ie, -- the <module>:<name> form) for the associated entity -- lookupLOcc :: Located Name -> DsM (Core TH.Name) -- Lookup an occurrence; it can't be a splice. -- Use the in-scope bindings if they exist lookupLOcc (L _ n) = lookupOcc n lookupOcc :: Name -> DsM (Core TH.Name) lookupOcc n = do { mb_val <- dsLookupMetaEnv n ; case mb_val of Nothing -> globalVar n Just (DsBound x) -> return (coreVar x) Just (DsSplice _) -> pprPanic "repE:lookupOcc" (ppr n) } globalVar :: Name -> DsM (Core TH.Name) -- Not bound by the meta-env -- Could be top-level; or could be local -- f x = $(g [| x |]) -- Here the x will be local globalVar name | isExternalName name = do { MkC mod <- coreStringLit name_mod ; MkC pkg <- coreStringLit name_pkg ; MkC occ <- nameLit name ; rep2 mk_varg [pkg,mod,occ] } | otherwise = do { MkC occ <- nameLit name ; MkC uni <- coreIntLit (getKey (getUnique name)) ; rep2 mkNameLName [occ,uni] } where mod = ASSERT( isExternalName name) nameModule name name_mod = moduleNameString (moduleName mod) name_pkg = unitIdString (moduleUnitId mod) name_occ = nameOccName name mk_varg | OccName.isDataOcc name_occ = mkNameG_dName | OccName.isVarOcc name_occ = mkNameG_vName | OccName.isTcOcc name_occ = mkNameG_tcName | otherwise = pprPanic "DsMeta.globalVar" (ppr name) lookupType :: Name -- Name of type constructor (e.g. TH.ExpQ) -> DsM Type -- The type lookupType tc_name = do { tc <- dsLookupTyCon tc_name ; return (mkTyConApp tc []) } wrapGenSyms :: [GenSymBind] -> Core (TH.Q a) -> DsM (Core (TH.Q a)) -- wrapGenSyms [(nm1,id1), (nm2,id2)] y -- --> bindQ (gensym nm1) (\ id1 -> -- bindQ (gensym nm2 (\ id2 -> -- y)) wrapGenSyms binds body@(MkC b) = do { var_ty <- lookupType nameTyConName ; go var_ty binds } where [elt_ty] = tcTyConAppArgs (exprType b) -- b :: Q a, so we can get the type 'a' by looking at the -- argument type. NB: this relies on Q being a data/newtype, -- not a type synonym go _ [] = return body go var_ty ((name,id) : binds) = do { MkC body' <- go var_ty binds ; lit_str <- nameLit name ; gensym_app <- repGensym lit_str ; repBindQ var_ty elt_ty gensym_app (MkC (Lam id body')) } nameLit :: Name -> DsM (Core String) nameLit n = coreStringLit (occNameString (nameOccName n)) occNameLit :: OccName -> DsM (Core String) occNameLit name = coreStringLit (occNameString name) -- %********************************************************************* -- %* * -- Constructing code -- %* * -- %********************************************************************* ----------------------------------------------------------------------------- -- PHANTOM TYPES for consistency. In order to make sure we do this correct -- we invent a new datatype which uses phantom types. newtype Core a = MkC CoreExpr unC :: Core a -> CoreExpr unC (MkC x) = x rep2 :: Name -> [ CoreExpr ] -> DsM (Core a) rep2 n xs = do { id <- dsLookupGlobalId n ; return (MkC (foldl App (Var id) xs)) } dataCon' :: Name -> [CoreExpr] -> DsM (Core a) dataCon' n args = do { id <- dsLookupDataCon n ; return $ MkC $ mkCoreConApps id args } dataCon :: Name -> DsM (Core a) dataCon n = dataCon' n [] -- %********************************************************************* -- %* * -- The 'smart constructors' -- %* * -- %********************************************************************* --------------- Patterns ----------------- repPlit :: Core TH.Lit -> DsM (Core TH.PatQ) repPlit (MkC l) = rep2 litPName [l] repPvar :: Core TH.Name -> DsM (Core TH.PatQ) repPvar (MkC s) = rep2 varPName [s] repPtup :: Core [TH.PatQ] -> DsM (Core TH.PatQ) repPtup (MkC ps) = rep2 tupPName [ps] repPunboxedTup :: Core [TH.PatQ] -> DsM (Core TH.PatQ) repPunboxedTup (MkC ps) = rep2 unboxedTupPName [ps] repPcon :: Core TH.Name -> Core [TH.PatQ] -> DsM (Core TH.PatQ) repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps] repPrec :: Core TH.Name -> Core [(TH.Name,TH.PatQ)] -> DsM (Core TH.PatQ) repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps] repPinfix :: Core TH.PatQ -> Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ) repPinfix (MkC p1) (MkC n) (MkC p2) = rep2 infixPName [p1, n, p2] repPtilde :: Core TH.PatQ -> DsM (Core TH.PatQ) repPtilde (MkC p) = rep2 tildePName [p] repPbang :: Core TH.PatQ -> DsM (Core TH.PatQ) repPbang (MkC p) = rep2 bangPName [p] repPaspat :: Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ) repPaspat (MkC s) (MkC p) = rep2 asPName [s, p] repPwild :: DsM (Core TH.PatQ) repPwild = rep2 wildPName [] repPlist :: Core [TH.PatQ] -> DsM (Core TH.PatQ) repPlist (MkC ps) = rep2 listPName [ps] repPview :: Core TH.ExpQ -> Core TH.PatQ -> DsM (Core TH.PatQ) repPview (MkC e) (MkC p) = rep2 viewPName [e,p] --------------- Expressions ----------------- repVarOrCon :: Name -> Core TH.Name -> DsM (Core TH.ExpQ) repVarOrCon vc str | isDataOcc (nameOccName vc) = repCon str | otherwise = repVar str repVar :: Core TH.Name -> DsM (Core TH.ExpQ) repVar (MkC s) = rep2 varEName [s] repCon :: Core TH.Name -> DsM (Core TH.ExpQ) repCon (MkC s) = rep2 conEName [s] repLit :: Core TH.Lit -> DsM (Core TH.ExpQ) repLit (MkC c) = rep2 litEName [c] repApp :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repApp (MkC x) (MkC y) = rep2 appEName [x,y] repLam :: Core [TH.PatQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repLam (MkC ps) (MkC e) = rep2 lamEName [ps, e] repLamCase :: Core [TH.MatchQ] -> DsM (Core TH.ExpQ) repLamCase (MkC ms) = rep2 lamCaseEName [ms] repTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) repTup (MkC es) = rep2 tupEName [es] repUnboxedTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) repUnboxedTup (MkC es) = rep2 unboxedTupEName [es] repCond :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repCond (MkC x) (MkC y) (MkC z) = rep2 condEName [x,y,z] repMultiIf :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.ExpQ) repMultiIf (MkC alts) = rep2 multiIfEName [alts] repLetE :: Core [TH.DecQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repLetE (MkC ds) (MkC e) = rep2 letEName [ds, e] repCaseE :: Core TH.ExpQ -> Core [TH.MatchQ] -> DsM( Core TH.ExpQ) repCaseE (MkC e) (MkC ms) = rep2 caseEName [e, ms] repDoE :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ) repDoE (MkC ss) = rep2 doEName [ss] repComp :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ) repComp (MkC ss) = rep2 compEName [ss] repListExp :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ) repListExp (MkC es) = rep2 listEName [es] repSigExp :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ) repSigExp (MkC e) (MkC t) = rep2 sigEName [e,t] repRecCon :: Core TH.Name -> Core [TH.Q TH.FieldExp]-> DsM (Core TH.ExpQ) repRecCon (MkC c) (MkC fs) = rep2 recConEName [c,fs] repRecUpd :: Core TH.ExpQ -> Core [TH.Q TH.FieldExp] -> DsM (Core TH.ExpQ) repRecUpd (MkC e) (MkC fs) = rep2 recUpdEName [e,fs] repFieldExp :: Core TH.Name -> Core TH.ExpQ -> DsM (Core (TH.Q TH.FieldExp)) repFieldExp (MkC n) (MkC x) = rep2 fieldExpName [n,x] repInfixApp :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repInfixApp (MkC x) (MkC y) (MkC z) = rep2 infixAppName [x,y,z] repSectionL :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repSectionL (MkC x) (MkC y) = rep2 sectionLName [x,y] repSectionR :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repSectionR (MkC x) (MkC y) = rep2 sectionRName [x,y] ------------ Right hand sides (guarded expressions) ---- repGuarded :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.BodyQ) repGuarded (MkC pairs) = rep2 guardedBName [pairs] repNormal :: Core TH.ExpQ -> DsM (Core TH.BodyQ) repNormal (MkC e) = rep2 normalBName [e] ------------ Guards ---- repLNormalGE :: LHsExpr Name -> LHsExpr Name -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) repLNormalGE g e = do g' <- repLE g e' <- repLE e repNormalGE g' e' repNormalGE :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) repNormalGE (MkC g) (MkC e) = rep2 normalGEName [g, e] repPatGE :: Core [TH.StmtQ] -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp))) repPatGE (MkC ss) (MkC e) = rep2 patGEName [ss, e] ------------- Stmts ------------------- repBindSt :: Core TH.PatQ -> Core TH.ExpQ -> DsM (Core TH.StmtQ) repBindSt (MkC p) (MkC e) = rep2 bindSName [p,e] repLetSt :: Core [TH.DecQ] -> DsM (Core TH.StmtQ) repLetSt (MkC ds) = rep2 letSName [ds] repNoBindSt :: Core TH.ExpQ -> DsM (Core TH.StmtQ) repNoBindSt (MkC e) = rep2 noBindSName [e] repParSt :: Core [[TH.StmtQ]] -> DsM (Core TH.StmtQ) repParSt (MkC sss) = rep2 parSName [sss] -------------- Range (Arithmetic sequences) ----------- repFrom :: Core TH.ExpQ -> DsM (Core TH.ExpQ) repFrom (MkC x) = rep2 fromEName [x] repFromThen :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repFromThen (MkC x) (MkC y) = rep2 fromThenEName [x,y] repFromTo :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repFromTo (MkC x) (MkC y) = rep2 fromToEName [x,y] repFromThenTo :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ) repFromThenTo (MkC x) (MkC y) (MkC z) = rep2 fromThenToEName [x,y,z] ------------ Match and Clause Tuples ----------- repMatch :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.MatchQ) repMatch (MkC p) (MkC bod) (MkC ds) = rep2 matchName [p, bod, ds] repClause :: Core [TH.PatQ] -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.ClauseQ) repClause (MkC ps) (MkC bod) (MkC ds) = rep2 clauseName [ps, bod, ds] -------------- Dec ----------------------------- repVal :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ) repVal (MkC p) (MkC b) (MkC ds) = rep2 valDName [p, b, ds] repFun :: Core TH.Name -> Core [TH.ClauseQ] -> DsM (Core TH.DecQ) repFun (MkC nm) (MkC b) = rep2 funDName [nm, b] repData :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -> Maybe (Core [TH.TypeQ]) -> Core (Maybe TH.Kind) -> Core [TH.ConQ] -> Core TH.CxtQ -> DsM (Core TH.DecQ) repData (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC ksig) (MkC cons) (MkC derivs) = rep2 dataDName [cxt, nm, tvs, ksig, cons, derivs] repData (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC ksig) (MkC cons) (MkC derivs) = rep2 dataInstDName [cxt, nm, tys, ksig, cons, derivs] repNewtype :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -> Maybe (Core [TH.TypeQ]) -> Core (Maybe TH.Kind) -> Core TH.ConQ -> Core TH.CxtQ -> DsM (Core TH.DecQ) repNewtype (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC ksig) (MkC con) (MkC derivs) = rep2 newtypeDName [cxt, nm, tvs, ksig, con, derivs] repNewtype (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC ksig) (MkC con) (MkC derivs) = rep2 newtypeInstDName [cxt, nm, tys, ksig, con, derivs] repTySyn :: Core TH.Name -> Core [TH.TyVarBndr] -> Core TH.TypeQ -> DsM (Core TH.DecQ) repTySyn (MkC nm) (MkC tvs) (MkC rhs) = rep2 tySynDName [nm, tvs, rhs] repInst :: Core (Maybe TH.Overlap) -> Core TH.CxtQ -> Core TH.TypeQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ) repInst (MkC o) (MkC cxt) (MkC ty) (MkC ds) = rep2 instanceWithOverlapDName [o, cxt, ty, ds] repOverlap :: Maybe OverlapMode -> DsM (Core (Maybe TH.Overlap)) repOverlap mb = case mb of Nothing -> nothing Just o -> case o of NoOverlap _ -> nothing Overlappable _ -> just =<< dataCon overlappableDataConName Overlapping _ -> just =<< dataCon overlappingDataConName Overlaps _ -> just =<< dataCon overlapsDataConName Incoherent _ -> just =<< dataCon incoherentDataConName where nothing = coreNothing overlapTyConName just = coreJust overlapTyConName repClass :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr] -> Core [TH.FunDep] -> Core [TH.DecQ] -> DsM (Core TH.DecQ) repClass (MkC cxt) (MkC cls) (MkC tvs) (MkC fds) (MkC ds) = rep2 classDName [cxt, cls, tvs, fds, ds] repDeriv :: Core TH.CxtQ -> Core TH.TypeQ -> DsM (Core TH.DecQ) repDeriv (MkC cxt) (MkC ty) = rep2 standaloneDerivDName [cxt, ty] repPragInl :: Core TH.Name -> Core TH.Inline -> Core TH.RuleMatch -> Core TH.Phases -> DsM (Core TH.DecQ) repPragInl (MkC nm) (MkC inline) (MkC rm) (MkC phases) = rep2 pragInlDName [nm, inline, rm, phases] repPragSpec :: Core TH.Name -> Core TH.TypeQ -> Core TH.Phases -> DsM (Core TH.DecQ) repPragSpec (MkC nm) (MkC ty) (MkC phases) = rep2 pragSpecDName [nm, ty, phases] repPragSpecInl :: Core TH.Name -> Core TH.TypeQ -> Core TH.Inline -> Core TH.Phases -> DsM (Core TH.DecQ) repPragSpecInl (MkC nm) (MkC ty) (MkC inline) (MkC phases) = rep2 pragSpecInlDName [nm, ty, inline, phases] repPragSpecInst :: Core TH.TypeQ -> DsM (Core TH.DecQ) repPragSpecInst (MkC ty) = rep2 pragSpecInstDName [ty] repPragRule :: Core String -> Core [TH.RuleBndrQ] -> Core TH.ExpQ -> Core TH.ExpQ -> Core TH.Phases -> DsM (Core TH.DecQ) repPragRule (MkC nm) (MkC bndrs) (MkC lhs) (MkC rhs) (MkC phases) = rep2 pragRuleDName [nm, bndrs, lhs, rhs, phases] repPragAnn :: Core TH.AnnTarget -> Core TH.ExpQ -> DsM (Core TH.DecQ) repPragAnn (MkC targ) (MkC e) = rep2 pragAnnDName [targ, e] repTySynInst :: Core TH.Name -> Core TH.TySynEqnQ -> DsM (Core TH.DecQ) repTySynInst (MkC nm) (MkC eqn) = rep2 tySynInstDName [nm, eqn] repDataFamilyD :: Core TH.Name -> Core [TH.TyVarBndr] -> Core (Maybe TH.Kind) -> DsM (Core TH.DecQ) repDataFamilyD (MkC nm) (MkC tvs) (MkC kind) = rep2 dataFamilyDName [nm, tvs, kind] repOpenFamilyD :: Core TH.Name -> Core [TH.TyVarBndr] -> Core TH.FamilyResultSig -> Core (Maybe TH.InjectivityAnn) -> DsM (Core TH.DecQ) repOpenFamilyD (MkC nm) (MkC tvs) (MkC result) (MkC inj) = rep2 openTypeFamilyDName [nm, tvs, result, inj] repClosedFamilyD :: Core TH.Name -> Core [TH.TyVarBndr] -> Core TH.FamilyResultSig -> Core (Maybe TH.InjectivityAnn) -> Core [TH.TySynEqnQ] -> DsM (Core TH.DecQ) repClosedFamilyD (MkC nm) (MkC tvs) (MkC res) (MkC inj) (MkC eqns) = rep2 closedTypeFamilyDName [nm, tvs, res, inj, eqns] repTySynEqn :: Core [TH.TypeQ] -> Core TH.TypeQ -> DsM (Core TH.TySynEqnQ) repTySynEqn (MkC lhs) (MkC rhs) = rep2 tySynEqnName [lhs, rhs] repRoleAnnotD :: Core TH.Name -> Core [TH.Role] -> DsM (Core TH.DecQ) repRoleAnnotD (MkC n) (MkC roles) = rep2 roleAnnotDName [n, roles] repFunDep :: Core [TH.Name] -> Core [TH.Name] -> DsM (Core TH.FunDep) repFunDep (MkC xs) (MkC ys) = rep2 funDepName [xs, ys] repProto :: Name -> Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ) repProto mk_sig (MkC s) (MkC ty) = rep2 mk_sig [s, ty] repCtxt :: Core [TH.PredQ] -> DsM (Core TH.CxtQ) repCtxt (MkC tys) = rep2 cxtName [tys] repDataCon :: Located Name -> HsConDeclDetails Name -> DsM (Core TH.ConQ) repDataCon con details = do con' <- lookupLOcc con -- See Note [Binders and occurrences] repConstr details Nothing [con'] repGadtDataCons :: [Located Name] -> HsConDeclDetails Name -> LHsType Name -> DsM (Core TH.ConQ) repGadtDataCons cons details res_ty = do cons' <- mapM lookupLOcc cons -- See Note [Binders and occurrences] repConstr details (Just res_ty) cons' -- Invariant: -- * for plain H98 data constructors second argument is Nothing and third -- argument is a singleton list -- * for GADTs data constructors second argument is (Just return_type) and -- third argument is a non-empty list repConstr :: HsConDeclDetails Name -> Maybe (LHsType Name) -> [Core TH.Name] -> DsM (Core TH.ConQ) repConstr (PrefixCon ps) Nothing [con] = do arg_tys <- repList bangTypeQTyConName repBangTy ps rep2 normalCName [unC con, unC arg_tys] repConstr (PrefixCon ps) (Just (L _ res_ty)) cons = do arg_tys <- repList bangTypeQTyConName repBangTy ps res_ty' <- repTy res_ty rep2 gadtCName [ unC (nonEmptyCoreList cons), unC arg_tys, unC res_ty'] repConstr (RecCon (L _ ips)) resTy cons = do args <- concatMapM rep_ip ips arg_vtys <- coreList varBangTypeQTyConName args case resTy of Nothing -> rep2 recCName [unC (head cons), unC arg_vtys] Just (L _ res_ty) -> do res_ty' <- repTy res_ty rep2 recGadtCName [unC (nonEmptyCoreList cons), unC arg_vtys, unC res_ty'] where rep_ip (L _ ip) = mapM (rep_one_ip (cd_fld_type ip)) (cd_fld_names ip) rep_one_ip :: LBangType Name -> LFieldOcc Name -> DsM (Core a) rep_one_ip t n = do { MkC v <- lookupOcc (selectorFieldOcc $ unLoc n) ; MkC ty <- repBangTy t ; rep2 varBangTypeName [v,ty] } repConstr (InfixCon st1 st2) Nothing [con] = do arg1 <- repBangTy st1 arg2 <- repBangTy st2 rep2 infixCName [unC arg1, unC con, unC arg2] repConstr (InfixCon {}) (Just _) _ = panic "repConstr: infix GADT constructor should be in a PrefixCon" repConstr _ _ _ = panic "repConstr: invariant violated" ------------ Types ------------------- repTForall :: Core [TH.TyVarBndr] -> Core TH.CxtQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ) repTForall (MkC tvars) (MkC ctxt) (MkC ty) = rep2 forallTName [tvars, ctxt, ty] repTvar :: Core TH.Name -> DsM (Core TH.TypeQ) repTvar (MkC s) = rep2 varTName [s] repTapp :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ) repTapp (MkC t1) (MkC t2) = rep2 appTName [t1, t2] repTapps :: Core TH.TypeQ -> [Core TH.TypeQ] -> DsM (Core TH.TypeQ) repTapps f [] = return f repTapps f (t:ts) = do { f1 <- repTapp f t; repTapps f1 ts } repTSig :: Core TH.TypeQ -> Core TH.Kind -> DsM (Core TH.TypeQ) repTSig (MkC ty) (MkC ki) = rep2 sigTName [ty, ki] repTequality :: DsM (Core TH.TypeQ) repTequality = rep2 equalityTName [] repTPromotedList :: [Core TH.TypeQ] -> DsM (Core TH.TypeQ) repTPromotedList [] = repPromotedNilTyCon repTPromotedList (t:ts) = do { tcon <- repPromotedConsTyCon ; f <- repTapp tcon t ; t' <- repTPromotedList ts ; repTapp f t' } repTLit :: Core TH.TyLitQ -> DsM (Core TH.TypeQ) repTLit (MkC lit) = rep2 litTName [lit] repTWildCard :: DsM (Core TH.TypeQ) repTWildCard = rep2 wildCardTName [] --------- Type constructors -------------- repNamedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ) repNamedTyCon (MkC s) = rep2 conTName [s] repTupleTyCon :: Int -> DsM (Core TH.TypeQ) -- Note: not Core Int; it's easier to be direct here repTupleTyCon i = do dflags <- getDynFlags rep2 tupleTName [mkIntExprInt dflags i] repUnboxedTupleTyCon :: Int -> DsM (Core TH.TypeQ) -- Note: not Core Int; it's easier to be direct here repUnboxedTupleTyCon i = do dflags <- getDynFlags rep2 unboxedTupleTName [mkIntExprInt dflags i] repArrowTyCon :: DsM (Core TH.TypeQ) repArrowTyCon = rep2 arrowTName [] repListTyCon :: DsM (Core TH.TypeQ) repListTyCon = rep2 listTName [] repPromotedDataCon :: Core TH.Name -> DsM (Core TH.TypeQ) repPromotedDataCon (MkC s) = rep2 promotedTName [s] repPromotedTupleTyCon :: Int -> DsM (Core TH.TypeQ) repPromotedTupleTyCon i = do dflags <- getDynFlags rep2 promotedTupleTName [mkIntExprInt dflags i] repPromotedNilTyCon :: DsM (Core TH.TypeQ) repPromotedNilTyCon = rep2 promotedNilTName [] repPromotedConsTyCon :: DsM (Core TH.TypeQ) repPromotedConsTyCon = rep2 promotedConsTName [] ------------ Kinds ------------------- repPlainTV :: Core TH.Name -> DsM (Core TH.TyVarBndr) repPlainTV (MkC nm) = rep2 plainTVName [nm] repKindedTV :: Core TH.Name -> Core TH.Kind -> DsM (Core TH.TyVarBndr) repKindedTV (MkC nm) (MkC ki) = rep2 kindedTVName [nm, ki] repKVar :: Core TH.Name -> DsM (Core TH.Kind) repKVar (MkC s) = rep2 varKName [s] repKCon :: Core TH.Name -> DsM (Core TH.Kind) repKCon (MkC s) = rep2 conKName [s] repKTuple :: Int -> DsM (Core TH.Kind) repKTuple i = do dflags <- getDynFlags rep2 tupleKName [mkIntExprInt dflags i] repKArrow :: DsM (Core TH.Kind) repKArrow = rep2 arrowKName [] repKList :: DsM (Core TH.Kind) repKList = rep2 listKName [] repKApp :: Core TH.Kind -> Core TH.Kind -> DsM (Core TH.Kind) repKApp (MkC k1) (MkC k2) = rep2 appKName [k1, k2] repKApps :: Core TH.Kind -> [Core TH.Kind] -> DsM (Core TH.Kind) repKApps f [] = return f repKApps f (k:ks) = do { f' <- repKApp f k; repKApps f' ks } repKStar :: DsM (Core TH.Kind) repKStar = rep2 starKName [] repKConstraint :: DsM (Core TH.Kind) repKConstraint = rep2 constraintKName [] ---------------------------------------------------------- -- Type family result signature repNoSig :: DsM (Core TH.FamilyResultSig) repNoSig = rep2 noSigName [] repKindSig :: Core TH.Kind -> DsM (Core TH.FamilyResultSig) repKindSig (MkC ki) = rep2 kindSigName [ki] repTyVarSig :: Core TH.TyVarBndr -> DsM (Core TH.FamilyResultSig) repTyVarSig (MkC bndr) = rep2 tyVarSigName [bndr] ---------------------------------------------------------- -- Literals repLiteral :: HsLit -> DsM (Core TH.Lit) repLiteral (HsStringPrim _ bs) = do dflags <- getDynFlags word8_ty <- lookupType word8TyConName let w8s = unpack bs w8s_expr = map (\w8 -> mkCoreConApps word8DataCon [mkWordLit dflags (toInteger w8)]) w8s rep2 stringPrimLName [mkListExpr word8_ty w8s_expr] repLiteral lit = do lit' <- case lit of HsIntPrim _ i -> mk_integer i HsWordPrim _ w -> mk_integer w HsInt _ i -> mk_integer i HsFloatPrim r -> mk_rational r HsDoublePrim r -> mk_rational r HsCharPrim _ c -> mk_char c _ -> return lit lit_expr <- dsLit lit' case mb_lit_name of Just lit_name -> rep2 lit_name [lit_expr] Nothing -> notHandled "Exotic literal" (ppr lit) where mb_lit_name = case lit of HsInteger _ _ _ -> Just integerLName HsInt _ _ -> Just integerLName HsIntPrim _ _ -> Just intPrimLName HsWordPrim _ _ -> Just wordPrimLName HsFloatPrim _ -> Just floatPrimLName HsDoublePrim _ -> Just doublePrimLName HsChar _ _ -> Just charLName HsCharPrim _ _ -> Just charPrimLName HsString _ _ -> Just stringLName HsRat _ _ -> Just rationalLName _ -> Nothing mk_integer :: Integer -> DsM HsLit mk_integer i = do integer_ty <- lookupType integerTyConName return $ HsInteger "" i integer_ty mk_rational :: FractionalLit -> DsM HsLit mk_rational r = do rat_ty <- lookupType rationalTyConName return $ HsRat r rat_ty mk_string :: FastString -> DsM HsLit mk_string s = return $ HsString "" s mk_char :: Char -> DsM HsLit mk_char c = return $ HsChar "" c repOverloadedLiteral :: HsOverLit Name -> DsM (Core TH.Lit) repOverloadedLiteral (OverLit { ol_val = val}) = do { lit <- mk_lit val; repLiteral lit } -- The type Rational will be in the environment, because -- the smart constructor 'TH.Syntax.rationalL' uses it in its type, -- and rationalL is sucked in when any TH stuff is used mk_lit :: OverLitVal -> DsM HsLit mk_lit (HsIntegral _ i) = mk_integer i mk_lit (HsFractional f) = mk_rational f mk_lit (HsIsString _ s) = mk_string s repNameS :: Core String -> DsM (Core TH.Name) repNameS (MkC name) = rep2 mkNameSName [name] --------------- Miscellaneous ------------------- repGensym :: Core String -> DsM (Core (TH.Q TH.Name)) repGensym (MkC lit_str) = rep2 newNameName [lit_str] repBindQ :: Type -> Type -- a and b -> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b)) repBindQ ty_a ty_b (MkC x) (MkC y) = rep2 bindQName [Type ty_a, Type ty_b, x, y] repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a])) repSequenceQ ty_a (MkC list) = rep2 sequenceQName [Type ty_a, list] repUnboundVar :: Core TH.Name -> DsM (Core TH.ExpQ) repUnboundVar (MkC name) = rep2 unboundVarEName [name] ------------ Lists ------------------- -- turn a list of patterns into a single pattern matching a list repList :: Name -> (a -> DsM (Core b)) -> [a] -> DsM (Core [b]) repList tc_name f args = do { args1 <- mapM f args ; coreList tc_name args1 } coreList :: Name -- Of the TyCon of the element type -> [Core a] -> DsM (Core [a]) coreList tc_name es = do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) } coreList' :: Type -- The element type -> [Core a] -> Core [a] coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es )) nonEmptyCoreList :: [Core a] -> Core [a] -- The list must be non-empty so we can get the element type -- Otherwise use coreList nonEmptyCoreList [] = panic "coreList: empty argument" nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs)) coreStringLit :: String -> DsM (Core String) coreStringLit s = do { z <- mkStringExpr s; return(MkC z) } ------------------- Maybe ------------------ -- | Construct Core expression for Nothing of a given type name coreNothing :: Name -- ^ Name of the TyCon of the element type -> DsM (Core (Maybe a)) coreNothing tc_name = do { elt_ty <- lookupType tc_name; return (coreNothing' elt_ty) } -- | Construct Core expression for Nothing of a given type coreNothing' :: Type -- ^ The element type -> Core (Maybe a) coreNothing' elt_ty = MkC (mkNothingExpr elt_ty) -- | Store given Core expression in a Just of a given type name coreJust :: Name -- ^ Name of the TyCon of the element type -> Core a -> DsM (Core (Maybe a)) coreJust tc_name es = do { elt_ty <- lookupType tc_name; return (coreJust' elt_ty es) } -- | Store given Core expression in a Just of a given type coreJust' :: Type -- ^ The element type -> Core a -> Core (Maybe a) coreJust' elt_ty es = MkC (mkJustExpr elt_ty (unC es)) ------------ Literals & Variables ------------------- coreIntLit :: Int -> DsM (Core Int) coreIntLit i = do dflags <- getDynFlags return (MkC (mkIntExprInt dflags i)) coreVar :: Id -> Core TH.Name -- The Id has type Name coreVar id = MkC (Var id) ----------------- Failure ----------------------- notHandledL :: SrcSpan -> String -> SDoc -> DsM a notHandledL loc what doc | isGoodSrcSpan loc = putSrcSpanDs loc $ notHandled what doc | otherwise = notHandled what doc notHandled :: String -> SDoc -> DsM a notHandled what doc = failWithDs msg where msg = hang (text what <+> text "not (yet) handled by Template Haskell") 2 doc
GaloisInc/halvm-ghc
compiler/deSugar/DsMeta.hs
bsd-3-clause
93,749
59
24
28,400
29,477
14,735
14,742
1,583
18
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | Consider this module to be internal, and don't import directly. module Network.Hawk.Internal.Server.Types where import Data.ByteString (ByteString) import Data.Text (Text) import Data.Time.Clock.POSIX (POSIXTime) import Network.HTTP.Types.Method (Method) import GHC.Generics import Data.Default import Network.Hawk.Types -- | The end result of authentication. type AuthResult t = AuthResult' (AuthSuccess t) -- | An intermediate result of authentication. type AuthResult' r = Either AuthFail r -- | Authentication can fail in multiple ways. This type includes the -- information necessary to generate a suitable response for the -- client. In the case of a stale timestamp, the client may try -- another authenticated request. data AuthFail = AuthFailBadRequest String (Maybe HeaderArtifacts) | AuthFailUnauthorized String (Maybe Credentials) (Maybe HeaderArtifacts) | AuthFailStaleTimeStamp String POSIXTime Credentials HeaderArtifacts deriving (Show, Eq) -- | Successful authentication produces a set of credentials and -- "artifacts". Also included in the result is the result of -- 'CredentialsFunc'. data AuthSuccess t = AuthSuccess Credentials HeaderArtifacts t instance Show t => Show (AuthSuccess t) where show (AuthSuccess c a t) = "AuthSuccess " ++ show t instance Eq t => Eq (AuthSuccess t) where AuthSuccess c a t == AuthSuccess d b u = c == d && a == b && t == u -- | The result of an 'AuthSuccess'. authValue :: AuthSuccess t -> t authValue (AuthSuccess _ _ t) = t -- | The error message from an 'AuthFail'. authFailMessage :: AuthFail -> String authFailMessage (AuthFailBadRequest e _) = e authFailMessage (AuthFailUnauthorized e _ _) = e authFailMessage (AuthFailStaleTimeStamp e _ _ _) = e ---------------------------------------------------------------------------- -- | A package of values containing the attributes of a HTTP request -- which are relevant to Hawk authentication. data HawkReq = HawkReq { hrqMethod :: Method , hrqUrl :: ByteString , hrqHost :: ByteString , hrqPort :: Maybe Int , hrqAuthorization :: ByteString , hrqPayload :: Maybe PayloadInfo , hrqBewit :: Maybe ByteString , hrqBewitlessUrl :: ByteString } deriving Show instance Default HawkReq where def = HawkReq "GET" "/" "localhost" Nothing "" Nothing Nothing "" -- | The set of data the server requires for key-based hash -- verification of artifacts. data Credentials = Credentials { scKey :: Key -- ^ Key , scAlgorithm :: HawkAlgo -- ^ HMAC } deriving (Show, Eq, Generic) -- | A user-supplied callback to get credentials from a client -- identifier. type CredentialsFunc m t = ClientId -> m (Either String (Credentials, t)) -- | User-supplied nonce validation function. It should return 'True' -- if the nonce is valid. -- -- Checking nonces can prevent request replay attacks. If the same key -- and nonce have already been seen, then the request can be denied. type NonceFunc = Key -> POSIXTime -> Nonce -> IO Bool -- | The nonce should be a short sequence of random ASCII characters. type Nonce = ByteString
rvl/hsoz
src/Network/Hawk/Internal/Server/Types.hs
bsd-3-clause
3,276
0
10
664
596
340
256
46
1
module Data.ByteString.Lazy ( module ListBased ) where import ListBased
Soostone/string-compat
src/Data/ByteString/Lazy.hs
bsd-3-clause
92
0
4
29
16
11
5
3
0
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-missing-import-lists #-} {-# OPTIONS_GHC -fno-warn-implicit-prelude #-} module Paths_CommonResources ( version, getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getDataFileName, getSysconfDir ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) import Prelude #if defined(VERSION_base) #if MIN_VERSION_base(4,0,0) catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a #else catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a #endif #else catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a #endif catchIO = Exception.catch version :: Version version = Version [0,1,0,0] [] bindir, libdir, dynlibdir, datadir, libexecdir, sysconfdir :: FilePath bindir = "/home/ggunn/DFS/TransactionServer/.stack-work/install/x86_64-linux/lts-7.13/8.0.1/bin" libdir = "/home/ggunn/DFS/TransactionServer/.stack-work/install/x86_64-linux/lts-7.13/8.0.1/lib/x86_64-linux-ghc-8.0.1/CommonResources-0.1.0.0-2hAoDRm32jf136sTU7I7w0" dynlibdir = "/home/ggunn/DFS/TransactionServer/.stack-work/install/x86_64-linux/lts-7.13/8.0.1/lib/x86_64-linux-ghc-8.0.1" datadir = "/home/ggunn/DFS/TransactionServer/.stack-work/install/x86_64-linux/lts-7.13/8.0.1/share/x86_64-linux-ghc-8.0.1/CommonResources-0.1.0.0" libexecdir = "/home/ggunn/DFS/TransactionServer/.stack-work/install/x86_64-linux/lts-7.13/8.0.1/libexec" sysconfdir = "/home/ggunn/DFS/TransactionServer/.stack-work/install/x86_64-linux/lts-7.13/8.0.1/etc" getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "CommonResources_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "CommonResources_libdir") (\_ -> return libdir) getDynLibDir = catchIO (getEnv "CommonResources_dynlibdir") (\_ -> return dynlibdir) getDataDir = catchIO (getEnv "CommonResources_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "CommonResources_libexecdir") (\_ -> return libexecdir) getSysconfDir = catchIO (getEnv "CommonResources_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
Garygunn94/DFS
CommonResources/.stack-work/dist/x86_64-linux/Cabal-1.24.2.0/build/autogen/Paths_CommonResources.hs
bsd-3-clause
2,272
0
10
239
410
238
172
33
1
-- | Module to Provide an ND-Distribution Datatype module EFA.Data.ND.Distribution where newtype Class typ dim a = ND.Data dim a -- A Distribution is often sparsely populated -- A Data.Map is the best datatype -- | Module for randomly spaced ND-data of a Map data Distribution typ dim a b = Distribution (Grid label typ dim a) Map (Class typ dim a) b -- TODO:: Methods to create clever grids and convert between mid and edge {- even :: (P.RealFrac a) => a -> a -> a -> Class a even interval offs x = Class (P.fromIntegral((P.round ((x P.+ offs) P./ interval))::P.Integer) P.* interval P.- offs) class ClassificationVector where midFromEdge :: EdgeVec vec [a] -> MidVec vec [a] edgeFromMid :: MidVec vec [a] -> EdgeVec vec [a] -}
energyflowanalysis/efa-2.1
src/EFA/Data/ND/Cube/Distribution.hs
bsd-3-clause
748
1
8
147
68
44
24
-1
-1
module InputReader where import StringUtils import Data.List.Split import PaymentTracker (Payment(..)) import Category (Category(..), Money) import CategoryConfig contentToPayments :: String -> [Payment] contentToPayments content = map lineToPayment (lines content) lineToPayment :: String -> Payment lineToPayment line = let (val:cat:desc:_) = splitOn comma line paidValue = read val :: Money categ = findCategory cat in Payment { value = paidValue, category = categ, description = desc } findCategory :: String -> Category findCategory cat = let definedCat = filter (\c -> name c == cat) validCategories in if (length definedCat == 0) then others else head definedCat
Sam-Serpoosh/WatchIt
src/InputReader.hs
bsd-3-clause
712
0
13
137
231
127
104
18
2
module Data.Conduit.List.Extra ( isolateWhile , ignoreWhile , takeWhile , dropWhile ) where import Prelude hiding (takeWhile, dropWhile) import qualified Data.Conduit as C import qualified Data.Conduit.List as C -- | Constructs list from upstream values while the predicate holds (and while there are any values left). -- If you want to pipe the values instead of accumulating them, use isolateWhile. -- This function is semantically equivalent to: -- -- > isolateWhile pr =$ consume -- takeWhile :: Monad m => (a -> Bool) -> C.Sink a m [a] takeWhile pr = isolateWhile pr C.=$ C.consume -- | Constructs list from upstream values, discarding them while the predicate holds (and while there are any values left). -- This function is semantically equivalent to: -- -- > takeWhile pr >> return () -- -- This function is consistent with `Data.Conduit.List.drop`, if you want it -- to be consistent with `Data.List.drop` instead use: -- -- > dropWhile pr >> consume -- -- Or alternatively: -- -- > ignoreWhile pr =$ consume -- dropWhile :: Monad m => (a -> Bool) -> C.Sink a m () dropWhile pr = loop where loop = C.await >>= maybe (return ()) (\val -> if pr val then loop else C.leftover val ) -- | Ignores the values from upstream while the predicate holds, after that pipes all the values. Complement to `isolateWhile`. -- Example: -- -- >>> sourceList [1..10] $= ignoreWhile (< 3) $$ consume -- [3,4,5,6,7,8,9,10] ignoreWhile :: Monad m => (a -> Bool) -> C.Conduit a m a ignoreWhile pr = loop where loop = C.await >>= maybe (return ()) (\val -> if pr val then loop else C.leftover val >> C.awaitForever C.yield ) -- | Pipes all the the values from upstream while the predicate holds. Complement to `ignoreWhile`. -- Example: -- -- >>> sourceList [1..10] $= isolateWhile (< 3) $$ consume -- [1, 2] isolateWhile :: Monad m => (a -> Bool) -> C.Conduit a m a isolateWhile pr = loop where loop = C.await >>= maybe (return ()) (\val -> if pr val then C.yield val >> loop else C.leftover val )
Palmik/wai-sockjs
src/Data/Conduit/List/Extra.hs
bsd-3-clause
2,592
0
14
957
427
241
186
28
2
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} module Guesswork.Estimate.Linear where import Data.List import Data.Ord import Data.Serialize import GHC.Generics import Control.Arrow import Control.Applicative import qualified Data.Vector.Unboxed as V import qualified Data.Packed.Matrix as PM import qualified Data.Packed.Vector as PV import qualified Numeric.LinearAlgebra.Algorithms as Algo import qualified Numeric.Container as N import Guesswork.Types import Guesswork.Math.Statistics import qualified Guesswork.Transform as TRANSFORM import Guesswork.Estimate data Linear = Linear Solution TRANSFORM.Operation Trace deriving (Generic,Eq) instance Serialize Linear type Solution = PM.Matrix Double -- FIXME: a quicker way? instance Eq (PM.Matrix Double) where a == b = open a == open b where open = map PV.toList . PM.toRows instance GuessworkEstimator Linear where guessWith (Linear solution op _) = apply solution . TRANSFORM.apply op instance Serialize (PM.Matrix Double) where get = PM.fromRows . map PV.fromList <$> get put = put . map PV.toList . PM.toRows linear :: (Sample a) => TRANSFORM.Transformed a -> Guesswork (Estimated a) linear (TRANSFORM.Separated train test trace) = do let trainFeatures = featureMatrix train trainTruth = PV.fromList . map target $ train solution = solve trainFeatures trainTruth estimates = map (apply solution . features) test truths = map target test samples = test return $ Estimated truths estimates samples (trace ++ ",R=linear") where linear (TRANSFORM.LeaveOneOut samples trace) = do let indices = [0..(length samples - 1)] groups = map (takeBut samples) indices solutions = map (second trainLinear') groups truths = map target samples estimates = map (uncurry apply . second features . flip') solutions return $ Estimated truths estimates samples (trace ++ ",R=linear") where flip' (a,b) = (b,a) trainLinear :: (Sample a) => TRANSFORM.Transformed a -> Guesswork Linear trainLinear (TRANSFORM.OnlyTrain train op trace) = do let solution = trainLinear' train return $ Linear solution op (trace ++ ",R=linear") trainLinear' :: (Sample a) => [a] -> Solution trainLinear' train = let trainFeatures = featureMatrix train trainTruth = PV.fromList . map target $ train in solve trainFeatures trainTruth solve trainFeatures trainTruth = Algo.linearSolveSVD trainFeatures $ PM.fromColumns [trainTruth] featureMatrix :: (Sample a) => [a] -> PM.Matrix Double featureMatrix = PM.fromRows . map (packVector . features) apply :: Solution -> V.Vector Double -> Double apply solution features = let features' = PM.fromRows [packVector features] [estimate] = PV.toList . head . PM.toColumns $ features' `N.mXm` solution in estimate -- | Packs given list to Vector and adds slack(?) variable 1 for determining constant C. packVector :: V.Vector Double -> PV.Vector Double packVector featureV = PV.fromList $ (V.toList featureV) ++[1]
deggis/guesswork
src/Guesswork/Estimate/Linear.hs
bsd-3-clause
3,236
0
14
664
962
504
458
71
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RecordWildCards #-} module PatternRecogn.NeuronalNetworks.Types where import PatternRecogn.Lina as Lina hiding( cond ) import PatternRecogn.Types hiding( cond ) import PatternRecogn.Utils import Data.Foldable as Fold import Control.Monad.Random import Control.Monad import qualified Data.Sequence as Seq --import Control.DeepSeq ----------------------------------------------------------------- -- Types: ----------------------------------------------------------------- -- |represents the whole network -- |list of weight-matrix for every layer -- | columns: weights for one perceptron type ClassificationParam = [Matrix] data NetworkParams = NetworkParams { dims :: NetworkDimensions, outputInterpretation :: OutputInterpretation } data LearningParams = LearningParams { learningP_specificParams :: SpecificLearningParams, learningP_sampleSize :: Maybe Int } data SpecificLearningParams = LearningParamsDefault DefaultLearningParams | LearningParamsSilvaAlmeida SilvaAlmeidaParams | LearningParamsRProp RPropParams data DefaultLearningParams = DefaultLearningParams { learnRate :: R, dampingFactor :: R } defDefaultLearningParams = DefaultLearningParams { learnRate = 0.1, dampingFactor = 0 } data SilvaAlmeidaParams = SilvaAlmeidaParams { silva_accelerateFactor :: R, silva_decelerateFactor :: R } defSilvaAlmeidaParams = SilvaAlmeidaParams { silva_accelerateFactor = 2, silva_decelerateFactor = 0.5 } data RPropParams = RPropParams { rprop_stepMin :: R, rprop_stepMax :: R, rprop_accelerateFactor :: R, rprop_decelerateFactor :: R } defRPropParams = RPropParams { rprop_stepMin = 0.1, rprop_stepMax = 10, rprop_accelerateFactor = 2, rprop_decelerateFactor = 0.5 } type NetworkDimensions = [Int] type TrainingDataInternal_unpacked = [(Vector,Vector)] -- sample, expected output type TrainingDataInternal = Seq.Seq (Vector,Vector) -- sample, expected output randomPermutation :: MonadRandom m => TrainingDataInternal -> m TrainingDataInternal randomPermutation l | Seq.null l = return l | otherwise = do index <- getRandomR (0, Seq.length l - 1) (\rest -> ((Seq.<|) $ ((Seq.index $ l) $ index)) $ rest) <$> randomPermutation (deleteAt index $ l) --(\rest -> ((Seq.<|) $!! ((Seq.index $!! l) $!! index)) $!! rest) <$> randomPermutation (force $ deleteAt index $!! l) deleteAt index l = case Seq.splitAt index l of (x, y) -> x Seq.>< Seq.drop 1 y rotateTrainingData :: Int -> TrainingDataInternal -> TrainingDataInternal rotateTrainingData index = (\(x,y) -> y Seq.>< x) . Seq.splitAt index takeSample :: Int -> TrainingDataInternal -> TrainingDataInternal_unpacked takeSample sampleMaxSize l = Fold.toList $ Seq.take sampleMaxSize l packTrainingData :: TrainingDataInternal_unpacked -> TrainingDataInternal packTrainingData = Seq.fromList unpackTrainingData :: TrainingDataInternal -> [(Vector,Vector)] unpackTrainingData = Fold.toList internalFromTrainingData OutputInterpretation{..} = map (mapToSnd $ labelToOutput) internalFromBundledTrainingData OutputInterpretation{..} = map (mapToSnd $ labelToOutput) . fromBundled data OutputInterpretation = OutputInterpretation { outputToLabel :: Vector -> Label, labelToOutput :: Label -> Vector } data StopCond = StopAfterMaxIt Int | StopIfConverges R | StopIfQualityReached R data StopReason = StopReason_MaxIt Int | StopReason_Converged R Int | StopReason_QualityReached R Int -- | 0 <-> (1,0,0,...); 3 <-> (0,0,0,1,0,...) outputInterpretationMaximum count = OutputInterpretation{ outputToLabel = fromIntegral . Lina.maxIndex, labelToOutput = \lbl -> Lina.fromList $ setElemAt (fromIntegral lbl) 1 $ replicate count 0 } outputInterpretationSingleOutput = OutputInterpretation{ outputToLabel = \x -> case Lina.toList x of [output] -> round output _ -> error "outputInterpretation: error!", labelToOutput = \lbl -> Lina.fromList [fromIntegral lbl] } data TrainingState = TrainingState { nwData_weights :: ClassificationParam, nwData_gradients :: [Matrix], nwData_stepWidths :: [Matrix] --nwData_trainingView :: TrainingDataInternal } initialTrainingState weights = TrainingState{ nwData_weights = weights, nwData_gradients = map (\x -> Lina.konst 0 $ Lina.size x) weights, nwData_stepWidths = map (Lina.konst 0.1 . Lina.size) weights --nwData_trainingView = trainingData } -- | sums up element wise differences paramsDiff newWeights weights = sum $ map (sum . join . toLists . cmap abs) $ zipWith (-) newWeights weights
EsGeh/pattern-recognition
src/PatternRecogn/NeuronalNetworks/Types.hs
bsd-3-clause
4,616
275
13
730
1,171
686
485
130
2
module Network.OpenFlow.Parser.OfpType where import Control.Monad import Data.Word (Word8) import Data.Attoparsec.ByteString (Parser, anyWord8, satisfy, (<?>)) import qualified Network.OpenFlow.Message.OfpType as O ofpType :: Parser O.OfpType ofpType = (<?> "OfpType") $ do ofptM <- fmap fromWord8 $ satisfy isOfpType case ofptM of Just t -> return t Nothing -> mzero fromWord8 :: Word8 -> Maybe O.OfpType fromWord8 = O.ofpType . fromIntegral isOfpType :: Word8 -> Bool isOfpType w = case fromWord8 w of Just _ -> True Nothing -> False
utky/openflow
src/Network/OpenFlow/Parser/OfpType.hs
bsd-3-clause
595
0
11
136
184
101
83
18
2
module Spec.Spec where import Spec.Bitmask import Spec.Command import Spec.Constant import Spec.Enum import Spec.Extension import Spec.Section import Spec.Tag import Spec.Type import Spec.VendorID import Prelude hiding (Enum) -- | The Specification in a format which closely resembles the xml specification data Spec = Spec { sTypes :: [TypeDecl] , sConstants :: [Constant] , sEnums :: [Enum] , sBitmasks :: [Bitmask] , sCommands :: [Command] , sCopyright :: String , sSections :: [Section] , sExtensions :: [Extension] , sTags :: [Tag] , sVendorIDs :: [VendorID] } deriving (Show) getSpecExtensionTags :: Spec -> [String] getSpecExtensionTags spec = (tName <$> sTags spec) ++ (viName <$> sVendorIDs spec)
oldmanmike/vulkan
generate/src/Spec/Spec.hs
bsd-3-clause
884
0
9
280
208
128
80
25
1
module Main where import AUTOSAR -- | Set this flag to @False@ to disable all task assignments. main :: IO () main = do rng <- newTFGen simulateUsingExternal True rng simulinkABSgood1 -- simulateUsingExternal True rng simulinkABSbad1 return ()
josefs/autosar
ARSim/arsim-examples/Examples/ABS.hs
bsd-3-clause
254
0
8
48
49
25
24
7
1
{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, CPP #-} module AWS.EC2.Util ( list , head , each , eachp , wait , count , findTag , sleep , retry ) where import Data.Conduit import qualified Data.Conduit.List as CL import Control.Monad.Trans.Class (MonadTrans, lift) import Prelude hiding (head) import Safe import qualified Control.Concurrent as CC import Control.Monad.IO.Class (liftIO, MonadIO) #if MIN_VERSION_conduit(1,1,0) import Control.Monad.Trans.Resource (MonadBaseControl, MonadResource) #endif import Data.Text (Text) import qualified Data.Text as T import Control.Applicative import Control.Parallel (par) import Data.List (find) import qualified Control.Exception.Lifted as E import AWS.EC2.Internal import AWS.EC2.Types (ResourceTag(resourceTagKey)) list :: Monad m => EC2 m (ResumableSource m a) -> EC2 m [a] list src = do s <- src lift $ s $$+- CL.consume head :: Monad m => EC2 m (ResumableSource m a) -> EC2 m (Maybe a) head src = do s <- src lift $ s $$+- CL.head each :: Monad m => (a -> m b) -> EC2 m (ResumableSource m a) -> EC2 m () each f res = res >>= lift . each' f where each' g rsrc = do (s', ma) <- rsrc $$++ CL.head maybe (return ()) (\a -> g a >> each' g s') ma -- | parallel each eachp :: Monad m => (a -> m b) -> EC2 m (ResumableSource m a) -> EC2 m () eachp f res = res >>= lift . each' f where each' g rsrc = do (s', ma) <- rsrc $$++ CL.head maybe (return ()) (\a -> g a `par` each' g s') ma -- | Count resources. count :: Monad m => EC2 m (ResumableSource m a) -> EC2 m Int count ers = do s <- ers lift $ s $$+- c 0 where c n = await >>= maybe (return n) (const $ c $ n + 1) -- | Wait for condition. -- -- > import AWS.EC2 -- > import AWS.EC2.Types -- > import AWS.EC2.Util (list, wait) -- > -- > waitForAvailable :: (MonadIO m, Functor m) -- > => Text -- ^ ImageId -- > -> EC2 m a -- > waitForAvailable = wait -- > (\img -> imageImageState img == ImageAvailable) -- > (\imgId -> list (describeImages [imgId] [] [] [])) wait :: (MonadIO m, Functor m) => (a -> Bool) -- ^ condition -> (Text -> EC2 m [a]) -- ^ DescribeResources -> Text -- ^ Resource Id -> EC2 m a wait f g rid = do mr <- headMay <$> g rid case mr of Nothing -> fail $ "Resource not found: " ++ T.unpack rid Just r -> if f r then return r else do sleep 5 wait f g rid findTag :: Text -- ^ resourceKey -> [ResourceTag] -- ^ TagSet -> Maybe ResourceTag findTag key tags = find f tags where f t = resourceTagKey t == key sleep :: MonadIO m => Int -> EC2 m () sleep sec = liftIO $ CC.threadDelay $ sec * 1000 * 1000 retry :: forall m a. (MonadBaseControl IO m, MonadResource m) => Int -- ^ sleep count -> Int -- ^ number of retry -> EC2 m a -> EC2 m a retry _ 0 f = f retry sec cnt f = f `E.catch` handler where handler :: E.SomeException -> EC2 m a handler _ = do sleep sec retry sec (cnt - 1) f
IanConnolly/aws-sdk-fork
AWS/EC2/Util.hs
bsd-3-clause
3,180
0
13
935
1,111
587
524
101
3
module CabalIndex ( buildDatabase , queryPackages) where import Control.Monad import System.Directory (renameFile) import System.FilePath ((</>)) import System.Process (readProcess) import Database.HDBC import Database.HDBC.Sqlite3 import qualified Data.List as L {-| Insert packages into table -} populate :: IConnection c => c -> [(String, String)] -> IO () populate conn ps = do stmt <- prepare conn "INSERT INTO packages VALUES (?, ?)" executeMany stmt $ map (\(n,m) -> [toSql n, toSql m]) ps {-| Create table for packages -} createTable :: IConnection c => c -> IO () createTable conn = void $ run conn "CREATE TABLE packages (name VARCHAR(16) PRIMARY KEY, meta VARCHAR(128))" [] {-| Create and populate a new database, replacing the old -} buildDatabase :: FilePath -> String -> IO () buildDatabase dbDir dbName = do -- place tmp file in same dir as db to allow atomic move let tmpDb = dbDir </> dbName ++ "-partial" -- build database in temporary path conn <- connectSqlite3 tmpDb createTable conn populate conn =<< parseCabal -- commit and disconnect commit conn disconnect conn -- move new database over old one renameFile tmpDb $ dbDir </> dbName {-| Query a database, using the output from Cabal -} queryPackages :: FilePath -> String -> IO [(String, String)] queryPackages db term = do conn <- connectSqlite3 db rows <- quickQuery conn "SELECT * FROM packages WHERE name LIKE ?" [toSql $ '%':term++"%"] return $ map (\[n,m] -> (fromSql n :: String, fromSql m :: String)) rows {-| List packages using Cabal and parse the result to (name, meta) -} parseCabal :: IO [(String, String)] parseCabal = go `fmap` lines `fmap` readProcess "cabal" ["list"] [] where go [] = [] go (('*':' ':name):rest) = let (meta, rest') = gm [] rest in (name, L.intercalate "\n" meta) : go rest' go l = error $ "Unexpected cabal output" ++ show l gm m [] = (m, []) gm m (rest@(('*':_):_)) = (m, rest) gm m (x:xs) | L.null x = gm m xs | otherwise = gm (m ++ [x]) xs
brinchj/CabalSearch
CabalIndex.hs
bsd-3-clause
2,129
0
13
512
694
363
331
44
5
module Test.Data.ART.Internal.SortingNetwork where import Control.Monad (join) import qualified Data.Array.IArray as Array import qualified Data.List as List import Data.ART.Internal.Array (Key) import Data.ART.Internal.SortingNetwork import Test.Tasty import qualified Test.Tasty.QuickCheck as QC tests :: [TestTree] tests = [ QC.testProperty "sort4" prop_sort4 , QC.testProperty "sort5" prop_sort5 ] prop_sort4 :: Key -> Key -> Key -> Key -> Bool prop_sort4 a b c d = all (== (keys, values)) . map toArray $ List.permutations [a, b, c, d] where toArray ls = sort4 (Array.listArray (0,3) ls) (Array.listArray (0,3) ls) keys = Array.listArray (0,3) $ List.sort [a, b, c, d] values = Array.listArray (0,3) $ List.sort [a, b, c, d] prop_sort5 :: Key -> Key -> Key -> Key -> Key -> Bool prop_sort5 a b c d e = all (== (keys, values)) . map toArray $ List.permutations [a, b, c, d, e] where toArray ls = sort5 (Array.listArray (0,4) ls) (Array.listArray (0,4) ls) keys = Array.listArray (0,4) $ List.sort [a, b, c, d, e] values = Array.listArray (0,4) $ List.sort [a, b, c, d, e]
TikhonJelvis/adaptive-radix-trees
test/Test/Data/ART/Internal/SortingNetwork.hs
bsd-3-clause
1,247
0
10
341
511
292
219
23
1
{-# LANGUAGE ViewPatterns #-} -- | Generate Haskell-syntax output complete with hyperlinks to Haddock docs module Code(code) where import Data.Char import Control.Monad.Extra import System.Directory import Data.List.Extra import Data.Maybe import Text.HTML.TagSoup -- | Given the location of the haddock --hoogle output, generate something that takes code blocks -- to HTML pieces. code :: FilePath -> IO (String -> [Tag String]) code file = do unlessM (doesFileExist file) $ fail "You must run cabal haddock --hoogle to generate the necessary info first" r <- resolve file pure $ format r resolve :: FilePath -> IO (String -> [Tag String]) resolve file = do src <- readFile file let info = catMaybes $ snd $ mapAccumL f "" $ map words $ lines src pure $ \x -> fromMaybe [TagText x] $ lookup x info where f _ ("module":modu:_) = (fix modu, Just (modu, link modu "" "" modu)) f modu (('(':x):rest) = f modu $ init x : rest f modu (('[':x):rest) = f modu $ init x : rest f modu (x:"::":_) | x /= "*>" = (modu, Just (x, link modu "v" x x)) f modu (key:x:_) | key `elem` ["type","data","newtype","class"] , x `notElem` ["Show","Typeable","Binary","Eq","Hashable","NFData"] = (modu, Just (x, link modu "t" x x)) f modu _ = (modu, Nothing) fix "Development.Shake.Command" = "Development.Shake" fix x = x link modu tag name inner = [TagOpen "a" [("href",url)], TagText inner, TagClose "a"] where url = "https://hackage.haskell.org/package/shake/docs/" ++ intercalate "-" (wordsBy (== '.') modu) ++ ".html" ++ (if name == "" then "" else "#" ++ tag ++ ":" ++ concatMap g name) g x | x `elem` "%*-<>/&?=|~" = "-" ++ show (ord x) ++ "-" g x = [x] format :: (String -> [Tag String]) -> String -> [Tag String] format txt x | x == "\\" || any (`isPrefixOf` x) ["#!","3m","shake ","cabal "] = [TagText x] format txt xs = concatMap f $ lexer xs where f x | x `elem` ["import","do","let"] = spn "key" x f [x] | x `elem` "(){}[]\\=|" = spn "sym" [x] f x | x `elem` ["->","::","<-"] = spn "sym" x f (x:xs) | x `elem` "\"\'" = spn "str" $ x:xs f x = txt x spn cls x = [TagOpen "span" [("class",cls)], TagText x, TagClose "span"] lexer :: String -> [String] lexer [] = [] lexer (stripPrefix "Development" -> Just x) = let (a,b) = span (\x -> isAlpha x || x == '.') x in ("Development" ++ a) : lexer b lexer x@(c:_) | isSpace c = let (a,b) = span isSpace x in a : lexer b lexer (lex -> [(a,b)]) = a : lexer b lexer (x:xs) = [x] : lexer xs
ndmitchell/shake
website/Code.hs
bsd-3-clause
2,710
0
15
735
1,204
624
580
54
9
module Main where import ABS (a:b:tmp:n:n1:res:the_end:_)=[1..] main_ :: Method main_ [] this wb k = Assign n (Val (I 18)) $ Assign a (Val (I 1)) $ Assign b (Val (I 3)) $ Assign tmp (Val (I 2)) $ Assign res (Sync hanoi [a,b,tmp,n]) k hanoi :: Method hanoi [a,b,tmp,n] this wb k = Assign res (Val (I 0)) $ If (IGT (I n) (I 0)) (\ k' -> Assign n1 (Val (Param (n-1))) $ Assign res (Sync hanoi [a,tmp,b,n1]) $ Assign n1 (Val (Param (n-1))) $ Assign res (Sync hanoi [tmp,b,a,n1]) k') Skip $ Return res wb k -- dummy main :: IO () main = printHeap =<< run 9999999999999999 main_ the_end
abstools/abs-haskell-formal
benchmarks/6_hanoi/progs/18.hs
bsd-3-clause
653
0
19
185
416
216
200
22
1
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : $Header$ Description : Abstract syntax for propositional logic extended with QBFs Copyright : (c) Jonathan von Schroeder, DFKI GmbH 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : <[email protected]> Stability : experimental Portability : portable Definition of abstract syntax for propositional logic extended with QBFs Ref. <http://en.wikipedia.org/wiki/Propositional_logic> <http://www.voronkov.com/lics.cgi> -} module QBF.AS_BASIC_QBF ( FORMULA (..) -- datatype for Propositional Formulas , BASICITEMS (..) -- Items of a Basic Spec , BASICSPEC (..) -- Basic Spec , SYMBITEMS (..) -- List of symbols , SYMB (..) -- Symbols , SYMBMAPITEMS (..) -- Symbol map , SYMBORMAP (..) -- Symbol or symbol map , PREDITEM (..) -- Predicates , isPrimForm , ID (..) ) where import Common.Id as Id import Common.Doc import Common.DocUtils import Common.Keywords import Common.AS_Annotation as AS_Anno import Data.Data import Data.Maybe (isJust) import qualified Data.List as List -- DrIFT command {-! global: GetRange !-} -- | predicates = propositions data PREDITEM = PredItem [Id.Token] Id.Range deriving (Show, Typeable, Data) newtype BASICSPEC = BasicSpec [AS_Anno.Annoted BASICITEMS] deriving (Show, Typeable, Data) data BASICITEMS = PredDecl PREDITEM | AxiomItems [AS_Anno.Annoted FORMULA] -- pos: dots deriving (Show, Typeable, Data) -- | Datatype for QBF formulas data FORMULA = FalseAtom Id.Range -- pos: "False | TrueAtom Id.Range -- pos: "True" | Predication Id.Token -- pos: Propositional Identifiers | Negation FORMULA Id.Range -- pos: not | Conjunction [FORMULA] Id.Range -- pos: "/\"s | Disjunction [FORMULA] Id.Range -- pos: "\/"s | Implication FORMULA FORMULA Id.Range -- pos: "=>" | Equivalence FORMULA FORMULA Id.Range -- pos: "<=>" | ForAll [Id.Token] FORMULA Id.Range | Exists [Id.Token] FORMULA Id.Range deriving (Show, Ord, Typeable, Data) data ID = ID Id.Token (Maybe Id.Token) deriving (Typeable, Data) instance Eq ID where ID t1 (Just t2) == ID t3 (Just t4) = ((t1 == t3) && (t2 == t4)) || ((t2 == t3) && (t1 == t4)) ID t1 Nothing == ID t2 t3 = (t1 == t2) || (Just t1 == t3) ID _ (Just _) == ID _ Nothing = False {- two QBFs are equivalent if bound variables can be renamed such that the QBFs are equal -} qbfMakeEqual :: Maybe [ID] -> FORMULA -> [Id.Token] -> FORMULA -> [Id.Token] -> Maybe [ID] qbfMakeEqual (Just ids) f ts f1 ts1 = if length ts /= length ts1 then Nothing else case (f, f1) of (Predication t, Predication t1) | t == t1 -> Just ids | t `elem` ts && t1 `elem` ts1 -> let tt1 = ID t (Just t1) in if tt1 `elem` ids then Just ids else if ID t Nothing `notElem` ids && ID t1 Nothing `notElem` ids then Just (tt1 : ids) else Nothing | otherwise -> Nothing (Negation f_ _, Negation f1_ _) -> qbfMakeEqual (Just ids) f_ ts f1_ ts1 (Conjunction (f_ : fs) _, Conjunction (f1_ : fs1) _) -> if length fs /= length fs1 then Nothing else case r of Nothing -> Nothing _ -> qbfMakeEqual r (Conjunction fs nullRange) ts (Conjunction fs1 nullRange) ts1 where r = qbfMakeEqual (Just ids) f_ ts f1_ ts1 (Disjunction fs r, Disjunction fs1 r1) -> qbfMakeEqual (Just ids) (Conjunction fs r) ts (Conjunction fs1 r1) ts1 (Implication f_ f1_ _, Implication f2 f3 _) -> case r of Nothing -> Nothing _ -> qbfMakeEqual r f1_ ts f3 ts1 where r = qbfMakeEqual (Just ids) f_ ts f2 ts1 (Equivalence f_ f1_ r1, Equivalence f2 f3 _) -> qbfMakeEqual (Just ids) (Implication f_ f1_ r1) ts (Implication f2 f3 r1) ts1 (ForAll ts_ f_ _, ForAll ts1_ f1_ _) -> case r of Nothing -> Nothing (Just ids_) -> Just (ids ++ filter (\ (ID x my) -> let Just y = my in (x `elem` ts_ && y `notElem` ts1_) || (x `elem` ts1_ && y `notElem` ts_)) d) where d = ids_ List.\\ ids where r = qbfMakeEqual (Just ids) f_ (ts ++ ts_) f1_ (ts1 ++ ts1_) (Exists ts_ f_ r, Exists ts1_ f1_ r1) -> qbfMakeEqual (Just ids) (Exists ts_ f_ r) ts (Exists ts1_ f1_ r1) ts1 (_1, _2) -> Nothing qbfMakeEqual Nothing _ _ _ _ = Nothing -- ranges are always equal (see Common/Id.hs) - thus they can be ignored instance Eq FORMULA where FalseAtom _ == FalseAtom _ = True TrueAtom _ == TrueAtom _ = True Predication t == Predication t1 = t == t1 Negation f _ == Negation f1 _ = f == f1 Conjunction xs _ == Conjunction xs1 _ = xs == xs1 Disjunction xs _ == Disjunction xs1 _ = xs == xs1 Implication f f1 _ == Implication f2 f3 _ = (f == f2) && (f1 == f3) Equivalence f f1 _ == Equivalence f2 f3 _ = (f == f2) && (f1 == f3) ForAll ts f _ == ForAll ts1 f1 _ = isJust (qbfMakeEqual (Just []) f ts f1 ts1) Exists ts f _ == Exists ts1 f1 _ = isJust (qbfMakeEqual (Just []) f ts f1 ts1) _ == _ = False data SYMBITEMS = SymbItems [SYMB] Id.Range -- pos: SYMB_KIND, commas deriving (Show, Eq, Ord, Typeable, Data) newtype SYMB = SymbId Id.Token -- pos: colon deriving (Show, Eq, Ord, Typeable, Data) data SYMBMAPITEMS = SymbMapItems [SYMBORMAP] Id.Range -- pos: SYMB_KIND, commas deriving (Show, Eq, Ord, Typeable, Data) data SYMBORMAP = Symb SYMB | SymbMap SYMB SYMB Id.Range -- pos: "|->" deriving (Show, Eq, Ord, Typeable, Data) -- All about pretty printing we chose the easy way here :) instance Pretty FORMULA where pretty = printFormula instance Pretty BASICSPEC where pretty = printBasicSpec instance Pretty SYMB where pretty = printSymbol instance Pretty SYMBITEMS where pretty = printSymbItems instance Pretty SYMBMAPITEMS where pretty = printSymbMapItems instance Pretty BASICITEMS where pretty = printBasicItems instance Pretty SYMBORMAP where pretty = printSymbOrMap instance Pretty PREDITEM where pretty = printPredItem isPrimForm :: FORMULA -> Bool isPrimForm f = case f of TrueAtom _ -> True FalseAtom _ -> True Predication _ -> True Negation _ _ -> True _ -> False -- Pretty printing for formulas printFormula :: FORMULA -> Doc printFormula frm = let ppf p f = (if p f then id else parens) $ printFormula f isJunctForm f = case f of Implication {} -> False Equivalence {} -> False ForAll {} -> False Exists {} -> False _ -> True in case frm of FalseAtom _ -> text falseS TrueAtom _ -> text trueS Predication x -> pretty x Negation f _ -> notDoc <+> ppf isPrimForm f Conjunction xs _ -> sepByArbitrary andDoc $ map (ppf isPrimForm) xs Disjunction xs _ -> sepByArbitrary orDoc $ map (ppf isPrimForm) xs Implication x y _ -> ppf isJunctForm x <+> implies <+> ppf isJunctForm y Equivalence x y _ -> ppf isJunctForm x <+> equiv <+> ppf isJunctForm y ForAll xs y _ -> forallDoc <+> sepByArbitrary comma (map pretty xs) <+> space <+> ppf isJunctForm y Exists xs y _ -> exists <+> sepByArbitrary comma (map pretty xs) <+> space <+> ppf isJunctForm y sepByArbitrary :: Doc -> [Doc] -> Doc sepByArbitrary d = fsep . prepPunctuate (d <> space) printPredItem :: PREDITEM -> Doc printPredItem (PredItem xs _) = fsep $ map pretty xs printBasicSpec :: BASICSPEC -> Doc printBasicSpec (BasicSpec xs) = vcat $ map pretty xs printBasicItems :: BASICITEMS -> Doc printBasicItems (AxiomItems xs) = vcat $ map pretty xs printBasicItems (PredDecl x) = pretty x printSymbol :: SYMB -> Doc printSymbol (SymbId sym) = pretty sym printSymbItems :: SYMBITEMS -> Doc printSymbItems (SymbItems xs _) = fsep $ map pretty xs printSymbOrMap :: SYMBORMAP -> Doc printSymbOrMap (Symb sym) = pretty sym printSymbOrMap (SymbMap source dest _) = pretty source <+> mapsto <+> pretty dest printSymbMapItems :: SYMBMAPITEMS -> Doc printSymbMapItems (SymbMapItems xs _) = fsep $ map pretty xs
mariefarrell/Hets
QBF/AS_BASIC_QBF.der.hs
gpl-2.0
8,500
6
22
2,411
2,478
1,354
1,124
179
16
{-| Module : IRTS.Lang Description : Internal representation of Idris' constructs. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE DeriveDataTypeable, DeriveFunctor, DeriveGeneric, FlexibleContexts, PatternGuards #-} module IRTS.Lang where import Idris.Core.CaseTree import Idris.Core.TT import Control.Applicative hiding (Const) import Control.Monad.State hiding (lift) import Data.Data (Data) import Data.List import Data.Typeable (Typeable) import Debug.Trace import GHC.Generics (Generic) data Endianness = Native | BE | LE deriving (Show, Eq) data LVar = Loc Int | Glob Name deriving (Show, Eq) -- ASSUMPTION: All variable bindings have unique names here -- Constructors commented as lifted are not present in the LIR provided to the different backends. data LExp = LV LVar | LApp Bool LExp [LExp] -- True = tail call | LLazyApp Name [LExp] -- True = tail call | LLazyExp LExp -- lifted out before compiling | LForce LExp -- make sure Exp is evaluted | LLet Name LExp LExp -- name just for pretty printing | LLam [Name] LExp -- lambda, lifted out before compiling | LProj LExp Int -- projection | LCon (Maybe LVar) -- Location to reallocate, if available Int Name [LExp] | LCase CaseType LExp [LAlt] | LConst Const | LForeign FDesc -- Function descriptor (usually name as string) FDesc -- Return type descriptor [(FDesc, LExp)] -- first LExp is the FFI type description | LOp PrimFn [LExp] | LNothing | LError String deriving Eq data FDesc = FCon Name | FStr String | FUnknown | FIO FDesc | FApp Name [FDesc] deriving (Show, Eq) data Export = ExportData FDesc -- Exported data descriptor (usually string) | ExportFun Name -- Idris name FDesc -- Exported function descriptor FDesc -- Return type descriptor [FDesc] -- Argument types deriving (Show, Eq) data ExportIFace = Export Name -- FFI descriptor String -- interface file [Export] deriving (Show, Eq) -- Primitive operators. Backends are not *required* to implement all -- of these, but should report an error if they are unable data PrimFn = LPlus ArithTy | LMinus ArithTy | LTimes ArithTy | LUDiv IntTy | LSDiv ArithTy | LURem IntTy | LSRem ArithTy | LAnd IntTy | LOr IntTy | LXOr IntTy | LCompl IntTy | LSHL IntTy | LLSHR IntTy | LASHR IntTy | LEq ArithTy | LLt IntTy | LLe IntTy | LGt IntTy | LGe IntTy | LSLt ArithTy | LSLe ArithTy | LSGt ArithTy | LSGe ArithTy | LSExt IntTy IntTy | LZExt IntTy IntTy | LTrunc IntTy IntTy | LStrConcat | LStrLt | LStrEq | LStrLen | LIntFloat IntTy | LFloatInt IntTy | LIntStr IntTy | LStrInt IntTy | LFloatStr | LStrFloat | LChInt IntTy | LIntCh IntTy | LBitCast ArithTy ArithTy -- Only for values of equal width | LFExp | LFLog | LFSin | LFCos | LFTan | LFASin | LFACos | LFATan | LFSqrt | LFFloor | LFCeil | LFNegate | LStrHead | LStrTail | LStrCons | LStrIndex | LStrRev | LStrSubstr | LReadStr | LWriteStr -- system info | LSystemInfo | LFork | LPar -- evaluate argument anywhere, possibly on another -- core or another machine. 'id' is a valid implementation | LExternal Name | LCrash | LNoOp deriving (Show, Eq, Generic) -- Supported target languages for foreign calls data FCallType = FStatic | FObject | FConstructor deriving (Show, Eq) data FType = FArith ArithTy | FFunction | FFunctionIO | FString | FUnit | FPtr | FManagedPtr | FCData | FAny deriving (Show, Eq) -- FIXME: Why not use this for all the IRs now? data LAlt' e = LConCase Int Name [Name] e | LConstCase Const e | LDefaultCase e deriving (Show, Eq, Functor, Data, Typeable) type LAlt = LAlt' LExp data LDecl = LFun [LOpt] Name [Name] LExp -- options, name, arg names, def | LConstructor Name Int Int -- constructor name, tag, arity deriving (Show, Eq) type LDefs = Ctxt LDecl data LOpt = Inline | NoInline deriving (Show, Eq) addTags :: Int -> [(Name, LDecl)] -> (Int, [(Name, LDecl)]) addTags i ds = tag i ds [] where tag i ((n, LConstructor n' (-1) a) : as) acc = tag (i + 1) as ((n, LConstructor n' i a) : acc) tag i ((n, LConstructor n' t a) : as) acc = tag i as ((n, LConstructor n' t a) : acc) tag i (x : as) acc = tag i as (x : acc) tag i [] acc = (i, reverse acc) data LiftState = LS Name Int [(Name, LDecl)] lname (NS n x) i = NS (lname n i) x lname (UN n) i = MN i n lname x i = sMN i (showCG x ++ "_lam") liftAll :: [(Name, LDecl)] -> [(Name, LDecl)] liftAll xs = concatMap (\ (x, d) -> lambdaLift x d) xs lambdaLift :: Name -> LDecl -> [(Name, LDecl)] lambdaLift n (LFun opts _ args e) = let (e', (LS _ _ decls)) = runState (lift args e) (LS n 0 []) in (n, LFun opts n args e') : decls lambdaLift n x = [(n, x)] getNextName :: State LiftState Name getNextName = do LS n i ds <- get put (LS n (i + 1) ds) return (lname n i) addFn :: Name -> LDecl -> State LiftState () addFn fn d = do LS n i ds <- get put (LS n i ((fn, d) : ds)) lift :: [Name] -> LExp -> State LiftState LExp lift env (LV v) = return (LV v) -- Lifting happens before these can exist... lift env (LApp tc (LV (Glob n)) args) = do args' <- mapM (lift env) args return (LApp tc (LV (Glob n)) args') lift env (LApp tc f args) = do f' <- lift env f fn <- getNextName addFn fn (LFun [Inline] fn env f') args' <- mapM (lift env) args return (LApp tc (LV (Glob fn)) (map (LV . Glob) env ++ args')) lift env (LLazyApp n args) = do args' <- mapM (lift env) args return (LLazyApp n args') lift env (LLazyExp (LConst c)) = return (LConst c) -- lift env (LLazyExp (LApp tc (LV (Glob f)) args)) -- = lift env (LLazyApp f args) lift env (LLazyExp e) = do e' <- lift env e let usedArgs = nub $ usedIn env e' fn <- getNextName addFn fn (LFun [NoInline] fn usedArgs e') return (LLazyApp fn (map (LV . Glob) usedArgs)) lift env (LForce e) = do e' <- lift env e return (LForce e') lift env (LLet n v e) = do v' <- lift env v e' <- lift (env ++ [n]) e return (LLet n v' e') lift env (LLam args e) = do e' <- lift (env ++ args) e let usedArgs = nub $ usedIn env e' fn <- getNextName addFn fn (LFun [Inline] fn (usedArgs ++ args) e') return (LApp False (LV (Glob fn)) (map (LV . Glob) usedArgs)) lift env (LProj t i) = do t' <- lift env t return (LProj t' i) lift env (LCon loc i n args) = do args' <- mapM (lift env) args return (LCon loc i n args') lift env (LCase up e alts) = do alts' <- mapM liftA alts e' <- lift env e return (LCase up e' alts') where liftA (LConCase i n args e) = do e' <- lift (env ++ args) e return (LConCase i n args e') liftA (LConstCase c e) = do e' <- lift env e return (LConstCase c e') liftA (LDefaultCase e) = do e' <- lift env e return (LDefaultCase e') lift env (LConst c) = return (LConst c) lift env (LForeign t s args) = do args' <- mapM (liftF env) args return (LForeign t s args') where liftF env (t, e) = do e' <- lift env e return (t, e') lift env (LOp f args) = do args' <- mapM (lift env) args return (LOp f args') lift env (LError str) = return $ LError str lift env LNothing = return LNothing allocUnique :: LDefs -> (Name, LDecl) -> (Name, LDecl) allocUnique defs p@(n, LConstructor _ _ _) = p allocUnique defs (n, LFun opts fn args e) = let e' = evalState (findUp e) [] in (n, LFun opts fn args e') where -- Keep track of 'updatable' names in the state, i.e. names whose heap -- entry may be reused, along with the arity which was there findUp :: LExp -> State [(Name, Int)] LExp findUp (LApp t (LV (Glob n)) as) | Just (LConstructor _ i ar) <- lookupCtxtExact n defs, ar == length as = findUp (LCon Nothing i n as) findUp (LV (Glob n)) | Just (LConstructor _ i 0) <- lookupCtxtExact n defs = return $ LCon Nothing i n [] -- nullary cons are global, no need to update findUp (LApp t f as) = LApp t <$> findUp f <*> mapM findUp as findUp (LLazyApp n as) = LLazyApp n <$> mapM findUp as findUp (LLazyExp e) = LLazyExp <$> findUp e findUp (LForce e) = LForce <$> findUp e -- use assumption that names are unique! findUp (LLet n val sc) = LLet n <$> findUp val <*> findUp sc findUp (LLam ns sc) = LLam ns <$> findUp sc findUp (LProj e i) = LProj <$> findUp e <*> return i findUp (LCon (Just l) i n es) = LCon (Just l) i n <$> mapM findUp es findUp (LCon Nothing i n es) = do avail <- get v <- findVar [] avail (length es) LCon v i n <$> mapM findUp es findUp (LForeign t s es) = LForeign t s <$> mapM (\ (t, e) -> do e' <- findUp e return (t, e')) es findUp (LOp o es) = LOp o <$> mapM findUp es findUp (LCase Updatable e@(LV (Glob n)) as) = LCase Updatable e <$> mapM (doUpAlt n) as findUp (LCase t e as) = LCase t <$> findUp e <*> mapM findUpAlt as findUp t = return t findUpAlt (LConCase i t args rhs) = do avail <- get rhs' <- findUp rhs put avail return $ LConCase i t args rhs' findUpAlt (LConstCase i rhs) = LConstCase i <$> findUp rhs findUpAlt (LDefaultCase rhs) = LDefaultCase <$> findUp rhs doUpAlt n (LConCase i t args rhs) = do avail <- get put ((n, length args) : avail) rhs' <- findUp rhs put avail return $ LConCase i t args rhs' doUpAlt n (LConstCase i rhs) = LConstCase i <$> findUp rhs doUpAlt n (LDefaultCase rhs) = LDefaultCase <$> findUp rhs findVar _ [] i = return Nothing findVar acc ((n, l) : ns) i | l == i = do put (reverse acc ++ ns) return (Just (Glob n)) findVar acc (n : ns) i = findVar (n : acc) ns i -- Return variables in list which are used in the expression usedArg env n | n `elem` env = [n] | otherwise = [] usedIn :: [Name] -> LExp -> [Name] usedIn env (LV (Glob n)) = usedArg env n usedIn env (LApp _ e args) = usedIn env e ++ concatMap (usedIn env) args usedIn env (LLazyApp n args) = concatMap (usedIn env) args ++ usedArg env n usedIn env (LLazyExp e) = usedIn env e usedIn env (LForce e) = usedIn env e usedIn env (LLet n v e) = usedIn env v ++ usedIn (env \\ [n]) e usedIn env (LLam ns e) = usedIn (env \\ ns) e usedIn env (LCon v i n args) = let rest = concatMap (usedIn env) args in case v of Nothing -> rest Just (Glob n) -> usedArg env n ++ rest usedIn env (LProj t i) = usedIn env t usedIn env (LCase up e alts) = usedIn env e ++ concatMap (usedInA env) alts where usedInA env (LConCase i n ns e) = usedIn env e usedInA env (LConstCase c e) = usedIn env e usedInA env (LDefaultCase e) = usedIn env e usedIn env (LForeign _ _ args) = concatMap (usedIn env) (map snd args) usedIn env (LOp f args) = concatMap (usedIn env) args usedIn env _ = [] lsubst :: Name -> LExp -> LExp -> LExp lsubst n new (LV (Glob x)) | n == x = new lsubst n new (LApp t e args) = let e' = lsubst n new e args' = map (lsubst n new) args in LApp t e' args' lsubst n new (LLazyApp fn args) = let args' = map (lsubst n new) args in LLazyApp fn args' lsubst n new (LLazyExp e) = LLazyExp (lsubst n new e) lsubst n new (LForce e) = LForce (lsubst n new e) lsubst n new (LLet v val sc) = LLet v (lsubst n new val) (lsubst n new sc) lsubst n new (LLam ns sc) = LLam ns (lsubst n new sc) lsubst n new (LProj e i) = LProj (lsubst n new e) i lsubst n new (LCon lv t cn args) = let args' = map (lsubst n new) args in LCon lv t cn args' lsubst n new (LOp op args) = let args' = map (lsubst n new) args in LOp op args' lsubst n new (LForeign fd rd args) = let args' = map (\(d, a) -> (d, lsubst n new a)) args in LForeign fd rd args' lsubst n new (LCase t e alts) = let e' = lsubst n new e alts' = map (fmap (lsubst n new)) alts in LCase t e' alts' lsubst n new tm = tm instance Show LExp where show e = show' [] "" e where show' env ind (LV (Loc i)) = env!!i show' env ind (LV (Glob n)) = show n show' env ind (LLazyApp e args) = show e ++ "|(" ++ showSep ", " (map (show' env ind) args) ++")" show' env ind (LApp _ e args) = show' env ind e ++ "(" ++ showSep ", " (map (show' env ind) args) ++")" show' env ind (LLazyExp e) = "lazy{ " ++ show' env ind e ++ " }" show' env ind (LForce e) = "force{ " ++ show' env ind e ++ " }" show' env ind (LLet n v e) = "let " ++ show n ++ " = " ++ show' env ind v ++ " in " ++ show' (env ++ [show n]) ind e show' env ind (LLam args e) = "\\ " ++ showSep "," (map show args) ++ " => " ++ show' (env ++ (map show args)) ind e show' env ind (LProj t i) = show t ++ "!" ++ show i show' env ind (LCon loc i n args) = atloc loc ++ show n ++ "(" ++ showSep ", " (map (show' env ind) args) ++ ")" where atloc Nothing = "" atloc (Just l) = "@" ++ show (LV l) ++ ":" show' env ind (LCase up e alts) = "case" ++ update ++ show' env ind e ++ " of \n" ++ fmt alts where update = case up of Shared -> " " Updatable -> "! " fmt [] = "" fmt [alt] = "\t" ++ ind ++ "| " ++ showAlt env (ind ++ " ") alt fmt (alt:as) = "\t" ++ ind ++ "| " ++ showAlt env (ind ++ ". ") alt ++ "\n" ++ fmt as show' env ind (LConst c) = show c show' env ind (LForeign ty n args) = concat [ "foreign{ " , show n ++ "(" , showSep ", " (map (\(ty,x) -> show' env ind x ++ " : " ++ show ty) args) , ") : " , show ty , " }" ] show' env ind (LOp f args) = show f ++ "(" ++ showSep ", " (map (show' env ind) args) ++ ")" show' env ind (LError str) = "error " ++ show str show' env ind LNothing = "____" showAlt env ind (LConCase _ n args e) = show n ++ "(" ++ showSep ", " (map show args) ++ ") => " ++ show' env ind e showAlt env ind (LConstCase c e) = show c ++ " => " ++ show' env ind e showAlt env ind (LDefaultCase e) = "_ => " ++ show' env ind e
mpkh/Idris-dev
src/IRTS/Lang.hs
bsd-3-clause
16,317
0
17
6,069
6,168
3,109
3,059
316
22
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE Rank2Types #-} import BinTerm import Data.ByteString.Lazy.Char8 (ByteString, unpack) import Text.Syntax.Check.Attoparsec.ByteString (printParseIsoByteStringChar8) import Text.Syntax.Printer.ByteString(runAsPrinterChar8) exprPPIso :: ByteString -> Either String Exp exprPPIso = printParseIsoByteStringChar8 expr programPPIso :: ByteString -> Either String Program programPPIso = printParseIsoByteStringChar8 program showResult :: BinSyntax a -> Either String a -> String showResult syn = d where d (Right r) = "Good isomorphism syntax:\n" ++ unpack (fromRight (runAsPrinterChar8 syn r)) ++ "\n" d (Left e) = e fromRight (Right r) = r main :: IO () main = mapM_ putStrLn (map (showResult expr . exprPPIso ) allExpTests ++ map (showResult program . programPPIso) allProgTests)
khibino/haskell-invertible-syntax-attoparsec
example/bytestringLazy.hs
bsd-3-clause
877
0
13
159
245
129
116
20
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | Cache information about previous builds module Stack.Build.Cache ( tryGetBuildCache , tryGetConfigCache , tryGetCabalMod , getInstalledExes , tryGetFlagCache , deleteCaches , markExeInstalled , markExeNotInstalled , writeFlagCache , writeBuildCache , writeConfigCache , writeCabalMod , setTestSuccess , unsetTestSuccess , checkTestSuccess , writePrecompiledCache , readPrecompiledCache -- Exported for testing , BuildCache(..) ) where import Control.DeepSeq (NFData) import Control.Exception.Enclosed (handleIO, tryAnyDeep) import Control.Monad (liftM) import Control.Monad.Catch (MonadThrow, MonadCatch) import Control.Monad.IO.Class import Control.Monad.Logger (MonadLogger, logDebug) import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Control (MonadBaseControl) import qualified Crypto.Hash.SHA256 as SHA256 import Data.Binary (Binary (..)) import qualified Data.Binary as Binary import Data.Binary.Tagged (HasStructuralInfo, HasSemanticVersion) import qualified Data.Binary.Tagged as BinaryTagged import qualified Data.ByteString.Base16 as B16 import qualified Data.ByteString.Base64.URL as B64URL import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy as LBS import Data.Foldable (forM_) import Data.Map (Map) import qualified Data.Map as M import Data.Maybe (fromMaybe, mapMaybe) import Data.Monoid ((<>)) import Data.Set (Set) import qualified Data.Set as Set import qualified Data.Store as Store import Data.Store.VersionTagged import Data.Text (Text) import qualified Data.Text as T import Data.Traversable (forM) import Path import Path.IO import Stack.Constants import Stack.Types.Build import Stack.Types.Compiler import Stack.Types.Config import Stack.Types.GhcPkgId import Stack.Types.Package import Stack.Types.PackageIdentifier import Stack.Types.Version import qualified System.FilePath as FilePath -- | Directory containing files to mark an executable as installed exeInstalledDir :: (MonadReader env m, HasEnvConfig env, MonadThrow m) => InstallLocation -> m (Path Abs Dir) exeInstalledDir Snap = (</> $(mkRelDir "installed-packages")) `liftM` installationRootDeps exeInstalledDir Local = (</> $(mkRelDir "installed-packages")) `liftM` installationRootLocal -- | Get all of the installed executables getInstalledExes :: (MonadReader env m, HasEnvConfig env, MonadIO m, MonadThrow m) => InstallLocation -> m [PackageIdentifier] getInstalledExes loc = do dir <- exeInstalledDir loc (_, files) <- liftIO $ handleIO (const $ return ([], [])) $ listDir dir return $ concat $ M.elems $ -- If there are multiple install records (from a stack version -- before https://github.com/commercialhaskell/stack/issues/2373 -- was fixed), then we don't know which is correct - ignore them. M.fromListWith (\_ _ -> []) $ map (\x -> (packageIdentifierName x, [x])) $ mapMaybe (parsePackageIdentifierFromString . toFilePath . filename) files -- | Mark the given executable as installed markExeInstalled :: (MonadReader env m, HasEnvConfig env, MonadIO m, MonadCatch m) => InstallLocation -> PackageIdentifier -> m () markExeInstalled loc ident = do dir <- exeInstalledDir loc ensureDir dir ident' <- parseRelFile $ packageIdentifierString ident let fp = toFilePath $ dir </> ident' -- Remove old install records for this package. -- TODO: This is a bit in-efficient. Put all this metadata into one file? installed <- getInstalledExes loc forM_ (filter (\x -> packageIdentifierName ident == packageIdentifierName x) installed) (markExeNotInstalled loc) -- TODO consideration for the future: list all of the executables -- installed, and invalidate this file in getInstalledExes if they no -- longer exist liftIO $ writeFile fp "Installed" -- | Mark the given executable as not installed markExeNotInstalled :: (MonadReader env m, HasEnvConfig env, MonadIO m, MonadCatch m) => InstallLocation -> PackageIdentifier -> m () markExeNotInstalled loc ident = do dir <- exeInstalledDir loc ident' <- parseRelFile $ packageIdentifierString ident ignoringAbsence (removeFile $ dir </> ident') -- | Try to read the dirtiness cache for the given package directory. tryGetBuildCache :: (MonadIO m, MonadReader env m, MonadThrow m, MonadLogger m, HasEnvConfig env, MonadBaseControl IO m) => Path Abs Dir -> m (Maybe (Map FilePath FileCacheInfo)) tryGetBuildCache dir = liftM (fmap buildCacheTimes) . $(versionedDecodeFile buildCacheVC) =<< buildCacheFile dir -- | Try to read the dirtiness cache for the given package directory. tryGetConfigCache :: (MonadIO m, MonadReader env m, MonadThrow m, HasEnvConfig env, MonadBaseControl IO m, MonadLogger m) => Path Abs Dir -> m (Maybe ConfigCache) tryGetConfigCache dir = $(versionedDecodeFile configCacheVC) =<< configCacheFile dir -- | Try to read the mod time of the cabal file from the last build tryGetCabalMod :: (MonadIO m, MonadReader env m, MonadThrow m, HasEnvConfig env, MonadBaseControl IO m, MonadLogger m) => Path Abs Dir -> m (Maybe ModTime) tryGetCabalMod dir = $(versionedDecodeFile modTimeVC) =<< configCabalMod dir -- | Write the dirtiness cache for this package's files. writeBuildCache :: (MonadIO m, MonadReader env m, MonadThrow m, HasEnvConfig env, MonadLogger m) => Path Abs Dir -> Map FilePath FileCacheInfo -> m () writeBuildCache dir times = do fp <- buildCacheFile dir $(versionedEncodeFile buildCacheVC) fp BuildCache { buildCacheTimes = times } -- | Write the dirtiness cache for this package's configuration. writeConfigCache :: (MonadIO m, MonadReader env m, MonadThrow m, HasEnvConfig env, MonadLogger m) => Path Abs Dir -> ConfigCache -> m () writeConfigCache dir x = do fp <- configCacheFile dir $(versionedEncodeFile configCacheVC) fp x -- | See 'tryGetCabalMod' writeCabalMod :: (MonadIO m, MonadReader env m, MonadThrow m, HasEnvConfig env, MonadLogger m) => Path Abs Dir -> ModTime -> m () writeCabalMod dir x = do fp <- configCabalMod dir $(versionedEncodeFile modTimeVC) fp x -- | Delete the caches for the project. deleteCaches :: (MonadIO m, MonadReader env m, MonadCatch m, HasEnvConfig env) => Path Abs Dir -> m () deleteCaches dir = do {- FIXME confirm that this is acceptable to remove bfp <- buildCacheFile dir removeFileIfExists bfp -} cfp <- configCacheFile dir ignoringAbsence (removeFile cfp) flagCacheFile :: (MonadIO m, MonadThrow m, MonadReader env m, HasEnvConfig env) => Installed -> m (Path Abs File) flagCacheFile installed = do rel <- parseRelFile $ case installed of Library _ gid -> ghcPkgIdString gid Executable ident -> packageIdentifierString ident dir <- flagCacheLocal return $ dir </> rel -- | Loads the flag cache for the given installed extra-deps tryGetFlagCache :: (MonadIO m, MonadThrow m, MonadReader env m, HasEnvConfig env, MonadBaseControl IO m, MonadLogger m) => Installed -> m (Maybe ConfigCache) tryGetFlagCache gid = do fp <- flagCacheFile gid $(versionedDecodeFile configCacheVC) fp writeFlagCache :: (MonadIO m, MonadReader env m, HasEnvConfig env, MonadThrow m, MonadLogger m) => Installed -> ConfigCache -> m () writeFlagCache gid cache = do file <- flagCacheFile gid ensureDir (parent file) $(versionedEncodeFile configCacheVC) file cache -- | Mark a test suite as having succeeded setTestSuccess :: (MonadIO m, MonadThrow m, MonadReader env m, HasEnvConfig env, MonadLogger m) => Path Abs Dir -> m () setTestSuccess dir = do fp <- testSuccessFile dir $(versionedEncodeFile testSuccessVC) fp True -- | Mark a test suite as not having succeeded unsetTestSuccess :: (MonadIO m, MonadThrow m, MonadReader env m, HasEnvConfig env, MonadLogger m) => Path Abs Dir -> m () unsetTestSuccess dir = do fp <- testSuccessFile dir $(versionedEncodeFile testSuccessVC) fp False -- | Check if the test suite already passed checkTestSuccess :: (MonadIO m, MonadThrow m, MonadReader env m, HasEnvConfig env, MonadBaseControl IO m, MonadLogger m) => Path Abs Dir -> m Bool checkTestSuccess dir = liftM (fromMaybe False) ($(versionedDecodeFile testSuccessVC) =<< testSuccessFile dir) -------------------------------------- -- Precompiled Cache -- -- Idea is simple: cache information about packages built in other snapshots, -- and then for identical matches (same flags, config options, dependencies) -- just copy over the executables and reregister the libraries. -------------------------------------- -- | The file containing information on the given package/configuration -- combination. The filename contains a hash of the non-directory configure -- options for quick lookup if there's a match. -- -- It also returns an action yielding the location of the precompiled -- path based on the old binary encoding. -- -- We only pay attention to non-directory options. We don't want to avoid a -- cache hit just because it was installed in a different directory. precompiledCacheFile :: (MonadThrow m, MonadReader env m, HasEnvConfig env, MonadLogger m) => PackageIdentifier -> ConfigureOpts -> Set GhcPkgId -- ^ dependencies -> m (Path Abs File, m (Path Abs File)) precompiledCacheFile pkgident copts installedPackageIDs = do ec <- asks getEnvConfig compiler <- parseRelDir $ compilerVersionString $ envConfigCompilerVersion ec cabal <- parseRelDir $ versionString $ envConfigCabalVersion ec pkg <- parseRelDir $ packageIdentifierString pkgident platformRelDir <- platformGhcRelDir let input = (coNoDirs copts, installedPackageIDs) -- In Cabal versions 1.22 and later, the configure options contain the -- installed package IDs, which is what we need for a unique hash. -- Unfortunately, earlier Cabals don't have the information, so we must -- supplement it with the installed package IDs directly. -- See issue: https://github.com/commercialhaskell/stack/issues/1103 let oldHash = B16.encode $ SHA256.hash $ LBS.toStrict $ if envConfigCabalVersion ec >= $(mkVersion "1.22") then Binary.encode (coNoDirs copts) else Binary.encode input hashToPath hash = do hashPath <- parseRelFile $ S8.unpack hash return $ getStackRoot ec </> $(mkRelDir "precompiled") </> platformRelDir </> compiler </> cabal </> pkg </> hashPath $logDebug $ "Precompiled cache input = " <> T.pack (show input) newPath <- hashToPath $ B64URL.encode $ SHA256.hash $ Store.encode input return (newPath, hashToPath oldHash) -- | Write out information about a newly built package writePrecompiledCache :: (MonadThrow m, MonadReader env m, HasEnvConfig env, MonadIO m, MonadLogger m) => BaseConfigOpts -> PackageIdentifier -> ConfigureOpts -> Set GhcPkgId -- ^ dependencies -> Installed -- ^ library -> Set Text -- ^ executables -> m () writePrecompiledCache baseConfigOpts pkgident copts depIDs mghcPkgId exes = do (file, _) <- precompiledCacheFile pkgident copts depIDs ensureDir (parent file) ec <- asks getEnvConfig let stackRootRelative = makeRelative (getStackRoot ec) mlibpath <- case mghcPkgId of Executable _ -> return Nothing Library _ ipid -> liftM Just $ do ipid' <- parseRelFile $ ghcPkgIdString ipid ++ ".conf" relPath <- stackRootRelative $ bcoSnapDB baseConfigOpts </> ipid' return $ toFilePath $ relPath exes' <- forM (Set.toList exes) $ \exe -> do name <- parseRelFile $ T.unpack exe relPath <- stackRootRelative $ bcoSnapInstallRoot baseConfigOpts </> bindirSuffix </> name return $ toFilePath $ relPath $(versionedEncodeFile precompiledCacheVC) file PrecompiledCache { pcLibrary = mlibpath , pcExes = exes' } -- | Check the cache for a precompiled package matching the given -- configuration. readPrecompiledCache :: (MonadThrow m, MonadReader env m, HasEnvConfig env, MonadIO m, MonadLogger m, MonadBaseControl IO m) => PackageIdentifier -- ^ target package -> ConfigureOpts -> Set GhcPkgId -- ^ dependencies -> m (Maybe PrecompiledCache) readPrecompiledCache pkgident copts depIDs = do ec <- asks getEnvConfig let toAbsPath path = do if FilePath.isAbsolute path then path -- Only older version store absolute path else toFilePath (getStackRoot ec) FilePath.</> path let toAbsPC pc = PrecompiledCache { pcLibrary = fmap toAbsPath (pcLibrary pc) , pcExes = map toAbsPath (pcExes pc) } (file, getOldFile) <- precompiledCacheFile pkgident copts depIDs mres <- $(versionedDecodeFile precompiledCacheVC) file case mres of Just res -> return (Just $ toAbsPC res) Nothing -> do -- Fallback on trying the old binary format. oldFile <- getOldFile mpc <- fmap (fmap toAbsPC) $ binaryDecodeFileOrFailDeep oldFile -- Write out file in new format. Keep old file around for -- the benefit of older stack versions. forM_ mpc ($(versionedEncodeFile precompiledCacheVC) file) return mpc -- | Ensure that there are no lurking exceptions deep inside the parsed -- value... because that happens unfortunately. See -- https://github.com/commercialhaskell/stack/issues/554 binaryDecodeFileOrFailDeep :: (BinarySchema a, MonadIO m) => Path loc File -> m (Maybe a) binaryDecodeFileOrFailDeep fp = liftIO $ fmap (either (\_ -> Nothing) id) $ tryAnyDeep $ do eres <- BinaryTagged.taggedDecodeFileOrFail (toFilePath fp) case eres of Left _ -> return Nothing Right x -> return (Just x) type BinarySchema a = (Binary a, NFData a, HasStructuralInfo a, HasSemanticVersion a)
Blaisorblade/stack
src/Stack/Build/Cache.hs
bsd-3-clause
15,541
0
20
4,066
3,472
1,784
1,688
266
3
{-# LANGUAGE DuplicateRecordFields #-} {-# OPTIONS_GHC -Werror #-} import OverloadedRecFldsFail12_A data S = MkS { foo :: Bool } -- Use of foo and bar should give deprecation warnings f :: T -> T f e = e { foo = 3, bar = 3 } s :: T -> Int s = foo main = return ()
ezyang/ghc
testsuite/tests/overloadedrecflds/should_fail/overloadedrecfldsfail12.hs
bsd-3-clause
269
0
8
63
77
45
32
9
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} -- | It is well known that fully parallel loops can always be -- interchanged inwards with a sequential loop. This module -- implements that transformation. -- -- This is also where we implement loop-switching (for branches), -- which is semantically similar to interchange. module Futhark.Pass.ExtractKernels.Interchange ( SeqLoop (..), interchangeLoops, Branch (..), interchangeBranch, WithAccStm (..), interchangeWithAcc, ) where import Control.Monad.Identity import Data.List (find) import Data.Maybe import Futhark.IR.SOACS import Futhark.MonadFreshNames import Futhark.Pass.ExtractKernels.Distribution ( KernelNest, LoopNesting (..), kernelNestLoops, scopeOfKernelNest, ) import Futhark.Tools import Futhark.Transform.Rename import Futhark.Util (splitFromEnd) -- | An encoding of a sequential do-loop with no existential context, -- alongside its result pattern. data SeqLoop = SeqLoop [Int] Pat [(FParam, SubExp)] (LoopForm SOACS) Body seqLoopStm :: SeqLoop -> Stm seqLoopStm (SeqLoop _ pat merge form body) = Let pat (defAux ()) $ DoLoop merge form body interchangeLoop :: (MonadBuilder m, LocalScope SOACS m) => (VName -> Maybe VName) -> SeqLoop -> LoopNesting -> m SeqLoop interchangeLoop isMapParameter (SeqLoop perm loop_pat merge form body) (MapNesting pat aux w params_and_arrs) = do merge_expanded <- localScope (scopeOfLParams $ map fst params_and_arrs) $ mapM expand merge let loop_pat_expanded = Pat $ map expandPatElem $ patElems loop_pat new_params = [Param attrs pname $ fromDecl ptype | (Param attrs pname ptype, _) <- merge] new_arrs = map (paramName . fst) merge_expanded rettype = map rowType $ patTypes loop_pat_expanded -- If the map consumes something that is bound outside the loop -- (i.e. is not a merge parameter), we have to copy() it. As a -- small simplification, we just remove the parameter outright if -- it is not used anymore. This might happen if the parameter was -- used just as the inital value of a merge parameter. ((params', arrs'), pre_copy_stms) <- runBuilder $ localScope (scopeOfLParams new_params) $ unzip . catMaybes <$> mapM copyOrRemoveParam params_and_arrs let lam = Lambda (params' <> new_params) body rettype map_stm = Let loop_pat_expanded aux $ Op $ Screma w (arrs' <> new_arrs) (mapSOAC lam) res = varsRes $ patNames loop_pat_expanded pat' = Pat $ rearrangeShape perm $ patElems pat pure $ SeqLoop perm pat' merge_expanded form $ mkBody (pre_copy_stms <> oneStm map_stm) res where free_in_body = freeIn body copyOrRemoveParam (param, arr) | not (paramName param `nameIn` free_in_body) = return Nothing | otherwise = return $ Just (param, arr) expandedInit _ (Var v) | Just arr <- isMapParameter v = pure $ Var arr expandedInit param_name se = letSubExp (param_name <> "_expanded_init") $ BasicOp $ Replicate (Shape [w]) se expand (merge_param, merge_init) = do expanded_param <- newParam (param_name <> "_expanded") $ -- FIXME: Unique here is a hack to make sure the copy from -- makeCopyInitial is not prematurely simplified away. -- It'd be better to fix this somewhere else... arrayOf (paramDeclType merge_param) (Shape [w]) Unique expanded_init <- expandedInit param_name merge_init return (expanded_param, expanded_init) where param_name = baseString $ paramName merge_param expandPatElem (PatElem name t) = PatElem name $ arrayOfRow t w -- We need to copy some initial arguments because otherwise the result -- of the loop might alias the input (if the number of iterations is -- 0), which is a problem if the result is consumed. maybeCopyInitial :: (MonadBuilder m) => (VName -> Bool) -> SeqLoop -> m SeqLoop maybeCopyInitial isMapInput (SeqLoop perm loop_pat merge form body) = SeqLoop perm loop_pat <$> mapM f merge <*> pure form <*> pure body where f (p, Var arg) | isMapInput arg = (p,) <$> letSubExp (baseString (paramName p) <> "_inter_copy") (BasicOp $ Copy arg) f (p, arg) = pure (p, arg) manifestMaps :: [LoopNesting] -> [VName] -> Stms SOACS -> ([VName], Stms SOACS) manifestMaps [] res stms = (res, stms) manifestMaps (n : ns) res stms = let (res', stms') = manifestMaps ns res stms (params, arrs) = unzip $ loopNestingParamsAndArrs n lam = Lambda params (mkBody stms' $ varsRes res') (map rowType $ patTypes (loopNestingPat n)) in ( patNames $ loopNestingPat n, oneStm $ Let (loopNestingPat n) (loopNestingAux n) $ Op $ Screma (loopNestingWidth n) arrs (mapSOAC lam) ) -- | Given a (parallel) map nesting and an inner sequential loop, move -- the maps inside the sequential loop. The result is several -- statements - one of these will be the loop, which will then contain -- statements with @map@ expressions. interchangeLoops :: (MonadFreshNames m, HasScope SOACS m) => KernelNest -> SeqLoop -> m (Stms SOACS) interchangeLoops full_nest = recurse (kernelNestLoops full_nest) where recurse nest loop | (ns, [n]) <- splitFromEnd 1 nest = do let isMapParameter v = snd <$> find ((== v) . paramName . fst) (loopNestingParamsAndArrs n) isMapInput v = v `elem` map snd (loopNestingParamsAndArrs n) (loop', stms) <- runBuilder . localScope (scopeOfKernelNest full_nest) $ maybeCopyInitial isMapInput =<< interchangeLoop isMapParameter loop n -- Only safe to continue interchanging if we didn't need to add -- any new statements; otherwise we manifest the remaining nests -- as Maps and hand them back to the flattener. if null stms then recurse ns loop' else let loop_stm = seqLoopStm loop' in pure $ snd $ manifestMaps ns (patNames (stmPat loop_stm)) $ stms <> oneStm loop_stm | otherwise = pure $ oneStm $ seqLoopStm loop data Branch = Branch [Int] Pat SubExp Body Body (IfDec (BranchType SOACS)) branchStm :: Branch -> Stm branchStm (Branch _ pat cond tbranch fbranch ret) = Let pat (defAux ()) $ If cond tbranch fbranch ret interchangeBranch1 :: (MonadBuilder m) => Branch -> LoopNesting -> m Branch interchangeBranch1 (Branch perm branch_pat cond tbranch fbranch (IfDec ret if_sort)) (MapNesting pat aux w params_and_arrs) = do let ret' = map (`arrayOfRow` Free w) ret pat' = Pat $ rearrangeShape perm $ patElems pat (params, arrs) = unzip params_and_arrs lam_ret = rearrangeShape perm $ map rowType $ patTypes pat branch_pat' = Pat $ map (fmap (`arrayOfRow` w)) $ patElems branch_pat mkBranch branch = (renameBody =<<) $ do let lam = Lambda params branch lam_ret res = varsRes $ patNames branch_pat' map_stm = Let branch_pat' aux $ Op $ Screma w arrs $ mapSOAC lam return $ mkBody (oneStm map_stm) res tbranch' <- mkBranch tbranch fbranch' <- mkBranch fbranch return $ Branch [0 .. patSize pat -1] pat' cond tbranch' fbranch' $ IfDec ret' if_sort interchangeBranch :: (MonadFreshNames m, HasScope SOACS m) => KernelNest -> Branch -> m (Stms SOACS) interchangeBranch nest loop = do (loop', stms) <- runBuilder $ foldM interchangeBranch1 loop $ reverse $ kernelNestLoops nest return $ stms <> oneStm (branchStm loop') data WithAccStm = WithAccStm [Int] Pat [(Shape, [VName], Maybe (Lambda, [SubExp]))] Lambda withAccStm :: WithAccStm -> Stm withAccStm (WithAccStm _ pat inputs lam) = Let pat (defAux ()) $ WithAcc inputs lam interchangeWithAcc1 :: (MonadBuilder m, Rep m ~ SOACS) => WithAccStm -> LoopNesting -> m WithAccStm interchangeWithAcc1 (WithAccStm perm _withacc_pat inputs acc_lam) (MapNesting map_pat map_aux w params_and_arrs) = do inputs' <- mapM onInput inputs lam_params' <- newAccLamParams $ lambdaParams acc_lam iota_p <- newParam "iota_p" $ Prim int64 acc_lam' <- trLam (Var (paramName iota_p)) <=< mkLambda lam_params' $ do let acc_params = drop (length inputs) lam_params' orig_acc_params = drop (length inputs) $ lambdaParams acc_lam iota_w <- letExp "acc_inter_iota" . BasicOp $ Iota w (intConst Int64 0) (intConst Int64 1) Int64 let (params, arrs) = unzip params_and_arrs maplam_ret = lambdaReturnType acc_lam maplam = Lambda (iota_p : orig_acc_params ++ params) (lambdaBody acc_lam) maplam_ret auxing map_aux . fmap subExpsRes . letTupExp' "withacc_inter" $ Op $ Screma w (iota_w : map paramName acc_params ++ arrs) (mapSOAC maplam) let pat = Pat $ rearrangeShape perm $ patElems map_pat pure $ WithAccStm perm pat inputs' acc_lam' where newAccLamParams ps = do let (cert_ps, acc_ps) = splitAt (length ps `div` 2) ps -- Should not rename the certificates. acc_ps' <- forM acc_ps $ \(Param attrs v t) -> Param attrs <$> newVName (baseString v) <*> pure t pure $ cert_ps <> acc_ps' num_accs = length inputs acc_certs = map paramName $ take num_accs $ lambdaParams acc_lam onArr v = pure . maybe v snd $ find ((== v) . paramName . fst) params_and_arrs onInput (shape, arrs, op) = (Shape [w] <> shape,,) <$> mapM onArr arrs <*> traverse onOp op onOp (op_lam, nes) = do -- We need to add an additional index parameter because we are -- extending the index space of the accumulator. idx_p <- newParam "idx" $ Prim int64 pure (op_lam {lambdaParams = idx_p : lambdaParams op_lam}, nes) trType :: TypeBase shape u -> TypeBase shape u trType (Acc acc ispace ts u) | acc `elem` acc_certs = Acc acc (Shape [w] <> ispace) ts u trType t = t trParam :: Param (TypeBase shape u) -> Param (TypeBase shape u) trParam = fmap trType trLam i (Lambda params body ret) = localScope (scopeOfLParams params) $ Lambda (map trParam params) <$> trBody i body <*> pure (map trType ret) trBody i (Body dec stms res) = inScopeOf stms $ Body dec <$> traverse (trStm i) stms <*> pure res trStm i (Let pat aux e) = Let (fmap trType pat) aux <$> trExp i e trSOAC i = mapSOACM mapper where mapper = identitySOACMapper {mapOnSOACLambda = trLam i} trExp i (WithAcc acc_inputs lam) = WithAcc acc_inputs <$> trLam i lam trExp i (BasicOp (UpdateAcc acc is ses)) = do acc_t <- lookupType acc pure $ case acc_t of Acc cert _ _ _ | cert `elem` acc_certs -> BasicOp $ UpdateAcc acc (i : is) ses _ -> BasicOp $ UpdateAcc acc is ses trExp i e = mapExpM mapper e where mapper = identityMapper { mapOnBody = \scope -> localScope scope . trBody i, mapOnRetType = pure . trType, mapOnBranchType = pure . trType, mapOnFParam = pure . trParam, mapOnLParam = pure . trParam, mapOnOp = trSOAC i } interchangeWithAcc :: (MonadFreshNames m, HasScope SOACS m) => KernelNest -> WithAccStm -> m (Stms SOACS) interchangeWithAcc nest withacc = do (withacc', stms) <- runBuilder $ foldM interchangeWithAcc1 withacc $ reverse $ kernelNestLoops nest return $ stms <> oneStm (withAccStm withacc')
HIPERFIT/futhark
src/Futhark/Pass/ExtractKernels/Interchange.hs
isc
11,964
0
21
3,279
3,538
1,776
1,762
253
5
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeOperators #-} -- | GitHub event types and instances. module Github.Event.Types ( Event(..) , EventPayload(..) , StatusCommit(..) , Commit(..) , PushCommit(..) , Repository(..) , Committer(..) , PullRequest(..) , Issue(..) , Comment(..) , User(..) , Review(..) , isPingEvent , isPushEvent , isPullRequestEvent , isStatusEvent , isIssuesEvent , isIssueCommentEvent , isPullRequestReviewEvent , isPullRequestReviewCommentEvent , repository ) where import GHC.Generics import Data.Aeson import Data.Text (Text) import qualified JsonOptions as Json -- ---------------------------------------------- {-# ANN module ("HLint: ignore Use camelCase" :: Text) #-} -- ---------------------------------------------- -- | An GitHub event including metadata. data Event = Event { evtPayload :: EventPayload -- ^ The event payload , evtType :: Text -- ^ The event name, as set in the @X-GitHub-Event@ header , evtId :: Text -- ^ The delivery id, as set in the @X-GitHub-Delivery@ header } deriving (Show) -- | The GitHub event payload. data EventPayload = -- | A <https://developer.github.com/webhooks/#ping-event ping> event. PingEvent { epiZen :: Text , epiHook_id :: Int , epiRepository :: Repository } -- | A <https://developer.github.com/v3/activity/events/types/#pushevent push> event. | PushEvent { epuRef :: Text , epuCommits :: [PushCommit] , epuHead_commit :: Maybe PushCommit , epuCompare :: Text , epuRepository :: Repository } -- | A <https://developer.github.com/v3/activity/events/types/#pullrequestevent pull_request> event. | PullRequestEvent { eprAction :: Text , eprNumber :: Int , eprPull_request :: PullRequest , eprRepository :: Repository } -- | A <https://developer.github.com/v3/activity/events/types/#statusevent status> event. | StatusEvent { estSha :: Text , estState :: Text , estDescription :: Maybe Text , estCommit :: StatusCommit , estTarget_url :: Maybe Text , estRepository :: Repository } -- | A <https://developer.github.com/v3/activity/events/types/#issuesevent issues> event. | IssuesEvent { eisAction :: Text , eisIssue :: Issue , eisRepository :: Repository } -- | A <https://developer.github.com/v3/activity/events/types/#issuecommentevent issue_comment> event. | IssueCommentEvent { ecoAction :: Text , ecoIssue :: Issue , ecoComment :: Comment , ecoRepository :: Repository } -- | A <https://developer.github.com/v3/activity/events/types/#pullrequestreviewevent pull_request_review> event. | PullRequestReviewEvent { ervAction :: Text , ervReview :: Review , ervPull_request :: PullRequest , ervRepository :: Repository } -- | A <https://developer.github.com/v3/activity/events/types/#pullrequestreviewcommentevent pull_request_review_comment> event. | PullRequestReviewCommentEvent { ercAction :: Text , ercComment :: Comment , ercPull_request :: PullRequest , ercRepository :: Repository } deriving (Eq, Show, Generic) instance FromJSON EventPayload where parseJSON = genericParseJSON Json.parseOptions data PushCommit = PushCommit { pcmId :: Text , pcmMessage :: Text , pcmCommitter :: Committer } deriving (Eq, Show, Generic) instance FromJSON PushCommit where parseJSON = genericParseJSON Json.parseOptions data StatusCommit = StatusCommit { scmSha :: Text , scmHtml_url :: Text , scmCommit :: Commit } deriving (Eq, Show, Generic) instance FromJSON StatusCommit where parseJSON = genericParseJSON Json.parseOptions data Commit = Commit { cmtMessage :: Text } deriving (Eq, Show, Generic) instance FromJSON Commit where parseJSON = genericParseJSON Json.parseOptions data Repository = Repository { repName :: Text , repFull_name :: Text , repDefault_branch :: Text , repHtml_url :: Text } deriving (Eq, Show, Generic) instance FromJSON Repository where parseJSON = genericParseJSON Json.parseOptions data Pusher = Pusher { pshEmail :: Text } deriving (Eq, Show, Generic) instance ToJSON Pusher data Committer = Committer { citEmail :: Text , citUsername :: Text , citName :: Text } deriving (Eq, Show, Generic) instance FromJSON Committer where parseJSON = genericParseJSON Json.parseOptions data PullRequest = PullRequest { purNumber :: Int , purHtml_url :: Text , purState :: Text , purTitle :: Text , purMerged :: Maybe Bool , purMerged_by :: Maybe User , purUser :: User } deriving (Eq, Show, Generic) instance FromJSON PullRequest where parseJSON = genericParseJSON Json.parseOptions data Comment = Comment { comHtml_url :: Text , comBody :: Text , comUser :: User , comCreated_at :: Text } deriving (Eq, Show, Generic) instance FromJSON Comment where parseJSON = genericParseJSON Json.parseOptions data User = User { usrLogin :: Text , usrHtml_url :: Text } deriving (Eq, Show, Generic) instance FromJSON User where parseJSON = genericParseJSON Json.parseOptions data Issue = Issue { issNumber :: Int , issState :: Text , issTitle :: Text , issBody :: Text , issHtml_url :: Text , issUser :: User , issClosed_at :: Maybe Text -- XXX: add labels, assignee etc. } deriving (Eq, Show, Generic) instance FromJSON Issue where parseJSON = genericParseJSON Json.parseOptions data Review = Review { revHtml_url :: Text , revBody :: Text , revState :: Text , revUser :: User } deriving (Eq, Show, Generic) instance FromJSON Review where parseJSON = genericParseJSON Json.parseOptions -- ---------------------------------------------- -- | If the event is a ping event. isPingEvent :: EventPayload -> Bool isPingEvent PingEvent{} = True isPingEvent _ = False -- | If the event is a push event. isPushEvent :: EventPayload -> Bool isPushEvent PushEvent{} = True isPushEvent _ = False -- | If the event is a pull request event. isPullRequestEvent :: EventPayload -> Bool isPullRequestEvent PullRequestEvent{} = True isPullRequestEvent _ = False -- | If the event is a status event. isStatusEvent :: EventPayload -> Bool isStatusEvent StatusEvent{} = True isStatusEvent _ = False -- | If the event is an issues event. isIssuesEvent :: EventPayload -> Bool isIssuesEvent IssuesEvent{} = True isIssuesEvent _ = False -- | If the event is an issue comment event. isIssueCommentEvent :: EventPayload -> Bool isIssueCommentEvent IssueCommentEvent{} = True isIssueCommentEvent _ = False -- | If the event is a review event. isPullRequestReviewEvent :: EventPayload -> Bool isPullRequestReviewEvent PullRequestReviewEvent{} = True isPullRequestReviewEvent _ = False -- | If the event is a review comment event. isPullRequestReviewCommentEvent :: EventPayload -> Bool isPullRequestReviewCommentEvent PullRequestReviewCommentEvent{} = True isPullRequestReviewCommentEvent _ = False -- | The source repository of this event. repository :: EventPayload -> Repository repository PingEvent{..} = epiRepository repository PushEvent{..} = epuRepository repository PullRequestEvent{..} = eprRepository repository StatusEvent{..} = estRepository repository IssuesEvent{..} = eisRepository repository IssueCommentEvent{..} = ecoRepository repository PullRequestReviewEvent{..} = ervRepository repository PullRequestReviewCommentEvent{..} = ercRepository
UlfS/ghmm
src/Github/Event/Types.hs
mit
8,131
0
9
1,978
1,547
911
636
197
1
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GADTs #-} import Control.Monad.ST import Data.Array.ST import Data.Array.Unboxed import Data.Foldable import System.Environment data LinearSpace a b where Vector :: a -> LinearSpace a b Sum :: LinearSpace a b -> LinearSpace a b -> LinearSpace a b Scale :: b -> LinearSpace a b -> LinearSpace a b data LinearSpaceOpt a b where LinearComb :: [(b,LinearSpace a b)] -> LinearSpaceOpt a b {- showVectorExpr :: (Show a,Show b) => LinearSpace a b -> String showVectorExpr (Vector a) = "(Array " ++ (show a) ++ ")" showVectorExpr (Sum a1 a2) = "(" ++ (showVectorExpr a1) ++ "+" ++ (showVectorExpr a2) ++ ")" showVectorExpr (Scale b a1) = (show b) ++ "*" ++ (showVectorExpr a1) -} vectorExpr2lc :: (Num b) => LinearSpace a b -> [(b,LinearSpace a b)] vectorExpr2lc (Vector x) = [(1,Vector x)] vectorExpr2lc (Scale u x) = map (\z->(u* fst z,snd z)) (vectorExpr2lc x) vectorExpr2lc (Sum x y) = vectorExpr2lc x ++ vectorExpr2lc y optVectorExpr :: (Num b) => LinearSpace a b -> LinearSpaceOpt a b optVectorExpr x = LinearComb (vectorExpr2lc x) evalUArrayExpr :: LinearSpace (UArray Int Int) Int -> LinearSpace (UArray Int Int) Int evalUArrayExpr (Vector x) = Vector x evalUArrayExpr (Sum (Vector x) (Vector y)) = Vector z where z = listArray (1,n) [(x ! i) + (y ! i) | i <- [1..n]] where n = snd $ bounds x evalUArrayExpr (Sum x (Vector y)) = evalUArrayExpr (Sum (evalUArrayExpr x) (Vector y)) evalUArrayExpr (Sum (Vector y) x) = evalUArrayExpr (Sum x (Vector y)) evalUArrayExpr (Sum x y) = evalUArrayExpr (Sum (evalUArrayExpr x) (evalUArrayExpr y)) evalUArrayExpr (Scale y (Vector x)) = Vector z where z = listArray (1,n) [(x ! i) * y | i<-[1..n]] where n = snd $ bounds x evalUArrayExpr (Scale y x) = evalUArrayExpr (Scale y (evalUArrayExpr x)) getUArray :: forall t t1. LinearSpace t t1 -> t getUArray (Vector x) = x getUArray _ = error "bad" make :: [Int] -> ST s (STUArray s Int Int) make xs = newListArray (1, length xs) xs evalUArrayExprOpt :: LinearSpaceOpt (UArray Int Int) Int -> LinearSpace (UArray Int Int) Int evalUArrayExprOpt (LinearComb x) = Vector y where y=runSTUArray $ do let n= (snd . bounds . getUArray . snd . head) x tmp<-make (replicate n 0) let vs = map (\s -> (fst s,getUArray (snd s))) x forM_ [1..n] $ \i1 -> forM_ vs $ \i2 -> do val1<-readArray tmp i1 let val2 = fst i2 * snd i2 ! i1 writeArray tmp i1 (val1+val2) return tmp main :: IO () main = do args<-getArgs let arrval = ( read . head) args :: Int let n = read (args !! 1)::Int let nterms = read (args !! 2):: Int let mode= args !! 3 {-Generate seed arrays-} let x = listArray (1,n) [arrval+i | i<-[1..n]] :: UArray Int Int let y = listArray (1,n) [arrval+i | i<-[1..n]] :: UArray Int Int let zeros = listArray (1,n) (replicate n 0) :: UArray Int Int {-Feed them into the Vector AST-} let vx = Vector x let vy = Vector y let zs = Vector zeros {-Create large ASTs-} let vxs= [Scale i vx | i<-[1..nterms]] let vys= [Scale (i-1) vy | i<-[1..nterms]] let vvs= zipWith Sum vxs vys let vz = foldr Sum zs vvs {-Naive evaluation of AST-} let h = evalUArrayExpr vz {-Optimized evaluation of AST-} let hopt=evalUArrayExprOpt (optVectorExpr vz) {-Back out Haskell Unboxed Array-} let out= getUArray (if mode=="opt" then hopt else h) {-Compute summary value to ensure nothing gets lazified-} let val= foldl' (+) 0 (elems out) print val
ReidAtcheson/vectorhaskell
linearspace.hs
mit
3,601
0
21
844
1,509
759
750
70
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Main where import BasePrelude hiding (left) import Data.Configurator import Data.Configurator.Types (Config) import Database.PostgreSQL.Simple (ConnectInfo (..), Connection, connect, defaultConnectInfo) import App import Control.Error import Csv (CsvError (..)) import Db (DbEnv (..), DbError (..)) main :: IO () main = runScript $ do args <- scriptIO $ getArgs env <- loadConfig fn <- headMay args ?? usage e <- scriptIO . runApp env . loadAndInsert $ fn scriptIO . putStrLn . either appErrorString successString $ e loadConfig :: Script AppEnv loadConfig = fmapLT ("There were problems loading the config:\n" <>) $ do conf <- scriptIO $ load [Required "app.cfg"] conn <- scriptIO $ requireConnection conf pure $ AppEnv (DbEnv conn) requireConnection :: Config -> IO Connection requireConnection c = do host <- lookupDefault (connectHost defaultConnectInfo) c "db.host" port <- lookupDefault (connectPort defaultConnectInfo) c "db.port" user <- lookupDefault (connectUser defaultConnectInfo) c "db.user" pass <- lookupDefault (connectPassword defaultConnectInfo) c "db.password" db <- lookupDefault (connectDatabase defaultConnectInfo) c "db.database" connect (ConnectInfo host port user pass db) -- This can also be achieved with the prisms from Control.Lens appErrorString :: AppError -> String appErrorString (AppDbError db) = dbErrorString db appErrorString (AppCsvError csv) = csvErrorString csv dbErrorString :: DbError -> String dbErrorString (DbQueryError q) = "There was a problem with one of the sql queries: " <> show q dbErrorString (DbSqlError s) = "There was a problem connecting to the database: " <> show s csvErrorString :: CsvError -> String csvErrorString (CsvIoError i) = "There was file error reading the csv file: " <> show i csvErrorString (CsvHeaderParseError s) = "Failed parsing the csv header to get the account number: " <> s csvErrorString (CsvDecodeErrors s) = unlines $ "Some csv lines failed to parse:" : s successString :: [Int] -> String successString ids = "Great Success! " <> (show . length $ ids) <> " rows inserted" usage :: String usage = "missing file name: run with cabal run -- <filename>"
benkolera/talk-stacking-your-monads
code/Main.hs
mit
2,343
0
12
455
615
314
301
46
1
{-# LANGUAGE StandaloneDeriving, TypeOperators, MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, UndecidableInstances #-} -- Experimenting with Data types à la carte -- http://www.cs.ru.nl/~W.Swierstra/Publications/DataTypesALaCarte.pdf module ALaCarte where import Data.Monoid import Data.Proxy (Proxy(..)) import Data.Union import Data.Functor.Classes -- Expressions parameterized by the signature of the expression constructor. newtype Expr f = In (f (Expr f)) deriving instance Show (f (Expr f)) => Show (Expr f) -- Smart constructor helper inject :: (g :< f) => g (Expr (Union f)) -> Expr (Union f) inject = In . inj -- Result of evaluating, checking, infering... type Result = Either String -- Example usage: -- λ let x :: ALaCarte.Expr (Union '[Val, Add, Mul]) = val 80 ⓧ val 5 ⊕ val 3 -- λ ALaCarte.eval x -- 403 -- λ ALaCarte.pretty x -- "((80 * 5) + 3)" -- Specific expression data types (these are the à la carte data types). -- newtype Val e = Val Int deriving (Functor) -- instance Eval Val where -- evalAlgebra (Val x) = x -- instance Render Val where -- render (Val x) = show x -- -- data Add e = Add e e deriving (Functor) -- instance Eval Add where -- evalAlgebra (Add x y) = x + y -- instance Render Add where -- render (Add x y) = "(" <> pretty x <> " + " <> pretty y <> ")" -- -- data Mul x = Mul x x deriving (Functor) -- instance Eval Mul where -- evalAlgebra (Mul x y) = x * y -- instance Render Mul where -- render (Mul x y) = "(" <> pretty x <> " * " <> pretty y <> ")" -- Smart constructors -- val :: (Val :< f) => Int -> Expr (Union f) -- val = inject . Val -- -- infixl 6 ⊕ -- (⊕) :: (Add :< f) => Expr (Union f) -> Expr (Union f) -> Expr (Union f) -- x ⊕ y = inject (Add x y) -- -- infixl 7 ⓧ -- (ⓧ) :: (Mul :< f) => Expr (Union f) -> Expr (Union f) -> Expr (Union f) -- x ⓧ y = inject (Mul x y)
tclem/lilo
src/ALaCarte.hs
mit
1,880
0
11
382
191
123
68
11
1
import Oczor.Test.Tests import Prelude main :: IO () main = af
ptol/oczor
test/Spec.hs
mit
64
0
6
12
25
14
11
4
1
{-# LANGUAGE CPP #-} module Database.PostgreSQL.Protocol.Store.Encode ( Encode , getEncodeLen , runEncode , putByteString , putByteStringNull , putWord8 , putWord16BE , putWord32BE , putWord64BE , putInt16BE , putInt32BE , putInt64BE , putFloat32BE , putFloat64BE ) where import Data.Monoid (Monoid(..), (<>)) import Foreign (Storable, alloca, peek, poke, castPtr, plusPtr, Ptr) import Data.Int (Int16, Int32, Int64) import Data.Word (Word8, Word16, Word32, Word64, byteSwap16, byteSwap32, byteSwap64) import Data.ByteString (ByteString) import Data.ByteString.Internal (toForeignPtr) import Data.Store.Core (Poke(..), unsafeEncodeWith, pokeStatePtr, pokeFromForeignPtr) import qualified Data.Semigroup as Sem data Encode = Encode {-# UNPACK #-} !Int !(Poke ()) instance Sem.Semigroup Encode where {-# INLINE (<>) #-} (Encode len1 f1) <> (Encode len2 f2) = Encode (len1 + len2) (f1 *> f2) instance Monoid Encode where {-# INLINE mempty #-} mempty = Encode 0 . Poke $ \_ offset -> pure (offset, ()) #if !(MIN_VERSION_base(4,11,0)) mappend = (Sem.<>) #endif instance Show Encode where show (Encode len _) = "Encode instance of length " ++ show len {-# INLINE getEncodeLen #-} getEncodeLen :: Encode -> Int getEncodeLen (Encode len _) = len {-# INLINE runEncode #-} runEncode :: Encode -> ByteString runEncode (Encode len f) = unsafeEncodeWith f len {-# INLINE fixed #-} fixed :: Int -> (Ptr Word8 -> IO ()) -> Encode fixed len f = Encode len . Poke $ \state offset -> do f $ pokeStatePtr state `plusPtr` offset let !newOffset = offset + len return (newOffset, ()) {-# INLINE putByteString #-} putByteString :: ByteString -> Encode putByteString bs = let (ptr, offset, len) = toForeignPtr bs in Encode len $ pokeFromForeignPtr ptr offset len -- | C-like string {-# INLINE putByteStringNull #-} putByteStringNull :: ByteString -> Encode putByteStringNull bs = putByteString bs <> putWord8 0 {-# INLINE putWord8 #-} putWord8 :: Word8 -> Encode putWord8 w = fixed 1 $ \p -> poke p w {-# INLINE putWord16BE #-} putWord16BE :: Word16 -> Encode putWord16BE w = fixed 2 $ \p -> poke (castPtr p) (byteSwap16 w) {-# INLINE putWord32BE #-} putWord32BE :: Word32 -> Encode putWord32BE w = fixed 4 $ \p -> poke (castPtr p) (byteSwap32 w) {-# INLINE putWord64BE #-} putWord64BE :: Word64 -> Encode putWord64BE w = fixed 8 $ \p -> poke (castPtr p) (byteSwap64 w) {-# INLINE putInt16BE #-} putInt16BE :: Int16 -> Encode putInt16BE = putWord16BE . fromIntegral {-# INLINE putInt32BE #-} putInt32BE :: Int32 -> Encode putInt32BE = putWord32BE . fromIntegral {-# INLINE putInt64BE #-} putInt64BE :: Int64 -> Encode putInt64BE = putWord64BE . fromIntegral {-# INLINE putFloat32BE #-} putFloat32BE :: Float -> Encode putFloat32BE float = fixed 4 $ \ptr -> byteSwap32 <$> floatToWord float >>= poke (castPtr ptr) {-# INLINE putFloat64BE #-} putFloat64BE :: Double -> Encode putFloat64BE double = fixed 8 $ \ptr -> byteSwap64 <$> floatToWord double >>= poke (castPtr ptr) {-# INLINE floatToWord #-} floatToWord :: (Storable word, Storable float) => float -> IO word floatToWord float = alloca $ \buf -> do poke (castPtr buf) float peek buf
postgres-haskell/postgres-wire
src/Database/PostgreSQL/Protocol/Store/Encode.hs
mit
3,413
0
12
785
1,002
544
458
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Web.Hablog.Page where import Control.Arrow ((&&&)) import qualified Data.Map as M import qualified Data.Text.Lazy as T import qualified Text.Blaze.Html5 as H import Web.Hablog.Utils import Web.Hablog.Post data Page = Page { pageURL :: FilePath , pageName :: T.Text , pagePreview :: Preview , pageModificationTime :: UTCTime , pageContent :: H.Html } toPage :: UTCTime -> T.Text -> Maybe Page toPage modtime fileContent = Page <$> fmap T.unpack (M.lookup "route" header) <*> M.lookup "title" header <*> pure (mkPreview header) <*> pure modtime <*> pure (createBody content') where (header, content') = (getHeader &&& getContent) fileContent instance Show Page where show = pageURL instance Eq Page where (==) p1 p2 = pageURL p1 == pageURL p2 instance Ord Page where compare p1 p2 | pageName p1 < pageName p2 = LT | otherwise = GT
soupi/hablog
src/Web/Hablog/Page.hs
mit
974
0
13
238
304
167
137
31
1
{-# LANGUAGE DeriveGeneric #-} module Tinc.Config ( getAdditionalDependencies , configFile ) where import Data.Aeson import GHC.Generics import Hpack.Config import Hpack.Yaml import System.Directory import Tinc.Fail data Config = Config { dependencies :: [Dependency] } deriving (Eq, Show, Generic) instance FromJSON Config configFile :: FilePath configFile = "tinc.yaml" getAdditionalDependencies :: IO [Dependency] getAdditionalDependencies = do exists <- doesFileExist configFile if exists then readConfig else return [] readConfig :: IO [Dependency] readConfig = decodeYaml configFile >>= either die (return . dependencies)
robbinch/tinc
src/Tinc/Config.hs
mit
711
0
9
161
172
95
77
24
2
-- | Provides datatypes for complex numbers (or complex anything, really) module Data.KnotComplex ( Complex (..) , K (..) ) where import Prelude import Data.Ratio hiding (numerator,denominator) -- | Data representing a complex number as a pair of arbitrary types. data Complex a = (:+) { realPart :: a, imagPart :: a } deriving (Eq,Show) instance Num a => Num (Complex a) where (a :+ b) + (a' :+ b') = (a+a') :+ (b+b') (a :+ b) * (a' :+ b') = (a*a'-b*b') :+ (a*b'+a'*b) negate (a :+ b) = (-a) :+ (-b) fromInteger n = fromInteger n :+ 0 abs (a :+ b) = undefined signum (a :+ b) = undefined instance Fractional a => Fractional (Complex a) where recip (a :+ b) = let r = recip (a*a+b*b) in ((a*r) :+ (-b*r)) fromRational q = fromRational q :+ 0 -- | Data representing a complex number as a pair of rationals. data K = K { re2::Rational, im2::Rational } deriving (Eq,Show) instance Num K where K a b + K a' b' = K (a+a') (b+b') K a b * K a' b' = K (a*a'+2*b*b') (a*b'+a'*b) negate (K a b) = K (negate a) (negate b) abs _ = error "" signum _ = error "" fromInteger i = K (fromInteger i) 0 instance Fractional K where recip (K a b) = let r = recip (a*a-2*b) in K (r*a) (-r*b) fromRational x = K x 0
adolenc/AlexanderTheGreat
src/Data/KnotComplex.hs
mit
1,238
6
14
285
682
355
327
28
0
module Main where import Prelude hiding (mod) import Systat.Opts import Systat.Driver main :: IO () main = getOpts >>= exec
mfaerevaag/systat
src/Main.hs
mit
127
0
6
23
42
25
17
6
1
import XMonad import XMonad.Actions.UpdatePointer import XMonad.Config.Xfce import XMonad.Hooks.DynamicLog import XMonad.Hooks.ManageDocks import XMonad.Hooks.ManageHelpers import XMonad.Hooks.EwmhDesktops import XMonad.Hooks.Script import XMonad.Layout.Fullscreen import XMonad.Layout.Grid import XMonad.Layout.IM import XMonad.Layout.NoBorders import XMonad.Layout.Reflect import XMonad.Layout.Spacing import XMonad.Layout.Spiral import XMonad.Layout.Tabbed import XMonad.Util.EZConfig(additionalKeys) import XMonad.Util.Run(spawnPipe) import Data.Ratio ((%)) import System.IO import qualified XMonad.StackSet as W myLayout = avoidStruts (Tall 1 (3/100) (34/55)) ||| -- approx of golden ratio ;-) noBorders (fullscreenFull Full) -- spiral (6/7) -- use 'xprop' to get the class information from a window myManageHook = composeAll [ className =? "Gimp" --> doFloat , className =? "Gimp-2.6" --> doFloat , className =? "Msgcompose" --> doCenterFloat , className =? "Ekiga" --> doFloat , className =? "Sflphone" --> doFloat , className =? "Skype" --> doFloat , title =? "Volume Control" --> doFloat , resource =? "desktop_window" --> doIgnore , resource =? "kdesktop" --> doIgnore ] myWorkspaces = [ "1", "2", "3", "4", "5", "6", "7", "8", "9" ] main = xmonad =<< xmobar myConfig -- , logHook = updatePointer (Relative 0.5 0.5) -- , ((mod4Mask .|. shiftMask, xK_z), spawn "ndh_suspend") -- , ((mod4Mask .|. shiftMask, xK_q), spawn "xfce4-session-logout") myConfig = xfceConfig { manageHook = manageDocks <+> myManageHook -- make sure to include myManageHook definition from above <+> manageHook defaultConfig , borderWidth = 1 , layoutHook = smartBorders $ myLayout , startupHook = execScriptHook "startup" , modMask = mod4Mask -- Rebind Mod to the Windows key , terminal = "st -f Hack-14" -- "simple terminal" } `additionalKeys` [ ((mod4Mask, xK_a), spawn "pavucontrol") , ((mod4Mask, xK_p), spawn "exe=`dmenu_path | dmenu` && eval \"exec $exe\"") , ((mod4Mask, xK_v), spawn "gvim") , ((mod4Mask, xK_f), spawn "pcmanfm") , ((mod4Mask, xK_c), spawn "chromium-browser") , ((mod4Mask, xK_z), spawn "xscreensaver-command -lock") , ((mod1Mask, xK_Tab), windows W.focusDown) ]
neilh23/dotfiles
xmonad/xmonad.hs
mit
2,400
0
10
510
541
328
213
51
1
{-- - Problem 2 (*) Find the last but one element of a list. (Note that the Lisp transcription of this problem is incorrect.) Example in Haskell: Prelude> myButLast [1,2,3,4] 3 Prelude> myButLast ['a'..'z'] 'y' --} myButLast = last . init -- init :: Vector a -> Vector a Source -- O(1) Yield all but the last element without copying. The vector may not be empty. myButLast' = head . drop 1 .reverse myButLast'' [x, _] = x myButLast'' (_:xs) = myButLast'' xs
sighingnow/Functional-99-Problems
Haskell/02.hs
mit
512
1
7
137
61
33
28
4
1
module HashtablesPlus.HashRef where import HashtablesPlus.Prelude -- | -- A reference to a mutable value, -- which provides instances for 'Hashable' and 'Eq'. -- -- It allows to use the values without those instances as keys in hash tables. data HashRef a = HashRef {-# UNPACK #-} !(StableName a) !a -- | -- Create a new reference. -- -- Two references created from the same value are not guaranteed to be equal or -- produce the same hash. -- However the references created from different values are guaranteed -- to be different. new :: a -> IO (HashRef a) new a = do sn <- makeStableName a return $ HashRef sn a -- | -- Extract the value from this reference. value :: HashRef a -> a value (HashRef _ a) = a instance Hashable (HashRef a) where hashWithSalt s (HashRef sn _) = hashWithSalt s sn hash (HashRef sn _) = hash sn instance Eq (HashRef a) where HashRef a _ == HashRef b _ = a == b
nikita-volkov/hashtables-plus
library/HashtablesPlus/HashRef.hs
mit
914
0
9
191
217
113
104
16
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-redirectallrequeststo.html module Stratosphere.ResourceProperties.S3BucketRedirectAllRequestsTo where import Stratosphere.ResourceImports -- | Full data type definition for S3BucketRedirectAllRequestsTo. See -- 's3BucketRedirectAllRequestsTo' for a more convenient constructor. data S3BucketRedirectAllRequestsTo = S3BucketRedirectAllRequestsTo { _s3BucketRedirectAllRequestsToHostName :: Val Text , _s3BucketRedirectAllRequestsToProtocol :: Maybe (Val Text) } deriving (Show, Eq) instance ToJSON S3BucketRedirectAllRequestsTo where toJSON S3BucketRedirectAllRequestsTo{..} = object $ catMaybes [ (Just . ("HostName",) . toJSON) _s3BucketRedirectAllRequestsToHostName , fmap (("Protocol",) . toJSON) _s3BucketRedirectAllRequestsToProtocol ] -- | Constructor for 'S3BucketRedirectAllRequestsTo' containing required -- fields as arguments. s3BucketRedirectAllRequestsTo :: Val Text -- ^ 'sbrartHostName' -> S3BucketRedirectAllRequestsTo s3BucketRedirectAllRequestsTo hostNamearg = S3BucketRedirectAllRequestsTo { _s3BucketRedirectAllRequestsToHostName = hostNamearg , _s3BucketRedirectAllRequestsToProtocol = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-redirectallrequeststo.html#cfn-s3-websiteconfiguration-redirectallrequeststo-hostname sbrartHostName :: Lens' S3BucketRedirectAllRequestsTo (Val Text) sbrartHostName = lens _s3BucketRedirectAllRequestsToHostName (\s a -> s { _s3BucketRedirectAllRequestsToHostName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-redirectallrequeststo.html#cfn-s3-websiteconfiguration-redirectallrequeststo-protocol sbrartProtocol :: Lens' S3BucketRedirectAllRequestsTo (Maybe (Val Text)) sbrartProtocol = lens _s3BucketRedirectAllRequestsToProtocol (\s a -> s { _s3BucketRedirectAllRequestsToProtocol = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/S3BucketRedirectAllRequestsTo.hs
mit
2,163
0
13
212
265
151
114
28
1
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} module Printparser where -- pretty-printer generated by the BNF converter import Absparser import Data.Char -- the top-level printing method printTree :: Print a => a -> String printTree = render . prt 0 type Doc = [ShowS] -> [ShowS] doc :: ShowS -> Doc doc = (:) render :: Doc -> String render d = rend 0 (map ($ "") $ d []) "" where rend i ss = case ss of "[" :ts -> showChar '[' . rend i ts "(" :ts -> showChar '(' . rend i ts "{" :ts -> showChar '{' . new (i+1) . rend (i+1) ts "}" : ";":ts -> new (i-1) . space "}" . showChar ';' . new (i-1) . rend (i-1) ts "}" :ts -> new (i-1) . showChar '}' . new (i-1) . rend (i-1) ts ";" :ts -> showChar ';' . new i . rend i ts t : "," :ts -> showString t . space "," . rend i ts t : ")" :ts -> showString t . showChar ')' . rend i ts t : "]" :ts -> showString t . showChar ']' . rend i ts t :ts -> space t . rend i ts _ -> id new i = showChar '\n' . replicateS (2*i) (showChar ' ') . dropWhile isSpace space t = showString t . (\s -> if null s then "" else (' ':s)) parenth :: Doc -> Doc parenth ss = doc (showChar '(') . ss . doc (showChar ')') concatS :: [ShowS] -> ShowS concatS = foldr (.) id concatD :: [Doc] -> Doc concatD = foldr (.) id replicateS :: Int -> ShowS -> ShowS replicateS n f = concatS (replicate n f) -- the printer class does the job class Print a where prt :: Int -> a -> Doc prtList :: [a] -> Doc prtList = concatD . map (prt 0) instance Print a => Print [a] where prt _ = prtList instance Print Char where prt _ s = doc (showChar '\'' . mkEsc '\'' s . showChar '\'') prtList s = doc (showChar '"' . concatS (map (mkEsc '"') s) . showChar '"') mkEsc :: Char -> Char -> ShowS mkEsc q s = case s of _ | s == q -> showChar '\\' . showChar s '\\'-> showString "\\\\" '\n' -> showString "\\n" '\t' -> showString "\\t" _ -> showChar s prPrec :: Int -> Int -> Doc -> Doc prPrec i j = if j<i then parenth else id instance Print Integer where prt _ x = doc (shows x) instance Print Double where prt _ x = doc (shows x) instance Print Ident where prt _ (Ident i) = doc (showString ( i)) prtList es = case es of [] -> (concatD []) [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ",") , prt 0 xs]) instance Print UIdent where prt _ (UIdent i) = doc (showString ( i)) instance Print AMPLCODE where prt i e = case e of Main handles cohandles constructors destructors processes functions start -> prPrec i 0 (concatD [prt 0 handles , prt 0 cohandles , prt 0 constructors , prt 0 destructors , prt 0 processes , prt 0 functions , prt 0 start]) instance Print HANDLE_SPEC where prt i e = case e of Hand_spec uident handles -> prPrec i 0 (concatD [prt 0 uident , doc (showString "=") , doc (showString "{") , prt 0 handles , doc (showString "}")]) prtList es = case es of [] -> (concatD []) [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ";") , prt 0 xs]) instance Print Handle where prt i e = case e of HandName uident -> prPrec i 0 (concatD [prt 0 uident]) prtList es = case es of [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ";") , prt 0 xs]) instance Print CONSTRUCTORS where prt i e = case e of Constructors structor_specs -> prPrec i 0 (concatD [doc (showString "%constructors") , doc (showString ":") , doc (showString "{") , prt 0 structor_specs , doc (showString "}")]) Constructors_none -> prPrec i 0 (concatD []) instance Print DESTRUCTORS where prt i e = case e of Destructors structor_specs -> prPrec i 0 (concatD [doc (showString "%destructors") , doc (showString ":") , doc (showString "{") , prt 0 structor_specs , doc (showString "}")]) Destructors_none -> prPrec i 0 (concatD []) instance Print STRUCTOR_SPEC where prt i e = case e of Struct_spec uident structs -> prPrec i 0 (concatD [prt 0 uident , doc (showString "=") , doc (showString "{") , prt 0 structs , doc (showString "}")]) prtList es = case es of [] -> (concatD []) [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ";") , prt 0 xs]) instance Print STRUCT where prt i e = case e of Struct uident n -> prPrec i 0 (concatD [prt 0 uident , prt 0 n]) prtList es = case es of [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ";") , prt 0 xs]) instance Print HANDLES where prt i e = case e of Handles handle_specs -> prPrec i 0 (concatD [doc (showString "%handles") , doc (showString ":") , doc (showString "{") , prt 0 handle_specs , doc (showString "}")]) Handles_none -> prPrec i 0 (concatD []) instance Print COHANDLES where prt i e = case e of Cohandles handle_specs -> prPrec i 0 (concatD [doc (showString "%cohandles") , doc (showString ":") , doc (showString "{") , prt 0 handle_specs , doc (showString "}")]) Cohandles_none -> prPrec i 0 (concatD []) instance Print PROCESSES where prt i e = case e of Processes process_specs -> prPrec i 0 (concatD [doc (showString "%processes") , doc (showString ":") , doc (showString "{") , prt 0 process_specs , doc (showString "}")]) Processes_none -> prPrec i 0 (concatD []) instance Print PROCESS_SPEC where prt i e = case e of Process_spec id varss ids0 ids coms -> prPrec i 0 (concatD [prt 0 id , doc (showString "(") , prt 0 varss , doc (showString "|") , prt 0 ids0 , doc (showString "=>") , prt 0 ids , doc (showString ")") , doc (showString "=") , prt 0 coms]) prtList es = case es of [] -> (concatD []) [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ";") , prt 0 xs]) instance Print Vars where prt i e = case e of VName id -> prPrec i 0 (concatD [prt 0 id]) prtList es = case es of [] -> (concatD []) [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ",") , prt 0 xs]) instance Print FUNCTIONS where prt i e = case e of Functions function_specs -> prPrec i 0 (concatD [doc (showString "%functions") , doc (showString ":") , doc (showString "{") , prt 0 function_specs , doc (showString "}")]) Functions_none -> prPrec i 0 (concatD []) instance Print FUNCTION_SPEC where prt i e = case e of Function_spec id varss coms -> prPrec i 0 (concatD [prt 0 id , doc (showString "(") , prt 0 varss , doc (showString ")") , doc (showString "=") , prt 0 coms]) prtList es = case es of [] -> (concatD []) [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ";") , prt 0 xs]) instance Print START where prt i e = case e of Start channel_spec coms -> prPrec i 0 (concatD [doc (showString "%run") , prt 0 channel_spec , doc (showString ":") , prt 0 coms]) instance Print CHANNEL_SPEC where prt i e = case e of Channel_specf ids0 ids -> prPrec i 0 (concatD [doc (showString "(") , doc (showString "|") , prt 0 ids0 , doc (showString "=>") , prt 0 ids , doc (showString ")")]) Channel_spec cintegers0 cintegers -> prPrec i 0 (concatD [doc (showString "(") , prt 0 cintegers0 , doc (showString "=>") , prt 0 cintegers , doc (showString ")")]) instance Print COMS where prt i e = case e of Prog coms -> prPrec i 0 (concatD [doc (showString "{") , prt 0 coms , doc (showString "}")]) prtList es = case es of [] -> (concatD []) [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ",") , prt 0 xs]) instance Print COM where prt i e = case e of AC_STOREf id -> prPrec i 0 (concatD [doc (showString "store") , prt 0 id]) AC_LOADf id -> prPrec i 0 (concatD [doc (showString "load") , prt 0 id]) AC_RET -> prPrec i 0 (concatD [doc (showString "ret")]) AC_FRET -> prPrec i 0 (concatD [doc (showString "fret")]) AC_CALLf id ids -> prPrec i 0 (concatD [doc (showString "call") , prt 0 id , doc (showString "(") , prt 0 ids , doc (showString ")")]) AC_INT cinteger -> prPrec i 0 (concatD [doc (showString "cInt") , prt 0 cinteger]) AC_LEQ -> prPrec i 0 (concatD [doc (showString "leq")]) AC_ADD -> prPrec i 0 (concatD [doc (showString "add")]) AC_MUL -> prPrec i 0 (concatD [doc (showString "mul")]) AC_CONS n0 n -> prPrec i 0 (concatD [doc (showString "cons") , doc (showString "(") , prt 0 n0 , doc (showString ",") , prt 0 n , doc (showString ")")]) AC_STRUCT uident0 uident -> prPrec i 0 (concatD [prt 0 uident0 , doc (showString ".") , prt 0 uident]) AC_STRUCTas uident0 uident ids -> prPrec i 0 (concatD [prt 0 uident0 , doc (showString ".") , prt 0 uident , doc (showString "(") , prt 0 ids , doc (showString ")")]) AC_CASEf labelcomss -> prPrec i 0 (concatD [doc (showString "case") , doc (showString "of") , doc (showString "{") , prt 0 labelcomss , doc (showString "}")]) AC_RECORDf labelcomss -> prPrec i 0 (concatD [doc (showString "rec") , doc (showString "of") , doc (showString "{") , prt 0 labelcomss , doc (showString "}")]) AC_DEST n0 n -> prPrec i 0 (concatD [doc (showString "dest") , prt 0 n0 , prt 0 n]) AC_GETf id -> prPrec i 0 (concatD [doc (showString "get") , prt 0 id]) AC_HPUTf id uident0 uident -> prPrec i 0 (concatD [doc (showString "hput") , prt 0 id , prt 0 uident0 , doc (showString ".") , prt 0 uident]) AC_HCASEf id labelcomss -> prPrec i 0 (concatD [doc (showString "hcase") , prt 0 id , doc (showString "of") , doc (showString "{") , prt 0 labelcomss , doc (showString "}")]) AC_PUTf id -> prPrec i 0 (concatD [doc (showString "put") , prt 0 id]) AC_SPLITf id0 id1 id -> prPrec i 0 (concatD [doc (showString "split") , prt 0 id0 , doc (showString "into") , prt 0 id1 , prt 0 id]) AC_FORKf id0 id1 ids2 coms3 id ids coms -> prPrec i 0 (concatD [doc (showString "fork") , prt 0 id0 , doc (showString "as") , doc (showString "{") , prt 0 id1 , doc (showString "with") , prt 0 ids2 , doc (showString "as") , prt 0 coms3 , doc (showString ";") , prt 0 id , doc (showString "with") , prt 0 ids , doc (showString "as") , prt 0 coms , doc (showString "}")]) AC_PLUGf id ids0 coms1 ids coms -> prPrec i 0 (concatD [doc (showString "plug") , prt 0 id , doc (showString "with") , doc (showString "{") , doc (showString "[") , prt 0 ids0 , doc (showString "]") , doc (showString ":") , prt 0 coms1 , doc (showString ";") , doc (showString "[") , prt 0 ids , doc (showString "]") , doc (showString ":") , prt 0 coms , doc (showString "}")]) AC_RUNf id ids0 ids1 ids -> prPrec i 0 (concatD [doc (showString "run") , prt 0 id , doc (showString "(") , prt 0 ids0 , doc (showString "|") , prt 0 ids1 , doc (showString "=>") , prt 0 ids , doc (showString ")")]) AC_IDF id0 id -> prPrec i 0 (concatD [prt 0 id0 , doc (showString ":=") , prt 0 id]) AC_CLOSEf id -> prPrec i 0 (concatD [doc (showString "close") , prt 0 id]) AC_HALTf id -> prPrec i 0 (concatD [doc (showString "halt") , prt 0 id]) prtList es = case es of [] -> (concatD []) [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ";") , prt 0 xs]) instance Print LABELCOMS where prt i e = case e of Labelcoms1 uident0 uident coms -> prPrec i 0 (concatD [prt 0 uident0 , doc (showString ".") , prt 0 uident , doc (showString ":") , prt 0 coms]) Labelcoms2 uident0 uident ids coms -> prPrec i 0 (concatD [prt 0 uident0 , doc (showString ".") , prt 0 uident , doc (showString "(") , prt 0 ids , doc (showString ")") , doc (showString ":") , prt 0 coms]) prtList es = case es of [] -> (concatD []) [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ";") , prt 0 xs]) instance Print TRAN where prt i e = case e of TranIn11 n0 n -> prPrec i 0 (concatD [doc (showString "(") , prt 0 n0 , doc (showString ",") , doc (showString "IN") , doc (showString ",") , prt 0 n , doc (showString ")")]) TranIn12 n0 n -> prPrec i 0 (concatD [doc (showString "(") , prt 0 n0 , doc (showString ",") , doc (showString "OUT") , doc (showString ",") , prt 0 n , doc (showString ")")]) prtList es = case es of [] -> (concatD []) [] -> (concatD []) [x] -> (concatD [prt 0 x]) [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ",") , prt 0 xs]) x:xs -> (concatD [prt 0 x , doc (showString ";") , prt 0 xs]) instance Print NCInteger where prt i e = case e of Ncinteger cinteger -> prPrec i 0 (concatD [prt 0 cinteger]) prtList es = case es of [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ",") , prt 0 xs]) instance Print NIdent where prt i e = case e of Nident1 id -> prPrec i 0 (concatD [prt 0 id]) prtList es = case es of [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ",") , prt 0 xs]) instance Print CInteger where prt i e = case e of Positive n -> prPrec i 0 (concatD [prt 0 n]) Negative n -> prPrec i 0 (concatD [doc (showString "-") , prt 0 n]) prtList es = case es of [] -> (concatD []) [x] -> (concatD [prt 0 x]) x:xs -> (concatD [prt 0 x , doc (showString ",") , prt 0 xs])
prashant007/AMPL
myAMPL/src/TEMP/Printparser.hs
mit
13,039
0
16
3,090
6,794
3,349
3,445
222
12
-- | -- Checks that actions scope cannot be top-level module Main where import Control.Monad (void) import Control.Biegunka main :: IO () main = void (biegunka id run (link ".xmonad/xmonad.hs" ".xmonad/xmonad.hs.bak")) -- STDERR -- Couldn't match type ‘'Actions’ with ‘'Sources’ -- Expected type: Script 'Sources () -- Actual type: Script 'Actions ()
biegunka/biegunka
test/typecheck/should_fail/Fail1.hs
mit
377
0
9
70
61
36
25
5
1
{-# LANGUAGE DeriveDataTypeable, ScopedTypeVariables, MultiParamTypeClasses #-} module Pump.Inter where import Pump.Type import Pump.Positiv import Pump.Negativ import Language.Syntax import Language.Inter import Language import Pump.Conf import qualified Pump.Quiz import Challenger.Partial import Autolib.Util.Sort import Autolib.Util.Seed import Autolib.Util.Zufall import Autolib.FiniteMap import Inter.Types import Autolib.Reporter import Autolib.ToDoc import Autolib.Reader import qualified Pump.REG as REG import qualified Pump.CF as CF import Inter.Quiz import Data.Typeable ------------------------------------------------------------------------ data PUMP = PUMP String deriving ( Eq, Ord, Typeable ) instance OrderScore PUMP where scoringOrder _ = None -- ? instance ToDoc PUMP where toDoc ( PUMP kind ) = text $ "PUMP-" ++ kind instance Reader PUMP where reader = do my_reserved "PUMP" -- for backward compatibility cs <- option "REG" $ do Autolib.Reader.char '-' many alphaNum return $ PUMP cs instance Pumping z => Partial PUMP ( Conf z ) ( Pump z ) where describe ( PUMP {} ) ( conf :: Conf z ) = vcat [ text $ "Untersuchen Sie, ob die Sprache L = " , nest 4 $ toDoc (inter $ lang conf) , text $ "die " ++ Pump.Type.tag ( undefined :: z ) ++ " erfüllt." , text "" , nest 4 $ parens $ text "Ja-Einsendungen werden bei dieser Aufgabe" $$ text "nur für n <=" <+> toDoc (ja_bound conf) <+> text "akzeptiert." , text "Zu dieser Sprache gehören unter anderem die Wörter:" , nest 4 $ toDoc $ take 10 $ samp conf ] initial ( PUMP {} ) conf = Ja { n = 3, zerlege = listToFM $ do w <- take 3 $ samp conf return ( w, exem w ) } -- partial p conf z = total ( PUMP {} ) conf p @ ( Nein {} ) = do negativ ( inter $ lang conf ) p return () total ( PUMP {} ) conf p @ ( Ja {} ) = do assert ( n p <= ja_bound conf ) $ text "Ist Ihr n kleiner als die Schranke?" let ws = take 5 $ filter ( (n p <= ) . length ) $ samp conf positiv ( inter $ lang conf ) p ws return () ---------------------------------------------------------------------- instance ( Reader z, ToDoc z , Pumping z ) => Generator ( PUMP ) ( Pump.Quiz.Conf z ) ( Conf z ) where generator p c key = do let l = Pump.Quiz.lang c wss <- sequence $ do c <- [ 10 .. 30 ] return $ lift $ samples ( inter l ) 2 c return $ Conf { lang = l , samp = nub $ concat wss , ja_bound = Pump.Quiz.ja_bound c } instance Project ( PUMP ) ( Conf z ) ( Conf z ) where project p c = c ---------------------------------------------------------------------- reg = quiz ( PUMP "REG" ) ( Pump.Quiz.example :: Pump.Quiz.Conf REG.Zerlegung ) cf = quiz ( PUMP "CF" ) ( Pump.Quiz.example :: Pump.Quiz.Conf CF.Zerlegung )
Erdwolf/autotool-bonn
src/Pump/Inter.hs
gpl-2.0
3,005
18
21
832
947
493
454
77
1
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for ganeti-htools. -} {- Copyright (C) 2009, 2010, 2011, 2012 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Test.Ganeti.Luxi (testLuxi) where import Test.HUnit import Test.QuickCheck import Test.QuickCheck.Monadic (monadicIO, run, stop) import Data.List import Control.Applicative import Control.Concurrent (forkIO) import Control.Exception (bracket) import System.Directory (getTemporaryDirectory, removeFile) import System.IO (hClose, openTempFile) import qualified Text.JSON as J import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Test.Ganeti.Query.Language (genFilter) import Test.Ganeti.OpCodes () import Ganeti.BasicTypes import qualified Ganeti.Luxi as Luxi {-# ANN module "HLint: ignore Use camelCase" #-} -- * Luxi tests $(genArbitrary ''Luxi.LuxiReq) instance Arbitrary Luxi.LuxiOp where arbitrary = do lreq <- arbitrary case lreq of Luxi.ReqQuery -> Luxi.Query <$> arbitrary <*> genFields <*> genFilter Luxi.ReqQueryFields -> Luxi.QueryFields <$> arbitrary <*> genFields Luxi.ReqQueryNodes -> Luxi.QueryNodes <$> listOf genFQDN <*> genFields <*> arbitrary Luxi.ReqQueryGroups -> Luxi.QueryGroups <$> arbitrary <*> arbitrary <*> arbitrary Luxi.ReqQueryNetworks -> Luxi.QueryNetworks <$> arbitrary <*> arbitrary <*> arbitrary Luxi.ReqQueryInstances -> Luxi.QueryInstances <$> listOf genFQDN <*> genFields <*> arbitrary Luxi.ReqQueryJobs -> Luxi.QueryJobs <$> arbitrary <*> genFields Luxi.ReqQueryExports -> Luxi.QueryExports <$> listOf genFQDN <*> arbitrary Luxi.ReqQueryConfigValues -> Luxi.QueryConfigValues <$> genFields Luxi.ReqQueryClusterInfo -> pure Luxi.QueryClusterInfo Luxi.ReqQueryTags -> Luxi.QueryTags <$> arbitrary Luxi.ReqSubmitJob -> Luxi.SubmitJob <$> resize maxOpCodes arbitrary Luxi.ReqSubmitManyJobs -> Luxi.SubmitManyJobs <$> resize maxOpCodes arbitrary Luxi.ReqWaitForJobChange -> Luxi.WaitForJobChange <$> arbitrary <*> genFields <*> pure J.JSNull <*> pure J.JSNull <*> arbitrary Luxi.ReqArchiveJob -> Luxi.ArchiveJob <$> arbitrary Luxi.ReqAutoArchiveJobs -> Luxi.AutoArchiveJobs <$> arbitrary <*> arbitrary Luxi.ReqCancelJob -> Luxi.CancelJob <$> arbitrary Luxi.ReqChangeJobPriority -> Luxi.ChangeJobPriority <$> arbitrary <*> arbitrary Luxi.ReqSetDrainFlag -> Luxi.SetDrainFlag <$> arbitrary Luxi.ReqSetWatcherPause -> Luxi.SetWatcherPause <$> arbitrary -- | Simple check that encoding/decoding of LuxiOp works. prop_CallEncoding :: Luxi.LuxiOp -> Property prop_CallEncoding op = (Luxi.validateCall (Luxi.buildCall op) >>= Luxi.decodeCall) ==? Ok op -- | Helper to a get a temporary file name. getTempFileName :: IO FilePath getTempFileName = do tempdir <- getTemporaryDirectory (fpath, handle) <- openTempFile tempdir "luxitest" _ <- hClose handle removeFile fpath return fpath -- | Server ping-pong helper. luxiServerPong :: Luxi.Client -> IO () luxiServerPong c = do msg <- Luxi.recvMsgExt c case msg of Luxi.RecvOk m -> Luxi.sendMsg c m >> luxiServerPong c _ -> return () -- | Client ping-pong helper. luxiClientPong :: Luxi.Client -> [String] -> IO [String] luxiClientPong c = mapM (\m -> Luxi.sendMsg c m >> Luxi.recvMsg c) -- | Monadic check that, given a server socket, we can connect via a -- client to it, and that we can send a list of arbitrary messages and -- get back what we sent. prop_ClientServer :: [[DNSChar]] -> Property prop_ClientServer dnschars = monadicIO $ do let msgs = map (map dnsGetChar) dnschars fpath <- run getTempFileName -- we need to create the server first, otherwise (if we do it in the -- forked thread) the client could try to connect to it before it's -- ready server <- run $ Luxi.getServer False fpath -- fork the server responder _ <- run . forkIO $ bracket (Luxi.acceptClient server) (\c -> Luxi.closeClient c >> Luxi.closeServer fpath server) luxiServerPong replies <- run $ bracket (Luxi.getClient fpath) Luxi.closeClient (`luxiClientPong` msgs) stop $ replies ==? msgs -- | Check that Python and Haskell define the same Luxi requests list. case_AllDefined :: Assertion case_AllDefined = do py_stdout <- runPython "from ganeti import luxi\n\ \print '\\n'.join(luxi.REQ_ALL)" "" >>= checkPythonResult let py_ops = sort $ lines py_stdout hs_ops = Luxi.allLuxiCalls extra_py = py_ops \\ hs_ops extra_hs = hs_ops \\ py_ops assertBool ("Luxi calls missing from Haskell code:\n" ++ unlines extra_py) (null extra_py) assertBool ("Extra Luxi calls in the Haskell code code:\n" ++ unlines extra_hs) (null extra_hs) testSuite "Luxi" [ 'prop_CallEncoding , 'prop_ClientServer , 'case_AllDefined ]
narurien/ganeti-ceph
test/hs/Test/Ganeti/Luxi.hs
gpl-2.0
5,917
0
16
1,395
1,149
592
557
107
2
module Tema_17a_ConjuntoConListasNoOrdenadasConDuplicados_Spec (main, spec) where import Tema_17.ConjuntoConListasNoOrdenadasConDuplicados import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "ConjuntoConListasNoOrdenadasConDuplicados" $ do it "e1" $ escribeConjunto (foldr inserta vacio [2,5,1,3,7,5,3,2,1,9,0]) `shouldBe` "{2,5,1,3,7,5,3,2,1,9,0}" it "e2" $ show (foldr inserta vacio [2,5,1,3,7,5,3,2,1,9,0]) `shouldBe` "{2,5,1,3,7,5,3,2,1,9,0}" it "e3" $ show (vacio :: Conj Int) `shouldBe` "{}" it "e4" $ show (inserta 5 (foldr inserta vacio [2,5,1,3,7,5,3,2,1,9,0])) `shouldBe` "{5,2,5,1,3,7,5,3,2,1,9,0}" it "e5" $ show (elimina 3 (foldr inserta vacio [2,5,1,3,7,5,3,2,1,9,0])) `shouldBe` "{2,5,1,7,5,2,1,9,0}" it "e6" $ pertenece 3 (foldr inserta vacio [2,5,1,3,7,5,3,2,1,9,0]) `shouldBe` True it "e7" $ pertenece 4 (foldr inserta vacio [2,5,1,3,7,5,3,2,1,9,0]) `shouldBe` False it "e8" $ esVacio (foldr inserta vacio [2,5,1,3,7,5,3,2,1,9,0]) `shouldBe` False it "e9" $ esVacio (vacio :: Conj Int) `shouldBe` True
jaalonso/I1M-Cod-Temas
test/Tema_17a_ConjuntoConListasNoOrdenadasConDuplicados_Spec.hs
gpl-2.0
1,189
0
17
262
570
323
247
31
1
import Data.List (maximumBy, tails, inits) import Data.Foldable (foldr') -- we use strict version to be kind to the stack and -- get the answer quickly main = putStrLn . show $ consecutivePrimeSum' 1000000 -- Eventually came up with this gnarly one-liner -- 4000 is rather large and has to be processed; could have a nicer way to -- guess that bit, or make it lazy somehow -- originally just started using -- powers of 10 consecutivePrimeSum limit = maximumBy (\a b -> compare (fst $ snd a) (fst $ snd b) ) $ filter (\ys -> (fst ys) < limit && (prime $ fst ys)) $ map (\xs -> (sum xs, (length xs, xs))) $ filter (/= []) $ concatMap tails $ inits $ primesTo 4000 -- However, it'd be much nicer to break this out into functions, reduce the number of -- list traversals and get rid of intermediary tuples -- Also uses a strict fold, meaning using less than half the memory and getting -- the answer in 0.5 seconds rather than 1.2 seconds consecutivePrimeSum' limit = (sum answer, length answer, answer) where answer = getBestist limit candidates getBestist limit xs = foldr' (\x y -> if length x > length y then if (sum x) < limit && prime (sum x) then x else y else y ) [] xs candidates = concatMap tails $ inits pt pt = primesTo 4000 primesTo :: Integer -> [Integer] primesTo n = takeWhile ( < n) primes primes :: [Integer] primes = 2 : primes' where primes' = sieve [3,5..] 9 primes' sieve (x:xs) q ps@ ~(p:t) | x < q = x : sieve xs q ps | otherwise = sieve [y | y <- xs, y `mod` p > 0] (head t^2) t prime n = n > 1 && foldr (\p r -> p*p > n || ((n `rem` p) /= 0 && r)) True primes
ciderpunx/project_euler_in_haskell
euler050.hs
gpl-2.0
1,804
0
17
541
571
302
269
30
3
module E2ASM.Assembler.Token ( Token(..) , TokenInfo(..) ) where import qualified Text.Parsec as P import qualified E2ASM.Assembler.Directive as Dir import qualified E2ASM.Assembler.Instruction as Instr import qualified E2ASM.Assembler.Label as Lab import qualified E2ASM.Assembler.Number as Num import qualified E2ASM.Assembler.Predicate as Pred import qualified E2ASM.Assembler.Register as Reg data Token = Token TokenInfo P.SourcePos deriving (Eq, Show) data TokenInfo = TReg Reg.Register | TPred Pred.Predicate | TInstr Instr.Instruction | TLabelDef Lab.Label | TLabelRef Lab.Label | TDir Dir.Directive | TNum Num.Number | TSep () | TLParen () | TRParen () deriving (Eq, Show)
E2LP/e2asm
src/E2ASM/Assembler/Token.hs
gpl-3.0
782
0
7
188
194
125
69
25
0
{-# LANGUAGE Unsafe #-} {-# LANGUAGE ConstraintKinds #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Typeable.Internal -- Copyright : (c) The University of Glasgow, CWI 2001--2011 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- The representations of the types TyCon and TypeRep, and the -- function mkTyCon which is used by derived instances of Typeable to -- construct a TyCon. -- ----------------------------------------------------------------------------- {-# LANGUAGE CPP , NoImplicitPrelude , OverlappingInstances , ScopedTypeVariables , FlexibleInstances , MagicHash , KindSignatures , PolyKinds , DeriveDataTypeable , StandaloneDeriving #-} module Data.Typeable.Internal ( Proxy (..), TypeRep(..), Fingerprint(..), typeOf, typeOf1, typeOf2, typeOf3, typeOf4, typeOf5, typeOf6, typeOf7, Typeable1, Typeable2, Typeable3, Typeable4, Typeable5, Typeable6, Typeable7, TyCon(..), typeRep, mkTyCon, mkTyCon3, mkTyConApp, mkAppTy, typeRepTyCon, Typeable(..), mkFunTy, splitTyConApp, funResultTy, typeRepArgs, showsTypeRep, tyConString, listTc, funTc ) where import GHC.Base import GHC.Word import GHC.Show import Data.Maybe import Data.Proxy import GHC.Num import GHC.Real -- import GHC.IORef -- import GHC.IOArray -- import GHC.MVar import GHC.ST ( ST ) import GHC.STRef ( STRef ) import GHC.Ptr ( Ptr, FunPtr ) -- import GHC.Stable import GHC.Arr ( Array, STArray ) import Data.Type.Coercion import Data.Type.Equality -- import Data.Int import GHC.Fingerprint.Type import {-# SOURCE #-} GHC.Fingerprint -- loop: GHC.Fingerprint -> Foreign.Ptr -> Data.Typeable -- Better to break the loop here, because we want non-SOURCE imports -- of Data.Typeable as much as possible so we can optimise the derived -- instances. -- | A concrete representation of a (monomorphic) type. 'TypeRep' -- supports reasonably efficient equality. data TypeRep = TypeRep {-# UNPACK #-} !Fingerprint TyCon [TypeRep] -- Compare keys for equality instance Eq TypeRep where (TypeRep k1 _ _) == (TypeRep k2 _ _) = k1 == k2 instance Ord TypeRep where (TypeRep k1 _ _) <= (TypeRep k2 _ _) = k1 <= k2 -- | An abstract representation of a type constructor. 'TyCon' objects can -- be built using 'mkTyCon'. data TyCon = TyCon { tyConHash :: {-# UNPACK #-} !Fingerprint, tyConPackage :: String, -- ^ /Since: 4.5.0.0/ tyConModule :: String, -- ^ /Since: 4.5.0.0/ tyConName :: String -- ^ /Since: 4.5.0.0/ } instance Eq TyCon where (TyCon t1 _ _ _) == (TyCon t2 _ _ _) = t1 == t2 instance Ord TyCon where (TyCon k1 _ _ _) <= (TyCon k2 _ _ _) = k1 <= k2 ----------------- Construction -------------------- #include "MachDeps.h" -- mkTyCon is an internal function to make it easier for GHC to -- generate derived instances. GHC precomputes the MD5 hash for the -- TyCon and passes it as two separate 64-bit values to mkTyCon. The -- TyCon for a derived Typeable instance will end up being statically -- allocated. #if WORD_SIZE_IN_BITS < 64 mkTyCon :: Word64# -> Word64# -> String -> String -> String -> TyCon #else mkTyCon :: Word# -> Word# -> String -> String -> String -> TyCon #endif mkTyCon high# low# pkg modl name = TyCon (Fingerprint (W64# high#) (W64# low#)) pkg modl name -- | Applies a type constructor to a sequence of types mkTyConApp :: TyCon -> [TypeRep] -> TypeRep mkTyConApp tc@(TyCon tc_k _ _ _) [] = TypeRep tc_k tc [] -- optimisation: all derived Typeable instances -- end up here, and it helps generate smaller -- code for derived Typeable. mkTyConApp tc@(TyCon tc_k _ _ _) args = TypeRep (fingerprintFingerprints (tc_k : arg_ks)) tc args where arg_ks = [k | TypeRep k _ _ <- args] -- | A special case of 'mkTyConApp', which applies the function -- type constructor to a pair of types. mkFunTy :: TypeRep -> TypeRep -> TypeRep mkFunTy f a = mkTyConApp funTc [f,a] -- | Splits a type constructor application splitTyConApp :: TypeRep -> (TyCon,[TypeRep]) splitTyConApp (TypeRep _ tc trs) = (tc,trs) -- | Applies a type to a function type. Returns: @'Just' u@ if the -- first argument represents a function of type @t -> u@ and the -- second argument represents a function of type @t@. Otherwise, -- returns 'Nothing'. funResultTy :: TypeRep -> TypeRep -> Maybe TypeRep funResultTy trFun trArg = case splitTyConApp trFun of (tc, [t1,t2]) | tc == funTc && t1 == trArg -> Just t2 _ -> Nothing -- | Adds a TypeRep argument to a TypeRep. mkAppTy :: TypeRep -> TypeRep -> TypeRep mkAppTy (TypeRep _ tc trs) arg_tr = mkTyConApp tc (trs ++ [arg_tr]) -- Notice that we call mkTyConApp to construct the fingerprint from tc and -- the arg fingerprints. Simply combining the current fingerprint with -- the new one won't give the same answer, but of course we want to -- ensure that a TypeRep of the same shape has the same fingerprint! -- See Trac #5962 -- | Builds a 'TyCon' object representing a type constructor. An -- implementation of "Data.Typeable" should ensure that the following holds: -- -- > A==A' ^ B==B' ^ C==C' ==> mkTyCon A B C == mkTyCon A' B' C' -- -- mkTyCon3 :: String -- ^ package name -> String -- ^ module name -> String -- ^ the name of the type constructor -> TyCon -- ^ A unique 'TyCon' object mkTyCon3 pkg modl name = TyCon (fingerprintString (pkg ++ (' ':modl) ++ (' ':name))) pkg modl name ----------------- Observation --------------------- -- | Observe the type constructor of a type representation typeRepTyCon :: TypeRep -> TyCon typeRepTyCon (TypeRep _ tc _) = tc -- | Observe the argument types of a type representation typeRepArgs :: TypeRep -> [TypeRep] typeRepArgs (TypeRep _ _ args) = args -- | Observe string encoding of a type representation {-# DEPRECATED tyConString "renamed to 'tyConName'; 'tyConModule' and 'tyConPackage' are also available." #-} -- deprecated in 7.4 tyConString :: TyCon -> String tyConString = tyConName ------------------------------------------------------------- -- -- The Typeable class and friends -- ------------------------------------------------------------- -- | The class 'Typeable' allows a concrete representation of a type to -- be calculated. class Typeable a where typeRep# :: Proxy# a -> TypeRep -- | Takes a value of type @a@ and returns a concrete representation -- of that type. -- -- /Since: 4.7.0.0/ typeRep :: forall proxy a. Typeable a => proxy a -> TypeRep typeRep _ = typeRep# (proxy# :: Proxy# a) {-# INLINE typeRep #-} -- Keeping backwards-compatibility typeOf :: forall a. Typeable a => a -> TypeRep typeOf _ = typeRep (Proxy :: Proxy a) typeOf1 :: forall t (a :: *). Typeable t => t a -> TypeRep typeOf1 _ = typeRep (Proxy :: Proxy t) typeOf2 :: forall t (a :: *) (b :: *). Typeable t => t a b -> TypeRep typeOf2 _ = typeRep (Proxy :: Proxy t) typeOf3 :: forall t (a :: *) (b :: *) (c :: *). Typeable t => t a b c -> TypeRep typeOf3 _ = typeRep (Proxy :: Proxy t) typeOf4 :: forall t (a :: *) (b :: *) (c :: *) (d :: *). Typeable t => t a b c d -> TypeRep typeOf4 _ = typeRep (Proxy :: Proxy t) typeOf5 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *). Typeable t => t a b c d e -> TypeRep typeOf5 _ = typeRep (Proxy :: Proxy t) typeOf6 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *) (f :: *). Typeable t => t a b c d e f -> TypeRep typeOf6 _ = typeRep (Proxy :: Proxy t) typeOf7 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *) (f :: *) (g :: *). Typeable t => t a b c d e f g -> TypeRep typeOf7 _ = typeRep (Proxy :: Proxy t) type Typeable1 (a :: * -> *) = Typeable a type Typeable2 (a :: * -> * -> *) = Typeable a type Typeable3 (a :: * -> * -> * -> *) = Typeable a type Typeable4 (a :: * -> * -> * -> * -> *) = Typeable a type Typeable5 (a :: * -> * -> * -> * -> * -> *) = Typeable a type Typeable6 (a :: * -> * -> * -> * -> * -> * -> *) = Typeable a type Typeable7 (a :: * -> * -> * -> * -> * -> * -> * -> *) = Typeable a {-# DEPRECATED Typeable1 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable2 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable3 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable4 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable5 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable6 "renamed to 'Typeable'" #-} -- deprecated in 7.8 {-# DEPRECATED Typeable7 "renamed to 'Typeable'" #-} -- deprecated in 7.8 -- | Kind-polymorphic Typeable instance for type application instance (Typeable s, Typeable a) => Typeable (s a) where typeRep# = \_ -> rep where rep = typeRep# (proxy# :: Proxy# s) `mkAppTy` typeRep# (proxy# :: Proxy# a) ----------------- Showing TypeReps -------------------- instance Show TypeRep where showsPrec p (TypeRep _ tycon tys) = case tys of [] -> showsPrec p tycon [x] | tycon == listTc -> showChar '[' . shows x . showChar ']' [a,r] | tycon == funTc -> showParen (p > 8) $ showsPrec 9 a . showString " -> " . showsPrec 8 r xs | isTupleTyCon tycon -> showTuple xs | otherwise -> showParen (p > 9) $ showsPrec p tycon . showChar ' ' . showArgs (showChar ' ') tys showsTypeRep :: TypeRep -> ShowS showsTypeRep = shows instance Show TyCon where showsPrec _ t = showString (tyConName t) isTupleTyCon :: TyCon -> Bool isTupleTyCon (TyCon _ _ _ ('(':',':_)) = True isTupleTyCon _ = False -- Some (Show.TypeRep) helpers: showArgs :: Show a => ShowS -> [a] -> ShowS showArgs _ [] = id showArgs _ [a] = showsPrec 10 a showArgs sep (a:as) = showsPrec 10 a . sep . showArgs sep as showTuple :: [TypeRep] -> ShowS showTuple args = showChar '(' . showArgs (showChar ',') args . showChar ')' listTc :: TyCon listTc = typeRepTyCon (typeOf [()]) funTc :: TyCon funTc = typeRepTyCon (typeRep (Proxy :: Proxy (->))) ------------------------------------------------------------- -- -- Instances of the Typeable classes for Prelude types -- ------------------------------------------------------------- deriving instance Typeable () deriving instance Typeable [] deriving instance Typeable Maybe deriving instance Typeable Ratio deriving instance Typeable (->) deriving instance Typeable IO deriving instance Typeable Array deriving instance Typeable ST deriving instance Typeable STRef deriving instance Typeable STArray deriving instance Typeable (,) deriving instance Typeable (,,) deriving instance Typeable (,,,) deriving instance Typeable (,,,,) deriving instance Typeable (,,,,,) deriving instance Typeable (,,,,,,) deriving instance Typeable Ptr deriving instance Typeable FunPtr ------------------------------------------------------- -- -- Generate Typeable instances for standard datatypes -- ------------------------------------------------------- deriving instance Typeable Bool deriving instance Typeable Char deriving instance Typeable Float deriving instance Typeable Double deriving instance Typeable Int deriving instance Typeable Word deriving instance Typeable Integer deriving instance Typeable Ordering deriving instance Typeable Word8 deriving instance Typeable Word16 deriving instance Typeable Word32 deriving instance Typeable Word64 deriving instance Typeable TyCon deriving instance Typeable TypeRep deriving instance Typeable RealWorld deriving instance Typeable Proxy deriving instance Typeable (:~:) deriving instance Typeable Coercion
jwiegley/ghc-release
libraries/base/Data/Typeable/Internal.hs
gpl-3.0
12,150
0
15
2,842
2,883
1,616
1,267
209
2
module Homework where sum'n'count :: Integer -> (Integer, Integer) sum'n'count x | x == 0 = (0, 1) | otherwise = helper x where helper t | t == 0 = (0, 0) | otherwise = let rec_res = helper (quot t 10) in ((fst rec_res) + abs (rem t 10), (snd rec_res) + 1) integration :: (Double -> Double) -> Double -> Double -> Double integration f a b = let t = (b - a) / 1000 in let helper step acc | step == 1000 = acc | otherwise = let this_result = t * (f (a + step * t) + f (a + (step + 1) * t)) / 2 in helper (step + 1) (acc + this_result) in helper 0 0.0
ItsLastDay/academic_university_2016-2018
subjects/Haskell/4/homework.hs
gpl-3.0
671
0
25
249
327
163
164
14
1
{-# LANGUAGE DeriveDataTypeable, RecursiveDo, ScopedTypeVariables #-} module InnerEar.Exercises.MultipleChoice where import Reflex import Reflex.Dom import Reflex.Dom.Contrib.Widgets.ButtonGroup (radioGroup) import Reflex.Dom.Contrib.Widgets.Common import Data.Map import Control.Monad (zipWithM) import Control.Monad.IO.Class (liftIO) import Data.List (findIndices,partition,elemIndex) import Data.Maybe (fromJust) import System.Random import Text.JSON import Text.JSON.Generic import InnerEar.Types.ExerciseId import InnerEar.Types.Data hiding (Time) import InnerEar.Types.Exercise import InnerEar.Types.ExerciseNavigation import InnerEar.Types.Score import InnerEar.Types.MultipleChoiceStore import InnerEar.Types.Utility import InnerEar.Widgets.Utility import InnerEar.Widgets.AnswerButton import Sound.MusicW -- | This module introduces a function to generate multiple choice exercises. -- Most specifically, it abstracts over the requirement to provide a widget -- to present questions, requiring instead that a fixed list of possible -- answers be provided, together with a pure function that converts an answer -- value to a sound. -- | AnswerRenderer takes the system resources, a question configuration, sound source, -- and a potential answer and builds a `Synth` for that answer. If the answer is `Nothing` a -- reference synth should be constructed. type AnswerRenderer c a = Map String AudioBuffer -> c -> (SourceNodeSpec, Maybe Time) -> Maybe a -> Synth () -- | ConfigWidgetBuilder constructs a configuration widget with a given default configuration. type ConfigWidgetBuilder m t c a = Dynamic t (Map String AudioBuffer) -> c -> m (Dynamic t c, Dynamic t (Maybe (SourceNodeSpec, Maybe Time)), Event t (), Event t ()) multipleChoiceExercise :: forall t m c q a e s. (MonadWidget t m, Show a, Eq a, Ord a, Data a, Data c, Ord c,Buttonable a) => Int -- maximum number of tries to allow -> [a] -> m () -> ConfigWidgetBuilder m t c a -> AnswerRenderer c a -> ExerciseId -> c -> (Dynamic t (Map a Score) -> Dynamic t (MultipleChoiceStore c a) -> m ()) -> (c -> [ExerciseDatum] -> IO ([a],a)) -> (Map c (Map a Score) -> (Int,Int)) -- function to calculate Xp from a map of performance over all configurations -> Exercise t m c [a] a (Map a Score) (MultipleChoiceStore c a) multipleChoiceExercise maxTries answers iWidget cWidget render i c de g calculateXp = Exercise { exerciseId = i, instructionsWidget = iWidget, defaultConfig = c, defaultEvaluation = empty, displayEvaluation = de, generateQuestion = g, questionWidget = multipleChoiceQuestionWidget maxTries answers i iWidget cWidget render de calculateXp } multipleChoiceQuestionWidget :: forall t m c q a e s. (MonadWidget t m, Show a, Eq a, Ord a,Data a,Data c,Ord c, Buttonable a) => Int -- maximum number of tries -> [a] -- fixed list of potential answers -> ExerciseId -> m () -> ConfigWidgetBuilder m t c a -> AnswerRenderer c a -> (Dynamic t (Map a Score) -> Dynamic t (MultipleChoiceStore c a) -> m ()) -> (Map c (Map a Score) -> (Int,Int)) -> Dynamic t (Map String AudioBuffer) -> c -> Map a Score -> Event t ([a],a) -> m (Event t ExerciseDatum,Event t (Maybe (Synth ())),Event t c,Event t ExerciseNavigation) multipleChoiceQuestionWidget maxTries answers exId exInstructions cWidget render eWidget calculateXp sysResources config initialEval newQuestion = elClass "div" "exerciseWrapper" $ mdo let initialStore = MultipleChoiceStore { scores = empty, xp = (0,1) } -- normally this would come as an argument, then reset session specific elements of store let newScoreMaps = fmap (newScores calculateXp) $ updated evaluations let storeUpdates = newScoreMaps currentStore <- foldDyn ($) initialStore storeUpdates let initialState = initialMultipleChoiceState config answers maxTries let newQuestionAndConfig = attachDyn dynConfig newQuestion let newQuestion' = fmap (\(c, q) -> newQuestionMultipleChoiceState c q) newQuestionAndConfig questionHeard0 <- holdDyn False $ leftmost [False <$ newQuestion, True <$ listenPressed] let questionHeard = nubDyn questionHeard0 let questionHeard' = fmap (const onceQuestionHeard) $ ffilter (== True) $ updated questionHeard let answerPressed' = fmap answerSelected answerPressed let stateChanges = leftmost [newQuestion', questionHeard', answerPressed'] multipleChoiceState <- foldDyn ($) initialState stateChanges modes <- mapDyn answerButtonModes multipleChoiceState modes' <- mapM (\x-> mapDyn (!!x) modes) [0,1..9] -- scores <- mapDyn scoreMap multipleChoiceState scores <- combineDyn (\x y -> maybe empty id $ Data.Map.lookup x (scoreMap y)) dynConfig multipleChoiceState -- MC question controls and answer input. -- (Event t ExerciseNavigation, Event t (), Event t a, Event t ExerciseNavigation) (closeExercise, listenPressed, answerPressed, nextQuestionNav) <- elClass "div" "topRow" $ do w <- elClass "div" "topRowHeader" $ do elClass "div" "questionTitle" $ text $ ("Exercise: " ++ showExerciseTitle exId) elClass "div" "closeExerciseButton" $ buttonClass "Close" "closeExerciseButton" (x,y,z) <- elClass "div" "buttonInterface" $ do x <- elClass "div" "listenButton" $ buttonClass "Listen" "listenButton" y <- elClass "div" "answerButtonWrapper" $ do -- leftmost <$> zipWithM (\f m -> answerButton (show f) m f) answers modes' leftmost <$> zipWithM makeButton answers modes' z <- elClass "div" "nextButton" $ revealableButton "Next" "nextButton" questionHeard return (x, y, z) return (CloseExercise <$ w, x, y, InQuestion <$ z) -- Instructions and configuration widgets. -- (Dynamic t c, Dynamic t (Maybe SourceNodeSpec), Event t (), Event t ()) (dynConfig, dynSource, playPressed, stopPressed) <- elClass "div" "middleRow" $ do elClass "div" "evaluation" $ exInstructions elClass "div" "journal" $ do text "Configuration" elClass "div" "configWidgetWrapper" $ cWidget sysResources config journalData <- elClass "div" "bottomRow" $ do elClass "div" "evaluation" $ do eWidget scores currentStore elClass "div" "journal" $ journalWidget let answerEvent = gate (fmap (==AnswerMode) . fmap mode . current $ multipleChoiceState) answerPressed let exploreAnswerPressed = gate (fmap (==ExploreMode) . fmap mode . current $ multipleChoiceState) answerPressed -- generate sounds to be played answer <- holdDyn Nothing $ fmap (Just . snd) newQuestion let listenToQuestionPressed = fmapMaybe id $ tagDyn answer listenPressed playbackSynthChanged <- connectPlaybackControls listenToQuestionPressed exploreAnswerPressed playPressed stopPressed dynConfig dynSource sysResources render let navEvents = leftmost [closeExercise, nextQuestionNav] -- generate data for adaptive questions and analysis let questionWhileListened = (\x -> (possibleAnswers x, correctAnswer x)) <$> tagDyn multipleChoiceState listenPressed let listenedQuestionData = attachDynWith (\c (q, a)-> ListenedQuestion c q a) dynConfig questionWhileListened let questionWhileReference = (\x -> (possibleAnswers x,correctAnswer x)) <$> tagDyn multipleChoiceState playPressed let listenedReferenceData = attachDynWith (\c (q, a) -> ListenedReference c q a) dynConfig questionWhileReference evaluations <- mapDyn scoreMap multipleChoiceState mcsAndConfig <- combineDyn (,) dynConfig multipleChoiceState let answerWithContext = attachDynWith (\(c,mcs) s -> (s, c, possibleAnswers mcs, correctAnswer mcs)) mcsAndConfig answerEvent let tempHack k m = findWithDefault empty k m let answerData = attachDynWith (\e (s,c,q,a) -> Answered s (tempHack c e) (tempHack c e) c q a) evaluations answerWithContext let questionWhileExplore = attachDynWith (\x y -> (possibleAnswers x,correctAnswer x,y)) multipleChoiceState answerPressed let listenedExploreData = attachDynWith (\c (q,a,s) -> ListenedExplore s c q a) dynConfig questionWhileExplore let datums = leftmost [listenedQuestionData,listenedReferenceData, answerData,listenedExploreData,journalData] :: Event t (Datum c [a] a (Map a Score) (MultipleChoiceStore c a)) let datums' = fmap toExerciseDatum datums return (datums', playbackSynthChanged, updated dynConfig, navEvents) connectPlaybackControls :: MonadWidget t m => Event t a -> Event t a -> Event t () -> Event t () -> Dynamic t c -> Dynamic t (Maybe (SourceNodeSpec, Maybe Time)) -> Dynamic t (Map String AudioBuffer) -> (Map String AudioBuffer -> c -> (SourceNodeSpec, Maybe Time) -> Maybe a -> Synth ()) -> m (Event t (Maybe (Synth ()))) connectPlaybackControls playQuestion exploreAnswer playReference stop dynConfig dynSrc sysResources render = do let triggerPlay = leftmost [Just <$> playQuestion, Just <$> exploreAnswer, Nothing <$ playReference] let triggerStop = Nothing <$ stop render' <- mapDyn render sysResources -- Dynamic t (c -> (SourceNodeSpec, Maybe Time) -> Maybe a -> Synth ()) render'' <- combineDyn ($) render' dynConfig -- Dynamic t ((SourceNodeSpec,Maybe Time) -> Maybe a -> Synth ()) render''' <- combineDyn (\x y -> maybe (const Nothing) (\z -> Just . x z) y) render'' dynSrc let triggerPlay' = attachDynWith ($) render''' triggerPlay return $ leftmost [triggerStop, triggerPlay'] journalWidget :: MonadWidget t m => m (Event t (Datum c q a e s)) journalWidget = elClass "div" "journalItem" $ mdo let attrs = constDyn $ fromList $ zip ["class"] ["journalItem"] let resetText = "" <$ b text "Journal" t <- textArea $ def & textAreaConfig_attributes .~ attrs & textAreaConfig_setValue .~ resetText b <- button "Save" return $ Reflection <$> tag (current $ _textArea_value t) b randomMultipleChoiceQuestion :: [a] -> IO ([a],a) randomMultipleChoiceQuestion possibilities = do let n = length possibilities x <- getStdRandom ((randomR (0,n-1))::StdGen -> (Int,StdGen)) return (possibilities,possibilities!!x) radioConfigWidget :: (MonadWidget t m, Eq a, Show a) => String -> String -> [a] -> a -> m (Event t a) radioConfigWidget explanation msg possibilities i = do let radioButtonMap = zip [0::Int,1..] possibilities let iVal = maybe 0 id $ elemIndex i possibilities elClass "div" "explanation" $ text explanation elClass "div" "configText" $ text msg radioWidget <- radioGroup (constDyn "radioWidget") (constDyn $ fmap (\(x,y)->(x,show y)) radioButtonMap) (WidgetConfig {_widgetConfig_initialValue= Just iVal ,_widgetConfig_setValue = never ,_widgetConfig_attributes = constDyn empty}) dynConfig <- holdDyn i $ fmap (\x-> maybe i id $ Data.Map.lookup (maybe 0 id x) (fromList radioButtonMap)) (_hwidget_change radioWidget) b <- button "Begin Exercise" return $ tagDyn dynConfig b trivialBWidget :: MonadWidget t m => m (Dynamic t ()) trivialBWidget = holdDyn () $ never data MultipleChoiceMode = ListenMode | AnswerMode | ExploreMode deriving (Eq) data MultipleChoiceState a c = MultipleChoiceState { mode :: MultipleChoiceMode, currentConfig :: c, correctAnswer :: a, allAnswers :: [a], possibleAnswers :: [a], answerButtonModes :: [AnswerButtonMode], attemptsRemainingDefault :: Int, attemptsRemaining :: Int, scoreMap :: Map c (Map a Score) } -- initialMultipleChoiceState provides a useful initial configuration of -- the MultipleChoiceState for the time before a new question has been -- generated. initialMultipleChoiceState :: Ord c => c -> [a] -> Int -> MultipleChoiceState a c initialMultipleChoiceState c xs n = MultipleChoiceState { mode = ListenMode, currentConfig = c, correctAnswer = xs!!0, allAnswers = xs, possibleAnswers = xs, answerButtonModes = NotPossible <$ xs, attemptsRemainingDefault = n, attemptsRemaining = n, scoreMap = empty } -- When a multiple choice question is generated, all of the buttons are -- not possible, pending the user listening to the correct answer. newQuestionMultipleChoiceState :: Ord c => c -> ([a],a) -> MultipleChoiceState a c -> MultipleChoiceState a c newQuestionMultipleChoiceState c (xs,x) s = s { mode = ListenMode, currentConfig = c, correctAnswer = x, possibleAnswers = xs, answerButtonModes = NotPossible <$ allAnswers s, attemptsRemaining = attemptsRemainingDefault s } -- Once the user has listened to the correct answer at least once, all -- of the buttons that represent possible answers become possible and the -- mode changes to AnswerMode (the only mode in which answers are processed) onceQuestionHeard :: Eq a => MultipleChoiceState a c -> MultipleChoiceState a c onceQuestionHeard s = s { mode = AnswerMode, answerButtonModes = m } where m = fmap f $ fmap (flip elem $ possibleAnswers s) $ allAnswers s f True = Possible f False = NotPossible -- When answers are selected they are ignored if mode is ListenMode or ExploreMode -- Otherwise (i.e. AnswerMode) the state is updated in different ways depending -- on whether the answer is correct or incorrect, and answerSelected :: (Eq a,Ord a,Ord c) => a -> MultipleChoiceState a c -> MultipleChoiceState a c answerSelected _ s | mode s == ListenMode = s answerSelected _ s | mode s == ExploreMode = s answerSelected a s | a == correctAnswer s = toExploreMode $ s { answerButtonModes = replaceAtSameIndex a (allAnswers s) Correct (answerButtonModes s), scoreMap = insert (currentConfig s) newSpecificMap (scoreMap s) } where newSpecificMap = markCorrect a $ findWithDefault empty (currentConfig s) (scoreMap s) answerSelected a s | a /= correctAnswer s && attemptsRemaining s > 1 = s { answerButtonModes = replaceAtSameIndex a (allAnswers s) IncorrectDisactivated (answerButtonModes s), attemptsRemaining = attemptsRemaining s - 1, scoreMap = insert (currentConfig s) newSpecificMap (scoreMap s) } where newSpecificMap = markIncorrect a (correctAnswer s)$ findWithDefault empty (currentConfig s) (scoreMap s) answerSelected a s | a /= correctAnswer s && attemptsRemaining s <= 1 = toExploreMode $ s { answerButtonModes = replaceAtSameIndex a (allAnswers s) IncorrectActivated $ replaceAtSameIndex (correctAnswer s) (allAnswers s) CorrectMissed (answerButtonModes s), scoreMap = insert (currentConfig s) newSpecificMap (scoreMap s) } where newSpecificMap = markIncorrect a (correctAnswer s) $ findWithDefault empty (currentConfig s) (scoreMap s) toExploreMode :: MultipleChoiceState a c -> MultipleChoiceState a c toExploreMode s = s { mode = ExploreMode, answerButtonModes = fmap f $ answerButtonModes s } where f NotPossible = NotPossible f Possible = Possible f IncorrectDisactivated = IncorrectActivated f IncorrectActivated = IncorrectActivated f Correct = Correct f CorrectMissed = CorrectMissed
luisnavarrodelangel/InnerEar
src/InnerEar/Exercises/MultipleChoice.hs
gpl-3.0
14,844
0
26
2,635
4,414
2,265
2,149
227
6
module Main where import Control.Monad.IO.Class import System.Environment import System.Console.GetOpt (getOpt, OptDescr(..), ArgDescr(..), ArgOrder(..)) import Network.URI import OHS.Client main = do argv <- getArgs let (Options host port, rest) = case getOpt Permute globalArgSpec argv of (o,r,[] ) -> (foldr id (Options "localhost" "1234") o, r) (_,_,errs) -> error $ "Parsing command line options failed: " ++ concat errs case (rest) of ["login", uri, uid, ua] -> do let Just uri' = parseURI uri print =<< runOHST host port (login uri' (UId uid)) ["register", _url, _locator, _cookies] -> print =<< runOHST host port register -- mock "login":_ -> putStrLn $ usage "login" "register":_ -> putStrLn $ usage "register" _ -> putStrLn "Usage: login | register ..." usage "login" = "Usage: login URL USER_ID USER_AGENT" usage "register" = "Usage: register URL LOCATOR COOKIES" option :: [Char] -> [String] -> String -> ArgDescr a -> OptDescr a option s l udsc dsc = Option s l dsc udsc reqArg :: String -> (String -> a) -> ArgDescr a reqArg udsc dsc = ReqArg dsc udsc data Options = Options { optServer :: String , optPort :: String } globalArgSpec :: [OptDescr (Options -> Options)] globalArgSpec = [ option "" ["server"] "Server to connect to" $ reqArg "SERVER" $ \s o -> o { optServer = s } , option "" ["port"] "TCP port to connect to" $ reqArg "PORT" $ \s o -> o { optPort = s } ]
DanielG/ohs
src/OHScli/Cli.hs
gpl-3.0
1,545
0
17
398
543
290
253
36
6
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Dataflow.Projects.Locations.Jobs.Messages.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Request the job status. -- -- /See:/ <https://cloud.google.com/dataflow Google Dataflow API Reference> for @dataflow.projects.locations.jobs.messages.list@. module Network.Google.Resource.Dataflow.Projects.Locations.Jobs.Messages.List ( -- * REST Resource ProjectsLocationsJobsMessagesListResource -- * Creating a Request , projectsLocationsJobsMessagesList , ProjectsLocationsJobsMessagesList -- * Request Lenses , pljmlXgafv , pljmlJobId , pljmlUploadProtocol , pljmlLocation , pljmlStartTime , pljmlPp , pljmlAccessToken , pljmlUploadType , pljmlBearerToken , pljmlEndTime , pljmlMinimumImportance , pljmlPageToken , pljmlProjectId , pljmlPageSize , pljmlCallback ) where import Network.Google.Dataflow.Types import Network.Google.Prelude -- | A resource alias for @dataflow.projects.locations.jobs.messages.list@ method which the -- 'ProjectsLocationsJobsMessagesList' request conforms to. type ProjectsLocationsJobsMessagesListResource = "v1b3" :> "projects" :> Capture "projectId" Text :> "locations" :> Capture "location" Text :> "jobs" :> Capture "jobId" Text :> "messages" :> QueryParam "$.xgafv" Text :> QueryParam "upload_protocol" Text :> QueryParam "startTime" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "endTime" Text :> QueryParam "minimumImportance" Text :> QueryParam "pageToken" Text :> QueryParam "pageSize" (Textual Int32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ListJobMessagesResponse -- | Request the job status. -- -- /See:/ 'projectsLocationsJobsMessagesList' smart constructor. data ProjectsLocationsJobsMessagesList = ProjectsLocationsJobsMessagesList' { _pljmlXgafv :: !(Maybe Text) , _pljmlJobId :: !Text , _pljmlUploadProtocol :: !(Maybe Text) , _pljmlLocation :: !Text , _pljmlStartTime :: !(Maybe Text) , _pljmlPp :: !Bool , _pljmlAccessToken :: !(Maybe Text) , _pljmlUploadType :: !(Maybe Text) , _pljmlBearerToken :: !(Maybe Text) , _pljmlEndTime :: !(Maybe Text) , _pljmlMinimumImportance :: !(Maybe Text) , _pljmlPageToken :: !(Maybe Text) , _pljmlProjectId :: !Text , _pljmlPageSize :: !(Maybe (Textual Int32)) , _pljmlCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProjectsLocationsJobsMessagesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pljmlXgafv' -- -- * 'pljmlJobId' -- -- * 'pljmlUploadProtocol' -- -- * 'pljmlLocation' -- -- * 'pljmlStartTime' -- -- * 'pljmlPp' -- -- * 'pljmlAccessToken' -- -- * 'pljmlUploadType' -- -- * 'pljmlBearerToken' -- -- * 'pljmlEndTime' -- -- * 'pljmlMinimumImportance' -- -- * 'pljmlPageToken' -- -- * 'pljmlProjectId' -- -- * 'pljmlPageSize' -- -- * 'pljmlCallback' projectsLocationsJobsMessagesList :: Text -- ^ 'pljmlJobId' -> Text -- ^ 'pljmlLocation' -> Text -- ^ 'pljmlProjectId' -> ProjectsLocationsJobsMessagesList projectsLocationsJobsMessagesList pPljmlJobId_ pPljmlLocation_ pPljmlProjectId_ = ProjectsLocationsJobsMessagesList' { _pljmlXgafv = Nothing , _pljmlJobId = pPljmlJobId_ , _pljmlUploadProtocol = Nothing , _pljmlLocation = pPljmlLocation_ , _pljmlStartTime = Nothing , _pljmlPp = True , _pljmlAccessToken = Nothing , _pljmlUploadType = Nothing , _pljmlBearerToken = Nothing , _pljmlEndTime = Nothing , _pljmlMinimumImportance = Nothing , _pljmlPageToken = Nothing , _pljmlProjectId = pPljmlProjectId_ , _pljmlPageSize = Nothing , _pljmlCallback = Nothing } -- | V1 error format. pljmlXgafv :: Lens' ProjectsLocationsJobsMessagesList (Maybe Text) pljmlXgafv = lens _pljmlXgafv (\ s a -> s{_pljmlXgafv = a}) -- | The job to get messages about. pljmlJobId :: Lens' ProjectsLocationsJobsMessagesList Text pljmlJobId = lens _pljmlJobId (\ s a -> s{_pljmlJobId = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pljmlUploadProtocol :: Lens' ProjectsLocationsJobsMessagesList (Maybe Text) pljmlUploadProtocol = lens _pljmlUploadProtocol (\ s a -> s{_pljmlUploadProtocol = a}) -- | The location which contains the job specified by job_id. pljmlLocation :: Lens' ProjectsLocationsJobsMessagesList Text pljmlLocation = lens _pljmlLocation (\ s a -> s{_pljmlLocation = a}) -- | If specified, return only messages with timestamps >= start_time. The -- default is the job creation time (i.e. beginning of messages). pljmlStartTime :: Lens' ProjectsLocationsJobsMessagesList (Maybe Text) pljmlStartTime = lens _pljmlStartTime (\ s a -> s{_pljmlStartTime = a}) -- | Pretty-print response. pljmlPp :: Lens' ProjectsLocationsJobsMessagesList Bool pljmlPp = lens _pljmlPp (\ s a -> s{_pljmlPp = a}) -- | OAuth access token. pljmlAccessToken :: Lens' ProjectsLocationsJobsMessagesList (Maybe Text) pljmlAccessToken = lens _pljmlAccessToken (\ s a -> s{_pljmlAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pljmlUploadType :: Lens' ProjectsLocationsJobsMessagesList (Maybe Text) pljmlUploadType = lens _pljmlUploadType (\ s a -> s{_pljmlUploadType = a}) -- | OAuth bearer token. pljmlBearerToken :: Lens' ProjectsLocationsJobsMessagesList (Maybe Text) pljmlBearerToken = lens _pljmlBearerToken (\ s a -> s{_pljmlBearerToken = a}) -- | Return only messages with timestamps \< end_time. The default is now -- (i.e. return up to the latest messages available). pljmlEndTime :: Lens' ProjectsLocationsJobsMessagesList (Maybe Text) pljmlEndTime = lens _pljmlEndTime (\ s a -> s{_pljmlEndTime = a}) -- | Filter to only get messages with importance >= level pljmlMinimumImportance :: Lens' ProjectsLocationsJobsMessagesList (Maybe Text) pljmlMinimumImportance = lens _pljmlMinimumImportance (\ s a -> s{_pljmlMinimumImportance = a}) -- | If supplied, this should be the value of next_page_token returned by an -- earlier call. This will cause the next page of results to be returned. pljmlPageToken :: Lens' ProjectsLocationsJobsMessagesList (Maybe Text) pljmlPageToken = lens _pljmlPageToken (\ s a -> s{_pljmlPageToken = a}) -- | A project id. pljmlProjectId :: Lens' ProjectsLocationsJobsMessagesList Text pljmlProjectId = lens _pljmlProjectId (\ s a -> s{_pljmlProjectId = a}) -- | If specified, determines the maximum number of messages to return. If -- unspecified, the service may choose an appropriate default, or may -- return an arbitrarily large number of results. pljmlPageSize :: Lens' ProjectsLocationsJobsMessagesList (Maybe Int32) pljmlPageSize = lens _pljmlPageSize (\ s a -> s{_pljmlPageSize = a}) . mapping _Coerce -- | JSONP pljmlCallback :: Lens' ProjectsLocationsJobsMessagesList (Maybe Text) pljmlCallback = lens _pljmlCallback (\ s a -> s{_pljmlCallback = a}) instance GoogleRequest ProjectsLocationsJobsMessagesList where type Rs ProjectsLocationsJobsMessagesList = ListJobMessagesResponse type Scopes ProjectsLocationsJobsMessagesList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email"] requestClient ProjectsLocationsJobsMessagesList'{..} = go _pljmlProjectId _pljmlLocation _pljmlJobId _pljmlXgafv _pljmlUploadProtocol _pljmlStartTime (Just _pljmlPp) _pljmlAccessToken _pljmlUploadType _pljmlBearerToken _pljmlEndTime _pljmlMinimumImportance _pljmlPageToken _pljmlPageSize _pljmlCallback (Just AltJSON) dataflowService where go = buildClient (Proxy :: Proxy ProjectsLocationsJobsMessagesListResource) mempty
rueshyna/gogol
gogol-dataflow/gen/Network/Google/Resource/Dataflow/Projects/Locations/Jobs/Messages/List.hs
mpl-2.0
9,732
0
28
2,604
1,444
830
614
212
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.CivicInfo.Types -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.CivicInfo.Types ( -- * Service Configuration civicInfoService -- * RepresentativeInfoResponseDivisions , RepresentativeInfoResponseDivisions , representativeInfoResponseDivisions , rirdAddtional -- * VoterInfoResponse , VoterInfoResponse , voterInfoResponse , virOtherElections , virContests , virState , virKind , virDropOffLocations , virElection , virNormalizedInput , virMailOnly , virEarlyVoteSites , virPollingLocations , virPrecinctId -- * PollingLocation , PollingLocation , pollingLocation , plVoterServices , plEndDate , plSources , plAddress , plStartDate , plPollingHours , plName , plId , plNotes -- * RepresentativesRepresentativeInfoByDivisionLevels , RepresentativesRepresentativeInfoByDivisionLevels (..) -- * GeographicDivision , GeographicDivision , geographicDivision , gdName , gdOfficeIndices , gdAlsoKnownAs -- * Candidate , Candidate , candidate , cEmail , cPhone , cPhotoURL , cChannels , cCandidateURL , cOrderOnBallot , cName , cParty -- * RepresentativesRepresentativeInfoByAddressLevels , RepresentativesRepresentativeInfoByAddressLevels (..) -- * Office , Office , office , oDivisionId , oRoles , oOfficialIndices , oSources , oName , oLevels -- * RepresentativesRepresentativeInfoByDivisionRoles , RepresentativesRepresentativeInfoByDivisionRoles (..) -- * ElectionsQueryRequest , ElectionsQueryRequest , electionsQueryRequest , eqrContextParams -- * Channel , Channel , channel , cId , cType -- * Election , Election , election , eOcdDivisionId , eElectionDay , eName , eId -- * RepresentativeInfoResponse , RepresentativeInfoResponse , representativeInfoResponse , rirKind , rirNormalizedInput , rirOfficials , rirDivisions , rirOffices -- * VoterInfoSegmentResult , VoterInfoSegmentResult , voterInfoSegmentResult , visrResponse , visrGeneratedMillis , visrPostalAddress , visrRequest -- * DivisionSearchResult , DivisionSearchResult , divisionSearchResult , dsrAliases , dsrName , dsrOcdId -- * DivisionSearchRequest , DivisionSearchRequest , divisionSearchRequest , dsrContextParams -- * AdministrativeBody , AdministrativeBody , administrativeBody , abCorrespondenceAddress , abAbsenteeVotingInfoURL , abHoursOfOperation , abBallotInfoURL , abPhysicalAddress , abElectionRegistrationConfirmationURL , abElectionInfoURL , abVotingLocationFinderURL , abElectionOfficials , abName , abElectionRulesURL , abAddressLines , abVoterServices , abElectionRegistrationURL -- * RepresentativeInfoRequest , RepresentativeInfoRequest , representativeInfoRequest , rirContextParams -- * Contest , Contest , contest , conReferendumPassageThreshold , conRoles , conReferendumURL , conReferendumEffectOfAbstain , conReferendumSubtitle , conNumberVotingFor , conOffice , conReferendumConStatement , conSources , conReferendumProStatement , conReferendumBallotResponses , conNumberElected , conSpecial , conReferendumText , conPrimaryParty , conId , conType , conElectorateSpecifications , conReferendumBrief , conDistrict , conLevel , conCandidates , conReferendumTitle , conBallotPlacement -- * DivisionSearchResponse , DivisionSearchResponse , divisionSearchResponse , dsrResults , dsrKind -- * RepresentativeInfoDataDivisions , RepresentativeInfoDataDivisions , representativeInfoDataDivisions , riddAddtional -- * RepresentativesRepresentativeInfoByAddressRoles , RepresentativesRepresentativeInfoByAddressRoles (..) -- * ElectionOfficial , ElectionOfficial , electionOfficial , eoFaxNumber , eoName , eoOfficePhoneNumber , eoEmailAddress , eoTitle -- * RepresentativeInfoData , RepresentativeInfoData , representativeInfoData , ridOfficials , ridDivisions , ridOffices -- * Source , Source , source , sName , sOfficial -- * DivisionRepresentativeInfoRequest , DivisionRepresentativeInfoRequest , divisionRepresentativeInfoRequest , drirContextParams -- * ElectoralDistrict , ElectoralDistrict , electoralDistrict , edKgForeignKey , edName , edScope , edId -- * VoterInfoRequest , VoterInfoRequest , voterInfoRequest , virVoterInfoSegmentResult , virContextParams -- * SimpleAddressType , SimpleAddressType , simpleAddressType , satLine2 , satState , satLine3 , satZip , satCity , satLine1 , satLocationName -- * ContextParams , ContextParams , contextParams , cpClientProFile -- * PostalAddress , PostalAddress , postalAddress , paAdministrativeAreaName , paRecipientName , paLanguageCode , paSortingCode , paPremiseName , paPostalCodeNumberExtension , paCountryNameCode , paDependentThoroughfaresConnector , paThoroughfareLeadingType , paSubAdministrativeAreaName , paThoroughfareTrailingType , paPostBoxNumber , paThoroughfarePreDirection , paLocalityName , paDependentThoroughfaresType , paThoroughfarePostDirection , paIsDisputed , paDependentThoroughfarePreDirection , paThoroughfareNumber , paDependentThoroughfaresIndicator , paDependentLocalityName , paFirmName , paCountryName , paDependentThoroughfareTrailingType , paDependentThoroughfareName , paDependentThoroughfarePostDirection , paAddressLines , paPostalCodeNumber , paThoroughfareName , paSubPremiseName , paDependentThoroughfareLeadingType -- * AdministrationRegion , AdministrationRegion , administrationRegion , arLocalJurisdiction , arSources , arName , arElectionAdministrationBody , arId -- * ElectionsQueryResponse , ElectionsQueryResponse , electionsQueryResponse , eqrKind , eqrElections -- * Official , Official , official , offPhotoURL , offURLs , offChannels , offAddress , offPhones , offName , offEmails , offParty ) where import Network.Google.CivicInfo.Types.Product import Network.Google.CivicInfo.Types.Sum import Network.Google.Prelude -- | Default request referring to version 'v2' of the Google Civic Information API. This contains the host and root path used as a starting point for constructing service requests. civicInfoService :: ServiceConfig civicInfoService = defaultService (ServiceId "civicinfo:v2") "www.googleapis.com"
rueshyna/gogol
gogol-civicinfo/gen/Network/Google/CivicInfo/Types.hs
mpl-2.0
7,542
0
7
1,893
827
568
259
251
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Container.Projects.Zones.Operations.Cancel -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Cancels the specified operation. -- -- /See:/ <https://cloud.google.com/container-engine/ Kubernetes Engine API Reference> for @container.projects.zones.operations.cancel@. module Network.Google.Resource.Container.Projects.Zones.Operations.Cancel ( -- * REST Resource ProjectsZonesOperationsCancelResource -- * Creating a Request , projectsZonesOperationsCancel , ProjectsZonesOperationsCancel -- * Request Lenses , pzocXgafv , pzocUploadProtocol , pzocAccessToken , pzocUploadType , pzocZone , pzocPayload , pzocProjectId , pzocOperationId , pzocCallback ) where import Network.Google.Container.Types import Network.Google.Prelude -- | A resource alias for @container.projects.zones.operations.cancel@ method which the -- 'ProjectsZonesOperationsCancel' request conforms to. type ProjectsZonesOperationsCancelResource = "v1" :> "projects" :> Capture "projectId" Text :> "zones" :> Capture "zone" Text :> "operations" :> CaptureMode "operationId" "cancel" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] CancelOperationRequest :> Post '[JSON] Empty -- | Cancels the specified operation. -- -- /See:/ 'projectsZonesOperationsCancel' smart constructor. data ProjectsZonesOperationsCancel = ProjectsZonesOperationsCancel' { _pzocXgafv :: !(Maybe Xgafv) , _pzocUploadProtocol :: !(Maybe Text) , _pzocAccessToken :: !(Maybe Text) , _pzocUploadType :: !(Maybe Text) , _pzocZone :: !Text , _pzocPayload :: !CancelOperationRequest , _pzocProjectId :: !Text , _pzocOperationId :: !Text , _pzocCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsZonesOperationsCancel' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pzocXgafv' -- -- * 'pzocUploadProtocol' -- -- * 'pzocAccessToken' -- -- * 'pzocUploadType' -- -- * 'pzocZone' -- -- * 'pzocPayload' -- -- * 'pzocProjectId' -- -- * 'pzocOperationId' -- -- * 'pzocCallback' projectsZonesOperationsCancel :: Text -- ^ 'pzocZone' -> CancelOperationRequest -- ^ 'pzocPayload' -> Text -- ^ 'pzocProjectId' -> Text -- ^ 'pzocOperationId' -> ProjectsZonesOperationsCancel projectsZonesOperationsCancel pPzocZone_ pPzocPayload_ pPzocProjectId_ pPzocOperationId_ = ProjectsZonesOperationsCancel' { _pzocXgafv = Nothing , _pzocUploadProtocol = Nothing , _pzocAccessToken = Nothing , _pzocUploadType = Nothing , _pzocZone = pPzocZone_ , _pzocPayload = pPzocPayload_ , _pzocProjectId = pPzocProjectId_ , _pzocOperationId = pPzocOperationId_ , _pzocCallback = Nothing } -- | V1 error format. pzocXgafv :: Lens' ProjectsZonesOperationsCancel (Maybe Xgafv) pzocXgafv = lens _pzocXgafv (\ s a -> s{_pzocXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pzocUploadProtocol :: Lens' ProjectsZonesOperationsCancel (Maybe Text) pzocUploadProtocol = lens _pzocUploadProtocol (\ s a -> s{_pzocUploadProtocol = a}) -- | OAuth access token. pzocAccessToken :: Lens' ProjectsZonesOperationsCancel (Maybe Text) pzocAccessToken = lens _pzocAccessToken (\ s a -> s{_pzocAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pzocUploadType :: Lens' ProjectsZonesOperationsCancel (Maybe Text) pzocUploadType = lens _pzocUploadType (\ s a -> s{_pzocUploadType = a}) -- | Deprecated. The name of the Google Compute Engine -- [zone](https:\/\/cloud.google.com\/compute\/docs\/zones#available) in -- which the operation resides. This field has been deprecated and replaced -- by the name field. pzocZone :: Lens' ProjectsZonesOperationsCancel Text pzocZone = lens _pzocZone (\ s a -> s{_pzocZone = a}) -- | Multipart request metadata. pzocPayload :: Lens' ProjectsZonesOperationsCancel CancelOperationRequest pzocPayload = lens _pzocPayload (\ s a -> s{_pzocPayload = a}) -- | Deprecated. The Google Developers Console [project ID or project -- number](https:\/\/support.google.com\/cloud\/answer\/6158840). This -- field has been deprecated and replaced by the name field. pzocProjectId :: Lens' ProjectsZonesOperationsCancel Text pzocProjectId = lens _pzocProjectId (\ s a -> s{_pzocProjectId = a}) -- | Deprecated. The server-assigned \`name\` of the operation. This field -- has been deprecated and replaced by the name field. pzocOperationId :: Lens' ProjectsZonesOperationsCancel Text pzocOperationId = lens _pzocOperationId (\ s a -> s{_pzocOperationId = a}) -- | JSONP pzocCallback :: Lens' ProjectsZonesOperationsCancel (Maybe Text) pzocCallback = lens _pzocCallback (\ s a -> s{_pzocCallback = a}) instance GoogleRequest ProjectsZonesOperationsCancel where type Rs ProjectsZonesOperationsCancel = Empty type Scopes ProjectsZonesOperationsCancel = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsZonesOperationsCancel'{..} = go _pzocProjectId _pzocZone _pzocOperationId _pzocXgafv _pzocUploadProtocol _pzocAccessToken _pzocUploadType _pzocCallback (Just AltJSON) _pzocPayload containerService where go = buildClient (Proxy :: Proxy ProjectsZonesOperationsCancelResource) mempty
brendanhay/gogol
gogol-container/gen/Network/Google/Resource/Container/Projects/Zones/Operations/Cancel.hs
mpl-2.0
6,765
0
21
1,559
946
552
394
141
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Gmail.Users.Drafts.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the specified draft. -- -- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.drafts.get@. module Network.Google.Resource.Gmail.Users.Drafts.Get ( -- * REST Resource UsersDraftsGetResource -- * Creating a Request , usersDraftsGet , UsersDraftsGet -- * Request Lenses , udgXgafv , udgUploadProtocol , udgAccessToken , udgFormat , udgUploadType , udgUserId , udgId , udgCallback ) where import Network.Google.Gmail.Types import Network.Google.Prelude -- | A resource alias for @gmail.users.drafts.get@ method which the -- 'UsersDraftsGet' request conforms to. type UsersDraftsGetResource = "gmail" :> "v1" :> "users" :> Capture "userId" Text :> "drafts" :> Capture "id" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "format" UsersDraftsGetFormat :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Draft -- | Gets the specified draft. -- -- /See:/ 'usersDraftsGet' smart constructor. data UsersDraftsGet = UsersDraftsGet' { _udgXgafv :: !(Maybe Xgafv) , _udgUploadProtocol :: !(Maybe Text) , _udgAccessToken :: !(Maybe Text) , _udgFormat :: !UsersDraftsGetFormat , _udgUploadType :: !(Maybe Text) , _udgUserId :: !Text , _udgId :: !Text , _udgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UsersDraftsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'udgXgafv' -- -- * 'udgUploadProtocol' -- -- * 'udgAccessToken' -- -- * 'udgFormat' -- -- * 'udgUploadType' -- -- * 'udgUserId' -- -- * 'udgId' -- -- * 'udgCallback' usersDraftsGet :: Text -- ^ 'udgId' -> UsersDraftsGet usersDraftsGet pUdgId_ = UsersDraftsGet' { _udgXgafv = Nothing , _udgUploadProtocol = Nothing , _udgAccessToken = Nothing , _udgFormat = UDGFFull , _udgUploadType = Nothing , _udgUserId = "me" , _udgId = pUdgId_ , _udgCallback = Nothing } -- | V1 error format. udgXgafv :: Lens' UsersDraftsGet (Maybe Xgafv) udgXgafv = lens _udgXgafv (\ s a -> s{_udgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). udgUploadProtocol :: Lens' UsersDraftsGet (Maybe Text) udgUploadProtocol = lens _udgUploadProtocol (\ s a -> s{_udgUploadProtocol = a}) -- | OAuth access token. udgAccessToken :: Lens' UsersDraftsGet (Maybe Text) udgAccessToken = lens _udgAccessToken (\ s a -> s{_udgAccessToken = a}) -- | The format to return the draft in. udgFormat :: Lens' UsersDraftsGet UsersDraftsGetFormat udgFormat = lens _udgFormat (\ s a -> s{_udgFormat = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). udgUploadType :: Lens' UsersDraftsGet (Maybe Text) udgUploadType = lens _udgUploadType (\ s a -> s{_udgUploadType = a}) -- | The user\'s email address. The special value \`me\` can be used to -- indicate the authenticated user. udgUserId :: Lens' UsersDraftsGet Text udgUserId = lens _udgUserId (\ s a -> s{_udgUserId = a}) -- | The ID of the draft to retrieve. udgId :: Lens' UsersDraftsGet Text udgId = lens _udgId (\ s a -> s{_udgId = a}) -- | JSONP udgCallback :: Lens' UsersDraftsGet (Maybe Text) udgCallback = lens _udgCallback (\ s a -> s{_udgCallback = a}) instance GoogleRequest UsersDraftsGet where type Rs UsersDraftsGet = Draft type Scopes UsersDraftsGet = '["https://mail.google.com/", "https://www.googleapis.com/auth/gmail.compose", "https://www.googleapis.com/auth/gmail.modify", "https://www.googleapis.com/auth/gmail.readonly"] requestClient UsersDraftsGet'{..} = go _udgUserId _udgId _udgXgafv _udgUploadProtocol _udgAccessToken (Just _udgFormat) _udgUploadType _udgCallback (Just AltJSON) gmailService where go = buildClient (Proxy :: Proxy UsersDraftsGetResource) mempty
brendanhay/gogol
gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Drafts/Get.hs
mpl-2.0
5,217
0
20
1,320
859
500
359
124
1
-- -- Copyright (c) 2005, 2012 Stefan Wehr - http://www.stefanwehr.de -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library 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 -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA -- {- | This module defines types and functions dealing with source code locations. -} module Test.Framework.Location ( Location, unknownLocation, fileName, lineNumber, showLoc, makeLoc ) where -- | An abstract type representing locations in a file. data Location = Location String Int deriving (Eq, Ord, Show, Read) -- | Render a 'Location' as a 'String'. showLoc :: Location -> String showLoc (Location f n) = f ++ ":" ++ show n -- | Extract the file name of a 'Location'. fileName :: Location -> String fileName (Location f _ ) = f -- | Extract the line number of a 'Location'. lineNumber :: Location -> Int lineNumber (Location _ i) = i -- | Create a new location. makeLoc :: String -- ^ The file name -> Int -- ^ The line number -> Location makeLoc = Location -- | The unknown location (file @?@ and line @0@). unknownLocation :: Location unknownLocation = Location "?" 0
ekarayel/HTF
Test/Framework/Location.hs
lgpl-2.1
1,742
0
7
354
202
122
80
18
1
import Distribution.Simple import Distribution.Simple.LocalBuildInfo import Distribution.Simple.Program import Distribution.Simple.Setup import Distribution.PackageDescription import Distribution.Verbosity import Control.Monad import Data.Maybe import Data.Monoid import Data.Functor import System.FilePath.Posix import System.Directory import Text.Printf main = defaultMainWithHooks simpleUserHooks { hookedPrograms = [nvccProg], buildHook = myBuildHook } where nvccProg = (simpleProgram "nvcc") { programPostConf = \ _ _ -> return ["--compile"] } myBuildHook pkg_descr local_bld_info user_hooks bld_flags = do let lib = fromJust (library pkg_descr) lib_bi = libBuildInfo lib custom_bi = customFieldsBI lib_bi sources = fromMaybe [] (lines <$> lookup "x-cuda-sources" custom_bi) count = length sources cc_opts = ccOptions lib_bi ld_opts = ldOptions lib_bi inc_dirs = includeDirs lib_bi lib_dirs = extraLibDirs lib_bi libs = extraLibs lib_bi bld_dir = buildDir local_bld_info progs = withPrograms local_bld_info ver = (pkgVersion . package) pkg_descr nvcc = fromJust $ lookupProgram (simpleProgram "nvcc") progs verb = (fromFlag . buildVerbosity) bld_flags putStrLn "Compiling CUDA sources" objs <- mapM (\(idx,path) -> compileCuda nvcc cc_opts inc_dirs verb bld_dir idx count path) (zip [1..count] sources) let new_bi = lib_bi { ldOptions = objs } new_lib = lib { libBuildInfo = new_bi } new_pkg = pkg_descr { library = Just new_lib } buildHook simpleUserHooks new_pkg local_bld_info user_hooks bld_flags compileCuda :: ConfiguredProgram -- ^ CUDA compiler (nvcc) -> [String] -- ^ Compile options from Cabal -> [String] -- ^ Include paths from Cabal -> Verbosity -- ^ Verbosity -> FilePath -- ^ Base output directory -> Int -- ^ Source number -> Int -- ^ Source count -> FilePath -- ^ Path to source file -> IO FilePath -- ^ Path to generated object code compileCuda nvcc opts incls verb out_path idx count cxx_src = do let includes = map ("-I" ++) incls out_path' = normalise out_path cxx_src' = normalise cxx_src out_file = out_path' </> dropFileName cxx_src </> replaceExtension (takeFileName cxx_src) ".o" out = ["-c", cxx_src', "-o", out_file] createDirectoryIfMissing True (dropFileName out_file) let format = "[%" ++ show (length $ show count) ++ "d of " ++ show count ++"] Compiling CUDA kernel ( %s, %s )\n" printf format idx cxx_src out_file runProgram verb nvcc (includes ++ opts ++ out) return out_file
hsyl20/HaskellPU
Setup.hs
lgpl-3.0
2,833
0
17
758
686
360
326
60
1
myMap [] fn = [] myMap (x:xs) fn = fn x : myMap xs fn myReduce i [] fn = i myReduce i (a:as) fn = myReduce (fn i a) as fn myFilter fn [] = [] myFilter fn (x:xs) = if fn x then x : myFilter fn xs else myFilter fn xs myTake 0 xs = [] myTake n [] = [] myTake n (x:xs) = x : myTake (n-1) xs myTakeWhile fn [] = [] myTakeWhile fn (x:xs) = if fn x then x : myTakeWhile fn xs else [] myDrop 0 xs = xs myDrop n (x:xs) = myDrop (n-1) xs myZip fn xs [] = [] myZip fn [] ys =[] myZip fn (x:xs) (y:ys) = fn x y : myZip fn xs ys flatmap fn [] = [] flatmap fn (x:xs) = fn x ++ flatmap fn xs flatten [] = [] flatten (xs:xss) = xs ++ (flatten xss) data MyBox a = MyBox a mmap fn (MyBox a) = MyBox (fn a) join (MyBox (MyBox(x))) = MyBox x mflatmap fn x = join (mmap fn x)
abyu/learning
haskell/listFuncs.hs
unlicense
759
0
10
187
535
268
267
24
2
module Main where luhnDouble :: Int -> Int luhnDouble x | x * 2 > 9 = (x * 2) - 9 | otherwise = x * 2 luhn :: Int -> Int -> Int -> Int -> Bool luhn a b c d = luhnTotal `mod` 10 == 0 where luhnTotal = luhnDouble a + b + luhnDouble c + d
Crossroadsman/ProgrammingInHaskell
04/luhn.hs
apache-2.0
290
0
10
116
129
66
63
7
1
module Chapter2.PatternMatching where import Chapter2.DataModels clientName :: Client -> String clientName (GovOrg name) = name clientName (Company name _ _ _) = name clientName (Individual (Person fName lName _) _) = fName ++ " " ++ lName companyName :: Client -> Maybe String companyName (Company name _ _ _) = Just name companyName _ = Nothing reduceTimeMachines :: [TimeMachine] -> Double -> [TimeMachine] reduceTimeMachines [] _ = [] reduceTimeMachines (TimeMachine a b c d p:[]) r = [TimeMachine a b c d (p - p * r)] reduceTimeMachines (x:xs) r = reduceTimeMachines [x] r ++ reduceTimeMachines xs r
zer/BeginningHaskell
src/Chapter2/PatternMatching.hs
apache-2.0
713
0
9
206
253
130
123
13
1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Graphics.Hoodle.Render.PDFBackground -- Copyright : (c) 2011-2013 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <[email protected]> -- Stability : experimental -- Portability : GHC -- ----------------------------------------------------------------------------- module Graphics.Hoodle.Render.Background where import Control.Monad.State hiding (mapM_) import Data.ByteString hiding (putStrLn,filter) import Data.Foldable (mapM_) import Graphics.Rendering.Cairo -- import qualified Data.Map as M import Data.ByteString.Base64 import qualified Data.ByteString.Char8 as C import Data.Monoid import Data.UUID.V4 (nextRandom) import qualified Graphics.UI.Gtk.Poppler.Document as Poppler import qualified Graphics.UI.Gtk.Poppler.Page as PopplerPage import System.Directory import System.FilePath ((</>),(<.>)) -- from hoodle-platform import Data.Hoodle.BBox import Data.Hoodle.Predefined import Data.Hoodle.Simple -- import Graphics.Hoodle.Render.Type.Background -- import Prelude hiding (mapM_) -- | popplerGetDocFromFile :: ByteString -> IO (Maybe Poppler.Document) popplerGetDocFromFile fp = Poppler.documentNewFromFile (C.unpack ("file://localhost" `mappend` fp)) Nothing -- | getByteStringIfEmbeddedPDF :: ByteString -> Maybe ByteString getByteStringIfEmbeddedPDF bstr = do guard (C.length bstr > 30) let (header,dat) = C.splitAt 30 bstr guard (header == "data:application/x-pdf;base64,") either (const Nothing) return (decode dat) -- | popplerGetDocFromDataURI :: ByteString -> IO (Maybe Poppler.Document) popplerGetDocFromDataURI dat = do let mdecoded = getByteStringIfEmbeddedPDF dat case mdecoded of Nothing -> return Nothing Just decoded -> do uuidstr <- liftM show nextRandom tmpdir <- getTemporaryDirectory let tmpfile = tmpdir </> uuidstr <.> "pdf" C.writeFile tmpfile decoded mdoc <- popplerGetDocFromFile (C.pack tmpfile) removeFile tmpfile return mdoc -- | popplerGetPageFromDoc :: Poppler.Document -> Int -- ^ page number -> IO (Maybe Poppler.Page, Maybe Surface) popplerGetPageFromDoc doc pn = do n <- Poppler.documentGetNPages doc if pn > n then return (Nothing, Nothing) else do pg <- Poppler.documentGetPage doc (pn-1) (w,h) <- PopplerPage.pageGetSize pg sfc <- createImageSurface FormatARGB32 (floor w) (floor h) renderWith sfc $ do setSourceRGBA 1 1 1 1 rectangle 0 0 w h fill PopplerPage.pageRender pg return (Just pg, Just sfc) -- | draw ruling all drawRuling :: Double -> Double -> ByteString -> Render () drawRuling w h style = do let drawHorizRules = do let (r,g,b,a) = predefined_RULING_COLOR setSourceRGBA r g b a setLineWidth predefined_RULING_THICKNESS let drawonerule y = do moveTo 0 y lineTo w y stroke mapM_ drawonerule [ predefined_RULING_TOPMARGIN , predefined_RULING_TOPMARGIN+predefined_RULING_SPACING .. h-1 ] case style of "plain" -> return () "lined" -> do drawHorizRules let (r2,g2,b2,a2) = predefined_RULING_MARGIN_COLOR setSourceRGBA r2 g2 b2 a2 setLineWidth predefined_RULING_THICKNESS moveTo predefined_RULING_LEFTMARGIN 0 lineTo predefined_RULING_LEFTMARGIN h stroke "ruled" -> drawHorizRules "graph" -> do let (r3,g3,b3,a3) = predefined_RULING_COLOR setSourceRGBA r3 g3 b3 a3 setLineWidth predefined_RULING_THICKNESS let drawonegraphvert x = do moveTo x 0 lineTo x h stroke let drawonegraphhoriz y = do moveTo 0 y lineTo w y stroke mapM_ drawonegraphvert [0,predefined_RULING_GRAPHSPACING..w-1] mapM_ drawonegraphhoriz [0,predefined_RULING_GRAPHSPACING..h-1] _ -> return () -- | draw ruling in bbox drawRuling_InBBox :: BBox -> Double -> Double -> ByteString -> Render () drawRuling_InBBox (BBox (x1,y1) (x2,y2)) w h style = do let drawonerule y = do moveTo x1 y lineTo x2 y stroke let drawonegraphvert x = do moveTo x y1 lineTo x y2 stroke let drawonegraphhoriz y = do moveTo x1 y lineTo x2 y stroke fullRuleYs = [ predefined_RULING_TOPMARGIN , predefined_RULING_TOPMARGIN+predefined_RULING_SPACING .. h-1 ] ruleYs = filter (\y-> (y <= y2) && (y >= y1)) fullRuleYs fullGraphXs = [0,predefined_RULING_GRAPHSPACING..w-1] fullGraphYs = [0,predefined_RULING_GRAPHSPACING..h-1] graphXs = filter (\x->(x<=x2)&&(x>=x1)) fullGraphXs graphYs = filter (\y->(y<=y2)&&(y>=y1)) fullGraphYs let drawHorizRules = do let (r,g,b,a) = predefined_RULING_COLOR setSourceRGBA r g b a setLineWidth predefined_RULING_THICKNESS mapM_ drawonerule ruleYs case style of "plain" -> return () "lined" -> do drawHorizRules let (r2,g2,b2,a2) = predefined_RULING_MARGIN_COLOR setSourceRGBA r2 g2 b2 a2 setLineWidth predefined_RULING_THICKNESS moveTo predefined_RULING_LEFTMARGIN 0 lineTo predefined_RULING_LEFTMARGIN h stroke "ruled" -> drawHorizRules "graph" -> do let (r3,g3,b3,a3) = predefined_RULING_COLOR setSourceRGBA r3 g3 b3 a3 setLineWidth predefined_RULING_THICKNESS mapM_ drawonegraphvert graphXs mapM_ drawonegraphhoriz graphYs _ -> return () -- | render background without any constraint renderBkg :: (Background,Dimension) -> Render () renderBkg (Background _typ col sty,Dim w h) = do let c = M.lookup col predefined_bkgcolor case c of Just (r,g,b,_a) -> setSourceRGB r g b Nothing -> setSourceRGB 1 1 1 rectangle 0 0 w h fill drawRuling w h sty renderBkg (BackgroundPdf _ _ _ _,Dim w h) = do setSourceRGBA 1 1 1 1 rectangle 0 0 w h fill renderBkg (BackgroundEmbedPdf _ _,Dim w h) = do setSourceRGBA 1 1 1 1 rectangle 0 0 w h fill -- | this has some bugs. need to fix cnstrctRBkg_StateT :: Dimension -> Background -> StateT (Maybe Context) IO RBackground cnstrctRBkg_StateT dim@(Dim w h) bkg = do case bkg of Background _t c s -> do sfc <- liftIO $ createImageSurface FormatARGB32 (floor w) (floor h) renderWith sfc $ renderBkg (bkg,dim) return (RBkgSmpl c s (Just sfc)) BackgroundPdf _t md mf pn -> do case (md,mf) of (Just d, Just f) -> do mdoc <- liftIO $ popplerGetDocFromFile f put $ Just (Context d f mdoc Nothing) case mdoc of Just doc -> do (mpg,msfc) <- liftIO $ popplerGetPageFromDoc doc pn return (RBkgPDF md f pn mpg msfc) Nothing -> error "error1 in cnstrctRBkg_StateT" _ -> do mctxt <- get case mctxt of Just (Context oldd oldf olddoc _) -> do (mpage,msfc) <- case olddoc of Just doc -> do liftIO $ popplerGetPageFromDoc doc pn Nothing -> error "error2 in cnstrctRBkg_StateT" maybe (liftIO $ putStrLn ( "pn = " ++ show pn )) (const (return ())) mpage return (RBkgPDF (Just oldd) oldf pn mpage msfc) Nothing -> error "error3 in cnstrctRBkg_StateT" BackgroundEmbedPdf _ pn -> do mctxt <- get case mctxt of Just (Context _ _ _ mdoc) -> do (mpage,msfc) <- case mdoc of Just doc -> do liftIO $ popplerGetPageFromDoc doc pn Nothing -> error "error4 in cnstrctRBkg_StateT" return (RBkgEmbedPDF pn mpage msfc) Nothing -> error "error5 in cnstrctRBkg_StateT"
wavewave/hoodle-render
src/Graphics/Hoodle/Render/Background.hs
bsd-2-clause
8,340
9
36
2,511
2,413
1,192
1,221
-1
-1
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, TypeSynonymInstances, FlexibleInstances #-} -- | Basic definitions od spaces and their properties module Data.Reals.Space ( sor, sand, force, Hausdorff (..), Discrete (..), Compact (..), Overt (..), LinearOrder (..) ) where import Data.Reals.Staged -- | The Sierpinski space @Sigma@ is represented by staged booleans type Sigma = StagedWithFun Bool -- | Disjunction for Sierpinski space sor :: Sigma -> Sigma -> Sigma sor = lift2 (\s p q -> p || q) -- | Conjunction for Sierpinski space sand :: Sigma -> Sigma -> Sigma sand = lift2 (\s p q -> p && q) -- | Force a value in the Sierpinski space into Booleans. This may diverge as bottom cannot be -- reliably detected. force :: Sigma -> Bool force p = loop 0 where loop k | approximate p (prec RoundDown k) = True -- lower approximation is True, the value is top | not (approximate p (prec RoundUp k)) = False -- upper approximation is False, the value is bottom | otherwise = loop (k+1) -- | The Show instance may cause divergence because 'force' could diverge. An alternative -- implementation would give up after a while, and the user would have to use 'force' explicitly to -- get the exact results (or divergence). instance Show Sigma where show p = show $ force p -- | A space is Hausdorff if inequality, here called 'apart', is an open relation. class Hausdorff t where apart :: t -> t -> Sigma -- | A space is Discrete if equality, here called 'equal', is an open relation. class Discrete t where equal :: t -> t -> Sigma -- | Suppose the type 's' represents a family of subspaces of 't'. The typical example is -- that 't' is the type of reals and 's' is the type of closed intervals. Then the subspaces -- represented by 's' are compact subspaces of 't' if the universal quantifier is a continuous -- map from @t -> 'Sigma'@ to 'Sigma'. class Compact s t | s -> t where forall :: s -> (t -> Sigma) -> Sigma -- | Suppose the type 's' represents a family of subspaces of 't'. The typical example is -- that 't' is the type of reals and 's' is the type of closed intervals. Then the subspaces -- represented by 's' are overt subspaces of 't' if the existential quantifier is a continuous -- map from @t -> 'Sigma'@ to 'Sigma'. class Overt s t | s -> t where exists :: s -> (t -> Sigma) -> Sigma -- | The real numbers are strictly linearly ordered by open relation <, we define -- a class that expresses that fact. class LinearOrder t where less :: t -> t -> Sigma more :: t -> t -> Sigma -- default implemetnation of 'more' in terms of 'less' more x y = less y x
comius/haskell-fast-reals
src/Data/Reals/Space.hs
bsd-2-clause
2,760
0
14
667
454
254
200
34
1
{-# LANGUAGE TupleSections #-} {-# LANGUAGE ParallelListComp #-} module Data.Discrimination.Internal ( runs , groupNum , bdiscNat , updateBag , updateSet , spanEither ) where import Data.Array as Array import Data.Functor import Data.Int import qualified Data.List as List import Prelude hiding (read, concat) -------------------------------------------------------------------------------- -- * Utilities -------------------------------------------------------------------------------- bdiscNat :: Int -> ([v] -> v -> [v]) -> [(Int,v)] -> [[v]] bdiscNat n update xs = reverse <$> Array.elems (Array.accumArray update [] (0,n) xs) {-# INLINE bdiscNat #-} runs :: Eq a => [(a,b)] -> [[b]] runs [] = [] runs ((a,b):xs0) = (b:ys0) : runs zs0 where (ys0,zs0) = go xs0 go [] = ([],[]) go xs@((a', b'):xs') | a == a' = case go xs' of (ys, zs) -> (b':ys,zs) | otherwise = ([], xs) groupNum :: [[k]] -> [(k,Int)] groupNum kss = List.concat [ (,n) <$> ks | n <- [0..] | ks <- kss ] updateBag :: [Int] -> Int -> [Int] updateBag vs v = v : vs updateSet :: [Int] -> Int -> [Int] updateSet [] w = [w] updateSet vs@(v:_) w | v == w = vs | otherwise = w : vs -- | Optimized and CPS'd version of 'Data.Either.partitionEithers', where all lefts are known to come before all rights spanEither :: ([a] -> [b] -> c) -> [Either a b] -> c spanEither k xs0 = go [] xs0 where go acc (Left x:xs) = go (x:acc) xs go acc rights = k (reverse acc) (fromRight <$> rights) fromRight :: Either a b -> b fromRight (Right y) = y fromRight _ = error "unstable discriminator"
markus1189/discrimination
src/Data/Discrimination/Internal.hs
bsd-2-clause
1,609
1
12
333
691
382
309
42
2
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE CPP #-} ------------------------------------------------------------------------------- -- | -- Module : Yesod.Helpers.RssFeed -- Copyright : Patrick Brisbin -- License : as-is -- -- Maintainer : Patrick Brisbin <[email protected]> -- Stability : Stable -- Portability : Portable -- -- An Rss news feed. -- -- Rss spec: <http://www.rssboard.org/rss-specification> -- ------------------------------------------------------------------------------- module Yesod.Helpers.RssFeed ( rssFeed , rssLink , RepRss (..) , module Yesod.Helpers.FeedTypes ) where import Yesod.Handler import Yesod.Content import Yesod.Widget import Yesod.Helpers.FeedTypes import Text.Hamlet (Hamlet, xhamlet, hamlet) import qualified Data.ByteString.Char8 as S8 import Control.Monad (liftM) -- | The Rss content type newtype RepRss = RepRss Content instance HasReps RepRss where chooseRep (RepRss c) _ = return (typeRss, c) -- | The feed response itself rssFeed :: Monad mo => Feed (Route master) -> GGHandler sub master mo RepRss rssFeed = liftM RepRss . hamletToContent . template template :: Feed url -> Hamlet url template arg = #if __GLASGOW_HASKELL__ >= 700 [xhamlet| #else [$xhamlet| #endif \<?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" <channel <atom:link href=@{feedLinkSelf arg} rel="self" type=#{S8.unpack typeRss} <title>#{feedTitle arg} <link>@{feedLinkHome arg} <description>#{feedDescription arg} <lastBuildDate>#{formatRFC822 $ feedUpdated arg} <language>#{feedLanguage arg} $forall entry <- feedEntries arg ^{entryTemplate entry} |] entryTemplate :: FeedEntry url -> Hamlet url entryTemplate arg = #if __GLASGOW_HASKELL__ >= 700 [xhamlet| #else [$xhamlet| #endif <item <title>#{feedEntryTitle arg} <link>@{feedEntryLink arg} <guid>@{feedEntryLink arg} <pubDate>#{formatRFC822 $ feedEntryUpdated arg} <description>#{feedEntryContent arg} |] -- | Generates a link tag in the head of a widget. rssLink :: Route m -> String -- ^ title -> GWidget s m () rssLink u title = addHamletHead #if __GLASGOW_HASKELL__ >= 700 [hamlet| #else [$hamlet| #endif <link href=@{u} type=#{S8.unpack typeRss} rel="alternate" title=#{title} |]
pbrisbin/yesod-newsfeed
Yesod/Helpers/RssFeed.hs
bsd-2-clause
2,479
0
9
543
296
178
118
30
1
{-| Module : Control.IxFunctor.Examples.Examples Description : A bunch of fairly trivial examples Copyright : Pavel Lepin, 2015 License : BSD2 Maintainer : [email protected] Stability : experimental Portability : GHC >= 7.8 -} module Control.IxFunctor.Examples.Examples ( paraFactorial , anacataFactorial , hyloFactorial , sumList , sumTree , sumEven , genEven , RoseTree(RoseTree) , Even(ENil, ECons) , Odd(OCons) ) where import Control.IxFunctor.Nat import Control.IxFunctor.List import Control.IxFunctor.Rose import Control.IxFunctor.EvenOdd -- |Factorial as a paramorphism on nats. paraFactorial :: Integer -> Integer paraFactorial = paraInteger $ 1 `maybe` \(n, x) -> n * succ x -- |Factorial as a hylomorphism on lists. anacataFactorial :: Integer -> Integer anacataFactorial = cataList (1 `maybe` uncurry (*)) . anaList coalg where coalg 0 = Nothing coalg n = Just (n, pred n) -- |Same, but with explicit appeal to hylo. hyloFactorial :: Integer -> Integer hyloFactorial = hyloList (1 `maybe` uncurry (*)) coalg where coalg 0 = Nothing coalg n = Just (n, pred n) sumList :: Num a => [a] -> a sumList = cataList (0 `maybe` uncurry (+)) sumTree :: Num a => RoseTree a -> a sumTree = cataRose (\(x, xs) -> x + sumList xs) sumEven :: Even Integer String -> Integer sumEven = cataEven (0 `maybe` uncurry (+)) (\(x, y) -> read x + y) genEven :: Integer -> Even Integer Integer genEven = anaEven (\x -> if x <= 0 then Nothing else Just (x, pred x)) (\x -> (x, pred x))
pbl64k/gpif-datakinds
src/Control/IxFunctor/Examples/Examples.hs
bsd-2-clause
1,622
0
11
393
476
273
203
39
2
module Main where import Criterion.Main import Crypto.Number.Serialize -- import Crypto.Number.Generate import qualified Data.ByteString as B import Crypto.Number.ModArithmetic import Crypto.Number.F2m import Data.Bits primes = [3, 5, 7, 29, 31, 211, 2309, 2311, 30029, 200560490131, 304250263527209] carmichaelNumbers = [41041, 62745, 63973, 75361, 101101, 126217, 172081, 188461, 278545, 340561] lg1, lg2 :: Integer lg1 = 21389083291083903845902381390285907190274907230982112390820985903825329874812973821790321904790217490217409721904832974210974921740972109481490128430982190472109874802174907490271904124908210958093285098309582093850918902581290859012850829105809128590218590281905812905810928590128509128940821903829018390849839578967358920127598901248259797158249684571948075896458741905823982671490352896791052386357019528367902 lg2 = 21392813098390824190840192812389082390812940821904891028439028490128904829104891208940835932882910839218309812093118249089871209347472901874902407219740921840928149087284397490128903843789289014374839281492038091283923091809734832974180398210938901284839274091749021709 fx = 11692013098647223345629478661730264157247460344009 -- x^163+x^7+x^6+x^3+1 bitsAndShift8 n i = (n `shiftR` i, n .&. 0xff) modAndShift8 n i = (n `shiftR` i, n `mod` 0x100) main = defaultMain [ bgroup "std ops" [ bench "mod" $ nf (mod lg1) lg2 , bench "rem" $ nf (rem lg1) lg2 , bench "div" $ nf (div lg1) lg2 , bench "quot" $ nf (quot lg1) lg2 , bench "divmod" $ nf (divMod lg1) lg2 , bench "quotRem" $ nf (quotRem lg1) lg2 ] , bgroup "divMod by 256" [ bench "divmod 256" $ nf (divMod lg1) 256 , bench "quotRem 256" $ nf (quotRem lg1) 256 , bench "modAndShift 8" $ nf (modAndShift8 lg1) 8 , bench "bitsAndShift 8" $ nf (bitsAndShift8 lg1) 8 ] , bgroup "serialization bs->i" [ bench "8" $ nf os2ip b8 , bench "32" $ nf os2ip b32 , bench "64" $ nf os2ip b64 , bench "256" $ nf os2ip b256 , bench "1024" $ nf os2ip b1024 ] , bgroup "serialization i->bs" [ bench "10" $ nf i2osp (2^10) , bench "100" $ nf i2osp (2^100) , bench "1000" $ nf i2osp (2^1000) , bench "10000" $ nf i2osp (2^10000) , bench "100000" $ nf i2osp (2^100000) ] , bgroup "serialization i->bs of size" [ bench "10" $ nf (i2ospOf_ 4) (2^10) , bench "100" $ nf (i2ospOf_ 16) (2^100) , bench "1000" $ nf (i2ospOf_ 128) (2^1000) , bench "10000" $ nf (i2ospOf_ 1560) (2^10000) , bench "100000" $ nf (i2ospOf_ 12502) (2^100000) ] , bgroup "exponentiation" [ bench "2^1234 mod 2^999" $ nf (exponantiation 2 1234) (2^999) , bench "130^5432 mod 100^9990" $ nf (exponantiation 130 5432) (100^9999) , bench "2^1234 mod 2^999" $ nf (exponantiation_rtl_binary 2 1234) (2^999) , bench "130^5432 mod 100^9990" $ nf (exponantiation_rtl_binary 130 5432) (100^9999) ] , bgroup "F2m" [ bench "addition" $ nf (addF2m lg1) lg2 , bench "multiplication" $ nf (mulF2m fx lg1) lg2 , bench "square" $ nf (squareF2m fx) lg1 , bench "square multiplication" $ nf (mulF2m fx lg1) lg1 , bench "reduction" $ nf (modF2m fx) lg1 , bench "inversion" $ nf (invF2m fx) lg1 ] ] where b8 = B.replicate 8 0xf7 b32 = B.replicate 32 0xf7 b64 = B.replicate 64 0x7f b256 = B.replicate 256 0x7f b1024 = B.replicate 1024 0x7f
vincenthz/hs-crypto-numbers
Benchmarks/Benchmarks.hs
bsd-2-clause
3,616
0
12
890
1,102
568
534
63
1
module RefacMvDefBtwMod(moveDefBtwMod) where import Maybe import List import RefacUtils hiding (getQualifier) import PFE0 (findFile) import PrettyPrint {-This refactoring moves a user-selected function definition/pattern binding from current module to a user specified module. To perform this refactoring: put the cursor at the begining of the function/pattern name, then select the 'moveDefBtwMod' menu from the 'refactor' menu, and input the target module name in the mini-buffer as prompted.-} moveDefBtwMod args = do let fileName = ghead "filename" args destModName' = args!! 1 destModName = strToModName destModName' -- there may be problem with the main module row = read (args!!2)::Int col = read (args!!3)::Int origModName <- fileNameToModName fileName r <-isAnExistingMod destModName unless r $ error "The specified module does not exist!" unless (origModName /= destModName) $ error "The target module name is the same as the current module name!" (origInscps, _, origMod, origToks) <- parseSourceFile fileName let pn = pNTtoPN $ locToPNT fileName (row, col) origMod decl =definingDecls [pn] (hsModDecls origMod) False True unless (pn /= defaultPN) $ error "Invalid cursor position. Please point the cursor to the beginning of the function/pattern name!" unless (isTopLevelPN pn && decl/=[]) $ error "The selected definition is not a top-level function/pattern definition!" -- Find the file name of the target module. destFile<-PFE0.findFile destModName -- Parse the target module. (destInscps, _, destMod, destToks) <-parseSourceFile destFile -- get the pnames defined by the declaration to be moved. let pns = nub $ concatMap definedPNs decl -- get the subset of 'pns' which are already defined in the target module. namesDefined <- namesDefinedIn (map pNtoName pns) destMod unless (namesDefined == [] ) (if length namesDefined == 1 then error ("The function/pattern name: " ++ show (head (namesDefined)) ++ " is already defined in module "++ destModName'++ " !") else error ("The pattern names: " ++ show namesDefined ++ " are already defined in module " ++ destModName'++ " !")) -- Get the client modules and the corresponding file names of the original module. clientsOfOrigMod <- clientModsAndFiles =<< RefacUtils.fileNameToModName fileName -- Get the client modules and the corresponding file names of the original module. clientsOfDestMod <- clientModsAndFiles =<< RefacUtils.fileNameToModName destFile -- get the free variables in the definition to be moved. freePnts <- freePNTsIn pns decl let pnsNotInscope = varsNotInScope freePnts destInscps unless (pnsNotInscope == []) -- why can not import these variables in the dest module? (if length pnsNotInscope == 1 then error ("The free variable: '" ++ pNtoName (head pnsNotInscope)++ "', which is used by the definition to be moved is not in scope in the target module "++destModName' ++ " !") else error ("The free variables: " ++ showEntities pNtoName pnsNotInscope ++ ", which are used by the definition to be moved are not in scope in the target module " ++destModName' ++ " !")) -- Will the moving cause recursive modules? r <-causeRecursiveMods decl fileName origModName destModName unless (not r) $ error ("Moving the definition to module " ++ show destModName++ " will cause mutually recursive modules!") -- Remove the definition from the original module. (origMod', ((origToks',origM),_))<-rmCodeFromMod pns fileName (origMod, origToks) destModName destFile -- Parse all those client modules. let modsAndFiles=nub (clientsOfOrigMod++clientsOfDestMod) \\ [(origModName, fileName),(destModName, destFile)] parsedMods <-mapM parseSourceFile $ map snd modsAndFiles -- is the definition name used in modules other than the target module? let used = any (\(_,_,mod,_)->isUsedByMod pns mod) parsedMods || isUsedByMod pns origMod -- Add the definition to the destination module. (destMod',((destToks',destM),_))<-addCodeToMod pns destFile (origMod, origToks) (destInscps,destModName,destMod, destToks) used --Do corrsponding modification in the client modules. refacClients <- mapM (refactorInClientMod origModName destModName pns) $ zip parsedMods $ map snd modsAndFiles -- output the result. writeRefactoredFiles False $ [((fileName,origM),(origToks',origMod')), ((destFile,destM),(destToks',destMod'))] ++ refacClients -- Return the subset of 'names' that are defined in 't'. namesDefinedIn names t =do (_,rd)<-hsFreeAndDeclaredPNs t return ((map pNtoName rd) `intersect` names) --Get those free variables (used by the definition to be moved) that are not in scope in the destination module. varsNotInScope pnts inScopeRel = nub $ map pNTtoPN (filter (\pnt->if isQualifiedPN (pNTtoPN pnt) then hsQualifier pnt inScopeRel == [] else not (isInScopeAndUnqualified (pNTtoName pnt) inScopeRel)) pnts) -- get those pnts which are free in 't' and not included in 'pns' freePNTsIn pns t = do (pns', _) <- hsFDsFromInside t -- Why not use freeAndDeclared? let pnts = nub $ hsPNTs =<< rmLocs t return $ filter (\t->elem (pNTtoPN t) (pns' \\ pns)) pnts --Return True if moving the definition from origMod to destMod will cause recursive modules. causeRecursiveMods decl origFile origModName destModName =do let pns = nub $ concatMap definedPNs decl clients<-clientModsAndFiles origModName servers <-serverModsAndFiles destModName let clientMods1 = map fst clients clientFiles =map snd clients serverMods = map fst servers serverFiles =map snd servers if elem destModName clientMods1 then do let ms = origFile:(clientFiles `intersect` serverFiles) parsedMods<-mapM parseSourceFile ms let (_,_,origMod,_) = ghead "causeRecursiveMods" parsedMods return ( isUsedBy pns (hsDecls origMod \\ decl) || (any (\ (_,_,mod,_)->isUsedByMod pns mod) (tail parsedMods))) else if elem destModName serverMods then do clients <- clientModsAndFiles destModName let ms = origModName : (map fst clients `intersect` serverMods) r = map fromJust (filter isJust (map hasModName $ nub (map pNTtoPN (hsPNTs decl)) \\ pns)) return $ any (\m-> elem m r ) ms else return False isUsedByMod pns (HsModule _ _ _ _ ds) = isUsedBy pns ds --Return True if any pname in 'pns' is used by 'mod' isUsedBy pns t = fromMaybe False (applyTU (once_tdTU (failTU `adhocTU` worker)) t) where worker (pnt::PNT) | elem (pNTtoPN pnt) pns && isUsedInRhs pnt t = Just True worker _ = mzero -- Remove the definition from the original module. rmCodeFromMod pns fileName (mod, tokList) destModName destFileName = runStateT (do -- remove the definition. decls'<-rmDecl (ghead "rmCodeFromMod" pns) True (hsDecls mod) -- remove the definition name from the export list mod'<-rmItemsFromExport (replaceDecls mod decls') (Left ([],pns)) -- is the definition used in the current module? if isUsedByMod pns mod' then -- yes. add the definition name to the import. do let qual=getQualifier destModName mod' mod''<-replaceQualifier pns qual mod' addImport destFileName destModName pns mod'' else --No, do nothing. return mod') ((tokList,unmodified),(-1000,0)) -- Add the definition to the client module, and modify the import/export if necessary. addCodeToMod pns destFileName (origMod, origToks) (destInscps,destModName, destMod, destToks) usedByClients = do let -- get the declaraion. False means not spliting the type signature. decl = definingDecls pns (hsDecls origMod) True False --get the fun binding. funBinding = ghead "addCodeToMod" $ filter isFunOrPatBind decl -- shoudn't be empty. --get the type signature if there is any. typeSig = filter isTypeSig decl decl' = if typeSig==[] then [funBinding] else [ghead "addCodeToMod" (getTypeSig pns (head typeSig)),funBinding] toksTobeAdded =getDeclToks (ghead "addCodeToMod" pns) True decl origToks (decl'', toksTobeAdded') <- if isDirectRecursiveDef funBinding && sameNameInScope (ghead "addCodeToMod" pns) destInscps then do (t,((toks',_), m))<-runStateT (addQualifier pns modName decl) ((toksTobeAdded,unmodified),(-1000,0)) return (t, toks') else return (decl', toksTobeAdded) (decl''',((toksTobeAdded'',_),_)) <-runStateT (replaceQualifier pns destModName decl'') ((toksTobeAdded',unmodified),(-1000,0)) --destFileName) runStateT ( do destMod'<-resolveAmbiguity pns destInscps destMod mod'<-replaceQualifier pns destModName destMod' mod''<- addDecl mod' Nothing (decl''', Just toksTobeAdded'') True mod''' <- rmItemsFromImport mod'' pns if usedByClients && not (modIsExported destMod) -- The definition name is used by other modules, but it is then addItemsToExport mod''' Nothing False (Right (map pnToEnt pns)) --so make it exported. else return mod''' -- Do nothing. ) ((destToks,unmodified), (-1000,0)) --destFileName) where -- Get the type signatures defines the type of pns. getTypeSig pns (Dec (HsTypeSig loc is c tp)) =[(Dec (HsTypeSig loc (filter (\x->isJust (find (==pNTtoPN x) pns)) is) c tp))] getTypeSig pns _ = [] modName = modNameToStr destModName pnToEnt pn = EntE (Var (pNtoPNT pn Value)) -- |Returns True if another identifier which has the same name but different meaning is in scope. -- NOTE: The name space should be taken into account as well. sameNameInScope::PName -- ^ The identifier ->InScopes -- ^ The inscope relation ->Bool -- ^ The result sameNameInScope pn inScopeRel = isJust $ find (\ (name, nameSpace, modName, _)-> name == pNtoName pn && hasModName pn /= Just modName ) $ inScopeInfo inScopeRel -- modify the import interface in the client modules. refactorInClientMod origModName destModName pns ((inscps, exps,mod, ts), fileName) = do (mod', ((ts',m),_)) <- runStateT ( do mod'<-rmItemsFromImport mod pns mod''<- if isUsedByMod pns mod then do let qual=getQualifier destModName mod addImport fileName destModName pns =<< replaceQualifier pns qual mod' else if itemIsImportedByDefault destModName mod && causeAmbiguity pns mod' then addHiding destModName mod' pns else return mod' return mod'' ) ((ts,unmodified),(-1000,0)) return ((fileName,m),(ts',mod')) --add a definition name to the import. If the module is not imported yet, then create a new import decl. -- addImport::String->HsName.ModuleName->[PName]->HsModuleP->HsModuleP addImport destFileName destModName pns mod@(HsModule _ _ _ imp _) =if itemIsImportedByDefault destModName mod -- Is the definition name explicitly imported? then return mod -- Yes. Do nothing. else if itemsAreExplicitlyImported destModName mod --Is the module imported and some of its items are explicitly imported? then addVarItemInImport1 destModName pns mod -- Yes. Then add the definition name to the list. else addImportDecl mod (modNameToStr destModName) False Nothing False (map pNtoName pns) --addImportDecl mod (mkImportDecl destFileName destModName False (map pNtoName pns)) --Create a new import decl. where {- Compose a import declaration which imports the module specified by 'modName', and only imports the definition spcified by 'e'. -} --mkImportDecl::String->HsName.ModuleName->Bool->[HsName.Id]->HsImportDeclP {- mkImportDecl fileName modName qual ids = (HsImportDecl loc0 (SN modName loc0) qual Nothing (Just (False, (map makeEnt ids)))) where makeEnt id= Var $ PNT (PN (UnQual id) (G modName id (N (Just loc0)))) Value (N (Just loc0)) -} itemsAreExplicitlyImported serverModName (HsModule _ _ _ imps _) = any (isExplicitlyImported serverModName) imps where isExplicitlyImported serverModName ((HsImportDecl _ (SN modName _) _ _ h)::HsImportDeclP) = serverModName == modName && isJust h && not (fst (fromJust h)) -- are items defined in the serverModName imported by the current module by default? itemIsImportedByDefault serverModName (HsModule _ _ _ imps _) = any (isImportedByDefault' serverModName) imps where isImportedByDefault' serverModName ((HsImportDecl _ (SN modName _) _ _ h)::HsImportDeclP) = serverModName == modName && ( isNothing h || (isJust h && fst(fromJust h))) addVarItemInImport1 serverModName pns mod = applyTP ((once_tdTP (failTP `adhocTP` inImport)) `choiceTP` idTP) mod where inImport (imp@(HsImportDecl loc@(SrcLoc fileName _ row col) (SN modName l) qual as (Just (b,ents))):: HsImportDeclP) | serverModName == modName && not b = {-do let ents'= map (\pn->Var (pNtoPNT pn Value)) pns addItemsToImport1 imp ents' return (HsImportDecl loc (SN modName l) qual as (Just (b, (ents'++ents)))) -} addItemsToImport serverModName Nothing (Left (map pNtoName pns)) imp inImport x = mzero --same name but with different meaning is used. causeAmbiguity pns mod = fromMaybe False (applyTU (once_tdTU (failTU `adhocTU` worker)) (hsDecls mod)) where worker (pnt::PNT) | not (isQualifiedPN (pNTtoPN pnt)) && elem (pNTtoName pnt) (map pNtoName pns) && not (elem (pNTtoPN pnt) pns) = Just True worker _ = Nothing resolveAmbiguity pns inScopeRel t =applyTP (full_tdTP (adhocTP idTP rename)) t where rename pnt@(PNT pn@(PN (UnQual s) l) ty loc@(N (Just (SrcLoc fileName _ row col)))) | isTopLevelPNT pnt && ty==Value && elem (pNTtoName pnt) (map pNtoName pns) && not (elem (pNTtoPN pnt) pns) = do let qual@(PlainModule q)= ghead "resolveAmbiguity" (hsQualifier pnt inScopeRel) pnt'=(PNT (PN (Qual qual s) l) ty loc) update pnt pnt' pnt rename x = return x -- getQualifier :: HsName.ModuleName->HsModuleP->HsName.ModuleName getQualifier modName (HsModule _ _ _ imp _) = let r=(nub.ghead "getQualifier") (applyTU (once_tdTU (constTU [] `adhocTU` inImport)) imp) in if r==[] then modName else head r where inImport ((HsImportDecl _ (SN m loc) _ as _ )::HsImportDeclP) | show modName == show m = if isJust as then return [simpModName (gfromJust "getQualifier" as)] else return [] inImport _ = mzero -- simpModName :: PosSyntax.ModuleName ->HsName.ModuleName simpModName (SN m loc) = m replaceQualifier pns qual t =applyTP (full_tdTP (adhocTP idTP rename)) t where rename pnt@(PNT pn ty loc) |isQualifiedPN pn && elem pn pns = do let pnt'=PNT (replaceQual pn qual) ty loc update pnt pnt' pnt where replaceQual (PN (Qual modName s) l) qual = PN (Qual qual s) l replaceQual pn _ = pn rename x=return x addQualifier pns qualifier t =applyTP (full_tdTP (adhocTP idTP rename)) t where rename pnt@(PNT pn@(PN (UnQual s) l) ty loc) | elem pn pns && isUsedInRhs pnt t = do let pnt'=(PNT (PN (Qual (strToModName qualifier) s) l) ty loc) update pnt pnt' pnt rename x=return x
forste/haReFork
refactorer/RefacMvDefBtwMod.hs
bsd-3-clause
17,342
0
24
5,240
4,159
2,117
2,042
-1
-1
-- Copyright (c) 2012 Eric McCorkle. All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- 3. Neither the name of the author nor the names of any contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS -- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -- SUCH DAMAGE. -- | This module provides a class representing an interface to a -- gensym monad. This monad generates symbols from strings. It is -- intended primarily for use in lexers. module Control.Monad.Gensym.Class( MonadGensym(..), ) where import Data.Symbol(Symbol) -- | A monad class representing a symbol generator. This will create -- symbols from strings. class Monad m => MonadGensym m where -- | Create a symbol for the given string. All invocations of this -- function will return the same symbol. symbol :: String -> m Symbol -- | Create a unique symbol for the given string, that will not be -- equivalent to any other, even if it has the same name. unique :: String -> m Symbol
emc2/proglang-util
Control/Monad/Gensym/Class.hs
bsd-3-clause
2,261
0
8
415
103
73
30
6
0
module Sharc.Instruments.BassClarinet (bassClarinet) where import Sharc.Types bassClarinet :: Instr bassClarinet = Instr "bass_clarinet" "Bass Clarinet" (Legend "McGill" "2" "12") (Range (InstrRange (HarmonicFreq 1 (Pitch 69.29 25 "c#2")) (Pitch 69.29 25 "c#2") (Amplitude 8789.36 (HarmonicFreq 113 (Pitch 77.782 27 "d#2")) 8.0e-2)) (InstrRange (HarmonicFreq 43 (Pitch 10022.52 46 "a#3")) (Pitch 277.18 49 "c#4") (Amplitude 220.0 (HarmonicFreq 1 (Pitch 220.0 45 "a3")) 5021.0))) [note0 ,note1 ,note2 ,note3 ,note4 ,note5 ,note6 ,note7 ,note8 ,note9 ,note10 ,note11 ,note12 ,note13 ,note14 ,note15 ,note16 ,note17 ,note18 ,note19 ,note20 ,note21 ,note22 ,note23 ,note24] note0 :: Note note0 = Note (Pitch 69.296 25 "c#2") 1 (Range (NoteRange (NoteRangeAmplitude 6652.41 96 0.22) (NoteRangeHarmonicFreq 1 69.29)) (NoteRange (NoteRangeAmplitude 207.88 3 2985.0) (NoteRangeHarmonicFreq 144 9978.62))) [Harmonic 1 2.831 2490.73 ,Harmonic 2 (-2.775) 39.05 ,Harmonic 3 (-0.422) 2985.0 ,Harmonic 4 (-2.663) 35.04 ,Harmonic 5 (-1.492) 2416.73 ,Harmonic 6 1.137 26.71 ,Harmonic 7 (-1.923) 566.27 ,Harmonic 8 (-0.334) 19.82 ,Harmonic 9 (-2.632) 121.05 ,Harmonic 10 0.91 24.04 ,Harmonic 11 (-1.132) 229.97 ,Harmonic 12 (-1.358) 154.75 ,Harmonic 13 2.363 355.93 ,Harmonic 14 0.759 288.08 ,Harmonic 15 (-2.373) 545.82 ,Harmonic 16 2.523 219.79 ,Harmonic 17 1.867 637.5 ,Harmonic 18 2.624 133.69 ,Harmonic 19 0.578 406.51 ,Harmonic 20 0.384 183.02 ,Harmonic 21 (-1.06) 365.25 ,Harmonic 22 (-1.101) 252.54 ,Harmonic 23 (-2.375) 456.05 ,Harmonic 24 (-2.82) 134.71 ,Harmonic 25 1.543 220.39 ,Harmonic 26 2.05 54.72 ,Harmonic 27 0.858 273.12 ,Harmonic 28 0.747 200.54 ,Harmonic 29 (-2.08) 316.0 ,Harmonic 30 (-2.109) 90.5 ,Harmonic 31 2.326 121.96 ,Harmonic 32 1.534 67.91 ,Harmonic 33 0.372 172.82 ,Harmonic 34 (-0.805) 61.85 ,Harmonic 35 (-0.387) 65.72 ,Harmonic 36 (-1.629) 58.48 ,Harmonic 37 3.029 190.51 ,Harmonic 38 0.38 87.68 ,Harmonic 39 (-0.417) 90.85 ,Harmonic 40 2.901 29.41 ,Harmonic 41 (-0.953) 19.52 ,Harmonic 42 2.195 52.46 ,Harmonic 43 (-1.683) 3.66 ,Harmonic 44 1.206 29.48 ,Harmonic 45 (-2.565) 27.68 ,Harmonic 46 (-1.277) 28.82 ,Harmonic 47 (-1.439) 9.42 ,Harmonic 48 (-2.6) 24.0 ,Harmonic 49 1.851 36.58 ,Harmonic 50 1.885 31.02 ,Harmonic 51 (-0.821) 24.75 ,Harmonic 52 (-0.75) 34.23 ,Harmonic 53 2.863 39.91 ,Harmonic 54 1.883 19.9 ,Harmonic 55 0.809 19.28 ,Harmonic 56 1.039 20.04 ,Harmonic 57 (-0.861) 23.85 ,Harmonic 58 (-1.497) 10.1 ,Harmonic 59 (-2.655) 2.4 ,Harmonic 60 (-1.784) 8.45 ,Harmonic 61 (-2.986) 3.78 ,Harmonic 62 (-0.814) 7.38 ,Harmonic 63 (-2.81) 19.55 ,Harmonic 64 2.769 19.8 ,Harmonic 65 0.723 13.04 ,Harmonic 66 2.537 2.09 ,Harmonic 67 2.739 0.64 ,Harmonic 68 1.752 1.9 ,Harmonic 69 1.217 10.93 ,Harmonic 70 (-2.338) 5.96 ,Harmonic 71 (-1.736) 3.4 ,Harmonic 72 1.502 7.71 ,Harmonic 73 2.342 4.5 ,Harmonic 74 0.236 2.94 ,Harmonic 75 (-1.033) 2.8 ,Harmonic 76 (-0.14) 14.32 ,Harmonic 77 (-1.544) 5.19 ,Harmonic 78 (-2.547) 13.22 ,Harmonic 79 (-0.3) 1.77 ,Harmonic 80 0.997 4.74 ,Harmonic 81 (-1.452) 0.37 ,Harmonic 82 2.148 6.02 ,Harmonic 83 0.236 2.77 ,Harmonic 84 (-2.982) 0.76 ,Harmonic 85 (-2.089) 2.81 ,Harmonic 86 2.774 2.48 ,Harmonic 87 (-0.68) 1.92 ,Harmonic 88 (-0.655) 1.56 ,Harmonic 89 (-1.885) 0.65 ,Harmonic 90 (-0.918) 1.36 ,Harmonic 91 (-2.092) 1.68 ,Harmonic 92 (-0.28) 0.35 ,Harmonic 93 (-0.685) 3.18 ,Harmonic 94 (-0.726) 1.27 ,Harmonic 95 (-0.66) 1.55 ,Harmonic 96 (-1.585) 0.22 ,Harmonic 97 (-2.06) 1.1 ,Harmonic 98 3.111 1.37 ,Harmonic 99 (-3.132) 1.26 ,Harmonic 100 (-2.148) 2.4 ,Harmonic 101 (-2.046) 2.36 ,Harmonic 102 (-1.093) 4.34 ,Harmonic 103 (-9.1e-2) 3.71 ,Harmonic 104 1.0e-3 1.32 ,Harmonic 105 1.01 1.83 ,Harmonic 106 1.486 1.39 ,Harmonic 107 3.053 2.12 ,Harmonic 108 (-2.388) 1.56 ,Harmonic 109 (-2.194) 4.87 ,Harmonic 110 (-2.175) 5.84 ,Harmonic 111 (-1.302) 4.19 ,Harmonic 112 (-0.889) 4.15 ,Harmonic 113 (-0.434) 4.99 ,Harmonic 114 (-0.287) 2.97 ,Harmonic 115 0.569 1.29 ,Harmonic 116 (-1.893) 0.81 ,Harmonic 117 (-2.185) 2.12 ,Harmonic 118 (-1.571) 3.35 ,Harmonic 119 (-1.571) 3.45 ,Harmonic 120 (-1.524) 3.32 ,Harmonic 121 (-0.692) 3.91 ,Harmonic 122 (-5.0e-2) 1.89 ,Harmonic 123 (-0.488) 1.38 ,Harmonic 124 (-1.902) 0.97 ,Harmonic 125 (-2.46) 2.76 ,Harmonic 126 (-2.322) 1.76 ,Harmonic 127 (-1.887) 3.36 ,Harmonic 128 (-1.315) 3.7 ,Harmonic 129 (-0.641) 3.21 ,Harmonic 130 (-0.782) 2.47 ,Harmonic 131 1.031 1.69 ,Harmonic 132 1.862 2.81 ,Harmonic 133 2.518 2.19 ,Harmonic 134 (-2.763) 3.8 ,Harmonic 135 (-2.518) 4.2 ,Harmonic 136 (-2.075) 4.27 ,Harmonic 137 (-1.14) 3.82 ,Harmonic 138 (-0.784) 4.95 ,Harmonic 139 (-5.7e-2) 3.92 ,Harmonic 140 0.564 3.93 ,Harmonic 141 0.99 2.49 ,Harmonic 142 1.892 3.77 ,Harmonic 143 2.483 2.58 ,Harmonic 144 (-2.927) 3.33] note1 :: Note note1 = Note (Pitch 73.416 26 "d2") 2 (Range (NoteRange (NoteRangeAmplitude 8809.92 120 0.29) (NoteRangeHarmonicFreq 1 73.41)) (NoteRange (NoteRangeAmplitude 73.41 1 2759.0) (NoteRangeHarmonicFreq 136 9984.57))) [Harmonic 1 (-0.78) 2759.0 ,Harmonic 2 2.902 21.78 ,Harmonic 3 2.672 2318.11 ,Harmonic 4 (-2.879) 54.42 ,Harmonic 5 2.023 2650.25 ,Harmonic 6 1.65 34.71 ,Harmonic 7 0.624 1965.28 ,Harmonic 8 (-2.833) 19.69 ,Harmonic 9 (-0.492) 618.66 ,Harmonic 10 (-2.279) 27.75 ,Harmonic 11 (-1.097) 784.72 ,Harmonic 12 1.815 127.19 ,Harmonic 13 (-3.095) 18.37 ,Harmonic 14 2.387 134.13 ,Harmonic 15 (-1.451) 187.72 ,Harmonic 16 0.723 69.1 ,Harmonic 17 2.937 307.03 ,Harmonic 18 0.888 12.21 ,Harmonic 19 (-2.994) 410.53 ,Harmonic 20 0.4 136.13 ,Harmonic 21 0.635 447.99 ,Harmonic 22 (-2.958) 162.55 ,Harmonic 23 1.506 60.45 ,Harmonic 24 2.438 81.43 ,Harmonic 25 (-2.994) 17.74 ,Harmonic 26 (-1.465) 32.05 ,Harmonic 27 1.044 84.56 ,Harmonic 28 3.032 83.77 ,Harmonic 29 (-1.735) 308.38 ,Harmonic 30 0.474 171.77 ,Harmonic 31 1.864 337.23 ,Harmonic 32 (-2.458) 145.12 ,Harmonic 33 (-0.234) 125.63 ,Harmonic 34 2.194 82.84 ,Harmonic 35 (-2.769) 166.43 ,Harmonic 36 (-1.787) 6.8 ,Harmonic 37 2.567 68.18 ,Harmonic 38 (-2.501) 55.96 ,Harmonic 39 (-0.613) 39.26 ,Harmonic 40 (-0.301) 41.38 ,Harmonic 41 (-0.869) 14.38 ,Harmonic 42 2.075 15.9 ,Harmonic 43 1.298 15.78 ,Harmonic 44 (-1.258) 7.69 ,Harmonic 45 0.5 8.93 ,Harmonic 46 2.445 16.84 ,Harmonic 47 (-1.989) 13.53 ,Harmonic 48 (-0.228) 6.14 ,Harmonic 49 0.503 4.15 ,Harmonic 50 (-0.423) 14.07 ,Harmonic 51 1.172 27.56 ,Harmonic 52 1.07 10.97 ,Harmonic 53 (-2.146) 20.92 ,Harmonic 54 (-0.985) 4.39 ,Harmonic 55 0.198 0.8 ,Harmonic 56 2.092 7.82 ,Harmonic 57 (-0.709) 10.16 ,Harmonic 58 (-0.256) 9.49 ,Harmonic 59 1.506 3.78 ,Harmonic 60 2.538 10.2 ,Harmonic 61 (-2.628) 1.75 ,Harmonic 62 (-1.469) 6.2 ,Harmonic 63 (-2.842) 5.69 ,Harmonic 64 1.72 3.38 ,Harmonic 65 (-3.129) 4.64 ,Harmonic 66 2.469 0.97 ,Harmonic 67 (-2.209) 12.55 ,Harmonic 68 (-0.908) 1.82 ,Harmonic 69 0.354 17.52 ,Harmonic 70 1.422 15.53 ,Harmonic 71 (-2.664) 5.63 ,Harmonic 72 2.526 7.69 ,Harmonic 73 (-1.462) 8.19 ,Harmonic 74 (-0.924) 18.44 ,Harmonic 75 2.013 14.54 ,Harmonic 76 (-3.069) 12.16 ,Harmonic 77 1.979 1.41 ,Harmonic 78 (-2.946) 5.0 ,Harmonic 79 (-3.13) 2.58 ,Harmonic 80 1.044 11.51 ,Harmonic 81 (-2.543) 6.11 ,Harmonic 82 (-2.261) 4.31 ,Harmonic 83 (-1.975) 2.2 ,Harmonic 84 0.753 1.28 ,Harmonic 85 1.098 2.7 ,Harmonic 86 (-2.938) 2.61 ,Harmonic 87 (-0.438) 1.34 ,Harmonic 88 (-0.472) 1.25 ,Harmonic 89 0.749 1.41 ,Harmonic 90 (-0.156) 0.79 ,Harmonic 91 2.891 2.69 ,Harmonic 92 0.57 1.53 ,Harmonic 93 (-2.855) 1.02 ,Harmonic 94 1.33 2.14 ,Harmonic 95 3.033 0.53 ,Harmonic 96 1.002 2.04 ,Harmonic 97 (-1.39) 0.88 ,Harmonic 98 (-0.257) 1.2 ,Harmonic 99 1.429 1.95 ,Harmonic 100 (-1.56) 3.87 ,Harmonic 101 1.728 3.25 ,Harmonic 102 (-1.025) 4.11 ,Harmonic 103 1.818 2.72 ,Harmonic 104 (-0.983) 2.94 ,Harmonic 105 2.207 1.61 ,Harmonic 106 (-0.845) 2.32 ,Harmonic 107 2.916 0.67 ,Harmonic 108 2.645 1.53 ,Harmonic 109 (-0.618) 2.8 ,Harmonic 110 3.027 3.49 ,Harmonic 111 (-0.23) 5.27 ,Harmonic 112 3.004 5.64 ,Harmonic 113 8.7e-2 6.84 ,Harmonic 114 3.087 4.69 ,Harmonic 115 0.313 5.33 ,Harmonic 116 (-2.648) 2.88 ,Harmonic 117 0.631 2.17 ,Harmonic 118 (-2.4) 1.48 ,Harmonic 119 1.839 0.7 ,Harmonic 120 1.646 0.29 ,Harmonic 121 (-2.169) 1.73 ,Harmonic 122 1.37 1.97 ,Harmonic 123 (-1.369) 1.8 ,Harmonic 124 2.057 1.99 ,Harmonic 125 (-0.903) 2.71 ,Harmonic 126 2.232 2.06 ,Harmonic 127 (-0.336) 2.24 ,Harmonic 128 3.095 1.43 ,Harmonic 129 0.232 0.93 ,Harmonic 130 (-1.637) 1.0 ,Harmonic 131 2.207 1.01 ,Harmonic 132 (-0.377) 0.88 ,Harmonic 133 2.723 1.01 ,Harmonic 134 0.286 1.04 ,Harmonic 135 (-1.803) 1.15 ,Harmonic 136 1.096 2.17] note2 :: Note note2 = Note (Pitch 77.782 27 "d#2") 3 (Range (NoteRange (NoteRangeAmplitude 8789.36 113 8.0e-2) (NoteRangeHarmonicFreq 1 77.78)) (NoteRange (NoteRangeAmplitude 77.78 1 2500.0) (NoteRangeHarmonicFreq 128 9956.09))) [Harmonic 1 (-2.365) 2500.0 ,Harmonic 2 (-3.4e-2) 9.73 ,Harmonic 3 (-0.704) 1408.17 ,Harmonic 4 (-1.67) 30.01 ,Harmonic 5 2.309 834.33 ,Harmonic 6 (-1.074) 28.83 ,Harmonic 7 (-1.377) 1143.99 ,Harmonic 8 2.294 43.18 ,Harmonic 9 (-2.98) 377.26 ,Harmonic 10 0.574 68.39 ,Harmonic 11 (-0.206) 302.95 ,Harmonic 12 2.784 37.79 ,Harmonic 13 (-2.232) 267.91 ,Harmonic 14 (-1.757) 83.22 ,Harmonic 15 (-0.294) 393.4 ,Harmonic 16 1.782 18.76 ,Harmonic 17 2.148 21.1 ,Harmonic 18 (-0.596) 142.02 ,Harmonic 19 (-1.643) 308.08 ,Harmonic 20 (-0.483) 201.03 ,Harmonic 21 (-1.241) 144.69 ,Harmonic 22 (-0.553) 44.94 ,Harmonic 23 1.346 82.38 ,Harmonic 24 (-3.124) 49.51 ,Harmonic 25 3.116 80.96 ,Harmonic 26 (-1.461) 86.52 ,Harmonic 27 (-1.176) 150.18 ,Harmonic 28 (-0.553) 128.29 ,Harmonic 29 (-0.475) 202.4 ,Harmonic 30 (-0.343) 129.58 ,Harmonic 31 0.924 116.19 ,Harmonic 32 1.938 60.34 ,Harmonic 33 1.873 93.49 ,Harmonic 34 2.942 19.2 ,Harmonic 35 (-0.988) 31.07 ,Harmonic 36 (-1.262) 47.4 ,Harmonic 37 (-1.691) 3.57 ,Harmonic 38 (-1.548) 26.0 ,Harmonic 39 2.493 15.24 ,Harmonic 40 (-1.348) 9.68 ,Harmonic 41 2.732 9.88 ,Harmonic 42 (-1.583) 7.77 ,Harmonic 43 (-0.615) 13.08 ,Harmonic 44 (-0.902) 2.26 ,Harmonic 45 0.363 8.2 ,Harmonic 46 (-0.579) 6.98 ,Harmonic 47 (-2.012) 18.57 ,Harmonic 48 (-2.29) 18.03 ,Harmonic 49 (-1.933) 5.28 ,Harmonic 50 (-2.245) 14.06 ,Harmonic 51 (-1.827) 1.54 ,Harmonic 52 (-0.972) 10.7 ,Harmonic 53 2.773 2.52 ,Harmonic 54 (-0.212) 13.73 ,Harmonic 55 (-0.933) 3.06 ,Harmonic 56 7.2e-2 16.96 ,Harmonic 57 (-3.037) 3.64 ,Harmonic 58 3.0e-3 5.83 ,Harmonic 59 2.706 2.49 ,Harmonic 60 0.932 2.74 ,Harmonic 61 0.183 5.17 ,Harmonic 62 (-2.848) 2.36 ,Harmonic 63 (-1.327) 8.76 ,Harmonic 64 2.06 2.43 ,Harmonic 65 (-1.349) 12.29 ,Harmonic 66 (-1.675) 11.49 ,Harmonic 67 (-1.376) 1.87 ,Harmonic 68 2.721 8.28 ,Harmonic 69 (-2.271) 5.17 ,Harmonic 70 (-2.721) 17.92 ,Harmonic 71 (-0.993) 9.12 ,Harmonic 72 (-1.063) 4.01 ,Harmonic 73 2.626 3.88 ,Harmonic 74 (-3.068) 3.97 ,Harmonic 75 (-2.202) 1.51 ,Harmonic 76 (-1.878) 6.89 ,Harmonic 77 2.453 0.91 ,Harmonic 78 2.646 2.49 ,Harmonic 79 (-0.991) 2.23 ,Harmonic 80 (-2.488) 1.89 ,Harmonic 81 (-1.211) 1.49 ,Harmonic 82 2.249 0.32 ,Harmonic 83 (-2.757) 0.57 ,Harmonic 84 0.341 0.63 ,Harmonic 85 2.824 0.45 ,Harmonic 86 (-2.342) 0.92 ,Harmonic 87 0.384 0.56 ,Harmonic 88 2.935 1.42 ,Harmonic 89 (-2.069) 1.2 ,Harmonic 90 1.677 0.93 ,Harmonic 91 (-1.733) 0.44 ,Harmonic 92 (-2.49) 1.04 ,Harmonic 93 (-2.347) 1.2 ,Harmonic 94 6.6e-2 2.76 ,Harmonic 95 2.192 2.55 ,Harmonic 96 (-2.062) 4.1 ,Harmonic 97 0.254 2.58 ,Harmonic 98 2.282 3.22 ,Harmonic 99 (-1.929) 4.02 ,Harmonic 100 0.388 1.95 ,Harmonic 101 2.079 1.91 ,Harmonic 102 0.655 1.79 ,Harmonic 103 2.695 2.63 ,Harmonic 104 (-1.499) 3.96 ,Harmonic 105 0.564 5.09 ,Harmonic 106 2.696 5.13 ,Harmonic 107 (-1.598) 5.18 ,Harmonic 108 0.615 3.39 ,Harmonic 109 2.776 3.83 ,Harmonic 110 (-1.188) 1.91 ,Harmonic 111 1.321 2.1 ,Harmonic 112 (-2.819) 1.37 ,Harmonic 113 1.832 8.0e-2 ,Harmonic 114 (-1.96) 0.66 ,Harmonic 115 (-0.682) 1.8 ,Harmonic 116 2.208 1.35 ,Harmonic 117 (-2.216) 1.81 ,Harmonic 118 9.2e-2 1.51 ,Harmonic 119 2.801 1.15 ,Harmonic 120 (-1.302) 0.88 ,Harmonic 121 6.6e-2 0.62 ,Harmonic 122 (-1.832) 0.88 ,Harmonic 123 0.688 0.66 ,Harmonic 124 2.822 0.64 ,Harmonic 125 9.7e-2 0.98 ,Harmonic 126 2.02 1.6 ,Harmonic 127 (-1.719) 1.45 ,Harmonic 128 0.199 1.57] note3 :: Note note3 = Note (Pitch 82.407 28 "e2") 4 (Range (NoteRange (NoteRangeAmplitude 9559.21 116 0.77) (NoteRangeHarmonicFreq 1 82.4)) (NoteRange (NoteRangeAmplitude 247.22 3 4017.0) (NoteRangeHarmonicFreq 120 9888.84))) [Harmonic 1 2.163 3864.97 ,Harmonic 2 (-1.544) 65.44 ,Harmonic 3 1.195 4017.0 ,Harmonic 4 (-1.521) 85.43 ,Harmonic 5 1.217 2949.78 ,Harmonic 6 1.368 48.32 ,Harmonic 7 (-1.414) 738.04 ,Harmonic 8 1.766 45.11 ,Harmonic 9 2.69 370.26 ,Harmonic 10 (-3.062) 242.31 ,Harmonic 11 2.419 919.27 ,Harmonic 12 1.965 331.2 ,Harmonic 13 1.864 1127.05 ,Harmonic 14 1.006 391.44 ,Harmonic 15 1.242 1270.74 ,Harmonic 16 2.146 460.14 ,Harmonic 17 0.203 1645.33 ,Harmonic 18 (-0.189) 395.04 ,Harmonic 19 (-1.564) 1177.02 ,Harmonic 20 (-2.066) 218.76 ,Harmonic 21 2.34 342.64 ,Harmonic 22 1.648 205.65 ,Harmonic 23 0.257 346.48 ,Harmonic 24 3.064 52.6 ,Harmonic 25 0.391 298.56 ,Harmonic 26 (-1.728) 134.6 ,Harmonic 27 2.722 600.33 ,Harmonic 28 0.927 478.6 ,Harmonic 29 0.219 409.06 ,Harmonic 30 (-0.331) 133.01 ,Harmonic 31 (-1.331) 174.78 ,Harmonic 32 (-2.178) 77.48 ,Harmonic 33 (-2.543) 113.3 ,Harmonic 34 1.766 183.63 ,Harmonic 35 (-2.548) 33.27 ,Harmonic 36 (-1.454) 126.13 ,Harmonic 37 1.306 61.87 ,Harmonic 38 1.837 16.47 ,Harmonic 39 2.633 21.6 ,Harmonic 40 2.657 37.62 ,Harmonic 41 1.552 62.67 ,Harmonic 42 1.516 14.29 ,Harmonic 43 (-1.112) 48.54 ,Harmonic 44 2.89 86.62 ,Harmonic 45 1.013 86.18 ,Harmonic 46 (-0.757) 31.54 ,Harmonic 47 (-1.578) 25.34 ,Harmonic 48 2.296 9.26 ,Harmonic 49 2.174 11.67 ,Harmonic 50 0.211 9.59 ,Harmonic 51 (-0.89) 14.32 ,Harmonic 52 (-2.922) 17.36 ,Harmonic 53 1.454 24.35 ,Harmonic 54 (-0.374) 52.41 ,Harmonic 55 (-2.693) 21.94 ,Harmonic 56 (-3.065) 28.62 ,Harmonic 57 1.625 23.04 ,Harmonic 58 (-0.526) 9.13 ,Harmonic 59 (-2.135) 16.32 ,Harmonic 60 (-1.638) 5.56 ,Harmonic 61 (-0.951) 14.96 ,Harmonic 62 1.636 28.44 ,Harmonic 63 0.682 17.28 ,Harmonic 64 (-2.717) 14.84 ,Harmonic 65 1.788 16.98 ,Harmonic 66 0.839 54.22 ,Harmonic 67 (-0.102) 20.15 ,Harmonic 68 (-0.732) 16.64 ,Harmonic 69 (-0.883) 16.47 ,Harmonic 70 (-0.161) 20.98 ,Harmonic 71 (-0.925) 18.11 ,Harmonic 72 (-2.427) 11.2 ,Harmonic 73 3.094 4.06 ,Harmonic 74 (-1.421) 7.47 ,Harmonic 75 (-2.624) 9.92 ,Harmonic 76 2.504 3.01 ,Harmonic 77 1.11 3.48 ,Harmonic 78 0.964 4.61 ,Harmonic 79 1.983 3.5 ,Harmonic 80 2.223 4.77 ,Harmonic 81 1.759 4.06 ,Harmonic 82 3.124 1.67 ,Harmonic 83 2.543 1.3 ,Harmonic 84 (-0.984) 3.45 ,Harmonic 85 (-0.416) 1.02 ,Harmonic 86 1.972 2.07 ,Harmonic 87 2.33 5.03 ,Harmonic 88 3.047 5.0 ,Harmonic 89 (-3.007) 7.73 ,Harmonic 90 (-1.812) 7.15 ,Harmonic 91 (-1.569) 11.78 ,Harmonic 92 (-1.059) 14.92 ,Harmonic 93 (-0.5) 12.64 ,Harmonic 94 (-4.9e-2) 10.97 ,Harmonic 95 0.448 9.98 ,Harmonic 96 1.032 5.68 ,Harmonic 97 2.362 5.53 ,Harmonic 98 (-2.503) 2.94 ,Harmonic 99 (-2.426) 7.48 ,Harmonic 100 (-1.53) 9.21 ,Harmonic 101 (-1.149) 9.65 ,Harmonic 102 (-0.804) 6.84 ,Harmonic 103 0.311 5.44 ,Harmonic 104 1.275 3.27 ,Harmonic 105 1.695 1.97 ,Harmonic 106 2.49 4.45 ,Harmonic 107 (-1.905) 1.39 ,Harmonic 108 (-2.038) 2.23 ,Harmonic 109 (-9.8e-2) 2.93 ,Harmonic 110 1.067 2.99 ,Harmonic 111 1.16 3.92 ,Harmonic 112 1.506 3.43 ,Harmonic 113 1.764 2.47 ,Harmonic 114 (-2.382) 4.85 ,Harmonic 115 2.983 1.07 ,Harmonic 116 0.722 0.77 ,Harmonic 117 (-9.8e-2) 3.54 ,Harmonic 118 0.916 4.92 ,Harmonic 119 1.862 3.9 ,Harmonic 120 2.011 5.8] note4 :: Note note4 = Note (Pitch 87.307 29 "f2") 5 (Range (NoteRange (NoteRangeAmplitude 8818.0 101 0.79) (NoteRangeHarmonicFreq 1 87.3)) (NoteRange (NoteRangeAmplitude 261.92 3 2481.0) (NoteRangeHarmonicFreq 114 9952.99))) [Harmonic 1 0.799 2205.51 ,Harmonic 2 2.274 25.61 ,Harmonic 3 2.33 2481.0 ,Harmonic 4 (-1.563) 69.29 ,Harmonic 5 (-0.263) 1006.89 ,Harmonic 6 2.664 18.57 ,Harmonic 7 (-2.896) 498.68 ,Harmonic 8 2.234 32.41 ,Harmonic 9 0.606 387.55 ,Harmonic 10 (-0.49) 79.01 ,Harmonic 11 (-2.94) 321.94 ,Harmonic 12 2.066 174.21 ,Harmonic 13 0.217 795.65 ,Harmonic 14 (-2.034) 65.09 ,Harmonic 15 1.94 232.97 ,Harmonic 16 9.1e-2 110.24 ,Harmonic 17 (-2.685) 527.32 ,Harmonic 18 (-4.2e-2) 255.24 ,Harmonic 19 3.024 217.18 ,Harmonic 20 (-0.288) 92.34 ,Harmonic 21 (-2.448) 75.6 ,Harmonic 22 0.464 62.06 ,Harmonic 23 (-1.651) 53.36 ,Harmonic 24 2.151 83.03 ,Harmonic 25 0.85 305.21 ,Harmonic 26 3.019 261.56 ,Harmonic 27 0.406 197.21 ,Harmonic 28 3.066 102.8 ,Harmonic 29 1.221 184.96 ,Harmonic 30 (-3.062) 285.1 ,Harmonic 31 1.232 31.73 ,Harmonic 32 0.389 87.35 ,Harmonic 33 0.842 71.42 ,Harmonic 34 0.377 63.65 ,Harmonic 35 0.781 39.89 ,Harmonic 36 0.595 23.36 ,Harmonic 37 0.73 28.47 ,Harmonic 38 (-2.341) 20.06 ,Harmonic 39 0.95 21.47 ,Harmonic 40 2.528 20.33 ,Harmonic 41 0.608 29.29 ,Harmonic 42 2.519 12.64 ,Harmonic 43 (-0.73) 1.95 ,Harmonic 44 1.204 42.99 ,Harmonic 45 (-1.906) 6.93 ,Harmonic 46 (-2.529) 2.14 ,Harmonic 47 0.867 3.84 ,Harmonic 48 1.406 22.26 ,Harmonic 49 (-2.499) 8.05 ,Harmonic 50 1.398 17.84 ,Harmonic 51 (-3.117) 13.41 ,Harmonic 52 0.957 9.17 ,Harmonic 53 1.677 4.73 ,Harmonic 54 (-1.368) 2.71 ,Harmonic 55 1.665 17.05 ,Harmonic 56 2.17 6.19 ,Harmonic 57 1.188 13.36 ,Harmonic 58 2.768 15.55 ,Harmonic 59 (-1.311) 7.48 ,Harmonic 60 2.136 17.68 ,Harmonic 61 2.275 3.61 ,Harmonic 62 0.284 12.44 ,Harmonic 63 3.064 4.37 ,Harmonic 64 0.411 22.79 ,Harmonic 65 (-3.138) 6.69 ,Harmonic 66 (-2.183) 2.26 ,Harmonic 67 1.503 5.88 ,Harmonic 68 (-1.593) 12.91 ,Harmonic 69 1.333 8.24 ,Harmonic 70 0.279 1.57 ,Harmonic 71 (-1.124) 4.02 ,Harmonic 72 2.548 2.82 ,Harmonic 73 0.889 4.32 ,Harmonic 74 (-1.936) 1.57 ,Harmonic 75 (-2.813) 2.18 ,Harmonic 76 2.685 3.13 ,Harmonic 77 1.753 2.82 ,Harmonic 78 0.787 2.84 ,Harmonic 79 9.1e-2 2.61 ,Harmonic 80 (-2.871) 1.34 ,Harmonic 81 (-2.614) 2.11 ,Harmonic 82 1.292 0.83 ,Harmonic 83 (-1.223) 2.22 ,Harmonic 84 (-2.873) 3.01 ,Harmonic 85 2.603 6.05 ,Harmonic 86 1.499 5.55 ,Harmonic 87 0.474 5.26 ,Harmonic 88 (-1.107) 4.63 ,Harmonic 89 (-2.041) 4.22 ,Harmonic 90 3.097 2.85 ,Harmonic 91 2.579 2.63 ,Harmonic 92 2.407 2.64 ,Harmonic 93 2.191 3.5 ,Harmonic 94 0.906 3.9 ,Harmonic 95 (-6.6e-2) 3.94 ,Harmonic 96 (-1.182) 4.25 ,Harmonic 97 (-2.289) 4.07 ,Harmonic 98 (-3.051) 3.65 ,Harmonic 99 2.224 2.43 ,Harmonic 100 1.714 1.95 ,Harmonic 101 1.491 0.79 ,Harmonic 102 1.258 1.1 ,Harmonic 103 1.8e-2 1.27 ,Harmonic 104 (-0.762) 2.49 ,Harmonic 105 (-2.002) 2.1 ,Harmonic 106 (-2.495) 2.41 ,Harmonic 107 2.67 1.15 ,Harmonic 108 2.661 2.27 ,Harmonic 109 1.41 1.24 ,Harmonic 110 1.555 2.41 ,Harmonic 111 (-0.232) 1.64 ,Harmonic 112 (-0.189) 1.46 ,Harmonic 113 (-1.527) 2.11 ,Harmonic 114 (-1.904) 1.6] note5 :: Note note5 = Note (Pitch 92.499 30 "f#2") 6 (Range (NoteRange (NoteRangeAmplitude 6474.92 70 0.18) (NoteRangeHarmonicFreq 1 92.49)) (NoteRange (NoteRangeAmplitude 92.49 1 2611.0) (NoteRangeHarmonicFreq 108 9989.89))) [Harmonic 1 (-2.291) 2611.0 ,Harmonic 2 0.684 29.81 ,Harmonic 3 (-0.317) 2200.14 ,Harmonic 4 (-2.334) 19.02 ,Harmonic 5 (-2.269) 772.32 ,Harmonic 6 (-0.591) 61.3 ,Harmonic 7 1.124 494.31 ,Harmonic 8 2.77 53.46 ,Harmonic 9 (-1.122) 251.98 ,Harmonic 10 1.163 124.22 ,Harmonic 11 (-2.932) 265.41 ,Harmonic 12 (-1.799) 247.97 ,Harmonic 13 (-0.84) 507.44 ,Harmonic 14 1.002 183.12 ,Harmonic 15 1.992 291.99 ,Harmonic 16 (-3.024) 346.99 ,Harmonic 17 1.845 102.48 ,Harmonic 18 2.163 155.24 ,Harmonic 19 2.692 77.86 ,Harmonic 20 (-1.094) 33.11 ,Harmonic 21 2.541 51.96 ,Harmonic 22 2.386 88.06 ,Harmonic 23 (-1.44) 79.66 ,Harmonic 24 9.9e-2 253.87 ,Harmonic 25 (-0.457) 159.05 ,Harmonic 26 0.177 81.1 ,Harmonic 27 (-2.7e-2) 47.87 ,Harmonic 28 0.215 126.24 ,Harmonic 29 (-0.698) 42.64 ,Harmonic 30 (-2.354) 30.42 ,Harmonic 31 3.038 94.91 ,Harmonic 32 1.155 71.31 ,Harmonic 33 0.738 14.48 ,Harmonic 34 1.217 41.32 ,Harmonic 35 3.12 7.96 ,Harmonic 36 (-1.669) 12.26 ,Harmonic 37 (-1.331) 18.42 ,Harmonic 38 0.422 31.53 ,Harmonic 39 (-0.549) 39.44 ,Harmonic 40 (-0.638) 35.51 ,Harmonic 41 (-0.766) 55.06 ,Harmonic 42 0.325 19.22 ,Harmonic 43 (-1.584) 12.76 ,Harmonic 44 1.443 3.13 ,Harmonic 45 (-1.009) 2.54 ,Harmonic 46 0.329 3.88 ,Harmonic 47 (-0.607) 15.44 ,Harmonic 48 1.625 7.09 ,Harmonic 49 (-0.992) 10.98 ,Harmonic 50 2.666 3.35 ,Harmonic 51 (-1.494) 2.86 ,Harmonic 52 2.737 9.54 ,Harmonic 53 0.199 8.1 ,Harmonic 54 3.055 14.69 ,Harmonic 55 1.887 6.37 ,Harmonic 56 1.213 15.08 ,Harmonic 57 0.125 14.52 ,Harmonic 58 0.228 5.87 ,Harmonic 59 (-1.235) 14.68 ,Harmonic 60 0.165 16.49 ,Harmonic 61 (-0.794) 15.73 ,Harmonic 62 1.563 3.74 ,Harmonic 63 (-2.195) 3.64 ,Harmonic 64 (-0.615) 8.36 ,Harmonic 65 (-1.742) 8.19 ,Harmonic 66 (-0.917) 1.25 ,Harmonic 67 2.347 5.29 ,Harmonic 68 (-2.692) 2.97 ,Harmonic 69 (-2.134) 4.15 ,Harmonic 70 (-1.158) 0.18 ,Harmonic 71 2.187 2.34 ,Harmonic 72 (-2.796) 2.81 ,Harmonic 73 (-1.469) 2.14 ,Harmonic 74 2.035 2.07 ,Harmonic 75 (-1.945) 1.72 ,Harmonic 76 1.066 1.16 ,Harmonic 77 (-2.751) 1.48 ,Harmonic 78 1.297 0.97 ,Harmonic 79 2.714 2.1 ,Harmonic 80 (-0.811) 1.54 ,Harmonic 81 1.963 2.38 ,Harmonic 82 (-2.147) 2.73 ,Harmonic 83 0.587 3.76 ,Harmonic 84 2.541 2.74 ,Harmonic 85 (-1.264) 3.87 ,Harmonic 86 1.382 2.73 ,Harmonic 87 (-2.537) 1.54 ,Harmonic 88 0.192 2.27 ,Harmonic 89 3.034 4.21 ,Harmonic 90 (-1.237) 3.13 ,Harmonic 91 1.017 3.77 ,Harmonic 92 (-2.736) 2.96 ,Harmonic 93 (-0.437) 1.3 ,Harmonic 94 2.196 2.02 ,Harmonic 95 (-1.627) 0.85 ,Harmonic 96 1.357 0.77 ,Harmonic 97 (-1.62) 1.23 ,Harmonic 98 0.644 1.1 ,Harmonic 99 2.888 1.68 ,Harmonic 100 (-0.946) 1.43 ,Harmonic 101 2.169 0.99 ,Harmonic 102 (-1.72) 0.5 ,Harmonic 103 2.307 0.81 ,Harmonic 104 (-2.339) 0.89 ,Harmonic 105 1.148 1.12 ,Harmonic 106 (-2.556) 1.2 ,Harmonic 107 (-0.282) 1.14 ,Harmonic 108 2.591 1.25] note6 :: Note note6 = Note (Pitch 97.999 31 "g2") 7 (Range (NoteRange (NoteRangeAmplitude 5781.94 59 1.59) (NoteRangeHarmonicFreq 1 97.99)) (NoteRange (NoteRangeAmplitude 97.99 1 3736.0) (NoteRangeHarmonicFreq 101 9897.89))) [Harmonic 1 0.228 3736.0 ,Harmonic 2 2.712 31.89 ,Harmonic 3 2.127 2915.29 ,Harmonic 4 1.551 19.67 ,Harmonic 5 (-0.855) 704.45 ,Harmonic 6 (-0.677) 36.34 ,Harmonic 7 3.132 1398.36 ,Harmonic 8 1.897 213.86 ,Harmonic 9 (-0.173) 675.42 ,Harmonic 10 (-1.86) 396.58 ,Harmonic 11 2.365 1755.73 ,Harmonic 12 0.83 362.88 ,Harmonic 13 (-2.056) 539.68 ,Harmonic 14 2.361 472.94 ,Harmonic 15 (-1.251) 361.61 ,Harmonic 16 1.455 530.36 ,Harmonic 17 2.759 55.81 ,Harmonic 18 0.425 181.68 ,Harmonic 19 (-2.876) 71.05 ,Harmonic 20 0.729 136.64 ,Harmonic 21 (-0.136) 114.84 ,Harmonic 22 2.604 162.75 ,Harmonic 23 (-0.954) 332.84 ,Harmonic 24 2.101 337.74 ,Harmonic 25 (-1.14) 292.85 ,Harmonic 26 2.418 199.7 ,Harmonic 27 (-2.402) 110.64 ,Harmonic 28 (-1.762) 47.49 ,Harmonic 29 0.653 177.82 ,Harmonic 30 1.156 189.47 ,Harmonic 31 1.141 25.13 ,Harmonic 32 0.114 94.1 ,Harmonic 33 (-1.582) 11.96 ,Harmonic 34 (-0.981) 2.64 ,Harmonic 35 (-1.09) 11.75 ,Harmonic 36 (-2.619) 101.32 ,Harmonic 37 (-0.959) 62.14 ,Harmonic 38 1.662 90.86 ,Harmonic 39 (-2.744) 63.64 ,Harmonic 40 1.345 21.47 ,Harmonic 41 1.294 8.81 ,Harmonic 42 0.69 14.92 ,Harmonic 43 (-2.222) 16.18 ,Harmonic 44 (-0.38) 9.27 ,Harmonic 45 1.873 39.94 ,Harmonic 46 (-1.315) 28.18 ,Harmonic 47 0.623 9.37 ,Harmonic 48 (-2.699) 11.25 ,Harmonic 49 (-0.278) 26.57 ,Harmonic 50 (-1.928) 8.37 ,Harmonic 51 2.795 12.05 ,Harmonic 52 (-2.779) 21.58 ,Harmonic 53 (-0.738) 13.83 ,Harmonic 54 1.574 17.73 ,Harmonic 55 (-2.142) 9.2 ,Harmonic 56 0.255 20.56 ,Harmonic 57 2.86 43.47 ,Harmonic 58 0.239 10.86 ,Harmonic 59 0.255 1.59 ,Harmonic 60 (-2.764) 26.69 ,Harmonic 61 0.362 24.57 ,Harmonic 62 (-0.687) 11.42 ,Harmonic 63 (-1.718) 20.81 ,Harmonic 64 1.652 7.56 ,Harmonic 65 (-0.564) 2.16 ,Harmonic 66 (-2.484) 1.74 ,Harmonic 67 2.735 8.54 ,Harmonic 68 1.252 3.84 ,Harmonic 69 0.0 2.1 ,Harmonic 70 (-0.724) 3.81 ,Harmonic 71 (-1.771) 2.22 ,Harmonic 72 (-2.847) 3.93 ,Harmonic 73 1.773 2.37 ,Harmonic 74 (-1.736) 2.12 ,Harmonic 75 (-2.618) 5.28 ,Harmonic 76 2.251 7.54 ,Harmonic 77 1.027 8.95 ,Harmonic 78 (-0.198) 9.68 ,Harmonic 79 (-1.215) 6.5 ,Harmonic 80 (-1.379) 4.42 ,Harmonic 81 (-1.798) 5.44 ,Harmonic 82 (-2.772) 8.51 ,Harmonic 83 2.344 13.84 ,Harmonic 84 1.196 14.57 ,Harmonic 85 4.9e-2 11.66 ,Harmonic 86 (-1.134) 11.69 ,Harmonic 87 (-2.037) 8.44 ,Harmonic 88 (-2.864) 6.16 ,Harmonic 89 (-3.017) 4.73 ,Harmonic 90 2.529 5.57 ,Harmonic 91 1.655 8.28 ,Harmonic 92 0.585 7.82 ,Harmonic 93 (-0.386) 6.01 ,Harmonic 94 (-1.529) 6.01 ,Harmonic 95 (-2.239) 5.43 ,Harmonic 96 (-3.111) 3.09 ,Harmonic 97 (-3.042) 2.07 ,Harmonic 98 2.297 2.92 ,Harmonic 99 2.003 2.72 ,Harmonic 100 1.094 3.81 ,Harmonic 101 (-0.11) 4.55] note7 :: Note note7 = Note (Pitch 103.826 32 "g#2") 8 (Range (NoteRange (NoteRangeAmplitude 7163.99 69 0.55) (NoteRangeHarmonicFreq 1 103.82)) (NoteRange (NoteRangeAmplitude 103.82 1 2107.0) (NoteRangeHarmonicFreq 96 9967.29))) [Harmonic 1 (-1.962) 2107.0 ,Harmonic 2 3.054 35.68 ,Harmonic 3 1.151 539.81 ,Harmonic 4 2.013 16.19 ,Harmonic 5 2.168 617.95 ,Harmonic 6 (-0.545) 75.85 ,Harmonic 7 0.484 914.82 ,Harmonic 8 (-2.626) 227.47 ,Harmonic 9 (-0.717) 618.01 ,Harmonic 10 1.66 396.64 ,Harmonic 11 2.694 757.31 ,Harmonic 12 (-1.659) 153.82 ,Harmonic 13 0.524 359.57 ,Harmonic 14 1.585 117.2 ,Harmonic 15 0.154 215.87 ,Harmonic 16 0.868 112.12 ,Harmonic 17 1.482 251.61 ,Harmonic 18 (-1.411) 135.92 ,Harmonic 19 (-1.581) 89.98 ,Harmonic 20 1.889 120.22 ,Harmonic 21 1.094 146.77 ,Harmonic 22 2.078 202.29 ,Harmonic 23 1.4 210.61 ,Harmonic 24 (-3.037) 92.34 ,Harmonic 25 2.616 117.23 ,Harmonic 26 (-0.638) 12.91 ,Harmonic 27 0.217 95.73 ,Harmonic 28 (-0.701) 114.43 ,Harmonic 29 2.922 22.46 ,Harmonic 30 (-0.895) 37.98 ,Harmonic 31 2.67 2.48 ,Harmonic 32 (-1.848) 30.49 ,Harmonic 33 (-2.351) 46.18 ,Harmonic 34 4.0e-2 75.01 ,Harmonic 35 (-0.464) 87.35 ,Harmonic 36 (-0.31) 20.22 ,Harmonic 37 (-1.007) 14.61 ,Harmonic 38 (-0.266) 14.59 ,Harmonic 39 (-0.186) 16.59 ,Harmonic 40 1.946 11.36 ,Harmonic 41 0.911 23.62 ,Harmonic 42 1.127 31.01 ,Harmonic 43 0.93 20.82 ,Harmonic 44 0.406 10.31 ,Harmonic 45 0.997 3.9 ,Harmonic 46 1.574 8.63 ,Harmonic 47 (-0.424) 6.76 ,Harmonic 48 (-0.726) 3.9 ,Harmonic 49 (-1.654) 27.44 ,Harmonic 50 (-2.289) 26.92 ,Harmonic 51 (-1.718) 17.45 ,Harmonic 52 (-2.859) 7.91 ,Harmonic 53 (-1.761) 26.15 ,Harmonic 54 (-0.842) 18.14 ,Harmonic 55 1.501 3.62 ,Harmonic 56 (-2.919) 9.57 ,Harmonic 57 (-0.71) 10.94 ,Harmonic 58 2.741 5.5 ,Harmonic 59 (-2.012) 7.37 ,Harmonic 60 0.955 8.22 ,Harmonic 61 2.921 9.06 ,Harmonic 62 (-2.137) 3.93 ,Harmonic 63 8.3e-2 1.62 ,Harmonic 64 (-2.828) 3.94 ,Harmonic 65 (-0.956) 3.66 ,Harmonic 66 2.326 1.94 ,Harmonic 67 (-0.813) 2.96 ,Harmonic 68 1.555 3.07 ,Harmonic 69 (-0.423) 0.55 ,Harmonic 70 (-1.896) 2.11 ,Harmonic 71 1.459 4.57 ,Harmonic 72 (-2.085) 6.42 ,Harmonic 73 0.965 7.97 ,Harmonic 74 (-2.894) 6.76 ,Harmonic 75 0.329 5.37 ,Harmonic 76 3.117 4.34 ,Harmonic 77 1.301 5.17 ,Harmonic 78 (-1.97) 7.39 ,Harmonic 79 0.957 9.59 ,Harmonic 80 (-2.403) 9.45 ,Harmonic 81 0.379 6.55 ,Harmonic 82 (-2.836) 7.13 ,Harmonic 83 0.651 5.51 ,Harmonic 84 (-2.753) 1.31 ,Harmonic 85 1.079 2.61 ,Harmonic 86 (-1.278) 5.0 ,Harmonic 87 1.502 2.63 ,Harmonic 88 (-1.718) 4.03 ,Harmonic 89 1.71 2.89 ,Harmonic 90 (-1.483) 2.33 ,Harmonic 91 2.681 2.48 ,Harmonic 92 (-0.185) 2.17 ,Harmonic 93 2.704 2.03 ,Harmonic 94 (-5.7e-2) 3.19 ,Harmonic 95 3.059 3.42 ,Harmonic 96 (-1.5e-2) 4.31] note8 :: Note note8 = Note (Pitch 110.0 33 "a2") 9 (Range (NoteRange (NoteRangeAmplitude 5060.0 46 1.07) (NoteRangeHarmonicFreq 1 110.0)) (NoteRange (NoteRangeAmplitude 110.0 1 3048.0) (NoteRangeHarmonicFreq 90 9900.0))) [Harmonic 1 0.305 3048.0 ,Harmonic 2 1.457 29.38 ,Harmonic 3 2.323 1495.14 ,Harmonic 4 2.974 32.62 ,Harmonic 5 1.417 233.02 ,Harmonic 6 0.672 95.89 ,Harmonic 7 (-2.284) 1346.64 ,Harmonic 8 2.871 314.66 ,Harmonic 9 1.324 933.52 ,Harmonic 10 (-1.461) 524.19 ,Harmonic 11 2.889 621.3 ,Harmonic 12 1.682 62.02 ,Harmonic 13 (-2.966) 268.03 ,Harmonic 14 0.545 261.81 ,Harmonic 15 1.334 188.76 ,Harmonic 16 (-1.032) 313.18 ,Harmonic 17 1.909 191.46 ,Harmonic 18 1.231 241.0 ,Harmonic 19 (-2.081) 172.89 ,Harmonic 20 0.144 159.15 ,Harmonic 21 2.062 324.78 ,Harmonic 22 (-0.247) 144.37 ,Harmonic 23 1.561 115.0 ,Harmonic 24 (-2.539) 13.82 ,Harmonic 25 2.92 74.2 ,Harmonic 26 (-1.454) 23.94 ,Harmonic 27 1.055 27.85 ,Harmonic 28 1.464 53.77 ,Harmonic 29 (-1.662) 7.55 ,Harmonic 30 (-1.415) 25.34 ,Harmonic 31 1.541 30.85 ,Harmonic 32 (-0.893) 87.51 ,Harmonic 33 0.885 115.27 ,Harmonic 34 2.942 45.71 ,Harmonic 35 (-1.995) 18.24 ,Harmonic 36 0.822 33.73 ,Harmonic 37 (-2.791) 9.07 ,Harmonic 38 1.221 23.76 ,Harmonic 39 2.617 17.35 ,Harmonic 40 (-1.426) 33.27 ,Harmonic 41 0.743 12.37 ,Harmonic 42 2.56 23.38 ,Harmonic 43 3.2e-2 4.05 ,Harmonic 44 2.309 22.22 ,Harmonic 45 0.841 10.75 ,Harmonic 46 2.271 1.07 ,Harmonic 47 (-1.635) 33.05 ,Harmonic 48 (-5.0e-3) 17.31 ,Harmonic 49 2.547 8.52 ,Harmonic 50 (-2.737) 28.59 ,Harmonic 51 1.038 37.6 ,Harmonic 52 (-0.648) 5.14 ,Harmonic 53 (-1.052) 11.26 ,Harmonic 54 1.379 17.58 ,Harmonic 55 0.903 4.67 ,Harmonic 56 (-1.446) 13.84 ,Harmonic 57 (-3.026) 14.64 ,Harmonic 58 1.563 8.76 ,Harmonic 59 1.665 5.66 ,Harmonic 60 2.996 3.79 ,Harmonic 61 0.422 1.93 ,Harmonic 62 0.793 2.12 ,Harmonic 63 (-0.843) 2.23 ,Harmonic 64 (-1.647) 3.86 ,Harmonic 65 (-2.625) 2.13 ,Harmonic 66 (-1.904) 1.32 ,Harmonic 67 (-1.835) 3.66 ,Harmonic 68 (-2.756) 5.85 ,Harmonic 69 2.329 6.55 ,Harmonic 70 1.141 6.46 ,Harmonic 71 (-0.359) 4.53 ,Harmonic 72 (-0.507) 2.35 ,Harmonic 73 (-0.423) 6.15 ,Harmonic 74 (-1.705) 10.13 ,Harmonic 75 (-2.687) 11.52 ,Harmonic 76 2.518 10.57 ,Harmonic 77 1.494 8.95 ,Harmonic 78 0.544 7.13 ,Harmonic 79 (-0.557) 5.27 ,Harmonic 80 (-0.116) 1.9 ,Harmonic 81 (-1.124) 1.41 ,Harmonic 82 (-1.878) 4.75 ,Harmonic 83 (-2.7) 4.86 ,Harmonic 84 2.711 2.94 ,Harmonic 85 2.485 2.27 ,Harmonic 86 1.097 2.66 ,Harmonic 87 1.472 1.78 ,Harmonic 88 0.941 2.47 ,Harmonic 89 0.293 1.57 ,Harmonic 90 (-0.271) 3.98] note9 :: Note note9 = Note (Pitch 116.541 34 "a#2") 10 (Range (NoteRange (NoteRangeAmplitude 9556.36 82 0.47) (NoteRangeHarmonicFreq 1 116.54)) (NoteRange (NoteRangeAmplitude 116.54 1 2783.0) (NoteRangeHarmonicFreq 85 9905.98))) [Harmonic 1 (-2.944) 2783.0 ,Harmonic 2 1.075 41.93 ,Harmonic 3 (-4.1e-2) 1411.6 ,Harmonic 4 2.189 7.35 ,Harmonic 5 (-1.186) 2180.43 ,Harmonic 6 0.657 169.47 ,Harmonic 7 1.391 1419.53 ,Harmonic 8 (-2.754) 437.11 ,Harmonic 9 (-1.344) 2755.36 ,Harmonic 10 (-0.478) 191.51 ,Harmonic 11 0.775 794.39 ,Harmonic 12 1.15 211.23 ,Harmonic 13 (-1.675) 624.93 ,Harmonic 14 (-2.401) 349.23 ,Harmonic 15 (-2.148) 258.12 ,Harmonic 16 (-1.25) 180.55 ,Harmonic 17 0.907 318.9 ,Harmonic 18 1.772 31.36 ,Harmonic 19 (-2.068) 409.6 ,Harmonic 20 (-2.17) 391.69 ,Harmonic 21 (-3.058) 271.66 ,Harmonic 22 3.051 180.9 ,Harmonic 23 (-1.121) 79.0 ,Harmonic 24 (-2.621) 96.37 ,Harmonic 25 (-2.195) 98.8 ,Harmonic 26 0.506 118.94 ,Harmonic 27 (-1.088) 6.38 ,Harmonic 28 2.796 21.65 ,Harmonic 29 1.966 57.55 ,Harmonic 30 2.819 107.62 ,Harmonic 31 1.255 133.69 ,Harmonic 32 (-0.76) 45.42 ,Harmonic 33 (-1.169) 55.37 ,Harmonic 34 3.112 16.21 ,Harmonic 35 3.068 22.05 ,Harmonic 36 (-2.92) 24.02 ,Harmonic 37 1.442 37.86 ,Harmonic 38 0.333 32.52 ,Harmonic 39 (-1.369) 17.34 ,Harmonic 40 2.823 13.92 ,Harmonic 41 2.662 24.49 ,Harmonic 42 (-0.365) 5.29 ,Harmonic 43 (-1.504) 30.5 ,Harmonic 44 (-2.286) 58.55 ,Harmonic 45 (-3.059) 48.75 ,Harmonic 46 (-0.995) 5.1 ,Harmonic 47 0.29 62.86 ,Harmonic 48 (-0.255) 41.68 ,Harmonic 49 1.258 19.52 ,Harmonic 50 1.337 14.19 ,Harmonic 51 2.971 34.12 ,Harmonic 52 (-1.269) 9.28 ,Harmonic 53 0.439 13.09 ,Harmonic 54 0.645 18.26 ,Harmonic 55 1.943 3.48 ,Harmonic 56 (-2.496) 5.7 ,Harmonic 57 (-1.103) 2.47 ,Harmonic 58 1.556 10.62 ,Harmonic 59 (-1.936) 2.71 ,Harmonic 60 (-1.756) 6.51 ,Harmonic 61 2.163 0.55 ,Harmonic 62 (-6.2e-2) 1.34 ,Harmonic 63 1.243 4.28 ,Harmonic 64 (-2.996) 4.97 ,Harmonic 65 (-0.526) 5.4 ,Harmonic 66 1.84 5.93 ,Harmonic 67 (-2.782) 5.98 ,Harmonic 68 (-0.212) 6.65 ,Harmonic 69 2.982 8.75 ,Harmonic 70 (-1.231) 9.04 ,Harmonic 71 0.911 14.79 ,Harmonic 72 (-2.944) 10.67 ,Harmonic 73 (-1.192) 9.27 ,Harmonic 74 1.298 9.03 ,Harmonic 75 (-2.384) 4.48 ,Harmonic 76 1.988 2.16 ,Harmonic 77 (-2.549) 6.07 ,Harmonic 78 (-0.436) 7.25 ,Harmonic 79 1.45 5.35 ,Harmonic 80 (-2.009) 6.14 ,Harmonic 81 (-0.322) 2.85 ,Harmonic 82 (-1.425) 0.47 ,Harmonic 83 0.35 2.41 ,Harmonic 84 1.99 4.01 ,Harmonic 85 (-1.636) 5.95] note10 :: Note note10 = Note (Pitch 123.471 35 "b2") 11 (Range (NoteRange (NoteRangeAmplitude 6667.43 54 0.49) (NoteRangeHarmonicFreq 1 123.47)) (NoteRange (NoteRangeAmplitude 123.47 1 2723.0) (NoteRangeHarmonicFreq 81 10001.15))) [Harmonic 1 (-1.178) 2723.0 ,Harmonic 2 (-2.597) 24.56 ,Harmonic 3 (-2.076) 985.25 ,Harmonic 4 (-1.99) 10.98 ,Harmonic 5 (-0.298) 845.12 ,Harmonic 6 (-2.712) 294.25 ,Harmonic 7 (-1.006) 673.76 ,Harmonic 8 2.768 421.64 ,Harmonic 9 (-2.232) 806.06 ,Harmonic 10 1.839 126.3 ,Harmonic 11 2.063 342.85 ,Harmonic 12 (-2.876) 366.74 ,Harmonic 13 1.075 116.43 ,Harmonic 14 (-2.06) 172.49 ,Harmonic 15 (-0.742) 330.88 ,Harmonic 16 (-2.633) 242.3 ,Harmonic 17 (-2.572) 33.66 ,Harmonic 18 2.734 193.52 ,Harmonic 19 2.627 410.16 ,Harmonic 20 (-1.158) 65.72 ,Harmonic 21 (-2.045) 63.63 ,Harmonic 22 (-8.8e-2) 9.24 ,Harmonic 23 2.141 51.25 ,Harmonic 24 0.374 134.48 ,Harmonic 25 (-1.333) 42.54 ,Harmonic 26 (-0.55) 12.23 ,Harmonic 27 (-0.379) 30.77 ,Harmonic 28 2.036 25.97 ,Harmonic 29 1.216 80.9 ,Harmonic 30 0.13 11.19 ,Harmonic 31 0.272 39.62 ,Harmonic 32 0.546 5.71 ,Harmonic 33 1.674 15.22 ,Harmonic 34 1.288 2.24 ,Harmonic 35 2.164 23.4 ,Harmonic 36 0.828 14.93 ,Harmonic 37 2.757 11.07 ,Harmonic 38 0.503 14.68 ,Harmonic 39 1.208 4.88 ,Harmonic 40 (-0.325) 4.41 ,Harmonic 41 (-0.427) 11.08 ,Harmonic 42 0.399 29.75 ,Harmonic 43 1.102 11.66 ,Harmonic 44 0.695 1.69 ,Harmonic 45 0.37 43.2 ,Harmonic 46 2.35 12.68 ,Harmonic 47 (-0.61) 20.29 ,Harmonic 48 2.387 6.89 ,Harmonic 49 (-0.915) 5.11 ,Harmonic 50 (-0.546) 6.95 ,Harmonic 51 2.937 13.4 ,Harmonic 52 (-0.656) 5.79 ,Harmonic 53 2.344 2.08 ,Harmonic 54 1.027 0.49 ,Harmonic 55 (-3.04) 1.97 ,Harmonic 56 (-1.592) 2.59 ,Harmonic 57 (-3.121) 3.33 ,Harmonic 58 2.809 1.91 ,Harmonic 59 (-1.461) 2.75 ,Harmonic 60 (-3.006) 3.14 ,Harmonic 61 (-0.364) 4.14 ,Harmonic 62 (-2.685) 5.92 ,Harmonic 63 0.79 2.01 ,Harmonic 64 (-1.952) 3.58 ,Harmonic 65 (-2.784) 3.14 ,Harmonic 66 0.437 5.01 ,Harmonic 67 (-2.769) 6.25 ,Harmonic 68 1.218 8.53 ,Harmonic 69 (-0.983) 2.84 ,Harmonic 70 0.93 3.95 ,Harmonic 71 (-0.342) 4.87 ,Harmonic 72 (-0.847) 2.17 ,Harmonic 73 (-2.0) 0.92 ,Harmonic 74 (-0.519) 6.14 ,Harmonic 75 (-2.99) 1.99 ,Harmonic 76 6.3e-2 3.48 ,Harmonic 77 (-2.051) 3.86 ,Harmonic 78 (-1.486) 1.43 ,Harmonic 79 0.786 2.42 ,Harmonic 80 (-1.605) 2.62 ,Harmonic 81 1.528 3.32] note11 :: Note note11 = Note (Pitch 130.813 36 "c3") 12 (Range (NoteRange (NoteRangeAmplitude 9549.34 73 0.75) (NoteRangeHarmonicFreq 1 130.81)) (NoteRange (NoteRangeAmplitude 130.81 1 3250.0) (NoteRangeHarmonicFreq 76 9941.78))) [Harmonic 1 1.651 3250.0 ,Harmonic 2 (-2.084) 29.1 ,Harmonic 3 (-1.282) 522.51 ,Harmonic 4 1.97 13.41 ,Harmonic 5 2.627 1145.4 ,Harmonic 6 1.737 176.37 ,Harmonic 7 2.035 908.75 ,Harmonic 8 0.209 656.73 ,Harmonic 9 (-2.1e-2) 707.2 ,Harmonic 10 (-0.127) 87.87 ,Harmonic 11 1.719 542.62 ,Harmonic 12 (-0.667) 26.58 ,Harmonic 13 0.772 218.0 ,Harmonic 14 0.483 103.07 ,Harmonic 15 1.458 189.73 ,Harmonic 16 (-2.892) 19.35 ,Harmonic 17 (-0.682) 278.23 ,Harmonic 18 1.33 199.0 ,Harmonic 19 1.344 185.77 ,Harmonic 20 2.001 75.76 ,Harmonic 21 (-1.934) 20.42 ,Harmonic 22 (-0.386) 132.71 ,Harmonic 23 0.33 127.44 ,Harmonic 24 (-0.657) 8.15 ,Harmonic 25 (-1.893) 16.78 ,Harmonic 26 1.336 18.54 ,Harmonic 27 8.3e-2 56.26 ,Harmonic 28 1.942 69.79 ,Harmonic 29 (-0.377) 27.07 ,Harmonic 30 1.055 26.25 ,Harmonic 31 0.887 3.54 ,Harmonic 32 (-3.115) 25.69 ,Harmonic 33 (-2.437) 6.78 ,Harmonic 34 2.071 34.5 ,Harmonic 35 (-3.108) 5.65 ,Harmonic 36 1.828 2.91 ,Harmonic 37 (-1.646) 11.08 ,Harmonic 38 (-1.375) 10.67 ,Harmonic 39 1.04 26.3 ,Harmonic 40 (-2.25) 62.07 ,Harmonic 41 (-1.175) 2.03 ,Harmonic 42 3.026 39.11 ,Harmonic 43 1.234 9.74 ,Harmonic 44 2.447 9.21 ,Harmonic 45 (-0.518) 4.98 ,Harmonic 46 2.75 3.8 ,Harmonic 47 (-2.632) 14.83 ,Harmonic 48 (-2.919) 6.96 ,Harmonic 49 2.535 13.71 ,Harmonic 50 (-2.883) 5.66 ,Harmonic 51 2.506 4.8 ,Harmonic 52 0.685 2.3 ,Harmonic 53 2.051 10.55 ,Harmonic 54 1.807 5.09 ,Harmonic 55 0.352 1.95 ,Harmonic 56 (-1.757) 2.93 ,Harmonic 57 (-0.726) 3.56 ,Harmonic 58 (-0.799) 8.08 ,Harmonic 59 (-0.838) 6.37 ,Harmonic 60 (-0.351) 6.67 ,Harmonic 61 0.808 4.79 ,Harmonic 62 1.315 7.33 ,Harmonic 63 1.638 8.0 ,Harmonic 64 2.192 8.39 ,Harmonic 65 2.29 6.73 ,Harmonic 66 2.497 4.45 ,Harmonic 67 (-2.819) 4.12 ,Harmonic 68 (-1.066) 2.09 ,Harmonic 69 (-0.885) 4.43 ,Harmonic 70 (-0.674) 4.95 ,Harmonic 71 0.222 2.84 ,Harmonic 72 1.007 3.83 ,Harmonic 73 (-3.0e-2) 0.75 ,Harmonic 74 1.813 2.32 ,Harmonic 75 2.833 3.76 ,Harmonic 76 (-2.725) 3.08] note12 :: Note note12 = Note (Pitch 138.591 37 "c#3") 13 (Range (NoteRange (NoteRangeAmplitude 9562.77 69 0.66) (NoteRangeHarmonicFreq 1 138.59)) (NoteRange (NoteRangeAmplitude 138.59 1 2407.0) (NoteRangeHarmonicFreq 72 9978.55))) [Harmonic 1 (-1.113) 2407.0 ,Harmonic 2 (-2.009) 28.64 ,Harmonic 3 0.202 616.95 ,Harmonic 4 4.9e-2 41.26 ,Harmonic 5 2.41 957.92 ,Harmonic 6 (-0.298) 238.2 ,Harmonic 7 (-3.131) 927.59 ,Harmonic 8 (-0.273) 288.75 ,Harmonic 9 1.967 277.26 ,Harmonic 10 (-2.135) 141.14 ,Harmonic 11 3.122 159.66 ,Harmonic 12 (-2.736) 473.59 ,Harmonic 13 0.235 105.61 ,Harmonic 14 (-1.582) 105.17 ,Harmonic 15 (-8.9e-2) 81.87 ,Harmonic 16 (-1.828) 220.71 ,Harmonic 17 (-2.143) 347.45 ,Harmonic 18 1.456 157.09 ,Harmonic 19 (-0.81) 142.66 ,Harmonic 20 (-1.631) 10.79 ,Harmonic 21 (-1.952) 108.79 ,Harmonic 22 2.111 87.77 ,Harmonic 23 (-2.315) 9.97 ,Harmonic 24 2.222 21.7 ,Harmonic 25 1.304 33.16 ,Harmonic 26 (-1.864) 102.83 ,Harmonic 27 2.851 83.8 ,Harmonic 28 (-1.73) 28.72 ,Harmonic 29 2.735 8.89 ,Harmonic 30 0.477 23.29 ,Harmonic 31 (-0.967) 6.99 ,Harmonic 32 1.671 11.38 ,Harmonic 33 (-1.547) 20.54 ,Harmonic 34 (-3.125) 19.87 ,Harmonic 35 (-5.0e-3) 6.91 ,Harmonic 36 (-1.892) 45.49 ,Harmonic 37 (-2.979) 13.51 ,Harmonic 38 (-1.674) 56.59 ,Harmonic 39 1.98 16.28 ,Harmonic 40 (-1.286) 36.04 ,Harmonic 41 (-1.1) 12.79 ,Harmonic 42 (-1.051) 14.41 ,Harmonic 43 (-1.135) 15.26 ,Harmonic 44 (-2.947) 8.5 ,Harmonic 45 (-0.942) 14.58 ,Harmonic 46 2.412 7.41 ,Harmonic 47 (-1.825) 1.68 ,Harmonic 48 2.115 1.05 ,Harmonic 49 0.541 7.46 ,Harmonic 50 (-1.155) 6.02 ,Harmonic 51 1.274 6.58 ,Harmonic 52 1.895 2.65 ,Harmonic 53 (-1.118) 2.58 ,Harmonic 54 (-2.799) 2.02 ,Harmonic 55 0.921 3.59 ,Harmonic 56 (-1.247) 5.06 ,Harmonic 57 (-3.061) 2.33 ,Harmonic 58 2.08 3.76 ,Harmonic 59 (-0.214) 4.38 ,Harmonic 60 (-2.477) 5.72 ,Harmonic 61 1.44 4.95 ,Harmonic 62 (-0.448) 3.33 ,Harmonic 63 (-2.631) 2.8 ,Harmonic 64 1.369 3.2 ,Harmonic 65 1.809 2.02 ,Harmonic 66 (-0.757) 1.66 ,Harmonic 67 (-2.987) 2.72 ,Harmonic 68 0.807 4.54 ,Harmonic 69 6.0e-3 0.66 ,Harmonic 70 (-0.705) 1.36 ,Harmonic 71 3.138 1.77 ,Harmonic 72 1.768 1.67] note13 :: Note note13 = Note (Pitch 146.832 38 "d3") 14 (Range (NoteRange (NoteRangeAmplitude 6754.27 46 2.13) (NoteRangeHarmonicFreq 1 146.83)) (NoteRange (NoteRangeAmplitude 146.83 1 3477.0) (NoteRangeHarmonicFreq 68 9984.57))) [Harmonic 1 (-1.855) 3477.0 ,Harmonic 2 (-1.926) 12.83 ,Harmonic 3 (-2.367) 451.19 ,Harmonic 4 2.469 130.4 ,Harmonic 5 (-0.799) 1561.77 ,Harmonic 6 0.853 209.8 ,Harmonic 7 (-1.735) 2595.07 ,Harmonic 8 (-1.656) 542.59 ,Harmonic 9 0.227 267.56 ,Harmonic 10 0.774 36.04 ,Harmonic 11 (-0.776) 897.04 ,Harmonic 12 (-0.824) 254.42 ,Harmonic 13 (-3.121) 234.67 ,Harmonic 14 (-1.937) 143.98 ,Harmonic 15 2.302 527.55 ,Harmonic 16 1.896 634.75 ,Harmonic 17 2.716 117.87 ,Harmonic 18 0.929 191.41 ,Harmonic 19 2.883 41.06 ,Harmonic 20 (-1.283) 76.5 ,Harmonic 21 0.867 93.09 ,Harmonic 22 (-1.269) 21.82 ,Harmonic 23 (-0.407) 80.33 ,Harmonic 24 (-1.068) 70.81 ,Harmonic 25 (-1.505) 109.3 ,Harmonic 26 2.957 117.39 ,Harmonic 27 (-1.59) 24.93 ,Harmonic 28 2.492 11.37 ,Harmonic 29 (-2.623) 32.79 ,Harmonic 30 1.165 38.3 ,Harmonic 31 0.957 19.67 ,Harmonic 32 (-0.569) 16.67 ,Harmonic 33 (-1.244) 38.06 ,Harmonic 34 (-2.844) 7.5 ,Harmonic 35 2.734 17.61 ,Harmonic 36 0.891 43.95 ,Harmonic 37 (-0.441) 9.6 ,Harmonic 38 (-0.406) 67.15 ,Harmonic 39 0.562 46.81 ,Harmonic 40 (-2.622) 48.55 ,Harmonic 41 (-1.909) 25.29 ,Harmonic 42 0.792 15.12 ,Harmonic 43 1.601 15.1 ,Harmonic 44 2.797 14.66 ,Harmonic 45 0.28 5.15 ,Harmonic 46 (-2.835) 2.13 ,Harmonic 47 (-1.035) 10.9 ,Harmonic 48 2.968 9.48 ,Harmonic 49 (-2.483) 8.54 ,Harmonic 50 (-1.874) 3.21 ,Harmonic 51 2.903 2.62 ,Harmonic 52 (-0.663) 9.97 ,Harmonic 53 2.995 12.28 ,Harmonic 54 (-0.661) 9.76 ,Harmonic 55 (-2.096) 5.93 ,Harmonic 56 1.082 7.48 ,Harmonic 57 (-1.481) 11.86 ,Harmonic 58 1.889 8.86 ,Harmonic 59 (-0.871) 12.91 ,Harmonic 60 2.535 4.08 ,Harmonic 61 7.7e-2 3.7 ,Harmonic 62 (-1.995) 6.49 ,Harmonic 63 1.121 6.98 ,Harmonic 64 (-1.359) 2.3 ,Harmonic 65 (-3.1) 2.34 ,Harmonic 66 0.747 2.18 ,Harmonic 67 (-1.425) 3.83 ,Harmonic 68 2.463 2.5] note14 :: Note note14 = Note (Pitch 155.563 39 "d#3") 15 (Range (NoteRange (NoteRangeAmplitude 9800.46 63 1.03) (NoteRangeHarmonicFreq 1 155.56)) (NoteRange (NoteRangeAmplitude 155.56 1 2518.0) (NoteRangeHarmonicFreq 64 9956.03))) [Harmonic 1 1.998 2518.0 ,Harmonic 2 (-2.368) 24.8 ,Harmonic 3 2.134 692.03 ,Harmonic 4 (-1.334) 99.49 ,Harmonic 5 (-1.572) 1971.54 ,Harmonic 6 (-1.346) 280.28 ,Harmonic 7 (-1.524) 2108.79 ,Harmonic 8 0.256 110.66 ,Harmonic 9 1.01 266.19 ,Harmonic 10 (-0.774) 117.57 ,Harmonic 11 0.281 471.16 ,Harmonic 12 0.691 153.39 ,Harmonic 13 1.509 387.87 ,Harmonic 14 (-1.661) 5.05 ,Harmonic 15 (-1.239) 504.92 ,Harmonic 16 1.936 325.34 ,Harmonic 17 (-1.646) 48.19 ,Harmonic 18 (-1.568) 55.15 ,Harmonic 19 (-1.052) 132.24 ,Harmonic 20 (-1.097) 26.33 ,Harmonic 21 0.153 28.31 ,Harmonic 22 2.116 37.93 ,Harmonic 23 0.642 53.8 ,Harmonic 24 (-0.673) 19.28 ,Harmonic 25 (-0.735) 26.41 ,Harmonic 26 (-0.251) 10.62 ,Harmonic 27 0.769 21.27 ,Harmonic 28 1.47 30.49 ,Harmonic 29 1.224 35.46 ,Harmonic 30 (-1.127) 7.38 ,Harmonic 31 1.151 60.82 ,Harmonic 32 (-2.075) 3.07 ,Harmonic 33 0.565 48.51 ,Harmonic 34 1.338 41.49 ,Harmonic 35 (-0.875) 11.88 ,Harmonic 36 1.051 35.95 ,Harmonic 37 (-0.471) 14.35 ,Harmonic 38 (-5.7e-2) 22.33 ,Harmonic 39 (-2.835) 2.49 ,Harmonic 40 (-1.022) 3.86 ,Harmonic 41 2.585 13.73 ,Harmonic 42 0.164 2.32 ,Harmonic 43 2.345 8.31 ,Harmonic 44 1.73 14.61 ,Harmonic 45 2.946 6.97 ,Harmonic 46 2.062 15.33 ,Harmonic 47 (-1.224) 3.7 ,Harmonic 48 0.965 6.63 ,Harmonic 49 1.145 7.85 ,Harmonic 50 2.116 9.76 ,Harmonic 51 2.393 6.51 ,Harmonic 52 (-1.983) 3.18 ,Harmonic 53 (-1.569) 7.76 ,Harmonic 54 0.436 4.49 ,Harmonic 55 (-0.276) 4.44 ,Harmonic 56 2.215 4.21 ,Harmonic 57 (-2.706) 3.72 ,Harmonic 58 (-2.284) 4.2 ,Harmonic 59 (-8.0e-3) 5.79 ,Harmonic 60 (-0.7) 1.03 ,Harmonic 61 1.861 3.28 ,Harmonic 62 (-2.839) 2.88 ,Harmonic 63 (-1.656) 1.03 ,Harmonic 64 (-0.278) 3.12] note15 :: Note note15 = Note (Pitch 164.814 40 "e3") 16 (Range (NoteRange (NoteRangeAmplitude 9559.21 58 0.38) (NoteRangeHarmonicFreq 1 164.81)) (NoteRange (NoteRangeAmplitude 164.81 1 2986.0) (NoteRangeHarmonicFreq 60 9888.84))) [Harmonic 1 1.482 2986.0 ,Harmonic 2 (-1.929) 2.85 ,Harmonic 3 3.096 231.42 ,Harmonic 4 3.115 75.34 ,Harmonic 5 1.628 878.69 ,Harmonic 6 1.263 175.54 ,Harmonic 7 0.837 1096.04 ,Harmonic 8 2.501 9.48 ,Harmonic 9 1.554 676.97 ,Harmonic 10 2.998 367.22 ,Harmonic 11 0.891 308.89 ,Harmonic 12 0.141 175.84 ,Harmonic 13 1.229 212.43 ,Harmonic 14 2.629 148.55 ,Harmonic 15 0.697 203.34 ,Harmonic 16 0.103 87.47 ,Harmonic 17 (-2.092) 11.6 ,Harmonic 18 (-2.406) 65.08 ,Harmonic 19 2.482 64.61 ,Harmonic 20 1.151 7.56 ,Harmonic 21 1.303 59.84 ,Harmonic 22 2.247 43.53 ,Harmonic 23 (-0.781) 24.18 ,Harmonic 24 (-0.74) 22.83 ,Harmonic 25 (-2.858) 8.18 ,Harmonic 26 (-1.091) 43.86 ,Harmonic 27 (-0.41) 4.18 ,Harmonic 28 2.84 6.99 ,Harmonic 29 2.631 26.66 ,Harmonic 30 0.688 11.5 ,Harmonic 31 0.787 31.77 ,Harmonic 32 1.438 15.09 ,Harmonic 33 (-2.842) 6.08 ,Harmonic 34 (-1.305) 30.17 ,Harmonic 35 (-1.98) 10.21 ,Harmonic 36 2.875 19.95 ,Harmonic 37 2.845 5.53 ,Harmonic 38 (-0.636) 4.87 ,Harmonic 39 3.032 2.37 ,Harmonic 40 (-2.912) 5.38 ,Harmonic 41 2.109 8.62 ,Harmonic 42 1.964 2.84 ,Harmonic 43 1.953 3.88 ,Harmonic 44 (-2.103) 3.81 ,Harmonic 45 (-1.454) 2.38 ,Harmonic 46 (-1.262) 7.58 ,Harmonic 47 (-1.214) 5.78 ,Harmonic 48 (-0.789) 1.45 ,Harmonic 49 0.758 2.37 ,Harmonic 50 1.605 3.74 ,Harmonic 51 1.33 4.91 ,Harmonic 52 2.791 1.79 ,Harmonic 53 2.924 1.78 ,Harmonic 54 (-1.874) 2.23 ,Harmonic 55 (-1.842) 3.98 ,Harmonic 56 (-1.202) 2.55 ,Harmonic 57 (-1.219) 1.13 ,Harmonic 58 0.627 0.38 ,Harmonic 59 1.435 2.35 ,Harmonic 60 2.677 2.58] note16 :: Note note16 = Note (Pitch 174.614 41 "f3") 17 (Range (NoteRange (NoteRangeAmplitude 9952.99 57 1.58) (NoteRangeHarmonicFreq 1 174.61)) (NoteRange (NoteRangeAmplitude 174.61 1 2889.0) (NoteRangeHarmonicFreq 57 9952.99))) [Harmonic 1 2.173 2889.0 ,Harmonic 2 (-0.695) 9.87 ,Harmonic 3 3.0e-2 1402.38 ,Harmonic 4 1.405 162.77 ,Harmonic 5 0.995 1384.55 ,Harmonic 6 2.239 372.47 ,Harmonic 7 1.925 940.96 ,Harmonic 8 (-1.827) 59.58 ,Harmonic 9 1.66 279.95 ,Harmonic 10 0.464 43.93 ,Harmonic 11 0.792 346.4 ,Harmonic 12 0.25 9.76 ,Harmonic 13 (-0.697) 266.98 ,Harmonic 14 3.107 174.39 ,Harmonic 15 (-0.744) 280.97 ,Harmonic 16 1.664 65.72 ,Harmonic 17 (-1.629) 109.4 ,Harmonic 18 (-1.725) 56.39 ,Harmonic 19 (-0.116) 21.3 ,Harmonic 20 (-0.463) 37.9 ,Harmonic 21 0.488 39.72 ,Harmonic 22 (-0.128) 18.86 ,Harmonic 23 0.303 32.06 ,Harmonic 24 1.048 13.92 ,Harmonic 25 1.161 48.82 ,Harmonic 26 0.944 46.26 ,Harmonic 27 0.266 13.3 ,Harmonic 28 1.028 26.71 ,Harmonic 29 1.273 29.19 ,Harmonic 30 (-0.454) 12.35 ,Harmonic 31 1.805 18.04 ,Harmonic 32 2.756 9.15 ,Harmonic 33 1.293 20.06 ,Harmonic 34 (-0.823) 3.71 ,Harmonic 35 (-8.0e-3) 32.35 ,Harmonic 36 (-1.861) 3.72 ,Harmonic 37 0.939 8.13 ,Harmonic 38 0.743 6.35 ,Harmonic 39 2.596 11.55 ,Harmonic 40 (-2.982) 4.57 ,Harmonic 41 (-2.735) 6.67 ,Harmonic 42 0.64 2.38 ,Harmonic 43 (-2.764) 3.92 ,Harmonic 44 (-2.007) 5.63 ,Harmonic 45 (-0.473) 4.17 ,Harmonic 46 1.363 1.92 ,Harmonic 47 (-2.213) 7.27 ,Harmonic 48 (-0.907) 8.16 ,Harmonic 49 0.509 9.2 ,Harmonic 50 1.841 6.42 ,Harmonic 51 (-2.837) 3.28 ,Harmonic 52 (-0.73) 4.62 ,Harmonic 53 1.439 4.18 ,Harmonic 54 (-3.072) 2.39 ,Harmonic 55 (-1.707) 3.5 ,Harmonic 56 0.198 2.55 ,Harmonic 57 2.641 1.58] note17 :: Note note17 = Note (Pitch 184.997 42 "f#3") 18 (Range (NoteRange (NoteRangeAmplitude 7399.88 40 1.08) (NoteRangeHarmonicFreq 1 184.99)) (NoteRange (NoteRangeAmplitude 184.99 1 3197.0) (NoteRangeHarmonicFreq 54 9989.83))) [Harmonic 1 1.249 3197.0 ,Harmonic 2 2.926 4.76 ,Harmonic 3 2.527 524.98 ,Harmonic 4 (-2.926) 100.34 ,Harmonic 5 1.674 549.24 ,Harmonic 6 1.759 274.91 ,Harmonic 7 (-2.703) 137.64 ,Harmonic 8 2.119 207.84 ,Harmonic 9 1.984 358.55 ,Harmonic 10 1.811 106.41 ,Harmonic 11 (-0.205) 271.4 ,Harmonic 12 (-2.345) 110.15 ,Harmonic 13 0.209 334.28 ,Harmonic 14 (-2.948) 28.81 ,Harmonic 15 (-2.15) 120.26 ,Harmonic 16 1.007 74.47 ,Harmonic 17 (-5.1e-2) 40.88 ,Harmonic 18 (-1.929) 20.97 ,Harmonic 19 (-1.469) 86.46 ,Harmonic 20 (-3.091) 8.89 ,Harmonic 21 0.226 37.0 ,Harmonic 22 (-1.199) 2.76 ,Harmonic 23 (-2.019) 27.29 ,Harmonic 24 (-2.877) 8.09 ,Harmonic 25 0.832 15.69 ,Harmonic 26 3.6e-2 43.52 ,Harmonic 27 0.22 10.14 ,Harmonic 28 (-1.846) 39.88 ,Harmonic 29 (-2.62) 24.7 ,Harmonic 30 (-2.014) 31.79 ,Harmonic 31 0.966 32.31 ,Harmonic 32 1.076 3.98 ,Harmonic 33 (-3.092) 23.36 ,Harmonic 34 1.624 3.18 ,Harmonic 35 0.583 4.7 ,Harmonic 36 (-0.598) 6.01 ,Harmonic 37 (-6.5e-2) 5.41 ,Harmonic 38 (-1.085) 4.21 ,Harmonic 39 (-0.642) 1.49 ,Harmonic 40 1.805 1.08 ,Harmonic 41 2.069 5.12 ,Harmonic 42 2.741 4.99 ,Harmonic 43 2.868 4.59 ,Harmonic 44 (-1.834) 6.31 ,Harmonic 45 (-1.646) 4.61 ,Harmonic 46 (-1.75) 5.84 ,Harmonic 47 (-1.22) 5.8 ,Harmonic 48 (-0.372) 2.07 ,Harmonic 49 0.313 4.49 ,Harmonic 50 1.033 3.53 ,Harmonic 51 1.23 3.76 ,Harmonic 52 2.272 3.04 ,Harmonic 53 2.858 3.2 ,Harmonic 54 (-2.846) 2.13] note18 :: Note note18 = Note (Pitch 195.998 43 "g3") 19 (Range (NoteRange (NoteRangeAmplitude 391.99 2 2.81) (NoteRangeHarmonicFreq 1 195.99)) (NoteRange (NoteRangeAmplitude 195.99 1 3812.0) (NoteRangeHarmonicFreq 51 9995.89))) [Harmonic 1 1.781 3812.0 ,Harmonic 2 (-0.539) 2.81 ,Harmonic 3 (-0.754) 557.33 ,Harmonic 4 0.314 235.37 ,Harmonic 5 0.622 403.92 ,Harmonic 6 0.738 237.35 ,Harmonic 7 (-3.099) 39.6 ,Harmonic 8 (-1.12) 224.66 ,Harmonic 9 (-2.958) 194.12 ,Harmonic 10 (-1.586) 245.24 ,Harmonic 11 (-2.499) 163.11 ,Harmonic 12 1.604 591.79 ,Harmonic 13 (-3.137) 76.53 ,Harmonic 14 (-0.39) 70.69 ,Harmonic 15 (-0.891) 158.84 ,Harmonic 16 (-1.523) 69.08 ,Harmonic 17 (-1.882) 9.78 ,Harmonic 18 2.724 36.57 ,Harmonic 19 (-2.76) 50.73 ,Harmonic 20 1.109 20.59 ,Harmonic 21 1.558 5.64 ,Harmonic 22 0.243 14.84 ,Harmonic 23 2.3e-2 45.15 ,Harmonic 24 (-2.135) 11.47 ,Harmonic 25 3.0e-3 20.13 ,Harmonic 26 (-1.002) 16.71 ,Harmonic 27 1.035 42.73 ,Harmonic 28 1.256 28.5 ,Harmonic 29 (-1.298) 15.61 ,Harmonic 30 (-1.354) 11.42 ,Harmonic 31 2.556 16.11 ,Harmonic 32 (-2.783) 32.32 ,Harmonic 33 2.442 5.01 ,Harmonic 34 (-3.13) 9.71 ,Harmonic 35 (-2.43) 15.98 ,Harmonic 36 (-1.375) 7.01 ,Harmonic 37 (-2.128) 9.57 ,Harmonic 38 (-2.444) 6.38 ,Harmonic 39 (-1.575) 12.07 ,Harmonic 40 (-0.793) 6.29 ,Harmonic 41 1.58 16.2 ,Harmonic 42 2.576 5.35 ,Harmonic 43 (-2.562) 7.58 ,Harmonic 44 (-0.587) 8.15 ,Harmonic 45 0.888 4.1 ,Harmonic 46 3.065 6.57 ,Harmonic 47 (-2.347) 4.67 ,Harmonic 48 7.4e-2 4.13 ,Harmonic 49 2.09 4.67 ,Harmonic 50 (-2.413) 4.24 ,Harmonic 51 (-0.918) 4.0] note19 :: Note note19 = Note (Pitch 207.652 44 "g#3") 20 (Range (NoteRange (NoteRangeAmplitude 9967.29 48 1.56) (NoteRangeHarmonicFreq 1 207.65)) (NoteRange (NoteRangeAmplitude 207.65 1 3272.0) (NoteRangeHarmonicFreq 48 9967.29))) [Harmonic 1 1.737 3272.0 ,Harmonic 2 (-1.021) 7.0 ,Harmonic 3 (-0.683) 301.62 ,Harmonic 4 0.334 147.82 ,Harmonic 5 0.965 597.64 ,Harmonic 6 0.888 105.41 ,Harmonic 7 2.551 314.03 ,Harmonic 8 (-1.376) 513.87 ,Harmonic 9 (-1.877) 171.9 ,Harmonic 10 (-2.211) 96.76 ,Harmonic 11 1.476 401.47 ,Harmonic 12 0.195 92.39 ,Harmonic 13 (-7.5e-2) 186.6 ,Harmonic 14 (-2.999) 35.3 ,Harmonic 15 3.042 23.4 ,Harmonic 16 1.296 24.63 ,Harmonic 17 1.639 56.48 ,Harmonic 18 (-1.068) 62.59 ,Harmonic 19 (-2.322) 7.28 ,Harmonic 20 (-2.859) 13.19 ,Harmonic 21 (-2.385) 35.99 ,Harmonic 22 2.809 4.77 ,Harmonic 23 0.504 16.74 ,Harmonic 24 1.066 28.76 ,Harmonic 25 1.002 17.86 ,Harmonic 26 2.192 9.97 ,Harmonic 27 (-0.631) 24.74 ,Harmonic 28 0.359 17.42 ,Harmonic 29 1.548 11.48 ,Harmonic 30 2.734 19.68 ,Harmonic 31 1.44 11.27 ,Harmonic 32 0.995 8.02 ,Harmonic 33 (-2.634) 6.59 ,Harmonic 34 (-3.094) 4.51 ,Harmonic 35 (-2.073) 4.28 ,Harmonic 36 (-1.804) 4.82 ,Harmonic 37 (-2.669) 3.74 ,Harmonic 38 (-1.319) 5.14 ,Harmonic 39 (-8.3e-2) 8.84 ,Harmonic 40 1.431 9.58 ,Harmonic 41 2.635 7.56 ,Harmonic 42 (-1.954) 4.29 ,Harmonic 43 (-0.343) 3.19 ,Harmonic 44 1.815 4.61 ,Harmonic 45 2.993 3.74 ,Harmonic 46 (-1.193) 1.62 ,Harmonic 47 1.107 1.78 ,Harmonic 48 (-2.915) 1.56] note20 :: Note note20 = Note (Pitch 220.0 45 "a3") 21 (Range (NoteRange (NoteRangeAmplitude 9460.0 43 3.82) (NoteRangeHarmonicFreq 1 220.0)) (NoteRange (NoteRangeAmplitude 220.0 1 5021.0) (NoteRangeHarmonicFreq 45 9900.0))) [Harmonic 1 (-1.997) 5021.0 ,Harmonic 2 (-7.4e-2) 250.21 ,Harmonic 3 (-1.934) 2400.45 ,Harmonic 4 1.654 128.18 ,Harmonic 5 (-1.61) 988.04 ,Harmonic 6 2.081 203.74 ,Harmonic 7 (-0.651) 2153.48 ,Harmonic 8 (-0.156) 675.24 ,Harmonic 9 1.734 933.65 ,Harmonic 10 (-2.956) 883.97 ,Harmonic 11 (-1.403) 334.15 ,Harmonic 12 (-1.034) 243.41 ,Harmonic 13 (-0.486) 307.69 ,Harmonic 14 (-1.825) 17.26 ,Harmonic 15 (-0.436) 28.0 ,Harmonic 16 (-1.541) 210.01 ,Harmonic 17 (-2.08) 41.33 ,Harmonic 18 (-1.927) 109.8 ,Harmonic 19 (-1.14) 35.1 ,Harmonic 20 (-1.835) 55.92 ,Harmonic 21 2.48 37.44 ,Harmonic 22 (-2.207) 21.51 ,Harmonic 23 (-0.196) 14.46 ,Harmonic 24 (-1.417) 31.38 ,Harmonic 25 1.806 67.93 ,Harmonic 26 3.087 21.17 ,Harmonic 27 1.977 30.37 ,Harmonic 28 (-7.5e-2) 13.07 ,Harmonic 29 0.954 7.12 ,Harmonic 30 1.396 5.12 ,Harmonic 31 1.275 10.15 ,Harmonic 32 0.231 9.52 ,Harmonic 33 2.866 8.48 ,Harmonic 34 2.229 9.98 ,Harmonic 35 1.564 7.3 ,Harmonic 36 1.769 8.84 ,Harmonic 37 1.433 14.46 ,Harmonic 38 1.075 16.6 ,Harmonic 39 0.853 11.57 ,Harmonic 40 0.885 6.42 ,Harmonic 41 1.612 5.42 ,Harmonic 42 1.221 7.91 ,Harmonic 43 1.886 3.82 ,Harmonic 44 2.118 4.72 ,Harmonic 45 2.003 11.76] note21 :: Note note21 = Note (Pitch 233.082 46 "a#3") 22 (Range (NoteRange (NoteRangeAmplitude 9556.36 41 1.6) (NoteRangeHarmonicFreq 1 233.08)) (NoteRange (NoteRangeAmplitude 233.08 1 5010.0) (NoteRangeHarmonicFreq 43 10022.52))) [Harmonic 1 1.204 5010.0 ,Harmonic 2 0.472 134.97 ,Harmonic 3 (-2.831) 1796.14 ,Harmonic 4 2.829 64.24 ,Harmonic 5 (-2.305) 825.91 ,Harmonic 6 2.695 100.53 ,Harmonic 7 6.7e-2 1358.52 ,Harmonic 8 2.571 252.62 ,Harmonic 9 3.14 453.08 ,Harmonic 10 (-0.51) 825.53 ,Harmonic 11 (-2.771) 335.76 ,Harmonic 12 2.389 279.34 ,Harmonic 13 2.747 262.74 ,Harmonic 14 (-0.561) 15.98 ,Harmonic 15 1.788 99.89 ,Harmonic 16 (-3.044) 61.85 ,Harmonic 17 (-0.132) 43.29 ,Harmonic 18 2.776 62.77 ,Harmonic 19 (-2.079) 29.82 ,Harmonic 20 (-0.334) 29.35 ,Harmonic 21 2.005 21.57 ,Harmonic 22 1.621 10.5 ,Harmonic 23 2.486 25.8 ,Harmonic 24 (-1.502) 37.36 ,Harmonic 25 (-1.667) 12.31 ,Harmonic 26 1.36 3.59 ,Harmonic 27 (-1.876) 2.87 ,Harmonic 28 2.403 2.7 ,Harmonic 29 (-2.642) 3.39 ,Harmonic 30 (-0.207) 5.48 ,Harmonic 31 0.107 3.82 ,Harmonic 32 2.329 7.69 ,Harmonic 33 (-1.886) 9.74 ,Harmonic 34 1.499 2.07 ,Harmonic 35 (-2.133) 12.93 ,Harmonic 36 (-0.276) 11.39 ,Harmonic 37 2.401 8.98 ,Harmonic 38 (-1.057) 2.13 ,Harmonic 39 2.8 3.42 ,Harmonic 40 (-1.353) 3.41 ,Harmonic 41 2.986 1.6 ,Harmonic 42 (-0.3) 4.9 ,Harmonic 43 2.255 4.42] note22 :: Note note22 = Note (Pitch 246.942 47 "b3") 23 (Range (NoteRange (NoteRangeAmplitude 7161.31 29 2.53) (NoteRangeHarmonicFreq 1 246.94)) (NoteRange (NoteRangeAmplitude 246.94 1 4774.0) (NoteRangeHarmonicFreq 40 9877.68))) [Harmonic 1 (-1.645) 4774.0 ,Harmonic 2 (-0.149) 112.48 ,Harmonic 3 3.14 111.29 ,Harmonic 4 1.582 241.35 ,Harmonic 5 (-5.8e-2) 1496.2 ,Harmonic 6 (-1.2e-2) 350.24 ,Harmonic 7 2.214 363.13 ,Harmonic 8 2.85 398.41 ,Harmonic 9 2.584 420.88 ,Harmonic 10 2.744 303.99 ,Harmonic 11 (-2.509) 102.27 ,Harmonic 12 (-1.551) 80.73 ,Harmonic 13 (-1.496) 5.39 ,Harmonic 14 1.347 39.6 ,Harmonic 15 1.574 178.89 ,Harmonic 16 0.783 40.53 ,Harmonic 17 (-1.132) 35.89 ,Harmonic 18 2.925 57.59 ,Harmonic 19 1.894 14.67 ,Harmonic 20 (-0.134) 27.88 ,Harmonic 21 2.737 51.34 ,Harmonic 22 0.296 42.71 ,Harmonic 23 2.787 21.25 ,Harmonic 24 3.001 16.71 ,Harmonic 25 2.368 13.03 ,Harmonic 26 (-1.809) 11.6 ,Harmonic 27 (-1.718) 6.45 ,Harmonic 28 2.482 6.18 ,Harmonic 29 1.581 2.53 ,Harmonic 30 (-2.39) 11.26 ,Harmonic 31 2.678 14.01 ,Harmonic 32 1.529 4.77 ,Harmonic 33 2.752 9.61 ,Harmonic 34 1.472 13.75 ,Harmonic 35 0.984 5.51 ,Harmonic 36 1.149 6.1 ,Harmonic 37 2.3e-2 6.4 ,Harmonic 38 1.13 3.2 ,Harmonic 39 0.957 5.27 ,Harmonic 40 0.165 7.81] note23 :: Note note23 = Note (Pitch 261.626 48 "c4") 24 (Range (NoteRange (NoteRangeAmplitude 6540.65 25 0.77) (NoteRangeHarmonicFreq 1 261.62)) (NoteRange (NoteRangeAmplitude 261.62 1 3720.0) (NoteRangeHarmonicFreq 38 9941.78))) [Harmonic 1 (-1.972) 3720.0 ,Harmonic 2 0.826 20.09 ,Harmonic 3 4.9e-2 650.32 ,Harmonic 4 2.741 151.69 ,Harmonic 5 (-0.119) 249.43 ,Harmonic 6 (-1.139) 348.48 ,Harmonic 7 0.577 176.44 ,Harmonic 8 0.435 123.81 ,Harmonic 9 (-0.719) 304.1 ,Harmonic 10 (-1.887) 27.63 ,Harmonic 11 2.87 36.96 ,Harmonic 12 1.004 16.41 ,Harmonic 13 (-1.277) 43.18 ,Harmonic 14 2.848 67.99 ,Harmonic 15 2.111 22.02 ,Harmonic 16 0.689 32.16 ,Harmonic 17 (-2.361) 18.32 ,Harmonic 18 2.883 12.34 ,Harmonic 19 (-1.748) 8.2 ,Harmonic 20 1.377 15.25 ,Harmonic 21 0.163 9.89 ,Harmonic 22 2.057 11.59 ,Harmonic 23 0.502 9.7 ,Harmonic 24 2.333 2.62 ,Harmonic 25 (-2.535) 0.77 ,Harmonic 26 (-2.014) 2.76 ,Harmonic 27 1.104 1.24 ,Harmonic 28 (-0.943) 2.44 ,Harmonic 29 (-1.505) 7.51 ,Harmonic 30 3.021 4.27 ,Harmonic 31 (-1.901) 4.38 ,Harmonic 32 2.763 8.02 ,Harmonic 33 1.499 2.76 ,Harmonic 34 (-3.121) 1.99 ,Harmonic 35 1.838 3.14 ,Harmonic 36 1.884 0.86 ,Harmonic 37 2.275 2.44 ,Harmonic 38 1.54 3.07] note24 :: Note note24 = Note (Pitch 277.183 49 "c#4") 25 (Range (NoteRange (NoteRangeAmplitude 8869.85 32 2.04) (NoteRangeHarmonicFreq 1 277.18)) (NoteRange (NoteRangeAmplitude 277.18 1 3035.0) (NoteRangeHarmonicFreq 36 9978.58))) [Harmonic 1 0.939 3035.0 ,Harmonic 2 1.343 32.53 ,Harmonic 3 3.103 711.59 ,Harmonic 4 2.392 227.61 ,Harmonic 5 2.143 894.68 ,Harmonic 6 2.077 182.7 ,Harmonic 7 (-0.809) 234.97 ,Harmonic 8 1.973 154.42 ,Harmonic 9 (-1.364) 151.75 ,Harmonic 10 2.148 109.05 ,Harmonic 11 0.92 61.99 ,Harmonic 12 0.494 16.7 ,Harmonic 13 2.114 81.26 ,Harmonic 14 1.699 28.25 ,Harmonic 15 (-3.065) 5.41 ,Harmonic 16 (-2.302) 35.35 ,Harmonic 17 2.181 4.97 ,Harmonic 18 (-2.588) 19.4 ,Harmonic 19 (-2.674) 25.04 ,Harmonic 20 2.403 26.23 ,Harmonic 21 (-3.091) 8.32 ,Harmonic 22 (-2.981) 8.51 ,Harmonic 23 (-1.365) 5.91 ,Harmonic 24 0.772 2.36 ,Harmonic 25 2.768 4.7 ,Harmonic 26 0.785 2.95 ,Harmonic 27 3.078 4.1 ,Harmonic 28 (-1.935) 7.21 ,Harmonic 29 1.6 3.76 ,Harmonic 30 (-2.992) 10.0 ,Harmonic 31 (-1.096) 4.52 ,Harmonic 32 2.452 2.04 ,Harmonic 33 (-1.336) 4.51 ,Harmonic 34 0.446 2.08 ,Harmonic 35 (-1.803) 2.39 ,Harmonic 36 0.95 3.83]
anton-k/sharc-timbre
src/Sharc/Instruments/BassClarinet.hs
bsd-3-clause
67,262
0
15
18,555
26,838
13,927
12,911
2,271
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} -- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- module Feldspar.Core.Constructs.Mutable ( module Feldspar.Core.Constructs.Mutable , module Language.Syntactic.Constructs.Monad ) where import Data.Map import Data.Typeable import System.IO.Unsafe import Language.Syntactic import Language.Syntactic.Constructs.Binding import Language.Syntactic.Constructs.Binding.HigherOrder import Language.Syntactic.Constructs.Monad import Feldspar.Core.Types import Feldspar.Core.Interpretation import Feldspar.Core.Constructs.Binding data Mutable a where Run :: Type a => Mutable (Mut a :-> Full a) instance Semantic Mutable where semantics Run = Sem "runMutable" unsafePerformIO instance Equality Mutable where equal = equalDefault; exprHash = exprHashDefault instance Render Mutable where renderArgs = renderArgsDefault instance ToTree Mutable instance Eval Mutable where evaluate = evaluateDefault instance EvalBind Mutable where evalBindSym = evalBindSymDefault instance Sharable Mutable instance Typed Mutable where typeDictSym Run = Just Dict instance AlphaEq dom dom dom env => AlphaEq Mutable Mutable dom env where alphaEqSym = alphaEqSymDefault instance Sharable (MONAD Mut) instance SizeProp (MONAD Mut) where sizeProp Return (WrapFull a :* Nil) = infoSize a sizeProp Bind (_ :* WrapFull f :* Nil) = snd $ infoSize f sizeProp Then (_ :* WrapFull b :* Nil) = infoSize b sizeProp When _ = AnySize instance SizeProp Mutable where sizeProp Run (WrapFull a :* Nil) = infoSize a monadProxy :: P Mut monadProxy = P instance ( MONAD Mut :<: dom , (Variable :|| Type) :<: dom , CLambda Type :<: dom , Let :<: dom , OptimizeSuper dom) => Optimize (MONAD Mut) dom where optimizeFeat opts bnd@Bind (ma :* f :* Nil) = do ma' <- optimizeM opts ma case getInfo ma' of Info (MutType ty) sz vs src -> do f' <- optimizeFunction opts (optimizeM opts) (Info ty sz vs src) f case getInfo f' of Info{} -> constructFeat opts bnd (ma' :* f' :* Nil) optimizeFeat opts a args = optimizeFeatDefault opts a args constructFeatOpt _ Bind (ma :* (lam :$ (ret :$ var)) :* Nil) | Just (SubConstr2 (Lambda v1)) <- prjLambda lam , Just Return <- prjMonad monadProxy ret , Just (C' (Variable v2)) <- prjF var , v1 == v2 , Just ma' <- gcast ma = return ma' constructFeatOpt opts Bind (ma :* (lam :$ body) :* Nil) | Just (SubConstr2 (Lambda v)) <- prjLambda lam , v `notMember` vars = constructFeat opts Then (ma :* body :* Nil) where vars = infoVars $ getInfo body -- (bind e1 (\x -> e2) >> e3 ==> bind e1 (\x -> e2 >> e3) constructFeatOpt opts Then ((bnd :$ x :$ (lam :$ bd)) :* y :* Nil) | Just Bind <- prjMonad monadProxy bnd , Just lam'@(SubConstr2 (Lambda v1)) <- prjLambda lam = do bb <- constructFeat opts Then (bd :* y :* Nil) bd' <- constructFeat opts (reuseCLambda lam') (bb :* Nil) constructFeatUnOpt opts Bind (x :* bd' :* Nil) -- (bind (bind e1 (\x -> e2)) (\y -> e3) => bind e1 (\x -> bind e2 (\y-> e3)) constructFeatOpt opts Bind ((bnd :$ x :$ (lam :$ bd)) :* y :* Nil) | Just Bind <- prjMonad monadProxy bnd , Just lam'@(SubConstr2 (Lambda v1)) <- prjLambda lam = do bb <- constructFeat opts Bind (bd :* y :* Nil) bd' <- constructFeat opts (reuseCLambda lam') (bb :* Nil) constructFeatUnOpt opts Bind (x :* bd' :* Nil) -- return x >> mb ==> mb constructFeatOpt _ Then ((ret :$ _) :* mb :* Nil) | Just Return <- prjMonad monadProxy ret = return mb -- ma >> return () ==> ma constructFeatOpt _ Then (ma :* (ret :$ u) :* Nil) | Just Return <- prjMonad monadProxy ret , Just TypeEq <- typeEq (infoType $ getInfo ma) (MutType UnitType) , Just TypeEq <- typeEq (infoType $ getInfo ret) (MutType UnitType) , Just () <- viewLiteral u = return ma constructFeatOpt opts a args = constructFeatUnOpt opts a args constructFeatUnOpt opts Return args@(a :* Nil) | Info {infoType = t} <- getInfo a = constructFeatUnOptDefaultTyp opts (MutType t) Return args constructFeatUnOpt opts Bind args@(_ :* f@(lam :$ body) :* Nil) | Just (SubConstr2 (Lambda _)) <- prjLambda lam , Info {infoType = t} <- getInfo body = constructFeatUnOptDefaultTyp opts t Bind args constructFeatUnOpt opts Then args@(_ :* mb :* Nil) | Info {infoType = t} <- getInfo mb = constructFeatUnOptDefaultTyp opts t Then args constructFeatUnOpt opts When args = constructFeatUnOptDefaultTyp opts voidTypeRep When args instance (Mutable :<: dom, MONAD Mut :<: dom, OptimizeSuper dom) => Optimize Mutable dom where constructFeatUnOpt _ Run ((ret :$ a) :* Nil) | Just Return <- prjMonad monadProxy ret = return a constructFeatUnOpt opts Run args = constructFeatUnOptDefault opts Run args
rCEx/feldspar-lang-small
src/Feldspar/Core/Constructs/Mutable.hs
bsd-3-clause
7,003
0
19
1,740
1,785
905
880
111
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} module CLaSH.Util.CoreHW.Traverse (startContext ,transformationStep ,changed ) where -- External Modules import Control.Monad (liftM, liftM2) import qualified Data.Label.PureM as Label import Data.Monoid (Monoid, mempty, mconcat, mappend) import Language.KURE hiding (apply) import qualified Language.KURE as KURE -- Internal Modules import CLaSH.Util import qualified CLaSH.Util.CoreHW.Syntax as C import qualified CLaSH.Util.CoreHW.Types as C import CLaSH.Util.Pretty startContext :: [C.CoreContext] startContext = [] data CoreGeneric = CTerm C.Term instance Term C.Term where type Generic C.Term = CoreGeneric select (CTerm e) = Just e inject = CTerm instance Term CoreGeneric where type Generic CoreGeneric = CoreGeneric inject = id select = Just apply :: Monad m => C.CoreContext -> Translate m [C.CoreContext] e1 e2 -> e1 -> RewriteM m [C.CoreContext] e2 apply c rw e = mapEnvM (c:) $ KURE.apply rw e varR :: (Monoid dec, Monad m) => Rewrite m dec C.Term varR = transparently $ rewrite $ \e -> case e of (C.Var x) -> return (C.Var x) _ -> fail "varR" varU :: (Monad m, Monoid dec, Monoid r) => Translate m dec C.Term r varU = translate $ \e -> case e of (C.Var x) -> return $ mempty (C.Var x) _ -> fail "varU" primR :: (Monoid dec, Monad m) => Rewrite m dec C.Term primR = transparently $ rewrite $ \e -> case e of (C.Prim x) -> return (C.Prim x) _ -> fail "varR" primU :: (Monad m, Monoid dec, Monoid r) => Translate m dec C.Term r primU = translate $ \e -> case e of (C.Prim x) -> return $ mempty (C.Prim x) _ -> fail "varU" litR :: (Monoid dec, Monad m) => Rewrite m dec C.Term litR = transparently $ rewrite $ \e -> case e of (C.Literal x) -> return (C.Literal x) _ -> fail "litR" litU :: (Monad m, Monoid dec, Monoid r) => Translate m dec C.Term r litU = translate $ \e -> case e of (C.Literal x) -> return $ mempty _ -> fail "litU" tyLamR :: Monad m => Rewrite m [C.CoreContext] C.Term -> Rewrite m [C.CoreContext] C.Term tyLamR rr = transparently $ rewrite $ \e -> case e of C.TyLambda tv e -> liftM (C.TyLambda tv) (apply (C.TyLambdaBody tv) rr e) _ -> fail "tyLamR" tyLamU :: (Monad m, Monoid r) => Translate m [C.CoreContext] C.Term r -> Translate m [C.CoreContext] C.Term r tyLamU rr = translate $ \e -> case e of C.TyLambda tv e -> apply (C.TyLambdaBody tv) rr e _ -> fail "tyLamU" lamR :: Monad m => Rewrite m [C.CoreContext] C.Term -> Rewrite m [C.CoreContext] C.Term lamR rr = transparently $ rewrite $ \e -> case e of C.Lambda tv e -> liftM (C.Lambda tv) (apply (C.LambdaBody tv) rr e) _ -> fail "lamR" lamU :: (Monad m, Monoid r) => Translate m [C.CoreContext] C.Term r -> Translate m [C.CoreContext] C.Term r lamU rr = translate $ \e -> case e of C.Lambda tv e -> apply (C.LambdaBody tv) rr e _ -> fail "lamU" dataR :: (Monoid dec, Monad m) => Rewrite m dec C.Term dataR = transparently $ rewrite $ \e -> case e of (C.Data d) -> return (C.Data d) _ -> fail "dataR" dataU :: (Monoid dec, Monad m, Monoid r) => Translate m dec C.Term r dataU = translate $ \e -> case e of (C.Data d) -> return $ mempty _ -> fail "dataU" appR :: (Monad m) => Rewrite m [C.CoreContext] C.Term -> Rewrite m [C.CoreContext] C.Term -> Rewrite m [C.CoreContext] C.Term appR rr1 rr2 = transparently $ rewrite $ \e -> case e of (C.App e1 e2) -> liftM2 C.App (apply C.AppFirst rr1 e1) (apply C.AppSecond rr2 e2) _ -> fail "appR" appU :: (Monad m, Monoid r) => Translate m [C.CoreContext] C.Term r -> Translate m [C.CoreContext] C.Term r -> Translate m [C.CoreContext] C.Term r appU rr1 rr2 = translate $ \e -> case e of (C.App e1 e2) -> liftM2 mappend (apply C.AppFirst rr1 e1) (apply C.AppSecond rr2 e2) _ -> fail "appU" tyAppR :: (Monad m) => Rewrite m [C.CoreContext] C.Term -> Rewrite m [C.CoreContext] C.Term tyAppR rr = transparently $ rewrite $ \e -> case e of (C.TyApp e t) -> liftM (`C.TyApp` t) (apply C.TyAppFirst rr e) _ -> fail "appR" tyAppU :: (Monad m, Monoid r) => Translate m [C.CoreContext] C.Term r -> Translate m [C.CoreContext] C.Term r tyAppU rr = translate $ \e -> case e of (C.TyApp e t) -> (apply C.TyAppFirst rr e) _ -> fail "appU" letR :: (Monad m) => Rewrite m [C.CoreContext] C.Term -> Rewrite m [C.CoreContext] C.Term -> Rewrite m [C.CoreContext] C.Term letR rr1 rr2 = transparently $ rewrite $ \e -> case e of (C.LetRec binds e) -> do let bndrs = map fst binds liftM2 C.LetRec (mapM (secondM (apply (C.LetBinding bndrs) rr1)) binds) (apply (C.LetBody bndrs) rr2 e) _ -> fail "letR" letU :: (Monad m, Monoid r) => Translate m [C.CoreContext] C.Term r -> Translate m [C.CoreContext] C.Term r -> Translate m [C.CoreContext] C.Term r letU rr1 rr2 = translate $ \e -> case e of (C.LetRec binds e) -> do let bndrs = map fst binds liftM2 mappend (liftM mconcat (mapM (apply (C.LetBinding bndrs) rr1 . snd) binds)) (apply (C.LetBody bndrs) rr2 e) _ -> fail "letU" caseR :: (Monad m) => Rewrite m [C.CoreContext] C.Term -> Rewrite m [C.CoreContext] C.Term -> Rewrite m [C.CoreContext] C.Term caseR rr1 rr2 = transparently $ rewrite $ \e -> case e of (C.Case scrut t alts) -> liftM2 (\scrut' alts' -> C.Case scrut' t alts') (apply C.Other rr1 scrut) (mapM (secondM (apply C.CaseAlt rr2)) alts) _ -> fail "caseR" caseU :: (Monad m, Monoid r) => Translate m [C.CoreContext] C.Term r -> Translate m [C.CoreContext] C.Term r -> Translate m [C.CoreContext] C.Term r caseU rr1 rr2 = translate $ \e -> case e of (C.Case scrut t alts) -> liftM2 mappend (apply C.Other rr1 scrut) (liftM mconcat (mapM (apply C.CaseAlt rr2 . snd) alts)) _ -> fail "caseU" instance (Monad m) => Walker m [C.CoreContext] C.Term where allR rr = varR <+ litR <+ primR <+ tyLamR (extractR rr) <+ lamR (extractR rr) <+ dataR <+ appR (extractR rr) (extractR rr) <+ tyAppR (extractR rr) <+ letR (extractR rr) (extractR rr) <+ caseR (extractR rr) (extractR rr) crushU rr = varU <+ litU <+ primU <+ tyLamU (extractU rr) <+ lamU (extractU rr) <+ dataU <+ appU (extractU rr) (extractU rr) <+ tyAppU (extractU rr) <+ letU (extractU rr) (extractU rr) <+ caseU (extractU rr) (extractU rr) instance (Monad m) => Walker m [C.CoreContext] CoreGeneric where allR rr = transparently $ rewrite $ \e -> case e of CTerm s -> liftM CTerm $ KURE.apply (allR rr) s crushU rr = translate $ \e -> case e of CTerm s -> KURE.apply (crushU rr) s transformationStep step = rewrite $ \e -> do c <- readEnvM step c e changed :: (Monad m) => String -> C.Term -> C.Term -> RewriteM (C.TransformSession m) [C.CoreContext] C.Term changed tId prevTerm expr = do liftQ $ Label.modify C.tsTransformCounter (+1) --trace ("\n" ++ tId ++ "(before):\n" ++ pprString prevTerm ++ "\n\n" ++ tId ++ "(after):\n" ++ pprString expr) $ markM $ return expr --trace tId $ markM $ return expr markM $ return expr
christiaanb/clash-tryout
src/CLaSH/Util/CoreHW/Traverse.hs
bsd-3-clause
7,814
0
22
2,271
3,266
1,662
1,604
195
2
{-# LANGUAGE NoImplicitPrelude #-} module Protocol.ROC.PointTypes.PointType6 where import Data.Binary.Get (getByteString, getWord8, getWord16le, Get) import Data.ByteString (ByteString) import Data.Word (Word8,Word16) import Prelude (($), return, Eq, Float, Read, Show) import Protocol.ROC.Float (getIeeeFloat32) import Protocol.ROC.Utils (getTLP) data PointType6 = PointType6 { pointType6PntTag :: !PointType6PntTag ,pointType6CtrlType :: !PointType6CtrlType ,pointType6SwitchStatus :: !PointType6SwitchStatus ,pointType6ActualLoopPeriod :: !PointType6ActualLoopPeriod ,pointType6PrimInputPnt :: !PointType6PrimInputPnt ,pointType6PrimOutputPIDOutput :: !PointType6PrimOutputPIDOutput ,pointType6PrimSwitchStpnt :: !PointType6PrimSwitchStpnt ,pointType6PrimSwitchProcVar :: !PointType6PrimSwitchProcVar ,pointType6PrimSwitchMode :: !PointType6PrimSwitchMode ,pointType6OvrdInputPnt :: !PointType6OvrdInputPnt ,pointType6OvrdInputPntPID2ndOutput :: !PointType6OvrdInputPntPID2ndOutput ,pointType6OvrdSwitchStpnt :: !PointType6OvrdSwitchStpnt ,pointType6OvrdSwitchProcVar :: !PointType6OvrdSwitchProcVar ,pointType6OvrdSwitchMode :: !PointType6OvrdSwitchMode ,pointType6PrimStpnt :: !PointType6PrimStpnt ,pointType6PrimStpntMinChangeMax :: !PointType6PrimStpntMinChangeMax ,pointType6PrimLoopPeriod :: !PointType6PrimLoopPeriod ,pointType6PrimPropGain :: !PointType6PrimPropGain ,pointType6PrimResetIntegralGain :: !PointType6PrimResetIntegralGain ,pointType6PrimRateDerivativeGain :: !PointType6PrimRateDerivativeGain ,pointType6PrimScaleFactor :: !PointType6PrimScaleFactor ,pointType6PrimIntegralDeadband :: !PointType6PrimIntegralDeadband ,pointType6PrimProcVar :: !PointType6PrimProcVar ,pointType6PrimOutputCurrentPIDOutput :: !PointType6PrimOutputCurrentPIDOutput ,pointType6PrimSwitchProcVarPrimChangeOutput :: !PointType6PrimSwitchProcVarPrimChangeOutput ,pointType6MinCtrlTime :: !PointType6MinCtrlTime ,pointType6OvrdStpnt :: !PointType6OvrdStpnt ,pointType6OvrdStpntMinChangeMax :: !PointType6OvrdStpntMinChangeMax ,pointType6OvrdLoopPeriod :: !PointType6OvrdLoopPeriod ,pointType6OvrdPropGain :: !PointType6OvrdPropGain ,pointType6OvrdResetIntegralGain :: !PointType6OvrdResetIntegralGain ,pointType6OvrdRateDerivativeGain :: !PointType6OvrdRateDerivativeGain ,pointType6OvrdScaleFactor :: !PointType6OvrdScaleFactor ,pointType6OvrdIntegralDeadband :: !PointType6OvrdIntegralDeadband ,pointType6OvrdProcVar :: !PointType6OvrdProcVar ,pointType6OvrdOutputCurrentPIDOutput :: !PointType6OvrdOutputCurrentPIDOutput ,pointType6OvrdSwitchProcVarOvrdChangeOutput :: !PointType6OvrdSwitchProcVarOvrdChangeOutput } deriving (Read,Eq, Show) type PointType6PntTag = ByteString type PointType6CtrlType = Word8 type PointType6SwitchStatus = Word8 type PointType6ActualLoopPeriod = Word16 type PointType6PrimInputPnt = [Word8] type PointType6PrimOutputPIDOutput = [Word8] type PointType6PrimSwitchStpnt = Float type PointType6PrimSwitchProcVar = [Word8] type PointType6PrimSwitchMode = ByteString type PointType6OvrdInputPnt = [Word8] type PointType6OvrdInputPntPID2ndOutput = [Word8] type PointType6OvrdSwitchStpnt = Float type PointType6OvrdSwitchProcVar = [Word8] type PointType6OvrdSwitchMode = ByteString type PointType6PrimStpnt = Float type PointType6PrimStpntMinChangeMax = Float type PointType6PrimLoopPeriod = Word16 type PointType6PrimPropGain = Float type PointType6PrimResetIntegralGain = Float type PointType6PrimRateDerivativeGain = Float type PointType6PrimScaleFactor = Float type PointType6PrimIntegralDeadband = Float type PointType6PrimProcVar = Float type PointType6PrimOutputCurrentPIDOutput = Float type PointType6PrimSwitchProcVarPrimChangeOutput = Float type PointType6MinCtrlTime = Word16 type PointType6OvrdStpnt = Float type PointType6OvrdStpntMinChangeMax = Float type PointType6OvrdLoopPeriod = Word16 type PointType6OvrdPropGain = Float type PointType6OvrdResetIntegralGain = Float type PointType6OvrdRateDerivativeGain = Float type PointType6OvrdScaleFactor = Float type PointType6OvrdIntegralDeadband = Float type PointType6OvrdProcVar = Float type PointType6OvrdOutputCurrentPIDOutput = Float type PointType6OvrdSwitchProcVarOvrdChangeOutput = Float pointType6Parser :: Get PointType6 pointType6Parser = do pointId <- getByteString 10 ctrlType <- getWord8 switchStatus <- getWord8 actualLoopPeriod <- getWord16le primInputPnt <- getTLP primOutputPIDOutput <- getTLP primSwitchStpnt <- getIeeeFloat32 primSwitchProcVar <- getTLP primSwitchMode <- getByteString 1 ovrdInputPnt <- getTLP ovrdInputPntPID2ndOutput <- getTLP ovrdSwitchStpnt <- getIeeeFloat32 ovrdSwitchProcVar <- getTLP ovrdSwitchMode <- getByteString 1 primStpnt <- getIeeeFloat32 primStpntMinChangeMax <- getIeeeFloat32 primLoopPeriod <- getWord16le primPropGain <- getIeeeFloat32 primResetIntegralGain <- getIeeeFloat32 primRateDerivativeGain <- getIeeeFloat32 primScaleFactor <- getIeeeFloat32 primIntegralDeadband <- getIeeeFloat32 primProcVar <- getIeeeFloat32 primOutputCurrentPIDOutput <- getIeeeFloat32 primSwitchProcVarPrimChangeOutput <- getIeeeFloat32 minCtrlTime <- getWord16le ovrdStpnt <- getIeeeFloat32 ovrdStpntMinChangeMax <- getIeeeFloat32 ovrdLoopPeriod <- getWord16le ovrdPropGain <- getIeeeFloat32 ovrdResetIntegralGain <- getIeeeFloat32 ovrdRateDerivativGain <- getIeeeFloat32 ovrdScaleFactor <- getIeeeFloat32 ovrdIntegralDeadband <- getIeeeFloat32 ovrdProcVar <- getIeeeFloat32 ovrdOutputCurrentPIDOutput <- getIeeeFloat32 ovrdSwitchProcVarOvrdChangeOutput <- getIeeeFloat32 return $ PointType6 pointId ctrlType switchStatus actualLoopPeriod primInputPnt primOutputPIDOutput primSwitchStpnt primSwitchProcVar primSwitchMode ovrdInputPnt ovrdInputPntPID2ndOutput ovrdSwitchStpnt ovrdSwitchProcVar ovrdSwitchMode primStpnt primStpntMinChangeMax primLoopPeriod primPropGain primResetIntegralGain primRateDerivativeGain primScaleFactor primIntegralDeadband primProcVar primOutputCurrentPIDOutput primSwitchProcVarPrimChangeOutput minCtrlTime ovrdStpnt ovrdStpntMinChangeMax ovrdLoopPeriod ovrdPropGain ovrdResetIntegralGain ovrdRateDerivativGain ovrdScaleFactor ovrdIntegralDeadband ovrdProcVar ovrdOutputCurrentPIDOutput ovrdSwitchProcVarOvrdChangeOutput
plow-technologies/roc-translator
src/Protocol/ROC/PointTypes/PointType6.hs
bsd-3-clause
8,098
0
9
2,388
985
547
438
209
1
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable, ScopedTypeVariables #-} module Main (main) where import Data.List (intercalate) import qualified Data.Map as Map import Data.Maybe (fromMaybe) import Data.Monoid ((<>),mempty,mconcat) import qualified Data.ByteString as BS import Data.Char (toUpper,isUpper) import Data.List (intercalate) import Data.String (fromString) import Data.String.Utils (endswith) import qualified System.Console.CmdArgs as CA import System.Directory (doesFileExist, createDirectoryIfMissing) import System.Exit (exitSuccess, exitFailure) import System.FilePath.Posix (replaceExtension, takeFileName, (</>)) import qualified Language.Slice.Syntax.Parser as SlcP import Language.Slice.Syntax.AST as AST data CppGenArgs = CppGenArgs { icefile :: FilePath , targetDir :: FilePath , overwrite :: Bool , cpp98 :: Bool , longguard :: Bool , fwdFctMthds :: Bool } deriving (Show, CA.Data, CA.Typeable) defaultArgs = CppGenArgs { icefile = CA.def CA.&= CA.args CA.&= CA.typ "INPUTFILE" , targetDir = "" , overwrite = False , cpp98 = False , longguard = False , fwdFctMthds = True } camelSplit :: String -> [String] camelSplit s = let (wrd,lst) = foldl (\(wrd,lst) c -> if isUpper c then ([c],if null wrd then lst else reverse wrd:lst) else (c:wrd,lst)) ([],[]) s in reverse (reverse wrd:lst) replaceTail :: String -> String -> String -> String replaceTail what with target = let n = length what m = length target - n (thead, ttail) = splitAt m target in if ttail == what then thead ++ with else target -- namespaces and names are in reverse order (e.g ["InterfaceName", "InnerNamespace", "OuterNamespace"]) findInterfaces :: [String] -> AST.SliceDecl -> Map.Map [String] AST.SliceDecl findInterfaces ns (ModuleDecl (Ident nm) decls) = Map.unions $ map (findInterfaces (nm:ns)) decls findInterfaces ns i@(InterfaceDecl (Ident nm) _ _) = Map.singleton (nm:ns) i findInterfaces _ _ = Map.empty findIfcsWFactory :: AST.SliceDecl -> Map.Map [String] AST.SliceDecl findIfcsWFactory ast = Map.foldlWithKey (\acc k v -> if pred k then Map.insert (reverse k) v acc else acc) Map.empty interfaces where interfaces = findInterfaces [] ast pred k = let k' = (head k ++ "Factory") : tail k in Map.member k' interfaces findFctyMthds :: [SliceDecl] -> Map.Map [String] [MethodDecl] findFctyMthds asts = mapMaybeReverseKey (\k v -> mFctyMthds k) interfaces where interfaces = Map.unions . map (findInterfaces []) $ asts isFcty k = endswith "Factory" (head k) && Map.member (replaceTail "Factory" "" (head k) : tail k) interfaces mFctyMthds k = if isFcty k then Map.lookup k interfaces >>= \(InterfaceDecl _ _ mthds) -> Just mthds else Nothing mapMaybeReverseKey :: ([String] -> a -> Maybe b) -> Map.Map [String] a -> Map.Map [String] b mapMaybeReverseKey f m = go Map.empty (Map.toList m) where go acc [] = acc go acc ((k,v):xs) = case f k v of (Just x) -> go (Map.insert (reverse k) x acc) xs Nothing -> go acc xs sliceCppGen :: Map.Map [String] [MethodDecl] -> CppGenArgs -> SliceDecl -> [(FilePath,BS.ByteString)] sliceCppGen fctyMthds args decl = go [] decl where go ns (ModuleDecl (Ident mName) decls) = concatMap (go (ns++[mName])) decls go ns (InterfaceDecl (Ident nm) ext mthds) = [ (targetDir args </> nm ++ "I.h", genH ns nm mthds) , (targetDir args </> nm ++ "I.cpp", genCpp ns nm mthds)] go ns _ = [] genH :: [String] -> String -> [MethodDecl] -> BS.ByteString genH ns nm mthds = let staticMthds = fromMaybe [] $ Map.lookup (ns ++ [nm++"Factory"]) fctyMthds hnames = [replaceExtension (takeFileName $ icefile args) ".h"] classCont = \indent -> genClass indent nm mthds staticMthds ctnt = genInclds hnames <> genNs "" ns classCont guardItems = if longguard args then ns ++ [nm] else [nm] in genIfDef guardItems ctnt genCpp ns nm mthds = let fwdMthds = fromMaybe [] $ Map.lookup (ns++[nm]) fctyMthds staticMthds = fromMaybe [] $ Map.lookup (ns ++ [nm++"Factory"]) fctyMthds mthdsCont = \indent -> genMethods indent nm (mthds ++ staticMthds) fwdMthds hnames = (targetDir args </> nm ++ "I.h") : if null fwdMthds then [] else [targetDir args </> replaceTail "Factory" "" nm ++ "I.h"] in genInclds hnames <> genNs "" ns mthdsCont genIfDef tkns ctnt = let ident = fromString $ intercalate "_" $ map (map toUpper) (concatMap camelSplit tkns) ++ ["I","H"] in ("#ifndef " <> ident <>"\n#define " <> ident <> "\n\n") <> ctnt <> "\n#endif" genInclds xs = mconcat (map (\x -> "#include <" <> fromString x <> ">\n") xs) <> "\n" genNs :: String -> [String] -> (String -> BS.ByteString) -> BS.ByteString genNs indent (ns:nss) cont = let indent' = fromString indent in indent' <> "namespace " <> fromString ns <> "\n" <> indent' <> "{\n" <> genNs ('\t':indent) nss cont <> indent' <> "};\n" genNs indent [] cont = cont indent genClass :: String -> String -> [MethodDecl] -> [MethodDecl] -> BS.ByteString genClass indent nm mthds staticMthds = let indent' = fromString indent nm' = fromString nm override = if cpp98 args then "" else " override" in indent' <> "class " <> nm' <> "I: public " <> nm' <> "\n" <> indent' <> "{\n" <> indent'<> "public:\n" <> genMethodHeads override ('\t':indent) mthds <> (if null staticMthds then "" else "\n" <> genMethodHeads "" ('\t':indent ++ "static ") staticMthds) <> indent' <> "};\n" genMethods indent nm mthds fwdMthds = let indent' = fromString indent nm' = fromString nm bodyStub = "\n" <> indent' <> "{\n" <> indent' <> "}\n\n" <> indent' in if null fwdMthds then indent' <> (BS.intercalate bodyStub (map (genMethodHead (nm' <> "I::")) mthds) <> "\n" <> indent' <> "{\n" <> indent' <> "}\n") else BS.intercalate "\n" (map (genFwdMethod indent' nm) fwdMthds) genMethodHeads override indent mthds = fromString indent <> BS.intercalate (override <> ";\n" <> fromString indent) (map (genMethodHead "") mthds) <> override <> ";\n" genMethodHead :: BS.ByteString -> MethodDecl -> BS.ByteString genMethodHead scope (MethodDecl tp (Ident nm) flds _ _) = genType tp <> " " <> scope <> fromString nm <> "(" <> genFields flds <> (if null flds then "" else ", ") <> "const Ice::Current& current)" fs = fromString genFwdMethod indent scope mdecl@(MethodDecl tp (Ident nm) flds _ _) = let scope' = fs $ replaceTail "Factory" "" scope vals = map (\(FieldDecl _ (Ident fnm) _) -> fs fnm) flds ++ ["current"] ret = if tp == STVoid then "" else "return " in indent <> genMethodHead (fs scope <> "I::") mdecl <> "\n" <> indent <> "{\n" <> indent <> "\t" <> ret <> scope' <> "I::" <> fs nm <> "(" <> BS.intercalate ", " vals <> ");\n" <> indent <> "}\n" genField (FieldDecl tp (Ident nm) _) = passRefOrVal tp <> " " <> fromString nm genFields flds = BS.intercalate ", " $ map genField flds genType :: SliceType -> BS.ByteString genType STVoid = "void" genType STBool = "bool" genType STByte = "Ice::Byte" genType STShort = "Ice::Short" genType STInt = "Ice::Int" genType STLong = "Ice::Long" genType STFloat = "float" genType STDouble = "double" genType STString = "std::string" genType (STUserDefined (NsQualIdent nm ns)) = fromString (intercalate "::" (ns ++ [nm])) genType (STUserDefinedPrx (NsQualIdent nm ns)) = fromString (intercalate "::" (ns ++ [nm])) <> "Prx" passRefOrVal tp@(STString) = "const " <> genType tp <> "&" passRefOrVal tp@(STUserDefined _) = "const " <> genType tp <> "&" passRefOrVal tp = genType tp main = CA.cmdArgs defaultArgs >>= \args@(CppGenArgs icef trgtD ovrw _ _ _) -> do parseResult <- SlcP.parseFile icef createDirectoryIfMissing True trgtD case parseResult of Left err -> putStrLn (show err) >> exitFailure Right [] -> putStrLn ("Parsing '" ++ icef ++ "' didn't produce any output, probably because the Slice parser is deficient.\nTo improve it, please report your slice file to [email protected]") >> exitFailure Right asts -> do let fctyMthds = if fwdFctMthds args then findFctyMthds asts else Map.empty fileData = concatMap (sliceCppGen fctyMthds args) asts wrtr = \(fn,ctnt) -> do putStrLn $ "generating '" ++ fn ++ "'" (BS.writeFile fn ctnt) chkwrtr = if ovrw then wrtr else \(fn,ctnt) -> do p <- doesFileExist fn if p then putStrLn ('\'' : fn ++ "' aready exists. To overwrite use '--overwrite=True'") else wrtr (fn,ctnt) mapM_ chkwrtr fileData
paulkoerbitz/slice-cpp-gen
src/slice-cpp-gen.hs
bsd-3-clause
11,352
0
27
4,527
3,243
1,682
1,561
149
23
module T450 where import Data.Maybe import Data.Singletons.TH import Data.Singletons.TH.Options import Data.Text (Text) import Language.Haskell.TH (Name) import Prelude.Singletons newtype Message = MkMessage Text newtype PMessage = PMkMessage Symbol newtype Function a b = MkFunction (a -> b) newtype PFunction a b = PMkFunction (a ~> b) $(do let customPromote :: [(Name, Name)] -> Name -> Name customPromote customs n = fromMaybe n $ lookup n customs customOptions :: [(Name, Name)] -> Options customOptions customs = defaultOptions{ promotedDataTypeOrConName = \n -> promotedDataTypeOrConName defaultOptions (customPromote customs n) , defunctionalizedName = \n sat -> defunctionalizedName defaultOptions (customPromote customs n) sat } messageDecs <- withOptions (customOptions [ (''Message, ''PMessage) , ('MkMessage, 'PMkMessage) , (''Text, ''Symbol) ]) $ do messageDecs1 <- genSingletons [''Message] messageDecs2 <- singletons [d| appendMessage :: Message -> Message -> Message appendMessage (MkMessage (x :: Text)) (MkMessage (y :: Text)) = MkMessage (x <> y :: Text) |] pure $ messageDecs1 ++ messageDecs2 functionDecs <- withOptions (customOptions [ (''Function, ''PFunction) , ('MkFunction, 'PMkFunction) ]) $ do functionDecs1 <- genSingletons [''Function] functionDecs2 <- singletons [d| composeFunction :: Function b c -> Function a b -> Function a c composeFunction (MkFunction (f :: b -> c)) (MkFunction (g :: a -> b)) = MkFunction (f . g :: a -> c) |] pure $ functionDecs1 ++ functionDecs2 pure $ messageDecs ++ functionDecs)
goldfirere/singletons
singletons-base/tests/compile-and-dump/Singletons/T450.hs
bsd-3-clause
2,105
0
17
781
425
237
188
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Main where -- Imports import Control.Monad.Trans.Maybe import Data.Typeable import Web.Spock import Web.Spock.Config import qualified Database.MongoDB as DB import qualified Database.MongoDB.Connection as DB import qualified Database.MongoDB.Query as DB import Lucid import qualified Data.Text.Lazy as LT import qualified Data.Text as T import Data.Bson import Network.HTTP.Types.Status import qualified Data.Time.LocalTime as ZT import qualified Data.List.Split as LS -- Model data BlogPost = BlogPost { blogPostDateTime :: T.Text , blogPostName :: T.Text , blogPostBody :: T.Text , blogPostImage :: (T.Text, T.Text) -- (src, alt) , blogPostLinks :: [(T.Text, T.Text)] -- [(href, text)] } deriving (Show, Eq, Typeable) blogPostToDocument :: BlogPost -> Document blogPostToDocument b = [ "blogPostDateTime" := String (blogPostDateTime b) , "blogPostName" := String (blogPostName b) , "blogPostBody" := String (blogPostBody b) , "blogPostImageSrc" := String (fst (blogPostImage b)) , "blogPostImageAlt" := String (snd (blogPostImage b)) ] ++ blogPostLinksToDocument (blogPostLinks b) 0 blogPostLinksToDocument :: [(T.Text, T.Text)] -> Int -> Document blogPostLinksToDocument [] _ = [] blogPostLinksToDocument (l:ls) i = [ T.pack ("blogPostLinkHref" ++ show i) := String (fst l) , T.pack ("blogPostLinkText" ++ show i) := String (snd l) ] ++ blogPostLinksToDocument ls (i+1) documentToBlogPost :: Document -> BlogPost documentToBlogPost document = let bDateTime = "blogPostDateTime" `at` document bName = "blogPostName" `at` document bBody = "blogPostBody" `at` document bImageSrc = "blogPostImageSrc" `at` document bImageAlt = "blogPostImageAlt" `at` document in BlogPost bDateTime bName bBody (bImageSrc, bImageAlt) (documentToBlogPostLinks document 0) documentToBlogPostLinks :: Document -> Int -> [(T.Text, T.Text)] documentToBlogPostLinks document index = let bLinkHref = document !? T.pack ("blogPostLinkHref" ++ show index) bLinkText = document !? T.pack ("blogPostLinkText" ++ show index) in case (bLinkHref, bLinkText) of (Nothing, _) -> [] (_, Nothing) -> [] (Just h, Just t) -> (h, t) : documentToBlogPostLinks document (index+1) sampleBlogPosts :: [BlogPost] sampleBlogPosts = let ba = BlogPost "2017-01-01 00:00:01" "First Blog Post" "How can I insert data into the data structure" ("http://tenggren.net/product.jpg", "Product") [("http://google.com", "Google"), ("http://svt.se", "SVT")] bb = BlogPost "2017-01-02 13:56:34" "Second Blog Post" "Getting warm" ("http://tenggren.net/kajak.jpg", "Kajak") [("http://haskell.org", "Haskell"), ("http://spock.li", "Spock")] in [ba, bb] -- DateTime functions getDateTimeAsString :: IO T.Text getDateTimeAsString = do zonedDateTime <- ZT.getZonedTime let localDateTime = ZT.zonedTimeToLocalTime zonedDateTime localDate = ZT.localDay localDateTime localTime = ZT.localTimeOfDay localDateTime localDateString = show localDate localUnformattedTimeString = show localTime localTimeString = Prelude.head $ LS.splitOn "." localUnformattedTimeString return $ T.pack (localDateString ++ " " ++ localTimeString) updateDateTimeInBlogPost :: T.Text -> BlogPost -> BlogPost updateDateTimeInBlogPost dateTime blogPost = blogPost { blogPostDateTime = dateTime } -- Database Actions fetchAllBlogPosts :: DB.Pipe -> IO [BlogPost] fetchAllBlogPosts pipe = do ps <- DB.access pipe DB.master "blogPosts" run return $ map documentToBlogPost ps where run = getAllBlogPosts getAllBlogPosts :: DB.Action IO [DB.Document] getAllBlogPosts = DB.rest =<< DB.find (DB.select [] "blogPosts") {DB.sort = ["blogPostDateTime" =: (1 :: Int)]} insertBlogPost :: BlogPost -> DB.Pipe -> IO () insertBlogPost blogPost pipe = do bDateTime <- getDateTimeAsString let updatedBlogPost = updateDateTimeInBlogPost bDateTime blogPost DB.access pipe DB.master "blogPosts" (run updatedBlogPost) return () where run updatedBlogPost = DB.insert "blogPosts" (blogPostToDocument updatedBlogPost) -- Spock Actions getBlogPosts :: SpockAction DB.Pipe session state () getBlogPosts = do allBlogPosts <- runQuery fetchAllBlogPosts lucid $ pageTemplate $ do h1_ "Blog" renderBlogPosts allBlogPosts a_ [ href_ "/add-blog-post" ] "Add Your Blog Post!" postBlogPost :: SpockAction DB.Pipe session state () postBlogPost = do maybeBlogPost <- blogPostFromPOST case maybeBlogPost of Nothing -> do lucid (p_ "A blog post was not submitted.") setStatus status400 Just blogPost -> do runQuery (insertBlogPost blogPost) redirect "/" blogPostFromPOST :: SpockAction database session state (Maybe BlogPost) blogPostFromPOST = runMaybeT $ do name <- MaybeT $ param "name" body <- MaybeT $ param "body" imageSrc <- MaybeT $ param "imageSrc" imageAlt <- MaybeT $ param "imageAlt" -- :: MaybeT (ActionCtxT () (WebStateM database session state)) T.Text linkHref0 <- MaybeT $ param "linkHref0" linkText0 <- MaybeT $ param "linkText0" linkHref1 <- MaybeT $ param "linkHref1" linkText1 <- MaybeT $ param "linkText1" linkHref2 <- MaybeT $ param "linkHref2" linkText2 <- MaybeT $ param "linkText2" linkHref3 <- MaybeT $ param "linkHref3" linkText3 <- MaybeT $ param "linkText3" linkHref4 <- MaybeT $ param "linkHref4" linkText4 <- MaybeT $ param "linkText4" return $ BlogPost "" name body (imageSrc, imageAlt) [(linkHref0, linkText0), (linkHref1, linkText1), (linkHref2, linkText2), (linkHref3, linkText3), (linkHref4, linkText4)] addBlogPostForm :: SpockAction database session state () addBlogPostForm = lucid $ pageTemplate $ form_ [ method_ "post", action_ "/blog-posts" ] $ do p_ $ do label_ "Blog Post Name " input_ [ name_ "name" ] p_ $ do label_ "Body " termWith "textarea" [ name_ "body" ] mempty p_ $ do label_ "Image Src " input_ [ name_ "imageSrc" ] p_ $ do label_ "Image Alt " input_ [ name_ "imageAlt" ] p_ $ do label_ "Link Href 0 " input_ [ name_ "linkHref0" ] p_ $ do label_ "Link Text 0 " input_ [ name_ "linkText0" ] p_ $ do label_ "Link Href 1 " input_ [ name_ "linkHref1" ] p_ $ do label_ "Link Text 1 " input_ [ name_ "linkText1" ] p_ $ do label_ "Link Href 2 " input_ [ name_ "linkHref2" ] p_ $ do label_ "Link Text 2 " input_ [ name_ "linkText2" ] p_ $ do label_ "Link Href 3 " input_ [ name_ "linkHref3" ] p_ $ do label_ "Link Text 3 " input_ [ name_ "linkText3" ] p_ $ do label_ "Link Href 4 " input_ [ name_ "linkHref4" ] p_ $ do label_ "Link Text 4 " input_ [ name_ "linkText4" ] input_ [ type_ "submit", value_ "Add Blog Post" ] lucid :: Html () -> SpockAction database session state () lucid document = html (LT.toStrict (renderText document)) -- Spock Initialization and Routing main :: IO () main = do sessionCfg <- defaultSessionCfg () spockCfg <- defaultSpockCfg sessionCfg dbConn initialState runSpock 8080 $ spock spockCfg app app :: SpockM DB.Pipe session state () app = do get "/" getBlogPosts post "/blog-posts" postBlogPost get "/add-blog-post" addBlogPostForm initialState :: () initialState = () dbConn :: PoolOrConn DB.Pipe dbConn = let pConfig = PoolCfg 1 10 20 cBuilder = ConnBuilder { cb_createConn = DB.connect $ DB.host "127.0.0.1" , cb_destroyConn = DB.close , cb_poolConfiguration = pConfig } in PCConn cBuilder -- Lucid View blogPostToRow :: BlogPost -> Html () blogPostToRow blogPost = tr_ $ do td_ (toHtml (blogPostDateTime blogPost)) td_ (toHtml (blogPostName blogPost)) td_ (toHtml (blogPostBody blogPost)) td_ $ img_ [ src_ (fst (blogPostImage blogPost)), alt_ (snd (blogPostImage blogPost)), style_ "width:100px" ] td_ $ foldMap linkToLink $ blogPostLinks blogPost linkToLink :: (T.Text, T.Text) -> Html () linkToLink ("",_) = "" linkToLink (_,"") = "" linkToLink (h,t) = do a_ [ href_ h ] (toHtml t); br_ [] renderBlogPosts :: [BlogPost] -> Html () renderBlogPosts blogPosts = table_ $ thead_ $ do tr_ $ do th_ "Date and Time" th_ "Name" th_ "Body" th_ "Image" th_ "Links" tbody_ (foldMap blogPostToRow blogPosts) pageTemplate :: Html () -> Html () pageTemplate contents = doctypehtml_ (do head_ (do title_ "nerggnet / tenggren" meta_ [charset_ "utf-8"] link_ [ rel_ "stylesheet" , type_ "text/css" , href_ "//tenggren.net/stylesheet.css" ]) body_ contents)
nerggnet/blog
app/Main.hs
bsd-3-clause
9,312
0
15
2,422
2,747
1,364
1,383
216
3
-- | Provides functions and datatypes for interacting with the /market endpoint -- | IG Api. module IG.REST.Markets where import Control.Lens hiding (from, to) import Data.Aeson import Data.Aeson.Types hiding (Options) import Data.List as List import Data.String.Conversions import Data.Text as Text import IG import IG.REST import IG.REST.Markets.Types import Network.Wreq marketUrl :: Bool -> Text marketUrl isDemo = host isDemo </> restPathSegment -- | Get the subnodes of a given node in the market navigation hierarchy navigateMarkets :: AuthHeaders -> Maybe Node -> IO (Either ApiError MarketData) navigateMarkets a@(AuthHeaders _ _ _ isDemo) n = do let opts = v1 a let suffix = case n of Nothing -> mempty Just (Node id _) -> id let url = cs $ marketUrl isDemo </> "marketnavigation" </> suffix apiRequest $ getWith opts url -- | Download the details of a given set of markets. There is in fact a separate -- endpoint that allows the user to download the details of a single market, -- but since that can be achieved here anyway it has not been included. markets :: AuthHeaders -> [Epic] -> IO (Either ApiError [MarketDetails]) markets a@(AuthHeaders _ _ _ isDemo) epics = do let epicsQuery = Text.concat . List.intersperse "," $ epics let opts = v2 a & param "epics" .~ [ epicsQuery] let url = cs $ marketUrl isDemo </> "markets" response <- apiRequest $ getWith opts url :: IO (Either ApiError Value) case response of Left e -> return $ Left e Right r -> let decodeMarkets :: Value -> Parser [MarketDetails] decodeMarkets = withObject "markets" $ \o -> o .: "marketDetails" in case parseEither decodeMarkets r of Left parseError -> return (Left . BadPayload . cs $ parseError) Right details -> return $ Right details market :: AuthHeaders -> Epic -> IO (Either ApiError MarketDetails) market a@(AuthHeaders _ _ _ isDemo) e = do let opts = v2 a let url = cs $ marketUrl isDemo </> "markets" </> e apiRequest $ getWith opts url historicalData :: AuthHeaders -> Epic -> HistoryOpts -> Maybe Int -> IO (Either ApiError HistoricalPrices) historicalData a@(AuthHeaders _ _ _ isDemo) e hOpts page = do let opts = v3 a -? ("from", from hOpts) -? ("to", to hOpts) -? ("max", IG.REST.Markets.Types.max (hOpts :: HistoryOpts)) -? ("pageSize", pageSize (hOpts :: HistoryOpts)) -? ("page", page) let url = cs $ marketUrl isDemo </> "prices" </> e apiRequest $ getWith opts url (-?) :: Show a => Options -> (Text, Maybe a) -> Options (-?) base (k, val) = case val of Nothing -> base Just v -> base & param k .~ [cs $ show v]
wjdhamilton/ig-haskell
src/IG/REST/Markets.hs
bsd-3-clause
2,867
0
19
781
902
460
442
55
3
{-# LANGUAGE OverloadedStrings #-} -------------------------------------------------------------------------------- module OneDrive.Internals.OAuth2 ( Auth , getAuth , newAuth , signIn , offline , readOnly , readWrite , appFolder ) where -------------------------------------------------------------------------------- import qualified Data.ByteString as B import Data.Default -------------------------------------------------------------------------------- data Client = Client { clientId :: B.ByteString , clientSecret :: B.ByteString , redirectURI :: String , clientScope :: Scope } data Token = Token { accessToken :: B.ByteString , tokenType :: String , expiresIn :: Integer , scope :: Scope , refreshToken :: B.ByteString } type AuthCode = B.ByteString type Scope = [B.ByteString] data Auth = Auth { client :: Client , token :: Maybe Token , authCode :: Maybe AuthCode } -------------------------------------------------------------------------------- instance Default Client where def = Client { clientId = error "Define a client id" , clientSecret = error "Define a client secret" , redirectURI = "https://login.live.com/oauth20_desktop.srf" , clientScope = signIn ++ offline ++ appFolder } -------------------------------------------------------------------------------- getAuth :: Auth -> IO Auth getAuth (Auth c (Just t) _) = reToken c t getAuth (Auth c _ (Just a)) = newToken c a getAuth (Auth c _ _) = newToken c $ getAuthCode c newAuth :: Client -> IO Auth newAuth c = getAuth $ Auth c Nothing Nothing reToken :: Client -> Token -> IO Auth reToken = undefined newToken :: Client -> AuthCode -> IO Auth newToken = undefined getAuthCode :: Client -> AuthCode getAuthCode = undefined signIn, offline, readOnly, readWrite, appFolder :: Scope signIn = ["wl.signin"] offline = ["wl.offline_access"] readOnly = ["onedrive.readonly"] readWrite = ["onedrive.readwrite"] appFolder = ["onedrive.appfolder"]
dfaligertwood/onedrive
OneDrive/Internals/OAuth2.hs
bsd-3-clause
2,058
0
9
397
475
276
199
55
1
{-# LANGUAGE OverloadedStrings, FlexibleContexts, NamedFieldPuns , RecordWildCards #-} module Erisbot where import Erisbot.Types import Erisbot.Commands import Erisbot.Plugins import Erisbot.Plugins.URL import Erisbot.Plugins.Sed import Network import Network.IRC.ByteString.Parser import Data.ByteString (ByteString) import qualified Data.HashMap.Strict as HM import qualified Data.ByteString.Char8 as BS import Data.Attoparsec import Data.Monoid ((<>)) import Data.Char (toLower) import Control.Concurrent.Lifted import Control.Monad import Control.Monad.IO.Class import Control.Lens import System.IO --waitForNoIdent :: Handle -> IO () --waitForNoIdent sock = do -- line <- BS.hGetLine sock -- BS.putStrLn line -- if "No Ident response" `BS.isInfixOf` line -- then return () -- else waitForNoIdent sock -- |Waits for 001 numeric before performing the given action waitFor001 :: Bot s () -> Bot s () waitFor001 action = do msg <- recvMsg case msg of IRCMsg {msgCmd = "001"} -> action _ -> waitFor001 action -- |Indefinitely read input from the given 'Handle', parse each line as an IRC message, and send the IRC message to the bot input queue socketReader :: Handle -> Bot s a socketReader sock = do inQ <- use inQueue debugMsg "starting socketReader" forever $ do debugMsg "waiting for socket input..." line <- liftIO (BS.hGetLine sock) debugMsgByteString line case feed (toIRCMsg line) "" of Partial _ -> debugMsg "impossible partial result" Fail _ context errMsg -> debugMsg $ "parse error: " <> show context <> " " <> errMsg Done leftover msg -> do debugMsg $ "Sending message to input queue: " <> show msg --putStrLn . show $ msg --unless (BS.null leftover) . BS.hPutStrLn stderr -- $ "socketReader: warning: leftovers when parsing: " <> leftover writeChan inQ msg -- |Indefinitely read IRC messages from the bot output queue, serialize them, and write them to the given handle socketWriter :: Handle -> Bot s a socketWriter sock = do outQ <- use outQueue debugMsg "starting socketWriter" forever $ do debugMsg "waiting for output" line <- readChan outQ let msgStr = fromIRCMsg line debugMsgByteString msgStr liftIO (BS.hPutStr sock msgStr) debugMsg "output sent" -- |Listens for PING messages and replies with a suitable PONG pingListener :: InputListener s pingListener IRCMsg {msgCmd = "PING", msgParams, msgTrail} = sendMsg "PONG" msgParams msgTrail pingListener _ = return () rejoinListener :: InputListener s rejoinListener IRCMsg {msgCmd = "KICK", msgParams = [channel, nick]} = do BotConf{nick = myNick} <- readMVar =<< use botConf when (BS.map toLower nick == BS.map toLower (BS.pack myNick)) $ do threadDelay 3000000 sendMsg "JOIN" [channel] "" rejoinListener _ = return () -- |proof of concept annoyingNickChanger :: Bot () () annoyingNickChanger = forever $ do threadDelay 2760000000 -- wait 46 minutes changeNick "erisbot" threadDelay 2760000000 -- wait 46 minutes changeNick "strifebot" where changeNick n = do use botConf >>= (`modifyMVar_` (\c -> return c {nick = n})) sendMsg "NICK" [BS.pack n] "" erisbot :: BotConf -> IO () erisbot conf@BotConf {..} = withSocketsDo $ do sock <- connectTo network (PortNumber port) putStrLn $ "Connecting to " ++ network ++ ":" ++ show port ++ "..." hSetBuffering sock LineBuffering botState <- newBotState conf () runBot botState $ do debugMode .= True debugMsg "initializing socket reader" forkBot_ (socketReader sock) debugMsg "initializing socket writer" forkBot_ (socketWriter sock) debugMsg "initializing command dispatcher" forkInputListener_ commandDispatcher forkInputListener_ pingListener forkInputListener_ urlListener forkInputListener_ rejoinListener forkBot_ annoyingNickChanger forkInputListenerWithState_ HM.empty sedListener addCommand defaultCommand { name = "say" , handler = sayCommand } threadDelay 2000000 sendMsg "NICK" [BS.pack nick] "" sendMsg "USER" [BS.pack user, "0", "0"] (BS.pack realname) waitFor001 $ do forM_ plugins (uncurry loadPlugin) forM_ channels $ \c -> sendMsg "JOIN" [BS.pack c] "" debugMsg "main sleeping" sleepForever where sleepForever = threadDelay maxBound >> sleepForever
kallisti-dev/erisbot
src/Erisbot.hs
bsd-3-clause
4,467
0
19
967
1,124
546
578
104
3
{-| Module : Graphics.Sudbury.WireMessages Description : Representation of messages parsed from the wayland wire protocol Copyright : (c) Auke Booij, 2015-2017 License : MIT Maintainer : [email protected] Stability : experimental -} module Graphics.Sudbury.WireMessages where import Data.Fixed import Data.Word import Data.Int import Data.Monoid import qualified Data.Attoparsec.ByteString as A import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Builder as BB import qualified Data.ByteString.Builder.Extra as BBE import Graphics.Sudbury.WirePackages import Graphics.Sudbury.Internal import Graphics.Sudbury.Argument import Graphics.Sudbury.Protocol.XML.Types type family WireArgument (t :: ArgumentType) where WireArgument 'IntWAT = Int32 WireArgument 'UIntWAT = Word32 WireArgument 'FixedWAT = Fixed23_8 WireArgument 'StringWAT = B.ByteString WireArgument 'ObjectWAT = Word32 WireArgument 'NewIdWAT = Word32 WireArgument 'ArrayWAT = B.ByteString WireArgument 'FdWAT = () data WireArgBox = forall t. WireArgBox (SArgumentType t) (WireArgument t) data WireMessage = WireMessage { wireMessageSender :: Word32 , wireMessageOpcode :: Word16 , wireMessageArguments :: [WireArgBox] } parseWireByteString :: A.Parser B.ByteString parseWireByteString = do len' <- anyWord32he let len = fromIntegral len' size = 4 * (1 + ((len - 1) `div` 4)) padding = size - len bs <- A.take len _ <- A.take padding return bs -- | Decode an individual argument parseWireArgument :: SArgumentType t -> A.Parser (WireArgument t) parseWireArgument SIntWAT = anyInt32he parseWireArgument SUIntWAT = anyWord32he parseWireArgument SFixedWAT = do n <- anyInt32he return (MkFixed (fromIntegral n)) parseWireArgument SStringWAT = parseWireByteString parseWireArgument SObjectWAT = anyWord32he parseWireArgument SNewIdWAT = anyWord32he parseWireArgument SArrayWAT= parseWireByteString parseWireArgument SFdWAT = return () boxedParse :: ArgTypeBox -> A.Parser WireArgBox boxedParse (ArgTypeBox tp) = WireArgBox tp <$> parseWireArgument tp decode :: Word32 -> Word16 -> Message it et -> A.Parser WireMessage decode sender opcode msg = do args <- mapM (boxedParse . argDataProj . argumentType) (messageArguments msg) return WireMessage { wireMessageSender = sender , wireMessageOpcode = opcode , wireMessageArguments = args } payloadFromTypes :: Word32 -> Word16 -> [ArgTypeBox] -> A.Parser WireMessage payloadFromTypes sender opcode types = do args <- mapM boxedParse types return WireMessage { wireMessageSender = sender , wireMessageOpcode = opcode , wireMessageArguments = args } -- | Encode some argument values into a ByteString. -- -- This does not produce a full wayland package. See 'Graphics.Sudbury.WirePackages.packBuilder'. encodeArgs :: [WireArgBox] -> BB.Builder encodeArgs = mconcat . map boxedEncodeArgs boxedEncodeArgs :: WireArgBox -> BB.Builder boxedEncodeArgs (WireArgBox tp arg) = encodeArgument tp arg buildWireByteString :: B.ByteString -> BB.Builder buildWireByteString bs = BBE.word32Host (fromIntegral len) <> BB.byteString bs <> mconcat (replicate padding (BB.int8 0)) where len = B.length bs size = 4 * (1 + ((len -1) `div` 4)) padding = size - len -- | Encode an individual argument encodeArgument :: SArgumentType t -> WireArgument t -> BB.Builder encodeArgument SIntWAT i = BBE.int32Host i encodeArgument SUIntWAT i = BBE.word32Host i encodeArgument SFixedWAT (MkFixed n) = BBE.int32Host $ fromIntegral n encodeArgument SStringWAT bytes = buildWireByteString bytes encodeArgument SObjectWAT i = BBE.word32Host i encodeArgument SNewIdWAT i = BBE.word32Host i encodeArgument SArrayWAT bytes = buildWireByteString bytes encodeArgument SFdWAT () = mempty messageToPackage :: WireMessage -> WirePackage messageToPackage msg = WirePackage { wirePackageSender = wireMessageSender msg , wirePackageSize = 8 + fromIntegral (B.length payload) , wirePackageOpcode = wireMessageOpcode msg , wirePackagePayload = payload } where payload :: B.ByteString payload = BL.toStrict $ BB.toLazyByteString $ encodeArgs $ wireMessageArguments msg
abooij/sudbury
Graphics/Sudbury/WireMessages.hs
mit
4,249
0
16
693
1,108
587
521
-1
-1
-- | -- Module : Aura.Colour -- Copyright : (c) Colin Woodbury, 2012 - 2020 -- License : GPL3 -- Maintainer: Colin Woodbury <[email protected]> -- -- Annotate `Doc` text with various colours. module Aura.Colour ( -- * Render to Text dtot -- * Colours , cyan, bCyan, green, yellow, red, magenta ) where import Data.Text.Prettyprint.Doc import Data.Text.Prettyprint.Doc.Render.Terminal import RIO --- -- | Render an assembled `Doc` into strict `Text`. dtot :: Doc AnsiStyle -> Text dtot = renderStrict . layoutPretty defaultLayoutOptions -- | Colour a `Doc` cyan. cyan :: Doc AnsiStyle -> Doc AnsiStyle cyan = annotate (color Cyan) -- | Colour a `Doc` cyan and bold. bCyan :: Doc AnsiStyle -> Doc AnsiStyle bCyan = annotate (color Cyan <> bold) -- | Colour a `Doc` green. green :: Doc AnsiStyle -> Doc AnsiStyle green = annotate (color Green) -- | Colour a `Doc` yellow. yellow :: Doc AnsiStyle -> Doc AnsiStyle yellow = annotate (color Yellow) -- | Colour a `Doc` red. red :: Doc AnsiStyle -> Doc AnsiStyle red = annotate (color Red) -- | Colour a `Doc` magenta. magenta :: Doc AnsiStyle -> Doc AnsiStyle magenta = annotate (color Magenta)
aurapm/aura
aura/lib/Aura/Colour.hs
gpl-3.0
1,168
0
8
222
267
148
119
21
1
module Main where import System.Random import Test.Tasty --import Test.Tasty.QuickCheck as QC --import SugarScape.Discrete --import SugarScape.Model import Agent import Environment import Simulation --import StatsUtils -- clear & stack test --test-arguments="--quickcheck-tests=100 --quickcheck-replay=" seed :: Int seed = 42 main :: IO () main = do -- fix RNG right from the beginning, to be --let g = mkStdGen seed --setStdGen g g <- newStdGen {- let xs = [219.9468438538206 , 202.1627906976744 , 205.74418604651163 , 198.2890365448505 , 205.99003322259136 , 205.57142857142858 , 203.1860465116279 , 202.77408637873754 , 200.62458471760797 , 204.48504983388705 , 208.156146179402 , 196.58139534883722 , 206.09634551495017 , 196.9435215946844 , 206.49169435215947 , 204.1063122923588 , 207.66445182724252 , 216.734219269103 , 214.82059800664453 , 204.7375415282392 , 203.64119601328903 , 201.6013289036545 , 192.10963455149502 , 198.55149501661128 , 202.58471760797343 , 211.54817275747507 , 196.3687707641196 , 205.51162790697674 , 204.19601328903656 , 216.35215946843854 , 203.41860465116278 , 198.3953488372093 , 208.91029900332225 , 211.95016611295682 , 214.42857142857142 , 190.80730897009965 , 200.3156146179402 , 195.27242524916943 , 203.29900332225913 , 201.3654485049834 , 207.34883720930233 , 195.68106312292358 , 213.33554817275748 , 194.78737541528238 , 200.1029900332226 , 213.14617940199335 , 219.531561461794 , 201.265780730897 , 213.32558139534885] print $ tTest "carrying caps" xs 200 0.05 --print $ tTest "test1" [1..10] 5.5 0.05 --print $ tTest "test2" [1..10] 0.0 0.05 -} {- putStrLn "" x <- generate arbitrary :: IO (Discrete2d SugEnvCell) print x -} let sugarScapeTests = testGroup "SugarScape Tests" [ agentTests g, envTests g --, agentTests g --simTests g ] defaultMain sugarScapeTests
thalerjonathan/phd
public/towards/SugarScape/experimental/chapter2_environment/src/test/Test.hs
gpl-3.0
2,632
0
12
1,040
99
58
41
16
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.EC2.DisableVGWRoutePropagation -- 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) -- -- Disables a virtual private gateway (VGW) from propagating routes to a -- specified route table of a VPC. -- -- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DisableVGWRoutePropagation.html AWS API Reference> for DisableVGWRoutePropagation. module Network.AWS.EC2.DisableVGWRoutePropagation ( -- * Creating a Request disableVGWRoutePropagation , DisableVGWRoutePropagation -- * Request Lenses , dvrpRouteTableId , dvrpGatewayId -- * Destructuring the Response , disableVGWRoutePropagationResponse , DisableVGWRoutePropagationResponse ) where import Network.AWS.EC2.Types import Network.AWS.EC2.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'disableVGWRoutePropagation' smart constructor. data DisableVGWRoutePropagation = DisableVGWRoutePropagation' { _dvrpRouteTableId :: !Text , _dvrpGatewayId :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DisableVGWRoutePropagation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dvrpRouteTableId' -- -- * 'dvrpGatewayId' disableVGWRoutePropagation :: Text -- ^ 'dvrpRouteTableId' -> Text -- ^ 'dvrpGatewayId' -> DisableVGWRoutePropagation disableVGWRoutePropagation pRouteTableId_ pGatewayId_ = DisableVGWRoutePropagation' { _dvrpRouteTableId = pRouteTableId_ , _dvrpGatewayId = pGatewayId_ } -- | The ID of the route table. dvrpRouteTableId :: Lens' DisableVGWRoutePropagation Text dvrpRouteTableId = lens _dvrpRouteTableId (\ s a -> s{_dvrpRouteTableId = a}); -- | The ID of the virtual private gateway. dvrpGatewayId :: Lens' DisableVGWRoutePropagation Text dvrpGatewayId = lens _dvrpGatewayId (\ s a -> s{_dvrpGatewayId = a}); instance AWSRequest DisableVGWRoutePropagation where type Rs DisableVGWRoutePropagation = DisableVGWRoutePropagationResponse request = postQuery eC2 response = receiveNull DisableVGWRoutePropagationResponse' instance ToHeaders DisableVGWRoutePropagation where toHeaders = const mempty instance ToPath DisableVGWRoutePropagation where toPath = const "/" instance ToQuery DisableVGWRoutePropagation where toQuery DisableVGWRoutePropagation'{..} = mconcat ["Action" =: ("DisableVgwRoutePropagation" :: ByteString), "Version" =: ("2015-04-15" :: ByteString), "RouteTableId" =: _dvrpRouteTableId, "GatewayId" =: _dvrpGatewayId] -- | /See:/ 'disableVGWRoutePropagationResponse' smart constructor. data DisableVGWRoutePropagationResponse = DisableVGWRoutePropagationResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DisableVGWRoutePropagationResponse' with the minimum fields required to make a request. -- disableVGWRoutePropagationResponse :: DisableVGWRoutePropagationResponse disableVGWRoutePropagationResponse = DisableVGWRoutePropagationResponse'
fmapfmapfmap/amazonka
amazonka-ec2/gen/Network/AWS/EC2/DisableVGWRoutePropagation.hs
mpl-2.0
3,869
0
9
729
439
266
173
65
1
module Example where import Prelude hiding (tail) import Language.Cil main = putStr (pr ass "") ass :: Assembly ass = Assembly [mscorlibRef] "Example" [hello] hello :: TypeDef hello = classDef [CaPublic] "Haskell.Ehc.Hello" noExtends noImplements [] [myMain] [] deadbeef = 3735928559 int16 = ValueType "mscorlib" "System.Int16" myMain :: MethodDef myMain = Method [MaStatic, MaPublic] Void "main" [] [ entryPoint , localsInit [Local Int32 "x"] , ldc_i4 deadbeef , stloc 0 , ldstr "First {0:X} then {1:X} then {2:X}" , ldloca 0 , ldind_i2 , box int16 , ldloca 0 , ldc_i4 1 , add , unalignedPtr ByteAligned $ ldind_i2 , box int16 , ldloca 0 , ldc_i4 2 , add , unalignedPtr DoubleByteAligned $ volatilePtr -- Marked as volatile, for no particular reason $ ldind_i2 , box int16 , call [] Void "mscorlib" "System.Console" "WriteLine" [String, Object, Object, Object] , ret ]
tomlokhorst/language-cil
examples/08_Indirect.hs
bsd-3-clause
950
0
9
221
286
156
130
36
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE OverloadedStrings, FlexibleInstances, GeneralizedNewtypeDeriving, CPP #-} -- | Haste AST pretty printing machinery. The actual printing happens in -- Haste.AST.Print. module Haste.AST.PP where import Data.Monoid import Data.String import Data.List (foldl') import Data.Array import Control.Monad import Control.Applicative import qualified Data.Map as M import qualified Data.ByteString.Lazy as BS import qualified Data.ByteString.Char8 as BSS import Data.ByteString (ByteString) import Haste.AST.Syntax (Name (..)) import Data.ByteString.Builder import Haste.Config import Haste.AST.PP.Opts type IndentLvl = Int -- | Final name for symbols. This name is what actually appears in the final -- JS dump, albeit "base 62"-encoded. newtype FinalName = FinalName Int deriving (Ord, Eq, Enum, Show) type NameSupply = (FinalName, M.Map Name FinalName) emptyNS :: NameSupply emptyNS = (FinalName 0, M.empty) newtype PP a = PP {unPP :: Config -> IndentLvl -> NameSupply -> Builder -> (NameSupply, Builder, a)} instance Monad PP where PP m >>= f = PP $ \cfg indentlvl ns b -> case m cfg indentlvl ns b of (ns', b', x) -> unPP (f x) cfg indentlvl ns' b' return x = PP $ \_ _ ns b -> (ns, b, x) instance Applicative PP where pure = return (<*>) = ap instance Functor PP where fmap f p = p >>= return . f -- | Convenience operator for using the PP () IsString instance. (.+.) :: PP () -> PP () -> PP () (.+.) = (>>) infixl 1 .+. -- | Generate the final name for a variable. -- Up until this point, internal names may be just about anything. -- The "final name" scheme ensures that all internal names end up with a -- proper, unique JS name. finalNameFor :: Name -> PP FinalName finalNameFor n = PP $ \_ _ ns@(nextN, m) b -> case M.lookup n m of Just n' -> (ns, b, n') _ -> ((succ nextN, M.insert n nextN m), b, nextN) -- | Returns the value of the given pretty-printer option. getOpt :: (PPOpts -> a) -> PP a getOpt f = getCfg (f . ppOpts) -- | Runs the given printer iff the specified PP option is True. whenOpt :: (PPOpts -> Bool) -> PP () -> PP () whenOpt f p = getOpt f >>= \x -> when x p -- | Returns the value of the given pretty-printer option. getCfg :: (Config -> a) -> PP a getCfg f = PP $ \cfg _ ns b -> (ns, b, f cfg) -- | Pretty print an AST. pretty :: Pretty a => Config -> a -> BS.ByteString pretty cfg ast = case runPP cfg (pp ast) of (b, _) -> toLazyByteString b -- | Run a pretty printer. runPP :: Config -> PP a -> (Builder, a) runPP cfg p = case unPP p cfg 0 emptyNS mempty of (_, b, x) -> (b, x) -- | Pretty-print a program and return the final name for its entry point. prettyProg :: Pretty a => Config -> Name -> a -> (Builder, Builder) prettyProg cfg mainSym ast = runPP cfg $ do pp ast hsnames <- getOpt preserveNames if hsnames then return $ buildStgName mainSym else buildFinalName <$> finalNameFor mainSym -- | JS-mangled version of an internal name. buildStgName :: Name -> Builder buildStgName (Name n mq) = byteString "$hs$" <> qual <> byteString (BSS.map mkjs n) where qual = case mq of Just (_, m) -> byteString (BSS.map mkjs m) <> byteString "$" _ -> mempty mkjs c | c >= 'a' && c <= 'z' = c | c >= 'A' && c <= 'Z' = c | c >= '0' && c <= '9' = c | c == '$' = c | otherwise = '_' -- | Turn a FinalName into a Builder. buildFinalName :: FinalName -> Builder buildFinalName (FinalName 0) = fromString "_0" buildFinalName (FinalName fn) = charUtf8 '_' <> go fn mempty where arrLen = 62 chars = listArray (0,arrLen-1) $ "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" go 0 acc = acc go n acc = let (rest, ix) = n `quotRem` arrLen in go rest (charUtf8 (chars ! ix) <> acc) -- | Indent the given builder another step. indent :: PP a -> PP a indent (PP p) = PP $ \cfg indentlvl ns b -> if useIndentation (ppOpts cfg) then p cfg (indentlvl+1) ns b else p cfg 0 ns b class Buildable a where put :: a -> PP () instance Buildable Builder where put x = PP $ \_ _ ns b -> (ns, b <> x, ()) instance Buildable ByteString where put = put . byteString instance Buildable String where put = put . stringUtf8 instance Buildable Char where put = put . charUtf8 instance Buildable Int where put = put . intDec instance Buildable Double where put d = case round d of n | fromIntegral n == d -> put $ intDec n | otherwise -> put $ doubleDec d instance Buildable Integer where put = put . integerDec instance Buildable Bool where put True = "true" put False = "false" -- | Emit indentation up to the current level. ind :: PP () ind = PP $ \cfg indentlvl ns b -> (ns, foldl' (<>) b (replicate indentlvl (indentStr $ ppOpts cfg)), ()) -- | A space character. sp :: PP () sp = whenOpt useSpaces $ put ' ' -- | A newline character. newl :: PP () newl = whenOpt useNewlines $ put '\n' -- | Indent the given builder and terminate it with a newline. line :: PP () -> PP () line p = do ind >> p whenOpt useNewlines $ put '\n' -- | Pretty print a list with the given separator. ppList :: Pretty a => PP () -> [a] -> PP () ppList sep (x:xs) = foldl' (\l r -> l >> sep >> pp r) (pp x) xs ppList _ _ = return () instance IsString (PP ()) where fromString = put . stringUtf8 -- | Pretty-printer class. Each part of the AST needs an instance of this. class Pretty a where pp :: a -> PP ()
nyson/haste-compiler
src/Haste/AST/PP.hs
bsd-3-clause
5,691
0
14
1,461
1,906
1,006
900
137
2
-- -- Copyright (c) 2014 Joachim Breitner -- module CallArity ( callArityAnalProgram , callArityRHS -- for testing ) where import VarSet import VarEnv import DynFlags ( DynFlags ) import BasicTypes import CoreSyn import Id import CoreArity ( typeArity ) import CoreUtils ( exprIsHNF, exprIsTrivial ) --import Outputable import UnVarGraph import Demand import Control.Arrow ( first, second ) {- %************************************************************************ %* * Call Arity Analyis %* * %************************************************************************ Note [Call Arity: The goal] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The goal of this analysis is to find out if we can eta-expand a local function, based on how it is being called. The motivating example is this code, which comes up when we implement foldl using foldr, and do list fusion: let go = \x -> let d = case ... of False -> go (x+1) True -> id in \z -> d (x + z) in go 1 0 If we do not eta-expand `go` to have arity 2, we are going to allocate a lot of partial function applications, which would be bad. The function `go` has a type of arity two, but only one lambda is manifest. Furthermore, an analysis that only looks at the RHS of go cannot be sufficient to eta-expand go: If `go` is ever called with one argument (and the result used multiple times), we would be doing the work in `...` multiple times. So `callArityAnalProgram` looks at the whole let expression to figure out if all calls are nice, i.e. have a high enough arity. It then stores the result in the `calledArity` field of the `IdInfo` of `go`, which the next simplifier phase will eta-expand. The specification of the `calledArity` field is: No work will be lost if you eta-expand me to the arity in `calledArity`. What we want to know for a variable ----------------------------------- For every let-bound variable we'd like to know: 1. A lower bound on the arity of all calls to the variable, and 2. whether the variable is being called at most once or possible multiple times. It is always ok to lower the arity, or pretend that there are multiple calls. In particular, "Minimum arity 0 and possible called multiple times" is always correct. What we want to know from an expression --------------------------------------- In order to obtain that information for variables, we analyize expression and obtain bits of information: I. The arity analysis: For every variable, whether it is absent, or called, and if called, which what arity. II. The Co-Called analysis: For every two variables, whether there is a possibility that both are being called. We obtain as a special case: For every variables, whether there is a possibility that it is being called twice. For efficiency reasons, we gather this information only for a set of *interesting variables*, to avoid spending time on, e.g., variables from pattern matches. The two analysis are not completely independent, as a higher arity can improve the information about what variables are being called once or multiple times. Note [Analysis I: The arity analyis] ------------------------------------ The arity analysis is quite straight forward: The information about an expression is an VarEnv Arity where absent variables are bound to Nothing and otherwise to a lower bound to their arity. When we analyize an expression, we analyize it with a given context arity. Lambdas decrease and applications increase the incoming arity. Analysizing a variable will put that arity in the environment. In lets or cases all the results from the various subexpressions are lubed, which takes the point-wise minimum (considering Nothing an infinity). Note [Analysis II: The Co-Called analysis] ------------------------------------------ The second part is more sophisticated. For reasons explained below, it is not sufficient to simply know how often an expression evalutes a variable. Instead we need to know which variables are possibly called together. The data structure here is an undirected graph of variables, which is provided by the abstract UnVarGraph It is safe to return a larger graph, i.e. one with more edges. The worst case (i.e. the least useful and always correct result) is the complete graph on all free variables, which means that anything can be called together with anything (including itself). Notation for the following: C(e) is the co-called result for e. G₁∪G₂ is the union of two graphs fv is the set of free variables (conveniently the domain of the arity analysis result) S₁×S₂ is the complete bipartite graph { {a,b} | a ∈ S₁, b ∈ S₂ } S² is the complete graph on the set of variables S, S² = S×S C'(e) is a variant for bound expression: If e is called at most once, or it is and stays a thunk (after the analysis), it is simply C(e). Otherwise, the expression can be called multiple times and we return (fv e)² The interesting cases of the analysis: * Var v: No other variables are being called. Return {} (the empty graph) * Lambda v e, under arity 0: This means that e can be evaluated many times and we cannot get any useful co-call information. Return (fv e)² * Case alternatives alt₁,alt₂,...: Only one can be execuded, so Return (alt₁ ∪ alt₂ ∪...) * App e₁ e₂ (and analogously Case scrut alts), with non-trivial e₂: We get the results from both sides, with the argument evaluted at most once. Additionally, anything called by e₁ can possibly be called with anything from e₂. Return: C(e₁) ∪ C(e₂) ∪ (fv e₁) × (fv e₂) * App e₁ x: As this is already in A-normal form, CorePrep will not separately lambda bind (and hence share) x. So we conservatively assume multiple calls to x here Return: C(e₁) ∪ (fv e₁) × {x} ∪ {(x,x)} * Let v = rhs in body: In addition to the results from the subexpressions, add all co-calls from everything that the body calls together with v to everthing that is called by v. Return: C'(rhs) ∪ C(body) ∪ (fv rhs) × {v'| {v,v'} ∈ C(body)} * Letrec v₁ = rhs₁ ... vₙ = rhsₙ in body Tricky. We assume that it is really mutually recursive, i.e. that every variable calls one of the others, and that this is strongly connected (otherwise we return an over-approximation, so that's ok), see note [Recursion and fixpointing]. Let V = {v₁,...vₙ}. Assume that the vs have been analysed with an incoming demand and cardinality consistent with the final result (this is the fixed-pointing). Again we can use the results from all subexpressions. In addition, for every variable vᵢ, we need to find out what it is called with (call this set Sᵢ). There are two cases: * If vᵢ is a function, we need to go through all right-hand-sides and bodies, and collect every variable that is called together with any variable from V: Sᵢ = {v' | j ∈ {1,...,n}, {v',vⱼ} ∈ C'(rhs₁) ∪ ... ∪ C'(rhsₙ) ∪ C(body) } * If vᵢ is a thunk, then its rhs is evaluated only once, so we need to exclude it from this set: Sᵢ = {v' | j ∈ {1,...,n}, j≠i, {v',vⱼ} ∈ C'(rhs₁) ∪ ... ∪ C'(rhsₙ) ∪ C(body) } Finally, combine all this: Return: C(body) ∪ C'(rhs₁) ∪ ... ∪ C'(rhsₙ) ∪ (fv rhs₁) × S₁) ∪ ... ∪ (fv rhsₙ) × Sₙ) Using the result: Eta-Expansion ------------------------------- We use the result of these two analyses to decide whether we can eta-expand the rhs of a let-bound variable. If the variable is already a function (exprIsHNF), and all calls to the variables have a higher arity than the current manifest arity (i.e. the number of lambdas), expand. If the variable is a thunk we must be careful: Eta-Expansion will prevent sharing of work, so this is only safe if there is at most one call to the function. Therefore, we check whether {v,v} ∈ G. Example: let n = case .. of .. -- A thunk! in n 0 + n 1 vs. let n = case .. of .. in case .. of T -> n 0 F -> n 1 We are only allowed to eta-expand `n` if it is going to be called at most once in the body of the outer let. So we need to know, for each variable individually, that it is going to be called at most once. Why the co-call graph? ---------------------- Why is it not sufficient to simply remember which variables are called once and which are called multiple times? It would be in the previous example, but consider let n = case .. of .. in case .. of True -> let go = \y -> case .. of True -> go (y + n 1) False > n in go 1 False -> n vs. let n = case .. of .. in case .. of True -> let go = \y -> case .. of True -> go (y+1) False > n in go 1 False -> n In both cases, the body and the rhs of the inner let call n at most once. But only in the second case that holds for the whole expression! The crucial difference is that in the first case, the rhs of `go` can call *both* `go` and `n`, and hence can call `n` multiple times as it recurses, while in the second case find out that `go` and `n` are not called together. Why co-call information for functions? -------------------------------------- Although for eta-expansion we need the information only for thunks, we still need to know whether functions are being called once or multiple times, and together with what other functions. Example: let n = case .. of .. f x = n (x+1) in f 1 + f 2 vs. let n = case .. of .. f x = n (x+1) in case .. of T -> f 0 F -> f 1 Here, the body of f calls n exactly once, but f itself is being called multiple times, so eta-expansion is not allowed. Note [Analysis type signature] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The work-hourse of the analysis is the function `callArityAnal`, with the following type: type CallArityRes = (UnVarGraph, VarEnv Arity) callArityAnal :: Arity -> -- The arity this expression is called with VarSet -> -- The set of interesting variables CoreExpr -> -- The expression to analyse (CallArityRes, CoreExpr) and the following specification: ((coCalls, callArityEnv), expr') = callArityEnv arity interestingIds expr <=> Assume the expression `expr` is being passed `arity` arguments. Then it holds that * The domain of `callArityEnv` is a subset of `interestingIds`. * Any variable from `interestingIds` that is not mentioned in the `callArityEnv` is absent, i.e. not called at all. * Every call from `expr` to a variable bound to n in `callArityEnv` has at least n value arguments. * For two interesting variables `v1` and `v2`, they are not adjacent in `coCalls`, then in no execution of `expr` both are being called. Furthermore, expr' is expr with the callArity field of the `IdInfo` updated. Note [Which variables are interesting] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The analysis would quickly become prohibitive expensive if we would analyse all variables; for most variables we simply do not care about how often they are called, i.e. variables bound in a pattern match. So interesting are variables that are * top-level or let bound * and possibly functions (typeArity > 0) Note [Taking boring variables into account] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we decide that the variable bound in `let x = e1 in e2` is not interesting, the analysis of `e2` will not report anything about `x`. To ensure that `callArityBind` does still do the right thing we have to take that into account everytime we would be lookup up `x` in the analysis result of `e2`. * Instead of calling lookupCallArityRes, we return (0, True), indicating that this variable might be called many times with no variables. * Instead of checking `calledWith x`, we assume that everything can be called with it. * In the recursive case, when calclulating the `cross_calls`, if there is any boring variable in the recursive group, we ignore all co-call-results and directly go to a very conservative assumption. The last point has the nice side effect that the relatively expensive integration of co-call results in a recursive groups is often skipped. This helped to avoid the compile time blowup in some real-world code with large recursive groups (#10293). Note [Recursion and fixpointing] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For a mutually recursive let, we begin by 1. analysing the body, using the same incoming arity as for the whole expression. 2. Then we iterate, memoizing for each of the bound variables the last analysis call, i.e. incoming arity, whether it is called once, and the CallArityRes. 3. We combine the analysis result from the body and the memoized results for the arguments (if already present). 4. For each variable, we find out the incoming arity and whether it is called once, based on the the current analysis result. If this differs from the memoized results, we re-analyse the rhs and update the memoized table. 5. If nothing had to be reanalized, we are done. Otherwise, repeat from step 3. Note [Thunks in recursive groups] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We never eta-expand a thunk in a recursive group, on the grounds that if it is part of a recursive group, then it will be called multipe times. This is not necessarily true, e.g. it would be safe to eta-expand t2 (but not t1) in the following code: let go x = t1 t1 = if ... then t2 else ... t2 = if ... then go 1 else ... in go 0 Detecting this would require finding out what variables are only ever called from thunks. While this is certainly possible, we yet have to see this to be relevant in the wild. Note [Analysing top-level binds] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We can eta-expand top-level-binds if they are not exported, as we see all calls to them. The plan is as follows: Treat the top-level binds as nested lets around a body representing “all external calls”, which returns a pessimistic CallArityRes (the co-call graph is the complete graph, all arityies 0). Note [Trimming arity] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the Call Arity papers, we are working on an untyped lambda calculus with no other id annotations, where eta-expansion is always possible. But this is not the case for Core! 1. We need to ensure the invariant callArity e <= typeArity (exprType e) for the same reasons that exprArity needs this invariant (see Note [exprArity invariant] in CoreArity). If we are not doing that, a too-high arity annotation will be stored with the id, confusing the simplifier later on. 2. Eta-expanding a right hand side might invalidate existing annotations. In particular, if an id has a strictness annotation of <...><...>b, then passing two arguments to it will definitely bottom out, so the simplifier will throw away additional parameters. This conflicts with Call Arity! So we ensure that we never eta-expand such a value beyond the number of arguments mentioned in the strictness signature. See #10176 for a real-world-example. -} -- Main entry point callArityAnalProgram :: DynFlags -> CoreProgram -> CoreProgram callArityAnalProgram _dflags binds = binds' where (_, binds') = callArityTopLvl [] emptyVarSet binds -- See Note [Analysing top-level-binds] callArityTopLvl :: [Var] -> VarSet -> [CoreBind] -> (CallArityRes, [CoreBind]) callArityTopLvl exported _ [] = ( calledMultipleTimes $ (emptyUnVarGraph, mkVarEnv $ [(v, 0) | v <- exported]) , [] ) callArityTopLvl exported int1 (b:bs) = (ae2, b':bs') where int2 = bindersOf b exported' = filter isExportedId int2 ++ exported int' = int1 `addInterestingBinds` b (ae1, bs') = callArityTopLvl exported' int' bs (ae2, b') = callArityBind (boringBinds b) ae1 int1 b callArityRHS :: CoreExpr -> CoreExpr callArityRHS = snd . callArityAnal 0 emptyVarSet -- The main analysis function. See Note [Analysis type signature] callArityAnal :: Arity -> -- The arity this expression is called with VarSet -> -- The set of interesting variables CoreExpr -> -- The expression to analyse (CallArityRes, CoreExpr) -- How this expression uses its interesting variables -- and the expression with IdInfo updated -- The trivial base cases callArityAnal _ _ e@(Lit _) = (emptyArityRes, e) callArityAnal _ _ e@(Type _) = (emptyArityRes, e) callArityAnal _ _ e@(Coercion _) = (emptyArityRes, e) -- The transparent cases callArityAnal arity int (Tick t e) = second (Tick t) $ callArityAnal arity int e callArityAnal arity int (Cast e co) = second (\e -> Cast e co) $ callArityAnal arity int e -- The interesting case: Variables, Lambdas, Lets, Applications, Cases callArityAnal arity int e@(Var v) | v `elemVarSet` int = (unitArityRes v arity, e) | otherwise = (emptyArityRes, e) -- Non-value lambdas are ignored callArityAnal arity int (Lam v e) | not (isId v) = second (Lam v) $ callArityAnal arity (int `delVarSet` v) e -- We have a lambda that may be called multiple times, so its free variables -- can all be co-called. callArityAnal 0 int (Lam v e) = (ae', Lam v e') where (ae, e') = callArityAnal 0 (int `delVarSet` v) e ae' = calledMultipleTimes ae -- We have a lambda that we are calling. decrease arity. callArityAnal arity int (Lam v e) = (ae, Lam v e') where (ae, e') = callArityAnal (arity - 1) (int `delVarSet` v) e -- Application. Increase arity for the called expresion, nothing to know about -- the second callArityAnal arity int (App e (Type t)) = second (\e -> App e (Type t)) $ callArityAnal arity int e callArityAnal arity int (App e1 e2) = (final_ae, App e1' e2') where (ae1, e1') = callArityAnal (arity + 1) int e1 (ae2, e2') = callArityAnal 0 int e2 -- If the argument is trivial (e.g. a variable), then it will _not_ be -- let-bound in the Core to STG transformation (CorePrep actually), -- so no sharing will happen here, and we have to assume many calls. ae2' | exprIsTrivial e2 = calledMultipleTimes ae2 | otherwise = ae2 final_ae = ae1 `both` ae2' -- Case expression. callArityAnal arity int (Case scrut bndr ty alts) = -- pprTrace "callArityAnal:Case" -- (vcat [ppr scrut, ppr final_ae]) (final_ae, Case scrut' bndr ty alts') where (alt_aes, alts') = unzip $ map go alts go (dc, bndrs, e) = let (ae, e') = callArityAnal arity int e in (ae, (dc, bndrs, e')) alt_ae = lubRess alt_aes (scrut_ae, scrut') = callArityAnal 0 int scrut final_ae = scrut_ae `both` alt_ae -- For lets, use callArityBind callArityAnal arity int (Let bind e) = -- pprTrace "callArityAnal:Let" -- (vcat [ppr v, ppr arity, ppr n, ppr final_ae ]) (final_ae, Let bind' e') where int_body = int `addInterestingBinds` bind (ae_body, e') = callArityAnal arity int_body e (final_ae, bind') = callArityBind (boringBinds bind) ae_body int bind -- Which bindings should we look at? -- See Note [Which variables are interesting] isInteresting :: Var -> Bool isInteresting v = 0 < length (typeArity (idType v)) interestingBinds :: CoreBind -> [Var] interestingBinds = filter isInteresting . bindersOf boringBinds :: CoreBind -> VarSet boringBinds = mkVarSet . filter (not . isInteresting) . bindersOf addInterestingBinds :: VarSet -> CoreBind -> VarSet addInterestingBinds int bind = int `delVarSetList` bindersOf bind -- Possible shadowing `extendVarSetList` interestingBinds bind -- Used for both local and top-level binds -- Second argument is the demand from the body callArityBind :: VarSet -> CallArityRes -> VarSet -> CoreBind -> (CallArityRes, CoreBind) -- Non-recursive let callArityBind boring_vars ae_body int (NonRec v rhs) | otherwise = -- pprTrace "callArityBind:NonRec" -- (vcat [ppr v, ppr ae_body, ppr int, ppr ae_rhs, ppr safe_arity]) (final_ae, NonRec v' rhs') where is_thunk = not (exprIsHNF rhs) -- If v is boring, we will not find it in ae_body, but always assume (0, False) boring = v `elemVarSet` boring_vars (arity, called_once) | boring = (0, False) -- See Note [Taking boring variables into account] | otherwise = lookupCallArityRes ae_body v safe_arity | called_once = arity | is_thunk = 0 -- A thunk! Do not eta-expand | otherwise = arity -- See Note [Trimming arity] trimmed_arity = trimArity v safe_arity (ae_rhs, rhs') = callArityAnal trimmed_arity int rhs ae_rhs'| called_once = ae_rhs | safe_arity == 0 = ae_rhs -- If it is not a function, its body is evaluated only once | otherwise = calledMultipleTimes ae_rhs called_by_v = domRes ae_rhs' called_with_v | boring = domRes ae_body | otherwise = calledWith ae_body v `delUnVarSet` v final_ae = addCrossCoCalls called_by_v called_with_v $ ae_rhs' `lubRes` resDel v ae_body v' = v `setIdCallArity` trimmed_arity -- Recursive let. See Note [Recursion and fixpointing] callArityBind boring_vars ae_body int b@(Rec binds) = -- (if length binds > 300 then -- pprTrace "callArityBind:Rec" -- (vcat [ppr (Rec binds'), ppr ae_body, ppr int, ppr ae_rhs]) else id) $ (final_ae, Rec binds') where -- See Note [Taking boring variables into account] any_boring = any (`elemVarSet` boring_vars) [ i | (i, _) <- binds] int_body = int `addInterestingBinds` b (ae_rhs, binds') = fix initial_binds final_ae = bindersOf b `resDelList` ae_rhs initial_binds = [(i,Nothing,e) | (i,e) <- binds] fix :: [(Id, Maybe (Bool, Arity, CallArityRes), CoreExpr)] -> (CallArityRes, [(Id, CoreExpr)]) fix ann_binds | -- pprTrace "callArityBind:fix" (vcat [ppr ann_binds, ppr any_change, ppr ae]) $ any_change = fix ann_binds' | otherwise = (ae, map (\(i, _, e) -> (i, e)) ann_binds') where aes_old = [ (i,ae) | (i, Just (_,_,ae), _) <- ann_binds ] ae = callArityRecEnv any_boring aes_old ae_body rerun (i, mbLastRun, rhs) | i `elemVarSet` int_body && not (i `elemUnVarSet` domRes ae) -- No call to this yet, so do nothing = (False, (i, Nothing, rhs)) | Just (old_called_once, old_arity, _) <- mbLastRun , called_once == old_called_once , new_arity == old_arity -- No change, no need to re-analize = (False, (i, mbLastRun, rhs)) | otherwise -- We previously analized this with a different arity (or not at all) = let is_thunk = not (exprIsHNF rhs) safe_arity | is_thunk = 0 -- See Note [Thunks in recursive groups] | otherwise = new_arity -- See Note [Trimming arity] trimmed_arity = trimArity i safe_arity (ae_rhs, rhs') = callArityAnal trimmed_arity int_body rhs ae_rhs' | called_once = ae_rhs | safe_arity == 0 = ae_rhs -- If it is not a function, its body is evaluated only once | otherwise = calledMultipleTimes ae_rhs in (True, (i `setIdCallArity` trimmed_arity, Just (called_once, new_arity, ae_rhs'), rhs')) where -- See Note [Taking boring variables into account] (new_arity, called_once) | i `elemVarSet` boring_vars = (0, False) | otherwise = lookupCallArityRes ae i (changes, ann_binds') = unzip $ map rerun ann_binds any_change = or changes -- Combining the results from body and rhs, (mutually) recursive case -- See Note [Analysis II: The Co-Called analysis] callArityRecEnv :: Bool -> [(Var, CallArityRes)] -> CallArityRes -> CallArityRes callArityRecEnv any_boring ae_rhss ae_body = -- (if length ae_rhss > 300 then pprTrace "callArityRecEnv" (vcat [ppr ae_rhss, ppr ae_body, ppr ae_new]) else id) $ ae_new where vars = map fst ae_rhss ae_combined = lubRess (map snd ae_rhss) `lubRes` ae_body cross_calls -- See Note [Taking boring variables into account] | any_boring = completeGraph (domRes ae_combined) -- Also, calculating cross_calls is expensive. Simply be conservative -- if the mutually recursive group becomes too large. | length ae_rhss > 25 = completeGraph (domRes ae_combined) | otherwise = unionUnVarGraphs $ map cross_call ae_rhss cross_call (v, ae_rhs) = completeBipartiteGraph called_by_v called_with_v where is_thunk = idCallArity v == 0 -- What rhs are relevant as happening before (or after) calling v? -- If v is a thunk, everything from all the _other_ variables -- If v is not a thunk, everything can happen. ae_before_v | is_thunk = lubRess (map snd $ filter ((/= v) . fst) ae_rhss) `lubRes` ae_body | otherwise = ae_combined -- What do we want to know from these? -- Which calls can happen next to any recursive call. called_with_v = unionUnVarSets $ map (calledWith ae_before_v) vars called_by_v = domRes ae_rhs ae_new = first (cross_calls `unionUnVarGraph`) ae_combined -- See Note [Trimming arity] trimArity :: Id -> Arity -> Arity trimArity v a = minimum [a, max_arity_by_type, max_arity_by_strsig] where max_arity_by_type = length (typeArity (idType v)) max_arity_by_strsig | isBotRes result_info = length demands | otherwise = a (demands, result_info) = splitStrictSig (idStrictness v) --------------------------------------- -- Functions related to CallArityRes -- --------------------------------------- -- Result type for the two analyses. -- See Note [Analysis I: The arity analyis] -- and Note [Analysis II: The Co-Called analysis] type CallArityRes = (UnVarGraph, VarEnv Arity) emptyArityRes :: CallArityRes emptyArityRes = (emptyUnVarGraph, emptyVarEnv) unitArityRes :: Var -> Arity -> CallArityRes unitArityRes v arity = (emptyUnVarGraph, unitVarEnv v arity) resDelList :: [Var] -> CallArityRes -> CallArityRes resDelList vs ae = foldr resDel ae vs resDel :: Var -> CallArityRes -> CallArityRes resDel v (g, ae) = (g `delNode` v, ae `delVarEnv` v) domRes :: CallArityRes -> UnVarSet domRes (_, ae) = varEnvDom ae -- In the result, find out the minimum arity and whether the variable is called -- at most once. lookupCallArityRes :: CallArityRes -> Var -> (Arity, Bool) lookupCallArityRes (g, ae) v = case lookupVarEnv ae v of Just a -> (a, not (v `elemUnVarSet` (neighbors g v))) Nothing -> (0, False) calledWith :: CallArityRes -> Var -> UnVarSet calledWith (g, _) v = neighbors g v addCrossCoCalls :: UnVarSet -> UnVarSet -> CallArityRes -> CallArityRes addCrossCoCalls set1 set2 = first (completeBipartiteGraph set1 set2 `unionUnVarGraph`) -- Replaces the co-call graph by a complete graph (i.e. no information) calledMultipleTimes :: CallArityRes -> CallArityRes calledMultipleTimes res = first (const (completeGraph (domRes res))) res -- Used for application and cases both :: CallArityRes -> CallArityRes -> CallArityRes both r1 r2 = addCrossCoCalls (domRes r1) (domRes r2) $ r1 `lubRes` r2 -- Used when combining results from alternative cases; take the minimum lubRes :: CallArityRes -> CallArityRes -> CallArityRes lubRes (g1, ae1) (g2, ae2) = (g1 `unionUnVarGraph` g2, ae1 `lubArityEnv` ae2) lubArityEnv :: VarEnv Arity -> VarEnv Arity -> VarEnv Arity lubArityEnv = plusVarEnv_C min lubRess :: [CallArityRes] -> CallArityRes lubRess = foldl lubRes emptyArityRes
tjakway/ghcjvm
compiler/simplCore/CallArity.hs
bsd-3-clause
28,592
10
19
6,934
3,248
1,788
1,460
209
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.ElastiCache.DescribeReservedCacheNodes -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | The /DescribeReservedCacheNodes/ action returns information about reserved -- cache nodes for this account, or about a specified reserved cache node. -- -- <http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_DescribeReservedCacheNodes.html> module Network.AWS.ElastiCache.DescribeReservedCacheNodes ( -- * Request DescribeReservedCacheNodes -- ** Request constructor , describeReservedCacheNodes -- ** Request lenses , drcnCacheNodeType , drcnDuration , drcnMarker , drcnMaxRecords , drcnOfferingType , drcnProductDescription , drcnReservedCacheNodeId , drcnReservedCacheNodesOfferingId -- * Response , DescribeReservedCacheNodesResponse -- ** Response constructor , describeReservedCacheNodesResponse -- ** Response lenses , drcnrMarker , drcnrReservedCacheNodes ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.ElastiCache.Types import qualified GHC.Exts data DescribeReservedCacheNodes = DescribeReservedCacheNodes { _drcnCacheNodeType :: Maybe Text , _drcnDuration :: Maybe Text , _drcnMarker :: Maybe Text , _drcnMaxRecords :: Maybe Int , _drcnOfferingType :: Maybe Text , _drcnProductDescription :: Maybe Text , _drcnReservedCacheNodeId :: Maybe Text , _drcnReservedCacheNodesOfferingId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'DescribeReservedCacheNodes' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'drcnCacheNodeType' @::@ 'Maybe' 'Text' -- -- * 'drcnDuration' @::@ 'Maybe' 'Text' -- -- * 'drcnMarker' @::@ 'Maybe' 'Text' -- -- * 'drcnMaxRecords' @::@ 'Maybe' 'Int' -- -- * 'drcnOfferingType' @::@ 'Maybe' 'Text' -- -- * 'drcnProductDescription' @::@ 'Maybe' 'Text' -- -- * 'drcnReservedCacheNodeId' @::@ 'Maybe' 'Text' -- -- * 'drcnReservedCacheNodesOfferingId' @::@ 'Maybe' 'Text' -- describeReservedCacheNodes :: DescribeReservedCacheNodes describeReservedCacheNodes = DescribeReservedCacheNodes { _drcnReservedCacheNodeId = Nothing , _drcnReservedCacheNodesOfferingId = Nothing , _drcnCacheNodeType = Nothing , _drcnDuration = Nothing , _drcnProductDescription = Nothing , _drcnOfferingType = Nothing , _drcnMaxRecords = Nothing , _drcnMarker = Nothing } -- | The cache node type filter value. Use this parameter to show only those -- reservations matching the specified cache node type. -- -- Valid node types are as follows: -- -- General purpose: Current generation: 'cache.t2.micro', 'cache.t2.small', 'cache.t2.medium', 'cache.m3.medium', 'cache.m3.large', 'cache.m3.xlarge', 'cache.m3.2xlarge' Previous -- generation: 'cache.t1.micro', 'cache.m1.small', 'cache.m1.medium', 'cache.m1.large', 'cache.m1.xlarge' Compute optimized: 'cache.c1.xlarge' Memory optimized Current generation: 'cache.r3.large', 'cache.r3.xlarge', 'cache.r3.2xlarge', 'cache.r3.4xlarge', 'cache.r3.8xlarge' Previous generation: -- 'cache.m2.xlarge', 'cache.m2.2xlarge', 'cache.m2.4xlarge' Notes: -- -- All t2 instances are created in an Amazon Virtual Private Cloud (VPC). Redis backup/restore is not supported for t2 instances. -- Redis Append-only files (AOF) functionality is not supported for t1 or t2 -- instances. For a complete listing of cache node types and specifications, -- see <http://aws.amazon.com/elasticache/details Amazon ElastiCache Product Features and Details> and <http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Memcached.html#CacheParameterGroups.Memcached.NodeSpecific Cache NodeType-Specific Parameters for Memcached> or <http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Redis.html#CacheParameterGroups.Redis.NodeSpecific Cache Node Type-Specific Parametersfor Redis>. drcnCacheNodeType :: Lens' DescribeReservedCacheNodes (Maybe Text) drcnCacheNodeType = lens _drcnCacheNodeType (\s a -> s { _drcnCacheNodeType = a }) -- | The duration filter value, specified in years or seconds. Use this parameter -- to show only reservations for this duration. -- -- Valid Values: '1 | 3 | 31536000 | 94608000' drcnDuration :: Lens' DescribeReservedCacheNodes (Maybe Text) drcnDuration = lens _drcnDuration (\s a -> s { _drcnDuration = a }) -- | An optional marker returned from a prior request. Use this marker for -- pagination of results from this action. If this parameter is specified, the -- response includes only records beyond the marker, up to the value specified -- by /MaxRecords/. drcnMarker :: Lens' DescribeReservedCacheNodes (Maybe Text) drcnMarker = lens _drcnMarker (\s a -> s { _drcnMarker = a }) -- | The maximum number of records to include in the response. If more records -- exist than the specified 'MaxRecords' value, a marker is included in the -- response so that the remaining results can be retrieved. -- -- Default: 100 -- -- Constraints: minimum 20; maximum 100. drcnMaxRecords :: Lens' DescribeReservedCacheNodes (Maybe Int) drcnMaxRecords = lens _drcnMaxRecords (\s a -> s { _drcnMaxRecords = a }) -- | The offering type filter value. Use this parameter to show only the available -- offerings matching the specified offering type. -- -- Valid values: '"Light Utilization"|"Medium Utilization"|"Heavy Utilization"' drcnOfferingType :: Lens' DescribeReservedCacheNodes (Maybe Text) drcnOfferingType = lens _drcnOfferingType (\s a -> s { _drcnOfferingType = a }) -- | The product description filter value. Use this parameter to show only those -- reservations matching the specified product description. drcnProductDescription :: Lens' DescribeReservedCacheNodes (Maybe Text) drcnProductDescription = lens _drcnProductDescription (\s a -> s { _drcnProductDescription = a }) -- | The reserved cache node identifier filter value. Use this parameter to show -- only the reservation that matches the specified reservation ID. drcnReservedCacheNodeId :: Lens' DescribeReservedCacheNodes (Maybe Text) drcnReservedCacheNodeId = lens _drcnReservedCacheNodeId (\s a -> s { _drcnReservedCacheNodeId = a }) -- | The offering identifier filter value. Use this parameter to show only -- purchased reservations matching the specified offering identifier. drcnReservedCacheNodesOfferingId :: Lens' DescribeReservedCacheNodes (Maybe Text) drcnReservedCacheNodesOfferingId = lens _drcnReservedCacheNodesOfferingId (\s a -> s { _drcnReservedCacheNodesOfferingId = a }) data DescribeReservedCacheNodesResponse = DescribeReservedCacheNodesResponse { _drcnrMarker :: Maybe Text , _drcnrReservedCacheNodes :: List "member" ReservedCacheNode } deriving (Eq, Read, Show) -- | 'DescribeReservedCacheNodesResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'drcnrMarker' @::@ 'Maybe' 'Text' -- -- * 'drcnrReservedCacheNodes' @::@ ['ReservedCacheNode'] -- describeReservedCacheNodesResponse :: DescribeReservedCacheNodesResponse describeReservedCacheNodesResponse = DescribeReservedCacheNodesResponse { _drcnrMarker = Nothing , _drcnrReservedCacheNodes = mempty } -- | Provides an identifier to allow retrieval of paginated results. drcnrMarker :: Lens' DescribeReservedCacheNodesResponse (Maybe Text) drcnrMarker = lens _drcnrMarker (\s a -> s { _drcnrMarker = a }) -- | A list of reserved cache nodes. Each element in the list contains detailed -- information about one node. drcnrReservedCacheNodes :: Lens' DescribeReservedCacheNodesResponse [ReservedCacheNode] drcnrReservedCacheNodes = lens _drcnrReservedCacheNodes (\s a -> s { _drcnrReservedCacheNodes = a }) . _List instance ToPath DescribeReservedCacheNodes where toPath = const "/" instance ToQuery DescribeReservedCacheNodes where toQuery DescribeReservedCacheNodes{..} = mconcat [ "CacheNodeType" =? _drcnCacheNodeType , "Duration" =? _drcnDuration , "Marker" =? _drcnMarker , "MaxRecords" =? _drcnMaxRecords , "OfferingType" =? _drcnOfferingType , "ProductDescription" =? _drcnProductDescription , "ReservedCacheNodeId" =? _drcnReservedCacheNodeId , "ReservedCacheNodesOfferingId" =? _drcnReservedCacheNodesOfferingId ] instance ToHeaders DescribeReservedCacheNodes instance AWSRequest DescribeReservedCacheNodes where type Sv DescribeReservedCacheNodes = ElastiCache type Rs DescribeReservedCacheNodes = DescribeReservedCacheNodesResponse request = post "DescribeReservedCacheNodes" response = xmlResponse instance FromXML DescribeReservedCacheNodesResponse where parseXML = withElement "DescribeReservedCacheNodesResult" $ \x -> DescribeReservedCacheNodesResponse <$> x .@? "Marker" <*> x .@? "ReservedCacheNodes" .!@ mempty instance AWSPager DescribeReservedCacheNodes where page rq rs | stop (rs ^. drcnrMarker) = Nothing | otherwise = (\x -> rq & drcnMarker ?~ x) <$> (rs ^. drcnrMarker)
romanb/amazonka
amazonka-elasticache/gen/Network/AWS/ElastiCache/DescribeReservedCacheNodes.hs
mpl-2.0
10,392
0
12
2,056
1,105
661
444
112
1
{- Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE PackageImports #-} {-# LANGUAGE NoImplicitPrelude #-} module Data.Ix (module M) where import "base" Data.Ix as M
d191562687/codeworld
codeworld-base/src/Data/Ix.hs
apache-2.0
729
0
4
136
23
17
6
4
0
{-# LANGUAGE ScopedTypeVariables #-} -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you 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 Main where import qualified Control.Exception import qualified Data.Map as Map import qualified Data.Set as Set import qualified Network import Thrift import Thrift.Protocol.Binary import Thrift.Server import Thrift.Transport.Handle import qualified ThriftTestUtils import qualified ThriftTest import qualified ThriftTest_Client as Client import qualified ThriftTest_Iface as Iface import qualified ThriftTest_Types as Types data TestHandler = TestHandler instance Iface.ThriftTest_Iface TestHandler where testVoid _ = return () testString _ (Just s) = do ThriftTestUtils.serverLog s return s testString _ Nothing = do error $ "Unsupported testString form" testByte _ (Just x) = do ThriftTestUtils.serverLog $ show x return x testByte _ Nothing = do error $ "Unsupported testByte form" testI32 _ (Just x) = do ThriftTestUtils.serverLog $ show x return x testI32 _ Nothing = do error $ "Unsupported testI32 form" testI64 _ (Just x) = do ThriftTestUtils.serverLog $ show x return x testI64 _ Nothing = do error $ "Unsupported testI64 form" testDouble _ (Just x) = do ThriftTestUtils.serverLog $ show x return x testDouble _ Nothing = do error $ "Unsupported testDouble form" testStruct _ (Just x) = do ThriftTestUtils.serverLog $ show x return x testStruct _ Nothing = do error $ "Unsupported testStruct form" testNest _ (Just x) = do ThriftTestUtils.serverLog $ show x return x testNest _ Nothing = do error $ "Unsupported testNest form" testMap _ (Just x) = do ThriftTestUtils.serverLog $ show x return x testMap _ Nothing = do error $ "Unsupported testMap form" testStringMap _ (Just x) = do ThriftTestUtils.serverLog $ show x return x testStringMap _ Nothing = do error $ "Unsupported testMap form" testSet _ (Just x) = do ThriftTestUtils.serverLog $ show x return x testSet _ Nothing = do error $ "Unsupported testSet form" testList _ (Just x) = do ThriftTestUtils.serverLog $ show x return x testList _ Nothing = do error $ "Unsupported testList form" testEnum _ (Just x) = do ThriftTestUtils.serverLog $ show x return x testEnum _ Nothing = do error $ "Unsupported testEnum form" testTypedef _ (Just x) = do ThriftTestUtils.serverLog $ show x return x testTypedef _ Nothing = do error $ "Unsupported testTypedef form" testMapMap _ (Just _) = do return (Map.fromList [(1, Map.fromList [(2, 2)])]) testMapMap _ Nothing = do error $ "Unsupported testMapMap form" testInsanity _ (Just x) = do return (Map.fromList [(1, Map.fromList [(Types.ONE, x)])]) testInsanity _ Nothing = do error $ "Unsupported testInsanity form" testMulti _ _ _ _ _ _ _ = do return (Types.Xtruct Nothing Nothing Nothing Nothing) testException _ _ = do Control.Exception.throw (Types.Xception (Just 1) (Just "bya")) testMultiException _ _ _ = do Control.Exception.throw (Types.Xception (Just 1) (Just "xyz")) testOneway _ (Just i) = do ThriftTestUtils.serverLog $ show i testOneway _ Nothing = do error $ "Unsupported testOneway form" client :: (String, Network.PortID) -> IO () client addr = do to <- hOpen addr let ps = (BinaryProtocol to, BinaryProtocol to) v1 <- Client.testString ps "bya" ThriftTestUtils.clientLog v1 v2 <- Client.testByte ps 8 ThriftTestUtils.clientLog $ show v2 v3 <- Client.testByte ps (-8) ThriftTestUtils.clientLog $ show v3 v4 <- Client.testI32 ps 32 ThriftTestUtils.clientLog $ show v4 v5 <- Client.testI32 ps (-32) ThriftTestUtils.clientLog $ show v5 v6 <- Client.testI64 ps 64 ThriftTestUtils.clientLog $ show v6 v7 <- Client.testI64 ps (-64) ThriftTestUtils.clientLog $ show v7 v8 <- Client.testDouble ps 3.14 ThriftTestUtils.clientLog $ show v8 v9 <- Client.testDouble ps (-3.14) ThriftTestUtils.clientLog $ show v9 v10 <- Client.testMap ps (Map.fromList [(1,1),(2,2),(3,3)]) ThriftTestUtils.clientLog $ show v10 v11 <- Client.testStringMap ps (Map.fromList [("a","123"),("a b","with spaces "),("same","same"),("0","numeric key")]) ThriftTestUtils.clientLog $ show v11 v12 <- Client.testList ps [1,2,3,4,5] ThriftTestUtils.clientLog $ show v12 v13 <- Client.testSet ps (Set.fromList [1,2,3,4,5]) ThriftTestUtils.clientLog $ show v13 v14 <- Client.testStruct ps (Types.Xtruct (Just "hi") (Just 4) (Just 5) Nothing) ThriftTestUtils.clientLog $ show v14 (testException ps "bad") `Control.Exception.catch` testExceptionHandler (testMultiException ps "ok") `Control.Exception.catch` testMultiExceptionHandler1 (testMultiException ps "bad") `Control.Exception.catch` testMultiExceptionHandler2 `Control.Exception.catch` testMultiExceptionHandler3 -- ( (Client.testMultiException ps "e" "e2">> ThriftTestUtils.clientLog "bad") `Control.Exception.catch` tClose to where testException ps msg = do Client.testException ps "e" ThriftTestUtils.clientLog msg return () testExceptionHandler (e :: Types.Xception) = do ThriftTestUtils.clientLog $ show e testMultiException ps msg = do _ <- Client.testMultiException ps "e" "e2" ThriftTestUtils.clientLog msg return () testMultiExceptionHandler1 (e :: Types.Xception) = do ThriftTestUtils.clientLog $ show e testMultiExceptionHandler2 (e :: Types.Xception2) = do ThriftTestUtils.clientLog $ show e testMultiExceptionHandler3 (_ :: Control.Exception.SomeException) = do ThriftTestUtils.clientLog "ok" server :: Network.PortNumber -> IO () server port = do ThriftTestUtils.serverLog "Ready..." (runBasicServer TestHandler ThriftTest.process port) `Control.Exception.catch` (\(TransportExn s _) -> error $ "FAILURE: " ++ s) main :: IO () main = ThriftTestUtils.runTest server client
YinYanfei/CadalWorkspace
thrift/src/thrift-0.8.0/test/hs/ThriftTest_Main.hs
gpl-3.0
7,188
0
16
1,794
2,056
1,008
1,048
161
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="fa-IR"> <title>GraalVM JavaScript</title> <maps> <homeID>graaljs</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>
kingthorin/zap-extensions
addOns/graaljs/src/main/javahelp/help_fa_IR/helpset_fa_IR.hs
apache-2.0
967
77
66
156
407
206
201
-1
-1
module PolymorhicIn1 where f :: [a] -> a f ((x : xs@[])) = x f ((x : xs@(b_1 : b_2))) = x f ((x : xs)) = x
kmate/HaRe
old/testing/subIntroPattern/PolymorphicIn1_TokOut.hs
bsd-3-clause
108
0
11
29
85
49
36
5
1
module M where import A f :: T -> String f = show
ezyang/ghc
testsuite/tests/backpack/cabal/bkpcabal05/M.hs
bsd-3-clause
50
0
5
13
21
13
8
4
1
{-# LANGUAGE TypeOperators #-} module T4239A where data (:+++) = (:+++) | (:---) | X | Y
urbanslug/ghc
testsuite/tests/rename/should_compile/T4239A.hs
bsd-3-clause
129
4
4
57
28
20
8
6
0
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-} {-# LANGUAGE Arrows, FunctionalDependencies, FlexibleContexts, MultiParamTypeClasses, RecordWildCards #-} module T5045 where import Control.Arrow class (Control.Arrow.Arrow a') => ArrowAddReader r a a' | a -> a' where elimReader :: a (e, s) b -> a' (e, (r, s)) b newtype ByteString = FakeByteString String pathInfo :: Monad m => m String pathInfo = undefined requestMethod :: Monad m => m String requestMethod = undefined getInputsFPS :: Monad m => m [(String, ByteString)] getInputsFPS = undefined class HTTPRequest r s | r -> s where httpGetPath :: r -> String httpSetPath :: r -> String -> r httpGetMethod :: r -> String httpGetInputs :: r -> [(String, s)] data CGIDispatch = CGIDispatch { dispatchPath :: String, dispatchMethod :: String, dispatchInputs :: [(String, ByteString)] } instance HTTPRequest CGIDispatch ByteString where httpGetPath = dispatchPath httpSetPath r s = r { dispatchPath = s } httpGetMethod = dispatchMethod httpGetInputs = dispatchInputs runDispatch :: (Arrow a, ArrowAddReader CGIDispatch a a', Monad m) => a b c -> m (a' b c) runDispatch a = do dispatchPath <- pathInfo dispatchMethod <- requestMethod dispatchInputs <- getInputsFPS return $ proc b -> (| elimReader (a -< b) |) CGIDispatch { .. }
urbanslug/ghc
testsuite/tests/ghci/scripts/T5045.hs
bsd-3-clause
1,375
3
12
293
418
228
190
-1
-1
{-# LANGUAGE Safe #-} module UnsafeInfered09 where import safe UnsafeInfered09_A h :: Int h = g
ghc-android/ghc
testsuite/tests/safeHaskell/safeInfered/UnsafeInfered09.hs
bsd-3-clause
99
1
4
19
19
13
6
5
1