code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Data/Attoparsec/ByteString/FastSet.hs" #-}
{-# LANGUAGE BangPatterns, MagicHash #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Attoparsec.ByteString.FastSet
-- Copyright : Bryan O'Sullivan 2007-2015
-- License : BSD3
--
-- Maintainer : bos@serpentine.com
-- Stability : experimental
-- Portability : unknown
--
-- Fast set membership tests for 'Word8' and 8-bit 'Char' values. The
-- set representation is unboxed for efficiency. For small sets, we
-- test for membership using a binary search. For larger sets, we use
-- a lookup table.
--
-----------------------------------------------------------------------------
module Data.Attoparsec.ByteString.FastSet
(
-- * Data type
FastSet
-- * Construction
, fromList
, set
-- * Lookup
, memberChar
, memberWord8
-- * Debugging
, fromSet
-- * Handy interface
, charClass
) where
import Data.Bits ((.&.), (.|.))
import Foreign.Storable (peekByteOff, pokeByteOff)
import GHC.Base (Int(I#), iShiftRA#, narrow8Word#, shiftL#)
import GHC.Word (Word8(W8#))
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Internal as I
import qualified Data.ByteString.Unsafe as U
data FastSet = Sorted { fromSet :: !B.ByteString }
| Table { fromSet :: !B.ByteString }
deriving (Eq, Ord)
instance Show FastSet where
show (Sorted s) = "FastSet Sorted " ++ show (B8.unpack s)
show (Table _) = "FastSet Table"
-- | The lower bound on the size of a lookup table. We choose this to
-- balance table density against performance.
tableCutoff :: Int
tableCutoff = 8
-- | Create a set.
set :: B.ByteString -> FastSet
set s | B.length s < tableCutoff = Sorted . B.sort $ s
| otherwise = Table . mkTable $ s
fromList :: [Word8] -> FastSet
fromList = set . B.pack
data I = I {-# UNPACK #-} !Int {-# UNPACK #-} !Word8
shiftR :: Int -> Int -> Int
shiftR (I# x#) (I# i#) = I# (x# `iShiftRA#` i#)
shiftL :: Word8 -> Int -> Word8
shiftL (W8# x#) (I# i#) = W8# (narrow8Word# (x# `shiftL#` i#))
index :: Int -> I
index i = I (i `shiftR` 3) (1 `shiftL` (i .&. 7))
{-# INLINE index #-}
-- | Check the set for membership.
memberWord8 :: Word8 -> FastSet -> Bool
memberWord8 w (Table t) =
let I byte bit = index (fromIntegral w)
in U.unsafeIndex t byte .&. bit /= 0
memberWord8 w (Sorted s) = search 0 (B.length s - 1)
where search lo hi
| hi < lo = False
| otherwise =
let mid = (lo + hi) `quot` 2
in case compare w (U.unsafeIndex s mid) of
GT -> search (mid + 1) hi
LT -> search lo (mid - 1)
_ -> True
-- | Check the set for membership. Only works with 8-bit characters:
-- characters above code point 255 will give wrong answers.
memberChar :: Char -> FastSet -> Bool
memberChar c = memberWord8 (I.c2w c)
{-# INLINE memberChar #-}
mkTable :: B.ByteString -> B.ByteString
mkTable s = I.unsafeCreate 32 $ \t -> do
_ <- I.memset t 0 32
U.unsafeUseAsCStringLen s $ \(p, l) ->
let loop n | n == l = return ()
| otherwise = do
c <- peekByteOff p n :: IO Word8
let I byte bit = index (fromIntegral c)
prev <- peekByteOff t byte :: IO Word8
pokeByteOff t byte (prev .|. bit)
loop (n + 1)
in loop 0
charClass :: String -> FastSet
charClass = set . B8.pack . go
where go (a:'-':b:xs) = [a..b] ++ go xs
go (x:xs) = x : go xs
go _ = ""
|
phischu/fragnix
|
tests/packages/scotty/Data.Attoparsec.ByteString.FastSet.hs
|
bsd-3-clause
| 3,785
| 0
| 23
| 1,068
| 1,062
| 572
| 490
| 78
| 3
|
-- I think building ASTs like this could lead to advantages:
-- * performance improvements
-- - the StatefulReactT monad is really a function from state to AST and
-- a new state. to get the AST you need to evaluate the function. react
-- also has planned support for defining the virtual dom in this way
-- rather than by function calls, the idea being that things like
-- react-haskell could interface in that way.
-- * introspection, i guess
-- - you can inspect a piece of DOM being passed around without
-- evaluating the function
--
-- ReactNode already exists, but it's not convenient.
main = do
Just elem <- elemById "inject"
render elem $
Div [("className", Str "foo")] [
[ Text [] "some string"
, Div [("className", Str "bar")] []
, Pre [] [ Text [] "this thing should be in a pre" ]
, Text [] "some other string"
]
]
|
joelburget/react-haskell
|
sketches/immutable.hs
|
mit
| 937
| 0
| 14
| 265
| 123
| 67
| 56
| 8
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module CreateLabels where
import Data.List (intercalate)
import qualified Github.Auth as Github
import qualified Github.Issues.Labels as Github
main = do
let auth = Github.GithubBasicAuth "user" "password"
possibleLabel <- Github.createLabel auth "thoughtbot" "papperclip" "sample label" "ff00ff"
case possibleLabel of
(Left error) -> putStrLn $ "Error: " ++ show error
(Right label) -> putStrLn . formatLabel $ label
formatLabel label = Github.labelName label ++
", colored " ++
Github.labelColor label
|
bitemyapp/github
|
samples/Issues/Labels/CreateLabels.hs
|
bsd-3-clause
| 631
| 0
| 11
| 163
| 149
| 78
| 71
| 14
| 2
|
module Lambda1 where
f = \x -> \y -> x + y + 1
g = f (fib 27) (fib 30)
fib 1 = 1
fib 0 = 1
fib n = fib (n-1) + fib (n-2)
|
RefactoringTools/HaRe
|
old/testing/evalMonad/Lambda1_TokOut.hs
|
bsd-3-clause
| 126
| 0
| 8
| 42
| 97
| 51
| 46
| 6
| 1
|
module F1 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/F1_TokOut.hs
|
bsd-3-clause
| 1,008
| 0
| 15
| 414
| 348
| 172
| 176
| 21
| 3
|
{-# LANGUAGE ImplicitParams, TypeSynonymInstances, FlexibleInstances #-}
-- Similar to tc024, but cross module
module TcRun025_B where
import Data.List( sort )
-- This class has no tyvars in its class op context
-- One uses a newtype, the other a data type
class C1 a where
fc1 :: (?p :: String) => a;
class C2 a where
fc2 :: (?p :: String) => a;
opc :: a
instance C1 String where
fc1 = ?p;
instance C2 String where
fc2 = ?p;
opc = "x"
-- This class constrains no new type variables in
-- its class op context
class D1 a where
fd1 :: (Ord a) => [a] -> [a]
class D2 a where
fd2 :: (Ord a) => [a] -> [a]
opd :: a
instance D1 (Maybe a) where
fd1 xs = sort xs
instance D2 (Maybe a) where
fd2 xs = sort xs
opd = Nothing
|
ryantm/ghc
|
testsuite/tests/typecheck/should_run/TcRun025_B.hs
|
bsd-3-clause
| 799
| 4
| 9
| 231
| 236
| 133
| 103
| 23
| 0
|
import OneShot1
import System.Environment
import Debug.Trace
p n = trace "p evaluated" (n > 0)
{-# NOINLINE p #-}
summap :: (Int -> Int) -> (Int -> Int)
summap f n = sum $ map f [1..10]
{-# NOINLINE summap #-}
foo' n = if p n then foo n else foo (n+1)
{-# NOINLINE foo' #-}
bar' n = if p n then bar n else bar (n+1)
{-# NOINLINE bar' #-}
baz' n = if p n then baz n else baz (n+1)
{-# NOINLINE baz' #-}
main = do
n <- length `fmap` getArgs
print $ summap (foo' n) n + summap (bar' n) n + summap (baz' n) n
|
sgillespie/ghc
|
testsuite/tests/simplCore/prog003/OneShot2.hs
|
bsd-3-clause
| 516
| 1
| 12
| 124
| 251
| 128
| 123
| 17
| 2
|
module B (T,t) where
import A
|
urbanslug/ghc
|
testsuite/tests/driver/recomp008/B.hs
|
bsd-3-clause
| 32
| 0
| 4
| 8
| 15
| 10
| 5
| 2
| 0
|
module ShouldCompile where
x = const 1.0e+x where e = 3
|
sdiehl/ghc
|
testsuite/tests/parser/should_compile/read033.hs
|
bsd-3-clause
| 57
| 0
| 6
| 12
| 25
| 14
| 11
| -1
| -1
|
module PropImports
( module PropImports) where
import BasicPrelude as PropImports
import Test.Hspec as PropImports (Spec, hspec, describe)
import Test.Hspec.QuickCheck as PropImports (modifyMaxSuccess, prop)
import Test.QuickCheck as PropImports (forAll,elements,choose)
import Generator as PropImports
import Tabulator as PropImports
import Output as PropImports
import Types as PropImports
|
mlitchard/primenator
|
src-test/PropImports.hs
|
isc
| 478
| 0
| 5
| 130
| 87
| 62
| 25
| 10
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module Handler.Dispatch where
import Import
import Handler.Types (Composer, compoFromCompi)
import Handler.Markdown (markdownComposer)
import Handler.Publications (publicationsComposer)
import Handler.Resume (resumeComposer)
import qualified Data.Text as T (null, append)
import qualified Data.Text.Encoding as E (decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import qualified Data.ByteString as B (readFile)
import Data.Maybe (fromJust)
import Data.Aeson.TH
import Data.Yaml
import System.FilePath ((</>))
import Data.Text (unpack)
import Data.Time.Calendar (Day)
import Data.Time.Format (readTime, formatTime)
import System.Locale (defaultTimeLocale)
data Article = Article { file :: FilePath
, composer :: Text
} deriving Show
data Page = Page { title :: Text
, articles :: [Article]
} deriving Show
data Footer = Footer { copyright :: Text
, last_updated :: Text
} deriving Show
data TOC = TOC { home :: Page
, resume :: Page
, publications :: Page
, code :: Page
, contact :: Page
, footer :: Footer
} deriving Show
$(deriveJSON defaultOptions ''Article)
$(deriveJSON defaultOptions ''Page)
$(deriveJSON defaultOptions ''Footer)
$(deriveJSON defaultOptions ''TOC)
renderArticle :: FilePath -> Article -> IO Widget
renderArticle dir (Article fp comp) = do
contentRaw <- B.readFile $ dir </> fp
return $ getComposer comp $ E.decodeUtf8With lenientDecode $ contentRaw
pageHandler :: Page -> Footer -> Handler Html
pageHandler (Page titl arts) (Footer copy upd) = do
ext <- getExtra
defaultLayout $ do
setTitle $ toHtml $ T.append "Nicolas Dudebout" $ if T.null titl then titl
else T.append " - " titl
articleWidgets <- liftIO $ mapM (renderArticle (contentDir ext)) arts
let day = readTime defaultTimeLocale "%m/%d/%Y" (unpack upd) :: Day
updateString = formatTime defaultTimeLocale "%B %e, %Y" day
updateDatetime = formatTime defaultTimeLocale "%Y-%m-%d" day
footerWidget <- return $(widgetFile "footer")
sequence_ $ articleWidgets ++ [footerWidget]
tocEntryHandler :: (TOC -> Page) -> Handler Html
tocEntryHandler pageSelect = do
ext <- getExtra
toc <- liftIO $ readTOC $ contentDir ext </> "toc.yaml"
pageHandler (pageSelect toc) (footer toc)
readTOC :: FilePath -> IO TOC
readTOC toc = do
contentRaw <- B.readFile toc
return $ fromJust $ decode contentRaw
getComposer :: Text -> Composer
getComposer name = case name of
"markdown" -> markdownComposer
"resume" -> resumeComposer
"publications" -> publicationsComposer
_ -> htmlComposer
htmlComposer :: Composer
htmlComposer = compoFromCompi toHtml
getHomeR :: Handler Html
getHomeR = tocEntryHandler home
getResumeR :: Handler Html
getResumeR = tocEntryHandler resume
getPublicationsR :: Handler Html
getPublicationsR = tocEntryHandler publications
getCodeR :: Handler Html
getCodeR = tocEntryHandler code
getContactR :: Handler Html
getContactR = tocEntryHandler contact
|
dudebout/dudeboutdotcom
|
Handler/Dispatch.hs
|
isc
| 3,365
| 0
| 16
| 876
| 903
| 481
| 422
| -1
| -1
|
main = putStrLn $ show solve
-- This is just the lowest common multiple. Note that this is also very easy to
-- work out by hand for numbers up to 20 (the answer is 2^4*3^2*5*7*11*13*17*19).
solve :: Int
solve = foldr lcm 2 [3..20]
|
pshendry/project-euler-solutions
|
0005/solution.hs
|
mit
| 233
| 0
| 6
| 46
| 37
| 20
| 17
| 3
| 1
|
sieve :: [Integer]->[Integer]
sieve []=[]
sieve (x:xs) = x:sieve [y | y<-xs, y `mod` x >0]
main=print(sieve [2..])
|
manuchandel/Academics
|
Principles-Of-Programming-Languages/sieveOfEratosthenes.hs
|
mit
| 117
| 1
| 10
| 20
| 96
| 49
| 47
| 4
| 1
|
module Problem35 where
{--
Task description:
The number, 197, is called a circular prime because all rotations of the digits:
197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
--}
import Control.Monad
import Data.List
import Data.Set (Set)
import qualified Data.Set as Set
type N = Integer
primes :: [N]
primes = 2 : 3 : sieve [] (tail primes) 3
where
notDivsBy d n = n `rem` d /= 0
sieve ds (p:ps) x = foldr (filter . notDivsBy) [x+2, x+4..p*p-2] ds
`mappend` sieve (p:ds) ps (p*p)
root :: N -> N
root = round . sqrt . fromIntegral
isPrime :: N -> Bool
isPrime x
| x <= 1 = False
| otherwise = notElem 0 . fmap (mod x) $ takeWhile (<= root x) primes
magic :: N
magic = 1000000
candidates :: [N]
candidates = takeWhile (<= magic) primes
rotations :: N -> [N]
rotations n = let s = show n
zs = zipWith (++) (tails s) (inits s)
in fmap read . init . tail $ zs
circularPrimes :: [[N]]
circularPrimes = do
p <- candidates
let rs = rotations p
guard . all isPrime $ rotations p
return $ p:rs
cPrimeSet = Set.fromList $ concat circularPrimes
solution = Set.size cPrimeSet
main = print solution
|
runjak/projectEuler
|
src/Problem35.hs
|
mit
| 1,324
| 0
| 11
| 335
| 473
| 249
| 224
| 34
| 1
|
-- file: ch20/RunProcess.hs
{-# OPTIONS_GHC -XDatatypeContexts #-}
{-# OPTIONS_GHC -XTypeSynonymInstances #-}
{-# OPTIONS_GHC -XFlexibleInstances #-}
module RunProcess where
import System.Process
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Exception
import System.Posix.Directory
import System.Directory(setCurrentDirectory)
import System.IO
import System.Exit
import Text.Regex
import System.Posix.Process
import System.Posix.IO
import System.Posix.Types
import Data.List
import System.Posix.Env(getEnv)
{- | The type for running external commands. The first part
of the tuple is the program name. The list represents the
command-line parameters to pass to the command. -}
type SysCommand = (String, [String])
{- | The result of running any command -}
data CommandResult = CommandResult {
cmdOutput :: IO String, -- ^ IO action that yields the output
getExitStatus :: IO ProcessStatus -- ^ IO action that yields exit result
}
{- | The type for handling global lists of FDs to always close in the clients
-}
type CloseFDs = MVar [Fd]
{- | Class representing anything that is a runnable command -}
class CommandLike a where
{- | Given the command and a String representing input,
invokes the command. Returns a String
representing the output of the command. -}
invoke :: a -> CloseFDs -> String -> IO CommandResult
-- Support for running system commands
instance CommandLike SysCommand where
invoke (cmd, args) closefds input =
do -- Create two pipes: one to handle stdin and the other
-- to handle stdout. We do not redirect stderr in this program.
(stdinread, stdinwrite) <- createPipe
(stdoutread, stdoutwrite) <- createPipe
-- We add the parent FDs to this list because we always need
-- to close them in the clients.
addCloseFDs closefds [stdinwrite, stdoutread]
-- Now, grab the closed FDs list and fork the child.
childPID <- withMVar closefds (\fds ->
forkProcess (child fds stdinread stdoutwrite))
-- Now, on the parent, close the client-side FDs.
closeFd stdinread
closeFd stdoutwrite
-- Write the input to the command.
stdinhdl <- fdToHandle stdinwrite
forkIO $ do hPutStr stdinhdl input
hClose stdinhdl
-- Prepare to receive output from the command
stdouthdl <- fdToHandle stdoutread
-- Set up the function to call when ready to wait for the
-- child to exit.
let waitfunc =
do status <- getProcessStatus True False childPID
case status of
Nothing -> fail $ "Error: Nothing from getProcessStatus"
Just ps -> do removeCloseFDs closefds
[stdinwrite, stdoutread]
return ps
return $ CommandResult {cmdOutput = hGetContents stdouthdl,
getExitStatus = waitfunc}
-- Define what happens in the child process
where child closefds stdinread stdoutwrite =
do -- Copy our pipes over the regular stdin/stdout FDs
dupTo stdinread stdInput
dupTo stdoutwrite stdOutput
-- Now close the original pipe FDs
closeFd stdinread
closeFd stdoutwrite
-- Close all the open FDs we inherited from the parent
mapM_ (\fd -> catch (closeFd fd) (\(SomeException e) -> return ())) closefds
-- Start the program
executeFile cmd True args Nothing
{- | An instance of 'CommandLike' for an external command. The String is
passed to a shell for evaluation and invocation. -}
instance CommandLike String where
invoke cmd closefds input =
do -- Use the shell given by the environment variable SHELL,
-- if any. Otherwise, use /bin/sh
esh <- getEnv "SHELL"
let sh = case esh of
Nothing -> "/bin/sh"
Just x -> x
invoke (sh, ["-c", cmd]) closefds input
-- Add FDs to the list of FDs that must be closed post-fork in a child
addCloseFDs :: CloseFDs -> [Fd] -> IO ()
addCloseFDs closefds newfds =
modifyMVar_ closefds (\oldfds -> return $ oldfds ++ newfds)
-- Remove FDs from the list
removeCloseFDs :: CloseFDs -> [Fd] -> IO ()
removeCloseFDs closefds removethem =
modifyMVar_ closefds (\fdlist -> return $ procfdlist fdlist removethem)
where
procfdlist fdlist [] = fdlist
procfdlist fdlist (x:xs) = procfdlist (removefd fdlist x) xs
-- We want to remove only the first occurance ot any given fd
removefd [] _ = []
removefd (x:xs) fd
| fd == x = xs
| otherwise = x : removefd xs fd
-- Support for running Haskell commands
instance CommandLike (String -> IO String) where
invoke func _ input =
return $ CommandResult (func input) (return (Exited ExitSuccess))
-- Support pure Haskell functions by wrapping them in IO
instance CommandLike (String -> String) where
invoke func = invoke iofunc
where iofunc :: String -> IO String
iofunc = return . func
-- It's also useful to operate on lines. Define support for line-based
-- functions both within and without the IO monad.
instance CommandLike ([String] -> IO [String]) where
invoke func _ input =
return $ CommandResult linedfunc (return (Exited ExitSuccess))
where linedfunc = func (lines input) >>= (return . unlines)
instance CommandLike ([String] -> [String]) where
invoke func = invoke (unlines . func . lines)
{- | Type representing a pipe. A 'PipeCommand' consists of a source
and destination part, both of which must be instances of
'CommandLike'. -}
data (CommandLike src, CommandLike dest) =>
PipeCommand src dest = PipeCommand src dest
{- | A convenient function for creating a 'PipeCommand'. -}
(-|-) :: (CommandLike a, CommandLike b) => a -> b -> PipeCommand a b
(-|-) = PipeCommand
{- | Make 'PipeCommand' runnable as a command -}
instance (CommandLike a, CommandLike b) =>
CommandLike (PipeCommand a b) where
invoke (PipeCommand src dest) closefds input =
do res1 <- invoke src closefds input
output1 <- cmdOutput res1
res2 <- invoke dest closefds output1
return $ CommandResult (cmdOutput res2) (getEC res1 res2)
{- | Given two 'CommandResult' items, evaluate the exit codes for
both and then return a "combined" exit code. This will be ExitSuccess
if both exited successfully. Otherwise, it will reflect the first
error encountered. -}
getEC :: CommandResult -> CommandResult -> IO ProcessStatus
getEC src dest =
do sec <- getExitStatus src
dec <- getExitStatus dest
case sec of
Exited ExitSuccess -> return dec
x -> return x
{- | Different ways to get data from 'run'.
* IO () runs, throws an exception on error, and sends stdout to stdout
* IO String runs, throws an exception on error, reads stdout into
a buffer, and returns it as a string.
* IO [String] is same as IO String, but returns the results as lines
* IO ProcessStatus runs and returns a ProcessStatus with the exit
information. stdout is sent to stdout. Exceptions are not thrown.
* IO (String, ProcessStatus) is like IO ProcessStatus, but also
includes a description of the last command in the pipe to have
an error (or the last command, if there was no error)
* IO Int returns the exit code from a program directly. If a signal
caused the command to be reaped, returns 128 + SIGNUM.
* IO Bool returns True if the program exited normally (exit code 0,
not stopped by a signal) and False otherwise.
-}
class RunResult a where
{- | Runs a command (or pipe of commands), with results presented
in any number of different ways. -}
run :: (CommandLike b) => b -> a
-- | Utility function for use by 'RunResult' instances
setUpCommand :: CommandLike a => a -> IO CommandResult
setUpCommand cmd =
do -- Initialize our closefds list
closefds <- newMVar []
-- Invoke the command
invoke cmd closefds []
instance RunResult (IO ()) where
run cmd = run cmd >>= checkResult
instance RunResult (IO ProcessStatus) where
run cmd =
do res <- setUpCommand cmd
-- Process its output
output <- cmdOutput res
putStr output
getExitStatus res
instance RunResult (IO Int) where
run cmd = do rc <- run cmd
case rc of
Exited (ExitSuccess) -> return 0
Exited (ExitFailure x) -> return x
(Terminated x _) -> return (128 + (fromIntegral x))
Stopped x -> return (128 + (fromIntegral x))
instance RunResult (IO Bool) where
run cmd = do rc <- run cmd
return ((rc::Int) == 0)
instance RunResult (IO [String]) where
run cmd = do r <- run cmd
return (lines r)
instance RunResult (IO String) where
run cmd =
do res <- setUpCommand cmd
output <- cmdOutput res
-- Force output to be buffered
evaluate (length output)
ec <- getExitStatus res
checkResult ec
return output
checkResult :: ProcessStatus -> IO ()
checkResult ps =
case ps of
Exited (ExitSuccess) -> return ()
x -> fail (show x)
{- | A convenience function. Refers only to the version of 'run'
that returns @IO ()@. This prevents you from having to cast to it
all the time when you do not care about the result of 'run'.
-}
runIO :: CommandLike a => a -> IO ()
runIO = run
------------------------------------------------------------
-- Utility Functions
------------------------------------------------------------
cd :: FilePath -> IO ()
cd = setCurrentDirectory
{- | Takes a string and sends it on as standard output.
The input to this function is never read. -}
echo :: String -> String -> String
echo inp _ = inp
-- | Search for the regexp in the lines. Return those that match.
grep :: String -> [String] -> [String]
grep pat = filter (ismatch regex)
where regex = mkRegex pat
ismatch r inp = case matchRegex r inp of
Nothing -> False
Just _ -> True
{- | Creates the given directory. A value of 0o755 for mode would be typical.
An alias for System.Posix.Directory.createDirectory. -}
mkdir :: FilePath -> FileMode -> IO ()
mkdir = createDirectory
{- | Remove duplicate lines from a file (like Unix uniq).
Takes a String representing a file or output and plugs it through
lines and then nub to uniqify on a line basis. -}
uniq :: String -> String
uniq = unlines . nub . lines
-- | Count number of lines. wc -l
wcL, wcW :: [String] -> [String]
wcL inp = [show (genericLength inp :: Integer)]
-- | Count number of words in a file (like wc -w)
wcW inp = [show ((genericLength $ words $ unlines inp) :: Integer)]
sortLines :: [String] -> [String]
sortLines = sort
-- | Count the lines in the input
countLines :: String -> IO String
countLines = return . (++) "\n" . show . length . lines
|
Airtnp/Freshman_Simple_Haskell_Lib
|
Utils/shell.hs
|
mit
| 11,399
| 0
| 19
| 3,214
| 2,204
| 1,125
| 1,079
| 171
| 3
|
{-# LANGUAGE BangPatterns, DeriveGeneric, RecordWildCards, FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Core.State(
GameState(..)
, stepGame
, initialGameState
) where
import Core.Context
import Core.Monad
import Prelude hiding (id, (.))
import FRP.Netwire
import Control.Wire.Core (stepWire)
import GHC.Generics (Generic)
import Control.DeepSeq
import Control.Monad.State.Strict
import Control.Monad.STM
import Control.Concurrent
import Control.Concurrent.STM.TQueue
import Network.Protocol.Message
import Data.HashMap.Strict as HM
import Control.Monad as Monad
import qualified Data.Traversable as T
import qualified Data.Sequence as S
import Util.Concurrent
import qualified Data.Text.IO as T
import Data.Text (Text)
-- | The main state of game
data GameState = GameState {
-- | Holds info about simulation time and delta time
gameSession :: !GameSession
-- | Current simulation wire (arrow)
, gameMainWire :: !(GameWire () ())
-- | Current game context (events, inner messages, everthing that could be used in GameMonad)
, gameContext :: !GameContext
} deriving (Generic)
instance NFData GameSession where
rnf = (`seq` ())
instance NFData (GameWire () ()) where
rnf = (`seq` ())
instance NFData GameState
-- | Simulate one step (frame) of game simulation
stepGame :: TQueue (Text, NetworkMessage) -- ^ Channel with received network messages from server core
-> TQueue Text -- ^ Channel with names of connected players
-> TQueue Text -- ^ Channel with names of disconnected players
-> GameState -- ^ Previous game state
-> IO GameState -- ^ Next game state
stepGame messageBus connChan disconnChan (!GameState{..}) = do
-- Send quequed messages
_ <- mapM sendMessage $ reverse $ eventMngMessages2Send $ gameCustomContext gameContext
-- Read new events and empty queue of out messages
emng' <- EventManager <$> readMessagesMap <*> readConnects <*> readDisconnects <*> pure []
let gameContext' = gameContext { gameCustomContext = emng' }
-- Simulate one step
(s, session') <- stepSession gameSession
let ((_, wire'), context') = runState (stepWire gameMainWire s (Right ())) gameContext'
-- Put all messages from log
_ <- T.mapM T.putStrLn . S.reverse $ gameLogMessages context'
-- Calculate new state of game
return $! GameState session' wire' context' { gameLogMessages = S.empty }
where
sendMessage :: (Text, NetworkMessage) -> IO ()
sendMessage !msg = do
putStrLn $ unwords ["Message sent:", show msg]
atomically $ writeTQueue messageBus msg
yield -- let core server thread to awake
readMessages :: IO [(Text, NetworkMessage)]
readMessages = readTQueueWhileCould' messageBus
readMessagesMap :: IO (HashMap Text [NetworkMessage])
readMessagesMap = do
msgs <- readMessages
Monad.unless (Prelude.null msgs) $ print msgs -- DEBUG
return $! Prelude.foldr go HM.empty msgs
where
go (name, msg) acc = HM.insertWith (\_ msgs -> msg : msgs) name [msg] acc
readConnects :: IO [Text]
readConnects = readTQueueWhileCould' connChan
readDisconnects :: IO [Text]
readDisconnects = readTQueueWhileCould' disconnChan
-- | Runs initialization that calclulates first game state
initialGameState :: GameMonad (GameWire () ()) -> GameState
initialGameState w =
let (mainWire, gContext) = runState w newGameContext
in GameState clockSession_ mainWire gContext
|
NCrashed/sinister
|
src/server/Core/State.hs
|
mit
| 3,458
| 0
| 15
| 648
| 845
| 464
| 381
| 75
| 1
|
module Dice where
import System.Random (randomRIO)
data Score = Score { stack :: Int, score :: Int }
main :: IO ()
main = loop (Score 0 0) (Score 0 0)
loop :: Score -> Score -> IO ()
loop p1 p2 = do
putStrLn $ "\nPlayer 1 ~ " ++ show (score p1)
p1' <- askPlayer p1
putStrLn $ "\nPlayer 2 ~ " ++ show (score p2)
p2' <- askPlayer p2
case (p1', p2') of
(Score _ s1, _ ) | s1 >= 100 -> putStrLn "P1 won!"
(_ , Score _ s2) | s2 >= 100 -> putStrLn "P2 won!"
_ -> loop p1' p2'
askPlayer :: Score -> IO Score
askPlayer (Score stack score) = do
putStr "\n(h)old or (r)oll?"
answer <- getChar
roll <- randomRIO (1,6)
case (answer, roll) of
('h', _) -> do
putStrLn $ " Score = " ++ show (stack + score)
return $ Score 0 (stack + score)
('r', 1) -> do
putStrLn $ "\nSorry - stack was resetted. You got a 1!"
return $ Score 0 score
('r', _) -> do
putStr $ " => " ++ show stack
askPlayer $ Score (stack + roll) score
_ -> do
putStrLn "\nInvalid input - please try again."
askPlayer $ Score stack score
|
cirquit/Personal-Repository
|
Haskell/RosettaCode/Pig-the-dice-game/Dice-game.hs
|
mit
| 1,157
| 0
| 15
| 379
| 465
| 227
| 238
| 33
| 4
|
module RPGSpec (main, spec) where
import Test.Hspec
import RPG
import Control.Monad (replicateM)
import Data.Either (isLeft, isRight)
import qualified Data.Map.Strict as Map
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
let me = mtPlayer { hp = 10, mana = 250 }
boss1 = BossStats 13 8
spells1 = [ Later Poison
, Now MagicMissile
]
game1 = mtGame { playerStats = PS me
, enemyStats = BS boss1
, strategy = ListStrat spells1 }
spells2 = [ Later Recharge
, Later Shield
, Now Drain
, Later Poison
, Now MagicMissile
]
boss2 = BossStats 14 8
poison = getEffect Poison
recharge = getEffect Recharge
shield = getEffect Shield
poisonE = Map.singleton Poison poison
describe "oneRound" $ do
let game2 = game1 { playerStats = PS me { mana = 77 }
, enemyStats = BS boss1
, activeEffects = poisonE
, spellsCast = 1
, manaSpent = 173
, turn = E Enemy }
let game3 = game1 { playerStats = PS me { hp = 2, mana = 77 }
, enemyStats = BS $ boss1 { hp' = 10 }
, activeEffects = Map.singleton Poison (poison { eDuration = 5})
, spellsCast = 1
, manaSpent = 173
, turn = P Player }
let game4 = game1 { playerStats = PS me { hp = 2, mana = 24 }
, enemyStats = BS $ boss1 { hp' = 3 }
, activeEffects = Map.singleton Poison (poison { eDuration = 4})
, spellsCast = 2
, manaSpent = 226
, turn = E Enemy}
it "should run one round of a fight" $
execGame' oneRound game1 `shouldBe` Right game2
it "should run several rounds as expected" $ do
execGame' (replicateM 1 oneRound) game1 `shouldBe` Right game2
execGame' (replicateM 2 oneRound) game1 `shouldBe` Right game3
execGame' (replicateM 3 oneRound) game1 `shouldBe` Right game4
it "should provide output about the status of the game" $
showGame' battle game1 `shouldSatisfy` isRight
let game1' = game1 { enemyStats = BS boss2
, strategy = ListStrat spells2 }
let game2' = game1' { playerStats = PS me { mana = 21 }
, activeEffects = Map.singleton Recharge (recharge { eDuration = 5 })
, spellsCast = 1
, manaSpent = 229
, turn = E Enemy
}
let game3' = game1' { playerStats = PS me { hp = 2, mana = 122 }
, activeEffects = Map.singleton Recharge (recharge { eDuration = 4 })
, spellsCast = 1
, manaSpent = 229
, turn = P Player
}
let game4' = game1' { playerStats = PS me { hp = 2, armor = 7, mana = 110 }
, activeEffects = Map.fromList [ (Recharge, recharge { eDuration = 3 })
, (Shield, shield { eDuration = 5 })
]
, spellsCast = 2
, manaSpent = 342
, turn = E Enemy
}
let game5' = game1' { playerStats = PS me { hp = 1, armor = 7, mana = 211 }
, activeEffects = Map.fromList [ (Recharge, recharge { eDuration = 2 })
, (Shield, shield { eDuration = 4 })
]
, spellsCast = 2
, manaSpent = 342
, turn = P Player
}
let game6' = game1' { playerStats = PS me { hp = 3, armor = 7, mana = 239 }
, enemyStats = BS boss2 { hp' = 12}
, activeEffects = Map.fromList [ (Recharge, recharge { eDuration = 1 })
, (Shield, shield { eDuration = 3 })
]
, spellsCast = 3
, manaSpent = 415
, turn = E Enemy
}
let game7' = game1' { playerStats = PS me { hp = 2, armor = 7, mana = 340 }
, enemyStats = BS boss2 { hp' = 12}
, activeEffects = Map.fromList [ (Shield, shield { eDuration = 2 })]
, spellsCast = 3
, manaSpent = 415
, turn = P Player
}
let game8' = game1' { playerStats = PS me { hp = 2, armor = 7, mana = 167 }
, enemyStats = BS boss2 { hp' = 12}
, activeEffects = Map.fromList [ (Shield, shield { eDuration = 1 })
, (Poison, poison { eDuration = 6})]
, spellsCast = 4
, manaSpent = 588
, turn = E Enemy
}
let game9' = game1' { playerStats = PS me { hp = 1, armor = 7, mana = 167 }
, enemyStats = BS boss2 { hp' = 9 }
, activeEffects = Map.fromList [ (Poison, poison { eDuration = 5}) ]
, spellsCast = 4
, manaSpent = 588
, turn = P Player
}
let game10' = game1' { playerStats = PS me { hp = 1, armor = 0, mana = 114 }
, enemyStats = BS boss2 { hp' = 2 }
, activeEffects = Map.fromList [ (Poison, poison { eDuration = 4}) ]
, spellsCast = 5
, manaSpent = 641
, turn = E Enemy
}
it "should run several rounds of a different game" $ do
execGame' (replicateM 1 oneRound) game1' `shouldBe` Right game2'
execGame' (replicateM 2 oneRound) game1' `shouldBe` Right game3'
execGame' (replicateM 3 oneRound) game1' `shouldBe` Right game4'
execGame' (replicateM 4 oneRound) game1' `shouldBe` Right game5'
execGame' (replicateM 5 oneRound) game1' `shouldBe` Right game6'
execGame' (replicateM 6 oneRound) game1' `shouldBe` Right game7'
execGame' (replicateM 7 oneRound) game1' `shouldBe` Right game8'
execGame' (replicateM 8 oneRound) game1' `shouldBe` Right game9'
execGame' (replicateM 9 oneRound) game1' `shouldBe` Right game10'
describe "validSequence" $ do
it "should confirm that a unique sequence is valid" $ do
let spellsSeq1 = [ Now MagicMissile
, Now Drain
, Later Shield
, Later Poison
, Later Recharge]
spellsSeq1 `shouldSatisfy` validSequence
it "should check that two Shields don't appear in 5 places of each other" $ do
let spellsSeq2 = [ Now MagicMissile
, Now Drain
, Later Shield
, Later Poison
, Later Shield]
spellsSeq2 `shouldSatisfy` not . validSequence
describe "playerWins" $
it "should return True if the player won fight" $ do
playerWins (BS boss1) spells1 `shouldBe` True
playerWins (BS boss2) spells2 `shouldBe` True
|
corajr/adventofcode2015
|
22/test/RPGSpec.hs
|
mit
| 7,708
| 0
| 19
| 3,561
| 2,022
| 1,121
| 901
| -1
| -1
|
import Text.RegexPR
import Data.Maybe
identifier = isJust . matchRegexPR "^[a-zA-Z](-?[a-zA-Z0-9])*$"
main = do
print $ identifier "this-is-a-long-identifier"
print $ identifier "this-ends-in-"
print $ identifier "two--hyphens"
|
zeyuanxy/haskell-playground
|
ninety-nine-haskell-problems/vol11/96.hs
|
mit
| 242
| 0
| 8
| 39
| 58
| 27
| 31
| 7
| 1
|
{-# LANGUAGE TypeFamilies, FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE PartialTypeSignatures #-}
module AI.Funn.Diff.RNN (scanlDiff, mapDiff, zipDiff, unzipDiff, vsumDiff) where
import Control.Applicative
import Control.Applicative.Backwards
import Control.Monad
import Control.Monad.State.Lazy
import Data.Foldable
import Data.Traversable
import Data.Coerce
import Debug.Trace
import Foreign.C
import Foreign.Ptr
import System.IO
import System.IO.Unsafe
import Data.Functor.Identity
import Data.Vector (Vector)
import qualified Data.Vector.Generic as V
import qualified Data.Vector.Storable as S
import qualified Data.Vector.Storable.Mutable as M
import qualified Numeric.LinearAlgebra.HMatrix as HM
import AI.Funn.Diff.Diff (Derivable(..), Diff(..), Additive(..))
import qualified AI.Funn.Diff.Diff as Diff
traverseBack :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b)
traverseBack f = forwards . traverse (Backwards . f)
scanlDiff :: forall m x s i o. (Monad m, Additive m (D x)) =>
Diff m (x,(s,i)) (s, o) -> Diff m (x, (s, Vector i)) (s, Vector o)
scanlDiff layer = Diff run
where run (x,(s,inputs)) = do (oks, s') <- runStateT (traverse (go_forward x) inputs) s
let
(os, ks) = V.unzip oks
back (ds', dos) = do
(dxis, ds) <- runStateT (traverseBack go_backward (V.zip dos ks)) ds'
let (dxs, dis) = V.unzip dxis
dx <- plusm (toList dxs)
return (dx, (ds, dis))
return ((s', os), back)
-- go_forward :: x -> i -> StateT s m (o, _)
go_forward x i = do s <- get
((s',o), k) <- lift $ runDiff layer (x,(s,i))
put s'
return (o, k)
-- go_backward :: (D o, _) -> StateT (D s) m (D x, D i)
go_backward (dout, k) = do ds' <- get
(dx, (ds, di)) <- lift $ k (ds', dout)
put ds
return (dx, di)
zipDiff :: (Applicative m) => Diff m (Vector x, Vector y) (Vector (x,y))
zipDiff = Diff run
where
run (xs, ys) = pure (V.zip xs ys, pure . V.unzip)
unzipDiff :: (Applicative m) => Diff m (Vector (x,y)) (Vector x, Vector y)
unzipDiff = Diff run
where
run (xys) = pure (V.unzip xys, pure . uncurry V.zip)
-- mapDiff :: forall m x i o. (Monad m, Additive m (D x)) =>
-- Diff m (x,i) o -> Diff m (x, Vector i) (Vector o)
-- mapDiff layer = Diff run
-- where run (x,inputs) = do oks <- traverse (go_forward x) inputs
-- let
-- (os, ks) = V.unzip oks
-- back dos = do
-- dxis <- traverseBack go_backward (V.zip dos ks)
-- let (dxs, dis) = V.unzip dxis
-- dx <- plusm dxs
-- return (dx, dis)
-- return (os, back)
-- go_forward x i = runDiff layer (x,i)
-- go_backward (dout, k) = k dout
mapDiff :: forall m i o. (Monad m) => Diff m i o -> Diff m (Vector i) (Vector o)
mapDiff layer = Diff run
where run inputs = do oks <- traverse (runDiff layer) inputs
let
(os, ks) = V.unzip oks
back dos = traverse go_backward (V.zip dos ks)
return (os, back)
go_backward (dout, k) = k dout
vsumDiff :: (Monad m, Additive m a) => Diff m (Vector a) a
vsumDiff = Diff run
where
run inputs = do out <- plusm (toList inputs)
let !n = V.length inputs
back dout = return (V.replicate n dout)
return (out, back)
|
nshepperd/funn
|
AI/Funn/Diff/RNN.hs
|
mit
| 4,229
| 0
| 20
| 1,678
| 1,188
| 652
| 536
| 68
| 1
|
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
-- | Generate random numbers
module Random (LCGGen, mkLCGGen, randomList) where
--------------------------------------------------------------------------------
------------------------------------ Header ------------------------------------
--------------------------------------------------------------------------------
-- Imports
import System.Random
--------------------------------------------------------------------------------
------------------------------------ Types -------------------------------------
--------------------------------------------------------------------------------
newtype LCGGen = LCGGen [Int] deriving (Eq)
instance RandomGen LCGGen where
next (LCGGen (x:xs)) = (x, LCGGen xs)
genRange _ = (0, lcgModulus - 1)
split (LCGGen l) = (LCGGen (odds l), LCGGen (evens l))
--------------------------------------------------------------------------------
---------------------------------- Functions -----------------------------------
--------------------------------------------------------------------------------
-- | Generate a new linear congruential generator from the given seed
mkLCGGen :: Int -> LCGGen
mkLCGGen = LCGGen . randomList
-- | Infinite list of random numbers generated from the given seed
randomList :: Int -> [Int]
randomList seed = r : randomList r
where r = (seed * lcgMultiplier + lcgIncrement) `rem` lcgModulus
--------------------------------------------------------------------------------
---------------------------------- Constants -----------------------------------
--------------------------------------------------------------------------------
lcgModulus, lcgMultiplier, lcgIncrement :: Int
lcgModulus = 2 ^ 32
lcgMultiplier = 1103515245
lcgIncrement = 12345
--------------------------------------------------------------------------------
------------------------------ Utility functions -------------------------------
--------------------------------------------------------------------------------
-- | All the odd-numbered elements of a (potentially infinite) list
odds :: [a] -> [a]
odds [] = []
odds [a] = [a]
odds (a:_:xs) = a : odds xs
-- | All the even-numbered elements of a (potentially infinite) list
evens :: [a] -> [a]
evens [] = []
evens (_:xs) = evens xs
|
sebmathguy/icfp-2015
|
library/Random.hs
|
mit
| 2,353
| 0
| 10
| 282
| 363
| 211
| 152
| 24
| 1
|
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.YarnServiceProtos.StopContainerResponseProto (StopContainerResponseProto(..)) where
import Prelude ((+), (/))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data StopContainerResponseProto = StopContainerResponseProto{}
deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable StopContainerResponseProto where
mergeAppend StopContainerResponseProto StopContainerResponseProto = StopContainerResponseProto
instance P'.Default StopContainerResponseProto where
defaultValue = StopContainerResponseProto
instance P'.Wire StopContainerResponseProto where
wireSize ft' self'@(StopContainerResponseProto)
= case ft' of
10 -> calc'Size
11 -> P'.prependMessageSize calc'Size
_ -> P'.wireSizeErr ft' self'
where
calc'Size = 0
wirePut ft' self'@(StopContainerResponseProto)
= case ft' of
10 -> put'Fields
11 -> do
P'.putSize (P'.wireSize 10 self')
put'Fields
_ -> P'.wirePutErr ft' self'
where
put'Fields
= do
Prelude'.return ()
wireGet ft'
= case ft' of
10 -> P'.getBareMessageWith update'Self
11 -> P'.getMessageWith update'Self
_ -> P'.wireGetErr ft'
where
update'Self wire'Tag old'Self
= case wire'Tag of
_ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
instance P'.MessageAPI msg' (msg' -> StopContainerResponseProto) StopContainerResponseProto where
getVal m' f' = f' m'
instance P'.GPB StopContainerResponseProto
instance P'.ReflectDescriptor StopContainerResponseProto where
getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList [])
reflectDescriptorInfo _
= Prelude'.read
"DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.yarn.StopContainerResponseProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"YarnServiceProtos\"], baseName = MName \"StopContainerResponseProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"YarnServiceProtos\",\"StopContainerResponseProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
instance P'.TextType StopContainerResponseProto where
tellT = P'.tellSubMessage
getT = P'.getSubMessage
instance P'.TextMsg StopContainerResponseProto where
textPut msg = Prelude'.return ()
textGet = Prelude'.return P'.defaultValue
|
alexbiehl/hoop
|
hadoop-protos/src/Hadoop/Protos/YarnServiceProtos/StopContainerResponseProto.hs
|
mit
| 2,943
| 1
| 16
| 536
| 554
| 291
| 263
| 53
| 0
|
module Emit where
import Control.Monad.Except
import Control.Applicative
import qualified LLVM.General.Module as Module
import qualified LLVM.General.Context as Context
import qualified LLVM.General.AST as AST
import qualified LLVM.General.AST.Constant as C
import qualified LLVM.General.AST.Type as LT
import Data.Char
import qualified Data.Map as Map
import Codegen
import JIT
import qualified Syntax as S
import qualified Types as T
liftError :: ExceptT String IO a -> IO a
liftError = runExceptT >=> either fail return
codegenTop :: S.TopLevelDecl -> LLVM ()
codegenTop (S.FunctionDecl name (S.Signature args result) (Just body)) = do
mapM defineConst constants
define resultType name funcArgs blocks
where
resultType = resultTypeOf result
funcArgs = funcArgsOf args
(blocks, constants) = blocksFor body funcArgs
codegenTop (S.ExternFunctionDecl name (S.Signature args result)) = do
external resultType name funcArgs
where
resultType = resultTypeOf result
funcArgs = funcArgsOf args
codegen :: AST.Module -> [S.TopLevelDecl] -> IO AST.Module
codegen mod decls = do
res <- runJIT oldast
case res of
Right newast -> return newast
Left err -> putStrLn err >> return oldast
where
modn = mapM codegenTop decls
oldast = runLLVM mod modn
-- # codegen expressions and statements
cgen :: S.Statement -> Codegen AST.Operand
cgen (S.SimpleStmt (S.ExpressionStmt expr)) = cgenexpr expr
cgen statement = error $ "Unable to understand statement: " ++ show statement
cgenexpr :: S.Expression -> Codegen AST.Operand
cgenexpr (S.Binary (S.AddBinOp S.Plus) a b) = cgenbinop iadd a b
cgenexpr (S.Binary (S.AddBinOp S.Minus) a b) = cgenbinop isub a b
cgenexpr (S.Binary (S.MulBinOp S.Mult) a b) = cgenbinop imul a b
cgenexpr (S.Binary (S.MulBinOp S.Div) a b) = cgenbinop idiv a b
cgenexpr (S.Binary (S.MulBinOp S.Mod) a b) = cgenbinop imod a b
cgenexpr (S.Unary (S.PrimaryExpr (S.Arguments f args _ _))) = cgencall f args
cgenexpr (S.Unary (S.PrimaryExpr (S.Operand (S.Literal (S.IntLiteral value))))) = return $ cons $ C.Int 64 value
cgenexpr (S.Unary (S.PrimaryExpr (S.Operand (S.Literal (S.StringLiteral value))))) = cgencstring value
cgenexpr (S.Unary (S.PrimaryExpr (S.Operand (S.OperandName (S.OperandIdentifier name))))) = getvar name
cgenexpr expr = error $ "Unable to understand expression: " ++ show expr
cgenfn :: S.PrimaryExpr -> Codegen AST.Operand
cgenfn (S.Operand (S.OperandName (S.OperandIdentifier name))) = return $ funref $ AST.Name name
cgenbinop :: (AST.Operand -> AST.Operand -> Codegen AST.Operand) -> S.Expression -> S.Expression -> Codegen AST.Operand
cgenbinop fn a b = do
ca <- cgenexpr a
cb <- cgenexpr b
fn ca cb
cgencall :: S.PrimaryExpr -> [S.Expression] -> Codegen AST.Operand
cgencall f args = do
cf <- cgenfn f
cargs <- mapM cgenexpr args
call cf cargs
i8array :: String -> [C.Constant]
i8array [] = [C.Int 8 0]
i8array (x:xs) = (C.Int 8 $ toInteger $ ord x):(i8array xs)
cgencstring :: String -> Codegen AST.Operand
cgencstring value = do
var <- alloca $ T.array (fromIntegral $ length strvalue) T.char
store var strconst
ptr <- ptrof var
return ptr
where
strconst = cons $ C.Array T.char $ i8array value
strvalue = i8array value
-- # Function generation helpers
funcArgsOf args = concat $ map funcArgOf args
-- FIXME: supports currently only void and int
resultTypeOf Nothing = T.void
resultTypeOf (Just (S.FunctionSingleResult _)) = T.i64
-- FIXME:
-- - does not implement ellipsis
funcArgOf (S.ParameterDecl names ty Nothing) = map (\name -> (getType ty, AST.Name name)) names
-- FIXME: ignores provided list of statements entirely
blocksFor :: [S.Statement] -> [(LT.Type, AST.Name)] -> ([AST.BasicBlock], ConstDef)
blocksFor body funcArgs =
(blocks, constants)
where
code = do
entry <- addBlock entryBlockName
setBlock entry
forM funcArgs $ \(ty, (AST.Name name)) -> do
assign name $ local ty $ AST.Name name
forM (filter nonEmpty body) cgen
voidRet
executed = execCodegen code
blocks = createBlocks executed
constants = getConstants executed
nonEmpty (S.SimpleStmt S.Empty) = False
nonEmpty _ = True
getType :: S.Type -> LT.Type
getType (S.TypeName (S.Identifier "cstring")) = T.cstring
getType (S.TypeName (S.Identifier "int")) = T.i64
getType (S.TypeLiteral (S.InterfaceType [])) = T.ptr T.void
getType x = error $ "Unable to recognize type: " ++ show x
defineConst :: SingleConstDef -> LLVM ()
defineConst (name, ty, value) = addPrivConst name ty value
|
waterlink/hgo
|
Emit.hs
|
mit
| 4,570
| 0
| 16
| 836
| 1,743
| 877
| 866
| 98
| 2
|
{-
@Author: Felipe Rabelo
@Date: Jan 10 2019
-}
data FB a = Fizz | Buzz | FizzBuzz | Val a deriving (Show)
fizzBuzz :: Int -> Int -> IO ()
fizzBuzz a b = mapM_ print' [if x `mod` 15 == 0 then FizzBuzz
else if x `mod` 5 == 0 then Buzz
else if x `mod` 3 == 0 then Fizz else Val x | x <- [a..b]]
print' :: (Show a) => FB a -> IO ()
print' (Val x) = print x
print' m = print m
|
KHs000/haskellToys
|
src/scripts/fizzbuzz.hs
|
mit
| 399
| 0
| 11
| 117
| 188
| 102
| 86
| 8
| 4
|
{-# LANGUAGE TemplateHaskell #-}
module UnitTest.RequestParse.AttachmentRequest where
import Data.Aeson (Value)
import Data.Yaml.TH (decodeFile)
import Test.Tasty as Tasty
import Web.Facebook.Messenger
import UnitTest.Internal
-------------------------
-- ATTACHMENT REQUESTS --
-------------------------
attachmentRequestTests :: TestTree
attachmentRequestTests = Tasty.testGroup "Attachment Requests"
[ attachmentRequestTypes
, attachmentRequestMedia
, attachmentRequestMediaReusable
]
attachmentRequestMediaVal :: Value
attachmentRequestMediaVal = $$(decodeFile "test/json/request/attachment_request_media.json")
attachmentRequestMedia :: TestTree
attachmentRequestMedia = parseTest "Media attachment" attachmentRequestMediaVal
$ sendRequest (recipientID $ PSID "<PSID>")
$ attachmentRequest_ $ multimediaRequest_ VIDEO "http://www.example.com/video.mp4"
attachmentRequestMediaReusableVal :: Value
attachmentRequestMediaReusableVal = $$(decodeFile "test/json/request/attachment_request_media_reusable.json")
attachmentRequestMediaReusable :: TestTree
attachmentRequestMediaReusable = parseTest "Reusable media attachment" attachmentRequestMediaReusableVal
$ sendRequest (recipientID $ PSID "<PSID>")
$ attachmentRequest_ $ multimediaRequest IMAGE "http://www.example.com/file.jpg" True
attachmentRequestTypesVal :: Value
attachmentRequestTypesVal = $$(decodeFile "test/json/request/attachment_request_media_types.json")
attachmentRequestTypes :: TestTree
attachmentRequestTypes = parseTest "Attachment types" attachmentRequestTypesVal $ [IMAGE, VIDEO, FILE, AUDIO]
|
Vlix/facebookmessenger
|
test/UnitTest/RequestParse/AttachmentRequest.hs
|
mit
| 1,711
| 0
| 11
| 264
| 250
| 139
| 111
| -1
| -1
|
{-|
Module : Day13
Description : <http://adventofcode.com/2016/day/13 Day 13: A Maze of Twisty Little Cubicles>
-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_HADDOCK ignore-exports #-}
module Day13 (main) where
import Common (readDataFile, unfold)
import Data.Bits (Bits, popCount, testBit)
import Data.Set (Set, insert, member, singleton)
import System.IO.Unsafe (unsafePerformIO)
input :: (Num a, Read a) => a
input = read $ unsafePerformIO $ readFile "day13.txt"
wall :: (Bits a, Num a) => a -> (a, a) -> Bool
wall input (x, y) = popCount (x^2 + 3*x + 2*x*y + y + y^2 + input) `testBit` 0
walk :: (Bits a, Num a, Ord a, Enum b) =>
a -> ((a, a), b) -> Set (a, a) -> ([((a, a), b)], Set (a, a))
walk input ((x, y), n) visited = (map (, succ n) next, foldr insert visited next) where
next = filter ok [(x + 1, y), (x, y - 1), (x - 1, y), (x, y + 1)]
ok (x, y) = x >= 0 && y >= 0 && not (wall input (x, y) || member (x, y) visited)
main :: IO ()
main = do
let reach = unfold (walk input) (singleton (1, 1)) [((1, 1), 0)] :: [((Int, Int), Int)]
print $ snd $ head $ filter ((==) (31, 39) . fst) reach
print $ length $ takeWhile ((<= 50) . snd) reach
|
ephemient/aoc2016
|
src/Day13.hs
|
mit
| 1,182
| 0
| 17
| 260
| 624
| 353
| 271
| 21
| 1
|
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.YarnServiceProtos.GetClusterNodeLabelsRequestProto (GetClusterNodeLabelsRequestProto(..)) where
import Prelude ((+), (/))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data GetClusterNodeLabelsRequestProto = GetClusterNodeLabelsRequestProto{}
deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable GetClusterNodeLabelsRequestProto where
mergeAppend GetClusterNodeLabelsRequestProto GetClusterNodeLabelsRequestProto = GetClusterNodeLabelsRequestProto
instance P'.Default GetClusterNodeLabelsRequestProto where
defaultValue = GetClusterNodeLabelsRequestProto
instance P'.Wire GetClusterNodeLabelsRequestProto where
wireSize ft' self'@(GetClusterNodeLabelsRequestProto)
= case ft' of
10 -> calc'Size
11 -> P'.prependMessageSize calc'Size
_ -> P'.wireSizeErr ft' self'
where
calc'Size = 0
wirePut ft' self'@(GetClusterNodeLabelsRequestProto)
= case ft' of
10 -> put'Fields
11 -> do
P'.putSize (P'.wireSize 10 self')
put'Fields
_ -> P'.wirePutErr ft' self'
where
put'Fields
= do
Prelude'.return ()
wireGet ft'
= case ft' of
10 -> P'.getBareMessageWith update'Self
11 -> P'.getMessageWith update'Self
_ -> P'.wireGetErr ft'
where
update'Self wire'Tag old'Self
= case wire'Tag of
_ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
instance P'.MessageAPI msg' (msg' -> GetClusterNodeLabelsRequestProto) GetClusterNodeLabelsRequestProto where
getVal m' f' = f' m'
instance P'.GPB GetClusterNodeLabelsRequestProto
instance P'.ReflectDescriptor GetClusterNodeLabelsRequestProto where
getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList [])
reflectDescriptorInfo _
= Prelude'.read
"DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.yarn.GetClusterNodeLabelsRequestProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"YarnServiceProtos\"], baseName = MName \"GetClusterNodeLabelsRequestProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"YarnServiceProtos\",\"GetClusterNodeLabelsRequestProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
instance P'.TextType GetClusterNodeLabelsRequestProto where
tellT = P'.tellSubMessage
getT = P'.getSubMessage
instance P'.TextMsg GetClusterNodeLabelsRequestProto where
textPut msg = Prelude'.return ()
textGet = Prelude'.return P'.defaultValue
|
alexbiehl/hoop
|
hadoop-protos/src/Hadoop/Protos/YarnServiceProtos/GetClusterNodeLabelsRequestProto.hs
|
mit
| 3,081
| 1
| 16
| 542
| 554
| 291
| 263
| 53
| 0
|
module Tree where
data Tree a = Tree a [Tree a]
deriving Show
mapTree :: (a -> b) -> Tree a -> [b]
mapTree fn (Tree a xs) = (fn a):(concat $ fmap (mapTree fn) xs)
mapTreeWithDepth :: (Int -> a -> b) -> Int -> Tree a -> [b]
mapTreeWithDepth fn depth (Tree a xs) = (fn depth a):(concat $ fmap (mapTreeWithDepth fn (depth+1)) xs)
mapTreePath :: ([a] -> b) -> [a]-> Tree a -> [b]
mapTreePath fn path (Tree a []) = [fn $ a:path]
mapTreePath fn path (Tree a xs) = concat $ fmap (mapTreePath fn (a:path)) xs
firstToDepth :: Int -> Tree a -> Maybe [a]
firstToDepth depth t = case pathsOfMatchingDepth of
[] -> Nothing
x:xs -> Just x
where paths = mapTreePath id [] t
pathsOfMatchingDepth = filter ((depth<=) . length) paths
buildTree :: ([a] -> a -> [a]) -> [a] -> a -> Tree a
buildTree fn path a = Tree a next
where next = fmap (buildTree fn $ a:path) (fn path a)
|
pzavolinsky/hungry-knight
|
core/Tree.hs
|
mit
| 885
| 0
| 12
| 199
| 488
| 254
| 234
| 19
| 2
|
{-# LANGUAGE DeriveGeneric #-}
import Debug.Trace
import GHC.Generics
import Test.QuickCheck
import Test.QuickCheck.Modifiers (NonEmptyList (..))
import Test.QuickCheck.Monadic (monadicIO, pick, pre, run, assert)
import Data.Int
import Data.List
import qualified Data.Char as Char
import qualified ReuseStdlib as Reuse
import Conversions
data ReuseString
= SEmpty
| SAppend Char ReuseString
| SPrepend Char ReuseString
| SSkip Int32 ReuseString
| STake Int32 ReuseString
| SJoin ReuseString [ReuseString]
| SReverse ReuseString
| SRest ReuseString
| SConcat ReuseString ReuseString
deriving Generic
show_list_of_reuse_strings :: [ReuseString] -> String
show_list_of_reuse_strings xs = "(list " ++ (unwords (map show xs)) ++ ")"
instance Show ReuseString where
show SEmpty = "(string-empty)"
show (SAppend x xs) = "(string-append " ++ (show (Char.ord x)) ++ " " ++ (show xs) ++ ")"
show (SPrepend x xs) = "(string-prepend " ++ (show (Char.ord x)) ++ " " ++ (show xs) ++ ")"
show (SSkip x xs) = "(string-skip " ++ (show x) ++ " " ++ (show xs) ++ ")"
show (STake x xs) = "(string-take " ++ (show x) ++ " " ++ (show xs) ++ ")"
show (SJoin sep xs) = "(string-join " ++ (show sep) ++ " " ++ (show_list_of_reuse_strings xs) ++ ")"
show (SReverse xs) = "(string-reverse " ++ (show xs) ++ ")"
show (SRest xs) = "(string-rest " ++ (show xs) ++ ")"
show (SConcat xs ys) = "(string-concat " ++ (show xs) ++ " " ++ (show ys) ++ ")"
genSafeChar :: Gen Char
genSafeChar = elements ['A'..'Z']
emptyGen :: Gen ReuseString
emptyGen = return SEmpty
appendGen :: Int -> Gen ReuseString
appendGen n = do
x <- genSafeChar
xs <- arbitraryReuseString (n - 1)
return (SAppend x xs)
prependGen :: Int -> Gen ReuseString
prependGen n = do
x <- genSafeChar
xs <- arbitraryReuseString (n - 1)
return (SPrepend x xs)
skipGen :: Int -> Gen ReuseString
skipGen n = do
x <- arbitrary
xs <- arbitraryReuseString (n - 1)
return (SSkip x xs)
takeGen :: Int -> Gen ReuseString
takeGen n = do
x <- arbitrary
xs <- arbitraryReuseString (n - 1)
return (STake x xs)
joinGen :: Int -> Gen ReuseString
joinGen n = do
k <- choose (1, n)
sep <- arbitraryReuseString (n `div` k)
xs <- sequence [ arbitraryReuseString (n `div` k) | _ <- [1..k] ]
return (SJoin sep xs)
reverseGen :: Int -> Gen ReuseString
reverseGen n = do
xs <- arbitraryReuseString (n - 1)
return (SReverse xs)
restGen :: Int -> Gen ReuseString
restGen n = do
xs <- arbitraryReuseString (n - 1)
return (SRest xs)
concatGen :: Int -> Gen ReuseString
concatGen n = do
xs <- arbitraryReuseString (n `div` 2)
ys <- arbitraryReuseString (n `div` 2)
return (SConcat xs ys)
arbitraryReuseString :: Int -> Gen ReuseString
arbitraryReuseString 0 = emptyGen
arbitraryReuseString n = oneof [appendGen n, prependGen n, skipGen n, takeGen n, joinGen n, reverseGen n, restGen n, concatGen n]
instance Arbitrary ReuseString where
arbitrary = do
x <- oneof [arbitraryReuseString 1, arbitraryReuseString 2, arbitraryReuseString 3, sized arbitraryReuseString]
return x
shrink x = shrinkToNil x ++ genericShrink x
where
shrinkToNil SEmpty = []
shrinkToNil _ = [SEmpty]
charToInt = fromIntegral . Char.ord
evalReuse :: ReuseString -> Reuse.String
evalReuse SEmpty = Reuse.string_empty
evalReuse (SAppend x xs) = Reuse.string_append (charToInt x) (evalReuse xs)
evalReuse (SPrepend x xs) = Reuse.string_prepend (charToInt x) (evalReuse xs)
evalReuse (SSkip x xs) = Reuse.string_skip x (evalReuse xs)
evalReuse (STake x xs) = Reuse.string_take x (evalReuse xs)
evalReuse (SJoin x xs) = Reuse.string_join (evalReuse x) (list_to_reuse (map evalReuse xs))
evalReuse (SReverse xs) = Reuse.string_reverse (evalReuse xs)
evalReuse (SRest xs) = Reuse.string_rest (evalReuse xs)
evalReuse (SConcat xs ys) = Reuse.string_concat (evalReuse xs) (evalReuse ys)
evalHs :: ReuseString -> String
evalHs SEmpty = ""
evalHs (SAppend x xs) = (evalHs xs) ++ [x]
evalHs (SPrepend x xs) = [x] ++ (evalHs xs)
evalHs (SSkip x xs) = drop (fromIntegral x) (evalHs xs)
evalHs (STake x xs) = take (fromIntegral x) (evalHs xs)
evalHs (SJoin x xs) = intercalate (evalHs x) (map evalHs xs)
evalHs (SReverse xs) = reverse (evalHs xs)
evalHs (SRest xs) = (if length s == 0 then "" else tail s) where s = (evalHs xs)
evalHs (SConcat xs ys) = (evalHs xs) ++ (evalHs ys)
prop_isomorphic :: String -> Bool
prop_isomorphic xs = string_to_hs (string_to_reuse xs) == xs
prop_equivalence :: ReuseString -> Bool
prop_equivalence xs = string_to_hs (evalReuse xs) == evalHs xs
prop_equivalence_backend :: String -> String -> ReuseString -> Property
prop_equivalence_backend lang source xs = monadicIO $ do
result <- run $ evalExpr lang source (show xs)
assert $ result == evalHs xs
prop_string_first :: NonEmptyList Char -> Bool
prop_string_first (NonEmpty s) = maybe_to_hs (Reuse.maybe_map (Char.chr . fromIntegral) (Reuse.string_first (string_to_reuse s))) == Just (head s)
prop_string_size :: String -> Bool
prop_string_size s = (fromIntegral . Reuse.string_size . string_to_reuse) s == length s
prop_string_every :: Fun Int Bool -> String -> Bool
prop_string_every (Fn f) xs = bool_to_hs (Reuse.string_every (bool_to_reuse . f . fromIntegral) (string_to_reuse xs)) == all (f . Char.ord) xs
prop_string_any :: Fun Int Bool -> String -> Bool
prop_string_any (Fn f) xs = bool_to_hs (Reuse.string_any (bool_to_reuse . f . fromIntegral) (string_to_reuse xs)) == any (f . Char.ord) xs
prop_string_to_int32 :: Int32 -> Bool
prop_string_to_int32 x = (maybe_to_hs . Reuse.string_to_int32 . string_to_reuse . show) x == Just x
prop_string_from_int32 :: Int32 -> Bool
prop_string_from_int32 x = (string_to_hs . Reuse.string_from_int32) x == show x
quickCheckN f = quickCheck (withMaxSuccess 1000 f)
main :: IO ()
main = do
quickCheck $ withMaxSuccess 100 $ prop_equivalence_backend "javascript" "executable.js"
quickCheck $ withMaxSuccess 100 $ prop_equivalence_backend "ocaml" "executable.ml"
quickCheckN prop_isomorphic
quickCheck (withMaxSuccess 100000 prop_equivalence)
quickCheckN prop_string_first
quickCheckN prop_string_size
quickCheckN prop_string_every
quickCheckN prop_string_any
quickCheckN prop_string_to_int32
|
redien/reuse-lang
|
standard-library/specification/string.hs
|
cc0-1.0
| 6,371
| 9
| 13
| 1,223
| 2,454
| 1,212
| 1,242
| 140
| 2
|
module Cashlog.Cli.Utility where
dateFormat = "%d.%m.%Y"
timeFormat = "%R"
iso8601SqlFormat = "%Y-%m-%d %T"
|
pads-fhs/Cashlog
|
src/Cashlog/Cli/Utility.hs
|
gpl-2.0
| 109
| 0
| 4
| 14
| 22
| 14
| 8
| 4
| 1
|
module Main where
import Data.Stdf
import qualified Data.ByteString.Lazy.Char8 as BL
import System.Environment (getArgs)
import System.Exit (exitFailure)
import Control.Monad (when)
import Data.Aeson
printUsage = putStrLn "usage: StdfToJson file.stdf"
-- unparsed records have type Raw for the time being
notRaw :: Rec -> Bool
notRaw (Raw _) = False
notRaw _ = True
isFtr :: Rec -> Bool
isFtr (Ftr{}) = True
isFtr _ = False
main = do
args <- getArgs
when (length args /= 1) $ do
printUsage
exitFailure
let file = head args
recs <- parseFile file
let goodRecs = filter notRaw recs
mapM_ (BL.putStrLn . encode) goodRecs
|
gitfoxi/Stdf
|
Examples/StdfToJson.hs
|
gpl-2.0
| 670
| 0
| 11
| 151
| 217
| 113
| 104
| 23
| 1
|
module Field where
import Data.List
{- A 4x4 field essentially is a list of lists (which is a more general approach than a tuple of tuples).
- Negative values encode empty fields
- Values > 0 encode powers of 2
- Values = 0 are not useful (undefined state)
-}
type Pos = (Int,Int)
type CellVal = Int
type Field=[[CellVal]]
testfield = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]::Field
arbitraryInitField = [ replicate 4 (-1)
, [-1,-1,2,-1]
, replicate 4 (-1)
, [-1,2,2,-1]
]::Field
rotateLeft:: Field -> Field
rotateLeft = reverse.transpose
rotateRight:: Field -> Field
rotateRight = transpose.reverse
|
FiskerLars/2048.hs
|
Field.hs
|
gpl-2.0
| 699
| 0
| 8
| 183
| 214
| 134
| 80
| 15
| 1
|
module Dep.Algorithms.Proc where
|
KommuSoft/dep-software
|
Dep.Algorithms.Proc.hs
|
gpl-3.0
| 34
| 0
| 3
| 4
| 7
| 5
| 2
| 1
| 0
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
module Language.Soiie.Internal.Codegen where
import Control.Lens (ASetter', Snoc, at,
makeLenses, use)
import Control.Lens.Operators
import Control.Monad.State (MonadState, State,
execState)
import Data.Foldable (toList)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)
import Data.Sequence (Seq)
import qualified Data.Sequence as S
import LLVM.General.AST.AddrSpace (AddrSpace (..))
import qualified LLVM.General.AST.CallingConvention as CC
import qualified LLVM.General.AST.Constant as C
import LLVM.General.AST.IntegerPredicate (IntegerPredicate)
import LLVM.General.AST.Type (i1, i64)
import LLVM.General.AST
--------------------------------------------------------------------------------
-- Codegen Monad
--------------------------------------------------------------------------------
data BlockgenState = BlockgenState
{ _name :: Name
, _instrs :: Seq (Named Instruction)
, _term :: Maybe (Named Terminator)
} deriving (Show)
makeLenses ''BlockgenState
type SymbolTable = Map String Operand
type NameSupply = Map (Maybe String) Word
data CodegenState = CodegenState
{ _currentBlock :: BlockgenState
, _blocks :: Seq BlockgenState
, _symbolTable :: SymbolTable
, _nameSupply :: NameSupply
} deriving (Show)
makeLenses ''CodegenState
newtype Codegen a = Codegen { runCodegen :: State CodegenState a }
deriving (Functor, Applicative, Monad, MonadState CodegenState)
emptyCodegenState :: CodegenState
emptyCodegenState = CodegenState entryBlk S.empty M.empty (M.singleton Nothing 1)
where
entryBlk = BlockgenState (UnName 0) S.empty Nothing
execCodegen :: Codegen a -> CodegenState
execCodegen m = execState (runCodegen m) emptyCodegenState
genBlocks :: CodegenState -> [BasicBlock]
genBlocks cs = toList . fmap mkBlock $ (cs^.blocks) |> (cs^.currentBlock)
where
mkBlock :: BlockgenState -> BasicBlock
mkBlock BlockgenState {..} =
BasicBlock _name
(toList _instrs)
(fromMaybe (error ("no terminator for block: " ++ show _name)) _term)
--------------------------------------------------------------------------------
-- State Manipulation Helpers
--------------------------------------------------------------------------------
uniqueName :: Maybe String -> Codegen Name
uniqueName maybeString = mkName <$> mkId
where
mkId :: Codegen Word
mkId = (nameSupply . at maybeString <<%= Just . (+1) . fromMaybe 0) <&> fromMaybe 0
mkName :: Word -> Name
mkName = case maybeString of
Nothing -> UnName
Just s -> Name . (s ++) . ('.' :) . show
setTerm :: Named Terminator -> Codegen ()
setTerm t = currentBlock . term ?= t
addNewBlock :: Name -> Codegen ()
addNewBlock blkName =
do
c <- use currentBlock
blocks |>= c
currentBlock .= BlockgenState blkName S.empty Nothing
--------------------------------------------------------------------------------
-- Instructions
--------------------------------------------------------------------------------
instr :: Type -> Instruction -> Codegen Operand
instr ty i =
do
n <- uniqueName Nothing
currentBlock . instrs |>= (n := i)
return (locRef ty n)
add :: Operand -> Operand -> Codegen Operand
add op1 op2 = instr i64 (Add False False op1 op2 [])
sub :: Operand -> Operand -> Codegen Operand
sub op1 op2 = instr i64 (Sub False False op1 op2 [])
mul :: Operand -> Operand -> Codegen Operand
mul op1 op2 = instr i64 (Mul False False op1 op2 [])
div :: Operand -> Operand -> Codegen Operand
div op1 op2 = instr i64 (SDiv False op1 op2 [])
rem :: Operand -> Operand -> Codegen Operand
rem op1 op2 = instr i64 (SRem op1 op2 [])
neg :: Operand -> Codegen Operand
neg = sub (iconst 0)
icmp :: IntegerPredicate -> Operand -> Operand -> Codegen Operand
icmp ip op1 op2 = instr i1 (ICmp ip op1 op2 [])
alloca :: Type -> Codegen Operand
alloca ty = instr (ptrTo ty) (Alloca ty Nothing 0 [])
load :: Operand -> Codegen Operand
load ptr = instr i64 (Load False ptr Nothing 0 [])
store :: Operand -> Operand -> Codegen ()
store ptr val = currentBlock . instrs |>= Do (Store False ptr val Nothing 0 [])
getelemptr :: Type -> Operand -> Integer -> Codegen Operand
getelemptr ty arr idx = instr (ptrTo ty)
(GetElementPtr True arr [iconst 0, iconst idx] [])
call :: Type -> Operand -> [Operand] -> Codegen Operand
call ty func args = instr ty Call
{ tailCallKind = Nothing
, callingConvention = CC.C
, returnAttributes = []
, function = Right func
, arguments = fmap (\x->(x, [])) args
, functionAttributes = []
, metadata = []
}
--------------------------------------------------------------------------------
-- Symbol Table Helpers
--------------------------------------------------------------------------------
allocaVar :: String -> Codegen Operand
allocaVar var =
do
op <- alloca i64
prev <- symbolTable . at var <<.= Just op
case prev of
Nothing -> return op
_ -> error ("variable/parameter defined twice: " ++ var)
lookupVar :: String -> Codegen Operand
lookupVar var = fromMaybe die <$> use (symbolTable . at var)
where
die :: a
die = error ("use of undeclared variable: " ++ var)
--------------------------------------------------------------------------------
-- Utils
--------------------------------------------------------------------------------
ptrTo :: Type -> Type
ptrTo t = PointerType t (AddrSpace 0)
locRef :: Type -> Name -> Operand
locRef = LocalReference
gblRef :: Type -> Name -> Operand
gblRef t n = ConstantOperand (C.GlobalReference t n)
iconst :: Integer -> Operand
iconst i = ConstantOperand (C.Int 64 i)
infixl 4 |>=
(|>=) :: (MonadState s m, Snoc a a e e) => ASetter' s a -> e -> m ()
l |>= e = l %= (|> e)
|
HMPerson1/soiie
|
src/Language/Soiie/Internal/Codegen.hs
|
gpl-3.0
| 6,337
| 0
| 14
| 1,479
| 1,825
| 965
| 860
| -1
| -1
|
{-# LANGUAGE TemplateHaskell #-}
module Types.File
( File (..)
, id
, path
, size
, accessTime
, modTime
, user
, group
, other
, conv
) where
import Data.Word (Word64)
import Data.Int (Int64)
import Data.Time.Clock (UTCTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Control.Lens
import System.Posix.Files (accessTimeHiRes
,modificationTimeHiRes
,fileSize
,isRegularFile
)
import System.Posix.Files (FileStatus)
import qualified Types.Permission as P
import Prelude hiding (id)
data File =
File { _id :: !(Maybe Int64)
, _path :: !FilePath
, _size :: !Word64
, _accessTime :: !UTCTime
, _modTime :: !UTCTime
, _user :: !P.Permission
, _group :: !P.Permission
, _other :: !P.Permission
}
makeLenses ''File
-- | Convert a filestatus witha filepath to a File.
conv :: FilePath -- ^ Location of file.
-> FileStatus -- ^ Status of file.
-> Maybe File
conv fp fs =
let aT = posixSecondsToUTCTime . accessTimeHiRes
mT = posixSecondsToUTCTime . modificationTimeHiRes
c = File { _id = Nothing
, _path = fp
, _size = fromIntegral (fileSize fs)
, _accessTime = aT fs
, _modTime = mT fs
, _user = P.Permission True True False
, _group = P.Permission True True False
, _other = P.Permission True False False
}
in if isRegularFile fs
then Just c
else Nothing
|
steffenomak/file-indexer
|
src/Types/File.hs
|
gpl-3.0
| 1,813
| 0
| 13
| 752
| 388
| 226
| 162
| 67
| 2
|
import System.Environment
import Data.List
main = do
args <- getArgs
progName <- getProgName
putStrLn "the arguments are:"
mapM putStrLn args
putStrLn "the program name is:"
putStrLn progName
|
ljwolf/learnyouahaskell-assignments
|
ex.systemenvironment.hs
|
gpl-3.0
| 199
| 0
| 7
| 34
| 56
| 24
| 32
| 9
| 1
|
movingAvg :: Fractional a => Int -> Stream a -> Stream a
movingAvg n = extend (average n)
|
hmemcpy/milewski-ctfp-pdf
|
src/content/3.7/code/haskell/snippet24.hs
|
gpl-3.0
| 89
| 0
| 8
| 17
| 44
| 20
| 24
| 2
| 1
|
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module LevelTools.Make
(
lvlFromEdit,
makeLevelPuzzleWorldEmpty,
writeEditAsLevel,
writeWorldHeader,
) where
import MyPrelude
import Game
import LevelTools.EditWorld
import LevelTools.File
import Game.LevelPuzzleMode.LevelPuzzleWorld
import Game.LevelPuzzleMode.LevelPuzzleWorld.OutputState
import Game.Grid.GridWorld
import File.Binary
lvlFromEdit :: EditWorld -> MEnv' LevelPuzzleWorld
lvlFromEdit edit = do
let level = editLevel edit
creator = "grid_design"
name = "unknown name"
path = "/dev/null"
cnt <- makeContentEmpty
ixrooms <- io $ mapM makeRoomIxRoom $ scontentRooms $ editSemiContent edit
cnt' <- makeContentCamera (levelSegments level) ixrooms $
makeCameraWithView valueLevelPuzzleView
state <- makeOutputState
return LevelPuzzleWorld
{
levelpuzzleCreator = creator,
levelpuzzleName = name,
levelpuzzleLevelIx = 0,
levelpuzzleLevel = level,
levelpuzzleOldContent = cnt,
levelpuzzleContent = cnt',
levelpuzzleRefOldContent = mempty,
levelpuzzleRefSpace = mempty,
levelpuzzleIsPuzzle = False,
levelpuzzleEvents = [],
levelpuzzleSegmentsCount = levelSegments level,
levelpuzzleIsComplete = False,
levelpuzzleFailureEvent = EventEmpty,
levelpuzzleFile = path,
levelpuzzleFileSize = 0,
levelpuzzleFileDefOffset = 0,
levelpuzzleFileDefNextOffset = 0,
levelpuzzleOutputState = state
}
makeLevelPuzzleWorldEmpty :: MEnv' LevelPuzzleWorld
makeLevelPuzzleWorldEmpty = do
let level = makeLevel "empty_level" False 0
creator = "empty_creator"
name = "empty_name"
path = "/dev/null"
cnt <- makeContentEmpty
cnt' <- makeContentEmpty
state <- makeOutputState
return LevelPuzzleWorld
{
levelpuzzleCreator = creator,
levelpuzzleName = name,
levelpuzzleLevelIx = 0,
levelpuzzleLevel = level,
levelpuzzleOldContent = cnt,
levelpuzzleContent = cnt',
levelpuzzleRefOldContent = mempty,
levelpuzzleRefSpace = mempty,
levelpuzzleIsPuzzle = False,
levelpuzzleEvents = [],
levelpuzzleSegmentsCount = levelSegments level,
levelpuzzleIsComplete = False,
levelpuzzleFailureEvent = EventEmpty,
levelpuzzleFile = path,
levelpuzzleFileSize = 0,
levelpuzzleFileDefOffset = 0,
levelpuzzleFileDefNextOffset = 0,
levelpuzzleOutputState = state
}
writeEditAsLevel :: EditWorld -> FilePath -> IO ()
writeEditAsLevel edit path = do
maybeWrite <- writeBinary (wLevel edit) path
case maybeWrite of
Nothing -> return ()
Just msg -> putStrLn $ "could not write edit to file " ++ path ++ ": \n" ++ msg
writeWorldHeader :: String -> String -> FilePath -> IO ()
writeWorldHeader creator name path = do
maybeWrite <- writeBinary (wWorldHeader creator name) path
case maybeWrite of
Nothing -> return ()
Just msg -> putStrLn $ "could not write world header to file " ++ path ++ ": \n" ++ msg
|
karamellpelle/grid
|
designer/source/LevelTools/Make.hs
|
gpl-3.0
| 4,223
| 0
| 13
| 1,274
| 683
| 384
| 299
| 84
| 2
|
{-# 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.YouTube.Captions.Insert
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Inserts a new resource into this collection.
--
-- /See:/ <https://developers.google.com/youtube/ YouTube Data API v3 Reference> for @youtube.captions.insert@.
module Network.Google.Resource.YouTube.Captions.Insert
(
-- * REST Resource
CaptionsInsertResource
-- * Creating a Request
, captionsInsert
, CaptionsInsert
-- * Request Lenses
, ciOnBehalfOf
, ciXgafv
, ciPart
, ciUploadProtocol
, ciAccessToken
, ciUploadType
, ciPayload
, ciOnBehalfOfContentOwner
, ciSync
, ciCallback
) where
import Network.Google.Prelude
import Network.Google.YouTube.Types
-- | A resource alias for @youtube.captions.insert@ method which the
-- 'CaptionsInsert' request conforms to.
type CaptionsInsertResource =
"youtube" :>
"v3" :>
"captions" :>
QueryParams "part" Text :>
QueryParam "onBehalfOf" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "onBehalfOfContentOwner" Text :>
QueryParam "sync" Bool :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Caption :> Post '[JSON] Caption
:<|>
"upload" :>
"youtube" :>
"v3" :>
"captions" :>
QueryParams "part" Text :>
QueryParam "onBehalfOf" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "onBehalfOfContentOwner" Text :>
QueryParam "sync" Bool :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
QueryParam "uploadType" Multipart :>
MultipartRelated '[JSON] Caption :>
Post '[JSON] Caption
-- | Inserts a new resource into this collection.
--
-- /See:/ 'captionsInsert' smart constructor.
data CaptionsInsert =
CaptionsInsert'
{ _ciOnBehalfOf :: !(Maybe Text)
, _ciXgafv :: !(Maybe Xgafv)
, _ciPart :: ![Text]
, _ciUploadProtocol :: !(Maybe Text)
, _ciAccessToken :: !(Maybe Text)
, _ciUploadType :: !(Maybe Text)
, _ciPayload :: !Caption
, _ciOnBehalfOfContentOwner :: !(Maybe Text)
, _ciSync :: !(Maybe Bool)
, _ciCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CaptionsInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ciOnBehalfOf'
--
-- * 'ciXgafv'
--
-- * 'ciPart'
--
-- * 'ciUploadProtocol'
--
-- * 'ciAccessToken'
--
-- * 'ciUploadType'
--
-- * 'ciPayload'
--
-- * 'ciOnBehalfOfContentOwner'
--
-- * 'ciSync'
--
-- * 'ciCallback'
captionsInsert
:: [Text] -- ^ 'ciPart'
-> Caption -- ^ 'ciPayload'
-> CaptionsInsert
captionsInsert pCiPart_ pCiPayload_ =
CaptionsInsert'
{ _ciOnBehalfOf = Nothing
, _ciXgafv = Nothing
, _ciPart = _Coerce # pCiPart_
, _ciUploadProtocol = Nothing
, _ciAccessToken = Nothing
, _ciUploadType = Nothing
, _ciPayload = pCiPayload_
, _ciOnBehalfOfContentOwner = Nothing
, _ciSync = Nothing
, _ciCallback = Nothing
}
-- | ID of the Google+ Page for the channel that the request is be on behalf
-- of
ciOnBehalfOf :: Lens' CaptionsInsert (Maybe Text)
ciOnBehalfOf
= lens _ciOnBehalfOf (\ s a -> s{_ciOnBehalfOf = a})
-- | V1 error format.
ciXgafv :: Lens' CaptionsInsert (Maybe Xgafv)
ciXgafv = lens _ciXgafv (\ s a -> s{_ciXgafv = a})
-- | The *part* parameter specifies the caption resource parts that the API
-- response will include. Set the parameter value to snippet.
ciPart :: Lens' CaptionsInsert [Text]
ciPart
= lens _ciPart (\ s a -> s{_ciPart = a}) . _Coerce
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ciUploadProtocol :: Lens' CaptionsInsert (Maybe Text)
ciUploadProtocol
= lens _ciUploadProtocol
(\ s a -> s{_ciUploadProtocol = a})
-- | OAuth access token.
ciAccessToken :: Lens' CaptionsInsert (Maybe Text)
ciAccessToken
= lens _ciAccessToken
(\ s a -> s{_ciAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ciUploadType :: Lens' CaptionsInsert (Maybe Text)
ciUploadType
= lens _ciUploadType (\ s a -> s{_ciUploadType = a})
-- | Multipart request metadata.
ciPayload :: Lens' CaptionsInsert Caption
ciPayload
= lens _ciPayload (\ s a -> s{_ciPayload = a})
-- | *Note:* This parameter is intended exclusively for YouTube content
-- partners. The *onBehalfOfContentOwner* parameter indicates that the
-- request\'s authorization credentials identify a YouTube CMS user who is
-- acting on behalf of the content owner specified in the parameter value.
-- This parameter is intended for YouTube content partners that own and
-- manage many different YouTube channels. It allows content owners to
-- authenticate once and get access to all their video and channel data,
-- without having to provide authentication credentials for each individual
-- channel. The actual CMS account that the user authenticates with must be
-- linked to the specified YouTube content owner.
ciOnBehalfOfContentOwner :: Lens' CaptionsInsert (Maybe Text)
ciOnBehalfOfContentOwner
= lens _ciOnBehalfOfContentOwner
(\ s a -> s{_ciOnBehalfOfContentOwner = a})
-- | Extra parameter to allow automatically syncing the uploaded
-- caption\/transcript with the audio.
ciSync :: Lens' CaptionsInsert (Maybe Bool)
ciSync = lens _ciSync (\ s a -> s{_ciSync = a})
-- | JSONP
ciCallback :: Lens' CaptionsInsert (Maybe Text)
ciCallback
= lens _ciCallback (\ s a -> s{_ciCallback = a})
instance GoogleRequest CaptionsInsert where
type Rs CaptionsInsert = Caption
type Scopes CaptionsInsert =
'["https://www.googleapis.com/auth/youtube.force-ssl",
"https://www.googleapis.com/auth/youtubepartner"]
requestClient CaptionsInsert'{..}
= go _ciPart _ciOnBehalfOf _ciXgafv _ciUploadProtocol
_ciAccessToken
_ciUploadType
_ciOnBehalfOfContentOwner
_ciSync
_ciCallback
(Just AltJSON)
_ciPayload
youTubeService
where go :<|> _
= buildClient (Proxy :: Proxy CaptionsInsertResource)
mempty
instance GoogleRequest (MediaUpload CaptionsInsert)
where
type Rs (MediaUpload CaptionsInsert) = Caption
type Scopes (MediaUpload CaptionsInsert) =
Scopes CaptionsInsert
requestClient (MediaUpload CaptionsInsert'{..} body)
= go _ciPart _ciOnBehalfOf _ciXgafv _ciUploadProtocol
_ciAccessToken
_ciUploadType
_ciOnBehalfOfContentOwner
_ciSync
_ciCallback
(Just AltJSON)
(Just Multipart)
_ciPayload
body
youTubeService
where _ :<|> go
= buildClient (Proxy :: Proxy CaptionsInsertResource)
mempty
|
brendanhay/gogol
|
gogol-youtube/gen/Network/Google/Resource/YouTube/Captions/Insert.hs
|
mpl-2.0
| 8,376
| 0
| 38
| 2,365
| 1,338
| 750
| 588
| 179
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AndroidPublisher.Edits.Images.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes the image (specified by id) from the edit.
--
-- /See:/ <https://developers.google.com/android-publisher Google Play Android Developer API Reference> for @androidpublisher.edits.images.delete@.
module Network.Google.Resource.AndroidPublisher.Edits.Images.Delete
(
-- * REST Resource
EditsImagesDeleteResource
-- * Creating a Request
, editsImagesDelete
, EditsImagesDelete
-- * Request Lenses
, eidXgafv
, eidUploadProtocol
, eidPackageName
, eidAccessToken
, eidUploadType
, eidImageType
, eidImageId
, eidLanguage
, eidEditId
, eidCallback
) where
import Network.Google.AndroidPublisher.Types
import Network.Google.Prelude
-- | A resource alias for @androidpublisher.edits.images.delete@ method which the
-- 'EditsImagesDelete' request conforms to.
type EditsImagesDeleteResource =
"androidpublisher" :>
"v3" :>
"applications" :>
Capture "packageName" Text :>
"edits" :>
Capture "editId" Text :>
"listings" :>
Capture "language" Text :>
Capture "imageType" EditsImagesDeleteImageType :>
Capture "imageId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Deletes the image (specified by id) from the edit.
--
-- /See:/ 'editsImagesDelete' smart constructor.
data EditsImagesDelete =
EditsImagesDelete'
{ _eidXgafv :: !(Maybe Xgafv)
, _eidUploadProtocol :: !(Maybe Text)
, _eidPackageName :: !Text
, _eidAccessToken :: !(Maybe Text)
, _eidUploadType :: !(Maybe Text)
, _eidImageType :: !EditsImagesDeleteImageType
, _eidImageId :: !Text
, _eidLanguage :: !Text
, _eidEditId :: !Text
, _eidCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EditsImagesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eidXgafv'
--
-- * 'eidUploadProtocol'
--
-- * 'eidPackageName'
--
-- * 'eidAccessToken'
--
-- * 'eidUploadType'
--
-- * 'eidImageType'
--
-- * 'eidImageId'
--
-- * 'eidLanguage'
--
-- * 'eidEditId'
--
-- * 'eidCallback'
editsImagesDelete
:: Text -- ^ 'eidPackageName'
-> EditsImagesDeleteImageType -- ^ 'eidImageType'
-> Text -- ^ 'eidImageId'
-> Text -- ^ 'eidLanguage'
-> Text -- ^ 'eidEditId'
-> EditsImagesDelete
editsImagesDelete pEidPackageName_ pEidImageType_ pEidImageId_ pEidLanguage_ pEidEditId_ =
EditsImagesDelete'
{ _eidXgafv = Nothing
, _eidUploadProtocol = Nothing
, _eidPackageName = pEidPackageName_
, _eidAccessToken = Nothing
, _eidUploadType = Nothing
, _eidImageType = pEidImageType_
, _eidImageId = pEidImageId_
, _eidLanguage = pEidLanguage_
, _eidEditId = pEidEditId_
, _eidCallback = Nothing
}
-- | V1 error format.
eidXgafv :: Lens' EditsImagesDelete (Maybe Xgafv)
eidXgafv = lens _eidXgafv (\ s a -> s{_eidXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
eidUploadProtocol :: Lens' EditsImagesDelete (Maybe Text)
eidUploadProtocol
= lens _eidUploadProtocol
(\ s a -> s{_eidUploadProtocol = a})
-- | Package name of the app.
eidPackageName :: Lens' EditsImagesDelete Text
eidPackageName
= lens _eidPackageName
(\ s a -> s{_eidPackageName = a})
-- | OAuth access token.
eidAccessToken :: Lens' EditsImagesDelete (Maybe Text)
eidAccessToken
= lens _eidAccessToken
(\ s a -> s{_eidAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
eidUploadType :: Lens' EditsImagesDelete (Maybe Text)
eidUploadType
= lens _eidUploadType
(\ s a -> s{_eidUploadType = a})
-- | Type of the Image.
eidImageType :: Lens' EditsImagesDelete EditsImagesDeleteImageType
eidImageType
= lens _eidImageType (\ s a -> s{_eidImageType = a})
-- | Unique identifier an image within the set of images attached to this
-- edit.
eidImageId :: Lens' EditsImagesDelete Text
eidImageId
= lens _eidImageId (\ s a -> s{_eidImageId = a})
-- | Language localization code (a BCP-47 language tag; for example,
-- \"de-AT\" for Austrian German).
eidLanguage :: Lens' EditsImagesDelete Text
eidLanguage
= lens _eidLanguage (\ s a -> s{_eidLanguage = a})
-- | Identifier of the edit.
eidEditId :: Lens' EditsImagesDelete Text
eidEditId
= lens _eidEditId (\ s a -> s{_eidEditId = a})
-- | JSONP
eidCallback :: Lens' EditsImagesDelete (Maybe Text)
eidCallback
= lens _eidCallback (\ s a -> s{_eidCallback = a})
instance GoogleRequest EditsImagesDelete where
type Rs EditsImagesDelete = ()
type Scopes EditsImagesDelete =
'["https://www.googleapis.com/auth/androidpublisher"]
requestClient EditsImagesDelete'{..}
= go _eidPackageName _eidEditId _eidLanguage
_eidImageType
_eidImageId
_eidXgafv
_eidUploadProtocol
_eidAccessToken
_eidUploadType
_eidCallback
(Just AltJSON)
androidPublisherService
where go
= buildClient
(Proxy :: Proxy EditsImagesDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-android-publisher/gen/Network/Google/Resource/AndroidPublisher/Edits/Images/Delete.hs
|
mpl-2.0
| 6,430
| 0
| 23
| 1,611
| 1,017
| 590
| 427
| 150
| 1
|
module Problems001to010 where
import Data.Char
import Data.List
import Util
-- If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
-- The sum of these multiples is 23.
-- Find the sum of all the multiples of 3 or 5 below 1000.
problem001 :: String
problem001 = show . sum $ multiplesof3or5upto1000
where
multiplesof3or5upto1000 = [x | x <- [1..999], isMultiple x]
isMultiple x = x `mod` 3 == 0 || x `mod ` 5 == 0
-- Each new term in the Fibonacci sequence is generated by adding the previous two terms.
-- By starting with 1 and 2, the first 10 terms will be:
-- 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
-- By considering the terms in the Fibonacci sequence whose values do not exceed four million,
-- find the sum of the even-valued terms.
problem002 :: String
problem002 = show . sum $ evenFibNumbersBelow4Mio
where
evenFibNumbersBelow4Mio = filter even fibBelow4Mio
fibBelow4Mio = takeWhile under4Mio fibonacci
under4Mio n = n < 4000000
-- The prime factors of 13195 are 5, 7, 13 and 29.
-- What is the largest prime factor of the number 600851475143 ?
problem003 :: String
problem003 = show . last $ primeFactors 600851475143
-- A palindromic number reads the same both ways.
-- The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
-- Find the largest palindrome made from the product of two 3-digit numbers.
problem004 :: String
problem004 = show . maximum $ palindromes
where
palindromes = [n | x <- [100..999], y <- [100..999], let n = x*y, isPalindrome n]
isPalindrome number = let s = show number in s == reverse s
-- 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
-- What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
problem005 :: String
problem005 = show $ foldl lcm 1 [11..20]
-- The sum of the squares of the first ten natural numbers is,
-- 1^2 + 2^2 + ... + 10^2 = 385
-- The square of the sum of the first ten natural numbers is,
-- (1 + 2 + ... + 10)^2 = 55^2 = 3025
-- Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640.
-- Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
problem006 :: String
problem006 = show (squareOfSum numbers - sumOfSquares numbers)
where
numbers = [1..100]
sumOfSquares ns = sum (map square ns)
squareOfSum ns = square . sum $ ns
square x = x ^ 2
-- By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
-- What is the 10 001st prime number?
problem007 :: String
problem007 = show $ primes [2..] !! 10000
-- Find the greatest product of five consecutive digits in the 1000-digit number.
-- 73167176531330624919225119674426574742355349194934
-- 96983520312774506326239578318016984801869478851843
-- 85861560789112949495459501737958331952853208805511
-- 12540698747158523863050715693290963295227443043557
-- 66896648950445244523161731856403098711121722383113
-- 62229893423380308135336276614282806444486645238749
-- 30358907296290491560440772390713810515859307960866
-- 70172427121883998797908792274921901699720888093776
-- 65727333001053367881220235421809751254540594752243
-- 52584907711670556013604839586446706324415722155397
-- 53697817977846174064955149290862569321978468622482
-- 83972241375657056057490261407972968652414535100474
-- 82166370484403199890008895243450658541227588666881
-- 16427171479924442928230863465674813919123162824586
-- 17866458359124566529476545682848912883142607690042
-- 24219022671055626321111109370544217506941658960408
-- 07198403850962455444362981230987879927244284909188
-- 84580156166097919133875499200524063689912560717606
-- 05886116467109405077541002256983155200055935729725
-- 71636269561882670428252483600823257530420752963450
problem008 :: String
problem008 = show . maximum $ products
where
products = map (product . convert . take 5) extract
convert = map digitToInt
extract = tails dataString
dataString =
"7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843"
++ "8586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557"
++ "6689664895044524452316173185640309871112172238311362229893423380308135336276614282806444486645238749"
++ "3035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776"
++ "6572733300105336788122023542180975125454059475224352584907711670556013604839586446706324415722155397"
++ "5369781797784617406495514929086256932197846862248283972241375657056057490261407972968652414535100474"
++ "8216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586"
++ "1786645835912456652947654568284891288314260769004224219022671055626321111109370544217506941658960408"
++ "0719840385096245544436298123098787992724428490918884580156166097919133875499200524063689912560717606"
++ "0588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
-- A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
-- a^2 + b^2 = c^2
-- For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
-- There exists exactly one Pythagorean triplet for which a + b + c = 1000.
-- Find the product abc.
problem009 :: String
problem009 = show . head $ [a*b*c | a<-[1..333], b<-[1..500], let c = 1000 - a - b, a*a + b*b == c*c]
-- The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
-- Find the sum of all the primes below two million.
problem010 :: String
problem010 = show . sum $ primesUpTo 2000000
|
wey/projecteuler
|
Haskell/ProjectEuler/src/Problems001to010.hs
|
unlicense
| 6,005
| 0
| 15
| 1,081
| 679
| 381
| 298
| 49
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Gtd.RDF where
import Control.Applicative
import Data.Char (toLower)
import Data.List (foldl')
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Time
import Network.URI
import Swish.Namespace
import Swish.QName
import Swish.RDF.Graph
import Swish.RDF.Vocabulary.RDF
import Swish.RDF.Vocabulary.XSD
import Text.Printf
import Gtd.Types
todoToTriples :: NamespaceMap
-> Integer
-> (Int, RDFArcSet)
-> TodoItem
-> (Int, RDFArcSet)
todoToTriples nss year (n, arcs) Todo{..} = (n + 1, arcs')
where dtime = doneTime todoStatus
s = M.lookup (Just "s") nss
upri = M.lookup (Just "pri") nss
gtdName = makeName nss "gtd"
item = makeStringName nss "todo" $ printf "item%04d" n
titem = gtdName "todoitem"
tstatus = gtdName "status"
turl = gtdName "itemurl"
tpri = gtdName "priority"
tdone = gtdName "donedate"
ddate = gtdName "duedate"
ctx = gtdName "context"
proj = gtdName "project"
prog = gtdName "progress"
progD = gtdName "progressDone"
progE = gtdName "progressEstimate"
insert' = flip maybeInsert
arcs' = insert' (flip toRDFTriple rdfType <$> item <*> titem)
. insert' (flip labelRdf todoLabel <$> item)
. insert' (statusRdf <$> tstatus <*> s <*> pure (localStatus todoStatus) <*> item)
. insert' (priRdf <$> item <*> tpri <*> upri <*> localPri todoStatus)
. insert' (toRDFTriple <$> item <*> turl <*> todoUri)
. insert' (toRDFTriple <$> item <*> tdone <*> dtime)
. insert' (toRDFTriple <$> item <*> ddate <*> fmap (dueDate year dtime) todoDate)
. insert' (toRDFTriple <$> item <*> proj <*> (makeTextName nss "p" =<< todoProject))
. flip (foldl' maybeInsert) (progressRdf item n prog progD progE todoProgress)
$ foldl' maybeInsert arcs [ toRDFTriple <$> item <*> ctx <*> makeTextName nss "c" context
| context <- todoContexts
]
progressRdf :: Maybe ScopedName -> Int -> Maybe ScopedName -> Maybe ScopedName
-> Maybe ScopedName -> Maybe Progress -> [Maybe RDFTriple]
progressRdf _ _ _ _ _ Nothing = []
progressRdf item n prog progD progE (Just (Progress done estimate)) =
[ toRDFTriple <$> item <*> prog <*> pure parent
, toRDFTriple parent <$> progD <*> done
, flip (toRDFTriple parent) estimate <$> progE
]
where parent = Blank $ show n ++ "progress"
quickGraph :: NamespaceMap -> RDFArcSet -> RDFGraph
quickGraph nss arcs = emptyRDFGraph { namespaces = nss
, statements = arcs
}
makeNamespaces :: URI -> NamespaceMap
makeNamespaces prefix = M.fromList [ (Just "gtd", extendPath prefix "/gtd#")
, (Just "todo", extendPath prefix "/todo#")
, (Just "p", extendPath prefix "/project#")
, (Just "c", extendPath prefix "/context#")
, (Just "s", extendPath prefix "/status#")
, (Just "pri", extendPath prefix "/priority#")
, getNamespaceTuple namespaceRDF
, getNamespaceTuple namespaceRDFS
, getNamespaceTuple namespaceXSD
]
makeName :: NamespaceMap -> T.Text -> LName -> Maybe ScopedName
makeName nss pre lname = flip (makeScopedName mpre) lname <$> M.lookup mpre nss
where mpre = Just pre
makeTextName :: NamespaceMap -> T.Text -> T.Text -> Maybe ScopedName
makeTextName nss pre tname = newLName tname >>= makeName nss pre
makeStringName :: NamespaceMap -> T.Text -> String -> Maybe ScopedName
makeStringName nss pre = makeTextName nss pre . T.pack
todoListToGraph :: URI -> Integer -> Int -> [TodoItem] -> RDFGraph
todoListToGraph prefix year n =
quickGraph nss
. snd
. foldl' (todoToTriples nss year) (n, S.empty)
where nss = makeNamespaces prefix
maybeInsert :: Ord a => S.Set a -> Maybe a -> S.Set a
maybeInsert s (Just a) = S.insert a s
maybeInsert s Nothing = s
-- | RDF Stuff
instance ToRDFLabel T.Text where
toRDFLabel = toRDFLabel . T.unpack
localPri :: TodoStatus -> Maybe LName
localPri (Active (Just p)) = newLName . T.singleton $ toLower p
localPri _ = Nothing
priRdf :: (ToRDFLabel s) => s -> ScopedName -> URI -> LName -> RDFTriple
priRdf s p tpri = toRDFTriple s p . makeScopedName (Just "pri") tpri
extendPath :: URI -> String -> URI
extendPath u@URI{..} p = u { uriPath = uriPath ++ p }
localStatus :: TodoStatus -> LName
localStatus (Active _) = "active"
localStatus Pending = "pending"
localStatus (Gtd.Types.Done _) = "done"
localStatus (Archived _) = "archived"
statusRdf :: ToRDFLabel a => ScopedName -> URI -> LName -> a -> RDFTriple
statusRdf gtd p lname s = toRDFTriple s gtd $ makeScopedName (Just "s") p lname
labelRdf :: ToRDFLabel a => a -> T.Text -> RDFTriple
labelRdf item = toRDFTriple item rdfsLabel . Lit
doneTime :: TodoStatus -> Maybe UTCTime
doneTime (Gtd.Types.Done t) = Just t
doneTime (Archived t) = Just t
doneTime (Active _) = Nothing
doneTime Pending = Nothing
dueDate :: Integer -> Maybe UTCTime -> MonthDay -> Day
dueDate year doneDate (month, day) =
fromGregorian (maybe year getYear doneDate) month day
fst3 :: (a, b, c) -> a
fst3 (x, _, _) = x
getYear :: UTCTime -> Integer
getYear = fst3 . toGregorian . utctDay
|
erochest/todotxt
|
Gtd/RDF.hs
|
apache-2.0
| 6,095
| 0
| 21
| 1,986
| 1,818
| 934
| 884
| 119
| 1
|
{-# OPTIONS_GHC -Wall -fno-warn-name-shadowing #-}
module Database.Narc.Test where
import Prelude hiding (catch)
import Test.QuickCheck hiding (promote, Failure, Success)
import Test.HUnit hiding (State, assert)
import QCUtils
import Numeric.Unary
import Database.Narc.AST
import Database.Narc.Compile
import Database.Narc.Fallible
import qualified Database.Narc.SQL as SQL
import Database.Narc.Type as Type
import Database.Narc.TypeInfer
import Database.Narc.TermGen
normalizerTests :: Test
normalizerTests =
TestList [
TestCase $ unitAssert $
-- TBD: use builders here.
let term = (Comp "x" (Table "foo" [("fop", TNum)], ())
(If (Bool True,())
(Singleton (Record
[("f0", (Project (Var "x", ())
"fop",()))],()),())
(Singleton (Record
[("f0", (Num 3, ()))], ()), ()),
()), ()) in
let typedTerm = runFallibleGensym $ infer $ term in
(1::Integer) < (SQL.sizeQuery $ compile [] $ typedTerm)
]
unitTests :: Test
unitTests = TestList [tyCheckTests, normalizerTests, typingTest]
runUnitTests :: IO Counts
runUnitTests = runTestTT $ unitTests
--
-- Big QuickCheck properties
--
-- | Assertion that well-typed terms compile without throwing.
prop_compile_safe :: Property
prop_compile_safe =
forAll dbTableTypeGen $ \ty ->
forAll (sized (closedTypedTermGen ty)) $ \m ->
case tryFallibleGensym (infer m) of
Failure _ -> label "ill-typed" $ property True -- ignore ill-typed terms
-- but report their occurence.
Success (m'@(_, ty)) ->
classify (isDBTableTy ty) "Flat relation type" $
let q = (compile [] $! m') in
collect (min 100 (SQL.sizeQuery q::Unary)) $ -- NB: Counts sizes only up to ~100.
excAsFalse (q == q) -- Self-comparison forces the
-- value (?) thus surfacing
-- any @error@s that might be
-- raised.
prop_typedTermGen_tyCheck :: Property
prop_typedTermGen_tyCheck =
forAll (sized $ typeGen []) $ \ty ->
forAll (sized $ typedTermGen [] ty) $ \m ->
case tryFallibleGensym $ infer m of
Failure _ -> False
Success (_m', ty') -> isSuccess $ unify ty ty'
-- Main ----------------------------------------------------------------
main :: IO ()
main = do
quickCheckWith tinyArgs prop_typedTermGen_tyCheck
quickCheckWith tinyArgs prop_compile_safe
_ <- runUnitTests
return ()
|
ezrakilty/narc
|
Database/Narc/Test.hs
|
bsd-2-clause
| 2,708
| 0
| 25
| 836
| 720
| 395
| 325
| 56
| 2
|
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings
( widgetFile
, staticRoot
, staticDir
, Extra (..)
, parseExtra
) where
import Prelude
import Text.Shakespeare.Text (st)
import Language.Haskell.TH.Syntax
import Yesod.Default.Config
import Yesod.Default.Util
import Data.Text (Text)
import Data.Yaml
import Control.Applicative
import Settings.Development
import Data.Default(def)
import Text.Hamlet
-- Static setting below. Changing these requires a recompile
-- | The location of static files on your system. This is a file system
-- path. The default value works properly with your scaffolded site.
staticDir :: FilePath
staticDir = "static"
-- | The base URL for your static files. As you can see by the default
-- value, this can simply be "static" appended to your application root.
-- A powerful optimization can be serving static files from a separate
-- domain name. This allows you to use a web server optimized for static
-- files, more easily set expires and cache values, and avoid possibly
-- costly transference of cookies on static files. For more information,
-- please see:
-- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain
--
-- If you change the resource pattern for StaticR in Foundation.hs, you will
-- have to make a corresponding change here.
--
-- To see how this value is used, see urlRenderOverride in Foundation.hs
staticRoot :: AppConfig DefaultEnv x -> Text
staticRoot conf = [st|#{appRoot conf}/static|]
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def
{ wfsHamletSettings = defaultHamletSettings
{ hamletNewlines = AlwaysNewlines
}
}
-- The rest of this file contains settings which rarely need changing by a
-- user.
widgetFile :: String -> Q Exp
widgetFile = (if development then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
data Extra = Extra
{ extraCopyright :: Text
, extraAnalytics :: Maybe Text -- ^ Google Analytics
} deriving Show
parseExtra :: DefaultEnv -> Object -> Parser Extra
parseExtra _ o = Extra
<$> o .: "copyright"
<*> o .:? "analytics"
|
kmels/tersus
|
Settings.hs
|
bsd-2-clause
| 2,609
| 0
| 9
| 522
| 286
| 180
| 106
| -1
| -1
|
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Config
-- Copyright : (c) David Himmelstrup 2005
-- License : BSD-like
--
-- Maintainer : lemmih@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- Utilities for handling saved state such as known packages, known servers and
-- downloaded packages.
-----------------------------------------------------------------------------
module Distribution.Client.Config (
SavedConfig(..),
loadConfig,
showConfig,
showConfigWithComments,
parseConfig,
defaultCabalDir,
defaultConfigFile,
defaultCacheDir,
defaultCompiler,
defaultLogsDir,
defaultUserInstall,
baseSavedConfig,
commentSavedConfig,
initialSavedConfig,
configFieldDescriptions,
haddockFlagsFields,
installDirsFields,
withProgramsFields,
withProgramOptionsFields,
userConfigDiff,
userConfigUpdate
) where
import Distribution.Client.Types
( RemoteRepo(..), Username(..), Password(..), emptyRemoteRepo )
import Distribution.Client.BuildReports.Types
( ReportLevel(..) )
import Distribution.Client.Dependency.Types
( ConstraintSource(..) )
import Distribution.Client.Setup
( GlobalFlags(..), globalCommand, defaultGlobalFlags
, ConfigExFlags(..), configureExOptions, defaultConfigExFlags
, InstallFlags(..), installOptions, defaultInstallFlags
, UploadFlags(..), uploadCommand
, ReportFlags(..), reportCommand
, showRepo, parseRepo, readRepo )
import Distribution.Utils.NubList
( NubList, fromNubList, toNubList)
import Distribution.Simple.Compiler
( DebugInfoLevel(..), OptimisationLevel(..) )
import Distribution.Simple.Setup
( ConfigFlags(..), configureOptions, defaultConfigFlags
, HaddockFlags(..), haddockOptions, defaultHaddockFlags
, installDirsOptions, optionDistPref
, programConfigurationPaths', programConfigurationOptions
, Flag(..), toFlag, flagToMaybe, fromFlagOrDefault )
import Distribution.Simple.InstallDirs
( InstallDirs(..), defaultInstallDirs
, PathTemplate, toPathTemplate )
import Distribution.ParseUtils
( FieldDescr(..), liftField
, ParseResult(..), PError(..), PWarning(..)
, locatedErrorMsg, showPWarning
, readFields, warning, lineNo
, simpleField, listField, boolField, spaceListField
, parseFilePathQ, parseTokenQ )
import Distribution.Client.ParseUtils
( parseFields, ppFields, ppSection )
import Distribution.Client.HttpUtils
( isOldHackageURI )
import qualified Distribution.ParseUtils as ParseUtils
( Field(..) )
import qualified Distribution.Text as Text
( Text(..) )
import Distribution.Simple.Command
( CommandUI(commandOptions), commandDefaultFlags, ShowOrParseArgs(..)
, viewAsFieldDescr )
import Distribution.Simple.Program
( defaultProgramConfiguration )
import Distribution.Simple.Utils
( die, notice, warn, lowercase, cabalVersion )
import Distribution.Compiler
( CompilerFlavor(..), defaultCompilerFlavor )
import Distribution.Verbosity
( Verbosity, normal )
import Data.List
( partition, find, foldl' )
import Data.Maybe
( fromMaybe )
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid
( Monoid(..) )
#endif
import Control.Monad
( when, unless, foldM, liftM, liftM2 )
import qualified Distribution.Compat.ReadP as Parse
( option )
import qualified Text.PrettyPrint as Disp
( render, text, empty )
import Text.PrettyPrint
( ($+$) )
import Text.PrettyPrint.HughesPJ
( text, Doc )
import System.Directory
( createDirectoryIfMissing, getAppUserDataDirectory, renameFile )
import Network.URI
( URI(..), URIAuth(..), parseURI )
import System.FilePath
( (<.>), (</>), takeDirectory )
import System.IO.Error
( isDoesNotExistError )
import Distribution.Compat.Environment
( getEnvironment )
import Distribution.Compat.Exception
( catchIO )
import qualified Paths_cabal_install
( version )
import Data.Version
( showVersion )
import Data.Char
( isSpace )
import qualified Data.Map as M
import Data.Function
( on )
import Data.List
( nubBy )
--
-- * Configuration saved in the config file
--
data SavedConfig = SavedConfig {
savedGlobalFlags :: GlobalFlags,
savedInstallFlags :: InstallFlags,
savedConfigureFlags :: ConfigFlags,
savedConfigureExFlags :: ConfigExFlags,
savedUserInstallDirs :: InstallDirs (Flag PathTemplate),
savedGlobalInstallDirs :: InstallDirs (Flag PathTemplate),
savedUploadFlags :: UploadFlags,
savedReportFlags :: ReportFlags,
savedHaddockFlags :: HaddockFlags
}
instance Monoid SavedConfig where
mempty = SavedConfig {
savedGlobalFlags = mempty,
savedInstallFlags = mempty,
savedConfigureFlags = mempty,
savedConfigureExFlags = mempty,
savedUserInstallDirs = mempty,
savedGlobalInstallDirs = mempty,
savedUploadFlags = mempty,
savedReportFlags = mempty,
savedHaddockFlags = mempty
}
mappend a b = SavedConfig {
savedGlobalFlags = combinedSavedGlobalFlags,
savedInstallFlags = combinedSavedInstallFlags,
savedConfigureFlags = combinedSavedConfigureFlags,
savedConfigureExFlags = combinedSavedConfigureExFlags,
savedUserInstallDirs = combinedSavedUserInstallDirs,
savedGlobalInstallDirs = combinedSavedGlobalInstallDirs,
savedUploadFlags = combinedSavedUploadFlags,
savedReportFlags = combinedSavedReportFlags,
savedHaddockFlags = combinedSavedHaddockFlags
}
where
-- This is ugly, but necessary. If we're mappending two config files, we
-- want the values of the *non-empty* list fields from the second one to
-- *override* the corresponding values from the first one. Default
-- behaviour (concatenation) is confusing and makes some use cases (see
-- #1884) impossible.
--
-- However, we also want to allow specifying multiple values for a list
-- field in a *single* config file. For example, we want the following to
-- continue to work:
--
-- remote-repo: hackage.haskell.org:http://hackage.haskell.org/
-- remote-repo: private-collection:http://hackage.local/
--
-- So we can't just wrap the list fields inside Flags; we have to do some
-- special-casing just for SavedConfig.
-- NB: the signature prevents us from using 'combine' on lists.
combine' :: (SavedConfig -> flags) -> (flags -> Flag a) -> Flag a
combine' field subfield =
(subfield . field $ a) `mappend` (subfield . field $ b)
lastNonEmpty' :: (SavedConfig -> flags) -> (flags -> [a]) -> [a]
lastNonEmpty' field subfield =
let a' = subfield . field $ a
b' = subfield . field $ b
in case b' of [] -> a'
_ -> b'
lastNonEmptyNL' :: (SavedConfig -> flags) -> (flags -> NubList a)
-> NubList a
lastNonEmptyNL' field subfield =
let a' = subfield . field $ a
b' = subfield . field $ b
in case fromNubList b' of [] -> a'
_ -> b'
combinedSavedGlobalFlags = GlobalFlags {
globalVersion = combine globalVersion,
globalNumericVersion = combine globalNumericVersion,
globalConfigFile = combine globalConfigFile,
globalSandboxConfigFile = combine globalSandboxConfigFile,
globalConstraintsFile = combine globalConstraintsFile,
globalRemoteRepos = lastNonEmptyNL globalRemoteRepos,
globalCacheDir = combine globalCacheDir,
globalLocalRepos = lastNonEmptyNL globalLocalRepos,
globalLogsDir = combine globalLogsDir,
globalWorldFile = combine globalWorldFile,
globalRequireSandbox = combine globalRequireSandbox,
globalIgnoreSandbox = combine globalIgnoreSandbox,
globalIgnoreExpiry = combine globalIgnoreExpiry,
globalHttpTransport = combine globalHttpTransport
}
where
combine = combine' savedGlobalFlags
lastNonEmptyNL = lastNonEmptyNL' savedGlobalFlags
combinedSavedInstallFlags = InstallFlags {
installDocumentation = combine installDocumentation,
installHaddockIndex = combine installHaddockIndex,
installDryRun = combine installDryRun,
installMaxBackjumps = combine installMaxBackjumps,
installReorderGoals = combine installReorderGoals,
installIndependentGoals = combine installIndependentGoals,
installShadowPkgs = combine installShadowPkgs,
installStrongFlags = combine installStrongFlags,
installReinstall = combine installReinstall,
installAvoidReinstalls = combine installAvoidReinstalls,
installOverrideReinstall = combine installOverrideReinstall,
installUpgradeDeps = combine installUpgradeDeps,
installOnly = combine installOnly,
installOnlyDeps = combine installOnlyDeps,
installRootCmd = combine installRootCmd,
installSummaryFile = lastNonEmptyNL installSummaryFile,
installLogFile = combine installLogFile,
installBuildReports = combine installBuildReports,
installReportPlanningFailure = combine installReportPlanningFailure,
installSymlinkBinDir = combine installSymlinkBinDir,
installOneShot = combine installOneShot,
installNumJobs = combine installNumJobs,
installRunTests = combine installRunTests,
installOfflineMode = combine installOfflineMode
}
where
combine = combine' savedInstallFlags
lastNonEmptyNL = lastNonEmptyNL' savedInstallFlags
combinedSavedConfigureFlags = ConfigFlags {
configPrograms = configPrograms . savedConfigureFlags $ b,
-- TODO: NubListify
configProgramPaths = lastNonEmpty configProgramPaths,
-- TODO: NubListify
configProgramArgs = lastNonEmpty configProgramArgs,
configProgramPathExtra = lastNonEmptyNL configProgramPathExtra,
configHcFlavor = combine configHcFlavor,
configHcPath = combine configHcPath,
configHcPkg = combine configHcPkg,
configVanillaLib = combine configVanillaLib,
configProfLib = combine configProfLib,
configProf = combine configProf,
configSharedLib = combine configSharedLib,
configDynExe = combine configDynExe,
configProfExe = combine configProfExe,
configProfDetail = combine configProfDetail,
configProfLibDetail = combine configProfLibDetail,
-- TODO: NubListify
configConfigureArgs = lastNonEmpty configConfigureArgs,
configOptimization = combine configOptimization,
configDebugInfo = combine configDebugInfo,
configProgPrefix = combine configProgPrefix,
configProgSuffix = combine configProgSuffix,
-- Parametrised by (Flag PathTemplate), so safe to use 'mappend'.
configInstallDirs =
(configInstallDirs . savedConfigureFlags $ a)
`mappend` (configInstallDirs . savedConfigureFlags $ b),
configScratchDir = combine configScratchDir,
-- TODO: NubListify
configExtraLibDirs = lastNonEmpty configExtraLibDirs,
-- TODO: NubListify
configExtraIncludeDirs = lastNonEmpty configExtraIncludeDirs,
configIPID = combine configIPID,
configDistPref = combine configDistPref,
configVerbosity = combine configVerbosity,
configUserInstall = combine configUserInstall,
-- TODO: NubListify
configPackageDBs = lastNonEmpty configPackageDBs,
configGHCiLib = combine configGHCiLib,
configSplitObjs = combine configSplitObjs,
configStripExes = combine configStripExes,
configStripLibs = combine configStripLibs,
-- TODO: NubListify
configConstraints = lastNonEmpty configConstraints,
-- TODO: NubListify
configDependencies = lastNonEmpty configDependencies,
configInstantiateWith = lastNonEmpty configInstantiateWith,
-- TODO: NubListify
configConfigurationsFlags = lastNonEmpty configConfigurationsFlags,
configTests = combine configTests,
configBenchmarks = combine configBenchmarks,
configCoverage = combine configCoverage,
configLibCoverage = combine configLibCoverage,
configExactConfiguration = combine configExactConfiguration,
configFlagError = combine configFlagError,
configRelocatable = combine configRelocatable
}
where
combine = combine' savedConfigureFlags
lastNonEmpty = lastNonEmpty' savedConfigureFlags
lastNonEmptyNL = lastNonEmptyNL' savedConfigureFlags
combinedSavedConfigureExFlags = ConfigExFlags {
configCabalVersion = combine configCabalVersion,
-- TODO: NubListify
configExConstraints = lastNonEmpty configExConstraints,
-- TODO: NubListify
configPreferences = lastNonEmpty configPreferences,
configSolver = combine configSolver,
configAllowNewer = combine configAllowNewer
}
where
combine = combine' savedConfigureExFlags
lastNonEmpty = lastNonEmpty' savedConfigureExFlags
-- Parametrised by (Flag PathTemplate), so safe to use 'mappend'.
combinedSavedUserInstallDirs = savedUserInstallDirs a
`mappend` savedUserInstallDirs b
-- Parametrised by (Flag PathTemplate), so safe to use 'mappend'.
combinedSavedGlobalInstallDirs = savedGlobalInstallDirs a
`mappend` savedGlobalInstallDirs b
combinedSavedUploadFlags = UploadFlags {
uploadCheck = combine uploadCheck,
uploadDoc = combine uploadDoc,
uploadUsername = combine uploadUsername,
uploadPassword = combine uploadPassword,
uploadPasswordCmd = combine uploadPasswordCmd,
uploadVerbosity = combine uploadVerbosity
}
where
combine = combine' savedUploadFlags
combinedSavedReportFlags = ReportFlags {
reportUsername = combine reportUsername,
reportPassword = combine reportPassword,
reportVerbosity = combine reportVerbosity
}
where
combine = combine' savedReportFlags
combinedSavedHaddockFlags = HaddockFlags {
-- TODO: NubListify
haddockProgramPaths = lastNonEmpty haddockProgramPaths,
-- TODO: NubListify
haddockProgramArgs = lastNonEmpty haddockProgramArgs,
haddockHoogle = combine haddockHoogle,
haddockHtml = combine haddockHtml,
haddockHtmlLocation = combine haddockHtmlLocation,
haddockForHackage = combine haddockForHackage,
haddockExecutables = combine haddockExecutables,
haddockTestSuites = combine haddockTestSuites,
haddockBenchmarks = combine haddockBenchmarks,
haddockInternal = combine haddockInternal,
haddockCss = combine haddockCss,
haddockHscolour = combine haddockHscolour,
haddockHscolourCss = combine haddockHscolourCss,
haddockContents = combine haddockContents,
haddockDistPref = combine haddockDistPref,
haddockKeepTempFiles = combine haddockKeepTempFiles,
haddockVerbosity = combine haddockVerbosity
}
where
combine = combine' savedHaddockFlags
lastNonEmpty = lastNonEmpty' savedHaddockFlags
--
-- * Default config
--
-- | These are the absolute basic defaults. The fields that must be
-- initialised. When we load the config from the file we layer the loaded
-- values over these ones, so any missing fields in the file take their values
-- from here.
--
baseSavedConfig :: IO SavedConfig
baseSavedConfig = do
userPrefix <- defaultCabalDir
logsDir <- defaultLogsDir
worldFile <- defaultWorldFile
return mempty {
savedConfigureFlags = mempty {
configHcFlavor = toFlag defaultCompiler,
configUserInstall = toFlag defaultUserInstall,
configVerbosity = toFlag normal
},
savedUserInstallDirs = mempty {
prefix = toFlag (toPathTemplate userPrefix)
},
savedGlobalFlags = mempty {
globalLogsDir = toFlag logsDir,
globalWorldFile = toFlag worldFile
}
}
-- | This is the initial configuration that we write out to to the config file
-- if the file does not exist (or the config we use if the file cannot be read
-- for some other reason). When the config gets loaded it gets layered on top
-- of 'baseSavedConfig' so we do not need to include it into the initial
-- values we save into the config file.
--
initialSavedConfig :: IO SavedConfig
initialSavedConfig = do
cacheDir <- defaultCacheDir
logsDir <- defaultLogsDir
worldFile <- defaultWorldFile
extraPath <- defaultExtraPath
return mempty {
savedGlobalFlags = mempty {
globalCacheDir = toFlag cacheDir,
globalRemoteRepos = toNubList [addInfoForKnownRepos defaultRemoteRepo],
globalWorldFile = toFlag worldFile
},
savedConfigureFlags = mempty {
configProgramPathExtra = toNubList extraPath
},
savedInstallFlags = mempty {
installSummaryFile = toNubList [toPathTemplate (logsDir </> "build.log")],
installBuildReports= toFlag AnonymousReports,
installNumJobs = toFlag Nothing
}
}
--TODO: misleading, there's no way to override this default
-- either make it possible or rename to simply getCabalDir.
defaultCabalDir :: IO FilePath
defaultCabalDir = getAppUserDataDirectory "cabal"
defaultConfigFile :: IO FilePath
defaultConfigFile = do
dir <- defaultCabalDir
return $ dir </> "config"
defaultCacheDir :: IO FilePath
defaultCacheDir = do
dir <- defaultCabalDir
return $ dir </> "packages"
defaultLogsDir :: IO FilePath
defaultLogsDir = do
dir <- defaultCabalDir
return $ dir </> "logs"
-- | Default position of the world file
defaultWorldFile :: IO FilePath
defaultWorldFile = do
dir <- defaultCabalDir
return $ dir </> "world"
defaultExtraPath :: IO [FilePath]
defaultExtraPath = do
dir <- defaultCabalDir
return [dir </> "bin"]
defaultCompiler :: CompilerFlavor
defaultCompiler = fromMaybe GHC defaultCompilerFlavor
defaultUserInstall :: Bool
defaultUserInstall = True
-- We do per-user installs by default on all platforms. We used to default to
-- global installs on Windows but that no longer works on Windows Vista or 7.
defaultRemoteRepo :: RemoteRepo
defaultRemoteRepo = RemoteRepo name uri False [] 0 False
where
name = "hackage.haskell.org"
uri = URI "http:" (Just (URIAuth "" name "")) "/" "" ""
-- Note that lots of old ~/.cabal/config files will have the old url
-- http://hackage.haskell.org/packages/archive
-- but new config files can use the new url (without the /packages/archive)
-- and avoid having to do a http redirect
-- TODO: Once we make secure access opt-out rather than opt-in, we could
-- Use this as a source for crypto credentials when finding old remote-repo
-- entries that match repo name and url (not only be used for generating
-- fresh config files).
-- For the default repo we know extra information, fill this in.
--
-- We need this because the 'defaultRemoteRepo' above is only used for the
-- first time when a config file is made. So for users with older config files
-- we might have only have older info. This lets us fill that in even for old
-- config files.
--
addInfoForKnownRepos :: RemoteRepo -> RemoteRepo
addInfoForKnownRepos repo@RemoteRepo{ remoteRepoName = "hackage.haskell.org" } =
tryHttps $ if isOldHackageURI (remoteRepoURI repo) then defaultRemoteRepo else repo
where
tryHttps r = r { remoteRepoShouldTryHttps = True }
addInfoForKnownRepos other = other
--
-- * Config file reading
--
loadConfig :: Verbosity -> Flag FilePath -> IO SavedConfig
loadConfig verbosity configFileFlag = addBaseConf $ do
(source, configFile) <- lookupConfigFile configFileFlag
minp <- readConfigFile mempty configFile
case minp of
Nothing -> do
notice verbosity $ "Config file path source is " ++ sourceMsg source ++ "."
notice verbosity $ "Config file " ++ configFile ++ " not found."
notice verbosity $ "Writing default configuration to " ++ configFile
commentConf <- commentSavedConfig
initialConf <- initialSavedConfig
writeConfigFile configFile commentConf initialConf
return initialConf
Just (ParseOk ws conf) -> do
unless (null ws) $ warn verbosity $
unlines (map (showPWarning configFile) ws)
return conf
Just (ParseFailed err) -> do
let (line, msg) = locatedErrorMsg err
die $
"Error parsing config file " ++ configFile
++ maybe "" (\n -> ':' : show n) line ++ ":\n" ++ msg
where
addBaseConf body = do
base <- baseSavedConfig
extra <- body
return (base `mappend` extra)
sourceMsg CommandlineOption = "commandline option"
sourceMsg EnvironmentVariable = "env var CABAL_CONFIG"
sourceMsg Default = "default config file"
data ConfigFileSource = CommandlineOption
| EnvironmentVariable
| Default
lookupConfigFile :: Flag FilePath -> IO (ConfigFileSource, FilePath)
lookupConfigFile configFileFlag =
getSource sources
where
sources =
[ (CommandlineOption, return . flagToMaybe $ configFileFlag)
, (EnvironmentVariable, lookup "CABAL_CONFIG" `liftM` getEnvironment)
, (Default, Just `liftM` defaultConfigFile) ]
getSource [] = error "no config file path candidate found."
getSource ((source,action): xs) =
action >>= maybe (getSource xs) (return . (,) source)
readConfigFile :: SavedConfig -> FilePath -> IO (Maybe (ParseResult SavedConfig))
readConfigFile initial file = handleNotExists $
fmap (Just . parseConfig (ConstraintSourceMainConfig file) initial)
(readFile file)
where
handleNotExists action = catchIO action $ \ioe ->
if isDoesNotExistError ioe
then return Nothing
else ioError ioe
writeConfigFile :: FilePath -> SavedConfig -> SavedConfig -> IO ()
writeConfigFile file comments vals = do
let tmpFile = file <.> "tmp"
createDirectoryIfMissing True (takeDirectory file)
writeFile tmpFile $ explanation ++ showConfigWithComments comments vals ++ "\n"
renameFile tmpFile file
where
explanation = unlines
["-- This is the configuration file for the 'cabal' command line tool."
,""
,"-- The available configuration options are listed below."
,"-- Some of them have default values listed."
,""
,"-- Lines (like this one) beginning with '--' are comments."
,"-- Be careful with spaces and indentation because they are"
,"-- used to indicate layout for nested sections."
,""
,"-- Cabal library version: " ++ showVersion cabalVersion
,"-- cabal-install version: " ++ showVersion Paths_cabal_install.version
,"",""
]
-- | These are the default values that get used in Cabal if a no value is
-- given. We use these here to include in comments when we write out the
-- initial config file so that the user can see what default value they are
-- overriding.
--
commentSavedConfig :: IO SavedConfig
commentSavedConfig = do
userInstallDirs <- defaultInstallDirs defaultCompiler True True
globalInstallDirs <- defaultInstallDirs defaultCompiler False True
return SavedConfig {
savedGlobalFlags = defaultGlobalFlags,
savedInstallFlags = defaultInstallFlags,
savedConfigureExFlags = defaultConfigExFlags,
savedConfigureFlags = (defaultConfigFlags defaultProgramConfiguration) {
configUserInstall = toFlag defaultUserInstall
},
savedUserInstallDirs = fmap toFlag userInstallDirs,
savedGlobalInstallDirs = fmap toFlag globalInstallDirs,
savedUploadFlags = commandDefaultFlags uploadCommand,
savedReportFlags = commandDefaultFlags reportCommand,
savedHaddockFlags = defaultHaddockFlags
}
-- | All config file fields.
--
configFieldDescriptions :: ConstraintSource -> [FieldDescr SavedConfig]
configFieldDescriptions src =
toSavedConfig liftGlobalFlag
(commandOptions (globalCommand []) ParseArgs)
["version", "numeric-version", "config-file", "sandbox-config-file"] []
++ toSavedConfig liftConfigFlag
(configureOptions ParseArgs)
(["builddir", "constraint", "dependency"]
++ map fieldName installDirsFields)
--FIXME: this is only here because viewAsFieldDescr gives us a parser
-- that only recognises 'ghc' etc, the case-sensitive flag names, not
-- what the normal case-insensitive parser gives us.
[simpleField "compiler"
(fromFlagOrDefault Disp.empty . fmap Text.disp) (optional Text.parse)
configHcFlavor (\v flags -> flags { configHcFlavor = v })
-- TODO: The following is a temporary fix. The "optimization"
-- and "debug-info" fields are OptArg, and viewAsFieldDescr
-- fails on that. Instead of a hand-written hackaged parser
-- and printer, we should handle this case properly in the
-- library.
,liftField configOptimization (\v flags -> flags { configOptimization = v }) $
let name = "optimization" in
FieldDescr name
(\f -> case f of
Flag NoOptimisation -> Disp.text "False"
Flag NormalOptimisation -> Disp.text "True"
Flag MaximumOptimisation -> Disp.text "2"
_ -> Disp.empty)
(\line str _ -> case () of
_ | str == "False" -> ParseOk [] (Flag NoOptimisation)
| str == "True" -> ParseOk [] (Flag NormalOptimisation)
| str == "0" -> ParseOk [] (Flag NoOptimisation)
| str == "1" -> ParseOk [] (Flag NormalOptimisation)
| str == "2" -> ParseOk [] (Flag MaximumOptimisation)
| lstr == "false" -> ParseOk [caseWarning] (Flag NoOptimisation)
| lstr == "true" -> ParseOk [caseWarning] (Flag NormalOptimisation)
| otherwise -> ParseFailed (NoParse name line)
where
lstr = lowercase str
caseWarning = PWarning $
"The '" ++ name ++ "' field is case sensitive, use 'True' or 'False'.")
,liftField configDebugInfo (\v flags -> flags { configDebugInfo = v }) $
let name = "debug-info" in
FieldDescr name
(\f -> case f of
Flag NoDebugInfo -> Disp.text "False"
Flag MinimalDebugInfo -> Disp.text "1"
Flag NormalDebugInfo -> Disp.text "True"
Flag MaximalDebugInfo -> Disp.text "3"
_ -> Disp.empty)
(\line str _ -> case () of
_ | str == "False" -> ParseOk [] (Flag NoDebugInfo)
| str == "True" -> ParseOk [] (Flag NormalDebugInfo)
| str == "0" -> ParseOk [] (Flag NoDebugInfo)
| str == "1" -> ParseOk [] (Flag MinimalDebugInfo)
| str == "2" -> ParseOk [] (Flag NormalDebugInfo)
| str == "3" -> ParseOk [] (Flag MaximalDebugInfo)
| lstr == "false" -> ParseOk [caseWarning] (Flag NoDebugInfo)
| lstr == "true" -> ParseOk [caseWarning] (Flag NormalDebugInfo)
| otherwise -> ParseFailed (NoParse name line)
where
lstr = lowercase str
caseWarning = PWarning $
"The '" ++ name ++ "' field is case sensitive, use 'True' or 'False'.")
]
++ toSavedConfig liftConfigExFlag
(configureExOptions ParseArgs src)
[] []
++ toSavedConfig liftInstallFlag
(installOptions ParseArgs)
["dry-run", "only", "only-dependencies", "dependencies-only"] []
++ toSavedConfig liftUploadFlag
(commandOptions uploadCommand ParseArgs)
["verbose", "check"] []
++ toSavedConfig liftReportFlag
(commandOptions reportCommand ParseArgs)
["verbose", "username", "password"] []
--FIXME: this is a hack, hiding the user name and password.
-- But otherwise it masks the upload ones. Either need to
-- share the options or make then distinct. In any case
-- they should probably be per-server.
++ [ viewAsFieldDescr
$ optionDistPref
(configDistPref . savedConfigureFlags)
(\distPref config ->
config
{ savedConfigureFlags = (savedConfigureFlags config) { configDistPref = distPref }
, savedHaddockFlags = (savedHaddockFlags config) { haddockDistPref = distPref }
}
)
ParseArgs
]
where
toSavedConfig lift options exclusions replacements =
[ lift (fromMaybe field replacement)
| opt <- options
, let field = viewAsFieldDescr opt
name = fieldName field
replacement = find ((== name) . fieldName) replacements
, name `notElem` exclusions ]
optional = Parse.option mempty . fmap toFlag
-- TODO: next step, make the deprecated fields elicit a warning.
--
deprecatedFieldDescriptions :: [FieldDescr SavedConfig]
deprecatedFieldDescriptions =
[ liftGlobalFlag $
listField "repos"
(Disp.text . showRepo) parseRepo
(fromNubList . globalRemoteRepos)
(\rs cfg -> cfg { globalRemoteRepos = toNubList rs })
, liftGlobalFlag $
simpleField "cachedir"
(Disp.text . fromFlagOrDefault "") (optional parseFilePathQ)
globalCacheDir (\d cfg -> cfg { globalCacheDir = d })
, liftUploadFlag $
simpleField "hackage-username"
(Disp.text . fromFlagOrDefault "" . fmap unUsername)
(optional (fmap Username parseTokenQ))
uploadUsername (\d cfg -> cfg { uploadUsername = d })
, liftUploadFlag $
simpleField "hackage-password"
(Disp.text . fromFlagOrDefault "" . fmap unPassword)
(optional (fmap Password parseTokenQ))
uploadPassword (\d cfg -> cfg { uploadPassword = d })
, liftUploadFlag $
spaceListField "hackage-password-command"
Disp.text parseTokenQ
(fromFlagOrDefault [] . uploadPasswordCmd)
(\d cfg -> cfg { uploadPasswordCmd = Flag d })
]
++ map (modifyFieldName ("user-"++) . liftUserInstallDirs) installDirsFields
++ map (modifyFieldName ("global-"++) . liftGlobalInstallDirs) installDirsFields
where
optional = Parse.option mempty . fmap toFlag
modifyFieldName :: (String -> String) -> FieldDescr a -> FieldDescr a
modifyFieldName f d = d { fieldName = f (fieldName d) }
liftUserInstallDirs :: FieldDescr (InstallDirs (Flag PathTemplate))
-> FieldDescr SavedConfig
liftUserInstallDirs = liftField
savedUserInstallDirs (\flags conf -> conf { savedUserInstallDirs = flags })
liftGlobalInstallDirs :: FieldDescr (InstallDirs (Flag PathTemplate))
-> FieldDescr SavedConfig
liftGlobalInstallDirs = liftField
savedGlobalInstallDirs (\flags conf -> conf { savedGlobalInstallDirs = flags })
liftGlobalFlag :: FieldDescr GlobalFlags -> FieldDescr SavedConfig
liftGlobalFlag = liftField
savedGlobalFlags (\flags conf -> conf { savedGlobalFlags = flags })
liftConfigFlag :: FieldDescr ConfigFlags -> FieldDescr SavedConfig
liftConfigFlag = liftField
savedConfigureFlags (\flags conf -> conf { savedConfigureFlags = flags })
liftConfigExFlag :: FieldDescr ConfigExFlags -> FieldDescr SavedConfig
liftConfigExFlag = liftField
savedConfigureExFlags (\flags conf -> conf { savedConfigureExFlags = flags })
liftInstallFlag :: FieldDescr InstallFlags -> FieldDescr SavedConfig
liftInstallFlag = liftField
savedInstallFlags (\flags conf -> conf { savedInstallFlags = flags })
liftUploadFlag :: FieldDescr UploadFlags -> FieldDescr SavedConfig
liftUploadFlag = liftField
savedUploadFlags (\flags conf -> conf { savedUploadFlags = flags })
liftReportFlag :: FieldDescr ReportFlags -> FieldDescr SavedConfig
liftReportFlag = liftField
savedReportFlags (\flags conf -> conf { savedReportFlags = flags })
parseConfig :: ConstraintSource
-> SavedConfig
-> String
-> ParseResult SavedConfig
parseConfig src initial = \str -> do
fields <- readFields str
let (knownSections, others) = partition isKnownSection fields
config <- parse others
let user0 = savedUserInstallDirs config
global0 = savedGlobalInstallDirs config
(remoteRepoSections0, haddockFlags, user, global, paths, args) <-
foldM parseSections
([], savedHaddockFlags config, user0, global0, [], [])
knownSections
let remoteRepoSections =
map addInfoForKnownRepos
. reverse
. nubBy ((==) `on` remoteRepoName)
$ remoteRepoSections0
return config {
savedGlobalFlags = (savedGlobalFlags config) {
globalRemoteRepos = toNubList remoteRepoSections
},
savedConfigureFlags = (savedConfigureFlags config) {
configProgramPaths = paths,
configProgramArgs = args
},
savedHaddockFlags = haddockFlags,
savedUserInstallDirs = user,
savedGlobalInstallDirs = global
}
where
isKnownSection (ParseUtils.Section _ "remote-repo" _ _) = True
isKnownSection (ParseUtils.F _ "remote-repo" _) = True
isKnownSection (ParseUtils.Section _ "haddock" _ _) = True
isKnownSection (ParseUtils.Section _ "install-dirs" _ _) = True
isKnownSection (ParseUtils.Section _ "program-locations" _ _) = True
isKnownSection (ParseUtils.Section _ "program-default-options" _ _) = True
isKnownSection _ = False
parse = parseFields (configFieldDescriptions src
++ deprecatedFieldDescriptions) initial
parseSections (rs, h, u, g, p, a)
(ParseUtils.Section _ "remote-repo" name fs) = do
r' <- parseFields remoteRepoFields (emptyRemoteRepo name) fs
when (remoteRepoKeyThreshold r' > length (remoteRepoRootKeys r')) $
warning $ "'key-threshold' for repository " ++ show (remoteRepoName r')
++ " higher than number of keys"
when (not (null (remoteRepoRootKeys r')) && not (remoteRepoSecure r')) $
warning $ "'root-keys' for repository " ++ show (remoteRepoName r')
++ " non-empty, but 'secure' not set to True."
return (r':rs, h, u, g, p, a)
parseSections (rs, h, u, g, p, a)
(ParseUtils.F lno "remote-repo" raw) = do
let mr' = readRepo raw
r' <- maybe (ParseFailed $ NoParse "remote-repo" lno) return mr'
return (r':rs, h, u, g, p, a)
parseSections accum@(rs, h, u, g, p, a)
(ParseUtils.Section _ "haddock" name fs)
| name == "" = do h' <- parseFields haddockFlagsFields h fs
return (rs, h', u, g, p, a)
| otherwise = do
warning "The 'haddock' section should be unnamed"
return accum
parseSections accum@(rs, h, u, g, p, a)
(ParseUtils.Section _ "install-dirs" name fs)
| name' == "user" = do u' <- parseFields installDirsFields u fs
return (rs, h, u', g, p, a)
| name' == "global" = do g' <- parseFields installDirsFields g fs
return (rs, h, u, g', p, a)
| otherwise = do
warning "The 'install-paths' section should be for 'user' or 'global'"
return accum
where name' = lowercase name
parseSections accum@(rs, h, u, g, p, a)
(ParseUtils.Section _ "program-locations" name fs)
| name == "" = do p' <- parseFields withProgramsFields p fs
return (rs, h, u, g, p', a)
| otherwise = do
warning "The 'program-locations' section should be unnamed"
return accum
parseSections accum@(rs, h, u, g, p, a)
(ParseUtils.Section _ "program-default-options" name fs)
| name == "" = do a' <- parseFields withProgramOptionsFields a fs
return (rs, h, u, g, p, a')
| otherwise = do
warning "The 'program-default-options' section should be unnamed"
return accum
parseSections accum f = do
warning $ "Unrecognized stanza on line " ++ show (lineNo f)
return accum
showConfig :: SavedConfig -> String
showConfig = showConfigWithComments mempty
showConfigWithComments :: SavedConfig -> SavedConfig -> String
showConfigWithComments comment vals = Disp.render $
case fmap ppRemoteRepoSection . fromNubList . globalRemoteRepos . savedGlobalFlags $ vals of
[] -> Disp.text ""
(x:xs) -> foldl' (\ r r' -> r $+$ Disp.text "" $+$ r') x xs
$+$ Disp.text ""
$+$ ppFields (skipSomeFields (configFieldDescriptions ConstraintSourceUnknown))
mcomment vals
$+$ Disp.text ""
$+$ ppSection "haddock" "" haddockFlagsFields
(fmap savedHaddockFlags mcomment) (savedHaddockFlags vals)
$+$ Disp.text ""
$+$ installDirsSection "user" savedUserInstallDirs
$+$ Disp.text ""
$+$ installDirsSection "global" savedGlobalInstallDirs
$+$ Disp.text ""
$+$ configFlagsSection "program-locations" withProgramsFields
configProgramPaths
$+$ Disp.text ""
$+$ configFlagsSection "program-default-options" withProgramOptionsFields
configProgramArgs
where
mcomment = Just comment
installDirsSection name field =
ppSection "install-dirs" name installDirsFields
(fmap field mcomment) (field vals)
configFlagsSection name fields field =
ppSection name "" fields
(fmap (field . savedConfigureFlags) mcomment)
((field . savedConfigureFlags) vals)
-- skip fields based on field name. currently only skips "remote-repo",
-- because that is rendered as a section. (see 'ppRemoteRepoSection'.)
skipSomeFields = filter ((/= "remote-repo") . fieldName)
-- | Fields for the 'install-dirs' sections.
installDirsFields :: [FieldDescr (InstallDirs (Flag PathTemplate))]
installDirsFields = map viewAsFieldDescr installDirsOptions
ppRemoteRepoSection :: RemoteRepo -> Doc
ppRemoteRepoSection vals = ppSection "remote-repo" (remoteRepoName vals)
remoteRepoFields Nothing vals
remoteRepoFields :: [FieldDescr RemoteRepo]
remoteRepoFields =
[ simpleField "url"
(text . show) (parseTokenQ >>= parseURI')
remoteRepoURI (\x repo -> repo { remoteRepoURI = x })
, boolField "secure"
remoteRepoSecure (\x repo -> repo { remoteRepoSecure = x })
, listField "root-keys"
text parseTokenQ
remoteRepoRootKeys (\x repo -> repo { remoteRepoRootKeys = x })
, simpleField "key-threshold"
(text . show) (parseTokenQ >>= parseInt)
remoteRepoKeyThreshold (\x repo -> repo { remoteRepoKeyThreshold = x })
]
where
parseURI' uriString =
case parseURI uriString of
Nothing -> fail $ "remote-repo: no parse on " ++ show uriString
Just uri -> return uri
-- from base >= 4.6 we can use 'Text.Read.readEither' but right now we
-- support everything back to ghc 7.2 (base 4.4)
parseInt intString =
case filter (null . snd) (reads intString) of
[(n, _)] -> return n
_ -> fail $ "remote-remo: could not parse int " ++ show intString
-- | Fields for the 'haddock' section.
haddockFlagsFields :: [FieldDescr HaddockFlags]
haddockFlagsFields = [ field
| opt <- haddockOptions ParseArgs
, let field = viewAsFieldDescr opt
name = fieldName field
, name `notElem` exclusions ]
where
exclusions = ["verbose", "builddir"]
-- | Fields for the 'program-locations' section.
withProgramsFields :: [FieldDescr [(String, FilePath)]]
withProgramsFields =
map viewAsFieldDescr $
programConfigurationPaths' (++ "-location") defaultProgramConfiguration
ParseArgs id (++)
-- | Fields for the 'program-default-options' section.
withProgramOptionsFields :: [FieldDescr [(String, [String])]]
withProgramOptionsFields =
map viewAsFieldDescr $
programConfigurationOptions defaultProgramConfiguration ParseArgs id (++)
-- | Get the differences (as a pseudo code diff) between the user's
-- '~/.cabal/config' and the one that cabal would generate if it didn't exist.
userConfigDiff :: GlobalFlags -> IO [String]
userConfigDiff globalFlags = do
userConfig <- loadConfig normal (globalConfigFile globalFlags)
testConfig <- liftM2 mappend baseSavedConfig initialSavedConfig
return $ reverse . foldl' createDiff [] . M.toList
$ M.unionWith combine
(M.fromList . map justFst $ filterShow testConfig)
(M.fromList . map justSnd $ filterShow userConfig)
where
justFst (a, b) = (a, (Just b, Nothing))
justSnd (a, b) = (a, (Nothing, Just b))
combine (Nothing, Just b) (Just a, Nothing) = (Just a, Just b)
combine (Just a, Nothing) (Nothing, Just b) = (Just a, Just b)
combine x y = error $ "Can't happen : userConfigDiff " ++ show x ++ " " ++ show y
createDiff :: [String] -> (String, (Maybe String, Maybe String)) -> [String]
createDiff acc (key, (Just a, Just b))
| a == b = acc
| otherwise = ("+ " ++ key ++ ": " ++ b) : ("- " ++ key ++ ": " ++ a) : acc
createDiff acc (key, (Nothing, Just b)) = ("+ " ++ key ++ ": " ++ b) : acc
createDiff acc (key, (Just a, Nothing)) = ("- " ++ key ++ ": " ++ a) : acc
createDiff acc (_, (Nothing, Nothing)) = acc
filterShow :: SavedConfig -> [(String, String)]
filterShow cfg = map keyValueSplit
. filter (\s -> not (null s) && any (== ':') s)
. map nonComment
. lines
$ showConfig cfg
nonComment [] = []
nonComment ('-':'-':_) = []
nonComment (x:xs) = x : nonComment xs
topAndTail = reverse . dropWhile isSpace . reverse . dropWhile isSpace
keyValueSplit s =
let (left, right) = break (== ':') s
in (topAndTail left, topAndTail (drop 1 right))
-- | Update the user's ~/.cabal/config' keeping the user's customizations.
userConfigUpdate :: Verbosity -> GlobalFlags -> IO ()
userConfigUpdate verbosity globalFlags = do
userConfig <- loadConfig normal (globalConfigFile globalFlags)
newConfig <- liftM2 mappend baseSavedConfig initialSavedConfig
commentConf <- commentSavedConfig
(_, cabalFile) <- lookupConfigFile $ globalConfigFile globalFlags
let backup = cabalFile ++ ".backup"
notice verbosity $ "Renaming " ++ cabalFile ++ " to " ++ backup ++ "."
renameFile cabalFile backup
notice verbosity $ "Writing merged config to " ++ cabalFile ++ "."
writeConfigFile cabalFile commentConf (newConfig `mappend` userConfig)
|
martinvlk/cabal
|
cabal-install/Distribution/Client/Config.hs
|
bsd-3-clause
| 44,602
| 0
| 27
| 12,084
| 9,374
| 5,052
| 4,322
| 794
| 13
|
{-
This parser was created by Irina Artemeva and since then modified.
Available at https://github.com/Pluralia/uKanren_translator/blob/58ab786f94f68da1027428706448fbddb980fa72/src/Parser.hs
-}
{-# LANGUAGE DerivingStrategies #-}
module Parser.IrinaParser (parseProg, parseProgramWithImports) where
import qualified Control.Applicative.Combinators.NonEmpty as NE
import Eval (postEval)
import Text.Megaparsec ( (<|>), many, some, MonadParsec(try) )
import Syntax
( G((:=:), Invoke, Fresh),
Program(..),
Def(..),
Term(..),
X,
unsafeDisj,
unsafeConj',
unsafeDisj' )
import Parser.Data ( Parser )
import Parser.Lexer
( sc, symbol, roundBr, angleBr, boxBr, curvyBr, identifier )
parseProgramWithImports :: Parser ([String], Program)
parseProgramWithImports = do
imports <- many parseImport
program <- parseProg
return (imports, program)
parseImport :: Parser String
parseImport = do
symbol "import"
ident
reserved :: [String]
reserved = ["trueo", "falso", "zero", "succ", "conde", "import"]
ident :: Parser String
ident = identifier reserved
-----------------------------------------------------------------------------------------------------
-- term
parseTerm :: Parser (Term X)
parseTerm = parseListTerm
parseListTerm :: Parser (Term X)
parseListTerm = try conso
<|> try (roundBr conso)
<|> niloOrNum
niloOrNum :: Parser (Term X)
niloOrNum = try parseNumTerm <|> do
symbol "[]"
return $ C "Nil" []
conso :: Parser (Term X)
conso = do
x <- niloOrNum <|> roundBr parseTerm
xs <- some $ symbol "%" *> parseTerm
return $ foldr1 (\term acc -> C "Cons" [term, acc]) (x : xs)
parseNumTerm :: Parser (Term X)
parseNumTerm = try succo
<|> try (roundBr succo)
<|> zeroOrBool
zeroOrBool :: Parser (Term X)
zeroOrBool = try parseBoolTerm <|> do
symbol "zero"
return $ C "O" []
succo :: Parser (Term X)
succo = do
symbol "succ"
x <- try zeroOrBool <|> roundBr succo
return $ C "S" [x]
parseBoolTerm :: Parser (Term X)
parseBoolTerm = try falso
<|> try trueo
<|> parseDesugarTerm
trueo :: Parser (Term X)
trueo = do
symbol "trueo"
return $ C "true" []
falso :: Parser (Term X)
falso = do
symbol "falso"
return $ C "false" []
parseDesugarTerm :: Parser (Term X)
parseDesugarTerm = try c <|> v
where
v = V <$> ident
c = angleBr $ do
name <- ident
symbol ":"
terms <- many parseTerm
return $ C name terms
-----------------------------------------------------------------------------------------------------
-- goal
parseFresh :: Parser (G X)
parseFresh = boxBr $ do
names <- some ident
symbol ":"
goal <- parseGoal
return $ foldr Fresh goal names
parseInvoke :: Parser (G X)
parseInvoke = curvyBr $
Invoke
<$> ident
<*> many parseTerm
parsePat :: Parser (G X)
parsePat = try $ do
term1 <- parseTerm
symbol "==="
term2 <- parseTerm
return $ term1 :=: term2
<|> try (roundBr parseOp)
<|> try parseFresh
<|> parseInvoke
parseOp :: Parser (G X)
parseOp =
unsafeDisj' <$> NE.sepBy1 (unsafeConj' <$> NE.sepBy1 parsePat (symbol "/\\")) (symbol "\\/")
-- makeExprParser parsePat ops
-- where
-- go assoc op f = assoc (f <$ symbol op)
-- ops = [ [ go InfixR "/\\" (:/\:) ]
-- , [ go InfixR "\\/" (:\/:) ]
-- ]
parseGoal :: Parser (G X)
parseGoal = try parseConde
<|> parseDesugarGoal
parseConde :: Parser (G X)
parseConde = do
symbol "conde"
goals <- some (roundBr parseDesugarGoal)
return $ unsafeDisj goals
parseDesugarGoal :: Parser (G X)
parseDesugarGoal = sc
*> try parseOp
<|> try parseFresh
<|> parseInvoke
parseQuery :: Parser (G X)
parseQuery = do
symbol "?"
parseGoal
-----------------------------------------------------------------------------------------------------
-- definition
parseDef :: Parser Def
parseDef = do
symbol "::"
name <- ident
args <- many ident
symbol "="
goal <- parseGoal
return $ Def name args goal
-----------------------------------------------------------------------------------------------------
-- program
parseProg :: Parser Program
parseProg =
Program <$> many parseDef <*> (postEval [] <$> parseQuery)
|
kajigor/uKanren_transformations
|
src/Parser/IrinaParser.hs
|
bsd-3-clause
| 4,247
| 0
| 12
| 897
| 1,280
| 651
| 629
| 129
| 1
|
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
-- The Timber compiler <timber-lang.org>
--
-- Copyright 2008-2009 Johan Nordlander <nordland@csee.ltu.se>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the names of the copyright holder and any identified
-- contributors, nor the names of their affiliations, may be used to
-- endorse or promote products derived from this software without
-- specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
-- OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
-- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
-- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
-- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
module Kindle where
import Monad
import Common
import PP
import qualified Core
import qualified Env
import Data.Binary
import Control.Monad.Identity
-- Kindle is the main back-end intermediate language. It is a typed imperative language with dynamic
-- memory allocation and garbage-collection, that can be described as a slightly extended version of
-- the common subset of C, Java and C++. The purpose of Kindle is to function as a high-level back-
-- end program format that can be translated into standard imperative languages as well as assembly
-- code without too much difficulty. None of C's pointer arithmetic features are present, neither
-- are the class hieracrhies of Java and C++. The type system of Kindle is a miniature variant of
-- System F, but unsafe type-casts are supported. The main extension compared to Java is nested
-- recursive functions. Heap-allocated struct objects may contain function-valued components which
-- are invoked using self-application. This provides a form of basic OO capability that may serve
-- as a target for a closure conversion pass. For more details on the relation between Kindle and
-- the primary intermediate language Core, see module Core2Kindle.
-- A Kindle module consists of type declarations and term bindings. A type declaration introduces
-- a struct type, and optionally also an enumeration of type names. A binding defines either a named
-- function or a named value of atomic type. Function bindings are immutable. All type declarations
-- are mutually recursive, and so are binding groups.
data Module = Module Name [Name] TEnv Decls Binds
deriving (Eq,Show)
-- A type declaration introduces a struct type that defines the layout of heap-allocated objects.
-- A struct type may bind type parameters and may contain both value and function fields. Each
-- struct introduces a private namespace for its field names. A struct can also be declared an
-- extension of another struct, as indicated by the Link parameter. If a struct is an extension,
-- a prefix of its field names and their types must match the full definition of the extended
-- struct when instantiated with the given type arguments. In addition, an extended struct may
-- indicate that a subset of its type parameters are to be existentially quantified when the
-- struct is cast to its base type, and this list must contain the existential parameters of
-- its base type (if any) as a prefix. If a struct is not an extension, it must either be an
-- ordinary Top of an extension hierarchy, or a Union - the latter form supporting case analysis
-- between different extensions by means of the 'switch' command.
type Decls = Map Name Decl
data Decl = Struct [Name] TEnv Link
deriving (Eq,Show)
data Link = Top
| Union
| Extends Name [AType] [Name]
deriving (Eq,Show)
-- A term binding is either a named value of atomic type or a named function. A named function can
-- bind type parameters, thus introducing polymorphism in the style of System F. The result and
-- parameter types of a function are in the scope of the defined type parameters and must all be
-- atomic.
type Binds = Map Name Bind
data Bind = Val AType Exp
| Fun [Name] AType ATEnv Cmd
deriving (Eq,Show)
-- The type of a binding is either just an atomic type in case of a value binding, or a triple
-- consisting of abstracted type parameters, the argument types, and the result type in the
-- function binding case.
type TEnv = Map Name Type
data Type = ValT AType
| FunT [Name] [AType] AType
deriving (Eq,Show)
-- An atomic type is either a named constructor or a type variable (both possibly applied to
-- further atomic type arguments), or an index into the sequence of existentially quantified
-- type components of the surrounding struct (only valid within function-valued field definitions).
type ATEnv = Map Name AType
data AType = TCon Name [AType]
| TVar Name [AType]
| TThis Int
deriving (Eq,Show)
-- A function body is a command that computes the desired result, possibly while performing imperative
-- side-effects. The current type system does not distinguish pure functions from side-effecting ones,
-- although that separation will indeed be maintained by the translation from type-checked Core programs.
data Cmd = CRet Exp -- simply return $1
| CRun Exp Cmd -- evaluate $1 for its side-effects only, then execure tail $2
| CBind Bool Binds Cmd -- introduce (recursive? $1) local bindings $2, then execute tail $3
| CUpd Name Exp Cmd -- overwrite value variable $1 with value $2, execute tail $3
| CUpdS Exp Name Exp Cmd -- overwrite value field $2 of struct $1 with value $3, execute tail $4
| CUpdA Exp Exp Exp Cmd -- overwrite index $2 of array $1 with value $3, execute tail $4
| CSwitch Exp [Alt] -- depending on the dynamic value of $1, choose tails from $2
| CSeq Cmd Cmd -- execute $1; if fall-through, continue with $2
| CBreak -- break out of a surrounding switch
| CRaise Exp -- raise an exception
| CWhile Exp Cmd Cmd -- run $2 while $1 is non-zero, then execute tail $3
| CCont -- start next turn of enclosing while loop
deriving (Eq,Show)
-- Note 1: command (CRun e c) is identical to (CBind False [(x,e)] c) if x is a fresh name not used anywhere else
-- Note 2: the Cmd alternatives CSeq and CBreak are intended to implement the Fatbar and Fail primitives
-- of the pattern-matching datatype PMC used in Core.
data Alt = ACon Name [Name] ATEnv Cmd -- if switch value has struct type variant $1, execute tail $4 with
-- $3 bound to the actual struct fields and $2 bound to the struct
-- type arguments not statically known
| ALit Lit Cmd -- if switch value matches literal $1, execute tail $2
| AWild Cmd -- execute tail $1 as default alternative
deriving (Eq,Show)
-- Simple expressions that can be RH sides of value definitions as well as function arguments.
data Exp = EVar Name -- local or global value name, enum constructor or function parameter
| EThis -- the surrounding struct itself
-- (only valid within function fields, illegal in local/global functions)
| ELit Lit -- literal
| ESel Exp Name -- selection of value field $2 from struct $1
| ENew Name [AType] Binds -- a new struct of type $1 with type args $2, (partially) initialized by $3
| ECall Name [AType] [Exp] -- calling local or global function $1 with type/term arguments $2/$3
| EEnter Exp Name [AType] [Exp] -- entering function $2 of struct $1 with type/term arguments $3/($1:$4)
| ECast AType Exp -- unchecked cast of value $2 to type $1
deriving (Eq,Show)
-- Note: Kindle allows free variables to occur inside local functions and function-valued struct fields. A
-- Kindle implementation must either handle this correctly at run-time, or such variable occurrences must be
-- transformed away at compile-time. The latter can be done using lambda-lifting for local functions and
-- explicitly closing the struct functions via extra value fields accessed through "this".
tId x = tCon (prim x)
tCon n = TCon n []
tVar n = TVar n []
tPOLY = tId POLY
tWORD = tId WORD
tUNIT = tCon (tuple 0)
tTime = tId Time
tMsg = tId Msg
tOID = tId OID
tInt = tId Int
tFloat = tId Float
tChar = tId Char
tBool = tId Bool
tBITS8 = tId BITS8
tBITS16 = tId BITS16
tBITS32 = tId BITS32
tTimer = tId TIMERTYPE
tRef a = TCon (prim Ref) [a]
tLIST a = TCon (prim LIST) [a]
tArray a = TCon (prim Array) [a]
maxSmallCLOS = 3 :: Int
smallCLOS 1 = CLOS1
smallCLOS 2 = CLOS2
smallCLOS 3 = CLOS3
encodeCLOS [] t ts = t:ts
encodeCLOS vs t ts = t:ts ++ tCon (prim CLOS) : map tVar vs
decodeCLOS ts0 = (vs, ts, t)
where (t:ts,tvs) = span (/=(tCon (prim CLOS))) ts0
vs = [ v | TVar v _ <- tvs ]
tClos t ts = tClos2 [] t ts
tClos2 [] t ts
| a <= maxSmallCLOS = TCon (prim (smallCLOS a)) (t:ts)
where a = length ts
tClos2 vs t ts = TCon (prim CLOS) (encodeCLOS vs t ts)
openClosureType (TCon (Prim p _) ts)
| p `elem` [CLOS1,CLOS2,CLOS3,CLOS] = decodeCLOS ts
openClosureType t = internalError "Kindle.openClosureType" t
closure t te c = closure2 [] t te c
closure2 [] t te c
| a <= maxSmallCLOS = ENew (prim (smallCLOS a)) (t:rng te) [(prim Code, Fun [] t te c)]
where a = length te
closure2 vs t te c = ENew (prim CLOS) (encodeCLOS vs t (rng te)) [(prim Code, Fun vs t te c)]
closBind ts0 = [(prim Code, FunT vs ts t)]
where (vs,ts,t) = decodeCLOS ts0
enter e ts es = EEnter e (prim Code) ts es
multiEnter [] [] e = e
multiEnter (ts:tss) es e = multiEnter tss es2 (enter e [] es1)
where (es1,es2) = splitAt (length ts) es
tupleDecl (Tuple n _) = Struct ids (map f ids) Top
where ids = take n abcSupply
f n = (n, ValT (TVar n []))
equants (Extends _ _ vs) = vs
equants _ = []
litType (LInt _ _) = tInt
litType (LRat _ _) = tFloat
litType (LChr _ _) = tChar
litType (LStr _ _) = tLIST tChar
a = name0 "a"
b = name0 "b"
c = name0 "c"
d = name0 "d"
ta = TVar a []
tb = TVar b []
tc = TVar c []
td = TVar d []
primDecls = (prim Bool, Struct [] [] Union) :
(prim FALSE, Struct [] [] (Extends (prim Bool) [] [])) :
(prim TRUE, Struct [] [] (Extends (prim Bool) [] [])) :
(prim LIST, Struct [a] [] Union) :
(prim NIL, Struct [a] [] (Extends (prim LIST) [ta] [])) :
(prim CONS, Struct [a] [(a, ValT ta),
(b, ValT (tLIST ta))] (Extends (prim LIST) [ta] [])) :
(prim Ref, Struct [a] [(prim STATE, ValT ta)] Top) :
(prim EITHER, Struct [a,b] [] Union) :
(prim LEFT, Struct [a,b] [(a,ValT ta)] (Extends (prim EITHER) [ta,tb] [])) :
(prim RIGHT, Struct [a,b] [(a,ValT tb)] (Extends (prim EITHER) [ta,tb] [])) :
(prim Msg, Struct [] [(prim Code, FunT [] [] tUNIT),
(prim Baseline, ValT (tId AbsTime)),
(prim Deadline, ValT (tId AbsTime)),
(prim Next, ValT (tId Msg))] Top) :
(prim TIMERTYPE, Struct [] [(prim Reset, FunT [] [tInt] tUNIT),
(prim Sample, FunT [] [tInt] tTime)] Top) :
(prim CLOS1, Struct [a,b] [(prim Code, FunT [] [tb] ta)] Top) :
(prim CLOS2, Struct [a,b,c] [(prim Code, FunT [] [tb,tc] ta)] Top) :
(prim CLOS3, Struct [a,b,c,d] [(prim Code, FunT [] [tb,tc,td] ta)] Top) :
[]
isInfix (Prim p _) = p `elem` [MIN____KINDLE_INFIX .. MAX____KINDLE_INFIX]
isInfix _ = False
isUnaryOp (Prim p _) = p `elem` [IntNeg, FloatNeg, NOT8, NOT16, NOT32]
isUnaryOp _ = False
primKindleTerms = map prim [ MIN____VAR .. MAX____KINDLEVAR ]
primTEnv = primTEnv0 ++ map cv (Env.primTypeEnv `restrict` primKindleTerms)
where
cv (x,Core.Scheme r [] ke) = (x, cv0 r (dom ke))
cv0 (Core.F ts t) vs = FunT vs (map cv1 ts) (cv2 t)
cv0 (Core.R t) [] = ValT (cv3 t)
cv0 (Core.R t) vs = FunT vs [] (cv3 t)
cv1 (Core.Scheme r [] []) = cv2 r
cv2 (Core.R t) = cv3 t
cv3 t
| isCon n = TCon n ts'
| otherwise = TVar n ts'
where (Core.TId n, ts) = Core.tFlat t
ts' = map cv3 ts
-- N.B.: This type/scheme conversion algorithm is partial; it is only intended to cover the cases that appear
-- when converting Env.primTypeEnv restricted to primKindleTerms (note the exceptions for TIMERTERM and Abort).
-- Primitive names only visible after translation into Kindle
primTEnv0 = (prim TIMERTERM, FunT [] [tInt] (tId TIMERTYPE)) :
(prim Abort, FunT [a] [tMsg, tRef ta] tUNIT) :
(prim NEWREF, FunT [a] [ta] (tRef ta)) :
(prim STATEOF, FunT [a] [tRef ta] ta) :
(prim ASYNC, FunT [] [tMsg,tTime,tTime] tUNIT) :
(prim LOCK, FunT [] [tOID] tUNIT) :
(prim UNLOCK, FunT [] [tOID] tUNIT) :
(prim Inherit, ValT tTime) :
(prim EmptyArray, FunT [a] [tInt] (tArray ta)) :
(prim CloneArray, FunT [a] [tArray ta, tInt] (tArray ta)) :
[]
okRec (ValT t) = okRec' t
okRec (FunT vs ts t) = True -- Good: recursive function
okRec' (TVar _ _) = False -- Bad: statically unknown representation
okRec' (TThis _) = False -- Bad: statically unknown representation
okRec' (TCon n _) | n `elem` scalars = False -- Bad: type that can't fit placeholder
| otherwise = True -- Good: heap allocated data
scalars = tuple 0 : map prim [Int, Float, Char, Bool, BITS8, BITS16, BITS32, AbsTime]
smallTypes = tuple 0 : map prim [Char, Bool, BITS8, BITS16]
isVal (_, Val _ _) = True
isVal (_, Fun _ _ _ _) = False
isFunT (_, ValT _) = False
isFunT (_, FunT _ _ _) = True
isTVar (TVar _ _) = True
isTVar _ = False
isArray (TCon (Prim Array _) _) = True
isArray _ = False
isEVar (EVar _) = True
isEVar _ = False
typeOf (Val t e) = ValT t
typeOf (Fun vs t te c) = FunT vs (rng te) t
rngType (ValT t) = t
rngType (FunT vs ts t) = t
typeOf' b = rngType (typeOf b)
declsOf (Module _ _ _ ds _) = ds
unions ds = [ n | (n,Struct _ _ Union) <- ds ]
variants ds n0 = [ n | (n,Struct _ _ (Extends n' _ _)) <- ds, n' == n0 ]
typeOfSel ds l = head [ (k,vs,t) | (k,Struct vs te _) <- ds, (l',t) <- te, l'==l ]
unit = ENew (tuple 0) [] []
cBind [] c = c
cBind bs c = CBind False bs c
cBindR r [] c = c
cBindR r bs c = CBind r bs c
flatBinds bf = flat (bf CBreak)
where flat (CBind r bs c) = bs ++ flat c
flat _ = []
cUpd [] [] c = c
cUpd (x:xs) (e:es) c = CUpd x e (cUpd xs es c)
simpleExp (EVar _) = True
simpleExp (ELit _) = True
simpleExp (ECast _ e) = simpleExp e
simpleExp _ = False
lock t e = ECast t (ECall (prim LOCK) [] [ECast tOID e])
unlock x c = cMap (CRun (ECall (prim UNLOCK) [] [e0]) . CRet) c
where e0 = ECast tOID (EVar x)
cMap f (CRet e) = f e
cMap f (CRun e c) = CRun e (cMap f c)
cMap f (CBind r bs c) = CBind r bs (cMap f c)
cMap f (CUpd y e c) = CUpd y e (cMap f c)
cMap f (CUpdS e y e' c) = CUpdS e y e' (cMap f c)
cMap f (CUpdA e i e' c) = CUpdA e i e' (cMap f c)
cMap f (CSwitch e alts) = CSwitch e (clift (cMap f) alts)
where g (ACon y vs te c) = ACon y vs te (cMap f c)
g (ALit l c) = ALit l (cMap f c)
g (AWild c) = AWild (cMap f c)
cMap f (CSeq c c') = CSeq (cMap f c) (cMap f c')
cMap f (CBreak) = CBreak
cMap f (CRaise e) = CRaise e
cMap f (CWhile e c c') = CWhile e (cMap f c) (cMap f c')
cMap f (CCont) = CCont
cMap' f = cMap (CRet . f)
class CLift a where
clift :: (Cmd -> Cmd) -> a -> a
instance CLift Cmd where
clift f = f
instance CLift Alt where
clift f (ACon y vs te c) = ACon y vs te (f c)
clift f (ALit l c) = ALit l (f c)
clift f (AWild c) = AWild (f c)
instance CLift a => CLift [a] where
clift f = map (clift f)
cmap f = clift (cMap (CRet . f))
findStruct s0 [] = Nothing
findStruct s0 ((n,s):ds)
| equalStructs (s0,s) = Just n
| otherwise = findStruct s0 ds
equalStructs (Struct [] te1 l1, Struct [] te2 l2)
= l1 == l2 && ls1 == ls2 && all equalTypes (ts1 `zip` ts2)
where (ls1,ts1) = unzip te1
(ls2,ts2) = unzip te2
equalStructs (Struct vs1 te1 l1, Struct vs2 te2 l2)
= l1 == l2 && length vs1 == length vs2 &&
ls1 == ls2 && all equalTypes (subst s ts1 `zip` ts2)
where s = vs1 `zip` map tVar vs2
(ls1,ts1) = unzip te1
(ls2,ts2) = unzip te2
equalTypes (ValT t1, ValT t2) = t1 == t2
equalTypes (FunT vs1 ts1 t1, FunT vs2 ts2 t2)
= length vs1 == length vs2 && (t1:ts1) == subst s (t2:ts2)
where s = vs2 `zip` map tVar vs1
equalTypes _ = False
subexps (CRet e) = [e]
subexps (CRun e _) = [e]
subexps (CBind _ bs _) = [ e | (_,Val _ e) <- bs ]
subexps (CUpd _ e _) = [e]
subexps (CUpdS e _ e' _) = [e,e']
subexps (CUpdA e _ e' _) = [e,e']
subexps (CSwitch e _) = [e]
subexps (CWhile e _ _) = [e]
subexps _ = []
raises es = [ e | ECall (Prim Raise _) _ [e] <- es ]
class RefThis a where
refThis :: a -> Bool
instance RefThis a => RefThis [a] where
refThis xs = any refThis xs
instance RefThis a => RefThis (Name,a) where
refThis (_,x) = refThis x
instance RefThis Exp where
refThis (EVar _) = False
refThis (EThis) = True
refThis (ELit _) = False
refThis (ESel e _) = refThis e
refThis (ENew _ ts bs) = refThis ts || refThis bs
refThis (ECall _ ts es) = refThis ts || refThis es
refThis (EEnter e _ ts es) = refThis e || refThis ts || refThis es
refThis (ECast t e) = refThis t || refThis e
instance RefThis Cmd where
refThis (CRet e) = refThis e
refThis (CRun e c) = refThis e || refThis c
refThis (CBind _ bs c) = refThis bs || refThis c
refThis (CUpd _ e c) = refThis e || refThis c
refThis (CUpdS e _ e' c) = refThis [e,e'] || refThis c
refThis (CUpdA e e' e'' c) = refThis [e,e',e''] || refThis c
refThis (CSwitch e alts) = refThis e || refThis alts
refThis (CSeq c c') = refThis c || refThis c'
refThis (CBreak) = False
refThis (CRaise e) = refThis e
refThis (CWhile e c c') = refThis e || refThis c || refThis c'
refThis (CCont) = False
instance RefThis Alt where
refThis (ACon _ _ te c) = refThis te || refThis c
refThis (ALit l c) = refThis c
refThis (AWild c) = refThis c
instance RefThis Bind where
refThis (Val t e) = refThis t || refThis e
refThis (Fun vs t te c) = refThis t || refThis te
instance RefThis AType where
refThis (TCon _ ts) = refThis ts
refThis (TVar _ ts) = refThis ts
refThis (TThis i) = True
-- Free variables ------------------------------------------------------------------------------------
instance Ids Exp where
idents (EVar x) = [x]
idents (EThis) = []
idents (ELit l) = []
idents (ESel e l) = idents e
idents (ENew x ts bs) = idents bs
idents (ECall x ts es) = x : idents es
idents (EEnter e x ts es) = idents e ++ idents es
idents (ECast t e) = idents e
instance Ids Cmd where
idents (CRet e) = idents e
idents (CRun e c) = idents e ++ idents c
idents (CBind False bs c) = idents bs ++ (idents c \\ dom bs)
idents (CBind True bs c) = (idents bs ++ idents c) \\ dom bs
idents (CUpd x e c) = idents e ++ idents c
idents (CUpdS e x e' c) = idents e ++ idents e' ++ idents c
idents (CUpdA e i e' c) = idents e ++ idents i ++ idents e' ++ idents c
idents (CSwitch e alts) = idents e ++ idents alts
idents (CSeq c c') = idents c ++ idents c'
idents (CBreak) = []
idents (CRaise e) = idents e
idents (CWhile e c c') = idents e ++ idents c ++ idents c'
idents (CCont) = []
instance Ids Alt where
idents (ACon x vs te c) = idents c \\ dom te
idents (ALit l c) = idents c
idents (AWild c) = idents c
instance Ids Bind where
idents (Val t e) = idents e
idents (Fun vs t te c) = idents c \\ dom te
instance Ids AType where
idents (TCon c ts) = c : idents ts
idents (TVar v ts) = v : idents ts
idents (TThis i) = []
instance Ids Type where
idents (ValT t) = idents t
idents (FunT vs ts t) = idents (t:ts) \\ vs
class TypeVars a where
typevars :: a -> [Name]
instance TypeVars a => TypeVars [a] where
typevars xs = concatMap typevars xs
instance TypeVars a => TypeVars (Name,a) where
typevars (_,x) = typevars x
instance TypeVars Bind where
typevars (Val t e) = typevars t ++ typevars e
typevars (Fun vs t te c) = (typevars t ++ typevars te ++ typevars c) \\ vs
instance TypeVars Exp where
typevars (EVar _) = []
typevars (EThis) = []
typevars (ELit _) = []
typevars (ESel e _) = typevars e
typevars (ENew _ ts bs) = typevars ts ++ typevars bs
typevars (ECall _ ts es) = typevars ts ++ typevars es
typevars (EEnter e _ ts es) = typevars ts ++ typevars (e:es)
typevars (ECast t e) = typevars t ++ typevars e
instance TypeVars Cmd where
typevars (CRet e) = typevars e
typevars (CRun e c) = typevars e ++ typevars c
typevars (CBind _ bs c) = typevars bs ++ typevars c
typevars (CUpd _ e c) = typevars e ++ typevars c
typevars (CUpdS e _ e' c) = typevars [e,e'] ++ typevars c
typevars (CUpdA e i e' c) = typevars [e,i,e'] ++ typevars c
typevars (CSwitch e alts) = typevars e ++ typevars alts
typevars (CSeq c c') = typevars c ++ typevars c'
typevars (CBreak) = []
typevars (CRaise e) = typevars e
typevars (CWhile e c c') = typevars e ++ typevars [c,c']
typevars (CCont) = []
instance TypeVars Alt where
typevars (ACon _ vs te c) = (typevars c ++ typevars te) \\ vs
typevars (ALit _ c) = typevars c
typevars (AWild c) = typevars c
instance TypeVars AType where
typevars (TCon _ ts) = typevars ts
typevars (TVar n ts) = n : typevars ts
typevars (TThis i) = []
-- Substitutions ------------------------------------------------------------------------------------------
instance Subst Exp Name Exp where
subst s (EVar v) = case lookup v s of
Just e -> e
_ -> EVar v
subst s (EThis) = EThis
subst s (ELit l) = ELit l
subst s (ESel e l) = ESel (subst s e) l
subst s (ENew x ts bs) = ENew x ts (subst s bs)
subst s (ECall x ts es) = ECall x ts (subst s es)
subst s (EEnter e x ts es) = EEnter (subst s e) x ts (subst s es)
subst s (ECast t e) = ECast t (subst s e)
instance Subst Cmd Name Exp where
subst s (CRet e) = CRet (subst s e)
subst s (CRun e c) = CRun (subst s e) (subst s c)
subst s (CBind r bs c) = CBind r (subst s bs) (subst s c)
subst s (CUpd x e c) = CUpd x (subst s e) (subst s c)
subst s (CUpdS e x e' c) = CUpdS (subst s e) x (subst s e') (subst s c)
subst s (CUpdA e i e' c) = CUpdA (subst s e) (subst s i) (subst s e') (subst s c)
subst s (CSwitch e alts) = CSwitch (subst s e) (subst s alts)
subst s (CSeq c c') = CSeq (subst s c) (subst s c')
subst s (CBreak) = CBreak
subst s (CRaise e) = CRaise (subst s e)
subst s (CWhile e c c') = CWhile (subst s e) (subst s c) (subst s c')
subst s (CCont) = CCont
instance Subst Alt Name Exp where
subst s (ACon x vs te c) = ACon x vs te (subst s c) -- NOTE: no alpha-conversion!!
subst s (ALit l c) = ALit l (subst s c)
subst s (AWild c) = AWild (subst s c)
instance Subst Bind Name Exp where
subst s (Val t e) = Val t (subst s e)
subst s (Fun vs t te c) = Fun vs t te (subst s c)
instance Subst Exp Name Name where
subst [] e = e
subst s (EVar v) = EVar (subst s v)
subst s (EThis) = EThis
subst s (ELit l) = ELit l
subst s (ESel e l) = ESel (subst s e) (subst s l)
subst s (ENew x ts bs) = ENew (subst s x) ts (subst s bs)
subst s (ECall x ts es) = ECall (subst s x) ts (subst s es)
subst s (EEnter e x ts es) = EEnter (subst s e) (subst s x) ts (subst s es)
subst s (ECast t e) = ECast t (subst s e)
instance Subst Cmd Name Name where
subst [] c = c
subst s (CRet e) = CRet (subst s e)
subst s (CRun e c) = CRun (subst s e) (subst s c)
subst s (CBind r bs c) = CBind r (subst s bs) (subst s c)
subst s (CUpd x e c) = CUpd (subst s x) (subst s e) (subst s c)
subst s (CUpdS e x e' c) = CUpdS (subst s e) (subst s x) (subst s e') (subst s c)
subst s (CUpdA e i e' c) = CUpdA (subst s e) (subst s i) (subst s e') (subst s c)
subst s (CSwitch e alts) = CSwitch (subst s e) (subst s alts)
subst s (CSeq c c') = CSeq (subst s c) (subst s c')
subst s (CBreak) = CBreak
subst s (CRaise e) = CRaise (subst s e)
subst s (CWhile e c c') = CWhile (subst s e) (subst s c) (subst s c')
subst s (CCont) = CCont
instance Subst Alt Name Name where
subst s (ACon x vs te c) = ACon (subst s x) vs te (subst (prune s vs) c) -- NOTE: no alpha-conversion!!
subst s (ALit l c) = ALit l (subst s c)
subst s (AWild c) = AWild (subst s c)
instance Subst Bind Name Name where
subst s (Val t e) = Val t (subst s e)
subst s (Fun vs t te c) = Fun vs t te (subst (prune s (dom te)) c)
instance Subst Type Name AType where
subst s (ValT t) = ValT (subst s t)
subst s (FunT vs t ts) = FunT vs (subst s t) (subst s ts) -- NOTE: no alpha-conversion!!
instance Subst AType Name AType where
subst s (TCon c ts) = TCon c (subst s ts)
subst s (TVar v ts) = case lookup v s of
Just t -> appargs t
_ -> TVar v ts'
where ts' = subst s ts
appargs (TCon c ts) = norm c (ts++ts')
appargs (TVar v ts) = TVar v (ts++ts')
appargs (TThis i) = TThis i
norm (Prim Class _) [t] = tClos t [tInt]
norm (Prim Request _) [t] = tClos t [tInt]
norm (Prim Cmd _) [s,t] = tClos t [tRef s]
norm c ts = TCon c ts
subst s (TThis i) = TThis i
instance Subst Exp Name AType where
subst s (ESel e l) = ESel (subst s e) l
subst s (ENew x ts bs) = ENew x (subst s ts) (subst s bs)
subst s (ECall x ts es) = ECall x (subst s ts) (subst s es)
subst s (EEnter e f ts es) = EEnter (subst s e) f (subst s ts) (subst s es)
subst s (ECast t e) = ECast (subst s t) (subst s e)
subst s e = e
instance Subst Bind Name AType where
subst s (Val t e) = Val (subst s t) (subst s e)
subst s (Fun vs t te c) = Fun vs (subst s t) (subst s te) (subst s c) -- NOTE: no alpha-conversion!!
instance Subst Cmd Name AType where
subst s (CRet e) = CRet (subst s e)
subst s (CRun e c) = CRun (subst s e) (subst s c)
subst s (CBind r bs c) = CBind r (subst s bs) (subst s c)
subst s (CUpd x e c) = CUpd x (subst s e) (subst s c)
subst s (CUpdS e x e' c) = CUpdS (subst s e) x (subst s e') (subst s c)
subst s (CUpdA e i e' c) = CUpdA (subst s e) (subst s i) (subst s e') (subst s c)
subst s (CSwitch e alts) = CSwitch (subst s e) (subst s alts)
subst s (CSeq c c') = CSeq (subst s c) (subst s c')
subst s (CBreak) = CBreak
subst s (CRaise e) = CRaise (subst s e)
subst s (CWhile e c c') = CWhile (subst s e) (subst s c) (subst s c')
subst s (CCont) = CCont
instance Subst Alt Name AType where
subst s (ACon x vs te c) = ACon x vs (subst s te) (subst s c)
subst s (ALit l c) = ALit l (subst s c)
subst s (AWild c) = AWild (subst s c)
-- Tentative concrete syntax ------------------------------------------------------------------------------
instance Pr Module where
pr (Module m ns es ds bs) =text "module" <+> prId2 m <+> text "where" $$
text "import" <+> hpr ',' ns $$
text "extern" <+> vpr es $$
vpr ds $$
vpr bs
instance Pr (Module,a) where
pr (m,_) = pr m
instance Pr (Name, Decl) where
pr (c, Struct vs te lnk) = text "struct" <+> prId2 c <+> prTyvars vs <+> text "{" $$
nest 4 (vpr te) $$
text "}" <+> pr lnk
prTyvars [] = empty
prTyvars vs = text "<" <> commasep pr vs <> text ">"
instance Pr Link where
pr Top = empty
pr Union = text "union"
pr (Extends n ts []) = text "extends" <+> pr (TCon n ts)
pr (Extends n ts vs) = text "extends" <+> pr (TCon n ts) <+> text "hiding" <+> prTyvars vs
instance Pr (Name, Type) where
pr (x, ValT t) = pr t <+> prId2 x <> text ";"
pr (x, FunT vs ts t) = prTyvars vs <+> pr t <+> prId2 x <> parens (commasep pr ts) <> text ";"
instance Pr AType where
pr (TCon (Prim CLOS _) ts0) = prTyvars vs <+> prId2 (prim CLOS) <> prTyargs (t:ts)
where (vs,ts,t) = decodeCLOS ts0
pr (TCon c ts) = prId2 c <> prTyargs ts
pr (TVar v ts) = prId2 v <> prTyargs ts
pr (TThis i) = text ('#' : show i)
prTyargs [] = empty
prTyargs ts = text "<" <> commasep pr ts <> text ">"
instance Pr (Name, AType) where
pr (x, t) = pr t <+> prId2 x
instance Pr (Name, Bind) where
pr (x, Val t e) = pr t <+> prId2 x <+> text "=" <+> pr e <> text ";"
pr (x, Fun vs t te c) = prTyvars vs <+> pr t <+> prId2 x <+> parens (commasep pr te) <+> text "{" $$
nest 4 (pr c) $$
text "}"
instance Pr Cmd where
pr (CRet e) = text "return" <+> pr e <> text ";"
pr (CRun e c) = pr e <> text ";" $$
pr c
pr (CBind r bs c) = vpr bs $$
pr c
pr (CUpd x e c) = prId2 x <+> text "=" <+> pr e <> text ";" $$
pr c
pr (CUpdS e x e' c) = pr (ESel e x) <+> text "=" <+> pr e' <> text ";" $$
pr c
pr (CUpdA e i e' c) = pr (ECall (prim IndexArray) [] [e,i]) <+> text "=" <+> pr e' <> text ";" $$
pr c
pr (CSwitch e alts) = text "switch" <+> parens (pr e) <+> text "{" $$
nest 2 (vpr alts) $$
text "}"
pr (CSeq c1 c2) = pr c1 $$
pr c2
pr (CBreak) = text "break;"
pr (CRaise e) = text "RAISE" <> parens (pr e) <> text ";"
pr (CWhile e c c') = text "while" <+> parens (pr e) <+> text "{" $$
nest 4 (pr c) $$
text "}" $$
pr c'
pr (CCont) = text "continue;"
prScope (CRaise e) = pr (CRaise e)
prScope (CBreak) = pr CBreak
prScope (CCont) = pr CCont
prScope (CRet x) = pr (CRet x)
prScope c = text "{" <+> pr c $$
text "}"
instance Pr Alt where
pr (ACon x vs [] c) = prId2 x <+> prTyvars vs <> text ":" <+> prScope c
pr (ACon x vs te c) = prId2 x <+> prTyvars vs <+> parens (commasep pr te) <> text ":" <+> prScope c
pr (ALit l c) = pr l <> text ":" <+> prScope c
pr (AWild c) = text "default:" <+> prScope c
instance Pr Exp where
prn 0 (ECall x [] [e1,e2])
| isInfix x && isSym x = prn 1 e1 <+> prId2 x <+> prn 1 e2
prn 0 (ELit l) = prn 0 l
prn 0 e = prn 1 e
prn 1 (ECall x [] [e])
| isUnaryOp x && isSym x = prId2 x <> prn 1 e
prn 1 (ECast t e) = parens (pr t) <> prn 1 e
prn 1 e = prn 2 e
prn 2 (EVar x) = prId2 x
prn 2 (EThis) = text "this"
prn 2 (ELit l) = prn 1 l
prn 2 (ENew x ts bs)
| all isVal bs = text "new" <+> prId2 x <> prTyargs ts <+> text "{" <> commasep prInit bs <> text "}"
prn 2 (ENew x ts bs) = text "new" <+> prId2 x <> prTyargs ts <+> text "{" $$
nest 4 (vpr bs) $$
text "}"
prn 2 (ECall x ts es) = prId2 x <> prTyargs ts <> parens (commasep pr es)
prn 2 (ESel e l) = prn 2 e <> text "->" <> prId2 l
prn 2 (EEnter e x ts es) = prn 2 e <> text "->" <> prId2 x <> prTyargs ts <> parens (commasep pr es)
prn 2 e = parens (prn 0 e)
prInit (x, Val t e) = prId2 x <+> text "=" <+> pr e
prInit b = pr b
-- HasPos --------------------
instance HasPos AType where
posInfo (TCon n ts) = between (posInfo n) (posInfo ts)
posInfo (TVar n ts) = between (posInfo n) (posInfo ts)
posInfo (TThis i) = Unknown
-- Binary --------------------
{-
instance Binary Module where
put (Module a b c d) = put a >> put b >> put c >> put d
get = get >>= \a -> get >>= \b -> get >>= \c -> get >>= \d -> return (Module a b c d)
-}
instance Binary Decl where
put (Struct a b c) = putWord8 0 >> put a >> put b >> put c
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> get >>= \b -> get >>= \c -> return (Struct a b c)
_ -> fail "no parse"
instance Binary Link where
put Top = putWord8 0
put Union = putWord8 1
put (Extends a b c) = putWord8 2 >> put a >> put b >> put c
get = do
tag_ <- getWord8
case tag_ of
0 -> return Top
1 -> return Union
2 -> get >>= \a -> get >>= \b -> get >>= \c -> return (Extends a b c)
_ -> fail "no parse"
{-
instance Binary Bind where
put (Val a b) = putWord8 0 >> put a >> put b
put (Fun a b c) = putWord8 1 >> put a >> put b >> put c
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> get >>= \b -> return (Val a b)
1 -> get >>= \a -> get >>= \b -> get >>= \c -> return (Fun a b c)
_ -> fail "no parse"
-}
instance Binary Type where
put (ValT a) = putWord8 0 >> put a
put (FunT a b c) = putWord8 1 >> put a >> put b >> put c
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> return (ValT a)
1 -> get >>= \a -> get >>= \b -> get >>= \c -> return (FunT a b c)
_ -> fail "no parse"
instance Binary AType where
put (TCon a b) = putWord8 0 >> put a >> put b
put (TVar a b) = putWord8 1 >> put a >> put b
put (TThis a) = putWord8 2 >> put a
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> get >>= \b -> return (TCon a b)
1 -> get >>= \a -> get >>= \b -> return (TVar a b)
2 -> get >>= \a -> return (TThis a)
_ -> fail "no parse"
|
mattias-lundell/timber-llvm
|
src/Kindle.hs
|
bsd-3-clause
| 45,530
| 0
| 25
| 20,628
| 14,175
| 7,074
| 7,101
| 629
| 3
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module API.IB.Parse where
import Control.Applicative
import Control.Monad
import Data.Attoparsec.ByteString.Char8
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BC
import Data.Map (Map)
import qualified Data.Map as Map (lookup)
import Data.Maybe
import Data.String
import Data.Time
import Data.Time.Clock.POSIX
import Data.Time.Zones
import Prelude hiding (takeWhile)
import API.IB.Constant
import API.IB.Util
-- -----------------------------------------------------------------------------
parseField :: Parser a -> Parser a
parseField p = p <* char sepC
parseEmptyField :: Parser ()
parseEmptyField = char sepC *> return ()
parseMaybeEmptyField :: Parser a -> Parser (Maybe a)
parseMaybeEmptyField p = mconcat
[ parseEmptyField *> return Nothing
, Just <$> parseField p
, parseStringField *> return Nothing
]
parseIntField :: Parser Int
parseIntField = parseField decimal
parseIntField' :: Parser Int
parseIntField' = (parseEmptyField *> return 0) <|> parseIntField
parseSignedIntField :: Parser Int
parseSignedIntField = parseField $ signed decimal
parseMaybeIntField :: Parser (Maybe Int)
parseMaybeIntField = parseMaybeEmptyField decimal
parseByteStringField :: Parser ByteString
parseByteStringField = parseField parseByteString
parseStringField :: Parser String
parseStringField = parseField parseString
parseMaybeStringField :: Parser (Maybe String)
parseMaybeStringField = parseMaybeEmptyField parseString
parseDoubleField :: Parser Double
parseDoubleField = parseField double
parseDoubleField' :: Parser Double
parseDoubleField' = (parseEmptyField *> return 0) <|> parseDoubleField
parseMaybeDoubleField :: Parser (Maybe Double)
parseMaybeDoubleField = parseMaybeEmptyField double
parseMaybeDoubleField' :: Parser (Maybe Double)
parseMaybeDoubleField' =
(string "1.7976931348623157E308" *> return Nothing) <|>
parseMaybeDoubleField
parseSignedDoubleField :: Parser Double
parseSignedDoubleField = parseField $ signed double
parseBoolBinaryField :: Parser Bool
parseBoolBinaryField = parseField $ (char '0' *> return False) <|> (char '1' *> return True)
parseBoolStringField :: Parser Bool
parseBoolStringField = parseField $ (stringCI "false" *> return False) <|> (stringCI "true" *> return True)
parseUTCTimeField :: Parser UTCTime
parseUTCTimeField = (posixSecondsToUTCTime . realToFrac) <$> parseIntField
parseByteString :: Parser ByteString
parseByteString = takeWhile (/= sepC)
parseString :: Parser String
parseString = BC.unpack <$> parseByteString
parseMaybe :: Parser a -> Parser (Maybe a)
parseMaybe p = (Just <$> p) <|> (parseStringField *> return Nothing)
parseStringToEnum :: (Read a) => Parser a
parseStringToEnum = do
s <- parseString
case stringToEnum s of
Just s' -> return s'
Nothing -> fail ""
parseStringToEnumField :: (Read a) => Parser a
parseStringToEnumField = parseField parseStringToEnum
parseDayYYYYMMDD :: Parser Day
parseDayYYYYMMDD = decimal >>= maybe empty return . decode
where
decode i =
let year = i `quot` 10000
month = fromIntegral $ (i - year * 10000) `quot` 100
day = fromIntegral $ i `mod` 100
in fromGregorianValid year month day
parseDayYYYYMMDD' :: Parser (Maybe Day)
parseDayYYYYMMDD' = parseMaybeEmptyField parseDayYYYYMMDD
parseTimeOfDayHHMMSS :: Parser TimeOfDay
parseTimeOfDayHHMMSS = do
t <- makeTimeOfDayValid <$>
(decimal <* char ':') <*>
(decimal <* char ':') <*>
(fromInteger <$> decimal)
maybe empty return t
parseTimeOfDayHHMM :: Parser TimeOfDay
parseTimeOfDayHHMM = do
t <- makeTimeOfDayValid <$>
(decimal <* char ':') <*>
decimal <*>
pure 0
maybe empty return t
parseTZ :: Map String TZ -> Parser TZ
parseTZ tzs = do
s <- parseString
let tz = Map.lookup s tzs
maybe (fail "") return tz
|
cmahon/interactive-brokers
|
library/API/IB/Parse.hs
|
bsd-3-clause
| 4,128
| 0
| 15
| 855
| 1,101
| 568
| 533
| 101
| 2
|
module Test.PartialDeduction where
import Program.List (nil, revAcco, reverso)
import Program.Programs (doubleAppendo)
import qualified Program.Prop
import Syntax
import Transformer.PD
dA = Program doubleAppendo $ fresh ["x", "y", "z", "r"] (call "doubleAppendo" [V "x", V "y", V "z", V "r"])
revAcco' = Program revAcco $ fresh ["x", "y"] (call "revacco" [V "x", nil, V "y"])
rev = Program reverso $ fresh ["x", "y"] (call "reverso" [V "x", V "y"])
prop = Program.Prop.query3
unit_partialDeductionTest = do
transform "da" dA
transform "rev" rev
transform "revAcco" revAcco'
transform "prop" prop
|
kajigor/uKanren_transformations
|
test/auto/Test/PartialDeduction.hs
|
bsd-3-clause
| 652
| 0
| 10
| 141
| 241
| 127
| 114
| 15
| 1
|
{-# Language OverloadedStrings #-}
{-# Language FlexibleContexts #-}
{-# Language NoImplicitPrelude #-}
{-# Language DataKinds #-}
module Main where
import ClassyPrelude hiding (Handler)
import Data.Acid.Database
import Config
import Data.Yaml.Config
import Data.Yaml
import Data.Aeson (FromJSON, ToJSON)
import GHC.Generics (Generic)
import Data.Text (Text)
import Network.IRC.Runner (IrcInfo(..))
import qualified Network.IRC.Runner as IRC
import Plugin
import Hooks.Algebra
import Hooks.Eval
import Hooks.Title
import Hooks.Weather
import Hooks.PlusOne
import Hooks.Chatter
import Network.IRC
import Types
import qualified Network.IRC as IRC
import qualified Data.Text as T
import Data.Time
import Control.Lens ((^.), (^..))
import Data.Text.Lens (packed, unpacked)
import Control.Concurrent.Async (wait)
import Text.Printf (printf)
adminHook (PrivMsg _nick _target msg) =
case T.words msg of
["!join", channel] -> sendMessage (Join channel)
_ -> return ()
adminHook _ = return ()
uptimeHook :: InMsg -> Handler UTCTime ()
uptimeHook (PrivMsg nick target "!uptime") = do
started <- asks readStateApp
now <- liftIO getCurrentTime
let seconds = floor $ diffUTCTime now started :: Integer
(days, seconds') = seconds `quotRem` 86400
(hours, seconds'') = seconds' `quotRem` 3600
(minutes, seconds''') = seconds'' `quotRem` 60
uptime = printf "%d days, %d hours, %d minutes, %d seconds" days hours minutes seconds'''
respondTo nick target $ T.pack uptime
uptimeHook _ = return ()
base = Plugin () (const $ return ())
-- myPlugins :: HasDarkskyApiKey s String => UTCTime -> AcidState IrcState -> s -> Plugins InMsg '[(), AcidState IrcState, AcidState IrcState, ApiKey, UTCTime]
myPlugins start acid conf = base adminHook
:> Plugin acid (const $ return ()) urlTitleHook
:> Plugin acid (const $ return ()) plusOneHook
:> Plugin (ApiKey (conf ^. darkskyApiKey)) (const $ return ()) weatherHook
:> Plugin (ApiKey (conf ^. darkskyApiKey)) (const $ return ()) chatterHook
:> Plugin start (const $ return ()) uptimeHook
:> Plugin EvalState (const $ return ()) evalHook
:> PNil
withAcid :: FilePath -> IrcState -> (AcidState IrcState -> IO c) -> IO c
withAcid path initial = bracket (openLocalStateFrom path initial) createCheckpointAndClose
main :: IO ()
main = withAcid "state" initialIrcState $ \acid -> do
now <- getCurrentTime
conf <- loadYamlSettings ["config/irc.yaml"] [] ignoreEnv :: IO Configuration
let runConfs = [(defaultConf conn) {hooks = myPlugins now acid $ conf ^. hooksConf} | conn <- conf ^. connection]
threads <- forM runConfs $ \c ->
async . defaultMain $ c
mapM_ wait threads
|
MasseR/FreeIrc
|
src/Main.hs
|
bsd-3-clause
| 2,866
| 0
| 17
| 649
| 866
| 462
| 404
| 66
| 2
|
-----------------------------------------------------------------------------
-- |
-- Module : System.Win32.Com.Exception
-- Copyright : (c) 2009, Sigbjorn Finne
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : sof@forkIO.com
-- Stability : provisional
-- Portability : portable
--
-- Representing and working with COM's 'exception model' (@HRESULT@s) in Haskell.
-- Failures in COM method calls are mapped into 'Control.Exception' Haskell exceptions,
-- providing convenient handlers to catch and throw these.
--
-----------------------------------------------------------------------------
module System.Win32.Com.Exception where
import System.Win32.Com.HDirect.HDirect hiding ( readFloat )
import System.Win32.Com.Base
import Data.Int
import Data.Word
import Data.Bits
import Data.Dynamic
import Data.Maybe ( isJust, fromMaybe )
import Numeric ( showHex )
import System.IO.Error ( ioeGetErrorString )
#if BASE == 3
import GHC.IOBase
import Control.Exception
-- | @act `catchComException` (ex -> hdlr ex)@ performs the
-- IO action @act@, but catches any IO or COM exceptions @ex@,
-- passing them to the handler @hdlr@.
catchComException :: IO a -> (Com_Exception -> IO a) -> IO a
catchComException act hdlr =
Control.Exception.catch act
(\ ex ->
case ex of
DynException d ->
case fromDynamic d of
Just ce -> hdlr (Right ce)
_ -> throwIO ex
IOException ioe -> hdlr (Left ioe)
_ -> throwIO ex)
catch_ce_ :: IO a -> (Maybe ComException -> IO a) -> IO a
catch_ce_ act hdlr =
catchComException
act
(\ e ->
case e of
Left ioe -> hdlr Nothing
Right ce -> hdlr (Just ce))
#else
import Control.Exception
-- | @act `catchComException` (ex -> hdlr ex)@ performs the
-- IO action @act@, but catches any IO or COM exceptions @ex@,
-- passing them to the handler @hdlr@.
catchComException :: IO a -> (Com_Exception -> IO a) -> IO a
catchComException act hdlr =
Control.Exception.catch act
(\ e ->
case fromException e of
Just ioe -> hdlr (Left ioe)
_ -> case fromException e of
Just d -> hdlr (Right d)
_ -> throwIO e)
catch_ce_ :: IO a -> (Maybe ComException -> IO a) -> IO a
catch_ce_ act hdlr =
catchComException
act
(\ e ->
case e of
Left ioe -> hdlr Nothing
Right ce -> hdlr (Just ce))
#endif
-- | @Com_Exception@ is either an 'IOException' or 'ComException';
-- no attempt is made to embed one inside the other.
type Com_Exception = Either IOException ComException
-- | @throwIOComException ex@ raises/throws the exception @ex@;
-- @ex@ is either an 'IOException' or a 'ComException'.
throwIOComException :: Com_Exception -> IO a
throwIOComException (Left e) = ioError e
throwIOComException (Right ce) = throwComException ce
-- | @check2HR hr@ triggers a COM exception if the HRESULT
-- @hr@ represent an error condition. The current /last error/
-- value embedded in the exception gives more information about
-- cause.
check2HR :: HRESULT -> IO ()
check2HR hr
| succeeded hr = return ()
| otherwise = do
dw <- getLastError
coFailHR (word32ToInt32 dw)
-- | @checkBool mbZero@ raises a COM exception if @mbZero@ is equal
-- to...zero. The /last error/ is embedded inside the exception.
checkBool :: Int32 -> IO ()
checkBool flg
| flg /=0 = return ()
| otherwise = do
dw <- getLastError
coFailHR (word32ToInt32 dw)
-- | @returnHR act@ runs the IO action @act@, catching any
-- COM exceptions. Success or failure is then mapped back into
-- the corresponding HRESULT. In the case of success, 's_OK'.
returnHR :: IO () -> IO HRESULT
returnHR act =
catch_ce_
(act >> return s_OK)
(\ mb_hr -> return (maybe failure toHR mb_hr))
where
toHR ComException{comException=(ComError hr)} = hr
-- better return codes could easily be imagined..
failure = e_FAIL
-- | @isCoError e@ returns @True@ for COM exceptions; @False@
-- for IO exception values.
isCoError :: Com_Exception -> Bool
isCoError Right{} = True
isCoError Left{} = False
-- | @coGetException ei@ picks out the COM exception @ei@, if one.
coGetException :: Com_Exception -> Maybe ComException
coGetException (Right ce) = Just ce
coGetException _ = Nothing
-- | @coGetException ei@ picks out the COM HRESULT from the exception, if any.
coGetErrorHR :: Com_Exception -> Maybe HRESULT
coGetErrorHR Left{} = Nothing
coGetErrorHR (Right ce) = Just (case comException ce of (ComError hr) -> hr)
-- | @coGetException ei@ returns a user-friendlier representation of the @ei@ exception.
coGetErrorString :: Com_Exception -> String
coGetErrorString (Left ioe) = ioeGetErrorString ioe
coGetErrorString (Right ce) =
comExceptionMsg ce ++
showParen True (showHex (int32ToWord32 (comExceptionHR ce))) ""
printComError :: Com_Exception -> IO ()
printComError ce = putStrLn (coGetErrorString ce)
-- | An alias to 'coGetErrorString'.
hresultToString :: HRESULT -> IO String
hresultToString = stringFromHR
coAssert :: Bool -> String -> IO ()
coAssert True msg = return ()
coAssert False msg = coFail msg
coOnFail :: IO a -> String -> IO a
coOnFail io msg = catchComException io
(\ e ->
case e of
Left ioe -> coFail (msg ++ ": " ++ ioeGetErrorString ioe)
Right ce -> coFail (msg ++ ": " ++ comExceptionMsg ce))
-- | @coFail msg@ raised the @E_FAIL@ COM exception along with
-- the descriptive string @msg@.
coFail :: String -> IO a
coFail = coFailWithHR e_FAIL
-- | @s_OK@ and @s_FALSE@ are the boolean values encoded as 'HRESULT's.
s_FALSE, s_OK :: HRESULT
s_OK = 0
s_FALSE = 1
nOERROR :: HRESULT
nOERROR = 0
nO_ERROR :: HRESULT
nO_ERROR = 0
sEVERITY_ERROR :: Int32
sEVERITY_ERROR = 1
sEVERITY_SUCCESS :: Int32
sEVERITY_SUCCESS = 0
succeeded :: HRESULT -> Bool
succeeded hr = hr >=0
winErrorToHR :: Int32 -> HRESULT
winErrorToHR 0 = 0
winErrorToHR x = (fACILITY_WIN32 `shiftL` 16) .|. (bit 31) .|. (x .&. 0xffff)
hRESULT_CODE :: HRESULT -> Int32
hRESULT_CODE hr = hr .&. (fromIntegral 0xffff)
hRESULT_FACILITY :: HRESULT -> Int32
hRESULT_FACILITY hr = (hr `shiftR` 16) .&. 0x1fff
hRESULT_SEVERITY :: HRESULT -> Int32
hRESULT_SEVERITY hr = (hr `shiftR` 31) .&. 0x1
mkHRESULT :: Int32 -> Int32 -> Int32 -> HRESULT
mkHRESULT sev fac code =
word32ToInt32 (
((int32ToWord32 sev) `shiftL` 31) .|.
((int32ToWord32 fac) `shiftL` 16) .|.
(int32ToWord32 code)
)
cAT_E_CATIDNOEXIST :: HRESULT
cAT_E_CATIDNOEXIST = word32ToInt32 (0x80040160 ::Word32)
cAT_E_FIRST :: HRESULT
cAT_E_FIRST = word32ToInt32 (0x80040160 ::Word32)
cAT_E_LAST :: HRESULT
cAT_E_LAST = word32ToInt32 (0x80040161 ::Word32)
cAT_E_NODESCRIPTION :: HRESULT
cAT_E_NODESCRIPTION = word32ToInt32 (0x80040161 ::Word32)
cLASS_E_CLASSNOTAVAILABLE :: HRESULT
cLASS_E_CLASSNOTAVAILABLE = word32ToInt32 (0x80040111 ::Word32)
cLASS_E_NOAGGREGATION :: HRESULT
cLASS_E_NOAGGREGATION = word32ToInt32 (0x80040110 ::Word32)
cLASS_E_NOTLICENSED :: HRESULT
cLASS_E_NOTLICENSED = word32ToInt32 (0x80040112 ::Word32)
cO_E_ACCESSCHECKFAILED :: HRESULT
cO_E_ACCESSCHECKFAILED = word32ToInt32 (0x80040207 ::Word32)
cO_E_ACESINWRONGORDER :: HRESULT
cO_E_ACESINWRONGORDER = word32ToInt32 (0x80040217 ::Word32)
cO_E_ACNOTINITIALIZED :: HRESULT
cO_E_ACNOTINITIALIZED = word32ToInt32 (0x8004021B ::Word32)
cO_E_ALREADYINITIALIZED :: HRESULT
cO_E_ALREADYINITIALIZED = word32ToInt32 (0x800401F1 ::Word32)
cO_E_APPDIDNTREG :: HRESULT
cO_E_APPDIDNTREG = word32ToInt32 (0x800401FE ::Word32)
cO_E_APPNOTFOUND :: HRESULT
cO_E_APPNOTFOUND = word32ToInt32 (0x800401F5 ::Word32)
cO_E_APPSINGLEUSE :: HRESULT
cO_E_APPSINGLEUSE = word32ToInt32 (0x800401F6 ::Word32)
cO_E_BAD_PATH :: HRESULT
cO_E_BAD_PATH = word32ToInt32 (0x80080004 ::Word32)
cO_E_BAD_SERVER_NAME :: HRESULT
cO_E_BAD_SERVER_NAME = word32ToInt32 (0x80004014 ::Word32)
cO_E_CANTDETERMINECLASS :: HRESULT
cO_E_CANTDETERMINECLASS = word32ToInt32 (0x800401F2 ::Word32)
cO_E_CANT_REMOTE :: HRESULT
cO_E_CANT_REMOTE = word32ToInt32 (0x80004013 ::Word32)
cO_E_CLASSSTRING :: HRESULT
cO_E_CLASSSTRING = word32ToInt32 (0x800401F3 ::Word32)
cO_E_CLASS_CREATE_FAILED :: HRESULT
cO_E_CLASS_CREATE_FAILED = word32ToInt32 (0x80080001 ::Word32)
cO_E_CLSREG_INCONSISTENT :: HRESULT
cO_E_CLSREG_INCONSISTENT = word32ToInt32 (0x8000401F ::Word32)
cO_E_CONVERSIONFAILED :: HRESULT
cO_E_CONVERSIONFAILED = word32ToInt32 (0x8004020B ::Word32)
cO_E_CREATEPROCESS_FAILURE :: HRESULT
cO_E_CREATEPROCESS_FAILURE = word32ToInt32 (0x80004018 ::Word32)
cO_E_DECODEFAILED :: HRESULT
cO_E_DECODEFAILED = word32ToInt32 (0x8004021A ::Word32)
cO_E_DLLNOTFOUND :: HRESULT
cO_E_DLLNOTFOUND = word32ToInt32 (0x800401F8 ::Word32)
cO_E_ERRORINAPP :: HRESULT
cO_E_ERRORINAPP = word32ToInt32 (0x800401F7 ::Word32)
cO_E_ERRORINDLL :: HRESULT
cO_E_ERRORINDLL = word32ToInt32 (0x800401F9 ::Word32)
cO_E_EXCEEDSYSACLLIMIT :: HRESULT
cO_E_EXCEEDSYSACLLIMIT = word32ToInt32 (0x80040216 ::Word32)
cO_E_FAILEDTOCLOSEHANDLE :: HRESULT
cO_E_FAILEDTOCLOSEHANDLE = word32ToInt32 (0x80040215 ::Word32)
cO_E_FAILEDTOCREATEFILE :: HRESULT
cO_E_FAILEDTOCREATEFILE = word32ToInt32 (0x80040214 ::Word32)
cO_E_FAILEDTOGENUUID :: HRESULT
cO_E_FAILEDTOGENUUID = word32ToInt32 (0x80040213 ::Word32)
cO_E_FAILEDTOGETSECCTX :: HRESULT
cO_E_FAILEDTOGETSECCTX = word32ToInt32 (0x80040201 ::Word32)
cO_E_FAILEDTOGETTOKENINFO :: HRESULT
cO_E_FAILEDTOGETTOKENINFO = word32ToInt32 (0x80040203 ::Word32)
cO_E_FAILEDTOGETWINDIR :: HRESULT
cO_E_FAILEDTOGETWINDIR = word32ToInt32 (0x80040211 ::Word32)
cO_E_FAILEDTOIMPERSONATE :: HRESULT
cO_E_FAILEDTOIMPERSONATE = word32ToInt32 (0x80040200 ::Word32)
cO_E_FAILEDTOOPENPROCESSTOKEN :: HRESULT
cO_E_FAILEDTOOPENPROCESSTOKEN = word32ToInt32 (0x80040219 ::Word32)
cO_E_FAILEDTOOPENTHREADTOKEN :: HRESULT
cO_E_FAILEDTOOPENTHREADTOKEN = word32ToInt32 (0x80040202 ::Word32)
cO_E_FAILEDTOQUERYCLIENTBLANKET :: HRESULT
cO_E_FAILEDTOQUERYCLIENTBLANKET = word32ToInt32 (0x80040205 ::Word32)
cO_E_FAILEDTOSETDACL :: HRESULT
cO_E_FAILEDTOSETDACL = word32ToInt32 (0x80040206 ::Word32)
cO_E_FIRST :: HRESULT
cO_E_FIRST = word32ToInt32 (0x800401F0 ::Word32)
cO_E_IIDREG_INCONSISTENT :: HRESULT
cO_E_IIDREG_INCONSISTENT = word32ToInt32 (0x80004020 ::Word32)
cO_E_IIDSTRING :: HRESULT
cO_E_IIDSTRING = word32ToInt32 (0x800401F4 ::Word32)
cO_E_INCOMPATIBLESTREAMVERSION :: HRESULT
cO_E_INCOMPATIBLESTREAMVERSION = word32ToInt32 (0x80040218 ::Word32)
cO_E_INIT_CLASS_CACHE :: HRESULT
cO_E_INIT_CLASS_CACHE = word32ToInt32 (0x80004009 ::Word32)
cO_E_INIT_MEMORY_ALLOCATOR :: HRESULT
cO_E_INIT_MEMORY_ALLOCATOR = word32ToInt32 (0x80004008 ::Word32)
cO_E_INIT_ONLY_SINGLE_THREADED :: HRESULT
cO_E_INIT_ONLY_SINGLE_THREADED = word32ToInt32 (0x80004012 ::Word32)
cO_E_INIT_RPC_CHANNEL :: HRESULT
cO_E_INIT_RPC_CHANNEL = word32ToInt32 (0x8000400A ::Word32)
cO_E_INIT_SCM_EXEC_FAILURE :: HRESULT
cO_E_INIT_SCM_EXEC_FAILURE = word32ToInt32 (0x80004011 ::Word32)
cO_E_INIT_SCM_FILE_MAPPING_EXISTS :: HRESULT
cO_E_INIT_SCM_FILE_MAPPING_EXISTS = word32ToInt32 (0x8000400F ::Word32)
cO_E_INIT_SCM_MAP_VIEW_OF_FILE :: HRESULT
cO_E_INIT_SCM_MAP_VIEW_OF_FILE = word32ToInt32 (0x80004010 ::Word32)
cO_E_INIT_SCM_MUTEX_EXISTS :: HRESULT
cO_E_INIT_SCM_MUTEX_EXISTS = word32ToInt32 (0x8000400E ::Word32)
cO_E_INIT_SHARED_ALLOCATOR :: HRESULT
cO_E_INIT_SHARED_ALLOCATOR = word32ToInt32 (0x80004007 ::Word32)
cO_E_INIT_TLS :: HRESULT
cO_E_INIT_TLS = word32ToInt32 (0x80004006 ::Word32)
cO_E_INIT_TLS_CHANNEL_CONTROL :: HRESULT
cO_E_INIT_TLS_CHANNEL_CONTROL = word32ToInt32 (0x8000400C ::Word32)
cO_E_INIT_TLS_SET_CHANNEL_CONTROL :: HRESULT
cO_E_INIT_TLS_SET_CHANNEL_CONTROL = word32ToInt32 (0x8000400B ::Word32)
cO_E_INIT_UNACCEPTED_USER_ALLOCATOR :: HRESULT
cO_E_INIT_UNACCEPTED_USER_ALLOCATOR = word32ToInt32 (0x8000400D ::Word32)
cO_E_INVALIDSID :: HRESULT
cO_E_INVALIDSID = word32ToInt32 (0x8004020A ::Word32)
cO_E_LAST :: HRESULT
cO_E_LAST = word32ToInt32 (0x800401FF ::Word32)
cO_E_LAUNCH_PERMSSION_DENIED :: HRESULT
cO_E_LAUNCH_PERMSSION_DENIED = word32ToInt32 (0x8000401B ::Word32)
cO_E_LOOKUPACCNAMEFAILED :: HRESULT
cO_E_LOOKUPACCNAMEFAILED = word32ToInt32 (0x8004020F ::Word32)
cO_E_LOOKUPACCSIDFAILED :: HRESULT
cO_E_LOOKUPACCSIDFAILED = word32ToInt32 (0x8004020D ::Word32)
cO_E_MSI_ERROR :: HRESULT
cO_E_MSI_ERROR = word32ToInt32 (0x80004023 ::Word32)
cO_E_NETACCESSAPIFAILED :: HRESULT
cO_E_NETACCESSAPIFAILED = word32ToInt32 (0x80040208 ::Word32)
cO_E_NOMATCHINGNAMEFOUND :: HRESULT
cO_E_NOMATCHINGNAMEFOUND = word32ToInt32 (0x8004020E ::Word32)
cO_E_NOMATCHINGSIDFOUND :: HRESULT
cO_E_NOMATCHINGSIDFOUND = word32ToInt32 (0x8004020C ::Word32)
cO_E_NOTINITIALIZED :: HRESULT
cO_E_NOTINITIALIZED = word32ToInt32 (0x800401F0 ::Word32)
cO_E_NOT_SUPPORTED :: HRESULT
cO_E_NOT_SUPPORTED = word32ToInt32 (0x80004021 ::Word32)
cO_E_OBJISREG :: HRESULT
cO_E_OBJISREG = word32ToInt32 (0x800401FC ::Word32)
cO_E_OBJNOTCONNECTED :: HRESULT
cO_E_OBJNOTCONNECTED = word32ToInt32 (0x800401FD ::Word32)
cO_E_OBJNOTREG :: HRESULT
cO_E_OBJNOTREG = word32ToInt32 (0x800401FB ::Word32)
cO_E_OBJSRV_RPC_FAILURE :: HRESULT
cO_E_OBJSRV_RPC_FAILURE = word32ToInt32 (0x80080006 ::Word32)
cO_E_OLE1DDE_DISABLED :: HRESULT
cO_E_OLE1DDE_DISABLED = word32ToInt32 (0x80004016 ::Word32)
cO_E_PATHTOOLONG :: HRESULT
cO_E_PATHTOOLONG = word32ToInt32 (0x80040212 ::Word32)
cO_E_RELEASED :: HRESULT
cO_E_RELEASED = word32ToInt32 (0x800401FF ::Word32)
cO_E_RELOAD_DLL :: HRESULT
cO_E_RELOAD_DLL = word32ToInt32 (0x80004022 ::Word32)
cO_E_REMOTE_COMMUNICATION_FAILURE :: HRESULT
cO_E_REMOTE_COMMUNICATION_FAILURE = word32ToInt32 (0x8000401D ::Word32)
cO_E_RUNAS_CREATEPROCESS_FAILURE :: HRESULT
cO_E_RUNAS_CREATEPROCESS_FAILURE = word32ToInt32 (0x80004019 ::Word32)
cO_E_RUNAS_LOGON_FAILURE :: HRESULT
cO_E_RUNAS_LOGON_FAILURE = word32ToInt32 (0x8000401A ::Word32)
cO_E_RUNAS_SYNTAX :: HRESULT
cO_E_RUNAS_SYNTAX = word32ToInt32 (0x80004017 ::Word32)
cO_E_SCM_ERROR :: HRESULT
cO_E_SCM_ERROR = word32ToInt32 (0x80080002 ::Word32)
cO_E_SCM_RPC_FAILURE :: HRESULT
cO_E_SCM_RPC_FAILURE = word32ToInt32 (0x80080003 ::Word32)
cO_E_SERVER_EXEC_FAILURE :: HRESULT
cO_E_SERVER_EXEC_FAILURE = word32ToInt32 (0x80080005 ::Word32)
cO_E_SERVER_START_TIMEOUT :: HRESULT
cO_E_SERVER_START_TIMEOUT = word32ToInt32 (0x8000401E ::Word32)
cO_E_SERVER_STOPPING :: HRESULT
cO_E_SERVER_STOPPING = word32ToInt32 (0x80080008 ::Word32)
cO_E_SETSERLHNDLFAILED :: HRESULT
cO_E_SETSERLHNDLFAILED = word32ToInt32 (0x80040210 ::Word32)
cO_E_START_SERVICE_FAILURE :: HRESULT
cO_E_START_SERVICE_FAILURE = word32ToInt32 (0x8000401C ::Word32)
cO_E_TRUSTEEDOESNTMATCHCLIENT :: HRESULT
cO_E_TRUSTEEDOESNTMATCHCLIENT = word32ToInt32 (0x80040204 ::Word32)
cO_E_WRONGOSFORAPP :: HRESULT
cO_E_WRONGOSFORAPP = word32ToInt32 (0x800401FA ::Word32)
cO_E_WRONGTRUSTEENAMESYNTAX :: HRESULT
cO_E_WRONGTRUSTEENAMESYNTAX = word32ToInt32 (0x80040209 ::Word32)
cO_E_WRONG_SERVER_IDENTITY :: HRESULT
cO_E_WRONG_SERVER_IDENTITY = word32ToInt32 (0x80004015 ::Word32)
cO_S_FIRST :: HRESULT
cO_S_FIRST = word32ToInt32 (0x000401F0 ::Word32)
cO_S_LAST :: HRESULT
cO_S_LAST = word32ToInt32 (0x000401FF ::Word32)
cO_S_NOTALLINTERFACES :: HRESULT
cO_S_NOTALLINTERFACES = word32ToInt32 (0x00080012 ::Word32)
dISP_E_ARRAYISLOCKED :: HRESULT
dISP_E_ARRAYISLOCKED = word32ToInt32 (0x8002000D ::Word32)
dISP_E_BADCALLEE :: HRESULT
dISP_E_BADCALLEE = word32ToInt32 (0x80020010 ::Word32)
dISP_E_BADINDEX :: HRESULT
dISP_E_BADINDEX = word32ToInt32 (0x8002000B ::Word32)
dISP_E_BADPARAMCOUNT :: HRESULT
dISP_E_BADPARAMCOUNT = word32ToInt32 (0x8002000E ::Word32)
dISP_E_BADVARTYPE :: HRESULT
dISP_E_BADVARTYPE = word32ToInt32 (0x80020008 ::Word32)
dISP_E_DIVBYZERO :: HRESULT
dISP_E_DIVBYZERO = word32ToInt32 (0x80020012 ::Word32)
dISP_E_EXCEPTION :: HRESULT
dISP_E_EXCEPTION = word32ToInt32 (0x80020009 ::Word32)
dISP_E_MEMBERNOTFOUND :: HRESULT
dISP_E_MEMBERNOTFOUND = word32ToInt32 (0x80020003 ::Word32)
dISP_E_NONAMEDARGS :: HRESULT
dISP_E_NONAMEDARGS = word32ToInt32 (0x80020007 ::Word32)
dISP_E_NOTACOLLECTION :: HRESULT
dISP_E_NOTACOLLECTION = word32ToInt32 (0x80020011 ::Word32)
dISP_E_OVERFLOW :: HRESULT
dISP_E_OVERFLOW = word32ToInt32 (0x8002000A ::Word32)
dISP_E_PARAMNOTFOUND :: HRESULT
dISP_E_PARAMNOTFOUND = word32ToInt32 (0x80020004 ::Word32)
dISP_E_PARAMNOTOPTIONAL :: HRESULT
dISP_E_PARAMNOTOPTIONAL = word32ToInt32 (0x8002000F ::Word32)
dISP_E_TYPEMISMATCH :: HRESULT
dISP_E_TYPEMISMATCH = word32ToInt32 (0x80020005 ::Word32)
dISP_E_UNKNOWNINTERFACE :: HRESULT
dISP_E_UNKNOWNINTERFACE = word32ToInt32 (0x80020001 ::Word32)
dISP_E_UNKNOWNLCID :: HRESULT
dISP_E_UNKNOWNLCID = word32ToInt32 (0x8002000C ::Word32)
dISP_E_UNKNOWNNAME :: HRESULT
dISP_E_UNKNOWNNAME = word32ToInt32 (0x80020006 ::Word32)
dV_E_CLIPFORMAT :: HRESULT
dV_E_CLIPFORMAT = word32ToInt32 (0x8004006A ::Word32)
dV_E_DVASPECT :: HRESULT
dV_E_DVASPECT = word32ToInt32 (0x8004006B ::Word32)
dV_E_DVTARGETDEVICE :: HRESULT
dV_E_DVTARGETDEVICE = word32ToInt32 (0x80040065 ::Word32)
dV_E_DVTARGETDEVICE_SIZE :: HRESULT
dV_E_DVTARGETDEVICE_SIZE = word32ToInt32 (0x8004006C ::Word32)
dV_E_FORMATETC :: HRESULT
dV_E_FORMATETC = word32ToInt32 (0x80040064 ::Word32)
dV_E_LINDEX :: HRESULT
dV_E_LINDEX = word32ToInt32 (0x80040068 ::Word32)
dV_E_NOIVIEWOBJECT :: HRESULT
dV_E_NOIVIEWOBJECT = word32ToInt32 (0x8004006D ::Word32)
dV_E_STATDATA :: HRESULT
dV_E_STATDATA = word32ToInt32 (0x80040067 ::Word32)
dV_E_STGMEDIUM :: HRESULT
dV_E_STGMEDIUM = word32ToInt32 (0x80040066 ::Word32)
dV_E_TYMED :: HRESULT
dV_E_TYMED = word32ToInt32 (0x80040069 ::Word32)
e_ABORT :: HRESULT
e_ABORT = word32ToInt32 (0x80004004 ::Word32)
e_ACCESSDENIED :: HRESULT
e_ACCESSDENIED = word32ToInt32 (0x80070005 ::Word32)
e_FAIL :: HRESULT
e_FAIL = word32ToInt32 (0x80004005 ::Word32)
e_HANDLE :: HRESULT
e_HANDLE = word32ToInt32 (0x80070006 ::Word32)
e_INVALIDARG :: HRESULT
e_INVALIDARG = word32ToInt32 (0x80070057 ::Word32)
e_NOINTERFACE :: HRESULT
e_NOINTERFACE = word32ToInt32 (0x80004002 ::Word32)
e_NOTIMPL :: HRESULT
e_NOTIMPL = word32ToInt32 (0x80004001 ::Word32)
e_OUTOFMEMORY :: HRESULT
e_OUTOFMEMORY = word32ToInt32 (0x8007000E ::Word32)
e_PENDING :: HRESULT
e_PENDING = word32ToInt32 (0x8000000A ::Word32)
e_POINTER :: HRESULT
e_POINTER = word32ToInt32 (0x80004003 ::Word32)
e_UNEXPECTED :: HRESULT
e_UNEXPECTED = word32ToInt32 (0x8000FFFF ::Word32)
fACILITY_CERT :: HRESULT
fACILITY_CERT = 11
fACILITY_CONTROL :: HRESULT
fACILITY_CONTROL = 10
fACILITY_DISPATCH :: HRESULT
fACILITY_DISPATCH = 2
fACILITY_INTERNET :: HRESULT
fACILITY_INTERNET = 12
fACILITY_ITF :: HRESULT
fACILITY_ITF = 4
fACILITY_MEDIASERVER :: HRESULT
fACILITY_MEDIASERVER = 13
fACILITY_MSMQ :: HRESULT
fACILITY_MSMQ = 14
fACILITY_NT_BIT :: HRESULT
fACILITY_NT_BIT = word32ToInt32 (0x10000000 ::Word32)
fACILITY_NULL :: HRESULT
fACILITY_NULL = 0
fACILITY_RPC :: HRESULT
fACILITY_RPC = 1
fACILITY_SETUPAPI :: HRESULT
fACILITY_SETUPAPI = 15
fACILITY_SSPI :: HRESULT
fACILITY_SSPI = 9
fACILITY_STORAGE :: HRESULT
fACILITY_STORAGE = 3
fACILITY_WIN32 :: HRESULT
fACILITY_WIN32 = 7
fACILITY_WINDOWS :: HRESULT
fACILITY_WINDOWS = 8
iNPLACE_E_FIRST :: HRESULT
iNPLACE_E_FIRST = word32ToInt32 (0x800401A0 ::Word32)
iNPLACE_E_LAST :: HRESULT
iNPLACE_E_LAST = word32ToInt32 (0x800401AF ::Word32)
iNPLACE_E_NOTOOLSPACE :: HRESULT
iNPLACE_E_NOTOOLSPACE = word32ToInt32 (0x800401A1 ::Word32)
iNPLACE_E_NOTUNDOABLE :: HRESULT
iNPLACE_E_NOTUNDOABLE = word32ToInt32 (0x800401A0 ::Word32)
iNPLACE_S_FIRST :: HRESULT
iNPLACE_S_FIRST = word32ToInt32 (0x000401A0 ::Word32)
iNPLACE_S_LAST :: HRESULT
iNPLACE_S_LAST = word32ToInt32 (0x000401AF ::Word32)
iNPLACE_S_TRUNCATED :: HRESULT
iNPLACE_S_TRUNCATED = word32ToInt32 (0x000401A0 ::Word32)
mARSHAL_E_FIRST :: HRESULT
mARSHAL_E_FIRST = word32ToInt32 (0x80040120 ::Word32)
mARSHAL_E_LAST :: HRESULT
mARSHAL_E_LAST = word32ToInt32 (0x8004012F ::Word32)
mARSHAL_S_FIRST :: HRESULT
mARSHAL_S_FIRST = word32ToInt32 (0x00040120 ::Word32)
mARSHAL_S_LAST :: HRESULT
mARSHAL_S_LAST = word32ToInt32 (0x0004012F ::Word32)
mEM_E_INVALID_LINK :: HRESULT
mEM_E_INVALID_LINK = word32ToInt32 (0x80080010 ::Word32)
mEM_E_INVALID_ROOT :: HRESULT
mEM_E_INVALID_ROOT = word32ToInt32 (0x80080009 ::Word32)
mEM_E_INVALID_SIZE :: HRESULT
mEM_E_INVALID_SIZE = word32ToInt32 (0x80080011 ::Word32)
mK_E_CANTOPENFILE :: HRESULT
mK_E_CANTOPENFILE = word32ToInt32 (0x800401EA ::Word32)
mK_E_CONNECTMANUALLY :: HRESULT
mK_E_CONNECTMANUALLY = word32ToInt32 (0x800401E0 ::Word32)
mK_E_ENUMERATION_FAILED :: HRESULT
mK_E_ENUMERATION_FAILED = word32ToInt32 (0x800401EF ::Word32)
mK_E_EXCEEDEDDEADLINE :: HRESULT
mK_E_EXCEEDEDDEADLINE = word32ToInt32 (0x800401E1 ::Word32)
mK_E_FIRST :: HRESULT
mK_E_FIRST = word32ToInt32 (0x800401E0 ::Word32)
mK_E_INTERMEDIATEINTERFACENOTSUPPORTED :: HRESULT
mK_E_INTERMEDIATEINTERFACENOTSUPPORTED = word32ToInt32 (0x800401E7 ::Word32)
mK_E_INVALIDEXTENSION :: HRESULT
mK_E_INVALIDEXTENSION = word32ToInt32 (0x800401E6 ::Word32)
mK_E_LAST :: HRESULT
mK_E_LAST = word32ToInt32 (0x800401EF ::Word32)
mK_E_MUSTBOTHERUSER :: HRESULT
mK_E_MUSTBOTHERUSER = word32ToInt32 (0x800401EB ::Word32)
mK_E_NEEDGENERIC :: HRESULT
mK_E_NEEDGENERIC = word32ToInt32 (0x800401E2 ::Word32)
mK_E_NOINVERSE :: HRESULT
mK_E_NOINVERSE = word32ToInt32 (0x800401EC ::Word32)
mK_E_NOOBJECT :: HRESULT
mK_E_NOOBJECT = word32ToInt32 (0x800401E5 ::Word32)
mK_E_NOPREFIX :: HRESULT
mK_E_NOPREFIX = word32ToInt32 (0x800401EE ::Word32)
mK_E_NOSTORAGE :: HRESULT
mK_E_NOSTORAGE = word32ToInt32 (0x800401ED ::Word32)
mK_E_NOTBINDABLE :: HRESULT
mK_E_NOTBINDABLE = word32ToInt32 (0x800401E8 ::Word32)
mK_E_NOTBOUND :: HRESULT
mK_E_NOTBOUND = word32ToInt32 (0x800401E9 ::Word32)
mK_E_NO_NORMALIZED :: HRESULT
mK_E_NO_NORMALIZED = word32ToInt32 (0x80080007 ::Word32)
mK_E_SYNTAX :: HRESULT
mK_E_SYNTAX = word32ToInt32 (0x800401E4 ::Word32)
mK_E_UNAVAILABLE :: HRESULT
mK_E_UNAVAILABLE = word32ToInt32 (0x800401E3 ::Word32)
mK_S_FIRST :: HRESULT
mK_S_FIRST = word32ToInt32 (0x000401E0 ::Word32)
mK_S_HIM :: HRESULT
mK_S_HIM = word32ToInt32 (0x000401E5 ::Word32)
mK_S_LAST :: HRESULT
mK_S_LAST = word32ToInt32 (0x000401EF ::Word32)
mK_S_ME :: HRESULT
mK_S_ME = word32ToInt32 (0x000401E4 ::Word32)
mK_S_MONIKERALREADYREGISTERED :: HRESULT
mK_S_MONIKERALREADYREGISTERED = word32ToInt32 (0x000401E7 ::Word32)
mK_S_REDUCED_TO_SELF :: HRESULT
mK_S_REDUCED_TO_SELF = word32ToInt32 (0x000401E2 ::Word32)
mK_S_US :: HRESULT
mK_S_US = word32ToInt32 (0x000401E6 ::Word32)
oLEOBJ_E_FIRST :: HRESULT
oLEOBJ_E_FIRST = word32ToInt32 (0x80040180 ::Word32)
oLEOBJ_E_INVALIDVERB :: HRESULT
oLEOBJ_E_INVALIDVERB = word32ToInt32 (0x80040181 ::Word32)
oLEOBJ_E_LAST :: HRESULT
oLEOBJ_E_LAST = word32ToInt32 (0x8004018F ::Word32)
oLEOBJ_E_NOVERBS :: HRESULT
oLEOBJ_E_NOVERBS = word32ToInt32 (0x80040180 ::Word32)
oLEOBJ_S_CANNOT_DOVERB_NOW :: HRESULT
oLEOBJ_S_CANNOT_DOVERB_NOW = word32ToInt32 (0x00040181 ::Word32)
oLEOBJ_S_FIRST :: HRESULT
oLEOBJ_S_FIRST = word32ToInt32 (0x00040180 ::Word32)
oLEOBJ_S_INVALIDHWND :: HRESULT
oLEOBJ_S_INVALIDHWND = word32ToInt32 (0x00040182 ::Word32)
oLEOBJ_S_INVALIDVERB :: HRESULT
oLEOBJ_S_INVALIDVERB = word32ToInt32 (0x00040180 ::Word32)
oLEOBJ_S_LAST :: HRESULT
oLEOBJ_S_LAST = word32ToInt32 (0x0004018F ::Word32)
oLE_E_ADVF :: HRESULT
oLE_E_ADVF = word32ToInt32 (0x80040001 ::Word32)
oLE_E_ADVISENOTSUPPORTED :: HRESULT
oLE_E_ADVISENOTSUPPORTED = word32ToInt32 (0x80040003 ::Word32)
oLE_E_BLANK :: HRESULT
oLE_E_BLANK = word32ToInt32 (0x80040007 ::Word32)
oLE_E_CANTCONVERT :: HRESULT
oLE_E_CANTCONVERT = word32ToInt32 (0x80040011 ::Word32)
oLE_E_CANT_BINDTOSOURCE :: HRESULT
oLE_E_CANT_BINDTOSOURCE = word32ToInt32 (0x8004000A ::Word32)
oLE_E_CANT_GETMONIKER :: HRESULT
oLE_E_CANT_GETMONIKER = word32ToInt32 (0x80040009 ::Word32)
oLE_E_CLASSDIFF :: HRESULT
oLE_E_CLASSDIFF = word32ToInt32 (0x80040008 ::Word32)
oLE_E_ENUM_NOMORE :: HRESULT
oLE_E_ENUM_NOMORE = word32ToInt32 (0x80040002 ::Word32)
oLE_E_FIRST :: HRESULT
oLE_E_FIRST = word32ToInt32 (0x80040000::Word32)
oLE_E_INVALIDHWND :: HRESULT
oLE_E_INVALIDHWND = word32ToInt32 (0x8004000F ::Word32)
oLE_E_INVALIDRECT :: HRESULT
oLE_E_INVALIDRECT = word32ToInt32 (0x8004000D ::Word32)
oLE_E_LAST :: HRESULT
oLE_E_LAST = word32ToInt32 (0x800400FF::Word32)
oLE_E_NOCACHE :: HRESULT
oLE_E_NOCACHE = word32ToInt32 (0x80040006 ::Word32)
oLE_E_NOCONNECTION :: HRESULT
oLE_E_NOCONNECTION = word32ToInt32 (0x80040004 ::Word32)
oLE_E_NOSTORAGE :: HRESULT
oLE_E_NOSTORAGE = word32ToInt32 (0x80040012 ::Word32)
oLE_E_NOTRUNNING :: HRESULT
oLE_E_NOTRUNNING = word32ToInt32 (0x80040005 ::Word32)
oLE_E_NOT_INPLACEACTIVE :: HRESULT
oLE_E_NOT_INPLACEACTIVE = word32ToInt32 (0x80040010 ::Word32)
oLE_E_OLEVERB :: HRESULT
oLE_E_OLEVERB = word32ToInt32 (0x80040000 ::Word32)
oLE_E_PROMPTSAVECANCELLED :: HRESULT
oLE_E_PROMPTSAVECANCELLED = word32ToInt32 (0x8004000C ::Word32)
oLE_E_STATIC :: HRESULT
oLE_E_STATIC = word32ToInt32 (0x8004000B ::Word32)
oLE_E_WRONGCOMPOBJ :: HRESULT
oLE_E_WRONGCOMPOBJ = word32ToInt32 (0x8004000E ::Word32)
oLE_S_FIRST :: HRESULT
oLE_S_FIRST = word32ToInt32 (0x00040000 ::Word32)
oLE_S_LAST :: HRESULT
oLE_S_LAST = word32ToInt32 (0x000400FF ::Word32)
oLE_S_MAC_CLIPFORMAT :: HRESULT
oLE_S_MAC_CLIPFORMAT = word32ToInt32 (0x00040002 ::Word32)
oLE_S_STATIC :: HRESULT
oLE_S_STATIC = word32ToInt32 (0x00040001 ::Word32)
oLE_S_USEREG :: HRESULT
oLE_S_USEREG = word32ToInt32 (0x00040000 ::Word32)
pERSIST_E_NOTSELFSIZING :: HRESULT
pERSIST_E_NOTSELFSIZING = word32ToInt32 (0x800B000B ::Word32)
pERSIST_E_SIZEDEFINITE :: HRESULT
pERSIST_E_SIZEDEFINITE = word32ToInt32 (0x800B0009 ::Word32)
pERSIST_E_SIZEINDEFINITE :: HRESULT
pERSIST_E_SIZEINDEFINITE = word32ToInt32 (0x800B000A ::Word32)
sTG_E_ABNORMALAPIEXIT :: HRESULT
sTG_E_ABNORMALAPIEXIT = word32ToInt32 (0x800300FA ::Word32)
sTG_E_ACCESSDENIED :: HRESULT
sTG_E_ACCESSDENIED = word32ToInt32 (0x80030005 ::Word32)
sTG_E_BADBASEADDRESS :: HRESULT
sTG_E_BADBASEADDRESS = word32ToInt32 (0x80030110 ::Word32)
sTG_E_CANTSAVE :: HRESULT
sTG_E_CANTSAVE = word32ToInt32 (0x80030103 ::Word32)
sTG_E_DISKISWRITEPROTECTED :: HRESULT
sTG_E_DISKISWRITEPROTECTED = word32ToInt32 (0x80030013 ::Word32)
sTG_E_DOCFILECORRUPT :: HRESULT
sTG_E_DOCFILECORRUPT = word32ToInt32 (0x80030109 ::Word32)
sTG_E_EXTANTMARSHALLINGS :: HRESULT
sTG_E_EXTANTMARSHALLINGS = word32ToInt32 (0x80030108 ::Word32)
sTG_E_FILEALREADYEXISTS :: HRESULT
sTG_E_FILEALREADYEXISTS = word32ToInt32 (0x80030050 ::Word32)
sTG_E_FILENOTFOUND :: HRESULT
sTG_E_FILENOTFOUND = word32ToInt32 (0x80030002 ::Word32)
sTG_E_INCOMPLETE :: HRESULT
sTG_E_INCOMPLETE = word32ToInt32 (0x80030201 ::Word32)
sTG_E_INSUFFICIENTMEMORY :: HRESULT
sTG_E_INSUFFICIENTMEMORY = word32ToInt32 (0x80030008 ::Word32)
sTG_E_INUSE :: HRESULT
sTG_E_INUSE = word32ToInt32 (0x80030100 ::Word32)
sTG_E_INVALIDFLAG :: HRESULT
sTG_E_INVALIDFLAG = word32ToInt32 (0x800300FF ::Word32)
sTG_E_INVALIDFUNCTION :: HRESULT
sTG_E_INVALIDFUNCTION = word32ToInt32 (0x80030001 ::Word32)
sTG_E_INVALIDHANDLE :: HRESULT
sTG_E_INVALIDHANDLE = word32ToInt32 (0x80030006 ::Word32)
sTG_E_INVALIDHEADER :: HRESULT
sTG_E_INVALIDHEADER = word32ToInt32 (0x800300FB ::Word32)
sTG_E_INVALIDNAME :: HRESULT
sTG_E_INVALIDNAME = word32ToInt32 (0x800300FC ::Word32)
sTG_E_INVALIDPARAMETER :: HRESULT
sTG_E_INVALIDPARAMETER = word32ToInt32 (0x80030057 ::Word32)
sTG_E_INVALIDPOINTER :: HRESULT
sTG_E_INVALIDPOINTER = word32ToInt32 (0x80030009 ::Word32)
sTG_E_LOCKVIOLATION :: HRESULT
sTG_E_LOCKVIOLATION = word32ToInt32 (0x80030021 ::Word32)
sTG_E_MEDIUMFULL :: HRESULT
sTG_E_MEDIUMFULL = word32ToInt32 (0x80030070 ::Word32)
sTG_E_NOMOREFILES :: HRESULT
sTG_E_NOMOREFILES = word32ToInt32 (0x80030012 ::Word32)
sTG_E_NOTCURRENT :: HRESULT
sTG_E_NOTCURRENT = word32ToInt32 (0x80030101 ::Word32)
sTG_E_NOTFILEBASEDSTORAGE :: HRESULT
sTG_E_NOTFILEBASEDSTORAGE = word32ToInt32 (0x80030107 ::Word32)
sTG_E_OLDDLL :: HRESULT
sTG_E_OLDDLL = word32ToInt32 (0x80030105 ::Word32)
sTG_E_OLDFORMAT :: HRESULT
sTG_E_OLDFORMAT = word32ToInt32 (0x80030104 ::Word32)
sTG_E_PATHNOTFOUND :: HRESULT
sTG_E_PATHNOTFOUND = word32ToInt32 (0x80030003 ::Word32)
sTG_E_PROPSETMISMATCHED :: HRESULT
sTG_E_PROPSETMISMATCHED = word32ToInt32 (0x800300F0 ::Word32)
sTG_E_READFAULT :: HRESULT
sTG_E_READFAULT = word32ToInt32 (0x8003001E ::Word32)
sTG_E_REVERTED :: HRESULT
sTG_E_REVERTED = word32ToInt32 (0x80030102 ::Word32)
sTG_E_SEEKERROR :: HRESULT
sTG_E_SEEKERROR = word32ToInt32 (0x80030019 ::Word32)
sTG_E_SHAREREQUIRED :: HRESULT
sTG_E_SHAREREQUIRED = word32ToInt32 (0x80030106 ::Word32)
sTG_E_SHAREVIOLATION :: HRESULT
sTG_E_SHAREVIOLATION = word32ToInt32 (0x80030020 ::Word32)
sTG_E_TERMINATED :: HRESULT
sTG_E_TERMINATED = word32ToInt32 (0x80030202 ::Word32)
sTG_E_TOOMANYOPENFILES :: HRESULT
sTG_E_TOOMANYOPENFILES = word32ToInt32 (0x80030004 ::Word32)
sTG_E_UNIMPLEMENTEDFUNCTION :: HRESULT
sTG_E_UNIMPLEMENTEDFUNCTION = word32ToInt32 (0x800300FE ::Word32)
sTG_E_UNKNOWN :: HRESULT
sTG_E_UNKNOWN = word32ToInt32 (0x800300FD ::Word32)
sTG_E_WRITEFAULT :: HRESULT
sTG_E_WRITEFAULT = word32ToInt32 (0x8003001D ::Word32)
sTG_S_BLOCK :: HRESULT
sTG_S_BLOCK = word32ToInt32 (0x00030201 ::Word32)
sTG_S_CANNOTCONSOLIDATE :: HRESULT
sTG_S_CANNOTCONSOLIDATE = word32ToInt32 (0x00030206 ::Word32)
sTG_S_CONSOLIDATIONFAILED :: HRESULT
sTG_S_CONSOLIDATIONFAILED = word32ToInt32 (0x00030205 ::Word32)
sTG_S_CONVERTED :: HRESULT
sTG_S_CONVERTED = word32ToInt32 (0x00030200 ::Word32)
sTG_S_MONITORING :: HRESULT
sTG_S_MONITORING = word32ToInt32 (0x00030203 ::Word32)
sTG_S_MULTIPLEOPENS :: HRESULT
sTG_S_MULTIPLEOPENS = word32ToInt32 (0x00030204 ::Word32)
sTG_S_RETRYNOW :: HRESULT
sTG_S_RETRYNOW = word32ToInt32 (0x00030202 ::Word32)
tYPE_E_AMBIGUOUSNAME :: HRESULT
tYPE_E_AMBIGUOUSNAME = word32ToInt32 (0x8002802C ::Word32)
tYPE_E_BADMODULEKIND :: HRESULT
tYPE_E_BADMODULEKIND = word32ToInt32 (0x800288BD ::Word32)
tYPE_E_BUFFERTOOSMALL :: HRESULT
tYPE_E_BUFFERTOOSMALL = word32ToInt32 (0x80028016 ::Word32)
tYPE_E_CANTCREATETMPFILE :: HRESULT
tYPE_E_CANTCREATETMPFILE = word32ToInt32 (0x80028CA3 ::Word32)
tYPE_E_CANTLOADLIBRARY :: HRESULT
tYPE_E_CANTLOADLIBRARY = word32ToInt32 (0x80029C4A ::Word32)
tYPE_E_CIRCULARTYPE :: HRESULT
tYPE_E_CIRCULARTYPE = word32ToInt32 (0x80029C84 ::Word32)
tYPE_E_DLLFUNCTIONNOTFOUND :: HRESULT
tYPE_E_DLLFUNCTIONNOTFOUND = word32ToInt32 (0x8002802F ::Word32)
tYPE_E_DUPLICATEID :: HRESULT
tYPE_E_DUPLICATEID = word32ToInt32 (0x800288C6 ::Word32)
tYPE_E_ELEMENTNOTFOUND :: HRESULT
tYPE_E_ELEMENTNOTFOUND = word32ToInt32 (0x8002802B ::Word32)
tYPE_E_FIELDNOTFOUND :: HRESULT
tYPE_E_FIELDNOTFOUND = word32ToInt32 (0x80028017 ::Word32)
tYPE_E_INCONSISTENTPROPFUNCS :: HRESULT
tYPE_E_INCONSISTENTPROPFUNCS = word32ToInt32 (0x80029C83 ::Word32)
tYPE_E_INVALIDID :: HRESULT
tYPE_E_INVALIDID = word32ToInt32 (0x800288CF ::Word32)
tYPE_E_INVALIDSTATE :: HRESULT
tYPE_E_INVALIDSTATE = word32ToInt32 (0x80028029 ::Word32)
tYPE_E_INVDATAREAD :: HRESULT
tYPE_E_INVDATAREAD = word32ToInt32 (0x80028018 ::Word32)
tYPE_E_IOERROR :: HRESULT
tYPE_E_IOERROR = word32ToInt32 (0x80028CA2 ::Word32)
tYPE_E_LIBNOTREGISTERED :: HRESULT
tYPE_E_LIBNOTREGISTERED = word32ToInt32 (0x8002801D ::Word32)
tYPE_E_NAMECONFLICT :: HRESULT
tYPE_E_NAMECONFLICT = word32ToInt32 (0x8002802D ::Word32)
tYPE_E_OUTOFBOUNDS :: HRESULT
tYPE_E_OUTOFBOUNDS = word32ToInt32 (0x80028CA1 ::Word32)
tYPE_E_QUALIFIEDNAMEDISALLOWED :: HRESULT
tYPE_E_QUALIFIEDNAMEDISALLOWED = word32ToInt32 (0x80028028 ::Word32)
tYPE_E_REGISTRYACCESS :: HRESULT
tYPE_E_REGISTRYACCESS = word32ToInt32 (0x8002801C ::Word32)
tYPE_E_SIZETOOBIG :: HRESULT
tYPE_E_SIZETOOBIG = word32ToInt32 (0x800288C5 ::Word32)
tYPE_E_TYPEMISMATCH :: HRESULT
tYPE_E_TYPEMISMATCH = word32ToInt32 (0x80028CA0 ::Word32)
tYPE_E_UNDEFINEDTYPE :: HRESULT
tYPE_E_UNDEFINEDTYPE = word32ToInt32 (0x80028027 ::Word32)
tYPE_E_UNKNOWNLCID :: HRESULT
tYPE_E_UNKNOWNLCID = word32ToInt32 (0x8002802E ::Word32)
tYPE_E_UNSUPFORMAT :: HRESULT
tYPE_E_UNSUPFORMAT = word32ToInt32 (0x80028019 ::Word32)
tYPE_E_WRONGTYPEKIND :: HRESULT
tYPE_E_WRONGTYPEKIND = word32ToInt32 (0x8002802A ::Word32)
vIEW_E_DRAW :: HRESULT
vIEW_E_DRAW = word32ToInt32 (0x80040140 ::Word32)
vIEW_E_FIRST :: HRESULT
vIEW_E_FIRST = word32ToInt32 (0x80040140 ::Word32)
vIEW_E_LAST :: HRESULT
vIEW_E_LAST = word32ToInt32 (0x8004014F ::Word32)
vIEW_S_ALREADY_FROZEN :: HRESULT
vIEW_S_ALREADY_FROZEN = word32ToInt32 (0x00040140 ::Word32)
vIEW_S_FIRST :: HRESULT
vIEW_S_FIRST = word32ToInt32 (0x00040140 ::Word32)
vIEW_S_LAST :: HRESULT
vIEW_S_LAST = word32ToInt32 (0x0004014F ::Word32)
|
jjinkou2/ComForGHC7.4
|
System/Win32/Com/Exception.hs
|
bsd-3-clause
| 32,380
| 3
| 16
| 3,750
| 6,937
| 3,949
| 2,988
| 710
| 3
|
module Four (four) where
import Data.List
import Data.Ord
import Data.Char
import Text.Regex.TDFA
import Debug.Trace
-- this is pretty cute actually
-- sorts and groups a string, map to tuple of char and count
-- sorts by descending count and ascending alphabet
-- then takes the first five chars
checksum :: String -> String
checksum w = snd <$> (take 5 $ sortBy (mconcat [flip $ comparing fst, comparing snd])
((\c -> (length c, head c)) <$> (group $ sort w)))
parse :: String -> (String, Integer, String)
parse l = (s', n', c)
where (s:n:c:[]) = tail $ getAllTextSubmatches (l =~ "^([a-z-]*)([0-9]*)\\[([a-z]*)" :: AllTextSubmatches [] String)
s' = filter (/= '-') s
n' = read n
abcAdd :: (Integral a) => a -> Char -> Char
abcAdd n c = chr $ ((ord c - 97 + fromIntegral n) `mod` 26) + 97
four = do
input <- (fmap parse) <$> lines <$> readFile "data/four.txt"
let result1 = foldr (\(_, n, _) acc -> acc + n) 0 $ filter (\(s, _, c) -> checksum s == c) input
putStrLn $ "part A: " ++ show result1
let result2 = snd $ head $ filter (isPrefixOf "north" . fst) $ (\(s, n, _) -> (abcAdd n <$> s, n)) <$> input
putStrLn $ "part B: " ++ show result2
|
alicemaz/advent2016
|
Four.hs
|
bsd-3-clause
| 1,199
| 0
| 16
| 274
| 501
| 268
| 233
| 22
| 1
|
-- | Test suite for Theo1 statistics from this paper:
--
-- Howe, D.A. 2006. "TheoH: a hybrid, high-confidence statistic that
-- improves on the Allan deviation." Metrologia 43: S322-S331.
-- Available online: http://www.tf.nist.gov/timefreq/general/pdf/2109.pdf
--
module TauSigma.Statistics.HoweSpec where
import Control.Monad (unless)
import Data.Maybe (fromJust)
import Data.Tagged
import Data.Vector (Vector)
import qualified Data.Vector as V
import Text.Printf (printf)
import TauSigma.Types
import TauSigma.Statistics.Theo1 (theo1dev)
import Test.Hspec
spec :: Spec
spec = do
describe "Howe 2006, Appendix A" $ do
describe "Theo1 DEV" $ do
it "m = 10" $ do
let (_, sigma) = fromJust $ theo1dev 86400 10 howeData
sigma `shouldBeAbout` (7.66e-15, 7e-18)
shouldBeAbout :: Double -> (Double, Double) -> Expectation
actual `shouldBeAbout` (expected, tolerance) =
unless (delta <= tolerance) (expectationFailure message)
where
delta = abs (actual - expected)
message =
printf "expected = %f, actual = %f, delta = %f" expected actual delta
-- | Howe 2006, Appendix A test suite
howeData :: Vector Double
howeData = V.fromList (map (unTagged . (*1e-9)) raw)
where
-- These are given as nanoseconds, which we convert to seconds
raw :: [TimeData Double]
raw = [ -2.15
, -0.99
, 1
, 2.5
, 0.65
, -3.71
, -3.3
, 1.08
, 0.5
, 2.2
, 4.68
, 3.29
]
|
sacundim/tau-sigma
|
test/TauSigma/Statistics/HoweSpec.hs
|
bsd-3-clause
| 1,538
| 0
| 20
| 403
| 357
| 204
| 153
| 38
| 1
|
{-# LANGUAGE TemplateHaskell #-}
module Lightray.Types.GeometricShape where
import Control.Lens
import Linear.V3 (V3)
data GeometricPrimitive = Plane { _planePoint :: V3 Double
, _planeNormal :: V3 Double }
| Sphere { _sphereCenter :: V3 Double
, _sphereRadius :: Double }
deriving (Show)
makeLenses ''GeometricPrimitive
|
alandao/lightray
|
src/Lightray/Types/GeometricShape.hs
|
bsd-3-clause
| 489
| 0
| 9
| 211
| 85
| 49
| 36
| 10
| 0
|
import System.FilePath.Glob (glob)
import Test.DocTest (doctest)
-- main = glob "src/**/*.*hs" >>= doctest
main = do
src_hs <- glob "src/**/*.hs"
src_lhs <- glob "src/**/*.lhs"
doctest (src_hs ++ src_lhs ++ ["test/TestInstances.hs", "test/TestUtil.hs"])
|
bjornbm/astro
|
test/Doctests.hs
|
bsd-3-clause
| 266
| 0
| 10
| 43
| 71
| 37
| 34
| 6
| 1
|
{-# LANGUAGE UndecidableInstances #-}
-- | Derive @generics-sop@ boilerplate instances from GHC's 'GHC.Generic'.
--
-- The technique being used here is described in the following paper:
--
-- * José Pedro Magalhães and Andres Löh.
-- <http://www.andres-loeh.de/GenericGenericProgramming Generic Generic Programming>.
-- Practical Aspects of Declarative Languages (PADL) 2014.
--
module Generics.SOP.GGP
( GCode
, GFrom
, GTo
, GDatatypeInfo
, gfrom
, gto
, gdatatypeInfo
) where
import Data.Proxy
import GHC.Generics as GHC
import Generics.SOP.NP as SOP
import Generics.SOP.NS as SOP
import Generics.SOP.BasicFunctors as SOP
import Generics.SOP.Constraint as SOP
import Generics.SOP.Metadata as SOP
import Generics.SOP.Sing
type family ToSingleCode (a :: * -> *) :: *
type instance ToSingleCode (K1 i a) = a
type family ToProductCode (a :: * -> *) (xs :: [*]) :: [*]
type instance ToProductCode (a :*: b) xs = ToProductCode a (ToProductCode b xs)
type instance ToProductCode U1 xs = xs
type instance ToProductCode (M1 S c a) xs = ToSingleCode a ': xs
type family ToSumCode (a :: * -> *) (xs :: [[*]]) :: [[*]]
type instance ToSumCode (a :+: b) xs = ToSumCode a (ToSumCode b xs)
type instance ToSumCode V1 xs = xs
type instance ToSumCode (M1 D c a) xs = ToSumCode a xs
type instance ToSumCode (M1 C c a) xs = ToProductCode a '[] ': xs
#if MIN_VERSION_base(4,9,0)
data InfoProxy (c :: Meta) (f :: * -> *) (x :: *) = InfoProxy
#else
data InfoProxy (c :: *) (f :: * -> *) (x :: *) = InfoProxy
#endif
class GDatatypeInfo' (a :: * -> *) where
gDatatypeInfo' :: proxy a -> DatatypeInfo (ToSumCode a '[])
#if !(MIN_VERSION_base(4,7,0))
-- | 'isNewtype' does not exist in "GHC.Generics" before GHC-7.8.
--
-- The only safe assumption to make is that it always returns 'False'.
--
isNewtype :: Datatype d => t d (f :: * -> *) a -> Bool
isNewtype _ = False
#endif
instance (All SListI (ToSumCode a '[]), Datatype c, GConstructorInfos a) => GDatatypeInfo' (M1 D c a) where
gDatatypeInfo' _ =
let adt = ADT (moduleName p) (datatypeName p)
ci = gConstructorInfos (Proxy :: Proxy a) Nil
in if isNewtype p
then case isNewtypeShape ci of
NewYes c -> Newtype (moduleName p) (datatypeName p) c
NewNo -> adt ci -- should not happen
else adt ci
where
p :: InfoProxy c a x
p = InfoProxy
data IsNewtypeShape (xss :: [[*]]) where
NewYes :: ConstructorInfo '[x] -> IsNewtypeShape '[ '[x] ]
NewNo :: IsNewtypeShape xss
isNewtypeShape :: All SListI xss => NP ConstructorInfo xss -> IsNewtypeShape xss
isNewtypeShape (x :* Nil) = go shape x
where
go :: Shape xs -> ConstructorInfo xs -> IsNewtypeShape '[ xs ]
go (ShapeCons ShapeNil) c = NewYes c
go _ _ = NewNo
isNewtypeShape _ = NewNo
class GConstructorInfos (a :: * -> *) where
gConstructorInfos :: proxy a -> NP ConstructorInfo xss -> NP ConstructorInfo (ToSumCode a xss)
instance (GConstructorInfos a, GConstructorInfos b) => GConstructorInfos (a :+: b) where
gConstructorInfos _ xss = gConstructorInfos (Proxy :: Proxy a) (gConstructorInfos (Proxy :: Proxy b) xss)
instance GConstructorInfos GHC.V1 where
gConstructorInfos _ xss = xss
instance (Constructor c, GFieldInfos a, SListI (ToProductCode a '[])) => GConstructorInfos (M1 C c a) where
gConstructorInfos _ xss
| conIsRecord p = Record (conName p) (gFieldInfos (Proxy :: Proxy a) Nil) :* xss
| otherwise = case conFixity p of
Prefix -> Constructor (conName p) :* xss
GHC.Infix a f -> case (shape :: Shape (ToProductCode a '[])) of
ShapeCons (ShapeCons ShapeNil) -> SOP.Infix (conName p) a f :* xss
_ -> Constructor (conName p) :* xss -- should not happen
where
p :: InfoProxy c a x
p = InfoProxy
class GFieldInfos (a :: * -> *) where
gFieldInfos :: proxy a -> NP FieldInfo xs -> NP FieldInfo (ToProductCode a xs)
instance (GFieldInfos a, GFieldInfos b) => GFieldInfos (a :*: b) where
gFieldInfos _ xs = gFieldInfos (Proxy :: Proxy a) (gFieldInfos (Proxy :: Proxy b) xs)
instance GFieldInfos U1 where
gFieldInfos _ xs = xs
instance (Selector c) => GFieldInfos (M1 S c a) where
gFieldInfos _ xs = FieldInfo (selName p) :* xs
where
p :: InfoProxy c a x
p = InfoProxy
class GSingleFrom (a :: * -> *) where
gSingleFrom :: a x -> ToSingleCode a
instance GSingleFrom (K1 i a) where
gSingleFrom (K1 a) = a
class GProductFrom (a :: * -> *) where
gProductFrom :: a x -> NP I xs -> NP I (ToProductCode a xs)
instance (GProductFrom a, GProductFrom b) => GProductFrom (a :*: b) where
gProductFrom (a :*: b) xs = gProductFrom a (gProductFrom b xs)
instance GProductFrom U1 where
gProductFrom U1 xs = xs
instance GSingleFrom a => GProductFrom (M1 S c a) where
gProductFrom (M1 a) xs = I (gSingleFrom a) :* xs
class GSingleTo (a :: * -> *) where
gSingleTo :: ToSingleCode a -> a x
instance GSingleTo (K1 i a) where
gSingleTo a = K1 a
class GProductTo (a :: * -> *) where
gProductTo :: NP I (ToProductCode a xs) -> (a x -> NP I xs -> r) -> r
instance (GProductTo a, GProductTo b) => GProductTo (a :*: b) where
gProductTo xs k = gProductTo xs (\ a ys -> gProductTo ys (\ b zs -> k (a :*: b) zs))
instance GSingleTo a => GProductTo (M1 S c a) where
gProductTo (SOP.I a :* xs) k = k (M1 (gSingleTo a)) xs
gProductTo _ _ = error "inaccessible"
instance GProductTo U1 where
gProductTo xs k = k U1 xs
-- This can most certainly be simplified
class GSumFrom (a :: * -> *) where
gSumFrom :: a x -> SOP I xss -> SOP I (ToSumCode a xss)
gSumSkip :: proxy a -> SOP I xss -> SOP I (ToSumCode a xss)
instance (GSumFrom a, GSumFrom b) => GSumFrom (a :+: b) where
gSumFrom (L1 a) xss = gSumFrom a (gSumSkip (Proxy :: Proxy b) xss)
gSumFrom (R1 b) xss = gSumSkip (Proxy :: Proxy a) (gSumFrom b xss)
gSumSkip _ xss = gSumSkip (Proxy :: Proxy a) (gSumSkip (Proxy :: Proxy b) xss)
instance (GSumFrom a) => GSumFrom (M1 D c a) where
gSumFrom (M1 a) xss = gSumFrom a xss
gSumSkip _ xss = gSumSkip (Proxy :: Proxy a) xss
instance (GProductFrom a) => GSumFrom (M1 C c a) where
gSumFrom (M1 a) _ = SOP (Z (gProductFrom a Nil))
gSumSkip _ (SOP xss) = SOP (S xss)
class GSumTo (a :: * -> *) where
gSumTo :: SOP I (ToSumCode a xss) -> (a x -> r) -> (SOP I xss -> r) -> r
instance (GSumTo a, GSumTo b) => GSumTo (a :+: b) where
gSumTo xss s k = gSumTo xss (s . L1) (\ r -> gSumTo r (s . R1) k)
instance (GProductTo a) => GSumTo (M1 C c a) where
gSumTo (SOP (Z xs)) s _ = s (M1 (gProductTo xs ((\ x Nil -> x) :: a x -> NP I '[] -> a x)))
gSumTo (SOP (S xs)) _ k = k (SOP xs)
instance (GSumTo a) => GSumTo (M1 D c a) where
gSumTo xss s k = gSumTo xss (s . M1) k
-- | Compute the SOP code of a datatype.
--
-- This requires that 'GHC.Rep' is defined, which in turn requires that
-- the type has a 'GHC.Generic' (from module "GHC.Generics") instance.
--
-- This is the default definition for 'Generics.SOP.Code'.
-- For more info, see 'Generics.SOP.Generic'.
--
type GCode (a :: *) = ToSumCode (GHC.Rep a) '[]
-- | Constraint for the class that computes 'gfrom'.
type GFrom a = GSumFrom (GHC.Rep a)
-- | Constraint for the class that computes 'gto'.
type GTo a = GSumTo (GHC.Rep a)
-- | Constraint for the class that computes 'gdatatypeInfo'.
type GDatatypeInfo a = GDatatypeInfo' (GHC.Rep a)
-- | An automatically computed version of 'Generics.SOP.from'.
--
-- This requires that the type being converted has a
-- 'GHC.Generic' (from module "GHC.Generics") instance.
--
-- This is the default definition for 'Generics.SOP.from'.
-- For more info, see 'Generics.SOP.Generic'.
--
gfrom :: (GFrom a, GHC.Generic a) => a -> SOP I (GCode a)
gfrom x = gSumFrom (GHC.from x) (error "gfrom: internal error" :: SOP.SOP SOP.I '[])
-- | An automatically computed version of 'Generics.SOP.to'.
--
-- This requires that the type being converted has a
-- 'GHC.Generic' (from module "GHC.Generics") instance.
--
-- This is the default definition for 'Generics.SOP.to'.
-- For more info, see 'Generics.SOP.Generic'.
--
gto :: forall a. (GTo a, GHC.Generic a) => SOP I (GCode a) -> a
gto x = GHC.to (gSumTo x id ((\ _ -> error "inaccessible") :: SOP I '[] -> (GHC.Rep a) x))
-- | An automatically computed version of 'Generics.SOP.datatypeInfo'.
--
-- This requires that the type being converted has a
-- 'GHC.Generic' (from module "GHC.Generics") instance.
--
-- This is the default definition for 'Generics.SOP.datatypeInfo'.
-- For more info, see 'Generics.SOP.HasDatatypeInfo'.
--
gdatatypeInfo :: forall proxy a. (GDatatypeInfo a) => proxy a -> DatatypeInfo (GCode a)
gdatatypeInfo _ = gDatatypeInfo' (Proxy :: Proxy (GHC.Rep a))
|
phadej/generics-sop
|
src/Generics/SOP/GGP.hs
|
bsd-3-clause
| 8,793
| 0
| 16
| 1,942
| 3,130
| 1,645
| 1,485
| -1
| -1
|
-- | User friendly functions
-- This is essentially the user interface to the module
module Reports where
import Calcs
import DateCalcs
import NumCalcs ()
-- Some nicely formated reports
-- print lines and total of SE, PY, and HE
printGemTotal :: String -> IO ()
printGemTotal txt = do
printGemLines txt
printGem txt
-- print one line for each Word of SE, PY and HE
printGemLines :: String -> IO ()
printGemLines txt = mapM_ printEach3 (findGem txt)
-- print total of SE, PY, and HE
printGem :: String -> IO ()
printGem txt = printEach3 (txt, sumSE txt, sumPY txt, sumHE txt)
printPyTotal :: String -> IO ()
printPyTotal txt = do
printPyLines txt
printPy txt
printPyLines :: String -> IO ()
printPyLines txt = mapM_ printEach3 (findPythag txt)
printPy :: String -> IO ()
printPy txt = printEach3 (txt, sumPY txt, sumPS txt, sumPX txt)
-- print totals
printTot :: String -> IO ()
printTot txt = do
putStrLn (txt ++ " -- " ++
show (sumSE txt) ++ " SE - " ++ show (sumEN txt) ++ " EN - " ++
show (sumCE txt) ++ " CE - " ++ show (sumPY txt) ++ " PY - " ++
show (sumPS txt) ++ " PS - " ++ show (sumPX txt) ++ " PX - " ++
show (sumHE txt) ++ " HE - " ++ show (sumBC txt) ++ " BC ")
-- report funtions that also show work
-- print and show work given a calc funtion and a String
printSW :: (String -> [Int]) -> String -> IO ()
printSW fn str = putStrLn (str ++ " - " ++ showWList lst ++ " = " ++ show (sum lst))
where lst = fn str
-- print and show work of various gematria
printSEsw,printPYsw,printPSsw,printPXsw,printHEsw,printBCsw
:: String -> IO ()
printSEsw = printSW calcSE
printPYsw = printSW calcPY
printPSsw = printSW calcPS
printPXsw = printSW calcPX
printHEsw = printSW calcHE
printBCsw = printSW calcBC
-- print gematria totals and show work
printGemTotSW :: String -> IO ()
printGemTotSW str = do
printSEsw str
printPYsw str
printHEsw str
-- print Pythagorean totals and show work
printPyTotSW :: String -> IO ()
printPyTotSW str = do
printPYsw str
printPSsw str
printPXsw str
-- print ALL totals and show work
printTotSW :: String -> IO ()
printTotSW str = do
printSEsw str
printPYsw str
printPSsw str
printPXsw str
printHEsw str
printBCsw str
-- Date reports
printDateSplit :: String -> IO ()
printDateSplit day1 = do
case dt of
Nothing -> putStrLn "Error in date format: Should be MM/DD/YYYY"
Just (year,month,day) -> do
putStrLn (show month ++ "/" ++ show day ++ "/" ++ show yr ++ " - " ++
showWList ones ++ " = " ++ show (sum ones))
putStrLn (show month ++ "/" ++ show day ++ "/" ++ show yr ++ " - " ++
showWList [month,day,hnds,tens] ++ " = " ++ show (sum [month,day,hnds,tens]))
putStrLn (show month ++ "/" ++ show day ++ "/" ++ show yr ++ " - " ++
showWList [month,day,spT hnds, spO hnds, spT tens, spO tens] ++ " = " ++
show (sum [month,day,spT hnds, spO hnds, spT tens, spO tens]))
putStrLn (show month ++ "/" ++ show day ++ "/" ++ show tens ++ " - " ++
showWList [month,day,tens] ++ " = " ++ show (sum [month,day,tens]))
where yr = fromIntegral year
ones = [spT month, spO month, spT day, spO day, spT hnds, spO hnds, spT tens, spO tens]
hnds = yr `div` 100
tens = yr `rem` 100
spT n = n `div` 10
spO n = n `rem` 10
where dt = conv (readDate day1)
printDateSpread :: String -> IO ()
printDateSpread day =
case dt of
Nothing -> putStrLn "Error in date format: Should be MM/DD/YYYY"
Just (d1, d2) ->
putStrLn (show d1 ++ " days since start of year " ++ show d2 ++ " days til end of year")
where dt = calcSpread day
printDateDiff :: String -> String -> IO ()
printDateDiff day1 day2 =
case dt of
Nothing -> putStrLn "Error in date format: Should be MM/DD/YYYY"
Just dys -> putStrLn (show dys ++ " days")
where dt = calcDiffDays day1 day2
-- Utility functions
printEach2 :: (String, Int, Int) -> IO ()
printEach2 (wrd, x, y) =
putStrLn (wrd ++ " -- " ++ show x ++ "/" ++ show y)
printEach3 :: (String, Int, Int, Int) -> IO ()
printEach3 (wrd, x, y, z) =
putStrLn (wrd ++ " -- " ++ show x ++ "/" ++ show y ++ "/" ++ show z)
-- show the work list
showWList :: (Eq a, Num a, Show a) => [a] -> String
showWList [x] = show x
showWList (x:xs)
| x == 0 = showWList xs
| otherwise = show x ++ "+" ++ showWList xs
showWList [] = ""
|
emaphis/pythagorean
|
src/Reports.hs
|
bsd-3-clause
| 4,515
| 0
| 27
| 1,193
| 1,676
| 836
| 840
| 102
| 2
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import System.IO.Net
import System.IO.Buffered
import Control.Concurrent
import Foreign.ForeignPtr
import qualified Data.ByteString as B
import qualified Data.ByteString.Internal as B
import GHC.ForeignPtr
import Control.Monad
import System.IO.Exception
import System.IO.UV.Stream
import System.IO
import Data.IORef.Unboxed
import System.Environment
import Text.Read (readMaybe)
main :: IO ()
main = do
portStr <- lookupEnv "PORT"
let port = maybe 8888 id (readMaybe =<< portStr)
let conf = ServerConfig
(SockAddrInet port inetAny)
128
(\ uvs -> do
recvbuf <- mallocPlainForeignPtrBytes 2048 -- we reuse buffer as golang does,
-- since node use slab, which is in face a memory pool
echo uvs recvbuf)
True
(print :: SomeException -> IO())
startServer conf
where
echo uvs recvbuf = loop
where
loop = do
r <- withForeignPtr recvbuf $ \ p -> do
readInput uvs p 2048
when (r /= 0) $ do
withForeignPtr sendbuffp $ \ p -> writeOutput uvs p l
loop
(B.PS sendbuffp _ l) =
"HTTP/1.1 200 OK\r\n\
\Content-Type: text/html; charset=UTF-8\r\n\
\Content-Length: 500\r\n\
\Connection: Keep-Alive\r\n\
\\r\n" `B.append` (B.replicate 500 48)
|
winterland1989/stdio
|
bench/tcp/LibUV.hs
|
bsd-3-clause
| 1,551
| 0
| 16
| 509
| 345
| 184
| 161
| 40
| 1
|
module Tests.AlpmList where
import Control.Applicative
import Control.Concurrent
import Control.Monad
import Data.List
import System.IO
import System.Mem
import Test.QuickCheck
import Test.QuickCheck.Monadic
import Distribution.ArchLinux.Libalpm.Wrapper.List
newtype StringWithNoNulls = StringWithNoNulls { getString :: String } deriving (Show)
instance Arbitrary StringWithNoNulls where
arbitrary = StringWithNoNulls <$> listOf almostArbitraryChar
where
almostArbitraryChar = (arbitrary :: Gen Char) `suchThat` (/= '\NUL')
runAlpmListTests :: IO ()
runAlpmListTests = do
putStrLn "Test with not null chars"
quickCheck $ forAll (arbitrary :: Gen [StringWithNoNulls]) $
prop_fromList_toList_strings . map getString
--putStrLn "Performing memory test"
--memoryTest
arbStrList :: IO [String]
arbStrList = map getString <$> take 10 <$> sample' (arbitrary :: Gen StringWithNoNulls)
simpleStrList :: IO [String]
simpleStrList = return $ replicate 10 ['0'..'9']
wait = do
putStr "Press enter" >> hFlush stdout
_ <- getLine
return ()
memoryTest :: IO ()
memoryTest = do
lst <- concat <$> (replicateM 100000 $ simpleStrList)
alpmList <- withAlpmList lst Full toList
wait
putStrLn $ show $ alpmList == lst
performGC
wait
return ()
prop_fromList_toList_strings :: [String] -> Property
prop_fromList_toList_strings lst =
all ('\NUL' `notElem`) lst ==>
monadicIO $ do
clst <- run $ withAlpmList lst Full toList
assert $ clst == lst
|
netvl/alpmhs
|
lib/test/Tests/AlpmList.hs
|
bsd-3-clause
| 1,502
| 0
| 13
| 269
| 432
| 225
| 207
| 42
| 1
|
-- Copyright (c) 2015 Eric McCorkle. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS''
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
{-# OPTIONS_GHC -Wall -Werror #-}
-- | This module implements compilation of SimpleIR to LLVM. Roughly
-- speaking, the process goes something like this:
--
-- 1) Convert all named types to LLVM types
-- 2) Generate metadata for generated GC types
-- 3) Generate declarations for all necessary accessors and modifiers
-- for GC types.
-- 4) Generate declarations for all globals, and convert their types.
-- 5) Compute dominance frontiers, and from that, phi-sets for each
-- function.
-- 6) Generate code for all functions.
--
-- What isn't implemented:
-- * Escape analysis to figure out what needs to be alloca'ed
-- * Storing local variables in alloca'ed slots at all
--
-- Notes:
-- * Variants can be treated like any other aggregate. Anytime we
-- assign a particular variant to a variant typed value, set all
-- the fields for the other variants to undef.
-- * Local variables should probably be annotated with a source.
-- This would allow static link accessed variables to be bound
-- properly.
-- * Functions could take an additional argument list representing
-- static linking.
module IR.FlatIR.LLVMGen(
toLLVM
) where
import Data.Graph.Inductive
import IR.FlatIR.Syntax
import qualified LLVM.Core as LLVM
import qualified IR.FlatIR.LLVMGen.GCAccessors as GCAccessors
import qualified IR.FlatIR.LLVMGen.GCHeaders as GCHeaders
import qualified IR.FlatIR.LLVMGen.Globals as Globals
import qualified IR.FlatIR.LLVMGen.Metadata as Metadata
import qualified IR.FlatIR.LLVMGen.Types as Types
-- | A datatype representing parameters to the compiler.
data CompileParams =
CompileParams {
-- | The DWARF Language ID.
languageId :: Word,
-- | The name of the compiler (will be indicated in debugging information).
producerName :: String,
-- | Whether or not this module is the main module for the program.
main :: Bool,
-- | Whether or not this module is optimized.
optimize :: Bool,
-- | The runtime version.
runtimeVersion :: Word,
-- | The compiler flags.
flags :: String,
}
-- | Generate LLVM IR from the FlatIR module.
toLLVM :: Graph gr
=> Module gr
-- ^ The FlatIR module being translated.
-> IO LLVM.ModuleRef
-- ^ The LLVM Module.
toLLVM irmod @ (Module { modName = name }) =
let
genTypeDefs = Types.genTypeDefs irmod
genGCHeaders = GCHeaders.genGCHeaders irmod
genAccessors = GCAccessors.genAccessors irmod
genMetadata = Metadata.genMetadata irmod
genDecls = Globals.genDecls irmod
genDefs = Globals.genDefs irmod
in do
llvmmod <- LLVM.moduleCreateWithName name
ctx <- LLVM.getModuleContext llvmmod
typedefs <- genTypeDefs ctx
_ <- genGCHeaders llvmmod ctx typedefs
genMetadata llvmmod ctx
decls <- genDecls llvmmod ctx typedefs
genAccessors llvmmod ctx typedefs
genDefs ctx decls typedefs
return llvmmod
|
emc2/iridium
|
src/IR/FlatIR/LLVMGen.hs
|
bsd-3-clause
| 4,468
| 3
| 8
| 878
| 254
| 195
| 59
| -1
| -1
|
module FP.Console where
import FP.Core hiding (reset)
import FP.Pretty
import FP.Free
import System.IO.Unsafe
leader :: String
leader = "\ESC["
sgrCloser :: String
sgrCloser = "m"
reset :: String
reset = "0"
fgCode :: Color256 -> String
fgCode = (++) "38;5;" . toString
bgCode :: Color256 -> String
bgCode = (++) "48;5;" . toString
ulCode :: String
ulCode = "4"
bdCode :: String
bdCode = "1"
applyFormat :: Format -> String -> String
applyFormat (Format fg bg ul bd) s = concat
[ leader
, concat $ intersperse ";" $ mconcat
[ useMaybeZero $ fgCode ^$ fg
, useMaybeZero $ bgCode ^$ bg
, guard ul >> return ulCode
, guard bd >> return bdCode
]
, sgrCloser
, s
, leader
, reset
, sgrCloser
]
formatOut :: POut -> String
formatOut (MonoidFunctorElem o) = formatChunk o
formatOut MFNull = ""
formatOut (o1 :+++: o2) = formatOut o1 ++ formatOut o2
formatOut (MFApply (fmt, o)) = applyFormat fmt $ formatOut o
pprintWith :: (Pretty a) => (Doc -> Doc) -> a -> IO ()
pprintWith f = print . formatOut . execDoc . f . pretty
pprint :: (Pretty a) => a -> IO ()
pprint = pprintWith id
pprintWidth :: (Pretty a) => Int -> a -> IO ()
pprintWidth = pprintWith . localSetL maxColumnWidthL
pprintRibbon :: (Pretty a) => Int -> a -> IO ()
pprintRibbon = pprintWith . localSetL maxRibbonWidthL
ptrace :: (Pretty a) => a -> b -> b
ptrace a b = unsafePerformIO $ do
pprint a
return b
|
davdar/quals
|
src/FP/Console.hs
|
bsd-3-clause
| 1,418
| 0
| 11
| 310
| 554
| 293
| 261
| 49
| 1
|
{-# LANGUAGE DeriveFunctor #-}
module Data.Interface.Change.View where
import Data.Bifunctor ( bimap )
import Data.Interface.Change
-- | A @DiffView m@ for a `Monoid` @m@ is a pair of @m@s that represent the
-- two @a@s in a particular @Change a@, plus a possible @m@ that represents
-- a combined view of those @a@s.
data DiffView m = DiffView
{ viewCombined :: Maybe m
, viewSeparate :: Change m
} deriving (Show, Eq, Ord, Functor)
instance Applicative DiffView where
pure m = DiffView (Just m) (NoChange m)
DiffView fc fs <*> DiffView xc xs = DiffView (fc <*> xc) (fs <*> xs)
instance Monad DiffView where
return = pure
DiffView c s >>= f =
DiffView { viewCombined = viewCombined . f =<< c
, viewSeparate = viewSeparate . f =<< s
}
instance (Monoid m) => Monoid (DiffView m) where
mempty = pure mempty
DiffView ac as `mappend` DiffView bc bs =
DiffView (mappend <$> ac <*> bc) (mappend as bs)
changeView :: Change m -> DiffView m
changeView c = case c of
NoChange m -> DiffView (Just m) c
Change{} -> DiffView Nothing c
elemView :: (Monoid m) => Elem (Change m) m -> DiffView m
elemView e = case e of
Removed m -> DiffView Nothing $ Change m mempty
Added m -> DiffView Nothing $ Change mempty m
Elem c -> changeView c
type RenderCombined m = Elem (Replace m) m -> Maybe m
elemView' :: (Monoid m) => RenderCombined m -> Elem (Change m) m -> DiffView m
elemView' rc e = case e of
Elem NoChange{} -> elemView e
_ -> (elemView e) { viewCombined = rc $ mapElem toReplace e }
combineRC :: RenderCombined m -> RenderCombined n -> RenderCombined (m,n)
combineRC rc0 rc1 e =
(,) <$> rc0 (bimap (fmap fst) fst e) <*> rc1 (bimap (fmap snd) snd e)
|
cdxr/haskell-interface
|
src/Data/Interface/Change/View.hs
|
bsd-3-clause
| 1,775
| 0
| 11
| 443
| 657
| 330
| 327
| 37
| 3
|
{--
Growable square matrix, TODO this is not finished
--}
module PolyGraph.Common.BuildableMatrix (
MatrixDataSet
, emptyMatrix
--, addMatrixElement
--, toDataMatrix
) where
import qualified Data.Foldable as F
import qualified Data.Sequence as S
import qualified Data.Matrix as M
data MatrixDataSet a = MatrixDataSet {
size:: Int,
-- seq of rows
elements :: S.Seq (S.Seq a)
}
emptyMatrix :: forall a . MatrixDataSet a
emptyMatrix = MatrixDataSet {size = 0, elements=S.empty }
growMatrix :: forall a . (Num a) => Int -> MatrixDataSet a -> MatrixDataSet a
growMatrix amount matrix = let newsize = (size matrix) + amount
appendToEachRow = S.replicate amount 0
appendRows = S.replicate amount appendToEachRow :: S.Seq (S.Seq a)
wider = fmap (\r -> r S.>< appendToEachRow) (elements matrix) :: S.Seq (S.Seq a)
square = wider S.>< appendRows
in MatrixDataSet {size= newsize, elements = square}
-- auto-grows the matrix
-- | row -> column -> matrix
addMatrixElement :: forall a . (Num a) => Int -> Int -> a -> MatrixDataSet a -> MatrixDataSet a
addMatrixElement row column value matrix =
let newSize = (max row) . (max column) $ size matrix
growBy = newSize - row
newmatrix = if growBy > 0
then growMatrix growBy matrix
else matrix
oldelements = elements newmatrix
newelements = S.adjust (S.update column value) row
in undefined
toLists :: MatrixDataSet a -> [[a]]
toLists matrix = map (F.toList) (F.toList (elements matrix))
--TODO finish these
--fromLists :: Int -> [[a]] -> MatrixDataSet a
--fromLists size lists = undefined
toDataMatrix :: MatrixDataSet a -> M.Matrix a
toDataMatrix matrix = M.fromLists . toLists $ matrix
--fromDataMatrix :: Int -> M.Matrix a -> MatrixDataSet a
--fromDataMatrix size m = undefined
|
rpeszek/GraphPlay
|
src/PolyGraph/Common/BuildableMatrix.hs
|
bsd-3-clause
| 2,108
| 0
| 12
| 667
| 529
| 289
| 240
| -1
| -1
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Command
-- Copyright : Duncan Coutts 2007
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This is to do with command line handling. The Cabal command line is
-- organised into a number of named sub-commands (much like darcs). The
-- 'CommandUI' abstraction represents one of these sub-commands, with a name,
-- description, a set of flags. Commands can be associated with actions and
-- run. It handles some common stuff automatically, like the @--help@ and
-- command line completion flags. It is designed to allow other tools make
-- derived commands. This feature is used heavily in @cabal-install@.
{- All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Isaac Jones nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -}
module Distribution.Simple.Command (
-- * Command interface
CommandUI(..),
commandShowOptions,
-- ** Constructing commands
ShowOrParseArgs(..),
makeCommand,
-- ** Associating actions with commands
Command,
commandAddAction,
noExtraFlags,
-- ** Running commands
CommandParse(..),
commandsRun,
-- * Option Fields
OptionField(..), Name,
-- ** Constructing Option Fields
option, multiOption,
-- ** Liftings & Projections
liftOption, viewAsFieldDescr,
-- * Option Descriptions
OptDescr(..), Description, SFlags, LFlags, OptFlags, ArgPlaceHolder,
-- ** OptDescr 'smart' constructors
MkOptDescr,
reqArg, reqArg', optArg, optArg', noArg,
boolOpt, boolOpt', choiceOpt, choiceOptFromEnum
) where
import Control.Monad
import Data.Char (isAlpha, toLower)
import Data.List (sortBy)
import Data.Maybe
import Data.Monoid
import qualified Distribution.GetOpt as GetOpt
import Distribution.Text
( Text(disp, parse) )
import Distribution.ParseUtils
import Distribution.ReadE
import Distribution.Simple.Utils (die, intercalate)
import Text.PrettyPrint.HughesPJ ( punctuate, cat, comma, text, empty)
data CommandUI flags = CommandUI {
-- | The name of the command as it would be entered on the command line.
-- For example @\"build\"@.
commandName :: String,
-- | A short, one line description of the command to use in help texts.
commandSynopsis :: String,
-- | The useage line summary for this command
commandUsage :: String -> String,
-- | Additional explanation of the command to use in help texts.
commandDescription :: Maybe (String -> String),
-- | Initial \/ empty flags
commandDefaultFlags :: flags,
-- | All the Option fields for this command
commandOptions :: ShowOrParseArgs -> [OptionField flags]
}
data ShowOrParseArgs = ShowArgs | ParseArgs
type Name = String
type Description = String
-- | We usually have a datatype for storing configuration values, where
-- every field stores a configuration option, and the user sets
-- the value either via command line flags or a configuration file.
-- An individual OptionField models such a field, and we usually
-- build a list of options associated to a configuration datatype.
data OptionField a = OptionField {
optionName :: Name,
optionDescr :: [OptDescr a] }
-- | An OptionField takes one or more OptDescrs, describing the command line interface for the field.
data OptDescr a = ReqArg Description OptFlags ArgPlaceHolder (ReadE (a->a)) (a -> [String])
| OptArg Description OptFlags ArgPlaceHolder (ReadE (a->a)) (a->a) (a -> [Maybe String])
| ChoiceOpt [(Description, OptFlags, a->a, a -> Bool)]
| BoolOpt Description OptFlags{-True-} OptFlags{-False-} (Bool -> a -> a) (a-> Maybe Bool)
-- | Short command line option strings
type SFlags = [Char]
-- | Long command line option strings
type LFlags = [String]
type OptFlags = (SFlags,LFlags)
type ArgPlaceHolder = String
-- | Create an option taking a single OptDescr.
-- No explicit Name is given for the Option, the name is the first LFlag given.
option :: SFlags -> LFlags -> Description -> get -> set -> MkOptDescr get set a -> OptionField a
option sf lf@(n:_) d get set arg = OptionField n [arg sf lf d get set]
option _ _ _ _ _ _ = error "Distribution.command.option: An OptionField must have at least one LFlag"
-- | Create an option taking several OptDescrs.
-- You will have to give the flags and description individually to the OptDescr constructor.
multiOption :: Name -> get -> set
-> [get -> set -> OptDescr a] -- ^MkOptDescr constructors partially applied to flags and description.
-> OptionField a
multiOption n get set args = OptionField n [arg get set | arg <- args]
type MkOptDescr get set a = SFlags -> LFlags -> Description -> get -> set -> OptDescr a
-- | Create a string-valued command line interface.
reqArg :: Monoid b => ArgPlaceHolder -> ReadE b -> (b -> [String])
-> MkOptDescr (a -> b) (b -> a -> a) a
reqArg ad mkflag showflag sf lf d get set =
ReqArg d (sf,lf) ad (fmap (\a b -> set (get b `mappend` a) b) mkflag) (showflag . get)
-- | Create a string-valued command line interface with a default value.
optArg :: Monoid b => ArgPlaceHolder -> ReadE b -> b -> (b -> [Maybe String])
-> MkOptDescr (a -> b) (b -> a -> a) a
optArg ad mkflag def showflag sf lf d get set =
OptArg d (sf,lf) ad (fmap (\a b -> set (get b `mappend` a) b) mkflag)
(\b -> set (get b `mappend` def) b)
(showflag . get)
-- | (String -> a) variant of "reqArg"
reqArg' :: Monoid b => ArgPlaceHolder -> (String -> b) -> (b -> [String])
-> MkOptDescr (a -> b) (b -> a -> a) a
reqArg' ad mkflag showflag =
reqArg ad (succeedReadE mkflag) showflag
-- | (String -> a) variant of "optArg"
optArg' :: Monoid b => ArgPlaceHolder -> (Maybe String -> b) -> (b -> [Maybe String])
-> MkOptDescr (a -> b) (b -> a -> a) a
optArg' ad mkflag showflag =
optArg ad (succeedReadE (mkflag . Just)) def showflag
where def = mkflag Nothing
noArg :: (Eq b, Monoid b) => b -> MkOptDescr (a -> b) (b -> a -> a) a
noArg flag sf lf d = choiceOpt [(flag, (sf,lf), d)] sf lf d
boolOpt :: (b -> Maybe Bool) -> (Bool -> b) -> SFlags -> SFlags -> MkOptDescr (a -> b) (b -> a -> a) a
boolOpt g s sfT sfF _sf _lf@(n:_) d get set =
BoolOpt d (sfT, ["enable-"++n]) (sfF, ["disable-"++n]) (set.s) (g.get)
boolOpt _ _ _ _ _ _ _ _ _ = error "Distribution.Simple.Setup.boolOpt: unreachable"
boolOpt' :: (b -> Maybe Bool) -> (Bool -> b) -> OptFlags -> OptFlags -> MkOptDescr (a -> b) (b -> a -> a) a
boolOpt' g s ffT ffF _sf _lf d get set = BoolOpt d ffT ffF (set.s) (g . get)
-- | create a Choice option
choiceOpt :: Eq b => [(b,OptFlags,Description)] -> MkOptDescr (a -> b) (b -> a -> a) a
choiceOpt aa_ff _sf _lf _d get set = ChoiceOpt alts
where alts = [(d,flags, set alt, (==alt) . get) | (alt,flags,d) <- aa_ff]
-- | create a Choice option out of an enumeration type.
-- As long flags, the Show output is used. As short flags, the first character
-- which does not conflict with a previous one is used.
choiceOptFromEnum :: (Bounded b, Enum b, Show b, Eq b) => MkOptDescr (a -> b) (b -> a -> a) a
choiceOptFromEnum _sf _lf d get = choiceOpt [ (x, (sf, [map toLower $ show x]), d')
| (x, sf) <- sflags'
, let d' = d ++ show x]
_sf _lf d get
where sflags' = foldl f [] [firstOne..]
f prev x = let prevflags = concatMap snd prev in
prev ++ take 1 [(x, [toLower sf]) | sf <- show x, isAlpha sf
, toLower sf `notElem` prevflags]
firstOne = minBound `asTypeOf` get undefined
commandGetOpts :: ShowOrParseArgs -> CommandUI flags -> [GetOpt.OptDescr (flags -> flags)]
commandGetOpts showOrParse command =
concatMap viewAsGetOpt (commandOptions command showOrParse)
viewAsGetOpt :: OptionField a -> [GetOpt.OptDescr (a->a)]
viewAsGetOpt (OptionField _n aa) = concatMap optDescrToGetOpt aa
where
optDescrToGetOpt (ReqArg d (cs,ss) arg_desc set _) =
[GetOpt.Option cs ss (GetOpt.ReqArg set' arg_desc) d]
where set' = readEOrFail set
optDescrToGetOpt (OptArg d (cs,ss) arg_desc set def _) =
[GetOpt.Option cs ss (GetOpt.OptArg set' arg_desc) d]
where set' Nothing = def
set' (Just txt) = readEOrFail set txt
optDescrToGetOpt (ChoiceOpt alts) =
[GetOpt.Option sf lf (GetOpt.NoArg set) d | (d,(sf,lf),set,_) <- alts ]
optDescrToGetOpt (BoolOpt d (sfT,lfT) (sfF, lfF) set _) =
[ GetOpt.Option sfT lfT (GetOpt.NoArg (set True)) ("Enable " ++ d)
, GetOpt.Option sfF lfF (GetOpt.NoArg (set False)) ("Disable " ++ d) ]
-- | to view as a FieldDescr, we sort the list of interfaces (Req > Bool > Choice > Opt) and consider only the first one.
viewAsFieldDescr :: OptionField a -> FieldDescr a
viewAsFieldDescr (OptionField _n []) = error "Distribution.command.viewAsFieldDescr: unexpected"
viewAsFieldDescr (OptionField n dd) = FieldDescr n get set
where optDescr = head $ sortBy cmp dd
ReqArg{} `cmp` ReqArg{} = EQ
ReqArg{} `cmp` _ = GT
BoolOpt{} `cmp` ReqArg{} = LT
BoolOpt{} `cmp` BoolOpt{} = EQ
BoolOpt{} `cmp` _ = GT
ChoiceOpt{} `cmp` ReqArg{} = LT
ChoiceOpt{} `cmp` BoolOpt{} = LT
ChoiceOpt{} `cmp` ChoiceOpt{} = EQ
ChoiceOpt{} `cmp` _ = GT
OptArg{} `cmp` OptArg{} = EQ
OptArg{} `cmp` _ = LT
get t = case optDescr of
ReqArg _ _ _ _ ppr ->
(cat . punctuate comma . map text . ppr) t
OptArg _ _ _ _ _ ppr ->
case ppr t of
[] -> empty
(Nothing : _) -> text "True"
(Just a : _) -> text a
ChoiceOpt alts ->
fromMaybe empty $ listToMaybe
[ text lf | (_,(_,lf:_), _,enabled) <- alts, enabled t]
BoolOpt _ _ _ _ enabled -> (maybe empty disp . enabled) t
set line val a =
case optDescr of
ReqArg _ _ _ readE _ -> ($ a) `liftM` runE line n readE val
-- We parse for a single value instead of a list,
-- as one can't really implement parseList :: ReadE a -> ReadE [a]
-- with the current ReadE definition
ChoiceOpt{} -> case getChoiceByLongFlag optDescr val of
Just f -> return (f a)
_ -> syntaxError line val
BoolOpt _ _ _ setV _ -> (`setV` a) `liftM` runP line n parse val
OptArg _ _ _ _readE _ _ -> -- The behaviour in this case is not clear, and it has no use so far,
-- so we avoid future surprises by not implementing it.
error "Command.optionToFieldDescr: feature not implemented"
getChoiceByLongFlag :: OptDescr b -> String -> Maybe (b->b)
getChoiceByLongFlag (ChoiceOpt alts) val = listToMaybe [ set | (_,(_sf,lf:_), set, _) <- alts
, lf == val]
getChoiceByLongFlag _ _ = error "Distribution.command.getChoiceByLongFlag: expected a choice option"
getCurrentChoice :: OptDescr a -> a -> [String]
getCurrentChoice (ChoiceOpt alts) a =
[ lf | (_,(_sf,lf:_), _, currentChoice) <- alts, currentChoice a]
getCurrentChoice _ _ = error "Command.getChoice: expected a Choice OptDescr"
liftOption :: (b -> a) -> (a -> (b -> b)) -> OptionField a -> OptionField b
liftOption get' set' opt = opt { optionDescr = liftOptDescr get' set' `map` optionDescr opt}
liftOptDescr :: (b -> a) -> (a -> (b -> b)) -> OptDescr a -> OptDescr b
liftOptDescr get' set' (ChoiceOpt opts) =
ChoiceOpt [ (d, ff, liftSet get' set' set , (get . get'))
| (d, ff, set, get) <- opts]
liftOptDescr get' set' (OptArg d ff ad set def get) =
OptArg d ff ad (liftSet get' set' `fmap` set) (liftSet get' set' def) (get . get')
liftOptDescr get' set' (ReqArg d ff ad set get) =
ReqArg d ff ad (liftSet get' set' `fmap` set) (get . get')
liftOptDescr get' set' (BoolOpt d ffT ffF set get) =
BoolOpt d ffT ffF (liftSet get' set' . set) (get . get')
liftSet :: (b -> a) -> (a -> (b -> b)) -> (a -> a) -> b -> b
liftSet get' set' set x = set' (set $ get' x) x
-- | Show flags in the standard long option command line format
commandShowOptions :: CommandUI flags -> flags -> [String]
commandShowOptions command v = concat
[ showOptDescr v od | o <- commandOptions command ParseArgs
, od <- optionDescr o]
where
showOptDescr :: a -> OptDescr a -> [String]
showOptDescr x (BoolOpt _ (_,lfT:_) (_,lfF:_) _ enabled)
= case enabled x of
Nothing -> []
Just True -> ["--" ++ lfT]
Just False -> ["--" ++ lfF]
showOptDescr x c@ChoiceOpt{}
= ["--" ++ val | val <- getCurrentChoice c x]
showOptDescr x (ReqArg _ (_ssff,lf:_) _ _ showflag)
= [ "--"++lf++"="++flag
| flag <- showflag x ]
showOptDescr x (OptArg _ (_ssff,lf:_) _ _ _ showflag)
= [ case flag of
Just s -> "--"++lf++"="++s
Nothing -> "--"++lf
| flag <- showflag x ]
showOptDescr _ _
= error "Distribution.Simple.Command.showOptDescr: unreachable"
commandListOptions :: CommandUI flags -> [String]
commandListOptions command =
concatMap listOption $
addCommonFlags ShowArgs $ -- This is a slight hack, we don't want
-- "--list-options" showing up in the
-- list options output, so use ShowArgs
commandGetOpts ShowArgs command
where
listOption (GetOpt.Option shortNames longNames _ _) =
[ "-" ++ [name] | name <- shortNames ]
++ [ "--" ++ name | name <- longNames ]
-- | The help text for this command with descriptions of all the options.
commandHelp :: CommandUI flags -> String -> String
commandHelp command pname =
commandUsage command pname
++ (GetOpt.usageInfo ""
. addCommonFlags ShowArgs
$ commandGetOpts ShowArgs command)
++ case commandDescription command of
Nothing -> ""
Just desc -> '\n': desc pname
-- | Make a Command from standard 'GetOpt' options.
makeCommand :: String -- ^ name
-> String -- ^ short description
-> Maybe (String -> String) -- ^ long description
-> flags -- ^ initial\/empty flags
-> (ShowOrParseArgs -> [OptionField flags]) -- ^ options
-> CommandUI flags
makeCommand name shortDesc longDesc defaultFlags options =
CommandUI {
commandName = name,
commandSynopsis = shortDesc,
commandDescription = longDesc,
commandUsage = usage,
commandDefaultFlags = defaultFlags,
commandOptions = options
}
where usage pname = "Usage: " ++ pname ++ " " ++ name ++ " [FLAGS]\n\n"
++ "Flags for " ++ name ++ ":"
-- | Common flags that apply to every command
data CommonFlag = HelpFlag | ListOptionsFlag
commonFlags :: ShowOrParseArgs -> [GetOpt.OptDescr CommonFlag]
commonFlags showOrParseArgs = case showOrParseArgs of
ShowArgs -> [help]
ParseArgs -> [help, list]
where
help = GetOpt.Option helpShortFlags ["help"] (GetOpt.NoArg HelpFlag)
"Show this help text"
helpShortFlags = case showOrParseArgs of
ShowArgs -> ['h']
ParseArgs -> ['h', '?']
list = GetOpt.Option [] ["list-options"] (GetOpt.NoArg ListOptionsFlag)
"Print a list of command line flags"
addCommonFlags :: ShowOrParseArgs
-> [GetOpt.OptDescr a]
-> [GetOpt.OptDescr (Either CommonFlag a)]
addCommonFlags showOrParseArgs options =
map (fmapOptDesc Left) (commonFlags showOrParseArgs)
++ map (fmapOptDesc Right) options
where fmapOptDesc f (GetOpt.Option s l d m) =
GetOpt.Option s l (fmapArgDesc f d) m
fmapArgDesc f (GetOpt.NoArg a) = GetOpt.NoArg (f a)
fmapArgDesc f (GetOpt.ReqArg s d) = GetOpt.ReqArg (f . s) d
fmapArgDesc f (GetOpt.OptArg s d) = GetOpt.OptArg (f . s) d
commandParseArgs :: CommandUI flags -> Bool -> [String]
-> CommandParse (flags -> flags, [String])
commandParseArgs command global args =
let options = addCommonFlags ParseArgs
$ commandGetOpts ParseArgs command
order | global = GetOpt.RequireOrder
| otherwise = GetOpt.Permute
in case GetOpt.getOpt' order options args of
(flags, _, _, _)
| any listFlag flags -> CommandList (commandListOptions command)
| any helpFlag flags -> CommandHelp (commandHelp command)
where listFlag (Left ListOptionsFlag) = True; listFlag _ = False
helpFlag (Left HelpFlag) = True; helpFlag _ = False
(flags, opts, opts', [])
| global || null opts' -> CommandReadyToGo (accum flags, mix opts opts')
| otherwise -> CommandErrors (unrecognised opts')
(_, _, _, errs) -> CommandErrors errs
where -- Note: It is crucial to use reverse function composition here or to
-- reverse the flags here as we want to process the flags left to right
-- but data flow in function compsition is right to left.
accum flags = foldr (flip (.)) id [ f | Right f <- flags ]
unrecognised opts = [ "unrecognized option `" ++ opt ++ "'\n"
| opt <- opts ]
-- For unrecognised global flags we put them in the position just after
-- the command, if there is one. This gives us a chance to parse them
-- as sub-command rather than global flags.
mix [] ys = ys
mix (x:xs) ys = x:ys++xs
data CommandParse flags = CommandHelp (String -> String)
| CommandList [String]
| CommandErrors [String]
| CommandReadyToGo flags
instance Functor CommandParse where
fmap _ (CommandHelp help) = CommandHelp help
fmap _ (CommandList opts) = CommandList opts
fmap _ (CommandErrors errs) = CommandErrors errs
fmap f (CommandReadyToGo flags) = CommandReadyToGo (f flags)
data Command action = Command String String ([String] -> CommandParse action)
commandAddAction :: CommandUI flags
-> (flags -> [String] -> action)
-> Command action
commandAddAction command action =
Command (commandName command)
(commandSynopsis command)
(fmap (uncurry applyDefaultArgs)
. commandParseArgs command False)
where applyDefaultArgs mkflags args =
let flags = mkflags (commandDefaultFlags command)
in action flags args
commandsRun :: CommandUI a
-> [Command action]
-> [String]
-> CommandParse (a, CommandParse action)
commandsRun globalCommand commands args =
case commandParseArgs globalCommand' True args of
CommandHelp help -> CommandHelp help
CommandList opts -> CommandList (opts ++ commandNames)
CommandErrors errs -> CommandErrors errs
CommandReadyToGo (mkflags, args') -> case args' of
("help":cmdArgs) -> handleHelpCommand cmdArgs
(name:cmdArgs) -> case lookupCommand name of
[Command _ _ action] -> CommandReadyToGo (flags, action cmdArgs)
_ -> CommandReadyToGo (flags, badCommand name)
[] -> CommandReadyToGo (flags, noCommand)
where flags = mkflags (commandDefaultFlags globalCommand)
where
lookupCommand cname = [ cmd | cmd@(Command cname' _ _) <- commands'
, cname'==cname ]
noCommand = CommandErrors ["no command given (try --help)\n"]
badCommand cname = CommandErrors ["unrecognised command: " ++ cname
++ " (try --help)\n"]
commands' = commands ++ [commandAddAction helpCommandUI undefined]
commandNames = [ name | Command name _ _ <- commands' ]
globalCommand' = globalCommand {
commandUsage = \pname ->
(case commandUsage globalCommand pname of
"" -> ""
original -> original ++ "\n")
++ "Usage: " ++ pname ++ " COMMAND [FLAGS]\n"
++ " or: " ++ pname ++ " [GLOBAL FLAGS]\n\n"
++ "Global flags:",
commandDescription = Just $ \pname ->
"Commands:\n"
++ unlines [ " " ++ align name ++ " " ++ description
| Command name description _ <- commands' ]
++ case commandDescription globalCommand of
Nothing -> ""
Just desc -> '\n': desc pname
}
where maxlen = maximum [ length name | Command name _ _ <- commands' ]
align str = str ++ replicate (maxlen - length str) ' '
-- A bit of a hack: support "prog help" as a synonym of "prog --help"
-- furthermore, support "prog help command" as "prog command --help"
handleHelpCommand cmdArgs =
case commandParseArgs helpCommandUI True cmdArgs of
CommandHelp help -> CommandHelp help
CommandList list -> CommandList (list ++ commandNames)
CommandErrors _ -> CommandHelp globalHelp
CommandReadyToGo (_,[]) -> CommandHelp globalHelp
CommandReadyToGo (_,(name:cmdArgs')) ->
case lookupCommand name of
[Command _ _ action] ->
case action ("--help":cmdArgs') of
CommandHelp help -> CommandHelp help
CommandList _ -> CommandList []
_ -> CommandHelp globalHelp
_ -> badCommand name
where globalHelp = commandHelp globalCommand'
helpCommandUI =
(makeCommand "help" "Help about commands" Nothing () (const [])) {
commandUsage = \pname ->
"Usage: " ++ pname ++ " help [FLAGS]\n"
++ " or: " ++ pname ++ " help COMMAND [FLAGS]\n\n"
++ "Flags for help:"
}
-- | Utility function, many commands do not accept additional flags. This
-- action fails with a helpful error message if the user supplies any extra.
--
noExtraFlags :: [String] -> IO ()
noExtraFlags [] = return ()
noExtraFlags extraFlags =
die $ "Unrecognised flags: " ++ intercalate ", " extraFlags
--TODO: eliminate this function and turn it into a variant on commandAddAction
-- instead like commandAddActionNoArgs that doesn't supply the [String]
|
dcreager/cabal
|
Distribution/Simple/Command.hs
|
bsd-3-clause
| 24,533
| 0
| 21
| 7,118
| 6,497
| 3,426
| 3,071
| 359
| 20
|
-- Copyright 2021 Google LLC
--
-- Use of this source code is governed by a BSD-style
-- license that can be found in the LICENSE file or at
-- https://developers.google.com/open-source/licenses/bsd
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE OverloadedStrings #-}
module LLVM.JIT (
JIT, createJIT, destroyJIT, withJIT,
NativeModule, compileModule, unloadNativeModule, withNativeModule,
getFunctionPtr
) where
import LLVM.HEAD.JIT
|
google-research/dex-lang
|
src/lib/LLVM/JIT.hs
|
bsd-3-clause
| 483
| 0
| 4
| 70
| 49
| 35
| 14
| 8
| 0
|
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS -Wall -fwarn-tabs -fno-warn-type-defaults -fno-warn-unused-do-bind #-}
{-# LANGUAGE ScopedTypeVariables #-}
module BuilderTypes where
type Env = String
type Deps = [LibRef]
type Name = String
type Value = String
type Deploy = String
data LibRef = LibRef {grp :: String, artifact :: String, version :: String} deriving (Show)
data Item = Item (Name, Value) deriving (Show)
data Module = Module {mName::Name, items :: [Item], deps :: Deps} deriving (Show)
data Build = Build [Module] deriving (Show)
data Project = Project {env :: Env, buil :: Build, deploy :: Deploy} deriving (Show)
-- Get an item by Name from a list of Item
itemByName :: Name -> [Item] -> Either String Item
itemByName nm [] = Left ("No Item with name:" ++ (show nm))
itemByName nm (x:xs)
| nm == n' = Right x
| otherwise = itemByName nm xs
where Item (n', _) = x
-- ------------------------------------------------------
itemByNameInModule :: Module -> Name -> Either String Item
itemByNameInModule m n =itemByName n (items m)
-- ------------------------------------------------------
moduleName :: Module -> Value
moduleName m =
case itemByName "name" (items m) of
Right (Item (_, v)) -> v
Left _ -> "Module has no name!!"::Value
-- ------------------------------------------------------
moduleByName :: Name -> Project -> Either String Module
moduleByName n p =
case filter (\m -> mName m == n ) mods of
[] -> Left ("No module with name: " ++ (show n))
(a:[]) -> Right a
(_:_) -> Left ("Duplicate modeules with name: " ++ (show n)) -- won't happen!
where
Build mods = buil p
-- ------------------------------------------------------
itemNames :: Module -> [Name]
itemNames m = [ n | Item (n, _) <- items m]
-- ------------------------------------------------------
-- Is the supplied name the name of a module
isModule :: Name -> Project -> Bool
isModule name proj = name `elem` (moduleNames proj)
-- ------------------------------------------------------
-- Get a list of all module names in the project
moduleNames :: Project -> [Name]
moduleNames p = res where
Build mods = buil p
itms = concat [ items m | m <- mods ]
x = filter f itms where f (Item (name, _)) = name == "name"
res = [ v | Item (_, v) <- x]
|
mike-k-houghton/Builder
|
src/BuilderTypes.hs
|
bsd-3-clause
| 2,366
| 0
| 12
| 502
| 742
| 404
| 338
| 44
| 3
|
{-# Language ForeignFunctionInterface #-}
module Graphics.Efl.Canvas (
module M,
initCanvas, shutdownCanvas,
createCanvas, destroyCanvas,
focusCanvasIn, focusCanvasOut, isCanvasFocused,
increaseNoChangeCounter, decreaseNoChangeCounter,
attachCanvasData, getCanvasAttachedData,
addDamageRectangle, addObscuredRectangle, clearObscuredRegions,
renderCanvas, norenderCanvas, discardCanvasRenderingCache, discardCanvasData
) where
import Graphics.Efl.Canvas.Types as M
import Graphics.Efl.Canvas.BasicObject as M
import Graphics.Efl.Canvas.Rectangle as M
import Graphics.Efl.Canvas.Line as M
import Graphics.Efl.Canvas.Polygon as M
import Graphics.Efl.Canvas.Image as M
import Graphics.Efl.Canvas.Events as M
import Graphics.Efl.Canvas.MouseEvents as M
import Graphics.Efl.Canvas.MultiEvents as M
import Graphics.Efl.Canvas.KeyEvents as M
import Graphics.Efl.Canvas.MiscEvents as M
import Graphics.Efl.Canvas.Misc as M
import Graphics.Efl.Canvas.Text as M
import Graphics.Efl.Canvas.TextBlock as M
import Graphics.Efl.Canvas.Map as M
import Graphics.Efl.Canvas.Engine as M
import Graphics.Efl.Canvas.ViewPort as M
import Graphics.Efl.Canvas.Pointer as M
import Foreign.Ptr
import Foreign.C.Types
import Graphics.Efl.Eina
-- | Initialize the canvas manager. Consider using @getWindowCanvas@ instead
foreign import ccall "evas_init" initCanvas :: IO CInt
-- | Shutdown the canvas manager.
foreign import ccall "evas_shutdown" shutdownCanvas :: IO ()
-- | Create a canvas
foreign import ccall "evas_new" createCanvas :: IO Canvas
-- | Destroy a canvas
foreign import ccall "evas_free" destroyCanvas :: Canvas -> IO ()
-- | Inform the canvas that it got the focus
foreign import ccall "evas_focus_in" focusCanvasIn :: Canvas -> IO ()
-- | Inform the canvas that it lost the focus
foreign import ccall "evas_focus_out" focusCanvasOut :: Canvas -> IO ()
-- | Get the focus state known by the cancas
isCanvasFocused :: Canvas -> IO Bool
isCanvasFocused canvas = toBool <$> _evas_focus_state_get canvas
foreign import ccall "evas_focus_state_get" _evas_focus_state_get :: Canvas -> IO EinaBool
-- | Increase the no-change counter
--
-- This tells the canvas that while the no-change counter is greater than 0, do not
-- mark objects as "changed" when making changes.
foreign import ccall "evas_nochange_push" increaseNoChangeCounter :: Canvas -> IO ()
-- | Decrease the no-change counter
foreign import ccall "evas_nochange_pop" decreaseNoChangeCounter :: Canvas -> IO ()
-- | Attach data to the canvas
foreign import ccall "evas_data_attach_set" attachCanvasData :: Canvas -> Ptr () -> IO ()
-- | Get data attached to the canvas
foreign import ccall "evas_data_attach_get" getCanvasAttachedData :: Canvas -> IO (Ptr ())
-- | Add a damage rectangle
foreign import ccall "evas_damage_rectangle_add" addDamageRectangle :: Canvas -> CInt -> CInt -> CInt -> CInt -> IO ()
-- | Add an obscured rectangle
foreign import ccall "evas_obscured_rectangle_add" addObscuredRectangle :: Canvas -> CInt -> CInt -> CInt -> CInt -> IO ()
-- | Clear obscured regions
foreign import ccall "evas_obscured_clear" clearObscuredRegions :: Canvas -> IO ()
-- | Force renderization of the canvas
foreign import ccall "evas_render" renderCanvas :: Canvas -> IO ()
-- | Update the canvas internal objects but not triggering immediate renderization.
foreign import ccall "evas_norender" norenderCanvas :: Canvas -> IO ()
-- | Discard cached data used for the rendering
foreign import ccall "evas_render_idle_flush" discardCanvasRenderingCache :: Canvas -> IO ()
-- | Make the canvas discard as much data as possible used by the engine at runtime.
foreign import ccall "evas_render_dump" discardCanvasData :: Canvas -> IO ()
|
hsyl20/graphics-efl
|
src/Graphics/Efl/Canvas.hs
|
bsd-3-clause
| 3,730
| 0
| 12
| 530
| 702
| 429
| 273
| 51
| 1
|
module OrdRequiresEq where
data Uni = Uni
deriving (Ord)
instance Eq Uni where
(==) Uni Uni = True
|
phischu/fragnix
|
tests/quick/OrdRequiresEq/OrdRequiresEq.hs
|
bsd-3-clause
| 109
| 0
| 6
| 28
| 38
| 22
| 16
| 5
| 0
|
module Main where
import BasePrelude
import Control.Lens.Basic
-- Uses the Strict Record syntax.
type Person =
{!
name :: String,
birthday :: {! year :: Int, month :: Int, day :: Int },
country :: Country
}
-- Uses the Lazy Record syntax.
type Country =
{~
name :: String,
language :: String
}
person :: Person
person =
{!
name = "Yuri Alekseyevich Gagarin",
birthday = {! year = 1934, month = 3, day = 9 },
country = {~ name = "Soviet Union", language = "Russian" }
}
-- Uses the Field-label Lens syntax.
main = do
putStrLn $ "Name: " <> show (view @name person)
putStrLn $ "Country: " <> show (view (@country . @name) person)
|
nikita-volkov/record-preprocessor-demo
|
record-preprocessor-demo/Main.hs
|
mit
| 690
| 19
| 13
| 181
| 142
| 99
| 43
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE CPP #-}
module Main where
import Lens.Micro ((^.), (&), (.~), (%~))
import Lens.Micro.TH (makeLenses)
import Control.Monad (void, forever)
import Control.Concurrent (threadDelay, forkIO)
#if !(MIN_VERSION_base(4,11,0))
import Data.Monoid
#endif
import qualified Graphics.Vty as V
import Brick.BChan
import Brick.Main
( App(..)
, showFirstCursor
, customMain
, continue
, halt
)
import Brick.AttrMap
( attrMap
)
import Brick.Types
( Widget
, Next
, EventM
, BrickEvent(..)
)
import Brick.Widgets.Core
( (<=>)
, str
)
data CustomEvent = Counter deriving Show
data St =
St { _stLastBrickEvent :: Maybe (BrickEvent () CustomEvent)
, _stCounter :: Int
}
makeLenses ''St
drawUI :: St -> [Widget ()]
drawUI st = [a]
where
a = (str $ "Last event: " <> (show $ st^.stLastBrickEvent))
<=>
(str $ "Counter value is: " <> (show $ st^.stCounter))
appEvent :: St -> BrickEvent () CustomEvent -> EventM () (Next St)
appEvent st e =
case e of
VtyEvent (V.EvKey V.KEsc []) -> halt st
VtyEvent _ -> continue $ st & stLastBrickEvent .~ (Just e)
AppEvent Counter -> continue $ st & stCounter %~ (+1)
& stLastBrickEvent .~ (Just e)
_ -> continue st
initialState :: St
initialState =
St { _stLastBrickEvent = Nothing
, _stCounter = 0
}
theApp :: App St CustomEvent ()
theApp =
App { appDraw = drawUI
, appChooseCursor = showFirstCursor
, appHandleEvent = appEvent
, appStartEvent = return
, appAttrMap = const $ attrMap V.defAttr []
}
main :: IO ()
main = do
chan <- newBChan 10
void $ forkIO $ forever $ do
writeBChan chan Counter
threadDelay 1000000
let buildVty = V.mkVty V.defaultConfig
initialVty <- buildVty
void $ customMain initialVty buildVty (Just chan) theApp initialState
|
sjakobi/brick
|
programs/CustomEventDemo.hs
|
bsd-3-clause
| 2,017
| 0
| 12
| 556
| 638
| 354
| 284
| 65
| 4
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[TcMonoType]{Typechecking user-specified @MonoTypes@}
-}
{-# LANGUAGE CPP #-}
module TcHsType (
tcHsSigType, tcHsSigTypeNC, tcHsDeriv, tcHsVectInst,
tcHsInstHead,
UserTypeCtxt(..),
-- Type checking type and class decls
kcLookupKind, kcTyClTyVars, tcTyClTyVars,
tcHsConArgType, tcDataKindSig,
tcClassSigType,
-- Kind-checking types
-- No kind generalisation, no checkValidType
kcHsTyVarBndrs, tcHsTyVarBndrs,
tcHsLiftedType, tcHsOpenType,
tcLHsType, tcCheckLHsType,
tcHsContext, tcInferApps, tcHsArgTys,
kindGeneralize, checkKind,
-- Sort-checking kinds
tcLHsKind,
-- Pattern type signatures
tcHsPatSigType, tcPatSig
) where
#include "HsVersions.h"
import HsSyn
import TcRnMonad
import TcEvidence( HsWrapper )
import TcEnv
import TcMType
import TcValidity
import TcUnify
import TcIface
import TcType
import Type
import TypeRep( Type(..) ) -- For the mkNakedXXX stuff
import Kind
import RdrName( lookupLocalRdrOcc )
import Var
import VarSet
import TyCon
import ConLike
import DataCon
import TysPrim ( liftedTypeKindTyConName, constraintKindTyConName )
import Class
import Name
import NameEnv
import TysWiredIn
import BasicTypes
import SrcLoc
import DynFlags ( ExtensionFlag( Opt_DataKinds ), getDynFlags )
import Unique
import UniqSupply
import Outputable
import FastString
import Util
import Data.Maybe( isNothing )
import Control.Monad ( unless, when, zipWithM )
import PrelNames( ipClassName, funTyConKey, allNameStrings )
{-
----------------------------
General notes
----------------------------
Generally speaking we now type-check types in three phases
1. kcHsType: kind check the HsType
*includes* performing any TH type splices;
so it returns a translated, and kind-annotated, type
2. dsHsType: convert from HsType to Type:
perform zonking
expand type synonyms [mkGenTyApps]
hoist the foralls [tcHsType]
3. checkValidType: check the validity of the resulting type
Often these steps are done one after the other (tcHsSigType).
But in mutually recursive groups of type and class decls we do
1 kind-check the whole group
2 build TyCons/Classes in a knot-tied way
3 check the validity of types in the now-unknotted TyCons/Classes
For example, when we find
(forall a m. m a -> m a)
we bind a,m to kind varibles and kind-check (m a -> m a). This makes
a get kind *, and m get kind *->*. Now we typecheck (m a -> m a) in
an environment that binds a and m suitably.
The kind checker passed to tcHsTyVars needs to look at enough to
establish the kind of the tyvar:
* For a group of type and class decls, it's just the group, not
the rest of the program
* For a tyvar bound in a pattern type signature, its the types
mentioned in the other type signatures in that bunch of patterns
* For a tyvar bound in a RULE, it's the type signatures on other
universally quantified variables in the rule
Note that this may occasionally give surprising results. For example:
data T a b = MkT (a b)
Here we deduce a::*->*, b::*
But equally valid would be a::(*->*)-> *, b::*->*
Validity checking
~~~~~~~~~~~~~~~~~
Some of the validity check could in principle be done by the kind checker,
but not all:
- During desugaring, we normalise by expanding type synonyms. Only
after this step can we check things like type-synonym saturation
e.g. type T k = k Int
type S a = a
Then (T S) is ok, because T is saturated; (T S) expands to (S Int);
and then S is saturated. This is a GHC extension.
- Similarly, also a GHC extension, we look through synonyms before complaining
about the form of a class or instance declaration
- Ambiguity checks involve functional dependencies, and it's easier to wait
until knots have been resolved before poking into them
Also, in a mutually recursive group of types, we can't look at the TyCon until we've
finished building the loop. So to keep things simple, we postpone most validity
checking until step (3).
Knot tying
~~~~~~~~~~
During step (1) we might fault in a TyCon defined in another module, and it might
(via a loop) refer back to a TyCon defined in this module. So when we tie a big
knot around type declarations with ARecThing, so that the fault-in code can get
the TyCon being defined.
************************************************************************
* *
Check types AND do validity checking
* *
************************************************************************
-}
tcHsSigType, tcHsSigTypeNC :: UserTypeCtxt -> LHsType Name -> TcM Type
-- NB: it's important that the foralls that come from the top-level
-- HsForAllTy in hs_ty occur *first* in the returned type.
-- See Note [Scoped] with TcSigInfo
tcHsSigType ctxt hs_ty
= addErrCtxt (pprSigCtxt ctxt empty (ppr hs_ty)) $
tcHsSigTypeNC ctxt hs_ty
tcHsSigTypeNC ctxt (L loc hs_ty)
= setSrcSpan loc $ -- The "In the type..." context
-- comes from the caller; hence "NC"
do { kind <- case expectedKindInCtxt ctxt of
Nothing -> newMetaKindVar
Just k -> return k
-- The kind is checked by checkValidType, and isn't necessarily
-- of kind * in a Template Haskell quote eg [t| Maybe |]
-- Generalise here: see Note [Kind generalisation]
; ty <- tcCheckHsTypeAndGen hs_ty kind
-- Zonk to expose kind information to checkValidType
; ty <- zonkSigType ty
; checkValidType ctxt ty
; return ty }
-----------------
tcHsInstHead :: UserTypeCtxt -> LHsType Name -> TcM ([TyVar], ThetaType, Class, [Type])
-- Like tcHsSigTypeNC, but for an instance head.
tcHsInstHead user_ctxt lhs_ty@(L loc hs_ty)
= setSrcSpan loc $ -- The "In the type..." context comes from the caller
do { inst_ty <- tc_inst_head hs_ty
; kvs <- zonkTcTypeAndFV inst_ty
; kvs <- kindGeneralize kvs
; inst_ty <- zonkSigType (mkForAllTys kvs inst_ty)
; checkValidInstance user_ctxt lhs_ty inst_ty }
tc_inst_head :: HsType Name -> TcM TcType
tc_inst_head (HsForAllTy _ _ hs_tvs hs_ctxt hs_ty)
= tcHsTyVarBndrs hs_tvs $ \ tvs ->
do { ctxt <- tcHsContext hs_ctxt
; ty <- tc_lhs_type hs_ty ekConstraint -- Body for forall has kind Constraint
; return (mkSigmaTy tvs ctxt ty) }
tc_inst_head hs_ty
= tc_hs_type hs_ty ekConstraint
-----------------
tcHsDeriv :: HsType Name -> TcM ([TyVar], Class, [Type], Kind)
-- Like tcHsSigTypeNC, but for the ...deriving( C t1 ty2 ) clause
-- Returns the C, [ty1, ty2, and the kind of C's *next* argument
-- E.g. class C (a::*) (b::k->k)
-- data T a b = ... deriving( C Int )
-- returns ([k], C, [k, Int], k->k)
-- Also checks that (C ty1 ty2 arg) :: Constraint
-- if arg has a suitable kind
tcHsDeriv hs_ty
= do { arg_kind <- newMetaKindVar
; ty <- tcCheckHsTypeAndGen hs_ty (mkArrowKind arg_kind constraintKind)
; ty <- zonkSigType ty
; arg_kind <- zonkSigType arg_kind
; let (tvs, pred) = splitForAllTys ty
; case getClassPredTys_maybe pred of
Just (cls, tys) -> return (tvs, cls, tys, arg_kind)
Nothing -> failWithTc (ptext (sLit "Illegal deriving item") <+> quotes (ppr hs_ty)) }
-- Used for 'VECTORISE [SCALAR] instance' declarations
--
tcHsVectInst :: LHsType Name -> TcM (Class, [Type])
tcHsVectInst ty
| Just (L _ cls_name, tys) <- splitLHsClassTy_maybe ty
= do { (cls, cls_kind) <- tcClass cls_name
; (arg_tys, _res_kind) <- tcInferApps cls_name cls_kind tys
; return (cls, arg_tys) }
| otherwise
= failWithTc $ ptext (sLit "Malformed instance type")
{-
These functions are used during knot-tying in
type and class declarations, when we have to
separate kind-checking, desugaring, and validity checking
************************************************************************
* *
The main kind checker: no validity checks here
* *
************************************************************************
First a couple of simple wrappers for kcHsType
-}
tcClassSigType :: LHsType Name -> TcM Type
tcClassSigType lhs_ty@(L _ hs_ty)
= addTypeCtxt lhs_ty $
do { ty <- tcCheckHsTypeAndGen hs_ty liftedTypeKind
; zonkSigType ty }
tcHsConArgType :: NewOrData -> LHsType Name -> TcM Type
-- Permit a bang, but discard it
tcHsConArgType NewType bty = tcHsLiftedType (getBangType bty)
-- Newtypes can't have bangs, but we don't check that
-- until checkValidDataCon, so do not want to crash here
tcHsConArgType DataType bty = tcHsOpenType (getBangType bty)
-- Can't allow an unlifted type for newtypes, because we're effectively
-- going to remove the constructor while coercing it to a lifted type.
-- And newtypes can't be bang'd
---------------------------
tcHsArgTys :: SDoc -> [LHsType Name] -> [Kind] -> TcM [TcType]
tcHsArgTys what tys kinds
= sequence [ addTypeCtxt ty $
tc_lhs_type ty (expArgKind what kind n)
| (ty,kind,n) <- zip3 tys kinds [1..] ]
tc_hs_arg_tys :: SDoc -> [LHsType Name] -> [Kind] -> TcM [TcType]
-- Just like tcHsArgTys but without the addTypeCtxt
tc_hs_arg_tys what tys kinds
= sequence [ tc_lhs_type ty (expArgKind what kind n)
| (ty,kind,n) <- zip3 tys kinds [1..] ]
---------------------------
tcHsOpenType, tcHsLiftedType :: LHsType Name -> TcM TcType
-- Used for type signatures
-- Do not do validity checking
tcHsOpenType ty = addTypeCtxt ty $ tc_lhs_type ty ekOpen
tcHsLiftedType ty = addTypeCtxt ty $ tc_lhs_type ty ekLifted
-- Like tcHsType, but takes an expected kind
tcCheckLHsType :: LHsType Name -> Kind -> TcM Type
tcCheckLHsType hs_ty exp_kind
= addTypeCtxt hs_ty $
tc_lhs_type hs_ty (EK exp_kind expectedKindMsg)
tcLHsType :: LHsType Name -> TcM (TcType, TcKind)
-- Called from outside: set the context
tcLHsType ty = addTypeCtxt ty (tc_infer_lhs_type ty)
---------------------------
tcCheckHsTypeAndGen :: HsType Name -> Kind -> TcM Type
-- Input type is HsType, not LhsType; the caller adds the context
-- Typecheck a type signature, and kind-generalise it
-- The result is not necessarily zonked, and has not been checked for validity
tcCheckHsTypeAndGen hs_ty kind
= do { ty <- tc_hs_type hs_ty (EK kind expectedKindMsg)
; traceTc "tcCheckHsTypeAndGen" (ppr hs_ty)
; kvs <- zonkTcTypeAndFV ty
; kvs <- kindGeneralize kvs
; return (mkForAllTys kvs ty) }
{-
Like tcExpr, tc_hs_type takes an expected kind which it unifies with
the kind it figures out. When we don't know what kind to expect, we use
tc_lhs_type_fresh, to first create a new meta kind variable and use that as
the expected kind.
-}
tc_infer_lhs_type :: LHsType Name -> TcM (TcType, TcKind)
tc_infer_lhs_type ty =
do { kv <- newMetaKindVar
; r <- tc_lhs_type ty (EK kv expectedKindMsg)
; return (r, kv) }
tc_lhs_type :: LHsType Name -> ExpKind -> TcM TcType
tc_lhs_type (L span ty) exp_kind
= setSrcSpan span $
do { traceTc "tc_lhs_type:" (ppr ty $$ ppr exp_kind)
; tc_hs_type ty exp_kind }
tc_lhs_types :: [(LHsType Name, ExpKind)] -> TcM [TcType]
tc_lhs_types tys_w_kinds = mapM (uncurry tc_lhs_type) tys_w_kinds
------------------------------------------
tc_fun_type :: HsType Name -> LHsType Name -> LHsType Name -> ExpKind -> TcM TcType
-- We need to recognise (->) so that we can construct a FunTy,
-- *and* we need to do by looking at the Name, not the TyCon
-- (see Note [Zonking inside the knot]). For example,
-- consider f :: (->) Int Int (Trac #7312)
tc_fun_type ty ty1 ty2 exp_kind@(EK _ ctxt)
= do { ty1' <- tc_lhs_type ty1 (EK openTypeKind ctxt)
; ty2' <- tc_lhs_type ty2 (EK openTypeKind ctxt)
; checkExpectedKind ty liftedTypeKind exp_kind
; return (mkFunTy ty1' ty2') }
------------------------------------------
tc_hs_type :: HsType Name -> ExpKind -> TcM TcType
tc_hs_type (HsParTy ty) exp_kind = tc_lhs_type ty exp_kind
tc_hs_type (HsDocTy ty _) exp_kind = tc_lhs_type ty exp_kind
tc_hs_type (HsQuasiQuoteTy {}) _ = panic "tc_hs_type: qq" -- Eliminated by renamer
tc_hs_type ty@(HsBangTy {}) _
-- While top-level bangs at this point are eliminated (eg !(Maybe Int)),
-- other kinds of bangs are not (eg ((!Maybe) Int)). These kinds of
-- bangs are invalid, so fail. (#7210)
= failWithTc (ptext (sLit "Unexpected strictness annotation:") <+> ppr ty)
tc_hs_type (HsRecTy _) _ = panic "tc_hs_type: record" -- Unwrapped by con decls
-- Record types (which only show up temporarily in constructor
-- signatures) should have been removed by now
---------- Functions and applications
tc_hs_type hs_ty@(HsTyVar name) exp_kind
= do { (ty, k) <- tcTyVar name
; checkExpectedKind hs_ty k exp_kind
; return ty }
tc_hs_type ty@(HsFunTy ty1 ty2) exp_kind
= tc_fun_type ty ty1 ty2 exp_kind
tc_hs_type hs_ty@(HsOpTy ty1 (_, l_op@(L _ op)) ty2) exp_kind
| op `hasKey` funTyConKey
= tc_fun_type hs_ty ty1 ty2 exp_kind
| otherwise
= do { (op', op_kind) <- tcTyVar op
; tys' <- tcCheckApps hs_ty l_op op_kind [ty1,ty2] exp_kind
; return (mkNakedAppTys op' tys') }
-- mkNakedAppTys: see Note [Zonking inside the knot]
tc_hs_type hs_ty@(HsAppTy ty1 ty2) exp_kind
-- | L _ (HsTyVar fun) <- fun_ty
-- , fun `hasKey` funTyConKey
-- , [fty1,fty2] <- arg_tys
-- = tc_fun_type hs_ty fty1 fty2 exp_kind
-- | otherwise
= do { (fun_ty', fun_kind) <- tc_infer_lhs_type fun_ty
; arg_tys' <- tcCheckApps hs_ty fun_ty fun_kind arg_tys exp_kind
; return (mkNakedAppTys fun_ty' arg_tys') }
-- mkNakedAppTys: see Note [Zonking inside the knot]
-- This looks fragile; how do we *know* that fun_ty isn't
-- a TyConApp, say (which is never supposed to appear in the
-- function position of an AppTy)?
where
(fun_ty, arg_tys) = splitHsAppTys ty1 [ty2]
--------- Foralls
tc_hs_type hs_ty@(HsForAllTy _ _ hs_tvs context ty) exp_kind@(EK exp_k _)
| isConstraintKind exp_k
= failWithTc (hang (ptext (sLit "Illegal constraint:")) 2 (ppr hs_ty))
| otherwise
= tcHsTyVarBndrs hs_tvs $ \ tvs' ->
-- Do not kind-generalise here! See Note [Kind generalisation]
do { ctxt' <- tcHsContext context
; ty' <- if null (unLoc context) then -- Plain forall, no context
tc_lhs_type ty exp_kind -- Why exp_kind? See Note [Body kind of forall]
else
-- If there is a context, then this forall is really a
-- _function_, so the kind of the result really is *
-- The body kind (result of the function can be * or #, hence ekOpen
do { checkExpectedKind hs_ty liftedTypeKind exp_kind
; tc_lhs_type ty ekOpen }
; return (mkSigmaTy tvs' ctxt' ty') }
--------- Lists, arrays, and tuples
tc_hs_type hs_ty@(HsListTy elt_ty) exp_kind
= do { tau_ty <- tc_lhs_type elt_ty ekLifted
; checkExpectedKind hs_ty liftedTypeKind exp_kind
; checkWiredInTyCon listTyCon
; return (mkListTy tau_ty) }
tc_hs_type hs_ty@(HsPArrTy elt_ty) exp_kind
= do { tau_ty <- tc_lhs_type elt_ty ekLifted
; checkExpectedKind hs_ty liftedTypeKind exp_kind
; checkWiredInTyCon parrTyCon
; return (mkPArrTy tau_ty) }
-- See Note [Distinguishing tuple kinds] in HsTypes
-- See Note [Inferring tuple kinds]
tc_hs_type hs_ty@(HsTupleTy HsBoxedOrConstraintTuple hs_tys) exp_kind@(EK exp_k _ctxt)
-- (NB: not zonking before looking at exp_k, to avoid left-right bias)
| Just tup_sort <- tupKindSort_maybe exp_k
= traceTc "tc_hs_type tuple" (ppr hs_tys) >>
tc_tuple hs_ty tup_sort hs_tys exp_kind
| otherwise
= do { traceTc "tc_hs_type tuple 2" (ppr hs_tys)
; (tys, kinds) <- mapAndUnzipM tc_infer_lhs_type hs_tys
; kinds <- mapM zonkTcKind kinds
-- Infer each arg type separately, because errors can be
-- confusing if we give them a shared kind. Eg Trac #7410
-- (Either Int, Int), we do not want to get an error saying
-- "the second argument of a tuple should have kind *->*"
; let (arg_kind, tup_sort)
= case [ (k,s) | k <- kinds
, Just s <- [tupKindSort_maybe k] ] of
((k,s) : _) -> (k,s)
[] -> (liftedTypeKind, BoxedTuple)
-- In the [] case, it's not clear what the kind is, so guess *
; sequence_ [ setSrcSpan loc $
checkExpectedKind ty kind
(expArgKind (ptext (sLit "a tuple")) arg_kind n)
| (ty@(L loc _),kind,n) <- zip3 hs_tys kinds [1..] ]
; finish_tuple hs_ty tup_sort tys exp_kind }
tc_hs_type hs_ty@(HsTupleTy hs_tup_sort tys) exp_kind
= tc_tuple hs_ty tup_sort tys exp_kind
where
tup_sort = case hs_tup_sort of -- Fourth case dealt with above
HsUnboxedTuple -> UnboxedTuple
HsBoxedTuple -> BoxedTuple
HsConstraintTuple -> ConstraintTuple
_ -> panic "tc_hs_type HsTupleTy"
--------- Promoted lists and tuples
tc_hs_type hs_ty@(HsExplicitListTy _k tys) exp_kind
= do { tks <- mapM tc_infer_lhs_type tys
; let taus = map fst tks
; kind <- unifyKinds (ptext (sLit "In a promoted list")) tks
; checkExpectedKind hs_ty (mkPromotedListTy kind) exp_kind
; return (foldr (mk_cons kind) (mk_nil kind) taus) }
where
mk_cons k a b = mkTyConApp (promoteDataCon consDataCon) [k, a, b]
mk_nil k = mkTyConApp (promoteDataCon nilDataCon) [k]
tc_hs_type hs_ty@(HsExplicitTupleTy _ tys) exp_kind
= do { tks <- mapM tc_infer_lhs_type tys
; let n = length tys
kind_con = promotedTupleTyCon BoxedTuple n
ty_con = promotedTupleDataCon BoxedTuple n
(taus, ks) = unzip tks
tup_k = mkTyConApp kind_con ks
; checkExpectedKind hs_ty tup_k exp_kind
; return (mkTyConApp ty_con (ks ++ taus)) }
--------- Constraint types
tc_hs_type ipTy@(HsIParamTy n ty) exp_kind
= do { ty' <- tc_lhs_type ty ekLifted
; checkExpectedKind ipTy constraintKind exp_kind
; ipClass <- tcLookupClass ipClassName
; let n' = mkStrLitTy $ hsIPNameFS n
; return (mkClassPred ipClass [n',ty'])
}
tc_hs_type ty@(HsEqTy ty1 ty2) exp_kind
= do { (ty1', kind1) <- tc_infer_lhs_type ty1
; (ty2', kind2) <- tc_infer_lhs_type ty2
; checkExpectedKind ty2 kind2
(EK kind1 msg_fn)
; checkExpectedKind ty constraintKind exp_kind
; return (mkNakedTyConApp eqTyCon [kind1, ty1', ty2']) }
where
msg_fn pkind = ptext (sLit "The left argument of the equality had kind")
<+> quotes (pprKind pkind)
--------- Misc
tc_hs_type (HsKindSig ty sig_k) exp_kind
= do { sig_k' <- tcLHsKind sig_k
; checkExpectedKind ty sig_k' exp_kind
; tc_lhs_type ty (EK sig_k' msg_fn) }
where
msg_fn pkind = ptext (sLit "The signature specified kind")
<+> quotes (pprKind pkind)
tc_hs_type (HsCoreTy ty) exp_kind
= do { checkExpectedKind ty (typeKind ty) exp_kind
; return ty }
-- This should never happen; type splices are expanded by the renamer
tc_hs_type ty@(HsSpliceTy {}) _exp_kind
= failWithTc (ptext (sLit "Unexpected type splice:") <+> ppr ty)
tc_hs_type (HsWrapTy {}) _exp_kind
= panic "tc_hs_type HsWrapTy" -- We kind checked something twice
tc_hs_type hs_ty@(HsTyLit (HsNumTy n)) exp_kind
= do { checkExpectedKind hs_ty typeNatKind exp_kind
; checkWiredInTyCon typeNatKindCon
; return (mkNumLitTy n) }
tc_hs_type hs_ty@(HsTyLit (HsStrTy s)) exp_kind
= do { checkExpectedKind hs_ty typeSymbolKind exp_kind
; checkWiredInTyCon typeSymbolKindCon
; return (mkStrLitTy s) }
tc_hs_type HsWildcardTy _ = panic "tc_hs_type HsWildcardTy"
-- unnamed wildcards should have been replaced by named wildcards
tc_hs_type hs_ty@(HsNamedWildcardTy name) exp_kind
= do { (ty, k) <- tcTyVar name
; checkExpectedKind hs_ty k exp_kind
; return ty }
---------------------------
tupKindSort_maybe :: TcKind -> Maybe TupleSort
tupKindSort_maybe k
| isConstraintKind k = Just ConstraintTuple
| isLiftedTypeKind k = Just BoxedTuple
| otherwise = Nothing
tc_tuple :: HsType Name -> TupleSort -> [LHsType Name] -> ExpKind -> TcM TcType
tc_tuple hs_ty tup_sort tys exp_kind
= do { tau_tys <- tc_hs_arg_tys cxt_doc tys (repeat arg_kind)
; finish_tuple hs_ty tup_sort tau_tys exp_kind }
where
arg_kind = case tup_sort of
BoxedTuple -> liftedTypeKind
UnboxedTuple -> openTypeKind
ConstraintTuple -> constraintKind
cxt_doc = case tup_sort of
BoxedTuple -> ptext (sLit "a tuple")
UnboxedTuple -> ptext (sLit "an unboxed tuple")
ConstraintTuple -> ptext (sLit "a constraint tuple")
finish_tuple :: HsType Name -> TupleSort -> [TcType] -> ExpKind -> TcM TcType
finish_tuple hs_ty tup_sort tau_tys exp_kind
= do { traceTc "finish_tuple" (ppr res_kind $$ ppr exp_kind $$ ppr exp_kind)
; checkExpectedKind hs_ty res_kind exp_kind
; checkWiredInTyCon tycon
; return (mkTyConApp tycon tau_tys) }
where
tycon = tupleTyCon tup_sort (length tau_tys)
res_kind = case tup_sort of
UnboxedTuple -> unliftedTypeKind
BoxedTuple -> liftedTypeKind
ConstraintTuple -> constraintKind
---------------------------
tcInferApps :: Outputable a
=> a
-> TcKind -- Function kind
-> [LHsType Name] -- Arg types
-> TcM ([TcType], TcKind) -- Kind-checked args
tcInferApps the_fun fun_kind args
= do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) fun_kind args
; args' <- tc_lhs_types args_w_kinds
; return (args', res_kind) }
tcCheckApps :: Outputable a
=> HsType Name -- The type being checked (for err messages only)
-> a -- The function
-> TcKind -> [LHsType Name] -- Fun kind and arg types
-> ExpKind -- Expected kind
-> TcM [TcType]
tcCheckApps hs_ty the_fun fun_kind args exp_kind
= do { (arg_tys, res_kind) <- tcInferApps the_fun fun_kind args
; checkExpectedKind hs_ty res_kind exp_kind
; return arg_tys }
---------------------------
splitFunKind :: SDoc -> TcKind -> [b] -> TcM ([(b,ExpKind)], TcKind)
splitFunKind the_fun fun_kind args
= go 1 fun_kind args
where
go _ fk [] = return ([], fk)
go arg_no fk (arg:args)
= do { mb_fk <- matchExpectedFunKind fk
; case mb_fk of
Nothing -> failWithTc too_many_args
Just (ak,fk') -> do { (aks, rk) <- go (arg_no+1) fk' args
; let exp_kind = expArgKind (quotes the_fun) ak arg_no
; return ((arg, exp_kind) : aks, rk) } }
too_many_args = quotes the_fun <+>
ptext (sLit "is applied to too many type arguments")
---------------------------
tcHsContext :: LHsContext Name -> TcM [PredType]
tcHsContext ctxt = mapM tcHsLPredType (unLoc ctxt)
tcHsLPredType :: LHsType Name -> TcM PredType
tcHsLPredType pred = tc_lhs_type pred ekConstraint
---------------------------
tcTyVar :: Name -> TcM (TcType, TcKind)
-- See Note [Type checking recursive type and class declarations]
-- in TcTyClsDecls
tcTyVar name -- Could be a tyvar, a tycon, or a datacon
= do { traceTc "lk1" (ppr name)
; thing <- tcLookup name
; case thing of
ATyVar _ tv
| isKindVar tv
-> failWithTc (ptext (sLit "Kind variable") <+> quotes (ppr tv)
<+> ptext (sLit "used as a type"))
| otherwise
-> return (mkTyVarTy tv, tyVarKind tv)
AThing kind -> do { tc <- get_loopy_tc name
; inst_tycon (mkNakedTyConApp tc) kind }
-- mkNakedTyConApp: see Note [Zonking inside the knot]
AGlobal (ATyCon tc) -> inst_tycon (mkTyConApp tc) (tyConKind tc)
AGlobal (AConLike (RealDataCon dc))
| Just tc <- promoteDataCon_maybe dc
-> do { data_kinds <- xoptM Opt_DataKinds
; unless data_kinds $ promotionErr name NoDataKinds
; inst_tycon (mkTyConApp tc) (tyConKind tc) }
| otherwise -> failWithTc (ptext (sLit "Data constructor") <+> quotes (ppr dc)
<+> ptext (sLit "comes from an un-promotable type")
<+> quotes (ppr (dataConTyCon dc)))
APromotionErr err -> promotionErr name err
_ -> wrongThingErr "type" thing name }
where
get_loopy_tc name
= do { env <- getGblEnv
; case lookupNameEnv (tcg_type_env env) name of
Just (ATyCon tc) -> return tc
_ -> return (aThingErr "tcTyVar" name) }
inst_tycon :: ([Type] -> Type) -> Kind -> TcM (Type, Kind)
-- Instantiate the polymorphic kind
-- Lazy in the TyCon
inst_tycon mk_tc_app kind
| null kvs
= return (mk_tc_app [], ki_body)
| otherwise
= do { traceTc "lk4" (ppr name <+> dcolon <+> ppr kind)
; ks <- mapM (const newMetaKindVar) kvs
; return (mk_tc_app ks, substKiWith kvs ks ki_body) }
where
(kvs, ki_body) = splitForAllTys kind
tcClass :: Name -> TcM (Class, TcKind)
tcClass cls -- Must be a class
= do { thing <- tcLookup cls
; case thing of
AThing kind -> return (aThingErr "tcClass" cls, kind)
AGlobal (ATyCon tc)
| Just cls <- tyConClass_maybe tc
-> return (cls, tyConKind tc)
_ -> wrongThingErr "class" thing cls }
aThingErr :: String -> Name -> b
-- The type checker for types is sometimes called simply to
-- do *kind* checking; and in that case it ignores the type
-- returned. Which is a good thing since it may not be available yet!
aThingErr str x = pprPanic "AThing evaluated unexpectedly" (text str <+> ppr x)
{-
Note [Zonking inside the knot]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we are checking the argument types of a data constructor. We
must zonk the types before making the DataCon, because once built we
can't change it. So we must traverse the type.
BUT the parent TyCon is knot-tied, so we can't look at it yet.
So we must be careful not to use "smart constructors" for types that
look at the TyCon or Class involved.
* Hence the use of mkNakedXXX functions. These do *not* enforce
the invariants (for example that we use (FunTy s t) rather
than (TyConApp (->) [s,t])).
* Ditto in zonkTcType (which may be applied more than once, eg to
squeeze out kind meta-variables), we are careful not to look at
the TyCon.
* We arrange to call zonkSigType *once* right at the end, and it
does establish the invariants. But in exchange we can't look
at the result (not even its structure) until we have emerged
from the "knot".
* TcHsSyn.zonkTcTypeToType also can safely check/establish
invariants.
This is horribly delicate. I hate it. A good example of how
delicate it is can be seen in Trac #7903.
-}
mkNakedTyConApp :: TyCon -> [Type] -> Type
-- Builds a TyConApp
-- * without being strict in TyCon,
-- * without satisfying the invariants of TyConApp
-- A subsequent zonking will establish the invariants
mkNakedTyConApp tc tys = TyConApp tc tys
mkNakedAppTys :: Type -> [Type] -> Type
mkNakedAppTys ty1 [] = ty1
mkNakedAppTys (TyConApp tc tys1) tys2 = mkNakedTyConApp tc (tys1 ++ tys2)
mkNakedAppTys ty1 tys2 = foldl AppTy ty1 tys2
zonkSigType :: TcType -> TcM TcType
-- Zonk the result of type-checking a user-written type signature
-- It may have kind variables in it, but no meta type variables
-- Because of knot-typing (see Note [Zonking inside the knot])
-- it may need to establish the Type invariants;
-- hence the use of mkTyConApp and mkAppTy
zonkSigType ty
= go ty
where
go (TyConApp tc tys) = do tys' <- mapM go tys
return (mkTyConApp tc tys')
-- Key point: establish Type invariants!
-- See Note [Zonking inside the knot]
go (LitTy n) = return (LitTy n)
go (FunTy arg res) = do arg' <- go arg
res' <- go res
return (FunTy arg' res')
go (AppTy fun arg) = do fun' <- go fun
arg' <- go arg
return (mkAppTy fun' arg')
-- NB the mkAppTy; we might have instantiated a
-- type variable to a type constructor, so we need
-- to pull the TyConApp to the top.
-- The two interesting cases!
go (TyVarTy tyvar) | isTcTyVar tyvar = zonkTcTyVar tyvar
| otherwise = TyVarTy <$> updateTyVarKindM go tyvar
-- Ordinary (non Tc) tyvars occur inside quantified types
go (ForAllTy tv ty) = do { tv' <- zonkTcTyVarBndr tv
; ty' <- go ty
; return (ForAllTy tv' ty') }
{-
Note [Body kind of a forall]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The body of a forall is usually a type, but in principle
there's no reason to prohibit *unlifted* types.
In fact, GHC can itself construct a function with an
unboxed tuple inside a for-all (via CPR analyis; see
typecheck/should_compile/tc170).
Moreover in instance heads we get forall-types with
kind Constraint.
Moreover if we have a signature
f :: Int#
then we represent it as (HsForAll Implicit [] [] Int#). And this must
be legal! We can't drop the empty forall until *after* typechecking
the body because of kind polymorphism:
Typeable :: forall k. k -> Constraint
data Apply f t = Apply (f t)
-- Apply :: forall k. (k -> *) -> k -> *
instance Typeable Apply where ...
Then the dfun has type
df :: forall k. Typeable ((k->*) -> k -> *) (Apply k)
f :: Typeable Apply
f :: forall (t:k->*) (a:k). t a -> t a
class C a b where
op :: a b -> Typeable Apply
data T a = MkT (Typeable Apply)
| T2 a
T :: * -> *
MkT :: forall k. (Typeable ((k->*) -> k -> *) (Apply k)) -> T a
f :: (forall (k:BOX). forall (t:: k->*) (a:k). t a -> t a) -> Int
f :: (forall a. a -> Typeable Apply) -> Int
So we *must* keep the HsForAll on the instance type
HsForAll Implicit [] [] (Typeable Apply)
so that we do kind generalisation on it.
Really we should check that it's a type of value kind
{*, Constraint, #}, but I'm not doing that yet
Example that should be rejected:
f :: (forall (a:*->*). a) Int
Note [Inferring tuple kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Give a tuple type (a,b,c), which the parser labels as HsBoxedOrConstraintTuple,
we try to figure out whether it's a tuple of kind * or Constraint.
Step 1: look at the expected kind
Step 2: infer argument kinds
If after Step 2 it's not clear from the arguments that it's
Constraint, then it must be *. Once having decided that we re-check
the Check the arguments again to give good error messages
in eg. `(Maybe, Maybe)`
Note that we will still fail to infer the correct kind in this case:
type T a = ((a,a), D a)
type family D :: Constraint -> Constraint
While kind checking T, we do not yet know the kind of D, so we will default the
kind of T to * -> *. It works if we annotate `a` with kind `Constraint`.
Note [Desugaring types]
~~~~~~~~~~~~~~~~~~~~~~~
The type desugarer is phase 2 of dealing with HsTypes. Specifically:
* It transforms from HsType to Type
* It zonks any kinds. The returned type should have no mutable kind
or type variables (hence returning Type not TcType):
- any unconstrained kind variables are defaulted to AnyK just
as in TcHsSyn.
- there are no mutable type variables because we are
kind-checking a type
Reason: the returned type may be put in a TyCon or DataCon where
it will never subsequently be zonked.
You might worry about nested scopes:
..a:kappa in scope..
let f :: forall b. T '[a,b] -> Int
In this case, f's type could have a mutable kind variable kappa in it;
and we might then default it to AnyK when dealing with f's type
signature. But we don't expect this to happen because we can't get a
lexically scoped type variable with a mutable kind variable in it. A
delicate point, this. If it becomes an issue we might need to
distinguish top-level from nested uses.
Moreover
* it cannot fail,
* it does no unifications
* it does no validity checking, except for structural matters, such as
(a) spurious ! annotations.
(b) a class used as a type
Note [Kind of a type splice]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider these terms, each with TH type splice inside:
[| e1 :: Maybe $(..blah..) |]
[| e2 :: $(..blah..) |]
When kind-checking the type signature, we'll kind-check the splice
$(..blah..); we want to give it a kind that can fit in any context,
as if $(..blah..) :: forall k. k.
In the e1 example, the context of the splice fixes kappa to *. But
in the e2 example, we'll desugar the type, zonking the kind unification
variables as we go. When we encounter the unconstrained kappa, we
want to default it to '*', not to AnyK.
Help functions for type applications
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-}
addTypeCtxt :: LHsType Name -> TcM a -> TcM a
-- Wrap a context around only if we want to show that contexts.
-- Omit invisble ones and ones user's won't grok
addTypeCtxt (L _ ty) thing
= addErrCtxt doc thing
where
doc = ptext (sLit "In the type") <+> quotes (ppr ty)
{-
************************************************************************
* *
Type-variable binders
* *
************************************************************************
-}
mkKindSigVar :: Name -> TcM KindVar
-- Use the specified name; don't clone it
mkKindSigVar n
= do { mb_thing <- tcLookupLcl_maybe n
; case mb_thing of
Just (AThing k)
| Just kvar <- getTyVar_maybe k
-> return kvar
_ -> return $ mkTcTyVar n superKind (SkolemTv False) }
kcScopedKindVars :: [Name] -> TcM a -> TcM a
-- Given some tyvar binders like [a (b :: k -> *) (c :: k)]
-- bind each scoped kind variable (k in this case) to a fresh
-- kind skolem variable
kcScopedKindVars kv_ns thing_inside
= do { kvs <- mapM (\n -> newSigTyVar n superKind) kv_ns
-- NB: use mutable signature variables
; tcExtendTyVarEnv2 (kv_ns `zip` kvs) thing_inside }
-- | Kind-check a 'LHsTyVarBndrs'. If the decl under consideration has a complete,
-- user-supplied kind signature (CUSK), generalise the result. Used in 'getInitialKind'
-- and in kind-checking. See also Note [Complete user-supplied kind signatures] in
-- HsDecls.
kcHsTyVarBndrs :: Bool -- ^ True <=> the decl being checked has a CUSK
-> LHsTyVarBndrs Name
-> TcM (Kind, r) -- ^ the result kind, possibly with other info
-> TcM (Kind, r) -- ^ The full kind of the thing being declared,
-- with the other info
kcHsTyVarBndrs cusk (HsQTvs { hsq_kvs = kv_ns, hsq_tvs = hs_tvs }) thing_inside
= do { kvs <- if cusk
then mapM mkKindSigVar kv_ns
else mapM (\n -> newSigTyVar n superKind) kv_ns
; tcExtendTyVarEnv2 (kv_ns `zip` kvs) $
do { nks <- mapM (kc_hs_tv . unLoc) hs_tvs
; (res_kind, stuff) <- tcExtendKindEnv nks thing_inside
; let full_kind = mkArrowKinds (map snd nks) res_kind
kvs = filter (not . isMetaTyVar) $
varSetElems $ tyVarsOfType full_kind
gen_kind = if cusk
then mkForAllTys kvs full_kind
else full_kind
; return (gen_kind, stuff) } }
where
kc_hs_tv :: HsTyVarBndr Name -> TcM (Name, TcKind)
kc_hs_tv (UserTyVar n)
= do { mb_thing <- tcLookupLcl_maybe n
; kind <- case mb_thing of
Just (AThing k) -> return k
_ | cusk -> return liftedTypeKind
| otherwise -> newMetaKindVar
; return (n, kind) }
kc_hs_tv (KindedTyVar n k)
= do { kind <- tcLHsKind k
-- In an associated type decl, the type variable may already
-- be in scope; in that case we want to make sure its kind
-- matches the one declared here
; mb_thing <- tcLookupLcl_maybe n
; case mb_thing of
Nothing -> return ()
Just (AThing ks) -> checkKind kind ks
Just thing -> pprPanic "check_in_scope" (ppr thing)
; return (n, kind) }
tcHsTyVarBndrs :: LHsTyVarBndrs Name
-> ([TcTyVar] -> TcM r)
-> TcM r
-- Bind the kind variables to fresh skolem variables
-- and type variables to skolems, each with a meta-kind variable kind
tcHsTyVarBndrs (HsQTvs { hsq_kvs = kv_ns, hsq_tvs = hs_tvs }) thing_inside
= do { kvs <- mapM mkKindSigVar kv_ns
; tcExtendTyVarEnv kvs $ do
{ tvs <- mapM tcHsTyVarBndr hs_tvs
; traceTc "tcHsTyVarBndrs {" (vcat [ text "Hs kind vars:" <+> ppr kv_ns
, text "Hs type vars:" <+> ppr hs_tvs
, text "Kind vars:" <+> ppr kvs
, text "Type vars:" <+> ppr tvs ])
; res <- tcExtendTyVarEnv tvs (thing_inside (kvs ++ tvs))
; traceTc "tcHsTyVarBndrs }" (vcat [ text "Hs kind vars:" <+> ppr kv_ns
, text "Hs type vars:" <+> ppr hs_tvs
, text "Kind vars:" <+> ppr kvs
, text "Type vars:" <+> ppr tvs ])
; return res } }
tcHsTyVarBndr :: LHsTyVarBndr Name -> TcM TcTyVar
-- Return a type variable
-- initialised with a kind variable.
-- Typically the Kind inside the HsTyVarBndr will be a tyvar with a mutable kind
-- in it.
--
-- If the variable is already in scope return it, instead of introducing a new
-- one. This can occur in
-- instance C (a,b) where
-- type F (a,b) c = ...
-- Here a,b will be in scope when processing the associated type instance for F.
-- See Note [Associated type tyvar names] in Class
tcHsTyVarBndr (L _ hs_tv)
= do { let name = hsTyVarName hs_tv
; mb_tv <- tcLookupLcl_maybe name
; case mb_tv of {
Just (ATyVar _ tv) -> return tv ;
_ -> do
{ kind <- case hs_tv of
UserTyVar {} -> newMetaKindVar
KindedTyVar _ kind -> tcLHsKind kind
; return ( mkTcTyVar name kind (SkolemTv False)) } } }
------------------
kindGeneralize :: TyVarSet -> TcM [KindVar]
kindGeneralize tkvs
= do { gbl_tvs <- tcGetGlobalTyVars -- Already zonked
; quantifyTyVars gbl_tvs (filterVarSet isKindVar tkvs) }
-- ToDo: remove the (filter isKindVar)
-- Any type variables in tkvs will be in scope,
-- and hence in gbl_tvs, so after removing gbl_tvs
-- we should only have kind variables left
--
-- BUT there is a smelly case (to be fixed when TH is reorganised)
-- f t = [| e :: $t |]
-- When typechecking the body of the bracket, we typecheck $t to a
-- unification variable 'alpha', with no biding forall. We don't
-- want to kind-quantify it!
{-
Note [Kind generalisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~
We do kind generalisation only at the outer level of a type signature.
For example, consider
T :: forall k. k -> *
f :: (forall a. T a -> Int) -> Int
When kind-checking f's type signature we generalise the kind at
the outermost level, thus:
f1 :: forall k. (forall (a:k). T k a -> Int) -> Int -- YES!
and *not* at the inner forall:
f2 :: (forall k. forall (a:k). T k a -> Int) -> Int -- NO!
Reason: same as for HM inference on value level declarations,
we want to infer the most general type. The f2 type signature
would be *less applicable* than f1, because it requires a more
polymorphic argument.
Note [Kinds of quantified type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
tcTyVarBndrsGen quantifies over a specified list of type variables,
*and* over the kind variables mentioned in the kinds of those tyvars.
Note that we must zonk those kinds (obviously) but less obviously, we
must return type variables whose kinds are zonked too. Example
(a :: k7) where k7 := k9 -> k9
We must return
[k9, a:k9->k9]
and NOT
[k9, a:k7]
Reason: we're going to turn this into a for-all type,
forall k9. forall (a:k7). blah
which the type checker will then instantiate, and instantiate does not
look through unification variables!
Hence using zonked_kinds when forming tvs'.
-}
--------------------
-- getInitialKind has made a suitably-shaped kind for the type or class
-- Unpack it, and attribute those kinds to the type variables
-- Extend the env with bindings for the tyvars, taken from
-- the kind of the tycon/class. Give it to the thing inside, and
-- check the result kind matches
kcLookupKind :: Name -> TcM Kind
kcLookupKind nm
= do { tc_ty_thing <- tcLookup nm
; case tc_ty_thing of
AThing k -> return k
AGlobal (ATyCon tc) -> return (tyConKind tc)
_ -> pprPanic "kcLookupKind" (ppr tc_ty_thing) }
kcTyClTyVars :: Name -> LHsTyVarBndrs Name -> TcM a -> TcM a
-- Used for the type variables of a type or class decl,
-- when doing the initial kind-check.
kcTyClTyVars name (HsQTvs { hsq_kvs = kvs, hsq_tvs = hs_tvs }) thing_inside
= kcScopedKindVars kvs $
do { tc_kind <- kcLookupKind name
; let (_, mono_kind) = splitForAllTys tc_kind
-- if we have a FullKindSignature, the tc_kind may already
-- be generalized. The kvs get matched up while kind-checking
-- the types in kc_tv, below
(arg_ks, _res_k) = splitKindFunTysN (length hs_tvs) mono_kind
-- There should be enough arrows, because
-- getInitialKinds used the tcdTyVars
; name_ks <- zipWithM kc_tv hs_tvs arg_ks
; tcExtendKindEnv name_ks thing_inside }
where
-- getInitialKind has already gotten the kinds of these type
-- variables, but tiresomely we need to check them *again*
-- to match the kind variables they mention against the ones
-- we've freshly brought into scope
kc_tv :: LHsTyVarBndr Name -> Kind -> TcM (Name, Kind)
kc_tv (L _ (UserTyVar n)) exp_k
= return (n, exp_k)
kc_tv (L _ (KindedTyVar n hs_k)) exp_k
= do { k <- tcLHsKind hs_k
; checkKind k exp_k
; return (n, exp_k) }
-----------------------
tcTyClTyVars :: Name -> LHsTyVarBndrs Name -- LHS of the type or class decl
-> ([TyVar] -> Kind -> TcM a) -> TcM a
-- Used for the type variables of a type or class decl,
-- on the second pass when constructing the final result
-- (tcTyClTyVars T [a,b] thing_inside)
-- where T : forall k1 k2 (a:k1 -> *) (b:k1). k2 -> *
-- calls thing_inside with arguments
-- [k1,k2,a,b] (k2 -> *)
-- having also extended the type environment with bindings
-- for k1,k2,a,b
--
-- No need to freshen the k's because they are just skolem
-- constants here, and we are at top level anyway.
tcTyClTyVars tycon (HsQTvs { hsq_kvs = hs_kvs, hsq_tvs = hs_tvs }) thing_inside
= kcScopedKindVars hs_kvs $ -- Bind scoped kind vars to fresh kind univ vars
-- There may be fewer of these than the kvs of
-- the type constructor, of course
do { thing <- tcLookup tycon
; let { kind = case thing of
AThing kind -> kind
_ -> panic "tcTyClTyVars"
-- We only call tcTyClTyVars during typechecking in
-- TcTyClDecls, where the local env is extended with
-- the generalized_env (mapping Names to AThings).
; (kvs, body) = splitForAllTys kind
; (kinds, res) = splitKindFunTysN (length hs_tvs) body }
; tvs <- zipWithM tc_hs_tv hs_tvs kinds
; tcExtendTyVarEnv tvs (thing_inside (kvs ++ tvs) res) }
where
-- In the case of associated types, the renamer has
-- ensured that the names are in commmon
-- e.g. class C a_29 where
-- type T b_30 a_29 :: *
-- Here the a_29 is shared
tc_hs_tv (L _ (UserTyVar n)) kind = return (mkTyVar n kind)
tc_hs_tv (L _ (KindedTyVar n hs_k)) kind = do { tc_kind <- tcLHsKind hs_k
; checkKind kind tc_kind
; return (mkTyVar n kind) }
-----------------------------------
tcDataKindSig :: Kind -> TcM [TyVar]
-- GADT decls can have a (perhaps partial) kind signature
-- e.g. data T :: * -> * -> * where ...
-- This function makes up suitable (kinded) type variables for
-- the argument kinds, and checks that the result kind is indeed *.
-- We use it also to make up argument type variables for for data instances.
tcDataKindSig kind
= do { checkTc (isLiftedTypeKind res_kind) (badKindSig kind)
; span <- getSrcSpanM
; us <- newUniqueSupply
; rdr_env <- getLocalRdrEnv
; let uniqs = uniqsFromSupply us
occs = [ occ | str <- allNameStrings
, let occ = mkOccName tvName str
, isNothing (lookupLocalRdrOcc rdr_env occ) ]
-- Note [Avoid name clashes for associated data types]
; return [ mk_tv span uniq occ kind
| ((kind, occ), uniq) <- arg_kinds `zip` occs `zip` uniqs ] }
where
(arg_kinds, res_kind) = splitKindFunTys kind
mk_tv loc uniq occ kind
= mkTyVar (mkInternalName uniq occ loc) kind
badKindSig :: Kind -> SDoc
badKindSig kind
= hang (ptext (sLit "Kind signature on data type declaration has non-* return kind"))
2 (ppr kind)
{-
Note [Avoid name clashes for associated data types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider class C a b where
data D b :: * -> *
When typechecking the decl for D, we'll invent an extra type variable
for D, to fill out its kind. Ideally we don't want this type variable
to be 'a', because when pretty printing we'll get
class C a b where
data D b a0
(NB: the tidying happens in the conversion to IfaceSyn, which happens
as part of pretty-printing a TyThing.)
That's why we look in the LocalRdrEnv to see what's in scope. This is
important only to get nice-looking output when doing ":info C" in GHCi.
It isn't essential for correctness.
************************************************************************
* *
Scoped type variables
* *
************************************************************************
tcAddScopedTyVars is used for scoped type variables added by pattern
type signatures
e.g. \ ((x::a), (y::a)) -> x+y
They never have explicit kinds (because this is source-code only)
They are mutable (because they can get bound to a more specific type).
Usually we kind-infer and expand type splices, and then
tupecheck/desugar the type. That doesn't work well for scoped type
variables, because they scope left-right in patterns. (e.g. in the
example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
The current not-very-good plan is to
* find all the types in the patterns
* find their free tyvars
* do kind inference
* bring the kinded type vars into scope
* BUT throw away the kind-checked type
(we'll kind-check it again when we type-check the pattern)
This is bad because throwing away the kind checked type throws away
its splices. But too bad for now. [July 03]
Historical note:
We no longer specify that these type variables must be univerally
quantified (lots of email on the subject). If you want to put that
back in, you need to
a) Do a checkSigTyVars after thing_inside
b) More insidiously, don't pass in expected_ty, else
we unify with it too early and checkSigTyVars barfs
Instead you have to pass in a fresh ty var, and unify
it with expected_ty afterwards
-}
tcHsPatSigType :: UserTypeCtxt
-> HsWithBndrs Name (LHsType Name) -- The type signature
-> TcM ( Type -- The signature
, [(Name, TcTyVar)] -- The new bit of type environment, binding
-- the scoped type variables
, [(Name, TcTyVar)] ) -- The wildcards
-- Used for type-checking type signatures in
-- (a) patterns e.g f (x::Int) = e
-- (b) result signatures e.g. g x :: Int = e
-- (c) RULE forall bndrs e.g. forall (x::Int). f x = x
tcHsPatSigType ctxt (HsWB { hswb_cts = hs_ty, hswb_kvs = sig_kvs,
hswb_tvs = sig_tvs, hswb_wcs = sig_wcs })
= addErrCtxt (pprSigCtxt ctxt empty (ppr hs_ty)) $
do { kvs <- mapM new_kv sig_kvs
; tvs <- mapM new_tv sig_tvs
; nwc_tvs <- mapM newWildcardVarMetaKind sig_wcs
; let nwc_binds = sig_wcs `zip` nwc_tvs
ktv_binds = (sig_kvs `zip` kvs) ++ (sig_tvs `zip` tvs)
; sig_ty <- tcExtendTyVarEnv2 (ktv_binds ++ nwc_binds) $
tcHsLiftedType hs_ty
; sig_ty <- zonkSigType sig_ty
; checkValidType ctxt sig_ty
; emitWildcardHoleConstraints (zip sig_wcs nwc_tvs)
; return (sig_ty, ktv_binds, nwc_binds) }
where
new_kv name = new_tkv name superKind
new_tv name = do { kind <- newMetaKindVar
; new_tkv name kind }
new_tkv name kind -- See Note [Pattern signature binders]
= case ctxt of
RuleSigCtxt {} -> return (mkTcTyVar name kind (SkolemTv False))
_ -> newSigTyVar name kind -- See Note [Unifying SigTvs]
tcPatSig :: Bool -- True <=> pattern binding
-> HsWithBndrs Name (LHsType Name)
-> TcSigmaType
-> TcM (TcType, -- The type to use for "inside" the signature
[(Name, TcTyVar)], -- The new bit of type environment, binding
-- the scoped type variables
[(Name, TcTyVar)], -- The wildcards
HsWrapper) -- Coercion due to unification with actual ty
-- Of shape: res_ty ~ sig_ty
tcPatSig in_pat_bind sig res_ty
= do { (sig_ty, sig_tvs, sig_nwcs) <- tcHsPatSigType PatSigCtxt sig
-- sig_tvs are the type variables free in 'sig',
-- and not already in scope. These are the ones
-- that should be brought into scope
; if null sig_tvs then do {
-- Just do the subsumption check and return
wrap <- addErrCtxtM (mk_msg sig_ty) $
tcSubType_NC PatSigCtxt res_ty sig_ty
; return (sig_ty, [], sig_nwcs, wrap)
} else do
-- Type signature binds at least one scoped type variable
-- A pattern binding cannot bind scoped type variables
-- It is more convenient to make the test here
-- than in the renamer
{ when in_pat_bind (addErr (patBindSigErr sig_tvs))
-- Check that all newly-in-scope tyvars are in fact
-- constrained by the pattern. This catches tiresome
-- cases like
-- type T a = Int
-- f :: Int -> Int
-- f (x :: T a) = ...
-- Here 'a' doesn't get a binding. Sigh
; let bad_tvs = [ tv | (_, tv) <- sig_tvs
, not (tv `elemVarSet` exactTyVarsOfType sig_ty) ]
; checkTc (null bad_tvs) (badPatSigTvs sig_ty bad_tvs)
-- Now do a subsumption check of the pattern signature against res_ty
; wrap <- addErrCtxtM (mk_msg sig_ty) $
tcSubType_NC PatSigCtxt res_ty sig_ty
-- Phew!
; return (sig_ty, sig_tvs, sig_nwcs, wrap)
} }
where
mk_msg sig_ty tidy_env
= do { (tidy_env, sig_ty) <- zonkTidyTcType tidy_env sig_ty
; (tidy_env, res_ty) <- zonkTidyTcType tidy_env res_ty
; let msg = vcat [ hang (ptext (sLit "When checking that the pattern signature:"))
4 (ppr sig_ty)
, nest 2 (hang (ptext (sLit "fits the type of its context:"))
2 (ppr res_ty)) ]
; return (tidy_env, msg) }
patBindSigErr :: [(Name, TcTyVar)] -> SDoc
patBindSigErr sig_tvs
= hang (ptext (sLit "You cannot bind scoped type variable") <> plural sig_tvs
<+> pprQuotedList (map fst sig_tvs))
2 (ptext (sLit "in a pattern binding signature"))
{-
Note [Pattern signature binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data T = forall a. T a (a->Int)
f (T x (f :: a->Int) = blah)
Here
* The pattern (T p1 p2) creates a *skolem* type variable 'a_sk',
It must be a skolem so that that it retains its identity, and
TcErrors.getSkolemInfo can thereby find the binding site for the skolem.
* The type signature pattern (f :: a->Int) binds "a" -> a_sig in the envt
* Then unificaiton makes a_sig := a_sk
That's why we must make a_sig a MetaTv (albeit a SigTv),
not a SkolemTv, so that it can unify to a_sk.
For RULE binders, though, things are a bit different (yuk).
RULE "foo" forall (x::a) (y::[a]). f x y = ...
Here this really is the binding site of the type variable so we'd like
to use a skolem, so that we get a complaint if we unify two of them
together.
Note [Unifying SigTvs]
~~~~~~~~~~~~~~~~~~~~~~
ALAS we have no decent way of avoiding two SigTvs getting unified.
Consider
f (x::(a,b)) (y::c)) = [fst x, y]
Here we'd really like to complain that 'a' and 'c' are unified. But
for the reasons above we can't make a,b,c into skolems, so they
are just SigTvs that can unify. And indeed, this would be ok,
f x (y::c) = case x of
(x1 :: a1, True) -> [x,y]
(x1 :: a2, False) -> [x,y,y]
Here the type of x's first component is called 'a1' in one branch and
'a2' in the other. We could try insisting on the same OccName, but
they definitely won't have the sane lexical Name.
I think we could solve this by recording in a SigTv a list of all the
in-scope variables that it should not unify with, but it's fiddly.
************************************************************************
* *
Checking kinds
* *
************************************************************************
We would like to get a decent error message from
(a) Under-applied type constructors
f :: (Maybe, Maybe)
(b) Over-applied type constructors
f :: Int x -> Int x
-}
-- The ExpKind datatype means "expected kind" and contains
-- some info about just why that kind is expected, to improve
-- the error message on a mis-match
data ExpKind = EK TcKind (TcKind -> SDoc)
-- The second arg is function that takes a *tidied* version
-- of the first arg, and produces something like
-- "Expected kind k"
-- "Expected a constraint"
-- "The argument of Maybe should have kind k"
instance Outputable ExpKind where
ppr (EK k f) = f k
ekLifted, ekOpen, ekConstraint :: ExpKind
ekLifted = EK liftedTypeKind expectedKindMsg
ekOpen = EK openTypeKind expectedKindMsg
ekConstraint = EK constraintKind expectedKindMsg
expectedKindMsg :: TcKind -> SDoc
expectedKindMsg pkind
| isConstraintKind pkind = ptext (sLit "Expected a constraint")
| isOpenTypeKind pkind = ptext (sLit "Expected a type")
| otherwise = ptext (sLit "Expected kind") <+> quotes (pprKind pkind)
-- Build an ExpKind for arguments
expArgKind :: SDoc -> TcKind -> Int -> ExpKind
expArgKind exp kind arg_no = EK kind msg_fn
where
msg_fn pkind
= sep [ ptext (sLit "The") <+> speakNth arg_no
<+> ptext (sLit "argument of") <+> exp
, nest 2 $ ptext (sLit "should have kind")
<+> quotes (pprKind pkind) ]
unifyKinds :: SDoc -> [(TcType, TcKind)] -> TcM TcKind
unifyKinds fun act_kinds
= do { kind <- newMetaKindVar
; let check (arg_no, (ty, act_kind))
= checkExpectedKind ty act_kind (expArgKind (quotes fun) kind arg_no)
; mapM_ check (zip [1..] act_kinds)
; return kind }
checkKind :: TcKind -> TcKind -> TcM ()
checkKind act_kind exp_kind
= do { mb_subk <- unifyKindX act_kind exp_kind
; case mb_subk of
Just EQ -> return ()
_ -> unifyKindMisMatch act_kind exp_kind }
checkExpectedKind :: Outputable a => a -> TcKind -> ExpKind -> TcM ()
-- A fancy wrapper for 'unifyKindX', which tries
-- to give decent error messages.
-- (checkExpectedKind ty act_kind exp_kind)
-- checks that the actual kind act_kind is compatible
-- with the expected kind exp_kind
-- The first argument, ty, is used only in the error message generation
checkExpectedKind ty act_kind (EK exp_kind ek_ctxt)
= do { mb_subk <- unifyKindX act_kind exp_kind
-- Kind unification only generates definite errors
; case mb_subk of {
Just LT -> return () ; -- act_kind is a sub-kind of exp_kind
Just EQ -> return () ; -- The two are equal
_other -> do
{ -- So there's an error
-- Now to find out what sort
exp_kind <- zonkTcKind exp_kind
; act_kind <- zonkTcKind act_kind
; traceTc "checkExpectedKind" (ppr ty $$ ppr act_kind $$ ppr exp_kind)
; env0 <- tcInitTidyEnv
; dflags <- getDynFlags
; let (exp_as, _) = splitKindFunTys exp_kind
(act_as, _) = splitKindFunTys act_kind
n_exp_as = length exp_as
n_act_as = length act_as
n_diff_as = n_act_as - n_exp_as
(env1, tidy_exp_kind) = tidyOpenKind env0 exp_kind
(env2, tidy_act_kind) = tidyOpenKind env1 act_kind
occurs_check
| Just act_tv <- tcGetTyVar_maybe act_kind
= check_occ act_tv exp_kind
| Just exp_tv <- tcGetTyVar_maybe exp_kind
= check_occ exp_tv act_kind
| otherwise
= False
check_occ tv k = case occurCheckExpand dflags tv k of
OC_Occurs -> True
_bad -> False
err | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
= ptext (sLit "Expecting a lifted type, but") <+> quotes (ppr ty)
<+> ptext (sLit "is unlifted")
| isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
= ptext (sLit "Expecting an unlifted type, but") <+> quotes (ppr ty)
<+> ptext (sLit "is lifted")
| occurs_check -- Must precede the "more args expected" check
= ptext (sLit "Kind occurs check") $$ more_info
| n_exp_as < n_act_as -- E.g. [Maybe]
= vcat [ ptext (sLit "Expecting") <+>
speakN n_diff_as <+> ptext (sLit "more argument")
<> (if n_diff_as > 1 then char 's' else empty)
<+> ptext (sLit "to") <+> quotes (ppr ty)
, more_info ]
-- Now n_exp_as >= n_act_as. In the next two cases,
-- n_exp_as == 0, and hence so is n_act_as
| otherwise -- E.g. Monad [Int]
= more_info
more_info = sep [ ek_ctxt tidy_exp_kind <> comma
, nest 2 $ ptext (sLit "but") <+> quotes (ppr ty)
<+> ptext (sLit "has kind") <+> quotes (pprKind tidy_act_kind)]
; traceTc "checkExpectedKind 1" (ppr ty $$ ppr tidy_act_kind $$ ppr tidy_exp_kind $$ ppr env1 $$ ppr env2)
; failWithTcM (env2, err) } } }
{-
************************************************************************
* *
Sort checking kinds
* *
************************************************************************
tcLHsKind converts a user-written kind to an internal, sort-checked kind.
It does sort checking and desugaring at the same time, in one single pass.
It fails when the kinds are not well-formed (eg. data A :: * Int), or if there
are non-promotable or non-fully applied kinds.
-}
tcLHsKind :: LHsKind Name -> TcM Kind
tcLHsKind k = addErrCtxt (ptext (sLit "In the kind") <+> quotes (ppr k)) $
tc_lhs_kind k
tc_lhs_kind :: LHsKind Name -> TcM Kind
tc_lhs_kind (L span ki) = setSrcSpan span (tc_hs_kind ki)
-- The main worker
tc_hs_kind :: HsKind Name -> TcM Kind
tc_hs_kind (HsTyVar tc) = tc_kind_var_app tc []
tc_hs_kind k@(HsAppTy _ _) = tc_kind_app k []
tc_hs_kind (HsParTy ki) = tc_lhs_kind ki
tc_hs_kind (HsFunTy ki1 ki2) =
do kappa_ki1 <- tc_lhs_kind ki1
kappa_ki2 <- tc_lhs_kind ki2
return (mkArrowKind kappa_ki1 kappa_ki2)
tc_hs_kind (HsListTy ki) =
do kappa <- tc_lhs_kind ki
checkWiredInTyCon listTyCon
return $ mkPromotedListTy kappa
tc_hs_kind (HsTupleTy _ kis) =
do kappas <- mapM tc_lhs_kind kis
checkWiredInTyCon tycon
return $ mkTyConApp tycon kappas
where
tycon = promotedTupleTyCon BoxedTuple (length kis)
-- Argument not kind-shaped
tc_hs_kind k = pprPanic "tc_hs_kind" (ppr k)
-- Special case for kind application
tc_kind_app :: HsKind Name -> [LHsKind Name] -> TcM Kind
tc_kind_app (HsAppTy ki1 ki2) kis = tc_kind_app (unLoc ki1) (ki2:kis)
tc_kind_app (HsTyVar tc) kis = do { arg_kis <- mapM tc_lhs_kind kis
; tc_kind_var_app tc arg_kis }
tc_kind_app ki _ = failWithTc (quotes (ppr ki) <+>
ptext (sLit "is not a kind constructor"))
tc_kind_var_app :: Name -> [Kind] -> TcM Kind
-- Special case for * and Constraint kinds
-- They are kinds already, so we don't need to promote them
tc_kind_var_app name arg_kis
| name == liftedTypeKindTyConName
|| name == constraintKindTyConName
= do { unless (null arg_kis)
(failWithTc (text "Kind" <+> ppr name <+> text "cannot be applied"))
; thing <- tcLookup name
; case thing of
AGlobal (ATyCon tc) -> return (mkTyConApp tc [])
_ -> panic "tc_kind_var_app 1" }
-- General case
tc_kind_var_app name arg_kis
= do { thing <- tcLookup name
; case thing of
AGlobal (ATyCon tc)
-> do { data_kinds <- xoptM Opt_DataKinds
; unless data_kinds $ addErr (dataKindsErr name)
; case promotableTyCon_maybe tc of
Just prom_tc | arg_kis `lengthIs` tyConArity prom_tc
-> return (mkTyConApp prom_tc arg_kis)
Just _ -> tycon_err tc "is not fully applied"
Nothing -> tycon_err tc "is not promotable" }
-- A lexically scoped kind variable
ATyVar _ kind_var
| not (isKindVar kind_var)
-> failWithTc (ptext (sLit "Type variable") <+> quotes (ppr kind_var)
<+> ptext (sLit "used as a kind"))
| not (null arg_kis) -- Kind variables always have kind BOX,
-- so cannot be applied to anything
-> failWithTc (ptext (sLit "Kind variable") <+> quotes (ppr name)
<+> ptext (sLit "cannot appear in a function position"))
| otherwise
-> return (mkAppTys (mkTyVarTy kind_var) arg_kis)
-- It is in scope, but not what we expected
AThing _
| isTyVarName name
-> failWithTc (ptext (sLit "Type variable") <+> quotes (ppr name)
<+> ptext (sLit "used in a kind"))
| otherwise
-> failWithTc (hang (ptext (sLit "Type constructor") <+> quotes (ppr name)
<+> ptext (sLit "used in a kind"))
2 (ptext (sLit "inside its own recursive group")))
APromotionErr err -> promotionErr name err
_ -> wrongThingErr "promoted type" thing name
-- This really should not happen
}
where
tycon_err tc msg = failWithTc (quotes (ppr tc) <+> ptext (sLit "of kind")
<+> quotes (ppr (tyConKind tc)) <+> ptext (sLit msg))
dataKindsErr :: Name -> SDoc
dataKindsErr name
= hang (ptext (sLit "Illegal kind:") <+> quotes (ppr name))
2 (ptext (sLit "Perhaps you intended to use DataKinds"))
promotionErr :: Name -> PromotionErr -> TcM a
promotionErr name err
= failWithTc (hang (pprPECategory err <+> quotes (ppr name) <+> ptext (sLit "cannot be used here"))
2 (parens reason))
where
reason = case err of
FamDataConPE -> ptext (sLit "it comes from a data family instance")
NoDataKinds -> ptext (sLit "Perhaps you intended to use DataKinds")
_ -> ptext (sLit "it is defined and used in the same recursive group")
{-
************************************************************************
* *
Scoped type variables
* *
************************************************************************
-}
badPatSigTvs :: TcType -> [TyVar] -> SDoc
badPatSigTvs sig_ty bad_tvs
= vcat [ fsep [ptext (sLit "The type variable") <> plural bad_tvs,
quotes (pprWithCommas ppr bad_tvs),
ptext (sLit "should be bound by the pattern signature") <+> quotes (ppr sig_ty),
ptext (sLit "but are actually discarded by a type synonym") ]
, ptext (sLit "To fix this, expand the type synonym")
, ptext (sLit "[Note: I hope to lift this restriction in due course]") ]
unifyKindMisMatch :: TcKind -> TcKind -> TcM a
unifyKindMisMatch ki1 ki2 = do
ki1' <- zonkTcKind ki1
ki2' <- zonkTcKind ki2
let msg = hang (ptext (sLit "Couldn't match kind"))
2 (sep [quotes (ppr ki1'),
ptext (sLit "against"),
quotes (ppr ki2')])
failWithTc msg
|
bitemyapp/ghc
|
compiler/typecheck/TcHsType.hs
|
bsd-3-clause
| 68,518
| 106
| 26
| 20,302
| 11,985
| 6,144
| 5,841
| 793
| 8
|
{- |
Module : $Header$
Description : compute xml diffs
Copyright : (c) Christian Maeder, DFKI GmbH 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : portable
-}
module Common.XmlDiff where
import Common.ToXml
import Common.Utils as Utils
import Common.XPath
import Common.XUpdate
import Common.Lib.MapSet (setToMap)
import Data.List
import qualified Data.Set as Set
import qualified Data.Map as Map
import Text.XML.Light as XML
hetsTags :: UnordTags
hetsTags = Map.fromList
$ map (\ (e, as) -> (unqual e, Set.fromList $ map unqual as))
[ ("DGNode", ["name"])
, ("DGLink", ["linkid", "source", "target"])
, ("Axiom", [])
, ("Theorem", []) ]
{- for symbols the order matters. For axioms and theorems the names should be
stored separately -}
hetsXmlChanges :: Element -> Element -> [Change]
hetsXmlChanges e1 e2 = xmlDiff hetsTags [] Map.empty
[Elem $ cleanUpElem e1]
[Elem $ cleanUpElem e2]
hetsXmlDiff :: Element -> Element -> Element
hetsXmlDiff e = mkMods . hetsXmlChanges e
{- for elements, whose order does not matter, use the given attribute keys to
determine their equality. An empty set indicates an element that only contains
text to be compared. -}
type UnordTags = Map.Map QName (Set.Set QName)
-- keep track of the nth element with a given tag
type Count = Map.Map QName Int
{- we assume an element contains other elements and no text entries or just a
single text content -}
xmlDiff :: UnordTags -> [Step] -> Count -> [Content] -> [Content] -> [Change]
xmlDiff m stps em old new = case (old, filter validContent new) of
([], []) -> []
([], ns) ->
[Change (Add Append $ map contentToAddChange ns) $ pathToExpr stps]
(os, []) -> removeIns stps em os
(o : os, ns@(n : rt)) ->
if validContent o then
case o of
Elem e ->
let en = elName e
atts = elAttribs e
cs = elContent e
(nm, nstps) = extendPath en em stps
downDiffs = xmlElemDiff m nstps atts cs
restDiffs = xmlDiff m stps nm os
rmO = Change Remove (pathToExpr nstps) : restDiffs ns
in case Map.lookup en m of
Nothing -> case n of
Elem e2 | elName e2 == en ->
downDiffs e2
++ restDiffs rt
_ -> rmO
Just ats -> let
(mns, rns) = partition (matchElems en (strContent e) $
Map.intersection (attrMap atts) $ setToMap ats) ns
in case mns of
Elem mn : rm -> downDiffs mn
++ restDiffs (rm ++ rns)
_ -> rmO
XML.Text cd -> let inText = cdData cd in case n of
XML.Text cd2 | trim inText == trim nText
-> xmlDiff m stps em os rt
| otherwise -> Change (Update nText) (pathToExpr stps)
: xmlDiff m stps em os rt
where nText = cdData cd2
_ -> error "xmldiff2"
_ -> error "xmldiff"
else xmlDiff m stps em os ns
removeIns :: [Step] -> Count -> [Content] -> [Change]
removeIns stps em cs = case cs of
[] -> []
c : rs -> case c of
Elem e -> let
(nm, nstps) = extendPath (elName e) em stps
in Change Remove (pathToExpr nstps) : removeIns stps nm rs
_ -> Change (Update "") (pathToExpr stps) : removeIns stps em rs
-- does not work for multiple text entries
attrMap :: [Attr] -> Map.Map QName String
attrMap = Map.fromList . map (\ a -> (attrKey a, attrVal a))
matchElems :: QName -> String -> Map.Map QName String -> Content -> Bool
matchElems en t atts c = case c of
Elem e -> elName e == en
&& if Map.null atts then null (elChildren e) && strContent e == t else
Map.isSubmapOfBy (==) atts (attrMap $ elAttribs e)
_ -> False
xmlElemDiff :: UnordTags -> [Step] -> [Attr] -> [Content] -> Element -> [Change]
xmlElemDiff m nPath atts cs e2 = xmlAttrDiff nPath atts (elAttribs e2)
++ xmlDiff m nPath Map.empty cs (elContent e2)
xmlAttrDiff :: [Step] -> [Attr] -> [Attr] -> [Change]
xmlAttrDiff p a1 a2 = let
m1 = attrMap a1
m2 = attrMap a2
rms = Map.toList $ Map.difference m1 m2
ins = Map.toList $ Map.difference m2 m1
inter = Map.toList $ Map.filter (uncurry (/=))
$ Map.intersectionWith (,) m1 m2
addAttrStep a = pathToExpr $ Step Attribute (NameTest $ qName a) [] : p
in map (Change Remove . addAttrStep . fst) rms
++ map (\ (a, (_, v)) -> Change (Update v) $ addAttrStep a) inter
++ if null ins then [] else
[Change (Add Append $ map (AddAttr . uncurry Attr) ins) $ pathToExpr p]
pathToExpr :: [Step] -> Expr
pathToExpr = PathExpr Nothing . Path True . reverse
extendPath :: QName -> Count -> [Step] -> (Count, [Step])
extendPath en em stps = let
nm = Map.insertWith (+) en 1 em
i = Map.findWithDefault 1 en nm
nstps = Step Child (NameTest $ qName en) [PrimExpr Number $ show i] : stps
in (nm, nstps)
-- steps and predicates are reversed!
addPathNumber :: Int -> [Step] -> [Step]
addPathNumber i stps =
let e = PrimExpr Number $ show i
in case stps of
[] -> []
Step a n es : rs -> Step a n (e : es) : rs
contentToAddChange :: Content -> AddChange
contentToAddChange c = case c of
Elem e -> AddElem e
XML.Text t -> AddText $ cdData t
CRef s -> AddText s
mkXQName :: String -> QName
mkXQName s = (unqual s) { qPrefix = Just xupdateS }
changeToXml :: Change -> Element
changeToXml (Change csel pth) = let
sel = add_attr (mkAttr selectS $ show pth)
in case csel of
Add i as -> sel
. node (mkXQName $ showInsert i) $ map addsToXml as
Remove -> sel $ node (mkXQName removeS) ()
Update s -> sel $ node (mkXQName updateS) s
_ -> error "changeToXml"
addsToXml :: AddChange -> Content
addsToXml a = case a of
AddElem e -> Elem $ cleanUpElem e
AddAttr (Attr k v) -> Elem
. add_attr (mkNameAttr $ qName k) $ node (mkXQName attributeS) v
AddText s -> mkText s
_ -> error "addsToXml"
mkMods :: [Change] -> Element
mkMods = node (mkXQName "modifications") . map changeToXml
|
mariefarrell/Hets
|
Common/XmlDiff.hs
|
gpl-2.0
| 6,006
| 0
| 27
| 1,545
| 2,281
| 1,157
| 1,124
| 135
| 11
|
git test
|
jtapolczai/shapelessFS
|
test.hs
|
apache-2.0
| 9
| 0
| 5
| 2
| 7
| 2
| 5
| -1
| -1
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GADTs #-}
-- | Make changes to project or global configuration.
module Stack.ConfigCmd
(ConfigCmdSet(..)
,configCmdSetParser
,cfgCmdSet
,cfgCmdSetName
,cfgCmdName) where
import Stack.Prelude
import qualified Data.ByteString as S
import qualified Data.HashMap.Strict as HMap
import qualified Data.Text as T
import qualified Data.Yaml as Yaml
import qualified Options.Applicative as OA
import qualified Options.Applicative.Types as OA
import Path
import Path.IO
import Stack.Config (makeConcreteResolver, getProjectConfig, getImplicitGlobalProjectDir, LocalConfigStatus(..))
import Stack.Constants
import Stack.Snapshot (loadResolver)
import Stack.Types.Config
import Stack.Types.Resolver
data ConfigCmdSet
= ConfigCmdSetResolver AbstractResolver
| ConfigCmdSetSystemGhc CommandScope
Bool
| ConfigCmdSetInstallGhc CommandScope
Bool
data CommandScope
= CommandScopeGlobal
-- ^ Apply changes to the global configuration,
-- typically at @~/.stack/config.yaml@.
| CommandScopeProject
-- ^ Apply changes to the project @stack.yaml@.
configCmdSetScope :: ConfigCmdSet -> CommandScope
configCmdSetScope (ConfigCmdSetResolver _) = CommandScopeProject
configCmdSetScope (ConfigCmdSetSystemGhc scope _) = scope
configCmdSetScope (ConfigCmdSetInstallGhc scope _) = scope
cfgCmdSet
:: (HasConfig env, HasGHCVariant env)
=> GlobalOpts -> ConfigCmdSet -> RIO env ()
cfgCmdSet go cmd = do
conf <- view configL
configFilePath <-
case configCmdSetScope cmd of
CommandScopeProject -> do
mstackYamlOption <- forM (globalStackYaml go) resolveFile'
mstackYaml <- getProjectConfig mstackYamlOption
case mstackYaml of
LCSProject stackYaml -> return stackYaml
LCSNoProject -> liftM (</> stackDotYaml) (getImplicitGlobalProjectDir conf)
LCSNoConfig _ -> throwString "config command used when no local configuration available"
CommandScopeGlobal -> return (configUserConfigPath conf)
-- We don't need to worry about checking for a valid yaml here
(config :: Yaml.Object) <-
liftIO (Yaml.decodeFileEither (toFilePath configFilePath)) >>= either throwM return
newValue <- cfgCmdSetValue (parent configFilePath) cmd
let cmdKey = cfgCmdSetOptionName cmd
config' = HMap.insert cmdKey newValue config
if config' == config
then logInfo
(T.pack (toFilePath configFilePath) <>
" already contained the intended configuration and remains unchanged.")
else do
liftIO (S.writeFile (toFilePath configFilePath) (Yaml.encode config'))
logInfo (T.pack (toFilePath configFilePath) <> " has been updated.")
cfgCmdSetValue
:: (HasConfig env, HasGHCVariant env)
=> Path Abs Dir -- ^ root directory of project
-> ConfigCmdSet -> RIO env Yaml.Value
cfgCmdSetValue root (ConfigCmdSetResolver newResolver) = do
concreteResolver <- makeConcreteResolver (Just root) newResolver
-- Check that the snapshot actually exists
void $ loadResolver concreteResolver
return (Yaml.toJSON concreteResolver)
cfgCmdSetValue _ (ConfigCmdSetSystemGhc _ bool) =
return (Yaml.Bool bool)
cfgCmdSetValue _ (ConfigCmdSetInstallGhc _ bool) =
return (Yaml.Bool bool)
cfgCmdSetOptionName :: ConfigCmdSet -> Text
cfgCmdSetOptionName (ConfigCmdSetResolver _) = "resolver"
cfgCmdSetOptionName (ConfigCmdSetSystemGhc _ _) = configMonoidSystemGHCName
cfgCmdSetOptionName (ConfigCmdSetInstallGhc _ _) = configMonoidInstallGHCName
cfgCmdName :: String
cfgCmdName = "config"
cfgCmdSetName :: String
cfgCmdSetName = "set"
configCmdSetParser :: OA.Parser ConfigCmdSet
configCmdSetParser =
OA.hsubparser $
mconcat
[ OA.command
"resolver"
(OA.info
(ConfigCmdSetResolver <$>
OA.argument
readAbstractResolver
(OA.metavar "RESOLVER" <>
OA.help "E.g. \"nightly\" or \"lts-7.2\""))
(OA.progDesc
"Change the resolver of the current project. See https://docs.haskellstack.org/en/stable/yaml_configuration/#resolver for more info."))
, OA.command
(T.unpack configMonoidSystemGHCName)
(OA.info
(ConfigCmdSetSystemGhc <$> scopeFlag <*> boolArgument)
(OA.progDesc
"Configure whether stack should use a system GHC installation or not."))
, OA.command
(T.unpack configMonoidInstallGHCName)
(OA.info
(ConfigCmdSetInstallGhc <$> scopeFlag <*> boolArgument)
(OA.progDesc
"Configure whether stack should automatically install GHC when necessary."))
]
scopeFlag :: OA.Parser CommandScope
scopeFlag =
OA.flag
CommandScopeProject
CommandScopeGlobal
(OA.long "global" <>
OA.help
"Modify the global configuration (typically at \"~/.stack/config.yaml\") instead of the project stack.yaml.")
readBool :: OA.ReadM Bool
readBool = do
s <- OA.readerAsk
case s of
"true" -> return True
"false" -> return False
_ -> OA.readerError ("Invalid value " ++ show s ++ ": Expected \"true\" or \"false\"")
boolArgument :: OA.Parser Bool
boolArgument = OA.argument readBool (OA.metavar "true|false" <> OA.completeWith ["true", "false"])
|
MichielDerhaeg/stack
|
src/Stack/ConfigCmd.hs
|
bsd-3-clause
| 5,956
| 0
| 18
| 1,620
| 1,155
| 599
| 556
| 129
| 5
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
-- |
-- Module : Documentation.Haddock.Parser
-- Copyright : (c) Mateusz Kowalczyk 2013-2014,
-- Simon Hengel 2013
-- License : BSD-like
--
-- Maintainer : haddock@projects.haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Parser used for Haddock comments. For external users of this
-- library, the most commonly used combination of functions is going
-- to be
--
-- @'toRegular' . 'parseParas'@
module Documentation.Haddock.Parser ( parseString, parseParas
, overIdentifier, toRegular, Identifier
) where
import Control.Applicative
import Control.Arrow (first)
import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.Char (chr, isAsciiUpper)
import Data.List (stripPrefix, intercalate, unfoldr)
import Data.Maybe (fromMaybe)
import Data.Monoid
import Documentation.Haddock.Doc
import Documentation.Haddock.Parser.Monad hiding (take, endOfLine)
import Documentation.Haddock.Parser.Util
import Documentation.Haddock.Types
import Documentation.Haddock.Utf8
import Prelude hiding (takeWhile)
-- $setup
-- >>> :set -XOverloadedStrings
-- | Identifier string surrounded with opening and closing quotes/backticks.
type Identifier = (Char, String, Char)
-- | Drops the quotes/backticks around all identifiers, as if they
-- were valid but still 'String's.
toRegular :: DocH mod Identifier -> DocH mod String
toRegular = fmap (\(_, x, _) -> x)
-- | Maps over 'DocIdentifier's over 'String' with potentially failing
-- conversion using user-supplied function. If the conversion fails,
-- the identifier is deemed to not be valid and is treated as a
-- regular string.
overIdentifier :: (String -> Maybe a)
-> DocH mod Identifier
-> DocH mod a
overIdentifier f d = g d
where
g (DocIdentifier (o, x, e)) = case f x of
Nothing -> DocString $ o : x ++ [e]
Just x' -> DocIdentifier x'
g DocEmpty = DocEmpty
g (DocAppend x x') = DocAppend (g x) (g x')
g (DocString x) = DocString x
g (DocParagraph x) = DocParagraph $ g x
g (DocIdentifierUnchecked x) = DocIdentifierUnchecked x
g (DocModule x) = DocModule x
g (DocWarning x) = DocWarning $ g x
g (DocEmphasis x) = DocEmphasis $ g x
g (DocMonospaced x) = DocMonospaced $ g x
g (DocBold x) = DocBold $ g x
g (DocUnorderedList x) = DocUnorderedList $ fmap g x
g (DocOrderedList x) = DocOrderedList $ fmap g x
g (DocDefList x) = DocDefList $ fmap (\(y, z) -> (g y, g z)) x
g (DocCodeBlock x) = DocCodeBlock $ g x
g (DocHyperlink x) = DocHyperlink x
g (DocPic x) = DocPic x
g (DocMathInline x) = DocMathInline x
g (DocMathDisplay x) = DocMathDisplay x
g (DocAName x) = DocAName x
g (DocProperty x) = DocProperty x
g (DocExamples x) = DocExamples x
g (DocHeader (Header l x)) = DocHeader . Header l $ g x
parse :: Parser a -> BS.ByteString -> (ParserState, a)
parse p = either err id . parseOnly (p <* endOfInput)
where
err = error . ("Haddock.Parser.parse: " ++)
-- | Main entry point to the parser. Appends the newline character
-- to the input string.
parseParas :: String -- ^ String to parse
-> MetaDoc mod Identifier
parseParas input = case parseParasState input of
(state, a) -> MetaDoc { _meta = Meta { _version = parserStateSince state }
, _doc = a
}
parseParasState :: String -> (ParserState, DocH mod Identifier)
parseParasState =
parse (p <* skipSpace) . encodeUtf8 . (++ "\n") . filter (/= '\r')
where
p :: Parser (DocH mod Identifier)
p = docConcat <$> paragraph `sepBy` many (skipHorizontalSpace *> "\n")
parseParagraphs :: String -> Parser (DocH mod Identifier)
parseParagraphs input = case parseParasState input of
(state, a) -> setParserState state >> return a
-- | Parse a text paragraph. Actually just a wrapper over 'parseStringBS' which
-- drops leading whitespace and encodes the string to UTF8 first.
parseString :: String -> DocH mod Identifier
parseString = parseStringBS . encodeUtf8 . dropWhile isSpace . filter (/= '\r')
parseStringBS :: BS.ByteString -> DocH mod Identifier
parseStringBS = snd . parse p
where
p :: Parser (DocH mod Identifier)
p = docConcat <$> many (monospace <|> anchor <|> identifier <|> moduleName
<|> picture <|> mathDisplay <|> mathInline
<|> markdownImage
<|> hyperlink <|> bold
<|> emphasis <|> encodedChar <|> string'
<|> skipSpecialChar)
-- | Parses and processes
-- <https://en.wikipedia.org/wiki/Numeric_character_reference Numeric character references>
--
-- >>> parseString "A"
-- DocString "A"
encodedChar :: Parser (DocH mod a)
encodedChar = "&#" *> c <* ";"
where
c = DocString . return . chr <$> num
num = hex <|> decimal
hex = ("x" <|> "X") *> hexadecimal
-- | List of characters that we use to delimit any special markup.
-- Once we have checked for any of these and tried to parse the
-- relevant markup, we can assume they are used as regular text.
specialChar :: [Char]
specialChar = "_/<@\"&'`# "
-- | Plain, regular parser for text. Called as one of the last parsers
-- to ensure that we have already given a chance to more meaningful parsers
-- before capturing their characers.
string' :: Parser (DocH mod a)
string' = DocString . unescape . decodeUtf8 <$> takeWhile1_ (`notElem` specialChar)
where
unescape "" = ""
unescape ('\\':x:xs) = x : unescape xs
unescape (x:xs) = x : unescape xs
-- | Skips a single special character and treats it as a plain string.
-- This is done to skip over any special characters belonging to other
-- elements but which were not deemed meaningful at their positions.
skipSpecialChar :: Parser (DocH mod a)
skipSpecialChar = DocString . return <$> satisfy (`elem` specialChar)
-- | Emphasis parser.
--
-- >>> parseString "/Hello world/"
-- DocEmphasis (DocString "Hello world")
emphasis :: Parser (DocH mod Identifier)
emphasis = DocEmphasis . parseStringBS <$>
mfilter ('\n' `BS.notElem`) ("/" *> takeWhile1_ (/= '/') <* "/")
-- | Bold parser.
--
-- >>> parseString "__Hello world__"
-- DocBold (DocString "Hello world")
bold :: Parser (DocH mod Identifier)
bold = DocBold . parseStringBS <$> disallowNewline ("__" *> takeUntil "__")
disallowNewline :: Parser BS.ByteString -> Parser BS.ByteString
disallowNewline = mfilter ('\n' `BS.notElem`)
-- | Like `takeWhile`, but unconditionally take escaped characters.
takeWhile_ :: (Char -> Bool) -> Parser BS.ByteString
takeWhile_ p = scan False p_
where
p_ escaped c
| escaped = Just False
| not $ p c = Nothing
| otherwise = Just (c == '\\')
-- | Like `takeWhile1`, but unconditionally take escaped characters.
takeWhile1_ :: (Char -> Bool) -> Parser BS.ByteString
takeWhile1_ = mfilter (not . BS.null) . takeWhile_
-- | Text anchors to allow for jumping around the generated documentation.
--
-- >>> parseString "#Hello world#"
-- DocAName "Hello world"
anchor :: Parser (DocH mod a)
anchor = DocAName . decodeUtf8 <$>
disallowNewline ("#" *> takeWhile1_ (/= '#') <* "#")
-- | Monospaced strings.
--
-- >>> parseString "@cruel@"
-- DocMonospaced (DocString "cruel")
monospace :: Parser (DocH mod Identifier)
monospace = DocMonospaced . parseStringBS
<$> ("@" *> takeWhile1_ (/= '@') <* "@")
-- | Module names: we try our reasonable best to only allow valid
-- Haskell module names, with caveat about not matching on technically
-- valid unicode symbols.
moduleName :: Parser (DocH mod a)
moduleName = DocModule <$> (char '"' *> modid <* char '"')
where
modid = intercalate "." <$> conid `sepBy1` "."
conid = (:)
<$> satisfy isAsciiUpper
-- NOTE: According to Haskell 2010 we should actually only
-- accept {small | large | digit | ' } here. But as we can't
-- match on unicode characters, this is currently not possible.
-- Note that we allow ‘#’ to suport anchors.
<*> (decodeUtf8 <$> takeWhile (`notElem` (" .&[{}(=*)+]!|@/;,^?\"\n"::String)))
-- | Picture parser, surrounded by \<\< and \>\>. It's possible to specify
-- a title for the picture.
--
-- >>> parseString "<<hello.png>>"
-- DocPic (Picture {pictureUri = "hello.png", pictureTitle = Nothing})
-- >>> parseString "<<hello.png world>>"
-- DocPic (Picture {pictureUri = "hello.png", pictureTitle = Just "world"})
picture :: Parser (DocH mod a)
picture = DocPic . makeLabeled Picture . decodeUtf8
<$> disallowNewline ("<<" *> takeUntil ">>")
-- | Inline math parser, surrounded by \\( and \\).
--
-- >>> parseString "\\(\\int_{-\\infty}^{\\infty} e^{-x^2/2} = \\sqrt{2\\pi}\\)"
-- DocMathInline "\\int_{-\\infty}^{\\infty} e^{-x^2/2} = \\sqrt{2\\pi}"
mathInline :: Parser (DocH mod a)
mathInline = DocMathInline . decodeUtf8
<$> disallowNewline ("\\(" *> takeUntil "\\)")
-- | Display math parser, surrounded by \\[ and \\].
--
-- >>> parseString "\\[\\int_{-\\infty}^{\\infty} e^{-x^2/2} = \\sqrt{2\\pi}\\]"
-- DocMathDisplay "\\int_{-\\infty}^{\\infty} e^{-x^2/2} = \\sqrt{2\\pi}"
mathDisplay :: Parser (DocH mod a)
mathDisplay = DocMathDisplay . decodeUtf8
<$> ("\\[" *> takeUntil "\\]")
markdownImage :: Parser (DocH mod a)
markdownImage = fromHyperlink <$> ("!" *> linkParser)
where
fromHyperlink (Hyperlink url label) = DocPic (Picture url label)
-- | Paragraph parser, called by 'parseParas'.
paragraph :: Parser (DocH mod Identifier)
paragraph = examples <|> do
indent <- takeIndent
choice
[ since
, unorderedList indent
, orderedList indent
, birdtracks
, codeblock
, property
, header
, textParagraphThatStartsWithMarkdownLink
, definitionList indent
, docParagraph <$> textParagraph
]
since :: Parser (DocH mod a)
since = ("@since " *> version <* skipHorizontalSpace <* endOfLine) >>= setSince >> return DocEmpty
where
version = decimal `sepBy1'` "."
-- | Headers inside the comment denoted with @=@ signs, up to 6 levels
-- deep.
--
-- >>> snd <$> parseOnly header "= Hello"
-- Right (DocHeader (Header {headerLevel = 1, headerTitle = DocString "Hello"}))
-- >>> snd <$> parseOnly header "== World"
-- Right (DocHeader (Header {headerLevel = 2, headerTitle = DocString "World"}))
header :: Parser (DocH mod Identifier)
header = do
let psers = map (string . encodeUtf8 . concat . flip replicate "=") [6, 5 .. 1]
pser = foldl1 (<|>) psers
delim <- decodeUtf8 <$> pser
line <- skipHorizontalSpace *> nonEmptyLine >>= return . parseString
rest <- paragraph <|> return DocEmpty
return $ DocHeader (Header (length delim) line) `docAppend` rest
textParagraph :: Parser (DocH mod Identifier)
textParagraph = parseString . intercalate "\n" <$> many1 nonEmptyLine
textParagraphThatStartsWithMarkdownLink :: Parser (DocH mod Identifier)
textParagraphThatStartsWithMarkdownLink = docParagraph <$> (docAppend <$> markdownLink <*> optionalTextParagraph)
where
optionalTextParagraph :: Parser (DocH mod Identifier)
optionalTextParagraph = (docAppend <$> whitespace <*> textParagraph) <|> pure DocEmpty
whitespace :: Parser (DocH mod a)
whitespace = DocString <$> (f <$> takeHorizontalSpace <*> optional "\n")
where
f :: BS.ByteString -> Maybe BS.ByteString -> String
f xs (fromMaybe "" -> x)
| BS.null (xs <> x) = ""
| otherwise = " "
-- | Parses unordered (bullet) lists.
unorderedList :: BS.ByteString -> Parser (DocH mod Identifier)
unorderedList indent = DocUnorderedList <$> p
where
p = ("*" <|> "-") *> innerList indent p
-- | Parses ordered lists (numbered or dashed).
orderedList :: BS.ByteString -> Parser (DocH mod Identifier)
orderedList indent = DocOrderedList <$> p
where
p = (paren <|> dot) *> innerList indent p
dot = (decimal :: Parser Int) <* "."
paren = "(" *> decimal <* ")"
-- | Generic function collecting any further lines belonging to the
-- list entry and recursively collecting any further lists in the
-- same paragraph. Usually used as
--
-- > someListFunction = listBeginning *> innerList someListFunction
innerList :: BS.ByteString -> Parser [DocH mod Identifier]
-> Parser [DocH mod Identifier]
innerList indent item = do
c <- takeLine
(cs, items) <- more indent item
let contents = docParagraph . parseString . dropNLs . unlines $ c : cs
return $ case items of
Left p -> [contents `docAppend` p]
Right i -> contents : i
-- | Parses definition lists.
definitionList :: BS.ByteString -> Parser (DocH mod Identifier)
definitionList indent = DocDefList <$> p
where
p = do
label <- "[" *> (parseStringBS <$> takeWhile1 (`notElem` ("]\n" :: String))) <* ("]" <* optional ":")
c <- takeLine
(cs, items) <- more indent p
let contents = parseString . dropNLs . unlines $ c : cs
return $ case items of
Left x -> [(label, contents `docAppend` x)]
Right i -> (label, contents) : i
-- | Drops all trailing newlines.
dropNLs :: String -> String
dropNLs = reverse . dropWhile (== '\n') . reverse
-- | Main worker for 'innerList' and 'definitionList'.
-- We need the 'Either' here to be able to tell in the respective functions
-- whether we're dealing with the next list or a nested paragraph.
more :: Monoid a => BS.ByteString -> Parser a
-> Parser ([String], Either (DocH mod Identifier) a)
more indent item = innerParagraphs indent
<|> moreListItems indent item
<|> moreContent indent item
<|> pure ([], Right mempty)
-- | Used by 'innerList' and 'definitionList' to parse any nested paragraphs.
innerParagraphs :: BS.ByteString
-> Parser ([String], Either (DocH mod Identifier) a)
innerParagraphs indent = (,) [] . Left <$> ("\n" *> indentedParagraphs indent)
-- | Attempts to fetch the next list if possibly. Used by 'innerList' and
-- 'definitionList' to recursively grab lists that aren't separated by a whole
-- paragraph.
moreListItems :: BS.ByteString -> Parser a
-> Parser ([String], Either (DocH mod Identifier) a)
moreListItems indent item = (,) [] . Right <$> indentedItem
where
indentedItem = string indent *> skipSpace *> item
-- | Helper for 'innerList' and 'definitionList' which simply takes
-- a line of text and attempts to parse more list content with 'more'.
moreContent :: Monoid a => BS.ByteString -> Parser a
-> Parser ([String], Either (DocH mod Identifier) a)
moreContent indent item = first . (:) <$> nonEmptyLine <*> more indent item
-- | Parses an indented paragraph.
-- The indentation is 4 spaces.
indentedParagraphs :: BS.ByteString -> Parser (DocH mod Identifier)
indentedParagraphs indent =
(concat <$> dropFrontOfPara indent') >>= parseParagraphs
where
indent' = string $ BS.append indent " "
-- | Grab as many fully indented paragraphs as we can.
dropFrontOfPara :: Parser BS.ByteString -> Parser [String]
dropFrontOfPara sp = do
currentParagraph <- some (sp *> takeNonEmptyLine)
followingParagraphs <-
skipHorizontalSpace *> nextPar -- we have more paragraphs to take
<|> skipHorizontalSpace *> nlList -- end of the ride, remember the newline
<|> endOfInput *> return [] -- nothing more to take at all
return (currentParagraph ++ followingParagraphs)
where
nextPar = (++) <$> nlList <*> dropFrontOfPara sp
nlList = "\n" *> return ["\n"]
nonSpace :: BS.ByteString -> Parser BS.ByteString
nonSpace xs
| not $ any (not . isSpace) $ decodeUtf8 xs = fail "empty line"
| otherwise = return xs
-- | Takes a non-empty, not fully whitespace line.
--
-- Doesn't discard the trailing newline.
takeNonEmptyLine :: Parser String
takeNonEmptyLine = do
(++ "\n") . decodeUtf8 <$> (takeWhile1 (/= '\n') >>= nonSpace) <* "\n"
-- | Takes indentation of first non-empty line.
--
-- More precisely: skips all whitespace-only lines and returns indentation
-- (horizontal space, might be empty) of that non-empty line.
takeIndent :: Parser BS.ByteString
takeIndent = do
indent <- takeHorizontalSpace
"\n" *> takeIndent <|> return indent
-- | Blocks of text of the form:
--
-- >> foo
-- >> bar
-- >> baz
--
birdtracks :: Parser (DocH mod a)
birdtracks = DocCodeBlock . DocString . intercalate "\n" . stripSpace <$> many1 line
where
line = skipHorizontalSpace *> ">" *> takeLine
stripSpace :: [String] -> [String]
stripSpace = fromMaybe <*> mapM strip'
where
strip' (' ':xs') = Just xs'
strip' "" = Just ""
strip' _ = Nothing
-- | Parses examples. Examples are a paragraph level entitity (separated by an empty line).
-- Consecutive examples are accepted.
examples :: Parser (DocH mod a)
examples = DocExamples <$> (many (skipHorizontalSpace *> "\n") *> go)
where
go :: Parser [Example]
go = do
prefix <- decodeUtf8 <$> takeHorizontalSpace <* ">>>"
expr <- takeLine
(rs, es) <- resultAndMoreExamples
return (makeExample prefix expr rs : es)
where
resultAndMoreExamples :: Parser ([String], [Example])
resultAndMoreExamples = moreExamples <|> result <|> pure ([], [])
where
moreExamples :: Parser ([String], [Example])
moreExamples = (,) [] <$> go
result :: Parser ([String], [Example])
result = first . (:) <$> nonEmptyLine <*> resultAndMoreExamples
makeExample :: String -> String -> [String] -> Example
makeExample prefix expression res =
Example (strip expression) result
where
result = map (substituteBlankLine . tryStripPrefix) res
tryStripPrefix xs = fromMaybe xs (stripPrefix prefix xs)
substituteBlankLine "<BLANKLINE>" = ""
substituteBlankLine xs = xs
nonEmptyLine :: Parser String
nonEmptyLine = mfilter (any (not . isSpace)) takeLine
takeLine :: Parser String
takeLine = decodeUtf8 <$> takeWhile (/= '\n') <* endOfLine
endOfLine :: Parser ()
endOfLine = void "\n" <|> endOfInput
-- | Property parser.
--
-- >>> snd <$> parseOnly property "prop> hello world"
-- Right (DocProperty "hello world")
property :: Parser (DocH mod a)
property = DocProperty . strip . decodeUtf8 <$> ("prop>" *> takeWhile1 (/= '\n'))
-- |
-- Paragraph level codeblock. Anything between the two delimiting \@ is parsed
-- for markup.
codeblock :: Parser (DocH mod Identifier)
codeblock =
DocCodeBlock . parseStringBS . dropSpaces
<$> ("@" *> skipHorizontalSpace *> "\n" *> block' <* "@")
where
dropSpaces xs =
let rs = decodeUtf8 xs
in case splitByNl rs of
[] -> xs
ys -> case last ys of
' ':_ -> case mapM dropSpace ys of
Nothing -> xs
Just zs -> encodeUtf8 $ intercalate "\n" zs
_ -> xs
-- This is necessary because ‘lines’ swallows up a trailing newline
-- and we lose information about whether the last line belongs to @ or to
-- text which we need to decide whether we actually want to be dropping
-- anything at all.
splitByNl = unfoldr (\x -> case x of
'\n':s -> Just (span (/= '\n') s)
_ -> Nothing)
. ('\n' :)
dropSpace "" = Just ""
dropSpace (' ':xs) = Just xs
dropSpace _ = Nothing
block' = scan False p
where
p isNewline c
| isNewline && c == '@' = Nothing
| isNewline && isSpace c = Just isNewline
| otherwise = Just $ c == '\n'
hyperlink :: Parser (DocH mod a)
hyperlink = DocHyperlink . makeLabeled Hyperlink . decodeUtf8
<$> disallowNewline ("<" *> takeUntil ">")
<|> autoUrl
<|> markdownLink
markdownLink :: Parser (DocH mod a)
markdownLink = DocHyperlink <$> linkParser
linkParser :: Parser Hyperlink
linkParser = flip Hyperlink <$> label <*> (whitespace *> url)
where
label :: Parser (Maybe String)
label = Just . strip . decode <$> ("[" *> takeUntil "]")
whitespace :: Parser ()
whitespace = skipHorizontalSpace <* optional ("\n" *> skipHorizontalSpace)
url :: Parser String
url = rejectWhitespace (decode <$> ("(" *> takeUntil ")"))
rejectWhitespace :: MonadPlus m => m String -> m String
rejectWhitespace = mfilter (all (not . isSpace))
decode :: BS.ByteString -> String
decode = removeEscapes . decodeUtf8
-- | Looks for URL-like things to automatically hyperlink even if they
-- weren't marked as links.
autoUrl :: Parser (DocH mod a)
autoUrl = mkLink <$> url
where
url = mappend <$> ("http://" <|> "https://" <|> "ftp://") <*> takeWhile1 (not . isSpace)
mkLink :: BS.ByteString -> DocH mod a
mkLink s = case unsnoc s of
Just (xs, x) | x `elem` (",.!?" :: String) -> DocHyperlink (Hyperlink (decodeUtf8 xs) Nothing) `docAppend` DocString [x]
_ -> DocHyperlink (Hyperlink (decodeUtf8 s) Nothing)
-- | Parses strings between identifier delimiters. Consumes all input that it
-- deems to be valid in an identifier. Note that it simply blindly consumes
-- characters and does no actual validation itself.
parseValid :: Parser String
parseValid = p some
where
idChar = satisfy (`elem` ("_.!#$%&*+/<=>?@\\|-~:^"::String))
<|> digit <|> letter_ascii
p p' = do
vs' <- p' $ utf8String "⋆" <|> return <$> idChar
let vs = concat vs'
c <- peekChar'
case c of
'`' -> return vs
'\'' -> (\x -> vs ++ "'" ++ x) <$> ("'" *> p many') <|> return vs
_ -> fail "outofvalid"
-- | Parses UTF8 strings from ByteString streams.
utf8String :: String -> Parser String
utf8String x = decodeUtf8 <$> string (encodeUtf8 x)
-- | Parses identifiers with help of 'parseValid'. Asks GHC for
-- 'String' from the string it deems valid.
identifier :: Parser (DocH mod Identifier)
identifier = do
o <- idDelim
vid <- parseValid
e <- idDelim
return $ DocIdentifier (o, vid, e)
where
idDelim = char '\'' <|> char '`'
|
Helkafen/haddock
|
haddock-library/src/Documentation/Haddock/Parser.hs
|
bsd-2-clause
| 22,245
| 0
| 22
| 5,132
| 5,598
| 2,943
| 2,655
| 346
| 24
|
module D4 where
data Tree a = Leaf a | Branch (Tree a) (Tree a)
fringe :: (Tree a) -> [a]
fringe (Leaf x) = [x]
fringe (Branch left right)
= (fringe left) ++ (fringe right)
class SameOrNot a
where
isSameOrNot :: a -> a -> Bool
isNotSame :: a -> a -> Bool
instance SameOrNot Int
where
isSameOrNot a b = a == b
isNotSame a b = a /= b
sumSquares ((x : xs))
= (sq x) + (sumSquares xs)
where
sq x = x ^ pow
pow = 2
sumSquares [] = 0
|
kmate/HaRe
|
old/testing/renaming/D4_AstOut.hs
|
bsd-3-clause
| 489
| 0
| 8
| 157
| 234
| 123
| 111
| 17
| 1
|
import UnavailableModule
main :: IO ()
main = putStrLn "Hello"
|
tolysz/prepare-ghcjs
|
spec-lts8/cabal/Cabal/tests/PackageTests/BuildableField/Main.hs
|
bsd-3-clause
| 64
| 0
| 6
| 11
| 22
| 11
| 11
| 3
| 1
|
module A (
) where
-- This reproduces the issue where type variables would be lifted out in
-- different orders. Compare:
--
-- lvl =
-- \ (@ (c :: * -> *)) (@ (t :: * -> *)) ->
-- undefined
-- @ ((forall d. Data d => c (t d))
-- -> Maybe (c Node))
-- (some Callstack thing)
--
-- $cdataCast1 =
-- \ (@ (c :: * -> *)) (@ (t :: * -> *)) _ [Occ=Dead] ->
-- lvl @ c @ t
--
-- vs
--
-- lvl =
-- \ (@ (t :: * -> *)) (@ (c :: * -> *)) ->
-- undefined
-- @ ((forall d. Data d => c (t d))
-- -> Maybe (c Node))
-- (some Callstack thing)
--
-- $cdataCast1 =
-- \ (@ (c :: * -> *)) (@ (t :: * -> *)) _ [Occ=Dead] ->
-- lvl @ t @ c
import Data.Data
data Node = Node (Maybe Int) [Node]
instance Data Node where
gfoldl = gfoldl
gunfold = gunfold
toConstr = toConstr
dataTypeOf = dataTypeOf
dataCast1 _ = undefined
dataCast2 = dataCast2
gmapT = gmapT
gmapQl = gmapQl
gmapQr = gmapQr
gmapQ = gmapQ
gmapQi = gmapQi
gmapM = gmapM
gmapMp = gmapMp
gmapMo = gmapMo
|
oldmanmike/ghc
|
testsuite/tests/determinism/typecheck/A.hs
|
bsd-3-clause
| 1,036
| 0
| 8
| 306
| 139
| 92
| 47
| 18
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Lazy as B
import Data.ByteString.Lazy.Char8 ()
import qualified Network.Riak.Basic as RB
import Network.Riak.Connection (defaultClient)
import Network.Riak.Content
import Network.Riak.Types (Bucket(..), Key(..), Quorum(..))
client :: RB.Client
client = RB.Client "127.0.0.1" "8087" "test"
testBucket :: B.ByteString
testBucket = "testBucket"
testKey :: B.ByteString
testKey = "testKey"
testValue :: B.ByteString
testValue = "{something: 'blah'}"
putSomeData conn bucket key value = do
putStrLn ("Get: bucket=" ++ show bucket ++ ", key = " ++ show key ++ ", value = " ++ show value)
RB.put conn testBucket testKey Nothing (binary testValue) Default Default
putStrLn "=========================="
getSomeData conn bucket key = do
putStrLn ("Get: bucket=" ++ show bucket ++ ", key = " ++ show key)
b <- RB.get conn testBucket key Default
maybe (print "No value") (print) b
putStrLn "=========================="
deleteSomeData conn bucket key = do
putStrLn ("Delete: bucket=" ++ show bucket ++ ", key = " ++ show key)
RB.delete conn bucket key Default
putStrLn "=========================="
listBuckets conn = do
buckets <- RB.listBuckets conn
print buckets
main = do
c <- RB.connect client
a <- RB.ping c
listBuckets c
putSomeData c testBucket testKey (binary testValue)
getSomeData c testBucket testKey
deleteSomeData c testBucket testKey
getSomeData c testBucket testKey
|
tmcgilchrist/taste-of-haskell
|
src/Main.hs
|
mit
| 1,558
| 0
| 14
| 305
| 470
| 235
| 235
| 40
| 1
|
module CFDI.Types.TaxId where
import CFDI.Chainable
import CFDI.Types.Type
import Data.Text (Text, pack, unpack)
import Text.Regex (mkRegex)
import Text.Regex.Posix (matchTest)
newtype TaxId = TaxId Text deriving (Eq, Show)
instance Chainable TaxId where
chain (TaxId i) = i
instance Type TaxId where
parseExpr str
| matchTest regExp str = Right . TaxId $ pack str
| otherwise = Left $ DoesNotMatchExpr ".{1,40}"
where
regExp = mkRegex "^.{1,40}$"
render (TaxId i) = unpack i
|
yusent/cfdis
|
src/CFDI/Types/TaxId.hs
|
mit
| 518
| 0
| 9
| 112
| 177
| 94
| 83
| 15
| 0
|
module Control.Monad.Trans.Activatable (
-- * The 'Activatable' monad
Activatable, runActivatable, finalizeActivatable,
-- * The 'ActivatableT' monad transformer
ActivatableT(), runActivatableT, finalizeActivatableT,
-- * Activation-related types
ActivationError(..), Switched(..),
-- * Activation operations
tryActivate, switching, switching'
) where
import Control.Monad.Trans.Activatable.Internal
|
antalsz/hs-to-coq
|
src/lib/Control/Monad/Trans/Activatable.hs
|
mit
| 417
| 0
| 5
| 54
| 66
| 47
| 19
| 8
| 0
|
module Pong ( Paddle (..)
, Ball (..)
, Scene (..)
, renderScene
) where
--------------------
-- Global Imports --
import Graphics.Rendering.OpenGL
import Linear.V2
-------------------
-- Local Imports --
import Renderable
import Collision
import Config
import Utils
----------
-- Code --
{-|
The paddle datatypes. Stores the position and the size. The score is stored
within the @'Scene'@ datatype.
-}
data Paddle = Paddle (V2 Float) (V2 Float)
deriving (Eq, Show, Read)
instance Collidable Paddle where
collisionRectangle (Paddle pos size) = CollisionRectangle pos size
{-|
The ball datatype, stores the position and the radius.
-}
data Ball = Ball (V2 Float) Float
deriving (Eq, Show, Read)
instance Collidable Ball where
collisionRectangle (Ball (V2 x y) r) =
CollisionRectangle (V2 (x - r) (y - r))
(V2 (r * 2) (r * 2))
{-|
The scene datatype contains all of the information for a given frame of the
game. It has the @'Paddle'@s, the scores, and the @'Ball'@.
-}
data Scene = Scene { getLeftPaddle :: Paddle
, getLeftScore :: Int
, getRightPaddle :: Paddle
, getRightScore :: Int
, getBall :: Ball
}
deriving (Eq, Show, Read)
{-|
Rendering a given @'Paddle'@.
-}
renderPaddle :: Paddle -> IO ()
renderPaddle (Paddle pos size) =
renderPrimitive Quads $
mapM_ linearVertex $ generateVertecies pos size
{-|
Rendering a given @'Ball'@.
-}
renderBall :: Ball -> IO ()
renderBall (Ball pos r) =
renderPrimitive TriangleFan $
mapM_ linearVertex $ pos : gvs 0
where gvs :: Float -> [V2 Float]
gvs radians
| radians > 360 = []
| otherwise = generateVertex : gvs (radians + (2 * pi / renderDetail))
where generateVertex :: V2 Float
generateVertex = pos + (V2 r r) * V2 (sin radians) (cos radians)
{-|
Rendering a line down the middle of the screen.
-}
renderCenter :: V2 Float -> IO ()
renderCenter (V2 _ h) = do
renderPrimitive Lines $ do
vertex $ Vertex2 (0 :: GLfloat) (realToFrac ( h) :: GLfloat)
vertex $ Vertex2 (0 :: GLfloat) (realToFrac (-h) :: GLfloat)
{-|
Rendering a given score on a given side.
-}
renderScore :: Float -> Either () () -> V2 Float -> IO ()
renderScore score side (V2 w h) =
renderPrimitive Quads $
mapM_ linearVertex $
case side of
Left () ->
generateVertecies (V2 (-w + horizontalScoreMargin) (h - verticalScoreMargin))
(V2 score scoreHeight)
Right () ->
generateVertecies (V2 ( w - horizontalScoreMargin - score) (h - verticalScoreMargin))
(V2 score scoreHeight)
{-|
Rendering a given scene. This includes rendering both @'Paddle'@, the
@'Ball'@, and both of the scores.
-}
renderScene :: Scene -> IO ()
renderScene scene = do
r <- renderSize'
color $ Color3 (0.5 :: GLfloat) (0.5 :: GLfloat) (0.5 :: GLfloat)
renderCenter r
color $ Color3 (1 :: GLfloat) (1 :: GLfloat) (1 :: GLfloat)
renderPaddle $ getLeftPaddle scene
renderPaddle $ getRightPaddle scene
renderBall $ getBall scene
color $ Color3 (1 :: GLfloat) (1 :: GLfloat) (0.3 :: GLfloat)
renderScore (fromIntegral $ getLeftScore scene) (Left ()) r
renderScore (fromIntegral $ getRightScore scene) (Right ()) r
{-|
The @'Renderable''@ instance for @'Scene'@.
-}
instance Renderable' Scene where
render = renderScene
|
crockeo/netwire-pong
|
src/Pong.hs
|
mit
| 3,540
| 0
| 15
| 959
| 1,026
| 534
| 492
| 70
| 2
|
module Network.VoiceText.Types (
basicAuth,
ttsParams,
speakerName,
formatName,
emotionName,
addFormat,
addEmotion,
addEmotionLevel,
addPitch,
addSpeed,
addVolume,
BasicAuth(..),
TtsParams(..),
Speaker(..),
Format(..),
Emotion(..),
Error(..)) where
data BasicAuth = BasicAuth { username::String, password::String } deriving (Eq, Show)
basicAuth :: String -> String -> BasicAuth
basicAuth username password = BasicAuth { username=username, password=password }
data TtsParams = TtsParams {
text::String
, speaker::Speaker
, format::Maybe Format
, emotion::Maybe Emotion
, emotionLevel::Maybe Int
, pitch::Maybe Int
, speed::Maybe Int
, volume::Maybe Int } deriving (Eq, Show)
data Speaker = Show | Haruka | Hikari | Takeru | Santa | Bear deriving (Eq, Read, Show)
speakerName :: Speaker -> String
speakerName Show = "show"
speakerName Haruka = "haruka"
speakerName Hikari = "hikari"
speakerName Takeru = "takeru"
speakerName Santa = "santa"
speakerName Bear = "bear"
data Format = Wav | Ogg | Mp3 deriving (Eq, Read, Show)
formatName :: Format -> String
formatName Wav = "wav"
formatName Ogg = "ogg"
formatName Mp3 = "mp3"
data Emotion = Happiness | Anger | Sadness deriving (Eq, Read, Show)
emotionName :: Emotion -> String
emotionName Happiness = "happiness"
emotionName Anger = "anger"
emotionName Sadness = "sadness"
data Error = Error { code::Int, message::String, body::String } deriving (Eq, Show)
ttsParams :: String -> Speaker -> TtsParams
ttsParams text speaker = TtsParams {
text=text,
speaker=speaker,
format=Nothing,
emotion=Nothing,
emotionLevel=Nothing,
pitch=Nothing,
speed=Nothing,
volume=Nothing }
addFormat :: Format -> TtsParams -> TtsParams
addFormat format ttsParams = ttsParams { format=Just format }
addEmotion :: Emotion -> TtsParams -> TtsParams
addEmotion emotion ttsParams = ttsParams { emotion=Just emotion }
addEmotionLevel :: Int -> TtsParams -> TtsParams
addEmotionLevel emotionLevel ttsParams = ttsParams { emotionLevel=Just emotionLevel }
addPitch :: Int -> TtsParams -> TtsParams
addPitch pitch ttsParams = ttsParams { pitch=Just pitch }
addSpeed :: Int -> TtsParams -> TtsParams
addSpeed speed ttsParams = ttsParams { speed=Just speed }
addVolume :: Int -> TtsParams -> TtsParams
addVolume volume ttsParams = ttsParams { volume=Just volume }
|
zaneli/network-voicetext
|
src/Network/VoiceText/Types.hs
|
mit
| 2,363
| 0
| 9
| 400
| 770
| 440
| 330
| 71
| 1
|
{-|
Module : Pager.PaperFormat
Description : Defines functions and dataformats needed to handle different sizes\/formats of paper
Copyright : (c) Norbert Melzer, 2014
License : MIT
Maintainer : timmelzer@gmail.com
Stability : experimental
Portability : portable
Longer description follows later!
-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Pager.PaperFormat ( Points (Points)
, MilliMeters(MilliMeters)
, MilliInches(MilliInches)
, PaperSize (..)
, PaperFormat(..)
, Orientation(..)
, pt2mm
, pt2minch
, mm2pt
, mm2minch
, minch2pt
, minch2mm
, toPDFRect) where
import Data.Tuple
import qualified Graphics.PDF as PDF
class Unbox a b where
ub :: a -> b
-- | represents a length\/size\/value in pt (1/72 of an inch)
newtype Points = Points Int deriving (Show)
instance Unbox Points Int where
ub (Points x) = x
-- | represents a length\/size\/value in thousands of a meter (see <http://en.wikipedia.org/wiki/International_System_of_Units>)
newtype MilliMeters = MilliMeters Int deriving (Show)
instance Unbox MilliMeters Int where
ub (MilliMeters x) = x
-- | represents a length\/size\/value in thousands of an inch
newtype MilliInches = MilliInches Int deriving (Show)
instance Unbox MilliInches Int where
ub (MilliInches x) = x
-- | Converts 'Points' into 'MilliMeters'
--
-- Example:
--
-- >>> pt2mm $ Points 72
-- MilliMeters 25
pt2mm :: Points -- ^ a value in 'Points'
-> MilliMeters -- ^ the value in 'MilliMeters'
pt2mm (Points pt) = MilliMeters (round (0.352777778 * fromIntegral pt))
-- | Converts 'Points' into 'MilliInches'
--
-- Example:
--
-- >>> pt2minch $ Points 72
-- MilliInches 1000
pt2minch :: Points -- ^ a value in 'Points'
-> MilliInches -- ^ the value in 'MilliInches'
pt2minch (Points pt) = MilliInches (round ((fromIntegral pt / 72) * 1000))
-- | Converts 'MilliMeters' to 'Points'
--
-- Example:
--
-- >>> mm2pt $ MilliMeters 1000
-- Points 2835
mm2pt :: MilliMeters -- ^ a value in 'MilliMeters'
-> Points -- ^ the value in 'Points'
mm2pt (MilliMeters mm) = Points (round (2.834645669 * fromIntegral mm))
-- | Converts 'MilliMeters' to 'MilliInches'
--
-- Example:
--
-- >>> mm2minch $ MilliMeters 1000
-- MilliInches 39370
mm2minch :: MilliMeters -- ^ a value in 'MilliMeters'
-> MilliInches -- ^ the value in 'MilliInches'
mm2minch (MilliMeters mm) = MilliInches (round (39.370079 * fromIntegral mm))
-- | Converts 'MilliInches' to 'Points'
--
-- Example:
--
-- >>> minch2pt $ MilliInches 1000
-- Points 72
minch2pt :: MilliInches -- ^ a value in 'MilliInches'
-> Points -- ^ the value in 'Points'
minch2pt (MilliInches minch) = Points (round ((fromIntegral minch * 72) / 1000))
-- | Converts 'MilliInches' to 'MilliMeters'
--
-- Example:
--
-- >>> minch2mm $ MilliInches 1000
-- MilliMeters 25
minch2mm :: MilliInches -- ^ a value in 'MilliInches'
-> MilliMeters -- ^ the value in 'MilliMeters'
minch2mm (MilliInches minch) = MilliMeters (round (fromIntegral minch * 0.0254))
-- | Defines the size of the paper
data PaperSize = PaperSize !Orientation !PaperFormat -- ^ Defines the size of the paper in respect of ISO
| PaperRectPt !Points !Points -- ^ Defines the size of the paper given by length and height in 'Points'
| PaperRectMM !MilliMeters !MilliMeters -- ^ Defines the size of the paper given by length and height in 'MilliMeters'
| PaperRectMI !MilliInches !MilliInches -- ^ Defines the size of the paper given by length and height in 'MilliInches'
-- | Possible predefined paperformats, please see <http://www.prepressure.com/library/paper-size>
data PaperFormat = A0 | A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8
| B0 | B1 | B2 | B3 | B4 | B5 | B6 | B7 | B8 | B9 | B10
| C2 | C3 | C4 | C5 | C6
| Letter | Legal
deriving (Eq, Show)
-- | Describes the orientation of the paper
data Orientation = Landscape -- ^ the paper is oriented in a way that the width is greater than the height
| Portrait -- ^ the paper is oriented in a way that the height is greater than the width
-- | Returns a 'PDFRect' representing the corresponding 'PaperSize'
toPDFRect :: PaperSize -> PDF.PDFRect
toPDFRect (PaperSize o pf) = case o of
Landscape -> uncurry (PDF.PDFRect 0 0) (swap $ dimension)
Portrait -> uncurry (PDF.PDFRect 0 0) ( dimension)
where
dimension = maybe (0, 0) id $ lookup pf dimensionList
toPDFRect (PaperRectPt w h ) = PDF.PDFRect 0 0 (ub w) (ub h)
toPDFRect (PaperRectMM w h ) = PDF.PDFRect 0 0 (ub . mm2pt $ w) (ub . mm2pt $ h)
toPDFRect (PaperRectMI w h ) = PDF.PDFRect 0 0 (ub . minch2pt $ w) (ub . minch2pt $ h)
dimensionList :: [(PaperFormat, (Int, Int))]
dimensionList = [ (A0, (2384, 3370))
, (A1, (1684, 2384))
, (A2, (1190, 1684))
, (A3, ( 842, 1190))
, (A4, ( 595, 842))
, (A5, ( 420, 595))
, (A6, ( 298, 420))
, (A7, ( 210, 298))
, (A8, ( 148, 210))
, (B0, (2835, 4008))
, (B1, (2004, 2835))
, (B2, (1417, 2004))
, (B3, (1001, 1417))
, (B4, ( 709, 1001))
, (B5, ( 499, 709))
, (B6, ( 354, 499))
, (B7, ( 249, 354))
, (B8, ( 176, 249))
, (B9, ( 125, 176))
, (B10, ( 88, 125))
, (C2, (1837, 578))
, (C3, ( 578, 919))
, (C4, ( 919, 649))
, (C5, ( 649, 459))
, (C6, ( 459, 323))
, (Letter, ( 612, 792))
, (Legal, ( 612, 1008))
]
|
NobbZ/pager
|
src/Pager/PaperFormat.hs
|
mit
| 6,254
| 0
| 12
| 2,072
| 1,373
| 825
| 548
| 115
| 2
|
{-# LANGUAGE CPP #-}
module GHCJS.DOM.Database (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Database
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Database
#else
#endif
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/Database.hs
|
mit
| 317
| 0
| 5
| 33
| 31
| 24
| 7
| 4
| 0
|
module HelperFunctions
( choice_
, isVowel
, isConsonant
, format
, shuffleLists
, replicateUntilM
, safeSample
, safeSample2
, safeChoice2
, safeChoices2
, choices2
, randomSubset
, safeSampleSet
, triangle
, triangleChoice
, zipf
, zipfChoice
) where
import ClassyPrelude
import Data.RVar
import Data.Random hiding (sample, gamma)
import Data.Random.Extras
import Data.Random.Distribution.Triangular
import Data.Random.Distribution.Categorical
import Data.Text (replace)
import Data.Random.Lift as R (lift)
import Data.Phoneme
isVowel :: Phoneme -> Bool
isVowel Vowel{} = True
isVowel _ = False
isConsonant :: Phoneme -> Bool
isConsonant Consonant{} = True
isConsonant _ = False
-- HashMap stuff
-- Avoids (hash hash value, value) (hash value, value) duplicates
-- Doesn't avoid (key1, value) (key2, value) duplicates
insertMap_ :: Hashable a => HashMap Int a -> a -> (HashMap Int a, Int)
insertMap_ hm value = (insertMap key value hm, key) where
key = foobar hm (hash value) value
foobar :: HashMap Int a -> Int -> a -> Int
foobar hm k v
| (\case Just v -> True; _ -> False) v_ = k -- this mean the value is already in the hashtable under that key
| isNothing v_ = k
| otherwise = foobar hm (hash k) v where
v_ = lookup k hm
-- Used for text formatting
format :: Text -> [Text] -> Text
format a b = doFormat a (0::Int,b)
where
doFormat a (_,[]) = a
doFormat a (n,b:bs) = replace (old n) b a `doFormat` (n+1,bs)
old n = "{" ++ tshow n ++ "}"
-- Shuffles two lists together
shuffleLists :: [a] -> [a] -> [a]
shuffleLists [] ys = ys
shuffleLists (x:xs) ys = x : shuffleLists ys xs
-- RVar stuff
-- Weighs the first argument by N
choice_ :: Int -> a -> a -> RVar a
choice_ wei fir sec = choice (sec : replicate wei fir)
-- First argument contains the weights of the second argument
-- The two have to be equal in size
choiceWeight :: [Int] -> [a] -> Maybe (RVar a)
choiceWeight [] _ = Nothing
choiceWeight _ [] = Nothing
choiceWeight ws xs
| length ws /= length xs = Nothing
| otherwise = Just $ choice $ concat $ zipWith replicate ws xs
-- sample but without worrying about empty list exception
safeSample :: Int -> [a] -> Maybe (RVar [a])
safeSample n xs
| length xs >= n = Just $ sample n xs
| otherwise = Nothing
-- safeSample but RVar on outside
safeSample2 :: Int -> [a] -> RVar (Maybe [a])
safeSample2 n xs
| length xs >= n = Just <$> sample n xs
| otherwise = return Nothing
-- safeChoice but RVar on outside
safeChoice2 :: [a] -> RVar (Maybe a)
safeChoice2 [] = return Nothing
safeChoice2 xs = Just <$> choice xs
-- safeChoice but RVar on outside
safeChoices2 :: Int -> [a] -> RVar (Maybe [a])
safeChoices2 _ [] = return Nothing
safeChoices2 n xs = Just <$> choices n xs
-- choices but returns [] on empty list
choices2 :: Int -> [a] -> RVar [a]
choices2 _ [] = return []
choices2 n xs = choices n xs
randomSubset :: [a] -> RVar [a]
randomSubset [] = return []
randomSubset xs = join $ flip sample xs <$> uniform 0 (length xs)
safeSampleSet :: Ord a => Int -> Set a -> Maybe (RVar (Set a))
safeSampleSet n xs = do
foo <- safeSample n (setToList xs)
return $ setFromList <$> foo
choiceExtract2 :: [a] -> RVar (Maybe ([a], a))
choiceExtract2 [] = return Nothing
choiceExtract2 xs = extract xs <$> uniform 0 (length xs - 1)
extract :: [a] -> Int -> Maybe ([a], a)
extract s i | null r = Nothing
| otherwise = Just (a ++ c, b)
where (a, r) = splitAt i s
(b : c) = r
triangle :: Int -> Int -> RVar Int
triangle n x
| n == x = return n
| otherwise = do
y <- rvar (Triangular (fromIntegral n :: Double) (fromIntegral n :: Double) (fromIntegral x :: Double))
return $ round y
-- Should use this for phoneme selection
triangleChoice :: [a] -> RVar a
triangleChoice xs = do
n <- triangle 0 (length xs)
return $ unsafeIndex xs n
-- Zipf Distribution stuff
{-zipfPMF :: Float -> Int -> Int -> Float
zipfPMF s n k = (1 / (fromIntegral k ** s)) / harm n s
harm :: Int -> Float -> Float
harm n m = sum $ map (\k -> 1 / (fromIntegral k ** m)) [1..n]-}
zipfPMF :: Float -> Int -> Int -> Float
zipfPMF 1 n r = zipfPMF 1.001 n r -- 1.0 isn't defined
zipfPMF a n r = (r_ ** (-a)) / (((n_ ** (-a)) * (0.5 + (n_/(1 - a)))) + ((2 ** (-a)) * (0.5 - (2/(1 - a)))) + 1) where
n_ = fromIntegral n
r_ = fromIntegral r
zipf :: Float -> Int -> RVar Int
zipf s n = categorical $ map (\k -> (zipfPMF s n k, k)) [1..n]
zipfChoice :: Float -> [a] -> RVar (Maybe a)
zipfChoice s xs
| s <= 0 = return Nothing
| otherwise = do
n <- zipf s (length xs)
return $ index xs (n-1)
-- Doesn't work?
-- This is like replicateM, except it replicates until it either hits the amount
-- you want or it reaches a specified limit (so it doesn't go forever).
-- This is actually pretty useful, I'm suprised it doesn't exist already.
replicateUntilM :: Monad m => (a -> Bool) -> Int -> Int -> m a -> m [a]
replicateUntilM _ 0 _ _ = return []
replicateUntilM _ _ 0 _ = return []
replicateUntilM test i limit thing = do
revealThing <- thing
itFails <- replicateUntilM test i (limit-1) thing
itSucceeds <- replicateUntilM test (i-1) (limit-1) thing
if test revealThing then return (revealThing:itSucceeds) else return itFails
|
Brightgalrs/con-lang-gen
|
src/HelperFunctions.hs
|
mit
| 5,245
| 0
| 16
| 1,150
| 2,029
| 1,044
| 985
| -1
| -1
|
{-# LANGUAGE NoImplicitPrelude, PackageImports #-}
module Test where
import "base-compat-batteries" Data.Monoid.Compat
|
haskell-compat/base-compat
|
check/check-hs/Data.Monoid.Compat.check.hs
|
mit
| 119
| 0
| 4
| 11
| 12
| 9
| 3
| 3
| 0
|
{-# LANGUAGE PatternGuards #-}
module Language.Ruby.Hubris.ZCode (zenc,zdec,Zname(..)) where
import Data.Char
import Data.Ix
import qualified Data.Map as M
import Numeric
zemap :: M.Map Char String
zemap = M.fromList $
[ ('(', "ZL")
, (')', "ZR")
, ('[', "ZM")
, (']', "ZN")
, (':', "ZC")
, ('Z', "ZZ")
, ('z', "zz")
, ('&', "za")
, ('|', "zb")
, ('^', "zc")
, ('$', "zd")
, ('=', "ze")
, ('>', "zg")
, ('#', "zh")
, ('.', "zi")
, ('<', "zl")
, ('-', "zm")
, ('!', "zn")
, ('+', "zp")
, ('\'', "zq")
, ('\\', "zr")
, ('/', "zs")
, ('*', "zt")
, ('_', "zu")
, ('%', "zv")
]
zdmap :: M.Map String Char
zdmap = M.fromList . map (\(a, b) -> (b, a)) . M.toList $ zemap
newtype Zname = Zname String
zenc :: String -> Zname
zenc s = Zname $ concatMap (\c -> M.findWithDefault (z c) c zemap) s
where
z c
| any (($ c) . inRange) [('a', 'y'), ('A', 'Z'), ('0', '9')] =
[c]
| otherwise =
let
s = showHex (ord c) "U"
p = if inRange ('0', '9') (head s) then id else ('0' :)
in
'z' : p s
zdec :: String -> String
zdec "" = ""
zdec [c] = [c]
zdec (c : cs@(c' : cs'))
| c `elem` "zZ"
, Just x <- M.lookup [c, c'] zdmap
= x : zdec cs'
| c == 'z'
, (h@(_ : _), 'U' : t) <- span isHexDigit cs
, [(n, "")] <- readHex h
= chr n : zdec t
| otherwise = c : zdec cs
|
mwotton/Hubris-Haskell
|
Language/Ruby/Hubris/ZCode.hs
|
mit
| 1,489
| 0
| 15
| 509
| 731
| 425
| 306
| 58
| 2
|
compare100 :: (Num a, Ord a) => a -> Ordering
-- Which is the same thing as:
-- compare100 x = compare 100 x
compare100 = compare 100
divide10 :: (Floating a) => a -> a
divide10 = (/10)
isUpperAlphanum :: Char -> Bool
isUpperAlphanum = (`elem` ['A'..'Z'])
add1 :: Int -> Int
add1 = (+1)
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)
r1 = applyTwice (++ "B") "A"
r2 = applyTwice ("A" ++) "B"
r3 = applyTwice (3:) [1]
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' _ [] _ = []
zipWith' _ _ [] = []
zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys
r4 = zipWith' (+) [1,2,3] [4,5,6]
f :: a -> b -> (a, b)
f a b = (a, b)
r5 = zipWith' (+) [1,2,3] [4,5,6]
r6 = zipWith' f [1,2,3] [4,5,6]
r7 = zipWith' (++) ["joy ", "sonic ", "massic "] ["division", "youth", "attack"]
-- Which is the same thing as:
-- flip' :: (a -> b -> c) -> b -> a -> c
flip' :: (a -> b -> c) -> (b -> a -> c)
flip' f y x = f x y
r8 = flip' zip [1, 2, 3, 4, 5] "hello"
r9 = zipWith (flip' div) [2, 2..] [10, 8, 6, 4, 2]
map' :: (a -> b) -> [a] -> [b]
map' _ [] = []
map' f (x:xs) = f x : map' f xs
r10 = map (+3) [1, 2, 3, 4]
r11 = map (++ "!") ["BANG", "POW", "BIFF"]
r12 = map (replicate 3) [3..6]
r13 = map (map (^2)) [[1,2], [3,4,5,6], [7,8]]
r14 = map fst [(1,2), (3,4), (5,6), (7,8), (9,0)]
filter' :: (a -> Bool) -> [a] -> [a]
filter' _ [] = []
filter' p (x:xs)
| p x = x : filter' p xs
| otherwise = filter' p xs
r15 = filter (>3) [1,5,3,2,9,7,8]
r16 = filter (==3) [1,5,3,2,9,7,8]
r17 = filter even [1..10]
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smaller = quicksort (filter (<= x) xs)
bigger = quicksort (filter (> x) xs)
in smaller ++ [x] ++ bigger
largestDivisible :: (Integral a) => a
largestDivisible = head (filter p [100000, 99999 ..])
where p x = x `mod` 3829 == 0
chain :: (Integral a) => a -> [a]
chain 1 = [1]
chain n
| even n = n:chain (n `div` 2)
| odd n = n:chain (n * 3 + 1)
listOfFuns = map (*) [0..]
res18 = (listOfFuns !! 4) 5
-- A lambda example. I now this is the same as (+2)
add2 = \x -> x + 2
sum' :: (Num a) => [a] -> a
-- Which is the same as:
-- sum' = foldl (+) 0
sum' xs = foldl (\acc x -> acc + x) 0 xs
-- dont forget: foldl foldr foldl1 foldr1
-- also: scanl scanr scanl1 scanr1
-- Which is the same as sum (map sqrt [1..30])
res19 = sum $ map sqrt [1..30]
res20 = map ($ 3) [(4+), (10*), (^2), sqrt]
-- 3*(1+ x)
res21 = (1+) . (3*)
res22 = map (negate . abs) [5, -3, -6, 7, -3, 2, -19, 24]
res23 = map (negate . sum . tail) [[1..5], [3..6], [1..7]]
res24 = sum (replicate 5 (max 6.7 8.9))
res25 = sum . replicate 5 . max 6.7 $ 8.9
-- The following three functions are equivalent
oddSquareSum1 :: Integer
oddSquareSum1 = sum (takeWhile (< 10000) (filter odd (map (^2) [1..])))
oddSquareSum2 :: Integer
oddSquareSum2 = sum . takeWhile (< 10000) . filter odd $ map (^2) [1..]
oddSquareSum3 :: Integer
oddSquareSum3 =
let oddSquares = filter odd $ map (^2) [1..]
belowLimit = takeWhile (<10000) oddSquares
in sum belowLimit
|
fabriceleal/learn-you-a-haskell
|
06/highorder.hs
|
mit
| 3,072
| 5
| 12
| 737
| 1,730
| 977
| 753
| 78
| 1
|
module Reducer where
import Data
import List
reduce :: StartPoint -> [Module] -> Module
reduce (StartPoint initNT baseModuleName) modules =
reduceModule basemodule modules
where
basemodule = case (findModule baseModuleName modules) of
Nothing -> error msg
Just m -> m
msg = "Module '" ++ baseModuleName ++ "' not found."
reduceModule :: Module -> [Module] -> Module
reduceModule m ms | undefNT == [] = reducedModule
| otherwise = error (msg m)
where
reducedModule =
applyOverrides
$ flip applyImports ms
$ rmAbstracts m
undefNT = undefinedNT m
msg (Module mname _) =
"There are undefined nonterminals in module '"
++ mname
++ "': "
++ show (undefNTNames undefNT)
++ "\nYou have to declare them as 'abstract' or define add grammar rules."
undefNTNames [] = []
undefNTNames ((Nonterminal name):es) = union [name] (undefNTNames es)
rmAbstracts :: Module -> Module
rmAbstracts (Module m c) = Module m newc
where
newc = rmAbstract_ c
rmAbstract_ [] = []
rmAbstract_ ((Abstract _):ss) = rmAbstract_ ss
rmAbstract_ (s:ss) = s : rmAbstract_ ss
applyImports :: Module -> [Module] -> Module
applyImports (Module m c) ms =
if length (nubBy ntNames cnew) == length cnew
then Module m cnew
else error ("There are some clashing NTs while executing imports in '" ++ m ++ "' module.")
where
ntNames (Rule l1 _) (Rule l2 _) = l1 == l2
ntNames _ _ = False
cnew = applyImports_ c
applyImports_ [] = []
applyImports_ ((Import targetname ioptions):ss) =
importedContent ++ applyImports_ ss
where importedContent = importModule targetname ioptions ms
applyImports_ (s:ss) = s : applyImports_ ss
importModule :: ModuleName -> [ImportOption] -> [Module] -> [Statement]
importModule mn ios ms = applyImportOptions ios c
where
(Module _ c) = reduceModule m ms
m = case (findModule mn ms) of
Nothing -> error msg
Just m -> m
msg = "Importing module '" ++ mn ++ "' failed. Not found."
applyImportOptions :: [ImportOption] -> [Statement] -> [Statement]
applyImportOptions [] sts = sts
applyImportOptions ((Rename (Nonterminal e1) (Nonterminal e2)):ios) sts =
if isThereNT (Nonterminal e1) sts
then if not (isThereNT (Nonterminal e2) sts)
then applyImportOptions ios (renameNT (Nonterminal e1) (Nonterminal e2) sts)
else error ("Cannot rename '" ++ e1 ++ "' as '" ++ e2 ++ "'. Already exists.")
else error ("Cannot rename nonterminal " ++ e1 ++ ". Not found.")
applyImportOptions ((Drop (Nonterminal e)):ios) sts =
if isThereNT (Nonterminal e) sts
then applyImportOptions ios (dropNT (Nonterminal e) sts)
else error ("Cannot rename nonterminal " ++ e ++ ". Not found.")
applyOverrides :: Module -> Module
applyOverrides (Module m c) = Module m newc
where
newc = applyOverrides_ overrides rules
overrides = [Override r | Override r <- c]
rules = [Rule l r | Rule l r <- c]
applyOverrides_ [] rs = rs
applyOverrides_ ((Override (Rule (Nonterminal l) r)):os) rs =
if isThereNT (Nonterminal l) rs
then applyOverrides_ os (override (Rule (Nonterminal l) r) rs)
else error ("Cannot override nonterminal " ++ l ++ ". Not found")
override :: Statement -> [Statement] -> [Statement]
override _ [] = []
override (Rule l1 r1) ((Rule l2 r2):ss) | l1 == l2 = lr1 : override lr1 ss
| l1 /= l2 = lr2 : override lr1 ss
where
lr1 = Rule l1 r1
lr2 = Rule l2 r2
override r (s:ss) = s : override r ss
undefinedNT :: Module -> [Element]
undefinedNT (Module m c) =
[nt | nt <- allUndefinedNT, notElem nt abstractedNT]
where
allUndefinedNT = undefinedNT_ c [] []
abstractedNT = findAbstractedNTs c
undefinedNT_ [] def undef = undef
undefinedNT_ ((Rule l r):ss) def undef = undefinedNT_ ss newDef newUndef
where
newDef = def ++ [l]
newUndef = filter (/= l) undef
++ [e | e <- grepNT $ concat r, notElem e newDef]
where
grepNT [] = []
grepNT ((Nonterminal nt):es) = Nonterminal nt : grepNT es
grepNT ((Terminal _):es) = grepNT es
undefinedNT_ (s:ss) def undef = undefinedNT_ ss def undef
findAbstractedNTs :: [Statement] -> [Element]
findAbstractedNTs [] = []
findAbstractedNTs ((Abstract e):ss) = e : findAbstractedNTs ss
findAbstractedNTs (s:ss) = findAbstractedNTs ss
findModule :: ModuleName -> [Module] -> Maybe Module
findModule mname = find (\(Module m c) -> m == mname)
isThereNT :: Element -> [Statement] -> Bool
isThereNT e [] = False
isThereNT e ((Rule l _):sts) | l == e = True
| otherwise = isThereNT e sts
isThereNT e (s:sts) = isThereNT e sts
dropNT :: Element -> [Statement] -> [Statement]
dropNT e [] = []
dropNT e ((Rule el els):sts) | el == e = dropNT e sts
| otherwise = Rule el els : dropNT e sts
dropNT e (st:sts) = st : dropNT e sts
renameNT :: Element -> Element -> [Statement] -> [Statement]
renameNT eFrom eTo [] = []
renameNT eFrom eTo ((Rule l rs):sts) = Rule newL newRs
: renameNT eFrom eTo sts
where
newL = if l == eFrom
then eTo
else l
newRs = map newR rs
newR x = [if e == eFrom then eTo else e | e <- x]
renameNT eFrom eTo (st:sts) = st : renameNT eFrom eTo sts
-- EOF
|
mkopta/fika-ha
|
src/Reducer.hs
|
mit
| 5,481
| 0
| 15
| 1,474
| 2,097
| 1,062
| 1,035
| 121
| 5
|
module Probability.Distribution.Normal where
import Probability.Random
import MCMC
builtin normal_density 3 "normal_density" "Distribution"
builtin normal_quantile 3 "normal_quantile" "Distribution"
builtin builtin_sample_normal 3 "sample_normal" "Distribution"
normal_bounds = realLine
normal_effect x = add_move $ slice_sample_real_random_variable x normal_bounds
sample_normal m s = RandomStructure normal_effect modifiable_structure $ liftIO (IOAction (\state -> (state, builtin_sample_normal m s state)))
annotated_normal_density mu sigma x = do
in_edge "mu" mu
in_edge "sigma" sigma
return [normal_density mu sigma x]
normal m s = Distribution "normal" (annotated_normal_density m s) (normal_quantile m s) (sample_normal m s) normal_bounds
|
bredelings/BAli-Phy
|
haskell/Probability/Distribution/Normal.hs
|
gpl-2.0
| 758
| 0
| 12
| 95
| 211
| 102
| 109
| -1
| -1
|
{- |
Module : $Header$
Description : lists with their size similar to Data.Edison.Seq.SizedSeq
Copyright : C. Maeder DFKI Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : experimental
Portability : portable
a list plus its length for a more efficient history implementation.
Parts of the implementation is stolen from Data.Edison.Seq.SizedSeq
-}
module Common.Lib.SizedList
( SizedList
, fromList
, toList
, empty
, singleton
, cons
, append
, head
, tail
, null
, size
, reverse
, take
, drop
, map
) where
import Prelude hiding (null, head, tail, reverse, take, drop, map)
import qualified Data.List as List
data SizedList a = N !Int [a] deriving (Show, Eq, Ord)
fromList :: [a] -> SizedList a
fromList xs = N (length xs) xs
toList :: SizedList a -> [a]
toList (N _ xs) = xs
empty :: SizedList a
empty = N 0 []
singleton :: a -> SizedList a
singleton x = N 1 [x]
cons :: a -> SizedList a -> SizedList a
cons x (N n xs) = N (succ n) $ x : xs
append :: SizedList a -> SizedList a -> SizedList a
append (N m xs) (N n ys) = N (m + n) $ xs ++ ys
head :: SizedList a -> a
head (N n xs) = case xs of
x : _ | n > 0 -> x
_ -> error "SizedList.head: empty list"
tail :: SizedList a -> SizedList a
tail (N n xs) = case xs of
_ : r | n > 0 -> N (pred n) r
_ -> error "SizedList.tail: empty list"
null :: SizedList a -> Bool
null (N n _) = n == 0
size :: SizedList a -> Int
size (N n _) = n
reverse :: SizedList a -> SizedList a
reverse (N n xs) = N n (List.reverse xs)
take :: Int -> SizedList a -> SizedList a
take i original@(N n xs)
| i <= 0 = empty
| i >= n = original
| otherwise = N i $ List.take i xs
drop :: Int -> SizedList a -> SizedList a
drop i original@(N n xs)
| i <= 0 = original
| i >= n = empty
| otherwise = N (n - i) $ List.drop i xs
map :: (a -> b) -> SizedList a -> SizedList b
map f (N n xs) = N n (List.map f xs)
|
nevrenato/HetsAlloy
|
Common/Lib/SizedList.hs
|
gpl-2.0
| 1,975
| 0
| 11
| 502
| 832
| 421
| 411
| 59
| 2
|
module P30MultTblSpec (main,spec) where
import Test.Hspec
import Test.Hspec.QuickCheck
import P30MultTbl hiding (main)
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "multTbl" $ do
it "returns [(0,0,0)] if called with (-1)" $ do
multTbl (-1) `shouldBe` [(0,0,0)]
it "returns [(0,0,0)] if called with 0" $ do
multTbl 0 `shouldBe` [(0,0,0)]
it "returns [(0,0,0),(0,1,0),(1,0,0),(1,1,1)] if called with 1" $ do
multTbl 1 `shouldBe` [(0,0,0),(0,1,0),(1,0,0),(1,1,1)]
describe "table" $ do
it "gives a formatted 12 times table when given a multTbl 12" $ do
(table $ multTbl 12) `shouldBe` " 0 1 2 3 4 5 6 7 8 9 10 11 12 \n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n 1 0 1 2 3 4 5 6 7 8 9 10 11 12 \n 2 0 2 4 6 8 10 12 14 16 18 20 22 24 \n 3 0 3 6 9 12 15 18 21 24 27 30 33 36 \n 4 0 4 8 12 16 20 24 28 32 36 40 44 48 \n 5 0 5 10 15 20 25 30 35 40 45 50 55 60 \n 6 0 6 12 18 24 30 36 42 48 54 60 66 72 \n 7 0 7 14 21 28 35 42 49 56 63 70 77 84 \n 8 0 8 16 24 32 40 48 56 64 72 80 88 96 \n 9 0 9 18 27 36 45 54 63 72 81 90 99 108 \n 10 0 10 20 30 40 50 60 70 80 90 100 110 120 \n 11 0 11 22 33 44 55 66 77 88 99 110 121 132 \n 12 0 12 24 36 48 60 72 84 96 108 120 132 144 "
|
ciderpunx/57-exercises-for-programmers
|
test/P30MultTblSpec.hs
|
gpl-3.0
| 1,462
| 0
| 16
| 592
| 252
| 139
| 113
| 18
| 1
|
module Problem002 (answer) where
import NumUtil (fibs)
answer :: Int
answer = sum $ filter even $ takeWhile (<4000000) fibs
|
geekingfrog/project-euler
|
Problem002.hs
|
gpl-3.0
| 126
| 0
| 7
| 22
| 47
| 27
| 20
| 4
| 1
|
{-# Language OverloadedStrings, FlexibleInstances, TypeFamilies, NoMonomorphismRestriction, ScopedTypeVariables, FlexibleContexts #-}
module Test.Parse where
import Test.Tasty
import Test.Helper
import Person
import Person.Parse
tests :: TestTree
tests = testGroup "parsing" [
(Nothing :: Maybe Date) .==: "abc",
Just (Date 1943 2 13) .==: "2/13/1943",
Just (Date 1943 2 13) .==: "2-13-1943",
Just Male .==: "Male",
Just Female .==: "Female",
Just Male .==: "M",
Just Female .==: "F",
(Nothing :: Maybe Gender) .==: "abc",
Just neil .==: "Abercrombie, Neil, Male, Tan, 2/13/1943",
(Nothing :: Maybe Person) .==: "Abercrombie, Neil, abc, Tan, 2/13/1943",
(Nothing :: Maybe Person) .==: "Abercrombie, Neil, Male, Tan, abc",
Just steve .==: "Smith | Steve | D | M | Red | 3-3-1985",
Just anna .==: "Hingis Martina M F 4-2-1979 Green",
(Nothing :: Maybe Person) .==: "abc",
Just [steve, neil] .==: "Smith | Steve | D | M | Red | 3-3-1985\nAbercrombie | Neil | S | M | Tan | 2-13-1943"
]
where neil = Person "Neil" "Abercrombie" Male (Date 1943 2 13) "Tan"
anna = Person "Martina" "Hingis" Female (Date 1979 4 2) "Green"
steve = Person "Steve" "Smith" Male (Date 1985 3 3) "Red"
(.==:) :: (Eq p, Show p, Parse p) => Maybe p -> String -> TestTree
expected .==: string = (expected .==. parse string)
|
mattraibert/codetest
|
src/Test/Parse.hs
|
gpl-3.0
| 1,470
| 0
| 10
| 387
| 386
| 204
| 182
| 28
| 1
|
-- | An RPC-like interface for daemons is provided by
-- 'ensureDaemonRunning' and 'runClient'.
--
-- A more versatile interface that lets you supply your own `Handler`
-- is provided by `ensureDaemonWithHandlerRunning` and
-- `runClientWithHandler`. These are useful if, for instance, you
-- need streaming requests or replies, or if you need to change your
-- event handler at runtime.
--
-- The event handling loop is provided by `runInForeground`. You may
-- want to use this for debugging purposes or if you want to handle
-- daemonization manually.
module System.Daemon (
-- * Daemons
ensureDaemonRunning, ensureDaemonWithHandlerRunning,
-- * Clients,
runClient, runClientWithHandler,
-- * Types
DaemonOptions(..), PidFile(..), HostName, Port,
-- * Helpers
runInForeground, bindPort, getSocket
) where
import Control.Concurrent ( threadDelay )
import qualified Control.Exception as CE
import Control.Monad ( when )
import Control.Pipe.C3 ( commandSender, commandReceiver )
import Control.Pipe.Socket ( Handler, runSocketServer, runSocketClient )
import Data.Default ( Default(..) )
import Data.Serialize ( Serialize )
import Data.String ( IsString(..) )
import Network.Socket ( Socket, SockAddr(..), Family(..), SocketType(..)
, SocketOption(..), setSocketOption
, socket, close, connect, bind, listen
, AddrInfo(..), getAddrInfo, addrAddress, defaultHints
, defaultProtocol, tupleToHostAddress, maxListenQueue )
import System.Directory ( getHomeDirectory )
import System.FilePath ( (</>), (<.>) )
import System.Posix.Daemon ( runDetached, isRunning )
import Text.Printf ( printf )
type Port = Int
type HostName = String
-- | The configuration options of a daemon. See 'ensureDaemonRunning'
-- for a description of each.
data DaemonOptions = DaemonOptions
{ daemonPort :: Port
, daemonPidFile :: PidFile
, printOnDaemonStarted :: Bool
} deriving ( Show )
instance Default DaemonOptions where
def = DaemonOptions { daemonPort = 5000
, daemonPidFile = InHome
, printOnDaemonStarted = True
}
-- | The location of the daemon's pidfile.
data PidFile = InHome
| PidFile FilePath
deriving ( Show )
instance IsString PidFile where
fromString = PidFile
-- | Simple wrapper around 'ensureDaemonWithHandlerRunning' which uses
-- a simple function to respond to commands and doesn't deal with
-- pipes.
--
-- The @handler@ is just a function that takes a command and returns a
-- response.
ensureDaemonRunning :: (Serialize a, Serialize b)
=> String -- ^ name
-> DaemonOptions -- ^ options
-> (a -> IO b) -- ^ handler
-> IO ()
ensureDaemonRunning name options executeCommand = do
ensureDaemonWithHandlerRunning name options (commandReceiver executeCommand)
-- FIXME Add set-up and tear-down action. The reason the threaded
-- runtime wouldn't work was because we were creating the mvar in a
-- different thread!
-- | Start a daemon running on the given port, using the given handler
-- to respond to events. If the daemon is already running, don't do
-- anything. Returns immediately.
--
-- The pidfile @PidFile options@ will be created and locked. This
-- function checks the pidfile to see if the daemon is already
-- running.
--
-- The daemon will listen for incoming connections on all interfaces
-- on @daemonPort options@.
--
-- The @handler@ is a function that takes the reader and writer
-- 'ByteString' pipes and does something with them. See
-- 'commandReceiver' for an example handler.
ensureDaemonWithHandlerRunning :: String -- ^ name
-> DaemonOptions -- ^ options
-> Handler () -- ^ handler
-> IO ()
ensureDaemonWithHandlerRunning name options handler = do
home <- getHomeDirectory
let pidfile = case daemonPidFile options of
InHome -> home </> ("." ++ name) <.> "pid"
PidFile path -> path
running <- isRunning pidfile
when (not running) $ do
runDetached (Just pidfile) def
(runInForeground (daemonPort options) handler)
when (printOnDaemonStarted options)
(printf "Daemon started on port %d\n" (daemonPort options))
threadDelay (1 * 1000 * 1000) -- 1s delay
-- | Start the given handler in the foreground. It will listen and
-- respond to events on the given port.
--
-- This is the function that 'ensureDaemonWithHandlerRunning' runs on
-- the daemon thread.
runInForeground :: Port -> Handler () -> IO ()
runInForeground port handler = do
CE.bracket
(bindPort port)
close
(\lsocket ->
runSocketServer lsocket handler)
-- | Send a command to the daemon running at the given network address
-- and wait for a response.
--
-- This is a simple wrapper around 'runClientWithHandler' that sends a
-- single command and waits for a single response.
--
-- If the connection is closed before receiving a response, return
-- 'Nothing'.
runClient :: (Serialize a, Serialize b)
=> HostName -- ^ hostname
-> Port -- ^ port
-> a -- ^ command
-> IO (Maybe b)
runClient hostname port comm =
runClientWithHandler hostname port (commandSender comm)
-- | Connect to the given network address and run the handler on the
-- reader and wrier pipes for the socket.
--
-- The @handler@ is a function that takes the reader and writer
-- 'ByteString' pipes and does something with them. For an example
-- handler, see 'commandSender', which sends a command and waits for a
-- response.
runClientWithHandler :: HostName -- ^ hostname
-> Port -- ^ port
-> Handler a -- ^ command
-> IO a
runClientWithHandler hostname port handler = do
CE.bracket
(getSocket hostname port)
close
(\s -> runSocketClient s handler)
-- | Create a socket and bind it to the given port.
bindPort :: Port -> IO Socket
bindPort port = do
CE.bracketOnError
(socket AF_INET Stream defaultProtocol)
close
(\s -> do
-- FIXME See the examples at the end of Network.Socket.ByteString
setSocketOption s ReuseAddr 1
bind s (SockAddrInet (fromIntegral port) (tupleToHostAddress (0, 0, 0, 0)))
listen s maxListenQueue
return s)
-- | Create a socket connected to the given network address.
getSocket :: HostName -> Port -> IO Socket
getSocket hostname port = do
addrInfos <- getAddrInfo (Just (defaultHints { addrFamily = AF_INET }))
(Just hostname)
(Just $ show port)
CE.bracketOnError
(socket AF_INET Stream defaultProtocol)
close
(\s -> do
connect s (addrAddress $ head addrInfos)
return s)
|
scvalex/daemons
|
src/System/Daemon.hs
|
gpl-3.0
| 7,198
| 0
| 17
| 2,008
| 1,174
| 669
| 505
| 105
| 2
|
module Data.Rhythm.Guitar where
import qualified Numeric.NonNegative.Wrapper as NN
type GtrFret = NN.Int
data SixString = S6 | S5 | S4 | S3 | S2 | S1
deriving (Eq, Ord, Show, Read, Enum, Bounded)
type SixTuning a = SixString -> a
play :: (Num a) => SixString -> GtrFret -> SixTuning a -> a
play s f t = t s + fromIntegral f
-- | The MIDI pitches of standard (EADGBE) guitar tuning.
stdTuning :: (Num a) => SixTuning a
stdTuning s = [40, 45, 50, 55, 59, 64] !! fromEnum s
-- | The MIDI pitches of drop D (DADGBE) guitar tuning.
dropD :: (Num a) => SixTuning a
dropD S6 = 38
dropD s = stdTuning s
|
mtolly/rhythm
|
src/Data/Rhythm/Guitar.hs
|
gpl-3.0
| 603
| 2
| 9
| 127
| 225
| 126
| 99
| 13
| 1
|
module DomainLanguageSpec (spec) where
import Test.Hspec
import Language.Mulang.Ast
import Language.Mulang.Inspector.Combiner (detect)
import Language.Mulang.DomainLanguage (DomainLanguage(..), hasMisspelledIdentifiers, hasTooShortIdentifiers, hasWrongCaseIdentifiers)
import Language.Mulang.Parsers.Haskell (hs)
import Language.Mulang.Parsers.JavaScript (js)
import Language.Mulang.Parsers.Python (py)
import Text.Dictionary (toDictionary)
import Text.Inflections.Tokenizer (camelCase, rubyCase)
spec :: Spec
spec = do
let english = toDictionary ["a","day","great","is","today"]
let jargon = ["ui", "js"]
let language = DomainLanguage english camelCase 3 jargon
describe "hasTooShortIdentifiers" $ do
let run = hasTooShortIdentifiers language
let runDetection = detect (hasTooShortIdentifiers language)
it "is True when it is a one-char identifier" $ do
run (hs "x = True") `shouldBe` True
it "is True when it has numbers" $ do
run (hs "x1 = True") `shouldBe` True
it "is True when it is a two-chars identifier" $ do
run (hs "xy = True") `shouldBe` True
it "is False when it is a three-chars identifier" $ do
run (hs "zip = []") `shouldBe` False
it "is False when it contains a short parameter name" $ do
run (hs "aFunction a = a") `shouldBe` False
it "is False when it contains a short local variable name, but it is detected" $ do
let sample = js "function foo() { let x = 1; return x }"
run sample `shouldBe` False
runDetection sample `shouldBe` ["x"]
it "is False when it uses a short named function" $ do
run (hs "aFunction aNumber = f aNumber") `shouldBe` False
it "is False when it contains a short local variable name in a method, but it is detected" $ do
let sample = js "let pepita = {come:function(){let x = 1; }, vola:function(){}};"
runDetection sample `shouldBe` ["x"]
run sample `shouldBe` False
it "is False when it contains a short local parameter name in a method" $ do
run (js "let pepita = {come:function(x){ }, vola:function(){}};") `shouldBe` False
it "is False when it contains a short named method, but it is detected" $ do
let sample = js "let pepita = {x:function(){}, vola:function(){}};"
runDetection sample `shouldBe` ["x"]
run sample `shouldBe` False
it "is True when it contains a short named attribute" $ do
let sample = js "let pepita = {x: 2, vola:function(){}};"
runDetection sample `shouldBe` ["x"]
run sample `shouldBe` False
it "is True when it contains a short variable name" $ do
run (js "let x = 3;") `shouldBe` True
it "is False when it is jargon" $ do
run (hs "ui = False") `shouldBe` False
describe "hasWrongCaseIdentifiers" $ do
context "camelCase language" $ do
let run = hasWrongCaseIdentifiers language
it "is True when it is a snake case identifier on a camel case language" $ do
run (js "let a_day = 'monday'") `shouldBe` True
it "is False when it is a only camel case identifier on a camel case language" $ do
run (js "let aDay = 'monday'") `shouldBe` False
it "is False when it has numbers but proper casing" $ do
run (js "let aFoo2 = 'monday'") `shouldBe` False
context "rubyCase language" $ do
let run = hasWrongCaseIdentifiers (DomainLanguage english rubyCase 3 jargon)
it "is True when method name is camelCase" $ do
run (SimpleMethod "helloWorld" [] None) `shouldBe` True
it "is False when method name is snake_case" $ do
run (SimpleMethod "hello_world" [] None) `shouldBe` False
it "is False when method name is snake_case!" $ do
run (SimpleMethod "hello_world!" [] None) `shouldBe` False
it "is False when method name is snake_case?" $ do
run (SimpleMethod "hello_world?" [] None) `shouldBe` False
it "is False when method is a symbol" $ do
run (SimpleMethod "+" [] None) `shouldBe` False
it "is True when it is a lower camel case identifier" $ do
run (Variable "helloWorld" None) `shouldBe` True
it "is False when it is a upper camel case identifier" $ do
run (Variable "HelloWorld" None) `shouldBe` False
it "is False when it is a lower snake case identifier" $ do
run (Variable "hello_world" None) `shouldBe` False
it "is False when there is a single upper case char" $ do
run (Variable "H" None) `shouldBe` False
it "is False when there is a single lower case char" $ do
run (Variable "h" None) `shouldBe` False
it "is True when it is a upper snake case identifier" $ do
run (Variable "Hello_World" None) `shouldBe` True
it "is False when it is private snake case method identifier" $ do
run (Variable "_var" None) `shouldBe` False
run (SimpleMethod "__send__" [] None) `shouldBe` False
run (py "def __init__(self): pass") `shouldBe` False
run (py "def ___too_private_to_be_true__(self): pass") `shouldBe` True
describe "hasMisspelledIdentifiers" $ do
let run = hasMisspelledIdentifiers language
it "is False when it is a single, well written token" $ do
run (hs "today = True") `shouldBe` False
it "is False when it is a single, well written but jargon token" $ do
run (hs "js = True") `shouldBe` False
it "is False when all tokens are well-written" $ do
run (hs "todayIsAGreatDay = True") `shouldBe` False
it "is True when it is a single, bad written token" $ do
run (hs "tuday = True") `shouldBe` True
it "is False when it is a typos" $ do
run (hs "tudayIsAGreatDay = True") `shouldBe` True
run (hs "todayIsAGraetDay = True") `shouldBe` True
|
mumuki/mulang
|
spec/DomainLanguageSpec.hs
|
gpl-3.0
| 5,859
| 0
| 20
| 1,488
| 1,444
| 697
| 747
| 103
| 1
|
intSqrt :: Int -> Int
intSqrt = floor . sqrt . fromIntegral
isSquare :: Int -> Bool
isSquare x2 = x2 == x*x
where x = intSqrt x2
catheti :: Int -> [Int]
catheti a = [b|b<-[1..(a-1)], let cc = a*a-b*b, b*b<=cc, isSquare cc]
isCatheti :: Int -> Int -> Int -> Bool
isCatheti a b d = e*b == a*d && cc == c*c
where e = div (a*d) b
cc = a*a-e*e
c = floor ( sqrt ( fromIntegral cc))
solve'' :: Int -> Int -> Bool
solve'' a b | a > b = solve'' b a
solve'' a b | otherwise = (any (isCatheti b a) (catheti a))
solve' :: [Int] -> String
solve' [a,b] | solve'' a b = "TRUE"
| otherwise = "FALSE"
solve :: [String] -> String
solve = solve' . map (read)
main :: IO ()
main = interact (unlines . map (solve . words) . tail . lines)
|
KommuSoft/ieeextreme8
|
ieeextreme80/right-angled-triangles.hs
|
gpl-3.0
| 765
| 31
| 11
| 205
| 427
| 222
| 205
| 22
| 1
|
{-
Copyright (c) 2014 Genome Research Ltd.
Author: Nicholas A. Clarke <nicholas.clarke@sanger.ac.uk>
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 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 General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module Tabula.Command.Cat (
catSession
, Format(..)
) where
import Prelude hiding (init)
import Control.Monad (unless)
import Data.Aeson
import Data.Aeson.Encode.Pretty (encodePretty)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy.Char8 as LB
import Data.Conduit
import qualified Data.Conduit.Binary as DCB
import qualified Data.Conduit.List as DCL
import System.IO
import Tabula.Destination
import Tabula.Record (entry)
import Tabula.Record.Console (command)
data Format = Full | AsHistory
-- | Print a project log to stdout.
catSession :: Destination -- ^ Session to fetch logs from
-> Format -- ^ Show history commands only
-> IO ()
catSession dest fmt = runResourceT $ (recordSource dest)
=$= formatter
=$= DCL.map (B.concat . LB.toChunks)
$$ DCB.sinkHandle stdout
where
formatter = case fmt of
Full -> DCL.map encodePretty =$= mkString "[" "," "]\n"
AsHistory -> DCL.map (fmap (LB.pack . command) . fromJSONMaybe . entry)
=$= DCL.catMaybes =$= mkString "" "\n" "\n"
fromJSONMaybe a = case fromJSON a of
Error _ -> Nothing
Success b -> Just b
mkString :: (Monad m) =>
LB.ByteString -- ^ Initial marker
-> LB.ByteString -- ^ Separation marker
-> LB.ByteString -- ^ Terminal marker
-> Conduit LB.ByteString m LB.ByteString
mkString init sep term = yield init >> loop True >> yield term where
loop first = await >>= \case
Just a -> do
unless first $ yield sep
yield a
loop False
Nothing -> return ()
|
nc6/tabula
|
Tabula/Command/Cat.hs
|
gpl-3.0
| 2,471
| 0
| 19
| 604
| 470
| 254
| 216
| 45
| 3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.