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 Zero.Bitfinex.Internal
(
Ticker(..)
, defaultTicker
) where
import GHC.Generics (Generic)
import Data.Aeson
import Data.Text (Text)
------------------------------------------------------------------------------
--
------------------------------------------------------------------------------
data Ticker = Ticker {
t_mid :: Text
, t_bid :: Text
, t_ask :: Text
, t_lastPrice :: Text
, t_low :: Text
, t_high :: Text
, t_volume :: Text
, t_timestamp :: Text
} deriving (Show, Generic)
defaultTicker =
Ticker "0.0" "0.0" "0.0" "0.0" "0.0" "0.0" "0.0" "TIMESTAMP"
instance FromJSON Ticker where
parseJSON = withObject "Ticker" $ \v -> Ticker
<$> v .: "mid"
<*> v .: "bid"
<*> v .: "ask"
<*> v .: "last_price"
<*> v .: "low"
<*> v .: "high"
<*> v .: "volume"
<*> v .: "timestamp"
instance ToJSON Ticker where
toJSON (Ticker a1 a2 a3 a4 a5 a6 a7 a8) =
object [
"mid" .= a1
, "bid" .= a2
, "ask" .= a3
, "last_price" .= a4
, "low" .= a5
, "high" .= a6
, "volume" .= a7
, "timestamp" .= a8
]
|
et4te/zero
|
src-shared/Zero/Bitfinex/Internal.hs
|
bsd-3-clause
| 1,140 | 0 | 23 | 310 | 321 | 181 | 140 | 40 | 1 |
module Opticover.Geometry.Calc.Box where
import Control.Lens
import Data.AEq
import Opticover.Geometry.Types
import Opticover.Ple
pointInBox :: Box -> Point -> Bool
pointInBox (Box pair) p =
let (p1, p2) = unPair pair
in p1 <= p && p <= p2
-- Hoping derived Ord instance do what we expect here
segmentBorderBox :: Segment -> Box
segmentBorderBox (Segment pair) = Box pair
|
s9gf4ult/opticover
|
src/Opticover/Geometry/Calc/Box.hs
|
bsd-3-clause
| 381 | 0 | 9 | 67 | 118 | 64 | 54 | 11 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ExistentialQuantification #-}
module Lib.Exception
( finally
, onException, onExceptionWith
, catch, handle
, bracket, bracket_, bracketOnError
, logErrors
, handleSync
, putLn
, swallowExceptions
) where
import qualified Control.Exception as E
#if MIN_VERSION_base(4,7,0)
import Control.Exception (SomeAsyncException)
#else
import Data.Typeable
#endif
import Data.Maybe (isJust)
import qualified System.IO as IO
import Prelude.Compat
putLn :: IO.Handle -> String -> IO ()
putLn h = swallowExceptions . IO.hPutStrLn h
swallowExceptions :: IO () -> IO ()
swallowExceptions = E.uninterruptibleMask_ . handle (\E.SomeException {} -> pure ())
infixl 1 `finally`
finally :: IO a -> IO () -> IO a
action `finally` cleanup =
E.mask $ \restore -> do
res <- restore action
`catch` \[email protected] {} -> do
cleanup `logErrors` ("overrides original error (" ++ show e ++ ")")
E.throwIO e
E.uninterruptibleMask_ cleanup `logErrors` "during successful finally cleanup"
pure res
infixl 1 `catch`
catch :: E.Exception e => IO a -> (e -> IO a) -> IO a
act `catch` handler = act `E.catch` (E.uninterruptibleMask_ . handler)
handle :: E.Exception e => (e -> IO a) -> IO a -> IO a
handle = flip catch
infixl 1 `onException`
onException :: IO a -> IO b -> IO a
onException act handler = E.onException act (E.uninterruptibleMask_ handler)
infixl 1 `onExceptionWith`
{-# INLINE onExceptionWith #-}
onExceptionWith :: IO a -> (E.SomeException -> IO ()) -> IO a
onExceptionWith act f =
act `E.catch` \e -> E.uninterruptibleMask_ (f e) >> E.throwIO e
infixl 1 `logErrors`
logErrors :: IO a -> String -> IO a
logErrors act prefix = onExceptionWith act $ \e ->
putLn IO.stderr (prefix ++ ": " ++ show e)
bracket :: IO a -> (a -> IO ()) -> (a -> IO b) -> IO b
bracket before after = E.bracket before (E.uninterruptibleMask_ . after)
bracket_ :: IO a -> IO () -> IO b -> IO b
bracket_ before after = E.bracket_ before (E.uninterruptibleMask_ after)
bracketOnError :: IO a -> (a -> IO ()) -> (a -> IO b) -> IO b
bracketOnError before after = E.bracketOnError before (E.uninterruptibleMask_ . after)
---------------------------------------------------------------------------
-- The following was copied from asynchronous-exceptions, as that package has been deprecated (and
-- requires base < 4.8)
---------------------------------------------------------------------------
#if !MIN_VERSION_base(4,7,0)
-- | Exception class for asynchronous exceptions
data SomeAsyncException
= forall e . E.Exception e => SomeAsyncException e
deriving Typeable
instance E.Exception SomeAsyncException
instance Show SomeAsyncException where
showsPrec p (SomeAsyncException e) = showsPrec p e
#endif
isAsynchronous :: E.SomeException -> Bool
isAsynchronous e =
isJust (E.fromException e :: Maybe E.AsyncException) ||
isJust (E.fromException e :: Maybe SomeAsyncException)
-- | Like 'catch', but catch any synchronous exceptions; let asynchronous ones pass through
catchSync :: IO a -> (E.SomeException -> IO a) -> IO a
catchSync a h =
E.catch a $ \e ->
if isAsynchronous e
then E.throwIO e
else h e
-- | Like 'handle', but catch any synchronous exceptions; let asynchronous ones pass through
handleSync :: (E.SomeException -> IO a) -> IO a -> IO a
handleSync = flip catchSync
---------------------------------------------------------------------------
|
buildsome/buildsome
|
src/Lib/Exception.hs
|
gpl-2.0
| 3,554 | 0 | 18 | 680 | 1,088 | 565 | 523 | 72 | 2 |
--
-- Copyright (c) 2012 Citrix Systems, Inc.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
--
{-# LANGUAGE ViewPatterns #-}
module Tools.Process (spawnShell
,spawnShell'
,safeSpawnShell
,getCurrentRunLevel
,readProcess
,readProcessOrDie
,readProcessOrDieWithEnv
,readProcess_closeFds
,readProcessWithExitCode_closeFds
,runInteractiveCommand_closeFds
)
where
import Data.List (intercalate)
import Data.Maybe
import System.Process
import System.Process.Internals (runGenProcess_)
import System.Exit
import System.Environment
import System.IO
import System.IO.Error
import Control.Concurrent
import Control.Monad
import qualified Control.Exception as E
import GHC.IO.Exception (IOErrorType(..))
-- ToDo: Consider actually parsing the output "unknown" instead of just relying on the ExitFailure?
getCurrentRunLevel :: IO (Maybe Int)
getCurrentRunLevel = (liftM.liftM) parse $ spawnShell' "runlevel" where
parse (words -> [prevStr, read -> current]) = current
-- Execute shell command and wait for its output, return empty string in case of exit failure
spawnShell :: String -> IO String
spawnShell cmd =
spawnShell' cmd >>= f where f Nothing = return ""
f (Just s) = return s
-- Execute shell command and wait for its output, return Nothing on failure exit code
spawnShell' :: String -> IO (Maybe String)
spawnShell' cmd =
runInteractiveCommand_closeFds cmd >>= \ (_, stdout, _, h) ->
do contents <- hGetContents stdout
-- force evaluation of contents
exitCode <- length contents `seq` waitForProcess h
case exitCode of
ExitSuccess -> return $ Just contents
_ -> return Nothing
-- Execute shell command and wait for its output, cause exception on failure exit code
safeSpawnShell :: String -> IO String
safeSpawnShell cmd =
spawnShell' cmd >>= f where
f Nothing = error $ message
f (Just s) = return s
message = "shell command: " ++ cmd ++ " FAILED."
readProcessWithEnv' :: [(String,String)] -> FilePath -> [String] -> String -> IO (Maybe String)
readProcessWithEnv' extraEnv p xs i = fmap from $ readProcessWithEnvAndExitCode_closeFds extraEnv p xs i where
from ( ExitSuccess, o, _) = Just o
from ((ExitFailure _), _, _) = Nothing
readProcess' :: FilePath -> [String] -> String -> IO (Maybe String)
readProcess' = readProcessWithEnv' []
readProcessOrDie :: FilePath -> [String] -> String -> IO String
readProcessOrDie p xs i = from =<< readProcess' p xs i where
from (Just r) = return r
from Nothing = error $ "command: " ++ show cmd ++ " FAILED."
cmd = p ++ " " ++ (intercalate " " xs)
readProcessOrDieWithEnv :: [(String,String)] -> FilePath -> [String] -> String -> IO String
readProcessOrDieWithEnv extraEnv p xs i = from =<< readProcessWithEnv' extraEnv p xs i where
from (Just r) = return r
from Nothing = error $ "command: " ++ show cmd ++ " FAILED."
cmd = p ++ (intercalate " " xs)
readProcessWithEnv_closeFds
:: [(String,String)] -- ^ extra environment variables
-> FilePath -- ^ command to run
-> [String] -- ^ any arguments
-> String -- ^ standard input
-> IO String -- ^ stdout + stderr
readProcessWithEnv_closeFds extraEnv cmd args input = do
newEnv <- if null extraEnv then return Nothing else ((Just . (extraEnv ++)) `fmap` getEnvironment)
(Just inh, Just outh, _, pid) <-
createProcess (proc cmd args){ std_in = CreatePipe,
std_out = CreatePipe,
std_err = Inherit,
close_fds = True,
env = newEnv }
-- fork off a thread to start consuming the output
output <- hGetContents outh
outMVar <- newEmptyMVar
_ <- forkIO $ E.evaluate (length output) >> putMVar outMVar ()
-- now write and flush any input
when (not (null input)) $ do hPutStr inh input; hFlush inh
hClose inh -- done with stdin
-- wait on the output
takeMVar outMVar
hClose outh
-- wait on the process
ex <- waitForProcess pid
case ex of
ExitSuccess -> return output
ExitFailure r ->
ioError (mkIOError OtherError ("readProcess: " ++ cmd ++
' ':unwords (map show args) ++
" (exit " ++ show r ++ ")")
Nothing Nothing)
readProcess_closeFds
:: FilePath -- ^ command to run
-> [String] -- ^ any arguments
-> String -- ^ standard input
-> IO String -- ^ stdout + stderr
readProcess_closeFds = readProcessWithEnv_closeFds []
readProcessWithExitCode_closeFds = readProcessWithEnvAndExitCode_closeFds []
readProcessWithEnvAndExitCode_closeFds
:: [(String, String)] -- ^ extra environment variables
-> FilePath -- ^ command to run
-> [String] -- ^ any arguments
-> String -- ^ standard input
-> IO (ExitCode,String,String) -- ^ exitcode, stdout, stderr
readProcessWithEnvAndExitCode_closeFds extraEnv cmd args input = do
newEnv <- if null extraEnv then return Nothing else ((Just . (extraEnv ++)) `fmap` getEnvironment)
(Just inh, Just outh, Just errh, pid) <-
createProcess (proc cmd args){ std_in = CreatePipe,
std_out = CreatePipe,
std_err = CreatePipe,
close_fds = True,
env = newEnv }
outMVar <- newEmptyMVar
-- fork off a thread to start consuming stdout
out <- hGetContents outh
forkIO $ E.evaluate (length out) >> putMVar outMVar ()
-- fork off a thread to start consuming stderr
err <- hGetContents errh
forkIO $ E.evaluate (length err) >> putMVar outMVar ()
-- now write and flush any input
when (not (null input)) $ do hPutStr inh input; hFlush inh
hClose inh -- done with stdin
-- wait on the output
takeMVar outMVar
takeMVar outMVar
hClose outh
-- wait on the process
ex <- waitForProcess pid
return (ex, out, err)
runInteractiveProcess1_closeFds
:: String
-> CreateProcess
-> IO (Handle,Handle,Handle,ProcessHandle)
runInteractiveProcess1_closeFds fun cmd = do
(mb_in, mb_out, mb_err, p) <-
runGenProcess_ fun
cmd{ std_in = CreatePipe,
std_out = CreatePipe,
std_err = CreatePipe,
close_fds = True}
Nothing Nothing
return (fromJust mb_in, fromJust mb_out, fromJust mb_err, p)
runInteractiveCommand_closeFds
:: String
-> IO (Handle,Handle,Handle,ProcessHandle)
runInteractiveCommand_closeFds string =
runInteractiveProcess1_closeFds "runInteractiveCommand_closeFds" (shell string)
|
OpenXT/xclibs
|
xchutils/Tools/Process.hs
|
lgpl-2.1
| 7,954 | 0 | 20 | 2,408 | 1,757 | 927 | 830 | 140 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.PackageDescription.Parse
-- Copyright : Isaac Jones 2003-2005
-- License : BSD3
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This defined parsers and partial pretty printers for the @.cabal@ format.
-- Some of the complexity in this module is due to the fact that we have to be
-- backwards compatible with old @.cabal@ files, so there's code to translate
-- into the newer structure.
module Distribution.PackageDescription.Parse (
-- * Package descriptions
readPackageDescription,
writePackageDescription,
parsePackageDescription,
showPackageDescription,
-- ** Parsing
ParseResult(..),
FieldDescr(..),
LineNo,
-- ** Supplementary build information
readHookedBuildInfo,
parseHookedBuildInfo,
writeHookedBuildInfo,
showHookedBuildInfo,
pkgDescrFieldDescrs,
libFieldDescrs,
executableFieldDescrs,
binfoFieldDescrs,
sourceRepoFieldDescrs,
testSuiteFieldDescrs,
flagFieldDescrs
) where
import Data.Char (isSpace)
import Data.Maybe (listToMaybe, isJust)
#if __GLASGOW_HASKELL__ < 710
import Data.Monoid ( Monoid(..) )
#endif
import Data.List (nub, unfoldr, partition, (\\))
import Control.Monad (liftM, foldM, when, unless, ap)
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative (Applicative(..))
#endif
import Control.Arrow (first)
import System.Directory (doesFileExist)
import qualified Data.ByteString.Lazy.Char8 as BS.Char8
import Data.Typeable
import Data.Data
import qualified Data.Map as Map
import Distribution.Text
( Text(disp, parse), display, simpleParse )
import Distribution.Compat.ReadP
((+++), option)
import qualified Distribution.Compat.ReadP as Parse
import Text.PrettyPrint
import Distribution.ParseUtils hiding (parseFields)
import Distribution.PackageDescription
import Distribution.PackageDescription.Utils
( cabalBug, userBug )
import Distribution.Package
( PackageIdentifier(..), Dependency(..), packageName, packageVersion )
import Distribution.ModuleName ( ModuleName )
import Distribution.Version
( Version(Version), orLaterVersion
, LowerBound(..), asVersionIntervals )
import Distribution.Verbosity (Verbosity)
import Distribution.Compiler (CompilerFlavor(..))
import Distribution.PackageDescription.Configuration (parseCondition, freeVars)
import Distribution.Simple.Utils
( die, dieWithLocation, warn, intercalate, lowercase, cabalVersion
, withFileContents, withUTF8FileContents
, writeFileAtomic, writeUTF8File )
-- -----------------------------------------------------------------------------
-- The PackageDescription type
pkgDescrFieldDescrs :: [FieldDescr PackageDescription]
pkgDescrFieldDescrs =
[ simpleField "name"
disp parse
packageName (\name pkg -> pkg{package=(package pkg){pkgName=name}})
, simpleField "version"
disp parse
packageVersion (\ver pkg -> pkg{package=(package pkg){pkgVersion=ver}})
, simpleField "cabal-version"
(either disp disp) (liftM Left parse +++ liftM Right parse)
specVersionRaw (\v pkg -> pkg{specVersionRaw=v})
, simpleField "build-type"
(maybe empty disp) (fmap Just parse)
buildType (\t pkg -> pkg{buildType=t})
, simpleField "license"
disp parseLicenseQ
license (\l pkg -> pkg{license=l})
-- We have both 'license-file' and 'license-files' fields.
-- Rather than declaring license-file to be deprecated, we will continue
-- to allow both. The 'license-file' will continue to only allow single
-- tokens, while 'license-files' allows multiple. On pretty-printing, we
-- will use 'license-file' if there's just one, and use 'license-files'
-- otherwise.
, simpleField "license-file"
showFilePath parseFilePathQ
(\pkg -> case licenseFiles pkg of
[x] -> x
_ -> "")
(\l pkg -> pkg{licenseFiles=licenseFiles pkg ++ [l]})
, listField "license-files"
showFilePath parseFilePathQ
(\pkg -> case licenseFiles pkg of
[_] -> []
xs -> xs)
(\ls pkg -> pkg{licenseFiles=ls})
, simpleField "copyright"
showFreeText parseFreeText
copyright (\val pkg -> pkg{copyright=val})
, simpleField "maintainer"
showFreeText parseFreeText
maintainer (\val pkg -> pkg{maintainer=val})
, simpleField "stability"
showFreeText parseFreeText
stability (\val pkg -> pkg{stability=val})
, simpleField "homepage"
showFreeText parseFreeText
homepage (\val pkg -> pkg{homepage=val})
, simpleField "package-url"
showFreeText parseFreeText
pkgUrl (\val pkg -> pkg{pkgUrl=val})
, simpleField "bug-reports"
showFreeText parseFreeText
bugReports (\val pkg -> pkg{bugReports=val})
, simpleField "synopsis"
showFreeText parseFreeText
synopsis (\val pkg -> pkg{synopsis=val})
, simpleField "description"
showFreeText parseFreeText
description (\val pkg -> pkg{description=val})
, simpleField "category"
showFreeText parseFreeText
category (\val pkg -> pkg{category=val})
, simpleField "author"
showFreeText parseFreeText
author (\val pkg -> pkg{author=val})
, listField "tested-with"
showTestedWith parseTestedWithQ
testedWith (\val pkg -> pkg{testedWith=val})
, listFieldWithSep vcat "data-files"
showFilePath parseFilePathQ
dataFiles (\val pkg -> pkg{dataFiles=val})
, simpleField "data-dir"
showFilePath parseFilePathQ
dataDir (\val pkg -> pkg{dataDir=val})
, listFieldWithSep vcat "extra-source-files"
showFilePath parseFilePathQ
extraSrcFiles (\val pkg -> pkg{extraSrcFiles=val})
, listFieldWithSep vcat "extra-tmp-files"
showFilePath parseFilePathQ
extraTmpFiles (\val pkg -> pkg{extraTmpFiles=val})
, listFieldWithSep vcat "extra-doc-files"
showFilePath parseFilePathQ
extraDocFiles (\val pkg -> pkg{extraDocFiles=val})
]
-- | Store any fields beginning with "x-" in the customFields field of
-- a PackageDescription. All other fields will generate a warning.
storeXFieldsPD :: UnrecFieldParser PackageDescription
storeXFieldsPD (f@('x':'-':_),val) pkg =
Just pkg{ customFieldsPD =
customFieldsPD pkg ++ [(f,val)]}
storeXFieldsPD _ _ = Nothing
-- ---------------------------------------------------------------------------
-- The Library type
libFieldDescrs :: [FieldDescr Library]
libFieldDescrs =
[ listFieldWithSep vcat "exposed-modules" disp parseModuleNameQ
exposedModules (\mods lib -> lib{exposedModules=mods})
, commaListFieldWithSep vcat "reexported-modules" disp parse
reexportedModules (\mods lib -> lib{reexportedModules=mods})
, listFieldWithSep vcat "required-signatures" disp parseModuleNameQ
requiredSignatures (\mods lib -> lib{requiredSignatures=mods})
, listFieldWithSep vcat "exposed-signatures" disp parseModuleNameQ
exposedSignatures (\mods lib -> lib{exposedSignatures=mods})
, boolField "exposed"
libExposed (\val lib -> lib{libExposed=val})
] ++ map biToLib binfoFieldDescrs
where biToLib = liftField libBuildInfo (\bi lib -> lib{libBuildInfo=bi})
storeXFieldsLib :: UnrecFieldParser Library
storeXFieldsLib (f@('x':'-':_), val) l@(Library { libBuildInfo = bi }) =
Just $ l {libBuildInfo =
bi{ customFieldsBI = customFieldsBI bi ++ [(f,val)]}}
storeXFieldsLib _ _ = Nothing
-- ---------------------------------------------------------------------------
-- The Executable type
executableFieldDescrs :: [FieldDescr Executable]
executableFieldDescrs =
[ -- note ordering: configuration must come first, for
-- showPackageDescription.
simpleField "executable"
showToken parseTokenQ
exeName (\xs exe -> exe{exeName=xs})
, simpleField "main-is"
showFilePath parseFilePathQ
modulePath (\xs exe -> exe{modulePath=xs})
]
++ map biToExe binfoFieldDescrs
where biToExe = liftField buildInfo (\bi exe -> exe{buildInfo=bi})
storeXFieldsExe :: UnrecFieldParser Executable
storeXFieldsExe (f@('x':'-':_), val) e@(Executable { buildInfo = bi }) =
Just $ e {buildInfo = bi{ customFieldsBI = (f,val):customFieldsBI bi}}
storeXFieldsExe _ _ = Nothing
-- ---------------------------------------------------------------------------
-- The TestSuite type
-- | An intermediate type just used for parsing the test-suite stanza.
-- After validation it is converted into the proper 'TestSuite' type.
data TestSuiteStanza = TestSuiteStanza {
testStanzaTestType :: Maybe TestType,
testStanzaMainIs :: Maybe FilePath,
testStanzaTestModule :: Maybe ModuleName,
testStanzaBuildInfo :: BuildInfo
}
emptyTestStanza :: TestSuiteStanza
emptyTestStanza = TestSuiteStanza Nothing Nothing Nothing mempty
testSuiteFieldDescrs :: [FieldDescr TestSuiteStanza]
testSuiteFieldDescrs =
[ simpleField "type"
(maybe empty disp) (fmap Just parse)
testStanzaTestType (\x suite -> suite { testStanzaTestType = x })
, simpleField "main-is"
(maybe empty showFilePath) (fmap Just parseFilePathQ)
testStanzaMainIs (\x suite -> suite { testStanzaMainIs = x })
, simpleField "test-module"
(maybe empty disp) (fmap Just parseModuleNameQ)
testStanzaTestModule (\x suite -> suite { testStanzaTestModule = x })
]
++ map biToTest binfoFieldDescrs
where
biToTest = liftField testStanzaBuildInfo
(\bi suite -> suite { testStanzaBuildInfo = bi })
storeXFieldsTest :: UnrecFieldParser TestSuiteStanza
storeXFieldsTest (f@('x':'-':_), val) t@(TestSuiteStanza { testStanzaBuildInfo = bi }) =
Just $ t {testStanzaBuildInfo = bi{ customFieldsBI = (f,val):customFieldsBI bi}}
storeXFieldsTest _ _ = Nothing
validateTestSuite :: LineNo -> TestSuiteStanza -> ParseResult TestSuite
validateTestSuite line stanza =
case testStanzaTestType stanza of
Nothing -> return $
emptyTestSuite { testBuildInfo = testStanzaBuildInfo stanza }
Just tt@(TestTypeUnknown _ _) ->
return emptyTestSuite {
testInterface = TestSuiteUnsupported tt,
testBuildInfo = testStanzaBuildInfo stanza
}
Just tt | tt `notElem` knownTestTypes ->
return emptyTestSuite {
testInterface = TestSuiteUnsupported tt,
testBuildInfo = testStanzaBuildInfo stanza
}
Just tt@(TestTypeExe ver) ->
case testStanzaMainIs stanza of
Nothing -> syntaxError line (missingField "main-is" tt)
Just file -> do
when (isJust (testStanzaTestModule stanza)) $
warning (extraField "test-module" tt)
return emptyTestSuite {
testInterface = TestSuiteExeV10 ver file,
testBuildInfo = testStanzaBuildInfo stanza
}
Just tt@(TestTypeLib ver) ->
case testStanzaTestModule stanza of
Nothing -> syntaxError line (missingField "test-module" tt)
Just module_ -> do
when (isJust (testStanzaMainIs stanza)) $
warning (extraField "main-is" tt)
return emptyTestSuite {
testInterface = TestSuiteLibV09 ver module_,
testBuildInfo = testStanzaBuildInfo stanza
}
where
missingField name tt = "The '" ++ name ++ "' field is required for the "
++ display tt ++ " test suite type."
extraField name tt = "The '" ++ name ++ "' field is not used for the '"
++ display tt ++ "' test suite type."
-- ---------------------------------------------------------------------------
-- The Benchmark type
-- | An intermediate type just used for parsing the benchmark stanza.
-- After validation it is converted into the proper 'Benchmark' type.
data BenchmarkStanza = BenchmarkStanza {
benchmarkStanzaBenchmarkType :: Maybe BenchmarkType,
benchmarkStanzaMainIs :: Maybe FilePath,
benchmarkStanzaBenchmarkModule :: Maybe ModuleName,
benchmarkStanzaBuildInfo :: BuildInfo
}
emptyBenchmarkStanza :: BenchmarkStanza
emptyBenchmarkStanza = BenchmarkStanza Nothing Nothing Nothing mempty
benchmarkFieldDescrs :: [FieldDescr BenchmarkStanza]
benchmarkFieldDescrs =
[ simpleField "type"
(maybe empty disp) (fmap Just parse)
benchmarkStanzaBenchmarkType
(\x suite -> suite { benchmarkStanzaBenchmarkType = x })
, simpleField "main-is"
(maybe empty showFilePath) (fmap Just parseFilePathQ)
benchmarkStanzaMainIs
(\x suite -> suite { benchmarkStanzaMainIs = x })
]
++ map biToBenchmark binfoFieldDescrs
where
biToBenchmark = liftField benchmarkStanzaBuildInfo
(\bi suite -> suite { benchmarkStanzaBuildInfo = bi })
storeXFieldsBenchmark :: UnrecFieldParser BenchmarkStanza
storeXFieldsBenchmark (f@('x':'-':_), val)
t@(BenchmarkStanza { benchmarkStanzaBuildInfo = bi }) =
Just $ t {benchmarkStanzaBuildInfo =
bi{ customFieldsBI = (f,val):customFieldsBI bi}}
storeXFieldsBenchmark _ _ = Nothing
validateBenchmark :: LineNo -> BenchmarkStanza -> ParseResult Benchmark
validateBenchmark line stanza =
case benchmarkStanzaBenchmarkType stanza of
Nothing -> return $
emptyBenchmark { benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza }
Just tt@(BenchmarkTypeUnknown _ _) ->
return emptyBenchmark {
benchmarkInterface = BenchmarkUnsupported tt,
benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza
}
Just tt | tt `notElem` knownBenchmarkTypes ->
return emptyBenchmark {
benchmarkInterface = BenchmarkUnsupported tt,
benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza
}
Just tt@(BenchmarkTypeExe ver) ->
case benchmarkStanzaMainIs stanza of
Nothing -> syntaxError line (missingField "main-is" tt)
Just file -> do
when (isJust (benchmarkStanzaBenchmarkModule stanza)) $
warning (extraField "benchmark-module" tt)
return emptyBenchmark {
benchmarkInterface = BenchmarkExeV10 ver file,
benchmarkBuildInfo = benchmarkStanzaBuildInfo stanza
}
where
missingField name tt = "The '" ++ name ++ "' field is required for the "
++ display tt ++ " benchmark type."
extraField name tt = "The '" ++ name ++ "' field is not used for the '"
++ display tt ++ "' benchmark type."
-- ---------------------------------------------------------------------------
-- The BuildInfo type
binfoFieldDescrs :: [FieldDescr BuildInfo]
binfoFieldDescrs =
[ boolField "buildable"
buildable (\val binfo -> binfo{buildable=val})
, commaListField "build-tools"
disp parseBuildTool
buildTools (\xs binfo -> binfo{buildTools=xs})
, commaListFieldWithSep vcat "build-depends"
disp parse
buildDependsWithRenaming
setBuildDependsWithRenaming
, spaceListField "cpp-options"
showToken parseTokenQ'
cppOptions (\val binfo -> binfo{cppOptions=val})
, spaceListField "cc-options"
showToken parseTokenQ'
ccOptions (\val binfo -> binfo{ccOptions=val})
, spaceListField "ld-options"
showToken parseTokenQ'
ldOptions (\val binfo -> binfo{ldOptions=val})
, commaListField "pkgconfig-depends"
disp parsePkgconfigDependency
pkgconfigDepends (\xs binfo -> binfo{pkgconfigDepends=xs})
, listField "frameworks"
showToken parseTokenQ
frameworks (\val binfo -> binfo{frameworks=val})
, listFieldWithSep vcat "c-sources"
showFilePath parseFilePathQ
cSources (\paths binfo -> binfo{cSources=paths})
, listFieldWithSep vcat "js-sources"
showFilePath parseFilePathQ
jsSources (\paths binfo -> binfo{jsSources=paths})
, simpleField "default-language"
(maybe empty disp) (option Nothing (fmap Just parseLanguageQ))
defaultLanguage (\lang binfo -> binfo{defaultLanguage=lang})
, listField "other-languages"
disp parseLanguageQ
otherLanguages (\langs binfo -> binfo{otherLanguages=langs})
, listField "default-extensions"
disp parseExtensionQ
defaultExtensions (\exts binfo -> binfo{defaultExtensions=exts})
, listField "other-extensions"
disp parseExtensionQ
otherExtensions (\exts binfo -> binfo{otherExtensions=exts})
, listField "extensions"
disp parseExtensionQ
oldExtensions (\exts binfo -> binfo{oldExtensions=exts})
, listFieldWithSep vcat "extra-libraries"
showToken parseTokenQ
extraLibs (\xs binfo -> binfo{extraLibs=xs})
, listFieldWithSep vcat "extra-ghci-libraries"
showToken parseTokenQ
extraGHCiLibs (\xs binfo -> binfo{extraGHCiLibs=xs})
, listField "extra-lib-dirs"
showFilePath parseFilePathQ
extraLibDirs (\xs binfo -> binfo{extraLibDirs=xs})
, listFieldWithSep vcat "includes"
showFilePath parseFilePathQ
includes (\paths binfo -> binfo{includes=paths})
, listFieldWithSep vcat "install-includes"
showFilePath parseFilePathQ
installIncludes (\paths binfo -> binfo{installIncludes=paths})
, listField "include-dirs"
showFilePath parseFilePathQ
includeDirs (\paths binfo -> binfo{includeDirs=paths})
, listField "hs-source-dirs"
showFilePath parseFilePathQ
hsSourceDirs (\paths binfo -> binfo{hsSourceDirs=paths})
, listFieldWithSep vcat "other-modules"
disp parseModuleNameQ
otherModules (\val binfo -> binfo{otherModules=val})
, optsField "ghc-prof-options" GHC
profOptions (\val binfo -> binfo{profOptions=val})
, optsField "ghcjs-prof-options" GHCJS
profOptions (\val binfo -> binfo{profOptions=val})
, optsField "ghc-shared-options" GHC
sharedOptions (\val binfo -> binfo{sharedOptions=val})
, optsField "ghcjs-shared-options" GHCJS
sharedOptions (\val binfo -> binfo{sharedOptions=val})
, optsField "ghc-options" GHC
options (\path binfo -> binfo{options=path})
, optsField "ghcjs-options" GHCJS
options (\path binfo -> binfo{options=path})
, optsField "jhc-options" JHC
options (\path binfo -> binfo{options=path})
-- NOTE: Hugs and NHC are not supported anymore, but these fields are kept
-- around for backwards compatibility.
, optsField "hugs-options" Hugs
options (const id)
, optsField "nhc98-options" NHC
options (const id)
]
storeXFieldsBI :: UnrecFieldParser BuildInfo
storeXFieldsBI (f@('x':'-':_),val) bi = Just bi{ customFieldsBI = (f,val):customFieldsBI bi }
storeXFieldsBI _ _ = Nothing
------------------------------------------------------------------------------
flagFieldDescrs :: [FieldDescr Flag]
flagFieldDescrs =
[ simpleField "description"
showFreeText parseFreeText
flagDescription (\val fl -> fl{ flagDescription = val })
, boolField "default"
flagDefault (\val fl -> fl{ flagDefault = val })
, boolField "manual"
flagManual (\val fl -> fl{ flagManual = val })
]
------------------------------------------------------------------------------
sourceRepoFieldDescrs :: [FieldDescr SourceRepo]
sourceRepoFieldDescrs =
[ simpleField "type"
(maybe empty disp) (fmap Just parse)
repoType (\val repo -> repo { repoType = val })
, simpleField "location"
(maybe empty showFreeText) (fmap Just parseFreeText)
repoLocation (\val repo -> repo { repoLocation = val })
, simpleField "module"
(maybe empty showToken) (fmap Just parseTokenQ)
repoModule (\val repo -> repo { repoModule = val })
, simpleField "branch"
(maybe empty showToken) (fmap Just parseTokenQ)
repoBranch (\val repo -> repo { repoBranch = val })
, simpleField "tag"
(maybe empty showToken) (fmap Just parseTokenQ)
repoTag (\val repo -> repo { repoTag = val })
, simpleField "subdir"
(maybe empty showFilePath) (fmap Just parseFilePathQ)
repoSubdir (\val repo -> repo { repoSubdir = val })
]
-- ---------------------------------------------------------------
-- Parsing
-- | Given a parser and a filename, return the parse of the file,
-- after checking if the file exists.
readAndParseFile :: (FilePath -> (String -> IO a) -> IO a)
-> (String -> ParseResult a)
-> Verbosity
-> FilePath -> IO a
readAndParseFile withFileContents' parser verbosity fpath = do
exists <- doesFileExist fpath
unless exists
(die $ "Error Parsing: file \"" ++ fpath ++ "\" doesn't exist. Cannot continue.")
withFileContents' fpath $ \str -> case parser str of
ParseFailed e -> do
let (line, message) = locatedErrorMsg e
dieWithLocation fpath line message
ParseOk warnings x -> do
mapM_ (warn verbosity . showPWarning fpath) $ reverse warnings
return x
readHookedBuildInfo :: Verbosity -> FilePath -> IO HookedBuildInfo
readHookedBuildInfo =
readAndParseFile withFileContents parseHookedBuildInfo
-- |Parse the given package file.
readPackageDescription :: Verbosity -> FilePath -> IO GenericPackageDescription
readPackageDescription =
readAndParseFile withUTF8FileContents parsePackageDescription
stanzas :: [Field] -> [[Field]]
stanzas [] = []
stanzas (f:fields) = (f:this) : stanzas rest
where
(this, rest) = break isStanzaHeader fields
isStanzaHeader :: Field -> Bool
isStanzaHeader (F _ f _) = f == "executable"
isStanzaHeader _ = False
------------------------------------------------------------------------------
mapSimpleFields :: (Field -> ParseResult Field) -> [Field]
-> ParseResult [Field]
mapSimpleFields f = mapM walk
where
walk fld@F{} = f fld
walk (IfBlock l c fs1 fs2) = do
fs1' <- mapM walk fs1
fs2' <- mapM walk fs2
return (IfBlock l c fs1' fs2')
walk (Section ln n l fs1) = do
fs1' <- mapM walk fs1
return (Section ln n l fs1')
-- prop_isMapM fs = mapSimpleFields return fs == return fs
-- names of fields that represents dependencies, thus consrca
constraintFieldNames :: [String]
constraintFieldNames = ["build-depends"]
-- Possible refactoring would be to have modifiers be explicit about what
-- they add and define an accessor that specifies what the dependencies
-- are. This way we would completely reuse the parsing knowledge from the
-- field descriptor.
parseConstraint :: Field -> ParseResult [DependencyWithRenaming]
parseConstraint (F l n v)
| n == "build-depends" = runP l n (parseCommaList parse) v
parseConstraint f = userBug $ "Constraint was expected (got: " ++ show f ++ ")"
{-
headerFieldNames :: [String]
headerFieldNames = filter (\n -> not (n `elem` constraintFieldNames))
. map fieldName $ pkgDescrFieldDescrs
-}
libFieldNames :: [String]
libFieldNames = map fieldName libFieldDescrs
++ buildInfoNames ++ constraintFieldNames
-- exeFieldNames :: [String]
-- exeFieldNames = map fieldName executableFieldDescrs
-- ++ buildInfoNames
buildInfoNames :: [String]
buildInfoNames = map fieldName binfoFieldDescrs
++ map fst deprecatedFieldsBuildInfo
-- A minimal implementation of the StateT monad transformer to avoid depending
-- on the 'mtl' package.
newtype StT s m a = StT { runStT :: s -> m (a,s) }
instance Functor f => Functor (StT s f) where
fmap g (StT f) = StT $ fmap (first g) . f
instance (Monad m, Functor m) => Applicative (StT s m) where
pure = return
(<*>) = ap
instance Monad m => Monad (StT s m) where
return a = StT (\s -> return (a,s))
StT f >>= g = StT $ \s -> do
(a,s') <- f s
runStT (g a) s'
get :: Monad m => StT s m s
get = StT $ \s -> return (s, s)
modify :: Monad m => (s -> s) -> StT s m ()
modify f = StT $ \s -> return ((),f s)
lift :: Monad m => m a -> StT s m a
lift m = StT $ \s -> m >>= \a -> return (a,s)
evalStT :: Monad m => StT s m a -> s -> m a
evalStT st s = liftM fst $ runStT st s
-- Our monad for parsing a list/tree of fields.
--
-- The state represents the remaining fields to be processed.
type PM a = StT [Field] ParseResult a
-- return look-ahead field or nothing if we're at the end of the file
peekField :: PM (Maybe Field)
peekField = liftM listToMaybe get
-- Unconditionally discard the first field in our state. Will error when it
-- reaches end of file. (Yes, that's evil.)
skipField :: PM ()
skipField = modify tail
--FIXME: this should take a ByteString, not a String. We have to be able to
-- decode UTF8 and handle the BOM.
-- | Parses the given file into a 'GenericPackageDescription'.
--
-- In Cabal 1.2 the syntax for package descriptions was changed to a format
-- with sections and possibly indented property descriptions.
parsePackageDescription :: String -> ParseResult GenericPackageDescription
parsePackageDescription file = do
-- This function is quite complex because it needs to be able to parse
-- both pre-Cabal-1.2 and post-Cabal-1.2 files. Additionally, it contains
-- a lot of parser-related noise since we do not want to depend on Parsec.
--
-- If we detect an pre-1.2 file we implicitly convert it to post-1.2
-- style. See 'sectionizeFields' below for details about the conversion.
fields0 <- readFields file `catchParseError` \err ->
let tabs = findIndentTabs file in
case err of
-- In case of a TabsError report them all at once.
TabsError tabLineNo -> reportTabsError
-- but only report the ones including and following
-- the one that caused the actual error
[ t | t@(lineNo',_) <- tabs
, lineNo' >= tabLineNo ]
_ -> parseFail err
let cabalVersionNeeded =
head $ [ minVersionBound versionRange
| Just versionRange <- [ simpleParse v
| F _ "cabal-version" v <- fields0 ] ]
++ [Version [0] []]
minVersionBound versionRange =
case asVersionIntervals versionRange of
[] -> Version [0] []
((LowerBound version _, _):_) -> version
handleFutureVersionParseFailure cabalVersionNeeded $ do
let sf = sectionizeFields fields0 -- ensure 1.2 format
-- figure out and warn about deprecated stuff (warnings are collected
-- inside our parsing monad)
fields <- mapSimpleFields deprecField sf
-- Our parsing monad takes the not-yet-parsed fields as its state.
-- After each successful parse we remove the field from the state
-- ('skipField') and move on to the next one.
--
-- Things are complicated a bit, because fields take a tree-like
-- structure -- they can be sections or "if"/"else" conditionals.
flip evalStT fields $ do
-- The header consists of all simple fields up to the first section
-- (flag, library, executable).
header_fields <- getHeader []
-- Parses just the header fields and stores them in a
-- 'PackageDescription'. Note that our final result is a
-- 'GenericPackageDescription'; for pragmatic reasons we just store
-- the partially filled-out 'PackageDescription' inside the
-- 'GenericPackageDescription'.
pkg <- lift $ parseFields pkgDescrFieldDescrs
storeXFieldsPD
emptyPackageDescription
header_fields
-- 'getBody' assumes that the remaining fields only consist of
-- flags, lib and exe sections.
(repos, flags, mlib, exes, tests, bms) <- getBody
warnIfRest -- warn if getBody did not parse up to the last field.
-- warn about using old/new syntax with wrong cabal-version:
maybeWarnCabalVersion (not $ oldSyntax fields0) pkg
checkForUndefinedFlags flags mlib exes tests
return $ GenericPackageDescription
pkg { sourceRepos = repos }
flags mlib exes tests bms
where
oldSyntax = all isSimpleField
reportTabsError tabs =
syntaxError (fst (head tabs)) $
"Do not use tabs for indentation (use spaces instead)\n"
++ " Tabs were used at (line,column): " ++ show tabs
maybeWarnCabalVersion newsyntax pkg
| newsyntax && specVersion pkg < Version [1,2] []
= lift $ warning $
"A package using section syntax must specify at least\n"
++ "'cabal-version: >= 1.2'."
maybeWarnCabalVersion newsyntax pkg
| not newsyntax && specVersion pkg >= Version [1,2] []
= lift $ warning $
"A package using 'cabal-version: "
++ displaySpecVersion (specVersionRaw pkg)
++ "' must use section syntax. See the Cabal user guide for details."
where
displaySpecVersion (Left version) = display version
displaySpecVersion (Right versionRange) =
case asVersionIntervals versionRange of
[] {- impossible -} -> display versionRange
((LowerBound version _, _):_) -> display (orLaterVersion version)
maybeWarnCabalVersion _ _ = return ()
handleFutureVersionParseFailure cabalVersionNeeded parseBody =
(unless versionOk (warning message) >> parseBody)
`catchParseError` \parseError -> case parseError of
TabsError _ -> parseFail parseError
_ | versionOk -> parseFail parseError
| otherwise -> fail message
where versionOk = cabalVersionNeeded <= cabalVersion
message = "This package requires at least Cabal version "
++ display cabalVersionNeeded
-- "Sectionize" an old-style Cabal file. A sectionized file has:
--
-- * all global fields at the beginning, followed by
--
-- * all flag declarations, followed by
--
-- * an optional library section, and an arbitrary number of executable
-- sections (in any order).
--
-- The current implementation just gathers all library-specific fields
-- in a library section and wraps all executable stanzas in an executable
-- section.
sectionizeFields :: [Field] -> [Field]
sectionizeFields fs
| oldSyntax fs =
let
-- "build-depends" is a local field now. To be backwards
-- compatible, we still allow it as a global field in old-style
-- package description files and translate it to a local field by
-- adding it to every non-empty section
(hdr0, exes0) = break ((=="executable") . fName) fs
(hdr, libfs0) = partition (not . (`elem` libFieldNames) . fName) hdr0
(deps, libfs) = partition ((== "build-depends") . fName)
libfs0
exes = unfoldr toExe exes0
toExe [] = Nothing
toExe (F l e n : r)
| e == "executable" =
let (efs, r') = break ((=="executable") . fName) r
in Just (Section l "executable" n (deps ++ efs), r')
toExe _ = cabalBug "unexpected input to 'toExe'"
in
hdr ++
(if null libfs then []
else [Section (lineNo (head libfs)) "library" "" (deps ++ libfs)])
++ exes
| otherwise = fs
isSimpleField F{} = True
isSimpleField _ = False
-- warn if there's something at the end of the file
warnIfRest :: PM ()
warnIfRest = do
s <- get
case s of
[] -> return ()
_ -> lift $ warning "Ignoring trailing declarations." -- add line no.
-- all simple fields at the beginning of the file are (considered) header
-- fields
getHeader :: [Field] -> PM [Field]
getHeader acc = peekField >>= \mf -> case mf of
Just f@F{} -> skipField >> getHeader (f:acc)
_ -> return (reverse acc)
--
-- body ::= { repo | flag | library | executable | test }+ -- at most one lib
--
-- The body consists of an optional sequence of declarations of flags and
-- an arbitrary number of executables and at most one library.
getBody :: PM ([SourceRepo], [Flag]
,Maybe (CondTree ConfVar [Dependency] Library)
,[(String, CondTree ConfVar [Dependency] Executable)]
,[(String, CondTree ConfVar [Dependency] TestSuite)]
,[(String, CondTree ConfVar [Dependency] Benchmark)])
getBody = peekField >>= \mf -> case mf of
Just (Section line_no sec_type sec_label sec_fields)
| sec_type == "executable" -> do
when (null sec_label) $ lift $ syntaxError line_no
"'executable' needs one argument (the executable's name)"
exename <- lift $ runP line_no "executable" parseTokenQ sec_label
flds <- collectFields parseExeFields sec_fields
skipField
(repos, flags, lib, exes, tests, bms) <- getBody
return (repos, flags, lib, (exename, flds): exes, tests, bms)
| sec_type == "test-suite" -> do
when (null sec_label) $ lift $ syntaxError line_no
"'test-suite' needs one argument (the test suite's name)"
testname <- lift $ runP line_no "test" parseTokenQ sec_label
flds <- collectFields (parseTestFields line_no) sec_fields
-- Check that a valid test suite type has been chosen. A type
-- field may be given inside a conditional block, so we must
-- check for that before complaining that a type field has not
-- been given. The test suite must always have a valid type, so
-- we need to check both the 'then' and 'else' blocks, though
-- the blocks need not have the same type.
let checkTestType ts ct =
let ts' = mappend ts $ condTreeData ct
-- If a conditional has only a 'then' block and no
-- 'else' block, then it cannot have a valid type
-- in every branch, unless the type is specified at
-- a higher level in the tree.
checkComponent (_, _, Nothing) = False
-- If a conditional has a 'then' block and an 'else'
-- block, both must specify a test type, unless the
-- type is specified higher in the tree.
checkComponent (_, t, Just e) =
checkTestType ts' t && checkTestType ts' e
-- Does the current node specify a test type?
hasTestType = testInterface ts'
/= testInterface emptyTestSuite
components = condTreeComponents ct
-- If the current level of the tree specifies a type,
-- then we are done. If not, then one of the conditional
-- branches below the current node must specify a type.
-- Each node may have multiple immediate children; we
-- only one need one to specify a type because the
-- configure step uses 'mappend' to join together the
-- results of flag resolution.
in hasTestType || any checkComponent components
if checkTestType emptyTestSuite flds
then do
skipField
(repos, flags, lib, exes, tests, bms) <- getBody
return (repos, flags, lib, exes, (testname, flds) : tests, bms)
else lift $ syntaxError line_no $
"Test suite \"" ++ testname
++ "\" is missing required field \"type\" or the field "
++ "is not present in all conditional branches. The "
++ "available test types are: "
++ intercalate ", " (map display knownTestTypes)
| sec_type == "benchmark" -> do
when (null sec_label) $ lift $ syntaxError line_no
"'benchmark' needs one argument (the benchmark's name)"
benchname <- lift $ runP line_no "benchmark" parseTokenQ sec_label
flds <- collectFields (parseBenchmarkFields line_no) sec_fields
-- Check that a valid benchmark type has been chosen. A type
-- field may be given inside a conditional block, so we must
-- check for that before complaining that a type field has not
-- been given. The benchmark must always have a valid type, so
-- we need to check both the 'then' and 'else' blocks, though
-- the blocks need not have the same type.
let checkBenchmarkType ts ct =
let ts' = mappend ts $ condTreeData ct
-- If a conditional has only a 'then' block and no
-- 'else' block, then it cannot have a valid type
-- in every branch, unless the type is specified at
-- a higher level in the tree.
checkComponent (_, _, Nothing) = False
-- If a conditional has a 'then' block and an 'else'
-- block, both must specify a benchmark type, unless the
-- type is specified higher in the tree.
checkComponent (_, t, Just e) =
checkBenchmarkType ts' t && checkBenchmarkType ts' e
-- Does the current node specify a benchmark type?
hasBenchmarkType = benchmarkInterface ts'
/= benchmarkInterface emptyBenchmark
components = condTreeComponents ct
-- If the current level of the tree specifies a type,
-- then we are done. If not, then one of the conditional
-- branches below the current node must specify a type.
-- Each node may have multiple immediate children; we
-- only one need one to specify a type because the
-- configure step uses 'mappend' to join together the
-- results of flag resolution.
in hasBenchmarkType || any checkComponent components
if checkBenchmarkType emptyBenchmark flds
then do
skipField
(repos, flags, lib, exes, tests, bms) <- getBody
return (repos, flags, lib, exes, tests, (benchname, flds) : bms)
else lift $ syntaxError line_no $
"Benchmark \"" ++ benchname
++ "\" is missing required field \"type\" or the field "
++ "is not present in all conditional branches. The "
++ "available benchmark types are: "
++ intercalate ", " (map display knownBenchmarkTypes)
| sec_type == "library" -> do
unless (null sec_label) $ lift $
syntaxError line_no "'library' expects no argument"
flds <- collectFields parseLibFields sec_fields
skipField
(repos, flags, lib, exes, tests, bms) <- getBody
when (isJust lib) $ lift $ syntaxError line_no
"There can only be one library section in a package description."
return (repos, flags, Just flds, exes, tests, bms)
| sec_type == "flag" -> do
when (null sec_label) $ lift $
syntaxError line_no "'flag' needs one argument (the flag's name)"
flag <- lift $ parseFields
flagFieldDescrs
warnUnrec
(MkFlag (FlagName (lowercase sec_label)) "" True False)
sec_fields
skipField
(repos, flags, lib, exes, tests, bms) <- getBody
return (repos, flag:flags, lib, exes, tests, bms)
| sec_type == "source-repository" -> do
when (null sec_label) $ lift $ syntaxError line_no $
"'source-repository' needs one argument, "
++ "the repo kind which is usually 'head' or 'this'"
kind <- case simpleParse sec_label of
Just kind -> return kind
Nothing -> lift $ syntaxError line_no $
"could not parse repo kind: " ++ sec_label
repo <- lift $ parseFields
sourceRepoFieldDescrs
warnUnrec
SourceRepo {
repoKind = kind,
repoType = Nothing,
repoLocation = Nothing,
repoModule = Nothing,
repoBranch = Nothing,
repoTag = Nothing,
repoSubdir = Nothing
}
sec_fields
skipField
(repos, flags, lib, exes, tests, bms) <- getBody
return (repo:repos, flags, lib, exes, tests, bms)
| otherwise -> do
lift $ warning $ "Ignoring unknown section type: " ++ sec_type
skipField
getBody
Just f@(F {}) -> do
_ <- lift $ syntaxError (lineNo f) $
"Plain fields are not allowed in between stanzas: " ++ show f
skipField
getBody
Just f@(IfBlock {}) -> do
_ <- lift $ syntaxError (lineNo f) $
"If-blocks are not allowed in between stanzas: " ++ show f
skipField
getBody
Nothing -> return ([], [], Nothing, [], [], [])
-- Extracts all fields in a block and returns a 'CondTree'.
--
-- We have to recurse down into conditionals and we treat fields that
-- describe dependencies specially.
collectFields :: ([Field] -> PM a) -> [Field]
-> PM (CondTree ConfVar [Dependency] a)
collectFields parser allflds = do
let simplFlds = [ F l n v | F l n v <- allflds ]
condFlds = [ f | f@IfBlock{} <- allflds ]
sections = [ s | s@Section{} <- allflds ]
-- Put these through the normal parsing pass too, so that we
-- collect the ModRenamings
let depFlds = filter isConstraint simplFlds
mapM_
(\(Section l n _ _) -> lift . warning $
"Unexpected section '" ++ n ++ "' on line " ++ show l)
sections
a <- parser simplFlds
deps <- liftM concat . mapM (lift . fmap (map dependency) . parseConstraint) $ depFlds
ifs <- mapM processIfs condFlds
return (CondNode a deps ifs)
where
isConstraint (F _ n _) = n `elem` constraintFieldNames
isConstraint _ = False
processIfs (IfBlock l c t e) = do
cnd <- lift $ runP l "if" parseCondition c
t' <- collectFields parser t
e' <- case e of
[] -> return Nothing
es -> do fs <- collectFields parser es
return (Just fs)
return (cnd, t', e')
processIfs _ = cabalBug "processIfs called with wrong field type"
parseLibFields :: [Field] -> PM Library
parseLibFields = lift . parseFields libFieldDescrs storeXFieldsLib emptyLibrary
-- Note: we don't parse the "executable" field here, hence the tail hack.
parseExeFields :: [Field] -> PM Executable
parseExeFields = lift . parseFields (tail executableFieldDescrs)
storeXFieldsExe emptyExecutable
parseTestFields :: LineNo -> [Field] -> PM TestSuite
parseTestFields line fields = do
x <- lift $ parseFields testSuiteFieldDescrs storeXFieldsTest
emptyTestStanza fields
lift $ validateTestSuite line x
parseBenchmarkFields :: LineNo -> [Field] -> PM Benchmark
parseBenchmarkFields line fields = do
x <- lift $ parseFields benchmarkFieldDescrs storeXFieldsBenchmark
emptyBenchmarkStanza fields
lift $ validateBenchmark line x
checkForUndefinedFlags ::
[Flag] ->
Maybe (CondTree ConfVar [Dependency] Library) ->
[(String, CondTree ConfVar [Dependency] Executable)] ->
[(String, CondTree ConfVar [Dependency] TestSuite)] ->
PM ()
checkForUndefinedFlags flags mlib exes tests = do
let definedFlags = map flagName flags
maybe (return ()) (checkCondTreeFlags definedFlags) mlib
mapM_ (checkCondTreeFlags definedFlags . snd) exes
mapM_ (checkCondTreeFlags definedFlags . snd) tests
checkCondTreeFlags :: [FlagName] -> CondTree ConfVar c a -> PM ()
checkCondTreeFlags definedFlags ct = do
let fv = nub $ freeVars ct
unless (all (`elem` definedFlags) fv) $
fail $ "These flags are used without having been defined: "
++ intercalate ", " [ n | FlagName n <- fv \\ definedFlags ]
-- | Parse a list of fields, given a list of field descriptions,
-- a structure to accumulate the parsed fields, and a function
-- that can decide what to do with fields which don't match any
-- of the field descriptions.
parseFields :: [FieldDescr a] -- ^ descriptions of fields we know how to
-- parse
-> UnrecFieldParser a -- ^ possibly do something with
-- unrecognized fields
-> a -- ^ accumulator
-> [Field] -- ^ fields to be parsed
-> ParseResult a
parseFields descrs unrec ini fields =
do (a, unknowns) <- foldM (parseField descrs unrec) (ini, []) fields
unless (null unknowns) $ warning $ render $
text "Unknown fields:" <+>
commaSep (map (\(l,u) -> u ++ " (line " ++ show l ++ ")")
(reverse unknowns))
$+$
text "Fields allowed in this section:" $$
nest 4 (commaSep $ map fieldName descrs)
return a
where
commaSep = fsep . punctuate comma . map text
parseField :: [FieldDescr a] -- ^ list of parseable fields
-> UnrecFieldParser a -- ^ possibly do something with
-- unrecognized fields
-> (a,[(Int,String)]) -- ^ accumulated result and warnings
-> Field -- ^ the field to be parsed
-> ParseResult (a, [(Int,String)])
parseField (FieldDescr name _ parser : fields) unrec (a, us) (F line f val)
| name == f = parser line val a >>= \a' -> return (a',us)
| otherwise = parseField fields unrec (a,us) (F line f val)
parseField [] unrec (a,us) (F l f val) = return $
case unrec (f,val) a of -- no fields matched, see if the 'unrec'
Just a' -> (a',us) -- function wants to do anything with it
Nothing -> (a, (l,f):us)
parseField _ _ _ _ = cabalBug "'parseField' called on a non-field"
deprecatedFields :: [(String,String)]
deprecatedFields =
deprecatedFieldsPkgDescr ++ deprecatedFieldsBuildInfo
deprecatedFieldsPkgDescr :: [(String,String)]
deprecatedFieldsPkgDescr = [ ("other-files", "extra-source-files") ]
deprecatedFieldsBuildInfo :: [(String,String)]
deprecatedFieldsBuildInfo = [ ("hs-source-dir","hs-source-dirs") ]
-- Handle deprecated fields
deprecField :: Field -> ParseResult Field
deprecField (F line fld val) = do
fld' <- case lookup fld deprecatedFields of
Nothing -> return fld
Just newName -> do
warning $ "The field \"" ++ fld
++ "\" is deprecated, please use \"" ++ newName ++ "\""
return newName
return (F line fld' val)
deprecField _ = cabalBug "'deprecField' called on a non-field"
parseHookedBuildInfo :: String -> ParseResult HookedBuildInfo
parseHookedBuildInfo inp = do
fields <- readFields inp
let ss@(mLibFields:exes) = stanzas fields
mLib <- parseLib mLibFields
biExes <- mapM parseExe (maybe ss (const exes) mLib)
return (mLib, biExes)
where
parseLib :: [Field] -> ParseResult (Maybe BuildInfo)
parseLib (bi@(F _ inFieldName _:_))
| lowercase inFieldName /= "executable" = liftM Just (parseBI bi)
parseLib _ = return Nothing
parseExe :: [Field] -> ParseResult (String, BuildInfo)
parseExe (F line inFieldName mName:bi)
| lowercase inFieldName == "executable"
= do bis <- parseBI bi
return (mName, bis)
| otherwise = syntaxError line "expecting 'executable' at top of stanza"
parseExe (_:_) = cabalBug "`parseExe' called on a non-field"
parseExe [] = syntaxError 0 "error in parsing buildinfo file. Expected executable stanza"
parseBI st = parseFields binfoFieldDescrs storeXFieldsBI emptyBuildInfo st
-- ---------------------------------------------------------------------------
-- Pretty printing
writePackageDescription :: FilePath -> PackageDescription -> IO ()
writePackageDescription fpath pkg = writeUTF8File fpath (showPackageDescription pkg)
--TODO: make this use section syntax
-- add equivalent for GenericPackageDescription
showPackageDescription :: PackageDescription -> String
showPackageDescription pkg = render $
ppPackage pkg
$$ ppCustomFields (customFieldsPD pkg)
$$ (case library pkg of
Nothing -> empty
Just lib -> ppLibrary lib)
$$ vcat [ space $$ ppExecutable exe | exe <- executables pkg ]
where
ppPackage = ppFields pkgDescrFieldDescrs
ppLibrary = ppFields libFieldDescrs
ppExecutable = ppFields executableFieldDescrs
ppCustomFields :: [(String,String)] -> Doc
ppCustomFields flds = vcat (map ppCustomField flds)
ppCustomField :: (String,String) -> Doc
ppCustomField (name,val) = text name <> colon <+> showFreeText val
writeHookedBuildInfo :: FilePath -> HookedBuildInfo -> IO ()
writeHookedBuildInfo fpath = writeFileAtomic fpath . BS.Char8.pack
. showHookedBuildInfo
showHookedBuildInfo :: HookedBuildInfo -> String
showHookedBuildInfo (mb_lib_bi, ex_bis) = render $
(case mb_lib_bi of
Nothing -> empty
Just bi -> ppBuildInfo bi)
$$ vcat [ space
$$ text "executable:" <+> text name
$$ ppBuildInfo bi
| (name, bi) <- ex_bis ]
where
ppBuildInfo bi = ppFields binfoFieldDescrs bi
$$ ppCustomFields (customFieldsBI bi)
-- replace all tabs used as indentation with whitespace, also return where
-- tabs were found
findIndentTabs :: String -> [(Int,Int)]
findIndentTabs = concatMap checkLine
. zip [1..]
. lines
where
checkLine (lineno, l) =
let (indent, _content) = span isSpace l
tabCols = map fst . filter ((== '\t') . snd) . zip [0..]
addLineNo = map (\col -> (lineno,col))
in addLineNo (tabCols indent)
--test_findIndentTabs = findIndentTabs $ unlines $
-- [ "foo", " bar", " \t baz", "\t biz\t", "\t\t \t mib" ]
-- | Dependencies plus module renamings. This is what users specify; however,
-- renaming information is not used for dependency resolution.
data DependencyWithRenaming = DependencyWithRenaming Dependency ModuleRenaming
deriving (Read, Show, Eq, Typeable, Data)
dependency :: DependencyWithRenaming -> Dependency
dependency (DependencyWithRenaming dep _) = dep
instance Text DependencyWithRenaming where
disp (DependencyWithRenaming d rns) = disp d <+> disp rns
parse = do d <- parse
Parse.skipSpaces
rns <- parse
Parse.skipSpaces
return (DependencyWithRenaming d rns)
buildDependsWithRenaming :: BuildInfo -> [DependencyWithRenaming]
buildDependsWithRenaming pkg =
map (\dep@(Dependency n _) ->
DependencyWithRenaming dep
(Map.findWithDefault defaultRenaming n (targetBuildRenaming pkg)))
(targetBuildDepends pkg)
setBuildDependsWithRenaming :: [DependencyWithRenaming] -> BuildInfo -> BuildInfo
setBuildDependsWithRenaming deps pkg = pkg {
targetBuildDepends = map dependency deps,
targetBuildRenaming = Map.fromList (map (\(DependencyWithRenaming (Dependency n _) rns) -> (n, rns)) deps)
}
|
DavidAlphaFox/ghc
|
libraries/Cabal/Cabal/Distribution/PackageDescription/Parse.hs
|
bsd-3-clause
| 54,747 | 321 | 19 | 16,740 | 11,569 | 6,269 | 5,300 | 885 | 25 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
-----------------------------------------------------------------------------
-- |
-- Module : Generics.Instant.Base
-- Copyright : (c) 2010, Universiteit Utrecht
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable
--
-- This module defines the basic representation types and the conversion
-- functions 'to' and 'from'. A typical instance for a user-defined datatype
-- would be:
--
-- > -- Example datatype
-- > data Exp = Const Int | Plus Exp Exp
-- >
-- > -- Auxiliary datatypes for constructor representations
-- > data Const
-- > data Plus
-- >
-- > instance Constructor Const where conName _ = "Const"
-- > instance Constructor Plus where conName _ = "Plus"
-- >
-- > -- Representable instance
-- > instance Representable Exp where
-- > type Rep Exp = C Const (Var Int) :+: C Plus (Rec Exp :*: Rec Exp)
-- >
-- > from (Const n) = L (C (Var n))
-- > from (Plus e e') = R (C (Rec e :*: Rec e'))
-- >
-- > to (L (C (Var n))) = Const n
-- > to (R (C (Rec e :*: Rec e'))) = Plus e e'
--
-----------------------------------------------------------------------------
module Generics.Instant.Base (
Z, U(..), (:+:)(..), (:*:)(..), CEq(..), C, Var(..), Rec(..)
, Constructor(..), Fixity(..), Associativity(..)
, Representable(..)
, X, Nat(..)
) where
infixr 5 :+:
infixr 6 :*:
data Z
data U = U deriving (Show, Read)
data a :+: b = L a | R b deriving (Show, Read)
data a :*: b = a :*: b deriving (Show, Read)
data Var a = Var a deriving (Show, Read)
data Rec a = Rec a deriving (Show, Read)
data CEq c p q a where C :: a -> CEq c p p a
deriving instance (Show a) => Show (CEq c p q a)
deriving instance (Read a) => Read (CEq c p p a)
-- Shorthand when no proofs are required
type C c a = CEq c () () a
-- | Class for datatypes that represent data constructors.
-- For non-symbolic constructors, only 'conName' has to be defined.
class Constructor c where
conName :: t c p q a -> String
{-# INLINE conFixity #-}
conFixity :: t c p q a -> Fixity
conFixity = const Prefix
{-# INLINE conIsRecord #-}
conIsRecord :: t c p q a -> Bool
conIsRecord = const False
-- | Datatype to represent the fixity of a constructor. An infix declaration
-- directly corresponds to an application of 'Infix'.
data Fixity = Prefix | Infix Associativity Int
deriving (Eq, Show, Ord, Read)
-- | Datatype to represent the associativy of a constructor.
data Associativity = LeftAssociative | RightAssociative | NotAssociative
deriving (Eq, Show, Ord, Read)
class Representable a where
type Rep a
to :: Rep a -> a
from :: a -> Rep a
-- defaults
{-
type Rep a = a -- type synonyms defaults are not yet implemented!
to = id
from = id
-}
-- Type family for representing existentially-quantified variables
type family X c (n :: Nat) (a :: k1) :: k2
-- Natural numbers, to be used at the type level
data Nat = Ze | Su Nat
|
dreixel/instant-generics
|
src/Generics/Instant/Base.hs
|
bsd-3-clause
| 3,468 | 0 | 8 | 944 | 599 | 373 | 226 | -1 | -1 |
{-# LANGUAGE LambdaCase #-}
import Control.Arrow
import Control.Lens
import Data.Char
import Data.List.Split
import qualified Data.Map as M
data ColorDef = ColorDef { colorName :: String, colorValue :: String }
main = interact process
where
process = generateDefs . map processColor . tail . lines
processColor = mkColorDef . (init &&& last) . words
mkColorDef :: ([String], String) -> ColorDef
mkColorDef = ColorDef <$> (mkVarName . fst) <*> snd
mkVarName (n:ns)
= map (\case '/' -> '_'; c -> c)
$ n ++ concatMap upFirst ns
upFirst (c:cs) = toUpper c : cs
generateDefs :: [ColorDef] -> String
generateDefs cs = formatColorDefs cs ++ "\n" ++ formatColorMap cs
formatColorDefs cs = unlines . map mkEqn $ cs
where
width = maximum . map (length . colorName) $ cs
mkEqn (ColorDef v c) = padded v ++ " = fromJust $ readHexColor " ++ show c
padded a = a ++ (replicate (width - length a) ' ')
formatColorMap cs =
unlines $
[ "xkcdColorMap :: M.Map String (AlphaColour Double)"
, "xkcdColorMap = M.fromList"
]
++
(map mkAssoc cs & _Cons . _2 . traverse %~ (" , "++)
& _Cons . _1 %~ (" [ "++)
)
++
[ " ]" ]
where
mkAssoc (ColorDef n c) = "(" ++ show n ++ ", " ++ n ++ ")"
|
diagrams/diagrams-contrib
|
src/Diagrams/Color/ProcessXKCDColors.hs
|
bsd-3-clause
| 1,426 | 1 | 15 | 481 | 464 | 243 | 221 | -1 | -1 |
module Deprecated.DiGraph.SampleData where
import PolyGraph.Common
import qualified Instances.SimpleGraph as SG
import qualified SampleInstances.FirstLastWord as FL
import qualified Data.HashSet as HS
-- simple test data (list of pars that will serve as edges)
testEdges = map(OPair) [
("a0", "a01"),
("a0", "a02"),
("a01", "a1"),
("a02", "a1"),
("a0", "a1"),
("a1", "a11"),
("a1", "a12"),
("a11", "a2"),
("a12", "a2"),
("a1", "a2")
]
--
-- notice SimpleGraph is not specialized to String type
--
playTwoDiamondsSetGraph :: SG.SimpleSetDiGraph String
playTwoDiamondsSetGraph = SG.SimpleGraph (HS.fromList testEdges) HS.empty
playTwoDiamonds :: SG.SimpleListDiGraph String
playTwoDiamonds = SG.SimpleGraph testEdges []
playFirstLastTxt:: String
playFirstLastTxt = "a implies b\n" ++
"a implies c\n" ++
"b implies d\n" ++
"c implies d\n" ++
"d implies e\n" ++
"a implies f\n"
playFirstLast = FL.FLWordText playFirstLastTxt
|
rpeszek/GraphPlay
|
play/Play/DiGraph/SampleData.hs
|
bsd-3-clause
| 1,095 | 0 | 9 | 292 | 239 | 146 | 93 | 28 | 1 |
{-# LANGUAGE LambdaCase, PatternGuards, ViewPatterns #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Elab.Term where
import Idris.AbsSyntax
import Idris.AbsSyntaxTree
import Idris.DSL
import Idris.Delaborate
import Idris.Error
import Idris.ProofSearch
import Idris.Output (pshow)
import Idris.Core.CaseTree (SC, SC'(STerm), findCalls, findUsedArgs)
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Core.Unify
import Idris.Core.ProofTerm (getProofTerm)
import Idris.Core.Typecheck (check, recheck, converts, isType)
import Idris.Core.WHNF (whnf)
import Idris.Coverage (buildSCG, checkDeclTotality, genClauses, recoverableCoverage, validCoverageCase)
import Idris.ErrReverse (errReverse)
import Idris.ElabQuasiquote (extractUnquotes)
import Idris.Elab.Utils
import Idris.Reflection
import qualified Util.Pretty as U
import Control.Applicative ((<$>))
import Control.Monad
import Control.Monad.State.Strict
import Data.Foldable (for_)
import Data.List
import qualified Data.Map as M
import Data.Maybe (mapMaybe, fromMaybe, catMaybes, maybeToList)
import qualified Data.Set as S
import qualified Data.Text as T
import Debug.Trace
data ElabMode = ETyDecl | ETransLHS | ELHS | ERHS
deriving Eq
data ElabResult =
ElabResult { resultTerm :: Term -- ^ The term resulting from elaboration
, resultMetavars :: [(Name, (Int, Maybe Name, Type, [Name]))]
-- ^ Information about new metavariables
, resultCaseDecls :: [PDecl]
-- ^ Deferred declarations as the meaning of case blocks
, resultContext :: Context
-- ^ The potentially extended context from new definitions
, resultTyDecls :: [RDeclInstructions]
-- ^ Meta-info about the new type declarations
, resultHighlighting :: [(FC, OutputAnnotation)]
}
-- Using the elaborator, convert a term in raw syntax to a fully
-- elaborated, typechecked term.
--
-- If building a pattern match, we convert undeclared variables from
-- holes to pattern bindings.
-- Also find deferred names in the term and their types
build :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm ->
ElabD ElabResult
build ist info emode opts fn tm
= do elab ist info emode opts fn tm
let tmIn = tm
let inf = case lookupCtxt fn (idris_tyinfodata ist) of
[TIPartial] -> True
_ -> False
hs <- get_holes
ivs <- get_instances
ptm <- get_term
-- Resolve remaining type classes. Two passes - first to get the
-- default Num instances, second to clean up the rest
when (not pattern) $
mapM_ (\n -> when (n `elem` hs) $
do focus n
g <- goal
try (resolveTC' True False 10 g fn ist)
(movelast n)) ivs
ivs <- get_instances
hs <- get_holes
when (not pattern) $
mapM_ (\n -> when (n `elem` hs) $
do focus n
g <- goal
ptm <- get_term
resolveTC' True True 10 g fn ist) ivs
when (not pattern) $ solveAutos ist fn False
tm <- get_term
ctxt <- get_context
probs <- get_probs
u <- getUnifyLog
hs <- get_holes
when (not pattern) $
traceWhen u ("Remaining holes:\n" ++ show hs ++ "\n" ++
"Remaining problems:\n" ++ qshow probs) $
do unify_all; matchProblems True; unifyProblems
when (not pattern) $ solveAutos ist fn True
probs <- get_probs
case probs of
[] -> return ()
((_,_,_,_,e,_,_):es) -> traceWhen u ("Final problems:\n" ++ qshow probs ++ "\nin\n" ++ show tm) $
if inf then return ()
else lift (Error e)
when tydecl (do mkPat
update_term liftPats
update_term orderPats)
EState is _ impls highlights <- getAux
tt <- get_term
ctxt <- get_context
let (tm, ds) = runState (collectDeferred (Just fn) (map fst is) ctxt tt) []
log <- getLog
if log /= ""
then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights)
else return (ElabResult tm ds (map snd is) ctxt impls highlights)
where pattern = emode == ELHS
tydecl = emode == ETyDecl
mkPat = do hs <- get_holes
tm <- get_term
case hs of
(h: hs) -> do patvar h; mkPat
[] -> return ()
-- Build a term autogenerated as a typeclass method definition
-- (Separate, so we don't go overboard resolving things that we don't
-- know about yet on the LHS of a pattern def)
buildTC :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name ->
[Name] -> -- Cached names in the PTerm, before adding PAlternatives
PTerm ->
ElabD ElabResult
buildTC ist info emode opts fn ns tm
= do let tmIn = tm
let inf = case lookupCtxt fn (idris_tyinfodata ist) of
[TIPartial] -> True
_ -> False
-- set name supply to begin after highest index in tm
initNextNameFrom ns
elab ist info emode opts fn tm
probs <- get_probs
tm <- get_term
case probs of
[] -> return ()
((_,_,_,_,e,_,_):es) -> if inf then return ()
else lift (Error e)
dots <- get_dotterm
-- 'dots' are the PHidden things which have not been solved by
-- unification
when (not (null dots)) $
lift (Error (CantMatch (getInferTerm tm)))
EState is _ impls highlights <- getAux
tt <- get_term
ctxt <- get_context
let (tm, ds) = runState (collectDeferred (Just fn) (map fst is) ctxt tt) []
log <- getLog
if (log /= "")
then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights)
else return (ElabResult tm ds (map snd is) ctxt impls highlights)
where pattern = emode == ELHS
-- return whether arguments of the given constructor name can be
-- matched on. If they're polymorphic, no, unless the type has beed made
-- concrete by the time we get around to elaborating the argument.
getUnmatchable :: Context -> Name -> [Bool]
getUnmatchable ctxt n | isDConName n ctxt && n /= inferCon
= case lookupTyExact n ctxt of
Nothing -> []
Just ty -> checkArgs [] [] ty
where checkArgs :: [Name] -> [[Name]] -> Type -> [Bool]
checkArgs env ns (Bind n (Pi _ t _) sc)
= let env' = case t of
TType _ -> n : env
_ -> env in
checkArgs env' (intersect env (refsIn t) : ns)
(instantiate (P Bound n t) sc)
checkArgs env ns t
= map (not . null) (reverse ns)
getUnmatchable ctxt n = []
data ElabCtxt = ElabCtxt { e_inarg :: Bool,
e_isfn :: Bool, -- ^ Function part of application
e_guarded :: Bool,
e_intype :: Bool,
e_qq :: Bool,
e_nomatching :: Bool -- ^ can't pattern match
}
initElabCtxt = ElabCtxt False False False False False False
goal_polymorphic :: ElabD Bool
goal_polymorphic =
do ty <- goal
case ty of
P _ n _ -> do env <- get_env
case lookup n env of
Nothing -> return False
_ -> return True
_ -> return False
-- | Returns the set of declarations we need to add to complete the
-- definition (most likely case blocks to elaborate) as well as
-- declarations resulting from user tactic scripts (%runElab)
elab :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm ->
ElabD ()
elab ist info emode opts fn tm
= do let loglvl = opt_logLevel (idris_options ist)
when (loglvl > 5) $ unifyLog True
compute -- expand type synonyms, etc
let fc = maybe "(unknown)"
elabE initElabCtxt (elabFC info) tm -- (in argument, guarded, in type, in qquote)
est <- getAux
sequence_ (get_delayed_elab est)
end_unify
ptm <- get_term
when (pattern || intransform) -- convert remaining holes to pattern vars
(do update_term orderPats
unify_all
matchProblems False -- only the ones we matched earlier
unifyProblems
mkPat)
where
pattern = emode == ELHS
intransform = emode == ETransLHS
bindfree = emode == ETyDecl || emode == ELHS || emode == ETransLHS
get_delayed_elab est =
let ds = delayed_elab est in
map snd $ sortBy (\(p1, _) (p2, _) -> compare p1 p2) ds
tcgen = Dictionary `elem` opts
reflection = Reflection `elem` opts
isph arg = case getTm arg of
Placeholder -> (True, priority arg)
tm -> (False, priority arg)
toElab ina arg = case getTm arg of
Placeholder -> Nothing
v -> Just (priority arg, elabE ina (elabFC info) v)
toElab' ina arg = case getTm arg of
Placeholder -> Nothing
v -> Just (elabE ina (elabFC info) v)
mkPat = do hs <- get_holes
tm <- get_term
case hs of
(h: hs) -> do patvar h; mkPat
[] -> return ()
-- | elabE elaborates an expression, possibly wrapping implicit coercions
-- and forces/delays. If you make a recursive call in elab', it is
-- normally correct to call elabE - the ones that don't are desugarings
-- typically
elabE :: ElabCtxt -> Maybe FC -> PTerm -> ElabD ()
elabE ina fc' t =
do solved <- get_recents
as <- get_autos
hs <- get_holes
-- If any of the autos use variables which have recently been solved,
-- have another go at solving them now.
mapM_ (\(a, (failc, ns)) ->
if any (\n -> n `elem` solved) ns && head hs /= a
then solveAuto ist fn False (a, failc)
else return ()) as
itm <- if not pattern then insertImpLam ina t else return t
ct <- insertCoerce ina itm
t' <- insertLazy ct
g <- goal
tm <- get_term
ps <- get_probs
hs <- get_holes
--trace ("Elaborating " ++ show t' ++ " in " ++ show g
-- ++ "\n" ++ show tm
-- ++ "\nholes " ++ show hs
-- ++ "\nproblems " ++ show ps
-- ++ "\n-----------\n") $
--trace ("ELAB " ++ show t') $
let fc = fileFC "Force"
env <- get_env
handleError (forceErr t' env)
(elab' ina fc' t')
(elab' ina fc' (PApp fc (PRef fc [] (sUN "Force"))
[pimp (sUN "t") Placeholder True,
pimp (sUN "a") Placeholder True,
pexp ct]))
forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _)
| (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t),
ht == txt "Lazy'" = notDelay orig
forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _)
| (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t'),
ht == txt "Lazy'" = notDelay orig
forceErr orig env (InfiniteUnify _ t _)
| (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t),
ht == txt "Lazy'" = notDelay orig
forceErr orig env (Elaborating _ _ _ t) = forceErr orig env t
forceErr orig env (ElaboratingArg _ _ _ t) = forceErr orig env t
forceErr orig env (At _ t) = forceErr orig env t
forceErr orig env t = False
notDelay t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Delay" = False
notDelay _ = True
local f = do e <- get_env
return (f `elem` map fst e)
-- | Is a constant a type?
constType :: Const -> Bool
constType (AType _) = True
constType StrType = True
constType VoidType = True
constType _ = False
-- "guarded" means immediately under a constructor, to help find patvars
elab' :: ElabCtxt -- ^ (in an argument, guarded, in a type, in a quasiquote)
-> Maybe FC -- ^ The closest FC in the syntax tree, if applicable
-> PTerm -- ^ The term to elaborate
-> ElabD ()
elab' ina fc (PNoImplicits t) = elab' ina fc t -- skip elabE step
elab' ina fc (PType fc') =
do apply RType []
solve
highlightSource fc' (AnnType "Type" "The type of types")
elab' ina fc (PUniverse u) = do apply (RUType u) []; solve
-- elab' (_,_,inty) (PConstant c)
-- | constType c && pattern && not reflection && not inty
-- = lift $ tfail (Msg "Typecase is not allowed")
elab' ina fc tm@(PConstant fc' c)
| pattern && not reflection && not (e_qq ina) && not (e_intype ina)
&& isTypeConst c
= lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
| pattern && not reflection && not (e_qq ina) && e_nomatching ina
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| otherwise = do apply (RConstant c) []
solve
highlightSource fc' (AnnConst c)
elab' ina fc (PQuote r) = do fill r; solve
elab' ina _ (PTrue fc _) =
do hnf_compute
g <- goal
case g of
TType _ -> elab' ina (Just fc) (PRef fc [] unitTy)
UType _ -> elab' ina (Just fc) (PRef fc [] unitTy)
_ -> elab' ina (Just fc) (PRef fc [] unitCon)
elab' ina fc (PResolveTC (FC "HACK" _ _)) -- for chasing parent classes
= do g <- goal; resolveTC' False False 5 g fn ist
elab' ina fc (PResolveTC fc')
= do c <- getNameFrom (sMN 0 "__class")
instanceArg c
-- Elaborate the equality type first homogeneously, then
-- heterogeneously as a fallback
elab' ina _ (PApp fc (PRef _ _ n) args)
| n == eqTy, [Placeholder, Placeholder, l, r] <- map getTm args
= try (do tyn <- getNameFrom (sMN 0 "aqty")
claim tyn RType
movelast tyn
elab' ina (Just fc) (PApp fc (PRef fc [] eqTy)
[pimp (sUN "A") (PRef NoFC [] tyn) True,
pimp (sUN "B") (PRef NoFC [] tyn) False,
pexp l, pexp r]))
(do atyn <- getNameFrom (sMN 0 "aqty")
btyn <- getNameFrom (sMN 0 "bqty")
claim atyn RType
movelast atyn
claim btyn RType
movelast btyn
elab' ina (Just fc) (PApp fc (PRef fc [] eqTy)
[pimp (sUN "A") (PRef NoFC [] atyn) True,
pimp (sUN "B") (PRef NoFC [] btyn) False,
pexp l, pexp r]))
elab' ina _ (PPair fc hls _ l r)
= do hnf_compute
g <- goal
let (tc, _) = unApply g
case g of
TType _ -> elab' ina (Just fc) (PApp fc (PRef fc hls pairTy)
[pexp l,pexp r])
UType _ -> elab' ina (Just fc) (PApp fc (PRef fc hls upairTy)
[pexp l,pexp r])
_ -> case tc of
P _ n _ | n == upairTy
-> elab' ina (Just fc) (PApp fc (PRef fc hls upairCon)
[pimp (sUN "A") Placeholder False,
pimp (sUN "B") Placeholder False,
pexp l, pexp r])
_ -> elab' ina (Just fc) (PApp fc (PRef fc hls pairCon)
[pimp (sUN "A") Placeholder False,
pimp (sUN "B") Placeholder False,
pexp l, pexp r])
-- _ -> try' (elab' ina (Just fc) (PApp fc (PRef fc pairCon)
-- [pimp (sUN "A") Placeholder False,
-- pimp (sUN "B") Placeholder False,
-- pexp l, pexp r]))
-- (elab' ina (Just fc) (PApp fc (PRef fc upairCon)
-- [pimp (sUN "A") Placeholder False,
-- pimp (sUN "B") Placeholder False,
-- pexp l, pexp r]))
-- True
elab' ina _ (PDPair fc hls p l@(PRef nfc hl n) t r)
= case t of
Placeholder ->
do hnf_compute
g <- goal
case g of
TType _ -> asType
_ -> asValue
_ -> asType
where asType = elab' ina (Just fc) (PApp fc (PRef NoFC hls sigmaTy)
[pexp t,
pexp (PLam fc n nfc Placeholder r)])
asValue = elab' ina (Just fc) (PApp fc (PRef fc hls sigmaCon)
[pimp (sMN 0 "a") t False,
pimp (sMN 0 "P") Placeholder True,
pexp l, pexp r])
elab' ina _ (PDPair fc hls p l t r) = elab' ina (Just fc) (PApp fc (PRef fc hls sigmaCon)
[pimp (sMN 0 "a") t False,
pimp (sMN 0 "P") Placeholder True,
pexp l, pexp r])
elab' ina fc (PAlternative ms (ExactlyOne delayok) as)
= do as_pruned <- doPrune as
-- Finish the mkUniqueNames job with the pruned set, rather than
-- the full set.
uns <- get_usedns
let as' = map (mkUniqueNames (uns ++ map snd ms) ms) as_pruned
(h : hs) <- get_holes
ty <- goal
case as' of
[] -> do hds <- mapM showHd as
lift $ tfail $ NoValidAlts hds
[x] -> elab' ina fc x
-- If there's options, try now, and if that fails, postpone
-- to later.
_ -> handleError isAmbiguous
(do hds <- mapM showHd as'
tryAll (zip (map (elab' ina fc) as')
hds))
(do movelast h
delayElab 5 $ do
hs <- get_holes
when (h `elem` hs) $ do
focus h
as'' <- doPrune as'
case as'' of
[x] -> elab' ina fc x
_ -> do hds <- mapM showHd as''
tryAll (zip (map (elab' ina fc) as'')
hds))
where showHd (PApp _ (PRef _ _ (UN l)) [_, _, arg])
| l == txt "Delay" = showHd (getTm arg)
showHd (PApp _ (PRef _ _ n) _) = return n
showHd (PRef _ _ n) = return n
showHd (PApp _ h _) = showHd h
showHd x = getNameFrom (sMN 0 "_") -- We probably should do something better than this here
doPrune as =
do compute
ty <- goal
let (tc, _) = unApply (unDelay ty)
env <- get_env
return $ pruneByType env tc ist as
unDelay t | (P _ (UN l) _, [_, arg]) <- unApply t,
l == txt "Lazy'" = unDelay arg
| otherwise = t
isAmbiguous (CantResolveAlts _) = delayok
isAmbiguous (Elaborating _ _ _ e) = isAmbiguous e
isAmbiguous (ElaboratingArg _ _ _ e) = isAmbiguous e
isAmbiguous (At _ e) = isAmbiguous e
isAmbiguous _ = False
elab' ina fc (PAlternative ms FirstSuccess as_in)
= do -- finish the mkUniqueNames job
uns <- get_usedns
let as = map (mkUniqueNames (uns ++ map snd ms) ms) as_in
trySeq as
where -- if none work, take the error from the first
trySeq (x : xs) = let e1 = elab' ina fc x in
try' e1 (trySeq' e1 xs) True
trySeq [] = fail "Nothing to try in sequence"
trySeq' deferr [] = proofFail deferr
trySeq' deferr (x : xs)
= try' (do elab' ina fc x
solveAutos ist fn False) (trySeq' deferr xs) True
elab' ina fc (PAlternative ms TryImplicit (orig : alts)) = do
env <- get_env
compute
ty <- goal
let doelab = elab' ina fc orig
tryCatch doelab
(\err ->
if recoverableErr err
then -- trace ("NEED IMPLICIT! " ++ show orig ++ "\n" ++
-- show alts ++ "\n" ++
-- showQuick err) $
-- Prune the coercions so that only the ones
-- with the right type to fix the error will be tried!
case pruneAlts err alts env of
[] -> lift $ tfail err
alts' -> do
try' (elab' ina fc (PAlternative ms (ExactlyOne False) alts'))
(lift $ tfail err) -- take error from original if all fail
True
else lift $ tfail err)
where
recoverableErr (CantUnify _ _ _ _ _ _) = True
recoverableErr (TooManyArguments _) = False
recoverableErr (CantSolveGoal _ _) = False
recoverableErr (CantResolveAlts _) = False
recoverableErr (NoValidAlts _) = True
recoverableErr (ProofSearchFail (Msg _)) = True
recoverableErr (ProofSearchFail _) = False
recoverableErr (ElaboratingArg _ _ _ e) = recoverableErr e
recoverableErr (At _ e) = recoverableErr e
recoverableErr (ElabScriptDebug _ _ _) = False
recoverableErr _ = True
pruneAlts (CantUnify _ (inc, _) (outc, _) _ _ _) alts env
= case unApply (normalise (tt_ctxt ist) env inc) of
(P (TCon _ _) n _, _) -> filter (hasArg n env) alts
(Constant _, _) -> alts
_ -> filter isLend alts -- special case hack for 'Borrowed'
pruneAlts (ElaboratingArg _ _ _ e) alts env = pruneAlts e alts env
pruneAlts (At _ e) alts env = pruneAlts e alts env
pruneAlts (NoValidAlts as) alts env = alts
pruneAlts err alts _ = filter isLend alts
hasArg n env ap | isLend ap = True -- special case hack for 'Borrowed'
hasArg n env (PApp _ (PRef _ _ a) _)
= case lookupTyExact a (tt_ctxt ist) of
Just ty -> let args = map snd (getArgTys (normalise (tt_ctxt ist) env ty)) in
any (fnIs n) args
Nothing -> False
hasArg n env (PAlternative _ _ as) = any (hasArg n env) as
hasArg n _ tm = False
isLend (PApp _ (PRef _ _ l) _) = l == sNS (sUN "lend") ["Ownership"]
isLend _ = False
fnIs n ty = case unApply ty of
(P _ n' _, _) -> n == n'
_ -> False
showQuick (CantUnify _ (l, _) (r, _) _ _ _)
= show (l, r)
showQuick (ElaboratingArg _ _ _ e) = showQuick e
showQuick (At _ e) = showQuick e
showQuick (ProofSearchFail (Msg _)) = "search fail"
showQuick _ = "No chance"
elab' ina _ (PPatvar fc n) | bindfree
= do patvar n
update_term liftPats
highlightSource fc (AnnBoundName n False)
-- elab' (_, _, inty) (PRef fc f)
-- | isTConName f (tt_ctxt ist) && pattern && not reflection && not inty
-- = lift $ tfail (Msg "Typecase is not allowed")
elab' ec _ tm@(PRef fc hl n)
| pattern && not reflection && not (e_qq ec) && not (e_intype ec)
&& isTConName n (tt_ctxt ist)
= lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
| pattern && not reflection && not (e_qq ec) && e_nomatching ec
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| (pattern || intransform || (bindfree && bindable n)) && not (inparamBlock n) && not (e_qq ec)
= do let ina = e_inarg ec
guarded = e_guarded ec
inty = e_intype ec
ctxt <- get_context
let defined = case lookupTy n ctxt of
[] -> False
_ -> True
-- this is to stop us resolve type classes recursively
-- trace (show (n, guarded)) $
if (tcname n && ina && not intransform)
then erun fc $
do patvar n
update_term liftPats
highlightSource fc (AnnBoundName n False)
else if (defined && not guarded)
then do apply (Var n) []
annot <- findHighlight n
solve
highlightSource fc annot
else try (do apply (Var n) []
annot <- findHighlight n
solve
highlightSource fc annot)
(do patvar n
update_term liftPats
highlightSource fc (AnnBoundName n False))
where inparamBlock n = case lookupCtxtName n (inblock info) of
[] -> False
_ -> True
bindable (NS _ _) = False
bindable n = implicitable n
elab' ina _ f@(PInferRef fc hls n) = elab' ina (Just fc) (PApp NoFC f [])
elab' ina fc' tm@(PRef fc hls n)
| pattern && not reflection && not (e_qq ina) && not (e_intype ina)
&& isTConName n (tt_ctxt ist)
= lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
| pattern && not reflection && not (e_qq ina) && e_nomatching ina
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| otherwise =
do fty <- get_type (Var n) -- check for implicits
ctxt <- get_context
env <- get_env
let a' = insertScopedImps fc (normalise ctxt env fty) []
if null a'
then erun fc $
do apply (Var n) []
hilite <- findHighlight n
solve
mapM_ (uncurry highlightSource) $
(fc, hilite) : map (\f -> (f, hilite)) hls
else elab' ina fc' (PApp fc tm [])
elab' ina _ (PLam _ _ _ _ PImpossible) = lift . tfail . Msg $ "Only pattern-matching lambdas can be impossible"
elab' ina _ (PLam fc n nfc Placeholder sc)
= do -- if n is a type constructor name, this makes no sense...
ctxt <- get_context
when (isTConName n ctxt) $
lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here")
checkPiGoal n
attack; intro (Just n);
addPSname n -- okay for proof search
-- trace ("------ intro " ++ show n ++ " ---- \n" ++ show ptm)
elabE (ina { e_inarg = True } ) (Just fc) sc; solve
highlightSource nfc (AnnBoundName n False)
elab' ec _ (PLam fc n nfc ty sc)
= do tyn <- getNameFrom (sMN 0 "lamty")
-- if n is a type constructor name, this makes no sense...
ctxt <- get_context
when (isTConName n ctxt) $
lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here")
checkPiGoal n
claim tyn RType
explicit tyn
attack
ptm <- get_term
hs <- get_holes
introTy (Var tyn) (Just n)
addPSname n -- okay for proof search
focus tyn
elabE (ec { e_inarg = True, e_intype = True }) (Just fc) ty
elabE (ec { e_inarg = True }) (Just fc) sc
solve
highlightSource nfc (AnnBoundName n False)
elab' ina fc (PPi p n nfc Placeholder sc)
= do attack; arg n (is_scoped p) (sMN 0 "ty")
addPSname n -- okay for proof search
elabE (ina { e_inarg = True, e_intype = True }) fc sc
solve
highlightSource nfc (AnnBoundName n False)
elab' ina fc (PPi p n nfc ty sc)
= do attack; tyn <- getNameFrom (sMN 0 "ty")
claim tyn RType
n' <- case n of
MN _ _ -> unique_hole n
_ -> return n
forall n' (is_scoped p) (Var tyn)
addPSname n' -- okay for proof search
focus tyn
let ec' = ina { e_inarg = True, e_intype = True }
elabE ec' fc ty
elabE ec' fc sc
solve
highlightSource nfc (AnnBoundName n False)
elab' ina _ tm@(PLet fc n nfc ty val sc)
= do attack
ivs <- get_instances
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
explicit valn
letbind n (Var tyn) (Var valn)
addPSname n
case ty of
Placeholder -> return ()
_ -> do focus tyn
explicit tyn
elabE (ina { e_inarg = True, e_intype = True })
(Just fc) ty
focus valn
elabE (ina { e_inarg = True, e_intype = True })
(Just fc) val
ivs' <- get_instances
env <- get_env
elabE (ina { e_inarg = True }) (Just fc) sc
when (not (pattern || intransform)) $
mapM_ (\n -> do focus n
g <- goal
hs <- get_holes
if all (\n -> n == tyn || not (n `elem` hs)) (freeNames g)
then handleError (tcRecoverable emode)
(resolveTC' True False 10 g fn ist)
(movelast n)
else movelast n)
(ivs' \\ ivs)
-- HACK: If the name leaks into its type, it may leak out of
-- scope outside, so substitute in the outer scope.
expandLet n (case lookup n env of
Just (Let t v) -> v
other -> error ("Value not a let binding: " ++ show other))
solve
highlightSource nfc (AnnBoundName n False)
elab' ina _ (PGoal fc r n sc) = do
rty <- goal
attack
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letbind n (Var tyn) (Var valn)
focus valn
elabE (ina { e_inarg = True, e_intype = True }) (Just fc) (PApp fc r [pexp (delab ist rty)])
env <- get_env
computeLet n
elabE (ina { e_inarg = True }) (Just fc) sc
solve
-- elab' ina fc (PLet n Placeholder
-- (PApp fc r [pexp (delab ist rty)]) sc)
elab' ina _ tm@(PApp fc (PInferRef _ _ f) args) = do
rty <- goal
ds <- get_deferred
ctxt <- get_context
-- make a function type a -> b -> c -> ... -> rty for the
-- new function name
env <- get_env
argTys <- claimArgTys env args
fn <- getNameFrom (sMN 0 "inf_fn")
let fty = fnTy argTys rty
-- trace (show (ptm, map fst argTys)) $ focus fn
-- build and defer the function application
attack; deferType (mkN f) fty (map fst argTys); solve
-- elaborate the arguments, to unify their types. They all have to
-- be explicit.
mapM_ elabIArg (zip argTys args)
where claimArgTys env [] = return []
claimArgTys env (arg : xs) | Just n <- localVar env (getTm arg)
= do nty <- get_type (Var n)
ans <- claimArgTys env xs
return ((n, (False, forget nty)) : ans)
claimArgTys env (_ : xs)
= do an <- getNameFrom (sMN 0 "inf_argTy")
aval <- getNameFrom (sMN 0 "inf_arg")
claim an RType
claim aval (Var an)
ans <- claimArgTys env xs
return ((aval, (True, (Var an))) : ans)
fnTy [] ret = forget ret
fnTy ((x, (_, xt)) : xs) ret = RBind x (Pi Nothing xt RType) (fnTy xs ret)
localVar env (PRef _ _ x)
= case lookup x env of
Just _ -> Just x
_ -> Nothing
localVar env _ = Nothing
elabIArg ((n, (True, ty)), def) =
do focus n; elabE ina (Just fc) (getTm def)
elabIArg _ = return () -- already done, just a name
mkN n@(NS _ _) = n
mkN n@(SN _) = n
mkN n = case namespace info of
Just xs@(_:_) -> sNS n xs
_ -> n
elab' ina _ (PMatchApp fc fn)
= do (fn', imps) <- case lookupCtxtName fn (idris_implicits ist) of
[(n, args)] -> return (n, map (const True) args)
_ -> lift $ tfail (NoSuchVariable fn)
ns <- match_apply (Var fn') (map (\x -> (x,0)) imps)
solve
-- if f is local, just do a simple_app
-- FIXME: Anyone feel like refactoring this mess? - EB
elab' ina topfc tm@(PApp fc (PRef ffc hls f) args_in)
| pattern && not reflection && not (e_qq ina) && e_nomatching ina
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| otherwise = implicitApp $
do env <- get_env
ty <- goal
fty <- get_type (Var f)
ctxt <- get_context
annot <- findHighlight f
mapM_ checkKnownImplicit args_in
let args = insertScopedImps fc (normalise ctxt env fty) args_in
let unmatchableArgs = if pattern
then getUnmatchable (tt_ctxt ist) f
else []
-- trace ("BEFORE " ++ show f ++ ": " ++ show ty) $
when (pattern && not reflection && not (e_qq ina) && not (e_intype ina)
&& isTConName f (tt_ctxt ist)) $
lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
-- trace (show (f, args_in, args)) $
if (f `elem` map fst env && length args == 1 && length args_in == 1)
then -- simple app, as below
do simple_app False
(elabE (ina { e_isfn = True }) (Just fc) (PRef ffc hls f))
(elabE (ina { e_inarg = True }) (Just fc) (getTm (head args)))
(show tm)
solve
mapM (uncurry highlightSource) $
(ffc, annot) : map (\f -> (f, annot)) hls
return []
else
do ivs <- get_instances
ps <- get_probs
-- HACK: we shouldn't resolve type classes if we're defining an instance
-- function or default definition.
let isinf = f == inferCon || tcname f
-- if f is a type class, we need to know its arguments so that
-- we can unify with them
case lookupCtxt f (idris_classes ist) of
[] -> return ()
_ -> do mapM_ setInjective (map getTm args)
-- maybe more things are solvable now
unifyProblems
let guarded = isConName f ctxt
-- trace ("args is " ++ show args) $ return ()
ns <- apply (Var f) (map isph args)
-- trace ("ns is " ++ show ns) $ return ()
-- mark any type class arguments as injective
when (not pattern) $ mapM_ checkIfInjective (map snd ns)
unifyProblems -- try again with the new information,
-- to help with disambiguation
ulog <- getUnifyLog
annot <- findHighlight f
mapM (uncurry highlightSource) $
(ffc, annot) : map (\f -> (f, annot)) hls
elabArgs ist (ina { e_inarg = e_inarg ina || not isinf })
[] fc False f
(zip ns (unmatchableArgs ++ repeat False))
(f == sUN "Force")
(map (\x -> getTm x) args) -- TODO: remove this False arg
imp <- if (e_isfn ina) then
do guess <- get_guess
env <- get_env
case safeForgetEnv (map fst env) guess of
Nothing ->
return []
Just rguess -> do
gty <- get_type rguess
let ty_n = normalise ctxt env gty
return $ getReqImps ty_n
else return []
-- Now we find out how many implicits we needed at the
-- end of the application by looking at the goal again
-- - Have another go, but this time add the
-- implicits (can't think of a better way than this...)
case imp of
rs@(_:_) | not pattern -> return rs -- quit, try again
_ -> do solve
hs <- get_holes
ivs' <- get_instances
-- Attempt to resolve any type classes which have 'complete' types,
-- i.e. no holes in them
when (not pattern || (e_inarg ina && not tcgen &&
not (e_guarded ina))) $
mapM_ (\n -> do focus n
g <- goal
env <- get_env
hs <- get_holes
if all (\n -> not (n `elem` hs)) (freeNames g)
then handleError (tcRecoverable emode)
(resolveTC' False False 10 g fn ist)
(movelast n)
else movelast n)
(ivs' \\ ivs)
return []
where
-- Run the elaborator, which returns how many implicit
-- args were needed, then run it again with those args. We need
-- this because we have to elaborate the whole application to
-- find out whether any computations have caused more implicits
-- to be needed.
implicitApp :: ElabD [ImplicitInfo] -> ElabD ()
implicitApp elab
| pattern || intransform = do elab; return ()
| otherwise
= do s <- get
imps <- elab
case imps of
[] -> return ()
es -> do put s
elab' ina topfc (PAppImpl tm es)
checkKnownImplicit imp
| UnknownImp `elem` argopts imp
= lift $ tfail $ UnknownImplicit (pname imp) f
checkKnownImplicit _ = return ()
getReqImps (Bind x (Pi (Just i) ty _) sc)
= i : getReqImps sc
getReqImps _ = []
checkIfInjective n = do
env <- get_env
case lookup n env of
Nothing -> return ()
Just b ->
case unApply (normalise (tt_ctxt ist) env (binderTy b)) of
(P _ c _, args) ->
case lookupCtxtExact c (idris_classes ist) of
Nothing -> return ()
Just ci -> -- type class, set as injective
do mapM_ setinjArg (getDets 0 (class_determiners ci) args)
-- maybe we can solve more things now...
ulog <- getUnifyLog
probs <- get_probs
traceWhen ulog ("Injective now " ++ show args ++ "\n" ++ qshow probs) $
unifyProblems
probs <- get_probs
traceWhen ulog (qshow probs) $ return ()
_ -> return ()
setinjArg (P _ n _) = setinj n
setinjArg _ = return ()
getDets i ds [] = []
getDets i ds (a : as) | i `elem` ds = a : getDets (i + 1) ds as
| otherwise = getDets (i + 1) ds as
tacTm (PTactics _) = True
tacTm (PProof _) = True
tacTm _ = False
setInjective (PRef _ _ n) = setinj n
setInjective (PApp _ (PRef _ _ n) _) = setinj n
setInjective _ = return ()
elab' ina _ tm@(PApp fc f [arg]) =
erun fc $
do simple_app (not $ headRef f)
(elabE (ina { e_isfn = True }) (Just fc) f)
(elabE (ina { e_inarg = True }) (Just fc) (getTm arg))
(show tm)
solve
where headRef (PRef _ _ _) = True
headRef (PApp _ f _) = headRef f
headRef (PAlternative _ _ as) = all headRef as
headRef _ = False
elab' ina fc (PAppImpl f es) = do appImpl (reverse es) -- not that we look...
solve
where appImpl [] = elab' (ina { e_isfn = False }) fc f -- e_isfn not set, so no recursive expansion of implicits
appImpl (e : es) = simple_app False
(appImpl es)
(elab' ina fc Placeholder)
(show f)
elab' ina fc Placeholder
= do (h : hs) <- get_holes
movelast h
elab' ina fc (PMetavar nfc n) =
do ptm <- get_term
-- When building the metavar application, leave out the unique
-- names which have been used elsewhere in the term, since we
-- won't be able to use them in the resulting application.
let unique_used = getUniqueUsed (tt_ctxt ist) ptm
let n' = metavarName (namespace info) n
attack
psns <- getPSnames
n' <- defer unique_used n'
solve
highlightSource nfc (AnnName n' (Just MetavarOutput) Nothing Nothing)
elab' ina fc (PProof ts) = do compute; mapM_ (runTac True ist (elabFC info) fn) ts
elab' ina fc (PTactics ts)
| not pattern = do mapM_ (runTac False ist fc fn) ts
| otherwise = elab' ina fc Placeholder
elab' ina fc (PElabError e) = lift $ tfail e
elab' ina _ (PRewrite fc r sc newg)
= do attack
tyn <- getNameFrom (sMN 0 "rty")
claim tyn RType
valn <- getNameFrom (sMN 0 "rval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "_rewrite_rule")
letbind letn (Var tyn) (Var valn)
focus valn
elab' ina (Just fc) r
compute
g <- goal
rewrite (Var letn)
g' <- goal
when (g == g') $ lift $ tfail (NoRewriting g)
case newg of
Nothing -> elab' ina (Just fc) sc
Just t -> doEquiv t sc
solve
where doEquiv t sc =
do attack
tyn <- getNameFrom (sMN 0 "ety")
claim tyn RType
valn <- getNameFrom (sMN 0 "eqval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "equiv_val")
letbind letn (Var tyn) (Var valn)
focus tyn
elab' ina (Just fc) t
focus valn
elab' ina (Just fc) sc
elab' ina (Just fc) (PRef fc [] letn)
solve
elab' ina _ c@(PCase fc scr opts)
= do attack
tyn <- getNameFrom (sMN 0 "scty")
claim tyn RType
valn <- getNameFrom (sMN 0 "scval")
scvn <- getNameFrom (sMN 0 "scvar")
claim valn (Var tyn)
letbind scvn (Var tyn) (Var valn)
focus valn
elabE (ina { e_inarg = True }) (Just fc) scr
-- Solve any remaining implicits - we need to solve as many
-- as possible before making the 'case' type
unifyProblems
matchProblems True
args <- get_env
envU <- mapM (getKind args) args
let namesUsedInRHS = nub $ scvn : concatMap (\(_,rhs) -> allNamesIn rhs) opts
-- Drop the unique arguments used in the term already
-- and in the scrutinee (since it's
-- not valid to use them again anyway)
--
-- Also drop unique arguments which don't appear explicitly
-- in either case branch so they don't count as used
-- unnecessarily (can only do this for unique things, since we
-- assume they don't appear implicitly in types)
ptm <- get_term
let inOpts = (filter (/= scvn) (map fst args)) \\ (concatMap (\x -> allNamesIn (snd x)) opts)
let argsDropped = filter (isUnique envU)
(nub $ allNamesIn scr ++ inApp ptm ++
inOpts)
let args' = filter (\(n, _) -> n `notElem` argsDropped) args
attack
cname' <- defer argsDropped (mkN (mkCaseName fc fn))
solve
-- if the scrutinee is one of the 'args' in env, we should
-- inspect it directly, rather than adding it as a new argument
let newdef = PClauses fc [] cname'
(caseBlock fc cname' scr
(map (isScr scr) (reverse args')) opts)
-- elaborate case
updateAux (\e -> e { case_decls = (cname', newdef) : case_decls e } )
-- if we haven't got the type yet, hopefully we'll get it later!
movelast tyn
solve
where mkCaseName fc (NS n ns) = NS (mkCaseName fc n) ns
mkCaseName fc n = SN (CaseN (FC' fc) n)
-- mkCaseName (UN x) = UN (x ++ "_case")
-- mkCaseName (MN i x) = MN i (x ++ "_case")
mkN n@(NS _ _) = n
mkN n = case namespace info of
Just xs@(_:_) -> sNS n xs
_ -> n
inApp (P _ n _) = [n]
inApp (App _ f a) = inApp f ++ inApp a
inApp (Bind n (Let _ v) sc) = inApp v ++ inApp sc
inApp (Bind n (Guess _ v) sc) = inApp v ++ inApp sc
inApp (Bind n b sc) = inApp sc
inApp _ = []
isUnique envk n = case lookup n envk of
Just u -> u
_ -> False
getKind env (n, _)
= case lookup n env of
Nothing -> return (n, False) -- can't happen, actually...
Just b ->
do ty <- get_type (forget (binderTy b))
case ty of
UType UniqueType -> return (n, True)
UType AllTypes -> return (n, True)
_ -> return (n, False)
tcName tm | (P _ n _, _) <- unApply tm
= case lookupCtxt n (idris_classes ist) of
[_] -> True
_ -> False
tcName _ = False
usedIn ns (n, b)
= n `elem` ns
|| any (\x -> x `elem` ns) (allTTNames (binderTy b))
elab' ina fc (PUnifyLog t) = do unifyLog True
elab' ina fc t
unifyLog False
elab' ina fc (PQuasiquote t goalt)
= do -- First extract the unquoted subterms, replacing them with fresh
-- names in the quasiquoted term. Claim their reflections to be
-- an inferred type (to support polytypic quasiquotes).
finalTy <- goal
(t, unq) <- extractUnquotes 0 t
let unquoteNames = map fst unq
mapM_ (\uqn -> claim uqn (forget finalTy)) unquoteNames
-- Save the old state - we need a fresh proof state to avoid
-- capturing lexically available variables in the quoted term.
ctxt <- get_context
datatypes <- get_datatypes
saveState
updatePS (const .
newProof (sMN 0 "q") ctxt datatypes $
P Ref (reflm "TT") Erased)
-- Re-add the unquotes, letting Idris infer the (fictional)
-- types. Here, they represent the real type rather than the type
-- of their reflection.
mapM_ (\n -> do ty <- getNameFrom (sMN 0 "unqTy")
claim ty RType
movelast ty
claim n (Var ty)
movelast n)
unquoteNames
-- Determine whether there's an explicit goal type, and act accordingly
-- Establish holes for the type and value of the term to be
-- quasiquoted
qTy <- getNameFrom (sMN 0 "qquoteTy")
claim qTy RType
movelast qTy
qTm <- getNameFrom (sMN 0 "qquoteTm")
claim qTm (Var qTy)
-- Let-bind the result of elaborating the contained term, so that
-- the hole doesn't disappear
nTm <- getNameFrom (sMN 0 "quotedTerm")
letbind nTm (Var qTy) (Var qTm)
-- Fill out the goal type, if relevant
case goalt of
Nothing -> return ()
Just gTy -> do focus qTy
elabE (ina { e_qq = True }) fc gTy
-- Elaborate the quasiquoted term into the hole
focus qTm
elabE (ina { e_qq = True }) fc t
end_unify
-- We now have an elaborated term. Reflect it and solve the
-- original goal in the original proof state, preserving highlighting
env <- get_env
EState _ _ _ hs <- getAux
loadState
updateAux (\aux -> aux { highlighting = hs })
let quoted = fmap (explicitNames . binderVal) $ lookup nTm env
isRaw = case unApply (normaliseAll ctxt env finalTy) of
(P _ n _, []) | n == reflm "Raw" -> True
_ -> False
case quoted of
Just q -> do ctxt <- get_context
(q', _, _) <- lift $ recheck ctxt [(uq, Lam Erased) | uq <- unquoteNames] (forget q) q
if pattern
then if isRaw
then reflectRawQuotePattern unquoteNames (forget q')
else reflectTTQuotePattern unquoteNames q'
else do if isRaw
then -- we forget q' instead of using q to ensure rechecking
fill $ reflectRawQuote unquoteNames (forget q')
else fill $ reflectTTQuote unquoteNames q'
solve
Nothing -> lift . tfail . Msg $ "Broken elaboration of quasiquote"
-- Finally fill in the terms or patterns from the unquotes. This
-- happens last so that their holes still exist while elaborating
-- the main quotation.
mapM_ elabUnquote unq
where elabUnquote (n, tm)
= do focus n
elabE (ina { e_qq = False }) fc tm
elab' ina fc (PUnquote t) = fail "Found unquote outside of quasiquote"
elab' ina fc (PQuoteName n False nfc) =
do fill $ reflectName n
solve
elab' ina fc (PQuoteName n True nfc) =
do ctxt <- get_context
env <- get_env
case lookup n env of
Just _ -> do fill $ reflectName n
solve
highlightSource nfc (AnnBoundName n False)
Nothing ->
case lookupNameDef n ctxt of
[(n', _)] -> do fill $ reflectName n'
solve
highlightSource nfc (AnnName n' Nothing Nothing Nothing)
[] -> lift . tfail . NoSuchVariable $ n
more -> lift . tfail . CantResolveAlts $ map fst more
elab' ina fc (PAs _ n t) = lift . tfail . Msg $ "@-pattern not allowed here"
elab' ina fc (PHidden t)
| reflection = elab' ina fc t
| otherwise
= do (h : hs) <- get_holes
-- Dotting a hole means that either the hole or any outer
-- hole (a hole outside any occurrence of it)
-- must be solvable by unification as well as being filled
-- in directly.
-- Delay dotted things to the end, then when we elaborate them
-- we can check the result against what was inferred
movelast h
delayElab 10 $ do focus h
dotterm
elab' ina fc t
elab' ina fc (PRunElab fc' tm ns) =
do attack
n <- getNameFrom (sMN 0 "tacticScript")
let scriptTy = RApp (Var (sNS (sUN "Elab")
["Elab", "Reflection", "Language"]))
(Var unitTy)
claim n scriptTy
focus n
attack -- to get an extra hole
elab' ina (Just fc') tm
script <- get_guess
fullyElaborated script
solve -- eliminate the hole. Becuase there are no references, the script is only in the binding
env <- get_env
runElabAction ist (maybe fc' id fc) env script ns
solve
elab' ina fc (PConstSugar constFC tm) =
-- Here we elaborate the contained term, then calculate
-- highlighting for constFC. The highlighting is the
-- highlighting for the outermost constructor of the result of
-- evaluating the elaborated term, if one exists (it always
-- should, but better to fail gracefully for something silly
-- like highlighting info). This is how implicit applications of
-- fromInteger get highlighted.
do saveState -- so we don't pollute the elaborated term
n <- getNameFrom (sMN 0 "cstI")
n' <- getNameFrom (sMN 0 "cstIhole")
g <- forget <$> goal
claim n' g
movelast n'
-- In order to intercept the elaborated value, we need to
-- let-bind it.
attack
letbind n g (Var n')
focus n'
elab' ina fc tm
env <- get_env
ctxt <- get_context
let v = fmap (normaliseAll ctxt env . finalise . binderVal)
(lookup n env)
loadState -- we have the highlighting - re-elaborate the value
elab' ina fc tm
case v of
Just val -> highlightConst constFC val
Nothing -> return ()
where highlightConst fc (P _ n _) =
highlightSource fc (AnnName n Nothing Nothing Nothing)
highlightConst fc (App _ f _) =
highlightConst fc f
highlightConst fc (Constant c) =
highlightSource fc (AnnConst c)
highlightConst _ _ = return ()
elab' ina fc x = fail $ "Unelaboratable syntactic form " ++ showTmImpls x
-- delay elaboration of 't', with priority 'pri' until after everything
-- else is done.
-- The delayed things with lower numbered priority will be elaborated
-- first. (In practice, this means delayed alternatives, then PHidden
-- things.)
delayElab pri t
= updateAux (\e -> e { delayed_elab = delayed_elab e ++ [(pri, t)] })
isScr :: PTerm -> (Name, Binder Term) -> (Name, (Bool, Binder Term))
isScr (PRef _ _ n) (n', b) = (n', (n == n', b))
isScr _ (n', b) = (n', (False, b))
caseBlock :: FC -> Name
-> PTerm -- original scrutinee
-> [(Name, (Bool, Binder Term))] -> [(PTerm, PTerm)] -> [PClause]
caseBlock fc n scr env opts
= let args' = findScr env
args = map mkarg (map getNmScr args') in
map (mkClause args) opts
where -- Find the variable we want as the scrutinee and mark it as
-- 'True'. If the scrutinee is in the environment, match on that
-- otherwise match on the new argument we're adding.
findScr ((n, (True, t)) : xs)
= (n, (True, t)) : scrName n xs
findScr [(n, (_, t))] = [(n, (True, t))]
findScr (x : xs) = x : findScr xs
-- [] can't happen since scrutinee is in the environment!
findScr [] = error "The impossible happened - the scrutinee was not in the environment"
-- To make sure top level pattern name remains in scope, put
-- it at the end of the environment
scrName n [] = []
scrName n [(_, t)] = [(n, t)]
scrName n (x : xs) = x : scrName n xs
getNmScr (n, (s, _)) = (n, s)
mkarg (n, s) = (PRef fc [] n, s)
-- may be shadowed names in the new pattern - so replace the
-- old ones with an _
-- Also, names which don't appear on the rhs should not be
-- fixed on the lhs, or this restricts the kind of matching
-- we can do to non-dependent types.
mkClause args (l, r)
= let args' = map (shadowed (allNamesIn l)) args
args'' = map (implicitable (allNamesIn r ++
keepscrName scr)) args'
lhs = PApp (getFC fc l) (PRef NoFC [] n)
(map (mkLHSarg l) args'') in
PClause (getFC fc l) n lhs [] r []
-- Keep scrutinee available if it's just a name (this makes
-- the names in scope look better when looking at a hole on
-- the rhs of a case)
keepscrName (PRef _ _ n) = [n]
keepscrName _ = []
mkLHSarg l (tm, True) = pexp l
mkLHSarg l (tm, False) = pexp tm
shadowed new (PRef _ _ n, s) | n `elem` new = (Placeholder, s)
shadowed new t = t
implicitable rhs (PRef _ _ n, s) | n `notElem` rhs = (Placeholder, s)
implicitable rhs t = t
getFC d (PApp fc _ _) = fc
getFC d (PRef fc _ _) = fc
getFC d (PAlternative _ _ (x:_)) = getFC d x
getFC d x = d
-- Fail if a term is not yet fully elaborated (e.g. if it contains
-- case block functions that don't yet exist)
fullyElaborated :: Term -> ElabD ()
fullyElaborated (P _ n _) =
do EState cases _ _ _ <- getAux
case lookup n cases of
Nothing -> return ()
Just _ -> lift . tfail $ ElabScriptStaging n
fullyElaborated (Bind n b body) = fullyElaborated body >> for_ b fullyElaborated
fullyElaborated (App _ l r) = fullyElaborated l >> fullyElaborated r
fullyElaborated (Proj t _) = fullyElaborated t
fullyElaborated _ = return ()
insertLazy :: PTerm -> ElabD PTerm
insertLazy t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Delay" = return t
insertLazy t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Force" = return t
insertLazy (PCoerced t) = return t
insertLazy t =
do ty <- goal
env <- get_env
let (tyh, _) = unApply (normalise (tt_ctxt ist) env ty)
let tries = if pattern then [t, mkDelay env t] else [mkDelay env t, t]
case tyh of
P _ (UN l) _ | l == txt "Lazy'"
-> return (PAlternative [] FirstSuccess tries)
_ -> return t
where
mkDelay env (PAlternative ms b xs) = PAlternative ms b (map (mkDelay env) xs)
mkDelay env t
= let fc = fileFC "Delay" in
addImplBound ist (map fst env) (PApp fc (PRef fc [] (sUN "Delay"))
[pexp t])
-- Don't put implicit coercions around applications which are marked
-- as '%noImplicit', or around case blocks, otherwise we get exponential
-- blowup especially where there are errors deep in large expressions.
notImplicitable (PApp _ f _) = notImplicitable f
-- TMP HACK no coercing on bind (make this configurable)
notImplicitable (PRef _ _ n)
| [opts] <- lookupCtxt n (idris_flags ist)
= NoImplicit `elem` opts
notImplicitable (PAlternative _ _ as) = any notImplicitable as
-- case is tricky enough without implicit coercions! If they are needed,
-- they can go in the branches separately.
notImplicitable (PCase _ _ _) = True
notImplicitable _ = False
insertScopedImps fc (Bind n (Pi im@(Just i) _ _) sc) xs
| tcinstance i && not (toplevel_imp i)
= pimp n (PResolveTC fc) True : insertScopedImps fc sc xs
| not (toplevel_imp i)
= pimp n Placeholder True : insertScopedImps fc sc xs
insertScopedImps fc (Bind n (Pi _ _ _) sc) (x : xs)
= x : insertScopedImps fc sc xs
insertScopedImps _ _ xs = xs
insertImpLam ina t =
do ty <- goal
env <- get_env
let ty' = normalise (tt_ctxt ist) env ty
addLam ty' t
where
-- just one level at a time
addLam (Bind n (Pi (Just _) _ _) sc) t =
do impn <- unique_hole n -- (sMN 0 "scoped_imp")
if e_isfn ina -- apply to an implicit immediately
then return (PApp emptyFC
(PLam emptyFC impn NoFC Placeholder t)
[pexp Placeholder])
else return (PLam emptyFC impn NoFC Placeholder t)
addLam _ t = return t
insertCoerce ina t@(PCase _ _ _) = return t
insertCoerce ina t | notImplicitable t = return t
insertCoerce ina t =
do ty <- goal
-- Check for possible coercions to get to the goal
-- and add them as 'alternatives'
env <- get_env
let ty' = normalise (tt_ctxt ist) env ty
let cs = getCoercionsTo ist ty'
let t' = case (t, cs) of
(PCoerced tm, _) -> tm
(_, []) -> t
(_, cs) -> PAlternative [] TryImplicit
(t : map (mkCoerce env t) cs)
return t'
where
mkCoerce env (PAlternative ms aty tms) n
= PAlternative ms aty (map (\t -> mkCoerce env t n) tms)
mkCoerce env t n = let fc = maybe (fileFC "Coercion") id (highestFC t) in
addImplBound ist (map fst env)
(PApp fc (PRef fc [] n) [pexp (PCoerced t)])
-- | Elaborate the arguments to a function
elabArgs :: IState -- ^ The current Idris state
-> ElabCtxt -- ^ (in an argument, guarded, in a type, in a qquote)
-> [Bool]
-> FC -- ^ Source location
-> Bool
-> Name -- ^ Name of the function being applied
-> [((Name, Name), Bool)] -- ^ (Argument Name, Hole Name, unmatchable)
-> Bool -- ^ under a 'force'
-> [PTerm] -- ^ argument
-> ElabD ()
elabArgs ist ina failed fc retry f [] force _ = return ()
elabArgs ist ina failed fc r f (((argName, holeName), unm):ns) force (t : args)
= do hs <- get_holes
if holeName `elem` hs then
do focus holeName
case t of
Placeholder -> do movelast holeName
elabArgs ist ina failed fc r f ns force args
_ -> elabArg t
else elabArgs ist ina failed fc r f ns force args
where elabArg t =
do -- solveAutos ist fn False
now_elaborating fc f argName
wrapErr f argName $ do
hs <- get_holes
tm <- get_term
-- No coercing under an explicit Force (or it can Force/Delay
-- recursively!)
let elab = if force then elab' else elabE
failed' <- -- trace (show (n, t, hs, tm)) $
-- traceWhen (not (null cs)) (show ty ++ "\n" ++ showImp True t) $
do focus holeName;
g <- goal
-- Can't pattern match on polymorphic goals
poly <- goal_polymorphic
ulog <- getUnifyLog
traceWhen ulog ("Elaborating argument " ++ show (argName, holeName, g)) $
elab (ina { e_nomatching = unm && poly }) (Just fc) t
return failed
done_elaborating_arg f argName
elabArgs ist ina failed fc r f ns force args
wrapErr f argName action =
do elabState <- get
while <- elaborating_app
let while' = map (\(x, y, z)-> (y, z)) while
(result, newState) <- case runStateT action elabState of
OK (res, newState) -> return (res, newState)
Error e -> do done_elaborating_arg f argName
lift (tfail (elaboratingArgErr while' e))
put newState
return result
elabArgs _ _ _ _ _ _ (((arg, hole), _) : _) _ [] =
fail $ "Can't elaborate these args: " ++ show arg ++ " " ++ show hole
-- For every alternative, look at the function at the head. Automatically resolve
-- any nested alternatives where that function is also at the head
pruneAlt :: [PTerm] -> [PTerm]
pruneAlt xs = map prune xs
where
prune (PApp fc1 (PRef fc2 hls f) as)
= PApp fc1 (PRef fc2 hls f) (fmap (fmap (choose f)) as)
prune t = t
choose f (PAlternative ms a as)
= let as' = fmap (choose f) as
fs = filter (headIs f) as' in
case fs of
[a] -> a
_ -> PAlternative ms a as'
choose f (PApp fc f' as) = PApp fc (choose f f') (fmap (fmap (choose f)) as)
choose f t = t
headIs f (PApp _ (PRef _ _ f') _) = f == f'
headIs f (PApp _ f' _) = headIs f f'
headIs f _ = True -- keep if it's not an application
-- Rule out alternatives that don't return the same type as the head of the goal
-- (If there are none left as a result, do nothing)
pruneByType :: Env -> Term -> -- head of the goal
IState -> [PTerm] -> [PTerm]
-- if an alternative has a locally bound name at the head, take it
pruneByType env t c as
| Just a <- locallyBound as = [a]
where
locallyBound [] = Nothing
locallyBound (t:ts)
| Just n <- getName t,
n `elem` map fst env = Just t
| otherwise = locallyBound ts
getName (PRef _ _ n) = Just n
getName (PApp _ (PRef _ _ (UN l)) [_, _, arg]) -- ignore Delays
| l == txt "Delay" = getName (getTm arg)
getName (PApp _ f _) = getName f
getName (PHidden t) = getName t
getName _ = Nothing
-- 'n' is the name at the head of the goal type
pruneByType env (P _ n _) ist as
-- if the goal type is polymorphic, keep everything
| Nothing <- lookupTyExact n ctxt = as
-- if the goal type is a ?metavariable, keep everything
| Just _ <- lookup n (idris_metavars ist) = as
| otherwise
= let asV = filter (headIs True n) as
as' = filter (headIs False n) as in
case as' of
[] -> asV
_ -> as'
where
ctxt = tt_ctxt ist
headIs var f (PRef _ _ f') = typeHead var f f'
headIs var f (PApp _ (PRef _ _ (UN l)) [_, _, arg])
| l == txt "Delay" = headIs var f (getTm arg)
headIs var f (PApp _ (PRef _ _ f') _) = typeHead var f f'
headIs var f (PApp _ f' _) = headIs var f f'
headIs var f (PPi _ _ _ _ sc) = headIs var f sc
headIs var f (PHidden t) = headIs var f t
headIs var f t = True -- keep if it's not an application
typeHead var f f'
= -- trace ("Trying " ++ show f' ++ " for " ++ show n) $
case lookupTyExact f' ctxt of
Just ty -> case unApply (getRetTy ty) of
(P _ ctyn _, _) | isConName ctyn ctxt -> ctyn == f
_ -> let ty' = normalise ctxt [] ty in
case unApply (getRetTy ty') of
(P _ ftyn _, _) -> ftyn == f
(V _, _) ->
-- keep, variable
-- trace ("Keeping " ++ show (f', ty')
-- ++ " for " ++ show n) $
isPlausible ist var env n ty
_ -> False
_ -> False
pruneByType _ t _ as = as
-- Could the name feasibly be the return type?
-- If there is a type class constraint on the return type, and no instance
-- in the environment or globally for that name, then no
-- Otherwise, yes
-- (FIXME: This isn't complete, but I'm leaving it here and coming back
-- to it later - just returns 'var' for now. EB)
isPlausible :: IState -> Bool -> Env -> Name -> Type -> Bool
isPlausible ist var env n ty
= let (hvar, classes) = collectConstraints [] [] ty in
case hvar of
Nothing -> True
Just rth -> var -- trace (show (rth, classes)) var
where
collectConstraints :: [Name] -> [(Term, [Name])] -> Type ->
(Maybe Name, [(Term, [Name])])
collectConstraints env tcs (Bind n (Pi _ ty _) sc)
= let tcs' = case unApply ty of
(P _ c _, _) ->
case lookupCtxtExact c (idris_classes ist) of
Just tc -> ((ty, map fst (class_instances tc))
: tcs)
Nothing -> tcs
_ -> tcs
in
collectConstraints (n : env) tcs' sc
collectConstraints env tcs t
| (V i, _) <- unApply t = (Just (env !! i), tcs)
| otherwise = (Nothing, tcs)
-- | Use the local elab context to work out the highlighting for a name
findHighlight :: Name -> ElabD OutputAnnotation
findHighlight n = do ctxt <- get_context
env <- get_env
case lookup n env of
Just _ -> return $ AnnBoundName n False
Nothing -> case lookupTyExact n ctxt of
Just _ -> return $ AnnName n Nothing Nothing Nothing
Nothing -> lift . tfail . InternalMsg $
"Can't find name " ++ show n
-- Try again to solve auto implicits
solveAuto :: IState -> Name -> Bool -> (Name, [FailContext]) -> ElabD ()
solveAuto ist fn ambigok (n, failc)
= do hs <- get_holes
when (not (null hs)) $ do
env <- get_env
g <- goal
handleError cantsolve (when (n `elem` hs) $ do
focus n
isg <- is_guess -- if it's a guess, we're working on it recursively, so stop
when (not isg) $
proofSearch' ist True ambigok 100 True Nothing fn [] [])
(lift $ Error (addLoc failc
(CantSolveGoal g (map (\(n, b) -> (n, binderTy b)) env))))
return ()
where addLoc (FailContext fc f x : prev) err
= At fc (ElaboratingArg f x
(map (\(FailContext _ f' x') -> (f', x')) prev) err)
addLoc _ err = err
cantsolve (CantSolveGoal _ _) = True
cantsolve (InternalMsg _) = True
cantsolve (At _ e) = cantsolve e
cantsolve (Elaborating _ _ _ e) = cantsolve e
cantsolve (ElaboratingArg _ _ _ e) = cantsolve e
cantsolve _ = False
solveAutos :: IState -> Name -> Bool -> ElabD ()
solveAutos ist fn ambigok
= do autos <- get_autos
mapM_ (solveAuto ist fn ambigok) (map (\(n, (fc, _)) -> (n, fc)) autos)
-- Return true if the given error suggests a type class failure is
-- recoverable
tcRecoverable :: ElabMode -> Err -> Bool
tcRecoverable ERHS (CantResolve f g) = f
tcRecoverable ETyDecl (CantResolve f g) = f
tcRecoverable e (ElaboratingArg _ _ _ err) = tcRecoverable e err
tcRecoverable e (At _ err) = tcRecoverable e err
tcRecoverable _ _ = True
trivial' ist
= trivial (elab ist toplevel ERHS [] (sMN 0 "tac")) ist
trivialHoles' psn h ist
= trivialHoles psn h (elab ist toplevel ERHS [] (sMN 0 "tac")) ist
proofSearch' ist rec ambigok depth prv top n psns hints
= do unifyProblems
proofSearch rec prv ambigok (not prv) depth
(elab ist toplevel ERHS [] (sMN 0 "tac")) top n psns hints ist
resolveTC' di mv depth tm n ist
= resolveTC di mv depth tm n (elab ist toplevel ERHS [] (sMN 0 "tac")) ist
collectDeferred :: Maybe Name -> [Name] -> Context ->
Term -> State [(Name, (Int, Maybe Name, Type, [Name]))] Term
collectDeferred top casenames ctxt (Bind n (GHole i psns t) app) =
do ds <- get
t' <- collectDeferred top casenames ctxt t
when (not (n `elem` map fst ds)) $ put (ds ++ [(n, (i, top, tidyArg [] t', psns))])
collectDeferred top casenames ctxt app
where
-- Evaluate the top level functions in arguments, if possible, and if it's
-- not a name we're immediately going to define in a case block, so that
-- any immediate specialisation of the function applied to constructors
-- can be done
tidyArg env (Bind n b@(Pi im t k) sc)
= Bind n (Pi im (tidy ctxt env t) k)
(tidyArg ((n, b) : env) sc)
tidyArg env t = tidy ctxt env t
tidy ctxt env t = normalise ctxt env t
getFn (Bind n (Lam _) t) = getFn t
getFn t | (f, a) <- unApply t = f
collectDeferred top ns ctxt (Bind n b t)
= do b' <- cdb b
t' <- collectDeferred top ns ctxt t
return (Bind n b' t')
where
cdb (Let t v) = liftM2 Let (collectDeferred top ns ctxt t) (collectDeferred top ns ctxt v)
cdb (Guess t v) = liftM2 Guess (collectDeferred top ns ctxt t) (collectDeferred top ns ctxt v)
cdb b = do ty' <- collectDeferred top ns ctxt (binderTy b)
return (b { binderTy = ty' })
collectDeferred top ns ctxt (App s f a) = liftM2 (App s) (collectDeferred top ns ctxt f)
(collectDeferred top ns ctxt a)
collectDeferred top ns ctxt t = return t
case_ :: Bool -> Bool -> IState -> Name -> PTerm -> ElabD ()
case_ ind autoSolve ist fn tm = do
attack
tyn <- getNameFrom (sMN 0 "ity")
claim tyn RType
valn <- getNameFrom (sMN 0 "ival")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "irule")
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
env <- get_env
let (Just binding) = lookup letn env
let val = binderVal binding
if ind then induction (forget val)
else casetac (forget val)
when autoSolve solveAll
-- | Compute the appropriate name for a top-level metavariable
metavarName :: Maybe [String] -> Name -> Name
metavarName _ n@(NS _ _) = n
metavarName (Just (ns@(_:_))) n = sNS n ns
metavarName _ n = n
runElabAction :: IState -> FC -> Env -> Term -> [String] -> ElabD Term
runElabAction ist fc env tm ns = do tm' <- eval tm
runTacTm tm'
where
eval tm = do ctxt <- get_context
return $ normaliseAll ctxt env (finalise tm)
returnUnit = return $ P (DCon 0 0 False) unitCon (P (TCon 0 0) unitTy Erased)
patvars :: [Name] -> Term -> ([Name], Term)
patvars ns (Bind n (PVar t) sc) = patvars (n : ns) (instantiate (P Bound n t) sc)
patvars ns tm = (ns, tm)
pullVars :: (Term, Term) -> ([Name], Term, Term)
pullVars (lhs, rhs) = (fst (patvars [] lhs), snd (patvars [] lhs), snd (patvars [] rhs)) -- TODO alpha-convert rhs
defineFunction :: RFunDefn -> ElabD ()
defineFunction (RDefineFun n clauses) =
do ctxt <- get_context
ty <- maybe (fail "no type decl") return $ lookupTyExact n ctxt
let info = CaseInfo True True False -- TODO document and figure out
clauses' <- forM clauses (\case
RMkFunClause lhs rhs ->
do (lhs', lty) <- lift $ check ctxt [] lhs
(rhs', rty) <- lift $ check ctxt [] rhs
lift $ converts ctxt [] lty rty
return $ Right (lhs', rhs')
RMkImpossibleClause lhs ->
do lhs' <- fmap fst . lift $ check ctxt [] lhs
return $ Left lhs')
let clauses'' = map (\case Right c -> pullVars c
Left lhs -> let (ns, lhs') = patvars [] lhs'
in (ns, lhs', Impossible))
clauses'
ctxt'<- lift $
addCasedef n (const [])
info False (STerm Erased)
True False -- TODO what are these?
(map snd $ getArgTys ty) [] -- TODO inaccessible types
clauses'
clauses''
clauses''
clauses''
clauses''
ty
ctxt
set_context ctxt'
updateAux $ \e -> e { new_tyDecls = RClausesInstrs n clauses'' : new_tyDecls e}
return ()
checkClosed :: Raw -> Elab' aux (Term, Type)
checkClosed tm = do ctxt <- get_context
(val, ty) <- lift $ check ctxt [] tm
return $! (finalise val, finalise ty)
-- | Do a step in the reflected elaborator monad. The input is the
-- step, the output is the (reflected) term returned.
runTacTm :: Term -> ElabD Term
runTacTm (unApply -> tac@(P _ n _, args))
| n == tacN "Prim__Solve", [] <- args
= do solve
returnUnit
| n == tacN "Prim__Goal", [] <- args
= do hs <- get_holes
case hs of
(h : _) -> do t <- goal
fmap fst . checkClosed $
rawPair (Var (reflm "TTName"), Var (reflm "TT"))
(reflectName h, reflect t)
[] -> lift . tfail . Msg $
"Elaboration is complete. There are no goals."
| n == tacN "Prim__Holes", [] <- args
= do hs <- get_holes
fmap fst . checkClosed $
mkList (Var $ reflm "TTName") (map reflectName hs)
| n == tacN "Prim__Guess", [] <- args
= do g <- get_guess
fmap fst . checkClosed $ reflect g
| n == tacN "Prim__LookupTy", [n] <- args
= do n' <- reifyTTName n
ctxt <- get_context
let getNameTypeAndType = \case Function ty _ -> (Ref, ty)
TyDecl nt ty -> (nt, ty)
Operator ty _ _ -> (Ref, ty)
CaseOp _ ty _ _ _ _ -> (Ref, ty)
-- Idris tuples nest to the right
reflectTriple (x, y, z) =
raw_apply (Var pairCon) [ Var (reflm "TTName")
, raw_apply (Var pairTy) [Var (reflm "NameType"), Var (reflm "TT")]
, x
, raw_apply (Var pairCon) [ Var (reflm "NameType"), Var (reflm "TT")
, y, z]]
let defs = [ reflectTriple (reflectName n, reflectNameType nt, reflect ty)
| (n, def) <- lookupNameDef n' ctxt
, let (nt, ty) = getNameTypeAndType def ]
fmap fst . checkClosed $
rawList (raw_apply (Var pairTy) [ Var (reflm "TTName")
, raw_apply (Var pairTy) [ Var (reflm "NameType")
, Var (reflm "TT")]])
defs
| n == tacN "Prim__LookupDatatype", [name] <- args
= do n' <- reifyTTName name
datatypes <- get_datatypes
ctxt <- get_context
fmap fst . checkClosed $
rawList (Var (tacN "Datatype"))
(map reflectDatatype (buildDatatypes ist n'))
| n == tacN "Prim__LookupArgs", [name] <- args
= do n' <- reifyTTName name
let listTy = Var (sNS (sUN "List") ["List", "Prelude"])
listFunArg = RApp listTy (Var (tacN "FunArg"))
-- Idris tuples nest to the right
let reflectTriple (x, y, z) =
raw_apply (Var pairCon) [ Var (reflm "TTName")
, raw_apply (Var pairTy) [listFunArg, Var (reflm "Raw")]
, x
, raw_apply (Var pairCon) [listFunArg, Var (reflm "Raw")
, y, z]]
let out =
[ reflectTriple (reflectName fn, reflectList (Var (tacN "FunArg")) (map reflectArg args), reflectRaw res)
| (fn, pargs) <- lookupCtxtName n' (idris_implicits ist)
, (args, res) <- getArgs pargs . forget <$>
maybeToList (lookupTyExact fn (tt_ctxt ist))
]
fmap fst . checkClosed $
rawList (raw_apply (Var pairTy) [Var (reflm "TTName")
, raw_apply (Var pairTy) [ RApp listTy
(Var (tacN "FunArg"))
, Var (reflm "Raw")]])
out
| n == tacN "Prim__SourceLocation", [] <- args
= fmap fst . checkClosed $
reflectFC fc
| n == tacN "Prim__Namespace", [] <- args
= fmap fst . checkClosed $
rawList (RConstant StrType) (map (RConstant . Str) ns)
| n == tacN "Prim__Env", [] <- args
= do env <- get_env
fmap fst . checkClosed $ reflectEnv env
| n == tacN "Prim__Fail", [_a, errs] <- args
= do errs' <- eval errs
parts <- reifyReportParts errs'
lift . tfail $ ReflectionError [parts] (Msg "")
| n == tacN "Prim__PureElab", [_a, tm] <- args
= return tm
| n == tacN "Prim__BindElab", [_a, _b, first, andThen] <- args
= do first' <- eval first
res <- eval =<< runTacTm first'
next <- eval (App Complete andThen res)
runTacTm next
| n == tacN "Prim__Try", [_a, first, alt] <- args
= do first' <- eval first
alt' <- eval alt
try' (runTacTm first') (runTacTm alt') True
| n == tacN "Prim__Fill", [raw] <- args
= do raw' <- reifyRaw =<< eval raw
apply raw' []
returnUnit
| n == tacN "Prim__Apply" || n == tacN "Prim__MatchApply"
, [raw, argSpec] <- args
= do raw' <- reifyRaw =<< eval raw
argSpec' <- map (\b -> (b, 0)) <$> reifyList reifyBool argSpec
let op = if n == tacN "Prim__Apply"
then apply
else match_apply
ns <- op raw' argSpec'
fmap fst . checkClosed $
rawList (rawPairTy (Var $ reflm "TTName") (Var $ reflm "TTName"))
[ rawPair (Var $ reflm "TTName", Var $ reflm "TTName")
(reflectName n1, reflectName n2)
| (n1, n2) <- ns
]
| n == tacN "Prim__Gensym", [hint] <- args
= do hintStr <- eval hint
case hintStr of
Constant (Str h) -> do
n <- getNameFrom (sMN 0 h)
fmap fst $ get_type_val (reflectName n)
_ -> fail "no hint"
| n == tacN "Prim__Claim", [n, ty] <- args
= do n' <- reifyTTName n
ty' <- reifyRaw ty
claim n' ty'
returnUnit
| n == tacN "Prim__Check", [env', raw] <- args
= do env <- reifyEnv env'
raw' <- reifyRaw =<< eval raw
ctxt <- get_context
(tm, ty) <- lift $ check ctxt env raw'
fmap fst . checkClosed $
rawPair (Var (reflm "TT"), Var (reflm "TT"))
(reflect tm, reflect ty)
| n == tacN "Prim__Attack", [] <- args
= do attack
returnUnit
| n == tacN "Prim__Rewrite", [rule] <- args
= do r <- reifyRaw rule
rewrite r
returnUnit
| n == tacN "Prim__Focus", [what] <- args
= do n' <- reifyTTName what
hs <- get_holes
if elem n' hs
then focus n' >> returnUnit
else lift . tfail . Msg $ "The name " ++ show n' ++ " does not denote a hole"
| n == tacN "Prim__Unfocus", [what] <- args
= do n' <- reifyTTName what
movelast n'
returnUnit
| n == tacN "Prim__Intro", [mn] <- args
= do n <- case fromTTMaybe mn of
Nothing -> return Nothing
Just name -> fmap Just $ reifyTTName name
intro n
returnUnit
| n == tacN "Prim__Forall", [n, ty] <- args
= do n' <- reifyTTName n
ty' <- reifyRaw ty
forall n' Nothing ty'
returnUnit
| n == tacN "Prim__PatVar", [n] <- args
= do n' <- reifyTTName n
patvar' n'
returnUnit
| n == tacN "Prim__PatBind", [n] <- args
= do n' <- reifyTTName n
patbind n'
returnUnit
| n == tacN "Prim__LetBind", [n, ty, tm] <- args
= do n' <- reifyTTName n
ty' <- reifyRaw ty
tm' <- reifyRaw tm
letbind n' ty' tm'
returnUnit
| n == tacN "Prim__Compute", [] <- args
= do compute ; returnUnit
| n == tacN "Prim__Normalise", [env, tm] <- args
= do env' <- reifyEnv env
tm' <- reifyTT tm
ctxt <- get_context
let out = normaliseAll ctxt env' (finalise tm')
fmap fst . checkClosed $ reflect out
| n == tacN "Prim__Whnf", [tm] <- args
= do tm' <- reifyTT tm
ctxt <- get_context
fmap fst . checkClosed . reflect $ whnf ctxt tm'
| n == tacN "Prim__Converts", [env, tm1, tm2] <- args
= do env' <- reifyEnv env
tm1' <- reifyTT tm1
tm2' <- reifyTT tm2
ctxt <- get_context
lift $ converts ctxt env' tm1' tm2'
returnUnit
| n == tacN "Prim__DeclareType", [decl] <- args
= do (RDeclare n args res) <- reifyTyDecl decl
ctxt <- get_context
let mkPi arg res = RBind (argName arg)
(Pi Nothing (argTy arg) (RUType AllTypes))
res
rty = foldr mkPi res args
(checked, ty') <- lift $ check ctxt [] rty
case normaliseAll ctxt [] (finalise ty') of
UType _ -> return ()
TType _ -> return ()
ty'' -> lift . tfail . InternalMsg $
show checked ++ " is not a type: it's " ++ show ty''
case lookupDefExact n ctxt of
Just _ -> lift . tfail . InternalMsg $
show n ++ " is already defined."
Nothing -> return ()
let decl = TyDecl Ref checked
ctxt' = addCtxtDef n decl ctxt
set_context ctxt'
updateAux $ \e -> e { new_tyDecls = (RTyDeclInstrs n fc (map rFunArgToPArg args) checked) :
new_tyDecls e }
returnUnit
| n == tacN "Prim__DefineFunction", [decl] <- args
= do defn <- reifyFunDefn decl
defineFunction defn
returnUnit
| n == tacN "Prim__AddInstance", [cls, inst] <- args
= do className <- reifyTTName cls
instName <- reifyTTName inst
updateAux $ \e -> e { new_tyDecls = RAddInstance className instName :
new_tyDecls e}
returnUnit
| n == tacN "Prim__IsTCName", [n] <- args
= do n' <- reifyTTName n
case lookupCtxtExact n' (idris_classes ist) of
Just _ -> fmap fst . checkClosed $ Var (sNS (sUN "True") ["Bool", "Prelude"])
Nothing -> fmap fst . checkClosed $ Var (sNS (sUN "False") ["Bool", "Prelude"])
| n == tacN "Prim__ResolveTC", [fn] <- args
= do g <- goal
fn <- reifyTTName fn
resolveTC' False True 100 g fn ist
returnUnit
| n == tacN "Prim__Search", [depth, hints] <- args
= do d <- eval depth
hints' <- eval hints
case (d, unList hints') of
(Constant (I i), Just hs) ->
do actualHints <- mapM reifyTTName hs
unifyProblems
let psElab = elab ist toplevel ERHS [] (sMN 0 "tac")
proofSearch True True False False i psElab Nothing (sMN 0 "search ") [] actualHints ist
returnUnit
(Constant (I _), Nothing ) ->
lift . tfail . InternalMsg $ "Not a list: " ++ show hints'
(_, _) -> lift . tfail . InternalMsg $ "Can't reify int " ++ show d
| n == tacN "Prim__RecursiveElab", [goal, script] <- args
= do goal' <- reifyRaw goal
ctxt <- get_context
script <- eval script
(goalTT, goalTy) <- lift $ check ctxt [] goal'
lift $ isType ctxt [] goalTy
recH <- getNameFrom (sMN 0 "recElabHole")
aux <- getAux
datatypes <- get_datatypes
env <- get_env
(ctxt', ES (p, aux') _ _) <-
do (ES (current_p, _) _ _) <- get
lift $ runElab aux
(do runElabAction ist fc [] script ns
ctxt' <- get_context
return ctxt')
((newProof recH ctxt datatypes goalTT)
{ nextname = nextname current_p })
set_context ctxt'
let tm_out = getProofTerm (pterm p)
do (ES (prf, _) s e) <- get
let p' = prf { nextname = nextname p }
put (ES (p', aux') s e)
env' <- get_env
(tm, ty, _) <- lift $ recheck ctxt' env (forget tm_out) tm_out
let (tm', ty') = (reflect tm, reflect ty)
fmap fst . checkClosed $
rawPair (Var $ reflm "TT", Var $ reflm "TT")
(tm', ty')
| n == tacN "Prim__Metavar", [n] <- args
= do n' <- reifyTTName n
ctxt <- get_context
ptm <- get_term
-- See documentation above in the elab case for PMetavar
let unique_used = getUniqueUsed ctxt ptm
let mvn = metavarName (Just ns) n'
attack
defer unique_used mvn
solve
returnUnit
| n == tacN "Prim__Fixity", [op'] <- args
= do opTm <- eval op'
case opTm of
Constant (Str op) ->
let opChars = ":!#$%&*+./<=>?@\\^|-~"
invalidOperators = [":", "=>", "->", "<-", "=", "?=", "|", "**", "==>", "\\", "%", "~", "?", "!"]
fixities = idris_infixes ist
in if not (all (flip elem opChars) op) || elem op invalidOperators
then lift . tfail . Msg $ "'" ++ op ++ "' is not a valid operator name."
else case nub [f | Fix f someOp <- fixities, someOp == op] of
[] -> lift . tfail . Msg $ "No fixity found for operator '" ++ op ++ "'."
[f] -> fmap fst . checkClosed $ reflectFixity f
many -> lift . tfail . InternalMsg $ "Ambiguous fixity for '" ++ op ++ "'! Found " ++ show many
_ -> lift . tfail . Msg $ "Not a constant string for an operator name: " ++ show opTm
| n == tacN "Prim__Debug", [ty, msg] <- args
= do msg' <- eval msg
parts <- reifyReportParts msg
debugElaborator parts
runTacTm x = lift . tfail $ ElabScriptStuck x
-- Running tactics directly
-- if a tactic adds unification problems, return an error
runTac :: Bool -> IState -> Maybe FC -> Name -> PTactic -> ElabD ()
runTac autoSolve ist perhapsFC fn tac
= do env <- get_env
g <- goal
let tac' = fmap (addImplBound ist (map fst env)) tac
if autoSolve
then runT tac'
else no_errors (runT tac')
(Just (CantSolveGoal g (map (\(n, b) -> (n, binderTy b)) env)))
where
runT (Intro []) = do g <- goal
attack; intro (bname g)
where
bname (Bind n _ _) = Just n
bname _ = Nothing
runT (Intro xs) = mapM_ (\x -> do attack; intro (Just x)) xs
runT Intros = do g <- goal
attack;
intro (bname g)
try' (runT Intros)
(return ()) True
where
bname (Bind n _ _) = Just n
bname _ = Nothing
runT (Exact tm) = do elab ist toplevel ERHS [] (sMN 0 "tac") tm
when autoSolve solveAll
runT (MatchRefine fn)
= do fnimps <-
case lookupCtxtName fn (idris_implicits ist) of
[] -> do a <- envArgs fn
return [(fn, a)]
ns -> return (map (\ (n, a) -> (n, map (const True) a)) ns)
let tacs = map (\ (fn', imps) ->
(match_apply (Var fn') (map (\x -> (x, 0)) imps),
fn')) fnimps
tryAll tacs
when autoSolve solveAll
where envArgs n = do e <- get_env
case lookup n e of
Just t -> return $ map (const False)
(getArgTys (binderTy t))
_ -> return []
runT (Refine fn [])
= do fnimps <-
case lookupCtxtName fn (idris_implicits ist) of
[] -> do a <- envArgs fn
return [(fn, a)]
ns -> return (map (\ (n, a) -> (n, map isImp a)) ns)
let tacs = map (\ (fn', imps) ->
(apply (Var fn') (map (\x -> (x, 0)) imps),
fn')) fnimps
tryAll tacs
when autoSolve solveAll
where isImp (PImp _ _ _ _ _) = True
isImp _ = False
envArgs n = do e <- get_env
case lookup n e of
Just t -> return $ map (const False)
(getArgTys (binderTy t))
_ -> return []
runT (Refine fn imps) = do ns <- apply (Var fn) (map (\x -> (x,0)) imps)
when autoSolve solveAll
runT DoUnify = do unify_all
when autoSolve solveAll
runT (Claim n tm) = do tmHole <- getNameFrom (sMN 0 "newGoal")
claim tmHole RType
claim n (Var tmHole)
focus tmHole
elab ist toplevel ERHS [] (sMN 0 "tac") tm
focus n
runT (Equiv tm) -- let bind tm, then
= do attack
tyn <- getNameFrom (sMN 0 "ety")
claim tyn RType
valn <- getNameFrom (sMN 0 "eqval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "equiv_val")
letbind letn (Var tyn) (Var valn)
focus tyn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
focus valn
when autoSolve solveAll
runT (Rewrite tm) -- to elaborate tm, let bind it, then rewrite by that
= do attack; -- (h:_) <- get_holes
tyn <- getNameFrom (sMN 0 "rty")
-- start_unify h
claim tyn RType
valn <- getNameFrom (sMN 0 "rval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "rewrite_rule")
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
rewrite (Var letn)
when autoSolve solveAll
runT (Induction tm) -- let bind tm, similar to the others
= case_ True autoSolve ist fn tm
runT (CaseTac tm)
= case_ False autoSolve ist fn tm
runT (LetTac n tm)
= do attack
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- unique_hole n
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
when autoSolve solveAll
runT (LetTacTy n ty tm)
= do attack
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- unique_hole n
letbind letn (Var tyn) (Var valn)
focus tyn
elab ist toplevel ERHS [] (sMN 0 "tac") ty
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
when autoSolve solveAll
runT Compute = compute
runT Trivial = do trivial' ist; when autoSolve solveAll
runT TCInstance = runT (Exact (PResolveTC emptyFC))
runT (ProofSearch rec prover depth top psns hints)
= do proofSearch' ist rec False depth prover top fn psns hints
when autoSolve solveAll
runT (Focus n) = focus n
runT Unfocus = do hs <- get_holes
case hs of
[] -> return ()
(h : _) -> movelast h
runT Solve = solve
runT (Try l r) = do try' (runT l) (runT r) True
runT (TSeq l r) = do runT l; runT r
runT (ApplyTactic tm) = do tenv <- get_env -- store the environment
tgoal <- goal -- store the goal
attack -- let f : List (TTName, Binder TT) -> TT -> Tactic = tm in ...
script <- getNameFrom (sMN 0 "script")
claim script scriptTy
scriptvar <- getNameFrom (sMN 0 "scriptvar" )
letbind scriptvar scriptTy (Var script)
focus script
elab ist toplevel ERHS [] (sMN 0 "tac") tm
(script', _) <- get_type_val (Var scriptvar)
-- now that we have the script apply
-- it to the reflected goal and context
restac <- getNameFrom (sMN 0 "restac")
claim restac tacticTy
focus restac
fill (raw_apply (forget script')
[reflectEnv tenv, reflect tgoal])
restac' <- get_guess
solve
-- normalise the result in order to
-- reify it
ctxt <- get_context
env <- get_env
let tactic = normalise ctxt env restac'
runReflected tactic
where tacticTy = Var (reflm "Tactic")
listTy = Var (sNS (sUN "List") ["List", "Prelude"])
scriptTy = (RBind (sMN 0 "__pi_arg")
(Pi Nothing (RApp listTy envTupleType) RType)
(RBind (sMN 1 "__pi_arg")
(Pi Nothing (Var $ reflm "TT") RType) tacticTy))
runT (ByReflection tm) -- run the reflection function 'tm' on the
-- goal, then apply the resulting reflected Tactic
= do tgoal <- goal
attack
script <- getNameFrom (sMN 0 "script")
claim script scriptTy
scriptvar <- getNameFrom (sMN 0 "scriptvar" )
letbind scriptvar scriptTy (Var script)
focus script
ptm <- get_term
elab ist toplevel ERHS [] (sMN 0 "tac")
(PApp emptyFC tm [pexp (delabTy' ist [] tgoal True True)])
(script', _) <- get_type_val (Var scriptvar)
-- now that we have the script apply
-- it to the reflected goal
restac <- getNameFrom (sMN 0 "restac")
claim restac tacticTy
focus restac
fill (forget script')
restac' <- get_guess
solve
-- normalise the result in order to
-- reify it
ctxt <- get_context
env <- get_env
let tactic = normalise ctxt env restac'
runReflected tactic
where tacticTy = Var (reflm "Tactic")
scriptTy = tacticTy
runT (Reflect v) = do attack -- let x = reflect v in ...
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "letvar")
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") v
(value, _) <- get_type_val (Var letn)
ctxt <- get_context
env <- get_env
let value' = hnf ctxt env value
runTac autoSolve ist perhapsFC fn (Exact $ PQuote (reflect value'))
runT (Fill v) = do attack -- let x = fill x in ...
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "letvar")
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") v
(value, _) <- get_type_val (Var letn)
ctxt <- get_context
env <- get_env
let value' = normalise ctxt env value
rawValue <- reifyRaw value'
runTac autoSolve ist perhapsFC fn (Exact $ PQuote rawValue)
runT (GoalType n tac) = do g <- goal
case unApply g of
(P _ n' _, _) ->
if nsroot n' == sUN n
then runT tac
else fail "Wrong goal type"
_ -> fail "Wrong goal type"
runT ProofState = do g <- goal
return ()
runT Skip = return ()
runT (TFail err) = lift . tfail $ ReflectionError [err] (Msg "")
runT SourceFC =
case perhapsFC of
Nothing -> lift . tfail $ Msg "There is no source location available."
Just fc ->
do fill $ reflectFC fc
solve
runT Qed = lift . tfail $ Msg "The qed command is only valid in the interactive prover"
runT x = fail $ "Not implemented " ++ show x
runReflected t = do t' <- reify ist t
runTac autoSolve ist perhapsFC fn t'
elaboratingArgErr :: [(Name, Name)] -> Err -> Err
elaboratingArgErr [] err = err
elaboratingArgErr ((f,x):during) err = fromMaybe err (rewrite err)
where rewrite (ElaboratingArg _ _ _ _) = Nothing
rewrite (ProofSearchFail e) = fmap ProofSearchFail (rewrite e)
rewrite (At fc e) = fmap (At fc) (rewrite e)
rewrite err = Just (ElaboratingArg f x during err)
withErrorReflection :: Idris a -> Idris a
withErrorReflection x = idrisCatch x (\ e -> handle e >>= ierror)
where handle :: Err -> Idris Err
handle e@(ReflectionError _ _) = do logLvl 3 "Skipping reflection of error reflection result"
return e -- Don't do meta-reflection of errors
handle e@(ReflectionFailed _ _) = do logLvl 3 "Skipping reflection of reflection failure"
return e
-- At and Elaborating are just plumbing - error reflection shouldn't rewrite them
handle e@(At fc err) = do logLvl 3 "Reflecting body of At"
err' <- handle err
return (At fc err')
handle e@(Elaborating what n ty err) = do logLvl 3 "Reflecting body of Elaborating"
err' <- handle err
return (Elaborating what n ty err')
handle e@(ElaboratingArg f a prev err) = do logLvl 3 "Reflecting body of ElaboratingArg"
hs <- getFnHandlers f a
err' <- if null hs
then handle err
else applyHandlers err hs
return (ElaboratingArg f a prev err')
-- ProofSearchFail is an internal detail - so don't expose it
handle (ProofSearchFail e) = handle e
-- TODO: argument-specific error handlers go here for ElaboratingArg
handle e = do ist <- getIState
logLvl 2 "Starting error reflection"
logLvl 5 (show e)
let handlers = idris_errorhandlers ist
applyHandlers e handlers
getFnHandlers :: Name -> Name -> Idris [Name]
getFnHandlers f arg = do ist <- getIState
let funHandlers = maybe M.empty id .
lookupCtxtExact f .
idris_function_errorhandlers $ ist
return . maybe [] S.toList . M.lookup arg $ funHandlers
applyHandlers e handlers =
do ist <- getIState
let err = fmap (errReverse ist) e
logLvl 3 $ "Using reflection handlers " ++
concat (intersperse ", " (map show handlers))
let reports = map (\n -> RApp (Var n) (reflectErr err)) handlers
-- Typecheck error handlers - if this fails, then something else was wrong earlier!
handlers <- case mapM (check (tt_ctxt ist) []) reports of
Error e -> ierror $ ReflectionFailed "Type error while constructing reflected error" e
OK hs -> return hs
-- Normalize error handler terms to produce the new messages
ctxt <- getContext
let results = map (normalise ctxt []) (map fst handlers)
logLvl 3 $ "New error message info: " ++ concat (intersperse " and " (map show results))
-- For each handler term output, either discard it if it is Nothing or reify it the Haskell equivalent
let errorpartsTT = mapMaybe unList (mapMaybe fromTTMaybe results)
errorparts <- case mapM (mapM reifyReportPart) errorpartsTT of
Left err -> ierror err
Right ok -> return ok
return $ case errorparts of
[] -> e
parts -> ReflectionError errorparts e
solveAll = try (do solve; solveAll) (return ())
-- | Do the left-over work after creating declarations in reflected
-- elaborator scripts
processTacticDecls :: ElabInfo -> [RDeclInstructions] -> Idris ()
processTacticDecls info steps =
-- The order of steps is important: type declarations might
-- establish metavars that later function bodies resolve.
forM_ (reverse steps) $ \case
RTyDeclInstrs n fc impls ty ->
do logLvl 3 $ "Declaration from tactics: " ++ show n ++ " : " ++ show ty
logLvl 3 $ " It has impls " ++ show impls
updateIState $ \i -> i { idris_implicits =
addDef n impls (idris_implicits i) }
addIBC (IBCImp n)
ds <- checkDef fc (\_ e -> e) [(n, (-1, Nothing, ty, []))]
addIBC (IBCDef n)
ctxt <- getContext
case lookupDef n ctxt of
(TyDecl _ _ : _) ->
-- If the function isn't defined at the end of the elab script,
-- then it must be added as a metavariable. This needs guarding
-- to prevent overwriting case defs with a metavar, if the case
-- defs come after the type decl in the same script!
let ds' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, True))) ds
in addDeferred ds'
_ -> return ()
RAddInstance className instName ->
do -- The type class resolution machinery relies on a special
logLvl 2 $ "Adding elab script instance " ++ show instName ++
" for " ++ show className
addInstance False True className instName
addIBC (IBCInstance False True className instName)
RClausesInstrs n cs ->
do logLvl 3 $ "Pattern-matching definition from tactics: " ++ show n
solveDeferred n
let lhss = map (\(_, lhs, _) -> lhs) cs
let fc = fileFC "elab_reflected"
pmissing <-
do ist <- getIState
possible <- genClauses fc n lhss
(map (\lhs ->
delab' ist lhs True True) lhss)
missing <- filterM (checkPossible n) possible
return (filter (noMatch ist lhss) missing)
let tot = if null pmissing
then Unchecked -- still need to check recursive calls
else Partial NotCovering -- missing cases implies not total
setTotality n tot
updateIState $ \i -> i { idris_patdefs =
addDef n (cs, pmissing) $ idris_patdefs i }
addIBC (IBCDef n)
ctxt <- getContext
case lookupDefExact n ctxt of
Just (CaseOp _ _ _ _ _ cd) ->
-- Here, we populate the call graph with a list of things
-- we refer to, so that if they aren't total, the whole
-- thing won't be.
let (scargs, sc) = cases_compiletime cd
(scargs', sc') = cases_runtime cd
calls = findCalls sc' scargs
used = findUsedArgs sc' scargs'
cg = CGInfo scargs' calls [] used []
in do logLvl 2 $ "Called names in reflected elab: " ++ show cg
addToCG n cg
addToCalledG n (nub (map fst calls))
addIBC $ IBCCG n
Just _ -> return () -- TODO throw internal error
Nothing -> return ()
-- checkDeclTotality requires that the call graph be present
-- before calling it.
-- TODO: reduce code duplication with Idris.Elab.Clause
buildSCG (fc, n)
-- Actually run the totality checker. In the main clause
-- elaborator, this is deferred until after. Here, we run it
-- now to get totality information as early as possible.
tot' <- checkDeclTotality (fc, n)
setTotality n tot'
when (tot' /= Unchecked) $ addIBC (IBCTotal n tot')
where
-- TODO: see if the code duplication with Idris.Elab.Clause can be
-- reduced or eliminated.
checkPossible :: Name -> PTerm -> Idris Bool
checkPossible fname lhs_in =
do ctxt <- getContext
ist <- getIState
let lhs = addImplPat ist lhs_in
let fc = fileFC "elab_reflected_totality"
let tcgen = False -- TODO: later we may support dictionary generation
case elaborate ctxt (idris_datatypes ist) (sMN 0 "refPatLHS") infP initEState
(erun fc (buildTC ist info ELHS [] fname (allNamesIn lhs_in)
(infTerm lhs))) of
OK (ElabResult lhs' _ _ _ _ _, _) ->
do -- not recursively calling here, because we don't
-- want to run infinitely many times
let lhs_tm = orderPats (getInferTerm lhs')
case recheck ctxt [] (forget lhs_tm) lhs_tm of
OK _ -> return True
err -> return False
-- if it's a recoverable error, the case may become possible
Error err -> if tcgen then return (recoverableCoverage ctxt err)
else return (validCoverageCase ctxt err ||
recoverableCoverage ctxt err)
-- TODO: Attempt to reduce/eliminate code duplication with Idris.Elab.Clause
noMatch i cs tm = all (\x -> case matchClause i (delab' i x True True) tm of
Right _ -> False
Left _ -> True) cs
|
adnelson/Idris-dev
|
src/Idris/Elab/Term.hs
|
bsd-3-clause
| 119,645 | 1,365 | 62 | 52,758 | 24,158 | 13,969 | 10,189 | 2,107 | 226 |
-- (c) The University of Glasgow, 1997-2006
{-# LANGUAGE BangPatterns, CPP, DeriveDataTypeable, MagicHash, UnboxedTuples #-}
{-# OPTIONS_GHC -O -funbox-strict-fields #-}
-- We always optimise this, otherwise performance of a non-optimised
-- compiler is severely affected
-- |
-- There are two principal string types used internally by GHC:
--
-- ['FastString']
--
-- * A compact, hash-consed, representation of character strings.
-- * Comparison is O(1), and you can get a 'Unique.Unique' from them.
-- * Generated by 'fsLit'.
-- * Turn into 'Outputable.SDoc' with 'Outputable.ftext'.
--
-- ['LitString']
--
-- * Just a wrapper for the @Addr#@ of a C string (@Ptr CChar@).
-- * Practically no operations.
-- * Outputing them is fast.
-- * Generated by 'sLit'.
-- * Turn into 'Outputable.SDoc' with 'Outputable.ptext'
--
-- Use 'LitString' unless you want the facilities of 'FastString'.
module FastString
(
-- * ByteString
fastStringToByteString,
mkFastStringByteString,
fastZStringToByteString,
unsafeMkByteString,
hashByteString,
-- * FastZString
FastZString,
hPutFZS,
zString,
lengthFZS,
-- * FastStrings
FastString(..), -- not abstract, for now.
-- ** Construction
fsLit,
mkFastString,
mkFastStringBytes,
mkFastStringByteList,
mkFastStringForeignPtr,
mkFastString#,
-- ** Deconstruction
unpackFS, -- :: FastString -> String
bytesFS, -- :: FastString -> [Word8]
-- ** Encoding
zEncodeFS,
-- ** Operations
uniqueOfFS,
lengthFS,
nullFS,
appendFS,
headFS,
tailFS,
concatFS,
consFS,
nilFS,
-- ** Outputing
hPutFS,
-- ** Internal
getFastStringTable,
hasZEncoding,
-- * LitStrings
LitString,
-- ** Construction
sLit,
mkLitString#,
mkLitString,
-- ** Deconstruction
unpackLitString,
-- ** Operations
lengthLS
) where
#include "HsVersions.h"
import Encoding
import FastFunctions
import Panic
import Util
import Control.Monad
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Internal as BS
import qualified Data.ByteString.Unsafe as BS
import Foreign.C
import GHC.Exts
import System.IO
import System.IO.Unsafe ( unsafePerformIO )
import Data.Data
import Data.IORef ( IORef, newIORef, readIORef, atomicModifyIORef' )
import Data.Maybe ( isJust )
import Data.Char
import Data.List ( elemIndex )
import GHC.IO ( IO(..), unsafeDupablePerformIO )
import Foreign
#if STAGE >= 2
import GHC.Conc.Sync (sharedCAF)
#endif
import GHC.Base ( unpackCString# )
#define hASH_TBL_SIZE 4091
#define hASH_TBL_SIZE_UNBOXED 4091#
fastStringToByteString :: FastString -> ByteString
fastStringToByteString f = fs_bs f
fastZStringToByteString :: FastZString -> ByteString
fastZStringToByteString (FastZString bs) = bs
-- This will drop information if any character > '\xFF'
unsafeMkByteString :: String -> ByteString
unsafeMkByteString = BSC.pack
hashByteString :: ByteString -> Int
hashByteString bs
= inlinePerformIO $ BS.unsafeUseAsCStringLen bs $ \(ptr, len) ->
return $ hashStr (castPtr ptr) len
-- -----------------------------------------------------------------------------
newtype FastZString = FastZString ByteString
hPutFZS :: Handle -> FastZString -> IO ()
hPutFZS handle (FastZString bs) = BS.hPut handle bs
zString :: FastZString -> String
zString (FastZString bs) =
inlinePerformIO $ BS.unsafeUseAsCStringLen bs peekCAStringLen
lengthFZS :: FastZString -> Int
lengthFZS (FastZString bs) = BS.length bs
mkFastZStringString :: String -> FastZString
mkFastZStringString str = FastZString (BSC.pack str)
-- -----------------------------------------------------------------------------
{-|
A 'FastString' is an array of bytes, hashed to support fast O(1)
comparison. It is also associated with a character encoding, so that
we know how to convert a 'FastString' to the local encoding, or to the
Z-encoding used by the compiler internally.
'FastString's support a memoized conversion to the Z-encoding via zEncodeFS.
-}
data FastString = FastString {
uniq :: {-# UNPACK #-} !Int, -- unique id
n_chars :: {-# UNPACK #-} !Int, -- number of chars
fs_bs :: {-# UNPACK #-} !ByteString,
fs_ref :: {-# UNPACK #-} !(IORef (Maybe FastZString))
} deriving Typeable
instance Eq FastString where
f1 == f2 = uniq f1 == uniq f2
instance Ord FastString where
-- Compares lexicographically, not by unique
a <= b = case cmpFS a b of { LT -> True; EQ -> True; GT -> False }
a < b = case cmpFS a b of { LT -> True; EQ -> False; GT -> False }
a >= b = case cmpFS a b of { LT -> False; EQ -> True; GT -> True }
a > b = case cmpFS a b of { LT -> False; EQ -> False; GT -> True }
max x y | x >= y = x
| otherwise = y
min x y | x <= y = x
| otherwise = y
compare a b = cmpFS a b
instance Monoid FastString where
mempty = nilFS
mappend = appendFS
instance Show FastString where
show fs = show (unpackFS fs)
instance Data FastString where
-- don't traverse?
toConstr _ = abstractConstr "FastString"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "FastString"
cmpFS :: FastString -> FastString -> Ordering
cmpFS f1@(FastString u1 _ _ _) f2@(FastString u2 _ _ _) =
if u1 == u2 then EQ else
compare (fastStringToByteString f1) (fastStringToByteString f2)
foreign import ccall unsafe "ghc_memcmp"
memcmp :: Ptr a -> Ptr b -> Int -> IO Int
-- -----------------------------------------------------------------------------
-- Construction
{-
Internally, the compiler will maintain a fast string symbol table, providing
sharing and fast comparison. Creation of new @FastString@s then covertly does a
lookup, re-using the @FastString@ if there was a hit.
The design of the FastString hash table allows for lockless concurrent reads
and updates to multiple buckets with low synchronization overhead.
See Note [Updating the FastString table] on how it's updated.
-}
data FastStringTable =
FastStringTable
{-# UNPACK #-} !(IORef Int) -- the unique ID counter shared with all buckets
(MutableArray# RealWorld (IORef [FastString])) -- the array of mutable buckets
string_table :: FastStringTable
{-# NOINLINE string_table #-}
string_table = unsafePerformIO $ do
uid <- newIORef 603979776 -- ord '$' * 0x01000000
tab <- IO $ \s1# -> case newArray# hASH_TBL_SIZE_UNBOXED (panic "string_table") s1# of
(# s2#, arr# #) ->
(# s2#, FastStringTable uid arr# #)
forM_ [0.. hASH_TBL_SIZE-1] $ \i -> do
bucket <- newIORef []
updTbl tab i bucket
-- use the support wired into the RTS to share this CAF among all images of
-- libHSghc
#if STAGE < 2
return tab
#else
sharedCAF tab getOrSetLibHSghcFastStringTable
-- from the RTS; thus we cannot use this mechanism when STAGE<2; the previous
-- RTS might not have this symbol
foreign import ccall unsafe "getOrSetLibHSghcFastStringTable"
getOrSetLibHSghcFastStringTable :: Ptr a -> IO (Ptr a)
#endif
{-
We include the FastString table in the `sharedCAF` mechanism because we'd like
FastStrings created by a Core plugin to have the same uniques as corresponding
strings created by the host compiler itself. For example, this allows plugins
to lookup known names (eg `mkTcOcc "MySpecialType"`) in the GlobalRdrEnv or
even re-invoke the parser.
In particular, the following little sanity test was failing in a plugin
prototyping safe newtype-coercions: GHC.NT.Type.NT was imported, but could not
be looked up /by the plugin/.
let rdrName = mkModuleName "GHC.NT.Type" `mkRdrQual` mkTcOcc "NT"
putMsgS $ showSDoc dflags $ ppr $ lookupGRE_RdrName rdrName $ mg_rdr_env guts
`mkTcOcc` involves the lookup (or creation) of a FastString. Since the
plugin's FastString.string_table is empty, constructing the RdrName also
allocates new uniques for the FastStrings "GHC.NT.Type" and "NT". These
uniques are almost certainly unequal to the ones that the host compiler
originally assigned to those FastStrings. Thus the lookup fails since the
domain of the GlobalRdrEnv is affected by the RdrName's OccName's FastString's
unique.
The old `reinitializeGlobals` mechanism is enough to provide the plugin with
read-access to the table, but it insufficient in the general case where the
plugin may allocate FastStrings. This mutates the supply for the FastStrings'
unique, and that needs to be propagated back to the compiler's instance of the
global variable. Such propagation is beyond the `reinitializeGlobals`
mechanism.
Maintaining synchronization of the two instances of this global is rather
difficult because of the uses of `unsafePerformIO` in this module. Not
synchronizing them risks breaking the rather major invariant that two
FastStrings with the same unique have the same string. Thus we use the
lower-level `sharedCAF` mechanism that relies on Globals.c.
-}
lookupTbl :: FastStringTable -> Int -> IO (IORef [FastString])
lookupTbl (FastStringTable _ arr#) (I# i#) =
IO $ \ s# -> readArray# arr# i# s#
updTbl :: FastStringTable -> Int -> IORef [FastString] -> IO ()
updTbl (FastStringTable _uid arr#) (I# i#) ls = do
(IO $ \ s# -> case writeArray# arr# i# ls s# of { s2# -> (# s2#, () #) })
mkFastString# :: Addr# -> FastString
mkFastString# a# = mkFastStringBytes ptr (ptrStrLength ptr)
where ptr = Ptr a#
{- Note [Updating the FastString table]
The procedure goes like this:
1. Read the relevant bucket and perform a look up of the string.
2. If it exists, return it.
3. Otherwise grab a unique ID, create a new FastString and atomically attempt
to update the relevant bucket with this FastString:
* Double check that the string is not in the bucket. Another thread may have
inserted it while we were creating our string.
* Return the existing FastString if it exists. The one we preemptively
created will get GCed.
* Otherwise, insert and return the string we created.
-}
{- Note [Double-checking the bucket]
It is not necessary to check the entire bucket the second time. We only have to
check the strings that are new to the bucket since the last time we read it.
-}
mkFastStringWith :: (Int -> IO FastString) -> Ptr Word8 -> Int -> IO FastString
mkFastStringWith mk_fs !ptr !len = do
let hash = hashStr ptr len
bucket <- lookupTbl string_table hash
ls1 <- readIORef bucket
res <- bucket_match ls1 len ptr
case res of
Just v -> return v
Nothing -> do
n <- get_uid
new_fs <- mk_fs n
atomicModifyIORef' bucket $ \ls2 ->
-- Note [Double-checking the bucket]
let delta_ls = case ls1 of
[] -> ls2
l:_ -> case l `elemIndex` ls2 of
Nothing -> panic "mkFastStringWith"
Just idx -> take idx ls2
-- NB: Might as well use inlinePerformIO, since the call to
-- bucket_match doesn't perform any IO that could be floated
-- out of this closure or erroneously duplicated.
in case inlinePerformIO (bucket_match delta_ls len ptr) of
Nothing -> (new_fs:ls2, new_fs)
Just fs -> (ls2,fs)
where
!(FastStringTable uid _arr) = string_table
get_uid = atomicModifyIORef' uid $ \n -> (n+1,n)
mkFastStringBytes :: Ptr Word8 -> Int -> FastString
mkFastStringBytes !ptr !len =
-- NB: Might as well use unsafeDupablePerformIO, since mkFastStringWith is
-- idempotent.
unsafeDupablePerformIO $
mkFastStringWith (copyNewFastString ptr len) ptr len
-- | Create a 'FastString' from an existing 'ForeignPtr'; the difference
-- between this and 'mkFastStringBytes' is that we don't have to copy
-- the bytes if the string is new to the table.
mkFastStringForeignPtr :: Ptr Word8 -> ForeignPtr Word8 -> Int -> IO FastString
mkFastStringForeignPtr ptr !fp len
= mkFastStringWith (mkNewFastString fp ptr len) ptr len
-- | Create a 'FastString' from an existing 'ForeignPtr'; the difference
-- between this and 'mkFastStringBytes' is that we don't have to copy
-- the bytes if the string is new to the table.
mkFastStringByteString :: ByteString -> FastString
mkFastStringByteString bs =
inlinePerformIO $
BS.unsafeUseAsCStringLen bs $ \(ptr, len) -> do
let ptr' = castPtr ptr
mkFastStringWith (mkNewFastStringByteString bs ptr' len) ptr' len
-- | Creates a UTF-8 encoded 'FastString' from a 'String'
mkFastString :: String -> FastString
mkFastString str =
inlinePerformIO $ do
let l = utf8EncodedLength str
buf <- mallocForeignPtrBytes l
withForeignPtr buf $ \ptr -> do
utf8EncodeString ptr str
mkFastStringForeignPtr ptr buf l
-- | Creates a 'FastString' from a UTF-8 encoded @[Word8]@
mkFastStringByteList :: [Word8] -> FastString
mkFastStringByteList str =
inlinePerformIO $ do
let l = Prelude.length str
buf <- mallocForeignPtrBytes l
withForeignPtr buf $ \ptr -> do
pokeArray (castPtr ptr) str
mkFastStringForeignPtr ptr buf l
-- | Creates a Z-encoded 'FastString' from a 'String'
mkZFastString :: String -> FastZString
mkZFastString = mkFastZStringString
bucket_match :: [FastString] -> Int -> Ptr Word8 -> IO (Maybe FastString)
bucket_match [] _ _ = return Nothing
bucket_match (v@(FastString _ _ bs _):ls) len ptr
| len == BS.length bs = do
b <- BS.unsafeUseAsCString bs $ \buf ->
cmpStringPrefix ptr (castPtr buf) len
if b then return (Just v)
else bucket_match ls len ptr
| otherwise =
bucket_match ls len ptr
mkNewFastString :: ForeignPtr Word8 -> Ptr Word8 -> Int -> Int
-> IO FastString
mkNewFastString fp ptr len uid = do
ref <- newIORef Nothing
n_chars <- countUTF8Chars ptr len
return (FastString uid n_chars (BS.fromForeignPtr fp 0 len) ref)
mkNewFastStringByteString :: ByteString -> Ptr Word8 -> Int -> Int
-> IO FastString
mkNewFastStringByteString bs ptr len uid = do
ref <- newIORef Nothing
n_chars <- countUTF8Chars ptr len
return (FastString uid n_chars bs ref)
copyNewFastString :: Ptr Word8 -> Int -> Int -> IO FastString
copyNewFastString ptr len uid = do
fp <- copyBytesToForeignPtr ptr len
ref <- newIORef Nothing
n_chars <- countUTF8Chars ptr len
return (FastString uid n_chars (BS.fromForeignPtr fp 0 len) ref)
copyBytesToForeignPtr :: Ptr Word8 -> Int -> IO (ForeignPtr Word8)
copyBytesToForeignPtr ptr len = do
fp <- mallocForeignPtrBytes len
withForeignPtr fp $ \ptr' -> copyBytes ptr' ptr len
return fp
cmpStringPrefix :: Ptr Word8 -> Ptr Word8 -> Int -> IO Bool
cmpStringPrefix ptr1 ptr2 len =
do r <- memcmp ptr1 ptr2 len
return (r == 0)
hashStr :: Ptr Word8 -> Int -> Int
-- use the Addr to produce a hash value between 0 & m (inclusive)
hashStr (Ptr a#) (I# len#) = loop 0# 0#
where
loop h n | isTrue# (n ==# len#) = I# h
| otherwise = loop h2 (n +# 1#)
where !c = ord# (indexCharOffAddr# a# n)
!h2 = (c +# (h *# 128#)) `remInt#`
hASH_TBL_SIZE#
-- -----------------------------------------------------------------------------
-- Operations
-- | Returns the length of the 'FastString' in characters
lengthFS :: FastString -> Int
lengthFS f = n_chars f
-- | Returns @True@ if this 'FastString' is not Z-encoded but already has
-- a Z-encoding cached (used in producing stats).
hasZEncoding :: FastString -> Bool
hasZEncoding (FastString _ _ _ ref) =
inlinePerformIO $ do
m <- readIORef ref
return (isJust m)
-- | Returns @True@ if the 'FastString' is empty
nullFS :: FastString -> Bool
nullFS f = BS.null (fs_bs f)
-- | Unpacks and decodes the FastString
unpackFS :: FastString -> String
unpackFS (FastString _ _ bs _) =
inlinePerformIO $ BS.unsafeUseAsCStringLen bs $ \(ptr, len) ->
utf8DecodeString (castPtr ptr) len
-- | Gives the UTF-8 encoded bytes corresponding to a 'FastString'
bytesFS :: FastString -> [Word8]
bytesFS fs = BS.unpack $ fastStringToByteString fs
-- | Returns a Z-encoded version of a 'FastString'. This might be the
-- original, if it was already Z-encoded. The first time this
-- function is applied to a particular 'FastString', the results are
-- memoized.
--
zEncodeFS :: FastString -> FastZString
zEncodeFS fs@(FastString _ _ _ ref) =
inlinePerformIO $ do
m <- readIORef ref
case m of
Just zfs -> return zfs
Nothing -> do
atomicModifyIORef' ref $ \m' -> case m' of
Nothing -> let zfs = mkZFastString (zEncodeString (unpackFS fs))
in (Just zfs, zfs)
Just zfs -> (m', zfs)
appendFS :: FastString -> FastString -> FastString
appendFS fs1 fs2 = mkFastStringByteString
$ BS.append (fastStringToByteString fs1)
(fastStringToByteString fs2)
concatFS :: [FastString] -> FastString
concatFS ls = mkFastString (Prelude.concat (map unpackFS ls)) -- ToDo: do better
headFS :: FastString -> Char
headFS (FastString _ 0 _ _) = panic "headFS: Empty FastString"
headFS (FastString _ _ bs _) =
inlinePerformIO $ BS.unsafeUseAsCString bs $ \ptr ->
return (fst (utf8DecodeChar (castPtr ptr)))
tailFS :: FastString -> FastString
tailFS (FastString _ 0 _ _) = panic "tailFS: Empty FastString"
tailFS (FastString _ _ bs _) =
inlinePerformIO $ BS.unsafeUseAsCString bs $ \ptr ->
do let (_, n) = utf8DecodeChar (castPtr ptr)
return $! mkFastStringByteString (BS.drop n bs)
consFS :: Char -> FastString -> FastString
consFS c fs = mkFastString (c : unpackFS fs)
uniqueOfFS :: FastString -> Int
uniqueOfFS (FastString u _ _ _) = u
nilFS :: FastString
nilFS = mkFastString ""
-- -----------------------------------------------------------------------------
-- Stats
getFastStringTable :: IO [[FastString]]
getFastStringTable = do
buckets <- forM [0.. hASH_TBL_SIZE-1] $ \idx -> do
bucket <- lookupTbl string_table idx
readIORef bucket
return buckets
-- -----------------------------------------------------------------------------
-- Outputting 'FastString's
-- |Outputs a 'FastString' with /no decoding at all/, that is, you
-- get the actual bytes in the 'FastString' written to the 'Handle'.
hPutFS :: Handle -> FastString -> IO ()
hPutFS handle fs = BS.hPut handle $ fastStringToByteString fs
-- ToDo: we'll probably want an hPutFSLocal, or something, to output
-- in the current locale's encoding (for error messages and suchlike).
-- -----------------------------------------------------------------------------
-- LitStrings, here for convenience only.
type LitString = Ptr Word8
--Why do we recalculate length every time it's requested?
--If it's commonly needed, we should perhaps have
--data LitString = LitString {-#UNPACK#-}!Addr# {-#UNPACK#-}!Int#
mkLitString# :: Addr# -> LitString
mkLitString# a# = Ptr a#
{-# INLINE mkLitString #-}
mkLitString :: String -> LitString
mkLitString s =
unsafePerformIO (do
p <- mallocBytes (length s + 1)
let
loop :: Int -> String -> IO ()
loop !n [] = pokeByteOff p n (0 :: Word8)
loop n (c:cs) = do
pokeByteOff p n (fromIntegral (ord c) :: Word8)
loop (1+n) cs
loop 0 s
return p
)
unpackLitString :: LitString -> String
unpackLitString (Ptr p) = unpackCString# p
lengthLS :: LitString -> Int
lengthLS = ptrStrLength
-- -----------------------------------------------------------------------------
-- under the carpet
foreign import ccall unsafe "ghc_strlen"
ptrStrLength :: Ptr Word8 -> Int
{-# NOINLINE sLit #-}
sLit :: String -> LitString
sLit x = mkLitString x
{-# NOINLINE fsLit #-}
fsLit :: String -> FastString
fsLit x = mkFastString x
{-# RULES "slit"
forall x . sLit (unpackCString# x) = mkLitString# x #-}
{-# RULES "fslit"
forall x . fsLit (unpackCString# x) = mkFastString# x #-}
|
tjakway/ghcjvm
|
compiler/utils/FastString.hs
|
bsd-3-clause
| 20,477 | 0 | 26 | 4,726 | 4,085 | 2,107 | 1,978 | 326 | 5 |
module Foo where
{-@ LIQUID "--no-termination" @-}
{-@ LIQUID "--native" @-}
{-@ foo :: {v:a | false} @-}
foo = foo
nat :: Int
{-@ nat :: Nat @-}
nat = 42
|
ssaavedra/liquidhaskell
|
tests/todo/false.hs
|
bsd-3-clause
| 160 | 0 | 4 | 37 | 23 | 16 | 7 | 4 | 1 |
{-# LANGUAGE
MagicHash,
FlexibleInstances,
MultiParamTypeClasses,
TypeFamilies,
PolyKinds,
DataKinds,
FunctionalDependencies,
TypeFamilyDependencies #-}
module T17541 where
import GHC.Prim
import GHC.Exts
type family Rep rep where
Rep Int = IntRep
type family Unboxed rep = (urep :: TYPE (Rep rep)) | urep -> rep where
Unboxed Int = Int#
|
sdiehl/ghc
|
testsuite/tests/dependent/should_fail/T17541.hs
|
bsd-3-clause
| 450 | 0 | 9 | 158 | 68 | 42 | 26 | 16 | 0 |
module E4 where
--Any type/data constructor name declared in this module can be renamed.
--Any type variable can be renamed.
--Rename type Constructor 'BTree' to 'MyBTree'
data BTree a = Empty | T a (BTree a) (BTree a)
deriving Show
buildtree :: (Monad m, Ord a) => [a] -> m (BTree a)
buildtree [] = return Empty
buildtree (x:xs) = do
res1 <- buildtree xs
res <- insert x res1
return res
insert :: (Monad m, Ord a) => a -> BTree a -> m (BTree a)
insert val v2 = do
case v2 of
T val Empty Empty
| val == val -> return Empty
| otherwise -> return (T val Empty (T val Empty Empty))
T val (T val2 Empty Empty) Empty -> return Empty
_ -> return v2
main :: IO ()
main = do
(a,T val Empty Empty) <- buildtree [3,1,2]
putStrLn $ show (T val Empty Empty)
|
SAdams601/HaRe
|
old/testing/asPatterns/E4.hs
|
bsd-3-clause
| 1,008 | 0 | 15 | 414 | 348 | 172 | 176 | 21 | 3 |
{-# LANGUAGE TypeInType, GADTs #-}
module T11811 where
import Data.Kind
data Test (a :: x) (b :: x) :: x -> *
where K :: Test Int Bool Double
|
olsner/ghc
|
testsuite/tests/typecheck/should_compile/T11811.hs
|
bsd-3-clause
| 147 | 0 | 6 | 34 | 47 | 30 | 17 | -1 | -1 |
-- Test for Trac #2188
module TH_scope where
f g = [d| f :: Int
f = g
g :: Int
g = 4 |]
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/th/TH_scope.hs
|
bsd-3-clause
| 120 | 0 | 5 | 57 | 17 | 12 | 5 | -1 | -1 |
-- read.hs
-- read a file
import System.IO
main = do
withFile "song.txt" ReadMode (\handle -> do
contents <- hGetContents handle
putStr contents)
|
doylew/practice
|
haskell/file.hs
|
mit
| 158 | 1 | 13 | 35 | 50 | 23 | 27 | 5 | 1 |
-- |
-- Module : HGE2D.Time
-- Copyright : (c) 2016 Martin Buck
-- License : see LICENSE
--
-- Containing functions to get the current time or transform times
module HGE2D.Time where
import HGE2D.Types
import Data.Time.Clock
--------------------------------------------------------------------------------
-- | Get the current time in seconds
getSeconds :: IO Double
getSeconds = getCurrentTime >>= return . fromRational . toRational . utctDayTime
--------------------------------------------------------------------------------
-- | Transform seconds to milliseconds
toMilliSeconds :: Double -> Millisecond
toMilliSeconds secs = floor $ 1000 * secs
|
I3ck/HGE2D
|
src/HGE2D/Time.hs
|
mit
| 671 | 0 | 8 | 102 | 81 | 49 | 32 | 7 | 1 |
-- Algorithms/Strings/Game of Thrones - I
module HackerRank.Algorithms.GameOfThrones1 where
import Data.Hashable (Hashable)
import qualified Data.HashMap.Strict as M
data Answer = YES | NO deriving (Show)
mkAnswer :: Bool -> Answer
mkAnswer True = YES
mkAnswer False = NO
freqMap :: (Hashable a, Ord a) => [a] -> M.HashMap a Int
freqMap xs = freqMap_ xs M.empty
freqMap_ :: (Hashable a, Ord a) => [a] -> M.HashMap a Int -> M.HashMap a Int
freqMap_ [] m = m
freqMap_ (x:xs) m = freqMap_ xs $ M.insertWith (+) x 1 m
isSymmetric :: (Hashable a, Ord a) => [a] -> Bool
isSymmetric xs = let eles = M.elems $ freqMap xs
odds = filter odd eles
in length odds <= 1
main :: IO ()
main = do
s <- getLine
let a = mkAnswer $ isSymmetric s
print a
|
4e6/sandbox
|
haskell/HackerRank/Algorithms/GameOfThrones1.hs
|
mit
| 791 | 0 | 11 | 195 | 328 | 171 | 157 | 21 | 1 |
{-# LANGUAGE RankNTypes #-}
-- | @SkipList@s are comprised of a list and an index on top of it
-- which makes deep indexing into the list more efficient (O(log n)).
-- They achieve this by essentially memoizing the @tail@ function to
-- create a balanced tree.
--
-- NOTE: @SkipList@s are /amortized/ efficient, see the benchmarks for
-- performance results.
module Data.SkipList
( SkipList
, toSkipList
, lookup )
where
import Prelude hiding (lookup)
-- | A SkipIndex stores "pointers" into the tail of a list for efficient
-- deep indexing. If you have
-- SkipIndex ls i
-- and the quantization is `q` then the elements of `q` are "pointers"
-- into every `q`th tail of the list. For example, if `q` = 2 and
-- `ls = [1,2,3,4,5,6,7]`, then the frist level of `i` contains:
-- [1,2,3,4,5,6,7], [3,4,5,6,7], [5,6,7], [7]
-- the next level of `i` conceptually contains:
-- [1,2,3,4,5,6,7], [5,6,7]
-- Note however, that these are not lists, but rather references to
-- @SkipIndex@s from `i`
data SkipIndex a =
SkipIndex ![a] (SkipIndex (SkipIndex a))
-- | @SkipList@s are lists that support amortized efficient indexing.
data SkipList a = SkipList !Int (SkipIndex a)
instance Functor SkipList where
fmap f (SkipList q (SkipIndex raw _)) = toSkipList q $ f <$> raw
instance Foldable SkipList where
foldMap f (SkipList _ (SkipIndex ls _)) = foldMap f ls
-- | Convert a list to a @SkipList@.
toSkipList :: Int -- ^ The step size in the index.
-> [a] -- ^ The list to convert.
-> SkipList a
toSkipList quant = SkipList quant . toSkipIndex quant
-- | Build the infinite tree of skips.
toSkipIndex :: Int -> [a] -> SkipIndex a
toSkipIndex quant
| quant > 1 = \ ls ->
let self = SkipIndex ls $ toSkipIndex quant (self : rest)
rest = toSkipIndex quant <$> fastTails ls
in self
| otherwise = error "Can not make SkipList with quantization <= 1"
where
fastTails ls = dropped : fastTails dropped
where dropped = drop quant ls
-- | Lookup in a @SkipList@.
lookup :: SkipList a -> Int -> a
lookup (SkipList q (SkipIndex ls index)) i
| i >= q = get q q (\ (SkipIndex a _) -> (!!) a) index i
| otherwise = ls !! i
-- | Get an element from a @SkipIndex@.
get :: Int -- ^ The step increment in the index
-> Int -- ^ The current step size
-> (b -> Int -> a) -- ^ Continuation to call with the result
-> SkipIndex b -- ^ The index to look in
-> Int -- ^ The position to look for
-> a
get q stepSize kont (SkipIndex here next) n
| n >= q * stepSize =
get q (q*stepSize) (get q stepSize kont) next n
| otherwise = kont (here !! idx) rest
where idx = n `div` stepSize
rest = n `mod` stepSize
|
gmalecha/skip-list
|
src/Data/SkipList.hs
|
mit
| 2,746 | 0 | 14 | 666 | 600 | 318 | 282 | 46 | 1 |
-- A permutation is an ordered arrangement of objects. For example,
-- 3124 is one possible permutation of the digits 1, 2, 3 and 4. If
-- all of the permutations are listed numerically or alphabetically,
-- we call it lexicographic order. The lexicographic permutations of
-- 0, 1 and 2 are:
-- 012 021 102 120 201 210
-- What is the millionth lexicographic permutation of the digits 0, 1,
-- 2, 3, 4, 5, 6, 7, 8 and 9?
module Euler.Problem024
( solution
, nthLexicographicPermutation
, permutationCount
) where
import Data.List (delete, sort)
import Euler.Factorial (factorial)
solution :: Int -> Int
solution n = read $ nthLexicographicPermutation n "0123456789"
nthLexicographicPermutation :: Ord a => Int -> [a] -> [a]
nthLexicographicPermutation i as
| i < 1 = error "index out of range"
| (i - 1) > permutationCount as = error "index out of range"
| otherwise = lexPerm (i - 1) (sort as)
-- The private version of nthLexicographicPermutation. Assumes that
-- the list is sorted, that the index is 0-based, and that there exist
-- sufficient permutations of the list to satisfy the index.
lexPerm :: Ord a => Int -> [a] -> [a]
lexPerm 0 as = as
lexPerm _ [] = error "permutations exhausted"
lexPerm i as = a : lexPerm (i - k * step) (delete a as)
where a = as !! k
k = i `div` step
step = permutationCount $ tail as
permutationCount :: [a] -> Int
permutationCount = factorial . length
|
whittle/euler
|
src/Euler/Problem024.hs
|
mit
| 1,462 | 0 | 10 | 323 | 323 | 174 | 149 | 22 | 1 |
module Data.Streaming.Process.Internal
( StreamingProcessHandle (..)
, InputSource (..)
, OutputSink (..)
) where
import Control.Concurrent.STM (TMVar)
import System.Exit (ExitCode)
import System.IO (Handle)
import System.Process (ProcessHandle, StdStream (CreatePipe))
-- | Class for all things which can be used to provide standard input.
--
-- Since 0.1.4
class InputSource a where
isStdStream :: (Maybe Handle -> IO a, Maybe StdStream)
instance InputSource Handle where
isStdStream = (\(Just h) -> return h, Just CreatePipe)
-- | Class for all things which can be used to consume standard output or
-- error.
--
-- Since 0.1.4
class OutputSink a where
osStdStream :: (Maybe Handle -> IO a, Maybe StdStream)
instance OutputSink Handle where
osStdStream = (\(Just h) -> return h, Just CreatePipe)
-- | Wraps up the standard @ProcessHandle@ to avoid the @waitForProcess@
-- deadlock. See the linked documentation from the module header for more
-- information.
--
-- Since 0.1.4
data StreamingProcessHandle = StreamingProcessHandle
ProcessHandle
(TMVar ExitCode)
(IO ()) -- cleanup resources
|
fpco/streaming-commons
|
Data/Streaming/Process/Internal.hs
|
mit
| 1,213 | 0 | 9 | 279 | 257 | 149 | 108 | 20 | 0 |
module PrintProof where
import Data.IORef
import Control.Monad (liftM)
import NarrowingSearch
import Syntax
prMeta :: MMetavar a -> (a -> IO String) -> IO String
prMeta m prv = do
b <- readIORef $ mbind m
case b of
Nothing -> return $ "?" ++ show (mid m)
Just v -> prv v
prProof :: Int -> MetaProof -> IO String
prProof ctx p =
prMeta p $ \p -> case p of
Intro p -> prIntro ctx p
Elim hyp p -> do
hyp <- prHyp ctx hyp
p <- prProofElim ctx p
return $ "(elim " ++ hyp ++ " " ++ p ++ ")"
RAA p -> do
p <- prProof (ctx + 1) p
return $ "(RAA (\\#" ++ show ctx ++ "." ++ p ++ "))"
prIntro :: Int -> MetaIntro -> IO String
prIntro ctx p =
prMeta p $ \p -> case p of
OrIl p -> do
p <- prProof ctx p
return $ "(Or-Il " ++ p ++ ")"
OrIr p -> do
p <- prProof ctx p
return $ "(Or-Ir " ++ p ++ ")"
AndI p1 p2 -> do
p1 <- prProof ctx p1
p2 <- prProof ctx p2
return $ "(And-I " ++ p1 ++ " " ++ p2 ++ ")"
ExistsI f p -> do
f <- prForm ctx $ Meta f
p <- prProof ctx p
return $ "(Exists-I " ++ f ++ " " ++ p ++ ")"
ImpliesI p -> do
p <- prProof (ctx + 1) p
return $ "(Implies-I (\\#" ++ show ctx ++ "." ++ p ++ "))"
NotI p -> do
p <- prProof (ctx + 1) p
return $ "(Not-I (\\#" ++ show ctx ++ "." ++ p ++ "))"
ForallI p -> do
p <- prProof (ctx + 1) p
return $ "(Forall-I (\\#" ++ show ctx ++ "." ++ p ++ "))"
TopI ->
return "Top-I"
EqI p -> do
p <- prProofEq ctx p
return $ "(=-I " ++ p ++ ")"
prHyp :: Int -> MetaHyp -> IO String
prHyp ctx hyp =
prMeta hyp $ \(Hyp elr _) ->
case elr of
HVar v -> return $ "#" ++ show (ctx - v - 1)
HGlob gh -> return $ "<<" ++ ghName gh ++ ">>"
AC typ qf p -> do
typ <- prType $ Meta typ
qf <- prForm ctx $ Meta qf
p <- prProof ctx p
return $ "(AC " ++ typ ++ " " ++ qf ++ " " ++ p ++ ")"
prProofElim :: Int -> MetaProofElim -> IO String
prProofElim ctx p =
prMeta p $ \p -> case p of
Use p -> do
p <- prProofEqSimp ctx p
return $ "(use " ++ p ++ ")"
ElimStep p -> prElimStep ctx p
prProofEqElim :: Int -> MetaProofEqElim -> IO String
prProofEqElim ctx p =
prMeta p $ \p -> case p of
UseEq -> return "use-eq"
UseEqSym -> return "use-eq-sym"
EqElimStep p -> prEqElimStep ctx p
prEqElimStep :: Int -> MetaEqElimStep -> IO String
prEqElimStep ctx p =
prMeta p $ \p -> case p of
NTEqElimStep p -> prNTElimStep (prProofEqElim ctx) ctx p
prElimStep :: Int -> MetaElimStep -> IO String
prElimStep ctx p =
prMeta p $ \p -> case p of
BotE -> return "Bot-E"
NotE p -> do
p <- prProof ctx p
return $ "(Not-E " ++ p ++ ")"
OrE p1 p2 -> do
p1 <- prProof (ctx + 1) p1
p2 <- prProof (ctx + 1) p2
return $ "(Or-E " ++ p1 ++ " " ++ p2 ++ ")"
NTElimStep p -> prNTElimStep (prProofElim ctx) ctx p
prNTElimStep :: (a -> IO String) -> Int -> NTElimStep a -> IO String
prNTElimStep pr ctx p =
case p of
AndEl p -> do
p <- pr p
return $ "(And-El " ++ p ++ ")"
AndEr p -> do
p <- pr p
return $ "(And-Er " ++ p ++ ")"
ExistsE p -> do
p <- pr p
return $ "(Exists-E " ++ p ++ ")"
ImpliesE p1 p2 -> do
p1 <- prProof ctx p1
p2 <- pr p2
return $ "(Implies-E " ++ p1 ++ " " ++ p2 ++ ")"
ForallE f p -> do
f <- prForm ctx $ Meta f
p <- pr p
return $ "(Forall-E " ++ f ++ " " ++ p ++ ")"
InvBoolExtl p1 p2 -> do
p1 <- prProof ctx p1
p2 <- pr p2
return $ "(inv-bool-extl " ++ p1 ++ " " ++ p2 ++ ")"
InvBoolExtr p1 p2 -> do
p1 <- prProof ctx p1
p2 <- pr p2
return $ "(inv-bool-extr " ++ p1 ++ " " ++ p2 ++ ")"
InvFunExt f p -> do
f <- prForm ctx $ Meta f
p <- pr p
return $ "(inv-fun-ext " ++ f ++ " " ++ p ++ ")"
prProofEq :: Int -> MetaProofEq -> IO String
prProofEq ctx p =
prMeta p $ \p -> case p of
Simp p -> prProofEqSimp ctx p
Step hyp elimp simpp eqp -> do
hyp <- prHyp ctx hyp
elimp <- prProofEqElim ctx elimp
simpp <- prProofEqSimp ctx simpp
eqp <- prProofEq ctx eqp
return $ "(step " ++ hyp ++ " " ++ elimp ++ " " ++ simpp ++ " " ++ eqp ++ ")"
BoolExt p1 p2 -> do
p1 <- prProof (ctx + 1) p1
p2 <- prProof (ctx + 1) p2
return $ "(bool-ext " ++ p1 ++ " " ++ p2 ++ ")"
FunExt p -> do
p <- prProofEq (ctx + 1) p
return $ "(fun-ext " ++ p ++ ")"
prProofEqSimp :: Int -> MetaProofEqSimp -> IO String
prProofEqSimp ctx p = do
os <- only_simp p
case os of
True ->
return $ "simp-all"
False ->
prMeta p $ \p -> case p of
SimpLam em p -> do
p <- prProofEq (ctx + 1) p
return $ "(simp-lam " ++ pem em ++ p ++ ")"
where
pem EMNone = ""
pem EMLeft = "{- eta-conv lhs -} "
pem EMRight = "{- eta-conv rhs -} "
SimpCons c ps -> do
ps <- mapM (prProofEq ctx) ps
return $ "(simp-" ++ show c ++ concat (map (" " ++) ps) ++ ")"
SimpApp ps -> do
ps <- prProofEqs ctx ps
return $ "(simp-app" ++ ps ++ ")"
SimpChoice p ps -> do
p <- prProofEq ctx p
ps <- prProofEqs ctx ps
return $ "(simp-choice " ++ p ++ ps ++ ")"
prProofEqs :: Int -> MetaProofEqs -> IO String
prProofEqs ctx p =
prMeta p $ \p -> case p of
PrEqNil -> return ""
PrEqCons p ps -> do
p <- prProofEq ctx p
ps <- prProofEqs ctx ps
return $ " " ++ p ++ ps
only_simp :: MetaProofEqSimp -> IO Bool
only_simp p =
expandbind (Meta p) >>= \p -> case p of
Meta{} -> return False
NotM p -> case p of
SimpLam _ p -> h p
SimpCons _ ps -> do
bs <- mapM h ps
return $ and bs
SimpApp ps -> g ps
SimpChoice p ps -> do
b1 <- h p
b2 <- g ps
return $ b1 && b2
where
h p =
expandbind (Meta p) >>= \p -> case p of
Meta{} -> return False
NotM p -> case p of
Simp p -> only_simp p
_ -> return False
g ps =
expandbind (Meta ps) >>= \ps -> case ps of
Meta{} -> return False
NotM p -> case p of
PrEqNil -> return True
PrEqCons p ps -> do
b1 <- h p
b2 <- g ps
return $ b1 && b2
prForm :: Int -> MFormula -> IO String
prForm ctx f =
expandbind f >>= \f -> case f of
Meta m -> return $ "?" ++ show (mid m)
NotM (Lam muid t bdy) -> do
t <- prType t
bdy <- prForm (ctx + 1) bdy
return $ "(\\#" ++ pmuid muid ++ show ctx ++ ":" ++ t ++ "." ++ bdy ++ ")"
NotM (C muid c args) -> do
args <- mapM (\arg -> case arg of
F f -> prForm ctx f >>= \f -> return $ f
T t -> prType t >>= \t -> return $ t
) args
return $ "(" ++ show c ++ pmuid muid ++ concat (map (" " ++) args) ++ ")"
NotM (App muid elr args) -> do
args <- prArgs ctx args
let pelr = case elr of
Var i -> "#" ++ show (ctx - i - 1)
Glob gv -> "<<" ++ gvName gv ++ ">>"
return $ "(" ++ pelr ++ pmuid muid ++ args ++ ")"
NotM (Choice muid typ qf args) -> do
typ <- prType typ
qf <- prForm ctx qf
args <- prArgs ctx args
return $ "(choice" ++ pmuid muid ++ " " ++ typ ++ " " ++ qf ++ args ++ ")"
where
pmuid _ = ""
prArgs :: Int -> MArgs -> IO String
prArgs ctx xs =
expandbind xs >>= \xs -> case xs of
Meta m -> return $ "[?" ++ show (mid m) ++ "]"
NotM ArgNil -> return ""
NotM (ArgCons x xs) -> do
x <- prForm ctx x
xs <- prArgs ctx xs
return $ " " ++ x ++ xs
prType :: MType -> IO String
prType t =
expandbind t >>= \t -> case t of
Meta m -> return $ "?" ++ show (mid m)
NotM (Ind i) -> return $ "$i" ++ if i >= 0 then show i else ""
NotM Bool -> return "$o"
NotM (Map t1 t2) -> do
t1 <- prType t1
t2 <- prType t2
return $ "(" ++ t1 ++ ">" ++ t2 ++ ")"
prProblem :: Problem -> IO String
prProblem pr = do
globvars <- mapM prGlobVar $ prGlobVars pr
globhyps <- mapM prGlobHyp $ prGlobHyps pr
conjs <- mapM (\(cn, form) -> prForm 0 form >>= \form -> return (cn ++ " : " ++ form)) $ prConjectures pr
return $ "global variables\n" ++ unlines globvars ++
"\nglobal hypotheses\n" ++ unlines globhyps ++
"\nconjectures\n" ++ unlines conjs
prGlobVar :: GlobVar -> IO String
prGlobVar gv = do
typ <- prType $ gvType gv
return $ gvName gv ++ " : " ++ typ
prGlobHyp :: GlobHyp -> IO String
prGlobHyp gh = do
form <- prForm 0 $ ghForm gh
return $ ghName gh ++ " : " ++ form ++ " (" ++ show (ghGenCost gh) ++ ")"
-- ------------------------------------
prCFormula :: Int -> CFormula -> IO String
prCFormula ctx (Cl env form) =
expandbind form >>= \form -> case form of
Meta m -> do
env <- prEnv env
return $ env ++ "?" ++ show (mid m)
NotM (Lam muid t bdy) -> do
t <- prType t
bdy <- prCFormula (ctx + 1) (Cl (Skip : env) bdy)
return $ "(\\#" ++ pmuid muid ++ show ctx ++ ":" ++ t ++ "." ++ bdy ++ ")"
NotM (C muid c args) -> do
args <- mapM (\arg -> case arg of
F f -> prCFormula ctx (Cl env f) >>= \f -> return $ f
T t -> prType t >>= \t -> return $ t
) args
return $ "(" ++ show c ++ pmuid muid ++ concat (map (" " ++) args) ++ ")"
NotM (App muid elr args) -> do
elr <- case elr of
Var i -> case doclos env i of
Left i -> return $ "#" ++ show (ctx - i - 1)
Right form -> do
form <- prCFormula ctx form
return $ "{" ++ form ++ "}"
Glob gv -> return $ gvName gv
args <- prargs args
return $ "(" ++ elr ++ pmuid muid ++ args ++ ")"
NotM (Choice muid typ qf args) -> do
typ <- prType typ
qf <- prCFormula ctx (Cl env qf)
args <- prargs args
return $ "(choice" ++ pmuid muid ++ " " ++ typ ++ " " ++ qf ++ args ++ ")"
where
pmuid _ = ""
prargs args =
expandbind args >>= \args -> case args of
Meta m -> do
env <- prEnv env
return $ env ++ "?" ++ show (mid m)
NotM ArgNil -> return ""
NotM (ArgCons x xs) -> do
x <- prCFormula ctx (Cl env x)
xs <- prargs xs
return $ " " ++ x ++ xs
prCFormula ctx (CApp c1 c2) = do
c1 <- prCFormula ctx c1
c2 <- prCFormula ctx c2
return $ "(capp " ++ c1 ++ " " ++ c2 ++ ")"
prCFormula ctx (CNot c) = do
c <- prCFormula ctx c
return $ "(cnot " ++ c ++ ")"
prCFormula _ (CHN _) = return "<CHN>"
prEnv :: Env -> IO String
prEnv = g 0
where
g _ [] = return ""
g i (Skip : env) = g (i + 1) env
g i (Sub f : env) = do
env <- g (i + 1) env
f <- prCFormula 0 f
return $ "[@" ++ show i ++ "=" ++ f ++ "]" ++ env
g i (Lift n : env) = do
env <- g i env
return $ "[L" ++ show n ++ "]" ++ env
prCtx :: Context -> IO String
prCtx ctx = g (length ctx - 1) ctx
where
g _ [] = return ""
g i (VarExt t : ctx) = do
ctx <- g (i - 1) ctx
t <- prType t
return $ ctx ++ "[#" ++ show i ++ ":" ++ t ++ "]"
g i (HypExt f : ctx) = do
ctx <- g (i - 1) ctx
f <- prCFormula i f
return $ ctx ++ "[#" ++ show i ++ ":" ++ f ++ "]"
|
frelindb/agsyHOL
|
PrintProof.hs
|
mit
| 10,596 | 0 | 23 | 3,242 | 5,219 | 2,429 | 2,790 | 336 | 10 |
{-# LANGUAGE DeriveDataTypeable #-}
module Development.Duplo.Types.Builder where
import Control.Exception (Exception)
import Data.Typeable (Typeable)
data BuilderException = MissingGithubUserException
| MissingGithubRepoException
| MalformedManifestException String
| MissingManifestException String
| MissingTestDirectory
deriving (Typeable)
instance Exception BuilderException
instance Show BuilderException where
show MissingGithubUserException =
"There must be a GitHub user."
show MissingGithubRepoException =
"There must be a GitHub repo."
show (MalformedManifestException path) =
"The manifest file `" ++ path ++ "` is not a valid duplo JSON."
show (MissingManifestException path) =
"`" ++ path ++ "` is expected at the current location."
show MissingTestDirectory =
"There must be a `tests/` directory in order to run tests."
|
pixbi/duplo
|
src/Development/Duplo/Types/Builder.hs
|
mit
| 1,003 | 0 | 8 | 270 | 142 | 78 | 64 | 22 | 0 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Shifts.Types
(
Eng(..)
, Shift(..)
) where
import Control.Monad (liftM)
import Data.Aeson
import Data.Text
import Data.Time
import GHC.Generics
instance Ord Shift where
(Shift s1 _ _) `compare` (Shift s2 _ _) = s1 `compare` s2
data Shift = Shift
{ _startDay :: Day
, _endDay :: Day
, _engOwner :: Eng
}
deriving (Show, Eq, ToJSON, Generic)
data Eng = Eng { _initials :: Text }
deriving (Show, Eq, ToJSON, Generic)
parseDate :: String -> Day
parseDate = parseTimeOrError True defaultTimeLocale "%Y-%m-%d"
instance FromJSON Day where
parseJSON (Object v) = liftM parseDate (v .: "date")
parseJSON _ = fail "invalid"
instance ToJSON Day where
toJSON = toJSON . showGregorian
|
tippenein/shifts
|
src/Shifts/Types.hs
|
mit
| 824 | 0 | 8 | 169 | 265 | 149 | 116 | 28 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import CoinApi
import qualified CoinApi.Monadic as M
import Data.Time
import Control.Monad.State (liftIO)
key = "73034021-0EBC-493D-8A00-E0F138111F41"
asset_id_base = "BTC"
asset_id_quote = "USD"
symbol_id = "BITSTAMP_SPOT_BTC_USD"
period_id = "1HRS"
time_start = UTCTime (fromGregorian 2016 01 01) (fromIntegral 0)
time_end = UTCTime (fromGregorian 2016 01 03) (fromIntegral 0)
limit = 100 :: Int
-- using pure interface
pure :: IO ()
pure = do
putStrLn "list_all_exchanges:"
ex <- metadata_list_exchanges key
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "list_all_assets:"
ex <- metadata_list_assets key
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "list_all_symbols:"
ex <- metadata_list_symbols key
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "get_specific_rate:"
ex <- metadata_list_symbols key
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "get_specific_rate_t:"
ex <- exchange_rates_get_specific_rate_t key asset_id_base asset_id_quote time_start
case ex of
Right result -> print result
Left err -> putStrLn err
putStrLn ""
putStrLn $ "get_all_current_rates:"
ex <- exchange_rates_get_all_current_rates key asset_id_base
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "list_all_periods:"
ex <- ohlcv_list_all_periods key
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "quotes_latest_data:"
ex <- quotes_latest_data key
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "quotes_latest_data_s:"
ex <- quotes_latest_data_s key symbol_id
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "quotes_latest_data_l:"
ex <- quotes_latest_data_l key limit
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "quotes_latest_data_sl:"
ex <- quotes_latest_data_sl key symbol_id limit
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "quotes_historical_data:"
ex <- quotes_historical_data key symbol_id time_start
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "quotes_historical_data_e:"
ex <- quotes_historical_data_e key symbol_id time_start time_end
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "quotes_historical_data_l:"
ex <- quotes_historical_data_l key symbol_id time_start limit
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "quotes_historical_data_el:"
ex <- quotes_historical_data_el key symbol_id time_start time_end limit
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "orderbooks_current_data:"
ex <- orderbooks_current_data key
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "orderbooks_current_data_s:"
ex <- orderbooks_current_data_s key symbol_id
case ex of
Right result -> print result
Left err -> putStrLn err
putStrLn ""
putStrLn "orderbooks_latest_data:"
ex <- orderbooks_latest_data key symbol_id
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "orderbooks_latest_data_l:"
ex <- orderbooks_latest_data_l key symbol_id limit
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "orderbooks_historical_data:"
ex <- orderbooks_historical_data key symbol_id time_start
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "orderbooks_historical_data_e:"
ex <- orderbooks_historical_data_e key symbol_id time_start time_end
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "orderbooks_historical_data_l:"
ex <- orderbooks_historical_data_l key symbol_id time_start limit
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
putStrLn "orderbooks_historical_data_el:"
ex <- orderbooks_historical_data_el key symbol_id time_start time_end limit
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
-- using monadic interface
monadic :: IO ()
monadic = M.withApiKey key $ do
ex <- M.metadata_list_exchanges
liftIO $ do putStrLn "list_all_exchanges:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.metadata_list_assets
liftIO $ do putStrLn "list_all_assets:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.metadata_list_symbols
liftIO $ do putStrLn "list_all_symbols:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.metadata_list_symbols
liftIO $ do putStrLn "get_specific_rate:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.exchange_rates_get_specific_rate_t asset_id_base asset_id_quote time_start
liftIO $ do putStrLn "get_specific_rate_t:"
case ex of
Right result -> print result
Left err -> putStrLn err
putStrLn ""
ex <- M.exchange_rates_get_all_current_rates asset_id_base
liftIO $ do putStrLn $ "get_all_current_rates:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.ohlcv_list_all_periods
liftIO $ do putStrLn "list_all_periods:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.quotes_latest_data
liftIO $ do putStrLn "quotes_latest_data:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.quotes_latest_data_s symbol_id
liftIO $ do putStrLn "quotes_latest_data_s:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.quotes_latest_data_l limit
liftIO $ do putStrLn "quotes_latest_data_l:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.quotes_latest_data_sl symbol_id limit
liftIO $ do putStrLn "quotes_latest_data_sl:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.quotes_historical_data symbol_id time_start
liftIO $ do putStrLn "quotes_historical_data:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.quotes_historical_data_e symbol_id time_start time_end
liftIO $ do putStrLn "quotes_historical_data_e:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.quotes_historical_data_l symbol_id time_start limit
liftIO $ do putStrLn "quotes_historical_data_l:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.quotes_historical_data_el symbol_id time_start time_end limit
liftIO $ do putStrLn "quotes_historical_data_el:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.orderbooks_current_data
liftIO $ do putStrLn "orderbooks_current_data:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.orderbooks_current_data_s symbol_id
liftIO $ do putStrLn "orderbooks_current_data_s:"
case ex of
Right result -> print result
Left err -> putStrLn err
putStrLn ""
ex <- M.orderbooks_latest_data symbol_id
liftIO $ do putStrLn "orderbooks_latest_data:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.orderbooks_latest_data_l symbol_id limit
liftIO $ do putStrLn "orderbooks_latest_data_l:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.orderbooks_historical_data symbol_id time_start
liftIO $ do putStrLn "orderbooks_historical_data:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.orderbooks_historical_data_e symbol_id time_start time_end
liftIO $ do putStrLn "orderbooks_historical_data_e:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.orderbooks_historical_data_l symbol_id time_start limit
liftIO $ do putStrLn "orderbooks_historical_data_l:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
ex <- M.orderbooks_historical_data_el symbol_id time_start time_end limit
liftIO $ do putStrLn "orderbooks_historical_data_el:"
case ex of
Right result -> mapM_ print $ take 2 result
Left err -> putStrLn err
putStrLn ""
main = do putStrLn "Pure interface:"
Main.pure
putStrLn "Monadic interface:"
Main.monadic
|
coinapi/coinapi-sdk
|
data-api/haskell-rest/Main.hs
|
mit
| 11,093 | 0 | 15 | 3,451 | 3,301 | 1,378 | 1,923 | 298 | 24 |
{-# LANGUAGE CPP #-}
module Compat where
import Control.Concurrent (mkWeakThreadId, myThreadId)
import Control.Exception (AsyncException (UserInterrupt), throwTo)
import System.Mem.Weak (deRefWeak)
#if defined(mingw32_HOST_OS)
import qualified GHC.ConsoleHandler as WinSig
#else
import qualified System.Posix.Signals as Sig
#endif
installSignalHandlers :: IO ()
installSignalHandlers = do
main_thread <- myThreadId
wtid <- mkWeakThreadId main_thread
let interrupt = do
r <- deRefWeak wtid
case r of
Nothing -> return ()
Just t -> throwTo t UserInterrupt
#if defined(mingw32_HOST_OS)
let sig_handler WinSig.ControlC = interrupt
sig_handler WinSig.Break = interrupt
sig_handler _ = return ()
_ <- WinSig.installHandler (WinSig.Catch sig_handler)
#else
_ <- Sig.installHandler Sig.sigQUIT (Sig.Catch interrupt) Nothing
_ <- Sig.installHandler Sig.sigINT (Sig.Catch interrupt) Nothing
#endif
return ()
|
unisonweb/platform
|
parser-typechecker/unison/Compat.hs
|
mit
| 987 | 0 | 16 | 196 | 208 | 108 | 100 | 18 | 2 |
module Main where
import Haste
main = withElem "root" $ \root -> do
img <- newElem "img"
setAttr img "src" "cat.jpg"
setAttr img "id" "cat"
addChild img root
onEvent img OnMouseOver $ \_ ->
setClass img "foo" True
onEvent img OnMouseOut
$ setClass img "foo" False
|
laser/haste-experiment
|
demos/event-handling/event-handling.hs
|
mit
| 289 | 0 | 11 | 71 | 105 | 48 | 57 | 11 | 1 |
import qualified Data.List
import Kd2nTree
p1 :: Point3d
p1 = list2Point [3.0,-1.0,2.1]
p2 :: Point3d
p2 = list2Point [3.5,2.8,3.1]
p3 :: Point3d
p3 = list2Point [3.5,0.0,2.1]
p4 :: Point3d
p4 = list2Point [3.0,-1.7,3.1]
p5 :: Point3d
p5 = list2Point [3.0,5.1,0.0]
p6 :: Point3d
p6 = list2Point [1.5,8.0,1.5]
p7 :: Point3d
p7 = list2Point [3.3,2.8,2.5]
p8 :: Point3d
p8 = list2Point [4.0,5.1,3.8]
p9 :: Point3d
p9 = list2Point [3.1,3.8,4.8]
p10 :: Point3d
p10 = list2Point [1.8,1.1,-2.0]
p11 :: Point3d
p11 = list2Point [-100000, 0.0, 100000]
enunciat :: Kd2nTree Point3d
enunciat = buildIni [
([3.0, -1.0, 2.1], [1, 3]),
([3.5, 2.8, 3.1], [1, 2]),
([3.5, 0.0, 2.1], [3]),
([3.0, -1.7, 3.1], [1, 2, 3]),
([3.0, 5.1, 0.0], [2]),
([1.5, 8.0, 1.5], [1]),
([3.3, 2.8, 2.5], [3]),
([4.0, 5.1, 3.8], [2]),
([3.1, 3.8, 4.8], [1, 3]),
([1.8, 1.1, -2.0], [1, 2])]
pau :: Kd2nTree Point3d
pau = buildIni [
([0,0,0], [1]),
([-1,1,0], [1]),
([2,200,0],[1]),
([1,2,0], [1]),
([1,20,0], [1]),
([30,-20,0], [1])]
empty :: Kd2nTree Point3d
empty = buildIni []
equivalent1 :: Kd2nTree Point3d
equivalent1 = buildIni [
([2,3,-100.5], [2,3]),
([5,0,-10], [1]),
([-2,-2,-2], [3])
]
equivalent2 :: Kd2nTree Point3d
equivalent2 = buildIni [
([5,0,-10.0], [2,3]),
([-2,-2,-2], [1]),
([2,3,-100.5], [2])
]
antiequivalent :: Kd2nTree Point3d
antiequivalent = buildIni [
([5,0,-10.00001], [2,3]),
([-2,-2,-2], [1]),
([2,3,-100.5], [2])
]
punts :: [Point3d]
punts = [p1, p2, p3, p4, p5, p6, p11, pscale 2 p11, pscale (-2) (pscale (-1) p11), nearest pau p11, nearest enunciat p11, nearest equivalent1 p11]
arbres :: [Kd2nTree Point3d]
arbres = [pau, enunciat, antiequivalent, equivalent1, equivalent2, empty]
llistes :: [[Point3d]]
llistes = [allinInterval equivalent1 p6 p8, allinInterval equivalent1 p8 p6, allinInterval enunciat (list2Point [-500, -500, -500]) (list2Point [500, 500, 500])]
strings :: [String]
strings = [show $ dist p1 p2, show $ allinInterval enunciat (list2Point [-500, -500, -500]) (list2Point [500,500,500])]
proves :: [([Char], Bool)]
proves = [
("Igualtat punts", p1 == p1),
("Desigualtat punts", p1 /= p2),
("Dimensio punts", dim p1 == 3),
("Seleccio punts", sel 1 p1 == 3),
("Translacio punts", ptrans [1,1,1] p1 == list2Point [4,0,3.1]),
("Distancia punts", dist p1 p1 == 0 && dist2 p1 p1 == 0),
("Comprovacio empty", empty == Empty),
("Igualtat d'empty", empty == empty),
("Desigualtat empty/no empty", empty /= enunciat && enunciat /= empty),
("Igualtat no empty", enunciat == enunciat),
("Equivalencia certa directa", equivalent1 == equivalent2),
("Equivalencia certa insert", (insert equivalent1 p11 [1]) == (insert equivalent2 p11 [2,3])),
("Equivalencia certa elems", elems equivalent1 `eqList` elems equivalent2),
("Equivalencia certa translation", (translation [500,0,-1] equivalent1) == (translation [500,0,-1] equivalent2)),
("Equivalencia certa scale", (elems $ scale (-5.33) equivalent1) `eqList` (elems $ scale (-5.33) equivalent2)),
("Equivalencia certa scale 2", (scale (200) equivalent1) == (scale 200 equivalent2)),
("Equivalencia certa allInInterval", (allinInterval equivalent1 p6 p8) `eqList` (allinInterval equivalent2 p6 p8)),
("Equivalencia falsa directa", equivalent1 /= antiequivalent && equivalent2 /= antiequivalent),
("Equivalencia falsa insert", (insert equivalent1 p1 [2,3]) /= (insert equivalent2 p11 [2,3])),
("Equivalencia falsa elems", elems equivalent1 `difList` elems antiequivalent),
("Equivalencia falsa translation", (translation [500,0,1] equivalent1) /= (translation [500,0,-1] equivalent2)),
("Equivalencia falsa scale", (elems $ scale (-5.23) equivalent1) `difList` (elems $ scale (-5.33) equivalent2)),
("Equivalencia falsa scale 2", (scale (100) equivalent1) /= (scale 200 equivalent2)),
("Operacions sobre empty's 1", (insert Empty p1 [2,3]) == (insert Empty p1 [1,2])),
("Operacions sobre empty's 2", (get_all Empty) == (get_all $ foldl remove enunciat (elems enunciat))),
("Operacions sobre empty's 3", (remove Empty p1) == empty),
("Operacions sobre empty's 4", not $ (any (== True)) (map (contains Empty) (elems enunciat))),
("Operacions sobre empty's 5", null $ allinInterval empty (list2Point [-500,-500,-500]) (list2Point [500,500,500])),
("Operacions sobre empty's 6", translation [-5,0,-5] Empty == empty),
("Operacions sobre empty's 7", scale (-10.5) Empty == empty),
("Propietat conjunts1", insert enunciat p1 [2,3] == enunciat),
("Propietat conjunts2", insert enunciat p2 [2,3] == enunciat),
("Propietat conjunts3", insert enunciat p3 [1] == enunciat),
("Propietat conjunts4", insert enunciat p11 [1] /= enunciat),
("Propietat conjunts5", foldl (\e (x,y) -> insert e x y) enunciat (get_all enunciat) == enunciat),
("Propietat conjunts6", foldl (\e (x,y) -> insert e x y) equivalent1 (get_all equivalent1) == equivalent2)
]
eqList l1 l2 = (length l1 == length l2) && (length l1 == length (l1 `Data.List.intersect` l2))
difList = not .: eqList where (.:) = (.).(.)
printTests _ [] = do putStrLn "Fi de proves\n----------"
printTests s l = do putStrLn "----------"; printTests' s l 1
where
printTests' _ [] _ = do putStrLn "Fi de proves\n----------"
printTests' s (x:xs) i = do
putStrLn (s ++ "#" ++ (show i))
putStrLn (show x)
putStrLn ""
printTests' s xs (i + 1)
main = do
printTests "Punt " punts
printTests "Arbre " arbres
printTests "Llista " llistes
printTests "Prova " proves
if (and (map snd proves)) then do putStrLn "Proves OK!" else do putStrLn "Proves NOT ok!"
mapM_ putStrLn [string ++ "\n" | string <- strings]
|
albertsgrc/practica-lp-kd2ntrees
|
Main.hs
|
mit
| 6,316 | 1 | 13 | 1,611 | 2,681 | 1,550 | 1,131 | 124 | 2 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, InstanceSigs #-}
{--# LANGUAGE DeriveDataTypeable, ScopedTypeVariables, MultiParamTypeClasses
, FlexibleInstances, FunctionalDependencies #-}
module TemplatesUtility (templatesSettings) where
import Control.Applicative
import Control.Monad
import Data.EitherR
import Data.List
import qualified Data.Map as DM
import System.Exit
import System.FilePath.Posix
import System.Directory
import System.IO
import System.Path.NameManip
import System.Process
import Text.Regex.PCRE
import Data.ConfigFile
import CompilationUtility
import qualified ConfigFile
import Translations
import Templates
import Printer
import Utility
data TEMPLATES_SETTINGS = TEMPLATES_SETTINGS {
ts_executable :: FilePath,
ts_soytojssrccompiler :: FilePath,
ts_flags :: [String],
ts_outputpathformat :: String, -- A format string that specifies how to build the path to each output
-- file. The format string can include literal characters as well as the
-- placeholders {INPUT_PREFIX}, {INPUT_DIRECTORY}, {INPUT_FILE_NAME},
-- {INPUT_FILE_NAME_NO_EXT}
ts_inputs :: [FilePath],
ts_src_path :: FilePath,
ts_app_path :: FilePath,
ts_verbose :: Bool
}
instance UtilitySettings TEMPLATES_SETTINGS where
executable = ts_executable
toStringList a = "-jar":(ts_soytojssrccompiler a):"--outputPathFormat":(ts_outputpathformat a):
(concat [ts_flags a,["--srcs"],[intercalate "," $ ts_inputs a]])
utitle _ = Just "Soy template compiler"
verbose = ts_verbose
templatesSettings :: ConfigParser -> [FilePath] -> EitherT String IO TEMPLATES_SETTINGS
templatesSettings cp inputs = TEMPLATES_SETTINGS
<$> ConfigFile.getFile cp "DEFAULT" "utility.templates.executable"
<*> ConfigFile.getFile cp "DEFAULT" "utility.templates.soytojssrccompiler"
<*> (fmap words $ hoistEither $ ConfigFile.get cp "DEFAULT" "utility.templates.flags")
<*> pure "{INPUT_DIRECTORY}/{INPUT_FILE_NAME}.TEMP"
<*> pure inputs
<*> (fmap dropTrailingPathSeparator $ hoistEither $ ConfigFile.get cp "DEFAULT" "src.path")
<*> (fmap dropTrailingPathSeparator $ hoistEither $ ConfigFile.get cp "DEFAULT" "app.path")
<*> (hoistEither $ ConfigFile.getBool cp "DEFAULT" "verbose")
instance CompilationUtility TEMPLATES_SETTINGS Translations where
defaultValue _ = emptyTrans
failure :: UtilityResult TEMPLATES_SETTINGS -> EitherT String IO Translations
failure r = do
dPut [Failure]
closed <- catchIO $ hIsClosed $ ur_stderr r
if closed then return () else catchIO $ hGetContents (ur_stderr r) >>= putStr
dPut [Ln $ "Exit code: " ++ (show $ ur_exit_code r)]
throwT "TemplatesUtility failure"
success :: UtilityResult TEMPLATES_SETTINGS -> EitherT String IO Translations
success r = do
dPut [Success]
outputs <- moveOutputs (ur_compilation_args r) (ts_inputs $ ur_compilation_args r)
foldM filesExtractor emptyTrans $ zip (ts_inputs $ ur_compilation_args r) outputs
where
moveOutputs :: TEMPLATES_SETTINGS -> [FilePath] -> EitherT String IO [FilePath]
moveOutputs ts [] = return []
moveOutputs ts (f:fs) = do
newName <- hoistEither $ soyToSoyJs (ts_src_path ts) (ts_app_path ts) f
catchIO $ renameFile (f ++ ".TEMP") newName
(:) newName <$> moveOutputs ts fs
filesExtractor :: Translations -> (FilePath, FilePath) -> EitherT String IO Translations
filesExtractor trans (input, output) = do
local <- extractTrans input
catchIO $ withFile output AppendMode $ writeTrans local
return $ mergeTrans trans local
|
Prinhotels/goog-closure
|
src/TemplatesUtility.hs
|
mit
| 3,681 | 0 | 14 | 668 | 882 | 457 | 425 | 72 | 1 |
-- Copyright (C) 2009 Petr Rockai
--
-- Permission is hereby granted, free of charge, to any person
-- obtaining a copy of this software and associated documentation
-- files (the "Software"), to deal in the Software without
-- restriction, including without limitation the rights to use, copy,
-- modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be
-- included in all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
-- BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
-- ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
{-# LANGUAGE CPP #-}
module Darcs.UI.Commands.ShowIndex
( showIndex
, showPristineCmd -- for alias
) where
import Control.Applicative ( (<$>) )
import Control.Monad ( (>=>) )
import Darcs.UI.Flags ( DarcsFlag(NullFlag), useCache )
import Darcs.UI.Commands ( DarcsCommand(..), withStdOpts, nodefaults, amInRepository )
import Prelude hiding ( (^) )
import Darcs.UI.Options ( DarcsOption, (^), oid, odesc, ocheck, onormalise, defaultFlags )
import qualified Darcs.UI.Options.All as O
import Darcs.Repository ( withRepository, RepoJob(..), readIndex )
import Darcs.Repository.State ( readRecorded )
import Storage.Hashed( floatPath )
import Storage.Hashed.Hash( encodeBase16, Hash( NoHash ) )
import Storage.Hashed.Tree( list, expand, itemHash, Tree, TreeItem( SubTree ) )
import Storage.Hashed.Index( updateIndex, listFileIDs )
import Darcs.Util.Path( anchorPath, AbsolutePath )
import System.Posix.Types ( FileID )
import qualified Data.ByteString.Char8 as BS
import Data.Maybe ( fromJust )
import qualified Data.Map as M ( Map, lookup, fromList )
showIndexBasicOpts :: DarcsOption a
(Bool -> Bool -> Bool -> Maybe String -> a)
showIndexBasicOpts = O.files ^ O.directories ^ O.nullFlag ^ O.workingRepoDir
showIndexOpts :: DarcsOption a
(Bool
-> Bool
-> Bool
-> Maybe String
-> Maybe O.StdCmdAction
-> Bool
-> Bool
-> O.Verbosity
-> Bool
-> O.UseCache
-> Maybe String
-> Bool
-> Maybe String
-> Bool
-> a)
showIndexOpts = showIndexBasicOpts `withStdOpts` oid
showIndex :: DarcsCommand [DarcsFlag]
showIndex = DarcsCommand {
commandProgramName = "darcs",
commandName = "index",
commandDescription = "Dump contents of working tree index.",
commandHelp =
"The `darcs show index` command lists all version-controlled files and " ++
"directories along with their hashes as stored in `_darcs/index`. " ++
"For files, the fields correspond to file size, sha256 of the current " ++
"file content and the filename.",
commandExtraArgs = 0,
commandExtraArgHelp = [],
commandCommand = showIndexCmd,
commandPrereq = amInRepository,
commandGetArgPossibilities = return [],
commandArgdefaults = nodefaults,
commandAdvancedOptions = [],
commandBasicOptions = odesc showIndexBasicOpts,
commandDefaults = defaultFlags showIndexOpts,
commandCheckOptions = ocheck showIndexOpts,
commandParseOptions = onormalise showIndexOpts }
dump :: [DarcsFlag] -> Maybe (M.Map FilePath FileID) -> Tree IO -> IO ()
dump opts fileids tree = do
let line | NullFlag `elem` opts = \t -> putStr t >> putChar '\0'
| otherwise = putStrLn
output (p, i) = do
let hash = case itemHash i of
NoHash -> "(no hash available)"
h -> BS.unpack $ encodeBase16 h
path = anchorPath "" p
isdir = case i of
SubTree _ -> "/"
_ -> ""
fileid = case fileids of
Nothing -> ""
Just fileids' -> " " ++ (show $ fromJust $ M.lookup path fileids')
line $ hash ++ fileid ++ " " ++ path ++ isdir
x <- expand tree
mapM_ output $ (floatPath ".", SubTree x) : list x
showIndexCmd :: (AbsolutePath, AbsolutePath) -> [DarcsFlag] -> [String] -> IO ()
showIndexCmd _ opts _ = withRepository (useCache opts) $ RepoJob $ \repo ->
do index <- readIndex repo
index_tree <- updateIndex index
fileids <- (M.fromList . map (\((a,_),b) -> (anchorPath "" a,b))) <$> listFileIDs index
dump opts (Just fileids) index_tree
showPristineCmd :: (AbsolutePath, AbsolutePath) -> [DarcsFlag] -> [String] -> IO ()
showPristineCmd _ opts _ = withRepository (useCache opts) $ RepoJob $
readRecorded >=> dump opts Nothing
|
DavidAlphaFox/darcs
|
src/Darcs/UI/Commands/ShowIndex.hs
|
gpl-2.0
| 5,133 | 0 | 22 | 1,285 | 1,140 | 643 | 497 | 90 | 4 |
-- | Partially taken from Hugs AnsiScreen.hs library:
module Language.Haskell.HsColour.ANSI
( highlightOnG,highlightOn
, highlightOff
, highlightG,highlight
, cleareol, clearbol, clearline, clearDown, clearUp, cls
, goto
, cursorUp, cursorDown, cursorLeft, cursorRight
, savePosition, restorePosition
, Highlight(..)
, Colour(..)
, colourCycle
, enableScrollRegion, scrollUp, scrollDown
, lineWrap
, TerminalType(..)
) where
import Language.Haskell.HsColour.ColourHighlight
import Language.Haskell.HsColour.Output(TerminalType(..))
import Data.List (intersperse,isPrefixOf)
import Data.Char (isDigit)
-- Basic screen control codes:
type Pos = (Int,Int)
at :: Pos -> String -> String
-- | Move the screen cursor to the given position.
goto :: Int -> Int -> String
home :: String
-- | Clear the screen.
cls :: String
at (x,y) s = goto x y ++ s
goto x y = '\ESC':'[':(show y ++(';':show x ++ "H"))
home = goto 1 1
cursorUp = "\ESC[A"
cursorDown = "\ESC[B"
cursorRight = "\ESC[C"
cursorLeft = "\ESC[D"
cleareol = "\ESC[K"
clearbol = "\ESC[1K"
clearline = "\ESC[2K"
clearDown = "\ESC[J"
clearUp = "\ESC[1J"
-- Choose whichever of the following lines is suitable for your system:
cls = "\ESC[2J" -- for PC with ANSI.SYS
--cls = "\^L" -- for Sun window
savePosition = "\ESC7"
restorePosition = "\ESC8"
-- data Colour -- imported from ColourHighlight
-- data Highlight -- imported from ColourHighlight
instance Enum Highlight where
fromEnum Normal = 0
fromEnum Bold = 1
fromEnum Dim = 2
fromEnum Underscore = 4
fromEnum Blink = 5
fromEnum ReverseVideo = 7
fromEnum Concealed = 8
-- The translation of these depends on the terminal type, and they don't translate to single numbers anyway. Should we really use the Enum class for this purpose rather than simply moving this table to 'renderAttrG'?
fromEnum (Foreground (Rgb _ _ _)) = error "Internal error: fromEnum (Foreground (Rgb _ _ _))"
fromEnum (Background (Rgb _ _ _)) = error "Internal error: fromEnum (Background (Rgb _ _ _))"
fromEnum (Foreground c) = 30 + fromEnum c
fromEnum (Background c) = 40 + fromEnum c
fromEnum Italic = 2
-- | = 'highlightG' 'Ansi16Colour'
highlight :: [Highlight] -> String -> String
highlight = highlightG Ansi16Colour
-- | = 'highlightOn' 'Ansi16Colour'
highlightOn :: [Highlight] -> String
highlightOn = highlightOnG Ansi16Colour
-- | Make the given string appear with all of the listed highlights
highlightG :: TerminalType -> [Highlight] -> String -> String
highlightG tt attrs s = highlightOnG tt attrs ++ s ++ highlightOff
highlightOnG :: TerminalType -> [Highlight] -> String
highlightOnG tt [] = highlightOnG tt [Normal]
highlightOnG tt attrs = "\ESC["
++ concat (intersperse ";" (concatMap (renderAttrG tt) attrs))
++"m"
highlightOff :: [Char]
highlightOff = "\ESC[0m"
renderAttrG :: TerminalType -> Highlight -> [String]
renderAttrG XTerm256Compatible (Foreground (Rgb r g b)) =
[ "38", "5", show ( rgb24bit_to_xterm256 r g b ) ]
renderAttrG XTerm256Compatible (Background (Rgb r g b)) =
[ "48", "5", show ( rgb24bit_to_xterm256 r g b ) ]
renderAttrG _ a =
[ show (fromEnum (hlProjectToBasicColour8 a)) ]
-- | An infinite supply of colours.
colourCycle :: [Colour]
colourCycle = cycle [Red,Blue,Magenta,Green,Cyan]
-- | Scrolling
enableScrollRegion :: Int -> Int -> String
enableScrollRegion start end = "\ESC["++show start++';':show end++"r"
scrollDown :: String
scrollDown = "\ESCD"
scrollUp :: String
scrollUp = "\ESCM"
-- Line-wrapping mode
lineWrap :: Bool -> [Char]
lineWrap True = "\ESC[7h"
lineWrap False = "\ESC[7l"
|
crackleware/hscolour
|
Language/Haskell/HsColour/ANSI.hs
|
gpl-2.0
| 3,849 | 0 | 13 | 870 | 956 | 533 | 423 | 82 | 1 |
{-# LANGUAGE NoMonomorphismRestriction #-}
import System.Console.Haskeline
import Text.ParserCombinators.Parsec
import Control.Applicative hiding (many, optional, (<|>))
import Control.Monad.Trans.State hiding (get, put)
import Control.Monad.State.Class
import Control.Monad.IO.Class
import Control.Monad.Trans
import qualified Data.Map as M
import Control.Lens
import Parser
import Types
import TypeChecker
-- Command line command types
data Command =
Quit
| Evaluate String
| GetType String
| Print String
| Load String
| Let String
deriving Show
getType = string ":t" *> optional spaces *> liftA GetType (many anyChar)
quit = string ":q" *> return Quit
evaluate = liftA Evaluate (many anyChar)
putLn = string ":p" *> optional spaces *> liftA Print (many anyChar)
load = string ":l" *> optional spaces *> liftA (Load . trim) (many anyChar)
where trim = filter (`notElem` " \t\r\n")
bind = string ":let" *> optional spaces *> liftA Let (many anyChar)
command = try getType
<|> try quit
<|> try putLn
<|> try bind
<|> try load
<|> evaluate
parseCommand = parse command "(command)"
runQuit = lift $ outputStrLn "Goodbye!"
runGetType str = do
fs@(FievelState _ types) <- get
case M.lookup str types of
Just t -> lift $ outputStrLn $ show t
Nothing -> do
let out = parseSingleExpr str
lift $ case out of
Left (Parser err) -> outputStrLn str >> outputStrLn err
Right e -> case typeOf e of
Right t -> outputStrLn $ show t
Left (TypeError err) -> outputStrLn err
runPrint str = do
fs@(FievelState exprs _) <- get
case M.lookup str exprs of
Just e -> lift $ outputStrLn $ show e
Nothing -> do
let out = parseSingleExpr str
lift $ case out of
Left (Parser err) -> outputStrLn str >> outputStrLn err
Right e -> outputStrLn $ show e
runLoad path = do
fs <- get
out <- liftIO $ parseFievelFile fs path
case out of
Left (Parser err) -> lift $ outputStrLn err
Right st -> do
put st
lift $ (outputStrLn $ show st)
runBind :: String -> StateT FievelState (InputT IO) ()
runBind str = do
fs@(FievelState exprs types) <- get
let out = parseFievel fs str
case out of
Left (Parser err) -> lift $ (outputStrLn str >> outputStrLn err)
Right (res, fs') -> do
lift $ outputStrLn (show res)
put fs'
runEvaluate str = lift $ outputStrLn "Todo: Evaluation"
loop :: StateT FievelState (InputT IO) ()
loop = do
minput <- lift $ getInputLine "Fievel*> "
case minput of
Nothing -> runQuit
Just "" -> loop
Just cmd -> do
let parsed = parseCommand cmd
lift $ outputStrLn $ show parsed
case parsed of
Left err -> lift $ outputStrLn $ show err
Right c -> case c of
Quit -> runQuit
GetType str -> runGetType str >> loop
Print str -> runPrint str >> loop
Let str -> runBind str >> loop
Load path -> runLoad path >> loop
Evaluate str -> runEvaluate str >> loop
main :: IO ()
main = runInputT defaultSettings (evalStateT loop emptyState)
|
5outh/fievel
|
REPL.hs
|
gpl-2.0
| 3,269 | 0 | 21 | 953 | 1,154 | 559 | 595 | 94 | 9 |
{-- |
This module is concerned with individual posts.
It adds three new classes of functionality to Hakyll. Firstly,
pages are routed as `/year/month/day/post-title/index.html` instead of
being routed as ``/posts/year-month-day-title.html`. Secondly, it has
code to detect and filter out drafts from built websites. Thirdly it
adds tags to the post context, and only exposts 'postContextWithTags'
rather than the usual 'postContext'
-}
module Site.Meta ( dateRoute
, filterDrafts
, filterDraftItems
, getYearContext
, postContext
, postContextWithTags
, stripIndexSuffix
) where
import Control.Monad (filterM, liftM)
import Data.Char (isDigit)
import Data.List (isPrefixOf, isSuffixOf)
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid ((<>))
import Data.Time.Calendar (toGregorian)
import Data.Time.Clock
import Data.Time.Format
import Hakyll
import System.FilePath.Posix (takeFileName, dropExtension)
isNotDraft :: MonadMetadata m => Identifier -> m Bool
isNotDraft identifier = liftM (/= Just "true") (getMetadataField identifier "draft")
filterDrafts :: MonadMetadata m => [Identifier] -> m [Identifier]
filterDrafts = filterM isNotDraft
filterDraftItems :: [Item a] -> Compiler [Item a]
filterDraftItems = filterM (isNotDraft . itemIdentifier)
-- A neat trick for static sites is to put pages in directories,
-- and to put the page itself in index.html in the directory.
-- This is how the site is generated, but links should not have the index.html suffix.
stripIndexSuffix :: Item String -> Compiler (Item String)
stripIndexSuffix = return . fmap (withUrls stripSuffix)
where idx = "/index.html"
domain = "http://amixtureofmusings.com/"
domainidx = "http://amixtureofmusings.com/index.html"
shouldStrip url = (("/" `isPrefixOf` url) || (domain `isPrefixOf` url)) &&
(idx `isSuffixOf` url)
stripSuffix url
| url == idx = "/"
| url == domainidx = domain
| shouldStrip url = reverse $ drop (length idx) $ reverse url
| otherwise = url
-- Route a post to a directory which is based on the post date.
dateRoute :: Routes
dateRoute = metadataRoute (\md ->
-- Extract date from metadata, and format it as yyyy/mm/dd.
-- Also extract the slug from the original file, and append it.
let dateString = fromMaybe "2000-01-01" $ M.lookup "date" md
date = parseTimeOrError False defaultTimeLocale "%Y-%m-%d %H:%M" dateString :: UTCTime
datePath = formatTime defaultTimeLocale "%Y/%m/%d" date
dropDate = dropWhile $ \c -> isDigit c || (c == '-')
slug = dropDate . dropExtension . takeFileName . toFilePath
url = (++ "/index.html") . ((datePath ++ "/") ++) . slug
in customRoute url)
-- Post context contains human and machine readable date.
postContext :: Context String
postContext =
dateField "humandate" "%e %B, %Y" <>
dateField "machinedate" "%Y-%m-%d" <>
dateField "archivedate" "%e %B" <>
dateField "archiveyear" "%Y" <>
defaultContext
postContextWithTags :: Tags -> Context String
postContextWithTags tags =
tagsField "tags" tags <> postContext
-- Extracts the year from a time.
getYear :: UTCTime -> Integer
getYear = (\(y, _, _) -> y) . toGregorian . utctDay
-- Site context contains the field 'year'.
yearContext :: Integer -> Context String
yearContext year = constField "year" (show year)
getYearContext :: IO (Context String)
getYearContext = fmap (yearContext . getYear) getCurrentTime
|
budgefeeney/amixtureofmusings
|
Site/Meta.hs
|
gpl-3.0
| 3,775 | 0 | 16 | 942 | 763 | 414 | 349 | 61 | 1 |
module BenchmarkScene5 where
{- A scene to highlight glossy reflection -}
import Objects
import Materials
import Types
bench5Lights :: [Light]
bench5Lights = [Light (Vec3 20 0 0)
(Vec3 0 1 0)
(Vec3 0 0 1)
(Color 0.8 0.8 0.8) ]
bench5Objects :: [Object]
bench5Objects =
[ Sphere (Vec3 1 0 0) 3 whiteMirror
, Sphere (Vec3 5 (-4) 4) 3 redM
, Sphere (Vec3 5 (-4) (-4)) 3 darkgreyM
, Sphere (Vec3 5 4 4) 3 greenM
, Sphere (Vec3 5 4 (-4)) 3 greyM
]
|
jrraymond/ray-tracer
|
src/BenchmarkScene5.hs
|
gpl-3.0
| 540 | 0 | 10 | 183 | 212 | 114 | 98 | 16 | 1 |
{-# Language DoAndIfThenElse #-}
-- | Modulo respectivo a la parte derecha de la interfaz, es decir, el
-- campo de texto.
module GUI.EditBook where
import Graphics.UI.Gtk hiding (get)
import Graphics.UI.Gtk.SourceView
import Control.Lens hiding (set)
import Control.Monad (void)
import Control.Monad.Trans.RWS
import Data.Text (Text, unpack, pack)
import qualified Data.Text as T (concat,length)
import Data.Maybe (fromMaybe)
import GUI.GState
import GUI.Completion
import GUI.Config
import GUI.Utils
import Fun.Module (ModName)
import Fun.Parser
import Paths_fun_gui
-- Configura el lenguaje para el sourceView.
configLanguage :: SourceBuffer -> GuiMonad ()
configLanguage buf = io $ do
-- Language Spec
slm <- sourceLanguageManagerNew
path <- sourceLanguageManagerGetSearchPath slm
langSpecFolder <- getDataFileName languageSpecFolder
sourceLanguageManagerSetSearchPath slm (Just $ langSpecFolder:path)
mlang <- sourceLanguageManagerGuessLanguage
--slm (Just languageSpecFunFile) (Just funMimeType)
slm (Just languageSpecFunFile) (Just funMimeType)
case mlang of
Nothing -> putStrLn "WARNING: No se puede cargar el highlighting para el lenguaje"
Just lang -> do
sourceBufferSetLanguage buf (Just lang)
sourceBufferSetHighlightSyntax buf True
sourceBufferSetHighlightMatchingBrackets buf True
-- Style Scheme
stm <- sourceStyleSchemeManagerNew
txtStyleFolder <- getDataFileName textStylesFolder
sourceStyleSchemeManagerSetSearchPath stm (Just [txtStyleFolder])
styleSch <- sourceStyleSchemeManagerGetScheme stm "fun"
sourceBufferSetStyleScheme buf (Just styleSch)
-- | Configuración del sourceView.
configSourceView :: SourceView -> GuiMonad ()
configSourceView sv = ask >>= \cnt -> get >>= \stref ->
io $ do
sourceViewSetIndentWidth sv funIdentWidth
sourceViewSetAutoIndent sv autoIdent
sourceViewSetIndentOnTab sv setIndentOnTab
sourceViewSetInsertSpacesInsteadOfTabs sv spacesInsteadTab
sourceViewSetShowLineNumbers sv True
void $ io $ on sv keyPressEvent $ deleteCompl cnt stref
void $ io $ on sv moveCursor $ stopCompl cnt stref
void $ io $ on sv buttonPressEvent $ eventStopCompl cnt stref
void $ io $ on sv focusOutEvent $ eventStopCompl cnt stref
return ()
where
eventStopCompl :: GReader -> GStateRef -> EventM t Bool
eventStopCompl cnt stref = io $
eval (updateGState (gFunCompletion .~ Nothing)) cnt stref >>
return False
stopCompl :: GReader -> GStateRef -> MovementStep -> Int -> Bool -> IO ()
stopCompl cnt stref _ _ _ =
eval (updateGState (gFunCompletion .~ Nothing)) cnt stref
deleteCompl :: GReader -> GStateRef -> EventM EKey Bool
deleteCompl cnt stref = eventKeyName >>= \key ->
if key == pack "BackSpace"
then io (eval delCompl cnt stref >> return False)
else return False
delCompl :: GuiMonad ()
delCompl = updateGState
(\st -> maybe
st
(\cpl -> (.~) gFunCompletion
(Just $ rmCharToCompletion cpl) st)
(st ^. gFunCompletion)
)
-- | Configuración de la ventana de scroll, que contiene el campo de texto.
configScrolledWindow :: ScrolledWindow -> GuiMonad ()
configScrolledWindow sw = io $
set sw [ scrolledWindowHscrollbarPolicy := PolicyAutomatic
, scrolledWindowVscrollbarPolicy := PolicyAlways
]
-- | Configuración del aspecto del notebook que contiene los archivos abiertos.
configNotebook :: Notebook -> GuiMonad ()
configNotebook nb = io $
set nb [ notebookTabBorder := 0
, notebookTabHborder := 0
, notebookTabVborder := 0
]
-- | Crea un campo de texto y lo llena, de ser posible, con el string.
createTextEntry :: Maybe String -> GuiMonad SourceView
createTextEntry mcode = do
buf <- io $ sourceBufferNew Nothing
configLanguage buf
maybe (return ()) (io . loadCode buf) mcode
configSourceBuffer buf
sourceview <- io $ sourceViewNewWithBuffer buf
configSourceView sourceview
return sourceview
where
loadCode :: TextBufferClass tbuffer => tbuffer -> String -> IO ()
loadCode buf code = do
start <- textBufferGetStartIter buf
textBufferInsert buf start code
configSourceBuffer :: SourceBuffer -> GuiMonad ()
configSourceBuffer sb = ask >>= \cnt -> get >>= \stref -> io $ do
void $ after sb bufferInsertText $ insCompl cnt stref
where
insCompl :: GReader -> GStateRef -> TextIter -> Text -> IO ()
insCompl cnt stref ti str = eval (putCompletion ti str) cnt stref
putCompletion :: TextIter -> Text -> GuiMonad ()
putCompletion ti str
| checkBeginChar str =
updateGState (gFunCompletion .~ (Just $ newCompletion))
| checkEndChar str = tryPutSymbol ti str
| otherwise =
getGState >>= \st ->
maybe (return ()) (putCompl str) (st ^. gFunCompletion)
tryPutSymbol :: TextIter -> Text -> GuiMonad ()
tryPutSymbol ti str = getGState >>= \st ->
maybe (updateGState (gFunCompletion .~ Nothing))
(replaceSymbol ti str)
(maybe Nothing
checkCompletion (st ^. gFunCompletion))
replaceSymbol :: TextIter -> Text -> (Text, Text) -> GuiMonad ()
replaceSymbol eit str (sy,nname) = io (
textIterCopy eit >>= \bit ->
textIterBackwardChars bit (T.length nname + 2) >>
textBufferSelectRange sb bit eit >>
textBufferDeleteSelection sb True True >>
textBufferInsertAtCursor sb (T.concat [sy,str])) >>
updateGState (gFunCompletion .~ Nothing)
putCompl :: Text -> Completion -> GuiMonad ()
putCompl str cpl = updateGState (gFunCompletion .~
(Just $ addCharToCompletion str cpl))
-- | Crea un campo de texto con su respectivo scrollWindow.
createTextEdit :: Maybe String -> GuiMonad ScrolledWindow
createTextEdit mcode = do
swindow <- io $ scrolledWindowNew Nothing Nothing
configScrolledWindow swindow
texte <- createTextEntry mcode
io $ containerAdd swindow texte
io $ widgetShowAll texte
io $ widgetShowAll swindow
return swindow
getTextViewFilePath :: Int -> GuiMonad (Maybe TextFilePath)
getTextViewFilePath i = do
st <- getGState
return . takeFilePath $ st ^. gFunEditBook
where
takeFilePath :: FunEditBook -> Maybe TextFilePath
takeFilePath feb = (feb ^. tabFileList) !! i
-- | Dado un EditBook, obtiene el campo de texto que esta seleccionado en
-- ese momento y su nombre.
getTextEditFromFunEditBook :: FunEditBook ->
GuiMonad (Maybe (Maybe TextFilePath, String,TextView))
getTextEditFromFunEditBook feditBook = do
let notebook = feditBook ^. book
cPageNum <- io $ notebookGetCurrentPage notebook
if (cPageNum < 0) then return Nothing
else do
mfp <- getTextViewFilePath cPageNum
Just cpSW <- io $ notebookGetNthPage notebook cPageNum
Just textViewN <- io $ notebookGetTabLabelText notebook cpSW
[tv] <- io $ containerGetChildren (castToContainer cpSW)
return (Just (mfp,textViewN,castToTextView tv))
withTextEditFromFunEditBook :: FunEditBook ->
((Maybe TextFilePath, String,TextView) -> GuiMonad ()) ->
GuiMonad ()
withTextEditFromFunEditBook feditBook action = getTextEditFromFunEditBook feditBook >>=
maybe (return ()) action
-- | similar a la anterior pero en la mónada IO. Le debemos pasar el notebook.
getTextEditFromNotebook :: Notebook -> IO (String,TextView)
getTextEditFromNotebook notebook = do
cPageNum <- notebookGetCurrentPage notebook
Just cpSW <- notebookGetNthPage notebook cPageNum
Just textViewN <- notebookGetTabLabelText notebook cpSW
[tv] <- containerGetChildren (castToContainer cpSW)
return (textViewN,castToTextView tv)
-- | Dado un EditBook y un nombre de módulo, actualiza el mapeo entre tabs-nombres de modulos
-- asignando al tab seleccionado el nombre de modulo.
updateModulesFunEditBook :: FunEditBook -> ModName -> GuiMonad ()
updateModulesFunEditBook feditBook mName = do
let notebook = feditBook ^. book
cPageNum <- io $ notebookGetCurrentPage notebook
-- actualizamos el label del tab con el nombre del modulo
Just cpSW <- io $ notebookGetNthPage notebook cPageNum
io $ notebookSetTabLabelText notebook cpSW (unpack mName)
-- | Crea un editBook, el cual tiene un primer campo de texto con nombre
-- y contenido de ser posible.
createEditBook :: Maybe String -> Maybe String -> GuiMonad Notebook
createEditBook mname mcode = do
let name = fromMaybe "blank" mname
newnt <- io notebookNew
configNotebook newnt
texte <- createTextEdit mcode
_<- io $ notebookAppendPage newnt texte name
content <- ask
let editorPaned = content ^. (gFunEditorPaned . epaned)
io $ panedAdd1 editorPaned newnt
io $ widgetShowAll editorPaned
return newnt
|
alexgadea/fun-gui
|
GUI/EditBook.hs
|
gpl-3.0
| 10,349 | 0 | 19 | 3,396 | 2,361 | 1,147 | 1,214 | 177 | 2 |
{-# OPTIONS_GHC -Wall #-}
-----------------------------------------------------------------------------
-- |
-- Module : Numeric.LATC.SparseIntMap
-- Copyright : (c) Matthew Peddie 2012
-- License : GPLv3 (see the file latc/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : GHC
--
-- IntMaps as a (sparse) linear algebra backend
-----------------------------------------------------------------------------
module Numeric.LATC.SparseIntMap (
-- * Newtype wrappers
Vector
, Matrix
-- * Structural functions
-- ** Structural functions on a @Vector@
-- , fromList
-- , toList
-- , fromSparseList
-- , toSparseList
-- , length
-- , map
-- -- ** Structural functions on a @Matrix@
-- , fromLists
-- , toLists
-- , fromSparseLists
-- , toSparseLists
-- , size
-- , mmap
-- , transpose
-- -- ** Structural functions between @Vector@s and @Matrix@es
-- , toRows
-- , fromRows
-- , toCols
-- , fromCols
-- -- * Math functions
-- , matvec
-- , vecmat
-- , matmat
-- , inner
-- , outer
) where
import Prelude hiding (length, map)
import qualified Prelude as P
import Data.IntMap (IntMap(..))
import qualified Data.IntMap as IM
data Vector a = Vector { unvector :: IntMap a
, vlen :: Int
} deriving (Eq)
data Matrix a = Matrix { unmatrix :: IntMap (IntMap a)
, msize :: (Int, Int)
} deriving (Eq)
instance Show a => Show (Vector a) where
show (Vector l v) = "Vector<" ++ show l ++ "> " ++ show v
instance Show a => Show (Matrix a) where
show (Matrix m) = "Matrix " ++ show m
unsparse :: a -> Int -> IM.IntMap a -> [a]
unsparse def size im = P.map (\k -> IM.findWithDefault def k im) [0..size]
-- | Convert a list to a @Vector@
fromList :: [b] -> Vector b
fromList l = Vector (IM.fromList $ (zip [0..] l)) (P.length l)
-- | Convert a @Vector@ to a list
toList :: Vector b -> [b]
toList (Vector l v) = if l == IM.size v
then IM.toList v
else zip (unsparse 0
-- | Convert a list of pairs @(index, value)@ to a @Vector@
fromSparseList :: [(Int, b)] -> Vector b
fromSparseList = Vector . IM.fromList
-- | Convert a @Vector@ to a list of pairs @(index, value)@
toSparseList :: Vector b -> [(Int, b)]
toSparseList = IM.toList . unvector
|
peddie/latc
|
Numeric/LATC/SparseIntMap.hs
|
gpl-3.0
| 3,310 | 6 | 11 | 1,530 | 518 | 303 | 215 | -1 | -1 |
-- Copyright 2011 Jared Hance
{-# LANGUAGE FlexibleContexts, TypeOperators #-}
module Data.Binary.Derive
(
derivePut,
deriveGet
)
where
import Control.Applicative
import Data.Binary
import GHC.Generics
data ConsChoice = L | R
instance Binary ConsChoice where
put L = put True
put R = put False
get = do b <- get
case b of
True -> return L
False -> return R
-- | Derives a `put` function for an instance of Binary. Normally you won't
-- call this from anywhere except that `put` function in your instance
-- declaration.
derivePut :: (Generic t, GBinary (Rep t)) => t -> Put
derivePut = gput . from
-- | Derives a `get` value for an instance of Binary. Normally you won't use
-- this from anywhere except that `get` value in your instance declaration.
deriveGet :: (Generic t, GBinary (Rep t)) => Get t
deriveGet = gget >>= return . to
class GBinary f where
gput :: f t -> Put
gget :: Get (f t)
instance GBinary U1 where
gput U1 = return ()
gget = return U1
instance Binary t => GBinary (K1 i t) where
gput (K1 x) = put x
gget = do x <- get
return $ K1 x
instance GBinary t => GBinary (M1 i c t) where
gput (M1 x) = gput x
gget = do x <- gget
return $ M1 x
instance (GBinary a, GBinary b) => GBinary (a :+: b) where
gput (L1 x) = put L >> gput x
gput (R1 x) = put R >> gput x
gget = do t <- get
case t of
L -> do x <- gget
return $ L1 x
R -> do x <- gget
return $ R1 x
instance (GBinary a, GBinary b) => GBinary (a :*: b) where
gput (x :*: y) = do gput x
gput y
gget = do (:*:) <$> gget <*> gget
|
jhance/binary-derive
|
Data/Binary/Derive.hs
|
gpl-3.0
| 1,778 | 16 | 16 | 597 | 609 | 301 | 308 | 47 | 1 |
module Chap05.Data.PairingHeap.Exercise08 where
import Chap03.Data.Heap (Heap(..), arbHeap)
import Chap05.Data.BinaryTree
import Test.QuickCheck (Arbitrary(..), sized)
newtype PairingHeap a = C5E8 (BinaryTree a)
deriving (Show)
instance Heap PairingHeap where
empty = C5E8 E
isEmpty (C5E8 E) = True
isEmpty _ = False
findMin (C5E8 E) = Nothing
findMin (C5E8 (T x _ _)) = Just x
merge h (C5E8 E) = h
merge (C5E8 E) h = h
merge (C5E8 (T x a1 _)) (C5E8 (T y a2 _))
| x <= y = C5E8 $ T x (T y a2 a1) E
| otherwise = C5E8 $ T y (T x a1 a2) E
insert x = merge (C5E8 $ T x E E)
deleteMin (C5E8 E) = Nothing
deleteMin (C5E8 (T _ a _)) = Just $ mergePairs a
where
mergePairs :: Ord a => BinaryTree a -> PairingHeap a
mergePairs (T a1 x (T a2 y rest)) =
let h1 = C5E8 $ T a1 x E
h2 = C5E8 $ T a2 y E
in merge (merge h1 h2) (mergePairs rest)
mergePairs t = C5E8 t
instance (Ord a, Arbitrary a) => Arbitrary (PairingHeap a) where
arbitrary = sized arbHeap
|
stappit/okasaki-pfds
|
src/Chap05/Data/PairingHeap/Exercise08.hs
|
gpl-3.0
| 1,085 | 0 | 13 | 332 | 512 | 260 | 252 | 28 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Calendar.CalendarList.Watch
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Watch for changes to CalendarList resources.
--
-- /See:/ <https://developers.google.com/google-apps/calendar/firstapp Calendar API Reference> for @calendar.calendarList.watch@.
module Network.Google.Resource.Calendar.CalendarList.Watch
(
-- * REST Resource
CalendarListWatchResource
-- * Creating a Request
, calendarListWatch
, CalendarListWatch
-- * Request Lenses
, clwSyncToken
, clwMinAccessRole
, clwShowDeleted
, clwPayload
, clwShowHidden
, clwPageToken
, clwMaxResults
) where
import Network.Google.AppsCalendar.Types
import Network.Google.Prelude
-- | A resource alias for @calendar.calendarList.watch@ method which the
-- 'CalendarListWatch' request conforms to.
type CalendarListWatchResource =
"calendar" :>
"v3" :>
"users" :>
"me" :>
"calendarList" :>
"watch" :>
QueryParam "syncToken" Text :>
QueryParam "minAccessRole"
CalendarListWatchMinAccessRole
:>
QueryParam "showDeleted" Bool :>
QueryParam "showHidden" Bool :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Int32) :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Channel :> Post '[JSON] Channel
-- | Watch for changes to CalendarList resources.
--
-- /See:/ 'calendarListWatch' smart constructor.
data CalendarListWatch = CalendarListWatch'
{ _clwSyncToken :: !(Maybe Text)
, _clwMinAccessRole :: !(Maybe CalendarListWatchMinAccessRole)
, _clwShowDeleted :: !(Maybe Bool)
, _clwPayload :: !Channel
, _clwShowHidden :: !(Maybe Bool)
, _clwPageToken :: !(Maybe Text)
, _clwMaxResults :: !(Maybe (Textual Int32))
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'CalendarListWatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'clwSyncToken'
--
-- * 'clwMinAccessRole'
--
-- * 'clwShowDeleted'
--
-- * 'clwPayload'
--
-- * 'clwShowHidden'
--
-- * 'clwPageToken'
--
-- * 'clwMaxResults'
calendarListWatch
:: Channel -- ^ 'clwPayload'
-> CalendarListWatch
calendarListWatch pClwPayload_ =
CalendarListWatch'
{ _clwSyncToken = Nothing
, _clwMinAccessRole = Nothing
, _clwShowDeleted = Nothing
, _clwPayload = pClwPayload_
, _clwShowHidden = Nothing
, _clwPageToken = Nothing
, _clwMaxResults = Nothing
}
-- | Token obtained from the nextSyncToken field returned on the last page of
-- results from the previous list request. It makes the result of this list
-- request contain only entries that have changed since then. If only
-- read-only fields such as calendar properties or ACLs have changed, the
-- entry won\'t be returned. All entries deleted and hidden since the
-- previous list request will always be in the result set and it is not
-- allowed to set showDeleted neither showHidden to False. To ensure client
-- state consistency minAccessRole query parameter cannot be specified
-- together with nextSyncToken. If the syncToken expires, the server will
-- respond with a 410 GONE response code and the client should clear its
-- storage and perform a full synchronization without any syncToken. Learn
-- more about incremental synchronization. Optional. The default is to
-- return all entries.
clwSyncToken :: Lens' CalendarListWatch (Maybe Text)
clwSyncToken
= lens _clwSyncToken (\ s a -> s{_clwSyncToken = a})
-- | The minimum access role for the user in the returned entries. Optional.
-- The default is no restriction.
clwMinAccessRole :: Lens' CalendarListWatch (Maybe CalendarListWatchMinAccessRole)
clwMinAccessRole
= lens _clwMinAccessRole
(\ s a -> s{_clwMinAccessRole = a})
-- | Whether to include deleted calendar list entries in the result.
-- Optional. The default is False.
clwShowDeleted :: Lens' CalendarListWatch (Maybe Bool)
clwShowDeleted
= lens _clwShowDeleted
(\ s a -> s{_clwShowDeleted = a})
-- | Multipart request metadata.
clwPayload :: Lens' CalendarListWatch Channel
clwPayload
= lens _clwPayload (\ s a -> s{_clwPayload = a})
-- | Whether to show hidden entries. Optional. The default is False.
clwShowHidden :: Lens' CalendarListWatch (Maybe Bool)
clwShowHidden
= lens _clwShowHidden
(\ s a -> s{_clwShowHidden = a})
-- | Token specifying which result page to return. Optional.
clwPageToken :: Lens' CalendarListWatch (Maybe Text)
clwPageToken
= lens _clwPageToken (\ s a -> s{_clwPageToken = a})
-- | Maximum number of entries returned on one result page. By default the
-- value is 100 entries. The page size can never be larger than 250
-- entries. Optional.
clwMaxResults :: Lens' CalendarListWatch (Maybe Int32)
clwMaxResults
= lens _clwMaxResults
(\ s a -> s{_clwMaxResults = a})
. mapping _Coerce
instance GoogleRequest CalendarListWatch where
type Rs CalendarListWatch = Channel
type Scopes CalendarListWatch =
'["https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/calendar.readonly"]
requestClient CalendarListWatch'{..}
= go _clwSyncToken _clwMinAccessRole _clwShowDeleted
_clwShowHidden
_clwPageToken
_clwMaxResults
(Just AltJSON)
_clwPayload
appsCalendarService
where go
= buildClient
(Proxy :: Proxy CalendarListWatchResource)
mempty
|
rueshyna/gogol
|
gogol-apps-calendar/gen/Network/Google/Resource/Calendar/CalendarList/Watch.hs
|
mpl-2.0
| 6,531 | 0 | 21 | 1,574 | 837 | 490 | 347 | 121 | 1 |
-- eidolon -- A simple gallery in Haskell and Yesod
-- Copyright (C) 2015 Amedeo Molnár
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Affero General Public License as published
-- by the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
module Handler.Reactivate where
import Import
import Control.Monad
import Data.Text.Encoding
getReactivateR :: Handler Html
getReactivateR = do
(reactivateWidget, enctype) <- generateFormPost reactivateForm
formLayout $ do
setTitle "Eidolon :: Reactivate account"
$(widgetFile "reactivate")
postReactivateR :: Handler Html
postReactivateR = do
((result, _), _) <- runFormPost reactivateForm
case result of
FormSuccess temp -> do
users <- runDB $ selectList [UserEmail ==. temp] []
case null users of
True -> do
userTokens <- foldM (\userTokens (Entity userId user) -> do
token <- liftIO $ generateString
_ <- runDB $ insert $ Token (encodeUtf8 token) "activate" (Just userId)
return $ (user, token) : userTokens
) [] users
_ <- foldM (\sent (user, token) ->
case sent of
False ->
return False
True -> do
activateLink <- ($ ActivateR token) <$> getUrlRender
sendMail (userEmail user) "Reset your password" $
[shamlet|
<h1>Welcome again to Eidolon #{userName user}
To reset your password visit the following link:
<a href="#{activateLink}">#{activateLink}
See you soon!
|]
return True
) True userTokens
setMessage "Your new password activation will arrive in your e-mail"
redirect $ HomeR
False -> do
setMessage "No user mith this Email"
redirect $ LoginR
_ -> do
setMessage "There is something wrong with your email"
redirect $ ReactivateR
reactivateForm :: Form Text
reactivateForm = renderDivs $ (\a -> a)
<$> areq emailField "Email" Nothing
|
Mic92/eidolon
|
Handler/Reactivate.hs
|
agpl-3.0
| 2,628 | 3 | 30 | 773 | 461 | 232 | 229 | -1 | -1 |
----------------------------------------------------------------------------
-- |
-- Module : Parser
-- Copyright : (c) Masahiro Sakai 2007-2009
-- License : BSD3-style (see LICENSE)
--
-- Maintainer: [email protected]
-- Stability : experimental
-- Portability : non-portable
{-# LANGUAGE GADTs, TypeOperators #-}
module Parser (parse, parseAny) where
import Data.Char
import Control.Applicative
import Control.Monad
import qualified Data.IntSet as IS
import P
-----------------------------------------------------------------------------
-- パーサのコア部分
type Token = String
newtype Parser a
= Parser
{ runParser :: Env -> State -> [Token] -> [(a, State, [Token])]
}
instance Functor Parser where
fmap = liftM
instance Applicative Parser where
pure = return
(<*>) = ap
instance Alternative Parser where
empty = mzero
(<|>) = mplus
instance Monad Parser where
return x = Parser $ \_ s ts -> [(x,s,ts)]
m >>= f = Parser $ \env s ts ->
do (v,s',ts') <- runParser m env s ts
runParser (f v) env s' ts'
instance MonadPlus Parser where
mzero = Parser $ \_ _ _ -> []
mplus x y = Parser $ \env s ts ->
runParser x env s ts ++ runParser y env s ts
anyToken :: Parser Token
anyToken = Parser g
where g _ _ [] = []
g _ s (t:ts) = [(t, s, ts)]
lookAhead :: Parser Token
lookAhead = Parser g
where g _ _ [] = []
g _ s (t:ts) = [(t, s, t:ts)]
-----------------------------------------------------------------------------
-- 環境
data Env
= Env
{ s3env :: S3Env
}
initialEnv :: Env
initialEnv = Env{ s3env = initialS3Env }
local :: (Env -> Env) -> Parser a -> Parser a
local f (Parser g) = Parser g'
where g' env s ts = g (f env) s ts
ask :: Parser Env
ask = Parser g
where g env s ts = [(env,s,ts)]
-----------------------------------------------------------------------------
-- 状態
data State
= State
{ gensymState :: PronounNo
, f10State :: F10State
}
initialState :: State
initialState = State{ gensymState = 0, f10State = initialF10State }
get :: Parser State
get = Parser g
where g _ s xs = [(s,s,xs)]
put :: State -> Parser ()
put s = Parser g
where g _ _ xs = [((),s,xs)]
-----------------------------------------------------------------------------
-- S3Env
type S3Env = [(PronounNo,Gender)] -- S3規則で使うためのデータ
initialS3Env :: S3Env
initialS3Env = []
localS3 :: (S3Env -> S3Env) -> Parser a -> Parser a
localS3 f = local (\env@Env{ s3env = x } -> env{ s3env = f x })
askS3 :: Parser S3Env
askS3 = liftM s3env ask
-----------------------------------------------------------------------------
-- Counter
gensym :: Parser PronounNo
gensym =
do s@State{ gensymState = i } <- get
put s{ gensymState = i+1 }
return i
-----------------------------------------------------------------------------
-- F10のための処理
-- DVarStateみたいな名前にした方が良いか
type F10Entry = (PronounNo, Gender, P T, IS.IntSet)
type F10State = [F10Entry] -- F10で使うためのデータ
initialF10State :: F10State
initialF10State = []
getF10State :: Parser F10State
getF10State =
do State{ f10State = s } <- get
return s
putF10State :: F10State -> Parser ()
putF10State s =
do x <- get
put x{ f10State = s }
asPronoun :: Gender -> P T -> Parser (P T)
asPronoun g t =
do n <- gensym
s <- getF10State
putF10State ((n,g,t,fvs t) : s)
return (He n)
mayF10s :: F10 c => Parser (P c) -> Parser (P c)
mayF10s p = liftM fst $ mayF10s' $ p >>= \x -> return (x,())
mayF10s' :: F10 c => Parser (P c, a) -> Parser (P c, a)
mayF10s' p =
do s <- getF10State
putF10State []
(x,a) <- localS3 ([(n,g) | (n,g,_,_)<-s]++) p
x' <- introF10s x
s' <- getF10State
putF10State (s'++s)
return (x',a)
introF10 :: F10 c => P c -> Parser (P c)
introF10 x =
do (n, _, alpha, _) <- takeF10Entry
return (F10 n alpha x)
introF10s :: F10 c => P c -> Parser (P c)
introF10s x = (introF10 x >>= introF10s) <|> return x
-- F10に変換可能なエントリを取り出す
takeF10Entry :: Parser F10Entry
takeF10Entry =
do s <- getF10State
(e@(n,_,_,_), s') <- msum $ map return $ pick s
noDanglingRef n
putF10State s'
return e
pick :: [a] -> [(a,[a])]
pick [] = []
pick (x:xs) = (x,xs) : [(y,x:ys) | (y,ys) <- pick xs]
-- nへの参照が残っていないことを保障
noDanglingRef :: PronounNo -> Parser ()
noDanglingRef n =
do s <- getF10State
guard $ and [not (IS.member n vs) | (_,_,_,vs) <- s]
-----------------------------------------------------------------------------
-- パーサのユーティリティ
token :: Token -> Parser Token
token x =
do y <- anyToken
guard $ x==y
return y
chainr1 :: Parser a -> Parser (a->a->a) -> Parser a
chainr1 p q =
do x <- p
f <- do{ op <- q; y <- chainr1 p q; return (`op` y) } <|> return id
return (f x)
-----------------------------------------------------------------------------
-- API
parse :: String -> [P Sen]
parse = parse' p_t
parseAny :: String -> [PAny]
parseAny s = concat $
[ f p_Det, f (liftM fst p_CN), f p_IAV_T, f p_t_t, f p_t, f p_Adj, f p_PP
, f p_IAV, f p_PP_T, f (p_T [Subject, Object]) ] ++
[ concat [ f (p_IV x), f (p_TV x), f (p_IV__IV x), f (p_DTV x), f (p_IV_t x)
, f (p_IV_Adj x)] | x <- vfs ]
where
f :: CatType a => Parser (P a) -> [PAny]
f p = map PAny (parse' p s)
vfs :: [VerbForm]
vfs = [VFOrig, VFPastParticiple] ++ [f True | f <- [VFPresent, VFFuture, VFPerfect]]
-- 否定形の動詞それ自体はPで表現できないのでパース出来ない
parse' :: Parser (P a) -> String -> [P a]
parse' p s = [x | (x, State{ f10State = [] }, []) <- runParser p initialEnv initialState ts]
where ts = tokenize s
tokenize :: String -> [Token]
tokenize = expandAbbr . words . map toLower . filter ('.'/=)
expandAbbr :: [String] -> [String]
expandAbbr = concatMap f
where f "doesn't" = ["does", "not"]
f "won't" = ["will", "not"]
f "hasn't" = ["has", "not"]
f "isn't" = ["is", "not"]
f x = [x]
-----------------------------------------------------------------------------
-- 各範疇のパーサ
p_Det :: Parser (P Det)
p_Det =
do x@(B _ s) <- s1_Det
let x' = if s=="an" then B (cat :: Cat Det) "a" else x -- XXX
-- FIXME: anの場合には次の語が母音で始まるかチェック
return $ x'
p_CN :: Parser (P CN, Gender)
p_CN = mayF10s' $ -- S15
do (zeta,g) <- s1_CN
zeta <- s3s g zeta
return (zeta,g)
-- FIXME: 全ての組み合わせを網羅している?
p_T :: [Case] -> Parser (P T)
p_T cs = chainr1 (p <|> he_n cs) f9 -- S13
where p = do (x,g) <- s1_T <|> s2
return x <|> asPronoun g x
-- He_n
he_n :: [Case] -> Parser (P T)
he_n cs =
do g <- mplus
(if Subject `elem` cs
then msum [ token "he" >> return Masculine
, token "she" >> return Feminine
, token "it" >> return Neuter
]
else mzero)
(if Object `elem` cs
then msum [ token "him" >> return Masculine
, token "her" >> return Feminine
, token "it" >> return Neuter
]
else mzero)
xs <- getF10State
ys <- askS3
let ns = [(n,g') | (n, g', _, _) <- xs] ++ ys
msum [ return (He n) | (n,g') <- ns, g==g' ]
-- FIXME: 全ての組み合わせを網羅している?
p_IV :: VerbForm -> Parser (P IV)
p_IV vf = mayF10s q -- S16
where p = do x <- s1_IV vf
<|> s5 vf
<|> s7 vf
<|> s8 vf
<|> s18 vf
<|> s19 vf
<|> s23 vf
liftM (foldl (flip F7) x) (many p_IAV) -- S10
q = chainr1 p (f8 <|> f9) -- S12a, S12b
p_TV :: VerbForm -> Parser (P TV)
p_TV vf = s1_TV vf <|> s20 vf <|> s21 vf
p_IAV_T :: Parser (P (IAV :/ T))
p_IAV_T = s1_IAV_T
p_IV__IV :: VerbForm -> Parser (P (IV :// IV))
p_IV__IV = s1_IV__IV
p_t_t :: Parser (P (Sen :/ Sen))
p_t_t = s1_t_t
-- FIXME: 全ての組み合わせを網羅している?
p_t :: Parser (P Sen)
p_t = mayF10s $ -- S14
chainr1 (s9 <|> s4_or_s17) (f8 <|> f9) -- S11a, S11b
p_IV_t :: VerbForm -> Parser (P (IV :/ Sen))
p_IV_t = s1_IV_t
p_IV_Adj :: VerbForm -> Parser (P (IV :/ Adj))
p_IV_Adj vf = s1_IV_Adj vf
p_Adj :: Parser (P Adj)
p_Adj = s1_Adj <|> s25
-- FIXME
p_DTV :: VerbForm -> Parser (P DTV)
p_DTV vf = mzero -- ???
p_PP :: Parser (P PP)
p_PP = s24
p_IAV :: Parser (P IAV)
p_IAV = s1_IAV <|> s6
p_PP_T :: Parser (P (PP :/ T))
p_PP_T = s1_PP_T
-----------------------------------------------------------------------------
-- 動詞の辞書
-- (原形, 三人称単数現在形, 過去分詞)
type VerbEntry = (String, String, String)
verb_be :: VerbEntry
verb_be = ("be", "is", "been")
{-# INLINE regularVerb #-}
regularVerb :: String -> VerbEntry
regularVerb s = (s, present, past_participle)
where
rs = reverse s
present =
case rs of
's':'s':_ -> s ++ "es"
'h':'c':_ -> s ++ "es"
'h':'s':_ -> s ++ "es"
'x':_ -> s ++ "es"
'y':s' -> reverse s' ++ "ies"
_ -> s ++ "s"
past_participle =
case rs of
'e':_ -> s ++ "d"
'y':s' -> reverse s' ++ "ied"
_ -> s ++ "ed"
dict_IV :: [VerbEntry]
dict_IV =
[ regularVerb "walk"
, regularVerb "talk"
, regularVerb "change"
, ("run", "runs", "ran")
, ("rise", "rises", "rosen")
]
dict_TV :: [VerbEntry]
dict_TV =
[ ("find", "finds", "found")
, ("lose", "loses", "lost")
, ("eat", "eats", "eaten")
, ("seek", "seeks", "sought")
, regularVerb "love"
, regularVerb "date"
--, "coneive" -- FIXME: conceiveの間違い?
, verb_be
]
dict_IV_t :: [VerbEntry]
dict_IV_t =
[ regularVerb "believe"
, regularVerb "assert"
]
dict_IV__IV :: [VerbEntry]
dict_IV__IV =
[ regularVerb "try"
, regularVerb "wish"
]
dict_IV_Adj :: [VerbEntry]
dict_IV_Adj = [verb_be]
-- DTVをTTVに変換することは出来るから、giveの範疇はDTVだろうな。多分。
dict_DTV :: [VerbEntry]
dict_DTV =
[ ("give", "gives", "given")
]
-----------------------------------------------------------------------------
-- 動詞のパーサ
data VerbForm
= VFOrig -- 原形
| VFPastParticiple -- 過去分詞
| VFPresent !Bool -- 三人称単数現在形とその否定形
| VFFuture !Bool -- 三人称単数未来系とその否定形
| VFPerfect !Bool -- 三人称単数現在完了系とその否定形
{-# INLINE verbParser #-}
verbParser :: CatType c => [VerbEntry] -> VerbForm -> Parser (P c)
verbParser dict vf =
do s <- verbParser' dict vf
return (B cat s)
-- FIXME: 後で整理する
{-# INLINE verbParser' #-}
verbParser' :: [VerbEntry] -> VerbForm -> Parser String
verbParser' dict (VFPresent False) =
mplus (do token "does"
token "not"
x <- verbParser' dict VFOrig
guard (x/="be")
return x)
(do x <- verbParser' dict (VFPresent True)
guard (x=="be")
token "not"
return x)
verbParser' dict (VFFuture b) =
do token "will"
unless b $ token "not" >> return ()
verbParser' dict VFOrig
verbParser' dict (VFPerfect b) =
do token "has"
unless b $ token "not" >> return ()
verbParser' dict VFPastParticiple
verbParser' dict vf =
do x <- anyToken
msum [ return o
| (o, present, pastparticiple) <- dict
, case vf of
VFOrig -> o==x
VFPastParticiple -> pastparticiple==x
VFPresent True -> present==x
_ -> False -- shouldn't happen
]
-----------------------------------------------------------------------------
-- 名詞の辞書とパーサ
data Case = Subject | Object deriving (Show,Eq,Ord)
data Gender = Masculine | Feminine | Neuter deriving (Show,Eq,Ord)
type NounEntry = (String, Gender)
dict_T :: [NounEntry]
dict_T =
[ ("john" , Masculine)
, ("mary" , Feminine)
, ("bill" , Masculine)
, ("ninety" , Neuter)
]
dict_CN :: [NounEntry]
dict_CN =
[ ("man" , Masculine)
, ("woman" , Feminine)
, ("park" , Neuter)
, ("fish" , Neuter)
, ("pen" , Neuter)
, ("unicorn" , Neuter)
, ("price" , Neuter)
, ("temperature" , Neuter)
]
{-# INLINE nounParser #-}
nounParser :: CatType c => [NounEntry] -> Parser (P c, Gender)
nounParser dict =
do x <- anyToken
case lookup x dict of
Nothing -> mzero
Just g -> return (B cat x, g)
-----------------------------------------------------------------------------
-- それ以外の基本表現の辞書とパーサ
dict_IAV :: [String]
dict_IAV =
[ "rapidly"
, "slowly"
, "voluntarily"
, "allegedly"
]
dict_t_t :: [String]
dict_t_t = ["necessarily"]
dict_IAV_T :: [String]
dict_IAV_T = ["in", "about"]
dict_Adj :: [String]
dict_Adj = ["asleep"]
dict_Det :: [String]
dict_Det = ["a", "an", "the", "every", "no"]
dict_PP_T :: [String]
dict_PP_T = ["by"]
{-# INLINE dictParser #-}
dictParser :: CatType c => [String] -> Parser (P c)
dictParser dict =
do x <- anyToken
guard $ x `elem` dict
return $ B cat x
-----------------------------------------------------------------------------
-- 各統語規則のパーサ
s1_IV :: VerbForm -> Parser (P IV)
s1_IV = verbParser dict_IV
s1_TV :: VerbForm -> Parser (P TV)
s1_TV = verbParser dict_TV
s1_IV_t :: VerbForm -> Parser (P (IV :/ Sen))
s1_IV_t = verbParser dict_IV_t
s1_IV__IV :: VerbForm -> Parser (P (IV :// IV))
s1_IV__IV = verbParser dict_IV__IV
s1_IV_Adj :: VerbForm -> Parser (P (IV :/ Adj))
s1_IV_Adj = verbParser dict_IV_Adj
s1_T :: Parser (P T, Gender)
s1_T = nounParser dict_T
s1_CN :: Parser (P CN, Gender)
s1_CN = nounParser dict_CN
s1_IAV :: Parser (P IAV)
s1_IAV = dictParser dict_IAV
s1_t_t :: Parser (P (Sen :/ Sen))
s1_t_t = dictParser dict_t_t
s1_IAV_T :: Parser (P (IAV :/ T))
s1_IAV_T = dictParser dict_IAV_T
s1_Adj :: Parser (P Adj)
s1_Adj = dictParser dict_Adj
s1_Det :: Parser (P Det)
s1_Det = dictParser dict_Det
s1_PP_T :: Parser (P (PP :/ T))
s1_PP_T = dictParser dict_PP_T
s2 :: Parser (P T, Gender)
s2 =
do delta <- p_Det
-- w <- lookAhead
(zeta,g) <- p_CN
return (F2 delta zeta, g)
s3s :: Gender -> P CN -> Parser (P CN)
s3s g zeta = (s3_postfix g zeta >>= s3s g) <|> return zeta
s3_postfix :: Gender -> P CN -> Parser (P CN)
s3_postfix g zeta =
do token "such"
token "that"
n <- gensym
phi <- localS3 ((n,g):) p_t
guard $ IS.member n (fvs phi) -- XXX: He n が現れていることを検査。
noDanglingRef n -- nを参照している参照が残っていないことを保障
return (F3 n zeta phi)
s4_or_s17 :: Parser (P Sen)
s4_or_s17 =
do alpha <- p_T [Subject]
msum [ do delta <- p_IV (VFPresent True)
return (F4 alpha delta) -- 三人称単数現在形 (S4)
, do delta <- p_IV (VFPresent False)
return (F11 alpha delta) -- 三人称単数現在の否定形 (S17)
, do delta <- p_IV (VFFuture True)
return (F12 alpha delta) -- 三人称単数未来形 (S17)
, do delta <- p_IV (VFFuture False)
return (F13 alpha delta) -- 三人称単数未来の否定形 (S17)
, do delta <- p_IV (VFPerfect True)
return (F14 alpha delta) -- 三人称単数現在完了形 (S17)
, do delta <- p_IV (VFPerfect False)
return (F15 alpha delta) -- 三人称単数現在完了の否定形 (S17)
]
s5 :: VerbForm -> Parser (P IV)
s5 vf =
do delta <- p_TV vf
beta <- p_T [Object]
return (F5 delta beta)
s6 :: Parser (P IAV)
s6 =
do delta <- p_IAV_T
beta <- p_T [Object]
return (F5 delta beta)
s7 :: VerbForm -> Parser (P IV)
s7 vf =
do delta <- p_IV_t vf
token "that"
phi <- p_t
return (F16 delta phi)
s8 :: VerbForm -> Parser (P IV)
s8 vf =
do delta <- p_IV__IV vf
token "to"
beta <- p_IV VFOrig
return (F17 delta beta)
s9 :: Parser (P Sen)
s9 =
do delta <- p_t_t
beta <- p_t
return (F6 delta beta)
-- S10 は他のパーサの中に組み込んでしまっている
-- S11a, S11b, S12a, S12b, S13 は他のパーサの中に組み込んでしまっている
-- S14, S15, S16 は他のパーサの中に組み込んでしまっている
f8 :: F8 c => Parser (P c -> P c -> P c)
f8 = token "and" >> return F8
f9 :: F9 c => Parser (P c -> P c -> P c)
f9 = token "or" >> return F9
-- S17はS4のパーサの中に組み込んでしまっている
-- 講義資料でF9と書いてある???
s18 :: VerbForm -> Parser (P IV)
s18 vf =
do alpha <- p_IV_Adj vf
beta <- p_Adj
return (F6 alpha beta)
s19 :: VerbForm -> Parser (P IV)
s19 vf = liftM F19 (p_TV vf)
-- FIXME: S20とS21のどちらかはTTVでは?
-- S20の方か?
-- ???: x が DTV ならば、x to him は TV
s20 :: VerbForm -> Parser (P TV)
s20 vf =
do delta <- p_DTV vf
token "to"
beta <- p_T [Object]
return (F20 delta beta)
s21 :: VerbForm -> Parser (P TV)
s21 vf =
do delta <- p_DTV vf
beta <- p_T [Object]
return (F21 delta beta)
-- FIXME: この規則はどこからも使われていないけど良いのだろうか?
s22 :: VerbForm -> Parser (P TTV)
s22 vf = liftM F22 (p_DTV vf)
-- FIXME: αが-enならばというのは何を指している?
-- δ が been, rosen, eaten であること?
s23 :: VerbForm -> Parser (P IV)
s23 vf =
do verbParser' [verb_be] vf
delta <- p_TV VFPastParticiple
alpha <- p_PP
return (F23 alpha delta)
-- FIXME: αが-enならばというのは何を指している?
-- β≠he_n の間違いか?
s24 :: Parser (P PP)
s24 =
do alpha <- p_PP_T
beta <- p_T [Object]
return (F24 alpha beta)
s25 :: Parser (P Adj)
s25 =
do delta <- p_TV VFPastParticiple
return (F25 delta)
-----------------------------------------------------------------------------
-- He n で表される「自由変数」の集合
fvs :: P c -> IS.IntSet
fvs (B _ _) = IS.empty
fvs (He n) = IS.singleton n
fvs (F2 x y) = IS.union (fvs x) (fvs y)
fvs (F3 n x y) = IS.delete n $ IS.union (fvs x) (fvs y)
fvs (F4 x y) = IS.union (fvs x) (fvs y)
fvs (F5 x y) = IS.union (fvs x) (fvs y)
fvs (F6 x y) = IS.union (fvs x) (fvs y)
fvs (F7 x y) = IS.union (fvs x) (fvs y)
fvs (F8 x y) = IS.union (fvs x) (fvs y)
fvs (F9 x y) = IS.union (fvs x) (fvs y)
fvs (F10 n x y) = IS.delete n $ IS.union (fvs x) (fvs y)
fvs (F11 x y) = IS.union (fvs x) (fvs y)
fvs (F12 x y) = IS.union (fvs x) (fvs y)
fvs (F13 x y) = IS.union (fvs x) (fvs y)
fvs (F14 x y) = IS.union (fvs x) (fvs y)
fvs (F15 x y) = IS.union (fvs x) (fvs y)
fvs (F16 x y) = IS.union (fvs x) (fvs y)
fvs (F17 x y) = IS.union (fvs x) (fvs y)
fvs (F19 x) = fvs x
fvs (F20 x y) = IS.union (fvs x) (fvs y)
fvs (F21 x y) = IS.union (fvs x) (fvs y)
fvs (F22 x) = fvs x
fvs (F23 x y) = IS.union (fvs x) (fvs y)
fvs (F24 x y) = IS.union (fvs x) (fvs y)
fvs (F25 x) = fvs x
|
msakai/ptq
|
src/Parser.hs
|
lgpl-2.1
| 19,831 | 0 | 16 | 5,297 | 7,283 | 3,755 | 3,528 | 513 | 8 |
import Text.VCard.Format.Directory
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.ByteString.Lazy.Char8.Caseless as I
import Text.VCard.Format.Directory
import qualified Text.VCard.Query as Q
import Text.Regex.PCRE.ByteString.Lazy
import Control.Monad (when)
import System.IO
import System.IO.Unsafe
import System.Environment
import System.Exit
printUsage = putStrLn "mutt_vcard_query FILE PATTERN" >> exitFailure
(=~) :: Regex -> B.ByteString -> Bool
r =~ str = unsafePerformIO $
execute r str >>= return . either (error . snd) (maybe False (const True))
mkLine :: [I.ByteString] -> VCard -> B.ByteString
mkLine spec card =
B.intercalate "\t" $ map elim $ map (flip Q.lookup card) spec
where elim (Just [Text x]) = x
elim _ = ""
main = do
args <- getArgs
(filename, restr, handle)
<- case args of
[file,restr] -> openFile file ReadMode >>=
return . ((,,) file (B.pack restr))
_ -> printUsage
dirstr <- B.hGetContents handle
result <- compile compCaseless execBlank restr
let re = case result of Left (_, err) -> error err
Right re -> re
cards = readVCards filename dirstr
matches = Q.filterWithProperty query cards
query prop | prop @@ "fn", Text name <- prop_value prop,
re =~ name = True
| otherwise = False
when (null matches) $ putStrLn "No matches found." >> exitFailure
putStrLn $ "Entries: " ++ show (length cards) ++ " Matching: " ++ show (length matches)
let lines = map (mkLine ["email", "fn", "note"]) matches
mapM_ B.putStrLn lines
return exitSuccess
|
mboes/vCard
|
t/Mutt.hs
|
lgpl-3.0
| 1,671 | 0 | 16 | 407 | 583 | 301 | 282 | 41 | 3 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ms-MY">
<title>TLS Debug | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
secdec/zap-extensions
|
addOns/tlsdebug/src/main/javahelp/org/zaproxy/zap/extension/tlsdebug/resources/help_ms_MY/helpset_ms_MY.hs
|
apache-2.0
| 970 | 78 | 66 | 159 | 413 | 209 | 204 | -1 | -1 |
{-
Copyright 2018 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
-- |
-- Module : Data.MultiMap
-- Copyright : (c) CodeWorld Authors 2017
-- License : Apache-2.0
--
-- Maintainer : Joachim Breitner <[email protected]>
--
-- A simple MultiMap.
--
-- This differs from the one in the @multimap@ package by using
-- 'Data.Sequence.Seq' for efficient insert-at-end and other improved speeds.
--
-- Also only supports the operations required by CodeWorld for now.
{-# LANGUAGE TupleSections #-}
module Data.MultiMap
( MultiMap
, empty
, null
, insertL
, insertR
, toList
, spanAntitone
, union
, keys
) where
import Data.Bifunctor
import Data.Coerce
import qualified Data.Foldable (toList)
import qualified Data.Map as M
import qualified Data.Sequence as S
import Prelude hiding (null)
newtype MultiMap k v =
MM (M.Map k (S.Seq v))
deriving (Show, Eq)
empty :: MultiMap k v
empty = MM M.empty
null :: MultiMap k v -> Bool
null (MM m) = M.null m
insertL :: Ord k => k -> v -> MultiMap k v -> MultiMap k v
insertL k v (MM m) = MM (M.alter (Just . maybe (S.singleton v) (v S.<|)) k m)
insertR :: Ord k => k -> v -> MultiMap k v -> MultiMap k v
insertR k v (MM m) = MM (M.alter (Just . maybe (S.singleton v) (S.|> v)) k m)
toList :: MultiMap k v -> [(k, v)]
toList (MM m) = [(k, v) | (k, vs) <- M.toList m, v <- Data.Foldable.toList vs]
-- TODO: replace with M.spanAntitone once containers is updated
mapSpanAntitone :: (k -> Bool) -> M.Map k a -> (M.Map k a, M.Map k a)
mapSpanAntitone p =
bimap M.fromDistinctAscList M.fromDistinctAscList .
span (p . fst) . M.toList
spanAntitone :: (k -> Bool) -> MultiMap k v -> (MultiMap k v, MultiMap k v)
spanAntitone p (MM m) = coerce (mapSpanAntitone p m)
union :: Ord k => MultiMap k v -> MultiMap k v -> MultiMap k v
union (MM m1) (MM m2) = MM (M.unionWith (S.><) m1 m2)
keys :: MultiMap k v -> [k]
keys (MM m) = M.keys m
|
tgdavies/codeworld
|
codeworld-prediction/src/Data/MultiMap.hs
|
apache-2.0
| 2,493 | 0 | 13 | 538 | 718 | 384 | 334 | 40 | 1 |
import Data.List
import Data.Char
main = do line' <- fmap reverse getLine
putStrLn $ "You said " ++ line' ++ " backwords!"
-- fmap reverse will give "Just halb" from "Just Blah"
-- getLine gives IO String and mapping it to reverse IO gnirtS kind of :)-
main1 = do line' <- fmap (++ "!") getLine
putStrLn $ "You said " ++ line'
-- fmap does postfix "!" to everyline
--
main2 = do line' <- fmap (intersperse '-' . reverse . map toUpper ) getLine
putStrLn $ "You said (With beautification) : " ++ line'
--Two Functor laws
--fmap id = id
--fmap (f . g) = fmap f . fmap g
|
dongarerahul/lyah
|
chapter11-functorApplicativeMonad/IOFunctor.hs
|
apache-2.0
| 607 | 0 | 12 | 153 | 127 | 65 | 62 | 8 | 1 |
module Finance.Hqfl.Instrument.Cap
(
Cap
)where
data Cap
|
cokleisli/hqfl
|
src/Finance/Hqfl/Instrument/Cap.hs
|
apache-2.0
| 66 | 0 | 4 | 16 | 16 | 11 | 5 | -1 | -1 |
{-# LANGUAGE RankNTypes, FlexibleContexts, ScopedTypeVariables #-}
{- fixing resolution. This is a large beast of a module. Sorry.
updated for version 2.0.3 to match protoc's namespace resolution better
updated for version 2.0.4 to differentiate Entity and E'Entity, this makes eName a total selector
updated after version 2.0.5 to fix problem when package name was not specified in proto file.
main calls either runStandalone or runPlugin which call loadProto or loadStandalone which both call loadProto'
loadProto' uses getPackage to make packageName, loads the imports, and passes all this to makeTopLevel to get Env
The "load" loop in loadProto' caches the imported TopLevel based on _filename_
files can be loaded via multiple paths but this is not important
this may interact badly with absent "package" declarations that act as part of importing package
need these to be "polymorphic" in the packageID somehow?
Speculate: makeTopLevel knows the parent from the imports:
parent with explicit package could resolve "polymorphic" imports by a recursive transformation?
parent with no explicit package could do nothing.
root will need default explicit package name ? or special handling in loadProto' or load* ?
Then loadProto or loadStandalone both call run' which calls makeNameMaps with the Env from loadProto'
makeNameMaps calls makeNameMap on each top level fdp from each TopLevel in the Global Env from loadProto'
makeNameMap calls getPackage to form packageName, and unless overridden it is also used for hParent
makeNameMap on the imports gets called without any special knowledge of the "parent". If
root or some imports are still "polymorphic" then this is most annoying.
Alternative solution: a middle step after makeTopLevel and before makeNameMaps examines and fixes all the polymorphic imports.
The nameMap this computes is passed by run' to makeProtoInfo from MakeReflections
The bug is being reported by main>runStandalon>loadStandalone>loadProto'>makeTopLevel>resolveFDP>fqFileDP>fqMessage>fqField>resolvePredEnv
entityField uses resolveMGE instead of expectMGE and resolveEnv : this should allow field types to resolve just to MGE insteadof other field names.
what about keys 'extendee' resolution to Message names only? expectM in entityField
'makeTopLevel' is the main internal entry point in this module.
This is called from loadProto' which has two callers:
loadProto and loadCodeGenRequest
makeTopLevel uses a lazy 'myFixSE' trick and so the order of execution is not immediately clear.
The environment for name resolution comes from the global' declaration which first involves using
resolveFDP/runRE (E'Entity). To make things more complicated the definition of global' passes
global' to (resolveFDP fdp).
The resolveFDP/runRE runs all the fq* stuff (E'Entity and consumeUNO/interpretOption/resolveHere).
Note that the only source of E'Error values of E'Entity are from 'unique' detecting name
collisions.
This global' environment gets fed back in as global'Param to form the SEnv for running the
entityMsg, entityField, entityEnum, entityService functions. These clean up the parsed descriptor
proto structures into dependable and fully resolved ones.
The kids operator and the unZip are used to seprate and collect all the error messages, so that
they can be checked for and reported as a group.
====
Problem? Nesting namespaces allows shadowing. I forget if Google's protoc allows this.
Problem? When the current file being resolves has the same package name as an imported file then
hprotoc will find unqualified names in the local name space and the imported name space. But if
there is a name collision between the two then hprotoc will not detect this; the unqualified name
will resolve to the local file and not observe the duplicate from the import. TODO: check what
Google's protoc does in this case.
Solution to either of the above might be to resolve to a list of successes and check for a single
success. This may be too lazy.
====
aggregate option types not handled: Need to take fk and bytestring from parser and:
1) look at mVal of fk (E'Message) to understand what fields are expected (listed in mVals of this mVal).
2) lex the bytestring
3) parse the sequence of "name" ":" "value" by doing
4) find "name" in the expected list from (1) (E'Field)
5) Look at the fType of this E'Field and parse the "value", if Nothing (message/group/enum) then
6) resolve name and look at mVal
7) if enum then parse "value" as identifier or if message or group
8) recursively go to (1) and either prepend lenght (message) or append stop tag (group)
9) runPut to get the wire encoded field tag and value when Just a simple type
10) concatentanate the results of (3) to get the wire encoding for the message value
Handling recursive message/groups makes this more annoying.
-}
-- | This huge module handles the loading and name resolution. The
-- loadProto command recursively gets all the imported proto files.
-- The makeNameMaps command makes the translator from proto name to
-- Haskell name. Many possible errors in the proto data are caught
-- and reported by these operations.
--
-- hprotoc will actually resolve more unqualified imported names than Google's protoc which requires
-- more qualified names. I do not have the obsessive nature to fix this.
module Text.ProtocolBuffers.ProtoCompile.Resolve(loadProto,loadCodeGenRequest,makeNameMaps,getTLS,getPackageID
,Env(..),TopLevel(..),ReMap,NameMap(..),PackageID(..),LocalFP(..),CanonFP(..)) where
import qualified Text.DescriptorProtos.DescriptorProto as D(DescriptorProto)
import qualified Text.DescriptorProtos.DescriptorProto as D.DescriptorProto(DescriptorProto(..))
import qualified Text.DescriptorProtos.DescriptorProto.ExtensionRange as D(ExtensionRange(ExtensionRange))
import qualified Text.DescriptorProtos.DescriptorProto.ExtensionRange as D.ExtensionRange(ExtensionRange(..))
import qualified Text.DescriptorProtos.EnumDescriptorProto as D(EnumDescriptorProto(EnumDescriptorProto))
import qualified Text.DescriptorProtos.EnumDescriptorProto as D.EnumDescriptorProto(EnumDescriptorProto(..))
import qualified Text.DescriptorProtos.EnumValueDescriptorProto as D(EnumValueDescriptorProto)
import qualified Text.DescriptorProtos.EnumValueDescriptorProto as D.EnumValueDescriptorProto(EnumValueDescriptorProto(..))
import qualified Text.DescriptorProtos.FieldDescriptorProto as D(FieldDescriptorProto(FieldDescriptorProto))
import qualified Text.DescriptorProtos.FieldDescriptorProto as D.FieldDescriptorProto(FieldDescriptorProto(..))
import Text.DescriptorProtos.FieldDescriptorProto.Label
import qualified Text.DescriptorProtos.FieldDescriptorProto.Type as D(Type)
import Text.DescriptorProtos.FieldDescriptorProto.Type as D.Type(Type(..))
import qualified Text.DescriptorProtos.FileDescriptorProto as D(FileDescriptorProto)
import qualified Text.DescriptorProtos.FileDescriptorProto as D.FileDescriptorProto(FileDescriptorProto(..))
import qualified Text.DescriptorProtos.MethodDescriptorProto as D(MethodDescriptorProto)
import qualified Text.DescriptorProtos.MethodDescriptorProto as D.MethodDescriptorProto(MethodDescriptorProto(..))
import qualified Text.DescriptorProtos.ServiceDescriptorProto as D(ServiceDescriptorProto)
import qualified Text.DescriptorProtos.ServiceDescriptorProto as D.ServiceDescriptorProto(ServiceDescriptorProto(..))
import qualified Text.DescriptorProtos.UninterpretedOption as D(UninterpretedOption)
import qualified Text.DescriptorProtos.UninterpretedOption as D.UninterpretedOption(UninterpretedOption(..))
import qualified Text.DescriptorProtos.UninterpretedOption.NamePart as D(NamePart(NamePart))
import qualified Text.DescriptorProtos.UninterpretedOption.NamePart as D.NamePart(NamePart(..))
-- import qualified Text.DescriptorProtos.EnumOptions as D(EnumOptions)
import qualified Text.DescriptorProtos.EnumOptions as D.EnumOptions(EnumOptions(uninterpreted_option))
-- import qualified Text.DescriptorProtos.EnumValueOptions as D(EnumValueOptions)
import qualified Text.DescriptorProtos.EnumValueOptions as D.EnumValueOptions(EnumValueOptions(uninterpreted_option))
import qualified Text.DescriptorProtos.FieldOptions as D(FieldOptions(FieldOptions))
import qualified Text.DescriptorProtos.FieldOptions as D.FieldOptions(FieldOptions(packed,uninterpreted_option))
-- import qualified Text.DescriptorProtos.FileOptions as D(FileOptions)
import qualified Text.DescriptorProtos.FileOptions as D.FileOptions(FileOptions(..))
-- import qualified Text.DescriptorProtos.MessageOptions as D(MessageOptions)
import qualified Text.DescriptorProtos.MessageOptions as D.MessageOptions(MessageOptions(uninterpreted_option))
-- import qualified Text.DescriptorProtos.MethodOptions as D(MethodOptions)
import qualified Text.DescriptorProtos.MethodOptions as D.MethodOptions(MethodOptions(uninterpreted_option))
-- import qualified Text.DescriptorProtos.ServiceOptions as D(ServiceOptions)
import qualified Text.DescriptorProtos.ServiceOptions as D.ServiceOptions(ServiceOptions(uninterpreted_option))
import qualified Text.Google.Protobuf.Compiler.CodeGeneratorRequest as CGR
import Text.ProtocolBuffers.Header
import Text.ProtocolBuffers.Identifiers
import Text.ProtocolBuffers.Extensions
import Text.ProtocolBuffers.WireMessage
import Text.ProtocolBuffers.ProtoCompile.Instances
import Text.ProtocolBuffers.ProtoCompile.Parser
import Control.Applicative
import Control.Monad.Identity
import Control.Monad.State
import Control.Monad.Reader
import Control.Monad.Error
import Control.Monad.Writer
import Data.Char
import Data.Ratio
import Data.Ix(inRange)
import Data.List(foldl',stripPrefix,isPrefixOf,isSuffixOf)
import Data.Map(Map)
import Data.Maybe(mapMaybe)
import Data.Typeable
-- import Data.Monoid()
import System.Directory
import qualified System.FilePath as Local(pathSeparator,splitDirectories,joinPath,combine,makeRelative)
import qualified System.FilePath.Posix as Canon(pathSeparator,splitDirectories,joinPath,takeBaseName)
import qualified Data.ByteString.Lazy.Char8 as LC
import qualified Data.ByteString.Lazy.UTF8 as U
import qualified Data.Foldable as F
import qualified Data.Sequence as Seq
import qualified Data.Map as M
import qualified Data.Set as Set
import qualified Data.Traversable as T
--import Debug.Trace(trace)
-- Used by err and throw
indent :: String -> String
indent = unlines . map (\str -> ' ':' ':str) . lines
ishow :: Show a => a -> String
ishow = indent . show
errMsg :: String -> String
errMsg s = "Text.ProtocolBuffers.ProtoCompile.Resolve fatal error encountered, message:\n"++indent s
err :: forall b. String -> b
err = error . errMsg
throw :: (Error e, MonadError e m) => String -> m a
throw s = throwError (strMsg (errMsg s))
annErr :: (MonadError String m) => String -> m a -> m a
annErr s act = catchError act (\e -> throwError ("Text.ProtocolBuffers.ProtoCompile.Resolve annErr: "++s++'\n':indent e))
getJust :: (Error e,MonadError e m, Typeable a) => String -> Maybe a -> m a
{-# INLINE getJust #-}
getJust s ma@Nothing = throw $ "Impossible? Expected Just of type "++show (typeOf ma)++" but got nothing:\n"++indent s
getJust _s (Just a) = return a
defaultPackageName :: Utf8
defaultPackageName = Utf8 (LC.pack "defaultPackageName")
-- The "package" name turns out to be more complicated than I anticipated (when missing). Instead
-- of plain UTF8 annotate this with the PackageID newtype to force me to trace the usage. Later
-- change this to track the additional complexity.
--newtype PackageID a = PackageID { getPackageID :: a } deriving (Show)
data PackageID a = PackageID { _getPackageID :: a }
| NoPackageID { _getNoPackageID :: a }
deriving (Show)
instance Functor PackageID where
fmap f (PackageID a) = PackageID (f a)
fmap f (NoPackageID a) = NoPackageID (f a)
-- Used in MakeReflections.makeProtoInfo
getPackageID :: PackageID a -> a
getPackageID (PackageID a) = a
getPackageID (NoPackageID a) = a
-- The package field of FileDescriptorProto is set in Parser.hs.
-- 'getPackage' is the only direct user of this information in hprotoc.
-- The convertFileToPackage was developed looking at the Java output of Google's protoc.
-- In 2.0.5 this has lead to problems with the stricter import name resolution when the imported file has no package directive.
-- I need a fancier way of handling this.
getPackage :: D.FileDescriptorProto -> PackageID Utf8
getPackage fdp = case D.FileDescriptorProto.package fdp of
Just a -> PackageID a
Nothing -> case D.FileDescriptorProto.name fdp of
Nothing -> NoPackageID defaultPackageName
Just filename -> case convertFileToPackage filename of
Nothing -> NoPackageID defaultPackageName
Just name -> NoPackageID name
--getPackageUtf8 :: PackageID Utf8 -> Utf8
--getPackageUtf8 (PackageID {_getPackageID=x}) = x
--getPackageUtf8 (NoPackageID {_getNoPackageID=x}) = x
-- LOSES PackageID vs NoPackageID 2012-09-19
checkPackageID :: PackageID Utf8 -> Either String (PackageID (Bool,[IName Utf8]))
checkPackageID (PackageID a) = fmap PackageID (checkDIUtf8 a)
checkPackageID (NoPackageID a) = fmap NoPackageID (checkDIUtf8 a)
-- | 'convertFileToPackage' mimics what I observe protoc --java_out do to convert the file name to a
-- class name.
convertFileToPackage :: Utf8 -> Maybe Utf8
convertFileToPackage filename =
let full = toString filename
suffix = ".proto"
noproto = if suffix `isSuffixOf` full then take (length full - length suffix) full else full
convert :: Bool -> String -> String
convert _ [] = []
convert toUp (x:xs) | inRange ('a','z') x = if toUp
then toUpper x : convert False xs
else x : convert False xs
| inRange ('A','Z') x = x : convert False xs
| inRange ('0','9') x = x : convert True xs
| '_' == x = x : convert True xs
| otherwise = convert True xs
converted = convert True noproto
leading = case converted of
(x:_) | inRange ('0','9') x -> "proto_" ++ converted
_ -> converted
in if null leading then Nothing else (Just (fromString leading))
-- This adds a leading dot if the input is non-empty
joinDot :: [IName String] -> FIName String
joinDot [] = err $ "joinDot on an empty list of IName!"
joinDot (x:xs) = fqAppend (promoteFI x) xs
checkFI :: [(FieldId,FieldId)] -> FieldId -> Bool
checkFI ers fid = any (`inRange` fid) ers
getExtRanges :: D.DescriptorProto -> [(FieldId,FieldId)]
getExtRanges d = concatMap check unchecked
where check x@(lo,hi) | hi < lo = []
| hi<19000 || 19999<lo = [x]
| otherwise = concatMap check [(lo,18999),(20000,hi)]
unchecked = F.foldr ((:) . extToPair) [] (D.DescriptorProto.extension_range d)
extToPair (D.ExtensionRange
{ D.ExtensionRange.start = start
, D.ExtensionRange.end = end }) =
(maybe minBound FieldId start, maybe maxBound (FieldId . pred) end)
-- | By construction Env is 0 or more Local Entity namespaces followed
-- by 1 or more Global TopLevel namespaces (self and imported files).
-- Entities in first Global TopLevel namespace can refer to each other
-- and to Entities in the list of directly imported TopLevel namespaces only.
data Env = Local [IName String] EMap {- E'Message,E'Group,E'Service -} Env
| Global TopLevel [TopLevel]
deriving Show
-- | TopLevel corresponds to all items defined in a .proto file. This
-- includes the FileOptions since this will be consulted when
-- generating the Haskell module names, and the imported files are only
-- known through their TopLevel data.
data TopLevel = TopLevel { top'Path :: FilePath
, top'Package :: PackageID [IName String]
, top'FDP :: Either ErrStr D.FileDescriptorProto -- resolvedFDP'd
, top'mVals :: EMap } deriving Show
-- | The EMap type is a local namespace attached to an entity
--
-- The E'Error values come from using unique to resolse name collisions when building EMap
type EMap = Map (IName String) E'Entity
-- | An Entity is some concrete item in the namespace of a proto file.
-- All Entity values have a leading-dot fully-qualified with the package "eName".
-- The E'Message,Group,Service have EMap namespaces to inner Entity items.
data Entity = E'Message { eName :: [IName String], validExtensions :: [(FieldId,FieldId)]
, mVals :: EMap {- E'Message,Group,Field,Key,Enum -} }
| E'Group { eName :: [IName String], mVals :: EMap {- E'Message,Group,Field,Key,Enum -} }
| E'Service { eName :: [IName String], mVals :: EMap {- E'Method -} }
| E'Key { eName :: [IName String], eMsg :: Either ErrStr Entity {- E'Message -}
, fNumber :: FieldId, fType :: Maybe D.Type
, mVal :: Maybe (Either ErrStr Entity) {- E'Message,Group,Enum -} }
| E'Field { eName :: [IName String], fNumber :: FieldId, fType :: Maybe D.Type
, mVal :: Maybe (Either ErrStr Entity) {- E'Message,Group,Enum -} }
| E'Enum { eName :: [IName String], eVals :: Map (IName Utf8) Int32 }
| E'Method { eName :: [IName String], eMsgIn,eMsgOut :: Maybe (Either ErrStr Entity) {- E'Message -} }
deriving (Show)
-- This type handles entity errors by storing them rather than propagating or throwing them.
--
-- The E'Error values come from using unique to resolse name collisions when building EMap
data E'Entity = E'Ok Entity
| E'Error String [E'Entity]
deriving (Show)
newtype LocalFP = LocalFP { unLocalFP :: FilePath } deriving (Read,Show,Eq,Ord)
newtype CanonFP = CanonFP { unCanonFP :: FilePath } deriving (Read,Show,Eq,Ord)
fpLocalToCanon :: LocalFP -> CanonFP
fpLocalToCanon | Canon.pathSeparator == Local.pathSeparator = CanonFP . unLocalFP
| otherwise = CanonFP . Canon.joinPath . Local.splitDirectories . unLocalFP
fpCanonToLocal :: CanonFP -> LocalFP
fpCanonToLocal | Canon.pathSeparator == Local.pathSeparator = LocalFP . unCanonFP
| otherwise = LocalFP . Local.joinPath . Canon.splitDirectories . unCanonFP
-- Used to create optimal error messages
allowedGlobal :: Env -> [(PackageID [IName String],[IName String])]
allowedGlobal (Local _ _ env) = allowedGlobal env
allowedGlobal (Global t ts) = map allowedT (t:ts)
allowedT :: TopLevel -> (PackageID [IName String], [IName String])
allowedT tl = (top'Package tl,M.keys (top'mVals tl))
-- Used to create optional error messages
allowedLocal :: Env -> [([IName String],[IName String])]
allowedLocal (Global _t _ts) = []
allowedLocal (Local name vals env) = allowedE : allowedLocal env
where allowedE :: ([IName String], [IName String])
allowedE = (name,M.keys vals)
-- Create a mapping from the "official" name to the Haskell hierarchy mangled name
type ReMap = Map (FIName Utf8) ProtoName
data NameMap = NameMap ( PackageID (FIName Utf8) -- packageName from 'getPackage' on fdp
, [MName String] -- hPrefix from command line
, [MName String]) -- hParent from java_outer_classname, java_package, or 'getPackage'
ReMap
deriving (Show)
type RE a = ReaderT Env (Either ErrStr) a
data SEnv = SEnv { my'Parent :: [IName String] -- top level value is derived from PackageID
, my'Env :: Env }
-- , my'Template :: ProtoName }
-- E'Service here is arbitrary
emptyEntity :: Entity
emptyEntity = E'Service [IName "emptyEntity from myFix"] mempty
emptyEnv :: Env
emptyEnv = Global (TopLevel "emptyEnv from myFix" (PackageID [IName "emptyEnv form myFix"]) (Left "emptyEnv: top'FDP does not exist") mempty) []
instance Show SEnv where
show (SEnv p e) = "(SEnv "++show p++" ; "++ whereEnv e ++ ")" --" ; "++show (haskellPrefix t,parentModule t)++ " )"
type ErrStr = String
type SE a = ReaderT SEnv (Either ErrStr) a
runSE :: SEnv -> SE a -> Either ErrStr a
runSE sEnv m = runReaderT m sEnv
fqName :: Entity -> FIName Utf8
fqName = fiFromString . joinDot . eName
fiFromString :: FIName String -> FIName Utf8
fiFromString = FIName . fromString . fiName
iToString :: IName Utf8 -> IName String
iToString = IName . toString . iName
-- Three entities provide child namespaces: E'Message, E'Group, and E'Service
get'mVals'E :: E'Entity -> Maybe EMap
get'mVals'E (E'Ok entity) = get'mVals entity
get'mVals'E (E'Error {}) = Nothing
get'mVals :: Entity -> Maybe EMap
get'mVals (E'Message {mVals = x}) = Just x
get'mVals (E'Group {mVals = x}) = Just x
get'mVals (E'Service {mVals = x}) = Just x
get'mVals _ = Nothing
-- | This is a helper for resolveEnv
toGlobal :: Env -> Env
toGlobal (Local _ _ env) = toGlobal env
toGlobal x@(Global {}) = x
getTL :: Env -> TopLevel
getTL (Local _ _ env) = getTL env
getTL (Global tl _tls) = tl
getTLS :: Env -> (TopLevel,[TopLevel])
getTLS (Local _ _ env) = getTLS env
getTLS (Global tl tls) = (tl, tls)
-- | This is used for resolving some UninterpretedOption names
resolveHere :: Entity -> Utf8 -> RE Entity
resolveHere parent nameU = do
let rFail msg = throw ("Could not lookup "++show (toString nameU)++"\n"++indent msg)
x <- getJust ("resolveHere: validI nameU failed for "++show nameU) (fmap iToString (validI nameU))
case get'mVals parent of
Just vals -> case M.lookup x vals of
Just (E'Ok entity) -> return entity
Just (E'Error s _) -> rFail ("because the name resolved to an error:\n" ++ indent s)
Nothing -> rFail ("because there is no such name here: "++show (eName parent))
Nothing -> rFail ("because environment has no local names:\n"++ishow (eName parent))
-- | 'resolvePredEnv' is the query operation for the Env namespace. It recognizes names beginning
-- with a '.' as already being fully-qualified names. This is called from the different monads via
-- resolveEnv, resolveMGE, and resolveM
--
-- The returned (Right _::Entity) will never be an E'Error, which results in (Left _::ErrStr) instead
resolvePredEnv :: String -> (E'Entity -> Bool) -> Utf8 -> Env -> Either ErrStr Entity
resolvePredEnv userMessage accept nameU envIn = do
(isGlobal,xs) <- checkDIUtf8 nameU
let mResult = if isGlobal then lookupEnv (map iToString xs) (toGlobal envIn)
else lookupEnv (map iToString xs) envIn
case mResult of
Just (E'Ok e) -> return e
Just (E'Error s _es) -> throw s
Nothing -> throw . unlines $ [ "resolvePredEnv: Could not lookup " ++ show nameU
, "which parses as " ++ show (isGlobal,xs)
, "in environment: " ++ (whereEnv envIn)
, "looking for: " ++ userMessage
, "allowed (local): " ++ show (allowedLocal envIn)
, "allowed (global): " ++ show (allowedGlobal envIn) ]
where
lookupEnv :: [IName String] -> Env -> Maybe E'Entity
lookupEnv xs (Global tl tls) = let findThis = lookupTopLevel main xs
where main = top'Package tl
in msum (map findThis (tl:tls))
lookupEnv xs (Local _ vals env) = filteredLookup vals xs <|> lookupEnv xs env
lookupTopLevel :: PackageID [IName String] -> [IName String] -> TopLevel -> Maybe E'Entity
lookupTopLevel main xs tl =
(if matchesMain main (top'Package tl) then filteredLookup (top'mVals tl) xs else Nothing)
<|>
(matchPrefix (top'Package tl) xs >>= filteredLookup (top'mVals tl))
where matchesMain (PackageID {_getPackageID=a}) (PackageID {_getPackageID=b}) = a==b
matchesMain (NoPackageID {}) (PackageID {}) = False -- XXX XXX XXX 2012-09-19 suspicious
matchesMain (PackageID {}) (NoPackageID {}) = True
matchesMain (NoPackageID {}) (NoPackageID {}) = True
matchPrefix (NoPackageID {}) _ = Nothing
matchPrefix (PackageID {_getPackageID=a}) ys = stripPrefix a ys
filteredLookup valsIn namesIn =
let lookupVals :: EMap -> [IName String] -> Maybe E'Entity
lookupVals _vals [] = Nothing
lookupVals vals [x] = M.lookup x vals
lookupVals vals (x:xs) = do
entity <- M.lookup x vals
case get'mVals'E entity of
Just vals' -> lookupVals vals' xs
Nothing -> Nothing
m'x = lookupVals valsIn namesIn
in case m'x of
Just entity | accept entity -> m'x
_ -> Nothing
-- Used in resolveRE and getType.resolveSE. Accepts all types and so commits to first hit, but
-- caller may reject some types later.
resolveEnv :: Utf8 -> Env -> Either ErrStr Entity
resolveEnv = resolvePredEnv "Any item" (const True)
-- resolveRE is the often used workhorse of the fq* family of functions
resolveRE :: Utf8 -> RE Entity
resolveRE nameU = lift . (resolveEnv nameU) =<< ask
-- | 'getType' is used to lookup the type strings in service method records.
getType :: Show a => String -> (a -> Maybe Utf8) -> a -> SE (Maybe (Either ErrStr Entity))
getType s f a = do
typeU <- getJust s (f a)
case parseType (toString typeU) of
Just _ -> return Nothing
Nothing -> do ee <- resolveSE typeU
return (Just (expectMGE ee))
where
-- All uses of this then apply expectMGE or expectM, so provide predicate 'skip' support.
resolveSE :: Utf8 -> SE (Either ErrStr Entity)
resolveSE nameU = fmap (resolveEnv nameU) (asks my'Env)
-- | 'expectMGE' is used by getType and 'entityField'
expectMGE :: Either ErrStr Entity -> Either ErrStr Entity
expectMGE ee@(Left {}) = ee
expectMGE ee@(Right e) | isMGE = ee
| otherwise = throw $ "expectMGE: Name resolution failed to find a Message, Group, or Enum:\n"++ishow (eName e)
-- cannot show all of "e" because this will loop and hang the hprotoc program
where isMGE = case e of E'Message {} -> True
E'Group {} -> True
E'Enum {} -> True
_ -> False
-- | This is a helper for resolveEnv and (Show SEnv) for error messages
whereEnv :: Env -> String
whereEnv (Local name _ env) = fiName (joinDot name) ++ " in "++show (top'Path . getTL $ env)
-- WAS whereEnv (Global tl _) = fiName (joinDot (getPackageID (top'Package tl))) ++ " in " ++ show (top'Path tl)
whereEnv (Global tl _) = formatPackageID ++ " in " ++ show (top'Path tl)
where formatPackageID = case top'Package tl of
PackageID {_getPackageID=x} -> fiName (joinDot x)
NoPackageID {_getNoPackageID=y} -> show y
-- | 'partEither' separates the Left errors and Right success in the obvious way.
partEither :: [Either a b] -> ([a],[b])
partEither [] = ([],[])
partEither (Left a:xs) = let ~(ls,rs) = partEither xs
in (a:ls,rs)
partEither (Right b:xs) = let ~(ls,rs) = partEither xs
in (ls,b:rs)
-- | The 'unique' function is used with Data.Map.fromListWithKey to detect
-- name collisions and record this as E'Error entries in the map.
--
-- This constructs new E'Error values
unique :: IName String -> E'Entity -> E'Entity -> E'Entity
unique name (E'Error _ a) (E'Error _ b) = E'Error ("Namespace collision for "++show name) (a++b)
unique name (E'Error _ a) b = E'Error ("Namespace collision for "++show name) (a++[b])
unique name a (E'Error _ b) = E'Error ("Namespace collision for "++show name) (a:b)
unique name a b = E'Error ("Namespace collision for "++show name) [a,b]
maybeM :: Monad m => (x -> m a) -> (Maybe x) -> m (Maybe a)
maybeM f mx = maybe (return Nothing) (liftM Just . f) mx
-- ReaderT containing template stacked on WriterT of list of name translations stacked on error reporting
type MRM a = ReaderT ProtoName (WriterT [(FIName Utf8,ProtoName)] (Either ErrStr)) a
runMRM'Reader :: MRM a -> ProtoName -> WriterT [(FIName Utf8,ProtoName)] (Either ErrStr) a
runMRM'Reader = runReaderT
runMRM'Writer :: WriterT [(FIName Utf8,ProtoName)] (Either ErrStr) a -> Either ErrStr (a,[(FIName Utf8,ProtoName)])
runMRM'Writer = runWriterT
mrmName :: String -> (a -> Maybe Utf8) -> a -> MRM ProtoName
mrmName s f a = do
template <- ask
iSelf <- getJust s (validI =<< f a)
let mSelf = mangle iSelf
fqSelf = fqAppend (protobufName template) [iSelf]
self = template { protobufName = fqSelf
, baseName = mSelf }
template' = template { protobufName = fqSelf
, parentModule = parentModule template ++ [mSelf] }
tell [(fqSelf,self)]
return template'
-- Compute the nameMap that determine how to translate from proto names to haskell names
-- The loop oever makeNameMap uses the (optional) package name
-- makeNameMaps is called from the run' routine in ProtoCompile.hs for both standalone and plugin use.
-- hPrefix and hAs are command line controlled options.
-- hPrefix is "-p MODULE --prefix=MODULE dotted Haskell MODULE name to use as a prefix (default is none); last flag used"
-- hAs is "-a FILEPATH=MODULE --as=FILEPATH=MODULE assign prefix module to imported prot file: --as descriptor.proto=Text"
-- Note that 'setAs' puts both the full path and the basename as keys into the association list
makeNameMaps :: [MName String] -> [(CanonFP,[MName String])] -> Env -> Either ErrStr NameMap
makeNameMaps hPrefix hAs env = do
let getPrefix fdp =
case D.FileDescriptorProto.name fdp of
Nothing -> hPrefix -- really likely to be an error elsewhere since this ought to be a filename
Just n -> let path = CanonFP (toString n)
in case lookup path hAs of
Just p -> p
Nothing -> case lookup (CanonFP . Canon.takeBaseName . unCanonFP $ path) hAs of
Just p -> p
Nothing -> hPrefix -- this is the usual branch unless overridden on command line
let (tl,tls) = getTLS env
(fdp:fdps) <- mapM top'FDP (tl:tls)
(NameMap tuple m) <- makeNameMap (getPrefix fdp) fdp
let f (NameMap _ x) = x
ms <- fmap (map f) . mapM (\y -> makeNameMap (getPrefix y) y) $ fdps
let nameMap = (NameMap tuple (M.unions (m:ms)))
-- trace (show nameMap) $
return nameMap
-- | 'makeNameMap' conservatively checks its input.
makeNameMap :: [MName String] -> D.FileDescriptorProto -> Either ErrStr NameMap
makeNameMap hPrefix fdpIn = go (makeOne fdpIn) where
go = fmap ((\(a,w) -> NameMap a (M.fromList w))) . runMRM'Writer
makeOne fdp = do
-- Create 'template' :: ProtoName using "Text.ProtocolBuffers.Identifiers" with error for baseName
let rawPackage = getPackage fdp :: PackageID Utf8
_ <- lift (checkPackageID rawPackage) -- guard-like effect
{-
-- Previously patched way of doing this
let packageName = case D.FileDescriptorProto.package fdp of
Nothing -> FIName $ fromString ""
Just p -> difi $ DIName p
-}
let packageName :: PackageID (FIName Utf8)
packageName = fmap (difi . DIName) rawPackage
fi'package'name = getPackageID packageName
rawParent <- getJust "makeNameMap.makeOne: impossible Nothing found" . msum $
[ D.FileOptions.java_outer_classname =<< (D.FileDescriptorProto.options fdp)
, D.FileOptions.java_package =<< (D.FileDescriptorProto.options fdp)
, Just (getPackageID rawPackage)]
diParent <- getJust ("makeNameMap.makeOne: invalid character in: "++show rawParent)
(validDI rawParent)
let hParent = map (mangle :: IName Utf8 -> MName String) . splitDI $ diParent
template = ProtoName fi'package'name hPrefix hParent
(error "makeNameMap.makeOne.template.baseName undefined")
runMRM'Reader (mrmFile fdp) template
return (packageName,hPrefix,hParent)
-- Traversal of the named DescriptorProto types
mrmFile :: D.FileDescriptorProto -> MRM ()
mrmFile fdp = do
F.mapM_ mrmMsg (D.FileDescriptorProto.message_type fdp)
F.mapM_ mrmField (D.FileDescriptorProto.extension fdp)
F.mapM_ mrmEnum (D.FileDescriptorProto.enum_type fdp)
F.mapM_ mrmService (D.FileDescriptorProto.service fdp)
mrmMsg dp = do
template <- mrmName "mrmMsg.name" D.DescriptorProto.name dp
local (const template) $ do
F.mapM_ mrmEnum (D.DescriptorProto.enum_type dp)
F.mapM_ mrmField (D.DescriptorProto.extension dp)
F.mapM_ mrmField (D.DescriptorProto.field dp)
F.mapM_ mrmMsg (D.DescriptorProto.nested_type dp)
mrmField fdp = mrmName "mrmField.name" D.FieldDescriptorProto.name fdp
mrmEnum edp = do
template <- mrmName "mrmEnum.name" D.EnumDescriptorProto.name edp
local (const template) $ F.mapM_ mrmEnumValue (D.EnumDescriptorProto.value edp)
mrmEnumValue evdp = mrmName "mrmEnumValue.name" D.EnumValueDescriptorProto.name evdp
mrmService sdp = do
template <- mrmName "mrmService.name" D.ServiceDescriptorProto.name sdp
local (const template) $ F.mapM_ mrmMethod (D.ServiceDescriptorProto.method sdp)
mrmMethod mdp = mrmName "mrmMethod.name" D.MethodDescriptorProto.name mdp
getNames :: String -> (a -> Maybe Utf8) -> a -> SE (IName String,[IName String])
getNames errorMessage accessor record = do
parent <- asks my'Parent
iSelf <- fmap iToString $ getJust errorMessage (validI =<< accessor record)
let names = parent ++ [ iSelf ]
return (iSelf,names)
descend :: [IName String] -> Entity -> SE a -> SE a
descend names entity act = local mutate act
where mutate (SEnv _parent env) = SEnv parent' env'
where parent' = names -- cannot call eName ename, will cause <<loop>> with "getNames" -- XXX revisit
env' = Local (eName entity) (mVals entity) env
-- Run each element of (Seq x) as (f x) with same initial environment and state.
-- Then merge the output states and sort out the failures and successes.
kids :: (x -> SE (IName String,E'Entity)) -> Seq x -> SE ([ErrStr],[(IName String,E'Entity)])
kids f xs = do sEnv <- ask
let ans = map (runSE sEnv) . map f . F.toList $ xs
return (partEither ans)
-- | 'makeTopLevel' takes a .proto file's FileDescriptorProto and the TopLevel values of its
-- directly imported file and constructs the TopLevel of the FileDescriptorProto in a Global
-- Environment.
--
-- This goes to some lengths to be a total function with good error messages. Errors in building
-- the skeleton of the namespace are detected and reported instead of returning the new 'Global'
-- environment. Collisions in the namespace are only detected when the offending name is looked up,
-- and will return an E'Error entity with a message and list of colliding Entity items. The
-- cross-linking of Entity fields may fail and this failure is stored in the corresponding Entity.
--
-- Also caught: name collisions in Enum definitions.
--
-- The 'mdo' usage has been replace by modified forms of 'mfix' that will generate useful error
-- values instead of calling 'error' and halting 'hprotoc'.
--
-- Used from loadProto'
makeTopLevel :: D.FileDescriptorProto -> PackageID [IName String] -> [TopLevel] -> Either ErrStr Env {- Global -}
makeTopLevel fdp packageName imports = do
filePath <- getJust "makeTopLevel.filePath" (D.FileDescriptorProto.name fdp)
let -- There should be no TYPE_GROUP in the extension list here, but to be safe:
isGroup = (`elem` groupNames) where
groupNamesRaw = map toString . mapMaybe D.FieldDescriptorProto.type_name
. filter (maybe False (TYPE_GROUP ==) . D.FieldDescriptorProto.type')
$ (F.toList . D.FileDescriptorProto.extension $ fdp)
groupNamesI = mapMaybe validI groupNamesRaw
groupNamesDI = mapMaybe validDI groupNamesRaw -- These fully qualified names from using hprotoc as a plugin for protoc
groupNames = groupNamesI ++ map (last . splitDI) groupNamesDI
(bad,global) <- myFixE ("makeTopLevel myFixE",emptyEnv) $ \ global'Param ->
let sEnv = SEnv (get'SEnv'root'from'PackageID packageName) global'Param
in runSE sEnv $ do
(bads,children) <- fmap unzip . sequence $
[ kids (entityMsg isGroup) (D.FileDescriptorProto.message_type fdp)
, kids (entityField True) (D.FileDescriptorProto.extension fdp)
, kids entityEnum (D.FileDescriptorProto.enum_type fdp)
, kids entityService (D.FileDescriptorProto.service fdp) ]
let bad' = unlines (concat bads)
global' = Global (TopLevel (toString filePath)
packageName
(resolveFDP fdp global')
(M.fromListWithKey unique (concat children)))
imports
return (bad',global')
-- Moving this outside the myFixE reduces the cases where myFixE generates an 'error' call.
when (not (null bad)) $
throw $ "makeTopLevel.bad: Some children failed for "++show filePath++"\n"++bad
return global
where resolveFDP :: D.FileDescriptorProto -> Env -> Either ErrStr D.FileDescriptorProto
resolveFDP fdpIn env = runRE env (fqFileDP fdpIn)
where runRE :: Env -> RE D.FileDescriptorProto -> Either ErrStr D.FileDescriptorProto
runRE envIn m = runReaderT m envIn
-- Used from makeTopLevel, from loadProto'
get'SEnv'root'from'PackageID :: PackageID [IName String] -> [IName String]
get'SEnv'root'from'PackageID = getPackageID -- was mPackageID before 2012-09-19
-- where
-- Used from get'SEnv makeTopLevel, from loadProto'
-- mPackageID :: Monoid a => PackageID a -> a
-- mPackageID (PackageID {_getPackageID=x}) = x
-- mPackageID (NoPackageID {}) = mempty
-- Copies of mFix for use the string in (Left msg) for the error message.
-- Note that the usual mfix for Either calls 'error' while this does not,
-- it uses a default value passed to myFix*.
myFixSE :: (String,a) -> (a -> SE (String,a)) -> SE (String,a)
myFixSE s f = ReaderT $ \r -> myFixE s (\a -> runReaderT (f a) r)
-- Note that f ignores the fst argument
myFixE :: (String,a) -> (a -> Either ErrStr (String,a)) -> Either ErrStr (String,a)
myFixE s f = let a = f (unRight a) in a
where unRight (Right x) = snd x
unRight (Left _msg) = snd s
-- ( "Text.ProtocolBuffers.ProtoCompile.Resolve: "++fst s ++":\n" ++ indent msg
-- , snd s)
{- ***
All the entity* functions are used by makeTopLevel and each other.
If there is no error then these return (IName String,E'Entity) and this E'Entity is always E'Ok.
*** -}
-- Fix this to look at groupNamesDI as well as the original list of groupNamesI. This fixes a bug
-- in the plug-in usage because protoc will have already resolved the type_name to a fully qualified
-- name.
entityMsg :: (IName String -> Bool) -> D.DescriptorProto -> SE (IName String,E'Entity)
entityMsg isGroup dp = annErr ("entityMsg DescriptorProto name is "++show (D.DescriptorProto.name dp)) $ do
(self,names) <- getNames "entityMsg.name" D.DescriptorProto.name dp
numbers <- fmap Set.fromList . mapM (getJust "entityMsg.field.number" . D.FieldDescriptorProto.number) . F.toList . D.DescriptorProto.field $ dp
when (Set.size numbers /= Seq.length (D.DescriptorProto.field dp)) $
throwError $ "entityMsg.field.number: There must be duplicate field numbers for "++show names++"\n "++show numbers
let groupNamesRaw = map toString . mapMaybe D.FieldDescriptorProto.type_name
. filter (maybe False (TYPE_GROUP ==) . D.FieldDescriptorProto.type')
$ (F.toList . D.DescriptorProto.field $ dp) ++ (F.toList . D.DescriptorProto.extension $ dp)
groupNamesI = mapMaybe validI groupNamesRaw
groupNamesDI = mapMaybe validDI groupNamesRaw -- These fully qualified names from using hprotoc as a plugin for protoc
groupNames = groupNamesI ++ map (last . splitDI) groupNamesDI
isGroup' = (`elem` groupNames)
(bad,entity) <- myFixSE ("myFixSE entityMsg",emptyEntity) $ \ entity'Param -> descend names entity'Param $ do
(bads,children) <- fmap unzip . sequence $
[ kids entityEnum (D.DescriptorProto.enum_type dp)
, kids (entityField True) (D.DescriptorProto.extension dp)
, kids (entityField False) (D.DescriptorProto.field dp)
, kids (entityMsg isGroup') (D.DescriptorProto.nested_type dp) ]
let bad' = unlines (concat bads)
entity' | isGroup self = E'Group names (M.fromListWithKey unique (concat children))
| otherwise = E'Message names (getExtRanges dp) (M.fromListWithKey unique (concat children))
return (bad',entity')
-- Moving this outside the myFixSE reduces the cases where myFixSE uses the error-default call.
when (not (null bad)) $
throwError $ "entityMsg.bad: Some children failed for "++show names++"\n"++bad
return (self,E'Ok $ entity)
-- Among other things, this is where ambiguous type names in the proto file are resolved into a
-- Message or a Group or an Enum.
entityField :: Bool -> D.FieldDescriptorProto -> SE (IName String,E'Entity)
entityField isKey fdp = annErr ("entityField FieldDescriptorProto name is "++show (D.FieldDescriptorProto.name fdp)) $ do
(self,names) <- getNames "entityField.name" D.FieldDescriptorProto.name fdp
let isKey' = maybe False (const True) (D.FieldDescriptorProto.extendee fdp)
when (isKey/=isKey') $
throwError $ "entityField: Impossible? Expected key and got field or vice-versa:\n"++ishow ((isKey,isKey'),names,fdp)
number <- getJust "entityField.name" . D.FieldDescriptorProto.number $ fdp
let mType = D.FieldDescriptorProto.type' fdp
typeName <- maybeM resolveMGE (D.FieldDescriptorProto.type_name fdp)
if isKey
then do
extendee <- resolveM =<< getJust "entityField.extendee" (D.FieldDescriptorProto.extendee fdp)
return (self,E'Ok $ E'Key names extendee (FieldId number) mType typeName)
else
return (self,E'Ok $ E'Field names (FieldId number) mType typeName)
where
resolveMGE :: Utf8 -> SE (Either ErrStr Entity)
resolveMGE nameU = fmap (resolvePredEnv "Message or Group or Enum" isMGE nameU) (asks my'Env)
where isMGE (E'Ok e') = case e' of E'Message {} -> True
E'Group {} -> True
E'Enum {} -> True
_ -> False
isMGE (E'Error {}) = False
-- To be used for key extendee name resolution, but not part of the official protobuf-2.1.0 update, since made official
resolveM :: Utf8 -> SE (Either ErrStr Entity)
resolveM nameU = fmap (resolvePredEnv "Message" isM nameU) (asks my'Env)
where isM (E'Ok e') = case e' of E'Message {} -> True
_ -> False
isM (E'Error {}) = False
entityEnum :: D.EnumDescriptorProto -> SE (IName String,E'Entity)
entityEnum edp@(D.EnumDescriptorProto {D.EnumDescriptorProto.value=vs}) = do
(self,names) <- getNames "entityEnum.name" D.EnumDescriptorProto.name edp
values <- mapM (getJust "entityEnum.value.number" . D.EnumValueDescriptorProto.number) . F.toList $ vs
{- Cannot match protoc if I enable this as a fatal check here
when (Set.size (Set.fromList values) /= Seq.length vs) $
throwError $ "entityEnum.value.number: There must be duplicate enum values for "++show names++"\n "++show values
-}
justNames <- mapM (\v -> getJust ("entityEnum.value.name failed for "++show v) (D.EnumValueDescriptorProto.name v))
. F.toList $ vs
valNames <- mapM (\n -> getJust ("validI of entityEnum.value.name failed for "++show n) (validI n)) justNames
let mapping = M.fromList (zip valNames values)
when (M.size mapping /= Seq.length vs) $
throwError $ "entityEnum.value.name: There must be duplicate enum names for "++show names++"\n "++show valNames
descend'Enum names $ F.mapM_ entityEnumValue vs
return (self,E'Ok $ E'Enum names mapping) -- discard values
where entityEnumValue :: D.EnumValueDescriptorProto -> SE ()
entityEnumValue evdp = do -- Merely use getNames to add mangled self to ReMap state
_ <- getNames "entityEnumValue.name" D.EnumValueDescriptorProto.name evdp
return ()
descend'Enum :: [IName String] -> SE a -> SE a
descend'Enum names act = local mutate act
where mutate (SEnv _parent env) = SEnv names env
entityService :: D.ServiceDescriptorProto -> SE (IName String,E'Entity)
entityService sdp = annErr ("entityService ServiceDescriptorProto name is "++show (D.ServiceDescriptorProto.name sdp)) $ do
(self,names) <- getNames "entityService.name" D.ServiceDescriptorProto.name sdp
(bad,entity) <- myFixSE ("myFixSE entityService",emptyEntity) $ \ entity'Param ->
descend names entity'Param $ do
(badMethods',goodMethods) <- kids entityMethod (D.ServiceDescriptorProto.method sdp)
let bad' = unlines badMethods'
entity' = E'Service names (M.fromListWithKey unique goodMethods)
return (bad',entity')
-- Moving this outside the myFixSE reduces the cases where myFixSE generates an 'error' call.
when (not (null bad)) $
throwError $ "entityService.badMethods: Some methods failed for "++show names++"\n"++bad
return (self,E'Ok entity)
entityMethod :: D.MethodDescriptorProto -> SE (IName String,E'Entity)
entityMethod mdp = do
(self,names) <- getNames "entityMethod.name" D.MethodDescriptorProto.name mdp
inputType <- getType "entityMethod.input_type" D.MethodDescriptorProto.input_type mdp
outputType <- getType "entityMethod.output_type" D.MethodDescriptorProto.output_type mdp
return (self,E'Ok $ E'Method names inputType outputType)
{- ***
The namespace Env is used to transform the original FileDescriptorProto into a canonical
FileDescriptorProto. The goal is to match the transformation done by Google's protoc program. This
will allow the "front end" vs "back end" of each program to cross-couple, which will at least allow
better testing of hprotoc and the new UninterpretedOption support.
The UninterpretedOption fields are converted by the resolveFDP code below.
These should be total functions with no 'error' or 'undefined' values possible.
*** -}
fqFail :: Show a => String -> a -> Entity -> RE b
fqFail msg dp entity = do
env <- ask
throw $ unlines [ msg, "resolving: "++show dp, "in environment: "++whereEnv env, "found: "++show (eName entity) ]
fqFileDP :: D.FileDescriptorProto -> RE D.FileDescriptorProto
fqFileDP fdp = annErr ("fqFileDP FileDescriptorProto (name,package) is "++show (D.FileDescriptorProto.name fdp,D.FileDescriptorProto.package fdp)) $ do
newMessages <- T.mapM fqMessage (D.FileDescriptorProto.message_type fdp)
newEnums <- T.mapM fqEnum (D.FileDescriptorProto.enum_type fdp)
newServices <- T.mapM fqService (D.FileDescriptorProto.service fdp)
newKeys <- T.mapM (fqField True) (D.FileDescriptorProto.extension fdp)
consumeUNO $ fdp { D.FileDescriptorProto.message_type = newMessages
, D.FileDescriptorProto.enum_type = newEnums
, D.FileDescriptorProto.service = newServices
, D.FileDescriptorProto.extension = newKeys }
fqMessage :: D.DescriptorProto -> RE D.DescriptorProto
fqMessage dp = annErr ("fqMessage DescriptorProto name is "++show (D.DescriptorProto.name dp)) $ do
entity <- resolveRE =<< getJust "fqMessage.name" (D.DescriptorProto.name dp)
(name,vals) <- case entity of
E'Message {eName=name',mVals=vals'} -> return (name',vals')
E'Group {eName=name',mVals=vals'} -> return (name',vals')
_ -> fqFail "fqMessage.entity: did not resolve to an E'Message or E'Group:" dp entity
local (\env -> (Local name vals env)) $ do
newFields <- T.mapM (fqField False) (D.DescriptorProto.field dp)
newKeys <- T.mapM (fqField True) (D.DescriptorProto.extension dp)
newMessages <- T.mapM fqMessage (D.DescriptorProto.nested_type dp)
newEnums <- T.mapM fqEnum (D.DescriptorProto.enum_type dp)
consumeUNO $ dp { D.DescriptorProto.field = newFields
, D.DescriptorProto.extension = newKeys
, D.DescriptorProto.nested_type = newMessages
, D.DescriptorProto.enum_type = newEnums }
fqService :: D.ServiceDescriptorProto -> RE D.ServiceDescriptorProto
fqService sdp = annErr ("fqService ServiceDescriptorProto name is "++show (D.ServiceDescriptorProto.name sdp)) $ do
entity <- resolveRE =<< getJust "fqService.name" (D.ServiceDescriptorProto.name sdp)
case entity of
E'Service {eName=name,mVals=vals} -> do
newMethods <- local (Local name vals) $ T.mapM fqMethod (D.ServiceDescriptorProto.method sdp)
consumeUNO $ sdp { D.ServiceDescriptorProto.method = newMethods }
_ -> fqFail "fqService.entity: did not resolve to a service:" sdp entity
fqMethod :: D.MethodDescriptorProto -> RE D.MethodDescriptorProto
fqMethod mdp = do
entity <- resolveRE =<< getJust "fqMethod.name" (D.MethodDescriptorProto.name mdp)
case entity of
E'Method {eMsgIn=msgIn,eMsgOut=msgOut} -> do
mdp1 <- case msgIn of
Nothing -> return mdp
Just resolveIn -> do
new <- fmap fqName (lift resolveIn)
return (mdp {D.MethodDescriptorProto.input_type = Just (fiName new)})
mdp2 <- case msgOut of
Nothing -> return mdp1
Just resolveIn -> do
new <- fmap fqName (lift resolveIn)
return (mdp1 {D.MethodDescriptorProto.output_type = Just (fiName new)})
consumeUNO mdp2
_ -> fqFail "fqMethod.entity: did not resolve to a Method:" mdp entity
-- The field is a bit more complicated to resolve. The Key variant needs to resolve the extendee.
-- The type code from Parser.hs might be Nothing and this needs to be resolved to TYPE_MESSAGE or
-- TYPE_ENUM (at last!), and if it is the latter then any default value string is checked for
-- validity.
fqField :: Bool -> D.FieldDescriptorProto -> RE D.FieldDescriptorProto
fqField isKey fdp = annErr ("fqField FieldDescriptorProto name is "++show (D.FieldDescriptorProto.name fdp)) $ do
let isKey' = maybe False (const True) (D.FieldDescriptorProto.extendee fdp)
when (isKey/=isKey') $
ask >>= \env -> throwError $ "fqField.isKey: Expected key and got field or vice-versa:\n"++ishow ((isKey,isKey'),whereEnv env,fdp)
entity <- expectFK =<< resolveRE =<< getJust "fqField.name" (D.FieldDescriptorProto.name fdp)
newExtendee <- case (isKey,entity) of
(True,E'Key {eMsg=msg,fNumber=fNum}) -> do
ext <- lift msg
case ext of
E'Message {} -> when (not (checkFI (validExtensions ext) fNum)) $
throwError $ "fqField.newExtendee: Field Number of extention key invalid:\n"
++unlines ["Number is "++show (fNumber entity)
,"Valid ranges: "++show (validExtensions ext)
,"Extendee: "++show (eName ext)
,"Descriptor: "++show fdp]
_ -> fqFail "fqField.ext: Key's target is not an E'Message:" fdp ext
fmap (Just . fiName . fqName) . lift . eMsg $ entity
(False,E'Field {}) -> return Nothing
_ -> fqFail "fqField.entity: did not resolve to expected E'Key or E'Field:" fdp entity
mTypeName <- maybeM lift (mVal entity) -- "Just (Left _)" triggers a throwError here (see comment for entityField)
-- Finally fully determine D.Type, (type'==Nothing) meant ambiguously TYPE_MESSAGE or TYPE_ENUM from Parser.hs
-- This has gotten more verbose with the addition of verifying packed is being used properly.
actualType <- case (fType entity,mTypeName) of
(Just TYPE_GROUP, Just (E'Group {})) | isNotPacked fdp -> return TYPE_GROUP
| otherwise ->
fqFail ("fqField.actualType : This Group is invalid, you cannot pack a group field.") fdp entity
(Nothing, Just (E'Message {})) | isNotPacked fdp -> return TYPE_MESSAGE
| otherwise ->
fqFail ("fqField.actualType : This Message is invalid, you cannot pack a message field.") fdp entity
(Nothing, Just (E'Enum {})) | isNotPacked fdp -> return TYPE_ENUM
| isRepeated fdp -> return TYPE_ENUM
| otherwise ->
fqFail ("fqField.actualType : This Enum is invalid, you cannot pack a non-repeated field.") fdp entity
(Just t, Nothing) -> return t
(Just TYPE_MESSAGE, Just (E'Message {})) -> return TYPE_MESSAGE
(Just TYPE_ENUM, Just (E'Enum {})) -> return TYPE_ENUM
(mt,me) -> fqFail ("fqField.actualType: "++show mt++" and "++show (fmap eName me)++" is invalid.") fdp entity
-- Check that a default value of an TYPE_ENUM is valid
case (mTypeName,D.FieldDescriptorProto.default_value fdp) of
(Just ee@(E'Enum {eVals = enumVals}),Just enumVal) ->
let badVal = throwError $ "fqField.default_value: Default enum value is invalid:\n"
++unlines ["Value is "++show (toString enumVal)
,"Allowed values from "++show (eName ee)
," are "++show (M.keys enumVals)
,"Descriptor: "++show fdp]
in case validI enumVal of
Nothing -> badVal
Just iVal -> when (M.notMember iVal enumVals) badVal
_ -> return ()
consumeUNO $
if isKey then (fdp { D.FieldDescriptorProto.extendee = newExtendee
, D.FieldDescriptorProto.type' = Just actualType
, D.FieldDescriptorProto.type_name = fmap (fiName . fqName) mTypeName })
else (fdp { D.FieldDescriptorProto.type' = Just actualType
, D.FieldDescriptorProto.type_name = fmap (fiName . fqName) mTypeName })
where isRepeated :: D.FieldDescriptorProto -> Bool
isRepeated (D.FieldDescriptorProto {
D.FieldDescriptorProto.label =
Just LABEL_REPEATED }) =
True
isRepeated _ = False
isNotPacked :: D.FieldDescriptorProto -> Bool
isNotPacked (D.FieldDescriptorProto {
D.FieldDescriptorProto.options =
Just (D.FieldOptions {
D.FieldOptions.packed =
Just isPacked })}) =
not isPacked
isNotPacked _ = True
expectFK :: Entity -> RE Entity
expectFK e | isFK = return e
| otherwise = throwError $ "expectF: Name resolution failed to find a Field or Key:\n"++ishow (eName e)
where isFK = case e of E'Field {} -> True
E'Key {} -> True
_ -> False
fqEnum :: D.EnumDescriptorProto -> RE D.EnumDescriptorProto
fqEnum edp = do
entity <- resolveRE =<< getJust "fqEnum.name" (D.EnumDescriptorProto.name edp)
case entity of
E'Enum {} -> do evdps <- T.mapM consumeUNO (D.EnumDescriptorProto.value edp)
consumeUNO $ edp { D.EnumDescriptorProto.value = evdps }
_ -> fqFail "fqEnum.entity: did not resolve to an E'Enum:" edp entity
{- The consumeUNO calls above hide this cut-and-pasted boilerplate between interpretOptions and the DescriptorProto type -}
class ConsumeUNO a where consumeUNO :: a -> RE a
instance ConsumeUNO D.EnumDescriptorProto where
consumeUNO a = maybe (return a) (processOpt >=> \o -> return $ a { D.EnumDescriptorProto.options = Just o })
(D.EnumDescriptorProto.options a)
where processOpt m = do m' <- interpretOptions "EnumOptions" m (D.EnumOptions.uninterpreted_option m)
return (m' { D.EnumOptions.uninterpreted_option = mempty })
instance ConsumeUNO D.EnumValueDescriptorProto where
consumeUNO a = maybe (return a) (processOpt >=> \o -> return $ a { D.EnumValueDescriptorProto.options = Just o })
(D.EnumValueDescriptorProto.options a)
where processOpt m = do m' <- interpretOptions "EnumValueOptions" m (D.EnumValueOptions.uninterpreted_option m)
return (m' { D.EnumValueOptions.uninterpreted_option = mempty })
instance ConsumeUNO D.MethodDescriptorProto where
consumeUNO a = maybe (return a) (processOpt >=> \o -> return $ a { D.MethodDescriptorProto.options = Just o })
(D.MethodDescriptorProto.options a)
where processOpt m = do m' <- interpretOptions "MethodOptions" m (D.MethodOptions.uninterpreted_option m)
return (m' { D.MethodOptions.uninterpreted_option = mempty })
instance ConsumeUNO D.ServiceDescriptorProto where
consumeUNO a = maybe (return a) (processOpt >=> \o -> return $ a { D.ServiceDescriptorProto.options = Just o })
(D.ServiceDescriptorProto.options a)
where processOpt m = do m' <- interpretOptions "ServiceOptions" m (D.ServiceOptions.uninterpreted_option m)
return (m' { D.ServiceOptions.uninterpreted_option = mempty })
instance ConsumeUNO D.FieldDescriptorProto where
consumeUNO a = maybe (return a) (processOpt >=> \o -> return $ a { D.FieldDescriptorProto.options = Just o })
(D.FieldDescriptorProto.options a)
where processOpt m = do m' <- interpretOptions "FieldOptions" m (D.FieldOptions.uninterpreted_option m)
return (m' { D.FieldOptions.uninterpreted_option = mempty })
instance ConsumeUNO D.FileDescriptorProto where
consumeUNO a = maybe (return a) (processOpt >=> \o -> return $ a { D.FileDescriptorProto.options = Just o })
(D.FileDescriptorProto.options a)
where processOpt m = do m' <- interpretOptions "FileOptions" m (D.FileOptions.uninterpreted_option m)
return (m' { D.FileOptions.uninterpreted_option = mempty })
instance ConsumeUNO D.DescriptorProto where
consumeUNO a = maybe (return a) (processOpt >=> \o -> return $ a { D.DescriptorProto.options = Just o })
(D.DescriptorProto.options a)
where processOpt m = do m' <- interpretOptions "MessageOptions" m (D.MessageOptions.uninterpreted_option m)
return (m' { D.MessageOptions.uninterpreted_option = mempty })
{- The boilerplate above feeds interpretOptions to do the real work -}
-- 'interpretOptions' is used by the 'consumeUNO' instances
-- This prepends the ["google","protobuf"] and updates all the options into the ExtField of msg
interpretOptions :: ExtendMessage msg => String -> msg -> Seq D.UninterpretedOption -> RE msg
interpretOptions name msg unos = do
name' <- getJust ("interpretOptions: invalid name "++show name) (validI name)
ios <- mapM (interpretOption [IName "google",IName "protobuf",name']) . F.toList $ unos
let (ExtField ef) = getExtField msg
ef' = foldl' (\m (k,v) -> seq v $ M.insertWithKey mergeWires k v m) ef ios
mergeWires _k (ExtFromWire newData) (ExtFromWire oldData) =
ExtFromWire (mappend oldData newData)
{-
mergeWires k (ExtFromWire wt1 newData) (ExtFromWire wt2 oldData) =
if wt1 /= wt2 then err $ "interpretOptions.mergeWires : ExtFromWire WireType mismatch while storing new options in extension fields: " ++ show (name,k,(wt1,wt2))
else ExtFromWire wt2 (mappend oldData newData)
-}
mergeWires k a b = err $ "interpretOptions.mergeWires : impossible case\n"++show (k,a,b)
msg' = seq ef' (putExtField (ExtField ef') msg)
return msg'
-- 'interpretOption' is called by 'interpretOptions'
-- The 'interpretOption' function is quite long because there are two things going on.
-- The first is the actual type must be retrieved from the UninterpretedOption and encoded.
-- The second is that messages/groups holding messages/groups ... holding the above must wrap this.
-- Both of the above might come from extension keys or from field names.
-- And as usual, there are many ways thing could conceivable go wrong or be out of bounds.
--
-- The first parameter must be a name such as ["google","protobuf","FieldOption"]
interpretOption :: [IName String] -> D.UninterpretedOption -> RE (FieldId,ExtFieldValue)
interpretOption optName uno = case F.toList (D.UninterpretedOption.name uno) of
[] -> iFail $ "Empty name_part"
(part:parts) -> go Nothing optName part parts
where
iFail :: String -> RE a -- needed by ghc-7.0.2
iFail msg = do env <- ask
throw $ unlines [ "interpretOption: Failed to handle UninterpretedOption for: "++show optName
, " environment: "++whereEnv env
, " value: "++show uno
, " message: "++msg ]
-- This takes care of an intermediate message or group type
go :: Maybe Entity {- E'Message E'Group -} -> [IName String] -> D.NamePart -> [D.NamePart] -> RE (FieldId,ExtFieldValue)
go mParent names (D.NamePart { D.NamePart.name_part = name
, D.NamePart.is_extension = isKey }) (next:rest) = do
-- get entity (Field or Key) and the TYPE_*
-- fk will ceratinly be E'Field or E'Key
(fk,entity) <-
if not isKey
then case mParent of
Nothing -> iFail $ "Cannot resolve local (is_extension False) name, no parent; expected (key)."
Just parent -> do
entity'field <- resolveHere parent name
case entity'field of
(E'Field {}) ->
case mVal entity'field of
Nothing -> iFail $ "Intermediate entry E'Field is of basic type, not E'Message or E'Group: "++show (names,eName entity'field)
Just val -> lift val >>= \e -> return (entity'field,e)
_ -> iFail $ "Name "++show (toString name)++" was resolved but was not an E'Field: "++show (eName entity'field)
else do entity'key <- resolveRE name
case entity'key of
(E'Key {eMsg=msg}) -> do
extendee <- lift msg
when (eName extendee /= names) $
iFail $ "Intermediate entry E'Key extends wrong type: "++show (names,eName extendee)
case mVal entity'key of
Nothing-> iFail $ "Intermediate entry E'Key is of basic type, not E'Message or E'Group: "++show (names,eName entity'key)
Just val -> lift val >>= \e -> return (entity'key,e)
_ -> iFail $ "Name "++show (toString name)++" was resolved but was not an E'Key: "++show (eName entity'key)
t <- case entity of
E'Message {} -> return TYPE_MESSAGE
E'Group {} -> return TYPE_GROUP
_ -> iFail $ "Intermediate entry is not an E'Message or E'Group: "++show (eName entity)
-- recursive call to get inner result
(fid',ExtFromWire raw') <- go (Just entity) (eName entity) next rest
-- wrap old tag + inner result with outer info
let tag@(WireTag tag') = mkWireTag fid' wt'
(EP wt' bs') = Seq.index raw' 0
let fid = fNumber fk -- safe by construction of fk
wt = toWireType (FieldType (fromEnum t))
bs = runPut $
case t of TYPE_MESSAGE -> do putSize (size'WireTag tag + LC.length bs')
putVarUInt tag'
putLazyByteString bs'
TYPE_GROUP -> do putVarUInt tag'
putLazyByteString bs'
putVarUInt (succ (getWireTag (mkWireTag fid wt)))
_ -> fail $ "bug! raw with type "++show t++" should be impossible"
return (fid,ExtFromWire (Seq.singleton (EP wt bs)))
-- This takes care of the acutal value of the option, which must be a basic type
go mParent names (D.NamePart { D.NamePart.name_part = name
, D.NamePart.is_extension = isKey }) [] = do
-- get entity (Field or Key) and the TYPE_*
fk <- if isKey then resolveRE name
else case mParent of
Just parent -> resolveHere parent name
Nothing -> iFail $ "Cannot resolve local (is_extension False) name, no parent; expected (key)."
case fk of
E'Field {} | not isKey -> return ()
E'Key {} | isKey -> do
ext <- lift (eMsg fk)
when (eName ext /= names) $ iFail $ "Last entry E'Key extends wrong type: "++show (names,eName ext)
_ -> iFail $ "Last entity was resolved but was not an E'Field or E'Key: "++show fk
t <- case (fType fk) of
Nothing -> return TYPE_ENUM -- XXX not a good assumption with aggregate types !!!! This also covers groups and messages.
Just TYPE_GROUP -> iFail $ "Last entry was a TYPE_GROUP instead of concrete value type" -- impossible
Just TYPE_MESSAGE -> {- impossible -} iFail $ "Last entry was a TYPE_MESSAGE instead of concrete value type" -- impossible
Just typeCode -> return typeCode
-- Need to define a polymorphic 'done' to convert actual data type to its wire encoding
let done :: Wire v => v -> RE (FieldId,ExtFieldValue)
done v = let ft = FieldType (fromEnum t)
wt = toWireType ft
fid = fNumber fk
in return (fid,ExtFromWire (Seq.singleton (EP wt (runPut (wirePut ft v)))))
-- The actual type and value fed to 'done' depends on the values 't' and 'uno':
case t of
TYPE_ENUM -> -- Now must also also handle Message and Group
case (mVal fk,D.UninterpretedOption.identifier_value uno,D.UninterpretedOption.aggregate_value uno) of
(Just (Right (E'Enum {eVals=enumVals})),Just enumVal,_) ->
case validI enumVal of
Nothing -> iFail $ "invalid D.UninterpretedOption.identifier_value: "++show enumVal
Just enumIVal -> case M.lookup enumIVal enumVals of
Nothing -> iFail $ "enumVal lookup failed: "++show (enumIVal,M.keys enumVals)
Just val -> done (fromEnum val) -- fromEnum :: Int32 -> Int
(Just (Right (E'Enum {})),Nothing,_) -> iFail $ "No identifer_value value to lookup in E'Enum"
(Just (Right (E'Message {})),_,Nothing) -> iFail "Expected aggregate syntax to set a message option"
(Just (Right (E'Message {})),_,Just aggVal) -> iFail $ "\n\n\
\=========================================================================================\n\
\Google's 2.4.0 aggregate syntax for message options is not yet supported, value would be:\n\
\=========================================================================================\n" ++ show aggVal
(Just (Right (E'Group {})),_,Nothing) -> iFail "Expected aggregate syntax to set a group option (impossible?)"
(Just (Right (E'Group {})),_,Just aggVal) -> iFail $ "\n\n\
\=========================================================================================\n\
\Google's 2.4.0 aggregate syntax for message options is not yet supported, value would be:\n\
\=========================================================================================\n" ++ show aggVal
(me,_,_) -> iFail $ "Expected Just E'Enum or E'Message or E'Group, got:\n"++show me
TYPE_STRING -> do
bs <- getJust "UninterpretedOption.string_value" (D.UninterpretedOption.string_value uno)
maybe (done (Utf8 bs)) (\i -> iFail $ "Invalid utf8 in string_value at index: "++show i)
(isValidUTF8 bs)
TYPE_BYTES -> done =<< getJust "UninterpretedOption.string_value" (D.UninterpretedOption.string_value uno)
TYPE_BOOL -> done =<< bVal
TYPE_DOUBLE -> done =<< dVal
TYPE_FLOAT -> done =<< asFloat =<< dVal
TYPE_INT64 -> done =<< (iVal :: RE Int64)
TYPE_SFIXED64 -> done =<< (iVal :: RE Int64)
TYPE_SINT64 -> done =<< (iVal :: RE Int64)
TYPE_UINT64 -> done =<< (iVal :: RE Word64)
TYPE_FIXED64 -> done =<< (iVal :: RE Word64)
TYPE_INT32 -> done =<< (iVal :: RE Int32)
TYPE_SFIXED32 -> done =<< (iVal :: RE Int32)
TYPE_SINT32 -> done =<< (iVal :: RE Int32)
TYPE_UINT32 -> done =<< (iVal :: RE Word32)
TYPE_FIXED32 -> done =<< (iVal :: RE Word32)
_ -> iFail $ "bug! go with type "++show t++" should be impossible"
-- Machinery needed by the final call of go
bVal :: RE Bool
bVal = let true = Utf8 (U.fromString "true")
false = Utf8 (U.fromString "false")
in case D.UninterpretedOption.identifier_value uno of
Just s | s == true -> return True
| s == false -> return False
_ -> iFail "Expected 'true' or 'false' identifier_value"
dVal :: RE Double
dVal = case (D.UninterpretedOption.negative_int_value uno
,D.UninterpretedOption.positive_int_value uno
,D.UninterpretedOption.double_value uno) of
(_,_,Just d) -> return d
(_,Just p,_) -> return (fromIntegral p)
(Just n,_,_) -> return (fromIntegral n)
_ -> iFail "No numeric value"
asFloat :: Double -> RE Float
asFloat d = let fmax :: Ratio Integer
fmax = (2-(1%2)^(23::Int)) * (2^(127::Int))
d' = toRational d
in if (negate fmax <= d') && (d' <= fmax)
then return (fromRational d')
else iFail $ "Double out of range for Float: "++show d
rangeCheck :: forall a. (Bounded a,Integral a) => Integer -> RE a
rangeCheck i = let r = (toInteger (minBound ::a),toInteger (maxBound :: a))
in if inRange r i then return (fromInteger i) else iFail $ "Constant out of range: "++show (r,i)
asInt :: Double -> RE Integer
asInt x = let (a,b) = properFraction x
in if b==0 then return a
else iFail $ "Double value not an integer: "++show x
iVal :: (Bounded y, Integral y) => RE y
iVal = case (D.UninterpretedOption.negative_int_value uno
,D.UninterpretedOption.positive_int_value uno
,D.UninterpretedOption.double_value uno) of
(_,Just p,_) -> rangeCheck (toInteger p)
(Just n,_,_) -> rangeCheck (toInteger n)
(_,_,Just d) -> rangeCheck =<< asInt d
_ -> iFail "No numeric value"
-- | 'findFile' looks through the current and import directories to find the target file on the system.
-- It also converts the relative path to a standard form to use as the name of the FileDescriptorProto.
findFile :: [LocalFP] -> LocalFP -> IO (Maybe (LocalFP,CanonFP)) -- absolute and canonical parts
findFile paths (LocalFP target) = test paths where
test [] = return Nothing
test (LocalFP path:rest) = do
let fullname = Local.combine path target
found <- doesFileExist fullname -- stop at first hit
if not found
then test rest
else do truepath <- canonicalizePath path
truefile <- canonicalizePath fullname
if truepath `isPrefixOf` truefile
then do let rel = fpLocalToCanon (LocalFP (Local.makeRelative truepath truefile))
return (Just (LocalFP truefile,rel))
else fail $ "file found but it is not below path, cannot make canonical name:\n path: "
++show truepath++"\n file: "++show truefile
-- | Given a path, tries to find and parse a FileDescriptorProto
-- corresponding to it; returns also a canonicalised path.
type DescriptorReader m = (Monad m) => LocalFP -> m (D.FileDescriptorProto, LocalFP)
loadProto' :: (Functor r,Monad r) => DescriptorReader r -> LocalFP -> r (Env,[D.FileDescriptorProto])
loadProto' fdpReader protoFile = goState (load Set.empty protoFile) where
goState act = do (env,m) <- runStateT act mempty
let fromRight (Right x) = x
fromRight (Left s) = error $ "loadProto failed to resolve a FileDescriptorProto: "++s
return (env,map (fromRight . top'FDP . fst . getTLS) (M.elems m))
load parentsIn file = do
built <- get
when (Set.member file parentsIn)
(loadFailed file (unlines ["imports failed: recursive loop detected"
,unlines . map show . M.assocs $ built,show parentsIn]))
case M.lookup file built of -- check memorized results
Just result -> return result
Nothing -> do
(parsed'fdp, canonicalFile) <- lift $ fdpReader file
let rawPackage = getPackage parsed'fdp
packageName <- either (loadFailed canonicalFile . show)
(return . fmap (map iToString . snd)) -- 2012-09-19 suspicious
(checkPackageID rawPackage)
{-
-- OLD before 2012-09-19
packageName <- either (loadFailed canonicalFile . show)
(return . PackageID . map iToString . snd) -- 2012-09-19 suspicious
(checkPackageID rawPackage)
-}
{-
-- previously patched solution
packageName <- case D.FileDescriptorProto.package parsed'fdp of
Nothing -> return []
Just p -> either (loadFailed canonicalFile . show)
(return . map iToString . snd) $
(checkDIUtf8 p)
-}
let parents = Set.insert file parentsIn
importList = map (fpCanonToLocal . CanonFP . toString) . F.toList . D.FileDescriptorProto.dependency $ parsed'fdp
imports <- mapM (fmap getTL . load parents) importList
let eEnv = makeTopLevel parsed'fdp packageName imports -- makeTopLevel is the "internal entry point" of Resolve.hs
-- Stricly force these two value to report errors here
global'env <- either (loadFailed file) return eEnv
_ <- either (loadFailed file) return (top'FDP . getTL $ global'env)
modify (M.insert file global'env) -- add to memorized results
return global'env
loadFailed :: (Monad m) => LocalFP -> String -> m a
loadFailed f msg = fail . unlines $ ["Parsing proto:",show (unLocalFP f),"has failed with message",msg]
-- | Given a list of paths to search, loads proto files by
-- looking for them in the file system.
loadProto :: [LocalFP] -> LocalFP -> IO (Env,[D.FileDescriptorProto])
loadProto protoDirs protoFile = loadProto' findAndParseSource protoFile where
findAndParseSource :: DescriptorReader IO
findAndParseSource file = do
mayToRead <- liftIO $ findFile protoDirs file
case mayToRead of
Nothing -> loadFailed file (unlines (["loading failed, could not find file: "++show (unLocalFP file)
,"Searched paths were:"] ++ map ((" "++).show.unLocalFP) protoDirs))
Just (toRead,relpath) -> do
protoContents <- liftIO $ do putStrLn ("Loading filepath: "++show (unLocalFP toRead))
LC.readFile (unLocalFP toRead)
parsed'fdp <- either (loadFailed toRead . show) return $
(parseProto (unCanonFP relpath) protoContents)
return (parsed'fdp, toRead)
loadCodeGenRequest :: CGR.CodeGeneratorRequest -> LocalFP -> (Env,[D.FileDescriptorProto])
loadCodeGenRequest req protoFile = runIdentity $ loadProto' lookUpParsedSource protoFile where
lookUpParsedSource :: DescriptorReader Identity
lookUpParsedSource file = case M.lookup file fdpsByName of
Just result -> return (result, file)
Nothing -> loadFailed file ("Request refers to file: "++show (unLocalFP file)
++" but it was not supplied in the request.")
fdpsByName = M.fromList . map keyByName . F.toList . CGR.proto_file $ req
keyByName fdp = (fdpName fdp, fdp)
fdpName = LocalFP . maybe "" (LC.unpack . utf8) . D.FileDescriptorProto.name
-- wart: descend should take (eName,eMvals) not Entity
-- wart: myFix* obviously implements a WriterT by hand. Implement as WriterT ?
|
edahlgren/protocol-buffers
|
hprotoc/Text/ProtocolBuffers/ProtoCompile/Resolve.hs
|
apache-2.0
| 78,001 | 733 | 28 | 19,440 | 17,083 | 9,251 | 7,832 | 933 | 54 |
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses, FlexibleInstances,
UndecidableInstances, RebindableSyntax, DataKinds,
TypeOperators, PolyKinds, FlexibleContexts, ConstraintKinds,
IncoherentInstances, GADTs
#-}
module Control.Effect.State (Set(..), get, put, State(..), (:->)(..), (:!)(..),
Eff(..), Action(..), Var(..), union, UnionS,
Reads(..), Writes(..), Unionable, Sortable, SetLike,
StateSet,
--- may not want to export these
IntersectR, Update, Sort, Split) where
import Control.Effect
import Data.Type.Set hiding (Unionable, union, SetLike, Nub, Nubable(..))
import qualified Data.Type.Set as Set
--import Data.Type.Map (Mapping(..), Var(..))
import Prelude hiding (Monad(..),reads)
import GHC.TypeLits
{-| Provides an effect-parameterised version of the state monad, which gives an
effect system for stateful computations with annotations that are sets of
variable-type-action triples. -}
{-| Distinguish reads, writes, and read-writes -}
data Eff = R | W | RW
{-| Provides a wrapper for effect actions -}
data Action (s :: Eff) = Eff
instance Show (Action R) where
show _ = "R"
instance Show (Action W) where
show _ = "W"
instance Show (Action RW) where
show _ = "RW"
infixl 2 :->
data (k :: Symbol) :-> (v :: *) = (Var k) :-> v
data Var (k :: Symbol) where Var :: Var k
{- Some special defaults for some common names -}
X :: Var "x"
Y :: Var "y"
Z :: Var "z"
instance (Show (Var k), Show v) => Show (k :-> v) where
show (k :-> v) = "(" ++ show k ++ " :-> " ++ show v ++ ")"
instance Show (Var "x") where
show X = "x"
show Var = "Var"
instance Show (Var "y") where
show Y = "y"
show Var = "Var"
instance Show (Var "z") where
show Z = "z"
show Var = "Var"
instance Show (Var v) where
show _ = "Var"
{-| Symbol comparison -}
type instance Cmp (v :-> a) (u :-> b) = CmpSymbol v u
{-| Describes an effect action 's' on a value of type 'a' -}
--data EffMapping a (s :: Eff) = a :! (Action s)
data a :! (s :: Eff) = a :! (Action s)
instance (Show (Action f), Show a) => Show (a :! f) where
show (a :! f) = show a ++ " ! " ++ show f
infixl 3 :!
type SetLike s = Nub (Sort s)
type UnionS s t = Nub (Sort (s :++ t))
type Unionable s t = (Sortable (s :++ t), Nubable (Sort (s :++ t)) (Nub (Sort (s :++ t))),
Split s t (Union s t))
{-| Union operation for state effects -}
union :: (Unionable s t) => Set s -> Set t -> Set (UnionS s t)
union s t = nub (quicksort (append s t))
{-| Type-level remove duplicates from a type-level list and turn different sorts into 'RW'| -}
type family Nub t where
Nub '[] = '[]
Nub '[e] = '[e]
Nub (e ': e ': as) = Nub (e ': as)
Nub ((k :-> a :! s) ': (k :-> a :! t) ': as) = Nub ((k :-> a :! RW) ': as)
Nub (e ': f ': as) = e ': Nub (f ': as)
{-| Value-level remove duplicates from a type-level list and turn different sorts into 'RW'| -}
class Nubable t v where
nub :: Set t -> Set v
instance Nubable '[] '[] where
nub Empty = Empty
instance Nubable '[e] '[e] where
nub (Ext e Empty) = (Ext e Empty)
instance Nubable ((k :-> b :! s) ': as) as' =>
Nubable ((k :-> a :! s) ': (k :-> b :! s) ': as) as' where
nub (Ext _ (Ext x xs)) = nub (Ext x xs)
instance Nubable ((k :-> a :! RW) ': as) as' =>
Nubable ((k :-> a :! s) ': (k :-> a :! t) ': as) as' where
nub (Ext _ (Ext (k :-> (a :! _)) xs)) = nub (Ext (k :-> (a :! (Eff::(Action RW)))) xs)
instance Nubable ((j :-> b :! t) ': as) as' =>
Nubable ((k :-> a :! s) ': (j :-> b :! t) ': as) ((k :-> a :! s) ': as') where
nub (Ext (k :-> (a :! s)) (Ext (j :-> (b :! t)) xs)) = Ext (k :-> (a :! s)) (nub (Ext (j :-> (b :! t)) xs))
{-| Update reads, that is any writes are pushed into reads, a bit like intersection -}
class Update s t where
update :: Set s -> Set t
instance Update xs '[] where
update _ = Empty
instance Update '[e] '[e] where
update s = s
{-
instance Update ((v :-> b :! R) ': as) as' => Update ((v :-> a :! s) ': (v :-> b :! s) ': as) as' where
update (Ext _ (Ext (v :-> (b :! _)) xs)) = update (Ext (v :-> (b :! (Eff::(Action R)))) xs) -}
instance Update ((v :-> a :! R) ': as) as' => Update ((v :-> a :! W) ': (v :-> b :! R) ': as) as' where
update (Ext (v :-> (a :! _)) (Ext _ xs)) = update (Ext (v :-> (a :! (Eff::(Action R)))) xs)
instance Update ((u :-> b :! s) ': as) as' => Update ((v :-> a :! W) ': (u :-> b :! s) ': as) as' where
update (Ext _ (Ext e xs)) = update (Ext e xs)
instance Update ((u :-> b :! s) ': as) as' => Update ((v :-> a :! R) ': (u :-> b :! s) ': as) ((v :-> a :! R) ': as') where
update (Ext e (Ext e' xs)) = Ext e $ update (Ext e' xs)
type IntersectR s t = (Sortable (s :++ t), Update (Sort (s :++ t)) t)
{-| Intersects a set of write effects and a set of read effects, updating any read effects with
any corresponding write value -}
intersectR :: (Reads t ~ t, Writes s ~ s, IsSet s, IsSet t, IntersectR s t) => Set s -> Set t -> Set t
intersectR s t = update (quicksort (append s t))
{-| Parametric effect state monad -}
data State s a = State { runState :: Set (Reads s) -> (a, Set (Writes s)) }
{-| Calculate just the reader effects -}
type family Reads t where
Reads '[] = '[]
Reads ((k :-> a :! R) ': xs) = (k :-> a :! R) ': (Reads xs)
Reads ((k :-> a :! RW) ': xs) = (k :-> a :! R) ': (Reads xs)
Reads ((k :-> a :! W) ': xs) = Reads xs
{-| Calculate just the writer effects -}
type family Writes t where
Writes '[] = '[]
Writes ((k :-> a :! W) ': xs) = (k :-> a :! W) ': (Writes xs)
Writes ((k :-> a :! RW) ': xs) = (k :-> a :! W) ': (Writes xs)
Writes ((k :-> a :! R) ': xs) = Writes xs
{-| Read from a variable 'v' of type 'a'. Raise a read effect. -}
get :: Var v -> State '[v :-> a :! R] a
get _ = State $ \(Ext (v :-> (a :! _)) Empty) -> (a, Empty)
{-| Write to a variable 'v' with a value of type 'a'. Raises a write effect -}
put :: Var v -> a -> State '[v :-> a :! W] ()
put _ a = State $ \Empty -> ((), Ext (Var :-> a :! Eff) Empty)
{-| Captures what it means to be a set of state effects -}
type StateSet f = (StateSetProperties f, StateSetProperties (Reads f), StateSetProperties (Writes f))
type StateSetProperties f = (IntersectR f '[], IntersectR '[] f,
UnionS f '[] ~ f, Split f '[] f,
UnionS '[] f ~ f, Split '[] f f,
UnionS f f ~ f, Split f f f,
Unionable f '[], Unionable '[] f)
-- Indexed monad instance
instance Effect State where
type Inv State s t = (IsSet s, IsSet (Reads s), IsSet (Writes s),
IsSet t, IsSet (Reads t), IsSet (Writes t),
Reads (Reads t) ~ Reads t, Writes (Writes s) ~ Writes s,
Split (Reads s) (Reads t) (Reads (UnionS s t)),
Unionable (Writes s) (Writes t),
IntersectR (Writes s) (Reads t),
Writes (UnionS s t) ~ UnionS (Writes s) (Writes t))
{-| Pure state effect is the empty state -}
type Unit State = '[]
{-| Combine state effects via specialised union (which combines R and W effects on the same
variable into RW effects -}
type Plus State s t = UnionS s t
return x = State $ \Empty -> (x, Empty)
(State e) >>= k =
State $ \st -> let (sR, tR) = split st
(a, sW) = e sR
(b, tW) = (runState $ k a) (sW `intersectR` tR)
in (b, sW `union` tW)
{-
instance (Split s t (Union s t), Sub s t) => Subeffect State s t where
sub (State e) = IxR $ \st -> let (s, t) = split st
_ = ReflP p t
in e s
-}
|
dorchard/effect-monad
|
src/Control/Effect/State.hs
|
bsd-2-clause
| 8,221 | 8 | 15 | 2,659 | 3,309 | 1,770 | 1,539 | 125 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.PhoneNumber.AR.Corpus
( corpus
, negativeCorpus
) where
import Prelude
import Data.String
import Duckling.Locale
import Duckling.PhoneNumber.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus =
(testContext { locale = makeLocale AR Nothing }, testOptions, allExamples)
negativeCorpus :: NegativeCorpus
negativeCorpus = (testContext, testOptions, xs)
where
xs =
[ "١٢٣٤٥"
, "١٢٣٤٥٦٧٨٩٠١٢٣٤٥٦٧٧٧٧٧٧"
, "١٢٣٤٥٦٧٨٩٠١٢٣٤٥٦"
]
-- Tests include both unicode characters and equivalent unicode decimal code
-- representation because the Arabic phone number regex is constructed with
-- unicode decimal form.
allExamples :: [Example]
allExamples =
concat
[ examples (PhoneNumberValue "6507018887")
[ "٦٥٠٧٠١٨٨٨٧"
, "\1638\1637\1632\1639\1632\1633\1640\1640\1640\1639"
, "٦٥٠ ٧٠١ ٨٨٨٧"
, "\1638\1637\1632 \1639\1632\1633 \1640\1640\1640\1639"
, "٦٥٠-٧٠١-٨٨٨٧"
, "\1638\1637\1632-\1639\1632\1633-\1640\1640\1640\1639"
]
, examples (PhoneNumberValue "(+1) 6507018887")
[ "+١ ٦٥٠٧٠١٨٨٨٧"
, "+\1633 \1638\1637\1632\1639\1632\1633\1640\1640\1640\1639"
, "(+١)٦٥٠٧٠١٨٨٨٧"
, "(+\1633)\1638\1637\1632\1639\1632\1633\1640\1640\1640\1639"
, "(+١) ٦٥٠ - ٧٠١ ٨٨٨٧"
, "(+\1633) \1638\1637\1632 - \1639\1632\1633 \1640\1640\1640\1639"
]
, examples (PhoneNumberValue "(+33) 146647998")
[ "+٣٣ ١ ٤٦٦٤٧٩٩٨"
, "+\1635\1635 \1633 \1636\1638\1638\1636\1639\1641\1641\1640"
]
, examples (PhoneNumberValue "0620702220")
[ "٠٦ ٢٠٧٠ ٢٢٢٠"
]
, examples (PhoneNumberValue "6507018887 ext 897")
[ "٦٥٠٧٠١٨٨٨٧ ext ٨٩٧"
, "٦٥٠٧٠١٨٨٨٧ x ٨٩٧"
, "٦٥٠٧٠١٨٨٨٧ ext. ٨٩٧"
]
, examples (PhoneNumberValue "6507018887 ext 897")
[ "٦٥٠٧٠١٨٨٨٧ فرعي ٨٩٧"
]
, examples (PhoneNumberValue "(+1) 2025550121")
[ "+١-٢٠٢-٥٥٥-٠١٢١"
, "+١ ٢٠٢.٥٥٥.٠١٢١"
]
, examples (PhoneNumberValue "4866827")
[ "٤.٨.٦.٦.٨.٢.٧"
]
, examples (PhoneNumberValue "(+55) 19992842606")
[ "(+٥٥) ١٩٩٩٢٨٤٢٦٠٦"
]
]
|
facebookincubator/duckling
|
Duckling/PhoneNumber/AR/Corpus.hs
|
bsd-3-clause
| 2,919 | 0 | 9 | 829 | 333 | 198 | 135 | 54 | 1 |
{-# OPTIONS -fglasgow-exts #-}
module GisServer.Data.Common ( LexicalLevel, lexLevel
, fieldTermChar, fieldTerm
, recordTermChar, recordTerm
, getStringN, getStringEncoded, getStringTill
, getInt, getIntN
) where
import Data.Binary
import Data.Binary.Get
import Data.Char
import Int
import qualified Data.Bits as Bits
import qualified Data.ByteString.Lazy as B
import Test.QuickCheck
import Data.Text as T
import qualified Data.Encoding as E
import Data.Encoding.ASCII
import Data.Encoding.UTF16
import Data.Encoding.ISO88591
data LexicalLevel =
LexLevel0 | LexLevel1 | LexLevel2
deriving (Eq, Show, Ord, Enum)
lexLevel :: Int -> LexicalLevel
lexLevel = toEnum
fieldTermChar = '\RS'
fieldTerm :: Word8
fieldTerm = fromIntegral $ ord fieldTermChar
recordTermChar = '\US'
recordTerm :: Word8
recordTerm = fromIntegral $ ord recordTermChar
getStringTill :: LexicalLevel -> Get String
getStringTill l = getStringTill' l fieldTerm
getStringTill' l c = undefined
--getStringTill = getStringTill' LexLevel0
--getStringTill' l c = do
-- c' <- fmap (word8char l) get
-- if (c' == c)
-- then do return [c']
-- else do cs <- getStringTill' l c
-- return $ c:cs
getIntN :: Int -> Get Int
getIntN n = fmap read $ getStringN LexLevel0 n
getStringN l n = fmap (getStringEncoded l) $ getLazyByteString $ fromIntegral n
getStringEncoded LexLevel0 = E.decodeLazyByteString ASCII
getStringEncoded LexLevel1 = E.decodeLazyByteString ISO88591
getStringEncoded LexLevel2 = E.decodeLazyByteString UTF16LE
getInt :: Bool -> Int -> Get Int
getInt s 4 =
if (s)
then do v <- fmap decomplement2 getWord32le
return $ negate $ fromIntegral v
else fmap fromIntegral getWord32le
prop_readInt8 :: Int8 -> Bool
prop_readInt8 i =
let bs = encode i
decode = runGet (getInt True 1) bs
in decode == fromIntegral i
complement2 :: (Bits.Bits t) => t -> t
complement2 x = 1 + Bits.complement x
decomplement2 :: (Bits.Bits t) => t -> t
decomplement2 x = Bits.complement $ x - 1
instance Arbitrary Word64 where
arbitrary = arbitrarySizedIntegral
instance Arbitrary Int8 where
arbitrary = arbitrarySizedIntegral
prop_complement2 :: Word64 -> Bool
prop_complement2 x = x == decomplement2 (complement2 x)
|
alios/gisserver
|
GisServer/Data/Common.hs
|
bsd-3-clause
| 2,485 | 0 | 11 | 641 | 605 | 329 | 276 | 59 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
-- | Github API: http://developer.github.com/v3/oauth/
module Main where
import Control.Monad (mzero)
import Data.Aeson
import qualified Data.ByteString as BS
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Network.HTTP.Conduit
import URI.ByteString
import URI.ByteString.QQ
import Network.OAuth.OAuth2
import Keys
main :: IO ()
main = do
let state = "testGithubApi"
print $ serializeURIRef' $ appendQueryParams [("state", state)] $ authorizationUrl githubKey
putStrLn "visit the url and paste code here: "
code <- getLine
mgr <- newManager tlsManagerSettings
let (url, body) = accessTokenUrl githubKey $ ExchangeToken $ T.pack $ code
token <- doJSONPostRequest mgr githubKey url (body ++ [("state", state)])
print (token :: OAuth2Result OAuth2Token)
case token of
Right at -> userInfo mgr (accessToken at) >>= print
Left _ -> putStrLn "no access token found yet"
-- | Test API: user
--
userInfo :: Manager -> AccessToken -> IO (OAuth2Result GithubUser)
userInfo mgr token = authGetJSON mgr token [uri|https://api.github.com/user|]
data GithubUser = GithubUser { gid :: Integer
, gname :: Text
} deriving (Show, Eq)
instance FromJSON GithubUser where
parseJSON (Object o) = GithubUser
<$> o .: "id"
<*> o .: "name"
parseJSON _ = mzero
sToBS :: String -> BS.ByteString
sToBS = T.encodeUtf8 . T.pack
|
reactormonk/hoauth2
|
example/Github/test.hs
|
bsd-3-clause
| 1,761 | 0 | 13 | 517 | 431 | 233 | 198 | 40 | 2 |
{-# OPTIONS -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.HashTable
-- Copyright : (c) The University of Glasgow 2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- An implementation of extensible hash tables, as described in
-- Per-Ake Larson, /Dynamic Hash Tables/, CACM 31(4), April 1988,
-- pp. 446--457. The implementation is also derived from the one
-- in GHC's runtime system (@ghc\/rts\/Hash.{c,h}@).
--
-----------------------------------------------------------------------------
module Data.HashTable (
-- * Basic hash table operations
HashTable, new, insert, delete, lookup,
-- * Converting to and from lists
fromList, toList,
-- * Hash functions
-- $hash_functions
hashInt, hashString,
prime,
-- * Diagnostics
longestChain
) where
-- This module is imported by Data.Dynamic, which is pretty low down in the
-- module hierarchy, so don't import "high-level" modules
import Prelude hiding ( lookup )
import Data.Tuple ( fst )
import Data.Bits
import Data.Maybe
import Data.List ( maximumBy, filter, length, concat )
import Data.Int ( Int32 )
import Data.Char ( ord )
import Data.IORef ( IORef, newIORef, readIORef, writeIORef )
import Hugs.IOArray ( IOArray, newIOArray, readIOArray, writeIOArray,
unsafeReadIOArray, unsafeWriteIOArray )
import Control.Monad ( when, mapM, sequence_ )
-----------------------------------------------------------------------
myReadArray :: IOArray Int32 a -> Int32 -> IO a
myWriteArray :: IOArray Int32 a -> Int32 -> a -> IO ()
myReadArray arr i = unsafeReadIOArray arr (fromIntegral i)
myWriteArray arr i x = unsafeWriteIOArray arr (fromIntegral i) x
-- | A hash table mapping keys of type @key@ to values of type @val@.
--
-- The implementation will grow the hash table as necessary, trying to
-- maintain a reasonable average load per bucket in the table.
--
newtype HashTable key val = HashTable (IORef (HT key val))
-- TODO: the IORef should really be an MVar.
data HT key val
= HT {
split :: !Int32, -- Next bucket to split when expanding
max_bucket :: !Int32, -- Max bucket of smaller table
mask1 :: !Int32, -- Mask for doing the mod of h_1 (smaller table)
mask2 :: !Int32, -- Mask for doing the mod of h_2 (larger table)
kcount :: !Int32, -- Number of keys
bcount :: !Int32, -- Number of buckets
dir :: !(IOArray Int32 (IOArray Int32 [(key,val)])),
hash_fn :: key -> Int32,
cmp :: key -> key -> Bool
}
{-
ALTERNATIVE IMPLEMENTATION:
This works out slightly slower, because there's a tradeoff between
allocating a complete new HT structure each time a modification is
made (in the version above), and allocating new Int32s each time one
of them is modified, as below. Using FastMutInt instead of IORef
Int32 helps, but yields an implementation which has about the same
performance as the version above (and is more complex).
data HashTable key val
= HashTable {
split :: !(IORef Int32), -- Next bucket to split when expanding
max_bucket :: !(IORef Int32), -- Max bucket of smaller table
mask1 :: !(IORef Int32), -- Mask for doing the mod of h_1 (smaller table)
mask2 :: !(IORef Int32), -- Mask for doing the mod of h_2 (larger table)
kcount :: !(IORef Int32), -- Number of keys
bcount :: !(IORef Int32), -- Number of buckets
dir :: !(IOArray Int32 (IOArray Int32 [(key,val)])),
hash_fn :: key -> Int32,
cmp :: key -> key -> Bool
}
-}
-- -----------------------------------------------------------------------------
-- Sample hash functions
-- $hash_functions
--
-- This implementation of hash tables uses the low-order /n/ bits of the hash
-- value for a key, where /n/ varies as the hash table grows. A good hash
-- function therefore will give an even distribution regardless of /n/.
--
-- If your keyspace is integrals such that the low-order bits between
-- keys are highly variable, then you could get away with using 'id'
-- as the hash function.
--
-- We provide some sample hash functions for 'Int' and 'String' below.
-- | A sample hash function for 'Int', implemented as simply @(x `mod` P)@
-- where P is a suitable prime (currently 1500007). Should give
-- reasonable results for most distributions of 'Int' values, except
-- when the keys are all multiples of the prime!
--
hashInt :: Int -> Int32
hashInt = (`rem` prime) . fromIntegral
-- | A sample hash function for 'String's. The implementation is:
--
-- > hashString = fromIntegral . foldr f 0
-- > where f c m = ord c + (m * 128) `rem` 1500007
--
-- which seems to give reasonable results.
--
hashString :: String -> Int32
hashString = fromIntegral . foldr f 0
where f c m = ord c + (m * 128) `rem` fromIntegral prime
-- | A prime larger than the maximum hash table size
prime :: Int32
prime = 1500007
-- -----------------------------------------------------------------------------
-- Parameters
sEGMENT_SIZE = 1024 :: Int32 -- Size of a single hash table segment
sEGMENT_SHIFT = 10 :: Int -- derived
sEGMENT_MASK = 0x3ff :: Int32 -- derived
dIR_SIZE = 1024 :: Int32 -- Size of the segment directory
-- Maximum hash table size is sEGMENT_SIZE * dIR_SIZE
hLOAD = 4 :: Int32 -- Maximum average load of a single hash bucket
-- -----------------------------------------------------------------------------
-- Creating a new hash table
-- | Creates a new hash table
new
:: (key -> key -> Bool) -- ^ An equality comparison on keys
-> (key -> Int32) -- ^ A hash function on keys
-> IO (HashTable key val) -- ^ Returns: an empty hash table
new cmp hash_fn = do
-- make a new hash table with a single, empty, segment
dir <- newIOArray (0,dIR_SIZE) undefined
segment <- newIOArray (0,sEGMENT_SIZE-1) []
myWriteArray dir 0 segment
let
split = 0
max = sEGMENT_SIZE
mask1 = (sEGMENT_SIZE - 1)
mask2 = (2 * sEGMENT_SIZE - 1)
kcount = 0
bcount = sEGMENT_SIZE
ht = HT { dir=dir, split=split, max_bucket=max, mask1=mask1, mask2=mask2,
kcount=kcount, bcount=bcount, hash_fn=hash_fn, cmp=cmp
}
table <- newIORef ht
return (HashTable table)
-- -----------------------------------------------------------------------------
-- Inserting a key\/value pair into the hash table
-- | Inserts an key\/value mapping into the hash table.
insert :: HashTable key val -> key -> val -> IO ()
insert (HashTable ref) key val = do
table@HT{ kcount=k, bcount=b, dir=dir } <- readIORef ref
let table1 = table{ kcount = k+1 }
table2 <-
if (k > hLOAD * b)
then expandHashTable table1
else return table1
writeIORef ref table2
(segment_index,segment_offset) <- tableLocation table key
segment <- myReadArray dir segment_index
bucket <- myReadArray segment segment_offset
myWriteArray segment segment_offset ((key,val):bucket)
return ()
bucketIndex :: HT key val -> key -> IO Int32
bucketIndex HT{ hash_fn=hash_fn,
split=split,
mask1=mask1,
mask2=mask2 } key = do
let
h = fromIntegral (hash_fn key)
small_bucket = h .&. mask1
large_bucket = h .&. mask2
--
if small_bucket < split
then return large_bucket
else return small_bucket
tableLocation :: HT key val -> key -> IO (Int32,Int32)
tableLocation table key = do
bucket_index <- bucketIndex table key
let
segment_index = bucket_index `shiftR` sEGMENT_SHIFT
segment_offset = bucket_index .&. sEGMENT_MASK
--
return (segment_index,segment_offset)
expandHashTable :: HT key val -> IO (HT key val)
expandHashTable
table@HT{ dir=dir,
split=split,
max_bucket=max,
mask2=mask2 } = do
let
oldsegment = split `shiftR` sEGMENT_SHIFT
oldindex = split .&. sEGMENT_MASK
newbucket = max + split
newsegment = newbucket `shiftR` sEGMENT_SHIFT
newindex = newbucket .&. sEGMENT_MASK
--
when (newindex == 0) $
do segment <- newIOArray (0,sEGMENT_SIZE-1) []
myWriteArray dir newsegment segment
--
let table' =
if (split+1) < max
then table{ split = split+1 }
-- we've expanded all the buckets in this table, so start from
-- the beginning again.
else table{ split = 0,
max_bucket = max * 2,
mask1 = mask2,
mask2 = mask2 `shiftL` 1 .|. 1 }
let
split_bucket old new [] = do
segment <- myReadArray dir oldsegment
myWriteArray segment oldindex old
segment <- myReadArray dir newsegment
myWriteArray segment newindex new
split_bucket old new ((k,v):xs) = do
h <- bucketIndex table' k
if h == newbucket
then split_bucket old ((k,v):new) xs
else split_bucket ((k,v):old) new xs
--
segment <- myReadArray dir oldsegment
bucket <- myReadArray segment oldindex
split_bucket [] [] bucket
return table'
-- -----------------------------------------------------------------------------
-- Deleting a mapping from the hash table
-- | Remove an entry from the hash table.
delete :: HashTable key val -> key -> IO ()
delete (HashTable ref) key = do
table@HT{ dir=dir, cmp=cmp } <- readIORef ref
(segment_index,segment_offset) <- tableLocation table key
segment <- myReadArray dir segment_index
bucket <- myReadArray segment segment_offset
myWriteArray segment segment_offset (filter (not.(key `cmp`).fst) bucket)
return ()
-- -----------------------------------------------------------------------------
-- Looking up an entry in the hash table
-- | Looks up the value of a key in the hash table.
lookup :: HashTable key val -> key -> IO (Maybe val)
lookup (HashTable ref) key = do
table@HT{ dir=dir, cmp=cmp } <- readIORef ref
(segment_index,segment_offset) <- tableLocation table key
segment <- myReadArray dir segment_index
bucket <- myReadArray segment segment_offset
case [ val | (key',val) <- bucket, cmp key key' ] of
[] -> return Nothing
(v:_) -> return (Just v)
-- -----------------------------------------------------------------------------
-- Converting to/from lists
-- | Convert a list of key\/value pairs into a hash table. Equality on keys
-- is taken from the Eq instance for the key type.
--
fromList :: Eq key => (key -> Int32) -> [(key,val)] -> IO (HashTable key val)
fromList hash_fn list = do
table <- new (==) hash_fn
sequence_ [ insert table k v | (k,v) <- list ]
return table
-- | Converts a hash table to a list of key\/value pairs.
--
toList :: HashTable key val -> IO [(key,val)]
toList (HashTable ref) = do
HT{ dir=dir, max_bucket=max, split=split } <- readIORef ref
--
let
max_segment = (max + split - 1) `quot` sEGMENT_SIZE
--
segments <- mapM (segmentContents dir) [0 .. max_segment]
return (concat segments)
where
segmentContents dir seg_index = do
segment <- myReadArray dir seg_index
bs <- mapM (myReadArray segment) [0 .. sEGMENT_SIZE-1]
return (concat bs)
-- -----------------------------------------------------------------------------
-- Diagnostics
-- | This function is useful for determining whether your hash function
-- is working well for your data set. It returns the longest chain
-- of key\/value pairs in the hash table for which all the keys hash to
-- the same bucket. If this chain is particularly long (say, longer
-- than 10 elements), then it might be a good idea to try a different
-- hash function.
--
longestChain :: HashTable key val -> IO [(key,val)]
longestChain (HashTable ref) = do
HT{ dir=dir, max_bucket=max, split=split } <- readIORef ref
--
let
max_segment = (max + split - 1) `quot` sEGMENT_SIZE
--
--trace ("maxChainLength: max = " ++ show max ++ ", split = " ++ show split ++ ", max_segment = " ++ show max_segment) $ do
segments <- mapM (segmentMaxChainLength dir) [0 .. max_segment]
return (maximumBy lengthCmp segments)
where
segmentMaxChainLength dir seg_index = do
segment <- myReadArray dir seg_index
bs <- mapM (myReadArray segment) [0 .. sEGMENT_SIZE-1]
return (maximumBy lengthCmp bs)
lengthCmp x y = length x `compare` length y
|
OS2World/DEV-UTIL-HUGS
|
libraries/Data/HashTable.hs
|
bsd-3-clause
| 12,055 | 96 | 19 | 2,369 | 2,681 | 1,461 | 1,220 | 194 | 4 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
module Zodiac.Cli.TSRP.Env(
tsrpParamsFromEnv
) where
import Control.Monad.IO.Class (liftIO)
import Data.ByteString (ByteString)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import P
import System.Environment (lookupEnv)
import System.IO (IO)
import X.Control.Monad.Trans.Either (EitherT, left)
import Zodiac.Raw
import Zodiac.Cli.TSRP.Data
import Zodiac.Cli.TSRP.Error
tsrpParamsFromEnv :: EitherT TSRPError IO TSRPParams
tsrpParamsFromEnv = do
sk <- getEnvParam "TSRP_SECRET_KEY" >>=
(parseParam "symmetric key" parseTSRPKey)
kid <- getEnvParam "TSRP_KEY_ID" >>=
(parseParam "key ID" parseKeyId)
pure $ TSRPParams sk kid
parseParam :: Text -> (ByteString -> Maybe' a) -> Text -> EitherT TSRPError IO a
parseParam var f t =
maybe' (left . TSRPParamError $ InvalidParam var t) pure $ (f . T.encodeUtf8) t
getEnvParam :: Text -> EitherT TSRPError IO Text
getEnvParam var =
liftIO (lookupEnv (T.unpack var)) >>= \case
Nothing -> left . TSRPParamError $ MissingRequiredParam var
Just val -> pure $ T.pack val
|
ambiata/zodiac
|
zodiac-cli/src/Zodiac/Cli/TSRP/Env.hs
|
bsd-3-clause
| 1,276 | 0 | 11 | 293 | 351 | 191 | 160 | 31 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Data.Conduit.Succinct.JsonSpec (spec) where
import Control.Monad.Trans.Resource (MonadThrow)
import Data.ByteString
import Data.Conduit
import Data.Conduit.Succinct.Json
import Data.Int
import Data.Succinct
import Test.Hspec
import Data.Conduit.Tokenize.Attoparsec
import Data.Conduit.Tokenize.Attoparsec.Offset
import Data.Json.Token
markerToBits :: [Int64] -> [Bool]
markerToBits ms = runListConduit ms (markerToByteString =$= byteStringToBits)
jsonToBits :: [ByteString] -> [Bool]
jsonToBits json = runListConduit json $
textToJsonToken =$= jsonToken2Markers =$= markerToByteString =$= byteStringToBits
jsonToMarkerBS :: [ByteString] -> [ByteString]
jsonToMarkerBS json = runListConduit json $
textToJsonToken =$= jsonToken2Markers =$= markerToByteString
jsonToMarkers :: [ByteString] -> [Int64]
jsonToMarkers json = runListConduit json $
textToJsonToken =$= jsonToken2Markers
jsonToken2Markers2 :: [(ParseDelta Offset, JsonToken)] -> [Int64]
jsonToken2Markers2 json = runListConduit json $ jsonToken2Markers
identity :: Monad m => Conduit i m i
identity = do
ma <- await
case ma of
Just a -> yield a
Nothing -> return ()
spec :: Spec
spec = describe "Data.Conduit.Succinct.JsonSpec" $ do
it "No markers should produce no bits" $
markerToBits [] `shouldBe` []
it "One marker < 8 should produce one byte with one bit set" $ do
markerToBits [0] `shouldBe` stringToBits "10000000"
markerToBits [1] `shouldBe` stringToBits "01000000"
markerToBits [2] `shouldBe` stringToBits "00100000"
markerToBits [3] `shouldBe` stringToBits "00010000"
markerToBits [4] `shouldBe` stringToBits "00001000"
markerToBits [5] `shouldBe` stringToBits "00000100"
markerToBits [6] `shouldBe` stringToBits "00000010"
markerToBits [7] `shouldBe` stringToBits "00000001"
it "One 8 <= marker < 16 should produce one byte empty byte and another byte with one bit set" $ do
markerToBits [ 8] `shouldBe` stringToBits "00000000 10000000"
markerToBits [ 9] `shouldBe` stringToBits "00000000 01000000"
markerToBits [10] `shouldBe` stringToBits "00000000 00100000"
markerToBits [11] `shouldBe` stringToBits "00000000 00010000"
markerToBits [12] `shouldBe` stringToBits "00000000 00001000"
markerToBits [13] `shouldBe` stringToBits "00000000 00000100"
markerToBits [14] `shouldBe` stringToBits "00000000 00000010"
markerToBits [15] `shouldBe` stringToBits "00000000 00000001"
it "All markers 0 .. 7 should produce one full byte" $
markerToBits [0, 1, 2, 3, 4, 5, 6, 7] `shouldBe` stringToBits "11111111"
it "All markers 0 .. 7 except 1 should produce one almost full byte" $ do
markerToBits [1, 2, 3, 4, 5, 6, 7] `shouldBe` stringToBits "01111111"
markerToBits [0, 2, 3, 4, 5, 6, 7] `shouldBe` stringToBits "10111111"
markerToBits [0, 1, 3, 4, 5, 6, 7] `shouldBe` stringToBits "11011111"
markerToBits [0, 1, 2, 4, 5, 6, 7] `shouldBe` stringToBits "11101111"
markerToBits [0, 1, 2, 3, 5, 6, 7] `shouldBe` stringToBits "11110111"
markerToBits [0, 1, 2, 3, 4, 6, 7] `shouldBe` stringToBits "11111011"
markerToBits [0, 1, 2, 3, 4, 5, 7] `shouldBe` stringToBits "11111101"
markerToBits [0, 1, 2, 3, 4, 5, 6] `shouldBe` stringToBits "11111110"
it "All markers 0 .. 8 should produce one almost full byte and one near empty byte" $
markerToBits [0, 1, 2, 3, 4, 5, 6, 7, 8] `shouldBe` stringToBits "11111111 10000000"
it "Matching bits for bytes" $
runListConduit [pack [0x80], pack [0xff], pack [0x01]] byteStringToBits `shouldBe`
stringToBits "00000001 11111111 10000000"
it "Every interesting token should produce a marker" $
jsonToken2Markers2 [
(ParseDelta (Offset 0) (Offset 1), JsonTokenBraceL),
(ParseDelta (Offset 1) (Offset 2), JsonTokenBraceL),
(ParseDelta (Offset 2) (Offset 3), JsonTokenBraceR),
(ParseDelta (Offset 3) (Offset 4), JsonTokenBraceR)] `shouldBe` [0, 1, 2, 3]
describe "When converting Json to tokens to markers to bits" $ do
it "Empty Json should produce no bits" $
jsonToBits [""] `shouldBe` []
it "Spaces and newlines should produce no bits" $
jsonToBits [" \n \r \t "] `shouldBe` []
it "number at beginning should produce one bit" $
jsonToBits ["1234 "] `shouldBe` stringToBits "10000000"
it "false at beginning should produce one bit" $
jsonToBits ["false "] `shouldBe` stringToBits "10000000"
it "true at beginning should produce one bit" $
jsonToBits ["true "] `shouldBe` stringToBits "10000000"
it "string at beginning should produce one bit" $
jsonToBits ["\"hello\" "] `shouldBe` stringToBits "10000000"
it "left brace at beginning should produce one bit" $
jsonToBits ["{ "] `shouldBe` stringToBits "10000000"
it "right brace at beginning should produce one bit" $
jsonToBits ["} "] `shouldBe` stringToBits "10000000"
it "left bracket at beginning should produce one bit" $
jsonToBits ["[ "] `shouldBe` stringToBits "10000000"
it "right bracket at beginning should produce one bit" $
jsonToBits ["] "] `shouldBe` stringToBits "10000000"
it "right bracket at beginning should produce one bit" $
jsonToBits [": "] `shouldBe` stringToBits "10000000"
it "right bracket at beginning should produce one bit" $
jsonToBits [", "] `shouldBe` stringToBits "10000000"
it "Four consecutive braces should produce four bits" $
jsonToBits ["{{}}"] `shouldBe` stringToBits "11110000"
it "Four spread out braces should produce four spread out bits" $
jsonToBits [" { { } } "] `shouldBe` stringToBits "01010101"
|
haskell-works/conduit-succinct-json
|
test/Data/Conduit/Succinct/JsonSpec.hs
|
bsd-3-clause
| 5,764 | 0 | 15 | 1,166 | 1,613 | 850 | 763 | 104 | 2 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.CullDistance
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.CullDistance (
-- * Extension Support
glGetARBCullDistance,
gl_ARB_cull_distance,
-- * Enums
pattern GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES,
pattern GL_MAX_CULL_DISTANCES
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/ARB/CullDistance.hs
|
bsd-3-clause
| 699 | 0 | 5 | 95 | 52 | 39 | 13 | 8 | 0 |
{-# OPTIONS -XDeriveDataTypeable #-}
-- this program imput numbers and calculate their factorials. The workflow control a record all the inputs and outputs
-- so that when the program restart, all the previous results are shown.
-- if the program abort by a runtime error or a power failure, the program will still work
-- enter 0 for exit and finalize the workflow (all the intermediate data will be erased)
-- enter any alphanumeric character for aborting and then re-start.
module Main where
import Control.Workflow
import Data.Typeable
import Data.Binary
import Data.RefSerialize
import Data.Maybe
fact 0 =1
fact n= n * fact (n-1)
-- now the workflow versión
data Fact= Fact Integer Integer deriving (Typeable, Read, Show)
instance Binary Fact where
put (Fact n v)= put n >> put v
get= do
n <- get
v <- get
return $ Fact n v
instance Serialize Fact where
showp= showpBinary
readp= readpBinary
factorials = do
all <- getAll
let lfacts = mapMaybe safeFromIDyn all :: [Fact]
unsafeIOtoWF $ putStrLn "Factorials calculated so far:"
unsafeIOtoWF $ mapM (\fct -> print fct) lfacts
factLoop (Fact 0 1)
where
factLoop fct= do
nf <- plift $ do -- plift == step
putStrLn "give me a number if you enter a letter or 0, the program will abort. Then, please restart to see how the program continues"
str<- getLine
let n= read str :: Integer -- if you enter alphanumeric characters the program will abort. please restart
let fct= fact n
print fct
return $ Fact n fct
case nf of
Fact 0 _ -> do
unsafeIOtoWF $ print "bye"
return (Fact 0 0)
_ -> factLoop nf
main = exec1 "factorials" factorials
|
agocorona/Workflow
|
Demos/fact.hs
|
bsd-3-clause
| 1,741 | 6 | 18 | 436 | 385 | 194 | 191 | 39 | 2 |
module FillingJars
( getlines,
startjars
) where
getlines :: Int -> IO Integer
getlines m
| m <= 0 = do return 0
| otherwise = do
x_temp <- getLine
let x_t = words x_temp
let a = read $ x_t!!0 :: Integer
let b = read $ x_t!!1 :: Integer
let k = read $ x_t!!2 :: Integer
total <- getlines (m-1)
let ret = total + (b - a + 1)*k
return ret
startjars :: Int -> IO ()
startjars cnt
| cnt <= 0 = putStrLn ""
| otherwise = do
x_temp <- getLine
let x_t = words x_temp
let n = read $ x_t!!0 :: Integer
let m = read $ x_t!!1 :: Int
total <- getlines m
let t = total `div` n
print t
|
zuoqin/hackerrank
|
src/FillingJars.hs
|
bsd-3-clause
| 741 | 0 | 15 | 299 | 321 | 152 | 169 | 26 | 1 |
module Module3.Task17 where
-- system code
coins :: (Ord a, Num a) => [a]
coins = [2, 3, 7]
-- solution code
change :: (Ord a, Num a) => a -> [[a]]
change 0 = [[]]
change s = [coin:ch | coin <- coins, coin <= s, ch <- (change $ s - coin)]
|
dstarcev/stepic-haskell
|
src/Module3/Task17.hs
|
bsd-3-clause
| 241 | 0 | 10 | 56 | 138 | 78 | 60 | 6 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module CommandLine (readOptions) where
import Control.Applicative ((<$>), (<*>))
import Control.Arrow (first)
import Control.Monad (unless)
import Data.Maybe (fromMaybe)
import System.Console.GetOpt (getOpt, ArgOrder(..), OptDescr(..), ArgDescr(..))
import System.Exit (exitFailure)
import Network (PortID(..), PortNumber)
import Network.PeyoTLS.ReadFile ( CertSecretKey,
readKey, readCertificateChain, readCertificateStore)
import Network.PeyoTLS.Server (CipherSuite(..), KeyExchange(..), BulkEncryption(..))
import qualified Data.X509 as X509
import qualified Data.X509.CertificateStore as X509
readOptions :: [String] -> IO (
PortID,
[CipherSuite],
(CertSecretKey, X509.CertificateChain),
(CertSecretKey, X509.CertificateChain),
Maybe X509.CertificateStore,
FilePath )
readOptions args = do
let (os, as, es) = getOpt Permute options args
unless (null es) $ mapM_ putStr es >> exitFailure
unless (null as) $ putStrLn ("naked args: " ++ show as) >> exitFailure
opts <- either ((>> exitFailure) . putStr) return $ construct os
let prt = PortNumber 443 `fromMaybe` optPort opts
css = maybe id (drop . fromEnum) (optLevel opts) cipherSuites
td = "test" `fromMaybe` optTestDirectory opts
rkf = "localhost.key" `fromMaybe` optRsaKeyFile opts
rcf = "localhost.crt" `fromMaybe` optRsaCertFile opts
ekf = "localhost_ecdsa.key" `fromMaybe` optEcKeyFile opts
ecf = "localhost_ecdsa.cert" `fromMaybe` optEcCertFile opts
rsa <- (,) <$> readKey rkf <*> readCertificateChain rcf
ec <- (,) <$> readKey ekf <*> readCertificateChain ecf
mcs <- if optDisableClientCert opts then return Nothing else Just <$>
readCertificateStore ["cacert.pem"]
return (prt, css, rsa, ec, mcs, td)
data Options = Options {
optPort :: Maybe PortID,
optLevel :: Maybe CipherSuiteLevel,
optRsaKeyFile :: Maybe FilePath,
optRsaCertFile :: Maybe FilePath,
optEcKeyFile :: Maybe FilePath,
optEcCertFile :: Maybe FilePath,
optDisableClientCert :: Bool,
optTestDirectory :: Maybe FilePath }
deriving Show
nullOptions :: Options
nullOptions = Options {
optPort = Nothing,
optLevel = Nothing,
optRsaKeyFile = Nothing,
optRsaCertFile = Nothing,
optEcKeyFile = Nothing,
optEcCertFile = Nothing,
optDisableClientCert = False,
optTestDirectory = Nothing }
construct :: [Option] -> Either String Options
construct [] = return nullOptions
construct (o : os) = do
c <- construct os
case o of
OptPort p -> ck (optPort c) >> return c { optPort = Just p }
OptDisableClientCert -> if optDisableClientCert c
then Left "CommandLine.construct: duplicated -d options\n"
else return c { optDisableClientCert = True }
OptLevel (NoLevel l) -> Left $
"CommandLine.construct: no such level " ++ show l ++ "\n"
OptLevel csl -> ck (optLevel c) >> return c { optLevel = Just csl }
OptTestDirectory td -> ck (optTestDirectory c) >>
return c { optTestDirectory = Just td }
OptRsaKeyFile kf -> ck (optRsaKeyFile c) >>
return c { optRsaKeyFile = Just kf }
OptRsaCertFile cf -> ck (optRsaCertFile c) >>
return c { optRsaCertFile = Just cf }
OptEcKeyFile ekf -> ck (optEcKeyFile c) >>
return c { optEcKeyFile = Just ekf }
OptEcCertFile ecf -> ck (optEcCertFile c) >>
return c { optEcCertFile = Just ecf }
where
ck :: Show a => Maybe a -> Either String ()
ck = maybe (Right ()) (Left . ("Can't set: already " ++) . (++ "\n") . show)
data Option
= OptPort PortID
| OptLevel CipherSuiteLevel
| OptRsaKeyFile FilePath
| OptRsaCertFile FilePath
| OptEcKeyFile FilePath
| OptEcCertFile FilePath
| OptDisableClientCert
| OptTestDirectory FilePath
deriving (Show, Eq)
options :: [OptDescr Option]
options = [
Option "p" ["port"]
(ReqArg (OptPort . PortNumber . read) "port number")
"set port number",
Option "l" ["level"]
(ReqArg (OptLevel . readCipherSuiteLevel) "cipher suite level")
"set cipher suite level",
Option "k" ["rsa-key-file"]
(ReqArg OptRsaKeyFile "RSA key file") "set RSA key file",
Option "c" ["rsa-cert-file"]
(ReqArg OptRsaCertFile "RSA cert file") "set RSA cert file",
Option "K" ["ecdsa-key-file"]
(ReqArg OptEcKeyFile "ECDSA key file") "set ECDSA key file",
Option "C" ["ecdsa-cert-file"]
(ReqArg OptEcCertFile "ECDSA cert file") "set ECDSA cert file",
Option "d" ["disable-client-cert"]
(NoArg OptDisableClientCert) "disable client certification",
Option "t" ["test-directory"]
(ReqArg OptTestDirectory "test directory") "set test directory" ]
instance Read PortNumber where
readsPrec n = map (first (fromIntegral :: Int -> PortNumber)) . readsPrec n
data CipherSuiteLevel
= ToEcdsa256 | ToEcdsa | ToEcdhe256 | ToEcdhe
| ToDhe256 | ToDhe | ToRsa256 | ToRsa | NoLevel String
deriving (Show, Eq)
instance Enum CipherSuiteLevel where
toEnum 0 = ToEcdsa256
toEnum 1 = ToEcdsa
toEnum 2 = ToEcdhe256
toEnum 3 = ToEcdhe
toEnum 4 = ToDhe256
toEnum 5 = ToDhe
toEnum 6 = ToRsa256
toEnum 7 = ToRsa
toEnum _ = NoLevel ""
fromEnum ToEcdsa256 = 0
fromEnum ToEcdsa = 1
fromEnum ToEcdhe256 = 2
fromEnum ToEcdhe = 3
fromEnum ToDhe256 = 4
fromEnum ToDhe = 5
fromEnum ToRsa256 = 6
fromEnum ToRsa = 7
fromEnum (NoLevel _) = 8
readCipherSuiteLevel :: String -> CipherSuiteLevel
readCipherSuiteLevel "ecdsa256" = ToEcdsa256
readCipherSuiteLevel "ecdsa" = ToEcdsa
readCipherSuiteLevel "ecdhe256" = ToEcdhe256
readCipherSuiteLevel "ecdhe" = ToEcdhe
readCipherSuiteLevel "dhe256" = ToDhe256
readCipherSuiteLevel "dhe" = ToDhe
readCipherSuiteLevel "rsa256" = ToRsa256
readCipherSuiteLevel "rsa" = ToRsa
readCipherSuiteLevel l = NoLevel l
cipherSuites :: [CipherSuite]
cipherSuites = [
CipherSuite ECDHE_ECDSA AES_128_CBC_SHA256,
CipherSuite ECDHE_ECDSA AES_128_CBC_SHA,
CipherSuite ECDHE_RSA AES_128_CBC_SHA256,
CipherSuite ECDHE_RSA AES_128_CBC_SHA,
CipherSuite DHE_RSA AES_128_CBC_SHA256,
CipherSuite DHE_RSA AES_128_CBC_SHA,
CipherSuite RSA AES_128_CBC_SHA256,
CipherSuite RSA AES_128_CBC_SHA ]
|
YoshikuniJujo/forest
|
subprojects/tls-analysis/server/CommandLine.hs
|
bsd-3-clause
| 5,968 | 220 | 14 | 978 | 1,935 | 1,045 | 890 | 158 | 10 |
{-# LANGUAGE CPP #-}
-- | HPACK(<https://tools.ietf.org/html/rfc7541>) encoding and decoding a header list.
module Network.HPACK (
-- * Encoding and decoding
encodeHeader
, decodeHeader
-- * Encoding and decoding with token
, encodeTokenHeader
, decodeTokenHeader
-- * DynamicTable
, DynamicTable
, defaultDynamicTableSize
, newDynamicTableForEncoding
, newDynamicTableForDecoding
, withDynamicTableForEncoding
, withDynamicTableForDecoding
, setLimitForEncoding
-- * Strategy for encoding
, CompressionAlgo(..)
, EncodeStrategy(..)
, defaultEncodeStrategy
-- * Errors
, DecodeError(..)
, BufferOverrun(..)
-- * Headers
, HeaderList
, Header
, HeaderName
, HeaderValue
, TokenHeaderList
, TokenHeader
-- * Value table
, ValueTable
, HeaderTable
, getHeaderValue
, toHeaderTable
-- * Basic types
, Size
, Index
, Buffer
, BufferSize
-- * Re-exports
, original
, foldedCase
, mk
) where
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative ((<$>))
#endif
import Data.CaseInsensitive
import Network.HPACK.HeaderBlock
import Network.HPACK.Table
import Network.HPACK.Types
-- | Default dynamic table size.
-- The value is 4,096 bytes: an array has 128 entries.
--
-- >>> defaultDynamicTableSize
-- 4096
defaultDynamicTableSize :: Int
defaultDynamicTableSize = 4096
|
kazu-yamamoto/http2
|
Network/HPACK.hs
|
bsd-3-clause
| 1,358 | 0 | 5 | 259 | 186 | 130 | 56 | 42 | 1 |
module Main (main) where
import qualified Data.ByteString as B
--import Language.C
import Language.CIL
import System.Environment
--import Compile
--import Verify
version = "0.2.0"
main :: IO ()
main = do
args <- getArgs
case args of
[] -> help
(a:_) | elem a ["help", "-h", "--help", "-help"] -> help
| elem a ["version", "-v", "--version"] -> putStrLn $ "afv " ++ version
["example"] -> example
["header"] -> header
["verify", file] -> do
a <- if file == "-" then B.getContents else B.readFile file
let cil = parseCIL (if file == "-" then "stdin" else file) a
print cil
--model <- compile $ parse (if file == "-" then "stdin" else file) a
--verify "yices" 20 model
_ -> help
header :: IO ()
header = do
putStrLn "writing AFV header file (afv.h) ..."
writeFile "afv.h" $ unlines
[ "#ifndef AFV"
, "#include <assert.h>"
, "#define assume assert"
, "#endif"
]
example :: IO ()
example = do
header
putStrLn "writing example design (example.c) ..."
putStrLn "verify with: afv verify -k 15 example.c"
writeFile "example.c" $ unlines
[ "// Provides assert and assume functions."
, "#include \"afv.h\""
, ""
, "// Periodic function for verification. Implements a simple rolling counter."
, "void example () {"
, ""
, " // The rolling counter."
, " static int counter = 0;"
, ""
, " // Assertions."
, " GreaterThanOrEqualTo0: assert(counter >= 0); // The 'counter' must always be greater than or equal to 0."
, " LessThan10: assert(counter < 10); // The 'counter' must always be less than 10."
, ""
, " // Implementation 1."
, " if (counter == 10)"
, " counter = 0;"
, " else"
, " counter++;"
, ""
, " // Implementation 2."
, " // if (counter == 9)"
, " // counter = 0;"
, " // else"
, " // counter = counter + 1;"
, ""
, " // Implementation 3."
, " // if (counter >= 9)"
, " // counter = 0;"
, " // else"
, " // counter++;"
, ""
, " // Implementation 4."
, " // if (counter >= 9 || counter < 0)"
, " // counter = 0;"
, " // else"
, " // counter++;"
, ""
, " // Implementation 5."
, " // counter = (counter + 1) % 10;"
, ""
, "}"
, ""
, "void main() {"
, " while (1) example();"
, "}"
, ""
]
help :: IO ()
help = putStrLn $ unlines
[ ""
, "NAME"
, " afv - Atom Formal Verifier"
, ""
, "VERSION"
, " " ++ version
, ""
, "SYNOPSIS"
, " afv verify ( <file> | - )"
, " afv header"
, " afv example"
, ""
, "DESCRIPTION"
, " Afv performs bounded model checking and k-induction on C code with a signle infinite loop."
, " Requires GCC for C preprocessing and the Yices SMT solver."
, ""
, "COMMANDS"
, " verify ( <file> | - )"
, " Runs verification on a C preprocessed file (CPP) or from stdin."
, ""
, " header"
, " Writes AFV's header file (afv.h), which provides the 'assert' and 'assume' functions."
, ""
, " example"
, " Writes an example design (example.c). Verify with:"
, " afv verify -k 15 example.c"
, ""
]
|
tomahawkins/afv
|
src/AFV.hs
|
bsd-3-clause
| 3,244 | 0 | 18 | 1,003 | 572 | 329 | 243 | 108 | 8 |
{-# LANGUAGE CPP #-}
module Feldspar.IO.Frontend
( module Feldspar.IO.Frontend
, ExternalCompilerOpts (..)
, defaultExtCompilerOpts
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Data.Ix
import Data.Monoid
import Data.Proxy
import Text.Printf (PrintfArg)
import qualified Control.Monad.Operational.Higher as Imp
import Language.Embedded.Imperative.CMD (FileCMD (..))
import Language.Embedded.Imperative.Frontend.General
import qualified Language.Embedded.Imperative as Imp
import qualified Language.Embedded.Imperative.CMD as Imp
import Language.Embedded.Backend.C (ExternalCompilerOpts (..), defaultExtCompilerOpts)
import qualified Language.Embedded.Backend.C as Imp
import Feldspar (Type, Data, WordN (..))
import Feldspar.Compiler.FromImperative (feldsparCIncludes)
import Feldspar.IO.CMD
deriving instance PrintfArg WordN -- TODO Should go into feldspar-language
deriving instance Read WordN -- TODO Should go into feldspar-language
deriving instance Formattable WordN -- TODO Should go into feldspar-compiler-shim
-- | Program monad
newtype Program a = Program {unProgram :: Imp.Program FeldCMD a}
deriving (Functor, Applicative, Monad)
--------------------------------------------------------------------------------
-- * References
--------------------------------------------------------------------------------
-- | Create an uninitialized reference
newRef :: Type a => Program (Ref a)
newRef = Program Imp.newRef
-- | Create an initialized reference
initRef :: Type a => Data a -> Program (Ref a)
initRef = Program . Imp.initRef
-- | Get the contents of a reference
getRef :: Type a => Ref a -> Program (Data a)
getRef = Program . Imp.getRef
-- | Set the contents of a reference
setRef :: Type a => Ref a -> Data a -> Program ()
setRef r = Program . Imp.setRef r
-- | Modify the contents of reference
modifyRef :: Type a => Ref a -> (Data a -> Data a) -> Program ()
modifyRef r f = Program $ Imp.modifyRef r f
-- | Freeze the contents of reference (only safe if the reference is not updated
-- as long as the resulting value is alive)
unsafeFreezeRef :: Type a => Ref a -> Program (Data a)
unsafeFreezeRef = Program . Imp.unsafeFreezeRef
-- | Compute and share a value. Like 'share' but using the 'Program' monad
-- instead of a higher-order interface.
shareVal :: Type a => Data a -> Program (Data a)
shareVal a = initRef a >>= unsafeFreezeRef
--------------------------------------------------------------------------------
-- * Arrays
--------------------------------------------------------------------------------
-- | Create an uninitialized array
newArr :: (Type a, Type i, Integral i, Ix i) => Data i -> Program (Arr i a)
newArr n = Program $ Imp.newArr n
-- | Get an element of an array
getArr :: (Type a, Type i, Integral i, Ix i) =>
Data i -> Arr i a -> Program (Data a)
getArr i arr = Program $ Imp.getArr i arr
-- | Set an element of an array
setArr :: (Type a, Type i, Integral i, Ix i) =>
Data i -> Data a -> Arr i a -> Program ()
setArr i a arr = Program $ Imp.setArr i a arr
-- | Copy the contents of an array to another array. The number of elements to
-- copy must not be greater than the number of allocated elements in either
-- array.
copyArr :: (Type a, Type i, Integral i, Ix i)
=> Arr i a -- ^ Destination
-> Arr i a -- ^ Source
-> Data i -- ^ Number of elements
-> Program ()
copyArr arr1 arr2 len = Program $ Imp.copyArr arr1 arr2 len
thawArr :: (Type a, Num n, Ix n) => Data [a] -> Program (Arr n a)
thawArr = Program . Imp.singleInj . ThawArr
unsafeThawArr :: (Type a, Num n, Ix n) => Data [a] -> Program (Arr n a)
unsafeThawArr = Program . Imp.singleInj . UnsafeThawArr
freezeArr :: (Type a, Num n, Ix n) => Arr n a -> Data n -> Program (Data [a])
freezeArr a n = Program $ Imp.singleInj $ FreezeArr a n
--------------------------------------------------------------------------------
-- * Control flow
--------------------------------------------------------------------------------
-- | Conditional statement
iff
:: Data Bool -- ^ Condition
-> Program () -- ^ True branch
-> Program () -- ^ False branch
-> Program ()
iff b t f = Program $ Imp.iff b (unProgram t) (unProgram f)
-- | Conditional statement that returns an expression
ifE :: Type a
=> Data Bool -- ^ Condition
-> Program (Data a) -- ^ True branch
-> Program (Data a) -- ^ False branch
-> Program (Data a)
ifE b t f = Program $ Imp.ifE b (unProgram t) (unProgram f)
-- | For loop
for :: (Integral n, Type n)
=> IxRange (Data n) -- ^ Index range
-> (Data n -> Program ()) -- ^ Loop body
-> Program ()
for range body = Program $ Imp.for range (unProgram . body)
-- | While loop
while
:: Program (Data Bool) -- ^ Continue condition
-> Program () -- ^ Loop body
-> Program ()
while b t = Program $ Imp.while (unProgram b) (unProgram t)
-- | Assertion
assert
:: Data Bool -- ^ Expression that should be true
-> String -- ^ Message in case of failure
-> Program ()
assert cond msg = Program $ Imp.assert cond msg
-- | Break out from a loop
break :: Program ()
break = Program Imp.break
--------------------------------------------------------------------------------
-- * File handling
--------------------------------------------------------------------------------
-- | Open a file
fopen :: FilePath -> IOMode -> Program Handle
fopen file = Program . Imp.fopen file
-- | Close a file
fclose :: Handle -> Program ()
fclose = Program . Imp.fclose
-- | Check for end of file
feof :: Handle -> Program (Data Bool)
feof = Program . Imp.feof
class PrintfType r
where
fprf :: Handle -> String -> [Imp.PrintfArg Data] -> r
instance (a ~ ()) => PrintfType (Program a)
where
fprf h form as = Program $ Imp.singleE $ FPrintf h form (reverse as)
instance (Formattable a, Type a, PrintfType r) => PrintfType (Data a -> r)
where
fprf h form as = \a -> fprf h form (Imp.PrintfArg a : as)
-- | Print to a handle. Accepts a variable number of arguments.
fprintf :: PrintfType r => Handle -> String -> r
fprintf h format = fprf h format []
-- | Put a single value to a handle
fput :: (Formattable a, Type a)
=> Handle
-> String -- Prefix
-> Data a -- Expression to print
-> String -- Suffix
-> Program ()
fput h pre a post = Program $ Imp.fput h pre a post
-- | Get a single value from a handle
fget :: (Formattable a, Type a) => Handle -> Program (Data a)
fget = Program . Imp.fget
-- | Print to @stdout@. Accepts a variable number of arguments.
printf :: PrintfType r => String -> r
printf = fprintf Imp.stdout
--------------------------------------------------------------------------------
-- * Abstract objects
--------------------------------------------------------------------------------
newObject
:: String -- ^ Object type
-> Program Object
newObject = Program . Imp.newObject
initObject
:: String -- ^ Function name
-> String -- ^ Object type
-> [FunArg Data] -- ^ Arguments
-> Program Object
initObject fun ty args = Program $ Imp.initObject fun ty args
initUObject
:: String -- ^ Function name
-> String -- ^ Object type
-> [FunArg Data] -- ^ Arguments
-> Program Object
initUObject fun ty args = Program $ Imp.initUObject fun ty args
--------------------------------------------------------------------------------
-- * External function calls (C-specific)
--------------------------------------------------------------------------------
-- | Add an @#include@ statement to the generated code
addInclude :: String -> Program ()
addInclude = Program . Imp.addInclude
-- | Add a global definition to the generated code
--
-- Can be used conveniently as follows:
--
-- > {-# LANGUAGE QuasiQuotes #-}
-- >
-- > import Feldspar.IO
-- >
-- > prog = do
-- > ...
-- > addDefinition myCFunction
-- > ...
-- > where
-- > myCFunction = [cedecl|
-- > void my_C_function( ... )
-- > {
-- > // C code
-- > // goes here
-- > }
-- > |]
addDefinition :: Definition -> Program ()
addDefinition = Program . Imp.addDefinition
-- | Declare an external function
addExternFun :: forall proxy res . Type res
=> String -- ^ Function name
-> proxy res -- ^ Proxy for expression and result type
-> [FunArg Data] -- ^ Arguments (only used to determine types)
-> Program ()
addExternFun fun res args = Program $ Imp.addExternFun fun res' args
where
res' = Proxy :: Proxy (Data res)
-- | Declare an external procedure
addExternProc
:: String -- ^ Procedure name
-> [FunArg Data] -- ^ Arguments (only used to determine types)
-> Program ()
addExternProc proc args = Program $ Imp.addExternProc proc args
-- | Call a function
callFun :: Type a
=> String -- ^ Function name
-> [FunArg Data] -- ^ Arguments
-> Program (Data a)
callFun fun as = Program $ Imp.callFun fun as
-- | Call a procedure
callProc
:: String -- ^ Function name
-> [FunArg Data] -- ^ Arguments
-> Program ()
callProc fun as = Program $ Imp.callProc fun as
-- | Declare and call an external function
externFun :: Type res
=> String -- ^ Procedure name
-> [FunArg Data] -- ^ Arguments
-> Program (Data res)
externFun fun args = Program $ Imp.externFun fun args
-- | Declare and call an external procedure
externProc
:: String -- ^ Procedure name
-> [FunArg Data] -- ^ Arguments
-> Program ()
externProc proc args = Program $ Imp.externProc proc args
-- | Get current time as number of seconds passed today
getTime :: Program (Data Double)
getTime = Program Imp.getTime
strArg :: String -> FunArg Data
strArg = Imp.strArg
valArg :: Type a => Data a -> FunArg Data
valArg = Imp.valArg
refArg :: Type a => Ref a -> FunArg Data
refArg = Imp.refArg
arrArg :: Type a => Arr n a -> FunArg Data
arrArg = Imp.arrArg
objArg :: Object -> FunArg Data
objArg = Imp.objArg
addr :: FunArg Data -> FunArg Data
addr = Imp.addr
--------------------------------------------------------------------------------
-- * Back ends
--------------------------------------------------------------------------------
-- | Interpret a program in the 'IO' monad
runIO :: Program a -> IO a
runIO = Imp.runIO . unProgram
-- | Like 'runIO' but with explicit input/output connected to @stdin@/@stdout@
captureIO
:: Program a -- ^ Program to run
-> String -- ^ Faked @stdin@
-> IO String -- ^ Captured @stdout@
captureIO = Imp.captureIO . unProgram
-- | Compile a program to C code represented as a string. To compile the
-- resulting C code, use something like
--
-- > gcc -std=c99 -Ipath/to/feldspar-compiler/lib/Feldspar/C YOURPROGRAM.c
--
-- For programs that make use of the primitives in "Feldspar.Concurrent", some
-- extra flags are needed:
--
-- > gcc -std=c99 -Ipath/to/feldspar-compiler/lib/Feldspar/C -Ipath/to/imperative-edsl/include path/to/imperative-edsl/csrc/chan.c -lpthread YOURPROGRAM.c
compile :: Program a -> String
compile = Imp.compile . unProgram
-- | Compile a program to C code and print it on the screen. To compile the
-- resulting C code, use something like
--
-- > gcc -std=c99 -Ipath/to/feldspar-compiler/lib/Feldspar/C YOURPROGRAM.c
--
-- For programs that make use of the primitives in "Feldspar.Concurrent", some
-- extra flags are needed:
--
-- > gcc -std=c99 -Ipath/to/feldspar-compiler/lib/Feldspar/C -Ipath/to/imperative-edsl/include path/to/imperative-edsl/csrc/chan.c -lpthread YOURPROGRAM.c
icompile :: Program a -> IO ()
icompile = putStrLn . compile
addFeldsparCIncludes :: ExternalCompilerOpts -> IO ExternalCompilerOpts
addFeldsparCIncludes opts = do
feldLib <- feldsparCIncludes
return $ opts <> mempty { externalFlagsPre = ["-I" ++ feldLib] }
-- | Generate C code and use GCC to check that it compiles (no linking)
compileAndCheck' :: ExternalCompilerOpts -> Program a -> IO ()
compileAndCheck' opts prog = do
opts' <- addFeldsparCIncludes opts
Imp.compileAndCheck' opts' (unProgram prog)
-- | Generate C code and use GCC to check that it compiles (no linking)
compileAndCheck :: Program a -> IO ()
compileAndCheck = compileAndCheck' mempty
-- | Generate C code, use GCC to compile it, and run the resulting executable
runCompiled' :: ExternalCompilerOpts -> Program a -> IO ()
runCompiled' opts prog = do
opts' <- addFeldsparCIncludes opts
Imp.runCompiled' opts' (unProgram prog)
-- | Generate C code, use GCC to compile it, and run the resulting executable
runCompiled :: Program a -> IO ()
runCompiled = runCompiled' mempty
-- | Like 'runCompiled'' but with explicit input/output connected to
-- @stdin@/@stdout@
captureCompiled'
:: ExternalCompilerOpts
-> Program a -- ^ Program to run
-> String -- ^ Input to send to @stdin@
-> IO String -- ^ Result from @stdout@
captureCompiled' opts prog inp = do
opts' <- addFeldsparCIncludes opts
Imp.captureCompiled' opts' (unProgram prog) inp
-- | Like 'runCompiled' but with explicit input/output connected to
-- @stdin@/@stdout@
captureCompiled
:: Program a -- ^ Program to run
-> String -- ^ Input to send to @stdin@
-> IO String -- ^ Result from @stdout@
captureCompiled = captureCompiled' mempty
-- | Compare the content written to 'stdout' from interpretation in 'IO' and
-- from running the compiled C code
compareCompiled'
:: ExternalCompilerOpts
-> Program a -- ^ Program to run
-> String -- ^ Input to send to @stdin@
-> IO ()
compareCompiled' opts prog inp = do
opts' <- addFeldsparCIncludes opts
Imp.compareCompiled' opts' (unProgram prog) inp
-- | Compare the content written to 'stdout' from interpretation in 'IO' and
-- from running the compiled C code
compareCompiled
:: Program a -- ^ Program to run
-> String -- ^ Input to send to @stdin@
-> IO ()
compareCompiled = compareCompiled' mempty
|
emilaxelsson/feldspar-io
|
src/Feldspar/IO/Frontend.hs
|
bsd-3-clause
| 14,031 | 0 | 12 | 2,861 | 3,225 | 1,701 | 1,524 | -1 | -1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module: $HEADER$
-- Description: Data type that represents name of a SCM (Source Code
-- Management) tool.
-- Copyright: (c) 2016 Peter Trško
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: experimental
-- Portability: GHC specific language extensions.
--
-- Data type that represents name of a SCM (Source Code Management) tool.
module YX.Type.DbConnection
( DbConnection(..)
, withSQLiteConn
)
where
import Data.Function (($))
import GHC.Generics (Generic)
import qualified Database.SQLite.Simple as SQLite (Connection)
-- | YX stores its global data about existing projects in a database. This data
-- type wraps lower level connection for more type safety.
newtype DbConnection = DbConnection SQLite.Connection
deriving (Generic)
-- | Use 'DbConnection' as a SQLite Simple 'SQLite.Connection'.
--
-- Example:
--
-- @
-- 'withSQLiteConn' conn $ \\c ->
-- SQLite.query_ c \"SELECT * FROM InterestingTable;\"
-- @
withSQLiteConn :: DbConnection -> (SQLite.Connection -> a) -> a
withSQLiteConn (DbConnection c) = ($ c)
|
trskop/yx
|
src/YX/Type/DbConnection.hs
|
bsd-3-clause
| 1,177 | 0 | 9 | 221 | 136 | 93 | 43 | 12 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
module VarEnv (
-- * Var, Id and TyVar environments (maps)
VarEnv, IdEnv, TyVarEnv, CoVarEnv, TyCoVarEnv,
-- ** Manipulating these environments
emptyVarEnv, unitVarEnv, mkVarEnv, mkVarEnv_Directly,
elemVarEnv, disjointVarEnv,
extendVarEnv, extendVarEnv_C, extendVarEnv_Acc, extendVarEnv_Directly,
extendVarEnvList,
plusVarEnv, plusVarEnv_C, plusVarEnv_CD, plusMaybeVarEnv_C,
plusVarEnvList, alterVarEnv,
delVarEnvList, delVarEnv, delVarEnv_Directly,
minusVarEnv, intersectsVarEnv,
lookupVarEnv, lookupVarEnv_NF, lookupWithDefaultVarEnv,
mapVarEnv, zipVarEnv,
modifyVarEnv, modifyVarEnv_Directly,
isEmptyVarEnv,
elemVarEnvByKey, lookupVarEnv_Directly,
filterVarEnv, filterVarEnv_Directly, restrictVarEnv,
partitionVarEnv,
-- * Deterministic Var environments (maps)
DVarEnv, DIdEnv, DTyVarEnv,
-- ** Manipulating these environments
emptyDVarEnv, mkDVarEnv,
dVarEnvElts,
extendDVarEnv, extendDVarEnv_C,
extendDVarEnvList,
lookupDVarEnv, elemDVarEnv,
isEmptyDVarEnv, foldDVarEnv,
mapDVarEnv, filterDVarEnv,
modifyDVarEnv,
alterDVarEnv,
plusDVarEnv, plusDVarEnv_C,
unitDVarEnv,
delDVarEnv,
delDVarEnvList,
minusDVarEnv,
partitionDVarEnv,
anyDVarEnv,
-- * The InScopeSet type
InScopeSet,
-- ** Operations on InScopeSets
emptyInScopeSet, mkInScopeSet, delInScopeSet,
extendInScopeSet, extendInScopeSetList, extendInScopeSetSet,
getInScopeVars, lookupInScope, lookupInScope_Directly,
unionInScope, elemInScopeSet, uniqAway,
varSetInScope,
unsafeGetFreshLocalUnique,
-- * The RnEnv2 type
RnEnv2,
-- ** Operations on RnEnv2s
mkRnEnv2, rnBndr2, rnBndrs2, rnBndr2_var,
rnOccL, rnOccR, inRnEnvL, inRnEnvR, rnOccL_maybe, rnOccR_maybe,
rnBndrL, rnBndrR, nukeRnEnvL, nukeRnEnvR, rnSwap,
delBndrL, delBndrR, delBndrsL, delBndrsR,
addRnInScopeSet,
rnEtaL, rnEtaR,
rnInScope, rnInScopeSet, lookupRnInScope,
rnEnvL, rnEnvR,
-- * TidyEnv and its operation
TidyEnv,
emptyTidyEnv, mkEmptyTidyEnv, delTidyEnvList
) where
import GhcPrelude
import qualified Data.IntMap.Strict as IntMap -- TODO: Move this to UniqFM
import OccName
import Name
import Var
import VarSet
import UniqSet
import UniqFM
import UniqDFM
import Unique
import Util
import Maybes
import Outputable
{-
************************************************************************
* *
In-scope sets
* *
************************************************************************
-}
-- | A set of variables that are in scope at some point
-- "Secrets of the Glasgow Haskell Compiler inliner" Section 3.2 provides
-- the motivation for this abstraction.
newtype InScopeSet = InScope VarSet
-- Note [Lookups in in-scope set]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- We store a VarSet here, but we use this for lookups rather than just
-- membership tests. Typically the InScopeSet contains the canonical
-- version of the variable (e.g. with an informative unfolding), so this
-- lookup is useful (see, for instance, Note [In-scope set as a
-- substitution]).
instance Outputable InScopeSet where
ppr (InScope s) =
text "InScope" <+>
braces (fsep (map (ppr . Var.varName) (nonDetEltsUniqSet s)))
-- It's OK to use nonDetEltsUniqSet here because it's
-- only for pretty printing
-- In-scope sets get big, and with -dppr-debug
-- the output is overwhelming
emptyInScopeSet :: InScopeSet
emptyInScopeSet = InScope emptyVarSet
getInScopeVars :: InScopeSet -> VarSet
getInScopeVars (InScope vs) = vs
mkInScopeSet :: VarSet -> InScopeSet
mkInScopeSet in_scope = InScope in_scope
extendInScopeSet :: InScopeSet -> Var -> InScopeSet
extendInScopeSet (InScope in_scope) v
= InScope (extendVarSet in_scope v)
extendInScopeSetList :: InScopeSet -> [Var] -> InScopeSet
extendInScopeSetList (InScope in_scope) vs
= InScope $ foldl' extendVarSet in_scope vs
extendInScopeSetSet :: InScopeSet -> VarSet -> InScopeSet
extendInScopeSetSet (InScope in_scope) vs
= InScope (in_scope `unionVarSet` vs)
delInScopeSet :: InScopeSet -> Var -> InScopeSet
delInScopeSet (InScope in_scope) v = InScope (in_scope `delVarSet` v)
elemInScopeSet :: Var -> InScopeSet -> Bool
elemInScopeSet v (InScope in_scope) = v `elemVarSet` in_scope
-- | Look up a variable the 'InScopeSet'. This lets you map from
-- the variable's identity (unique) to its full value.
lookupInScope :: InScopeSet -> Var -> Maybe Var
lookupInScope (InScope in_scope) v = lookupVarSet in_scope v
lookupInScope_Directly :: InScopeSet -> Unique -> Maybe Var
lookupInScope_Directly (InScope in_scope) uniq
= lookupVarSet_Directly in_scope uniq
unionInScope :: InScopeSet -> InScopeSet -> InScopeSet
unionInScope (InScope s1) (InScope s2)
= InScope (s1 `unionVarSet` s2)
varSetInScope :: VarSet -> InScopeSet -> Bool
varSetInScope vars (InScope s1) = vars `subVarSet` s1
{-
Note [Local uniques]
~~~~~~~~~~~~~~~~~~~~
Sometimes one must create conjure up a unique which is unique in a particular
context (but not necessarily globally unique). For instance, one might need to
create a fresh local identifier which does not shadow any of the locally
in-scope variables. For this we purpose we provide 'uniqAway'.
'uniqAway' is implemented in terms of the 'unsafeGetFreshLocalUnique'
operation, which generates an unclaimed 'Unique' from an 'InScopeSet'. To
ensure that we do not conflict with uniques allocated by future allocations
from 'UniqSupply's, Uniques generated by 'unsafeGetFreshLocalUnique' are
allocated into a dedicated region of the unique space (namely the X tag).
Note that one must be quite carefully when using uniques generated in this way
since they are only locally unique. In particular, two successive calls to
'uniqAway' on the same 'InScopeSet' will produce the same unique.
-}
-- | @uniqAway in_scope v@ finds a unique that is not used in the
-- in-scope set, and gives that to v. See Note [Local uniques].
uniqAway :: InScopeSet -> Var -> Var
-- It starts with v's current unique, of course, in the hope that it won't
-- have to change, and thereafter uses the successor to the last derived unique
-- found in the in-scope set.
uniqAway in_scope var
| var `elemInScopeSet` in_scope = uniqAway' in_scope var -- Make a new one
| otherwise = var -- Nothing to do
uniqAway' :: InScopeSet -> Var -> Var
-- This one *always* makes up a new variable
uniqAway' in_scope var
= setVarUnique var (unsafeGetFreshLocalUnique in_scope)
-- | @unsafeGetFreshUnique in_scope@ finds a unique that is not in-scope in the
-- given 'InScopeSet'. This must be used very carefully since one can very easily
-- introduce non-unique 'Unique's this way. See Note [Local uniques].
unsafeGetFreshLocalUnique :: InScopeSet -> Unique
unsafeGetFreshLocalUnique (InScope set)
| Just (uniq,_) <- IntMap.lookupLT (getKey maxLocalUnique) (ufmToIntMap $ getUniqSet set)
, let uniq' = mkLocalUnique uniq
, not $ uniq' `ltUnique` minLocalUnique
= incrUnique uniq'
| otherwise
= minLocalUnique
{-
************************************************************************
* *
Dual renaming
* *
************************************************************************
-}
-- | Rename Environment 2
--
-- When we are comparing (or matching) types or terms, we are faced with
-- \"going under\" corresponding binders. E.g. when comparing:
--
-- > \x. e1 ~ \y. e2
--
-- Basically we want to rename [@x@ -> @y@] or [@y@ -> @x@], but there are lots of
-- things we must be careful of. In particular, @x@ might be free in @e2@, or
-- y in @e1@. So the idea is that we come up with a fresh binder that is free
-- in neither, and rename @x@ and @y@ respectively. That means we must maintain:
--
-- 1. A renaming for the left-hand expression
--
-- 2. A renaming for the right-hand expressions
--
-- 3. An in-scope set
--
-- Furthermore, when matching, we want to be able to have an 'occurs check',
-- to prevent:
--
-- > \x. f ~ \y. y
--
-- matching with [@f@ -> @y@]. So for each expression we want to know that set of
-- locally-bound variables. That is precisely the domain of the mappings 1.
-- and 2., but we must ensure that we always extend the mappings as we go in.
--
-- All of this information is bundled up in the 'RnEnv2'
data RnEnv2
= RV2 { envL :: VarEnv Var -- Renaming for Left term
, envR :: VarEnv Var -- Renaming for Right term
, in_scope :: InScopeSet } -- In scope in left or right terms
-- The renamings envL and envR are *guaranteed* to contain a binding
-- for every variable bound as we go into the term, even if it is not
-- renamed. That way we can ask what variables are locally bound
-- (inRnEnvL, inRnEnvR)
mkRnEnv2 :: InScopeSet -> RnEnv2
mkRnEnv2 vars = RV2 { envL = emptyVarEnv
, envR = emptyVarEnv
, in_scope = vars }
addRnInScopeSet :: RnEnv2 -> VarSet -> RnEnv2
addRnInScopeSet env vs
| isEmptyVarSet vs = env
| otherwise = env { in_scope = extendInScopeSetSet (in_scope env) vs }
rnInScope :: Var -> RnEnv2 -> Bool
rnInScope x env = x `elemInScopeSet` in_scope env
rnInScopeSet :: RnEnv2 -> InScopeSet
rnInScopeSet = in_scope
-- | Retrieve the left mapping
rnEnvL :: RnEnv2 -> VarEnv Var
rnEnvL = envL
-- | Retrieve the right mapping
rnEnvR :: RnEnv2 -> VarEnv Var
rnEnvR = envR
rnBndrs2 :: RnEnv2 -> [Var] -> [Var] -> RnEnv2
-- ^ Applies 'rnBndr2' to several variables: the two variable lists must be of equal length
rnBndrs2 env bsL bsR = foldl2 rnBndr2 env bsL bsR
rnBndr2 :: RnEnv2 -> Var -> Var -> RnEnv2
-- ^ @rnBndr2 env bL bR@ goes under a binder @bL@ in the Left term,
-- and binder @bR@ in the Right term.
-- It finds a new binder, @new_b@,
-- and returns an environment mapping @bL -> new_b@ and @bR -> new_b@
rnBndr2 env bL bR = fst $ rnBndr2_var env bL bR
rnBndr2_var :: RnEnv2 -> Var -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndr2' but returns the new variable as well as the
-- new environment
rnBndr2_var (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL bR
= (RV2 { envL = extendVarEnv envL bL new_b -- See Note
, envR = extendVarEnv envR bR new_b -- [Rebinding]
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
-- Find a new binder not in scope in either term
new_b | not (bL `elemInScopeSet` in_scope) = bL
| not (bR `elemInScopeSet` in_scope) = bR
| otherwise = uniqAway' in_scope bL
-- Note [Rebinding]
-- If the new var is the same as the old one, note that
-- the extendVarEnv *deletes* any current renaming
-- E.g. (\x. \x. ...) ~ (\y. \z. ...)
--
-- Inside \x \y { [x->y], [y->y], {y} }
-- \x \z { [x->x], [y->y, z->x], {y,x} }
rnBndrL :: RnEnv2 -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndr2' but used when there's a binder on the left
-- side only.
rnBndrL (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL
= (RV2 { envL = extendVarEnv envL bL new_b
, envR = envR
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
new_b = uniqAway in_scope bL
rnBndrR :: RnEnv2 -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndr2' but used when there's a binder on the right
-- side only.
rnBndrR (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bR
= (RV2 { envR = extendVarEnv envR bR new_b
, envL = envL
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
new_b = uniqAway in_scope bR
rnEtaL :: RnEnv2 -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndrL' but used for eta expansion
-- See Note [Eta expansion]
rnEtaL (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL
= (RV2 { envL = extendVarEnv envL bL new_b
, envR = extendVarEnv envR new_b new_b -- Note [Eta expansion]
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
new_b = uniqAway in_scope bL
rnEtaR :: RnEnv2 -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndr2' but used for eta expansion
-- See Note [Eta expansion]
rnEtaR (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bR
= (RV2 { envL = extendVarEnv envL new_b new_b -- Note [Eta expansion]
, envR = extendVarEnv envR bR new_b
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
new_b = uniqAway in_scope bR
delBndrL, delBndrR :: RnEnv2 -> Var -> RnEnv2
delBndrL rn@(RV2 { envL = env, in_scope = in_scope }) v
= rn { envL = env `delVarEnv` v, in_scope = in_scope `extendInScopeSet` v }
delBndrR rn@(RV2 { envR = env, in_scope = in_scope }) v
= rn { envR = env `delVarEnv` v, in_scope = in_scope `extendInScopeSet` v }
delBndrsL, delBndrsR :: RnEnv2 -> [Var] -> RnEnv2
delBndrsL rn@(RV2 { envL = env, in_scope = in_scope }) v
= rn { envL = env `delVarEnvList` v, in_scope = in_scope `extendInScopeSetList` v }
delBndrsR rn@(RV2 { envR = env, in_scope = in_scope }) v
= rn { envR = env `delVarEnvList` v, in_scope = in_scope `extendInScopeSetList` v }
rnOccL, rnOccR :: RnEnv2 -> Var -> Var
-- ^ Look up the renaming of an occurrence in the left or right term
rnOccL (RV2 { envL = env }) v = lookupVarEnv env v `orElse` v
rnOccR (RV2 { envR = env }) v = lookupVarEnv env v `orElse` v
rnOccL_maybe, rnOccR_maybe :: RnEnv2 -> Var -> Maybe Var
-- ^ Look up the renaming of an occurrence in the left or right term
rnOccL_maybe (RV2 { envL = env }) v = lookupVarEnv env v
rnOccR_maybe (RV2 { envR = env }) v = lookupVarEnv env v
inRnEnvL, inRnEnvR :: RnEnv2 -> Var -> Bool
-- ^ Tells whether a variable is locally bound
inRnEnvL (RV2 { envL = env }) v = v `elemVarEnv` env
inRnEnvR (RV2 { envR = env }) v = v `elemVarEnv` env
lookupRnInScope :: RnEnv2 -> Var -> Var
lookupRnInScope env v = lookupInScope (in_scope env) v `orElse` v
nukeRnEnvL, nukeRnEnvR :: RnEnv2 -> RnEnv2
-- ^ Wipe the left or right side renaming
nukeRnEnvL env = env { envL = emptyVarEnv }
nukeRnEnvR env = env { envR = emptyVarEnv }
rnSwap :: RnEnv2 -> RnEnv2
-- ^ swap the meaning of left and right
rnSwap (RV2 { envL = envL, envR = envR, in_scope = in_scope })
= RV2 { envL = envR, envR = envL, in_scope = in_scope }
{-
Note [Eta expansion]
~~~~~~~~~~~~~~~~~~~~
When matching
(\x.M) ~ N
we rename x to x' with, where x' is not in scope in
either term. Then we want to behave as if we'd seen
(\x'.M) ~ (\x'.N x')
Since x' isn't in scope in N, the form (\x'. N x') doesn't
capture any variables in N. But we must nevertheless extend
the envR with a binding [x' -> x'], to support the occurs check.
For example, if we don't do this, we can get silly matches like
forall a. (\y.a) ~ v
succeeding with [a -> v y], which is bogus of course.
************************************************************************
* *
Tidying
* *
************************************************************************
-}
-- | Tidy Environment
--
-- When tidying up print names, we keep a mapping of in-scope occ-names
-- (the 'TidyOccEnv') and a Var-to-Var of the current renamings
type TidyEnv = (TidyOccEnv, VarEnv Var)
emptyTidyEnv :: TidyEnv
emptyTidyEnv = (emptyTidyOccEnv, emptyVarEnv)
mkEmptyTidyEnv :: TidyOccEnv -> TidyEnv
mkEmptyTidyEnv occ_env = (occ_env, emptyVarEnv)
delTidyEnvList :: TidyEnv -> [Var] -> TidyEnv
delTidyEnvList (occ_env, var_env) vs = (occ_env', var_env')
where
occ_env' = occ_env `delTidyOccEnvList` map (occNameFS . getOccName) vs
var_env' = var_env `delVarEnvList` vs
{-
************************************************************************
* *
\subsection{@VarEnv@s}
* *
************************************************************************
-}
-- | Variable Environment
type VarEnv elt = UniqFM elt
-- | Identifier Environment
type IdEnv elt = VarEnv elt
-- | Type Variable Environment
type TyVarEnv elt = VarEnv elt
-- | Type or Coercion Variable Environment
type TyCoVarEnv elt = VarEnv elt
-- | Coercion Variable Environment
type CoVarEnv elt = VarEnv elt
emptyVarEnv :: VarEnv a
mkVarEnv :: [(Var, a)] -> VarEnv a
mkVarEnv_Directly :: [(Unique, a)] -> VarEnv a
zipVarEnv :: [Var] -> [a] -> VarEnv a
unitVarEnv :: Var -> a -> VarEnv a
alterVarEnv :: (Maybe a -> Maybe a) -> VarEnv a -> Var -> VarEnv a
extendVarEnv :: VarEnv a -> Var -> a -> VarEnv a
extendVarEnv_C :: (a->a->a) -> VarEnv a -> Var -> a -> VarEnv a
extendVarEnv_Acc :: (a->b->b) -> (a->b) -> VarEnv b -> Var -> a -> VarEnv b
extendVarEnv_Directly :: VarEnv a -> Unique -> a -> VarEnv a
plusVarEnv :: VarEnv a -> VarEnv a -> VarEnv a
plusVarEnvList :: [VarEnv a] -> VarEnv a
extendVarEnvList :: VarEnv a -> [(Var, a)] -> VarEnv a
lookupVarEnv_Directly :: VarEnv a -> Unique -> Maybe a
filterVarEnv_Directly :: (Unique -> a -> Bool) -> VarEnv a -> VarEnv a
delVarEnv_Directly :: VarEnv a -> Unique -> VarEnv a
partitionVarEnv :: (a -> Bool) -> VarEnv a -> (VarEnv a, VarEnv a)
restrictVarEnv :: VarEnv a -> VarSet -> VarEnv a
delVarEnvList :: VarEnv a -> [Var] -> VarEnv a
delVarEnv :: VarEnv a -> Var -> VarEnv a
minusVarEnv :: VarEnv a -> VarEnv b -> VarEnv a
intersectsVarEnv :: VarEnv a -> VarEnv a -> Bool
plusVarEnv_C :: (a -> a -> a) -> VarEnv a -> VarEnv a -> VarEnv a
plusVarEnv_CD :: (a -> a -> a) -> VarEnv a -> a -> VarEnv a -> a -> VarEnv a
plusMaybeVarEnv_C :: (a -> a -> Maybe a) -> VarEnv a -> VarEnv a -> VarEnv a
mapVarEnv :: (a -> b) -> VarEnv a -> VarEnv b
modifyVarEnv :: (a -> a) -> VarEnv a -> Var -> VarEnv a
isEmptyVarEnv :: VarEnv a -> Bool
lookupVarEnv :: VarEnv a -> Var -> Maybe a
filterVarEnv :: (a -> Bool) -> VarEnv a -> VarEnv a
lookupVarEnv_NF :: VarEnv a -> Var -> a
lookupWithDefaultVarEnv :: VarEnv a -> a -> Var -> a
elemVarEnv :: Var -> VarEnv a -> Bool
elemVarEnvByKey :: Unique -> VarEnv a -> Bool
disjointVarEnv :: VarEnv a -> VarEnv a -> Bool
elemVarEnv = elemUFM
elemVarEnvByKey = elemUFM_Directly
disjointVarEnv = disjointUFM
alterVarEnv = alterUFM
extendVarEnv = addToUFM
extendVarEnv_C = addToUFM_C
extendVarEnv_Acc = addToUFM_Acc
extendVarEnv_Directly = addToUFM_Directly
extendVarEnvList = addListToUFM
plusVarEnv_C = plusUFM_C
plusVarEnv_CD = plusUFM_CD
plusMaybeVarEnv_C = plusMaybeUFM_C
delVarEnvList = delListFromUFM
delVarEnv = delFromUFM
minusVarEnv = minusUFM
intersectsVarEnv e1 e2 = not (isEmptyVarEnv (e1 `intersectUFM` e2))
plusVarEnv = plusUFM
plusVarEnvList = plusUFMList
lookupVarEnv = lookupUFM
filterVarEnv = filterUFM
lookupWithDefaultVarEnv = lookupWithDefaultUFM
mapVarEnv = mapUFM
mkVarEnv = listToUFM
mkVarEnv_Directly= listToUFM_Directly
emptyVarEnv = emptyUFM
unitVarEnv = unitUFM
isEmptyVarEnv = isNullUFM
lookupVarEnv_Directly = lookupUFM_Directly
filterVarEnv_Directly = filterUFM_Directly
delVarEnv_Directly = delFromUFM_Directly
partitionVarEnv = partitionUFM
restrictVarEnv env vs = filterVarEnv_Directly keep env
where
keep u _ = u `elemVarSetByKey` vs
zipVarEnv tyvars tys = mkVarEnv (zipEqual "zipVarEnv" tyvars tys)
lookupVarEnv_NF env id = case lookupVarEnv env id of
Just xx -> xx
Nothing -> panic "lookupVarEnv_NF: Nothing"
{-
@modifyVarEnv@: Look up a thing in the VarEnv,
then mash it with the modify function, and put it back.
-}
modifyVarEnv mangle_fn env key
= case (lookupVarEnv env key) of
Nothing -> env
Just xx -> extendVarEnv env key (mangle_fn xx)
modifyVarEnv_Directly :: (a -> a) -> UniqFM a -> Unique -> UniqFM a
modifyVarEnv_Directly mangle_fn env key
= case (lookupUFM_Directly env key) of
Nothing -> env
Just xx -> addToUFM_Directly env key (mangle_fn xx)
-- Deterministic VarEnv
-- See Note [Deterministic UniqFM] in UniqDFM for explanation why we need
-- DVarEnv.
-- | Deterministic Variable Environment
type DVarEnv elt = UniqDFM elt
-- | Deterministic Identifier Environment
type DIdEnv elt = DVarEnv elt
-- | Deterministic Type Variable Environment
type DTyVarEnv elt = DVarEnv elt
emptyDVarEnv :: DVarEnv a
emptyDVarEnv = emptyUDFM
dVarEnvElts :: DVarEnv a -> [a]
dVarEnvElts = eltsUDFM
mkDVarEnv :: [(Var, a)] -> DVarEnv a
mkDVarEnv = listToUDFM
extendDVarEnv :: DVarEnv a -> Var -> a -> DVarEnv a
extendDVarEnv = addToUDFM
minusDVarEnv :: DVarEnv a -> DVarEnv a' -> DVarEnv a
minusDVarEnv = minusUDFM
lookupDVarEnv :: DVarEnv a -> Var -> Maybe a
lookupDVarEnv = lookupUDFM
foldDVarEnv :: (a -> b -> b) -> b -> DVarEnv a -> b
foldDVarEnv = foldUDFM
mapDVarEnv :: (a -> b) -> DVarEnv a -> DVarEnv b
mapDVarEnv = mapUDFM
filterDVarEnv :: (a -> Bool) -> DVarEnv a -> DVarEnv a
filterDVarEnv = filterUDFM
alterDVarEnv :: (Maybe a -> Maybe a) -> DVarEnv a -> Var -> DVarEnv a
alterDVarEnv = alterUDFM
plusDVarEnv :: DVarEnv a -> DVarEnv a -> DVarEnv a
plusDVarEnv = plusUDFM
plusDVarEnv_C :: (a -> a -> a) -> DVarEnv a -> DVarEnv a -> DVarEnv a
plusDVarEnv_C = plusUDFM_C
unitDVarEnv :: Var -> a -> DVarEnv a
unitDVarEnv = unitUDFM
delDVarEnv :: DVarEnv a -> Var -> DVarEnv a
delDVarEnv = delFromUDFM
delDVarEnvList :: DVarEnv a -> [Var] -> DVarEnv a
delDVarEnvList = delListFromUDFM
isEmptyDVarEnv :: DVarEnv a -> Bool
isEmptyDVarEnv = isNullUDFM
elemDVarEnv :: Var -> DVarEnv a -> Bool
elemDVarEnv = elemUDFM
extendDVarEnv_C :: (a -> a -> a) -> DVarEnv a -> Var -> a -> DVarEnv a
extendDVarEnv_C = addToUDFM_C
modifyDVarEnv :: (a -> a) -> DVarEnv a -> Var -> DVarEnv a
modifyDVarEnv mangle_fn env key
= case (lookupDVarEnv env key) of
Nothing -> env
Just xx -> extendDVarEnv env key (mangle_fn xx)
partitionDVarEnv :: (a -> Bool) -> DVarEnv a -> (DVarEnv a, DVarEnv a)
partitionDVarEnv = partitionUDFM
extendDVarEnvList :: DVarEnv a -> [(Var, a)] -> DVarEnv a
extendDVarEnvList = addListToUDFM
anyDVarEnv :: (a -> Bool) -> DVarEnv a -> Bool
anyDVarEnv = anyUDFM
|
sdiehl/ghc
|
compiler/basicTypes/VarEnv.hs
|
bsd-3-clause
| 23,220 | 0 | 14 | 5,678 | 4,845 | 2,694 | 2,151 | 342 | 2 |
module Main where
import qualified Sonos.Main as M
main :: IO ()
main = M.main
|
merc1031/haskell-sonos-http-api
|
app/Main.hs
|
bsd-3-clause
| 81 | 0 | 6 | 17 | 29 | 18 | 11 | 4 | 1 |
module ErrorMessagesSpec where
import TestImport
import Data.List
import qualified Data.Map as M
import qualified Parser
import Codegen
import Err
import Text.RawString.QQ (r)
spec :: Spec
spec = describe "generateDedan" $ context "should show context in errors" $ do
it "in servers" $ do
testErrorMessageContains [r|
server buf {
var count : 1..N;
}
|] ["server buf", "var count", "N"]
testErrorMessageContains [r|
server buf {
var count : (0..1)[:banana];
}
|] ["server buf", "var count", "banana not in type Int"]
testErrorMessageContains [r|
server sem {
{ v | value = :up } -> { ok }
}
|] ["server sem", "action v", "predicate", "value"]
testErrorMessageContains [r|
server sem {
var value : {up, down};
{ v | value = foo } -> { ok }
}
|] ["server sem", "action v", "predicate", "state { value = :up }", "foo"]
testErrorMessageContains [r|
server sem {
var value : {up, down};
{ v } -> { value = 7 }
}
|] ["server sem", "action v",
"updates",
"state { value = :up }",
"assignment of variable \"value\"",
"value 7 not in type {up, down}"]
testErrorMessageContains [r|
server sem {
var value : {up, down};
{ v } -> { bleh = 7 }
}
|] ["server sem",
"action v",
"updates",
"state { value = :up }",
"Undefined symbol \"bleh\""]
it "in initializers" $ do
testErrorMessageContains [r|
server sem { var state : {up, down} }
var mutex = sem() { state = bleh };
|] ["initializer of server instance \"mutex\"",
"Undefined symbol \"bleh\""]
it "in processes" $ do
testErrorMessageContains [r|
process foo() { loop skip; }
|] ["process \"foo\"",
"Cycle detected in CFG"]
testErrorMessageContains :: String -> [String] -> Assertion
testErrorMessageContains source chunks =
let model = unsafeParse Parser.model source
in case generateDedan model of
Right _ -> error $ "Expected error message with " ++ show chunks ++ ", got success!"
Left err ->
let msg = ppError err
in forM_ chunks $ \chunk ->
unless (chunk `isInfixOf` msg) $
error $ "Error message:\n" ++ msg ++ "\ndoes not contain " ++ show chunk
|
zyla/rybu
|
test/ErrorMessagesSpec.hs
|
bsd-3-clause
| 2,683 | 0 | 21 | 1,033 | 426 | 238 | 188 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.DeviceFarm.Types.Sum
-- 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 Network.AWS.DeviceFarm.Types.Sum where
import Network.AWS.Prelude
data ArtifactCategory
= ACFile
| ACLog
| ACScreenshot
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ArtifactCategory where
parser = takeLowerText >>= \case
"file" -> pure ACFile
"log" -> pure ACLog
"screenshot" -> pure ACScreenshot
e -> fromTextError $ "Failure parsing ArtifactCategory from value: '" <> e
<> "'. Accepted values: FILE, LOG, SCREENSHOT"
instance ToText ArtifactCategory where
toText = \case
ACFile -> "FILE"
ACLog -> "LOG"
ACScreenshot -> "SCREENSHOT"
instance Hashable ArtifactCategory
instance ToByteString ArtifactCategory
instance ToQuery ArtifactCategory
instance ToHeader ArtifactCategory
instance ToJSON ArtifactCategory where
toJSON = toJSONText
data ArtifactType
= AppiumJavaOutput
| AppiumJavaXMLOutput
| AppiumServerOutput
| AutomationOutput
| CalabashJSONOutput
| CalabashJavaXMLOutput
| CalabashPrettyOutput
| CalabashStandardOutput
| DeviceLog
| ExerciserMonkeyOutput
| InstrumentationOutput
| MessageLog
| ResultLog
| Screenshot
| ServiceLog
| Unknown
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ArtifactType where
parser = takeLowerText >>= \case
"appium_java_output" -> pure AppiumJavaOutput
"appium_java_xml_output" -> pure AppiumJavaXMLOutput
"appium_server_output" -> pure AppiumServerOutput
"automation_output" -> pure AutomationOutput
"calabash_json_output" -> pure CalabashJSONOutput
"calabash_java_xml_output" -> pure CalabashJavaXMLOutput
"calabash_pretty_output" -> pure CalabashPrettyOutput
"calabash_standard_output" -> pure CalabashStandardOutput
"device_log" -> pure DeviceLog
"exerciser_monkey_output" -> pure ExerciserMonkeyOutput
"instrumentation_output" -> pure InstrumentationOutput
"message_log" -> pure MessageLog
"result_log" -> pure ResultLog
"screenshot" -> pure Screenshot
"service_log" -> pure ServiceLog
"unknown" -> pure Unknown
e -> fromTextError $ "Failure parsing ArtifactType from value: '" <> e
<> "'. Accepted values: APPIUM_JAVA_OUTPUT, APPIUM_JAVA_XML_OUTPUT, APPIUM_SERVER_OUTPUT, AUTOMATION_OUTPUT, CALABASH_JSON_OUTPUT, CALABASH_JAVA_XML_OUTPUT, CALABASH_PRETTY_OUTPUT, CALABASH_STANDARD_OUTPUT, DEVICE_LOG, EXERCISER_MONKEY_OUTPUT, INSTRUMENTATION_OUTPUT, MESSAGE_LOG, RESULT_LOG, SCREENSHOT, SERVICE_LOG, UNKNOWN"
instance ToText ArtifactType where
toText = \case
AppiumJavaOutput -> "APPIUM_JAVA_OUTPUT"
AppiumJavaXMLOutput -> "APPIUM_JAVA_XML_OUTPUT"
AppiumServerOutput -> "APPIUM_SERVER_OUTPUT"
AutomationOutput -> "AUTOMATION_OUTPUT"
CalabashJSONOutput -> "CALABASH_JSON_OUTPUT"
CalabashJavaXMLOutput -> "CALABASH_JAVA_XML_OUTPUT"
CalabashPrettyOutput -> "CALABASH_PRETTY_OUTPUT"
CalabashStandardOutput -> "CALABASH_STANDARD_OUTPUT"
DeviceLog -> "DEVICE_LOG"
ExerciserMonkeyOutput -> "EXERCISER_MONKEY_OUTPUT"
InstrumentationOutput -> "INSTRUMENTATION_OUTPUT"
MessageLog -> "MESSAGE_LOG"
ResultLog -> "RESULT_LOG"
Screenshot -> "SCREENSHOT"
ServiceLog -> "SERVICE_LOG"
Unknown -> "UNKNOWN"
instance Hashable ArtifactType
instance ToByteString ArtifactType
instance ToQuery ArtifactType
instance ToHeader ArtifactType
instance FromJSON ArtifactType where
parseJSON = parseJSONText "ArtifactType"
data BillingMethod
= Metered
| Unmetered
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText BillingMethod where
parser = takeLowerText >>= \case
"metered" -> pure Metered
"unmetered" -> pure Unmetered
e -> fromTextError $ "Failure parsing BillingMethod from value: '" <> e
<> "'. Accepted values: METERED, UNMETERED"
instance ToText BillingMethod where
toText = \case
Metered -> "METERED"
Unmetered -> "UNMETERED"
instance Hashable BillingMethod
instance ToByteString BillingMethod
instance ToQuery BillingMethod
instance ToHeader BillingMethod
instance ToJSON BillingMethod where
toJSON = toJSONText
instance FromJSON BillingMethod where
parseJSON = parseJSONText "BillingMethod"
data DeviceAttribute
= ARN
| FormFactor
| Manufacturer
| Platform
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText DeviceAttribute where
parser = takeLowerText >>= \case
"arn" -> pure ARN
"form_factor" -> pure FormFactor
"manufacturer" -> pure Manufacturer
"platform" -> pure Platform
e -> fromTextError $ "Failure parsing DeviceAttribute from value: '" <> e
<> "'. Accepted values: ARN, FORM_FACTOR, MANUFACTURER, PLATFORM"
instance ToText DeviceAttribute where
toText = \case
ARN -> "ARN"
FormFactor -> "FORM_FACTOR"
Manufacturer -> "MANUFACTURER"
Platform -> "PLATFORM"
instance Hashable DeviceAttribute
instance ToByteString DeviceAttribute
instance ToQuery DeviceAttribute
instance ToHeader DeviceAttribute
instance ToJSON DeviceAttribute where
toJSON = toJSONText
instance FromJSON DeviceAttribute where
parseJSON = parseJSONText "DeviceAttribute"
data DeviceFormFactor
= Phone
| Tablet
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText DeviceFormFactor where
parser = takeLowerText >>= \case
"phone" -> pure Phone
"tablet" -> pure Tablet
e -> fromTextError $ "Failure parsing DeviceFormFactor from value: '" <> e
<> "'. Accepted values: PHONE, TABLET"
instance ToText DeviceFormFactor where
toText = \case
Phone -> "PHONE"
Tablet -> "TABLET"
instance Hashable DeviceFormFactor
instance ToByteString DeviceFormFactor
instance ToQuery DeviceFormFactor
instance ToHeader DeviceFormFactor
instance FromJSON DeviceFormFactor where
parseJSON = parseJSONText "DeviceFormFactor"
data DevicePlatform
= Android
| Ios
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText DevicePlatform where
parser = takeLowerText >>= \case
"android" -> pure Android
"ios" -> pure Ios
e -> fromTextError $ "Failure parsing DevicePlatform from value: '" <> e
<> "'. Accepted values: ANDROID, IOS"
instance ToText DevicePlatform where
toText = \case
Android -> "ANDROID"
Ios -> "IOS"
instance Hashable DevicePlatform
instance ToByteString DevicePlatform
instance ToQuery DevicePlatform
instance ToHeader DevicePlatform
instance FromJSON DevicePlatform where
parseJSON = parseJSONText "DevicePlatform"
data DevicePoolType
= Curated
| Private
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText DevicePoolType where
parser = takeLowerText >>= \case
"curated" -> pure Curated
"private" -> pure Private
e -> fromTextError $ "Failure parsing DevicePoolType from value: '" <> e
<> "'. Accepted values: CURATED, PRIVATE"
instance ToText DevicePoolType where
toText = \case
Curated -> "CURATED"
Private -> "PRIVATE"
instance Hashable DevicePoolType
instance ToByteString DevicePoolType
instance ToQuery DevicePoolType
instance ToHeader DevicePoolType
instance ToJSON DevicePoolType where
toJSON = toJSONText
instance FromJSON DevicePoolType where
parseJSON = parseJSONText "DevicePoolType"
data ExecutionResult
= ERErrored
| ERFailed
| ERPassed
| ERPending
| ERSkipped
| ERStopped
| ERWarned
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ExecutionResult where
parser = takeLowerText >>= \case
"errored" -> pure ERErrored
"failed" -> pure ERFailed
"passed" -> pure ERPassed
"pending" -> pure ERPending
"skipped" -> pure ERSkipped
"stopped" -> pure ERStopped
"warned" -> pure ERWarned
e -> fromTextError $ "Failure parsing ExecutionResult from value: '" <> e
<> "'. Accepted values: ERRORED, FAILED, PASSED, PENDING, SKIPPED, STOPPED, WARNED"
instance ToText ExecutionResult where
toText = \case
ERErrored -> "ERRORED"
ERFailed -> "FAILED"
ERPassed -> "PASSED"
ERPending -> "PENDING"
ERSkipped -> "SKIPPED"
ERStopped -> "STOPPED"
ERWarned -> "WARNED"
instance Hashable ExecutionResult
instance ToByteString ExecutionResult
instance ToQuery ExecutionResult
instance ToHeader ExecutionResult
instance FromJSON ExecutionResult where
parseJSON = parseJSONText "ExecutionResult"
data ExecutionStatus
= Completed
| Pending
| Processing
| Running
| Scheduling
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ExecutionStatus where
parser = takeLowerText >>= \case
"completed" -> pure Completed
"pending" -> pure Pending
"processing" -> pure Processing
"running" -> pure Running
"scheduling" -> pure Scheduling
e -> fromTextError $ "Failure parsing ExecutionStatus from value: '" <> e
<> "'. Accepted values: COMPLETED, PENDING, PROCESSING, RUNNING, SCHEDULING"
instance ToText ExecutionStatus where
toText = \case
Completed -> "COMPLETED"
Pending -> "PENDING"
Processing -> "PROCESSING"
Running -> "RUNNING"
Scheduling -> "SCHEDULING"
instance Hashable ExecutionStatus
instance ToByteString ExecutionStatus
instance ToQuery ExecutionStatus
instance ToHeader ExecutionStatus
instance FromJSON ExecutionStatus where
parseJSON = parseJSONText "ExecutionStatus"
data RuleOperator
= Equals
| GreaterThan
| IN
| LessThan
| NotIn
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText RuleOperator where
parser = takeLowerText >>= \case
"equals" -> pure Equals
"greater_than" -> pure GreaterThan
"in" -> pure IN
"less_than" -> pure LessThan
"not_in" -> pure NotIn
e -> fromTextError $ "Failure parsing RuleOperator from value: '" <> e
<> "'. Accepted values: EQUALS, GREATER_THAN, IN, LESS_THAN, NOT_IN"
instance ToText RuleOperator where
toText = \case
Equals -> "EQUALS"
GreaterThan -> "GREATER_THAN"
IN -> "IN"
LessThan -> "LESS_THAN"
NotIn -> "NOT_IN"
instance Hashable RuleOperator
instance ToByteString RuleOperator
instance ToQuery RuleOperator
instance ToHeader RuleOperator
instance ToJSON RuleOperator where
toJSON = toJSONText
instance FromJSON RuleOperator where
parseJSON = parseJSONText "RuleOperator"
data SampleType
= CPU
| Memory
| NativeAvgDrawtime
| NativeFps
| NativeFrames
| NativeMaxDrawtime
| NativeMinDrawtime
| OpenglAvgDrawtime
| OpenglFps
| OpenglFrames
| OpenglMaxDrawtime
| OpenglMinDrawtime
| RX
| RxRate
| TX
| Threads
| TxRate
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText SampleType where
parser = takeLowerText >>= \case
"cpu" -> pure CPU
"memory" -> pure Memory
"native_avg_drawtime" -> pure NativeAvgDrawtime
"native_fps" -> pure NativeFps
"native_frames" -> pure NativeFrames
"native_max_drawtime" -> pure NativeMaxDrawtime
"native_min_drawtime" -> pure NativeMinDrawtime
"opengl_avg_drawtime" -> pure OpenglAvgDrawtime
"opengl_fps" -> pure OpenglFps
"opengl_frames" -> pure OpenglFrames
"opengl_max_drawtime" -> pure OpenglMaxDrawtime
"opengl_min_drawtime" -> pure OpenglMinDrawtime
"rx" -> pure RX
"rx_rate" -> pure RxRate
"tx" -> pure TX
"threads" -> pure Threads
"tx_rate" -> pure TxRate
e -> fromTextError $ "Failure parsing SampleType from value: '" <> e
<> "'. Accepted values: CPU, MEMORY, NATIVE_AVG_DRAWTIME, NATIVE_FPS, NATIVE_FRAMES, NATIVE_MAX_DRAWTIME, NATIVE_MIN_DRAWTIME, OPENGL_AVG_DRAWTIME, OPENGL_FPS, OPENGL_FRAMES, OPENGL_MAX_DRAWTIME, OPENGL_MIN_DRAWTIME, RX, RX_RATE, TX, THREADS, TX_RATE"
instance ToText SampleType where
toText = \case
CPU -> "CPU"
Memory -> "MEMORY"
NativeAvgDrawtime -> "NATIVE_AVG_DRAWTIME"
NativeFps -> "NATIVE_FPS"
NativeFrames -> "NATIVE_FRAMES"
NativeMaxDrawtime -> "NATIVE_MAX_DRAWTIME"
NativeMinDrawtime -> "NATIVE_MIN_DRAWTIME"
OpenglAvgDrawtime -> "OPENGL_AVG_DRAWTIME"
OpenglFps -> "OPENGL_FPS"
OpenglFrames -> "OPENGL_FRAMES"
OpenglMaxDrawtime -> "OPENGL_MAX_DRAWTIME"
OpenglMinDrawtime -> "OPENGL_MIN_DRAWTIME"
RX -> "RX"
RxRate -> "RX_RATE"
TX -> "TX"
Threads -> "THREADS"
TxRate -> "TX_RATE"
instance Hashable SampleType
instance ToByteString SampleType
instance ToQuery SampleType
instance ToHeader SampleType
instance FromJSON SampleType where
parseJSON = parseJSONText "SampleType"
data TestType
= AppiumJavaJunit
| AppiumJavaTestng
| BuiltinExplorer
| BuiltinFuzz
| Calabash
| Instrumentation
| Uiautomation
| Uiautomator
| Xctest
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText TestType where
parser = takeLowerText >>= \case
"appium_java_junit" -> pure AppiumJavaJunit
"appium_java_testng" -> pure AppiumJavaTestng
"builtin_explorer" -> pure BuiltinExplorer
"builtin_fuzz" -> pure BuiltinFuzz
"calabash" -> pure Calabash
"instrumentation" -> pure Instrumentation
"uiautomation" -> pure Uiautomation
"uiautomator" -> pure Uiautomator
"xctest" -> pure Xctest
e -> fromTextError $ "Failure parsing TestType from value: '" <> e
<> "'. Accepted values: APPIUM_JAVA_JUNIT, APPIUM_JAVA_TESTNG, BUILTIN_EXPLORER, BUILTIN_FUZZ, CALABASH, INSTRUMENTATION, UIAUTOMATION, UIAUTOMATOR, XCTEST"
instance ToText TestType where
toText = \case
AppiumJavaJunit -> "APPIUM_JAVA_JUNIT"
AppiumJavaTestng -> "APPIUM_JAVA_TESTNG"
BuiltinExplorer -> "BUILTIN_EXPLORER"
BuiltinFuzz -> "BUILTIN_FUZZ"
Calabash -> "CALABASH"
Instrumentation -> "INSTRUMENTATION"
Uiautomation -> "UIAUTOMATION"
Uiautomator -> "UIAUTOMATOR"
Xctest -> "XCTEST"
instance Hashable TestType
instance ToByteString TestType
instance ToQuery TestType
instance ToHeader TestType
instance ToJSON TestType where
toJSON = toJSONText
instance FromJSON TestType where
parseJSON = parseJSONText "TestType"
data UploadStatus
= USFailed
| USInitialized
| USProcessing
| USSucceeded
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText UploadStatus where
parser = takeLowerText >>= \case
"failed" -> pure USFailed
"initialized" -> pure USInitialized
"processing" -> pure USProcessing
"succeeded" -> pure USSucceeded
e -> fromTextError $ "Failure parsing UploadStatus from value: '" <> e
<> "'. Accepted values: FAILED, INITIALIZED, PROCESSING, SUCCEEDED"
instance ToText UploadStatus where
toText = \case
USFailed -> "FAILED"
USInitialized -> "INITIALIZED"
USProcessing -> "PROCESSING"
USSucceeded -> "SUCCEEDED"
instance Hashable UploadStatus
instance ToByteString UploadStatus
instance ToQuery UploadStatus
instance ToHeader UploadStatus
instance FromJSON UploadStatus where
parseJSON = parseJSONText "UploadStatus"
data UploadType
= AndroidApp
| AppiumJavaJunitTestPackage
| AppiumJavaTestngTestPackage
| CalabashTestPackage
| ExternalData
| InstrumentationTestPackage
| IosApp
| UiautomationTestPackage
| UiautomatorTestPackage
| XctestTestPackage
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText UploadType where
parser = takeLowerText >>= \case
"android_app" -> pure AndroidApp
"appium_java_junit_test_package" -> pure AppiumJavaJunitTestPackage
"appium_java_testng_test_package" -> pure AppiumJavaTestngTestPackage
"calabash_test_package" -> pure CalabashTestPackage
"external_data" -> pure ExternalData
"instrumentation_test_package" -> pure InstrumentationTestPackage
"ios_app" -> pure IosApp
"uiautomation_test_package" -> pure UiautomationTestPackage
"uiautomator_test_package" -> pure UiautomatorTestPackage
"xctest_test_package" -> pure XctestTestPackage
e -> fromTextError $ "Failure parsing UploadType from value: '" <> e
<> "'. Accepted values: ANDROID_APP, APPIUM_JAVA_JUNIT_TEST_PACKAGE, APPIUM_JAVA_TESTNG_TEST_PACKAGE, CALABASH_TEST_PACKAGE, EXTERNAL_DATA, INSTRUMENTATION_TEST_PACKAGE, IOS_APP, UIAUTOMATION_TEST_PACKAGE, UIAUTOMATOR_TEST_PACKAGE, XCTEST_TEST_PACKAGE"
instance ToText UploadType where
toText = \case
AndroidApp -> "ANDROID_APP"
AppiumJavaJunitTestPackage -> "APPIUM_JAVA_JUNIT_TEST_PACKAGE"
AppiumJavaTestngTestPackage -> "APPIUM_JAVA_TESTNG_TEST_PACKAGE"
CalabashTestPackage -> "CALABASH_TEST_PACKAGE"
ExternalData -> "EXTERNAL_DATA"
InstrumentationTestPackage -> "INSTRUMENTATION_TEST_PACKAGE"
IosApp -> "IOS_APP"
UiautomationTestPackage -> "UIAUTOMATION_TEST_PACKAGE"
UiautomatorTestPackage -> "UIAUTOMATOR_TEST_PACKAGE"
XctestTestPackage -> "XCTEST_TEST_PACKAGE"
instance Hashable UploadType
instance ToByteString UploadType
instance ToQuery UploadType
instance ToHeader UploadType
instance ToJSON UploadType where
toJSON = toJSONText
instance FromJSON UploadType where
parseJSON = parseJSONText "UploadType"
|
fmapfmapfmap/amazonka
|
amazonka-devicefarm/gen/Network/AWS/DeviceFarm/Types/Sum.hs
|
mpl-2.0
| 18,789 | 0 | 12 | 4,352 | 3,578 | 1,796 | 1,782 | 479 | 0 |
-- Copyright 2014 by Mark Watson. All rights reserved. The software and data in this project can be used under the terms of the GPL version 3 license.
module NamePrefixes (namePrefixes) where
import qualified Data.Set as S
namePrefixes = S.fromList ["Dr", "Premier", "Major", "King", "General", "Ms", "Gen", "Mrs", "Sen", "Mr", "Doctor", "St", "Prince", "Representative", "Maj", "President", "Congressman", "Vice", "Lt", "Senator"]
|
mark-watson/kbnlp.hs
|
NamePrefixes.hs
|
agpl-3.0
| 435 | 0 | 6 | 63 | 88 | 58 | 30 | 3 | 1 |
--
-- Copyright (c) 2012 Citrix Systems, Inc.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
--
-- Some utility file functions
module Tools.File (
maybeGetContents
, filesInDir
, getDirectoryContents_nonDotted
, fileSha1Sum
, fileSha256Sum
, readFileStrict
, module Tools.FileC
) where
import Control.Monad
import Control.Applicative
import System.Directory
import System.IO
import System.FilePath.Posix
import Tools.FileC
import Tools.Process
import Tools.Misc
maybeGetContents :: FilePath -> IO (Maybe String)
maybeGetContents p = doesFileExist p >>= maybeRead
where maybeRead False = return Nothing
maybeRead True = readFileStrict p >>= return . Just
readFileStrict :: FilePath -> IO String
readFileStrict p = do
contents <- readFile p
length contents `seq` return contents
filesInDir :: FilePath -> IO [FilePath]
filesInDir p = map (p </>) <$> getDirectoryContents_nonDotted p
dotted :: FilePath -> Bool
dotted "." = True
dotted ".." = True
dotted _ = False
getDirectoryContents_nonDotted :: FilePath -> IO [FilePath]
getDirectoryContents_nonDotted = fmap (filter $ not . dotted) . getDirectoryContents
fileSha1Sum :: FilePath -> IO Integer
fileSha1Sum path = do
(sumStr:_) <- reverse . words <$> readProcessOrDie "openssl" ["dgst", "-sha1", path] ""
return $ read ("0x" ++ sumStr)
fileSha256Sum :: FilePath -> IO Integer
fileSha256Sum path = do
(sumStr:_) <- reverse . words <$> readProcessOrDie "openssl" ["dgst", "-sha256", path] ""
return $ read ("0x" ++ sumStr)
|
OpenXT/xclibs
|
xchutils/Tools/File.hs
|
lgpl-2.1
| 2,317 | 0 | 10 | 483 | 459 | 248 | 211 | 40 | 2 |
module Even where
{-@ type Even = {v:Int | v mod 2 = 0} @-}
{-@ notEven :: Int -> Even @-}
notEven :: Int -> Int
notEven x = x * 2
|
ssaavedra/liquidhaskell
|
tests/pos/Even.hs
|
bsd-3-clause
| 134 | 0 | 5 | 36 | 27 | 16 | 11 | 3 | 1 |
--
-- Copyright (C) 2012 Parallel Scientific. All rights reserved.
--
-- See the accompanying LICENSE file for license information.
--
import Control.Exception ( finally )
import Control.Monad ( forever, void )
import qualified Data.ByteString.Char8 as B ( putStrLn, pack )
import Network.CCI ( withCCI, withPollingEndpoint, getEndpt_URI, accept
, pollWithEventData, EventData(..), disconnect, send
, unsafePackEventBytes
)
main :: IO ()
main =
withCCI$
withPollingEndpoint Nothing$ \ep -> do
getEndpt_URI ep >>= putStrLn
_ <- forever$ pollWithEventData ep$ \evd ->
case evd of
EvConnectRequest ev _bs _cattr -> void$ accept ev 0
EvRecv ebs conn -> flip finally (disconnect conn)$
do unsafePackEventBytes ebs >>= B.putStrLn
send conn (B.pack "pong!") 1
_ -> print evd
return ()
|
tkonolige/haskell-cci
|
examples/Server.hs
|
bsd-3-clause
| 976 | 0 | 21 | 313 | 247 | 131 | 116 | 19 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeApplications #-}
module Main where
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import Data.Proxy (Proxy(Proxy))
import Data.Ratio ((%), numerator, denominator)
import qualified Data.Serialize as Cereal
import Data.Word (Word8)
import GHC.Exts (fromList)
import GHC.TypeLits (Nat, Symbol, KnownSymbol, symbolVal)
import qualified Money
import qualified Test.Tasty as Tasty
import Test.Tasty.HUnit ((@?=), (@=?))
import qualified Test.Tasty.HUnit as HU
import qualified Test.Tasty.Runners as Tasty
import Test.Tasty.QuickCheck ((===), (==>), (.&&.))
import qualified Test.Tasty.QuickCheck as QC
import Money.Cereal ()
--------------------------------------------------------------------------------
main :: IO ()
main = Tasty.defaultMainWithIngredients
[ Tasty.consoleTestReporter
, Tasty.listingTests
] (Tasty.localOption (QC.QuickCheckTests 100) tests)
tests :: Tasty.TestTree
tests =
Tasty.testGroup "root"
[ testCurrencies
, testCurrencyUnits
, testExchange
, testRawSerializations
]
testCurrencies :: Tasty.TestTree
testCurrencies =
Tasty.testGroup "Currency"
[ testDense (Proxy :: Proxy "BTC") -- A cryptocurrency.
, testDense (Proxy :: Proxy "USD") -- A fiat currency with decimal fractions.
, testDense (Proxy :: Proxy "VUV") -- A fiat currency with non-decimal fractions.
, testDense (Proxy :: Proxy "XAU") -- A precious metal.
]
testCurrencyUnits :: Tasty.TestTree
testCurrencyUnits =
Tasty.testGroup "Currency units"
[ testDiscrete (Proxy :: Proxy "BTC") (Proxy :: Proxy "satoshi")
, testDiscrete (Proxy :: Proxy "BTC") (Proxy :: Proxy "bitcoin")
, testDiscrete (Proxy :: Proxy "USD") (Proxy :: Proxy "cent")
, testDiscrete (Proxy :: Proxy "USD") (Proxy :: Proxy "dollar")
, testDiscrete (Proxy :: Proxy "VUV") (Proxy :: Proxy "vatu")
, testDiscrete (Proxy :: Proxy "XAU") (Proxy :: Proxy "gram")
, testDiscrete (Proxy :: Proxy "XAU") (Proxy :: Proxy "grain")
]
testDense
:: forall currency
. KnownSymbol currency
=> Proxy currency
-> Tasty.TestTree
testDense pc =
Tasty.testGroup ("Dense " ++ show (symbolVal pc))
[ QC.testProperty "Cereal encoding roundtrip" $
QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) ->
Right x === Cereal.decode (Cereal.encode x)
, QC.testProperty "Cereal encoding roundtrip (SomeDense)" $
QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) ->
let x' = Money.toSomeDense x
in Right x' === Cereal.decode (Cereal.encode x')
, QC.testProperty "Cereal encoding roundtrip (Dense through SomeDense)" $
QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) ->
Right x === Cereal.decode (Cereal.encode (Money.toSomeDense x))
, QC.testProperty "Cereal encoding roundtrip (SomeDense through Dense)" $
QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) ->
Right (Money.toSomeDense x) === Cereal.decode (Cereal.encode x)
]
testExchange :: Tasty.TestTree
testExchange =
Tasty.testGroup "Exchange"
[ testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "BTC")
, testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "USD")
, testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "VUV")
, testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "XAU")
, testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "BTC")
, testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "USD")
, testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "VUV")
, testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "XAU")
, testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "BTC")
, testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "USD")
, testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "VUV")
, testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "XAU")
, testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "BTC")
, testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "USD")
, testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "VUV")
, testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "XAU")
]
testDiscrete
:: forall (currency :: Symbol) (unit :: Symbol)
. ( Money.GoodScale (Money.UnitScale currency unit)
, KnownSymbol currency
, KnownSymbol unit )
=> Proxy currency
-> Proxy unit
-> Tasty.TestTree
testDiscrete pc pu =
Tasty.testGroup ("Discrete " ++ show (symbolVal pc) ++ " "
++ show (symbolVal pu))
[ QC.testProperty "Cereal encoding roundtrip" $
QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) ->
Right x === Cereal.decode (Cereal.encode x)
, QC.testProperty "Cereal encoding roundtrip (SomeDiscrete)" $
QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) ->
let x' = Money.toSomeDiscrete x
in Right x' === Cereal.decode (Cereal.encode x')
, QC.testProperty "Cereal encoding roundtrip (Discrete through SomeDiscrete)" $
QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) ->
Right x === Cereal.decode (Cereal.encode (Money.toSomeDiscrete x))
, QC.testProperty "Cereal encoding roundtrip (SomeDiscrete through Discrete)" $
QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) ->
Right (Money.toSomeDiscrete x) === Cereal.decode (Cereal.encode x)
]
testExchangeRate
:: forall (src :: Symbol) (dst :: Symbol)
. (KnownSymbol src, KnownSymbol dst)
=> Proxy src
-> Proxy dst
-> Tasty.TestTree
testExchangeRate ps pd =
Tasty.testGroup ("ExchangeRate " ++ show (symbolVal ps) ++ " "
++ show (symbolVal pd))
[ QC.testProperty "Cereal encoding roundtrip" $
QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) ->
Right x === Cereal.decode (Cereal.encode x)
, QC.testProperty "Cereal encoding roundtrip (SomeExchangeRate)" $
QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) ->
let x' = Money.toSomeExchangeRate x
in Right x' === Cereal.decode (Cereal.encode x')
, QC.testProperty "Cereal encoding roundtrip (ExchangeRate through SomeExchangeRate)" $
QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) ->
Right x === Cereal.decode (Cereal.encode (Money.toSomeExchangeRate x))
, QC.testProperty "Cereal encoding roundtrip (SomeExchangeRate through ExchangeRate)" $
QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) ->
Right (Money.toSomeExchangeRate x) === Cereal.decode (Cereal.encode x)
]
--------------------------------------------------------------------------------
-- Raw parsing "golden tests"
testRawSerializations :: Tasty.TestTree
testRawSerializations =
Tasty.testGroup "Raw serializations"
[ Tasty.testGroup "cereal"
[ Tasty.testGroup "decode"
[ HU.testCase "Dense" $ do
Right rawDns0 @=? Cereal.decode rawDns0_cereal
, HU.testCase "Discrete" $ do
Right rawDis0 @=? Cereal.decode rawDis0_cereal
, HU.testCase "ExchangeRate" $ do
Right rawXr0 @=? Cereal.decode rawXr0_cereal
]
, Tasty.testGroup "encode"
[ HU.testCase "Dense" $ rawDns0_cereal @=? Cereal.encode rawDns0
, HU.testCase "Discrete" $ rawDis0_cereal @=? Cereal.encode rawDis0
, HU.testCase "ExchangeRate" $ rawXr0_cereal @=? Cereal.encode rawXr0
]
]
]
rawDns0 :: Money.Dense "USD"
rawDns0 = Money.dense' (26%1)
rawDis0 :: Money.Discrete "USD" "cent"
rawDis0 = Money.discrete 4
rawXr0 :: Money.ExchangeRate "USD" "BTC"
Just rawXr0 = Money.exchangeRate (3%2)
-- Such a waste of space these many bytes! Can we shrink this and maintain
-- backwards compatibility?
rawDns0_cereal :: B.ByteString
rawDns0_cereal = "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\ETXUSD\NUL\NUL\NUL\NUL\SUB\NUL\NUL\NUL\NUL\SOH"
rawDis0_cereal :: B.ByteString
rawDis0_cereal = "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\ETXUSD\NUL\NUL\NUL\NULd\NUL\NUL\NUL\NUL\SOH\NUL\NUL\NUL\NUL\EOT"
rawXr0_cereal :: B.ByteString
rawXr0_cereal = "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\ETXUSD\NUL\NUL\NUL\NUL\NUL\NUL\NUL\ETXBTC\NUL\NUL\NUL\NUL\ETX\NUL\NUL\NUL\NUL\STX"
|
k0001/haskell-money
|
safe-money-cereal/test/Main.hs
|
bsd-3-clause
| 8,375 | 0 | 16 | 1,547 | 2,428 | 1,277 | 1,151 | 167 | 1 |
-- | This module provides support for parsing values from ByteString
-- 'InputStream's using @attoparsec@. /Since: 1.4.0.0./
module System.IO.Streams.Attoparsec.ByteString
( -- * Parsing
parseFromStream
, parserToInputStream
, ParseException(..)
) where
------------------------------------------------------------------------------
import Data.Attoparsec.ByteString.Char8 (Parser)
import Data.ByteString (ByteString)
------------------------------------------------------------------------------
import System.IO.Streams.Internal (InputStream)
import qualified System.IO.Streams.Internal as Streams
import System.IO.Streams.Internal.Attoparsec (ParseData (..), ParseException (..), parseFromStreamInternal)
------------------------------------------------------------------------------
-- | Supplies an @attoparsec@ 'Parser' with an 'InputStream', returning the
-- final parsed value or throwing a 'ParseException' if parsing fails.
--
-- 'parseFromStream' consumes only as much input as necessary to satisfy the
-- 'Parser': any unconsumed input is pushed back onto the 'InputStream'.
--
-- If the 'Parser' exhausts the 'InputStream', the end-of-stream signal is sent
-- to attoparsec.
--
-- Example:
--
-- @
-- ghci> import "Data.Attoparsec.ByteString.Char8"
-- ghci> is <- 'System.IO.Streams.fromList' [\"12345xxx\" :: 'ByteString']
-- ghci> 'parseFromStream' ('Data.Attoparsec.ByteString.Char8.takeWhile' 'Data.Attoparsec.ByteString.Char8.isDigit') is
-- \"12345\"
-- ghci> 'System.IO.Streams.read' is
-- Just \"xxx\"
-- @
parseFromStream :: Parser r
-> InputStream ByteString
-> IO r
parseFromStream = parseFromStreamInternal parse feed
------------------------------------------------------------------------------
-- | Given a 'Parser' yielding values of type @'Maybe' r@, transforms an
-- 'InputStream' over byte strings to an 'InputStream' yielding values of type
-- @r@.
--
-- If the parser yields @Just x@, then @x@ will be passed along downstream, and
-- if the parser yields @Nothing@, that will be interpreted as end-of-stream.
--
-- Upon a parse error, 'parserToInputStream' will throw a 'ParseException'.
--
-- Example:
--
-- @
-- ghci> import "Control.Applicative"
-- ghci> import "Data.Attoparsec.ByteString.Char8"
-- ghci> is <- 'System.IO.Streams.fromList' [\"1 2 3 4 5\" :: 'ByteString']
-- ghci> let parser = ('Data.Attoparsec.ByteString.Char8.endOfInput' >> 'Control.Applicative.pure' 'Nothing') \<|\> (Just \<$\> ('Data.Attoparsec.ByteString.Char8.skipWhile' 'Data.Attoparsec.ByteString.Char8.isSpace' *> 'Data.Attoparsec.ByteString.Char8.decimal'))
-- ghci> 'parserToInputStream' parser is >>= 'System.IO.Streams.toList'
-- [1,2,3,4,5]
-- ghci> is' \<- 'System.IO.Streams.fromList' [\"1 2xx3 4 5\" :: 'ByteString'] >>= 'parserToInputStream' parser
-- ghci> 'read' is'
-- Just 1
-- ghci> 'read' is'
-- Just 2
-- ghci> 'read' is'
-- *** Exception: Parse exception: Failed reading: takeWhile1
-- @
parserToInputStream :: Parser (Maybe r)
-> InputStream ByteString
-> IO (InputStream r)
parserToInputStream = (Streams.makeInputStream .) . parseFromStream
{-# INLINE parserToInputStream #-}
|
LukeHoersten/io-streams
|
src/System/IO/Streams/Attoparsec/ByteString.hs
|
bsd-3-clause
| 3,289 | 0 | 9 | 525 | 229 | 159 | 70 | 19 | 1 |
-- Utility for sending a command to xmonad and have
-- it immediately executed even when xmonad isn't built
-- with -threaded.
module Main () where
import Control.Concurrent
import Control.Monad
import Data.List
import Data.Monoid
import Data.Word
import Graphics.X11.Xlib
import Graphics.X11.Xlib.Event
import Graphics.X11.Xlib.Extras
import Network
import System.Console.GetOpt
import System.Environment
import System.IO
data Options = Options { optPort :: PortID
, optHost :: HostName
, optWait :: Bool
, optHelp :: Bool
}
defaultOptions :: Options
defaultOptions = Options { optPort = PortNumber 4242
, optHost = "localhost"
, optWait = False
, optHelp = False
}
readPort :: String -> Options -> Options
readPort str opts = opts { optPort = portNum }
where portNum = PortNumber . fromIntegral $ (read str :: Word16)
options :: [OptDescr (Endo Options)]
options = [ Option ['p'] ["port"]
(ReqArg (Endo . readPort) "<port>")
("Port on which to connect. <port> is expected to be an integer"
++ " between 0 and 65535. (Defaults to 4242)")
, Option ['h'] ["host"]
(ReqArg (\s -> Endo $ \opts -> opts { optHost = s }) "<hostname>")
"Which host to connect to. (Defaults to \"localhost\")"
, Option ['w'] ["wait"]
(NoArg . Endo $ \opts -> opts { optWait = True })
"Wait until the command is executed and print the result. (Default: False)"
, Option [] ["help"]
(NoArg . Endo $ \opts -> opts { optHelp = True })
"Show usage information."
]
getOptions :: [String] -> IO (Options,String)
getOptions args =
case getOpt Permute options args of
(o,rest,[]) -> return (mconcat o `appEndo` defaultOptions, intercalate " " rest)
(_,_,errs) -> ioError . userError $ concat errs ++ usageInfo header options
header :: String
header = "USAGE: xmonadcmd [OPTIONS] <string to send>"
sendCommand :: Options -> String -> IO ()
sendCommand opts cmd = openDisplay "" >>= \dpy -> do
putStrLn cmd
h <- connectTo (optHost opts) (optPort opts)
hSetBuffering h LineBuffering
hPutStrLn h cmd
rootw <- rootWindow dpy $ defaultScreen dpy
atom <- internAtom dpy "TEST" True
forkIO $ allocaXEvent $ \e -> do
setEventType e clientMessage
setClientMessageEvent e rootw atom 32 0 currentTime
sendEvent dpy rootw False structureNotifyMask e
sync dpy False
when (optWait opts) $ putStrLn =<< hGetLine h
hClose h
main :: IO ()
main = do
(opts,cmd) <- getOptions =<< getArgs
if optHelp opts
then putStrLn $ usageInfo header options
else sendCommand opts cmd
|
LeifW/xmonad-extras
|
XMonadCmd.hs
|
bsd-3-clause
| 2,902 | 0 | 14 | 874 | 790 | 422 | 368 | 67 | 2 |
{-# LANGUAGE NoImplicitPrelude, CPP #-}
{-| Export Prelude as in base 4.8.0
-}
{-
Copyright (C) 2015 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Prelude (
-- * Standard types, classes and related functions
-- ** Basic data types
Bool(False, True),
(&&), (||), not, otherwise,
Maybe(Nothing, Just),
maybe,
Either(Left, Right),
either,
Ordering(LT, EQ, GT),
Char, String,
-- *** Tuples
fst, snd, curry, uncurry,
-- ** Basic type classes
Eq((==), (/=)),
Ord(compare, (<), (<=), (>=), (>), max, min),
Enum(succ, pred, toEnum, fromEnum, enumFrom, enumFromThen,
enumFromTo, enumFromThenTo),
Bounded(minBound, maxBound),
-- ** Numbers
-- *** Numeric types
Int, Integer, Float, Double,
Rational, Word,
-- *** Numeric type classes
Num((+), (-), (*), negate, abs, signum, fromInteger),
Real(toRational),
Integral(quot, rem, div, mod, quotRem, divMod, toInteger),
Fractional((/), recip, fromRational),
Floating(pi, exp, log, sqrt, (**), logBase, sin, cos, tan,
asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh),
RealFrac(properFraction, truncate, round, ceiling, floor),
RealFloat(floatRadix, floatDigits, floatRange, decodeFloat,
encodeFloat, exponent, significand, scaleFloat, isNaN,
isInfinite, isDenormalized, isIEEE, isNegativeZero, atan2),
-- *** Numeric functions
subtract, even, odd, gcd, lcm, (^), (^^),
fromIntegral, realToFrac,
-- ** Monoids
Monoid(mempty, mappend, mconcat),
-- ** Monads and functors
Functor(fmap, (<$)), (<$>),
Applicative(pure, (<*>), (*>), (<*)),
Monad((>>=), (>>), return, fail),
mapM_, sequence_, (=<<),
#if MIN_VERSION_base(4,8,0)
-- ** Folds and traversals
Foldable(elem, -- :: (Foldable t, Eq a) => a -> t a -> Bool
-- fold, -- :: Monoid m => t m -> m
foldMap, -- :: Monoid m => (a -> m) -> t a -> m
foldr, -- :: (a -> b -> b) -> b -> t a -> b
-- foldr', -- :: (a -> b -> b) -> b -> t a -> b
foldl, -- :: (b -> a -> b) -> b -> t a -> b
-- foldl', -- :: (b -> a -> b) -> b -> t a -> b
foldr1, -- :: (a -> a -> a) -> t a -> a
foldl1, -- :: (a -> a -> a) -> t a -> a
maximum, -- :: (Foldable t, Ord a) => t a -> a
minimum, -- :: (Foldable t, Ord a) => t a -> a
product, -- :: (Foldable t, Num a) => t a -> a
sum), -- :: Num a => t a -> a
-- toList) -- :: Foldable t => t a -> [a]
#else
Foldable(foldMap,
foldr,
foldl,
foldr1,
foldl1),
elem,
maximum,
minimum,
product,
sum,
#endif
Traversable(traverse, sequenceA, mapM, sequence),
-- ** Miscellaneous functions
id, const, (.), flip, ($), until,
asTypeOf, error, undefined,
seq, ($!),
-- * List operations
map, (++), filter,
head, last, tail, init, null, length, (!!),
reverse,
-- *** Special folds
and, or, any, all,
concat, concatMap,
-- ** Building lists
-- *** Scans
scanl, scanl1, scanr, scanr1,
-- *** Infinite lists
iterate, repeat, replicate, cycle,
-- ** Sublists
take, drop, splitAt, takeWhile, dropWhile, span, break,
-- ** Searching lists
notElem, lookup,
-- ** Zipping and unzipping lists
zip, zip3, zipWith, zipWith3, unzip, unzip3,
-- ** Functions on strings
lines, words, unlines, unwords,
-- * Converting to and from @String@
-- ** Converting to @String@
ShowS,
Show(showsPrec, showList, show),
shows,
showChar, showString, showParen,
-- ** Converting from @String@
ReadS,
Read(readsPrec, readList),
reads, readParen, read, lex,
-- * Basic Input and output
IO,
-- ** Simple I\/O operations
-- All I/O functions defined here are character oriented. The
-- treatment of the newline character will vary on different systems.
-- For example, two characters of input, return and linefeed, may
-- read as a single newline character. These functions cannot be
-- used portably for binary I/O.
-- *** Output functions
putChar,
putStr, putStrLn, print,
-- *** Input functions
getChar,
getLine, getContents, interact,
-- *** Files
FilePath,
readFile, writeFile, appendFile, readIO, readLn,
-- ** Exception handling in the I\/O monad
IOError, ioError, userError,
) where
#if MIN_VERSION_base(4,8,0)
import Prelude
#else
import Prelude hiding ( elem, maximum, minimum, product, sum )
import Data.Foldable ( Foldable(..), elem, maximum, minimum, product, sum )
import Data.Traversable ( Traversable(..) )
import Control.Applicative
import Data.Monoid
import Data.Word
#endif
|
leshchevds/ganeti
|
src/Ganeti/Prelude.hs
|
bsd-2-clause
| 6,145 | 0 | 5 | 1,603 | 813 | 649 | 164 | 128 | 0 |
module Github.Teams (
teamInfoFor
,teamInfoFor'
,teamsInfo'
,createTeamFor'
,editTeam'
,deleteTeam'
,listTeamsCurrent'
,module Github.Data
) where
import Github.Data
import Github.Private
-- | The information for a single team, by team id.
-- | With authentication
--
-- > teamInfoFor' (Just $ GithubOAuth "token") 1010101
teamInfoFor' :: Maybe GithubAuth -> Int -> IO (Either Error DetailedTeam)
teamInfoFor' auth team_id = githubGet' auth ["teams", show team_id]
-- | The information for a single team, by team id.
--
-- > teamInfoFor' (Just $ GithubOAuth "token") 1010101
teamInfoFor :: Int -> IO (Either Error DetailedTeam)
teamInfoFor = teamInfoFor' Nothing
-- | Lists all teams, across all organizations, that the current user belongs to.
--
-- > teamsInfo' (Just $ GithubOAuth "token")
teamsInfo' :: Maybe GithubAuth -> IO (Either Error [DetailedTeam])
teamsInfo' auth = githubGet' auth ["user", "teams"]
-- | Create a team under an organization
--
-- > createTeamFor' (GithubOAuth "token") "organization" (CreateTeam "newteamname" "some description" [] PermssionPull)
createTeamFor' :: GithubAuth
-> String
-> CreateTeam
-> IO (Either Error DetailedTeam)
createTeamFor' auth organization create_team =
githubPost auth ["orgs", organization, "teams"] create_team
-- | Edit a team, by id.
--
-- > editTeamFor'
editTeam' :: GithubAuth
-> Int
-> EditTeam
-> IO (Either Error DetailedTeam)
editTeam' auth team_id edit_team =
githubPatch auth ["teams", show team_id] edit_team
-- | Delete a team, by id.
--
-- > deleteTeam' (GithubOAuth "token") 1010101
deleteTeam' :: GithubAuth -> Int -> IO (Either Error ())
deleteTeam' auth team_id = githubDelete auth ["teams", show team_id]
-- | List teams for current authenticated user
--
-- > listTeamsCurrent' (GithubOAuth "token")
listTeamsCurrent' :: GithubAuth -> IO (Either Error [DetailedTeam])
listTeamsCurrent' auth = githubGet' (Just auth) ["user", "teams"]
|
beni55/github
|
Github/Teams.hs
|
bsd-3-clause
| 1,999 | 0 | 10 | 361 | 401 | 220 | 181 | 33 | 1 |
{-# LANGUAGE FlexibleInstances #-}
module MockedProcess where
import MockedEnv
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
import Tinc.Process
type ReadProcess = FilePath -> [String] -> String -> IO String
type CallProcess = FilePath -> [String] -> IO ()
data Env = Env {
envReadProcess :: ReadProcess
, envCallProcess :: CallProcess
}
env :: Env
env = Env readProcessM callProcessM
instance MonadProcess (WithEnv Env) where
readProcessM command args input = WithEnv $ asks envReadProcess >>= liftIO . ($ input) . ($ args) . ($ command)
callProcessM command args = WithEnv $ asks envCallProcess >>= liftIO . ($ args) . ($ command)
|
sol/tinc
|
test/MockedProcess.hs
|
mit
| 664 | 0 | 11 | 110 | 207 | 118 | 89 | 16 | 1 |
module Util.DocLike(module Util.DocLike, module Data.Monoid) where
-- simplified from Doc.DocLike
import Control.Applicative
import Data.Monoid(Monoid(..),(<>))
import Data.Traversable as T
import qualified Text.PrettyPrint.HughesPJ as P
import qualified Text.PrettyPrint.Leijen as L
--infixr 5 <$> -- ,<//>,<$>,<$$>
infixr 6 <+>, <->
infixl 5 $$, $+$
-- we expect a monoid instance with <>
class DocLike a where
emptyDoc :: a
text :: String -> a
oobText :: String -> a
char :: Char -> a
char x = text [x]
(<+>) :: a -> a -> a
(<->) :: a -> a -> a
($$) :: a -> a -> a
($+$) :: a -> a -> a
hsep :: [a] -> a
hcat :: [a] -> a
vcat :: [a] -> a
tupled :: [a] -> a
list :: [a] -> a
fsep :: [a] -> a
fcat :: [a] -> a
sep :: [a] -> a
cat :: [a] -> a
semiBraces :: [a] -> a
enclose :: a -> a -> a -> a
encloseSep :: a -> a -> a -> [a] -> a
oobText _ = emptyDoc
emptyDoc = text []
hcat [] = emptyDoc
hcat xs = foldr1 (<->) xs
hsep [] = emptyDoc
hsep xs = foldr1 (<+>) xs
vcat [] = emptyDoc
vcat xs = foldr1 (\x y -> x <-> char '\n' <-> y) xs
fsep = hsep
fcat = hcat
sep = hsep
cat = hcat
x <+> y = x <-> char ' ' <-> y
x $$ y = x <-> char '\n' <-> y
x $+$ y = x $$ y
encloseSep l r s ds = enclose l r (hcat $ punctuate s ds)
enclose l r x = l <-> x <-> r
list = encloseSep lbracket rbracket comma
tupled = encloseSep lparen rparen comma
semiBraces = encloseSep lbrace rbrace semi
------------------------
-- Basic building blocks
------------------------
tshow :: (Show a,DocLike b) => a -> b
tshow x = text (show x)
lparen,rparen,langle,rangle,
lbrace,rbrace,lbracket,rbracket,squote,
dquote,semi,colon,comma,space,dot,backslash,equals
:: DocLike a => a
lparen = char '('
rparen = char ')'
langle = char '<'
rangle = char '>'
lbrace = char '{'
rbrace = char '}'
lbracket = char '['
rbracket = char ']'
squote = char '\''
dquote = char '"'
semi = char ';'
colon = char ':'
comma = char ','
space = char ' '
dot = char '.'
backslash = char '\\'
equals = char '='
squotes x = enclose squote squote x
dquotes x = enclose dquote dquote x
parens x = enclose lparen rparen x
braces x = enclose lbrace rbrace x
brackets x = enclose lbracket rbracket x
angles x = enclose langle rangle x
-----------------------------------------------------------
-- punctuate p [d1,d2,...,dn] => [d1 <> p,d2 <> p, ... ,dn]
-----------------------------------------------------------
punctuate _ [] = []
punctuate _ [d] = [d]
punctuate p (d:ds) = (d <-> p) : punctuate p ds
newtype ShowSDoc = SD { unSD :: String -> String }
showSD (SD s) = s ""
instance Monoid ShowSDoc where
mempty = SD id
mappend (SD a) (SD b) = SD $ a . b
instance (DocLike ShowSDoc) where
char c = SD (c:)
text s = SD (s ++)
SD x <+> SD y = SD $ x . (' ':) . y
x <-> y = mappend x y
emptyDoc = mempty
instance (DocLike [Char]) where
char c = [c]
text s = s
x <+> y = x ++ " " ++ y
x <-> y = mappend x y
emptyDoc = mempty
instance (DocLike a, Applicative m) => DocLike (m a) where
emptyDoc = pure emptyDoc
char x = pure (char x)
text x = pure (text x)
($$) = liftA2 ($$)
($+$) = liftA2 ($+$)
(<+>) = liftA2 (<+>)
(<->) = liftA2 (<->)
vcat xs = vcat <$> traverse id xs
hsep xs = hsep <$> traverse id xs
---------------------
-- HughesPJ instances
---------------------
-- instance Monoid P.Doc where
-- mappend = (P.<>)
-- mempty = P.empty
-- mconcat = P.hcat
instance DocLike P.Doc where
emptyDoc = mempty
text = P.text
char = P.char
(<->) = (P.<>)
(<+>) = (P.<+>)
($$) = (P.$$)
($+$) = (P.$+$)
hsep = P.hsep
vcat = P.vcat
oobText = P.zeroWidthText
fcat = P.fcat
fsep = P.fsep
cat = P.cat
sep = P.sep
instance DocLike L.Doc where
emptyDoc = mempty
text = L.text
char = L.char
(<->) = (L.<>)
(<+>) = (L.<+>)
($$) = (L.</>)
($+$) = (L.<$>)
hsep = L.hsep
vcat = L.vcat
fcat = L.fillCat
fsep = L.fillSep
cat = L.cat
sep = L.sep
instance Monoid L.Doc where
mempty = L.empty
mappend = (L.<>)
mconcat = L.hcat
|
hvr/jhc
|
src/Util/DocLike.hs
|
mit
| 4,453 | 10 | 12 | 1,379 | 1,680 | 942 | 738 | 142 | 1 |
{-# LANGUAGE BangPatterns, CPP, OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
module Aeson
(
aeson
, value'
) where
import Data.ByteString.Builder
(Builder, byteString, toLazyByteString, charUtf8, word8)
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((*>), (<$>), (<*), pure)
import Data.Monoid (mappend, mempty)
#endif
import Common (pathTo)
import Control.Applicative (liftA2)
import Control.DeepSeq (NFData(..))
import Control.Monad (forM)
import Data.Attoparsec.ByteString.Char8 (Parser, char, endOfInput, scientific,
skipSpace, string)
import Data.Bits ((.|.), shiftL)
import Data.ByteString (ByteString)
import Data.Char (chr)
import Data.List (sort)
import Data.Scientific (Scientific)
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8')
import Data.Vector as Vector (Vector, foldl', fromList)
import Data.Word (Word8)
import System.Directory (getDirectoryContents)
import System.FilePath ((</>), dropExtension)
import qualified Data.Attoparsec.ByteString as A
import qualified Data.Attoparsec.Lazy as L
import qualified Data.Attoparsec.Zepto as Z
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Unsafe as B
import qualified Data.HashMap.Strict as H
import Criterion.Main
#define BACKSLASH 92
#define CLOSE_CURLY 125
#define CLOSE_SQUARE 93
#define COMMA 44
#define DOUBLE_QUOTE 34
#define OPEN_CURLY 123
#define OPEN_SQUARE 91
#define C_0 48
#define C_9 57
#define C_A 65
#define C_F 70
#define C_a 97
#define C_f 102
#define C_n 110
#define C_t 116
data Result a = Error String
| Success a
deriving (Eq, Show)
-- | A JSON \"object\" (key\/value map).
type Object = H.HashMap Text Value
-- | A JSON \"array\" (sequence).
type Array = Vector Value
-- | A JSON value represented as a Haskell value.
data Value = Object !Object
| Array !Array
| String !Text
| Number !Scientific
| Bool !Bool
| Null
deriving (Eq, Show)
instance NFData Value where
rnf (Object o) = rnf o
rnf (Array a) = Vector.foldl' (\x y -> rnf y `seq` x) () a
rnf (String s) = rnf s
rnf (Number n) = rnf n
rnf (Bool b) = rnf b
rnf Null = ()
-- | Parse a top-level JSON value. This must be either an object or
-- an array, per RFC 4627.
--
-- The conversion of a parsed value to a Haskell value is deferred
-- until the Haskell value is needed. This may improve performance if
-- only a subset of the results of conversions are needed, but at a
-- cost in thunk allocation.
json :: Parser Value
json = json_ object_ array_
-- | Parse a top-level JSON value. This must be either an object or
-- an array, per RFC 4627.
--
-- This is a strict version of 'json' which avoids building up thunks
-- during parsing; it performs all conversions immediately. Prefer
-- this version if most of the JSON data needs to be accessed.
json' :: Parser Value
json' = json_ object_' array_'
json_ :: Parser Value -> Parser Value -> Parser Value
json_ obj ary = do
w <- skipSpace *> A.satisfy (\w -> w == OPEN_CURLY || w == OPEN_SQUARE)
if w == OPEN_CURLY
then obj
else ary
{-# INLINE json_ #-}
object_ :: Parser Value
object_ = {-# SCC "object_" #-} Object <$> objectValues jstring value
object_' :: Parser Value
object_' = {-# SCC "object_'" #-} do
!vals <- objectValues jstring' value'
return (Object vals)
where
jstring' = do
!s <- jstring
return s
objectValues :: Parser Text -> Parser Value -> Parser (H.HashMap Text Value)
objectValues str val = do
skipSpace
let pair = liftA2 (,) (str <* skipSpace) (char ':' *> skipSpace *> val)
H.fromList <$> commaSeparated pair CLOSE_CURLY
{-# INLINE objectValues #-}
array_ :: Parser Value
array_ = {-# SCC "array_" #-} Array <$> arrayValues value
array_' :: Parser Value
array_' = {-# SCC "array_'" #-} do
!vals <- arrayValues value'
return (Array vals)
commaSeparated :: Parser a -> Word8 -> Parser [a]
commaSeparated item endByte = do
w <- A.peekWord8'
if w == endByte
then A.anyWord8 >> return []
else loop
where
loop = do
v <- item <* skipSpace
ch <- A.satisfy $ \w -> w == COMMA || w == endByte
if ch == COMMA
then skipSpace >> (v:) <$> loop
else return [v]
{-# INLINE commaSeparated #-}
arrayValues :: Parser Value -> Parser (Vector Value)
arrayValues val = do
skipSpace
Vector.fromList <$> commaSeparated val CLOSE_SQUARE
{-# INLINE arrayValues #-}
-- | Parse any JSON value. You should usually 'json' in preference to
-- this function, as this function relaxes the object-or-array
-- requirement of RFC 4627.
--
-- In particular, be careful in using this function if you think your
-- code might interoperate with Javascript. A naïve Javascript
-- library that parses JSON data using @eval@ is vulnerable to attack
-- unless the encoded data represents an object or an array. JSON
-- implementations in other languages conform to that same restriction
-- to preserve interoperability and security.
value :: Parser Value
value = do
w <- A.peekWord8'
case w of
DOUBLE_QUOTE -> A.anyWord8 *> (String <$> jstring_)
OPEN_CURLY -> A.anyWord8 *> object_
OPEN_SQUARE -> A.anyWord8 *> array_
C_f -> string "false" *> pure (Bool False)
C_t -> string "true" *> pure (Bool True)
C_n -> string "null" *> pure Null
_ | w >= 48 && w <= 57 || w == 45
-> Number <$> scientific
| otherwise -> fail "not a valid json value"
-- | Strict version of 'value'. See also 'json''.
value' :: Parser Value
value' = do
w <- A.peekWord8'
case w of
DOUBLE_QUOTE -> do
!s <- A.anyWord8 *> jstring_
return (String s)
OPEN_CURLY -> A.anyWord8 *> object_'
OPEN_SQUARE -> A.anyWord8 *> array_'
C_f -> string "false" *> pure (Bool False)
C_t -> string "true" *> pure (Bool True)
C_n -> string "null" *> pure Null
_ | w >= 48 && w <= 57 || w == 45
-> do
!n <- scientific
return (Number n)
| otherwise -> fail "not a valid json value"
-- | Parse a quoted JSON string.
jstring :: Parser Text
jstring = A.word8 DOUBLE_QUOTE *> jstring_
-- | Parse a string without a leading quote.
jstring_ :: Parser Text
jstring_ = {-# SCC "jstring_" #-} do
s <- A.scan False $ \s c -> if s then Just False
else if c == DOUBLE_QUOTE
then Nothing
else Just (c == BACKSLASH)
_ <- A.word8 DOUBLE_QUOTE
s1 <- if BACKSLASH `B.elem` s
then case Z.parse unescape s of
Right r -> return r
Left err -> fail err
else return s
case decodeUtf8' s1 of
Right r -> return r
Left err -> fail $ show err
{-# INLINE jstring_ #-}
unescape :: Z.Parser ByteString
unescape = toByteString <$> go mempty where
go acc = do
h <- Z.takeWhile (/=BACKSLASH)
let rest = do
start <- Z.take 2
let !slash = B.unsafeHead start
!t = B.unsafeIndex start 1
escape = case B.findIndex (==t) "\"\\/ntbrfu" of
Just i -> i
_ -> 255
if slash /= BACKSLASH || escape == 255
then fail "invalid JSON escape sequence"
else do
let cont m = go (acc `mappend` byteString h `mappend` m)
{-# INLINE cont #-}
if t /= 117 -- 'u'
then cont (word8 (B.unsafeIndex mapping escape))
else do
a <- hexQuad
if a < 0xd800 || a > 0xdfff
then cont (charUtf8 (chr a))
else do
b <- Z.string "\\u" *> hexQuad
if a <= 0xdbff && b >= 0xdc00 && b <= 0xdfff
then let !c = ((a - 0xd800) `shiftL` 10) +
(b - 0xdc00) + 0x10000
in cont (charUtf8 (chr c))
else fail "invalid UTF-16 surrogates"
done <- Z.atEnd
if done
then return (acc `mappend` byteString h)
else rest
mapping = "\"\\/\n\t\b\r\f"
hexQuad :: Z.Parser Int
hexQuad = do
s <- Z.take 4
let hex n | w >= C_0 && w <= C_9 = w - C_0
| w >= C_a && w <= C_f = w - 87
| w >= C_A && w <= C_F = w - 55
| otherwise = 255
where w = fromIntegral $ B.unsafeIndex s n
a = hex 0; b = hex 1; c = hex 2; d = hex 3
if (a .|. b .|. c .|. d) /= 255
then return $! d .|. (c `shiftL` 4) .|. (b `shiftL` 8) .|. (a `shiftL` 12)
else fail "invalid hex escape"
decodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString -> Maybe a
decodeWith p to s =
case L.parse p s of
L.Done _ v -> case to v of
Success a -> Just a
_ -> Nothing
_ -> Nothing
{-# INLINE decodeWith #-}
decodeStrictWith :: Parser Value -> (Value -> Result a) -> B.ByteString
-> Maybe a
decodeStrictWith p to s =
case either Error to (A.parseOnly p s) of
Success a -> Just a
Error _ -> Nothing
{-# INLINE decodeStrictWith #-}
eitherDecodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString
-> Either String a
eitherDecodeWith p to s =
case L.parse p s of
L.Done _ v -> case to v of
Success a -> Right a
Error msg -> Left msg
L.Fail _ _ msg -> Left msg
{-# INLINE eitherDecodeWith #-}
eitherDecodeStrictWith :: Parser Value -> (Value -> Result a) -> B.ByteString
-> Either String a
eitherDecodeStrictWith p to s =
case either Error to (A.parseOnly p s) of
Success a -> Right a
Error msg -> Left msg
{-# INLINE eitherDecodeStrictWith #-}
-- $lazy
--
-- The 'json' and 'value' parsers decouple identification from
-- conversion. Identification occurs immediately (so that an invalid
-- JSON document can be rejected as early as possible), but conversion
-- to a Haskell value is deferred until that value is needed.
--
-- This decoupling can be time-efficient if only a smallish subset of
-- elements in a JSON value need to be inspected, since the cost of
-- conversion is zero for uninspected elements. The trade off is an
-- increase in memory usage, due to allocation of thunks for values
-- that have not yet been converted.
-- $strict
--
-- The 'json'' and 'value'' parsers combine identification with
-- conversion. They consume more CPU cycles up front, but have a
-- smaller memory footprint.
-- | Parse a top-level JSON value followed by optional whitespace and
-- end-of-input. See also: 'json'.
jsonEOF :: Parser Value
jsonEOF = json <* skipSpace <* endOfInput
-- | Parse a top-level JSON value followed by optional whitespace and
-- end-of-input. See also: 'json''.
jsonEOF' :: Parser Value
jsonEOF' = json' <* skipSpace <* endOfInput
toByteString :: Builder -> ByteString
toByteString = L.toStrict . toLazyByteString
{-# INLINE toByteString #-}
aeson :: IO Benchmark
aeson = do
path <- pathTo "json-data"
names <- sort . filter (`notElem` [".", ".."]) <$> getDirectoryContents path
benches <- forM names $ \name -> do
bs <- B.readFile (path </> name)
return . bench (dropExtension name) $ nf (A.parseOnly jsonEOF') bs
return $ bgroup "aeson" benches
|
beni55/attoparsec
|
benchmarks/Aeson.hs
|
bsd-3-clause
| 11,671 | 10 | 34 | 3,376 | 3,104 | 1,593 | 1,511 | 254 | 7 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sq-AL">
<title>Code Dx | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_sq_AL/helpset_sq_AL.hs
|
apache-2.0
| 968 | 83 | 52 | 159 | 396 | 209 | 187 | -1 | -1 |
-- | UTF-8 encode a text
--
-- Tested in this benchmark:
--
-- * Replicating a string a number of times
--
-- * UTF-8 encoding it
--
module Benchmarks.EncodeUtf8
( benchmark
) where
import Criterion (Benchmark, bgroup, bench, whnf)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
benchmark :: String -> IO Benchmark
benchmark string = do
return $ bgroup "EncodeUtf8"
[ bench "Text" $ whnf (B.length . T.encodeUtf8) text
, bench "LazyText" $ whnf (BL.length . TL.encodeUtf8) lazyText
]
where
-- The string in different formats
text = T.replicate k $ T.pack string
lazyText = TL.replicate (fromIntegral k) $ TL.pack string
-- Amount
k = 100000
|
beni55/text
|
benchmarks/haskell/Benchmarks/EncodeUtf8.hs
|
bsd-2-clause
| 901 | 0 | 14 | 198 | 226 | 135 | 91 | 17 | 1 |
{-# LANGUAGE DeriveDataTypeable, TypeFamilies, TemplateHaskell,
RankNTypes, NamedFieldPuns, RecordWildCards,
RecursiveDo, BangPatterns, CPP #-}
module Distribution.Server.Features.HoogleData (
initHoogleDataFeature,
HoogleDataFeature(..),
) where
import Distribution.Server.Framework hiding (path)
import Distribution.Server.Framework.BlobStorage (BlobId)
import qualified Distribution.Server.Framework.BlobStorage as BlobStorage
import Distribution.Server.Features.Core
import Distribution.Server.Features.Documentation
import Distribution.Server.Features.TarIndexCache
import qualified Distribution.Server.Packages.PackageIndex as PackageIndex
import Data.TarIndex as TarIndex
import Distribution.Package
import Distribution.Text
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
import qualified Codec.Compression.GZip as GZip
import qualified Codec.Compression.Zlib.Internal as Zlib
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.ByteString.Lazy as BS
import Data.Serialize (runGetLazy, runPutLazy)
import Data.SafeCopy (SafeCopy, safeGet, safePut)
import Data.Maybe
import Control.Monad.State
import System.IO
import System.IO.Unsafe (unsafeInterleaveIO)
import System.Directory
import System.FilePath
import Control.Concurrent.MVar
import Control.Concurrent.Async
import Control.Exception
import qualified System.IO.Error as IOError
-- | A feature to serve up a tarball of hoogle files, for the hoogle client.
--
data HoogleDataFeature = HoogleDataFeature {
hoogleDataFeatureInterface :: HackageFeature
}
instance IsHackageFeature HoogleDataFeature where
getFeatureInterface = hoogleDataFeatureInterface
----------------------------------------
-- Feature definition & initialisation
--
initHoogleDataFeature :: ServerEnv
-> IO (CoreFeature
-> DocumentationFeature
-> TarIndexCacheFeature
-> IO HoogleDataFeature)
initHoogleDataFeature env@ServerEnv{ serverCacheDelay,
serverVerbosity = verbosity } = do
-- Ephemeral state
docsUpdatedState <- newMemStateWHNF Set.empty
hoogleBundleUpdateJob <- newAsyncUpdate serverCacheDelay verbosity
"hoogle.tar.gz"
return $ \core docs tarIndexCache -> do
let feature = hoogleDataFeature docsUpdatedState
hoogleBundleUpdateJob
env core docs tarIndexCache
return feature
hoogleDataFeature :: MemState (Set PackageId)
-> AsyncUpdate
-> ServerEnv
-> CoreFeature
-> DocumentationFeature
-> TarIndexCacheFeature
-> HoogleDataFeature
hoogleDataFeature docsUpdatedState hoogleBundleUpdateJob
ServerEnv{serverBlobStore = store, serverStateDir}
CoreFeature{..} DocumentationFeature{..}
TarIndexCacheFeature{..}
= HoogleDataFeature {..}
where
hoogleDataFeatureInterface = (emptyHackageFeature "hoogle-data") {
featureDesc = "Provide a tarball of all package's hoogle files"
, featureResources = [hoogleBundleResource]
, featureState = []
, featureCaches = []
, featurePostInit = postInit
}
-- Resources
--
hoogleBundleResource =
(resourceAt "/packages/hoogle.tar.gz") {
resourceDesc = [ (GET, "get the tarball of hoogle files for all packages")
]
, resourceGet = [ ("tarball", serveHoogleData) ]
}
-- Request handlers
--
featureStateDir = serverStateDir </> "db" </> "HoogleData"
bundleTarGzFile = featureStateDir </> "hoogle.tar.gz"
bundleCacheFile = featureStateDir </> "cache"
serveHoogleData :: DynamicPath -> ServerPartE Response
serveHoogleData _ =
-- serve the cached hoogle.tar.gz file
serveFile (asContentType "application/x-gzip") bundleTarGzFile
postInit :: IO ()
postInit = do
createDirectoryIfMissing False featureStateDir
prodFileCacheUpdate
registerHook documentationChangeHook $ \pkgid -> do
modifyMemState docsUpdatedState (Set.insert pkgid)
prodFileCacheUpdate
prodFileCacheUpdate :: IO ()
prodFileCacheUpdate =
asyncUpdate hoogleBundleUpdateJob updateHoogleBundle
-- Actually do the update. Here we are guaranteed that we're only doing
-- one update at once, no concurrent updates.
updateHoogleBundle :: IO ()
updateHoogleBundle = do
docsUpdated <- readMemState docsUpdatedState
writeMemState docsUpdatedState Set.empty
updated <- maybeWithFile bundleTarGzFile $ \mhOldTar -> do
mcache <- readCacheFile bundleCacheFile
let docEntryCache = maybe Map.empty fst mcache
oldTarPkgids = maybe Set.empty snd mcache
tmpdir = featureStateDir
updateTarBundle mhOldTar tmpdir
docEntryCache oldTarPkgids
docsUpdated
case updated of
Nothing -> return ()
Just (docEntryCache', newTarPkgids, newTarFile) -> do
renameFile newTarFile bundleTarGzFile
writeCacheFile bundleCacheFile (docEntryCache', newTarPkgids)
updateTarBundle :: Maybe Handle -> FilePath
-> Map PackageId (Maybe (BlobId, TarEntryOffset))
-> Set PackageId
-> Set PackageId
-> IO (Maybe (Map PackageId (Maybe (BlobId, TarEntryOffset))
,Set PackageId, FilePath))
updateTarBundle mhOldTar tmpdir docEntryCache oldTarPkgids docsUpdated = do
-- Invalidate cached info about any package docs that have been updated
let docEntryCache' = docEntryCache `Map.difference` fromSet docsUpdated
cachedPkgids = fromSet (oldTarPkgids `Set.difference` docsUpdated)
-- get the package & docs index
pkgindex <- queryGetPackageIndex
docindex <- queryDocumentationIndex
-- Select the package ids that have corresponding docs that contain a
-- hoogle .txt file.
-- We prefer later package versions, but if a later one is missing the
-- hoogle .txt file then we fall back to older ones.
--
-- For the package ids we pick we keep the associated doc tarball blobid
-- and the offset of the hoogle .txt file within that tarball.
--
-- Looking up if a package's docs contains the hoogle .txt file is
-- expensive (have to read the doc tarball's index) so we maintain a
-- cache of that information.
(selectedPkgids, docEntryCache'') <-
-- use a state monad for access to and updating the cache
flip runStateT docEntryCache' $
fmap (Map.fromList . catMaybes) $
sequence
[ findFirstCached (lookupHoogleEntry docindex)
(reverse (map packageId pkgs))
| pkgs <- PackageIndex.allPackagesByName pkgindex ]
-- the set of pkgids to try to reuse from the existing tar file
let reusePkgs :: Map PackageId ()
reusePkgs = cachedPkgids `Map.intersection` selectedPkgids
-- the packages where we need to read it fresh
readFreshPkgs :: Map PackageId (BlobId, TarEntryOffset)
readFreshPkgs = selectedPkgids `Map.difference` reusePkgs
if Map.null readFreshPkgs && Map.keysSet reusePkgs == oldTarPkgids
then return Nothing
else liftM Just $
withTempFile tmpdir "newtar" $ \hNewTar newTarFile ->
withWriter (tarWriter hNewTar) $ \putEntry -> do
-- We truncate on tar format errors. This works for the empty case
-- and should be self-correcting for real errors. It just means we
-- miss a few entries from the tarball 'til next time its updated.
oldEntries <- case mhOldTar of
Nothing -> return []
Just hOldTar ->
return . Tar.foldEntries (:) [] (const [])
. Tar.read
. BS.fromChunks
. Zlib.foldDecompressStream (:) [] (\_ _ -> [])
. Zlib.decompressWithErrors
Zlib.gzipFormat
Zlib.defaultDecompressParams
=<< BS.hGetContents hOldTar
-- Write out the cached ones
sequence_
[ putEntry entry
| entry <- oldEntries
, pkgid <- maybeToList (entryPkgId entry)
, pkgid `Map.member` reusePkgs ]
-- Write out the new/changed ones
sequence_
[ withFile doctarfile ReadMode $ \hDocTar -> do
mentry <- newCacheTarEntry pkgid hDocTar taroffset
maybe (return ()) putEntry mentry
| (pkgid, (doctarblobid, taroffset)) <- Map.toList readFreshPkgs
, let doctarfile = BlobStorage.filepath store doctarblobid ]
return (docEntryCache'', Map.keysSet selectedPkgids, newTarFile)
lookupHoogleEntry :: Map PackageId BlobId -> PackageId -> IO (Maybe (BlobId, TarEntryOffset))
lookupHoogleEntry docindex pkgid
| Just doctarblobid <- Map.lookup pkgid docindex
= do doctarindex <- cachedTarIndex doctarblobid
case lookupPkgDocHoogleFile pkgid doctarindex of
Nothing -> return Nothing
Just offset -> return (Just (doctarblobid, offset))
| otherwise = return Nothing
fromSet :: Ord a => Set a -> Map a ()
fromSet = Map.fromAscList . map (\x -> (x, ())) . Set.toAscList
-- | Like list 'find' but with a monadic lookup function and we cache the
-- results of that lookup function.
--
findFirstCached :: (Ord a, Monad m)
=> (a -> m (Maybe b))
-> [a] -> StateT (Map a (Maybe b)) m (Maybe (a, b))
findFirstCached _ [] = return Nothing
findFirstCached f (x:xs) = do
cache <- get
case Map.lookup x cache of
Just m_y -> checkY m_y
Nothing -> do
m_y <- lift (f x)
put (Map.insert x m_y cache)
checkY m_y
where
checkY Nothing = findFirstCached f xs
checkY (Just y) = return (Just (x, y))
withTempFile :: FilePath -> String -> (Handle -> FilePath -> IO a) -> IO a
withTempFile tmpdir template action =
mask $ \restore -> do
(fname, hnd) <- openTempFile tmpdir template
x <- restore (action hnd fname)
`onException` (hClose hnd >> removeFile fname)
hClose hnd
return x
maybeWithFile :: FilePath -> (Maybe Handle -> IO a) -> IO a
maybeWithFile file action =
mask $ \unmask -> do
mhnd <- try $ openFile file ReadMode
case mhnd of
Right hnd -> unmask (action (Just hnd)) `finally` hClose hnd
Left e | IOError.isDoesNotExistError e
, Just file == IOError.ioeGetFileName e
-> unmask (action Nothing)
Left e -> throw e
readCacheFile :: SafeCopy a => FilePath -> IO (Maybe a)
readCacheFile file =
maybeWithFile file $ \mhnd ->
case mhnd of
Nothing -> return Nothing
Just hnd -> do
content <- BS.hGetContents hnd
case runGetLazy safeGet content of
Left _ -> return Nothing
Right x -> return (Just x)
writeCacheFile :: SafeCopy a => FilePath -> a -> IO ()
writeCacheFile file x =
BS.writeFile file (runPutLazy (safePut x))
lookupPkgDocHoogleFile :: PackageId -> TarIndex -> Maybe TarEntryOffset
lookupPkgDocHoogleFile pkgid index = do
TarFileEntry offset <- TarIndex.lookup index path
return offset
where
path = (display pkgid ++ "-docs") </> display (packageName pkgid) <.> "txt"
newCacheTarEntry :: PackageId -> Handle -> TarEntryOffset -> IO (Maybe Tar.Entry)
newCacheTarEntry pkgid htar offset
| Just entrypath <- hoogleDataTarPath pkgid = do
morigEntry <- readTarEntryAt htar offset
case morigEntry of
Nothing -> return Nothing
Just origEntry ->
return $ Just
(Tar.simpleEntry entrypath (Tar.entryContent origEntry)) {
Tar.entryTime = Tar.entryTime origEntry
}
| otherwise = return Nothing
hoogleDataTarPath :: PackageId -> Maybe Tar.TarPath
hoogleDataTarPath pkgid =
either (const Nothing) Just (Tar.toTarPath False filepath)
where
-- like zlib/0.5.4.1/doc/html/zlib.txt
filepath = joinPath [ display (packageName pkgid)
, display (packageVersion pkgid)
, "doc", "html"
, display (packageName pkgid) <.> "txt" ]
entryPkgId :: Tar.Entry -> Maybe PackageId
entryPkgId = parseEntryPath . Tar.entryPath
parseEntryPath :: FilePath -> Maybe PackageId
parseEntryPath filename
| [namestr, verstr,
"doc", "html",
filestr] <- splitDirectories filename
, Just pkgname <- simpleParse namestr
, Just pkgver <- simpleParse verstr
, (namestr', ".txt") <- splitExtension filestr
, Just pkgname' <- simpleParse namestr'
, pkgname == pkgname'
= Just (PackageIdentifier pkgname pkgver)
| otherwise
= Nothing
readTarEntryAt :: Handle -> TarEntryOffset -> IO (Maybe Tar.Entry)
readTarEntryAt htar off = do
hSeek htar AbsoluteSeek (fromIntegral (off * 512))
header <- BS.hGet htar 512
case Tar.read header of
(Tar.Next [email protected]{Tar.entryContent = Tar.NormalFile _ size} _) -> do
content <- BS.hGet htar (fromIntegral size)
return $ Just entry { Tar.entryContent = Tar.NormalFile content size }
_ -> return Nothing
data Writer a = Writer { wWrite :: a -> IO (), wClose :: IO () }
withWriter :: IO (Writer b) -> ((b -> IO ()) -> IO a) -> IO a
withWriter mkwriter action = bracket mkwriter wClose (action . wWrite)
tarWriter :: Handle -> IO (Writer Tar.Entry)
tarWriter hnd = do
chan <- newBChan
awriter <- async $ do
entries <- getBChanContents chan
BS.hPut hnd ((GZip.compress . Tar.write) entries)
return Writer {
wWrite = writeBChan chan,
wClose = do closeBChan chan
wait awriter
}
newtype BChan a = BChan (MVar (Maybe a))
newBChan :: IO (BChan a)
newBChan = liftM BChan newEmptyMVar
writeBChan :: BChan a -> a -> IO ()
writeBChan (BChan c) = putMVar c . Just
closeBChan :: BChan a -> IO ()
closeBChan (BChan c) = putMVar c Nothing
getBChanContents :: BChan a -> IO [a]
getBChanContents (BChan c) = do
res <- takeMVar c
case res of
Nothing -> return []
Just x -> do xs <- unsafeInterleaveIO (getBChanContents (BChan c))
return (x : xs)
|
ocharles/hackage-server
|
Distribution/Server/Features/HoogleData.hs
|
bsd-3-clause
| 14,928 | 0 | 29 | 4,259 | 3,631 | 1,850 | 1,781 | 290 | 5 |
-- Trac #958
module ShoulFail where
data Succ a = S a -- NB: deriving Show omitted
data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
|
ezyang/ghc
|
testsuite/tests/typecheck/should_fail/tcfail169.hs
|
bsd-3-clause
| 148 | 0 | 10 | 39 | 46 | 28 | 18 | 3 | 0 |
{-# LANGUAGE Arrows #-}
module Main(main) where
import Control.Arrow
import Control.Category
import Prelude hiding (id, (.))
class ArrowLoop a => ArrowCircuit a where
delay :: b -> a b b
-- stream map instance
data Stream a = Cons a (Stream a)
instance Functor Stream where
fmap f ~(Cons a as) = Cons (f a) (fmap f as)
zipStream :: Stream a -> Stream b -> Stream (a,b)
zipStream ~(Cons a as) ~(Cons b bs) = Cons (a,b) (zipStream as bs)
unzipStream :: Stream (a,b) -> (Stream a, Stream b)
unzipStream abs = (fmap fst abs, fmap snd abs)
newtype StreamMap a b = StreamMap (Stream a -> Stream b)
unStreamMap (StreamMap f) = f
instance Category StreamMap where
id = StreamMap id
StreamMap f . StreamMap g = StreamMap (f . g)
instance Arrow StreamMap where
arr f = StreamMap (fmap f)
first (StreamMap f) =
StreamMap (uncurry zipStream . first f . unzipStream)
instance ArrowLoop StreamMap where
loop (StreamMap f) =
StreamMap (loop (unzipStream . f . uncurry zipStream))
instance ArrowCircuit StreamMap where
delay a = StreamMap (Cons a)
listToStream :: [a] -> Stream a
listToStream = foldr Cons undefined
streamToList :: Stream a -> [a]
streamToList (Cons a as) = a:streamToList as
runStreamMap :: StreamMap a b -> [a] -> [b]
runStreamMap (StreamMap f) as =
take (length as) (streamToList (f (listToStream as)))
-- simple automaton instance
data Auto a b = Auto (a -> (b, Auto a b))
instance Category Auto where
id = Auto $ \a -> (a, id)
Auto f . Auto g = Auto $ \b ->
let (c, g') = g b
(d, f') = f c
in (d, f' . g')
instance Arrow Auto where
arr f = Auto $ \a -> (f a, arr f)
first (Auto f) = Auto $ \(b,d) -> let (c,f') = f b in ((c,d), first f')
instance ArrowLoop Auto where
loop (Auto f) = Auto $ \b ->
let (~(c,d), f') = f (b,d)
in (c, loop f')
instance ArrowCircuit Auto where
delay a = Auto $ \a' -> (a, delay a')
runAuto :: Auto a b -> [a] -> [b]
runAuto (Auto f) [] = []
runAuto (Auto f) (a:as) = let (b, f') = f a in b:runAuto f' as
-- Some simple example circuits
-- A resettable counter (first example in several Hawk papers):
counter :: ArrowCircuit a => a Bool Int
counter = proc reset -> do
rec output <- returnA -< if reset then 0 else next
next <- delay 0 -< output+1
returnA -< output
-- Some other basic circuits from the Hawk library.
-- flush: when reset is True, return d for n ticks, otherwise copy value.
-- (a variation on the resettable counter)
flush :: ArrowCircuit a => Int -> b -> a (b, Bool) b
flush n d = proc (value, reset) -> do
rec count <- returnA -< if reset then n else max (next-1) 0
next <- delay 0 -< count
returnA -< if count > 0 then d else value
-- latch: on each tick, return the last value for which reset was True,
-- or init if there was none.
--
latch :: ArrowCircuit a => b -> a (b, Bool) b
latch init = proc (value, reset) -> do
rec out <- returnA -< if reset then value else last
last <- delay init -< out
returnA -< out
-- Some tests using the counter
test_input = [True, False, True, False, False, True, False, True]
test_input2 = zip [1..] test_input
-- A test of the resettable counter.
main = do
print (runStreamMap counter test_input)
print (runAuto counter test_input)
print (runStreamMap (flush 2 0) test_input2)
print (runAuto (flush 2 0) test_input2)
print (runStreamMap (latch 0) test_input2)
print (runAuto (latch 0) test_input2)
-- A step function (cf current in Lustre)
step :: ArrowCircuit a => b -> a (Either b c) b
step b = proc x -> do
rec last_b <- delay b -< getLeft last_b x
returnA -< last_b
where getLeft _ (Left b) = b
getLeft b (Right _) = b
|
wxwxwwxxx/ghc
|
testsuite/tests/arrows/should_run/arrowrun003.hs
|
bsd-3-clause
| 3,614 | 22 | 17 | 781 | 1,619 | 823 | 796 | 84 | 3 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module JPSubreddits.Types where
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class (MonadIO)
import Data.Aeson (FromJSON (..), ToJSON (..), object, (.:), (.=))
import Data.Text (Text)
import Data.Time (ZonedTime)
class DataSource a where
getListFromDataSource :: (Functor m, MonadIO m) => a -> m [(CategoryName, [(Title, Url)])]
newtype Url = Url { unUrl :: Text }
deriving (Show, Read, ToJSON, FromJSON)
newtype Title = Title { unTitle :: Text }
deriving (Show, Read, ToJSON, FromJSON)
newtype CategoryName = CategoryName { unCategoryName :: Text }
deriving (Show, Read, ToJSON, FromJSON)
data Subreddit = Subreddit
{ url :: Url
, title :: Title
}
deriving (Show, Read)
data Category = Category
{ name :: CategoryName
, subreddits :: [Subreddit]
}
deriving (Show, Read)
data JPSubreddits = JPSubreddits
{ generatedAt :: ZonedTime
, categories :: [Category]
}
deriving (Show, Read)
---------------------------------------------
-- Instancies
---------------------------------------------
instance FromJSON Subreddit where
parseJSON = parseJSON >=> go
where
go o = Subreddit
<$> o .: "url"
<*> o .: "title"
instance ToJSON Subreddit where
toJSON s = object
[ "url" .= url s
, "title" .= title s
]
instance FromJSON Category where
parseJSON = parseJSON >=> go
where
go o = Category
<$> o .: "category"
<*> o .: "list"
instance ToJSON Category where
toJSON s = object
[ "category" .= name s
, "list" .= subreddits s
]
instance FromJSON JPSubreddits where
parseJSON = parseJSON >=> go
where
go o = JPSubreddits
<$> o .: "generated_at"
<*> o .: "jpsubreddits"
instance ToJSON JPSubreddits where
toJSON s = object
[ "generated_at" .= show (generatedAt s)
, "jpsubreddits" .= categories s
]
|
sifisifi/jpsubreddits
|
src/JPSubreddits/Types.hs
|
mit
| 2,136 | 0 | 13 | 614 | 591 | 333 | 258 | 56 | 0 |
-- prolog engine v1
-- TODO lists and strings
import Prelude hiding (pred)
import Test.Hspec
import Text.ParserCombinators.Parsec
import Text.Parsec.Error
import Control.Applicative hiding ((<|>), many)
import Control.Monad
import System.IO
import Data.List
import Data.Maybe
import qualified Data.Map as Map
--import Debug.Trace (trace)
type VarName = String
data Term = Atom String | Var VarName | Func String [Term] | Int Integer
deriving (Show, Eq)
data Pred = Pred String [Term] | NegPred String [Term]
deriving (Show, Eq)
data Rule = Rule Pred [Pred]
deriving (Show, Eq)
-- do we need a completely separate representation of logical formulas?
type Clause = [Pred]
-- substitution Var -> Term
type Sub = Map.Map VarName Term
-- ====== --
-- Parser --
-- ====== --
lowerWordP :: Parser String
lowerWordP = (:) <$> lower <*> many alphaNum
atomP :: Parser Term
atomP = Atom <$> lowerWordP
varP :: Parser Term
varP = liftM Var $ (:) <$> upper <*> many alphaNum
intP :: Parser Term
intP = Int . read <$> many1 digit
funcP :: Parser Term
funcP = Func <$>
((lowerWordP <|> string ".") <* char '(') <*>
(termListP <* char ')')
termP :: Parser Term
termP = try funcP <|> intP <|> varP <|> atomP
-- interesting approach for just a list of terms, "return" here acts
-- as the list constructor
-- termListP = return <$> termP
termListP :: Parser [Term]
-- left-recursive version doesn't work
-- termListP = ((++) <$> termListP <* char ',' <*> (return <$> termP)) <|>
-- return <$> termP
termListP = sepBy termP (char ',' <* spaces)
predP :: Parser Pred
predP = Pred <$> lowerWordP <* char '(' <*> termListP <* char ')'
predListP :: Parser [Pred]
predListP = sepBy predP (char ',' <* spaces)
queryP :: Parser [Pred]
queryP = predListP <* char '.'
ruleP :: Parser Rule
ruleP = Rule <$> predP <* spaces <* string ":-" <* spaces <*> predListP <* char '.'
-- =========== --
-- Unification --
-- =========== --
-- handbook of tableau methods (pg 160)
-- purposely don't handle term lists of different lengths. will throw an exception at runtime
-- should probably handle functors with different arity here as they will never unify anyways
disagreement :: [Term] -> [Term] -> Maybe (Term, Term)
disagreement [] [] = Nothing
disagreement (x:xs) (y:ys)
| x == y = disagreement xs ys
disagreement (Func f1 args1 : _) (Func f2 args2 : _)
-- decomposition of functors, agreeing functors handled above
| f1 == f2 = disagreement args1 args2
-- make sure the variable comes first if there is one
-- disagreement (x:_) (y:_) = Just $ case x of Var _ -> (x, y)
-- _ -> (y, x)
-- clearer than preceding?
disagreement (x@(Var _):_) (y:_) = Just (x, y)
disagreement (x:_) (y:_) = Just (y, x)
applySub :: [Term] -> Sub -> [Term]
applySub [] _ = []
applySub (t@(Var v):ts) sub = newT : applySub ts sub
where newT = case Map.lookup v sub of
Just x -> x
_ -> t
applySub (Func f args : ts) sub = Func f (applySub args sub) : applySub ts sub
applySub (t:ts) sub = t : applySub ts sub
applySubPred :: Pred -> Sub -> Pred
applySubPred (Pred name args) s = Pred name (applySub args s)
applySubPred (NegPred name args) s = NegPred name (applySub args s)
occursCheck :: Term -> String -> Bool
occursCheck (Atom _) _ = False
occursCheck (Func _ args) vname = Var vname `elem` args
occursCheck _ _ = False
unify :: [Term] -> [Term] -> Maybe Sub
unify = let applyAndContinue s t1 t2 = unifyInternal s t1' t2'
where t1' = applySub t1 s
t2' = applySub t2 s
unifyInternal s t1 t2 = case disagreement t1 t2 of
Nothing -> Just s
Just (Var vname, t)
| not $ occursCheck t vname ->
applyAndContinue (Map.insert vname t s) t1 t2
_ -> Nothing
in unifyInternal Map.empty
-- unify [Func "vertical" [Func "line" [Func "point" [Var "X", Var "Y"], Func "point" [Var "X", Var "Z"]]]] [Func "vertical" [Func "line" [Func "point" [Var "X", Var "Y"], Func "point" [Var "X", Var "Z"]]]]
-- TODO add these to tests:
{--
*Main> unify [Func "vertical" [Func "line" [Func "point" [Var "X", Var "Y"], Func "point" [Var "X", Var "Z"]]]] [Func "vertical" [Func "line" [Func "point" [Int 1, Int 1], Func "point" [Int 1, Int 3]]]]
Just (fromList [("X",Int 1),("Y",Int 1),("Z",Int 3)])
*Main> unify [Func "vertical" [Func "line" [Func "point" [Var "X", Var "Y"], Func "point" [Var "X", Var "Z"]]]] [Func "vertical" [Func "line" [Func "point" [Int 1, Int 1], Func "point" [Int 3, Int 2]]]]
Nothing
--}
-- ========== --
-- Resolution --
-- ========== --
-- KB is (ultimately) a conjunction of clauses
testKb1 :: [Clause]
testKb1 = [[Pred "rdf:type" [Atom "bsbase:ABriefHistoryOfEverything",
Atom "bibo:Book"]],
[Pred "bsbase:subject" [Atom "bsbase:ABriefHistoryOfEverything",
Atom "bsbase:IntegralTheory"]],
-- thinksItsCool(X, Y) :- thinksItsCool(jess, Y).
-- If Jess thinks it's cool, everyone thinks it's cool.
[Pred "thinksItsCool" [Var "X", Var "Y"],
NegPred "thinksItsCool" [Atom "jess", Var "Y"]],
[Pred "thinksItsCool" [Atom "jess", Atom "PhilCollins"]],
[Pred "f" [Atom "a"]], [Pred "f" [Atom "b"]],
[Pred "g" [Atom "a"]], [Pred "g" [Atom "b"]],
[Pred "h" [Atom "b"]],
[Pred "k" [Var "X"], NegPred "f" [Var "X"], NegPred "g" [Var "X"], NegPred "h" [Var "X"]]]
predArgs :: Pred -> [Term]
predArgs (Pred _ a) = a
predArgs (NegPred _ a) = a
predVarNames :: Pred -> [VarName]
predVarNames =
let foldIt names term = case term of (Var name) -> name:names; _ -> names
in nub . foldl foldIt [] . predArgs
-- find a way to rewrite this?
findClashingPred :: Clause -> Pred -> Maybe (Pred, Clause)
findClashingPred c (Pred predName _) = case partition (\x -> case x of NegPred predName' _ | predName' == predName -> True
_ -> False) c
of ([p], rest) -> Just (p, rest)
_ -> Nothing
findClashingPred c (NegPred predName _) = case partition (\x -> case x of Pred predName' _ | predName' == predName -> True
_ -> False) c
of ([p], rest) -> Just (p, rest)
_ -> Nothing
findClashingClauses :: [Clause] -> Pred -> [(Sub, Clause)]
findClashingClauses clauses pred =
let clausesMatchingPred :: [(Pred, Clause)]
clausesMatchingPred = mapMaybe (`findClashingPred` pred) clauses
args :: [Term]
args = predArgs pred
maybeUnifyAndReturnBoth :: (Pred, Clause) -> Maybe (Sub, Clause)
--maybeUnifyAndReturnBoth (p, c) = (unify args $ predArgs p) >>= (\sub -> return (p, map (`applySubPred` sub) c))
maybeUnifyAndReturnBoth (p, c) = do
sub <- unify args $ predArgs p
return (sub, map (`applySubPred` sub) c)
-- clausesUnifying :: [Sub]
-- clausesUnifying = mapMaybe ((unify args) . (predArgs . fst)) clausesMatchingPred
-- c0 = head clausesMatchingPred
-- c0args = (predArgs . fst) c0
-- c0sub = fromJust $ unify args c0args
-- c0resolvents = map (`applySubPred` c0sub) $ snd c0
--dealWithPred possibleClash =
in --[c0resolvents]
mapMaybe maybeUnifyAndReturnBoth clausesMatchingPred
-- TODO allow multiple clauses instead of a single predicate
solve1 :: Pred -> [Clause] -> [Sub]
solve1 pred kb =
let clashes0 :: (Sub, Clause)
clashes0 = head $ findClashingClauses kb pred
--vars = predVars pred
in []
solve01 :: [Clause] -> [Term] -> Sub -> Maybe Sub
-- nothing left to resolve, return sub
solve01 [] _ s = Just s
solve01 clauses vars s =
let kb :: [Clause]
kb = testKb1
sub :: Sub
sub = fst . head $ findClashingClauses kb $ (head . head) clauses
in Nothing
-- resolve :: Pred -> Disj -> Disj
-- resolve _ [] = []
-- resolve goal ps = -- @(Pred pname args) ps =
-- -- let x a b = (a, b)
-- -- in snd $ mapAccumL x "" []
-- let (negGoal, gname, gargs) = case goal of
-- NegPred gname gargs -> (Pred gname gargs, gname, gargs)
-- Pred gname gargs -> (NegPred gname gargs, gname, gargs)
-- xXX (sub, newList) (Pred pname args:ps)
-- | pname == gname and s@(unify args gargs) = (s
-- foldl xXX (Map.empty, []) ps
-- ========================== --
-- repl stuff copied from:
-- ========================== --
-- http://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours/Building_a_REPL
flushStr :: String -> IO ()
flushStr str = putStr str >> hFlush stdout
readPrompt :: String -> IO String
readPrompt prompt = flushStr prompt >> getLine
evalString :: String -> IO String
evalString expr = --return $ extractValue $ trapError (liftM show $ readExpr expr >>= eval)
return $ case parse (queryP <* eof) "" expr
of Right x -> show x
-- TODO this error message isn't useful
Left err -> intercalate "\n" (map messageString $ errorMessages err)
--Left err -> foldl (\x y -> messageString x ++ y (Message "") $ errorMessages err
evalAndPrint :: String -> IO ()
evalAndPrint expr = evalString expr >>= putStrLn
until_ :: Monad m => (a -> Bool) -> m a -> (a -> m ()) -> m ()
until_ pred prompt action = do
result <- prompt
unless (pred result) $ action result >> until_ pred prompt action
runRepl :: IO ()
runRepl = until_ (== "quit") (readPrompt "?- ") evalAndPrint
-- ===============================
main :: IO ()
main = do
putStrLn "================="
putStrLn " Prolog Engine 1"
putStrLn "================="
hspec . describe ">>> Parser tests" $ do
it "should parse basic predicates" $
case parse (predP <* eof) "" "pred(a, B)"
of Right x -> x `shouldBe`
Pred "pred" [Atom "a", Var "B"]
it "should parse functors" $
case parse (predP <* eof) "" "pred(sentence(nphrase(john),vbphrase(verb(likes),nphrase(mary))), B)"
of Right x -> x `shouldBe`
Pred "pred"
[Func "sentence"
[Func "nphrase"
[Atom "john"],
Func "vbphrase"
[Func "verb"
[Atom "likes"],
Func "nphrase"
[Atom "mary"]]],
Var "B"]
it "should parse rules" $
case parse (ruleP <* eof) "" "jealous(X, Y) :- loves(X, Z), loves(Y, Z)."
of Right x -> x `shouldBe`
Rule (Pred "jealous" [Var "X",Var "Y"])
[Pred "loves" [Var "X",Var "Z"],
Pred "loves" [Var "Y",Var "Z"]]
it "should parse unsugared lists" $
-- TODO last param should be the empty list
case parse (termP <* eof) "" ".(1, .(2, .(3, .())))"
of Right x -> x `shouldBe`
Func "." [Int 1,Func "." [Int 2,Func "." [Int 3,Func "." []]]]
hspec . describe ">>> Unification tests" $ do
it "should calculate disagreement sets properly" $
let dset = disagreement
[Func "g" [Atom "x"], Atom "y"]
[Func "g" [Atom "a", Atom "y", Atom "u"]] in
dset `shouldBe` Just (Atom "a",Atom "x")
it "should calculate disagreement sets with functors properly" $
let dset = disagreement
[Func "g" [Atom "x"], Atom "y"]
[Func "g" [Atom "x"], Atom "n", Atom "u"] in
dset `shouldBe` Just (Atom "n",Atom "y")
it "should apply a substitution" $
let sub = Map.fromList [("X",Atom "a")]
expr1 = Func "f" [Atom "b", Var "X"]
expr2 = Func "f" [Func "g" [Atom "a"]]
expr1' = applySub [expr1] sub
expr2' = applySub [expr2] sub
in (expr1', expr2') `shouldBe`
([Func "f" [Atom "b",Atom "a"]], [Func "f" [Func "g" [Atom "a"]]])
it "should perform a trivial unification" $
unify [Var "X"] [Atom "a"] `shouldBe` Just (Map.fromList [("X",Atom "a")])
it "should reject an invalid unification" $
unify [Atom "b"] [Func "f" [Var "X"]] `shouldBe` Nothing
it "should unify within functors" $
unify
[Atom "a", Func "f" [Atom "a", Var "X"]]
[Atom "a", Func "f" [Atom "a", Var "Y"]]
`shouldBe`
Just (Map.fromList [("X",Var "Y")])
it "should perform correctly on `complex terms' example" $
-- from Learn Prolog Now
unify
-- k(s(g), Y) = k(X, t(k))
[Func "k" [Func "s" [Atom "g"], Var "Y"]]
[Func "k" [Var "X", Func "t" [Atom "k"]]]
`shouldBe`
-- X = s(g), Y = t(k)
Just (Map.fromList [("X",Func "s" [Atom "g"]),("Y",Func "t" [Atom "k"])])
it "should reject impossible variable instantiations" $
unify
[Func "loves" [Var "X", Var "X"]]
[Func "loves" [Atom "marcellus", Atom "mia"]]
`shouldBe` Nothing
-- hspec . describe ">>> Resolution tests" $ do
-- it "should find clashing predicates in clauses" $
-- findClashingClauses testKb1 (NegPred "rdf:type" [])
-- `shouldBe`
-- [(Pred "rdf:type" [Atom "bsbase:ABriefHistoryOfEverything",Atom "bibo:Book"],[])]
-- it "should not find clashing predicates sometimes" $
-- findClashingClauses testKb1 (Pred "rdf:type" [])
-- `shouldBe` []
putStrLn "Welcome to Prolog Engine 1"
--runRepl
return ()
|
jbalint/banshee-sympatico
|
meera/prolog_engine1.hs
|
mit
| 13,740 | 0 | 23 | 3,937 | 3,734 | 1,937 | 1,797 | 221 | 5 |
module Operation
( Operation(..)
, operate
, undo
) where
import Data.Ix
data Operation = SwapIndices Int Int
| SwapLetters Char Char
| RotateLeft Int
| RotateRight Int
| RotateAroundLetter Char
| Reverse Int Int
| Move Int Int
deriving (Show)
operate :: String -> Operation -> String
operate str (SwapIndices x y) = map (\(c', c) -> if c == x then y' else if c == y then x' else c') (zip str [0..])
where (x', y') = (str !! x, str !! y)
operate str (SwapLetters x y) = map (\c -> if c == x then y else if c == y then x else c) str
operate str (RotateLeft steps)
| steps == 0 = str
| otherwise = operate str' (RotateLeft (steps - 1))
where str' = (tail str) ++ [head str]
operate str (RotateRight steps)
| steps == 0 = str
| otherwise = operate str' (RotateRight (steps - 1))
where str' = (last str) : (take (n - 1) str)
n = length str
operate str (RotateAroundLetter x) = operate str rotator
where xIndex = (snd . head) (filter (\(c, i) -> c == x) (zip str [0..]))
rotator = RotateRight (1 + xIndex + maybeExtra)
maybeExtra = if xIndex >= 4 then 1 else 0
operate str (Reverse x y) = front ++ (reverse middle) ++ back
where front = ((map fst) . (filter (\(a, b) -> b < x))) (zip str [0..])
middle = ((map fst) . (filter (\(a, b) -> inRange (x, y) b))) (zip str [0..])
back = ((map fst) . (filter (\(a, b) -> b > y))) (zip str [0..])
operate str (Move x y) = str''
where chr = str !! x
str' = (take x str) ++ (drop (x + 1) str)
str'' = (take y str') ++ [chr] ++ (drop y str')
undo :: String -> Operation -> String
undo str (RotateLeft steps) = operate str (RotateRight steps)
undo str (RotateRight steps) = operate str (RotateLeft steps)
undo str (RotateAroundLetter x) = until done (\str' -> operate str' (RotateLeft 1)) str
where done str' = str == (operate str' (RotateAroundLetter x))
undo str (Move x y) = operate str (Move y x)
undo str op = operate str op -- covers SwapIndices, SwapLetters, Reverse
instance Read Operation where
readsPrec _ ('s':'w':'a':'p':rs)
| r1 == "position" = [(SwapIndices ((read p1) :: Int) ((read p2) :: Int), "")]
| otherwise = [(SwapLetters (head p1) (head p2), "")]
where (r1:p1:_:_:p2:_) = words rs
readsPrec _ ('r':'o':'t':'a':'t':'e':rs)
| dir == "left" = [(RotateLeft n, "")]
| dir == "right" = [(RotateRight n, "")]
| otherwise = [(RotateAroundLetter ((head . last) rs'), "")]
where rs'@(dir:_) = words rs
n = read (rs' !! 1) :: Int
c = (head . last) rs'
readsPrec _ ('r':'e':'v':'e':'r':'s':'e':rs) = [(Reverse ((read p1) :: Int) ((read p2) :: Int), "")]
where (_:p1:_:p2:_) = words rs
readsPrec _ ('m':'o':'v':'e':rs) = [(Move ((read p1) :: Int) ((read p2) :: Int), "")]
where (_:p1:_:_:p2:_) = words rs
|
ajm188/advent_of_code
|
2016/21/Operation.hs
|
mit
| 2,988 | 0 | 15 | 842 | 1,548 | 819 | 729 | 61 | 6 |
module Test where
import Nat
import System.Random (newStdGen, randomRs)
import Tree (FoldTree (..), Tree (..))
tOrder = (5,2,10)
tBits = [15..17]
tFirstNat = fromInteger (5) :: Nat
tSecondNat = fromInteger (7) :: Nat
tContains = [[1..5], [2,0], [3,4]]
tList3 = [1..3] :: [Int]
tTree = Node 3 (Node 1 Leaf Leaf) $ Node 66 (Node 4 Leaf Leaf) Leaf
tFold = Tree 3 (Tree 1 Empty Empty) $ Tree 66 (Tree 4 Empty Empty) Empty
tList5 = [1..5]
tStr = "abc"
tCollect = [1..8]
passTests = [ "1", "1 2 3", " 1", "1 ", "\t1\t", "\t12345\t", "010 020 030"
, " 123 456 789 ", "-1", "-1 -2 -3", "\t-12345\t", " -123 -456 -789 "
, "\n1\t\n3 555 -1\n\n\n-5", "123\t\n\t\n\t\n321 -4 -40"
]
mustFail = ["asd", "1-1", "1.2", "--2", "+1", "1+"]
advancedTests = [ "+1", "1 +1", "-1 +1", "+1 -1"]
advancedMustFail = ["1+1", "++1", "-+1", "+-1", "1 + 1"]
tMerge = [2,1,0,3,10,5]
randomIntList :: Int -> Int -> Int -> IO [Int]
randomIntList n from to = take n . randomRs (from, to) <$> newStdGen
|
mortum5/programming
|
haskell/ITMO-Course/hw1/src/Test.hs
|
mit
| 1,068 | 0 | 9 | 276 | 430 | 255 | 175 | 24 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Text.Blaze.Bootstrap where
import qualified Text.Blaze.Html5 as BH
import qualified Text.Blaze.Internal as TBI
nav :: BH.Html -- ^ Inner HTML.
-> BH.Html -- ^ Resulting HTML.
nav = TBI.Parent "nav" "<nav" "</nav>"
-- Bootstrap attributes
dataToggle :: BH.AttributeValue -- ^ Attribute value.
-> BH.Attribute -- ^ Resulting attribute.
dataToggle = TBI.customAttribute "data-toggle"
dataTarget :: BH.AttributeValue -- ^ Attribute value.
-> BH.Attribute -- ^ Resulting attribute.
dataTarget = TBI.customAttribute "data-target"
ariaExpanded :: BH.AttributeValue -- ^ Attribute value.
-> BH.Attribute -- ^ Resulting attribute.
ariaExpanded = TBI.customAttribute "aria-expanded"
ariaControls :: BH.AttributeValue -- ^ Attribute value.
-> BH.Attribute -- ^ Resulting attribute.
ariaControls = TBI.customAttribute "aria-controls"
ariaHaspopup :: BH.AttributeValue -- ^ Attribute value.
-> BH.Attribute -- ^ Resulting attribute.
ariaHaspopup = TBI.customAttribute "aria-haspopup"
ariaLabelledby :: BH.AttributeValue -- ^ Attribute value.
-> BH.Attribute -- ^ Resulting attribute.
ariaLabelledby = TBI.customAttribute "aria-labelledby"
role :: BH.AttributeValue -- ^ Attribute value.
-> BH.Attribute -- ^ Resulting attribute.
role = TBI.customAttribute "role"
|
lhoghu/happstack
|
src/Text/Blaze/Bootstrap.hs
|
mit
| 1,444 | 0 | 6 | 310 | 231 | 135 | 96 | 28 | 1 |
module TestHelpers where
import qualified Data.Aeson as AE
import qualified Data.Aeson.Encode.Pretty as AE
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe (fromJust)
import Data.Text (Text, pack)
import GHC.Generics (Generic)
import Network.JSONApi
import Network.URL (URL, importURL)
prettyEncode :: AE.ToJSON a => a -> BS.ByteString
prettyEncode = AE.encodePretty' prettyConfig
prettyConfig :: AE.Config
prettyConfig = AE.defConfig
{ AE.confIndent = AE.Spaces 2
, AE.confCompare = mempty
}
class HasIdentifiers a where
uniqueId :: a -> Int
typeDescriptor :: a -> Text
data TestResource = TestResource
{ myId :: Int
, myName :: Text
, myAge :: Int
, myFavoriteFood :: Text
} deriving (Show, Generic)
instance AE.ToJSON TestResource
instance AE.FromJSON TestResource
instance ResourcefulEntity TestResource where
resourceIdentifier = pack . show . myId
resourceType _ = "testResource"
resourceLinks _ = Nothing
resourceMetaData _ = Nothing
resourceRelationships _ = Nothing
instance HasIdentifiers TestResource where
uniqueId = myId
typeDescriptor _ = "TestResource"
data OtherTestResource = OtherTestResource
{ myFavoriteNumber :: Int
, myJob :: Text
, myPay :: Int
, myEmployer :: Text
} deriving (Show, Generic)
instance AE.ToJSON OtherTestResource
instance AE.FromJSON OtherTestResource
instance ResourcefulEntity OtherTestResource where
resourceIdentifier = pack . show . myFavoriteNumber
resourceType _ = "otherTestResource"
resourceLinks _ = Nothing
resourceMetaData _ = Nothing
resourceRelationships _ = Nothing
instance HasIdentifiers OtherTestResource where
uniqueId = myFavoriteNumber
typeDescriptor _ = "OtherTestResource"
data TestMetaObject = TestMetaObject
{ totalPages :: Int
, isSuperFun :: Bool
} deriving (Show, Generic)
instance AE.ToJSON TestMetaObject
instance AE.FromJSON TestMetaObject
instance MetaObject TestMetaObject where
typeName _ = "importantData"
toResource' :: (HasIdentifiers a) => a
-> Maybe Links
-> Maybe Meta
-> Resource a
toResource' obj links meta =
Resource
(Identifier (pack . show . uniqueId $ obj) (typeDescriptor obj) meta)
obj
links
Nothing
linksObj :: Links
linksObj = mkLinks [ ("self", toURL "/things/1")
, ("related", toURL "http://some.domain.com/other/things/1")
]
testObject :: TestResource
testObject = TestResource 1 "Fred Armisen" 51 "Pizza"
testObject2 :: TestResource
testObject2 = TestResource 2 "Carrie Brownstein" 35 "Lunch"
otherTestObject :: OtherTestResource
otherTestObject = OtherTestResource 999 "Atom Smasher" 100 "Atom Smashers, Inc"
testMetaObj :: Meta
testMetaObj = mkMeta (TestMetaObject 3 True)
emptyMeta :: Maybe Meta
emptyMeta = Nothing
toURL :: String -> URL
toURL = fromJust . importURL
emptyLinks :: Maybe Links
emptyLinks = Nothing
|
toddmohney/json-api
|
test/TestHelpers.hs
|
mit
| 2,915 | 0 | 11 | 543 | 761 | 416 | 345 | 87 | 1 |
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE RecordWildCards #-}
------------------------------------------------------------------------------
-- |
-- Module : Forecast
-- Copyright : (C) 2014 Samuli Thomasson
-- License : MIT (see the file LICENSE)
-- Maintainer : Samuli Thomasson <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- Regression utilities.
------------------------------------------------------------------------------
module Forecast where
import ZabbixDB (Epoch)
import Control.Applicative
import Control.Arrow
import Control.Monad.State.Strict
import Data.Char (toLower)
import Data.Function
import Data.Aeson.TH
import Data.Vector.Storable (Vector)
import qualified Data.Vector.Storable as V
import qualified Data.Vector as DV
import Data.Text (pack, unpack)
import Database.Persist.Quasi (PersistSettings(psToDBName), lowerCaseSettings)
-- | A simple stateful abstraction
type Predict = StateT (V.Vector Epoch, V.Vector Double) IO
-- | `simpleLinearRegression xs ys` gives (a, b, r2) for the line
-- y = a * x + b.
simpleLinearRegression :: (Eq n, Fractional n, V.Storable n) => Vector n -> Vector n
-> Maybe (n, n, n)
simpleLinearRegression xs ys
| num_x == 0 || num_y == 0 = Nothing
| otherwise = Just (a, b, r2)
where
a = cov_xy / var_x
b = mean_y - a * mean_x
cov_xy = (V.sum (V.zipWith (*) xs ys) / num_x) - mean_x * mean_y
var_x = V.sum (V.map (\x -> (x - mean_x) ^ (2 :: Int)) xs) / num_x
mean_x = V.sum xs / num_x
mean_y = V.sum ys / num_y
num_x = fromIntegral (V.length xs)
num_y = fromIntegral (V.length ys)
r2 = 1 - ss_res / ss_tot
ss_tot = V.sum $ V.map (\y -> (y - mean_y) ^ (2 :: Int)) ys
ss_res = V.sum $ V.zipWith (\x y -> (y - f x) ^ (2 :: Int)) xs ys
f x = a * x + b
-- |
--
-- @
-- y - y0 = a * (x - x0)
-- ==> y = a * x + (y0 - a * x0) = a * x + b'
-- @
drawFuture :: Double -- ^ a
-> Double -- ^ b
-> Maybe (Epoch, Double) -- ^ draw starting at (time, value)
-> V.Vector Epoch -- ^ clocks
-> V.Vector Double
drawFuture a b mlast = V.map (\x -> a * fromIntegral x + b')
where b' = case mlast of
Just (x0, y0) -> y0 - a * fromIntegral x0
Nothing -> b
-- * Filters
data Filter = Filter
{ aggregate :: FilterAggregate
, interval :: Epoch -- ^ seconds; a day an hour...
, intervalStarts :: Epoch }
data FilterAggregate = Max | Min | Avg
applyFilter :: Filter -> Predict ()
applyFilter Filter{..} = do
(clocks, values) <- get
let ixs = DV.map fst $ splittedAt (intervalStarts `rem` interval) interval (V.convert clocks)
slices vs = DV.zipWith (\i j -> DV.slice i (j - i) vs) ixs (DV.tail ixs)
put . (V.convert *** V.convert)
. DV.unzip . DV.map (apply aggregate) . slices
$ DV.zip (V.convert clocks) (V.convert values)
apply aggregate = case aggregate of
Max -> DV.maximumBy (compare `on` snd)
Min -> DV.minimumBy (compare `on` snd)
Avg -> (vectorMedian *** vectorAvg) . DV.unzip
-- | Fold left; accumulate the current index (and timestamp) when day changes.
splittedAt :: Epoch -> Epoch -> DV.Vector Epoch -> DV.Vector (Int, Epoch)
splittedAt start interval =
DV.ifoldl' go <$> DV.singleton . ((0,) . toInterval) . DV.head <*> DV.init
where
go v m c | (_, t) <- DV.last v, t == toInterval c = v
| otherwise = v `DV.snoc` (m, toInterval c)
toInterval = floor . (/ fromIntegral interval) . fromIntegral . (+ start)
maybeDrop vs =
let l = DV.length vs - 1 in
(if snd (vs DV.! 0) + (interval `div` 2) > snd (vs DV.! 1) then DV.tail else id)
. (if snd (vs DV.! (l - 1)) + (interval `div` 2) > snd (vs DV.! l) then DV.init else id)
$ vs
-- * Utility
vectorAvg :: (Real a, Fractional a) => DV.Vector a -> a
vectorAvg v = fromRational $ toRational (DV.sum v) / toRational (DV.length v)
vectorMedian :: DV.Vector a -> a
vectorMedian v = v DV.! floor (fromIntegral (DV.length v) / 2 :: Double)
aesonOptions = defaultOptions
{ fieldLabelModifier = unpack . psToDBName lowerCaseSettings . pack
, constructorTagModifier = map toLower }
|
Multi-Axis/habbix
|
src/Forecast.hs
|
mit
| 4,506 | 0 | 19 | 1,253 | 1,482 | 803 | 679 | 78 | 3 |
module Main where
factorial :: Integer -> Integer
factorial x
| x > 1 = x * factorial(x -1)
| otherwise = 1
|
mtraina/seven-languages-seven-weeks
|
week-7-haskell/day1/factorial_with_guards.hs
|
mit
| 124 | 0 | 9 | 39 | 54 | 27 | 27 | 5 | 1 |
import System.IO
import System.Environment
import Paths_hackertyper
main = do
args <- getArgs
let n = if null args then 3 else read (args !! 0) :: Int
hSetBuffering stdout NoBuffering
hSetBuffering stdin NoBuffering
hSetEcho stdin False
kernelPath <- getDataFileName "kernel.txt"
kernel <- readFile kernelPath
putStr "\ESC[2J" --clear the screen
typer n $ concat $ repeat kernel
typer n str = do
getChar
putStr $ take n str
typer n $ drop n str
|
fgaz/hackertyper
|
hackertyper.hs
|
mit
| 493 | 0 | 13 | 121 | 167 | 75 | 92 | 17 | 2 |
module Numbering where
import URM
piF m n = 2^m*(2*n+1)-1
xiF m n q = piF (piF (m-1) (n-1)) (q-1)
tauF as = (sum $ map (2^) as)-1
tauF' x = f (x+1) 0 where
f 0 _ = []
f b k | m==0 = r
| m==1 = k:r
where
r = f d (k+1)
(d,m) = b `divMod` 2
betaF (Z n) = 4*(n-1)
betaF (S n) = 4*(n-1)+1
betaF (T m n) = 4*(piF (m-1) (n-1))+2
betaF (J m n q) = 4*(xiF m n q)+3
betaF' x = s r where
s 0 = Z (u+1)
s 1 = S (u+1)
--s 2 = T (pi1F u+1) (pi2F i+1)
--s 3 = J m n q where (m,n,q) = xiF' u
(u,r) = x `divMod` 4
gammaF p = tauF $ map betaF p
|
ducis/URMsim
|
Numbering.hs
|
mit
| 567 | 0 | 11 | 179 | 444 | 231 | 213 | 20 | 2 |
{-# language DeriveDataTypeable, TemplateHaskell #-}
module Baum.Such.Config where
import Autolib.ToDoc
import Autolib.Reader
import Data.Typeable
data Config a = -- use phantom type for baum
Config { start_size :: Int
, min_key :: a
, max_key :: a
, fixed_insert_ops :: Int
, fixed_delete_ops :: Int
, guess_insert_ops :: Int
, guess_delete_ops :: Int
}
deriving ( Typeable )
$(derives [makeReader, makeToDoc] [''Config])
example :: Config Int
example = Config
{ start_size = 10
, min_key = 0
, max_key = 1000
, fixed_insert_ops = 5
, fixed_delete_ops = 0
, guess_insert_ops = 5
, guess_delete_ops = 0
}
|
florianpilz/autotool
|
src/Baum/Such/Config.hs
|
gpl-2.0
| 675 | 6 | 9 | 168 | 169 | 105 | 64 | 24 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Main (main) where
import Test.QuickCheck
import Test.Tasty (defaultMain, testGroup)
import Test.Tasty.QuickCheck (testProperty)
import Test.Tasty.TH
import Test.Tasty.HUnit
import Data.List
import ArithmeticPuzzle
prop_size_is_always_one_less x = (length x > 1) ==> length (split x) == (length x - 1)
prop_joint_response_combinador x = (length x > 1) ==> all (x==) joint_lists
where joint_lists = map (uncurry (++)) (split x)
test_unit = [
testGroup "Test puzzle" [
testCase "one solution" (assertEqual "" (puzzle [1,2,3]) (["(1+2)=3"])),
testCase "two solution" (assertEqual "" (sort $ puzzle [6,4,2]) (sort ["6=(4+2)", "(6-4)=2"])),
testCase "two solutions (tati)" (assertEqual "simple" (sort $ puzzle [2,2,0]) (sort ["(2-2)=0", "2=(2+0)", "2=(2-0)"])),
testCase "four solutions (senra)" (assertEqual "simple" (puzzle [1,2,3,6]) (["(1+(2+3))=6", "(1*(2*3))=6", "1=(2*3)/6", "1/2=3/6"]))
],
testGroup "Test given a list create a tree (tati)" [
testCase "One element" (assertEqual "" (treeGenerator [1]) [Leaf 1]),
testCase "Two elements" (assertEqual "" (treeGenerator [1,2]) [Node Addition (Leaf 1) (Leaf 2)]),
testCase "Three elements" (assertEqual "" (sort $ treeGenerator [1,2,3]) (sort [
Node Addition (Node Addition (Leaf 1) (Leaf 2)) (Leaf 3),
Node Addition (Leaf 1) (Node Addition (Leaf 2) (Leaf 3))
])),
testCase "Four elements" (assertEqual "" (sort $ treeGenerator [1,2,3,4]) (sort [
Node Addition (Node Addition (Leaf 1) (Leaf 2)) (Node Addition (Leaf 3) (Leaf 4)),
Node Addition (Leaf 1) (Node Addition (Leaf 2) (Node Addition (Leaf 3) (Leaf 4))),
Node Addition (Node Addition (Node Addition (Leaf 1) (Leaf 2)) (Leaf 3)) (Leaf 4),
Node Addition (Leaf 1) (Node Addition (Node Addition (Leaf 2) (Leaf 3)) (Leaf 4)),
Node Addition (Node Addition (Leaf 1) (Node Addition (Leaf 2) (Leaf 3))) (Leaf 4)
]))
]
]
main :: IO ()
main = $defaultMainGenerator
|
aflag/haskell-group
|
arithmeticPuzzle/Test.hs
|
gpl-2.0
| 2,170 | 0 | 20 | 538 | 909 | 482 | 427 | 32 | 1 |
module Net.IPv4Link where
-- Routing of IP packets in the simple where there is a single
-- link which has a router.
import Net.Interface as Net
import Net.IPv4
initialize net optRouter link = Interface { rx=rx link, tx=tx }
where
tx = maybe txlocal txr optRouter
txr routerIP ip = Net.tx link $ if sameNet net destIP
then (destIP,ip)
else (routerIP,ip)
where destIP = dest ip
txlocal ip = if sameNet net destIP
then Net.tx link (destIP,ip)
else return () -- no route, dropping packet
where destIP = dest ip
|
nh2/network-house
|
Net/IPv4Link.hs
|
gpl-2.0
| 588 | 8 | 9 | 170 | 175 | 96 | 79 | 13 | 3 |
import System.Environment (getArgs)
data Token = OpenParen | CloseParen deriving (Enum)
type Syntax = (Char, Token)
isToken :: Char -> Token
isToken x =
main = do
args <- getArgs
let filename =
|
MichaelShaulskiy/ct_crypt
|
generate.hs
|
gpl-3.0
| 212 | 1 | 6 | 51 | 70 | 41 | 29 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
{-|
Module : Minitel
Description : Interface to the Minitel
Copyright : (c) Frédéric BISSON, 2014
License : GPL-3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
This module provides to deal with Minitel communications.
-}
module Minitel.Minitel
( Sendable((<<<))
, Minitel(serial, input, output, receiver, sender)
, mConfirmation
, mCall
, readBCount
, readNCount
, getter
, readBMString
, readNMString
, waitFor
, standardSettings
, photoSettings
, spBitRate
, setSpeed
, waitForMinitel
, waitForConnection
, minitel
, killMinitel
)
where
import Minitel.Generate.Configuration (mSpeed, mIdentification)
import Minitel.Type.MNatural (MNat, mnat, fromMNat)
import Minitel.Type.MString
( MString
, MMString
, MCall
, MConfirmation
, completeReturn
)
import Minitel.Type.Queue (Queue, get, put, putM)
import qualified Data.ByteString as B
import System.Hardware.Serialport
( SerialPort(SerialPort)
, SerialPortSettings
( SerialPortSettings
, commSpeed
, bitsPerWord
, stopb
, parity
, flowControl
, timeout
)
, CommSpeed(CommSpeed, CS300, CS1200, CS4800, CS9600)
, StopBits(One)
, Parity(Even, NoParity)
, FlowControl(NoFlowControl)
, openSerial
, send
, recv
)
import Control.Concurrent
( killThread
, threadDelay
, forkIO
, ThreadId
, newEmptyMVar
, putMVar
, takeMVar
)
import Control.Concurrent.STM (atomically, newTQueue)
import Control.Monad (forever, when)
import Control.Applicative ((<$>), (<*>))
import Data.Char (ord)
class Sendable a where
(<<<) :: Minitel -> a -> IO ()
-- | Structure to hold Minitel components
data Minitel = Minitel
{ serial :: SerialPort -- ^ Serial port to which the Minitel is connected
, input :: Queue -- ^ What we receive from the Minitel
, output :: Queue -- ^ What we send to the Minitel
, receiver :: ThreadId -- ^ Receiver thread, allowing full-duplex
, sender :: ThreadId -- ^ Sender thread, allowing full-duplex
}
-- | Operator to send an MString to the Minitel
instance Sendable MString where
(<<<) minitel' = putM (output minitel')
instance Sendable [MString] where
(<<<) minitel' = mapM_ (minitel' <<<)
instance Sendable (Maybe [MString]) where
(<<<) minitel' (Just ms) = mapM_ (minitel' <<<) ms
(<<<) _ Nothing = return ()
instance Sendable (IO MMString) where
(<<<) minitel' = ((<<<) minitel' =<<)
instance Sendable [IO MMString] where
(<<<) minitel' = mapM_ (minitel' <<<)
instance Sendable Char where
(<<<) minitel' c = putM (output minitel') [(mnat . ord) c]
instance Sendable MCall where
(<<<) minitel' (mSend, _) = minitel' <<< mSend
instance Sendable [MCall] where
(<<<) minitel' = mapM_ (mCall minitel')
-- | Sends an MString to the Minitel and waits for its answer. The answer
-- should be the awaited one specified in the MConfirmation. If there is
-- no answer from the Minitel or the answer is not the right one, returns
-- False
mConfirmation :: Minitel -> MConfirmation -> IO Bool
mConfirmation minitel' (mSend, mReceive) = do
minitel' <<< mSend
answer <- readNMString (getter minitel') completeReturn
return (answer == mReceive)
-- | Sends an MString to the Minitel and waits for its answer. It returns
-- an MString of max length as specified in the MCall.
mCall :: Minitel -> MCall -> IO MString
mCall minitel' (mSend, count) = do
minitel' <<< mSend
readNCount (getter minitel') (fromMNat count)
-- | Waits for an MString of @count@ elements coming from the Minitel. If it
-- takes too long, returns what has already been collected.
-- This is the blocking version.
readBCount :: (Eq a) => IO a -> Int -> IO [a]
readBCount getter' count = readBMString getter' (\sequ -> length sequ == count)
-- | Waits for an MString of @count@ elements coming from the Minitel. If it
-- takes too long, returns what has already been collected.
-- This is the non-blocking version
readNCount :: (Eq a) => IO a -> Int -> IO [a]
readNCount getter' count = readNMString getter' (\sequ -> length sequ == count)
-- | Returns the getter for a Minitel
getter :: Minitel -> IO MNat
getter = get . input
-- | Waits for a complete MString coming from the Minitel. If it takes too
-- long, returns what has already been collected. To determine if the MString
-- is complete, it needs an @isComplete@ function which tells if an MString
-- is complete (True) or not (False).
-- This is the blocking version.
readBMString :: (Eq a) => IO a -> ([a] -> Bool) -> IO [a]
readBMString getter' isComplete = readBMString' []
where readBMString' s
| isComplete s = return s
| null s = getter' >>= \value -> readBMString' [value]
| otherwise = do
result <- waitFor 3000000 getter'
case result of
Just value -> readBMString' $ s ++ [value]
Nothing -> return s
-- | Waits for a complete MString coming from the Minitel. If it takes too
-- long, returns what has already been collected. To determine if the MString
-- is complete, it needs an @isComplete@ function which tells if an MString
-- is complete (True) or not (False).
-- This is the non-blocking version
readNMString :: (Eq a) => IO a -> ([a] -> Bool) -> IO [a]
readNMString getter' isComplete = readNMString' []
where readNMString' s
| isComplete s = return s
| otherwise = do
result <- waitFor 1000000 getter'
case result of
Just value -> readNMString' $ s ++ [value]
Nothing -> return s
-- | Waits for either a read to succeed or a delay to end. It does this by
-- running two threads. The first one to press the buzzer will stop the
-- function and returns the result (either Just a or Nothing)
waitFor :: (Eq a) => Int -> IO a -> IO (Maybe a)
waitFor delay getter' = do
done <- newEmptyMVar
-- Run a race between the reader and the waiter
reader <- forkIO $ getter' >>= putMVar done . Just
waiter <- forkIO $ threadDelay delay >> putMVar done Nothing
-- Wait for the first to win
result <- takeMVar done
killThread reader
killThread waiter
return result
-- | Standard settings for the serial port on which is connected a Minitel.
-- Standard configuration is 1200 bps, 7 bits, 1 stop, even parity.
standardSettings :: SerialPortSettings
standardSettings = SerialPortSettings
{ commSpeed = CS1200
, bitsPerWord = 7
, stopb = One
, parity = Even
, flowControl = NoFlowControl
, timeout = 10
}
-- | Settings for the serial port on which is connected a Minitel when in
-- photographic mode.
-- Configuration is 9600 bps, 8 bits, 1 stop, no parity.
photoSettings :: SerialPortSettings
photoSettings = SerialPortSettings
{ commSpeed = CS9600
, bitsPerWord = 8
, stopb = One
, parity = NoParity
, flowControl = NoFlowControl
, timeout = 10
}
-- | Translates bit rate to SerialPort types
spBitRate :: Int -> CommSpeed
spBitRate 300 = CS300
spBitRate 1200 = CS1200
spBitRate 4800 = CS4800
spBitRate 9600 = CS9600
spBitRate _ = error "Unsupported bit rate"
-- | Change Minitel speed
setSpeed :: Minitel -> Int -> IO Minitel
setSpeed m rate = do
waitForMinitel m
m <<< mSpeed rate
threadDelay 500000
killMinitel m
let settings = standardSettings { commSpeed = spBitRate rate }
minitel "" settings
-- | waitForMinitel waits till the Minitel has displayed everything
waitForMinitel :: Minitel -> IO ()
waitForMinitel minitel' = do
let (mSend, count) = mIdentification
minitel' <<< mSend
x <- readBCount (getter minitel') (fromMNat count)
print x
return ()
waitForConnection :: Minitel -> IO (Maybe MString)
waitForConnection minitel' = do
firstByte <- waitFor 20000000 (getter minitel')
followingBytes <- readNCount (getter minitel') 100
return ((:) <$> firstByte <*> Just followingBytes)
-- | Opens a full-duplex connection to a Minitel. The default serial is set
-- to \/dev\/ttyUSB0.
minitel :: String -> SerialPortSettings -> IO Minitel
minitel "" settings = minitel "/dev/ttyUSB0" settings
minitel dev settings = do
port <- openSerial dev settings
sendQueue <- atomically newTQueue
recvQueue <- atomically newTQueue
sendThread <- forkIO $ sendLoop port sendQueue
recvThread <- forkIO $ recvLoop port recvQueue
return Minitel
{ serial = port
, input = recvQueue
, output = sendQueue
, receiver = recvThread
, sender = sendThread
}
where sendLoop s q = forever $ get q >>= send s . B.singleton . fromIntegral
recvLoop s q = forever $ do
b <- recv s 1
when (1 <= B.length b) $ (put q . fromIntegral . B.head) b
-- | Kills a minitel, stopping its threads
killMinitel :: Minitel -> IO ()
killMinitel minitel' = do
killThread $ sender minitel'
killThread $ receiver minitel'
|
Zigazou/HaMinitel
|
src/Minitel/Minitel.hs
|
gpl-3.0
| 9,769 | 0 | 15 | 2,841 | 2,103 | 1,141 | 962 | 196 | 2 |
{-# LANGUAGE RecordWildCards #-}
module World where
import Debug.Trace
import Data.Monoid
import Data.Maybe
import Control.Arrow
import Control.Applicative
import Linear.V2
import Game.Folivora.TileGrid
import Game.Folivora.Sound
-- enemy: delay to fire next bullet
data PlatformerTile = Empty | Floor | Player | Enemy Int | Bullet
instance Monoid PlatformerTile where
mempty = Empty
mappend = error "do you really want to use monoid here?.."
-- mappend a _ = a
type PlatformerMap = DefaultTileGrid PlatformerTile
data PlatformerWorld = PlatformerWorld
{ tileMap :: PlatformerMap
, player :: V2 Int
, enemy :: V2 Int
, bullet :: V2 Int
, worldSound :: String
}
data UserControl = UserControl
{ walkTo :: V2 Int
}
worldStep :: PlatformerWorld -> UserControl -> PlatformerWorld
worldStep world (UserControl {..}) =
fixMap world $ world
{ player = player world + walkTo
, enemy = enemy world
, bullet = bullet world + V2 (-1) 0
, worldSound = "sounds.wav"
}
where
fixMap w w' = w' { tileMap =
eraseTile (player w)
>>> eraseTile (enemy w)
>>> eraseTile (bullet w)
>>> setCell (player w') Player
>>> setCell (enemy w') (Enemy 3)
>>> setCell (bullet w') Bullet
$ (tileMap w)
}
eraseTile x = setCell x Empty
newWorld :: PlatformerWorld
newWorld =
PlatformerWorld
{ tileMap = tileGrid fill (V2 40 10)
, player = V2 3 7
, enemy = V2 20 7
, bullet = V2 19 7
}
where
fill (V2 x y) | y > 7 = Floor
| y == 7 && x == 3 = Player
| y == 7 && x == 20 = Enemy 3
| y == 7 && x == 19 = Bullet
| otherwise = Empty
|
caryoscelus/folivora-ge
|
demos/platformer/World.hs
|
gpl-3.0
| 1,971 | 0 | 17 | 755 | 554 | 293 | 261 | 51 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.