code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Parser where import Data.Binary import Data.Binary.Get import qualified Data.ByteString.Lazy as BS import Codec.Compression.GZip (decompress) import Control.Monad import Numeric.LinearAlgebra import Numeric.LinearAlgebra.Devel import qualified Data.Vector as V import Control.Monad.ST type Pixel = Word8 type Image = V.Vector (Matrix Float) type Label = Vector Float decodeImages :: Get [Image] decodeImages = do mc <- getWord32be guard (mc == 0x00000803) [d1,d2,d3] <- many 3 getWord32be guard (d2 == 28 && d3 == 28) many d1 pic where pic :: Get Image pic = do bs <- getByteString (28*28) return . V.singleton . reshape 28 . toVecDouble . fromByteString $ bs toVecDouble :: Vector Pixel -> Vector Float -- mapVectorM requires the monad be strict -- so Identity monad shall not be used toVecDouble v = runST $ mapVectorM (return . (/255) . fromIntegral) v decodeLabels :: Get [Label] decodeLabels = do mc <- getWord32be guard (mc == 0x00000801) d1 <- getWord32be many d1 lbl where lbl :: Get Label lbl = do v <- fromIntegral <$> (get :: Get Word8) return $ fromList (replicate v 0 ++ [1] ++ replicate (9-v) 0) many :: (Integral n, Monad m) => n -> m a -> m [a] many cnt dec = sequence (replicate (fromIntegral cnt) dec) trainingData :: IO ([Image], [Label]) trainingData = do s <- decompress <$> BS.readFile "tdata/train-images-idx3-ubyte.gz" t <- decompress <$> BS.readFile "tdata/train-labels-idx1-ubyte.gz" return (runGet decodeImages s, runGet decodeLabels t) testData :: IO ([Image], [Label]) testData = do s <- decompress <$> BS.readFile "tdata/t10k-images-idx3-ubyte.gz" t <- decompress <$> BS.readFile "tdata/t10k-labels-idx1-ubyte.gz" return (runGet decodeImages s, runGet decodeLabels t)
pierric/neural-network
Backend-hmatrix/Example/MNIST/Parser.hs
bsd-3-clause
1,889
0
15
440
641
331
310
48
1
module Paths_sandlib ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version {versionBranch = [0,0,3], versionTags = []} bindir, libdir, datadir, libexecdir :: FilePath bindir = "/home/vertexclique/.cabal/bin" libdir = "/home/vertexclique/.cabal/lib/sandlib-0.0.3/ghc-7.4.1" datadir = "/home/vertexclique/.cabal/share/sandlib-0.0.3" libexecdir = "/home/vertexclique/.cabal/libexec" getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath getBinDir = catchIO (getEnv "sandlib_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "sandlib_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "sandlib_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "sandlib_libexecdir") (\_ -> return libexecdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
vertexclique/sandlib
dist/build/autogen/Paths_sandlib.hs
bsd-3-clause
1,149
0
10
164
326
186
140
25
1
-- | Errors that may occur during decoding/encoding of HTTP message bodies module Network.HTTP.Encoding.Error (EncodingError (..) ,ConversionError (..)) where import Codec.Text.IConv (ConversionError ,reportConversionError) -- | Encoding/Decoding error message data EncodingError = CannotDetermineCharacterEncoding -- ^ Character decoding is not specified and -- cannot be guessed | UnsupportedCompressionAlgorithm -- ^ A compression algorithm is not supported (LZW) | IConvError ConversionError -- ^ IConv conversion error | GenericError String -- ^ Other error instance Show EncodingError where show err = case err of CannotDetermineCharacterEncoding -> "No character encoding was specified in message headers \ \and the body character encoding cannot be determined" UnsupportedCompressionAlgorithm -> "Sorry, the 'compress' algorithm is not supported at this time" IConvError conv_err -> "Charset conversion error in iconv: " ++ show (reportConversionError conv_err) GenericError err -> "Generic error: " ++ err
achudnov/http-encodings
Network/HTTP/Encoding/Error.hs
bsd-3-clause
1,337
0
12
454
132
77
55
18
0
{-# LANGUAGE UnicodeSyntax #-} module Shake.It.FileSystem ( module FileSystem ) where import Shake.It.FileSystem.Dir as FileSystem import Shake.It.FileSystem.File as FileSystem
Heather/Shake.it.off
src/Shake/It/FileSystem.hs
bsd-3-clause
204
0
4
46
32
24
8
5
0
{-# LANGUAGE TypeOperators #-} module Web.ApiAi.API ( module Import , ApiAiAPI ) where import Servant.API import Web.ApiAi.API.Core as Import import Web.ApiAi.API.Entities as Import import Web.ApiAi.API.Query as Import type ApiAiAPI = ApiAiEntitiesAPI :<|> ApiAiQueryAPI
CthulhuDen/api-ai
src/Web/ApiAi/API.hs
bsd-3-clause
286
0
5
48
59
42
17
9
0
----------------------------------------------------------------------------- -- | -- Module : Distribution.Make -- Copyright : Martin Sj&#xF6;gren 2004 -- -- Maintainer : [email protected] -- Portability : portable -- -- This is an alternative build system that delegates everything to the @make@ -- program. All the commands just end up calling @make@ with appropriate -- arguments. The intention was to allow preexisting packages that used -- makefiles to be wrapped into Cabal packages. In practice essentially all -- such packages were converted over to the \"Simple\" build system instead. -- Consequently this module is not used much and it certainly only sees cursory -- maintenance and no testing. Perhaps at some point we should stop pretending -- that it works. -- -- Uses the parsed command-line from Distribution.Setup in order to build -- Haskell tools using a backend build system based on make. Obviously we -- assume that there is a configure script, and that after the ConfigCmd has -- been run, there is a Makefile. Further assumptions: -- -- [ConfigCmd] We assume the configure script accepts -- @--with-hc@, -- @--with-hc-pkg@, -- @--prefix@, -- @--bindir@, -- @--libdir@, -- @--libexecdir@, -- @--datadir@. -- -- [BuildCmd] We assume that the default Makefile target will build everything. -- -- [InstallCmd] We assume there is an @install@ target. Note that we assume that -- this does *not* register the package! -- -- [CopyCmd] We assume there is a @copy@ target, and a variable @$(destdir)@. -- The @copy@ target should probably just invoke @make install@ -- recursively (e.g. @$(MAKE) install prefix=$(destdir)\/$(prefix) -- bindir=$(destdir)\/$(bindir)@. The reason we can\'t invoke @make -- install@ directly here is that we don\'t know the value of @$(prefix)@. -- -- [SDistCmd] We assume there is a @dist@ target. -- -- [RegisterCmd] We assume there is a @register@ target and a variable @$(user)@. -- -- [UnregisterCmd] We assume there is an @unregister@ target. -- -- [HaddockCmd] We assume there is a @docs@ or @doc@ target. -- copy : -- $(MAKE) install prefix=$(destdir)/$(prefix) \ -- bindir=$(destdir)/$(bindir) \ {- 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 Isaac Jones nor the names of other 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 OWNER 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 Distribution.Make ( module Distribution.Package, License(..), Version(..), defaultMain, defaultMainArgs, defaultMainNoRead ) where -- local import Distribution.Package --must not specify imports, since we're exporting moule. import Distribution.Simple.Program(defaultProgramConfiguration) import Distribution.PackageDescription import Distribution.Simple.Setup import Distribution.Simple.Command import Distribution.Simple.Utils (rawSystemExit, cabalVersion) import Distribution.License (License(..)) import Distribution.Version ( Version(..) ) import Distribution.Text ( display ) import System.Environment (getArgs, getProgName) import Data.List (intersperse) import System.Exit defaultMain :: IO () defaultMain = getArgs >>= defaultMainArgs defaultMainArgs :: [String] -> IO () defaultMainArgs = defaultMainHelper {-# DEPRECATED defaultMainNoRead "it ignores its PackageDescription arg" #-} defaultMainNoRead :: PackageDescription -> IO () defaultMainNoRead = const defaultMain defaultMainHelper :: [String] -> IO () defaultMainHelper args = case commandsRun globalCommand commands args of CommandHelp help -> printHelp help CommandList opts -> printOptionsList opts CommandErrors errs -> printErrors errs CommandReadyToGo (flags, commandParse) -> case commandParse of _ | fromFlag (globalVersion flags) -> printVersion | fromFlag (globalNumericVersion flags) -> printNumericVersion CommandHelp help -> printHelp help CommandList opts -> printOptionsList opts CommandErrors errs -> printErrors errs CommandReadyToGo action -> action where printHelp help = getProgName >>= putStr . help printOptionsList = putStr . unlines printErrors errs = do putStr (concat (intersperse "\n" errs)) exitWith (ExitFailure 1) printNumericVersion = putStrLn $ display cabalVersion printVersion = putStrLn $ "Cabal library version " ++ display cabalVersion progs = defaultProgramConfiguration commands = [configureCommand progs `commandAddAction` configureAction ,buildCommand progs `commandAddAction` buildAction ,installCommand `commandAddAction` installAction ,copyCommand `commandAddAction` copyAction ,haddockCommand `commandAddAction` haddockAction ,cleanCommand `commandAddAction` cleanAction ,sdistCommand `commandAddAction` sdistAction ,registerCommand `commandAddAction` registerAction ,unregisterCommand `commandAddAction` unregisterAction ] configureAction :: ConfigFlags -> [String] -> IO () configureAction flags args = do noExtraFlags args let verbosity = fromFlag (configVerbosity flags) rawSystemExit verbosity "sh" $ "configure" : configureArgs backwardsCompatHack flags where backwardsCompatHack = True copyAction :: CopyFlags -> [String] -> IO () copyAction flags args = do noExtraFlags args let destArgs = case fromFlag $ copyDest flags of NoCopyDest -> ["install"] CopyTo path -> ["copy", "destdir=" ++ path] CopyPrefix path -> ["install", "prefix=" ++ path] -- CopyPrefix is backwards compat, DEPRECATED rawSystemExit (fromFlag $ copyVerbosity flags) "make" destArgs installAction :: InstallFlags -> [String] -> IO () installAction flags args = do noExtraFlags args rawSystemExit (fromFlag $ installVerbosity flags) "make" ["install"] rawSystemExit (fromFlag $ installVerbosity flags) "make" ["register"] haddockAction :: HaddockFlags -> [String] -> IO () haddockAction flags args = do noExtraFlags args rawSystemExit (fromFlag $ haddockVerbosity flags) "make" ["docs"] `catch` \_ -> rawSystemExit (fromFlag $ haddockVerbosity flags) "make" ["doc"] buildAction :: BuildFlags -> [String] -> IO () buildAction flags args = do noExtraFlags args rawSystemExit (fromFlag $ buildVerbosity flags) "make" [] cleanAction :: CleanFlags -> [String] -> IO () cleanAction flags args = do noExtraFlags args rawSystemExit (fromFlag $ cleanVerbosity flags) "make" ["clean"] sdistAction :: SDistFlags -> [String] -> IO () sdistAction flags args = do noExtraFlags args rawSystemExit (fromFlag $ sDistVerbosity flags) "make" ["dist"] registerAction :: RegisterFlags -> [String] -> IO () registerAction flags args = do noExtraFlags args rawSystemExit (fromFlag $ regVerbosity flags) "make" ["register"] unregisterAction :: RegisterFlags -> [String] -> IO () unregisterAction flags args = do noExtraFlags args rawSystemExit (fromFlag $ regVerbosity flags) "make" ["unregister"]
dcreager/cabal
Distribution/Make.hs
bsd-3-clause
8,739
0
16
1,920
1,317
703
614
105
8
-- | Here we use @dynamic-object@ to descibe the concept of point-like particles from -- classical mechanics. Also read the HSpec tests : -- <https://github.com/nushio3/dynamic-object/blob/master/test/ObjectSpec.hs> -- for more details. {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Data.Object.Dynamic.Examples.PointParticle (Vec(..), Mass(..), Velocity(..), Momentum(..), KineticEnergy(..), mass, velocity, momentum, kineticEnergy, fromMassVelocity, fromMassMomentum, laserBeam, duck, lens, banana, envelope, ghost ) where import Control.Applicative hiding (empty) import Control.Lens hiding (lens) import Data.Dynamic import Data.String import Test.QuickCheck import Data.Object.Dynamic import Data.Object.Dynamic.Type -- $setup -- >>> :set -XOverloadedStrings -- >>> :set -XScopedTypeVariables -- >>> import Data.Object.Dynamic.Presets -- >>> import Data.Maybe -- | First, let us create a tiny two-dimensional vector class. -- We make it an instance of 'Arbitrary' to use them later for tests. data Vec a = Vec a a deriving (Eq, Show, Ord, Typeable) instance (Arbitrary a) => Arbitrary (Vec a) where arbitrary = Vec <$> arbitrary <*> arbitrary shrink (Vec x y) = Vec <$> shrink x <*> shrink y -- | Now, let us introduce the concepts of 'Mass', 'Velocity', -- 'Momentum' and 'KineticEnergy'. Any such concepts are described -- in terms of 'Member' labels. data Mass = Mass deriving (Typeable) instance (Objective o, UseReal o) => Member o Mass where type ValType o Mass = UnderlyingReal o -- | To define a member with compound types like vector of real numbers, -- we use 'UnderlyingReal' to -- ask the object which real value it prefers, then put the response -- into the type constructors. -- -- We also give a fallback accessor here. If the 'velocity' field is missing, we attempt to re-calculate it -- from the 'mass' and 'momentum'. Here is how we can do that. data Velocity = Velocity deriving (Typeable) instance (Objective o, UseReal o, Fractional (UnderlyingReal o)) => Member o Velocity where type ValType o Velocity = Vec (UnderlyingReal o) memberLookup = acyclically $ do m <- its Mass Vec mx my <- its Momentum return $ Vec (mx/m) (my/m) -- | If the 'momentum' field is missing, we re-calculate it -- from the 'mass' and 'velocity'. data Momentum = Momentum deriving (Typeable) instance (Objective o, UseReal o, Fractional (UnderlyingReal o)) => Member o Momentum where type ValType o Momentum = Vec (UnderlyingReal o) memberLookup = acyclically $ do m <- its Mass Vec vx vy <- its Velocity return $ Vec (m * vx) (m * vy) -- | 'kineticEnergy', unless given explicitly, is defined in terms of 'mass' and 'velocity' . data KineticEnergy = KineticEnergy deriving (Typeable) instance (Objective o, UseReal o, Fractional (UnderlyingReal o)) => Member o KineticEnergy where type ValType o KineticEnergy = UnderlyingReal o memberLookup = acyclically $ do m <- its Mass Vec vx vy <- its Velocity return $ ((m * vx * vx) + (m * vy * vy)) / 2 -- | Now we define the lenses. mass :: MemberLens o Mass mass = memberLens Mass velocity :: MemberLens o Velocity velocity = memberLens Velocity momentum :: (UseReal o, Fractional (UnderlyingReal o)) => MemberLens o Momentum momentum = memberLens Momentum kineticEnergy :: (UseReal o, Fractional (UnderlyingReal o)) => MemberLens o KineticEnergy kineticEnergy = memberLens KineticEnergy -- | We can write functions that would construct a point particle from -- its mass and velocity. And we can make the function polymorphic over the -- representation of the real numbers the objects prefer. fromMassVelocity :: (Objective o, UseReal o, Fractional real, real ~ (UnderlyingReal o)) => real -> Vec real -> o fromMassVelocity m v = empty & insert Mass m & insert Velocity v -- | We can also construct a point particle from -- its mass and momentum. fromMassMomentum :: (Objective o, UseReal o, Fractional real, real ~ (UnderlyingReal o)) => real -> Vec real -> o fromMassMomentum m v = empty & insert Mass m & insert Momentum v -- | We define an instance of point-like particle. And again, we can -- keep it polymorphic, so that anyone can choose its concrete type -- later, according to their purpose. Thus we will achieve the -- polymorphic encoding of the knowledge of this world, in Haskell. -- -- >>> (laserBeam :: Object DIT) ^? kineticEnergy -- Just 1631.25 -- >>> (laserBeam :: Object Precise) ^? kineticEnergy -- Just (6525 % 4) -- -- Moreover, we can ask Ichiro to sign the ball. Usually, we needed to -- create a new data-type to add a new field. But with -- 'dynamic-object' we can do so without changing the type of the -- ball. So, we can put our precious, one-of-a-kind ball -- into toybox together with less uncommon balls, and with various -- other toys. And still, we can safely access the contents of the -- toybox without runtime errors, and e.g. see which toy is the heaviest. -- -- >>> let (mySpecialBall :: Object DIT) = laserBeam & insert Autograph "Ichiro Suzuki" -- >>> let toybox = [laserBeam, mySpecialBall] -- >>> let toybox2 = toybox ++ [duck, lens, banana, envelope, ghost] -- >>> maximum $ mapMaybe (^?mass) toybox2 -- 5.2 laserBeam :: (Objective o, UseReal o, Fractional real, real ~ (UnderlyingReal o)) => o laserBeam = fromMassVelocity 0.145 (Vec 150 0) -- a baseball thrown by -- Ichiro duck, lens, banana :: (Objective o, UseReal o, Fractional real, real ~ (UnderlyingReal o)) => o duck = empty & insert Mass 5.2 lens = empty & insert Mass 0.56 banana = empty & insert Mass 0.187 envelope :: (Objective o, UseReal o, UseString o, Fractional (UnderlyingReal o), IsString (UnderlyingString o)) => o envelope = empty & insert Mass 0.025 & insert Autograph (fromString "Edward Kmett") ghost :: (Objective o) => o ghost = empty data Autograph = Autograph deriving Typeable instance (Objective o, UseString o) => Member o Autograph where type ValType o Autograph = UnderlyingString o
nushio3/dynamic-object
Data/Object/Dynamic/Examples/PointParticle.hs
bsd-3-clause
6,339
0
15
1,281
1,307
717
590
81
1
module Main (main) where import D12Lib import System.Environment (getArgs) import Text.Parsec.String (parseFromFile) main :: IO () main = do file <- head <$> getArgs parseResult <- parseFromFile instructionsP file let instructions = either (error . show) id parseResult let vm = newVM instructions let vmRan = run vm putStrLn $ "final VM part 1: " ++ show vmRan let vm2 = newVM2 instructions let vm2Ran = run vm2 putStrLn $ "final VM part 2: " ++ show vm2Ran
wfleming/advent-of-code-2016
2016/app/D12.hs
bsd-3-clause
481
0
12
100
170
82
88
15
1
{-# LANGUAGE OverloadedStrings #-} module InvalidateCacheTestCommon (test1Common) where import qualified Data.ByteString.Char8 as BS test1Common lookup3 keysCached3 invalidateCache3 = do b <- lookup3 ("file1" :: BS.ByteString) b <- lookup3 "file2" b <- lookup3 "file3" b <- lookup3 "file2" b <- lookup3 "file3" shouldBe 3 "file3" b <- lookup3 "file1" b <- lookup3 "file2" b <- lookup3 "file3" b <- lookup3 "file1" shouldBe 3 "file1" b <- lookup3 "file1" b <- lookup3 "file2" b <- lookup3 "file3" b <- lookup3 "file4" b <- lookup3 "file5" b <- lookup3 "file2" shouldBe 5 "file2" b <- lookup3 "file1" b <- lookup3 "file2" b <- lookup3 "file3" b <- lookup3 "file4" b <- lookup3 "file5" b <- lookup3 "file6" b <- lookup3 "file7" b <- lookup3 "file8" b <- lookup3 "file9" b <- lookup3 "file3" shouldBe 9 "file3" return () where shouldBe count lastkey = do l <- keysCached3 putStrLn $ show l if count == (length l) then do kv <- invalidateCache3 putStrLn $ show kv case kv of Just (k, v) | k == lastkey -> do l2 <- keysCached3 if 0 == (length l2) then return () else error "Did not fully invalidate" else error "Wrong length"
elblake/expiring-cache-map
tests/InvalidateCacheTestCommon.hs
bsd-3-clause
1,344
0
21
419
467
204
263
48
3
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Init -- Copyright : (c) Brent Yorgey 2009 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Implementation of the 'cabal init' command, which creates an initial .cabal -- file for a project. -- ----------------------------------------------------------------------------- module Distribution.Client.Init ( -- * Commands initCabal ) where import System.IO ( hSetBuffering, stdout, BufferMode(..) ) import System.Directory ( getCurrentDirectory ) import Data.Time ( getCurrentTime, utcToLocalTime, toGregorian, localDay, getCurrentTimeZone ) import Data.List ( intersperse, (\\) ) import Data.Maybe ( fromMaybe, isJust ) import Data.Traversable ( traverse ) import Control.Monad ( when ) #if MIN_VERSION_base(3,0,0) import Control.Monad ( (>=>), join ) #endif import Text.PrettyPrint hiding (mode, cat) import Data.Version ( Version(..) ) import Distribution.Version ( orLaterVersion ) import Distribution.Client.Init.Types ( InitFlags(..), PackageType(..), Category(..) ) import Distribution.Client.Init.Licenses ( bsd3, gplv2, gplv3, lgpl2, lgpl3 ) import Distribution.Client.Init.Heuristics ( guessPackageName, guessAuthorNameMail, SourceFileEntry(..), scanForModules, neededBuildPrograms ) import Distribution.License ( License(..), knownLicenses ) import Distribution.ModuleName ( ) -- for the Text instance import Distribution.ReadE ( runReadE, readP_to_E ) import Distribution.Simple.Setup ( Flag(..), flagToMaybe ) import Distribution.Text ( display, Text(..) ) initCabal :: InitFlags -> IO () initCabal initFlags = do hSetBuffering stdout NoBuffering initFlags' <- extendFlags initFlags writeLicense initFlags' writeSetupFile initFlags' success <- writeCabalFile initFlags' when success $ generateWarnings initFlags' --------------------------------------------------------------------------- -- Flag acquisition ----------------------------------------------------- --------------------------------------------------------------------------- -- | Fill in more details by guessing, discovering, or prompting the -- user. extendFlags :: InitFlags -> IO InitFlags extendFlags = getPackageName >=> getVersion >=> getLicense >=> getAuthorInfo >=> getHomepage >=> getSynopsis >=> getCategory >=> getLibOrExec >=> getGenComments >=> getSrcDir >=> getModulesAndBuildTools -- | Combine two actions which may return a value, preferring the first. That -- is, run the second action only if the first doesn't return a value. infixr 1 ?>> (?>>) :: IO (Maybe a) -> IO (Maybe a) -> IO (Maybe a) f ?>> g = do ma <- f if isJust ma then return ma else g -- | Witness the isomorphism between Maybe and Flag. maybeToFlag :: Maybe a -> Flag a maybeToFlag = maybe NoFlag Flag -- | Get the package name: use the package directory (supplied, or the current -- directory by default) as a guess. getPackageName :: InitFlags -> IO InitFlags getPackageName flags = do guess <- traverse guessPackageName (flagToMaybe $ packageDir flags) ?>> Just `fmap` (getCurrentDirectory >>= guessPackageName) pkgName' <- return (flagToMaybe $ packageName flags) ?>> maybePrompt flags (promptStr "Package name" guess) ?>> return guess return $ flags { packageName = maybeToFlag pkgName' } -- | Package version: use 0.1.0.0 as a last resort, but try prompting the user -- if possible. getVersion :: InitFlags -> IO InitFlags getVersion flags = do let v = Just $ Version { versionBranch = [0,1,0,0], versionTags = [] } v' <- return (flagToMaybe $ version flags) ?>> maybePrompt flags (prompt "Package version" v) ?>> return v return $ flags { version = maybeToFlag v' } -- | Choose a license. getLicense :: InitFlags -> IO InitFlags getLicense flags = do lic <- return (flagToMaybe $ license flags) ?>> fmap (fmap (either UnknownLicense id) . join) (maybePrompt flags (promptListOptional "Please choose a license" listedLicenses)) return $ flags { license = maybeToFlag lic } where listedLicenses = knownLicenses \\ [GPL Nothing, LGPL Nothing, OtherLicense] -- | The author's name and email. Prompt, or try to guess from an existing -- darcs repo. getAuthorInfo :: InitFlags -> IO InitFlags getAuthorInfo flags = do (authorName, authorEmail) <- (\(a,e) -> (flagToMaybe a, flagToMaybe e)) `fmap` guessAuthorNameMail authorName' <- return (flagToMaybe $ author flags) ?>> maybePrompt flags (promptStr "Author name" authorName) ?>> return authorName authorEmail' <- return (flagToMaybe $ email flags) ?>> maybePrompt flags (promptStr "Maintainer email" authorEmail) ?>> return authorEmail return $ flags { author = maybeToFlag authorName' , email = maybeToFlag authorEmail' } -- | Prompt for a homepage URL. getHomepage :: InitFlags -> IO InitFlags getHomepage flags = do hp <- queryHomepage hp' <- return (flagToMaybe $ homepage flags) ?>> maybePrompt flags (promptStr "Project homepage/repo URL" hp) ?>> return hp return $ flags { homepage = maybeToFlag hp' } -- | Right now this does nothing, but it could be changed to do some -- intelligent guessing. queryHomepage :: IO (Maybe String) queryHomepage = return Nothing -- get default remote darcs repo? -- | Prompt for a project synopsis. getSynopsis :: InitFlags -> IO InitFlags getSynopsis flags = do syn <- return (flagToMaybe $ synopsis flags) ?>> maybePrompt flags (promptStr "Project synopsis" Nothing) return $ flags { synopsis = maybeToFlag syn } -- | Prompt for a package category. -- Note that it should be possible to do some smarter guessing here too, i.e. -- look at the name of the top level source directory. getCategory :: InitFlags -> IO InitFlags getCategory flags = do cat <- return (flagToMaybe $ category flags) ?>> fmap join (maybePrompt flags (promptListOptional "Project category" [Codec ..])) return $ flags { category = maybeToFlag cat } -- | Ask whether the project builds a library or executable. getLibOrExec :: InitFlags -> IO InitFlags getLibOrExec flags = do isLib <- return (flagToMaybe $ packageType flags) ?>> maybePrompt flags (either (const Library) id `fmap` (promptList "What does the package build" [Library, Executable] Nothing display False)) ?>> return (Just Library) return $ flags { packageType = maybeToFlag isLib } -- | Ask whether to generate explanitory comments. getGenComments :: InitFlags -> IO InitFlags getGenComments flags = do genComments <- return (flagToMaybe $ noComments flags) ?>> maybePrompt flags (promptYesNo promptMsg (Just False)) ?>> return (Just False) return $ flags { noComments = maybeToFlag (fmap not genComments) } where promptMsg = "Include documentation on what each field means y/n" -- | Try to guess the source root directory (don't prompt the user). getSrcDir :: InitFlags -> IO InitFlags getSrcDir flags = do srcDirs <- return (sourceDirs flags) ?>> guessSourceDirs return $ flags { sourceDirs = srcDirs } -- XXX -- | Try to guess source directories. guessSourceDirs :: IO (Maybe [String]) guessSourceDirs = return Nothing -- | Get the list of exposed modules and extra tools needed to build them. getModulesAndBuildTools :: InitFlags -> IO InitFlags getModulesAndBuildTools flags = do dir <- fromMaybe getCurrentDirectory (fmap return . flagToMaybe $ packageDir flags) -- XXX really should use guessed source roots. sourceFiles <- scanForModules dir mods <- return (exposedModules flags) ?>> (return . Just . map moduleName $ sourceFiles) tools <- return (buildTools flags) ?>> (return . Just . neededBuildPrograms $ sourceFiles) return $ flags { exposedModules = mods , buildTools = tools } --------------------------------------------------------------------------- -- Prompting/user interaction ------------------------------------------- --------------------------------------------------------------------------- -- | Run a prompt or not based on the nonInteractive flag of the -- InitFlags structure. maybePrompt :: InitFlags -> IO t -> IO (Maybe t) maybePrompt flags p = case nonInteractive flags of Flag True -> return Nothing _ -> Just `fmap` p -- | Create a prompt with optional default value that returns a -- String. promptStr :: String -> Maybe String -> IO String promptStr = promptDefault' Just id -- | Create a yes/no prompt with optional default value. -- promptYesNo :: String -> Maybe Bool -> IO Bool promptYesNo = promptDefault' recogniseYesNo showYesNo where recogniseYesNo s | s == "y" || s == "Y" = Just True | s == "n" || s == "N" = Just False | otherwise = Nothing showYesNo True = "y" showYesNo False = "n" -- | Create a prompt with optional default value that returns a value -- of some Text instance. prompt :: Text t => String -> Maybe t -> IO t prompt = promptDefault' (either (const Nothing) Just . runReadE (readP_to_E id parse)) display -- | Create a prompt with an optional default value. promptDefault' :: (String -> Maybe t) -- ^ parser -> (t -> String) -- ^ pretty-printer -> String -- ^ prompt message -> Maybe t -- ^ optional default value -> IO t promptDefault' parser pretty pr def = do putStr $ mkDefPrompt pr (pretty `fmap` def) inp <- getLine case (inp, def) of ("", Just d) -> return d _ -> case parser inp of Just t -> return t Nothing -> do putStrLn $ "Couldn't parse " ++ inp ++ ", please try again!" promptDefault' parser pretty pr def -- | Create a prompt from a prompt string and a String representation -- of an optional default value. mkDefPrompt :: String -> Maybe String -> String mkDefPrompt pr def = pr ++ "?" ++ defStr def where defStr Nothing = " " defStr (Just s) = " [default: " ++ s ++ "] " promptListOptional :: (Text t, Eq t) => String -- ^ prompt -> [t] -- ^ choices -> IO (Maybe (Either String t)) promptListOptional pr choices = fmap rearrange $ promptList pr (Nothing : map Just choices) (Just Nothing) (maybe "(none)" display) True where rearrange = either (Just . Left) (maybe Nothing (Just . Right)) -- | Create a prompt from a list of items. promptList :: Eq t => String -- ^ prompt -> [t] -- ^ choices -> Maybe t -- ^ optional default value -> (t -> String) -- ^ show an item -> Bool -- ^ whether to allow an 'other' option -> IO (Either String t) promptList pr choices def displayItem other = do putStrLn $ pr ++ ":" let options1 = map (\c -> (Just c == def, displayItem c)) choices options2 = zip ([1..]::[Int]) (options1 ++ if other then [(False, "Other (specify)")] else []) mapM_ (putStrLn . \(n,(i,s)) -> showOption n i ++ s) options2 promptList' displayItem (length options2) choices def other where showOption n i | n < 10 = " " ++ star i ++ " " ++ rest | otherwise = " " ++ star i ++ rest where rest = show n ++ ") " star True = "*" star False = " " promptList' :: (t -> String) -> Int -> [t] -> Maybe t -> Bool -> IO (Either String t) promptList' displayItem numChoices choices def other = do putStr $ mkDefPrompt "Your choice" (displayItem `fmap` def) inp <- getLine case (inp, def) of ("", Just d) -> return $ Right d _ -> case readMaybe inp of Nothing -> invalidChoice inp Just n -> getChoice n where invalidChoice inp = do putStrLn $ inp ++ " is not a valid choice." promptList' displayItem numChoices choices def other getChoice n | n < 1 || n > numChoices = invalidChoice (show n) | n < numChoices || (n == numChoices && not other) = return . Right $ choices !! (n-1) | otherwise = Left `fmap` promptStr "Please specify" Nothing readMaybe :: (Read a) => String -> Maybe a readMaybe s = case reads s of [(a,"")] -> Just a _ -> Nothing --------------------------------------------------------------------------- -- File generation ------------------------------------------------------ --------------------------------------------------------------------------- writeLicense :: InitFlags -> IO () writeLicense flags = do message flags "Generating LICENSE..." year <- getYear let licenseFile = case license flags of Flag BSD3 -> Just $ bsd3 (fromMaybe "???" . flagToMaybe . author $ flags) (show year) Flag (GPL (Just (Version {versionBranch = [2]}))) -> Just gplv2 Flag (GPL (Just (Version {versionBranch = [3]}))) -> Just gplv3 Flag (LGPL (Just (Version {versionBranch = [2]}))) -> Just lgpl2 Flag (LGPL (Just (Version {versionBranch = [3]}))) -> Just lgpl3 _ -> Nothing case licenseFile of Just licenseText -> writeFile "LICENSE" licenseText Nothing -> message flags "Warning: unknown license type, you must put a copy in LICENSE yourself." getYear :: IO Integer getYear = do u <- getCurrentTime z <- getCurrentTimeZone let l = utcToLocalTime z u (y, _, _) = toGregorian $ localDay l return y writeSetupFile :: InitFlags -> IO () writeSetupFile flags = do message flags "Generating Setup.hs..." writeFile "Setup.hs" setupFile where setupFile = unlines [ "import Distribution.Simple" , "main = defaultMain" ] writeCabalFile :: InitFlags -> IO Bool writeCabalFile flags@(InitFlags{packageName = NoFlag}) = do message flags "Error: no package name provided." return False writeCabalFile flags@(InitFlags{packageName = Flag p}) = do let cabalFileName = p ++ ".cabal" message flags $ "Generating " ++ cabalFileName ++ "..." writeFile cabalFileName (generateCabalFile cabalFileName flags) return True -- | Generate a .cabal file from an InitFlags structure. NOTE: this -- is rather ad-hoc! What we would REALLY like is to have a -- standard low-level AST type representing .cabal files, which -- preserves things like comments, and to write an *inverse* -- parser/pretty-printer pair between .cabal files and this AST. -- Then instead of this ad-hoc code we could just map an InitFlags -- structure onto a low-level AST structure and use the existing -- pretty-printing code to generate the file. generateCabalFile :: String -> InitFlags -> String generateCabalFile fileName c = renderStyle style { lineLength = 79, ribbonsPerLine = 1.1 } $ (if (minimal c /= Flag True) then showComment (Just $ "Initial " ++ fileName ++ " generated by cabal " ++ "init. For further documentation, see " ++ "http://haskell.org/cabal/users-guide/") $$ text "" else empty) $$ vcat [ fieldS "name" (packageName c) (Just "The name of the package.") True , field "version" (version c) (Just "The package version. See the Haskell package versioning policy (http://www.haskell.org/haskellwiki/Package_versioning_policy) for standards guiding when and how versions should be incremented.") True , fieldS "synopsis" (synopsis c) (Just "A short (one-line) description of the package.") True , fieldS "description" NoFlag (Just "A longer description of the package.") True , fieldS "homepage" (homepage c) (Just "URL for the project homepage or repository.") False , fieldS "bug-reports" NoFlag (Just "A URL where users can report bugs.") False , field "license" (license c) (Just "The license under which the package is released.") True , fieldS "license-file" (Flag "LICENSE") (Just "The file containing the license text.") True , fieldS "author" (author c) (Just "The package author(s).") True , fieldS "maintainer" (email c) (Just "An email address to which users can send suggestions, bug reports, and patches.") True , fieldS "copyright" NoFlag (Just "A copyright notice.") True , fieldS "category" (either id display `fmap` category c) Nothing True , fieldS "build-type" (Flag "Simple") Nothing True , fieldS "extra-source-files" NoFlag (Just "Extra files to be distributed with the package, such as examples or a README.") False , field "cabal-version" (Flag $ orLaterVersion (Version [1,8] [])) (Just "Constraint on the version of Cabal needed to build this package.") False , case packageType c of Flag Executable -> text "\nexecutable" <+> text (fromMaybe "" . flagToMaybe $ packageName c) $$ (nest 2 $ vcat [ fieldS "main-is" NoFlag (Just ".hs or .lhs file containing the Main module.") True , generateBuildInfo Executable c ]) Flag Library -> text "\nlibrary" $$ (nest 2 $ vcat [ fieldS "exposed-modules" (listField (exposedModules c)) (Just "Modules exported by the library.") True , generateBuildInfo Library c ]) _ -> empty ] where generateBuildInfo :: PackageType -> InitFlags -> Doc generateBuildInfo pkgtype c' = vcat [ fieldS "other-modules" (listField (otherModules c')) (Just $ case pkgtype of Library -> "Modules included in this library but not exported." Executable -> "Modules included in this executable, other than Main.") True , fieldS "build-depends" (listField (dependencies c')) (Just "Other library packages from which modules are imported.") True , fieldS "hs-source-dirs" (listFieldS (sourceDirs c')) (Just "Directories containing source files.") False , fieldS "build-tools" (listFieldS (buildTools c')) (Just "Extra tools (e.g. alex, hsc2hs, ...) needed to build the source.") False ] listField :: Text s => Maybe [s] -> Flag String listField = listFieldS . fmap (map display) listFieldS :: Maybe [String] -> Flag String listFieldS = Flag . maybe "" (concat . intersperse ", ") field :: Text t => String -> Flag t -> Maybe String -> Bool -> Doc field s f = fieldS s (fmap display f) fieldS :: String -- ^ Name of the field -> Flag String -- ^ Field contents -> Maybe String -- ^ Comment to explain the field -> Bool -- ^ Should the field be included (commented out) even if blank? -> Doc fieldS _ NoFlag _ inc | not inc || (minimal c == Flag True) = empty fieldS _ (Flag "") _ inc | not inc || (minimal c == Flag True) = empty fieldS s f com _ = case (isJust com, noComments c, minimal c) of (_, _, Flag True) -> id (_, Flag True, _) -> id (True, _, _) -> (showComment com $$) . ($$ text "") (False, _, _) -> ($$ text "") $ comment f <> text s <> colon <> text (take (20 - length s) (repeat ' ')) <> text (fromMaybe "" . flagToMaybe $ f) comment NoFlag = text "-- " comment (Flag "") = text "-- " comment _ = text "" showComment :: Maybe String -> Doc showComment (Just t) = vcat . map text . map ("-- "++) . lines . renderStyle style { lineLength = 76, ribbonsPerLine = 1.05 } . fsep . map text . words $ t showComment Nothing = text "" -- | Generate warnings for missing fields etc. generateWarnings :: InitFlags -> IO () generateWarnings flags = do message flags "" when (synopsis flags `elem` [NoFlag, Flag ""]) (message flags "Warning: no synopsis given. You should edit the .cabal file and add one.") message flags "You may want to edit the .cabal file and add a Description field." -- | Possibly generate a message to stdout, taking into account the -- --quiet flag. message :: InitFlags -> String -> IO () message (InitFlags{quiet = Flag True}) _ = return () message _ s = putStrLn s #if MIN_VERSION_base(3,0,0) #else (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c) f >=> g = \x -> f x >>= g #endif
IreneKnapp/Faction
faction/Distribution/Client/Init.hs
bsd-3-clause
22,401
0
22
6,823
5,325
2,719
2,606
414
13
module Text.Email.Parser.Polymorphic ( addrSpec, -- addrSpec is from this module, the rest are re-exports. localPart, domainPart, EmailAddress, unsafeEmailAddress, toByteString ) where import Text.Email.Parser (localPart, domainPart, EmailAddress(..), unsafeEmailAddress, toByteString) import Text.Domain.Parser.Polymorphic (domainParser,isAsciiAlphaNum) import qualified Data.ByteString.Char8 as BS import Data.ByteString (ByteString) import Text.Parser.Combinators hiding (between) import Text.Parser.Char import Control.Applicative import Control.Monad (void) import Data.List (intercalate) --import Data.Char (isAscii, isAlpha, isDigit) --import Data.List (intercalate) addrSpec :: (Monad m, CharParsing m) => m EmailAddress addrSpec = do l <- local char '@' d <- domain return (unsafeEmailAddress (BS.pack l) (BS.pack d)) local :: (Monad m, CharParsing m) => m String local = dottedAtoms domain :: (Monad m, CharParsing m) => m String domain = domainName <|> domainLiteral domainName :: (Monad m, CharParsing m) => m String domainName = undefined -- TODO: Not sure how to do this part polymorphically. dottedAtoms :: (Monad m, CharParsing m) => m String dottedAtoms = intercalate "." <$> between1 (optional cfws) (atom <|> quotedString) `sepBy1` char '.' atom :: (Monad m, CharParsing m) => m String atom = some (satisfy isAtomText) isAtomText :: Char -> Bool isAtomText x = isAsciiAlphaNum x || x `elem` "!#$%&'*+/=?^_`{|}~-" domainLiteral :: (Monad m, CharParsing m) => m String domainLiteral = do innards <- between (optional cfws *> char '[') (char ']' <* optional cfws) (many (optional fws >> some (satisfy isDomainText)) <* optional fws) return $ concat ["[",concat innards,"]"] isDomainText :: Char -> Bool isDomainText x = x `elem` "\33-\90\94-\126" || isObsNoWsCtl x quotedString :: (Monad m, CharParsing m) => m String quotedString = do innards <- between (char '"') (char '"') (many (optional fws >> quotedContent) <* optional fws) return $ "\"" ++ (concat innards) ++ "\"" quotedContent :: (Monad m, CharParsing m) => m String quotedContent = some (satisfy isQuotedText) <|> quotedPair isQuotedText :: Char -> Bool isQuotedText x = x `elem` "\33\35-\91\93-\126" || isObsNoWsCtl x quotedPair :: (Monad m, CharParsing m) => m String quotedPair = (\ c -> ['\\',c]) <$> (char '\\' *> (vchar <|> wsp <|> lf <|> cr <|> obsNoWsCtl <|> nullChar)) cfws :: (Monad m, CharParsing m) => m () cfws = skipMany (comment <|> fws) fws :: (Monad m, CharParsing m) => m () fws = void (wsp1 >> optional (crlf >> wsp1)) <|> (skipSome (crlf >> wsp1)) between :: Applicative f => f l -> f r -> f a -> f a between l r x = l *> x <* r between1 :: Applicative f => f lr -> f a -> f a between1 lr x = lr *> x <* lr comment :: (Monad m, CharParsing m) => m () comment = between (char '(') (char ')') $ skipMany (void commentContent <|> fws) commentContent :: (Monad m, CharParsing m) => m () commentContent = skipSome (satisfy isCommentText) <|> void quotedPair <|> comment isCommentText :: Char -> Bool isCommentText x = x `elem` "\33-\39\42-\91\93-\126" || isObsNoWsCtl x nullChar :: (CharParsing m) => m Char nullChar = char '\0' wsp1 :: (CharParsing m) => m () wsp1 = skipSome (satisfy isWsp) wsp :: (CharParsing m) => m Char wsp = satisfy isWsp isWsp :: Char -> Bool isWsp x = x == ' ' || x == '\t' cr :: (CharParsing m) => m Char cr = char '\r' lf :: (CharParsing m) => m Char lf = char '\n' crlf :: (Monad m, CharParsing m) => m () crlf = void $ cr >> lf isVchar :: Char -> Bool isVchar c = c `elem` "\x21-\x7e" vchar :: (CharParsing m) => m Char vchar = satisfy isVchar isObsNoWsCtl :: Char -> Bool isObsNoWsCtl c = c `elem` "\1-\8\11-\12\14-\31\127" obsNoWsCtl :: (CharParsing m) => m Char obsNoWsCtl = satisfy isObsNoWsCtl
bitemyapp/email-validate-hs
src/Text/Email/Parser/Polymorphic.hs
bsd-3-clause
3,833
0
16
719
1,481
778
703
88
1
{-# LANGUAGE OverloadedStrings #-} module NLP.Romkan.Internal ( romKanAList , romKanAList_H , kanRomAList , kanRomAList_H , kunreiToHepburnAList , hepburnToKunreiAList ) where import Data.Text (Text) romKanAList :: [(Text, Text)] romKanAList = [ ("bbya", "ッビャ") ,("bbyo", "ッビョ") ,("bbyu", "ッビュ") ,("ccha", "ッチャ") ,("cche", "ッチェ") ,("cchi", "ッチ") ,("ccho", "ッチョ") ,("cchu", "ッチュ") ,("ddya", "ッヂャ") ,("ddyo", "ッヂョ") ,("ddyu", "ッヂュ") ,("ggya", "ッギャ") ,("ggyo", "ッギョ") ,("ggyu", "ッギュ") ,("hhya", "ッヒャ") ,("hhyo", "ッヒョ") ,("hhyu", "ッヒュ") ,("kkya", "ッキャ") ,("kkyo", "ッキョ") ,("kkyu", "ッキュ") ,("ppya", "ッピャ") ,("ppyo", "ッピョ") ,("ppyu", "ッピュ") ,("rrya", "ッリャ") ,("rryo", "ッリョ") ,("rryu", "ッリュ") ,("ssha", "ッシャ") ,("sshe", "ッシェ") ,("sshi", "ッシ") ,("ssho", "ッショ") ,("sshu", "ッシュ") ,("ssya", "ッシャ") ,("ssye", "ッシェ") ,("ssyo", "ッショ") ,("ssyu", "ッシュ") ,("ttsu", "ッツ") ,("ttya", "ッチャ") ,("ttye", "ッチェ") ,("ttyo", "ッチョ") ,("ttyu", "ッチュ") ,("xtsu", "ッ") ,("zzya", "ッジャ") ,("zzyo", "ッジョ") ,("zzyu", "ッジュ") ,("bba", "ッバ") ,("bbe", "ッベ") ,("bbi", "ッビ") ,("bbo", "ッボ") ,("bbu", "ッブ") ,("bya", "ビャ") ,("byo", "ビョ") ,("byu", "ビュ") ,("cha", "チャ") ,("che", "チェ") ,("chi", "チ") ,("cho", "チョ") ,("chu", "チュ") ,("dda", "ッダ") ,("dde", "ッデ") ,("ddi", "ッヂ") ,("ddo", "ッド") ,("ddu", "ッドゥ") ,("dya", "ヂャ") ,("dyi", "ディ") ,("dyo", "ヂョ") ,("dyu", "ヂュ") ,("ffa", "ッファ") ,("ffe", "ッフェ") ,("ffi", "ッフィ") ,("ffo", "ッフォ") ,("ffu", "ッフュ") ,("gga", "ッガ") ,("gge", "ッゲ") ,("ggi", "ッギ") ,("ggo", "ッゴ") ,("ggu", "ッグ") ,("gya", "ギャ") ,("gyo", "ギョ") ,("gyu", "ギュ") ,("hha", "ッハ") ,("hhe", "ッヘ") ,("hhi", "ッヒ") ,("hho", "ッホ") ,("hhu", "ッフ") ,("hya", "ヒャ") ,("hyo", "ヒョ") ,("hyu", "ヒュ") ,("jja", "ッジャ") ,("jji", "ッジ") ,("jjo", "ッジョ") ,("jju", "ッジュ") ,("kka", "ッカ") ,("kke", "ッケ") ,("kki", "ッキ") ,("kko", "ッコ") ,("kku", "ック") ,("kya", "キャ") ,("kyo", "キョ") ,("kyu", "キュ") ,("mya", "ミャ") ,("myo", "ミョ") ,("myu", "ミュ") ,("nya", "ニャ") ,("nyo", "ニョ") ,("nyu", "ニュ") ,("ppa", "ッパ") ,("ppe", "ッペ") ,("ppi", "ッピ") ,("ppo", "ッポ") ,("ppu", "ップ") ,("pya", "ピャ") ,("pyo", "ピョ") ,("pyu", "ピュ") ,("rra", "ッラ") ,("rre", "ッレ") ,("rri", "ッリ") ,("rro", "ッロ") ,("rru", "ッル") ,("rya", "リャ") ,("ryo", "リョ") ,("ryu", "リュ") ,("sha", "シャ") ,("she", "シェ") ,("shi", "シ") ,("sho", "ショ") ,("shu", "シュ") ,("ssa", "ッサ") ,("sse", "ッセ") ,("ssi", "ッシ") ,("sso", "ッソ") ,("ssu", "ッス") ,("sya", "シャ") ,("sye", "シェ") ,("syo", "ショ") ,("syu", "シュ") ,("tsu", "ツ") ,("tta", "ッタ") ,("tte", "ッテ") ,("tti", "ッティ") ,("tto", "ット") ,("ttu", "ッツ") ,("tya", "チャ") ,("tye", "チェ") ,("tyo", "チョ") ,("tyu", "チュ") ,("vva", "ッヴァ") ,("vve", "ッヴェ") ,("vvi", "ッヴィ") ,("vvo", "ッヴォ") ,("vvu", "ッヴ") ,("xtu", "ッ") ,("xwa", "ヮ") ,("xya", "ャ") ,("xyo", "ョ") ,("xyu", "ュ") ,("yya", "ッヤ") ,("yyo", "ッヨ") ,("yyu", "ッユ") ,("zya", "ジャ") ,("zye", "ジェ") ,("zyo", "ジョ") ,("zyu", "ジュ") ,("zza", "ッザ") ,("zze", "ッゼ") ,("zzi", "ッジ") ,("zzo", "ッゾ") ,("zzu", "ッズ") ,("ba", "バ") ,("be", "ベ") ,("bi", "ビ") ,("bo", "ボ") ,("bu", "ブ") ,("da", "ダ") ,("de", "デ") ,("di", "ヂ") ,("do", "ド") ,("du", "ヅ") ,("fa", "ファ") ,("fe", "フェ") ,("fi", "フィ") ,("fo", "フォ") ,("fu", "フ") ,("ga", "ガ") ,("ge", "ゲ") ,("gi", "ギ") ,("go", "ゴ") ,("gu", "グ") ,("ha", "ハ") ,("he", "ヘ") ,("hi", "ヒ") ,("ho", "ホ") ,("hu", "フ") ,("ja", "ジャ") ,("je", "ジェ") ,("ji", "ジ") ,("jo", "ジョ") ,("ju", "ジュ") ,("ka", "カ") ,("ke", "ケ") ,("ki", "キ") ,("ko", "コ") ,("ku", "ク") ,("ma", "マ") ,("me", "メ") ,("mi", "ミ") ,("mo", "モ") ,("mu", "ム") ,("n'", "ン") ,("na", "ナ") ,("ne", "ネ") ,("ni", "ニ") ,("no", "ノ") ,("nu", "ヌ") ,("pa", "パ") ,("pe", "ペ") ,("pi", "ピ") ,("po", "ポ") ,("pu", "プ") ,("ra", "ラ") ,("re", "レ") ,("ri", "リ") ,("ro", "ロ") ,("ru", "ル") ,("sa", "サ") ,("se", "セ") ,("si", "シ") ,("so", "ソ") ,("su", "ス") ,("ta", "タ") ,("te", "テ") ,("ti", "チ") ,("to", "ト") ,("tu", "ツ") ,("va", "ヴァ") ,("ve", "ヴェ") ,("vi", "ヴィ") ,("vo", "ヴォ") ,("vu", "ヴ") ,("wa", "ワ") ,("we", "ウェ") ,("wi", "ウィ") ,("wo", "ヲ") ,("xa", "ァ") ,("xe", "ェ") ,("xi", "ィ") ,("xo", "ォ") ,("xu", "ゥ") ,("ya", "ヤ") ,("yo", "ヨ") ,("yu", "ユ") ,("za", "ザ") ,("ze", "ゼ") ,("zi", "ジ") ,("zo", "ゾ") ,("zu", "ズ") ,("-", "ー") ,("a", "ア") ,("e", "エ") ,("i", "イ") ,("n", "ン") ,("o", "オ") ,("u", "ウ") ] romKanAList_H :: [(Text, Text)] romKanAList_H = [ ("bbya", "っびゃ") ,("bbyo", "っびょ") ,("bbyu", "っびゅ") ,("ccha", "っちゃ") ,("cche", "っちぇ") ,("cchi", "っち") ,("ccho", "っちょ") ,("cchu", "っちゅ") ,("ddya", "っぢゃ") ,("ddyo", "っぢょ") ,("ddyu", "っぢゅ") ,("ggya", "っぎゃ") ,("ggyo", "っぎょ") ,("ggyu", "っぎゅ") ,("hhya", "っひゃ") ,("hhyo", "っひょ") ,("hhyu", "っひゅ") ,("kkya", "っきゃ") ,("kkyo", "っきょ") ,("kkyu", "っきゅ") ,("ppya", "っぴゃ") ,("ppyo", "っぴょ") ,("ppyu", "っぴゅ") ,("rrya", "っりゃ") ,("rryo", "っりょ") ,("rryu", "っりゅ") ,("ssha", "っしゃ") ,("sshi", "っし") ,("ssho", "っしょ") ,("sshu", "っしゅ") ,("ssya", "っしゃ") ,("ssyo", "っしょ") ,("ssyu", "っしゅ") ,("ttsu", "っつ") ,("ttya", "っちゃ") ,("ttye", "っちぇ") ,("ttyo", "っちょ") ,("ttyu", "っちゅ") ,("xtsu", "っ") ,("zzya", "っじゃ") ,("zzyo", "っじょ") ,("zzyu", "っじゅ") ,("bba", "っば") ,("bbe", "っべ") ,("bbi", "っび") ,("bbo", "っぼ") ,("bbu", "っぶ") ,("bya", "びゃ") ,("byo", "びょ") ,("byu", "びゅ") ,("cha", "ちゃ") ,("che", "ちぇ") ,("chi", "ち") ,("cho", "ちょ") ,("chu", "ちゅ") ,("dda", "っだ") ,("dde", "っで") ,("ddi", "っぢ") ,("ddo", "っど") ,("ddu", "っづ") ,("dya", "ぢゃ") ,("dyi", "でぃ") ,("dyo", "ぢょ") ,("dyu", "ぢゅ") ,("ffa", "っふぁ") ,("ffe", "っふぇ") ,("ffi", "っふぃ") ,("ffo", "っふぉ") ,("ffu", "っふ") ,("gga", "っが") ,("gge", "っげ") ,("ggi", "っぎ") ,("ggo", "っご") ,("ggu", "っぐ") ,("gya", "ぎゃ") ,("gyo", "ぎょ") ,("gyu", "ぎゅ") ,("hha", "っは") ,("hhe", "っへ") ,("hhi", "っひ") ,("hho", "っほ") ,("hhu", "っふ") ,("hya", "ひゃ") ,("hyo", "ひょ") ,("hyu", "ひゅ") ,("jja", "っじゃ") ,("jji", "っじ") ,("jjo", "っじょ") ,("jju", "っじゅ") ,("kka", "っか") ,("kke", "っけ") ,("kki", "っき") ,("kko", "っこ") ,("kku", "っく") ,("kya", "きゃ") ,("kyo", "きょ") ,("kyu", "きゅ") ,("mya", "みゃ") ,("myo", "みょ") ,("myu", "みゅ") ,("nya", "にゃ") ,("nyo", "にょ") ,("nyu", "にゅ") ,("ppa", "っぱ") ,("ppe", "っぺ") ,("ppi", "っぴ") ,("ppo", "っぽ") ,("ppu", "っぷ") ,("pya", "ぴゃ") ,("pyo", "ぴょ") ,("pyu", "ぴゅ") ,("rra", "っら") ,("rre", "っれ") ,("rri", "っり") ,("rro", "っろ") ,("rru", "っる") ,("rya", "りゃ") ,("ryo", "りょ") ,("ryu", "りゅ") ,("sha", "しゃ") ,("shi", "し") ,("sho", "しょ") ,("shu", "しゅ") ,("ssa", "っさ") ,("sse", "っせ") ,("ssi", "っし") ,("sso", "っそ") ,("ssu", "っす") ,("sya", "しゃ") ,("syo", "しょ") ,("syu", "しゅ") ,("tsu", "つ") ,("tta", "った") ,("tte", "って") ,("tti", "っち") ,("tto", "っと") ,("ttu", "っつ") ,("tya", "ちゃ") ,("tye", "ちぇ") ,("tyo", "ちょ") ,("tyu", "ちゅ") ,("vva", "っう゛ぁ") ,("vve", "っう゛ぇ") ,("vvi", "っう゛ぃ") ,("vvo", "っう゛ぉ") ,("vvu", "っう゛") ,("xtu", "っ") ,("xwa", "ゎ") ,("xya", "ゃ") ,("xyo", "ょ") ,("xyu", "ゅ") ,("yya", "っや") ,("yyo", "っよ") ,("yyu", "っゆ") ,("zya", "じゃ") ,("zye", "じぇ") ,("zyo", "じょ") ,("zyu", "じゅ") ,("zza", "っざ") ,("zze", "っぜ") ,("zzi", "っじ") ,("zzo", "っぞ") ,("zzu", "っず") ,("ba", "ば") ,("be", "べ") ,("bi", "び") ,("bo", "ぼ") ,("bu", "ぶ") ,("da", "だ") ,("de", "で") ,("di", "ぢ") ,("do", "ど") ,("du", "づ") ,("fa", "ふぁ") ,("fe", "ふぇ") ,("fi", "ふぃ") ,("fo", "ふぉ") ,("fu", "ふ") ,("ga", "が") ,("ge", "げ") ,("gi", "ぎ") ,("go", "ご") ,("gu", "ぐ") ,("ha", "は") ,("he", "へ") ,("hi", "ひ") ,("ho", "ほ") ,("hu", "ふ") ,("ja", "じゃ") ,("je", "じぇ") ,("ji", "じ") ,("jo", "じょ") ,("ju", "じゅ") ,("ka", "か") ,("ke", "け") ,("ki", "き") ,("ko", "こ") ,("ku", "く") ,("ma", "ま") ,("me", "め") ,("mi", "み") ,("mo", "も") ,("mu", "む") ,("n'", "ん") ,("na", "な") ,("ne", "ね") ,("ni", "に") ,("no", "の") ,("nu", "ぬ") ,("pa", "ぱ") ,("pe", "ぺ") ,("pi", "ぴ") ,("po", "ぽ") ,("pu", "ぷ") ,("ra", "ら") ,("re", "れ") ,("ri", "り") ,("ro", "ろ") ,("ru", "る") ,("sa", "さ") ,("se", "せ") ,("si", "し") ,("so", "そ") ,("su", "す") ,("ta", "た") ,("te", "て") ,("ti", "ち") ,("to", "と") ,("tu", "つ") ,("va", "う゛ぁ") ,("ve", "う゛ぇ") ,("vi", "う゛ぃ") ,("vo", "う゛ぉ") ,("vu", "う゛") ,("wa", "わ") ,("we", "うぇ") ,("wi", "うぃ") ,("wo", "を") ,("xa", "ぁ") ,("xe", "ぇ") ,("xi", "ぃ") ,("xo", "ぉ") ,("xu", "ぅ") ,("ya", "や") ,("yo", "よ") ,("yu", "ゆ") ,("za", "ざ") ,("ze", "ぜ") ,("zi", "じ") ,("zo", "ぞ") ,("zu", "ず") ,("-", "ー") ,("a", "あ") ,("e", "え") ,("i", "い") ,("n", "ん") ,("o", "お") ,("u", "う") ] kanRomAList :: [(Text, Text)] kanRomAList = [ ("ッジャ", "jja") ,("ッジュ", "jju") ,("ッジョ", "jjo") ,("ッティ", "tti") ,("ッドゥ", "ddu") ,("ッファ", "ffa") ,("ッフィ", "ffi") ,("ッフェ", "ffe") ,("ッフォ", "ffo") ,("ッフュ", "ffu") ,("ッヴァ", "vva") ,("ッヴィ", "vvi") ,("ッヴェ", "vve") ,("ッヴォ", "vvo") ,("ッキャ", "kkya") ,("ッキュ", "kkyu") ,("ッキョ", "kkyo") ,("ッギャ", "ggya") ,("ッギュ", "ggyu") ,("ッギョ", "ggyo") ,("ッシェ", "sshe") ,("ッシャ", "ssha") ,("ッシュ", "sshu") ,("ッショ", "ssho") ,("ッチェ", "cche") ,("ッチャ", "ccha") ,("ッチュ", "cchu") ,("ッチョ", "ccho") ,("ッヂャ", "ddya") ,("ッヂュ", "ddyu") ,("ッヂョ", "ddyo") ,("ッヒャ", "hhya") ,("ッヒュ", "hhyu") ,("ッヒョ", "hhyo") ,("ッビャ", "bbya") ,("ッビュ", "bbyu") ,("ッビョ", "bbyo") ,("ッピャ", "ppya") ,("ッピュ", "ppyu") ,("ッピョ", "ppyo") ,("ッリャ", "rrya") ,("ッリュ", "rryu") ,("ッリョ", "rryo") ,("ウィ", "wi") ,("ウェ", "we") ,("ウォ", "wo") ,("ジェ", "je") ,("ジャ", "ja") ,("ジュ", "ju") ,("ジョ", "jo") ,("ティ", "ti") ,("ディ", "di") ,("ドゥ", "du") ,("ファ", "fa") ,("フィ", "fi") ,("フェ", "fe") ,("フォ", "fo") ,("フュ", "fu") ,("ヴァ", "va") ,("ヴィ", "vi") ,("ヴェ", "ve") ,("ヴォ", "vo") ,("キャ", "kya") ,("キュ", "kyu") ,("キョ", "kyo") ,("ギャ", "gya") ,("ギュ", "gyu") ,("ギョ", "gyo") ,("シェ", "she") ,("シャ", "sha") ,("シュ", "shu") ,("ショ", "sho") ,("チェ", "che") ,("チャ", "cha") ,("チュ", "chu") ,("チョ", "cho") ,("ヂャ", "dya") ,("ヂュ", "dyu") ,("ヂョ", "dyo") ,("ッカ", "kka") ,("ッガ", "gga") ,("ッキ", "kki") ,("ッギ", "ggi") ,("ック", "kku") ,("ッグ", "ggu") ,("ッケ", "kke") ,("ッゲ", "gge") ,("ッコ", "kko") ,("ッゴ", "ggo") ,("ッサ", "ssa") ,("ッザ", "zza") ,("ッジ", "jji") ,("ッス", "ssu") ,("ッズ", "zzu") ,("ッセ", "sse") ,("ッゼ", "zze") ,("ッソ", "sso") ,("ッゾ", "zzo") ,("ッタ", "tta") ,("ッダ", "dda") ,("ッヂ", "ddi") ,("ッヅ", "ddu") ,("ッテ", "tte") ,("ッデ", "dde") ,("ット", "tto") ,("ッド", "ddo") ,("ッハ", "hha") ,("ッバ", "bba") ,("ッパ", "ppa") ,("ッヒ", "hhi") ,("ッビ", "bbi") ,("ッピ", "ppi") ,("ッフ", "ffu") ,("ッブ", "bbu") ,("ップ", "ppu") ,("ッヘ", "hhe") ,("ッベ", "bbe") ,("ッペ", "ppe") ,("ッホ", "hho") ,("ッボ", "bbo") ,("ッポ", "ppo") ,("ッヤ", "yya") ,("ッユ", "yyu") ,("ッヨ", "yyo") ,("ッラ", "rra") ,("ッリ", "rri") ,("ッル", "rru") ,("ッレ", "rre") ,("ッロ", "rro") ,("ッヴ", "vvu") ,("ニャ", "nya") ,("ニュ", "nyu") ,("ニョ", "nyo") ,("ヒャ", "hya") ,("ヒュ", "hyu") ,("ヒョ", "hyo") ,("ビャ", "bya") ,("ビュ", "byu") ,("ビョ", "byo") ,("ピャ", "pya") ,("ピュ", "pyu") ,("ピョ", "pyo") ,("ミャ", "mya") ,("ミュ", "myu") ,("ミョ", "myo") ,("リャ", "rya") ,("リュ", "ryu") ,("リョ", "ryo") ,("ッシ", "sshi") ,("ッチ", "cchi") ,("ッツ", "ttsu") ,("ア", "a") ,("イ", "i") ,("ウ", "u") ,("エ", "e") ,("オ", "o") ,("ー", "-") ,("ァ", "xa") ,("ィ", "xi") ,("ゥ", "xu") ,("ェ", "xe") ,("ォ", "xo") ,("カ", "ka") ,("ガ", "ga") ,("キ", "ki") ,("ギ", "gi") ,("ク", "ku") ,("グ", "gu") ,("ケ", "ke") ,("ゲ", "ge") ,("コ", "ko") ,("ゴ", "go") ,("サ", "sa") ,("ザ", "za") ,("ジ", "ji") ,("ス", "su") ,("ズ", "zu") ,("セ", "se") ,("ゼ", "ze") ,("ソ", "so") ,("ゾ", "zo") ,("タ", "ta") ,("ダ", "da") ,("ヂ", "di") ,("ヅ", "du") ,("テ", "te") ,("デ", "de") ,("ト", "to") ,("ド", "do") ,("ナ", "na") ,("ニ", "ni") ,("ヌ", "nu") ,("ネ", "ne") ,("ノ", "no") ,("ハ", "ha") ,("バ", "ba") ,("パ", "pa") ,("ヒ", "hi") ,("ビ", "bi") ,("ピ", "pi") ,("フ", "fu") ,("ブ", "bu") ,("プ", "pu") ,("ヘ", "he") ,("ベ", "be") ,("ペ", "pe") ,("ホ", "ho") ,("ボ", "bo") ,("ポ", "po") ,("マ", "ma") ,("ミ", "mi") ,("ム", "mu") ,("メ", "me") ,("モ", "mo") ,("ヤ", "ya") ,("ユ", "yu") ,("ヨ", "yo") ,("ラ", "ra") ,("リ", "ri") ,("ル", "ru") ,("レ", "re") ,("ロ", "ro") ,("ワ", "wa") ,("ヰ", "wi") ,("ヱ", "we") ,("ヲ", "wo") ,("ン", "n'") ,("ヴ", "vu") ,("シ", "shi") ,("チ", "chi") ,("ツ", "tsu") ,("ャ", "xya") ,("ュ", "xyu") ,("ョ", "xyo") ,("ヮ", "xwa") ,("ッ", "xtsu") ] kanRomAList_H :: [(Text, Text)] kanRomAList_H = [ ("っう゛ぁ", "vva") ,("っう゛ぃ", "vvi") ,("っう゛ぇ", "vve") ,("っう゛ぉ", "vvo") ,("う゛ぁ", "va") ,("う゛ぃ", "vi") ,("う゛ぇ", "ve") ,("う゛ぉ", "vo") ,("っう゛", "vvu") ,("っじゃ", "jja") ,("っじゅ", "jju") ,("っじょ", "jjo") ,("っふぁ", "ffa") ,("っふぃ", "ffi") ,("っふぇ", "ffe") ,("っふぉ", "ffo") ,("っきゃ", "kkya") ,("っきゅ", "kkyu") ,("っきょ", "kkyo") ,("っぎゃ", "ggya") ,("っぎゅ", "ggyu") ,("っぎょ", "ggyo") ,("っしゃ", "ssha") ,("っしゅ", "sshu") ,("っしょ", "ssho") ,("っちぇ", "cche") ,("っちゃ", "ccha") ,("っちゅ", "cchu") ,("っちょ", "ccho") ,("っぢゃ", "ddya") ,("っぢゅ", "ddyu") ,("っぢょ", "ddyo") ,("っひゃ", "hhya") ,("っひゅ", "hhyu") ,("っひょ", "hhyo") ,("っびゃ", "bbya") ,("っびゅ", "bbyu") ,("っびょ", "bbyo") ,("っぴゃ", "ppya") ,("っぴゅ", "ppyu") ,("っぴょ", "ppyo") ,("っりゃ", "rrya") ,("っりゅ", "rryu") ,("っりょ", "rryo") ,("う゛", "vu") ,("じぇ", "je") ,("じゃ", "ja") ,("じゅ", "ju") ,("じょ", "jo") ,("ふぁ", "fa") ,("ふぃ", "fi") ,("ふぇ", "fe") ,("ふぉ", "fo") ,("きゃ", "kya") ,("きゅ", "kyu") ,("きょ", "kyo") ,("ぎゃ", "gya") ,("ぎゅ", "gyu") ,("ぎょ", "gyo") ,("しゃ", "sha") ,("しゅ", "shu") ,("しょ", "sho") ,("ちぇ", "che") ,("ちゃ", "cha") ,("ちゅ", "chu") ,("ちょ", "cho") ,("ぢゃ", "dya") ,("ぢゅ", "dyu") ,("ぢょ", "dyo") ,("っか", "kka") ,("っが", "gga") ,("っき", "kki") ,("っぎ", "ggi") ,("っく", "kku") ,("っぐ", "ggu") ,("っけ", "kke") ,("っげ", "gge") ,("っこ", "kko") ,("っご", "ggo") ,("っさ", "ssa") ,("っざ", "zza") ,("っじ", "jji") ,("っす", "ssu") ,("っず", "zzu") ,("っせ", "sse") ,("っぜ", "zze") ,("っそ", "sso") ,("っぞ", "zzo") ,("った", "tta") ,("っだ", "dda") ,("っぢ", "ddi") ,("っづ", "ddu") ,("って", "tte") ,("っで", "dde") ,("っと", "tto") ,("っど", "ddo") ,("っは", "hha") ,("っば", "bba") ,("っぱ", "ppa") ,("っひ", "hhi") ,("っび", "bbi") ,("っぴ", "ppi") ,("っふ", "ffu") ,("っぶ", "bbu") ,("っぷ", "ppu") ,("っへ", "hhe") ,("っべ", "bbe") ,("っぺ", "ppe") ,("っほ", "hho") ,("っぼ", "bbo") ,("っぽ", "ppo") ,("っや", "yya") ,("っゆ", "yyu") ,("っよ", "yyo") ,("っら", "rra") ,("っり", "rri") ,("っる", "rru") ,("っれ", "rre") ,("っろ", "rro") ,("でぃ", "dyi") ,("にゃ", "nya") ,("にゅ", "nyu") ,("にょ", "nyo") ,("ひゃ", "hya") ,("ひゅ", "hyu") ,("ひょ", "hyo") ,("びゃ", "bya") ,("びゅ", "byu") ,("びょ", "byo") ,("ぴゃ", "pya") ,("ぴゅ", "pyu") ,("ぴょ", "pyo") ,("みゃ", "mya") ,("みゅ", "myu") ,("みょ", "myo") ,("りゃ", "rya") ,("りゅ", "ryu") ,("りょ", "ryo") ,("っし", "sshi") ,("っち", "cchi") ,("っつ", "ttsu") ,("あ", "a") ,("い", "i") ,("う", "u") ,("え", "e") ,("お", "o") ,("ー", "-") ,("ぁ", "xa") ,("ぃ", "xi") ,("ぅ", "xu") ,("ぇ", "xe") ,("ぉ", "xo") ,("か", "ka") ,("が", "ga") ,("き", "ki") ,("ぎ", "gi") ,("く", "ku") ,("ぐ", "gu") ,("け", "ke") ,("げ", "ge") ,("こ", "ko") ,("ご", "go") ,("さ", "sa") ,("ざ", "za") ,("じ", "ji") ,("す", "su") ,("ず", "zu") ,("せ", "se") ,("ぜ", "ze") ,("そ", "so") ,("ぞ", "zo") ,("た", "ta") ,("だ", "da") ,("ぢ", "di") ,("づ", "du") ,("て", "te") ,("で", "de") ,("と", "to") ,("ど", "do") ,("な", "na") ,("に", "ni") ,("ぬ", "nu") ,("ね", "ne") ,("の", "no") ,("は", "ha") ,("ば", "ba") ,("ぱ", "pa") ,("ひ", "hi") ,("び", "bi") ,("ぴ", "pi") ,("ふ", "fu") ,("ぶ", "bu") ,("ぷ", "pu") ,("へ", "he") ,("べ", "be") ,("ぺ", "pe") ,("ほ", "ho") ,("ぼ", "bo") ,("ぽ", "po") ,("ま", "ma") ,("み", "mi") ,("む", "mu") ,("め", "me") ,("も", "mo") ,("や", "ya") ,("ゆ", "yu") ,("よ", "yo") ,("ら", "ra") ,("り", "ri") ,("る", "ru") ,("れ", "re") ,("ろ", "ro") ,("わ", "wa") ,("ゐ", "wi") ,("ゑ", "we") ,("を", "wo") ,("ん", "n'") ,("し", "shi") ,("ち", "chi") ,("つ", "tsu") ,("ゃ", "xya") ,("ゅ", "xyu") ,("ょ", "xyo") ,("ゎ", "xwa") ,("っ", "xtsu") ] kunreiToHepburnAList :: [(Text, Text)] kunreiToHepburnAList = [ ("bbya", "bbya") ,("bbyo", "bbyo") ,("bbyu", "bbyu") ,("ddya", "ddya") ,("ddyo", "ddyo") ,("ddyu", "ddyu") ,("ggya", "ggya") ,("ggyo", "ggyo") ,("ggyu", "ggyu") ,("hhya", "hhya") ,("hhyo", "hhyo") ,("hhyu", "hhyu") ,("kkya", "kkya") ,("kkyo", "kkyo") ,("kkyu", "kkyu") ,("ppya", "ppya") ,("ppyo", "ppyo") ,("ppyu", "ppyu") ,("rrya", "rrya") ,("rryo", "rryo") ,("rryu", "rryu") ,("ssya", "ssha") ,("ssye", "sshe") ,("ssyo", "ssho") ,("ssyu", "sshu") ,("ttya", "ccha") ,("ttye", "cche") ,("ttyo", "ccho") ,("ttyu", "cchu") ,("zzya", "jja") ,("zzyo", "jjo") ,("zzyu", "jju") ,("bba", "bba") ,("bbe", "bbe") ,("bbi", "bbi") ,("bbo", "bbo") ,("bbu", "bbu") ,("bya", "bya") ,("byo", "byo") ,("byu", "byu") ,("dda", "dda") ,("dde", "dde") ,("ddi", "ddi") ,("ddo", "ddo") ,("ddu", "ddu") ,("dya", "dya") ,("dyi", "di") ,("dyo", "dyo") ,("dyu", "dyu") ,("ffa", "ffa") ,("ffe", "ffe") ,("ffi", "ffi") ,("ffo", "ffo") ,("ffu", "ffu") ,("gga", "gga") ,("gge", "gge") ,("ggi", "ggi") ,("ggo", "ggo") ,("ggu", "ggu") ,("gya", "gya") ,("gyo", "gyo") ,("gyu", "gyu") ,("hha", "hha") ,("hhe", "hhe") ,("hhi", "hhi") ,("hho", "hho") ,("hhu", "ffu") ,("hya", "hya") ,("hyo", "hyo") ,("hyu", "hyu") ,("kka", "kka") ,("kke", "kke") ,("kki", "kki") ,("kko", "kko") ,("kku", "kku") ,("kya", "kya") ,("kyo", "kyo") ,("kyu", "kyu") ,("mya", "mya") ,("myo", "myo") ,("myu", "myu") ,("nya", "nya") ,("nyo", "nyo") ,("nyu", "nyu") ,("ppa", "ppa") ,("ppe", "ppe") ,("ppi", "ppi") ,("ppo", "ppo") ,("ppu", "ppu") ,("pya", "pya") ,("pyo", "pyo") ,("pyu", "pyu") ,("rra", "rra") ,("rre", "rre") ,("rri", "rri") ,("rro", "rro") ,("rru", "rru") ,("rya", "rya") ,("ryo", "ryo") ,("ryu", "ryu") ,("ssa", "ssa") ,("sse", "sse") ,("ssi", "sshi") ,("sso", "sso") ,("ssu", "ssu") ,("sya", "sha") ,("sye", "she") ,("syo", "sho") ,("syu", "shu") ,("tta", "tta") ,("tte", "tte") ,("tti", "tti") ,("tto", "tto") ,("ttu", "ttsu") ,("tya", "cha") ,("tye", "che") ,("tyo", "cho") ,("tyu", "chu") ,("vva", "vva") ,("vve", "vve") ,("vvi", "vvi") ,("vvo", "vvo") ,("vvu", "vvu") ,("xtu", "xtsu") ,("xwa", "xwa") ,("xya", "xya") ,("xyo", "xyo") ,("xyu", "xyu") ,("yya", "yya") ,("yyo", "yyo") ,("yyu", "yyu") ,("zya", "ja") ,("zye", "je") ,("zyo", "jo") ,("zyu", "ju") ,("zza", "zza") ,("zze", "zze") ,("zzi", "jji") ,("zzo", "zzo") ,("zzu", "zzu") ,("ba", "ba") ,("be", "be") ,("bi", "bi") ,("bo", "bo") ,("bu", "bu") ,("da", "da") ,("de", "de") ,("di", "di") ,("do", "do") ,("du", "du") ,("fa", "fa") ,("fe", "fe") ,("fi", "fi") ,("fo", "fo") ,("fu", "fu") ,("ga", "ga") ,("ge", "ge") ,("gi", "gi") ,("go", "go") ,("gu", "gu") ,("ha", "ha") ,("he", "he") ,("hi", "hi") ,("ho", "ho") ,("hu", "fu") ,("ka", "ka") ,("ke", "ke") ,("ki", "ki") ,("ko", "ko") ,("ku", "ku") ,("ma", "ma") ,("me", "me") ,("mi", "mi") ,("mo", "mo") ,("mu", "mu") ,("n'", "n'") ,("na", "na") ,("ne", "ne") ,("ni", "ni") ,("no", "no") ,("nu", "nu") ,("pa", "pa") ,("pe", "pe") ,("pi", "pi") ,("po", "po") ,("pu", "pu") ,("ra", "ra") ,("re", "re") ,("ri", "ri") ,("ro", "ro") ,("ru", "ru") ,("sa", "sa") ,("se", "se") ,("si", "shi") ,("so", "so") ,("su", "su") ,("ta", "ta") ,("te", "te") ,("ti", "chi") ,("to", "to") ,("tu", "tsu") ,("va", "va") ,("ve", "ve") ,("vi", "vi") ,("vo", "vo") ,("vu", "vu") ,("wa", "wa") ,("we", "we") ,("wi", "wi") ,("wo", "wo") ,("xa", "xa") ,("xe", "xe") ,("xi", "xi") ,("xo", "xo") ,("xu", "xu") ,("ya", "ya") ,("yo", "yo") ,("yu", "yu") ,("za", "za") ,("ze", "ze") ,("zi", "ji") ,("zo", "zo") ,("zu", "zu") ,("-", "-") ,("a", "a") ,("e", "e") ,("i", "i") ,("n", "n") ,("o", "o") ,("u", "u") ] hepburnToKunreiAList :: [(Text, Text)] hepburnToKunreiAList = [ ("bbya", "bbya") ,("bbyo", "bbyo") ,("bbyu", "bbyu") ,("ccha", "ttya") ,("cche", "ttye") ,("cchi", "tti") ,("ccho", "ttyo") ,("cchu", "ttyu") ,("ddya", "ddya") ,("ddyo", "ddyo") ,("ddyu", "ddyu") ,("ggya", "ggya") ,("ggyo", "ggyo") ,("ggyu", "ggyu") ,("hhya", "hhya") ,("hhyo", "hhyo") ,("hhyu", "hhyu") ,("kkya", "kkya") ,("kkyo", "kkyo") ,("kkyu", "kkyu") ,("ppya", "ppya") ,("ppyo", "ppyo") ,("ppyu", "ppyu") ,("rrya", "rrya") ,("rryo", "rryo") ,("rryu", "rryu") ,("ssha", "ssya") ,("sshe", "ssye") ,("sshi", "ssi") ,("ssho", "ssyo") ,("sshu", "ssyu") ,("ttsu", "ttu") ,("xtsu", "xtu") ,("bba", "bba") ,("bbe", "bbe") ,("bbi", "bbi") ,("bbo", "bbo") ,("bbu", "bbu") ,("bya", "bya") ,("byo", "byo") ,("byu", "byu") ,("cha", "tya") ,("che", "tye") ,("chi", "ti") ,("cho", "tyo") ,("chu", "tyu") ,("dda", "dda") ,("dde", "dde") ,("ddi", "ddi") ,("ddo", "ddo") ,("ddu", "ddu") ,("dya", "dya") ,("dyo", "dyo") ,("dyu", "dyu") ,("ffa", "ffa") ,("ffe", "ffe") ,("ffi", "ffi") ,("ffo", "ffo") ,("ffu", "ffu") ,("gga", "gga") ,("gge", "gge") ,("ggi", "ggi") ,("ggo", "ggo") ,("ggu", "ggu") ,("gya", "gya") ,("gyo", "gyo") ,("gyu", "gyu") ,("hha", "hha") ,("hhe", "hhe") ,("hhi", "hhi") ,("hho", "hho") ,("hya", "hya") ,("hyo", "hyo") ,("hyu", "hyu") ,("jja", "zzya") ,("jji", "zzi") ,("jjo", "zzyo") ,("jju", "zzyu") ,("kka", "kka") ,("kke", "kke") ,("kki", "kki") ,("kko", "kko") ,("kku", "kku") ,("kya", "kya") ,("kyo", "kyo") ,("kyu", "kyu") ,("mya", "mya") ,("myo", "myo") ,("myu", "myu") ,("nya", "nya") ,("nyo", "nyo") ,("nyu", "nyu") ,("ppa", "ppa") ,("ppe", "ppe") ,("ppi", "ppi") ,("ppo", "ppo") ,("ppu", "ppu") ,("pya", "pya") ,("pyo", "pyo") ,("pyu", "pyu") ,("rra", "rra") ,("rre", "rre") ,("rri", "rri") ,("rro", "rro") ,("rru", "rru") ,("rya", "rya") ,("ryo", "ryo") ,("ryu", "ryu") ,("sha", "sya") ,("she", "sye") ,("shi", "si") ,("sho", "syo") ,("shu", "syu") ,("ssa", "ssa") ,("sse", "sse") ,("sso", "sso") ,("ssu", "ssu") ,("tsu", "tu") ,("tta", "tta") ,("tte", "tte") ,("tti", "tti") ,("tto", "tto") ,("vva", "vva") ,("vve", "vve") ,("vvi", "vvi") ,("vvo", "vvo") ,("vvu", "vvu") ,("xwa", "xwa") ,("xya", "xya") ,("xyo", "xyo") ,("xyu", "xyu") ,("yya", "yya") ,("yyo", "yyo") ,("yyu", "yyu") ,("zza", "zza") ,("zze", "zze") ,("zzo", "zzo") ,("zzu", "zzu") ,("ba", "ba") ,("be", "be") ,("bi", "bi") ,("bo", "bo") ,("bu", "bu") ,("da", "da") ,("de", "de") ,("di", "dyi") ,("do", "do") ,("du", "du") ,("fa", "fa") ,("fe", "fe") ,("fi", "fi") ,("fo", "fo") ,("fu", "fu") ,("ga", "ga") ,("ge", "ge") ,("gi", "gi") ,("go", "go") ,("gu", "gu") ,("ha", "ha") ,("he", "he") ,("hi", "hi") ,("ho", "ho") ,("ja", "zya") ,("je", "zye") ,("ji", "zi") ,("jo", "zyo") ,("ju", "zyu") ,("ka", "ka") ,("ke", "ke") ,("ki", "ki") ,("ko", "ko") ,("ku", "ku") ,("ma", "ma") ,("me", "me") ,("mi", "mi") ,("mo", "mo") ,("mu", "mu") ,("n'", "n'") ,("na", "na") ,("ne", "ne") ,("ni", "ni") ,("no", "no") ,("nu", "nu") ,("pa", "pa") ,("pe", "pe") ,("pi", "pi") ,("po", "po") ,("pu", "pu") ,("ra", "ra") ,("re", "re") ,("ri", "ri") ,("ro", "ro") ,("ru", "ru") ,("sa", "sa") ,("se", "se") ,("so", "so") ,("su", "su") ,("ta", "ta") ,("te", "te") ,("ti", "ti") ,("to", "to") ,("va", "va") ,("ve", "ve") ,("vi", "vi") ,("vo", "vo") ,("vu", "vu") ,("wa", "wa") ,("we", "we") ,("wi", "wi") ,("wo", "wo") ,("xa", "xa") ,("xe", "xe") ,("xi", "xi") ,("xo", "xo") ,("xu", "xu") ,("ya", "ya") ,("yo", "yo") ,("yu", "yu") ,("za", "za") ,("ze", "ze") ,("zo", "zo") ,("zu", "zu") ,("-", "-") ,("a", "a") ,("e", "e") ,("i", "i") ,("n", "n") ,("o", "o") ,("u", "u") ]
karlvoigtland/romkan-hs
NLP/Romkan/Internal.hs
bsd-3-clause
29,985
0
6
7,373
13,112
8,737
4,375
1,468
1
module Main ( main ) where import Test.HUnit (runTestTT) import Yawn.Test.Common (withServer) import qualified Yawn.Test.BlackBox.ParserTest as ParserTest (tests) main :: IO () main = withServer "www" $ do runTestTT ParserTest.tests return ()
ameingast/yawn
test/src/TestMain.hs
bsd-3-clause
252
0
9
41
83
47
36
9
1
module Benchmarks.ListSet where type Set a = [a] empty :: Set a empty = [] insert :: Ord a => a -> Set a -> Set a insert a [] = [a] insert a (x:xs) | a < x = a:x:xs | a > x = x:insert a xs | a == x = x:xs set :: Ord a => [a] -> Set a set = foldr insert empty ordered [] = True ordered [x] = True ordered (x:y:zs) = x <= y && ordered (y:zs) allDiff [] = True allDiff (x:xs) = x `notElem` xs && allDiff xs isSet s = ordered s && allDiff s -- Properties infixr 0 --> False --> _ = True True --> x = x prop_insertSet :: (Char, Set Char) -> Bool prop_insertSet (c, s) = ordered s --> ordered (insert c s)
UoYCS-plasma/LazySmallCheck2012
suite/performance/Benchmarks/ListSet.hs
bsd-3-clause
616
0
8
156
370
188
182
23
1
module HsImport.Utils ( firstSrcLine , lastSrcLine , srcSpan , declSrcLoc , importDecls ) where import qualified Language.Haskell.Exts as HS import HsImport.Types declSrcLoc :: Decl -> SrcLoc declSrcLoc decl = HS.SrcLoc srcFile srcLine srcCol where declSrcSpan = srcSpan . HS.ann $ decl srcFile = HS.srcSpanFilename declSrcSpan srcLine = HS.srcSpanStartLine declSrcSpan srcCol = HS.srcSpanStartColumn declSrcSpan importDecls :: Module -> [ImportDecl] importDecls (HS.Module _ _ _ imports _) = imports importDecls (HS.XmlPage _ _ _ _ _ _ _) = [] importDecls (HS.XmlHybrid _ _ _ imports _ _ _ _ _) = imports
dan-t/hsimport
lib/HsImport/Utils.hs
bsd-3-clause
692
0
9
177
208
112
96
18
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Common where -- orig in mu/Syntax.hs -- N for name, but Name already used in Bound, -- and Nm is a data type in Syntax, thus N - oh well type N = String data Binop = Add | Sub | Mul | Eql deriving (Eq, Ord, Show, Read)
reuleaux/pire
exe/Common.hs
bsd-3-clause
283
0
6
67
49
31
18
5
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RankNTypes #-} module Language.Haskell.Refact.Utils.ExactPrint ( replace , replaceAnnKey , copyAnn , setAnnKeywordDP , clearPriorComments , balanceAllComments ) where import qualified GHC as GHC import qualified Data.Generics as SYB import Control.Monad import Language.Haskell.GHC.ExactPrint.Transform import Language.Haskell.GHC.ExactPrint.Types -- import Language.Haskell.GHC.ExactPrint.Utils import Language.Haskell.Refact.Utils.GhcUtils import qualified Data.Map as Map -- --------------------------------------------------------------------- -- ++AZ++:TODO: Move this to ghc-exactprint -- |The annotations are keyed to the constructor, so if we replace a qualified -- with an unqualified RdrName or vice versa we have to rebuild the key for the -- appropriate annotation. replaceAnnKey :: (SYB.Data old,SYB.Data new) => GHC.Located old -> GHC.Located new -> Anns -> Anns replaceAnnKey old new ans = case Map.lookup (mkAnnKey old) ans of Nothing -> ans Just v -> anns' where anns1 = Map.delete (mkAnnKey old) ans anns' = Map.insert (mkAnnKey new) v anns1 -- --------------------------------------------------------------------- -- ++AZ++ TODO: migrate this to ghc-exactprint copyAnn :: (SYB.Data old,SYB.Data new) => GHC.Located old -> GHC.Located new -> Anns -> Anns copyAnn old new ans = case Map.lookup (mkAnnKey old) ans of Nothing -> ans Just v -> Map.insert (mkAnnKey new) v ans -- --------------------------------------------------------------------- -- | Replaces an old expression with a new expression replace :: AnnKey -> AnnKey -> Anns -> Maybe Anns replace old new ans = do let as = ans oldan <- Map.lookup old as newan <- Map.lookup new as let newan' = Ann { annEntryDelta = annEntryDelta oldan -- , annDelta = annDelta oldan -- , annTrueEntryDelta = annTrueEntryDelta oldan , annPriorComments = annPriorComments oldan , annFollowingComments = annFollowingComments oldan , annsDP = moveAnns (annsDP oldan) (annsDP newan) , annSortKey = annSortKey oldan , annCapturedSpan = annCapturedSpan oldan } return ((\anns -> Map.delete old . Map.insert new newan' $ anns) ans) -- --------------------------------------------------------------------- -- | Shift the first output annotation into the correct place moveAnns :: [(KeywordId, DeltaPos)] -> [(KeywordId, DeltaPos)] -> [(KeywordId, DeltaPos)] moveAnns [] xs = xs moveAnns ((_, dp): _) ((kw, _):xs) = (kw,dp) : xs moveAnns _ [] = [] -- --------------------------------------------------------------------- -- |Change the @DeltaPos@ for a given @KeywordId@ if it appears in the -- annotation for the given item. setAnnKeywordDP :: (SYB.Data a) => GHC.Located a -> KeywordId -> DeltaPos -> Transform () setAnnKeywordDP la kw dp = modifyAnnsT changer where changer ans = case Map.lookup (mkAnnKey la) ans of Nothing -> ans Just an -> Map.insert (mkAnnKey la) (an {annsDP = map update (annsDP an)}) ans update (kw',dp') | kw == kw' = (kw',dp) | otherwise = (kw',dp') -- --------------------------------------------------------------------- -- |Remove any preceding comments from the given item clearPriorComments :: (SYB.Data a) => GHC.Located a -> Transform () clearPriorComments la = do edp <- getEntryDPT la modifyAnnsT $ \ans -> case Map.lookup (mkAnnKey la) ans of Nothing -> ans Just an -> Map.insert (mkAnnKey la) (an {annPriorComments = [] }) ans setEntryDPT la edp -- --------------------------------------------------------------------- balanceAllComments :: SYB.Data a => GHC.Located a -> Transform (GHC.Located a) balanceAllComments la -- Must be top-down = everywhereM' (SYB.mkM inMod `SYB.extM` inExpr `SYB.extM` inMatch `SYB.extM` inStmt ) la where inMod :: GHC.ParsedSource -> Transform (GHC.ParsedSource) inMod m = doBalance m inExpr :: GHC.LHsExpr GHC.RdrName -> Transform (GHC.LHsExpr GHC.RdrName) inExpr e = doBalance e inMatch :: (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)) -> Transform (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)) inMatch m = doBalance m inStmt :: GHC.LStmt GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> Transform (GHC.LStmt GHC.RdrName (GHC.LHsExpr GHC.RdrName)) inStmt s = doBalance s -- |Balance all comments between adjacent decls, as well as pushing all -- trailing comments to the right place. {- e.g., for foo = do return x where x = ['a'] -- do bar = undefined the "-- do" comment must end up in the trailing comments for "x = ['a']" -} doBalance t = do decls <- hsDecls t let go [] = return [] go [x] = return [x] go (x1:x2:xs) = do balanceComments x1 x2 go (x2:xs) _ <- go decls -- replaceDecls t decls' unless (null decls) $ moveTrailingComments t (last decls) return t -- ---------------------------------------------------------------------
SAdams601/ParRegexSearch
test/HaRe/src/Language/Haskell/Refact/Utils/ExactPrint.hs
mit
5,482
0
16
1,338
1,370
715
655
93
3
{-# LANGUAGE RelaxedPolyRec #-} -- needed for inlinesBetween on GHC < 7 {-# LANGUAGE ScopedTypeVariables #-} {- Copyright (C) 2006-2015 John MacFarlane <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Readers.Markdown Copyright : Copyright (C) 2006-2015 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable Conversion of markdown-formatted plain text to 'Pandoc' document. -} module Text.Pandoc.Readers.Markdown ( readMarkdown, readMarkdownWithWarnings ) where import Data.List ( transpose, sortBy, findIndex, intersperse, intercalate ) import qualified Data.Map as M import Data.Scientific (coefficient, base10Exponent) import Data.Ord ( comparing ) import Data.Char ( isSpace, isAlphaNum, toLower ) import Data.Maybe import Text.Pandoc.Definition import Text.Pandoc.Emoji (emojis) import qualified Data.Text as T import Data.Text (Text) import qualified Data.Yaml as Yaml import Data.Yaml (ParseException(..), YamlException(..), YamlMark(..)) import qualified Data.HashMap.Strict as H import qualified Text.Pandoc.Builder as B import qualified Text.Pandoc.UTF8 as UTF8 import qualified Data.Vector as V import Text.Pandoc.Builder (Inlines, Blocks, trimInlines) import Text.Pandoc.Options import Text.Pandoc.Shared import Text.Pandoc.XML (fromEntities) import Text.Pandoc.Parsing hiding (tableWith) import Text.Pandoc.Readers.LaTeX ( rawLaTeXInline, rawLaTeXBlock ) import Text.Pandoc.Readers.HTML ( htmlTag, htmlInBalanced, isInlineTag, isBlockTag, isTextTag, isCommentTag ) import Control.Monad import System.FilePath (takeExtension, addExtension) import Text.HTML.TagSoup import Text.HTML.TagSoup.Match (tagOpen) import qualified Data.Set as Set import Text.Printf (printf) import Debug.Trace (trace) import Text.Pandoc.Compat.Monoid ((<>)) import Text.Pandoc.Error type MarkdownParser = Parser [Char] ParserState -- | Read markdown from an input string and return a Pandoc document. readMarkdown :: ReaderOptions -- ^ Reader options -> String -- ^ String to parse (assuming @'\n'@ line endings) -> Either PandocError Pandoc readMarkdown opts s = (readWith parseMarkdown) def{ stateOptions = opts } (s ++ "\n\n") -- | Read markdown from an input string and return a pair of a Pandoc document -- and a list of warnings. readMarkdownWithWarnings :: ReaderOptions -- ^ Reader options -> String -- ^ String to parse (assuming @'\n'@ line endings) -> Either PandocError (Pandoc, [String]) readMarkdownWithWarnings opts s = (readWithWarnings parseMarkdown) def{ stateOptions = opts } (s ++ "\n\n") trimInlinesF :: F Inlines -> F Inlines trimInlinesF = liftM trimInlines -- -- Constants and data structure definitions -- isBulletListMarker :: Char -> Bool isBulletListMarker '*' = True isBulletListMarker '+' = True isBulletListMarker '-' = True isBulletListMarker _ = False isHruleChar :: Char -> Bool isHruleChar '*' = True isHruleChar '-' = True isHruleChar '_' = True isHruleChar _ = False setextHChars :: String setextHChars = "=-" isBlank :: Char -> Bool isBlank ' ' = True isBlank '\t' = True isBlank '\n' = True isBlank _ = False -- -- auxiliary functions -- -- | Succeeds when we're in list context. inList :: MarkdownParser () inList = do ctx <- stateParserContext <$> getState guard (ctx == ListItemState) isNull :: F Inlines -> Bool isNull ils = B.isNull $ runF ils def spnl :: Parser [Char] st () spnl = try $ do skipSpaces optional newline skipSpaces notFollowedBy (char '\n') indentSpaces :: MarkdownParser String indentSpaces = try $ do tabStop <- getOption readerTabStop count tabStop (char ' ') <|> string "\t" <?> "indentation" nonindentSpaces :: MarkdownParser String nonindentSpaces = do tabStop <- getOption readerTabStop sps <- many (char ' ') if length sps < tabStop then return sps else unexpected "indented line" -- returns number of spaces parsed skipNonindentSpaces :: MarkdownParser Int skipNonindentSpaces = do tabStop <- getOption readerTabStop atMostSpaces (tabStop - 1) <* notFollowedBy (char ' ') atMostSpaces :: Int -> MarkdownParser Int atMostSpaces n | n > 0 = (char ' ' >> (+1) <$> atMostSpaces (n-1)) <|> return 0 | otherwise = return 0 litChar :: MarkdownParser Char litChar = escapedChar' <|> characterReference <|> noneOf "\n" <|> try (newline >> notFollowedBy blankline >> return ' ') -- | Parse a sequence of inline elements between square brackets, -- including inlines between balanced pairs of square brackets. inlinesInBalancedBrackets :: MarkdownParser (F Inlines) inlinesInBalancedBrackets = do char '[' (_, raw) <- withRaw $ charsInBalancedBrackets 1 guard $ not $ null raw parseFromString (trimInlinesF . mconcat <$> many inline) (init raw) charsInBalancedBrackets :: Int -> MarkdownParser () charsInBalancedBrackets 0 = return () charsInBalancedBrackets openBrackets = (char '[' >> charsInBalancedBrackets (openBrackets + 1)) <|> (char ']' >> charsInBalancedBrackets (openBrackets - 1)) <|> (( (() <$ code) <|> (() <$ (escapedChar')) <|> (newline >> notFollowedBy blankline) <|> skipMany1 (noneOf "[]`\n\\") <|> (() <$ count 1 (oneOf "`\\")) ) >> charsInBalancedBrackets openBrackets) -- -- document structure -- titleLine :: MarkdownParser (F Inlines) titleLine = try $ do char '%' skipSpaces res <- many $ (notFollowedBy newline >> inline) <|> try (endline >> whitespace) newline return $ trimInlinesF $ mconcat res authorsLine :: MarkdownParser (F [Inlines]) authorsLine = try $ do char '%' skipSpaces authors <- sepEndBy (many (notFollowedBy (satisfy $ \c -> c == ';' || c == '\n') >> inline)) (char ';' <|> try (newline >> notFollowedBy blankline >> spaceChar)) newline return $ sequence $ filter (not . isNull) $ map (trimInlinesF . mconcat) authors dateLine :: MarkdownParser (F Inlines) dateLine = try $ do char '%' skipSpaces trimInlinesF . mconcat <$> manyTill inline newline titleBlock :: MarkdownParser () titleBlock = pandocTitleBlock <|> mmdTitleBlock pandocTitleBlock :: MarkdownParser () pandocTitleBlock = try $ do guardEnabled Ext_pandoc_title_block lookAhead (char '%') title <- option mempty titleLine author <- option (return []) authorsLine date <- option mempty dateLine optional blanklines let meta' = do title' <- title author' <- author date' <- date return $ (if B.isNull title' then id else B.setMeta "title" title') . (if null author' then id else B.setMeta "author" author') . (if B.isNull date' then id else B.setMeta "date" date') $ nullMeta updateState $ \st -> st{ stateMeta' = stateMeta' st <> meta' } yamlMetaBlock :: MarkdownParser (F Blocks) yamlMetaBlock = try $ do guardEnabled Ext_yaml_metadata_block pos <- getPosition string "---" blankline notFollowedBy blankline -- if --- is followed by a blank it's an HRULE rawYamlLines <- manyTill anyLine stopLine -- by including --- and ..., we allow yaml blocks with just comments: let rawYaml = unlines ("---" : (rawYamlLines ++ ["..."])) optional blanklines opts <- stateOptions <$> getState meta' <- case Yaml.decodeEither' $ UTF8.fromString rawYaml of Right (Yaml.Object hashmap) -> return $ return $ H.foldrWithKey (\k v m -> if ignorable k then m else case yamlToMeta opts v of Left _ -> m Right v' -> B.setMeta (T.unpack k) v' m) nullMeta hashmap Right Yaml.Null -> return $ return nullMeta Right _ -> do addWarning (Just pos) "YAML header is not an object" return $ return nullMeta Left err' -> do case err' of InvalidYaml (Just YamlParseException{ yamlProblem = problem , yamlContext = _ctxt , yamlProblemMark = Yaml.YamlMark { yamlLine = yline , yamlColumn = ycol }}) -> addWarning (Just $ setSourceLine (setSourceColumn pos (sourceColumn pos + ycol)) (sourceLine pos + 1 + yline)) $ "Could not parse YAML header: " ++ problem _ -> addWarning (Just pos) $ "Could not parse YAML header: " ++ show err' return $ return nullMeta updateState $ \st -> st{ stateMeta' = stateMeta' st <> meta' } return mempty -- ignore fields ending with _ ignorable :: Text -> Bool ignorable t = (T.pack "_") `T.isSuffixOf` t toMetaValue :: ReaderOptions -> Text -> Either PandocError MetaValue toMetaValue opts x = toMeta <$> readMarkdown opts' (T.unpack x) where toMeta p = case p of Pandoc _ [Plain xs] -> MetaInlines xs Pandoc _ [Para xs] | endsWithNewline x -> MetaBlocks [Para xs] | otherwise -> MetaInlines xs Pandoc _ bs -> MetaBlocks bs endsWithNewline t = T.pack "\n" `T.isSuffixOf` t opts' = opts{readerExtensions=readerExtensions opts `Set.difference` meta_exts} meta_exts = Set.fromList [ Ext_pandoc_title_block , Ext_mmd_title_block , Ext_yaml_metadata_block ] yamlToMeta :: ReaderOptions -> Yaml.Value -> Either PandocError MetaValue yamlToMeta opts (Yaml.String t) = toMetaValue opts t yamlToMeta _ (Yaml.Number n) -- avoid decimal points for numbers that don't need them: | base10Exponent n >= 0 = return $ MetaString $ show $ coefficient n * (10 ^ base10Exponent n) | otherwise = return $ MetaString $ show n yamlToMeta _ (Yaml.Bool b) = return $ MetaBool b yamlToMeta opts (Yaml.Array xs) = B.toMetaValue <$> mapM (yamlToMeta opts) (V.toList xs) yamlToMeta opts (Yaml.Object o) = MetaMap <$> H.foldrWithKey (\k v m -> if ignorable k then m else (do v' <- yamlToMeta opts v m' <- m return (M.insert (T.unpack k) v' m'))) (return M.empty) o yamlToMeta _ _ = return $ MetaString "" stopLine :: MarkdownParser () stopLine = try $ (string "---" <|> string "...") >> blankline >> return () mmdTitleBlock :: MarkdownParser () mmdTitleBlock = try $ do guardEnabled Ext_mmd_title_block firstPair <- kvPair False restPairs <- many (kvPair True) let kvPairs = firstPair : restPairs blanklines updateState $ \st -> st{ stateMeta' = stateMeta' st <> return (Meta $ M.fromList kvPairs) } kvPair :: Bool -> MarkdownParser (String, MetaValue) kvPair allowEmpty = try $ do key <- many1Till (alphaNum <|> oneOf "_- ") (char ':') val <- trim <$> manyTill anyChar (try $ newline >> lookAhead (blankline <|> nonspaceChar)) guard $ allowEmpty || not (null val) let key' = concat $ words $ map toLower key let val' = MetaBlocks $ B.toList $ B.plain $ B.text $ val return (key',val') parseMarkdown :: MarkdownParser Pandoc parseMarkdown = do -- markdown allows raw HTML updateState $ \state -> state { stateOptions = let oldOpts = stateOptions state in oldOpts{ readerParseRaw = True } } optional titleBlock blocks <- parseBlocks st <- getState let meta = runF (stateMeta' st) st let Pandoc _ bs = B.doc $ runF blocks st return $ Pandoc meta bs referenceKey :: MarkdownParser (F Blocks) referenceKey = try $ do pos <- getPosition skipNonindentSpaces (_,raw) <- reference char ':' skipSpaces >> optional newline >> skipSpaces >> notFollowedBy (char '[') let sourceURL = liftM unwords $ many $ try $ do skipMany spaceChar notFollowedBy' referenceTitle notFollowedBy' (() <$ reference) many1 $ notFollowedBy space >> litChar let betweenAngles = try $ char '<' >> manyTill litChar (char '>') src <- try betweenAngles <|> sourceURL tit <- option "" referenceTitle -- currently we just ignore MMD-style link/image attributes _kvs <- option [] $ guardEnabled Ext_link_attributes >> many (try $ spnl >> keyValAttr) blanklines let target = (escapeURI $ trimr src, tit) st <- getState let oldkeys = stateKeys st let key = toKey raw case M.lookup key oldkeys of Just _ -> addWarning (Just pos) $ "Duplicate link reference `" ++ raw ++ "'" Nothing -> return () updateState $ \s -> s { stateKeys = M.insert key target oldkeys } return $ return mempty referenceTitle :: MarkdownParser String referenceTitle = try $ do skipSpaces >> optional newline >> skipSpaces quotedTitle '"' <|> quotedTitle '\'' <|> charsInBalanced '(' ')' litChar -- A link title in quotes quotedTitle :: Char -> MarkdownParser String quotedTitle c = try $ do char c notFollowedBy spaces let pEnder = try $ char c >> notFollowedBy (satisfy isAlphaNum) let regChunk = many1 (noneOf ['\\','\n','&',c]) <|> count 1 litChar let nestedChunk = (\x -> [c] ++ x ++ [c]) <$> quotedTitle c unwords . words . concat <$> manyTill (nestedChunk <|> regChunk) pEnder -- | PHP Markdown Extra style abbreviation key. Currently -- we just skip them, since Pandoc doesn't have an element for -- an abbreviation. abbrevKey :: MarkdownParser (F Blocks) abbrevKey = do guardEnabled Ext_abbreviations try $ do char '*' reference char ':' skipMany (satisfy (/= '\n')) blanklines return $ return mempty noteMarker :: MarkdownParser String noteMarker = string "[^" >> many1Till (satisfy $ not . isBlank) (char ']') rawLine :: MarkdownParser String rawLine = try $ do notFollowedBy blankline notFollowedBy' $ try $ skipNonindentSpaces >> noteMarker optional indentSpaces anyLine rawLines :: MarkdownParser String rawLines = do first <- anyLine rest <- many rawLine return $ unlines (first:rest) noteBlock :: MarkdownParser (F Blocks) noteBlock = try $ do pos <- getPosition skipNonindentSpaces ref <- noteMarker char ':' optional blankline optional indentSpaces first <- rawLines rest <- many $ try $ blanklines >> indentSpaces >> rawLines let raw = unlines (first:rest) ++ "\n" optional blanklines parsed <- parseFromString parseBlocks raw let newnote = (ref, parsed) oldnotes <- stateNotes' <$> getState case lookup ref oldnotes of Just _ -> addWarning (Just pos) $ "Duplicate note reference `" ++ ref ++ "'" Nothing -> return () updateState $ \s -> s { stateNotes' = newnote : oldnotes } return mempty -- -- parsing blocks -- parseBlocks :: MarkdownParser (F Blocks) parseBlocks = mconcat <$> manyTill block eof block :: MarkdownParser (F Blocks) block = do tr <- getOption readerTrace pos <- getPosition res <- choice [ mempty <$ blanklines , codeBlockFenced , yamlMetaBlock , guardEnabled Ext_latex_macros *> (macro >>= return . return) -- note: bulletList needs to be before header because of -- the possibility of empty list items: - , bulletList , header , lhsCodeBlock , divHtml , htmlBlock , table , codeBlockIndented , rawTeXBlock , lineBlock , blockQuote , hrule , orderedList , definitionList , noteBlock , referenceKey , abbrevKey , para , plain ] <?> "block" when tr $ do st <- getState trace (printf "line %d: %s" (sourceLine pos) (take 60 $ show $ B.toList $ runF res st)) (return ()) return res -- -- header blocks -- header :: MarkdownParser (F Blocks) header = setextHeader <|> atxHeader <?> "header" atxChar :: MarkdownParser Char atxChar = do exts <- getOption readerExtensions return $ if Set.member Ext_literate_haskell exts then '=' else '#' atxHeader :: MarkdownParser (F Blocks) atxHeader = try $ do level <- atxChar >>= many1 . char >>= return . length notFollowedBy $ guardEnabled Ext_fancy_lists >> (char '.' <|> char ')') -- this would be a list skipSpaces (text, raw) <- withRaw $ trimInlinesF . mconcat <$> many (notFollowedBy atxClosing >> inline) attr <- atxClosing attr'@(ident,_,_) <- registerHeader attr (runF text defaultParserState) guardDisabled Ext_implicit_header_references <|> registerImplicitHeader raw ident return $ B.headerWith attr' level <$> text atxClosing :: MarkdownParser Attr atxClosing = try $ do attr' <- option nullAttr (guardEnabled Ext_mmd_header_identifiers >> mmdHeaderIdentifier) skipMany . char =<< atxChar skipSpaces attr <- option attr' (guardEnabled Ext_header_attributes >> attributes) blanklines return attr setextHeaderEnd :: MarkdownParser Attr setextHeaderEnd = try $ do attr <- option nullAttr $ (guardEnabled Ext_mmd_header_identifiers >> mmdHeaderIdentifier) <|> (guardEnabled Ext_header_attributes >> attributes) blanklines return attr mmdHeaderIdentifier :: MarkdownParser Attr mmdHeaderIdentifier = do ident <- stripFirstAndLast . snd <$> reference skipSpaces return (ident,[],[]) setextHeader :: MarkdownParser (F Blocks) setextHeader = try $ do -- This lookahead prevents us from wasting time parsing Inlines -- unless necessary -- it gives a significant performance boost. lookAhead $ anyLine >> many1 (oneOf setextHChars) >> blankline skipSpaces (text, raw) <- withRaw $ trimInlinesF . mconcat <$> many1 (notFollowedBy setextHeaderEnd >> inline) attr <- setextHeaderEnd underlineChar <- oneOf setextHChars many (char underlineChar) blanklines let level = (fromMaybe 0 $ findIndex (== underlineChar) setextHChars) + 1 attr'@(ident,_,_) <- registerHeader attr (runF text defaultParserState) guardDisabled Ext_implicit_header_references <|> registerImplicitHeader raw ident return $ B.headerWith attr' level <$> text registerImplicitHeader :: String -> String -> MarkdownParser () registerImplicitHeader raw ident = do let key = toKey $ "[" ++ raw ++ "]" updateState (\s -> s { stateHeaderKeys = M.insert key ('#':ident,"") (stateHeaderKeys s) }) -- -- hrule block -- hrule :: Parser [Char] st (F Blocks) hrule = try $ do skipSpaces start <- satisfy isHruleChar count 2 (skipSpaces >> char start) skipMany (spaceChar <|> char start) newline optional blanklines return $ return B.horizontalRule -- -- code blocks -- indentedLine :: MarkdownParser String indentedLine = indentSpaces >> anyLine >>= return . (++ "\n") blockDelimiter :: (Char -> Bool) -> Maybe Int -> Parser [Char] st Int blockDelimiter f len = try $ do c <- lookAhead (satisfy f) case len of Just l -> count l (char c) >> many (char c) >> return l Nothing -> count 3 (char c) >> many (char c) >>= return . (+ 3) . length attributes :: MarkdownParser Attr attributes = try $ do char '{' spnl attrs <- many (attribute <* spnl) char '}' return $ foldl (\x f -> f x) nullAttr attrs attribute :: MarkdownParser (Attr -> Attr) attribute = identifierAttr <|> classAttr <|> keyValAttr <|> specialAttr identifier :: MarkdownParser String identifier = do first <- letter rest <- many $ alphaNum <|> oneOf "-_:." return (first:rest) identifierAttr :: MarkdownParser (Attr -> Attr) identifierAttr = try $ do char '#' result <- identifier return $ \(_,cs,kvs) -> (result,cs,kvs) classAttr :: MarkdownParser (Attr -> Attr) classAttr = try $ do char '.' result <- identifier return $ \(id',cs,kvs) -> (id',cs ++ [result],kvs) keyValAttr :: MarkdownParser (Attr -> Attr) keyValAttr = try $ do key <- identifier char '=' val <- enclosed (char '"') (char '"') litChar <|> enclosed (char '\'') (char '\'') litChar <|> many (escapedChar' <|> noneOf " \t\n\r}") return $ \(id',cs,kvs) -> case key of "id" -> (val,cs,kvs) "class" -> (id',cs ++ words val,kvs) _ -> (id',cs,kvs ++ [(key,val)]) specialAttr :: MarkdownParser (Attr -> Attr) specialAttr = do char '-' return $ \(id',cs,kvs) -> (id',cs ++ ["unnumbered"],kvs) codeBlockFenced :: MarkdownParser (F Blocks) codeBlockFenced = try $ do c <- try (guardEnabled Ext_fenced_code_blocks >> lookAhead (char '~')) <|> (guardEnabled Ext_backtick_code_blocks >> lookAhead (char '`')) size <- blockDelimiter (== c) Nothing skipMany spaceChar attr <- option ([],[],[]) $ try (guardEnabled Ext_fenced_code_attributes >> attributes) <|> ((\x -> ("",[toLanguageId x],[])) <$> many1 nonspaceChar) blankline contents <- manyTill anyLine (blockDelimiter (== c) (Just size)) blanklines return $ return $ B.codeBlockWith attr $ intercalate "\n" contents -- correctly handle github language identifiers toLanguageId :: String -> String toLanguageId = map toLower . go where go "c++" = "cpp" go "objective-c" = "objectivec" go x = x codeBlockIndented :: MarkdownParser (F Blocks) codeBlockIndented = do contents <- many1 (indentedLine <|> try (do b <- blanklines l <- indentedLine return $ b ++ l)) optional blanklines classes <- getOption readerIndentedCodeClasses return $ return $ B.codeBlockWith ("", classes, []) $ stripTrailingNewlines $ concat contents lhsCodeBlock :: MarkdownParser (F Blocks) lhsCodeBlock = do guardEnabled Ext_literate_haskell (return . B.codeBlockWith ("",["sourceCode","literate","haskell"],[]) <$> (lhsCodeBlockBird <|> lhsCodeBlockLaTeX)) <|> (return . B.codeBlockWith ("",["sourceCode","haskell"],[]) <$> lhsCodeBlockInverseBird) lhsCodeBlockLaTeX :: MarkdownParser String lhsCodeBlockLaTeX = try $ do string "\\begin{code}" manyTill spaceChar newline contents <- many1Till anyChar (try $ string "\\end{code}") blanklines return $ stripTrailingNewlines contents lhsCodeBlockBird :: MarkdownParser String lhsCodeBlockBird = lhsCodeBlockBirdWith '>' lhsCodeBlockInverseBird :: MarkdownParser String lhsCodeBlockInverseBird = lhsCodeBlockBirdWith '<' lhsCodeBlockBirdWith :: Char -> MarkdownParser String lhsCodeBlockBirdWith c = try $ do pos <- getPosition when (sourceColumn pos /= 1) $ fail "Not in first column" lns <- many1 $ birdTrackLine c -- if (as is normal) there is always a space after >, drop it let lns' = if all (\ln -> null ln || take 1 ln == " ") lns then map (drop 1) lns else lns blanklines return $ intercalate "\n" lns' birdTrackLine :: Char -> Parser [Char] st String birdTrackLine c = try $ do char c -- allow html tags on left margin: when (c == '<') $ notFollowedBy letter anyLine -- -- block quotes -- emailBlockQuoteStart :: MarkdownParser Char emailBlockQuoteStart = try $ skipNonindentSpaces >> char '>' <* optional (char ' ') emailBlockQuote :: MarkdownParser [String] emailBlockQuote = try $ do emailBlockQuoteStart let emailLine = many $ nonEndline <|> try (endline >> notFollowedBy emailBlockQuoteStart >> return '\n') let emailSep = try (newline >> emailBlockQuoteStart) first <- emailLine rest <- many $ try $ emailSep >> emailLine let raw = first:rest newline <|> (eof >> return '\n') optional blanklines return raw blockQuote :: MarkdownParser (F Blocks) blockQuote = do raw <- emailBlockQuote -- parse the extracted block, which may contain various block elements: contents <- parseFromString parseBlocks $ (intercalate "\n" raw) ++ "\n\n" return $ B.blockQuote <$> contents -- -- list blocks -- bulletListStart :: MarkdownParser () bulletListStart = try $ do optional newline -- if preceded by a Plain block in a list context startpos <- sourceColumn <$> getPosition skipNonindentSpaces notFollowedBy' (() <$ hrule) -- because hrules start out just like lists satisfy isBulletListMarker endpos <- sourceColumn <$> getPosition tabStop <- getOption readerTabStop lookAhead (newline <|> spaceChar) () <$ atMostSpaces (tabStop - (endpos - startpos)) anyOrderedListStart :: MarkdownParser (Int, ListNumberStyle, ListNumberDelim) anyOrderedListStart = try $ do optional newline -- if preceded by a Plain block in a list context startpos <- sourceColumn <$> getPosition skipNonindentSpaces notFollowedBy $ string "p." >> spaceChar >> digit -- page number res <- do guardDisabled Ext_fancy_lists start <- many1 digit >>= safeRead char '.' return (start, DefaultStyle, DefaultDelim) <|> do (num, style, delim) <- anyOrderedListMarker -- if it could be an abbreviated first name, -- insist on more than one space when (delim == Period && (style == UpperAlpha || (style == UpperRoman && num `elem` [1, 5, 10, 50, 100, 500, 1000]))) $ () <$ spaceChar return (num, style, delim) endpos <- sourceColumn <$> getPosition tabStop <- getOption readerTabStop lookAhead (newline <|> spaceChar) atMostSpaces (tabStop - (endpos - startpos)) return res listStart :: MarkdownParser () listStart = bulletListStart <|> (anyOrderedListStart >> return ()) listLine :: MarkdownParser String listLine = try $ do notFollowedBy' (do indentSpaces many spaceChar listStart) notFollowedByHtmlCloser optional (() <$ indentSpaces) listLineCommon listLineCommon :: MarkdownParser String listLineCommon = concat <$> manyTill ( many1 (satisfy $ \c -> c /= '\n' && c /= '<') <|> liftM snd (htmlTag isCommentTag) <|> count 1 anyChar ) newline -- parse raw text for one list item, excluding start marker and continuations rawListItem :: MarkdownParser a -> MarkdownParser String rawListItem start = try $ do start first <- listLineCommon rest <- many (notFollowedBy listStart >> notFollowedBy blankline >> listLine) blanks <- many blankline return $ unlines (first:rest) ++ blanks -- continuation of a list item - indented and separated by blankline -- or (in compact lists) endline. -- note: nested lists are parsed as continuations listContinuation :: MarkdownParser String listContinuation = try $ do lookAhead indentSpaces result <- many1 listContinuationLine blanks <- many blankline return $ concat result ++ blanks notFollowedByHtmlCloser :: MarkdownParser () notFollowedByHtmlCloser = do inHtmlBlock <- stateInHtmlBlock <$> getState case inHtmlBlock of Just t -> notFollowedBy' $ htmlTag (~== TagClose t) Nothing -> return () listContinuationLine :: MarkdownParser String listContinuationLine = try $ do notFollowedBy blankline notFollowedBy' listStart notFollowedByHtmlCloser optional indentSpaces result <- anyLine return $ result ++ "\n" listItem :: MarkdownParser a -> MarkdownParser (F Blocks) listItem start = try $ do first <- rawListItem start continuations <- many listContinuation -- parsing with ListItemState forces markers at beginning of lines to -- count as list item markers, even if not separated by blank space. -- see definition of "endline" state <- getState let oldContext = stateParserContext state setState $ state {stateParserContext = ListItemState} -- parse the extracted block, which may contain various block elements: let raw = concat (first:continuations) contents <- parseFromString parseBlocks raw updateState (\st -> st {stateParserContext = oldContext}) return contents orderedList :: MarkdownParser (F Blocks) orderedList = try $ do (start, style, delim) <- lookAhead anyOrderedListStart unless (style `elem` [DefaultStyle, Decimal, Example] && delim `elem` [DefaultDelim, Period]) $ guardEnabled Ext_fancy_lists when (style == Example) $ guardEnabled Ext_example_lists items <- fmap sequence $ many1 $ listItem ( try $ do optional newline -- if preceded by Plain block in a list startpos <- sourceColumn <$> getPosition skipNonindentSpaces res <- orderedListMarker style delim endpos <- sourceColumn <$> getPosition tabStop <- getOption readerTabStop lookAhead (newline <|> spaceChar) atMostSpaces (tabStop - (endpos - startpos)) return res ) start' <- option 1 $ guardEnabled Ext_startnum >> return start return $ B.orderedListWith (start', style, delim) <$> fmap compactify' items bulletList :: MarkdownParser (F Blocks) bulletList = do items <- fmap sequence $ many1 $ listItem bulletListStart return $ B.bulletList <$> fmap compactify' items -- definition lists defListMarker :: MarkdownParser () defListMarker = do sps <- nonindentSpaces char ':' <|> char '~' tabStop <- getOption readerTabStop let remaining = tabStop - (length sps + 1) if remaining > 0 then try (count remaining (char ' ')) <|> string "\t" <|> many1 spaceChar else mzero return () definitionListItem :: Bool -> MarkdownParser (F (Inlines, [Blocks])) definitionListItem compact = try $ do rawLine' <- anyLine raw <- many1 $ defRawBlock compact term <- parseFromString (trimInlinesF . mconcat <$> many inline) rawLine' contents <- mapM (parseFromString parseBlocks . (++"\n")) raw optional blanklines return $ liftM2 (,) term (sequence contents) defRawBlock :: Bool -> MarkdownParser String defRawBlock compact = try $ do hasBlank <- option False $ blankline >> return True defListMarker firstline <- anyLine let dline = try ( do notFollowedBy blankline notFollowedByHtmlCloser if compact -- laziness not compatible with compact then () <$ indentSpaces else (() <$ indentSpaces) <|> notFollowedBy defListMarker anyLine ) rawlines <- many dline cont <- liftM concat $ many $ try $ do trailing <- option "" blanklines ln <- indentSpaces >> notFollowedBy blankline >> anyLine lns <- many dline return $ trailing ++ unlines (ln:lns) return $ trimr (firstline ++ "\n" ++ unlines rawlines ++ cont) ++ if hasBlank || not (null cont) then "\n\n" else "" definitionList :: MarkdownParser (F Blocks) definitionList = try $ do lookAhead (anyLine >> optional (blankline >> notFollowedBy (table >> return ())) >> -- don't capture table caption as def list! defListMarker) compactDefinitionList <|> normalDefinitionList compactDefinitionList :: MarkdownParser (F Blocks) compactDefinitionList = do guardEnabled Ext_compact_definition_lists items <- fmap sequence $ many1 $ definitionListItem True return $ B.definitionList <$> fmap compactify'DL items normalDefinitionList :: MarkdownParser (F Blocks) normalDefinitionList = do guardEnabled Ext_definition_lists items <- fmap sequence $ many1 $ definitionListItem False return $ B.definitionList <$> items -- -- paragraph block -- para :: MarkdownParser (F Blocks) para = try $ do exts <- getOption readerExtensions result <- trimInlinesF . mconcat <$> many1 inline option (B.plain <$> result) $ try $ do newline (blanklines >> return mempty) <|> (guardDisabled Ext_blank_before_blockquote >> () <$ lookAhead blockQuote) <|> (guardEnabled Ext_backtick_code_blocks >> () <$ lookAhead codeBlockFenced) <|> (guardDisabled Ext_blank_before_header >> () <$ lookAhead header) <|> (guardEnabled Ext_lists_without_preceding_blankline >> -- Avoid creating a paragraph in a nested list. notFollowedBy' inList >> () <$ lookAhead listStart) <|> do guardEnabled Ext_native_divs inHtmlBlock <- stateInHtmlBlock <$> getState case inHtmlBlock of Just "div" -> () <$ lookAhead (htmlTag (~== TagClose "div")) _ -> mzero return $ do result' <- result case B.toList result' of [Image alt (src,tit)] | Ext_implicit_figures `Set.member` exts -> -- the fig: at beginning of title indicates a figure return $ B.para $ B.singleton $ Image alt (src,'f':'i':'g':':':tit) _ -> return $ B.para result' plain :: MarkdownParser (F Blocks) plain = fmap B.plain . trimInlinesF . mconcat <$> many1 inline -- -- raw html -- htmlElement :: MarkdownParser String htmlElement = rawVerbatimBlock <|> strictHtmlBlock <|> liftM snd (htmlTag isBlockTag) htmlBlock :: MarkdownParser (F Blocks) htmlBlock = do guardEnabled Ext_raw_html try (do (TagOpen t attrs) <- lookAhead $ fst <$> htmlTag isBlockTag (guard (t `elem` ["pre","style","script"]) >> (return . B.rawBlock "html") <$> rawVerbatimBlock) <|> (do guardEnabled Ext_markdown_attribute oldMarkdownAttribute <- stateMarkdownAttribute <$> getState markdownAttribute <- case lookup "markdown" attrs of Just "0" -> False <$ updateState (\st -> st{ stateMarkdownAttribute = False }) Just _ -> True <$ updateState (\st -> st{ stateMarkdownAttribute = True }) Nothing -> return oldMarkdownAttribute res <- if markdownAttribute then rawHtmlBlocks else htmlBlock' updateState $ \st -> st{ stateMarkdownAttribute = oldMarkdownAttribute } return res) <|> (guardEnabled Ext_markdown_in_html_blocks >> rawHtmlBlocks)) <|> htmlBlock' htmlBlock' :: MarkdownParser (F Blocks) htmlBlock' = try $ do first <- htmlElement skipMany spaceChar optional blanklines return $ return $ B.rawBlock "html" first strictHtmlBlock :: MarkdownParser String strictHtmlBlock = htmlInBalanced (not . isInlineTag) rawVerbatimBlock :: MarkdownParser String rawVerbatimBlock = try $ do (TagOpen tag _, open) <- htmlTag (tagOpen (flip elem ["pre", "style", "script"]) (const True)) contents <- manyTill anyChar (htmlTag (~== TagClose tag)) return $ open ++ contents ++ renderTags' [TagClose tag] rawTeXBlock :: MarkdownParser (F Blocks) rawTeXBlock = do guardEnabled Ext_raw_tex result <- (B.rawBlock "latex" . concat <$> rawLaTeXBlock `sepEndBy1` blankline) <|> (B.rawBlock "context" . concat <$> rawConTeXtEnvironment `sepEndBy1` blankline) spaces return $ return result rawHtmlBlocks :: MarkdownParser (F Blocks) rawHtmlBlocks = do (TagOpen tagtype _, raw) <- htmlTag isBlockTag -- try to find closing tag -- we set stateInHtmlBlock so that closing tags that can be either block or -- inline will not be parsed as inline tags oldInHtmlBlock <- stateInHtmlBlock <$> getState updateState $ \st -> st{ stateInHtmlBlock = Just tagtype } let closer = htmlTag (\x -> x ~== TagClose tagtype) contents <- mconcat <$> many (notFollowedBy' closer >> block) result <- (closer >>= \(_, rawcloser) -> return ( return (B.rawBlock "html" $ stripMarkdownAttribute raw) <> contents <> return (B.rawBlock "html" rawcloser))) <|> return (return (B.rawBlock "html" raw) <> contents) updateState $ \st -> st{ stateInHtmlBlock = oldInHtmlBlock } return result -- remove markdown="1" attribute stripMarkdownAttribute :: String -> String stripMarkdownAttribute s = renderTags' $ map filterAttrib $ parseTags s where filterAttrib (TagOpen t as) = TagOpen t [(k,v) | (k,v) <- as, k /= "markdown"] filterAttrib x = x -- -- line block -- lineBlock :: MarkdownParser (F Blocks) lineBlock = try $ do guardEnabled Ext_line_blocks lines' <- lineBlockLines >>= mapM (parseFromString (trimInlinesF . mconcat <$> many inline)) return $ B.para <$> (mconcat $ intersperse (return B.linebreak) lines') -- -- Tables -- -- Parse a dashed line with optional trailing spaces; return its length -- and the length including trailing space. dashedLine :: Char -> Parser [Char] st (Int, Int) dashedLine ch = do dashes <- many1 (char ch) sp <- many spaceChar let lengthDashes = length dashes lengthSp = length sp return (lengthDashes, lengthDashes + lengthSp) -- Parse a table header with dashed lines of '-' preceded by -- one (or zero) line of text. simpleTableHeader :: Bool -- ^ Headerless table -> MarkdownParser (F [Blocks], [Alignment], [Int]) simpleTableHeader headless = try $ do rawContent <- if headless then return "" else anyLine initSp <- nonindentSpaces dashes <- many1 (dashedLine '-') newline let (lengths, lines') = unzip dashes let indices = scanl (+) (length initSp) lines' -- If no header, calculate alignment on basis of first row of text rawHeads <- liftM (tail . splitStringByIndices (init indices)) $ if headless then lookAhead anyLine else return rawContent let aligns = zipWith alignType (map (\a -> [a]) rawHeads) lengths let rawHeads' = if headless then replicate (length dashes) "" else rawHeads heads <- fmap sequence $ mapM (parseFromString (mconcat <$> many plain)) $ map trim rawHeads' return (heads, aligns, indices) -- Returns an alignment type for a table, based on a list of strings -- (the rows of the column header) and a number (the length of the -- dashed line under the rows. alignType :: [String] -> Int -> Alignment alignType [] _ = AlignDefault alignType strLst len = let nonempties = filter (not . null) $ map trimr strLst (leftSpace, rightSpace) = case sortBy (comparing length) nonempties of (x:_) -> (head x `elem` " \t", length x < len) [] -> (False, False) in case (leftSpace, rightSpace) of (True, False) -> AlignRight (False, True) -> AlignLeft (True, True) -> AlignCenter (False, False) -> AlignDefault -- Parse a table footer - dashed lines followed by blank line. tableFooter :: MarkdownParser String tableFooter = try $ skipNonindentSpaces >> many1 (dashedLine '-') >> blanklines -- Parse a table separator - dashed line. tableSep :: MarkdownParser Char tableSep = try $ skipNonindentSpaces >> many1 (dashedLine '-') >> char '\n' -- Parse a raw line and split it into chunks by indices. rawTableLine :: [Int] -> MarkdownParser [String] rawTableLine indices = do notFollowedBy' (blanklines <|> tableFooter) line <- many1Till anyChar newline return $ map trim $ tail $ splitStringByIndices (init indices) line -- Parse a table line and return a list of lists of blocks (columns). tableLine :: [Int] -> MarkdownParser (F [Blocks]) tableLine indices = rawTableLine indices >>= fmap sequence . mapM (parseFromString (mconcat <$> many plain)) -- Parse a multiline table row and return a list of blocks (columns). multilineRow :: [Int] -> MarkdownParser (F [Blocks]) multilineRow indices = do colLines <- many1 (rawTableLine indices) let cols = map unlines $ transpose colLines fmap sequence $ mapM (parseFromString (mconcat <$> many plain)) cols -- Parses a table caption: inlines beginning with 'Table:' -- and followed by blank lines. tableCaption :: MarkdownParser (F Inlines) tableCaption = try $ do guardEnabled Ext_table_captions skipNonindentSpaces string ":" <|> string "Table:" trimInlinesF . mconcat <$> many1 inline <* blanklines -- Parse a simple table with '---' header and one line per row. simpleTable :: Bool -- ^ Headerless table -> MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) simpleTable headless = do (aligns, _widths, heads', lines') <- tableWith (simpleTableHeader headless) tableLine (return ()) (if headless then tableFooter else tableFooter <|> blanklines) -- Simple tables get 0s for relative column widths (i.e., use default) return (aligns, replicate (length aligns) 0, heads', lines') -- Parse a multiline table: starts with row of '-' on top, then header -- (which may be multiline), then the rows, -- which may be multiline, separated by blank lines, and -- ending with a footer (dashed line followed by blank line). multilineTable :: Bool -- ^ Headerless table -> MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) multilineTable headless = tableWith (multilineTableHeader headless) multilineRow blanklines tableFooter multilineTableHeader :: Bool -- ^ Headerless table -> MarkdownParser (F [Blocks], [Alignment], [Int]) multilineTableHeader headless = try $ do unless headless $ tableSep >> notFollowedBy blankline rawContent <- if headless then return $ repeat "" else many1 $ notFollowedBy tableSep >> anyLine initSp <- nonindentSpaces dashes <- many1 (dashedLine '-') newline let (lengths, lines') = unzip dashes let indices = scanl (+) (length initSp) lines' rawHeadsList <- if headless then liftM (map (:[]) . tail . splitStringByIndices (init indices)) $ lookAhead anyLine else return $ transpose $ map (tail . splitStringByIndices (init indices)) rawContent let aligns = zipWith alignType rawHeadsList lengths let rawHeads = if headless then replicate (length dashes) "" else map (unlines . map trim) rawHeadsList heads <- fmap sequence $ mapM (parseFromString (mconcat <$> many plain)) $ map trim rawHeads return (heads, aligns, indices) -- Parse a grid table: starts with row of '-' on top, then header -- (which may be grid), then the rows, -- which may be grid, separated by blank lines, and -- ending with a footer (dashed line followed by blank line). gridTable :: Bool -- ^ Headerless table -> MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) gridTable headless = tableWith (gridTableHeader headless) gridTableRow (gridTableSep '-') gridTableFooter gridTableSplitLine :: [Int] -> String -> [String] gridTableSplitLine indices line = map removeFinalBar $ tail $ splitStringByIndices (init indices) $ trimr line gridPart :: Char -> Parser [Char] st (Int, Int) gridPart ch = do dashes <- many1 (char ch) char '+' let lengthDashes = length dashes return (lengthDashes, lengthDashes + 1) gridDashedLines :: Char -> Parser [Char] st [(Int,Int)] gridDashedLines ch = try $ char '+' >> many1 (gridPart ch) <* blankline removeFinalBar :: String -> String removeFinalBar = reverse . dropWhile (`elem` " \t") . dropWhile (=='|') . reverse -- | Separator between rows of grid table. gridTableSep :: Char -> MarkdownParser Char gridTableSep ch = try $ gridDashedLines ch >> return '\n' -- | Parse header for a grid table. gridTableHeader :: Bool -- ^ Headerless table -> MarkdownParser (F [Blocks], [Alignment], [Int]) gridTableHeader headless = try $ do optional blanklines dashes <- gridDashedLines '-' rawContent <- if headless then return $ repeat "" else many1 (notFollowedBy (gridTableSep '=') >> char '|' >> many1Till anyChar newline) if headless then return () else gridTableSep '=' >> return () let lines' = map snd dashes let indices = scanl (+) 0 lines' let aligns = replicate (length lines') AlignDefault -- RST does not have a notion of alignments let rawHeads = if headless then replicate (length dashes) "" else map (unlines . map trim) $ transpose $ map (gridTableSplitLine indices) rawContent heads <- fmap sequence $ mapM (parseFromString parseBlocks . trim) rawHeads return (heads, aligns, indices) gridTableRawLine :: [Int] -> MarkdownParser [String] gridTableRawLine indices = do char '|' line <- many1Till anyChar newline return (gridTableSplitLine indices line) -- | Parse row of grid table. gridTableRow :: [Int] -> MarkdownParser (F [Blocks]) gridTableRow indices = do colLines <- many1 (gridTableRawLine indices) let cols = map ((++ "\n") . unlines . removeOneLeadingSpace) $ transpose colLines fmap compactify' <$> fmap sequence (mapM (parseFromString parseBlocks) cols) removeOneLeadingSpace :: [String] -> [String] removeOneLeadingSpace xs = if all startsWithSpace xs then map (drop 1) xs else xs where startsWithSpace "" = True startsWithSpace (y:_) = y == ' ' -- | Parse footer for a grid table. gridTableFooter :: MarkdownParser [Char] gridTableFooter = blanklines pipeBreak :: MarkdownParser ([Alignment], [Int]) pipeBreak = try $ do nonindentSpaces openPipe <- (True <$ char '|') <|> return False first <- pipeTableHeaderPart rest <- many $ sepPipe *> pipeTableHeaderPart -- surrounding pipes needed for a one-column table: guard $ not (null rest && not openPipe) optional (char '|') blankline return $ unzip (first:rest) pipeTable :: MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) pipeTable = try $ do nonindentSpaces lookAhead nonspaceChar (heads,(aligns, seplengths)) <- (,) <$> pipeTableRow <*> pipeBreak (lines', rawRows) <- unzip <$> many (withRaw pipeTableRow) let maxlength = maximum $ map length rawRows numColumns <- getOption readerColumns let widths = if maxlength > numColumns then map (\len -> fromIntegral (len + 1) / fromIntegral numColumns) seplengths else replicate (length aligns) 0.0 return $ (aligns, widths, heads, sequence lines') sepPipe :: MarkdownParser () sepPipe = try $ do char '|' <|> char '+' notFollowedBy blankline -- parse a row, also returning probable alignments for org-table cells pipeTableRow :: MarkdownParser (F [Blocks]) pipeTableRow = do skipMany spaceChar openPipe <- (True <$ char '|') <|> return False let cell = mconcat <$> many (notFollowedBy (blankline <|> char '|') >> inline) first <- cell rest <- many $ sepPipe *> cell -- surrounding pipes needed for a one-column table: guard $ not (null rest && not openPipe) optional (char '|') blankline let cells = sequence (first:rest) return $ do cells' <- cells return $ map (\ils -> case trimInlines ils of ils' | B.isNull ils' -> mempty | otherwise -> B.plain $ ils') cells' pipeTableHeaderPart :: Parser [Char] st (Alignment, Int) pipeTableHeaderPart = try $ do skipMany spaceChar left <- optionMaybe (char ':') pipe <- many1 (char '-') right <- optionMaybe (char ':') skipMany spaceChar let len = length pipe + maybe 0 (const 1) left + maybe 0 (const 1) right return $ ((case (left,right) of (Nothing,Nothing) -> AlignDefault (Just _,Nothing) -> AlignLeft (Nothing,Just _) -> AlignRight (Just _,Just _) -> AlignCenter), len) -- Succeed only if current line contains a pipe. scanForPipe :: Parser [Char] st () scanForPipe = do inp <- getInput case break (\c -> c == '\n' || c == '|') inp of (_,'|':_) -> return () _ -> mzero -- | Parse a table using 'headerParser', 'rowParser', -- 'lineParser', and 'footerParser'. Variant of the version in -- Text.Pandoc.Parsing. tableWith :: MarkdownParser (F [Blocks], [Alignment], [Int]) -> ([Int] -> MarkdownParser (F [Blocks])) -> MarkdownParser sep -> MarkdownParser end -> MarkdownParser ([Alignment], [Double], F [Blocks], F [[Blocks]]) tableWith headerParser rowParser lineParser footerParser = try $ do (heads, aligns, indices) <- headerParser lines' <- fmap sequence $ rowParser indices `sepEndBy1` lineParser footerParser numColumns <- getOption readerColumns let widths = if (indices == []) then replicate (length aligns) 0.0 else widthsFromIndices numColumns indices return $ (aligns, widths, heads, lines') table :: MarkdownParser (F Blocks) table = try $ do frontCaption <- option Nothing (Just <$> tableCaption) (aligns, widths, heads, lns) <- try (guardEnabled Ext_pipe_tables >> scanForPipe >> pipeTable) <|> try (guardEnabled Ext_multiline_tables >> multilineTable False) <|> try (guardEnabled Ext_simple_tables >> (simpleTable True <|> simpleTable False)) <|> try (guardEnabled Ext_multiline_tables >> multilineTable True) <|> try (guardEnabled Ext_grid_tables >> (gridTable False <|> gridTable True)) <?> "table" optional blanklines caption <- case frontCaption of Nothing -> option (return mempty) tableCaption Just c -> return c return $ do caption' <- caption heads' <- heads lns' <- lns return $ B.table caption' (zip aligns widths) heads' lns' -- -- inline -- inline :: MarkdownParser (F Inlines) inline = choice [ whitespace , bareURL , str , endline , code , strongOrEmph , note , cite , link , image , math , strikeout , subscript , superscript , inlineNote -- after superscript because of ^[link](/foo)^ , autoLink , spanHtml , rawHtmlInline , escapedChar , rawLaTeXInline' , exampleRef , smart , return . B.singleton <$> charRef , emoji , symbol , ltSign ] <?> "inline" escapedChar' :: MarkdownParser Char escapedChar' = try $ do char '\\' (guardEnabled Ext_all_symbols_escapable >> satisfy (not . isAlphaNum)) <|> oneOf "\\`*_{}[]()>#+-.!~\"" escapedChar :: MarkdownParser (F Inlines) escapedChar = do result <- escapedChar' case result of ' ' -> return $ return $ B.str "\160" -- "\ " is a nonbreaking space '\n' -> guardEnabled Ext_escaped_line_breaks >> return (return B.linebreak) -- "\[newline]" is a linebreak _ -> return $ return $ B.str [result] ltSign :: MarkdownParser (F Inlines) ltSign = do guardDisabled Ext_raw_html <|> (notFollowedByHtmlCloser >> notFollowedBy' (htmlTag isBlockTag)) char '<' return $ return $ B.str "<" exampleRef :: MarkdownParser (F Inlines) exampleRef = try $ do guardEnabled Ext_example_lists char '@' lab <- many1 (alphaNum <|> oneOf "-_") return $ do st <- askF return $ case M.lookup lab (stateExamples st) of Just n -> B.str (show n) Nothing -> B.str ('@':lab) symbol :: MarkdownParser (F Inlines) symbol = do result <- noneOf "<\\\n\t " <|> try (do lookAhead $ char '\\' notFollowedBy' (() <$ rawTeXBlock) char '\\') return $ return $ B.str [result] -- parses inline code, between n `s and n `s code :: MarkdownParser (F Inlines) code = try $ do starts <- many1 (char '`') skipSpaces result <- many1Till (many1 (noneOf "`\n") <|> many1 (char '`') <|> (char '\n' >> notFollowedBy' blankline >> return " ")) (try (skipSpaces >> count (length starts) (char '`') >> notFollowedBy (char '`'))) attr <- option ([],[],[]) (try $ guardEnabled Ext_inline_code_attributes >> optional whitespace >> attributes) return $ return $ B.codeWith attr $ trim $ concat result math :: MarkdownParser (F Inlines) math = (return . B.displayMath <$> (mathDisplay >>= applyMacros')) <|> (return . B.math <$> (mathInline >>= applyMacros')) <+?> ((getOption readerSmart >>= guard) *> (return <$> apostrophe) <* notFollowedBy space) -- Parses material enclosed in *s, **s, _s, or __s. -- Designed to avoid backtracking. enclosure :: Char -> MarkdownParser (F Inlines) enclosure c = do -- we can't start an enclosure with _ if after a string and -- the intraword_underscores extension is enabled: guardDisabled Ext_intraword_underscores <|> guard (c == '*') <|> (guard =<< notAfterString) cs <- many1 (char c) (return (B.str cs) <>) <$> whitespace <|> do case length cs of 3 -> three c 2 -> two c mempty 1 -> one c mempty _ -> return (return $ B.str cs) ender :: Char -> Int -> MarkdownParser () ender c n = try $ do count n (char c) guard (c == '*') <|> guardDisabled Ext_intraword_underscores <|> notFollowedBy alphaNum -- Parse inlines til you hit one c or a sequence of two cs. -- If one c, emit emph and then parse two. -- If two cs, emit strong and then parse one. -- Otherwise, emit ccc then the results. three :: Char -> MarkdownParser (F Inlines) three c = do contents <- mconcat <$> many (notFollowedBy (ender c 1) >> inline) (ender c 3 >> return ((B.strong . B.emph) <$> contents)) <|> (ender c 2 >> one c (B.strong <$> contents)) <|> (ender c 1 >> two c (B.emph <$> contents)) <|> return (return (B.str [c,c,c]) <> contents) -- Parse inlines til you hit two c's, and emit strong. -- If you never do hit two cs, emit ** plus inlines parsed. two :: Char -> F Inlines -> MarkdownParser (F Inlines) two c prefix' = do contents <- mconcat <$> many (try $ notFollowedBy (ender c 2) >> inline) (ender c 2 >> return (B.strong <$> (prefix' <> contents))) <|> return (return (B.str [c,c]) <> (prefix' <> contents)) -- Parse inlines til you hit a c, and emit emph. -- If you never hit a c, emit * plus inlines parsed. one :: Char -> F Inlines -> MarkdownParser (F Inlines) one c prefix' = do contents <- mconcat <$> many ( (notFollowedBy (ender c 1) >> inline) <|> try (string [c,c] >> notFollowedBy (ender c 1) >> two c mempty) ) (ender c 1 >> return (B.emph <$> (prefix' <> contents))) <|> return (return (B.str [c]) <> (prefix' <> contents)) strongOrEmph :: MarkdownParser (F Inlines) strongOrEmph = enclosure '*' <|> enclosure '_' -- | Parses a list of inlines between start and end delimiters. inlinesBetween :: (Show b) => MarkdownParser a -> MarkdownParser b -> MarkdownParser (F Inlines) inlinesBetween start end = (trimInlinesF . mconcat) <$> try (start >> many1Till inner end) where inner = innerSpace <|> (notFollowedBy' (() <$ whitespace) >> inline) innerSpace = try $ whitespace <* notFollowedBy' end strikeout :: MarkdownParser (F Inlines) strikeout = fmap B.strikeout <$> (guardEnabled Ext_strikeout >> inlinesBetween strikeStart strikeEnd) where strikeStart = string "~~" >> lookAhead nonspaceChar >> notFollowedBy (char '~') strikeEnd = try $ string "~~" superscript :: MarkdownParser (F Inlines) superscript = fmap B.superscript <$> try (do guardEnabled Ext_superscript char '^' mconcat <$> many1Till (notFollowedBy spaceChar >> inline) (char '^')) subscript :: MarkdownParser (F Inlines) subscript = fmap B.subscript <$> try (do guardEnabled Ext_subscript char '~' mconcat <$> many1Till (notFollowedBy spaceChar >> inline) (char '~')) whitespace :: MarkdownParser (F Inlines) whitespace = spaceChar >> return <$> (lb <|> regsp) <?> "whitespace" where lb = spaceChar >> skipMany spaceChar >> option B.space (endline >> return B.linebreak) regsp = skipMany spaceChar >> return B.space nonEndline :: Parser [Char] st Char nonEndline = satisfy (/='\n') str :: MarkdownParser (F Inlines) str = do result <- many1 alphaNum updateLastStrPos let spacesToNbr = map (\c -> if c == ' ' then '\160' else c) isSmart <- getOption readerSmart if isSmart then case likelyAbbrev result of [] -> return $ return $ B.str result xs -> choice (map (\x -> try (string x >> oneOf " \n" >> lookAhead alphaNum >> return (return $ B.str $ result ++ spacesToNbr x ++ "\160"))) xs) <|> (return $ return $ B.str result) else return $ return $ B.str result -- | if the string matches the beginning of an abbreviation (before -- the first period, return strings that would finish the abbreviation. likelyAbbrev :: String -> [String] likelyAbbrev x = let abbrevs = [ "Mr.", "Mrs.", "Ms.", "Capt.", "Dr.", "Prof.", "Gen.", "Gov.", "e.g.", "i.e.", "Sgt.", "St.", "vol.", "vs.", "Sen.", "Rep.", "Pres.", "Hon.", "Rev.", "Ph.D.", "M.D.", "M.A.", "p.", "pp.", "ch.", "sec.", "cf.", "cp."] abbrPairs = map (break (=='.')) abbrevs in map snd $ filter (\(y,_) -> y == x) abbrPairs -- an endline character that can be treated as a space, not a structural break endline :: MarkdownParser (F Inlines) endline = try $ do newline notFollowedBy blankline -- parse potential list-starts differently if in a list: notFollowedBy (inList >> listStart) guardDisabled Ext_lists_without_preceding_blankline <|> notFollowedBy listStart guardEnabled Ext_blank_before_blockquote <|> notFollowedBy emailBlockQuoteStart guardEnabled Ext_blank_before_header <|> (notFollowedBy . char =<< atxChar) -- atx header guardDisabled Ext_backtick_code_blocks <|> notFollowedBy (() <$ (lookAhead (char '`') >> codeBlockFenced)) notFollowedByHtmlCloser (eof >> return mempty) <|> (guardEnabled Ext_hard_line_breaks >> return (return B.linebreak)) <|> (guardEnabled Ext_ignore_line_breaks >> return mempty) <|> (return $ return B.space) -- -- links -- -- a reference label for a link reference :: MarkdownParser (F Inlines, String) reference = do notFollowedBy' (string "[^") -- footnote reference withRaw $ trimInlinesF <$> inlinesInBalancedBrackets parenthesizedChars :: MarkdownParser [Char] parenthesizedChars = do result <- charsInBalanced '(' ')' litChar return $ '(' : result ++ ")" -- source for a link, with optional title source :: MarkdownParser (String, String) source = do char '(' skipSpaces let urlChunk = try parenthesizedChars <|> (notFollowedBy (oneOf " )") >> (count 1 litChar)) <|> try (many1 spaceChar <* notFollowedBy (oneOf "\"')")) let sourceURL = (unwords . words . concat) <$> many urlChunk let betweenAngles = try $ char '<' >> manyTill litChar (char '>') src <- try betweenAngles <|> sourceURL tit <- option "" $ try $ spnl >> linkTitle skipSpaces char ')' return (escapeURI $ trimr src, tit) linkTitle :: MarkdownParser String linkTitle = quotedTitle '"' <|> quotedTitle '\'' link :: MarkdownParser (F Inlines) link = try $ do st <- getState guard $ stateAllowLinks st setState $ st{ stateAllowLinks = False } (lab,raw) <- reference setState $ st{ stateAllowLinks = True } regLink B.link lab <|> referenceLink B.link (lab,raw) regLink :: (String -> String -> Inlines -> Inlines) -> F Inlines -> MarkdownParser (F Inlines) regLink constructor lab = try $ do (src, tit) <- source return $ constructor src tit <$> lab -- a link like [this][ref] or [this][] or [this] referenceLink :: (String -> String -> Inlines -> Inlines) -> (F Inlines, String) -> MarkdownParser (F Inlines) referenceLink constructor (lab, raw) = do sp <- (True <$ lookAhead (char ' ')) <|> return False (_,raw') <- option (mempty, "") $ lookAhead (try (spnl >> normalCite >> return (mempty, ""))) <|> try (spnl >> reference) when (raw' == "") $ guardEnabled Ext_shortcut_reference_links let labIsRef = raw' == "" || raw' == "[]" let key = toKey $ if labIsRef then raw else raw' parsedRaw <- parseFromString (mconcat <$> many inline) raw' fallback <- parseFromString (mconcat <$> many inline) $ dropBrackets raw implicitHeaderRefs <- option False $ True <$ guardEnabled Ext_implicit_header_references let makeFallback = do parsedRaw' <- parsedRaw fallback' <- fallback return $ B.str "[" <> fallback' <> B.str "]" <> (if sp && not (null raw) then B.space else mempty) <> parsedRaw' return $ do keys <- asksF stateKeys case M.lookup key keys of Nothing -> if implicitHeaderRefs then do headerKeys <- asksF stateHeaderKeys case M.lookup key headerKeys of Just (src, tit) -> constructor src tit <$> lab Nothing -> makeFallback else makeFallback Just (src,tit) -> constructor src tit <$> lab dropBrackets :: String -> String dropBrackets = reverse . dropRB . reverse . dropLB where dropRB (']':xs) = xs dropRB xs = xs dropLB ('[':xs) = xs dropLB xs = xs bareURL :: MarkdownParser (F Inlines) bareURL = try $ do guardEnabled Ext_autolink_bare_uris getState >>= guard . stateAllowLinks (orig, src) <- uri <|> emailAddress notFollowedBy $ try $ spaces >> htmlTag (~== TagClose "a") return $ return $ B.link src "" (B.str orig) autoLink :: MarkdownParser (F Inlines) autoLink = try $ do getState >>= guard . stateAllowLinks char '<' (orig, src) <- uri <|> emailAddress -- in rare cases, something may remain after the uri parser -- is finished, because the uri parser tries to avoid parsing -- final punctuation. for example: in `<http://hi---there>`, -- the URI parser will stop before the dashes. extra <- fromEntities <$> manyTill nonspaceChar (char '>') return $ return $ B.link (src ++ escapeURI extra) "" (B.str $ orig ++ extra) image :: MarkdownParser (F Inlines) image = try $ do char '!' (lab,raw) <- reference defaultExt <- getOption readerDefaultImageExtension let constructor src = case takeExtension src of "" -> B.image (addExtension src defaultExt) _ -> B.image src regLink constructor lab <|> referenceLink constructor (lab,raw) note :: MarkdownParser (F Inlines) note = try $ do guardEnabled Ext_footnotes ref <- noteMarker return $ do notes <- asksF stateNotes' case lookup ref notes of Nothing -> return $ B.str $ "[^" ++ ref ++ "]" Just contents -> do st <- askF -- process the note in a context that doesn't resolve -- notes, to avoid infinite looping with notes inside -- notes: let contents' = runF contents st{ stateNotes' = [] } return $ B.note contents' inlineNote :: MarkdownParser (F Inlines) inlineNote = try $ do guardEnabled Ext_inline_notes char '^' contents <- inlinesInBalancedBrackets return $ B.note . B.para <$> contents rawLaTeXInline' :: MarkdownParser (F Inlines) rawLaTeXInline' = try $ do guardEnabled Ext_raw_tex lookAhead $ char '\\' >> notFollowedBy' (string "start") -- context env RawInline _ s <- rawLaTeXInline return $ return $ B.rawInline "tex" s -- "tex" because it might be context or latex rawConTeXtEnvironment :: Parser [Char] st String rawConTeXtEnvironment = try $ do string "\\start" completion <- inBrackets (letter <|> digit <|> spaceChar) <|> (many1 letter) contents <- manyTill (rawConTeXtEnvironment <|> (count 1 anyChar)) (try $ string "\\stop" >> string completion) return $ "\\start" ++ completion ++ concat contents ++ "\\stop" ++ completion inBrackets :: (Parser [Char] st Char) -> Parser [Char] st String inBrackets parser = do char '[' contents <- many parser char ']' return $ "[" ++ contents ++ "]" spanHtml :: MarkdownParser (F Inlines) spanHtml = try $ do guardEnabled Ext_native_spans (TagOpen _ attrs, _) <- htmlTag (~== TagOpen "span" []) contents <- mconcat <$> manyTill inline (htmlTag (~== TagClose "span")) let ident = fromMaybe "" $ lookup "id" attrs let classes = maybe [] words $ lookup "class" attrs let keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"] case lookup "style" keyvals of Just s | null ident && null classes && map toLower (filter (`notElem` " \t;") s) == "font-variant:small-caps" -> return $ B.smallcaps <$> contents _ -> return $ B.spanWith (ident, classes, keyvals) <$> contents divHtml :: MarkdownParser (F Blocks) divHtml = try $ do guardEnabled Ext_native_divs (TagOpen _ attrs, rawtag) <- htmlTag (~== TagOpen "div" []) -- we set stateInHtmlBlock so that closing tags that can be either block or -- inline will not be parsed as inline tags oldInHtmlBlock <- stateInHtmlBlock <$> getState updateState $ \st -> st{ stateInHtmlBlock = Just "div" } bls <- option "" (blankline >> option "" blanklines) contents <- mconcat <$> many (notFollowedBy' (htmlTag (~== TagClose "div")) >> block) closed <- option False (True <$ htmlTag (~== TagClose "div")) if closed then do updateState $ \st -> st{ stateInHtmlBlock = oldInHtmlBlock } let ident = fromMaybe "" $ lookup "id" attrs let classes = maybe [] words $ lookup "class" attrs let keyvals = [(k,v) | (k,v) <- attrs, k /= "id" && k /= "class"] return $ B.divWith (ident, classes, keyvals) <$> contents else -- avoid backtracing return $ return (B.rawBlock "html" (rawtag <> bls)) <> contents rawHtmlInline :: MarkdownParser (F Inlines) rawHtmlInline = do guardEnabled Ext_raw_html inHtmlBlock <- stateInHtmlBlock <$> getState let isCloseBlockTag t = case inHtmlBlock of Just t' -> t ~== TagClose t' Nothing -> False mdInHtml <- option False $ ( guardEnabled Ext_markdown_in_html_blocks <|> guardEnabled Ext_markdown_attribute ) >> return True (_,result) <- htmlTag $ if mdInHtml then (\x -> isInlineTag x && not (isCloseBlockTag x)) else not . isTextTag return $ return $ B.rawInline "html" result -- Emoji emojiChars :: [Char] emojiChars = ['a'..'z'] ++ ['0'..'9'] ++ ['_','+','-'] emoji :: MarkdownParser (F Inlines) emoji = try $ do guardEnabled Ext_emoji char ':' emojikey <- many1 (oneOf emojiChars) char ':' case M.lookup emojikey emojis of Just s -> return (return (B.str s)) Nothing -> mzero -- Citations cite :: MarkdownParser (F Inlines) cite = do guardEnabled Ext_citations citations <- textualCite <|> do (cs, raw) <- withRaw normalCite return $ (flip B.cite (B.text raw)) <$> cs return citations textualCite :: MarkdownParser (F Inlines) textualCite = try $ do (_, key) <- citeKey let first = Citation{ citationId = key , citationPrefix = [] , citationSuffix = [] , citationMode = AuthorInText , citationNoteNum = 0 , citationHash = 0 } mbrest <- option Nothing $ try $ spnl >> Just <$> withRaw normalCite case mbrest of Just (rest, raw) -> return $ (flip B.cite (B.text $ '@':key ++ " " ++ raw) . (first:)) <$> rest Nothing -> (do (cs, raw) <- withRaw $ bareloc first let (spaces',raw') = span isSpace raw spc | null spaces' = mempty | otherwise = B.space lab <- parseFromString (mconcat <$> many inline) $ dropBrackets raw' fallback <- referenceLink B.link (lab,raw') return $ do fallback' <- fallback cs' <- cs return $ case B.toList fallback' of Link{}:_ -> B.cite [first] (B.str $ '@':key) <> spc <> fallback' _ -> B.cite cs' (B.text $ '@':key ++ " " ++ raw)) <|> return (do st <- askF return $ case M.lookup key (stateExamples st) of Just n -> B.str (show n) _ -> B.cite [first] $ B.str $ '@':key) bareloc :: Citation -> MarkdownParser (F [Citation]) bareloc c = try $ do spnl char '[' notFollowedBy $ char '^' suff <- suffix rest <- option (return []) $ try $ char ';' >> citeList spnl char ']' notFollowedBy $ oneOf "[(" return $ do suff' <- suff rest' <- rest return $ c{ citationSuffix = B.toList suff' } : rest' normalCite :: MarkdownParser (F [Citation]) normalCite = try $ do char '[' spnl citations <- citeList spnl char ']' return citations suffix :: MarkdownParser (F Inlines) suffix = try $ do hasSpace <- option False (notFollowedBy nonspaceChar >> return True) spnl rest <- trimInlinesF . mconcat <$> many (notFollowedBy (oneOf ";]") >> inline) return $ if hasSpace then (B.space <>) <$> rest else rest prefix :: MarkdownParser (F Inlines) prefix = trimInlinesF . mconcat <$> manyTill inline (char ']' <|> liftM (const ']') (lookAhead citeKey)) citeList :: MarkdownParser (F [Citation]) citeList = fmap sequence $ sepBy1 citation (try $ char ';' >> spnl) citation :: MarkdownParser (F Citation) citation = try $ do pref <- prefix (suppress_author, key) <- citeKey suff <- suffix return $ do x <- pref y <- suff return $ Citation{ citationId = key , citationPrefix = B.toList x , citationSuffix = B.toList y , citationMode = if suppress_author then SuppressAuthor else NormalCitation , citationNoteNum = 0 , citationHash = 0 } smart :: MarkdownParser (F Inlines) smart = do getOption readerSmart >>= guard doubleQuoted <|> singleQuoted <|> choice (map (return <$>) [apostrophe, dash, ellipses]) singleQuoted :: MarkdownParser (F Inlines) singleQuoted = try $ do singleQuoteStart withQuoteContext InSingleQuote $ fmap B.singleQuoted . trimInlinesF . mconcat <$> many1Till inline singleQuoteEnd -- doubleQuoted will handle regular double-quoted sections, as well -- as dialogues with an open double-quote without a close double-quote -- in the same paragraph. doubleQuoted :: MarkdownParser (F Inlines) doubleQuoted = try $ do doubleQuoteStart contents <- mconcat <$> many (try $ notFollowedBy doubleQuoteEnd >> inline) (withQuoteContext InDoubleQuote $ doubleQuoteEnd >> return (fmap B.doubleQuoted . trimInlinesF $ contents)) <|> (return $ return (B.str "\8220") <> contents)
alexvong1995/pandoc
src/Text/Pandoc/Readers/Markdown.hs
gpl-2.0
74,433
0
28
20,763
21,971
10,854
11,117
1,644
7
{-# LANGUAGE TemplateHaskell #-} module Lambda.Backward_Join.Solution where import Lambda.Type import Autolib.ToDoc import Autolib.Reader import Data.Typeable data Type = Make { start :: Lambda , left_steps :: [ Int ] , right_steps :: [ Int ] } deriving ( Typeable, Eq, Ord ) $(derives [makeReader, makeToDoc] [''Type]) example :: Type example = Make { start = read "(x -> x x)( x -> x x)" , left_steps = [0] , right_steps = [1] } -- local variables: -- mode: haskell -- end;
florianpilz/autotool
src/Lambda/Backward_Join/Solution.hs
gpl-2.0
560
0
9
165
141
86
55
17
1
{-# OPTIONS_GHC -F -pgmF htfpp #-} module GameTest where import Test.Framework prop_reverse :: [Int] -> Bool prop_reverse xs = xs == (reverse (reverse xs))
abailly/hsgames
acquire/test/GameTest.hs
apache-2.0
168
0
9
36
46
26
20
5
1
{-# LANGUAGE TemplateHaskell #-} {-| Implementation of the Ganeti LUXI interface. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.Luxi ( LuxiOp(..) , LuxiReq(..) , Client , Server , JobId , fromJobId , makeJobId , RecvResult(..) , strOfOp , opToArgs , getLuxiClient , getLuxiServer , acceptClient , closeClient , closeServer , callMethod , submitManyJobs , queryJobsStatus , buildCall , buildResponse , decodeLuxiCall , recvMsg , recvMsgExt , sendMsg , allLuxiCalls ) where import Control.Applicative (optional, liftA, (<|>)) import Control.Monad import qualified Text.JSON as J import Text.JSON.Pretty (pp_value) import Text.JSON.Types import Ganeti.BasicTypes import Ganeti.Constants import Ganeti.Errors import Ganeti.JSON (fromJResult, fromJVal, Tuple5(..), MaybeForJSON(..), TimeAsDoubleJSON(..)) import Ganeti.UDSServer import Ganeti.Objects import Ganeti.OpParams (pTagsObject) import Ganeti.OpCodes import qualified Ganeti.Query.Language as Qlang import Ganeti.Runtime (GanetiDaemon(..), GanetiGroup(..), MiscGroup(..)) import Ganeti.THH import Ganeti.THH.Field import Ganeti.THH.Types (getOneTuple) import Ganeti.Types import Ganeti.Utils -- | Currently supported Luxi operations and JSON serialization. $(genLuxiOp "LuxiOp" [ (luxiReqQuery, [ simpleField "what" [t| Qlang.ItemType |] , simpleField "fields" [t| [String] |] , simpleField "qfilter" [t| Qlang.Filter Qlang.FilterField |] ]) , (luxiReqQueryFields, [ simpleField "what" [t| Qlang.ItemType |] , simpleField "fields" [t| [String] |] ]) , (luxiReqQueryNodes, [ simpleField "names" [t| [String] |] , simpleField "fields" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryGroups, [ simpleField "names" [t| [String] |] , simpleField "fields" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryNetworks, [ simpleField "names" [t| [String] |] , simpleField "fields" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryInstances, [ simpleField "names" [t| [String] |] , simpleField "fields" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryFilters, [ simpleField "uuids" [t| [String] |] , simpleField "fields" [t| [String] |] ]) , (luxiReqReplaceFilter, -- UUID is missing for insert, present for upsert [ optionalNullSerField $ simpleField "uuid" [t| String |] , simpleField "priority" [t| NonNegative Int |] , simpleField "predicates" [t| [FilterPredicate] |] , simpleField "action" [t| FilterAction |] , simpleField "reason" [t| ReasonTrail |] ]) , (luxiReqDeleteFilter, [ simpleField "uuid" [t| String |] ]) , (luxiReqQueryJobs, [ simpleField "ids" [t| [JobId] |] , simpleField "fields" [t| [String] |] ]) , (luxiReqQueryExports, [ simpleField "nodes" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryConfigValues, [ simpleField "fields" [t| [String] |] ] ) , (luxiReqQueryClusterInfo, []) , (luxiReqQueryTags, [ pTagsObject , simpleField "name" [t| String |] ]) , (luxiReqSubmitJob, [ simpleField "job" [t| [MetaOpCode] |] ] ) , (luxiReqSubmitJobToDrainedQueue, [ simpleField "job" [t| [MetaOpCode] |] ] ) , (luxiReqSubmitManyJobs, [ simpleField "ops" [t| [[MetaOpCode]] |] ] ) , (luxiReqWaitForJobChange, [ simpleField "job" [t| JobId |] , simpleField "fields" [t| [String]|] , simpleField "prev_job" [t| JSValue |] , simpleField "prev_log" [t| JSValue |] , simpleField "tmout" [t| Int |] ]) , (luxiReqPickupJob, [ simpleField "job" [t| JobId |] ] ) , (luxiReqArchiveJob, [ simpleField "job" [t| JobId |] ] ) , (luxiReqAutoArchiveJobs, [ simpleField "age" [t| Int |] , simpleField "tmout" [t| Int |] ]) , (luxiReqCancelJob, [ simpleField "job" [t| JobId |] , simpleField "kill" [t| Bool |] ]) , (luxiReqChangeJobPriority, [ simpleField "job" [t| JobId |] , simpleField "priority" [t| Int |] ] ) , (luxiReqSetDrainFlag, [ simpleField "flag" [t| Bool |] ] ) , (luxiReqSetWatcherPause, [ optionalNullSerField $ timeAsDoubleField "duration" ] ) ]) $(makeJSONInstance ''LuxiReq) -- | List of all defined Luxi calls. $(genAllConstr (drop 3) ''LuxiReq "allLuxiCalls") -- | The serialisation of LuxiOps into strings in messages. $(genStrOfOp ''LuxiOp "strOfOp") luxiConnectConfig :: ServerConfig luxiConnectConfig = ServerConfig -- The rapi daemon talks to the luxi one, and for this -- purpose we need group rw permissions. FilePermissions { fpOwner = Just GanetiLuxid , fpGroup = Just $ ExtraGroup DaemonsGroup , fpPermissions = 0o0660 } ConnectConfig { recvTmo = luxiDefRwto , sendTmo = luxiDefRwto } -- | Connects to the master daemon and returns a luxi Client. getLuxiClient :: String -> IO Client getLuxiClient = connectClient (connConfig luxiConnectConfig) luxiDefCtmo -- | Creates and returns a server endpoint. getLuxiServer :: Bool -> FilePath -> IO Server getLuxiServer = connectServer luxiConnectConfig -- | Converts Luxi call arguments into a 'LuxiOp' data structure. -- This is used for building a Luxi 'Handler'. -- -- This is currently hand-coded until we make it more uniform so that -- it can be generated using TH. decodeLuxiCall :: JSValue -> JSValue -> Result LuxiOp decodeLuxiCall method args = do call <- fromJResult "Unable to parse LUXI request method" $ J.readJSON method case call of ReqQueryFilters -> do (uuids, fields) <- fromJVal args uuids' <- case uuids of JSNull -> return [] _ -> fromJVal uuids return $ QueryFilters uuids' fields ReqReplaceFilter -> do Tuple5 ( uuid , priority , predicates , action , reason) <- fromJVal args return $ ReplaceFilter (unMaybeForJSON uuid) priority predicates action reason ReqDeleteFilter -> do [uuid] <- fromJVal args return $ DeleteFilter uuid ReqQueryJobs -> do (jids, jargs) <- fromJVal args jids' <- case jids of JSNull -> return [] _ -> fromJVal jids return $ QueryJobs jids' jargs ReqQueryInstances -> do (names, fields, locking) <- fromJVal args return $ QueryInstances names fields locking ReqQueryNodes -> do (names, fields, locking) <- fromJVal args return $ QueryNodes names fields locking ReqQueryGroups -> do (names, fields, locking) <- fromJVal args return $ QueryGroups names fields locking ReqQueryClusterInfo -> return QueryClusterInfo ReqQueryNetworks -> do (names, fields, locking) <- fromJVal args return $ QueryNetworks names fields locking ReqQuery -> do (what, fields, qfilter) <- fromJVal args return $ Query what fields qfilter ReqQueryFields -> do (what, fields) <- fromJVal args fields' <- case fields of JSNull -> return [] _ -> fromJVal fields return $ QueryFields what fields' ReqSubmitJob -> do [ops1] <- fromJVal args ops2 <- mapM (fromJResult (luxiReqToRaw call) . J.readJSON) ops1 return $ SubmitJob ops2 ReqSubmitJobToDrainedQueue -> do [ops1] <- fromJVal args ops2 <- mapM (fromJResult (luxiReqToRaw call) . J.readJSON) ops1 return $ SubmitJobToDrainedQueue ops2 ReqSubmitManyJobs -> do [ops1] <- fromJVal args ops2 <- mapM (fromJResult (luxiReqToRaw call) . J.readJSON) ops1 return $ SubmitManyJobs ops2 ReqWaitForJobChange -> do (jid, fields, pinfo, pidx, wtmout) <- -- No instance for 5-tuple, code copied from the -- json sources and adapted fromJResult "Parsing WaitForJobChange message" $ case args of JSArray [a, b, c, d, e] -> (,,,,) `fmap` J.readJSON a `ap` J.readJSON b `ap` J.readJSON c `ap` J.readJSON d `ap` J.readJSON e _ -> J.Error "Not enough values" return $ WaitForJobChange jid fields pinfo pidx wtmout ReqPickupJob -> do [jid] <- fromJVal args return $ PickupJob jid ReqArchiveJob -> do [jid] <- fromJVal args return $ ArchiveJob jid ReqAutoArchiveJobs -> do (age, tmout) <- fromJVal args return $ AutoArchiveJobs age tmout ReqQueryExports -> do (nodes, lock) <- fromJVal args return $ QueryExports nodes lock ReqQueryConfigValues -> do [fields] <- fromJVal args return $ QueryConfigValues fields ReqQueryTags -> do (kind, name) <- fromJVal args return $ QueryTags kind name ReqCancelJob -> do (jid, kill) <- fromJVal args <|> liftA (flip (,) False . getOneTuple) (fromJVal args) return $ CancelJob jid kill ReqChangeJobPriority -> do (jid, priority) <- fromJVal args return $ ChangeJobPriority jid priority ReqSetDrainFlag -> do [flag] <- fromJVal args return $ SetDrainFlag flag ReqSetWatcherPause -> do duration <- optional $ do [x] <- fromJVal args liftM unTimeAsDoubleJSON $ fromJVal x return $ SetWatcherPause duration -- | Generic luxi method call callMethod :: LuxiOp -> Client -> IO (ErrorResult JSValue) callMethod method s = do sendMsg s $ buildCall (strOfOp method) (opToArgs method) result <- recvMsg s return $ parseResponse result -- | Parse job submission result. parseSubmitJobResult :: JSValue -> ErrorResult JobId parseSubmitJobResult (JSArray [JSBool True, v]) = case J.readJSON v of J.Error msg -> Bad $ LuxiError msg J.Ok v' -> Ok v' parseSubmitJobResult (JSArray [JSBool False, JSString x]) = Bad . LuxiError $ fromJSString x parseSubmitJobResult v = Bad . LuxiError $ "Unknown result from the master daemon: " ++ show (pp_value v) -- | Specialized submitManyJobs call. submitManyJobs :: Client -> [[MetaOpCode]] -> IO (ErrorResult [JobId]) submitManyJobs s jobs = do rval <- callMethod (SubmitManyJobs jobs) s -- map each result (status, payload) pair into a nice Result ADT return $ case rval of Bad x -> Bad x Ok (JSArray r) -> mapM parseSubmitJobResult r x -> Bad . LuxiError $ "Cannot parse response from Ganeti: " ++ show x -- | Custom queryJobs call. queryJobsStatus :: Client -> [JobId] -> IO (ErrorResult [JobStatus]) queryJobsStatus s jids = do rval <- callMethod (QueryJobs jids ["status"]) s return $ case rval of Bad x -> Bad x Ok y -> case J.readJSON y::(J.Result [[JobStatus]]) of J.Ok vals -> if any null vals then Bad $ LuxiError "Missing job status field" else Ok (map head vals) J.Error x -> Bad $ LuxiError x
mbakke/ganeti
src/Ganeti/Luxi.hs
bsd-2-clause
13,584
0
23
4,301
3,060
1,681
1,379
284
29
module Tandoori.GHC.Internals (module SrcLoc, module Outputable, module Name, module BasicTypes, module Unique, module FastString, module HsExpr, module HsTypes, module HsPat, module HsLit, module HsBinds, module DataCon, module TysWiredIn, module PrelNames, module HsDecls, module Module) where import SrcLoc import Outputable import Name import BasicTypes import Unique import FastString import HsExpr import HsTypes import HsPat import HsLit import HsBinds import DataCon (dataConName) import TysWiredIn (intTyConName, charTyConName, boolTyConName, listTyConName, tupleTyCon, nilDataCon, consDataCon, trueDataCon, falseDataCon) import PrelNames (stringTyConName, eqClassName, ordClassName, numClassName, fractionalClassName) import HsDecls import Module
bitemyapp/tandoori
src/Tandoori/GHC/Internals.hs
bsd-3-clause
845
0
5
170
172
119
53
33
0
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1997-1998 Author: Juan J. Quintela <[email protected]> -} {-# LANGUAGE CPP #-} module ETA.DeSugar.Check ( check , ExhaustivePat ) where import ETA.HsSyn.HsSyn import ETA.TypeCheck.TcHsSyn import ETA.DeSugar.DsUtils import ETA.DeSugar.MatchLit import ETA.BasicTypes.Id import ETA.BasicTypes.ConLike import ETA.BasicTypes.DataCon import ETA.BasicTypes.PatSyn import ETA.BasicTypes.Name import ETA.Prelude.TysWiredIn import ETA.Prelude.PrelNames import ETA.Types.TyCon import ETA.BasicTypes.SrcLoc import ETA.Utils.UniqSet import ETA.Utils.Util import ETA.BasicTypes.BasicTypes import ETA.Utils.Outputable import ETA.Utils.FastString #include "HsVersions.h" {- This module performs checks about if one list of equations are: \begin{itemize} \item Overlapped \item Non exhaustive \end{itemize} To discover that we go through the list of equations in a tree-like fashion. If you like theory, a similar algorithm is described in: \begin{quotation} {\em Two Techniques for Compiling Lazy Pattern Matching}, Luc Maranguet, INRIA Rocquencourt (RR-2385, 1994) \end{quotation} The algorithm is based on the first technique, but there are some differences: \begin{itemize} \item We don't generate code \item We have constructors and literals (not only literals as in the article) \item We don't use directions, we must select the columns from left-to-right \end{itemize} (By the way the second technique is really similar to the one used in @Match.lhs@ to generate code) This function takes the equations of a pattern and returns: \begin{itemize} \item The patterns that are not recognized \item The equations that are not overlapped \end{itemize} It simplify the patterns and then call @check'@ (the same semantics), and it needs to reconstruct the patterns again .... The problem appear with things like: \begin{verbatim} f [x,y] = .... f (x:xs) = ..... \end{verbatim} We want to put the two patterns with the same syntax, (prefix form) and then all the constructors are equal: \begin{verbatim} f (: x (: y [])) = .... f (: x xs) = ..... \end{verbatim} (more about that in @tidy_eqns@) We would prefer to have a @WarningPat@ of type @String@, but Strings and the Pretty Printer are not friends. We use @InPat@ in @WarningPat@ instead of @OutPat@ because we need to print the warning messages in the same way they are introduced, i.e. if the user wrote: \begin{verbatim} f [x,y] = .. \end{verbatim} He don't want a warning message written: \begin{verbatim} f (: x (: y [])) ........ \end{verbatim} Then we need to use InPats. \begin{quotation} Juan Quintela 5 JUL 1998\\ User-friendliness and compiler writers are no friends. \end{quotation} -} type WarningPat = InPat Name type ExhaustivePat = ([WarningPat], [(Name, [HsLit])]) type EqnNo = Int type EqnSet = UniqSet EqnNo check :: [EquationInfo] -> ([ExhaustivePat], [EquationInfo]) -- Second result is the shadowed equations -- if there are view patterns, just give up - don't know what the function is check qs = (untidy_warns, shadowed_eqns) where tidy_qs = map tidy_eqn qs (warns, used_nos) = check' ([1..] `zip` tidy_qs) untidy_warns = map untidy_exhaustive warns shadowed_eqns = [eqn | (eqn,i) <- qs `zip` [1..], not (i `elementOfUniqSet` used_nos)] untidy_exhaustive :: ExhaustivePat -> ExhaustivePat untidy_exhaustive ([pat], messages) = ([untidy_no_pars pat], map untidy_message messages) untidy_exhaustive (pats, messages) = (map untidy_pars pats, map untidy_message messages) untidy_message :: (Name, [HsLit]) -> (Name, [HsLit]) untidy_message (string, lits) = (string, map untidy_lit lits) -- The function @untidy@ does the reverse work of the @tidy_pat@ function. type NeedPars = Bool untidy_no_pars :: WarningPat -> WarningPat untidy_no_pars p = untidy False p untidy_pars :: WarningPat -> WarningPat untidy_pars p = untidy True p untidy :: NeedPars -> WarningPat -> WarningPat untidy b (L loc p) = L loc (untidy' b p) where untidy' _ p@(WildPat _) = p untidy' _ p@(VarPat _) = p untidy' _ (LitPat lit) = LitPat (untidy_lit lit) untidy' _ p@(ConPatIn _ (PrefixCon [])) = p untidy' b (ConPatIn name ps) = pars b (L loc (ConPatIn name (untidy_con ps))) untidy' _ (ListPat pats ty Nothing) = ListPat (map untidy_no_pars pats) ty Nothing untidy' _ (TuplePat pats box tys) = TuplePat (map untidy_no_pars pats) box tys untidy' _ (ListPat _ _ (Just _)) = panic "Check.untidy: Overloaded ListPat" untidy' _ (PArrPat _ _) = panic "Check.untidy: Shouldn't get a parallel array here!" untidy' _ (SigPatIn _ _) = panic "Check.untidy: SigPat" untidy' _ (LazyPat {}) = panic "Check.untidy: LazyPat" untidy' _ (AsPat {}) = panic "Check.untidy: AsPat" untidy' _ (ParPat {}) = panic "Check.untidy: ParPat" untidy' _ (BangPat {}) = panic "Check.untidy: BangPat" untidy' _ (ConPatOut {}) = panic "Check.untidy: ConPatOut" untidy' _ (ViewPat {}) = panic "Check.untidy: ViewPat" untidy' _ (SplicePat {}) = panic "Check.untidy: SplicePat" untidy' _ (QuasiQuotePat {}) = panic "Check.untidy: QuasiQuotePat" untidy' _ (NPat {}) = panic "Check.untidy: NPat" untidy' _ (NPlusKPat {}) = panic "Check.untidy: NPlusKPat" untidy' _ (SigPatOut {}) = panic "Check.untidy: SigPatOut" untidy' _ (CoPat {}) = panic "Check.untidy: CoPat" untidy_con :: HsConPatDetails Name -> HsConPatDetails Name untidy_con (PrefixCon pats) = PrefixCon (map untidy_pars pats) untidy_con (InfixCon p1 p2) = InfixCon (untidy_pars p1) (untidy_pars p2) untidy_con (RecCon (HsRecFields flds dd)) = RecCon (HsRecFields [ L l (fld { hsRecFieldArg = untidy_pars (hsRecFieldArg fld) }) | L l fld <- flds ] dd) pars :: NeedPars -> WarningPat -> Pat Name pars True p = ParPat p pars _ p = unLoc p untidy_lit :: HsLit -> HsLit untidy_lit (HsCharPrim src c) = HsChar src c untidy_lit lit = lit {- This equation is the same that check, the only difference is that the boring work is done, that work needs to be done only once, this is the reason top have two functions, check is the external interface, @check'@ is called recursively. There are several cases: \begin{itemize} \item There are no equations: Everything is OK. \item There are only one equation, that can fail, and all the patterns are variables. Then that equation is used and the same equation is non-exhaustive. \item All the patterns are variables, and the match can fail, there are more equations then the results is the result of the rest of equations and this equation is used also. \item The general case, if all the patterns are variables (here the match can't fail) then the result is that this equation is used and this equation doesn't generate non-exhaustive cases. \item In the general case, there can exist literals ,constructors or only vars in the first column, we actuate in consequence. \end{itemize} -} check' :: [(EqnNo, EquationInfo)] -> ([ExhaustivePat], -- Pattern scheme that might not be matched at all EqnSet) -- Eqns that are used (others are overlapped) check' [] = ([],emptyUniqSet) -- Was ([([],[])], emptyUniqSet) -- But that (a) seems weird, and (b) triggered Trac #7669 -- So now I'm just doing the simple obvious thing check' ((n, EqnInfo { eqn_pats = ps, eqn_rhs = MatchResult can_fail _ }) : rs) | first_eqn_all_vars && case can_fail of { CantFail -> True; CanFail -> False } = ([], unitUniqSet n) -- One eqn, which can't fail | first_eqn_all_vars && null rs -- One eqn, but it can fail = ([(takeList ps (repeat nlWildPatName),[])], unitUniqSet n) | first_eqn_all_vars -- Several eqns, first can fail = (pats, addOneToUniqSet indexs n) where first_eqn_all_vars = all_vars ps (pats,indexs) = check' rs check' qs | some_literals = split_by_literals qs | some_constructors = split_by_constructor qs | only_vars = first_column_only_vars qs | otherwise = pprPanic "Check.check': Not implemented :-(" (ppr first_pats) -- Shouldn't happen where -- Note: RecPats will have been simplified to ConPats -- at this stage. first_pats = ASSERT2( okGroup qs, pprGroup qs ) map firstPatN qs some_constructors = any is_con first_pats some_literals = any is_lit first_pats only_vars = all is_var first_pats {- Here begins the code to deal with literals, we need to split the matrix in different matrix beginning by each literal and a last matrix with the rest of values. -} split_by_literals :: [(EqnNo, EquationInfo)] -> ([ExhaustivePat], EqnSet) split_by_literals qs = process_literals used_lits qs where used_lits = get_used_lits qs {- @process_explicit_literals@ is a function that process each literal that appears in the column of the matrix. -} process_explicit_literals :: [HsLit] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet) process_explicit_literals lits qs = (concat pats, unionManyUniqSets indexs) where pats_indexs = map (\x -> construct_literal_matrix x qs) lits (pats,indexs) = unzip pats_indexs {- @process_literals@ calls @process_explicit_literals@ to deal with the literals that appears in the matrix and deal also with the rest of the cases. It must be one Variable to be complete. -} process_literals :: [HsLit] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet) process_literals used_lits qs | null default_eqns = ASSERT( not (null qs) ) ([make_row_vars used_lits (head qs)] ++ pats,indexs) | otherwise = (pats_default,indexs_default) where (pats,indexs) = process_explicit_literals used_lits qs default_eqns = ASSERT2( okGroup qs, pprGroup qs ) [remove_var q | q <- qs, is_var (firstPatN q)] (pats',indexs') = check' default_eqns pats_default = [(nlWildPatName:ps,constraints) | (ps,constraints) <- (pats')] ++ pats indexs_default = unionUniqSets indexs' indexs {- Here we have selected the literal and we will select all the equations that begins for that literal and create a new matrix. -} construct_literal_matrix :: HsLit -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet) construct_literal_matrix lit qs = (map (\ (xs,ys) -> (new_lit:xs,ys)) pats,indexs) where (pats,indexs) = (check' (remove_first_column_lit lit qs)) new_lit = nlLitPat lit remove_first_column_lit :: HsLit -> [(EqnNo, EquationInfo)] -> [(EqnNo, EquationInfo)] remove_first_column_lit lit qs = ASSERT2( okGroup qs, pprGroup qs ) [(n, shift_pat eqn) | q@(n,eqn) <- qs, is_var_lit lit (firstPatN q)] where shift_pat eqn@(EqnInfo { eqn_pats = _:ps}) = eqn { eqn_pats = ps } shift_pat _ = panic "Check.shift_var: no patterns" {- This function splits the equations @qs@ in groups that deal with the same constructor. -} split_by_constructor :: [(EqnNo, EquationInfo)] -> ([ExhaustivePat], EqnSet) split_by_constructor qs | null used_cons = ([], mkUniqSet $ map fst qs) | notNull unused_cons = need_default_case used_cons unused_cons qs | otherwise = no_need_default_case used_cons qs where used_cons = get_used_cons qs unused_cons = get_unused_cons used_cons {- The first column of the patterns matrix only have vars, then there is nothing to do. -} first_column_only_vars :: [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet) first_column_only_vars qs = (map (\ (xs,ys) -> (nlWildPatName:xs,ys)) pats,indexs) where (pats, indexs) = check' (map remove_var qs) {- This equation takes a matrix of patterns and split the equations by constructor, using all the constructors that appears in the first column of the pattern matching. We can need a default clause or not ...., it depends if we used all the constructors or not explicitly. The reasoning is similar to @process_literals@, the difference is that here the default case is not always needed. -} no_need_default_case :: [Pat Id] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet) no_need_default_case cons qs = (concat pats, unionManyUniqSets indexs) where pats_indexs = map (\x -> construct_matrix x qs) cons (pats,indexs) = unzip pats_indexs need_default_case :: [Pat Id] -> [DataCon] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet) need_default_case used_cons unused_cons qs | null default_eqns = (pats_default_no_eqns,indexs) | otherwise = (pats_default,indexs_default) where (pats,indexs) = no_need_default_case used_cons qs default_eqns = ASSERT2( okGroup qs, pprGroup qs ) [remove_var q | q <- qs, is_var (firstPatN q)] (pats',indexs') = check' default_eqns pats_default = [(make_whole_con c:ps,constraints) | c <- unused_cons, (ps,constraints) <- pats'] ++ pats new_wilds = ASSERT( not (null qs) ) make_row_vars_for_constructor (head qs) pats_default_no_eqns = [(make_whole_con c:new_wilds,[]) | c <- unused_cons] ++ pats indexs_default = unionUniqSets indexs' indexs construct_matrix :: Pat Id -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet) construct_matrix con qs = (map (make_con con) pats,indexs) where (pats,indexs) = (check' (remove_first_column con qs)) {- Here remove first column is more difficult that with literals due to the fact that constructors can have arguments. For instance, the matrix \begin{verbatim} (: x xs) y z y \end{verbatim} is transformed in: \begin{verbatim} x xs y _ _ y \end{verbatim} -} remove_first_column :: Pat Id -- Constructor -> [(EqnNo, EquationInfo)] -> [(EqnNo, EquationInfo)] remove_first_column (ConPatOut{ pat_con = L _ con, pat_args = PrefixCon con_pats }) qs = ASSERT2( okGroup qs, pprGroup qs ) [(n, shift_var eqn) | q@(n, eqn) <- qs, is_var_con con (firstPatN q)] where new_wilds = [WildPat (hsLPatType arg_pat) | arg_pat <- con_pats] shift_var eqn@(EqnInfo { eqn_pats = ConPatOut{ pat_args = PrefixCon ps' } : ps}) = eqn { eqn_pats = map unLoc ps' ++ ps } shift_var eqn@(EqnInfo { eqn_pats = WildPat _ : ps }) = eqn { eqn_pats = new_wilds ++ ps } shift_var _ = panic "Check.Shift_var:No done" remove_first_column _ _ = panic "Check.remove_first_column: Not ConPatOut" make_row_vars :: [HsLit] -> (EqnNo, EquationInfo) -> ExhaustivePat make_row_vars used_lits (_, EqnInfo { eqn_pats = pats}) = (nlVarPat new_var:takeList (tail pats) (repeat nlWildPatName) ,[(new_var,used_lits)]) where new_var = hash_x hash_x :: Name hash_x = mkInternalName unboundKey {- doesn't matter much -} (mkVarOccFS (fsLit "#x")) noSrcSpan make_row_vars_for_constructor :: (EqnNo, EquationInfo) -> [WarningPat] make_row_vars_for_constructor (_, EqnInfo { eqn_pats = pats}) = takeList (tail pats) (repeat nlWildPatName) compare_cons :: Pat Id -> Pat Id -> Bool compare_cons (ConPatOut{ pat_con = L _ con1 }) (ConPatOut{ pat_con = L _ con2 }) = case (con1, con2) of (RealDataCon id1, RealDataCon id2) -> id1 == id2 _ -> False compare_cons _ _ = panic "Check.compare_cons: Not ConPatOut with RealDataCon" remove_dups :: [Pat Id] -> [Pat Id] remove_dups [] = [] remove_dups (x:xs) | any (\y -> compare_cons x y) xs = remove_dups xs | otherwise = x : remove_dups xs get_used_cons :: [(EqnNo, EquationInfo)] -> [Pat Id] get_used_cons qs = remove_dups [pat | q <- qs, let pat = firstPatN q, isConPatOut pat] isConPatOut :: Pat Id -> Bool isConPatOut ConPatOut{ pat_con = L _ RealDataCon{} } = True isConPatOut _ = False remove_dups' :: [HsLit] -> [HsLit] remove_dups' [] = [] remove_dups' (x:xs) | x `elem` xs = remove_dups' xs | otherwise = x : remove_dups' xs get_used_lits :: [(EqnNo, EquationInfo)] -> [HsLit] get_used_lits qs = remove_dups' all_literals where all_literals = get_used_lits' qs get_used_lits' :: [(EqnNo, EquationInfo)] -> [HsLit] get_used_lits' [] = [] get_used_lits' (q:qs) | Just lit <- get_lit (firstPatN q) = lit : get_used_lits' qs | otherwise = get_used_lits qs get_lit :: Pat id -> Maybe HsLit -- Get a representative HsLit to stand for the OverLit -- It doesn't matter which one, because they will only be compared -- with other HsLits gotten in the same way get_lit (LitPat lit) = Just lit get_lit (NPat (L _ (OverLit { ol_val = HsIntegral src i})) mb _) = Just (HsIntPrim src (mb_neg negate mb i)) get_lit (NPat (L _ (OverLit { ol_val = HsFractional f })) mb _) = Just (HsFloatPrim (mb_neg negateFractionalLit mb f)) get_lit (NPat (L _ (OverLit { ol_val = HsIsString src s })) _ _) = Just (HsStringPrim src (fastStringToByteString s)) get_lit _ = Nothing mb_neg :: (a -> a) -> Maybe b -> a -> a mb_neg _ Nothing v = v mb_neg negate (Just _) v = negate v get_unused_cons :: [Pat Id] -> [DataCon] get_unused_cons used_cons = ASSERT( not (null used_cons) ) unused_cons where used_set :: UniqSet DataCon used_set = mkUniqSet [d | ConPatOut{ pat_con = L _ (RealDataCon d) } <- used_cons] (ConPatOut { pat_con = L _ (RealDataCon con1), pat_arg_tys = inst_tys }) = head used_cons ty_con = dataConTyCon con1 unused_cons = filterOut is_used (tyConDataCons ty_con) is_used con = con `elementOfUniqSet` used_set || dataConCannotMatch inst_tys con all_vars :: [Pat Id] -> Bool all_vars [] = True all_vars (WildPat _:ps) = all_vars ps all_vars _ = False remove_var :: (EqnNo, EquationInfo) -> (EqnNo, EquationInfo) remove_var (n, eqn@(EqnInfo { eqn_pats = WildPat _ : ps})) = (n, eqn { eqn_pats = ps }) remove_var _ = panic "Check.remove_var: equation does not begin with a variable" ----------------------- eqnPats :: (EqnNo, EquationInfo) -> [Pat Id] eqnPats (_, eqn) = eqn_pats eqn okGroup :: [(EqnNo, EquationInfo)] -> Bool -- True if all equations have at least one pattern, and -- all have the same number of patterns okGroup [] = True okGroup (e:es) = n_pats > 0 && and [length (eqnPats e) == n_pats | e <- es] where n_pats = length (eqnPats e) -- Half-baked print pprGroup :: [(EqnNo, EquationInfo)] -> SDoc pprEqnInfo :: (EqnNo, EquationInfo) -> SDoc pprGroup es = vcat (map pprEqnInfo es) pprEqnInfo e = ppr (eqnPats e) firstPatN :: (EqnNo, EquationInfo) -> Pat Id firstPatN (_, eqn) = firstPat eqn is_con :: Pat Id -> Bool is_con (ConPatOut {}) = True is_con _ = False is_lit :: Pat Id -> Bool is_lit (LitPat _) = True is_lit (NPat _ _ _) = True is_lit _ = False is_var :: Pat Id -> Bool is_var (WildPat _) = True is_var _ = False is_var_con :: ConLike -> Pat Id -> Bool is_var_con _ (WildPat _) = True is_var_con con (ConPatOut{ pat_con = L _ id }) = id == con is_var_con _ _ = False is_var_lit :: HsLit -> Pat Id -> Bool is_var_lit _ (WildPat _) = True is_var_lit lit pat | Just lit' <- get_lit pat = lit == lit' | otherwise = False {- The difference beteewn @make_con@ and @make_whole_con@ is that @make_wole_con@ creates a new constructor with all their arguments, and @make_con@ takes a list of argumntes, creates the contructor getting their arguments from the list. See where \fbox{\ ???\ } are used for details. We need to reconstruct the patterns (make the constructors infix and similar) at the same time that we create the constructors. You can tell tuple constructors using \begin{verbatim} Id.isTupleDataCon \end{verbatim} You can see if one constructor is infix with this clearer code :-)))))))))) \begin{verbatim} Lex.isLexConSym (Name.occNameString (Name.getOccName con)) \end{verbatim} Rather clumsy but it works. (Simon Peyton Jones) We don't mind the @nilDataCon@ because it doesn't change the way to print the message, we are searching only for things like: @[1,2,3]@, not @x:xs@ .... In @reconstruct_pat@ we want to ``undo'' the work that we have done in @tidy_pat@. In particular: \begin{tabular}{lll} @((,) x y)@ & returns to be & @(x, y)@ \\ @((:) x xs)@ & returns to be & @(x:xs)@ \\ @(x:(...:[])@ & returns to be & @[x,...]@ \end{tabular} The difficult case is the third one becouse we need to follow all the contructors until the @[]@ to know that we need to use the second case, not the second. \fbox{\ ???\ } -} isInfixCon :: DataCon -> Bool isInfixCon con = isDataSymOcc (getOccName con) is_nil :: Pat Name -> Bool is_nil (ConPatIn con (PrefixCon [])) = unLoc con == getName nilDataCon is_nil _ = False is_list :: Pat Name -> Bool is_list (ListPat _ _ Nothing) = True is_list _ = False return_list :: DataCon -> Pat Name -> Bool return_list id q = id == consDataCon && (is_nil q || is_list q) make_list :: LPat Name -> Pat Name -> Pat Name make_list p q | is_nil q = ListPat [p] placeHolderType Nothing make_list p (ListPat ps ty Nothing) = ListPat (p:ps) ty Nothing make_list _ _ = panic "Check.make_list: Invalid argument" make_con :: Pat Id -> ExhaustivePat -> ExhaustivePat make_con (ConPatOut{ pat_con = L _ (RealDataCon id) }) (lp:lq:ps, constraints) | return_list id q = (noLoc (make_list lp q) : ps, constraints) | isInfixCon id = (nlInfixConPat (getName id) lp lq : ps, constraints) where q = unLoc lq make_con (ConPatOut{ pat_con = L _ (RealDataCon id), pat_args = PrefixCon pats}) (ps, constraints) | isTupleTyCon tc = (noLoc (TuplePat pats_con (tupleTyConBoxity tc) []) : rest_pats, constraints) | isPArrFakeCon id = (noLoc (PArrPat pats_con placeHolderType) : rest_pats, constraints) | otherwise = (nlConPatName name pats_con : rest_pats, constraints) where name = getName id (pats_con, rest_pats) = splitAtList pats ps tc = dataConTyCon id make_con _ _ = panic "Check.make_con: Not ConPatOut" -- reconstruct parallel array pattern -- -- * don't check for the type only; we need to make sure that we are really -- dealing with one of the fake constructors and not with the real -- representation make_whole_con :: DataCon -> WarningPat make_whole_con con | isInfixCon con = nlInfixConPat name nlWildPatName nlWildPatName | otherwise = nlConPatName name pats where name = getName con pats = [nlWildPatName | _ <- dataConOrigArgTys con] {- ------------------------------------------------------------------------ Tidying equations ------------------------------------------------------------------------ tidy_eqn does more or less the same thing as @tidy@ in @Match.lhs@; that is, it removes syntactic sugar, reducing the number of cases that must be handled by the main checking algorithm. One difference is that here we can do *all* the tidying at once (recursively), rather than doing it incrementally. -} tidy_eqn :: EquationInfo -> EquationInfo tidy_eqn eqn = eqn { eqn_pats = map tidy_pat (eqn_pats eqn), eqn_rhs = tidy_rhs (eqn_rhs eqn) } where -- Horrible hack. The tidy_pat stuff converts "might-fail" patterns to -- WildPats which of course loses the info that they can fail to match. -- So we stick in a CanFail as if it were a guard. tidy_rhs (MatchResult can_fail body) | any might_fail_pat (eqn_pats eqn) = MatchResult CanFail body | otherwise = MatchResult can_fail body -------------- might_fail_pat :: Pat Id -> Bool -- Returns True of patterns that might fail (i.e. fall through) in a way -- that is not covered by the checking algorithm. Specifically: -- NPlusKPat -- ViewPat (if refutable) -- ConPatOut of a PatSynCon -- First the two special cases might_fail_pat (NPlusKPat {}) = True might_fail_pat (ViewPat _ p _) = not (isIrrefutableHsPat p) -- Now the recursive stuff might_fail_pat (ParPat p) = might_fail_lpat p might_fail_pat (AsPat _ p) = might_fail_lpat p might_fail_pat (SigPatOut p _ ) = might_fail_lpat p might_fail_pat (ListPat ps _ Nothing) = any might_fail_lpat ps might_fail_pat (ListPat _ _ (Just _)) = True might_fail_pat (TuplePat ps _ _) = any might_fail_lpat ps might_fail_pat (PArrPat ps _) = any might_fail_lpat ps might_fail_pat (BangPat p) = might_fail_lpat p might_fail_pat (ConPatOut { pat_con = con, pat_args = ps }) = case unLoc con of RealDataCon _dcon -> any might_fail_lpat (hsConPatArgs ps) PatSynCon _psyn -> True -- Finally the ones that are sure to succeed, or which are covered by the checking algorithm might_fail_pat (LazyPat _) = False -- Always succeeds might_fail_pat _ = False -- VarPat, WildPat, LitPat, NPat -------------- might_fail_lpat :: LPat Id -> Bool might_fail_lpat (L _ p) = might_fail_pat p -------------- tidy_lpat :: LPat Id -> LPat Id tidy_lpat p = fmap tidy_pat p -------------- tidy_pat :: Pat Id -> Pat Id tidy_pat pat@(WildPat _) = pat tidy_pat (VarPat id) = WildPat (idType id) tidy_pat (ParPat p) = tidy_pat (unLoc p) tidy_pat (LazyPat p) = WildPat (hsLPatType p) -- For overlap and exhaustiveness checking -- purposes, a ~pat is like a wildcard tidy_pat (BangPat p) = tidy_pat (unLoc p) tidy_pat (AsPat _ p) = tidy_pat (unLoc p) tidy_pat (SigPatOut p _) = tidy_pat (unLoc p) tidy_pat (CoPat _ pat _) = tidy_pat pat -- These two are might_fail patterns, so we map them to -- WildPats. The might_fail_pat stuff arranges that the -- guard says "this equation might fall through". tidy_pat (NPlusKPat id _ _ _) = WildPat (idType (unLoc id)) tidy_pat (ViewPat _ _ ty) = WildPat ty tidy_pat (ListPat _ _ (Just (ty,_))) = WildPat ty tidy_pat (ConPatOut { pat_con = L _ (PatSynCon syn), pat_arg_tys = tys }) = WildPat (patSynInstResTy syn tys) tidy_pat pat@(ConPatOut { pat_con = L _ con, pat_args = ps }) = pat { pat_args = tidy_con con ps } tidy_pat (ListPat ps ty Nothing) = unLoc $ foldr (\ x y -> mkPrefixConPat consDataCon [x,y] [ty]) (mkNilPat ty) (map tidy_lpat ps) -- introduce fake parallel array constructors to be able to handle parallel -- arrays with the existing machinery for constructor pattern -- tidy_pat (PArrPat ps ty) = unLoc $ mkPrefixConPat (parrFakeCon (length ps)) (map tidy_lpat ps) [ty] tidy_pat (TuplePat ps boxity tys) = unLoc $ mkPrefixConPat (tupleCon (boxityNormalTupleSort boxity) arity) (map tidy_lpat ps) tys where arity = length ps tidy_pat (NPat (L _ lit) mb_neg eq) = tidyNPat tidy_lit_pat lit mb_neg eq tidy_pat (LitPat lit) = tidy_lit_pat lit tidy_pat (ConPatIn {}) = panic "Check.tidy_pat: ConPatIn" tidy_pat (SplicePat {}) = panic "Check.tidy_pat: SplicePat" tidy_pat (QuasiQuotePat {}) = panic "Check.tidy_pat: QuasiQuotePat" tidy_pat (SigPatIn {}) = panic "Check.tidy_pat: SigPatIn" tidy_lit_pat :: HsLit -> Pat Id -- Unpack string patterns fully, so we can see when they -- overlap with each other, or even explicit lists of Chars. tidy_lit_pat lit | HsString src s <- lit = unLoc $ foldr (\c pat -> mkPrefixConPat consDataCon [mkCharLitPat src c, pat] [charTy]) (mkPrefixConPat nilDataCon [] [charTy]) (unpackFS s) | otherwise = tidyLitPat lit ----------------- tidy_con :: ConLike -> HsConPatDetails Id -> HsConPatDetails Id tidy_con _ (PrefixCon ps) = PrefixCon (map tidy_lpat ps) tidy_con _ (InfixCon p1 p2) = PrefixCon [tidy_lpat p1, tidy_lpat p2] tidy_con con (RecCon (HsRecFields fs _)) | null fs = PrefixCon (replicate arity nlWildPatId) -- Special case for null patterns; maybe not a record at all | otherwise = PrefixCon (map (tidy_lpat.snd) all_pats) where arity = case con of RealDataCon dcon -> dataConSourceArity dcon PatSynCon psyn -> patSynArity psyn -- pad out all the missing fields with WildPats. field_pats = case con of RealDataCon dc -> map (\ f -> (f, nlWildPatId)) (dataConFieldLabels dc) PatSynCon{} -> panic "Check.tidy_con: pattern synonym with record syntax" all_pats = foldr (\(L _ (HsRecField id p _)) acc -> insertNm (getName (unLoc id)) p acc) field_pats fs insertNm nm p [] = [(nm,p)] insertNm nm p (x@(n,_):xs) | nm == n = (nm,p):xs | otherwise = x : insertNm nm p xs
pparkkin/eta
compiler/ETA/DeSugar/Check.hs
bsd-3-clause
30,170
0
17
7,713
7,417
3,867
3,550
402
22
{-# LANGUAGE CPP #-} -- | -- Package configuration information: essentially the interface to Cabal, with -- some utilities -- -- (c) The University of Glasgow, 2004 -- module PackageConfig ( -- $package_naming -- * PackageId mkPackageId, packageConfigId, -- * The PackageConfig type: information about a package PackageConfig, InstalledPackageInfo_(..), display, Version(..), PackageIdentifier(..), defaultPackageConfig, packageConfigToInstalledPackageInfo, installedPackageInfoToPackageConfig ) where #include "HsVersions.h" import Distribution.InstalledPackageInfo import Distribution.ModuleName import Distribution.Package hiding (PackageId) import Distribution.Text import Distribution.Version import Maybes import Module -- ----------------------------------------------------------------------------- -- Our PackageConfig type is just InstalledPackageInfo from Cabal. Later we -- might need to extend it with some GHC-specific stuff, but for now it's fine. type PackageConfig = InstalledPackageInfo_ Module.ModuleName defaultPackageConfig :: PackageConfig defaultPackageConfig = emptyInstalledPackageInfo -- ----------------------------------------------------------------------------- -- PackageId (package names with versions) -- $package_naming -- #package_naming# -- Mostly the compiler deals in terms of 'PackageId's, which have the -- form @<pkg>-<version>@. You're expected to pass in the version for -- the @-package-name@ flag. However, for wired-in packages like @base@ -- & @rts@, we don't necessarily know what the version is, so these are -- handled specially; see #wired_in_packages#. -- | Turn a Cabal 'PackageIdentifier' into a GHC 'PackageId' mkPackageId :: PackageIdentifier -> PackageId mkPackageId = stringToPackageId . display -- | Get the GHC 'PackageId' right out of a Cabalish 'PackageConfig' packageConfigId :: PackageConfig -> PackageId packageConfigId = mkPackageId . sourcePackageId -- | Turn a 'PackageConfig', which contains GHC 'Module.ModuleName's into a Cabal specific -- 'InstalledPackageInfo' which contains Cabal 'Distribution.ModuleName.ModuleName's packageConfigToInstalledPackageInfo :: PackageConfig -> InstalledPackageInfo packageConfigToInstalledPackageInfo (pkgconf@(InstalledPackageInfo { exposedModules = e, hiddenModules = h })) = pkgconf{ exposedModules = map convert e, hiddenModules = map convert h } where convert :: Module.ModuleName -> Distribution.ModuleName.ModuleName convert = (expectJust "packageConfigToInstalledPackageInfo") . simpleParse . moduleNameString -- | Turn an 'InstalledPackageInfo', which contains Cabal 'Distribution.ModuleName.ModuleName's -- into a GHC specific 'PackageConfig' which contains GHC 'Module.ModuleName's installedPackageInfoToPackageConfig :: InstalledPackageInfo_ String -> PackageConfig installedPackageInfoToPackageConfig (pkgconf@(InstalledPackageInfo { exposedModules = e, hiddenModules = h })) = pkgconf{ exposedModules = map mkModuleName e, hiddenModules = map mkModuleName h }
frantisekfarka/ghc-dsi
compiler/main/PackageConfig.hs
bsd-3-clause
3,235
0
11
585
339
211
128
38
1
import WFA.Matrix import WFA.Type import WFA.RGB import WFA.Write import Data.Map ( Map ) import qualified Data.Map as M import Data.Set ( Set ) import qualified Data.Set as S main :: IO () main = writePBM "bild-b.pbm" Main.b 9 a :: WFA Quad Int RGB a = let s = WFA.RGB.maxplus in WFA { WFA.Type.semiring = s , alphabet = S.fromList quads , states = S.fromList [ 1,2 ] , initial = WFA.Matrix.make s [ ( (), blue, 1 ) ] , transition = M.fromList [ ( (L,U), WFA.Matrix.make s [ (1, white, 2) ] ) , ( (L,D), WFA.Matrix.make s [ (1, white, 2) ] ) , ( (R,U), WFA.Matrix.make s [ (1, white, 2) ] ) , ( (R,D), WFA.Matrix.make s [ (1, white, 2) ] ) ] , final = WFA.Matrix.make s [ ( 2, red, () ) ] } b :: WFA Quad Int RGB b = let s = WFA.RGB.maxplus2 in WFA { WFA.Type.semiring = s , alphabet = S.fromList quads , states = S.fromList [ 1,2 ] , initial = WFA.Matrix.make s [ ( (), white, 1 ), ( (), white, 2 ) ] , transition = M.fromList [ ( (L,U), WFA.Matrix.make s [ (1, red, 2), (1, blue, 1) ] ) , ( (L,D), WFA.Matrix.make s [ (2, green, 1), (2, blue, 2) ] ) , ( (R,U), WFA.Matrix.make s [ (1, white, 1), (1, red, 2) ] ) , ( (R,D), WFA.Matrix.make s [ (1, red, 1), (1, green, 2) ] ) ] , final = WFA.Matrix.make s [ ( 1, white, () ), ( 2, white, () ) ] }
florianpilz/autotool
src/WFA/Main.hs
gpl-2.0
1,547
2
14
567
717
432
285
36
1
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} {- Copyright (C) 2011-2014 John MacFarlane <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.ImageSize Copyright : Copyright (C) 2011-2014 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable Functions for determining the size of a PNG, JPEG, or GIF image. -} module Text.Pandoc.ImageSize ( ImageType(..), imageType, imageSize, sizeInPixels, sizeInPoints ) where import Data.ByteString (ByteString, unpack) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy as BL import Control.Applicative import Control.Monad import Data.Bits import Data.Binary import Data.Binary.Get import Text.Pandoc.Shared (safeRead) import qualified Data.Map as M -- quick and dirty functions to get image sizes -- algorithms borrowed from wwwis.pl data ImageType = Png | Gif | Jpeg | Pdf | Eps deriving Show data ImageSize = ImageSize{ pxX :: Integer , pxY :: Integer , dpiX :: Integer , dpiY :: Integer } deriving (Read, Show, Eq) imageType :: ByteString -> Maybe ImageType imageType img = case B.take 4 img of "\x89\x50\x4e\x47" -> return Png "\x47\x49\x46\x38" -> return Gif "\xff\xd8\xff\xe0" -> return Jpeg -- JFIF "\xff\xd8\xff\xe1" -> return Jpeg -- Exif "%PDF" -> return Pdf "%!PS" | (B.take 4 $ B.drop 1 $ B.dropWhile (/=' ') img) == "EPSF" -> return Eps _ -> fail "Unknown image type" imageSize :: ByteString -> Maybe ImageSize imageSize img = do t <- imageType img case t of Png -> pngSize img Gif -> gifSize img Jpeg -> jpegSize img Eps -> epsSize img Pdf -> Nothing -- TODO defaultSize :: (Integer, Integer) defaultSize = (72, 72) sizeInPixels :: ImageSize -> (Integer, Integer) sizeInPixels s = (pxX s, pxY s) sizeInPoints :: ImageSize -> (Integer, Integer) sizeInPoints s = (pxX s * 72 `div` dpiX s, pxY s * 72 `div` dpiY s) epsSize :: ByteString -> Maybe ImageSize epsSize img = do let ls = takeWhile ("%" `B.isPrefixOf`) $ B.lines img let ls' = dropWhile (not . ("%%BoundingBox:" `B.isPrefixOf`)) ls case ls' of [] -> mzero (x:_) -> case B.words x of (_:_:_:ux:uy:[]) -> do ux' <- safeRead $ B.unpack ux uy' <- safeRead $ B.unpack uy return ImageSize{ pxX = ux' , pxY = uy' , dpiX = 72 , dpiY = 72 } _ -> mzero pngSize :: ByteString -> Maybe ImageSize pngSize img = do let (h, rest) = B.splitAt 8 img guard $ h == "\x8a\x4d\x4e\x47\x0d\x0a\x1a\x0a" || h == "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a" let (i, rest') = B.splitAt 4 $ B.drop 4 rest guard $ i == "MHDR" || i == "IHDR" let (sizes, rest'') = B.splitAt 8 rest' (x,y) <- case map fromIntegral $ unpack $ sizes of ([w1,w2,w3,w4,h1,h2,h3,h4] :: [Integer]) -> return ((shift w1 24) + (shift w2 16) + (shift w3 8) + w4, (shift h1 24) + (shift h2 16) + (shift h3 8) + h4) _ -> fail "PNG parse error" let (dpix, dpiy) = findpHYs rest'' return $ ImageSize { pxX = x, pxY = y, dpiX = dpix, dpiY = dpiy } findpHYs :: ByteString -> (Integer, Integer) findpHYs x = if B.null x || "IDAT" `B.isPrefixOf` x then (72,72) -- default, no pHYs else if "pHYs" `B.isPrefixOf` x then let [x1,x2,x3,x4,y1,y2,y3,y4,u] = map fromIntegral $ unpack $ B.take 9 $ B.drop 4 x factor = if u == 1 -- dots per meter then \z -> z * 254 `div` 10000 else const 72 in ( factor $ (shift x1 24) + (shift x2 16) + (shift x3 8) + x4, factor $ (shift y1 24) + (shift y2 16) + (shift y3 8) + y4 ) else findpHYs $ B.drop 1 x -- read another byte gifSize :: ByteString -> Maybe ImageSize gifSize img = do let (h, rest) = B.splitAt 6 img guard $ h == "GIF87a" || h == "GIF89a" case map fromIntegral $ unpack $ B.take 4 rest of [w2,w1,h2,h1] -> return ImageSize { pxX = shift w1 8 + w2, pxY = shift h1 8 + h2, dpiX = 72, dpiY = 72 } _ -> fail "GIF parse error" jpegSize :: ByteString -> Maybe ImageSize jpegSize img = do let (hdr, rest) = B.splitAt 4 img guard $ B.length rest >= 14 case hdr of "\xff\xd8\xff\xe0" -> jfifSize rest "\xff\xd8\xff\xe1" -> exifSize $ B.takeWhile (/= '\xff') rest _ -> mzero jfifSize :: ByteString -> Maybe ImageSize jfifSize rest = do let [dpiDensity,dpix1,dpix2,dpiy1,dpiy2] = map fromIntegral $ unpack $ B.take 5 $ B.drop 9 $ rest let factor = case dpiDensity of 1 -> id 2 -> \x -> (x * 254 `div` 10) _ -> const 72 let dpix = factor (shift dpix1 8 + dpix2) let dpiy = factor (shift dpiy1 8 + dpiy2) (w,h) <- findJfifSize rest return $ ImageSize { pxX = w, pxY = h, dpiX = dpix, dpiY = dpiy } findJfifSize :: ByteString -> Maybe (Integer,Integer) findJfifSize bs = do let bs' = B.dropWhile (=='\xff') $ B.dropWhile (/='\xff') bs case B.uncons bs' of Just (c,bs'') | c >= '\xc0' && c <= '\xc3' -> do case map fromIntegral $ unpack $ B.take 4 $ B.drop 3 bs'' of [h1,h2,w1,w2] -> return (shift w1 8 + w2, shift h1 8 + h2) _ -> fail "JPEG parse error" Just (_,bs'') -> do case map fromIntegral $ unpack $ B.take 2 bs'' of [c1,c2] -> do let len = shift c1 8 + c2 -- skip variables findJfifSize $ B.drop len bs'' _ -> fail "JPEG parse error" Nothing -> fail "Did not find length record" exifSize :: ByteString -> Maybe ImageSize exifSize bs = runGet (Just <$> exifHeader bl) bl where bl = BL.fromChunks [bs] -- NOTE: It would be nicer to do -- runGet ((Just <$> exifHeader) <|> return Nothing) -- which would prevent pandoc from raising an error when an exif header can't -- be parsed. But we only get an Alternative instance for Get in binary 0.6, -- and binary 0.5 ships with ghc 7.6. exifHeader :: BL.ByteString -> Get ImageSize exifHeader hdr = do _app1DataSize <- getWord16be exifHdr <- getWord32be unless (exifHdr == 0x45786966) $ fail "Did not find exif header" zeros <- getWord16be unless (zeros == 0) $ fail "Expected zeros after exif header" -- beginning of tiff header -- we read whole thing to use -- in getting data from offsets: let tiffHeader = BL.drop 8 hdr byteAlign <- getWord16be let bigEndian = byteAlign == 0x4d4d let (getWord16, getWord32, getWord64) = if bigEndian then (getWord16be, getWord32be, getWord64be) else (getWord16le, getWord32le, getWord64le) let getRational = do num <- getWord32 den <- getWord32 return $ fromIntegral num / fromIntegral den tagmark <- getWord16 unless (tagmark == 0x002a) $ fail "Failed alignment sanity check" ifdOffset <- getWord32 skip (fromIntegral ifdOffset - 8) -- skip to IDF numentries <- getWord16 let ifdEntry = do tag <- getWord16 >>= \t -> maybe (return UnknownTagType) return (M.lookup t tagTypeTable) dataFormat <- getWord16 numComponents <- getWord32 (fmt, bytesPerComponent) <- case dataFormat of 1 -> return (UnsignedByte . runGet getWord8, 1) 2 -> return (AsciiString, 1) 3 -> return (UnsignedShort . runGet getWord16, 2) 4 -> return (UnsignedLong . runGet getWord32, 4) 5 -> return (UnsignedRational . runGet getRational, 8) 6 -> return (SignedByte . runGet getWord8, 1) 7 -> return (Undefined . runGet getWord8, 1) 8 -> return (SignedShort . runGet getWord16, 2) 9 -> return (SignedLong . runGet getWord32, 4) 10 -> return (SignedRational . runGet getRational, 8) 11 -> return (SingleFloat . runGet getWord32 {- TODO -}, 4) 12 -> return (DoubleFloat . runGet getWord64 {- TODO -}, 8) _ -> fail $ "Unknown data format " ++ show dataFormat let totalBytes = fromIntegral $ numComponents * bytesPerComponent payload <- if totalBytes <= 4 -- data is right here then fmt <$> (getLazyByteString (fromIntegral totalBytes) <* skip (4 - totalBytes)) else do -- get data from offset offs <- getWord32 return $ fmt $ BL.take (fromIntegral totalBytes) $ BL.drop (fromIntegral offs) tiffHeader return (tag, payload) entries <- sequence $ replicate (fromIntegral numentries) ifdEntry subentries <- case lookup ExifOffset entries of Just (UnsignedLong offset) -> do pos <- bytesRead skip (fromIntegral offset - (fromIntegral pos - 8)) numsubentries <- getWord16 sequence $ replicate (fromIntegral numsubentries) ifdEntry _ -> return [] let allentries = entries ++ subentries (width, height) <- case (lookup ExifImageWidth allentries, lookup ExifImageHeight allentries) of (Just (UnsignedLong w), Just (UnsignedLong h)) -> return (fromIntegral w, fromIntegral h) _ -> return defaultSize -- we return a default width and height when -- the exif header doesn't contain these let resfactor = case lookup ResolutionUnit allentries of Just (UnsignedShort 1) -> (100 / 254) _ -> 1 let xres = maybe 72 (\(UnsignedRational x) -> floor $ x * resfactor) $ lookup XResolution allentries let yres = maybe 72 (\(UnsignedRational x) -> floor $ x * resfactor) $ lookup YResolution allentries return $ ImageSize{ pxX = width , pxY = height , dpiX = xres , dpiY = yres } data DataFormat = UnsignedByte Word8 | AsciiString BL.ByteString | UnsignedShort Word16 | UnsignedLong Word32 | UnsignedRational Rational | SignedByte Word8 | Undefined Word8 | SignedShort Word16 | SignedLong Word32 | SignedRational Rational | SingleFloat Word32 | DoubleFloat Word64 deriving (Show) data TagType = ImageDescription | Make | Model | Orientation | XResolution | YResolution | ResolutionUnit | Software | DateTime | WhitePoint | PrimaryChromaticities | YCbCrCoefficients | YCbCrPositioning | ReferenceBlackWhite | Copyright | ExifOffset | ExposureTime | FNumber | ExposureProgram | ISOSpeedRatings | ExifVersion | DateTimeOriginal | DateTimeDigitized | ComponentConfiguration | CompressedBitsPerPixel | ShutterSpeedValue | ApertureValue | BrightnessValue | ExposureBiasValue | MaxApertureValue | SubjectDistance | MeteringMode | LightSource | Flash | FocalLength | MakerNote | UserComment | FlashPixVersion | ColorSpace | ExifImageWidth | ExifImageHeight | RelatedSoundFile | ExifInteroperabilityOffset | FocalPlaneXResolution | FocalPlaneYResolution | FocalPlaneResolutionUnit | SensingMethod | FileSource | SceneType | UnknownTagType deriving (Show, Eq, Ord) tagTypeTable :: M.Map Word16 TagType tagTypeTable = M.fromList [ (0x010e, ImageDescription) , (0x010f, Make) , (0x0110, Model) , (0x0112, Orientation) , (0x011a, XResolution) , (0x011b, YResolution) , (0x0128, ResolutionUnit) , (0x0131, Software) , (0x0132, DateTime) , (0x013e, WhitePoint) , (0x013f, PrimaryChromaticities) , (0x0211, YCbCrCoefficients) , (0x0213, YCbCrPositioning) , (0x0214, ReferenceBlackWhite) , (0x8298, Copyright) , (0x8769, ExifOffset) , (0x829a, ExposureTime) , (0x829d, FNumber) , (0x8822, ExposureProgram) , (0x8827, ISOSpeedRatings) , (0x9000, ExifVersion) , (0x9003, DateTimeOriginal) , (0x9004, DateTimeDigitized) , (0x9101, ComponentConfiguration) , (0x9102, CompressedBitsPerPixel) , (0x9201, ShutterSpeedValue) , (0x9202, ApertureValue) , (0x9203, BrightnessValue) , (0x9204, ExposureBiasValue) , (0x9205, MaxApertureValue) , (0x9206, SubjectDistance) , (0x9207, MeteringMode) , (0x9208, LightSource) , (0x9209, Flash) , (0x920a, FocalLength) , (0x927c, MakerNote) , (0x9286, UserComment) , (0xa000, FlashPixVersion) , (0xa001, ColorSpace) , (0xa002, ExifImageWidth) , (0xa003, ExifImageHeight) , (0xa004, RelatedSoundFile) , (0xa005, ExifInteroperabilityOffset) , (0xa20e, FocalPlaneXResolution) , (0xa20f, FocalPlaneYResolution) , (0xa210, FocalPlaneResolutionUnit) , (0xa217, SensingMethod) , (0xa300, FileSource) , (0xa301, SceneType) ]
sapek/pandoc
src/Text/Pandoc/ImageSize.hs
gpl-2.0
15,318
0
21
5,476
4,027
2,157
1,870
335
18
module A1 where import D1 sumSq xs ys= sum (map sq xs) + sumSquares xs ys main = sumSq [1..4]
kmate/HaRe
old/testing/rmOneParameter/A1.hs
bsd-3-clause
99
0
8
25
50
26
24
4
1
{-# LANGUAGE TypeFamilyDependencies #-} module T6018Bfail where import Data.Kind (Type) type family H a b c = (result :: Type) | result -> a b c
sdiehl/ghc
testsuite/tests/typecheck/should_fail/T6018Bfail.hs
bsd-3-clause
148
0
6
29
39
28
11
-1
-1
import GHC.Conc main :: IO () main = setNumCapabilities 0
ezyang/ghc
testsuite/tests/rts/T13832.hs
bsd-3-clause
59
0
6
11
24
12
12
3
1
{-# LANGUAGE FlexibleContexts #-} -- | Implementation of Kahan summation algorithm that tests -- performance of tight loops involving unboxed arrays and floating -- point arithmetic. module Main (main) where import Control.Monad.ST import Data.Array.Base import Data.Array.ST import Data.Bits import Data.Word import System.Environment vdim :: Int vdim = 100 prng :: Word -> Word prng w = w' where w1 = w `xor` (w `shiftL` 13) w2 = w1 `xor` (w1 `shiftR` 7) w' = w2 `xor` (w2 `shiftL` 17) type Vec s = STUArray s Int Double kahan :: Int -> Vec s -> Vec s -> ST s () kahan vnum s c = do let inner w j | j < vdim = do cj <- unsafeRead c j sj <- unsafeRead s j let y = fromIntegral w - cj t = sj + y w' = prng w unsafeWrite c j ((t-sj)-y) unsafeWrite s j t inner w' (j+1) | otherwise = return () outer i | i <= vnum = inner (fromIntegral i) 0 >> outer (i+1) | otherwise = return () outer 1 calc :: Int -> ST s (Vec s) calc vnum = do s <- newArray (0,vdim-1) 0 c <- newArray (0,vdim-1) 0 kahan vnum s c return s main :: IO () main = do [arg] <- getArgs print . elems $ runSTUArray $ calc $ read arg
k-bx/ghcjs
test/nofib/imaginary/kahan/Main.hs
mit
1,334
0
17
467
533
272
261
42
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilyDependencies #-} module T13271 where import GHC.TypeLits data T1 = T1 type T2 = TypeError (Text "You can't do that!") type family X i = r | r -> i where X 1 = T1 X 2 = T2
shlevy/ghc
testsuite/tests/indexed-types/should_fail/T13271.hs
bsd-3-clause
229
0
7
53
64
39
25
9
0
{-# LANGUAGE TemplateHaskell #-} module Main where import Data.Maybe (Maybe(..)) import Data.Ord (Ord) import Language.Haskell.TH (mkName, nameSpace) main :: IO () main = mapM_ (print . nameSpace) [ 'Prelude.id , mkName "id" , 'Data.Maybe.Just , ''Data.Maybe.Maybe , ''Data.Ord.Ord ]
ezyang/ghc
testsuite/tests/th/TH_nameSpace.hs
bsd-3-clause
364
0
8
119
105
64
41
12
1
main = interact wordCount where wordCount input = show (length input) ++ "\n"
akampjes/learning-realworldhaskell
ch01/WC.hs
mit
80
0
8
15
32
15
17
2
1
{-# Language GADTs #-} module Unison.Runtime.Vector where import Unison.Prelude import qualified Data.MemoCombinators as Memo import qualified Data.Vector.Unboxed as UV -- A `Vec a` denotes a `Nat -> Maybe a` data Vec a where Scalar :: a -> Vec a Vec :: UV.Unbox a => UV.Vector a -> Vec a Pair :: Vec a -> Vec b -> Vec (a, b) Choose :: Vec Bool -> Vec a -> Vec a -> Vec a Mux :: Vec Nat -> Vec (Vec a) -> Vec a -- todo: maybe make representation `(UV.Vector Nat -> UnboxedMap Nat a, Bound)` -- `UnboxedMap Nat a = (UV.Vector Nat, UV.Vector a)` -- UnboxedMap Nat could be implemented as an `UArray` -- `Bound` is Nat, max possible index -- then easy to implement `+`, `-`, etc type Nat = Word64 mu :: Vec a -> Nat -> Maybe a mu v = case v of Scalar a -> const (Just a) Vec vs -> \i -> vs UV.!? fromIntegral i Choose cond t f -> let (condr, tr, tf) = (mu cond, mu t, mu f) in \i -> condr i >>= \b -> if b then tr i else tf i Mux mux branches -> let muxr = mu mux branchesr = Memo.integral $ let f = mu branches in \i -> mu <$> f i in \i -> do j <- muxr i; b <- branchesr j; b i Pair v1 v2 -> let (v1r, v2r) = (mu v1, mu v2) in \i -> liftA2 (,) (v1r i) (v2r i) -- Returns the maximum `Nat` for which `mu v` may return `Just`. bound :: Nat -> Vec a -> Nat bound width v = case v of Scalar _ -> width Vec vs -> fromIntegral $ UV.length vs Pair v1 v2 -> bound width v1 `min` bound width v2 Choose cond _ _ -> bound width cond Mux mux _ -> bound width mux toList :: Vec a -> [a] toList v = let n = bound maxBound v muv = mu v in catMaybes $ muv <$> [0..n]
unisonweb/platform
parser-typechecker/src/Unison/Runtime/Vector.hs
mit
1,622
0
17
417
667
334
333
38
6
import Control.Monad import Test.QuickCheck import Test.QuickCheck.Checkers import Test.QuickCheck.Classes bind :: Monad m => (a -> m b) -> m a -> m b bind f n = join $ fmap f n data Nope a = NopeDotJpg deriving (Show, Eq) instance Functor Nope where fmap f a = NopeDotJpg instance Applicative Nope where pure a = NopeDotJpg f <*> g = NopeDotJpg instance Monad Nope where return a = NopeDotJpg f >>= g = NopeDotJpg instance Arbitrary (Nope a) where arbitrary = elements [ NopeDotJpg ] instance Eq a => EqProp (Nope a) where (=-=) = eq main :: IO() main = let trigger = undefined :: Nope (Int, Int, Int) in quickBatch $ monad trigger data PhhhbbtttEither b a = Lefty a | Righty b deriving (Eq, Show) instance Functor (PhhhbbtttEither b) where fmap f (Lefty a) = Lefty (f a) fmap f (Righty b) = Righty b instance Applicative (PhhhbbtttEither b) where pure a = Lefty a _ <*> Righty b = Righty b Righty b <*> _ = Righty b Lefty f <*> Lefty a = Lefty (f a) instance Monad (PhhhbbtttEither b) where return a = Lefty a Lefty a >>= f = f a Righty b >>= _ = Righty b instance (Arbitrary a, Arbitrary b) => Arbitrary (PhhhbbtttEither b a) where arbitrary = do a <- arbitrary b <- arbitrary elements [Lefty a, Righty b] instance (Eq a, Eq b) => EqProp (PhhhbbtttEither a b) where (=-=) = eq main2 :: IO() main2 = let trigger = undefined :: PhhhbbtttEither Int (Int, Int, Int) in quickBatch $ monad trigger newtype Identity a = Identity a deriving (Eq, Ord, Show) instance Functor Identity where fmap f (Identity a) = Identity (f a) instance Applicative Identity where pure = Identity Identity f <*> Identity a = Identity (f a) instance Monad Identity where return = pure Identity a >>= f = f a instance (Arbitrary a) => Arbitrary (Identity a) where arbitrary = do a <- arbitrary return (Identity a) instance (Eq a) => EqProp (Identity a) where (=-=) = eq main3 :: IO() main3 = let trigger = undefined :: Identity (Int, Int, Int) in quickBatch $ monad trigger data List a = Nil | Cons a (List a) deriving (Eq, Show) instance Functor List where fmap f Nil = Nil fmap f (Cons a b) = Cons (f a) (fmap f b) instance Applicative List where pure a = Cons a Nil Nil <*> _ = Nil _ <*> Nil = Nil Cons f g <*> a = append (fmap f a) (g <*> a) instance Monad List where return = pure a >>= f = flatMap f a -- from ch17 append :: List a -> List a -> List a append Nil ys = ys append (Cons x xs) ys = Cons x $ xs `append` ys fold :: ( a -> b -> b) -> b -> List a -> b fold _ b Nil = b fold f b (Cons h t) = f h (fold f b t) concat' :: List (List a) -> List a concat' = fold append Nil -- write this one in terms of concat' and fmap flatMap :: (a -> List b) -> List a -> List b flatMap f as = concat' (fmap f as) instance (Arbitrary a) => Arbitrary (List a) where arbitrary = do a <- arbitrary b <- arbitrary frequency [ (1, return Nil) , (2, return (Cons a b)) ] instance Eq a => EqProp (List a) where (=-=) = eq main4 :: IO() main4 = let trigger = undefined :: List (Int, Int, Int) in quickBatch $ monad trigger j :: Monad m => m (m a) -> m a j = join l1 :: Monad m => (a -> b) -> m a -> m b l1 = (<$>) l2 :: Monad m => (a -> b -> c) -> m a -> m b -> m c l2 = liftM2 a :: Monad m => m a -> m (a -> b) -> m b a = flip (<*>) meh :: Monad m => [a] -> (a -> m b) -> m [b] meh l f = let g = map f l in sequence g meh2 :: Monad m => [a] -> (a -> m b) -> m [b] meh2 [] _ = pure [] meh2 (x:xs) f = do y <- f x z <- meh2 xs f pure (y : z) meh3 :: Monad m => [a] -> (a -> m b) -> m [b] meh3 [] _ = pure [] meh3 (x:xs) f = f x >>= \y -> (meh3 xs f) >>= \z -> return (y:z) flipType :: (Monad m) => [m a] -> m [a] flipType = sequence flipType2 :: (Monad m) => [m a] -> m [a] flipType2 k = meh k id
mitochon/hexercise
src/haskellbook/ch18/ch18.hs
mit
3,911
0
12
1,065
2,025
1,010
1,015
115
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE ScopedTypeVariables #-} module Database.Esqueleto.TextSearchSpec (main, spec) where import Control.Monad (forM_) import Data.Text (Text, pack) import Control.Monad.IO.Class (MonadIO(liftIO)) import Control.Monad.Logger (MonadLogger(..), runStderrLoggingT) import Control.Monad.Trans.Resource ( MonadBaseControl, MonadThrow, ResourceT, runResourceT) import Database.Esqueleto ( SqlExpr, Value(..), unValue, update, select, set, val, from, where_ , (=.), (^.)) import Database.Persist (entityKey, insert, get, PersistField(..)) import Database.Persist.Postgresql ( SqlPersistT, ConnectionString, runSqlConn, transactionUndo , withPostgresqlConn, runMigration) import Database.Persist.TH ( mkPersist, mkMigrate, persistUpperCase, share, sqlSettings) import Test.Hspec (Spec, hspec, describe, it, shouldBe) import Test.QuickCheck ( Arbitrary(..), property, elements, oneof, listOf, listOf1, choose) import Database.Esqueleto.TextSearch connString :: ConnectionString connString = "host=localhost port=5432 user=test dbname=test password=test" -- Test schema share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistUpperCase| Article title Text content Text textsearch TsVector deriving Eq Show WeightsModel weights Weights deriving Eq Show WeightModel weight Weight deriving Eq Show RegConfigModel config RegConfig deriving Eq Show QueryModel query (TsQuery Lexemes) deriving Eq Show |] main :: IO () main = hspec spec to_etsvector :: SqlExpr (Value Text) -> SqlExpr (Value TsVector) to_etsvector = to_tsvector (val "english") spec :: Spec spec = do describe "TsVector" $ do it "can be persisted and retrieved" $ run $ do let article = Article "some title" "some content" def arId <- insert article update $ \a -> do set a [ArticleTextsearch =. to_etsvector (a^.ArticleContent)] Just ret <- get arId liftIO $ articleTextsearch ret /= def `shouldBe` True it "can be persisted and retrieved with weight" $ run $ do let article = Article "some title" "some content" def arId <- insert article update $ \a -> do set a [ ArticleTextsearch =. setweight (to_etsvector (a^.ArticleContent)) (val Highest) ] Just ret <- get arId liftIO $ articleTextsearch ret /= def `shouldBe` True describe "Weight" $ do it "can be persisted and retrieved" $ run $ do forM_ [Low, Medium, High, Highest] $ \w -> do let m = WeightModel w wId <- insert m ret <- get wId liftIO $ ret `shouldBe` Just m describe "Weights" $ do it "can be persisted and retrieved" $ run $ do let m = WeightsModel $ Weights 0.5 0.6 0.7 0.8 wsId <- insert m ret <- get wsId liftIO $ ret `shouldBe` Just m describe "RegConfig" $ do it "can be persisted and retrieved" $ run $ do forM_ ["english", "spanish"] $ \c -> do let m = RegConfigModel c wId <- insert m ret <- get wId liftIO $ ret `shouldBe` Just m describe "TsQuery" $ do it "can be persisted and retrieved" $ run $ do let qm = QueryModel (lexm "foo" :& lexm "bar") qId <- insert qm Just ret <- get qId liftIO $ qm `shouldBe` ret describe "to_tsquery" $ do it "converts words to lexemes" $ run $ do [Value lq ] <- select $ return $ to_tsquery (val "english") (val ("supernovae" :& "rats")) liftIO $ lq `shouldBe` (lexm "supernova" :& lexm "rat") describe "plainto_tsquery" $ do it "converts text to lexemes" $ run $ do [Value lq ] <- select $ return $ plainto_tsquery (val "english") (val "rats in supernovae") liftIO $ lq `shouldBe` (lexm "rat" :& lexm "supernova") describe "queryToText" $ do it "can serialize infix lexeme" $ queryToText (lexm "foo") `shouldBe` "'foo'" it "can serialize infix lexeme with weights" $ queryToText (Lexeme Infix [Highest,Low] "foo") `shouldBe` "'foo':AD" it "can serialize prefix lexeme" $ queryToText (Lexeme Prefix [] "foo") `shouldBe` "'foo':*" it "can serialize prefix lexeme with weights" $ queryToText (Lexeme Prefix [Highest,Low] "foo") `shouldBe` "'foo':*AD" it "can serialize AND" $ queryToText ("foo" :& "bar" :& "car") `shouldBe` "'foo'&('bar'&'car')" it "can serialize OR" $ queryToText ("foo" :| "bar") `shouldBe` "'foo'|'bar'" it "can serialize Not" $ queryToText (Not "bar") `shouldBe` "!'bar'" describe "textToQuery" $ do describe "infix lexeme" $ do it "can parse it" $ textToQuery "'foo'" `shouldBe` Right (lexm "foo") it "can parse it surrounded by spaces" $ textToQuery " 'foo' " `shouldBe` Right (lexm "foo") describe "infix lexeme with weights" $ do it "can parse it" $ textToQuery "'foo':AB" `shouldBe` Right (Lexeme Infix [Highest,High] "foo") it "can parse it surrounded by spaces" $ textToQuery " 'foo':AB " `shouldBe` Right (Lexeme Infix [Highest,High] "foo") describe "prefix lexeme" $ do it "can parse it" $ textToQuery "'foo':*" `shouldBe` Right (Lexeme Prefix [] "foo") it "can parse it surrounded byb spaces" $ textToQuery " 'foo':* " `shouldBe` Right (Lexeme Prefix [] "foo") describe "prefix lexeme with weights" $ do it "can parse it" $ textToQuery "'foo':*AB" `shouldBe` Right (Lexeme Prefix [Highest,High] "foo") it "can parse it surrounded by spaces" $ textToQuery " 'foo':*AB " `shouldBe` Right (Lexeme Prefix [Highest,High] "foo") describe "&" $ do it "can parse it" $ textToQuery "'foo'&'bar'" `shouldBe` Right (lexm "foo" :& lexm "bar") it "can parse it surrounded by spaces" $ do textToQuery "'foo' & 'bar'" `shouldBe` Right (lexm "foo" :& lexm "bar") textToQuery "'foo'& 'bar'" `shouldBe` Right (lexm "foo" :& lexm "bar") textToQuery "'foo' &'bar'" `shouldBe` Right (lexm "foo" :& lexm "bar") textToQuery " 'foo'&'bar' " `shouldBe` Right (lexm "foo" :& lexm "bar") it "can parse several" $ textToQuery "'foo'&'bar'&'car'" `shouldBe` Right (lexm "foo" :& lexm "bar" :& lexm "car") describe "|" $ do it "can parse it" $ textToQuery "'foo'|'bar'" `shouldBe` Right (lexm "foo" :| lexm "bar") it "can parse several" $ textToQuery "'foo'|'bar'|'car'" `shouldBe` Right (lexm "foo" :| lexm "bar" :| lexm "car") describe "mixed |s and &s" $ do it "respects precedence" $ do textToQuery "'foo'|'bar'&'car'" `shouldBe` Right (lexm "foo" :| lexm "bar" :& lexm "car") textToQuery "'foo'&'bar'|'car'" `shouldBe` Right (lexm "foo" :& lexm "bar" :| lexm "car") describe "!" $ do it "can parse it" $ textToQuery "!'foo'" `shouldBe` Right (Not (lexm "foo")) describe "! and &" $ do it "can parse it" $ do textToQuery "!'foo'&'car'" `shouldBe` Right (Not (lexm "foo") :& lexm "car") textToQuery "!('foo'&'car')" `shouldBe` Right (Not (lexm "foo" :& lexm "car")) it "can parse it surrounded by spaces" $ do textToQuery "!'foo' & 'car'" `shouldBe` Right (Not (lexm "foo") :& lexm "car") textToQuery "!( 'foo' & 'car' )" `shouldBe` Right (Not (lexm "foo" :& lexm "car")) describe "textToQuery . queryToText" $ do it "is isomorphism" $ property $ \q -> (textToQuery . queryToText) q `shouldBe` Right q describe "@@" $ do it "works as expected" $ run $ do let article = Article "some title" "some content" def arId <- insert article update $ \a -> do set a [ArticleTextsearch =. to_etsvector (a^.ArticleContent)] let query = to_tsquery (val "english") (val "content") result <- select $ from $ \a -> do where_ $ (a^. ArticleTextsearch) @@. query return a liftIO $ do length result `shouldBe` 1 map entityKey result `shouldBe` [arId] let query2 = to_tsquery (val "english") (val "foo") result2 <- select $ from $ \a -> do where_ $ (a^. ArticleTextsearch) @@. query2 return a liftIO $ length result2 `shouldBe` 0 describe "ts_rank_cd" $ do it "works as expected" $ run $ do let vector = to_tsvector (val "english") (val content) content = "content" :: Text query = to_tsquery (val "english") (val "content") norm = val [] ret <- select $ return $ ts_rank_cd (val def) vector query norm liftIO $ map unValue ret `shouldBe` [0.1] describe "ts_rank" $ do it "works as expected" $ run $ do let vector = to_tsvector (val "english") (val content) content = "content" :: Text query = to_tsquery (val "english") (val "content") norm = val [] ret <- select $ return $ ts_rank (val def) vector query norm liftIO $ map unValue ret `shouldBe` [6.07927e-2] describe "NormalizationOption" $ do describe "fromPersistValue . toPersistValue" $ do let isEqual [] [] = True isEqual [NormNone] [] = True isEqual [] [NormNone] = True isEqual a b = a == b toRight (Right a) = a toRight _ = error "unexpected Left" it "is isomorphism" $ property $ \(q :: [NormalizationOption]) -> isEqual ((toRight . fromPersistValue . toPersistValue) q) q `shouldBe` True instance Arbitrary ([NormalizationOption]) where arbitrary = (:[]) <$> elements [minBound..maxBound] instance a ~ Lexemes => Arbitrary (TsQuery a) where arbitrary = query 0 where maxDepth :: Int maxDepth = 10 query d | d<maxDepth = oneof [lexeme, and_ d, or_ d, not_ d] | otherwise = lexeme lexeme = Lexeme <$> arbitrary <*> weights <*> lexString weights = listOf arbitrary and_ d = (:&) <$> query (d+1) <*> query (d+1) or_ d = (:|) <$> query (d+1) <*> query (d+1) not_ d = Not <$> query (d+1) lexString = pack <$> listOf1 (oneof $ [ choose ('a','z') , choose ('A','Z') , choose ('0','9') ] ++ map pure "-_&|ñçáéíóú") instance Arbitrary Position where arbitrary = oneof [pure Infix, pure Prefix] instance Arbitrary Weight where arbitrary = oneof [pure Highest, pure High, pure Medium, pure Low] lexm :: Text -> TsQuery Lexemes lexm = Lexeme Infix [] type RunDbMonad m = (MonadBaseControl IO m, MonadIO m, MonadLogger m, MonadThrow m) run :: (forall m. RunDbMonad m => SqlPersistT (ResourceT m) a) -> IO a run act = runStderrLoggingT . runResourceT . withPostgresqlConn connString . runSqlConn $ (initializeDB >> act >>= \ret -> transactionUndo >> return ret) initializeDB :: (forall m. RunDbMonad m => SqlPersistT (ResourceT m) ()) initializeDB = do runMigration migrateAll
albertov/esqueleto-textsearch
test/Database/Esqueleto/TextSearchSpec.hs
mit
11,840
0
25
3,394
3,663
1,804
1,859
262
5
{- ghci c:\Users\Thomas\Documents\GitHub\practice\pe\nonvisualstudio\haskell\Spec\Problem0002.Spec.hs c:\Users\Thomas\Documents\GitHub\practice\pe\nonvisualstudio\haskell\Implementation\Problem0002.hs -} -- :r :q :set +s for times module Problem0002Tests where import Test.HUnit import System.IO import Problem0002 testCases = TestList [ TestCase $ assertEqual "sumOfEvenFibonacciesLessThan 100 should return 44" 44 (sumOfEvenFibonacciesLessThan 100), TestCase $ assertEqual "sumOfEvenFibonacciesLessThan 4000000 should return 44" 4613732 (sumOfEvenFibonacciesLessThan 4000000) ] tests = runTestTT testCases
Sobieck00/practice
pe/nonvisualstudio/haskell/OldWork/Spec/Problem0002.Spec.hs
mit
644
0
10
88
75
41
34
9
1
{-# OPTIONS #-} -- ------------------------------------------------------------ module Holumbus.Crawler.XmlArrows where import Text.XML.HXT.Core -- ------------------------------------------------------------ -- | Remove contents, when document status isn't ok, but remain meta info checkDocumentStatus :: IOSArrow XmlTree XmlTree checkDocumentStatus = replaceChildren none `whenNot` documentStatusOk -- ------------------------------------------------------------
ichistmeinname/holumbus
src/Holumbus/Crawler/XmlArrows.hs
mit
578
0
6
151
43
28
15
7
1
{-| Module : Control.Monad.Bayes.LogDomain Description : Numeric types representing numbers using their logarithms Copyright : (c) Adam Scibior, 2016 License : MIT Maintainer : [email protected] Stability : experimental Portability : GHC -} -- Log-domain non-negative real numbers -- Essentially a polymorphic version of LogFloat to allow for AD module Control.Monad.Bayes.LogDomain where import qualified Numeric.SpecFunctions as Spec import Data.Reflection import Numeric.AD.Mode.Reverse import Numeric.AD.Internal.Reverse import Numeric.AD.Internal.Identity import Numeric.AD.Jacobian -- | Log-domain non-negative real numbers. -- Used to prevent underflow when computing small probabilities. newtype LogDomain a = LogDomain a deriving (Eq, Ord) -- | Convert to log-domain. toLogDomain :: Floating a => a -> LogDomain a toLogDomain = fromLog . log -- | Inverse of `toLogDomain`. -- -- > toLogDomain . fromLogDomain = id -- > fromLogDomain . toLogDomain = id fromLogDomain :: Floating a => LogDomain a -> a fromLogDomain = exp . toLog -- | Apply a function to a log-domain value by first exponentiating, -- then applying the function, then taking the logarithm. -- -- > mapLog f = toLogDomain . f . fromLogDomain mapLog :: (Floating a, Floating b) => (a -> b) -> LogDomain a -> LogDomain b mapLog f = toLogDomain . f . fromLogDomain -- | A raw representation of a logarithm. -- -- > toLog = log . fromLogDomain toLog :: LogDomain a -> a toLog (LogDomain x) = x -- | Inverse of `toLog`. -- -- > fromLog = toLogDomain . exp fromLog :: a -> LogDomain a fromLog = LogDomain -- | Apply a function to a logarithm. -- -- > liftLog f = fromLog . f . toLog liftLog :: (a -> b) -> LogDomain a -> LogDomain b liftLog f = fromLog . f . toLog -- | Apply a function of two arguments to two logarithms. -- -- > liftLog2 f x y = fromLog $ f (toLog x) (toLog y) liftLog2 :: (a -> b -> c) -> LogDomain a -> LogDomain b -> LogDomain c liftLog2 f x y = fromLog $ f (toLog x) (toLog y) instance Show a => Show (LogDomain a) where show = show . toLog instance (Ord a, Floating a) => Num (LogDomain a) where x + y = if y > x then y + x else fromLog (toLog x + log (1 + exp (toLog y - toLog x))) x - y = if x >= y then fromLog (toLog x + log (1 - exp (toLog y - toLog x))) else error "LogDomain: subtraction resulted in a negative value" (*) = liftLog2 (+) negate _ = error "LogDomain does not support negation" abs = id signum x = if toLog x == -1/0 then 0 else 1 fromInteger = toLogDomain . fromInteger instance (Real a, Floating a) => Real (LogDomain a) where toRational = toRational . fromLogDomain instance (Ord a, Floating a) => Fractional (LogDomain a) where (/) = liftLog2 (-) recip = liftLog negate fromRational = toLogDomain . fromRational instance (Ord a, Floating a) => Floating (LogDomain a) where pi = toLogDomain pi exp = liftLog exp log = liftLog log sqrt = liftLog (/ 2) x ** y = liftLog (* fromLogDomain y) x logBase x y = log y / log x sin = mapLog sin cos = mapLog cos tan = mapLog tan asin = mapLog asin acos = mapLog acos atan = mapLog atan sinh = mapLog sinh cosh = mapLog cosh tanh = mapLog tanh asinh = mapLog asinh acosh = mapLog acosh atanh = mapLog atanh -- | A class for numeric types that provide certain special functions. class Floating a => NumSpec a where {-# MINIMAL (gamma | logGamma) , (beta | logBeta) #-} -- | Gamma function. gamma :: a -> a gamma = exp . logGamma -- | Beta function. beta :: a -> a -> a beta a b = exp $ logBeta a b -- | Logarithm of `gamma`. -- -- > logGamma = log . gamma logGamma :: a -> a logGamma = log . gamma -- | Logarithm of `beta` -- -- > logBeta a b = log (beta a b) logBeta :: a -> a -> a logBeta a b = log $ beta a b instance NumSpec Double where logGamma = Spec.logGamma logBeta = Spec.logBeta instance (Ord a, NumSpec a) => NumSpec (LogDomain a) where gamma = liftLog (logGamma . exp) beta a b = liftLog2 (\x y -> logBeta (exp x) (exp y)) a b ------------------------------------------------- -- Automatic Differentiation instances instance (Reifies s Tape) => NumSpec (Reverse s Double) where logGamma = lift1 logGamma (Id . Spec.digamma . runId) logBeta = lift2 logBeta (\(Id x) (Id y) -> (Id (psi x - psi (x+y)), Id (psi y - psi (x+y)))) where psi = Spec.digamma
ocramz/monad-bayes
src/Control/Monad/Bayes/LogDomain.hs
mit
4,423
0
16
1,000
1,299
691
608
-1
-1
module Frontend.Values where import Frontend.Types import Internal data Value = IntValue Int | FloatValue Float | BoolValue Bool | UnitValue deriving Eq instance Show Value where show (IntValue i) = show i show (FloatValue f) = show f show (BoolValue True) = "true" show (BoolValue False) = "false" show UnitValue = "()" typeOfValue :: Value -> Type typeOfValue (IntValue _) = IntType typeOfValue (FloatValue _) = FloatType typeOfValue (BoolValue _) = BoolType typeOfValue UnitValue = UnitType
alpicola/mel
src/Frontend/Values.hs
mit
553
0
8
135
176
92
84
19
1
data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show) data Direction = L | R deriving (Show) type Directions = [ Direction ] freeTree :: Tree Char freeTree = Node 'P' (Node 'O' (Node 'L' (Node 'N' Empty Empty) (Node 'T' Empty Empty) ) (Node 'Y' (Node 'S' Empty Empty) (Node 'A' Empty Empty) ) ) (Node 'L' (Node 'W' (Node 'C' Empty Empty) (Node 'R' Empty Empty) ) (Node 'A' (Node 'A' Empty Empty) (Node 'C' Empty Empty) ) ) data Crumb a = LeftCrumb a (Tree a) | RightCrumb a (Tree a) deriving (Show) type Breadcrumbs a = [ Crumb a ] type Zipper a = (Tree a, Breadcrumbs a) goLeft :: Zipper a -> Maybe (Zipper a) goLeft (Node x l r, bs) = Just (l, LeftCrumb x r:bs) goLeft (Empty, _) = Nothing goRight :: Zipper a -> Maybe (Zipper a) goRight (Node x l r, bs) = Just (r, RightCrumb x l:bs) goRight (Empty, _) = Nothing goUp :: Zipper a -> Maybe (Zipper a) goUp (t, LeftCrumb x r:bs) = Just (Node x t r, bs) goUp (t, RightCrumb x l:bs) = Just (Node x l t, bs) goUp (_, []) = Nothing moveAround = return (freeTree, []) >>= goLeft >= goRight
afronski/playground-fp
books/learn-you-a-haskell-for-great-good/zippers/trees.hs
mit
1,321
0
11
489
580
304
276
34
1
module GameTests where import Chess.FEN import Chess.Internal.Piece import Chess.Internal.Move import Chess.Internal.Game import TestUtils import Test.Hspec gameSpec :: IO () gameSpec = hspec $ describe "Game" $ do applyMoveSpec isCheckmateSpec isStalemateSpec isInsufficientMaterialSpec isDrawSpec getWinnerSpec applyMoveSpec :: Spec applyMoveSpec = describe "applyMove" $ do it "should update board, player and full move counter correctly" $ testApplyingMove "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" (Movement (Piece White Pawn) (coord "e2") (coord "e3")) "rnbqkbnr/pppppppp/8/8/8/4P3/PPPP1PPP/RNBQKBNR b KQkq - 0 1" it "should update en passant square for white correctly" $ testApplyingMove "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" (PawnDoubleMove (Piece White Pawn) (coord "e2") (coord "e4")) "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1" it "should update en passant square for black correctly" $ testApplyingMove "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1" (PawnDoubleMove (Piece Black Pawn) (coord "c7") (coord "c5")) "rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c6 0 2" it "should update halfmove counter when no capture of pawn advance" $ testApplyingMove "rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c6 0 2" (Movement (Piece White Knight) (coord "g1") (coord "f3")) "rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2" it "should zero halfmove counter piece is captured" $ testApplyingMove "r1bqkb1r/pppppppp/2n2n2/4N3/8/2N5/PPPPPPPP/R1BQKB1R b KQkq - 5 3" (Capture (Piece Black Knight) (coord "c6") (coord "e5")) "r1bqkb1r/pppppppp/5n2/4n3/8/2N5/PPPPPPPP/R1BQKB1R w KQkq - 0 4" it "should zero halfmove counter when pawn moves" $ testApplyingMove "r1bqkb1r/pppp1ppp/2n2n2/4p3/2B1P3/2N2N2/PPPP1PPP/R1BQK2R b KQkq - 5 4" (Movement (Piece Black Pawn) (coord "d7") (coord "d6")) "r1bqkb1r/ppp2ppp/2np1n2/4p3/2B1P3/2N2N2/PPPP1PPP/R1BQK2R w KQkq - 0 5" it "should zero halfmove counter when pawn promotes" $ testApplyingMove "rnbqkbnr/ppp2ppp/B7/4N3/8/2N5/PPPP2pP/R1BQK2R b KQkq - 1 6" (Promotion (Piece Black Pawn) (coord "g2") (coord "g1") Queen) "rnbqkbnr/ppp2ppp/B7/4N3/8/2N5/PPPP3P/R1BQK1qR w KQkq - 0 7" it "should zero halfmove counter when pawn promotes and captures" $ testApplyingMove "rnbqkbnr/ppp2ppp/B7/4N3/8/2N5/PPPP2pP/R1BQK2R b KQkq - 1 6" (Promotion (Piece Black Pawn) (coord "g2") (coord "h1") Queen) "rnbqkbnr/ppp2ppp/B7/4N3/8/2N5/PPPP3P/R1BQK2q w Qkq - 0 7" it "should invalidate short castling when kingside rook moves" $ testApplyingMove "rnbqk1nr/pppp2pp/5p2/2b5/2B1Pp2/5N2/PPPP2PP/RNBQK2R w KQkq - 0 5" (Movement (Piece White Rook) (coord "h1") (coord "g1")) "rnbqk1nr/pppp2pp/5p2/2b5/2B1Pp2/5N2/PPPP2PP/RNBQK1R1 b Qkq - 1 5" it "should invalidate long castling when queenside rook moves" $ testApplyingMove "r3k1nr/pppq2pp/2npbp2/2b5/2B1PB2/2NP1N2/PPP1Q1PP/R3K1R1 b Qkq - 0 9" (Movement (Piece Black Rook) (coord "a8") (coord "d8")) "3rk1nr/pppq2pp/2npbp2/2b5/2B1PB2/2NP1N2/PPP1Q1PP/R3K1R1 w Qk - 1 10" it "should invalidate both castlings when king moves" $ testApplyingMove "rnb1kbnr/ppppqppp/8/4p3/2B1P3/8/PPPP1PPP/RNBQK1NR w KQkq - 2 3" (Movement (Piece White King) (coord "e1") (coord "e2")) "rnb1kbnr/ppppqppp/8/4p3/2B1P3/8/PPPPKPPP/RNBQ2NR b kq - 3 3" it "should invalidate long castling when queenside rook is captured" $ testApplyingMove "r1b1kbnr/1p1npppp/R2q4/p1pp4/P7/8/1PPPPPPP/1NBQKBNR w Kkq - 4 6" (Capture (Piece White Rook) (coord "a6") (coord "a8")) "R1b1kbnr/1p1npppp/3q4/p1pp4/P7/8/1PPPPPPP/1NBQKBNR b Kk - 0 6" isCheckmateSpec :: Spec isCheckmateSpec = describe "isCheckmate" $ do it "should not consider initial state as checkmate" $ isCheckmate initialState `shouldBe` False it "should not consider check a checkmate" $ isCheckmate (game "rnbqkb1r/ppp2ppp/3p1n2/1B2p3/4P3/2N2N2/PPPP1PPP/R1BQK2R b KQkq - 1 4") `shouldBe` False it "should not consider stalemates a checkmate" $ do isCheckmate (game "1R6/8/8/8/8/8/7R/k6K b - - 0 1") `shouldBe` False isCheckmate (game "8/8/5k2/p4p1p/P4K1P/1r6/8/8 w - - 0 2") `shouldBe` False it "should detect checkmate correctly" $ do isCheckmate (game "8/5r2/4K1q1/4p3/3k4/8/8/8 w - - 0 7") `shouldBe` True isCheckmate (game "4r2r/p6p/1pnN2p1/kQp5/3pPq2/3P4/PPP3PP/R5K1 b - - 0 2") `shouldBe` True isCheckmate (game "r3k2r/ppp2p1p/2n1p1p1/8/2B2P1q/2NPb1n1/PP4PP/R2Q3K w kq - 0 8") `shouldBe` True isCheckmate (game "8/6R1/pp1r3p/6p1/P3R1Pk/1P4P1/7K/8 b - - 0 4") `shouldBe` True isStalemateSpec :: Spec isStalemateSpec = describe "isStalemate" $ do it "should not consider initial state as stalemate" $ isStalemate initialState `shouldBe` False it "should not consider check a stalemate" $ isStalemate (game "rnbqkb1r/ppp2ppp/3p1n2/1B2p3/4P3/2N2N2/PPPP1PPP/R1BQK2R b KQkq - 1 4") `shouldBe` False it "should detect stalemate correctly" $ do isStalemate (game "1R6/8/8/8/8/8/7R/k6K b - - 0 1") `shouldBe` True isStalemate (game "8/8/5k2/p4p1p/P4K1P/1r6/8/8 w - - 0 2") `shouldBe` True isInsufficientMaterialSpec :: Spec isInsufficientMaterialSpec = describe "isInsufficientMaterial" $ do it "should not consider initial state as insufficient material" $ isInsufficientMaterial initialState `shouldBe` False it "should not consider queen+king vs. queen+king as insufficient material" $ isInsufficientMaterial (game "3qk3/8/8/8/8/8/8/3QK3 w - - 0 10") `shouldBe` False it "should not consider rook+king vs. king as insufficient material" $ do isInsufficientMaterial (game "4k3/8/8/8/8/8/8/3RK3 w - - 0 10") `shouldBe` False isInsufficientMaterial (game "4k3/2r5/8/8/8/8/8/4K3 w - - 0 1") `shouldBe` False it "should not consider pawn+king vs. king as insufficient material" $ do isInsufficientMaterial (game "4k3/8/8/8/8/8/1P6/4K3 w - - 0 10") `shouldBe` False isInsufficientMaterial (game "4k3/2p5/8/8/8/8/8/4K3 w - - 0 1") `shouldBe` False it "should not consider knight+bishop+king vs. king as insufficient material" $ isInsufficientMaterial (game "4k3/8/8/8/8/8/2BN4/4K3 w - - 0 1") `shouldBe` False it "should not consider bishop+bishop+king vs. king as insufficient material if bishops are on different colored squares" $ isInsufficientMaterial (game "4k3/8/8/8/8/8/2BB4/4K3 w - - 0 1") `shouldBe` False it "should consider bishop+bishop+king vs. king as insufficient material if bishops are on same colored squares" $ isInsufficientMaterial (game "4k3/8/8/8/8/2B5/3B4/4K3 w - - 0 1") `shouldBe` True it "should not consider knight+knight+king vs. king as insufficient material" $ isInsufficientMaterial (game "4k3/8/8/8/8/8/2NN4/4K3 w - - 0 1") `shouldBe` False it "should consider king vs. king as insufficient material" $ isInsufficientMaterial (game "4k3/8/8/8/8/8/8/4K3 w - - 0 10") `shouldBe` True it "should consider bishop+king vs. king as insufficient material" $ do isInsufficientMaterial (game "4k3/8/8/8/8/8/8/3BK3 w - - 0 10") `shouldBe` True isInsufficientMaterial (game "4k3/2b5/8/8/8/8/8/4K3 w - - 0 1") `shouldBe` True it "should consider knight+king vs. king as insufficient material" $ do isInsufficientMaterial (game "4k3/8/8/8/8/8/8/3NK3 w - - 0 10") `shouldBe` True isInsufficientMaterial (game "4k3/2n5/8/8/8/8/8/4K3 w - - 0 1") `shouldBe` True it "should consider bishop+king vs. bishop+king as insufficient material if both bishops are on same color square" $ isInsufficientMaterial (game "4k3/8/3b4/8/8/8/1B6/4K3 w - - 0 10") `shouldBe` True it "should consider n*bishop+king vs. n*bishop+king as insufficient material if bishop pairs are on same color square" $ isInsufficientMaterial (game "8/b1B1b1B1/1b1B1b1B/8/8/8/8/1k5K w - - 0 1") `shouldBe` True it "should not consider n*bishop+king vs. n*bishop+king as insufficient material if bishop pairs are on different color square" $ isInsufficientMaterial (game "8/bB2b1B1/1b1B1b1B/8/8/8/8/1k5K w - - 0 1") `shouldBe` False it "should not consider bishop+king vs. bishop+king as insufficient material if both bishops are on different color square" $ isInsufficientMaterial (game "4k3/8/4b3/8/8/8/1B6/4K3 w - - 0 10") `shouldBe` False isDrawSpec :: Spec isDrawSpec = describe "isDraw" $ do it "should not detect normal game as draw" $ isDraw initialState `shouldBe` False it "should not detect checkmate as draw" $ isDraw (game "8/5r2/4K1q1/4p3/3k4/8/8/8 w - - 0 7") `shouldBe` False it "should detect stalemate as draw" $ isDraw (game "1R6/8/8/8/8/8/7R/k6K b - - 0 1") `shouldBe` True it "should detect insufficient material as draw" $ isDraw (game "4k3/8/8/8/8/8/8/4K3 w - - 0 10") `shouldBe` True testApplyingMove :: String -> Move -> String -> Expectation testApplyingMove beforeFen move afterFen = writeFEN newGame `shouldBe` afterFen where Right newGame = applyMove (game beforeFen) move getWinnerSpec :: Spec getWinnerSpec = describe "getWinner" $ do it "should not give winner if there is no checkmate" $ getWinner (game "rnbqkb1r/ppp2ppp/3p1n2/1B2p3/4P3/2N2N2/PPPP1PPP/R1BQK2R b KQkq - 1 4") `shouldBe` Nothing it "should not give winner if the game is draw" $ getWinner (game "1R6/8/8/8/8/8/7R/k6K b - - 0 1") `shouldBe` Nothing it "should return correct winner if the game is checkmate" $ do getWinner (game "8/5r2/4K1q1/4p3/3k4/8/8/8 w - - 0 7") `shouldBe` Just Black getWinner (game "4r2r/p6p/1pnN2p1/kQp5/3pPq2/3P4/PPP3PP/R5K1 b - - 0 2") `shouldBe` Just White
nablaa/hchesslib
test/Chess/GameTests.hs
gpl-2.0
10,736
0
14
2,676
1,720
828
892
129
1
import Graphics.UI.Gtk hiding (Settings) import Data.Time.Clock.POSIX import Data.Time import System.Directory import Control.Exception import System.Locale (defaultTimeLocale) import Data.IORef import Control.Monad (when,forM) import Data.List import Text.Printf iDuration = 30 rDuration = 120 amountOfIntervals = rDuration `div` iDuration data Result = Result { rDate :: String, rMrks, rRank, rErrs :: Int } deriving (Read, Show) instance Eq Result where (Result date1 mrks1 rnk1 errs1) == (Result date2 mrks2 rnk2 errs2) = mrks1 == mrks2 && date1 == date2 instance Ord Result where compare = fasterFst fasterFst (Result date1 mrks1 rnk1 errs1) (Result date2 mrks2 rnk2 errs2) = if mrks1 /= mrks2 then mrks2 `compare` mrks1 else date1 `compare` date2 zeroResult = Result { rDate = "0000-00-00 00:00:00", rMrks = 0, rRank = 0, rErrs = 0 } data Timing = Timing { sSession :: String, sTotal :: Int, sSecsLeft :: Int, sSpeed :: Double } deriving Show zeroTiming = Timing { sSession = "00:00", sTotal = 0, sSecsLeft = iDuration, sSpeed = 0.0 } data Interval = Interval { iNum, iMrks, iErrs :: Int } deriving Show zeroInterval = Interval { iNum = -1, iMrks = 0, iErrs = 0 } data GUI = NotCreated | GUI { gEntry :: Entry, gLabel1, gLabel2 :: Label, gModelR :: ListStore Result, gModelS :: ListStore Timing, gModelI :: ListStore Interval } data GameStatus = Error | Correct | Back | NotStarted deriving (Eq, Show) data State = State { homeDirectory :: String, textLines :: [String], startTime :: POSIXTime, oldStatus :: GameStatus, oldlen :: Int, lastShownIv :: Int, oLabelStrs :: [String], total :: Int, speedNows :: [(POSIXTime, Int)], intervals :: [Interval], results :: [Result], sessionBest :: Result, settings :: Settings, gui :: GUI } initState = State { homeDirectory = "", textLines = [], startTime = fromIntegral 0 :: POSIXTime, oldStatus = NotStarted, oLabelStrs = ["",""], oldlen = 0, total = 0, speedNows = [], lastShownIv = -1, intervals = [], results = [], sessionBest = zeroResult, settings = defaultSettings, gui = NotCreated } data Settings = Settings { startLine :: Int, lineLen :: Int, textfile :: String, font :: String } deriving (Read, Show) defaultSettings = Settings { startLine = 0, lineLen = 60, textfile = "morse.txt", font = "monospace 10" } xxx = replicate (lineLen defaultSettings) 'x' s gs = settings gs g gs = gui gs r gs = results gs resultsFromFile fname = do structFromFile fname readRs [] settingsFromFile fname = do structFromFile fname readSs defaultSettings structFromFile fname pFunc zero = do content <- readFile fname `catch` \(SomeException e) -> return "" result <- pFunc content `catch` \(SomeException e) -> return zero return result readRs :: String -> IO [Result] readRs = readIO readSs :: String -> IO Settings readSs = readIO resultsFile = "results.txt" settingsFile = "settings.txt" getStartupConfig gsRef = do gs <- readIORef gsRef -- directory homedir <- getHomeDirectory let dir = homedir ++ "/.hatupist" createDirectoryIfMissing False (dir) -- settings let rname = dir ++ "/" ++ settingsFile oldSettings <- settingsFromFile rname putStrLn ("Reading " ++ rname) putStrLn (show (oldSettings)) -- results let rname = dir ++ "/" ++ resultsFile oldResults <- resultsFromFile rname putStrLn ("Reading " ++ rname ++ ": " ++ show (length (oldResults)) ++ " rows") listStoreSetValue (gModelR (g gs)) 0 (bestResult oldResults) -- other writeIORef gsRef gs { homeDirectory = dir, results = oldResults, settings = oldSettings } setFonts gsRef getLines gsRef = do gs <- readIORef gsRef originalText <- readFile (textfile (s gs)) let textLinesss = colLines (collectWords (words (originalText)) (lineLen (s gs))) textLiness = map (++" ") textLinesss writeIORef gsRef gs { textLines = textLiness } renewLabels gsRef quitProgram gsRef = do print "Quitting." gs <- readIORef gsRef -- results let rname = (homeDirectory gs) ++ "/" ++ resultsFile writeFile rname (show (r gs)) putStrLn ("Writing " ++ rname) -- settings let rname = (homeDirectory gs) ++ "/" ++ settingsFile writeFile rname (show (s gs)) putStrLn ("Writing " ++ rname) mainQuit main = do gsRef <- newIORef initState initGUI createGUI gsRef getStartupConfig gsRef getLines gsRef gs <- readIORef gsRef mainGUI setFonts gsRef = do gs <- readIORef gsRef let gui = g gs newFont = font (s gs) srcfont <- fontDescriptionFromString newFont widgetModifyFont (gLabel1 gui) (Just srcfont) widgetModifyFont (gLabel2 gui) (Just srcfont) widgetModifyFont (gEntry gui) (Just srcfont) getStatus :: String -> String -> Int -> GameStatus getStatus written goal oldlen | a == b && c < d = Correct | a == b = Back | otherwise = Error where a = written b = commonPrefix written goal c = oldlen d = length written commonPrefix (x:xs) (y:ys) | x == y = x : commonPrefix xs ys | otherwise = [] commonPrefix _ _ = [] rInitModel = replicate 3 zeroResult rColTitles = ["Päiväys", "Tulos", "Sija", "Virheitä" ] rColFuncs = [ rDate, rSpeed . rMrks, rShowRank, rErrorPros] sInitModel = [zeroTiming] sColTitles = ["Istunto", "Yhteensä", "Jäljellä", "Nopeus"] sColFuncs = [ sSession, show . sTotal, show . sSecsLeft, f01 . sSpeed] iInitModel = replicate amountOfIntervals zeroInterval iColTitles = ["Alkoi", "Päättyi", "Nopeus", "Virheitä" ] iColFuncs = [ iStarts . iNum, iEnds . iNum, iSpeed . iMrks, iErrorPros] createGUI gsRef = do gs <- readIORef gsRef window <- windowNew onDestroy window (quitProgram gsRef) extrmVBox <- vBoxNew False 0 outerHBox <- hBoxNew False 0 outerVBox <- vBoxNew False 0 middleHBox <- hBoxNew False 0 innerVBox1 <- vBoxNew False 0 innerVBox2 <- vBoxNew False 0 menubar <- createMenuBar menuBarDescr gsRef boxPackStart extrmVBox menubar PackNatural 0 rModel <- setupView rInitModel rColTitles rColFuncs innerVBox1 sModel <- setupView sInitModel sColTitles sColFuncs innerVBox1 iModel <- setupView iInitModel iColTitles iColFuncs innerVBox2 boxPackStart middleHBox innerVBox1 PackNatural 0 boxPackStart middleHBox innerVBox2 PackNatural 6 boxPackStart outerVBox middleHBox PackNatural 3 boxPackStart outerHBox outerVBox PackNatural 6 boxPackStart extrmVBox outerHBox PackNatural 0 set window [ windowTitle := "Hatupist", containerChild := extrmVBox ] label1 <- labelNew (Just xxx) miscSetAlignment label1 0 0 boxPackStart outerVBox label1 PackNatural 0 label2 <- labelNew (Just xxx) miscSetAlignment label2 0 0 boxPackStart outerVBox label2 PackNatural 0 entry <- entryNew entrySetHasFrame entry False boxPackStart outerVBox entry PackNatural 3 onEditableChanged entry ( whenEntryChanged gsRef) widgetShowAll window writeIORef gsRef gs { gui = GUI { gEntry = entry, gLabel1 = label1, gLabel2 = label2, gModelR = rModel, gModelS = sModel, gModelI = iModel }} setupView initModel titles funcs parent = do model <- listStoreNew (initModel) view <- treeViewNewWithModel model mapM ( \(title, func) -> newcol view model title func ) ( zip titles funcs ) set view [ widgetCanFocus := False ] boxPackStart parent view PackNatural 3 return model where newcol view model title func = do renderer <- cellRendererTextNew col <- treeViewColumnNew cellLayoutPackStart col renderer True cellLayoutSetAttributes col renderer model ( \row -> [ cellText := func row]) treeViewColumnSetTitle col title treeViewAppendColumn view col menuBarDescr = [("_Tiedosto", [("gtk-open", openFile), ("gtk-select-font", openFont), ("gtk-preferences", setPreferences), ("gtk-about", noop), ("gtk-quit", quitProgram)]) ] createMenuBar descr gsRef = do bar <- menuBarNew mapM_ (createMenu bar) descr return bar where createMenu bar (name,items) = do menu <- menuNew item <- menuItemNewWithLabelOrMnemonic name menuItemSetSubmenu item menu menuShellAppend bar item mapM_ (createMenuItem menu) items createMenuItem menu (stock,action) = do item <- imageMenuItemNewFromStock stock menuShellAppend menu item onActivateLeaf item (do action gsRef) menuItemNewWithLabelOrMnemonic name | elem '_' name = menuItemNewWithMnemonic name | otherwise = menuItemNewWithLabel name noop gsRef = do return () setPreferences gsRef = do gs <- readIORef gsRef result <- chooseLineLen "Rivinpituus" (lineLen (s gs)) case result of Just newLineLen -> do writeIORef gsRef gs { settings = (s gs) { lineLen = newLineLen, startLine = 0 }} getLines gsRef otherwise -> return () chooseLineLen prompt oldLineLen = do dialog <- dialogNew set dialog [ windowTitle := prompt ] dialogAddButton dialog stockCancel ResponseCancel dialogAddButton dialog stockOk ResponseOk nameLabel <- labelNew $ Just "Rivinpituus (merkkiä):" adjustment <- adjustmentNew (fromIntegral oldLineLen) 1 250 5 1 0 spinbutton <- spinButtonNew adjustment 1.0 0 upbox <- dialogGetUpper dialog boxPackStart upbox nameLabel PackNatural 0 boxPackStart upbox spinbutton PackNatural 0 widgetShowAll upbox response <- dialogRun dialog print response widgetDestroy dialog case response of ResponseOk -> do value <- spinButtonGetValueAsInt spinbutton widgetDestroy dialog return (Just value) ResponseCancel -> do widgetDestroy dialog return Nothing ResponseDeleteEvent -> do widgetDestroy dialog return Nothing _ -> return Nothing openFont gsRef = do gs <- readIORef gsRef result <- chooseFont "Valitse kirjasin" (font (s gs)) case result of Just newFont -> do writeIORef gsRef gs { settings = (s gs) { font = newFont }} setFonts gsRef otherwise -> return () chooseFont prompt oldFont = do dialog <- fontSelectionDialogNew prompt fontSelectionDialogSetFontName dialog oldFont widgetShow dialog response <- dialogRun dialog print response case response of ResponseOk -> do fn <- fontSelectionDialogGetFontName dialog widgetDestroy dialog return fn ResponseCancel -> do widgetDestroy dialog return Nothing ResponseDeleteEvent -> do widgetDestroy dialog return Nothing _ -> return Nothing openFile gsRef = do gs <- readIORef gsRef result <- chooseFile "Valitse teksti" case result of Just newTextFile -> do writeIORef gsRef gs { settings = (s gs) { textfile = newTextFile, startLine = 0 }} getLines gsRef otherwise -> return () chooseFile prompt = do dialog <- fileChooserDialogNew (Just prompt) Nothing FileChooserActionOpen [("gtk-cancel",ResponseCancel), ("gtk-open", ResponseAccept)] fileChooserSetCurrentFolder dialog "." widgetShow dialog response <- dialogRun dialog case response of ResponseAccept -> do fn <- fileChooserGetFilename dialog widgetDestroy dialog return fn ResponseCancel -> do widgetDestroy dialog return Nothing ResponseDeleteEvent -> do widgetDestroy dialog return Nothing _ -> return Nothing rShowRank rR = showRank (rRank rR) rErrorPros rR = f02p (errorPros (rErrs rR) (rMrks rR)) iErrorPros iV = f02p (errorPros (iErrs iV) (iMrks iV)) errorPros errs mrks | total == 0 = 0.0 | otherwise = 100.0 * (intToDouble errs) / (intToDouble total) where total = mrks + errs f01 :: Double -> String f01 = printf "%.1f" f02p :: Double -> String f02p = printf "%.2f%%" speed mrks t = (intToDouble mrks) * 60.0 / (max t 1.0) iSpeed mrks = f01 (speed mrks (intToDouble iDuration)) rSpeed mrks = f01 (speed mrks (intToDouble rDuration)) iStarts n | n <= 0 = "00:00" | otherwise = mmss (fromIntegral (n*iDuration) :: Double) iEnds n = iStarts (n+1) iNumber t = floor t `div` iDuration iLeft t = iDuration - (floor t `mod` iDuration) mmss seconds = leadingZero (show (floor seconds `div` 60)) ++ ":" ++ leadingZero (show (floor seconds `mod` 60)) leadingZero s | length s < 2 = "0" ++ s | otherwise = s secondsFrom startPt endPt = a - b where a = ptToDouble endPt b = ptToDouble startPt ptToDouble :: POSIXTime -> Double ptToDouble t = fromRational (toRational t) intToDouble :: Int -> Double intToDouble i = fromRational (toRational i) blankStart n str = replicate n ' ' ++ drop n str renewLabels gsRef = do gs <- readIORef gsRef let labelStrs = labelStrings (startLine (settings gs)) (textLines gs) set (gLabel1 (g gs)) [ labelLabel := labelStrs !! 0 ] set (gLabel2 (g gs)) [ labelLabel := labelStrs !! 1 ] writeIORef gsRef gs { oLabelStrs = labelStrs } entrySetText (gEntry (g gs)) "" labelStrings :: Int -> [String] -> [String] labelStrings startline textLines = [textLines !! first] ++ [textLines !! second] where first = startline `mod` (length textLines) second = (startline + 1) `mod` (length textLines) ivsBetween iMin iMax ivs = filter (\iv -> iMin <= (iNum iv) && (iNum iv) <= iMax) ivs ivsFrom iMin ivs = filter (\iv -> iMin <= (iNum iv)) ivs ivsAllBetween iMin iMax ivs = [ivExactly n ivs | n <- [iMin .. iMax]] ivExactly n ivs = case find (\iv -> n == (iNum iv)) ivs of Just x -> x Nothing -> zeroInterval { iNum = n } tableRRefreshMs = 500 speedFromMs = 10000 speedCount = speedFromMs `div` tableRRefreshMs difs speds = if null speds then (0.0, 0) else (secondsFrom (fst start) (fst end), (snd end) - (snd start)) where start = last speds end = head speds renewTableS gs t = do pt <- getPOSIXTime let newGs = gs { speedNows = [(pt, (total gs))] ++ take speedCount (speedNows gs) } let s = difs (speedNows newGs) listStoreSetValue (gModelS (g gs)) 0 Timing { sSecsLeft = iLeft t, sSession = mmss t, sTotal = total gs, sSpeed = speed (snd s) (fst s) } return newGs bestResult results = if null results then zeroResult else head results timeFormatted :: ZonedTime -> String timeFormatted = formatTime defaultTimeLocale "%Y-%m-%d %H:%M:%S" reRank1 (Result { rDate = a, rMrks = b, rRank = c, rErrs = d }, newRank) = Result { rDate = a, rMrks = b, rRank = newRank, rErrs = d } reRank rs = map reRank1 (zip rs [1..]) addResult showIvs gs = do pt <- getPOSIXTime tz <- getCurrentTimeZone let newResult0 = zeroResult { rDate = timeFormatted (utcToZonedTime tz (posixSecondsToUTCTime pt)), rMrks = sum [iMrks g | g <- showIvs], rErrs = sum [iErrs g | g <- showIvs] } let newResult = newResult0 { rRank = tellRank newResult0 (results gs) } let newRs = take maxRank (insert newResult (results gs)) new2Rs = reRank newRs newShownRs = [ bestResult new2Rs, (sessionBest gs) `min` newResult, newResult ] return (new2Rs, newShownRs) showRank rank | rank <= maxRank = show rank | otherwise = ">" ++ show maxRank tellRank x xs = case findIndex (x <=) xs of Just n -> n + 1 Nothing -> length xs + 1 maxRank = 5000 renewTableR gs shownRs = do mapM (\(a,b) -> listStoreSetValue (gModelR (g gs)) a b) (zip [0..] shownRs) return () renewTableI gs iCur = do mapM (\(a,b) -> listStoreSetValue (gModelI (g gs)) (amountOfIntervals-a) b) (zip [1..] showIvs) (newRs, newShownRs) <- addResult showIvs gs return (gs { intervals = newIvs, lastShownIv = iCur, results = newRs, sessionBest = newShownRs !! 1 }, newShownRs) where iMaxShow = iCur - 1 infimum = iMaxShow - amountOfIntervals + 1 iMinShow = max 0 infimum iMinNeed = max 0 (infimum + 1) newIvs = ivsFrom iMinNeed (intervals gs) showIvs = reverse (ivsAllBetween iMinShow iMaxShow (intervals gs)) renewSeldomTables gs iCur = do (newGs, shownRs) <- renewTableI gs iCur renewTableR newGs shownRs return newGs renewTables gs t iCur = do newGs <- renewTableS gs t new2Gs <- if (lastShownIv newGs /= iCur) && iCur >= 1 then renewSeldomTables newGs iCur else return newGs return new2Gs onTimeout gsRef = do gs <- readIORef gsRef pt <- getPOSIXTime let t = secondsFrom (startTime gs) pt iCur = iNumber t newGs <- renewTables gs t iCur writeIORef gsRef newGs return True whenEntryChanged gsRef = do pt <- getPOSIXTime gs <- readIORef gsRef txt <- entryGetText (gEntry (g gs)) let label1Str = head (oLabelStrs gs) status = getStatus txt label1Str (oldlen gs) f = case (status,oldStatus gs) of (_,NotStarted) -> whenNotStarted status (Correct,_) -> whenCorrect txt (Error,Correct) -> whenNewError otherwise -> whenOther status (oldStatus gs) cprfix = length (commonPrefix txt label1Str) newGs <- f pt gsRef gs set (gLabel1 (g gs)) [ labelLabel := blankStart cprfix label1Str] writeIORef gsRef newGs { oldStatus = status, oldlen = max cprfix (oldlen gs) } when (label1Str == txt) (advanceLine gsRef newGs) return () whenNotStarted status pt gsRef gs = do putStrLn ("Started with " ++ (show status)) timeoutAdd (onTimeout gsRef) tableRRefreshMs return gs { total = if status == Correct then 1 else 0, startTime = pt, intervals = addTime status (iNumber 0.0) (intervals gs) } whenCorrect txt pt gsRef gs = do print "Correct." return gs { total = (total gs) + 1, intervals = addTime Correct (iNumber (secondsFrom (startTime gs) pt)) (intervals gs) } whenNewError pt gsRef gs = do print "New Error." return gs { intervals = addTime Error (iNumber (secondsFrom (startTime gs) pt)) (intervals gs) } whenOther status oldStatus pt gsRef gs = do putStrLn ("Other with " ++ (show (status,oldStatus))) return gs latestIvNum ivs = if null ivs then -1 else iNum (head ivs) addTime status i intervals = [newHead] ++ tail newIvs where newHead = case status of Correct -> headIv { iMrks = (iMrks headIv) + 1 } Error -> headIv { iErrs = (iErrs headIv) + 1 } headIv = head newIvs newIvs = if null intervals || i /= latestIvNum intervals then [zeroInterval { iNum = i }] ++ intervals else intervals advanceLine gsRef gs = do gs <- readIORef gsRef let newStartLine = ((startLine (s gs)) + 1) `mod` (length (textLines gs)) writeIORef gsRef gs { settings = (s gs) { startLine = newStartLine}, oldlen = 0 } renewLabels gsRef return () colLines (xs:xss) = (unwords xs) : colLines xss colLines [] = [] collectWords [] n = [] collectWords ys n = p1 : collectWords p2 n where (p1,p2) = splitAt (length (untilLen ys 0 n)) ys untilLen (t:ts) s n | s+x<n || s==0 = t : untilLen ts (s+x) n | otherwise = [] where x = length t + 1 untilLen [] s n = []
jsavatgy/hatupist
code/settings.hs
gpl-2.0
19,266
138
17
4,674
7,264
3,452
3,812
605
4
module Main where import System.Console.GetOpt import System.Environment import System.Directory (doesDirectoryExist) import System.IO import System.Exit import Control.Applicative import Process import Poll data Options = Options { optCodeDir :: String , optDocsDir :: String , optCss :: Maybe String , optCode :: Bool , optHtml :: Bool , optMarkdown :: Bool , optWatch :: Bool , optNumber :: Bool } startOptions :: Options startOptions = Options { optCodeDir = "./" , optDocsDir = "./" , optCss = Nothing , optCode = False , optHtml = False , optMarkdown = False , optWatch = False , optNumber = False } options :: [ OptDescr (Options -> IO Options) ] options = [ Option "h" ["html"] (NoArg (\opt -> return opt { optHtml = True })) "Generate html" , Option "m" ["markdown"] (NoArg (\opt -> return opt { optMarkdown = True })) "Generate markdown" , Option "c" ["code"] (NoArg (\opt -> return opt { optCode = True })) "Generate code by file extension" , Option "n" ["number"] (NoArg (\opt -> return opt { optNumber = True })) "Add annotations to generated code noting the source lit file and line number" , Option "" ["css"] (ReqArg (\arg opt -> return opt { optCss = Just arg }) "FILE") "Specify a css file for html generation" , Option "" ["docs-dir"] (ReqArg (\arg opt -> return opt { optDocsDir = arg }) "DIR") "Directory for generated docs" , Option "" ["code-dir"] (ReqArg (\arg opt -> return opt { optCodeDir = arg }) "DIR") "Directory for generated code" , Option "w" ["watch"] (NoArg (\opt -> return opt { optWatch = True})) "Watch for file changes, automatically run lit" , Option "v" ["version"] (NoArg (\_ -> do hPutStrLn stderr "Version 0.1.1.0" exitWith ExitSuccess)) "Print version" , Option "" ["help"] (NoArg (\_ -> do prg <- getProgName hPutStrLn stderr (usageInfo usage options) exitWith ExitSuccess)) "Display help" ] usage = "Usage: lit OPTIONS... FILES..." help = "Try: lit --help" main = do args <- getArgs -- Parse options, getting a list of option actions let (actions, files, errors) = getOpt Permute options args opts <- foldl (>>=) (return startOptions) actions let Options { optCodeDir = codeDir , optDocsDir = docsDir , optMarkdown = markdown , optCode = code , optHtml = html , optCss = mCss , optWatch = watching , optNumber = showLines } = opts codeDirCheck <- doesDirectoryExist codeDir docsDirCheck <- doesDirectoryExist docsDir let htmlPipe = if html then [Process.htmlPipeline docsDir mCss] else [] mdPipe = if markdown then [Process.mdPipeline docsDir mCss] else [] codePipe = if code then [Process.codePipeline codeDir mCss showLines] else [] pipes = htmlPipe ++ mdPipe ++ codePipe maybeWatch = if watching then Poll.watch else mapM_ errors' = if codeDirCheck then [] else ["Directory: " ++ codeDir ++ " does not exist\n"] errors'' = if docsDirCheck then [] else ["Directory: " ++ docsDir ++ " does not exist\n"] allErr = errors ++ errors' ++ errors'' if allErr /= [] || (not html && not code && not markdown) || files == [] then hPutStrLn stderr ((concat allErr) ++ help) else (maybeWatch (Process.process pipes)) files
cdosborn/lit
src/lit.hs
gpl-2.0
4,129
0
15
1,578
1,040
573
467
100
8
{-# LANGUAGE OverloadedLists #-} module Nirum.Targets.DocsSpec where import System.FilePath ((</>)) import Test.Hspec.Meta import Text.Blaze.Html.Renderer.Utf8 (renderHtml) import Nirum.Constructs.Annotation (empty) import Nirum.Constructs.DeclarationSet (DeclarationSet) import Nirum.Constructs.Module (Module (..)) import Nirum.Constructs.TypeDeclaration (TypeDeclaration (Import)) import qualified Nirum.Docs as D import qualified Nirum.Targets.Docs as DT spec :: Spec spec = describe "Docs" $ do let decls = [Import ["zzz"] "qqq" empty] :: DeclarationSet TypeDeclaration mod1 = Module decls Nothing mod2 = Module decls $ Just "module level docs...\nblahblah" mod3 = Module decls $ Just "# One Spoqa Trinity Studio\nblahblah" specify "makeFilePath" $ DT.makeFilePath ["foo", "bar", "baz"] `shouldBe` "foo" </> "bar" </> "baz" </> "index.html" specify "makeUri" $ DT.makeUri ["foo", "bar", "baz"] `shouldBe` "foo/bar/baz/index.html" specify "moduleTitle" $ do fmap renderHtml (DT.moduleTitle mod1) `shouldBe` Nothing fmap renderHtml (DT.moduleTitle mod2) `shouldBe` Nothing fmap renderHtml (DT.moduleTitle mod3) `shouldBe` Just "One Spoqa Trinity Studio" specify "blockToHtml" $ do let h = D.Paragraph [D.Strong ["Hi!"]] renderHtml (DT.blockToHtml h) `shouldBe` "<p><strong>Hi!</strong></p>"
dahlia/nirum
test/Nirum/Targets/DocsSpec.hs
gpl-3.0
1,421
0
17
275
399
218
181
30
1
Config { font = "xft:Source Code Pro:size=8" , borderColor = "#839496" , bgColor = "#073642" -- , border = FullBM 0 , border = NoBorder , fgColor = "#839496" -- , alpha = 120 , position = Static { xpos = 0, ypos = 0, width = 1600, height = 19 }, , lowerOnStart = True , hideOnStart = False , allDesktops = True , sepChar = "%" , alignSep = "}{" , overrideRedirect = True , persistent = True , commands = [ Run StdinReader -- cpu related , Run MultiCpu ["-t","<total0>%","-w","1"] 10 , Run CoreTemp ["-t","<core0>"] 10 -- memory related , Run Memory ["-t","<usedratio>%"] 10 , Run Swap ["-t","<usedratio>%"] 10 , Run DiskU [("/", "<usedp>%"), ("/home", "<usedp>%")] ["-L", "20", "-H", "50", "-m", "1", "-p", "2"] 20 -- network related , Run Com "iwgetid" ["-r"] "" 0 , Run DynNetwork ["-t", "<dev>-<tx>,<rx>"] 30 , Run Network "wlp3s0" ["-t","<rx>,<tx>"] 10 -- misc , Run BatteryP ["BAT0"] ["-t", "<acstatus>", "-L", "10", "-H", "80", "-l", "red", "-h", "green", "--", "-i", "ac", "-o", "<left>%"] 10 , Run Kbd [("be", "En"), ("ara(basic)", "Ar")] , Run Volume "default" "Master" ["-t","<volume>%"] 10 , Run Weather "GMMC" ["-t", "<tempC>°C"] 36000 , Run Date "%A %d-%m-%Y %H:%M:%S" "date" 10 -- usefull someday -- , Run DiskIO [("/", "/ <total>"), ("/home", "~ <total>")] ["-l", "green", "--normal","orange","--high","red"] 10 -- , Run Cpu ["-t","<total>%"] 10 -- , Run CpuFreq ["-t", "<cpu0>,<cpu1>"] 50 -- , Run ThermalZone 0 ["-t","<temp>C"] 30 , Run NamedXPropertyLog "_XMONAD_LOG_TOP" "xm" , Run MPD ["-t","<statei> <ppos>/<plength>","--", "-P", ">>", "-Z", "|", "-S", "><"] 10 ] , template = "%StdinReader% %mpd% }{ <fc=#fdf6e3,#657B83> %multicpu% %coretemp% %memory%-%swap% %disku% %dynnetwork% </fc><fc=#fdf6e3,#93a1a1> %battery% %default:Master% %kbd% </fc><fc=#fdf6e3,#cb4b16> %date% %GMMC% </fc>" }
wlaaraki/dotfiles
xmobar/xmobarrc.hs
gpl-3.0
2,335
2
10
801
502
306
196
-1
-1
{-# OPTIONS -Wall #-} {-# LANGUAGE OverloadedStrings, TemplateHaskell #-} module Graphics.UI.Bottle.Widgets.TextEdit( Cursor, Style(..), make, defaultCursorColor, defaultCursorWidth, atSCursorColor, atSCursorWidth, atSTextCursorId, atSBackgroundCursorId, atSEmptyString, atSTextViewStyle) where import Control.Arrow (first) import Data.Char (isSpace) import Data.List (genericLength) import Data.List.Split (splitWhen) import Data.List.Utils (enumerate) import Data.Maybe (fromJust, mapMaybe) import Data.Monoid (Monoid(..)) import Data.Vector.Vector2 (Vector2(..)) import Graphics.DrawingCombinators.Utils (square, textHeight) import Graphics.UI.Bottle.Sized (Sized(..)) import Graphics.UI.Bottle.Widget (Widget(..)) import Graphics.UI.GLFW (Key(KeyBackspace, KeyDel, KeyDown, KeyEnd, KeyEnter, KeyHome, KeyLeft, KeyRight, KeyUp)) import qualified Data.AtFieldTH as AtFieldTH import qualified Data.Binary.Utils as BinUtils import qualified Data.ByteString.Char8 as SBS8 import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.Vector.Vector2 as Vector2 import qualified Graphics.DrawingCombinators as Draw import qualified Graphics.UI.Bottle.Animation as Anim import qualified Graphics.UI.Bottle.EventMap as E import qualified Graphics.UI.Bottle.SizeRange as SizeRange import qualified Graphics.UI.Bottle.Sized as Sized import qualified Graphics.UI.Bottle.Widget as Widget import qualified Graphics.UI.Bottle.Widgets.TextView as TextView import qualified Safe type Cursor = Int data Style = Style { sCursorColor :: Draw.Color, sCursorWidth :: Draw.R, sTextCursorId :: Anim.AnimId, sBackgroundCursorId :: Anim.AnimId, sEmptyString :: String, sTextViewStyle :: TextView.Style } AtFieldTH.make ''Style defaultCursorColor :: Draw.Color defaultCursorColor = Draw.Color 0 1 0 1 defaultCursorWidth :: Draw.R defaultCursorWidth = 8 tillEndOfWord :: String -> String tillEndOfWord xs = spaces ++ nonSpaces where spaces = takeWhile isSpace xs nonSpaces = takeWhile (not . isSpace) . dropWhile isSpace $ xs makeDisplayStr :: Style -> String -> String makeDisplayStr style "" = sEmptyString style makeDisplayStr _ str = str cursorTranslate :: Style -> Anim.Frame -> Anim.Frame cursorTranslate style = Anim.translate (Vector2 (sCursorWidth style / 2) 0) makeTextEditCursor :: Anim.AnimId -> Int -> Anim.AnimId makeTextEditCursor myId = Anim.joinId myId . (:[]) . BinUtils.encodeS makeUnfocused :: Style -> String -> Anim.AnimId -> Widget ((,) String) makeUnfocused style str myId = Widget.takesFocus enter . (Widget.atContent . Sized.atRequestedSize) ((SizeRange.atSrMinSize . Vector2.first) (+ sCursorWidth style) . (SizeRange.atSrMaxSize . Vector2.first . fmap) (+ sCursorWidth style)) . Widget.atImage (cursorTranslate style) $ TextView.makeWidget (sTextViewStyle style) str myId where enter dir = (str, makeTextEditCursor myId (enterPos dir)) enterPos (Just (Vector2 x _)) | x < 0 = 0 | otherwise = length str enterPos Nothing = length str -- TODO: Instead of font + ptSize, let's pass a text-drawer (that's -- what "Font" should be) -- | Note: maxLines prevents the *user* from exceeding it, not the -- | given text... makeFocused :: Cursor -> Style -> String -> Anim.AnimId -> Widget ((,) String) makeFocused cursor style str myId = Widget.backgroundColor (sBackgroundCursorId style) blue . Widget.atImage (`mappend` cursorFrame) . Widget.strongerEvents eventMap $ widget where widget = Widget { isFocused = True, content = Sized reqSize . const $ Widget.UserIO { Widget.uioFrame = img, Widget.uioEventMap = mempty, Widget.uioMaybeEnter = Nothing } } reqSize = SizeRange.fixedSize $ Vector2 (sCursorWidth style + tlWidth) tlHeight img = cursorTranslate style $ frameGen myId (frameGen, Vector2 tlWidth tlHeight) = TextView.drawText True (sTextViewStyle style) displayStr blue = Draw.Color 0 0 0.8 0.8 textLinesWidth = Vector2.fst . snd . TextView.drawText True (sTextViewStyle style) sz = fromIntegral . TextView.styleFontSize $ sTextViewStyle style lineHeight = sz * textHeight strWithIds = map (first Just) $ enumerate str beforeCursor = take cursor strWithIds cursorPosX = textLinesWidth . map snd . last $ splitLines beforeCursor cursorPosY = (lineHeight *) . subtract 1 . genericLength . splitLines $ beforeCursor cursorFrame = Anim.onDepth (+2) . Anim.translate (Vector2 cursorPosX cursorPosY) . Anim.scale (Vector2 (sCursorWidth style) lineHeight) . Anim.simpleFrame (sTextCursorId style) $ Draw.tint (sCursorColor style) square (before, after) = splitAt cursor strWithIds textLength = length str lineCount = length $ splitWhen (== '\n') displayStr displayStr = makeDisplayStr style str splitLines = splitWhen ((== '\n') . snd) linesBefore = reverse (splitLines before) linesAfter = splitLines after prevLine = linesBefore !! 1 nextLine = linesAfter !! 1 curLineBefore = head linesBefore curLineAfter = head linesAfter cursorX = length curLineBefore cursorY = length linesBefore - 1 eventResult newText newCursor = (map snd newText, Widget.EventResult { Widget.eCursor = Just $ makeTextEditCursor myId newCursor, Widget.eAnimIdMapping = mapping }) where mapping animId = maybe animId (Anim.joinId myId . translateId) $ Anim.subId myId animId translateId [subId] = (:[]) . maybe subId (SBS8.pack . show) $ (`Map.lookup` dict) =<< Safe.readMay (SBS8.unpack subId) translateId x = x dict = mappend movedDict deletedDict movedDict = Map.fromList . mapMaybe posMapping . enumerate $ map fst newText deletedDict = Map.fromList . map (flip (,) (-1)) $ Set.toList deletedKeys posMapping (_, Nothing) = Nothing posMapping (newPos, Just oldPos) = Just (oldPos, newPos) deletedKeys = Set.fromList (mapMaybe fst strWithIds) `Set.difference` Set.fromList (mapMaybe fst newText) moveAbsolute a = eventResult strWithIds . max 0 $ min (length str) a moveRelative d = moveAbsolute (cursor + d) backDelete n = eventResult (take (cursor-n) strWithIds ++ drop cursor strWithIds) (cursor-n) delete n = eventResult (before ++ drop n after) cursor insert l = eventResult str' cursor' where cursor' = cursor + length l str' = concat [before, map ((,) Nothing) l, after] backDeleteWord = backDelete . length . tillEndOfWord . reverse $ map snd before deleteWord = delete . length . tillEndOfWord $ map snd after backMoveWord = moveRelative . negate . length . tillEndOfWord . reverse $ map snd before moveWord = moveRelative . length . tillEndOfWord $ map snd after keys doc = mconcat . map (`E.fromEventType` doc) specialKey = E.KeyEventType E.noMods ctrlSpecialKey = E.KeyEventType E.ctrl ctrlCharKey = E.KeyEventType E.ctrl . E.charKey altCharKey = E.KeyEventType E.alt . E.charKey homeKeys = [specialKey KeyHome, ctrlCharKey 'A'] endKeys = [specialKey KeyEnd, ctrlCharKey 'E'] eventMap = mconcat . concat $ [ [ keys "Move left" [specialKey KeyLeft] $ moveRelative (-1) | cursor > 0 ], [ keys "Move right" [specialKey KeyRight] $ moveRelative 1 | cursor < textLength ], [ keys "Move word left" [ctrlSpecialKey KeyLeft] backMoveWord | cursor > 0 ], [ keys "Move word right" [ctrlSpecialKey KeyRight] moveWord | cursor < textLength ], [ keys "Move up" [specialKey KeyUp] $ moveRelative (- cursorX - 1 - length (drop cursorX prevLine)) | cursorY > 0 ], [ keys "Move down" [specialKey KeyDown] $ moveRelative (length curLineAfter + 1 + min cursorX (length nextLine)) | cursorY < lineCount - 1 ], [ keys "Move to beginning of line" homeKeys $ moveRelative (-cursorX) | cursorX > 0 ], [ keys "Move to end of line" endKeys $ moveRelative (length curLineAfter) | not . null $ curLineAfter ], [ keys "Move to beginning of text" homeKeys $ moveAbsolute 0 | cursorX == 0 && cursor > 0 ], [ keys "Move to end of text" endKeys $ moveAbsolute textLength | null curLineAfter && cursor < textLength ], [ keys "Delete backwards" [specialKey KeyBackspace] $ backDelete 1 | cursor > 0 ], [ keys "Delete word backwards" [ctrlCharKey 'w'] backDeleteWord | cursor > 0 ], let swapPoint = min (textLength - 2) (cursor - 1) (beforeSwap, x:y:afterSwap) = splitAt swapPoint strWithIds swapLetters = eventResult (beforeSwap ++ y:x:afterSwap) $ min textLength (cursor + 1) in [ keys "Swap letters" [ctrlCharKey 't'] swapLetters | cursor > 0 && textLength >= 2 ], [ keys "Delete forward" [specialKey KeyDel] $ delete 1 | cursor < textLength ], [ keys "Delete word forward" [altCharKey 'd'] deleteWord | cursor < textLength ], [ keys "Delete rest of line" [ctrlCharKey 'k'] $ delete (length curLineAfter) | not . null $ curLineAfter ], [ keys "Delete newline" [ctrlCharKey 'k'] $ delete 1 | null curLineAfter && cursor < textLength ], [ keys "Delete till beginning of line" [ctrlCharKey 'u'] $ backDelete (length curLineBefore) | not . null $ curLineBefore ], [ E.singleton E.CharEventType "Insert character" (insert . (: []) . fromJust . E.keyEventChar) ], [ keys "Insert Newline" [specialKey KeyEnter] (insert "\n") ] ] make :: Style -> Anim.AnimId -> String -> Anim.AnimId -> Widget ((,) String) make style cursor str myId = Widget.align (Vector2 0.5 0.5) $ maybe makeUnfocused makeFocused mCursor style str myId where mCursor = fmap extractTextEditCursor $ Anim.subId myId cursor extractTextEditCursor [x] = BinUtils.decodeS x extractTextEditCursor _ = length str
alonho/bottle
src/Graphics/UI/Bottle/Widgets/TextEdit.hs
gpl-3.0
10,295
0
18
2,436
3,150
1,682
1,468
222
3
module OpenSandbox.Rules ( DiggingStatus (..) ) where import Data.Serialize import OpenSandbox.Protocol.Types (putVarInt,getVarInt) data DiggingStatus = StartedDigging | CancelledDigging | FinishedDigging | DropItemStack | DropItem | ShootArrowOrFinishEating | SwapItemInHand deriving (Show,Eq,Enum) instance Serialize DiggingStatus where put = putVarInt . fromEnum get = toEnum <$> getVarInt
oldmanmike/opensandbox
src/OpenSandbox/Rules.hs
gpl-3.0
420
0
6
71
100
60
40
16
0
import Control.Monad.Except import Data.Char (isNumber, isPunctuation) data PwdError = PwdError String instance Monoid PwdError where mempty = PwdError "" (PwdError x) `mappend` (PwdError y) = PwdError $ x ++ y type PwdErrorMonad = ExceptT PwdError IO askPassword' :: PwdErrorMonad () askPassword' = do liftIO $ putStrLn "Enter your new password:" value <- msum $ repeat getValidPassword' liftIO $ putStrLn "Storing in database..." getValidPassword' :: PwdErrorMonad String --getValidPassword' = undefined getValidPassword' = do action `catchError` handler where handler (PwdError s) = do liftIO $ putStrLn $ "Incorrect input: " ++ s mzero action = do s <- liftIO getLine isValidPassword s short_pass = "password is too short!" no_digit_pass = "password must contain some digits!" no_punct_pass = "password must contain some punctuations!" isValidPassword :: String -> PwdErrorMonad String isValidPassword s | length s < 8 = throwError $ PwdError short_pass | not $ any isNumber s = throwError $ PwdError no_digit_pass | not $ any isPunctuation s = throwError $ PwdError no_punct_pass | otherwise = return s
ItsLastDay/academic_university_2016-2018
subjects/Haskell/11/my_pwd_valid.hs
gpl-3.0
1,255
7
11
312
360
165
195
29
1
instance Monoid [a] where mempty = [] mappend = (++)
hmemcpy/milewski-ctfp-pdf
src/content/2.3/code/haskell/snippet02.hs
gpl-3.0
60
2
5
17
36
15
21
3
0
{-# 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.Compute.RegionBackendServices.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) -- -- Returns the specified regional BackendService resource. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionBackendServices.get@. module Network.Google.Resource.Compute.RegionBackendServices.Get ( -- * REST Resource RegionBackendServicesGetResource -- * Creating a Request , regionBackendServicesGet , RegionBackendServicesGet -- * Request Lenses , rbsgProject , rbsgRegion , rbsgBackendService ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.regionBackendServices.get@ method which the -- 'RegionBackendServicesGet' request conforms to. type RegionBackendServicesGetResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "backendServices" :> Capture "backendService" Text :> QueryParam "alt" AltJSON :> Get '[JSON] BackendService -- | Returns the specified regional BackendService resource. -- -- /See:/ 'regionBackendServicesGet' smart constructor. data RegionBackendServicesGet = RegionBackendServicesGet' { _rbsgProject :: !Text , _rbsgRegion :: !Text , _rbsgBackendService :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RegionBackendServicesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rbsgProject' -- -- * 'rbsgRegion' -- -- * 'rbsgBackendService' regionBackendServicesGet :: Text -- ^ 'rbsgProject' -> Text -- ^ 'rbsgRegion' -> Text -- ^ 'rbsgBackendService' -> RegionBackendServicesGet regionBackendServicesGet pRbsgProject_ pRbsgRegion_ pRbsgBackendService_ = RegionBackendServicesGet' { _rbsgProject = pRbsgProject_ , _rbsgRegion = pRbsgRegion_ , _rbsgBackendService = pRbsgBackendService_ } -- | Project ID for this request. rbsgProject :: Lens' RegionBackendServicesGet Text rbsgProject = lens _rbsgProject (\ s a -> s{_rbsgProject = a}) -- | Name of the region scoping this request. rbsgRegion :: Lens' RegionBackendServicesGet Text rbsgRegion = lens _rbsgRegion (\ s a -> s{_rbsgRegion = a}) -- | Name of the BackendService resource to return. rbsgBackendService :: Lens' RegionBackendServicesGet Text rbsgBackendService = lens _rbsgBackendService (\ s a -> s{_rbsgBackendService = a}) instance GoogleRequest RegionBackendServicesGet where type Rs RegionBackendServicesGet = BackendService type Scopes RegionBackendServicesGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient RegionBackendServicesGet'{..} = go _rbsgProject _rbsgRegion _rbsgBackendService (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy RegionBackendServicesGetResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/RegionBackendServices/Get.hs
mpl-2.0
4,033
0
16
903
466
278
188
79
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.Directory.Users.Aliases.Insert -- 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) -- -- Adds an alias. -- -- /See:/ <https://developers.google.com/admin-sdk/ Admin SDK API Reference> for @directory.users.aliases.insert@. module Network.Google.Resource.Directory.Users.Aliases.Insert ( -- * REST Resource UsersAliasesInsertResource -- * Creating a Request , usersAliasesInsert , UsersAliasesInsert -- * Request Lenses , uaiXgafv , uaiUploadProtocol , uaiAccessToken , uaiUploadType , uaiPayload , uaiUserKey , uaiCallback ) where import Network.Google.Directory.Types import Network.Google.Prelude -- | A resource alias for @directory.users.aliases.insert@ method which the -- 'UsersAliasesInsert' request conforms to. type UsersAliasesInsertResource = "admin" :> "directory" :> "v1" :> "users" :> Capture "userKey" Text :> "aliases" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Alias :> Post '[JSON] Alias -- | Adds an alias. -- -- /See:/ 'usersAliasesInsert' smart constructor. data UsersAliasesInsert = UsersAliasesInsert' { _uaiXgafv :: !(Maybe Xgafv) , _uaiUploadProtocol :: !(Maybe Text) , _uaiAccessToken :: !(Maybe Text) , _uaiUploadType :: !(Maybe Text) , _uaiPayload :: !Alias , _uaiUserKey :: !Text , _uaiCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UsersAliasesInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uaiXgafv' -- -- * 'uaiUploadProtocol' -- -- * 'uaiAccessToken' -- -- * 'uaiUploadType' -- -- * 'uaiPayload' -- -- * 'uaiUserKey' -- -- * 'uaiCallback' usersAliasesInsert :: Alias -- ^ 'uaiPayload' -> Text -- ^ 'uaiUserKey' -> UsersAliasesInsert usersAliasesInsert pUaiPayload_ pUaiUserKey_ = UsersAliasesInsert' { _uaiXgafv = Nothing , _uaiUploadProtocol = Nothing , _uaiAccessToken = Nothing , _uaiUploadType = Nothing , _uaiPayload = pUaiPayload_ , _uaiUserKey = pUaiUserKey_ , _uaiCallback = Nothing } -- | V1 error format. uaiXgafv :: Lens' UsersAliasesInsert (Maybe Xgafv) uaiXgafv = lens _uaiXgafv (\ s a -> s{_uaiXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). uaiUploadProtocol :: Lens' UsersAliasesInsert (Maybe Text) uaiUploadProtocol = lens _uaiUploadProtocol (\ s a -> s{_uaiUploadProtocol = a}) -- | OAuth access token. uaiAccessToken :: Lens' UsersAliasesInsert (Maybe Text) uaiAccessToken = lens _uaiAccessToken (\ s a -> s{_uaiAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). uaiUploadType :: Lens' UsersAliasesInsert (Maybe Text) uaiUploadType = lens _uaiUploadType (\ s a -> s{_uaiUploadType = a}) -- | Multipart request metadata. uaiPayload :: Lens' UsersAliasesInsert Alias uaiPayload = lens _uaiPayload (\ s a -> s{_uaiPayload = a}) -- | Identifies the user in the API request. The value can be the user\'s -- primary email address, alias email address, or unique user ID. uaiUserKey :: Lens' UsersAliasesInsert Text uaiUserKey = lens _uaiUserKey (\ s a -> s{_uaiUserKey = a}) -- | JSONP uaiCallback :: Lens' UsersAliasesInsert (Maybe Text) uaiCallback = lens _uaiCallback (\ s a -> s{_uaiCallback = a}) instance GoogleRequest UsersAliasesInsert where type Rs UsersAliasesInsert = Alias type Scopes UsersAliasesInsert = '["https://www.googleapis.com/auth/admin.directory.user", "https://www.googleapis.com/auth/admin.directory.user.alias"] requestClient UsersAliasesInsert'{..} = go _uaiUserKey _uaiXgafv _uaiUploadProtocol _uaiAccessToken _uaiUploadType _uaiCallback (Just AltJSON) _uaiPayload directoryService where go = buildClient (Proxy :: Proxy UsersAliasesInsertResource) mempty
brendanhay/gogol
gogol-admin-directory/gen/Network/Google/Resource/Directory/Users/Aliases/Insert.hs
mpl-2.0
5,125
0
20
1,266
795
463
332
117
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.Plus.Activities.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) -- -- List all of the activities in the specified collection for a particular -- user. -- -- /See:/ <https://developers.google.com/+/api/ Google+ API Reference> for @plus.activities.list@. module Network.Google.Resource.Plus.Activities.List ( -- * REST Resource ActivitiesListResource -- * Creating a Request , activitiesList , ActivitiesList -- * Request Lenses , alCollection , alUserId , alPageToken , alMaxResults ) where import Network.Google.Plus.Types import Network.Google.Prelude -- | A resource alias for @plus.activities.list@ method which the -- 'ActivitiesList' request conforms to. type ActivitiesListResource = "plus" :> "v1" :> "people" :> Capture "userId" Text :> "activities" :> Capture "collection" ActivitiesListCollection :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] ActivityFeed -- | List all of the activities in the specified collection for a particular -- user. -- -- /See:/ 'activitiesList' smart constructor. data ActivitiesList = ActivitiesList' { _alCollection :: !ActivitiesListCollection , _alUserId :: !Text , _alPageToken :: !(Maybe Text) , _alMaxResults :: !(Textual Word32) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ActivitiesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'alCollection' -- -- * 'alUserId' -- -- * 'alPageToken' -- -- * 'alMaxResults' activitiesList :: ActivitiesListCollection -- ^ 'alCollection' -> Text -- ^ 'alUserId' -> ActivitiesList activitiesList pAlCollection_ pAlUserId_ = ActivitiesList' { _alCollection = pAlCollection_ , _alUserId = pAlUserId_ , _alPageToken = Nothing , _alMaxResults = 20 } -- | The collection of activities to list. alCollection :: Lens' ActivitiesList ActivitiesListCollection alCollection = lens _alCollection (\ s a -> s{_alCollection = a}) -- | The ID of the user to get activities for. The special value \"me\" can -- be used to indicate the authenticated user. alUserId :: Lens' ActivitiesList Text alUserId = lens _alUserId (\ s a -> s{_alUserId = a}) -- | The continuation token, which is used to page through large result sets. -- To get the next page of results, set this parameter to the value of -- \"nextPageToken\" from the previous response. alPageToken :: Lens' ActivitiesList (Maybe Text) alPageToken = lens _alPageToken (\ s a -> s{_alPageToken = a}) -- | The maximum number of activities to include in the response, which is -- used for paging. For any response, the actual number returned might be -- less than the specified maxResults. alMaxResults :: Lens' ActivitiesList Word32 alMaxResults = lens _alMaxResults (\ s a -> s{_alMaxResults = a}) . _Coerce instance GoogleRequest ActivitiesList where type Rs ActivitiesList = ActivityFeed type Scopes ActivitiesList = '["https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/plus.me"] requestClient ActivitiesList'{..} = go _alUserId _alCollection _alPageToken (Just _alMaxResults) (Just AltJSON) plusService where go = buildClient (Proxy :: Proxy ActivitiesListResource) mempty
rueshyna/gogol
gogol-plus/gen/Network/Google/Resource/Plus/Activities/List.hs
mpl-2.0
4,336
0
16
1,006
561
333
228
82
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.Sheets.Spreadsheets.Values.BatchUpdate -- 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) -- -- Sets values in one or more ranges of a spreadsheet. The caller must -- specify the spreadsheet ID, a valueInputOption, and one or more -- ValueRanges. -- -- /See:/ <https://developers.google.com/sheets/ Google Sheets API Reference> for @sheets.spreadsheets.values.batchUpdate@. module Network.Google.Resource.Sheets.Spreadsheets.Values.BatchUpdate ( -- * REST Resource SpreadsheetsValuesBatchUpdateResource -- * Creating a Request , spreadsheetsValuesBatchUpdate , SpreadsheetsValuesBatchUpdate -- * Request Lenses , svbuXgafv , svbuUploadProtocol , svbuPp , svbuAccessToken , svbuSpreadsheetId , svbuUploadType , svbuPayload , svbuBearerToken , svbuCallback ) where import Network.Google.Prelude import Network.Google.Sheets.Types -- | A resource alias for @sheets.spreadsheets.values.batchUpdate@ method which the -- 'SpreadsheetsValuesBatchUpdate' request conforms to. type SpreadsheetsValuesBatchUpdateResource = "v4" :> "spreadsheets" :> Capture "spreadsheetId" Text :> "values:batchUpdate" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] BatchUpdateValuesRequest :> Post '[JSON] BatchUpdateValuesResponse -- | Sets values in one or more ranges of a spreadsheet. The caller must -- specify the spreadsheet ID, a valueInputOption, and one or more -- ValueRanges. -- -- /See:/ 'spreadsheetsValuesBatchUpdate' smart constructor. data SpreadsheetsValuesBatchUpdate = SpreadsheetsValuesBatchUpdate' { _svbuXgafv :: !(Maybe Xgafv) , _svbuUploadProtocol :: !(Maybe Text) , _svbuPp :: !Bool , _svbuAccessToken :: !(Maybe Text) , _svbuSpreadsheetId :: !Text , _svbuUploadType :: !(Maybe Text) , _svbuPayload :: !BatchUpdateValuesRequest , _svbuBearerToken :: !(Maybe Text) , _svbuCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'SpreadsheetsValuesBatchUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'svbuXgafv' -- -- * 'svbuUploadProtocol' -- -- * 'svbuPp' -- -- * 'svbuAccessToken' -- -- * 'svbuSpreadsheetId' -- -- * 'svbuUploadType' -- -- * 'svbuPayload' -- -- * 'svbuBearerToken' -- -- * 'svbuCallback' spreadsheetsValuesBatchUpdate :: Text -- ^ 'svbuSpreadsheetId' -> BatchUpdateValuesRequest -- ^ 'svbuPayload' -> SpreadsheetsValuesBatchUpdate spreadsheetsValuesBatchUpdate pSvbuSpreadsheetId_ pSvbuPayload_ = SpreadsheetsValuesBatchUpdate' { _svbuXgafv = Nothing , _svbuUploadProtocol = Nothing , _svbuPp = True , _svbuAccessToken = Nothing , _svbuSpreadsheetId = pSvbuSpreadsheetId_ , _svbuUploadType = Nothing , _svbuPayload = pSvbuPayload_ , _svbuBearerToken = Nothing , _svbuCallback = Nothing } -- | V1 error format. svbuXgafv :: Lens' SpreadsheetsValuesBatchUpdate (Maybe Xgafv) svbuXgafv = lens _svbuXgafv (\ s a -> s{_svbuXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). svbuUploadProtocol :: Lens' SpreadsheetsValuesBatchUpdate (Maybe Text) svbuUploadProtocol = lens _svbuUploadProtocol (\ s a -> s{_svbuUploadProtocol = a}) -- | Pretty-print response. svbuPp :: Lens' SpreadsheetsValuesBatchUpdate Bool svbuPp = lens _svbuPp (\ s a -> s{_svbuPp = a}) -- | OAuth access token. svbuAccessToken :: Lens' SpreadsheetsValuesBatchUpdate (Maybe Text) svbuAccessToken = lens _svbuAccessToken (\ s a -> s{_svbuAccessToken = a}) -- | The ID of the spreadsheet to update. svbuSpreadsheetId :: Lens' SpreadsheetsValuesBatchUpdate Text svbuSpreadsheetId = lens _svbuSpreadsheetId (\ s a -> s{_svbuSpreadsheetId = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). svbuUploadType :: Lens' SpreadsheetsValuesBatchUpdate (Maybe Text) svbuUploadType = lens _svbuUploadType (\ s a -> s{_svbuUploadType = a}) -- | Multipart request metadata. svbuPayload :: Lens' SpreadsheetsValuesBatchUpdate BatchUpdateValuesRequest svbuPayload = lens _svbuPayload (\ s a -> s{_svbuPayload = a}) -- | OAuth bearer token. svbuBearerToken :: Lens' SpreadsheetsValuesBatchUpdate (Maybe Text) svbuBearerToken = lens _svbuBearerToken (\ s a -> s{_svbuBearerToken = a}) -- | JSONP svbuCallback :: Lens' SpreadsheetsValuesBatchUpdate (Maybe Text) svbuCallback = lens _svbuCallback (\ s a -> s{_svbuCallback = a}) instance GoogleRequest SpreadsheetsValuesBatchUpdate where type Rs SpreadsheetsValuesBatchUpdate = BatchUpdateValuesResponse type Scopes SpreadsheetsValuesBatchUpdate = '["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets"] requestClient SpreadsheetsValuesBatchUpdate'{..} = go _svbuSpreadsheetId _svbuXgafv _svbuUploadProtocol (Just _svbuPp) _svbuAccessToken _svbuUploadType _svbuBearerToken _svbuCallback (Just AltJSON) _svbuPayload sheetsService where go = buildClient (Proxy :: Proxy SpreadsheetsValuesBatchUpdateResource) mempty
rueshyna/gogol
gogol-sheets/gen/Network/Google/Resource/Sheets/Spreadsheets/Values/BatchUpdate.hs
mpl-2.0
6,602
0
20
1,592
944
549
395
140
1
{- - This file is part of Bilder. - - Bilder 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 3 of the License, or - (at your option) any later version. - - Bilder 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 Bilder. If not, see <http://www.gnu.org/licenses/>. - - Copyright © 2012-2013 Filip Lundborg - Copyright © 2012-2013 Ingemar Ådahl - -} {-# LANGUAGE UnicodeSyntax, TupleSections #-} module Compiler.Merge where import Control.Arrow import Control.Monad.State import Data.Maybe import Data.List import qualified Data.Map as Map import Utils import Compiler.Simple.Utils import Compiler.Simple.Types import Compiler.Simple.AbsSimple data Count = Count { images ∷ [Map.Map String String], -- Variables containing sampler alias samples ∷ Map.Map String Int, shader ∷ Shader } deriving (Show) type Functions = Map.Map String Function emptyState ∷ Shader → Count emptyState shd = Count [Map.empty] (Map.fromList (("unknown",0):map ((,0) . variableName) (filter (\v → variableType v == TSampler) $ Map.elems (inputs shd)))) shd setAlias ∷ String → String → State Count () setAlias variable target = modify (\st → st { images = Map.insert variable target (head (images st)):tail (images st)}) increment ∷ String → State Count () increment s = modify (\st → st { samples = Map.insertWith (+) s 1 (samples st)}) sampleCount ∷ Shader → Int sampleCount shd = evalState (countSamples mainFun) (emptyState shd) where mainFun = fromJust $ Map.lookup "main" (functions shd) countSamples ∷ Function → State Count Int countSamples (Function _ _ _ _ stms) = do c ← mapM countStm stms return $ sum c countStm ∷ Stm → State Count Int countStm (SDecl v) | variableType v == TSampler = setAlias (variableName v) "unknown" >> return 0 countStm (SDeclAss v (EVar s)) | variableType v == TSampler = setAlias (variableName v) s >> return 0 countStm (SDeclAss v _) | variableType v == TSampler = setAlias (variableName v) "unknown" >> -- Find out which sampler from exp? return 0 countStm (SFor {}) = return 9001 countStm (SDoWhile {}) = return 9001 countStm (SWhile {}) = return 9001 countStm (SExp (EAss (EVar var) (EVar samp))) = do aliases ← gets (head . images) case Map.lookup var aliases of Just s → setAlias s samp >> return 0 Nothing → return 0 countStm s = foldStmExpM (\p e → liftM (+p) (countExp e)) 0 s countExp ∷ Exp → State Count Int countExp (ECall name [_, _]) = do aliases ← gets (head . images) ins ← gets (inputs . shader) case Map.lookup name aliases `mplus` fmap variableName (Map.lookup name ins) of Just s → increment s >> return 1 Nothing → do funs ← gets (functions . shader) case Map.lookup name funs of Just f → countSamples f Nothing → return 0 countExp (ECall name es) = do funs ← gets (functions . shader) case Map.lookup name funs of Just f → branchFun f es Nothing → return 0 countExp _ = return 0 branchFun ∷ Function → [Exp] → State Count Int branchFun fun args = do modify (\st → st { images = Map.empty:images st}) -- Match arguments with expressions, and set aliases where applicable mapM_ (\(v,e) → case e of EVar n → setAlias (variableName v) n _ → setAlias (variableName v) "unknown") $ filter (\(v, _) → variableType v == TSampler) $ zip (parameters fun) args c ← countSamples fun modify (\st → st { images = tail (images st)}) return c mergeShaders ∷ [Shader] → [Shader] mergeShaders ss = dropShaders $ if clean then ss' else mergeShaders ss' where (clean, ss') = ((not . dirty) &&& (Map.elems . shaders)) $ execState (startMerge mainShd) (freshState mainShd ss) mainShd = head $ filter isMain ss -- Drop shaders not needed any more due to them being merged in to another shader dropShaders ∷ [Shader] → [Shader] dropShaders ss = filter needed ss where ins = nub $ "result_image":concatMap (map variableName . Map.elems . inputs) ss needed ∷ Shader → Bool needed s = variableName (output s) `elem` ins isMain ∷ Shader → Bool isMain = (==) "result_image" . variableName . output data Merge = Merge { currentShader ∷ Shader, currentFunction ∷ Function, shaders ∷ Map.Map String Shader, samplers ∷ Map.Map String Variable, dirty ∷ Bool } deriving (Show) updateSampler ∷ String → String → State Merge () updateSampler var samp = do smps ← gets samplers case Map.lookup samp smps of Just s → modify (\st → st { samplers = Map.insert var s smps}) Nothing → return () -- Sampler wasn't referencing anything useful :( startMerge ∷ Shader → State Merge () startMerge shd = do let f = fromJust $ Map.lookup "main" (functions shd) stms ← mapM mergeStm (statements f) -- copypasta: -- Update state currShader ← gets currentShader let shader' = currShader { functions = Map.insert (functionName f) f { statements = stms} (functions currShader) } modify (\st → st { currentShader = shader' , shaders = Map.insert (variableName (output shader')) shader' (shaders st) }) freshState ∷ Shader → [Shader] → Merge freshState shd shds = Merge shd (fromJust $ Map.lookup "main" $ functions shd) (Map.fromList $ map ((variableName . output) &&& id) shds) (Map.filter ((==) TSampler . variableType) (inputs shd)) False -- Finds which shader is referred to with the string s in the current context resolveShader ∷ String → State Merge (Maybe String) resolveShader s = gets (fmap variableName . Map.lookup s . samplers) mergeFun ∷ Function → [Exp] → State Merge (String, [Exp]) mergeFun f args = do -- Add sampler aliases to state modify (\st → st { samplers = Map.union (samplers st) $ Map.fromList [ (alias, let Just v = (Map.lookup sampler (samplers st)) in v) | (Variable alias TSampler _ _, EVar sampler) ← zip (parameters f) args ] }) stms ← mapM mergeStm (statements f) if stms == statements f then return (functionName f, args) else do -- Stuff has changed, we might not be dependent on samplers as args any more newName ← iterateFun (functionName f) let references = usedVars stms let (params', args') = unzip $ filter ((`elem` references) . variableName . fst) $ zip (parameters f) args -- Update state currShader ← gets currentShader let shader' = currShader { functions = Map.insert newName f { functionName = newName, parameters = params', statements = stms } (functions currShader) } modify (\st → st { currentShader = shader' , shaders = Map.insert (variableName (output shader')) shader' (shaders st) }) return (newName, args') mergeStm ∷ Stm → State Merge Stm mergeStm s@(SDeclAss var (EVar samp)) | variableType var == TSampler = updateSampler (variableName var) samp >> return s mergeStm s = mapStmExpM mergeExp s mergeExp ∷ Exp → State Merge Exp mergeExp (ECall f [ex, ey]) = do shd ← resolveShader f shds ← gets shaders ex' ← mergeExp ex ey' ← mergeExp ey funs ← gets (functions . currentShader) -- Tries inlining let inlined = shd >>= flip Map.lookup shds >>= (\s → mayhaps (sampleCount s < 3) (inline s ex' ey')) -- Tries branching let branch = fmap (\g → mergeFun g [ex', ey'] >>= (\(fun, args) → return (ECall fun args))) (Map.lookup f funs) -- Performs actual computation fromJust $ inlined `mplus` branch `mplus` Just (return (ECall f [ex', ey'])) mergeExp (ECall f es) = do es' ← mapM mergeExp es funs ← gets (functions . currentShader) case Map.lookup f funs of Just f' → mergeFun f' es' >>= (\(fun, args) → return (ECall fun args)) Nothing → return (ECall f es') mergeExp e@(EAss (EVar v) (EVar s)) = -- Naïve solution :S updateSampler v s >> return e mergeExp e = mapExpM mergeExp e inline ∷ Shader → Exp → Exp → State Merge Exp inline shd ex ey = do let mainF = fromJust $ Map.lookup "main" (functions shd) let main' = renameMain mainF (variableName $ output shd) let shd' = shd { functions = (Map.insert (functionName main') main' . Map.delete "main") (functions shd)} modify (\st → st { currentShader = mergeShader (currentShader st) shd', dirty = True}) return $ ECall (functionName main') [ex,ey] -- Merge the second shader into the first, removing unneccecary in/outs mergeShader ∷ Shader → Shader → Shader mergeShader orig new = Shader { variables = variables orig `Map.union` variables new , functions = functions orig `Map.union` (uniquify orig new `Map.union` functions new) , output = output orig , inputs = Map.filter (\v → variableName v /= variableName (output new)) $ inputs orig `Map.union` inputs new } where uniquify ∷ Shader → Shader → Functions uniquify shOrig shNew = if Map.null $ intersec shOrig shNew then functions shNew else uniquify shOrig (renameShader (Map.keys $ intersec shOrig shNew) shNew) intersec ∷ Shader → Shader → Functions intersec shOrig shNew = Map.filterWithKey (\k v → let Just y = (Map.lookup k (functions shOrig)) in statements v /= statements y) $ functions shNew `Map.intersection` functions shOrig renameShader ∷ [String] → Shader → Shader renameShader ss shd = foldr (\s pr → pr { functions = renameCalls (functions pr) s ('r':s) }) shd ss renameCalls ∷ Functions → String → String → Functions renameCalls fs fun newName = Map.fromList $ map (\(k,f) → let n = if k == fun then newName else k in (n,f { statements = map (mapStmExp (renameExp fun newName)) (statements f), functionName = n })) $ Map.toList fs renameExp ∷ String → String → Exp → Exp renameExp fun replace (ECall str es) | str == fun = ECall replace (map (renameExp fun replace) es) renameExp fun replace e = mapExp (renameExp fun replace) e renameMain ∷ Function → String → Function renameMain f s = f { functionName = 'm':s } iterateFun ∷ String → State Merge String iterateFun s = iterateFun' ['a'..'z'] where iterateFun' ∷ String → State Merge String iterateFun' more = do funs ← gets (concatMap (Map.keys . functions) . Map.elems . shaders) if s ++ [head more] `elem` funs then iterateFun' (tail more) else return $ s ++ [head more]
ingemaradahl/bilder
src/Compiler/Merge.hs
lgpl-3.0
11,129
0
23
2,572
3,983
2,016
1,967
221
4
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE StandaloneDeriving #-} module Nanocoin.Network.Peer ( Peer(..), Peers, ) where import Protolude hiding (put, get) import Data.Aeson (ToJSON(..)) import Data.Binary (Binary, encode, decode) import Data.Serialize (Serialize(..)) import Control.Distributed.Process (ProcessId, NodeId) import Control.Distributed.Process.Serializable import Nanocoin.Network.Utils type Peers = Set Peer instance Serialize NodeId where put = put . encode get = decode <$> get newtype Peer = Peer { nid :: NodeId } deriving (Show, Eq, Ord, Generic, Binary, Typeable, Serializable, Serialize)
tdietert/nanocoin
src/Nanocoin/Network/Peer.hs
apache-2.0
663
0
6
98
189
117
72
19
0
module Lycopene.Core.Record.Service where import Control.Monad.Trans (liftIO) import Data.Time.Clock (getCurrentTime) import Data.Time.LocalTime (utcToLocalTime, getCurrentTimeZone, LocalTime) import Lycopene.Core.Monad import Lycopene.Core.Database import qualified Lycopene.Core.Record as E newRecord :: Integer -> LocalTime -> Lycopene Integer newRecord i st = do et <- liftIO $ utcToLocalTime <$> getCurrentTimeZone <*> getCurrentTime let v = E.RecordV { E.vIssueId = i , E.vStartOn = st , E.vEndOn = Just et } runPersist $ insertP E.insertRecordV v history :: Integer -> Lycopene [E.Record] history i = runPersist $ relationP E.selectRecordByIssue i
utky/lycopene
src/Lycopene/Core/Record/Service.hs
apache-2.0
714
0
12
141
203
114
89
14
1
module Handler.ToPostList where import Import import Data.List (sort) getToPostListR :: Handler RepHtml getToPostListR = do toposts <- liftIO getToPosts defaultLayout $ do setTitle "To post list" $(widgetFile "topost-list")
snoyberg/photosorter
Handler/ToPostList.hs
bsd-2-clause
250
0
12
54
65
32
33
9
1
module Database.Narc.Common where type Tabname = String type Field = String
ezrakilty/narc
Database/Narc/Common.hs
bsd-2-clause
79
0
4
14
19
13
6
3
0
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QLineEdit.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:25 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QLineEdit ( QqLineEdit(..) ,backspace ,QcursorBackward(..) ,QcursorForward(..) ,cursorPosition ,cursorPositionAt, qcursorPositionAt ,cursorWordBackward ,cursorWordForward ,del ,deselect ,displayText ,echoMode ,hasSelectedText ,inputMask ,insert ,maxLength ,setCursorPosition ,setEchoMode ,setInputMask ,setMaxLength ,qLineEdit_delete ,qLineEdit_deleteLater ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QLineEdit import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QuserMethod (QLineEdit ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QLineEdit_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QLineEdit_userMethod" qtc_QLineEdit_userMethod :: Ptr (TQLineEdit a) -> CInt -> IO () instance QuserMethod (QLineEditSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QLineEdit_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QLineEdit ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QLineEdit_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QLineEdit_userMethodVariant" qtc_QLineEdit_userMethodVariant :: Ptr (TQLineEdit a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QLineEditSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QLineEdit_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqLineEdit x1 where qLineEdit :: x1 -> IO (QLineEdit ()) instance QqLineEdit (()) where qLineEdit () = withQLineEditResult $ qtc_QLineEdit foreign import ccall "qtc_QLineEdit" qtc_QLineEdit :: IO (Ptr (TQLineEdit ())) instance QqLineEdit ((String)) where qLineEdit (x1) = withQLineEditResult $ withCWString x1 $ \cstr_x1 -> qtc_QLineEdit1 cstr_x1 foreign import ccall "qtc_QLineEdit1" qtc_QLineEdit1 :: CWString -> IO (Ptr (TQLineEdit ())) instance QqLineEdit ((QWidget t1)) where qLineEdit (x1) = withQLineEditResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit2 cobj_x1 foreign import ccall "qtc_QLineEdit2" qtc_QLineEdit2 :: Ptr (TQWidget t1) -> IO (Ptr (TQLineEdit ())) instance QqLineEdit ((String, QWidget t2)) where qLineEdit (x1, x2) = withQLineEditResult $ withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QLineEdit3 cstr_x1 cobj_x2 foreign import ccall "qtc_QLineEdit3" qtc_QLineEdit3 :: CWString -> Ptr (TQWidget t2) -> IO (Ptr (TQLineEdit ())) instance Qalignment (QLineEdit a) (()) where alignment x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_alignment cobj_x0 foreign import ccall "qtc_QLineEdit_alignment" qtc_QLineEdit_alignment :: Ptr (TQLineEdit a) -> IO CLong backspace :: QLineEdit a -> (()) -> IO () backspace x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_backspace cobj_x0 foreign import ccall "qtc_QLineEdit_backspace" qtc_QLineEdit_backspace :: Ptr (TQLineEdit a) -> IO () instance QchangeEvent (QLineEdit ()) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_changeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_changeEvent_h" qtc_QLineEdit_changeEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent (QLineEditSc a) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_changeEvent_h cobj_x0 cobj_x1 instance Qclear (QLineEdit a) (()) where clear x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_clear cobj_x0 foreign import ccall "qtc_QLineEdit_clear" qtc_QLineEdit_clear :: Ptr (TQLineEdit a) -> IO () instance Qcompleter (QLineEdit a) (()) where completer x0 () = withQCompleterResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_completer cobj_x0 foreign import ccall "qtc_QLineEdit_completer" qtc_QLineEdit_completer :: Ptr (TQLineEdit a) -> IO (Ptr (TQCompleter ())) instance QcontextMenuEvent (QLineEdit ()) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_contextMenuEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_contextMenuEvent_h" qtc_QLineEdit_contextMenuEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent (QLineEditSc a) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_contextMenuEvent_h cobj_x0 cobj_x1 instance Qcopy (QLineEdit a) (()) (IO ()) where copy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_copy cobj_x0 foreign import ccall "qtc_QLineEdit_copy" qtc_QLineEdit_copy :: Ptr (TQLineEdit a) -> IO () instance Qcopy_nf (QLineEdit a) (()) (IO ()) where copy_nf x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_copy cobj_x0 instance QcreateStandardContextMenu (QLineEdit a) (()) where createStandardContextMenu x0 () = withQMenuResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_createStandardContextMenu cobj_x0 foreign import ccall "qtc_QLineEdit_createStandardContextMenu" qtc_QLineEdit_createStandardContextMenu :: Ptr (TQLineEdit a) -> IO (Ptr (TQMenu ())) class QcursorBackward x1 where cursorBackward :: QLineEdit a -> x1 -> IO () instance QcursorBackward ((Bool)) where cursorBackward x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cursorBackward cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_cursorBackward" qtc_QLineEdit_cursorBackward :: Ptr (TQLineEdit a) -> CBool -> IO () instance QcursorBackward ((Bool, Int)) where cursorBackward x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cursorBackward1 cobj_x0 (toCBool x1) (toCInt x2) foreign import ccall "qtc_QLineEdit_cursorBackward1" qtc_QLineEdit_cursorBackward1 :: Ptr (TQLineEdit a) -> CBool -> CInt -> IO () class QcursorForward x1 where cursorForward :: QLineEdit a -> x1 -> IO () instance QcursorForward ((Bool)) where cursorForward x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cursorForward cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_cursorForward" qtc_QLineEdit_cursorForward :: Ptr (TQLineEdit a) -> CBool -> IO () instance QcursorForward ((Bool, Int)) where cursorForward x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cursorForward1 cobj_x0 (toCBool x1) (toCInt x2) foreign import ccall "qtc_QLineEdit_cursorForward1" qtc_QLineEdit_cursorForward1 :: Ptr (TQLineEdit a) -> CBool -> CInt -> IO () cursorPosition :: QLineEdit a -> (()) -> IO (Int) cursorPosition x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cursorPosition cobj_x0 foreign import ccall "qtc_QLineEdit_cursorPosition" qtc_QLineEdit_cursorPosition :: Ptr (TQLineEdit a) -> IO CInt cursorPositionAt :: QLineEdit a -> ((Point)) -> IO (Int) cursorPositionAt x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QLineEdit_cursorPositionAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QLineEdit_cursorPositionAt_qth" qtc_QLineEdit_cursorPositionAt_qth :: Ptr (TQLineEdit a) -> CInt -> CInt -> IO CInt qcursorPositionAt :: QLineEdit a -> ((QPoint t1)) -> IO (Int) qcursorPositionAt x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_cursorPositionAt cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_cursorPositionAt" qtc_QLineEdit_cursorPositionAt :: Ptr (TQLineEdit a) -> Ptr (TQPoint t1) -> IO CInt cursorWordBackward :: QLineEdit a -> ((Bool)) -> IO () cursorWordBackward x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cursorWordBackward cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_cursorWordBackward" qtc_QLineEdit_cursorWordBackward :: Ptr (TQLineEdit a) -> CBool -> IO () cursorWordForward :: QLineEdit a -> ((Bool)) -> IO () cursorWordForward x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cursorWordForward cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_cursorWordForward" qtc_QLineEdit_cursorWordForward :: Ptr (TQLineEdit a) -> CBool -> IO () instance Qcut (QLineEdit a) (()) where cut x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cut cobj_x0 foreign import ccall "qtc_QLineEdit_cut" qtc_QLineEdit_cut :: Ptr (TQLineEdit a) -> IO () del :: QLineEdit a -> (()) -> IO () del x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_del cobj_x0 foreign import ccall "qtc_QLineEdit_del" qtc_QLineEdit_del :: Ptr (TQLineEdit a) -> IO () deselect :: QLineEdit a -> (()) -> IO () deselect x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_deselect cobj_x0 foreign import ccall "qtc_QLineEdit_deselect" qtc_QLineEdit_deselect :: Ptr (TQLineEdit a) -> IO () displayText :: QLineEdit a -> (()) -> IO (String) displayText x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_displayText cobj_x0 foreign import ccall "qtc_QLineEdit_displayText" qtc_QLineEdit_displayText :: Ptr (TQLineEdit a) -> IO (Ptr (TQString ())) instance QdragEnabled (QLineEdit a) (()) where dragEnabled x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_dragEnabled cobj_x0 foreign import ccall "qtc_QLineEdit_dragEnabled" qtc_QLineEdit_dragEnabled :: Ptr (TQLineEdit a) -> IO CBool instance QdragEnterEvent (QLineEdit ()) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dragEnterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_dragEnterEvent_h" qtc_QLineEdit_dragEnterEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent (QLineEditSc a) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dragEnterEvent_h cobj_x0 cobj_x1 instance QdragLeaveEvent (QLineEdit ()) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dragLeaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_dragLeaveEvent_h" qtc_QLineEdit_dragLeaveEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent (QLineEditSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dragLeaveEvent_h cobj_x0 cobj_x1 instance QdragMoveEvent (QLineEdit ()) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dragMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_dragMoveEvent_h" qtc_QLineEdit_dragMoveEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent (QLineEditSc a) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dragMoveEvent_h cobj_x0 cobj_x1 instance QdropEvent (QLineEdit ()) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dropEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_dropEvent_h" qtc_QLineEdit_dropEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent (QLineEditSc a) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dropEvent_h cobj_x0 cobj_x1 echoMode :: QLineEdit a -> (()) -> IO (EchoMode) echoMode x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_echoMode cobj_x0 foreign import ccall "qtc_QLineEdit_echoMode" qtc_QLineEdit_echoMode :: Ptr (TQLineEdit a) -> IO CLong instance Qend (QLineEdit a) ((Bool)) (IO ()) where end x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_end cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_end" qtc_QLineEdit_end :: Ptr (TQLineEdit a) -> CBool -> IO () instance Qevent (QLineEdit ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_event_h" qtc_QLineEdit_event_h :: Ptr (TQLineEdit a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QLineEditSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_event_h cobj_x0 cobj_x1 instance QfocusInEvent (QLineEdit ()) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_focusInEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_focusInEvent_h" qtc_QLineEdit_focusInEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent (QLineEditSc a) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_focusInEvent_h cobj_x0 cobj_x1 instance QfocusOutEvent (QLineEdit ()) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_focusOutEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_focusOutEvent_h" qtc_QLineEdit_focusOutEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent (QLineEditSc a) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_focusOutEvent_h cobj_x0 cobj_x1 instance QhasAcceptableInput (QLineEdit a) (()) where hasAcceptableInput x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_hasAcceptableInput cobj_x0 foreign import ccall "qtc_QLineEdit_hasAcceptableInput" qtc_QLineEdit_hasAcceptableInput :: Ptr (TQLineEdit a) -> IO CBool instance QhasFrame (QLineEdit a) (()) where hasFrame x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_hasFrame cobj_x0 foreign import ccall "qtc_QLineEdit_hasFrame" qtc_QLineEdit_hasFrame :: Ptr (TQLineEdit a) -> IO CBool hasSelectedText :: QLineEdit a -> (()) -> IO (Bool) hasSelectedText x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_hasSelectedText cobj_x0 foreign import ccall "qtc_QLineEdit_hasSelectedText" qtc_QLineEdit_hasSelectedText :: Ptr (TQLineEdit a) -> IO CBool instance Qhome (QLineEdit a) ((Bool)) where home x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_home cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_home" qtc_QLineEdit_home :: Ptr (TQLineEdit a) -> CBool -> IO () instance QinitStyleOption (QLineEdit ()) ((QStyleOptionFrame t1)) where initStyleOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_initStyleOption cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_initStyleOption" qtc_QLineEdit_initStyleOption :: Ptr (TQLineEdit a) -> Ptr (TQStyleOptionFrame t1) -> IO () instance QinitStyleOption (QLineEditSc a) ((QStyleOptionFrame t1)) where initStyleOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_initStyleOption cobj_x0 cobj_x1 inputMask :: QLineEdit a -> (()) -> IO (String) inputMask x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_inputMask cobj_x0 foreign import ccall "qtc_QLineEdit_inputMask" qtc_QLineEdit_inputMask :: Ptr (TQLineEdit a) -> IO (Ptr (TQString ())) instance QinputMethodEvent (QLineEdit ()) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_inputMethodEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_inputMethodEvent" qtc_QLineEdit_inputMethodEvent :: Ptr (TQLineEdit a) -> Ptr (TQInputMethodEvent t1) -> IO () instance QinputMethodEvent (QLineEditSc a) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_inputMethodEvent cobj_x0 cobj_x1 instance QinputMethodQuery (QLineEdit ()) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QLineEdit_inputMethodQuery_h" qtc_QLineEdit_inputMethodQuery_h :: Ptr (TQLineEdit a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery (QLineEditSc a) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) insert :: QLineEdit a -> ((String)) -> IO () insert x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_insert cobj_x0 cstr_x1 foreign import ccall "qtc_QLineEdit_insert" qtc_QLineEdit_insert :: Ptr (TQLineEdit a) -> CWString -> IO () instance QisModified (QLineEdit a) (()) where isModified x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_isModified cobj_x0 foreign import ccall "qtc_QLineEdit_isModified" qtc_QLineEdit_isModified :: Ptr (TQLineEdit a) -> IO CBool instance QisReadOnly (QLineEdit a) (()) where isReadOnly x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_isReadOnly cobj_x0 foreign import ccall "qtc_QLineEdit_isReadOnly" qtc_QLineEdit_isReadOnly :: Ptr (TQLineEdit a) -> IO CBool instance QisRedoAvailable (QLineEdit a) (()) where isRedoAvailable x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_isRedoAvailable cobj_x0 foreign import ccall "qtc_QLineEdit_isRedoAvailable" qtc_QLineEdit_isRedoAvailable :: Ptr (TQLineEdit a) -> IO CBool instance QisUndoAvailable (QLineEdit a) (()) where isUndoAvailable x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_isUndoAvailable cobj_x0 foreign import ccall "qtc_QLineEdit_isUndoAvailable" qtc_QLineEdit_isUndoAvailable :: Ptr (TQLineEdit a) -> IO CBool instance QkeyPressEvent (QLineEdit ()) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_keyPressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_keyPressEvent_h" qtc_QLineEdit_keyPressEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent (QLineEditSc a) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_keyPressEvent_h cobj_x0 cobj_x1 maxLength :: QLineEdit a -> (()) -> IO (Int) maxLength x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_maxLength cobj_x0 foreign import ccall "qtc_QLineEdit_maxLength" qtc_QLineEdit_maxLength :: Ptr (TQLineEdit a) -> IO CInt instance QqminimumSizeHint (QLineEdit ()) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_minimumSizeHint_h cobj_x0 foreign import ccall "qtc_QLineEdit_minimumSizeHint_h" qtc_QLineEdit_minimumSizeHint_h :: Ptr (TQLineEdit a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint (QLineEditSc a) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_minimumSizeHint_h cobj_x0 instance QminimumSizeHint (QLineEdit ()) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QLineEdit_minimumSizeHint_qth_h" qtc_QLineEdit_minimumSizeHint_qth_h :: Ptr (TQLineEdit a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint (QLineEditSc a) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance QmouseDoubleClickEvent (QLineEdit ()) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mouseDoubleClickEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_mouseDoubleClickEvent_h" qtc_QLineEdit_mouseDoubleClickEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent (QLineEditSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mouseDoubleClickEvent_h cobj_x0 cobj_x1 instance QmouseMoveEvent (QLineEdit ()) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mouseMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_mouseMoveEvent_h" qtc_QLineEdit_mouseMoveEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent (QLineEditSc a) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mouseMoveEvent_h cobj_x0 cobj_x1 instance QmousePressEvent (QLineEdit ()) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mousePressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_mousePressEvent_h" qtc_QLineEdit_mousePressEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent (QLineEditSc a) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mousePressEvent_h cobj_x0 cobj_x1 instance QmouseReleaseEvent (QLineEdit ()) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mouseReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_mouseReleaseEvent_h" qtc_QLineEdit_mouseReleaseEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent (QLineEditSc a) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mouseReleaseEvent_h cobj_x0 cobj_x1 instance QpaintEvent (QLineEdit ()) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_paintEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_paintEvent_h" qtc_QLineEdit_paintEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent (QLineEditSc a) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_paintEvent_h cobj_x0 cobj_x1 instance Qpaste (QLineEdit a) (()) where paste x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_paste cobj_x0 foreign import ccall "qtc_QLineEdit_paste" qtc_QLineEdit_paste :: Ptr (TQLineEdit a) -> IO () instance Qredo (QLineEdit a) (()) where redo x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_redo cobj_x0 foreign import ccall "qtc_QLineEdit_redo" qtc_QLineEdit_redo :: Ptr (TQLineEdit a) -> IO () instance QselectAll (QLineEdit a) (()) where selectAll x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_selectAll cobj_x0 foreign import ccall "qtc_QLineEdit_selectAll" qtc_QLineEdit_selectAll :: Ptr (TQLineEdit a) -> IO () instance QselectedText (QLineEdit a) (()) where selectedText x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_selectedText cobj_x0 foreign import ccall "qtc_QLineEdit_selectedText" qtc_QLineEdit_selectedText :: Ptr (TQLineEdit a) -> IO (Ptr (TQString ())) instance QselectionStart (QLineEdit a) (()) where selectionStart x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_selectionStart cobj_x0 foreign import ccall "qtc_QLineEdit_selectionStart" qtc_QLineEdit_selectionStart :: Ptr (TQLineEdit a) -> IO CInt instance QsetAlignment (QLineEdit a) ((Alignment)) (IO ()) where setAlignment x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setAlignment cobj_x0 (toCLong $ qFlags_toInt x1) foreign import ccall "qtc_QLineEdit_setAlignment" qtc_QLineEdit_setAlignment :: Ptr (TQLineEdit a) -> CLong -> IO () instance QsetCompleter (QLineEdit a) ((QCompleter t1)) where setCompleter x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_setCompleter cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_setCompleter" qtc_QLineEdit_setCompleter :: Ptr (TQLineEdit a) -> Ptr (TQCompleter t1) -> IO () setCursorPosition :: QLineEdit a -> ((Int)) -> IO () setCursorPosition x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setCursorPosition cobj_x0 (toCInt x1) foreign import ccall "qtc_QLineEdit_setCursorPosition" qtc_QLineEdit_setCursorPosition :: Ptr (TQLineEdit a) -> CInt -> IO () instance QsetDragEnabled (QLineEdit a) ((Bool)) where setDragEnabled x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setDragEnabled cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_setDragEnabled" qtc_QLineEdit_setDragEnabled :: Ptr (TQLineEdit a) -> CBool -> IO () setEchoMode :: QLineEdit a -> ((EchoMode)) -> IO () setEchoMode x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setEchoMode cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QLineEdit_setEchoMode" qtc_QLineEdit_setEchoMode :: Ptr (TQLineEdit a) -> CLong -> IO () instance QsetFrame (QLineEdit a) ((Bool)) where setFrame x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setFrame cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_setFrame" qtc_QLineEdit_setFrame :: Ptr (TQLineEdit a) -> CBool -> IO () setInputMask :: QLineEdit a -> ((String)) -> IO () setInputMask x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_setInputMask cobj_x0 cstr_x1 foreign import ccall "qtc_QLineEdit_setInputMask" qtc_QLineEdit_setInputMask :: Ptr (TQLineEdit a) -> CWString -> IO () setMaxLength :: QLineEdit a -> ((Int)) -> IO () setMaxLength x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setMaxLength cobj_x0 (toCInt x1) foreign import ccall "qtc_QLineEdit_setMaxLength" qtc_QLineEdit_setMaxLength :: Ptr (TQLineEdit a) -> CInt -> IO () instance QsetModified (QLineEdit a) ((Bool)) where setModified x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setModified cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_setModified" qtc_QLineEdit_setModified :: Ptr (TQLineEdit a) -> CBool -> IO () instance QsetReadOnly (QLineEdit a) ((Bool)) where setReadOnly x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setReadOnly cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_setReadOnly" qtc_QLineEdit_setReadOnly :: Ptr (TQLineEdit a) -> CBool -> IO () instance QsetSelection (QLineEdit a) ((Int, Int)) where setSelection x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setSelection cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QLineEdit_setSelection" qtc_QLineEdit_setSelection :: Ptr (TQLineEdit a) -> CInt -> CInt -> IO () instance QsetText (QLineEdit a) ((String)) where setText x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_setText cobj_x0 cstr_x1 foreign import ccall "qtc_QLineEdit_setText" qtc_QLineEdit_setText :: Ptr (TQLineEdit a) -> CWString -> IO () instance QsetValidator (QLineEdit a) ((QValidator t1)) where setValidator x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_setValidator cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_setValidator" qtc_QLineEdit_setValidator :: Ptr (TQLineEdit a) -> Ptr (TQValidator t1) -> IO () instance QqsizeHint (QLineEdit ()) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_sizeHint_h cobj_x0 foreign import ccall "qtc_QLineEdit_sizeHint_h" qtc_QLineEdit_sizeHint_h :: Ptr (TQLineEdit a) -> IO (Ptr (TQSize ())) instance QqsizeHint (QLineEditSc a) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_sizeHint_h cobj_x0 instance QsizeHint (QLineEdit ()) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QLineEdit_sizeHint_qth_h" qtc_QLineEdit_sizeHint_qth_h :: Ptr (TQLineEdit a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint (QLineEditSc a) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance Qtext (QLineEdit a) (()) (IO (String)) where text x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_text cobj_x0 foreign import ccall "qtc_QLineEdit_text" qtc_QLineEdit_text :: Ptr (TQLineEdit a) -> IO (Ptr (TQString ())) instance Qundo (QLineEdit a) (()) where undo x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_undo cobj_x0 foreign import ccall "qtc_QLineEdit_undo" qtc_QLineEdit_undo :: Ptr (TQLineEdit a) -> IO () instance Qvalidator (QLineEdit a) (()) where validator x0 () = withQValidatorResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_validator cobj_x0 foreign import ccall "qtc_QLineEdit_validator" qtc_QLineEdit_validator :: Ptr (TQLineEdit a) -> IO (Ptr (TQValidator ())) qLineEdit_delete :: QLineEdit a -> IO () qLineEdit_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_delete cobj_x0 foreign import ccall "qtc_QLineEdit_delete" qtc_QLineEdit_delete :: Ptr (TQLineEdit a) -> IO () qLineEdit_deleteLater :: QLineEdit a -> IO () qLineEdit_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_deleteLater cobj_x0 foreign import ccall "qtc_QLineEdit_deleteLater" qtc_QLineEdit_deleteLater :: Ptr (TQLineEdit a) -> IO () instance QactionEvent (QLineEdit ()) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_actionEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_actionEvent_h" qtc_QLineEdit_actionEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent (QLineEditSc a) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_actionEvent_h cobj_x0 cobj_x1 instance QaddAction (QLineEdit ()) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_addAction cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_addAction" qtc_QLineEdit_addAction :: Ptr (TQLineEdit a) -> Ptr (TQAction t1) -> IO () instance QaddAction (QLineEditSc a) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_addAction cobj_x0 cobj_x1 instance QcloseEvent (QLineEdit ()) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_closeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_closeEvent_h" qtc_QLineEdit_closeEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent (QLineEditSc a) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_closeEvent_h cobj_x0 cobj_x1 instance Qcreate (QLineEdit ()) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_create cobj_x0 foreign import ccall "qtc_QLineEdit_create" qtc_QLineEdit_create :: Ptr (TQLineEdit a) -> IO () instance Qcreate (QLineEditSc a) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_create cobj_x0 instance Qcreate (QLineEdit ()) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_create1 cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_create1" qtc_QLineEdit_create1 :: Ptr (TQLineEdit a) -> Ptr (TQVoid t1) -> IO () instance Qcreate (QLineEditSc a) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_create1 cobj_x0 cobj_x1 instance Qcreate (QLineEdit ()) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_create2 cobj_x0 cobj_x1 (toCBool x2) foreign import ccall "qtc_QLineEdit_create2" qtc_QLineEdit_create2 :: Ptr (TQLineEdit a) -> Ptr (TQVoid t1) -> CBool -> IO () instance Qcreate (QLineEditSc a) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_create2 cobj_x0 cobj_x1 (toCBool x2) instance Qcreate (QLineEdit ()) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) foreign import ccall "qtc_QLineEdit_create3" qtc_QLineEdit_create3 :: Ptr (TQLineEdit a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO () instance Qcreate (QLineEditSc a) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) instance Qdestroy (QLineEdit ()) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_destroy cobj_x0 foreign import ccall "qtc_QLineEdit_destroy" qtc_QLineEdit_destroy :: Ptr (TQLineEdit a) -> IO () instance Qdestroy (QLineEditSc a) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_destroy cobj_x0 instance Qdestroy (QLineEdit ()) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_destroy1 cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_destroy1" qtc_QLineEdit_destroy1 :: Ptr (TQLineEdit a) -> CBool -> IO () instance Qdestroy (QLineEditSc a) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_destroy1 cobj_x0 (toCBool x1) instance Qdestroy (QLineEdit ()) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_destroy2 cobj_x0 (toCBool x1) (toCBool x2) foreign import ccall "qtc_QLineEdit_destroy2" qtc_QLineEdit_destroy2 :: Ptr (TQLineEdit a) -> CBool -> CBool -> IO () instance Qdestroy (QLineEditSc a) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_destroy2 cobj_x0 (toCBool x1) (toCBool x2) instance QdevType (QLineEdit ()) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_devType_h cobj_x0 foreign import ccall "qtc_QLineEdit_devType_h" qtc_QLineEdit_devType_h :: Ptr (TQLineEdit a) -> IO CInt instance QdevType (QLineEditSc a) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_devType_h cobj_x0 instance QenabledChange (QLineEdit ()) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_enabledChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_enabledChange" qtc_QLineEdit_enabledChange :: Ptr (TQLineEdit a) -> CBool -> IO () instance QenabledChange (QLineEditSc a) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_enabledChange cobj_x0 (toCBool x1) instance QenterEvent (QLineEdit ()) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_enterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_enterEvent_h" qtc_QLineEdit_enterEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent (QLineEditSc a) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_enterEvent_h cobj_x0 cobj_x1 instance QfocusNextChild (QLineEdit ()) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_focusNextChild cobj_x0 foreign import ccall "qtc_QLineEdit_focusNextChild" qtc_QLineEdit_focusNextChild :: Ptr (TQLineEdit a) -> IO CBool instance QfocusNextChild (QLineEditSc a) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_focusNextChild cobj_x0 instance QfocusNextPrevChild (QLineEdit ()) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_focusNextPrevChild cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_focusNextPrevChild" qtc_QLineEdit_focusNextPrevChild :: Ptr (TQLineEdit a) -> CBool -> IO CBool instance QfocusNextPrevChild (QLineEditSc a) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_focusNextPrevChild cobj_x0 (toCBool x1) instance QfocusPreviousChild (QLineEdit ()) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_focusPreviousChild cobj_x0 foreign import ccall "qtc_QLineEdit_focusPreviousChild" qtc_QLineEdit_focusPreviousChild :: Ptr (TQLineEdit a) -> IO CBool instance QfocusPreviousChild (QLineEditSc a) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_focusPreviousChild cobj_x0 instance QfontChange (QLineEdit ()) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_fontChange cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_fontChange" qtc_QLineEdit_fontChange :: Ptr (TQLineEdit a) -> Ptr (TQFont t1) -> IO () instance QfontChange (QLineEditSc a) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_fontChange cobj_x0 cobj_x1 instance QheightForWidth (QLineEdit ()) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_heightForWidth_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QLineEdit_heightForWidth_h" qtc_QLineEdit_heightForWidth_h :: Ptr (TQLineEdit a) -> CInt -> IO CInt instance QheightForWidth (QLineEditSc a) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_heightForWidth_h cobj_x0 (toCInt x1) instance QhideEvent (QLineEdit ()) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_hideEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_hideEvent_h" qtc_QLineEdit_hideEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent (QLineEditSc a) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_hideEvent_h cobj_x0 cobj_x1 instance QkeyReleaseEvent (QLineEdit ()) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_keyReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_keyReleaseEvent_h" qtc_QLineEdit_keyReleaseEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent (QLineEditSc a) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_keyReleaseEvent_h cobj_x0 cobj_x1 instance QlanguageChange (QLineEdit ()) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_languageChange cobj_x0 foreign import ccall "qtc_QLineEdit_languageChange" qtc_QLineEdit_languageChange :: Ptr (TQLineEdit a) -> IO () instance QlanguageChange (QLineEditSc a) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_languageChange cobj_x0 instance QleaveEvent (QLineEdit ()) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_leaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_leaveEvent_h" qtc_QLineEdit_leaveEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent (QLineEditSc a) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_leaveEvent_h cobj_x0 cobj_x1 instance Qmetric (QLineEdit ()) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_metric cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QLineEdit_metric" qtc_QLineEdit_metric :: Ptr (TQLineEdit a) -> CLong -> IO CInt instance Qmetric (QLineEditSc a) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_metric cobj_x0 (toCLong $ qEnum_toInt x1) instance Qmove (QLineEdit ()) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_move1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QLineEdit_move1" qtc_QLineEdit_move1 :: Ptr (TQLineEdit a) -> CInt -> CInt -> IO () instance Qmove (QLineEditSc a) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_move1 cobj_x0 (toCInt x1) (toCInt x2) instance Qmove (QLineEdit ()) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QLineEdit_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QLineEdit_move_qth" qtc_QLineEdit_move_qth :: Ptr (TQLineEdit a) -> CInt -> CInt -> IO () instance Qmove (QLineEditSc a) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QLineEdit_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y instance Qqmove (QLineEdit ()) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_move cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_move" qtc_QLineEdit_move :: Ptr (TQLineEdit a) -> Ptr (TQPoint t1) -> IO () instance Qqmove (QLineEditSc a) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_move cobj_x0 cobj_x1 instance QmoveEvent (QLineEdit ()) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_moveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_moveEvent_h" qtc_QLineEdit_moveEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent (QLineEditSc a) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_moveEvent_h cobj_x0 cobj_x1 instance QpaintEngine (QLineEdit ()) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_paintEngine_h cobj_x0 foreign import ccall "qtc_QLineEdit_paintEngine_h" qtc_QLineEdit_paintEngine_h :: Ptr (TQLineEdit a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine (QLineEditSc a) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_paintEngine_h cobj_x0 instance QpaletteChange (QLineEdit ()) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_paletteChange cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_paletteChange" qtc_QLineEdit_paletteChange :: Ptr (TQLineEdit a) -> Ptr (TQPalette t1) -> IO () instance QpaletteChange (QLineEditSc a) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_paletteChange cobj_x0 cobj_x1 instance Qrepaint (QLineEdit ()) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_repaint cobj_x0 foreign import ccall "qtc_QLineEdit_repaint" qtc_QLineEdit_repaint :: Ptr (TQLineEdit a) -> IO () instance Qrepaint (QLineEditSc a) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_repaint cobj_x0 instance Qrepaint (QLineEdit ()) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QLineEdit_repaint2" qtc_QLineEdit_repaint2 :: Ptr (TQLineEdit a) -> CInt -> CInt -> CInt -> CInt -> IO () instance Qrepaint (QLineEditSc a) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance Qrepaint (QLineEdit ()) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_repaint1 cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_repaint1" qtc_QLineEdit_repaint1 :: Ptr (TQLineEdit a) -> Ptr (TQRegion t1) -> IO () instance Qrepaint (QLineEditSc a) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_repaint1 cobj_x0 cobj_x1 instance QresetInputContext (QLineEdit ()) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_resetInputContext cobj_x0 foreign import ccall "qtc_QLineEdit_resetInputContext" qtc_QLineEdit_resetInputContext :: Ptr (TQLineEdit a) -> IO () instance QresetInputContext (QLineEditSc a) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_resetInputContext cobj_x0 instance Qresize (QLineEdit ()) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_resize1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QLineEdit_resize1" qtc_QLineEdit_resize1 :: Ptr (TQLineEdit a) -> CInt -> CInt -> IO () instance Qresize (QLineEditSc a) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_resize1 cobj_x0 (toCInt x1) (toCInt x2) instance Qqresize (QLineEdit ()) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_resize cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_resize" qtc_QLineEdit_resize :: Ptr (TQLineEdit a) -> Ptr (TQSize t1) -> IO () instance Qqresize (QLineEditSc a) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_resize cobj_x0 cobj_x1 instance Qresize (QLineEdit ()) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QLineEdit_resize_qth cobj_x0 csize_x1_w csize_x1_h foreign import ccall "qtc_QLineEdit_resize_qth" qtc_QLineEdit_resize_qth :: Ptr (TQLineEdit a) -> CInt -> CInt -> IO () instance Qresize (QLineEditSc a) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QLineEdit_resize_qth cobj_x0 csize_x1_w csize_x1_h instance QresizeEvent (QLineEdit ()) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_resizeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_resizeEvent_h" qtc_QLineEdit_resizeEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent (QLineEditSc a) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_resizeEvent_h cobj_x0 cobj_x1 instance QsetGeometry (QLineEdit ()) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QLineEdit_setGeometry1" qtc_QLineEdit_setGeometry1 :: Ptr (TQLineEdit a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QLineEditSc a) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance QqsetGeometry (QLineEdit ()) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_setGeometry cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_setGeometry" qtc_QLineEdit_setGeometry :: Ptr (TQLineEdit a) -> Ptr (TQRect t1) -> IO () instance QqsetGeometry (QLineEditSc a) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_setGeometry cobj_x0 cobj_x1 instance QsetGeometry (QLineEdit ()) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QLineEdit_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QLineEdit_setGeometry_qth" qtc_QLineEdit_setGeometry_qth :: Ptr (TQLineEdit a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QLineEditSc a) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QLineEdit_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QsetMouseTracking (QLineEdit ()) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setMouseTracking cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_setMouseTracking" qtc_QLineEdit_setMouseTracking :: Ptr (TQLineEdit a) -> CBool -> IO () instance QsetMouseTracking (QLineEditSc a) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setMouseTracking cobj_x0 (toCBool x1) instance QsetVisible (QLineEdit ()) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setVisible_h cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_setVisible_h" qtc_QLineEdit_setVisible_h :: Ptr (TQLineEdit a) -> CBool -> IO () instance QsetVisible (QLineEditSc a) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setVisible_h cobj_x0 (toCBool x1) instance QshowEvent (QLineEdit ()) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_showEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_showEvent_h" qtc_QLineEdit_showEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent (QLineEditSc a) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_showEvent_h cobj_x0 cobj_x1 instance QtabletEvent (QLineEdit ()) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_tabletEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_tabletEvent_h" qtc_QLineEdit_tabletEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent (QLineEditSc a) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_tabletEvent_h cobj_x0 cobj_x1 instance QupdateMicroFocus (QLineEdit ()) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_updateMicroFocus cobj_x0 foreign import ccall "qtc_QLineEdit_updateMicroFocus" qtc_QLineEdit_updateMicroFocus :: Ptr (TQLineEdit a) -> IO () instance QupdateMicroFocus (QLineEditSc a) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_updateMicroFocus cobj_x0 instance QwheelEvent (QLineEdit ()) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_wheelEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_wheelEvent_h" qtc_QLineEdit_wheelEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent (QLineEditSc a) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_wheelEvent_h cobj_x0 cobj_x1 instance QwindowActivationChange (QLineEdit ()) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_windowActivationChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_windowActivationChange" qtc_QLineEdit_windowActivationChange :: Ptr (TQLineEdit a) -> CBool -> IO () instance QwindowActivationChange (QLineEditSc a) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_windowActivationChange cobj_x0 (toCBool x1) instance QchildEvent (QLineEdit ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_childEvent" qtc_QLineEdit_childEvent :: Ptr (TQLineEdit a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QLineEditSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QLineEdit ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QLineEdit_connectNotify" qtc_QLineEdit_connectNotify :: Ptr (TQLineEdit a) -> CWString -> IO () instance QconnectNotify (QLineEditSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QLineEdit ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_customEvent" qtc_QLineEdit_customEvent :: Ptr (TQLineEdit a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QLineEditSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QLineEdit ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QLineEdit_disconnectNotify" qtc_QLineEdit_disconnectNotify :: Ptr (TQLineEdit a) -> CWString -> IO () instance QdisconnectNotify (QLineEditSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_disconnectNotify cobj_x0 cstr_x1 instance QeventFilter (QLineEdit ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QLineEdit_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QLineEdit_eventFilter_h" qtc_QLineEdit_eventFilter_h :: Ptr (TQLineEdit a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QLineEditSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QLineEdit_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qreceivers (QLineEdit ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QLineEdit_receivers" qtc_QLineEdit_receivers :: Ptr (TQLineEdit a) -> CWString -> IO CInt instance Qreceivers (QLineEditSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_receivers cobj_x0 cstr_x1 instance Qsender (QLineEdit ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_sender cobj_x0 foreign import ccall "qtc_QLineEdit_sender" qtc_QLineEdit_sender :: Ptr (TQLineEdit a) -> IO (Ptr (TQObject ())) instance Qsender (QLineEditSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_sender cobj_x0 instance QtimerEvent (QLineEdit ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_timerEvent" qtc_QLineEdit_timerEvent :: Ptr (TQLineEdit a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QLineEditSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_timerEvent cobj_x0 cobj_x1
keera-studios/hsQt
Qtc/Gui/QLineEdit.hs
bsd-2-clause
59,042
0
14
9,734
19,614
9,943
9,671
-1
-1
{-# LANGUAGE BangPatterns #-} module AI.HMM.Type where import qualified Data.Vector as V import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Generic as G import Numeric.LinearAlgebra.HMatrix import AI.Function -- constant: log (2*pi) m_log_2_pi :: Double m_log_2_pi = 1.8378770664093453 -- | multivariate normal distribution data MVN = MVN { _mean :: !(U.Vector Double) , _cov :: !(U.Vector Double) -- ^ row majored covariance matrix , _invcov :: !(U.Vector Double) , _logdet :: !Double -- ^ log determinant of covariance matrix , _dim :: !Int , _covType :: !CovType } deriving (Show) data CovType = Full | Diagonal deriving (Show) data CovEstimator = FullCov | DiagonalCov | LassoCov mvn :: U.Vector Double -> U.Vector Double -> MVN mvn m cov | d*d /= U.length cov = error "incompatible dimemsion of mean and covariance" | otherwise = MVN m cov (G.convert $ flatten invcov) logdet d Full where (invcov, (logdet, _)) = invlndet $ reshape d $ G.convert cov d = U.length m {-# INLINE mvn #-} mvnDiag :: U.Vector Double -> U.Vector Double -> MVN mvnDiag m cov | d /= U.length cov = error "incompatible dimemsion of mean and covariance" | otherwise = MVN m cov invcov logdet d Diagonal where invcov = U.map (1/) cov logdet = U.sum . U.map log $ cov d = U.length m {-# INLINE mvnDiag #-} {- -- | log probability of MVN logPDF :: MVN -> Vector Double -> Double logPDF (MVN m _ invcov logdet) x = -0.5 * ( d * log (2*pi) + logdet + (x' <> invcov <> tr x') ! 0 ! 0 ) where x' = asRow $ x - m d = fromIntegral . G.length $ m {-# INLINE logPDF #-} -} logPDF :: MVN -> U.Vector Double -> Double logPDF (MVN m _ invcov logdet d t) x = -0.5 * (fromIntegral d * m_log_2_pi + logdet + quadTerm) where quadTerm = case t of Full -> loop 0 0 Diagonal -> U.sum $ U.zipWith (*) invcov $ U.map (**2) x' where loop !acc !i | i < d*d = let r = i `div` d c = i `mod` d in acc + U.unsafeIndex invcov i * U.unsafeIndex x' r * U.unsafeIndex x' c | otherwise = acc x' = U.zipWith (-) x m {-# INLINE logPDF #-} -- | mixture of multivariate normal variables, weight is in log form newtype MixMVN = MixMVN (V.Vector (Double, MVN)) deriving (Show) getWeight :: MixMVN -> Int -> Double getWeight (MixMVN xs) i = fst $ xs V.! i {-# INLINE getWeight #-} logPDFMix :: MixMVN -> U.Vector Double -> Double logPDFMix (MixMVN v) xs = logSumExp . V.map (\(logw, m) -> logw + logPDF m xs) $ v {-# INLINE logPDFMix #-}
kaizhang/HMM
src/AI/HMM/Type.hs
bsd-3-clause
2,750
0
16
808
812
429
383
67
2
module Paths_bogre_banana ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version {versionBranch = [0,0,1], versionTags = []} bindir, libdir, datadir, libexecdir :: FilePath bindir = "/home/david/.cabal/bin" libdir = "/home/david/.cabal/lib/bogre-banana-0.0.1/ghc-7.4.2" datadir = "/home/david/.cabal/share/bogre-banana-0.0.1" libexecdir = "/home/david/.cabal/libexec" getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath getBinDir = catchIO (getEnv "bogre_banana_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "bogre_banana_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "bogre_banana_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "bogre_banana_libexecdir") (\_ -> return libexecdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
DavidEichmann/boger-banana
.dist-buildwrapper/dist/build/autogen/Paths_bogre_banana.hs
bsd-3-clause
1,156
0
10
164
326
186
140
25
1
module Main where import System.Environment (getArgs) import Budget.App (run, BudgetCommand(..)) main :: IO () main = do args <- getArgs case parseOpts args of Left m -> putStrLn m Right c -> run c parseOpts :: [String] -> Either String BudgetCommand parseOpts ("configure":options) = Right (Configure (parseDatapath options)) parseOpts ("start":options) = Right (Start (parsePort options) (parseDatapath options)) parseOpts _ = Left "configure | start" parseDatapath :: [String] -> String parseDatapath [] = ":memory:" parseDatapath ("-d":datapath:_) = datapath parseDatapath (_:xs) = parseDatapath xs parsePort :: [String] -> Int parsePort [] = 8080 parsePort ("-p":port:_) = read port parsePort (_:xs) = parsePort xs
utky/budget
app/Main.hs
bsd-3-clause
808
0
10
189
304
156
148
24
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-| Module : Numeric.AERN.RealArithmetic.Basis.MPFR.Effort Description : MPFR precision is an effort indicator Copyright : (c) Michal Konecny License : BSD3 Maintainer : [email protected] Stability : experimental Portability : portable MPFR precision is an effort indicator. This is a private module reexported publicly via its parent. -} module Numeric.AERN.RealArithmetic.Basis.MPFR.Basics ( MPFR(..), RoundedTowardInf, liftRoundedToMPFR1, liftRoundedToMPFR2, MPFRPrec, defaultPrecision, getPrecision, samePrecision, withPrec, withPrecRoundDown ) where import Numeric.AERN.Basics.Effort import qualified Numeric.Rounded as R import GHC.TypeLits import Data.Proxy import Unsafe.Coerce --import qualified Data.Number.MPFR as M import Test.QuickCheck data MPFR = forall p. (R.Precision p) => MPFR (RoundedTowardInf p) type RoundedTowardInf p = R.Rounded R.TowardInf p deriving instance Show MPFR newtype MPFRPrec = MPFRPrec Int deriving (Eq, Ord, Show, Enum, EffortIndicator, Num, Real, Integral) withPrec :: MPFRPrec -> (forall p. (R.Precision p) => R.Rounded R.TowardInf p) -> MPFR withPrec (MPFRPrec p) computation | p < 2 = error "MPFR precision has to be at least 2" | otherwise = R.reifyPrecision p (\(_ :: Proxy p) -> MPFR (computation :: R.Rounded R.TowardInf p)) {-| This should be needed very rarely, in cases such as to get a lower bound on pi. -} withPrecRoundDown :: MPFRPrec -> (forall p. (R.Precision p) => R.Rounded R.TowardNegInf p) -> MPFR withPrecRoundDown (MPFRPrec p) computation | p < 2 = error "MPFR precision has to be at least 2" | otherwise = R.reifyPrecision p (\(_ :: Proxy p) -> MPFR (unsafeCoerce (computation :: R.Rounded R.TowardNegInf p) :: R.Rounded R.TowardInf p)) instance Arbitrary MPFRPrec where arbitrary = do p <- choose (10,1000) return (MPFRPrec (p :: Int)) defaultPrecision :: MPFRPrec defaultPrecision = 100 --type DefaultPrecision = 100 getPrecision :: MPFR -> MPFRPrec getPrecision (MPFR v) = MPFRPrec $ R.precision v samePrecision :: MPFR -> MPFR -> Bool samePrecision m1 m2 = p1 == p2 where p1 = getPrecision m1 p2 = getPrecision m2 withSamePrecision :: String -> (forall p. (R.Precision p) => (RoundedTowardInf p) -> (RoundedTowardInf p) -> t) -> MPFR -> MPFR -> t withSamePrecision context f m1@(MPFR v1) m2@(MPFR v2) | samePrecision m1 m2 = f v1 (unsafeCoerce v2) | otherwise = error $ mixPrecisionErrorMessage context m1 m2 mixPrecisionErrorMessage context m1 m2 = context ++ ": trying to mix precisions: " ++ show (getPrecision m1) ++ " vs " ++ show (getPrecision m2) instance Eq MPFR where (==) = withSamePrecision "==" (==) instance Ord MPFR where compare = withSamePrecision "compare" compare liftRoundedToMPFR1 :: (forall p. (R.Precision p) => (RoundedTowardInf p) -> (RoundedTowardInf p)) -> MPFR -> MPFR liftRoundedToMPFR1 f (MPFR v) = (MPFR (f v)) liftRoundedToMPFR2 :: String -> (forall p. (R.Precision p) => (RoundedTowardInf p) -> (RoundedTowardInf p) -> (RoundedTowardInf p)) -> MPFR -> MPFR -> MPFR liftRoundedToMPFR2 context f = withSamePrecision context (\ v1 v2 -> MPFR (f v1 v2)) instance Num MPFR where (+) = liftRoundedToMPFR2 "+" (+) (-) = liftRoundedToMPFR2 "-" (-) (*) = liftRoundedToMPFR2 "*" (*) negate = liftRoundedToMPFR1 negate -- fromInteger n = withPrec defaultPrecision $ fromInteger n -- useless fromInteger _ = error "MPFR type: fromInteger not implemented" abs = liftRoundedToMPFR1 abs signum = liftRoundedToMPFR1 signum instance Fractional MPFR where (/) = liftRoundedToMPFR2 "/" (/) fromRational _ = error "MPFR type: fromRational not implemented" instance Floating MPFR where pi = error "MPFR type: pi not implemented" exp = liftRoundedToMPFR1 exp sqrt = liftRoundedToMPFR1 sqrt log = liftRoundedToMPFR1 log sin = liftRoundedToMPFR1 sin tan = liftRoundedToMPFR1 tan cos = liftRoundedToMPFR1 cos asin = liftRoundedToMPFR1 asin atan = liftRoundedToMPFR1 atan acos = liftRoundedToMPFR1 acos sinh = liftRoundedToMPFR1 sinh tanh = liftRoundedToMPFR1 tanh cosh = liftRoundedToMPFR1 cosh asinh = liftRoundedToMPFR1 asinh atanh = liftRoundedToMPFR1 atanh acosh = liftRoundedToMPFR1 acosh instance Real MPFR where toRational (MPFR v) = toRational v {- local tests as a proof of concept: -} testRounded = R.reifyPrecision 512 (\(_ :: Proxy p) -> show (logBase 10 2 :: R.Rounded R.TowardNearest p)) a :: MPFR a = withPrec 100 pi b :: MPFR b = withPrec 1000 1 aPrec = getPrecision a mpfrPlus :: MPFR -> MPFR -> MPFR mpfrPlus = liftRoundedToMPFR2 "mpfrPlus" (+) aPa = a `mpfrPlus` a aPb = a `mpfrPlus` b -- throws exception
michalkonecny/aern
aern-mpfr-rounded/src/Numeric/AERN/RealArithmetic/Basis/MPFR/Basics.hs
bsd-3-clause
5,210
0
14
1,162
1,404
747
657
124
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} module Home.Routes where import Servant import Servant.HTML.Blaze import Text.Blaze.Html5 type HomeRoutes = Home type Home = Get '[HTML] Html
hectorhon/autotrace2
app/Home/Routes.hs
bsd-3-clause
204
0
7
31
45
29
16
8
0
-- 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.Distance.KO.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Testing.Asserts import Duckling.Distance.KO.Corpus tests :: TestTree tests = testGroup "KO Tests" [ makeCorpusTest [Seal Distance] corpus ]
facebookincubator/duckling
tests/Duckling/Distance/KO/Tests.hs
bsd-3-clause
507
0
9
78
79
50
29
11
1
{-# LANGUAGE MultiParamTypeClasses #-} -- | Internal only. Do Not Eat. module Tea.TeaState ( TeaState (..) , EventState (..) ) where import Data.Map(Map) import Data.Array(Array) import Tea.Screen(Screen) import Tea.Input(KeyCode) data TeaState = TS { _screen :: Screen, _eventState :: EventState, _fpsCap :: Int, _lastUpdate :: Int, _channels :: Map Int Int} data EventState = ES { keyCodes :: Array KeyCode Bool , keysDown :: Int }
liamoc/tea-hs
Tea/TeaState.hs
bsd-3-clause
524
0
9
156
134
83
51
10
0
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable -} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} module Fragment.Bool.Rules.Kind.Infer.Common ( BoolInferKindConstraint , boolInferKindInput ) where import Data.Proxy (Proxy(..)) import Control.Lens (review, preview) import Ast.Kind import Ast.Type import Rules.Kind.Infer.Common import Fragment.KiBase.Ast.Kind import Fragment.Bool.Ast.Type type BoolInferKindConstraint e w s r m ki ty a i = ( BasicInferKindConstraint e w s r m ki ty a i , AsKiBase ki , AsTyBool ki ty ) boolInferKindInput :: BoolInferKindConstraint e w s r m ki ty a i => Proxy (MonadProxy e w s r m) -> Proxy i -> InferKindInput e w s r m (InferKindMonad m ki a i) ki ty a boolInferKindInput m i = InferKindInput [] [ InferKindBase $ inferTyBool m (Proxy :: Proxy ki) (Proxy :: Proxy ty) (Proxy :: Proxy a) i ] inferTyBool :: BoolInferKindConstraint e w s r m ki ty a i => Proxy (MonadProxy e w s r m) -> Proxy ki -> Proxy ty -> Proxy a -> Proxy i -> Type ki ty a -> Maybe (InferKindMonad m ki a i (Kind ki a)) inferTyBool pm pki pty pa pi ty = do _ <- preview _TyBool ty return . return . review _KiBase $ ()
dalaing/type-systems
src/Fragment/Bool/Rules/Kind/Infer/Common.hs
bsd-3-clause
1,494
0
16
411
444
237
207
37
1
----------------------------------------------------------------------------- -- -- Pretty-printing assembly language -- -- (c) The University of Glasgow 1993-2005 -- ----------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-warn-orphans #-} module PPC.Ppr ( pprNatCmmDecl, pprBasicBlock, pprSectionHeader, pprData, pprInstr, pprFormat, pprImm, pprDataItem, ) where import PPC.Regs import PPC.Instr import PPC.Cond import PprBase import Instruction import Format import Reg import RegClass import TargetReg import Cmm hiding (topInfoTable) import BlockId import CLabel import Unique ( pprUnique, Uniquable(..) ) import Platform import FastString import Outputable import DynFlags import Data.Word import Data.Bits -- ----------------------------------------------------------------------------- -- Printing this stuff out pprNatCmmDecl :: NatCmmDecl CmmStatics Instr -> SDoc pprNatCmmDecl (CmmData section dats) = pprSectionHeader section $$ pprDatas dats pprNatCmmDecl proc@(CmmProc top_info lbl _ (ListGraph blocks)) = case topInfoTable proc of Nothing -> sdocWithPlatform $ \platform -> case blocks of [] -> -- special case for split markers: pprLabel lbl blocks -> -- special case for code without info table: pprSectionHeader Text $$ (case platformArch platform of ArchPPC_64 ELF_V1 -> pprFunctionDescriptor lbl ArchPPC_64 ELF_V2 -> pprFunctionPrologue lbl _ -> pprLabel lbl) $$ -- blocks guaranteed not null, -- so label needed vcat (map (pprBasicBlock top_info) blocks) Just (Statics info_lbl _) -> sdocWithPlatform $ \platform -> (if platformHasSubsectionsViaSymbols platform then pprSectionHeader Text $$ ppr (mkDeadStripPreventer info_lbl) <> char ':' else empty) $$ vcat (map (pprBasicBlock top_info) blocks) $$ -- above: Even the first block gets a label, because with branch-chain -- elimination, it might be the target of a goto. (if platformHasSubsectionsViaSymbols platform then -- See Note [Subsections Via Symbols] text "\t.long " <+> ppr info_lbl <+> char '-' <+> ppr (mkDeadStripPreventer info_lbl) else empty) pprFunctionDescriptor :: CLabel -> SDoc pprFunctionDescriptor lab = pprGloblDecl lab $$ text ".section \".opd\",\"aw\"" $$ text ".align 3" $$ ppr lab <> char ':' $$ text ".quad ." <> ppr lab <> text ",.TOC.@tocbase,0" $$ text ".previous" $$ text ".type " <> ppr lab <> text ", @function" $$ char '.' <> ppr lab <> char ':' pprFunctionPrologue :: CLabel ->SDoc pprFunctionPrologue lab = pprGloblDecl lab $$ text ".type " <> ppr lab <> text ", @function" $$ ppr lab <> char ':' $$ text "0:\taddis\t" <> pprReg toc <> text ",12,.TOC.-0b@ha" $$ text "\taddi\t" <> pprReg toc <> char ',' <> pprReg toc <> text ",.TOC.-0b@l" $$ text "\t.localentry\t" <> ppr lab <> text ",.-" <> ppr lab pprBasicBlock :: BlockEnv CmmStatics -> NatBasicBlock Instr -> SDoc pprBasicBlock info_env (BasicBlock blockid instrs) = maybe_infotable $$ pprLabel (mkAsmTempLabel (getUnique blockid)) $$ vcat (map pprInstr instrs) where maybe_infotable = case mapLookup blockid info_env of Nothing -> empty Just (Statics info_lbl info) -> pprSectionHeader Text $$ vcat (map pprData info) $$ pprLabel info_lbl pprDatas :: CmmStatics -> SDoc pprDatas (Statics lbl dats) = vcat (pprLabel lbl : map pprData dats) pprData :: CmmStatic -> SDoc pprData (CmmString str) = pprASCII str pprData (CmmUninitialised bytes) = keyword <> int bytes where keyword = sdocWithPlatform $ \platform -> case platformOS platform of OSDarwin -> ptext (sLit ".space ") _ -> ptext (sLit ".skip ") pprData (CmmStaticLit lit) = pprDataItem lit pprGloblDecl :: CLabel -> SDoc pprGloblDecl lbl | not (externallyVisibleCLabel lbl) = empty | otherwise = ptext (sLit ".globl ") <> ppr lbl pprTypeAndSizeDecl :: CLabel -> SDoc pprTypeAndSizeDecl lbl = sdocWithPlatform $ \platform -> if platformOS platform == OSLinux && externallyVisibleCLabel lbl then ptext (sLit ".type ") <> ppr lbl <> ptext (sLit ", @object") else empty pprLabel :: CLabel -> SDoc pprLabel lbl = pprGloblDecl lbl $$ pprTypeAndSizeDecl lbl $$ (ppr lbl <> char ':') pprASCII :: [Word8] -> SDoc pprASCII str = vcat (map do1 str) $$ do1 0 where do1 :: Word8 -> SDoc do1 w = ptext (sLit "\t.byte\t") <> int (fromIntegral w) -- ----------------------------------------------------------------------------- -- pprInstr: print an 'Instr' instance Outputable Instr where ppr instr = pprInstr instr pprReg :: Reg -> SDoc pprReg r = case r of RegReal (RealRegSingle i) -> ppr_reg_no i RegReal (RealRegPair{}) -> panic "PPC.pprReg: no reg pairs on this arch" RegVirtual (VirtualRegI u) -> text "%vI_" <> pprUnique u RegVirtual (VirtualRegHi u) -> text "%vHi_" <> pprUnique u RegVirtual (VirtualRegF u) -> text "%vF_" <> pprUnique u RegVirtual (VirtualRegD u) -> text "%vD_" <> pprUnique u RegVirtual (VirtualRegSSE u) -> text "%vSSE_" <> pprUnique u where ppr_reg_no :: Int -> SDoc ppr_reg_no i = sdocWithPlatform $ \platform -> case platformOS platform of OSDarwin -> ptext (case i of { 0 -> sLit "r0"; 1 -> sLit "r1"; 2 -> sLit "r2"; 3 -> sLit "r3"; 4 -> sLit "r4"; 5 -> sLit "r5"; 6 -> sLit "r6"; 7 -> sLit "r7"; 8 -> sLit "r8"; 9 -> sLit "r9"; 10 -> sLit "r10"; 11 -> sLit "r11"; 12 -> sLit "r12"; 13 -> sLit "r13"; 14 -> sLit "r14"; 15 -> sLit "r15"; 16 -> sLit "r16"; 17 -> sLit "r17"; 18 -> sLit "r18"; 19 -> sLit "r19"; 20 -> sLit "r20"; 21 -> sLit "r21"; 22 -> sLit "r22"; 23 -> sLit "r23"; 24 -> sLit "r24"; 25 -> sLit "r25"; 26 -> sLit "r26"; 27 -> sLit "r27"; 28 -> sLit "r28"; 29 -> sLit "r29"; 30 -> sLit "r30"; 31 -> sLit "r31"; 32 -> sLit "f0"; 33 -> sLit "f1"; 34 -> sLit "f2"; 35 -> sLit "f3"; 36 -> sLit "f4"; 37 -> sLit "f5"; 38 -> sLit "f6"; 39 -> sLit "f7"; 40 -> sLit "f8"; 41 -> sLit "f9"; 42 -> sLit "f10"; 43 -> sLit "f11"; 44 -> sLit "f12"; 45 -> sLit "f13"; 46 -> sLit "f14"; 47 -> sLit "f15"; 48 -> sLit "f16"; 49 -> sLit "f17"; 50 -> sLit "f18"; 51 -> sLit "f19"; 52 -> sLit "f20"; 53 -> sLit "f21"; 54 -> sLit "f22"; 55 -> sLit "f23"; 56 -> sLit "f24"; 57 -> sLit "f25"; 58 -> sLit "f26"; 59 -> sLit "f27"; 60 -> sLit "f28"; 61 -> sLit "f29"; 62 -> sLit "f30"; 63 -> sLit "f31"; _ -> sLit "very naughty powerpc register" }) _ | i <= 31 -> int i -- GPRs | i <= 63 -> int (i-32) -- FPRs | otherwise -> ptext (sLit "very naughty powerpc register") pprFormat :: Format -> SDoc pprFormat x = ptext (case x of II8 -> sLit "b" II16 -> sLit "h" II32 -> sLit "w" II64 -> sLit "d" FF32 -> sLit "fs" FF64 -> sLit "fd" _ -> panic "PPC.Ppr.pprFormat: no match") pprCond :: Cond -> SDoc pprCond c = ptext (case c of { ALWAYS -> sLit ""; EQQ -> sLit "eq"; NE -> sLit "ne"; LTT -> sLit "lt"; GE -> sLit "ge"; GTT -> sLit "gt"; LE -> sLit "le"; LU -> sLit "lt"; GEU -> sLit "ge"; GU -> sLit "gt"; LEU -> sLit "le"; }) pprImm :: Imm -> SDoc pprImm (ImmInt i) = int i pprImm (ImmInteger i) = integer i pprImm (ImmCLbl l) = ppr l pprImm (ImmIndex l i) = ppr l <> char '+' <> int i pprImm (ImmLit s) = s pprImm (ImmFloat _) = ptext (sLit "naughty float immediate") pprImm (ImmDouble _) = ptext (sLit "naughty double immediate") pprImm (ImmConstantSum a b) = pprImm a <> char '+' <> pprImm b pprImm (ImmConstantDiff a b) = pprImm a <> char '-' <> lparen <> pprImm b <> rparen pprImm (LO i) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then hcat [ text "lo16(", pprImm i, rparen ] else pprImm i <> text "@l" pprImm (HI i) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then hcat [ text "hi16(", pprImm i, rparen ] else pprImm i <> text "@h" pprImm (HA i) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then hcat [ text "ha16(", pprImm i, rparen ] else pprImm i <> text "@ha" pprImm (HIGHERA i) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then panic "PPC.pprImm: highera not implemented on Darwin" else pprImm i <> text "@highera" pprImm (HIGHESTA i) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then panic "PPC.pprImm: highesta not implemented on Darwin" else pprImm i <> text "@highesta" pprAddr :: AddrMode -> SDoc pprAddr (AddrRegReg r1 r2) = pprReg r1 <+> ptext (sLit ", ") <+> pprReg r2 pprAddr (AddrRegImm r1 (ImmInt i)) = hcat [ int i, char '(', pprReg r1, char ')' ] pprAddr (AddrRegImm r1 (ImmInteger i)) = hcat [ integer i, char '(', pprReg r1, char ')' ] pprAddr (AddrRegImm r1 imm) = hcat [ pprImm imm, char '(', pprReg r1, char ')' ] pprSectionHeader :: Section -> SDoc pprSectionHeader seg = sdocWithPlatform $ \platform -> let osDarwin = platformOS platform == OSDarwin ppc64 = not $ target32Bit platform in case seg of Text -> text ".text\n\t.align 2" Data | ppc64 -> text ".data\n.align 3" | otherwise -> text ".data\n.align 2" ReadOnlyData | osDarwin -> text ".const\n\t.align 2" | ppc64 -> text ".section .rodata\n\t.align 3" | otherwise -> text ".section .rodata\n\t.align 2" RelocatableReadOnlyData | osDarwin -> text ".const_data\n\t.align 2" | ppc64 -> text ".data\n\t.align 3" | otherwise -> text ".data\n\t.align 2" UninitialisedData | osDarwin -> text ".const_data\n\t.align 2" | ppc64 -> text ".section .bss\n\t.align 3" | otherwise -> text ".section .bss\n\t.align 2" ReadOnlyData16 | osDarwin -> text ".const\n\t.align 4" | otherwise -> text ".section .rodata\n\t.align 4" OtherSection _ -> panic "PprMach.pprSectionHeader: unknown section" pprDataItem :: CmmLit -> SDoc pprDataItem lit = sdocWithDynFlags $ \dflags -> vcat (ppr_item (cmmTypeFormat $ cmmLitType dflags lit) lit dflags) where imm = litToImm lit archPPC_64 dflags = not $ target32Bit $ targetPlatform dflags ppr_item II8 _ _ = [ptext (sLit "\t.byte\t") <> pprImm imm] ppr_item II32 _ _ = [ptext (sLit "\t.long\t") <> pprImm imm] ppr_item II64 _ dflags | archPPC_64 dflags = [ptext (sLit "\t.quad\t") <> pprImm imm] ppr_item FF32 (CmmFloat r _) _ = let bs = floatToBytes (fromRational r) in map (\b -> ptext (sLit "\t.byte\t") <> pprImm (ImmInt b)) bs ppr_item FF64 (CmmFloat r _) _ = let bs = doubleToBytes (fromRational r) in map (\b -> ptext (sLit "\t.byte\t") <> pprImm (ImmInt b)) bs ppr_item II16 _ _ = [ptext (sLit "\t.short\t") <> pprImm imm] ppr_item II64 (CmmInt x _) dflags | not(archPPC_64 dflags) = [ptext (sLit "\t.long\t") <> int (fromIntegral (fromIntegral (x `shiftR` 32) :: Word32)), ptext (sLit "\t.long\t") <> int (fromIntegral (fromIntegral x :: Word32))] ppr_item _ _ _ = panic "PPC.Ppr.pprDataItem: no match" pprInstr :: Instr -> SDoc pprInstr (COMMENT _) = empty -- nuke 'em {- pprInstr (COMMENT s) = if platformOS platform == OSLinux then ptext (sLit "# ") <> ftext s else ptext (sLit "; ") <> ftext s -} pprInstr (DELTA d) = pprInstr (COMMENT (mkFastString ("\tdelta = " ++ show d))) pprInstr (NEWBLOCK _) = panic "PprMach.pprInstr: NEWBLOCK" pprInstr (LDATA _ _) = panic "PprMach.pprInstr: LDATA" {- pprInstr (SPILL reg slot) = hcat [ ptext (sLit "\tSPILL"), char '\t', pprReg reg, comma, ptext (sLit "SLOT") <> parens (int slot)] pprInstr (RELOAD slot reg) = hcat [ ptext (sLit "\tRELOAD"), char '\t', ptext (sLit "SLOT") <> parens (int slot), comma, pprReg reg] -} pprInstr (LD fmt reg addr) = hcat [ char '\t', ptext (sLit "l"), ptext (case fmt of II8 -> sLit "bz" II16 -> sLit "hz" II32 -> sLit "wz" II64 -> sLit "d" FF32 -> sLit "fs" FF64 -> sLit "fd" _ -> panic "PPC.Ppr.pprInstr: no match" ), case addr of AddrRegImm _ _ -> empty AddrRegReg _ _ -> char 'x', char '\t', pprReg reg, ptext (sLit ", "), pprAddr addr ] pprInstr (LDFAR fmt reg (AddrRegImm source off)) = sdocWithPlatform $ \platform -> vcat [ pprInstr (ADDIS (tmpReg platform) source (HA off)), pprInstr (LD fmt reg (AddrRegImm (tmpReg platform) (LO off))) ] pprInstr (LDFAR _ _ _) = panic "PPC.Ppr.pprInstr LDFAR: no match" pprInstr (LA fmt reg addr) = hcat [ char '\t', ptext (sLit "l"), ptext (case fmt of II8 -> sLit "ba" II16 -> sLit "ha" II32 -> sLit "wa" II64 -> sLit "d" FF32 -> sLit "fs" FF64 -> sLit "fd" _ -> panic "PPC.Ppr.pprInstr: no match" ), case addr of AddrRegImm _ _ -> empty AddrRegReg _ _ -> char 'x', char '\t', pprReg reg, ptext (sLit ", "), pprAddr addr ] pprInstr (ST fmt reg addr) = hcat [ char '\t', ptext (sLit "st"), pprFormat fmt, case addr of AddrRegImm _ _ -> empty AddrRegReg _ _ -> char 'x', char '\t', pprReg reg, ptext (sLit ", "), pprAddr addr ] pprInstr (STFAR fmt reg (AddrRegImm source off)) = sdocWithPlatform $ \platform -> vcat [ pprInstr (ADDIS (tmpReg platform) source (HA off)), pprInstr (ST fmt reg (AddrRegImm (tmpReg platform) (LO off))) ] pprInstr (STFAR _ _ _) = panic "PPC.Ppr.pprInstr STFAR: no match" pprInstr (STU fmt reg addr) = hcat [ char '\t', ptext (sLit "st"), pprFormat fmt, ptext (sLit "u\t"), case addr of AddrRegImm _ _ -> empty AddrRegReg _ _ -> char 'x', pprReg reg, ptext (sLit ", "), pprAddr addr ] pprInstr (LIS reg imm) = hcat [ char '\t', ptext (sLit "lis"), char '\t', pprReg reg, ptext (sLit ", "), pprImm imm ] pprInstr (LI reg imm) = hcat [ char '\t', ptext (sLit "li"), char '\t', pprReg reg, ptext (sLit ", "), pprImm imm ] pprInstr (MR reg1 reg2) | reg1 == reg2 = empty | otherwise = hcat [ char '\t', sdocWithPlatform $ \platform -> case targetClassOfReg platform reg1 of RcInteger -> ptext (sLit "mr") _ -> ptext (sLit "fmr"), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2 ] pprInstr (CMP fmt reg ri) = hcat [ char '\t', op, char '\t', pprReg reg, ptext (sLit ", "), pprRI ri ] where op = hcat [ ptext (sLit "cmp"), pprFormat fmt, case ri of RIReg _ -> empty RIImm _ -> char 'i' ] pprInstr (CMPL fmt reg ri) = hcat [ char '\t', op, char '\t', pprReg reg, ptext (sLit ", "), pprRI ri ] where op = hcat [ ptext (sLit "cmpl"), pprFormat fmt, case ri of RIReg _ -> empty RIImm _ -> char 'i' ] pprInstr (BCC cond blockid) = hcat [ char '\t', ptext (sLit "b"), pprCond cond, char '\t', ppr lbl ] where lbl = mkAsmTempLabel (getUnique blockid) pprInstr (BCCFAR cond blockid) = vcat [ hcat [ ptext (sLit "\tb"), pprCond (condNegate cond), ptext (sLit "\t$+8") ], hcat [ ptext (sLit "\tb\t"), ppr lbl ] ] where lbl = mkAsmTempLabel (getUnique blockid) pprInstr (JMP lbl) = hcat [ -- an alias for b that takes a CLabel char '\t', ptext (sLit "b"), char '\t', ppr lbl ] pprInstr (MTCTR reg) = hcat [ char '\t', ptext (sLit "mtctr"), char '\t', pprReg reg ] pprInstr (BCTR _ _) = hcat [ char '\t', ptext (sLit "bctr") ] pprInstr (BL lbl _) = hcat [ ptext (sLit "\tbl\t"), ppr lbl ] pprInstr (BCTRL _) = hcat [ char '\t', ptext (sLit "bctrl") ] pprInstr (ADD reg1 reg2 ri) = pprLogic (sLit "add") reg1 reg2 ri pprInstr (ADDI reg1 reg2 imm) = hcat [ char '\t', ptext (sLit "addi"), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprImm imm ] pprInstr (ADDIS reg1 reg2 imm) = hcat [ char '\t', ptext (sLit "addis"), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprImm imm ] pprInstr (ADDC reg1 reg2 reg3) = pprLogic (sLit "addc") reg1 reg2 (RIReg reg3) pprInstr (ADDE reg1 reg2 reg3) = pprLogic (sLit "adde") reg1 reg2 (RIReg reg3) pprInstr (SUBF reg1 reg2 reg3) = pprLogic (sLit "subf") reg1 reg2 (RIReg reg3) pprInstr (SUBFC reg1 reg2 reg3) = pprLogic (sLit "subfc") reg1 reg2 (RIReg reg3) pprInstr (SUBFE reg1 reg2 reg3) = pprLogic (sLit "subfe") reg1 reg2 (RIReg reg3) pprInstr (MULLD reg1 reg2 ri@(RIReg _)) = pprLogic (sLit "mulld") reg1 reg2 ri pprInstr (MULLW reg1 reg2 ri@(RIReg _)) = pprLogic (sLit "mullw") reg1 reg2 ri pprInstr (MULLD reg1 reg2 ri@(RIImm _)) = pprLogic (sLit "mull") reg1 reg2 ri pprInstr (MULLW reg1 reg2 ri@(RIImm _)) = pprLogic (sLit "mull") reg1 reg2 ri pprInstr (DIVW reg1 reg2 reg3) = pprLogic (sLit "divw") reg1 reg2 (RIReg reg3) pprInstr (DIVD reg1 reg2 reg3) = pprLogic (sLit "divd") reg1 reg2 (RIReg reg3) pprInstr (DIVWU reg1 reg2 reg3) = pprLogic (sLit "divwu") reg1 reg2 (RIReg reg3) pprInstr (DIVDU reg1 reg2 reg3) = pprLogic (sLit "divdu") reg1 reg2 (RIReg reg3) pprInstr (MULLW_MayOflo reg1 reg2 reg3) = vcat [ hcat [ ptext (sLit "\tmullwo\t"), pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprReg reg3 ], hcat [ ptext (sLit "\tmfxer\t"), pprReg reg1 ], hcat [ ptext (sLit "\trlwinm\t"), pprReg reg1, ptext (sLit ", "), pprReg reg1, ptext (sLit ", "), ptext (sLit "2, 31, 31") ] ] pprInstr (MULLD_MayOflo reg1 reg2 reg3) = vcat [ hcat [ ptext (sLit "\tmulldo\t"), pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprReg reg3 ], hcat [ ptext (sLit "\tmfxer\t"), pprReg reg1 ], hcat [ ptext (sLit "\trlwinm\t"), pprReg reg1, ptext (sLit ", "), pprReg reg1, ptext (sLit ", "), ptext (sLit "2, 31, 31") ] ] -- for some reason, "andi" doesn't exist. -- we'll use "andi." instead. pprInstr (AND reg1 reg2 (RIImm imm)) = hcat [ char '\t', ptext (sLit "andi."), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprImm imm ] pprInstr (AND reg1 reg2 ri) = pprLogic (sLit "and") reg1 reg2 ri pprInstr (OR reg1 reg2 ri) = pprLogic (sLit "or") reg1 reg2 ri pprInstr (XOR reg1 reg2 ri) = pprLogic (sLit "xor") reg1 reg2 ri pprInstr (ORIS reg1 reg2 imm) = hcat [ char '\t', ptext (sLit "oris"), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprImm imm ] pprInstr (XORIS reg1 reg2 imm) = hcat [ char '\t', ptext (sLit "xoris"), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprImm imm ] pprInstr (EXTS fmt reg1 reg2) = hcat [ char '\t', ptext (sLit "exts"), pprFormat fmt, char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2 ] pprInstr (NEG reg1 reg2) = pprUnary (sLit "neg") reg1 reg2 pprInstr (NOT reg1 reg2) = pprUnary (sLit "not") reg1 reg2 pprInstr (SL fmt reg1 reg2 ri) = let op = case fmt of II32 -> "slw" II64 -> "sld" _ -> panic "PPC.Ppr.pprInstr: shift illegal size" in pprLogic (sLit op) reg1 reg2 (limitShiftRI fmt ri) pprInstr (SR II32 reg1 reg2 (RIImm (ImmInt i))) | i > 31 || i < 0 = -- Handle the case where we are asked to shift a 32 bit register by -- less than zero or more than 31 bits. We convert this into a clear -- of the destination register. -- Fixes ticket http://ghc.haskell.org/trac/ghc/ticket/5900 pprInstr (XOR reg1 reg2 (RIReg reg2)) pprInstr (SR fmt reg1 reg2 ri) = let op = case fmt of II32 -> "srw" II64 -> "srd" _ -> panic "PPC.Ppr.pprInstr: shift illegal size" in pprLogic (sLit op) reg1 reg2 (limitShiftRI fmt ri) pprInstr (SRA fmt reg1 reg2 ri) = let op = case fmt of II32 -> "sraw" II64 -> "srad" _ -> panic "PPC.Ppr.pprInstr: shift illegal size" in pprLogic (sLit op) reg1 reg2 (limitShiftRI fmt ri) pprInstr (RLWINM reg1 reg2 sh mb me) = hcat [ ptext (sLit "\trlwinm\t"), pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), int sh, ptext (sLit ", "), int mb, ptext (sLit ", "), int me ] pprInstr (FADD fmt reg1 reg2 reg3) = pprBinaryF (sLit "fadd") fmt reg1 reg2 reg3 pprInstr (FSUB fmt reg1 reg2 reg3) = pprBinaryF (sLit "fsub") fmt reg1 reg2 reg3 pprInstr (FMUL fmt reg1 reg2 reg3) = pprBinaryF (sLit "fmul") fmt reg1 reg2 reg3 pprInstr (FDIV fmt reg1 reg2 reg3) = pprBinaryF (sLit "fdiv") fmt reg1 reg2 reg3 pprInstr (FNEG reg1 reg2) = pprUnary (sLit "fneg") reg1 reg2 pprInstr (FCMP reg1 reg2) = hcat [ char '\t', ptext (sLit "fcmpu\tcr0, "), -- Note: we're using fcmpu, not fcmpo -- The difference is with fcmpo, compare with NaN is an invalid operation. -- We don't handle invalid fp ops, so we don't care pprReg reg1, ptext (sLit ", "), pprReg reg2 ] pprInstr (FCTIWZ reg1 reg2) = pprUnary (sLit "fctiwz") reg1 reg2 pprInstr (FCTIDZ reg1 reg2) = pprUnary (sLit "fctidz") reg1 reg2 pprInstr (FCFID reg1 reg2) = pprUnary (sLit "fcfid") reg1 reg2 pprInstr (FRSP reg1 reg2) = pprUnary (sLit "frsp") reg1 reg2 pprInstr (CRNOR dst src1 src2) = hcat [ ptext (sLit "\tcrnor\t"), int dst, ptext (sLit ", "), int src1, ptext (sLit ", "), int src2 ] pprInstr (MFCR reg) = hcat [ char '\t', ptext (sLit "mfcr"), char '\t', pprReg reg ] pprInstr (MFLR reg) = hcat [ char '\t', ptext (sLit "mflr"), char '\t', pprReg reg ] pprInstr (FETCHPC reg) = vcat [ ptext (sLit "\tbcl\t20,31,1f"), hcat [ ptext (sLit "1:\tmflr\t"), pprReg reg ] ] pprInstr (FETCHTOC reg lab) = vcat [ hcat [ ptext (sLit "0:\taddis\t"), pprReg reg, ptext (sLit ",12,.TOC.-0b@ha") ], hcat [ ptext (sLit "\taddi\t"), pprReg reg, char ',', pprReg reg, ptext (sLit ",.TOC.-0b@l") ], hcat [ ptext (sLit "\t.localentry\t"), ppr lab, ptext (sLit ",.-"), ppr lab] ] pprInstr LWSYNC = ptext (sLit "\tlwsync") pprInstr NOP = ptext (sLit "\tnop") pprInstr (UPDATE_SP fmt amount@(ImmInt offset)) | fits16Bits offset = vcat [ pprInstr (LD fmt r0 (AddrRegImm sp (ImmInt 0))), pprInstr (STU fmt r0 (AddrRegImm sp amount)) ] pprInstr (UPDATE_SP fmt amount) = sdocWithPlatform $ \platform -> let tmp = tmpReg platform in vcat [ pprInstr (LD fmt r0 (AddrRegImm sp (ImmInt 0))), pprInstr (ADDIS tmp sp (HA amount)), pprInstr (ADD tmp tmp (RIImm (LO amount))), pprInstr (STU fmt r0 (AddrRegReg sp tmp)) ] -- pprInstr _ = panic "pprInstr (ppc)" pprLogic :: LitString -> Reg -> Reg -> RI -> SDoc pprLogic op reg1 reg2 ri = hcat [ char '\t', ptext op, case ri of RIReg _ -> empty RIImm _ -> char 'i', char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprRI ri ] pprUnary :: LitString -> Reg -> Reg -> SDoc pprUnary op reg1 reg2 = hcat [ char '\t', ptext op, char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2 ] pprBinaryF :: LitString -> Format -> Reg -> Reg -> Reg -> SDoc pprBinaryF op fmt reg1 reg2 reg3 = hcat [ char '\t', ptext op, pprFFormat fmt, char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprReg reg3 ] pprRI :: RI -> SDoc pprRI (RIReg r) = pprReg r pprRI (RIImm r) = pprImm r pprFFormat :: Format -> SDoc pprFFormat FF64 = empty pprFFormat FF32 = char 's' pprFFormat _ = panic "PPC.Ppr.pprFFormat: no match" -- limit immediate argument for shift instruction to range 0..63 -- for 64 bit size and 0..32 otherwise limitShiftRI :: Format -> RI -> RI limitShiftRI II64 (RIImm (ImmInt i)) | i > 63 || i < 0 = panic $ "PPC.Ppr: Shift by " ++ show i ++ " bits is not allowed." limitShiftRI II32 (RIImm (ImmInt i)) | i > 31 || i < 0 = panic $ "PPC.Ppr: 32 bit: Shift by " ++ show i ++ " bits is not allowed." limitShiftRI _ x = x
ml9951/ghc
compiler/nativeGen/PPC/Ppr.hs
bsd-3-clause
28,362
0
22
10,248
9,219
4,511
4,708
681
72
module Stars where import Rumpus -- Golden Section Spiral (via http://www.softimageblog.com/archives/115) pointsOnSphere :: Int -> [V3 GLfloat] pointsOnSphere (fromIntegral -> n) = map (\k -> let y = k * off - 1 + (off / 2) r = sqrt (1 - y*y) phi = k * inc in V3 (cos phi * r) y (sin phi * r) ) [0..n] where inc = pi * (3 - sqrt 5) off = 2 / n start :: Start start = do -- We only take half the request points to get the upper hemisphere let numPoints = 400 :: Int points = reverse $ drop (numPoints `div` 2) $ pointsOnSphere numPoints hues = map ((/ fromIntegral numPoints) . fromIntegral) [0..numPoints] forM_ (zip3 [0..] points hues) $ \(i, pos, hue) -> spawnChild $ do myTransformType ==> AbsolutePose myShape ==> Sphere mySize ==> 0.001 myColor ==> colorHSL hue 0.8 0.8 myPose ==> position (pos * 500) myStart ==> do setDelayedAction (fromIntegral i * 0.05) $ setSize 5 myUpdate ==> do now <- (fromIntegral i +) <$> getNow let offset = V3 (sin now * 50) 0 0 setColor (colorHSL (now*0.5) 0.8 0.5) setPosition (offset + pos * 500)
lukexi/rumpus
pristine/Intro/Stars.hs
bsd-3-clause
1,339
0
21
501
465
236
229
-1
-1
module RevealHs.Sample.Env where import Data.Time.Clock import Data.Time.Format import Data.Time.LocalTime today :: IO String today = do tz <- getCurrentTimeZone t <- fmap (utcToLocalTime tz) getCurrentTime return $ formatTime defaultTimeLocale (iso8601DateFormat Nothing) t
KenetJervet/reveal-hs
app/RevealHs/Sample/Env.hs
bsd-3-clause
313
0
10
70
83
44
39
9
1
{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving #-} module Math.InfoRetrieval.TFIDF ( Document(..) , Term(..) , Corpus , emptyCorpus , addDocument , removeDocument , FreqScaling(..) , tfidf , search ) where import Control.Lens import Data.Function (on) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as M import Data.HashSet (HashSet) import qualified Data.HashSet as S import Data.Hashable import Data.List import Data.Monoid import qualified Data.Text as T import Data.String (IsString) type Score = Double newtype Document = Doc Int deriving (Show, Eq, Hashable) newtype Term = Term T.Text deriving (Show, Eq, Hashable, IsString) data Corpus = Corpus { _cDocuments :: HashSet Document , _cTerms :: HashMap Term (HashMap Document Int) } makeLenses ''Corpus emptyCorpus :: Corpus emptyCorpus = Corpus S.empty M.empty addDocument :: Document -> [Term] -> Corpus -> Corpus addDocument d ts c = addDocument' d ts' c where ts' = foldl' (flip $ \t->M.insertWith (+) t 1) M.empty ts addDocument' :: Document -> HashMap Term Int -> Corpus -> Corpus addDocument' d ts c = cDocuments %~ S.insert d $ M.foldlWithKey' (\c term n->cTerms %~ M.insertWith (<>) term (M.singleton d n) $ c) c ts removeDocument :: Document -> Corpus -> Corpus removeDocument d = (cDocuments %~ S.delete d) . (cTerms %~ M.map (M.delete d)) idf :: Corpus -> Term -> Double idf c t = log $ docs / docsWithTerm where docs = realToFrac $ views cDocuments S.size c docsWithTerm = realToFrac $ M.size $ M.lookupDefault M.empty t (c^.cTerms) data FreqScaling = BoolScaling | LogScaling | LinearScaling | NormedScaling tf :: FreqScaling -> Corpus -> Term -> Document -> Score tf LinearScaling c t d = realToFrac $ M.lookupDefault 0 d $ M.lookupDefault M.empty t (c^.cTerms) tf LogScaling c t d = log $ tf LinearScaling c t d tf BoolScaling c t d = if tf LinearScaling c t d > 0 then 1 else 0 tfidf :: FreqScaling -> Corpus -> Term -> Document -> Score tfidf scaling c t d = tf scaling c t d * idf c t search :: FreqScaling -> Corpus -> Term -> [(Document, Score)] search scaling c t = sortBy (flip (compare `on` snd)) $ map (\d->(d, tfidf scaling c t d)) $ views cDocuments S.toList c
bgamari/tf-idf
Math/InfoRetrieval/TFIDF.hs
bsd-3-clause
2,526
0
14
707
871
472
399
60
2
{-| Module : Numeric.AERN.RealArithmetic.RefinementOrderRounding.Operators Description : convenience operators and functions with default effort Description : re-export of parent's operators for easier direct import Copyright : (c) Michal Konecny License : BSD3 Maintainer : [email protected] Stability : experimental Portability : portable Re-export of operators from the parent module for easier direct import. -} module Numeric.AERN.RealArithmetic.RefinementOrderRounding.Operators ( (>+<), (<+>), (>-<), (<->), (>*<), (<*>), (>/<), (</>), -- (>/+<), (</+>), (/+), (>^<), (<^>), (|>+<), (|<+>), (|+), (>+<|), (<+>|), (+|), (|>*<), (|<*>), (|*), (>*<|), (<*>|), (*|), (>/<|), (</>|), (/|) ) where import Numeric.AERN.RealArithmetic.RefinementOrderRounding
michalkonecny/aern
aern-real/src/Numeric/AERN/RealArithmetic/RefinementOrderRounding/Operators.hs
bsd-3-clause
862
0
4
189
145
115
30
9
0
import Language.Haskell.Exts.Parser import Language.Haskell.Exts.Syntax import System.FilePath import System.Directory import Control.Monad import Data.Maybe import Data.List import Control.Applicative import Data.GraphViz.Types.Graph import Data.GraphViz.Commands.IO import Data.GraphViz.Types.Canonical import Data.Text.Lazy (pack) relations :: Module -> (ModuleName, [ModuleName]) relations (Module _ name _ _ _ imports _) = (name, map importModule imports) findHsFiles :: String -> IO [String] findHsFiles path = do allFiles <- getDirectoryContents path let files = map (path </>) $ filter (flip notElem $ [".", ".."]) allFiles let hsFiles = filter (\x -> takeExtension x == ".hs") files directories <- filterM doesDirectoryExist files ((hsFiles ++) . concat) <$> mapM findHsFiles directories relationsFrom :: FilePath -> IO (Maybe (ModuleName, [ModuleName])) relationsFrom fileName = do src <- readFile fileName -- (parseFileWithMode (defaultParseMode { fixities = [] } ) case parseModuleWithMode (defaultParseMode { fixities = Just [] }) src of ParseOk parsed -> return $ Just (relations parsed) ParseFailed _ _ -> return Nothing --mkGraph nodes edges namesFromModules :: [ModuleName] -> [String] namesFromModules ((ModuleName name) : t) = [name] ++ namesFromModules t namesFromModules _ = [] nodesFromRelations :: [(ModuleName, [ModuleName])] -> [String] nodesFromRelations ((ModuleName name, imports) : t) = [name] ++ namesFromModules imports ++ nodesFromRelations t nodesFromRelations _ = [] edgesFromRelation :: (ModuleName, [ModuleName]) -> [(String, String)] edgesFromRelation (ModuleName name, imports) = zip (repeat name) (namesFromModules imports) edgesFromRelations :: [(ModuleName, [ModuleName])] -> [(String, String)] edgesFromRelations (h : t) = (edgesFromRelation h) ++ edgesFromRelations t edgesFromRelations _ = [] dotNodes :: [String] -> [DotNode String] dotNodes nodes = map (\nodeName -> DotNode nodeName []) nodes dotEdges :: [(String, String)] -> [DotEdge String] dotEdges edges = map (\(a, b) -> DotEdge a b []) edges main :: IO() main = do files <- findHsFiles "." maybeRelations <- mapM relationsFrom files let found = catMaybes maybeRelations let nodes = sort $ nub $ nodesFromRelations $ found let edges = sort $ nub $ edgesFromRelations $ found let graph = DotGraph False True (Just (Str (pack "h2dot"))) (DotStmts [] [] (dotNodes nodes) (dotEdges edges)) writeDotFile "hs2dot.dot" graph
bneijt/hs2dot
src/main/Main.hs
bsd-3-clause
2,509
0
16
414
910
479
431
51
2
{-# LANGUAGE CPP #-} module Database.PostgreSQL.PQTypes.Internal.Monad ( DBT_(..) , DBT , runDBT , mapDBT ) where import Control.Applicative import Control.Concurrent.MVar import Control.Monad.Base import Control.Monad.Catch import Control.Monad.Error.Class import Control.Monad.Reader.Class import Control.Monad.State.Strict import Control.Monad.Trans.Control import Control.Monad.Writer.Class import qualified Control.Monad.Trans.State.Strict as S import qualified Control.Monad.Fail as MF import Database.PostgreSQL.PQTypes.Class import Database.PostgreSQL.PQTypes.Internal.Connection import Database.PostgreSQL.PQTypes.Internal.Error import Database.PostgreSQL.PQTypes.Internal.Notification import Database.PostgreSQL.PQTypes.Internal.Query import Database.PostgreSQL.PQTypes.Internal.State import Database.PostgreSQL.PQTypes.SQL import Database.PostgreSQL.PQTypes.SQL.Class import Database.PostgreSQL.PQTypes.Transaction import Database.PostgreSQL.PQTypes.Transaction.Settings import Database.PostgreSQL.PQTypes.Utils type InnerDBT m = StateT (DBState m) -- | Monad transformer for adding database -- interaction capabilities to the underlying monad. newtype DBT_ m n a = DBT { unDBT :: InnerDBT m n a } deriving (Alternative, Applicative, Functor, Monad, MF.MonadFail, MonadBase b, MonadCatch, MonadIO, MonadMask, MonadPlus, MonadThrow, MonadTrans) type DBT m = DBT_ m m -- | Evaluate monadic action with supplied -- connection source and transaction settings. {-# INLINABLE runDBT #-} runDBT :: (MonadBase IO m, MonadMask m) => ConnectionSourceM m -> TransactionSettings -> DBT m a -> m a runDBT cs ts m = withConnection cs $ \conn -> do evalStateT action $ DBState { dbConnection = conn , dbConnectionSource = cs , dbTransactionSettings = ts , dbLastQuery = SomeSQL (mempty::SQL) , dbRecordLastQuery = True , dbQueryResult = Nothing } where action = unDBT $ if tsAutoTransaction ts then withTransaction' (ts { tsAutoTransaction = False }) m else m -- | Transform the underlying monad. {-# INLINABLE mapDBT #-} mapDBT :: (DBState n -> DBState m) -> (m (a, DBState m) -> n (b, DBState n)) -> DBT m a -> DBT n b mapDBT f g m = DBT . StateT $ g . runStateT (unDBT m) . f ---------------------------------------- instance (m ~ n, MonadBase IO m, MonadMask m) => MonadDB (DBT_ m n) where runQuery sql = DBT . StateT $ liftBase . runQueryIO sql getLastQuery = DBT . gets $ dbLastQuery withFrozenLastQuery callback = DBT . StateT $ \st -> do let st' = st { dbRecordLastQuery = False } (x, st'') <- runStateT (unDBT callback) st' pure (x, st'' { dbRecordLastQuery = dbRecordLastQuery st }) getConnectionStats = do mconn <- DBT $ liftBase . readMVar =<< gets (unConnection . dbConnection) case mconn of Nothing -> throwDB $ HPQTypesError "getConnectionStats: no connection" Just cd -> return $ cdStats cd getQueryResult = DBT . gets $ \st -> dbQueryResult st clearQueryResult = DBT . modify $ \st -> st { dbQueryResult = Nothing } getTransactionSettings = DBT . gets $ dbTransactionSettings setTransactionSettings ts = DBT . modify $ \st -> st { dbTransactionSettings = ts } getNotification time = DBT . StateT $ \st -> (, st) <$> liftBase (getNotificationIO st time) withNewConnection m = DBT . StateT $ \st -> do let cs = dbConnectionSource st ts = dbTransactionSettings st res <- runDBT cs ts m return (res, st) {-# INLINABLE runQuery #-} {-# INLINABLE getLastQuery #-} {-# INLINABLE withFrozenLastQuery #-} {-# INLINABLE getConnectionStats #-} {-# INLINABLE getQueryResult #-} {-# INLINABLE clearQueryResult #-} {-# INLINABLE getTransactionSettings #-} {-# INLINABLE setTransactionSettings #-} {-# INLINABLE getNotification #-} {-# INLINABLE withNewConnection #-} ---------------------------------------- instance MonadTransControl (DBT_ m) where type StT (DBT_ m) a = StT (InnerDBT m) a liftWith = defaultLiftWith DBT unDBT restoreT = defaultRestoreT DBT {-# INLINE liftWith #-} {-# INLINE restoreT #-} instance (m ~ n, MonadBaseControl b m) => MonadBaseControl b (DBT_ m n) where type StM (DBT_ m n) a = ComposeSt (DBT_ m) m a liftBaseWith = defaultLiftBaseWith restoreM = defaultRestoreM {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance (m ~ n, MonadError e m) => MonadError e (DBT_ m n) where throwError = lift . throwError catchError m h = DBT $ S.liftCatch catchError (unDBT m) (unDBT . h) {-# INLINE throwError #-} {-# INLINE catchError #-} instance (m ~ n, MonadReader r m) => MonadReader r (DBT_ m n) where ask = lift ask local f = mapDBT id (local f) reader = lift . reader {-# INLINE ask #-} {-# INLINE local #-} {-# INLINE reader #-} instance (m ~ n, MonadState s m) => MonadState s (DBT_ m n) where get = lift get put = lift . put state = lift . state {-# INLINE get #-} {-# INLINE put #-} {-# INLINE state #-} instance (m ~ n, MonadWriter w m) => MonadWriter w (DBT_ m n) where writer = lift . writer tell = lift . tell listen = DBT . S.liftListen listen . unDBT pass = DBT . S.liftPass pass . unDBT {-# INLINE writer #-} {-# INLINE tell #-} {-# INLINE listen #-} {-# INLINE pass #-}
scrive/hpqtypes
src/Database/PostgreSQL/PQTypes/Internal/Monad.hs
bsd-3-clause
5,271
0
14
1,012
1,479
822
657
-1
-1
{-# LANGUAGE EmptyDataDecls, FlexibleContexts, FlexibleInstances, RankNTypes #-} {-# LANGUAGE TypeSynonymInstances, UndecidableInstances #-} module Main where import Data.Constraint.Unsafely import Data.Proxy class Semigroup a where -- | binary operation which satisifies associative law: -- @(a .+. b) .+. c == a .+. (b .+. c)@ (.+.) :: a -> a -> a infixl 6 .+. -- | 'Int', 'Integer' and 'Rational' satisfies associative law. instance Semigroup Int where (.+.) = (+) instance Semigroup Integer where (.+.) = (+) instance Semigroup Rational where (.+.) = (+) -- | Dummy type indicating the computation which may /unsafely/ violates associative law. data ViolateAssocLaw -- | Helper function to use /unsafe/ instance for @Semigroup@ unsafelyViolate :: (Unsafely ViolateAssocLaw => a) -> a unsafelyViolate = unsafely (Proxy :: Proxy ViolateAssocLaw) -- | 'Double' doesn't satsfies associative law: -- -- > (1.9546929672907305 + 2.0) + 0.14197132377740074 == 4.096664291068132 -- > 1.9546929672907305 + (2.0 + 0.14197132377740074) == 4.096664291068131 -- -- But sometimes there is the case the instance for @Semigroup@ for Double is required. -- So we use @Unsafely@ to mark this instance is somewhat unsafe. instance Unsafely ViolateAssocLaw => Semigroup Double where (.+.) = (+) main :: IO () main = do print (1 .+. 2 :: Int) unsafelyViolate $ print (3 .+. 4 :: Double) -- You cannot done as above, if you drop @unsafelyViolate@. -- Uncommenting following line causes type error. -- print (5 .+. 6 :: Double)
konn/unsafely
examples/semigroup.hs
bsd-3-clause
1,564
0
10
288
226
137
89
-1
-1
{- Author: George Karachalias <[email protected]> Haskell expressions (as used by the pattern matching checker) and utilities. -} {-# LANGUAGE CPP #-} module PmExpr ( PmExpr(..), PmLit(..), SimpleEq, ComplexEq, toComplex, eqPmLit, truePmExpr, falsePmExpr, isTruePmExpr, isFalsePmExpr, isNotPmExprOther, lhsExprToPmExpr, hsExprToPmExpr, substComplexEq, filterComplex, pprPmExprWithParens, runPmPprM ) where #include "HsVersions.h" import HsSyn import Id import Name import NameSet import DataCon import TysWiredIn import Outputable import Util import SrcLoc #if __GLASGOW_HASKELL__ < 709 import Data.Functor ((<$>)) #endif import Data.Maybe (mapMaybe) import Data.List (groupBy, sortBy, nubBy) import Control.Monad.Trans.State.Lazy {- %************************************************************************ %* * Lifted Expressions %* * %************************************************************************ -} {- Note [PmExprOther in PmExpr] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Since there is no plan to extend the (currently pretty naive) term oracle in the near future, instead of playing with the verbose (HsExpr Id), we lift it to PmExpr. All expressions the term oracle does not handle are wrapped by the constructor PmExprOther. Note that we do not perform substitution in PmExprOther. Because of this, we do not even print PmExprOther, since they may refer to variables that are otherwise substituted away. -} -- ---------------------------------------------------------------------------- -- ** Types -- | Lifted expressions for pattern match checking. data PmExpr = PmExprVar Name | PmExprCon DataCon [PmExpr] | PmExprLit PmLit | PmExprEq PmExpr PmExpr -- Syntactic equality | PmExprOther (HsExpr Id) -- Note [PmExprOther in PmExpr] -- | Literals (simple and overloaded ones) for pattern match checking. data PmLit = PmSLit HsLit -- simple | PmOLit Bool {- is it negated? -} (HsOverLit Id) -- overloaded -- | Equality between literals for pattern match checking. eqPmLit :: PmLit -> PmLit -> Bool eqPmLit (PmSLit l1) (PmSLit l2) = l1 == l2 eqPmLit (PmOLit b1 l1) (PmOLit b2 l2) = b1 == b2 && l1 == l2 -- See Note [Undecidable Equality for Overloaded Literals] eqPmLit _ _ = False {- Note [Undecidable Equality for Overloaded Literals] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Equality on overloaded literals is undecidable in the general case. Consider the following example: instance Num Bool where ... fromInteger 0 = False -- C-like representation of booleans fromInteger _ = True f :: Bool -> () f 1 = () -- Clause A f 2 = () -- Clause B Clause B is redundant but to detect this, we should be able to solve the constraint: False ~ (fromInteger 2 ~ fromInteger 1) which means that we have to look through function `fromInteger`, whose implementation could be anything. This poses difficulties for: 1. The expressive power of the check. We cannot expect a reasonable implementation of pattern matching to detect that fromInteger 2 ~ fromInteger 1 is True, unless we unfold function fromInteger. This puts termination at risk and is undecidable in the general case. 2. Performance. Having an unresolved constraint False ~ (fromInteger 2 ~ fromInteger 1) lying around could become expensive really fast. Ticket #11161 illustrates how heavy use of overloaded literals can generate plenty of those constraints, effectively undermining the term oracle's performance. 3. Error nessages/Warnings. What should our message for `f` above be? A reasonable approach would be to issue: Pattern matches are (potentially) redundant: f 2 = ... under the assumption that 1 == 2 but seems to complex and confusing for the user. We choose to treat overloaded literals that look different as different. The impact of this is the following: * Redundancy checking is rather conservative, since it cannot see that clause B above is redundant. * We have instant equality check for overloaded literals (we do not rely on the term oracle which is rather expensive, both in terms of performance and memory). This significantly improves the performance of functions `covered` `uncovered` and `divergent` in deSugar/Check.hs and effectively addresses #11161. * The warnings issued are simpler. * We do not play on the safe side, strictly speaking. The assumption that 1 /= 2 makes the redundancy check more conservative but at the same time makes its dual (exhaustiveness check) unsafe. This we can live with, mainly for two reasons: 1. At the moment we do not use the results of the check during compilation where this would be a disaster (could result in runtime errors even if our function was deemed exhaustive). 2. Pattern matcing on literals can never be considered exhaustive unless we have a catch-all clause. Hence, this assumption affects mainly the appearance of the warnings and is, in practice safe. -} nubPmLit :: [PmLit] -> [PmLit] nubPmLit = nubBy eqPmLit -- | Term equalities type SimpleEq = (Id, PmExpr) -- We always use this orientation type ComplexEq = (PmExpr, PmExpr) -- | Lift a `SimpleEq` to a `ComplexEq` toComplex :: SimpleEq -> ComplexEq toComplex (x,e) = (PmExprVar (idName x), e) -- | Expression `True' truePmExpr :: PmExpr truePmExpr = PmExprCon trueDataCon [] -- | Expression `False' falsePmExpr :: PmExpr falsePmExpr = PmExprCon falseDataCon [] -- ---------------------------------------------------------------------------- -- ** Predicates on PmExpr -- | Check if an expression is lifted or not isNotPmExprOther :: PmExpr -> Bool isNotPmExprOther (PmExprOther _) = False isNotPmExprOther _expr = True -- | Check whether a literal is negated isNegatedPmLit :: PmLit -> Bool isNegatedPmLit (PmOLit b _) = b isNegatedPmLit _other_lit = False -- | Check whether a PmExpr is syntactically equal to term `True'. isTruePmExpr :: PmExpr -> Bool isTruePmExpr (PmExprCon c []) = c == trueDataCon isTruePmExpr _other_expr = False -- | Check whether a PmExpr is syntactically equal to term `False'. isFalsePmExpr :: PmExpr -> Bool isFalsePmExpr (PmExprCon c []) = c == falseDataCon isFalsePmExpr _other_expr = False -- | Check whether a PmExpr is syntactically e isNilPmExpr :: PmExpr -> Bool isNilPmExpr (PmExprCon c _) = c == nilDataCon isNilPmExpr _other_expr = False -- | Check whether a PmExpr is syntactically equal to (x == y). -- Since (==) is overloaded and can have an arbitrary implementation, we use -- the PmExprEq constructor to represent only equalities with non-overloaded -- literals where it coincides with a syntactic equality check. isPmExprEq :: PmExpr -> Maybe (PmExpr, PmExpr) isPmExprEq (PmExprEq e1 e2) = Just (e1,e2) isPmExprEq _other_expr = Nothing -- | Check if a DataCon is (:). isConsDataCon :: DataCon -> Bool isConsDataCon con = consDataCon == con -- ---------------------------------------------------------------------------- -- ** Substitution in PmExpr -- | We return a boolean along with the expression. Hence, if substitution was -- a no-op, we know that the expression still cannot progress. substPmExpr :: Name -> PmExpr -> PmExpr -> (PmExpr, Bool) substPmExpr x e1 e = case e of PmExprVar z | x == z -> (e1, True) | otherwise -> (e, False) PmExprCon c ps -> let (ps', bs) = mapAndUnzip (substPmExpr x e1) ps in (PmExprCon c ps', or bs) PmExprEq ex ey -> let (ex', bx) = substPmExpr x e1 ex (ey', by) = substPmExpr x e1 ey in (PmExprEq ex' ey', bx || by) _other_expr -> (e, False) -- The rest are terminals (We silently ignore -- Other). See Note [PmExprOther in PmExpr] -- | Substitute in a complex equality. We return (Left eq) if the substitution -- affected the equality or (Right eq) if nothing happened. substComplexEq :: Name -> PmExpr -> ComplexEq -> Either ComplexEq ComplexEq substComplexEq x e (ex, ey) | bx || by = Left (ex', ey') | otherwise = Right (ex', ey') where (ex', bx) = substPmExpr x e ex (ey', by) = substPmExpr x e ey -- ----------------------------------------------------------------------- -- ** Lift source expressions (HsExpr Id) to PmExpr lhsExprToPmExpr :: LHsExpr Id -> PmExpr lhsExprToPmExpr (L _ e) = hsExprToPmExpr e hsExprToPmExpr :: HsExpr Id -> PmExpr hsExprToPmExpr (HsVar x) = PmExprVar (idName (unLoc x)) hsExprToPmExpr (HsOverLit olit) = PmExprLit (PmOLit False olit) hsExprToPmExpr (HsLit lit) = PmExprLit (PmSLit lit) hsExprToPmExpr e@(NegApp _ neg_e) | PmExprLit (PmOLit False ol) <- synExprToPmExpr neg_e = PmExprLit (PmOLit True ol) | otherwise = PmExprOther e hsExprToPmExpr (HsPar (L _ e)) = hsExprToPmExpr e hsExprToPmExpr e@(ExplicitTuple ps boxity) | all tupArgPresent ps = PmExprCon tuple_con tuple_args | otherwise = PmExprOther e where tuple_con = tupleDataCon boxity (length ps) tuple_args = [ lhsExprToPmExpr e | L _ (Present e) <- ps ] hsExprToPmExpr e@(ExplicitList _elem_ty mb_ol elems) | Nothing <- mb_ol = foldr cons nil (map lhsExprToPmExpr elems) | otherwise = PmExprOther e {- overloaded list: No PmExprApp -} where cons x xs = PmExprCon consDataCon [x,xs] nil = PmExprCon nilDataCon [] hsExprToPmExpr (ExplicitPArr _elem_ty elems) = PmExprCon (parrFakeCon (length elems)) (map lhsExprToPmExpr elems) -- we want this but we would have to make evrything monadic :/ -- ./compiler/deSugar/DsMonad.hs:397:dsLookupDataCon :: Name -> DsM DataCon -- -- hsExprToPmExpr (RecordCon c _ binds) = do -- con <- dsLookupDataCon (unLoc c) -- args <- mapM lhsExprToPmExpr (hsRecFieldsArgs binds) -- return (PmExprCon con args) hsExprToPmExpr e@(RecordCon _ _ _ _) = PmExprOther e hsExprToPmExpr (HsTick _ e) = lhsExprToPmExpr e hsExprToPmExpr (HsBinTick _ _ e) = lhsExprToPmExpr e hsExprToPmExpr (HsTickPragma _ _ _ e) = lhsExprToPmExpr e hsExprToPmExpr (HsSCC _ _ e) = lhsExprToPmExpr e hsExprToPmExpr (HsCoreAnn _ _ e) = lhsExprToPmExpr e hsExprToPmExpr (ExprWithTySig e _) = lhsExprToPmExpr e hsExprToPmExpr (ExprWithTySigOut e _) = lhsExprToPmExpr e hsExprToPmExpr (HsWrap _ e) = hsExprToPmExpr e hsExprToPmExpr e = PmExprOther e -- the rest are not handled by the oracle synExprToPmExpr :: SyntaxExpr Id -> PmExpr synExprToPmExpr = hsExprToPmExpr . syn_expr -- ignore the wrappers {- %************************************************************************ %* * Pretty printing %* * %************************************************************************ -} {- 1. Literals ~~~~~~~~~~~~~~ Starting with a function definition like: f :: Int -> Bool f 5 = True f 6 = True The uncovered set looks like: { var |> False == (var == 5), False == (var == 6) } Yet, we would like to print this nicely as follows: x , where x not one of {5,6} Function `filterComplex' takes the set of residual constraints and packs together the negative constraints that refer to the same variable so we can do just this. Since these variables will be shown to the programmer, we also give them better names (t1, t2, ..), hence the SDoc in PmNegLitCt. 2. Residual Constraints ~~~~~~~~~~~~~~~~~~~~~~~ Unhandled constraints that refer to HsExpr are typically ignored by the solver (it does not even substitute in HsExpr so they are even printed as wildcards). Additionally, the oracle returns a substitution if it succeeds so we apply this substitution to the vectors before printing them out (see function `pprOne' in Check.hs) to be more precice. -} -- ----------------------------------------------------------------------------- -- ** Transform residual constraints in appropriate form for pretty printing type PmNegLitCt = (Name, (SDoc, [PmLit])) filterComplex :: [ComplexEq] -> [PmNegLitCt] filterComplex = zipWith rename nameList . map mkGroup . groupBy name . sortBy order . mapMaybe isNegLitCs where order x y = compare (fst x) (fst y) name x y = fst x == fst y mkGroup l = (fst (head l), nubPmLit $ map snd l) rename new (old, lits) = (old, (new, lits)) isNegLitCs (e1,e2) | isFalsePmExpr e1, Just (x,y) <- isPmExprEq e2 = isNegLitCs' x y | isFalsePmExpr e2, Just (x,y) <- isPmExprEq e1 = isNegLitCs' x y | otherwise = Nothing isNegLitCs' (PmExprVar x) (PmExprLit l) = Just (x, l) isNegLitCs' (PmExprLit l) (PmExprVar x) = Just (x, l) isNegLitCs' _ _ = Nothing -- Try nice names p,q,r,s,t before using the (ugly) t_i nameList :: [SDoc] nameList = map text ["p","q","r","s","t"] ++ [ text ('t':show u) | u <- [(0 :: Int)..] ] -- ---------------------------------------------------------------------------- runPmPprM :: PmPprM a -> [PmNegLitCt] -> (a, [(SDoc,[PmLit])]) runPmPprM m lit_env = (result, mapMaybe is_used lit_env) where (result, (_lit_env, used)) = runState m (lit_env, emptyNameSet) is_used (x,(name, lits)) | elemNameSet x used = Just (name, lits) | otherwise = Nothing type PmPprM a = State ([PmNegLitCt], NameSet) a -- (the first part of the state is read only. make it a reader?) addUsed :: Name -> PmPprM () addUsed x = modify (\(negated, used) -> (negated, extendNameSet used x)) checkNegation :: Name -> PmPprM (Maybe SDoc) -- the clean name if it is negated checkNegation x = do negated <- gets fst return $ case lookup x negated of Just (new, _) -> Just new Nothing -> Nothing -- | Pretty print a pmexpr, but remember to prettify the names of the variables -- that refer to neg-literals. The ones that cannot be shown are printed as -- underscores. pprPmExpr :: PmExpr -> PmPprM SDoc pprPmExpr (PmExprVar x) = do mb_name <- checkNegation x case mb_name of Just name -> addUsed x >> return name Nothing -> return underscore pprPmExpr (PmExprCon con args) = pprPmExprCon con args pprPmExpr (PmExprLit l) = return (ppr l) pprPmExpr (PmExprEq _ _) = return underscore -- don't show pprPmExpr (PmExprOther _) = return underscore -- don't show needsParens :: PmExpr -> Bool needsParens (PmExprVar {}) = False needsParens (PmExprLit l) = isNegatedPmLit l needsParens (PmExprEq {}) = False -- will become a wildcard needsParens (PmExprOther {}) = False -- will become a wildcard needsParens (PmExprCon c es) | isTupleDataCon c || isPArrFakeCon c || isConsDataCon c || null es = False | otherwise = True pprPmExprWithParens :: PmExpr -> PmPprM SDoc pprPmExprWithParens expr | needsParens expr = parens <$> pprPmExpr expr | otherwise = pprPmExpr expr pprPmExprCon :: DataCon -> [PmExpr] -> PmPprM SDoc pprPmExprCon con args | isTupleDataCon con = mkTuple <$> mapM pprPmExpr args | isPArrFakeCon con = mkPArr <$> mapM pprPmExpr args | isConsDataCon con = pretty_list | dataConIsInfix con = case args of [x, y] -> do x' <- pprPmExprWithParens x y' <- pprPmExprWithParens y return (x' <+> ppr con <+> y') -- can it be infix but have more than two arguments? list -> pprPanic "pprPmExprCon:" (ppr list) | null args = return (ppr con) | otherwise = do args' <- mapM pprPmExprWithParens args return (fsep (ppr con : args')) where mkTuple, mkPArr :: [SDoc] -> SDoc mkTuple = parens . fsep . punctuate comma mkPArr = paBrackets . fsep . punctuate comma -- lazily, to be used in the list case only pretty_list :: PmPprM SDoc pretty_list = case isNilPmExpr (last list) of True -> brackets . fsep . punctuate comma <$> mapM pprPmExpr (init list) False -> parens . hcat . punctuate colon <$> mapM pprPmExpr list list = list_elements args list_elements [x,y] | PmExprCon c es <- y, nilDataCon == c = ASSERT(null es) [x,y] | PmExprCon c es <- y, consDataCon == c = x : list_elements es | otherwise = [x,y] list_elements list = pprPanic "list_elements:" (ppr list) instance Outputable PmLit where ppr (PmSLit l) = pmPprHsLit l ppr (PmOLit neg l) = (if neg then char '-' else empty) <> ppr l -- not really useful for pmexprs per se instance Outputable PmExpr where ppr e = fst $ runPmPprM (pprPmExpr e) []
GaloisInc/halvm-ghc
compiler/deSugar/PmExpr.hs
bsd-3-clause
16,939
0
15
3,946
3,341
1,730
1,611
199
4
{-# LANGUAGE CPP #-} -- | Contains commons utilities when defining your own widget module Glazier.React.ReactDOM ( renderDOM ) where import Glazier.React.ReactElement import qualified JS.DOM.EventTarget.Node.Element as DOM -- | Using a React Element (first arg) give React rendering control over a DOM element (second arg). -- This should only be called for the topmost component. renderDOM :: ReactElement -> DOM.Element -> IO () renderDOM = js_render #ifdef __GHCJS__ foreign import javascript unsafe "hgr$ReactDOM().render($1, $2);" js_render :: ReactElement -> DOM.Element -> IO () #else js_render :: ReactElement -> DOM.Element -> IO () js_render _ _ = pure () #endif
louispan/glazier-react
src/Glazier/React/ReactDOM.hs
bsd-3-clause
689
5
9
114
91
56
35
9
1
-- | This module supplies the types that are used in interacting with -- and parsing from the database. module Database.Influx.Types ( module Database.Influx.Types.Core , module Database.Influx.Types.FromInfluxPoint ) where import Database.Influx.Types.Core import Database.Influx.Types.FromInfluxPoint
factisresearch/influx
src/Database/Influx/Types.hs
bsd-3-clause
316
0
5
46
41
30
11
5
0
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE UnicodeSyntax #-} {-| [@ISO639-1@] fi [@ISO639-2B@] fin [@ISO639-3@] fin [@Native name@] suomi [@English name@] Finnish -} module Text.Numeral.Language.FIN ( -- * Language entry entry -- * Inflection , Inflection -- * Conversions , cardinal , ordinal -- * Structure , struct -- * Bounds , bounds ) where ------------------------------------------------------------------------------- -- Imports ------------------------------------------------------------------------------- import "base" Data.Bool ( otherwise ) import "base" Data.Function ( ($), fix, flip ) import "base" Data.Maybe ( Maybe(Just) ) import "base" Prelude ( Num, Integral, (-), negate, divMod ) import "base-unicode-symbols" Data.Bool.Unicode ( (∧) ) import "base-unicode-symbols" Data.Eq.Unicode ( (≡) ) import "base-unicode-symbols" Data.Function.Unicode ( (∘) ) import "base-unicode-symbols" Data.Ord.Unicode ( (≤) ) import qualified "containers" Data.Map as M ( fromList, lookup ) import "this" Text.Numeral import qualified "this" Text.Numeral.BigNum as BN import qualified "this" Text.Numeral.Exp as E import qualified "this" Text.Numeral.Grammar as G import "this" Text.Numeral.Misc ( dec ) import "this" Text.Numeral.Entry import "text" Data.Text ( Text ) ------------------------------------------------------------------------------- -- FIN ------------------------------------------------------------------------------- entry ∷ Entry entry = emptyEntry { entIso639_1 = Just "fi" , entIso639_2 = ["fin"] , entIso639_3 = Just "fin" , entNativeNames = ["suomi"] , entEnglishName = Just "Finnish" , entCardinal = Just Conversion { toNumeral = cardinal , toStructure = struct } , entOrdinal = Just Conversion { toNumeral = ordinal , toStructure = struct } } type Inflection i = ( G.Singular i , G.Plural i , G.Abessive i , G.Accusative i , G.Comitative i , G.Delative i , G.Distributive i , G.DistributiveTemporal i , G.Essive i , G.Genitive i , G.Instructive i , G.Lative i , G.LocativeInessive i , G.LocativeElative i , G.LocativeIllative i , G.LocativeAdessive i , G.LocativeAblative i , G.LocativeAllative i , G.Multiplicative i , G.Nominative i , G.Partitive i , G.Sublative i , G.SuperEssive i , G.Translative i ) cardinal ∷ (Inflection i, Integral α, E.Scale α) ⇒ i → α → Maybe Text cardinal inf = cardinalRepr inf ∘ struct ordinal ∷ (Inflection i, Integral α, E.Scale α) ⇒ i → α → Maybe Text ordinal inf = ordinalRepr inf ∘ struct struct ∷ ( Integral α, E.Scale α , E.Unknown β, E.Lit β, E.Add β, E.Mul β , E.Inflection β, E.Scale β , G.Singular (E.Inf β) , G.Nominative (E.Inf β) , G.Accusative (E.Inf β) , G.Partitive (E.Inf β) ) ⇒ α → β struct = fix $ rule `combine` pelletierScale R L BN.rule where rule = findRule ( 0, lit) [ ( 11, add 10 L) , ( 20, fi_mul 10) , ( 100, step 100 10 R L) , (1000, step 1000 1000 R L) ] (dec 6 - 1) -- | Like the normal 'mul' rule with the difference that the value -- that is multiplied is changed to the partitive case. fi_mul ∷ ( Integral α , E.Add β, E.Mul β, E.Inflection β , G.Singular (E.Inf β) , G.Nominative (E.Inf β) , G.Accusative (E.Inf β) , G.Partitive (E.Inf β) ) ⇒ α → Rule α β fi_mul val = \f n → let (m, a) = n `divMod` val mval = E.mul (f m) (E.inflection toPartitive $ f val) in if a ≡ 0 then mval else (flip E.add) (f a) mval where toPartitive ∷ (G.Singular i, G.Nominative i, G.Accusative i, G.Partitive i) ⇒ i → i toPartitive inf | G.isSingular inf ∧ G.isNominative inf = G.partitive inf | G.isSingular inf ∧ G.isAccusative inf = G.partitive inf | otherwise = inf bounds ∷ (Integral α) ⇒ (α, α) bounds = let x = dec 15 - 1 in (negate x, x) cardinalRepr ∷ (Inflection i) ⇒ i → Exp i → Maybe Text cardinalRepr = render defaultRepr { reprValue = \inf n → M.lookup n (syms inf) , reprScale = BN.pelletierRepr (BN.quantityName "iljoona" "iljoonaa") (BN.quantityName "iljardi" "iljardia") [] , reprAdd = Just $ \_ _ _ → "" , reprMul = Just $ \_ _ _ → "" } where syms inf = M.fromList [ (0, \c → infForms inf c -- singular "nolla" {- nom -} "nolla" {- acc -} "nollan" {- gen -} "nollaa" {- ptv -} "nollana" {- ess -} "nollaksi" {- transl -} "nollassa" {- ine -} "nollasta" {- ela -} "nollaan" {- ill -} "nollalla" {- ade -} "nollalta" {- abl -} "nollalle" {- all -} "nollatta" {- abe -} "?" {- other -} -- plural "nollat" {- nom -} "nollat" {- acc -} "nollien" {- gen -} "nollia" {- ptv -} "nollina" {- ess -} "nolliksi" {- transl -} "nollissa" {- ine -} "nollista" {- ela -} "nolliin" {- ill -} "nollilla" {- ade -} "nollilta" {- abl -} "nollille" {- all -} "nollitta" {- abe -} "nolline" {- com -} "nollin" {- instr -} "?" {- other -} ) , (1, \c → infForms inf c -- singular "yksi" {- nom -} "yksi" {- acc -} "yhden" {- gen -} "yhtä" {- ptv -} "yhtenä" {- ess -} "yhdeksi" {- transl -} "yhdessä" {- ine -} "yhdestä" {- ela -} "yhteen" {- ill -} "yhdellä" {- ade -} "yhdeltä" {- abl -} "yhdelle" {- all -} "yhdettä" {- abe -} (case inf of _ | G.isSuperEssive inf → "yhtäällä" | G.isDelative inf → "yhtäältä" | G.isSublative inf → "yhtäälle" | G.isLative inf → "yhä" | G.isMultiplicative inf → "yhdesti" | otherwise → "?" ) -- plural "yhdet" {- nom -} "yhdet" {- acc -} "yksien" {- gen -} "yksiä" {- ptv -} "yksinä" {- ess -} "yksiksi" {- transl -} "yksissä" {- ine -} "yksistä" {- ela -} "yksiin" {- ill -} "yksillä" {- ade -} "yksiltä" {- abl -} "yksille" {- all -} "yksittä" {- abe -} "yksine" {- com -} "yksin" {- instr -} (case inf of _ | G.isDistributive inf → "yksittäin" | otherwise → "?" ) ) , (2, \c → infForms inf c -- singular "kaksi" {- nom -} "kaksi" {- acc -} "kahden" {- gen -} "kahta" {- ptv -} "kahtena" {- ess -} "kahdeksi" {- transl -} "kahdessa" {- ine -} "kahdesta" {- ela -} "kahteen" {- ill -} "kahdella" {- ade -} "kahdelta" {- abl -} "kahdelle" {- all -} "kahdetta" {- abe -} (case inf of _ | G.isInstructive inf → "kahden" | G.isSuperEssive inf → "kahtaalla" | G.isDelative inf → "kahtaalta" | G.isSublative inf → "kahtaalle" | G.isLative inf → "kahtia" | G.isMultiplicative inf → "kahdesti" | otherwise → "?" ) -- plural "kahdet" {- nom -} "kahdet" {- acc -} "kaksien" {- gen -} "kaksia" {- ptv -} "kaksina" {- ess -} "kaksiksi" {- transl -} "kaksissa" {- ine -} "kaksista" {- ela -} "kaksiin" {- ill -} "kaksilla" {- ade -} "kaksilta" {- abl -} "kaksille" {- all -} "kaksitta" {- abe -} "kaksine" {- com -} "kaksin" {- instr -} (case inf of _ | G.isDistributive inf → "kaksittain" | otherwise → "?" ) ) , (3, \c → infForms inf c -- singular "kolme" {- nom -} "kolme" {- acc -} "kolmen" {- gen -} "kolmea" {- ptv -} "kolmena" {- ess -} "kolmeksi" {- transl -} "kolmessa" {- ine -} "kolmesta" {- ela -} "kolmeen" {- ill -} "kolmella" {- ade -} "kolmelta" {- abl -} "kolmelle" {- all -} "kolmetta" {- abe -} (case inf of _ | G.isInstructive inf → "kolmen" | G.isLative inf → "kolmia" | G.isMultiplicative inf → "kolmesti" | otherwise → "?" ) -- plural "kolmet" {- nom -} "kolmet" {- acc -} "kolmien" {- gen -} "kolmia" {- ptv -} "kolmina" {- ess -} "kolmiksi" {- transl -} "kolmissa" {- ine -} "kolmista" {- ela -} "kolmiin" {- ill -} "kolmilla" {- ade -} "kolmilta" {- abl -} "kolmille" {- all -} "kolmitta" {- abe -} "kolmine" {- com -} "kolmin" {- instr -} (case inf of _ | G.isDistributive inf → "kolmittain" | G.isDistributiveTemporal inf → "kolmisin" | otherwise → "?" ) ) , (4, \c → infForms inf c -- singular "neljä" {- nom -} "neljä" {- acc -} "neljän" {- gen -} "neljää" {- ptv -} "neljänä" {- ess -} "neljäksi" {- transl -} "neljässä" {- ine -} "neljästä" {- ela -} "neljään" {- ill -} "neljällä" {- ade -} "neljältä" {- abl -} "neljälle" {- all -} "neljättä" {- abe -} "?" {- other -} -- plural "neljät" {- nom -} "neljät" {- acc -} "neljien" {- gen -} "neljiä" {- ptv -} "neljinä" {- ess -} "neljiksi" {- transl -} "neljissä" {- ine -} "neljistä" {- ela -} "neljiin" {- ill -} "neljillä" {- ade -} "neljiltä" {- abl -} "neljille" {- all -} "neljittä" {- abe -} "neljine" {- com -} "neljin" {- instr -} "?" {- other -} ) , (5, \c → infForms inf c -- singular "viisi" {- nom -} "viisi" {- acc -} "viiden" {- gen -} "viittä" {- ptv -} "viitenä" {- ess -} "viideksi" {- transl -} "viidessä" {- ine -} "viidestä" {- ela -} "viiteen" {- ill -} "viidellä" {- ade -} "viideltä" {- abl -} "viidelle" {- all -} "viidettä" {- abe -} "?" {- other -} -- plural "viidet" {- nom -} "viidet" {- acc -} "viisien" {- gen -} "viisiä" {- ptv -} "viisinä" {- ess -} "viisiksi" {- transl -} "viisissä" {- ine -} "viisistä" {- ela -} "viisiin" {- ill -} "viisillä" {- ade -} "viisiltä" {- abl -} "viisille" {- all -} "viisittä" {- abe -} "viisine" {- com -} "viisin" {- instr -} "?" {- other -} ) , (6, \c → infForms inf c -- singular "kuusi" {- nom -} "kuusi" {- acc -} "kuuden" {- gen -} "kuutta" {- ptv -} "kuutena" {- ess -} "kuudeksi" {- transl -} "kuudessa" {- ine -} "kuudesta" {- ela -} "kuuteen" {- ill -} "kuudella" {- ade -} "kuudelta" {- abl -} "kuudelle" {- all -} "kuudetta" {- abe -} "?" {- other -} -- plural "kuudet" {- nom -} "kuudet" {- acc -} "kuusien" {- gen -} "kuusia" {- ptv -} "kuusina" {- ess -} "kuusiksi" {- transl -} "kuusissa" {- ine -} "kuusista" {- ela -} "kuusiin" {- ill -} "kuusilla" {- ade -} "kuusilta" {- abl -} "kuusille" {- all -} "kuusitta" {- abe -} "kuusine" {- com -} "kuusin" {- instr -} "?" {- other -} ) , (7, \c → infForms inf c -- singular "seitsemän" {- nom -} "seitsemän" {- acc -} "seitsemän" {- gen -} "seitsemää" {- ptv -} "seitsemänä" {- ess -} "seitsemäksi" {- transl -} "seitsemässä" {- ine -} "seitsemästä" {- ela -} "seitsemään" {- ill -} "seitsemällä" {- ade -} "seitsemältä" {- abl -} "seitsemälle" {- all -} "seitsemättä" {- abe -} "?" {- other -} -- plural "seitsemät" {- nom -} "seitsemät" {- acc -} "seitsemien" {- gen -} "seitsemiä" {- ptv -} "seitseminä" {- ess -} "seitsemiksi" {- transl -} "seitsemissä" {- ine -} "seitsemistä" {- ela -} "seitsemiin" {- ill -} "seitsemillä" {- ade -} "seitsemiltä" {- abl -} "seitsemille" {- all -} "seitsemittä" {- abe -} "seitsemine" {- com -} "seitsemin" {- instr -} "?" {- other -} ) , (8, \c → infForms inf c -- singular "kahdeksan" {- nom -} "kahdeksan" {- acc -} "kahdeksan" {- gen -} "kahdeksaa" {- ptv -} "kahdeksana" {- ess -} "kahdeksaksi" {- transl -} "kahdeksassa" {- ine -} "kahdeksasta" {- ela -} "kahdeksaan" {- ill -} "kahdeksalla" {- ade -} "kahdeksalta" {- abl -} "kahdeksalle" {- all -} "kahdeksatta" {- abe -} "?" {- other -} -- plural "kahdeksat" {- nom -} "kahdeksat" {- acc -} "kahdeksien" {- gen -} "kahdeksia" {- ptv -} "kahdeksina" {- ess -} "kahdeksiksi" {- transl -} "kahdeksissa" {- ine -} "kahdeksista" {- ela -} "kahdeksiin" {- ill -} "kahdeksilla" {- ade -} "kahdeksilta" {- abl -} "kahdeksille" {- all -} "kahdeksitta" {- abe -} "kahdeksine" {- com -} "kahdeksin" {- instr -} "?" {- other -} ) , (9, \c → infForms inf c -- singular "yhdeksän" {- nom -} "yhdeksän" {- acc -} "yhdeksän" {- gen -} "yhdeksää" {- ptv -} "yhdeksänä" {- ess -} "yhdeksäksi" {- transl -} "yhdeksässä" {- ine -} "yhdeksästä" {- ela -} "yhdeksään" {- ill -} "yhdeksällä" {- ade -} "yhdeksältä" {- abl -} "yhdeksälle" {- all -} "yhdeksättä" {- abe -} "?" {- other -} -- plural "yhdeksät" {- nom -} "yhdeksät" {- acc -} "yhdeksien" {- gen -} "yhdeksiä" {- ptv -} "yhdeksinä" {- ess -} "yhdeksiksi" {- transl -} "yhdeksissä" {- ine -} "yhdeksistä" {- ela -} "yhdeksiin" {- ill -} "yhdeksillä" {- ade -} "yhdeksiltä" {- abl -} "yhdeksille" {- all -} "yhdeksittä" {- abe -} "yhdeksine" {- com -} "yhdeksin" {- instr -} "?" {- other -} ) , (10, \c → case c of CtxAdd _ (Lit _) _ → "toista" -- singular partitive ordinal 2 _ → infForms inf c -- singular "kymmenen" {- nom -} "kymmenen" {- acc -} "kymmenen" {- gen -} "kymmentä" {- ptv -} "kymmenenä" {- ess -} "kymmeneksi" {- transl -} "kymmenessä" {- ine -} "kymmenestä" {- ela -} "kymmeneen" {- ill -} "kymmenellä" {- ade -} "kymmeneltä" {- abl -} "kymmenelle" {- all -} "kymmenettä" {- abe -} "?" {- other -} -- plural "kymmenet" {- nom -} "kymmenet" {- acc -} "kymmenien" {- gen -} "kymmeniä" {- ptv -} "kymmeninä" {- ess -} "kymmeniksi" {- transl -} "kymmenissä" {- ine -} "kymmenistä" {- ela -} "kymmeniin" {- ill -} "kymmenillä" {- ade -} "kymmeniltä" {- abl -} "kymmenille" {- all -} "kymmenittä" {- abe -} "kymmenine" {- com -} "kymmenin" {- instr -} "?" {- other -} ) , (100, \c → case c of CtxMul _ (Lit n) _ | n ≤ 9 → "sataa" _ → infForms inf c -- singular "sata" {- nom -} "sata" {- acc -} "sadan" {- gen -} "sataa" {- ptv -} "satana" {- ess -} "sadaksi" {- transl -} "sadassa" {- ine -} "sadasta" {- ela -} "sataan" {- ill -} "sadalla" {- ade -} "sadalta" {- abl -} "sadalle" {- all -} "sadatta" {- abe -} "?" {- other -} -- plural "sadat" {- nom -} "sadat" {- acc -} "satojen" {- gen -} "satoja" {- ptv -} "satoina" {- ess -} "sadoiksi" {- transl -} "sadoissa" {- ine -} "sadoista" {- ela -} "satoihin" {- ill -} "sadoilla" {- ade -} "sadoilta" {- abl -} "sadoille" {- all -} "sadoitta" {- abe -} "satoine" {- com -} "sadoin" {- instr -} "?" {- other -} ) , (1000, \c → case c of CtxMul {} → "tuhatta" _ → infForms inf c -- singular "tuhat" {- nom -} "tuhat" {- acc -} "tuhannen" {- gen -} "tuhatta" {- ptv -} "tuhantena" {- ess -} "tuhanneksi" {- transl -} "tuhannessa" {- ine -} "tuhannesta" {- ela -} "tuhanteen" {- ill -} "tuhannella" {- ade -} "tuhannelta" {- abl -} "tuhannelle" {- all -} "tuhannetta" {- abe -} "?" {- other -} -- plural "tuhannet" {- nom -} "tuhannet" {- acc -} "tuhansien" {- gen -} "tuhansia" {- ptv -} "tuhansina" {- ess -} "tuhansiksi" {- transl -} "tuhansissa" {- ine -} "tuhansista" {- ela -} "tuhansiin" {- ill -} "tuhansilla" {- ade -} "tuhansilta" {- abl -} "tuhansille" {- all -} "tuhansitta" {- abe -} "tuhansine" {- com -} "tuhansin" {- instr -} "?" {- other -} ) ] ordinalRepr ∷ (Inflection i) ⇒ i → Exp i → Maybe Text ordinalRepr = render defaultRepr { reprValue = \inf n → M.lookup n (syms inf) , reprScale = BN.pelletierRepr (BN.quantityName "iljoona" "iljoonaa") (BN.quantityName "iljardi" "iljardia") [] , reprAdd = Just $ \_ _ _ → "" , reprMul = Just $ \_ _ _ → "" } where syms inf = M.fromList [ (0, \c → infForms inf c -- singular "nollas" {- nom -} "nollas" {- acc -} "nollannen" {- gen -} "nollatta" {- ptv -} "nollantena" {- ess -} "nollanneksi" {- transl -} "nollannessa" {- ine -} "nollannesta" {- ela -} "nollanteen" {- ill -} "nollannella" {- ade -} "nollannelta" {- abl -} "nollannelle" {- all -} "nollannetta" {- abe -} "?" {- other -} -- plural "nollannet" {- nom -} "nollannet" {- acc -} "nollansien" {- gen -} "nollansia" {- ptv -} "nollansina" {- ess -} "nollansiksi" {- transl -} "nollansissa" {- ine -} "nollansista" {- ela -} "nollansiin" {- ill -} "nollansilla" {- ade -} "nollansilta" {- abl -} "nollansille" {- all -} "nollansitta" {- abe -} "nollansine" {- com -} "nollansin" {- instr -} "?" {- other -} ) , (1, \c → case c of CtxAdd _ (Lit 10) _ → infForms inf c -- singular "yhdes" {- nom -} "yhdes" {- acc -} "yhdennen" {- gen -} "yhdettä" {- ptv -} "yhdennessä" {- ess -} "yhdenneksi" {- transl -} "yhdennessä" {- ine -} "yhdennestä" {- ela -} "yhdenteen" {- ill -} "yhdennellä" {- ade -} "yhdenneltä" {- abl -} "yhdennelle" {- all -} "yhdennettä" {- abe -} "?" {- other -} -- plural "yhdennet" {- nom -} "yhdennet" {- acc -} "yhdensien" {- gen -} "yhdensiä" {- ptv -} "yhdensinä" {- ess -} "yhdensiksi" {- transl -} "yhdensissä" {- ine -} "yhdensistä" {- ela -} "yhdensiin" {- ill -} "yhdensillä" {- ade -} "yhdensitlä" {- abl -} "yhdensiin" {- all -} "yhdensittä" {- abe -} "yhdensine" {- com -} "yhdensin" {- instr -} "?" {- other -} _ → infForms inf c -- singular "ensimmäinen" {- nom -} "ensimmäinen" {- acc -} "ensimmäisen" {- gen -} "ensimmäistä" {- ptv -} "ensimmmäisenä" {- ess -} "ensimmäiseksi" {- transl -} "ensimmäisessä" {- ine -} "ensimmäisestä" {- ela -} "ensimmäiseen" {- ill -} "ensimmäisellä" {- ade -} "ensimmäiseltä" {- abl -} "ensimmäiselle" {- all -} "ensimmäisettä" {- abe -} "?" {- other -} -- plural "ensimmäiset" {- nom -} "ensimmäiset" {- acc -} "ensimmäisten" {- gen -} "ensimmäisiä" {- ptv -} "ensimmäisinä" {- ess -} "ensimmäisiksi" {- transl -} "ensimmäisissä" {- ine -} "ensimmäisistä" {- ela -} "ensimmäisiin" {- ill -} "ensimmäisillä" {- ade -} "ensimmäisiltä" {- abl -} "ensimmäisille" {- all -} "ensimmäisittä" {- abe -} "ensimmäisine" {- com -} "ensimmäisin" {- instr -} "?" {- other -} ) , (2, \c → case c of CtxAdd _ (Lit 10) _ → infForms inf c -- singular "kahdes" {- nom -} "kahdes" {- acc -} "kahdennen" {- gen -} "kahdetta" {- ptv -} "kahdentena" {- ess -} "kahdenneksi" {- transl -} "kahdennessa" {- ine -} "kahdennesta" {- ela -} "kahdenteen" {- ill -} "kahdennella" {- ade -} "kahdennelta" {- abl -} "kahdennelle" {- all -} "kahdennetta" {- abe -} "?" {- other -} -- plural "kahdennet" {- nom -} "kahdennet" {- acc -} "kahdensien" {- gen -} "kahdensia" {- ptv -} "kahdensina" {- ess -} "kahdensiksi" {- transl -} "kahdensissa" {- ine -} "kahdensista" {- ela -} "kahdensiin" {- ill -} "kahdensilla" {- ade -} "kahdensilta" {- abl -} "kahdensille" {- all -} "kahdensitta" {- abe -} "kahdensine" {- com -} "kahdensin" {- instr -} "?" {- other -} _ → infForms inf c -- singular "toinen" {- nom -} "toinen" {- acc -} "toisen" {- gen -} "toista" {- ptv -} "toisena" {- ess -} "toiseksi" {- transl -} "toisessa" {- ine -} "toisesta" {- ela -} "toiseen" {- ill -} "toisella" {- ade -} "toiselta" {- abl -} "toiselle" {- all -} "toisetta" {- abe -} "?" {- other -} -- plural "toiset" {- nom -} "toiset" {- acc -} "toisten" {- gen -} "toisia" {- ptv -} "toisina" {- ess -} "toisiksi" {- transl -} "toisissa" {- ine -} "toisista" {- ela -} "toisiin" {- ill -} "toisilla" {- ade -} "toisilta" {- abl -} "toisille" {- all -} "toisitta" {- abe -} "toisine" {- com -} "toisin" {- instr -} "?" {- other -} ) , (3, \c → infForms inf c -- singular "kolmas" {- nom -} "kolmas" {- acc -} "kolmannen" {- gen -} "kolmatta" {- ptv -} "kolmantena" {- ess -} "kolmanneksi" {- transl -} "kolmannessa" {- ine -} "kolmannesta" {- ela -} "kolmanteen" {- ill -} "kolmannella" {- ade -} "kolmannelta" {- abl -} "kolmannelle" {- all -} "kolmannetta" {- abe -} "?" {- other -} -- plural "kolmannet" {- nom -} "kolmannet" {- acc -} "kolmansien" {- gen -} "kolmansia" {- ptv -} "kolmansina" {- ess -} "kolmansiksi" {- transl -} "kolmansissa" {- ine -} "kolmansista" {- ela -} "kolmansiin" {- ill -} "kolmansilla" {- ade -} "kolmansilta" {- abl -} "kolmansille" {- all -} "kolmansitta" {- abe -} "kolmansine" {- com -} "kolmansin" {- instr -} "?" {- other -} ) , (4, \c → infForms inf c -- singular "neljäs" {- nom -} "neljäs" {- acc -} "neljännen" {- gen -} "neljättä" {- ptv -} "neljäntenä" {- ess -} "neljänneksi" {- transl -} "neljännessä" {- ine -} "neljännestä" {- ela -} "neljänteen" {- ill -} "neljännellä" {- ade -} "neljänneltä" {- abl -} "neljännelle" {- all -} "neljännettä" {- abe -} (case inf of _ | G.isComitative inf → "neljänsine" | G.isInstructive inf → "neljänsin" | otherwise → "?" ) -- plural "neljännet" {- nom -} "neljännet" {- acc -} "neljänsien" {- gen -} "neljänsiä" {- ptv -} "neljänsinä" {- ess -} "neljänsiksi" {- transl -} "neljänsissä" {- ine -} "neljänsistä" {- ela -} "neljänsiin" {- ill -} "neljänsillä" {- ade -} "neljänsiltä" {- abl -} "neljänsille" {- all -} "neljänsittä" {- abe -} "neljänsine" {- com -} "neljänsin" {- instr -} "?" {- other -} ) , (5, \c → infForms inf c -- singular "viides" {- nom -} "viides" {- acc -} "viidennen" {- gen -} "viidettä" {- ptv -} "viidentenä" {- ess -} "viidenneksi" {- transl -} "viidennessä" {- ine -} "viidennestä" {- ela -} "viidenteen" {- ill -} "viidennellä" {- ade -} "viidenneltä" {- abl -} "viidennelle" {- all -} "viidennettä" {- abe -} "?" {- other -} -- plural "viidennet" {- nom -} "viidennet" {- acc -} "viidensien" {- gen -} "viidensiä" {- ptv -} "viidensinä" {- ess -} "viidensiksi" {- transl -} "viidensissä" {- ine -} "viidensistä" {- ela -} "viidensiin" {- ill -} "viidensillä" {- ade -} "viidensiltä" {- abl -} "viidensille" {- all -} "viidensittä" {- abe -} "viidensine" {- com -} "viidensin" {- instr -} "?" {- other -} ) , (6, \c → infForms inf c -- singular "kuudes" {- nom -} "kuudes" {- acc -} "kuudennen" {- gen -} "kuudetta" {- ptv -} "kuudentena" {- ess -} "kuudenneksi" {- transl -} "kuudennessa" {- ine -} "kuudennesta" {- ela -} "kuudenteen" {- ill -} "kuudennella" {- ade -} "kuudennelta" {- abl -} "kuudennelle" {- all -} "kuudennetta" {- abe -} "?" {- other -} -- plural "kuudennet" {- nom -} "kuudennet" {- acc -} "kuudensien" {- gen -} "kuudensia" {- ptv -} "kuudensina" {- ess -} "kuudensiksi" {- transl -} "kuudensissa" {- ine -} "kuudensista" {- ela -} "kuudensiin" {- ill -} "kuudensilla" {- ade -} "kuudensilta" {- abl -} "kuudensille" {- all -} "kuudensitta" {- abe -} "kuudensine" {- com -} "kuudensin" {- instr -} "?" {- other -} ) , (7, \c → infForms inf c -- singular "seitsemäs" {- nom -} "seitsemäs" {- acc -} "seitsemännen" {- gen -} "seitsemättä" {- ptv -} "seitsemäntenä" {- ess -} "seitsemänneksi" {- transl -} "seitsemännessä" {- ine -} "seitsemännestä" {- ela -} "seitsemänteen" {- ill -} "seitsemännellä" {- ade -} "seitsemänneltä" {- abl -} "seitsemännelle" {- all -} "seitsemännettä" {- abe -} "?" {- other -} -- plural "seitsemännet" {- nom -} "seitsemännet" {- acc -} "seitsemänsien" {- gen -} "seitsemänsiä" {- ptv -} "seitsemänsinä" {- ess -} "seitsemänsiksi" {- transl -} "seitsemänsissä" {- ine -} "seitsemänsistä" {- ela -} "seitsemänsiin" {- ill -} "seitsemänsillä" {- ade -} "seitsemänsiltä" {- abl -} "seitsemänsille" {- all -} "seitsemänsittä" {- abe -} "seitsemänsine" {- com -} "seitsemänsin" {- instr -} "?" {- other -} ) , (8, \c → infForms inf c -- singular "kahdeksas" {- nom -} "kahdeksas" {- acc -} "kahdeksannen" {- gen -} "kahdeksatta" {- ptv -} "kahdeksantena" {- ess -} "kahdeksanneksi" {- transl -} "kahdeksannessa" {- ine -} "kahdeksannesta" {- ela -} "kahdeksanteen" {- ill -} "kahdeksannella" {- ade -} "kahdeksannelta" {- abl -} "kahdeksannelle" {- all -} "kahdeksannetta" {- abe -} "?" {- other -} -- plural "kahdeksannet" {- nom -} "kahdeksannet" {- acc -} "kahdeksansien" {- gen -} "kahdeksansia" {- ptv -} "kahdeksansina" {- ess -} "kahdeksansiksi" {- transl -} "kahdeksansissa" {- ine -} "kahdeksansista" {- ela -} "kahdeksansiin" {- ill -} "kahdeksansilla" {- ade -} "kahdeksansilta" {- abl -} "kahdeksansille" {- all -} "kahdeksansitta" {- abe -} "kahdeksansine" {- com -} "kahdeksansin" {- instr -} "?" {- other -} ) , (9, \c → infForms inf c -- singular "yhdeksäs" {- nom -} "yhdeksäs" {- acc -} "yhdeksännen" {- gen -} "yhdeksättä" {- ptv -} "yhdeksäntenä" {- ess -} "yhdeksänneksi" {- transl -} "yhdeksännessä" {- ine -} "yhdeksännestä" {- ela -} "yhdeksänteen" {- ill -} "yhdeksännellä" {- ade -} "yhdeksänneltä" {- abl -} "yhdeksännelle" {- all -} "yhdeksännettä" {- abe -} "?" {- other -} -- plural "yhdeksännet" {- nom -} "yhdeksännet" {- acc -} "yhdeksänsien" {- gen -} "yhdeksänsiä" {- ptv -} "yhdeksänsinä" {- ess -} "yhdeksänsiksi" {- transl -} "yhdeksänsissä" {- ine -} "yhdeksänsistä" {- ela -} "yhdeksänsiin" {- ill -} "yhdeksänsillä" {- ade -} "yhdeksänsiltä" {- abl -} "yhdeksänsille" {- all -} "yhdeksänsittä" {- abe -} "yhdeksänsine" {- com -} "yhdeksänsin" {- instr -} "?" {- other -} ) , (10, \c → case c of CtxAdd _ (Lit _) _ → "toista" -- singular partitive ordinal 2 _ → infForms inf c -- singular "kymmenes" {- nom -} "kymmenes" {- acc -} "kymmenennen" {- gen -} "kymmenettä" {- ptv -} "kymmenentenä" {- ess -} "kymmenenneksi" {- transl -} "kymmenennessä" {- ine -} "kymmenennestä" {- ela -} "kymmenenteen" {- ill -} "kymmenennellä" {- ade -} "kymmenenneltä" {- abl -} "kymmenennelle" {- all -} "kymmenennettä" {- abe -} "?" {- other -} -- plural "kymmenennet" {- nom -} "kymmenennet" {- acc -} "kymmenensien" {- gen -} "kymmenensiä" {- ptv -} "kymmenensinä" {- ess -} "kymmenensiksi" {- transl -} "kymmenensissä" {- ine -} "kymmenensistä" {- ela -} "kymmenensiin" {- ill -} "kymmenensillä" {- ade -} "kymmenensiltä" {- abl -} "kymmenensille" {- all -} "kymmenensittä" {- abe -} "kymmenensine" {- com -} "kymmenensin" {- instr -} "?" {- other -} ) , (100, \c → case c of _ → infForms inf c -- singular "sadas" {- nom -} "sadas" {- acc -} "sadannen" {- gen -} "sadatta" {- ptv -} "sadantena" {- ess -} "sadanneksi" {- transl -} "sadannessa" {- ine -} "sadannesta" {- ela -} "sadanteen" {- ill -} "sadannella" {- ade -} "sadannelta" {- abl -} "sadannelle" {- all -} "sadannetta" {- abe -} "?" {- other -} -- plural "sadannet" {- nom -} "sadannet" {- acc -} "sadansien" {- gen -} "sadansia" {- ptv -} "sadansina" {- ess -} "sadansiksi" {- transl -} "sadansissa" {- ine -} "sadansista" {- ela -} "sadansiin" {- ill -} "sadansilla" {- ade -} "sadansilta" {- abl -} "sadansille" {- all -} "sadansitta" {- abe -} "sadansine" {- com -} "sadansin" {- instr -} "?" {- other -} ) , (1000, \c → case c of _ → infForms inf c -- singular "tuhannes" {- nom -} "tuhannes" {- acc -} "tuhannennen" {- gen -} "tuhannetta" {- ptv -} "tuhannentena" {- ess -} "tuhannenneksi" {- transl -} "tuhannennessa" {- ine -} "tuhannennesta" {- ela -} "tuhannenteen" {- ill -} "tuhannennella" {- ade -} "tuhannennelta" {- abl -} "tuhannennelle" {- all -} "tuhannennetta" {- abe -} "?" {- other -} -- plural "tuhannennet" {- nom -} "tuhannennet" {- acc -} "tuhannensien" {- gen -} "tuhannensia" {- ptv -} "tuhannensina" {- ess -} "tuhannensiksi" {- transl -} "tuhannensissa" {- ine -} "tuhannensista" {- ela -} "tuhannensiin" {- ill -} "tuhannensilla" {- ade -} "tuhannensilta" {- abl -} "tuhannensille" {- all -} "tuhannensitta" {- abe -} "tuhannensine" {- com -} "tuhannensin" {- instr -} "?" {- other -} ) ] infForms ∷ (Inflection i) ⇒ i → Ctx (Exp i) → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text infForms inf _ s_nom s_acc s_gen s_ptv s_ess s_transl s_ine s_ela s_ill s_ade s_abl s_all s_abe s_other p_nom p_acc p_gen p_ptv p_ess p_transl p_ine p_ela p_ill p_ade p_abl p_all p_abe p_com p_instr p_other | G.isSingular inf = singularForms | G.isPlural inf = pluralForms | otherwise = "?" where singularForms | G.isNominative inf = s_nom | G.isAccusative inf = s_acc | G.isGenitive inf = s_gen | G.isPartitive inf = s_ptv | G.isEssive inf = s_ess | G.isTranslative inf = s_transl | G.isLocativeInessive inf = s_ine | G.isLocativeElative inf = s_ela | G.isLocativeIllative inf = s_ill | G.isLocativeAdessive inf = s_ade | G.isLocativeAblative inf = s_abl | G.isLocativeAllative inf = s_all | G.isAbessive inf = s_abe | otherwise = s_other pluralForms | G.isNominative inf = p_nom | G.isAccusative inf = p_acc | G.isGenitive inf = p_gen | G.isPartitive inf = p_ptv | G.isEssive inf = p_ess | G.isTranslative inf = p_transl | G.isLocativeInessive inf = p_ine | G.isLocativeElative inf = p_ela | G.isLocativeIllative inf = p_ill | G.isLocativeAdessive inf = p_ade | G.isLocativeAblative inf = p_abl | G.isLocativeAllative inf = p_all | G.isAbessive inf = p_abe | G.isComitative inf = p_com | G.isInstructive inf = p_instr | otherwise = p_other
telser/numerals
src/Text/Numeral/Language/FIN.hs
bsd-3-clause
49,160
0
37
26,239
5,963
3,491
2,472
724
4
module Main where import Test.HUnit hiding (path) import TestUtil import Database.TokyoCabinet.HDB import Data.Maybe (catMaybes) import Data.List (sort) import Control.Monad dbname :: String dbname = "foo.tch" withOpenedHDB :: String -> (HDB -> IO a) -> IO a withOpenedHDB name action = do h <- new open h name [OREADER, OWRITER, OCREAT] res <- action h close h return res test_ecode = withoutFile dbname $ \fn -> do h <- new open h fn [OREADER] ecode h >>= (ENOFILE @=?) test_new_delete = do hdb <- new delete hdb test_open_close = withoutFile dbname $ \fn -> do hdb <- new not `fmap` open hdb fn [OREADER] @? "file does not exist" open hdb fn [OREADER, OWRITER, OCREAT] @? "open" close hdb @? "close" not `fmap` close hdb @? "cannot close closed file" test_putxx = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do put hdb "foo" "bar" get hdb "foo" >>= (Just "bar" @=?) putkeep hdb "foo" "baz" get hdb "foo" >>= (Just "bar" @=?) putcat hdb "foo" "baz" get hdb "foo" >>= (Just "barbaz" @=?) putasync hdb "bar" "baz" sync hdb get hdb "bar" >>= (Just "baz" @=?) test_out = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do put hdb "foo" "bar" get hdb "foo" >>= (Just "bar" @=?) out hdb "foo" @? "out succeeded" get hdb "foo" >>= ((Nothing :: Maybe String) @=?) test_put_get = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do put hdb "1" "foo" put hdb "2" "bar" put hdb "3" "baz" get hdb "1" >>= (Just "foo" @=?) get hdb "2" >>= (Just "bar" @=?) get hdb "3" >>= (Just "baz" @=?) test_vsiz = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do put hdb "foo" "bar" vsiz hdb "foo" >>= (Just 3 @=?) vsiz hdb "bar" >>= ((Nothing :: Maybe Int) @=?) test_iterate = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do let keys = [1, 2, 3] :: [Int] vals = ["foo", "bar", "baz"] zipWithM_ (put hdb) keys vals iterinit hdb keys' <- sequence $ replicate (length keys) (iternext hdb) (sort $ catMaybes keys') @?= (sort keys) test_fwmkeys = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do mapM_ (uncurry (put hdb)) ([ ("foo", 100) , ("bar", 200) , ("baz", 201) , ("jkl", 300)] :: [(String, Int)]) fwmkeys hdb "ba" 10 >>= (["bar", "baz"] @=?) . sort fwmkeys hdb "ba" 1 >>= (["bar"] @=?) fwmkeys hdb "" 10 >>= (["bar", "baz", "foo", "jkl"] @=?) . sort test_addint = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do let ini = 32 :: Int put hdb "foo" ini get hdb "foo" >>= (Just ini @=?) addint hdb "foo" 3 get hdb "foo" >>= (Just (ini+3) @=?) addint hdb "bar" 1 >>= (Just 1 @=?) put hdb "bar" "foo" addint hdb "bar" 1 >>= (Nothing @=?) test_adddouble = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do let ini = 0.003 :: Double put hdb "foo" ini get hdb "foo" >>= (Just ini @=?) adddouble hdb "foo" 0.3 (get hdb "foo" >>= (isIn (ini+0.3))) @? "isIn" adddouble hdb "bar" 0.5 >>= (Just 0.5 @=?) put hdb "bar" "foo" adddouble hdb "bar" 1.2 >>= (Nothing @=?) where margin = 1e-30 isIn :: Double -> (Maybe Double) -> IO Bool isIn expected (Just actual) = let diff = expected - actual in return $ abs diff <= margin test_vanish = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do put hdb "foo" "111" put hdb "bar" "222" put hdb "baz" "333" rnum hdb >>= (3 @=?) vanish hdb rnum hdb >>= (0 @=?) test_copy = withoutFile dbname $ \fns -> withoutFile "bar.tch" $ \fnd -> withOpenedHDB fns $ \hdb -> do put hdb "foo" "bar" copy hdb fnd close hdb open hdb fnd [OREADER] get hdb "foo" >>= (Just "bar" @=?) test_txn = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do tranbegin hdb put hdb "foo" "bar" get hdb "foo" >>= (Just "bar" @=?) tranabort hdb get hdb "foo" >>= ((Nothing :: Maybe String) @=?) tranbegin hdb put hdb "foo" "baz" get hdb "foo" >>= (Just "baz" @=?) trancommit hdb get hdb "foo" >>= (Just "baz" @=?) test_path = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> path hdb >>= (Just dbname @=?) test_util = withoutFile dbname $ \fn -> do hdb <- new setcache hdb 1000000 @? "setcache" setxmsiz hdb 1000000 @? "setxmsiz" tune hdb 150000 5 11 [TLARGE, TBZIP] @? "tune" open hdb fn [OREADER, OWRITER, OCREAT] path hdb >>= (Just fn @=?) rnum hdb >>= (0 @=?) ((> 0) `fmap` fsiz hdb) @? "fsiz" sync hdb @? "sync" optimize hdb 0 (-1) (-1) [] @? "optimize" close hdb tests = test [ "new delete" ~: test_new_delete , "ecode" ~: test_ecode , "open close" ~: test_open_close , "put get" ~: test_put_get , "out" ~: test_out , "putxx" ~: test_putxx , "copy" ~: test_copy , "transaction" ~: test_txn , "fwmkeys" ~: test_fwmkeys , "path" ~: test_path , "addint" ~: test_addint , "adddouble" ~: test_adddouble , "util" ~: test_util , "vsiz" ~: test_vsiz , "vanish" ~: test_vanish , "iterate" ~: test_iterate ] main = runTestTT tests
tom-lpsd/tokyocabinet-haskell
tests/HDBTest.hs
bsd-3-clause
6,050
0
17
2,227
2,170
1,073
1,097
177
1
module CRF.Control.Monad.Lazy ( mapM' -- , mapM_' , sequence' ) where import System.IO.Unsafe (unsafeInterleaveIO) sequence' (mx:xs) = unsafeInterleaveIO $ combine xs =<< mx where combine xs x = return . (x:) =<< sequence' xs sequence' [] = return [] mapM' f (x:xs) = unsafeInterleaveIO $ do y <- f x ys <- mapM' f xs return (y : ys) mapM' _ [] = return [] -- mapM_' f (x:xs) = unsafeInterleaveIO $ do -- y <- f x -- mapM_' f xs -- mapM_' _ [] = return ()
kawu/tagger
src/CRF/Control/Monad/Lazy.hs
bsd-3-clause
488
0
10
121
173
91
82
13
1
-- From Thinking Functionally with Haskell -- One man went to mow -- Went to mow a meadow -- One man and his dog -- Went to mow a meadow -- Two men went to mow -- Went to mow a meadow -- Two men, one man and his dog -- Went to mow a meadow -- Three men went to mow -- Went to mow a meadow -- Three men, two men, one man and his dog -- Went to mow a meadow units :: [String] units = ["zero","one","two","three","four","five","six","seven","eight","nine"] convert1 :: Int -> String convert1 n = units!!n convert = convert1 men :: Int -> String men n | n <= 1 = convert n ++ " man" | otherwise = convert n ++ " men" s1 :: Int -> String s1 n = men n ++ " went to mow\n" s2 :: Int -> String s2 n = "Went to mow a meadow\n" s3 :: Int -> String s3 n | n <= 1 = men n ++ " and his dog\n" | otherwise = men n ++ ", " ++ s3 (n - 1) s4 :: Int -> String s4 = s2 song :: Int -> String song n | n == 0 = "" | n <10 = s1 n ++ s2 n ++ s3 n ++ s4 n | otherwise = ""
trymilix/cookbooks
Software/haskell/song.hs
apache-2.0
992
0
9
270
325
170
155
24
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Data.Word (Word8, Word16) import Data.List (unfoldr) import Data.Bits (shiftL, (.&.)) import Data.ByteString.Char8 () import Data.Monoid import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import qualified Data.Binary.BitBuilder as BB import Test.QuickCheck hiding ((.&.)) -- This test constructs random sequences of elements from the following list. -- The first element of each pair is some BitBuilder and the second element -- is a list of the bits that such a BitBuilder should append. Then we run -- the sequence of BitBuilders and concat the sequence of [Bool] and check -- that the output is the same type TestElement = (BB.BitBuilder, [Bool]) elems :: [TestElement] elems = [ (BB.singleton True, [True]) , (BB.singleton False, [False]) , (BB.fromByteString ("\x01\x02", 0), byteToBits 1 ++ byteToBits 2) , (BB.fromByteString ("\x01\x02", 4), byteToBits 1 ++ replicate 4 False) , (BB.fromByteString ("\x01\x02", 1), byteToBits 1 ++ [False]) , (BB.fromByteString ("", 0), []) , (BB.fromBits 0 (0::Int), []) , (BB.fromByteString ("\xfc", 7), replicate 6 True ++ [False]) , (BB.fromBits 7 (0xfe::Word8), replicate 6 True ++ [False]) , (BB.fromBits 3 (3::Word8), [False, True, True]) , (BB.fromBits 64 (0::Word16), replicate 64 False) ] lbsToBits = concatMap byteToBits . L.unpack byteToBits = unfoldr f . (,) 8 where f (0, _) = Nothing f (n, byte) = Just (byte .&. 0x80 == 0x80, (n-1, byte `shiftL` 1)) zeroExtend :: [Bool] -> [Bool] zeroExtend x = x ++ (replicate ((8 - (length x)) `mod` 8) False) prop_order xs = lbsToBits (BB.toLazyByteString bb) == zeroExtend list where es = map (\x -> elems !! (x `mod` (length elems))) xs bb = foldr mappend mempty $ map fst es list = concat $ map snd es main = quickCheckWith (stdArgs { maxSize = 10000}) prop_order
KrzyStar/binary-low-level
tests/BitBuilderTest.hs
bsd-3-clause
1,956
0
14
396
698
404
294
35
2
-- | This module contains any objects relating to order theory module SubHask.Algebra.Ord where import qualified Prelude as P import qualified Data.List as L import qualified GHC.Arr as Arr import Data.Array.ST hiding (freeze,thaw) import Control.Monad import Control.Monad.Random import Control.Monad.ST import Prelude (take) import SubHask.Algebra import SubHask.Category import SubHask.Mutable import SubHask.SubType import SubHask.Internal.Prelude import SubHask.TemplateHaskell.Deriving -------------------------------------------------------------------------------- -- | This wrapper let's us convert between SubHask's Ord type and the Prelude's. -- See the "sort" function below for an example. newtype WithPreludeOrd a = WithPreludeOrd { unWithPreludeOrd :: a } deriving Storable instance Show a => Show (WithPreludeOrd a) where show (WithPreludeOrd a) = show a -- | FIXME: for some reason, our deriving mechanism doesn't work on Show here; -- It causes's Set's show to enter an infinite loop deriveHierarchyFiltered ''WithPreludeOrd [ ''Eq_, ''Enum, ''Boolean, ''Ring, ''Metric ] [ ''Show ] instance Eq a => P.Eq (WithPreludeOrd a) where {-# INLINE (==) #-} a==b = a==b instance Ord a => P.Ord (WithPreludeOrd a) where {-# INLINE (<=) #-} a<=b = a<=b -- | A wrapper around the Prelude's sort function. -- -- FIXME: -- We should put this in the container hierarchy so we can sort any data type sort :: Ord a => [a] -> [a] sort = map unWithPreludeOrd . L.sort . map WithPreludeOrd -- | Randomly shuffles a list in time O(n log n); see http://www.haskell.org/haskellwiki/Random_shuffle shuffle :: (Eq a, MonadRandom m) => [a] -> m [a] shuffle xs = do let l = length xs rands <- take l `liftM` getRandomRs (0, l-1) let ar = runSTArray ( do ar <- Arr.thawSTArray (Arr.listArray (0, l-1) xs) forM_ (L.zip [0..(l-1)] rands) $ \(i, j) -> do vi <- Arr.readSTArray ar i vj <- Arr.readSTArray ar j Arr.writeSTArray ar j vi Arr.writeSTArray ar i vj return ar ) return (Arr.elems ar)
abailly/subhask
src/SubHask/Algebra/Ord.hs
bsd-3-clause
2,149
0
20
470
574
310
264
-1
-1
{- | Module : $Header$ Description : Parser of common logic interface format Copyright : (c) Karl Luc, DFKI Bremen 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable -- Tests and examples of Common Logic AS and CLIF parse -} module CommonLogic.ClTests where import CommonLogic.AS_CommonLogic import CommonLogic.Parse_CLIF import Common.Doc as Doc import Common.Id as Id import Text.ParserCombinators.Parsec -- examples for abstract syntax a :: NAME a = Token "x" nullRange b :: NAME b = Token "y" nullRange t1 :: TERM t1 = Name_term a t2 :: TERM t2 = Name_term b t3 :: TERM t3 = Name_term (Token "P" nullRange) t4 :: TERM t4 = Name_term (Token "Q" nullRange) ts1 :: TERM_SEQ ts1 = Term_seq t1 b1 :: BOOL_SENT b1 = Conjunction [s1, sa2] b2 :: BOOL_SENT b2 = Negation s1 b3 :: BOOL_SENT b3 = Implication s1 s1 s1 :: SENTENCE s1 = Atom_sent at1 nullRange sa2 :: SENTENCE sa2 = Atom_sent at2 nullRange at1 :: ATOM at1 = Atom t3 [Term_seq t1] at2 :: ATOM at2 = Atom t4 [Term_seq t2] s2 :: SENTENCE s2 = Bool_sent b1 nullRange s3 :: SENTENCE s3 = Bool_sent (Negation s1) nullRange s4 :: SENTENCE s4 = Bool_sent (Disjunction [s1, sa2]) nullRange ct :: TERM ct = Name_term (Token "Cat" nullRange) {- bs1 :: BINDING_SEQ bs1 = B_name a nullRange bs2 :: BINDING_SEQ bs2 = B_name b nullRange -} -- examples for pretty printing test :: Doc test = Doc.text "Atom:" <+> printAtom at1 $+$ Doc.text "Atom_sent:" <+> printSentence s1 $+$ Doc.text "Bool_sent:" <+> printSentence s2 $+$ Doc.text "Bool_sent:" <+> printSentence s4 $+$ Doc.text "Bool_sent:" <+> printSentence s3 $+$ Doc.text "Bool_sent:" <+> printSentence (Bool_sent (Implication s1 sa2) nullRange) $+$ Doc.text "Bool_sent:" <+> printSentence (Bool_sent (Biconditional s1 sa2) nullRange) $+$ Doc.text "Quant_sent:" <+> printSentence (Quant_sent (Existential [] s1) nullRange) $+$ Doc.text "Quant_sent:" <+> printSentence (Quant_sent (Universal [] s1) nullRange) $+$ Doc.text "Equation:" <+> printAtom (Equation t1 t1) $+$ Doc.text "Functional Term:" <+> printTerm (Funct_term t1 [ts1] nullRange) $+$ Doc.text "Sentence Functional:" <+> printSentence ( Atom_sent (Atom (Funct_term t1 [ts1] nullRange) [Term_seq t1]) nullRange) -- examples for CLIF parser p1 = parseTest sentence "(P x)" p2 = parseTest sentence "(and (P x) (Q y))" p3 = parseTest sentence "(or (Cat x) (Mat y))" p4 = parseTest sentence "(not (On x y))" p5 = parseTest sentence "(if (P x) (Q x))" p6 = parseTest sentence "(exists (z) (and (Pet x) (Happy z) (Attr x z)))" -- helper functions for testing sublogics -- | parses the given string abstrSyntax :: String -> Either ParseError TEXT_META abstrSyntax = parse CommonLogic.Parse_CLIF.cltext "" cParse p = parse p ""
mariefarrell/Hets
CommonLogic/ClTests.hs
gpl-2.0
2,912
0
29
586
779
400
379
70
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="de-DE"> <title>Active Scan Rules - Alpha | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Suche</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>
0xkasun/security-tools
src/org/zaproxy/zap/extension/ascanrulesAlpha/resources/help_de_DE/helpset_de_DE.hs
apache-2.0
986
80
67
163
422
213
209
-1
-1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ExtendedDefaultRules #-} -- | A first example in equalional reasoning. -- | From the definition of append we should be able to -- | semi-automatically prove the two axioms. -- | Note for soundness we need -- | totallity: all the cases should be covered -- | termination: we cannot have diverging things into proofs {-@ LIQUID "--autoproofs" @-} {-@ LIQUID "--totality" @-} {-@ LIQUID "--exact-data-cons" @-} module Append where import Axiomatize import Equational import Prelude hiding (map) data L a = N | C a (L a) instance Eq a => Eq (L a) where N == N = True (C x xs) == (C x' xs') = x == x' && xs == xs' {-@ axiomatize map @-} $(axiomatize [d| map :: (a -> b) -> L a -> L b map f N = N map f (C x xs) = f x `C` map f xs |]) -- axioms: -- axiom_map_N :: forall f. map f N == N -- axiom_map_C :: forall f x xs. map f (C x xs) == C (f x) (map f xs) {-@ axiomatize compose @-} $(axiomatize [d| compose :: (b -> c) ->(a -> b) -> (a -> c) compose f g x = f (g x) |]) {-@ prop_fusion :: f:(a -> a) -> g:(a -> a) -> xs:L a -> {v:Proof | map f (map g xs) == map (compose f g) xs } @-} prop_fusion :: Eq a => (a -> a) -> (a -> a) -> L a -> Proof prop_fusion f g N = -- refl e1 `by` pr1 `by` pr2 `by` pr3 auto 2 (map f (map g N) == map (compose f g) N) {- where e1 = map f (map g N) pr1 = axiom_map_N g e2 = map f N pr2 = axiom_map_N f e3 = N pr3 = axiom_map_N (compose f g) e4 = map (compose f g) N -} prop_fusion f g (C x xs) = auto 2 (map f (map g (C x xs)) == map (compose f g) (C x xs)) -- refl e1 `by` pr1 `by` pr2 `by` pr3 `by` pr4 `by` pr5 {- where e1 = map f (map g (C x xs)) pr1 = axiom_map_C g x xs e2 = map f (C (g x) (map g xs)) pr2 = axiom_map_C f (g x) (map g xs) e3 = C (f (g x)) (map f (map g xs)) pr3 = prop_fusion f g xs e4 = C (f (g x)) (map (compose f g) xs) pr4 = axiom_compose f g x e5 = C ((compose f g) x) (map (compose f g) xs) pr5 = axiom_map_C (compose f g) x xs e6 = map (compose f g) (C x xs) -} {-@ data L [llen] @-} {-@ invariant {v: L a | llen v >= 0} @-} {-@ measure llen @-} llen :: L a -> Int llen N = 0 llen (C x xs) = 1 + llen xs
abakst/liquidhaskell
tests/equationalproofs/pos/MapFusion.hs
bsd-3-clause
2,338
0
12
733
371
201
170
25
1
module Lib where data Value = Finite Integer | Infinity deriving (Eq) instance Num Value where (+) = undefined (*) = undefined abs = undefined signum = undefined negate = undefined fromInteger = Finite -- | @litCon _@ should not elicit an overlapping patterns warning when it -- passes through the LitCon case. litCon :: Value -> Bool litCon Infinity = True litCon 0 = True litCon _ = False -- | @conLit Infinity@ should not elicit an overlapping patterns warning when -- it passes through the ConLit case. conLit :: Value -> Bool conLit 0 = True conLit Infinity = True conLit _ = False
sdiehl/ghc
testsuite/tests/pmcheck/should_compile/T16289.hs
bsd-3-clause
667
0
6
186
135
78
57
18
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="ja-JP"> <title>FuzzDB Files</title> <maps> <homeID>fuzzdb</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/fuzzdb/src/main/javahelp/help_ja_JP/helpset_ja_JP.hs
apache-2.0
960
77
66
156
407
206
201
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE Trustworthy #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Functor.Identity -- Copyright : (c) Andy Gill 2001, -- (c) Oregon Graduate Institute of Science and Technology 2001 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- The identity functor and monad. -- -- This trivial type constructor serves two purposes: -- -- * It can be used with functions parameterized by functor or monad classes. -- -- * It can be used as a base monad to which a series of monad -- transformers may be applied to construct a composite monad. -- Most monad transformer modules include the special case of -- applying the transformer to 'Identity'. For example, @State s@ -- is an abbreviation for @StateT s 'Identity'@. -- -- @since 4.8.0.0 ----------------------------------------------------------------------------- module Data.Functor.Identity ( Identity(..), ) where import Control.Monad.Fix import Data.Bits (Bits, FiniteBits) import Data.Coerce import Data.Foldable import Data.Functor.Utils ((#.)) import Foreign.Storable (Storable) import GHC.Arr (Ix) import GHC.Base ( Applicative(..), Eq(..), Functor(..), Monad(..) , Monoid, Ord(..), ($), (.) ) import GHC.Enum (Bounded, Enum) import GHC.Float (Floating, RealFloat) import GHC.Generics (Generic, Generic1) import GHC.Num (Num) import GHC.Read (Read(..), lex, readParen) import GHC.Real (Fractional, Integral, Real, RealFrac) import GHC.Show (Show(..), showParen, showString) import GHC.Types (Bool(..)) -- | Identity functor and monad. (a non-strict monad) -- -- @since 4.8.0.0 newtype Identity a = Identity { runIdentity :: a } deriving ( Bits, Bounded, Enum, Eq, FiniteBits, Floating, Fractional , Generic, Generic1, Integral, Ix, Monoid, Num, Ord , Real, RealFrac, RealFloat, Storable) -- | This instance would be equivalent to the derived instances of the -- 'Identity' newtype if the 'runIdentity' field were removed -- -- @since 4.8.0.0 instance (Read a) => Read (Identity a) where readsPrec d = readParen (d > 10) $ \ r -> [(Identity x,t) | ("Identity",s) <- lex r, (x,t) <- readsPrec 11 s] -- | This instance would be equivalent to the derived instances of the -- 'Identity' newtype if the 'runIdentity' field were removed -- -- @since 4.8.0.0 instance (Show a) => Show (Identity a) where showsPrec d (Identity x) = showParen (d > 10) $ showString "Identity " . showsPrec 11 x -- --------------------------------------------------------------------------- -- Identity instances for Functor and Monad -- | @since 4.8.0.0 instance Foldable Identity where foldMap = coerce elem = (. runIdentity) #. (==) foldl = coerce foldl' = coerce foldl1 _ = runIdentity foldr f z (Identity x) = f x z foldr' = foldr foldr1 _ = runIdentity length _ = 1 maximum = runIdentity minimum = runIdentity null _ = False product = runIdentity sum = runIdentity toList (Identity x) = [x] -- | @since 4.8.0.0 instance Functor Identity where fmap = coerce -- | @since 4.8.0.0 instance Applicative Identity where pure = Identity (<*>) = coerce -- | @since 4.8.0.0 instance Monad Identity where m >>= k = k (runIdentity m) -- | @since 4.8.0.0 instance MonadFix Identity where mfix f = Identity (fix (runIdentity . f))
olsner/ghc
libraries/base/Data/Functor/Identity.hs
bsd-3-clause
3,919
0
11
952
785
470
315
60
0
import Control.Exception import System.Environment import Control.Monad.Par.Scheds.Trace -- NB. using Trace here, Direct is too strict and forces the fibs in -- the parent; see https://github.com/simonmar/monad-par/issues/27 -- <<fib fib :: Integer -> Integer fib 0 = 1 fib 1 = 1 fib n = fib (n-1) + fib (n-2) -- >> main = do args <- getArgs let [n,m] = map read args print $ -- <<runPar runPar $ do i <- new -- <1> j <- new -- <1> fork (put i (fib n)) -- <2> fork (put j (fib m)) -- <2> a <- get i -- <3> b <- get j -- <3> return (a+b) -- <4> -- >>
lywaterman/parconc-examples
parmonad.hs
bsd-3-clause
747
0
14
308
220
113
107
19
1
{-# LANGUAGE TemplateHaskell #-} module T15502 where import Language.Haskell.TH.Syntax (Lift(lift)) main = print ( $( lift (toInteger (maxBound :: Int) + 1) ) , $( lift (minBound :: Int) ) )
sdiehl/ghc
testsuite/tests/th/T15502.hs
bsd-3-clause
221
0
13
61
71
42
29
5
1
{-# LANGUAGE TypeFamilies #-} module C where import A data C type instance F (a,C) = Bool
shlevy/ghc
testsuite/tests/driver/recomp017/C2.hs
bsd-3-clause
90
0
5
17
27
18
9
-1
-1
{-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-unbox-small-strict-fields #-} -- Makes f2 a bit more challenging module Foo where h :: Int -> Int -> Bool h 0 y = y>0 h n y = h (n-1) y -- The main point: all of these functions can have the CPR property ------- f1 ----------- -- x is used strictly by h, so it'll be available -- unboxed before it is returned in the True branch f1 :: Int -> Int f1 x = case h x x of True -> x False -> f1 (x-1) ------- f2 ----------- -- x is a strict field of MkT2, so we'll pass it unboxed -- to $wf2, so it's available unboxed. This depends on -- the case expression analysing (a subcomponent of) one -- of the original arguments to the function, so it's -- a bit more delicate. data T2 = MkT2 !Int Int f2 :: T2 -> Int f2 (MkT2 x y) | y>0 = f2 (MkT2 x (y-1)) | y>1 = 1 | otherwise = x ------- f3 ----------- -- h is strict in x, so x will be unboxed before it -- is rerturned in the otherwise case. data T3 = MkT3 Int Int f1 :: T3 -> Int f1 (MkT3 x y) | h x y = f3 (MkT3 x (y-1)) | otherwise = x ------- f4 ----------- -- Just like f2, but MkT4 can't unbox its strict -- argument automatically, as f2 can data family Foo a newtype instance Foo Int = Foo Int data T4 a = MkT4 !(Foo a) Int f4 :: T4 Int -> Int f4 (MkT4 x@(Foo v) y) | y>0 = f4 (MkT4 x (y-1)) | otherwise = v
urbanslug/ghc
testsuite/tests/stranal/T10482a.hs
bsd-3-clause
1,448
0
10
424
392
206
186
29
2
import Control.Exception import Control.DeepSeq main = evaluate (('a' : undefined) `deepseq` return () :: IO ())
ezyang/ghc
testsuite/tests/simplCore/should_fail/T7411.hs
bsd-3-clause
113
0
9
16
48
26
22
3
1
-- !!! Monomorphism restriction -- This one should work fine, despite the monomorphism restriction -- Fails with GHC 5.00.1 module Test where import Control.Monad.ST import Data.STRef -- Should get -- apa :: forall s. ST s () apa = newSTRef () >> return () foo1 = runST apa
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/typecheck/should_compile/tc132.hs
bsd-3-clause
278
0
7
52
47
28
19
5
1
module ShouldSucceed where f x = a a = (x,x) x = x
urbanslug/ghc
testsuite/tests/typecheck/should_compile/tc021.hs
bsd-3-clause
54
0
5
16
28
17
11
4
1
module Main where import Tracks.Network import Tracks.Service import Tracks.Train import Tracks.Signals (Signals) import qualified Tracks.Signals as Signals import Control.Monad.STM import Control.Concurrent import qualified STMContainers.Set as Set import System.Random foxhole, riverford, tunwall, maccton, welbridge :: Station foxhole = Station "Foxhole" riverford = Station "Riverford" tunwall = Station "Tunwall" maccton = Station "Maccton" welbridge = Station "Welbridge" foxLine, newLine :: Line foxLine = Line "Fox" newLine = Line "New" main :: IO () main = do network <- readTracksFile "test.tracks" services <- readServicesFile "test.services" putStrLn $ writeTracksCommands network signals <- atomically Signals.clear forkIO $ startTrain "001" foxLine 1 services signals network forkIO $ startTrain "002" foxLine 1 services signals network forkIO $ startTrain "A01" newLine 1 services signals network getLine return () startTrain :: String -> Line -> Int -> Services -> Signals -> Network -> IO () startTrain name line num services signals network = do let service = getLineService num line services train <- atomically $ placeTrain name service line signals network case train of Just t -> do print t runTrain t Nothing -> do threadDelay (500 * 1000) startTrain name line num services signals network runTrain :: Train -> IO () runTrain train = do train' <- atomically $ stepTrain train print train' gen <- newStdGen let (delay, _) = randomR (200000, 500000) gen threadDelay delay runTrain train'
derkyjadex/tracks
Main.hs
mit
1,749
0
14
460
506
250
256
49
2
import Algorithms.MDP.Examples.Ex_3_1 import Algorithms.MDP import Algorithms.MDP.ValueIteration import qualified Data.Vector as V converging :: Double -> (CF State Control Double, CF State Control Double) -> Bool converging tol (cf, cf') = abs (x - y) > tol where x = (\(_, _, c) -> c) (cf V.! 0) y = (\(_, _, c) -> c) (cf' V.! 0) iterations = valueIteration mdp main = do mapM_ (putStrLn . showAll) $ take 100 iterations where showCosts cf = V.map (\(_, _, c) -> c) cf showActions cf = V.map (\(_, a, _) -> a) cf showAll cf = show (showCosts cf) ++ " " ++ show (showActions cf)
prsteele/mdp
src/run-ex-3-1.hs
mit
634
0
11
160
295
162
133
16
1