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 : ChainFlyer
Copyright : (c) Tatsuya Hirose, 2015
License : BSD3
Maintainer : [email protected]
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module Servant.ChainFlyer.Types.Block
( Block(..)
) where
import Control.Monad (mzero)
import Data.Aeson
import Data.Time.Clock
import Data.Time.Format
import GHC.Generics
-- | Block.
data Block = Block
{ block_hash :: String
, height :: Int
, is_main :: Bool
, version :: Int
, prev_block :: String
, markle_root :: String
, timestamp :: UTCTime
, bits :: Integer
, nonce :: Integer
, txnum :: Int
, total_fees :: Integer
, tx_hashes :: [String]
} deriving (Show, Generic)
instance FromJSON Block where
parseJSON (Object v) = Block
<$> v .: "block_hash"
<*> v .: "height"
<*> v .: "is_main"
<*> v .: "version"
<*> v .: "prev_block"
<*> v .: "merkle_root"
<*> (v .: "timestamp" >>= parseTimeM True defaultTimeLocale "%Y-%m-%dT%H:%M:%SZ")
<*> v .: "bits"
<*> v .: "nonce"
<*> v .: "txnum"
<*> v .: "total_fees"
<*> v .: "tx_hashes"
parseJSON _ = mzero
instance ToJSON Block
|
lotz84/chainFlyer
|
src/Servant/ChainFlyer/Types/Block.hs
|
bsd-3-clause
| 1,437 | 0 | 28 | 546 | 295 | 170 | 125 | 39 | 0 |
module Data.Aeson.Versions.CatMaybes where
import Data.Functor.Identity
import Data.Foldable
import Data.Traversable
import Data.Maybe
import Prelude hiding (sequence)
-- | Generalization of catMaybes that allows to remove `Nothings`
-- from singleton types
class Functor f => CatMaybes f where
catMaybes' :: f (Maybe a) -> Maybe (f a)
instance CatMaybes Maybe where
catMaybes' = sequence
instance CatMaybes Identity where
catMaybes' = sequence
instance CatMaybes [] where
catMaybes' = Just . catMaybes
|
vfiles/aeson-versioned
|
src/Data/Aeson/Versions/CatMaybes.hs
|
bsd-3-clause
| 519 | 0 | 10 | 84 | 128 | 71 | 57 | 14 | 0 |
-- |
-- Module: FRP.Netwire.Move
-- Copyright: (c) 2013 Ertugrul Soeylemez
-- License: BSD3
-- Maintainer: Ertugrul Soeylemez <[email protected]>
module FRP.Netwire.Move
( -- * Calculus
derivative,
integral,
integralWith
)
where
import Control.Wire
-- | Time derivative of the input signal.
--
-- * Depends: now.
--
-- * Inhibits: at singularities.
derivative ::
(RealFloat a, HasTime t s, Monoid e)
=> Wire s e m a a
derivative = mkPure $ \_ x -> (Left mempty, loop' x)
where
loop' x' =
mkPure $ \ds x ->
let dt = realToFrac (dtime ds)
dx = (x - x') / dt
mdx | isNaN dx = Right 0
| isInfinite dx = Left mempty
| otherwise = Right dx
in mdx `seq` (mdx, loop' x)
-- | Integrate the input signal over time.
--
-- * Depends: before now.
integral ::
(Fractional a, HasTime t s)
=> a -- ^ Integration constant (aka start value).
-> Wire s e m a a
integral x' =
mkPure $ \ds dx ->
let dt = realToFrac (dtime ds)
in x' `seq` (Right x', integral (x' + dt*dx))
-- | Integrate the left input signal over time, but apply the given
-- correction function to it. This can be used to implement collision
-- detection/reaction.
--
-- The right signal of type @w@ is the /world value/. It is just passed
-- to the correction function for reference and is not used otherwise.
--
-- The correction function must be idempotent with respect to the world
-- value: @f w (f w x) = f w x@. This is necessary and sufficient to
-- protect time continuity.
--
-- * Depends: before now.
integralWith ::
(Fractional a, HasTime t s)
=> (w -> a -> a) -- ^ Correction function.
-> a -- ^ Integration constant (aka start value).
-> Wire s e m (a, w) a
integralWith correct = loop'
where
loop' x' =
mkPure $ \ds (dx, w) ->
let dt = realToFrac (dtime ds)
x = correct w (x' + dt*dx)
in x' `seq` (Right x', loop' x)
|
Teaspot-Studio/netwire
|
FRP/Netwire/Move.hs
|
bsd-3-clause
| 2,077 | 0 | 16 | 650 | 492 | 269 | 223 | 37 | 1 |
module RoundTripSpec (main, spec) where
import Test.Hspec
import Language.Haskell.Refact.Refactoring.RoundTrip
import TestUtils
main :: IO ()
main = do
hspec spec
spec :: Spec
spec = do
describe "roundtrip" $ do
it "roundtrips B" $ do
r <- ct $ roundTrip defaultTestSettings testOptions "Case/BSimpleExpected.hs"
-- r <- ct $ roundTrip logTestSettings testOptions "Case/BSimpleExpected.hs"
r `shouldBe` ["Case/BSimpleExpected.hs"]
diff <- compareFiles "./test/testdata/Case/BSimpleExpected.refactored.hs"
"./test/testdata/Case/BSimpleExpected.hs"
diff `shouldBe` []
-- ---------------------------------
it "roundtrips FooExpected" $ do
r <- ct $ roundTrip defaultTestSettings testOptions "Case/FooExpected.hs"
-- r <- ct $ roundTrip logTestSettings testOptions "Case/FooExpected.hs"
r `shouldBe` ["Case/FooExpected.hs"]
diff <- compareFiles "./test/testdata/Case/FooExpected.refactored.hs"
"./test/testdata/Case/FooExpected.hs"
diff `shouldBe` []
-- ---------------------------------
it "roundtrips FExpected" $ do
r <- ct $ roundTrip defaultTestSettings testOptions "Case/FExpected.hs"
-- r <- ct $ roundTrip logTestSettings testOptions "Case/FExpected.hs"
r `shouldBe` ["Case/FExpected.hs"]
diff <- compareFiles "./test/testdata/Case/FExpected.refactored.hs"
"./test/testdata/Case/FExpected.hs"
diff `shouldBe` []
-- ---------------------------------
it "roundtrips CExpected" $ do
r <- ct $ roundTrip defaultTestSettings testOptions "Case/CExpected.hs"
-- r <- ct $ roundTrip logTestSettings testOptions "Case/CExpected.hs"
r `shouldBe` ["Case/CExpected.hs"]
diff <- compareFiles "./test/testdata/Case/CExpected.refactored.hs"
"./test/testdata/Case/CExpected.hs"
diff `shouldBe` []
-- ---------------------------------
{-
it "roundtrips Zipper.hs" $ do
r <- cdAndDo "/home/alanz/tmp/hackage/syz-0.2.0.0/" $ roundTrip defaultTestSettings testOptions "./Data/Generics/Zipper.hs"
r `shouldBe` ["./Data/Generics/Zipper.hs"]
diff <- compareFiles "/home/alanz/tmp/hackage/syz-0.2.0.0/Data/Generics/Zipper.refactored.hs"
"/home/alanz/tmp/hackage/syz-0.2.0.0/Data/Generics/Zipper.hs"
diff `shouldBe` []
-}
-- ---------------------------------
-- ---------------------------------------------------------------------
-- Helper functions
|
mpickering/HaRe
|
test/RoundTripSpec.hs
|
bsd-3-clause
| 2,578 | 0 | 15 | 551 | 333 | 171 | 162 | 34 | 1 |
module Main where
import Game
import Rendering
import System.Console.ANSI
import System.Random
runLoop :: RandomGen g => (GameBoard, Bool, Integer, Bool, g) -> IO ()
runLoop (board, _, score, True, _) = do
clearScreen
putStr "\n"
putStr $ printBoard board
putStrLn $ "Score: " ++ (show score)
putStrLn $ "No more moves!"
runLoop (board, movementMade, score, gameFinished, g) = do
clearScreen
putStr "\n"
putStr $ printBoard board
putStrLn $ "Score: " ++ (show score)
key <- getChar
case key of
'q' -> return ()
'a' -> runLoop $ updateBoard g board MovementLeft score
'w' -> runLoop $ updateBoard g board MovementUp score
's' -> runLoop $ updateBoard g board MovementDown score
'd' -> runLoop $ updateBoard g board MovementRight score
main :: IO ()
main = do
stdGen <- newStdGen
runLoop $ initGame stdGen
|
anuraags/hs2048
|
app/Main.hs
|
bsd-3-clause
| 929 | 0 | 11 | 258 | 315 | 157 | 158 | 28 | 5 |
module Data.Blockchain.Types
( module Data.Blockchain.Types.Blockchain
, module Data.Blockchain.Types.Block
, module Data.Blockchain.Types.BlockchainConfig
, module Data.Blockchain.Types.Difficulty
, module Data.Blockchain.Types.Hex
, module Data.Blockchain.Types.Transaction
) where
import Data.Blockchain.Types.Block
import Data.Blockchain.Types.Blockchain
import Data.Blockchain.Types.BlockchainConfig
import Data.Blockchain.Types.Difficulty
import Data.Blockchain.Types.Hex
import Data.Blockchain.Types.Transaction
|
TGOlson/blockchain
|
lib/Data/Blockchain/Types.hs
|
bsd-3-clause
| 548 | 0 | 5 | 63 | 99 | 72 | 27 | 13 | 0 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
-- Perform a build
module Stack.Build.Execute
( printPlan
, executePlan
) where
import Control.Concurrent (forkIO, getNumCapabilities)
import Control.Concurrent.Execute
import Control.Concurrent.MVar.Lifted
import Control.Concurrent.STM
import Control.Exception.Lifted
import Control.Monad
import Control.Monad.Catch (MonadCatch, MonadMask)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans.Control (liftBaseWith)
import Control.Monad.Trans.Resource
import Control.Monad.Writer
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import Data.Conduit
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.List as CL
import Data.Function
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import qualified Data.Map.Strict as Map
import Data.Maybe
import qualified Data.Set as Set
import Data.Streaming.Process hiding (callProcess, env)
import qualified Data.Streaming.Process as Process
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Distribution.System (OS (Windows),
Platform (Platform))
import Network.HTTP.Client.Conduit (HasHttpManager)
import Path
import Prelude hiding (FilePath, writeFile)
import Stack.Build.Cache
import Stack.Build.Installed
import Stack.Build.Types
import Stack.Constants
import Stack.Fetch as Fetch
import Stack.GhcPkg
import Stack.Package
import Stack.Types
import Stack.Types.Internal
import System.Directory hiding (findExecutable,
findFiles)
import System.Exit (ExitCode (ExitSuccess))
import System.IO
import System.IO.Temp (withSystemTempDirectory)
import System.Process.Internals (createProcess_)
import System.Process.Read
type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,HasBuildConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,MonadMask m,HasLogLevel env)
printPlan :: M env m => Plan -> m ()
printPlan plan = do
case Set.toList $ planUnregisterLocal plan of
[] -> $logInfo "Nothing to unregister"
xs -> do
$logInfo "Would unregister locally:"
mapM_ ($logInfo . T.pack . ghcPkgIdString) xs
$logInfo ""
case Map.elems $ planTasks plan of
[] -> $logInfo "Nothing to build"
xs -> do
$logInfo "Would build:"
mapM_ ($logInfo . displayTask) xs
-- | For a dry run
displayTask :: Task -> Text
displayTask task = T.pack $ concat
[ packageIdentifierString $ taskProvides task
, ": database="
, case taskLocation task of
Snap -> "snapshot"
Local -> "local"
, ", source="
, case taskType task of
TTLocal lp steps -> concat
[ toFilePath $ lpDir lp
, case steps of
AllSteps -> " (configure)"
SkipConfig -> " (build)"
JustFinal -> " (already built)"
]
TTUpstream _ _ -> "package index"
, if Set.null missing
then ""
else ", after: " ++ intercalate "," (map packageIdentifierString $ Set.toList missing)
]
where
missing = tcoMissing $ taskConfigOpts task
data ExecuteEnv = ExecuteEnv
{ eeEnvOverride :: !EnvOverride
, eeConfigureLock :: !(MVar ())
, eeInstallLock :: !(MVar ())
, eeBuildOpts :: !BuildOpts
, eeBaseConfigOpts :: !BaseConfigOpts
, eeGhcPkgIds :: !(TVar (Map PackageIdentifier Installed))
, eeTempDir :: !(Path Abs Dir)
, eeSetupHs :: !(Path Abs File)
, eeCabalPkgVer :: !PackageIdentifier
, eeTotalWanted :: !Int
}
-- | Perform the actual plan
executePlan :: M env m
=> EnvOverride
-> BuildOpts
-> BaseConfigOpts
-> PackageIdentifier -- ^ cabal version
-> [LocalPackage]
-> Plan
-> m ()
executePlan menv bopts baseConfigOpts cabalPkgVer locals plan =
withSystemTempDirectory stackProgName $ \tmpdir -> do
tmpdir' <- parseAbsDir tmpdir
configLock <- newMVar ()
installLock <- newMVar ()
idMap <- liftIO $ newTVarIO M.empty
let setupHs = tmpdir' </> $(mkRelFile "Setup.hs")
liftIO $ writeFile (toFilePath setupHs) "import Distribution.Simple\nmain = defaultMain"
executePlan' plan ExecuteEnv
{ eeEnvOverride = menv
, eeBuildOpts = bopts
-- Uncertain as to why we cannot run configures in parallel. This appears
-- to be a Cabal library bug. Original issue:
-- https://github.com/fpco/stack/issues/84. Ideally we'd be able to remove
-- this.
, eeConfigureLock = configLock
, eeInstallLock = installLock
, eeBaseConfigOpts = baseConfigOpts
, eeGhcPkgIds = idMap
, eeTempDir = tmpdir'
, eeSetupHs = setupHs
, eeCabalPkgVer = cabalPkgVer
, eeTotalWanted = length $ filter lpWanted locals
}
-- | Perform the actual plan (internal)
executePlan' :: M env m
=> Plan
-> ExecuteEnv
-> m ()
executePlan' plan ee = do
case Set.toList $ planUnregisterLocal plan of
[] -> return ()
ids -> do
localDB <- packageDatabaseLocal
forM_ ids $ \id' -> do
$logInfo $ T.concat
[ T.pack $ ghcPkgIdString id'
, ": unregistering"
]
unregisterGhcPkgId (eeEnvOverride ee) localDB id'
-- Yes, we're explicitly discarding result values, which in general would
-- be bad. monad-unlift does this all properly at the type system level,
-- but I don't want to pull it in for this one use case, when we know that
-- stack always using transformer stacks that are safe for this use case.
runInBase <- liftBaseWith $ \run -> return (void . run)
let actions = concatMap (toActions runInBase ee) $ Map.elems $ planTasks plan
threads <- liftIO getNumCapabilities -- TODO make a build opt to override this
errs <- liftIO $ runActions threads actions
unless (null errs) $ throwM $ ExecutionFailure errs
toActions :: M env m
=> (m () -> IO ())
-> ExecuteEnv
-> Task
-> [Action]
toActions runInBase ee task@Task {..} =
-- TODO in the future, we need to have proper support for cyclic
-- dependencies from test suites, in which case we'll need more than one
-- Action here
[ Action
{ actionId = ActionId taskProvides ATBuild
, actionDeps =
(Set.map (\ident -> ActionId ident ATBuild) (tcoMissing taskConfigOpts))
, actionDo = \ac -> runInBase $ singleBuild ac ee task
}
]
singleBuild :: M env m
=> ActionContext
-> ExecuteEnv
-> Task
-> m ()
singleBuild ActionContext {..} ExecuteEnv {..} task@Task {..} =
withPackage $ \package cabalfp pkgDir ->
withLogFile package $ \mlogFile ->
withCabal pkgDir mlogFile $ \cabal -> do
mconfigOpts <- if needsConfig
then withMVar eeConfigureLock $ \_ -> do
deleteCaches pkgDir
idMap <- liftIO $ readTVarIO eeGhcPkgIds
let getMissing ident =
case Map.lookup ident idMap of
Nothing -> error "singleBuild: invariant violated, missing package ID missing"
Just (Library x) -> Just x
Just Executable -> Nothing
missing' = Set.fromList $ mapMaybe getMissing $ Set.toList missing
TaskConfigOpts missing mkOpts = taskConfigOpts
configOpts = mkOpts missing'
allDeps = Set.union missing' taskPresent
announce "configure"
cabal False $ "configure" : map T.unpack configOpts
$logDebug $ T.pack $ show configOpts
writeConfigCache pkgDir configOpts allDeps
return $ Just (configOpts, allDeps)
else return Nothing
fileModTimes <- getPackageFileModTimes package cabalfp
writeBuildCache pkgDir fileModTimes
unless justFinal $ do
announce "build"
config <- asks getConfig
cabal (console && configHideTHLoading config) ["build"]
case boptsFinalAction eeBuildOpts of
DoTests -> when wanted $ do
announce "test"
runTests package pkgDir mlogFile
DoBenchmarks -> when wanted $ do
announce "benchmarks"
cabal False ["bench"]
DoHaddock -> do
announce "haddock"
hscolourExists <- doesExecutableExist eeEnvOverride "hscolour"
{- EKB TODO: doc generation for stack-doc-server
#ifndef mingw32_HOST_OS
liftIO (removeDocLinks docLoc package)
#endif
ifcOpts <- liftIO (haddockInterfaceOpts docLoc package packages)
-}
cabal False (concat [["haddock", "--html"]
,["--hyperlink-source" | hscolourExists]])
{- EKB TODO: doc generation for stack-doc-server
,"--hoogle"
,"--html-location=../$pkg-$version/"
,"--haddock-options=" ++ intercalate " " ifcOpts ]
haddockLocs <-
liftIO (findFiles (packageDocDir package)
(\loc -> FilePath.takeExtensions (toFilePath loc) ==
"." ++ haddockExtension)
(not . isHiddenDir))
forM_ haddockLocs $ \haddockLoc ->
do let hoogleTxtPath = FilePath.replaceExtension (toFilePath haddockLoc) "txt"
hoogleDbPath = FilePath.replaceExtension hoogleTxtPath hoogleDbExtension
hoogleExists <- liftIO (doesFileExist hoogleTxtPath)
when hoogleExists
(callProcess
"hoogle"
["convert"
,"--haddock"
,hoogleTxtPath
,hoogleDbPath])
-}
{- EKB TODO: doc generation for stack-doc-server
#ifndef mingw32_HOST_OS
case setupAction of
DoHaddock -> liftIO (createDocLinks docLoc package)
_ -> return ()
#endif
-- | Package's documentation directory.
packageDocDir :: (MonadThrow m, MonadReader env m, HasPlatform env)
=> PackageIdentifier -- ^ Cabal version
-> Package
-> m (Path Abs Dir)
packageDocDir cabalPkgVer package' = do
dist <- distDirFromDir cabalPkgVer (packageDir package')
return (dist </> $(mkRelDir "doc/"))
--}
DoNothing -> return ()
unless justFinal $ withMVar eeInstallLock $ \_ -> do
announce "install"
cabal False ["install"]
-- It seems correct to leave this outside of the "justFinal" check above,
-- in case another package depends on a justFinal target
let pkgDbs =
case taskLocation task of
Snap -> [bcoSnapDB eeBaseConfigOpts]
Local ->
[ bcoSnapDB eeBaseConfigOpts
, bcoLocalDB eeBaseConfigOpts
]
mpkgid <- findGhcPkgId eeEnvOverride pkgDbs (packageName package)
mpkgid' <- case (packageHasLibrary package, mpkgid) of
(False, _) -> assert (isNothing mpkgid) $ do
markExeInstalled (taskLocation task) taskProvides
return Executable
(True, Nothing) -> throwM $ Couldn'tFindPkgId $ packageName package
(True, Just pkgid) -> do
case mconfigOpts of
Nothing -> return ()
Just (configOpts, deps) -> writeFlagCache
pkgid
(map encodeUtf8 configOpts)
deps
return $ Library pkgid
liftIO $ atomically $ modifyTVar eeGhcPkgIds $ Map.insert taskProvides mpkgid'
where
announce x = $logInfo $ T.concat
[ T.pack $ packageIdentifierString taskProvides
, ": "
, x
]
needsConfig =
case taskType of
TTLocal _ y -> y == AllSteps
TTUpstream _ _ -> True
justFinal =
case taskType of
TTLocal _ JustFinal -> True
_ -> False
wanted =
case taskType of
TTLocal lp _ -> lpWanted lp
TTUpstream _ _ -> False
console = wanted && acRemaining == 0 && eeTotalWanted == 1
withPackage inner =
case taskType of
TTLocal lp _ -> inner (lpPackage lp) (lpCabalFile lp) (lpDir lp)
TTUpstream package _ -> do
mdist <- liftM Just $ distRelativeDir eeCabalPkgVer
m <- unpackPackageIdents eeEnvOverride eeTempDir mdist $ Set.singleton taskProvides
case M.toList m of
[(ident, dir)]
| ident == taskProvides -> do
let name = packageIdentifierName taskProvides
cabalfpRel <- parseRelFile $ packageNameString name ++ ".cabal"
let cabalfp = dir </> cabalfpRel
inner package cabalfp dir
_ -> error $ "withPackage: invariant violated: " ++ show m
withLogFile package inner
| console = inner Nothing
| otherwise = do
logPath <- buildLogPath package
liftIO $ createDirectoryIfMissing True $ toFilePath $ parent logPath
let fp = toFilePath logPath
bracket
(liftIO $ openBinaryFile fp WriteMode)
(liftIO . hClose)
$ \h -> inner (Just (logPath, h))
withCabal pkgDir mlogFile inner = do
config <- asks getConfig
menv <- liftIO $ configEnvOverride config EnvSettings
{ esIncludeLocals = taskLocation task == Local
, esIncludeGhcPackagePath = False
}
exeName <- liftIO $ join $ findExecutable menv "runhaskell"
distRelativeDir' <- distRelativeDir eeCabalPkgVer
msetuphs <- liftIO $ getSetupHs pkgDir
let setuphs = fromMaybe eeSetupHs msetuphs
inner $ \stripTHLoading args -> do
let fullArgs =
("-package=" ++ packageIdentifierString eeCabalPkgVer)
: "-clear-package-db"
: "-global-package-db"
-- TODO: Perhaps we want to include the snapshot package database here
-- as well
: toFilePath setuphs
: ("--builddir=" ++ toFilePath distRelativeDir')
: args
cp0 = proc (toFilePath exeName) fullArgs
cp = cp0
{ cwd = Just $ toFilePath pkgDir
, Process.env = envHelper menv
, std_in = CreatePipe
, std_out =
if stripTHLoading
then CreatePipe
else case mlogFile of
Nothing -> Inherit
Just (_, h) -> UseHandle h
, std_err =
case mlogFile of
Nothing -> Inherit
Just (_, h) -> UseHandle h
}
$logDebug $ "Running: " <> T.pack (show $ toFilePath exeName : fullArgs)
-- Use createProcess_ to avoid the log file being closed afterwards
(Just inH, moutH, Nothing, ph) <- liftIO $ createProcess_ "singleBuild" cp
liftIO $ hClose inH
case moutH of
Just outH -> assert stripTHLoading $ printWithoutTHLoading outH
Nothing -> return ()
ec <- liftIO $ waitForProcess ph
case ec of
ExitSuccess -> return ()
_ -> do
bs <- liftIO $
case mlogFile of
Nothing -> return ""
Just (logFile, h) -> do
hClose h
S.readFile $ toFilePath logFile
throwM $ CabalExitedUnsuccessfully
ec
taskProvides
exeName
fullArgs
(fmap fst mlogFile)
bs
runTests package pkgDir mlogFile = do
bconfig <- asks getBuildConfig
distRelativeDir' <- distRelativeDir eeCabalPkgVer
let buildDir = pkgDir </> distRelativeDir'
let exeExtension =
case configPlatform $ getConfig bconfig of
Platform _ Windows -> ".exe"
_ -> ""
errs <- liftM Map.unions $ forM (Set.toList $ packageTests package) $ \testName -> do
nameDir <- liftIO $ parseRelDir $ T.unpack testName
nameExe <- liftIO $ parseRelFile $ T.unpack testName ++ exeExtension
let exeName = buildDir </> $(mkRelDir "build") </> nameDir </> nameExe
exists <- liftIO $ doesFileExist $ toFilePath exeName
config <- asks getConfig
menv <- liftIO $ configEnvOverride config EnvSettings
{ esIncludeLocals = taskLocation task == Local
, esIncludeGhcPackagePath = True
}
if exists
then do
announce $ "test " <> testName
let cp = (proc (toFilePath exeName) [])
{ cwd = Just $ toFilePath pkgDir
, Process.env = envHelper menv
, std_in = CreatePipe
, std_out =
case mlogFile of
Nothing -> Inherit
Just (_, h) -> UseHandle h
, std_err =
case mlogFile of
Nothing -> Inherit
Just (_, h) -> UseHandle h
}
-- Use createProcess_ to avoid the log file being closed afterwards
(Just inH, Nothing, Nothing, ph) <- liftIO $ createProcess_ "singleBuild.runTests" cp
liftIO $ hClose inH
ec <- liftIO $ waitForProcess ph
return $ case ec of
ExitSuccess -> M.empty
_ -> M.singleton testName $ Just ec
else do
$logError $ T.concat
[ "Test suite "
, testName
, " executable not found for "
, T.pack $ packageNameString $ packageName package
]
return $ Map.singleton testName Nothing
unless (Map.null errs) $ throwM $ TestSuiteFailure taskProvides errs (fmap fst mlogFile)
-- | Grab all output from the given @Handle@ and print it to stdout, stripping
-- Template Haskell "Loading package" lines. Does work in a separate thread.
printWithoutTHLoading :: MonadIO m => Handle -> m ()
printWithoutTHLoading outH = liftIO $ void $ forkIO $
CB.sourceHandle outH
$$ CB.lines
=$ CL.filter (not . isTHLoading)
=$ CL.mapM_ S8.putStrLn
where
-- | Is this line a Template Haskell "Loading package" line
-- ByteString
isTHLoading :: S8.ByteString -> Bool
isTHLoading bs =
"Loading package " `S8.isPrefixOf` bs &&
("done." `S8.isSuffixOf` bs || "done.\r" `S8.isSuffixOf` bs)
taskLocation :: Task -> Location
taskLocation task =
case taskType task of
TTLocal _ _ -> Local
TTUpstream _ loc -> loc
-- | Ensure Setup.hs exists in the given directory. Returns an action
-- to remove it later.
getSetupHs :: Path Abs Dir -- ^ project directory
-> IO (Maybe (Path Abs File))
getSetupHs dir = do
exists1 <- doesFileExist (toFilePath fp1)
if exists1
then return $ Just fp1
else do
exists2 <- doesFileExist (toFilePath fp2)
if exists2
then return $ Just fp2
else return Nothing
where
fp1 = dir </> $(mkRelFile "Setup.hs")
fp2 = dir </> $(mkRelFile "Setup.lhs")
|
mietek/stack
|
src/Stack/Build/Execute.hs
|
bsd-3-clause
| 21,775 | 0 | 27 | 8,520 | 4,403 | 2,218 | 2,185 | 423 | 27 |
{-# LANGUAGE PartialTypeSignatures #-}
import Opwer
import Upwork
import Web.Authenticate.OAuth( Credential )
import Data.ByteString( ByteString )
import Data.String( fromString )
import Data.Maybe( Maybe( Just ) )
import System.Environment( getArgs )
import Control.Exception( catch )
import Data.Aeson( decode )
import Network.HTTP.Client( responseBody )
import Control.Applicative( (<$>) )
readQuery :: String -> [(String, String)]
readQuery = read
adaptQuery :: (String, String) -> (ByteString, Maybe ByteString)
adaptQuery (a,b) = (fromString a, (Just . fromString) b)
convertQuery = (map adaptQuery) . readQuery
askAndPrintParsed :: _ -> _ -> _ -> IO ()
askAndPrintParsed oauth credential id = do
resp <- askForJob oauth credential id
putStrLn ((parseJobDetails . responseBody) resp)
main = do
[arg] <- getArgs
queryContents <- readFile arg
OpwerCredential oauth credential <- readCredential
resp <- askForJobs oauth credential (convertQuery queryContents)
case (decode (responseBody resp) :: Maybe SearchResult) of
Nothing -> putStrLn "The input does not seem valid"
Just result -> do
mapM (\ (JobResult id) -> catch (askAndPrintParsed oauth credential id) printException) (jobs result)
return ()
|
danse/opwer
|
app/opwer-search-and-fetch.hs
|
bsd-3-clause
| 1,244 | 0 | 17 | 203 | 419 | 222 | 197 | 31 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module ProveEverywhere.Types where
import Control.Applicative (empty)
import Data.Aeson
import Data.ByteString (ByteString)
import qualified Data.HashMap.Strict as HM
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as E
import Data.Time.Clock (UTCTime)
import Network.Wai.Handler.Warp (Port)
import System.IO (Handle)
import System.Process (ProcessHandle)
import Text.Parsec (ParseError)
data Config = Config
{ configPort :: Port -- ^ port number
, configMaxNumProcs :: Maybe Int -- ^ max number of coqtop processes
, configKillTime :: Maybe Int -- ^ per minute. default is infinity
} deriving (Eq, Show)
data Coqtop = Coqtop
{ coqtopId :: Int
, coqtopStdin :: Handle
, coqtopStdout :: Handle
, coqtopStderr :: Handle
, coqtopProcessHandle :: ProcessHandle
, coqtopState :: CoqtopState
, coqtopLastModified :: UTCTime
}
instance Eq Coqtop where
c1 == c2 = coqtopId c1 == coqtopId c2
instance Show Coqtop where
show (Coqtop i _ _ _ _ st time) = unlines
[ "Coqtop {"
, " id: " ++ show i
, " state: " ++ show st
, " last_modified: " ++ show time
, "}"
]
instance ToJSON Coqtop where
toJSON coqtop = object
[ "id" .= coqtopId coqtop
, "state" .= coqtopState coqtop
, "last_modified" .= coqtopLastModified coqtop
]
-- | only test
instance FromJSON Coqtop where
parseJSON (Object v) = Coqtop <$>
v .: "id" <*>
pure undefined <*>
pure undefined <*>
pure undefined <*>
pure undefined <*>
v .: "state" <*>
v .: "last_modified"
parseJSON _ = empty
data InitialInfo = InitialInfo
{ initialInfoId :: Int -- ^ coqtop id
, initialInfoOutput :: Text -- ^ coqtop initial output
, initialInfoState :: CoqtopState -- ^ initial state
} deriving (Eq, Show)
instance ToJSON InitialInfo where
toJSON info = object
[ "id" .= initialInfoId info
, "output" .= initialInfoOutput info
, "state" .= toJSON (initialInfoState info)
]
instance FromJSON InitialInfo where
parseJSON (Object v) = InitialInfo <$>
v .: "id" <*>
v .: "output" <*>
v .: "state"
parseJSON _ = empty
-- | The data type of output of coqtop.
-- done + remain == length (sent_commands)
data CoqtopOutput = CoqtopOutput
{ coqtopOutputId :: Int -- ^ coqtop id
, coqtopOutputSucceeded :: Int -- ^ the number of succeeded commands
, coqtopOutputRemaining :: Int -- ^ the number of remaining commands
, coqtopOutputLast :: Maybe Output -- ^ last output (except error)
, coqtopOutputError :: Maybe Output -- ^ error output
, coqtopOutputState :: CoqtopState -- ^ last state
} deriving (Eq, Show)
instance ToJSON CoqtopOutput where
toJSON output = object
[ "id" .= coqtopOutputId output
, "succeeded" .= coqtopOutputSucceeded output
, "remaining" .= coqtopOutputRemaining output
, "last_output" .= coqtopOutputLast output
, "error_output" .= coqtopOutputError output
, "state" .= coqtopOutputState output
]
instance FromJSON CoqtopOutput where
parseJSON (Object v) = CoqtopOutput <$>
v .: "id" <*>
v .: "succeeded" <*>
v .: "remaining" <*>
v .:? "last_output" <*>
v .:? "error_output" <*>
v .: "state"
parseJSON _ = empty
data ServerError
= NoSuchCoqtopError Int
| PromptParseError ParseError
| RequestParseError ByteString
| NoSuchApiError [Text]
| UnknownError Text
| ExceededMaxProcsError Int
deriving (Show)
instance ToJSON ServerError where
toJSON (NoSuchCoqtopError i) = object
[ "error" .= object
[ "id" .= (0 :: Int)
, "type" .= ("NoSuchCoqtopError" :: Text)
, "message" .= ("No such coqtop id: " <> T.pack (show i))
]
]
toJSON (PromptParseError e) = object
[ "error" .= object
[ "id" .= (1 :: Int)
, "type" .= ("PromptParseError" :: Text)
, "message" .= T.pack (show e)
]
]
toJSON (RequestParseError t) = object
[ "error" .= object
[ "id" .= (2 :: Int)
, "type" .= ("RequestParseError" :: Text)
, "message" .= (E.decodeUtf8 t)
]
]
toJSON (NoSuchApiError ps) = object
[ "error" .= object
[ "id" .= (3 :: Int)
, "type" .= ("NoSuchApiError" :: Text)
, "message" .= T.intercalate "/" ps
]
]
toJSON (UnknownError t) = object
[ "error" .= object
[ "id" .= (4 :: Int)
, "type" .= ("UnknownError" :: Text)
, "message" .= t
]
]
toJSON (ExceededMaxProcsError n) = object
[ "error" .= object
[ "id" .= (5 :: Int)
, "type" .= ("ExceededMaxProcsError" :: Text)
, "message" .= ("Exceeded max number of coqtop processes: " <> T.pack (show n))
]
]
data CoqtopState = CoqtopState
{ promptCurrentTheorem :: Text
, promptWholeStateNumber :: Integer
, promptTheoremStack :: [Text]
, promptTheoremStateNumber :: Integer
} deriving (Eq, Show)
instance ToJSON CoqtopState where
toJSON prompt = object
[ "current_theorem" .= promptCurrentTheorem prompt
, "whole_state_number" .= promptWholeStateNumber prompt
, "theorem_stack" .= promptTheoremStack prompt
, "theorem_state_number" .= promptTheoremStateNumber prompt
]
instance FromJSON CoqtopState where
parseJSON (Object v) = CoqtopState <$>
v .: "current_theorem" <*>
v .: "whole_state_number" <*>
v .: "theorem_stack" <*>
v .: "theorem_state_number"
parseJSON _ = empty
data Command = Command Text deriving (Eq, Show)
instance ToJSON Command where
toJSON (Command t) = object
[ "command" .= t
]
instance FromJSON Command where
parseJSON (Object v) = Command <$>
v .: "command"
parseJSON _ = mempty
data Output = Output
{ outputType :: OutputType
, outputText :: Text
} deriving (Eq, Show)
instance ToJSON Output where
toJSON output = object
[ "type" .= outputType output
, "output" .= outputText output
]
instance FromJSON Output where
parseJSON (Object v) = Output <$>
v .: "type" <*>
v .: "output"
parseJSON _ = empty
data OutputType = ErrorOutput
| InfoOutput
| ProofOutput
deriving (Eq, Show)
instance ToJSON OutputType where
toJSON ErrorOutput = String "error"
toJSON InfoOutput = String "info"
toJSON ProofOutput = String "proof"
instance FromJSON OutputType where
parseJSON (String "error") = pure ErrorOutput
parseJSON (String "info") = pure InfoOutput
parseJSON (String "proof") = pure ProofOutput
parseJSON _ = empty
data EmptyObject = EmptyObject deriving (Eq, Show)
instance ToJSON EmptyObject where
toJSON EmptyObject = object []
instance FromJSON EmptyObject where
parseJSON (Object v) | HM.null v = pure EmptyObject
parseJSON _ = empty
|
prove-everywhere/server
|
src/ProveEverywhere/Types.hs
|
bsd-3-clause
| 8,024 | 0 | 17 | 2,864 | 1,899 | 1,019 | 880 | 191 | 0 |
module Data.Blockchain.Crypto.ECDSASpec (spec) where
import TestUtil
import Data.Blockchain.Crypto
spec :: Spec
spec =
describe "Data.Blockchain.Crypto.ECDSA" $ do
safeJSONDeserializeSpec (Proxy :: Proxy PublicKey)
safeJSONDeserializeSpec (Proxy :: Proxy PrivateKey)
safeJSONDeserializeSpec (Proxy :: Proxy Signature)
roundTripJSONSpec (Proxy :: Proxy PublicKey)
roundTripJSONSpec (Proxy :: Proxy PrivateKey)
roundTripJSONSpec (Proxy :: Proxy Signature)
propNumTests 5 "should sign and verify correctly" $
\bs -> ioProperty $ do
(KeyPair publicKey privateKey) <- generate
sig <- sign privateKey bs
return $ verify publicKey sig bs
|
TGOlson/blockchain
|
test/Data/Blockchain/Crypto/ECDSASpec.hs
|
bsd-3-clause
| 756 | 0 | 15 | 201 | 191 | 94 | 97 | 17 | 1 |
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric, TemplateHaskell, TypeFamilies #-}
module Ext.TH where
import Data.Typeable
import GHC.Generics
import Language.Haskell.TH.Name.CamelCase (conCamelcaseName, ConName)
-- | derivingGeneric
derivingGeneric :: ConName
derivingGeneric = conCamelcaseName "Generic"
-- | derivingTypeable
derivingTypeable :: ConName
derivingTypeable = conCamelcaseName "Typeable"
-- | derivingOrd
derivingOrd :: ConName
derivingOrd = conCamelcaseName "Ord"
|
cutsea110/sig
|
sig-api/Ext/TH.hs
|
bsd-3-clause
| 485 | 0 | 5 | 53 | 75 | 46 | 29 | 11 | 1 |
{- DATX02-17-26, automated assessment of imperative programs.
- Copyright, 2017, see AUTHORS.md.
-
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-}
-- See https://github.com/nick8325/quickcheck/pull/136/
-- for more info and where the inspiration comes from
-- https://github.com/ambiata/disorder.hs/blob/master/disorder-jack
-- https://deque.blog/2017/02/03/code-your-own-quickcheck/
module Util.RoseGen where
import qualified Test.QuickCheck.Gen as QC
import qualified Test.QuickCheck as QC
import System.Random (split, Random, randomR)
import Test.QuickCheck.Random (QCGen)
import Data.RoseTree
import Control.Monad
import Control.Monad.Reader
data Env = Env { width :: Int, depth :: Int } deriving (Ord, Eq, Show)
defaultEnv :: Env
defaultEnv = Env 10 10
type Internal a = ReaderT Env QC.Gen (RoseTree a)
--Rose Generator wrapping the Generator from QC
newtype RoseGen a = RoseGen { unGen :: Internal a }
generate :: RoseGen a -> IO (RoseTree a)
generate (RoseGen gen) = QC.generate (runReaderT gen defaultEnv)
--Instances for Functor, Applicative and Monad for RoseGen
instance Functor RoseGen where
fmap f (RoseGen g) = RoseGen (fmap (fmap f) g)
instance Applicative RoseGen where
pure = RoseGen . pure . pure
RoseGen f <*> RoseGen x = RoseGen $ (<*>) <$> f <*> x
instance Monad RoseGen where
return = pure
m >>= f =
RoseGen $ bindGenTree (unGen m) (unGen . f)
-- | Used to implement '(>>=)'
bindGenTree :: Internal a -> (a -> Internal b) -> Internal b
bindGenTree m k = do
env <- ask
lift $ QC.MkGen $ \seed0 size ->
let
(seed1, seed2) = split seed0
runGen :: QCGen -> QC.Gen x -> x
runGen seed gen =
QC.unGen gen seed size
in
runGen seed1 (runReaderT m env) >>= runGen seed2 . (flip runReaderT env) . k
-- | Generate an arbitrary value, and all ways to shrink that value
anything :: QC.Arbitrary a => RoseGen a
anything = RoseGen $ do
a <- lift $ QC.arbitrary
return $ makeTree a
where
makeTree a = RoseTree a [makeTree a' | a' <- QC.shrink a]
-- TODO: Use the environment to
-- decide how much to shrink
choose :: Random a => (a,a) -> RoseGen a
choose (lo, hi) = RoseGen $ do
a <- lift $ QC.choose (lo, hi)
let shrinks = [] -- Use the environment to know how aggressively to shrink
return $ RoseTree a shrinks
-- TODO: Test this
listOf :: RoseGen a -> RoseGen [a]
listOf gen = do
n <- abs <$> anything
replicateM n gen
-- | Generate a value such that a predicate holds for that value
suchThat :: RoseGen a -> (a -> Bool) -> RoseGen a
suchThat gen p = RoseGen $ do
env <- ask
tree <- lift $ (runReaderT (unGen gen) env) `QC.suchThat` (\(RoseTree a _) -> p a)
return $ filterTree tree p
-- | Randomly choose a generator based on some frequency
frequency :: [(Int, RoseGen a)] -> RoseGen a
frequency gp = oneOf $ concat [replicate i g | (i, g) <- gp]
-- TODO: Is this the way we want
-- this generator to work, or do we want
-- it to shrink elements based on the list
-- we gave it as input?
elements :: [a] -> RoseGen a
elements = oneOf . map return
-- Randomly choose a generator
oneOf :: [RoseGen a] -> RoseGen a
oneOf gens = RoseGen $ do
env <- ask
let generators = [runReaderT (unGen g) env | g <- gens]
lift $ QC.oneof generators
|
DATX02-17-26/DATX02-17-26
|
libsrc/Util/RoseGen.hs
|
gpl-2.0
| 3,931 | 0 | 16 | 807 | 1,018 | 528 | 490 | 62 | 1 |
module StatsUtils
( avgTest
, tTest
, StatsUtils.mean
, StatsUtils.std
, median
, StatsUtils.skewness
, StatsUtils.kurtosis
) where
import Data.List as List
import Data.Vector.Generic as Vect
import Statistics.Distribution as Distr
import Statistics.Distribution.StudentT as StudT
import Statistics.Sample.Histogram as Hist
import Statistics.Sample as Sample
import Debug.Trace
avgTest :: [Double]
-> Double
-> Double
-> Bool
avgTest ys mu0 eps
= abs (mu - mu0) <= eps
where
mu = StatsUtils.mean ys
-- Performs a 2-sided t-test evaluating the null hypothesis that the mean of the population from which sample is drawn equals mu.
-- The functions returns 'Just True' in case the means are statistically equal and 'Just False' if they are not
-- In case no t-value could be calculated (in case all samples are same => no variance) Nothing is returned
--
-- To test the 2-sided hypothesis sample mean = mu at the 95% level, use 'tTest "testId" samples mu 0.05'
--
-- sources:
-- http://www.statisticssolutions.com/manova-analysis-one-sample-t-test/
-- http://home.apache.org/~luc/commons-math-3.6-RC2-site/jacoco/org.apache.commons.math3.stat.inference/TTest.java.html
-- https://commons.apache.org/proper/commons-math/javadocs/api-3.6/org/apache/commons/math3/stat/inference/TTest.html
tTest :: String
-> [Double]
-> Double
-> Double
-> Maybe Bool
tTest name samples mu0 alpha
= case mayP of
Nothing -> trace (name List.++ ": cant perform t-test, t-value undefined because 0 variance!") Nothing
Just p -> trace (name List.++ ": p = " List.++ show p) Just $ p > alpha
where
mayP = pValue tValue
pValue :: Maybe Double -> Maybe Double
pValue Nothing = Nothing
pValue (Just t) = trace (name List.++ ": t = " List.++ show t) Just p
where
degFree = fromIntegral $ List.length samples - 1
tDist = StudT.studentT degFree
tAbs = abs t
p = 2 * Distr.cumulative tDist (-tAbs)
-- note that t-value is undefined in case of 0 variance, all samples are the same
tValue :: Maybe Double
tValue
| sigma == 0 = trace ("n = " List.++ show n List.++
"\nmu = " List.++ show mu List.++
"\nsigma = " List.++ show sigma List.++
"\nundefined t value, sigma = 0!!!") Nothing
| otherwise = trace ("n = " List.++ show n List.++
"\nmu = " List.++ show mu List.++
"\nsigma = " List.++ show sigma List.++
"\nt = " List.++ show t) Just t
where
n = List.length samples
mu = StatsUtils.mean samples
sigma = StatsUtils.std samples
t = (mu - mu0) / (sigma / sqrt (fromIntegral n))
-- statistics package obviously provides mean and variance implementations
-- but they don't support simple lists ...
mean :: [Double] -> Double
mean xs = Sample.mean (Vect.fromList xs :: Sample)
std :: [Double] -> Double
std xs = Sample.stdDev (Vect.fromList xs :: Sample)
median :: [Double] -> Double
median xs
| odd n = c
| otherwise = (c + c_1) / 2
where
n = List.length xs
centerIdx = floor ((fromIntegral n / 2) :: Double)
c = xsSorted !! centerIdx
c_1 = xsSorted !! (centerIdx - 1)
xsSorted = List.sort xs
skewness :: [Double] -> Double
skewness xs = Sample.skewness (Vect.fromList xs :: Sample)
kurtosis :: [Double] -> Double
kurtosis xs = Sample.kurtosis (Vect.fromList xs :: Sample)
{-
histogram :: [Double] -> Int -> [(Double, Int)]
histogram xs bins = Vect.toList histVect
where
xsVect = Vect.fromList xs
(intervals, samples) = Hist.histogram bins xsVect
histVect = Vect.zip intervals samples
-}
|
thalerjonathan/phd
|
public/towards/SugarScape/experimental/chapter2_environment/src/test/StatsUtils.hs
|
gpl-3.0
| 3,933 | 0 | 17 | 1,116 | 870 | 460 | 410 | 70 | 3 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Main
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Main (main) where
import Test.Tasty
import Test.AWS.RDS
import Test.AWS.RDS.Internal
main :: IO ()
main = defaultMain $ testGroup "RDS"
[ testGroup "tests" tests
, testGroup "fixtures" fixtures
]
|
olorin/amazonka
|
amazonka-rds/test/Main.hs
|
mpl-2.0
| 522 | 0 | 8 | 103 | 76 | 47 | 29 | 9 | 1 |
{-# LANGUAGE OverloadedStrings, RecordWildCards, DoAndIfThenElse #-}
module Git.Store.ObjectStore (
createEmptyGitRepository
, pathForObject
, pathForPack
, createGitRepositoryFromPackfile
, updateHead
, readTree
, readObject
, readSymRef
, createRef
, getGitDirectory
) where
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Codec.Compression.Zlib as Z
import qualified Crypto.Hash.SHA1 as SHA1
-- FIXME -> don't use isJust/fromJust
import Data.Maybe (isJust, fromJust, isNothing)
import Text.Printf (printf)
import Data.Char (isSpace)
import Git.Pack.Packfile
import Git.Pack.Delta (patch)
import Git.Common (GitRepository(..), ObjectId, WithRepository, Ref(..))
-- Tree
import Git.Store.Object
import System.FilePath
import System.Directory
import Data.Foldable (forM_)
import Data.List (find, partition)
import Control.Monad.Reader hiding (forM_)
createGitRepositoryFromPackfile :: FilePath -> [Ref] -> WithRepository ()
createGitRepositoryFromPackfile packFile refs = do
pack <- liftIO $ packRead packFile
unpackPackfile pack
createRefs refs
updateHead refs
-- TODO properly handle the error condition here
unpackPackfile :: Packfile -> WithRepository ()
unpackPackfile InvalidPackfile = error "Attempting to unpack an invalid packfile"
unpackPackfile (Packfile _ _ objs) = do
repo <- ask
unresolvedObjects <- writeObjects objs
liftIO $ forM_ unresolvedObjects $ writeDelta repo
where writeObjects (x@(PackfileObject (OBJ_REF_DELTA _) _ _):xs) = liftM (x:) (writeObjects xs)
writeObjects (PackfileObject objType _ content : xs) = do
repo <- ask
_ <- liftIO $ writeObject repo (tt objType) content
writeObjects xs
writeObjects [] = return []
tt OBJ_COMMIT = BCommit
tt OBJ_TREE = BTree
tt OBJ_BLOB = BBlob
tt OBJ_TAG = BTag
tt _ = error "Unexpected blob type"
writeDelta repo (PackfileObject ty@(OBJ_REF_DELTA _) _ content) = do
base <- case toObjectId ty of
Just sha -> liftIO $ readObject repo sha
_ -> return Nothing
if isJust base then
case patch (getBlobContent $ fromJust base) content of
Right target -> do
let base' = fromJust base
filename <- writeObject repo (objType base') target
return $ Just filename
Left _ -> return Nothing
else return Nothing -- FIXME - base object doesn't exist yet
writeDelta _repo _ = error "Don't expect a resolved object here"
updateHead :: [Ref] -> WithRepository ()
updateHead [] = fail "Unexpected invalid packfile"
updateHead refs = do
let maybeHead = findHead refs
unless (isNothing maybeHead) $
let sha1 = C.unpack $ getObjId $ fromJust maybeHead
ref = maybe "refs/heads/master" (C.unpack . getRefName) $ findRef sha1 refs
in
do
createRef ref sha1
createSymRef "HEAD" ref
where isCommit ob = objectType ob == OBJ_COMMIT
findHead = find (\Ref{..} -> "HEAD" == getRefName)
findRef sha = find (\Ref{..} -> ("HEAD" /= getRefName && sha == (C.unpack getObjId)))
-- ref: refs/heads/master
createSymRef :: String -> String -> WithRepository ()
createSymRef symName ref = do
repo <- ask
liftIO $ writeFile (getGitDirectory repo </> symName) $ "ref: " ++ ref ++ "\n"
readSymRef :: String -> WithRepository ObjectId
readSymRef name = do
repo <- ask
let gitDir = getGitDirectory repo
ref <- liftIO $ C.readFile (gitDir </> name)
let unwrappedRef = C.unpack $ strip $ head $ tail $ C.split ':' ref
obj <- liftIO $ C.readFile (gitDir </> unwrappedRef)
return $ C.unpack (strip obj)
where strip = C.takeWhile (not . isSpace) . C.dropWhile isSpace
pathForPack :: GitRepository -> FilePath
pathForPack repo = getGitDirectory repo </> "objects" </> "pack"
pathForObject :: String -> String -> (FilePath, String)
pathForObject repoName sha | length sha == 40 = (repoName </> ".git" </> "objects" </> pre, rest)
where pre = take 2 sha
rest = drop 2 sha
pathForObject _ _ = ("", "")
readTree :: GitRepository -> ObjectId -> IO (Maybe Tree)
readTree repo sha = do
treeBlob <- readObject repo sha
return $ parseTree sha (getBlobContent $ fromJust treeBlob)
-- header: "type size\0"
-- sha1 $ header ++ content
readObject :: GitRepository -> ObjectId -> IO (Maybe Object)
readObject GitRepository{..} sha = do
let (path, name) = pathForObject getName sha
filename = path </> name
exists <- doesFileExist filename
if exists then do
bs <- C.readFile filename
return $ parseObject sha $ inflate bs
else return Nothing
where inflate blob = B.concat . L.toChunks . Z.decompress $ L.fromChunks [blob]
-- header: "type size\0"
-- sha1 $ header ++ content
encodeObject :: ObjectType -> C.ByteString -> (ObjectId, C.ByteString)
encodeObject objectType content = do
let header = headerForBlob (C.pack $ show objectType)
blob = header `C.append` content
sha1 = hsh blob
(sha1, blob)
where headerForBlob objType = objType `C.append` " " `C.append` C.pack (show $ C.length content) `C.append` "\0"
hsh = toHex . SHA1.hash
writeObject :: GitRepository -> ObjectType -> C.ByteString -> IO FilePath
writeObject GitRepository{..} objectType content = do
let (sha1, blob) = encodeObject objectType content
(path, name) = pathForObject getName sha1
filename = path </> name
_ <- createDirectoryIfMissing True path
L.writeFile filename $ compress blob
return filename
where compress data' = Z.compress $ L.fromChunks [data'] -- FIXME should data be lazy in the first place?
createEmptyGitRepository :: FilePath -> IO ()
createEmptyGitRepository gitDir =
mapM_ (\dir -> createDirectoryIfMissing True (gitDir </> dir)) topLevelDirectories
where topLevelDirectories = ["objects", "refs", "hooks", "info"]
toObjectId :: PackObjectType -> Maybe ObjectId
toObjectId (OBJ_REF_DELTA base) = Just $ toHex $ B.pack base
toObjectId _ = Nothing
toHex :: C.ByteString -> String
toHex bytes = C.unpack bytes >>= printf "%02x"
getGitDirectory :: GitRepository -> FilePath
getGitDirectory = (</> ".git") . getName
createRefs :: [Ref] -> WithRepository ()
createRefs refs = do
let (tags, branches) = partition isTag $ filter (not . isPeeledTag) refs
writeRefs "refs/remotes/origin" branches
writeRefs "refs/tags" tags
where simpleRefName = head . reverse . C.split '/'
isPeeledTag = C.isSuffixOf "^{}" . getRefName
isTag = (\e -> (not . C.isSuffixOf "^{}" $ getRefName e) && (C.isPrefixOf "refs/tags" $ getRefName e))
writeRefs refSpace = mapM_ (\Ref{..} -> createRef (refSpace ++ "/" ++ (C.unpack . simpleRefName $ getRefName)) (C.unpack getObjId))
createRef :: String -> String -> WithRepository ()
createRef ref sha = do
repo <- ask
let (path, name) = splitFileName ref
dir = getGitDirectory repo </> path
_ <- liftIO $ createDirectoryIfMissing True dir
liftIO $ writeFile (dir </> name) (sha ++ "\n")
|
fcharlie/hgit
|
src/Git/Store/ObjectStore.hs
|
bsd-3-clause
| 7,965 | 0 | 18 | 2,350 | 2,311 | 1,171 | 1,140 | 156 | 11 |
module Koan.Simple where
import Prelude hiding (all, any, const, curry, drop, dropWhile, elem, filter, flip, foldl, foldr, id, iterate, length, map, max, maximum, min, minimum, repeat, reverse, take, takeWhile, uncurry, zipWith, (!!), ($), (++), (.))
enrolled :: Bool
enrolled = False
id :: a -> a
id a = a
const :: a -> b -> a
const a _ = a
(.) :: (b -> c) -> (a -> b) -> a -> c
f . g = \x -> f (g x)
flip :: (a -> b -> c) -> b -> a -> c
flip f b a = f a b
($) :: (a -> b) -> a -> b
f $ a = f a
infixr 0 $
--------------------------------------------------------------------------------
-- LISTS
--------------------------------------------------------------------------------
length :: [a] -> Int
length = foldr (\_ b -> b + 1) 0
(!!) :: [a] -> Int -> Maybe a
[] !! _ = Nothing
(x:xs) !! i
| i < 0 = Nothing
| i == 0 = Just x
| otherwise = xs !! (i - 1)
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x:(xs ++ ys)
reverse :: [a] -> [a]
reverse = foldl (flip (:)) []
--------------------------------------------------------------------------------
-- Infinite lists
--------------------------------------------------------------------------------
repeat :: a -> [a]
repeat x = x : repeat x
iterate :: (a -> a) -> a -> [a]
iterate f x = x : iterate f (f x)
take :: Int -> [a] -> [a]
take n (x:xs)
| n <= 0 = []
| otherwise = x : take (n - 1) xs
drop :: Int -> [a] -> [a]
drop n xs | n <= 0 = xs
drop n (x:xs) = drop (n - 1) xs
drop _ [] = []
takeWhile :: (a -> Bool) -> [a] -> [a]
takeWhile p (x:xs) | p x = x : takeWhile p xs
takeWhile _ _ = []
dropWhile :: (a -> Bool) -> [a] -> [a]
dropWhile _ [] = []
dropWhile p (x:xs)
| p x = dropWhile p xs
| otherwise = x:xs
--------------------------------------------------------------------------------
-- Higher order functions on lists
--------------------------------------------------------------------------------
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
filter :: (a -> Bool) -> [a] -> [a]
filter _ [] = []
filter p (x:xs)
| p x = x : filter p xs
| otherwise = filter p xs
foldl :: (b -> a -> b) -> b -> [a] -> b
foldl _ acc [] = acc
foldl op acc (x:xs) =
let acc' = op acc x
in foldl op acc' xs
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr _ acc [] = acc
foldr op acc (x:xs) = op x (foldr op acc xs)
any :: (a -> Bool) -> [a] -> Bool
any p = foldl (\b a -> b || p a) False
all :: (a -> Bool) -> [a] -> Bool
all p = foldl (\b a -> b && p a) True
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith _ [] _ = []
zipWith _ _ [] = []
zipWith op (x:xs) (y:ys) = op x y : zipWith op xs ys
--------------------------------------------------------------------------------
-- Currying
--------------------------------------------------------------------------------
curry :: ((a, b) -> c) -> a -> b -> c
curry f a b = f (a,b)
uncurry :: (a -> b -> c) -> (a, b) -> c
uncurry f (a,b) = f a b
--------------------------------------------------------------------------------
-- Functions require Equality
--------------------------------------------------------------------------------
elem :: Eq a => a -> [a] -> Bool
elem _ [] = False
elem e (x:xs)
| e == x = True
| otherwise = e `elem` xs
--------------------------------------------------------------------------------
-- Functions require Ordering
--------------------------------------------------------------------------------
max :: Ord a => a -> a -> a
max x y = if x > y then x else y
min :: Ord a => a -> a -> a
min x y = if x < y then x else y
maximum :: Ord a => [a] -> a
maximum (x:xs) = foldr max x xs
minimum :: Ord a => [a] -> a
minimum (x:xs) = foldr min x xs
--------------------------------------------------------------------------------
-- Miscellaneous Exercises
--------------------------------------------------------------------------------
fibonacci :: [Int]
fibonacci = 1 : 1 : zipWith (+) fibonacci (tail fibonacci)
|
Kheldar/hw-koans
|
solution/Koan/Simple.hs
|
bsd-3-clause
| 4,030 | 0 | 9 | 894 | 1,866 | 999 | 867 | 91 | 2 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NondecreasingIndentation #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS -fno-cse #-}
-- -fno-cse is needed for GLOBAL_VAR's to behave properly
-----------------------------------------------------------------------------
--
-- GHC Interactive User Interface
--
-- (c) The GHC Team 2005-2006
--
-----------------------------------------------------------------------------
module Eta.REPL.UI (
interactiveUI,
REPLSettings(..),
defaultEtaReplSettings,
ghciCommands,
etaReplWelcomeMsg
) where
#include "HsVersions.h"
-- Eta REPL
import qualified Eta.REPL.UI.Monad as GhciMonad ( args, runStmt, runDecls )
import Eta.REPL.UI.Monad hiding ( args, runStmt, runDecls )
import Eta.REPL.UI.Tags
import Eta.REPL.UI.Info
-- import Debugger
-- The GHC interface
import Eta.REPL
import Eta.REPL.RemoteTypes
import Eta.Main.DynFlags as DynFlags
import Eta.Main.Constants
import Eta.Main.ErrUtils hiding (traceCmd)
import Eta.Main.Finder as Finder
import Eta.Main.GhcMonad ( modifySession )
import qualified Eta.Main.GHC as GHC
import Eta.Main.GHC ( LoadHowMuch(..), Target(..), TargetId(..), InteractiveImport(..),
TyThing(..), Phase, BreakIndex, Resume, SingleStep, Ghc,
getModuleGraph, handleSourceError )
import Eta.Main.DriverPhases ( partitionByHaskellish, Phase(..) )
import Eta.Main.DriverPipeline ( compileFiles )
import Eta.HsSyn.HsImpExp
import Eta.HsSyn.HsSyn
import Eta.Main.HscTypes ( tyThingParent_maybe, handleFlagWarnings, getSafeMode, hsc_IC,
setInteractivePrintName, hsc_dflags, msObjFilePath )
import Eta.BasicTypes.Module
import Eta.BasicTypes.Name
import Eta.Main.Packages ( trusted, getPackageDetails, getInstalledPackageDetails,
listVisibleModuleNames, pprFlag )
import Eta.Main.PprTyThing
import Eta.Prelude.PrelNames
import Eta.BasicTypes.RdrName as RdrName ( RdrName, getGRE_NameQualifier_maybes, getRdrName )
import Eta.BasicTypes.SrcLoc
import qualified Eta.Parser.Lexer as Lexer
import Eta.Utils.StringBuffer
import Eta.Utils.Outputable hiding ( printForUser, printForUserPartWay )
-- Other random utilities
import Eta.BasicTypes.BasicTypes hiding ( isTopLevel )
-- import ETAConfig
import Eta.Utils.Digraph
import Eta.Utils.Encoding
import Eta.Utils.FastString
import Eta.REPL.Linker
import Eta.REPL.Leak
import Eta.Utils.Maybes ( orElse )
import Eta.BasicTypes.NameSet
import Eta.Utils.Panic hiding ( showException )
import Eta.Utils.Util
import Eta.Utils.PprColor
-- Haskell Libraries
import System.Console.Haskeline as Haskeline
import Control.Applicative hiding (empty)
import Control.DeepSeq (deepseq)
import Control.Monad as Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except
import Data.Array
import qualified Data.ByteString.Char8 as BS
import Data.Char
import Data.Function
import Data.IORef ( IORef, modifyIORef, newIORef, readIORef, writeIORef )
import Data.List ( find, group, intercalate, intersperse, isPrefixOf, nub,
partition, sort, sortBy )
import qualified Data.Set as S
import Data.Maybe
import qualified Data.Map as M
import Data.Time.LocalTime ( getZonedTime )
import Data.Time.Format ( formatTime, defaultTimeLocale )
import Data.Version ( showVersion )
import Eta.Utils.Exception as Exception hiding (catch)
import Foreign hiding (void)
#if __GLASGOW_HASKELL__ < 800
import GHC.Stack
#else
import GHC.Stack hiding (srcLocFile)
#endif
import System.Directory
import System.Environment
import System.Exit ( exitWith, ExitCode(..) )
import System.FilePath
import System.Info
import System.IO
import System.IO.Error
import System.IO.Unsafe ( unsafePerformIO )
import System.Process
import Text.Printf
import Text.Read ( readMaybe )
import qualified Eta.LanguageExtensions as LangExt
import Unsafe.Coerce
#if !defined(mingw32_HOST_OS)
import System.Posix hiding ( getEnv )
#else
import qualified System.Win32
#endif
import GHC.IO.Exception ( IOErrorType(InvalidArgument) )
import GHC.IO.Handle ( hFlushAll )
import GHC.TopHandler ( topHandler )
-----------------------------------------------------------------------------
data REPLSettings = REPLSettings {
availableCommands :: [Command],
shortHelpText :: String,
fullHelpText :: String,
defPrompt :: PromptFunction,
defPromptCont :: PromptFunction
}
defaultEtaReplSettings :: REPLSettings
defaultEtaReplSettings =
REPLSettings {
availableCommands = ghciCommands,
shortHelpText = defShortHelpText,
defPrompt = default_prompt,
defPromptCont = default_prompt_cont,
fullHelpText = defFullHelpText
}
etaReplWelcomeMsg :: DynFlags -> String
etaReplWelcomeMsg dflags =
showSDocWithColor dflags $
vcat [ blankLine,
blankLine,
withBold (text startDashes) <+> colored colEtaFg (text version)
<+> withBold (text endDashes),
tableBlankLine,
insideTable (length (helpCommand ++ " " ++ helpDesc))
(colored colMagentaFg (text helpCommand) <+> text helpDesc),
insideTable (length (exitCommand ++ " " ++ exitDesc))
(colored colMagentaFg (text exitCommand) <+> text exitDesc),
insideTable (length (typeCommand ++ " " ++ typeDesc))
(colored colMagentaFg (text typeCommand) <+> text typeDesc),
insideTable (length (kindCommand ++ " " ++ kindDesc))
(colored colMagentaFg (text kindCommand) <+> text kindDesc),
insideTable (length (kindExCommand ++ " " ++ kindExDesc))
(colored colMagentaFg (text kindExCommand) <+> text kindExDesc),
tableBlankLine,
insideTable (length (itCommand ++ " " ++ itDesc))
(colored colMagentaFg (text itCommand) <+> text itDesc),
tableBlankLine,
insideTable (length (websiteMessage ++ " " ++ websiteLink))
(text websiteMessage <+> colored colBlueFg (text websiteLink)),
tableBlankLine,
withBold (text tableBottomLine),
blankLine ]
where unicode = useUnicode dflags
withBold sdoc
| unicode = sdoc
| otherwise = colored colBold sdoc
helpCommand = ":help"
helpDesc = "for help"
exitCommand = ":exit"
exitDesc = "to exit"
typeCommand = ":type [expr]"
typeDesc = "for type of expression"
kindCommand = ":kind [type]"
kindDesc = "for kind of type"
kindExCommand = ":kind! [type]"
kindExDesc = "for kind of simplified type"
itCommand = "it"
itDesc = "refers to the last expression"
websiteMessage = "For more details, check out"
websiteLink = "https://eta-lang.org"
startDashes
| unicode = unicodeStartDashes
| otherwise = "----"
version = "Welcome to Eta REPL v" ++ cProjectVersion ++ "!"
startLength = length (startDashes ++ version) + 2
totalDashLength = 60
endDashes
| unicode = unicodeEndDashes
| otherwise = replicate (totalDashLength - startLength) '-'
tableBottomLine
| unicode = unicodeBottomLeftCorner
: replicate (totalDashLength - 2) unicodeHorizontalDash
++ [unicodeBottomRightCorner]
| otherwise = replicate totalDashLength '-'
tableBlankLine
| unicode = text unicodeTableBlankLine
| otherwise = blankLine
insideTable len sdoc
| unicode = text [unicodeVerticalDash] <+> sdoc <+>
text (replicate (totalDashLength - (4 + len)) ' ') <>
text [unicodeVerticalDash]
| otherwise = space <> sdoc
unicodeStartDashes = unicodeTopLeftCorner : replicate 3 unicodeHorizontalDash
unicodeEndDashes = replicate (totalDashLength - startLength - 1) unicodeHorizontalDash
++ [unicodeTopRightCorner]
unicodeTableBlankLine = unicodeVerticalDash : replicate (totalDashLength - 2) ' '
++ [unicodeVerticalDash]
unicodeTopLeftCorner = '\x256d'
unicodeHorizontalDash = '\x2500'
unicodeVerticalDash = '\x2502'
unicodeTopRightCorner = '\x256e'
unicodeBottomLeftCorner = '\x2570'
unicodeBottomRightCorner = '\x256f'
ghciCommands :: [Command]
ghciCommands = map mkCmd [
-- Hugs users are accustomed to :e, so make sure it doesn't overlap
("?", keepGoing help, noCompletion),
("add", keepGoingPaths addModule, completeFilename),
("abandon", keepGoing abandonCmd, noCompletion),
("break", keepGoing breakCmd, completeIdentifier),
("back", keepGoing backCmd, noCompletion),
("browse", keepGoing' (browseCmd False), completeModule),
("browse!", keepGoing' (browseCmd True), completeModule),
("cd", keepGoing' changeDirectory, completeFilename),
("check", keepGoing' checkModule, completeHomeModule),
("continue", keepGoing continueCmd, noCompletion),
("cmd", keepGoing cmdCmd, completeExpression),
("ctags", keepGoing createCTagsWithLineNumbersCmd, completeFilename),
("ctags!", keepGoing createCTagsWithRegExesCmd, completeFilename),
("def", keepGoing (defineMacro False), completeExpression),
("def!", keepGoing (defineMacro True), completeExpression),
("delete", keepGoing deleteCmd, noCompletion),
("edit", keepGoing' editFile, completeFilename),
("etags", keepGoing createETagsFileCmd, completeFilename),
("exit", exit, noCompletion),
("force", keepGoing forceCmd, completeExpression),
("forward", keepGoing forwardCmd, noCompletion),
("help", keepGoing help, noCompletion),
("history", keepGoing historyCmd, noCompletion),
("info", keepGoing' (info False), completeIdentifier),
("info!", keepGoing' (info True), completeIdentifier),
("issafe", keepGoing' isSafeCmd, completeModule),
("kind", keepGoing' (kindOfType False), completeIdentifier),
("kind!", keepGoing' (kindOfType True), completeIdentifier),
("load", keepGoingPaths loadModule_, completeHomeModuleOrFile),
("load!", keepGoingPaths loadModuleDefer, completeHomeModuleOrFile),
("list", keepGoing' listCmd, noCompletion),
("module", keepGoing moduleCmd, completeSetModule),
("main", keepGoing runMain, completeFilename),
("print", keepGoing printCmd, completeExpression),
("reload", keepGoing' reloadModule, noCompletion),
("reload!", keepGoing' reloadModuleDefer, noCompletion),
("run", keepGoing runRun, completeFilename),
("script", keepGoing' scriptCmd, completeFilename),
("set", keepGoing setCmd, completeSetOptions),
("seti", keepGoing setiCmd, completeSeti),
("show", keepGoing showCmd, completeShowOptions),
("showi", keepGoing showiCmd, completeShowiOptions),
("sprint", keepGoing sprintCmd, completeExpression),
("step", keepGoing stepCmd, completeIdentifier),
("steplocal", keepGoing stepLocalCmd, completeIdentifier),
("stepmodule",keepGoing stepModuleCmd, completeIdentifier),
("type", keepGoing' typeOfExpr, completeExpression),
("trace", keepGoing traceCmd, completeExpression),
("unadd", keepGoingPaths unAddModule, completeFilename),
("undef", keepGoing undefineMacro, completeMacro),
("unset", keepGoing unsetOptions, completeSetOptions),
("where", keepGoing whereCmd, noCompletion)
] ++ map mkCmdHidden [ -- hidden commands
("all-types", keepGoing' allTypesCmd),
("complete", keepGoing completeCmd),
("loc-at", keepGoing' locAtCmd),
("type-at", keepGoing' typeAtCmd),
("uses", keepGoing' usesCmd)
]
where
mkCmd (n,a,c) = Command { cmdName = n
, cmdAction = a
, cmdHidden = False
, cmdCompletionFunc = c
}
mkCmdHidden (n,a) = Command { cmdName = n
, cmdAction = a
, cmdHidden = True
, cmdCompletionFunc = noCompletion
}
-- We initialize readline (in the interactiveUI function) to use
-- word_break_chars as the default set of completion word break characters.
-- This can be overridden for a particular command (for example, filename
-- expansion shouldn't consider '/' to be a word break) by setting the third
-- entry in the Command tuple above.
--
-- NOTE: in order for us to override the default correctly, any custom entry
-- must be a SUBSET of word_break_chars.
word_break_chars :: String
word_break_chars = spaces ++ specials ++ symbols
symbols, specials, spaces :: String
symbols = "!#$%&*+/<=>?@\\^|-~"
specials = "(),;[]`{}"
spaces = " \t\n"
flagWordBreakChars :: String
flagWordBreakChars = " \t\n"
keepGoing :: (String -> GHCi ()) -> (String -> InputT GHCi Bool)
keepGoing a str = keepGoing' (lift . a) str
keepGoing' :: Monad m => (String -> m ()) -> String -> m Bool
keepGoing' a str = a str >> return False
keepGoingPaths :: ([FilePath] -> InputT GHCi ()) -> (String -> InputT GHCi Bool)
keepGoingPaths a str
= do case toArgs str of
Left err -> liftIO $ hPutStrLn stderr err
Right args -> a args
return False
defShortHelpText :: String
defShortHelpText = "use :? for help.\n"
defFullHelpText :: String
defFullHelpText =
" Commands available from the prompt:\n" ++
"\n" ++
" <statement> evaluate/run <statement>\n" ++
" : repeat last command\n" ++
" :{\\n ..lines.. \\n:}\\n multiline command\n" ++
" :add [*]<module> ... add module(s) to the current target set\n" ++
" :browse[!] [[*]<mod>] display the names defined by module <mod>\n" ++
" (!: more details; *: all top-level names)\n" ++
" :cd <dir> change directory to <dir>\n" ++
" :cmd <expr> run the commands returned by <expr>::IO String\n" ++
" :complete <domain> [<range>] <input> list completions for partial input string\n" ++
" :ctags[!] [<file>] create tags file <file> for Vi (default: \"tags\")\n" ++
" (!: use regex instead of line number)\n" ++
" :def <cmd> <expr> define command :<cmd> (later defined command has\n" ++
" precedence, ::<cmd> is always a builtin command)\n" ++
" :edit <file> edit file\n" ++
" :edit edit last module\n" ++
" :etags [<file>] create tags file <file> for Emacs (default: \"TAGS\")\n" ++
" :help, :? display this list of commands\n" ++
" :info[!] [<name> ...] display information about the given names\n" ++
" (!: do not filter instances)\n" ++
" :issafe [<mod>] display safe haskell information of module <mod>\n" ++
" :kind[!] <type> show the kind of <type>\n" ++
" (!: also print the normalised type)\n" ++
" :load[!] [*]<module> ... load module(s) and their dependents\n" ++
" (!: defer type errors)\n" ++
" :main [<arguments> ...] run the main function with the given arguments\n" ++
" :module [+/-] [*]<mod> ... set the context for expression evaluation\n" ++
" :exit exit Eta REPL \n" ++
" :reload[!] reload the current module set\n" ++
" (!: defer type errors)\n" ++
" :run function [<arguments> ...] run the function with the given arguments\n" ++
" :script <file> run the script <file>\n" ++
" :type <expr> show the type of <expr>\n" ++
" :unadd <module> ... remove module(s) from the current target set\n" ++
" :undef <cmd> undefine user-defined command :<cmd>\n" ++
" :!<command> run the shell command <command>\n" ++
"\n" ++
-- " -- Commands for debugging:\n" ++
-- "\n" ++
-- " :abandon at a breakpoint, abandon current computation\n" ++
-- " :back [<n>] go back in the history N steps (after :trace)\n" ++
-- " :break [<mod>] <l> [<col>] set a breakpoint at the specified location\n" ++
-- " :break <name> set a breakpoint on the specified function\n" ++
-- " :continue resume after a breakpoint\n" ++
-- " :delete <number> delete the specified breakpoint\n" ++
-- " :delete * delete all breakpoints\n" ++
-- " :force <expr> print <expr>, forcing unevaluated parts\n" ++
-- " :forward [<n>] go forward in the history N step s(after :back)\n" ++
-- " :history [<n>] after :trace, show the execution history\n" ++
-- " :list show the source code around current breakpoint\n" ++
-- " :list <identifier> show the source code for <identifier>\n" ++
-- " :list [<module>] <line> show the source code around line number <line>\n" ++
-- " :print [<name> ...] show a value without forcing its computation\n" ++
-- " :sprint [<name> ...] simplified version of :print\n" ++
-- " :step single-step after stopping at a breakpoint\n"++
-- " :step <expr> single-step into <expr>\n"++
-- " :steplocal single-step within the current top-level binding\n"++
-- " :stepmodule single-step restricted to the current module\n"++
-- " :trace trace after stopping at a breakpoint\n"++
-- " :trace <expr> evaluate <expr> with tracing on (see :history)\n"++
-- "\n" ++
" -- Commands for changing settings:\n" ++
"\n" ++
" :set <option> ... set options\n" ++
" :seti <option> ... set options for interactive evaluation only\n" ++
" :set args <arg> ... set the arguments returned by System.getArgs\n" ++
" :set prog <progname> set the value returned by System.getProgName\n" ++
" :set prompt <prompt> set the prompt used in Eta REPL\n" ++
" :set prompt-cont <prompt> set the continuation prompt used in Eta REPL\n" ++
" :set prompt-function <expr> set the function to handle the prompt\n" ++
" :set prompt-cont-function <expr>" ++
"set the function to handle the continuation prompt\n" ++
" :set editor <cmd> set the command used for :edit\n" ++
" :set stop [<n>] <cmd> set the command to run when a breakpoint is hit\n" ++
" :unset <option> ... unset options\n" ++
"\n" ++
" Options for ':set' and ':unset':\n" ++
"\n" ++
" +m allow multiline commands\n" ++
" +r revert top-level expressions after each evaluation\n" ++
" +s print timing/memory stats after each evaluation\n" ++
" +t print type after evaluation\n" ++
" +c collect type/location info after loading modules\n" ++
" -<flags> most Eta command line flags can also be set here\n" ++
" (eg. -v2, -XFlexibleInstances, etc.)\n" ++
" for Eta REPL-specific flags, see User's Guide,\n"++
" Flag reference, Interactive-mode options\n" ++
"\n" ++
" -- Commands for displaying information:\n" ++
"\n" ++
" :show bindings show the current bindings made at the prompt\n" ++
-- " :show breaks show the active breakpoints\n" ++
-- " :show context show the breakpoint context\n" ++
" :show imports show the current imports\n" ++
" :show linker show current linker state\n" ++
" :show modules show the currently loaded modules\n" ++
" :show packages show the currently active package flags\n" ++
" :show paths show the currently active search paths\n" ++
" :show language show the currently active language flags\n" ++
" :show targets show the current set of targets\n" ++
" :show <setting> show value of <setting>, which is one of\n" ++
" [args, prog, editor, stop]\n" ++
" :showi language show language flags for interactive evaluation\n" ++
"\n"
findEditor :: IO String
findEditor = do
getEnv "EDITOR"
`catchIO` \_ -> do
#if defined(mingw32_HOST_OS)
win <- System.Win32.getWindowsDirectory
return (win </> "notepad.exe")
#else
return ""
#endif
default_progname, default_stop :: String
default_progname = "<interactive>"
default_stop = ""
default_prompt, default_prompt_cont :: PromptFunction
default_prompt = generatePromptFunctionFromString "%s> "
default_prompt_cont = generatePromptFunctionFromString "%s| "
default_args :: [String]
default_args = []
interactiveUI :: REPLSettings -> [(FilePath, Maybe Phase)] -> Maybe [String]
-> Ghc ()
interactiveUI config srcs maybe_exprs = do
-- HACK! If we happen to get into an infinite loop (eg the user
-- types 'let x=x in x' at the prompt), then the thread will block
-- on a blackhole, and become unreachable during GC. The GC will
-- detect that it is unreachable and send it the NonTermination
-- exception. However, since the thread is unreachable, everything
-- it refers to might be finalized, including the standard Handles.
-- This sounds like a bug, but we don't have a good solution right
-- now.
_ <- liftIO $ newStablePtr stdin
_ <- liftIO $ newStablePtr stdout
_ <- liftIO $ newStablePtr stderr
-- Initialise buffering for the *interpreted* I/O system
(nobuffering, flush) <- initInterpBuffering
-- The initial set of DynFlags used for interactive evaluation is the same
-- as the global DynFlags, plus -XExtendedDefaultRules and
-- -XNoMonomorphismRestriction.
dflags <- getDynFlags
let dflags' = (`xopt_set` LangExt.ExtendedDefaultRules)
. (`xopt_unset` LangExt.MonomorphismRestriction)
$ dflags
GHC.setInteractiveDynFlags dflags'
lastErrLocationsRef <- liftIO $ newIORef []
progDynFlags <- GHC.getProgramDynFlags
_ <- GHC.setProgramDynFlags $
progDynFlags { log_action = ghciLogAction lastErrLocationsRef }
when (isNothing maybe_exprs) $ do
-- Only for GHCi (not runghc and ghc -e):
-- Turn buffering off for the compiled program's stdout/stderr
turnOffBuffering_ nobuffering
-- Turn buffering off for GHCi's stdout
liftIO $ hFlush stdout
liftIO $ hSetBuffering stdout NoBuffering
-- We don't want the cmd line to buffer any input that might be
-- intended for the program, so unbuffer stdin.
liftIO $ hSetBuffering stdin NoBuffering
liftIO $ hSetBuffering stderr NoBuffering
#if defined(mingw32_HOST_OS)
-- On Unix, stdin will use the locale encoding. The IO library
-- doesn't do this on Windows (yet), so for now we use UTF-8,
-- for consistency with GHC 6.10 and to make the tests work.
liftIO $ hSetEncoding stdin utf8
#endif
default_editor <- liftIO $ findEditor
eval_wrapper <- mkEvalWrapper default_progname default_args
let prelude_import = simpleImportDecl preludeModuleName
startGHCi (runGHCi srcs maybe_exprs)
GHCiState{ progname = default_progname,
args = default_args,
evalWrapper = eval_wrapper,
prompt = default_prompt,
prompt_cont = default_prompt_cont,
stop = default_stop,
editor = default_editor,
options = [ShowType],
-- We initialize line number as 0, not 1, because we use
-- current line number while reporting errors which is
-- incremented after reading a line.
line_number = 0,
break_ctr = 0,
breaks = [],
tickarrays = emptyModuleEnv,
ghci_commands = availableCommands config,
ghci_macros = [],
last_command = Nothing,
cmdqueue = [],
remembered_ctx = [],
transient_ctx = [],
extra_imports = [],
prelude_imports = [prelude_import],
ghc_e = isJust maybe_exprs,
short_help = shortHelpText config,
long_help = fullHelpText config,
lastErrorLocations = lastErrLocationsRef,
mod_infos = M.empty,
flushStdHandles = flush,
noBuffering = nobuffering
}
return ()
resetLastErrorLocations :: GHCi ()
resetLastErrorLocations = do
st <- getGHCiState
liftIO $ writeIORef (lastErrorLocations st) []
ghciLogAction :: IORef [(FastString, Int)] -> LogAction
ghciLogAction lastErrLocations dflags flag severity srcSpan style msg = do
defaultLogAction dflags flag severity srcSpan style msg
case severity of
SevError -> case srcSpan of
RealSrcSpan rsp -> modifyIORef lastErrLocations
(++ [(srcLocFile (realSrcSpanStart rsp), srcLocLine (realSrcSpanStart rsp))])
_ -> return ()
_ -> return ()
withGhcAppData :: DynFlags -> (FilePath -> IO a) -> IO a -> IO a
withGhcAppData dflags right _left = do
let dir = topDir dflags
createDirectoryIfMissing True dir `catchIO` \_ -> return ()
right dir
runGHCi :: [(FilePath, Maybe Phase)] -> Maybe [String] -> GHCi ()
runGHCi paths maybe_exprs = do
dflags <- getDynFlags
let
ignore_dot_ghci = gopt Opt_IgnoreDotGhci dflags
current_dir = return (Just ".eta_repl")
app_user_dir = liftIO $ withGhcAppData dflags
(\dir -> return (Just (dir </> "eta_repl.conf")))
(return Nothing)
home_dir = do
either_dir <- liftIO $ tryIO (getEnv "HOME")
case either_dir of
Right home -> return (Just (home </> ".eta_repl"))
_ -> return Nothing
canonicalizePath' :: FilePath -> IO (Maybe FilePath)
canonicalizePath' fp = liftM Just (canonicalizePath fp)
`catchIO` \_ -> return Nothing
sourceConfigFile :: FilePath -> GHCi ()
sourceConfigFile file = do
exists <- liftIO $ doesFileExist file
when exists $ do
either_hdl <- liftIO $ tryIO (openFile file ReadMode)
case either_hdl of
Left _e -> return ()
-- NOTE: this assumes that runInputT won't affect the terminal;
-- can we assume this will always be the case?
-- This would be a good place for runFileInputT.
Right hdl ->
do runInputTWithPrefs defaultPrefs defaultSettings $
runCommands $ fileLoop hdl
liftIO (hClose hdl `catchIO` \_ -> return ())
-- Don't print a message if this is really ghc -e (#11478).
-- Also, let the user silence the message with -v0
-- (the default verbosity in GHCi is 1).
when (isNothing maybe_exprs && verbosity dflags > 0) $
liftIO $ putStrLn ("Loaded Eta REPL configuration from " ++ file)
--
setGHCContextFromGHCiState
dot_cfgs <- if ignore_dot_ghci then return [] else do
dot_files <- catMaybes <$> sequence [ current_dir, app_user_dir, home_dir ]
liftIO $ filterM checkFileAndDirPerms dot_files
mdot_cfgs <- liftIO $ mapM canonicalizePath' dot_cfgs
let arg_cfgs = reverse $ ghciScripts dflags
-- -ghci-script are collected in reverse order
-- We don't require that a script explicitly added by -ghci-script
-- is owned by the current user. (#6017)
mapM_ sourceConfigFile $ nub $ (catMaybes mdot_cfgs) ++ arg_cfgs
-- nub, because we don't want to read .ghci twice if the CWD is $HOME.
-- Perform a :load for files given on the GHCi command line
-- When in -e mode, if the load fails then we want to stop
-- immediately rather than going on to evaluate the expression.
when (not (null paths)) $ do
ok <- ghciHandle (\e -> do showException e; return Failed) $
-- TODO: this is a hack.
runInputTWithPrefs defaultPrefs defaultSettings $
loadModule paths
when (isJust maybe_exprs && failed ok) $
liftIO (exitWith (ExitFailure 1))
installInteractivePrint (interactivePrint dflags) (isJust maybe_exprs)
-- if verbosity is greater than 0, or we are connected to a
-- terminal, display the prompt in the interactive loop.
is_tty <- liftIO (hIsTerminalDevice stdin)
let show_prompt = verbosity dflags > 0 || is_tty
-- reset line number
modifyGHCiState $ \st -> st{line_number=0}
case maybe_exprs of
Nothing ->
do
-- enter the interactive loop
runGHCiInput $ runCommands $ nextInputLine show_prompt is_tty
Just exprs -> do
-- just evaluate the expression we were given
enqueueCommands exprs
let hdle e = do st <- getGHCiState
-- flush the interpreter's stdout/stderr on exit (#3890)
flushInterpBuffers
-- Jump through some hoops to get the
-- current progname in the exception text:
-- <progname>: <exception>
liftIO $ withProgName (progname st)
$ topHandler e
-- this used to be topHandlerFastExit, see #2228
runInputTWithPrefs defaultPrefs defaultSettings $ do
-- make `ghc -e` exit nonzero on invalid input, see Trac #7962
_ <- runCommands' hdle
(Just $ hdle (toException $ ExitFailure 1) >> return ())
(return Nothing)
return ()
-- and finally, exit
liftIO $ when (verbosity dflags > 0) $
putStrLn $ showSDocWithColor dflags $
colored colMagentaFg (text "Goodbye! See you soon.")
runGHCiInput :: InputT GHCi a -> GHCi a
runGHCiInput f = do
dflags <- getDynFlags
let ghciHistory = gopt Opt_GhciHistory dflags
let localGhciHistory = gopt Opt_LocalGhciHistory dflags
currentDirectory <- liftIO $ getCurrentDirectory
histFile <- case (ghciHistory, localGhciHistory) of
(True, True) -> return (Just (currentDirectory </> ".eta_repl_history"))
(True, _) -> liftIO $ withGhcAppData dflags
(\dir -> return (Just (dir </> "eta_repl_history"))) (return Nothing)
_ -> return Nothing
runInputT
(setComplete ghciCompleteWord $ defaultSettings {historyFile = histFile})
f
-- | How to get the next input line from the user
nextInputLine :: Bool -> Bool -> InputT GHCi (Maybe String)
nextInputLine show_prompt is_tty
| is_tty = do
prmpt <- if show_prompt then lift mkPrompt else return ""
r <- getInputLine prmpt
incrementLineNo
return r
| otherwise = do
when show_prompt $ lift mkPrompt >>= liftIO . putStr
fileLoop stdin
-- NOTE: We only read .ghci files if they are owned by the current user,
-- and aren't world writable (files owned by root are ok, see #9324).
-- Otherwise, we could be accidentally running code planted by
-- a malicious third party.
-- Furthermore, We only read ./.ghci if . is owned by the current user
-- and isn't writable by anyone else. I think this is sufficient: we
-- don't need to check .. and ../.. etc. because "." always refers to
-- the same directory while a process is running.
checkFileAndDirPerms :: FilePath -> IO Bool
checkFileAndDirPerms file = do
file_ok <- checkPerms file
-- Do not check dir perms when .ghci doesn't exist, otherwise GHCi will
-- print some confusing and useless warnings in some cases (e.g. in
-- travis). Note that we can't add a test for this, as all ghci tests should
-- run with -ignore-dot-ghci, which means we never get here.
if file_ok then checkPerms (getDirectory file) else return False
where
getDirectory f = case takeDirectory f of
"" -> "."
d -> d
checkPerms :: FilePath -> IO Bool
#if defined(mingw32_HOST_OS)
checkPerms _ = return True
#else
checkPerms file =
handleIO (\_ -> return False) $ do
st <- getFileStatus file
me <- getRealUserID
let mode = System.Posix.fileMode st
ok = (fileOwner st == me || fileOwner st == 0) &&
groupWriteMode /= mode `intersectFileModes` groupWriteMode &&
otherWriteMode /= mode `intersectFileModes` otherWriteMode
unless ok $
-- #8248: Improving warning to include a possible fix.
putStrLn $ "*** WARNING: " ++ file ++
" is writable by someone else, IGNORING!" ++
"\nSuggested fix: execute 'chmod go-w " ++ file ++ "'"
return ok
#endif
incrementLineNo :: InputT GHCi ()
incrementLineNo = modifyGHCiState incLineNo
where
incLineNo st = st { line_number = line_number st + 1 }
fileLoop :: Handle -> InputT GHCi (Maybe String)
fileLoop hdl = do
l <- liftIO $ tryIO $ hGetLine hdl
case l of
Left e | isEOFError e -> return Nothing
| -- as we share stdin with the program, the program
-- might have already closed it, so we might get a
-- handle-closed exception. We therefore catch that
-- too.
isIllegalOperation e -> return Nothing
| InvalidArgument <- etype -> return Nothing
| otherwise -> liftIO $ ioError e
where etype = ioeGetErrorType e
-- treat InvalidArgument in the same way as EOF:
-- this can happen if the user closed stdin, or
-- perhaps did getContents which closes stdin at
-- EOF.
Right l' -> do
incrementLineNo
return (Just l')
formatCurrentTime :: String -> IO String
formatCurrentTime format =
getZonedTime >>= return . (formatTime defaultTimeLocale format)
getUserName :: IO String
getUserName = do
#if defined(mingw32_HOST_OS)
getEnv "USERNAME"
`catchIO` \e -> do
putStrLn $ show e
return ""
#else
getLoginName
#endif
getInfoForPrompt :: GHCi (SDoc, [String], Int)
getInfoForPrompt = do
st <- getGHCiState
imports <- GHC.getContext
resumes <- GHC.getResumeContext
context_bit <-
case resumes of
[] -> return empty
r:_ -> do
let ix = GHC.resumeHistoryIx r
if ix == 0
then return (brackets (ppr (GHC.resumeSpan r)) <> space)
else do
let hist = GHC.resumeHistory r !! (ix-1)
pan <- GHC.getHistorySpan hist
return (brackets (ppr (negate ix) <> char ':'
<+> ppr pan) <> space)
let
dots | _:rs <- resumes, not (null rs) = text "... "
| otherwise = empty
rev_imports = reverse imports -- rightmost are the most recent
myIdeclName d | Just m <- ideclAs d = m
| otherwise = unLoc (ideclName d)
modules_names =
['*':(moduleNameString m) | IIModule m <- rev_imports] ++
[moduleNameString (myIdeclName d) | IIDecl d <- rev_imports]
line = 1 + line_number st
return (dots <> context_bit, modules_names, line)
parseCallEscape :: String -> (String, String)
parseCallEscape s
| not (all isSpace beforeOpen) = ("", "")
| null sinceOpen = ("", "")
| null sinceClosed = ("", "")
| null cmd = ("", "")
| otherwise = (cmd, tail sinceClosed)
where
(beforeOpen, sinceOpen) = span (/='(') s
(cmd, sinceClosed) = span (/=')') (tail sinceOpen)
checkPromptStringForErrors :: String -> Maybe String
checkPromptStringForErrors ('%':'c':'a':'l':'l':xs) =
case parseCallEscape xs of
("", "") -> Just ("Incorrect %call syntax. " ++
"Should be %call(a command and arguments).")
(_, afterClosed) -> checkPromptStringForErrors afterClosed
checkPromptStringForErrors ('%':'%':xs) = checkPromptStringForErrors xs
checkPromptStringForErrors (_:xs) = checkPromptStringForErrors xs
checkPromptStringForErrors "" = Nothing
generatePromptFunctionFromString :: String -> PromptFunction
generatePromptFunctionFromString promptS = \_ _ -> do
(context, modules_names, line) <- getInfoForPrompt
let
processString :: String -> GHCi SDoc
processString ('%':'s':xs) =
liftM2 (<>) (return modules_list) (processString xs)
where
modules_list = context <> modules_bit
modules_bit = hsep $ map text modules_names
processString ('%':'l':xs) =
liftM2 (<>) (return $ ppr line) (processString xs)
processString ('%':'d':xs) =
liftM2 (<>) (liftM text formatted_time) (processString xs)
where
formatted_time = liftIO $ formatCurrentTime "%a %b %d"
processString ('%':'t':xs) =
liftM2 (<>) (liftM text formatted_time) (processString xs)
where
formatted_time = liftIO $ formatCurrentTime "%H:%M:%S"
processString ('%':'T':xs) = do
liftM2 (<>) (liftM text formatted_time) (processString xs)
where
formatted_time = liftIO $ formatCurrentTime "%I:%M:%S"
processString ('%':'@':xs) = do
liftM2 (<>) (liftM text formatted_time) (processString xs)
where
formatted_time = liftIO $ formatCurrentTime "%I:%M %P"
processString ('%':'A':xs) = do
liftM2 (<>) (liftM text formatted_time) (processString xs)
where
formatted_time = liftIO $ formatCurrentTime "%H:%M"
processString ('%':'u':xs) =
liftM2 (<>) (liftM text user_name) (processString xs)
where
user_name = liftIO $ getUserName
processString ('%':'w':xs) =
liftM2 (<>) (liftM text current_directory) (processString xs)
where
current_directory = liftIO $ getCurrentDirectory
processString ('%':'o':xs) =
liftM ((text os) <>) (processString xs)
processString ('%':'a':xs) =
liftM ((text arch) <>) (processString xs)
processString ('%':'N':xs) =
liftM ((text compilerName) <>) (processString xs)
processString ('%':'V':xs) =
liftM ((text $ showVersion compilerVersion) <>) (processString xs)
processString ('%':'c':'a':'l':'l':xs) = do
respond <- liftIO $ do
(code, out, err) <-
readProcessWithExitCode
(head list_words) (tail list_words) ""
`catchIO` \e -> return (ExitFailure 1, "", show e)
case code of
ExitSuccess -> return out
_ -> do
hPutStrLn stderr err
return ""
liftM ((text respond) <>) (processString afterClosed)
where
(cmd, afterClosed) = parseCallEscape xs
list_words = words cmd
processString ('%':'%':xs) =
liftM ((char '%') <>) (processString xs)
processString (x:xs) =
liftM (char x <>) (processString xs)
processString "" =
return empty
processString promptS
mkPrompt :: GHCi String
mkPrompt = do
st <- getGHCiState
dflags <- getDynFlags
(context, modules_names, line) <- getInfoForPrompt
prompt_string <- (prompt st) modules_names line
let prompt_doc = context <> prompt_string
return (showSDocWithColor dflags $ colored colEtaFg (vcat [blankLine, prompt_doc]))
queryQueue :: GHCi (Maybe String)
queryQueue = do
st <- getGHCiState
case cmdqueue st of
[] -> return Nothing
c:cs -> do setGHCiState st{ cmdqueue = cs }
return (Just c)
-- Reconfigurable pretty-printing Ticket #5461
installInteractivePrint :: Maybe String -> Bool -> GHCi ()
installInteractivePrint Nothing _ = return ()
installInteractivePrint (Just ipFun) exprmode = do
ok <- trySuccess $ do
(name:_) <- GHC.parseName ipFun
modifySession (\he -> let new_ic = setInteractivePrintName (hsc_IC he) name
in he{hsc_IC = new_ic})
return Succeeded
when (failed ok && exprmode) $ liftIO (exitWith (ExitFailure 1))
-- | The main read-eval-print loop
runCommands :: InputT GHCi (Maybe String) -> InputT GHCi ()
runCommands gCmd = runCommands' handler Nothing gCmd >> return ()
runCommands' :: (SomeException -> GHCi Bool) -- ^ Exception handler
-> Maybe (GHCi ()) -- ^ Source error handler
-> InputT GHCi (Maybe String)
-> InputT GHCi (Maybe Bool)
-- We want to return () here, but have to return (Maybe Bool)
-- because gmask is not polymorphic enough: we want to use
-- unmask at two different types.
runCommands' eh sourceErrorHandler gCmd = gmask $ \unmask -> do
b <- ghandle (\e -> case fromException e of
Just UserInterrupt -> return $ Just False
_ -> case fromException e of
Just ghce ->
do liftIO (print (ghce :: GhcException))
return Nothing
_other ->
liftIO (Exception.throwIO e))
(unmask $ runOneCommand eh gCmd)
case b of
Nothing -> return Nothing
Just success -> do
unless success $ maybe (return ()) lift sourceErrorHandler
unmask $ runCommands' eh sourceErrorHandler gCmd
-- | Evaluate a single line of user input (either :<command> or Haskell code).
-- A result of Nothing means there was no more input to process.
-- Otherwise the result is Just b where b is True if the command succeeded;
-- this is relevant only to ghc -e, which will exit with status 1
-- if the command was unsuccessful. GHCi will continue in either case.
runOneCommand :: (SomeException -> GHCi Bool) -> InputT GHCi (Maybe String)
-> InputT GHCi (Maybe Bool)
runOneCommand eh gCmd = do
-- run a previously queued command if there is one, otherwise get new
-- input from user
mb_cmd0 <- noSpace (lift queryQueue)
mb_cmd1 <- maybe (noSpace gCmd) (return . Just) mb_cmd0
case mb_cmd1 of
Nothing -> return Nothing
Just c -> ghciHandle (\e -> lift $ eh e >>= return . Just) $
handleSourceError printErrorAndFail
(doCommand c)
-- source error's are handled by runStmt
-- is the handler necessary here?
where
printErrorAndFail err = do
GHC.printException err
return $ Just False -- Exit ghc -e, but not GHCi
noSpace q = q >>= maybe (return Nothing)
(\c -> case removeSpaces c of
"" -> noSpace q
":{" -> multiLineCmd q
_ -> return (Just c) )
multiLineCmd q = do
st <- getGHCiState
let p = prompt st
setGHCiState st{ prompt = prompt_cont st }
mb_cmd <- collectCommand q "" `GHC.gfinally`
modifyGHCiState (\st' -> st' { prompt = p })
return mb_cmd
-- we can't use removeSpaces for the sublines here, so
-- multiline commands are somewhat more brittle against
-- fileformat errors (such as \r in dos input on unix),
-- we get rid of any extra spaces for the ":}" test;
-- we also avoid silent failure if ":}" is not found;
-- and since there is no (?) valid occurrence of \r (as
-- opposed to its String representation, "\r") inside a
-- ghci command, we replace any such with ' ' (argh:-(
collectCommand q c = q >>=
maybe (liftIO (ioError collectError))
(\l->if removeSpaces l == ":}"
then return (Just c)
else collectCommand q (c ++ "\n" ++ map normSpace l))
where normSpace '\r' = ' '
normSpace x = x
-- SDM (2007-11-07): is userError the one to use here?
collectError = userError "unterminated multiline command :{ .. :}"
-- | Handle a line of input
doCommand :: String -> InputT GHCi (Maybe Bool)
-- command
doCommand stmt | (':' : cmd) <- removeSpaces stmt = do
result <- specialCommand cmd
case result of
True -> return Nothing
_ -> return $ Just True
-- haskell
doCommand stmt = do
-- if 'stmt' was entered via ':{' it will contain '\n's
let stmt_nl_cnt = length [ () | '\n' <- stmt ]
ml <- lift $ isOptionSet Multiline
if ml && stmt_nl_cnt == 0 -- don't trigger automatic multi-line mode for ':{'-multiline input
then do
fst_line_num <- line_number <$> getGHCiState
mb_stmt <- checkInputForLayout stmt gCmd
case mb_stmt of
Nothing -> return $ Just True
Just ml_stmt -> do
-- temporarily compensate line-number for multi-line input
result <- timeIt runAllocs $ lift $
runStmtWithLineNum fst_line_num ml_stmt GHC.RunToCompletion
return $ Just (runSuccess result)
else do -- single line input and :{ - multiline input
last_line_num <- line_number <$> getGHCiState
-- reconstruct first line num from last line num and stmt
let fst_line_num | stmt_nl_cnt > 0 = last_line_num - (stmt_nl_cnt2 + 1)
| otherwise = last_line_num -- single line input
stmt_nl_cnt2 = length [ () | '\n' <- stmt' ]
stmt' = dropLeadingWhiteLines stmt -- runStmt doesn't like leading empty lines
-- temporarily compensate line-number for multi-line input
result <- timeIt runAllocs $ lift $
runStmtWithLineNum fst_line_num stmt' GHC.RunToCompletion
return $ Just (runSuccess result)
-- runStmt wrapper for temporarily overridden line-number
runStmtWithLineNum :: Int -> String -> SingleStep
-> GHCi (Maybe GHC.ExecResult)
runStmtWithLineNum lnum stmt step = do
st0 <- getGHCiState
setGHCiState st0 { line_number = lnum }
result <- runStmt stmt step
-- restore original line_number
getGHCiState >>= \st -> setGHCiState st { line_number = line_number st0 }
return result
-- note: this is subtly different from 'unlines . dropWhile (all isSpace) . lines'
dropLeadingWhiteLines s | (l0,'\n':r) <- break (=='\n') s
, all isSpace l0 = dropLeadingWhiteLines r
| otherwise = s
-- #4316
-- lex the input. If there is an unclosed layout context, request input
checkInputForLayout :: String -> InputT GHCi (Maybe String)
-> InputT GHCi (Maybe String)
checkInputForLayout stmt getStmt = do
dflags' <- getDynFlags
let dflags = xopt_set dflags' LangExt.AlternativeLayoutRule
st0 <- getGHCiState
let buf' = stringToStringBuffer stmt
loc = mkRealSrcLoc (fsLit (progname st0)) (line_number st0) 1
pstate = Lexer.mkPState dflags buf' loc
case Lexer.unP goToEnd pstate of
(Lexer.POk _ False) -> return $ Just stmt
_other -> do
st1 <- getGHCiState
let p = prompt st1
setGHCiState st1{ prompt = prompt_cont st1 }
mb_stmt <- ghciHandle (\ex -> case fromException ex of
Just UserInterrupt -> return Nothing
_ -> case fromException ex of
Just ghce ->
do liftIO (print (ghce :: GhcException))
return Nothing
_other -> liftIO (Exception.throwIO ex))
getStmt
modifyGHCiState (\st' -> st' { prompt = p })
-- the recursive call does not recycle parser state
-- as we use a new string buffer
case mb_stmt of
Nothing -> return Nothing
Just str -> if str == ""
then return $ Just stmt
else do
checkInputForLayout (stmt++"\n"++str) getStmt
where goToEnd = do
eof <- Lexer.nextIsEOF
if eof
then Lexer.activeContext
else Lexer.lexer False return >> goToEnd
enqueueCommands :: [String] -> GHCi ()
enqueueCommands cmds = do
-- make sure we force any exceptions in the commands while we're
-- still inside the exception handler, otherwise bad things will
-- happen (see #10501)
cmds `deepseq` return ()
modifyGHCiState $ \st -> st{ cmdqueue = cmds ++ cmdqueue st }
-- | Entry point to execute some haskell code from user.
-- The return value True indicates success, as in `runOneCommand`.
runStmt :: String -> SingleStep -> GHCi (Maybe GHC.ExecResult)
runStmt stmt step = do
dflags <- GHC.getInteractiveDynFlags
if | GHC.isStmt dflags stmt -> run_stmt stmt
| GHC.isImport dflags stmt -> run_import stmt
-- Every import declaration should be handled by `run_import`. As GHCi
-- in general only accepts one command at a time, we simply throw an
-- exception when the input contains multiple commands of which at least
-- one is an import command (see #10663).
| GHC.hasImport dflags stmt -> throwGhcException
(CmdLineError "error: expecting a single import declaration")
-- Note: `GHC.isDecl` returns False on input like
-- `data Infix a b = a :@: b; infixl 4 :@:`
-- and should therefore not be used here.
| otherwise -> run_decl stmt
where
run_import stmt' = do
addImportToContext stmt'
return (Just (GHC.ExecComplete (Right []) 0))
run_decl stmt' =
do _ <- liftIO $ tryIO $ hFlushAll stdin
m_result <- GhciMonad.runDecls stmt'
case m_result of
Nothing -> return Nothing
Just result ->
Just <$> afterRunStmt (const True)
(GHC.ExecComplete (Right result) 0)
run_stmt stmt' =
do -- In the new IO library, read handles buffer data even if the Handle
-- is set to NoBuffering. This causes problems for GHCi where there
-- are really two stdin Handles. So we flush any bufferred data in
-- GHCi's stdin Handle here (only relevant if stdin is attached to
-- a file, otherwise the read buffer can't be flushed).
_ <- liftIO $ tryIO $ hFlushAll stdin
m_result <- GhciMonad.runStmt stmt' step
case m_result of
Nothing -> return Nothing
Just res -> case res of
Right result -> Just <$> afterRunStmt (const True) result
-- If we find a Q Dec or Q [Dec], then run it as a declaration.
Left reinterpret -> case reinterpret of
GHC.ReinterpretDecl -> run_decl stmt'
GHC.ReinterpretAsWrappedDecl -> run_decl ("fmap (:[]) (" ++ stmt' ++ ")")
GHC.ReinterpretRunQ -> run_stmt ("Language.Eta.Meta.runQ (" ++ stmt' ++ ")")
GHC.ReinterpretSplice -> run_stmt ("$(" ++ stmt' ++ ")")
-- | Clean up the GHCi environment after a statement has run
afterRunStmt :: (SrcSpan -> Bool) -> GHC.ExecResult -> GHCi GHC.ExecResult
afterRunStmt step_here run_result = do
resumes <- GHC.getResumeContext
case run_result of
GHC.ExecComplete{..} ->
case execResult of
Left ex -> liftIO $ Exception.throwIO ex
Right names -> do
show_types <- isOptionSet ShowType
when show_types $ printTypeOfNames names
GHC.ExecBreak names mb_info
| isNothing mb_info ||
step_here (GHC.resumeSpan $ head resumes) -> do
mb_id_loc <- toBreakIdAndLocation mb_info
let bCmd = maybe "" ( \(_,l) -> onBreakCmd l ) mb_id_loc
if (null bCmd)
then printStoppedAtBreakInfo (head resumes) names
else enqueueCommands [bCmd]
-- run the command set with ":set stop <cmd>"
st <- getGHCiState
enqueueCommands [stop st]
return ()
| otherwise -> resume step_here GHC.SingleStep >>=
afterRunStmt step_here >> return ()
flushInterpBuffers
withSignalHandlers $ do
b <- isOptionSet RevertCAFs
when b revertCAFs
return run_result
runSuccess :: Maybe GHC.ExecResult -> Bool
runSuccess run_result
| Just (GHC.ExecComplete { execResult = Right _ }) <- run_result = True
| otherwise = False
runAllocs :: Maybe GHC.ExecResult -> Maybe Integer
runAllocs m = do
res <- m
case res of
GHC.ExecComplete{..} -> Just (fromIntegral execAllocation)
_ -> Nothing
toBreakIdAndLocation ::
Maybe GHC.BreakInfo -> GHCi (Maybe (Int, BreakLocation))
toBreakIdAndLocation Nothing = return Nothing
toBreakIdAndLocation (Just inf) = do
let md = GHC.breakInfo_module inf
nm = GHC.breakInfo_number inf
st <- getGHCiState
return $ listToMaybe [ id_loc | id_loc@(_,loc) <- breaks st,
breakModule loc == md,
breakTick loc == nm ]
printStoppedAtBreakInfo :: Resume -> [Name] -> GHCi ()
printStoppedAtBreakInfo res names = do
printForUser $ pprStopped res
-- printTypeOfNames session names
let namesSorted = sortBy compareNames names
_tythings <- catMaybes `liftM` mapM GHC.lookupName namesSorted
panic "pprTypeAndContents: not handled!"
-- docs <- mapM pprTypeAndContents [i | AnId i <- tythings]
-- printForUserPartWay $ vcat docs
printTypeOfNames :: [Name] -> GHCi ()
printTypeOfNames names
= mapM_ (printTypeOfName ) $ sortBy compareNames names
compareNames :: Name -> Name -> Ordering
n1 `compareNames` n2 = compareWith n1 `compare` compareWith n2
where compareWith n = (getOccString n, getSrcSpan n)
printTypeOfName :: Name -> GHCi ()
printTypeOfName n
= do maybe_tything <- GHC.lookupName n
case maybe_tything of
Nothing -> return ()
Just thing -> printTyThing thing
data MaybeCommand = GotCommand Command | BadCommand | NoLastCommand
-- | Entry point for execution a ':<command>' input from user
specialCommand :: String -> InputT GHCi Bool
specialCommand ('!':str) = lift $ shellEscape (dropWhile isSpace str)
specialCommand str = do
let (cmd,rest) = break isSpace str
maybe_cmd <- lift $ lookupCommand cmd
htxt <- short_help <$> getGHCiState
case maybe_cmd of
GotCommand cmd -> (cmdAction cmd) (dropWhile isSpace rest)
BadCommand ->
do liftIO $ hPutStr stdout ("unknown command ':" ++ cmd ++ "'\n"
++ htxt)
return False
NoLastCommand ->
do liftIO $ hPutStr stdout ("there is no last command to perform\n"
++ htxt)
return False
shellEscape :: String -> GHCi Bool
shellEscape str = liftIO (system str >> return False)
lookupCommand :: String -> GHCi (MaybeCommand)
lookupCommand "" = do
st <- getGHCiState
case last_command st of
Just c -> return $ GotCommand c
Nothing -> return NoLastCommand
lookupCommand str = do
mc <- lookupCommand' str
modifyGHCiState (\st -> st { last_command = mc })
return $ case mc of
Just c -> GotCommand c
Nothing -> BadCommand
lookupCommand' :: String -> GHCi (Maybe Command)
lookupCommand' ":" = return Nothing
lookupCommand' str' = do
macros <- ghci_macros <$> getGHCiState
ghci_cmds <- ghci_commands <$> getGHCiState
let ghci_cmds_nohide = filter (not . cmdHidden) ghci_cmds
let (str, xcmds) = case str' of
':' : rest -> (rest, []) -- "::" selects a builtin command
_ -> (str', macros) -- otherwise include macros in lookup
lookupExact s = find $ (s ==) . cmdName
lookupPrefix s = find $ (s `isPrefixOf`) . cmdName
-- hidden commands can only be matched exact
builtinPfxMatch = lookupPrefix str ghci_cmds_nohide
-- first, look for exact match (while preferring macros); then, look
-- for first prefix match (preferring builtins), *unless* a macro
-- overrides the builtin; see #8305 for motivation
return $ lookupExact str xcmds <|>
lookupExact str ghci_cmds <|>
(builtinPfxMatch >>= \c -> lookupExact (cmdName c) xcmds) <|>
builtinPfxMatch <|>
lookupPrefix str xcmds
getCurrentBreakSpan :: GHCi (Maybe SrcSpan)
getCurrentBreakSpan = do
resumes <- GHC.getResumeContext
case resumes of
[] -> return Nothing
(r:_) -> do
let ix = GHC.resumeHistoryIx r
if ix == 0
then return (Just (GHC.resumeSpan r))
else do
let hist = GHC.resumeHistory r !! (ix-1)
pan <- GHC.getHistorySpan hist
return (Just pan)
getCallStackAtCurrentBreakpoint :: GHCi (Maybe [String])
getCallStackAtCurrentBreakpoint = do
resumes <- GHC.getResumeContext
case resumes of
[] -> return Nothing
(_r:_) -> do
_hsc_env <- GHC.getSession
panic "costCentreStackInfo: not handled!"
-- Just <$> liftIO (costCentreStackInfo hsc_env (GHC.resumeCCS r))
getCurrentBreakModule :: GHCi (Maybe Module)
getCurrentBreakModule = do
resumes <- GHC.getResumeContext
case resumes of
[] -> return Nothing
(r:_) -> do
let ix = GHC.resumeHistoryIx r
if ix == 0
then return (GHC.breakInfo_module `liftM` GHC.resumeBreakInfo r)
else do
let hist = GHC.resumeHistory r !! (ix-1)
return $ Just $ GHC.getHistoryModule hist
-----------------------------------------------------------------------------
--
-- Commands
--
-----------------------------------------------------------------------------
noArgs :: GHCi () -> String -> GHCi ()
noArgs m "" = m
noArgs _ _ = liftIO $ putStrLn "This command takes no arguments"
withSandboxOnly :: String -> GHCi () -> GHCi ()
withSandboxOnly cmd this = do
dflags <- getDynFlags
if not (gopt Opt_GhciSandbox dflags)
then printForUser (text cmd <+>
ptext (sLit "is not supported with -fno-eta-repl-sandbox"))
else this
-----------------------------------------------------------------------------
-- :help
help :: String -> GHCi ()
help _ = do
txt <- long_help `fmap` getGHCiState
liftIO $ putStr txt
-----------------------------------------------------------------------------
-- :info
info :: Bool -> String -> InputT GHCi ()
info _ "" = throwGhcException (CmdLineError "syntax: ':i <thing-you-want-info-about>'")
info allInfo s = handleSourceError GHC.printException $ do
unqual <- GHC.getPrintUnqual
dflags <- getDynFlags
sdocs <- mapM (infoThing allInfo) (words s)
mapM_ (liftIO . putStrLn . showSDocForUser dflags unqual) sdocs
infoThing :: GHC.GhcMonad m => Bool -> String -> m SDoc
infoThing allInfo str = do
names <- GHC.parseName str
mb_stuffs <- mapM (GHC.getInfo allInfo) names
let filtered = filterOutChildren (\(t,_f,_ci,_fi,_sd) -> t)
(catMaybes mb_stuffs)
return $ vcat (intersperse (text "") $ map pprInfo filtered)
-- Filter out names whose parent is also there Good
-- example is '[]', which is both a type and data
-- constructor in the same type
filterOutChildren :: (a -> TyThing) -> [a] -> [a]
filterOutChildren get_thing xs
= filterOut has_parent xs
where
all_names = mkNameSet (map (getName . get_thing) xs)
has_parent x = case tyThingParent_maybe (get_thing x) of
Just p -> getName p `elemNameSet` all_names
Nothing -> False
pprInfo :: (TyThing, Fixity, [GHC.ClsInst], [GHC.FamInst], SDoc) -> SDoc
pprInfo (thing, fixity, cls_insts, fam_insts, docs)
= docs
$$ pprTyThingInContextLoc thing
$$ show_fixity
$$ vcat (map GHC.pprInstance cls_insts)
$$ vcat (map GHC.pprFamInst fam_insts)
where
show_fixity
| fixity == GHC.defaultFixity = empty
| otherwise = ppr fixity <+> pprInfixName (GHC.getName thing)
-----------------------------------------------------------------------------
-- :main
runMain :: String -> GHCi ()
runMain s = case toArgs s of
Left err -> liftIO (hPutStrLn stderr err)
Right args ->
do dflags <- getDynFlags
let main = fromMaybe "main" (mainFunIs dflags)
-- Wrap the main function in 'void' to discard its value instead
-- of printing it (#9086). See Haskell 2010 report Chapter 5.
doWithArgs args $ "Control.Monad.void (" ++ main ++ ")"
-----------------------------------------------------------------------------
-- :run
runRun :: String -> GHCi ()
runRun s = case toCmdArgs s of
Left err -> liftIO (hPutStrLn stderr err)
Right (cmd, args) -> doWithArgs args cmd
doWithArgs :: [String] -> String -> GHCi ()
doWithArgs args cmd = enqueueCommands ["System.Environment.withArgs " ++
show args ++ " (" ++ cmd ++ ")"]
-----------------------------------------------------------------------------
-- :cd
changeDirectory :: String -> InputT GHCi ()
changeDirectory "" = do
-- :cd on its own changes to the user's home directory
either_dir <- liftIO $ tryIO getHomeDirectory
case either_dir of
Left _e -> return ()
Right dir -> changeDirectory dir
changeDirectory dir = do
graph <- GHC.getModuleGraph
when (not (null $ GHC.mgModSummaries graph)) $
liftIO $ putStrLn "Warning: changing directory causes all loaded modules to be unloaded,\nbecause the search path has changed."
GHC.setTargets []
_ <- GHC.load LoadAllTargets
lift $ setContextAfterLoad False []
GHC.workingDirectoryChanged
dir' <- expandPath dir
liftIO $ setCurrentDirectory dir'
dflags <- getDynFlags
-- With -fexternal-interpreter, we have to change the directory of the subprocess too.
-- (this gives consistent behaviour with and without -fexternal-interpreter)
when (gopt Opt_ExternalInterpreter dflags) $
lift $ enqueueCommands ["System.Directory.setCurrentDirectory " ++ show dir']
trySuccess :: GHC.GhcMonad m => m SuccessFlag -> m SuccessFlag
trySuccess act =
handleSourceError (\e -> do GHC.printException e
return Failed) $ do
act
-----------------------------------------------------------------------------
-- :edit
editFile :: String -> InputT GHCi ()
editFile str =
do file <- if null str then lift chooseEditFile else expandPath str
st <- getGHCiState
errs <- liftIO $ readIORef $ lastErrorLocations st
let cmd = editor st
when (null cmd)
$ throwGhcException (CmdLineError "editor not set, use :set editor")
lineOpt <- liftIO $ do
let sameFile p1 p2 = liftA2 (==) (canonicalizePath p1) (canonicalizePath p2)
`catchIO` (\_ -> return False)
curFileErrs <- filterM (\(f, _) -> unpackFS f `sameFile` file) errs
return $ case curFileErrs of
(_, line):_ -> " +" ++ show line
_ -> ""
let cmdArgs = ' ':(file ++ lineOpt)
code <- liftIO $ system (cmd ++ cmdArgs)
when (code == ExitSuccess)
$ reloadModule ""
-- The user didn't specify a file so we pick one for them.
-- Our strategy is to pick the first module that failed to load,
-- or otherwise the first target.
--
-- XXX: Can we figure out what happened if the depndecy analysis fails
-- (e.g., because the porgrammeer mistyped the name of a module)?
-- XXX: Can we figure out the location of an error to pass to the editor?
-- XXX: if we could figure out the list of errors that occured during the
-- last load/reaload, then we could start the editor focused on the first
-- of those.
chooseEditFile :: GHCi String
chooseEditFile =
do let hasFailed x = fmap not $ GHC.isLoaded $ GHC.ms_mod_name x
graph <- GHC.getModuleGraph
failed_graph <-
GHC.mkModuleGraph <$> filterM hasFailed (GHC.mgModSummaries graph)
let order g = flattenSCCs $ GHC.topSortModuleGraph True g Nothing
pick xs = case xs of
x : _ -> GHC.ml_hs_file (GHC.ms_location x)
_ -> Nothing
case pick (order failed_graph) of
Just file -> return file
Nothing ->
do targets <- GHC.getTargets
case msum (map fromTarget targets) of
Just file -> return file
Nothing -> throwGhcException (CmdLineError "No files to edit.")
where fromTarget (GHC.Target (GHC.TargetFile f _) _ _) = Just f
fromTarget _ = Nothing -- when would we get a module target?
-----------------------------------------------------------------------------
-- :def
defineMacro :: Bool{-overwrite-} -> String -> GHCi ()
defineMacro _ (':':_) =
liftIO $ putStrLn "macro name cannot start with a colon"
defineMacro overwrite s = do
let (macro_name, definition) = break isSpace s
macros <- ghci_macros <$> getGHCiState
let defined = map cmdName macros
if null macro_name
then if null defined
then liftIO $ putStrLn "no macros defined"
else liftIO $ putStr ("the following macros are defined:\n" ++
unlines defined)
else do
if (not overwrite && macro_name `elem` defined)
then throwGhcException (CmdLineError
("macro '" ++ macro_name ++ "' is already defined"))
else do
-- compile the expression
handleSourceError GHC.printException $ do
step <- getGhciStepIO
expr <- GHC.parseExpr definition
-- > ghciStepIO . definition :: String -> IO String
let stringTy = nlHsTyVar stringTy_RDR
ioM = nlHsTyVar (getRdrName ioTyConName) `nlHsAppTy` stringTy
body = nlHsVar compose_RDR `mkHsApp` (nlHsPar step)
`mkHsApp` (nlHsPar (noLoc expr))
tySig = stringTy `nlHsFunTy` ioM
new_expr = ExprWithTySig body tySig placeHolderType
hv <- GHC.compileParsedExprRemote new_expr
let newCmd = Command { cmdName = macro_name
, cmdAction = lift . runMacro hv
, cmdHidden = False
, cmdCompletionFunc = noCompletion
}
-- later defined macros have precedence
modifyGHCiState $ \s ->
let filtered = [ cmd | cmd <- macros, cmdName cmd /= macro_name ]
in s { ghci_macros = newCmd : filtered }
runMacro :: GHC.ForeignHValue{-String -> IO String-} -> String -> GHCi Bool
runMacro fun s = do
hsc_env <- GHC.getSession
str <- liftIO $ evalStringToIOString hsc_env fun s
enqueueCommands (lines str)
return False
-----------------------------------------------------------------------------
-- :undef
undefineMacro :: String -> GHCi ()
undefineMacro str = mapM_ undef (words str)
where undef macro_name = do
cmds <- ghci_macros <$> getGHCiState
if (macro_name `notElem` map cmdName cmds)
then throwGhcException (CmdLineError
("macro '" ++ macro_name ++ "' is not defined"))
else do
-- This is a tad racy but really, it's a shell
modifyGHCiState $ \s ->
s { ghci_macros = filter ((/= macro_name) . cmdName)
(ghci_macros s) }
-----------------------------------------------------------------------------
-- :cmd
cmdCmd :: String -> GHCi ()
cmdCmd str = handleSourceError GHC.printException $ do
step <- getGhciStepIO
expr <- GHC.parseExpr str
-- > ghciStepIO str :: IO String
let new_expr = step `mkHsApp` noLoc expr
hv <- GHC.compileParsedExprRemote (unLoc new_expr)
hsc_env <- GHC.getSession
cmds <- liftIO $ evalString hsc_env hv
enqueueCommands (lines cmds)
-- | Generate a typed ghciStepIO expression
-- @ghciStepIO :: Ty String -> IO String@.
getGhciStepIO :: GHCi (LHsExpr RdrName)
getGhciStepIO = do
ghciTyConName <- GHC.getGHCiMonad
let stringTy = nlHsTyVar stringTy_RDR
ghciM = nlHsTyVar (getRdrName ghciTyConName) `nlHsAppTy` stringTy
ioM = nlHsTyVar (getRdrName ioTyConName) `nlHsAppTy` stringTy
body = nlHsVar (getRdrName ghciStepIoMName)
tySig = ghciM `nlHsFunTy` ioM
return $ noLoc $ ExprWithTySig body tySig placeHolderType
-----------------------------------------------------------------------------
-- :check
checkModule :: String -> InputT GHCi ()
checkModule m = do
let modl = GHC.mkModuleName m
ok <- handleSourceError (\e -> GHC.printException e >> return False) $ do
r <- GHC.typecheckModule =<< GHC.parseModule =<< GHC.getModSummary modl
dflags <- getDynFlags
liftIO $ putStrLn $ showSDoc dflags $
case GHC.moduleInfo r of
cm | Just scope <- GHC.modInfoTopLevelScope cm ->
let
(loc, glob) = ASSERT( all isExternalName scope )
partition ((== modl) . GHC.moduleName . GHC.nameModule) scope
in
(text "global names: " <+> ppr glob) $$
(text "local names: " <+> ppr loc)
_ -> empty
return True
afterLoad (successIf ok) False
-----------------------------------------------------------------------------
-- :load, :add, :reload
-- | Sets '-fdefer-type-errors' if 'defer' is true, executes 'load' and unsets
-- '-fdefer-type-errors' again if it has not been set before.
wrapDeferTypeErrors :: InputT GHCi a -> InputT GHCi a
wrapDeferTypeErrors load =
gbracket
(do
-- Force originalFlags to avoid leaking the associated HscEnv
!originalFlags <- getDynFlags
void $ GHC.setProgramDynFlags $
setGeneralFlag' Opt_DeferTypeErrors originalFlags
return originalFlags)
(\originalFlags -> void $ GHC.setProgramDynFlags originalFlags)
(\_ -> load)
loadModule :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
loadModule fs = timeIt (const Nothing) (loadModule' fs)
-- | @:load@ command
loadModule_ :: [FilePath] -> InputT GHCi ()
loadModule_ fs = void $ loadModule (zip fs (repeat Nothing))
loadModuleDefer :: [FilePath] -> InputT GHCi ()
loadModuleDefer = wrapDeferTypeErrors . loadModule_
loadModule' :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
loadModule' files = do
let (filenames, phases) = unzip files
exp_filenames <- mapM expandPath filenames
let files' = zip exp_filenames phases
(haskellFiles, otherFiles) = partitionByHaskellish files'
targets <- mapM (uncurry GHC.guessTarget) haskellFiles
-- NOTE: we used to do the dependency anal first, so that if it
-- fails we didn't throw away the current set of modules. This would
-- require some re-working of the GHC interface, so we'll leave it
-- as a ToDo for now.
hsc_env <- GHC.getSession
-- Grab references to the currently loaded modules so that we can
-- see if they leak.
let !dflags = hsc_dflags hsc_env
liftIO $ debugTraceMsg dflags 3 $
text ( "loadModule': haskellFiles=" ++ (show haskellFiles)
++ ", otherFiles=" ++ (show otherFiles))
leak_indicators <- if gopt Opt_EtaReplLeakCheck dflags
then liftIO $ getLeakIndicators hsc_env
else return (panic "no leak indicators")
-- unload first
_ <- GHC.abandonAll
lift discardActiveBreakPoints
GHC.setTargets []
liftIO $ compileAndAddToClasspath hsc_env otherFiles
_ <- GHC.load LoadAllTargets
GHC.setTargets targets
success <- doLoadAndCollectInfo False LoadAllTargets
when (gopt Opt_EtaReplLeakCheck dflags) $
liftIO $ checkLeakIndicators dflags leak_indicators
return success
compileAndAddToClasspath :: GHC.HscEnv -> [(FilePath, Maybe Phase)] -> IO()
compileAndAddToClasspath hsc_env files = do
compiledFiles <- compileFiles hsc_env StopLn files
addDynamicClassPath hsc_env compiledFiles
setClassInfoPath hsc_env compiledFiles
-- | @:add@ command
addModule :: [FilePath] -> InputT GHCi ()
addModule files = do
lift revertCAFs -- always revert CAFs on load/add.
files' <- mapM expandPath files
let filesWithPhase = zip files' (repeat Nothing)
(haskellFiles, otherFiles) = partitionByHaskellish filesWithPhase
haskellFiles' = map fst haskellFiles
targets <- mapM (\m -> GHC.guessTarget m Nothing) haskellFiles'
targets' <- filterM checkTarget targets
-- remove old targets with the same id; e.g. for :add *M
mapM_ GHC.removeTarget [ tid | Target tid _ _ <- targets' ]
hsc_env <- GHC.getSession
liftIO $ compileAndAddToClasspath hsc_env otherFiles
mapM_ GHC.addTarget targets'
_ <- doLoadAndCollectInfo False LoadAllTargets
return ()
where
checkTarget :: Target -> InputT GHCi Bool
checkTarget (Target (TargetModule m) _ _) = checkTargetModule m
checkTarget (Target (TargetFile f _) _ _) = liftIO $ checkTargetFile f
checkTargetModule :: ModuleName -> InputT GHCi Bool
checkTargetModule m = do
hsc_env <- GHC.getSession
result <- liftIO $
Finder.findImportedModule hsc_env m (Just (fsLit "this"))
case result of
Found _ _ -> return True
_ -> (liftIO $ putStrLn $
"Module " ++ moduleNameString m ++ " not found") >> return False
checkTargetFile :: String -> IO Bool
checkTargetFile f = do
exists <- (doesFileExist f) :: IO Bool
unless exists $ putStrLn $ "File " ++ f ++ " not found"
return exists
-- | @:unadd@ command
unAddModule :: [FilePath] -> InputT GHCi ()
unAddModule files = do
files' <- mapM expandPath files
let filesWithPhase = zip files' (repeat Nothing)
(haskellFiles, _) = partitionByHaskellish filesWithPhase
haskellFiles' = map fst haskellFiles
targets <- mapM (\m -> GHC.guessTarget m Nothing) haskellFiles'
mapM_ GHC.removeTarget [ tid | Target tid _ _ <- targets ]
_ <- doLoadAndCollectInfo False LoadAllTargets
return ()
-- | @:reload@ command
reloadModule :: String -> InputT GHCi ()
reloadModule m = void $ doLoadAndCollectInfo True loadTargets
where
loadTargets | null m = LoadAllTargets
| otherwise = LoadUpTo (GHC.mkModuleName m)
reloadModuleDefer :: String -> InputT GHCi ()
reloadModuleDefer = wrapDeferTypeErrors . reloadModule
-- | Load/compile targets and (optionally) collect module-info
--
-- This collects the necessary SrcSpan annotated type information (via
-- 'collectInfo') required by the @:all-types@, @:loc-at@, @:type-at@,
-- and @:uses@ commands.
--
-- Meta-info collection is not enabled by default and needs to be
-- enabled explicitly via @:set +c@. The reason is that collecting
-- the type-information for all sub-spans can be quite expensive, and
-- since those commands are designed to be used by editors and
-- tooling, it's useless to collect this data for normal GHCi
-- sessions.
doLoadAndCollectInfo :: Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
doLoadAndCollectInfo retain_context howmuch = do
doCollectInfo <- lift (isOptionSet CollectInfo)
doLoad retain_context howmuch >>= \case
Succeeded | doCollectInfo -> do
mod_summaries <- GHC.mgModSummaries <$> getModuleGraph
loaded <- filterM GHC.isLoaded $ map GHC.ms_mod_name mod_summaries
v <- mod_infos <$> getGHCiState
!newInfos <- collectInfo v loaded
modifyGHCiState (\st -> st { mod_infos = newInfos })
return Succeeded
flag -> return flag
doLoad :: Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
doLoad retain_context howmuch = do
-- turn off breakpoints before we load: we can't turn them off later, because
-- the ModBreaks will have gone away.
lift discardActiveBreakPoints
lift resetLastErrorLocations
-- Enable buffering stdout and stderr as we're compiling. Keeping these
-- handles unbuffered will just slow the compilation down, especially when
-- compiling in parallel.
gbracket (liftIO $ do hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering)
(\_ ->
liftIO $ do hSetBuffering stdout NoBuffering
hSetBuffering stderr NoBuffering) $ \_ -> do
ok <- trySuccess $ GHC.load howmuch
afterLoad ok retain_context
return ok
afterLoad :: SuccessFlag
-> Bool -- keep the remembered_ctx, as far as possible (:reload)
-> InputT GHCi ()
afterLoad ok retain_context = do
lift revertCAFs -- always revert CAFs on load.
lift discardTickArrays
loaded_mods <- getLoadedModules
modulesLoadedMsg ok loaded_mods
lift $ setContextAfterLoad retain_context loaded_mods
setContextAfterLoad :: Bool -> [GHC.ModSummary] -> GHCi ()
setContextAfterLoad keep_ctxt [] = do
setContextKeepingPackageModules keep_ctxt []
setContextAfterLoad keep_ctxt ms = do
-- load a target if one is available, otherwise load the topmost module.
targets <- GHC.getTargets
case [ m | Just m <- map (findTarget ms) targets ] of
[] ->
let graph = GHC.mkModuleGraph ms
graph' = flattenSCCs (GHC.topSortModuleGraph True graph Nothing)
in load_this (last graph')
(m:_) ->
load_this m
where
findTarget mds t
= case filter (`matches` t) mds of
[] -> Nothing
(m:_) -> Just m
summary `matches` Target (TargetModule m) _ _
= GHC.ms_mod_name summary == m
summary `matches` Target (TargetFile f _) _ _
| Just f' <- GHC.ml_hs_file (GHC.ms_location summary) = f == f'
_ `matches` _
= False
load_this summary | m <- GHC.ms_mod summary = do
is_interp <- GHC.moduleIsInterpreted m
dflags <- getDynFlags
let star_ok = is_interp && not (safeLanguageOn dflags)
-- We import the module with a * iff
-- - it is interpreted, and
-- - -XSafe is off (it doesn't allow *-imports)
let new_ctx | star_ok = [mkIIModule (GHC.moduleName m)]
| otherwise = [mkIIDecl (GHC.moduleName m)]
setContextKeepingPackageModules keep_ctxt new_ctx
-- | Keep any package modules (except Prelude) when changing the context.
setContextKeepingPackageModules
:: Bool -- True <=> keep all of remembered_ctx
-- False <=> just keep package imports
-> [InteractiveImport] -- new context
-> GHCi ()
setContextKeepingPackageModules keep_ctx trans_ctx = do
st <- getGHCiState
let rem_ctx = remembered_ctx st
new_rem_ctx <- if keep_ctx then return rem_ctx
else keepPackageImports rem_ctx
setGHCiState st{ remembered_ctx = new_rem_ctx,
transient_ctx = filterSubsumed new_rem_ctx trans_ctx }
setGHCContextFromGHCiState
-- | Filters a list of 'InteractiveImport', clearing out any home package
-- imports so only imports from external packages are preserved. ('IIModule'
-- counts as a home package import, because we are only able to bring a
-- full top-level into scope when the source is available.)
keepPackageImports :: [InteractiveImport] -> GHCi [InteractiveImport]
keepPackageImports = filterM is_pkg_import
where
is_pkg_import :: InteractiveImport -> GHCi Bool
is_pkg_import (IIModule _) = return False
is_pkg_import (IIDecl d)
= do e <- gtry $ GHC.findModule mod_name (ideclPkgQual d)
case e :: Either SomeException Module of
Left _ -> return False
Right m -> return (not (isHomeModule m))
where
mod_name = unLoc (ideclName d)
modulesLoadedMsg :: SuccessFlag -> [GHC.ModSummary] -> InputT GHCi ()
modulesLoadedMsg ok mods = do
dflags <- getDynFlags
unqual <- GHC.getPrintUnqual
msg <- if gopt Opt_ShowLoadedModules dflags
then do
mod_names <- mapM mod_name mods
let mod_commas
| null mods = text "none."
| otherwise = hsep (punctuate comma mod_names) <> text "."
return $ withBlankLine $ colored color $
status <+> text "Modules loaded:" <+> mod_commas
else do
return $ withBlankLine $ colored color $
status <+> speakNOfCaps (length mods) (text "module") <+> "loaded."
when (verbosity dflags > 0) $
liftIO $ putStrLn $ showSDocForUserColored dflags unqual msg
where
withBlankLine sdoc = vcat [blankLine, blankLine, sdoc]
(status, color) = case ok of
Failed -> (text "Failed!", colRedFg)
Succeeded -> (text "Successful!", colGreenFg)
mod_name mod = do
is_interpreted <- GHC.moduleIsBootOrNotObjectLinkable mod
return $ if is_interpreted
then ppr (GHC.ms_mod mod)
else ppr (GHC.ms_mod mod)
<+> parens (text $ normalise $ msObjFilePath mod)
-- Fix #9887
-- | Run an 'ExceptT' wrapped 'GhcMonad' while handling source errors
-- and printing 'throwE' strings to 'stderr'
runExceptGhcMonad :: GHC.GhcMonad m => ExceptT SDoc m () -> m ()
runExceptGhcMonad act = handleSourceError GHC.printException $
either handleErr pure =<<
runExceptT act
where
handleErr sdoc = do
dflags <- getDynFlags
liftIO . hPutStrLn stderr . showSDocForUser dflags alwaysQualify $ sdoc
-- | Inverse of 'runExceptT' for \"pure\" computations
-- (c.f. 'except' for 'Except')
exceptT :: Applicative m => Either e a -> ExceptT e m a
exceptT = ExceptT . pure
-----------------------------------------------------------------------------
-- | @:type@ command. See also Note [TcRnExprMode] in TcRnDriver.
typeOfExpr :: String -> InputT GHCi ()
typeOfExpr str = handleSourceError GHC.printException $ do
-- let (mode, expr_str) = case break isSpace str of
-- ("+d", rest) -> (GHC.TM_Default, dropWhile isSpace rest)
-- ("+v", rest) -> (GHC.TM_NoInst, dropWhile isSpace rest)
-- _ -> (GHC.TM_Inst, str)
ty <- GHC.exprType str
printForUser $ sep [text str, nest 2 (dcolon <+> pprTypeForUser ty)]
-----------------------------------------------------------------------------
-- | @:type-at@ command
typeAtCmd :: String -> InputT GHCi ()
typeAtCmd str = runExceptGhcMonad $ do
(span',sample) <- exceptT $ parseSpanArg str
infos <- mod_infos <$> getGHCiState
(info, ty) <- findType infos span' sample
lift $ printForUserModInfo (modinfoInfo info)
(sep [text sample,nest 2 (dcolon <+> ppr ty)])
-----------------------------------------------------------------------------
-- | @:uses@ command
usesCmd :: String -> InputT GHCi ()
usesCmd str = runExceptGhcMonad $ do
(span',sample) <- exceptT $ parseSpanArg str
infos <- mod_infos <$> getGHCiState
uses <- findNameUses infos span' sample
forM_ uses (liftIO . putStrLn . showSrcSpan)
-----------------------------------------------------------------------------
-- | @:loc-at@ command
locAtCmd :: String -> InputT GHCi ()
locAtCmd str = runExceptGhcMonad $ do
(span',sample) <- exceptT $ parseSpanArg str
infos <- mod_infos <$> getGHCiState
(_,_,sp) <- findLoc infos span' sample
liftIO . putStrLn . showSrcSpan $ sp
-----------------------------------------------------------------------------
-- | @:all-types@ command
allTypesCmd :: String -> InputT GHCi ()
allTypesCmd _ = runExceptGhcMonad $ do
infos <- mod_infos <$> getGHCiState
forM_ (M.elems infos) $ \mi ->
forM_ (modinfoSpans mi) (lift . printSpan)
where
printSpan span'
| Just ty <- spaninfoType span' = do
df <- getDynFlags
let tyInfo = unwords . words $
showSDocForUser df alwaysQualify (pprTypeForUser ty)
liftIO . putStrLn $
showRealSrcSpan (spaninfoSrcSpan span') ++ ": " ++ tyInfo
| otherwise = return ()
-----------------------------------------------------------------------------
-- Helpers for locAtCmd/typeAtCmd/usesCmd
-- | Parse a span: <module-name/filepath> <sl> <sc> <el> <ec> <string>
parseSpanArg :: String -> Either SDoc (RealSrcSpan,String)
parseSpanArg s = do
(fp,s0) <- readAsString (skipWs s)
s0' <- skipWs1 s0
(sl,s1) <- readAsInt s0'
s1' <- skipWs1 s1
(sc,s2) <- readAsInt s1'
s2' <- skipWs1 s2
(el,s3) <- readAsInt s2'
s3' <- skipWs1 s3
(ec,s4) <- readAsInt s3'
trailer <- case s4 of
[] -> Right ""
_ -> skipWs1 s4
let fs = mkFastString fp
span' = mkRealSrcSpan (mkRealSrcLoc fs sl sc)
(mkRealSrcLoc fs el ec)
return (span',trailer)
where
readAsInt :: String -> Either SDoc (Int,String)
readAsInt "" = Left "Premature end of string while expecting Int"
readAsInt s0 = case reads s0 of
[s_rest] -> Right s_rest
_ -> Left ("Couldn't read" <+> text (show s0) <+> "as Int")
readAsString :: String -> Either SDoc (String,String)
readAsString s0
| '"':_ <- s0 = case reads s0 of
[s_rest] -> Right s_rest
_ -> leftRes
| s_rest@(_:_,_) <- breakWs s0 = Right s_rest
| otherwise = leftRes
where
leftRes = Left ("Couldn't read" <+> text (show s0) <+> "as String")
skipWs1 :: String -> Either SDoc String
skipWs1 (c:cs) | isWs c = Right (skipWs cs)
skipWs1 s0 = Left ("Expected whitespace in" <+> text (show s0))
isWs = (`elem` [' ','\t'])
skipWs = dropWhile isWs
breakWs = break isWs
-- | Pretty-print \"real\" 'SrcSpan's as
-- @<filename>:(<line>,<col>)-(<line-end>,<col-end>)@
-- while simply unpacking 'UnhelpfulSpan's
showSrcSpan :: SrcSpan -> String
showSrcSpan (UnhelpfulSpan s) = unpackFS s
showSrcSpan (RealSrcSpan spn) = showRealSrcSpan spn
-- | Variant of 'showSrcSpan' for 'RealSrcSpan's
showRealSrcSpan :: RealSrcSpan -> String
showRealSrcSpan spn = concat [ fp, ":(", show sl, ",", show sc
, ")-(", show el, ",", show ec, ")"
]
where
fp = unpackFS (srcSpanFile spn)
sl = srcSpanStartLine spn
sc = srcSpanStartCol spn
el = srcSpanEndLine spn
ec = srcSpanEndCol spn
-----------------------------------------------------------------------------
-- | @:kind@ command
kindOfType :: Bool -> String -> InputT GHCi ()
kindOfType norm str = handleSourceError GHC.printException $ do
(ty, kind) <- GHC.typeKind norm str
printForUser $ vcat [ text str <+> dcolon <+> pprTypeForUser kind
, ppWhen norm $ equals <+> pprTypeForUser ty ]
-----------------------------------------------------------------------------
-- :exit
exit :: String -> InputT GHCi Bool
exit _ = return True
-----------------------------------------------------------------------------
-- :script
-- running a script file #1363
scriptCmd :: String -> InputT GHCi ()
scriptCmd ws = do
case words ws of
[s] -> runScript s
_ -> throwGhcException (CmdLineError "syntax: :script <filename>")
runScript :: String -- ^ filename
-> InputT GHCi ()
runScript filename = do
filename' <- expandPath filename
either_script <- liftIO $ tryIO (openFile filename' ReadMode)
case either_script of
Left _err -> throwGhcException (CmdLineError $ "IO error: \""++filename++"\" "
++(ioeGetErrorString _err))
Right script -> do
st <- getGHCiState
let prog = progname st
line = line_number st
setGHCiState st{progname=filename',line_number=0}
scriptLoop script
liftIO $ hClose script
new_st <- getGHCiState
setGHCiState new_st{progname=prog,line_number=line}
where scriptLoop script = do
res <- runOneCommand handler $ fileLoop script
case res of
Nothing -> return ()
Just s -> if s
then scriptLoop script
else return ()
-----------------------------------------------------------------------------
-- :issafe
-- Displaying Safe Haskell properties of a module
isSafeCmd :: String -> InputT GHCi ()
isSafeCmd m =
case words m of
[s] | looksLikeModuleName s -> do
md <- lift $ lookupModule s
isSafeModule md
[] -> do md <- guessCurrentModule "issafe"
isSafeModule md
_ -> throwGhcException (CmdLineError "syntax: :issafe <module>")
isSafeModule :: Module -> InputT GHCi ()
isSafeModule m = do
mb_mod_info <- GHC.getModuleInfo m
when (isNothing mb_mod_info)
(throwGhcException $ CmdLineError $ "unknown module: " ++ mname)
dflags <- getDynFlags
let iface = GHC.modInfoIface $ fromJust mb_mod_info
when (isNothing iface)
(throwGhcException $ CmdLineError $ "can't load interface file for module: " ++
(GHC.moduleNameString $ GHC.moduleName m))
(msafe, pkgs) <- GHC.moduleTrustReqs m
let trust = showPpr dflags $ getSafeMode $ GHC.mi_trust $ fromJust iface
pkg = if packageTrusted dflags m then "trusted" else "untrusted"
(good, bad) = tallyPkgs dflags pkgs
-- print info to user...
liftIO $ putStrLn $ "Trust type is (Module: " ++ trust ++ ", Package: " ++ pkg ++ ")"
liftIO $ putStrLn $ "Package Trust: " ++ (if packageTrustOn dflags then "On" else "Off")
when (not $ S.null good)
(liftIO $ putStrLn $ "Trusted package dependencies (trusted): " ++
(intercalate ", " $ map (showPpr dflags) (S.toList good)))
case msafe && S.null bad of
True -> liftIO $ putStrLn $ mname ++ " is trusted!"
False -> do
when (not $ null bad)
(liftIO $ putStrLn $ "Trusted package dependencies (untrusted): "
++ (intercalate ", " $ map (showPpr dflags) (S.toList bad)))
liftIO $ putStrLn $ mname ++ " is NOT trusted!"
where
mname = GHC.moduleNameString $ GHC.moduleName m
packageTrusted dflags md
| thisPackage dflags == moduleUnitId md = True
| otherwise = trusted $ getPackageDetails dflags (moduleUnitId md)
tallyPkgs dflags deps | not (packageTrustOn dflags) = (S.empty, S.empty)
| otherwise = S.partition part deps
where part pkg = trusted $ getInstalledPackageDetails dflags pkg
-----------------------------------------------------------------------------
-- :browse
-- Browsing a module's contents
browseCmd :: Bool -> String -> InputT GHCi ()
browseCmd bang m =
case words m of
['*':s] | looksLikeModuleName s -> do
md <- lift $ wantInterpretedModule s
browseModule bang md False
[s] | looksLikeModuleName s -> do
md <- lift $ lookupModule s
browseModule bang md True
[] -> do md <- guessCurrentModule ("browse" ++ if bang then "!" else "")
browseModule bang md True
_ -> throwGhcException (CmdLineError "syntax: :browse <module>")
guessCurrentModule :: String -> InputT GHCi Module
-- Guess which module the user wants to browse. Pick
-- modules that are interpreted first. The most
-- recently-added module occurs last, it seems.
guessCurrentModule cmd
= do imports <- GHC.getContext
when (null imports) $ throwGhcException $
CmdLineError (':' : cmd ++ ": no current module")
case (head imports) of
IIModule m -> GHC.findModule m Nothing
IIDecl d -> GHC.findModule (unLoc (ideclName d))
(ideclPkgQual d)
-- without bang, show items in context of their parents and omit children
-- with bang, show class methods and data constructors separately, and
-- indicate import modules, to aid qualifying unqualified names
-- with sorted, sort items alphabetically
browseModule :: Bool -> Module -> Bool -> InputT GHCi ()
browseModule bang modl exports_only = do
-- :browse reports qualifiers wrt current context
unqual <- GHC.getPrintUnqual
mb_mod_info <- GHC.getModuleInfo modl
case mb_mod_info of
Nothing -> throwGhcException (CmdLineError ("unknown module: " ++
GHC.moduleNameString (GHC.moduleName modl)))
Just mod_info -> do
dflags <- getDynFlags
let names
| exports_only = GHC.modInfoExports mod_info
| otherwise = GHC.modInfoTopLevelScope mod_info
`orElse` []
-- sort alphabetically name, but putting locally-defined
-- identifiers first. We would like to improve this; see #1799.
sorted_names = loc_sort local ++ occ_sort external
where
(local,external) = ASSERT( all isExternalName names )
partition ((==modl) . nameModule) names
occ_sort = sortBy (compare `on` nameOccName)
-- try to sort by src location. If the first name in our list
-- has a good source location, then they all should.
loc_sort ns
| n:_ <- ns, isGoodSrcSpan (nameSrcSpan n)
= sortBy (compare `on` nameSrcSpan) ns
| otherwise
= occ_sort ns
mb_things <- mapM GHC.lookupName sorted_names
let filtered_things = filterOutChildren (\t -> t) (catMaybes mb_things)
rdr_env <- GHC.getGRE
let things | bang = catMaybes mb_things
| otherwise = filtered_things
pretty | bang = pprTyThing
| otherwise = pprTyThingInContext
labels [] = text "-- not currently imported"
labels l = text $ intercalate "\n" $ map qualifier l
qualifier :: Maybe [ModuleName] -> String
qualifier = maybe "-- defined locally"
(("-- imported via "++) . intercalate ", "
. map GHC.moduleNameString)
importInfo = RdrName.getGRE_NameQualifier_maybes rdr_env
modNames :: [[Maybe [ModuleName]]]
modNames = map (importInfo . GHC.getName) things
-- annotate groups of imports with their import modules
-- the default ordering is somewhat arbitrary, so we group
-- by header and sort groups; the names themselves should
-- really come in order of source appearance.. (trac #1799)
annotate mts = concatMap (\(m,ts)->labels m:ts)
$ sortBy cmpQualifiers $ grp mts
where cmpQualifiers =
compare `on` (map (fmap (map moduleNameFS)) . fst)
grp [] = []
grp mts@((m,_):_) = (m,map snd g) : grp ng
where (g,ng) = partition ((==m).fst) mts
let prettyThings, prettyThings' :: [SDoc]
prettyThings = map pretty things
prettyThings' | bang = annotate $ zip modNames prettyThings
| otherwise = prettyThings
liftIO $ putStrLn $ showSDocForUser dflags unqual (vcat prettyThings')
-- ToDo: modInfoInstances currently throws an exception for
-- package modules. When it works, we can do this:
-- $$ vcat (map GHC.pprInstance (GHC.modInfoInstances mod_info))
-----------------------------------------------------------------------------
-- :module
-- Setting the module context. For details on context handling see
-- "remembered_ctx" and "transient_ctx" in GhciMonad.
moduleCmd :: String -> GHCi ()
moduleCmd str
| all sensible strs = cmd
| otherwise = throwGhcException (CmdLineError "syntax: :module [+/-] [*]M1 ... [*]Mn")
where
(cmd, strs) =
case str of
'+':stuff -> rest addModulesToContext stuff
'-':stuff -> rest remModulesFromContext stuff
stuff -> rest setContext stuff
rest op stuff = (op as bs, stuffs)
where (as,bs) = partitionWith starred stuffs
stuffs = words stuff
sensible ('*':m) = looksLikeModuleName m
sensible m = looksLikeModuleName m
starred ('*':m) = Left (GHC.mkModuleName m)
starred m = Right (GHC.mkModuleName m)
-- -----------------------------------------------------------------------------
-- Four ways to manipulate the context:
-- (a) :module +<stuff>: addModulesToContext
-- (b) :module -<stuff>: remModulesFromContext
-- (c) :module <stuff>: setContext
-- (d) import <module>...: addImportToContext
addModulesToContext :: [ModuleName] -> [ModuleName] -> GHCi ()
addModulesToContext starred unstarred = restoreContextOnFailure $ do
addModulesToContext_ starred unstarred
addModulesToContext_ :: [ModuleName] -> [ModuleName] -> GHCi ()
addModulesToContext_ starred unstarred = do
mapM_ addII (map mkIIModule starred ++ map mkIIDecl unstarred)
setGHCContextFromGHCiState
remModulesFromContext :: [ModuleName] -> [ModuleName] -> GHCi ()
remModulesFromContext starred unstarred = do
-- we do *not* call restoreContextOnFailure here. If the user
-- is trying to fix up a context that contains errors by removing
-- modules, we don't want GHC to silently put them back in again.
mapM_ rm (starred ++ unstarred)
setGHCContextFromGHCiState
where
rm :: ModuleName -> GHCi ()
rm str = do
m <- moduleName <$> lookupModuleName str
let filt = filter ((/=) m . iiModuleName)
modifyGHCiState $ \st ->
st { remembered_ctx = filt (remembered_ctx st)
, transient_ctx = filt (transient_ctx st) }
setContext :: [ModuleName] -> [ModuleName] -> GHCi ()
setContext starred unstarred = restoreContextOnFailure $ do
modifyGHCiState $ \st -> st { remembered_ctx = [], transient_ctx = [] }
-- delete the transient context
addModulesToContext_ starred unstarred
addImportToContext :: String -> GHCi ()
addImportToContext str = restoreContextOnFailure $ do
idecl <- GHC.parseImportDecl str
addII (IIDecl idecl) -- #5836
setGHCContextFromGHCiState
-- Util used by addImportToContext and addModulesToContext
addII :: InteractiveImport -> GHCi ()
addII iidecl = do
checkAdd iidecl
modifyGHCiState $ \st ->
st { remembered_ctx = addNotSubsumed iidecl (remembered_ctx st)
, transient_ctx = filter (not . (iidecl `iiSubsumes`))
(transient_ctx st)
}
-- Sometimes we can't tell whether an import is valid or not until
-- we finally call 'GHC.setContext'. e.g.
--
-- import System.IO (foo)
--
-- will fail because System.IO does not export foo. In this case we
-- don't want to store the import in the context permanently, so we
-- catch the failure from 'setGHCContextFromGHCiState' and set the
-- context back to what it was.
--
-- See #6007
--
restoreContextOnFailure :: GHCi a -> GHCi a
restoreContextOnFailure do_this = do
st <- getGHCiState
let rc = remembered_ctx st; tc = transient_ctx st
do_this `gonException` (modifyGHCiState $ \st' ->
st' { remembered_ctx = rc, transient_ctx = tc })
-- -----------------------------------------------------------------------------
-- Validate a module that we want to add to the context
checkAdd :: InteractiveImport -> GHCi ()
checkAdd ii = do
dflags <- getDynFlags
let safe = safeLanguageOn dflags
case ii of
IIModule modname
| safe -> throwGhcException $ CmdLineError "can't use * imports with Safe Haskell"
| otherwise -> wantInterpretedModuleName modname >> return ()
IIDecl d -> do
let modname = unLoc (ideclName d)
pkgqual = ideclPkgQual d
m <- GHC.lookupModule modname pkgqual
when safe $ do
t <- GHC.isModuleTrusted m
when (not t) $ throwGhcException $ ProgramError $ ""
-- -----------------------------------------------------------------------------
-- Update the GHC API's view of the context
-- | Sets the GHC context from the GHCi state. The GHC context is
-- always set this way, we never modify it incrementally.
--
-- We ignore any imports for which the ModuleName does not currently
-- exist. This is so that the remembered_ctx can contain imports for
-- modules that are not currently loaded, perhaps because we just did
-- a :reload and encountered errors.
--
-- Prelude is added if not already present in the list. Therefore to
-- override the implicit Prelude import you can say 'import Prelude ()'
-- at the prompt, just as in Haskell source.
--
setGHCContextFromGHCiState :: GHCi ()
setGHCContextFromGHCiState = do
st <- getGHCiState
-- re-use checkAdd to check whether the module is valid. If the
-- module does not exist, we do *not* want to print an error
-- here, we just want to silently keep the module in the context
-- until such time as the module reappears again. So we ignore
-- the actual exception thrown by checkAdd, using tryBool to
-- turn it into a Bool.
iidecls <- filterM (tryBool.checkAdd) (transient_ctx st ++ remembered_ctx st)
prel_iidecls <- getImplicitPreludeImports iidecls
valid_prel_iidecls <- filterM (tryBool . checkAdd) prel_iidecls
extra_imports <- filterM (tryBool . checkAdd) (map IIDecl (extra_imports st))
GHC.setContext $ iidecls ++ extra_imports ++ valid_prel_iidecls
getImplicitPreludeImports :: [InteractiveImport] -> GHCi [InteractiveImport]
getImplicitPreludeImports iidecls = do
dflags <- GHC.getInteractiveDynFlags
-- allow :seti to override -XNoImplicitPrelude
st <- getGHCiState
-- We add the prelude imports if there are no *-imports, and we also
-- allow each prelude import to be subsumed by another explicit import
-- of the same module. This means that you can override the prelude import
-- with "import Prelude hiding (map)", for example.
let prel_iidecls =
if xopt LangExt.ImplicitPrelude dflags && not (any isIIModule iidecls)
then [ IIDecl imp
| imp <- prelude_imports st
, not (any (sameImpModule imp) iidecls) ]
else []
return prel_iidecls
-- -----------------------------------------------------------------------------
-- Utils on InteractiveImport
mkIIModule :: ModuleName -> InteractiveImport
mkIIModule = IIModule
mkIIDecl :: ModuleName -> InteractiveImport
mkIIDecl = IIDecl . simpleImportDecl
iiModules :: [InteractiveImport] -> [ModuleName]
iiModules is = [m | IIModule m <- is]
isIIModule :: InteractiveImport -> Bool
isIIModule (IIModule _) = True
isIIModule _ = False
iiModuleName :: InteractiveImport -> ModuleName
iiModuleName (IIModule m) = m
iiModuleName (IIDecl d) = unLoc (ideclName d)
preludeModuleName :: ModuleName
preludeModuleName = GHC.mkModuleName "Prelude"
sameImpModule :: ImportDecl RdrName -> InteractiveImport -> Bool
sameImpModule _ (IIModule _) = False -- we only care about imports here
sameImpModule imp (IIDecl d) = unLoc (ideclName d) == unLoc (ideclName imp)
addNotSubsumed :: InteractiveImport
-> [InteractiveImport] -> [InteractiveImport]
addNotSubsumed i is
| any (`iiSubsumes` i) is = is
| otherwise = i : filter (not . (i `iiSubsumes`)) is
-- | @filterSubsumed is js@ returns the elements of @js@ not subsumed
-- by any of @is@.
filterSubsumed :: [InteractiveImport] -> [InteractiveImport]
-> [InteractiveImport]
filterSubsumed is js = filter (\j -> not (any (`iiSubsumes` j) is)) js
-- | Returns True if the left import subsumes the right one. Doesn't
-- need to be 100% accurate, conservatively returning False is fine.
-- (EXCEPT: (IIModule m) *must* subsume itself, otherwise a panic in
-- plusProv will ensue (#5904))
--
-- Note that an IIModule does not necessarily subsume an IIDecl,
-- because e.g. a module might export a name that is only available
-- qualified within the module itself.
--
-- Note that 'import M' does not necessarily subsume 'import M(foo)',
-- because M might not export foo and we want an error to be produced
-- in that case.
--
iiSubsumes :: InteractiveImport -> InteractiveImport -> Bool
iiSubsumes (IIModule m1) (IIModule m2) = m1==m2
iiSubsumes (IIDecl d1) (IIDecl d2) -- A bit crude
= unLoc (ideclName d1) == unLoc (ideclName d2)
&& ideclAs d1 == ideclAs d2
&& (not (ideclQualified d1) || ideclQualified d2)
&& (ideclHiding d1 `hidingSubsumes` ideclHiding d2)
where
_ `hidingSubsumes` Just (False,L _ []) = True
Just (False, L _ xs) `hidingSubsumes` Just (False,L _ ys)
= all (`elem` xs) ys
h1 `hidingSubsumes` h2 = h1 == h2
iiSubsumes _ _ = False
----------------------------------------------------------------------------
-- :set
-- set options in the interpreter. Syntax is exactly the same as the
-- ghc command line, except that certain options aren't available (-C,
-- -E etc.)
--
-- This is pretty fragile: most options won't work as expected. ToDo:
-- figure out which ones & disallow them.
setCmd :: String -> GHCi ()
setCmd "" = showOptions False
setCmd "-a" = showOptions True
setCmd str
= case getCmd str of
Right ("args", rest) ->
case toArgs rest of
Left err -> liftIO (hPutStrLn stderr err)
Right args -> setArgs args
Right ("prog", rest) ->
case toArgs rest of
Right [prog] -> setProg prog
_ -> liftIO (hPutStrLn stderr "syntax: :set prog <progname>")
Right ("prompt", rest) ->
setPromptString setPrompt (dropWhile isSpace rest)
"syntax: set prompt <string>"
Right ("prompt-function", rest) ->
setPromptFunc setPrompt $ dropWhile isSpace rest
Right ("prompt-cont", rest) ->
setPromptString setPromptCont (dropWhile isSpace rest)
"syntax: :set prompt-cont <string>"
Right ("prompt-cont-function", rest) ->
setPromptFunc setPromptCont $ dropWhile isSpace rest
Right ("editor", rest) -> setEditor $ dropWhile isSpace rest
Right ("stop", rest) -> setStop $ dropWhile isSpace rest
_ -> case toArgs str of
Left err -> liftIO (hPutStrLn stderr err)
Right wds -> setOptions wds
setiCmd :: String -> GHCi ()
setiCmd "" = GHC.getInteractiveDynFlags >>= liftIO . showDynFlags False
setiCmd "-a" = GHC.getInteractiveDynFlags >>= liftIO . showDynFlags True
setiCmd str =
case toArgs str of
Left err -> liftIO (hPutStrLn stderr err)
Right wds -> newDynFlags True wds
showOptions :: Bool -> GHCi ()
showOptions show_all
= do st <- getGHCiState
dflags <- getDynFlags
let opts = options st
liftIO $ putStrLn (showSDoc dflags (
text "options currently set: " <>
if null opts
then text "none."
else hsep (map (\o -> char '+' <> text (optToStr o)) opts)
))
getDynFlags >>= liftIO . showDynFlags show_all
showDynFlags :: Bool -> DynFlags -> IO ()
showDynFlags show_all dflags = do
showLanguages' show_all dflags
putStrLn $ showSDoc dflags $
text "Eta REPL-specific dynamic flag settings:" $$
nest 2 (vcat (map (setting "-f" "-fno-" gopt) ghciFlags))
putStrLn $ showSDoc dflags $
text "other dynamic, non-language, flag settings:" $$
nest 2 (vcat (map (setting "-f" "-fno-" gopt) others))
putStrLn $ showSDoc dflags $
text "warning settings:" $$
nest 2 (vcat (map (setting "-W" "-Wno-" wopt) DynFlags.wWarningFlags))
where
setting prefix noPrefix test flag
| quiet = empty
| is_on = text prefix <> text name
| otherwise = text noPrefix <> text name
where name = flagSpecName flag
f = flagSpecFlag flag
is_on = test f dflags
quiet = not show_all && test f default_dflags == is_on
default_dflags = defaultDynFlags (settings dflags)
(ghciFlags,others) = partition (\f -> flagSpecFlag f `elem` flgs)
DynFlags.fFlags
flgs = [ Opt_PrintExplicitForalls
, Opt_PrintExplicitKinds
, Opt_PrintUnicodeSyntax
, Opt_PrintBindResult
, Opt_BreakOnException
, Opt_BreakOnError
, Opt_PrintEvldWithShow
]
setArgs, setOptions :: [String] -> GHCi ()
setProg, setEditor, setStop :: String -> GHCi ()
setArgs args = do
st <- getGHCiState
wrapper <- mkEvalWrapper (progname st) args
setGHCiState st { GhciMonad.args = args, evalWrapper = wrapper }
setProg prog = do
st <- getGHCiState
wrapper <- mkEvalWrapper prog (GhciMonad.args st)
setGHCiState st { progname = prog, evalWrapper = wrapper }
setEditor cmd = modifyGHCiState (\st -> st { editor = cmd })
setStop str@(c:_) | isDigit c
= do let (nm_str,rest) = break (not.isDigit) str
nm = read nm_str
st <- getGHCiState
let old_breaks = breaks st
if all ((/= nm) . fst) old_breaks
then printForUser (text "Breakpoint" <+> ppr nm <+>
text "does not exist")
else do
let new_breaks = map fn old_breaks
fn (i,loc) | i == nm = (i,loc { onBreakCmd = dropWhile isSpace rest })
| otherwise = (i,loc)
setGHCiState st{ breaks = new_breaks }
setStop cmd = modifyGHCiState (\st -> st { stop = cmd })
setPrompt :: PromptFunction -> GHCi ()
setPrompt v = modifyGHCiState (\st -> st {prompt = v})
setPromptCont :: PromptFunction -> GHCi ()
setPromptCont v = modifyGHCiState (\st -> st {prompt_cont = v})
setPromptFunc :: (PromptFunction -> GHCi ()) -> String -> GHCi ()
setPromptFunc fSetPrompt s = do
-- We explicitly annotate the type of the expression to ensure
-- that unsafeCoerce# is passed the exact type necessary rather
-- than a more general one
let exprStr = "(" ++ s ++ ") :: [String] -> Int -> IO String"
(HValue funValue) <- GHC.compileExpr exprStr
fSetPrompt (convertToPromptFunction $ unsafeCoerce funValue)
where
convertToPromptFunction :: ([String] -> Int -> IO String)
-> PromptFunction
convertToPromptFunction func = (\mods line -> liftIO $
liftM text (func mods line))
setPromptString :: (PromptFunction -> GHCi ()) -> String -> String -> GHCi ()
setPromptString fSetPrompt value err = do
if null value
then liftIO $ hPutStrLn stderr $ err
else case value of
('\"':_) ->
case reads value of
[(value', xs)] | all isSpace xs ->
setParsedPromptString fSetPrompt value'
_ -> liftIO $ hPutStrLn stderr
"Can't parse prompt string. Use Haskell syntax."
_ ->
setParsedPromptString fSetPrompt value
setParsedPromptString :: (PromptFunction -> GHCi ()) -> String -> GHCi ()
setParsedPromptString fSetPrompt s = do
case (checkPromptStringForErrors s) of
Just err ->
liftIO $ hPutStrLn stderr err
Nothing ->
fSetPrompt $ generatePromptFunctionFromString s
setOptions wds =
do -- first, deal with the GHCi opts (+s, +t, etc.)
let (plus_opts, minus_opts) = partitionWith isPlus wds
mapM_ setOpt plus_opts
-- then, dynamic flags
when (not (null minus_opts)) $ newDynFlags False minus_opts
newDynFlags :: Bool -> [String] -> GHCi ()
newDynFlags interactive_only minus_opts = do
let lopts = map noLoc minus_opts
idflags0 <- GHC.getInteractiveDynFlags
(idflags1, leftovers, warns) <- GHC.parseDynamicFlags idflags0 lopts
liftIO $ handleFlagWarnings idflags1 warns
when (not $ null leftovers)
(throwGhcException . CmdLineError
$ "Some flags have not been recognized: "
++ (concat . intersperse ", " $ map unLoc leftovers))
when (interactive_only && packageFlagsChanged idflags1 idflags0) $ do
liftIO $ hPutStrLn stderr "cannot set package flags with :seti; use :set"
GHC.setInteractiveDynFlags idflags1
installInteractivePrint (interactivePrint idflags1) False
dflags0 <- getDynFlags
when (not interactive_only) $ do
(dflags1, _, _) <- liftIO $ GHC.parseDynamicFlags dflags0 lopts
_new_pkgs <- GHC.setProgramDynFlags dflags1
-- if the package flags changed, reset the context and link
-- the new packages.
hsc_env <- GHC.getSession
let dflags2 = hsc_dflags hsc_env
when (packageFlagsChanged dflags2 dflags0) $ do
when (verbosity dflags2 > 0) $
liftIO . putStrLn $
"package flags have changed, resetting and loading new packages..."
GHC.setTargets []
_ <- GHC.load LoadAllTargets
_ <- panic "linkPackages: not handled!"
-- liftIO $ linkPackages hsc_env new_pkgs
-- package flags changed, we can't re-use any of the old context
setContextAfterLoad False []
-- and copy the package state to the interactive DynFlags
idflags <- GHC.getInteractiveDynFlags
GHC.setInteractiveDynFlags
idflags{ pkgState = pkgState dflags2
, pkgDatabase = pkgDatabase dflags2
, packageFlags = packageFlags dflags2 }
let ld0length = length $ ldInputs dflags0
fmrk0length = length $ cmdlineFrameworks dflags0
newLdInputs = drop ld0length (ldInputs dflags2)
newCLFrameworks = drop fmrk0length (cmdlineFrameworks dflags2)
_hsc_env' = hsc_env { hsc_dflags =
dflags2 { ldInputs = newLdInputs
, cmdlineFrameworks = newCLFrameworks } }
when (not (null newLdInputs && null newCLFrameworks)) $
panic "linkCmdLineLibs: not handled!"
-- liftIO $ linkCmdLineLibs hsc_env'
return ()
unsetOptions :: String -> GHCi ()
unsetOptions str
= -- first, deal with the GHCi opts (+s, +t, etc.)
let opts = words str
(minus_opts, rest1) = partition isMinus opts
(plus_opts, rest2) = partitionWith isPlus rest1
(other_opts, rest3) = partition (`elem` map fst defaulters) rest2
defaulters =
[ ("args" , setArgs default_args)
, ("prog" , setProg default_progname)
, ("prompt" , setPrompt default_prompt)
, ("prompt-cont", setPromptCont default_prompt_cont)
, ("editor" , liftIO findEditor >>= setEditor)
, ("stop" , setStop default_stop)
]
no_flag ('-':'f':rest) = return ("-fno-" ++ rest)
no_flag ('-':'X':rest) = return ("-XNo" ++ rest)
no_flag f = throwGhcException (ProgramError ("don't know how to reverse " ++ f))
in if (not (null rest3))
then liftIO (putStrLn ("unknown option: '" ++ head rest3 ++ "'"))
else do
mapM_ (fromJust.flip lookup defaulters) other_opts
mapM_ unsetOpt plus_opts
no_flags <- mapM no_flag minus_opts
when (not (null no_flags)) $ newDynFlags False no_flags
isMinus :: String -> Bool
isMinus ('-':_) = True
isMinus _ = False
isPlus :: String -> Either String String
isPlus ('+':opt) = Left opt
isPlus other = Right other
setOpt, unsetOpt :: String -> GHCi ()
setOpt str
= case strToGHCiOpt str of
Nothing -> liftIO (putStrLn ("unknown option: '" ++ str ++ "'"))
Just o -> setOption o
unsetOpt str
= case strToGHCiOpt str of
Nothing -> liftIO (putStrLn ("unknown option: '" ++ str ++ "'"))
Just o -> unsetOption o
strToGHCiOpt :: String -> (Maybe GHCiOption)
strToGHCiOpt "m" = Just Multiline
strToGHCiOpt "s" = Just ShowTiming
strToGHCiOpt "t" = Just ShowType
strToGHCiOpt "r" = Just RevertCAFs
strToGHCiOpt "c" = Just CollectInfo
strToGHCiOpt _ = Nothing
optToStr :: GHCiOption -> String
optToStr Multiline = "m"
optToStr ShowTiming = "s"
optToStr ShowType = "t"
optToStr RevertCAFs = "r"
optToStr CollectInfo = "c"
-- ---------------------------------------------------------------------------
-- :show
showCmd :: String -> GHCi ()
showCmd "" = showOptions False
showCmd "-a" = showOptions True
showCmd str = do
st <- getGHCiState
dflags <- getDynFlags
let lookupCmd :: String -> Maybe (GHCi ())
lookupCmd name = lookup name $ map (\(_,b,c) -> (b,c)) cmds
-- (show in help?, command name, action)
action :: String -> GHCi () -> (Bool, String, GHCi ())
action name m = (True, name, m)
hidden :: String -> GHCi () -> (Bool, String, GHCi ())
hidden name m = (False, name, m)
cmds =
[ action "args" $ liftIO $ putStrLn (show (GhciMonad.args st))
, action "prog" $ liftIO $ putStrLn (show (progname st))
, action "editor" $ liftIO $ putStrLn (show (editor st))
, action "stop" $ liftIO $ putStrLn (show (stop st))
, action "imports" $ showImports
, action "modules" $ showModules
, action "bindings" $ showBindings
, action "linker" $ getDynFlags >>= liftIO . showLinkerState
, action "breaks" $ showBkptTable
, action "context" $ showContext
, action "packages" $ showPackages
, action "paths" $ showPaths
, action "language" $ showLanguages
, hidden "languages" $ showLanguages -- backwards compat
, hidden "lang" $ showLanguages -- useful abbreviation
, action "targets" $ showTargets
]
case words str of
[w] | Just action <- lookupCmd w -> action
_ -> let helpCmds = [ text name | (True, name, _) <- cmds ]
in throwGhcException $ CmdLineError $ showSDoc dflags
$ hang (text "syntax:") 4
$ hang (text ":show") 6
$ brackets (fsep $ punctuate (text " |") helpCmds)
showiCmd :: String -> GHCi ()
showiCmd str = do
case words str of
["languages"] -> showiLanguages -- backwards compat
["language"] -> showiLanguages
["lang"] -> showiLanguages -- useful abbreviation
_ -> throwGhcException (CmdLineError ("syntax: :showi language"))
showImports :: GHCi ()
showImports = do
st <- getGHCiState
dflags <- getDynFlags
let rem_ctx = reverse (remembered_ctx st)
trans_ctx = transient_ctx st
show_one (IIModule star_m)
= ":module +*" ++ moduleNameString star_m
show_one (IIDecl imp) = showPpr dflags imp
prel_iidecls <- getImplicitPreludeImports (rem_ctx ++ trans_ctx)
let show_prel p = show_one p ++ " -- implicit"
show_extra p = show_one (IIDecl p) ++ " -- fixed"
trans_comment s = s ++ " -- added automatically" :: String
--
liftIO $ mapM_ putStrLn (map show_one rem_ctx ++
map (trans_comment . show_one) trans_ctx ++
map show_prel prel_iidecls ++
map show_extra (extra_imports st))
showModules :: GHCi ()
showModules = do
loaded_mods <- getLoadedModules
-- we want *loaded* modules only, see #1734
let show_one ms = do m <- GHC.showModule ms; liftIO (putStrLn m)
mapM_ show_one loaded_mods
getLoadedModules :: GHC.GhcMonad m => m [GHC.ModSummary]
getLoadedModules = do
graph <- GHC.getModuleGraph
filterM (GHC.isLoaded . GHC.ms_mod_name) (GHC.mgModSummaries graph)
showBindings :: GHCi ()
showBindings = do
bindings <- GHC.getBindings
(insts, finsts) <- GHC.getInsts
docs <- mapM makeDoc (reverse bindings)
-- reverse so the new ones come last
let idocs = map GHC.pprInstanceHdr insts
fidocs = map GHC.pprFamInst finsts
mapM_ printForUserPartWay (docs ++ idocs ++ fidocs)
where
makeDoc (AnId i) = pprTypeAndContents i
makeDoc tt = do
mb_stuff <- GHC.getInfo False (getName tt)
return $ maybe (text "") pprTT mb_stuff
pprTT :: (TyThing, Fixity, [GHC.ClsInst], [GHC.FamInst], SDoc) -> SDoc
pprTT (thing, fixity, _cls_insts, _fam_insts, _docs)
= pprTyThing thing
$$ show_fixity
where
show_fixity
| fixity == GHC.defaultFixity = empty
| otherwise = ppr fixity <+> ppr (GHC.getName thing)
printTyThing :: TyThing -> GHCi ()
printTyThing tyth = printForUser (colored colMagentaFg $ pprTyThing tyth)
showBkptTable :: GHCi ()
showBkptTable = do
st <- getGHCiState
printForUser $ prettyLocations (breaks st)
showContext :: GHCi ()
showContext = do
resumes <- GHC.getResumeContext
printForUser $ vcat (map pp_resume (reverse resumes))
where
pp_resume res =
ptext (sLit "--> ") <> text (GHC.resumeStmt res)
$$ nest 2 (pprStopped res)
pprStopped :: GHC.Resume -> SDoc
pprStopped res =
ptext (sLit "Stopped in")
<+> ((case mb_mod_name of
Nothing -> empty
Just mod_name -> text (moduleNameString mod_name) <> char '.')
<> text (GHC.resumeDecl res))
<> char ',' <+> ppr (GHC.resumeSpan res)
where
mb_mod_name = moduleName <$> GHC.breakInfo_module <$> GHC.resumeBreakInfo res
showPackages :: GHCi ()
showPackages = do
dflags <- getDynFlags
let pkg_flags = packageFlags dflags
liftIO $ putStrLn $ showSDoc dflags $
text ("active package flags:"++if null pkg_flags then " none" else "") $$
nest 2 (vcat (map pprFlag pkg_flags))
showPaths :: GHCi ()
showPaths = do
dflags <- getDynFlags
liftIO $ do
cwd <- getCurrentDirectory
putStrLn $ showSDoc dflags $
text "current working directory: " $$
nest 2 (text cwd)
let ipaths = importPaths dflags
putStrLn $ showSDoc dflags $
text ("module import search paths:"++if null ipaths then " none" else "") $$
nest 2 (vcat (map text ipaths))
showLanguages :: GHCi ()
showLanguages = getDynFlags >>= liftIO . showLanguages' False
showiLanguages :: GHCi ()
showiLanguages = GHC.getInteractiveDynFlags >>= liftIO . showLanguages' False
showLanguages' :: Bool -> DynFlags -> IO ()
showLanguages' show_all dflags =
putStrLn $ showSDoc dflags $ vcat
[ text "base language is: " <>
case language dflags of
Nothing -> text "Haskell2010"
Just Haskell98 -> text "Haskell98"
Just Haskell2010 -> text "Haskell2010"
, (if show_all then text "all active language options:"
else text "with the following modifiers:") $$
nest 2 (vcat (map (setting xopt) DynFlags.xFlags))
]
where
setting test flag
| quiet = empty
| is_on = text "-X" <> text name
| otherwise = text "-XNo" <> text name
where name = flagSpecName flag
f = flagSpecFlag flag
is_on = test f dflags
quiet = not show_all && test f default_dflags == is_on
default_dflags =
defaultDynFlags (settings dflags) `lang_set`
case language dflags of
Nothing -> Just Haskell2010
other -> other
showTargets :: GHCi ()
showTargets = mapM_ showTarget =<< GHC.getTargets
where
showTarget :: Target -> GHCi ()
showTarget (Target (TargetFile f _) _ _) = liftIO (putStrLn f)
showTarget (Target (TargetModule m) _ _) =
liftIO (putStrLn $ moduleNameString m)
-- -----------------------------------------------------------------------------
-- Completion
completeCmd :: String -> GHCi ()
completeCmd argLine0 = case parseLine argLine0 of
Just ("repl", resultRange, left) -> do
(unusedLine,compls) <- ghciCompleteWord (reverse left,"")
let compls' = takeRange resultRange compls
liftIO . putStrLn $ unwords [ show (length compls'), show (length compls), show (reverse unusedLine) ]
forM_ (takeRange resultRange compls) $ \(Completion r _ _) -> do
liftIO $ print r
_ -> throwGhcException (CmdLineError "Syntax: :complete repl [<range>] <quoted-string-to-complete>")
where
parseLine argLine
| null argLine = Nothing
| null rest1 = Nothing
| otherwise = (,,) dom <$> resRange <*> s
where
(dom, rest1) = breakSpace argLine
(rng, rest2) = breakSpace rest1
resRange | head rest1 == '"' = parseRange ""
| otherwise = parseRange rng
s | head rest1 == '"' = readMaybe rest1 :: Maybe String
| otherwise = readMaybe rest2
breakSpace = fmap (dropWhile isSpace) . break isSpace
takeRange (lb,ub) = maybe id (drop . pred) lb . maybe id take ub
-- syntax: [n-][m] with semantics "drop (n-1) . take m"
parseRange :: String -> Maybe (Maybe Int,Maybe Int)
parseRange s = case span isDigit s of
(_, "") ->
-- upper limit only
Just (Nothing, bndRead s)
(s1, '-' : s2)
| all isDigit s2 ->
Just (bndRead s1, bndRead s2)
_ ->
Nothing
where
bndRead x = if null x then Nothing else Just (read x)
completeGhciCommand, completeMacro, completeIdentifier, completeModule,
completeSetModule, completeSeti, completeShowiOptions,
completeHomeModule, completeSetOptions, completeShowOptions,
completeHomeModuleOrFile, completeExpression
:: CompletionFunc GHCi
-- | Provide completions for last word in a given string.
--
-- Takes a tuple of two strings. First string is a reversed line to be
-- completed. Second string is likely unused, 'completeCmd' always passes an
-- empty string as second item in tuple.
ghciCompleteWord :: CompletionFunc GHCi
ghciCompleteWord line@(left,_) = case firstWord of
-- If given string starts with `:` colon, and there is only one following
-- word then provide REPL command completions. If there is more than one
-- word complete either filename or builtin ghci commands or macros.
':':cmd | null rest -> completeGhciCommand line
| otherwise -> do
completion <- lookupCompletion cmd
completion line
-- If given string starts with `import` keyword provide module name
-- completions
"import" -> completeModule line
-- otherwise provide identifier completions
_ -> completeExpression line
where
(firstWord,rest) = break isSpace $ dropWhile isSpace $ reverse left
lookupCompletion ('!':_) = return completeFilename
lookupCompletion c = do
maybe_cmd <- lookupCommand' c
case maybe_cmd of
Just cmd -> return (cmdCompletionFunc cmd)
Nothing -> return completeFilename
completeGhciCommand = wrapCompleter " " $ \w -> do
macros <- ghci_macros <$> getGHCiState
cmds <- ghci_commands `fmap` getGHCiState
let macro_names = map (':':) . map cmdName $ macros
let command_names = map (':':) . map cmdName $ filter (not . cmdHidden) cmds
let{ candidates = case w of
':' : ':' : _ -> map (':':) command_names
_ -> nub $ macro_names ++ command_names }
return $ filter (w `isPrefixOf`) candidates
completeMacro = wrapIdentCompleter $ \w -> do
cmds <- ghci_macros <$> getGHCiState
return (filter (w `isPrefixOf`) (map cmdName cmds))
completeIdentifier line@(left, _) =
-- Note: `left` is a reversed input
case left of
(x:_) | isSymbolChar x -> wrapCompleter (specials ++ spaces) complete line
_ -> wrapIdentCompleter complete line
where
isSymbolChar c = c `elem` ("!@#$%&*+./<=>?\\^|:-~" :: String)
complete w = do
rdrs <- GHC.getRdrNamesInScope
dflags <- GHC.getSessionDynFlags
return (filter (w `isPrefixOf`) (map (showPpr dflags) rdrs))
completeModule = wrapIdentCompleter $ \w -> do
dflags <- GHC.getSessionDynFlags
let pkg_mods = allVisibleModules dflags
loaded_mods <- liftM (map GHC.ms_mod_name) getLoadedModules
return $ filter (w `isPrefixOf`)
$ map (showPpr dflags) $ loaded_mods ++ pkg_mods
completeSetModule = wrapIdentCompleterWithModifier "+-" $ \m w -> do
dflags <- GHC.getSessionDynFlags
modules <- case m of
Just '-' -> do
imports <- GHC.getContext
return $ map iiModuleName imports
_ -> do
let pkg_mods = allVisibleModules dflags
loaded_mods <- liftM (map GHC.ms_mod_name) getLoadedModules
return $ loaded_mods ++ pkg_mods
return $ filter (w `isPrefixOf`) $ map (showPpr dflags) modules
completeHomeModule = wrapIdentCompleter listHomeModules
listHomeModules :: String -> GHCi [String]
listHomeModules w = do
g <- GHC.getModuleGraph
let home_mods = map GHC.ms_mod_name (GHC.mgModSummaries g)
dflags <- getDynFlags
return $ sort $ filter (w `isPrefixOf`)
$ map (showPpr dflags) home_mods
completeSetOptions = wrapCompleter flagWordBreakChars $ \w -> do
return (filter (w `isPrefixOf`) opts)
where opts = "args":"prog":"prompt":"prompt-cont":"prompt-function":
"prompt-cont-function":"editor":"stop":flagList
flagList = map head $ group $ sort allFlags
completeSeti = wrapCompleter flagWordBreakChars $ \w -> do
return (filter (w `isPrefixOf`) flagList)
where flagList = map head $ group $ sort allFlags
completeShowOptions = wrapCompleter flagWordBreakChars $ \w -> do
return (filter (w `isPrefixOf`) opts)
where opts = ["args", "prog", "editor", "stop",
"modules", "bindings", "linker", "breaks",
"context", "packages", "paths", "language", "imports"]
completeShowiOptions = wrapCompleter flagWordBreakChars $ \w -> do
return (filter (w `isPrefixOf`) ["language"])
completeHomeModuleOrFile = completeWord Nothing filenameWordBreakChars
$ unionComplete (fmap (map simpleCompletion) . listHomeModules)
listFiles
unionComplete :: Monad m => (a -> m [b]) -> (a -> m [b]) -> a -> m [b]
unionComplete f1 f2 line = do
cs1 <- f1 line
cs2 <- f2 line
return (cs1 ++ cs2)
wrapCompleter :: String -> (String -> GHCi [String]) -> CompletionFunc GHCi
wrapCompleter breakChars fun = completeWord Nothing breakChars
$ fmap (map simpleCompletion . nubSort) . fun
wrapIdentCompleter :: (String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleter = wrapCompleter word_break_chars
wrapIdentCompleterWithModifier :: String -> (Maybe Char -> String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleterWithModifier modifChars fun = completeWordWithPrev Nothing word_break_chars
$ \rest -> fmap (map simpleCompletion . nubSort) . fun (getModifier rest)
where
getModifier = find (`elem` modifChars)
-- | Return a list of visible module names for autocompletion.
-- (NB: exposed != visible)
allVisibleModules :: DynFlags -> [ModuleName]
allVisibleModules dflags = listVisibleModuleNames dflags
completeExpression = completeQuotedWord (Just '\\') "\"" listFiles
completeIdentifier
-- -----------------------------------------------------------------------------
-- commands for debugger
sprintCmd, printCmd, forceCmd :: String -> GHCi ()
sprintCmd = pprintCommand False False
printCmd = pprintCommand True False
forceCmd = pprintCommand False True
pprintCommand :: Bool -> Bool -> String -> GHCi ()
pprintCommand _bind _force _str = panic "pprintCommand"
-- do
-- pprintClosureCommand bind force str
stepCmd :: String -> GHCi ()
stepCmd arg = withSandboxOnly ":step" $ step arg
where
step [] = doContinue (const True) GHC.SingleStep
step expression = runStmt expression GHC.SingleStep >> return ()
stepLocalCmd :: String -> GHCi ()
stepLocalCmd arg = withSandboxOnly ":steplocal" $ step arg
where
step expr
| not (null expr) = stepCmd expr
| otherwise = do
mb_span <- getCurrentBreakSpan
case mb_span of
Nothing -> stepCmd []
Just loc -> do
Just md <- getCurrentBreakModule
current_toplevel_decl <- enclosingTickSpan md loc
doContinue (`isSubspanOf` RealSrcSpan current_toplevel_decl) GHC.SingleStep
stepModuleCmd :: String -> GHCi ()
stepModuleCmd arg = withSandboxOnly ":stepmodule" $ step arg
where
step expr
| not (null expr) = stepCmd expr
| otherwise = do
mb_span <- getCurrentBreakSpan
case mb_span of
Nothing -> stepCmd []
Just pan -> do
let f some_span = srcSpanFileName_maybe pan == srcSpanFileName_maybe some_span
doContinue f GHC.SingleStep
-- | Returns the span of the largest tick containing the srcspan given
enclosingTickSpan :: Module -> SrcSpan -> GHCi RealSrcSpan
enclosingTickSpan _ (UnhelpfulSpan _) = panic "enclosingTickSpan UnhelpfulSpan"
enclosingTickSpan md (RealSrcSpan src) = do
ticks <- getTickArray md
let line = srcSpanStartLine src
ASSERT(inRange (bounds ticks) line) do
let enclosing_spans = [ pan | (_,pan) <- ticks ! line
, realSrcSpanEnd pan >= realSrcSpanEnd src]
return . head . sortBy leftmostLargestRealSrcSpan $ enclosing_spans
where
leftmostLargestRealSrcSpan :: RealSrcSpan -> RealSrcSpan -> Ordering
leftmostLargestRealSrcSpan a b =
(realSrcSpanStart a `compare` realSrcSpanStart b)
`thenCmp`
(realSrcSpanEnd b `compare` realSrcSpanEnd a)
traceCmd :: String -> GHCi ()
traceCmd arg
= withSandboxOnly ":trace" $ tr arg
where
tr [] = doContinue (const True) GHC.RunAndLogSteps
tr expression = runStmt expression GHC.RunAndLogSteps >> return ()
continueCmd :: String -> GHCi ()
continueCmd = noArgs $ withSandboxOnly ":continue" $ doContinue (const True) GHC.RunToCompletion
-- doContinue :: SingleStep -> GHCi ()
doContinue :: (SrcSpan -> Bool) -> SingleStep -> GHCi ()
doContinue pre step = do
runResult <- resume pre step
_ <- afterRunStmt pre runResult
return ()
abandonCmd :: String -> GHCi ()
abandonCmd = noArgs $ withSandboxOnly ":abandon" $ do
b <- GHC.abandon -- the prompt will change to indicate the new context
when (not b) $ liftIO $ putStrLn "There is no computation running."
deleteCmd :: String -> GHCi ()
deleteCmd argLine = withSandboxOnly ":delete" $ do
deleteSwitch $ words argLine
where
deleteSwitch :: [String] -> GHCi ()
deleteSwitch [] =
liftIO $ putStrLn "The delete command requires at least one argument."
-- delete all break points
deleteSwitch ("*":_rest) = discardActiveBreakPoints
deleteSwitch idents = do
mapM_ deleteOneBreak idents
where
deleteOneBreak :: String -> GHCi ()
deleteOneBreak str
| all isDigit str = deleteBreak (read str)
| otherwise = return ()
historyCmd :: String -> GHCi ()
historyCmd arg
| null arg = history 20
| all isDigit arg = history (read arg)
| otherwise = liftIO $ putStrLn "Syntax: :history [num]"
where
history num = do
resumes <- GHC.getResumeContext
case resumes of
[] -> liftIO $ putStrLn "Not stopped at a breakpoint"
(r:_) -> do
let hist = GHC.resumeHistory r
(took,rest) = splitAt num hist
case hist of
[] -> liftIO $ putStrLn $
"Empty history. Perhaps you forgot to use :trace?"
_ -> do
pans <- mapM GHC.getHistorySpan took
let nums = map (printf "-%-3d:") [(1::Int)..]
names = map GHC.historyEnclosingDecls took
printForUser (vcat(zipWith3
(\x y z -> x <+> y <+> z)
(map text nums)
(map (bold . hcat . punctuate colon . map text) names)
(map (parens . ppr) pans)))
liftIO $ putStrLn $ if null rest then "<end of history>" else "..."
bold :: SDoc -> SDoc
bold c | do_bold = text start_bold <> c <> text end_bold
| otherwise = c
backCmd :: String -> GHCi ()
backCmd arg
| null arg = back 1
| all isDigit arg = back (read arg)
| otherwise = liftIO $ putStrLn "Syntax: :back [num]"
where
back num = withSandboxOnly ":back" $ do
(names, _, pan, _) <- GHC.back num
printForUser $ ptext (sLit "Logged breakpoint at") <+> ppr pan
printTypeOfNames names
-- run the command set with ":set stop <cmd>"
st <- getGHCiState
enqueueCommands [stop st]
forwardCmd :: String -> GHCi ()
forwardCmd arg
| null arg = forward 1
| all isDigit arg = forward (read arg)
| otherwise = liftIO $ putStrLn "Syntax: :back [num]"
where
forward num = withSandboxOnly ":forward" $ do
(names, ix, pan, _) <- GHC.forward num
printForUser $ (if (ix == 0)
then ptext (sLit "Stopped at")
else ptext (sLit "Logged breakpoint at")) <+> ppr pan
printTypeOfNames names
-- run the command set with ":set stop <cmd>"
st <- getGHCiState
enqueueCommands [stop st]
-- handle the "break" command
breakCmd :: String -> GHCi ()
breakCmd argLine = withSandboxOnly ":break" $ breakSwitch $ words argLine
breakSwitch :: [String] -> GHCi ()
breakSwitch [] = do
liftIO $ putStrLn "The break command requires at least one argument."
breakSwitch (arg1:rest)
| looksLikeModuleName arg1 && not (null rest) = do
md <- wantInterpretedModule arg1
breakByModule md rest
| all isDigit arg1 = do
imports <- GHC.getContext
case iiModules imports of
(mn : _) -> do
md <- lookupModuleName mn
breakByModuleLine md (read arg1) rest
[] -> do
liftIO $ putStrLn "No modules are loaded with debugging support."
| otherwise = do -- try parsing it as an identifier
wantNameFromInterpretedModule noCanDo arg1 $ \name -> do
maybe_info <- GHC.getModuleInfo (GHC.nameModule name)
case maybe_info of
Nothing -> noCanDo name (ptext (sLit "cannot get module info"))
Just minf ->
ASSERT( isExternalName name )
findBreakAndSet (GHC.nameModule name) $
findBreakForBind name (GHC.modInfoModBreaks minf)
where
noCanDo n why = printForUser $
text "cannot set breakpoint on " <> ppr n <> text ": " <> why
breakByModule :: Module -> [String] -> GHCi ()
breakByModule md (arg1:rest)
| all isDigit arg1 = do -- looks like a line number
breakByModuleLine md (read arg1) rest
breakByModule _ _
= breakSyntax
breakByModuleLine :: Module -> Int -> [String] -> GHCi ()
breakByModuleLine md line args
| [] <- args = findBreakAndSet md $ maybeToList . findBreakByLine line
| [col] <- args, all isDigit col =
findBreakAndSet md $ maybeToList . findBreakByCoord Nothing (line, read col)
| otherwise = breakSyntax
breakSyntax :: a
breakSyntax = throwGhcException (CmdLineError "Syntax: :break [<mod>] <line> [<column>]")
findBreakAndSet :: Module -> (TickArray -> [(Int, RealSrcSpan)]) -> GHCi ()
findBreakAndSet md lookupTickTree = do
tickArray <- getTickArray md
(breakArray, _) <- getModBreak md
case lookupTickTree tickArray of
[] -> liftIO $ putStrLn $ "No breakpoints found at that location."
some -> mapM_ (breakAt breakArray) some
where
breakAt breakArray (tick, pan) = do
setBreakFlag True breakArray tick
(alreadySet, nm) <-
recordBreak $ BreakLocation
{ breakModule = md
, breakLoc = RealSrcSpan pan
, breakTick = tick
, onBreakCmd = ""
}
printForUser $
text "Breakpoint " <> ppr nm <>
if alreadySet
then text " was already set at " <> ppr pan
else text " activated at " <> ppr pan
-- When a line number is specified, the current policy for choosing
-- the best breakpoint is this:
-- - the leftmost complete subexpression on the specified line, or
-- - the leftmost subexpression starting on the specified line, or
-- - the rightmost subexpression enclosing the specified line
--
findBreakByLine :: Int -> TickArray -> Maybe (BreakIndex,RealSrcSpan)
findBreakByLine line arr
| not (inRange (bounds arr) line) = Nothing
| otherwise =
listToMaybe (sortBy (leftmostLargestRealSrcSpan `on` snd) comp) `mplus`
listToMaybe (sortBy (compare `on` snd) incomp) `mplus`
listToMaybe (sortBy (flip compare `on` snd) ticks)
where
ticks = arr ! line
starts_here = [ (ix,pan) | (ix, pan) <- ticks,
GHC.srcSpanStartLine pan == line ]
(comp, incomp) = partition ends_here starts_here
where ends_here (_,pan) = GHC.srcSpanEndLine pan == line
-- The aim is to find the breakpoints for all the RHSs of the
-- equations corresponding to a binding. So we find all breakpoints
-- for
-- (a) this binder only (not a nested declaration)
-- (b) that do not have an enclosing breakpoint
findBreakForBind :: Name -> GHC.ModBreaks -> TickArray
-> [(BreakIndex,RealSrcSpan)]
findBreakForBind name modbreaks _ = filter (not . enclosed) ticks
where
ticks = [ (index, span)
| (index, [n]) <- assocs (GHC.modBreaks_decls modbreaks),
n == occNameString (nameOccName name),
RealSrcSpan span <- [GHC.modBreaks_locs modbreaks ! index] ]
enclosed (_,sp0) = any subspan ticks
where subspan (_,sp) = sp /= sp0 &&
realSrcSpanStart sp <= realSrcSpanStart sp0 &&
realSrcSpanEnd sp0 <= realSrcSpanEnd sp
findBreakByCoord :: Maybe FastString -> (Int,Int) -> TickArray
-> Maybe (BreakIndex,RealSrcSpan)
findBreakByCoord mb_file (line, col) arr
| not (inRange (bounds arr) line) = Nothing
| otherwise =
listToMaybe (sortBy (flip compare `on` snd) contains ++
sortBy (compare `on` snd) after_here)
where
ticks = arr ! line
-- the ticks that span this coordinate
contains = [ tick | tick@(_,pan) <- ticks, RealSrcSpan pan `spans` (line,col),
is_correct_file pan ]
is_correct_file pan
| Just f <- mb_file = GHC.srcSpanFile pan == f
| otherwise = True
after_here = [ tick | tick@(_,pan) <- ticks,
GHC.srcSpanStartLine pan == line,
GHC.srcSpanStartCol pan >= col ]
-- For now, use ANSI bold on terminals that we know support it.
-- Otherwise, we add a line of carets under the active expression instead.
-- In particular, on Windows and when running the testsuite (which sets
-- TERM to vt100 for other reasons) we get carets.
-- We really ought to use a proper termcap/terminfo library.
do_bold :: Bool
do_bold = (`isPrefixOf` unsafePerformIO mTerm) `any` ["xterm", "linux"]
where mTerm = System.Environment.getEnv "TERM"
`catchIO` \_ -> return "TERM not set"
start_bold :: String
start_bold = "\ESC[1m"
end_bold :: String
end_bold = "\ESC[0m"
-----------------------------------------------------------------------------
-- :where
whereCmd :: String -> GHCi ()
whereCmd = noArgs $ do
mstrs <- getCallStackAtCurrentBreakpoint
case mstrs of
Nothing -> return ()
Just strs -> liftIO $ putStrLn (renderStack strs)
-----------------------------------------------------------------------------
-- :list
listCmd :: String -> InputT GHCi ()
listCmd c = listCmd' c
listCmd' :: String -> InputT GHCi ()
listCmd' "" = do
mb_span <- lift getCurrentBreakSpan
case mb_span of
Nothing ->
printForUser $ text "Not stopped at a breakpoint; nothing to list"
Just (RealSrcSpan pan) ->
listAround pan True
Just pan@(UnhelpfulSpan _) ->
do resumes <- GHC.getResumeContext
case resumes of
[] -> panic "No resumes"
(r:_) ->
do let traceIt = case GHC.resumeHistory r of
[] -> text "rerunning with :trace,"
_ -> empty
doWhat = traceIt <+> text ":back then :list"
printForUser (text "Unable to list source for" <+>
ppr pan
$$ text "Try" <+> doWhat)
listCmd' str = list2 (words str)
list2 :: [String] -> InputT GHCi ()
list2 [arg] | all isDigit arg = do
imports <- GHC.getContext
case iiModules imports of
[] -> liftIO $ putStrLn "No module to list"
(mn : _) -> do
md <- lift $ lookupModuleName mn
listModuleLine md (read arg)
list2 [arg1,arg2] | looksLikeModuleName arg1, all isDigit arg2 = do
md <- wantInterpretedModule arg1
listModuleLine md (read arg2)
list2 [arg] = do
wantNameFromInterpretedModule noCanDo arg $ \name -> do
let loc = GHC.srcSpanStart (GHC.nameSrcSpan name)
case loc of
RealSrcLoc l ->
do tickArray <- ASSERT( isExternalName name )
lift $ getTickArray (GHC.nameModule name)
let mb_span = findBreakByCoord (Just (GHC.srcLocFile l))
(GHC.srcLocLine l, GHC.srcLocCol l)
tickArray
case mb_span of
Nothing -> listAround (realSrcLocSpan l) False
Just (_, pan) -> listAround pan False
UnhelpfulLoc _ ->
noCanDo name $ text "can't find its location: " <>
ppr loc
where
noCanDo n why = printForUser $
text "cannot list source code for " <> ppr n <> text ": " <> why
list2 _other =
liftIO $ putStrLn "syntax: :list [<line> | <module> <line> | <identifier>]"
listModuleLine :: Module -> Int -> InputT GHCi ()
listModuleLine modl line = do
graph <- GHC.getModuleGraph
let this = GHC.mgLookupModule graph modl
case this of
Nothing -> panic "listModuleLine"
Just summ -> do
let filename = expectJust "listModuleLine" (ml_hs_file (GHC.ms_location summ))
loc = mkRealSrcLoc (mkFastString (filename)) line 0
listAround (realSrcLocSpan loc) False
-- | list a section of a source file around a particular SrcSpan.
-- If the highlight flag is True, also highlight the span using
-- start_bold\/end_bold.
-- GHC files are UTF-8, so we can implement this by:
-- 1) read the file in as a BS and syntax highlight it as before
-- 2) convert the BS to String using utf-string, and write it out.
-- It would be better if we could convert directly between UTF-8 and the
-- console encoding, of course.
listAround :: MonadIO m => RealSrcSpan -> Bool -> InputT m ()
listAround pan do_highlight = do
contents <- liftIO $ BS.readFile (unpackFS file)
-- Drop carriage returns to avoid duplicates, see #9367.
let ls = BS.split '\n' $ BS.filter (/= '\r') contents
ls' = take (line2 - line1 + 1 + pad_before + pad_after) $
drop (line1 - 1 - pad_before) $ ls
fst_line = max 1 (line1 - pad_before)
line_nos = [ fst_line .. ]
highlighted | do_highlight = zipWith highlight line_nos ls'
| otherwise = [\p -> BS.concat[p,l] | l <- ls']
bs_line_nos = [ BS.pack (show l ++ " ") | l <- line_nos ]
prefixed = zipWith ($) highlighted bs_line_nos
output = BS.intercalate (BS.pack "\n") prefixed
let utf8Decoded = utf8DecodeByteString output
liftIO $ putStrLn utf8Decoded
where
file = GHC.srcSpanFile pan
line1 = GHC.srcSpanStartLine pan
col1 = GHC.srcSpanStartCol pan - 1
line2 = GHC.srcSpanEndLine pan
col2 = GHC.srcSpanEndCol pan - 1
pad_before | line1 == 1 = 0
| otherwise = 1
pad_after = 1
highlight | do_bold = highlight_bold
| otherwise = highlight_carets
highlight_bold no line prefix
| no == line1 && no == line2
= let (a,r) = BS.splitAt col1 line
(b,c) = BS.splitAt (col2-col1) r
in
BS.concat [prefix, a,BS.pack start_bold,b,BS.pack end_bold,c]
| no == line1
= let (a,b) = BS.splitAt col1 line in
BS.concat [prefix, a, BS.pack start_bold, b]
| no == line2
= let (a,b) = BS.splitAt col2 line in
BS.concat [prefix, a, BS.pack end_bold, b]
| otherwise = BS.concat [prefix, line]
highlight_carets no line prefix
| no == line1 && no == line2
= BS.concat [prefix, line, nl, indent, BS.replicate col1 ' ',
BS.replicate (col2-col1) '^']
| no == line1
= BS.concat [indent, BS.replicate (col1 - 2) ' ', BS.pack "vv", nl,
prefix, line]
| no == line2
= BS.concat [prefix, line, nl, indent, BS.replicate col2 ' ',
BS.pack "^^"]
| otherwise = BS.concat [prefix, line]
where
indent = BS.pack (" " ++ replicate (length (show no)) ' ')
nl = BS.singleton '\n'
-- --------------------------------------------------------------------------
-- Tick arrays
getTickArray :: Module -> GHCi TickArray
getTickArray modl = do
st <- getGHCiState
let arrmap = tickarrays st
case lookupModuleEnv arrmap modl of
Just arr -> return arr
Nothing -> do
(_breakArray, ticks) <- getModBreak modl
let arr = mkTickArray (assocs ticks)
setGHCiState st{tickarrays = extendModuleEnv arrmap modl arr}
return arr
discardTickArrays :: GHCi ()
discardTickArrays = modifyGHCiState (\st -> st {tickarrays = emptyModuleEnv})
mkTickArray :: [(BreakIndex,SrcSpan)] -> TickArray
mkTickArray ticks
= accumArray (flip (:)) [] (1, max_line)
[ (line, (nm,pan)) | (nm,RealSrcSpan pan) <- ticks, line <- srcSpanLines pan ]
where
max_line = foldr max 0 [ GHC.srcSpanEndLine sp | (_, RealSrcSpan sp) <- ticks ]
srcSpanLines pan = [ GHC.srcSpanStartLine pan .. GHC.srcSpanEndLine pan ]
-- don't reset the counter back to zero?
discardActiveBreakPoints :: GHCi ()
discardActiveBreakPoints = do
st <- getGHCiState
mapM_ (turnOffBreak.snd) (breaks st)
setGHCiState $ st { breaks = [] }
deleteBreak :: Int -> GHCi ()
deleteBreak identity = do
st <- getGHCiState
let oldLocations = breaks st
(this,rest) = partition (\loc -> fst loc == identity) oldLocations
if null this
then printForUser (text "Breakpoint" <+> ppr identity <+>
text "does not exist")
else do
mapM_ (turnOffBreak.snd) this
setGHCiState $ st { breaks = rest }
turnOffBreak :: BreakLocation -> GHCi ()
turnOffBreak loc = do
(_arr, _) <- getModBreak (breakModule loc)
_hsc_env <- GHC.getSession
liftIO $ panic "turnOffBreak: Breakpoints not implemented"
-- enableBreakpoint hsc_env arr (breakTick loc) False
getModBreak :: Module -> GHCi (ForeignRef (), Array Int SrcSpan)
getModBreak m = do
Just mod_info <- GHC.getModuleInfo m
let modBreaks = GHC.modInfoModBreaks mod_info
let arr = GHC.modBreaks_flags modBreaks
let ticks = GHC.modBreaks_locs modBreaks
return (arr, ticks)
setBreakFlag :: Bool -> ForeignRef () -> Int -> GHCi ()
setBreakFlag _toggle _arr _i = do
_hsc_env <- GHC.getSession
liftIO $ panic "setBreakFlag: Breakpoints not implemented"
-- enableBreakpoint hsc_env arr i toggle
-- ---------------------------------------------------------------------------
-- User code exception handling
-- This is the exception handler for exceptions generated by the
-- user's code and exceptions coming from children sessions;
-- it normally just prints out the exception. The
-- handler must be recursive, in case showing the exception causes
-- more exceptions to be raised.
--
-- Bugfix: if the user closed stdout or stderr, the flushing will fail,
-- raising another exception. We therefore don't put the recursive
-- handler arond the flushing operation, so if stderr is closed
-- GHCi will just die gracefully rather than going into an infinite loop.
handler :: SomeException -> GHCi Bool
handler exception = do
flushInterpBuffers
withSignalHandlers $
ghciHandle handler (showException exception >> return False)
showException :: SomeException -> GHCi ()
showException se =
liftIO $ case fromException se of
-- omit the location for CmdLineError:
Just (CmdLineError s) -> putException s
-- ditto:
Just other_ghc_ex -> putException (show other_ghc_ex)
Nothing ->
case fromException se of
Just UserInterrupt -> putException "Interrupted."
_ -> putException ("*** Exception: " ++ show se)
where
putException = hPutStrLn stderr
-----------------------------------------------------------------------------
-- recursive exception handlers
-- Don't forget to unblock async exceptions in the handler, or if we're
-- in an exception loop (eg. let a = error a in a) the ^C exception
-- may never be delivered. Thanks to Marcin for pointing out the bug.
ghciHandle :: (HasDynFlags m, ExceptionMonad m) => (SomeException -> m a) -> m a -> m a
ghciHandle h m = gmask $ \restore -> do
-- Force dflags to avoid leaking the associated HscEnv
!dflags <- getDynFlags
gcatch (restore (GHC.prettyPrintGhcErrors dflags m)) $ \e -> restore (h e)
ghciTry :: GHCi a -> GHCi (Either SomeException a)
ghciTry (GHCi m) = GHCi $ \s -> gtry (m s)
tryBool :: GHCi a -> GHCi Bool
tryBool m = do
r <- ghciTry m
case r of
Left _ -> return False
Right _ -> return True
-- ----------------------------------------------------------------------------
-- Utils
lookupModule :: GHC.GhcMonad m => String -> m Module
lookupModule mName = lookupModuleName (GHC.mkModuleName mName)
lookupModuleName :: GHC.GhcMonad m => ModuleName -> m Module
lookupModuleName mName = GHC.lookupModule mName Nothing
isHomeModule :: Module -> Bool
isHomeModule m = GHC.moduleUnitId m == mainUnitId
-- TODO: won't work if home dir is encoded.
-- (changeDirectory may not work either in that case.)
expandPath :: MonadIO m => String -> InputT m String
expandPath = liftIO . expandPathIO
expandPathIO :: String -> IO String
expandPathIO p =
case dropWhile isSpace p of
('~':d) -> do
tilde <- getHomeDirectory -- will fail if HOME not defined
return (tilde ++ '/':d)
other ->
return other
wantInterpretedModule :: GHC.GhcMonad m => String -> m Module
wantInterpretedModule str = wantInterpretedModuleName (GHC.mkModuleName str)
wantInterpretedModuleName :: GHC.GhcMonad m => ModuleName -> m Module
wantInterpretedModuleName modname = do
modl <- lookupModuleName modname
let str = moduleNameString modname
dflags <- getDynFlags
when (GHC.moduleUnitId modl /= thisPackage dflags) $
throwGhcException (CmdLineError ("module '" ++ str ++ "' is from another package;\nthis command requires an interpreted module"))
is_interpreted <- GHC.moduleIsInterpreted modl
when (not is_interpreted) $
throwGhcException (CmdLineError ("module '" ++ str ++ "' is not interpreted; try \':add *" ++ str ++ "' first"))
return modl
wantNameFromInterpretedModule :: GHC.GhcMonad m
=> (Name -> SDoc -> m ())
-> String
-> (Name -> m ())
-> m ()
wantNameFromInterpretedModule noCanDo str and_then =
handleSourceError GHC.printException $ do
names <- GHC.parseName str
case names of
[] -> return ()
(n:_) -> do
let modl = ASSERT( isExternalName n ) GHC.nameModule n
if not (GHC.isExternalName n)
then noCanDo n $ ppr n <>
text " is not defined in an interpreted module"
else do
is_interpreted <- GHC.moduleIsInterpreted modl
if not is_interpreted
then noCanDo n $ text "module " <> ppr modl <>
text " is not interpreted"
else and_then n
pprTypeAndContents :: GHC.GhcMonad m => GHC.Id -> m SDoc
pprTypeAndContents id = do
dflags <- GHC.getSessionDynFlags
let _pcontents = gopt Opt_PrintBindContents dflags
pprdId = (pprTyThing . AnId) id
return pprdId
-- TODO: Implement runtime closure inspection
-- if pcontents
-- then do
-- let depthBound = 100
-- -- If the value is an exception, make sure we catch it and
-- -- show the exception, rather than propagating the exception out.
-- e_term <- gtry $ GHC.obtainTermFromId depthBound False id
-- docs_term <- case e_term of
-- Right term -> showTerm term
-- Left exn -> return (text "*** Exception:" <+>
-- text (show (exn :: SomeException)))
-- return $ pprdId <+> equals <+> docs_term
-- else return pprdId
|
rahulmutt/ghcvm
|
eta/Eta/REPL/UI.hs
|
bsd-3-clause
| 159,863 | 11 | 83 | 45,438 | 38,799 | 19,413 | 19,386 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Futhark.Representation.AST.SyntaxTests
()
where
-- There isn't anything to test in this module. At some point, maybe
-- we can put some Arbitrary instances here.
|
ihc/futhark
|
unittests/Futhark/Representation/AST/SyntaxTests.hs
|
isc
| 211 | 0 | 3 | 33 | 14 | 11 | 3 | 3 | 0 |
-- Test case constributed by Till Theis
{-# LANGUAGE CPP #-}
module Tests.DataToTag where
import Control.Monad
import System.IO.Unsafe
#ifdef __HASTE__
import Haste
output = alert
#else
output = putStrLn
#endif
trace :: Show a => a -> b -> b
trace msg = seq $ unsafePerformIO (output $ show msg)
runTest :: IO String
runTest = return . show $ parse "a"
-- | Parse a string into the token list [Tok1] and return True if the parser
-- (token Tok1) can verify that.
parse :: String -> Bool
parse s =
case runParser tokenize s of
Just ([], ts) -> case runParser (token Tok1) ts of
Just ([], _) -> True
_ -> False
_ -> False
-- | The Parser type is parameterized over the input stream element type @s@ and
-- the return type @a@. A parser takes the input and produces a return value
-- together with the not yet consumed input.
newtype Parser s a = Parser { runParser :: [s] -> Maybe ([s], a) }
parserError s msg = Nothing
parserAccept s a = Just (s, a)
instance Monad (Parser s) where
p >>= f = Parser $ \s ->
case runParser p s of
Just (s', a) -> runParser (f a) s'
Nothing -> Nothing
return = Parser . flip parserAccept
fail = Parser . flip parserError
(<|>) :: Parser s a -> Parser s a -> Parser s a
p1 <|> p2 = Parser $ \s -> runParser p1 s `or` runParser p2 s
where Nothing `or` b = b
a `or` _ = a
many :: Parser s a -> Parser s [a]
many p = many1 p <|> return []
many1 :: Parser s a -> Parser s [a]
many1 p = liftM2 (:) p (many p)
satisfy :: (s -> Bool) -> Parser s s
satisfy p = Parser go
where go (x:xs) | p x = parserAccept xs x
go s = parserError s "not satisfied"
data Token = Tok1 | Tok2 | Tok3 | Tok4 | Tok5 | Tok6 | Tok7 | Tok8 | Tok9 deriving (Show, Eq)
tokenize :: Parser Char [Token]
tokenize = many1 $ many1 (satisfy $ const True) >> return Tok1
token :: Token -> Parser Token Token
token t = satisfy (== t)
|
joelburget/haste-compiler
|
Tests/DataToTag.hs
|
bsd-3-clause
| 1,962 | 0 | 13 | 521 | 723 | 379 | 344 | 43 | 3 |
{-# LANGUAGE BangPatterns, NoImplicitPrelude, RecordWildCards, Trustworthy #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
module GHC.Event.IntTable
(
IntTable
, new
, lookup
, insertWith
, reset
, delete
, updateWith
) where
import Control.Monad ((=<<), liftM, unless, when)
import Data.Bits ((.&.), shiftL, shiftR)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Data.Maybe (Maybe(..), isJust)
import Foreign.ForeignPtr (ForeignPtr, mallocForeignPtr, withForeignPtr)
import Foreign.Storable (peek, poke)
import GHC.Base (Monad(..), ($), const, otherwise)
import GHC.Classes (Eq(..), Ord(..))
import GHC.Event.Arr (Arr)
import GHC.Num (Num(..))
import GHC.Prim (seq)
import GHC.Types (Bool(..), IO(..), Int(..))
import qualified GHC.Event.Arr as Arr
-- A very simple chained integer-keyed mutable hash table. We use
-- power-of-two sizing, grow at a load factor of 0.75, and never
-- shrink. The "hash function" is the identity function.
newtype IntTable a = IntTable (IORef (IT a))
data IT a = IT {
tabArr :: {-# UNPACK #-} !(Arr (Bucket a))
, tabSize :: {-# UNPACK #-} !(ForeignPtr Int)
}
data Bucket a = Empty
| Bucket {
bucketKey :: {-# UNPACK #-} !Int
, bucketValue :: a
, bucketNext :: Bucket a
}
lookup :: Int -> IntTable a -> IO (Maybe a)
lookup k (IntTable ref) = do
let go Bucket{..}
| bucketKey == k = return (Just bucketValue)
| otherwise = go bucketNext
go _ = return Nothing
it@IT{..} <- readIORef ref
go =<< Arr.read tabArr (indexOf k it)
new :: Int -> IO (IntTable a)
new capacity = IntTable `liftM` (newIORef =<< new_ capacity)
new_ :: Int -> IO (IT a)
new_ capacity = do
arr <- Arr.new Empty capacity
size <- mallocForeignPtr
withForeignPtr size $ \ptr -> poke ptr 0
return IT { tabArr = arr
, tabSize = size
}
grow :: IT a -> IORef (IT a) -> Int -> IO ()
grow oldit ref size = do
newit <- new_ (Arr.size (tabArr oldit) `shiftL` 1)
let copySlot n !i
| n == size = return ()
| otherwise = do
let copyBucket !m Empty = copySlot m (i+1)
copyBucket m bkt@Bucket{..} = do
let idx = indexOf bucketKey newit
next <- Arr.read (tabArr newit) idx
Arr.write (tabArr newit) idx bkt { bucketNext = next }
copyBucket (m+1) bucketNext
copyBucket n =<< Arr.read (tabArr oldit) i
copySlot 0 0
withForeignPtr (tabSize newit) $ \ptr -> poke ptr size
writeIORef ref newit
insertWith :: (a -> a -> a) -> Int -> a -> IntTable a -> IO (Maybe a)
insertWith f k v inttable@(IntTable ref) = do
it@IT{..} <- readIORef ref
let idx = indexOf k it
go seen bkt@Bucket{..}
| bucketKey == k = do
let !v' = f v bucketValue
!next = seen <> bucketNext
Empty <> bs = bs
b@Bucket{..} <> bs = b { bucketNext = bucketNext <> bs }
Arr.write tabArr idx (Bucket k v' next)
return (Just bucketValue)
| otherwise = go bkt { bucketNext = seen } bucketNext
go seen _ = withForeignPtr tabSize $ \ptr -> do
size <- peek ptr
if size + 1 >= Arr.size tabArr - (Arr.size tabArr `shiftR` 2)
then grow it ref size >> insertWith f k v inttable
else do
v `seq` Arr.write tabArr idx (Bucket k v seen)
poke ptr (size + 1)
return Nothing
go Empty =<< Arr.read tabArr idx
{-# INLINABLE insertWith #-}
-- | Used to undo the effect of a prior insertWith.
reset :: Int -> Maybe a -> IntTable a -> IO ()
reset k (Just v) tbl = insertWith const k v tbl >> return ()
reset k Nothing tbl = delete k tbl >> return ()
indexOf :: Int -> IT a -> Int
indexOf k IT{..} = k .&. (Arr.size tabArr - 1)
delete :: Int -> IntTable a -> IO (Maybe a)
delete k t = updateWith (const Nothing) k t
updateWith :: (a -> Maybe a) -> Int -> IntTable a -> IO (Maybe a)
updateWith f k (IntTable ref) = do
it@IT{..} <- readIORef ref
let idx = indexOf k it
go changed bkt@Bucket{..}
| bucketKey == k =
let fbv = f bucketValue
!nb = case fbv of
Just val -> bkt { bucketValue = val }
Nothing -> bucketNext
in (fbv, Just bucketValue, nb)
| otherwise = case go changed bucketNext of
(fbv, ov, nb) -> (fbv, ov, bkt { bucketNext = nb })
go _ e = (Nothing, Nothing, e)
(fbv, oldVal, newBucket) <- go False `liftM` Arr.read tabArr idx
when (isJust oldVal) $ do
Arr.write tabArr idx newBucket
unless (isJust fbv) $
withForeignPtr tabSize $ \ptr -> do
size <- peek ptr
poke ptr (size - 1)
return oldVal
|
frantisekfarka/ghc-dsi
|
libraries/base/GHC/Event/IntTable.hs
|
bsd-3-clause
| 4,807 | 0 | 21 | 1,426 | 1,900 | 967 | 933 | 117 | 4 |
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ForeignFunctionInterface #-}
module GHCi.StaticPtrTable ( sptAddEntry ) where
import Prelude -- See note [Why do we import Prelude here?]
import Data.Word
import Foreign
import GHC.Fingerprint
import GHCi.RemoteTypes
-- | Used by GHCi to add an SPT entry for a set of interactive bindings.
sptAddEntry :: Fingerprint -> HValue -> IO ()
sptAddEntry (Fingerprint a b) (HValue x) = do
-- We own the memory holding the key (fingerprint) which gets inserted into
-- the static pointer table and can't free it until the SPT entry is removed
-- (which is currently never).
fpr_ptr <- newArray [a,b]
sptr <- newStablePtr x
ent_ptr <- malloc
poke ent_ptr (castStablePtrToPtr sptr)
spt_insert_stableptr fpr_ptr ent_ptr
foreign import ccall "hs_spt_insert_stableptr"
spt_insert_stableptr :: Ptr Word64 -> Ptr (Ptr ()) -> IO ()
|
sdiehl/ghc
|
libraries/ghci/GHCi/StaticPtrTable.hs
|
bsd-3-clause
| 900 | 0 | 11 | 171 | 175 | 91 | 84 | 17 | 1 |
-- |
-- Module : Language.C.Parser.Builtin
-- Copyright : (c) 2001 Manuel M. T. Chakravarty
-- License : BSD-style
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module provides information about builtin entities.
--
-- Currently, only builtin type names are supported. The only builtin type
-- name is `__builtin_va_list', which is a builtin of GNU C.
--
module Language.C.Parser.Builtin (
builtinTypeNames
) where
import Language.C.Data.Ident (Ident, builtinIdent)
-- predefined type names
--
builtinTypeNames :: [Ident]
builtinTypeNames = [builtinIdent "__builtin_va_list"]
|
acowley/language-c
|
src/Language/C/Parser/Builtin.hs
|
bsd-3-clause
| 632 | 0 | 6 | 107 | 61 | 44 | 17 | 5 | 1 |
module Test0 () where
import Language.Haskell.Liquid.Prelude
x = choose 0
foo :: Num a => a -> a
foo x = 0 - x
prop_abs :: Bool
prop_abs = if x > 0 then baz (foo x) else False
baz :: (Num a, Ord a) => a -> Bool
baz z = liquidAssertB (z > 0)
|
ssaavedra/liquidhaskell
|
tests/neg/test00b.hs
|
bsd-3-clause
| 249 | 0 | 8 | 64 | 123 | 67 | 56 | 9 | 2 |
{-# Language TypeSynonymInstances #-}
{-# Language FlexibleInstances, MagicHash #-}
module Pretty( ppr, pp, banner, render, Pretty) where
import Prelude hiding ((<$>))
import Core
import Type
import Weight
import DataCon
import Text.PrettyPrint.Leijen hiding (Pretty)
parensIf :: Bool -> Doc -> Doc
parensIf True = parens
parensIf False = id
class Pretty p where
ppr :: Int -> Bool -> p -> Doc
instance Pretty Var where
ppr _ tp x@TyVar{varWeight=weight} =
if tp then
text (varName x) <> text "∷" <> ppr 0 True (varType x) <> ppr 0 True weight
else
text (varName x) <> ppr 0 True weight
ppr _ _ Hole = text "_"
instance Pretty Weight where
ppr _ _ Omega = empty
ppr _ _ One = text ":1"
ppr _ _ Zero = text ":0"
instance Pretty (Expr Var) where
ppr p tp (Var a) = ppr p tp a
ppr p tp (App a b) = parens (ppr p tp a) <+> ppr p tp b
ppr p tp (Lam a b) = vcat [text "\\" <> ppr p tp a <+> text "->" ,
nest 4 $ ppr p tp b]
ppr p tp (Let a b) = text "let " <> ppr p tp a <$> text "in" <+> ppr p tp b
ppr p tp (Type t) = ppr p tp t
ppr p tp (Op o e1 e2) = parensIf (p>0) $ ppr p tp e1 <+> ppr p tp o <+> ppr p tp e2
ppr p tp (Lit l) = ppr p tp l
{-ppr p tp (Case e b t [(c,vs,ex)]) = --let! binding-}
{-text "let!" <+> ppr p tp c <+> hsep (map (ppr p tp) vs) <+> text "=" <+> ppr p tp e <$> -}
{-text "in" <+> ppr p tp ex-}
ppr p tp (Case e b t alts) = text "case" <+> ppr p tp e <+> text "of" <+>
ppr p tp b <$> vcat (map (nest 4 . ppr p tp) alts)
instance Pretty Literal where
ppr _ _ (Int i) = int i <> text "#"
ppr _ _ (Bool True) = text "True"
ppr _ _ (Bool False) = text "False"
instance Pretty Binop where
ppr _ _ Add = text "+"
ppr _ _ Sub = text "-"
ppr _ _ Mul = text "*"
ppr _ _ Add# = text "+#"
ppr _ _ Sub# = text "-#"
ppr _ _ Mul# = text "*#"
instance Pretty Type where
ppr p True (TVar (TV t)) = text t
ppr p True (TCon c) = text c
ppr p True (TArr t1 t2) = ppr p True t1 <+> text "→" <+> ppr p True t2
ppr p True (TLArr t1 t2) = ppr p True t1 <+> text "⊸" <+> ppr p True t2
ppr _ False _ = text ""
instance Pretty (Bind Var) where
ppr p tp (NonRec b e) = ppr p tp b <+> text "=" <+> ppr p tp e
instance Pretty Function where
ppr p True f = text (fName f) <+> text "∷" <+> ppr p True (fType f) <$>
text (fName f) <+> text "=" <$> nest 4 (ppr p True (fBody f))
ppr p False f= text (fName f) <+> text "=" <$> nest 4 (ppr p False (fBody f))
instance Pretty (Alt Var) where
ppr p tp (c,[],e) = ppr p tp c <+> text "->" <+> ppr p tp e
ppr p tp (Default,bs,e) = hsep (map (ppr p tp) bs) <+> text "->" <+> ppr p tp e
ppr p tp (c,bs,e) = ppr p tp c <+> hsep (map (ppr p tp) bs) <+> text "->" <+> ppr p tp e
instance Pretty AltCon where
ppr p tp (LitAlt l) = ppr p tp l
ppr p tp (DataAlt d) = text $ dcName d
ppr p _ Default = text "_"
pp :: Pretty p => Bool -> p -> String
pp tp p= render $ ppr 0 tp p
banner :: String -> String
banner msg = render $
text (replicate n '=')
<+>
text msg
<+>
text (replicate n '=')
where
n = (76 - length msg) `div` 2
render :: Doc -> String
render d = (displayS (renderPretty 0.0 80 d)) ""
|
C-Elegans/linear
|
Pretty.hs
|
mit
| 3,417 | 0 | 13 | 1,099 | 1,648 | 806 | 842 | 78 | 1 |
module Main where
import qualified TicTacToe
main :: IO ()
main = TicTacToe.run
|
tomphp/haskell-tictactoe
|
app/Main.hs
|
mit
| 82 | 0 | 6 | 15 | 25 | 15 | 10 | 4 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Network.Policy.Serialize
-- Copyright : (c) 2014 Stefan Bühler
-- License : MIT-style (see the file COPYING)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Parsing and formatting request parameters and response actions.
--
-----------------------------------------------------------------------------
module Network.Policy.Serialize
( parsePolicyParameters
, formatPolicyParameters
, parsePolicyAction
, formatPolicyAction
) where
import Network.Policy.Types
import Control.Applicative
import Control.Monad (when)
import Data.Attoparsec.ByteString.Char8 (stringCI, space, decimal)
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Data.Word (Word8)
import qualified Data.Attoparsec.ByteString as A
import qualified Data.ByteString as B
import qualified Data.Map.Strict as M
import qualified Data.Text as T
{-|
Parses a policy request (see <http://www.postfix.org/SMTPD_POLICY_README.html>).
Each parameter is terminated by a newline, key and value are separated by the
first '=' in a parameter, the request is terminated by another new lines, and
the parameters must not contain any NUL bytes, and neither key nor value can
contain a newline.
-}
parsePolicyParameters :: A.Parser PolicyParameters
parsePolicyParameters = do
reqLines <- A.manyTill parseLine emptyLine
return $ M.fromList reqLines
where
nul :: Word8
nul = 0
newline :: Word8
newline = 10 -- fromIntegral $ fromEnum '\n'
equals :: Word8
equals = 61 -- fromIntegral $ fromEnum '='
emptyLine :: A.Parser ()
emptyLine = A.try $ A.word8 newline >> return ()
parseLine :: A.Parser (T.Text, T.Text)
parseLine = do
name <- A.takeWhile1 (\b -> nul /= b && newline /= b && equals /= b)
_ <- A.word8 equals A.<?> "require '=' after variable name"
value <- A.takeWhile (\b -> nul /= b && newline /= b)
_ <- A.word8 newline A.<?> "require end of line"
return (decodeUtf8 name, decodeUtf8 value)
{-|
Build message body from parameters as "key=value" pairs, ended by newlines and
terminated by an extra newline.
-}
formatPolicyParameters :: Monad m => PolicyParameters -> m B.ByteString
formatPolicyParameters params = return $ B.concat $ concat (map (\(k, v) -> [encodeUtf8 k, B.pack [61], encodeUtf8 v, B.pack[10] ]) $ M.toList params) ++ [B.pack [10]]
{-|
Parses a policy response; the basic format is the same as for
'parsePolicyParameters', but it expects exactly one parameter with the key
"action".
It then tries to parse the value of the 'action' parameter; if it can't parse
it as some known action it will return it as 'Policy_RAW' instead.
-}
parsePolicyAction :: A.Parser PolicyAction
parsePolicyAction = do
_ <- A.string "action=" A.<?> "expected 'action='"
value <- A.takeWhile (\b -> nul /= b && newline /= b)
_ <- A.word8 newline A.<?> "require end of line"
_ <- A.word8 newline A.<?> "only one response line allowed"
case A.parseOnly parseAction value of
Left err -> fail err
Right act -> return act
where
nul :: Word8
nul = 0
newline :: Word8
newline = 10 -- fromIntegral $ fromEnum '\n'
first :: [A.Parser x] -> A.Parser x
first [] = fail "no patterns to match"
first [x] = A.try x
first (x:xs) = A.try x <|> first xs
parseAction :: A.Parser PolicyAction
parseAction = first $ map (\p -> p >>= \r -> A.endOfInput >> return r)
[ stringCI "OK" >> return Policy_Accept
, stringCI "DUNNO" >> return Policy_Pass
, stringCI "DEFER" >> parseOptionalMessage >>= return . Policy_Defer
, stringCI "DEFER_IF_REJECT" >> parseOptionalMessage >>= return . Policy_Defer_If_Reject
, stringCI "DEFER_IF_PERMIT" >> parseOptionalMessage >>= return . Policy_Defer_If_Permit
, stringCI "REJECT" >> parseOptionalMessage >>= return . Policy_Reject
, (decimal :: A.Parser Int) >>= \code -> do
if code >= 200 && code <= 299
then return $ Policy_Accept_Num code
else space >> if code >= 400 && code <= 499
then parseMessage >>= return . Policy_Defer_Num code
else if code >= 500 && code <= 599
then parseMessage >>= return . Policy_Reject_Num code
else fail "unknown code range"
, parseMessage >>= return . Policy_RAW
]
parseOptionalMessage :: A.Parser T.Text
parseOptionalMessage = A.try (space >> parseMessage) <|> return ""
parseMessage :: A.Parser T.Text
parseMessage = do
A.takeByteString >>= return . decodeUtf8
{-|
Build message body from action response.
-}
formatPolicyAction :: Monad m => PolicyAction -> m B.ByteString
formatPolicyAction action = do
line <- policyActionText action
when (T.any (\c -> '\n' == c || '\0' == c) line) $ error $ "Invalid result line: " ++ show line
return $ encodeUtf8 $ T.concat ["action=", line, "\n\n"]
|
stbuehler/haskell-mail-policy
|
src/Network/Policy/Serialize.hs
|
mit
| 4,828 | 20 | 20 | 851 | 1,241 | 650 | 591 | 81 | 7 |
{-# LANGUAGE UnicodeSyntax #-}
--------------------------------------------------------------------------------
-- File : Main
-- Author : Alejandro Gómez Londoño
-- Date : Fri Aug 7 23:51:30 2015
-- Description : Testing for CM0081 programming lab 1
--------------------------------------------------------------------------------
-- Change log :
--------------------------------------------------------------------------------
module Main where
import SimAFA (accepts)
import Data.Automata.AFA.Examples (StateM(..), SymbolM(..),m1,m2,m3,m4,m5)
import Test.QuickCheck (Arbitrary,arbitrary,elements,forAll)
import Test.QuickCheck (maxSuccess,quickCheckWith,stdArgs)
import Test.QuickCheck (choose,listOf,Property)
instance Arbitrary SymbolM where
arbitrary = elements [A,B,C,D]
main ∷ IO ()
main = do
let conf = stdArgs {maxSuccess = 1000}
printTest (quickCheckWith conf prop1) "m1"
printTest (quickCheckWith conf prop2) "m2"
printTest (quickCheckWith conf prop3) "m3"
printTest (quickCheckWith conf prop4) "m4"
printTest (quickCheckWith conf prop5) "m5"
m1Check ∷ [SymbolM] → Bool
m1Check s = finishAB && noC && noD
where finishAB = (take 2 . reverse) s == [A,B]
noC = not $ elem C s
noD = not $ elem D s
m2Check ∷ [SymbolM] → Bool
m2Check _ = False
m3Check ∷ [SymbolM] → Bool
m3Check = null
m4Check ∷ [Int] → Bool
m4Check l = s0 l
where
s0 (0:x) = s0 x || s1 x
s0 _ = False
s1 (1:x) = s1 x || s2 x
s1 _ = False
s2 (2:x) = s2 x || s3 x
s2 _ = False
s3 [] = True
s3 _ = False
m5Check ∷ [Int] → Bool
m5Check l = s0 l
where
s0 (0:x) = s0 x
s0 (1:x) = s1 x && s2 x
s0 _ = False
s1 [] = True
s1 (1:x) = s1 x && s2 x
s1 _ = False
s2 [] = True
s2 (1:x) = s1 x && s2 x
s2 _ = False
prop1 ∷ [SymbolM] → Bool
prop1 x = m1Check x == accepts m1 x
prop2 ∷ [SymbolM] → Bool
prop2 x = m2Check x == accepts m2 x
prop3 ∷ [SymbolM] → Bool
prop3 x = m3Check x == accepts m3 x
prop4 ∷ Property
prop4 = forAll (listOf $ choose (0,2)) rawProp
where rawProp x = m4Check x == accepts m4 x
prop5 ∷ Property
prop5 = forAll (listOf $ choose (0,1)) rawProp
where rawProp x = m5Check x == accepts m5 x
printTest ∷ IO () → String → IO ()
printTest run msg = do
putStrLn "<div class=\"large-12 columns\">"
putStrLn $ "<h4> Test ( " ++ msg ++ " )</h4>"
putStrLn "</div>"
putStrLn "<div class=\"large-12 columns\">"
putStrLn "<div class=\"panel\">"
putStrLn "<pre>"
run
putStrLn "</pre>"
putStrLn "</div>"
putStrLn "</div>"
|
agomezl/fluffy-chainsaw
|
test/Main.hs
|
mit
| 2,757 | 0 | 11 | 723 | 978 | 501 | 477 | 71 | 7 |
{-# Language DeriveGeneric #-}
module Unison.Runtime.JournaledMap where
import Control.Concurrent.STM (atomically)
import Data.ByteString (ByteString)
import Data.Bytes.Serial (Serial)
import Data.Map (Map)
import GHC.Generics
import qualified Data.Map as Map
import qualified Unison.BlockStore as BS
import qualified Unison.Cryptography as C
import qualified Unison.Runtime.Block as B
import qualified Unison.Runtime.Journal as J
type JournaledMap k v = J.Journal (Map k v) (Update k v)
data Update k v
= Insert k v
| Delete k
| Clear
deriving Generic
instance (Serial k, Serial v) => Serial (Update k v)
insert :: (Serial k, Serial v) => k -> v -> JournaledMap k v -> IO ()
insert k v = J.update (Insert k v)
delete :: k -> JournaledMap k v -> IO ()
delete k = J.update (Delete k)
lookup :: (Serial k, Ord k, Serial v) => k -> JournaledMap k v -> IO (Maybe v)
lookup k j = atomically $ Map.lookup k <$> J.get j
lookupGT :: (Serial k, Ord k, Serial v) => k -> JournaledMap k v -> IO (Maybe (k, v))
lookupGT k j = atomically $ Map.lookupGT k <$> J.get j
keys :: JournaledMap k v -> IO [k]
keys j = Map.keys <$> atomically (J.get j)
fromBlocks :: (Eq h, Ord k, Serial k, Serial v)
=> BS.BlockStore h
-> B.Block (Maybe ByteString)
-> B.Block (Maybe ByteString)
-> IO (JournaledMap k v)
fromBlocks bs keyframe diffs = J.fromBlocks bs apply ks ds where
ks = B.serial Map.empty $ keyframe
ds = B.serial Nothing $ diffs
apply (Insert k v) m = Map.insert k v m
apply (Delete k) m = Map.delete k m
apply Clear _ = Map.empty
fromSeries :: (Eq h, Ord k, Serial k, Serial v)
=> BS.BlockStore h
-> BS.Series
-> BS.Series
-> IO (JournaledMap k v)
fromSeries bs keyframe diffs = fromBlocks bs (B.fromSeries keyframe) (B.fromSeries diffs)
fromEncryptedSeries :: (Eq h, Ord k, Serial k, Serial v)
=> C.Cryptography t1 t2 t3 t4 t5 t6 ByteString
-> BS.BlockStore h
-> BS.Series
-> BS.Series
-> IO (JournaledMap k v)
fromEncryptedSeries crypto bs keyframe diffs =
fromBlocks bs (B.encrypted crypto (B.fromSeries keyframe)) (B.encrypted crypto (B.fromSeries diffs))
|
nightscape/platform
|
node/src/Unison/Runtime/JournaledMap.hs
|
mit
| 2,266 | 0 | 12 | 571 | 932 | 482 | 450 | 54 | 3 |
-- Counting power sets
-- http://www.codewars.com/kata/54381f0b6f032f933c000108/
module PowerSetCounting where
powers :: Num a => [t] -> a
powers = (2^) . length
|
gafiatulin/codewars
|
src/7 kyu/PowerSetCounting.hs
|
mit
| 164 | 0 | 7 | 24 | 38 | 23 | 15 | 3 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main (main) where
import Control.Applicative ((<*>), (<|>), optional, many, pure)
import Data.Foldable (traverse_)
import Data.Functor ((<$>))
import Data.List (intercalate)
import Data.Monoid ((<>))
import qualified Options.Applicative as Opts
import qualified ProfFile as Prof
import System.Exit (ExitCode(..), exitFailure)
import System.FilePath ((</>), replaceExtension)
import System.IO (stderr, stdout, hPutStrLn, hPutStr, hGetContents, IOMode(..), hClose, openFile)
import System.Process (proc, createProcess, CreateProcess(..), StdStream(..), waitForProcess)
import Paths_ghc_prof_flamegraph (getDataDir)
data Options = Options
{ optionsReportType :: ReportType
, optionsProfFile :: Maybe FilePath
, optionsOutputFile :: Maybe FilePath
, optionsFlamegraphFlags :: [String]
} deriving (Eq, Show)
data ReportType = Alloc -- ^ Report allocations, percent
| Entries -- ^ Report entries, number
| Time -- ^ Report time spent in closure, percent
| Ticks -- ^ Report ticks, number
| Bytes -- ^ Report bytes allocated, number
deriving (Eq, Show)
optionsParser :: Opts.Parser Options
optionsParser = Options
<$> (Opts.flag' Alloc (Opts.long "alloc" <> Opts.help "Uses the allocation measurements instead of time measurements")
<|> Opts.flag' Entries (Opts.long "entry" <> Opts.help "Uses entries the measurements instead of time measurements")
<|> Opts.flag' Bytes (Opts.long "bytes" <> Opts.help "Memory measurements in bytes (+RTS -P -RTS)")
<|> Opts.flag' Ticks (Opts.long "ticks" <> Opts.help "Time measurements in ticks (+RTS -P -RTS)")
<|> Opts.flag Time Time (Opts.long "time" <> Opts.help "Uses time measurements"))
<*> optional
(Opts.strArgument
(Opts.metavar "PROF-FILE" <>
Opts.help "Profiling output to format as flame graph"))
<*> optional
(Opts.strOption
(Opts.short 'o' <>
Opts.long "output" <>
Opts.metavar "SVG-FILE" <>
Opts.help "Optional output file"))
<*> many
(Opts.strOption
(Opts.long "flamegraph-option" <>
Opts.metavar "STR" <>
Opts.help "Options to pass to flamegraph.pl"))
checkNames :: ReportType -> [String] -> Maybe String
checkNames Alloc _ = Nothing
checkNames Entries _ = Nothing
checkNames Time _ = Nothing
checkNames Ticks n
| "ticks" `elem` n = Nothing
| otherwise = Just "No ticks information, please run program with +RTS -P"
checkNames Bytes n
| "bytes" `elem` n = Nothing
| otherwise = Just "No ticks information, please run program with +RTS -P"
normalize :: ReportType -> Double -> Int
normalize Alloc = round . (10 *)
normalize Time = round . (10 *)
normalize _ = round
addUnknown :: ReportType -> (Int, [String]) -> [String]
addUnknown Time = \(entries, frames) ->
let unknown = 1000 - entries
in if unknown > 0
then ("UNKNOWN " ++ show unknown) : frames
else frames
addUnknown Alloc = \(entries, frames) ->
let unknown = 1000 - entries
in if unknown > 0
then ("UNKNOWN " ++ show unknown) : frames
else frames
addUnknown _ = snd
generateFrames :: Options -> [Prof.Line] -> [String]
generateFrames options lines0 = addUnknown (optionsReportType options) $ go [] lines0
where
go :: [String] -> [Prof.Line] -> (Int, [String])
go _stack [] =
(0, [])
go stack (line : lines') =
let entries = normalize (optionsReportType options) (individualMeasure line)
symbol = Prof.lModule line ++ "." ++ Prof.lCostCentre line
frame = intercalate ";" (reverse (symbol : stack)) ++ " " ++ show entries
(childrenEntries, childrenFrames) = go (symbol : stack) (Prof.lChildren line)
(restEntries, restFrames) = go stack lines'
in (entries + childrenEntries + restEntries, frame : childrenFrames ++ restFrames)
individualMeasure = case optionsReportType options of
Alloc -> Prof.lIndividualAlloc
Time -> Prof.lIndividualTime
Entries -> fromIntegral . Prof.lEntries
Ticks -> fromIntegral . Prof.lTicks
Bytes -> fromIntegral . Prof.lBytes
main :: IO ()
main = do
options <- Opts.execParser $
Opts.info (Opts.helper <*> optionsParser) Opts.fullDesc
s <- maybe getContents readFile $ optionsProfFile options
case Prof.parse s of
Left err -> error err
Right (names, ls) ->
case checkNames (optionsReportType options) names of
Just problem -> do
hPutStrLn stderr problem
exitFailure
Nothing -> do
dataDir <- getDataDir
let flamegraphPath = dataDir </> "FlameGraph" </> "flamegraph.pl"
flamegraphProc = (proc "perl" (flamegraphPath : optionsFlamegraphFlags options))
{ std_in = CreatePipe
, std_out = CreatePipe
, std_err = Inherit
}
(outputHandle, outputFileName, closeOutputHandle) <-
case (optionsOutputFile options, optionsProfFile options) of
(Just path, _) -> do
h <- openFile path WriteMode
pure (h, Just path, hClose h)
(Nothing, Just path) -> do
let path' = path `replaceExtension` "svg"
h <- openFile path' WriteMode
pure (h, Just path', hClose h)
_ ->
pure (stdout, Nothing, pure ())
(Just input, Just flamegraphResult, Nothing, procHandle) <- createProcess flamegraphProc
traverse_ (hPutStrLn input) $ generateFrames options ls
hClose input
hGetContents flamegraphResult >>= hPutStr outputHandle
exitCode <- waitForProcess procHandle
closeOutputHandle
case exitCode of
ExitSuccess ->
case outputFileName of
Nothing -> pure ()
Just path -> putStrLn $ "Output written to " <> path
ExitFailure{} ->
hPutStrLn stderr $ "Call to flamegraph.pl at " <> flamegraphPath <> " failed"
|
fpco/ghc-prof-flamegraph
|
ghc-prof-flamegraph.hs
|
mit
| 6,351 | 0 | 24 | 1,821 | 1,763 | 920 | 843 | 136 | 7 |
module Data.Advent.Day05 (
partOne,
partTwo
) where
import Crypto.Hash (Digest, MD5, hash)
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (pack)
import Data.List (isPrefixOf)
import qualified Data.Map.Lazy as Map
import Data.Monoid ((<>))
type Password = Map.Map Char Char
partOne :: String -> String
partOne doorID = take 8 $
[ digest !! 5 | digest <- map show (digests doorID)
, "00000" `isPrefixOf` digest ]
partTwo :: String -> String
partTwo doorID = Map.elems . partTwo' Map.empty $
[ (digest !! 5, digest !! 6) | digest <- map show (digests doorID)
, "00000" `isPrefixOf` digest
, digest !! 5 `elem` "01234567" ]
partTwo' :: Password -> [(Char, Char)] -> Password
partTwo' m ((k,v):kvs)
| 8 == Map.size m = m
| Map.member k m = partTwo' m kvs
| otherwise = flip partTwo' kvs $ Map.insertWith (const id) k v m
partTwo' _ [] = error "333"
digests :: String -> [Digest MD5]
digests doorID = digests' (pack doorID) 0
digests' :: ByteString -> Integer -> [Digest MD5]
digests' doorID n = md5 (doorID <> pack (show n)) : digests' doorID (n + 1)
md5 :: ByteString -> Digest MD5
md5 = hash
|
yurrriq/advent-of-idris
|
src/Data/Advent/Day05.hs
|
mit
| 1,318 | 0 | 11 | 402 | 494 | 263 | 231 | 31 | 1 |
{-# Language ScopedTypeVariables, CPP #-}
module FindSymbol
( findSymbol
) where
#if __GLASGOW_HASKELL__ >= 802
import GhcMonad (liftIO)
#elif __GLASGOW_HASKELL__ >= 710
import GHC.PackageDb (exposedName)
import GhcMonad (liftIO)
#else
import Control.Applicative ((<$>))
import qualified UniqFM
#endif
import Control.Exception
import Control.Monad (filterM)
import Data.List (find, nub)
import Data.Maybe (catMaybes, isJust)
import Exception (ghandle)
import qualified GHC
import qualified Packages as PKG
import qualified Name
import GhcTypes (getModSummaries)
type SymbolName = String
type ModuleName = String
findSymbol :: SymbolName -> GHC.Ghc [ModuleName]
findSymbol symbol = do
fileMods <- findSymbolInFile symbol
pkgsMods <- findSymbolInPackages symbol
return . nub . map (GHC.moduleNameString . GHC.moduleName) $ fileMods ++ pkgsMods
findSymbolInFile :: SymbolName -> GHC.Ghc [GHC.Module]
findSymbolInFile symbol =
filterM (containsSymbol symbol) =<< map GHC.ms_mod <$> getModSummaries
findSymbolInPackages :: SymbolName -> GHC.Ghc [GHC.Module]
findSymbolInPackages symbol =
filterM (containsSymbol symbol) =<< allExposedModules
where
allExposedModules :: GHC.Ghc [GHC.Module]
allExposedModules = do
modNames <- exposedModuleNames
catMaybes <$> mapM findModule modNames
where
exposedModuleNames :: GHC.Ghc [GHC.ModuleName]
#if __GLASGOW_HASKELL__ >= 802
exposedModuleNames = do
dynFlags <- GHC.getSessionDynFlags
pkgConfigs <- liftIO $ fmap concat
. (fmap . fmap) snd . PKG.readPackageConfigs $ dynFlags
return $ map fst (concatMap exposedModules pkgConfigs)
#elif __GLASGOW_HASKELL__ >= 800
exposedModuleNames = do
dynFlags <- GHC.getSessionDynFlags
pkgConfigs <- liftIO $ fmap concat
. (fmap . fmap) snd . PKG.readPackageConfigs $ dynFlags
return $ map exposedName (concatMap exposedModules pkgConfigs)
#elif __GLASGOW_HASKELL__ >= 710
exposedModuleNames = do
dynFlags <- GHC.getSessionDynFlags
pkgConfigs <- liftIO $ PKG.readPackageConfigs dynFlags
return $ map exposedName (concatMap exposedModules pkgConfigs)
#else
exposedModuleNames =
concatMap exposedModules
. UniqFM.eltsUFM
. PKG.pkgIdMap
. GHC.pkgState
<$> GHC.getSessionDynFlags
#endif
exposedModules pkg = if PKG.exposed pkg then PKG.exposedModules pkg else []
findModule :: GHC.ModuleName -> GHC.Ghc (Maybe GHC.Module)
findModule moduleName =
ghandle (\(_ :: SomeException) -> return Nothing)
(Just <$> GHC.findModule moduleName Nothing)
containsSymbol :: SymbolName -> GHC.Module -> GHC.Ghc Bool
containsSymbol symbol module_ =
isJust . find (== symbol) <$> allExportedSymbols
where
allExportedSymbols =
ghandle (\(_ :: SomeException) -> return [])
(do info <- GHC.getModuleInfo module_
return $ maybe [] (map Name.getOccString . GHC.modInfoExports) info)
|
hdevtools/hdevtools
|
src/FindSymbol.hs
|
mit
| 3,051 | 0 | 17 | 655 | 623 | 326 | 297 | 50 | 2 |
-- https://hackage.haskell.org/package/fasta-0.10.4.2
-- Parse module.
-- By G.W. Schwartz
--
{- | Collection of functions for the parsing of a fasta file. Uses the string
type.
-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE BangPatterns #-}
module ProjectRosalind.Fasta ( eoe
, eol --fasta
-- regularParse )
, parseFasta' )
-- , parseCLIPFasta
-- , pipesFasta
-- , removeNs
-- , removeN
-- , removeCLIPNs )
where
-- Built-in
import Data.Char
import Text.Parsec
import Control.Monad (void)
import qualified Data.Map as Map
import qualified System.IO as IO
import Text.Parsec.String (Parser)
-- Cabal
import Pipes
-- Local
import ProjectRosalind.Fasta_Types
eol :: Parsec String u String
eol = choice . map (try . string) $ ["\n\r", "\r\n", "\n", "\r"]
eoe :: Parsec String u ()
eoe = do
lookAhead (void $ char '>') <|> eof
-- from https://raw.githubusercontent.com/JakeWheat/intro_to_parsing/
--regularParse :: String -> Either ParseError FastaSequence
--regularParse = parse fasta "error"
fasta :: Parsec String u FastaSequence
fasta = do
spaces
char '>'
header <- manyTill (satisfy (/= '>')) eol
fseq <- manyTill anyChar eoe
return ( FastaSequence { fastaHeader = header
, fastaSeq = removeWhitespace fseq } )
where
removeWhitespace = filter (`notElem` "\n\r ")
fastaFile :: Parsec String u [FastaSequence]
fastaFile = do
spaces
many fasta
fastaCLIP :: Parsec String u (FastaSequence, [FastaSequence])
fastaCLIP = do
spaces
char '>'
germline <- fasta
clones <- many $ try fasta
return (germline, clones)
fastaCLIPFile :: Parsec String u [(FastaSequence, [FastaSequence])]
fastaCLIPFile = do
spaces
many fastaCLIP
parseFasta :: String -> FastaSequence
parseFasta = eToV . parse fasta "error"
where
eToV (Right x) = x
eToV (Left x) = error ("Unable to parse fasta file\n" ++ show x)
-- | Parse a standard fasta file into string sequences
parseFasta' :: String -> [FastaSequence]
parseFasta' = eToV . parse fastaFile "error"
where
eToV (Right x) = x
eToV (Left x) = error ("Unable to parse fasta file\n" ++ show x)
-- | Parse a CLIP fasta file into string sequences
parseCLIPFasta :: String -> CloneMap
parseCLIPFasta = Map.fromList
. map (\(x, (y, z)) -> ((x, y), z))
. zip [0..]
. eToV
. parse fastaCLIPFile "error"
where
eToV (Right x) = x
eToV (Left x) = error ("Unable to parse fasta file\n" ++ show x)
-- | Parse a standard fasta file into string sequences for pipes. This is
-- the highly recommeded way of parsing, as it is computationally fast and
-- uses constant file memory
pipesFasta :: (MonadIO m) => IO.Handle -> Pipe String FastaSequence m ()
pipesFasta h = do
first <- await
getRest first ""
where
getRest x !acc = do
eof <- liftIO $ IO.hIsEOF h
if eof
then yield FastaSequence { fastaHeader = tail x
, fastaSeq = filter
(`notElem` "\n\r ")
acc }
else do
y <- await
if take 1 y == ">"
then do
yield FastaSequence { fastaHeader = tail x
, fastaSeq = filter
(`notElem` "\n\r ")
acc }
getRest y ""
else getRest x (acc ++ y)
-- | Remove Ns from a collection of sequences
removeNs :: [FastaSequence] -> [FastaSequence]
removeNs = map (\x -> x { fastaSeq = noN . fastaSeq $ x })
where
noN = map (\y -> if (y /= 'N' && y /= 'n') then y else '-')
-- | Remove Ns from a sequence
removeN :: FastaSequence -> FastaSequence
removeN x = x { fastaSeq = noN . fastaSeq $ x }
where
noN = map (\y -> if (y /= 'N' && y /= 'n') then y else '-')
-- | Remove Ns from a collection of CLIP fasta sequences
removeCLIPNs :: CloneMap -> CloneMap
removeCLIPNs = Map.fromList . map remove . Map.toList
where
remove ((x, y), z) = ((x, newSeq y), map newSeq z)
newSeq x = x { fastaSeq = noN . fastaSeq $ x }
noN = map (\y -> if (y /= 'N' && y /= 'n') then y else '-')
|
brodyberg/Notes
|
ProjectRosalind.hsproj/LearnHaskell/lib/ProjectRosalind/Fasta.hs
|
mit
| 4,666 | 0 | 19 | 1,646 | 1,181 | 641 | 540 | 90 | 3 |
module Main
where
import System.IO
import Control.Exception
import qualified Crypto.Hash.SHA512 as S(hashlazy)
import qualified Crypto.Hash.Whirlpool as W(hashlazy)
import Data.ByteString.Builder(toLazyByteString, stringUtf8)
import qualified Data.ByteString.Lazy as L(ByteString, fromStrict, toStrict, concat, singleton)
import qualified Data.ByteString as B(ByteString, foldl, concat, hPut)
stateMod :: Integer
stateMod = 104723 :: Integer
rowsMod :: Int
rowsMod = 137 :: Int
colsMod :: Int
colsMod = 139 :: Int
seedSep :: String
seedSep = "::"
megabytes :: Int
megabytes = 16
{- 64 bytes per hash emitted, this much iterations per megabyte -}
iterations :: Int
iterations = 16384
main :: IO ()
main = do
_ <- putStrLn "Enter empty key to finish"
keysStr <- readKeysTillEmpty []
let keysBytes = map (L.toStrict . toLazyByteString . stringUtf8) keysStr
let seedPlainStr = foldl (\ acc pwd -> acc ++ seedSep ++ pwd) "" keysStr
let seedPlainBytes = toLazyByteString $ stringUtf8 seedPlainStr
let seed = B.concat [hash 0 seedPlainBytes, hash 1 seedPlainBytes]
let entropyCol0 = scanl (stretchAcc keysBytes) seed [1..rowsMod-1]
let entropyMtx = map (\ rowSeed -> scanl (stretchAcc keysBytes) rowSeed [2..colsMod]) entropyCol0
withFile "stretch.out" WriteMode $ writeStep entropyMtx (seed, megabytes * iterations)
writeStep :: [[B.ByteString]] -> (B.ByteString, Int) -> Handle -> IO ()
writeStep entropyMtx (state, idx) fileHandle =
if idx <= 0
then return ()
else do
let stateInt = asState state
let increment = entropyMtx !! (stateInt `mod` rowsMod) !! (stateInt `mod` colsMod)
let nextState = hash stateInt $ L.concat [L.fromStrict state, L.fromStrict increment]
_ <- B.hPut fileHandle nextState
writeStep entropyMtx (nextState , idx - 1) fileHandle
stretchAcc :: [B.ByteString] -> B.ByteString -> Int -> B.ByteString
stretchAcc keys acc idx =
hash (idx + asState acc) fullAcc
where
fullAcc =
L.concat[
L.fromStrict acc,
L.singleton $ fromIntegral idx,
L.fromStrict $ keys !! (idx `mod` length keys)
]
asInteger :: B.ByteString -> Integer
asInteger =
B.foldl (\ num word8 -> num * 256 + fromIntegral word8 ) 0
asState :: B.ByteString -> Int
asState str =
fromIntegral $ asInteger str `mod` stateMod
hash :: Int -> L.ByteString -> B.ByteString
hash algo =
case algo `mod` 2 of
0 -> hashWirp
_ -> hashSha
hashWirp :: L.ByteString -> B.ByteString
hashWirp = W.hashlazy
hashSha :: L.ByteString -> B.ByteString
hashSha = S.hashlazy
readKeysTillEmpty :: [String] -> IO [String]
readKeysTillEmpty accum = do
nextPwdMaybe <- readKeyNumbered $ length accum
maybe (return accum) (\ nextPwd -> readKeysTillEmpty $ accum ++ [nextPwd] ) nextPwdMaybe
readKeyNumbered :: Int -> IO (Maybe String)
readKeyNumbered idx =
readKeyVerified $ "Key #" ++ show idx
readKeyVerified :: String -> IO (Maybe String)
readKeyVerified prompt = do
putStr $ prompt ++ " (enter):"
pass1 <- readKey
if null pass1
then
return Nothing
else do
putStr $ prompt ++ " (verify):"
pass2 <- readKey
if pass1 == pass2
then
return (Just pass1)
else do
putStrLn "Retrying: 'enter' and 'verify' did not match"
readKeyVerified prompt
readKey :: IO String
readKey = do
hFlush stdout
old <- hGetEcho stdin
password <- bracket_ (hSetEcho stdin False) (hSetEcho stdin old) getLine
putChar '\n'
return password
|
akraievoy/funstuff
|
stretch/src/Main.hs
|
mit
| 3,554 | 0 | 15 | 788 | 1,178 | 612 | 566 | 92 | 3 |
import Data.Char
import Data.Char
import Data.List
import Data.List.Split
pkcs7pad len bytes = result
where
chunks = chunksOf len bytes
lst = last chunks
needed = len - (length lst)
padding = repeat needed
paddedLast = concat [lst,(take needed padding)]
chunksMinusLast = take (length chunks - 1) chunks
result = concat [chunksMinusLast,[paddedLast]]
main :: IO()
main = putStrLn result
where
bytes = pkcs7pad 20 (map ord "YELLOW SUBMARINE")
result = show bytes
|
mozkeeler/cryptopals
|
set2/challenge9/pkcs7pad.hs
|
mit
| 504 | 6 | 8 | 113 | 204 | 96 | 108 | 16 | 1 |
{-
Homework 2 (14.09.2015)
Author: Mikhail Kita, group 271
-}
import Data.List(delete)
-- Takes n first elements from the list
take' 0 _ = []
take' n (x:xs) = [x] ++ (take (n - 1) xs)
-- Deletes repeat values from the list
nub [] = []
nub (x:xs) = [x] ++ nub (newList x xs) where
newList a [] = []
newList a list = [x | x <- list, x /= a]
-- List of permutations
perm [] = [[]]
perm list = [(x:xs) | x <- list, xs <- perm $ delete x list]
-- List of sublists
subs [] = [[]]
subs list = nub [(x:xs) | x <- list, xs <- (subs $ tail' x list) ++ [[]]] where
tail' a [] = []
tail' a (x:xs) = if (x == a) then xs else (tail' a xs)
-- List of Cartesian products
dprod _ [] = [[]]
dprod [] _ = [[]]
dprod a b = [ [x,y] | x <- a, y <- b]
|
MaKToff/SPbSU_Homeworks
|
Semester 3/Homework 2/Homework2.hs
|
mit
| 771 | 6 | 12 | 213 | 450 | 221 | 229 | 16 | 3 |
{-# LANGUAGE ApplicativeDo #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
module Text.Parse.ODEBench
( Problem(..)
, problem
, Dependency(..)
, Sample(..)
, Bounds(..)
, ParamInfo(..)
, fromFile
, parseTest
) where
import Control.Applicative
import Control.Monad
import Data.List (sortOn, zipWith5)
import Data.Maybe
import Data.Monoid
import Data.Traversable
import Data.Utils
import Data.Vector.Storable (Vector)
import qualified Data.Vector.Storable as Vector
import GHC.Exts (IsString (..), fromList)
import Text.Parser.Char hiding (lower, upper)
import Text.Parser.Combinators
import Text.Parser.Token hiding (double)
import qualified Text.Parser.Token as Token
import Text.Parser.Token.Highlight
import Text.Parser.Token.Style
import Text.PrettyPrint.ANSI.Leijen (plain, putDoc)
import Text.Trifecta.Parser hiding (Parser, parseTest)
import qualified Text.Trifecta.Parser as Trifecta
import Text.Trifecta.Result
-- | Module for parsing the problems stated
-- at http://www.cse.chalmers.se/~dag/identification/Benchmarks/
-- $setup
-- >>> let p prsr = parseTest (whiteSpace *> prsr <* eof)
newtype Parser a = Parser
{ getParser :: Trifecta.Parser a
} deriving (Functor, Applicative, Monad, Alternative
,Parsing, CharParsing, MonadPlus)
-- | IsString instance for nice syntax
instance (a ~ ()) => IsString (Parser a) where
fromString = reserved
-- | Tests a parser without ansi-colorization for error messages.
parseTest :: Show a => Parser a -> String -> IO ()
parseTest p s =
case parseString (getParser p) mempty s of
Success x -> print x
Failure (ErrInfo d _) -> putDoc (plain d)
instance TokenParsing Parser where
someSpace = Parser $
buildSomeSpaceParser
someSpace
(CommentStyle "" "" "//" False)
identStyle :: IdentifierStyle Parser
identStyle = IdentifierStyle
"identifier"
letter
(alphaNum <|> char '_')
(fromList [])
Identifier
ReservedIdentifier
identifier :: Parser String
identifier = ident identStyle
-- | >>> p (reserved "hello") "hgello"
-- (interactive):1:1: error: expected: "hello"
-- hgello<EOF>
-- ^
reserved :: String -> Parser ()
reserved = reserve identStyle
-- | Parses special syntax which allows trailing dots
-- >>> p double "20."
-- 20.0
-- >>> p double "2"
-- 2.0
-- >>> p double "-2"
-- -2.0
-- >>> p double "-2."
-- -2.0
double :: Parser Double
double = try Token.double <|> do
num <- integer'
skipOptional (char '.')
whiteSpace
pure (fromInteger num)
-- | >>> p (property "lowerBound" *> double) "has lowerBound = 0.20000000E+00"
-- 0.2
property :: String -> Parser ()
property s = do
"has"
reserved s
"="
simpleProp :: String -> String -> Parser Double
simpleProp v p = reserved v *> property p *> double
context :: Parser a -> Parser a
context = ("of" *>)
data Dependency = Dependent
| Input
deriving (Show, Eq, Ord)
-- | >>> p dependency "is dependent"
-- Dependent
-- >>> p dependency "is inputVariable"
-- Input
dependency :: Parser Dependency
dependency = "is"
*> (Dependent <$ "dependent"
<|> Input <$ "inputVariable")
ind :: Parser Integer
ind = char '_' *> decimal
-- | >>> p (indexedOneDim "alpha") "alpha_1"
-- 1
indexedOneDim :: String -> Parser Integer
indexedOneDim s = token (string s *> ind)
-- | >>> p variable "variable_1 has name = x1 is dependent"
-- (1,Dependent)
variable :: Parser (Integer, Dependency)
variable = (,) <$> indexedOneDim "variable"
<* property "name"
<* identifier
<*> dependency
-- | >>> p experiment "experiment_1 has name = exp1 has perfectData"
-- 1
experiment :: Parser Integer
experiment = indexedOneDim "experiment"
<* property "name"
<* identifier
<* "has"
<* "perfectData"
-- | >>> p ((,) <$> indexedOneDim "sample" <*> context (indexedOneDim "experiment")) "sample_2 \nof experiment_1"
-- (2,1)
data Sample = Sample
{ sampleNum :: !Integer
, experimentNum :: !Integer
, time :: !Double
, values :: !(Vector Double)
, stdDevs :: !(Vector Double)
} deriving (Eq, Ord)
instance Show Sample where
show (Sample s e t vrs std) = concat
[ "Sample "
, show s
, " of experiment "
, show e
, " at time "
, show t
, "\n"
, show vrs
, "\n"
, show std ]
-- | >>> p (vec 4) "0.13 0.6036232 0.11150 0.75"
-- [0.13,0.6036232,0.1115,0.75]
vec :: Int -> Parser (Vector Double)
vec n = Vector.replicateM n double
-- | >>> :{
-- let s = unlines
-- [ "sample_2 of experiment_1"
-- , " has time = 0.20000000E+00"
-- , " has variable_ = 0.131E+01 0.6036 0.1115 0.75"
-- , " has sdev of variable_ = 0.131 0.6 0.11 0.0" ]
-- in p (sample 4) s
-- :}
-- Sample 2 of experiment 1 at time 0.2
-- [1.31,0.6036,0.1115,0.75]
-- [0.131,0.6,0.11,0.0]
sample :: Int -> Parser Sample
sample n = Sample <$> indexedOneDim "sample"
<*> context (indexedOneDim "experiment")
<* property "time"
<*> double
<* property "variable_"
<*> vec n
<*> foldr (*>) (vec n) ["has","sdev","of","variable_","="]
data ParamInfo a = ParamInfo
{ alphas :: [a]
, betas :: [a]
, posExps :: [[a]]
, negExps :: [[a]]
} deriving (Eq, Ord, Functor, Foldable)
instance Show a => Show (ParamInfo a) where
showsPrec _ p = showTable r 2 (n*2+2) hd cl where
n = length (alphas p)
r = (maximum . fmap (length.show)) p
hd = ["a"] ++ [ 'g' : show i | i <- [1..n] ] ++ ["b"] ++ [ 'h' : show i | i <- [1..n] ]
cl = zipWith5 (\i a ps b ns -> (show i, [a] ++ ps ++ [b] ++ ns))
([1..] :: [Int])
(alphas p)
(posExps p)
(betas p)
(negExps p)
data Bounds = Bounds
{ lower :: !Double
, upper :: !Double
} deriving (Eq, Ord)
instance Show Bounds where
showsPrec _ (Bounds l u) =
showParen True (shows l . showChar ',' . shows u)
paramInfo :: (String -> Parser a)
-> (String -> Parser b)
-> (a -> b -> a)
-> Int -> Parser (ParamInfo a)
paramInfo defInfo prop repDef n =
ParamInfo
<$> (map.repDef <$> defInfo "alpha" <*> traverse (coefInfo "alpha") [1..n])
<*> (map.repDef <$> defInfo "beta" <*> traverse (coefInfo "beta" ) [1..n])
<*> (map.map.repDef <$> defInfo "g" <*> traverse (for [1..n] . expInfo "g") [1..n])
<*> (map.map.repDef <$> defInfo "h" <*> traverse (for [1..n] . expInfo "h") [1..n])
where
coefInfo s i = prop (s <> "_" <> show i)
expInfo s i j = prop (s <> "_" <> show i <> "_" <> show j)
-- | >>> :{
-- let sampleStr = unlines
-- [ " alpha has defaultLowerBound = 20. "
-- , " alpha has defaultUpperBound = 0. "
-- , " beta has defaultLowerBound = 0. "
-- , " beta has defaultUpperBound = 20. "
-- , " g has defaultLowerBound = -4. "
-- , " g has defaultUpperBound = 4. "
-- , " g_1_1 has lowerBound = 0. "
-- , " g_1_1 has upperBound = 0. "
-- , " g_2_2 has lowerBound = 0. "
-- , " g_2_2 has upperBound = 0. "
-- , " h has defaultLowerBound = -4. "
-- , " h has defaultUpperBound = 4. "
-- , " h_1_1 has lowerBound = 1.5 "
-- , " h_2_2 has lowerBound = 1.2 " ]
-- in p (bounds 2) sampleStr
-- :}
-- ┌──┬──────────┬──────────┬──────────┬──────────┬──────────┬──────────┐
-- │ │ a │ g1 │ g2 │ b │ h1 │ h2 │
-- ├──┼──────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
-- │ 1│(20.0,0.0)│ (0.0,0.0)│(-4.0,4.0)│(0.0,20.0)│ (1.5,4.0)│(-4.0,4.0)│
-- │ 2│(20.0,0.0)│(-4.0,4.0)│ (0.0,0.0)│(0.0,20.0)│(-4.0,4.0)│ (1.2,4.0)│
-- └──┴──────────┴──────────┴──────────┴──────────┴──────────┴──────────┘
bounds :: Int -> Parser (ParamInfo Bounds)
bounds = paramInfo defaultBound bound repDef where
bound s =
(,) <$> optional (simpleProp s "lowerBound")
<*> optional (simpleProp s "upperBound")
defaultBound s =
Bounds <$> simpleProp s "defaultLowerBound"
<*> simpleProp s "defaultUpperBound"
repDef Bounds {..} (l,u) = Bounds (fromMaybe lower l) (fromMaybe upper u)
-- | >>> :{
-- let sampleStr = unlines
-- [ " alpha has defaultInitialValue = 20. "
-- , " beta has defaultInitialValue = 0. "
-- , " g has defaultInitialValue = -4. "
-- , " h has defaultInitialValue = -4. " ]
-- in p (initials 3) sampleStr
-- :}
-- ┌──┬────┬────┬────┬────┬────┬────┬────┬────┐
-- │ │ a │ g1 │ g2 │ g3 │ b │ h1 │ h2 │ h3 │
-- ├──┼────┼────┼────┼────┼────┼────┼────┼────┤
-- │ 1│20.0│-4.0│-4.0│-4.0│ 0.0│-4.0│-4.0│-4.0│
-- │ 2│20.0│-4.0│-4.0│-4.0│ 0.0│-4.0│-4.0│-4.0│
-- │ 3│20.0│-4.0│-4.0│-4.0│ 0.0│-4.0│-4.0│-4.0│
-- └──┴────┴────┴────┴────┴────┴────┴────┴────┘
initials :: Int -> Parser (ParamInfo Double)
initials = paramInfo defInit initial fromMaybe where
defInit s = simpleProp s "defaultInitialValue"
initial s = optional (simpleProp s "initialValue")
data Problem = Problem
{ variables :: [Dependency]
, space :: ParamInfo Bounds
, samples :: [Sample]
, initialSoln :: ParamInfo Double }
problem :: Parser Problem
problem = do
whiteSpace
vars <- some (variable <?> "vars")
let numVars = length vars
let varDeps = (map snd . sortOn fst) vars
Problem varDeps
<$> (bounds numVars <?> "bounds")
<* some (experiment <?> "exps")
<*> some (sample numVars <?> "sample")
<*> initials numVars
fromFile :: String -> IO Problem
fromFile = parseFromFileEx (getParser problem) >=> \case
Success x -> pure x
Failure (ErrInfo d _) -> putDoc d *> fail (show $ plain d)
|
oisdk/SSystemOpt
|
src/Text/Parse/ODEBench.hs
|
mit
| 11,286 | 0 | 15 | 2,961 | 2,429 | 1,316 | 1,113 | 215 | 2 |
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
module Leankit.Types.Board where
import Data.Aeson.TH
import Leankit.Types.Common
import Leankit.Types.User
import Leankit.Types.Lane
import Leankit.Types.TH
data Board = Board {
_active :: Maybe Bool,
_title :: Maybe String,
_prefix :: Maybe String,
_description :: Maybe String,
_version :: Maybe Int,
_excludeCompletedAndArchiveViolations :: Maybe Bool,
_isCardIdEnabled :: Maybe Bool,
_isHyperlinkEnabled :: Maybe Bool,
_isPrefixEnabled :: Maybe Bool,
_isPrefixIncludedInHyperlink :: Maybe Bool,
_isPrivate :: Maybe Bool,
_isWelcome :: Maybe Bool,
_classOfServiceEnabled :: Maybe Bool,
_archiveTopLevelLaneId :: Maybe Int,
_organizationId :: Maybe OrganizationID,
_cardColorField :: Maybe String,
_maxFileSize :: Maybe Int,
_format :: Maybe String,
_boardUsers :: [User],
_currentUserRole :: Maybe Int,
_topLevelLaneIds :: [LaneID],
_lanes :: [Lane]
} deriving (Eq, Show)
$(deriveFromJSON parseOptions ''Board)
|
dtorok/leankit-hsapi
|
Leankit/Types/Board.hs
|
mit
| 1,334 | 44 | 9 | 482 | 314 | 178 | 136 | 32 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Server.Views
( indexPage
, showPage
, error404Page
, error500Page
) where
import Control.Monad (forM_)
import Network.URI (URI)
import Data.Text (Text)
import Text.Blaze ((!))
import Text.Blaze.Html (Html)
import qualified Text.Blaze.Html5 as Html
import qualified Text.Blaze.Html5.Attributes as Attr
import Server.Types
indexPage :: [(Text, Text, Int, String)] -> Html
indexPage rows = template $ do
Html.p "See the frequency of every word at the given URL"
Html.form ! Attr.action "/histogram" ! Attr.method "post" $ do
Html.input ! Attr.type_ "url" ! Attr.name "url"
Html.input ! Attr.type_ "submit"
Html.h3 "Previous URLs entered:"
Html.table $ do
Html.tr $ do
Html.th "URL"
Html.th "Most Frequent Word"
Html.th "Count"
forM_ rows $ \(url, word, freq, href) ->
Html.tr $ do
Html.td $
Html.a ! Attr.href (Html.stringValue href) $ Html.toHtml url
Html.td $ Html.toHtml word
Html.td $ Html.toHtml freq
showPage :: URI -> [(Text, Int)] -> Html
showPage url rows = template $ do
Html.p $ do
Html.toHtml $ ("Top 10 words used in " :: String)
Html.a ! Attr.href (Html.stringValue urlStr) $ Html.toHtml urlStr
Html.toHtml $ (". " :: String)
Html.a ! Attr.href "/" $ "Try another URL"
Html.table $ do
Html.tr $ do
Html.th "Word"
Html.th "Frequency"
forM_ rows $ \(word, freq) ->
Html.tr $ do
Html.td $ Html.toHtml word
Html.td $ Html.toHtml freq
where
urlStr = show url
error404Page :: Html
error404Page = template $
Html.p "Error 404: Page Not found"
error500Page :: ServerError -> Html
error500Page err = template $
Html.p . Html.toHtml $ "Error 500: " ++ show err
-- helper functions
template :: Html -> Html
template contents =
Html.docTypeHtml $ do
Html.head $ do
Html.title "URL Text Histogram"
Html.style $ Html.toHtml stylesheet
Html.body $ do
Html.h1 "URL Text Histogram"
contents
-- NOTE: for *any* other application, I would add a static-file-serving WAI
-- middleware to serve assets. Because the "assets" are just a single
-- stylesheet, however, that doesn't seem worthwhile.
stylesheet :: String
stylesheet = unlines
[ "body {"
, " font-size: 14px;"
, " font-family: Helvetica, sans-serif;"
, "}"
, ""
, "table {"
, " border-collapse: collapse;"
, "}"
, ""
, "table td, table th {"
, " text-align: left;"
, " padding: 5px;"
, "}"
, ""
, "tr:nth-child(even) td, tr:nth-child(even) th {"
, " background-color: #EEE;"
, "}"
]
|
Jonplussed/url-text-histogram
|
src/Server/Views.hs
|
mit
| 2,729 | 0 | 21 | 732 | 778 | 399 | 379 | 82 | 1 |
module BST where
data BST = EmptyNode | Node BST Int BST deriving (Show, Eq)
inOrder :: BST -> [Int]
inOrder EmptyNode = []
inOrder (Node l v r) = inOrder l ++ [v] ++ inOrder r
find :: BST -> Int -> Bool
find EmptyNode _ = False
find (Node l v r) x
| x == v = True
| x > v = find r x
| otherwise = find l x
insert :: BST -> Int -> BST
insert EmptyNode x = Node EmptyNode x EmptyNode
insert node@(Node left value right) x
| x < value = Node (insert left x) value right
| x > value = Node left value (insert right x)
| otherwise = node
fromList :: [Int] -> BST
fromList [] = EmptyNode
fromList (first : rest) = insert (fromList rest) first
isBST :: BST -> Bool
isBST EmptyNode = True
isBST (Node EmptyNode _ EmptyNode) = True
isBST (Node l@(Node _ lv _) v EmptyNode) = lv < v && isBST l
isBST (Node EmptyNode v r@(Node _ rv _)) = rv > v && isBST r
isBST (Node l@(Node _ lv _) v r@(Node _ rv _)) = lv < v && v > rv && isBST l && isBST r
|
abhin4v/haskell-classes
|
2016-03-01/BST.hs
|
cc0-1.0
| 968 | 0 | 10 | 245 | 525 | 262 | 263 | 26 | 1 |
import Data.List
|
t00n/ProjectEuler
|
modules.hs
|
epl-1.0
| 16 | 0 | 4 | 1 | 6 | 3 | 3 | 1 | 0 |
module LF.MorphParser where
import LF.Sign
import LF.Morphism
import Common.Lexer
import Common.Parsec
import Common.AnnoParser (commentLine)
import Text.ParserCombinators.Parsec
import System.Directory
import System.IO.Unsafe
import qualified Data.Map as Map
readMorphism :: FilePath -> Morphism
readMorphism file =
let mor = unsafePerformIO $ readMorph file
in case mor of
Just m -> m
Nothing -> error $ "readMorphism : Could not read the " ++
"morphism from " ++ (show file)
readMorph :: FilePath -> IO (Maybe Morphism)
readMorph file = do
e <- doesFileExist file
if e then do
content <- readFile file
case runParser (parseMorphism << eof) () file content of
Right m -> return $ Just m
Left err -> error $ show err
else return Nothing
parseMorphism :: CharParser st Morphism
parseMorphism = do
skips $ manyTill anyChar (string "=")
pkeyword "Morphism"
skipChar '{'
mb <- parseWithEq "morphBase"
skipChar ','
mm <- parseWithEq "morphModule"
skipChar ','
mn <- parseWithEq "morphName"
skipChar ','
pkeyword "source"
skipChar '='
s <- parseSignature
skipChar ','
pkeyword "target"
skipChar '='
t <- parseSignature
skipChar ','
pkeyword "morphType"
skipChar '='
mt <- parseMorphType
skipChar ','
pkeyword "symMap"
skipChar '='
sm <- parseMap
skipChar '}'
return $ Morphism mb mm mn s t mt sm
-- | plain string parser with skip
pkeyword :: String -> CharParser st ()
pkeyword s = keywordNotFollowedBy s (alphaNum <|> char '/') >> return ()
keywordNotFollowedBy :: String -> CharParser st Char -> CharParser st String
keywordNotFollowedBy s c = skips $ try $ string s << notFollowedBy c
skips :: CharParser st a -> CharParser st a
skips = (<< skipMany
(forget space <|> forget commentLine <|> nestCommentOut <?> ""))
qString :: CharParser st String
qString = skips endsWithQuot
parensP :: CharParser st a -> CharParser st a
parensP p = between (skipChar '(') (skipChar ')') p
<|> p
bracesP :: CharParser st a -> CharParser st a
bracesP = between (skipChar '{') (skipChar '}')
bracketsP :: CharParser st a -> CharParser st a
bracketsP = between (skipChar '[') (skipChar ']')
endsWithQuot :: CharParser st String
endsWithQuot = do
skipChar '"'
manyTill anyChar (string "\"") >>= return
commaP :: CharParser st ()
commaP = skipChar ',' >> return ()
sepByComma :: CharParser st a -> CharParser st [a]
sepByComma p = sepBy1 p commaP
skipChar :: Char -> CharParser st ()
skipChar = forget . skips . char
parseWithEq :: String -> CharParser st String
parseWithEq s = do
pkeyword s
skipChar '='
qString >>= return
parseSym :: CharParser st Symbol
parseSym = do
pkeyword "Symbol"
skipChar '{'
sb <- parseWithEq "symBase"
skipChar ','
sm <- parseWithEq "symModule"
skipChar ','
sn <- parseWithEq "symName"
skipChar '}'
return $ Symbol sb sm sn
parse1Context :: CharParser st CONTEXT
parse1Context = do
skipChar '('
v <- qString
skipChar ','
e <- parseExp
option () $ skipChar ')'
return [(v, e)]
parseExp :: CharParser st EXP
parseExp = do
pkeyword "Type" >> return Type
<|> do
pkeyword "Var"
fmap Var qString
<|> do
pkeyword "Const"
fmap Const parseSym
<|> do
pkeyword "Appl"
ex <- parensP parseExp
exl <- bracketsP $ option [] $ sepByComma parseExp
return $ Appl ex exl
<|> do
pkeyword "Func"
exl <- bracketsP $ option [] $ sepByComma parseExp
ex <- parensP parseExp
return $ Func exl ex
<|> do
ty <- choice $ map (\ ty -> pkeyword ty >> return ty)
["Pi", "Lamb"]
c <- bracketsP $ option [] $ sepByComma parse1Context
e <- parensP parseExp
return $ (case ty of
"Pi" -> Pi
"Lamb" -> Lamb
_ -> error $ "Pi or Lamb expected.\n") (concat c) e
parseDef :: CharParser st DEF
parseDef = do
pkeyword "Def"
skipChar '{'
pkeyword "getSym"
skipChar '='
sym <- parseSym
skipChar ','
pkeyword "getType"
skipChar '='
tp <- parseExp
skipChar ','
pkeyword "getValue"
skipChar '='
val <- do pkeyword "Nothing" >> return Nothing
<|> do pkeyword "Just"
e <- parensP parseExp
return $ Just e
skipChar '}'
return $ Def sym tp val
parseSignature :: CharParser st Sign
parseSignature = do
pkeyword "Sign"
skipChar '{'
sb <- parseWithEq "sigBase"
skipChar ','
sm <- parseWithEq "sigModule"
skipChar ','
pkeyword "getDefs"
skipChar '='
sd <- bracketsP $ option [] $ sepByComma parseDef
skipChar '}'
return $ Sign sb sm sd
parseMorphType :: CharParser st MorphType
parseMorphType = do
choice $ map (\ t -> pkeyword (show t) >> return t)
[Definitional, Postulated, Unknown ]
parse1Map :: CharParser st (Symbol, EXP)
parse1Map = do
skipChar '('
s <- parseSym
skipChar ','
e <- parseExp
skipChar ')'
return (s, e)
parseMap :: CharParser st (Map.Map Symbol EXP)
parseMap = do
pkeyword "fromList"
fmap Map.fromList $ bracketsP $ option [] $ sepByComma parse1Map
|
nevrenato/Hets_Fork
|
LF/MorphParser.hs
|
gpl-2.0
| 5,359 | 0 | 14 | 1,506 | 1,855 | 837 | 1,018 | 181 | 3 |
module TMVar where
import Control.Monad (void)
import Control.Monad.STM
import Control.Concurrent
import Control.Concurrent.STM.TVar
newtype TMVar a = TMVar (TVar (Maybe a))
newEmptyTMVar :: STM (TMVar a)
newEmptyTMVar = do
t <- newTVar Nothing
return $ TMVar t
takeTMVar :: TMVar a -> STM a
takeTMVar (TMVar tvar) = do
m <- readTVar tvar
case m of
Nothing -> retry
Just a -> writeTVar tvar Nothing >> return a
putTMVar :: TMVar a -> a -> STM ()
putTMVar (TMVar tvar) a = do
m <- readTVar tvar
case m of
Just _ -> retry
Nothing -> void $ writeTVar tvar (Just a)
takeEitherTMVar :: TMVar a -> TMVar b -> STM (Either a b)
takeEitherTMVar ma mb = fmap Left (takeTMVar ma) `orElse` fmap Right (takeTMVar mb)
|
y-kamiya/parallel-concurrent-haskell
|
src/Stm/TMVar.hs
|
gpl-2.0
| 739 | 0 | 13 | 161 | 317 | 156 | 161 | 24 | 2 |
module Data.CycleRoll.Internal.LCP where
import Prelude hiding (
null, head, tail, length, last, sum
)
import qualified Data.CycleRoll.Internal.SuffixArray as SA
import Data.Vector.Unboxed hiding (find, sum)
import qualified Data.Vector.Primitive as PV
import qualified Data.List as List
import qualified Data.Heap as Heap
import qualified Data.Map as Map
import qualified Data.Foldable as Foldable
import qualified Data.RangeMin as RangeMin
find :: (Eq a, Unbox a, Num b) => Vector a -> Vector a -> b
find v w
| null v = 0
| null w = 0
| head v == head w = 1 + find (tail v) (tail w)
| otherwise = 0
array :: (Unbox a, Eq a) => Vector a -> Vector Int -> Vector Int
array v suf_arr
| sa_len <= 1 = fromList []
| otherwise = List.foldr fn empty [0..(sa_len-2)]
where
sa_len = length suf_arr
fn i sum =
(find (suffix i) $ suffix $ i+1) `cons` sum
where
suffix = SA.entry v suf_arr
rmq :: Vector Int -> (Int -> Int -> Int -> Bool)
rmq lcparr =
ret_fn $ RangeMin.intRangeMin pv_lcparr
where
pv_lcparr :: PV.Vector Int
pv_lcparr = PV.convert lcparr
ret_fn rmq_fn idx1 idx2 min_val
| idx1 == idx2 = error $ (show idx1) List.++ " = idx1 == idx2 = " List.++ (show idx2)
| idx1 < idx2 = not . test $ rmq_fn idx1 (idx2-idx1)
| otherwise = ret_fn rmq_fn idx2 idx1 min_val
where
test i = lcparr!i < min_val
data GroupElem =
GroupElem {
srcIdx :: Int,
saIdx :: Int
} deriving (Show, Eq, Ord)
data Group =
Group {
groupLCP :: Int,
groupMembers :: Heap.Heap GroupElem
} deriving (Eq)
--invert compare for Group so Heap will prioritize higher LCP
instance Ord Group where
compare a b = (groupLCP b) `compare` (groupLCP a)
instance Show Group where
show (Group lcp memb) =
" " List.++ (show lcp) List.++ ": " List.++ (Foldable.foldr fn "" memb) List.++ "\n"
where
fn (GroupElem a b) sum = "\n " List.++ (show (a,b)) List.++ sum
groups :: Vector Int -> Vector Int -> Heap.Heap Group
groups sarr lcparr
| length lcparr < 1 = Heap.empty
| otherwise = Map.foldlWithKey fold_fn Heap.empty lcp_group_map
where
fold_fn hp key val = Heap.insert (Group key val) hp
lcp_group_map =
add_ends_to middle
where
final_idx = (length sarr)-1
map_append k v mp
| k < 1 = mp -- LCP of zero is not a useful LCP group
| otherwise = Map.insert k new_el mp
where
new_el = Heap.insert v $ Map.findWithDefault Heap.empty k mp
add_ends_to mp =
map_append (lcparr!0) beg $ map_append (lcparr!(final_idx-1)) end mp
where
beg = GroupElem (head sarr) 0
end = GroupElem (last sarr) final_idx
middle =
List.foldl add_element Map.empty [1..(final_idx-1)]
where
add_element mp sa_idx =
map_append lcp (GroupElem (sarr!sa_idx) sa_idx) mp
where
lcp = max (lcparr!(sa_idx-1)) $ lcparr!sa_idx
mergedGroups :: Heap.Heap Group -> [Group]
mergedGroups grp_hp =
recurse Heap.empty [] grp_hp
where
recurse prev_mb base heap
| Heap.null heap = base
| otherwise = cur:(recurse merged base $ Heap.deleteMin heap)
where
cur_grp = Heap.minimum heap
merged = (groupMembers cur_grp) `Heap.union` prev_mb
cur = Group (groupLCP cur_grp) merged
|
cantora/cycle-roll
|
src/Data/CycleRoll/Internal/LCP.hs
|
gpl-3.0
| 3,509 | 0 | 19 | 1,044 | 1,287 | 663 | 624 | 81 | 1 |
module Functions.Combinatorics.CombFunc
(fact
,comb
,perm
) where
import Functions.Algebra (incSum)
--Single Factorial
fact :: Float -> Float
fact 0 = 1
fact n = n * (fact $ n - 1)
comb :: Float -> Float -> Float
comb n m | m > n = 0
| otherwise = perm n m / fact m
perm :: Float -> Float -> Float
perm n m | m > n = 0
| otherwise = (fact n) / fact (n - m)
|
LeoMingo/RPNMathParser
|
Functions/Combinatorics/CombFunc.hs
|
gpl-3.0
| 388 | 0 | 9 | 113 | 185 | 95 | 90 | 14 | 1 |
-----------------------------------------------------------------------------
-- Standard Library: List operations
--
-- Suitable for use with Helium, derived from Hugs 98 Standard Library
-- Modifications:
-- * tuple constructors for zip functions
-- * 'generic' functions for Integral type class are excluded
-- * list functions from Prelude are not exported by this module
-----------------------------------------------------------------------------
module List where
import Maybe
infix 5 \\
elemIndex :: Eq a => a -> [a] -> Maybe Int
elemIndex x = findIndex (x ==)
elemIndices :: Eq a => a -> [a] -> [Int]
elemIndices x = findIndices (x ==)
find :: (a -> Bool) -> [a] -> Maybe a
find p = listToMaybe . filter p
findIndex :: (a -> Bool) -> [a] -> Maybe Int
findIndex p = listToMaybe . findIndices p
findIndices :: (a -> Bool) -> [a] -> [Int]
findIndices p xs = [ i | (x,i) <- zip xs [0..], p x ]
nub :: (Eq a) => [a] -> [a]
nub = nubBy (==)
nubBy :: (a -> a -> Bool) -> [a] -> [a]
nubBy eq [] = []
nubBy eq (x:xs) = x : nubBy eq (filter (\y -> not (eq x y)) xs)
delete :: (Eq a) => a -> [a] -> [a]
delete = deleteBy (==)
deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
deleteBy eq x [] = []
deleteBy eq x (y:ys) = if x `eq` y then ys else y : deleteBy eq x ys
(\\) :: (Eq a) => [a] -> [a] -> [a]
(\\) = foldl (flip delete)
deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
deleteFirstsBy eq = foldl (flip (deleteBy eq))
union :: (Eq a) => [a] -> [a] -> [a]
union = unionBy (==)
unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
unionBy eq xs ys = xs ++ foldl (flip (deleteBy eq)) (nubBy eq ys) xs
intersect :: (Eq a) => [a] -> [a] -> [a]
intersect = intersectBy (==)
intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
intersectBy eq xs ys = [x | x <- xs, any (eq x) ys]
intersperse :: a -> [a] -> [a]
intersperse sep [] = []
intersperse sep [x] = [x]
intersperse sep (x:xs) = x : sep : intersperse sep xs
transpose :: [[a]] -> [[a]]
transpose [] = []
transpose ([] : xss) = transpose xss
transpose ((x:xs) : xss) = (x : [h | (h:t) <- xss]) :
transpose (xs : [ t | (h:t) <- xss])
partition :: (a -> Bool) -> [a] -> ([a],[a])
partition p xs = foldr select ([],[]) xs
where select x (ts,fs) | p x = (x:ts,fs)
| otherwise = (ts,x:fs)
-- group splits its list argument into a list of lists of equal, adjacent
-- elements. e.g.,
-- group "Mississippi" == ["M","i","ss","i","ss","i","pp","i"]
group :: (Eq a) => [a] -> [[a]]
group = groupBy (==)
groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy eq [] = []
groupBy eq (x:xs) = (x:ys) : groupBy eq zs
where (ys,zs) = span (eq x) xs
-- inits xs returns the list of initial segments of xs, shortest first.
-- e.g., inits "abc" == ["","a","ab","abc"]
inits :: [a] -> [[a]]
inits [] = [[]]
inits (x:xs) = [[]] ++ map (x:) (inits xs)
-- tails xs returns the list of all final segments of xs, longest first.
-- e.g., tails "abc" == ["abc", "bc", "c",""]
tails :: [a] -> [[a]]
tails [] = [[]]
tails xxs@(_:xs) = xxs : tails xs
isPrefixOf :: (Eq a) => [a] -> [a] -> Bool
isPrefixOf [] _ = True
isPrefixOf _ [] = False
isPrefixOf (x:xs) (y:ys) = x == y && isPrefixOf xs ys
isSuffixOf :: (Eq a) => [a] -> [a] -> Bool
isSuffixOf x y = reverse x `isPrefixOf` reverse y
mapAccumL :: (a -> b -> (a, c)) -> a -> [b] -> (a, [c])
mapAccumL f s [] = (s, [])
mapAccumL f s (x:xs) = (s'',y:ys)
where (s', y ) = f s x
(s'',ys) = mapAccumL f s' xs
mapAccumR :: (a -> b -> (a, c)) -> a -> [b] -> (a, [c])
mapAccumR f s [] = (s, [])
mapAccumR f s (x:xs) = (s'', y:ys)
where (s'',y ) = f s' x
(s', ys) = mapAccumR f s xs
unfoldr :: (b -> Maybe (a,b)) -> b -> [a]
unfoldr f b = case f b of Nothing -> []
Just (a,b) -> a : unfoldr f b
sort :: (Ord a) => [a] -> [a]
sort = sortBy compare
sortBy :: (a -> a -> Ordering) -> [a] -> [a]
sortBy cmp = foldr (insertBy cmp) []
insert :: (Ord a) => a -> [a] -> [a]
insert = insertBy compare
insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]
insertBy cmp x [] = [x]
insertBy cmp x ys@(y:ys')
= case cmp x y of
GT -> y : insertBy cmp x ys'
_ -> x : ys
maximumBy :: (a -> a -> Ordering) -> [a] -> a
maximumBy cmp [] = error "List.maximumBy: empty list"
maximumBy cmp xs = foldl1 max xs
where
max x y = case cmp x y of
GT -> x
_ -> y
minimumBy :: (a -> a -> Ordering) -> [a] -> a
minimumBy cmp [] = error "List.minimumBy: empty list"
minimumBy cmp xs = foldl1 min xs
where
min x y = case cmp x y of
GT -> y
_ -> x
zip4 :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]
zip4 = zipWith4 (\a b c d -> (a, b, c, d))
zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)]
zip5 = zipWith5 (\a b c d e -> (a, b, c, d, e))
zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] ->
[(a,b,c,d,e,f)]
zip6 = zipWith6 (\a b c d e f -> (a, b, c, d, e, f))
zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] ->
[g] -> [(a,b,c,d,e,f,g)]
zip7 = zipWith7 (\a b c d e f g -> (a, b, c, d, e, f, g))
zipWith4 :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
zipWith4 z (a:as) (b:bs) (c:cs) (d:ds)
= z a b c d : zipWith4 z as bs cs ds
zipWith4 _ _ _ _ _ = []
zipWith5 :: (a->b->c->d->e->f) ->
[a]->[b]->[c]->[d]->[e]->[f]
zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es)
= z a b c d e : zipWith5 z as bs cs ds es
zipWith5 _ _ _ _ _ _ = []
zipWith6 :: (a->b->c->d->e->f->g) ->
[a]->[b]->[c]->[d]->[e]->[f]->[g]
zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs)
= z a b c d e f : zipWith6 z as bs cs ds es fs
zipWith6 _ _ _ _ _ _ _ = []
zipWith7 :: (a->b->c->d->e->f->g->h) ->
[a]->[b]->[c]->[d]->[e]->[f]->[g]->[h]
zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs)
= z a b c d e f g : zipWith7 z as bs cs ds es fs gs
zipWith7 _ _ _ _ _ _ _ _ = []
unzip4 :: [(a,b,c,d)] -> ([a],[b],[c],[d])
unzip4 = foldr (\(a,b,c,d) ~(as,bs,cs,ds) ->
(a:as,b:bs,c:cs,d:ds))
([],[],[],[])
unzip5 :: [(a,b,c,d,e)] -> ([a],[b],[c],[d],[e])
unzip5 = foldr (\(a,b,c,d,e) ~(as,bs,cs,ds,es) ->
(a:as,b:bs,c:cs,d:ds,e:es))
([],[],[],[],[])
unzip6 :: [(a,b,c,d,e,f)] -> ([a],[b],[c],[d],[e],[f])
unzip6 = foldr (\(a,b,c,d,e,f) ~(as,bs,cs,ds,es,fs) ->
(a:as,b:bs,c:cs,d:ds,e:es,f:fs))
([],[],[],[],[],[])
unzip7 :: [(a,b,c,d,e,f,g)] -> ([a],[b],[c],[d],[e],[f],[g])
unzip7 = foldr (\(a,b,c,d,e,f,g) ~(as,bs,cs,ds,es,fs,gs) ->
(a:as,b:bs,c:cs,d:ds,e:es,f:fs,g:gs))
([],[],[],[],[],[],[])
-----------------------------------------------------------------------------
|
roberth/uu-helium
|
lib/List.hs
|
gpl-3.0
| 8,351 | 0 | 13 | 3,333 | 4,249 | 2,376 | 1,873 | 148 | 2 |
-- |
-- Module : Aura.Commands.O
-- Copyright : (c) Colin Woodbury, 2012 - 2020
-- License : GPL3
-- Maintainer: Colin Woodbury <[email protected]>
--
-- Handle all @-O@ flags - those which involve orphan packages.
module Aura.Commands.O ( displayOrphans, adoptPkg ) where
import Aura.Core (Env(..), orphans, sudo)
import Aura.IO (putTextLn)
import Aura.Pacman (pacman)
import Aura.Types
import RIO
---
-- | Print the result of @pacman -Qqdt@
displayOrphans :: IO ()
displayOrphans = orphans >>= traverse_ (putTextLn . pnName)
-- | Identical to @-D --asexplicit@.
adoptPkg :: NonEmpty PkgName -> RIO Env ()
adoptPkg pkgs = sudo . liftIO . pacman $ ["-D", "--asexplicit"] <> asFlag pkgs
|
bb010g/aura
|
aura/exec/Aura/Commands/O.hs
|
gpl-3.0
| 696 | 0 | 8 | 117 | 154 | 91 | 63 | 10 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.CloudWatchLogs.GetLogEvents
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Retrieves log events from the specified log stream. You can provide an
-- optional time range to filter the results on the event 'timestamp'.
--
-- By default, this operation returns as much log events as can fit in a
-- response size of 1MB, up to 10,000 log events. The response will always
-- include a 'nextForwardToken' and a 'nextBackwardToken' in the response body. You
-- can use any of these tokens in subsequent 'GetLogEvents' requests to paginate
-- through events in either forward or backward direction. You can also limit
-- the number of log events returned in the response by specifying the 'limit'
-- parameter in the request.
--
-- <http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetLogEvents.html>
module Network.AWS.CloudWatchLogs.GetLogEvents
(
-- * Request
GetLogEvents
-- ** Request constructor
, getLogEvents
-- ** Request lenses
, gleEndTime
, gleLimit
, gleLogGroupName
, gleLogStreamName
, gleNextToken
, gleStartFromHead
, gleStartTime
-- * Response
, GetLogEventsResponse
-- ** Response constructor
, getLogEventsResponse
-- ** Response lenses
, glerEvents
, glerNextBackwardToken
, glerNextForwardToken
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.CloudWatchLogs.Types
import qualified GHC.Exts
data GetLogEvents = GetLogEvents
{ _gleEndTime :: Maybe Nat
, _gleLimit :: Maybe Nat
, _gleLogGroupName :: Text
, _gleLogStreamName :: Text
, _gleNextToken :: Maybe Text
, _gleStartFromHead :: Maybe Bool
, _gleStartTime :: Maybe Nat
} deriving (Eq, Ord, Read, Show)
-- | 'GetLogEvents' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'gleEndTime' @::@ 'Maybe' 'Natural'
--
-- * 'gleLimit' @::@ 'Maybe' 'Natural'
--
-- * 'gleLogGroupName' @::@ 'Text'
--
-- * 'gleLogStreamName' @::@ 'Text'
--
-- * 'gleNextToken' @::@ 'Maybe' 'Text'
--
-- * 'gleStartFromHead' @::@ 'Maybe' 'Bool'
--
-- * 'gleStartTime' @::@ 'Maybe' 'Natural'
--
getLogEvents :: Text -- ^ 'gleLogGroupName'
-> Text -- ^ 'gleLogStreamName'
-> GetLogEvents
getLogEvents p1 p2 = GetLogEvents
{ _gleLogGroupName = p1
, _gleLogStreamName = p2
, _gleStartTime = Nothing
, _gleEndTime = Nothing
, _gleNextToken = Nothing
, _gleLimit = Nothing
, _gleStartFromHead = Nothing
}
gleEndTime :: Lens' GetLogEvents (Maybe Natural)
gleEndTime = lens _gleEndTime (\s a -> s { _gleEndTime = a }) . mapping _Nat
-- | The maximum number of log events returned in the response. If you don't
-- specify a value, the request would return as many log events as can fit in a
-- response size of 1MB, up to 10,000 log events.
gleLimit :: Lens' GetLogEvents (Maybe Natural)
gleLimit = lens _gleLimit (\s a -> s { _gleLimit = a }) . mapping _Nat
gleLogGroupName :: Lens' GetLogEvents Text
gleLogGroupName = lens _gleLogGroupName (\s a -> s { _gleLogGroupName = a })
gleLogStreamName :: Lens' GetLogEvents Text
gleLogStreamName = lens _gleLogStreamName (\s a -> s { _gleLogStreamName = a })
-- | A string token used for pagination that points to the next page of results.
-- It must be a value obtained from the 'nextForwardToken' or 'nextBackwardToken'
-- fields in the response of the previous 'GetLogEvents' request.
gleNextToken :: Lens' GetLogEvents (Maybe Text)
gleNextToken = lens _gleNextToken (\s a -> s { _gleNextToken = a })
-- | If set to true, the earliest log events would be returned first. The default
-- is false (the latest log events are returned first).
gleStartFromHead :: Lens' GetLogEvents (Maybe Bool)
gleStartFromHead = lens _gleStartFromHead (\s a -> s { _gleStartFromHead = a })
gleStartTime :: Lens' GetLogEvents (Maybe Natural)
gleStartTime = lens _gleStartTime (\s a -> s { _gleStartTime = a }) . mapping _Nat
data GetLogEventsResponse = GetLogEventsResponse
{ _glerEvents :: List "events" OutputLogEvent
, _glerNextBackwardToken :: Maybe Text
, _glerNextForwardToken :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'GetLogEventsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'glerEvents' @::@ ['OutputLogEvent']
--
-- * 'glerNextBackwardToken' @::@ 'Maybe' 'Text'
--
-- * 'glerNextForwardToken' @::@ 'Maybe' 'Text'
--
getLogEventsResponse :: GetLogEventsResponse
getLogEventsResponse = GetLogEventsResponse
{ _glerEvents = mempty
, _glerNextForwardToken = Nothing
, _glerNextBackwardToken = Nothing
}
glerEvents :: Lens' GetLogEventsResponse [OutputLogEvent]
glerEvents = lens _glerEvents (\s a -> s { _glerEvents = a }) . _List
glerNextBackwardToken :: Lens' GetLogEventsResponse (Maybe Text)
glerNextBackwardToken =
lens _glerNextBackwardToken (\s a -> s { _glerNextBackwardToken = a })
glerNextForwardToken :: Lens' GetLogEventsResponse (Maybe Text)
glerNextForwardToken =
lens _glerNextForwardToken (\s a -> s { _glerNextForwardToken = a })
instance ToPath GetLogEvents where
toPath = const "/"
instance ToQuery GetLogEvents where
toQuery = const mempty
instance ToHeaders GetLogEvents
instance ToJSON GetLogEvents where
toJSON GetLogEvents{..} = object
[ "logGroupName" .= _gleLogGroupName
, "logStreamName" .= _gleLogStreamName
, "startTime" .= _gleStartTime
, "endTime" .= _gleEndTime
, "nextToken" .= _gleNextToken
, "limit" .= _gleLimit
, "startFromHead" .= _gleStartFromHead
]
instance AWSRequest GetLogEvents where
type Sv GetLogEvents = CloudWatchLogs
type Rs GetLogEvents = GetLogEventsResponse
request = post "GetLogEvents"
response = jsonResponse
instance FromJSON GetLogEventsResponse where
parseJSON = withObject "GetLogEventsResponse" $ \o -> GetLogEventsResponse
<$> o .:? "events" .!= mempty
<*> o .:? "nextBackwardToken"
<*> o .:? "nextForwardToken"
|
romanb/amazonka
|
amazonka-cloudwatch-logs/gen/Network/AWS/CloudWatchLogs/GetLogEvents.hs
|
mpl-2.0
| 7,145 | 0 | 14 | 1,561 | 1,056 | 625 | 431 | 107 | 1 |
module Import.Layout (layout) where
import Import.Base
import Import.Enum
import Import.Piece
import Foundation
import Model
import Text.Julius (juliusFile)
import qualified Data.Aeson as Json
import qualified Data.CaseInsensitive as CI
import Import.Message
wrap :: Widget -> Text -> Widget
wrap w "navbar" = do
maid <- handlerToWidget maybeAuthId
ms <- getMessages
manager <- handlerToWidget $ checkLevel Manager
domain <- handlerToWidget getDomain
r <- handlerToWidget getCurrentRoute
wd <- handlerToWidget wrapData
let isHome = case r of
Just HomeR -> True
Just (CustomR "home") -> True
_ -> False
mhome' = wrapKey "home" wd
mhome = fmap (\(_, t, v) -> renderData t v) mhome'
$(widgetFile "wrappers/navbar")
wrap w "amazekebab" = do
maid <- handlerToWidget maybeAuthId
ms <- getMessages
manager <- handlerToWidget $ checkLevel Manager
domain <- handlerToWidget getDomain
r <- handlerToWidget getCurrentRoute
wd <- handlerToWidget wrapData
let isHome = case r of
Just HomeR -> True
Just (CustomR "home") -> True
_ -> False
mhome' = wrapKey "home" wd
mhome = fmap (\(_, t, v) -> renderData t v) mhome'
$(widgetFile "wrappers/amazekebab")
wrap w _ = getMessages >>= (\ms -> $(widgetFile "wrappers/default-layout"))
wrapData :: Handler [(Value Text, Value PieceDataType, Value Text)]
wrapData = do
d <- getDeploymentId
runDB $ select $ from $ \wd -> do
where_ $ wd ^. WrapDataDeployment ==. val d
return ( wd ^. WrapDataKey, wd ^. WrapDataType, wd ^. WrapDataValue )
wrapKey :: Text -> [(Value Text, Value PieceDataType, Value Text)] -> Maybe (Text, PieceDataType, Text)
wrapKey _ [] = Nothing
wrapKey key (r@(Value k, _, _):vs)
| k == key = Just $ unValue3 r
| otherwise = wrapKey key vs
wrapType :: Text
-> PieceDataType
-> [(Value Text, Value PieceDataType, Value Text)]
-> Maybe (Text, PieceDataType, Text)
wrapType key t l = wrapKey key l >>= (\r@(_, t', _) -> if t == t' then Just r else Nothing)
layout :: WidgetT App IO () -> HandlerT App IO Html
layout widget = do
-- Need getDeploymentSafe because the subwidget might be a 404 response already.
(domain, wrapper) <- do
md <- getDeploymentSafe
return $ case md of
Just d -> (deploymentDomain d, deploymentWrapper d)
Nothing -> ("fallback", "")
token <- returnJson . reqToken =<< getRequest
let csrfHeader = Json.toJSON $ decodeUtf8 $ CI.original defaultCsrfHeaderName
pc <- widgetToPageContent $ do
addStylesheet $ StaticR global_css_bootstrap_min_css
addStylesheet $ StaticR global_css_base_css
addStylesheet $ local domain ["css", "style.css"]
addScript $ StaticR global_js_jquery_1_11_3_min_js
addScript $ StaticR global_js_bootstrap_min_js
toWidget $(juliusFile "templates/ajax.julius")
wrap widget wrapper
withUrlRenderer [hamlet|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>#{pageTitle pc}
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="@{local domain ["img", "favicon.ico"]}">
^{pageHead pc}
<body>
^{pageBody pc}
|]
|
sir-murray/lol
|
Import/Layout.hs
|
agpl-3.0
| 3,359 | 0 | 15 | 814 | 1,007 | 501 | 506 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
module Ui
( Ui
, UiType(..)
, UiTypeMenu(..)
, defaultUi
, uiVisible
, _MkUiTypeMenu
) where
import Control.Lens
data Ui = MkUi
{ _uiVisible :: [UiType]
}
data UiType = MkUiTypeMenu UiTypeMenu
-- | MkUiTypeOverlay UiTypeOverlay
data UiTypeMenu = UiMenuMain
| UiMenuBuild
| UiMenuQuitConfirm
deriving Eq
makeLenses ''Ui
makePrisms ''UiType
-- data UiTypeOverlay = UiOverlayVitals -- TODO: defined but not used
defaultUi :: Ui
defaultUi = MkUi []
|
nitrix/lspace
|
legacy/Ui.hs
|
unlicense
| 584 | 0 | 9 | 178 | 114 | 68 | 46 | 20 | 1 |
{-# LANGUAGE CPP #-}
{-|
Module : Main
Description : roguelike game with puzzle elements
Copyright : (c) Khadaev Konstantin, 2016
License : Unlicense
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
-}
module Main where
import Data.Const
import Data.World
import Data.Define
import Utils.Changes (clearMessage)
import IO.Step
import IO.Show
import IO.Colors
import IO.Texts
import IO.SaveLoad
import Init
import UI.HSCurses.Curses
import Control.Monad (unless, liftM)
import System.Random (getStdGen)
import Control.Exception (catch, SomeException)
import Control.DeepSeq
import Data.Time.Clock
import System.Time.Utils (renderSecs)
import Data.Functor ((<$>))
import Data.Maybe (listToMaybe)
import qualified Data.Map as M
logName, saveName, resName :: String
-- | file with the game log
logName = "traphack.log"
-- | file with the game save
saveName = "traphack.save"
-- | file with results
resName = "traphack.res"
-- | catch all exceptions to run 'endWin' after exit with error
catchAll :: IO a -> (SomeException -> IO a) -> IO a
catchAll = catch
-- | split string to a list of strings by given separator
separate :: Char -> String -> [String]
separate _ [] = [""]
separate c s = takeWhile (c /=) s :
case dropWhile (c /=) s of
[] -> []
_ : rest -> separate c rest
-- | read file with name 'logName' and adapt it to show as in-game message
getReverseLog :: IO [(String, Int)]
getReverseLog = liftM (map (flip (,) defaultc) . tail . reverse
. separate '\n') $ readFile logName
-- | main loop in the game
loop :: World -> IO (Exit, World)
loop world =
if isPlayerNow world
then do
c <- redraw world
(_, width) <- scrSize
case step (clearMessage width world) c of
Left newWorld -> case action newWorld of
Save -> do
writeFile saveName $ show $ saveWorld newWorld
return (ExitSave, world)
Previous -> do
msgs <- getReverseLog
loop newWorld {action = AfterSpace, message = msgs}
AfterSpace -> loop newWorld
_ -> do
maybeAppendFile logName $ filter (not . null)
$ fst <$> message world
loop newWorld
Right (exit, w) ->
writeFile saveName "" >> appendFile logName (msgByExit exit ++ "\n")
>> return (exit, w)
else
case step world ' ' of
Left newWorld -> loop newWorld
Right (exit, newWorld) -> redraw newWorld >>
appendFile logName (msgByExit exit ++ "\n") >> return (exit, newWorld)
where
maybeAppendFile fileName strings =
unless (null strings) $ appendFile fileName $ unwords strings ++ "\n"
-- | add result with given Wave and Level to file 'resName'
addResult :: World -> IO ()
addResult w = do
s <- catchAll (readFile resName) $ const $ return ""
let stat = maybe M.empty fst $ listToMaybe $ reads s :: M.Map MapGenType (M.Map Int (Int, Int))
--let newStat = M.alter addNew lvl stat
let newStat = M.alter addNew mapGenType stat
s `deepseq` writeFile resName (show newStat)
putStrLn msgAskRes
ans <- getChar
_ <- getLine
unless (ans /= 'y' && ans /= 'Y') $ mapM_ printResult $ M.toList (newStat M.! mapGenType)
where
lvl = playerLevel w
wv = wave w - 1
mapGenType = mapType w
addNew :: Maybe (M.Map Int (Int, Int)) -> Maybe (M.Map Int (Int, Int))
addNew Nothing = Just $ M.singleton lvl (wv, 1)
addNew (Just m) = Just $ M.alter addNew' lvl m
addNew' :: Maybe (Int, Int) -> Maybe (Int, Int)
addNew' Nothing = Just (wv, 1)
addNew' (Just (sm, cnt)) = Just (sm + wv, cnt + 1)
printResult :: (Int, (Int, Int)) -> IO ()
printResult (level, (sm, cnt)) = let
avg = fromIntegral sm / fromIntegral cnt :: Float in
putStrLn $ "Level: " ++ show level ++ ". Reached: " ++ show cnt
++ " times. Average wave: " ++ show avg ++ "."
-- | choose all parameters and start or load the game
main :: IO ()
main = do
save <- catchAll (readFile saveName) $ const $ return ""
unless (null save) $ putStrLn msgAskLoad
ans <- if null save then return 'n' else do
c <- getChar
_ <- getLine
return c
_ <- initScr
(h, w) <- scrSize
_ <- endWin
if w <= 2 * xSight + 42 || h <= 2 * ySight + 5
then putStrLn msgSmallScr
else do gen <- getStdGen
putStrLn msgAskName
username <- getLine
maybeWorld <-
if ans == 'y' || ans == 'Y'
then catchAll (return $ Just $ loadWorld $ read save) $ const $ return Nothing
else do
mapgen <- showMapChoice
(char, isCheater) <- showCharChoice
writeFile logName ""
return $ Just $ initWorld mapgen char username isCheater gen
timeBegin <- getCurrentTime
case maybeWorld of
Nothing -> endWin >> putStrLn msgLoadErr
Just world ->
initScr >> initCurses >> startColor >> initColors >>
keypad stdScr True >> echo False >>
cursSet CursorInvisible >>
catchAll (do
(exit, newWorld) <- loop world
endWin
timeEnd <- getCurrentTime
putStr $ msgByExit exit ++ "\nTime in game: " ++
renderSecs (round $ diffUTCTime timeEnd timeBegin) ++
"\n"
if cheater newWorld
then putStr $ msgCheater ++ "\n"
else case exit of
ExitSave -> return ()
ExitQuit _ lvl -> do
putStr $ "Level: " ++ show lvl ++ "\n"
addResult newWorld
Die _ lvl -> do
putStr $ "Level: " ++ show lvl ++ "\n"
addResult newWorld
)
(\e -> endWin >> putStrLn (msgGameErr ++ show e))
|
green-orange/trapHack
|
src/Main.hs
|
unlicense
| 5,308 | 58 | 27 | 1,220 | 1,907 | 961 | 946 | 138 | 8 |
module Main where
import Data.Char
import SIL
--import SIL.Llvm
import SIL.Parser
import SIL.RunTime
import SIL.TypeChecker (typeCheck, inferType)
import SIL.Optimizer
import SIL.Eval
import qualified System.IO.Strict as Strict
main = do
preludeFile <- Strict.readFile "Prelude.sil"
let
prelude = case parsePrelude preludeFile of
Right p -> p
Left pe -> error $ show pe
testMethod n s = case resolveBinding n <$> parseWithPrelude prelude s of
Right (Just iexpr) -> simpleEval iexpr >>= \r -> print (PrettyIExpr r)
x -> print x
runMain s = case parseMain prelude s of
Left e -> putStrLn $ concat ["failed to parse ", s, " ", show e]
Right g -> evalLoop g
--testData = Twiddle $ Pair (Pair (Pair Zero Zero) Zero) (Pair Zero Zero)
--testData = PRight $ Pair (Pair (Pair Zero Zero) Zero) (Pair Zero Zero)
--testData = SetEnv $ Pair (Defer $ Pair Zero Env) Zero
testData = ite (Pair Zero Zero) (Pair (Pair Zero Zero) Zero) (Pair Zero (Pair Zero Zero))
--print $ makeModule testData
{-
runJIT (makeModule testData) >>= \result -> case result of
Left err -> putStrLn $ concat ["JIT error: ", err]
Right mod -> putStrLn "JIT seemed to finish ok"
-}
-- printBindingTypes prelude
Strict.readFile "tictactoe.sil" >>= runMain
--runMain "main = #x -> 0"
--runMain "main = #x -> if x then 0 else {\"Test message\", 0}"
--runMain "main = #x -> if listEqual (left x) \"quit\" then 0 else {\"type quit to exit\", 1}"
|
sfultong/stand-in-language
|
app/Main.hs
|
apache-2.0
| 1,497 | 0 | 17 | 335 | 317 | 164 | 153 | 23 | 4 |
{-# LANGUAGE UndecidableInstances #-}
--import Data.Fix as Fix
{-data Expr = Const' Int
| Add' Expr Expr
| Mul' Expr Expr deriving (Show)
-}
data ExprF a = Const Int
| Add a a
| Mul a a deriving (Show)
type Expr = Fix ExprF
newtype Fix f = In ( f (Fix f))
instance Show (f (Fix f)) => Show (Fix f) where
show (In i) = "(In $ " ++ show i ++ ")"
val :: Fix ExprF
val = In (Const 12)
testExpr = In $ (In $ (In $ Const 2) `Add`
(In $ Const 3)) `Mul` (In $ Const 4)
-- Altnrnatively use {-# LANGUAGE DeriveFunctor #-}, see falgebra_01.hs
instance Functor ExprF where
fmap _ (Const i) = Const i
fmap eval' (left `Add` right) = (eval' left) `Add` (eval' right)
fmap eval' (left `Mul` right) = (eval' left) `Mul` (eval' right)
{-
alg :: ExprF Int -> Int
alg (Const i) = i
alg (x `Add` y) = x + y
alg (x `Mul` y) = x * y
pretty :: ExprF String -> String
pretty (Const i) = show i
pretty (x `Add` y) = "(" ++ x ++ " + " ++ y ++ ")"
pretty (x `Mul` y) = "(" ++ x ++ " * " ++ y ++ ")"
-}
type Algebra f a = f a -> a
type SimpleA = Algebra ExprF Int
type StringA = Algebra ExprF String
type ExprInitAlg = Algebra ExprF (Fix ExprF)
alg :: SimpleA
alg (Const i) = i
alg (x `Add` y) = x + y
alg (x `Mul` y) = x * y
pretty :: StringA
pretty (Const i) = show i
pretty (x `Add` y) = "(" ++ x ++ " + " ++ y ++ ")"
pretty (x `Mul` y) = "(" ++ x ++ " * " ++ y ++ ")"
testExpr' = (Const 3) `Mul` (Const 4)
ex_init_alg :: ExprF (Fix ExprF) -> Fix ExprF
ex_init_alg = In
-- k = fmap alg
unFix :: Fix f -> f (Fix f)
unFix (In x) = x
cata :: Functor f => (f a -> a) -> Fix f -> a
cata alg = alg. fmap (cata alg) . unFix
cata' alg e= alg ( fmap (cata' alg) ( unFix e))
eval :: Fix ExprF -> Int
eval = alg . fmap eval . unFix
-- ListF algebra
data ListF a b = Nil | Cons a b deriving (Show)
instance Functor (ListF a) where
fmap f Nil = Nil
fmap f (Cons e x) = Cons e (f x)
algSum :: ListF Int Int -> Int
algSum Nil = 0
algSum (Cons e acc) = e + acc
lst :: Fix (ListF Int)
lst = In $ Cons 2 (In $ Cons 3 (In $ Cons 4 (In Nil)))
expr = Add (In $ Const 2) (In $ Const 3)
main = do
print "123"
print $ fmap alg testExpr'
print $ eval $ testExpr
print $ cata pretty $ testExpr
print $ cata algSum lst
print expr
print $ In expr
|
egaburov/funstuff
|
Haskell/dsl_fold/falgebra.hs
|
apache-2.0
| 2,313 | 21 | 13 | 633 | 1,091 | 524 | 567 | -1 | -1 |
-- Copyright (c) 2013-2014 PivotCloud, Inc.
--
-- Aws.DynamoDb.Streams.Commands.DescribeStream
--
-- Please feel free to contact us at [email protected] with any
-- contributions, additions, or other feedback; we would love to hear from
-- you.
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may
-- not use this file except in compliance with the License. You may obtain a
-- copy of the License at http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-- License for the specific language governing permissions and limitations
-- under the License.
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UnicodeSyntax #-}
-- |
-- Copyright: Copyright (c) 2013-2014 PivotCloud, Inc.
-- License: Apache-2.0
--
module Aws.DynamoDb.Streams.Commands.DescribeStream
( -- * Request
DescribeStream(..)
, describeStream
-- ** Lenses
, dstExclusiveStartShardId
, dstLimit
, dstStreamArn
-- * Response
, DescribeStreamResponse(..)
-- ** Lenses
, dstrStreamDescription
) where
import Aws.Core
import Aws.General (Arn)
import Aws.DynamoDb.Streams.Core
import Aws.DynamoDb.Streams.Types
import Control.Applicative
import Control.Applicative.Unicode
import Data.Aeson
import Data.Typeable
import Prelude.Unicode
data DescribeStream
= DescribeStream
{ _dstExclusiveStartShardId ∷ !(Maybe ShardId)
-- ^ The shard id of the first item this operation will evalute; see also
-- '_sdLastEvaluatedShardId'.
, _dstLimit ∷ !(Maybe Int)
-- ^ The maximum number of shard objects to return.
, _dstStreamArn ∷ !Arn
-- ^ The ARN of the stream to be described.
} deriving (Eq, Ord, Show, Read, Typeable)
-- | A basic 'DescribeStream' request for a given stream id.
--
-- @
-- myRequest =
-- 'describeStream' myStream
-- & 'dstLimit' ?~ 3
-- @
--
describeStream
∷ Arn
→ DescribeStream
describeStream streamArn = DescribeStream
{ _dstExclusiveStartShardId = Nothing
, _dstLimit = Nothing
, _dstStreamArn = streamArn
}
instance ToJSON DescribeStream where
toJSON DescribeStream{..} = object
[ "ExclusiveStartShardId" .= _dstExclusiveStartShardId
, "Limit" .= _dstLimit
, "StreamArn".= _dstStreamArn
]
instance FromJSON DescribeStream where
parseJSON =
withObject "DescribeStream" $ \o →
pure DescribeStream
⊛ o .:? "ExclusiveStartShardId"
⊛ o .:? "Limit"
⊛ o .: "StreamArn"
-- | A lens for '_dstExclusiveStartShardId'.
--
-- @
-- 'dstExclusiveStartShardId' ∷ Lens' 'DescribeStream' ('Maybe' 'ShardId')
-- @
--
dstExclusiveStartShardId
∷ Functor f
⇒ (Maybe ShardId → f (Maybe ShardId))
→ DescribeStream
→ f DescribeStream
dstExclusiveStartShardId i DescribeStream{..} =
(\_dstExclusiveStartShardId → DescribeStream{..})
<$> i _dstExclusiveStartShardId
{-# INLINE dstExclusiveStartShardId #-}
-- | A lens for '_dstLimit'.
--
-- @
-- 'dstLimit' ∷ Lens' 'DescribeStream' ('Maybe' 'Int')
-- @
--
dstLimit
∷ Functor f
⇒ (Maybe Int → f (Maybe Int))
→ DescribeStream
→ f DescribeStream
dstLimit i DescribeStream{..} =
(\_dstLimit → DescribeStream{..})
<$> i _dstLimit
{-# INLINE dstLimit #-}
-- | A lens for '_dstStreamArn'.
--
-- @
-- 'dstStreamArn' ∷ Lens' 'DescribeStream' 'StreamArn'
-- @
--
dstStreamArn
∷ Functor f
⇒ (Arn → f Arn)
→ DescribeStream
→ f DescribeStream
dstStreamArn i DescribeStream{..} =
(\_dstStreamArn → DescribeStream{..})
<$> i _dstStreamArn
{-# INLINE dstStreamArn #-}
data DescribeStreamResponse
= DescribeStreamResponse
{ _dstrStreamDescription ∷ !StreamDescription
} deriving (Eq, Ord, Show, Read, Typeable)
instance ToJSON DescribeStreamResponse where
toJSON DescribeStreamResponse{..} = object
[ "StreamDescription" .= _dstrStreamDescription
]
instance FromJSON DescribeStreamResponse where
parseJSON =
withObject "DescribeStreamResponse" $ \o →
DescribeStreamResponse
<$> o .: "StreamDescription"
-- | A lens for '_dstrStreamDescription'.
--
-- @
-- 'dstrStreamDescription' ∷ Lens' 'DescribeStreamResponse' 'StreamDescription'
-- @
--
dstrStreamDescription
∷ Functor f
⇒ (StreamDescription → f StreamDescription)
→ DescribeStreamResponse
→ f DescribeStreamResponse
dstrStreamDescription i DescribeStreamResponse{..} =
(\_dstrStreamDescription → DescribeStreamResponse{..})
<$> i _dstrStreamDescription
{-# INLINE dstrStreamDescription #-}
instance ResponseConsumer r DescribeStreamResponse where
type ResponseMetadata DescribeStreamResponse = StreamsMetadata
responseConsumer _ = streamsResponseConsumer
instance SignQuery DescribeStream where
type ServiceConfiguration DescribeStream = StreamsConfiguration
signQuery cmd = streamsSignQuery StreamsQuery
{ _stqAction = ActionDescribeStream
, _stqBody = encode cmd
}
instance Transaction DescribeStream DescribeStreamResponse
instance AsMemoryResponse DescribeStreamResponse where
type MemoryResponse DescribeStreamResponse = DescribeStreamResponse
loadToMemory = return
instance ListResponse DescribeStreamResponse Shard where
listResponse = _sdShards ∘ _dstrStreamDescription
instance IteratedTransaction DescribeStream DescribeStreamResponse where
nextIteratedRequest req@DescribeStream{..} DescribeStreamResponse{..} = do
let StreamDescription{..} = _dstrStreamDescription
lastEvaluatedShardId ← _sdLastEvaluatedShardId
return req
{ _dstExclusiveStartShardId = Just lastEvaluatedShardId
}
|
jonsterling/hs-aws-dynamodb-streams
|
src/Aws/DynamoDb/Streams/Commands/DescribeStream.hs
|
apache-2.0
| 5,907 | 0 | 14 | 969 | 962 | 544 | 418 | 126 | 1 |
module Test where
triple :: Integer -> Integer
triple x = x * 3
x = 7
y = 10
f = x + y
-- Intermission: Exercises
half x = x / 2
square x = x * x
piSquare x = 3.14 * square x
|
logistark/haskellbookexercises
|
2- Hello, Haskell/test.hs
|
apache-2.0
| 178 | 0 | 6 | 50 | 84 | 45 | 39 | 9 | 1 |
-----------------------------------------------------------------------------
--
-- Module : AI.Network.RNN
-- Copyright : (c) JP Moresmau
-- License : BSD3
--
-- Maintainer : JP Moresmau <[email protected]>
-- Stability : experimental
-- Portability :
--
-- | Library API
--
-----------------------------------------------------------------------------
module AI.Network.RNN
( RNNEval (..)
, RNNDimensions(..)
, RNNetwork
, evalSteps
, totalDataLength
, randNetwork
, createNetwork
, createNetworkFromArray
, networkToArray
, createNetworkFromVector
, networkDimensions
, cost
, LSTMNetwork
, lstmFullSize
, LSTMIO
, LSTMList
, lstmioFullSize
, lstmList
, learnGradientDescent
, learnGradientDescentSym
, learnRMSProp
, textToTrainData
, dataToText
, generate
, textToTrainDataS
, dataToTextS
, generateS
, RNNData(..)
, buildNetworkData
, stopf
, mutateNetwork
, TrainData(..)
, listMProd
) where
import AI.Network.RNN.Data
import AI.Network.RNN.Genetic
import AI.Network.RNN.LSTM
import AI.Network.RNN.RNN
import AI.Network.RNN.Types
import AI.Network.RNN.Util
|
JPMoresmau/rnn
|
src/AI/Network/RNN.hs
|
bsd-2-clause
| 1,133 | 0 | 5 | 192 | 179 | 127 | 52 | 40 | 0 |
module NLP.LTAG.Early4.Test3 where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (void)
import qualified Data.IntMap as I
import qualified Data.Set as S
import Data.List (sortBy)
import Data.Ord (comparing)
import NLP.LTAG.Tree (AuxTree(AuxTree), Tree(FNode, INode))
import NLP.LTAG.Early4
alpha :: Tree String String
alpha = INode "S"
[ FNode "p"
, INode "X"
[FNode "e"]
, FNode "q" ]
beta1 :: AuxTree String String
beta1 = AuxTree (INode "X"
[ FNode "a"
, INode "X"
[ INode "X" []
, FNode "a" ] ]
) [1,0]
beta2 :: AuxTree String String
beta2 = AuxTree (INode "X"
[ FNode "b"
, INode "X"
[ INode "X" []
, FNode "b" ] ]
) [1,0]
testGram :: [String] -> IO ()
testGram sent = do
void $ earley gram sent
-- mapM_ print $ S.toList gram
where
gram = S.fromList $ snd $ runRM $ do
mapM_ (treeRules True) [alpha]
mapM_ (auxRules True) [beta1, beta2]
|
kawu/ltag
|
src/NLP/LTAG/Early4/Test3.hs
|
bsd-2-clause
| 1,038 | 0 | 12 | 326 | 371 | 206 | 165 | 35 | 1 |
{- |
Module : Data.Set.Range.Modify
Description : Basic functions to modify the contents of a range set.
Copyright : (c) 2017 Daniel Lovasko
License : BSD2
Maintainer : Daniel Lovasko <[email protected]>
Stability : stable
Portability : portable
-}
module Data.Set.Range.Modify
( insertPoint
, insertRange
, removePoint
, removeRange
) where
import Data.Set.Range.Combine
import Data.Set.Range.Types
-- | Insert a single point into the range set.
insertPoint :: (Ord a, Enum a)
=> a -- ^ point
-> RangeSet a -- ^ old range set
-> RangeSet a -- ^ new range set
insertPoint p = union [(p,p)]
-- | Insert a range into the range set.
insertRange :: (Ord a, Enum a)
=> (a,a) -- ^ range
-> RangeSet a -- ^ old range set
-> RangeSet a -- ^ new range set
insertRange r = union [r]
-- | Remove a single point from the range set.
removePoint :: (Ord a, Enum a)
=> a
-> RangeSet a
-> RangeSet a
removePoint p = flip difference [(p,p)]
-- | Remove a range from the range set.
removeRange :: (Ord a, Enum a)
=> (a,a)
-> RangeSet a
-> RangeSet a
removeRange r = flip difference [r]
|
lovasko/rset
|
src/Data/Set/Range/Modify.hs
|
bsd-2-clause
| 1,135 | 0 | 8 | 256 | 267 | 150 | 117 | 27 | 1 |
import Driver
import Control.Monad
import System.Environment
import Text.Printf
import Orthogonal( tests_Orthogonal )
main :: IO ()
main = do
args <- getArgs
let n = if null args then 100 else read (head args)
printf "\nRunnings tests for field `%s'\n" field
(results, passed) <- liftM unzip $
foldM ( \prev (name,subtests) -> do
printf "\n%s\n" name
printf "%s\n" $ replicate (length name) '-'
cur <- mapM (\(s,a) -> printf "%-30s: " s >> a n) subtests
return (prev ++ cur)
)
[]
tests
printf "\nPassed %d tests!\n\n" (sum passed)
when (not . and $ results) $ fail "\nNot all tests passed!"
where
tests = [ ("Orthogonal Decompositions", tests_Orthogonal)
] :: [(String, [(String, Int -> IO (Bool, Int))])]
|
patperry/lapack
|
tests/Main.hs
|
bsd-3-clause
| 911 | 1 | 19 | 322 | 308 | 154 | 154 | 22 | 2 |
{-# LANGUAGE TypeFamilies, ConstraintKinds #-}
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE UndecidableInstances #-} -- see below
{-# OPTIONS_GHC -Wall #-}
-- {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP
-- {-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP
----------------------------------------------------------------------
-- |
-- Module : Control.ConstraintKinds.Category
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Category class with associated constraint
-- Copied & tweaked from Control.Category in base
----------------------------------------------------------------------
module Control.ConstraintKinds.Category
( Category(..) -- ,(<<<),(>>>)
, CategoryConstraint0
, CategoryProduct(..)
) where
-- TODO: explicit exports
import Prelude hiding (id,(.))
import qualified Prelude
import GHC.Prim (Constraint)
infixr 9 .
-- infixr 1 >>>, <<<
-- | A class for categories.
-- id and (.) must form a monoid.
class Category cat where
type CategoryConstraint cat a b :: Constraint
-- type CategoryConstraint cat a b = CategoryConstraint0 cat a b
type CategoryConstraint cat a b = CategoryConstraint0 cat a b
-- | the identity morphism
id :: CategoryConstraint cat a a =>
cat a a
-- | morphism composition
(.) :: (CategoryConstraint cat a b, CategoryConstraint cat b c) =>
cat b c -> cat a b -> cat a c
-- Workaround for problem with empty default associated constraints.
class CategoryConstraint0 (cat :: * -> * -> *) a b
instance CategoryConstraint0 cat a b
type CC cat a b = CategoryConstraint cat a b
{-# RULES
"identity/left" forall p .
id . p = p
"identity/right" forall p .
p . id = p
-- "association" forall p q r .
-- (p . q) . r = p . (q . r)
#-}
instance Category (->) where
id = Prelude.id
-- #ifndef __HADDOCK__
-- Haddock 1.x cannot parse this:
(.) = (Prelude..)
-- #endif
{-
-- | Right-to-left composition
(<<<) :: (Category cat, CC cat a, CC cat b, CC cat c) =>
cat b c -> cat a b -> cat a c
(<<<) = (.)
-- | Left-to-right composition
(>>>) :: (Category cat, CC cat a, CC cat b, CC cat c) =>
cat a b -> cat b c -> cat a c
(>>>) = flip (<<<)
-}
infixr 3 ***
infixr 3 &&&
class Category cat => CategoryProduct cat where
type CP12 cat a b c :: Constraint
type CP12 cat a b c = CC cat a (b,c)
type CP22 cat a b c d :: Constraint
type CP22 cat a b c d = CC cat (a,b) (c,d)
(***) :: (CC cat a c, CC cat b d, CP22 cat a b c d) =>
cat a c -> cat b d -> cat (a,b) (c,d)
(&&&) :: (CC cat a c, CC cat a d, CP12 cat a c d) =>
cat a c -> cat a d -> cat a (c,d)
first :: (CC cat a c, CC cat b b, CP22 cat a b c b) =>
cat a c -> cat (a,b) (c,b)
first = (*** id)
second :: (CC cat b d, CC cat a a, CP22 cat a b a d) =>
cat b d -> cat (a,b) (a,d)
second = (id ***)
-- Application is no smaller than the instance head
-- in the type family application: CategoryConstraint cat a (b, c)
-- (Use -XUndecidableInstances to permit this)
-- In the class declaration for `CategoryProduct'
--
-- Application is no smaller than the instance head
-- in the type family application: CategoryConstraint
-- cat (a, b) (c, d)
-- (Use -XUndecidableInstances to permit this)
-- In the class declaration for `CategoryProduct'
instance CategoryProduct (->) where
(f *** g) ~(x,y) = (f x, g y)
f &&& g = (f *** g) . (\ x -> (x,x))
-- TODO: Perhaps add dup, fst, snd
|
conal/linear-map-gadt
|
src/Control/ConstraintKinds/Category.hs
|
bsd-3-clause
| 3,684 | 2 | 11 | 960 | 797 | 461 | 336 | -1 | -1 |
{-# LANGUAGE TemplateHaskell, FlexibleInstances #-}
import System.IO.Unsafe (unsafePerformIO)
import Test.QuickCheck
import Test.QuickCheck.Monadic
import Test.Framework
import Test.Framework.TH
import Test.Framework.Providers.QuickCheck2
import Crypto.Paillier
instance Show (IO (PubKey, PrvKey)) where
show a = show (unsafePerformIO a)
instance Arbitrary (IO (PubKey, PrvKey)) where
arbitrary = do
nBits <- frequency [(2,return 512), (1,return 1024)]
return $ genKey nBits
prop_fixed_plaintext :: IO (PubKey, PrvKey) -> Property
prop_fixed_plaintext keys = monadicIO $ do
(pub, prv) <- run keys
let plaintext = 37
ciphertext <- run $ encrypt pub plaintext
let plaintext' = decrypt prv pub ciphertext
assert $ plaintext == plaintext'
main :: IO ()
main = $(defaultMainGenerator)
|
onemouth/HsPaillier
|
test/TestMain.hs
|
bsd-3-clause
| 835 | 1 | 12 | 155 | 281 | 143 | 138 | 23 | 1 |
{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, GADTs, TypeFamilies #-}
module Test.Hspec.LeanCheck
( prop
, forAll
, suchThat
) where
import Control.Exception
import Data.Bifunctor (first)
import Data.List (intercalate)
import Data.Maybe
import Data.String (String)
import Data.Typeable
import GHC.Stack
import Test.Hspec
import Test.Hspec.Core.Spec as Hspec
import qualified Test.HUnit.Lang as HUnit
import Test.LeanCheck.Core
data Property where
Property :: IOTestable prop => prop -> Property
-- | Perform an enumerative test of a property using LeanCheck.
--
-- 'prop' will typically be a function of one or more 'Listable' arguments, returning either 'Bool' or 'IO ()' (in the latter case, typically via 'shouldBe' and friends). For example:
--
-- > describe "+" $ do
-- > prop "associativity" $
-- > \ a b c -> a + (b + c) `shouldBe` (a + b :: Int) + c
prop :: (HasCallStack, IOTestable prop) => String -> prop -> Spec
prop s = it s . Property
data ForAll a where
ForAll :: IOTestable prop => [[a]] -> (a -> prop) -> ForAll a
-- | Test a property given by an explicit list of tiers rather than a 'Listable' instance. This can be used to e.g. filter input values for which the property does not hold.
--
-- > describe "mean" $ do
-- > prop "≥ the minimum" . forAll (not . null `filterT` tiers) $
-- > \ list -> (mean list :: Int) `shouldSatisfy` (>= min list)
forAll :: IOTestable prop => [[a]] -> (a -> prop) -> ForAll a
forAll = ForAll
instance Example Property where
type Arg Property = ()
evaluateExample (Property prop) (Params _ bound) _ _ = do
result <- try (iocounterExample bound prop)
case result of
Left e
| Just (LeanCheckException messages e') <- fromException e -> throw (addMessages messages e')
| otherwise -> throw e
Right (Just messages) -> pure $ Failure Nothing (Reason (concat messages))
Right Nothing -> pure Success
where addMessages messages (HUnit.HUnitFailure loc r) = HUnit.HUnitFailure loc $ case r of
HUnit.Reason s -> HUnit.Reason (intercalate "\n" messages ++ s)
HUnit.ExpectedButGot Nothing expected actual -> HUnit.ExpectedButGot (Just (concat messages)) expected actual
HUnit.ExpectedButGot (Just preface) expected actual -> HUnit.ExpectedButGot (Just (intercalate "\n" messages ++ preface)) expected actual
class IOTestable t where
-- 'resultiers', lifted into 'IO'.
ioResultTiers :: t -> [[IO ([String], Bool)]]
instance IOTestable (IO ()) where
ioResultTiers action = [[ (action >> pure ([], True)) `catch` (throw . LeanCheckException []) ]]
instance (IOTestable b, Show a, Listable a) => IOTestable (a -> b) where
ioResultTiers p = concatMapT (resultiersFor p) tiers
instance IOTestable Bool where
ioResultTiers p = [[ pure ([], p) ]]
instance Show a => IOTestable (ForAll a) where
ioResultTiers (ForAll tiers property) = concatMapT (resultiersFor property) tiers
resultiersFor :: (IOTestable b, Show a) => (a -> b) -> a -> [[IO ([String], Bool)]]
resultiersFor p x = fmap (eval x) <$> ioResultTiers (p x)
eval :: Show a => a -> IO ([String], Bool) -> IO ([String], Bool)
eval x action = first (prepend x) <$> action
`catch` \ (LeanCheckException messages failure) -> throw (LeanCheckException (prepend x messages) failure)
where prepend x = (showsPrec 11 x "":)
-- | 'counterExamples', lifted into 'IO'.
iocounterExamples :: IOTestable a => Int -> a -> IO [[String]]
iocounterExamples n = fmap (fmap fst . filter (not . snd)) . sequenceA . take n . concat . ioResultTiers
-- | 'counterExample', lifted into 'IO'.
iocounterExample :: IOTestable a => Int -> a -> IO (Maybe [String])
iocounterExample n = fmap listToMaybe . iocounterExamples n
data LeanCheckException = LeanCheckException [String] HUnit.HUnitFailure
deriving (Show, Typeable)
instance Exception LeanCheckException
|
robrix/surface
|
test/Test/Hspec/LeanCheck.hs
|
bsd-3-clause
| 3,871 | 0 | 17 | 734 | 1,191 | 624 | 567 | -1 | -1 |
{-# OPTIONS -fno-warn-missing-signatures #-}
----------------------------------------------------------------------------
--
-- Module : HXML.LLParsing
-- Copyright : (C) 2000-2002 Joe English. Freely redistributable.
-- License : "MIT-style"
--
-- Author : Joe English <[email protected]>
-- Stability : experimental
-- Portability : portable (wants rank-2 polymorphism but can live without it)
--
-- CVS : $Id: LLParsing.hs,v 1.6 2002/10/12 01:58:57 joe Exp $
--
----------------------------------------------------------------------------
--
-- 20 Jan 2000
-- Simple, non-backtracking, no-lookahead parser combinators.
-- Use with caution!
--
module LLParsing
( pTest , pCheck , pSym , pSucceed
,(<|>),(<*>),(<$>),(<^>),(<$),(<*),(*>),(<?>),(<**>)
, pMaybe , pFoldr , pList , pSome , pChainr , pChainl, pTry
, pRun
) where
import Prelude hiding ((<$), (<$>), (<*>), (<*), (*>), (<**>))
infixl 3 <|>
infixl 4 <*>, <$>, <^>, <?>, <$, <*, *>, <**>
{- <H98> -}
-- Use this for Haskell 98:
newtype P p = P p
{- </H98> -}
{- <H98EXT> -}
{-
-- Use this if the system supports rank-2 polymorphism:
newtype Parser sym res = P (forall a .
(res -> [sym] -> a) -- ok continuation
-> ([sym] -> a) -- failure continuation
-> ([sym] -> a) -- error continuation
-> [sym] -- input
-> a) -- result
pTest :: (a -> Bool) -> Parser a a
pCheck :: (a -> Maybe b) -> Parser a b
pSym :: (Eq a) => a -> Parser a a
pSucceed:: b -> Parser a b
(<|>) :: Parser a b -> Parser a b -> Parser a b -- union
(<*>) :: Parser a (b->c) -> Parser a b -> Parser a c -- sequence
(<$>) :: (b->c) -> Parser a b -> Parser a c -- application
(<$ ) :: c -> Parser a b -> Parser a c -- application, dropr
(<^>) :: Parser a b -> Parser a c -> Parser a (b,c) -- sequence
(<* ) :: Parser a b -> Parser a c -> Parser a b -- sequence, dropr
( *>) :: Parser a b -> Parser a c -> Parser a c -- sequence, dropl
(<?>) :: Parser a b -> b -> Parser a b -- optional
(<**>) :: Parser s b -> Parser s (b->a) -> Parser s a -- postfix application
pMaybe :: Parser s a -> Parser s (Maybe a)
pFoldr :: (a->b->b) -> b -> Parser s a -> Parser s b
pList :: Parser a b -> Parser a [b]
pSome :: Parser a b -> Parser a [b]
pChainr :: Parser a (b -> b -> b) -> Parser a b -> Parser a b
pChainl :: Parser a (b -> b -> b) -> Parser a b -> Parser a b
pRun :: Parser a b -> [a] -> Maybe (b,[a])
-}
{- </H98EXT> -}
pTest pred = P (ptest pred)
where
ptest _p _o f _e [] = f []
ptest p ok f _e l@(c:cs)
| p c = ok c cs
| otherwise = f l
pSym a = pTest (a==)
pCheck cmf = P (pcheck cmf) where
pcheck _mf _ok f _e [] = f []
pcheck mf ok f _e cs@(c:s) = case (mf c) of
Just x -> ok x s
Nothing -> f cs
pTry (P pa) = P (\ok f _e i -> pa ok f (\ _i' -> f i) i)
pSucceed a = P (\ok _f _e -> ok a)
(P pa) <|> (P pb) = P (\ok f e -> pa ok (pb ok f e) e)
(P pa) <*> (P pb) = P (\ok f e -> pa (\a -> pb (ok . a) e e) f e)
(P pa) <?> a = P (\ok _f -> pa ok (ok a))
(P pa) <^> (P pb) = P (\ok f e -> pa (\a->pb(\b->ok (a,b)) e e) f e)
f <$> (P pb) = P (\ok -> pb (ok . f))
f <$ (P pb) = P (\ok -> pb (ok . const f))
pa <* pb = curry fst <$> pa <*> pb
pa *> pb = curry snd <$> pa <*> pb
pa <**> pb = (\x f -> f x) <$> pa <*> pb
pMaybe p = Just <$> p <|> pSucceed Nothing
pFoldr op e p = loop where loop = (op <$> p <*> loop) <?> e
pList = pFoldr (:) []
pSome p = (:) <$> p <*> pList p
pChainr op p = loop
where loop = p <**> ((flip <$> op <*> loop) <?> id)
pChainl op p = foldl ap <$> p <*> pList (flip <$> op <*> p)
where ap x f = f x
pRun (P p) = p just2 fail fail where
just2 x y = Just (x,y)
fail = const Nothing
-- EOF --
|
pepeiborra/xml-bench
|
hxml-0.2/LLParsing.hs
|
bsd-3-clause
| 3,739 | 56 | 15 | 987 | 1,150 | 623 | 527 | 43 | 3 |
module Network.DNS.Cache.Utils where
import qualified Data.ByteString.Char8 as BS
import Data.Char (isDigit)
import Network.DNS.Cache.Types
isIPAddr :: Domain -> Bool
isIPAddr hn = length groups == 4 && all ip groups
where
groups = BS.split '.' hn
ip x = BS.length x <= 3
&& BS.all isDigit x
&& read (BS.unpack x) <= (255 :: Int)
fromResult :: Result -> HostAddress
fromResult (Hit addr) = addr
fromResult (Resolved addr) = addr
fromResult (Numeric addr) = addr
fromEither :: Either DNSError Result -> Maybe HostAddress
fromEither (Right res) = Just (fromResult res)
fromEither (Left _) = Nothing
|
kazu-yamamoto/concurrent-dns-cache
|
Network/DNS/Cache/Utils.hs
|
bsd-3-clause
| 636 | 0 | 12 | 133 | 239 | 125 | 114 | 17 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module SlashRedirect where
import Nero
import Nero.Application (slashRedirect)
app :: Request -> Maybe Response
app request = request ^? _GET
>>= slashRedirect (prefixed "/hello/" . suffixed "/")
(\name -> ok $ "<h1>Hello " <> name <> "</h1>")
|
plutonbrb/nero-examples
|
examples/SlashRedirect.hs
|
bsd-3-clause
| 319 | 0 | 11 | 81 | 84 | 45 | 39 | 8 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module: $HEADER$
-- Description: Type proxies for Data.Monoid module.
-- Copyright: (c) 2015, Peter Trško
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: experimental
-- Portability: NoImplicitPrelude
--
-- Type proxies for "Data.Monoid" module.
module Data.Proxy.Monoid
( aMonoid
-- * All and Any
, anAll
, anAny
-- * Dual
, aDual
, aDualOf
, dualOf
-- * Endo
, anEndo
, anEndoOf
, endoOf
, appEndoTo
, runEndoOn
-- * First
, aFirst
, aFirstOf
, firstOf
-- * Last
, aLast
, aLastOf
, lastOf
-- * Product
, aProduct
, aProductOf
, productOf
-- * Sum
, aSum
, aSumOf
, sumOf
)
where
import Data.Function (flip)
import Data.Maybe (Maybe)
import Data.Monoid
( All
, Any
, Dual(Dual)
, Endo(Endo, appEndo)
, First(First)
, Last(Last)
, Monoid
, Product(Product)
, Sum(Sum)
)
import Data.Proxy (Proxy(Proxy))
aMonoid :: Monoid a => Proxy a
aMonoid = Proxy
{-# INLINE aMonoid #-}
-- {{{ All and Any ------------------------------------------------------------
-- | Type proxy for 'All' data type.
anAll :: Proxy All
anAll = Proxy
{-# INLINE anAll #-}
-- | Type proxy for 'Any' data type.
anAny :: Proxy Any
anAny = Proxy
{-# INLINE anAny #-}
-- }}} All and Any ------------------------------------------------------------
-- {{{ Dual -------------------------------------------------------------------
-- | Type proxy for 'Dual' data type.
aDual :: Proxy (Dual a)
aDual = Proxy
{-# INLINE aDual #-}
-- | Restricted type proxy for 'Dual' data type.
aDualOf :: Proxy a -> Proxy (Dual a)
aDualOf Proxy = Proxy
{-# INLINE aDualOf #-}
-- | Constructor of 'Dual' parameterised by a type proxy of a value.
--
-- @
-- 'dualOf' 'aMonoid' :: 'Monoid' a => a -> 'Dual' a
-- ('Dual' .) . 'endoOf' :: 'Proxy' a -> (a -> a) -> 'Dual' ('Endo' a)
-- @
dualOf :: Proxy a -> a -> Dual a
dualOf Proxy = Dual
{-# INLINE dualOf #-}
-- }}} Dual -------------------------------------------------------------------
-- {{{ Endo -------------------------------------------------------------------
-- | Proxy for 'Endo' data type.
anEndo :: Proxy (Endo a)
anEndo = Proxy
{-# INLINE anEndo #-}
-- | Proxy for 'Endo' data type that restrict the type endo operates on.
anEndoOf :: Proxy a -> Proxy (Endo a)
anEndoOf Proxy = Proxy
{-# INLINE anEndoOf #-}
-- | Constructor of 'Endo' parameterised by a type proxy of a value.
endoOf :: Proxy a -> (a -> a) -> Endo a
endoOf Proxy = Endo
{-# INLINE endoOf #-}
-- | Type restricted version of 'appEndo'.
appEndoTo :: Proxy a -> Endo a -> a -> a
appEndoTo Proxy = appEndo
{-# INLINE appEndoTo #-}
-- | Type restricted version of flipped 'appEndo'.
runEndoOn :: Proxy a -> a -> Endo a -> a
runEndoOn Proxy = flip appEndo
{-# INLINE runEndoOn #-}
-- }}} Endo -------------------------------------------------------------------
-- {{{ First ------------------------------------------------------------------
aFirst :: Proxy (First a)
aFirst = Proxy
{-# INLINE aFirst #-}
aFirstOf :: Proxy a -> Proxy (First a)
aFirstOf Proxy = Proxy
{-# INLINE aFirstOf #-}
-- | Constructor of 'First' parameterised by a type proxy of a value.
firstOf :: Proxy a -> Maybe a -> First a
firstOf Proxy = First
{-# INLINE firstOf #-}
-- }}} First ------------------------------------------------------------------
-- {{{ Last -------------------------------------------------------------------
aLast :: Proxy (Last a)
aLast = Proxy
{-# INLINE aLast #-}
aLastOf :: Proxy a -> Proxy (Last a)
aLastOf Proxy = Proxy
{-# INLINE aLastOf #-}
-- | Constructor of 'Last' parameterised by a type proxy of a value.
lastOf :: Proxy a -> Maybe a -> Last a
lastOf Proxy = Last
{-# INLINE lastOf #-}
-- }}} Last -------------------------------------------------------------------
-- {{{ Product ----------------------------------------------------------------
aProduct :: Proxy (Product a)
aProduct = Proxy
{-# INLINE aProduct #-}
aProductOf :: Proxy a -> Proxy (Product a)
aProductOf Proxy = Proxy
{-# INLINE aProductOf #-}
-- | Constructor of 'Product' parameterised by a type proxy of a value.
--
-- @
-- 'productOf' 'aMonoid' :: 'Monoid' a => a -> 'Product' a
-- @
productOf :: Proxy a -> a -> Product a
productOf Proxy = Product
{-# INLINE productOf #-}
-- }}} Product ----------------------------------------------------------------
-- {{{ Sum --------------------------------------------------------------------
aSum :: Proxy (Sum a)
aSum = Proxy
{-# INLINE aSum #-}
aSumOf :: Proxy a -> Proxy (Sum a)
aSumOf Proxy = Proxy
{-# INLINE aSumOf #-}
-- | Constructor of 'Sum' parameterised by a type proxy of a value.
--
-- @
-- 'sumOf' 'aMonoid' :: 'Monoid' a => a -> 'Sum' a
-- @
sumOf :: Proxy a -> a -> Sum a
sumOf Proxy = Sum
{-# INLINE sumOf #-}
-- }}} Sum --------------------------------------------------------------------
|
trskop/type-proxies
|
src/Data/Proxy/Monoid.hs
|
bsd-3-clause
| 5,002 | 0 | 8 | 999 | 829 | 481 | 348 | 107 | 1 |
-- This is where you can change the default config path & other build-in defaults.
module Constants where
configPrefix = "config/"
-- Here's for a system program:
-- configPrefix = "/etc/progname/config/"
|
athanclark/optionz
|
src/Constants.hs
|
bsd-3-clause
| 208 | 0 | 4 | 34 | 12 | 9 | 3 | 2 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Render.Fast.Model where
import Control.Lens ((.=), (+=), preuse, ix, (^.), zoom, use, (%=), Traversal', _1, _2)
import Control.Monad (when, liftM)
import Data.Binary.IEEE754 (wordToFloat)
import Data.Bits ((.|.), (.&.), shiftL, shiftR)
import Data.Int (Int8, Int32)
import Data.IORef (IORef, newIORef, readIORef, writeIORef, modifyIORef')
import Data.Maybe (isNothing, fromJust, isJust)
import Data.Monoid ((<>), mempty)
import Data.Word (Word8, Word16, Word32)
import Linear (V3(..), V4(..), norm, _x, _y, _z, dot)
import qualified Data.ByteString as B
import qualified Data.ByteString.Builder as BB
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as BL
import qualified Data.Vector as V
import qualified Data.Vector.Storable.Mutable as MSV
import qualified Data.Vector.Unboxed as UV
import Text.Printf (printf)
import Game.CVarT
import QCommon.LumpT
import QCommon.QFiles.SP2.DSprFrameT
import Types
import Game.CPlaneT
import QuakeState
import QCommon.QFiles.BSP.DFaceT
import QCommon.QFiles.BSP.DHeaderT
import QCommon.QFiles.BSP.DLeafT
import QCommon.QFiles.BSP.DModelT
import QCommon.QFiles.BSP.DNodeT
import QCommon.QFiles.BSP.DPlaneT
import QCommon.QFiles.MD2.DAliasFrameT
import QCommon.QFiles.MD2.DMdlT
import QCommon.QFiles.MD2.DSTVertT
import QCommon.QFiles.MD2.DTriangleT
import QCommon.QFiles.SP2.DSpriteT
import QCommon.TexInfoT
import QCommon.XCommandT
import Util.Binary
import qualified Constants
import qualified Client.VID as VID
import qualified QCommon.Com as Com
import qualified QCommon.CVar as CVar
import {-# SOURCE #-} qualified QCommon.FS as FS
import qualified Render.Fast.Image as Image
import qualified Render.Fast.Polygon as Polygon
import {-# SOURCE #-} qualified Render.Fast.Surf as Surf
import qualified Render.Fast.Warp as Warp
import qualified Render.RenderAPIConstants as RenderAPIConstants
import qualified Util.Lib as Lib
modelListF :: XCommandT
modelListF =
XCommandT "Model.modelListF" (do
io (putStrLn "Model.modelListF") >> undefined -- TODO
)
modInit :: Quake ()
modInit = do
-- init mod_known
models <- io $ V.replicateM maxModKnown (newIORef newModelT)
fastRenderAPIGlobals.frModKnown .= models
fastRenderAPIGlobals.frModNoVis .= B.replicate (Constants.maxMapLeafs `div` 8) 0xFF
rBeginRegistration :: B.ByteString -> Quake ()
rBeginRegistration model = do
resetModelArrays
Polygon.reset
fastRenderAPIGlobals.frRegistrationSequence += 1
fastRenderAPIGlobals.frOldViewCluster .= (-1) -- force markleafs
let fullName = "maps/" `B.append` model `B.append` ".bsp"
-- explicitly free the old map if different
-- this guarantees that mod_known[0] is the world map
Just flushMap <- CVar.get "flushmap" "0" 0
Just modelRef <- preuse $ fastRenderAPIGlobals.frModKnown.ix 0
model <- io $ readIORef modelRef
let currentName = model^.mName
when (currentName /= fullName || (flushMap^.cvValue) /= 0) $
modFree modelRef
modelRef <- modForName fullName True
fastRenderAPIGlobals.frWorldModel .= modelRef
fastRenderAPIGlobals.frViewCluster .= (-1)
modFree :: IORef ModelT -> Quake ()
modFree modelRef = io $ writeIORef modelRef newModelT
resetModelArrays :: Quake ()
resetModelArrays = do
zoom (fastRenderAPIGlobals) $ do
frModelTextureCoordIdx .= 0
frModelVertexIndexIdx .= 0
{-
==================
Mod_ForName
Loads in a model for the given name
==================
-}
modForName :: B.ByteString -> Bool -> Quake (Maybe (IORef ModelT))
modForName name crash = do
when (B.null name) $
Com.comError Constants.errDrop "Mod_ForName: NULL name"
-- inline models are grabbed only from worldmodel
if name `BC.index` 0 == '*'
then do
worldModelRef <- use $ fastRenderAPIGlobals.frWorldModel
let i = Lib.atoi (B.drop 1 name)
err <- if i < 1 || isNothing worldModelRef
then return True
else do
worldModel <- io $ readIORef (fromJust worldModelRef)
return $ if i >= (worldModel^.mNumSubModels)
then True
else False
when err $ Com.comError Constants.errDrop "bad inline model number"
preuse $ fastRenderAPIGlobals.frModInline.ix i
else do
-- search the currently loaded models
modNumKnown <- use $ fastRenderAPIGlobals.frModNumKnown
modKnown <- use $ fastRenderAPIGlobals.frModKnown
foundRef <- findWithSameName modKnown 0 modNumKnown
case foundRef of
Just ref -> return (Just ref)
Nothing -> do
-- find a free model slot spot
emptySpot <- findEmptySpot modKnown 0 modNumKnown
emptySpotRef <- case emptySpot of
Just ref -> return ref
Nothing -> do
when (modNumKnown == maxModKnown) $
Com.comError Constants.errDrop "mod_numknown == MAX_MOD_KNOWN"
fastRenderAPIGlobals.frModNumKnown += 1
return (modKnown V.! modNumKnown)
io $ modifyIORef' emptySpotRef (\v -> v { _mName = name })
-- load the file
fileBuffer <- FS.loadFile name
case fileBuffer of
Nothing -> do
when crash $
Com.comError Constants.errDrop ("Mod_NumForName: " `B.append` name `B.append` " not found\n")
io $ modifyIORef' emptySpotRef (\v -> v { _mName = "" })
return Nothing
Just buffer -> do
fastRenderAPIGlobals.frLoadModel .= emptySpotRef
-- fill it in
-- call the apropriate loader
let header = B.take 4 buffer
if | header == idAliasHeader -> loadAliasModel emptySpotRef buffer
| header == idSpriteHeader -> loadSpriteModel emptySpotRef buffer
| header == idBSPHeader -> loadBrushModel emptySpotRef buffer
| otherwise -> Com.comError Constants.errDrop ("Mod_NumForName: unknown fileid for " `B.append` name)
return $ Just emptySpotRef
where findWithSameName :: V.Vector (IORef ModelT) -> Int -> Int -> Quake (Maybe (IORef ModelT))
findWithSameName modKnown idx maxIdx
| idx >= maxIdx = return Nothing
| otherwise = do
model <- io $ readIORef (modKnown V.! idx)
if (model^.mName) == name
then return $ Just (modKnown V.! idx)
else findWithSameName modKnown (idx + 1) maxIdx
findEmptySpot :: V.Vector (IORef ModelT) -> Int -> Int -> Quake (Maybe (IORef ModelT))
findEmptySpot modKnown idx maxIdx
| idx >= maxIdx = return Nothing
| otherwise = do
model <- io $ readIORef (modKnown V.! idx)
if B.null (model^.mName)
then return $ Just (modKnown V.! idx)
else findEmptySpot modKnown (idx + 1) maxIdx
loadAliasModel :: IORef ModelT -> B.ByteString -> Quake ()
loadAliasModel modelRef buffer = do
let lazyBuffer = BL.fromStrict buffer
pheader = newDMdlT lazyBuffer
model <- io $ readIORef modelRef
checkForErrors pheader (model^.mName)
-- load base s and t vertices (not used in gl version)
let pOutST = runGet (V.replicateM (pheader^.dmNumST) getDSTVertT) (BL.drop (fromIntegral $ pheader^.dmOfsST) lazyBuffer)
-- load triangle lists
let pOutTri = runGet (V.replicateM (pheader^.dmNumTris) getDTriangleT) (BL.drop (fromIntegral $ pheader^.dmOfsTris) lazyBuffer)
-- load the frames
let pOutFrame = runGet (V.replicateM (pheader^.dmNumFrames) (getDAliasFrameT (pheader^.dmNumXYZ))) (BL.drop (fromIntegral $ pheader^.dmOfsFrames) lazyBuffer)
-- load the glcmds
let pOutCmd = runGet (UV.replicateM (pheader^.dmNumGlCmds) getWord32le) (BL.drop (fromIntegral $ pheader^.dmOfsGlCmds) lazyBuffer)
-- register all skins
let skinNames = V.map (B.takeWhile (/= 0)) $ runGet (V.replicateM (pheader^.dmNumSkins) (getByteString Constants.maxSkinName)) (BL.drop (fromIntegral $ pheader^.dmOfsSkins) lazyBuffer)
skins <- V.mapM (\name -> Image.glFindImage name RenderAPIConstants.itSkin) skinNames
let pheader' = pheader { _dmSkinNames = Just skinNames
, _dmSTVerts = Just pOutST
, _dmTriAngles = Just pOutTri
, _dmGlCmds = Just pOutCmd
, _dmAliasFrames = Just pOutFrame
}
pheader'' <- precompileGLCmds pheader'
io $ modifyIORef' modelRef (\v -> v { _mType = RenderAPIConstants.modAlias
, _mExtraData = Just (AliasModelExtra pheader'')
, _mMins = V3 (-32) (-32) (-32)
, _mMaxs = V3 32 32 32
, _mSkins = skins
})
where checkForErrors :: DMdlT -> B.ByteString -> Quake ()
checkForErrors pheader modelName = do
when ((pheader^.dmVersion) /= Constants.aliasVersion) $
Com.comError Constants.errDrop (modelName `B.append` " has wrong version number (" `B.append` BC.pack (show (pheader^.dmVersion)) `B.append` " should be " `B.append` BC.pack (show Constants.aliasVersion) `B.append` ")") -- IMPROVE ?
when ((pheader^.dmSkinHeight) > RenderAPIConstants.maxLBMHeight) $
Com.comError Constants.errDrop ("model " `B.append` modelName `B.append` " has a skin taller than " `B.append` BC.pack (show RenderAPIConstants.maxLBMHeight))
when ((pheader^.dmNumXYZ) <= 0) $
Com.comError Constants.errDrop ("model " `B.append` modelName `B.append` " has no vertices")
when ((pheader^.dmNumXYZ) > Constants.maxVerts) $
Com.comError Constants.errDrop ("model " `B.append` modelName `B.append` " has too many vertices")
when ((pheader^.dmNumST) <= 0) $
Com.comError Constants.errDrop ("model " `B.append` modelName `B.append` " has no st vertices")
when ((pheader^.dmNumTris) <= 0) $
Com.comError Constants.errDrop ("model " `B.append` modelName `B.append` " has no triangles")
when ((pheader^.dmNumFrames) <= 0) $
Com.comError Constants.errDrop ("model " `B.append` modelName `B.append` " has no frames")
loadSpriteModel :: IORef ModelT -> B.ByteString -> Quake ()
loadSpriteModel modelRef buffer = do
let sprOut = newDSpriteT (BL.fromStrict buffer)
when ((sprOut^.dsVersion) /= spriteVersion) $ do
model <- io $ readIORef modelRef
Com.comError Constants.errDrop ((model^.mName) `B.append` " has wrong version number (" `B.append` BC.pack (show $ sprOut^.dsVersion) `B.append` " should be " `B.append` BC.pack (show spriteVersion) `B.append` ")") -- IMPROVE?
when ((sprOut^.dsNumFrames) > Constants.maxMd2Skins) $ do
model <- io $ readIORef modelRef
Com.comError Constants.errDrop ((model^.mName) `B.append` " has too many frames (" `B.append` BC.pack (show $ sprOut^.dsNumFrames) `B.append` " > " `B.append` BC.pack (show Constants.maxMd2Skins) `B.append` ")") -- IMPROVE?
skins <- V.mapM (\frame -> Image.glFindImage (frame^.dsfName) RenderAPIConstants.itSprite) (sprOut^.dsFrames)
io $ modifyIORef' modelRef (\v -> v { _mSkins = skins
, _mType = RenderAPIConstants.modSprite
, _mExtraData = Just (SpriteModelExtra sprOut)
})
loadBrushModel :: IORef ModelT -> B.ByteString -> Quake ()
loadBrushModel modelRef buffer = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
io $ modifyIORef' loadModelRef (\v -> v { _mType = RenderAPIConstants.modBrush })
Just modKnown0 <- preuse $ fastRenderAPIGlobals.frModKnown.ix 0
when (loadModelRef /= modKnown0) $
Com.comError Constants.errDrop "Loaded a brush model after the world"
let header = newDHeaderT (BL.fromStrict buffer)
when ((header^.dhVersion) /= Constants.bspVersion) $ do
model <- io $ readIORef modelRef
Com.comError Constants.errDrop ("Mod_LoadBrushModel: " `B.append` (model^.mName) `B.append` " has wrong version number (" `B.append` BC.pack (show (header^.dhVersion)) `B.append` " should be " `B.append` BC.pack (show Constants.bspVersion) `B.append` ")")
-- load into heap
loadVertexes buffer ((header^.dhLumps) V.! Constants.lumpVertexes)
loadEdges buffer ((header^.dhLumps) V.! Constants.lumpEdges)
loadSurfEdges buffer ((header^.dhLumps) V.! Constants.lumpSurfEdges)
loadLighting buffer ((header^.dhLumps) V.! Constants.lumpLighting)
loadPlanes buffer ((header^.dhLumps) V.! Constants.lumpPlanes)
loadTexInfo buffer ((header^.dhLumps) V.! Constants.lumpTexInfo)
loadFaces buffer ((header^.dhLumps) V.! Constants.lumpFaces)
loadMarkSurfaces buffer ((header^.dhLumps) V.! Constants.lumpLeafFaces)
loadVisibility buffer ((header^.dhLumps) V.! Constants.lumpVisibility)
loadLeafs buffer ((header^.dhLumps) V.! Constants.lumpLeafs)
loadNodes buffer ((header^.dhLumps) V.! Constants.lumpNodes)
loadSubmodels buffer ((header^.dhLumps) V.! Constants.lumpModels)
io $ modifyIORef' modelRef (\v -> v { _mNumFrames = 2 }) -- regular and alternate animation
-- set up the submodels
model <- io $ readIORef modelRef
setupSubmodels model 0 (model^.mNumSubModels)
where setupSubmodels :: ModelT -> Int -> Int -> Quake ()
setupSubmodels model idx maxIdx
| idx >= maxIdx = return ()
| otherwise = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
bm <- io $ readIORef $ (model^.mSubModels) V.! idx
loadModel <- io $ readIORef loadModelRef
starModRef <- io $ newIORef loadModel
fastRenderAPIGlobals.frModInline.ix idx .= starModRef
io $ modifyIORef' starModRef (\v -> v { _mFirstModelSurface = bm^.mmFirstFace
, _mNumModelSurfaces = bm^.mmNumFaces
, _mFirstNode = bm^.mmHeadNode
, _mMaxs = bm^.mmMaxs
, _mMins = bm^.mmMins
, _mRadius = bm^.mmRadius
})
when ((bm^.mmHeadNode) >= (loadModel^.mNumNodes)) $
Com.comError Constants.errDrop ("Inline model " `B.append` BC.pack (show idx) `B.append` " has bad firstnode") -- IMPROVE?
when (idx == 0) $ do
starMod <- io $ readIORef starModRef
loadModelRef' <- io $ newIORef starMod
fastRenderAPIGlobals.frLoadModel .= loadModelRef'
io $ modifyIORef' starModRef (\v -> v { _mNumLeafs = bm^.mmVisLeafs })
setupSubmodels model (idx + 1) maxIdx
loadVertexes :: B.ByteString -> LumpT -> Quake ()
loadVertexes buffer lump = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
when ((lump^.lFileLen) `mod` mVertexDiskSize /= 0) $ do
model <- io $ readIORef loadModelRef
Com.comError Constants.errDrop ("MOD_LoadBmodel: funny lump size in " `B.append` (model^.mName))
let count = (lump^.lFileLen) `div` mVertexDiskSize
buf = BL.fromStrict $ B.take (lump^.lFileLen) (B.drop (lump^.lFileOfs) buffer)
vertexes = runGet (getVertexes count) buf
vertexes' <- io $ V.mapM newIORef vertexes
io $ modifyIORef' loadModelRef (\v -> v { _mNumVertexes = count
, _mVertexes = vertexes'
})
where getVertexes :: Int -> Get (V.Vector MVertexT)
getVertexes count = V.replicateM count getMVertexT
loadEdges :: B.ByteString -> LumpT -> Quake ()
loadEdges buffer lump = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
when ((lump^.lFileLen) `mod` mEdgeDiskSize /= 0) $ do
model <- io $ readIORef loadModelRef
Com.comError Constants.errDrop ("MOD_LoadBmodel: funny lump size in " `B.append` (model^.mName))
let count = (lump^.lFileLen) `div` mEdgeDiskSize
buf = BL.fromStrict $ B.take (lump^.lFileLen) (B.drop (lump^.lFileOfs) buffer)
edges = runGet (getEdges count) buf
edges' <- io $ V.mapM newIORef edges
io $ modifyIORef' loadModelRef (\v -> v { _mNumEdges = count
, _mEdges = edges'
})
where getEdges :: Int -> Get (V.Vector MEdgeT)
getEdges count = V.replicateM count getMEdgeT
loadSurfEdges :: B.ByteString -> LumpT -> Quake ()
loadSurfEdges buffer lump = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
when ((lump^.lFileLen) `mod` Constants.sizeOfInt /= 0) $ do
model <- io $ readIORef loadModelRef
Com.comError Constants.errDrop ("MOD_LoadBmodel: funny lump size in " `B.append` (model^.mName))
let count = (lump^.lFileLen) `div` Constants.sizeOfInt
when (count < 1 || count >= Constants.maxMapSurfEdges) $ do
model <- io $ readIORef loadModelRef
Com.comError Constants.errDrop ("MOD_LoadBmodel bad surfedges count in " `B.append` (model^.mName) `B.append` ": " `B.append` BC.pack (show count)) -- IMPROVE?
let buf = BL.fromStrict $ B.take (lump^.lFileLen) (B.drop (lump^.lFileOfs) buffer)
offsets = runGet (getOffsets count) buf
io $ modifyIORef' loadModelRef (\v -> v { _mNumSurfEdges = count
, _mSurfEdges = offsets
})
where getOffsets :: Int -> Get (V.Vector Int)
getOffsets count = V.replicateM count getInt
loadLighting :: B.ByteString -> LumpT -> Quake ()
loadLighting buffer lump = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
let lightData = if (lump^.lFileLen) == 0
then Nothing
else Just (B.take (lump^.lFileLen) (B.drop (lump^.lFileOfs) buffer))
io $ modifyIORef' loadModelRef (\v -> v { _mLightdata = lightData })
loadPlanes :: B.ByteString -> LumpT -> Quake ()
loadPlanes buffer lump = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
when ((lump^.lFileLen) `mod` dPlaneTSize /= 0) $ do
model <- io $ readIORef loadModelRef
Com.comError Constants.errDrop ("MOD_LoadBmodel: funny lump size in " `B.append` (model^.mName))
let count = (lump^.lFileLen) `div` dPlaneTSize
buf = BL.fromStrict $ B.take (lump^.lFileLen) (B.drop (lump^.lFileOfs) buffer)
dplanes = runGet (getDPlanes count) buf
planes <- io $ V.mapM toCPlane dplanes
io $ modifyIORef' loadModelRef (\v -> v { _mNumPlanes = count
, _mPlanes = planes
})
where getDPlanes :: Int -> Get (V.Vector DPlaneT)
getDPlanes count = V.replicateM count getDPlaneT
toCPlane :: DPlaneT -> IO (IORef CPlaneT)
toCPlane dPlaneT = newIORef CPlaneT { _cpNormal = dPlaneT^.dpNormal
, _cpDist = dPlaneT^.dpDist
, _cpType = fromIntegral (dPlaneT^.dpType)
, _cpSignBits = flagBits (dPlaneT^.dpNormal)
, _cpPad = (0, 0)
}
flagBits :: V3 Float -> Int8
flagBits (V3 a b c) =
let a' :: Int8 = if a < 0 then 1 `shiftL` 0 else 0
b' :: Int8 = if b < 0 then 1 `shiftL` 1 else 0
c' :: Int8 = if c < 0 then 1 `shiftL` 2 else 0
in a' .|. b' .|. c'
loadTexInfo :: B.ByteString -> LumpT -> Quake ()
loadTexInfo buffer lump = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
when ((lump^.lFileLen) `mod` texInfoTSize /= 0) $ do
model <- io $ readIORef loadModelRef
Com.comError Constants.errDrop ("MOD_LoadBmodel: funny lump size in " `B.append` (model^.mName))
let count = (lump^.lFileLen) `div` texInfoTSize
buf = BL.fromStrict $ B.take (lump^.lFileLen) (B.drop (lump^.lFileOfs) buffer)
texInfoT = runGet (getTexInfo count) buf
mti <- io $ V.replicateM count (newIORef undefined)
io $ modifyIORef' loadModelRef (\v -> v { _mNumTexInfo = count
, _mTexInfo = mti
})
model <- io $ readIORef loadModelRef
V.imapM_ (toMTexInfoT model) texInfoT
countAnimationFrames model 0 count
where getTexInfo :: Int -> Get (V.Vector TexInfoT)
getTexInfo count = V.replicateM count getTexInfoT
toMTexInfoT :: ModelT -> Int -> TexInfoT -> Quake ()
toMTexInfoT model idx texInfoT = do
let name = "textures/" `B.append` (texInfoT^.tiTexture) `B.append` ".wal"
foundImage <- Image.glFindImage name RenderAPIConstants.itWall
imgRef <- case foundImage of
Just ref -> return ref
Nothing -> do
VID.printf Constants.printAll ("Couldn't load " `B.append` name `B.append` "\n")
use $ fastRenderAPIGlobals.frNoTexture
let mTexInfoRef = (model^.mTexInfo) V.! idx
io $ writeIORef mTexInfoRef MTexInfoT { _mtiVecs = texInfoT^.tiVecs
, _mtiFlags = texInfoT^.tiFlags
, _mtiNumFrames = 1
, _mtiNext = if (texInfoT^.tiNextTexInfo) > 0 then Just ((model^.mTexInfo) V.! (texInfoT^.tiNextTexInfo)) else Nothing
, _mtiImage = Just imgRef
}
countAnimationFrames :: ModelT -> Int -> Int -> Quake ()
countAnimationFrames model idx maxIdx
| idx >= maxIdx = return ()
| otherwise = do
let mTexInfoRef = (model^.mTexInfo) V.! idx
texInfo <- io $ readIORef mTexInfoRef
num <- countFrames mTexInfoRef (texInfo^.mtiNext) 1
io $ modifyIORef' mTexInfoRef (\v -> v { _mtiNumFrames = num })
countAnimationFrames model (idx + 1) maxIdx
countFrames :: IORef MTexInfoT -> Maybe (IORef MTexInfoT) -> Int -> Quake Int
countFrames _ Nothing n = return n
countFrames initial (Just current) n = do
if current == initial
then return n
else do
texInfo <- io $ readIORef current
countFrames initial (texInfo^.mtiNext) (n + 1)
loadFaces :: B.ByteString -> LumpT -> Quake ()
loadFaces buffer lump = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
when ((lump^.lFileLen) `mod` dFaceTSize /= 0) $ do
model <- io $ readIORef loadModelRef
Com.comError Constants.errDrop ("MOD_LoadBmodel: funny lump size in " `B.append` (model^.mName))
let count = (lump^.lFileLen) `div` dFaceTSize
buf = BL.fromStrict $ B.take (lump^.lFileLen) (B.drop (lump^.lFileOfs) buffer)
dFaces = runGet (getDFaces count) buf
fastRenderAPIGlobals.frCurrentModel .= Just loadModelRef
Surf.glBeginBuildingLightmaps loadModelRef
surfaces <- V.mapM toMSurfaceT dFaces
io $ modifyIORef' loadModelRef (\v -> v { _mNumSurfaces = count
, _mSurfaces = surfaces
})
Surf.glEndBuildingLightmaps
where getDFaces :: Int -> Get (V.Vector DFaceT)
getDFaces count = V.replicateM count getDFaceT
toMSurfaceT :: DFaceT -> Quake (IORef MSurfaceT)
toMSurfaceT dface = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
model <- io $ readIORef loadModelRef
let ti = fromIntegral (dface^.dfTexInfo)
when (ti < 0 || ti >= (model^.mNumTexInfo)) $
Com.comError Constants.errDrop "MOD_LoadBmodel: bad texinfo number"
let planeNum = fromIntegral (dface^.dfPlaneNum)
side = dface^.dfSide
flags = if side /= 0 then Constants.surfPlaneBack else 0
i = dface^.dfLightOfs
texInfoRef = (model^.mTexInfo) V.! ti
texInfo <- io $ readIORef texInfoRef
let texInfoFlags = texInfo^.mtiFlags
surfRef <- io $ newIORef newMSurfaceT { _msFirstEdge = dface^.dfFirstEdge
, _msNumEdges = fromIntegral (dface^.dfNumEdges)
, _msFlags = flags
, _msPolys = Nothing
, _msPlane = Just ((model^.mPlanes) V.! planeNum)
, _msTexInfo = texInfo
, _msStyles = dface^.dfStyles -- TODO: should we limit it by Constants.maxLightMaps ?
, _msSamples = if i == -1 then Nothing else Just (B.drop i (fromJust (model^.mLightdata)))
}
calcSurfaceExtents model texInfo surfRef
when (texInfoFlags .&. Constants.surfWarp /= 0) $ do
io $ modifyIORef' surfRef (\v -> v { _msFlags = flags .|. Constants.surfDrawTurb
, _msExtents = (16384, 16384)
, _msTextureMins = (-8192, -8192)
})
Warp.glSubdivideSurface surfRef
when (texInfoFlags .&. (Constants.surfSky .|. Constants.surfTrans33 .|. Constants.surfTrans66 .|. Constants.surfWarp) == 0) $
Surf.glCreateSurfaceLightmap surfRef
when (texInfoFlags .&. Constants.surfWarp == 0) $
Surf.glBuildPolygonFromSurface surfRef
return surfRef
calcSurfaceExtents :: ModelT -> MTexInfoT -> IORef MSurfaceT -> Quake ()
calcSurfaceExtents model texInfo surfRef = do
surf <- io $ readIORef surfRef
(mins, maxs) <- io $ calcMinsMaxs surf 0 (surf^.msNumEdges) (999999, 999999) (-99999, -99999)
let bmins = mapTuple (floor . (/ 16)) mins
bmaxs = mapTuple (ceiling . (/ 16)) maxs
io $ modifyIORef' surfRef (\v -> v { _msTextureMins = mapTuple (* 16) bmins
, _msExtents = mapTuple (* 16) (fst bmaxs - fst bmins, snd bmaxs - snd bmins)
})
where calcMinsMaxs :: MSurfaceT -> Int -> Int -> (Float, Float) -> (Float, Float) -> IO ((Float, Float), (Float, Float))
calcMinsMaxs surf idx maxIdx mins maxs
| idx >= maxIdx = return (mins, maxs)
| otherwise = do
let e = (model^.mSurfEdges) V.! ((surf^.msFirstEdge) + idx)
v <- if e >= 0
then do
let edgeRef = (model^.mEdges) V.! e
edge <- io $ readIORef edgeRef
let vertexRef = (model^.mVertexes) V.! (fromIntegral $ edge^.meV._1)
io $ readIORef vertexRef
else do
let edgeRef = (model^.mEdges) V.! (negate e)
edge <- io $ readIORef edgeRef
let vertexRef = (model^.mVertexes) V.! (fromIntegral $ edge^.meV._2)
io $ readIORef vertexRef
let V3 a b c = v^.mvPosition
(V4 a1 b1 c1 d1, V4 a2 b2 c2 d2) = texInfo^.mtiVecs
val1 = a * a1 + b * b1 + c * c1 + d1
val2 = a * a2 + b * b2 + c * c2 + d2
mins' = (if val1 < fst mins then val1 else fst mins, if val2 < snd mins then val2 else snd mins)
maxs' = (if val1 > fst maxs then val1 else fst maxs, if val2 > snd maxs then val2 else snd maxs)
calcMinsMaxs surf (idx + 1) maxIdx mins' maxs'
mapTuple :: (a -> b) -> (a, a) -> (b, b)
mapTuple f (a1, a2) = (f a1, f a2)
loadMarkSurfaces :: B.ByteString -> LumpT -> Quake ()
loadMarkSurfaces buffer lump = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
model <- io $ readIORef loadModelRef
when ((lump^.lFileLen) `mod` Constants.sizeOfShort /= 0) $ do
Com.comError Constants.errDrop ("MOD_LoadBmodel: funny lump size in " `B.append` (model^.mName))
let count = (lump^.lFileLen) `div` Constants.sizeOfShort
buf = BL.fromStrict $ B.take (lump^.lFileLen) (B.drop (lump^.lFileOfs) buffer)
surfaceIndexes = runGet (getSurfaceIndexes count) buf
markSurfaces <- V.mapM (toMSurfaceT model) surfaceIndexes
io $ modifyIORef' loadModelRef (\v -> v { _mNumMarkSurfaces = count
, _mMarkSurfaces = markSurfaces
})
where getSurfaceIndexes :: Int -> Get (V.Vector Word16)
getSurfaceIndexes count = V.replicateM count getWord16le
toMSurfaceT :: ModelT -> Word16 -> Quake (IORef MSurfaceT)
toMSurfaceT model idx = do
let i = fromIntegral idx
when (i < 0 || i >= (model^.mNumSurfaces)) $
Com.comError Constants.errDrop "Mod_ParseMarksurfaces: bad surface number"
return $ (model^.mSurfaces) V.! i
loadVisibility :: B.ByteString -> LumpT -> Quake ()
loadVisibility buffer lump = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
if (lump^.lFileLen) == 0
then
io $ modifyIORef' loadModelRef (\v -> v { _mVis = Nothing })
else do
let buf = B.take (lump^.lFileLen) (B.drop (lump^.lFileOfs) buffer)
buf' = BL.fromStrict buf
vis = newDVisT buf'
fastRenderAPIGlobals.frModelVisibility .= Just buf
io $ modifyIORef' loadModelRef (\v -> v { _mVis = Just vis })
loadLeafs :: B.ByteString -> LumpT -> Quake ()
loadLeafs buffer lump = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
model <- io $ readIORef loadModelRef
when ((lump^.lFileLen) `mod` dLeafTSize /= 0) $ do
Com.comError Constants.errDrop ("MOD_LoadBmodel: funny lump size in " `B.append` (model^.mName))
let count = (lump^.lFileLen) `div` dLeafTSize
buf = BL.fromStrict $ B.take (lump^.lFileLen) (B.drop (lump^.lFileOfs) buffer)
dLeafs = runGet (getDLeafs count) buf
leafs = V.map (toMLeafT model) dLeafs
leafs' <- io $ V.mapM newIORef leafs
io $ modifyIORef' loadModelRef (\v -> v { _mNumLeafs = count
, _mLeafs = leafs'
})
where getDLeafs :: Int -> Get (V.Vector DLeafT)
getDLeafs count = V.replicateM count getDLeafT
toMLeafT :: ModelT -> DLeafT -> MLeafT
toMLeafT model dLeaf = MLeafT { _mlContents = dLeaf^.dlContents
, _mlVisFrame = 0
, _mlMins = fmap fromIntegral (dLeaf^.dlMins)
, _mlMaxs = fmap fromIntegral (dLeaf^.dlMaxs)
, _mlParent = Nothing
, _mlCluster = fromIntegral (dLeaf^.dlCluster)
, _mlArea = fromIntegral (dLeaf^.dlArea)
, _mlNumMarkSurfaces = fromIntegral (dLeaf^.dlNumLeafFaces)
, _mlMarkIndex = fromIntegral (dLeaf^.dlFirstLeafFace)
}
loadNodes :: B.ByteString -> LumpT -> Quake ()
loadNodes buffer lump = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
when ((lump^.lFileLen) `mod` dNodeTSize /= 0) $ do
model <- io $ readIORef loadModelRef
Com.comError Constants.errDrop ("MOD_LoadBmodel: funny lump size in " `B.append` (model^.mName))
let count = (lump^.lFileLen) `div` dNodeTSize
buf = BL.fromStrict $ B.take (lump^.lFileLen) (B.drop (lump^.lFileOfs) buffer)
dNodes = runGet (getDNodes count) buf
nodes <- io $ V.replicateM count (newIORef undefined)
io $ modifyIORef' loadModelRef (\v -> v { _mNumNodes = count
, _mNodes = nodes
})
model <- io $ readIORef loadModelRef
V.imapM_ (toMNodeT model) dNodes
io $ setParent (MNodeChildReference $ (model^.mNodes) V.! 0) Nothing -- sets nodes and leafs
where getDNodes :: Int -> Get (V.Vector DNodeT)
getDNodes count = V.replicateM count getDNodeT
toMNodeT :: ModelT -> Int -> DNodeT -> Quake ()
toMNodeT loadModel idx dNode = do
let nodeRef = (loadModel^.mNodes) V.! idx
io $ writeIORef nodeRef MNodeT { _mnContents = (-1) -- differentiate from leafs
, _mnVisFrame = 0
, _mnMins = fmap fromIntegral (dNode^.dnMins)
, _mnMaxs = fmap fromIntegral (dNode^.dnMaxs)
, _mnParent = Nothing
, _mnPlane = (loadModel^.mPlanes) V.! (dNode^.dnPlaneNum)
, _mnChildren = getChildren loadModel (dNode^.dnChildren)
, _mnFirstSurface = fromIntegral (dNode^.dnFirstFace)
, _mnNumSurfaces = fromIntegral (dNode^.dnNumFaces)
}
getChildren :: ModelT -> (Int, Int) -> (MNodeChild, MNodeChild)
getChildren loadModel (p1, p2) =
let a = if p1 >= 0
then MNodeChildReference ((loadModel^.mNodes) V.! p1)
else MLeafChildReference ((loadModel^.mLeafs) V.! ((-1) - p1))
b = if p2 >= 0
then MNodeChildReference ((loadModel^.mNodes) V.! p2)
else MLeafChildReference ((loadModel^.mLeafs) V.! ((-1) - p2))
in (a, b)
setParent :: MNodeChild -> Maybe (IORef MNodeT) -> IO ()
setParent child parent =
case child of
MNodeChildReference nodeRef -> do
modifyIORef' nodeRef (\v -> v { _mnParent = parent })
node <- readIORef nodeRef
setParent (node^.mnChildren._1) (Just nodeRef)
setParent (node^.mnChildren._2) (Just nodeRef)
MLeafChildReference leafRef ->
modifyIORef' leafRef (\v -> v { _mlParent = parent })
loadSubmodels :: B.ByteString -> LumpT -> Quake ()
loadSubmodels buffer lump = do
loadModelRef <- use $ fastRenderAPIGlobals.frLoadModel
when ((lump^.lFileLen) `mod` dModelTSize /= 0) $ do
model <- io $ readIORef loadModelRef
Com.comError Constants.errDrop ("MOD_LoadBmodel: funny lump size in " `B.append` (model^.mName))
let count = (lump^.lFileLen) `div` dModelTSize
buf = BL.fromStrict $ B.take (lump^.lFileLen) (B.drop (lump^.lFileOfs) buffer)
dModels = runGet (getDModels count) buf
models = V.map toMModelT dModels
models' <- io $ V.mapM newIORef models
io $ modifyIORef' loadModelRef (\v -> v { _mNumSubModels = count
, _mSubModels = models'
})
where getDModels :: Int -> Get (V.Vector DModelT)
getDModels count = V.replicateM count getDModelT
toMModelT :: DModelT -> MModelT
toMModelT dModel =
-- spread the mins / maxs by a pixel
let mins = fmap (subtract 1) (dModel^.dmMins)
maxs = fmap (+1) (dModel^.dmMaxs)
in MModelT { _mmMins = mins
, _mmMaxs = maxs
, _mmOrigin = dModel^.dmOrigin
, _mmRadius = radiusFromBounds mins maxs
, _mmHeadNode = dModel^.dmHeadNode
, _mmVisLeafs = 0
, _mmFirstFace = dModel^.dmFirstFace
, _mmNumFaces = dModel^.dmNumFaces
}
radiusFromBounds :: V3 Float -> V3 Float -> Float
radiusFromBounds mins maxs =
let a = if abs (mins^._x) > abs (maxs^._x) then abs (mins^._x) else abs (maxs^._x)
b = if abs (mins^._y) > abs (maxs^._y) then abs (mins^._y) else abs (maxs^._y)
c = if abs (mins^._z) > abs (maxs^._z) then abs (mins^._z) else abs (maxs^._z)
in norm (V3 a b c)
precompileGLCmds :: DMdlT -> Quake DMdlT
precompileGLCmds model = do
textureBuf <- use $ fastRenderAPIGlobals.frModelTextureCoordBuf
vertexBuf <- use $ fastRenderAPIGlobals.frModelVertexIndexBuf
modelTextureCoordIdx <- use $ fastRenderAPIGlobals.frModelTextureCoordIdx
modelVertexIndexIdx <- use $ fastRenderAPIGlobals.frModelVertexIndexIdx
-- tmp is in reversed order, this should be taken into accounts in the
-- next calculations and assignments
(tmp, modelTextureCoordIdx', modelVertexIndexIdx') <- setTextureAndVertex textureBuf vertexBuf (fromJust $ model^.dmGlCmds) modelTextureCoordIdx modelVertexIndexIdx 0 []
let rtmp = reverse tmp
counts = UV.fromList rtmp
indexElements = collectIndexElements rtmp modelVertexIndexIdx 0 []
zoom fastRenderAPIGlobals $ do
frModelTextureCoordIdx .= modelTextureCoordIdx'
frModelVertexIndexIdx .= modelVertexIndexIdx'
return model { _dmTextureCoordBufIdx = modelTextureCoordIdx
, _dmVertexIndexBufIdx = modelVertexIndexIdx
, _dmCounts = counts
, _dmIndexElements = indexElements
}
where setTextureAndVertex :: MSV.IOVector Float -> MSV.IOVector Int32 -> UV.Vector Word32 -> Int -> Int -> Int -> [Int32] -> Quake ([Int32], Int, Int)
setTextureAndVertex textureBuf vertexBuf order textureCoordIdx vertexIndexIdx orderIndex tmp = do
let count :: Int32 = fromIntegral (order UV.! orderIndex)
if count /= 0
then do
let count' = if count < 0 then -count else count
(textureCoordIdx', vertexIndexIdx', orderIndex') <- setCoords textureBuf vertexBuf order textureCoordIdx vertexIndexIdx (orderIndex + 1) count'
setTextureAndVertex textureBuf vertexBuf order textureCoordIdx' vertexIndexIdx' orderIndex' (count : tmp)
else
return (tmp, textureCoordIdx, vertexIndexIdx)
setCoords :: MSV.IOVector Float -> MSV.IOVector Int32 -> UV.Vector Word32 -> Int -> Int -> Int -> Int32 -> Quake (Int, Int, Int)
setCoords textureBuf vertexBuf order textureCoordIdx vertexIndexIdx orderIndex count
| count <= 0 = return (textureCoordIdx, vertexIndexIdx, orderIndex)
| otherwise = do
io $ MSV.write textureBuf textureCoordIdx (wordToFloat $ order UV.! orderIndex)
io $ MSV.write textureBuf (textureCoordIdx + 1) (wordToFloat $ order UV.! (orderIndex + 1))
io $ MSV.write vertexBuf vertexIndexIdx (fromIntegral $ order UV.! (orderIndex + 2))
setCoords textureBuf vertexBuf order (textureCoordIdx + 2) (vertexIndexIdx + 1) (orderIndex + 3) (count - 1)
collectIndexElements :: [Int32] -> Int -> Int -> [(Int, Int)] -> V.Vector (Int, Int)
collectIndexElements [] _ _ acc = V.fromList (reverse acc)
collectIndexElements (x:xs) idx pos acc =
let count = fromIntegral $ if x < 0 then negate x else x
in collectIndexElements xs idx (pos + count) ((idx + pos, count) : acc)
rRegisterModel :: B.ByteString -> Quake (Maybe (IORef ModelT))
rRegisterModel name = do
modelRef <- modForName name False
when (isJust modelRef) $
registerModelImages (fromJust modelRef)
return modelRef
where registerModelImages :: IORef ModelT -> Quake ()
registerModelImages modelRef = do
model <- io $ readIORef modelRef
regSeq <- use $ fastRenderAPIGlobals.frRegistrationSequence
io $ modifyIORef' modelRef (\v -> v { _mRegistrationSequence = regSeq })
if | model^.mType == RenderAPIConstants.modSprite -> do
let Just (SpriteModelExtra sprOut) = model^.mExtraData
skins <- V.mapM (\frame -> Image.glFindImage (frame^.dsfName) RenderAPIConstants.itSprite) (sprOut^.dsFrames)
io $ modifyIORef' modelRef (\v -> v { _mSkins = skins })
| model^.mType == RenderAPIConstants.modAlias -> do
let Just (AliasModelExtra pheader) = model^.mExtraData
skins <- V.mapM (\skinName -> Image.glFindImage skinName RenderAPIConstants.itSkin) (fromJust $ pheader^.dmSkinNames)
io $ modifyIORef' modelRef (\v -> v { _mSkins = skins
, _mNumFrames = pheader^.dmNumFrames
})
| model^.mType == RenderAPIConstants.modBrush -> do
updateImageRegistrationSequence model regSeq 0 (model^.mNumTexInfo)
| otherwise -> return ()
updateImageRegistrationSequence :: ModelT -> Int -> Int -> Int -> Quake ()
updateImageRegistrationSequence model regSeq idx maxIdx
| idx >= maxIdx = return ()
| otherwise = do
texInfo <- io $ readIORef ((model^.mTexInfo) V.! idx)
io $ modifyIORef' (fromJust $ texInfo^.mtiImage) (\v -> v { _iRegistrationSequence = regSeq })
updateImageRegistrationSequence model regSeq (idx + 1) maxIdx
rEndRegistration :: Quake ()
rEndRegistration = do
modNumKnown <- use $ fastRenderAPIGlobals.frModNumKnown
modKnown <- use $ fastRenderAPIGlobals.frModKnown
regSeq <- use $ fastRenderAPIGlobals.frRegistrationSequence
checkModels modKnown regSeq 0 modNumKnown
Image.glFreeUnusedImages
where checkModels :: V.Vector (IORef ModelT) -> Int -> Int -> Int -> Quake ()
checkModels modKnown regSeq idx maxIdx
| idx >= maxIdx = return ()
| otherwise = do
model <- io $ readIORef (modKnown V.! idx)
if | B.null (model^.mName) -> return ()
| (model^.mRegistrationSequence) /= regSeq -> modFree (modKnown V.! idx)
| otherwise -> when ((model^.mType) == RenderAPIConstants.modAlias) $ do
let Just (AliasModelExtra pheader) = model^.mExtraData
pheader' <- precompileGLCmds pheader
io $ modifyIORef' (modKnown V.! idx) (\v -> v { _mExtraData = Just (AliasModelExtra pheader') })
checkModels modKnown regSeq (idx + 1) maxIdx
pointInLeaf :: V3 Float -> ModelT -> Quake MLeafT
pointInLeaf p model = do
let rootNode = MNodeChildReference ((model^.mNodes) V.! 0)
findLeaf rootNode
where findLeaf :: MNodeChild -> Quake MLeafT
findLeaf (MNodeChildReference nodeRef) = do
node <- io $ readIORef nodeRef
plane <- io $ readIORef (node^.mnPlane)
let d = p `dot` (plane^.cpNormal) - (plane^.cpDist)
childRef = if d > 0
then node^.mnChildren._1
else node^.mnChildren._2
case childRef of
MLeafChildReference leafRef -> io $ readIORef leafRef
nodeChild -> findLeaf nodeChild
clusterPVS :: Int -> ModelT -> Quake B.ByteString
clusterPVS cluster model = do
if cluster == -1 || isNothing (model^.mVis)
then
use $ fastRenderAPIGlobals.frModNoVis
else do
modelVisibility <- use $ fastRenderAPIGlobals.frModelVisibility
let vis = fromJust (model^.mVis)
-- TODO: instead of directly using _1 we should somehow use Constants.dvisPvs
return $ decompressVis modelVisibility (((vis^.dvBitOfs) V.! cluster)^._1) model
decompressVis :: Maybe B.ByteString -> Int -> ModelT -> B.ByteString
decompressVis maybeModelVisibility offset model =
let vis = fromJust (model^.mVis)
row = ((vis^.dvNumClusters) + 7) `shiftR` 3
in case maybeModelVisibility of
Nothing -> B.unfoldr (\idx -> if | idx >= Constants.maxMapLeafs `div` 8 -> Nothing
| idx < row -> Just (0xFF, idx + 1)
| otherwise -> Just (0, idx + 1)
) 0
Just modelVisibility -> buildVis modelVisibility row offset 0 mempty
where buildVis :: B.ByteString -> Int -> Int -> Int -> BB.Builder -> B.ByteString
buildVis modelVisibility row inp outp builder =
if (modelVisibility `B.index` inp) /= 0
then let builder' = builder <> BB.word8 (modelVisibility `B.index` inp)
in if outp + 1 < row
then buildVis modelVisibility row (inp + 1) (outp + 1) builder'
else let result = BL.toStrict (BB.toLazyByteString builder')
diff = Constants.maxMapLeafs `div` 8 - (B.length result)
in if diff > 0
then result `B.append` (B.replicate diff 0)
else result
else let c = modelVisibility `B.index` (inp + 1)
builder' = buildEmpty builder c
in if outp + fromIntegral c < row
then buildVis modelVisibility row (inp + 2) (outp + fromIntegral c) builder'
else let result = BL.toStrict (BB.toLazyByteString builder')
diff = Constants.maxMapLeafs `div` 8 - (B.length result)
in if diff > 0
then result `B.append` (B.replicate diff 0)
else result
buildEmpty :: BB.Builder -> Word8 -> BB.Builder
buildEmpty builder c
| c <= 0 = builder
| otherwise = buildEmpty (builder <> (BB.word8 0)) (c - 1)
freeAll :: Quake ()
freeAll = do
modNumKnown <- use $ fastRenderAPIGlobals.frModNumKnown
modKnown <- use $ fastRenderAPIGlobals.frModKnown
freeModels modKnown 0 modNumKnown
where freeModels :: V.Vector (IORef ModelT) -> Int -> Int -> Quake ()
freeModels modKnown idx maxIdx
| idx >= maxIdx = return ()
| otherwise = do
let modelRef = modKnown V.! idx
model <- io $ readIORef modelRef
case model^.mExtraData of
Nothing ->
freeModels modKnown (idx + 1) maxIdx
Just _ -> do
modFree modelRef
freeModels modKnown (idx + 1) maxIdx
|
ksaveljev/hake-2
|
src/Render/Fast/Model.hs
|
bsd-3-clause
| 47,565 | 0 | 25 | 15,294 | 14,222 | 7,317 | 6,905 | -1 | -1 |
module HsLexerPass1(module HsLexerPass1,module HsLexerPos) where
import HsLex(haskellLex)
import HsLexUtils
import HsLayoutPre(layoutPre,PosToken)
import HsLexerPos
import List(mapAccumL)
default(Int)
{-+
The function #lexerPass1# handles the part of lexical analysis that
can be done independently of the parser, i.e., the tokenization and the
addition of the extra layout tokens <n> and {n}, as specified in
section 9.3 of the revised Haskell 98 Report.
-}
type LexerOutput = [PosToken]
type Lexer = String -> LexerOutput
lexerPass1 :: Lexer
lexerPass1 = lexerPass1Only . lexerPass0
lexerPass1Only = layoutPre . rmSpace
rmSpace = filter (notWhite.fst)
notWhite t = t/=Whitespace &&
t/=Commentstart && t/=Comment &&
t/=NestedComment
-- Tokenize and add position information:
lexerPass0 :: Lexer
lexerPass0 = lexerPass0' startPos
lexerPass0' :: Pos -> Lexer
lexerPass0' pos0 = addPos . haskellLex . rmcr
where
addPos = snd . mapAccumL pos pos0
pos p (t,s) = {-seq p'-} (p',(t,(p,s)))
where p' = nextPos p s
-- where s = reverse r
{-+
Since #nextPos# examines one character at a time, it will increase the line
number by 2 if it sees \CR\LF, which can happen when reading DOS files on
a Unix like system.
Since the extra \CR characters can cause trouble later as well, we choose
to simply remove them here.
-}
rmcr ('\CR':'\LF':s) = '\LF':rmcr s
rmcr (c:s) = c:rmcr s
rmcr "" = ""
|
forste/haReFork
|
tools/base/parse2/Lexer/HsLexerPass1.hs
|
bsd-3-clause
| 1,447 | 0 | 11 | 277 | 301 | 171 | 130 | 26 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
module Data.Type.Length.Util where
import Data.Kind
import Data.Proxy
import Data.Singletons.Decide
import Data.Type.Length
import Data.Type.Nat
import Data.Type.Product hiding ((>:), append')
import Prelude hiding (init)
import Type.Class.Witness
import Type.Family.List
import Type.Family.List.Util
import Type.Family.Nat
import Type.Family.Nat.Util
import Unsafe.Coerce
import qualified Data.Type.Product as P
append'
:: Length ns
-> Length ms
-> Length (ns ++ ms)
append' = \case
LZ -> id
LS l -> LS . append' l
{-# INLINE append' #-}
infixr 5 `append'`
cons
:: Proxy a
-> Length as
-> Length (a ': as)
cons _ = LS
{-# INLINE cons #-}
tail'
:: Length (n ': ns)
-> Length ns
tail' = \case
LS l -> l
{-# INLINE tail' #-}
-- TODO: could PROBABLY just be unsafeCoerce?
reverse'
:: forall ns. ()
=> Length ns
-> Length (Reverse ns)
reverse' = unsafeCoerce
-- reverse' = \case
-- LZ -> LZ
-- LS l -> reverse' l >: (Proxy @(Head ns))
{-# INLINE reverse' #-}
-- TODO: is this ok to be unsafeCoerce?
(>:)
:: Length ns
-> Proxy n
-> Length (ns >: n)
-- (>:) l _ = unsafeCoerce $ LS l
(>:) = \case
LZ -> \_ -> LS LZ
LS l -> LS . (l >:)
{-# INLINE (>:) #-}
data SnocLength :: [a] -> Type where
SnocZ :: SnocLength '[]
SnocS :: SnocLength as -> Proxy a -> SnocLength (as >: a)
snocLengthHelp
:: forall as bs. ()
=> Length bs
-> SnocLength bs
-> Length as
-> SnocLength (bs ++ as)
snocLengthHelp lB sB = \case
LZ ->
sB \\ appendNil lB
lA@(LS lA') ->
snocLengthHelp (lB >: p lA) (SnocS sB (p lA)) lA'
\\ appendSnoc lB (p lA)
\\ appendAssoc lB (l lA) lA'
where
p :: forall c cs. Length (c ': cs) -> Proxy c
p _ = Proxy
{-# INLINE p #-}
l :: forall c cs. Length (c ': cs) -> Length '[c]
l _ = LS LZ
{-# INLINE l #-}
{-# INLINE snocLengthHelp #-}
-- | could this be unsafeCoerce?
snocLength
:: Length as
-> SnocLength as
snocLength l = snocLengthHelp LZ SnocZ l
{-# INLINE snocLength #-}
-- | could just be unsafeCoerce lol
snocLengthLength
:: SnocLength as
-> Length as
snocLengthLength = \case
SnocZ -> LZ
SnocS l s -> snocLengthLength l >: s
{-# INLINE snocLengthLength #-}
snocLengthReverse
:: SnocLength as
-> Length (Reverse as)
snocLengthReverse = \case
SnocZ -> LZ
SnocS (s :: SnocLength bs) (p :: Proxy b) ->
LS (snocLengthReverse s)
\\ snocReverse (snocLengthLength s) p
{-# INLINE snocLengthReverse #-}
-- | A @'MaxLength' n as@ is a witness that the list @as@ has a length of
-- at most @n@.
data MaxLength :: N -> [k] -> Type where
MLZ :: MaxLength n '[]
MLS :: !(MaxLength n as) -> MaxLength ('S n) (a ': as)
-- | An @'ExactLength' n as@ is a witness that the list @as@ has a length
-- of exactly @n@.
data ExactLength :: N -> [k] -> Type where
ELZ :: ExactLength 'Z '[]
ELS :: !(ExactLength n as) -> ExactLength ('S n) (a ': as)
data Splitting :: N -> ([k] -> Type) -> [k] -> Type where
Fewer
:: !(MaxLength n as)
-> !(f as)
-> Splitting n f as
Split
:: !(ExactLength n as)
-> !(f as)
-> !(f (b ': bs))
-> Splitting n f (as ++ (b ': bs))
splitting
:: Nat n
-> Prod f as
-> Splitting n (Prod f) as
splitting = \case
Z_ -> \case
Ø -> Fewer MLZ Ø
x :< xs -> Split ELZ Ø (x :< xs)
S_ n -> \case
Ø -> Fewer MLZ Ø
x :< xs -> case splitting n xs of
Fewer m xs' -> Fewer (MLS m) (x :< xs')
Split e xs' ys -> Split (ELS e) (x :< xs') ys
{-# INLINE splitting #-}
maxLength
:: Nat n
-> Length as
-> Decision (MaxLength n as)
maxLength = \case
Z_ -> \case
LZ -> Proved MLZ
LS _ -> Disproved (\case)
S_ n -> \case
LZ -> Proved MLZ
LS l -> case maxLength n l of
Proved m -> Proved (MLS m)
Disproved r -> Disproved $ \case
MLS m -> r m
{-# INLINE maxLength #-}
exactLength
:: Nat n
-> Length as
-> Decision (ExactLength n as)
exactLength = \case
Z_ -> \case
LZ -> Proved ELZ
LS _ -> Disproved (\case)
S_ n -> \case
LZ -> Disproved (\case)
LS l -> case exactLength n l of
Proved e -> Proved (ELS e)
Disproved r -> Disproved $ \case
ELS e -> r e
{-# INLINE exactLength #-}
fromMaxLength
:: MaxLength n as
-> Length as
fromMaxLength = \case
MLZ -> LZ
MLS m -> LS (fromMaxLength m)
{-# INLINE fromMaxLength #-}
fromExactLength
:: ExactLength n as
-> Length as
fromExactLength = \case
ELZ -> LZ
ELS m -> LS (fromExactLength m)
{-# INLINE fromExactLength #-}
weakenExactLength
:: ExactLength n as
-> MaxLength n as
weakenExactLength = \case
ELZ -> MLZ
ELS e -> MLS (weakenExactLength e)
{-# INLINE weakenExactLength #-}
weakenMaxLength
:: (n :<=: m)
-> MaxLength n as
-> MaxLength m as
weakenMaxLength = \case
LTEZ -> \case
MLZ -> MLZ
LTES l -> \case
MLZ -> MLZ
MLS s -> MLS (weakenMaxLength l s)
{-# INLINE weakenMaxLength #-}
data SplittingEnd :: N -> ([k] -> Type) -> [k] -> Type where
FewerEnd
:: !(MaxLength n as)
-> !(f as)
-> SplittingEnd n f as
SplitEnd
:: !(ExactLength n as)
-> !(f (b ': bs))
-> !(f as)
-> SplittingEnd n f ((b ': bs) ++ as)
-- | Pretty sure this is O(n^2) but what can you do you know
splittingEnd
:: Nat n
-> Prod f as
-> SplittingEnd n (Prod f) as
splittingEnd n xs = case splitting n xs of
Fewer m xs' -> FewerEnd m xs'
Split _ _ _ -> case xs of
Ø -> FewerEnd MLZ Ø
y :< ys -> case splittingEnd n ys of
FewerEnd m zs -> case consMaxLength n m of
Left e -> SplitEnd e (y :< Ø ) zs
Right m' -> FewerEnd m' (y :< zs)
SplitEnd e ys' zs -> SplitEnd e (y :< ys') zs
{-# INLINE splittingEnd #-}
consMaxLength
:: Nat n
-> MaxLength n as
-> Either (ExactLength n as) (MaxLength n (a ': as))
consMaxLength = \case
Z_ -> \case
MLZ -> Left ELZ
S_ n -> \case
MLZ -> Right (MLS MLZ)
MLS m -> case consMaxLength n m of
Left e -> Left (ELS e)
Right m' -> Right (MLS m')
{-# INLINE consMaxLength #-}
commuteProd
:: Length as
-> Length cs
-> Prod f (as ++ cs)
-> Prod f bs
-> (Prod f as, Prod f (cs ++ bs))
commuteProd = \case
LZ -> \_ xs ys -> (Ø, xs `P.append'` ys)
LS lA -> \lC -> \case
x :< xs -> \ys ->
case commuteProd lA lC xs ys of
(xs', ys') -> (x :< xs', ys')
{-# INLINE commuteProd #-}
lengthProd
:: Length as
-> Prod Proxy as
lengthProd = \case
LZ -> Ø
LS l -> Proxy :< lengthProd l
{-# INLINE lengthProd #-}
|
mstksg/tensor-ops
|
src/Data/Type/Length/Util.hs
|
bsd-3-clause
| 7,365 | 0 | 19 | 2,407 | 2,594 | 1,327 | 1,267 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Pronunciations
import qualified Data.Text as T
import qualified Data.Text.IO as T
import System.IO
import System.Environment
import System.Directory
import Control.Applicative
import Control.Monad
import Data.Functor
import Data.List
import Control.Monad.Loops
import qualified Data.Set as Set
import Prelude hiding (Word)
-- TODO: Make more UNIX-y, by talking to stderr, being more silent (take an --interactive flag?)
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
args <- getArgs
case args of
dictFileName : [] -> do
fileExists <- doesFileExist dictFileName
if fileExists
then do
putStrLn "Reading dictionary file ..."
maybeDict <- entries <$> T.readFile dictFileName
case maybeDict of
Just dictEntries ->
let !dict = pronunciations dictEntries
in do putStr "> "
whileM_ (not <$> isEOF) $ do
text <- T.toUpper . T.pack <$> getLine
case homophonesUsing dict (Word text) of
Nothing -> return ()
Just results ->
mapM_ (T.putStrLn . T.toLower . getWord) $ Set.toList results
putStr "> "
Nothing -> putStrLn $ "Failed to parse dictionary file: " ++ dictFileName
else putStrLn $ "Dictionary file does not exist: " ++ dictFileName
[] -> putStrLn "Too few arguments; please specify a single dictionary file"
_ -> putStrLn "Too many arguments; please specify a single dictionary file"
|
bitemyapp/pronunciations
|
app/Main.hs
|
bsd-3-clause
| 1,804 | 0 | 33 | 630 | 364 | 184 | 180 | 42 | 6 |
-----------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
-- |
-- | Module : Export library modules
-- | Author : Xiao Ling
-- | Date : 8/10/2016
-- |
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
module Lib (
module Parsers
, module Conduits
, module Preprocess
, module PatternCompiler
) where
import Parsers
import Conduits
import Preprocess
import PatternCompiler
|
lingxiao/GoodGreatIntensity
|
lib/Lib.hs
|
bsd-3-clause
| 709 | 0 | 4 | 93 | 43 | 33 | 10 | 9 | 0 |
module PTEstruturado.Data where
{-
modulo que contem a definicação das estruturas da Linguagem de programação
-}
data Variavel = Variavel {nome::String, tipo::Tipo} deriving (Show)
data Tipo = Inteiro
| Fracionario
| Logico
deriving (Eq)
instance Show Tipo where
show Inteiro = "int"
show Fracionario = "real"
show Logico = "logico"
data Expr = Arit ExpArit
| Logica ExpLogica
| Nada
deriving (Show)
data ExpLogica = VarLogica String
| ConsLogica Bool
| Negacao ExpLogica
| LogicoBin OpLogico ExpLogica ExpLogica
| RelacianalBin OpRelacional ExpArit ExpArit
deriving (Show)
data OpLogico = E | Ou deriving (Show)
data OpRelacional = Maior
| MaiorIgual
| Menor
| MenorIgual
| Igual
| Diferente
deriving (Show)
data ExpArit = VarArit String
| ConsArit (Either Integer Double)
| Neg ExpArit
| AritBin OpArit ExpArit ExpArit
deriving (Show)
data OpArit = Soma
| Subt
| Divi
| Mult
| Rest
deriving (Show)
data Instr = Seq [Instr]
| Atrib String Expr
| Se ExpLogica Instr Instr
| Enquanto ExpLogica Instr
| Escreva String Expr
| Ler String String
deriving (Show)
data Algoritimo = Algoritimo String [Variavel] Instr
deriving (Show)
|
dsvictor94/pt-estruturado
|
PTEstruturado/Data.hs
|
bsd-3-clause
| 1,661 | 0 | 8 | 711 | 349 | 202 | 147 | 48 | 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.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.GA.Corpus
( corpus
) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Numeral.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale GA Nothing}, testOptions, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (NumeralValue 0)
[ "0"
, "a náid"
]
, examples (NumeralValue 1)
[ "1"
, "aon"
, "a haon"
, "Amháin"
]
, examples (NumeralValue 20)
[ "20"
, "Fiche"
]
, examples (NumeralValue 30)
[ "déag is fiche"
]
, examples (NumeralValue 40)
[ "is dha fhichead"
, "is dá fhichead"
]
, examples (NumeralValue 50)
[ "deag is dha fhichead"
, "deag is dá fhichead"
]
]
|
facebookincubator/duckling
|
Duckling/Numeral/GA/Corpus.hs
|
bsd-3-clause
| 1,216 | 0 | 9 | 419 | 220 | 130 | 90 | 32 | 1 |
{-# LANGUAGE FlexibleInstances, TypeFamilies, TypeSynonymInstances, GeneralizedNewtypeDeriving #-}
module Examples.Slider where
import Data.Default
import Data.Dynamic
import Control.Newtype (pack)
import Graphics.UI.Toy.Prelude
import Graphics.UI.Toy.Slider
import Graphics.UI.Toy.Transformed
newtype State = State (Transformed (CairoSlider Double))
deriving (Interactive Gtk, Diagrammable Cairo R2)
type instance V State = R2
main :: IO ()
main = runToy (def :: State)
instance Default State where
def = State . translate (100 & 100) $ sli ||| sli ||| sli ||| sli ||| sli ||| sli
where
sli = mkTransformed mkDefaultSlider
instance GtkDisplay State where
display = defaultDisplay
|
mgsloan/toy-gtk-diagrams
|
Examples/Slider.hs
|
bsd-3-clause
| 700 | 0 | 15 | 107 | 193 | 109 | 84 | 18 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
module Database.NySQL.TH
( mkStmt
, mkQuery
, mkStmt'
, mkQuery'
, ToRow
, toRow
, FromRow
, fromRow
, SqlStmt
, runStmt
, SqlQuery
, runQuery
) where
import Text.Regex
import Data.Tuple (swap)
import Data.Char (toUpper, toLower)
import Data.List
import Data.Maybe
import Data.Convertible
import Database.HDBC
import Database.NySQL.Options
import System.FilePath
import Control.Lens
import Control.Monad ((>=>), (<=<))
import Control.Monad.Catch (MonadThrow)
import Control.Monad.Trans (MonadIO, liftIO)
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Language.Haskell.TH.Syntax
class FromRow a where
fromRow :: MonadThrow m => [(String, SqlValue)] -> m a
class ToRow a where
toRow :: a -> [(String, SqlValue)]
instance FromRow [(String, SqlValue)] where
fromRow = pure
instance ToRow [(String, SqlValue)] where
toRow = id
class SqlStmt a where
runStmt :: forall c m. (IConnection c, MonadIO m, MonadThrow m)
=> c -> a -> m Integer
class SqlQuery a where
runQuery :: forall c m r. (IConnection c, MonadIO m, MonadThrow m, FromRow r)
=> c -> a -> m [r]
data SqlType
= Stmt
| Query
mkStmt :: Options -> FilePath -> Q [Dec]
mkStmt = mkSql (Nothing :: Maybe (IO ConnWrapper)) Stmt
mkStmt' :: (IConnection c, Monad m) => m c -> Options -> FilePath -> Q [Dec]
mkStmt' gc = mkSql (Just gc) Stmt
mkQuery :: Options -> FilePath -> Q [Dec]
mkQuery = mkSql (Nothing :: Maybe (IO ConnWrapper)) Query
mkQuery' :: (IConnection c, Monad m) => m c -> Options -> FilePath -> Q [Dec]
mkQuery' gc = mkSql (Just gc) Query
mkSql :: (IConnection c, Monad m) => Maybe (m c) -> SqlType -> Options -> FilePath -> Q [Dec]
mkSql maybeGetConnection sqlType opts filepath = do
query <- runIO $ readFile filepath
nameDum <- newName "dummy"
let typeName = parseTypeName filepath
paramPrefix = parseParamPrefix filepath
className = parseClassName filepath
classFnName = parseClassFnName filepath
fnName = parseFnName filepath
params = (nameDum, "dummy") : fmap (\p -> (mkName (paramModifier opts $ paramPrefix ++ (p & ix 0 %~ toUpper)), p)) (parseParamStrings query)
(rs, ns, ss) <- fmap unzip3 $ (`mapM` nub params) $ \(pn, ps) -> do
pn' <- newName ps
pure (pure (pn, NotStrict, VarT pn'), pn', ps)
let vs = PlainTV <$> ns
eqRecords (a,_,_) (b,_,_) = a == b
con = mkName "con"
sequence
[ dataD (cxt []) typeName vs [recC typeName (tail rs)] []
, let tvb = mkName "a"
in classD
(cxt [])
className
[PlainTV tvb]
[]
[ sigD classFnName
(forallT
vs
((`mapM` ns) (\n ->
appT
(appT
(conT ''Convertible)
(varT n))
(conT ''SqlValue)))
[t| $(varT tvb) -> $(foldl appT (conT typeName) (varT <$> ns))|]) ]
, instanceD
((`mapM` (tail ns)) (\n ->
appT
(appT
(conT ''Convertible)
(varT n))
(conT ''SqlValue)))
(appT
(conT $ mkName $ case sqlType of
Stmt -> "SqlStmt"
Query -> "SqlQuery")
(foldl appT (conT typeName) (varT <$> ns)))
[funD
(mkName (case sqlType of
Stmt -> "runStmt"
Query -> "runQuery"))
[ let cv = mkName "cv"
in clause []
(normalB
(lamE
[varP con, varP cv]
(let fns = tail $ fmap (\s -> (s, appE (varE $ mkName (paramModifier opts $ paramPrefix ++ (s & ix 0 %~ toUpper))))) ss
vals = listE (fmap (\(s, f) -> tupE [litE (StringL s), appE (varE 'toSql) (f (varE cv))]) fns)
in case sqlType of
Stmt ->
[| liftIO (withTransaction $(varE con) (\con' -> do
stmt <- prepare con' $ replaceQs query
i <- execute stmt $ sortVals query $ toRow $vals
pure i)) |]
Query ->
[| liftIO (withTransaction $(varE con) (\con' -> do
stmt <- prepare con' $ replaceQs query
execute stmt $ sortVals query $ toRow $vals
mapM fromRow =<< fetchAllRowsAL stmt)) |]))) [] ]] ]
parseBaseName :: FilePath -> String
parseBaseName = (ix 0 %~ toUpper) . dropExtension . takeFileName
parseTypeName :: FilePath -> Name
parseTypeName = mkName . parseBaseName
parseParamPrefix :: FilePath -> String
parseParamPrefix = (ix 0 %~ toLower) . parseBaseName
parseClassName :: FilePath -> Name
parseClassName = mkName . ("Can"++) . parseBaseName
parseClassFnName :: FilePath -> Name
parseClassFnName = mkName . ("to"++) . parseBaseName
parseFnName :: FilePath -> Name
parseFnName = mkName . (ix 0 %~ toLower) . parseBaseName
parseParamStrings :: String -> [String]
parseParamStrings str =
concatMap (findMatches $ mkRegex "[^:]+")
(findMatches paramRegex str)
replaceQs :: String -> String
replaceQs s = subRegex paramRegex s "?"
sortVals :: String -> [(String, SqlValue)] -> [SqlValue]
sortVals str vs = catMaybes $ (`lookup` vs) <$> parseParamStrings str
paramRegex :: Regex
paramRegex = mkRegex "[:][[:alnum:]_-][[:alnum:]_-]*"
findMatches :: Regex -> String -> [String]
findMatches r s = maybe [] (\(_,m,s',_) -> m : findMatches r s')
(matchRegexAll r s)
|
broma0/nysql
|
src/hs/Database/NySQL/TH.hs
|
bsd-3-clause
| 6,137 | 0 | 39 | 1,988 | 1,884 | 1,018 | 866 | 157 | 4 |
-----------------------------------------------------------------------------
--
-- Module : GenerateForm
-- Copyright :
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings, ScopedTypeVariables, ExistentialQuantification #-}
module GenerateFormUndoMsg (
genFormUndoMsg
) where
import MFlow.Wai.Blaze.Html.All
import MFlow.Forms.Internals
import Control.Monad.State
import Data.Typeable
import Data.Monoid
import Prelude hiding (div)
import Text.Blaze.Html5.Attributes as At hiding (step,span,form)
import Data.List(nub)
import Control.Monad
import Data.List((\\))
--import Debug.Trace
--(!>)= flip trace
main=do
userRegister "edituser" "edituser"
runNavigation "nav" . step $ genFormUndoMsg
-- page with header
hpage w = page $ tFieldEd "editor" "genFormUndoMsgHeader.html" "HEADER EMPTY!" **> w
genFormUndoMsg= do
id <- getSessionId
let title= "generateForm/"++id ++ "/form.html"
initFormTemplate title
desc <- createForm 0 title
hpage $ b "This is the form created. Test it"
++> hr
++> generateForm title desc
**> wlink () "home/reset"
return()
type Template= String
data WType = Intv | Stringv | TextArea |OptionBox[String]
| WCheckBoxes [String] | ShowResults
| Form Template [WType] deriving (Typeable,Read,Show,Eq)
initFormTemplate title= do
liftIO $ writetField (title ++ show 1) $
p "( delete this line. Press the save button to save the edits)"
setSessionData ([] :: [WType])
setSessionData $ Seq 0
data Result = forall a.(Typeable a, Show a) => Result a deriving (Typeable)
instance Show Result where
show (Result x)= show x
genElem Intv = Result <$> dField (getInt Nothing)
genElem Stringv= Result <$> dField (getString Nothing)
genElem TextArea= Result <$> getMultilineText ""
genElem (OptionBox xs) =
Result <$> getSelect (setSelectedOption ""(p "select a option") <|>
firstOf[setOption op (fromStr op) | op <- xs])
genElem (WCheckBoxes xs) =
Result <$> getCheckBoxes(mconcat[setCheckBox False x <++ (fromStr x) | x <- xs])
genElem ShowResults = Result <$> do
xs <- getSessionData `onNothing` return []
pageFlow "" (allOf (map genElem (xs \\ [ShowResults]))) <|> return []
`wcallback` (\r -> pageFlow "button" $
submitButton "submit"
**> h2 "Result:"
++> dField(wraw $ b << show r)
**> return ())
genElem (Form temp desc)= Result <$> generateForm temp desc
generateForm title xs=
input ! At.type_ "hidden" ! name "p0" ! value "()"
++> (div ! At.id "p0"
<<< input ! type_ "hidden" ! name "p0" ! value"()"
++> ( template title . pageFlow "" . witerate . pageFlow "" . allOf $ map genElem xs))
-- n carries out the version number
createForm n title= do
desc <- getSessionData `onNothing` return []
Seq seq <- getSessionData `onNothing` return (Seq 0)
r <- hpage $ do
divmenu <<<(wlogin
**> do
br ++> wlink ("save" :: String) << b "Save the form and continue"
<++ br <> "(when finished)"
content <- liftIO $ readtField (mempty :: Html) (title ++ show n)
liftIO . writetField title $ content
liftIO $ forM_ [1 .. n] $ \n -> writetField (title ++ show n) ("" :: Html) -- delete
desc' <- getSessionData `onNothing` return []
desc <- addResults title desc'
return $ Just desc
<|> do
wdesc <- chooseWidget <++ hr
addElem (title ++ show n) (title ++ show (n+1)) wdesc
setSessionData $ mappend desc [wdesc]
return Nothing
)
<** divbody <<< (edTemplate "edituser" (title ++ show n) (return ()) )
case r of
Just desc -> breturn desc
Nothing -> createForm (n+1) title
-- add a "show results" element to the form if it is not already there
addResults title desc = do
if (null $ filter (== ShowResults) desc)
then do
addElem title title ShowResults
return $ desc ++ [ShowResults]
else return desc
-- add a form elem to the page being edited
addElem title title2 wdesc = do
Seq seq <- getSessionData `onNothing` return (Seq 0)
content <- liftIO $ readtField mempty title
fieldview <- generateView wdesc seq
liftIO . writetField title2 $ content <> br <> fieldview
divbody= div ! At.style "float:right;width:65%"
divmenu= div ! At.style "background-color:#EEEEEE;float:left;margin-left:10px;margin-right:10px;overflow:auto;"
newtype Seq= Seq Int deriving (Typeable)
generateView desc n= View $ do
s <- get
let n'= if n== 0 then 1 else n
put s{mfSequence= n'}
FormElm render mr <- runView $ genElem desc
n'' <- gets mfSequence
setSessionData $ Seq n''
return $ FormElm mempty $ Just ( br <> br <> render :: Html)
nrlink x v= wlink x v <! noAutoRefresh
chooseWidget= pageFlow "" $ autoRefresh $
(p $ a ! At.class_ "_noAutoRefresh" ! At.href "/" $ "home")
++>(p <<< absLink ("" ::String) "reset" <! noAutoRefresh)
**> p <<< do
wlink ("text":: String) "text field"
ul <<<(li <<< nrlink Intv "returning Int"
<|> li <<< nrlink Stringv "returning string")
<|> p <<< do nrlink TextArea "text area"
<|> p <<< do
wlink ("check" :: String) "checkBoxes"
ul <<< getOptions "comb"
<|> p <<< do
wlink ("options" :: String) "options"
ul <<< getOptions "opt"
<|> p <<< nrlink ShowResults "Show Form Results"
getOptions pf = autoRefresh . wform $
do
noCache
(op,_) <- (,)<$> getString Nothing <! [("size","8"),("placeholder","option")]
<*> submitButton "add"
<** submitButton "clear" `waction` const (delSessionData (undefined :: WType))
mops <- getSessionData
ops' <- case (mops,pf) of
(Nothing, "comb") -> do setSessionData $ WCheckBoxes [op] ; return [op]
(Nothing, "opt") -> do setSessionData $ OptionBox [op] ; return [op]
(Just (OptionBox _), "comb") -> do setSessionData $ WCheckBoxes [op] ; return [op]
(Just (WCheckBoxes _),"opt") -> do setSessionData $ OptionBox [op] ; return [op]
(Just (WCheckBoxes ops),"comb") -> do
let ops'= nub $ op:ops
setSessionData . WCheckBoxes $ ops'
return ops'
(Just (OptionBox ops),"opt") -> do
let ops'= nub $ op:ops
setSessionData . OptionBox $ ops'
return ops'
wraw $ mconcat [p << op | op <- ops']
**> do
r <- submitButton "create" <! noAutoRefresh
ops <- getSessionData
case ops of
Nothing -> stop
Just elem -> do
delSessionData (undefined :: WType)
return elem
|
agocorona/MFlow
|
Demos/GenerateFormUndoMsg.hs
|
bsd-3-clause
| 7,177 | 0 | 24 | 2,034 | 2,317 | 1,154 | 1,163 | 151 | 7 |
-- | Parsing and evaluation of strict Loop.
module Language.LoopGotoWhile.Loop.Strict
( run
, eval
, parse
, prettyPrint
) where
import Control.Monad
import Text.ParserCombinators.Parsec hiding (parse)
import Language.LoopGotoWhile.Shared.Util (mkStdParser, mkStdRunner)
import Language.LoopGotoWhile.Loop.StrictAS
import Language.LoopGotoWhile.Loop.Transform (toExtended, toWhile)
import qualified Language.LoopGotoWhile.While.Strict as WhileS
import qualified Language.LoopGotoWhile.While.Transform as WhileT
-- * Main Functions
-- ==============
-- | Given a string representation of a strict Loop program and a list of
-- arguments parse & evaluate the program and return either an error string or
-- the value of 'x0'.
run :: String -> [Integer] -> Either String Integer
run = mkStdRunner parse eval
-- | Given a strict Loop AST and a list of arguments evaluate the program
-- and return the value of 'x0'.
eval :: Program -> [Integer] -> Integer
eval ast = WhileS.eval (WhileT.toStrict . toWhile . toExtended $ ast)
-- | Given a string representation of a strict Loop program parse it and
-- return either an error string or the AST.
parse :: String -> Either String Program
parse = mkStdParser parseStats () spaces
-- * Parsing
-- =======
parseStats :: Parser Program
parseStats = do
stats <- parseStat `sepBy1` (string ";" >> spaces)
return $ case stats of
[x] -> x
x -> Seq x
where parseStat = parseAssign <|> parseLoop
parseLoop :: Parser Stat
parseLoop = do
_ <- string "LOOP"
spaces
x <- parseVar
spaces
_ <- string "DO"
spaces
body <- parseStats
spaces
_ <- string "END"
return $ Loop x body
parseAssign :: Parser Stat
parseAssign = do
x <- parseVar
spaces
_ <- string ":="
spaces
y <- parseVar
spaces
o <- parseOp
spaces
c <- parseConst
spaces
return $ Assign x y o c
parseOp :: Parser Op
parseOp = do
op <- oneOf "+-"
case op of
'+' -> return Plus
'-' -> return Minus
_ -> fail "Wrong operator"
parseVar :: Parser Index
parseVar = liftM read (char 'x' >> many1 (digit <?> "") <?> "variable")
parseConst :: Parser Const
parseConst = liftM read (many1 digit <?> "constant")
|
eugenkiss/loopgotowhile
|
src/Language/LoopGotoWhile/Loop/Strict.hs
|
bsd-3-clause
| 2,281 | 0 | 11 | 533 | 579 | 302 | 277 | 61 | 3 |
module Main (main) where
import System.Environment (getArgs)
import OnPing.DataServer.Language (prelude, runScript, runEval)
import OnPing.DataServer.Language.Parser (parseScriptFile)
main :: IO ()
main = do
xs <- getArgs
mapM_ runFile xs
runFile :: FilePath -> IO ()
runFile fp = do
putStrLn $ "Running file: " ++ fp
escr <- parseScriptFile fp
case escr of
Left err -> print err
Right scr -> runEval $ prelude >> runScript scr
|
plow-technologies/onping-data-language
|
main/Main.hs
|
bsd-3-clause
| 450 | 0 | 11 | 88 | 160 | 82 | 78 | 15 | 2 |
module Language.Epilog.Treelike
( Tree(..)
, Treelike
, drawTree
, leaf
, posRoot
, toForest
, toForest'
, toTree
) where
--------------------------------------------------------------------------------
import Language.Epilog.Common
--------------------------------------------------------------------------------
import qualified Data.Map.Strict as Map (toList)
import Data.Tree (Forest, Tree (..), drawTree)
--------------------------------------------------------------------------------
class Treelike a where
toTree :: a -> Tree String
toForest :: (Foldable f, Functor f) => f a -> Forest String
toForest = toList . fmap toTree
toForest' :: Map String a -> Forest String
toForest' = fmap (\(a, b) -> Node a [toTree b]) . Map.toList
posRoot :: (Int, Int) -> Tree String -> Tree String
posRoot pos tree =
tree {rootLabel = show pos <> rootLabel tree}
leaf :: String -> Tree String
leaf s = Node s []
|
adgalad/Epilog
|
src/Haskell/Language/Epilog/Treelike.hs
|
bsd-3-clause
| 979 | 0 | 13 | 195 | 279 | 155 | 124 | 23 | 1 |
{-# LANGUAGE ForeignFunctionInterface, CPP #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.VertexType2101010Rev
-- Copyright : (c) Sven Panne 2014
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- All raw functions and tokens from the ARB_vertex_type_2_10_10_10_rev
-- extension, see
-- <http://www.opengl.org/registry/specs/ARB/vertex_type_2_10_10_10_rev.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.VertexType2101010Rev (
-- * Functions
glVertexAttribP1ui,
glVertexAttribP1uiv,
glVertexAttribP2ui,
glVertexAttribP2uiv,
glVertexAttribP3ui,
glVertexAttribP3uiv,
glVertexAttribP4ui,
glVertexAttribP4uiv,
glVertexP2ui,
glVertexP2uiv,
glVertexP3ui,
glVertexP3uiv,
glVertexP4ui,
glVertexP4uiv,
glTexCoordP1ui,
glTexCoordP1uiv,
glTexCoordP2ui,
glTexCoordP2uiv,
glTexCoordP3ui,
glTexCoordP3uiv,
glTexCoordP4ui,
glTexCoordP4uiv,
glMultiTexCoordP1ui,
glMultiTexCoordP1uiv,
glMultiTexCoordP2ui,
glMultiTexCoordP2uiv,
glMultiTexCoordP3ui,
glMultiTexCoordP3uiv,
glMultiTexCoordP4ui,
glMultiTexCoordP4uiv,
glNormalP3ui,
glNormalP3uiv,
glColorP3ui,
glColorP3uiv,
glColorP4ui,
glColorP4uiv,
glSecondaryColorP3ui,
glSecondaryColorP3uiv,
-- * Tokens
gl_UNSIGNED_INT_2_10_10_10_REV,
gl_INT_2_10_10_10_REV
) where
import Foreign.C.Types
import Foreign.Ptr
import Graphics.Rendering.OpenGL.Raw.Core31.Tokens
import Graphics.Rendering.OpenGL.Raw.Core31.Types
import Graphics.Rendering.OpenGL.Raw.Extensions
--------------------------------------------------------------------------------
#include "HsOpenGLRaw.h"
extensionNameString :: String
extensionNameString = "GL_ARB_vertex_type_2_10_10_10_rev"
EXTENSION_ENTRY(dyn_glVertexAttribP1ui,ptr_glVertexAttribP1ui,"glVertexAttribP1ui",glVertexAttribP1ui,GLuint -> GLenum -> GLboolean -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glVertexAttribP1uiv,ptr_glVertexAttribP1uiv,"glVertexAttribP1uiv",glVertexAttribP1uiv,GLuint -> GLenum -> GLboolean -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glVertexAttribP2ui,ptr_glVertexAttribP2ui,"glVertexAttribP2ui",glVertexAttribP2ui,GLuint -> GLenum -> GLboolean -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glVertexAttribP2uiv,ptr_glVertexAttribP2uiv,"glVertexAttribP2uiv",glVertexAttribP2uiv,GLuint -> GLenum -> GLboolean -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glVertexAttribP3ui,ptr_glVertexAttribP3ui,"glVertexAttribP3ui",glVertexAttribP3ui,GLuint -> GLenum -> GLboolean -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glVertexAttribP3uiv,ptr_glVertexAttribP3uiv,"glVertexAttribP3uiv",glVertexAttribP3uiv,GLuint -> GLenum -> GLboolean -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glVertexAttribP4ui,ptr_glVertexAttribP4ui,"glVertexAttribP4ui",glVertexAttribP4ui,GLuint -> GLenum -> GLboolean -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glVertexAttribP4uiv,ptr_glVertexAttribP4uiv,"glVertexAttribP4uiv",glVertexAttribP4uiv,GLuint -> GLenum -> GLboolean -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glVertexP2ui,ptr_glVertexP2ui,"glVertexP2ui",glVertexP2ui,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glVertexP2uiv,ptr_glVertexP2uiv,"glVertexP2uiv",glVertexP2uiv,GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glVertexP3ui,ptr_glVertexP3ui,"glVertexP3ui",glVertexP3ui,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glVertexP3uiv,ptr_glVertexP3uiv,"glVertexP3uiv",glVertexP3uiv,GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glVertexP4ui,ptr_glVertexP4ui,"glVertexP4ui",glVertexP4ui,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glVertexP4uiv,ptr_glVertexP4uiv,"glVertexP4uiv",glVertexP4uiv,GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glTexCoordP1ui,ptr_glTexCoordP1ui,"glTexCoordP1ui",glTexCoordP1ui,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glTexCoordP1uiv,ptr_glTexCoordP1uiv,"glTexCoordP1uiv",glTexCoordP1uiv,GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glTexCoordP2ui,ptr_glTexCoordP2ui,"glTexCoordP2ui",glTexCoordP2ui,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glTexCoordP2uiv,ptr_glTexCoordP2uiv,"glTexCoordP2uiv",glTexCoordP2uiv,GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glTexCoordP3ui,ptr_glTexCoordP3ui,"glTexCoordP3ui",glTexCoordP3ui,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glTexCoordP3uiv,ptr_glTexCoordP3uiv,"glTexCoordP3uiv",glTexCoordP3uiv,GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glTexCoordP4ui,ptr_glTexCoordP4ui,"glTexCoordP4ui",glTexCoordP4ui,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glTexCoordP4uiv,ptr_glTexCoordP4uiv,"glTexCoordP4uiv",glTexCoordP4uiv,GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexCoordP1ui,ptr_glMultiTexCoordP1ui,"glMultiTexCoordP1ui",glMultiTexCoordP1ui,GLenum -> GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexCoordP1uiv,ptr_glMultiTexCoordP1uiv,"glMultiTexCoordP1uiv",glMultiTexCoordP1uiv,GLenum -> GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexCoordP2ui,ptr_glMultiTexCoordP2ui,"glMultiTexCoordP2ui",glMultiTexCoordP2ui,GLenum -> GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexCoordP2uiv,ptr_glMultiTexCoordP2uiv,"glMultiTexCoordP2uiv",glMultiTexCoordP2uiv,GLenum -> GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexCoordP3ui,ptr_glMultiTexCoordP3ui,"glMultiTexCoordP3ui",glMultiTexCoordP3ui,GLenum -> GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexCoordP3uiv,ptr_glMultiTexCoordP3uiv,"glMultiTexCoordP3uiv",glMultiTexCoordP3uiv,GLenum -> GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexCoordP4ui,ptr_glMultiTexCoordP4ui,"glMultiTexCoordP4ui",glMultiTexCoordP4ui,GLenum -> GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glMultiTexCoordP4uiv,ptr_glMultiTexCoordP4uiv,"glMultiTexCoordP4uiv",glMultiTexCoordP4uiv,GLenum -> GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glNormalP3ui,ptr_glNormalP3ui,"glNormalP3ui",glNormalP3ui,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glNormalP3uiv,ptr_glNormalP3uiv,"glNormalP3uiv",glNormalP3uiv,GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glColorP3ui,ptr_glColorP3ui,"glColorP3ui",glColorP3ui,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glColorP3uiv,ptr_glColorP3uiv,"glColorP3uiv",glColorP3uiv,GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glColorP4ui,ptr_glColorP4ui,"glColorP4ui",glColorP4ui,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glColorP4uiv,ptr_glColorP4uiv,"glColorP4uiv",glColorP4uiv,GLenum -> Ptr GLuint -> IO ())
EXTENSION_ENTRY(dyn_glSecondaryColorP3ui,ptr_glSecondaryColorP3ui,"glSecondaryColorP3ui",glSecondaryColorP3ui,GLenum -> GLuint -> IO ())
EXTENSION_ENTRY(dyn_glSecondaryColorP3uiv,ptr_glSecondaryColorP3uiv,"glSecondaryColorP3uiv",glSecondaryColorP3uiv,GLenum -> Ptr GLuint -> IO ())
gl_INT_2_10_10_10_REV :: GLenum
gl_INT_2_10_10_10_REV = 0x8D9F
|
mfpi/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/ARB/VertexType2101010Rev.hs
|
bsd-3-clause
| 6,980 | 0 | 13 | 580 | 1,582 | 899 | 683 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
module Tests.DevsTest (devs_tests) where
import Data.Monoid
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2
import Test.HUnit
import Test.QuickCheck
import Data.Typeable (Typeable)
import qualified Prelude as P
import Numeric.Units.Dimensional.Prelude
import Data.DEVS
devs_tests :: Test.Framework.Test
devs_tests = testGroup "DEVS tests"
[ t_infinity_tests
, selfRef_tests
]
--
-- t_infinity tests
--
t_infinity_tests = testGroup "t_infinity_tests"
[ testCase "t_infinity eq" test_t_infinity_eq
, testProperty "t_infinity smaller" prop_t_infinity_smaller
]
prop_t_infinity_smaller :: Double -> Property
prop_t_infinity_smaller d =
let dt = d *~ second
in not (dt == t_infinity) ==> dt < t_infinity
test_t_infinity_eq :: Assertion
test_t_infinity_eq = t_infinity @?= t_infinity
--
-- selfRef tests
--
selfRef_tests = testGroup "t_infinity_tests"
[ testCase "selfRef eq 1" test_selfRef_eq1
, testCase "selfRef eq 2" test_selfRef_eq2
, testCase "selfRef neq 1" test_selfRef_neq1
, testCase "selfRef neq 2" test_selfRef_neq2
]
data A1 = A1 deriving (Typeable, Show, Ord, Eq)
instance PDEVS A1
ref_a1 = selfRef A1
data A2 = A2 deriving (Typeable, Show, Ord, Eq)
instance PDEVS A2
ref_a2 = selfRef A2
test_selfRef_eq1 = ref_a1 @?= ref_a1
test_selfRef_eq2 = ref_a2 @?= ref_a2
test_selfRef_neq1 = assertBool (show ref_a1 ++ " must not be equal to " ++ show ref_a2 ) $
ref_a1 /= ref_a2
test_selfRef_neq2 = assertBool (show ref_a1 ++ " must not be equal to " ++ show ref_a2 ) $
ref_a2 /= ref_a1
|
alios/lambda-devs
|
Test/Tests/DevsTest.hs
|
bsd-3-clause
| 1,826 | 0 | 11 | 462 | 402 | 220 | 182 | 42 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Debug where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Language.Haskell.TH.Ppr
{-|
Debugging Template Haskell stuff at the GHCi REPL is hard because everything
ends up in the "Q" monad and there is no way to print the "Q" monad. These functions
call pprint and show but return a "Q Exp" so that the following expressions work
to print a given value (e.g. "x"):
$(pprintQ x)
$(showQ x)
NOTE: GHCi likes to run the contents of splices twice or more, so the results
may be printed multiple times.
-}
pprintQ :: (Ppr a) => Q a -> Q Exp
pprintQ x = x >>= (qRunIO . putStrLn . pprint) >> [|return ()|]
showQ :: (Show a) => Q a -> Q Exp
showQ x = x >>= (qRunIO . putStrLn . show) >> [|return ()|]
|
DanielG/deepcopy
|
Debug.hs
|
bsd-3-clause
| 765 | 0 | 9 | 147 | 134 | 77 | 57 | 9 | 1 |
module CO4.Example.LPOStandalone
where
import Prelude hiding (lex,lookup)
import CO4.Prelude.Nat
type Map k v = [(k,v)]
type Symbol = Nat
data Term = Var Symbol
| Node Symbol [Term]
deriving (Show)
data Order = Gr | Eq | NGe
type Rule = (Term,Term)
type Trs = [Rule]
type Precedence = Map Symbol Nat
constraint :: Trs -> Precedence -> Bool
constraint rules precedence =
all (\(lhs,rhs) -> eqOrder (lpo precedence lhs rhs) Gr) rules
lpo :: Precedence -> Term -> Term -> Order
lpo precedence s t = case t of
Var x -> case eqTerm s t of
False -> case varOccurs x s of
False -> NGe
True -> Gr
True -> Eq
Node g ts -> case s of
Var _ -> NGe
Node f ss ->
case all (\si -> eqOrder (lpo precedence si t) NGe) ss of
False -> Gr
True -> case ord precedence f g of
Gr -> case all (\ti -> eqOrder (lpo precedence s ti) Gr) ts of
False -> NGe
True -> Gr
Eq -> case all (\ti -> eqOrder (lpo precedence s ti) Gr) ts of
False -> NGe
True -> lex (lpo precedence) ss ts
NGe -> NGe
ord :: Precedence -> Symbol -> Symbol -> Order
ord precedence a b =
let pa = lookup eqSymbol a precedence
pb = lookup eqSymbol b precedence
in
ordNat pa pb
ordNat :: Nat -> Nat -> Order
ordNat a b = case eqNat a b of
True -> Eq
False -> case gtNat a b of
True -> Gr
False -> NGe
varOccurs :: Symbol -> Term -> Bool
varOccurs var term = case term of
Var var' -> eqSymbol var var'
Node _ ts -> any (varOccurs var) ts
lex :: (a -> b -> Order) -> [a] -> [b] -> Order
lex ord xs ys = case xs of
[] -> case ys of [] -> Eq
_ -> NGe
x:xs' -> case ys of
[] -> Gr
y:ys' -> case ord x y of
Gr -> Gr
Eq -> lex ord xs' ys'
NGe -> NGe
-- * utilities
lookup :: (k -> k -> Bool) -> k -> Map k v -> v
lookup f k map = case map of
[] -> undefined
m:ms -> case m of
(k',v) -> case f k k' of
False -> lookup f k ms
True -> v
eqTerm :: Term -> Term -> Bool
eqTerm x y = case x of
Var u -> case y of { Var v -> eqSymbol u v; _ -> False }
Node u us -> case y of
Node v vs -> (eqSymbol u v) &&
(eqList eqTerm us vs)
_ -> False
eqOrder :: Order -> Order -> Bool
eqOrder x y = case x of
Gr -> case y of { Gr -> True; _ -> False }
Eq -> case y of { Eq -> True; _ -> False }
NGe -> case y of { NGe -> True; _ -> False }
eqSymbol :: Symbol -> Symbol -> Bool
eqSymbol = eqNat
eqList :: (a -> a -> Bool) -> [a] -> [a] -> Bool
eqList f xs ys = case xs of
[] -> case ys of [] -> True
_ -> False
u:us -> case ys of [] -> False
v:vs -> (f u v) && (eqList f us vs)
|
apunktbau/co4
|
test/CO4/Example/LPOStandalone.hs
|
gpl-3.0
| 2,964 | 0 | 23 | 1,137 | 1,282 | 662 | 620 | 87 | 10 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS -fno-warn-orphans #-}
module System.Random.Utils
( splits, randFunc, genFromHashable
) where
import Prelude.Compat
import Data.Binary (Binary(..))
import Data.Hashable (Hashable, hashWithSalt)
import System.Random (RandomGen, Random, StdGen, split, mkStdGen, random)
-- Yucky work-around for lack of Binary instance
instance Binary StdGen where
get = read <$> get
put = put . show
splits :: RandomGen g => g -> [g]
splits = map fst . iterate (split . snd) . split
randFunc :: (Hashable h, Random r) => h -> r
randFunc = fst . random . genFromHashable
genFromHashable :: Hashable a => a -> StdGen
genFromHashable = mkStdGen . hashWithSalt 0
|
da-x/lamdu
|
bottlelib/System/Random/Utils.hs
|
gpl-3.0
| 709 | 0 | 9 | 127 | 214 | 122 | 92 | 17 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.EC2.ResetNetworkInterfaceAttribute
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Resets a network interface attribute. You can specify only one attribute
-- at a time.
--
-- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ResetNetworkInterfaceAttribute.html AWS API Reference> for ResetNetworkInterfaceAttribute.
module Network.AWS.EC2.ResetNetworkInterfaceAttribute
(
-- * Creating a Request
resetNetworkInterfaceAttribute
, ResetNetworkInterfaceAttribute
-- * Request Lenses
, rniaSourceDestCheck
, rniaDryRun
, rniaNetworkInterfaceId
-- * Destructuring the Response
, resetNetworkInterfaceAttributeResponse
, ResetNetworkInterfaceAttributeResponse
) where
import Network.AWS.EC2.Types
import Network.AWS.EC2.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'resetNetworkInterfaceAttribute' smart constructor.
data ResetNetworkInterfaceAttribute = ResetNetworkInterfaceAttribute'
{ _rniaSourceDestCheck :: !(Maybe Text)
, _rniaDryRun :: !(Maybe Bool)
, _rniaNetworkInterfaceId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ResetNetworkInterfaceAttribute' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rniaSourceDestCheck'
--
-- * 'rniaDryRun'
--
-- * 'rniaNetworkInterfaceId'
resetNetworkInterfaceAttribute
:: Text -- ^ 'rniaNetworkInterfaceId'
-> ResetNetworkInterfaceAttribute
resetNetworkInterfaceAttribute pNetworkInterfaceId_ =
ResetNetworkInterfaceAttribute'
{ _rniaSourceDestCheck = Nothing
, _rniaDryRun = Nothing
, _rniaNetworkInterfaceId = pNetworkInterfaceId_
}
-- | The source\/destination checking attribute. Resets the value to 'true'.
rniaSourceDestCheck :: Lens' ResetNetworkInterfaceAttribute (Maybe Text)
rniaSourceDestCheck = lens _rniaSourceDestCheck (\ s a -> s{_rniaSourceDestCheck = a});
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have
-- the required permissions, the error response is 'DryRunOperation'.
-- Otherwise, it is 'UnauthorizedOperation'.
rniaDryRun :: Lens' ResetNetworkInterfaceAttribute (Maybe Bool)
rniaDryRun = lens _rniaDryRun (\ s a -> s{_rniaDryRun = a});
-- | The ID of the network interface.
rniaNetworkInterfaceId :: Lens' ResetNetworkInterfaceAttribute Text
rniaNetworkInterfaceId = lens _rniaNetworkInterfaceId (\ s a -> s{_rniaNetworkInterfaceId = a});
instance AWSRequest ResetNetworkInterfaceAttribute
where
type Rs ResetNetworkInterfaceAttribute =
ResetNetworkInterfaceAttributeResponse
request = postQuery eC2
response
= receiveNull ResetNetworkInterfaceAttributeResponse'
instance ToHeaders ResetNetworkInterfaceAttribute
where
toHeaders = const mempty
instance ToPath ResetNetworkInterfaceAttribute where
toPath = const "/"
instance ToQuery ResetNetworkInterfaceAttribute where
toQuery ResetNetworkInterfaceAttribute'{..}
= mconcat
["Action" =:
("ResetNetworkInterfaceAttribute" :: ByteString),
"Version" =: ("2015-04-15" :: ByteString),
"SourceDestCheck" =: _rniaSourceDestCheck,
"DryRun" =: _rniaDryRun,
"NetworkInterfaceId" =: _rniaNetworkInterfaceId]
-- | /See:/ 'resetNetworkInterfaceAttributeResponse' smart constructor.
data ResetNetworkInterfaceAttributeResponse =
ResetNetworkInterfaceAttributeResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ResetNetworkInterfaceAttributeResponse' with the minimum fields required to make a request.
--
resetNetworkInterfaceAttributeResponse
:: ResetNetworkInterfaceAttributeResponse
resetNetworkInterfaceAttributeResponse =
ResetNetworkInterfaceAttributeResponse'
|
fmapfmapfmap/amazonka
|
amazonka-ec2/gen/Network/AWS/EC2/ResetNetworkInterfaceAttribute.hs
|
mpl-2.0
| 4,705 | 0 | 11 | 857 | 524 | 316 | 208 | 73 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Test where
import Prelude hiding (id,(.),(<*>),(<$>),pure,(*>),(<*),foldl,print)
import qualified Prelude as P
import Lojban
import OpenCog.Lojban
import OpenCog.Lojban.Util
import OpenCog.Lojban.Syntax
import OpenCog.Lojban.Syntax.Util
import OpenCog.Lojban.Syntax.Types
import OpenCog.Lojban.Syntax.AtomUtil
import OpenCog.AtomSpace
import Iso
import Syntax hiding (SynIso,Syntax)
import Lojban
import Lojban.Syntax.Util
import Control.Applicative ((<$>))
import Control.Arrow
import Control.Monad.RWS
import Control.Category (id,(.))
import qualified Data.ListTrie.Patricia.Set.Ord as TS
import Data.Maybe
import qualified Data.Map as M
--import Text.XML.HXT.Core
mystate s = State {sFlags = M.empty
,sAtoms = []
,sText = s
,sSeed = 0
,sNow = cCN "now_here" noTv
,sCtx = [cCN "now_here" noTv]
,sJAI = Nothing
,sXU = []}
loadwl = do
(wl :: WordList State) <- loadWordLists "cmavo.csv" "gismu.csv"
return wl
mpag :: WordList State -> Syntax a -> String -> Either String (a,State,())
mpag wl x y = runRWST (apply x ()) wl (mystate y)
mpa :: WordList State -> Syntax Atom -> String -> IO ()
mpa wl x y = do
case runRWST (apply x ()) wl (mystate y) of
Left s -> putStrLn s
Right (a,s,_) -> printAtom a >> P.print s
|
misgeatgit/opencog
|
opencog/nlp/lojban/HaskellLib/test/Test.hs
|
agpl-3.0
| 1,425 | 0 | 12 | 344 | 483 | 283 | 200 | 41 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.BEncode
-- Copyright : (c) 2005 Jesper Louis Andersen <[email protected]>
-- 2006 Lemmih <[email protected]>
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : believed to be stable
-- Portability : portable
--
-- Provides a BEncode data type is well as functions for converting this
-- data type to and from a String.
--
-- Also supplies a number of properties which the module must satisfy.
-----------------------------------------------------------------------------
module Data.BEncode
(
-- * Data types
BEncode(..),
-- * Functions
bRead,
bShow,
bPack
)
where
import qualified Data.Map as Map
import Data.Map (Map)
import Data.List (sort)
import Text.ParserCombinators.Parsec
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.ByteString.Char8 as BS
import Data.Binary
import Data.BEncode.Lexer ( Token (..), lexer )
type BParser a = GenParser Token () a
{- | The B-coding defines an abstract syntax tree given as a simple
data type here
-}
data BEncode = BInt Integer
| BString L.ByteString
| BList [BEncode]
| BDict (Map String BEncode)
deriving (Eq, Ord, Show)
instance Binary BEncode where
put e = put (BS.concat $ L.toChunks $ bPack e)
get = do s <- get
case bRead (L.fromChunks [s]) of
Just e -> return e
Nothing -> fail "Failed to parse BEncoded data"
-- Source position is pretty useless in BEncoded data. FIXME
updatePos :: (SourcePos -> Token -> [Token] -> SourcePos)
updatePos pos _ _ = pos
bToken :: Token -> BParser ()
bToken t = tokenPrim show updatePos fn
where fn t' | t' == t = Just ()
fn _ = Nothing
token' :: (Token -> Maybe a) -> BParser a
token' = tokenPrim show updatePos
tnumber :: BParser Integer
tnumber = token' fn
where fn (TNumber i) = Just i
fn _ = Nothing
tstring :: BParser L.ByteString
tstring = token' fn
where fn (TString str) = Just str
fn _ = Nothing
withToken :: Token -> BParser a -> BParser a
withToken tok
= between (bToken tok) (bToken TEnd)
--------------------------------------------------------------
--------------------------------------------------------------
bInt :: BParser BEncode
bInt = withToken TInt $ fmap BInt tnumber
bString :: BParser BEncode
bString = fmap BString tstring
bList :: BParser BEncode
bList = withToken TList $ fmap BList (many bParse)
bDict :: BParser BEncode
bDict = withToken TDict $
fmap (BDict . Map.fromAscList) (checkList =<< many bAssocList)
where checkList lst = if lst /= sort lst
then fail "dictionary not sorted"
else return lst
bAssocList
= do str <- tstring
value <- bParse
return (L.unpack str,value)
bParse :: BParser BEncode
bParse = bDict <|> bList <|> bString <|> bInt
{- | bRead is a conversion routine. It assumes a B-coded string as input
and attempts a parse of it into a BEncode data type
-}
bRead :: L.ByteString -> Maybe BEncode
bRead str = case parse bParse "" (lexer str) of
Left _err -> Nothing
Right b -> Just b
-- | Render a BEncode structure to a B-coded string
bShow :: BEncode -> ShowS
bShow = bShow'
where
sc = showChar
ss = showString
sKV (k,v) = sString k (length k) . bShow' v
sDict dict = foldr ((.) . sKV) id (Map.toAscList dict)
sList = foldr ((.) . bShow') id
sString str len = shows len . sc ':' . ss str
bShow' b =
case b of
BInt i -> sc 'i' . shows i . sc 'e'
BString s -> sString (L.unpack s) (L.length s)
BList bl -> sc 'l' . sList bl . sc 'e'
BDict bd -> sc 'd' . sDict bd . sc 'e'
bPack :: BEncode -> L.ByteString
bPack be = L.fromChunks (bPack' be [])
where intTag = BS.pack "i"
colonTag = BS.pack ":"
endTag = BS.pack "e"
listTag = BS.pack "l"
dictTag = BS.pack "d"
sString s r = BS.pack (show (L.length s)) : colonTag : L.toChunks s ++ r
bPack' (BInt i) r = intTag : BS.pack (show i) : endTag : r
bPack' (BString s) r = sString s r
bPack' (BList bl) r = listTag : foldr bPack' (endTag : r) bl
bPack' (BDict bd) r = dictTag : foldr (\(k,v) -> sString (L.pack k) . bPack' v) (endTag : r) (Map.toAscList bd)
--check be = bShow be "" == L.unpack (bPack be)
|
matthewleon/bencode
|
src/Data/BEncode.hs
|
bsd-3-clause
| 4,586 | 0 | 15 | 1,266 | 1,370 | 705 | 665 | 93 | 4 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Main where
import Control.Monad
import Control.Monad.State.Strict
import Data.ByteString (ByteString, pack)
import Pipes.Parse
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Test.QuickCheck.Monadic (assert, monadicIO, run)
import TestHelpers
import Vaultaire.Daemon
import Vaultaire.InternalStore (enumerateOrigin, internalStoreBuckets,
readFrom, writeTo)
import Vaultaire.Types
instance Arbitrary ByteString where arbitrary = fmap pack arbitrary
rollOverAddress :: Address
rollOverAddress = Address internalStoreBuckets
main :: IO ()
main = hspec suite
suite :: Spec
suite = do
describe "writing" $ do
it "writes simple bucket correctly" $ do
runTestDaemon "tcp://localhost:1234" $ writeTo (Origin "PONY") 4 "Hai"
readObject "02_PONY_INTERNAL_00000000000000000004_00000000000000000000_simple"
>>= (`shouldBe` Right "\x04\x00\x00\x00\x00\x00\x00\x00\
\\x00\x00\x00\x00\x00\x00\x00\x00\
\\x00\x00\x00\x00\x00\x00\x00\x00")
it "writes extended bucket correctly" $ do
runTestDaemon "tcp://localhost:1234" $ writeTo (Origin "PONY") 4 "Hai"
readObject "02_PONY_INTERNAL_00000000000000000004_00000000000000000000_extended"
>>= (`shouldBe` Right "\x03\x00\x00\x00\x00\x00\x00\x00\&Hai")
describe "reading" $ do
it "reads a write" $ -- Use the same write, as we have already shown it correct
runTestDaemon "tcp://localhost:1234"
(do writeTo (Origin "PONY") 4 "Hai"
readFrom (Origin "PONY") 4)
>>= (`shouldBe` Just "Hai")
it "disambiguates collision" $
runTestDaemon "tcp://localhost:1234"
(do writeTo (Origin "PONY") rollOverAddress "Hai1"
readFrom (Origin "PONY") 0)
>>= (`shouldBe` Nothing)
describe "enumeration" $
it "enumerates two writes" $ do
addrs <- runTestDaemon "tcp://localhost:1234" $ do
writeTo (Origin "PONY") rollOverAddress "Hai1"
writeTo (Origin "PONY") 0 "Hai2"
writeTo (Origin "PONY") rollOverAddress "Hai3" -- overwrite
evalStateT drawAll (enumerateOrigin "PONY")
addrs `shouldBe` [(0, "Hai2"), (rollOverAddress, "Hai3")]
describe "identity QuickCheck" $
prop "writes then reads" propWriteThenRead
propWriteThenRead :: (Origin, Address, ByteString) -> Property
propWriteThenRead arb@(_,_,payload) = monadicIO $ do
(enumeration, read') <- run $ runTestDaemon "tcp://localhost:1234" $ writeThenRead arb
assert $ (enumeration == read') && (read' == payload)
writeThenRead :: (Origin, Address, ByteString) -> Daemon (ByteString, ByteString)
writeThenRead (o,a,p) = do
writeTo o a p
[(a', e)] <- evalStateT drawAll (enumerateOrigin o)
unless (a' == a) $ error "invalid address from enumeration"
r <- readFrom o a >>= maybe (error "no value") return
return (e,r)
|
anchor/vaultaire
|
tests/InternalStoreTest.hs
|
bsd-3-clause
| 3,256 | 0 | 18 | 826 | 776 | 398 | 378 | 66 | 1 |
module Development.Abba.Core
( buildTargets
, shell
, clean
) where
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive.Query.BFS
import Data.List
import Data.Maybe
import Data.Ord
import Data.Set
( Set
)
import qualified Data.Set as Set
import Foreign.Marshal.Error
import System.Directory
import System.Process hiding (shell)
import Text.Printf
import Development.Abba.DependencyGraph
import Development.Abba.Types
buildTargets
:: Set Rule
-> DependencyGraph
-> [Dependency]
-> IO ()
buildTargets rules dependencyGraph targets = do
let
orderedNodes
:: [[Node]]
= map (\n -> reverse $ (bfs n dependencyGraph)) startNodes
orderedTargets
:: [[Dependency]]
= (map . map) (\n -> fromJust $ lookup n lNodes) orderedNodes
orderedRules
:: [[Rule]]
= (map . map)
(\t -> fromJust $ find (t `isTargetOf`) (Set.toList rules))
orderedTargets
mapM_ (mapM_ build) orderedRules
where
startNodes
:: [Node]
= map (\t -> errorOnNothing (printf "no rule to build target %s" t)
$ getNodeFromDependency lNodes t)
targets
lNodes
:: [DependencyNode]
= labNodes dependencyGraph
build
:: Rule
-> IO ()
build (Rule {targets, dependencies, recipe=maybeRecipe})
= case maybeRecipe of
Just recipe -> do
anyOutOfSync :: Bool
<- fmap or $ mapM isOutOfSync (dependencies ++ targets)
if anyOutOfSync
then
recipe targets dependencies
else
return ()
Nothing -> return ()
isTargetOf
:: String
-> Rule
-> Bool
isTargetOf target (Rule {targets})
= target `elem` targets
-- |Determine if a node is out of sync with other nodes.
isOutOfSync
:: String
-> IO Bool
isOutOfSync _ = return True
errorOnNothing
:: String
-> Maybe a
-> a
errorOnNothing errorMessage maybeValue
= case maybeValue of
Just value -> value
Nothing -> error errorMessage
shell
:: String
-> [String]
-> IO ()
shell command arguments
= do
putStrLn $ printf "executing: %s %s" command (unwords arguments)
void $ rawSystem command arguments
-- |Remove a file or directory, logging the action.
--
-- This is intended to be used in "clean" rules, where built files are
-- removed.
clean
:: FilePath
-> IO ()
clean filePath = do
fileExists <- doesFileExist filePath
directoryExists <- doesDirectoryExist filePath
if fileExists || directoryExists
then do
putStrLn $ printf "cleaning %s..." filePath
if fileExists
then removeFile filePath
else removeDirectory filePath
else return ()
|
mgeorgehansen/Abba
|
Development/Abba/Core.hs
|
bsd-3-clause
| 2,896 | 0 | 17 | 918 | 755 | 396 | 359 | -1 | -1 |
module Language.Pali
-- -- $Id$
( pali
, nopali
)
where
import Language.Type
import Autolib.Util.Zufall
import Autolib.Set
import Data.List (intersperse)
pali :: String -> Language
pali sigma =
Language
{ abbreviation = foldl1 (++) [ "{ w | w in {"
, intersperse ',' sigma
, "}^* und w == reverse w }"
]
, nametag = "Pali"
, alphabet = mkSet sigma
, contains = is_pali
, sample = sam sigma
, anti_sample = anti_sam sigma
}
is_pali w = w == reverse w
nopali :: String -> Language
nopali sigma = ( komplement $ pali sigma )
{ nametag = "ComPali"
, abbreviation = foldl1 (++) [ "{ w | w in {"
, intersperse ',' sigma
, "}^* und w != reverse w }"
]
}
-------------------------------------------------------------------------
sam :: RandomC m
=> String -> Int -> Int
-> m [ String ]
sam _ 0 n = return []
sam _ c 0 = return [ [] ]
sam sigma c n = do
let (q, r) = divMod n 2
sequence $ replicate c $ do
w <- someIO sigma (q + r)
return $ w ++ drop r (reverse w)
anti_sam :: RandomC m
=> String -> Int -> Int
-> m [ String ]
anti_sam _ 0 n = return []
anti_sam _ c n | n < 2 = return []
anti_sam sigma c n = sequence $ replicate c $ do
r <- randomRIO (n `div` 3, n `div` 2 - 1)
let l = length sigma
-- würfle zwei verschiedene Buchstaben x und y
i <- randomRIO (0, l-1)
d <- randomRIO (1, l-1)
let x = sigma !! i
y = sigma !! ( (i+d) `mod` l )
w <- someIO sigma r
v <- someIO sigma (n-2)
return $ w ++ [x] ++ v ++ [y] ++ reverse w
|
florianpilz/autotool
|
src/Language/Pali.hs
|
gpl-2.0
| 1,652 | 15 | 19 | 537 | 652 | 339 | 313 | 50 | 1 |
{-# LANGUAGE CPP #-}
-- -*-haskell-*-
-- GIMP Toolkit (GTK) CustomStore TreeModel
--
-- Author : Duncan Coutts, Axel Simon
--
-- Created: 11 Feburary 2006
--
-- Copyright (C) 2005 Duncan Coutts, Axel Simon
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- |
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable (depends on GHC)
--
-- Standard model to store list data.
--
module Graphics.UI.Gtk.ModelView.ListStore (
-- * Types
ListStore,
-- * Constructors
listStoreNew,
listStoreNewDND,
-- * Implementation of Interfaces
listStoreDefaultDragSourceIface,
listStoreDefaultDragDestIface,
-- * Methods
listStoreIterToIndex,
listStoreGetValue,
listStoreSafeGetValue,
listStoreSetValue,
listStoreToList,
listStoreGetSize,
listStoreInsert,
listStorePrepend,
listStoreAppend,
listStoreRemove,
listStoreClear,
) where
import Control.Monad (liftM, when)
import Data.IORef
import Data.Ix (inRange)
#if __GLASGOW_HASKELL__>=606
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.Foldable as F
#else
import qualified Graphics.UI.Gtk.ModelView.Sequence as Seq
import Graphics.UI.Gtk.ModelView.Sequence (Seq)
#endif
import Graphics.UI.Gtk.Types (GObjectClass(..))
-- import Graphics.UI.Gtk.ModelView.Types ()
import Graphics.UI.Gtk.ModelView.CustomStore
import Graphics.UI.Gtk.ModelView.TreeModel
import Graphics.UI.Gtk.ModelView.TreeDrag
import Control.Monad.Trans ( liftIO )
newtype ListStore a = ListStore (CustomStore (IORef (Seq a)) a)
instance TypedTreeModelClass ListStore
instance TreeModelClass (ListStore a)
instance GObjectClass (ListStore a) where
toGObject (ListStore tm) = toGObject tm
unsafeCastGObject = ListStore . unsafeCastGObject
-- | Create a new 'TreeModel' that contains a list of elements.
listStoreNew :: [a] -> IO (ListStore a)
listStoreNew xs = listStoreNewDND xs (Just listStoreDefaultDragSourceIface)
(Just listStoreDefaultDragDestIface)
-- | Create a new 'TreeModel' that contains a list of elements. In addition, specify two
-- interfaces for drag and drop.
--
listStoreNewDND :: [a] -- ^ the initial content of the model
-> Maybe (DragSourceIface ListStore a) -- ^ an optional interface for drags
-> Maybe (DragDestIface ListStore a) -- ^ an optional interface to handle drops
-> IO (ListStore a) -- ^ the new model
listStoreNewDND xs mDSource mDDest = do
rows <- newIORef (Seq.fromList xs)
customStoreNew rows ListStore TreeModelIface {
treeModelIfaceGetFlags = return [TreeModelListOnly],
treeModelIfaceGetIter = \[n] -> readIORef rows >>= \rows ->
return (if Seq.null rows then Nothing else
Just (TreeIter 0 (fromIntegral n) 0 0)),
treeModelIfaceGetPath = \(TreeIter _ n _ _) -> return [fromIntegral n],
treeModelIfaceGetRow = \(TreeIter _ n _ _) ->
readIORef rows >>= \rows ->
if inRange (0, Seq.length rows - 1) (fromIntegral n)
then return (rows `Seq.index` fromIntegral n)
else fail "ListStore.getRow: iter does not refer to a valid entry",
treeModelIfaceIterNext = \(TreeIter _ n _ _) ->
readIORef rows >>= \rows ->
if inRange (0, Seq.length rows - 1) (fromIntegral (n+1))
then return (Just (TreeIter 0 (n+1) 0 0))
else return Nothing,
treeModelIfaceIterChildren = \_ -> return Nothing,
treeModelIfaceIterHasChild = \_ -> return False,
treeModelIfaceIterNChildren = \index -> readIORef rows >>= \rows ->
case index of
Nothing -> return $! Seq.length rows
_ -> return 0,
treeModelIfaceIterNthChild = \index n -> case index of
Nothing -> return (Just (TreeIter 0 (fromIntegral n) 0 0))
_ -> return Nothing,
treeModelIfaceIterParent = \_ -> return Nothing,
treeModelIfaceRefNode = \_ -> return (),
treeModelIfaceUnrefNode = \_ -> return ()
} mDSource mDDest
-- | Convert a 'TreeIter' to an an index into the 'ListStore'. Note that this
-- function merely extracts the second element of the 'TreeIter'.
listStoreIterToIndex :: TreeIter -> Int
listStoreIterToIndex (TreeIter _ n _ _) = fromIntegral n
-- | Default drag functions for 'Graphics.UI.Gtk.ModelView.ListStore'. These
-- functions allow the rows of the model to serve as drag source. Any row is
-- allowed to be dragged and the data set in the 'SelectionDataM' object is
-- set with 'treeSetRowDragData', i.e. it contains the model and the
-- 'TreePath' to the row.
listStoreDefaultDragSourceIface :: DragSourceIface ListStore row
listStoreDefaultDragSourceIface = DragSourceIface {
treeDragSourceRowDraggable = \_ _-> return True,
treeDragSourceDragDataGet = treeSetRowDragData,
treeDragSourceDragDataDelete = \model (dest:_) -> do
liftIO $ listStoreRemove model dest
return True
}
-- | Default drop functions for 'Graphics.UI.Gtk.ModelView.ListStore'. These
-- functions accept a row and insert the row into the new location if it is
-- dragged into a tree view
-- that uses the same model.
listStoreDefaultDragDestIface :: DragDestIface ListStore row
listStoreDefaultDragDestIface = DragDestIface {
treeDragDestRowDropPossible = \model dest -> do
mModelPath <- treeGetRowDragData
case mModelPath of
Nothing -> return False
Just (model', source) -> return (toTreeModel model==toTreeModel model'),
treeDragDestDragDataReceived = \model (dest:_) -> do
mModelPath <- treeGetRowDragData
case mModelPath of
Nothing -> return False
Just (model', (source:_)) ->
if toTreeModel model/=toTreeModel model' then return False
else liftIO $ do
row <- listStoreGetValue model source
listStoreInsert model dest row
return True
}
-- | Extract the value at the given index.
--
listStoreGetValue :: ListStore a -> Int -> IO a
listStoreGetValue (ListStore model) index =
readIORef (customStoreGetPrivate model) >>= return . (`Seq.index` index)
-- | Extract the value at the given index.
--
listStoreSafeGetValue :: ListStore a -> Int -> IO (Maybe a)
listStoreSafeGetValue (ListStore model) index = do
seq <- readIORef (customStoreGetPrivate model)
return $ if index >=0 && index < Seq.length seq
then Just $ seq `Seq.index` index
else Nothing
-- | Update the value at the given index. The index must exist.
--
listStoreSetValue :: ListStore a -> Int -> a -> IO ()
listStoreSetValue (ListStore model) index value = do
modifyIORef (customStoreGetPrivate model) (Seq.update index value)
stamp <- customStoreGetStamp model
treeModelRowChanged model [index] (TreeIter stamp (fromIntegral index) 0 0)
-- | Extract all data from the store.
--
listStoreToList :: ListStore a -> IO [a]
listStoreToList (ListStore model) =
liftM
#if __GLASGOW_HASKELL__>=606
F.toList
#else
Seq.toList
#endif
$ readIORef (customStoreGetPrivate model)
-- | Query the number of elements in the store.
listStoreGetSize :: ListStore a -> IO Int
listStoreGetSize (ListStore model) =
liftM Seq.length $ readIORef (customStoreGetPrivate model)
-- | Insert an element in front of the given element. The element is appended
-- if the index is greater or equal to the size of the list.
listStoreInsert :: ListStore a -> Int -> a -> IO ()
listStoreInsert (ListStore model) index value = do
seq <- readIORef (customStoreGetPrivate model)
when (index >= 0) $ do
let index' | index > Seq.length seq = Seq.length seq
| otherwise = index
writeIORef (customStoreGetPrivate model) (insert index' value seq)
stamp <- customStoreGetStamp model
treeModelRowInserted model [index'] (TreeIter stamp (fromIntegral index') 0 0)
where insert :: Int -> a -> Seq a -> Seq a
insert i x xs = front Seq.>< x Seq.<| back
where (front, back) = Seq.splitAt i xs
-- | Prepend the element to the store.
listStorePrepend :: ListStore a -> a -> IO ()
listStorePrepend (ListStore model) value = do
modifyIORef (customStoreGetPrivate model)
(\seq -> value Seq.<| seq)
stamp <- customStoreGetStamp model
treeModelRowInserted model [0] (TreeIter stamp 0 0 0)
---- | Prepend a list to the store. Not implemented yet.
--listStorePrependList :: ListStore a -> [a] -> IO ()
--listStorePrependList store list =
-- mapM_ (listStoreInsert store 0) (reverse list)
-- | Append an element to the store. Returns the index of the inserted
-- element.
listStoreAppend :: ListStore a -> a -> IO Int
listStoreAppend (ListStore model) value = do
index <- atomicModifyIORef (customStoreGetPrivate model)
(\seq -> (seq Seq.|> value, Seq.length seq))
stamp <- customStoreGetStamp model
treeModelRowInserted model [index] (TreeIter stamp (fromIntegral index) 0 0)
return index
{-
listStoreAppendList :: ListStore a -> [a] -> IO ()
listStoreAppendList (ListStore model) values = do
seq <- readIORef (customStoreGetPrivate model)
let seq' = Seq.fromList values
startIndex = Seq.length seq
endIndex = startIndex + Seq.length seq' - 1
writeIORef (customStoreGetPrivate model) (seq Seq.>< seq')
stamp <- customStoreGetStamp model
flip mapM [startIndex..endIndex] $ \index ->
treeModelRowInserted model [index] (TreeIter stamp (fromIntegral index) 0 0)
-}
-- | Remove the element at the given index.
--
listStoreRemove :: ListStore a -> Int -> IO ()
listStoreRemove (ListStore model) index = do
seq <- readIORef (customStoreGetPrivate model)
when (index >=0 && index < Seq.length seq) $ do
writeIORef (customStoreGetPrivate model) (delete index seq)
treeModelRowDeleted model [index]
where delete :: Int -> Seq a -> Seq a
delete i xs = front Seq.>< Seq.drop 1 back
where (front, back) = Seq.splitAt i xs
-- | Empty the store.
listStoreClear :: ListStore a -> IO ()
listStoreClear (ListStore model) =
-- Since deleting rows can cause callbacks (eg due to selection changes)
-- we have to make sure the model is consitent with the view at each
-- intermediate step of clearing the store. Otherwise at some intermediate
-- stage when the view has only been informed about some delections, the
-- user might query the model expecting to find the remaining rows are there
-- but find them deleted. That'd be bad.
--
let loop (-1) Seq.EmptyR = return ()
loop n (seq Seq.:> _) = do
writeIORef (customStoreGetPrivate model) seq
treeModelRowDeleted model [n]
loop (n-1) (Seq.viewr seq)
in do seq <- readIORef (customStoreGetPrivate model)
loop (Seq.length seq - 1) (Seq.viewr seq)
---- | Permute the rows of the store. Not yet implemented.
--listStoreReorder :: ListStore a -> [Int] -> IO ()
--listStoreReorder store = undefined
--
---- | Swap two rows of the store. Not yet implemented.
--listStoreSwap :: ListStore a -> Int -> Int -> IO ()
--listStoreSwap store = undefined
--
---- | Move the element at the first index in front of the element denoted by
---- the second index. Not yet implemented.
--listStoreMoveBefore :: ListStore a -> Int -> Int -> IO ()
--listStoreMoveBefore store = undefined
--
---- | Move the element at the first index past the element denoted by the
---- second index. Not yet implemented.
--listStoreMoveAfter :: ListStore a -> Int -> Int -> IO ()
--listStoreMoveAfter store = undefined
|
k0001/gtk2hs
|
gtk/Graphics/UI/Gtk/ModelView/ListStore.hs
|
gpl-3.0
| 12,452 | 0 | 20 | 2,961 | 2,494 | 1,315 | 1,179 | 163 | 6 |
{-
A first example in equalional reasoning.
From the definition of append we should be able to
semi-automatically prove the three axioms.
-}
{-@ LIQUID "--no-termination" @-}
module Append where
data L a = N | C a (L a) deriving (Eq)
data Proof = Proof
append :: L a -> L a -> L a
append N xs = xs
append (C y ys) xs = C y (append ys xs)
{- All the followin will be autocatically generated by the definition of append
and a liquid annotation
axiomatize append
-}
{-@ measure append :: L a -> L a -> L a @-}
{-@ assume append :: xs:L a -> ys:L a -> {v:L a | v == append xs ys } @-}
{-@ assume axiom_append_nil :: xs:L a -> {v:Proof | append N xs == xs} @-}
axiom_append_nil :: L a -> Proof
axiom_append_nil xs = Proof
{-@ assume axiom_append_cons :: x:a -> xs: L a -> ys: L a
-> {v:Proof | append (C x xs) ys == C x (append xs ys) } @-}
axiom_append_cons :: a -> L a -> L a -> Proof
axiom_append_cons x xs ys = Proof
-- | Proof library:
{-@ toProof :: l:a -> r:{a|l = r} -> {v:Proof | l = r } @-}
toProof :: a -> a -> Proof
toProof x y = Proof
{-@ eqProof :: l:a -> r:a -> {v:Proof | l = r} -> {v:a | v = l } @-}
eqProof :: a -> a -> Proof -> a
eqProof x y _ = y
-- | Proof 1: N is neutral element
{-@ prop_nil :: xs:L a -> {v:Proof | (append xs N == xs) <=> true } @-}
prop_nil :: Eq a => L a -> Proof
prop_nil N = axiom_append_nil N
prop_nil (C x xs) = toProof e1 $ eqProof e1 (eqProof e2 e3 pr2) pr1
where
e1 = append (C x xs) N
pr1 = prop_nil xs
e2 = C x (append xs N)
pr2 = prop_nil xs
e3 = C x xs
-- | Proof 2: append is associative
{-@ prop_assoc :: xs:L a -> ys:L a -> zs:L a
-> {v:Proof | (append (append xs ys) zs == append N (append ys zs))} @-}
prop_assoc :: Eq a => L a -> L a -> L a -> Proof
prop_assoc N ys zs = toProof (append (append N ys) zs) $
eqProof (append (append N ys) zs)
(eqProof (append ys zs)
(append N (append ys zs))
(axiom_append_nil (append ys zs))
)(axiom_append_nil ys)
prop_assoc (C x xs) ys zs =
toProof e1 $
eqProof e1 (eqProof e2 (eqProof e3 (eqProof e4 e5 pr4) pr3) pr2) pr1
where
e1 = append (append (C x xs) ys) zs
pr1 = axiom_append_cons x xs ys
e2 = append (C x (append xs ys)) zs
pr2 = axiom_append_cons x (append xs ys) zs
e3 = C x (append (append xs ys) zs)
pr3 = prop_assoc xs ys zs
e4 = C x (append xs (append ys zs))
pr4 = axiom_append_cons x xs (append ys zs)
e5 = append (C x xs) (append ys zs)
|
abakst/liquidhaskell
|
tests/equationalproofs/neg/Append.hs
|
bsd-3-clause
| 2,627 | 6 | 12 | 805 | 768 | 388 | 380 | 41 | 1 |
{-# LANGUAGE MagicHash #-}
module Main where
import GHC.Prim
data A = A Word# deriving Show
main = print (A (int2Word# 4#))
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/deriving/should_run/T8280.hs
|
bsd-3-clause
| 127 | 0 | 9 | 25 | 42 | 24 | 18 | 5 | 1 |
{-# LANGUAGE
RankNTypes, ScopedTypeVariables #-}
module Paths where
import ClassyPrelude
import Patterns
data Sel = SelTitle TitlePat | SelIndex Int
instance Show Sel where
show (SelTitle t) = unpack $ renderTitlePat t
show (SelIndex i) = show i
data MSel = MSelList [Sel]
instance Show MSel where
show (MSelList ss) = intercalate "," (map show ss)
-- | Just a path to a note.
type Path = [Sel]
showPath :: Path -> Text
showPath = intercalate "/" . map tshow
-- | A path which chooses multiple notes.
type MPath = [MSel]
showMPath :: MPath -> Text
showMPath = intercalate "/" . map tshow
-- | Currently is the same as root path.
currentNote :: Path
currentNote = []
rootNote :: Path
rootNote = []
|
aelve/Jane
|
Paths.hs
|
mit
| 719 | 0 | 8 | 147 | 211 | 115 | 96 | 22 | 1 |
module GameTypes.ClientGame where
import Net.Communication (send, connect, receive)
import Net.Protocol (Message(..))
import System.IO (hClose)
import TicTacToe (Token(..))
import Players.LocalPlayer
import Players.RemotePlayer
cleanUp :: (RemotePlayer, LocalPlayer) -> IO ()
cleanUp ((RemotePlayer _ _ hdl), _) = do
hClose hdl
-- Joins a server by connecting to a host and exchanging
-- hello's with the host.
create :: IO (RemotePlayer, LocalPlayer)
create = do
putStrLn "Enter the name of the host"
host <- getLine
hdl <- connect host 2345
putStrLn "What's your name?"
oPlayer <- getLine
(Hello oPlayer) `send` hdl
(Hello xPlayer) <- receive hdl
return ((RemotePlayer xPlayer X hdl), (LocalPlayer oPlayer O hdl Nothing))
|
davidarnarsson/tictactoe
|
GameTypes/ClientGame.hs
|
mit
| 807 | 0 | 10 | 186 | 242 | 129 | 113 | 20 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Distribution.Archlinux.PackageInfo.Parse
( comment
, definition
, Definition
, field
, pkginfo
, value
) where
import Data.Attoparsec.Char8
import Control.Applicative ((<*), (<|>))
import qualified Data.Attoparsec.Char8 as A8
import qualified Data.Attoparsec as A
import qualified Data.ByteString as B
type Definition = (B.ByteString, B.ByteString)
comment :: Parser B.ByteString
comment = char '#' >> A.takeTill isEndOfLine <* endOfLine <?> "comment"
skipSpaces :: Parser ()
skipSpaces = skipWhile isSpace
field :: Parser B.ByteString
field = A.takeTill isHorizontalSpace <?> "field"
value :: Parser B.ByteString
value = A.takeTill isEndOfLine <* endOfLine <?> "value"
-- |Parses a key-value pair (e.g. \"foo = bar\").
definition :: Parser Definition
definition = do
f <- field
string " = "
v <- value
return (f, v) <?> "definition"
-- |Parses the PKGINFO format.
pkginfo :: Parser [Definition]
pkginfo = skipMany comment >> many definition
-- |Ignore the return value of 'Parser' /p/.
skip :: Parser a -> Parser ()
skip p = p >> return ()
|
sebnow/archlinux-pacman
|
Distribution/Archlinux/PackageInfo/Parse.hs
|
mit
| 1,136 | 0 | 9 | 213 | 310 | 172 | 138 | 32 | 1 |
module Attacker where
import Creature
class (Creature a) => Attacker a where
damage :: a -> Int
dealDamage :: (Attacker a, Creature c) => a -> c -> c
dealDamage attacker = receiveDamage (damage attacker)
duel :: Attacker a => a -> a -> (a, a)
duel = duel' True
where duel' isAttacking off def
| isAlive off && isAlive def = duel' (not isAttacking) (dealDamage off def) off
| isAttacking = (off, def)
| otherwise = (def, off)
|
StanislavKhalash/cruel-world-hs
|
src/Attacker.hs
|
mit
| 467 | 0 | 11 | 121 | 194 | 99 | 95 | 12 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Handler.Scim.Auth (
scimAuthHandler
) where
import Handler (HandlerFunc)
import ByteStringTools
import Network.Socket
import Network.Socket.ByteString (sendAllTo, recvFrom)
import qualified Data.ByteString.Lazy as L (ByteString, take, pack, unpack, length, intercalate)
import qualified Data.ByteString as B (ByteString, pack, intercalate, length)
import qualified Data.ByteString.Char8 as C (pack)
import Data.Word (Word8, Word32)
import Data.Binary (encode)
import Data.Bits (shiftL, (.|.))
import Database.HDBC
import Database.HDBC.PostgreSQL
import Data.ByteString.Internal (w2c, c2w)
scimAuthHandler :: HandlerFunc
scimAuthHandler sock addr pkt =
scimHandler sock addr pkt (take 2 (L.unpack pkt))
scimHandler :: Socket -> SockAddr -> L.ByteString -> [Word8] -> IO ()
scimHandler sock addr pkt [0x00, 0x00] = do
conn <- connectPostgreSQL "dbname=scim_auth"
let pktL = L.unpack pkt
let name = take (fromIntegral (pktL!!2 :: Word8)) (drop 4 pktL)
let passwd = take (fromIntegral (pktL!!3 :: Word8)) (drop 36 pktL)
r <- quickQuery' conn
"SELECT id FROM account WHERE email=? AND password=?" [toSql (B.pack name), toSql (B.pack passwd)]
putStrLn $ show (B.pack name) ++ "\n"
++ show (B.pack passwd)
let res = map convRow r -- returns [[SqlValue]]; in this case will return [[SqlValue id], [SqlValue id], ...]
mapM_ putStrLn res
let id = read (res!!0) :: Word8 -- reads id; should only be one element in list e.g. [SqlValue id]
if (res /= [])
then do r <- quickQuery' conn "UPDATE account SET online=true WHERE id=?" [SqlInteger (fromIntegral id)]
sendAllTo sock (B.pack [id]) addr
else sendAllTo sock (B.pack ([0x00] :: [Word8])) addr
commit conn
disconnect conn
scimHandler sock addr pkt [0x00, 0x03] = do
conn <- connectPostgreSQL "dbname=scim_auth"
let pktL = L.unpack pkt
putStrLn $ show pktL
let id = take 8 (drop 2 pktL)
putStrLn $ show (fromOctets id)
r <- quickQuery' conn
"SELECT online FROM account WHERE id=?" [toSql (fromOctets id)]
let res = map convRow r
let id = read (res!!0) :: Integer
if (res /= [])
then do r1 <- quickQuery' conn "SELECT address,port FROM portal ORDER BY address,port" []
let res1 = map convRow r1
mapM_ (\a -> sendAllTo sock (C.pack a) addr) res1
else sendAllTo sock (B.pack [0x00]) addr
disconnect conn
scimHandler sock addr pkt _ =
sendAllTo sock "invalid packet type" addr
fromOctets :: [Word8] -> Word32 -- convert Word8 to Word32
fromOctets = foldr accum 0
where
accum :: Word8 -> Word32 -> Word32
accum a o = (o `shiftL` 8) .|. (fromIntegral a)
convRow [id] =
desc id
convRow [id, passwd] =
(desc id) ++ " " ++ (desc passwd)
desc :: SqlValue -> String
desc sqlDesc = case fromSql sqlDesc of
Just x -> x
Nothing -> "NULL"
|
stnma7e/scim_serv
|
src/Handler/Scim/Auth.hs
|
mit
| 2,964 | 0 | 16 | 680 | 1,029 | 532 | 497 | 68 | 3 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( getApplicationDev
, appMain
, develMain
, makeFoundation
-- * for DevelMain
, getApplicationRepl
, shutdownApp
-- * for GHCI
, handler
, db
) where
import Control.Monad.Logger (liftLoc, runLoggingT)
import Database.Persist.Postgresql (createPostgresqlPool, pgConnStr,
pgPoolSize, runSqlPool)
import Import
import Language.Haskell.TH.Syntax (qLocation)
import Network.Wai (Middleware)
import Network.Wai.Handler.Warp (Settings, defaultSettings,
defaultShouldDisplayException,
runSettings, setHost,
setOnException, setPort, getPort)
import Network.Wai.Middleware.RequestLogger (Destination (Logger),
IPAddrSource (..),
OutputFormat (..), destination,
mkRequestLogger, outputFormat)
import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet,
toLogStr)
-- Used only in Application.hs
import qualified Data.Map as Map
import Control.Monad.Reader (ReaderT (..))
import Database.Persist.Sql (runMigration)
import Network.HTTP.Client.Conduit (newManager)
import Data.Default (def)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Common
import Handler.Home
import Handler.Help
import Handler.Thread
import Handler.Board
import Handler.Catalog
import Handler.Bookmarks
import Handler.Edit
import Handler.Feed
import Handler.Delete
import Handler.EventSource
import Handler.Admin
import Handler.Admin.Ban
import Handler.Admin.Hellban
import Handler.Admin.Board
import Handler.Admin.Config
import Handler.Admin.Group
import Handler.Admin.User
import Handler.Admin.Modlog
import Handler.Admin.Search
import Handler.Admin.Delete
import Handler.Admin.Wordfilter
import Handler.Admin.Reports
import Handler.Ajax
import Handler.Settings
import Handler.Captcha
import Handler.RSS
import Handler.Search
import Handler.API
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- | This function allocates resources (such as a database connection pool),
-- performs initialization and return a foundation datatype value. This is also
-- the place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeFoundation :: AppSettings -> IO App
makeFoundation appSettings = do
-- Some basic initializations: HTTP connection manager, logger, and static
-- subsite.
appHttpManager <- newManager
appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger
appStatic <-
(if appMutableStatic appSettings then staticDevel else static)
(appStaticDir appSettings)
appSSEClients <- newTVarIO Map.empty
appSSEChan <- atomically newBroadcastTChan
-- We need a log function to create a connection pool. We need a connection
-- pool to create our foundation. And we need our foundation to get a
-- logging function. To get out of this loop, we initially create a
-- temporary foundation without a real connection pool, get a log function
-- from there, and then create the real foundation.
let mkFoundation appConnPool = App {..}
-- The App {..} syntax is an example of record wild cards. For more
-- information, see:
-- https://ocharles.org.uk/blog/posts/2014-12-04-record-wildcards.html
tempFoundation = mkFoundation $ error "connPool forced in tempFoundation"
logFunc = messageLoggerSource tempFoundation appLogger
-- Create the database connection pool
pool <- flip runLoggingT logFunc $ createPostgresqlPool
(pgConnStr $ appDatabaseConf appSettings)
(pgPoolSize $ appDatabaseConf appSettings)
-- Perform database migration using our application's logging settings.
runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc
-- Return the foundation
return $ mkFoundation pool
makeApplication :: App -> IO Application
makeApplication foundation = do
logWare <- makeLogWare foundation
-- Create the WAI application and apply middlewares
appPlain <- toWaiAppPlain foundation
return $ logWare $ defaultMiddlewaresNoLogging appPlain
makeLogWare :: App -> IO Middleware
makeLogWare foundation =
mkRequestLogger def
{ outputFormat =
if appDetailedRequestLogging $ appSettings foundation
then Detailed True
else Apache
(if appIpFromHeader $ appSettings foundation
then FromFallback
else FromSocket)
, destination = Logger $ loggerSet $ appLogger foundation
}
-- | Warp settings for the given foundation value.
warpSettings :: App -> Settings
warpSettings foundation =
setPort (appPort $ appSettings foundation)
$ setHost (appHost $ appSettings foundation)
$ setOnException (\_req e ->
when (defaultShouldDisplayException e) $ messageLoggerSource
foundation
(appLogger foundation)
$(qLocation >>= liftLoc)
"yesod"
LevelError
(toLogStr $ "Exception from Warp: " ++ show e))
defaultSettings
-- | For yesod devel, return the Warp settings and WAI Application.
getApplicationDev :: IO (Settings, Application)
getApplicationDev = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app <- makeApplication foundation
return (wsettings, app)
getAppSettings :: IO AppSettings
getAppSettings = loadYamlSettings [configSettingsYml] [] useEnv
-- | main function for use by yesod devel
develMain :: IO ()
develMain = develMainHelper getApplicationDev
-- | The @main@ function for an executable running this site.
appMain :: IO ()
appMain = do
-- Get the settings from all relevant sources
settings <- loadYamlSettingsArgs
-- fall back to compile-time values, set to [] to require values at runtime
[configSettingsYmlValue]
-- allow environment variables to override
useEnv
-- Generate the foundation from the settings
foundation <- makeFoundation settings
-- Generate a WAI Application from the foundation
app <- makeApplication foundation
-- Run the application with Warp
runSettings (warpSettings foundation) app
--------------------------------------------------------------
-- Functions for DevelMain.hs (a way to run the app from GHCi)
--------------------------------------------------------------
getApplicationRepl :: IO (Int, App, Application)
getApplicationRepl = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app1 <- makeApplication foundation
return (getPort wsettings, foundation, app1)
shutdownApp :: App -> IO ()
shutdownApp _ = return ()
---------------------------------------------
-- Functions for use in development with GHCi
---------------------------------------------
-- | Run a handler
handler :: Handler a -> IO a
handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h
-- | Run DB queries
db :: ReaderT SqlBackend (HandlerFor App) a -> IO a
db = handler . runDB
|
ahushh/Monaba
|
monaba/src/Application.hs
|
mit
| 7,802 | 0 | 13 | 1,887 | 1,266 | 695 | 571 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.