code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Stack where
import Control.Monad.State
type Stack = [Int]
pop :: State Stack Int
pop = state $ \(x:xs) -> (x, xs)
push :: Int -> State Stack ()
push a = state $ \xs -> ((), a:xs)
stackManip :: State Stack Int
stackManip = do
push 3
_ <- pop
pop
stackStuff :: State Stack ()
stackStuff = do
a <- pop
if a == 5
then push 5
else do
push 3
push 8
moreStack :: State Stack ()
moreStack = do
a <- stackManip
if a == 100
then stackStuff
else return ()
stackyStack :: State Stack ()
stackyStack = do
stackNow <- get
if stackNow == [1,2,3]
then put [8,3,1]
else put [9,2,1]
pop' :: State Stack Int
pop' = do
(x:xs) <- get
put xs
return x
push' :: Int -> State Stack ()
push' x = do
xs <- get
put (x:xs)
|
alexliew/learn_you_a_haskell
|
code/stack.hs
|
unlicense
| 775 | 0 | 10 | 222 | 387 | 199 | 188 | 41 | 2 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
module Control.Monad.RWSIO.Strict
( MonadRWS
, RWSRef
, RWSIO (..)
, ask', get, tell, put
, initMonadRWS
, resetMonadRWS
, resetMonadRWSWriter
, runMonadRWS0
, runMonadRWS
, runMonadRWS'
)
where
import Control.Monad.IO.Class
import Control.Monad.Reader.Class (MonadReader, ask)
import Control.Monad.State.Class (MonadState, get, put)
import Control.Monad.Trans.Reader (ReaderT (..))
import Control.Monad.Writer.Class (MonadWriter (..), tell)
import Data.IORef
------------------------------------------------------------------------------
type RWSRef r w s = (r, IORef (w, s))
newtype RWSIO r w s a = RWSIO { unRWSIO :: RWSRef r w s -> IO a }
deriving (Functor, Applicative, Monad, MonadIO, MonadReader (RWSRef r w s))
via ReaderT (RWSRef r w s) IO
instance MonadState s (RWSIO r w s) where
get = do
(_, ref) <- ask
(_w, s) <- liftIO (readIORef ref)
pure s
put s' = do
(_, ref) <- ask
liftIO $ do
(w, _s) <- readIORef ref
writeIORef ref (w, s')
pure ()
instance Monoid w => MonadWriter w (RWSIO r w s) where
tell x = do
(_, ref) <- ask
liftIO $ do
(w, s) <- readIORef ref
writeIORef ref (w<>x, s)
pure ()
listen m = do
x@(_, ref) <- ask
liftIO $ do
(w, _s) <- readIORef ref
a <- unRWSIO m x
pure (a, w)
pass m = do
x@(_, ref) <- ask
liftIO $ do
(w, s) <- readIORef ref
(a, f) <- unRWSIO m x
writeIORef ref (f w, s)
pure a
ask' :: (Monad m, MonadReader (RWSRef r w s) m) => m r
ask' = fst <$> ask
type MonadRWS r w s m =
( MonadReader (RWSRef r w s) m
, MonadWriter w m
, MonadState s m )
initMonadRWS :: (MonadIO m, Monoid w) => r -> s -> m (RWSRef r w s)
initMonadRWS r s = (r,) <$> liftIO (newIORef (mempty, s))
resetMonadRWS :: (MonadIO m, Monoid w) => RWSRef r w s -> s -> m ()
resetMonadRWS (_, ref) s = liftIO (writeIORef ref (mempty, s))
resetMonadRWSWriter :: (MonadIO m, Monoid w) => RWSRef r w s -> m ()
resetMonadRWSWriter (_, ref) = liftIO (modifyIORef' ref (\(_, s) -> (mempty, s)))
runMonadRWS0
:: (MonadIO m, Monoid w)
=> RWSIO r w s a -> r -> s
-> m (a, s, w, RWSRef r w s)
runMonadRWS0 act r s = liftIO $ do
x@(_,ref) <- initMonadRWS r s
a <- unRWSIO act x
(w, s') <- readIORef ref
pure (a, s', w, x)
-- | Typical usage: 'initMonadRWS' followed by one or more 'runMonadRWS'
runMonadRWS
:: (MonadIO m, Monoid w)
=> RWSIO r w s a -> RWSRef r w s
-> m (a, s, w, RWSRef r w s)
runMonadRWS act x@(_,ref) = liftIO $ do
resetMonadRWSWriter x
a <- unRWSIO act x
(w, s') <- readIORef ref
pure (a, s', w, x)
runMonadRWS'
:: (MonadIO m, Monoid w)
=> RWSIO r w s a -> s -> RWSRef r w s
-> m (a, s, w, RWSRef r w s)
runMonadRWS' act s x@(_,ref) = liftIO $ do
resetMonadRWS x s
a <- unRWSIO act x
(w, s') <- readIORef ref
pure (a, s', w, x)
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/topic/monads/2020-06-hc-reader-and-monad-write-state-io/src/Control/Monad/RWSIO/Strict.hs
|
unlicense
| 3,410 | 0 | 13 | 1,029 | 1,393 | 745 | 648 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-
Copyright 2016 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Internal.Num (
Number,
(+),
(-),
(*),
(/),
(^),
(>),
(>=),
(<),
(<=),
max,
min,
opposite,
negate,
abs,
absoluteValue,
signum,
truncation,
rounded,
ceiling,
floor,
quotient,
remainder,
reciprocal,
pi,
exp,
sqrt,
squareRoot,
log,
logBase,
sin,
tan,
cos,
asin,
atan,
atan2,
acos,
properFraction,
even,
odd,
gcd,
lcm,
sum,
product,
maximum,
minimum,
isInteger,
fromInteger,
fromRational,
fromInt,
toInt,
fromDouble,
toDouble
) where
import qualified "base" Prelude as P
import "base" Prelude (Bool(..), (.), (==), map)
import Numeric (showFFloatAlt)
import qualified Internal.Truth
import Internal.Truth (Truth, otherwise, (&&))
import GHC.Stack (HasCallStack, withFrozenCallStack)
{-|The type for numbers.
Numbers can be positive or negative, whole or fractional. For example, 5,
3.2, and -10 are all values of the type Number.
-}
newtype Number = Number P.Double
deriving (P.RealFrac, P.Real, P.Floating, P.RealFloat, P.Eq)
{-# RULES "equality/num" forall (x :: Number). (Internal.Truth.==) x = (P.==) x #-}
{-# RULES "equality/point" forall (x :: (Number, Number)). (Internal.Truth.==) x = (P.==) x #-}
fromDouble :: HasCallStack => P.Double -> Number
fromDouble x | P.isNaN x = P.error "Number is undefined."
| P.isInfinite x = P.error "Number is too large."
| otherwise = Number x
toDouble :: Number -> P.Double
toDouble (Number x) = x
fromInteger :: P.Integer -> Number
fromInteger = fromDouble . P.fromInteger
fromRational :: P.Rational -> Number
fromRational = fromDouble . P.fromRational
fromInt :: P.Int -> Number
fromInt = fromDouble . P.fromIntegral
toInt :: HasCallStack => Number -> P.Int
toInt n | isInteger n = P.truncate (toDouble n)
| otherwise = P.error "Whole number is required."
instance P.Show Number where
show (Number x) = stripZeros (showFFloatAlt (P.Just 4) x "")
where stripZeros = P.reverse
. P.dropWhile (== '.')
. P.dropWhile (== '0')
. P.reverse
instance P.Num Number where
fromInteger = fromInteger
(+) = (+)
(-) = (-)
(*) = (*)
negate = opposite
abs = abs
signum = signum
instance P.Fractional Number where
fromRational x = Number (P.fromRational x)
(/) = (/)
instance P.Enum Number where
succ = fromDouble . P.succ . toDouble
pred = fromDouble . P.pred . toDouble
toEnum = fromDouble . P.toEnum
fromEnum = P.fromEnum . toDouble
enumFrom = map fromDouble . P.enumFrom . toDouble
enumFromThen (Number a) (Number b) = map fromDouble (P.enumFromThen a b)
enumFromTo (Number a) (Number b) = map fromDouble (P.enumFromTo a b)
enumFromThenTo (Number a) (Number b) (Number c) = map fromDouble (P.enumFromThenTo a b c)
instance P.Ord Number where
compare (Number a) (Number b) = P.compare a b
{-| Tells whether a Number is an integer or not.
An integer is a whole number, such as 5, 0, or -10. Numbers with non-zero
decimals, like 5.3, are not integers.
-}
isInteger :: Number -> Truth
isInteger (Number x) = x == P.fromIntegral (P.truncate x)
infixr 8 ^
infixl 7 *, /
infixl 6 +, -
infix 4 <, <=, >=, >
{-| Adds two numbers. -}
(+) :: Number -> Number -> Number
Number a + Number b = fromDouble (a P.+ b)
{-| Subtracts two numbers. -}
(-) :: Number -> Number -> Number
Number a - Number b = fromDouble (a P.- b)
{-| Multiplies two numbers. -}
(*) :: Number -> Number -> Number
Number a * Number b = fromDouble (a P.* b)
{-| Divides two numbers. The second number should not be zero. -}
(/) :: Number -> Number -> Number
Number a / Number b = fromDouble (a P./ b)
{-| Raises a number to a power. -}
(^) :: Number -> Number -> Number
Number a ^ Number b = fromDouble (a P.** b)
{-| Tells whether one number is less than the other. -}
(<) :: Number -> Number -> Truth
Number a < Number b = a P.< b
{-| Tells whether one number is less than or equal to the other. -}
(<=) :: Number -> Number -> Truth
Number a <= Number b = a P.<= b
{-| Tells whether one number is greater than the other. -}
(>) :: Number -> Number -> Truth
Number a > Number b = a P.> b
{-| Tells whether one number is greater than or equal to the other. -}
(>=) :: Number -> Number -> Truth
Number a >= Number b = a P.>= b
{-| Gives the larger of two numbers. -}
max :: (Number, Number) -> Number
max (Number a, Number b) = fromDouble (P.max a b)
{-| Gives the smaller of two numbers. -}
min :: (Number, Number) -> Number
min (Number a, Number b) = fromDouble (P.min a b)
{-| Gives the opposite (that is, the negative) of a number. -}
opposite :: Number -> Number
opposite = fromDouble . P.negate . toDouble
negate :: Number -> Number
negate = opposite
{-| Gives the absolute value of a number.
If the number if positive or zero, the absolute value is the same as the
number. If the number is negative, the absolute value is the opposite of
the number.
-}
abs :: Number -> Number
abs = fromDouble . P.abs . toDouble
absoluteValue :: Number -> Number
absoluteValue = abs
{-| Gives the sign of a number.
If the number is negative, the signum is -1. If it's positive, the signum
is 1. If the number is 0, the signum is 0. In general, a number is equal
to its absolute value ('abs') times its sign ('signum').
-}
signum :: Number -> Number
signum = fromDouble . P.signum . toDouble
{-| Gives the number without its fractional part.
For example, truncate(4.2) is 4, while truncate(-4.7) is -4.
-}
truncation :: Number -> Number
truncation = fromInteger . P.truncate . toDouble
{-| Gives the number rounded to the nearest integer.
For example, round(4.2) is 4, while round(4.7) is 5.
-}
rounded :: Number -> Number
rounded = fromInteger . P.round . toDouble
{-| Gives the smallest integer that is greater than or equal to a number.
For example, ceiling(4) is 4, while ceiling(4.1) is 5. With negative
numbers, ceiling(-3.5) is -3, since -3 is greater than -3.5.
-}
ceiling :: Number -> Number
ceiling = fromInteger . P.ceiling . toDouble
{-| Gives the largest integer that is less than or equal to a number.
For example, floor(4) is 4, while floor(3.9) is 3. With negative
numbers, floor(-3.5) is -4, since -4 is less than -3.5.
-}
floor :: Number -> Number
floor = fromInteger . P.floor . toDouble
{-| Gives the integer part of the result when dividing two numbers.
For example, 3/2 is 1.5, but quotient(3, 2) is 1, which is the integer
part.
-}
quotient :: (Number, Number) -> Number
quotient (a, b) = truncation (a / b)
{-| Gives the remainder when dividing two numbers.
For example, remainder(3,2) is 1, which is the remainder when dividing
3 by 2.
-}
remainder :: (Number, Number) -> Number
remainder (a, b) = a - b * quotient (a, b)
{-| Gives the repicrocal of a number.
For example, reciprocal(5) is 1/5 (also written as 0.2).
-}
reciprocal :: Number -> Number
reciprocal = fromDouble . P.recip . toDouble
{-| The constant pi, which is equal to the ration between the circumference
and diameter of a circle.
pi is approximately 3.14159.
-}
pi :: Number
pi = fromDouble P.pi
{-| Gives the exponential of a number. This is equal to the constant e,
raised to the power of the number.
The exp function increases faster and faster very quickly. For example,
if t is the current time in seconds, exp(t) will reach a million in about
14 seconds. It will reach a billion in around 21 seconds.
-}
exp :: Number -> Number
exp = fromDouble . P.exp . toDouble
{-| Gives the square root of a number. This is the positive number that, when
multiplied by itself, gives the original number back.
The sqrt always increases, but slows down. For example, if t is the
current time, sqrt(t) will reach 5 in 25 seconds. But it will take 100
seconds to reach 10, and 225 seconds (almost 4 minutes) to reach 15.
-}
sqrt :: Number -> Number
sqrt = fromDouble . P.sqrt . toDouble
squareRoot :: Number -> Number
squareRoot = sqrt
{-| Gives the natural log of a number. This is the opposite of the exp
function.
Like sqrt, the log function always increases, but slows down. However,
it slows down much sooner than the sqrt function. If t is the current time
in seconds, it takes more than 2 minutes for log(t) to reach 5, and more
than 6 hours to reach 10!
-}
log :: Number -> Number
log = fromDouble . P.log . toDouble
{-| Gives the logarithm of the first number, using the base of the second
number.
-}
logBase :: (Number, Number) -> Number
logBase (Number x, Number b) = fromDouble (P.logBase b x)
{-| Converts an angle from degrees to radians. -}
toRadians :: Number -> Number
toRadians d = d / 180 * pi
{-| Converts an angle from radians to degrees. -}
fromRadians :: Number -> Number
fromRadians r = r / pi * 180
{-| Gives the sine of an angle, where the angle is measured in degrees. -}
sin :: Number -> Number
sin = fromDouble . P.sin . toDouble . toRadians
{-| Gives the tangent of an angle, where the angle is measured in degrees.
This is the slope of a line at that angle from horizontal.
-}
tan :: Number -> Number
tan = fromDouble . P.tan . toDouble . toRadians
{-| Gives the cosine of an angle, where the angle is measured in degrees. -}
cos :: Number -> Number
cos = fromDouble . P.cos . toDouble . toRadians
{-| Gives the inverse sine of a value, in degrees.
This is the unique angle between -90 and 90 that has the input as its sine.
-}
asin :: Number -> Number
asin = fromRadians . fromDouble . P.asin . toDouble
{-| Gives the inverse tangent of a value, in degrees.
This is the unique angle between -90 and 90 that has the input as its tangent.
-}
atan :: Number -> Number
atan = fromRadians . fromDouble . P.atan . toDouble
{-| Gives the angle between the positive x axis and a given point, in degrees. -}
atan2 :: (Number, Number) -> Number
atan2 (Number a, Number b) = fromRadians (fromDouble (P.atan2 a b))
{-| Gives the inverse cosine of a value, in degrees.
This is the unique angle between 0 and 180 that has the input as its cosine.
-}
acos :: Number -> Number
acos = fromRadians . fromDouble . P.acos . toDouble
{-| Separates a number into its whole and fractional parts.
For example, properFraction(1.2) is (1, 0.2).
-}
properFraction :: Number -> (Number, Number)
properFraction (Number x) = (fromInteger w, fromDouble p)
where (w,p) = P.properFraction x
{-| Tells if a number is even. -}
even :: Number -> Truth
even n | isInteger n = P.even (toInt n)
| otherwise = False
{-| Tells if a number is odd. -}
odd :: Number -> Truth
odd n | isInteger n = P.odd (toInt n)
| otherwise = False
{-| Gives the greatest common divisor of two numbers.
This is the largest number that divides each of the two parameters.
Both parameters must be integers.
-}
gcd :: HasCallStack => (Number, Number) -> Number
gcd (a, b) = withFrozenCallStack (fromInt (P.gcd (toInt a) (toInt b)))
{-| Gives the least common multiple of two numbers.
This is the smallest number that is divisible by both of the two
parameters. Both parameters must be integers.
-}
lcm :: HasCallStack => (Number, Number) -> Number
lcm (a, b) = withFrozenCallStack (fromInt (P.lcm (toInt a) (toInt b)))
{-| Gives the sum of a list of numbers. -}
sum :: [Number] -> Number
sum = fromDouble . P.sum . P.map toDouble
{-| Gives the product of a list of numbers. -}
product :: [Number] -> Number
product = fromDouble . P.product . P.map toDouble
{-| Gives the largest number from a list. -}
maximum :: [Number] -> Number
maximum = fromDouble . P.maximum . P.map toDouble
{-| Gives the smallest number from a list. -}
minimum :: [Number] -> Number
minimum = fromDouble . P.minimum . P.map toDouble
|
nomeata/codeworld
|
codeworld-base/src/Internal/Num.hs
|
apache-2.0
| 12,691 | 2 | 12 | 2,864 | 2,679 | 1,468 | 1,211 | -1 | -1 |
-----------------------------------------------------------------------------
-- Copyright 2012 Microsoft Corporation.
--
-- This is free software; you can redistribute it and/or modify it under the
-- terms of the Apache License, Version 2.0. A copy of the License can be
-- found in the file "license.txt" at the root of this distribution.
-----------------------------------------------------------------------------
{-
Main module.
-}
-----------------------------------------------------------------------------
module Compiler.Options( -- * Command line options
getOptions, processOptions, Mode(..), Flags(..)
-- * Show standard messages
, showHelp, showEnv, showVersion, commandLineHelp, showIncludeInfo
-- * Utilities
, prettyEnvFromFlags
, colorSchemeFromFlags
, prettyIncludePath
) where
import Data.Char ( toUpper )
import Data.List ( intersperse )
import System.Environment ( getArgs )
import Platform.GetOptions
import Platform.Config ( version, compiler, buildTime, buildVariant, exeExtension, programName, getInstallDirectory, getDataDirectory )
import Lib.PPrint
import Lib.Printer
import Common.Failure ( raiseIO )
import Common.ColorScheme
import Common.File
import Common.System
import Common.Syntax ( Target (..), Host(..) )
import Compiler.Package
{--------------------------------------------------------------------------
Convert flags to pretty environment
--------------------------------------------------------------------------}
import qualified Type.Pretty as TP
prettyEnvFromFlags :: Flags -> TP.Env
prettyEnvFromFlags flags
= TP.defaultEnv{ TP.showKinds = showKinds flags
, TP.expandSynonyms = showSynonyms flags
, TP.colors = colorSchemeFromFlags flags
, TP.htmlBases = htmlBases flags
, TP.htmlCss = htmlCss flags
, TP.htmlJs = htmlJs flags
, TP.verbose = verbose flags
}
colorSchemeFromFlags :: Flags -> ColorScheme
colorSchemeFromFlags flags
= colorScheme flags
prettyIncludePath :: Flags -> Doc
prettyIncludePath flags
= let cscheme = colorScheme flags
path = includePath flags
in align (if null path then color (colorSource cscheme) (text "<empty>")
else cat (punctuate comma (map (\p -> color (colorSource cscheme) (text p)) path)))
{--------------------------------------------------------------------------
Options
--------------------------------------------------------------------------}
data Mode
= ModeHelp
| ModeVersion
| ModeCompiler { files :: [FilePath] }
| ModeInteractive { files :: [FilePath] }
data Option
= Interactive
| Version
| Help
| Flag (Flags -> Flags)
| Error String
data Flags
= Flags{ warnShadow :: Bool
, showKinds :: Bool
, showKindSigs :: Bool
, showSynonyms :: Bool
, showCore :: Bool
, showAsmCSharp :: Bool
, showAsmJavaScript :: Bool
, showTypeSigs :: Bool
, evaluate :: Bool
, library :: Bool
, targets :: [Target]
, host :: Host
, noSimplify :: Bool
, colorScheme :: ColorScheme
, outDir :: FilePath
, includePath :: [FilePath]
, csc :: FilePath
, node :: FilePath
, editor :: String
, redirectOutput :: FilePath
, maxStructFields :: Int
, outHtml :: Int
, htmlBases :: [(String,String)]
, htmlCss :: String
, htmlJs :: String
, verbose :: Int
, exeName :: String
, showSpan :: Bool
, console :: String
, rebuild :: Bool
, genCore :: Bool
-- , installDir :: FilePath
, semiInsert :: Bool
, packages :: Packages
}
flagsNull :: IO Flags
flagsNull
= do -- try to find the data file install dir and use it as first include path
includePath <- getInstallDirectory >>= \md-> return $ case md of
Nothing -> []
Just d -> [d]
-- a user specific path for storing application data
outDir <- getDataDirectory
createDirectoryIfMissing True outDir
return $ Flags -- warnings
True
-- show
False False -- kinds kindsigs
False False -- synonyms core
False -- show asmCSharp
False -- show asmJavaScript
False -- typesigs
True -- executes
False -- library
[JS]
Node
False -- noSimplify
defaultColorScheme
outDir
includePath
"csc"
"node"
""
""
3
0
[]
("styles/" ++ programName ++ ".css")
("")
0
""
False
"ansi" -- console: ansi, html
False -- rebuild
False -- genCore
-- "" -- install dir
True -- semi colon insertion
packagesEmpty -- packages
isHelp Help = True
isHelp _ = False
isVersion Version = True
isVersion _ = False
isInteractive Interactive = True
isInteractive _ = False
{--------------------------------------------------------------------------
Options and environment variables
--------------------------------------------------------------------------}
-- | The option table.
optionsAll :: [OptDescr Option]
optionsAll
= let (xs,ys) = options in (xs++ys)
options :: ([OptDescr Option],[OptDescr Option])
options = (\(xss,yss) -> (concat xss, concat yss)) $ unzip
[ option ['?','h'] ["help"] (NoArg Help) "show this information"
, option [] ["version"] (NoArg Version) "show the compiler version"
, option ['p'] ["prompt"] (NoArg Interactive) "interactive mode"
, flag ['e'] ["execute"] (\b f -> f{evaluate= b}) "compile and execute (default)"
, flag ['c'] ["compile"] (\b f -> f{evaluate= not b}) "only compile, do not execute"
, option ['i'] ["include"] (OptArg includePathFlag "dirs") "add <dirs> to search path (empty resets)"
, option ['o'] ["outdir"] (ReqArg outDirFlag "dir") "put generated files in <dir>"
, option [] ["outname"] (ReqArg exeNameFlag "name") "name of the final executable"
, flag ['v'] ["verbose"] (\b f -> f{verbose=if b then (verbose f)+1 else 0}) "run more verbose"
, flag ['r'] ["rebuild"] (\b f -> f{rebuild = b}) "rebuild all"
, flag ['l'] ["library"] (\b f -> f{library=b, evaluate=if b then False else (evaluate f) }) "generate a library"
, emptyline
, flag [] ["html"] (\b f -> f{outHtml = if b then 2 else 0}) "generate documentation"
, option [] ["htmlbases"] (ReqArg htmlBasesFlag "bases") "set link prefixes for documentation"
, option [] ["htmlcss"] (ReqArg htmlCssFlag "link") "set link to the css documentation style"
, config [] ["target"] [("js",[JS]),("cs",[CS])] (\t f -> f{targets=t}) "generate csharp or javascript (default)"
, config [] ["host"] [("node",Node),("browser",Browser)] (\h f -> f{ targets=[JS], host=h}) "specify host for running code"
, emptyline
, flag [] ["showspan"] (\b f -> f{ showSpan = b}) "show ending row/column too on errors"
-- , flag [] ["showkinds"] (\b f -> f{showKinds=b}) "show full kind annotations"
, flag [] ["showkindsigs"] (\b f -> f{showKindSigs=b}) "show kind signatures of type definitions"
, flag [] ["showtypesigs"] (\b f -> f{showTypeSigs=b}) "show type signatures of definitions"
, flag [] ["showsynonyms"] (\b f -> f{showSynonyms=b}) "show expanded type synonyms in types"
, flag [] ["showcore"] (\b f -> f{showCore=b}) "show core"
, flag [] ["showcs"] (\b f -> f{showAsmCSharp=b}) "show generated c#"
, flag [] ["showjs"] (\b f -> f{showAsmJavaScript=b}) "show generated javascript"
, flag [] ["core"] (\b f -> f{genCore=b}) "generate a core file"
-- , flag [] ["show-coreF"] (\b f -> f{showCoreF=b}) "show coreF"
, emptyline
, option [] ["editor"] (ReqArg editorFlag "cmd") "use <cmd> as editor"
, option [] ["csc"] (ReqArg cscFlag "cmd") "use <cmd> as the csharp backend compiler"
, option [] ["node"] (ReqArg nodeFlag "cmd") "use <cmd> to execute node"
, option [] ["color"] (ReqArg colorFlag "colors") "set colors"
, option [] ["redirect"] (ReqArg redirectFlag "file") "redirect output to <file>"
, configstr [] ["console"] ["ansi","html","raw"] (\s f -> f{console=s}) "console output format"
-- , option [] ["install-dir"] (ReqArg installDirFlag "dir") "set the install directory explicitly"
, hiddenFlag [] ["simplify"] (\b f -> f{noSimplify= not b}) "enable core simplification"
, hiddenFlag [] ["structs"] (\b f -> f{maxStructFields= if b then 3 else 0}) "pass constructors on stack"
, hiddenFlag [] ["semi"] (\b f -> f{semiInsert=b}) "insert semicolons based on layout"
]
where
emptyline
= flag [] [] (\b f -> f) ""
option short long f desc
= ([Option short long f desc],[])
hiddenOption short long f desc
= ([],[Option short long f desc])
flag short long f desc
= ([Option short long (NoArg (Flag (f True))) desc]
,[Option [] (map ("no-" ++) long) (NoArg (Flag (f False))) ""])
hiddenFlag short long f desc
= ([],[Option short long (NoArg (Flag (f True))) desc
,Option [] (map ("no-" ++) long) (NoArg (Flag (f False))) ""])
config short long opts f desc
= option short long (ReqArg validate valid) desc
where
valid = "(" ++ concat (intersperse "|" (map fst opts)) ++ ")"
validate s
= case lookup s opts of
Just x -> Flag (\flags -> f x flags)
Nothing -> Error ("invalid value for --" ++ head long ++ " option, expecting any of " ++ valid)
configstr short long opts f desc
= config short long (map (\s -> (s,s)) opts) f desc
colorFlag s
= Flag (\f -> f{ colorScheme = readColorFlags s (colorScheme f) })
consoleFlag s
= Flag (\f -> f{ console = s })
htmlBasesFlag s
= Flag (\f -> f{ htmlBases = (htmlBases f) ++ readHtmlBases s })
htmlCssFlag s
= Flag (\f -> f{ htmlCss = s })
includePathFlag mbs
= Flag (\f -> f{ includePath = case mbs of
Just s | not (null s) -> includePath f ++ splitSearchPath s
_ -> [] })
outDirFlag s
= Flag (\f -> f{ outDir = s })
exeNameFlag s
= Flag (\f -> f{ exeName = s })
cscFlag s
= Flag (\f -> f{ csc = s })
nodeFlag s
= Flag (\f -> f{ node = s })
editorFlag s
= Flag (\f -> f{ editor = s })
redirectFlag s
= Flag (\f -> f{ redirectOutput = s })
{-
installDirFlag s
= Flag (\f -> f{ installDir = s, includePath = (includePath f) ++ [libd] })
where
libd = joinPath s "lib"
-}
readHtmlBases :: String -> [(String,String)]
readHtmlBases s
= map toBase (splitComma s)
where
splitComma :: String -> [String]
splitComma xs
= let (pre,ys) = span (/=',') xs
in case ys of
(_:post) -> pre : splitComma post
[] -> [pre]
toBase xs
= let (pre,ys) = span (/='=') xs
in case ys of
(_:post) -> (pre,post)
_ -> ("",xs)
-- | Environment table
environment :: [ (String, String, (String -> [String]), String) ]
environment
= [ -- ("koka-dir", "dir", dirEnv, "The install directory")
("koka-options", "options", flagsEnv, "Add <options> to the command line")
, ("koka-editor", "command", editorEnv, "Use <cmd> as the editor (substitutes %l, %c, and %s)")
]
where
flagsEnv s = [s]
editorEnv s = ["--editor=" ++ s]
-- dirEnv s = ["--install-dir=" ++ s]
{--------------------------------------------------------------------------
Process options
--------------------------------------------------------------------------}
getOptions :: String -> IO (Flags,Mode)
getOptions extra
= do env <- getEnvOptions
args <- getArgs
flags <- flagsNull
processOptions flags (env ++ words extra ++ args)
processOptions :: Flags -> [String] -> IO (Flags,Mode)
processOptions flags0 opts
= let (options,files,errs0) = getOpt Permute optionsAll opts
errs = errs0 ++ extractErrors options
in if (null errs)
then let flags = extractFlags flags0 options
mode = if (any isHelp options) then ModeHelp
else if (any isVersion options) then ModeVersion
else if (any isInteractive options) then ModeInteractive files
else if (null files) then ModeInteractive files
else ModeCompiler files
in do pkgs <- discoverPackages (outDir flags)
return (flags{ packages = pkgs },mode)
else invokeError errs
extractFlags :: Flags -> [Option] -> Flags
extractFlags flagsInit options
= let flags = foldl extract flagsInit options
in case (JS `elem` targets flags) of -- the maxStructFields prevents us from generating CS and JS at the same time...
True -> flags{ maxStructFields = -1 }
_ -> flags
where
extract flags (Flag f) = f flags
extract flags _ = flags
extractErrors :: [Option] -> [String]
extractErrors options
= concatMap extract options
where
extract (Error s) = [s ++ "\n"]
extract _ = []
getEnvOptions :: IO [String]
getEnvOptions
= do csc <- getEnvCsc
xss <- mapM getEnvOption environment
return (concat ({- ["--install-dir=" ++ idir]:-} csc:xss))
where
getEnvOption (envName,_,extract,_)
= do s <- getEnvVar envName
if null s
then return []
else return (extract s)
getEnvCsc
= do fw <- getEnvVar "FRAMEWORK"
fv <- getEnvVar "FRAMEWORKVERSION"
if (null fw || null fv)
then do mbsroot <- getEnvVar "SYSTEMROOT"
let sroot = if null mbsroot then "c:\\windows" else mbsroot
froot = joinPath sroot "Microsoft.NET\\Framework"
mbcsc <- searchPaths [joinPath froot "v4.0.30319"
,joinPath froot "v2.0.50727"
,joinPath froot "v1.1.4322"]
[exeExtension] "csc"
case mbcsc of
Nothing -> return []
Just csc -> return ["--csc=" ++ csc ]
else return ["--csc="++ joinPaths [fw,fv,"csc"]]
{--------------------------------------------------------------------------
Show options
--------------------------------------------------------------------------}
invokeError :: [String] -> IO a
invokeError errs
= raiseIO (concat errs ++ " (" ++ helpMessage ++ ")\n")
where
helpMessage = "use \"--help\" for help on command line options"
-- | Show command line help
showHelp :: Printer p => Flags -> p -> IO ()
showHelp flags p
= do doc <- commandLineHelp flags
writePrettyLn p doc
-- | Show the morrow environment variables
showEnv :: Printer p => Flags -> p -> IO ()
showEnv flags p
= do doc <- environmentInfo (colorSchemeFromFlags flags)
writePrettyLn p (showIncludeInfo flags <$> showOutputInfo flags <$> doc)
commandLineHelp :: Flags -> IO Doc
commandLineHelp flags
= do envInfo <- environmentInfo colors
return $
vcat
[ infotext "usage:"
, text " " <> text programName <+> text "<options> files"
, empty
, infotext "options:" <> string (usageInfo "" (fst options))
, infotext "remarks:"
, text " Boolean options can be negated, as in: --no-compile"
, text " The editor <cmd> can contain %f, %l, and %c to substitute the filename"
, text " line number and column number on the ':e' command in the interpreter."
, text " The html bases are comma separated <base>=<url> pairs where the base"
, text " is a prefix of module names. If using just a <url> it matches any module."
, showIncludeInfo flags
, showOutputInfo flags
, envInfo
, empty
]
where
colors
= colorSchemeFromFlags flags
infotext s
= color (colorInterpreter colors) (text s)
showIncludeInfo flags
= hang 2 (infotext "include path:" <$> prettyIncludePath flags) -- text (if null paths then "<empty>" else paths))
where
paths
= concat $ intersperse [searchPathSeparator] (includePath flags)
colors
= colorSchemeFromFlags flags
infotext s
= color (colorInterpreter colors) (text s)
showOutputInfo flags
= hang 2 (infotext "output directory:" <$> text (outDir flags)) -- text (if null paths then "<empty>" else paths))
where
colors
= colorSchemeFromFlags flags
infotext s
= color (colorInterpreter colors) (text s)
environmentInfo colors
= do vals <- mapM getEnvValue environment
return (hang 2 (infotext "environment:" <$>
vcat (map ppEnv vals) <$> text " "))
where
infotext s
= color (colorInterpreter colors) (text s)
ppEnv (name,val)
= fill n (text name) <> text "=" <+> val
n = maximum [length name | (name,_,_,_) <- environment]
getEnvValue (name,val,_,desc)
= do s <- getEnvVar name
if null s
then return (name,text ("<" ++ val ++ ">"))
else return (name,text s)
showVersion :: Printer p => p -> IO ()
showVersion p
= writePrettyLn p versionMessage
versionMessage :: Doc
versionMessage
=
(vcat $ map text $
[ capitalize programName ++ " " ++ version ++ ", " ++ buildTime ++
(if null (compiler ++ buildVariant) then "" else " (" ++ compiler ++ " " ++ buildVariant ++ " version)")
, ""
])
<$>
(color DarkGray $ vcat $ map text
[ "Copyright 2012 Microsoft Corporation, by Daan Leijen."
, "This program is free software; see the source for copying conditions."
, "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."
])
where
capitalize "" = ""
capitalize (c:cs) = toUpper c : cs
|
lpeterse/koka
|
src/Compiler/Options.hs
|
apache-2.0
| 19,294 | 1 | 21 | 6,090 | 5,084 | 2,753 | 2,331 | 376 | 7 |
{-# LANGUAGE RecordWildCards #-}
module Concurrent.Internal.Backoff where
import Control.Concurrent
data Backoff = Backoff
{ current
, cap
, totalWait :: {-# UNPACK #-} !Int
}
defaultBackoff :: Backoff
defaultBackoff = Backoff 0 10000 0 -- 10ms
backoff :: Backoff -> IO Backoff
backoff b@Backoff{..}
| current < 1 = do
yield
return b { current = current + 1 }
| otherwise = do
threadDelay current
return b { current = min cap (2*current), totalWait = totalWait + current }
|
ekmett/concurrent
|
src/Concurrent/Internal/Backoff.hs
|
bsd-2-clause
| 508 | 0 | 13 | 115 | 163 | 87 | 76 | 17 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.SGIS.PointParameters
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/SGIS/point_parameters.txt SGIS_point_parameters> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.SGIS.PointParameters (
-- * Enums
gl_DISTANCE_ATTENUATION_SGIS,
gl_POINT_FADE_THRESHOLD_SIZE_SGIS,
gl_POINT_SIZE_MAX_SGIS,
gl_POINT_SIZE_MIN_SGIS,
-- * Functions
glPointParameterfSGIS,
glPointParameterfvSGIS
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/SGIS/PointParameters.hs
|
bsd-3-clause
| 877 | 0 | 4 | 100 | 61 | 48 | 13 | 9 | 0 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Jat.PState.MemoryModel.PairSharing
(
PairSharing
)
where
import qualified Control.Applicative as A
import Jat.Constraints (PATerm)
import Jat.JatM
import qualified Jat.PairSet as PS
import Jat.PState.AbstrValue
import Jat.PState.AbstrDomain as AD
import Jat.PState.Data
import Jat.PState.Fun
import Jat.PState.Frame
import Jat.PState.Heap
import Jat.PState.IntDomain
import Jat.PState.MemoryModel.Data
import Jat.PState.Object
import Jat.PState.Step
import Jat.Utils.Pretty as PP
import Jat.Utils.Fun
import qualified Jinja.Program as P
import Data.Maybe ( fromMaybe)
import qualified Data.Map as M
import Control.Monad.State
import Data.List (find)
import Data.Array as A
import qualified JFlow.Instances as F
import qualified JFlow.Flow as F
-- import Debug.Trace
mname :: String
mname = "Jat.PState.MemoryModel.PairSharing"
merror :: String -> a
merror msg = error $ mname ++ msg
data NShare = Address :/=: Address deriving (Eq,Ord)
type NShares = PS.PairSet Address
instance PS.Pair NShare Address where
unview (a:/=:b) = (a,b)
view = uncurry (:/=:)
instance Pretty NShare where pretty (q:/=:r) = int q <> text "/=" <> int r
instance Show NShare where show = show . pretty
data PairSharing =
Sh NShares (F.FactBase F.PFactP) ([F.Facts F.PFactP]) F.PFactP
type Sh i = PState i PairSharing
instance Pretty PairSharing where
pretty sh@(Sh _ _ _ f) =
hsep (map pretty $ nShares' sh) PP.<$>
string ( show f)
instance Show PairSharing where show = show . pretty
liftSh :: (PairSharing -> PairSharing) -> Sh i -> Sh i
liftSh f (PState hp frms sh) = PState hp frms (f sh)
liftSh _ st = st
nShares :: PairSharing -> NShares
nShares (Sh ns _ _ _) = ns
nShares' :: PairSharing -> [NShare]
nShares' = PS.elems . nShares
fact :: PairSharing -> F.PFactP
fact (Sh _ _ _ f) = f
liftNS :: (NShares -> NShares) -> PairSharing -> PairSharing
liftNS g (Sh ns fb fs f) = Sh (g ns) fb fs f
liftNS' :: (NShares -> a) -> PairSharing -> a
liftNS' f = f . nShares
initSh :: P.Program -> P.ClassId -> P.MethodId -> PairSharing
--initSh p cn mn = trace (show (fs,fb)) $ Sh PS.empty fb [fs] (F.unFacts fs A.! 0)
initSh p cn mn = Sh PS.empty fb [fs] (F.unFacts fs A.! 0)
where (fs,fb) = F.analyse (F.pFlowP p) p cn mn
sharing :: Sh i -> PairSharing
sharing (PState _ _ sh) = sh
sharing _ = error "Jat.PState.MemoryModel.PairSharing.sharing: the impossible happened"
-- properties
isAcyclicType :: P.Program -> Sh i -> Address -> Bool
isAcyclicType p st = P.isAcyclicClass p . refKindOf st
acyclicSh :: Sh i -> Address -> Bool
acyclicSh st q = any k (F.acyclicVarsP . fact $ sharing st)
where k x = q `elem` reachableV x st
acyclic :: P.Program -> Sh i -> Address -> Bool
acyclic p st q = isAcyclicType p st q || acyclicSh st q
areSharingTypes :: P.Program -> Sh i -> Address -> Address -> Bool
areSharingTypes p st q r = P.areSharingClasses p (refKindOf st q) (refKindOf st r)
maybeSharesSh :: Sh i -> Address -> Address -> Bool
maybeSharesSh st q r = any pairShares (F.sharingVarsP . fact $ sharing st)
where
pairShares (x,y) =
(q `elem` xReaches && r `elem` yReaches) ||
(q `elem` yReaches && r `elem` xReaches)
where
xReaches = reachableV x st
yReaches = reachableV y st
maybeShares :: P.Program -> Sh i -> Address -> Address -> Bool
maybeShares p st q r = areSharingTypes p st q r && maybeSharesSh st q r
areReachingTypes :: P.Program -> Sh i -> Address -> Address -> Bool
areReachingTypes p st q r = P.areReachingClasses p (refKindOf st q) (refKindOf st r)
maybeReachesSh :: P.Program -> Sh i -> Address -> Address -> Bool
maybeReachesSh p st q r =
any pairReaches (F.reachingVarsP . fact $ sharing st)
&& if q `elem` reachable r (heap st) then not (acyclic p st q) else True -- TODO: is this sound (necessary for flatten example)
where pairReaches (x,y) = q `elem` reachableV x st && r `elem` reachableV y st
maybeReaches :: P.Program -> Sh i -> Address -> Address -> Bool
maybeReaches p st q r = areReachingTypes p st q r && maybeReachesSh p st q r
isValidStateAC :: Sh i -> Bool
isValidStateAC st@(PState hp _ _) = not $ any (acyclicSh st) nonac
where nonac = (`isCyclic` hp) `filter` addresses hp
isValidStateAC _ = True
--maybeSharesV :: P.Program -> Sh i -> P.Var -> P.Var -> Bool
--maybeSharesV p st x y =
--P.areSharingTypes p (typeV x st) (typeV y st) &&
--order (x,y) `elem` (F.sharingVars . fact $ sharing st)
--where order (v,w) = if v <= w then (v,w) else (w,v)
unShare :: P.Program -> [Address] -> [Address] -> Sh i -> Sh i
unShare p qs rs st@(PState hp frms sh) =
PState hp frms (PS.union elements `liftNS` sh)
where
elements = PS.fromList [ q:/=:r | q <- qs, r <- rs, q /= r, related q r ]
related q r = P.areRelatedTypes p (tyOf st q) (tyOf st r)
unShare _ _ _ _ = error "Jat.PState.MemoryModel.PairSharingunShare: the impossible happened"
updateSH :: P.Program -> P.PC -> P.Instruction -> Sh i -> Sh i
updateSH _ _ _ st@(PState _ [] _) = st
updateSH _ _ ins st@(PState hp frms (Sh ns fb (fs:fss) _)) = case ins of
P.Return -> PState hp frms (Sh ns fb fss f1)
_ -> PState hp frms (Sh ns fb (fs:fss) f2)
where
pc = pcounter $ frame st
f1 = F.unFacts (head fss) A.! pc
f2 = F.unFacts fs A.!pc
updateSH _ _ _ st = st
instance MemoryModel PairSharing where
new = newSH
getField = getFieldSH
putField = putFieldSH
invoke = invokeSH
equals = equalsSH
nequals = nequalsSH
initMem = initMemSH
leq = leqSH
lub = joinSH
normalize = normalizeSH
state2TRS = state2TRSSH
update = updateSH
newSH :: (Monad m, IntDomain i) => Sh i -> P.ClassId -> JatM m (PStep(Sh i))
newSH (PState hp (Frame loc stk cn mn pc :frms) sh) newcn = do
p <- getProgram
let obt = mkInstance p newcn
(adr,hp') = insertHA obt hp
stk' = RefVal adr :stk
st1 = PState hp' (Frame loc stk' cn mn (pc+1) :frms) sh
st2 = unShare p [adr] (addresses hp) st1
return $ topEvaluation st2
newSH _ _ = merror ".new: unexpected case."
getFieldSH :: (Monad m, IntDomain i) => Sh i -> P.ClassId -> P.FieldId -> JatM m (PStep(Sh i))
getFieldSH st cn fn = case opstk $ frame st of
Null :_ -> return $ topEvaluation (EState NullPointerException)
RefVal adr : _ -> tryInstanceRefinement st adr |>> return (mkGetField st cn fn)
_ -> error $ mname ++ ".getField: unexpected case."
putFieldSH :: (Monad m, IntDomain i) => Sh i -> P.ClassId -> P.FieldId -> JatM m (PStep(Sh i))
putFieldSH st@PState{} cn fn = case opstk $ frame st of
_ : Null : _ -> return $ topEvaluation (EState NullPointerException)
_ : RefVal adr : _ -> tryInstanceRefinement st adr
|> tryEqualityRefinement st adr
|>> do
stp1 <- mkPutField (sharing st) st cn fn
return $ case stp1 of
Evaluation (st1,con) ->
let st2 = updateSH undefined undefined (P.PutField fn cn) st1 in
if isValidStateAC st2
then Evaluation (normalize st2,con)
else topEvaluation $ EState IllegalStateException
stp -> stp
_ -> merror ".getField: unexpected case."
putFieldSH _ _ _ = error "Jat.PState.MemoryModel.PairSharing.putFieldSH: the impossible happened"
invokeSH :: (Monad m, IntDomain i) => Sh i -> P.MethodId -> Int -> JatM m (PStep(Sh i))
invokeSH st1 mn1 n1 = do
p <- getProgram
invoke' p st1 mn1 n1
where
invoke' p st@(PState hp (Frame loc stk fcn fmn pc :frms) (Sh ns fb fs f)) mn n =
case rv of
Null -> return . topEvaluation $ EState NullPointerException
RefVal q -> tryInstanceRefinement st q
|>> return (topEvaluation $ PState hp (frm:Frame loc stk2 fcn fmn pc:frms) sh')
_ -> merror ".invoke: invalid type on stack"
where
(ps,stk1) = splitAt n stk
([rv],stk2) = splitAt 1 stk1
cn1 = className $ lookupH (theAddress rv) hp
(cn2,mb) = P.seesMethodIn p cn1 mn
mxl = P.maxLoc mb
frm = Frame (initL (rv:reverse ps) mxl) [] cn2 mn 0
fs' = F.queryFB'' (programLocation st) cn2 mn f fb
sh' = Sh ns fb (fs':fs) (F.unFacts fs' A.! 0)
invoke' _ _ _ _ = error ".inoke: exceptional case."
tryInstanceRefinement :: (Monad m, IntDomain i) => Sh i -> Address -> JatM m (Maybe (PStep(Sh i)))
tryInstanceRefinement st@(PState hp _ _) q = case lookupH q hp of
AbsVar _ -> getProgram >>= \p -> Just `liftM` instanceRefinement p st q
Instance _ _ -> return Nothing
tryInstanceRefinement _ _ = merror ".tryInstanceRefinement: exceptional case."
instanceRefinement :: (Monad m, IntDomain i) => P.Program -> Sh i -> Address -> JatM m (PStep(Sh i))
instanceRefinement p st@(PState hp frms sh) adr = do
instances <- instancesM
nullref <- nullM
return . topRefinement $ nullref:instances
where
cns = P.subClassesOf p . className $ lookupH adr hp
obtM = mapM (mkAbsInstance hp adr) cns
instancesM = map mkInstanceM `liftM` obtM
where mkInstanceM (hp1,obt1) = let hp2 = updateH adr obt1 hp1 in PState hp2 frms sh
nullM = return $ substituteSh st
substituteSh st1 = liftNS (PS.delete' adr) `liftSh` substitute (RefVal adr) Null st1
instanceRefinement _ _ _ = error "Jat.PState.MemoryModel.PairSharing.instanceRefinement: the impossible happened"
tryEqualityRefinement :: (Monad m, IntDomain i) => Sh i -> Address -> JatM m (Maybe(PStep(Sh i)))
tryEqualityRefinement st@(PState hp _ _) q = do
p <- getProgram
case find (maybeEqual p st q) (addresses hp) of
Just r -> Just `liftM` equalityRefinement st q r
Nothing -> return Nothing
tryEqualityRefinement _ _ = error "Jat.PState.MemoryModel.PairSharing.tryEqualityRefinement: the impossible happened"
-- rename also TreeShaped q
equalityRefinement :: (Monad m, IntDomain i) => Sh i -> Address -> Address -> JatM m (PStep(Sh i))
equalityRefinement st@(PState hp frms sh) q r = do
p <- getProgram
return . topRefinement $ if isValidStateAC mkEqual && leqSH p mkEqual st then [mkEqual, mkNequal] else [mkNequal]
where
mkEqual = liftNS (PS.renameWithLookup (`lookup` [(r,q)]))`liftSh` substitute (RefVal r) (RefVal q) st
mkNequal = PState hp frms (PS.insert (r:/=:q) `liftNS` sh)
equalityRefinement _ _ _ = error "Jat.PState.MemoryModel.PairSharing.equalityRefinement: the impossible happened"
maybeEqual :: IntDomain i => P.Program -> Sh i -> Address -> Address -> Bool
maybeEqual p st q r =
q/=r &&
not (PS.member (q:/=:r) `liftNS'` sharing st) &&
maybeShares p st q r
equalsSH :: (Monad m, IntDomain i) => Sh i -> JatM m (PStep(Sh i))
equalsSH st@(PState hp (Frame loc (v1:v2:stk) cn mn pc :frms) sh) =
getProgram >>= \p -> equalsx p v1 v2
where
equalsx _ (RefVal q) (RefVal r) | q == r = mkBool True
equalsx _ (RefVal q) (RefVal r) | PS.member (q:/=:r) `liftNS'` sh = mkBool False
equalsx p (RefVal q) (RefVal r) =
if maybeEqual p st q r
then equalityRefinement st q r
else mkBool False
equalsx _ (RefVal q) Null =
tryInstanceRefinement st q |>> mkBool False
equalsx _ Null (RefVal r) =
tryInstanceRefinement st r |>> mkBool False
equalsx _ _ _ = merror ".equals: unexpected case."
mkBool b = return . topEvaluation $ PState hp (Frame loc stk' cn mn (pc+1):frms) sh
where stk' = BoolVal (AD.constant b) : stk
equalsSH _ = merror ".equals: exceptional case."
nequalsSH :: (Monad m, IntDomain i) => Sh i -> JatM m (PStep(Sh i))
nequalsSH st@(PState hp (Frame loc (v1:v2:stk) cn mn pc :frms) sh) =
getProgram >>= \p -> nequalsx p v1 v2
where
nequalsx _ (RefVal q) (RefVal r) | q == r = mkBool False
nequalsx _ (RefVal q) (RefVal r) | PS.member (q:/=:r) `liftNS'` sh = mkBool True
nequalsx p (RefVal q) (RefVal r) =
if maybeEqual p st q r
then equalityRefinement st q r
else mkBool True
nequalsx _ (RefVal q) Null =
tryInstanceRefinement st q |>> mkBool True
nequalsx _ Null (RefVal r) =
tryInstanceRefinement st r |>> mkBool True
nequalsx _ _ _ = merror ".nequals: unexpected case."
mkBool b = return . topEvaluation $ PState hp (Frame loc stk' cn mn (pc+1):frms) sh
where stk' = BoolVal (AD.constant b) : stk
nequalsSH _ = merror ".nequals: exceptional case."
initMemSH :: (Monad m, IntDomain i) => P.ClassId -> P.MethodId -> JatM m (Sh i)
initMemSH cn mn = do
p <- getProgram
let m = P.theMethod p cn mn
(hp1,_) <- mkAbsInstance emptyH 0 cn
(hp2,params) <- foldM defaultAbstrValue (hp1,[]) (P.methodParams m)
let loc = initL (RefVal 0:params) $ P.maxLoc m
as = addresses hp2
st1 = PState hp2 [Frame loc [] cn mn 0] (initSh p cn mn)
st2 = unShare p as as st1
return st2
where
defaultAbstrValue (hp,params) ty = case ty of
P.BoolType -> AD.top >>= \b -> return (hp, params++[BoolVal b])
P.IntType -> AD.top >>= \i -> return (hp, params++[IntVal i])
P.NullType -> return (hp, params++[Null])
P.Void -> return (hp, params++[Unit])
P.RefType cn' -> return (hp',params++[RefVal r])
where (r, hp') = insertHA (AbsVar cn') hp
newtype M i = M {
unMorph :: M.Map (AbstrValue i) (AbstrValue i)
}
type Morph i = State (M i)
emptyMorph :: M i
emptyMorph = M{unMorph=M.empty}
{-withMorph :: (M.Map Address Address -> M.Map Address Address) -> Morph a -> Morph a-}
{-withMorph f = withState (\x -> x{unMorph=f(unMorph x)})-}
modifyMorph :: (M.Map (AbstrValue i) (AbstrValue i) -> M.Map (AbstrValue i) (AbstrValue i)) -> Morph i ()
modifyMorph f = modify $ \x -> x{unMorph=f(unMorph x)}
leqSh1 :: (AbstrValue i -> Maybe (AbstrValue i)) -> PairSharing -> PairSharing -> Bool
leqSh1 lookup' sh1 sh2 =
ns2' `PS.isSubsetOf` nShares sh1
where
ns2' = PS.fold k PS.empty (nShares sh2)
k (q:/=:r) = case (lookup' (RefVal q), lookup' (RefVal r)) of
(Just (RefVal q'), Just (RefVal r')) -> PS.insert (q':/=:r')
_ -> id
-- leqSH tries to find a mapping from addresses/variables to values, performing a 'parallel' preorder traversal, respecting the instance relation
-- difference to definition 5.4:
-- all null values have distinct implicit references in 5.4
-- nevertheless it's fine if (references of) class variables are mapped to multiple null values
-- ie t(cn_1,cn_1) [c_1 -> null] = t(null,null) as desired
leqSH :: IntDomain i => P.Program -> Sh i -> Sh i -> Bool
leqSH p (PState hp1 frms1 sh1) (PState hp2 frms2 sh2) =
let (leqFrms,morph) = runState runFrms emptyMorph in
let b1 = leqFrms
b2 = leqSh1 (flip M.lookup $ unMorph morph) sh1 sh2
in b1 && b2
where
runFrms = and `liftM` zipWithM leqValM (concatMap elemsF frms1) (concatMap elemsF frms2)
{-leqValM :: AbstrValue i -> AbstrValue i -> Morph i Bool-}
leqValM Unit _ = return True
leqValM Null Null = return True
leqValM (BoolVal a) (BoolVal b) | isConstant b = return $ a == b
leqValM (IntVal i) (IntVal j) | isConstant j = return $ i == j
leqValM Null v2@(RefVal r)
| not (isInstance (lookupH r hp2)) = fromMaybe True `liftM` validMapping v2 Null
-- liftM2 is strict in the first component !
leqValM v1@(RefVal q) v2@(RefVal r) = do
bM <- validMapping v2 v1
case bM of
Just b -> return b
Nothing -> leqObjM (lookupH q hp1) (lookupH r hp2)
leqValM v1@(BoolVal a) v2@(BoolVal b) = fromMaybe (a `AD.leq` b) `liftM` validMapping v2 v1
leqValM v1@(IntVal i) v2@(IntVal j) = fromMaybe (i `AD.leq` j) `liftM` validMapping v2 v1
leqValM _ _ = return False
{-validMapping :: AbstrValue i -> AbstrValue i -> Morph i (Maybe Bool)-}
validMapping v2 v1 = do
mapping <- gets unMorph
case M.lookup v2 mapping of
Just v1'-> return $ Just (v1 == v1')
Nothing -> modifyMorph (M.insert v2 v1) >> return Nothing
{-leqObjM :: Object i -> Object i -> Morph i Bool-}
leqObjM (Instance cn ft) (Instance cn' ft') = (cn == cn' &&) `liftM` leqFtM ft ft'
leqObjM (Instance cn _) (AbsVar cn') = return $ P.isSuber p cn cn'
leqObjM (AbsVar cn) (AbsVar cn') = return $ P.isSuber p cn cn'
leqObjM _ _ = return False
{-leqFtM :: FieldTable i -> FieldTable i -> Morph i Bool-}
leqFtM ft ft' = and `liftM` zipWithM leqValM (elemsFT ft) (elemsFT ft')
leqSH _ _ _ = error "Jat.PState.MemoryModel.PairSharing.leqSH: the impossible happened"
-- Todo: take correlation into account
joinSH :: (Monad m, IntDomain i) => Sh i -> Sh i -> JatM m (Sh i)
joinSH st1@(PState _ _ sh1) st2@(PState _ _ sh2) = do
p <- getProgram
~(PState hp frms _, cor) <- mergeStates' p st1 st2 undefined
let ns = joinNS hp cor (nShares sh1) (nShares sh2)
{-let ns = joinNS cor (PS.empty) (PS.empty)-}
{-ns = PS.empty-}
sh = sharing st1
return $ PState hp frms (const ns `liftNS` sh)
where
joinNS hp cor ns1 ns2 = PS.fromList $ do
let
(lk1,lk2) = unzip [ ((r,p),(r,q)) | (C p q, r) <- M.toList cor ]
qs = addresses hp
q1 <- qs
q2 <- qs
guard $ q1 < q2
guard $ maybe False (`PS.member` ns1) ((:/=:) A.<$> lookup q1 lk1 A.<*> lookup q2 lk1)
guard $ maybe False (`PS.member` ns2) ((:/=:) A.<$> lookup q1 lk2 A.<*> lookup q2 lk2)
return $ q1 :/=: q2
joinSH _ _ = error "Jat.PState.MemoryModel.PairSharing.joinSH: the impossible happened"
state2TRSSH :: (Monad m, IntDomain i) => Maybe Address -> Side -> Sh i -> Sh i -> Int -> JatM m PATerm
state2TRSSH m side st1@PState{} st2@PState{} n =
getProgram >>= \p -> pState2TRS (isSpecial p) (maybeReaches' p) m side st2 n
where
{-isSpecial p adr = isCyclic adr hp || isNotTreeShaped adr hp || not (treeShaped p st adr)-}
isSpecial p adr = not (acyclic p st2 adr)
maybeReaches' p q r = case lookupH q (heap st1) of
(AbsVar _) -> maybeReaches p st1 q r
_ -> False
state2TRSSH m side _ st n = pState2TRS undefined undefined m side st n
normalizeSH :: Sh i -> Sh i
normalizeSH (PState hp frms sh) = PState hp' frms (const (PS.filter k $ nShares sh) `liftNS` sh)
where
refsFS = [ r | RefVal r <- concatMap elemsF frms]
hp' = normalizeH refsFS hp
refsH = addresses hp'
k (q:/=:r) = q `elem` refsH && r `elem` refsH
normalizeSH st = st
|
ComputationWithBoundedResources/jat
|
src/Jat/PState/MemoryModel/PairSharing.hs
|
bsd-3-clause
| 18,835 | 0 | 22 | 4,791 | 7,321 | 3,718 | 3,603 | 343 | 14 |
module Hsync where
import Hsync.LCS
import Codec.Utils
import Data.Digest.MD5
import System.FilePath.Posix
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.ByteString.Internal (c2w,w2c)
import System.IO
bs :: Integer
bs = 1024*4 -- 4 kB
-- | return the raw data from a handle @hdl@ from @Offset@ to @Offset + blocksize - 1@
getBlock :: Handle -> Integer -> IO [Octet]
getBlock hdl o = let off = (\e -> minimum [(o*bs), e]) -- begining of block
end = (\e -> minimum [(bs + off e), e]) -- end of block
len = (\e -> end e - off e) in do -- size of block
pos <- hGetPosn hdl
eof <- hFileSize hdl
hSeek hdl AbsoluteSeek (off eof)
bs <- BL.hGet hdl (fromIntegral $ len eof)
hSetPosn pos
return $! map c2w . BL.unpack $ bs
-- | write given block at given offset in-place
writeBlock :: Handle -> Integer -> [Octet] -> IO ()
writeBlock hdl off blk = do
pos <- hGetPosn hdl
hSeek hdl AbsoluteSeek (bs*off)
BL.hPut hdl ( BL.pack $ map w2c blk )
-- | return a list of block hashes for a given file
getBlockHashes :: FilePath -> IO [[Octet]]
getBlockHashes fp = do bl <- getBlockList fp
return $ map hash bl
-- | return a list of blocks for each block in a file @fp@
getBlockList :: FilePath -> IO [[Octet]]
getBlockList fp =
let numBlocks = (\eof -> ceiling $ fromRational $ (fromIntegral eof) / (fromIntegral bs)) in
withFile fp ReadMode (\hdl -> do
eof <- hFileSize hdl
mapM (getBlock hdl) [0..(numBlocks eof - 1)] )
-- Patch-related code
data Patch = Change (Integer,[Octet])
| Delete Integer
| Insert (Integer,[Octet])
instance Show Patch where
show (Change (i,_)) = "Change " ++ show i
show (Delete i) = "Delete " ++ show i
show (Insert (i,_)) = "Insert " ++ show i
-- | patch @fb@ to match @fa@
patch :: FilePath -> FilePath -> IO ()
patch fa fb = do
bla <- getBlockList fa
blb <- getBlockList fb
let bha = map hash bla
bhb = map hash blb
cbs = lcs bha bhb
pb2a = mkPatch cbs bla bha bhb
putStrLn $ "ha: " ++ show bha
putStrLn $ "hb: " ++ show bhb
putStrLn $ "lcs: " ++ show cbs
putStrLn $ "pl: " ++ show pb2a
-- applyPatch pb2a fb
-- | Given the LCS of block lists between two files, and the source
-- files path, generate a patch to convert the destination file to the
-- source.
mkPatch :: [[Octet]] -- ^ LCS of hashes
-> [[Octet]] -- ^ blocks from source
-> [[Octet]] -- ^ hashes from source
-> [[Octet]] -- ^ hashes from dest
-> [Patch] -- ^ returned patch
mkPatch lcs blks hshs hshd = step 0 [] lcs blks hshs hshd
where step :: Integer -- ^ block counter
-> [Patch] -- ^ accumulator list
-> [[Octet]] -- ^ LCS of hashes
-> [[Octet]] -- ^ block list from source file
-> [[Octet]] -- ^ hash list from source file
-> [[Octet]] -- ^ hash list from dest file
-> [Patch] -- ^ returned patch
step _ pl _ [] [] _ = reverse pl -- out of source blocks and hashes, must be done
step _ pl lcs@(c:cs) [] _ _ = error "common element remaining, but blocks exhausted."
step _ pl _ [] hshs@(hs:hss) _ = error "block list exhausted, but source hashes remain."
step i pl [] blks@(b:bs) hshs@(hs:hss) hshd@(hd:hsd) = step (i+1) ((Change (i,b)):pl) [] bs hss hsd
step i pl [] blks hshs [] = (reverse pl) ++ map (\(i,b) -> Insert (i,b)) (zip [i..] blks)
step i pl lcs@(c:cs) blks@(b:bs) hshs@(hs:hss) hshd@(hd:hsd) =
if c == hd && c == hs -- hit common element, skip
then step (i+1) pl cs bs hss hsd
else if c == hd && c /= hs -- found element before common item in d but not c, insert
then step (i+1) ((Insert (i,b)):pl) lcs bs hss hsd
else if c /= hd && c == hs -- found element before common item in c but not d, delete
then step (i+1) ((Delete i):pl) lcs blks hshs hsd
else step (i+1) ((Change (i,b)):pl) lcs bs hss hsd -- before common item in both, change
-- | Apply a patch to a file. Write to copy of file and then
-- (atomically) update the file with rename.
applyPatch :: [Patch] -> FilePath -> IO ()
applyPatch = undefined
|
mee/hsync
|
Hsync.hs
|
bsd-3-clause
| 4,446 | 0 | 16 | 1,365 | 1,504 | 802 | 702 | 81 | 9 |
module Vehicles where
import Data.Int
data Price = Price Integer deriving (Eq, Show)
data Manufacturer = Mini
| Mazda
| Tata
deriving (Eq, Show)
data Airline = PapuAir
| CatapultsR'Us
| TakeYourChancesUnited
deriving (Eq, Show)
data Vehicle = Car Manufacturer Price
| Plane Airline
deriving (Eq, Show)
myCar = Car Mini (Price 14000)
urCar = Car Mazda (Price 20000)
clownCar = Car Tata (Price 7000)
doge = Plane PapuAir
isCar :: Vehicle -> Bool
isCar (Car _ _) = True
isCar _ = False
isPlane :: Vehicle -> Bool
isPlane (Plane _) = True
isPlane _ = False
areCars :: [Vehicle] -> [Bool]
areCars = map isCar
cardinalityInt16 = (abs $ fromEnum (minBound :: Int16)) + (fromEnum (maxBound :: Int16)) + 1
|
dsaenztagarro/haskellbook
|
src/chapter11/Vehicles.hs
|
bsd-3-clause
| 826 | 0 | 10 | 251 | 288 | 157 | 131 | 27 | 1 |
{-|
Description: High-level SDL state.
Provides SDL state which can be advanced given recent queue of events.
-}
module Graphics.UI.SDL.State
( module Types
, module Lens
, module Advance
) where
import Graphics.UI.SDL.State.Types as Types
import Graphics.UI.SDL.State.Lens as Lens
import Graphics.UI.SDL.State.Advance as Advance
|
abbradar/MySDL
|
src/Graphics/UI/SDL/State.hs
|
bsd-3-clause
| 360 | 0 | 4 | 73 | 53 | 41 | 12 | 7 | 0 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.SGIS.TextureEdgeClamp
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/SGIS/texture_edge_clamp.txt SGIS_texture_edge_clamp> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.SGIS.TextureEdgeClamp (
-- * Enums
gl_CLAMP_TO_EDGE_SGIS
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/SGIS/TextureEdgeClamp.hs
|
bsd-3-clause
| 672 | 0 | 4 | 78 | 37 | 31 | 6 | 3 | 0 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
-- | Text frontend based on Gtk.
module Game.LambdaHack.Client.UI.Frontend.Gtk
( -- * Session data type for the frontend
FrontendSession(sescMVar)
-- * The output and input operations
, fdisplay, fpromptGetKey, fsyncFrames
-- * Frontend administration tools
, frontendName, startup
) where
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.Async
import qualified Control.Concurrent.STM as STM
import qualified Control.Exception as Ex hiding (handle)
import Control.Monad
import Control.Monad.Reader
import qualified Data.ByteString.Char8 as BS
import Data.IORef
import Data.List
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.String (IsString (..))
import qualified Data.Text as T
import Graphics.UI.Gtk hiding (Point)
import System.Time
import qualified Game.LambdaHack.Client.Key as K
import Game.LambdaHack.Client.UI.Animation
import Game.LambdaHack.Common.ClientOptions
import qualified Game.LambdaHack.Common.Color as Color
import Game.LambdaHack.Common.LQueue
import Game.LambdaHack.Common.Point
data FrameState =
FPushed -- frames stored in a queue, to be drawn in equal time intervals
{ fpushed :: !(LQueue (Maybe GtkFrame)) -- ^ screen output channel
, fshown :: !GtkFrame -- ^ last full frame shown
}
| FNone -- no frames stored
-- | Session data maintained by the frontend.
data FrontendSession = FrontendSession
{ sview :: !TextView -- ^ the widget to draw to
, stags :: !(M.Map Color.Attr TextTag) -- ^ text color tags for fg/bg
, schanKey :: !(STM.TQueue K.KM) -- ^ channel for keyboard input
, sframeState :: !(MVar FrameState)
-- ^ State of the frame finite machine. This mvar is locked
-- for a short time only, because it's needed, among others,
-- to display frames, which is done by a single polling thread,
-- in real time.
, slastFull :: !(MVar (GtkFrame, Bool))
-- ^ Most recent full (not empty, not repeated) frame received
-- and if any empty frame followed it. This mvar is locked
-- for longer intervals to ensure that threads (possibly many)
-- add frames in an orderly manner. This is not done in real time,
-- though sometimes the frame display subsystem has to poll
-- for a frame, in which case the locking interval becomes meaningful.
, sescMVar :: !(Maybe (MVar ()))
, sdebugCli :: !DebugModeCli -- ^ client configuration
}
data GtkFrame = GtkFrame
{ gfChar :: !BS.ByteString
, gfAttr :: ![[TextTag]]
}
deriving Eq
dummyFrame :: GtkFrame
dummyFrame = GtkFrame BS.empty []
-- | Perform an operation on the frame queue.
onQueue :: (LQueue (Maybe GtkFrame) -> LQueue (Maybe GtkFrame))
-> FrontendSession -> IO ()
onQueue f FrontendSession{sframeState} = do
fs <- takeMVar sframeState
case fs of
FPushed{..} ->
putMVar sframeState FPushed{fpushed = f fpushed, ..}
FNone ->
putMVar sframeState fs
-- | The name of the frontend.
frontendName :: String
frontendName = "gtk"
-- | Starts GTK. The other threads have to be spawned
-- after gtk is initialized, because they call @postGUIAsync@,
-- and need @sview@ and @stags@. Because of Windows, GTK needs to be
-- on a bound thread, so we can't avoid the communication overhead
-- of bound threads, so there's no point spawning a separate thread for GTK.
startup :: DebugModeCli -> (FrontendSession -> IO ()) -> IO ()
startup = runGtk
-- | Sets up and starts the main GTK loop providing input and output.
runGtk :: DebugModeCli -> (FrontendSession -> IO ()) -> IO ()
runGtk sdebugCli@DebugModeCli{sfont} cont = do
-- Init GUI.
unsafeInitGUIForThreadedRTS
-- Text attributes.
ttt <- textTagTableNew
stags <- M.fromList <$>
mapM (\ ak -> do
tt <- textTagNew Nothing
textTagTableAdd ttt tt
doAttr sdebugCli tt ak
return (ak, tt))
[ Color.Attr{fg, bg}
| fg <- [minBound..maxBound], bg <- Color.legalBG ]
-- Text buffer.
tb <- textBufferNew (Just ttt)
-- Create text view. TODO: use GtkLayout or DrawingArea instead of TextView?
sview <- textViewNewWithBuffer tb
textViewSetEditable sview False
textViewSetCursorVisible sview False
-- Set up the channel for keyboard input.
schanKey <- STM.atomically STM.newTQueue
-- Set up the frame state.
let frameState = FNone
-- Create the session record.
sframeState <- newMVar frameState
slastFull <- newMVar (dummyFrame, False)
escMVar <- newEmptyMVar
let sess = FrontendSession{sescMVar = Just escMVar, ..}
-- Fork the game logic thread. When logic ends, game exits.
-- TODO: is postGUISync needed here?
aCont <- async $ cont sess `Ex.finally` postGUISync mainQuit
link aCont
-- Fork the thread that periodically draws a frame from a queue, if any.
-- TODO: mainQuit somehow never called.
aPoll <- async $ pollFramesAct sess `Ex.finally` postGUISync mainQuit
link aPoll
let flushChanKey = do
res <- STM.atomically $ STM.tryReadTQueue schanKey
when (isJust res) flushChanKey
-- Fill the keyboard channel.
sview `on` keyPressEvent $ do
n <- eventKeyName
mods <- eventModifier
#if MIN_VERSION_gtk(0,13,0)
let !key = K.keyTranslate $ T.unpack n
#else
let !key = K.keyTranslate n
#endif
!modifier = let md = modifierTranslate mods
in if md == K.Shift then K.NoModifier else md
!pointer = Nothing
liftIO $ do
unless (deadKey n) $ do
-- If ESC, also mark it specially and reset the key channel.
when (key == K.Esc) $ do
void $ tryPutMVar escMVar ()
flushChanKey
-- Store the key in the channel.
STM.atomically $ STM.writeTQueue schanKey K.KM{..}
return True
-- Set the font specified in config, if any.
f <- fontDescriptionFromString $ fromMaybe "" sfont
widgetModifyFont sview (Just f)
liftIO $ do
textViewSetLeftMargin sview 3
textViewSetRightMargin sview 3
-- Prepare font chooser dialog.
currentfont <- newIORef f
Just display <- displayGetDefault
-- TODO: change cursor depending on targeting mode, etc.; hard
cursor <- cursorNewForDisplay display Tcross -- Target Crosshair Arrow
sview `on` buttonPressEvent $ do
liftIO flushChanKey
but <- eventButton
(wx, wy) <- eventCoordinates
mods <- eventModifier
let !modifier = modifierTranslate mods -- Shift included
liftIO $ do
when (but == RightButton && modifier == K.Control) $ do
fsd <- fontSelectionDialogNew ("Choose font" :: String)
cf <- readIORef currentfont
fds <- fontDescriptionToString cf
fontSelectionDialogSetFontName fsd (fds :: String)
fontSelectionDialogSetPreviewText fsd ("eee...@.##+##" :: String)
resp <- dialogRun fsd
when (resp == ResponseOk) $ do
fn <- fontSelectionDialogGetFontName fsd
case fn :: Maybe String of
Just fn' -> do
fd <- fontDescriptionFromString fn'
writeIORef currentfont fd
widgetModifyFont sview (Just fd)
Nothing -> return ()
widgetDestroy fsd
-- We shouldn't pass on the click if the user has selected something.
hasSelection <- textBufferHasSelection tb
unless hasSelection $ do
mdrawWin <- displayGetWindowAtPointer display
let setCursor (drawWin, _, _) =
drawWindowSetCursor drawWin (Just cursor)
maybe (return ()) setCursor mdrawWin
(bx, by) <-
textViewWindowToBufferCoords sview TextWindowText
(round wx, round wy)
(iter, _) <- textViewGetIterAtPosition sview bx by
cx <- textIterGetLineOffset iter
cy <- textIterGetLine iter
let !key = case but of
LeftButton -> K.LeftButtonPress
MiddleButton -> K.MiddleButtonPress
RightButton -> K.RightButtonPress
_ -> K.LeftButtonPress
!pointer = Just $! Point cx (cy - 1)
-- Store the mouse even coords in the keypress channel.
STM.atomically $ STM.writeTQueue schanKey K.KM{..}
return $! but == RightButton -- not to disable selection
-- Modify default colours.
let black = Color minBound minBound minBound -- Color.defBG == Color.Black
white = Color 0xC500 0xBC00 0xB800 -- Color.defFG == Color.White
widgetModifyBase sview StateNormal black
widgetModifyText sview StateNormal white
-- Set up the main window.
w <- windowNew
containerAdd w sview
onDestroy w mainQuit
widgetShowAll w
mainGUI
-- | Output to the screen via the frontend.
output :: FrontendSession -- ^ frontend session data
-> GtkFrame -- ^ the screen frame to draw
-> IO ()
output FrontendSession{sview, stags} GtkFrame{..} = do -- new frame
tb <- textViewGetBuffer sview
let attrs = zip [0..] gfAttr
defAttr = stags M.! Color.defAttr
textBufferSetByteString tb gfChar
mapM_ (setTo tb defAttr 0) attrs
setTo :: TextBuffer -> TextTag -> Int -> (Int, [TextTag]) -> IO ()
setTo _ _ _ (_, []) = return ()
setTo tb defAttr lx (ly, attr:attrs) = do
ib <- textBufferGetIterAtLineOffset tb ly lx
ie <- textIterCopy ib
let setIter :: TextTag -> Int -> [TextTag] -> IO ()
setIter previous repetitions [] = do
textIterForwardChars ie repetitions
when (previous /= defAttr) $
textBufferApplyTag tb previous ib ie
setIter previous repetitions (a:as)
| a == previous =
setIter a (repetitions + 1) as
| otherwise = do
textIterForwardChars ie repetitions
when (previous /= defAttr) $
textBufferApplyTag tb previous ib ie
textIterForwardChars ib repetitions
setIter a 1 as
setIter attr 1 attrs
-- | Maximal polls per second.
maxPolls :: Int -> Int
maxPolls maxFps = max 120 (2 * maxFps)
picoInMicro :: Int
picoInMicro = 1000000
-- | Add a given number of microseconds to time.
addTime :: ClockTime -> Int -> ClockTime
addTime (TOD s p) mus = TOD s (p + fromIntegral (mus * picoInMicro))
-- | The difference between the first and the second time, in microseconds.
diffTime :: ClockTime -> ClockTime -> Int
diffTime (TOD s1 p1) (TOD s2 p2) =
fromIntegral (s1 - s2) * picoInMicro +
fromIntegral (p1 - p2) `div` picoInMicro
microInSec :: Int
microInSec = 1000000
defaultMaxFps :: Int
defaultMaxFps = 30
-- | Poll the frame queue often and draw frames at fixed intervals.
pollFramesWait :: FrontendSession -> ClockTime -> IO ()
pollFramesWait sess@FrontendSession{sdebugCli=DebugModeCli{smaxFps}}
setTime = do
-- Check if the time is up.
let maxFps = fromMaybe defaultMaxFps smaxFps
curTime <- getClockTime
let diffSetCur = diffTime setTime curTime
if diffSetCur > microInSec `div` maxPolls maxFps
then do
-- Delay half of the time difference.
threadDelay $ diffTime curTime setTime `div` 2
pollFramesWait sess setTime
else
-- Don't delay, because time is up!
pollFramesAct sess
-- | Poll the frame queue often and draw frames at fixed intervals.
pollFramesAct :: FrontendSession -> IO ()
pollFramesAct sess@FrontendSession{sframeState, sdebugCli=DebugModeCli{..}} = do
-- Time is up, check if we actually wait for anyting.
let maxFps = fromMaybe defaultMaxFps smaxFps
fs <- takeMVar sframeState
case fs of
FPushed{..} ->
case tryReadLQueue fpushed of
Just (Just frame, queue) -> do
-- The frame has arrived so send it for drawing and update delay.
putMVar sframeState FPushed{fpushed = queue, fshown = frame}
-- Count the time spent outputting towards the total frame time.
curTime <- getClockTime
-- Wait until the frame is drawn.
postGUISync $ output sess frame
-- Regardless of how much time drawing took, wait at least
-- half of the normal delay time. This can distort the large-scale
-- frame rhythm, but makes sure this frame can at all be seen.
-- If the main GTK thread doesn't lag, large-scale rhythm will be OK.
-- TODO: anyway, it's GC that causes visible snags, most probably.
threadDelay $ microInSec `div` (maxFps * 2)
pollFramesWait sess $ addTime curTime $ microInSec `div` maxFps
Just (Nothing, queue) -> do
-- Delay requested via an empty frame.
putMVar sframeState FPushed{fpushed = queue, ..}
unless snoDelay $
-- There is no problem if the delay is a bit delayed.
threadDelay $ microInSec `div` maxFps
pollFramesAct sess
Nothing -> do
-- The queue is empty, the game logic thread lags.
putMVar sframeState fs
-- Time is up, the game thread is going to send a frame,
-- (otherwise it would change the state), so poll often.
threadDelay $ microInSec `div` maxPolls maxFps
pollFramesAct sess
FNone -> do
putMVar sframeState fs
-- Not in the Push state, so poll lazily to catch the next state change.
-- The slow polling also gives the game logic a head start
-- in creating frames in case one of the further frames is slow
-- to generate and would normally cause a jerky delay in drawing.
threadDelay $ microInSec `div` (maxFps * 2)
pollFramesAct sess
-- | Add a game screen frame to the frame drawing channel, or show
-- it ASAP if @immediate@ display is requested and the channel is empty.
pushFrame :: FrontendSession -> Bool -> Maybe SingleFrame -> IO ()
pushFrame sess immediate rawFrame = do
let FrontendSession{sframeState, slastFull} = sess
-- Full evaluation is done outside the mvar locks.
let !frame = case rawFrame of
Nothing -> Nothing
Just fr -> Just $! evalFrame sess fr
-- Lock frame addition.
(lastFrame, anyFollowed) <- takeMVar slastFull
-- Comparison of frames is done outside the frame queue mvar lock.
let nextFrame = if frame == Just lastFrame
then Nothing -- no sense repeating
else frame
-- Lock frame queue.
fs <- takeMVar sframeState
case fs of
FPushed{..} ->
putMVar sframeState
$ if isNothing nextFrame && anyFollowed && isJust rawFrame
then fs -- old news
else FPushed{fpushed = writeLQueue fpushed nextFrame, ..}
FNone | immediate -> do
-- If the frame not repeated, draw it.
maybe (return ()) (postGUIAsync . output sess) nextFrame
-- Frame sent, we may now safely release the queue lock.
putMVar sframeState FNone
FNone ->
putMVar sframeState
$ if isNothing nextFrame && anyFollowed && isJust rawFrame
then fs -- old news
else FPushed{ fpushed = writeLQueue newLQueue nextFrame
, fshown = dummyFrame }
case nextFrame of
Nothing -> putMVar slastFull (lastFrame, not (case fs of
FNone -> True
FPushed{} -> False
&& immediate
&& not anyFollowed))
Just f -> putMVar slastFull (f, False)
evalFrame :: FrontendSession -> SingleFrame -> GtkFrame
evalFrame FrontendSession{stags} rawSF =
let SingleFrame{sfLevel} = overlayOverlay rawSF
sfLevelDecoded = map decodeLine sfLevel
levelChar = unlines $ map (map Color.acChar) sfLevelDecoded
gfChar = BS.pack $ init levelChar
-- Strict version of @map (map ((stags M.!) . fst)) sfLevelDecoded@.
gfAttr = reverse $ foldl' ff [] sfLevelDecoded
ff ll l = reverse (foldl' f [] l) : ll
f l ac = let !tag = stags M.! Color.acAttr ac in tag : l
in GtkFrame{..}
-- | Trim current frame queue and display the most recent frame, if any.
trimFrameState :: FrontendSession -> IO ()
trimFrameState sess@FrontendSession{sframeState} = do
-- Take the lock to wipe out the frame queue, unless it's empty already.
fs <- takeMVar sframeState
case fs of
FPushed{..} ->
-- Remove all but the last element of the frame queue.
-- The kept (and displayed) last element ensures that
-- @slastFull@ is not invalidated.
case lastLQueue fpushed of
Just frame -> do
-- Comparison is done inside the mvar lock, this time, but it's OK,
-- since we wipe out the queue anyway, not draw it concurrently.
-- The comparison is very rarely true, because that means
-- the screen looks the same as a few moves before.
-- Still, we want the invariant that frames are never repeated.
let lastFrame = fshown
nextFrame = if frame == lastFrame
then Nothing -- no sense repeating
else Just frame
-- Draw the last frame ASAP.
maybe (return ()) (postGUIAsync . output sess) nextFrame
Nothing -> return ()
FNone -> return ()
-- Wipe out the frame queue. Release the lock.
putMVar sframeState FNone
-- | Add a frame to be drawn.
fdisplay :: FrontendSession -- ^ frontend session data
-> Maybe SingleFrame -- ^ the screen frame to draw
-> IO ()
fdisplay sess = pushFrame sess False
-- Display all queued frames, synchronously.
displayAllFramesSync :: FrontendSession -> FrameState -> IO ()
displayAllFramesSync sess@FrontendSession{sdebugCli=DebugModeCli{..}, sescMVar}
fs = do
escPressed <- case sescMVar of
Nothing -> return False
Just escMVar -> not <$> isEmptyMVar escMVar
let maxFps = fromMaybe defaultMaxFps smaxFps
case fs of
_ | escPressed -> return ()
FPushed{..} ->
case tryReadLQueue fpushed of
Just (Just frame, queue) -> do
-- Display synchronously.
postGUISync $ output sess frame
threadDelay $ microInSec `div` maxFps
displayAllFramesSync sess FPushed{fpushed = queue, fshown = frame}
Just (Nothing, queue) -> do
-- Delay requested via an empty frame.
unless snoDelay $
threadDelay $ microInSec `div` maxFps
displayAllFramesSync sess FPushed{fpushed = queue, ..}
Nothing ->
-- The queue is empty.
return ()
FNone ->
-- Not in Push state to start with.
return ()
fsyncFrames :: FrontendSession -> IO ()
fsyncFrames sess@FrontendSession{sframeState} = do
fs <- takeMVar sframeState
displayAllFramesSync sess fs
putMVar sframeState FNone
-- | Display a prompt, wait for any key.
-- Starts in Push mode, ends in Push or None mode.
-- Syncs with the drawing threads by showing the last or all queued frames.
fpromptGetKey :: FrontendSession -> SingleFrame -> IO K.KM
fpromptGetKey sess@FrontendSession{..}
frame = do
pushFrame sess True $ Just frame
km <- STM.atomically $ STM.readTQueue schanKey
case km of
K.KM{key=K.Space} ->
-- Drop frames up to the first empty frame.
-- Keep the last non-empty frame, if any.
-- Pressing SPACE repeatedly can be used to step
-- through intermediate stages of an animation,
-- whereas any other key skips the whole animation outright.
onQueue dropStartLQueue sess
_ ->
-- Show the last non-empty frame and empty the queue.
trimFrameState sess
return km
-- | Tells a dead key.
deadKey :: (Eq t, IsString t) => t -> Bool
deadKey x = case x of
"Shift_L" -> True
"Shift_R" -> True
"Control_L" -> True
"Control_R" -> True
"Super_L" -> True
"Super_R" -> True
"Menu" -> True
"Alt_L" -> True
"Alt_R" -> True
"ISO_Level2_Shift" -> True
"ISO_Level3_Shift" -> True
"ISO_Level2_Latch" -> True
"ISO_Level3_Latch" -> True
"Num_Lock" -> True
"Caps_Lock" -> True
_ -> False
-- | Translates modifiers to our own encoding.
modifierTranslate :: [Modifier] -> K.Modifier
modifierTranslate mods
| Control `elem` mods = K.Control
| any (`elem` mods) [Meta, Super, Alt, Alt2, Alt3, Alt4, Alt5] = K.Alt
| Shift `elem` mods = K.Shift
| otherwise = K.NoModifier
doAttr :: DebugModeCli -> TextTag -> Color.Attr -> IO ()
doAttr sdebugCli tt [email protected]{fg, bg}
| attr == Color.defAttr = return ()
| fg == Color.defFG =
set tt $ extraAttr sdebugCli
++ [textTagBackground := Color.colorToRGB bg]
| bg == Color.defBG =
set tt $ extraAttr sdebugCli
++ [textTagForeground := Color.colorToRGB fg]
| otherwise =
set tt $ extraAttr sdebugCli
++ [ textTagForeground := Color.colorToRGB fg
, textTagBackground := Color.colorToRGB bg ]
extraAttr :: DebugModeCli -> [AttrOp TextTag]
extraAttr DebugModeCli{scolorIsBold} =
[textTagWeight := fromEnum WeightBold | scolorIsBold == Just True]
-- , textTagStretch := StretchUltraExpanded
|
Concomitant/LambdaHack
|
Game/LambdaHack/Client/UI/Frontend/Gtk.hs
|
bsd-3-clause
| 21,242 | 0 | 26 | 5,746 | 4,737 | 2,394 | 2,343 | -1 | -1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ordinal.RO.Corpus
( corpus ) where
import Prelude
import Data.String
import Duckling.Locale
import Duckling.Ordinal.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale RO Nothing}, testOptions, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (OrdinalData 1)
[ "primul"
, "prima"
]
, examples (OrdinalData 2)
[ "al doilea"
, "al doi-lea"
, "al doi lea"
, "al 2-lea"
, "al 2 lea"
, "a 2 a"
, "a 2-a"
, "a doua"
]
, examples (OrdinalData 3)
[ "al treilea"
, "al trei-lea"
, "a treia"
, "a 3-lea"
, "a 3a"
]
, examples (OrdinalData 4)
[ "a patra"
, "a patru-lea"
]
, examples (OrdinalData 6)
[ "al saselea"
, "al șaselea"
, "al sase-lea"
, "al șase-lea"
, "a sasea"
, "a șase a"
]
, examples (OrdinalData 9)
[ "al noualea"
, "al noua-lea"
, "al noua lea"
, "al nouălea"
, "al nouă lea"
, "a noua"
]
]
|
facebookincubator/duckling
|
Duckling/Ordinal/RO/Corpus.hs
|
bsd-3-clause
| 1,626 | 0 | 9 | 676 | 268 | 162 | 106 | 48 | 1 |
{-# LANGUAGE UnicodeSyntax #-}
module Shake.It.Global
( phonyArgs
, phonyActions
, objects
, objectsList
) where
import System.IO.Unsafe
import Data.IORef
phonyArgs ∷ IORef [String]
{-# NOINLINE phonyArgs #-}
phonyArgs = unsafePerformIO (newIORef [])
phonyActions ∷ IORef [(String, IO (), String)]
{-# NOINLINE phonyActions #-}
phonyActions = unsafePerformIO (newIORef [])
objects ∷ IORef [(String, IO ())]
{-# NOINLINE objects #-}
objects = unsafePerformIO (newIORef [])
objectsList ∷ IORef [String]
{-# NOINLINE objectsList #-}
objectsList = unsafePerformIO (newIORef [])
|
Heather/Shake.it.off
|
src/Shake/It/Global.hs
|
bsd-3-clause
| 619 | 0 | 9 | 114 | 170 | 96 | 74 | 20 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Temperature.PT.Corpus
( corpus ) where
import Prelude
import Data.String
import Duckling.Lang
import Duckling.Resolve
import Duckling.Temperature.Types
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {lang = PT}, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (TemperatureValue Celsius 37)
[ "37°C"
, "37 ° celsius"
, "37 graus Celsius"
, "37 graus C"
, "trinta e sete celsius"
, "37 centígrados"
, "37 graus centigrados"
]
, examples (TemperatureValue Fahrenheit 70)
[ "70°F"
, "70 ° Fahrenheit"
, "70 graus F"
, "setenta Fahrenheit"
]
, examples (TemperatureValue Degree 45)
[ "45°"
, "45 graus"
]
, examples (TemperatureValue Degree (-10))
[ "-10°"
, "- dez graus"
, "10 abaixo de zero"
]
]
|
rfranek/duckling
|
Duckling/Temperature/PT/Corpus.hs
|
bsd-3-clause
| 1,376 | 0 | 11 | 450 | 207 | 126 | 81 | 33 | 1 |
import qualified Data.Map as Map
import Data.Char
import System.Environment
import System.Directory
import System.FilePath
import Data.List
import Text.Show.Pretty
main = listAll
getPings =
do xs <- getDirectoryContents "."
return (filter ((== ".png") . takeExtension) xs)
listAll =
do xs <- getPings
putStrLn $ ppShow $ map head $ group $ sort $ map getName xs
getName xs =
case break (== '_') (reverse xs) of
(as,_:bs) -> reverse bs
(_,[]) -> error xs
renAll = mapM_ (\f -> renameFile f (ren f)) =<< getPings
ren = cvt1
where
cvt1 (x : xs) = toLower x : cvt2 xs
cvt1 [] = []
cvt2 (x : xs) | isUpper x = '_' : toLower x : cvt2 xs
cvt2 (x : xs) = x : cvt2 xs
cvt2 [] = []
|
GaloisInc/verification-game
|
web-prover/web_src/img/creatures/fixCreatures.hs
|
bsd-3-clause
| 754 | 0 | 12 | 211 | 338 | 173 | 165 | 25 | 4 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Unsafe #-}
-- | It provides functions which map read and write effects into security checks.
module MAC.Effects
(
create
, writeup
, readdown
, fix
, read_and_fix
, write_and_fix
, rw_read
, rw_write
)
where
import MAC.Lattice
import MAC.Core
{-|
It lifts functions which create resources into secure functions which
create labeled resources
-}
create :: Less l l' => IO (d a) -> MAC l (Res l' (d a))
create io = ioTCB io >>= return . MkRes
{-|
It lifts an 'IO'-action which writes into a data type @d a@
into a secure function which writes into a labeled resource
-}
writeup :: Less l l' => (d a -> IO ()) -> Res l' (d a) -> MAC l ()
writeup io (MkRes a) = ioTCB $ io a
{-|
It lifts an 'IO'-action which reads from a data type @d a@
into a secure function which reads from a labeled resource
-}
readdown :: Less l' l => (d a -> IO a) -> Res l' (d a) -> MAC l a
readdown io (MkRes da) = ioTCB $ io da
-- | Proxy function to set the index of the family member 'MAC'
fix :: l -> MAC l ()
fix _ = return ()
-- | Auxiliary function. A combination of 'fix' and 'readdown'.
read_and_fix :: Less l l => (d a -> IO a) -> Res l (d a) -> MAC l a
read_and_fix io r = fix (labelOf r) >> readdown io r
-- | Auxiliary function. A combination of 'fix' and 'readdown'.
write_and_fix :: Less l' l' => (d a -> IO ()) -> Res l' (d a) -> MAC l' ()
write_and_fix io r = fix (labelOf r) >> writeup io r
{-|
It lifts an operation which perform a read on data type @d a@, but
it also performs a write on it as side-effect
-}
rw_read :: (Less l l', Less l' l) => (d a -> IO a) -> Res l' (d a) -> MAC l a
rw_read io r = writeup (\_ -> return ()) r >> readdown io r
{-|
It lifts an operation which perform a write on data type @d a@, but
it also performs a read on it as side-effect
-}
rw_write :: (Less l l', Less l' l) => (d a -> IO ()) -> Res l' (d a) -> MAC l ()
rw_write io r = readdown (\_ -> return undefined) r >> writeup io r
|
alejandrorusso/mac-privacy
|
MAC/Effects.hs
|
bsd-3-clause
| 2,060 | 0 | 11 | 525 | 659 | 328 | 331 | 30 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE UnicodeSyntax #-}
{-|
[@ISO639-1@] ht
[@ISO639-2@] hat
[@ISO639-3@] hat
[@Native name@] -
[@English name@] Haitian Creole
-}
module Text.Numeral.Language.HAT.TestData (cardinals) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "base" Prelude ( Num )
import "numerals" Text.Numeral.Grammar.Reified ( defaultInflection )
import "this" Text.Numeral.Test ( TestData )
--------------------------------------------------------------------------------
-- Test data
--------------------------------------------------------------------------------
{-
Sources:
http://www.languagesandnumbers.com/how-to-count-in-haitian-creole/en/hat/
-}
cardinals ∷ (Num i) ⇒ TestData i
cardinals =
[ ( "default"
, defaultInflection
, [ (0, "zero")
, (1, "youn")
, (2, "de")
, (3, "twa")
, (4, "kat")
, (5, "senk")
, (6, "sis")
, (7, "sèt")
, (8, "uit")
, (9, "nèf")
, (10, "dis")
, (11, "onz")
, (12, "douz")
, (13, "trèz")
, (14, "katòz")
, (15, "kenz")
, (16, "sèz")
, (17, "disèt")
, (18, "dizuit")
, (19, "diznèf")
, (20, "ven")
, (21, "venteyen")
, (22, "vennde")
, (23, "venntwa")
, (24, "vennkat")
, (25, "vennsenk")
, (26, "vennsis")
, (27, "vennsèt")
, (28, "ventuit")
, (29, "ventnèf")
, (30, "trant")
, (31, "tranteyen")
, (32, "trannde")
, (33, "tranntwa")
, (34, "trannkat")
, (35, "trannsenk")
, (36, "trannsis")
, (37, "trannsèt")
, (38, "trantuit")
, (39, "trantnèf")
, (40, "karant")
, (41, "karanteyen")
, (42, "karannde")
, (43, "karanntwa")
, (44, "karannkat")
, (45, "karannsenk")
, (46, "karannsis")
, (47, "karannsèt")
, (48, "karantuit")
, (49, "karantnèf")
, (50, "senkant")
, (51, "senkanteyen")
, (52, "senkannde")
, (53, "senkanntwa")
, (54, "senkannkat")
, (55, "senkannsenk")
, (56, "senkannsis")
, (57, "senkannsèt")
, (58, "senkantuit")
, (59, "senkantnèf")
, (60, "swasann")
, (61, "swasannyoun")
, (62, "swasannde")
, (63, "swasanntwa")
, (64, "swasannkat")
, (65, "swasannsenk")
, (66, "swasannsis")
, (67, "swasannsèt")
, (68, "swasannuit")
, (69, "swasannnèf")
, (70, "swasanndis")
, (71, "swasannonz")
, (72, "swasanndisde")
, (73, "swasanntrèz")
, (74, "swasannkatòz")
, (75, "swasannkenz")
, (76, "swasannsèz")
, (77, "swasanndissèt")
, (78, "swasanndizuit")
, (79, "swasanndiznèf")
, (80, "katreven")
, (81, "katreventeyen")
, (82, "katrevennde")
, (83, "katrevenntwa")
, (84, "katrevennkat")
, (85, "katrevennsenk")
, (86, "katrevennsis")
, (87, "katrevennsèt")
, (88, "katreventuit")
, (89, "katreventnèf")
, (90, "katrevendis")
, (91, "katrevenonz")
, (92, "katrevendisde")
, (93, "katreventrèz")
, (94, "katrevenkatòz")
, (95, "katrevenkenz")
, (96, "katrevensèz")
, (97, "katrevendissèt")
, (98, "katrevendizuit")
, (99, "katrevendiznèf")
, (100, "san")
, (101, "san en")
, (102, "san de")
, (103, "san twa")
, (104, "san kat")
, (105, "san senk")
, (106, "san sis")
, (107, "san sèt")
, (108, "san uit")
, (109, "san nèf")
, (110, "san dis")
, (123, "san venntwa")
, (200, "de san")
, (300, "twa san")
, (321, "twa san venteyen")
, (400, "kat san")
, (500, "sen san")
, (600, "si san")
, (700, "sèt san")
, (800, "ui san")
, (900, "nèf san")
, (909, "nèf san nèf")
, (990, "nèf san katrevendis")
, (999, "nèf san katrevendiznèf")
, (1000, "mil")
, (1001, "mil youn")
, (1008, "mil uit")
, (1234, "mil de san trannkat")
, (2000, "de mil")
, (3000, "twa mil")
, (4000, "kat mil")
, (4321, "kat mil twa san venteyen")
, (5000, "senk mil")
, (6000, "sis mil")
, (7000, "sèt mil")
, (8000, "uit mil")
, (9000, "nèf mil")
, (10000, "di mil")
, (12345, "douz mil twa san karannsenk")
, (20000, "ven mil")
, (30000, "trant mil")
, (40000, "karant mil")
, (50000, "senkant mil")
, (54321, "senkannkat mil twa san venteyen")
, (60000, "swasann mil")
, (70000, "swasanndi mil")
, (80000, "katreven mil")
, (90000, "katrevendi mil")
, (100000, "san mil")
, (123456, "san venntwa mil kat san senkannsis")
, (200000, "de san mil")
, (300000, "twa san mil")
, (400000, "kat san mil")
, (500000, "sen san mil")
, (600000, "si san mil")
, (654321, "si san senkannkat mil twa san venteyen")
, (700000, "sèt san mil")
, (800000, "ui san mil")
, (900000, "nèf san mil")
, (1000000, "yon milyon")
, (1000001, "yon milyon youn")
, (1234567, "yon milyon de san trannkat mil sen san swasannsèt")
, (2000000, "de milyon")
, (3000000, "twa milyon")
, (4000000, "kat milyon")
, (5000000, "senk milyon")
, (6000000, "sis milyon")
, (7000000, "sèt milyon")
, (7654321, "sèt milyon si san senkannkat mil twa san venteyen")
, (8000000, "uit milyon")
, (9000000, "nèf milyon")
, (1000000000, "yon milya")
, (1000000001, "yon milya youn")
, (2000000000, "de milya")
, (3000000000, "twa milya")
, (4000000000, "kat milya")
, (5000000000, "senk milya")
, (6000000000, "sis milya")
, (7000000000, "sèt milya")
, (8000000000, "uit milya")
, (9000000000, "nèf milya")
]
)
]
|
telser/numerals
|
src-test/Text/Numeral/Language/HAT/TestData.hs
|
bsd-3-clause
| 6,214 | 0 | 8 | 1,905 | 1,723 | 1,151 | 572 | 193 | 1 |
{-# LANGUAGE LambdaCase #-}
module Main where
import Control.Monad
import System.Environment (getArgs)
import System.IO (BufferMode (NoBuffering), hSetBuffering,
stdin, stdout)
import Text.Show.Prettyprint
import Imperator.Interpreter
import Imperator.Parser
-- yes, im using `error` here. not like this is production code lmao
main :: IO ()
main = do
hSetBuffering stdin NoBuffering -- important
hSetBuffering stdout NoBuffering -- ditto
args <- getArgs
when (length args /= 1) $ error "USAGE: imperator path/to/file.dsl"
let fileName = args !! 0
file <- readFile fileName
case parseImperator fileName file of
Left parseError -> error $ "Error when parsing: " ++ show parseError
Right stmt -> do
putStrLn "===== gratuitous AST output ====="
prettyPrint stmt
putStrLn "================================="
putStrLn ""
runImperator stmt >>= \case
Left interpError -> error $ "Error while interpreting: " ++ show interpError
Right res -> return ()
|
iostat/imperator
|
app/Main.hs
|
bsd-3-clause
| 1,144 | 0 | 17 | 332 | 257 | 124 | 133 | 27 | 3 |
{-# LANGUAGE FlexibleContexts #-}
module Insomnia.ToF.Type where
import Control.Lens
import Control.Monad.Reader
import Data.Monoid
import qualified Data.Map as M
import qualified Unbound.Generics.LocallyNameless as U
import Insomnia.Identifier
import Insomnia.Types
import Insomnia.TypeDefn
import qualified FOmega.Syntax as F
import qualified FOmega.SemanticSig as F
import Insomnia.ToF.Env
import Insomnia.ToF.ModuleType (moduleType)
normalizeAbstractSig :: Monad m => F.AbstractSig -> m F.AbstractSig
normalizeAbstractSig = return -- TODO: finish first class module signature normalization
typeAlias :: ToF m => TypeAlias -> m F.SemanticSig
typeAlias (ManifestTypeAlias bnd) =
U.lunbind bnd $ \(tvks, t) ->
withTyVars tvks $ \tvks' -> do
(t', kcod) <- type' t
let kdoms = map snd tvks'
k = kdoms `F.kArrs` kcod
return $ F.TypeSem t' k
typeAlias (DataCopyTypeAlias _tp _defn) =
error "internal error: ToF.Type.typeAlias - translation of datatype copies unimplemented"
withTyVars :: ToF m => [KindedTVar] -> ([(F.TyVar, F.Kind)] -> m r) -> m r
withTyVars [] kont = kont []
withTyVars (tvk:tvks) kont =
withTyVar tvk $ \tvk' ->
withTyVars tvks $ \tvks' ->
kont $ tvk':tvks'
withTyVar :: ToF m => KindedTVar -> ((F.TyVar, F.Kind) -> m r) -> m r
withTyVar (tv, k) kont = do
k' <- kind k
withFreshName (U.name2String tv) $ \tv' ->
local (tyVarEnv %~ M.insert tv (tv', k'))
$ kont $ (tv', k')
kind :: Monad m => Kind -> m F.Kind
kind KType = return F.KType
kind (KArr k1 k2) = do
k1' <- kind k1
k2' <- kind k2
return $ F.KArr k1' k2'
type' :: ToF m => Type -> m (F.Type, F.Kind)
type' t_ =
case t_ of
TV tv -> do
mv <- view (tyVarEnv . at tv)
case mv of
Just (tv', k') -> return (F.TV tv', k')
Nothing -> do
env <- view tyVarEnv
env' <- view valEnv
throwError ("ToF.type' internal error: type variable " <> show tv
<> " not in environment " <> show env
<> " and value env " <> show env')
TUVar u -> throwError ("ToF.type' internal error: unexpected unification variable " ++ show u)
TC tc -> typeConstructor tc
TAnn t k -> do
(t', _) <- type' t
k' <- kind k
return (t', k')
TApp t1 t2 -> do
(t1', karr) <- type' t1
(t2', _) <- type' t2
case karr of
(F.KArr _ k2) -> do
-- do a bit of normalization if possible
tarr <- betaWhnf (F.TApp t1' t2')
return (tarr, k2)
F.KType -> throwError "ToF.type' internal error: unexpected KType in function position of type application"
TForall bnd ->
U.lunbind bnd $ \((tv, k), tbody) ->
withTyVar (tv,k) $ \(tv', k') -> do
(tbody', _) <- type' tbody
let
tall = F.TForall $ U.bind (tv', U.embed k') $ tbody'
return (tall, F.KType)
TRecord (Row lts) -> do
fts <- forM lts $ \(l, t) -> do
(t', _) <- type' t
return (F.FUser $ labelName l, t')
return (F.TRecord fts, F.KType)
TPack modTy -> do
absSig <- moduleType modTy
absSig' <- normalizeAbstractSig absSig
t' <- F.embedAbstractSig absSig'
return (t', F.KType)
-- opportunistically beta reduce some types.
betaWhnf :: U.LFresh m => F.Type -> m F.Type
betaWhnf t_ =
case t_ of
F.TApp t1 t2 -> do
t1' <- betaWhnf t1
case t1' of
F.TLam bnd ->
U.lunbind bnd $ \((tv,_k), tB) ->
betaWhnf (U.subst tv t2 tB)
_ -> return $ F.TApp t1' t2
_ -> return $ t_
typeConstructor :: ToF m => TypeConstructor -> m (F.Type, F.Kind)
typeConstructor (TCLocal tc) = do
ma <- view (tyConEnv . at tc)
e <- view tyConEnv
case ma of
Just (F.TypeSem t k) -> return (t, k)
Just (F.DataSem d _ k) -> return (F.TV d, k)
Just f -> throwError $ "ToF.typeConstructor: wanted a TypeSem, got a " ++ show f
Nothing -> throwError $ "ToF.typeConstructor: tyConEnv did not contain a TypeSem for a local type constructor: " ++ show tc ++ " in " ++ show e
typeConstructor (TCGlobal (TypePath p f)) = do
let
findIt ident = do
ma <- view (modEnv . at ident)
case ma of
Just (sig, x) -> return (sig, F.V x)
Nothing -> throwError "ToF.typeConstructor: type path has unbound module identifier at the root"
(s, _m) <- followUserPathAnything findIt (ProjP p f)
case s of
F.TypeSem t k -> return (t, k)
F.DataSem d _ k -> return (F.TV d, k)
_ -> throwError "ToF.typeConstructor: type path maps to non-type semantic signature"
|
lambdageek/insomnia
|
src/Insomnia/ToF/Type.hs
|
bsd-3-clause
| 4,509 | 0 | 22 | 1,170 | 1,757 | 872 | 885 | 120 | 10 |
module HighOrderFunc where
flip :: (a -> b -> c) -> b -> a -> c
flip f x y = f y x
flip' f = \x y -> f y x
returnLast :: a -> b -> c -> d -> d
returnLast _ _ _ d = d
-- won't work
returnLast' :: (((a -> b) -> c) -> d) -> d
returnLast' _ _ _ d = d
-- this works
returnLast'' :: a -> (b -> (c -> (d -> d)))
returnLast'' _ _ _ d = d
|
chengzh2008/hpffp
|
src/ch07-FunctionPattern/highOrderFun.hs
|
bsd-3-clause
| 334 | 0 | 11 | 97 | 194 | 104 | 90 | 10 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module OpenSSL.X509.SystemStore.Unix
( contextLoadSystemCerts
) where
import OpenSSL.Session (SSLContext, contextSetCADirectory, contextSetCAFile)
import qualified System.Posix.Files as U
import Control.Exception (try, IOException)
import System.IO.Unsafe (unsafePerformIO)
contextLoadSystemCerts :: SSLContext -> IO ()
contextLoadSystemCerts =
unsafePerformIO $ loop defaultSystemPaths
where
loop ((isDir, path) : rest) = do
mst <- try $ U.getFileStatus path
:: IO (Either IOException U.FileStatus)
case mst of
Right st | isDir, U.isDirectory st ->
return (flip contextSetCADirectory path)
Right st | not isDir, U.isRegularFile st ->
return (flip contextSetCAFile path)
_ -> loop rest
loop [] = return (const $ return ()) -- throw an exception instead?
{-# NOINLINE contextLoadSystemCerts #-}
-- A True value indicates that the path must be a directory.
-- According to [1], the fedora path should be tried before /etc/ssl/certs
-- because of [2].
--
-- [1] https://www.happyassassin.net/2015/01/12/a-note-about-ssltls-trusted-certificate-stores-and-platforms/
-- [2] https://bugzilla.redhat.com/show_bug.cgi?id=1053882
defaultSystemPaths :: [(Bool, FilePath)]
defaultSystemPaths =
[ (False, "/etc/pki/tls/certs/ca-bundle.crt" ) -- red hat, fedora, centos
, (True , "/etc/ssl/certs" ) -- other linux, netbsd
, (True , "/system/etc/security/cacerts" ) -- android
, (False, "/etc/ssl/cert.pem" ) -- openbsd/freebsd
, (False, "/usr/share/ssl/certs/ca-bundle.crt" ) -- older red hat
, (False, "/usr/local/share/certs/ca-root-nss.crt") -- freebsd (security/ca-root-nss)
, (True , "/usr/local/share/certs" ) -- freebsd
]
|
redneb/HsOpenSSL-x509-system
|
OpenSSL/X509/SystemStore/Unix.hs
|
bsd-3-clause
| 1,882 | 0 | 16 | 428 | 355 | 202 | 153 | 30 | 4 |
{- DO NOT EDIT THIS FILE
THIS FILE IS AUTOMAGICALLY GENERATED AND YOUR CHANGES WILL BE EATEN BY THE GENERATOR OVERLORD
All changes should go into the Model file (e.g. App/Models/ExampleModel.hs)
-}
module App.Models.Bases.PageFunctions where
import App.Models.Bases.Common
import qualified Database.HDBC as HDBC
import Data.Maybe
import Data.Time
-- My type
import App.Models.Bases.PageType
import Turbinado.Environment.Types
import Turbinado.Environment.Database
instance HasFindByPrimaryKey Page (String) where
find pk@(pk1) = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn ("SELECT _id , content , title FROM page WHERE (_id = ? )") [HDBC.toSql pk1]
case res of
[] -> throwDyn $ HDBC.SqlError
{HDBC.seState = "",
HDBC.seNativeError = (-1),
HDBC.seErrorMsg = "No record found when finding by Primary Key:page : " ++ (show pk)
}
r:[] -> return $ Page (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1)) (HDBC.fromSql (r !! 2))
_ -> throwDyn $ HDBC.SqlError
{HDBC.seState = "",
HDBC.seNativeError = (-1),
HDBC.seErrorMsg = "Too many records found when finding by Primary Key:page : " ++ (show pk)
}
delete pk@(pk1) = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.run conn ("DELETE FROM page WHERE (_id = ? )") [HDBC.toSql pk1]
case res of
0 -> (liftIO $ HDBC.handleSqlError $ HDBC.rollback conn) >>
(throwDyn $ HDBC.SqlError
{HDBC.seState = "",
HDBC.seNativeError = (-1),
HDBC.seErrorMsg = "Rolling back. No record found when deleting by Primary Key:page : " ++ (show pk)
})
1 -> (liftIO $ HDBC.handleSqlError $ HDBC.commit conn) >> return ()
_ -> (liftIO $ HDBC.handleSqlError $ HDBC.rollback conn) >>
(throwDyn $ HDBC.SqlError
{HDBC.seState = "",
HDBC.seNativeError = (-1),
HDBC.seErrorMsg = "Rolling back. Too many records deleted when deleting by Primary Key:page : " ++ (show pk)
})
update m = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.run conn "UPDATE page SET (_id , content , title) = (?,?,?) WHERE (_id = ? )"
[HDBC.toSql $ _id m , HDBC.toSql $ content m , HDBC.toSql $ title m, HDBC.toSql $ _id m]
liftIO $ HDBC.handleSqlError $ HDBC.commit conn
return ()
instance IsModel Page where
insert m returnId = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.run conn (" INSERT INTO page (_id,content,title) VALUES (?,?,?)") ( [HDBC.toSql $ _id m] ++ [HDBC.toSql $ content m] ++ [HDBC.toSql $ title m])
case res of
0 -> (liftIO $ HDBC.handleSqlError $ HDBC.rollback conn) >>
(throwDyn $ HDBC.SqlError
{HDBC.seState = "",
HDBC.seNativeError = (-1),
HDBC.seErrorMsg = "Rolling back. No record inserted :page : " ++ (show m)
})
1 -> liftIO $ HDBC.handleSqlError $ HDBC.commit conn >>
if returnId
then do i <- liftIO $ HDBC.catchSql (HDBC.handleSqlError $ HDBC.quickQuery' conn "SELECT lastval()" []) (\_ -> HDBC.commit conn >> (return $ [[HDBC.toSql (0 :: Integer)]]) )
return $ HDBC.fromSql $ head $ head i
else return Nothing
findAll = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn "SELECT _id , content , title FROM page" []
return $ map (\r -> Page (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1)) (HDBC.fromSql (r !! 2))) res
findAllWhere ss sp = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn ("SELECT _id , content , title FROM page WHERE (" ++ ss ++ ") ") sp
return $ map (\r -> Page (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1)) (HDBC.fromSql (r !! 2))) res
findAllOrderBy op = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn ("SELECT _id , content , title FROM page ORDER BY " ++ op) []
return $ map (\r -> Page (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1)) (HDBC.fromSql (r !! 2))) res
findAllWhereOrderBy ss sp op = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn ("SELECT _id , content , title FROM page WHERE (" ++ ss ++ ") ORDER BY " ++ op) sp
return $ map (\r -> Page (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1)) (HDBC.fromSql (r !! 2))) res
findOneWhere ss sp = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn ("SELECT _id , content , title FROM page WHERE (" ++ ss ++ ") LIMIT 1") sp
return $ (\r -> Page (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1)) (HDBC.fromSql (r !! 2))) (head res)
findOneOrderBy op = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn ("SELECT _id , content , title FROM page ORDER BY " ++ op ++ " LIMIT 1") []
return $ (\r -> Page (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1)) (HDBC.fromSql (r !! 2))) (head res)
findOneWhereOrderBy ss sp op = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn ("SELECT _id , content , title FROM page WHERE (" ++ ss ++ ") ORDER BY " ++ op ++" LIMIT 1") sp
return $ (\r -> Page (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1)) (HDBC.fromSql (r !! 2))) (head res)
deleteWhere :: (HasEnvironment m) => SelectString -> SelectParams -> m Integer
deleteWhere ss sp = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.run conn ("DELETE FROM page WHERE (" ++ ss ++ ") ") sp
return res
|
alsonkemp/turbinado-website
|
App/Models/Bases/PageFunctions.hs
|
bsd-3-clause
| 6,754 | 0 | 26 | 2,077 | 2,155 | 1,108 | 1,047 | -1 | -1 |
module Chapter2.ExercisesSpec where
import Test.Hspec
x = y ^ 2
waxOn = x * 5
y = z + 8
z = 7
triple x = x * 3
waxOff x = triple x
squareAndPi :: Integer -> Double
squareAndPi value = undefined
spec :: Spec
spec =
describe "Exercises Chapter 2" $ do
it "should compile" $ "" `shouldBe` ""
-- describe "Equivalent expressions" $ do
-- it "1 should be true or false" $ (1 + 1) == 2 `shouldBe` -- Enter True or False
-- it "2 should be true or false" $ (10 ^ 2) == (10 + 9 * 10) `shouldBe` -- Enter True or False
-- it "3 should be true or false" $ (400 - 37) == ((-) 37 400) `shouldBe` -- Enter True or False
-- -- Next test might throw an error.
-- it "4 should be true or false" $ (100 `div` 3) == (100 / 3) `shouldBe` -- Enter True or False
-- it "5 should be true or false" $ (2 * 5 + 18) == (2 * (5 + 18)) `shouldBe` -- Enter True or False
-- describe "More fun with functions" $ do
-- it "1a What do you expect" $ (1 + waxOn) `shouldBe` -- Enter your expected value
-- it "1b What do you expect" $ ((+10) waxOn) `shouldBe` -- Enter your expected value
-- it "1c What do you expect" $ ((-) 15 waxOn) `shouldBe` -- Enter your expected value
-- it "1d What do you expect" $ ((-) waxOn 15) `shouldBe` -- Enter your expected value
-- it "What is the expected output" $ (triple waxOn) `shouldBe` -- Enter your expected value
-- -- When the previous tests passed Rewrite waxOn as a function with a where clause an run tests again
-- it "What is the expected output" $ (waxOff waxOn) `shouldBe` -- Enter your expected value
-- describe "Intermediate tests" $ do
-- it "should multiply 3.14 with the square of a value" $ (squareAndPi 5) `shouldBe` (3.14 * 25)
-- it "should do the correct math" $ 8 + 7 * 9 `shouldBe` 135
|
yannick-cw/haskell_katas
|
test/Chapter2/ExercisesSpec.hs
|
bsd-3-clause
| 1,830 | 0 | 10 | 468 | 134 | 80 | 54 | 14 | 1 |
{-# LANGUAGE UnicodeSyntax #-}
module Shake.It.Rust.Cargo
( cargo
) where
import Control.Monad
import Shake.It.Core
cargo ∷ [String] → IO ()
cargo α = rawSystem "cargo" α >>= checkExitCode
|
Heather/Shake.it.off
|
src/Shake/It/Rust/Cargo.hs
|
bsd-3-clause
| 222 | 0 | 7 | 55 | 59 | 34 | 25 | 7 | 1 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances #-}
{- |
Module : ./Haskell/HatAna.hs
Description : calling programatica's analysis
Copyright : (c) Christian Maeder, Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable (multiple parameter class, functional dependency)
This module supplies a signature type and a type checking function
for the Haskell logic.
-}
module Haskell.HatAna (module Haskell.HatAna, PNT, TiDecl) where
import Haskell.HatParser hiding (hatParser)
import Haskell.PreludeString
import Common.AS_Annotation
import Common.Id (Pos (..), Range (..))
import Common.Result
import Common.GlobalAnnotations
import qualified Data.Map as Map
import qualified Data.Set as Set
import Common.Doc
import Common.DocUtils
import Common.ExtSign
import Data.List
import Data.Char
import qualified Data.Set as DSet
import Data.Maybe (fromMaybe)
type Scope = Rel (SN HsName) (Ent (SN String))
data Sign = Sign
{ instances :: [Instance PNT]
, types :: Map.Map (HsIdentI PNT) (Kind, TypeInfo PNT)
, values :: Map.Map (HsIdentI PNT) (Scheme PNT)
, scope :: Scope
, fixities :: Map.Map (HsIdentI (SN String)) HsFixity
} deriving Show
instance Eq Sign where
a == b = compare a b == EQ
instance Ord Sign where
compare a b = compare
( Map.keysSet $ types a, Map.keysSet $ values a, scope a
, Map.keysSet $ fixities a, length $ instances a)
( Map.keysSet $ types b, Map.keysSet $ values b, scope b
, Map.keysSet $ fixities b, length $ instances b)
diffSign :: Sign -> Sign -> Sign
diffSign e1 e2 = emptySign
{ instances = instances e1 \\ instances e2
, types = types e1 `Map.difference` types e2
, values = values e1 `Map.difference` values e2
, scope = scope e1 `minusRel` scope e2
, fixities = fixities e1 `Map.difference` fixities e2
}
addSign :: Sign -> Sign -> Sign
addSign e1 e2 = emptySign
{ instances = let is = instances e2 in (instances e1 \\ is) ++ is
, types = types e1 `Map.union` types e2
, values = values e1 `Map.union` values e2
, scope = scope e1 `DSet.union` scope e2
, fixities = fixities e1 `Map.union` fixities e2
}
isSubSign :: Sign -> Sign -> Bool
isSubSign e1 e2 = diffSign e1 e2 == emptySign
instance Eq (TypeInfo i) where
_ == _ = True
instance Eq (TiDecl PNT) where
a == b = compare a b == EQ
instance Ord (TiDecl PNT) where
compare a b = compare (show a) (show b)
instance Pretty (TiDecl PNT) where
pretty = text . pp
instance Pretty Sign where
pretty = printSign
printSign :: Sign -> Doc
printSign Sign { instances = is, types = ts,
values = vs, fixities = fs, scope = sc } =
text "{-" $+$ (if null is then empty else
text "instances:" $+$
vcat (map (text . pp . fst) is)) $+$
(if Map.null ts then empty else
text "\ntypes:" $+$
vcat (map (text . pp)
[ a :>: b | (a, b) <- Map.toList ts ])) $+$
(if Map.null vs then empty else
text "\nvalues:" $+$
vcat (map (text . pp)
[ a :>: b | (a, b) <- Map.toList vs ])) $+$
(if Map.null fs then empty else
text "\nfixities:" $+$
vcat [ text (pp b) <+> text (pp a)
| (a, b) <- Map.toList fs ]) $+$
text "\nscope:" $+$
text (pp sc) $+$
text "-}" $+$
text "module Dummy where"
extendSign :: Sign -> [Instance PNT]
-> [TAssump PNT]
-> [Assump PNT]
-> Scope
-> [(HsIdentI (SN String), HsFixity)]
-> Sign
extendSign e is ts vs s fs = addSign e emptySign
{ instances = is
, types = Map.fromList [ (a, b) | (a :>: b) <- ts ]
, values = Map.fromList [ (a, b) | (a :>: b) <- vs ]
, scope = s
, fixities = Map.fromList fs
}
emptySign :: Sign
emptySign = Sign
{ instances = []
, types = Map.empty
, values = Map.empty
, scope = emptyRel
, fixities = Map.empty
}
hatAna :: (HsDecls, Sign, GlobalAnnos) ->
Result (HsDecls, ExtSign Sign (), [Named (TiDecl PNT)])
hatAna (HsDecls hs, e, ga) = do
(decls, accSig, sens) <-
hatAna2 (HsDecls hs, addSign e preludeSign, ga)
return (decls, mkExtSign (diffSign accSig preludeSign), sens)
preludeSign :: Sign
preludeSign = case maybeResult $ hatAna2
(HsDecls preludeDecls, emptySign, emptyGlobalAnnos) of
Just (_, sig, _) -> sig
_ -> error "preludeSign"
hatAna2 :: (HsDecls, Sign, GlobalAnnos) ->
Result (HsDecls, Sign, [Named (TiDecl PNT)])
hatAna2 (hs@(HsDecls ds), e, _) = do
let parsedMod = HsModule loc0 (SN mod_Prelude loc0) Nothing [] ds
astMod = toMod parsedMod
insc = inscope astMod (const emptyRel)
osc = scope e `DSet.union` insc
expScope :: Rel (SN String) (Ent (SN String))
expScope = mapDom (fmap hsUnQual) osc
wm :: WorkModuleI QName (SN String)
wm = mkWM (osc, expScope)
fixs = mapFst getQualified $ getInfixes parsedMod
fixMap = Map.fromList fixs `Map.union` fixities e
rm = reAssocModule wm [(mod_Prelude, Map.toList fixMap)] parsedMod
(HsModule _ _ _ _ sds, _) =
scopeModule (wm, [(mod_Prelude, expScope)]) rm
ent2pnt (Ent m (HsCon i) t) =
HsCon (topName Nothing m (bn i) (origt m t))
ent2pnt (Ent m (HsVar i) t) =
HsVar (topName Nothing m (bn i) (origt m t))
bn = getBaseName
origt m = fmap (osub m)
osub m n = origName n m n
findPredef ns (_, n) =
case filter ((== ns) . namespace) $ applyRel expScope (fakeSN n) of
[v] -> Right (ent2pnt v)
_ -> Left ("'" ++ n ++ "' unknown or ambiguous")
inMyEnv = withStdNames findPredef
. inModule (const mod_Prelude) []
. extendts [ a :>: b | (a, b) <- Map.toList $ values e ]
. extendkts [ a :>: b | (a, b) <- Map.toList $ types e ]
. extendIEnv (instances e)
case sds of
[] -> return ()
d : _ -> Result [Diag Hint ('\n' : pp sds)
(Range [formSrcLoc $ srcLoc d])] $ Just ()
fs :>: (is, (ts, vs)) <-
lift $ inMyEnv $ tcTopDecls id sds
let accSign = extendSign e is ts vs insc fixs
return (hs, accSign, map (makeNamed "") $ fromDefs
(fs :: TiDecls PNT))
-- filtering some Prelude stuff
formSrcLoc :: SrcLoc -> Pos
formSrcLoc (SrcLoc file _ line col) = SourcePos file line col
getHsDecl :: (Rec a b, GetBaseStruct b (DI i e p ds t [t] t)) =>
a -> DI i e p ds t [t] t
getHsDecl = Data.Maybe.fromMaybe (HsFunBind loc0 []) . basestruct . struct
-- use a dummy for properties
preludeConflicts :: [HsDecl] -> ([HsDecl], [Diagnosis])
preludeConflicts =
foldr ( \ d (es, ds) -> let e = getHsDecl d
p = [formSrcLoc $ srcLoc e]
in
if preludeEntity e then
(es,
Diag Warning ("possible Prelude conflict:\n " ++ pp e)
(Range p) : ds)
else (d : es, ds)) ([], [])
preludeEntity :: (Printable i, Show t, DefinedNames i t) =>
DI i e p ds t [t] t -> Bool
preludeEntity d = case d of
HsFunBind _ ms -> any preludeMatch ms
HsTypeSig _ ts _ _ -> any (flip Set.member preludeValues . pp) ts
HsTypeDecl _ ty _ -> Set.member (pp $ definedType ty) preludeTypes
HsDataDecl _ _ ty cs _ -> Set.member (pp $ definedType ty) preludeTypes
|| any preludeConstr cs
HsInstDecl {} -> False
HsClassDecl {} -> False -- should not be a prelude class
_ -> True -- ignore others
preludeMatch :: Printable i =>
HsMatchI i e p ds -> Bool
preludeMatch m = case m of
HsMatch _ n _ _ _ -> let s = pp n in
Set.member s preludeValues || prefixed s
preludeConstr :: Printable i => HsConDeclI i t [t] -> Bool
preludeConstr c = let s = pp $ case c of
HsConDecl _ _ _ n _ -> n
HsRecDecl _ _ _ n _ -> n
in Set.member s preludeConstrs
genPrefixes :: [String]
genPrefixes = ["$--", "default__", "derived__Prelude", "inst__Prelude"]
prefixed :: String -> Bool
prefixed s = any (`isPrefixOf` s) genPrefixes
preludeValues :: Set.Set String
preludeValues = Set.fromList $ filter (not . prefixed) $ map pp
$ Map.keys $ values preludeSign
preludeConstrs :: Set.Set String
preludeConstrs =
Set.filter ( \ s -> not (null s) && isUpper (head s)) preludeValues
preludeTypes :: Set.Set String
preludeTypes = Set.fromList $ map pp $ Map.keys $ types preludeSign
|
spechub/Hets
|
Haskell/HatAna.hs
|
gpl-2.0
| 8,859 | 0 | 22 | 2,681 | 3,321 | 1,735 | 1,586 | 199 | 7 |
{-
- Copyright 2011 Per Magnus Therning
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-}
module BuildPkgs where
import PkgDB
import Util.Misc
import Control.Monad.Reader
buildPkgs :: Command ()
buildPkgs = do
db <- asks (dbFile . fst) >>= liftIO . readDb
pkgs <- asks $ pkgs . optsCmd . fst
liftIO $ mapM_ putStrLn $ transitiveDependants db pkgs
|
magthe/cblrepo
|
src/BuildPkgs.hs
|
apache-2.0
| 877 | 0 | 12 | 176 | 97 | 50 | 47 | 9 | 1 |
{-# LANGUAGE FlexibleContexts, MultiParamTypeClasses, FunctionalDependencies #-}
module CSPM.TypeChecker.Common where
import CSPM.Syntax.Literals
import CSPM.Syntax.Types
import CSPM.TypeChecker.Monad
import CSPM.TypeChecker.Unification
-- a -> b <=> We can't have two instances that match on a but differ on b
class TypeCheckable a b | a -> b where
typeCheck :: a -> TypeCheckMonad b
typeCheck a =
case errorContext a of
Just c -> addErrorContext c (typeCheck' a)
Nothing -> typeCheck' a
typeCheckExpect :: a -> Type -> TypeCheckMonad b
typeCheckExpect _ _ = panic "typeCheckExpect not supported"
typeCheck' :: a -> TypeCheckMonad b
errorContext :: a -> Maybe ErrorContext
instance TypeCheckable Literal Type where
errorContext _ = Nothing
typeCheck' (Int _) = return TInt
typeCheck' (Bool _) = return TBool
typeCheck' (Char _) = return TChar
typeCheck' (String _) = return $ TSeq TChar
ensureAreEqual :: TypeCheckable a Type => [a] -> TypeCheckMonad Type
ensureAreEqual [] = freshRegisteredTypeVar
ensureAreEqual (e:es) = do
t <- typeCheck e
mapM (\e -> typeCheckExpect e t) es
return t
ensureAreEqualTo :: TypeCheckable a Type => Type -> [a] -> TypeCheckMonad Type
ensureAreEqualTo typ es = do
mapM (\e -> typeCheckExpect e typ) es
return typ
ensureAreEqualAndHaveConstraint :: TypeCheckable a Type => Constraint -> [a] -> TypeCheckMonad Type
ensureAreEqualAndHaveConstraint c es = do
fv1 <- freshRegisteredTypeVarWithConstraints [c]
ensureAreEqualTo fv1 es
ensureIsList :: TypeCheckable a b => a -> TypeCheckMonad b
ensureIsList e = do
fv <- freshRegisteredTypeVar
typeCheckExpect e (TSeq fv)
ensureIsSet :: TypeCheckable a b => a -> TypeCheckMonad b
ensureIsSet e = do
fv <- freshRegisteredTypeVarWithConstraints [CSet]
typeCheckExpect e (TSet fv)
ensureIsBool :: TypeCheckable a b => a -> TypeCheckMonad b
ensureIsBool e = typeCheckExpect e TBool
ensureIsInt :: TypeCheckable a b => a -> TypeCheckMonad b
ensureIsInt e = typeCheckExpect e TInt
ensureIsChannel :: TypeCheckable a b => a -> TypeCheckMonad b
ensureIsChannel e = ensureIsExtendable e TEvent
ensureIsExtendable :: TypeCheckable a b => a -> Type -> TypeCheckMonad b
ensureIsExtendable e t = do
tvref <- freshRegisteredTypeVarRef []
typeCheckExpect e (TExtendable t tvref)
ensureIsEvent :: TypeCheckable a b => a -> TypeCheckMonad b
ensureIsEvent e = typeCheckExpect e TEvent
ensureIsProc :: TypeCheckable a b => a -> TypeCheckMonad b
ensureIsProc e = typeCheckExpect e TProc
ensureHasConstraint :: Constraint -> Type -> TypeCheckMonad Type
ensureHasConstraint c = ensureHasConstraints [c]
ensureHasConstraints :: [Constraint] -> Type -> TypeCheckMonad Type
ensureHasConstraints cs t = do
fv1 <- freshRegisteredTypeVarWithConstraints cs
unify fv1 t
|
sashabu/libcspm
|
src/CSPM/TypeChecker/Common.hs
|
bsd-3-clause
| 2,882 | 0 | 12 | 561 | 875 | 422 | 453 | 64 | 1 |
import System.Plugins
import API
--
-- what happens if we try to use code that has been unloaded?
--
main = do
m_v <- load "../Null.o" ["../api"] [] "resource"
(m,v) <- case m_v of
LoadSuccess m v -> return (m,v)
_ -> error "load failed"
putStrLn ( show (a v) )
unload m
|
abuiles/turbinado-blog
|
tmp/dependencies/hs-plugins-1.3.1/testsuite/unload/sjwtrap/prog/Main.hs
|
bsd-3-clause
| 323 | 0 | 12 | 105 | 108 | 54 | 54 | 9 | 2 |
module Ch08par where
-- todays goal is get through vid of 8
|
HaskellForCats/HaskellForCats
|
MenaBeginning/Ch001/2014-0224gargbColl.hs
|
mit
| 63 | 0 | 2 | 15 | 5 | 4 | 1 | 1 | 0 |
{-# LANGUAGE RecursiveDo #-}
module Ho.Build (
module Ho.Type,
dumpHoFile,
parseFiles,
preprocess,
preprocessHs,
buildLibrary
) where
import Util.Std
import Control.Concurrent
import Data.IORef
import Data.Tree
import Data.Version(Version,parseVersion,showVersion)
import System.FilePath as FP
import System.Mem
import Text.Printf
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Lazy.UTF8 as LBSU
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Text.PrettyPrint.HughesPJ as PPrint
import DataConstructors
import Doc.DocLike hiding((<>))
import Doc.PPrint
import Doc.Pretty
import E.E
import E.Rules
import E.Show
import E.Traverse(emapE)
import E.TypeCheck()
import FrontEnd.Class
import FrontEnd.FrontEnd
import FrontEnd.HsSyn
import FrontEnd.Infix
import FrontEnd.Warning
import Ho.Binary
import Ho.Collected()
import Ho.Library
import Ho.ReadSource
import Ho.Type
import Name.Names
import Options
import PackedString(PackedString,packString,unpackPS)
import Support.TempDir
import Util.Gen
import Util.SetLike
import Util.YAML
import Version.Config(version)
import Version.Version(versionString)
import qualified FlagDump as FD
import qualified FlagOpts as FO
import qualified Support.MD5 as MD5
import qualified Util.Graph as G
-- Ho File Format
--
-- ho files are standard CFF format files (PNG-like) as described in the Support.CFF modules.
--
-- the CFF magic for the files is the string "JHC"
--
-- JHDR - header info, contains a list of modules contained and dependencies that need to be checked to read the file
-- LIBR - only present if this is a library, contains library metainfo
-- IDEP - immutable import information, needed to tell if ho files are up to date
-- LINK - redirect to another file for file systems without symlinks
-- DEFS - definitions type checking information
-- CORE - compiled core and associated data
-- LDEF - library map of module group name to DEFS
-- LCOR - library map of module group name to CORE
-- GRIN - compiled grin code
-- FILE - Extra file, such as embedded c code.
{-
- We separate the data into various chunks for logical layout as well as the
- important property that each chunk is individually compressed and accessable.
- What this means is that we can skip chunks we don't need. for instance,
- during the final link we have no need of the haskell type checking
- information, we are only interested in the compiled code, so we can jump
- directly to it. If we relied on straight serialization, we would have to
- parse all preceding information just to discard it right away. We also lay
- them out so that we can generate error messages quickly. for instance, we can
- determine if a symbol is undefined quickly, before it has to load the
- typechecking data.
-}
type LibraryName = PackedString
findFirstFile :: [FilePath] -> IO (LBS.ByteString,FilePath)
findFirstFile [] = fail "findFirstFile: file not found"
findFirstFile (x:xs) = flip iocatch (\e -> findFirstFile xs) $ do
bs <- LBS.readFile x
return (bs,x)
data ModDone
= ModNotFound
| ModLibrary !Bool ModuleGroup Library
| Found SourceCode
data Done = Done {
hoCache :: Maybe FilePath,
knownSourceMap :: Map.Map SourceHash (Module,[(Module,SrcLoc)]),
validSources :: Set.Set SourceHash,
loadedLibraries :: Map.Map LibraryName Library,
hosEncountered :: Map.Map HoHash (FilePath,HoHeader,HoIDeps,Ho),
modEncountered :: Map.Map Module ModDone
}
hosEncountered_u f r@Done{hosEncountered = x} = r{hosEncountered = f x}
knownSourceMap_u f r@Done{knownSourceMap = x} = r{knownSourceMap = f x}
loadedLibraries_u f r@Done{loadedLibraries = x} = r{loadedLibraries = f x}
modEncountered_u f r@Done{modEncountered = x} = r{modEncountered = f x}
validSources_u f r@Done{validSources = x} = r{validSources = f x}
replaceSuffix suffix fp = reverse (dropWhile ('.' /=) (reverse fp)) ++ suffix
hoFile :: Maybe FilePath -> FilePath -> Maybe Module -> SourceHash -> FilePath
hoFile cacheDir fp mm sh = case (cacheDir,optHoDir options) of
(Nothing,Nothing) -> replaceSuffix "ho" fp
(Nothing,Just hdir) -> case mm of
Nothing -> hdir ++ "/" ++ MD5.md5show32 sh ++ ".ho"
Just m -> hdir ++ "/" ++ map ft (show m) ++ ".ho" where
ft '/' = '.'
ft x = x
(Just hdir,_) -> hdir ++ "/" ++ MD5.md5show32 sh ++ ".ho"
findHoFile :: IORef Done -> FilePath -> Maybe Module -> SourceHash -> IO (Bool,FilePath)
findHoFile done_ref fp mm sh = do
done <- readIORef done_ref
let honame = hoFile (hoCache done) fp mm sh
writeIORef done_ref (done { validSources = Set.insert sh (validSources done) })
if sh `Set.member` validSources done || optIgnoreHo options then return (False,honame) else do
onErr (return (False,honame)) (readHoFile honame) $ \ (hoh,hidep,ho) ->
case hohHash hoh `Map.lookup` hosEncountered done of
Just (fn,_,_,a) -> return (True,fn)
Nothing -> do
modifyIORef done_ref (knownSourceMap_u $ (`mappend` (hoIDeps hidep)))
modifyIORef done_ref (validSources_u $ Set.union (Set.fromList . map snd $ hoDepends hidep))
modifyIORef done_ref (hosEncountered_u $ Map.insert (hohHash hoh) (honame,hoh,hidep,ho))
return (True,honame)
onErr :: IO a -> IO b -> (b -> IO a) -> IO a
onErr err good cont = join $ iocatch (good >>= return . cont) (\_ -> return err)
fetchSource :: Opt -> IORef Done -> [FilePath] -> Maybe (Module,SrcLoc) -> IO Module
fetchSource _ _ [] _ = fail "No files to load"
fetchSource modOpt done_ref fs mm = do
let killMod = case mm of
Nothing -> fail $ "Could not load file: " ++ show fs
Just (m,sloc) -> do
warn sloc (MissingModule m Nothing) $ printf "Module '%s' not found." (show m)
modifyIORef done_ref (modEncountered_u $ Map.insert m ModNotFound) >> return m
onErr killMod (findFirstFile fs) $ \ (lbs,fn) -> do
let hash = MD5.md5lazy $ (LBSU.fromString version) `mappend` lbs
(foundho,mho) <- findHoFile done_ref fn (fmap fst mm) hash
done <- readIORef done_ref
(mod,m,ds) <- case mlookup hash (knownSourceMap done) of
Just (m,ds) -> return (Left lbs,m,ds)
Nothing -> do
(hmod,_) <- parseHsSource modOpt fn lbs
let m = hsModuleName hmod
ds = hsModuleRequires hmod
writeIORef done_ref (knownSourceMap_u (Map.insert hash (m,ds)) done)
case optAnnotate options of
Just _ -> return (Left lbs,m,ds)
_ -> return (Right hmod,m,ds)
case mm of
Just (m',_) | m /= m' -> do
putErrLn $ "Skipping file" <+> fn <+> "because its module declaration of" <+> show m <+> "does not equal the expected" <+> show m'
killMod
_ -> do
let sc (Right mod) = SourceParsed sinfo mod
sc (Left lbs) = SourceRaw sinfo lbs
sinfo = SI { sourceHash = hash, sourceDeps = ds, sourceFP = fn, sourceHoName = mho, sourceModName = m }
modifyIORef done_ref (modEncountered_u $ Map.insert m (Found (sc mod)))
fn' <- shortenPath fn
mho' <- shortenPath mho
putProgressLn $ if foundho
then printf "%-23s [%s] <%s>" (show m) fn' mho'
else printf "%-23s [%s]" (show m) fn'
mapM_ (resolveDeps modOpt done_ref) ds
return m
resolveDeps :: Opt -> IORef Done -> (Module,SrcLoc) -> IO ()
resolveDeps modOpt done_ref (m,sloc) = do
done <- readIORef done_ref
case m `mlookup` modEncountered done of
Just (ModLibrary False _ lib) | sloc /= bogusASrcLoc -> warn sloc (MissingModule m (Just $ libName lib)) (printf "ERROR: Attempt to import module '%s' which is a member of the library '%s'.\nPerhaps you need to add '-p%s' to the command line?" (show m) (libName lib) (libName lib))
Just _ -> return ()
Nothing -> fetchSource modOpt done_ref (map fst $ searchPaths modOpt (show m)) (Just (m,sloc)) >> return ()
type LibInfo = (Map.Map Module ModuleGroup, Map.Map ModuleGroup [ModuleGroup], Set.Set Module,Map.Map ModuleGroup HoBuild,Map.Map ModuleGroup HoTcInfo)
data CompNode = CompNode !HoHash [CompNode] {-# UNPACK #-} !(IORef CompLink)
data CompLink
= CompLinkUnit CompUnit
| CompCollected CollectedHo CompUnit
| CompTcCollected HoTcInfo CompUnit
| CompLinkLib (ModuleGroup,LibInfo) CompUnit
compLinkCompUnit (CompLinkUnit cu) = cu
compLinkCompUnit (CompCollected _ cu) = cu
compLinkCompUnit (CompTcCollected _ cu) = cu
compLinkCompUnit (CompLinkLib _ cu) = cu
instance MapKey Module where
showMapKey = show
instance MapKey MD5.Hash where
showMapKey = show
dumpDeps targets done cug = case optDeps options of
Nothing -> return ()
Just fp -> do
let memap = modEncountered done
let (sfps,sdps,ls) = collectDeps memap cug
let yaml = Map.fromList [
("Target",toNode targets),
("LibraryDesc",toNode [ fp | BuildHl fp <- [optMode options]]),
("LibraryDeps",toNode ls),
("LibraryDepsUnused", toNode [ (libHash l,libFileName l) | l <- Map.elems (loadedLibraries done), libHash l `Map.notMember` ls ]),
("ModuleSource",toNode sfps),
("ModuleDeps",toNode sdps)
]
writeFile fp (showYAML yaml)
collectDeps memap cs = mconcatMap f [ cu | (_,(_,cu)) <- cs] where
f (CompSources ss) = mconcat [ (Map.singleton (sourceModName s) (sourceFP s),Map.singleton (sourceModName s) (fsts $ sourceDeps s),mempty) | s <- map sourceInfo ss ]
f (CompLibrary _ lib) = (mempty,mempty,Map.singleton (libHash lib) (libFileName lib))
f (CompHo _hoh idep _ho) = (Map.fromList [ (sourceModName $ sourceInfo src, sourceFP $ sourceInfo src) | s <- fsts ss, Just (Found src) <- [Map.lookup s memap] ],Map.fromList [ (mms,fsts mms') | s <- snds ss, Just (mms,mms') <- [Map.lookup s (hoIDeps idep)] ],mempty) where
ss = [ s | s <- hoDepends idep ]
f _ = mempty
type CompUnitGraph = [(HoHash,([HoHash],CompUnit))]
data CompUnit
= CompHo HoHeader HoIDeps Ho
| CompSources [SourceCode]
| CompTCed ((HoTcInfo,TiData,[(HoHash,HsModule)],[String]))
| CompDummy
| CompLibrary Ho Library
instance Show CompUnit where
showsPrec _ = shows . providesModules
data SourceInfo = SI {
sourceHash :: SourceHash,
sourceDeps :: [(Module,SrcLoc)],
sourceFP :: FilePath,
sourceModName :: Module,
sourceHoName :: FilePath
}
data SourceCode
= SourceParsed { sourceInfo :: !SourceInfo, sourceModule :: HsModule }
| SourceRaw { sourceInfo :: !SourceInfo, sourceLBS :: LBS.ByteString }
sourceIdent = show . sourceModName . sourceInfo
class ProvidesModules a where
providesModules :: a -> [Module]
providesModules _ = []
instance ProvidesModules HoIDeps where
providesModules = fsts . hoDepends
instance ProvidesModules HoLib where
providesModules = Map.keys . hoModuleMap
instance ProvidesModules CompUnit where
providesModules (CompHo _ hoh _) = providesModules hoh
providesModules (CompSources ss) = concatMap providesModules ss
providesModules (CompLibrary ho libr) = libProvides (hoModuleGroup ho) libr
providesModules CompDummy = []
providesModules (CompTCed _) = error "providesModules: bad1."
instance ProvidesModules CompLink where
providesModules (CompLinkUnit cu) = providesModules cu
providesModules (CompCollected _ cu) = providesModules cu
providesModules (CompTcCollected _ cu) = providesModules cu
providesModules (CompLinkLib _ _) = error "providesModules: bad2c."
instance ProvidesModules SourceCode where
providesModules sp = [sourceModName (sourceInfo sp)]
-- | this walks the loaded modules and ho files, discarding out of
-- date ho files and organizing modules into their binding groups.
-- the result is an acyclic graph where the nodes are ho files, sets
-- of mutually recursive modules, or libraries.
-- there is a strict ordering of
-- source >= ho >= library
-- in terms of dependencies
toCompUnitGraph :: Done -> [Module] -> IO (HoHash,CompUnitGraph)
toCompUnitGraph done roots = do
let fs m = map inject $ maybe (error $ "can't find deps for: " ++ show m) (fsts . snd) (Map.lookup m (knownSourceMap done))
fs' m libr = fromMaybe (error $ "can't find deps for: " ++ show m) (Map.lookup m (hoModuleDeps $ libHoLib libr))
foundMods = [ ((m,Left (sourceHash $ sourceInfo sc)),fs (sourceHash $ sourceInfo sc)) | (m,Found sc) <- Map.toList (modEncountered done)]
foundMods' = Map.elems $ Map.fromList [ (mg,((mg,Right lib),fs' mg lib)) | (_,ModLibrary _ mg lib) <- Map.toList (modEncountered done)]
fullModMap = Map.unions (map libModMap $ Map.elems (loadedLibraries done))
inject m = Map.findWithDefault m m fullModMap
gr = G.newGraph (foundMods ++ foundMods') (fst . fst) snd
gr' = G.sccGroups gr
phomap = Map.fromListWith (++) (concat [ [ (m,[hh]) | (m,_) <- hoDepends idep ] | (hh,(_,_,idep,_)) <- Map.toList (hosEncountered done)])
sources = Map.fromList [ (m,sourceHash $ sourceInfo sc) | (m,Found sc) <- Map.toList (modEncountered done)]
when (dump FD.SccModules) $ do
mapM_ (putErrLn . show) $ map (map $ fst . fst) gr'
putErrLn $ drawForest (map (fmap (show . fst . fst)) (G.dff gr))
cug_ref <- newIORef []
hom_ref <- newIORef (Map.map ((,) False) $ hosEncountered done)
ms <- forM gr' $ \ns -> do
r <- newIORef (Left ns)
return (Map.fromList [ (m,r) | ((m,_),_) <- ns ])
let mods = Map.unions ms
lmods m = fromMaybe (error $ "modsLookup: " ++ show m) (Map.lookup m mods)
let f m = do
rr <- readIORef (lmods m)
case rr of
Right hh -> return hh
Left ns -> g ns
g ms@(((m,Left _),_):_) = do
let amods = map (fst . fst) ms
pm (fromMaybe [] (Map.lookup m phomap)) $ do
let deps = Set.toList $ Set.fromList (concat $ snds ms) `Set.difference` (Set.fromList amods)
deps' <- snub `fmap` mapM f deps
let mhash = MD5.md5String (concatMap (show . fst) ms ++ show deps')
writeIORef (lmods m) (Right mhash)
modifyIORef cug_ref ((mhash,(deps',CompSources $ map fs amods)):)
return mhash
g [((mg,Right lib),ds)] = do
let Just hob = Map.lookup mg $ libBuildMap lib
Just hot = Map.lookup mg $ libTcMap lib
ho = Ho { hoModuleGroup = mg, hoBuild = hob, hoTcInfo = hot }
myHash = libMgHash mg lib
deps <- snub `fmap` mapM f ds
writeIORef (lmods mg) (Right myHash)
modifyIORef cug_ref ((myHash,(deps,CompLibrary ho lib)):)
return myHash
g _ = error "Build.toCompUnitGraph: bad."
pm :: [HoHash] -> IO HoHash -> IO HoHash
pm [] els = els
pm (h:hs) els = hvalid h `iocatch` (\_ -> pm hs els)
hvalid h = do
ll <- Map.lookup h `fmap` readIORef hom_ref
case ll of
Nothing -> fail "Don't know anything about this hash"
Just (True,_) -> return h
Just (False,af@(fp,hoh,idep,ho)) -> do
fp <- shortenPath fp
isGood <- iocatch ( mapM_ cdep (hoDepends idep) >> mapM_ hvalid (hoModDepends idep) >> return True) (\_ -> return False)
let isStale = not . null $ map (show . fst) (hoDepends idep) `intersect` optStale options
libsGood = all (\ (p,h) -> fmap (libHash) (Map.lookup p (loadedLibraries done)) == Just h) (hohLibDeps hoh)
noGood forced = do
putProgressLn $ printf "Stale: <%s>%s" fp forced
modifyIORef hom_ref (Map.delete h)
fail "stale file"
case (isStale,isGood && libsGood) of
(False,True) -> do
putProgressLn $ printf "Fresh: <%s>" fp
hs <- mapM f (hoModuleGroupNeeds idep)
modifyIORef cug_ref ((h,(hs ++ hoModDepends idep,CompHo hoh idep ho)):)
modifyIORef hom_ref (Map.insert h (True,af))
return h
(True,_) -> noGood " (forced)"
(_,False) -> noGood ""
cdep (_,hash) | hash == MD5.emptyHash = return ()
cdep (mod,hash) = case Map.lookup mod sources of
Just hash' | hash == hash' -> return ()
_ -> fail "Can't verify module up to date"
fs m = case Map.lookup m (modEncountered done) of
Just (Found sc) -> sc
_ -> error $ "fs: " ++ show m
mapM_ f (map inject roots)
cug <- readIORef cug_ref
let (rhash,cug') = mkPhonyCompUnit roots cug
let gr = G.newGraph cug' fst (fst . snd)
gr' = G.transitiveReduction gr
when (dump FD.SccModules) $ do
putErrLn "ComponentsDeps:"
mapM_ (putErrLn . show) [ (snd $ snd v, map (snd . snd) vs) | (v,vs) <- G.fromGraph gr']
return (rhash,[ (h,([ d | (d,_) <- ns ],cu)) | ((h,(_,cu)),ns) <- G.fromGraph gr' ])
parseFiles
:: Opt -- ^ Options to use when parsing files
-> [FilePath] -- ^ Targets we are building, used when dumping dependencies
-> [Either Module FilePath] -- ^ Either a module or filename to find
-> (CollectedHo -> Ho -> IO CollectedHo) -- ^ Process initial ho loaded from file
-> (CollectedHo -> Ho -> TiData -> IO (CollectedHo,Ho)) -- ^ Process set of mutually recursive modules to produce final Ho
-> IO (CompNode,CollectedHo) -- ^ Final accumulated ho
parseFiles options targets need ifunc func = do
putProgressLn "Finding Dependencies..."
(ksm,chash,cug) <- loadModules options targets (optionLibs options) bogusASrcLoc need
cnode <- processCug cug chash
when (optStop options == StopParse) exitSuccess
performGC
putProgressLn "Typechecking..."
typeCheckGraph options cnode
if isJust (optAnnotate options) then exitSuccess else do
when (optStop options == StopTypeCheck) exitSuccess
performGC
putProgressLn "Compiling..."
cho <- compileCompNode ifunc func ksm cnode
return (cnode,cho)
-- this takes a list of modules or files to load, and produces a compunit graph
loadModules
:: Opt -- ^ Options to use when parsing files
-> [FilePath] -- ^ targets
-> [String] -- ^ libraries to load
-> SrcLoc -- ^ where these files are requsted from
-> [Either Module FilePath] -- ^ a list of modules or filenames
-> IO (Map.Map SourceHash (Module,[(Module,SrcLoc)]),HoHash,CompUnitGraph) -- ^ the resulting acyclic graph of compilation units
loadModules modOpt targets libs sloc need = do
theCache <- findHoCache
case theCache of
Just s -> putProgressLn $ printf "Using Ho Cache: '%s'" s
Nothing -> return ()
done_ref <- newIORef Done {
hoCache = theCache,
knownSourceMap = Map.empty,
validSources = Set.empty,
loadedLibraries = Map.empty,
hosEncountered = Map.empty,
modEncountered = Map.empty
}
(es,is,allLibraries) <- collectLibraries libs
let combModMap es = Map.unions [ Map.map ((,) l) (hoModuleMap $ libHoLib l) | l <- es]
explicitModMap = combModMap es
implicitModMap = combModMap is
reexported = Set.fromList [ m | l <- es, (m,_) <- Map.toList $ hoReexports (libHoLib l) ]
modEnc exp emap = Map.fromList [ (m,ModLibrary (exp || Set.member m reexported) mg l) | (m,(l,mg)) <- Map.toList emap ]
modifyIORef done_ref (loadedLibraries_u $ Map.union $ Map.fromList [ (libBaseName lib,lib) | lib <- es ++ is])
modifyIORef done_ref (modEncountered_u $ Map.union (modEnc True explicitModMap))
modifyIORef done_ref (modEncountered_u $ Map.union (modEnc False implicitModMap))
forM_ (concatMap libExtraFiles (es ++ is)) $ \ef -> do
fileInTempDir ("cbits/" ++ unpackPS (extraFileName ef)) $ \fn -> BS.writeFile fn (extraFileData ef)
done <- readIORef done_ref
forM_ (Map.elems $ loadedLibraries done) $ \ lib -> do
let libsBad = filter (\ (p,h) -> fmap (libHash) (Map.lookup p (loadedLibraries done)) /= Just h) (hohLibDeps $ libHoHeader lib)
unless (null libsBad) $ do
putErr $ printf "Library Dependencies not met. %s needs\n" (libName lib)
forM_ libsBad $ \ (p,h) -> putErr $ printf " %s (hash:%s)\n" (unpackPS p) (show h)
putErrDie "\n"
ms1 <- forM (rights need) $ \fn -> do
fetchSource modOpt done_ref [fn] Nothing
forM_ (map (,sloc) $ lefts need) $ resolveDeps modOpt done_ref
ws <- getIOErrors
let (missingModuleErrors,otherErrors) = partition isMissingModule ws
f (Warning { warnType = MissingModule m ml, warnSrcLoc }:ws) mp = f ws $ Map.insertWith comb m (maybeToList ml,[warnSrcLoc]) mp
f (_:ws) mp = f ws mp
f [] mp = mp
comb (ma,wsa) (mb,wsb) = (ma ++ mb,wsa ++ wsb)
mmmap = f missingModuleErrors Map.empty
unless (Map.null mmmap) $ do
forM_ (Map.toList mmmap) $ \ (mod,(ml,wss)) -> do
mapM_ (putErrLn . (++ ":") . show) (snub wss)
putErrLn $ printf " Attempt to import unknown module '%s'" (show mod)
case snub ml of
xs@(_:_) -> forM_ xs $ \x -> putErrLn $ printf " It is exported by '%s', perhaps you need -p%s on the command line." x x
[] -> forM_ (concat [ take 1 [ z | z <- l, let hl = libHoLib z,
mod `Map.member` hoModuleMap hl || mod `Map.member` hoReexports hl] | l <- Map.elems allLibraries]) $ \l -> do
putErrLn $ printf " It is exported by '%s', perhaps you need -p%s on the command line." (libName l) (unpackPS $ libBaseName l)
processErrors otherErrors
exitFailure
processErrors otherErrors
done <- readIORef done_ref
let needed = (ms1 ++ lefts need)
(chash,cug) <- toCompUnitGraph done needed
dumpDeps targets done cug
return (Map.filterWithKey (\k _ -> k `Set.member` validSources done) (knownSourceMap done),chash,cug)
isMissingModule Warning { warnType = MissingModule {} } = True
isMissingModule _ = False
-- turn the list of CompUnits into a true mutable graph.
processCug :: CompUnitGraph -> HoHash -> IO CompNode
processCug cug root = mdo
let mmap = Map.fromList xs
lup x = maybe (error $ "processCug: " ++ show x) id (Map.lookup x mmap)
f (h,(ds,cu)) = do
cur <- newIORef (CompLinkUnit cu)
return $ (h,CompNode h (map lup ds) cur)
xs <- mapM f cug
Just x <- return $ Map.lookup root mmap
return $ x
mkPhonyCompUnit :: [Module] -> CompUnitGraph -> (HoHash,CompUnitGraph)
mkPhonyCompUnit need cs = (fhash,(fhash,(fdeps,CompDummy)):cs) where
fhash = MD5.md5String $ show (sort fdeps)
fdeps = [ h | (h,(_,cu)) <- cs, not . null $ providesModules cu `intersect` need ]
printModProgress :: Int -> Int -> IO Int -> [HsModule] -> IO ()
printModProgress _ _ _ [] = return ()
printModProgress _ _ tickProgress ms | not progress = mapM_ (const tickProgress) ms
printModProgress fmtLen maxModules tickProgress ms = f "[" ms where
f bl ms = do
curModule <- tickProgress
case ms of
[x] -> g curModule bl "]" x
(x:xs) -> do g curModule bl "-" x; putErrLn ""; f "-" xs
_ -> error "Build.printModProgress: bad."
g curModule bl el modName = putErr $ printf "%s%*d of %*d%s %-17s" bl fmtLen curModule fmtLen maxModules el (show $ hsModuleName modName)
countNodes cn = do
seen <- newIORef Set.empty
let h (CompNode hh deps ref) = do
s <- readIORef seen
if hh `Set.member` s then return Set.empty else do
writeIORef seen (Set.insert hh s)
ds <- mapM h deps
cm <- readIORef ref >>= g
return (Set.unions (cm:ds))
g cn = case cn of
CompLinkUnit cu -> return $ f cu
CompTcCollected _ cu -> return $ f cu
CompCollected _ cu -> return $ f cu
CompLinkLib _ _ -> error "Build.countNodes: bad."
f cu = case cu of
CompTCed (_,_,_,ss) -> Set.fromList ss
CompSources sc -> Set.fromList (map sourceIdent sc)
_ -> Set.empty
h cn
typeCheckGraph :: Opt -> CompNode -> IO ()
typeCheckGraph modOpt cn = do
cur <- newMVar (1::Int)
maxModules <- Set.size `fmap` countNodes cn
let f (CompNode hh deps ref) = readIORef ref >>= \cn -> case cn of
CompTcCollected ctc _ -> return ctc
CompLinkUnit lu -> do
deps' <- randomPermuteIO deps
ctc <- mconcat `fmap` mapM f deps'
case lu of
CompDummy -> do
writeIORef ref (CompTcCollected ctc CompDummy)
return ctc
CompHo hoh idep ho -> do
let ctc' = hoTcInfo ho `mappend` ctc
writeIORef ref (CompTcCollected ctc' lu)
return ctc'
CompLibrary ho _libr -> do
let ctc' = hoTcInfo ho `mappend` ctc
writeIORef ref (CompTcCollected ctc' lu)
return ctc'
CompSources sc -> do
let mods = sort $ map (sourceModName . sourceInfo) sc
modules <- forM sc $ \x -> case x of
SourceParsed { sourceInfo = si, sourceModule = sm } ->
return (sourceHash si, sm, error "SourceParsed in AnnotateSource")
SourceRaw { sourceInfo = si, sourceLBS = lbs } -> do
(mod,lbs') <- parseHsSource modOpt (sourceFP si) lbs
case optAnnotate modOpt of
Just fp -> do
let ann = LBSU.fromString $ unlines [
"{- --ANNOTATE--",
"Module: " ++ show (sourceModName si),
"Deps: " ++ show (sort $ fsts $ sourceDeps si),
"Siblings: " ++ show mods,
"-}"]
LBS.writeFile (fp ++ "/" ++ show (hsModuleName mod) ++ ".hs") (ann `LBS.append` lbs')
_ -> return ()
return (sourceHash si,mod,lbs')
showProgress (map snd3 modules)
(htc,tidata) <- doModules ctc (map snd3 modules)
let ctc' = htc `mappend` ctc
writeIORef ref (CompTcCollected ctc' (CompTCed ((htc,tidata,[ (x,y) | (x,y,_) <- modules],map (sourceHoName . sourceInfo) sc))))
return ctc'
_ -> error "Build.typeCheckGraph: bad1."
_ -> error "Build.typeCheckGraph: bad2."
showProgress ms = printModProgress fmtLen maxModules tickProgress ms
fmtLen = ceiling (logBase 10 (fromIntegral maxModules+1) :: Double) :: Int
tickProgress = modifyMVar cur $ \val -> return (val+1,val)
f cn
return ()
compileCompNode :: (CollectedHo -> Ho -> IO CollectedHo) -- ^ Process initial ho loaded from file
-> (CollectedHo -> Ho -> TiData -> IO (CollectedHo,Ho)) -- ^ Process set of mutually recursive modules to produce final Ho
-> Map.Map SourceHash (Module,[(Module,SrcLoc)])
-> CompNode
-> IO CollectedHo
compileCompNode ifunc func ksm cn = do
cur <- newMVar (1::Int)
ksm_r <- newIORef ksm
let tickProgress = modifyMVar cur $ \val -> return (val+1,val)
maxModules <- Set.size `fmap` countNodes cn
let showProgress ms = printModProgress fmtLen maxModules tickProgress ms
fmtLen = ceiling (logBase 10 (fromIntegral maxModules+1) :: Double) :: Int
let f (CompNode hh deps ref) = readIORef ref >>= g where
g cn = case cn of
CompCollected ch _ -> return ch
CompTcCollected _ cl -> h cl
CompLinkUnit cu -> h cu
_ -> error "Build.compileCompNode: bad."
h cu = do
deps' <- randomPermuteIO deps
cho <- mconcat `fmap` mapM f deps'
case cu of
CompDummy -> do
writeIORef ref (CompCollected cho CompDummy)
return cho
(CompHo hoh idep ho) -> do
cho <- choLibDeps_u (Map.union $ Map.fromList (hohLibDeps hoh)) `fmap` ifunc cho ho
writeIORef ref (CompCollected cho cu)
return cho
(CompLibrary ho Library { libHoHeader = hoh }) -> do
cho <- ifunc cho ho
let Right (ln,_) = hohName hoh
lh = hohHash hoh
cho' = (choLibDeps_u (Map.insert ln lh) cho)
writeIORef ref (CompCollected cho' cu)
return cho'
CompTCed ((htc,tidata,modules,shns)) -> do
(hdep,ldep) <- fmap mconcat . forM deps $ \ (CompNode h _ ref) -> do
cl <- readIORef ref
case compLinkCompUnit cl of
CompLibrary ho _ -> return ([],[hoModuleGroup ho])
CompDummy {} -> return ([],[])
_ -> return ([h],[])
showProgress (snds modules)
let (mgName:_) = sort $ map (hsModuleName . snd) modules
(cho',newHo) <- func cho mempty { hoModuleGroup = mgName, hoTcInfo = htc } tidata
modifyIORef ksm_r (Map.union $ Map.fromList [ (h,(hsModuleName mod, hsModuleRequires mod)) | (h,mod) <- modules])
ksm <- readIORef ksm_r
let hoh = HoHeader {
hohVersion = error "hohVersion",
hohName = Left mgName,
hohHash = hh,
hohArchDeps = [],
hohLibDeps = Map.toList (choLibDeps cho')
}
idep = HoIDeps {
hoIDeps = ksm,
hoDepends = [ (hsModuleName mod,h) | (h,mod) <- modules],
hoModDepends = hdep,
hoModuleGroupNeeds = ldep
}
recordHoFile (mapHoBodies eraseE newHo) idep shns hoh
writeIORef ref (CompCollected cho' (CompHo hoh idep newHo))
return cho'
CompSources _ -> error "sources still exist!?"
f cn
hsModuleRequires x = snub ((mod_JhcPrimPrim,bogusASrcLoc):ans) where
noPrelude = FO.Prelude `Set.notMember` optFOptsSet (hsModuleOpt x)
ans = (if noPrelude then id else ((mod_Prelude,bogusASrcLoc):)) [ (hsImportDeclModule y,hsImportDeclSrcLoc y) | y <- hsModuleImports x]
searchPaths :: Opt -> String -> [(String,String)]
searchPaths modOpt m = ans where
f m | (xs,'.':ys) <- span (/= '.') m = let n = (xs FP.</> ys) in m:f n
| otherwise = [m]
ans = [ (root ++ suf,root ++ ".ho") | i <- optIncdirs modOpt, n <- f m, suf <- [".hs",".lhs",".hsc"], let root = FP.normalise $ i FP.</> n]
mapHoBodies :: (E -> E) -> Ho -> Ho
mapHoBodies sm ho = ho { hoBuild = g (hoBuild ho) } where
g ho = ho { hoEs = map f (hoEs ho) , hoRules = runIdentity (E.Rules.mapBodies (return . sm) (hoRules ho)) }
f (t,e) = (t,sm e)
eraseE :: E -> E
eraseE e = runIdentity $ f e where
f (EVar tv) = return $ EVar tvr { tvrIdent = tvrIdent tv }
f e = emapE f e
---------------------------------
-- library specific routines
---------------------------------
buildLibrary :: (CollectedHo -> Ho -> IO CollectedHo)
-> (CollectedHo -> Ho -> TiData -> IO (CollectedHo,Ho)) -- ^ Process set of mutually recursive modules to produce final Ho
-> FilePath
-> IO ()
buildLibrary ifunc func fp = do
(desc,name,vers,hmods,emods,modOpts,sources) <- parseYamlFile fp
vers <- runReadP parseVersion vers
let allMods = emodSet `Set.union` hmodSet
emodSet = Set.fromList emods
hmodSet = Set.fromList hmods
let outName = case optOutName modOpts of
Nothing -> name ++ "-" ++ showVersion vers ++ ".hl"
Just fn -> fn
-- TODO - must check we depend only on libraries
(rnode@(CompNode lhash _ _),cho) <- parseFiles modOpts [outName] (map Left $ Set.toList allMods) ifunc func
(_,(mmap,mdeps,prvds,lcor,ldef)) <- let
f (CompNode hs cd ref) = do
cl <- readIORef ref
case cl of
CompLinkLib l _ -> return l
CompCollected _ y -> g hs cd ref y
_ -> error "Build.buildLibrary: bad1."
g hh deps ref cn = do
deps <- mapM f deps
let (mg,mll) = case cn of
CompDummy -> (error "modgroup of dummy",mempty)
CompLibrary ho lib -> (hoModuleGroup ho,mempty)
CompHo hoh hidep ho -> (mg,(
Map.fromList $ zip (providesModules hidep) (repeat mg),
Map.singleton mg (sort $ fsts deps),
Set.fromList $ providesModules hidep,
Map.singleton mg (hoBuild ho'),
Map.singleton mg (hoTcInfo ho')
)) where
mg = hoModuleGroup ho
ho' = mapHoBodies eraseE ho
_ -> error "Build.buildLibrary: bad2."
res = (mg,mconcat (snds deps) `mappend` mll)
writeIORef ref (CompLinkLib res cn)
return res
in f rnode
let unknownMods = Set.toList $ Set.filter (`Set.notMember` allMods) prvds
mapM_ ((putStrLn . ("*** Module depended on in library that is not in export list: " ++)) . show) unknownMods
mapM_ ((putStrLn . ("*** We are re-exporting the following modules from other libraries: " ++)) . show) $ Set.toList (allMods Set.\\ prvds)
let hoh = HoHeader {
hohHash = lhash,
hohName = Right (packString name,vers),
hohLibDeps = Map.toList (choLibDeps cho),
hohArchDeps = [],
hohVersion = error "hohVersion"
}
let pdesc = [(packString n, packString v) | (n,v) <- ("jhc-hl-filename",outName):("jhc-description-file",fp):("jhc-compiled-by",versionString):desc, n /= "exposed-modules" ]
libr = HoLib {
hoReexports = Map.fromList [ (m,m) | m <- Set.toList $ allMods Set.\\ prvds ],
hoMetaInfo = pdesc,
hoModuleMap = mmap,
hoModuleDeps = mdeps
}
putProgressLn $ "Writing Library: " ++ outName
efs <- mapM fetchExtraFile sources
recordHlFile Library { libHoHeader = hoh, libHoLib = libr, libTcMap = ldef,
libBuildMap = lcor, libFileName = outName, libExtraFiles = efs }
-- parse library description file
parseYamlFile fp = do
putProgressLn $ "Creating library from description file: " ++ show fp
(LibDesc dlist dsing,modOpts) <- readYamlOpts options fp
when verbose2 $ do
mapM_ print (Map.toList dlist)
mapM_ print (Map.toList dsing)
let jfield x = maybe (fail $ "createLibrary: description lacks required field " ++ show x) return $ Map.lookup x dsing
mfield x = maybe [] id $ Map.lookup x dlist
--mfield x = maybe [] (words . map (\c -> if c == ',' then ' ' else c)) $ Map.lookup x dlist
name <- jfield "name"
vers <- jfield "version"
putVerboseLn $ show (optFOptsSet modOpts)
let hmods = map toModule $ snub $ mfield "hidden-modules"
emods = map toModule $ snub $ mfield "exposed-modules"
sources = map (FP.takeDirectory fp FP.</>) $ snub $ mfield "c-sources" ++ mfield "include-sources"
return (Map.toList dsing,name,vers,hmods,emods,modOpts,sources)
fetchExtraFile fp = do
c <- BS.readFile fp
return ExtraFile { extraFileName = packString (FP.takeFileName fp),
extraFileData = c }
------------------------------------
-- dumping contents of a ho file
------------------------------------
instance DocLike d => PPrint d MD5.Hash where
pprint h = tshow h
instance DocLike d => PPrint d SrcLoc where
pprint sl = tshow sl
instance DocLike d => PPrint d Version where
pprint sl = text $ showVersion sl
instance DocLike d => PPrint d PackedString where
pprint sl = text (unpackPS sl)
{-# NOINLINE dumpHoFile #-}
dumpHoFile :: String -> IO ()
dumpHoFile fn = ans where
ans = do
putStrLn fn
case reverse fn of
'l':'h':'.':_ -> doHl fn
'o':'h':'.':_ -> doHo fn
_ -> putErrDie "Error: --show-ho requires a .hl or .ho file"
vindent xs = vcat (map (" " ++) xs)
showList nm xs = when (not $ null xs) $ putStrLn $ (nm ++ ":\n") <> vindent xs
doHoh hoh = do
putStrLn $ "Version:" <+> pprint (hohVersion hoh)
putStrLn $ "Hash:" <+> pprint (hohHash hoh)
putStrLn $ "Name:" <+> pprint (hohName hoh)
showList "LibDeps" (map pprint . sortUnder fst $ hohLibDeps hoh)
showList "ArchDeps" (map pprint . sortUnder fst $ hohArchDeps hoh)
doHl fn = do
l <- readHlFile fn
doHoh $ libHoHeader l
showList "MetaInfo" (sort [text (unpackPS k) <> char ':' <+> show v |
(k,v) <- hoMetaInfo (libHoLib l)])
showList "ModuleMap" (map pprint . sortUnder fst $ Map.toList $ hoModuleMap $ libHoLib l)
showList "ModuleDeps" (map pprint . sortUnder fst $ Map.toList $ hoModuleDeps $ libHoLib l)
showList "ModuleReexports" (map pprint . sortUnder fst $ Map.toList $ hoReexports $ libHoLib l)
forM_ (Map.toList $ libBuildMap l) $ \ (g,hoB) -> do
print g
doHoB hoB
doHo fn = do
(hoh,idep,ho) <- readHoFile fn
doHoh hoh
let hoB = hoBuild ho
hoE = hoTcInfo ho
showList "Dependencies" (map pprint . sortUnder fst $ hoDepends idep)
showList "ModDependencies" (map pprint $ hoModDepends idep)
showList "IDepCache" (map pprint . sortUnder fst $ Map.toList $ hoIDeps idep)
putStrLn $ "Modules contained:" <+> tshow (keys $ hoExports hoE)
putStrLn $ "number of definitions:" <+> tshow (size $ hoDefs hoE)
putStrLn $ "hoAssumps:" <+> tshow (size $ hoAssumps hoE)
putStrLn $ "hoFixities:" <+> tshow (size $ hoFixities hoE)
putStrLn $ "hoKinds:" <+> tshow (size $ hoKinds hoE)
putStrLn $ "hoClassHierarchy:" <+> tshow (length $ classRecords $ hoClassHierarchy hoE)
putStrLn $ "hoTypeSynonyms:" <+> tshow (size $ hoTypeSynonyms hoE)
wdump FD.Exports $ do
putStrLn "---- exports information ----";
putStrLn $ (pprint $ hoExports hoE :: String)
wdump FD.Defs $ do
putStrLn "---- defs information ----";
putStrLn $ (pprint $ hoDefs hoE :: String)
when (dump FD.Kind) $ do
putStrLn "---- kind information ----";
putStrLn $ (pprint $ hoKinds hoE :: String)
when (dump FD.ClassSummary) $ do
putStrLn "---- class summary ---- "
printClassSummary (hoClassHierarchy hoE)
when (dump FD.Class) $
do {putStrLn "---- class hierarchy ---- ";
printClassHierarchy (hoClassHierarchy hoE)}
wdump FD.Types $ do
putStrLn " ---- the types of identifiers ---- "
putStrLn $ PPrint.render $ pprint (hoAssumps hoE)
doHoB hoB
doHoB hoB = do
putStrLn $ "hoDataTable:" <+> tshow (size $ hoDataTable hoB)
putStrLn $ "hoEs:" <+> tshow (size $ hoEs hoB)
putStrLn $ "hoRules:" <+> tshow (size $ hoRules hoB)
let rules = hoRules hoB
wdump FD.Rules $ putStrLn " ---- user rules ---- " >> printRules RuleUser rules
wdump FD.Rules $ putStrLn " ---- user catalysts ---- " >> printRules RuleCatalyst rules
wdump FD.RulesSpec $ putStrLn " ---- specializations ---- " >> printRules RuleSpecialization rules
wdump FD.Datatable $ do
putStrLn " ---- data table ---- "
putDocM putStr (showDataTable (hoDataTable hoB))
putChar '\n'
wdump FD.Core $ do
putStrLn " ---- lambdacube ---- "
mapM_ (\ (v,lc) -> putChar '\n' >> printCheckName'' (hoDataTable hoB) v lc) (hoEs hoB)
printCheckName'' :: DataTable -> TVr -> E -> IO ()
printCheckName'' _dataTable tvr e = do
when (dump FD.EInfo || verbose2) $ putStrLn (show $ tvrInfo tvr)
putStrLn (render $ hang 4 (pprint tvr <+> text "::" <+> pprint (tvrType tvr)))
putStrLn (render $ hang 4 (pprint tvr <+> equals <+> pprint e))
|
hvr/jhc
|
src/Ho/Build.hs
|
mit
| 42,275 | 0 | 45 | 13,245 | 13,914 | 6,994 | 6,920 | -1 | -1 |
module TestData where
import Data.IntMap as IMap
import Data.Set as Set
data Codegen = C | JS deriving (Show, Eq, Ord)
type Index = Int
data CompatCodegen = ANY | C_CG | NODE_CG | NONE
-- A TestFamily groups tests that share the same theme
data TestFamily = TestFamily {
-- A shorter lowcase name to use in filenames
id :: String,
-- A proper name for the test family that will be displayed
name :: String,
-- A map of test metadata:
-- - The key is the index (>=1 && <1000)
-- - The value is the set of compatible code generators,
-- or Nothing if the test doesn't depend on a code generator
tests :: IntMap (Maybe (Set Codegen))
} deriving (Show)
toCodegenSet :: CompatCodegen -> Maybe (Set Codegen)
toCodegenSet compatCodegen = fmap Set.fromList mList where
mList = case compatCodegen of
ANY -> Just [ C, JS ]
C_CG -> Just [ C ]
NODE_CG -> Just [ JS ]
NONE -> Nothing
testFamilies :: [TestFamily]
testFamilies = fmap instantiate testFamiliesData where
instantiate (id, name, testsData) = TestFamily id name tests where
tests = IMap.fromList (fmap makeSetCodegen testsData)
makeSetCodegen (index, codegens) = (index, toCodegenSet codegens)
testFamiliesForCodegen :: Codegen -> [TestFamily]
testFamiliesForCodegen codegen =
fmap (\testFamily -> testFamily {tests = IMap.filter f (tests testFamily)})
testFamilies
where
f mCodegens = case mCodegens of
Just codegens -> Set.member codegen codegens
Nothing -> True
-- The data to instanciate testFamilies
-- The first column is the id
-- The second column is the proper name (the prefix of the subfolders)
-- The third column is the data for each test
testFamiliesData :: [(String, String, [(Index, CompatCodegen)])]
testFamiliesData = [
("base", "Base",
[ ( 1, C_CG )]),
("basic", "Basic",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 4, ANY ),
( 5, ANY ),
( 6, ANY ),
( 7, C_CG ),
( 8, ANY ),
( 9, ANY ),
( 10, ANY ),
( 11, C_CG ),
( 12, ANY ),
( 13, ANY ),
( 14, ANY ),
( 15, ANY ),
( 16, ANY ),
( 17, ANY ),
( 18, ANY ),
( 19, ANY ),
( 20, ANY ),
( 21, C_CG ),
( 22, NODE_CG ),
( 23, ANY ),
( 24, ANY ),
( 25, ANY ),
( 26, ANY )]),
("bignum", "Bignum",
[ ( 1, ANY ),
( 2, ANY ),
( 3, C_CG )]),
("bounded", "Bounded",
[ ( 1, ANY )]),
("buffer", "Buffer",
[ ( 1, C_CG ),
( 2, C_CG )]),
("contrib", "Contrib",
[ ( 1, C_CG )]),
("corecords", "Corecords",
[ ( 1, ANY ),
( 2, ANY )]),
("delab", "De-elaboration",
[ ( 1, ANY )]),
("directives", "Directives",
[ ( 1, ANY ),
( 2, ANY ),
( 3, C_CG )]),
("disambig", "Disambiguation",
[ ( 2, ANY )]),
("docs", "Documentation",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 4, ANY ),
( 5, ANY ),
( 6, ANY )]),
("dsl", "DSL",
[ ( 1, ANY ),
( 2, C_CG ),
( 3, ANY ),
( 4, ANY )]),
("effects", "Effects",
[ ( 1, C_CG ),
( 2, C_CG ),
( 3, ANY ),
( 4, ANY ),
( 5, ANY )]),
("error", "Errors",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 4, ANY ),
( 5, ANY ),
( 6, ANY ),
( 7, ANY ),
( 8, ANY ),
( 9, ANY )]),
("ffi", "FFI",
[ ( 1, ANY )
, ( 2, ANY )
, ( 3, ANY )
, ( 4, ANY )
, ( 5, ANY )
, ( 6, C_CG )
, ( 7, C_CG )
, ( 8, C_CG )
, ( 9, C_CG )
, ( 10, NODE_CG )
, ( 11, NODE_CG )
, ( 12, NODE_CG )
, ( 13, C_CG )
]),
("folding", "Folding",
[ ( 1, ANY )]),
("idrisdoc", "Idris documentation",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 4, ANY ),
( 5, ANY ),
( 6, ANY ),
( 7, ANY ),
( 8, ANY ),
( 9, ANY )]),
("interactive", "Interactive editing",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 4, ANY ),
( 5, ANY ),
( 6, ANY ),
( 7, ANY ),
( 8, ANY ),
( 9, ANY ),
( 10, ANY ),
( 11, ANY ),
( 12, ANY ),
( 13, ANY ),
( 14, C_CG ),
( 15, ANY ),
( 16, ANY ),
-- FIXME: Re-enable interactive017 once it works with and without node.
-- FIXME: See https://github.com/idris-lang/Idris-dev/pull/4046#issuecomment-326910042
-- ( 17, ANY ),
( 18, ANY )]),
("interfaces", "Interfaces",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 4, ANY ),
-- ( 5, ANY ),
( 6, ANY ),
( 7, ANY ),
( 8, ANY ),
-- ( 9, ANY ),
( 10, ANY )]),
("interpret", "Interpret",
[ ( 1, ANY ),
( 2, ANY ),
( 3, C_CG )]),
("io", "IO monad",
[ ( 1, C_CG ),
( 2, ANY ),
( 3, C_CG )]),
("layout", "Layout",
[ ( 1, ANY )]),
("literate", "Literate programming",
[ ( 1, ANY )]),
("meta", "Meta-programming",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 4, ANY )]),
("pkg", "Packages",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 4, ANY ),
( 5, ANY ),
( 6, ANY ),
( 7, ANY ),
( 8, ANY ),
( 10, ANY )]),
("prelude", "Prelude",
[ ( 1, ANY )]),
("primitives", "Primitive types",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 5, C_CG ),
( 6, C_CG )]),
("proof", "Theorem proving",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 4, ANY ),
( 5, ANY ),
( 6, ANY ),
( 7, ANY ),
( 8, ANY ),
( 9, ANY ),
( 10, ANY ),
( 11, ANY )]),
("proofsearch", "Proof search",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY )]),
("pruviloj", "Pruviloj",
[ ( 1, ANY )]),
("quasiquote", "Quasiquotations",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 4, ANY ),
( 5, ANY ),
( 6, ANY )]),
("records", "Records",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 4, ANY ),
( 5, ANY )]),
("reg", "Regressions",
[ ( 1, ANY ),
( 2, ANY ),
( 4, ANY ),
( 5, ANY ),
( 13, ANY ),
( 16, ANY ),
( 17, ANY ),
( 20, ANY ),
( 24, ANY ),
( 25, ANY ),
( 27, ANY ),
( 29, C_CG ),
( 31, ANY ),
( 32, ANY ),
( 39, ANY ),
( 40, ANY ),
( 41, ANY ),
( 42, ANY ),
( 45, ANY ),
( 48, ANY ),
( 52, C_CG ),
( 67, ANY ),
( 75, ANY ),
( 76, ANY ),
( 77, ANY )]),
("regression", "Regression",
[ ( 1 , ANY ),
( 2 , ANY ),
( 3 , ANY )]),
("sourceLocation", "Source location",
[ ( 1 , ANY )]),
("st", "ST",
[ ( 1, C_CG),
( 2, C_CG),
( 3, C_CG),
( 4, C_CG),
( 5, C_CG),
( 6, C_CG),
( 7, C_CG)]),
("sugar", "Syntactic sugar",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 4, C_CG ),
( 5, ANY )]),
("syntax", "Syntax extensions",
[ ( 1, ANY ),
( 2, ANY )]),
("tactics", "Tactics",
[ ( 1, ANY )]),
("totality", "Totality checking",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 4, ANY ),
( 5, ANY ),
( 6, ANY ),
( 7, ANY ),
( 8, ANY ),
( 9, ANY ),
( 10, ANY ),
( 11, ANY ),
( 12, ANY ),
( 13, ANY ),
( 14, ANY ),
( 15, ANY ),
( 16, ANY ),
( 17, ANY ),
( 18, ANY ),
( 19, ANY ),
( 20, ANY ),
( 21, ANY ),
( 22, ANY ),
( 23, ANY ),
( 25, ANY ),
( 26, ANY )]),
("tutorial", "Tutorial examples",
[ ( 1, ANY ),
( 2, ANY ),
( 3, ANY ),
( 4, ANY ),
( 5, ANY ),
( 6, ANY ),
( 7, C_CG )]),
("unique", "Uniqueness types",
[ ( 1, ANY ),
( 4, ANY )]),
("universes", "Universes",
[ ( 1, ANY ),
( 2, ANY )]),
("views", "Views",
[ ( 1, ANY ),
( 2, ANY ),
( 3, C_CG )])]
|
kojiromike/Idris-dev
|
test/TestData.hs
|
bsd-3-clause
| 8,810 | 0 | 13 | 3,933 | 3,196 | 2,089 | 1,107 | 325 | 4 |
{-# OPTIONS -fglasgow-exts #-}
-- This one killed GHC 5.05 and earlier
-- The problem was in a newtype with a record selector, with
-- a polymorphic argument type. MkId generated a bogus selector
-- function
module ShouldCompile where
type M3 a = forall r. (forall b. M3' b -> (b -> M3' a) -> r) -> r
newtype M3' a = M3' { mkM3' :: M3 a }
flop :: forall a b. M3' b -> (b -> M3' a) -> Int
flop = \m' k -> mkM3' m' (\bm k1 -> error "urk")
-- Suppose mkM3' has the straightforward type:
-- mkM3' :: forall a. M3' a -> M3 a
-- Then (mkM3' m') :: forall r. (forall b. ...) -> r
-- If we simply do a subsumption check of this against
-- alpha -> Int
-- where alpha is the type inferred for (\bm k1 ...)
-- this won't work.
-- But if we give mkM3' the type
-- forall a r. M3' a -> (forall b. ...) -> r
-- everthing works fine. Very very delicate.
---------------- A more complex case -------------
bind :: M3 a -> (a -> M3 b) -> M3 b
bind m k b = b (M3' m) (\a -> M3' (k a))
observe :: M3 a -> a
observe m
= m (\m' k -> mkM3' m'
(\bm k1 -> observe (bind (mkM3' bm)
(\a -> bind (mkM3' (k1 a)) (\a -> mkM3' (k a)))))
)
|
hvr/jhc
|
regress/tests/1_typecheck/2_pass/ghc/tc163.hs
|
mit
| 1,198 | 0 | 21 | 334 | 320 | 177 | 143 | -1 | -1 |
{-# LANGUAGE PatternSynonyms, ViewPatterns #-}
module Foo (Foo(P)) where
data Foo a = Foo a
instance C Foo where
build a = Foo a
destruct (Foo a) = a
class C f where
build :: a -> f a
destruct :: f a -> a
pattern P :: C f => a -> f a
pattern P x <- (destruct -> x)
where
P x = build x
|
ezyang/ghc
|
testsuite/tests/patsyn/should_compile/poly-export.hs
|
bsd-3-clause
| 307 | 0 | 8 | 90 | 141 | 73 | 68 | 16 | 0 |
{-# LANGUAGE TypeFamilies #-}
module ShouldFail where
class C1 a where
data S1 a :: *
-- must fail: wrong category of type instance
instance C1 Int where
type S1 Int = Bool
|
siddhanathan/ghc
|
testsuite/tests/indexed-types/should_fail/SimpleFail3a.hs
|
bsd-3-clause
| 180 | 0 | 6 | 40 | 39 | 23 | 16 | 6 | 0 |
{-# LANGUAGE ExistentialQuantification #-}
-- Illegal existential context on a newtype
module ShouldFail where
newtype Foo = forall a . Foo a
|
ryantm/ghc
|
testsuite/tests/typecheck/should_fail/tcfail156.hs
|
bsd-3-clause
| 146 | 1 | 5 | 26 | 16 | 11 | 5 | 3 | 0 |
import qualified Attribute as A
attributeTypeOrdinal :: A.ComponentType -> Integer
attributeTypeOrdinal A.IntegerSigned = 0
attributeTypeOrdinal A.IntegerUnsigned = 1
attributeTypeOrdinal A.FloatingPoint = 2
|
io7m/smf
|
com.io7m.smfj.specification/src/main/resources/com/io7m/smfj/specification/attribute_map.hs
|
isc
| 212 | 0 | 6 | 26 | 48 | 26 | 22 | 5 | 1 |
module Day5Spec (spec) where
import Day5
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "day5" $ do
it "ugknbfddgicrmopn is nice because it has at least three vowels (u...i...o...), a double letter (...dd...), and none of the disallowed substrings." $ do
day5 "ugknbfddgicrmopn" `shouldBe` 1
it "aaa is nice because it has at least three vowels and a double letter, even though the letters used by different rules overlap." $ do
day5 "aaa" `shouldBe` 1
it "jchzalrnumimnmhp is naughty because it has no double letter." $ do
day5 "jchzalrnumimnmhp" `shouldBe` 0
it "haegwjzuvuyypxyu is naughty because it contains the string xy." $ do
day5 "haegwjzuvuyypxyu" `shouldBe` 0
it "dvszwmarrgswjxmb is naughty because it contains only one vowel." $ do
day5 "dvszwmarrgswjxmb" `shouldBe` 0
it "handles multiple lines of input." $ do
day5 (unlines ["ugknbfddgicrmopn", "aaa", "jchzalrnumimnmhp", "haegwjzuvuyypxyu", "dvszwmarrgswjxmb"]) `shouldBe` 2
describe "day5'" $ do
it "qjhvhtzxzqqjkmpb is nice because is has a pair that appears twice (qj) and a letter that repeats with exactly one letter between them (zxz)." $ do
day5' "qjhvhtzxzqqjkmpb" `shouldBe` 1
it "xxyxx is nice because it has a pair that appears twice and a letter that repeats with one between, even though the letters used by each rule overlap." $ do
day5' "xxyxx" `shouldBe` 1
it "uurcxstgmygtbstg is naughty because it has a pair (tg) but no repeat with a single letter between them." $ do
day5' "uurcxstgmygtbstg" `shouldBe` 0
it "ieodomkazucvgmuy is naughty because it has a repeating letter with one between (odo), but no pair that appears twice." $ do
day5' "ieodomkazucvgmuy" `shouldBe` 0
it "handles multiple lines of input" $ do
day5' (unlines ["qjhvhtzxzqqjkmpb", "xxyxx", "uurcxstgmygtbstg", "ieodomkazucvgmuy"]) `shouldBe` 2
|
brianshourd/adventOfCode2015
|
test/Day5Spec.hs
|
mit
| 2,074 | 0 | 17 | 527 | 346 | 168 | 178 | 31 | 1 |
-- Problem 17
--
-- If the numbers 1 to 5 are written out in words: one, two, three, four,
-- five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
--
-- If all the numbers from 1 to 1000 (one thousand) inclusive were written
-- out in words, how many letters would be used?
euler17 = length1To1000
length1To1000 =
(length "one") + lengthThousand + length1To999
length1To999 =
(length1To9 * 100) + (lengthHundred * 9) + (lengthHundredAnd * 9 * 99) + (10 * length1To99)
length1To99 =
length1To9 + length10To19 + (8 * length1To9) + (length10s * 10)
length1To9 =
length "one" + length "two" + length "three" + length "four"
+ length "five" + length "six" + length "seven" + length "eight"
+ length "nine"
length10To19 =
length "ten" + length "eleven" + length "twelve" + length "thirteen"
+ length "fourteen" + length "fifteen" + length "sixteen"
+ length "seventeen" + length "eighteen"
+ length "nineteen"
length10s =
length "twenty" + length "thirty" + length "forty" +
length "fifty" + length "sixty" + length "seventy" +
length "eighty" + length "ninety"
lengthHundred = length "hundred"
lengthHundredAnd = lengthHundred + (length "and")
lengthThousand = length "thousand"
|
RossMeikleham/Project-Euler-Haskell
|
17.hs
|
mit
| 1,261 | 0 | 14 | 279 | 335 | 164 | 171 | 23 | 1 |
-- Part B also
-- Does part A in 11s, part B in ~20m
--
import Control.Monad
import Data.List.Extra
import Data.Maybe
import qualified Data.Char as C
import qualified Data.Map as Map
--
--import qualified Data.Sequence as S
--import Data.Sequence ((<|), (|>), (><), ViewL(..))
import Debug.Trace
--------
{-
type Queue a = ([a], [a])
revApp [] ys = ys
revApp (x:xs) ys = revApp xs (x:ys)
enq (f, b) x = (f, revApp x b)
view ([], []) = Nothing
view (x:xs, b) = Just (x, (xs, b))
view ([], b) = view (reverse b, [])
qFromList x = (x, [])
-}
-------------
stuff = map sort $ [
["SG", "SM", "PG", "PM"],
["TG", "RG", "RM", "CG", "CM"],
["TM"],
[]]
stuff_b = map sort $ [
["SG", "SM", "PG", "PM", "EG", "EM", "DG", "DM"],
["TG", "RG", "RM", "CG", "CM"],
["TM"],
[]]
stuff' = map sort $ [
["HM", "LM"],
["HG"],
["LG"],
[]]
stuff'' = map sort $ [
["HM", "HG"],
[],
[],
[]]
oneThings xs =
do x <- xs
return [x]
twoThings xs =
do x <- xs
y <- xs \\ [x]
return [x, y]
things xs = oneThings xs ++ twoThings xs
replaceAtIndex n item ls = a ++ (item:b) where (a, (_:b)) = splitAt n ls
thingsmatch (x:"M") (y:"G") = x == y
thingsmatch _ _ = False
thingsbreak (x:"M") (y:"G") = x /= y
thingsbreak _ _ = False
linesafe xs = all (\x -> if (x !! 1) == 'M' then
any (thingsmatch x) xs || not (any (thingsbreak x) xs)
else True) xs
done [[], [], [], _] = True
done _ = False
--next :: Table -> (Int, (Int, [[String]])) -> [(Int, (Int, [[String]]))]
next map ((i, state)) =
do guard $ Map.notMember (i, state) map
let xs = state !! i
parts <- things xs
i' <- [i-1, i+1]
guard $ i' >= 0 && i' <= 3
-- guard $ length parts == 1 || i' == i+1
let state' = replaceAtIndex i (xs \\ parts) (replaceAtIndex i' (sort (parts ++ (state !! i'))) state)
guard $ all linesafe state'
guard $ Map.notMember (i', state') map
return (i', state')
type Table = Map.Map (Int, [[String]]) ()
traceNus x = traceShow x x
--traceA = traceShow
traceA a b = b
search k seen ([], stuff) = traceShow (k, Map.size seen, length nextStuff) $
search (k+1) seen (nextStuff, [])
where nextStuff = concat stuff
search k seen (st:rest, stuff) =
if done (snd st) then k else
search k seen' $ (rest, next seen st : stuff)
where seen' = Map.insert st () seen
searchStart st = search 0 Map.empty ([((0,st))], [])
{-
-- This was a previous version that relied on next keep track of lengths
search seen nus = case S.viewl nus of
(k,st) :< rest ->
if done (snd st) then k else
search seen' $ rest >< (S.fromList $ next seen (k,st))
where seen' = Map.insert st () seen
searchStart st = search Map.empty (S.fromList [(0,(0,stuff))])
-}
main = putStrLn $ show $ searchStart stuff_b
|
msullivan/advent-of-code
|
2016/A11a.hs
|
mit
| 2,850 | 0 | 18 | 743 | 1,022 | 558 | 464 | 66 | 2 |
module Main (
main
) where
import Diagrams.Prelude
import Render
diagram = circle 1
main = defaultMain diagram
|
leksah/leksah-diagrams-hello
|
src/Main.hs
|
mit
| 118 | 0 | 5 | 25 | 33 | 19 | 14 | 6 | 1 |
{-# LANGUAGE RankNTypes, OverloadedStrings, FlexibleContexts #-}
module FTag.AtomicSets.Operations where
import Data.Maybe
import Control.Exception (throw)
import Env
import FTag.Data
import FTag.DB
import FTag.AtomicSets.SpecialTags
atomicToStor :: UserAtomicSet -> FTag StorAtomicSet
atomicToStor = runInDB . c
where c (UASPreset n) = SASPreset . fromJust <$> presetIDByName n
c (UASTag n) = SASTag . fromJust <$> tagIDByName n
c (UASSpecial n) = return $ SASSpecial n
c (UASByName n) = do -- TODO: Rewrite this with Alternative
if isSpecial n
then return $ SASSpecial n
else do
mp <- presetIDByName n
case mp of
(Just id) -> return $ SASPreset id
Nothing -> do
mt <- tagIDByName n
case mt of
(Just id) -> return $ SASTag id
Nothing -> throw $ FTNoSuchTag n
|
chrys-h/ftag
|
src/FTag/AtomicSets/Operations.hs
|
mit
| 966 | 0 | 21 | 326 | 263 | 132 | 131 | 25 | 7 |
module PNM where
import qualified Data.ByteString.Lazy.Char8 as L8
import qualified Data.ByteString.Lazy as L
import Data.Char (isSpace)
data GreyMap = GreyMap {greyWidth, greyHeight, greyMax :: Int, greyData :: L.ByteString}
deriving (Eq)
instance Show GreyMap where
show (GreyMap w h m _) = "GreyMap" ++ show w ++ "x" ++ show h ++ " " ++ show m
parseP5 :: L.ByteString -> Maybe (GreyMap, L.ByteString)
parseP5 s =
case matchHeader (L8.pack "P5") s of
Nothing -> Nothing
Just s1 ->
case getNat s1 of
Nothing -> Nothing
Just (width, s2) ->
case getNat (L8.dropWhile isSpace s2) of
Nothing -> Nothing
Just (height, s3) ->
case getNat (L8.dropWhile isSpace s3) of
Nothing -> Nothing
Just (maxGrey, s4)
| maxGrey > 255 -> Nothing
| otherwise ->
case getBytes 1 s4 of
Nothing -> Nothing
Just (_, s5) ->
case getBytes (width * height) s5 of
Nothing -> Nothing
Just (bitmap, s6) ->
Just (GreyMap width height maxGrey bitmap, s6)
matchHeader :: L.ByteString -> L.ByteString -> Maybe L.ByteString
matchHeader prefix str
| prefix `L8.isPrefixOf` str = Just (L8.dropWhile isSpace (L.drop (L.length prefix) str))
| otherwise = Nothing
getNat :: L.ByteString -> Maybe (Int, L.ByteString)
getNat s = case L8.readInt s of
Nothing -> Nothing
Just (num,rest)
| num <= 0 -> Nothing
| otherwise -> Just (fromIntegral num, rest)
getBytes :: Int -> L.ByteString -> Maybe (L.ByteString, L.ByteString)
getBytes n str = let count = fromIntegral n
both@(prefix, _) = L.splitAt count str
in if L.length prefix < count
then Nothing
else Just both
-- removing boilerplate code
-- this is for the pattern that checks for a Nothing or returns the unwrapped result
(>>?) :: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing >>? _ = Nothing
Just v >>? f = f v
infixl 9 >>? -- default settings
-- second attempt to write our parser
parseP5_take2 :: L.ByteString -> Maybe (GreyMap, L.ByteString)
parseP5_take2 s =
matchHeader (L8.pack "P5") s >>?
\s -> skipSpace ((),s) >>?
(getNat . snd) >>?
skipSpace >>?
\(width, s) -> getNat s >>?
skipSpace >>?
\(height, s) -> getNat s >>?
\(maxGrey, s) -> getBytes 1 s >>?
(getBytes (width * height) . snd)>>?
\(bitmap, s) -> Just (GreyMap width height maxGrey bitmap, s)
skipSpace :: (a, L.ByteString) -> Maybe (a, L.ByteString)
skipSpace (a, s) = Just (a, L8.dropWhile isSpace s)
|
cirquit/Personal-Repository
|
Haskell/RWH/PGMParser/PNM.hs
|
mit
| 2,967 | 0 | 26 | 1,071 | 983 | 512 | 471 | 65 | 7 |
import qualified Data.Map as M
import qualified Data.ByteString.Lazy as L
import Network.HTTP.Conduit
import Control.Monad.IO.Class
type Query = M.Map String [String]
main = search "http://localhost:9200/" M.empty >>= L.putStr
search :: MonadIO m => String -> Query -> m L.ByteString
search uri query = simpleHttp uri
|
fabianvf/hselasticsearch
|
client.hs
|
mit
| 321 | 0 | 9 | 47 | 103 | 58 | 45 | 8 | 1 |
module DestinationType where
import System.IO.Unsafe
import Data.Unique
import Data.List
import qualified Data.Map as HM
import TypeSystem
destinationType :: Package -> Term -> Term
destinationType pkg (Var variable) = case flowTermByVar (pkg_getRule pkg) (Var variable) of
Nothing -> checkIfPatternMatched
Just anotherVar -> anotherVar
where
checkIfPatternMatched = case patternMatchByVar (pkg_getRule pkg) (Var variable) of
Nothing -> (Var variable)
Just premise -> destinationType pkg (reverseMatch pkg premise)
destinationType pkg (Constructor c terms) = (Constructor c (map (destinationType pkg) terms))
destinationType pkg (Application term1 term2) = (Application (destinationType pkg term1) (destinationType pkg term2))
destinationType pkg (Bound variable) = (Bound variable)
flowTermByVar :: Rule -> Term -> Maybe Term
flowTermByVar rule term = case searchPremiseByPredAndVar rule "flow" term of { Nothing -> Nothing ; Just (Formula pred strings interms outterms) -> Just (interms !! 1) }
makeFlow :: Term -> Term -> Premise
makeFlow = \type1 -> \type2 -> Formula "flow" [] [type1, type2] []
-- Given a pattern-maching variable, it searches its pattern-matching premise in the rule
patternMatchByVar :: Rule -> Term -> Maybe Premise
patternMatchByVar rule term = searchPremiseByPredAndVar rule "match" term
-- Given a pattern-matching premise, gives you the entire term. Care is given to put contravariant terms at their place.
reverseMatch :: Package -> Premise -> Term
reverseMatch pkg (Formula pred strings interms outterms) = if pred == "match" then (Constructor (head strings) outterms) else error "reverseMatch called with an argument that is not pattern-matching premise"
|
mcimini/GradualizerDynamicSemantics
|
DestinationType.hs
|
mit
| 1,935 | 0 | 12 | 483 | 485 | 251 | 234 | 24 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Data.Text.Extended (
module Data.Text
, constTimeCompare
) where
import Data.Bits
import Data.Char
import Data.Function (on)
import qualified Data.List as L
import Data.Text
import Prelude hiding (length, zip)
constTimeCompare :: Text -> Text -> Bool
constTimeCompare l r = length l == length r && comp' l r
where
comp' a b = 0 == L.foldl' (.|.) 0 (uncurry (on xor ord) <$> zip a b)
|
juretta/haskell-jwt
|
src/Data/Text/Extended.hs
|
mit
| 518 | 0 | 13 | 163 | 156 | 87 | 69 | 13 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : AI.Clustering.Hierarchical.Internal
-- Copyright : (c) 2015 Kai Zhang
-- License : MIT
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
--------------------------------------------------------------------------------
module AI.Clustering.Hierarchical.Internal
{-# WARNING "To be used by developer only" #-}
( nnChain
, single
, complete
, average
, weighted
, ward
) where
import Control.Monad (forM_, when)
import qualified Data.Map as M
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import AI.Clustering.Hierarchical.Types
type ActiveNodeSet = M.Map Int (Dendrogram Int)
type DistUpdateFn = Int -> Int -> ActiveNodeSet -> DistanceMat -> DistanceMat
-- | nearest neighbor chain algorithm
nnChain :: DistanceMat -> DistUpdateFn -> Dendrogram Int
nnChain (DistanceMat n dist) fn = go (DistanceMat n $ U.force dist) initSet []
where
go ds activeNodes chain@(b:a:rest)
| M.size activeNodes == 1 = head . M.elems $ activeNodes
| c == a = go ds' activeNodes' rest
| otherwise = go ds activeNodes $ c : chain
where
(c,d) = nearestNeighbor ds b a activeNodes
-- We always remove the node with smaller index. The other one will be
-- used to represent the merged result
activeNodes' = M.insert hi (Branch (size1+size2) d c1 c2)
. M.delete lo $ activeNodes
ds' = fn lo hi activeNodes ds
c1 = M.findWithDefault undefined lo activeNodes
c2 = M.findWithDefault undefined hi activeNodes
size1 = size c1
size2 = size c2
(lo,hi) = if a <= b then (a,b) else (b,a)
go ds activeNodes _ = go ds activeNodes [b,a]
where
a = fst $ M.elemAt 0 activeNodes
b = fst $ nearestNeighbor ds a (-1) activeNodes
initSet = M.fromList . map (\i -> (i, Leaf i)) $ [0..n-1]
{-# INLINE nnChain #-}
nearestNeighbor :: DistanceMat -- ^ distance matrix
-> Int -- ^ query
-> Int -- ^ this would be selected if
-- it achieves the minimal distance
-> M.Map Int (Dendrogram Int)
-> (Int, Double)
nearestNeighbor dist i preference = M.foldlWithKey' f (-1,1/0)
where
f (x,d) j _ | i == j = (x,d) -- skip
| d' < d = (j,d')
| d' == d && j == preference = (j,d')
| otherwise = (x,d)
where d' = dist ! (i,j)
{-# INLINE nearestNeighbor #-}
-- | all update functions perform destructive updates, and hence should not be
-- called by end users
-- | single linkage update formula
single :: DistUpdateFn
single lo hi nodeset (DistanceMat n dist) = DistanceMat n $ U.create $ do
v <- U.unsafeThaw dist
forM_ (M.keys nodeset) $ \i -> when (i/= hi && i/=lo) $ do
d_lo_i <- UM.unsafeRead v $ idx n i lo
d_hi_i <- UM.unsafeRead v $ idx n i hi
UM.unsafeWrite v (idx n i hi) $ min d_lo_i d_hi_i
return v
{-# INLINE single #-}
-- | complete linkage update formula
complete :: DistUpdateFn
complete lo hi nodeset (DistanceMat n dist) = DistanceMat n $ U.create $ do
v <- U.unsafeThaw dist
forM_ (M.keys nodeset) $ \i -> when (i/= hi && i/=lo) $ do
d_lo_i <- UM.unsafeRead v $ idx n i lo
d_hi_i <- UM.unsafeRead v $ idx n i hi
UM.unsafeWrite v (idx n i hi) $ max d_lo_i d_hi_i
return v
{-# INLINE complete #-}
-- | average linkage update formula
average :: DistUpdateFn
average lo hi nodeset (DistanceMat n dist) = DistanceMat n $ U.create $ do
v <- U.unsafeThaw dist
forM_ (M.keys nodeset) $ \i -> when (i/= hi && i/=lo) $ do
d_lo_i <- UM.unsafeRead v $ idx n i lo
d_hi_i <- UM.unsafeRead v $ idx n i hi
UM.unsafeWrite v (idx n i hi) $ f1 * d_lo_i + f2 * d_hi_i
return v
where
s1 = fromIntegral . size . M.findWithDefault undefined lo $ nodeset
s2 = fromIntegral . size . M.findWithDefault undefined hi $ nodeset
f1 = s1 / (s1+s2)
f2 = s2 / (s1+s2)
{-# INLINE average #-}
-- | weighted linkage update formula
weighted :: DistUpdateFn
weighted lo hi nodeset (DistanceMat n dist) = DistanceMat n $ U.create $ do
v <- U.unsafeThaw dist
forM_ (M.keys nodeset) $ \i -> when (i/= hi && i/=lo) $ do
d_lo_i <- UM.unsafeRead v $ idx n i lo
d_hi_i <- UM.unsafeRead v $ idx n i hi
UM.unsafeWrite v (idx n i hi) $ (d_lo_i + d_hi_i) / 2
return v
{-# INLINE weighted #-}
-- | ward linkage update formula
ward :: DistUpdateFn
ward lo hi nodeset (DistanceMat n dist) = DistanceMat n $ U.create $ do
v <- U.unsafeThaw dist
d_lo_hi <- UM.unsafeRead v $ idx n lo hi
forM_ (M.toList nodeset) $ \(i,t) -> when (i/= hi && i/=lo) $ do
let s3 = fromIntegral . size $ t
d_lo_i <- UM.unsafeRead v $ idx n i lo
d_hi_i <- UM.unsafeRead v $ idx n i hi
UM.unsafeWrite v (idx n i hi) $
((s1+s3)*d_lo_i + (s2+s3)*d_hi_i - s3*d_lo_hi) / (s1+s2+s3)
return v
where
s1 = fromIntegral . size . M.findWithDefault undefined lo $ nodeset
s2 = fromIntegral . size . M.findWithDefault undefined hi $ nodeset
{-# INLINE ward #-}
{-
-- O(n^2) time, O(n) space. Minimum spanning tree algorithm for single linkage
mst :: [a] -> DistFn a -> Dendrogram a
mst xs fn = undefined
-}
|
kaizhang/clustering
|
src/AI/Clustering/Hierarchical/Internal.hs
|
mit
| 5,558 | 0 | 22 | 1,570 | 1,888 | 958 | 930 | 101 | 3 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
module Yi.Prelude
(
(<>),
(++), -- consider scrapping this and replacing it by the above
(=<<),
Double,
Char,
Either(..),
Endom,
Eq(..),
Fractional(..),
Functor(..),
IO,
Integer,
Integral(..),
Bounded(..),
Enum(..),
Maybe(..),
Monad(..),
Num(..),
Ord(..),
Read(..),
Real(..),
RealFrac(..),
ReaderT(..),
SemiNum(..),
String,
commonPrefix,
every,
fromIntegral,
fst,
fst3,
groupBy',
list,
head,
init,
io,
last,
lookup,
mapAdjust',
mapAlter',
module Control.Applicative,
module Control.Category,
module Data.Accessor,
module Data.Accessor.Monad.FD.State, putA, getA, modA,
module Data.Bool,
module Data.Foldable,
module Data.Function,
module Data.Int,
module Data.Rope,
module Data.Traversable,
module Text.Show,
module Yi.Debug,
module Yi.Monad,
nubSet,
null,
print,
putStrLn,
replicate,
read,
seq,
singleton,
snd,
snd3,
tail,
trd3,
undefined,
unlines,
when,
writeFile -- because Data.Derive uses it.
) where
import Prelude hiding (any, all)
import Yi.Debug
import Yi.Monad
import qualified Data.Accessor.Basic
import Text.Show
import Data.Bool
import Data.Foldable
import Data.Function hiding ((.), id)
import Data.Int
import Data.Rope (Rope)
import Control.Category
import Control.Monad.Reader
import Control.Applicative
import Data.Traversable
import Control.Monad
import Data.Monoid
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Control.Monad.State.Class as CMSC
import qualified Data.Accessor.Basic as Accessor
import Data.Accessor ((<.), accessor, getVal, setVal, Accessor,(^.),(^:),(^=))
import qualified Data.Accessor.Monad.FD.State as Accessor.FD
import Data.Accessor.Monad.FD.State ((%:), (%=))
type Endom a = a -> a
(<>) :: Monoid a => a -> a -> a
(<>) = mappend
io :: MonadIO m => IO a -> m a
io = liftIO
fst3 :: (a,b,c) -> a
fst3 (x,_,_) = x
snd3 :: (a,b,c) -> b
snd3 (_,x,_) = x
trd3 :: (a,b,c) -> c
trd3 (_,_,x) = x
class SemiNum absolute relative | absolute -> relative where
(+~) :: absolute -> relative -> absolute
(-~) :: absolute -> relative -> absolute
(~-) :: absolute -> absolute -> relative
singleton :: a -> [a]
singleton x = [x]
-- 'list' is the canonical list destructor as 'either' or 'maybe'.
list :: b -> (a -> [a] -> b) -> [a] -> b
list nil _ [] = nil
list _ cons (x:xs) = cons x xs
-- TODO: move somewhere else.
-- | As 'Prelude.nub', but with O(n*log(n)) behaviour.
nubSet :: (Ord a) => [a] -> [a]
nubSet xss = f Set.empty xss where
f _ [] = []
f s (x:xs) = if x `Set.member` s then f s xs else x : f (Set.insert x s) xs
-- | As Map.adjust, but the combining function is applied strictly.
mapAdjust' :: (Ord k) => (a -> a) -> k -> Map.Map k a -> Map.Map k a
mapAdjust' f = Map.alter f' where
f' Nothing = Nothing
f' (Just x) = let x' = f x in x' `seq` Just x'
-- This works because Map is structure-strict, and alter needs to force f' to compute
-- the structure.
-- | As Map.alter, but the newly inserted element is forced with the map.
mapAlter' :: Ord k => (Maybe a -> Maybe a) -> k -> Map.Map k a -> Map.Map k a
mapAlter' f = Map.alter f' where
f' arg = case f arg of
Nothing -> Nothing
Just x -> x `seq` Just x
-- This works because Map is structure-strict, and alter needs to force f' to compute
-- the structure.
-- | Alternative to groupBy.
--
-- > groupBy' (\a b -> abs (a - b) <= 1) [1,2,3] = [[1,2,3]]
--
-- whereas
--
-- > groupBy (\a b -> abs (a - b) <= 1) [1,2,3] = [[1,2],[3]]
--
-- TODO: Check in ghc 6.12 release if groupBy == groupBy'.
groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy' _ [] = []
groupBy' p l = s1 : groupBy' p s2 where
(s1, s2) = chain p l
chain :: (a -> a -> Bool) -> [a] -> ([a],[a])
chain _ [] = ([], [])
chain _ [e] = ([e], [])
chain q (e1 : es@(e2 : _))
| q e1 e2 = let (s1, s2) = chain q es in (e1 : s1, s2)
| otherwise = ([e1], es)
----------------------
-- Accessors support
-- | Lift an accessor to a traversable structure. (This can be seen as a
-- generalization of fmap)
every :: Traversable t => Accessor whole part -> Accessor (t whole) (t part)
every a = accessor (fmap (getVal a)) (\parts wholes -> zipWithT (setVal a) parts wholes)
-- | zipWith, generalized to Traversable structures.
zipWithT :: Traversable t => (a -> b -> c) -> t a -> t b -> t c
zipWithT f ta tb = result
where step [] _ = Yi.Debug.error "zipT: non matching structures!"
step (b:bs) a = (bs,f a b)
([], result) = mapAccumL step (toList tb) ta
-- | Return the longest common prefix of a set of lists.
--
-- > P(xs) === all (isPrefixOf (commonPrefix xs)) xs
-- > length s > length (commonPrefix xs) --> not (all (isPrefixOf s) xs)
commonPrefix :: Eq a => [[a]] -> [a]
commonPrefix [] = []
commonPrefix strings
| any null strings = []
| all (== prefix) heads = prefix : commonPrefix tailz
| otherwise = []
where
(heads, tailz) = unzip [(h,t) | (h:t) <- strings]
prefix = head heads
-- for an alternative implementation see GHC's InteractiveUI module.
-----------------------
-- Acessor stuff
putA :: CMSC.MonadState r m => Accessor.T r a -> a -> m ()
putA = Accessor.FD.set
getA :: CMSC.MonadState r m => Accessor.T r a -> m a
getA = Accessor.FD.get
modA :: CMSC.MonadState r m => Accessor.T r a -> (a -> a) -> m ()
modA = Accessor.FD.modify
|
codemac/yi-editor
|
src/Yi/Prelude.hs
|
gpl-2.0
| 5,393 | 0 | 12 | 1,112 | 1,984 | 1,147 | 837 | 158 | 3 |
module Desugar (
desugar
)where
import Syntax
desugar :: [Toplevel] -> [CoreToplevel]
desugar = map desugarTop
desugarTop :: Toplevel -> CoreToplevel
desugarTop (TopVarDef n t e) = CTopVarDef n t (desugarExpr e )
desugarTop (TopFunDef n as t e) = CTopVarDef n t' e'
where aNames = map fst as
aTypes = map snd as
t' = foldr TyFun t aTypes
e' = foldr (\(n, t) acc -> CLam n t acc) (desugarExpr e) as
desugarExpr :: Expr -> CoreExpr
desugarExpr e = case e of
If c t e -> CIf (desugarExpr c) (desugarExpr t) (desugarExpr e)
Op op l r -> CApp (CApp (CVar (opName op)) (desugarExpr l)) (desugarExpr r)
Lit l -> CLit l
Str s -> CStr s
BoolConst b -> CBool b
Var v -> CVar v
Lam n t e -> CLam n t (desugarExpr e)
Funcall n as -> foldl (\n a -> CApp n (desugarExpr a)) (desugarExpr n) as
Let n d e -> CLet n (desugarExpr d) (desugarExpr e)
Block xs -> seqs xs
where seqs [x] = desugarExpr x
seqs (x:xs) = desugarExpr x `CSeq` seqs xs
opName :: String -> String
opName op = case op of
"==" -> "$__equal__$"
"/=" -> "$__notequal_$"
"<<" -> "$__shiftl__$"
">>" -> "$__shiftr__$"
"&" -> "$__and__$"
"|" -> "$__or__$"
"^" -> "$__xor__$"
"<" -> "$__lower__$"
">" -> "$__greater__$"
"+" -> "$__add__$"
"-" -> "$__sub__$"
"*" -> "$__mult__$"
"/" -> "$__div__$"
"%" -> "$__mod__$"
|
dosenfrucht/beagle
|
src/Desugar.hs
|
gpl-2.0
| 1,630 | 0 | 14 | 607 | 597 | 295 | 302 | 42 | 14 |
module Sivi.Operation.FromGCodeSpec (
spec
) where
import Test.Hspec
import Linear
import Sivi
import Sivi.IR
spec :: SpecWith ()
spec = describe "fromGCode" $
it "transforms a simple program into an operation" $ do
let program =
GCode [ g00 {x = Just 10, y = Just 20}
, g00 {z = Just 30 }
, g01 {x = Just 5, f = Just 100}
, g00 {x = Just 2, y = Just 1, z = Just 0}
, g03 {x = Just (-2), y = Just (-1), i = Just (-2), j = Just (-1)}
, g00 {x = Just 1, y = Just (-1), z = Just 1}
, g02 {x = Just (-3), y = Just 1, i = Just (-2), j = Just 1}
, g00 {x = Just 4, y = Just 0, z = Just 0}
, g38d2 {x = Just 3, f = Just 10}
, g92 {x = Just 0}
, gcomment { getComment = "Hello, world!" }
, m00
, g00 {x = Just 1, y = Just 0, z = Just 0}
]
let expectedOutput =
IR [ Move (V3 10 20 0) Rapid
, Move (V3 10 20 30) Rapid
, Move (V3 5 20 30) (LinearInterpolation 100)
, Move (V3 2 1 0) Rapid
, Move (V3 (-2) (-1) 0) (Arc CCW (V3 0 0 0) 100)
, Move (V3 1 (-1) 1) Rapid
, Move (V3 (-3) 1 1) (Arc CW (V3 (-1) 0 1) 100)
, Move (V3 4 0 0) Rapid
, Move (V3 3 0 0) (Probe 10)
, DefCurPos (V3 0 0 0)
, Comment "Hello, world!"
, Pause
, Move (V3 1 0 0) Rapid
]
runOperation defaultCuttingParameters (fromGCode program) `shouldBe` expectedOutput
|
iemxblog/sivi-haskell
|
tests/Sivi/Operation/FromGCodeSpec.hs
|
gpl-2.0
| 1,963 | 0 | 19 | 1,031 | 739 | 399 | 340 | 38 | 1 |
-- Difference between (sum x)^2 and sum(x^2) x from N
sumOfSquares = sum $ map (^2) [1..100]
squaredSum = (^2) $ sum [1..100]
main = do
return $ squaredSum - sumOfSquares
|
NaevaTheCat/Project-Euler-Haskell
|
P6.hs
|
gpl-2.0
| 174 | 0 | 8 | 34 | 62 | 34 | 28 | 4 | 1 |
{-
A Module to implement Vertical Rhythm in Css generated using clay
-}
{-# LANGUAGE OverloadedStrings #-}
module VerticalRhythmFunctions where
import Clay
import Control.Monad.State
import Data.Default
import Data.Maybe
-- | Type CSSState stores base_font_size, base_line_height, browser_default_font_size
data VerRhythm = VerRhythm {
baseFontSize :: Integer
, baseLineHeight :: Integer
, browserDefaultFontSize :: Integer
, minLinePadding :: Integer
, roundToHalfLine :: Bool
, defaultRhythmBorderStyle :: Stroke
}
instance Default VerRhythm where def = VerRhythm {
baseFontSize = 16
, baseLineHeight = 24
, browserDefaultFontSize = 16
, minLinePadding = 2
, roundToHalfLine = False
, defaultRhythmBorderStyle = solid
}
{-
USAGE : establishBaseline VerRhythm
verRhythm is the Vertical Rhythm State which gives the base variables as defined at the top of the module
This returns the CSS for the baseline
-}
establishBaseline :: VerRhythm -> Css
establishBaseline vr = baseline f h b
where
f = baseFontSize vr
h = baseLineHeight vr
b = browserDefaultFontSize vr
-- | returns baseline Css
baseline :: Integer -> Integer ->Integer -> Css
baseline x y z= do
--setting base Css
-- x is the base_font_size and y is the base_line_height and z is the browser_default_font_size
-- IE 6 refuses to resize fonts set in pixels and it weirdly resizes fonts
--whose root is set in ems. So we set the root font size in percentages of the default font size.
html|>body?
fontSize ( px x)
html ? do
fontSize (em p)
lineHeight (em k)
where
k = rhythm 1.0 x y 0
p= (realToFrac (x)) / (realToFrac 16)
-- | Calculates rhythm units
rhythm :: Double -> Integer-> Integer -> Integer -> Double
rhythm l f h o = ((l*realToFrac((h - o))) / realToFrac (f))
--l is the number of lines, f is the base_font_size, h is the base_line_height and o is the offset
{-
USAGE : toFontSize VerRhythm toSize lines fromSize
verRhythm is the Vertical Rhythm State which gives the base variables as defined at the top of the module
l specifies how many multiples of the baseline rhythm each line of this font should use up. It does not have to be an integer,
but it defaults to the smallest integer that is large enough to fit the font.
Use fromSize to adjust from a font-size other than the base font-size.
toSize is the targer font size
Adjust a block to have a different font size and line height to maintain the rhythm.
-}
toFontSize:: VerRhythm -> Integer -> Maybe Double -> Maybe Integer -> Css
toFontSize vr toSize lines fromSize = adjustFontSize toSize l1 f h
where
h = baseLineHeight vr
m = minLinePadding vr
r = roundToHalfLine vr
l1 = case lines of
Just k -> k
Nothing -> linesForFontSize toSize h m r
f = case fromSize of
Just k -> k
Nothing -> baseFontSize vr
-- | returns Css to adjust Fontsize of a element
adjustFontSize :: Integer -> Double -> Integer -> Integer -> Css
adjustFontSize t l f h = do
-- t is the to_font_size, l is the number of lines, f is the from_font_size, h is the baseline height
fontSize ( em k)
lineHeight (em s)
where
k= (realToFrac (t)) / (realToFrac f)
s=rhythm l t h 0
-- | Calculate the minimum multiple of rhythm units needed to contain the font-size.
linesForFontSize:: Integer-> Integer -> Integer -> Bool -> Double
linesForFontSize f h m r =
-- f is the to_fontsize, h is the base line height, m is the minimum line padding and r is the round_to_nearest_half_line
if (((l*realToFrac (h))) - realToFrac (f)) < (realToFrac(m*2))
then if r
then (l + 0.5)
else (l + 1.0)
else l
where
l = if r
then realToFrac(ceiling((realToFrac (f*2) / realToFrac (h))/2))
else realToFrac(ceiling(realToFrac (f) / realToFrac(h)))
{-
USAGE : leader verRhythm lines fSize property
verRhythm is the Vertical Rhythm State which gives the base variables as defined at the top of the module
line is Maybe type which takes in number of lines of verticalRhythm. If you give nothing it uses 1.0
fSize is the Mayhe type which is the font sie and if you give nothing it is the default base font size
property is either margin or trailer. If provided nothing takes as margin as the default type
Apply leading whitespace. The property can be margin or padding. By default property is margin
-}
leader:: VerRhythm -> Maybe Double-> Maybe Integer -> Maybe String -> Css
leader vr lines fSize property | property == (Just "padding") = paddingLeader vr lines fSize
| otherwise = marginLeader vr lines fSize
{-
USAGE : paddingLeader verRhythm lines fSize property
verRhythm is the Vertical Rhythm State which gives the base variables as defined at the top of the module
line is Maybe type which takes in number of lines of verticalRhythm. If you give nothing it uses 1.0
fSize is the Mayhe type which is the font sie and if you give nothing it is the default base font size
Apply leading whitespace as padding.
-}
paddingLeader:: VerRhythm -> Maybe Double-> Maybe Integer -> Css
paddingLeader vr lines fSize = paddingTop (em r)
where
l = fromMaybe 1.0 lines
f = fromMaybe (baseFontSize vr) fSize
r = rhythm l f (baseLineHeight vr) 0
{-
USAGE : marginLeader verRhythm lines fSize property
verRhythm is the Vertical Rhythm State which gives the base variables as defined at the top of the module
line is Maybe type which takes in number of lines of verticalRhythm. If you give nothing it uses 1.0
fSize is the Mayhe type which is the font sie and if you give nothing it is the default base font size
Apply leading whitespace as margin.
-}
marginLeader:: VerRhythm -> Maybe Double-> Maybe Integer -> Css
marginLeader vr lines fSize = marginTop (em r)
where
l = fromMaybe 1.0 lines
f = fromMaybe (baseFontSize vr) fSize
r = rhythm l f (baseLineHeight vr) 0
{-
USAGE : trailer verRhythm lines fSize property
verRhythm is the Vertical Rhythm State which gives the base variables as defined at the top of the module
line is Maybe type which takes in number of lines of verticalRhythm. If you give nothing it uses 1.0
fSize is the Mayhe type which is the font sie and if you give nothing it is the default base font size
property is either margin or trailer. If provided nothing takes as margin as the default type
Apply trailing whitespace. The property can be margin or padding. By default property is margin
-}
trailer:: VerRhythm -> Maybe Double-> Maybe Integer -> Maybe String -> Css
trailer vr lines fSize property | property == (Just "padding") = paddingTrailer vr lines fSize
| otherwise = marginTrailer vr lines fSize
{-
USAGE : paddingTrailer verRhythm lines fSize property
verRhythm is the Vertical Rhythm State which gives the base variables as defined at the top of the module
line is Maybe type which takes in number of lines of verticalRhythm. If you give nothing it uses 1.0
fSize is the Mayhe type which is the font sie and if you give nothing it is the default base font size
Apply trailing whitespace as padding.
-}
paddingTrailer:: VerRhythm -> Maybe Double-> Maybe Integer -> Css
paddingTrailer vr lines fSize = paddingBottom (em r)
where
l = fromMaybe 1.0 lines
f = fromMaybe (baseFontSize vr) fSize
r = rhythm l f (baseLineHeight vr) 0
{-
USAGE : marginTrailer verRhythm lines fSize property
verRhythm is the Vertical Rhythm State which gives the base variables as defined at the top of the module
line is Maybe type which takes in number of lines of verticalRhythm. If you give nothing it uses 1.0
fSize is the Mayhe type which is the font sie and if you give nothing it is the default base font size
Apply leading whitespace as padding.
-}
marginTrailer:: VerRhythm -> Maybe Double-> Maybe Integer -> Css
marginTrailer vr lines fSize = marginBottom (em r)
where
l = fromMaybe 1.0 lines
f = fromMaybe (baseFontSize vr) fSize
r = rhythm l f (baseLineHeight vr) 0
{-
USAGE : propertyRhythm verRhythm ml pl mt pt fSize
verRhythm is the Vertical Rhythm State which gives the base variables as defined at the top of the module
fSize is the Mayhe type which is the font sie and if you give nothing it is the default base font size
ml- the number of lines for leading margin whitespace with default value 0
pl- the number of lines for leading padding whitespace with default value 0
mt- the number of lines for trailing margin whitespace with default value 0
pt- the number of lines for trailing padding whitespace with default value 0
Shorthand function to apply whitespace for top and bottom margins and padding.
-}
propertyRhythm:: VerRhythm -> Maybe Double-> Maybe Double-> Maybe Double-> Maybe Double-> Maybe Integer -> Css
propertyRhythm vr ml pl mt pt fSize = do
-- ml is marginTop lines, pl is paddingTop lines,mt is marginBottom lines,pt is paddingBottom lines
marginLeader vr (Just ml1) fSize
paddingLeader vr (Just pl1) fSize
paddingTrailer vr (Just pt1) fSize
marginTrailer vr (Just mt1) fSize
where
ml1 = fromMaybe 0 ml
pl1 = fromMaybe 0 pl
mt1 = fromMaybe 0 mt
pt1 = fromMaybe 0 pt
{-
USAGE : applySideRhythmBorder verRhythm side w l fSize bs c
verRhythm is the Vertical Rhythm State which gives the base variables as defined at the top of the module
fSize is the Mayhe type which is the font sie and if you give nothing it is the default base font size
bs is the border style with the default value if send nothing in the VerRhythm data type
l- the number of lines for border with default value 1.0
s- it is the side on which border is to be applied
w is width and if send nothing has a default value of 1.0
c is the color and if send nothing uses default value of red
Apply a border & whitespace to any side without destroying the verticalrhythm.
The whitespace must be greater than the width of the border.
-}
applySideRhythmBorder:: VerRhythm-> String-> Maybe Integer-> Maybe Double-> Maybe Integer -> Maybe Stroke ->Maybe Color -> Css
applySideRhythmBorder vr side w l fSize bs c | side == "Left" = do borderLeft borderStyle (em w2) c1
paddingLeft (em r)
| side == "Top" = do borderTop borderStyle (em w2) c1
paddingTop (em r)
| side == "Bottom" = do borderBottom borderStyle (em w2) c1
paddingBottom (em r)
| side == "Right" = do borderRight borderStyle (em w2) c1
paddingRight (em r)
where
w1 = fromMaybe 1 w
l1 = fromMaybe 1.0 l
c1 = fromMaybe red c
fz = fromMaybe (baseFontSize vr) fSize
borderStyle = fromMaybe (defaultRhythmBorderStyle vr) bs
r = rhythm l1 fz (baseLineHeight vr) w1
w2 = realToFrac(w1) / realToFrac(fz)
{-
USAGE : rhythmBorders verRhythm w l fSize bs c
verRhythm is the Vertical Rhythm State which gives the base variables as defined at the top of the module
fSize is the Mayhe type which is the font sie and if you give nothing it is the default base font size
bs is the border style with the default value if send nothing in the VerRhythm data type
l- the number of lines for border with default value 1.0
s- it is the side on which border is to be applied
w is width and if send nothing has a default value of 1.0
c is the color and if send nothing uses default value of red
Apply borders and whitespace equally to all sides.
In the function w is width, l is number of line,fSize is font size, bs is borderstyle, c is the color
-}
rhythmBorders:: VerRhythm -> Maybe Integer -> Maybe Double -> Maybe Integer -> Maybe Stroke -> Maybe Color -> Css
rhythmBorders vr w l fSize bs c = do border borderStyle (em w3) c1
padding (em r) (em r) (em r) (em r)
where
l2 = fromMaybe 1.0 l
f2 = fromMaybe (baseFontSize vr) fSize
c1 = fromMaybe red c
borderStyle = fromMaybe (defaultRhythmBorderStyle vr) bs
w2 = fromMaybe 1 w
r = rhythm l2 f2 (baseLineHeight vr) w2
w3 = realToFrac(w2) / realToFrac(f2)
{-
USAGE : leadingBorder verRhythm width lines fSize borderStyle color
verRhythm is the Vertical Rhythm State which gives the base variables as defined at the top of the module
fSize is the Mayhe type which is the font sie and if you give nothing it is the default base font size
borderStyle is the border style with the default value if send nothing in the VerRhythm data type
l- the number of lines for border with default value 1.0
s- it is the side on which border is to be applied
width is width and if send nothing has a default value of 1.0
color is the color and if send nothing uses default value of red
Apply a leading border.
-}
leadingBorder :: VerRhythm -> Maybe Integer -> Maybe Double -> Maybe Integer -> Maybe Stroke -> Maybe Color ->Css
leadingBorder vr width lines fSize borderStyle color = applySideRhythmBorder vr "top" width lines fSize borderStyle color
{-
USAGE : trailingBorder verRhythm width lines fSize borderStyle color
verRhythm is the Vertical Rhythm State which gives the base variables as defined at the top of the module
fSize is the Mayhe type which is the font sie and if you give nothing it is the default base font size
borderStyle is the border style with the default value if send nothing in the VerRhythm data type
l- the number of lines for border with default value 1.0
s- it is the side on which border is to be applied
width is width and if send nothing has a default value of 1.0
color is the color and if send nothing uses default value of red
Apply a trailing border.
-}
trailingBorder :: VerRhythm -> Maybe Integer -> Maybe Double -> Maybe Integer -> Maybe Stroke -> Maybe Color ->Css
trailingBorder vr width lines fSize borderStyle color = applySideRhythmBorder vr "Bottom" width lines fSize borderStyle color
{-
USAGE : horizontalBorder verRhythm width lines fSize borderStyle color
verRhythm is the Vertical Rhythm State which gives the base variables as defined at the top of the module
fSize is the Mayhe type which is the font sie and if you give nothing it is the default base font size
borderStyle is the border style with the default value if send nothing in the VerRhythm data type
l- the number of lines for border with default value 1.0
s- it is the side on which border is to be applied
width is width and if send nothing has a default value of 1.0
color is the color and if send nothing uses default value of red
Apply both leading border and trailing border
-}
horizontalBorder :: VerRhythm -> Maybe Integer -> Maybe Double -> Maybe Integer -> Maybe Stroke -> Maybe Color ->Css
horizontalBorder vr width lines fSize borderStyle color = do leadingBorder vr width lines fSize borderStyle color
trailingBorder vr width lines fSize borderStyle color
-- |Alias for `horizontal_borders
hBorder :: VerRhythm -> Maybe Integer -> Maybe Double -> Maybe Integer -> Maybe Stroke -> Maybe Color ->Css
hBorder vr width lines fSize borderStyle color = horizontalBorder vr width lines fSize borderStyle color
|
pgarg22/Pottery
|
VerticalRhythmFunctions.hs
|
gpl-2.0
| 15,759 | 35 | 17 | 3,936 | 2,422 | 1,203 | 1,219 | 134 | 4 |
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings #-}
{-# OPTIONS_GHC -w #-}
module GTFS.Realtime.Internal.Com.Google.Transit.Realtime.VehiclePosition.CongestionLevel (CongestionLevel(..)) where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.List as Prelude'
import qualified Data.Typeable as Prelude'
import qualified GHC.Generics as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data CongestionLevel = UNKNOWN_CONGESTION_LEVEL
| RUNNING_SMOOTHLY
| STOP_AND_GO
| CONGESTION
| SEVERE_CONGESTION
deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data,
Prelude'.Generic)
instance P'.Mergeable CongestionLevel
instance Prelude'.Bounded CongestionLevel where
minBound = UNKNOWN_CONGESTION_LEVEL
maxBound = SEVERE_CONGESTION
instance P'.Default CongestionLevel where
defaultValue = UNKNOWN_CONGESTION_LEVEL
toMaybe'Enum :: Prelude'.Int -> P'.Maybe CongestionLevel
toMaybe'Enum 0 = Prelude'.Just UNKNOWN_CONGESTION_LEVEL
toMaybe'Enum 1 = Prelude'.Just RUNNING_SMOOTHLY
toMaybe'Enum 2 = Prelude'.Just STOP_AND_GO
toMaybe'Enum 3 = Prelude'.Just CONGESTION
toMaybe'Enum 4 = Prelude'.Just SEVERE_CONGESTION
toMaybe'Enum _ = Prelude'.Nothing
instance Prelude'.Enum CongestionLevel where
fromEnum UNKNOWN_CONGESTION_LEVEL = 0
fromEnum RUNNING_SMOOTHLY = 1
fromEnum STOP_AND_GO = 2
fromEnum CONGESTION = 3
fromEnum SEVERE_CONGESTION = 4
toEnum
= P'.fromMaybe
(Prelude'.error
"hprotoc generated code: toEnum failure for type GTFS.Realtime.Internal.Com.Google.Transit.Realtime.VehiclePosition.CongestionLevel")
. toMaybe'Enum
succ UNKNOWN_CONGESTION_LEVEL = RUNNING_SMOOTHLY
succ RUNNING_SMOOTHLY = STOP_AND_GO
succ STOP_AND_GO = CONGESTION
succ CONGESTION = SEVERE_CONGESTION
succ _
= Prelude'.error
"hprotoc generated code: succ failure for type GTFS.Realtime.Internal.Com.Google.Transit.Realtime.VehiclePosition.CongestionLevel"
pred RUNNING_SMOOTHLY = UNKNOWN_CONGESTION_LEVEL
pred STOP_AND_GO = RUNNING_SMOOTHLY
pred CONGESTION = STOP_AND_GO
pred SEVERE_CONGESTION = CONGESTION
pred _
= Prelude'.error
"hprotoc generated code: pred failure for type GTFS.Realtime.Internal.Com.Google.Transit.Realtime.VehiclePosition.CongestionLevel"
instance P'.Wire CongestionLevel where
wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum)
wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum)
wireGet 14 = P'.wireGetEnum toMaybe'Enum
wireGet ft' = P'.wireGetErr ft'
wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum
wireGetPacked ft' = P'.wireGetErr ft'
instance P'.GPB CongestionLevel
instance P'.MessageAPI msg' (msg' -> CongestionLevel) CongestionLevel where
getVal m' f' = f' m'
instance P'.ReflectEnum CongestionLevel where
reflectEnum
= [(0, "UNKNOWN_CONGESTION_LEVEL", UNKNOWN_CONGESTION_LEVEL), (1, "RUNNING_SMOOTHLY", RUNNING_SMOOTHLY),
(2, "STOP_AND_GO", STOP_AND_GO), (3, "CONGESTION", CONGESTION), (4, "SEVERE_CONGESTION", SEVERE_CONGESTION)]
reflectEnumInfo _
= P'.EnumInfo
(P'.makePNF (P'.pack ".transit_realtime.VehiclePosition.CongestionLevel") ["GTFS", "Realtime", "Internal"]
["Com", "Google", "Transit", "Realtime", "VehiclePosition"]
"CongestionLevel")
["GTFS", "Realtime", "Internal", "Com", "Google", "Transit", "Realtime", "VehiclePosition", "CongestionLevel.hs"]
[(0, "UNKNOWN_CONGESTION_LEVEL"), (1, "RUNNING_SMOOTHLY"), (2, "STOP_AND_GO"), (3, "CONGESTION"), (4, "SEVERE_CONGESTION")]
Prelude'.False
instance P'.TextType CongestionLevel where
tellT = P'.tellShow
getT = P'.getRead
|
romanofski/gtfsschedule
|
src/GTFS/Realtime/Internal/Com/Google/Transit/Realtime/VehiclePosition/CongestionLevel.hs
|
gpl-3.0
| 3,916 | 0 | 11 | 649 | 845 | 471 | 374 | 80 | 1 |
module Hadolint.Rule.DL3029 (rule) where
import Hadolint.Rule
import Language.Docker.Syntax
rule :: Rule args
rule = simpleRule code severity message check
where
code = "DL3029"
severity = DLWarningC
message = "Do not use --platform flag with FROM"
check (From BaseImage {platform = Just p}) = p == ""
check _ = True
{-# INLINEABLE rule #-}
|
lukasmartinelli/hadolint
|
src/Hadolint/Rule/DL3029.hs
|
gpl-3.0
| 366 | 0 | 13 | 79 | 101 | 56 | 45 | 10 | 2 |
{-# LANGUAGE NamedFieldPuns, ViewPatterns, MultiWayIf #-}
module Schafkopf.AI (GameState(..),
trumps,
trickRule,
play,
overbid) where
import Utility
import Utility.Cond
import Cards
import Trick.Rules
import Schafkopf.Score
import Schafkopf.GameTypes
import Prelude hiding ((||), (&&), not, or, and)
import Control.Applicative
import Data.List
data GameState = GameState
{
playerNames :: [String],
no :: Int,
player :: Maybe Int,
mate :: Maybe Int,
game :: GameType,
hands :: [Hand],
score :: Score,
takenTr :: Score,
rules :: [Hand -> PlayRule],
trRule :: TrickRule,
condRS :: Card -> Bool,
balance :: Score
}
-- no: index of the player who is about to start (intended to change)
-- player: index of the "Spieler" party player or Nothing if there is no player party.
-- hands: the players' cards (4-list) (intended to change)
-- score: the players' scores (4-tuple) (intended to change)
-- takenTr: the number of taken tricks.
-- rules: defines which card the player may pick (4-tuple) (only intended to change in Rufspiel)
-- trRule: the rule that specifies which card takes the trick (NOT intended to change)
-- condRS: (cryptic!) is necessary for Rufspiel to have a proper "run away" rule.
-- The predicate (fst) is intended to be "const False",
-- except in Rufspiel, where it is "(`notElem` normalTrumps) && suit $== s" and
-- is applied to the first card of the trick.
instance Show GameState where
show GameState
{
playerNames,
player,
mate,
game,
hands,
score,
takenTr,
balance
} =
"Spiel: " ++ show game ++ "\n" ++
"Spieler: " ++ (case player of Nothing -> "Niemand"; Just n -> playerNames!!n) ++ "\n" ++
-- "Spieler: " ++ (if isNothing player then "Nobody" else playerNames !! (fromJust player)) ++ "\n" ++
"Mitspieler: " ++ (case mate of Nothing -> "Niemand"; Just n -> playerNames!!n) ++ "\n" ++
(concat $ map playerdata [0..3])
where
playerdata n =
(playerNames !! n) ++ ": \n" ++
" Hand: " ++ showListNatural (hands !! n) ++ "\n" ++
" Score: " ++ show (score !! n) ++ "\n" ++
" Taken Tricks: " ++ show (takenTr !! n) ++ "\n" ++
" Win/Loss: " ++ show (balance !! n) ++ "\n"
defaultState :: [Hand] -> [Card] -> GameState
defaultState hands ts = GameState
{
playerNames = ["Du", "Alex", "Bernhard", "Caroline"],
no = 0,
game = Ramsch,
player = Just 0,
mate = Nothing,
hands,
rules = replicate 4 $ const $ cardAllowed ts,
trRule = normalTR,
condRS = const False,
score = replicate 4 0,
takenTr = replicate 4 0,
balance = replicate 4 0
}
overbid :: [Hand] -> GameType -> GameState
overbid = stupidOverbid
stupidOverbid :: [Hand] -> GameType -> GameState
stupidOverbid hs Ramsch = (defaultState hs normalTrumps)
{
no = 0,
player = Nothing,
game = Ramsch
}
stupidOverbid hands game@(Rufspiel calledSuit) = (defaultState hands normalTrumps)
{
no = 0,
player = Just 0,
mate = findIndex (elem $ Card calledSuit Ace) hands,
game = game,
rules = playerRulesRS calledSuit hands,
condRS = flip notElem normalTrumps && suit $== calledSuit
}
stupidOverbid hs game = (defaultState hs $ trumps game)
{
no = 0,
player = Just 0,
mate = Nothing,
game = game,
hands = hs,
trRule = trickRule game
}
type Trick = [Card]
play :: Trick -> Hand -> GameState -> IO Card
play = stupidPlay
stupidPlay :: Trick -> Hand -> GameState -> IO Card
stupidPlay _ h _ = return (head h)
trivialPlay :: Trick -> Hand -> GameState -> IO Card
trivialPlay _ [] _ = error "AI cannot play a card" -- this shall NEVER occur, fault by missing savatorian clause
trivialPlay _ [c] _ = return c
trivialPlay trick av GameState { game }
| game /= Ramsch = do
if trick `hasLength` 3
then let canOverbid = (== 4) <$> ( fst . (\c -> takesTrick (trickRule game) $ reverse (c : trick)) <$> av ) in
if | trickScore trick > 8 -> return $ head $ zipPred canOverbid av
| otherwise -> return $ head av
else do
return $ head av
| otherwise = return $ head av
|
Bolpat/CardGames
|
src/Schafkopf/AI.hs
|
gpl-3.0
| 4,973 | 0 | 22 | 1,839 | 1,167 | 647 | 520 | 101 | 3 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Main where
-- base, mtl, array, containers, random, monad-loops, ncurses, astar, hfov
import Control.Monad.State
import Data.Array.IArray
import Data.Array.IO
import Data.List (sortBy, find)
import Data.Ord (comparing)
import Data.Char
import qualified Data.Set as Set
import Data.Maybe
import System.Random
import qualified Data.List.Zipper as Z
import Control.Monad.Loops (iterateUntil)
import Data.Graph.AStar (aStar)
import UI.NCurses
import FOV
type Vector2 = (Int, Int)
type Room = (Vector2, Vector2) -- xy, size
type TileMapPart = [(Vector2, Char)] -- update for array
type TileMap = Array Vector2 Char
type Neighbours = Array Vector2 (Set.Set Vector2)
newtype GameT s m a = GameT (StateT s m a)
deriving (Functor, Monad, MonadIO, MonadTrans, MonadState s)
type Game = GameT GameState Curses
runGame1 :: GameState -> Game a -> Curses GameState
runGame1 s (GameT f) = execStateT f s
io :: IO a -> Game a
io = liftIO
curses :: Curses a -> Game a
curses = lift
data Side = T | B | L | R -- room sides
data ItemType = Weapon -- '|'
| Armor -- '['
| Potion -- '!'
| Scroll -- '?'
| Corpse -- '%'
| Food -- ','
deriving (Eq, Show, Read)
data ItemEffect = None
| Healing Int
| Death
| Teleport
| Yuck
| Transmute
deriving (Eq, Show, Read)
-- TODO: use this
data EntityStats = EntityStats
{ strength :: Int
, agility :: Int
, intelligence :: Int
, beauty :: Int
} deriving (Eq, Show, Read)
data Item = Item
{ iType :: ItemType
, iName :: String
, iSpeed :: Int
, iDamage :: Int
, iDefence :: Int
, iWeight :: Int -- mass in grams
, iEffect :: ItemEffect
, iCharge :: Int
} deriving (Eq, Show, Read)
data Inventory = Inventory
{ equWeapon :: Item
, equArmor :: Item
, equMisc :: Item
, storedItems :: [Item]
} deriving (Eq, Show, Read)
data Entity = Entity
{ pc :: Bool
, pos :: Vector2
, sym :: Char
, name :: String
, hp :: (Int, Int)
, inv :: Inventory
, stats :: EntityStats
, weight :: Int -- mass in grams
, speed :: Int
, nextMove :: Int
, seenL :: Array Vector2 Bool -- ^what the player has seen of the level
, seeingL :: Array Vector2 Bool -- ^what the player *currently* sees
} deriving (Eq, Show, Read)
data Level = Level
{ tilemap :: TileMap
, stairs :: (Vector2, Vector2) -- up and down stairs
, entities :: [Entity]
, items :: [(Vector2, Item)]
, narr :: Neighbours
} deriving (Eq, Show, Read)
data GameState = GameState
{ levels :: Z.Zipper Level
, msgs :: [(Int, Bool, String)] -- ^ turn added, seen by player, message
, turn :: Int
, pquit :: Bool
, dlvl :: Int
} deriving (Eq, Show)
cur :: Z.Zipper Level -> Level
cur = Z.cursor
-- | get the next actor and the rest
entityPQ :: [Entity] -> (Entity, [Entity])
entityPQ en =
let (p:ren) = sortBy (comparing nextMove) en
in (p, ren)
-- | get the player character and the rest
getPC :: [Entity] -> (Entity, [Entity])
getPC en =
let l = sortBy (comparing pc) en
in (last l, init l)
-- | check if the Entity is the player character
isPC :: Entity -> Bool
isPC = pc
-- empty level
emptyL :: TileMap
emptyL = listArray ((1,1), (80, 22)) (repeat ' ')
-- enemies don't use seenL/seeingL, so use this dummy array
nullA :: Array Vector2 Bool
nullA = listArray ((1,1), (2,2)) (repeat False)
testWeapons :: [Item]
testWeapons = [Item Weapon "Sword of Test +1" 100 4 0 1500 None 0
,Item Weapon "Shard of Glass" 150 2 0 300 None 0
,Item Weapon "Staff of Skepticism" 50 10 0 4000 None 0
]
testArmors :: [Item]
testArmors = [Item Armor "Tested Leather Armor" 100 0 2 5000 None 0
,Item Armor "Fancy Suit" 150 0 1 2000 None 0
,Item Armor "Power Armor mk2" 66 0 6 30000 None 0
]
testMisc :: [Item]
testMisc = [Item Scroll "Scroll of Modern Medicine" 100 0 0 100 (Healing 6) 3
,Item Potion "Potion of Alcohol" 100 0 0 700 (Healing (-1)) 3
,Item Potion "Homeopathic Potion" 100 0 0 500 (Healing 0) 3
,Item Scroll "Scroll of Death" 100 0 0 100 Death 3
,Item Scroll "Book of Teleportation" 100 0 0 1000 Teleport 3
,Item Corpse "Rodent Corpse" 100 0 0 1000 Yuck 3
,Item Scroll "Book of Transmutation" 100 0 0 1000 Transmute 3
]
noWeapon, noArmor, noMisc :: Item
noWeapon = Item Weapon "Prosthetic Fists" 100 1 0 0 None 3
noArmor = Item Armor "Wizard's Cape" 100 0 0 0 None 3
noMisc = Item Scroll "New York Times Magazine" 100 0 0 0 None 0
defaultStats :: EntityStats
defaultStats = EntityStats
{ strength = 8
, agility = 8
, intelligence = 8
, beauty = 8
}
testEnemies :: [Entity]
testEnemies =
[Entity False (0,0) 'L' "Lamar" (5,5) undefined defaultStats
30000 50 0 nullA nullA
,Entity False (0,0) 'A' "Giant Ant" (7,7) undefined defaultStats
10000 99 0 nullA nullA
,Entity False (0,0) 'm' "Mom" (8,8) undefined defaultStats
60000 101 0 nullA nullA
,Entity False (0,0) 'b' "Bear" (13,13) undefined defaultStats
120000 120 0 nullA nullA
,Entity False (0,0) 'd' "Dog" (3,3) undefined defaultStats
8000 95 0 nullA nullA
,Entity False (0,0) 'a' "Armadillo" (1,1) undefined defaultStats
1000 85 0 nullA nullA
,Entity False (0,0) 'E' "Etsilopp" (10,10) undefined defaultStats
100000 100 0 nullA nullA
]
testBoss :: Entity
testBoss =
Entity False (0,0) 'G' "Dreadlord Gates" (32,32)
undefined defaultStats 75000 135 0 nullA nullA
testItems :: [Item]
testItems = testWeapons ++ testArmors ++ testMisc
randInv :: IO Inventory
randInv = do
w <- randomElem testWeapons
a <- randomElem testArmors
m <- randomElem testMisc
return Inventory { equWeapon = w
, equArmor = a
, equMisc = m
, storedItems = [] }
-- to save disk space, the neighbours array could be discarded here
-- and then rebuilt on load
{-
save :: Game ()
save = get >>= io . writeFile "savefile" . show
load :: Game ()
load = io (readFile "saveFile") >>= io . readIO >>= put
-}
mkPlayer :: Vector2 -> IO Entity
mkPlayer pos' =
-- pinv <- randInv
return Entity
{ pc = True
, name = "Player"
, pos = pos'
, sym = '@'
, hp = (20, 20)
, inv = Inventory noWeapon noArmor noMisc []
, stats = defaultStats
, weight = 75000
, speed = 100
, nextMove = 0
, seenL = listArray ((1,1), (80,22)) (repeat False)
, seeingL = listArray ((1,1), (80,22)) (repeat False)
}
-- max carry weight is 5kg per strength point
maxCarryWeight :: Entity -> Int
maxCarryWeight e = 5000 * strength (stats e)
itemWeight :: [Item] -> Int
itemWeight = sum . map iWeight
mkEnemiesOnLevel :: Int -- number of enemies
-> Int -- nextMove of enemies, set to the nextMove of the player
-- when descending the dungeon
-> TileMap
-> IO [Entity]
mkEnemiesOnLevel dl nm l = do
en <- randomRIO (1 * dl, 3 * dl) -- amount of enemies
es <- randFloors l en -- positions
ei <- replicateM en randInv -- inventories
em <- replicateM en (randomElem testEnemies) -- random enemies
ep <- randFloor l -- position of boss, maybe
bi <- randInv -- inventory of boss, maybe
return $
-- add the boss on the fifth level
[testBoss { pos = ep, inv = bi, nextMove = nm } | dl == 5] ++
-- add normal enemies
zipWith3 (\e p i -> e { pos = p, inv = i, nextMove = nm }) em es ei
mkItemsOnLevel :: TileMap -> IO [(Vector2, Item)]
mkItemsOnLevel l = do
i <- randomRIO (3,9)
is <- replicateM i (randomElem testItems)
ip <- randFloors l i
return (zip ip is)
-- | make a random pair within given bounds
randomV2 :: (Vector2, Vector2) -> IO Vector2
randomV2 ((x1, y1), (x2, y2)) = do
x <- randomRIO (x1, x2)
y <- randomRIO (y1, y2)
return (x,y)
isFloor :: TileMap -> Vector2 -> Bool
isFloor l p = l ! p `elem` ".⋅"
-- | find a random part of the level that's walkable
randFloor :: TileMap -> IO Vector2
randFloor l = randomV2 (bounds l) `satisfying` isFloor l
-- | find n non-repeating random positions that are walkable
randFloors :: TileMap -> Int -> IO [Vector2]
randFloors l n = do
let floorTiles = map fst $ filter (\(_,c) -> c `elem` ".⋅") $ assocs l
when (length floorTiles <= n) $
error "randFloors: given level had fewer floor tiles than were requested"
flip execStateT [] $
replicateM_ n $ do
ps' <- get
xy <- liftIO $ randomElem floorTiles `satisfying` (`notElem` ps')
modify (xy:)
-- | check if two rooms overlap
roomOverlap :: Room -> Room -> Bool
roomOverlap ((x1, y1), (sx1, sy1)) ((x2, y2), (sx2, sy2)) =
not (x1 > x2 + sx2 + 1
||y1 > y2 + sy2 + 1
||x2 > x1 + sx1 + 1
||y2 > y2 + sy1 + 1)
-- | check if the given room overlaps any of the rooms in the list
roomOverlapAny :: Room -> [Room] -> Bool
roomOverlapAny r = any (roomOverlap r)
-- | create a room without checking if it's within level bounds
createRoom :: Vector2 -> IO Room
createRoom (sx, sy) = do
-- all rooms need to be at least 2 tiles away from the level bounds
-- 1 tile to make room for any paths, and +1 tile because FOV crashes
-- if it tries to look at nothingness.
x <- randomRIO (3, sx - 3)
y <- randomRIO (3, sy - 3)
rx <- randomRIO (2, sx `div` 2)
ry <- randomRIO (2, sy `div` 2)
return ((x, y), (rx, ry))
-- | check if a room is within (x2, y2) bounds
goodRoom :: Vector2 -> Room -> Bool
goodRoom (sx, sy) ((x, y), (rx, ry)) = x + rx < sx - 3 && y + ry < sy - 3
-- | try really hard to make a servicable dungeon
mkRandRooms :: Vector2 -> IO TileMap
mkRandRooms lbounds = do
-- try 1000 times to create good non-overlapping rooms
rooms <- flip execStateT [] $
replicateM_ 1000 $ do
rooms <- get
r <- liftIO (createRoom lbounds) `satisfying` goodRoom lbounds
unless (r `roomOverlapAny` rooms) (modify (r:))
when (null rooms)
(error "dungeon generator mkRandRooms didn't make any rooms")
let room_lps = mkRooms rooms :: TileMapPart
narrP = mkNeighbourArray (emptyL // room_lps) " "
paths1 <- connectRandomRoomToAll narrP rooms
paths2 <- connectRandomRooms narrP rooms (length rooms `div` 2)
return $ emptyL // (room_lps ++ paths1 ++ paths2)
-- | connect a random room from the list to all rooms. Cheap way to
-- ensure that all rooms are connected.
connectRandomRoomToAll :: Neighbours -> [Room] -> IO TileMapPart
connectRandomRoomToAll narrP rooms = do
rc <- randomElem rooms
concat `fmap` catMaybes `fmap` forM rooms (\r ->
if r /= rc
then connectRooms narrP r rc
else return Nothing)
-- | make n random connections between rooms
connectRandomRooms :: Neighbours -> [Room] -> Int -> IO TileMapPart
connectRandomRooms narrP rooms n =
concat `fmap` catMaybes `fmap` replicateM n
(do r1 <- randomElem rooms
r2 <- randomElem rooms
if r1 /= r2 then connectRooms narrP r1 r2
else return Nothing)
-- | connect two rooms, using corridors generated by A* pathfinding.
-- Randomly picks a side, so all rooms must have one tile free space
-- around them.
connectRooms :: Neighbours -> Room -> Room -> IO (Maybe TileMapPart)
connectRooms narrP r1 r2 = do
side1 <- randomRIO (1, 4::Int)
side2 <- randomRIO (1, 4::Int)
let (f1, r1p') =
case side1 of
1 -> (above, roomSideR r1 T)
2 -> (below, roomSideR r1 B)
3 -> (left, roomSideR r1 L)
4 -> (right, roomSideR r1 R)
_ -> error "wait, what?"
(f2, r2p') =
case side2 of
1 -> (above, roomSideR r2 T)
2 -> (below, roomSideR r2 B)
3 -> (left, roomSideR r2 L)
4 -> (right, roomSideR r2 R)
_ -> error "you're drunk; go home"
r1p <- r1p'
r2p <- r2p'
return $ mkPath narrP r1p r2p f1 f2
-- | produce a random tile location from given side of the given room
roomSideR :: Room -> Side -> IO Vector2
roomSideR ((x1, y1), (sx, sy)) s =
case s of
T -> randomRIO (x1+1, x1+sx-1) >>= \x -> return (x, y1)
B -> randomRIO (x1+1, x1+sx-1) >>= \x -> return (x, y1+sy)
R -> randomRIO (y1+1, y1+sy-1) >>= \y -> return (x1+sx, y)
L -> randomRIO (y1+1, y1+sy-1) >>= \y -> return (x1, y)
-- utils for Data.Graph.AStar
-- | distance between two level points (taxi metric)
distance :: Vector2 -> Vector2 -> Int
distance (a1,a2) (b1, b2) =
(b1 - a1) + (b2 - a2)
maybeLookup :: TileMap -> Vector2 -> Maybe Char
maybeLookup l p@(x,y) =
let ((x1, y1), (x2, y2)) = bounds l
in if x > x2 || x < x1 || y > y2 || y < y1
then Just (l ! p)
else Nothing
-- | create a array of the sets of neighbours for each tile
mkNeighbourArray :: TileMap -> String -> Neighbours
mkNeighbourArray l tt =
let (a@(x1,y1), b@(x2,y2)) = bounds l
in listArray (a, b) [setOfNeighbours l tt (x,y) |
x <- [x1..x2],
y <- [y1..y2]]
-- | create a set of all neighbours of a point that are walkable
setOfNeighbours :: TileMap -> String -> Vector2 -> Set.Set Vector2
setOfNeighbours l tt p =
Set.fromList
. map fst
. filter (\(p',_) -> l ! p' `elem` tt)
. filter (\(_,m) -> isNothing m) $
[ (above p, l `maybeLookup` above p)
, (below p, l `maybeLookup` below p)
, (right p, l `maybeLookup` right p)
, (left p, l `maybeLookup` left p)]
-- | aStar with defaults
simpleAStar :: Neighbours
-> Vector2
-> Vector2
-> Maybe [Vector2]
simpleAStar narrP start goal =
let adjdist _ _ = 1
nset p = narrP ! p
dist = distance goal
in aStar nset adjdist dist (==goal) start
-- | make a path between two rooms
mkPath :: Neighbours
-> Vector2 -- ^ from
-> Vector2 -- ^ to
-> (Vector2 -> Vector2)
-- pass above/below/right/left here, because if we're making
-- a path from a room, the first tile and last tiles are
-- impassable walls
-> (Vector2 -> Vector2)
-> Maybe TileMapPart
mkPath narrP p1 p2 f1 f2 = do
p' <- simpleAStar narrP (f1 p1) (f2 p2)
return $ zip p' (repeat '#') ++ [(f1 p1, '#'), (p1,'+'), (p2,'+')]
-- level construction
mkHwall :: Char -> Int -> Vector2 -> TileMapPart
mkHwall ch len (x,y) = zip (zip [x..(x-1+len)] (repeat y)) (repeat ch)
mkVwall :: Char -> Int -> Vector2 -> TileMapPart
mkVwall ch len (x,y) = zip (zip (repeat x) [y..(y-1+len)]) (repeat ch)
-- borders:
-- ┘ ┐ ┌ └ │ ─ ├ ┬ ┤ ┴ ┼ ╭ ╮ ╯ ╰
-- ═ ║ ╒ ╓ ╔ ╕ ╖ ╗ ╘ ╙ ╚ ╛ ╜ ╝ ╞ ╟
-- ╠ ╡ ╢ ╣ ╤ ╥ ╦ ╧ ╨ ╩ ╪ ╫ ╬
mkRoom :: Room -> TileMapPart
mkRoom ((x1, y1), (sx, sy)) = concat
-- floors
[[((x,y), '⋅') | y <- [y1..(y1+sy)], x <- [x1..(x1+sx)]]
-- walls
,mkHwall '═' sx (x1, y1)
,mkHwall '═' sx (x1, y1 + sy)
,mkVwall '║' (sy+1) (x1, y1)
,mkVwall '║' (sy+1) (x1 + sx, y1)
-- corners
,[((x1, y1), '╔'), ((x1+sx, y1+sy), '╝')
,((x1, y1+sy), '╚'), ((x1+sx, y1), '╗')]]
mkRooms :: [Room] -> TileMapPart
mkRooms = concatMap mkRoom
walkableL :: TileMap -> Vector2 -> Bool
walkableL l p@(x,y) =
let ((x1,y1), (x2,y2)) = bounds l
in (x < x2 || x > x1 || y < y2 || y > y1) && (l ! p `elem` ".⋅+#SDk>")
-- TODO: this needs to be fixed to account for messages over 75 chars
displayMessageLog :: Game ()
displayMessageLog = do
g <- get
let bs@(_, (x2,y2)) = bounds (tilemap (Z.cursor (levels g)))
ms = take (y2 -5) (msgs g)
pp = zip [3..] ms
curses $ do
draw $ do
clear bs
drawStringAt (1,1) "Message log: ('p' to return)"
forM_ pp $ \(y, (t, _, m)) ->
drawStringAt (1, y) $ take (x2 - 5) "[" ++ show t ++ "] " ++ m
_ <- waitForChrs "p"
draw $ clear bs
helpString :: [String]
helpString = ["Hello, hoodie here (press ? again to return)"
,""
,"Move with the Vi keys: hijkyubn"
,"Attack by moving into enemies"
,"Wait for a turn by pressing ."
,"i to look at your inventory"
,"e/d - equip drop"
,"a to apply your misc item"
,", to pick up items below you"
,"Descend to the next level with > when you are on stairs"
,"Press p to display the message log,"
,""
,"q to quit, coward."]
displayHelp :: Game ()
displayHelp = do
bs <- bounds `fmap` tilemap `fmap` Z.cursor `fmap` gets levels
curses $ do
draw $ do
clear bs
forM_ [1..length helpString] $ \y ->
drawStringAt (1, y) $ center 80 (helpString !! (y-1))
_ <- waitForChrs "?"
return ()
displayPlayerInventory :: Game ()
displayPlayerInventory = do
l <- Z.cursor `fmap` gets levels
let p = fst (getPC (entities l))
iItems = zip [0..] (storedItems (inv p))
w = equWeapon (inv p)
a = equArmor (inv p)
m = equMisc (inv p)
letters = ['a'..]
chargeStr i =
if iType i `notElem` [Weapon, Armor] then " (" ++ show (iCharge i) ++ ")" else []
curses $ do
draw $ do
clear (bounds (tilemap l))
let cw = sum $ map iWeight (w:a:m:storedItems (inv p))
let mw = maxCarryWeight p
drawStringAt (1,1) $
"Inventory. (current weight: " ++ show cw ++ " max: " ++ show mw ++ ")"
drawStringAt (1,2) "Items:"
drawStringAt (1,3) $ " [Wielded] " ++ iName w
drawStringAt (1,4) $ " [Worn] " ++ iName a
drawStringAt (1,5) $ " [Active] " ++ iName m ++ chargeStr m
forM_ iItems $ \(y, i) ->
drawStringAt (1, y + 7) $ " " ++ letters !! y : ". " ++ iName i
++ chargeStr i
render
_ <- waitForChrs $ ' ':['A'..'z']
return ()
withReverse :: Update () -> Update ()
withReverse upact = do
setAttribute AttributeReverse True
upact
setAttribute AttributeReverse False
itemSym :: Item -> Char
itemSym i = case iType i of
Weapon -> '|'
Armor -> '['
Potion -> '!'
Scroll -> '?'
Corpse -> '%'
Food -> ','
drawEverything :: Game ()
drawEverything = do
g <- get
l <- Z.cursor `fmap` gets levels
let (p, en') = getPC (entities l)
tm = tilemap l
seen = seenL p
seeing = seeingL p
(u,d) = stairs l
curses $ draw $ do
clear (bounds tm)
-- draw level
forM_ (indices tm) $ \i ->
when (seen ! i) (drawStringAt i [tm ! i])
withReverse $
forM_ (indices tm) $ \i ->
when (seeing ! i) $
drawStringAt i [tm ! i]
-- draw stairs
when (seen ! u) $ drawStringAt u "<"
when (seen ! d) $ drawStringAt d ">"
-- draw items
forM_ (items l) $ \(ip,i) ->
when (seeing ! ip) (drawStringAt ip [itemSym i])
-- draw enemies
forM_ en' $ \e ->
when (seeing ! pos e) (drawStringAt (pos e) [sym e])
-- draw player
withReverse $ drawStringAt (pos p) "@"
-- concat unseen messages and draw them
let dms = concat $ reverse $ map (\(_,_,m) -> m++" ") $
takeWhile (\(_,b,_) -> not b) (msgs g)
unless (null dms) $
withReverse $ drawStringAt (1,1) dms
-- draw a statusbar, displaying time, speed, dungeon level, and hp
withReverse $ drawStringAt (1, 24) $
"Time: " ++ show (nextMove p) ++ " Speed: " ++ show (speed p)
++ " DL: " ++ show (dlvl g) ++ " HP: " ++ show (fst (hp p))
++ "/" ++ show (snd (hp p))
above, below, right, left :: Vector2 -> Vector2
above (x, y) = (x, y - 1)
below (x, y) = (x, y + 1)
right (x, y) = (x + 1, y)
left (x, y) = (x - 1, y)
aboveleft, aboveright, belowleft, belowright :: Vector2 -> Vector2
aboveleft (x, y) = (x - 1, y - 1)
aboveright (x, y) = (x + 1, y - 1)
belowleft (x, y) = (x - 1, y + 1)
belowright (x, y) = (x + 1, y + 1)
-- | maps directional keys to movement functions
keyToDir :: Char -> Vector2 -> Vector2
keyToDir c =
case c of
'k' -> above
'j' -> below
'l' -> right
'h' -> left
'y' -> aboveleft
'u' -> aboveright
'b' -> belowleft
'n' -> belowright
'.' -> id
_ -> error "movePlayer: controls misconfigured"
-- | Move the player, fail to move the player, rest, or attack an entity
movePlayer :: Char -> Game ()
movePlayer c = do
l <- Z.cursor `fmap` gets levels
let (p,en') = getPC en
en = entities l
tm = tilemap l
-- position player wants to move to
newp = keyToDir c (pos p)
-- is there someone there?
case en' `getEntityAt` newp of
-- we're moving into an enemy
Just e -> attackEntity p e
-- or not
Nothing ->
if tm `walkableL` newp
then do
-- print a message if there are items under the player
is <- itemsAt newp
case length is of
0 -> return ()
1 -> addMessage $ "You see here " ++ iName (head is)
_ -> when (pos p /= newp) $
addMessage $ "You see here " ++
concatMap (\i -> iName i ++ ", ") (init is)
++ "and " ++ iName (last is)
p `moveEntityTo` newp
else addMessage "You bump into an obstacle!"
itemsAt :: Vector2 -> Game [Item]
itemsAt v = do
l <- items `fmap` Z.cursor `fmap` gets levels
return $ map snd $ filter (\(p,_) -> p == v) l
modifyEntityHp :: Int -> Entity -> Entity
modifyEntityHp n e =
let (hp', maxhp') = hp e
newhp = min maxhp' (hp' + n)
in e { hp = (newhp, maxhp') }
getEntityAt :: [Entity] -> Vector2 -> Maybe Entity
getEntityAt es p = find (\e -> pos e == p) es
anyEntityAt :: [Entity] -> Vector2 -> Bool
anyEntityAt es p = p `elem` map pos es
addMessage :: String -> Game ()
addMessage m = do
g <- get
put $ g { msgs = (turn g, False, m) : msgs g }
removePlayerFromCurLevel :: Game ()
removePlayerFromCurLevel = do
g <- get
ls <- gets levels
let l = Z.cursor ls
(_,en) = getPC (entities l)
l' = l { entities = en }
put $ g { levels = Z.replace l' ls }
addPlayerOnCurrentLevel :: Entity -> Game ()
addPlayerOnCurrentLevel e = do
g <- get
ls <- gets levels
let l = Z.cursor ls
l' = l { entities = e : entities l }
put $ g { levels = Z.replace l' ls }
ageEntities :: Int -> [Entity] -> [Entity]
ageEntities n es =
map (\e -> e { nextMove = n }) es
-- | merge the old "seen" array with the new "seeing" array
-- to produce an updated "seen" array
updateSeen :: Array Vector2 Bool
-> Array Vector2 Bool
-> IO (Array Vector2 Bool)
updateSeen old_seen new_seeing = do
u_n_s <- thaw new_seeing :: IO (IOArray Vector2 Bool)
upds <- filter snd `fmap` getAssocs u_n_s
return $ old_seen // upds
-- | update the "seen" and "seeing" arrays
updateVision' :: GameState -> IO GameState
updateVision' g = do
let l = Z.cursor $ levels g
tm = tilemap l
(p,en') = getPC (entities l)
pp = pos p
seen = seenL p
(seeing',seen') <- do
s <- ioInit
newSeeing <- newArray (bounds tm) False :: IO (IOUArray Vector2 Bool)
let lightPoint x y = writeArray newSeeing (x, y) True
isOpaque x y = return (tm ! (x, y) `elem` " ═║╔╝╚╗")
-- use FOV's circle to write into the newSeeing array
circle s pp 5 lightPoint isOpaque
newSeeing' <- freeze newSeeing :: IO (Array Vector2 Bool)
newSeen' <- updateSeen seen newSeeing'
return (newSeeing', newSeen')
let np = p { seenL = seen', seeingL = seeing' }
ne = np : en'
nl = l { entities = ne }
g' = g { levels = Z.replace nl (levels g) }
return g'
getGoodCh :: Game Char
getGoodCh = curses $ waitForChrs "?hjklyubnqpria.,><ed"
setQuit :: Game ()
setQuit = do
g <- get
put $ g { pquit = True }
-- | Checks if the player is dead and quits if they are.
isPlayerDead :: Game ()
isPlayerDead = do
php <- fst `fmap` hp `fmap` fst `fmap` getPC `fmap` entities `fmap` Z.cursor `fmap` gets levels
when (php <= 0) $ do
addMessage "Oh no! You are dead!"
setQuit
-- | Turn or time is a measure of how long the player has been in the dungeon.
-- An entity with 100 speed and 100 speed armor takes 10 "time" to move one
-- square. Higher speed = less time taken.
setTurn :: Game ()
setTurn = do
g <- get
p <- fst `fmap` getPC `fmap` entities `fmap` Z.cursor `fmap` gets levels
put $ g { turn = nextMove p }
-- | Creates a brand-new, fully filled Game.
mkDungeonLevel :: Game ()
mkDungeonLevel = do
l <- io $ mkRandRooms (80, 22) -- tilemap
p <- io $ randFloor l -- player position
ep <- io $ randFloor l -- exit position
is <- io $ mkItemsOnLevel l -- items
p' <- io $ mkPlayer p -- player entity
enemies' <- io $ mkEnemiesOnLevel 1 0 l
let l' = Level
{ tilemap = l
, stairs = (p, ep)
, entities = p' : enemies'
, items = is
, narr = mkNeighbourArray l ".⋅+#SDk"
}
put GameState
{ levels = Z.insert l' Z.empty
, msgs = [(0, False, "Welcome to hoodie! (press ? for help)")]
, turn = 0
, pquit = False
, dlvl = 1
}
descend :: Game ()
descend = do
level <- Z.cursor `fmap` gets levels
let exit = snd (stairs level)
if pos (fst (getPC (entities level))) == exit
then do
curses $ draw $ clear (bounds (tilemap level))
descendLevel
addMessage "You descend the stairs!"
else addMessage "There are no down stairs here!"
-- | changes all the things that need the change between floors
descendLevel :: Game ()
descendLevel = do
l <- cur `fmap` gets levels
let (p,_) = getPC (entities l) -- get current player
-- remove the player from the current level
removePlayerFromCurLevel
ls <- gets levels
-- check if there's a level below us already generated, otherwise make
-- a new level
(p'', ls'') <- if Z.beginp ls
then do -- we're making a new level
tm <- io $ mkRandRooms (80,22)
pp <- io $ randFloor tm -- new player position
ep <- io $ randFloor tm -- exit position
is <- io $ mkItemsOnLevel tm
en <- io $ mkEnemiesOnLevel 1 (nextMove p + 1) tm
let p' = p { pos = pp
, seenL = listArray ((1,1), (80,22)) (repeat False)
, seeingL = listArray ((1,1), (80,22)) (repeat False)
}
-- insert the level at the cursor
return (p', Z.insert Level
{ tilemap = tm
, stairs = (pos p', ep)
, entities = en
, items = is
, narr = mkNeighbourArray tm ".⋅+#SDk"
} ls)
-- there's already a generated level below us, so just switch
else do
let l' = Z.cursor $ Z.left ls
-- put the player on the up stairs of the level we're going to
exit = fst $ stairs l'
en = entities l'
-- adjust the nextMove of all entities on the previous
-- level to that of the player's current
l'' = l' { entities = ageEntities (nextMove p + 1) en }
-- move the player to the position of the up stairs on
-- the next level
p' = p { pos = exit
, seenL = listArray ((1,1), (80,22)) (repeat False)
, seeingL = listArray ((1,1), (80,22)) (repeat False)
}
return (p', Z.replace l'' (Z.left ls))
g <- get
put $ g { levels = ls''
, dlvl = 1 + dlvl g }
-- add the player back on the new level
addPlayerOnCurrentLevel p''
-- | go up if we can
ascend :: Game ()
ascend = do
g <- get
level <- Z.cursor `fmap` gets levels
let exit = fst (stairs level)
(p,_) = getPC (entities level)
if Z.endp (Z.right (levels g))
then if pos p == exit
then addMessage "Are you sure you want to exit the dungeon?"
else addMessage "There are no up stairs here!"
else
if pos p == exit
then do
let prevlevel = Z.cursor $ Z.right $ levels g
prevexit = snd $ stairs prevlevel
-- need to set the next move time of entities on the previous level
-- the player's current
preven = ageEntities (nextMove p) (entities prevlevel)
-- set the player's location to the previous' level down stairs
-- and reset the vision
newp = p { pos = prevexit
, seenL = listArray ((1,1), (80,22)) (repeat False)
, seeingL = listArray ((1,1), (80,22)) (repeat False)
}
-- add the player to the list of the entities on the previous
-- level
newen = newp : preven
newl = prevlevel { entities = newen }
curses $ draw $ clear (bounds (tilemap level))
-- remove the player from the current level
removePlayerFromCurLevel
g' <- get
-- and put him in the one we're going to, and decrement the
-- dungeon level
put $ g' { levels = Z.replace newl $ Z.right (levels g')
, dlvl = dlvl g' - 1 }
addMessage "You ascend the stairs!"
else addMessage "There are no up stairs here!"
-- | This is the main update function, updating one entity per call. The
-- entity to be updated is the one with the lowest nextMove value. When the
-- entity perform a task (including nothing at all), the time cost of the task
-- is added to its nextMove. "turn" is used for the lack of a better word.
gameTurn :: Game ()
gameTurn = do
processNegativeHpEntities
l <- Z.cursor `fmap` gets levels
let en@(e, _) = entityPQ (entities l)
if isPC e
then do
setTurn
testScreenSize
drawEverything
ageMessages
c <- getGoodCh
case c of
'q' -> setQuit
'p' -> displayMessageLog
'?' -> displayHelp
',' -> playerPickupItem
'd' -> playerDropItem
'a' -> entityUseItem e
'i' -> displayPlayerInventory
'e' -> playerWieldItem
'r' -> mkDungeonLevel >> updateVision
'>' -> descend >> updateVision
'<' -> ascend >> updateVision
_ -> movePlayer c >> updateVision
else processEnemies en
isPlayerDead
modifyEntity :: Entity -> (Entity -> Entity) -> Game ()
modifyEntity e f = do
g <- get
ls <- gets levels
let l = Z.cursor ls
en = entities l
ne = map (\e' -> if pos e' == pos e then f e' else e') en
nl = l { entities = ne }
put $ g { levels = Z.replace nl (levels g) }
-- | The time needed to perform an action is:
--
-- 1000
-- --------------------------------------
-- (speed of entity + speed of item used)
-- ----------------------------------
-- 2
--
-- or equivalently: 2000 / (speed of entity + speed of item used)
--
-- for moving around, the item speed used is that of the equipped armor
itemUseCost :: Entity -> Item -> Int
itemUseCost e i = 2000 `div` (speed e + iSpeed i)
entityUseItem :: Entity -> Game ()
entityUseItem e = do
let pm = equMisc (inv e)
verb = itemUseVerb pm
isPlayer = pc e
if iCharge pm >= 1
then entityApplyItem e
else when isPlayer $ addMessage $ "You can't " ++ verb ++ " that any more."
useMiscItemCharges :: Int -> Entity -> Entity
useMiscItemCharges n e =
let is = inv e
oi = equMisc is
ni = oi { iCharge = iCharge (equMisc is) - n }
in e { inv = is { equMisc = ni } }
itemUseVerb :: Item -> String
itemUseVerb i =
case iType i of
Potion -> "drink"
Scroll -> "read"
Corpse -> "squeeze"
_ -> "use"
-- TODO: consume item or item charge on use
-- | Use your misc item to do something
entityApplyItem :: Entity -> Game ()
entityApplyItem e = do
g <- get
let pm = equMisc (inv e)
verb = itemUseVerb pm
isPlayer = pc e
useMsg =
if isPlayer
then "You " ++ verb ++ " the " ++ iName pm ++ "!"
-- don't bother using verbs for others :)
else name e ++ " uses the " ++ iName pm ++ "!"
-- Notes:
-- * modifyEntity should be called once per effect.
-- * effects must have addEntityTime, otherwise AI can enter an infinite loop
case iEffect pm of
-- item does nothing
None -> do
addMessage useMsg
when isPlayer $ addMessage "You reflect on your life..."
modifyEntity e ( addEntityTime (itemUseCost e pm)
. useMiscItemCharges 1)
-- item heals (or hurts)
Healing n -> do
addMessage useMsg
modifyEntity e ( modifyEntityHp n
. addEntityTime (itemUseCost e pm)
. useMiscItemCharges 1)
-- item kills entity (doh)
Death -> do
-- always add useMsg
addMessage useMsg
-- only add these when the player uses items
when isPlayer $ addMessage "You feel stupid!"
modifyEntity e ( modifyEntityHp (-999)
. addEntityTime (itemUseCost e pm)
. useMiscItemCharges 1)
-- item randomly teleports entity
Teleport -> do
addMessage useMsg
newp <- io $ randFloor (tilemap $ Z.cursor $ levels g) `satisfying` (/= pos e)
modifyEntity e ( modifyEntityPos newp
. addEntityTime (itemUseCost e pm)
. useMiscItemCharges 1)
addMessage "Woosh!"
updateVision
-- item does nothing
Yuck -> do
addMessage useMsg
when isPlayer $ addMessage "Yuck!"
modifyEntity e ( addEntityTime (itemUseCost e pm)
. useMiscItemCharges 1)
-- item turns entity's weapon into another one
Transmute -> do
addMessage useMsg
let curWeapon = equWeapon $ inv e
-- find a new weapon that's different from the current one
newWeapon <- io $ randomElem testWeapons `satisfying` (/= curWeapon)
-- equip it
modifyEntity e ( modifyInventory (\i -> i { equWeapon = newWeapon })
. addEntityTime (itemUseCost e pm)
. useMiscItemCharges 1)
when isPlayer $ addMessage $ "Your " ++ iName curWeapon
++ " turns into " ++ iName newWeapon ++ "!"
satisfying :: Monad m => m a -> (a -> Bool) -> m a
satisfying = flip iterateUntil
modifyInventory :: (Inventory -> Inventory) -> Entity -> Entity
modifyInventory f e = e { inv = f (inv e) }
-- remove the nth item from the items at position
removeFloorItem :: Vector2 -> Int -> Game ()
removeFloorItem v n = do
g <- get
ls <- gets levels
is <- itemsAt v
-- new items on the floor
let new = map (\x -> (v, x)) (removeElem is n)
-- the rest of them
rest = filter (\x -> fst x /= v) (items l)
l = Z.cursor ls
ne = l { items = new ++ rest }
put $ g { levels = Z.replace ne ls }
-- display a menu to pick an item, and return the item and its index in the
-- list
pickItem :: [Item] -> Game (Maybe (Int, Item))
pickItem is = do
bs <- bounds `fmap` tilemap `fmap` Z.cursor `fmap` gets levels
let iItems = zip [0..] is
letters = ['a'..]
ch <- curses $ do
draw $ do
clear bs
drawStringAt (1,1) "Items:"
forM_ iItems $ \(y, i) ->
drawStringAt (1, y + 2) $ letters !! y : ". " ++ iName i
render
waitForChrs ['A'..'z']
let idx = ord ch - 97
if idx > length is || null is
then do addMessage "No such item."
return Nothing
else return $ Just (idx, is !! idx)
-- the player can pick up items.
-- the item is removed from the floor
-- the item is placed into the general inventory of the player
-- if there is more than one item, the player gets a menu to choose which
-- item to pick up.
-- the player has an inventory with 15 slots
-- 'i' displays an inventory. from there the player can
-- 'e' - equip an item from the general inventory
-- the item is equipped
-- the item is removed from the general inventory
-- the item that was previous equipped is added back into the G.I.
-- unless it's one of the default items
-- 'd' - drop an item
-- the item is removed from the general inventory
-- the item is added to the items list at the player's feet
-- 'U' - unwield an item
-- the item is unequipped, and replaced with the defaults
-- (fists, wizard's robe, NYT)
playerDropItem :: Game ()
playerDropItem = do
g <- get
ls <- gets levels
let l = Z.cursor ls
(p,_) = getPC (entities l)
mi <- pickItem (storedItems (inv p))
case mi of
Nothing -> return ()
Just (n,i) -> do
is <- itemsAt (pos p)
if length is >= 3
then
addMessage "There's no room to drop anything there!"
else do
let nl = l { items = (pos p, i) : items l }
put $ g { levels = Z.replace nl ls }
modifyEntity p ( modifyInventory (removeStoredItemNth n)
. addEntityTime (itemUseCost p i))
addMessage $ "You drop the " ++ iName i
playerWieldItem :: Game ()
playerWieldItem = do
-- player
p <- fst `fmap` getPC `fmap` entities `fmap` Z.cursor `fmap` gets levels
-- pick an item in the inventory
mi <- pickItem (storedItems (inv p))
case mi of
Nothing -> return ()
-- wield the selected item, remove it from the general inventory
Just (n,i) -> do
modifyEntity p ( modifyInventory (wieldItem i
. removeStoredItemNth n)
. addEntityTime (itemUseCost p i))
addMessage $ "You wield the " ++ iName i
removeStoredItemNth :: Int -> Inventory -> Inventory
removeStoredItemNth n iv = iv { storedItems = removeElem (storedItems iv) n }
wieldItem :: Item -> Inventory -> Inventory
wieldItem i iv =
let (ww, wa, wm) = (equWeapon iv, equArmor iv, equMisc iv)
in case iType i of
Weapon -> iv { equWeapon = i, storedItems = ww : storedItems iv }
Armor -> iv { equArmor = i, storedItems = wa : storedItems iv }
_ -> iv { equMisc = i, storedItems = wm : storedItems iv }
addItem :: Item -> Inventory -> Inventory
addItem i iv = iv { storedItems = i : storedItems iv }
entityItems :: Entity -> [Item]
entityItems e =
[equWeapon (inv e), equArmor (inv e), equMisc (inv e)] ++ storedItems (inv e)
-- | Pick up an item, if there is one below the player.
playerPickupItem :: Game ()
playerPickupItem = do
ls <- gets levels
let l = Z.cursor ls
-- player and friends
(p, _) = getPC (entities l)
-- is there an item below us?
is <- itemsAt (pos p)
if length (storedItems (inv p)) >= 10
|| itemWeight (entityItems p) >= maxCarryWeight p
then addMessage "You can't carry anything more!"
else
case length is of
0 -> addMessage "There's nothing here to pick up!"
1 -> do
let i = head is
addMessage $ "You pick up the " ++ iName i ++ "!"
modifyEntity p ( modifyInventory (addItem i)
. addEntityTime (itemUseCost p i))
removeFloorItem (pos p) 0
_ -> do
mi <- pickItem is
case mi of
Nothing -> return ()
Just (n,i) -> do
addMessage $ "You pick up the "++ iName i ++ "!"
modifyEntity p ( modifyInventory (addItem i)
. addEntityTime (itemUseCost p i))
removeFloorItem (pos p) n
{-
Nothing ->
Just i -> do
-- make a new inventory based on the type of the item
let newinv = case iType i of
Weapon -> cinv { equWeapon = i }
Armor -> cinv { equArmor = i }
_ -> cinv { equMisc = i }
-- item we're dropping from the player's inventory
dropped = case iType i of
Weapon -> equWeapon (inv p)
Armor -> equArmor (inv p)
_ -> equMisc (inv p)
-- commit new inventory, remove the item from the floor
-- and add the dropped item to the floor at the player's feet
put $ g { entities = p { inv = newinv } : en
, items = (pos p, dropped) : filter (/= (pos p, i)) is
}
-- picking stuff up takes time
modifyEntity p (addEntityTime (itemUseCost p i))
-- add message
-}
-- | After one turn, set messages to viewed so they don't display any more
ageMessages :: Game ()
ageMessages = do
g <- get
put $ g { msgs = map (\(t,_,m) -> (t, True, m)) (msgs g) }
updateVision :: Game ()
updateVision = get >>= io . updateVision' >>= put
-- | Checks if the Entity current hp <= 0.3 of max
panicEntityAI :: Entity -> Bool
panicEntityAI e =
let (cHp, mHp) = hp e
hpRatio = fromIntegral cHp / fromIntegral mHp :: Double
in hpRatio <= 0.3
processEnemies :: (Entity, [Entity]) -> Game ()
processEnemies (e, en) = do
let p = (fst . getPC) en
if panicEntityAI e && iCharge (equMisc (inv e)) >= 1
-- if the entity has low hp then use its misc item if the item has charges
then entityApplyItem e
else
-- if the enemy is next to the player, attack, otherwise
-- move closer to the player
if pos e `nextTo` pos p
then e `attackEntity` p
else moveEntityAI en e
-- | subtract damage from defender, add time spent to the attacker, and
-- add messages
attackEntity :: Entity -- attacker
-> Entity -- defender
-> Game ()
attackEntity atk def = do
let -- inventories of the attacker and defender
aw = equWeapon (inv atk)
da = equArmor (inv def)
-- damage done from attacker to defender is attacker's weapon attack
-- value minus defender's armor's defend value
dmg = max 0 (iDamage aw - iDefence da)
-- add messages
when (isPC def) $ addMessage $ "The " ++ name atk ++ " hits you!"
when (isPC atk) $ addMessage $ "You hit the " ++ name def ++ "!"
unless (isPC def || isPC atk) $
addMessage $ "The " ++ name atk ++ "hits the " ++ name def ++ "!"
-- damage the defender
modifyEntity def (modifyEntityHp (-dmg))
-- add attack cost to the attacker
modifyEntity atk (addEntityTime (itemUseCost atk aw))
-- | remove entities that have <= 0 current hitpoints and add messages about
-- their deaths
processNegativeHpEntities :: Game ()
processNegativeHpEntities = do
g <- get
ls <- gets levels
let l = Z.cursor ls
died = filter (\e -> fst (hp e) <= 0) (entities l)
unless (null died) $
-- death messages
do let dms = map (\e -> name e ++ " dies!") died
-- entities that are still alive
new = filter (`notElem` died) (entities l)
-- create corpses to drop at the positions where
-- the entities died
corpses = map (\e -> (pos e, entityToCorpse e)) died
-- add messages
mapM_ addMessage dms
let nl = l { entities = new, items = items l ++ corpses }
g' <- get
put $ g' { levels = Z.replace nl (levels g) }
entityToCorpse :: Entity -> Item
entityToCorpse e =
Item { iType = Corpse
, iName = name e ++ " corpse"
, iSpeed = 100
, iDamage = 0
, iDefence = 0
, iWeight = weight e
, iEffect = Yuck
, iCharge = 99
}
-- | cartesian distance function
cartDistance :: Vector2 -> Vector2 -> Double
cartDistance (x1, y1) (x2, y2) =
sqrt $ fromIntegral $ (x2-x1)^(2::Int) + (y2-y1)^(2::Int)
-- | all the directions you could ever possibly want to move in to including none
directions :: [Vector2 -> Vector2]
directions =
[id, above, below, right, left
,aboveright, aboveleft
,belowright, belowleft]
-- | calculate the distances between two points if you were to move the
-- *first* point in all possible directions
distances :: Vector2 -> Vector2 -> [Double]
distances a b =
map (\f -> cartDistance (f a) b) directions
-- | Check if a is next to b
nextTo :: Vector2 -> Vector2 -> Bool
nextTo a b = any (\f -> a == f b) directions
modifyEntityPos :: Vector2 -> Entity -> Entity
modifyEntityPos new e = e { pos = new }
addEntityTime :: Int -> Entity -> Entity
addEntityTime n e = e { nextMove = nextMove e + n }
moveEntityTo :: Entity -> Vector2 -> Game ()
moveEntityTo e newp =
modifyEntity e ( modifyEntityPos newp
. addEntityTime (itemUseCost e (equArmor (inv e)))
)
-- | make a list of functions sorted by the distance that they would bring
-- the enemy to if it moved in that direction, then select the first good one
moveEntityAI :: [Entity] -- rest of the enemies
-> Entity -- the entity we're moving
-> Game ()
moveEntityAI en' e = do
l <- Z.cursor `fmap` gets levels
let en = entities l
pp = pos (fst (getPC en))
-- entity position
ep = pos e
-- sort the movement functions by the distance that they would
-- bring the enemy to if it moved into that direction
sorted_funs = map snd $ sortBy (comparing fst)
(zip (distances ep pp) directions)
-- is this tile a good move?
goodmove ne = (tilemap l `walkableL` ne -- is the tile traversable?
-- is there an enemy on it?
&& not (en' `anyEntityAt` ne))
-- we can also just stand still
&& ne /= pp
-- get the first function that's a good move. Since they're sorted
-- by ascending distance, it's the optimal move. There is always
-- at least one element of this list - id.
bestfunc = head $ dropWhile (\f -> not (goodmove (f ep))) sorted_funs
-- enemies have a detection radius of 10, if the player is outside
-- it then just stand still
e `moveEntityTo` (if cartDistance ep pp < 10 then bestfunc ep else ep)
quitCond :: Game Bool
quitCond = liftM pquit get
testScreenSize :: Game ()
testScreenSize = do
(y, x) <- curses screenSize
when (y < 24 || x < 80) $
error $ "ERROR: Your terminal's size, " ++ show (x, y) ++
", is too small. You need at least (80, 22)"
runGame :: Game Bool -- ^ end condition
-> Game () -- ^ update function
-> IO GameState -- ^ end state
runGame predf logicf = do
let loop' = do
doquit <- predf
if doquit
then get
else logicf >> loop'
runCurses $ do
setEcho False
_ <- setCursorMode CursorInvisible
runGame1 undefined $ do
testScreenSize
mkDungeonLevel
updateVision
loop'
main :: IO ()
main = do
g <- runGame quitCond gameTurn
mapM_ print (reverse (msgs g))
mapM_ (print . entities) (Z.toList (levels g))
-- FOV init
ioInit :: IO Settings
ioInit = do
settings <- newSettings
setShape settings Circle
setOpaqueApply settings True
return settings
-- ncurses stuff
draw :: Update () -> Curses ()
draw ioact = do
w <- defaultWindow
updateWindow w ioact
render
clear :: (Vector2, Vector2) -> Update ()
clear ((x1, y1), (x2, y2)) =
let cs = replicate (x2-x1) ' '
in forM_ [y1..y2+2] $ \y ->
drawStringAt (x1, y) cs
waitForChrs :: String -> Curses Char
waitForChrs cs = loop' where
loop' = do
w <- defaultWindow
ev <- getEvent w Nothing
case ev of
Nothing -> loop'
Just (EventCharacter c) -> if c `elem` cs then return c else loop'
_ -> loop'
drawStringAt :: Vector2 -> String -> Update ()
drawStringAt (x, y) s = do
moveCursor' (y - 1, x - 1)
drawString s
screenSize' :: Curses Vector2
screenSize' = screenSize >>= \(y, x) ->
return (fromIntegral y, fromIntegral x)
moveCursor' :: Vector2 -> Update ()
moveCursor' (y, x) = moveCursor (fromIntegral y) (fromIntegral x)
-- misc stuff
swap :: (a, b) -> (b, a)
swap (a, b) = (b, a)
replaceElem :: [a] -> a -> Int -> [a]
replaceElem es e n = take n es ++ e : drop (n + 1) es
removeElem :: [a] -> Int -> [a]
removeElem es n = take n es ++ drop (n + 1) es
randomElem :: [a] -> IO a
randomElem xs = (xs !!) `fmap` randomRIO (0, length xs - 1)
center :: Int -> String -> String
center n xs =
let padding = replicate ((n - length xs) `div` 2) ' '
in padding ++ xs ++ padding
|
dvolk/hoodie
|
Main.hs
|
gpl-3.0
| 48,872 | 0 | 24 | 15,030 | 15,551 | 8,167 | 7,384 | -1 | -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.Games.TurnBasedMatches.Leave
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Leave a turn-based match when it is not the current player\'s turn,
-- without canceling the match.
--
-- /See:/ <https://developers.google.com/games/services/ Google Play Game Services API Reference> for @games.turnBasedMatches.leave@.
module Network.Google.Resource.Games.TurnBasedMatches.Leave
(
-- * REST Resource
TurnBasedMatchesLeaveResource
-- * Creating a Request
, turnBasedMatchesLeave
, TurnBasedMatchesLeave
-- * Request Lenses
, tbmlLanguage
, tbmlMatchId
) where
import Network.Google.Games.Types
import Network.Google.Prelude
-- | A resource alias for @games.turnBasedMatches.leave@ method which the
-- 'TurnBasedMatchesLeave' request conforms to.
type TurnBasedMatchesLeaveResource =
"games" :>
"v1" :>
"turnbasedmatches" :>
Capture "matchId" Text :>
"leave" :>
QueryParam "language" Text :>
QueryParam "alt" AltJSON :>
Put '[JSON] TurnBasedMatch
-- | Leave a turn-based match when it is not the current player\'s turn,
-- without canceling the match.
--
-- /See:/ 'turnBasedMatchesLeave' smart constructor.
data TurnBasedMatchesLeave =
TurnBasedMatchesLeave'
{ _tbmlLanguage :: !(Maybe Text)
, _tbmlMatchId :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TurnBasedMatchesLeave' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tbmlLanguage'
--
-- * 'tbmlMatchId'
turnBasedMatchesLeave
:: Text -- ^ 'tbmlMatchId'
-> TurnBasedMatchesLeave
turnBasedMatchesLeave pTbmlMatchId_ =
TurnBasedMatchesLeave' {_tbmlLanguage = Nothing, _tbmlMatchId = pTbmlMatchId_}
-- | The preferred language to use for strings returned by this method.
tbmlLanguage :: Lens' TurnBasedMatchesLeave (Maybe Text)
tbmlLanguage
= lens _tbmlLanguage (\ s a -> s{_tbmlLanguage = a})
-- | The ID of the match.
tbmlMatchId :: Lens' TurnBasedMatchesLeave Text
tbmlMatchId
= lens _tbmlMatchId (\ s a -> s{_tbmlMatchId = a})
instance GoogleRequest TurnBasedMatchesLeave where
type Rs TurnBasedMatchesLeave = TurnBasedMatch
type Scopes TurnBasedMatchesLeave =
'["https://www.googleapis.com/auth/games",
"https://www.googleapis.com/auth/plus.me"]
requestClient TurnBasedMatchesLeave'{..}
= go _tbmlMatchId _tbmlLanguage (Just AltJSON)
gamesService
where go
= buildClient
(Proxy :: Proxy TurnBasedMatchesLeaveResource)
mempty
|
brendanhay/gogol
|
gogol-games/gen/Network/Google/Resource/Games/TurnBasedMatches/Leave.hs
|
mpl-2.0
| 3,444 | 0 | 14 | 778 | 391 | 235 | 156 | 62 | 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.Spanner.Projects.Instances.Operations.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists operations that match the specified filter in the request. If the
-- server doesn\'t support this method, it returns \`UNIMPLEMENTED\`. NOTE:
-- the \`name\` binding allows API services to override the binding to use
-- different resource name schemes, such as \`users\/*\/operations\`. To
-- override the binding, API services can add a binding such as
-- \`\"\/v1\/{name=users\/*}\/operations\"\` to their service
-- configuration. For backwards compatibility, the default name includes
-- the operations collection id, however overriding users must ensure the
-- name binding is the parent resource, without the operations collection
-- id.
--
-- /See:/ <https://cloud.google.com/spanner/ Cloud Spanner API Reference> for @spanner.projects.instances.operations.list@.
module Network.Google.Resource.Spanner.Projects.Instances.Operations.List
(
-- * REST Resource
ProjectsInstancesOperationsListResource
-- * Creating a Request
, projectsInstancesOperationsList
, ProjectsInstancesOperationsList
-- * Request Lenses
, piolXgafv
, piolUploadProtocol
, piolAccessToken
, piolUploadType
, piolName
, piolFilter
, piolPageToken
, piolPageSize
, piolCallback
) where
import Network.Google.Prelude
import Network.Google.Spanner.Types
-- | A resource alias for @spanner.projects.instances.operations.list@ method which the
-- 'ProjectsInstancesOperationsList' request conforms to.
type ProjectsInstancesOperationsListResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListOperationsResponse
-- | Lists operations that match the specified filter in the request. If the
-- server doesn\'t support this method, it returns \`UNIMPLEMENTED\`. NOTE:
-- the \`name\` binding allows API services to override the binding to use
-- different resource name schemes, such as \`users\/*\/operations\`. To
-- override the binding, API services can add a binding such as
-- \`\"\/v1\/{name=users\/*}\/operations\"\` to their service
-- configuration. For backwards compatibility, the default name includes
-- the operations collection id, however overriding users must ensure the
-- name binding is the parent resource, without the operations collection
-- id.
--
-- /See:/ 'projectsInstancesOperationsList' smart constructor.
data ProjectsInstancesOperationsList =
ProjectsInstancesOperationsList'
{ _piolXgafv :: !(Maybe Xgafv)
, _piolUploadProtocol :: !(Maybe Text)
, _piolAccessToken :: !(Maybe Text)
, _piolUploadType :: !(Maybe Text)
, _piolName :: !Text
, _piolFilter :: !(Maybe Text)
, _piolPageToken :: !(Maybe Text)
, _piolPageSize :: !(Maybe (Textual Int32))
, _piolCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsInstancesOperationsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'piolXgafv'
--
-- * 'piolUploadProtocol'
--
-- * 'piolAccessToken'
--
-- * 'piolUploadType'
--
-- * 'piolName'
--
-- * 'piolFilter'
--
-- * 'piolPageToken'
--
-- * 'piolPageSize'
--
-- * 'piolCallback'
projectsInstancesOperationsList
:: Text -- ^ 'piolName'
-> ProjectsInstancesOperationsList
projectsInstancesOperationsList pPiolName_ =
ProjectsInstancesOperationsList'
{ _piolXgafv = Nothing
, _piolUploadProtocol = Nothing
, _piolAccessToken = Nothing
, _piolUploadType = Nothing
, _piolName = pPiolName_
, _piolFilter = Nothing
, _piolPageToken = Nothing
, _piolPageSize = Nothing
, _piolCallback = Nothing
}
-- | V1 error format.
piolXgafv :: Lens' ProjectsInstancesOperationsList (Maybe Xgafv)
piolXgafv
= lens _piolXgafv (\ s a -> s{_piolXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
piolUploadProtocol :: Lens' ProjectsInstancesOperationsList (Maybe Text)
piolUploadProtocol
= lens _piolUploadProtocol
(\ s a -> s{_piolUploadProtocol = a})
-- | OAuth access token.
piolAccessToken :: Lens' ProjectsInstancesOperationsList (Maybe Text)
piolAccessToken
= lens _piolAccessToken
(\ s a -> s{_piolAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
piolUploadType :: Lens' ProjectsInstancesOperationsList (Maybe Text)
piolUploadType
= lens _piolUploadType
(\ s a -> s{_piolUploadType = a})
-- | The name of the operation\'s parent resource.
piolName :: Lens' ProjectsInstancesOperationsList Text
piolName = lens _piolName (\ s a -> s{_piolName = a})
-- | The standard list filter.
piolFilter :: Lens' ProjectsInstancesOperationsList (Maybe Text)
piolFilter
= lens _piolFilter (\ s a -> s{_piolFilter = a})
-- | The standard list page token.
piolPageToken :: Lens' ProjectsInstancesOperationsList (Maybe Text)
piolPageToken
= lens _piolPageToken
(\ s a -> s{_piolPageToken = a})
-- | The standard list page size.
piolPageSize :: Lens' ProjectsInstancesOperationsList (Maybe Int32)
piolPageSize
= lens _piolPageSize (\ s a -> s{_piolPageSize = a})
. mapping _Coerce
-- | JSONP
piolCallback :: Lens' ProjectsInstancesOperationsList (Maybe Text)
piolCallback
= lens _piolCallback (\ s a -> s{_piolCallback = a})
instance GoogleRequest
ProjectsInstancesOperationsList
where
type Rs ProjectsInstancesOperationsList =
ListOperationsResponse
type Scopes ProjectsInstancesOperationsList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/spanner.admin"]
requestClient ProjectsInstancesOperationsList'{..}
= go _piolName _piolXgafv _piolUploadProtocol
_piolAccessToken
_piolUploadType
_piolFilter
_piolPageToken
_piolPageSize
_piolCallback
(Just AltJSON)
spannerService
where go
= buildClient
(Proxy ::
Proxy ProjectsInstancesOperationsListResource)
mempty
|
brendanhay/gogol
|
gogol-spanner/gen/Network/Google/Resource/Spanner/Projects/Instances/Operations/List.hs
|
mpl-2.0
| 7,387 | 0 | 18 | 1,608 | 976 | 571 | 405 | 138 | 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.AndroidManagement.Enterprises.Devices.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets a device.
--
-- /See:/ <https://developers.google.com/android/management Android Management API Reference> for @androidmanagement.enterprises.devices.get@.
module Network.Google.Resource.AndroidManagement.Enterprises.Devices.Get
(
-- * REST Resource
EnterprisesDevicesGetResource
-- * Creating a Request
, enterprisesDevicesGet
, EnterprisesDevicesGet
-- * Request Lenses
, edgXgafv
, edgUploadProtocol
, edgAccessToken
, edgUploadType
, edgName
, edgCallback
) where
import Network.Google.AndroidManagement.Types
import Network.Google.Prelude
-- | A resource alias for @androidmanagement.enterprises.devices.get@ method which the
-- 'EnterprisesDevicesGet' request conforms to.
type EnterprisesDevicesGetResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Device
-- | Gets a device.
--
-- /See:/ 'enterprisesDevicesGet' smart constructor.
data EnterprisesDevicesGet =
EnterprisesDevicesGet'
{ _edgXgafv :: !(Maybe Xgafv)
, _edgUploadProtocol :: !(Maybe Text)
, _edgAccessToken :: !(Maybe Text)
, _edgUploadType :: !(Maybe Text)
, _edgName :: !Text
, _edgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EnterprisesDevicesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'edgXgafv'
--
-- * 'edgUploadProtocol'
--
-- * 'edgAccessToken'
--
-- * 'edgUploadType'
--
-- * 'edgName'
--
-- * 'edgCallback'
enterprisesDevicesGet
:: Text -- ^ 'edgName'
-> EnterprisesDevicesGet
enterprisesDevicesGet pEdgName_ =
EnterprisesDevicesGet'
{ _edgXgafv = Nothing
, _edgUploadProtocol = Nothing
, _edgAccessToken = Nothing
, _edgUploadType = Nothing
, _edgName = pEdgName_
, _edgCallback = Nothing
}
-- | V1 error format.
edgXgafv :: Lens' EnterprisesDevicesGet (Maybe Xgafv)
edgXgafv = lens _edgXgafv (\ s a -> s{_edgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
edgUploadProtocol :: Lens' EnterprisesDevicesGet (Maybe Text)
edgUploadProtocol
= lens _edgUploadProtocol
(\ s a -> s{_edgUploadProtocol = a})
-- | OAuth access token.
edgAccessToken :: Lens' EnterprisesDevicesGet (Maybe Text)
edgAccessToken
= lens _edgAccessToken
(\ s a -> s{_edgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
edgUploadType :: Lens' EnterprisesDevicesGet (Maybe Text)
edgUploadType
= lens _edgUploadType
(\ s a -> s{_edgUploadType = a})
-- | The name of the device in the form
-- enterprises\/{enterpriseId}\/devices\/{deviceId}.
edgName :: Lens' EnterprisesDevicesGet Text
edgName = lens _edgName (\ s a -> s{_edgName = a})
-- | JSONP
edgCallback :: Lens' EnterprisesDevicesGet (Maybe Text)
edgCallback
= lens _edgCallback (\ s a -> s{_edgCallback = a})
instance GoogleRequest EnterprisesDevicesGet where
type Rs EnterprisesDevicesGet = Device
type Scopes EnterprisesDevicesGet =
'["https://www.googleapis.com/auth/androidmanagement"]
requestClient EnterprisesDevicesGet'{..}
= go _edgName _edgXgafv _edgUploadProtocol
_edgAccessToken
_edgUploadType
_edgCallback
(Just AltJSON)
androidManagementService
where go
= buildClient
(Proxy :: Proxy EnterprisesDevicesGetResource)
mempty
|
brendanhay/gogol
|
gogol-androidmanagement/gen/Network/Google/Resource/AndroidManagement/Enterprises/Devices/Get.hs
|
mpl-2.0
| 4,597 | 0 | 15 | 1,022 | 696 | 407 | 289 | 100 | 1 |
data MyRecord = MyRecord
{ a :: Int
-- comment
, b :: Int
}
|
lspitzner/brittany
|
data/Test63.hs
|
agpl-3.0
| 70 | 0 | 8 | 25 | 23 | 14 | 9 | 3 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
--------------------------------------------------------------------------------
-- See end of this file for licence information.
--------------------------------------------------------------------------------
-- |
-- Module : N3FormatterTest
-- Copyright : (c) 2003, Graham Klyne, 2009 Vasili I Galchin, 2011, 2012, 2013, 2014 Douglas Burke
-- License : GPL V2
--
-- Maintainer : Douglas Burke
-- Stability : experimental
-- Portability : CPP, OverloadedStrings
--
-- This Module defines test cases for module Parse parsing functions.
--
--------------------------------------------------------------------------------
module Main where
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
import qualified Data.Text.Lazy.Builder as B
import qualified Test.Framework as TF
import Swish.GraphClass (Arc, arc)
import Swish.Namespace (Namespace, makeNamespace, getNamespaceTuple, makeNSScopedName, namespaceToBuilder)
import Swish.QName (LName)
import Swish.RDF.Formatter.N3 (formatGraphAsLazyText, formatGraphDiag)
import Swish.RDF.Parser.N3 (parseN3)
import Swish.RDF.Graph
( RDFGraph, RDFTriple
, RDFLabel(..), ToRDFLabel
, NSGraph(..)
, NamespaceMap
, emptyRDFGraph, toRDFGraph, toRDFTriple
, resRdfType, resRdfFirst, resRdfRest, resRdfNil
, resOwlSameAs
)
import Swish.RDF.Vocabulary (toLangTag, namespaceRDF, namespaceXSD)
import Network.URI (URI, parseURI)
#if (!defined(__GLASGOW_HASKELL__)) || (__GLASGOW_HASKELL__ < 710)
import Data.Monoid (Monoid(..))
#endif
import Data.Maybe (fromJust)
import Data.String (IsString(..))
import Test.HUnit
( Test(TestCase,TestList)
, assertEqual )
import TestHelpers (conv, testCompareEq)
-- Specialized equality comparisons
testLabelEq :: String -> Bool -> RDFLabel -> RDFLabel -> Test
testLabelEq = testCompareEq "testLabelEq:"
testGraphEq :: String -> Bool -> RDFGraph -> RDFGraph -> Test
testGraphEq = testCompareEq "testGraphEq:"
------------------------------------------------------------
-- Define some common values
------------------------------------------------------------
toURI :: String -> URI
toURI = fromJust . parseURI
toNS :: T.Text -> String -> Namespace
toNS p = makeNamespace (Just p) . toURI
toRes :: Namespace -> LName -> RDFLabel
toRes ns = Res . makeNSScopedName ns
base1, base2, base3, base4, basef, baseu, basem :: Namespace
base1 = toNS "base1" "http://id.ninebynine.org/wip/2003/test/graph1/node#"
base2 = toNS "base2" "http://id.ninebynine.org/wip/2003/test/graph2/node/"
base3 = toNS "base3" "http://id.ninebynine.org/wip/2003/test/graph3/node"
base4 = toNS "base4" "http://id.ninebynine.org/wip/2003/test/graph3/nodebase"
basef = toNS "fbase" "file:///home/swish/photos/"
baseu = toNS "ubase" "urn:one:two:3.14"
basem = toNS "me" "http://example.com/ns#"
s1, s2, s3, sf, su :: RDFLabel
s1 = toRes base1 "s1"
s2 = toRes base2 "s2"
s3 = toRes base3 "s3"
sf = toRes basef "me.png"
su = toRes baseu ""
meDepicts, meMe, meHasURN :: RDFLabel
meDepicts = toRes basem "depicts"
meMe = toRes basem "me"
meHasURN = toRes basem "hasURN"
b1, b2, b3, b4, b5, b6, b7, b8 :: RDFLabel
b1 = Blank "b1"
b2 = Blank "b2"
b3 = Blank "b3"
b4 = Blank "b4"
b5 = Blank "b5"
b6 = Blank "b6"
b7 = Blank "b7"
b8 = Blank "b8"
c1, c2, c3, c4, c5, c6 :: RDFLabel
c1 = Blank "c1"
c2 = Blank "c2"
c3 = Blank "c3"
c4 = Blank "c4"
c5 = Blank "c5"
c6 = Blank "c6"
p1, p2, p3, p21, p22, p23, p24, p25, p26 :: RDFLabel
p1 = Res $ makeNSScopedName base1 "p1"
p2 = Res $ makeNSScopedName base2 "p2"
p3 = Res $ makeNSScopedName base3 "p3"
p21 = Res $ makeNSScopedName base2 "p21"
p22 = Res $ makeNSScopedName base2 "p22"
p23 = Res $ makeNSScopedName base2 "p23"
p24 = Res $ makeNSScopedName base2 "p24"
p25 = Res $ makeNSScopedName base2 "p25"
p26 = Res $ makeNSScopedName base2 "p26"
o1, o2, o3 :: RDFLabel
o1 = Res $ makeNSScopedName base1 "o1"
o2 = Res $ makeNSScopedName base2 "o2"
o3 = Res $ makeNSScopedName base3 "o3"
l1txt, l2txt, l3txt, l11txt, l12txt, l13txt, l14txt :: B.Builder
l1txt = "l1"
l2txt = "l2-'\"line1\"'\n\nl2-'\"\"line2\"\"'"
l3txt = "l3--\r\"'\\--\x0020\&--\x00A0\&--"
l11txt = "lx11"
l12txt = "lx12"
l13txt = "lx13"
l14txt = "lx14"
toL :: B.Builder -> RDFLabel
toL = Lit . L.toStrict . B.toLazyText
l1, l2, l3, l11, l12, l13, l14 :: RDFLabel
l1 = toL l1txt
l2 = toL l2txt
l3 = toL l3txt
l11 = toL l11txt
l12 = toL l12txt
l13 = toL l13txt
l14 = toL l14txt
lfr, lfoobar :: RDFLabel
lfr = LangLit "chat et chien" (fromJust $ toLangTag "fr")
lfoobar = TypedLit "foo bar" (makeNSScopedName base1 "o1")
f1, f2 :: RDFLabel
f1 = Res $ makeNSScopedName base1 "f1"
f2 = Res $ makeNSScopedName base2 "f2"
v1, v2, v3, v4 :: RDFLabel
v1 = Var "var1"
v2 = Var "var2"
v3 = Var "var3"
v4 = Var "var4"
------------------------------------------------------------
-- Construct graphs for testing
------------------------------------------------------------
t01, t02, t03, t04, t05, t06, t07 :: Arc RDFLabel
t01 = arc s1 p1 o1
t02 = arc s2 p1 o2
t03 = arc s3 p1 o3
t04 = arc s1 p1 l1
t05 = arc s2 p1 b1
t06 = arc s3 p1 l2
t07 = arc s3 p2 l3
nslist :: NamespaceMap
nslist = M.fromList $ map getNamespaceTuple
[ base1
, base2
, base3
, base4
]
g1np :: RDFGraph
g1np = emptyRDFGraph { namespaces = uncurry M.singleton (getNamespaceTuple base1)
, statements = S.singleton t01 }
toGraph :: [Arc RDFLabel] -> RDFGraph
toGraph arcs = (toRDFGraph (S.fromList arcs)) {namespaces = nslist}
g1, g1b1, g1b3, g1a1, g1l1, g1l2 :: RDFGraph
g1 = toGraph [t01]
g1b1 = toGraph [arc b1 p1 o1]
g1b3 = toGraph [arc b1 b2 b3]
g1a1 = toGraph [arc (Blank "1") p1 o1]
g1l1 = toGraph [arc s1 p1 l1]
g1l2 = toGraph [arc s1 p1 l2]
{-
g1f1 = NSGraph
{ namespaces = nslist
, formulae = M.singleton o1 (Formula o1g1)
, statements = [f01]
}
where
f01 = arc s1 p1 o1
-}
g1f2, g1f3 :: RDFGraph
g1f2 = NSGraph
{ namespaces = nslist
, formulae = M.singleton b2 g1 -- $ Formula b2 g1
, statements = S.singleton $ arc s1 p1 b2
}
g1f3 = NSGraph
{ namespaces = nslist
, formulae = M.singleton b3 g1f2 -- $ Formula b3 g1f2
, statements = S.singleton $ arc s1 p1 b3
}
g1fu1 :: RDFGraph
g1fu1 =
mempty
{ namespaces =
M.fromList $ map getNamespaceTuple
[basem, makeNamespace Nothing (toURI "file:///home/swish/photos/")]
, statements = S.fromList [arc sf meDepicts meMe, arc sf meHasURN su]
}
----
g2, g3, g4, g5, g6, g7 :: RDFGraph
g2 = toRDFGraph $ S.fromList [t01,t02,t03]
g3 = toGraph [t01,t04]
g4 = toGraph [t01,t05]
g5 = toGraph [t01,t02,t03,t04,t05]
g6 = toGraph [t01,t06]
g7 = toGraph [t01,t07]
t801, t802, t807, t808, t809, t810 :: Arc RDFLabel
t801 = arc s1 resRdfType o1
t802 = arc s2 resOwlSameAs o2
t807 = arc o1 p1 s1
t808 = arc s2 p1 o2
t809 = arc s1 p2 o1
t810 = arc o2 p2 s2
g8, g81, g83 :: RDFGraph
g8 = toGraph [t801,t802,t807,t808,t809,t810]
g81 = toGraph [t801,t802]
g83 = toGraph [t807,t808,t809,t810]
t911, t912, t913, t914, t921, t922, t923, t924,
t925, t926, t927, t928 :: Arc RDFLabel
t911 = arc s1 p1 o1
t912 = arc s1 p1 o2
t913 = arc s1 p2 o2
t914 = arc s1 p2 o3
t921 = arc s2 p1 o1
t922 = arc s2 p1 o2
t923 = arc s2 p1 o3
t924 = arc s2 p1 l1
t925 = arc s2 p2 o1
t926 = arc s2 p2 o2
t927 = arc s2 p2 o3
t928 = arc s2 p2 l1
g9 :: RDFGraph
g9 = toGraph [t911,t912,t913,t914,
t921,t922,t923,t924,
t925,t926,t927,t928]
t1011, t1012, t1013, t1014, t1021, t1022, t1023, t1024,
t1025, t1026, t1027, t1028 :: Arc RDFLabel
t1011 = arc s1 p1 o1
t1012 = arc o2 p1 s1
t1013 = arc s1 p2 o2
t1014 = arc o3 p2 s1
t1021 = arc s2 p1 o1
t1022 = arc s2 p1 o2
t1023 = arc s2 p1 o3
t1024 = arc s2 p1 l1
t1025 = arc o1 p2 s2
t1026 = arc o2 p2 s2
t1027 = arc o3 p2 s2
-- t1028 = arc l1 p2 s2
t1028 = arc s1 p2 s2
g10 :: RDFGraph
g10 = toGraph [t1011,t1012,t1013,t1014,
t1021,t1022,t1023,t1024,
t1025,t1026,t1027,t1028]
g11 :: RDFGraph
g11 = toGraph [ arc s1 p1 v1
, arc v2 p1 o1
, arc v3 p1 v4]
tx101, tx102, tx111, tx112, tx113, tx114,
tx121, tx122, tx123, tx124, tx125, tx126,
tx127, tx128 :: Arc RDFLabel
tx101 = arc b1 resOwlSameAs s1
tx102 = arc s2 resOwlSameAs b2
tx111 = arc b1 p1 o1
tx112 = arc b1 p1 o2
tx113 = arc b1 p2 o2
tx114 = arc b1 p2 o3
tx121 = arc b2 p1 o1
tx122 = arc b2 p1 o2
tx123 = arc b2 p1 o3
tx124 = arc b2 p1 l1
tx125 = arc b2 p2 o1
tx126 = arc b2 p2 o2
tx127 = arc b2 p2 o3
tx128 = arc b2 p2 l2
x1 :: RDFGraph
x1 = toGraph [tx101,tx102,
tx111,tx112,tx113,tx114,
tx121,tx122,tx123,tx124,
tx125,tx126,tx127,tx128]
tx201, tx202, tx211, tx212, tx213, tx214,
tx221, tx222, tx223, tx224, tx225, tx226,
tx227 :: Arc RDFLabel
tx201 = arc b1 resOwlSameAs s1
tx202 = arc s2 resOwlSameAs b2
tx211 = arc b1 p1 o1
tx212 = arc o2 p1 b1
tx213 = arc b1 p2 o2
tx214 = arc o3 p2 b1
tx221 = arc b2 p1 o1
tx222 = arc b2 p1 o2
tx223 = arc b2 p1 o3
tx224 = arc b2 p1 l1
tx225 = arc o1 p2 b2
tx226 = arc o2 p2 b2
tx227 = arc o3 p2 b2
-- tx228 = arc l1 p2 b2
x2 :: RDFGraph
x2 = toGraph [tx201,tx202,
tx211,tx212,tx213,tx214,
tx221,tx222,tx223,tx224,
tx225,tx226,tx227]
tx311, tx312, tx313, tx314,
tx321, tx322, tx323, tx324, tx325, tx326,
tx327 :: Arc RDFLabel
tx311 = arc s1 p1 o1
tx312 = arc o2 p1 s1
tx313 = arc s1 p2 o2
tx314 = arc o3 p2 s1
tx321 = arc s2 p1 o1
tx322 = arc s2 p1 o2
tx323 = arc s2 p1 o3
tx324 = arc s2 p1 l1
tx325 = arc o1 p2 s2
tx326 = arc o2 p2 s2
tx327 = arc o3 p2 s2
-- tx328 = arc l1 p2 s2
x3 :: RDFGraph
x3 = toGraph [tx311,tx312,tx313,tx314,
tx321,tx322,tx323,tx324,
tx325,tx326,tx327]
tx401, tx402, tx403, tx404, tx405, tx406,
tx407, tx408, tx409 :: Arc RDFLabel
tx401 = arc s1 resOwlSameAs b1
tx402 = arc b1 resRdfFirst o1
tx403 = arc b1 resRdfRest b2
tx404 = arc b2 resRdfFirst o2
tx405 = arc b2 resRdfRest b3
tx406 = arc b3 resRdfFirst o3
tx407 = arc b3 resRdfRest b4
tx408 = arc b4 resRdfFirst l1
tx409 = arc b4 resRdfRest resRdfNil
x4 :: RDFGraph
x4 = toGraph [tx401,tx402,tx403,tx404,
tx405,tx406,tx407,tx408,
tx409]
x5 :: RDFGraph
x5 = toGraph [ arc b1 resOwlSameAs s1
, arc b1 resRdfFirst o1
, arc b1 resRdfRest b2
, arc b2 resRdfFirst o2
, arc b2 resRdfRest b3
, arc b3 resRdfFirst o3
, arc b3 resRdfRest b4
, arc b4 resRdfFirst l1
, arc b4 resRdfRest resRdfNil
]
{-
I was aiming for
:s1 = (
:o1
b2:o2
b3:o3
"l1" ) .
but really it's
:s1 rdf:first ( b1:o1 b2:o2 b3:o3 "l1" ) .
or something like that. different versions of
cwm parse the triples differently, and it depends
on the output format too (eg n3 vs ntriples).
-}
x6 :: RDFGraph
x6 = toGraph [ arc s1 resRdfFirst o1
, arc s1 resRdfRest b2
, arc b2 resRdfFirst o2
, arc b2 resRdfRest b3
, arc b3 resRdfFirst o3
, arc b3 resRdfRest b4
, arc b4 resRdfFirst l1
, arc b4 resRdfRest resRdfNil
]
x7 :: RDFGraph
x7 = NSGraph
{ namespaces = nslist
, formulae = M.singleton b1 g2 -- $ Formula b1 g2
, statements = S.singleton $ arc b1 p2 f2
}
x8 :: RDFGraph
x8 = NSGraph
{ namespaces = nslist
, formulae = M.singleton f1 g2 -- $ Formula f1 g2
, statements = S.singleton $ arc f1 p2 f2
}
x9 :: RDFGraph
x9 = NSGraph
{ namespaces = nslist
, formulae = M.singleton f1 g1 -- $ Formula f1 g1
, statements = S.singleton $ arc f1 p2 f2
}
-- Test allocation of bnodes carries over a nested formula
x12, x12fg :: RDFGraph
x12 = NSGraph
{ namespaces = nslist
, formulae = M.singleton b2 x12fg -- $ Formula b2 x12fg
, statements = S.fromList
[ arc s1 p1 b1
, arc b1 p1 o1
, arc b2 p2 f2
, arc s3 p3 b3
, arc b3 p3 o3
]
}
x12fg = toRDFGraph $ S.fromList
[ arc s2 p2 b4
, arc b4 p2 o2
]
-- List of simple anon nodes
x13 :: RDFGraph
x13 = toGraph [ arc s1 resRdfFirst b1
, arc s1 resRdfRest c1
, arc c1 resRdfFirst b2
, arc c1 resRdfRest c2
, arc c2 resRdfFirst b3
, arc c2 resRdfRest resRdfNil
, arc b1 p1 o1
, arc b2 p1 o2
, arc b3 p1 o3
]
-- List of simple anon nodes using autogenerated bnodes
x13a :: RDFGraph
x13a = toGraph [ arc s1 resRdfFirst b_1
, arc s1 resRdfRest c_1
, arc c_1 resRdfFirst b_2
, arc c_1 resRdfRest c_2
, arc c_2 resRdfFirst b_3
, arc c_2 resRdfRest resRdfNil
, arc b_1 p1 o1
, arc b_2 p1 o2
, arc b_3 p1 o3
]
where
b_1 = Blank "1"
b_2 = Blank "2"
b_3 = Blank "3"
c_1 = Blank "4"
c_2 = Blank "5"
-- List of more complex anon nodes
x14 :: RDFGraph
x14 = toGraph [ arc s1 resRdfFirst b1
, arc s1 resRdfRest c1
, arc c1 resRdfFirst b2
, arc c1 resRdfRest c2
, arc c2 resRdfFirst b3
, arc c2 resRdfRest resRdfNil
, arc b1 p1 o1
, arc b1 p2 o1
, arc b2 p1 o2
, arc b2 p2 o2
, arc b3 p1 o3
, arc b3 p2 o3
]
-- List with nested list
x15 :: RDFGraph
x15 = toGraph [ arc s1 resRdfFirst b1
, arc s1 resRdfRest c1
, arc c1 resRdfFirst b2
, arc c1 resRdfRest c2
, arc c2 resRdfFirst b3
, arc c2 resRdfRest resRdfNil
, arc b1 p1 o1
, arc b2 p2 c3
, arc b3 p1 o3
, arc c3 resRdfFirst b4
, arc c3 resRdfRest c4
, arc c4 resRdfFirst b5
, arc c4 resRdfRest c5
, arc c5 resRdfFirst b6
, arc c5 resRdfRest resRdfNil
, arc b4 p1 o1
, arc b5 p1 o2
, arc b6 p1 o3
]
-- More complex list with nested list
x16 :: RDFGraph
x16 = toGraph [ arc s1 resRdfFirst b1
, arc s1 resRdfRest c1
, arc c1 resRdfFirst b2
, arc c1 resRdfRest c2
, arc c2 resRdfFirst b3
, arc c2 resRdfRest resRdfNil
, arc b1 p1 o1
, arc b1 p2 o1
, arc b2 p2 c3
, arc b3 p1 o3
, arc b3 p2 o3
, arc c3 resRdfFirst b4
, arc c3 resRdfRest c4
, arc c4 resRdfFirst b5
, arc c4 resRdfRest c5
, arc c5 resRdfFirst b6
, arc c5 resRdfRest resRdfNil
, arc b4 p1 o1
, arc b4 p2 o1
, arc b5 p1 o2
, arc b5 p2 o2
, arc b6 p1 o3
, arc b6 p2 o3
]
-- Troublesome example
x17 :: RDFGraph
x17 = toGraph [ arc s1 resRdfType o1
, arc s1 resRdfFirst b1
, arc s1 resRdfRest c1
, arc c1 resRdfFirst b2
, arc c1 resRdfRest resRdfNil
, arc b1 p21 o2
, arc b1 p22 c2
, arc b2 p24 o3
, arc b2 p25 l13
, arc c2 resRdfFirst b3
, arc c2 resRdfRest c3
, arc c3 resRdfFirst l12
, arc c3 resRdfRest resRdfNil
, arc b3 p23 l11
]
-- collection graphs
graph_c1, graph_c1rev, graph_c2, graph_c2rev,
graph_c3 :: RDFGraph
graph_c1 = toGraph [arc s1 p1 resRdfNil]
graph_c1rev = toGraph [arc resRdfNil p1 o1]
graph_c2 = toGraph [arc s1 p1 b1,
arc b1 resRdfFirst l1,
arc b1 resRdfRest b2,
arc b2 resRdfFirst o2,
arc b2 resRdfRest b3,
arc b3 resRdfFirst l2,
arc b3 resRdfRest b4,
arc b4 resRdfFirst o3,
arc b4 resRdfRest resRdfNil]
graph_c2rev = toGraph [arc b1 resRdfFirst l1,
arc b1 resRdfRest b2,
arc b2 resRdfFirst o2,
arc b2 resRdfRest b3,
arc b3 resRdfFirst l2,
arc b3 resRdfRest b4,
arc b4 resRdfFirst o3,
arc b4 resRdfRest resRdfNil,
arc b1 p1 o1]
graph_c3 = toGraph [arc s1 p1 b1,
arc b1 resRdfFirst l1,
arc b1 resRdfRest b2,
arc b2 resRdfFirst o2,
arc b2 resRdfRest b3,
arc b3 resRdfFirst l2,
arc b3 resRdfRest b4,
arc b4 resRdfFirst o3,
arc b4 resRdfRest resRdfNil,
arc s1 p2 resRdfNil,
arc s2 p2 o2]
-- bnode graphs
graph_b1, graph_b1rev, graph_b2, graph_b2rev, graph_b3,
graph_b4, graph_b5 :: RDFGraph
graph_b1 = toRDFGraph $ S.singleton $ arc s1 p1 b1
graph_b1rev = toRDFGraph $ S.singleton $ arc b1 p1 o1
graph_b2 = toRDFGraph $ S.fromList [arc s1 p1 b1,
arc b1 p2 l1,
arc b1 o2 o3]
graph_b2rev = toRDFGraph $ S.fromList [arc b1 p2 l1,
arc b1 o2 o3,
arc b1 p1 o1]
graph_b3 = toRDFGraph $ S.fromList [arc s1 p1 b1,
arc b1 p2 l2,
arc b1 o2 o3,
arc s1 p2 b2,
arc s2 p2 o2]
graph_b4 = toRDFGraph $ S.fromList [arc b1 resRdfType o1,
arc b2 resRdfType o2]
graph_b5 = toRDFGraph $ S.fromList [arc b1 resRdfType o1,
arc b2 p2 o2,
arc b3 resRdfType o3]
-- datatype/literal graphs
graph_l1, graph_l2, graph_l3, graph_l4 :: RDFGraph
graph_l1 = toGraph [arc s1 p1 lfr]
graph_l2 = toGraph [arc s1 p1 lfoobar]
graph_l3 =
let tf :: ToRDFLabel a => a -> RDFTriple
tf = toRDFTriple s1 p1
arcs = [ tf True
, tf (12::Int)
-- so, issue over comparing -2.304e-108 and value read in from string
-- due to comparing a ScopedName instance built from a RDFLabel
-- as the hash used in the comparison is based on the Show value
-- but then why isn't this a problem for Float
, tf ((-2.304e-108)::Double)
, tf (23.4::Float)
]
{-
gtmp = toRDFGraph arcs
in gtmp { namespaces =
M.insert (Just "xsd") ("http://www.w3.org/2001/XMLSchema#")
(namespaces gtmp)
}
-}
in toRDFGraph $ S.fromList arcs
graph_l4 = toGraph [ toRDFTriple s1 p1 ("A string with \"quotes\"" :: RDFLabel)
, toRDFTriple s2 p2 (TypedLit "A typed string with \"quotes\"" (fromString "urn:a#b"))
]
------------------------------------------------------------
-- Trivial formatter tests
------------------------------------------------------------
--
-- These are very basic tests that confirm that output for a
-- simple graph corresponds exactly to some supplied string.
formatTest :: String -> RDFGraph -> B.Builder -> Test
formatTest lab gr out =
TestList
[ TestCase ( assertEqual ("formatTest:"++lab) outTxt res )
]
where
outTxt = B.toLazyText out
res = formatGraphAsLazyText gr
diagTest :: String -> RDFGraph -> L.Text -> Test
diagTest lab gr out =
TestList
[ TestCase ( assertEqual ("diag:text:"++lab) out resTxt )
, TestCase ( assertEqual ("diag:map:"++lab) M.empty nmap )
, TestCase ( assertEqual ("diag:gen:"++lab) 0 ngen )
, TestCase ( assertEqual ("diag:trc:"++lab) [] trc )
]
where
(res,nmap,ngen,trc) = formatGraphDiag "\n" True gr
resTxt = B.toLazyText res
mkPrefix :: Namespace -> B.Builder
mkPrefix = namespaceToBuilder
prefixList :: [B.Builder]
prefixList =
[ mkPrefix base1
, mkPrefix base2
, mkPrefix base3
, mkPrefix base4
, mkPrefix namespaceRDF
, mkPrefix namespaceXSD
]
commonPrefixesN :: [Int] -> B.Builder
commonPrefixesN = mconcat . map (prefixList !!)
commonPrefixes :: B.Builder
commonPrefixes = commonPrefixesN [0..3]
commonPrefixes21, commonPrefixes321, commonPrefixes132 :: B.Builder
commonPrefixes21 = commonPrefixesN [1,0]
commonPrefixes321 = commonPrefixesN [2,1,0]
commonPrefixes132 = commonPrefixesN [0,2,1]
-- Single statement using <uri> form
simpleN3Graph_g1_01 :: B.Builder
simpleN3Graph_g1_01 =
"<http://id.ninebynine.org/wip/2003/test/graph1/node#s1> <http://id.ninebynine.org/wip/2003/test/graph1/node#p1> <http://id.ninebynine.org/wip/2003/test/graph1/node#o1> .\n"
-- Single statement using prefix:name form
simpleN3Graph_g1_02 :: B.Builder
simpleN3Graph_g1_02 =
commonPrefixes `mappend`
"base1:s1 base1:p1 base1:o1 .\n"
-- Single blank node
simpleN3Graph_g1_03 :: B.Builder
simpleN3Graph_g1_03 =
commonPrefixes `mappend`
"[\n base1:p1 base1:o1\n] .\n"
-- Single auto-allocated blank node
simpleN3Graph_g1_04 :: B.Builder
simpleN3Graph_g1_04 =
commonPrefixes `mappend`
"[\n base1:p1 base1:o1\n] .\n"
-- Single literal object
simpleN3Graph_g1_05 :: B.Builder
simpleN3Graph_g1_05 =
commonPrefixes `mappend`
"base1:s1 base1:p1 \"l1\" .\n"
-- Single multiline literal object
simpleN3Graph_g1_06 :: B.Builder
simpleN3Graph_g1_06 =
commonPrefixes `mappend`
"base1:s1 base1:p1 \"l2-'\\\"line1\\\"'\\n\\nl2-'\\\"\\\"line2\\\"\\\"'\" .\n"
-- this 'round trips' into a triple-quoted string
simpleN3Graph_g1_06_rt :: B.Builder
simpleN3Graph_g1_06_rt =
commonPrefixes `mappend`
"base1:s1 base1:p1 \"\"\"l2-'\"line1\"'\n\nl2-'\"\"line2\"\"'\"\"\" .\n"
{-
-- Single statement with formula node
simpleN3Graph_g1_07 =
commonPrefixes ++
"base1:s1 base1:p1 base1:o1 .\n"++
"base1:o1 :-\n"++
" {\n"++
" base1:s1 base1:p1 base1:o1\n"++
" } .\n"
-}
-- Single statement with formula blank node
simpleN3Graph_g1_08 :: B.Builder
simpleN3Graph_g1_08 =
mconcat
[ commonPrefixes
, "base1:s1 base1:p1 { \n"
, " base1:s1 base1:p1 base1:o1\n"
, " } .\n"
]
-- Three blank nodes (or is that blind mice?)
simpleN3Graph_g1_09 :: B.Builder
simpleN3Graph_g1_09 =
commonPrefixes `mappend`
"[\n _:b2 []\n] .\n"
-- Simple nested formula case
simpleN3Graph_g1_10 :: B.Builder
simpleN3Graph_g1_10 =
mconcat
[ commonPrefixes
, "base1:s1 base1:p1 { \n"
, " base1:s1 base1:p1 { \n"
, " base1:s1 base1:p1 base1:o1\n"
, " } \n"
, " } .\n"
]
-- try out URIs that do not use the http scheme
simpleN3Graph_g1_fu1 :: B.Builder
simpleN3Graph_g1_fu1 =
mconcat
[ "@prefix : <file:///home/swish/photos/> .\n"
, "@prefix me: <http://example.com/ns#> .\n"
-- , ":me.png me:depicts me:me ;\n"
, "<file:///home/swish/photos/me.png> me:depicts me:me ;\n"
, " me:hasURN <urn:one:two:3.14> .\n"
]
{-
Simple troublesome case
Changed Aug 15 2013 to support rendering
_:a :knows _:b . _:b :knows _:a .
which, as currently implemented, loses the ability to make the simplification below.
simpleN3Graph_x13a =
mconcat
[ commonPrefixes
, "base1:s1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "
, b1s
, " ;\n"
, " <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> ( ", b2s, " ", b3s, " ) .\n"
]
where
b1s = "[\n base1:p1 base1:o1\n]"
b2s = "[\n base1:p1 base2:o2\n]"
b3s = "[\n base1:p1 base3:o3\n]"
-}
simpleN3Graph_x13a :: B.Builder
simpleN3Graph_x13a =
mconcat
[ commonPrefixes
, "base1:s1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "
, b1n
, " ;\n <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> ( ", b2n, " ", b3n, " ) .\n"
, b1n, " base1:p1 base1:o1 .\n"
, b2n, " base1:p1 base2:o2 .\n"
, b3n, " base1:p1 base3:o3 .\n"
]
where
b1n = "_:swish1"
b2n = "_:swish2"
b3n = "_:swish3"
{-
Simple collection tests; may replicate some of the
previous tests.
-}
simpleN3Graph_c1 :: B.Builder
simpleN3Graph_c1 =
commonPrefixes `mappend`
"base1:s1 base1:p1 () .\n"
simpleN3Graph_c1rev :: B.Builder
simpleN3Graph_c1rev =
commonPrefixes `mappend`
"() base1:p1 base1:o1 .\n"
collItems :: B.Builder
collItems =
mconcat
[ "( \"l1\" base2:o2 \"\"\""
, l2txt
, "\"\"\" base3:o3 )" ]
simpleN3Graph_c2 :: B.Builder
simpleN3Graph_c2 =
mconcat
[ commonPrefixes
, "base1:s1 base1:p1 "
, collItems
, " .\n" ]
simpleN3Graph_c2rev :: B.Builder
simpleN3Graph_c2rev =
mconcat
[ commonPrefixes
, collItems, " base1:p1 base1:o1 .\n" ]
simpleN3Graph_c3 :: B.Builder
simpleN3Graph_c3 =
mconcat
[ commonPrefixes
, "base1:s1 base1:p1 ", collItems, " ;\n"
, " base2:p2 () .\n"
, "base2:s2 base2:p2 base2:o2 .\n" ]
{-
Simple bnode tests; may replicate some of the
previous tests.
-}
simpleN3Graph_b1 :: B.Builder
simpleN3Graph_b1 =
commonPrefixesN [0] `mappend`
"base1:s1 base1:p1 [] .\n"
simpleN3Graph_b1rev :: B.Builder
simpleN3Graph_b1rev =
commonPrefixesN [0] `mappend`
"[\n base1:p1 base1:o1\n] .\n"
{-
See discussion of simpleN3Graph_x13a for why this has been changed
simpleN3Graph_b2 =
commonPrefixesN [0,1,2] `mappend`
"base1:s1 base1:p1 [\n base2:o2 base3:o3 ;\n base2:p2 \"l1\"\n] .\n"
-}
simpleN3Graph_b2 :: B.Builder
simpleN3Graph_b2 =
commonPrefixesN [0,1,2] `mappend`
"base1:s1 base1:p1 _:b1 .\n_:b1 base2:o2 base3:o3 ;\n base2:p2 \"l1\" .\n"
simpleN3Graph_b2rev :: B.Builder
simpleN3Graph_b2rev =
commonPrefixesN [0,1,2] `mappend`
"[\n base1:p1 base1:o1 ;\n base2:o2 base3:o3 ;\n base2:p2 \"l1\"\n] .\n"
{-
See discussion of simpleN3Graph_x13a for why this has been changed
simpleN3Graph_b3 =
mconcat
[ commonPrefixesN [0,1,2]
, "base1:s1 base1:p1 [\n base2:o2 base3:o3 ;\n base2:p2 \"\"\"", l2txt, "\"\"\"\n] ;\n"
, " base2:p2 [] .\n"
, "base2:s2 base2:p2 base2:o2 .\n" ]
-}
simpleN3Graph_b3 :: B.Builder
simpleN3Graph_b3 =
mconcat
[ commonPrefixesN [0,1,2]
, "base1:s1 base1:p1 _:b1 ;\n"
, " base2:p2 [] .\n"
, "base2:s2 base2:p2 base2:o2 .\n"
, "_:b1 base2:o2 base3:o3 ;\n base2:p2 \"\"\"", l2txt, "\"\"\" .\n"
]
simpleN3Graph_b4 :: B.Builder
simpleN3Graph_b4 =
mconcat
[ commonPrefixesN [0,1,4]
, "[\n a base1:o1\n] .\n"
, "[\n a base2:o2\n] .\n" ]
simpleN3Graph_b5 :: B.Builder
simpleN3Graph_b5 =
mconcat
[ commonPrefixesN [0,1,2,4]
, "[\n a base1:o1\n] .\n"
, "[\n base2:p2 base2:o2\n] .\n"
, "[\n a base3:o3\n] .\n" ]
{-
Simple datatype/language tests; may replicate some of the
previous tests.
-}
simpleN3Graph_l1 :: B.Builder
simpleN3Graph_l1 =
commonPrefixes `mappend`
"base1:s1 base1:p1 \"chat et chien\"@fr .\n"
simpleN3Graph_l2 :: B.Builder
simpleN3Graph_l2 =
commonPrefixes `mappend`
"base1:s1 base1:p1 \"foo bar\"^^base1:o1 .\n"
simpleN3Graph_l3 :: B.Builder
simpleN3Graph_l3 =
mconcat
[ commonPrefixesN [0, 5]
, "\n" -- TODO: why do we need this newline?
, "base1:s1 base1:p1 -2.304e-108,\n"
, " 12,\n"
, " \"2.34E1\"^^xsd:float, true .\n" ]
simpleN3Graph_l4 :: B.Builder
simpleN3Graph_l4 =
mconcat
[ commonPrefixes
, "base1:s1 base1:p1 \"\"\"A string with \"quotes\\\"\"\"\" .\n"
, "base2:s2 base2:p2 \"\"\"A typed string with \"quotes\\\"\"\"\"^^<urn:a#b> .\n" ]
trivialTestSuite :: Test
trivialTestSuite = TestList
[ -- formatTest "trivialTest01" g1np simpleN3Graph_g1_01 - no longer valid as now add in a prefix/namespace declaration
formatTest "trivialTest02" g1 simpleN3Graph_g1_02
, formatTest "trivialTest03" g1b1 simpleN3Graph_g1_03
, formatTest "trivialTest04" g1a1 simpleN3Graph_g1_04
, formatTest "trivialTest05" g1l1 simpleN3Graph_g1_05
, formatTest "trivialTest06" g1l2 simpleN3Graph_g1_06_rt
-- trivialTest07 = formatTest "trivialTest07" g1f1 simpleN3Graph_g1_07 -- formula is a named node
, formatTest "trivialTest08" g1f2 simpleN3Graph_g1_08
, formatTest "trivialTest09" g1b3 simpleN3Graph_g1_09
, formatTest "trivialTest10" g1f3 simpleN3Graph_g1_10
, formatTest "trivialTest13a" x13a simpleN3Graph_x13a
, formatTest "trivialTestfu1" g1fu1 simpleN3Graph_g1_fu1
, formatTest "trivialTestc1" graph_c1 simpleN3Graph_c1
, formatTest "trivialTestc2" graph_c2 simpleN3Graph_c2
, formatTest "trivialTestc3" graph_c3 simpleN3Graph_c3
, formatTest "trivialTestc1rev" graph_c1rev simpleN3Graph_c1rev
, formatTest "trivialTestc2rev" graph_c2rev simpleN3Graph_c2rev
, formatTest "trivialTestb1" graph_b1 simpleN3Graph_b1
, formatTest "trivialTestb2" graph_b2 simpleN3Graph_b2
, formatTest "trivialTestb3" graph_b3 simpleN3Graph_b3
, formatTest "trivialTestb4" graph_b4 simpleN3Graph_b4
, formatTest "trivialTestb5" graph_b5 simpleN3Graph_b5
, formatTest "trivialTestb1rev" graph_b1rev simpleN3Graph_b1rev
, formatTest "trivialTestb2rev" graph_b2rev simpleN3Graph_b2rev
, formatTest "lit1" graph_l1 simpleN3Graph_l1
, formatTest "lit2" graph_l2 simpleN3Graph_l2
, formatTest "lit3" graph_l3 simpleN3Graph_l3
, formatTest "lit4" graph_l4 simpleN3Graph_l4
, formatTest "trivialTestx4" x4 exoticN3Graph_x4
, formatTest "trivialTestx5" x5 exoticN3Graph_x5
, formatTest "trivialTestx7" x7 exoticN3Graph_x7
]
------------------------------------------------------------
-- Parser tests to cross-check round-trip testing
------------------------------------------------------------
parseTest :: String -> B.Builder -> RDFGraph -> String -> Test
parseTest lab inp gr er =
TestList
[ TestCase ( assertEqual ("parseTestError:"++lab) er pe )
, TestCase ( assertEqual ("parseTestGraph:"++lab) gr pg )
]
where
(pe,pg) = case parseN3 (B.toLazyText inp) Nothing of
Right g -> ("", g)
Left s -> (s, emptyRDFGraph)
noError, errorText :: String
noError = ""
errorText = "*"
parseTestSuite :: Test
parseTestSuite = TestList
[ parseTest "01" simpleN3Graph_g1_01 g1np noError
, parseTest "02" simpleN3Graph_g1_02 g1 noError
, parseTest "03" simpleN3Graph_g1_03 g1b1 noError
, parseTest "04" simpleN3Graph_g1_04 g1a1 noError
, parseTest "05" simpleN3Graph_g1_05 g1l1 noError
, parseTest "06" simpleN3Graph_g1_06 g1l2 noError
, parseTest "06rt" simpleN3Graph_g1_06_rt g1l2 noError
-- parseTest07 = parseTest "07" simpleN3Graph_g1_07 g1f1 noError -- formula is a named node
, parseTest "08" simpleN3Graph_g1_08 g1f2 noError
]
------------------------------------------------------------
-- Repeat above tests using parser and graph-comparison
------------------------------------------------------------
--
-- This establishes a framework that will be used for
-- more complex tests that are less susceptible to trivial
-- formatting differences. The idea is to generate output
-- that can be parsed to obtain an equivalent graph.
roundTripTest :: String -> RDFGraph -> Test
roundTripTest lab gr =
TestList
[ TestCase ( assertEqual ("RoundTrip:gr:"++lab) gr pg )
, TestCase ( assertEqual ("RoundTrip:er:"++lab) "" pe )
-- , TestCase ( assertEqual ("Formatted:"++lab) "" out )
]
where
out = formatGraphAsLazyText gr
(pe,pg) = case parseN3 out Nothing of
Right g -> ("", g)
Left s -> (s, mempty)
-- Full round trip from graph source. This test may pick up some errors
-- the bnode generation logic that are not tested by hand-assembled graph
-- data structures.
fullRoundTripTest :: String -> B.Builder -> Test
fullRoundTripTest lab grstr =
TestList
[ TestCase ( assertEqual ("FullRoundTrip:gr:"++lab) gr pg )
, TestCase ( assertEqual ("FullRoundTrip:er:"++lab) "" pe )
-- , TestCase ( assertEqual ("FullRoundTrip:"++lab) "" out )
]
where
grtxt = B.toLazyText grstr
(_,gr) = case parseN3 grtxt Nothing of
Right g -> ("", g)
Left s -> (s, mempty)
out = formatGraphAsLazyText gr
(pe,pg) = case parseN3 out Nothing of
Right g -> ("", g)
Left s -> (s, mempty)
roundTripTestSuite :: Test
roundTripTestSuite = TestList
[ roundTripTest "01" g1np
, roundTripTest "02" g1
, roundTripTest "03" g1b1
, roundTripTest "04" g1a1
, roundTripTest "05" g1l1
, roundTripTest "06" g1l2
, roundTripTest "l1" graph_l1
, roundTripTest "l2" graph_l2
, roundTripTest "l3" graph_l3
, roundTripTest "l4" graph_l4
-- roundTripTest07 = roundTripTest "07" g1f1 -- formula is a named node
, roundTripTest "08" g1f2
, fullRoundTripTest "11" simpleN3Graph_g1_01
, fullRoundTripTest "12" simpleN3Graph_g1_02
, fullRoundTripTest "13" simpleN3Graph_g1_03
, fullRoundTripTest "14" simpleN3Graph_g1_04
, fullRoundTripTest "15" simpleN3Graph_g1_05
, fullRoundTripTest "16rt" simpleN3Graph_g1_06_rt
-- roundTripTest17 = fullRoundTripTest "17" simpleN3Graph_g1_07 -- TODO: :- with named node for formula
, fullRoundTripTest "18" simpleN3Graph_g1_08
, fullRoundTripTest "fu1" simpleN3Graph_g1_fu1
, fullRoundTripTest "l1" simpleN3Graph_l1
, fullRoundTripTest "l2" simpleN3Graph_l2
, fullRoundTripTest "l3" simpleN3Graph_l3
, fullRoundTripTest "l4" simpleN3Graph_l4
]
------------------------------------------------------------
-- Simple formatter tests
------------------------------------------------------------
--
-- These are simple tests that format and re-parse a graph,
-- and make sure that the result graph compares the same as
-- the original. Therefore, depends on a trusted parser and
-- graph compare function.
simpleTest :: String -> RDFGraph -> Test
simpleTest lab = roundTripTest ("SimpleTest:"++lab)
simpleTestSuite :: Test
simpleTestSuite = TestList
[ simpleTest "01" g2
, simpleTest "02" g3
, simpleTest "03" g4
, simpleTest "04" g5
, simpleTest "05" g6
, simpleTest "06" g7
, simpleTest "07" g8
, simpleTest "08" g81
, simpleTest "10" g83
, simpleTest "11" g9
, simpleTest "12" g10
, simpleTest "13" g11
]
------------------------------------------------------------
-- Exotic parser tests
------------------------------------------------------------
--
-- These tests cover various forms of anonymous nodes
-- [...], lists and formulae.
--
-- does a round-trip test starting with the
exoticTest :: String -> RDFGraph -> Test
exoticTest lab gr =
TestList
[ TestCase ( assertEqual ("ExoticTest:gr:"++lab) gr pg )
, TestCase ( assertEqual ("ExoticTest:er:"++lab) "" pe )
-- , TestCase ( assertEqual ("ExoticTest:"++lab) "" out )
]
where
out = formatGraphAsLazyText gr
(pe,pg) = case parseN3 out Nothing of
Right g -> ("", g)
Left s -> (s, mempty)
-- Simple anon nodes, with semicolons and commas
exoticN3Graph_x1 :: B.Builder
exoticN3Graph_x1 =
mconcat
[ commonPrefixes
, " [ base1:p1 base1:o1 ; \n"
, " base1:p1 base2:o2 ; \n"
, " base2:p2 base2:o2 ; \n"
, " base2:p2 base3:o3 ] = base1:s1 . \n"
, " base2:s2 = \n"
, " [ base1:p1 base1:o1 , \n"
, " base2:o2 , \n"
, " base3:o3 , \n"
, " \"l1\" ; \n"
, " base2:p2 base1:o1 , \n"
, " base2:o2 , \n"
, " base3:o3 , \n"
, " \"\"\"", l2txt, "\"\"\" ] . \n"
]
-- Simple anon nodes, with 'is ... of' and semicolons and commas
exoticN3Graph_x2 :: B.Builder
exoticN3Graph_x2 =
mconcat
[ commonPrefixes
, " [ @has base1:p1 base1:o1 ; \n"
, " @is base1:p1 @of base2:o2 ; \n"
, " @has base2:p2 base2:o2 ; \n"
, " @is base2:p2 @of base3:o3 ] = base1:s1 . \n"
, " base2:s2 = \n"
, " [ @has base1:p1 base1:o1 , \n"
, " base2:o2 , \n"
, " base3:o3 , \n"
, " \"l1\" ; \n"
, " @is base2:p2 @of base1:o1 , \n"
, " base2:o2 , \n"
, " base3:o3 ] . \n"
]
-- Simple anon nodes, attached to identified node
{-
exoticN3Graph_x3 =
commonPrefixes ++
" base1:s1 :- \n" ++
" [ has base1:p1 of base1:o1 ; \n" ++
" is base1:p1 of base2:o2 ; \n" ++
" has base2:p2 of base2:o2 ; \n" ++
" is base2:p2 of base3:o3 ] . \n" ++
" base2:s2 :- \n" ++
" [ has base1:p1 of base1:o1 , \n" ++
" base2:o2 , \n" ++
" base3:o3 , \n" ++
" \"l1\" ; \n" ++
" is base2:p2 of base1:o1 , \n" ++
" base2:o2 , \n" ++
" base3:o3 ] . \n"
-- " \"l1\" ] . \n"
-}
-- List nodes, with and without :-
exoticN3Graph_x4 :: B.Builder
exoticN3Graph_x4 =
commonPrefixes `mappend`
"base1:s1 = ( base1:o1 base2:o2 base3:o3 \"l1\" ) .\n"
exoticN3Graph_x5 :: B.Builder
exoticN3Graph_x5 =
commonPrefixes `mappend`
"( base1:o1 base2:o2 base3:o3 \"l1\" ) = base1:s1 .\n"
{-
exoticN3Graph_x6 =
commonPrefixes ++
" base1:s1 :- (base1:o1 base2:o2 base3:o3 \"l1\") .\n"
-}
-- Formula nodes
exoticN3Graph_x7 :: B.Builder
exoticN3Graph_x7 =
mconcat
[ commonPrefixes
, " { \n"
, " base1:s1 base1:p1 base1:o1 .\n"
, " base2:s2 base1:p1 base2:o2 .\n"
, " base3:s3 base1:p1 base3:o3\n"
, " } base2:p2 base2:f2 .\n"
]
-- as above with the trailing . in the formula
exoticN3Graph_x7a :: B.Builder
exoticN3Graph_x7a =
mconcat
[ commonPrefixes
, " { \n"
, " base1:s1 base1:p1 base1:o1 .\n"
, " base2:s2 base1:p1 base2:o2 .\n"
, " base3:s3 base1:p1 base3:o3 .\n"
, " } base2:p2 base2:f2 ."
]
{-
exoticN3Graph_x8 =
commonPrefixes ++
" base1:f1 :- \n" ++
" { base1:s1 base1:p1 base1:o1 . \n" ++
" base2:s2 base1:p1 base2:o2 . \n" ++
" base3:s3 base1:p1 base3:o3 . } ; \n" ++
" base2:p2 base2:f2 . "
-}
{-
exoticN3Graph_x9 =
commonPrefixes ++
" base1:f1 :- \n" ++
" { base1:s1 base1:p1 base1:o1 . } ; \n" ++
" base2:p2 base2:f2 . "
-}
-- Test allocation of bnodes over a nested formula
exoticN3Graph_x12 :: B.Builder
exoticN3Graph_x12 =
mconcat
[ commonPrefixes
, " base1:s1 base1:p1 [ base1:p1 base1:o1 ] . \n"
, " { base2:s2 base2:p2 [ base2:p2 base2:o2 ] . } \n"
, " base2:p2 base2:f2 . \n"
, " base3:s3 base3:p3 [ base3:p3 base3:o3 ] ."
]
-- List of bnodes
{-
exoticN3Graph_x13 =
commonPrefixes ++
" base1:s1 :- \n" ++
" ( [base1:p1 base1:o1] \n" ++
" [base1:p1 base2:o2] \n" ++
" [base1:p1 base3:o3] ) .\n"
-}
{-
TODO
Hmm, what does the input graph really mean?
can we test the following somewhere (do we already?)
exoticN3Graph_x13 =
commonPrefixes ++
" base1:s1 = \n" ++
" ( [base1:p1 base1:o1] \n" ++
" [base1:p1 base2:o2] \n" ++
" [base1:p1 base3:o3] ) .\n"
-}
-- List of more complex bnodes
{-
exoticN3Graph_x14 =
commonPrefixes ++
" base1:s1 :- \n" ++
" ( [base1:p1 base1:o1; base2:p2 base1:o1] \n" ++
" [base1:p1 base2:o2; base2:p2 base2:o2] \n" ++
" [base1:p1 base3:o3; base2:p2 base3:o3] ) .\n"
-}
exoticN3Graph_x14 :: B.Builder
exoticN3Graph_x14 =
mconcat
[ commonPrefixes
, " base1:s1 = \n"
, " ( [base1:p1 base1:o1; base2:p2 base1:o1] \n"
, " [base1:p1 base2:o2; base2:p2 base2:o2] \n"
, " [base1:p1 base3:o3; base2:p2 base3:o3] ) .\n"
]
-- List with nested list
{-
exoticN3Graph_x15 =
commonPrefixes ++
" base1:s1 :- \n" ++
" ( [base1:p1 base1:o1] \n"++
" [base2:p2 \n" ++
" ( [base1:p1 base1:o1] \n" ++
" [base1:p1 base2:o2] \n" ++
" [base1:p1 base3:o3] ) ] \n"++
" [base1:p1 base3:o3] ) .\n"
-}
-- More complex list with nested list
{-
exoticN3Graph_x16 =
commonPrefixes ++
" base1:s1 :- \n" ++
" ( [base1:p1 base1:o1; base2:p2 base1:o1] \n"++
" [base2:p2 \n" ++
" ( [base1:p1 base1:o1; base2:p2 base1:o1] \n" ++
" [base1:p1 base2:o2; base2:p2 base2:o2] \n" ++
" [base1:p1 base3:o3; base2:p2 base3:o3] ) ] \n"++
" [base1:p1 base3:o3; base2:p2 base3:o3] ) .\n"
-}
-- Troublesome example
{-
exoticN3Graph_x17 =
commonPrefixes ++
"base1:s1 a base1:o1 ; :- \n" ++
" ( [ base2:p21 base2:o2 ; \n" ++
" base2:p22 ( [ base2:p23 \"lx11\" ] \"lx12\" ) ] \n" ++
" [ base2:p24 base3:o3 ; base2:p25 \"lx13\" ] \n" ++
" ) . \n"
-}
-- Null prefixes
{-
exoticN3Graph_x18 =
commonPrefixes ++
"@prefix : <#> . " ++
":s1 a :o1 ; :- \n" ++
" ( [ :p21 :o2 ; \n" ++
" :p22 ( [ :p23 \"lx11\" ] \"lx12\" ) ] \n" ++
" [ :p24 :o3 ; :p25 \"lx13\" ] \n" ++
" ) . \n"
-}
-- Check graph sources parse to expected values
exoticTestSuite :: Test
exoticTestSuite = TestList
[ parseTest "exoticParseTest01" exoticN3Graph_x1 x1 noError
, parseTest "exoticParseTest02" exoticN3Graph_x2 x2 noError
-- exoticParseTest03 = parseTest "exoticParseTest03" exoticN3Graph_x3 x3 noError
, parseTest "exoticParseTest04" exoticN3Graph_x4 x4 noError
, parseTest "exoticParseTest05" exoticN3Graph_x5 x5 noError
-- exoticParseTest06 = parseTest "exoticParseTest06" exoticN3Graph_x6 x6 noError
, parseTest "exoticParseTest07" exoticN3Graph_x7 x7 noError
, parseTest "exoticParseTest07a" exoticN3Graph_x7a x7 noError
-- exoticParseTest08 = parseTest "exoticParseTest08" exoticN3Graph_x8 x8 noError
-- exoticParseTest09 = parseTest "exoticParseTest09" exoticN3Graph_x9 x9 noError
, parseTest "exoticParseTest12" exoticN3Graph_x12 x12 noError
-- exoticParseTest13 = parseTest "exoticParseTest13" exoticN3Graph_x13 x13 noError
-- exoticParseTest14 = parseTest "exoticParseTest14" exoticN3Graph_x14 x14 noError -- TODO: re-instate?
-- exoticParseTest15 = parseTest "exoticParseTest15" exoticN3Graph_x15 x15 noError
-- exoticParseTest16 = parseTest "exoticParseTest16" exoticN3Graph_x16 x16 noError
-- exoticParseTest17 = parseTest "exoticParseTest17" exoticN3Graph_x17 x17 noError
, exoticTest "01" x1
, exoticTest "02" x2
, exoticTest "03" x3
, exoticTest "04" x4
, exoticTest "05" x5
, exoticTest "06" x6
, exoticTest "07" x7
-- exoticTest08 = exoticTest "08" x8 -- TODO: serialisation uses :- with a named node
-- exoticTest09 = exoticTest "09" x9 -- TODO: serialisation uses :- with a named node
, testGraphEq "exoticTest10" False x7 x8
, testGraphEq "exoticTest11" False x8 x9
, exoticTest "12" x12
, exoticTest "13" x13
, exoticTest "13a" x13a
, exoticTest "14" x14
, exoticTest "15" x15
, exoticTest "16" x16
, exoticTest "17" x17
, fullRoundTripTest "Exotic01" exoticN3Graph_x1
, fullRoundTripTest "Exotic02" exoticN3Graph_x2
-- exoticRoundTripTest03 = fullRoundTripTest "Exotic03" exoticN3Graph_x3
, fullRoundTripTest "Exotic04" exoticN3Graph_x4
, fullRoundTripTest "Exotic05" exoticN3Graph_x5
-- exoticRoundTripTest06 = fullRoundTripTest "Exotic06" exoticN3Graph_x6
, fullRoundTripTest "Exotic07" exoticN3Graph_x7
-- exoticRoundTripTest08 = fullRoundTripTest "Exotic08" exoticN3Graph_x8
-- exoticRoundTripTest09 = fullRoundTripTest "Exotic09" exoticN3Graph_x9
, fullRoundTripTest "Exotic12" exoticN3Graph_x12
, fullRoundTripTest "Exotic14" exoticN3Graph_x14
-- exoticRoundTripTest15 = fullRoundTripTest "Exotic15" exoticN3Graph_x15
-- exoticRoundTripTest16 = fullRoundTripTest "Exotic16" exoticN3Graph_x16
-- exoticRoundTripTest17 = fullRoundTripTest "Exotic17" exoticN3Graph_x17
-- exoticRoundTripTest18 = fullRoundTripTest "Exotic18" exoticN3Graph_x18
]
------------------------------------------------------------
-- All tests
------------------------------------------------------------
allTests :: [TF.Test]
allTests =
[ conv "trivial" trivialTestSuite
, conv "parse" parseTestSuite
, conv "roundtrip" roundTripTestSuite
, conv "simple" simpleTestSuite
, conv "exotic" exoticTestSuite
]
main :: IO ()
main = TF.defaultMain allTests
--------------------------------------------------------------------------------
--
-- Copyright (c) 2003, Graham Klyne, 2009 Vasili I Galchin,
-- 2011, 2012, 2013 Douglas Burke
-- All rights reserved.
--
-- This file is part of Swish.
--
-- Swish is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- Swish 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 Swish; if not, write to:
-- The Free Software Foundation, Inc.,
-- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
--------------------------------------------------------------------------------
|
DougBurke/swish
|
tests/N3FormatterTest.hs
|
lgpl-2.1
| 45,943 | 0 | 13 | 12,370 | 9,087 | 5,088 | 3,999 | 936 | 3 |
-- |
-- Module : Examples.swmmout2csv
-- Copyright : (C) 2014 Siddhanathan Shanmugam
-- License : LGPL (see LICENSE)
-- Maintainer : [email protected]
-- Portability : very
--
-- Example of a program using SWMMoutGetMB for parsing SWMM .OUT files
-- Inspired by OOW/swmmout2csv originally written by @mplourde
--
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Control.Applicative ((<$>))
import Data.Char (isDigit, isSpace)
import Data.Csv (encode)
import Data.DateTime (DateTime, addSeconds, parseDateTime)
import Data.List (intersperse, transpose, elemIndex, elem, sort, union)
import Data.List.Split (splitOn)
import Data.Maybe (fromJust)
import Data.Monoid (Monoid(..), (<>))
import System.IO (appendFile)
import Water.SWMM
import qualified Data.ByteString.Lazy as BL (ByteString, appendFile, readFile)
import qualified Data.ByteString.Lazy.Char8 as BLC (ByteString, pack, concat, any, unpack, toStrict, append, lines, unlines, appendFile)
constantSWMMEpoch :: DateTime
constantSWMMEpoch = fromJust $ parseDateTime "%Y-%m-%d %H:%M:%S" "1899-12-30 00:00:00"
-- Identity element for monoid
swmmId :: SWMMObject
swmmId = SWMMObject (Header 516114522 51000 0 0 0 0 0)
(ObjectIds [] [] [] [] [])
(ObjectProperties (Properties 0 [] [])
(Properties 0 [] [])
(Properties 0 [] []))
(ReportingVariables (Variables 0 [])
(Variables 0 [])
(Variables 0 [])
(Variables 0 []))
(ReportingInterval 0.0 0)
(ComputedResult [])
(ClosingRecord 0 0 0 0 0 516114522)
isSimilar :: SWMMObject -> SWMMObject -> Bool
isSimilar a b = header a == header b
&& ids a == ids b
&& properties a == properties b
&& variables a == variables b
&& (timeIntervals . intervals) a == (timeIntervals . intervals) b
&& (closingIdNumber . closingRecord) a == (closingIdNumber . closingRecord) b
noDuplicates :: SWMMObject -> SWMMObject -> Bool
noDuplicates a b = sort(x `union` y) == sort(x ++ y)
where x = (allDateTimes . result) a
y = (allDateTimes . result) b
combineSwmmFiles :: SWMMObject -> SWMMObject -> SWMMObject
combineSwmmFiles a b
| a == swmmId = b
| b == swmmId = a
| isSimilar a b && noDuplicates a b =
SWMMObject (header a)
(ids a)
(properties a)
(variables a)
(ReportingInterval (minimum (map (startDateTime . intervals) [a,b]))
(timeIntervals . intervals $ a))
(ComputedResult ((allDateTimes . result) a ++ (allDateTimes . result) b))
(ClosingRecord 0 0 0 0 0 516114522)
| otherwise = error "ERROR: SWMM Files are not consistent"
-- Allows combining two .OUT files by treating them as monoids
instance Monoid SWMMObject where
mempty = swmmId
mappend = combineSwmmFiles
daysToSeconds :: Num a => a -> a
daysToSeconds x = x * 24 * 60 * 60
getSWMMTime :: Double -> DateTime
getSWMMTime daysSinceSWMMEpoch = addSeconds secondsSinceSWMMEpoch constantSWMMEpoch
where secondsSinceSWMMEpoch = round . daysToSeconds
$ daysSinceSWMMEpoch
parseFileInput :: FilePath -> FilePath
parseFileInput (' ' :xs) = parseFileInput xs
parseFileInput ('\'':xs) = parseFileInput xs
parseFileInput xs = go (reverse xs)
where go (' ' :ys) = go ys
go ('\'':ys) = go ys
go ys = reverse ys
parseUserOptions :: String -> Maybe [Int]
parseUserOptions s
| s == "" || all isSpace s = Nothing
| otherwise = Just $ concat $ map convertToUserSelections sList
where sList = splitOn "," s
convertToUserSelections s
| all isDigit s = [read s :: Int]
| otherwise = splitConvert s
where splitConvert s = [a..b]
tl = splitOn "-" s
a = read (tl !! 0) :: Int
b = read (tl !! 1) :: Int
printZippedOptions :: (Int, String) -> IO ()
printZippedOptions (a, b) = print $ show a ++ " - " ++ b
getIndices :: Eq a => [Int] -> [a] -> [a]
getIndices js xs = [a | a <- xs, (fromJust $ elemIndex a xs) `elem` js]
getUserVariables :: [Integer] -> [BLC.ByteString] -> IO [Int]
getUserVariables x y = do let options = map fromInteger x
mapM_ printZippedOptions (zip options (subcatchmentCodes y))
putStrLn "Please enter your choices: "
userChoices <- parseUserOptions <$> getLine
putStrLn ""
if userChoices /= Nothing
then return $ fromJust userChoices
else return options
getUserIds :: [BLC.ByteString] -> IO [Int]
getUserIds names = do let options = map BLC.unpack names
mapM_ printZippedOptions (zip [0..] options)
putStrLn "Please enter your choices: "
userChoices <- parseUserOptions <$> getLine
putStrLn ""
if userChoices /= Nothing
then return $ fromJust userChoices
else return $ take (length options) [0..]
subcatchmentCodes :: [BLC.ByteString] -> [String]
subcatchmentCodes pollutants = [ "Rainfall"
, "Snow Depth"
, "Evaporation Loss"
, "Infiltration Loss"
, "Runoff rate"
, "Groundwater Outflow Rate"
, "Groundwater Water Table Elevation"
, "Unsaturated zone moisture content"
] ++ map BLC.unpack pollutants
nodeCodes :: [BLC.ByteString] -> [String]
nodeCodes pollutants = [ "Depth of water above invert"
, "Hydraulic Head"
, "Volume of stored + ponded water"
, "Lateral inflow"
, "Total inflow (lateral + upstream)"
, "Flow lost to flooding"
] ++ map BLC.unpack pollutants
linkCodes :: [BLC.ByteString] -> [String]
linkCodes pollutants = [ "Flow rate"
, "Flow depth"
, "Flow velocity"
, "Flow volume"
, "Fraction of conduit's area filled or setting for non-conduits"
] ++ map BLC.unpack pollutants
systemIdNames :: [BLC.ByteString]
systemIdNames = [ "Air temperature"
, "Rainfall"
, "Snow Depth"
, "Evaporation + infiltration loss rate"
, "Runoff flow"
, "Dry weather inflow"
, "Groundwater inflow"
, "RDII inflow"
, "User supplied direct inflow"
, "Total lateral inflow (sum of variables 4 to 8)"
, "Flow lost to flooding"
, "Flow leaving through outfalls"
, "Volume of stored water"
, "Evaporation Rate"
]
printAllValues swmm fIds fVars strOption output fValue dateTimes = do
let idsList = fIds . ids $ swmm
let codeNumbers = (codeNumberVariables . fVars . variables) swmm
putStrLn $ "Select " ++ strOption ++ " variables: "
userVariables <- getUserVariables codeNumbers (pollutantIds . ids $ swmm)
putStrLn $ "Select " ++ strOption ++ " ids: "
userColumns <- getUserIds idsList
mapM_ (\y -> do let outputFile = output ++ "/" ++ strOption ++ show y ++ ".csv"
let csvHeader = encode ["DateTime" : (map BLC.unpack (getIndices userColumns idsList))]
BL.appendFile outputFile csvHeader
let values =
(map ( (getIndices userColumns)
. (getValue fValue y)
) ((allDateTimes . result) swmm))
let csvValues = encode values
let csvWithDates = BLC.unlines (zipWith (zipDateTimeWithValues) dateTimes (BLC.lines csvValues))
BL.appendFile outputFile csvWithDates
) userVariables
getValue :: (a -> [[b]]) -> Int -> a -> [b]
getValue f y x = (transpose . f $ x) !! y
zipDateTimeWithValues a b = BLC.append (BLC.pack ((show (getSWMMTime a))++",")) b
getFiles :: IO [String]
getFiles = do
file <- parseFileInput <$> getLine
if null file
then return []
else (file:) <$> getFiles
main :: IO ()
main = do
putStrLn "Press enter when done"
putStrLn "Please drag and drop files one by one, or enter filepaths: "
files <- map parseSWMMBinary <$> ((sequence . map (BL.readFile)) =<< getFiles)
--print <$> noDuplicates swmmObj swmmObj22
let swmmObject = foldl1 ((<>)) files
let dateTimes = map dateTimeValue $ (allDateTimes . result) swmmObject
putStrLn "Enter output file directory: "
outFile <- getLine
let output = parseFileInput outFile
putStrLn ""
-- All subcatchments
printAllValues swmmObject subcatchmentIds subcatchmentVariables "subcatchment"
output subcatchmentValue dateTimes
-- All nodes
printAllValues swmmObject nodeIds nodeVariables "node"
output nodeValue dateTimes
-- All links
printAllValues swmmObject linkIds linkVariables "link"
output linkValue dateTimes
-- All systems
let systemIdsList = systemIdNames
let outputFileName = output ++ "/system.csv"
putStrLn "Select system ids: "
userSystemColumns <- getUserIds systemIdsList
let csvHeader = encode ["DateTime" : (map BLC.unpack (getIndices userSystemColumns systemIdsList))]
BL.appendFile outputFileName csvHeader
let values = map ((getIndices userSystemColumns) . systemValue) ((allDateTimes . result) swmmObject)
let csvValues = encode values
let csvWithDates = BLC.unlines (zipWith (zipDateTimeWithValues) dateTimes (BLC.lines csvValues))
BL.appendFile outputFileName csvWithDates
print "Done"
|
Acidburn0zzz/SWMMoutGetMB
|
examples/swmmout2csv.hs
|
lgpl-3.0
| 10,932 | 0 | 21 | 4,050 | 2,699 | 1,386 | 1,313 | 199 | 3 |
{-# language ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
module LevelServer.Client where
import Control.Exception
import Control.Monad.Trans.Error
import Data.Aeson
import qualified Data.ByteString.Lazy as BSL
import Network.Client
import Network.Client.Exceptions
import Network.Download
import System.Directory
import System.FilePath
import Text.Logging
import Base
import Editor.Pickle.LevelFile
import LevelServer.Configuration
import LevelServer.Types
import Utils
downloadedLevels :: Application -> Play -> Int -> Parent -> AppState
downloadedLevels app play ps parent = NoGUIAppState $ io $ do
levels <- lookupDownloadedLevels
highScores <- getHighScores
return $ menuAppState app (NormalMenu (p "downloaded levels") Nothing) (Just parent) (
MenuItem (p "download new levels") (downloadNewLevels app . this) :
map (mkLevelItem highScores) levels ++
[]) ps
where
this ps = downloadedLevels app play ps parent
mkLevelItem :: Scores -> LevelFile -> MenuItem
mkLevelItem highScores file =
let label = showLevelForMenu highScores file
in MenuItem label (\ ps -> play (this ps) file)
lookupDownloadedLevels :: IO [LevelFile]
lookupDownloadedLevels = do
path <- getDownloadedLevelsPath
mapM (mkUserLevel path . (path </>)) =<< getFiles path (Just ".nl")
getDownloadedLevelsPath :: IO FilePath
getDownloadedLevelsPath = do
p <- (</> "downloadedLevels") <$> getAppUserDataDirectory "nikki-free-levels"
createDirectoryIfMissing True p
return p
downloadNewLevels :: Application -> AppState -> AppState
downloadNewLevels app follower =
appState (busyMessage $ p "downloading levels...") $ io $ networkTry app follower $ do
dir <- getDownloadedLevelsPath
-- todo: what in case of an error
Right (LevelList levelList) <- runErrorT $ askLevelServer GetLevelList
mapM_ (down dir) levelList
return follower
where
down dir url = do
download dir url
let metaUrl = url <.> "meta"
download dir metaUrl
download :: FilePath -> String -> IO ()
download dir url = do
logg Info ("downloading " ++ url)
let dest = dir </> takeFileName url
eContent <- downloadLazy url
case eContent of
Left errorMsg ->
throwIO (DownloadException url errorMsg)
Right content ->
BSL.writeFile dest content
-- * level updloading
-- | asking for licensing before uploading the level
uploadLevel :: Application -> Parent -> LevelFile -> Int -> AppState
uploadLevel app parent file =
menuAppState app (NormalMenu (p "level license") (Just text)) (Just parent) (
MenuItem (p "read the license (opens in browser)") (openLicense app . this) :
MenuItem (p "agree & upload") (const $ justUploadLevel app parent file) :
MenuItem (p "disagree & cancel") (const $ parent) :
[])
where
text = p "By uploading the level you agree to license your level under Creative Commons Attribution license."
this = uploadLevel app parent file
-- | opens the level license in a browser and returns to the given state
openLicense :: Application -> AppState -> AppState
openLicense app follower =
openUrl app levelServerLicenseUrl follower
-- | updaload the level without asking for licensing
justUploadLevel app follower file =
appState (busyMessage $ p "uploading...") $ io $ networkTry app follower $ do
let metadata = encode $ levelMetaData file
levelData <- readFile $ getAbsoluteFilePath file
response <- runErrorT $ askLevelServer $ UploadLevel metadata levelData
let msgs = case response of
Right UploadSucceeded -> [p "Level uploaded!"]
Right UploadNameClash ->
(p "There is already a level by that name." :
p "Upload failed!" :
[])
Right _ -> [p "Unexpected server response."]
Left err -> [p "server error: ", pv err]
return $ message app msgs follower
askLevelServer = askServer levelServerHost levelServerPort
|
nikki-and-the-robots/nikki
|
src/LevelServer/Client.hs
|
lgpl-3.0
| 4,318 | 0 | 17 | 1,158 | 1,082 | 532 | 550 | 88 | 4 |
----
-- Copyright (c) 2013 Andrea Bernardini.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
----
module Foundation where
import Prelude
import Yesod
import Yesod.Static
-- import Yesod.Auth
-- import Yesod.Auth.BrowserId
-- import Yesod.Auth.GoogleEmail
import Yesod.Default.Config
import Yesod.Default.Util (addStaticContentExternal)
import Network.HTTP.Conduit (Manager)
import qualified Settings
import Settings.Development (development)
import qualified Database.Persist
import Database.Persist.Sql (SqlPersistT)
import Settings.StaticFiles
import Settings (widgetFile, Extra (..))
-- import Model
import Text.Jasmine (minifym)
import Text.Hamlet (hamletFile)
import System.Log.FastLogger (Logger)
import Data.Text
-- | The site argument for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data App = App
{ settings :: AppConfig DefaultEnv Extra
, getStatic :: Static -- ^ Settings for static file serving.
-- , connPool :: Database.Persist.PersistConfigPool Settings.PersistConf -- ^ Database connection pool.
, httpManager :: Manager
-- , persistConfig :: Settings.PersistConf
, appLogger :: Logger
}
-- Set up i18n messages. See the message folder.
mkMessage "App" "messages" "en"
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/handler
--
-- This function does three things:
--
-- * Creates the route datatype AppRoute. Every valid URL in your
-- application can be represented as a value of this type.
-- * Creates the associated type:
-- type instance Route App = AppRoute
-- * Creates the value resourcesApp which contains information on the
-- resources declared below. This is used in Handler.hs by the call to
-- mkYesodDispatch
--
-- What this function does *not* do is create a YesodSite instance for
-- App. Creating that instance requires all of the handler functions
-- for our application to be in scope. However, the handler functions
-- usually require access to the AppRoute datatype. Therefore, we
-- split these actions into two functions and place them in separate files.
mkYesodData "App" $(parseRoutesFile "config/routes")
type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget)
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
approot = ApprootMaster $ appRoot . settings
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = fmap Just $ defaultClientSessionBackend
(120 * 60) -- 120 minutes
"config/client_session_key.aes"
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
$(combineStylesheets 'StaticR
[ css_normalize_css
, css_bootstrap_css
])
$(widgetFile "default-layout")
giveUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
-- This is done to provide an optimization for serving static files from
-- a separate domain. Please see the staticRoot setting in Settings.hs
urlRenderOverride y (StaticR s) =
Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s
urlRenderOverride _ _ = Nothing
-- The page to be redirected to when authentication is required.
-- authRoute _ = Just $ AuthR LoginR
authRoute _ = Just $ HomeR
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent =
addStaticContentExternal minifym genFileName Settings.staticDir (StaticR . flip StaticRoute [])
where
-- Generate a unique filename based on the content itself
genFileName lbs
| development = "autogen-" ++ base64md5 lbs
| otherwise = base64md5 lbs
-- Place Javascript at bottom of the body tag so the rest of the page loads first
jsLoader _ = BottomOfBody
-- What messages should be logged. The following includes all messages when
-- in development, and warnings and errors in production.
shouldLog _ _source level =
development || level == LevelWarn || level == LevelError
makeLogger = return . appLogger
-- How to run database actions.
-- instance YesodPersist App where
-- type YesodPersistBackend App = SqlPersistT
-- runDB = defaultRunDB persistConfig connPool
-- instance YesodPersistRunner App where
-- getDBRunner = defaultGetDBRunner connPool
-- instance YesodAuth App where
-- type AuthId App = UserId
-- -- Where to send a user after successful login
-- loginDest _ = HomeR
-- -- Where to send a user after logout
-- logoutDest _ = HomeR
-- getAuthId creds = runDB $ do
-- x <- getBy $ UniqueUser $ credsIdent creds
-- case x of
-- Just (Entity uid _) -> return $ Just uid
-- Nothing -> do
-- fmap Just $ insert $ User (credsIdent creds) Nothing
-- -- You can add other plugins like BrowserID, email or OAuth here
-- authPlugins _ = [authBrowserId def, authGoogleEmail]
-- authHttpManager = httpManager
-- This instance is required to use forms. You can modify renderMessage to
-- achieve customized and internationalized form validation messages.
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
-- | Get the 'Extra' value, used to hold data from the settings.yml file.
getExtra :: Handler Extra
getExtra = fmap (appExtra . settings) getYesod
-- Note: previous versions of the scaffolding included a deliver function to
-- send emails. Unfortunately, there are too many different options for us to
-- give a reasonable default. Instead, the information is available on the
-- wiki:
--
-- https://github.com/yesodweb/yesod/wiki/Sending-email
|
andrebask/newsprint
|
src/UserInterface/NewsPrint/Foundation.hs
|
apache-2.0
| 7,170 | 0 | 15 | 1,518 | 674 | 401 | 273 | -1 | -1 |
{- Copyright 2015 David Farrell <[email protected]>
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-}
module NickServ.Del where
import qualified Data.Map as M
import Arata.Types
import Ext.Help
exports = [CommandExport "nickserv" cmd]
cmd = (defaultCommand "DEL" handler) { extensions = M.singleton (typeOf extHelp) (toDyn extHelp)}
extHelp = defaultExtHelp { short = "Removes a property from your account" }
handler src dst _ = return [NoticeAction dst src "TODO"]
|
shockkolate/arata
|
plugins/NickServ/Del.hs
|
apache-2.0
| 976 | 0 | 9 | 166 | 116 | 65 | 51 | 8 | 1 |
-- |
--
-- Functions in this module return well-formed 'Encoding''.
-- Polymorphic variants, which return @'Encoding' a@, return a textual JSON
-- value, so it can be used as both @'Encoding'' 'Text'@ and @'Encoding' = 'Encoding'' 'Value'@.
module Data.Aeson.Encoding
(
-- * Encoding
Encoding
, Encoding'
, encodingToLazyByteString
, fromEncoding
, unsafeToEncoding
, Series
, pairs
, pair
, pairStr
, pair'
-- * Predicates
, nullEncoding
-- * Encoding constructors
, emptyArray_
, emptyObject_
, text
, lazyText
, string
, list
, dict
, null_
, bool
-- ** Decimal numbers
, int8, int16, int32, int64, int
, word8, word16, word32, word64, word
, integer, float, double, scientific
-- ** Decimal numbers as Text
, int8Text, int16Text, int32Text, int64Text, intText
, word8Text, word16Text, word32Text, word64Text, wordText
, integerText, floatText, doubleText, scientificText
-- ** Time
, day
, localTime
, utcTime
, timeOfDay
, zonedTime
-- ** value
, value
) where
import Prelude ()
import Data.Aeson.Encoding.Internal
|
sol/aeson
|
Data/Aeson/Encoding.hs
|
bsd-3-clause
| 1,191 | 0 | 4 | 330 | 196 | 135 | 61 | 36 | 0 |
{-# LANGUAGE DeriveDataTypeable, FlexibleContexts, Rank2Types #-}
-----------------------------------------------------------------------------
-- |
-- Module : Numeric.LinearAlgebra.Packed.Base
-- Copyright : Copyright (c) 2010, Patrick Perry <[email protected]>
-- License : BSD3
-- Maintainer : Patrick Perry <[email protected]>
-- Stability : experimental
--
-- Packed matrices.
--
module Numeric.LinearAlgebra.Packed.Base
where
import Control.Monad( when )
import Control.Monad.ST( ST, RealWorld, runST, unsafeIOToST )
import Data.Typeable( Typeable )
import Foreign( Storable, Ptr )
import Text.Printf( printf )
import Unsafe.Coerce( unsafeCoerce )
import Numeric.LinearAlgebra.Types( Herm(..) )
import Numeric.LinearAlgebra.Vector( Vector, RVector, STVector )
import qualified Numeric.LinearAlgebra.Vector as V
import Foreign.BLAS( BLAS2 )
import qualified Foreign.BLAS as BLAS
-- | Immutable packed matrices, stored in column-major order.
data Packed e = Packed !Int !(Vector e)
deriving (Typeable)
-- | Mutable packed matrices in the 'ST' monad.
newtype STPacked s e = STPacked { unSTPacked :: Packed e }
deriving (Typeable)
-- | Mutable packed matrices in the 'IO' monad.
type IOPacked = STPacked RealWorld
-- | The dimension of the packed matrix.
dim :: (Storable e) => Packed e -> Int
dim (Packed n _) = n
{-# INLINE dim #-}
-- | Allocate a mutable packed matrix of the given dimension.
new_ :: (Storable e) => Int -> ST s (STPacked s e)
new_ n
| n < 0 = error $
printf "new_ %d: negative dimension" n
| otherwise = do
mx <- V.new_ (n*(n+1) `div` 2)
x <- V.unsafeFreeze mx
return $ STPacked $ Packed n x
{-# INLINE new_ #-}
-- | Create a packed matrix view of a vector, ensurint that the
-- vector has dimension @n * (n+1)/2@, where @n@ is the desired dimension.
fromVector :: (Storable e) => Int -> Vector e -> Packed e
fromVector n x
| not $ 2 * nx == n * (n+1) = error $
printf ("fromVector %d <vector with dim %d>: dimension mismatch")
n nx
| otherwise =
unsafeFromVector n x
where
nx = V.dim x
{-# INLINE fromVector #-}
-- | Create a packed matrix view of a vector, wihtout checking
-- the dimension of the vector.
unsafeFromVector :: (Storable e) => Int -> Vector e -> Packed e
unsafeFromVector = Packed
{-# INLINE unsafeFromVector #-}
-- | Returns the dimension and underlying vector storage of a
-- packed matrix.
toVector :: (Storable e) => Packed e -> (Int, Vector e)
toVector (Packed n v) = (n,v)
{-# INLINE toVector #-}
{-
-- | Create a packed matrix view of a vector, ensurint that the
-- vector has dimension @n * (n+1)/2@, where @n@ is the desired dimension.
fromSTVector :: (Storable e) => Int -> STVector s e -> STPacked s e
fromSTVector n x
| not $ 2 * nx == n * (n+1) = error $
printf ("fromVectorST %d <vector with dim %d>: dimension mismatch")
n nx
| otherwise =
STPacked $ unsafeFromVector n x
where
nx = V.dim x
{-# INLINE fromSTVector #-}
-- | Create a packed matrix view of a vector, wihtout checking
-- the dimension of the vector.
unsafeFromSTVector :: (Storable e) => Int -> STVector s e -> STPacked s e
unsafeFromSTVector = STPacked
{-# INLINE unsafeFromSTVector #-}
-- | Returns the dimension and underlying vector storage of a
-- packed matrix.
toSTVector :: (Storable e) => STPacked s e -> (Int, STVector s e)
toSTVector (STPacked n v) = (n,v)
{-# INLINE toSTVector #-}
-}
-- | Read-only packed matrices.
class RPacked p where
-- | Returns the dimension of the packed matrix.
getDim :: (Storable e) => p e -> ST s Int
-- | Perform an action with the underlying vector storage of
-- the packed matrix.
withVector :: (Storable e)
=> p e
-> (forall v . RVector v => v e -> ST s a)
-> ST s a
-- | Perform an IO action with a pointer to the first element of
-- the packed matrix.
unsafeWith :: (Storable e) => p e -> (Ptr e -> IO a) -> IO a
-- | Converts a read-only packed matrix into an immutable one. This simply
-- casts the matrix from one type to the other without copying the matrix.
-- Note that because the matrix is possibly not copied, any subsequent
-- modifications made to the mutable version of the matrix may be shared
-- with the immutable version. It is safe to use, therefore, if the mutable
-- version is never modified after the freeze operation.
unsafeFreeze :: (Storable e) => p e -> ST s (Packed e)
unsafeThaw :: (Storable e) => p e -> ST s (STPacked s e)
-- | View a vector as a packed matrix and pass it to a function.
withFromVector :: (RVector v, Storable e)
=> Int
-> v e
-> (forall p . RPacked p => p e -> ST s a)
-> ST s a
withFromVector n v f = do
iv <- V.unsafeFreeze v
f $ fromVector n iv
{-# INLINE withFromVector #-}
-- | View a mutable vector as a mutable packed matrix and pass it
-- to a function.
withFromVectorM :: (Storable e)
=> Int
-> STVector s e
-> (STPacked s e -> ST s a)
-> ST s a
withFromVectorM n v f =
withFromVector n v $ \p -> do
mp <- unsafeThaw p
f mp
{-# INLINE withFromVectorM #-}
-- | Perform an action with the underlying vector storage of
-- the mutable packed matrix. See also 'withVectorView'.
withVectorM :: (Storable e)
=> STPacked s e
-> (STVector s e -> ST s a)
-> ST s a
withVectorM mp f =
withVector mp $ \v -> do
mv <- V.unsafeThaw v
f mv
{-# INLINE withVectorM #-}
instance RPacked Packed where
getDim = return . dim
{-# INLINE getDim #-}
withVector (Packed _ v) f = f v
{-# INLINE withVector #-}
unsafeWith (Packed _ v) = V.unsafeWith v
{-# INLINE unsafeWith #-}
unsafeFreeze = return
{-# INLINE unsafeFreeze #-}
unsafeThaw = return . STPacked
{-# INLINE unsafeThaw #-}
instance RPacked (STPacked s) where
getDim = getDim . unSTPacked
{-# INLINE getDim #-}
withVector = withVector . unSTPacked
{-# INLINE withVector #-}
unsafeWith = unsafeWith . unSTPacked
{-# INLINE unsafeWith #-}
unsafeFreeze = return . unSTPacked
{-# INLINE unsafeFreeze #-}
unsafeThaw p = return $ cast p
where
cast :: STPacked s e -> STPacked s' e
cast = unsafeCoerce
{-# INLINE unsafeThaw #-}
-- | Create a new copy of a packed matrix.
newCopy :: (RPacked p, Storable e)
=> p e -> ST s (STPacked s e)
newCopy p = do
n <- getDim p
p' <- new_ n
withVector p $ \v ->
withVectorM p' $ \v' ->
V.unsafeCopyTo v' v
return p'
{-# INLINE newCopy #-}
-- | Converts a mutable packed matrix to an immutable one by taking a complete
-- copy of it.
freeze :: (RPacked p, Storable e) => p e -> ST s (Packed e)
freeze p = do
p' <- newCopy p
unsafeFreeze p'
-- | A safe way to create and work with a mutable Packed before returning
-- an immutable one for later perusal.
create :: (Storable e)
=> (forall s. ST s ((STPacked s) e))
-> Packed e
create stmp = runST $ do
mp <- stmp
unsafeFreeze mp
-- | A safe way to create and work with a mutable Herm Packed before returning
-- an immutable one for later perusal.
hermCreate :: (Storable e)
=> (forall s. ST s (Herm (STPacked s) e))
-> Herm Packed e
hermCreate stmh = runST $ do
(Herm u mp) <- stmh
p <- unsafeFreeze mp
return $ Herm u p
-- | @hermRank1Update alpha x a@ returns
-- @alpha * x * x^H + a@.
hermRank1Update :: (BLAS2 e)
=> Double -> Vector e -> Herm Packed e -> Herm Packed e
hermRank1Update alpha x (Herm uplo ap) = hermCreate $ do
hp' <- Herm uplo `fmap` newCopy ap
hermRank1UpdateM_ alpha x hp'
return hp'
-- | @hermRank2Update alpha x y a@ returns
-- @alpha * x * y^H + conj(alpha) * y * x^H + a@.
hermRank2Update :: (BLAS2 e)
=> e -> Vector e -> Vector e -> Herm Packed e
-> Herm Packed e
hermRank2Update alpha x y (Herm uplo ap) = hermCreate $ do
hp' <- Herm uplo `fmap` newCopy ap
hermRank2UpdateM_ alpha x y hp'
return hp'
-- | @hermRank1UpdateM_ alpha x a@ sets
-- @a := alpha * x * x^H + a@.
hermRank1UpdateM_ :: (RVector v, BLAS2 e)
=> Double -> v e -> Herm (STPacked s) e -> ST s ()
hermRank1UpdateM_ alpha x (Herm uplo a) = do
nx <- V.getDim x
na <- getDim a
let n = nx
when ((not . and) [ nx == n, na == n ]) $ error $
printf ("hermRank1UpdateM_ _ <vector with dim %d>"
++ " (Herm _ <packed matrix with dim %d>):"
++ " invalid dimensions") nx na
unsafeIOToST $
V.unsafeWith x $ \px ->
unsafeWith a $ \pa ->
BLAS.hpr uplo n alpha px 1 pa
-- | @hermRank2UpdateM_ alpha x y a@ sets
-- @a := alpha * x * y^H + conj(alpha) * y * x^H + a@.
hermRank2UpdateM_ :: (RVector v1, RVector v2, BLAS2 e)
=> e -> v1 e -> v2 e -> Herm (STPacked s) e -> ST s ()
hermRank2UpdateM_ alpha x y (Herm uplo a) = do
nx <- V.getDim x
ny <- V.getDim y
na <- getDim a
let n = nx
when ((not . and) [ nx == n, ny == n, na == n ]) $ error $
printf ("hermRank2UpdateM_ _ <vector with dim %d>"
++ " <vector with dim %d>"
++ " (Herm _ <packed matrix with dim %d>):"
++ " invalid dimensions") nx ny na
unsafeIOToST $
V.unsafeWith x $ \px ->
V.unsafeWith y $ \py ->
unsafeWith a $ \pa ->
BLAS.hpr2 uplo n alpha px 1 py 1 pa
-- | @hermMulVector a x@ returns @a * x@.
hermMulVector :: (BLAS2 e)
=> Herm Packed e
-> Vector e
-> Vector e
hermMulVector a x =
V.create $ do
y <- V.new_ (V.dim x)
hermMulVectorTo y a x
return y
-- | @hermMulVectorWithScale alpha a x@ retunrs @alpha * a * x@.
hermMulVectorWithScale :: (BLAS2 e)
=> e
-> Herm Packed e
-> Vector e
-> Vector e
hermMulVectorWithScale alpha a x =
V.create $ do
y <- V.new_ (V.dim x)
hermMulVectorWithScaleTo y alpha a x
return y
-- | @addHermMulVectorWithScales alpha a x y@
-- returns @alpha * a * x + beta * y@.
addHermMulVectorWithScales :: (BLAS2 e)
=> e
-> Herm Packed e
-> Vector e
-> e
-> Vector e
-> Vector e
addHermMulVectorWithScales alpha a x beta y =
V.create $ do
y' <- V.newCopy y
addHermMulVectorWithScalesM_ alpha a x beta y'
return y'
-- | @hermMulVectorTo dst a x@ sets @dst := a * x@.
hermMulVectorTo :: (RPacked p, RVector v, BLAS2 e)
=> STVector s e
-> Herm p e
-> v e
-> ST s ()
hermMulVectorTo dst = hermMulVectorWithScaleTo dst 1
-- | @hermMulVectorWithScaleTo dst alpha a x@
-- sets @dst := alpha * a * x@.
hermMulVectorWithScaleTo :: (RPacked p, RVector v, BLAS2 e)
=> STVector s e
-> e
-> Herm p e
-> v e
-> ST s ()
hermMulVectorWithScaleTo dst alpha a x =
addHermMulVectorWithScalesM_ alpha a x 0 dst
-- | @addHermMulVectorWithScalesM_ alpha a x beta y@
-- sets @y := alpha * a * x + beta * y@.
addHermMulVectorWithScalesM_ :: (RPacked p, RVector v, BLAS2 e)
=> e
-> Herm p e
-> v e
-> e
-> STVector s e
-> ST s ()
addHermMulVectorWithScalesM_ alpha (Herm uplo a) x beta y = do
na <- getDim a
nx <- V.getDim x
ny <- V.getDim y
let n = ny
when ((not . and) [ na == n
, nx == n
, ny == n
]) $ error $
printf ("addHermMulVectorWithScalesM_ _"
++ " (Herm %s <packed matrix with dim %d>)"
++ " %s <vector with dim %d>"
++ " _"
++ " <vector with dim %d>: dimension mismatch")
(show uplo) na
nx ny
unsafeIOToST $
unsafeWith a $ \pa ->
V.unsafeWith x $ \px ->
V.unsafeWith y $ \py ->
BLAS.hpmv uplo n alpha pa px 1 beta py 1
|
patperry/hs-linear-algebra
|
lib/Numeric/LinearAlgebra/Packed/Base.hs
|
bsd-3-clause
| 12,703 | 0 | 14 | 4,138 | 3,038 | 1,537 | 1,501 | 254 | 1 |
-- |
-- Module : Crypto.Hash.SHA3
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : unknown
--
-- Module containing the binding functions to work with the
-- SHA3 cryptographic hash.
--
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
module Crypto.Hash.SHA3
( SHA3_224 (..), SHA3_256 (..), SHA3_384 (..), SHA3_512 (..)
) where
import Crypto.Hash.Types
import Foreign.Ptr (Ptr)
import Data.Data
import Data.Typeable
import Data.Word (Word8, Word32)
-- | SHA3 (224 bits) cryptographic hash algorithm
data SHA3_224 = SHA3_224
deriving (Show,Data,Typeable)
instance HashAlgorithm SHA3_224 where
type HashBlockSize SHA3_224 = 144
type HashDigestSize SHA3_224 = 28
type HashInternalContextSize SHA3_224 = 352
hashBlockSize _ = 144
hashDigestSize _ = 28
hashInternalContextSize _ = 352
hashInternalInit p = c_sha3_init p 224
hashInternalUpdate = c_sha3_update
hashInternalFinalize p = c_sha3_finalize p 224
-- | SHA3 (256 bits) cryptographic hash algorithm
data SHA3_256 = SHA3_256
deriving (Show,Data,Typeable)
instance HashAlgorithm SHA3_256 where
type HashBlockSize SHA3_256 = 136
type HashDigestSize SHA3_256 = 32
type HashInternalContextSize SHA3_256 = 344
hashBlockSize _ = 136
hashDigestSize _ = 32
hashInternalContextSize _ = 344
hashInternalInit p = c_sha3_init p 256
hashInternalUpdate = c_sha3_update
hashInternalFinalize p = c_sha3_finalize p 256
-- | SHA3 (384 bits) cryptographic hash algorithm
data SHA3_384 = SHA3_384
deriving (Show,Data,Typeable)
instance HashAlgorithm SHA3_384 where
type HashBlockSize SHA3_384 = 104
type HashDigestSize SHA3_384 = 48
type HashInternalContextSize SHA3_384 = 312
hashBlockSize _ = 104
hashDigestSize _ = 48
hashInternalContextSize _ = 312
hashInternalInit p = c_sha3_init p 384
hashInternalUpdate = c_sha3_update
hashInternalFinalize p = c_sha3_finalize p 384
-- | SHA3 (512 bits) cryptographic hash algorithm
data SHA3_512 = SHA3_512
deriving (Show,Data,Typeable)
instance HashAlgorithm SHA3_512 where
type HashBlockSize SHA3_512 = 72
type HashDigestSize SHA3_512 = 64
type HashInternalContextSize SHA3_512 = 280
hashBlockSize _ = 72
hashDigestSize _ = 64
hashInternalContextSize _ = 280
hashInternalInit p = c_sha3_init p 512
hashInternalUpdate = c_sha3_update
hashInternalFinalize p = c_sha3_finalize p 512
foreign import ccall unsafe "cryptonite_sha3_init"
c_sha3_init :: Ptr (Context a) -> Word32 -> IO ()
foreign import ccall "cryptonite_sha3_update"
c_sha3_update :: Ptr (Context a) -> Ptr Word8 -> Word32 -> IO ()
foreign import ccall unsafe "cryptonite_sha3_finalize"
c_sha3_finalize :: Ptr (Context a) -> Word32 -> Ptr (Digest a) -> IO ()
|
tekul/cryptonite
|
Crypto/Hash/SHA3.hs
|
bsd-3-clause
| 3,227 | 0 | 11 | 850 | 668 | 362 | 306 | 65 | 0 |
module Main (
main
) where
import Control.Monad
import Control.Monad.IO.Class
import Control.Concurrent (threadDelay)
import Control.Exception (SomeException)
import Data.Aeson
import qualified Data.ByteString.Char8 as C8
import qualified Data.ByteString.Lazy as B (toStrict)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Network (withSocketsDo)
import Network.HTTP.Conduit (withManager)
import System.IO
import Network.HTTP.Request as R
import System.Log.Carma
readFileUtf8 :: FilePath -> IO T.Text
readFileUtf8 f = fmap T.decodeUtf8 $ C8.readFile f
main :: IO ()
main = withFile "log/db.test.log" ReadMode loop where
loop :: Handle -> IO ()
loop h = withSocketsDo $ withManager $ \man -> do
R.withoutLogin man "http://localhost:8000" $ loop' h
where
loop' h = do
b <- liftIO $ hIsEOF h
when (not b) $ do
line <- liftIO $ fmap T.decodeUtf8 $ C8.hGetLine h
maybe (return ()) run $ parseMessage $ T.unpack line
loop' h
run (LogMessage _ (LogRequest (Just user) url method dat)) =
R.req method url dat >>= either printError printValue
run _ = return ()
printError :: MonadIO m => String -> m ()
printError e = liftIO $ putStrLn $ "Response error: " ++ e
printValue :: MonadIO m => Value -> m ()
printValue = liftIO . putStrLn . T.unpack . T.decodeUtf8 . B.toStrict . encode
|
f-me/carma-test
|
tools/carma-test-run.hs
|
bsd-3-clause
| 1,538 | 0 | 19 | 434 | 494 | 259 | 235 | 36 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Coerce where
import Data.Coerce
newtype V = V Int deriving (Show, Read, Eq, Ord, Num)
test :: [[Int]]
test = coerce [[V 1, V 2], [V 3, V 4, V 5]]
|
notae/haskell-exercise
|
data/Coerce.hs
|
bsd-3-clause
| 201 | 0 | 8 | 40 | 96 | 54 | 42 | 6 | 1 |
maxFactor x = helper x 2 where
divide x p = until (\x -> x `mod` p /= 0) (`div` p) x
helper x p | x < p * p = x
| x `mod` p == 0 = max p $ helper (divide x p) (p + 1)
| otherwise = helper x (p + 1)
main = print $ maxFactor 600851475143
|
foreverbell/project-euler-solutions
|
src/3.hs
|
bsd-3-clause
| 285 | 0 | 11 | 113 | 160 | 81 | 79 | 6 | 1 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances, GeneralizedNewtypeDeriving, MultiParamTypeClasses, StandaloneDeriving, UndecidableInstances #-}
module Network.IRC.Bot.BotMonad
( BotPartT(..)
, BotMonad(..)
, BotEnv(..)
, runBotPartT
, mapBotPartT
, maybeZero
) where
import Control.Applicative (Applicative, Alternative, (<$>))
import Control.Arrow (first)
import Control.Monad (MonadPlus(mplus, mzero), forever, replicateM, when)
import Control.Monad.Cont (MonadCont)
import Control.Monad.Error (MonadError)
import Control.Monad.Reader (MonadReader(ask, local), MonadTrans, ReaderT(runReaderT), mapReaderT)
import Control.Monad.Writer (MonadWriter)
import Control.Monad.State (MonadState)
import Control.Monad.RWS (MonadRWS)
import Control.Concurrent.Chan (Chan, dupChan, newChan, readChan, writeChan)
import Control.Monad.Fix (MonadFix)
import Control.Monad.Trans
import Network.IRC (Command, Message(Message, msg_prefix, msg_command, msg_params), Prefix(NickName), UserName, encode, decode, joinChan, nick, user)
import Network.IRC.Bot.Log
class (Functor m, MonadPlus m, MonadIO m) => BotMonad m where
askBotEnv :: m BotEnv
askMessage :: m Message
askOutChan :: m (Chan Message)
localMessage :: (Message -> Message) -> m a -> m a
sendMessage :: Message -> m ()
logM :: LogLevel -> String -> m ()
whoami :: m String
data BotEnv = BotEnv
{ message :: Message
, outChan :: Chan Message
, logFn :: Logger
, botName :: String
, cmdPrefix :: String
}
newtype BotPartT m a = BotPartT { unBotPartT :: ReaderT BotEnv m a }
deriving (Applicative, Alternative, Functor, Monad, MonadFix, MonadPlus, MonadTrans, MonadIO, MonadWriter w, MonadState s, MonadError e, MonadCont)
instance (MonadReader r m) => MonadReader r (BotPartT m) where
ask = BotPartT (lift ask)
local f = BotPartT . mapReaderT (local f) . unBotPartT
instance (MonadRWS r w s m) => MonadRWS r w s (BotPartT m)
runBotPartT :: BotPartT m a -> BotEnv -> m a
runBotPartT botPartT = runReaderT (unBotPartT botPartT)
mapBotPartT :: (m a -> n b) -> BotPartT m a -> BotPartT n b
mapBotPartT f (BotPartT r) = BotPartT $ mapReaderT f r
instance (Functor m, MonadIO m, MonadPlus m) => BotMonad (BotPartT m) where
askBotEnv = BotPartT ask
askMessage = BotPartT (message <$> ask)
askOutChan = BotPartT (outChan <$> ask)
localMessage f (BotPartT r) = BotPartT (local (\e -> e { message = f (message e) }) r)
sendMessage msg =
BotPartT $ do out <- outChan <$> ask
liftIO $ writeChan out msg
return ()
logM lvl msg =
BotPartT $ do l <- logFn <$> ask
liftIO $ l lvl msg
whoami = BotPartT $ botName <$> ask
maybeZero :: (MonadPlus m) => Maybe a -> m a
maybeZero Nothing = mzero
maybeZero (Just a) = return a
|
hrushikesh/ircbot
|
Network/IRC/Bot/BotMonad.hs
|
bsd-3-clause
| 2,864 | 0 | 15 | 600 | 987 | 546 | 441 | 62 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Data.ByteString.Num ( numCompare ) where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import Data.Bits
import Data.Binary ( encode )
import Data.List ( foldl', mapAccumL )
import Data.Word
-- Little Endian ByteStrings
instance Num BS.ByteString where
a + b = byteStrOp (+) a b
a * b = BS.take (max (BS.length a) (BS.length b)) (go (BS.unpack a) (BS.unpack b))
where
go as bs =
let cs = zip [0..] as
wordMult :: [[Word8]]
wordMult = map ((\f -> f bs) . doMult) cs
in foldl' (\a b -> a + BS.pack b) (BS.pack [0]) wordMult
doMult :: (Int, Word8) -> [Word8] -> [Word8]
doMult (i,a) b = replicate i 0 ++ byteMult a b 0
byteMult :: Word8 -> [Word8] -> Int -> [Word8]
byteMult _ [] c = [fromIntegral c]
byteMult a (b:bs) c =
let (q,r) = quotRem (fromIntegral a * fromIntegral b + c) 256
in fromIntegral r : byteMult a bs q
a - b = byteStrOp (-) a b
negate a = BS.replicate (BS.length a) 0 - a
abs a = a
signum a = a `seq` BS.pack [1]
fromInteger i = BS.pack $ go i []
where
go :: Integer -> [Word8] -> [Word8]
go i acc | i < 0 = BS.unpack $ (BS.pack [0]) - (BS.pack $ go (-i) acc)
go 0 acc = reverse acc
go i acc =
let (c,r) = divMod i 256
in go c (fromIntegral r:acc)
instance Integral BS.ByteString where
quot = asInteger2 quot
rem = asInteger2 rem
div = asInteger2 div
mod = asInteger2 mod
quotRem a b =
let (x,y) = quotRem (fromIntegral a) (fromIntegral b :: Integer)
in (fromIntegral x, fromIntegral y)
divMod a b =
let (x,y) = divMod (fromIntegral a) (fromIntegral b :: Integer)
in (fromIntegral x, fromIntegral y)
toInteger a = snd $ foldl' acc (0,0) (BS.unpack a)
where
acc :: (Integer, Integer) -> Word8 -> (Integer, Integer)
acc (i, tot) n = (i+1, tot + (fromIntegral n `shiftL` fromIntegral (i*8)))
-- FIXME use of 'Int' in 'shiftL' causes a maxbound issue
instance Real BS.ByteString where
toRational = toRational . fromIntegral
instance Enum BS.ByteString where
succ a = if isMaxBound a then error "succ maxBound" else a + 1
pred a = if isMinBound a then error "pred minBound" else a - 1
toEnum i = BS.concat $ LBS.toChunks $ encode i
fromEnum = fromIntegral
enumFrom a = if isMaxBound a then [a] else a : (enumFrom (succ a))
enumFromThen start cnt = normalized go start cnt
where
go s c =
if s > (BS.replicate (BS.length c) 0xFF) - c
then [s]
else s : (enumFromThen (s+c) c)
enumFromTo start end = normalized go start end
where go s e | numCompare s e == GT = []
| otherwise =
if isMaxBound s then [s] else s : enumFromTo (succ s) e
enumFromThenTo s c e =
takeWhile (\x -> numCompare x e /= GT) (enumFromThen s c)
isMaxBound :: BS.ByteString -> Bool
isMaxBound = BS.all (== 0xFF)
isMinBound :: BS.ByteString -> Bool
isMinBound = BS.all (== 0x0)
numCompare :: BS.ByteString -> BS.ByteString -> Ordering
numCompare a b =
let byteCmp = normalized (\x y -> reverse (BS.zipWith compare x y)) a b
in case dropWhile (== EQ) byteCmp of
(LT:_) -> LT
(GT:_) -> GT
_ -> EQ
byteStrOp :: (Int -> Int -> Int) -> BS.ByteString -> BS.ByteString -> BS.ByteString
byteStrOp op a b =
let (c,ws) = mapAccumL (combWords op) 0 (BS.zip a' b')
in BS.pack ws
where
(a',b') = normalize a b
combWords :: (Int -> Int -> Int) -> Int -> (Word8,Word8) -> (Int, Word8)
combWords op carry (a,b) = (c, fromIntegral r)
where
p :: Int
p = (fromIntegral a `op` fromIntegral b) + carry
(c,r) = quotRem p 256
normalized :: (BS.ByteString -> BS.ByteString -> a) -> -- The op
BS.ByteString -> BS.ByteString -> a -- lps to normalize
normalized op a b = let (a', b') = normalize a b in op a' b'
normalize :: BS.ByteString -> BS.ByteString -> (BS.ByteString, BS.ByteString)
normalize a b = (a',b')
where
aPad = BS.replicate (BS.length b - BS.length a) 0
bPad = BS.replicate (BS.length a - BS.length b) 0
a' = BS.append a aPad
b' = BS.append b bPad
asInteger :: (Integer -> Integer) -> BS.ByteString -> BS.ByteString
asInteger op = fromIntegral . op . fromIntegral
asInteger2 :: (Integer -> Integer -> Integer) ->
BS.ByteString -> BS.ByteString -> BS.ByteString
asInteger2 op a b = fromIntegral $ fromIntegral a `op` fromIntegral b
instance Bits BS.ByteString where
(.&.) = normalized (byteStrOp (.&.))
(.|.) = normalized (byteStrOp (.|.))
xor = normalized (byteStrOp xor)
complement = BS.map complement
a `shift` i = asInteger (`shift` i) a
a `rotate` i = asInteger (`rotate` i) a
bit i =
let (d,m) = i `quotRem` 8
in BS.snoc (BS.replicate (fromIntegral d) 0) (bit m)
setBit a i = asInteger (`setBit` i) a
clearBit a i = asInteger (`clearBit` i) a
complementBit a i = asInteger (`complementBit` i) a
testBit a i =
let (d, m) = i `quotRem` 8
in testBit (BS.index a d) m
bitSize a = 8 * fromIntegral (BS.length a)
isSigned _ = False
shiftL = shift
shiftR a i = shift a (-i)
rotateL = rotate
rotateR a i = rotate a (-i)
|
travitch/ddmin
|
src/Data/ByteString/Num.hs
|
bsd-3-clause
| 5,401 | 0 | 17 | 1,520 | 2,383 | 1,244 | 1,139 | 124 | 3 |
module Frenetic.TopoGen
( linear
, linearHosts
, kComplete
, kCompleteHosts
, waxman
, smallworld
, fattree
) where
import Frenetic.Topo
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import qualified Data.Set as Set
import System.Random
import Frenetic.NetCore.Types hiding (Switch)
distance (x1, y1) (x2, y2) = sqrt ((x1 - x2) ** 2 + (y1 - y2) ** 2)
rand01IO :: IO Double
rand01IO = randomRIO (0.0, 1.0)
-- | Produce a topology with n nodes in a row, port 1 pointing to the previous
-- and port 2 pointing to the next, starting at node 0.
linear :: (Integral n) => n -> Graph
linear n = graph where
switches = [0 .. ((fromIntegral n - 1))]
pairs = zip switches (tail switches)
graph = buildGraph . map (\(n1, n2) -> ((Switch n1, 2), (Switch n2, 1))) $ pairs
-- | Produce a topology with n nodes in a row, port 1 pointing to the previous
-- and port 2 pointing to the next, starting at node 0. Hosts are numbered 100
-- + (10 * switch) and 101 + (10 * switch). Does not support more than 10
-- switches. Port 3 connects to host XX0, port 4 connects to host XX1.
linearHosts :: (Integral n) => n -> Graph
linearHosts n = graph where
switches = [0 .. n - 1]
hostLinks = concatMap buildHosts switches
pairs = zip switches (tail switches)
graph = buildGraph $
map (\(n1, n2) -> ((Switch $ fromIntegral n1, 2),
(Switch $ fromIntegral n2, 1)))
pairs ++ hostLinks
buildHosts s = [((Switch $ fromIntegral s, 3), (Host $ fromIntegral $ 100 + 10 * s, 0)),
((Switch $ fromIntegral s, 4), (Host $ fromIntegral $ 101 + 10 * s, 0))]
kComplete :: (Integral n) => n -> Graph
-- |Produce a topology on the n-complete graph, starting with node 1. Each node
-- x has an edge to node y over port y.
kComplete n = buildGraph pairs where
switches = [1 .. n]
pairs = [((Switch $ fromIntegral x, fromIntegral y),
(Switch $ fromIntegral y, fromIntegral x))
| (x:xs) <- List.tails switches, y <- xs]
-- |Produce a topology on the n-complete graph, starting with node 1. Each node
-- x has an edge to node y over port y, and two hosts 1i1 and 1i2 connected at
-- ports of the same name.
kCompleteHosts :: (Integral n) => n -> Graph
kCompleteHosts n = buildGraph $ hostLinks ++ pairs where
switches = [1 .. n]
pairs = [((Switch $ fromIntegral x, fromIntegral y),
(Switch $ fromIntegral y, fromIntegral x))
| (x:xs) <- List.tails switches, y <- xs]
hostLinks = concatMap buildHostLinks $ switches
buildHostLinks s = [ ((Switch $ fromIntegral s, fromIntegral h1), (Host $ fromIntegral h1, 0))
, ((Switch $ fromIntegral s, fromIntegral h2), (Host $ fromIntegral h2, 0)) ]
where h1 = 101 + 10 * s
h2 = 102 + 10 * s
-- |Build a Waxman random graph with n nodes, h hosts on each node, and
-- parameters a and b. Suggested parameters: a=0.8, b=0.18
waxman :: (Integral n, Integral h) => n -> h -> Double -> Double -> IO Graph
waxman n h a b = do
plotted <- sequence [ do
x <- rand01IO
y <- rand01IO
return (n, (x, y))
| n <- ns]
let maxDistance = maximum $
[ distance p1 p2
| (_, p1) <- plotted, (_, p2) <- plotted]
let link (i, ip) (j, jp) = do
let d = distance ip jp
rv <- rand01IO
if rv < a * (exp (-d / (b * maxDistance)))
then return $ Just (i, j)
else return Nothing
edges <- sequence [ link i j | i : js <- List.tails plotted, j <- js]
let edges' = Maybe.catMaybes edges
return $ buildGraph (buildLinks n edges')
where ns = [1 .. fromIntegral n]
buildLinks :: (Integral n) => n -> [(n,n)] -> [((Element,Port), (Element,Port))]
buildLinks n edges = edgeLinks ++ hostLinks
where switches = Set.toList . Set.fromList $ uncurry (++) $ unzip edges
edgeLinks = map (\ (n1, n2) -> ((Switch $ fromIntegral n1, fromIntegral n2),
(Switch $ fromIntegral n2, fromIntegral n1)))
edges
hostLinks = buildHosts switches
buildHosts switches = concatMap addHosts switches
addHosts switch = [ ((Switch $ fromIntegral switch, fromIntegral host), (Host $ fromIntegral host, 0))
| host <- [100 * switch + 1 .. 100 * switch + n]]
-- |Build a Watts-Strogatz graph on n nodes, with degree k (even, n >> k >>
-- ln(n) >> 1) and rewiring likelihood 0 <= b <= 1. See
-- en.wikipedia.org/wiki/Watts_and_Strogatz_model for more information, and the
-- algorithm we follow. Suggested parameters: k = n/3, b=0.3
smallworld :: (Integral n, Integral h, Integral k) => n -> h -> k -> Double -> IO Graph
smallworld n h k b = do
edges' <- mapM rewire edges
let edges'' = Set.toList . Set.fromList $ edges'
return $ buildGraph (buildLinks n edges'')
where
ns = [1 .. fromIntegral n]
-- Get the edges in the ring forcing i < j
edges = [ (i, j)
| i <- ns, j <- [i + 1 .. n] -- => i < j => abs(i - j) > 0
, abs (i - j) <= fromIntegral k `quot` 2]
rewire (i, j) = do
let options = [x | x <- ns, x /= i]
rwValue <- rand01IO
let rw = rwValue < b
if rw then do
index <- randomRIO (0, length options - 1)
let j' = options !! index
return (i, j')
else return (i, j)
-- |Build a fattree topology with two aggregating switches, four top-of-rack
-- switches and six hosts per rack.
fattree :: Graph
fattree = buildGraph links where
a1 = Switch 1
a2 = Switch 2
t1 = Switch 11
t2 = Switch 12
t3 = Switch 13
t4 = Switch 14
links = [ ((a1, 1), (t1, 1))
, ((a2, 1), (t1, 2))
, ((a1, 2), (t2, 1))
, ((a2, 2), (t2, 2))
, ((a1, 3), (t3, 1))
, ((a2, 3), (t3, 2))
, ((a1, 4), (t4, 1))
, ((a2, 4), (t4, 2))
] ++ hosts
hosts = [ ((Switch $ fromIntegral t, h), (Host $ fromIntegral h, 0))
| t <- [11, 12, 13, 14], h <- [t * 10 .. t * 10 + 5]]
|
frenetic-lang/netcore-1.0
|
src/Frenetic/TopoGen.hs
|
bsd-3-clause
| 6,101 | 0 | 19 | 1,778 | 2,139 | 1,180 | 959 | 117 | 2 |
{-# LANGUAGE OverloadedStrings, RecordWildCards, ScopedTypeVariables #-}
module Main where
import Web.ClientSession
import qualified Data.ByteString.Char8 as B8
main = do
key <- getDefaultKey
s <- B8.getContents
let r = decrypt key s
print r
|
spacewaffle/ether
|
exp/session/Main2.hs
|
bsd-3-clause
| 257 | 0 | 10 | 48 | 60 | 32 | 28 | 9 | 1 |
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE OverloadedStrings #-}
module Controllers.Tag
( routes
, saveTags
, filterExistsTags
) where
import Application
import qualified Data.ByteString as BS
import Data.List (deleteFirstsBy, nub)
import qualified Data.Text as T
import qualified Heist.Interpreted as I
import Models.Tag
import Snap
import Snap.Snaplet.Heist
import Views.TagSplices
import Views.Utils
------------------------------------------------------------------------------
-- | Routes
-- /tags -> get all tags
--
routes :: [(BS.ByteString, Handler App App ())]
routes = [ ("/tags", Snap.method GET getTagsH)
]
tplTagList :: BS.ByteString
tplTagList = "tag-list"
------------------------------------------------------------------------------
-- | Fetch all tags
--
-- MAYBE: 1. if content-tye is not json, return empty
--
getTagsH :: AppHandler ()
getTagsH = do
req <- getRequest
tags <- findAllTags
let acceptJSON = hasAcceptHeaderJSON $ headers req
if acceptJSON then toJSONResponse tags else
heistLocal (I.bindSplice "tags" $ tagsSplice tags) $ render tplTagList
------------------------------------------------------------------------------
-- | Save a list of tags and return them getting ID has been insert.
-- Perform save if is new otherwise ignore.
--
--
saveTags :: [T.Text] -> AppHandler [Tag]
saveTags input = do
let input' = nub input
xs <- findSomeTagsName input'
ys <- mapM insertTag $ filterExistsTags (maybeNewTags input') xs
return (xs ++ ys)
where maybeNewTags = map textToTag
textToTag name = emptyTag { _tagName = name }
filterExistsTags :: [Tag] -- ^ Tags input from web
-> [Tag] -- ^ Exists Tags per input
-> [Tag] -- ^ Those new ones
filterExistsTags = deleteFirstsBy eqName
where eqName x y = _tagName x == _tagName y
----------------------------------------
|
HaskellCNOrg/snap-web
|
src/Controllers/Tag.hs
|
bsd-3-clause
| 2,025 | 0 | 13 | 470 | 409 | 228 | 181 | 40 | 2 |
module Main where
import qualified Insomnia.Main as M
main :: IO ()
main = M.compilerMain
|
lambdageek/insomnia
|
main-compile/Main.hs
|
bsd-3-clause
| 92 | 0 | 6 | 17 | 29 | 18 | 11 | 4 | 1 |
module Main where
-- This program can act as a FastCGI executable when the
-- program name is simple.fcgi.
import System.Environment
import System.Exit (exitFailure)
import Text.PrettyPrint.HughesPJClass
import Test.HUnit
import Language.Mojito.Syntax.SExpr
import Language.Mojito.Syntax.ExprBuilder
import qualified Language.Mojito.Inference.Cardelli.Prelude as C
(someEnvironment)
import qualified Language.Mojito.Inference.Cardelli.Cardelli as C
(infer)
import Language.Mojito.Inference.SystemCT1999.Prelude
import Language.Mojito.Inference.SystemCT1999.SystemCT1999
main :: IO ()
main = do
who <- getProgName
if who == "simple.fcgi"
then putStrLn "TODO: simple.fcgi"
else normal
try :: String -> Either String a -> IO a
try msg e = case e of
Left err -> putStrLn (msg ++ err) >> exitFailure
Right a -> return a
normal :: IO ()
normal = do
as <- getArgs
case as of
["--help"] -> usage
["--run-tests"] -> tests
["--sexpr", s] -> do
sexpr <- try "Parse error: " $ parseSExprs' s
print sexpr
["--expr", s] -> do
sexpr <- try "Parse error: " $ parseSExprs' s
expr <- try "Wrong s-expression: " $ sexprsToExpr sexpr
print expr
["--milner", s] -> do
sexpr <- try "Parse error: " $ parseSExprs' s
expr <- try "Wrong s-expression: " $ sexprsToExpr sexpr
case C.infer expr C.someEnvironment of
((Left err,_),_) -> putStrLn $ "Type-checking failed: " ++ err
((Right typedExpr,_),_) -> print typedExpr
["--system-ct", s] -> do
sexpr <- try "Parse error: " $ parseSExprs' s
expr <- try "Wrong s-expression: " $ sexprsToExpr sexpr
case infer someTypes expr someContext of
((Left err,_),_) -> putStrLn $ "Type-checking failed: " ++ err
((Right (c,g),_),inf) -> do
typedExpr <- try "wrong final type: " $ duplicate' inf expr c g
print $ pPrint typedExpr
_ -> putStrLn "Unrecognized arguments." >> usage
usage :: IO ()
usage = do
me <- getProgName
putStr . unlines $
concat [ "Usage: ", me, " [OPTION]"] :
"Options:" :
" --help Print this message" :
" --run-tests Run the test suite" :
" --sexpr <string> Parse the string as an s-expression" :
" and print it" :
" --expr <string> Parse the string as an abstract syntax" :
" tree and print it." :
" --milner <string> Parse the string as an abstract syntax" :
" tree, infer the types, and p-print it." :
" --system-ct <string> Parse the string as an abstract syntax" :
" tree, infer the types, and p-print it." :
[]
tests :: IO ()
tests = putStrLn "TODO --run-tests"
|
noteed/mojito
|
mojito.hs
|
bsd-3-clause
| 2,851 | 0 | 21 | 833 | 728 | 376 | 352 | 70 | 9 |
{-# LANGUAGE BangPatterns, CPP, MagicHash, NondecreasingIndentation #-}
-------------------------------------------------------------------------------
--
-- | Main API for compiling plain Haskell source code.
--
-- This module implements compilation of a Haskell source. It is
-- /not/ concerned with preprocessing of source files; this is handled
-- in "DriverPipeline".
--
-- There are various entry points depending on what mode we're in:
-- "batch" mode (@--make@), "one-shot" mode (@-c@, @-S@ etc.), and
-- "interactive" mode (GHCi). There are also entry points for
-- individual passes: parsing, typechecking/renaming, desugaring, and
-- simplification.
--
-- All the functions here take an 'HscEnv' as a parameter, but none of
-- them return a new one: 'HscEnv' is treated as an immutable value
-- from here on in (although it has mutable components, for the
-- caches).
--
-- Warning messages are dealt with consistently throughout this API:
-- during compilation warnings are collected, and before any function
-- in @HscMain@ returns, the warnings are either printed, or turned
-- into a real compialtion error if the @-Werror@ flag is enabled.
--
-- (c) The GRASP/AQUA Project, Glasgow University, 1993-2000
--
-------------------------------------------------------------------------------
module HscMain
(
-- * Making an HscEnv
newHscEnv
-- * Compiling complete source files
, Messager, batchMsg
, HscStatus (..)
, hscCompileOneShot
, hscCompileCmmFile
, hscCompileCore
, genericHscCompileGetFrontendResult
, genModDetails
, hscSimpleIface
, hscWriteIface
, hscNormalIface
, hscGenHardCode
, hscInteractive
-- * Running passes separately
, hscParse
, hscTypecheckRename
, hscDesugar
, makeSimpleIface
, makeSimpleDetails
, hscSimplify -- ToDo, shouldn't really export this
-- * Support for interactive evaluation
, hscParseIdentifier
, hscTcRcLookupName
, hscTcRnGetInfo
, hscCheckSafe
, hscGetSafe
#ifdef GHCI
, hscIsGHCiMonad
, hscGetModuleInterface
, hscRnImportDecls
, hscTcRnLookupRdrName
, hscStmt, hscStmtWithLocation
, hscDecls, hscDeclsWithLocation
, hscTcExpr, hscImport, hscKcType
, hscCompileCoreExpr
-- * Low-level exports for hooks
, hscCompileCoreExpr'
#endif
-- We want to make sure that we export enough to be able to redefine
-- hscFileFrontEnd in client code
, hscParse', hscSimplify', hscDesugar', tcRnModule'
, getHscEnv
, hscSimpleIface', hscNormalIface'
, oneShotMsg
, hscFileFrontEnd, genericHscFrontend, dumpIfaceStats
) where
#ifdef GHCI
import Id
import BasicTypes ( HValue )
import ByteCodeGen ( byteCodeGen, coreExprToBCOs )
import Linker
import CoreTidy ( tidyExpr )
import Type ( Type )
import PrelNames
import {- Kind parts of -} Type ( Kind )
import CoreMonad ( lintInteractiveExpr )
import DsMeta ( templateHaskellNames )
import VarEnv ( emptyTidyEnv )
import Panic
import GHC.Exts
#endif
import Module
import Packages
import RdrName
import HsSyn
import CoreSyn
import StringBuffer
import Parser
import Lexer
import SrcLoc
import TcRnDriver
import TcIface ( typecheckIface )
import TcRnMonad
import IfaceEnv ( initNameCache )
import LoadIface ( ifaceStats, initExternalPackageState )
import PrelInfo
import MkIface
import Desugar
import SimplCore
import TidyPgm
import CorePrep
import CoreToStg ( coreToStg )
import qualified StgCmm ( codeGen )
import StgSyn
import CostCentre
import ProfInit
import TyCon
import Name
import SimplStg ( stg2stg )
import Cmm
import CmmParse ( parseCmmFile )
import CmmBuildInfoTables
import CmmPipeline
import CmmInfo
import CodeOutput
import NameEnv ( emptyNameEnv )
import NameSet ( emptyNameSet )
import InstEnv
import FamInstEnv
import Fingerprint ( Fingerprint )
import Hooks
import DynFlags
import ErrUtils
import Outputable
import HscStats ( ppSourceStats )
import HscTypes
import FastString
import UniqFM ( emptyUFM )
import UniqSupply
import Bag
import Exception
import qualified Stream
import Stream (Stream)
import Util
import Data.List
import Control.Monad
import Data.Maybe
import Data.IORef
import System.FilePath as FilePath
import System.Directory
#include "HsVersions.h"
{- **********************************************************************
%* *
Initialisation
%* *
%********************************************************************* -}
newHscEnv :: DynFlags -> IO HscEnv
newHscEnv dflags = do
eps_var <- newIORef initExternalPackageState
us <- mkSplitUniqSupply 'r'
nc_var <- newIORef (initNameCache us knownKeyNames)
fc_var <- newIORef emptyUFM
mlc_var <- newIORef emptyModuleEnv
return HscEnv { hsc_dflags = dflags,
hsc_targets = [],
hsc_mod_graph = [],
hsc_IC = emptyInteractiveContext dflags,
hsc_HPT = emptyHomePackageTable,
hsc_EPS = eps_var,
hsc_NC = nc_var,
hsc_FC = fc_var,
hsc_MLC = mlc_var,
hsc_type_env_var = Nothing }
knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta,
knownKeyNames = -- where templateHaskellNames are defined
map getName wiredInThings
++ basicKnownKeyNames
#ifdef GHCI
++ templateHaskellNames
#endif
-- -----------------------------------------------------------------------------
getWarnings :: Hsc WarningMessages
getWarnings = Hsc $ \_ w -> return (w, w)
clearWarnings :: Hsc ()
clearWarnings = Hsc $ \_ _ -> return ((), emptyBag)
logWarnings :: WarningMessages -> Hsc ()
logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w)
getHscEnv :: Hsc HscEnv
getHscEnv = Hsc $ \e w -> return (e, w)
handleWarnings :: Hsc ()
handleWarnings = do
dflags <- getDynFlags
w <- getWarnings
liftIO $ printOrThrowWarnings dflags w
clearWarnings
-- | log warning in the monad, and if there are errors then
-- throw a SourceError exception.
logWarningsReportErrors :: Messages -> Hsc ()
logWarningsReportErrors (warns,errs) = do
logWarnings warns
when (not $ isEmptyBag errs) $ throwErrors errs
-- | Throw some errors.
throwErrors :: ErrorMessages -> Hsc a
throwErrors = liftIO . throwIO . mkSrcErr
-- | Deal with errors and warnings returned by a compilation step
--
-- In order to reduce dependencies to other parts of the compiler, functions
-- outside the "main" parts of GHC return warnings and errors as a parameter
-- and signal success via by wrapping the result in a 'Maybe' type. This
-- function logs the returned warnings and propagates errors as exceptions
-- (of type 'SourceError').
--
-- This function assumes the following invariants:
--
-- 1. If the second result indicates success (is of the form 'Just x'),
-- there must be no error messages in the first result.
--
-- 2. If there are no error messages, but the second result indicates failure
-- there should be warnings in the first result. That is, if the action
-- failed, it must have been due to the warnings (i.e., @-Werror@).
ioMsgMaybe :: IO (Messages, Maybe a) -> Hsc a
ioMsgMaybe ioA = do
((warns,errs), mb_r) <- liftIO ioA
logWarnings warns
case mb_r of
Nothing -> throwErrors errs
Just r -> ASSERT( isEmptyBag errs ) return r
-- | like ioMsgMaybe, except that we ignore error messages and return
-- 'Nothing' instead.
ioMsgMaybe' :: IO (Messages, Maybe a) -> Hsc (Maybe a)
ioMsgMaybe' ioA = do
((warns,_errs), mb_r) <- liftIO $ ioA
logWarnings warns
return mb_r
-- -----------------------------------------------------------------------------
-- | Lookup things in the compiler's environment
#ifdef GHCI
hscTcRnLookupRdrName :: HscEnv -> RdrName -> IO [Name]
hscTcRnLookupRdrName hsc_env0 rdr_name = runInteractiveHsc hsc_env0 $ do
hsc_env <- getHscEnv
ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name
#endif
hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing)
hscTcRcLookupName hsc_env0 name = runInteractiveHsc hsc_env0 $ do
hsc_env <- getHscEnv
ioMsgMaybe' $ tcRnLookupName hsc_env name
-- ignore errors: the only error we're likely to get is
-- "name not found", and the Maybe in the return type
-- is used to indicate that.
hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [ClsInst], [FamInst]))
hscTcRnGetInfo hsc_env0 name
= runInteractiveHsc hsc_env0 $
do { hsc_env <- getHscEnv
; ioMsgMaybe' $ tcRnGetInfo hsc_env name }
#ifdef GHCI
hscIsGHCiMonad :: HscEnv -> String -> IO Name
hscIsGHCiMonad hsc_env name
= runHsc hsc_env $ ioMsgMaybe $ isGHCiMonad hsc_env name
hscGetModuleInterface :: HscEnv -> Module -> IO ModIface
hscGetModuleInterface hsc_env0 mod = runInteractiveHsc hsc_env0 $ do
hsc_env <- getHscEnv
ioMsgMaybe $ getModuleInterface hsc_env mod
-- -----------------------------------------------------------------------------
-- | Rename some import declarations
hscRnImportDecls :: HscEnv -> [LImportDecl RdrName] -> IO GlobalRdrEnv
hscRnImportDecls hsc_env0 import_decls = runInteractiveHsc hsc_env0 $ do
hsc_env <- getHscEnv
ioMsgMaybe $ tcRnImportDecls hsc_env import_decls
#endif
-- -----------------------------------------------------------------------------
-- | parse a file, returning the abstract syntax
hscParse :: HscEnv -> ModSummary -> IO HsParsedModule
hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary
-- internal version, that doesn't fail due to -Werror
hscParse' :: ModSummary -> Hsc HsParsedModule
hscParse' mod_summary = do
dflags <- getDynFlags
let src_filename = ms_hspp_file mod_summary
maybe_src_buf = ms_hspp_buf mod_summary
-------------------------- Parser ----------------
liftIO $ showPass dflags "Parser"
{-# SCC "Parser" #-} do
-- sometimes we already have the buffer in memory, perhaps
-- because we needed to parse the imports out of it, or get the
-- module name.
buf <- case maybe_src_buf of
Just b -> return b
Nothing -> liftIO $ hGetStringBuffer src_filename
let loc = mkRealSrcLoc (mkFastString src_filename) 1 1
case unP parseModule (mkPState dflags buf loc) of
PFailed span err ->
liftIO $ throwOneError (mkPlainErrMsg dflags span err)
POk pst rdr_module -> do
logWarningsReportErrors (getMessages pst)
liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" $
ppr rdr_module
liftIO $ dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics" $
ppSourceStats False rdr_module
-- To get the list of extra source files, we take the list
-- that the parser gave us,
-- - eliminate files beginning with '<'. gcc likes to use
-- pseudo-filenames like "<built-in>" and "<command-line>"
-- - normalise them (elimiante differences between ./f and f)
-- - filter out the preprocessed source file
-- - filter out anything beginning with tmpdir
-- - remove duplicates
-- - filter out the .hs/.lhs source filename if we have one
--
let n_hspp = FilePath.normalise src_filename
srcs0 = nub $ filter (not . (tmpDir dflags `isPrefixOf`))
$ filter (not . (== n_hspp))
$ map FilePath.normalise
$ filter (not . (isPrefixOf "<"))
$ map unpackFS
$ srcfiles pst
srcs1 = case ml_hs_file (ms_location mod_summary) of
Just f -> filter (/= FilePath.normalise f) srcs0
Nothing -> srcs0
-- sometimes we see source files from earlier
-- preprocessing stages that cannot be found, so just
-- filter them out:
srcs2 <- liftIO $ filterM doesFileExist srcs1
return HsParsedModule {
hpm_module = rdr_module,
hpm_src_files = srcs2
}
-- XXX: should this really be a Maybe X? Check under which circumstances this
-- can become a Nothing and decide whether this should instead throw an
-- exception/signal an error.
type RenamedStuff =
(Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
Maybe LHsDocString))
-- | Rename and typecheck a module, additionally returning the renamed syntax
hscTypecheckRename :: HscEnv -> ModSummary -> HsParsedModule
-> IO (TcGblEnv, RenamedStuff)
hscTypecheckRename hsc_env mod_summary rdr_module = runHsc hsc_env $ do
tc_result <- tcRnModule' hsc_env mod_summary True rdr_module
-- This 'do' is in the Maybe monad!
let rn_info = do decl <- tcg_rn_decls tc_result
let imports = tcg_rn_imports tc_result
exports = tcg_rn_exports tc_result
doc_hdr = tcg_doc_hdr tc_result
return (decl,imports,exports,doc_hdr)
return (tc_result, rn_info)
-- wrapper around tcRnModule to handle safe haskell extras
tcRnModule' :: HscEnv -> ModSummary -> Bool -> HsParsedModule
-> Hsc TcGblEnv
tcRnModule' hsc_env sum save_rn_syntax mod = do
tcg_res <- {-# SCC "Typecheck-Rename" #-}
ioMsgMaybe $
tcRnModule hsc_env (ms_hsc_src sum) save_rn_syntax mod
tcSafeOK <- liftIO $ readIORef (tcg_safeInfer tcg_res)
dflags <- getDynFlags
let allSafeOK = safeInferred dflags && tcSafeOK
-- end of the safe haskell line, how to respond to user?
if not (safeHaskellOn dflags) || (safeInferOn dflags && not allSafeOK)
-- if safe Haskell off or safe infer failed, mark unsafe
then markUnsafeInfer tcg_res emptyBag
-- module (could be) safe, throw warning if needed
else do
tcg_res' <- hscCheckSafeImports tcg_res
safe <- liftIO $ readIORef (tcg_safeInfer tcg_res')
when safe $ do
case wopt Opt_WarnSafe dflags of
True -> (logWarnings $ unitBag $ mkPlainWarnMsg dflags
(warnSafeOnLoc dflags) $ errSafe tcg_res')
False | safeHaskell dflags == Sf_Trustworthy &&
wopt Opt_WarnTrustworthySafe dflags ->
(logWarnings $ unitBag $ mkPlainWarnMsg dflags
(trustworthyOnLoc dflags) $ errTwthySafe tcg_res')
False -> return ()
return tcg_res'
where
pprMod t = ppr $ moduleName $ tcg_mod t
errSafe t = quotes (pprMod t) <+> text "has been inferred as safe!"
errTwthySafe t = quotes (pprMod t)
<+> text "is marked as Trustworthy but has been inferred as safe!"
-- | Convert a typechecked module to Core
hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts
hscDesugar hsc_env mod_summary tc_result =
runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result
hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts
hscDesugar' mod_location tc_result = do
hsc_env <- getHscEnv
r <- ioMsgMaybe $
{-# SCC "deSugar" #-}
deSugar hsc_env mod_location tc_result
-- always check -Werror after desugaring, this is the last opportunity for
-- warnings to arise before the backend.
handleWarnings
return r
-- | Make a 'ModIface' from the results of typechecking. Used when
-- not optimising, and the interface doesn't need to contain any
-- unfoldings or other cross-module optimisation info.
-- ToDo: the old interface is only needed to get the version numbers,
-- we should use fingerprint versions instead.
makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails
-> IO (ModIface,Bool)
makeSimpleIface hsc_env maybe_old_iface tc_result details = runHsc hsc_env $ do
safe_mode <- hscGetSafeMode tc_result
ioMsgMaybe $ do
mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) safe_mode
details tc_result
-- | Make a 'ModDetails' from the results of typechecking. Used when
-- typechecking only, as opposed to full compilation.
makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails
makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result
{- **********************************************************************
%* *
The main compiler pipeline
%* *
%********************************************************************* -}
{-
--------------------------------
The compilation proper
--------------------------------
It's the task of the compilation proper to compile Haskell, hs-boot and core
files to either byte-code, hard-code (C, asm, LLVM, ect) or to nothing at all
(the module is still parsed and type-checked. This feature is mostly used by
IDE's and the likes). Compilation can happen in either 'one-shot', 'batch',
'nothing', or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch'
mode targets hard-code, 'nothing' mode targets nothing and 'interactive' mode
targets byte-code.
The modes are kept separate because of their different types and meanings:
* In 'one-shot' mode, we're only compiling a single file and can therefore
discard the new ModIface and ModDetails. This is also the reason it only
targets hard-code; compiling to byte-code or nothing doesn't make sense when
we discard the result.
* 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface
and ModDetails. 'Batch' mode doesn't target byte-code since that require us to
return the newly compiled byte-code.
* 'Nothing' mode has exactly the same type as 'batch' mode but they're still
kept separate. This is because compiling to nothing is fairly special: We
don't output any interface files, we don't run the simplifier and we don't
generate any code.
* 'Interactive' mode is similar to 'batch' mode except that we return the
compiled byte-code together with the ModIface and ModDetails.
Trying to compile a hs-boot file to byte-code will result in a run-time error.
This is the only thing that isn't caught by the type-system.
-}
type Messager = HscEnv -> (Int,Int) -> RecompileRequired -> ModSummary -> IO ()
genericHscCompileGetFrontendResult ::
Bool -- always do basic recompilation check?
-> Maybe TcGblEnv
-> Maybe Messager
-> HscEnv
-> ModSummary
-> SourceModified
-> Maybe ModIface -- Old interface, if available
-> (Int,Int) -- (i,n) = module i of n (for msgs)
-> IO (Either ModIface (TcGblEnv, Maybe Fingerprint))
genericHscCompileGetFrontendResult
always_do_basic_recompilation_check m_tc_result
mHscMessage hsc_env mod_summary source_modified mb_old_iface mod_index
= do
let msg what = case mHscMessage of
Just hscMessage -> hscMessage hsc_env mod_index what mod_summary
Nothing -> return ()
skip iface = do
msg UpToDate
return $ Left iface
compile mb_old_hash reason = do
msg reason
tc_result <- runHsc hsc_env $ genericHscFrontend mod_summary
return $ Right (tc_result, mb_old_hash)
stable = case source_modified of
SourceUnmodifiedAndStable -> True
_ -> False
case m_tc_result of
Just tc_result
| not always_do_basic_recompilation_check ->
return $ Right (tc_result, Nothing)
_ -> do
(recomp_reqd, mb_checked_iface)
<- {-# SCC "checkOldIface" #-}
checkOldIface hsc_env mod_summary
source_modified mb_old_iface
-- save the interface that comes back from checkOldIface.
-- In one-shot mode we don't have the old iface until this
-- point, when checkOldIface reads it from the disk.
let mb_old_hash = fmap mi_iface_hash mb_checked_iface
case mb_checked_iface of
Just iface | not (recompileRequired recomp_reqd) ->
-- If the module used TH splices when it was last
-- compiled, then the recompilation check is not
-- accurate enough (#481) and we must ignore
-- it. However, if the module is stable (none of
-- the modules it depends on, directly or
-- indirectly, changed), then we *can* skip
-- recompilation. This is why the SourceModified
-- type contains SourceUnmodifiedAndStable, and
-- it's pretty important: otherwise ghc --make
-- would always recompile TH modules, even if
-- nothing at all has changed. Stability is just
-- the same check that make is doing for us in
-- one-shot mode.
case m_tc_result of
Nothing
| mi_used_th iface && not stable ->
compile mb_old_hash (RecompBecause "TH")
_ ->
skip iface
_ ->
case m_tc_result of
Nothing -> compile mb_old_hash recomp_reqd
Just tc_result ->
return $ Right (tc_result, mb_old_hash)
genericHscFrontend :: ModSummary -> Hsc TcGblEnv
genericHscFrontend mod_summary =
getHooked hscFrontendHook genericHscFrontend' >>= ($ mod_summary)
genericHscFrontend' :: ModSummary -> Hsc TcGblEnv
genericHscFrontend' mod_summary = hscFileFrontEnd mod_summary
--------------------------------------------------------------
-- Compilers
--------------------------------------------------------------
hscCompileOneShot :: HscEnv
-> ModSummary
-> SourceModified
-> IO HscStatus
hscCompileOneShot env =
lookupHook hscCompileOneShotHook hscCompileOneShot' (hsc_dflags env) env
-- Compile Haskell/boot in OneShot mode.
hscCompileOneShot' :: HscEnv
-> ModSummary
-> SourceModified
-> IO HscStatus
hscCompileOneShot' hsc_env mod_summary src_changed
= do
-- One-shot mode needs a knot-tying mutable variable for interface
-- files. See TcRnTypes.TcGblEnv.tcg_type_env_var.
type_env_var <- newIORef emptyNameEnv
let mod = ms_mod mod_summary
hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) }
msg what = oneShotMsg hsc_env' what
skip = do msg UpToDate
dumpIfaceStats hsc_env'
return HscUpToDate
compile mb_old_hash reason = runHsc hsc_env' $ do
liftIO $ msg reason
tc_result <- genericHscFrontend mod_summary
guts0 <- hscDesugar' (ms_location mod_summary) tc_result
dflags <- getDynFlags
case hscTarget dflags of
HscNothing -> do
when (gopt Opt_WriteInterface dflags) $ liftIO $ do
(iface, changed, _details) <- hscSimpleIface hsc_env tc_result mb_old_hash
hscWriteIface dflags iface changed mod_summary
return HscNotGeneratingCode
_ ->
case ms_hsc_src mod_summary of
t | isHsBootOrSig t ->
do (iface, changed, _) <- hscSimpleIface' tc_result mb_old_hash
liftIO $ hscWriteIface dflags iface changed mod_summary
return HscUpdateBoot
_ ->
do guts <- hscSimplify' guts0
(iface, changed, _details, cgguts) <- hscNormalIface' guts mb_old_hash
liftIO $ hscWriteIface dflags iface changed mod_summary
return $ HscRecomp cgguts mod_summary
-- XXX This is always False, because in one-shot mode the
-- concept of stability does not exist. The driver never
-- passes SourceUnmodifiedAndStable in here.
stable = case src_changed of
SourceUnmodifiedAndStable -> True
_ -> False
(recomp_reqd, mb_checked_iface)
<- {-# SCC "checkOldIface" #-}
checkOldIface hsc_env' mod_summary src_changed Nothing
-- save the interface that comes back from checkOldIface.
-- In one-shot mode we don't have the old iface until this
-- point, when checkOldIface reads it from the disk.
let mb_old_hash = fmap mi_iface_hash mb_checked_iface
case mb_checked_iface of
Just iface | not (recompileRequired recomp_reqd) ->
-- If the module used TH splices when it was last compiled,
-- then the recompilation check is not accurate enough (#481)
-- and we must ignore it. However, if the module is stable
-- (none of the modules it depends on, directly or indirectly,
-- changed), then we *can* skip recompilation. This is why
-- the SourceModified type contains SourceUnmodifiedAndStable,
-- and it's pretty important: otherwise ghc --make would
-- always recompile TH modules, even if nothing at all has
-- changed. Stability is just the same check that make is
-- doing for us in one-shot mode.
if mi_used_th iface && not stable
then compile mb_old_hash (RecompBecause "TH")
else skip
_ ->
compile mb_old_hash recomp_reqd
--------------------------------------------------------------
-- NoRecomp handlers
--------------------------------------------------------------
genModDetails :: HscEnv -> ModIface -> IO ModDetails
genModDetails hsc_env old_iface
= do
new_details <- {-# SCC "tcRnIface" #-}
initIfaceCheck hsc_env (typecheckIface old_iface)
dumpIfaceStats hsc_env
return new_details
--------------------------------------------------------------
-- Progress displayers.
--------------------------------------------------------------
oneShotMsg :: HscEnv -> RecompileRequired -> IO ()
oneShotMsg hsc_env recomp =
case recomp of
UpToDate ->
compilationProgressMsg (hsc_dflags hsc_env) $
"compilation IS NOT required"
_ ->
return ()
batchMsg :: Messager
batchMsg hsc_env mod_index recomp mod_summary =
case recomp of
MustCompile -> showMsg "Compiling " ""
UpToDate
| verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping " ""
| otherwise -> return ()
RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]")
where
dflags = hsc_dflags hsc_env
showMsg msg reason =
compilationProgressMsg dflags $
(showModuleIndex mod_index ++
msg ++ showModMsg dflags (hscTarget dflags)
(recompileRequired recomp) mod_summary)
++ reason
--------------------------------------------------------------
-- FrontEnds
--------------------------------------------------------------
hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv
hscFileFrontEnd mod_summary = do
hpm <- hscParse' mod_summary
hsc_env <- getHscEnv
tcg_env <- tcRnModule' hsc_env mod_summary False hpm
return tcg_env
--------------------------------------------------------------
-- Safe Haskell
--------------------------------------------------------------
-- Note [Safe Haskell Trust Check]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Safe Haskell checks that an import is trusted according to the following
-- rules for an import of module M that resides in Package P:
--
-- * If M is recorded as Safe and all its trust dependencies are OK
-- then M is considered safe.
-- * If M is recorded as Trustworthy and P is considered trusted and
-- all M's trust dependencies are OK then M is considered safe.
--
-- By trust dependencies we mean that the check is transitive. So if
-- a module M that is Safe relies on a module N that is trustworthy,
-- importing module M will first check (according to the second case)
-- that N is trusted before checking M is trusted.
--
-- This is a minimal description, so please refer to the user guide
-- for more details. The user guide is also considered the authoritative
-- source in this matter, not the comments or code.
-- Note [Safe Haskell Inference]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Safe Haskell does Safe inference on modules that don't have any specific
-- safe haskell mode flag. The basic aproach to this is:
-- * When deciding if we need to do a Safe language check, treat
-- an unmarked module as having -XSafe mode specified.
-- * For checks, don't throw errors but return them to the caller.
-- * Caller checks if there are errors:
-- * For modules explicitly marked -XSafe, we throw the errors.
-- * For unmarked modules (inference mode), we drop the errors
-- and mark the module as being Unsafe.
--
-- It used to be that we only did safe inference on modules that had no Safe
-- Haskell flags, but now we perform safe inference on all modules as we want
-- to allow users to set the `--fwarn-safe`, `--fwarn-unsafe` and
-- `--fwarn-trustworthy-safe` flags on Trustworthy and Unsafe modules so that a
-- user can ensure their assumptions are correct and see reasons for why a
-- module is safe or unsafe.
--
-- This is tricky as we must be careful when we should throw an error compared
-- to just warnings. For checking safe imports we manage it as two steps. First
-- we check any imports that are required to be safe, then we check all other
-- imports to see if we can infer them to be safe.
-- | Check that the safe imports of the module being compiled are valid.
-- If not we either issue a compilation error if the module is explicitly
-- using Safe Haskell, or mark the module as unsafe if we're in safe
-- inference mode.
hscCheckSafeImports :: TcGblEnv -> Hsc TcGblEnv
hscCheckSafeImports tcg_env = do
dflags <- getDynFlags
tcg_env' <- checkSafeImports dflags tcg_env
checkRULES dflags tcg_env'
where
checkRULES dflags tcg_env' = do
case safeLanguageOn dflags of
True -> do
-- XSafe: we nuke user written RULES
logWarnings $ warns dflags (tcg_rules tcg_env')
return tcg_env' { tcg_rules = [] }
False
-- SafeInferred: user defined RULES, so not safe
| safeInferOn dflags && not (null $ tcg_rules tcg_env')
-> markUnsafeInfer tcg_env' $ warns dflags (tcg_rules tcg_env')
-- Trustworthy OR SafeInferred: with no RULES
| otherwise
-> return tcg_env'
warns dflags rules = listToBag $ map (warnRules dflags) rules
warnRules dflags (L loc (HsRule n _ _ _ _ _ _)) =
mkPlainWarnMsg dflags loc $
text "Rule \"" <> ftext n <> text "\" ignored" $+$
text "User defined rules are disabled under Safe Haskell"
-- | Validate that safe imported modules are actually safe. For modules in the
-- HomePackage (the package the module we are compiling in resides) this just
-- involves checking its trust type is 'Safe' or 'Trustworthy'. For modules
-- that reside in another package we also must check that the external pacakge
-- is trusted. See the Note [Safe Haskell Trust Check] above for more
-- information.
--
-- The code for this is quite tricky as the whole algorithm is done in a few
-- distinct phases in different parts of the code base. See
-- RnNames.rnImportDecl for where package trust dependencies for a module are
-- collected and unioned. Specifically see the Note [RnNames . Tracking Trust
-- Transitively] and the Note [RnNames . Trust Own Package].
checkSafeImports :: DynFlags -> TcGblEnv -> Hsc TcGblEnv
checkSafeImports dflags tcg_env
= do
imps <- mapM condense imports'
let (safeImps, regImps) = partition (\(_,_,s) -> s) imps
-- We want to use the warning state specifically for detecting if safe
-- inference has failed, so store and clear any existing warnings.
oldErrs <- getWarnings
clearWarnings
-- Check safe imports are correct
safePkgs <- mapM checkSafe safeImps
safeErrs <- getWarnings
clearWarnings
-- Check non-safe imports are correct if inferring safety
-- See the Note [Safe Haskell Inference]
(infErrs, infPkgs) <- case (safeInferOn dflags) of
False -> return (emptyBag, [])
True -> do infPkgs <- mapM checkSafe regImps
infErrs <- getWarnings
clearWarnings
return (infErrs, infPkgs)
-- restore old errors
logWarnings oldErrs
case (isEmptyBag safeErrs) of
-- Failed safe check
False -> liftIO . throwIO . mkSrcErr $ safeErrs
-- Passed safe check
True -> do
let infPassed = isEmptyBag infErrs
tcg_env' <- case (not infPassed) of
True -> markUnsafeInfer tcg_env infErrs
False -> return tcg_env
when (packageTrustOn dflags) $ checkPkgTrust dflags pkgReqs
let newTrust = pkgTrustReqs safePkgs infPkgs infPassed
return tcg_env' { tcg_imports = impInfo `plusImportAvails` newTrust }
where
impInfo = tcg_imports tcg_env -- ImportAvails
imports = imp_mods impInfo -- ImportedMods
imports' = moduleEnvToList imports -- (Module, [ImportedModsVal])
pkgReqs = imp_trust_pkgs impInfo -- [PackageKey]
condense :: (Module, [ImportedModsVal]) -> Hsc (Module, SrcSpan, IsSafeImport)
condense (_, []) = panic "HscMain.condense: Pattern match failure!"
condense (m, x:xs) = do (_,_,l,s) <- foldlM cond' x xs
return (m, l, s)
-- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport)
cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal
cond' v1@(m1,_,l1,s1) (_,_,_,s2)
| s1 /= s2
= throwErrors $ unitBag $ mkPlainErrMsg dflags l1
(text "Module" <+> ppr m1 <+>
(text $ "is imported both as a safe and unsafe import!"))
| otherwise
= return v1
-- easier interface to work with
checkSafe (m, l, _) = fst `fmap` hscCheckSafe' dflags m l
-- what pkg's to add to our trust requirements
pkgTrustReqs req inf infPassed | safeInferOn dflags
&& safeHaskell dflags == Sf_None && infPassed
= emptyImportAvails {
imp_trust_pkgs = catMaybes req ++ catMaybes inf
}
pkgTrustReqs _ _ _ | safeHaskell dflags == Sf_Unsafe
= emptyImportAvails
pkgTrustReqs req _ _ = emptyImportAvails { imp_trust_pkgs = catMaybes req }
-- | Check that a module is safe to import.
--
-- We return True to indicate the import is safe and False otherwise
-- although in the False case an exception may be thrown first.
hscCheckSafe :: HscEnv -> Module -> SrcSpan -> IO Bool
hscCheckSafe hsc_env m l = runHsc hsc_env $ do
dflags <- getDynFlags
pkgs <- snd `fmap` hscCheckSafe' dflags m l
when (packageTrustOn dflags) $ checkPkgTrust dflags pkgs
errs <- getWarnings
return $ isEmptyBag errs
-- | Return if a module is trusted and the pkgs it depends on to be trusted.
hscGetSafe :: HscEnv -> Module -> SrcSpan -> IO (Bool, [PackageKey])
hscGetSafe hsc_env m l = runHsc hsc_env $ do
dflags <- getDynFlags
(self, pkgs) <- hscCheckSafe' dflags m l
good <- isEmptyBag `fmap` getWarnings
clearWarnings -- don't want them printed...
let pkgs' | Just p <- self = p:pkgs
| otherwise = pkgs
return (good, pkgs')
-- | Is a module trusted? If not, throw or log errors depending on the type.
-- Return (regardless of trusted or not) if the trust type requires the modules
-- own package be trusted and a list of other packages required to be trusted
-- (these later ones haven't been checked) but the own package trust has been.
hscCheckSafe' :: DynFlags -> Module -> SrcSpan -> Hsc (Maybe PackageKey, [PackageKey])
hscCheckSafe' dflags m l = do
(tw, pkgs) <- isModSafe m l
case tw of
False -> return (Nothing, pkgs)
True | isHomePkg m -> return (Nothing, pkgs)
| otherwise -> return (Just $ modulePackageKey m, pkgs)
where
isModSafe :: Module -> SrcSpan -> Hsc (Bool, [PackageKey])
isModSafe m l = do
iface <- lookup' m
case iface of
-- can't load iface to check trust!
Nothing -> throwErrors $ unitBag $ mkPlainErrMsg dflags l
$ text "Can't load the interface file for" <+> ppr m
<> text ", to check that it can be safely imported"
-- got iface, check trust
Just iface' ->
let trust = getSafeMode $ mi_trust iface'
trust_own_pkg = mi_trust_pkg iface'
-- check module is trusted
safeM = trust `elem` [Sf_Safe, Sf_Trustworthy]
-- check package is trusted
safeP = packageTrusted trust trust_own_pkg m
-- pkg trust reqs
pkgRs = map fst $ filter snd $ dep_pkgs $ mi_deps iface'
-- General errors we throw but Safe errors we log
errs = case (safeM, safeP) of
(True, True ) -> emptyBag
(True, False) -> pkgTrustErr
(False, _ ) -> modTrustErr
in do
logWarnings errs
return (trust == Sf_Trustworthy, pkgRs)
where
pkgTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $
sep [ ppr (moduleName m)
<> text ": Can't be safely imported!"
, text "The package (" <> ppr (modulePackageKey m)
<> text ") the module resides in isn't trusted."
]
modTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $
sep [ ppr (moduleName m)
<> text ": Can't be safely imported!"
, text "The module itself isn't safe." ]
-- | Check the package a module resides in is trusted. Safe compiled
-- modules are trusted without requiring that their package is trusted. For
-- trustworthy modules, modules in the home package are trusted but
-- otherwise we check the package trust flag.
packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool
packageTrusted Sf_None _ _ = False -- shouldn't hit these cases
packageTrusted Sf_Unsafe _ _ = False -- prefer for completeness.
packageTrusted _ _ _
| not (packageTrustOn dflags) = True
packageTrusted Sf_Safe False _ = True
packageTrusted _ _ m
| isHomePkg m = True
| otherwise = trusted $ getPackageDetails dflags (modulePackageKey m)
lookup' :: Module -> Hsc (Maybe ModIface)
lookup' m = do
hsc_env <- getHscEnv
hsc_eps <- liftIO $ hscEPS hsc_env
let pkgIfaceT = eps_PIT hsc_eps
homePkgT = hsc_HPT hsc_env
iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m
#ifdef GHCI
-- the 'lookupIfaceByModule' method will always fail when calling from GHCi
-- as the compiler hasn't filled in the various module tables
-- so we need to call 'getModuleInterface' to load from disk
iface' <- case iface of
Just _ -> return iface
Nothing -> snd `fmap` (liftIO $ getModuleInterface hsc_env m)
return iface'
#else
return iface
#endif
isHomePkg :: Module -> Bool
isHomePkg m
| thisPackage dflags == modulePackageKey m = True
| otherwise = False
-- | Check the list of packages are trusted.
checkPkgTrust :: DynFlags -> [PackageKey] -> Hsc ()
checkPkgTrust dflags pkgs =
case errors of
[] -> return ()
_ -> (liftIO . throwIO . mkSrcErr . listToBag) errors
where
errors = catMaybes $ map go pkgs
go pkg
| trusted $ getPackageDetails dflags pkg
= Nothing
| otherwise
= Just $ mkErrMsg dflags noSrcSpan (pkgQual dflags)
$ text "The package (" <> ppr pkg <> text ") is required" <>
text " to be trusted but it isn't!"
-- | Set module to unsafe and (potentially) wipe trust information.
--
-- Make sure to call this method to set a module to inferred unsafe, it should
-- be a central and single failure method. We only wipe the trust information
-- when we aren't in a specific Safe Haskell mode.
--
-- While we only use this for recording that a module was inferred unsafe, we
-- may call it on modules using Trustworthy or Unsafe flags so as to allow
-- warning flags for safety to function correctly. See Note [Safe Haskell
-- Inference].
markUnsafeInfer :: TcGblEnv -> WarningMessages -> Hsc TcGblEnv
markUnsafeInfer tcg_env whyUnsafe = do
dflags <- getDynFlags
when (wopt Opt_WarnUnsafe dflags)
(logWarnings $ unitBag $
mkPlainWarnMsg dflags (warnUnsafeOnLoc dflags) (whyUnsafe' dflags))
liftIO $ writeIORef (tcg_safeInfer tcg_env) False
-- NOTE: Only wipe trust when not in an explicity safe haskell mode. Other
-- times inference may be on but we are in Trustworthy mode -- so we want
-- to record safe-inference failed but not wipe the trust dependencies.
case safeHaskell dflags == Sf_None of
True -> return $ tcg_env { tcg_imports = wiped_trust }
False -> return tcg_env
where
wiped_trust = (tcg_imports tcg_env) { imp_trust_pkgs = [] }
pprMod = ppr $ moduleName $ tcg_mod tcg_env
whyUnsafe' df = vcat [ quotes pprMod <+> text "has been inferred as unsafe!"
, text "Reason:"
, nest 4 $ (vcat $ badFlags df) $+$
(vcat $ pprErrMsgBagWithLoc whyUnsafe) $+$
(vcat $ badInsts $ tcg_insts tcg_env)
]
badFlags df = concat $ map (badFlag df) unsafeFlagsForInfer
badFlag df (str,loc,on,_)
| on df = [mkLocMessage SevOutput (loc df) $
text str <+> text "is not allowed in Safe Haskell"]
| otherwise = []
badInsts insts = concat $ map badInst insts
badInst ins | overlapMode (is_flag ins) /= NoOverlap
= [mkLocMessage SevOutput (nameSrcSpan $ getName $ is_dfun ins) $
ppr (overlapMode $ is_flag ins) <+>
text "overlap mode isn't allowed in Safe Haskell"]
| otherwise = []
-- | Figure out the final correct safe haskell mode
hscGetSafeMode :: TcGblEnv -> Hsc SafeHaskellMode
hscGetSafeMode tcg_env = do
dflags <- getDynFlags
liftIO $ finalSafeMode dflags tcg_env
--------------------------------------------------------------
-- Simplifiers
--------------------------------------------------------------
hscSimplify :: HscEnv -> ModGuts -> IO ModGuts
hscSimplify hsc_env modguts = runHsc hsc_env $ hscSimplify' modguts
hscSimplify' :: ModGuts -> Hsc ModGuts
hscSimplify' ds_result = do
hsc_env <- getHscEnv
{-# SCC "Core2Core" #-}
liftIO $ core2core hsc_env ds_result
--------------------------------------------------------------
-- Interface generators
--------------------------------------------------------------
hscSimpleIface :: HscEnv
-> TcGblEnv
-> Maybe Fingerprint
-> IO (ModIface, Bool, ModDetails)
hscSimpleIface hsc_env tc_result mb_old_iface
= runHsc hsc_env $ hscSimpleIface' tc_result mb_old_iface
hscSimpleIface' :: TcGblEnv
-> Maybe Fingerprint
-> Hsc (ModIface, Bool, ModDetails)
hscSimpleIface' tc_result mb_old_iface = do
hsc_env <- getHscEnv
details <- liftIO $ mkBootModDetailsTc hsc_env tc_result
safe_mode <- hscGetSafeMode tc_result
(new_iface, no_change)
<- {-# SCC "MkFinalIface" #-}
ioMsgMaybe $
mkIfaceTc hsc_env mb_old_iface safe_mode details tc_result
-- And the answer is ...
liftIO $ dumpIfaceStats hsc_env
return (new_iface, no_change, details)
hscNormalIface :: HscEnv
-> ModGuts
-> Maybe Fingerprint
-> IO (ModIface, Bool, ModDetails, CgGuts)
hscNormalIface hsc_env simpl_result mb_old_iface =
runHsc hsc_env $ hscNormalIface' simpl_result mb_old_iface
hscNormalIface' :: ModGuts
-> Maybe Fingerprint
-> Hsc (ModIface, Bool, ModDetails, CgGuts)
hscNormalIface' simpl_result mb_old_iface = do
hsc_env <- getHscEnv
(cg_guts, details) <- {-# SCC "CoreTidy" #-}
liftIO $ tidyProgram hsc_env simpl_result
-- BUILD THE NEW ModIface and ModDetails
-- and emit external core if necessary
-- This has to happen *after* code gen so that the back-end
-- info has been set. Not yet clear if it matters waiting
-- until after code output
(new_iface, no_change)
<- {-# SCC "MkFinalIface" #-}
ioMsgMaybe $
mkIface hsc_env mb_old_iface details simpl_result
liftIO $ dumpIfaceStats hsc_env
-- Return the prepared code.
return (new_iface, no_change, details, cg_guts)
--------------------------------------------------------------
-- BackEnd combinators
--------------------------------------------------------------
hscWriteIface :: DynFlags -> ModIface -> Bool -> ModSummary -> IO ()
hscWriteIface dflags iface no_change mod_summary = do
let ifaceFile = ml_hi_file (ms_location mod_summary)
unless no_change $
{-# SCC "writeIface" #-}
writeIfaceFile dflags ifaceFile iface
whenGeneratingDynamicToo dflags $ do
-- TODO: We should do a no_change check for the dynamic
-- interface file too
-- TODO: Should handle the dynamic hi filename properly
let dynIfaceFile = replaceExtension ifaceFile (dynHiSuf dflags)
dynIfaceFile' = addBootSuffix_maybe (mi_boot iface) dynIfaceFile
dynDflags = dynamicTooMkDynamicDynFlags dflags
writeIfaceFile dynDflags dynIfaceFile' iface
-- | Compile to hard-code.
hscGenHardCode :: HscEnv -> CgGuts -> ModSummary -> FilePath
-> IO (FilePath, Maybe FilePath) -- ^ @Just f@ <=> _stub.c is f
hscGenHardCode hsc_env cgguts mod_summary output_filename = do
let CgGuts{ -- This is the last use of the ModGuts in a compilation.
-- From now on, we just use the bits we need.
cg_module = this_mod,
cg_binds = core_binds,
cg_tycons = tycons,
cg_foreign = foreign_stubs0,
cg_dep_pkgs = dependencies,
cg_hpc_info = hpc_info } = cgguts
dflags = hsc_dflags hsc_env
location = ms_location mod_summary
data_tycons = filter isDataTyCon tycons
-- cg_tycons includes newtypes, for the benefit of External Core,
-- but we don't generate any code for newtypes
-------------------
-- PREPARE FOR CODE GENERATION
-- Do saturation and convert to A-normal form
prepd_binds <- {-# SCC "CorePrep" #-}
corePrepPgm dflags hsc_env core_binds data_tycons ;
----------------- Convert to STG ------------------
(stg_binds, cost_centre_info)
<- {-# SCC "CoreToStg" #-}
myCoreToStg dflags this_mod prepd_binds
let prof_init = profilingInitCode this_mod cost_centre_info
foreign_stubs = foreign_stubs0 `appendStubC` prof_init
------------------ Code generation ------------------
-- The back-end is streamed: each top-level function goes
-- from Stg all the way to asm before dealing with the next
-- top-level function, so showPass isn't very useful here.
-- Hence we have one showPass for the whole backend, the
-- next showPass after this will be "Assembler".
showPass dflags "CodeGen"
cmms <- {-# SCC "StgCmm" #-}
doCodeGen hsc_env this_mod data_tycons
cost_centre_info
stg_binds hpc_info
------------------ Code output -----------------------
rawcmms0 <- {-# SCC "cmmToRawCmm" #-}
cmmToRawCmm dflags cmms
let dump a = do dumpIfSet_dyn dflags Opt_D_dump_cmm_raw "Raw Cmm"
(ppr a)
return a
rawcmms1 = Stream.mapM dump rawcmms0
(output_filename, (_stub_h_exists, stub_c_exists))
<- {-# SCC "codeOutput" #-}
codeOutput dflags this_mod output_filename location
foreign_stubs dependencies rawcmms1
return (output_filename, stub_c_exists)
hscInteractive :: HscEnv
-> CgGuts
-> ModSummary
-> IO (Maybe FilePath, CompiledByteCode, ModBreaks)
#ifdef GHCI
hscInteractive hsc_env cgguts mod_summary = do
let dflags = hsc_dflags hsc_env
let CgGuts{ -- This is the last use of the ModGuts in a compilation.
-- From now on, we just use the bits we need.
cg_module = this_mod,
cg_binds = core_binds,
cg_tycons = tycons,
cg_foreign = foreign_stubs,
cg_modBreaks = mod_breaks } = cgguts
location = ms_location mod_summary
data_tycons = filter isDataTyCon tycons
-- cg_tycons includes newtypes, for the benefit of External Core,
-- but we don't generate any code for newtypes
-------------------
-- PREPARE FOR CODE GENERATION
-- Do saturation and convert to A-normal form
prepd_binds <- {-# SCC "CorePrep" #-}
corePrepPgm dflags hsc_env core_binds data_tycons
----------------- Generate byte code ------------------
comp_bc <- byteCodeGen dflags this_mod prepd_binds data_tycons mod_breaks
------------------ Create f-x-dynamic C-side stuff ---
(_istub_h_exists, istub_c_exists)
<- outputForeignStubs dflags this_mod location foreign_stubs
return (istub_c_exists, comp_bc, mod_breaks)
#else
hscInteractive _ _ = panic "GHC not compiled with interpreter"
#endif
------------------------------
hscCompileCmmFile :: HscEnv -> FilePath -> FilePath -> IO ()
hscCompileCmmFile hsc_env filename output_filename = runHsc hsc_env $ do
let dflags = hsc_dflags hsc_env
cmm <- ioMsgMaybe $ parseCmmFile dflags filename
liftIO $ do
us <- mkSplitUniqSupply 'S'
let initTopSRT = initUs_ us emptySRT
dumpIfSet_dyn dflags Opt_D_dump_cmm "Parsed Cmm" (ppr cmm)
(_, cmmgroup) <- cmmPipeline hsc_env initTopSRT cmm
rawCmms <- cmmToRawCmm dflags (Stream.yield cmmgroup)
_ <- codeOutput dflags no_mod output_filename no_loc NoStubs [] rawCmms
return ()
where
no_mod = panic "hscCmmFile: no_mod"
no_loc = ModLocation{ ml_hs_file = Just filename,
ml_hi_file = panic "hscCmmFile: no hi file",
ml_obj_file = panic "hscCmmFile: no obj file" }
-------------------- Stuff for new code gen ---------------------
doCodeGen :: HscEnv -> Module -> [TyCon]
-> CollectedCCs
-> [StgBinding]
-> HpcInfo
-> IO (Stream IO CmmGroup ())
-- Note we produce a 'Stream' of CmmGroups, so that the
-- backend can be run incrementally. Otherwise it generates all
-- the C-- up front, which has a significant space cost.
doCodeGen hsc_env this_mod data_tycons
cost_centre_info stg_binds hpc_info = do
let dflags = hsc_dflags hsc_env
let cmm_stream :: Stream IO CmmGroup ()
cmm_stream = {-# SCC "StgCmm" #-}
StgCmm.codeGen dflags this_mod data_tycons
cost_centre_info stg_binds hpc_info
-- codegen consumes a stream of CmmGroup, and produces a new
-- stream of CmmGroup (not necessarily synchronised: one
-- CmmGroup on input may produce many CmmGroups on output due
-- to proc-point splitting).
let dump1 a = do dumpIfSet_dyn dflags Opt_D_dump_cmm
"Cmm produced by new codegen" (ppr a)
return a
ppr_stream1 = Stream.mapM dump1 cmm_stream
-- We are building a single SRT for the entire module, so
-- we must thread it through all the procedures as we cps-convert them.
us <- mkSplitUniqSupply 'S'
-- When splitting, we generate one SRT per split chunk, otherwise
-- we generate one SRT for the whole module.
let
pipeline_stream
| gopt Opt_SplitObjs dflags
= {-# SCC "cmmPipeline" #-}
let run_pipeline us cmmgroup = do
let (topSRT', us') = initUs us emptySRT
(topSRT, cmmgroup) <- cmmPipeline hsc_env topSRT' cmmgroup
let srt | isEmptySRT topSRT = []
| otherwise = srtToData topSRT
return (us', srt ++ cmmgroup)
in do _ <- Stream.mapAccumL run_pipeline us ppr_stream1
return ()
| otherwise
= {-# SCC "cmmPipeline" #-}
let initTopSRT = initUs_ us emptySRT
run_pipeline = cmmPipeline hsc_env
in do topSRT <- Stream.mapAccumL run_pipeline initTopSRT ppr_stream1
Stream.yield (srtToData topSRT)
let
dump2 a = do dumpIfSet_dyn dflags Opt_D_dump_cmm "Output Cmm" $ ppr a
return a
ppr_stream2 = Stream.mapM dump2 pipeline_stream
return ppr_stream2
myCoreToStg :: DynFlags -> Module -> CoreProgram
-> IO ( [StgBinding] -- output program
, CollectedCCs) -- cost centre info (declared and used)
myCoreToStg dflags this_mod prepd_binds = do
stg_binds
<- {-# SCC "Core2Stg" #-}
coreToStg dflags this_mod prepd_binds
(stg_binds2, cost_centre_info)
<- {-# SCC "Stg2Stg" #-}
stg2stg dflags this_mod stg_binds
return (stg_binds2, cost_centre_info)
{- **********************************************************************
%* *
\subsection{Compiling a do-statement}
%* *
%********************************************************************* -}
{-
When the UnlinkedBCOExpr is linked you get an HValue of type *IO [HValue]* When
you run it you get a list of HValues that should be the same length as the list
of names; add them to the ClosureEnv.
A naked expression returns a singleton Name [it]. The stmt is lifted into the
IO monad as explained in Note [Interactively-bound Ids in GHCi] in HscTypes
-}
#ifdef GHCI
-- | Compile a stmt all the way to an HValue, but don't run it
--
-- We return Nothing to indicate an empty statement (or comment only), not a
-- parse error.
hscStmt :: HscEnv -> String -> IO (Maybe ([Id], IO [HValue], FixityEnv))
hscStmt hsc_env stmt = hscStmtWithLocation hsc_env stmt "<interactive>" 1
-- | Compile a stmt all the way to an HValue, but don't run it
--
-- We return Nothing to indicate an empty statement (or comment only), not a
-- parse error.
hscStmtWithLocation :: HscEnv
-> String -- ^ The statement
-> String -- ^ The source
-> Int -- ^ Starting line
-> IO (Maybe ([Id], IO [HValue], FixityEnv))
hscStmtWithLocation hsc_env0 stmt source linenumber =
runInteractiveHsc hsc_env0 $ do
maybe_stmt <- hscParseStmtWithLocation source linenumber stmt
case maybe_stmt of
Nothing -> return Nothing
Just parsed_stmt -> do
-- Rename and typecheck it
hsc_env <- getHscEnv
(ids, tc_expr, fix_env) <- ioMsgMaybe $ tcRnStmt hsc_env parsed_stmt
-- Desugar it
ds_expr <- ioMsgMaybe $ deSugarExpr hsc_env tc_expr
liftIO (lintInteractiveExpr "desugar expression" hsc_env ds_expr)
handleWarnings
-- Then code-gen, and link it
-- It's important NOT to have package 'interactive' as thisPackageKey
-- for linking, else we try to link 'main' and can't find it.
-- Whereas the linker already knows to ignore 'interactive'
let src_span = srcLocSpan interactiveSrcLoc
hval <- liftIO $ hscCompileCoreExpr hsc_env src_span ds_expr
let hval_io = unsafeCoerce# hval :: IO [HValue]
return $ Just (ids, hval_io, fix_env)
-- | Compile a decls
hscDecls :: HscEnv
-> String -- ^ The statement
-> IO ([TyThing], InteractiveContext)
hscDecls hsc_env str = hscDeclsWithLocation hsc_env str "<interactive>" 1
-- | Compile a decls
hscDeclsWithLocation :: HscEnv
-> String -- ^ The statement
-> String -- ^ The source
-> Int -- ^ Starting line
-> IO ([TyThing], InteractiveContext)
hscDeclsWithLocation hsc_env0 str source linenumber =
runInteractiveHsc hsc_env0 $ do
L _ (HsModule{ hsmodDecls = decls }) <-
hscParseThingWithLocation source linenumber parseModule str
{- Rename and typecheck it -}
hsc_env <- getHscEnv
tc_gblenv <- ioMsgMaybe $ tcRnDeclsi hsc_env decls
{- Grab the new instances -}
-- We grab the whole environment because of the overlapping that may have
-- been done. See the notes at the definition of InteractiveContext
-- (ic_instances) for more details.
let finsts = tcg_fam_insts tc_gblenv
insts = tcg_insts tc_gblenv
let defaults = tcg_default tc_gblenv
{- Desugar it -}
-- We use a basically null location for iNTERACTIVE
let iNTERACTIVELoc = ModLocation{ ml_hs_file = Nothing,
ml_hi_file = panic "hsDeclsWithLocation:ml_hi_file",
ml_obj_file = panic "hsDeclsWithLocation:ml_hi_file"}
ds_result <- hscDesugar' iNTERACTIVELoc tc_gblenv
{- Simplify -}
simpl_mg <- liftIO $ hscSimplify hsc_env ds_result
{- Tidy -}
(tidy_cg, _mod_details) <- liftIO $ tidyProgram hsc_env simpl_mg
let dflags = hsc_dflags hsc_env
!CgGuts{ cg_module = this_mod,
cg_binds = core_binds,
cg_tycons = tycons,
cg_modBreaks = mod_breaks } = tidy_cg
data_tycons = filter isDataTyCon tycons
{- Prepare For Code Generation -}
-- Do saturation and convert to A-normal form
prepd_binds <- {-# SCC "CorePrep" #-}
liftIO $ corePrepPgm dflags hsc_env core_binds data_tycons
{- Generate byte code -}
cbc <- liftIO $ byteCodeGen dflags this_mod
prepd_binds data_tycons mod_breaks
let src_span = srcLocSpan interactiveSrcLoc
liftIO $ linkDecls hsc_env src_span cbc
let tcs = filterOut isImplicitTyCon (mg_tcs simpl_mg)
ext_ids = [ id | id <- bindersOfBinds core_binds
, isExternalName (idName id)
, not (isDFunId id || isImplicitId id) ]
-- We only need to keep around the external bindings
-- (as decided by TidyPgm), since those are the only ones
-- that might be referenced elsewhere.
-- The DFunIds are in 'insts' (see Note [ic_tythings] in HscTypes
-- Implicit Ids are implicit in tcs
tythings = map AnId ext_ids ++ map ATyCon tcs
let icontext = hsc_IC hsc_env
ictxt1 = extendInteractiveContext icontext tythings
ictxt = ictxt1 { ic_instances = (insts, finsts)
, ic_default = defaults }
return (tythings, ictxt)
hscImport :: HscEnv -> String -> IO (ImportDecl RdrName)
hscImport hsc_env str = runInteractiveHsc hsc_env $ do
(L _ (HsModule{hsmodImports=is})) <-
hscParseThing parseModule str
case is of
[i] -> return (unLoc i)
_ -> liftIO $ throwOneError $
mkPlainErrMsg (hsc_dflags hsc_env) noSrcSpan $
ptext (sLit "parse error in import declaration")
-- | Typecheck an expression (but don't run it)
-- Returns its most general type
hscTcExpr :: HscEnv
-> String -- ^ The expression
-> IO Type
hscTcExpr hsc_env0 expr = runInteractiveHsc hsc_env0 $ do
hsc_env <- getHscEnv
maybe_stmt <- hscParseStmt expr
case maybe_stmt of
Just (L _ (BodyStmt expr _ _ _)) ->
ioMsgMaybe $ tcRnExpr hsc_env expr
_ ->
throwErrors $ unitBag $ mkPlainErrMsg (hsc_dflags hsc_env) noSrcSpan
(text "not an expression:" <+> quotes (text expr))
-- | Find the kind of a type
-- Currently this does *not* generalise the kinds of the type
hscKcType
:: HscEnv
-> Bool -- ^ Normalise the type
-> String -- ^ The type as a string
-> IO (Type, Kind) -- ^ Resulting type (possibly normalised) and kind
hscKcType hsc_env0 normalise str = runInteractiveHsc hsc_env0 $ do
hsc_env <- getHscEnv
ty <- hscParseType str
ioMsgMaybe $ tcRnType hsc_env normalise ty
hscParseStmt :: String -> Hsc (Maybe (GhciLStmt RdrName))
hscParseStmt = hscParseThing parseStmt
hscParseStmtWithLocation :: String -> Int -> String
-> Hsc (Maybe (GhciLStmt RdrName))
hscParseStmtWithLocation source linenumber stmt =
hscParseThingWithLocation source linenumber parseStmt stmt
hscParseType :: String -> Hsc (LHsType RdrName)
hscParseType = hscParseThing parseType
#endif
hscParseIdentifier :: HscEnv -> String -> IO (Located RdrName)
hscParseIdentifier hsc_env str =
runInteractiveHsc hsc_env $ hscParseThing parseIdentifier str
hscParseThing :: (Outputable thing) => Lexer.P thing -> String -> Hsc thing
hscParseThing = hscParseThingWithLocation "<interactive>" 1
hscParseThingWithLocation :: (Outputable thing) => String -> Int
-> Lexer.P thing -> String -> Hsc thing
hscParseThingWithLocation source linenumber parser str
= {-# SCC "Parser" #-} do
dflags <- getDynFlags
liftIO $ showPass dflags "Parser"
let buf = stringToStringBuffer str
loc = mkRealSrcLoc (fsLit source) linenumber 1
case unP parser (mkPState dflags buf loc) of
PFailed span err -> do
let msg = mkPlainErrMsg dflags span err
throwErrors $ unitBag msg
POk pst thing -> do
logWarningsReportErrors (getMessages pst)
liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing)
return thing
hscCompileCore :: HscEnv -> Bool -> SafeHaskellMode -> ModSummary
-> CoreProgram -> FilePath -> IO ()
hscCompileCore hsc_env simplify safe_mode mod_summary binds output_filename
= runHsc hsc_env $ do
guts <- maybe_simplify (mkModGuts (ms_mod mod_summary) safe_mode binds)
(iface, changed, _details, cgguts) <- hscNormalIface' guts Nothing
liftIO $ hscWriteIface (hsc_dflags hsc_env) iface changed mod_summary
_ <- liftIO $ hscGenHardCode hsc_env cgguts mod_summary output_filename
return ()
where
maybe_simplify mod_guts | simplify = hscSimplify' mod_guts
| otherwise = return mod_guts
-- Makes a "vanilla" ModGuts.
mkModGuts :: Module -> SafeHaskellMode -> CoreProgram -> ModGuts
mkModGuts mod safe binds =
ModGuts {
mg_module = mod,
mg_boot = False,
mg_exports = [],
mg_deps = noDependencies,
mg_dir_imps = emptyModuleEnv,
mg_used_names = emptyNameSet,
mg_used_th = False,
mg_rdr_env = emptyGlobalRdrEnv,
mg_fix_env = emptyFixityEnv,
mg_tcs = [],
mg_insts = [],
mg_fam_insts = [],
mg_patsyns = [],
mg_rules = [],
mg_vect_decls = [],
mg_binds = binds,
mg_foreign = NoStubs,
mg_warns = NoWarnings,
mg_anns = [],
mg_hpc_info = emptyHpcInfo False,
mg_modBreaks = emptyModBreaks,
mg_vect_info = noVectInfo,
mg_inst_env = emptyInstEnv,
mg_fam_inst_env = emptyFamInstEnv,
mg_safe_haskell = safe,
mg_trust_pkg = False,
mg_dependent_files = []
}
{- **********************************************************************
%* *
Desugar, simplify, convert to bytecode, and link an expression
%* *
%********************************************************************* -}
#ifdef GHCI
hscCompileCoreExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
hscCompileCoreExpr hsc_env =
lookupHook hscCompileCoreExprHook hscCompileCoreExpr' (hsc_dflags hsc_env) hsc_env
hscCompileCoreExpr' :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue
hscCompileCoreExpr' hsc_env srcspan ds_expr
| rtsIsProfiled
= throwIO (InstallationError "You can't call hscCompileCoreExpr in a profiled compiler")
-- Otherwise you get a seg-fault when you run it
| otherwise
= do { let dflags = hsc_dflags hsc_env
{- Simplify it -}
; simpl_expr <- simplifyExpr dflags ds_expr
{- Tidy it (temporary, until coreSat does cloning) -}
; let tidy_expr = tidyExpr emptyTidyEnv simpl_expr
{- Prepare for codegen -}
; prepd_expr <- corePrepExpr dflags hsc_env tidy_expr
{- Lint if necessary -}
; lintInteractiveExpr "hscCompileExpr" hsc_env prepd_expr
{- Convert to BCOs -}
; bcos <- coreExprToBCOs dflags (icInteractiveModule (hsc_IC hsc_env)) prepd_expr
{- link it -}
; hval <- linkExpr hsc_env srcspan bcos
; return hval }
#endif
{- **********************************************************************
%* *
Statistics on reading interfaces
%* *
%********************************************************************* -}
dumpIfaceStats :: HscEnv -> IO ()
dumpIfaceStats hsc_env = do
eps <- readIORef (hsc_EPS hsc_env)
dumpIfSet dflags (dump_if_trace || dump_rn_stats)
"Interface statistics"
(ifaceStats eps)
where
dflags = hsc_dflags hsc_env
dump_rn_stats = dopt Opt_D_dump_rn_stats dflags
dump_if_trace = dopt Opt_D_dump_if_trace dflags
{- **********************************************************************
%* *
Progress Messages: Module i of n
%* *
%********************************************************************* -}
showModuleIndex :: (Int, Int) -> String
showModuleIndex (i,n) = "[" ++ padded ++ " of " ++ n_str ++ "] "
where
n_str = show n
i_str = show i
padded = replicate (length n_str - length i_str) ' ' ++ i_str
|
jstolarek/ghc
|
compiler/main/HscMain.hs
|
bsd-3-clause
| 69,057 | 0 | 27 | 20,555 | 11,569 | 5,908 | 5,661 | 826 | 9 |
{-# LANGUAGE CPP #-}
module Database.HDBC.Locale
(
defaultTimeLocale,
iso8601DateFormat,
oldIso8601DateFormat
)
where
#ifdef MIN_TIME_15
import Data.Time.Format (defaultTimeLocale)
#else
import System.Locale (defaultTimeLocale)
#endif
-- | As the semantic of System.Locale.iso8601DateFormat has changed with
-- old-locale-1.0.0.2 in a non-compatible way, we now define our own
-- (compatible) version of it.
iso8601DateFormat :: Maybe String -> String
iso8601DateFormat mTimeFmt =
"%0Y-%m-%d" ++ case mTimeFmt of
Nothing -> ""
Just fmt -> ' ' : fmt
-- | HDBC would in versions up to and including 2.4.0.3 use this time format
-- string to serialize timestamps. To keep being able to deserialize timestamps
-- serialized on database engines that keep the representation intact (e.g.
-- SQLite) we keep this format string around, such that we can fall back to it.
oldIso8601DateFormat :: Maybe String -> String
oldIso8601DateFormat mTimeFmt =
"%Y-%m-%d" ++ case mTimeFmt of
Nothing -> ""
Just fmt -> ' ' : fmt
|
hdbc/hdbc
|
Database/HDBC/Locale.hs
|
bsd-3-clause
| 1,101 | 0 | 9 | 243 | 134 | 76 | 58 | 17 | 2 |
module Window (withWindow) where
import System.Exit
import qualified Graphics.UI.GLFW as G
withWindow :: Int -> Int -> String -> (G.Window -> IO ()) -> IO ()
withWindow width height title f = do
G.setErrorCallback $ Just simpleErrorCallback
successfulInit <- G.init
bool successfulInit exitFailure $ do
mw <- G.createWindow width height title Nothing Nothing
case mw of
Nothing -> G.terminate >> exitFailure
Just win -> do
G.makeContextCurrent mw
f win
G.destroyWindow win
G.terminate
exitSuccess
bool :: Bool -> a -> a -> a
bool b falseRes trueRes = if b then trueRes else falseRes
simpleErrorCallback :: G.ErrorCallback
simpleErrorCallback err = putStrLn
|
sgillis/HOpenGL
|
src/Window.hs
|
gpl-2.0
| 793 | 0 | 16 | 236 | 240 | 118 | 122 | 21 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : ./Common/Prec.hs
Description : precedence checking
Copyright : Christian Maeder and Uni Bremen 2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
Precedence checking
-}
module Common.Prec where
import Common.Id
import Common.GlobalAnnotations
import Common.AS_Annotation
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Common.Lib.Rel as Rel
import Data.Data
import Data.Maybe
import Data.List (partition)
-- | a precedence map using numbers for faster lookup
data PrecMap = PrecMap
{ precMap :: Map.Map Id Int
, maxWeight :: Int
} deriving (Show, Typeable, Data)
emptyPrecMap :: PrecMap
emptyPrecMap = PrecMap
{ precMap = Map.empty
, maxWeight = 0
}
mkPrecIntMap :: Rel.Rel Id -> PrecMap
mkPrecIntMap r =
let (m, t) = Rel.toPrecMap r
in emptyPrecMap
{ precMap = m
, maxWeight = t
}
getIdPrec :: PrecMap -> Set.Set Id -> Id -> Int
getIdPrec p ps i = let PrecMap m mx = p in
if i == applId then mx + 1
else Map.findWithDefault
(if begPlace i || endPlace i then
if Set.member i ps then Map.findWithDefault (div mx 2) eqId m else mx
else mx + 2) i m
getSimpleIdPrec :: PrecMap -> Id -> Int
getSimpleIdPrec p = getIdPrec p Set.empty
-- | drop as many elements as are in the first list
dropPrefix :: [a] -> [b] -> [b]
dropPrefix [] l = l
dropPrefix _ [] = []
dropPrefix (_ : xs) (_ : ys) = dropPrefix xs ys
{- | check if a left argument will be added.
(The 'Int' is the number of current arguments.) -}
isLeftArg :: Id -> [a] -> Bool
isLeftArg op nArgs = null nArgs && begPlace op
-- | check if a right argument will be added.
isRightArg :: Id -> [a] -> Bool
isRightArg op@(Id toks _ _) nArgs = endPlace op
&& isSingle (dropPrefix nArgs
$ filter (`elem` [placeTok, typeInstTok]) toks)
joinPlace :: AssocEither -> Id -> Bool
joinPlace side = case side of
ALeft -> begPlace
ARight -> endPlace
checkArg :: AssocEither -> GlobalAnnos -> (Id, Int) -> (Id, Int) -> Id -> Bool
checkArg side ga (op, opPrec) (arg, argPrec) weight =
let precs = prec_annos ga
junction = joinPlace side arg
sop = stripPoly op
assocCond b = if stripPoly arg == sop
then not $ isAssoc side (assoc_annos ga) sop else b
in argPrec > 0 &&
case compare argPrec opPrec of
LT -> not junction && op /= applId
GT -> True
EQ -> not junction ||
case precRel precs sop $ stripPoly weight of
Lower -> True
Higher -> False
BothDirections -> assocCond False
NoDirection ->
case (isInfix arg, joinPlace side op) of
(True, True) -> assocCond True
(False, True) -> True
(True, False) -> False
_ -> side == ALeft
-- | compute the left or right weight for the application
nextWeight :: AssocEither -> GlobalAnnos -> Id -> Id -> Id
nextWeight side ga arg op =
if joinPlace side arg then
case precRel (prec_annos ga) (stripPoly op) $ stripPoly arg of
Higher -> arg
_ -> op
else op
-- | check precedence of an argument and a top-level operator.
checkPrec :: GlobalAnnos -> (Id, Int) -> (Id, Int) -> [a]
-> (AssocEither -> Id) -> Bool
checkPrec ga op@(o, _) arg args weight
| isLeftArg o args = checkArg ARight ga op arg (weight ARight)
| isRightArg o args = checkArg ALeft ga op arg (weight ALeft)
| otherwise = True
-- | token for instantiation lists of polymorphic operations
typeInstTok :: Token
typeInstTok = mkSimpleId "[type ]"
-- | mark an identifier as polymorphic with a `typeInstTok` token
polyId :: Id -> Id
polyId (Id ts cs ps) = let (toks, pls) = splitMixToken ts in
Id (toks ++ [typeInstTok] ++ pls) cs ps
-- | remove the `typeInstTok` token again
unPolyId :: Id -> Maybe Id
unPolyId (Id ts cs ps) = let (ft, rt) = partition (== typeInstTok) ts in
case ft of
[_] -> Just $ Id rt cs ps
_ -> Nothing
stripPoly :: Id -> Id
stripPoly w = fromMaybe w $ unPolyId w
-- | get the token lists for polymorphic ids
getGenPolyTokenList :: String -> Id -> [Token]
getGenPolyTokenList str (Id ts cs ps) =
let (toks, pls) = splitMixToken ts in
getTokenList str (Id toks cs ps) ++
typeInstTok : getTokenList str (Id pls [] ps)
|
spechub/Hets
|
Common/Prec.hs
|
gpl-2.0
| 4,558 | 0 | 18 | 1,259 | 1,414 | 741 | 673 | 100 | 10 |
a@(b, c) = (2, 3)
main = (a, b, c)
|
roberth/uu-helium
|
test/parser/AsPatternBinding2.hs
|
gpl-3.0
| 38 | 0 | 6 | 13 | 36 | 22 | 14 | 2 | 1 |
module Main (main) where
import Control.Concurrent.Async
import System.Environment
import PHash
main :: IO ()
main = do
(path:_) <- getArgs
-- mapM imageHash (replicate 10 path)
mapConcurrently imageHash (replicate 50 path)
return ()
-- (path1:path2:_) <- getArgs
-- (Just ph1) <- imageHash path1
-- (Just ph2) <- imageHash path2
-- print $ hammingDistance ph1 ph2
-- runhaskell -Wall -threaded -lpthread -IpHash-0.9.6/src/ -LpHash-0.9.6/src/.libs -lpHash Main.hs /home/michael/Dropbox/Photos/IMAG0174.jpg /home/michael/Dropbox/Photos/IMAG0202.jpg
|
MichaelXavier/phash
|
Main.hs
|
gpl-3.0
| 567 | 0 | 9 | 85 | 82 | 46 | 36 | 9 | 1 |
module Tools (
separator
) where
separator :: String -> String
separator msg =
let width = 80
pre = "-- "
post = replicate (width - length pre - length msg - 1) '-' in
pre ++ msg ++ " " ++ post
|
FractalBobz/game
|
Tools.hs
|
gpl-3.0
| 229 | 0 | 14 | 79 | 85 | 44 | 41 | 8 | 1 |
--------------------------------------------------------------------------------
{-|
Module : Events
Copyright : (c) Daan Leijen 2003
(c) Shelarcy ([email protected]) 2006
License : wxWindows
Maintainer : [email protected]
Stability : provisional
Portability : portable
Define event handling. Events are parametrised by the widget that can
correspond to a certain event and the type of the event handler.
For example, the 'resize' event has type:
> Reactive w => Event w (IO ())
This means that all widgets in the 'Reactive' class can respond to
'resize' events (and since 'Window' is an instance of this class, this
means that basically all visible widgets are reactive).
An @Event w a@ can be transformed into an attribute of type 'Attr' @w a@
using the 'on' function.
> do f <- frame [text := "test"]
> set f [on resize := set f [text := "resizing"]]
For convenience, the 'mouse' and 'keyboard' have a serie of /event filters/:
'click', 'drag', 'enterKey', 'charKey', etc. These filters are write-only
and do not overwrite any previous mouse or keyboard handler but all stay
active at the same time. However, all filters will be overwritten again
when 'mouse' or 'keyboard' is set again. For example, the following program
makes sense:
> set w [on click := ..., on drag := ...]
But in the following program, only the handler for 'mouse' will be called:
> set w [on click := ..., on mouse := ...]
If you want to set the 'mouse' later but retain the old event filters,
you can first read the current 'mouse' handler and call it in the
new handler (and the same for the 'keyboard', of course). This implementation
technique is used to implement event filters themselves and is also
very useful when setting an event handler for a 'closing' event:
> set w [on closing :~ \previous -> do{ ...; previous }]
Note that you should call 'propagateEvent' (or 'Graphics.UI.WXCore.Events.skipCurrentEvent') whenever
you do not process the event yourself in an event handler. This propagates
the event to the parent event handlers and give them a chance to
handle the event in an appropiate way. This gives another elegant way to install
a 'closing' event handler:
> set w [on closing := do{ ...; propagateEvent }]
-}
--------------------------------------------------------------------------------
module Graphics.UI.WX.Events
( -- * Event
Event
, on
, mapEvent
, propagateEvent
-- * Basic events
-- ** Selecting
, Selecting, select
-- ** Commanding
, Commanding, command
-- ** Updating
, Updating, update
-- ** Reactive
, Reactive
, mouse, keyboard
, closing, idle, resize, focus, activate
, Paint
, paint, paintRaw, paintGc, repaint
-- * Event filters
-- ** Mouse filters
, enter, leave, motion, drag
, click, unclick, doubleClick
, clickRight, unclickRight
-- * Keyboard event filters
, anyKey, key, charKey
, enterKey,tabKey,escKey,helpKey
, delKey,homeKey,endKey
, pgupKey,pgdownKey
, downKey,upKey,leftKey,rightKey
, rebind
-- * Types
-- ** Modifiers
, Modifiers(..)
, showModifiers
, noneDown, justShift, justAlt, justControl, justMeta, isNoneDown
, isNoShiftAltControlDown
-- ** Mouse events
, EventMouse (..)
, showMouse
, mousePos, mouseModifiers
-- ** Calender event
, EventCalendar(..)
, calendarEvent
-- ** AuiNotebook event
, EventAuiNotebook(..)
, auiNotebookOnPageCloseEvent
, auiNotebookOnPageClosedEvent
, auiNotebookOnPageChangingEvent
, auiNotebookOnPageChangedEvent
-- ** Keyboard events
, EventKey (..), Key(..)
, keyKey, keyModifiers, keyPos
, showKey, showKeyModifiers
-- * Internal
, newEvent
) where
import Graphics.UI.WXCore hiding (Event)
import Graphics.UI.WX.Attributes
{--------------------------------------------------------------------
Basic events
--------------------------------------------------------------------}
-- | An event for a widget @w@ that expects an event handler of type @a@.
data Event w a = Event (Attr w a)
-- | Transform an event to an attribute.
on :: Event w a -> Attr w a
on (Event attr)
= attr
-- | Change the event type.
mapEvent :: (a -> b) -> (a -> b -> a) -> Event w a -> Event w b
mapEvent get' set' (Event attr)
= Event (mapAttr get' set' attr)
{--------------------------------------------------------------------
Event classes
--------------------------------------------------------------------}
-- | 'Selecting' widgets fire a 'select' event when an item is selected.
class Selecting w where
-- | A 'select' event is fired when an item is selected.
select :: Event w (IO ())
-- | 'Commanding' widgets fire a 'command' event.
class Commanding w where
-- | A commanding event, for example a button press.
command :: Event w (IO ())
-- | 'Updating' widgets fire an 'update' event.
class Updating w where
-- | An update event, for example when the text of a 'TextCtrl' changes.
-- An update event, unlike a 'command' event, is typically a passive state
-- change and doesn't require a response.
update :: Event w (IO ())
-- | 'Reactive' widgets are almost all visible widgets on the screen.
class Reactive w where
mouse :: Event w (EventMouse -> IO ())
keyboard :: Event w (EventKey -> IO ())
closing :: Event w (IO ())
idle :: Event w (IO Bool)
resize :: Event w (IO ())
focus :: Event w (Bool -> IO ())
activate :: Event w (Bool -> IO ())
-- | 'Paint' widgets can serve as a canvas.
-- /Note:/ it is illegal to use both a 'paint' and 'paintRaw'
-- event handler at the same widget.
class Paint w where
-- | Paint double buffered to a device context. The context is always
-- cleared before drawing. Takes the current view rectangle (adjusted
-- for scrolling) as an argument.
paint :: Event w (DC () -> Rect -> IO ())
-- | Paint directly to the on-screen device context. Takes the current
-- view rectangle and a list of dirty rectangles as arguments.\
paintRaw :: Event w (PaintDC () -> Rect -> [Rect] -> IO ())
-- | Paint double buffered to a 'GCDC' device context, for
-- anti-aliased drawing. The context is always cleared before
-- drawing. Takes the current view rectangle (adjusted for
-- scrolling) as an argument.
paintGc :: Event w (GCDC () -> Rect -> IO ())
-- | Emit a paint event to the specified widget.
repaint :: w -> IO ()
{--------------------------------------------------------------------
Mouse event filters
--------------------------------------------------------------------}
click :: Reactive w => Event w (Point -> IO ())
click
= mouseFilter "click" filter'
where
filter' (MouseLeftDown _point mod') = isNoShiftAltControlDown mod'
filter' _other = False
unclick :: Reactive w => Event w (Point -> IO ())
unclick
= mouseFilter "unclick" filter'
where
filter' (MouseLeftUp _point mod') = isNoShiftAltControlDown mod'
filter' _other = False
doubleClick :: Reactive w => Event w (Point -> IO ())
doubleClick
= mouseFilter "doubleClick" filter'
where
filter' (MouseLeftDClick _point mod') = isNoShiftAltControlDown mod'
filter' _other = False
drag :: Reactive w => Event w (Point -> IO ())
drag
= mouseFilter "drag" filter'
where
filter' (MouseLeftDrag _point mod') = isNoShiftAltControlDown mod'
filter' _other = False
motion :: Reactive w => Event w (Point -> IO ())
motion
= mouseFilter "motion" filter'
where
filter' (MouseMotion _point mod') = isNoShiftAltControlDown mod'
filter' _other = False
clickRight :: Reactive w => Event w (Point -> IO ())
clickRight
= mouseFilter "clickRight" filter'
where
filter' (MouseRightDown _point mod') = isNoShiftAltControlDown mod'
filter' _other = False
unclickRight :: Reactive w => Event w (Point -> IO ())
unclickRight
= mouseFilter "unclickRight" filter'
where
filter' (MouseRightUp _point mod') = isNoShiftAltControlDown mod'
filter' _other = False
enter :: Reactive w => Event w (Point -> IO ())
enter
= mouseFilter "enter" filter'
where
filter' (MouseEnter _point _mod) = True
filter' _other = False
leave :: Reactive w => Event w (Point -> IO ())
leave
= mouseFilter "leave" filter'
where
filter' (MouseLeave _point _mod) = True
filter' _other = False
mouseFilter :: Reactive w => String -> (EventMouse -> Bool) -> Event w (Point -> IO ())
mouseFilter name filter'
= mapEvent get' set' mouse
where
get' _prev _x
= ioError (userError ("WX.Events: the " ++ name ++ " event is write-only."))
set' prev new mouseEvent
= if (filter' mouseEvent)
then new (mousePos mouseEvent)
else prev mouseEvent
{--------------------------------------------------------------------
Keyboard filter events
--------------------------------------------------------------------}
rebind :: Event w (IO ()) -> Event w (IO ())
rebind event
= mapEvent get' set' event
where
get' prev
= prev
set' new _prev
= new
enterKey,tabKey,escKey,helpKey,delKey,homeKey,endKey :: Reactive w => Event w (IO ())
pgupKey,pgdownKey,downKey,upKey,leftKey,rightKey :: Reactive w => Event w (IO ())
enterKey = key KeyReturn
tabKey = key KeyTab
escKey = key KeyEscape
helpKey = key KeyHelp
delKey = key KeyDelete
homeKey = key KeyHome
endKey = key KeyEnd
pgupKey = key KeyPageUp
pgdownKey = key KeyPageDown
downKey = key KeyDown
upKey = key KeyUp
leftKey = key KeyLeft
rightKey = key KeyRight
charKey :: Reactive w => Char -> Event w (IO ())
charKey c
= key (KeyChar c)
key :: Reactive w => Key -> Event w (IO ())
key k
= keyboardFilter "key" filter'
where
filter' (EventKey x _mod _pt) = k==x
anyKey :: Reactive w => Event w (Key -> IO ())
anyKey
= keyboardFilter1 "anyKey" (const True)
keyboardFilter :: Reactive w => String -> (EventKey -> Bool) -> Event w (IO ())
keyboardFilter name filter'
= mapEvent get' set' keyboard
where
get' _prev
= ioError (userError ("WX.Events: the " ++ name ++ " event is write-only."))
set' prev new keyboardEvent
= do when (filter' keyboardEvent) new
prev keyboardEvent
keyboardFilter1 :: Reactive w => String -> (EventKey -> Bool) -> Event w (Key -> IO ())
keyboardFilter1 name filter'
= mapEvent get' set' keyboard
where
get' _prev _key
= ioError (userError ("WX.Events: the " ++ name ++ " event is write-only."))
set' prev new keyboardEvent
= if (filter' keyboardEvent)
then new (keyKey keyboardEvent)
else prev keyboardEvent
{--------------------------------------------------------------------
Calender event filters
--------------------------------------------------------------------}
calendarEvent :: Event (CalendarCtrl a) (EventCalendar -> IO ())
calendarEvent
= newEvent "calendarEvent" calendarCtrlGetOnCalEvent calendarCtrlOnCalEvent
{--------------------------------------------------------------------
AuiNotebook event filters
--------------------------------------------------------------------}
newAuiEvent :: String -> EventId -> Event (AuiNotebook a) (EventAuiNotebook -> IO ())
newAuiEvent s evId = newEvent s (auiNotebookGetOnAuiNotebookEvent evId) (auiNotebookOnAuiNotebookEvent s evId)
-- AUI Notebook PageClose
auiNotebookOnPageCloseEvent :: Event (AuiNotebook a) (EventAuiNotebook -> IO ())
auiNotebookOnPageCloseEvent = newAuiEvent "auiNotebookOnPageClose" wxEVT_AUINOTEBOOK_PAGE_CLOSE
-- AUINotebook PageClosed
auiNotebookOnPageClosedEvent :: Event (AuiNotebook a) (EventAuiNotebook -> IO ())
auiNotebookOnPageClosedEvent = newAuiEvent "auiNotebookOnPageClosed" wxEVT_AUINOTEBOOK_PAGE_CLOSED
-- AUINotebook PageChange
auiNotebookOnPageChangingEvent :: Event (AuiNotebook a) (EventAuiNotebook -> IO ())
auiNotebookOnPageChangingEvent = newAuiEvent "auiNotebookOnPageChanging" wxEVT_AUINOTEBOOK_PAGE_CHANGING
-- AUINotebook PageChanged
auiNotebookOnPageChangedEvent :: Event (AuiNotebook a) (EventAuiNotebook -> IO ())
auiNotebookOnPageChangedEvent = newAuiEvent "auiNotebookOnPageChanged" wxEVT_AUINOTEBOOK_PAGE_CHANGED
{--------------------------------------------------------------------
Generic event creators
-------------------------------------------------------------------}
-- | Create a new event from a get and set function.
newEvent :: String -> (w -> IO a) -> (w -> a -> IO ()) -> Event w a
newEvent name getter setter
= Event (newAttr name getter setter)
|
jacekszymanski/wxHaskell
|
wx/src/Graphics/UI/WX/Events.hs
|
lgpl-2.1
| 13,240 | 0 | 13 | 3,138 | 2,543 | 1,341 | 1,202 | 188 | 2 |
{-# LANGUAGE TupleSections #-}
{-| Implementation of the Ganeti confd server functionality.
-}
{-
Copyright (C) 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Confd.Server
( main
, checkMain
, prepMain
) where
import Control.Concurrent
import Control.Monad (forever, liftM)
import Data.IORef
import Data.List
import qualified Data.ByteString.Char8 as Char8
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import Network.BSD (getServicePortNumber)
import qualified Network.Socket as S
import Network.Socket.ByteString (recvFrom, sendTo)
import System.Exit
import System.IO
import qualified Text.JSON as J
import Ganeti.BasicTypes
import Ganeti.Errors
import Ganeti.Daemon
import Ganeti.JSON (containerFromList, fromContainer)
import Ganeti.Objects
import Ganeti.Confd.Types
import Ganeti.Confd.Utils
import Ganeti.Config
import Ganeti.ConfigReader
import Ganeti.Hash
import Ganeti.Logging
import qualified Ganeti.Constants as C
import qualified Ganeti.Query.Cluster as QCluster
import Ganeti.Utils
import Ganeti.DataCollectors.Types (DataCollector(..))
import Ganeti.DataCollectors (collectors)
-- * Types and constants definitions
-- | What we store as configuration.
type CRef = IORef (Result (ConfigData, LinkIpMap))
-- | A small type alias for readability.
type StatusAnswer = (ConfdReplyStatus, J.JSValue, Int)
-- | Unknown entry standard response.
queryUnknownEntry :: StatusAnswer
queryUnknownEntry = (ReplyStatusError, J.showJSON ConfdErrorUnknownEntry, 0)
{- not used yet
-- | Internal error standard response.
queryInternalError :: StatusAnswer
queryInternalError = (ReplyStatusError, J.showJSON ConfdErrorInternal)
-}
-- | Argument error standard response.
queryArgumentError :: StatusAnswer
queryArgumentError = (ReplyStatusError, J.showJSON ConfdErrorArgument, 0)
-- | Converter from specific error to a string format.
gntErrorToResult :: ErrorResult a -> Result a
gntErrorToResult (Bad err) = Bad (show err)
gntErrorToResult (Ok x) = Ok x
-- * Confd base functionality
-- | Computes the node role
nodeRole :: ConfigData -> String -> Result ConfdNodeRole
nodeRole cfg name = do
cmaster <- errToResult $ QCluster.clusterMasterNodeName cfg
mnode <- errToResult $ getNode cfg name
let nrole = case mnode of
node | cmaster == name -> NodeRoleMaster
| nodeDrained node -> NodeRoleDrained
| nodeOffline node -> NodeRoleOffline
| nodeMasterCandidate node -> NodeRoleCandidate
_ -> NodeRoleRegular
return nrole
-- | Does an instance ip -> instance -> primary node -> primary ip
-- transformation.
getNodePipByInstanceIp :: ConfigData
-> LinkIpMap
-> String
-> String
-> StatusAnswer
getNodePipByInstanceIp cfg linkipmap link instip =
case M.lookup instip (M.findWithDefault M.empty link linkipmap) of
Nothing -> queryUnknownEntry
Just instname ->
case getInstPrimaryNode cfg instname of
Bad _ -> queryUnknownEntry -- either instance or node not found
Ok node -> (ReplyStatusOk, J.showJSON (nodePrimaryIp node),
clusterSerial $ configCluster cfg)
-- | Returns a node name for a given UUID
uuidToNodeName :: ConfigData -> String -> Result String
uuidToNodeName cfg uuid = gntErrorToResult $ nodeName <$> getNode cfg uuid
-- | Encodes a list of minors into a JSON representation, converting UUIDs to
-- names in the process
encodeMinors :: ConfigData -> (String, Int, String, String, String, String)
-> Result J.JSValue
encodeMinors cfg (node_uuid, a, b, c, d, peer_uuid) = do
node_name <- uuidToNodeName cfg node_uuid
peer_name <- uuidToNodeName cfg peer_uuid
return . J.JSArray $ [J.showJSON node_name, J.showJSON a, J.showJSON b,
J.showJSON c, J.showJSON d, J.showJSON peer_name]
-- | Builds the response to a given query.
buildResponse :: (ConfigData, LinkIpMap) -> ConfdRequest -> Result StatusAnswer
buildResponse (cfg, _) (ConfdRequest { confdRqType = ReqPing }) =
return (ReplyStatusOk, J.showJSON (configVersion cfg), 0)
buildResponse cdata req@(ConfdRequest { confdRqType = ReqClusterMaster }) =
case confdRqQuery req of
EmptyQuery -> liftM ((ReplyStatusOk,,serial) . J.showJSON) master_name
PlainQuery _ -> return queryArgumentError
DictQuery reqq -> do
mnode <- gntErrorToResult $ getNode cfg master_uuid
mname <- master_name
let fvals = map (\field -> case field of
ReqFieldName -> mname
ReqFieldIp -> clusterMasterIp cluster
ReqFieldMNodePip -> nodePrimaryIp mnode
) (confdReqQFields reqq)
return (ReplyStatusOk, J.showJSON fvals, serial)
where master_uuid = clusterMasterNode cluster
master_name = errToResult $ QCluster.clusterMasterNodeName cfg
cluster = configCluster cfg
cfg = fst cdata
serial = clusterSerial $ configCluster cfg
buildResponse cdata req@(ConfdRequest { confdRqType = ReqNodeRoleByName }) = do
node_name <- case confdRqQuery req of
PlainQuery str -> return str
_ -> fail $ "Invalid query type " ++ show (confdRqQuery req)
nrole <- nodeRole (fst cdata) node_name
return (ReplyStatusOk, J.showJSON nrole,
clusterSerial . configCluster $ fst cdata)
buildResponse cdata (ConfdRequest { confdRqType = ReqNodePipList }) =
-- note: we use foldlWithKey because that's present across more
-- versions of the library
return (ReplyStatusOk, J.showJSON $
M.foldlWithKey (\accu _ n -> nodePrimaryIp n:accu) []
(fromContainer . configNodes . fst $ cdata),
clusterSerial . configCluster $ fst cdata)
buildResponse cdata (ConfdRequest { confdRqType = ReqMcPipList }) =
-- note: we use foldlWithKey because that's present across more
-- versions of the library
return (ReplyStatusOk, J.showJSON $
M.foldlWithKey (\accu _ n -> if nodeMasterCandidate n
then nodePrimaryIp n:accu
else accu) []
(fromContainer . configNodes . fst $ cdata),
clusterSerial . configCluster $ fst cdata)
buildResponse (cfg, linkipmap)
req@(ConfdRequest { confdRqType = ReqInstIpsList }) = do
link <- case confdRqQuery req of
PlainQuery str -> return str
EmptyQuery -> return (getDefaultNicLink cfg)
_ -> fail "Invalid query type"
return (ReplyStatusOk, J.showJSON $ getInstancesIpByLink linkipmap link,
clusterSerial $ configCluster cfg)
buildResponse cdata (ConfdRequest { confdRqType = ReqNodePipByInstPip
, confdRqQuery = DictQuery query}) =
let (cfg, linkipmap) = cdata
link = fromMaybe (getDefaultNicLink cfg) (confdReqQLink query)
in case confdReqQIp query of
Just ip -> return $ getNodePipByInstanceIp cfg linkipmap link ip
Nothing -> return (ReplyStatusOk,
J.showJSON $
map (getNodePipByInstanceIp cfg linkipmap link)
(confdReqQIpList query),
clusterSerial . configCluster $ fst cdata)
buildResponse _ (ConfdRequest { confdRqType = ReqNodePipByInstPip }) =
return queryArgumentError
buildResponse cdata req@(ConfdRequest { confdRqType = ReqNodeDrbd }) = do
let cfg = fst cdata
node_name <- case confdRqQuery req of
PlainQuery str -> return str
_ -> fail $ "Invalid query type " ++ show (confdRqQuery req)
node <- gntErrorToResult $ getNode cfg node_name
let minors = concatMap (getInstMinorsForNode cfg (uuidOf node)) .
M.elems . fromContainer . configInstances $ cfg
encoded <- mapM (encodeMinors cfg) minors
return (ReplyStatusOk, J.showJSON encoded, nodeSerial node)
-- | Return the list of instances for a node (as ([primary], [secondary])) given
-- the node name.
buildResponse cdata req@(ConfdRequest { confdRqType = ReqNodeInstances }) = do
let cfg = fst cdata
node_name <- case confdRqQuery req of
PlainQuery str -> return str
_ -> fail $ "Invalid query type " ++ show (confdRqQuery req)
node <-
case getNode cfg node_name of
Ok n -> return n
Bad e -> fail $ "Node not found in the configuration: " ++ show e
let node_uuid = uuidOf node
instances = getNodeInstances cfg node_uuid
return (ReplyStatusOk, J.showJSON instances, nodeSerial node)
-- | Return the list of disks for an instance given the instance uuid.
buildResponse cdata req@(ConfdRequest { confdRqType = ReqInstanceDisks }) = do
let cfg = fst cdata
inst_name <-
case confdRqQuery req of
PlainQuery str -> return str
_ -> fail $ "Invalid query type " ++ show (confdRqQuery req)
inst <-
case getInstance cfg inst_name of
Ok i -> return i
Bad e -> fail $ "Instance not found in the configuration: " ++ show e
case getInstDisks cfg . uuidOf $ inst of
Ok disks -> return (ReplyStatusOk, J.showJSON disks, instSerial inst)
Bad e -> fail $ "Could not retrieve disks: " ++ show e
-- | Return arbitrary configuration value given by a path.
buildResponse cdata req@(ConfdRequest { confdRqType = ReqConfigQuery
, confdRqQuery = pathQ }) = do
let cfg = fst cdata
path <-
case pathQ of
PlainQuery path -> return path
_ -> fail $ "Invalid query type " ++ show (confdRqQuery req)
let configValue = extractJSONPath path cfg
case configValue of
J.Ok jsvalue -> return (ReplyStatusOk, jsvalue,
clusterSerial $ configCluster cfg)
J.Error _ -> return queryArgumentError
-- | Return activation state of data collectors
buildResponse (cdata,_) (ConfdRequest { confdRqType = ReqDataCollectors }) = do
let mkConfig col =
(dName col, DataCollectorConfig
(dActive col (dName col) cdata)
(dInterval col (dName col) cdata))
datacollectors = containerFromList $ map mkConfig collectors
return (ReplyStatusOk, J.showJSON datacollectors,
clusterSerial . configCluster $ cdata)
-- | Creates a ConfdReply from a given answer.
serializeResponse :: Result StatusAnswer -> ConfdReply
serializeResponse r =
let (status, result, serial) = case r of
Bad err -> (ReplyStatusError, J.showJSON err, 0)
Ok (code, val, ser) -> (code, val, ser)
in ConfdReply { confdReplyProtocol = 1
, confdReplyStatus = status
, confdReplyAnswer = result
, confdReplySerial = serial }
-- ** Client input/output handlers
-- | Main loop for a given client.
responder :: CRef -> S.Socket -> HashKey -> String -> S.SockAddr -> IO ()
responder cfgref socket hmac msg peer = do
ctime <- getCurrentTime
case parseRequest hmac msg ctime of
Ok (origmsg, rq) -> do
logDebug $ "Processing request: " ++ rStripSpace origmsg
mcfg <- readIORef cfgref
let response = respondInner mcfg hmac rq
_ <- sendTo socket (Char8.pack response) peer
logDebug $ "Response sent: " ++ response
return ()
Bad err -> logInfo $ "Failed to parse incoming message: " ++ err
return ()
-- | Inner helper function for a given client. This generates the
-- final encoded message (as a string), ready to be sent out to the
-- client.
respondInner :: Result (ConfigData, LinkIpMap) -> HashKey
-> ConfdRequest -> String
respondInner cfg hmac rq =
let rsalt = confdRqRsalt rq
innermsg = serializeResponse (cfg >>= flip buildResponse rq)
innerserialised = J.encodeStrict innermsg
outermsg = signMessage hmac rsalt innerserialised
outerserialised = C.confdMagicFourcc ++ J.encodeStrict outermsg
in outerserialised
-- | Main listener loop.
listener :: S.Socket -> HashKey
-> (S.Socket -> HashKey -> String -> S.SockAddr -> IO ())
-> IO ()
listener s hmac resp = do
(msg, peer) <- (\(m, p) -> (Char8.unpack m, p)) <$> recvFrom s 4096
if C.confdMagicFourcc `isPrefixOf` msg
then forkIO (resp s hmac (drop 4 msg) peer) >> return ()
else logDebug "Invalid magic code!" >> return ()
return ()
-- | Type alias for prepMain results
type PrepResult = (S.Socket, IORef (Result (ConfigData, LinkIpMap)))
-- | Check function for confd.
checkMain :: CheckFn (S.Family, S.SockAddr)
checkMain opts = do
defaultPort <- withDefaultOnIOError C.defaultConfdPort
. liftM fromIntegral
$ getServicePortNumber C.confd
parseresult <- parseAddress opts defaultPort
case parseresult of
Bad msg -> do
hPutStrLn stderr $ "parsing bind address: " ++ msg
return . Left $ ExitFailure 1
Ok v -> return $ Right v
-- | Prepare function for confd.
prepMain :: PrepFn (S.Family, S.SockAddr) PrepResult
prepMain _ (af_family, bindaddr) = do
s <- S.socket af_family S.Datagram S.defaultProtocol
S.setSocketOption s S.ReuseAddr 1
S.bind s bindaddr
cref <- newIORef (Bad "Configuration not yet loaded")
return (s, cref)
-- | Main function.
main :: MainFn (S.Family, S.SockAddr) PrepResult
main _ _ (s, cref) = do
let cfg_transform :: Result ConfigData -> Result (ConfigData, LinkIpMap)
cfg_transform = liftM (\cfg -> (cfg, buildLinkIpInstnameMap cfg))
initConfigReader (writeIORef cref . cfg_transform)
hmac <- getClusterHmac
-- enter the responder loop
forever $ listener s hmac (responder cref)
|
mbakke/ganeti
|
src/Ganeti/Confd/Server.hs
|
bsd-2-clause
| 14,984 | 0 | 19 | 3,625 | 3,641 | 1,854 | 1,787 | 258 | 18 |
module Idris.REPL.Commands where
import Idris.AbsSyntaxTree
import Idris.Colours
import Idris.Core.TT
-- | REPL commands
data Command = Quit
| Help
| Eval PTerm
| NewDefn [PDecl] -- ^ Each 'PDecl' should be either a type declaration (at most one) or a clause defining the same name.
| Undefine [Name]
| Check PTerm
| Core PTerm
| DocStr (Either Name Const) HowMuchDocs
| TotCheck Name
| Reload
| Watch
| Load FilePath (Maybe Int) -- up to maximum line number
| ChangeDirectory FilePath
| ModImport String
| Edit
| Compile Codegen String
| Execute PTerm
| ExecVal PTerm
| Metavars
| Prove Bool Name -- ^ If false, use prover, if true, use elab shell
| AddProof (Maybe Name)
| RmProof Name
| ShowProof Name
| Proofs
| Universes
| LogLvl Int
| LogCategory [LogCat]
| Verbosity Int
| Spec PTerm
| WHNF PTerm
| TestInline PTerm
| Defn Name
| Missing Name
| DynamicLink FilePath
| ListDynamic
| Pattelab PTerm
| Search [String] PTerm
| CaseSplitAt Bool Int Name
| AddClauseFrom Bool Int Name
| AddProofClauseFrom Bool Int Name
| AddMissing Bool Int Name
| MakeWith Bool Int Name
| MakeCase Bool Int Name
| MakeLemma Bool Int Name
| DoProofSearch Bool -- update file
Bool -- recursive search
Int -- depth
Name -- top level name
[Name] -- hints
| SetOpt Opt
| UnsetOpt Opt
| NOP
| SetColour ColourType IdrisColour
| ColourOn
| ColourOff
| ListErrorHandlers
| SetConsoleWidth ConsoleWidth
| SetPrinterDepth (Maybe Int)
| Apropos [String] String
| WhoCalls Name
| CallsWho Name
| Browse [String]
| MakeDoc String -- IdrisDoc
| Warranty
| PrintDef Name
| PPrint OutputFmt Int PTerm
| TransformInfo Name
-- Debugging commands
| DebugInfo Name
| DebugUnify PTerm PTerm
|
bravit/Idris-dev
|
src/Idris/REPL/Commands.hs
|
bsd-3-clause
| 2,628 | 0 | 8 | 1,257 | 438 | 264 | 174 | 73 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE OverloadedStrings #-}
import Foreign.C.Types
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Unsafe as CU
C.include "<math.h>"
C.include "<stdio.h>"
test_cexp :: CDouble -> CDouble -> IO CDouble
test_cexp x y =
[C.exp| double{ cos($(double x)) + cos($(double y)) } |]
test_cexp_unsafe :: CDouble -> CDouble -> IO CDouble
test_cexp_unsafe x y =
[CU.exp| double{ cos($(double x)) + cos($(double y)) } |]
test_voidExp :: IO ()
test_voidExp = [C.exp| void { printf("Hello\n") } |]
main :: IO ()
main = do
print =<< test_cexp 3 4
print =<< test_cexp_unsafe 3 4
test_voidExp
|
fpco/inline-c
|
sample-cabal-project/src/Main.hs
|
mit
| 738 | 0 | 8 | 129 | 173 | 97 | 76 | 22 | 1 |
{-
Copyright 2017 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
import CodeWorld.Prediction
import qualified Data.IntMap as IM
import qualified Data.Map as M
import Data.Bifunctor
import Data.List
import System.Exit
import Test.QuickCheck
import Common
type EventsDone = ([TimeStamp], IM.IntMap [TEvent])
type LogEntry = Either Double Event
type Log = [LogEntry]
type Check = (EventsDone, Either Double (Int, TEvent))
type CheckReport = (Check, Future Log, Future Log, Future Log)
-- Fake state and handle functions
step :: Double -> Log -> Log
step dt = (Left dt :)
handle :: Event -> Log -> Log
handle dt = (Right dt :)
-- Global constant
rate :: Double
rate = 1/4 -- decimal display
-- Generation of random schedules
-- The actual check:
-- Exhaustively search the order in which these events could happen
-- Memoize every initial segment
-- Ensure that all possible ways reach the same conclusion.
failedChecks :: EventSchedule -> [CheckReport]
failedChecks schedule = map mkReport $ filter (not . check) allChecks
where
allDone :: [EventsDone]
allDone = do
let (tss,em) = schedule
tss' <- inits tss
em' <- traverse inits em -- wow!
return (tss', em')
allChecks :: [Check]
allChecks = allDone >>= prevs
prevs :: EventsDone -> [Check]
prevs (tss,m) =
[ ((init tss, m), Left (last tss))
| not (null tss)
] ++
[ ((tss, IM.adjust init i m), Right (i, last done))
| i <- IM.keys m
, let done = m IM.! i
, not (null done)
]
memo :: M.Map EventsDone (Future Log)
memo = M.fromList [ (eventsDone, recreate eventsDone) | eventsDone <- allDone ]
recreate :: EventsDone -> Future Log
recreate m = case prevs m of
[] -> initFuture [] (IM.size (snd m))
(c:_) -> checkActual c
check :: Check -> Bool
check c = checkActual c `eqFuture` checkExpected c
checkExpected :: Check -> Future Log
checkExpected (prev, Left t) = memo M.! first (++[t]) prev
checkExpected (prev, Right (p,(t,e))) = memo M.! second (IM.adjust (++[(t,e)]) p) prev
checkActual :: Check -> Future Log
checkActual (prev, Left t) =
currentTimePasses step rate t $
memo M.! prev
checkActual (prev, Right (p,(t,e))) =
addEvent step rate p t (handle <$> e) $
memo M.! prev
mkReport :: Check -> CheckReport
mkReport c = (c, memo M.! fst c, checkExpected c, checkActual c)
-- The quickcheck test, with reporting
testPrediction :: Property
testPrediction = forAllSchedules $ \schedule ->
let failed = failedChecks schedule
in reportFailedCheck (head failed) `whenFail` null failed
reportFailedCheck :: CheckReport -> IO ()
reportFailedCheck (c, before, expected, actual) = do
putStrLn "Failed Check"
putStrLn "History:"
putStr $ showHistory (fst c)
putStrLn "Event:"
print (snd c)
putStrLn "Before:"
printInternalState showLog before
putStrLn "Expected:"
printInternalState showLog expected
putStrLn "Actual:"
printInternalState showLog actual
putStrLn ""
showHistory :: EventsDone -> String
showHistory (tss,m) = unlines $
("Queried at: " ++ intercalate " " (map show tss)) : map go (IM.toList m)
where
go (p, tes) = "Player " ++ show p ++ ": " ++ intercalate " " (map ste tes)
ste (t, Nothing) = show t
ste (t, Just e) = show e ++ "@" ++ show t
showLog :: Log -> String
showLog l = intercalate " " (map sle (reverse l))
where
sle (Left x) = show x
sle (Right x) = "["++show x++"]"
-- The main entry point.
-- Set the exit code to please Cabal.
main :: IO ()
main = do
res <- quickCheckWithResult args testPrediction
case res of
Success {} -> exitSuccess
_ -> exitFailure
where
args = stdArgs { maxSize = 30 } -- more gets too large
|
nomeata/codeworld
|
codeworld-prediction/tests/prediction.hs
|
apache-2.0
| 4,434 | 0 | 14 | 1,099 | 1,377 | 720 | 657 | 93 | 4 |
-- data FooType = Baz
data TestType a = Foo a | Bar a FooType Bool
-- foo :: TestType a
-- foo = undefined
bar (Foo x) | x == 1 = Foo 1
|
themattchan/tandoori
|
input/input-3.hs
|
bsd-3-clause
| 155 | 0 | 8 | 54 | 50 | 26 | 24 | 2 | 1 |
{-# LANGUAGE MagicHash #-}
-----------------------------------------------------------------------------
--
-- GHCi Interactive debugging commands
--
-- Pepe Iborra (supported by Google SoC) 2006
--
-- ToDo: lots of violation of layering here. This module should
-- decide whether it is above the GHC API (import GHC and nothing
-- else) or below it.
--
-----------------------------------------------------------------------------
module Debugger (pprintClosureCommand, showTerm, pprTypeAndContents) where
import GhcPrelude
import Linker
import RtClosureInspect
import GHCi
import GHCi.RemoteTypes
import GhcMonad
import HscTypes
import Id
import IfaceSyn ( showToHeader )
import IfaceEnv( newInteractiveBinder )
import Name
import Var hiding ( varName )
import VarSet
import UniqSet
import Type
import GHC
import Outputable
import PprTyThing
import ErrUtils
import MonadUtils
import DynFlags
import Exception
import Control.Monad
import Data.List
import Data.Maybe
import Data.IORef
import GHC.Exts
-------------------------------------
-- | The :print & friends commands
-------------------------------------
pprintClosureCommand :: GhcMonad m => Bool -> Bool -> String -> m ()
pprintClosureCommand bindThings force str = do
tythings <- (catMaybes . concat) `liftM`
mapM (\w -> GHC.parseName w >>=
mapM GHC.lookupName)
(words str)
let ids = [id | AnId id <- tythings]
-- Obtain the terms and the recovered type information
(subst, terms) <- mapAccumLM go emptyTCvSubst ids
-- Apply the substitutions obtained after recovering the types
modifySession $ \hsc_env ->
hsc_env{hsc_IC = substInteractiveContext (hsc_IC hsc_env) subst}
-- Finally, print the Terms
unqual <- GHC.getPrintUnqual
docterms <- mapM showTerm terms
dflags <- getDynFlags
liftIO $ (printOutputForUser dflags unqual . vcat)
(zipWith (\id docterm -> ppr id <+> char '=' <+> docterm)
ids
docterms)
where
-- Do the obtainTerm--bindSuspensions-computeSubstitution dance
go :: GhcMonad m => TCvSubst -> Id -> m (TCvSubst, Term)
go subst id = do
let id' = id `setIdType` substTy subst (idType id)
term_ <- GHC.obtainTermFromId maxBound force id'
term <- tidyTermTyVars term_
term' <- if bindThings &&
(not (isUnliftedType (termType term)))
then bindSuspensions term
else return term
-- Before leaving, we compare the type obtained to see if it's more specific
-- Then, we extract a substitution,
-- mapping the old tyvars to the reconstructed types.
let reconstructed_type = termType term
hsc_env <- getSession
case (improveRTTIType hsc_env (idType id) (reconstructed_type)) of
Nothing -> return (subst, term')
Just subst' -> do { traceOptIf Opt_D_dump_rtti
(fsep $ [text "RTTI Improvement for", ppr id,
text "is the substitution:" , ppr subst'])
; return (subst `unionTCvSubst` subst', term')}
tidyTermTyVars :: GhcMonad m => Term -> m Term
tidyTermTyVars t =
withSession $ \hsc_env -> do
let env_tvs = tyThingsTyCoVars $ ic_tythings $ hsc_IC hsc_env
my_tvs = termTyCoVars t
tvs = env_tvs `minusVarSet` my_tvs
tyvarOccName = nameOccName . tyVarName
tidyEnv = (initTidyOccEnv (map tyvarOccName (nonDetEltsUniqSet tvs))
-- It's OK to use nonDetEltsUniqSet here because initTidyOccEnv
-- forgets the ordering immediately by creating an env
, getUniqSet $ env_tvs `intersectVarSet` my_tvs)
return $ mapTermType (snd . tidyOpenType tidyEnv) t
-- | Give names, and bind in the interactive environment, to all the suspensions
-- included (inductively) in a term
bindSuspensions :: GhcMonad m => Term -> m Term
bindSuspensions t = do
hsc_env <- getSession
inScope <- GHC.getBindings
let ictxt = hsc_IC hsc_env
prefix = "_t"
alreadyUsedNames = map (occNameString . nameOccName . getName) inScope
availNames = map ((prefix++) . show) [(1::Int)..] \\ alreadyUsedNames
availNames_var <- liftIO $ newIORef availNames
(t', stuff) <- liftIO $ foldTerm (nameSuspensionsAndGetInfos hsc_env availNames_var) t
let (names, tys, hvals) = unzip3 stuff
let ids = [ mkVanillaGlobal name ty
| (name,ty) <- zip names tys]
new_ic = extendInteractiveContextWithIds ictxt ids
fhvs <- liftIO $ mapM (mkFinalizedHValue hsc_env <=< mkRemoteRef) hvals
liftIO $ extendLinkEnv (zip names fhvs)
setSession hsc_env {hsc_IC = new_ic }
return t'
where
-- Processing suspensions. Give names and recopilate info
nameSuspensionsAndGetInfos :: HscEnv -> IORef [String]
-> TermFold (IO (Term, [(Name,Type,HValue)]))
nameSuspensionsAndGetInfos hsc_env freeNames = TermFold
{
fSuspension = doSuspension hsc_env freeNames
, fTerm = \ty dc v tt -> do
tt' <- sequence tt
let (terms,names) = unzip tt'
return (Term ty dc v terms, concat names)
, fPrim = \ty n ->return (Prim ty n,[])
, fNewtypeWrap =
\ty dc t -> do
(term, names) <- t
return (NewtypeWrap ty dc term, names)
, fRefWrap = \ty t -> do
(term, names) <- t
return (RefWrap ty term, names)
}
doSuspension hsc_env freeNames ct ty hval _name = do
name <- atomicModifyIORef' freeNames (\x->(tail x, head x))
n <- newGrimName hsc_env name
return (Suspension ct ty hval (Just n), [(n,ty,hval)])
-- A custom Term printer to enable the use of Show instances
showTerm :: GhcMonad m => Term -> m SDoc
showTerm term = do
dflags <- GHC.getSessionDynFlags
if gopt Opt_PrintEvldWithShow dflags
then cPprTerm (liftM2 (++) (\_y->[cPprShowable]) cPprTermBase) term
else cPprTerm cPprTermBase term
where
cPprShowable prec t@Term{ty=ty, val=val} =
if not (isFullyEvaluatedTerm t)
then return Nothing
else do
hsc_env <- getSession
dflags <- GHC.getSessionDynFlags
do
(new_env, bname) <- bindToFreshName hsc_env ty "showme"
setSession new_env
-- XXX: this tries to disable logging of errors
-- does this still do what it is intended to do
-- with the changed error handling and logging?
let noop_log _ _ _ _ _ _ = return ()
expr = "show " ++ showPpr dflags bname
_ <- GHC.setSessionDynFlags dflags{log_action=noop_log}
fhv <- liftIO $ mkFinalizedHValue hsc_env =<< mkRemoteRef val
txt_ <- withExtendedLinkEnv [(bname, fhv)]
(GHC.compileExpr expr)
let myprec = 10 -- application precedence. TODO Infix constructors
let txt = unsafeCoerce# txt_ :: [a]
if not (null txt) then
return $ Just $ cparen (prec >= myprec && needsParens txt)
(text txt)
else return Nothing
`gfinally` do
setSession hsc_env
GHC.setSessionDynFlags dflags
cPprShowable prec NewtypeWrap{ty=new_ty,wrapped_term=t} =
cPprShowable prec t{ty=new_ty}
cPprShowable _ _ = return Nothing
needsParens ('"':_) = False -- some simple heuristics to see whether parens
-- are redundant in an arbitrary Show output
needsParens ('(':_) = False
needsParens txt = ' ' `elem` txt
bindToFreshName hsc_env ty userName = do
name <- newGrimName hsc_env userName
let id = mkVanillaGlobal name ty
new_ic = extendInteractiveContextWithIds (hsc_IC hsc_env) [id]
return (hsc_env {hsc_IC = new_ic }, name)
-- Create new uniques and give them sequentially numbered names
newGrimName :: MonadIO m => HscEnv -> String -> m Name
newGrimName hsc_env userName
= liftIO (newInteractiveBinder hsc_env occ noSrcSpan)
where
occ = mkOccName varName userName
pprTypeAndContents :: GhcMonad m => Id -> m SDoc
pprTypeAndContents id = do
dflags <- GHC.getSessionDynFlags
let pcontents = gopt Opt_PrintBindContents dflags
pprdId = (pprTyThing showToHeader . AnId) id
if pcontents
then do
let depthBound = 100
-- If the value is an exception, make sure we catch it and
-- show the exception, rather than propagating the exception out.
e_term <- gtry $ GHC.obtainTermFromId depthBound False id
docs_term <- case e_term of
Right term -> showTerm term
Left exn -> return (text "*** Exception:" <+>
text (show (exn :: SomeException)))
return $ pprdId <+> equals <+> docs_term
else return pprdId
--------------------------------------------------------------
-- Utils
traceOptIf :: GhcMonad m => DumpFlag -> SDoc -> m ()
traceOptIf flag doc = do
dflags <- GHC.getSessionDynFlags
when (dopt flag dflags) $ liftIO $ printInfoForUser dflags alwaysQualify doc
|
ezyang/ghc
|
compiler/ghci/Debugger.hs
|
bsd-3-clause
| 9,705 | 0 | 20 | 3,023 | 2,359 | 1,208 | 1,151 | 175 | 8 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sq-AL">
<title>FuzzDB Files</title>
<maps>
<homeID>fuzzdb</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/fuzzdb/src/main/javahelp/help_sq_AL/helpset_sq_AL.hs
|
apache-2.0
| 960 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
module Foo.Baz where
bar = 4
|
RefactoringTools/HaRe
|
test/testdata/cabal/foo/src/Foo/Baz.hs
|
bsd-3-clause
| 30 | 0 | 4 | 7 | 11 | 7 | 4 | 2 | 1 |
----------------------------------------------------------------------------------------------------------------
-- Module : RefacTypeUtils
-- Maintainer : refactor-fp\@kent.ac.uk
-- |
--
-- This module contains a collection of program analysis and transformation functions (the API) that work
-- over the Type Decorated AST. Most of the functions defined in the module are taken directly from the API,
-- but in some cases are modified to work with the type decorated AST.
--
-- In particular some new functions have been added to make type decorated AST traversals easier.
--
-- In HaRe, in order to preserve the
-- comments and layout of refactored programs, a refactoring modifies not only the AST but also the token stream, and
-- the program source after the refactoring is extracted from the token stream rather than the AST, for the comments
-- and layout information is kept in the token steam instead of the AST. As a consequence, a program transformation
-- function from this API modifies both the AST and the token stream (unless explicitly stated). So when you build
-- your own program transformations, try to use the API to do the transformation, as this can liberate you from
-- caring about the token stream.
--
-- As the API is based on Programatica's abstract syntax for Haskell, we have re-exported those related module from
-- Programatica, so that you can browse the datatypes for the abstract syntax. Alternatively, you can go to
-- Programatica's webpage at: <http://www.cse.ogi.edu/~hallgren/Programatica/>. For Strafunski, you can find it
-- at: <http://www.cs.vu.nl/Strafunski/>.
--
-- This type decorated API is still in development. Any suggestions and comments are very much welcome.
------------------------------------------------------------------------------------------------------------------
module RefacTypeUtils(module DriftStructUtils, module StrategyLib, module RefacTITypeSyn, module PosSyntax,
module SourceNames, module UniqueNames, module PNT,
module Ents, module Relations, module QualNames, module TypedIds
-- * Program Analysis
-- ** Imports and exports
,inScopeInfo, isInScopeAndUnqualified, hsQualifier, {-This function should be removed-} rmPrelude
,exportInfo, isExported, isExplicitlyExported, modIsExported
-- ** Variable analysis
,hsPNs,hsPNTs,hsDataConstrs,hsTypeConstrsAndClasses, hsTypeVbls
,hsClassMembers, HsDecls(hsDecls,isDeclaredIn, replaceDecls)
,hsFreeAndDeclaredPNs,hsFreeAndDeclaredNames
,hsVisiblePNs, hsVisibleNames
,hsFDsFromInside, hsFDNamesFromInside
-- ** Property checking
,isVarId,isConId,isOperator,isTopLevelPN,isLocalPN,isTopLevelPNT
,isQualifiedPN,isFunPNT, isFunName, isPatName, isFunOrPatName,isTypeCon,isTypeSig,isFunBind,isPatBind,isSimplePatBind
,isComplexPatBind,isFunOrPatBind,isClassDecl,isInstDecl,isDirectRecursiveDef
,usedWithoutQual,canBeQualified, hasFreeVars,isUsedInRhs
,findPNT,findPN -- Try to remove this.
,findPNs, findEntity
,sameOccurrence
,defines,definesTypeSig, isTypeSigOf
,HasModName(hasModName), HasNameSpace(hasNameSpace)
-- ** Modules and files
,clientModsAndFiles,serverModsAndFiles,isAnExistingMod
,fileNameToModName, strToModName, modNameToStr
-- ** Locations
,defineLoc, useLoc,locToPNT,locToPN,locToExp, getStartEndLoc
-- * Program transformation
-- ** Adding
,addDecl ,addItemsToImport, addHiding, rmItemsFromImport, addItemsToExport
,addParamsToDecls, addGuardsToRhs, addImportDecl, duplicateDecl, moveDecl
-- ** Rmoving
,rmDecl, rmTypeSig, commentOutTypeSig, rmParams
,rmItemsFromExport, rmSubEntsFromExport, Delete(delete)
-- ** Updating
,Update(update)
,qualifyPName,rmQualifier,renamePN,replaceNameInPN,autoRenameLocalVar
-- * Miscellous
-- ** Parsing, writing and showing
,parseSourceFile,writeRefactoredFiles, showEntities ,showPNwithLoc, newProj, addFile, chase
-- ** Locations
,toRelativeLocs, rmLocs
-- ** Default values
,defaultPN,defaultPNT,defaultModName,defaultExp,defaultPat, defaultExpUnTyped
-- ** Identifiers, expressions, patterns and declarations
,pNTtoPN,pNTtoName,pNtoName,nameToPNT, nameToPN,pNtoPNT
,expToPNT, expToPN, nameToExp,pNtoExp,patToPNT, patToPN, nameToPat,pNtoPat
,definingDecls, definedPNs
,simplifyDecl
-- ** Others
,mkNewName, applyRefac, applyRefacToClientMods
-- The following functions are not in the the API yet.
,getDeclToks, causeNameClashInExports, inRegion , ghead, glast, gfromJust, unmodified, prettyprint,
getDeclAndToks
-- * Typed AST traversals (added by CMB)
-- * Miscellous
,removeFromInts, getDataName, checkTypes, getPNs, getPN, getPNPats, mapASTOverTAST
)
where
import Prelude hiding (putStr,putStrLn,writeFile,readFile)
import Data.Maybe
import Data.List hiding (delete)
import Data.Char
--------------------------------
import PfeChase
import PFE0
import PFE2
import PFE3(parseModule,parseModule', parseSourceFile')
import PFE4
import PosSyntax hiding (ModuleName, HsName, SN)
import SourceNames
import ScopeModule
import UniqueNames hiding (srcLoc)
import HsName
import HsLexerPass1
import AbstractIO
import PNT
import TiPNT
import SimpleGraphs(reverseGraph,reachable)
import Ents hiding (isValue)
import Relations
import QualNames
import TypedIds hiding (NameSpace, HasNameSpace)
import WorkModule
import TiDecorate
import TI hiding (TI)
import Pfe4Cmds
import PrettyPrint
import Unlit(readHaskellFile,writeHaskellFile)
import MUtils hiding (swap)
import EditorCommands(sendEditorModified)
import qualified MT(lift)
import HsTokens
-------------------------
import RefacTITypeSyn
import RefacTypeLocUtils
-------------------------
import StrategyLib hiding (findFile)
#if __GLASGOW_HASKELL__ <604
instance (Monoid a, Monoid b) => Monoid (a,b) where
mappend (a,b) (a',b') = (mappend a a', mappend b b')
mempty = (mempty, mempty)
#endif
------------------------------------------------------------------------------------------
{- | The Delete class. -}
class (Term t, Term t1)=>Delete t t1 where
-- | Delete the occurrence of a syntax phrase in a given context.
delete::(MonadPlus m, MonadState (([PosToken],Bool),t2) m)=> t -- ^ The syntax phrase to delete.
->t1 -- ^ The contex where the syntax phrase occurs.
->m t1 -- ^ The result.
-- An expression can only be deleted in certain circumstances.
instance (Term t) => Delete HsExpP t where
delete e t
= applyTP (once_tdTP (failTP `adhocTP` inExp)`choiceTP` failure) t
where
{- inExp ((Exp (HsApp e1 e2))::HsExpP)
| sameOccurrence e e1
= do deleteFromToks e1
return e2 -}
inExp (TiDecorate.Exp (HsApp e1 e2)::HsExpP)
| sameOccurrence e e2
= do deleteFromToks e2 getStartEndLoc
return e1
inExp (TiDecorate.Exp (HsList es))
|isJust $ find (\x->sameOccurrence e x) es
= do ((toks,_),others)<-get
let toks'=deleteEnt toks $ getStartEndLoc toks e
put ((toks',modified),others)
return (TiDecorate.Exp (HsList (es \\[e])))
inExp _ = mzero
sameOccurrence t1 t2
= rmParen t1== rmParen t2 && srcLocs t1 == srcLocs t2
rmParen (TiDecorate.Exp (HsParen e)) = rmParen e
rmParen e = e
failure = error "Delete: This expression can not be deleted!"
instance (Term t) => Delete HsPatP t where
delete p t
= applyTP (once_tdTP (failTP `adhocTP` inPats)) t
where
inPats (ps::[HsPatP])
|isJust $ find(\x->sameOccurrence p x) ps
= do deleteFromToks p getStartEndLoc
return (ps\\[p])
inPats _ = mzero
instance (Term t) => Delete HsImportDeclP t where
delete imp t
= applyTP (once_tdTP (failTP `adhocTP` inImps)) t
where
inImps (imps::[HsImportDeclP])
| isJust $ find (\x->sameOccurrence imp x) imps
= do deleteFromToks imp startEndLocIncFowNewLn
return (imps \\ [imp])
inImps _ = mzero
{- | The Update class, -}
class (Term t, Term t1)=>Update t t1 where
-- | Update the occurrence of one syntax phrase in a given scope by another syntax phrase of the same type.
update::(MonadPlus m, MonadState (([PosToken],Bool),(Int,Int)) m)=> t -- ^ The syntax phrase to be updated.
-> t -- ^ The new syntax phrase.
-> t1 -- ^ The contex where the old syntex phrase occurs.
-> m t1 -- ^ The result.
instance (Term t) =>Update HsExpP t where
update oldExp newExp t
= applyTP (once_tdTP (failTP `adhocTP` inExp)) t
where
inExp (e::HsExpP)
| e == oldExp && srcLocs e == srcLocs oldExp
= do (newExp', _) <-updateToks oldExp newExp prettyprint
return newExp'
inExp e = mzero
instance (Term t) =>Update PNT t where
update oldExp newExp t
= applyTP (once_tdTP (failTP `adhocTP` inExp)) t
where
inExp (e::PNT)
| e == oldExp && srcLocs e == srcLocs oldExp
= do (newExp',_) <- updateToks oldExp newExp prettyprint
return newExp'
inExp e = mzero
instance (Term t) =>Update HsMatchP t where
update oldExp newExp t
= applyTP (once_tdTP (failTP `adhocTP` inExp)) t
where
inExp (e::HsMatchP)
| e == oldExp && srcLocs e == srcLocs oldExp
= do (newExp',_) <- updateToks oldExp newExp prettyprint
return newExp'
inExp e = mzero
instance (Term t) =>Update HsPatP t where
update oldPat newPat t
= applyTP (once_tdTP (failTP `adhocTP` inPat)) t
where
inPat (p::HsPatP)
| p == oldPat && srcLocs p == srcLocs oldPat
= do (newPat', _) <- updateToks [oldPat] [newPat] (prettyprintPatList False)
return $ ghead "update" newPat'
inPat e = mzero
instance (Term t) =>Update [HsPatP] t where
update oldPat newPat t
= applyTP (once_tdTP (failTP `adhocTP` inPat)) t
where
inPat (p::[HsPatP])
| sameOccurrence p oldPat
= do (newPat', _) <- updateToks oldPat newPat (prettyprintPatList False)
return newPat'
inPat e = mzero
instance (Term t) =>Update HsDeclsP t where
update oldDecl@(Decs x y) newDecl@(Decs x2 y2) t
= applyTP (once_tdTP (failTP `adhocTP` inDecl)) t
where
inDecl (d::HsDeclsP)
| sameOccurrence d oldDecl
= do
(newDecl', _) <- updateToks oldDecl newDecl prettyprint
return newDecl'
inDecl e = mzero
instance (Term t) =>Update [HsDeclP] t where
update oldDecl newDecl t
= applyTP (once_tdTP (failTP `adhocTP` inDecl)) t
where
inDecl (d::[HsDeclP])
| sameOccurrence d oldDecl
= do
(newDecl',_) <- updateToks oldDecl newDecl prettyprint
return newDecl'
inDecl e = mzero
instance (Term t) =>Update HsDeclP t where
update oldDecl newDecl t
= applyTP (once_tdTP (failTP `adhocTP` inDecl)) t
where
inDecl (d::HsDeclP)
| sameOccurrence d oldDecl
= do (newDecl',_) <- updateToks oldDecl newDecl prettyprint
return newDecl'
inDecl e = mzero
instance (Term t) =>Update HsImportDeclP t where
update oldImpDecl newImpDecl t
= applyTP (once_tdTP (failTP `adhocTP` inDecl)) t
where
inDecl (d::HsImportDeclP)
| sameOccurrence d oldImpDecl
=do (newImpDecl', _) <-updateToks oldImpDecl newImpDecl prettyprint
return newImpDecl'
inDecl e = mzero
instance (Term t) => Update HsExportEntP t where
update oldEnt@(EntE s) newEnt@(EntE s1) t
= applyTP (once_tdTP (failTP `adhocTP` inEnt)) t
where
inEnt (e::HsExportEntP)
| sameOccurrence e oldEnt
= do (s1',_) <- updateToks s s1 prettyprint
return (EntE s1')
inEnt e = mzero
instance (Term t) => Update HsTypeP t where
update oldType newType t
= applyTP (once_tdTP (failTP `adhocTP` inType)) t
where
inType (t::HsTypeP)
| sameOccurrence t oldType
= do (newType', _) <- updateToks oldType newType prettyprint
return newType'
inType t = mzero
{-
{- | The Swap Class. The instances may be not complete, tell us what you need so that we can add it.-}
class (Term t, Term t1 ) => Swap t t1 where
-- | Swap the occurrences of two syntax phrases( of the same type) in a given scope.
swap :: (MonadState (([PosToken],Bool),t2) m)=> t -- ^ The first syntax phrase.
-> t -- ^ The second syntax phrase.
->t1 -- ^ The context where the two syntax phrases occur.
->m t1 -- ^ The result.
instance (Term t)=>Swap HsExpP t where
swap e1 e2 t
= do swapInToks e1 e2
applyTP (full_tdTP (idTP `adhocTP` inExp)) t -- both full_td and full_bu should wor
where
inExp (e ::HsExpP)
| sameOccurrence e e1
= return e2
inExp (e::HsExpP)
| e == e2 && srcLocs e == srcLocs e2
= return e1
inExp x = return x
instance (Term t) => Swap HsPatP t where
swap p1 p2 t
= do swapInToks p1 p2
applyTP (full_tdTP (idTP `adhocTP` inPat)) t
where
inPat (p::HsPatP)
| sameOccurrence p p1
= return p2
inPat (p::HsPatP)
| sameOccurrence p p2
= return p1
inPat x = return x
instance (Term t) => Swap HsTypeP t where
swap t1 t2 t
= do swapInToks t1 t2
applyTP (full_tdTP (idTP `adhocTP` inType)) t
where
inType (t::HsTypeP)
| sameOccurrence t t1
= return t2
inType (t::HsTypeP)
| sameOccurrence t t2
= return t1
inType t = return t
-}
class (DeclStartLoc t) =>CanHaveWhereClause t where
canHaveWhereClause:: t-> Bool
instance CanHaveWhereClause HsMatchP where
canHaveWhereClause t = True
instance CanHaveWhereClause HsDeclP where
canHaveWhereClause t = isPatBind t
instance CanHaveWhereClause HsAltP where
canHaveWhereClause t = True
{-
instance CanHaveWhereClause HsModuleP where
canHaveWhereClause t = True
-}
instance CanHaveWhereClause HsExpP where
canHaveWhereClause t = False
instance CanHaveWhereClause HsStmtP where
canHaveWhereClause t = False
class (StartEndLoc t) =>DeclStartLoc t where
-- | Given a syntax phrase, get the start location of enclosed top-level declaration list.
declStartLoc:: [PosToken]->t->Maybe RefacTITypeSyn.SimpPos
instance DeclStartLoc HsMatchP where
declStartLoc toks (HsMatch loc1 name pats rhs ds@(Decs x y))
= if x/=[] then Just $ fst (getStartEndLoc toks (ghead "declStartLoc" x))
else Nothing
instance DeclStartLoc HsDeclP where
declStartLoc toks (TiDecorate.Dec (HsPatBind loc p rhs ds@(Decs x y)))
= if x/=[] then Just$ (fst (getStartEndLoc toks (ghead "declStartLoc" x)))
else Nothing
declStartLoc toks _ = Nothing
instance DeclStartLoc HsExpP where
declStartLoc toks letExp@(TiDecorate.Exp (HsLet ds@(Decs x y) e))
= if x/=[] then Just $ fst (getStartEndLoc toks (ghead "declStartLoc" x))
else let (startPos,endPos)=getStartEndLoc toks letExp
expToks= getToks (startPos,endPos) toks
in Just $ ((tokenPos.(ghead "declStartLoc")) $ dropWhile (not.isIn) expToks)
instance DeclStartLoc HsAltP where
declStartLoc toks (HsAlt loc p rhs ds@(Decs x y))
=if x/=[] then Just $ (fst (getStartEndLoc toks (ghead "declStartLoc" x)))
else Nothing
instance DeclStartLoc HsStmtP where
declStartLoc toks (HsLetStmt ds@(Decs x y) stmts)
= if x/=[] then Just $ fst (getStartEndLoc toks (ghead "declStartLoc" x))
else Just $ fst (getStartEndLoc toks stmts) -- Qn: Is this possible?
-- | Return True if syntax phrases t1 and t2 refer to the same one.
sameOccurrence:: (Term t, Eq t) => t -> t -> Bool
sameOccurrence t1 t2
= t1==t2 && srcLocs t1 == srcLocs t2
{- | The 'HasNameSpace' class. -}
class HasNameSpace t where
hasNameSpace::t->NameSpace
instance HasNameSpace PNT where
hasNameSpace (PNT _ Value _) = ValueName
hasNameSpace (PNT _ (ConstrOf _ _ ) _) = DataCon
hasNameSpace (PNT _ (FieldOf _ _ ) _) = ValueName
hasNameSpace (PNT _ (MethodOf _ _ _) _) = ValueName
hasNameSpace (PNT _ (TypedIds.Class _ _) _) = ClassName
hasNameSpace (PNT _ (Type _) _ ) = TypeCon -- It is also possible that it is a type variable.
hasNameSpace _ = Other -- We don't care about Assertion & Property so far.
instance HasNameSpace ENT where
hasNameSpace (Ent _ _ Value) = ValueName
hasNameSpace (Ent _ _ (ConstrOf _ _ )) = DataCon
hasNameSpace (Ent _ _ (FieldOf _ _ )) = ValueName
hasNameSpace (Ent _ _ (MethodOf _ _ _)) = ValueName
hasNameSpace (Ent _ _ (TypedIds.Class _ _)) = ClassName
hasNameSpace (Ent _ _ (Type _)) = TypeCon
hasNameSpace _ = Other
----------------------------------------------------------------------------------------------
-- |Compose ModuleName from String.
strToModName::String->ModuleName
strToModName name = if name =="Main" then MainModule "Main.hs" -- THIS IS BASED ON ASSUMPTION.
else PlainModule name
-- |From ModuleName to string.
modNameToStr::ModuleName->String
modNameToStr (PlainModule name) = name
modNameToStr (MainModule _) = "Main"
-- | From file name to module name.
--fileNameToModName::( )=>String->PFE0MT n i ds ext m ModuleName
fileNameToModName::(PFE0_IO err m,IOErr err,HasInfixDecls i ds,QualNames i m1 n, Read n,Show n)=>
String->PFE0MT n i ds ext m ModuleName
fileNameToModName fileName =
do gf <- getCurrentModuleGraph
let fileAndMods = [(m,f)|(f,(m,ms))<-gf]
f = filter (\(m,f) -> f==fileName) fileAndMods
if f ==[] then error $ "Can't find module name"
else return $ (fst.head) f
-- | Return the client module and file names. The client modules of module, say m, are those modules
-- which import m directly or indirectly.
-- clientModsAndFiles::( ) =>ModuleName->PFE0MT n i ds ext m [(ModuleName, String)]
clientModsAndFiles::(PFE0_IO err m,IOErr err,HasInfixDecls i ds,QualNames i m1 n, Read n,Show n)=>
ModuleName->PFE0MT n i ds ext m [(ModuleName, String)]
clientModsAndFiles m =
do gf <- getCurrentModuleGraph
let fileAndMods = [(m,f)|(f,(m,ms))<-gf]
g = (reverseGraph.(map snd)) gf
clientMods = reachable g [m] \\ [m]
clients = concatMap (\m'->[(m,f)|(m,f)<-fileAndMods, m==m']) clientMods
return clients
-- | Return the server module and file names. The server modules of module, say m, are those modules
-- which are directly or indirectly imported by module m.
--serverModsAndFiles::( )=>ModuleName->PFE0MT n i ds ext m [(ModuleName, String)]
serverModsAndFiles::(PFE0_IO err m,IOErr err,HasInfixDecls i ds,QualNames i m1 n, Read n,Show n)=>
ModuleName->PFE0MT n i ds ext m [(ModuleName, String)]
serverModsAndFiles m =
do gf <- getCurrentModuleGraph
let fileAndMods = [(m,f)|(f,(m,ms))<-gf]
g = (map snd) gf
serverMods = reachable g [m] \\ [m]
servers = concatMap (\m'->[(m,f)|(m,f)<-fileAndMods, m==m']) serverMods
return servers
-- | Return True if the given module name exists in the project.
--isAnExistingMod::( ) =>ModuleName->PFE0MT n i ds ext m Bool
isAnExistingMod::(PFE0_IO err m,IOErr err,HasInfixDecls i ds,QualNames i m1 n, Read n,Show n)=>
ModuleName->PFE0MT n i ds ext m Bool
isAnExistingMod m
= do ms<-allModules
return (elem m ms)
{-Whenever an identifier is imported, the qualified name is imported, whereas the unqualified name
may or may not be imported. -}
-- | Return all the possible qualifiers for the identifier. The identifier is not inscope if the
-- result is an empty list.
hsQualifier::PNT -- ^ The identifier.
->InScopes -- ^ The in-scope relation.
->[ModuleName] -- ^ The result.
hsQualifier pnt@(PNT pname _ _ ) inScopeRel
= let r = filter ( \ ( name, nameSpace, modName, qual) -> pNtoName pname == name
&& hasModName pname == Just modName && hasNameSpace pnt == nameSpace
&& isJust qual) $ inScopeInfo inScopeRel
in map (\ (_,_,_,qual) -> fromJust qual ) r
-- |Process the inscope relation returned from the parsing and module analysis pass, and
-- return a list of four-element tuples. Each tuple contains an identifier name, the identifier's namespace
-- info, the identifier's defining module name and its qualifier name. The same identifier may have multiple
-- entries in the result because it may have different qualifiers. This makes it easier to decide whether the
-- identifier can be used unqualifiedly by just checking whether there is an entry for it with the qualifier field
-- being Nothing.
--
inScopeInfo::InScopes -- ^ The inscope relation .
->[(String, NameSpace, ModuleName, Maybe ModuleName)] -- ^ The result
inScopeInfo inScopeRel =nub $ map getEntInfo $ relToList inScopeRel
where
getEntInfo (qual, ent@(Ent modName ident _))
=(identToName ident, hasNameSpace ent, modName, getQualifier qual)
-- | Process the export relation returned from the parsing and module analysis pass, and
-- return a list of trhee-element tuples. Each tuple contains an identifier name, the
-- identifier's namespace info, and the identifier's define module.
exportInfo::Exports -- ^ The export relation.
-> [(String, NameSpace, ModuleName)] -- ^ The result
exportInfo exports = nub $ map getEntInfo exports
where
getEntInfo (_, ent@(Ent modName ident _))
=(identToName ident, hasNameSpace ent, modName)
-- | Return True if the identifier is inscope and can be used without a qualifier.
isInScopeAndUnqualified::String -- ^ The identifier name.
->InScopes -- ^ The inscope relation
->Bool -- ^ The result.
isInScopeAndUnqualified id inScopeRel
= isJust $ find (\ (x, _,_, qual) -> x == id && isNothing qual ) $ inScopeInfo inScopeRel
--Id is defined in two modules: HsNames.hs (type Id = String) and PosName.hs (type Id = SN HsNames.Id)
identToName (HsVar (SN i _)) = i
identToName (HsCon (SN i _)) = i
-- | Return True if the current module is exported either by default or by specifying the module name in the export.
modIsExported::HsModuleP -- ^ The AST of the module
->Bool -- ^ The result
modIsExported mod
= let exps = hsModExports mod
modName = hsModName mod
in if isNothing exps
then True
else isJust $ find (==(ModuleE modName)) (fromJust exps)
-- | Return True if the identifier is exported either implicitly or explicitly.
isExported::PNT -- ^ The identifier.
->Exports -- ^ The export relation.
->Bool -- ^ The result.
isExported pnt@(PNT pn t1 _) exps
= if isTopLevelPNT pnt
then case hasModName pn of
Just modName -> isJust (find (\(name, nameSpace, modName1) -> name == pNtoName pn
&& modName == modName1 && hasNameSpace pnt == nameSpace) $ exportInfo exps)
Nothing -> False
else False
-- | Return True if an identifier is explicitly exported by the module.
isExplicitlyExported::PName -- ^ The identifier
->HsModuleP -- ^ The AST of the module
->Bool -- ^ The result
isExplicitlyExported pn mod
= findEntity pn $ hsModExports mod
{-
causeNameClashInExports::String -- ^ The identifier name
->HsModuleP -- ^ The AST of the module
->Exports -- ^ The export relation of the module
->Bool -- ^ The result -}
-- Note that in the abstract representation of exps, there is no qualified entities.
causeNameClashInExports pn newName mod exps
= let modNames=nub (concatMap (\(x, Ent modName _ _)->if show x==show newName
then [modName]
else []) exps)
in (isExplicitlyExported pn mod) &&
( any (modIsUnQualifedImported mod) modNames
|| elem (let (SN modName1 _) =hsModName mod
in modName1) modNames)
where
modIsUnQualifedImported mod modName
=let imps =hsModImports mod
in isJust $ find (\(HsImportDecl _ (SN modName1 _) qualify _ h)->modName==modName1 && (not qualify)) imps
-------------------------------------------------------------------------------------------------
{-append an import declaration to the end of the import list in the module, this functions
modifies both the token stream and the AST
-}
-------------------------------------------------------------------------------------
addImportDecl mod@(HsModule _ _ _ imp decls) moduleName qualify alias hide idNames
= do ((toks, _),(v,v1)) <- get
let (toks1, toks2)
=if imps' /= []
then let (startLoc, endLoc) = startEndLocIncComments toks (last imps')
(toks1, toks2)= break (\t->tokenPos t==endLoc) toks
in (toks1 ++ [ghead "addImportDecl1" toks2], tail toks2)
else if decls /=[]
then let startLoc = fst $ startEndLocIncComments toks (ghead "addImportDecl1" decls)
(toks1, toks2) = break (\t ->tokenPos t==startLoc) toks
in (toks1, toks2)
else (toks,[])
before = if toks1/=[] && endsWithNewLn (glast "addImportDecl1" toks1) then "" else "\n"
after = if (toks2 /=[] && startsWithNewLn (ghead "addImportDecl1" toks2)) then "" else "\n"
colOffset = if imps'==[] && decls==[]
then 1
else getOffset toks
$ if imps'/=[] then fst $ startEndLoc toks (ghead "addImportDecl1" imps')
else fst $ startEndLoc toks (ghead "addImportDecl1" decls)
impToks =tokenise (Pos 0 v1 1) (colOffset-1) True
$ before++(render.ppi) impDecl++"\n" ++ after --- refactorer this
(impDecl', _) <- addLocInfo (impDecl,impToks)
let toks' = toks1++impToks++toks2
put ((toks',modified), ((tokenRow (glast "addImportDecl1" impToks) - 10,v1))) -- 10: step ; generalise this.
return (mod {hsModImports = imp ++ [impDecl']})
where
alias' = case alias of
Just m -> Just $ SN (PlainModule m) loc0
_ -> Nothing
impDecl = HsImportDecl loc0 (SN (PlainModule moduleName) loc0) qualify alias'
(if idNames==[] && hide==False
then Nothing
else (Just (hide, map nameToEnt idNames))) -- what about "Main"
imps' = imp \\ prelimps
nameToEnt name = Var (nameToPNT name)
---------------------------------------------------------------------------------------
-- | Adding a declaration to the declaration list of the given syntax phrase(so far only adding function\/pattern binding
-- has been tested). If the second argument is Nothing, then the declaration will be added to the beginning of the
-- declaration list, but after the data type declarations is there is any.
{-addDecl::( ) =>t -- ^ The AST.
-> Maybe PName -- ^ If this is Just, then the declaration will be added right after this identifier's definition.
->([HsDeclP], Maybe [PosToken]) -- ^ The declaration to be added, in both AST and Token stream format (optional).
->Bool -- ^ True means the declaration is a toplevel declaration.
->m t
-}
addDecl::((MonadState (([PosToken],Bool),(Int,Int)) m), StartEndLoc t, HsDecls t, Printable t)
=>t-> Maybe PName
->([HsDeclP], Maybe [PosToken])
->Bool
->m t
addDecl parent pn (decl, declToks) topLevel
= if isJust pn
then appendDecl parent (fromJust pn) (decl, declToks)
else if topLevel
then addTopLevelDecl (decl, declToks) parent
else addLocalDecl parent (decl,declToks)
where
{- Add a definition to the beginning of the definition declaration list, but after the data type declarations
if there is any. The definition will be pretty-printed if its token stream is not provided. -}
addTopLevelDecl (decl, declToks) parent
= do let decls = hsDecls parent
(decls1,decls2)=break (\x->isFunOrPatBind x || isTypeSig x) decls
((toks,_),(v1, v2))<-get
let loc1 = if decls2/=[] -- there are function/pattern binding decls.
then let ((startRow,_),_) = startEndLocIncComments toks (ghead "addTopLevelDecl" decls2)
in (startRow, 1)
else simpPos0 -- no function/pattern binding decls in the module.
(toks1, toks2) = if loc1==simpPos0 then (toks, [])
else break (\t->tokenPos t==loc1) toks
declStr = case declToks of
Just ts -> concatMap tokenCon ts
Nothing -> prettyprint decl++"\n\n"
colOffset = if decls ==[] then 1 else getOffset toks $ fst (getStartEndLoc toks (head decls))
newToks = tokenise (Pos 0 v1 1) colOffset True declStr
toks' = toks1 ++ newToks ++ toks2
-- error $ show decl
put ((toks',modified),((tokenRow (glast "addTopLevelDecl" newToks) -10), v2))
(decl',_) <- addLocInfo (decl, newToks)
-- error $ show decl
return (replaceDecls parent (Decs (decls1++decl'++decls2) ([], [])))
appendDecl parent pn (decl, declToks)
= do ((toks,_),(v1, v2))<-get
-- error (show parent ++ "----" ++ show pn ++ "-----" ++ show (decl, declToks))
let (startPos,endPos) = startEndLocIncFowComment toks (ghead "appendDecl1" after)
-- divide the toks into three parts.
(toks1, toks2, toks3) = splitToks' (startPos, endPos) toks
--get the toks defining pn
defToks = dropWhile (\t->tokenPos t /=startPos) toks2
offset = getOffset toks $ fst (getStartEndLoc toks (ghead "appendDecl2" decls))
declStr = case declToks of
Just ts -> concatMap tokenCon ts
Nothing -> prettyprint decl
newToks = tokenise (Pos 0 v1 1) offset True declStr
toks' = if endsWithNewLn (glast "appendDecl2" toks2)
then toks1++ toks2 ++ (newLnToken: newToks) ++ [newLnToken]++ compressPreNewLns toks3
else replaceToks toks startPos endPos (defToks++[newLnToken,newLnToken]++newToks)
-- (decl',_) <- addLocInfo (decl, newToks)
put ((toks',modified),((tokenRow (glast "appendDecl2" newToks) -10), v2))
return (replaceDecls parent (Decs (before ++ [ghead "appendDecl14" after]++ decl++ tail after) ([], [])))
where
decls = hsDecls parent
(before,after) = break (defines pn) decls -- Need to handle the case that 'after' is empty?
splitToks' (startPos, endPos) toks
= let (ts1, ts2, ts3) = splitToks ( startPos, endPos) toks
(ts11, ts12) = break hasNewLn (reverse ts1)
in (reverse ts12, reverse ts11++ts2, ts3)
-- This function need to be tested.
addLocalDecl parent (newFun, newFunToks)
=do
((toks,_), (v1, v2))<-get
let (startPos@(_,startCol),endPos'@(endRow',_)) --endPos' does not include the following newline or comment.
=if localDecls==[] then startEndLocIncFowComment toks parent --The 'where' clause is empty
else startEndLocIncFowComment toks localDecls
toks1=gtail "addLocalDecl1" $ dropWhile (\t->tokenPos t/=endPos') toks
ts1=takeWhile (\t->isWhite t && ((not.isMultiLineComment) t) && (not.hasNewLn) t) toks1
--nextTokPos is only used to test whether there is a 'In' or a nested comment.
nextTokPos= case (dropWhile (\t->isWhite t && ((not.isMultiLineComment) t) && (not.hasNewLn) t) toks1) of
[] -> simpPos0
l -> (tokenPos.ghead "addLocalFunInToks") l
needNewLn=if nextTokPos==simpPos0 --used to decide whether add a new line character before a introduced fun.
then if toks1==[] then True
else (not.endsWithNewLn) (last ts1)
else endRow'==fst nextTokPos
--endPos@(endRow,_)=if ts1==[] then endPos'
-- else tokenPos (last ts1)
offset = if localDecls == [] then getOffset toks startPos + 4 else getOffset toks startPos
newToks = tokenise (Pos 0 v1 1) offset True
$ if needNewLn then "\n"++newSource else newSource++"\n"
oldToks'=getToks (startPos,endPos') toks
toks'=replaceToks toks startPos endPos' (oldToks'++newToks)
(newFun',_) <- addLocInfo (newFun, newToks) -- This function calles problems because of the lexer.
put ((toks',modified),((tokenRow (glast "appendDecl2" newToks) -10), v2))
return (replaceDecls parent (Decs (hsDecls parent ++ newFun') ([], [])))
where
localDecls = hsDecls parent
newSource = if localDecls == []
then "where\n"++ concatMap (\l-> " "++l++"\n") (lines newFun')
else newFun'
where
newFun' = case newFunToks of
Just ts -> concatMap tokenCon ts
Nothing -> prettyprint newFun
-- | Remove the type signature that defines the given identifier's type from the declaration list.
{-rmTypeSig::(MonadState (([PosToken],Bool),t1) m)
=> PName -- ^ The identifier whose type signature is to be removed.
->[HsDeclP] -- ^ The declaration list
->m [HsDeclP] -- ^ The result -}
rmTypeSig pn t = applyTP (full_tdTP (idTP `adhocTP` inDecls)) t
where
inDecls (decls::[HsDeclP])
| snd (break (definesTypeSig pn) decls) /=[]
= do ((toks,_), others) <- get
let (decls1,decls2)= break (definesTypeSig pn) decls
(toks',decls')=
let sig@(TiDecorate.Dec (HsTypeSig loc is c tp))=ghead "rmTypeSig" decls2 -- as decls2/=[], no problem with head
(startPos,endPos)=getStartEndLoc toks sig
in if length is>1
then let newSig=(TiDecorate.Dec (HsTypeSig loc (filter (\x-> (pNTtoPN x)/=pn) is) c tp))
pnt = ghead "rmTypeSig" (filter (\x-> pNTtoPN x == pn) is)
(startPos1, endPos1) = let (startPos1', endPos1') = getStartEndLoc toks pnt
in if fromJust (elemIndex pnt is) >0
then extendForwards toks startPos1' endPos1' isComma
else extendBackwards toks startPos1' endPos1' isComma
in (deleteToks toks startPos1 endPos1,(decls1++[newSig]++tail decls2))
else ((deleteToks toks startPos endPos),(decls1++tail decls2))
put ((toks',modified),others)
return decls'
inDecls x = return x
-- |Comment out the type signature that defines pn's type in the token stream and remove it from the AST.
commentOutTypeSig::(MonadState (([PosToken],Bool),t1) m)
=> PName -- ^ The identifier.
->[HsDeclP] -- ^ The deckaration list.
->m [HsDeclP] -- ^ The result.
commentOutTypeSig pn decls
=let (decls1,decls2)=break (definesTypeSig pn) decls
in if decls2/=[] then --There is a type signature for pn
do ((toks,_),others)<-get
let (toks',decls')=
let sig@(TiDecorate.Dec (HsTypeSig loc is c tp))=ghead "rmTypeSig" decls2 -- as decls2/=[], no problem with head
in if length is>1 --This type signature also defines the type of variables other than pn
then let newSig=(TiDecorate.Dec (HsTypeSig loc (filter (\x-> (pNTtoPN x)/=pn) is) c tp))
pnt = ghead "commentTypeSig" $ filter (\x->pNTtoPN x==pn) is
(startPos,endPos) = getStartEndLoc toks pnt
in ((commentToks (startPos, endPos) toks),(decls1++[newSig]++tail decls2))
else let (startPos,endPos)=getStartEndLoc toks sig
in ((commentToks (startPos, endPos) toks),(decls1++tail decls2))
put ((toks',modified),others)
return decls'
else return decls
-- | Remove the declaration (and the type signature is the second parameter is True) that defines the given identifier
-- from the declaration list.
{-
rmDecl::(MonadState (([PosToken],Bool),t1) m)
=>PName -- ^ The identifier whose definition is to be removed.
->Bool -- ^ True means including the type signature.
->[HsDeclP] -- ^ The declaration list.
-> m [HsDeclP]-- ^ The result.
-}
rmDecl pn incSig t = applyTP (once_tdTP (failTP `adhocTP` inDecls)) t
where
inDecls (decls::[HsDeclP])
| snd (break (defines pn) decls) /=[]
= do let (decls1, decls2) = break (defines pn) decls
decl = ghead "rmDecl" decls2
-- error $ (render.ppi) t -- ecl ++ (show decl)
case isTopLevelPN pn of
True -> if incSig then rmTopLevelDecl decl =<< rmTypeSig pn decls
else rmTopLevelDecl decl decls
False -> if incSig then rmLocalDecl decl =<< rmTypeSig pn decls
else rmLocalDecl decl decls
inDecls x = mzero
rmTopLevelDecl decl decls
=do ((toks,_),others)<-get
let (startLoc, endLoc)=startEndLocIncComments toks decl
toks'=deleteToks toks startLoc endLoc
put ((toks',modified),others)
return (decls \\ [decl])
{- The difference between removing a top level declaration and a local declaration is:
if the local declaration to be removed is the only declaration in current declaration list,
then the 'where'/ 'let'/'in' enclosing this declaration should also be removed.
Whereas, when a only top level decl is removed, the 'where' can not be removed.
-}
-- |Remove a location declaration that defines pn.
rmLocalDecl decl decls
=do ((toks,_),others)<-get
let (startPos,endPos)=getStartEndLoc toks decl --startEndLoc toks decl
(startPos',endPos')=startEndLocIncComments toks decl
--(startPos',endPos')=startEndLocIncFowComment toks decl
toks'=if length decls==1 --only one decl, which means the accompaning 'where',
--'let' or'in' should be removed too.
then let (toks1,toks2)=break (\t->tokenPos t==startPos) toks --devide the token stream.
--get the 'where' or 'let' token
rvToks1=dropWhile (not.isWhereOrLet) (reverse toks1)
--There must be a 'where' or 'let', so rvToks1 can not be empty.
whereOrLet=ghead "rmLocalFunPatBind:whereOrLet" rvToks1
--drop the 'where' 'or 'let' token
toks1'=takeWhile (\t->tokenPos t/=tokenPos whereOrLet) toks1
--remove the declaration from the token stream.
toks2'=gtail "rmLocalDecl" $ dropWhile (\t->tokenPos t/=endPos') toks2
--get the remained tokens after the removed declaration.
remainedToks=dropWhile isWhite toks2'
in if remainedToks==[]
then --the removed declaration is the last decl in the file.
(compressEndNewLns toks1'++ compressPreNewLns toks2')
else if --remainedToks/=[], so no problem with head.
isIn (ghead "rmLocalDecl:isIn" remainedToks)
|| isComma (ghead "rmLocalDecl:isComma" remainedToks)
--There is a 'In' after the removed declaration.
then if isWhere whereOrLet
then deleteToks toks (tokenPos whereOrLet) endPos'
else deleteToks toks (tokenPos whereOrLet)
$ tokenPos (ghead "rmLocalDecl:tokenPos" remainedToks)
--delete the decl and adjust the layout
else if isCloseSquareBracket (ghead "rmLocalDecl:isCloseSquareBracker" remainedToks) &&
(isBar.(ghead "rmLocalDecl:isBar")) (dropWhile isWhite (tail rvToks1))
then deleteToks toks (tokenPos((ghead "rmLocalDecl")
(dropWhile isWhite (tail rvToks1)))) endPos'
else deleteToks toks (tokenPos whereOrLet) endPos'
--there are more than one decls
else deleteToks toks startPos' endPos'
put ((toks',modified),others) --Change the above endPos' to endPos will not delete the following comments.
return $ (decls \\ [decl])
{- ********* IMPORTANT : THIS FUNCTION SHOULD BE UPDATED TO THE NEW TOKEN STREAM METHOD ****** -}
-- | Duplicate a functon\/pattern binding declaration under a new name right after the original one.
duplicateDecl::(MonadState (([PosToken],Bool),t1) m)
=>[HsDeclP] -- ^ The declaration list
->PName -- ^ The identifier whose definition is going to be duplicated
->String -- ^ The new name
->m [HsDeclP] -- ^ The result
{-there maybe fun/simple pattern binding and type signature in the duplicated decls
function binding, and type signature are handled differently here: the comment and layout
in function binding are preserved.The type signature is output ted by pretty printer, so
the comments and layout are NOT preserved.
-}
duplicateDecl decls pn newFunName
= do ((toks,_), others)<-get
let (startPos, endPos) =startEndLocIncComments toks funBinding
{-take those tokens before (and include) the function binding and its following
white tokens before the 'new line' token. (some times the function may be followed by
comments) -}
toks1 = let (ts1, ts2) =break (\t->tokenPos t==endPos) toks in ts1++[ghead "duplicateDecl" ts2]
--take those token after (and include) the function binding
toks2 = dropWhile (\t->tokenPos t/=startPos || isNewLn t) toks
put((toks2,modified), others)
--rename the function name to the new name, and update token stream as well
funBinding'<-renamePN pn Nothing newFunName True funBinding
--rename function name in type signature without adjusting the token stream
typeSig' <- renamePN pn Nothing newFunName False typeSig
((toks2,_), others)<-get
let offset = getOffset toks (fst (startEndLoc toks funBinding))
newLineTok = if toks1/=[] && endsWithNewLn (glast "doDuplicating" toks1)
then [newLnToken]
else [newLnToken,newLnToken]
toks'= if typeSig/=[]
then let offset = tokenCol ((ghead "doDuplicating") (dropWhile (\t->isWhite t) toks2))
sigSource = concatMap (\s->replicate (offset-1) ' '++s++"\n")((lines.render.ppi) typeSig')
t = mkToken Whitespace (0,0) sigSource
in (toks1++newLineTok++[t]++(whiteSpacesToken (0,0) (snd startPos-1))++toks2)
else (toks1++newLineTok++(whiteSpacesToken (0,0) (snd startPos-1))++toks2)
put ((toks',modified),others)
return (typeSig'++funBinding')
where
declsToDup = definingDecls [pn] decls True False
funBinding = filter isFunOrPatBind declsToDup --get the fun binding.
typeSig = filter isTypeSig declsToDup --get the type signature.
------------------------------------------------------------------------------
-- | Add identifiers to the export list of a module. If the second argument is like: Just p, then do the adding only if p occurs
-- in the export list, and the new identifiers are added right after p in the export list. Otherwise the new identifiers are add
-- to the beginning of the export list. In the case that the export list is emport, then if the third argument is True, then create
-- an explict export list to contain only the new identifiers, otherwise do nothing.
{-
addItemsToExport::( )
=> HsModuleP -- The module AST.
-> Maybe PName -- The condtion identifier.
-> Bool -- Create an explicit list or not
-> Either [String] [HsExportEntP] -- The identifiers to add in either String or HsExportEntP format.
-> m HsModuleP -- The result.
-}
addItemsToExport::(MonadState (([PosToken],Bool), t1) m)
=> HsModuleP -- The module AST.
-> Maybe PName -- The condtion identifier.
-> Bool -- Create an explicit list or not
-> Either [String] [HsExportEntP] -- The identifiers to add in either String or HsExportEntP format.
-> m HsModuleP -- The result.
addItemsToExport mod _ _ (Left []) = return mod
addItemsToExport mod _ _ (Right []) = return mod
addItemsToExport mod@(HsModule loc modName exps imps ds) (Just pn) _ ids
= case exps of
Just ents ->let (e1,e2) = break (findEntity pn) ents
in if e2 /=[]
then do ((toks,_),others)<-get
let e = (ghead "addVarItemInExport" e2)
es = case ids of
(Left is' ) ->map (\x-> (EntE (Var (nameToPNT x)))) is'
(Right es') -> es'
let (_,endPos) = getStartEndLoc toks e
(t, (_,s)) = ghead "addVarItemInExport" $ getToks (endPos,endPos) toks
newToken = mkToken t endPos (s++","++ showEntities (render.ppi) es)
toks' = replaceToks toks endPos endPos [newToken]
put ((toks',modified),others)
return (HsModule loc modName (Just (e1++(e:es)++tail e2)) imps ds)
else return mod
Nothing -> return mod
addItemsToExport mod@(HsModule _ _ (Just ents) _ _) Nothing createExp ids
= do ((toks,_),others)<-get
let es = case ids of
(Left is' ) ->map (\x-> (EntE (Var (nameToPNT x)))) is'
(Right es') -> es'
(t, (pos,s))=fromJust $ find isOpenBracket toks -- s is the '('
newToken = if ents /=[] then (t, (pos,(s++showEntities (render.ppi) es++",")))
else (t, (pos,(s++showEntities (render.ppi) es)))
pos'= simpPos pos
toks' = replaceToks toks pos' pos' [newToken]
put ((toks',modified),others)
return mod {hsModExports=Just (es++ ents)}
addItemsToExport mod@(HsModule _ (SN modName (SrcLoc _ c row col)) Nothing _ _) Nothing createExp ids
=case createExp of
True ->do ((toks,_),others)<-get
let es = case ids of
(Left is' ) ->map (\x-> (EntE (Var (nameToPNT x)))) is'
(Right es') -> es'
pos = (row,col)
newToken = mkToken Varid pos (modNameToStr modName++ "("
++ showEntities (render.ppi) es++")")
toks' = replaceToks toks pos pos [newToken]
put ((toks', modified), others)
return mod {hsModExports=Just es}
False ->return mod
-- | Add identifiers (given by the third argument) to the explicit entity list in the declaration importing the
-- specified module name. The second argument serves as a condition: if it is like : Just p, then do the adding
-- the if only 'p' occurs in the entity list; if it is Nothing, then do the adding as normal. This function
-- does nothing if the import declaration does not have an explicit entity list.
{-
addItemsToImport::( )
=>ModuleName -- ^ The imported module name.
->Maybe PName -- ^ The condition identifier.
->Either [String] [EntSpecP] -- ^ The identifiers to add in either String or EntSpecP format.
->t -- ^ The given syntax phrase.
->m t -- ^ The result.
-}
addItemsToImport::(Term t,MonadState (([PosToken],Bool),t1) m)
=>ModuleName -- ^ The imported module name.
->Maybe PName -- ^ The condition identifier.
->Either [String] [EntSpecP] -- ^ The identifiers to add in either String or EntSpecP format.
->t -- ^ The given syntax phrase.
->m t -- ^ The result.
addItemsToImport serverModName pn (Left []) t = return t
addItemsToImport serverModName pn (Right []) t = return t
addItemsToImport serverModName pn ids t
=applyTP (full_buTP (idTP `adhocTP` inImport)) t
where
inImport (imp@(HsImportDecl loc m@(SN modName _) qual as h):: HsImportDeclP)
| serverModName == modName && (if isJust pn then findPN (fromJust pn) h else True)
= case h of
Nothing -> return imp
Just (b, ents) -> do let ents'=case ids of
Left is' -> map (\x-> Var (nameToPNT x)) is'
Right es -> es
((toks,_),others)<-get
let (_,endPos)=getStartEndLoc toks (glast "addItemsToImport" ents)
(t,(_,s))=ghead "addItemsToImport" $ getToks (endPos,endPos) toks
newToken = mkToken t endPos (s++","++showEntities (render.ppi) ents')
toks'=replaceToks toks endPos endPos [newToken]
put ((toks',modified),others)
return (HsImportDecl loc m qual as (Just (b, ents++ents')))
inImport imp = return imp
-- | add items to the hiding list of an import declaration which imports the specified module.
addHiding::(MonadState (([PosToken],Bool),t1) m)
=>ModuleName -- ^ The imported module name
->HsModuleP -- ^ The current module
->[PName] -- ^ The items to be added
->m HsModuleP -- ^ The result
addHiding serverModName mod pns
= applyTP (full_tdTP (idTP `adhocTP` inImport)) mod
where
inImport (imp@(HsImportDecl loc (SN modName _) qual as h)::HsImportDeclP)
| serverModName == modName && not qual
= case h of
Nothing ->do ((toks,_),others)<-get
let (_,endPos)=getStartEndLoc toks imp
(t,(_,s)) = ghead "addHiding" $ getToks (endPos,endPos) toks
newToken=mkToken t endPos (s++" hiding ("++showEntities pNtoName pns++")")
toks'=replaceToks toks endPos endPos [newToken]
put ((toks',modified),others)
return (replaceHiding imp (Just (True, map mkNewEnt pns )))
Just (True, ents) ->do ((toks,_),others)<-get
let (_,endPos)=getStartEndLoc toks imp
(t, (_,s))=ghead "addHiding" $ getToks (endPos,endPos) toks
newToken=mkToken t endPos (","++showEntities pNtoName pns ++s)
toks'=replaceToks toks endPos endPos [newToken]
put ((toks',modified),others)
return (replaceHiding imp (Just (True, (map mkNewEnt pns)++ents)))
Just (False, ent) -> return imp
inImport x = return x
mkNewEnt pn = (Var (PNT pn Value (N (Just loc0))))
replaceHiding (HsImportDecl loc modName qual as h) h1 = HsImportDecl loc modName qual as h1
-- | Remove those specified items from the entity list in the import declaration.
{-
rmItemsFromImport::( )
=>HsModuleP -- ^ The module AST
->[PName] -- ^ The items to be removed
->m HsModuleP -- ^ The result
-}
rmItemsFromImport::(MonadState (([PosToken],Bool),t1) m)
=>HsModuleP -- ^ The module AST
->[PName] -- ^ The items to be removed
->m HsModuleP -- ^ The result
rmItemsFromImport mod pns
= applyTP (full_buTP (idTP `adhocTP` inImport)) mod
where
inImport (imp@(HsImportDecl loc modName qual as h)::HsImportDeclP)
| any (flip findEntity imp) pns
= case h of
Just (b, ents) ->
do let matchedEnts=findEnts pns ents
if matchedEnts==[]
then return imp
else if length matchedEnts == length ents
then do ((toks,_),others)<-get
let (startPos,endPos)=getStartEndLoc toks ents
toks'=deleteToks toks startPos endPos
put ((toks',modified),others)
return (HsImportDecl loc modName qual as (Just (b,[])))
else do ((toks,_),others)<-get
let remainedEnts=concatMap (\pn->filter (not.match pn) ents) pns
toks'=foldl deleteEnt toks $ map (getStartEndLoc toks) matchedEnts
put ((toks',modified),others)
return (HsImportDecl loc modName qual as (Just (b, remainedEnts)))
_ ->return imp
inImport x = return x
findEnts pns ents =nub $ concatMap (\pn->filter (match pn) ents) pns
-- this function does not check this sub entities of the ListSubs. any problems?
match::PName -> EntSpec PNT ->Bool
match pn (Var pnt) = pNTtoPN pnt == pn
match pn (Abs pnt) = pNTtoPN pnt == pn
match pn (AllSubs pnt) = pNTtoPN pnt == pn
match pn (ListSubs pnt _) = pNTtoPN pnt == pn
-- | Remove the sub entities of a type constructor or class from the export list.
rmSubEntsFromExport::(MonadState (([PosToken],Bool),(Int,Int)) m)
=>PName -- ^ The type constructor or class name
->HsModuleP -- ^ The module AST
->m HsModuleP -- ^ The result
rmSubEntsFromExport typeCon
= applyTP (full_buTP (idTP `adhocTP` inEntSpec))
where
inEntSpec (ent@(AllSubs pnt)::EntSpec PNT)
| pNTtoPN pnt == typeCon
=do (ent', _)<-updateToks ent (Abs pnt) prettyprint
return ent'
inEntSpec (ent@(ListSubs pnt _))
| pNTtoPN pnt == typeCon
= do (ent', _) <- updateToks ent (Abs pnt) prettyprint
return ent'
inEntSpec ent = return ent
---------------------------------------------------------------------------------------
-- | Remove the specified entities from the module's exports. The entities can be specified in either of two formats:
-- i.e. either specify the module names and identifier names to be removed, so just given the exact AST for these entities.
{-rmItemsFromExport::( )
=>HsModuleP -- ^ The module AST.
->Either ([ModuleName],[PName]) [HsExportEntP] -- ^ The entities to remove.
->m HsModuleP -- ^ The result.
-}
rmItemsFromExport::(MonadState (([PosToken],Bool),t1) m)
=>HsModuleP -- ^ The module AST.
->Either ([ModuleName],[PName]) [HsExportEntP] -- ^ The entities to remove.
->m HsModuleP -- ^ The result.
rmItemsFromExport mod@(HsModule loc modName exps imps ds) (Left (modNames, pns))
=if isNothing exps
then return mod
else do let ents =findEnts (modNames, pns) (fromJust exps)
rmItemsFromExport mod (Right ents)
where
findEnts (modNames, pns) ents
=let ms = concatMap (\m ->filter (\e -> case e of
ModuleE (SN m' _) -> m==m'
EntE e' -> False) ents) modNames
es =concatMap (\pn->filter (\e ->case e of
ModuleE _ -> False
EntE e' -> match pn e') ents) pns
in (ms++es)
match::PName -> EntSpec PNT ->Bool
match pn (Var pnt) = pNTtoPN pnt == pn
match pn (Abs pnt) = pNTtoPN pnt == pn
match pn (AllSubs pnt) = pNTtoPN pnt == pn
match pn (ListSubs pnt _) = pNTtoPN pnt == pn
rmItemsFromExport mod@(HsModule loc modName exps@(Just es) imps ds) (Right ents)
= do exps'<- if ents==[]
then return exps
else if length ents == length es
then do ((toks,_),others)<-get
let (startPos,endPos) = getStartEndLoc toks ents
toks'= deleteToks toks startPos endPos
put ((toks',modified),others)
return (Just [] ) -- should not remove the empty bracket!!!
else do ((toks,_),others)<-get
let toks' = foldl deleteEnt toks $ map (getStartEndLoc toks) ents
put ((toks',modified),others)
return (Just (es \\ ents))
return (HsModule loc modName exps' imps ds)
rmItemsFromExport mod _ = return mod
--This function is only used by this module, and should not be exported.
deleteEnt toks (startPos, endPos)
= let (toks1,toks2)=break (\t->tokenPos t==startPos) toks
previousTok=ghead "deleteEnt" $ dropWhile isWhiteSpace $ reverse toks1
toks' = dropWhile isWhiteSpace $ gtail "deleteEnts" $ dropWhile (\t->tokenPos t/=endPos) toks2
nextTok = ghead "deleteEnt" toks'
startPos'=if isComma previousTok && (not (isComma nextTok)) then tokenPos previousTok else startPos
in if isComma nextTok
then let remainedToks = tail toks'
in if remainedToks /= []
then let whites = takeWhile isWhiteSpace remainedToks
in if whites /= [] then deleteToks toks startPos' (tokenPos (last whites))
else deleteToks toks startPos' (tokenPos nextTok)
else deleteToks toks startPos' (tokenPos nextTok)
else deleteToks toks startPos' endPos
--------------------------------TRY TO REMOVE THIS FUNCTION------------------------------
{-
moveDecl::(CanHaveWhereClause t,DeclStartLoc t, Term t,Printable t,MonadPlus m,
MonadState (([PosToken],Bool),(Int, Int)) m)
=> [PName] -- ^ The identifier(s) whose defining declaration is to be moved. List is used to handle pattern bindings where multiple identifiers are defined.
-> t -- ^ The syntax phrase where the declaration is going to be moved to.
-> Bool -- ^ True mean the function\/pattern binding being moved is going to be at the same level with t. Otherwise it will be a local declaration of t.
-> [HsDeclP] -- ^ The declaration list where the definition\/pattern binding originally exists.
-> Bool -- ^ True means the type signature will not be discarded.
-> m t -- ^ The result.
-}
moveDecl pns dest sameLevel decls incSig
= do ((ts,_),_)<-get
let defToks' =(getDeclToks (ghead "moveDecl:0" pns) True decls ts)
defToks =whiteSpaceTokens (tokenRow (ghead "moveDecl" defToks'),0)
-- do not use tokenCol here. should count the whilte spaces.
(tokenCol (ghead "moveDecl2" defToks') -1) ++ defToks'
movedDecls = definingDecls pns decls True False
decls'<-rmDecl (ghead "moveDecl3" pns) False =<<foldM (flip rmTypeSig) decls pns
addDecl dest Nothing (movedDecls, Just defToks) False
---------------------------------------------------------------------------------------------
-- |Parse a Haskell source files, and returns a four-element tuple. The first element in the result is the inscope
-- relation, the second element is the export relation, the third is the type decorated AST of the module and the forth element is
-- the token stream of the module.
{-
parseSourceFile:: ( ) =>FilePath
->m (InScopes,Exports,HsModuleP,[PosToken])
-}
parseSourceFile filename
= do
modle <- fileNameToModName filename
(inscps, exps, mod, tokList) <- (checkScope @@ parseSourceFile') filename
mod' <- typeCheckMod [modle]
-- map the normal AST over the typed AST preserving type info
mod2 <- mapASTOverTAST mod mod'
return (inscps, exps, mod2, tokList)
where
checkScope (ts,(((wm,_),mod),refs))
= check (checkRefs refs) >> return (inscpRel wm, exports wm, mod, expandNewLnTokens ts)
check [] = done
check errs = fail $ pp $ "Scoping errors" $$ vcat errs
typeCheckMod [mod] = do
x <- typeCheck (Just [mod])
let y = [map snd tms | (_,(x,(tms,y))) <- x]
-- let y' = map snd y
return (head (head y))
newProj args = do
newProject
addPaths True args
addFile fileName
= addPaths False fileName
chase fileNames
= findMissing fileNames
--preprocssing the token stream to expand the white spaces to individual tokens.
expandNewLnTokens::[PosToken]->[PosToken]
expandNewLnTokens ts = concatMap expand ts
where
expand tok@(Whitespace,(pos,s)) = doExpanding pos s
expand x = [x]
doExpanding pos [] =[]
doExpanding pos@(Pos c row col) (t:ts)
= case t of
'\n' -> (Whitespace, (pos,[t])):(doExpanding (Pos c (row+1) 1) ts)
_ -> (Whitespace, (pos,[t])):(doExpanding (Pos c row (col+1)) ts)
------------------------------------------------------------------------------------------------
-- | Write refactored program source to files.
{-
writeRefactoredFiles::Bool -- ^ True means the current refactoring is a sub-refactoring
->[((String,Bool),([PosToken],HsModuleP))] -- ^ String: the file name; Bool: True means the file has been modified.[PosToken]: the token stream; HsModuleP: the module AST.
-> m ()
-}
writeRefactoredFiles (isSubRefactor::Bool) (files::[((String,Bool),([PosToken], HsModuleP))])
= do let modifiedFiles = filter (\((f,m),_)->m==modified) files
addToHistory isSubRefactor $ map (fst.fst) modifiedFiles
mapM_ modifyFile modifiedFiles
mapM_ writeTestDataForFile files -- This should be removed for the release version.
{- -- the 'writeTestDataForFile' causes a 'stack overflow' problem, when applying refactorings to
-- large-scale programs,and the possible reason might be lazy evaluation and the huge size of AST.
-}
where
modifyFile ((fileName,_),(ts,mod)) = do
--let source =(render.ppi) mod
let source = concatMap (snd.snd) ts
seq (length source) $ writeHaskellFile fileName source
editorCmds <-getEditorCmds
MT.lift $ sendEditorModified editorCmds fileName
writeTestDataForFile ((fileName,_),(ts,mod)) = do
let source=concatMap (snd.snd) ts
seq (length source) $ writeFile (createNewFileName "_TokOut" fileName) source
writeHaskellFile (createNewFileName "AST" fileName) ((render.ppi.rmPrelude) mod)
createNewFileName str fileName
=let (name, posfix)=span (/='.') fileName
in (name++str++posfix)
---------------------------------------------------------------------------------------
-----Remove the 'Prelude' imports added by Programatica------------------------------
rmPrelude::HsModuleP->HsModuleP
rmPrelude (HsModule s m e is ds) = HsModule s m e (is \\ prelimps) ds
prelimps = [HsImportDecl loc0 (SN (PlainModule "Prelude") loc0) True Nothing Nothing,
HsImportDecl loc0 (SN (PlainModule "Prelude") loc0) False Nothing Nothing]
-- | Return True if a string is a lexically valid variable name.
isVarId::String->Bool
isVarId id =RefacTypeUtils.isId id && isSmall (ghead "isVarId" id)
where isSmall c=isLower c || c=='_'
-- | Return True if a string is a lexically valid constructor name.
isConId::String->Bool
isConId id =RefacTypeUtils.isId id && isUpper (ghead "isConId" id)
-- | Return True if a string is a lexically valid operator name.
isOperator::String->Bool
isOperator id = id /= [] && isOpSym (ghead "isOperator" id) &&
isLegalOpTail (tail id) && not (isReservedOp id)
where
isOpSym id = elem id opSymbols
where opSymbols = ['!', '#', '$', '%', '&', '*', '+','.','/','<','=','>','?','@','\'','^','|','-','~']
isLegalOpTail tail = all isLegal tail
where isLegal c = isOpSym c || c==':'
isReservedOp id = elem id reservedOps
where reservedOps = ["..", ":","::","=","\"", "|","<-","@","~","=>"]
{-Returns True if a string lexically is an identifier. *This function should not be exported.*
-}
isId::String->Bool
isId id = id/=[] && isLegalIdTail (tail id) && not (isReservedId id)
where
isLegalIdTail tail=all isLegal tail
where isLegal c=isSmall c|| isUpper c || isDigit c || c=='\''
isReservedId id=elem id reservedIds
where reservedIds=["case", "class", "data", "default", "deriving","do","else" ,"if",
"import", "in", "infix","infixl","infixr","instance","let","module",
"newtype", "of","then","type","where","_"]
isSmall c=isLower c || c=='_'
-----------------------------------------------------------------------------
-- |Return True if a PName is a toplevel PName.
isTopLevelPN::PName->Bool
isTopLevelPN (PN i (G _ _ _))=True
isTopLevelPN _ =False
-- |Return True if a PName is a local PName.
isLocalPN::PName->Bool
isLocalPN (PN i (UniqueNames.S _))=True
isLocalPN _ =False
-- |Return True if a PName is a qualified PName.
isQualifiedPN::PName->Bool
isQualifiedPN (PN (Qual mod id) _)=True
isQualifiedPN _ =False
-- |Return True if an PNT is a toplevel PNT.
isTopLevelPNT::PNT->Bool
isTopLevelPNT = isTopLevelPN.pNTtoPN
-- |Return True if a PName is a function\/pattern name defined in t.
isFunOrPatName::(Term t)=>PName->t->Bool
isFunOrPatName pn
=isJust.(applyTU (once_tdTU (failTU `adhocTU` worker)))
where
worker (decl::HsDeclP)
| defines pn decl=Just True
worker _ =Nothing
-- |Return True if a PNT is a function name defined in t.
isFunPNT::(Term t)=>PNT -> t -> Bool
isFunPNT pnt t = isFunName (pNTtoPN pnt) t
isFunName::(Term t)=>PName->t->Bool
isFunName pn
=isJust.(applyTU (once_tdTU (failTU `adhocTU` worker)))
where
worker (decl::HsDeclP)
| isFunBind decl && defines pn decl =Just True
worker _ =Nothing
-- |Return True if a PName is a pattern name defined in t.
isPatName::(Term t)=>PName->t->Bool
isPatName pn
=isJust.(applyTU (once_tdTU (failTU `adhocTU` worker)))
where
worker (decl::HsDeclP)
| isPatBind decl && defines pn decl =Just True
worker _ =Nothing
-------------------------------------------------------------------------------
-- | Return True if a PNT is a type constructor.
isTypeCon :: PNT -> Bool
isTypeCon (PNT pn (Type typeInfo) _) = defType typeInfo == Just TypedIds.Data
isTypeCon _ = False
-- | Return True if a declaration is a type signature declaration.
isTypeSig ::HsDeclP->Bool
isTypeSig (TiDecorate.Dec (HsTypeSig loc is c tp))=True
isTypeSig _=False
-- | Return True if a declaration is a function definition.
isFunBind::HsDeclP->Bool
isFunBind (TiDecorate.Dec (HsFunBind loc matches))=True
isFunBind _ =False
-- | Returns True if a declaration is a pattern binding.
isPatBind::HsDeclP->Bool
isPatBind (TiDecorate.Dec (HsPatBind _ _ _ _))=True
isPatBind _=False
-- | Return True if a declaration is a pattern binding which only defines a variable value.
isSimplePatBind::HsDeclP->Bool
isSimplePatBind decl=case decl of
TiDecorate.Dec (HsPatBind _ p _ _)->patToPN p /=defaultPN
_ ->False
-- | Return True if a declaration is a pattern binding but not a simple one.
isComplexPatBind::HsDeclP->Bool
isComplexPatBind decl=case decl of
TiDecorate.Dec (HsPatBind _ p _ _)->patToPN p ==defaultPN
_ -> False
-- | Return True if a declaration is a function\/pattern definition.
isFunOrPatBind::HsDeclP->Bool
isFunOrPatBind decl=isFunBind decl || isPatBind decl
-- | Return True if a declaration is a Class declaration.
isClassDecl :: HsDeclP ->Bool
isClassDecl (TiDecorate.Dec (HsClassDecl _ _ _ _ _)) = True
isClassDecl _ = False
-- | Return True if a declaration is a Class instance declaration.
isInstDecl :: HsDeclP -> Bool
isInstDecl (TiDecorate.Dec (HsInstDecl _ _ _ _ _)) = True
isInstDecl _ = False
-- | Return True if a function is a directly recursive function.
isDirectRecursiveDef::HsDeclP->Bool
isDirectRecursiveDef (TiDecorate.Dec (HsFunBind loc ms))
= any isUsedInDef ms
where
isUsedInDef (HsMatch loc1 fun pats rhs ds)
= findEntity (pNTtoPN fun) rhs
isDirectRecursiveDef _ = False
------------------------------------------------------------------------------------------------
-- | Add a qualifier to an identifier if it is not qualified.
qualifyPName::ModuleName -- ^ The qualifier.
->PName -- ^ The identifier.
->PName -- ^ The result.
qualifyPName qual pn
= case pn of
PN (UnQual n) ty -> PN (Qual qual n ) ty
_ -> pn
-- | Remove the qualifier from the given identifiers in the given syntax phrase.
rmQualifier::((MonadState (([PosToken], Bool), t1) m),Term t)
=>[PName] -- ^ The identifiers.
->t -- ^ The syntax phrase.
->m t -- ^ The result.
rmQualifier pns t
= applyTP (full_tdTP (adhocTP idTP rename )) t
where
rename pnt@(PNT pn@(PN (Qual modName s) l) ty loc@(N (Just (SrcLoc fileName _ row col))))
| elem pn pns
= do do ((toks,_), others)<-get
let toks' =replaceToks toks (row,col) (row,col) [mkToken Varid (row,col) s]
put ((toks', modified), others)
return (PNT (PN (UnQual s) l) ty loc)
rename x = return x
-- | Show a list of entities, the parameter f is a function that specifies how to format an entity.
showEntities::(Eq t, Term t)=>(t->String)->[t]->String
showEntities f [] = ""
showEntities f [pn] = f pn
showEntities f (pn:pns) =f pn ++ "," ++ showEntities f pns
-- | Show a PName in a format like: 'pn'(at row:r, col: c).
showPNwithLoc::PName->String
showPNwithLoc pn
= let (SrcLoc _ _ r c)=srcLoc pn
in " '"++pNtoName pn++"'" ++"(at row:"++show r ++ ",col:" ++ show c ++")"
----------------------------------------------------------------------------------
-- | Default identifier in the PName format.
defaultPN::PName
defaultPN=PN (UnQual "unknown") (G (PlainModule "unknown") "--" (N Nothing)) :: PName
-- | Default identifier in the PNT format.
defaultPNT::PNT
defaultPNT=PNT defaultPN Value (N Nothing) :: PNT
-- | Default module name.
defaultModName::ModuleName
defaultModName = PlainModule "unknown"
-- | Default expression.
defaultExp::HsExpP
defaultExp=TiDecorate.Exp (HsId (HsVar defaultPNT))
-- | Default expression for untyped AST
defaultExpUnTyped::HsExpI PNT
defaultExpUnTyped = PosSyntax.Exp (HsId (HsVar defaultPNT))
-- | Default pattern.
defaultPat::HsPatP
defaultPat=TiDecorate.Pat (HsPId (HsVar defaultPNT))
------------------------------------------------------------------------------------
-- | From PNT to PName.
pNTtoPN :: PNT->PName
pNTtoPN (PNT pname _ _)=pname
-- | From PName to Name. This function ignores the qualifier.
pNtoName::PName->String
pNtoName (PN (UnQual i) orig)=i
pNtoName (PN (Qual modName i) orig)=i
-- | From PNT to Name. This function ingnores the qualifier.
pNTtoName::PNT->String
pNTtoName=pNtoName.pNTtoPN
----------------------------------------------------------------------------------
class (Term t) => HasModName t where
-- | Fetch the module name from an identifier.
hasModName :: t->Maybe ModuleName
instance HasModName PNT where
hasModName (PNT (PN _ (G modName s1 loc)) _ _)=Just modName
hasModName _ =Nothing
instance HasModName PName where
hasModName (PN _ (G modName s1 loc))=Just modName
hasModName _ =Nothing
----------------------------------------------------------------------
-- | Compose a PNT form a String.
nameToPNT::String->PNT
nameToPNT id =(PNT (PN (UnQual id) (G (PlainModule "unknown") id
(N (Just loc0)))) Value (N (Just loc0)))
-- | Compose a PName from String.
nameToPN::String->PName
nameToPN id =(PN (UnQual id) (G (PlainModule "unknown") id (N (Just loc0))))
-- | Compose a PNT from a PName and the PName's name space Information
pNtoPNT::PName->IdTy PId->PNT
pNtoPNT pname ty = PNT pname ty (N (Just loc0))
-- | If an expression consists of only one identifier then return this identifier in the PNT format,
-- otherwise return the default PNT.
expToPNT::HsExpP->PNT
expToPNT (TiDecorate.Exp (HsId (HsVar pnt)))=pnt
expToPNT (TiDecorate.Exp (HsParen e))=expToPNT e
expToPNT _ =defaultPNT
-- | If an expression consists of only one identifier then return this identifier in the PName format,
-- otherwise returns the default PName.
expToPN::HsExpP->PName
expToPN =pNTtoPN.expToPNT
-- | Compose an expression from a String.
nameToExp ::String ->HsExpP
nameToExp name
=TiDecorate.Exp (HsId (HsVar (PNT (PN (UnQual name) (UniqueNames.S loc0)) Value (N (Just loc0)))))
-- | Compose an expression from a pName.
pNtoExp::PName->HsExpP
pNtoExp pn =TiDecorate.Exp (HsId (HsVar (PNT pn Value (N (Just loc0)))))
-- | If a pattern consists of only one identifier then return this identifier in the PNT format,
-- otherwise returns the default PNT.
patToPNT::HsPatP->PNT
patToPNT (TiDecorate.Pat (HsPId (HsVar pnt)))= pnt
patToPNT (TiDecorate.Pat (HsPParen p))=patToPNT p
patToPNT _=defaultPNT
-- | If a pattern consists of only one identifier then returns this identifier in the PName format,
-- otherwise returns the default PName.
patToPN::HsPatP->PName
patToPN=pNTtoPN.patToPNT
-- | Compose a pattern from a String.
nameToPat::String->HsPatP
nameToPat name
=TiDecorate.Pat (HsPId (HsVar (PNT (PN (UnQual name) (UniqueNames.S loc0)) Value (N (Just loc0)))))
-- | Compose a pattern from a pName.
pNtoPat :: PName -> HsPatP
pNtoPat pname
=let loc=srcLoc pname
in (TiDecorate.Pat (HsPId (HsVar (PNT pname Value (N (Just loc))))))
---------------------------------------------------------------------------
-- |Create a new name base on the old name. Suppose the old name is 'f', then
-- the new name would be like 'f_i' where 'i' is an integer.
mkNewName::String -- ^ The old name
->[String] -- ^ The set of names which the new name cannot take
->Int -- ^ The posfix value
->String -- ^ The result
mkNewName oldName fds init
=let newName=if init==0 then oldName
else oldName++"_"++ show init
in if elem newName fds
then mkNewName oldName fds (init+1)
else newName
-- | Return the identifier's defining location.
defineLoc::PNT->SrcLoc
defineLoc (PNT pname _ _) = srcLoc pname
-- | Return the identifier's source location.
useLoc::PNT->SrcLoc
useLoc (PNT pname _ (N (Just loc))) = loc
useLoc (PNT _ _ _ ) = loc0
-- | Return True if the identifier is used in the RHS if a function\/pattern binding.
isUsedInRhs::(Term t)=>PNT->t->Bool
isUsedInRhs pnt t= useLoc pnt /= defineLoc pnt && not (notInLhs pnt t)
where
notInLhs pnt
= (fromMaybe False).(applyTU (once_tdTU (failTU `adhocTU` inMatch
`adhocTU` inDecl)))
where
inMatch ((HsMatch loc1 name pats rhs ds)::HsMatchP)
| isJust (find (sameOccurrence pnt) [name]) = Just True
inMatch _ =Nothing
inDecl ((TiDecorate.Dec (HsTypeSig loc is c tp))::HsDeclP)
|isJust (find (sameOccurrence pnt) is) = Just True
inDecl _ =Nothing
-- | Return True is the identifier is unqualifiedly used in the given syntax phrase.
usedWithoutQual::(Term t)=>String->t->Bool
usedWithoutQual name t
=(fromMaybe False) (applyTU (once_tdTU (failTU `adhocTU` worker)) t)
where
worker (pnt::PNT)
|pNTtoName pnt ==name && isUsedInRhs pnt t && not (isQualifiedPN (pNTtoPN pnt))
= Just True
worker _ =Nothing
-- |Find the identifier(in PNT format) whose start position is (row,col) in the
-- file specified by the fileName, and returns defaultPNT is such an identifier does not exist.
locToPNT::(Term t)=>String -- ^ The file name
->(Int,Int) -- ^ The row and column number
->t -- ^ The syntax phrase
->PNT -- ^ The result
locToPNT fileName (row, col)
=(fromMaybe defaultPNT). applyTU (once_buTU (failTU `adhocTU` worker))
where
worker pnt@(PNT pname ty (N (Just (SrcLoc fileName1 _ row1 col1))))
|fileName1==fileName && (row1,col1) == (row,col) =Just pnt
worker _ =Nothing
-- | The same as locToPNT, except that it returns the identifier in the PName format.
locToPN::(Term t)=>String->(Int,Int)->t->PName
locToPN fileName pos = pNTtoPN.(locToPNT fileName pos)
-- | Given the syntax phrase (and the token stream), find the largest-leftmost expression contained in the
-- region specified by the start and end position. If no expression can be found, then return the defaultExp.
locToExp::(Term t) => RefacTITypeSyn.SimpPos -- ^ The start position.
-> RefacTITypeSyn.SimpPos -- ^ The end position.
-> [PosToken] -- ^ The token stream which should at least contain the tokens for t.
-> t -- ^ The syntax phrase.
-> HsExpP -- ^ The result.
locToExp beginPos endPos toks t
= fromMaybe defaultExp $ applyTU (once_tdTU (failTU `adhocTU` exp)) t
where
{- exp (e@(Exp (HsDo stmts))::HsExpP)
| filter inScope (map (getStartEndLoc toks) (getStmtList stmts))/=[]
= do let atoms = filter (\atom->inScope (getStartEndLoc toks atom)) (getStmtList stmts)
atoms'= reverse (dropWhile (not.isQualifierOrLastAtom) (reverse atoms))
if atoms'==[]
then fail "Expession not selected"
else do stmts' <-atoms2Stmt atoms'
Just (Exp (HsDo stmts')) -}
exp (e::HsExpP)
|inScope e = Just e
exp _ =Nothing
inScope e
= let (startLoc, endLoc)
= if expToPNT e /= defaultPNT
then let (SrcLoc _ _ row col) = useLoc (expToPNT e)
in ((row,col), (row,col))
else getStartEndLoc toks e
in (startLoc>=beginPos) && (startLoc<= endPos) && (endLoc>= beginPos) && endLoc<=endPos
isQualifierOrLastAtom (HsQualifierAtom e) = True
isQualifierOrLastAtom (HsLastAtom e) = True
isQualifierOrLastAtom _ = False
atoms2Stmt [HsQualifierAtom e] = return (HsLast e)
atoms2Stmt [HsLastAtom e] = return (HsLast e)
atoms2Stmt (HsGeneratorAtom s p e : ss) = HsGenerator s p e # atoms2Stmt ss
atoms2Stmt (HsLetStmtAtom ds : ss) = HsLetStmt ds # atoms2Stmt ss
atoms2Stmt (HsQualifierAtom e : ss) = HsQualifier e # atoms2Stmt ss
atoms2Stmt _ = fail "last statement in a 'do' expression must be an expression"
---------------------------------------------------------------------------------------
-- | Collect the identifiers (in PName format) in a given syntax phrase.
hsPNs::(Term t)=> t->[PName]
hsPNs=(nub.ghead "hsPNs").applyTU (full_tdTU (constTU [] `adhocTU` inPnt))
where
inPnt (PNT pname ty loc) = return [pname]
-- | Collect the identifiers (in PNT format) in a given syntax phrase.
hsPNTs ::(Term t)=>t->[PNT]
hsPNTs =(nub.ghead "hsPNTs").applyTU (full_tdTU (constTU [] `adhocTU` inPnt))
where
inPnt pnt@(PNT _ _ _) = return [pnt]
-- |Find those declarations(function\/pattern binding and type signature) which define the specified PNames.
--incTypeSig indicates whether the corresponding type signature will be included.
definingDecls::[PName] -- ^ The specified identifiers.
->[HsDeclP] -- ^ A collection of declarations.
->Bool -- ^ True means to include the type signature.
->Bool -- ^ True means to look at the local declarations as well.
->[HsDeclP] -- ^ The result.
definingDecls pns ds incTypeSig recursive=concatMap defines ds
where
defines decl
=if recursive
then ghead "defines" $ applyTU (stop_tdTU (failTU `adhocTU` inDecl)) decl
else defines' decl
where
inDecl (d::HsDeclP)
|defines' d /=[] =return $ defines' d
inDecl _=mzero
defines' decl@(TiDecorate.Dec (HsFunBind _ ((HsMatch _ (PNT pname _ _) _ _ _):ms)))
|isJust (find (==pname) pns) = [decl]
defines' decl@(TiDecorate.Dec (HsPatBind loc p rhs ds)) ---CONSIDER AGAIN----
|(hsPNs p) `intersect` pns /=[] = [decl]
defines' decl@(TiDecorate.Dec (HsTypeSig loc is c tp)) --handle cases like a,b::Int
|(map pNTtoPN is) `intersect` pns /=[]
=if incTypeSig
then [(TiDecorate.Dec (HsTypeSig loc (filter (\x->isJust (find (==pNTtoPN x) pns)) is) c tp))]
else []
defines' decl@(TiDecorate.Dec (HsDataDecl loc c tp cons i))
= if checkCons cons == True then [decl]
else []
where
checkCons [] = False
checkCons ((HsConDecl loc i c (PNT pname _ _) t):ms)
| isJust (find (==pname) pns) = True
| otherwise = checkCons ms
defines' _ =[]
-- | Return True if the function\/pattern binding defines the specified identifier.
defines::PName->HsDeclP->Bool
defines pn decl@(TiDecorate.Dec (HsFunBind loc ((HsMatch loc1 (PNT pname ty loc2) pats rhs ds):ms)))
= pname == pn
defines pn decl@(TiDecorate.Dec (HsPatBind loc p rhs ds)) = elem pn (hsPNs p)
defines _ _= False
-- | Return True if the declaration defines the type signature of the specified identifier.
definesTypeSig :: PName -> HsDeclP -> Bool
definesTypeSig pn (TiDecorate.Dec (HsTypeSig loc is c tp))=elem pn (map pNTtoPN is)
definesTypeSig _ _ =False
-- | Return True if the declaration defines the type signature of the specified identifier.
isTypeSigOf :: PNT -> HsDeclP -> Bool
isTypeSigOf pnt (TiDecorate.Dec (HsTypeSig loc is c tp))= elem pnt is
isTypeSigOf _ _ =False
-- | Return the list of identifiers (in PName format) defined by a function\/pattern binding.
definedPNs::HsDeclP->[PName]
definedPNs (TiDecorate.Dec (HsFunBind _ ((HsMatch _ (PNT pname _ _) _ _ _):_))) =[pname]
definedPNs (TiDecorate.Dec (HsPatBind _ p _ _)) =hsPNs p
definedPNs (TiDecorate.Dec (HsDataDecl _ _ _ cons _) )
= getCons cons
where
getCons [] = []
getCons ((HsConDecl _ _ _ (PNT pname _ _) _):ms)
= pname : (getCons ms)
getCons ((HsRecDecl _ _ _ (PNT pname _ _) _):ms)
= pname : (getCons ms)
getCons _ = []
definedPNs _=[]
-- |Return True if the given syntax phrase contains any free variables.
hasFreeVars::(Term t)=>t->Bool
hasFreeVars t = fromMaybe False (do (f,_)<-hsFreeAndDeclaredPNs t
if f/=[] then Just True
else Nothing)
{- Remove source location information in the syntax tree. that is to replace all
source locations by default location: loc0 -}
-- | Remove source location information in the syntax tree.
rmLocs :: (Term t)=> t->t
rmLocs t =runIdentity (applyTP (full_tdTP (idTP `adhocTP` exp
`adhocTP` pnt
`adhocTP` alt
`adhocTP` lit)) t)
where
exp ((TiDecorate.Exp (HsNegApp loc e)) ::HsExpP)=return (TiDecorate.Exp (HsNegApp loc0 e))
exp (TiDecorate.Exp (HsExpTypeSig loc e c t))=return (TiDecorate.Exp (HsExpTypeSig loc0 e c t))
exp x=return x
alt ((HsAlt loc p e ds)::HsAltP)=return (HsAlt loc0 p e ds)
lit (HsInt int) = return (HsInt int)
lit (HsFrac rat)= return (HsFrac rat)
pnt (PNT pname ty _)= return (PNT pname ty (N (Just loc0)))
-- | Change the absolute define locations of local variables to relative ones,
-- so that equality between expressions can be compared via alpha-renaming.
toRelativeLocs::(Term t)=>t->t
toRelativeLocs e = runIdentity (applyTP (full_tdTP (idTP `adhocTP` inLoc)) e)
where
inLoc (SrcLoc f c row col)
| elem (row,col) defLocs
= let index=fromJust (elemIndex (row,col) defLocs) + 1
in return (SrcLoc f index index index)
inLoc loc = return loc
defLocs= ((nub.ghead "toRelativeLoc").applyTU (full_tdTU (constTU []
`adhocTU` inPnt ))) e
where
inPnt pnt@(PNT pn ty loc)
|defineLoc pnt == useLoc pnt= return [(\(SrcLoc _ _ r c)->(r,c)) (srcLoc pn)]
inPnt _ = return []
------------------------------------------------------------------------------------------
-- | Replace the name (and qualifier if specified) by a new name (and qualifier) in a PName.
-- The function does not modify the token stream.
replaceNameInPN::Maybe ModuleName -- ^ The new qualifier
->PName -- ^ The old PName
->String -- ^ The new name
->PName -- ^ The result
replaceNameInPN qualifier (PN (UnQual s)(UniqueNames.S loc)) newName
= if isJust qualifier then (PN (Qual (fromJust qualifier) newName) (UniqueNames.S loc))
else (PN (UnQual newName) (UniqueNames.S loc))
replaceNameInPN qualifier (PN (Qual modName s)(UniqueNames.S loc)) newName
= if isJust qualifier then (PN (Qual (fromJust qualifier) newName)(UniqueNames.S loc))
else (PN (Qual modName newName) (UniqueNames.S loc))
replaceNameInPN qualifier (PN (UnQual s) (G modName s1 loc)) newName
= if isJust qualifier then (PN (Qual (fromJust qualifier) newName) (G modName newName loc))
else (PN (UnQual newName) (G modName newName loc))
replaceNameInPN qualifier (PN (Qual modName s) (G modName1 s1 loc)) newName
=if isJust qualifier then (PN (Qual (fromJust qualifier) newName) (G modName1 newName loc))
else (PN (Qual modName newName) (G modName1 newName loc))
-- | Rename each occurrences of the identifier in the given syntax phrase with the new name.
-- If the Bool parameter is True, then modify both the AST and the token stream, otherwise only modify the AST.
{-
renamePN::(Term t)
=>PName -- ^ The identifier to be renamed.
->Maybe ModuleName -- ^ The qualifier
->String -- ^ The new name
->Bool -- ^ True means modifying the token stream as well.
->t -- ^ The syntax phrase
->m t
-}
renamePN::((MonadState (([PosToken], Bool), t1) m),Term t)
=>PName -- ^ The identifier to be renamed.
->Maybe ModuleName -- ^ The qualifier
->String -- ^ The new name
->Bool -- ^ True means modifying the token stream as well.
->t -- ^ The syntax phrase
->m t
renamePN oldPN qualifier newName updateToks t
= applyTP (full_tdTP (adhocTP idTP rename)) t
where
rename pnt@(PNT pn ty (N (Just (SrcLoc fileName c row col))))
| (pn ==oldPN) && (srcLoc oldPN == srcLoc pn)
= do if updateToks
then do ((toks,_),others)<-get
let toks'=replaceToks toks (row,col) (row,col)
[mkToken Varid (row,col) ((render.ppi) (replaceName pn newName))]
put ((toks', modified),others)
return (PNT (replaceName pn newName) ty (N (Just (SrcLoc fileName c row col))))
else return (PNT (replaceName pn newName) ty (N (Just (SrcLoc fileName c row col))))
where
replaceName = if isJust qualifier && canBeQualified pnt t
then replaceNameInPN qualifier
else replaceNameInPN Nothing
rename x = return x
-- | Return True if the identifier can become qualified.
canBeQualified::(Term t)=>PNT->t->Bool
canBeQualified pnt t
= isTopLevelPNT pnt && isUsedInRhs pnt t && not (findPntInImp pnt t)
where
findPntInImp pnt
= (fromMaybe False).(applyTU (once_tdTU (failTU `adhocTU` inImp)))
where
inImp ((HsImportDecl loc modName qual as h)::HsImportDeclP)
|findEntity pnt h = Just True
inImp _ = Nothing
-- | Return True if the identifier(in PNT format) occurs in the given syntax phrase.
findPNT::(Term t)=>PNT->t->Bool
findPNT pnt
= (fromMaybe False).(applyTU (once_tdTU (failTU `adhocTU` worker)))
where
worker (pnt1::PNT)
| sameOccurrence pnt pnt1 =Just True
worker _ =Nothing
-- | Return True if the identifier (in PName format) occurs in the given syntax phrase.
findPN::(Term t)=>PName->t->Bool
findPN pn
=(fromMaybe False).(applyTU (once_tdTU (failTU `adhocTU` worker)))
where
worker (pn1::PName)
|pn == pn1 && srcLoc pn == srcLoc pn1 = Just True
worker _ =Nothing
-- | Return True if any of the specified PNames ocuur in the given syntax phrase.
findPNs::(Term t)=>[PName]->t->Bool
findPNs pns
=(fromMaybe False).(applyTU (once_tdTU (failTU `adhocTU` worker)))
where
worker (pn1::PName)
|elem pn1 pns = Just True
worker _ =Nothing
----------------------------------------------------------------------------------------
-- | Check whether the specified identifier is declared in the given syntax phrase t,
-- if so, rename the identifier by creating a new name automatically. If the Bool parameter
-- is True, the token stream will be modified, otherwise only the AST is modified.
{-
autoRenameLocalVar::(MonadPlus m, Term t)
=>Bool -- ^ True means modfiying the token stream as well.
->PName -- ^ The identifier.
->t -- ^ The syntax phrase.
-> m t -- ^ The result.
-}
autoRenameLocalVar::(MonadPlus m, (MonadState (([PosToken], Bool), (Int,Int)) m), Term t)
=>Bool -- ^ True means modfiying the token stream as well.
->PName -- ^ The identifier.
->t -- ^ The syntax phrase.
-> m t -- ^ The result.
autoRenameLocalVar updateToks pn
=applyTP (once_buTP (failTP `adhocTP` renameInMatch
`adhocTP` renameInPat
`adhocTP` renameInExp
`adhocTP` renameInAlt
`adhocTP` renameInStmts))
where
renameInMatch (match::HsMatchP)
|isDeclaredIn pn match=worker match
renameInMatch _ =mzero
renameInPat (pat::HsDeclP)
|isDeclaredIn pn pat=worker pat
renameInPat _ =mzero
renameInExp (exp::HsExpP)
|isDeclaredIn pn exp=worker exp
renameInExp _ =mzero
renameInAlt (alt::HsAltP)
|isDeclaredIn pn alt=worker alt
renameInAlt _ =mzero
renameInStmts (stmt::HsStmtP)
|isDeclaredIn pn stmt=worker stmt
renameInStmts _=mzero
worker t =do (f,d)<-hsFDNamesFromInside t
ds<-hsVisibleNames pn (hsDecls t)
let newName=mkNewName (pNtoName pn) (nub (f `union` d `union` ds)) 1
if updateToks
then renamePN pn Nothing newName True t
else renamePN pn Nothing newName False t
-------------------------------------------------------------------------------------
-- | Add a guard expression to the RHS of a function\/pattern definition. If a guard already
-- exists in the RHS, the new guard will be added to the beginning of the existing one.
addGuardsToRhs::(MonadState (([PosToken], Bool), (Int,Int)) m)
=> RhsP -- ^ The RHS of the declaration.
-> HsExpP -- ^ The guard expression to be added.
-> m RhsP -- ^ The result.
addGuardsToRhs (HsBody e) guardExp
= do ((toks,_), (v1,v2)) <-get
let (startPos', _) = startEndLoc toks e
(toks1,toks2) = break (\t->tokenPos t==startPos') toks
reversedToks1BeforeEqOrArrow = dropWhile (\t->not (isEqual t || isArrow t)) (reverse toks1)
eqOrArrowTok = ghead "addGuardsToRhs" reversedToks1BeforeEqOrArrow
startPos = tokenPos eqOrArrowTok
offset = lengthOfLastLine (reverse (gtail "addGuardsToRhs" reversedToks1BeforeEqOrArrow))
newCon = "|"++(render.ppi) guardExp ++ "\n" ++ replicate offset ' '++ tokenCon eqOrArrowTok
newToks = tokenise (Pos 0 v1 1) 0 False newCon
toks' = replaceToks toks startPos startPos newToks
put ((toks',modified), ((tokenRow (glast "addFormalParams" newToks) -10), v2))
-- (guardExp',_) <- addLocInfo (guardExp, newToks)
return $ HsGuard [(loc0, guardExp, e)]
addGuardsToRhs (HsGuard gs) guardExp
= do newGuards <- mapM (addGuard guardExp) gs
return (HsGuard newGuards)
where
addGuard guardExp (loc, e1, e2)
= do (e', _)<-updateToks e1 (TiDecorate.Exp (HsInfixApp guardExp (HsVar (nameToPNT "&&")) e1)) prettyprint
return (loc, e', e2)
------------------------------------------------------------------------------------------------------
{-
addParamsToDecls::(MonadPlus m)
=> [HsDeclP] -- ^ A declaration list where the function is defined and\/or used.
->PName -- ^ The function name.
->[PName] -- ^ The parameters to be added.
->Bool -- ^ Modify the token stream or not.
->m [HsDeclP] -- ^ The result.
-}
addParamsToDecls::(MonadPlus m, (MonadState (([PosToken], Bool), (Int,Int)) m))
=> [HsDeclP] -- ^ A declaration list where the function is defined and\/or used.
->PName -- ^ The function name.
->[PName] -- ^ The parameters to be added.
->Bool -- ^ Modify the token stream or not.
->m [HsDeclP] -- ^ The result.
addParamsToDecls decls pn paramPNames modifyToks
= if (paramPNames/=[])
then mapM addParamToDecl decls
else return decls
where
addParamToDecl (TiDecorate.Dec (HsFunBind loc matches@((HsMatch _ fun pats rhs ds):ms)))
| pNTtoPN fun == pn
= do matches'<-mapM addParamtoMatch matches
return (TiDecorate.Dec (HsFunBind loc matches'))
where
addParamtoMatch (HsMatch loc fun pats rhs decls)
= do rhs'<-addActualParamsToRhs pn paramPNames rhs
let pats' = map pNtoPat paramPNames
pats'' <- if modifyToks then do (p, _)<-addFormalParams fun pats'
return p
else return pats'
return (HsMatch loc fun (pats'++pats) rhs' decls)
addParamToDecl (TiDecorate.Dec (HsPatBind loc p rhs ds))
|patToPN p == pn
= do rhs'<-addActualParamsToRhs pn paramPNames rhs
let pats' = map pNtoPat paramPNames
pats'' <- if modifyToks then do (p, _) <-addFormalParams p pats'
return p
else return pats'
return (TiDecorate.Dec (HsFunBind loc [HsMatch loc (patToPNT p) pats' rhs ds]))
addParamToDecl x=return x
addActualParamsToRhs pn paramPNames
= applyTP (stop_tdTP (failTP `adhocTP` worker))
where
worker exp@(TiDecorate.Exp (HsId (HsVar (PNT pname ty loc))))
| pname==pn
= do let newExp=TiDecorate.Exp (HsParen (foldl addParamToExp exp (map pNtoExp paramPNames)))
if modifyToks then do (newExp', _) <- updateToks exp newExp prettyprint
return newExp'
else return newExp
worker x =mzero
addParamToExp exp param=(TiDecorate.Exp (HsApp exp param))
-------------------------------------------------------------------
-- | Remove the first n parameters of a given identifier in an expression.
rmParams:: (MonadPlus m,MonadState (([PosToken], Bool), (Int,Int)) m)=>
PNT -- ^ The identifier whose parameters are to be removed.
->Int -- ^ Number of parameters to be removed.
->HsExpP -- ^ The original expression.
->m HsExpP -- ^ The result expression.
rmParams pnt n exp
= if n==0 then return exp
else do exp'<-rmOneParam pnt exp
rmParams pnt (n-1) exp'
where
rmOneParam pnt= applyTP (stop_tdTP (failTP `adhocTP` inExp))
inExp (exp@(TiDecorate.Exp (HsParen (TiDecorate.Exp (HsApp e1 e2))))::HsExpP)
---dfd
|sameOccurrence (expToPNT e1) pnt
=do updateExp exp e1
inExp exp@(TiDecorate.Exp (HsApp e1 e2))
| sameOccurrence (expToPNT e1) pnt
=do updateExp exp e1
inExp _=mzero
updateExp exp e1
= do ((toks,_),others)<-get --handle the case like '(fun x) => fun "
let (startPos,endPos)=getStartEndLoc toks exp
toks'=replaceToks toks startPos endPos $ getToks (getStartEndLoc toks e1) toks
put ((toks',modified),others)
return e1
-------------------------------------------------------------------------------------------------------
{-A simple function binding satisfies : 1. all parameters are variables
2. only one match(equation)
3. The rhs of the match is not in guard style.
that is:
HsFunBind SrcLoc ((HsMatch SrcLoc i [var] (HsBody e) ds):[]) ds
If a function binding is not a simple function binding, then convert it into a simple binding
using Case or IfThenElse expressions like this:
case1: there are multi matches => case expression
case2: there is only one match, however the parameters are not simple variables =>case expression.
case3: there is only one match and the parameters are all simple variables, however there is a guard
in Rhs => If then else
In case of pattern binding: if there is guard in its Rhs, then convert it into IfThenElse style. -}
-- | If a function\/pattern binding then convert it into a simple binding using case and\/or if-then-else expressions.
-- A simple function\/pattern binding should satisfy: a) all the paraneters are simple variables; b). only has one equation;
-- c). the RHS does not have guards. This function DOES NOT modify the token stream not AST.
simplifyDecl::(Monad m)=>HsDeclP->m HsDeclP
simplifyDecl decl
|isFunBind decl =if (multiMatches decl) || (singleMatchWithComplexParams decl)
then matchesToCase decl
else return (guardToIfThenElse decl)
|isPatBind decl=return (guardToIfThenElse decl)
|otherwise = return decl
where
multiMatches (TiDecorate.Dec (HsFunBind loc matches))=length matches>1
multiMatches _ = False
singleMatchWithComplexParams (TiDecorate.Dec (HsFunBind loc matches@((HsMatch loc1 pnt pats rhs ds):ms)))
=length matches==1 && any (==defaultPN) (map patToPN pats)
singleMatchWithComplexParams _ =False
--convert a multi-match function declaration into a single-match declration using case expression.
matchesToCase decl@(TiDecorate.Dec (HsFunBind loc matches@((HsMatch loc1 pnt pats rhs ds):ms)))
=do params<-mkNewParamPNames (length pats)
exp<-pNamesToExp params
return (TiDecorate.Dec (HsFunBind loc [(HsMatch loc1 pnt (map pNtoPat params)
(HsBody (TiDecorate.Exp (HsCase exp (map matchToAlt matches)))) (Decs [] ([], [])))]))
--make n new parameters like [x_0,x_1, ...,x_n]
mkNewParamPNames n=mkNewParamPNames' n []
where mkNewParamPNames' n pNames
=if n==0 then return pNames
else do let pn'= PN (UnQual ("x_"++show (n-1))) (UniqueNames.S loc0)
mkNewParamPNames' (n-1) (pn':pNames)
matchToAlt ((HsMatch loc1 pnt pats rhs ds)::HsMatchP)=HsAlt loc0 (listToTuple pats) rhs ds
where
listToTuple pats=if (length pats)==1 then ghead "listToTuple" pats --no problem with head
else (TiDecorate.Pat (HsPTuple loc0 pats))
pNamesToExp pns@(p:ps)=if ps==[] then return $ pNtoExp p
else do let exp'=map pNtoExp pns
return (TiDecorate.Exp (HsTuple exp'))
guardToIfThenElse decl= case decl of
(TiDecorate.Dec (HsPatBind loc p g@(HsGuard gs) ds))->(TiDecorate.Dec (HsPatBind loc p (rmGuard g) ds))
(TiDecorate.Dec (HsFunBind loc ((HsMatch loc1 pnt pats g@(HsGuard gs) ds):[]))) ->
(TiDecorate.Dec (HsFunBind loc ((HsMatch loc1 pnt pats (rmGuard g) ds):[])))
_ ->decl
where
rmGuard ((HsGuard gs)::RhsP)
= let (_,e1,e2)=glast "guardToIfThenElse" gs
in if ((pNtoName.expToPN) e1)=="otherwise"
then HsBody (foldl mkIfThenElse e2 (tail(reverse gs)))
else HsBody (foldl mkIfThenElse defaultElse (reverse gs))
mkIfThenElse e (_,e1, e2)=(TiDecorate.Exp (HsIf e1 e2 e))
defaultElse=(TiDecorate.Exp (HsApp (TiDecorate.Exp (HsId (HsVar (PNT (PN (UnQual "error") (G (PlainModule "Prelude") "error"
(N (Just loc0)))) Value (N (Just loc0)))))) (TiDecorate.Exp (HsLit loc0 (HsString "UnMatched Pattern")))))
-----------------------------------------------------------------------------------------
-- | Collect those data constructors that occur in the given syntax phrase, say t. In the result,
-- the first list contains the data constructors that are declared in other modules, and the second
-- list contains the data constructors that are declared in the current module.
hsDataConstrs::Term t=>ModuleName -- ^ The name of the module which 't' belongs to.
-> t -- ^ The given syntax phrase.
->([PName],[PName]) -- ^ The result.
hsDataConstrs modName
= ghead "hsDataConstrs". (applyTU (stop_tdTU (failTU `adhocTU` pnt)))
where
pnt (PNT pname (ConstrOf _ _) _)
= if hasModName pname==Just modName
then return ([],[pname])
else return ([pname],[])
pnt _ = mzero
-- | Collect those type constructors and class names that occur in the given syntax phrase, say t.
-- In the result, the first list contains the type constructor\/classes which are
-- declared in other modules, and the second list contains those type constructor\/classes
-- that are declared in the current module.
hsTypeConstrsAndClasses::Term t=>ModuleName -- ^ The name of the module which 't' belongs to.
-> t -- ^ The given syntax phrase.
-> ([PName],[PName]) -- ^ The result.
hsTypeConstrsAndClasses modName
= ghead "hsTypeConstrAndClasses".(applyTU (stop_tdTU (failTU `adhocTU` pnt)))
where
pnt (PNT (PN i (G modName1 id loc)) (Type _) _)
= if modName == modName1
then return ([],[(PN i (G modName id loc))])
else return ([(PN i (G modName id loc))], [])
pnt (PNT pname (TypedIds.Class _ _) _)=if hasModName pname==Just modName
then return ([],[pname])
else return ([pname],[])
pnt _ =mzero
-- |Collect those type variables that are declared in a given syntax phrase t.
-- In the returned result, the first list is always be empty.
hsTypeVbls::(Term t) => t -> ([PName],[PName])
hsTypeVbls =ghead "hsTypeVbls".(applyTU (stop_tdTU (failTU `adhocTU` pnt)))
where
pnt (PNT (PN i (UniqueNames.S loc)) (Type _) _) = return ([], [(PN i (UniqueNames.S loc))])
pnt _ =mzero
-- |Collect the class instances of the spcified class from the given syntax phrase. In the result,
-- the first list contains those class instances which are declared in other modules,
-- and the second list contains those class instances that are declared in the current module.
hsClassMembers::Term t => String -- ^ The class name.
->ModuleName -- ^ The module name.
->t -- ^ The syntax phrase.
->([PName],[PName]) -- ^ The result.
hsClassMembers className modName
= ghead "hsClassMembers". (applyTU (stop_tdTU (failTU `adhocTU` pnt)))
where
pnt(PNT pname (MethodOf i _ _) _) -- Claus
| pNtoId i==className
= if hasModName pname == Just modName
then return ([],[pname])
else return ([pname],[])
pnt _ = mzero
pNtoId :: PN (HsName.Id) ->String
pNtoId (PN i orig)=i
------------------------------------------------------------------------------------------
-- | Collect the free and declared variables (in the PName format) in a given syntax phrase t.
-- In the result, the first list contains the free variables, and the second list contains the declared variables.
hsFreeAndDeclaredPNs:: (Term t, MonadPlus m)=> t-> m ([PName],[PName])
hsFreeAndDeclaredPNs t=do (f,d)<-hsFreeAndDeclared' t
return (nub f, nub d)
where
hsFreeAndDeclared'=applyTU (stop_tdTU (failTU `adhocTU` exp
`adhocTU` pat
`adhocTU` match
`adhocTU` patBind
`adhocTU` alt
`adhocTU` decls
`adhocTU` stmts
`adhocTU` recDecl))
exp (TiDecorate.Exp (HsId (HsVar (PNT pn _ _))))=return ([pn],[])
exp (TiDecorate.Exp (HsId (HsCon (PNT pn _ _))))=return ([pn],[])
exp (TiDecorate.Exp (HsInfixApp e1 (HsVar (PNT pn _ _)) e2))
=addFree pn (hsFreeAndDeclaredPNs [e1,e2])
exp (TiDecorate.Exp (HsLambda pats body))
= do (pf,pd) <-hsFreeAndDeclaredPNs pats
(bf,_) <-hsFreeAndDeclaredPNs body
return ((bf `union` pf) \\ pd, [])
exp (TiDecorate.Exp (HsLet decls exp))
= do (df,dd)<- hsFreeAndDeclaredPNs decls
(ef,_)<- hsFreeAndDeclaredPNs exp
return ((df `union` (ef \\ dd)),[])
exp (TiDecorate.Exp (HsRecConstr _ (PNT pn _ _) e))
=addFree pn (hsFreeAndDeclaredPNs e) --Need Testing
exp (TiDecorate.Exp (HsAsPat (PNT pn _ _) e))
=addFree pn (hsFreeAndDeclaredPNs e)
exp _ = mzero
pat (TiDecorate.Pat (HsPId (HsVar (PNT pn _ _))))=return ([],[pn])
pat (TiDecorate.Pat (HsPInfixApp p1 (PNT pn _ _) p2))=addFree pn (hsFreeAndDeclaredPNs [p1,p2])
pat (TiDecorate.Pat (HsPApp (PNT pn _ _) pats))=addFree pn (hsFreeAndDeclaredPNs pats)
pat (TiDecorate.Pat (HsPRec (PNT pn _ _) fields))=addFree pn (hsFreeAndDeclaredPNs fields)
pat _ =mzero
match ((HsMatch _ (PNT fun _ _) pats rhs decls)::HsMatchP)
= do (pf,pd) <- hsFreeAndDeclaredPNs pats
(rf,rd) <- hsFreeAndDeclaredPNs rhs
(df,dd) <- hsFreeAndDeclaredPNs decls
return ((pf `union` ((rf `union` df) \\ (dd `union` pd `union` [fun]))),[fun])
-------Added by Huiqing Li-------------------------------------------------------------------
patBind ((TiDecorate.Dec (HsPatBind _ pat (HsBody rhs) decls))::HsDeclP)
=do (pf,pd) <- hsFreeAndDeclaredPNs pat
(rf,rd) <- hsFreeAndDeclaredPNs rhs
(df,dd) <- hsFreeAndDeclaredPNs decls
return (pf `union` ((rf `union` df) \\(dd `union` pd)),pd)
patBind _=mzero
-------------------------------------------------------------------------------------------
alt ((HsAlt _ pat exp decls)::(HsAlt (HsExpP) (HsPatP) HsDeclsP))
= do (pf,pd) <- hsFreeAndDeclaredPNs pat
(ef,ed) <- hsFreeAndDeclaredPNs exp
(df,dd) <- hsFreeAndDeclaredPNs decls
return (pf `union` (((ef \\ dd) `union` df) \\ pd),[])
decls (ds :: [HsDeclP])
=do (f,d) <-hsFreeAndDeclaredList ds
return (f\\d,d)
stmts ((HsGenerator _ pat exp stmts) :: HsStmt (HsExpP) (HsPatP) HsDeclsP) -- Claus
=do (pf,pd) <-hsFreeAndDeclaredPNs pat
(ef,ed) <-hsFreeAndDeclaredPNs exp
(sf,sd) <-hsFreeAndDeclaredPNs stmts
return (pf `union` ef `union` (sf\\pd),[]) -- pd) -- Check this
stmts ((HsLetStmt decls stmts) :: HsStmt (HsExpP) (HsPatP) HsDeclsP)
=do (df,dd) <-hsFreeAndDeclaredPNs decls
(sf,sd) <-hsFreeAndDeclaredPNs stmts
return (df `union` (sf \\dd),[])
stmts _ =mzero
recDecl ((HsRecDecl _ _ _ _ is) :: HsConDeclI PNT (HsTypeI PNT) [HsTypeI PNT])
=do let d=map pNTtoPN $ concatMap fst is
return ([],d)
recDecl _ =mzero
addFree free mfd=do (f,d)<-mfd
return ([free] `union` f, d)
hsFreeAndDeclaredList l=do fds<-mapM hsFreeAndDeclaredPNs l
return (foldr union [] (map fst fds),
foldr union [] (map snd fds))
-- |The same as `hsFreeAndDeclaredPNs` except that the returned variables are in the String format.
hsFreeAndDeclaredNames::(Term t, MonadPlus m)=> t->m([String],[String])
hsFreeAndDeclaredNames t =do (f1,d1)<-hsFreeAndDeclaredPNs t
return ((nub.map pNtoName) f1, (nub.map pNtoName) d1)
-----------------------------------------------------------------------------------------
{- |`hsFDsFromInside` is different from `hsFreeAndDeclaredPNs` in that: given an syntax phrase t,
`hsFDsFromInside` returns not only the declared variables that are visible from outside of t,
but also those declared variables that are visible to the main expression inside t.
-}
hsFDsFromInside:: (Term t, MonadPlus m)=> t-> m ([PName],[PName])
hsFDsFromInside t = do (f,d)<-hsFDsFromInside' t
return (nub f, nub d)
where
hsFDsFromInside' = applyTU (once_tdTU (failTU `adhocTU` mod
-- `adhocTU` decls
`adhocTU` decl
`adhocTU` match
`adhocTU` exp
`adhocTU` alt
`adhocTU` stmts ))
mod ((HsModule loc modName exps imps ds)::HsModuleP)
= hsFreeAndDeclaredPNs ds
{- decls (ds::[HsDeclP]) --CHECK THIS.
= hsFreeAndDeclaredPNs decls
-}
match ((HsMatch loc1 (PNT fun _ _) pats rhs ds) ::HsMatchP)
= do (pf, pd) <-hsFreeAndDeclaredPNs pats
(rf, rd) <-hsFreeAndDeclaredPNs rhs
(df, dd) <-hsFreeAndDeclaredPNs ds
return (nub (pf `union` ((rf `union` df) \\ (dd `union` pd `union` [fun]))),
nub (pd `union` rd `union` dd `union` [fun]))
decl ((TiDecorate.Dec (HsPatBind loc p rhs ds))::HsDeclP)
= do (pf, pd)<-hsFreeAndDeclaredPNs p
(rf, rd)<-hsFreeAndDeclaredPNs rhs
(df, dd)<-hsFreeAndDeclaredPNs ds
return (nub (pf `union` ((rf `union` df) \\ (dd `union` pd))),
nub ((pd `union` rd `union` dd)))
decl (TiDecorate.Dec (HsFunBind loc matches))
=do fds <-mapM hsFDsFromInside matches
return (nub (concatMap fst fds), nub(concatMap snd fds))
decl _ = mzero
exp ((TiDecorate.Exp (HsLet decls exp))::HsExpP)
= do (df,dd)<- hsFreeAndDeclaredPNs decls
(ef,_)<- hsFreeAndDeclaredPNs exp
return (nub (df `union` (ef \\ dd)), nub dd)
exp (TiDecorate.Exp (HsLambda pats body))
= do (pf,pd) <-hsFreeAndDeclaredPNs pats
(bf,_) <-hsFreeAndDeclaredPNs body
return (nub ((bf `union` pf) \\ pd), nub pd)
exp _ = mzero
alt ((HsAlt _ pat exp decls)::HsAltP)
= do (pf,pd) <- hsFreeAndDeclaredPNs pat
(ef,ed) <- hsFreeAndDeclaredPNs exp
(df,dd) <- hsFreeAndDeclaredPNs decls
return (nub (pf `union` (((ef \\ dd) `union` df) \\ pd)), nub (pd `union` dd))
stmts ((HsLetStmt decls stmts)::HsStmtP)
= do (df,dd) <-hsFreeAndDeclaredPNs decls
(sf,sd) <-hsFreeAndDeclaredPNs stmts
return (nub (df `union` (sf \\dd)),[]) -- dd)
stmts (HsGenerator _ pat exp stmts)
= do (pf,pd) <-hsFreeAndDeclaredPNs pat
(ef,ed) <-hsFreeAndDeclaredPNs exp
(sf,sd) <-hsFreeAndDeclaredPNs stmts
return (nub (pf `union` ef `union` (sf\\pd)),[]) -- pd)
stmts _ = mzero
-- | The same as `hsFDsFromInside` except that the returned variables are in the String format
hsFDNamesFromInside::(Term t, MonadPlus m)=>t->m ([String],[String])
hsFDNamesFromInside t =do (f,d)<-hsFDsFromInside t
return ((nub.map pNtoName) f, (nub.map pNtoName) d)
------------------------------------------------------------------------------------------
-- | Same as `hsVisiblePNs' except that the returned identifiers are in String format.
hsVisibleNames:: (Term t1, Term t2, FindEntity t1, MonadPlus m) => t1 -> t2 -> m [String]
hsVisibleNames e t =do d<-hsVisiblePNs e t
return ((nub.map pNtoName) d)
-- | Given syntax phrases e and t, if e occurs in t, then return those vairables
-- which are declared in t and accessible to e, otherwise return [].
hsVisiblePNs :: (Term t1, Term t2, FindEntity t1, MonadPlus m) => t1 -> t2 -> m [PName]
hsVisiblePNs e t =applyTU (full_tdTU (constTU [] `adhocTU` mod
`adhocTU` exp
`adhocTU` match
`adhocTU` patBind
`adhocTU` alt
`adhocTU` stmts)) t
where
mod ((HsModule loc modName exps imps decls)::HsModuleP)
|findEntity e decls
=do (df,dd)<-hsFreeAndDeclaredPNs decls
return dd
mod _=return []
exp ((TiDecorate.Exp (HsLambda pats body))::HsExpP)
|findEntity e body
= do (pf,pd) <-hsFreeAndDeclaredPNs pats
return pd
exp (TiDecorate.Exp (HsLet decls e1))
|findEntity e e1 || findEntity e decls
= do (df,dd)<- hsFreeAndDeclaredPNs decls
return dd
exp _ =return []
match (m@(HsMatch _ (PNT fun _ _) pats rhs decls)::HsMatchP)
|findEntity e rhs || findEntity e decls
= do (pf,pd) <- hsFreeAndDeclaredPNs pats
(df,dd) <- hsFreeAndDeclaredPNs decls
return (pd `union` dd `union` [fun])
match _=return []
patBind (p@(TiDecorate.Dec (HsPatBind _ pat rhs decls))::HsDeclP)
|findEntity e rhs || findEntity e decls
=do (pf,pd) <- hsFreeAndDeclaredPNs pat
(df,dd) <- hsFreeAndDeclaredPNs decls
return (pd `union` dd)
patBind _=return []
alt ((HsAlt _ pat exp decls)::HsAltP)
|findEntity e exp || findEntity e decls
= do (pf,pd) <- hsFreeAndDeclaredPNs pat
(df,dd) <- hsFreeAndDeclaredPNs decls
return (pd `union` dd)
alt _=return []
stmts ((HsGenerator _ pat exp stmts) :: HsStmtP)
|findEntity e stmts
=do (pf,pd) <-hsFreeAndDeclaredPNs pat
return pd
stmts (HsLetStmt decls stmts)
|findEntity e decls || findEntity e stmts
=do (df,dd) <-hsFreeAndDeclaredPNs decls
return dd
stmts _ =return []
-------------------------------------------------------------------------------
{- | The HsDecls class -}
class (Term t) => HsDecls t where
-- | Return the declarations that are directly enclosed in the given syntax phrase.
hsDecls :: t->[HsDeclP]
-- | Replace the directly enclosed declaration list by the given declaration list.
-- Note: This function does not modify the token stream.
replaceDecls :: t->HsDeclsP->t
-- | Return True if the specified identifier is declared in the given syntax phrase.
isDeclaredIn :: PName -> t->Bool
instance HsDecls HsMatchP where
hsDecls (HsMatch loc1 fun pats rhs ds@(Decs x y))=x
replaceDecls (HsMatch loc1 fun pats rhs ds) ds'
=(HsMatch loc1 fun pats rhs ds')
isDeclaredIn pn match@(HsMatch loc1 (PNT fun _ _) pats rhs ds)
=fromMaybe False ( do (_,d)<-hsFDsFromInside match
Just (elem pn (d \\ [fun])))
instance HsDecls HsDeclP where
hsDecls (TiDecorate.Dec (HsPatBind loc p rhs ds@(Decs x y)))=x
hsDecls (TiDecorate.Dec (HsFunBind loc matches))=concatMap hsDecls matches
hsDecls _ =[]
replaceDecls (TiDecorate.Dec (HsPatBind loc p rhs ds)) ds'
=TiDecorate.Dec (HsPatBind loc p rhs ds')
replaceDecls x ds' =x
isDeclaredIn pn (TiDecorate.Dec (HsPatBind loc p rhs ds))
= fromMaybe False (do (_, rd)<-hsFreeAndDeclaredPNs rhs
(_, dd)<-hsFreeAndDeclaredPNs ds
Just (elem pn (rd `union` dd)))
isDeclaredIn pn _ =False
instance HsDecls HsDeclsP where
hsDecls ds@(Decs x y) = concatMap hsDecls x
replaceDecls ds _ = ds
isDeclaredIn _ ds@(Decs x y) = False
instance HsDecls [HsDeclP] where
hsDecls ds= concatMap hsDecls ds
replaceDecls ds _ = ds -- This should not happen.
isDeclaredIn _ ds = False -- This should not happen.
instance HsDecls HsModuleP where
hsDecls (HsModule loc modName exps imps ds@(Decs x y))=x
replaceDecls (HsModule loc modName exps imps ds) ds'
= HsModule loc modName exps imps ds'
isDeclaredIn pn (HsModule loc modName exps imps ds)
=fromMaybe False (do (rf,rd)<-hsFreeAndDeclaredPNs ds
Just (elem pn rd))
instance HsDecls RhsP where
hsDecls rhs=fromMaybe [] (applyTU (stop_tdTU (failTU `adhocTU` inLet
`adhocTU` inAlt
`adhocTU` inStmt)) rhs)
where inLet ((TiDecorate.Exp (HsLet ds@(Decs x y) e)) ::HsExpP)=Just x
inLet _ =mzero
inAlt ((HsAlt _ p rhs ds@(Decs x y))::HsAlt HsExpP HsPatP HsDeclsP)=Just x
inStmt ((HsLetStmt ds@(Decs x y) _)::HsStmt HsExpP HsPatP HsDeclsP)=Just x
inStmt _=mzero
replaceDecls rhs _ = rhs -- This should not happen.
isDeclaredIn _ _ = False -- This should not happen.
instance HsDecls HsExpP where
hsDecls rhs=fromMaybe [] (applyTU (stop_tdTU (failTU `adhocTU` inLet
`adhocTU` inAlt
`adhocTU` inStmt)) rhs)
where inLet ((TiDecorate.Exp (HsLet ds@(Decs x y) e)) ::HsExpP)=Just x
inLet (TiDecorate.Exp (HsListComp (HsLetStmt ds@(Decs x y) stmts)))=Just x
inLet (TiDecorate.Exp (HsDo (HsLetStmt ds@(Decs x y) stmts)))=Just x
inLet _ =Nothing
inAlt ((HsAlt _ p rhs ds@(Decs x y))::HsAlt HsExpP HsPatP HsDeclsP)=Just x
inStmt ((HsLetStmt ds@(Decs x y) _)::HsStmt HsExpP HsPatP HsDeclsP)=Just x
inStmt _=Nothing
replaceDecls (TiDecorate.Exp (HsLet ds e)) ds'
=if ds'== Decs [] ([], [])
then e
else (TiDecorate.Exp (HsLet ds' e))
replaceDecls (TiDecorate.Exp (HsListComp (HsLetStmt ds stmts))) ds'@(Decs x y)
=if x==[] && isLast stmts
then (TiDecorate.Exp (HsList [fromJust (expInLast stmts)]))
else (TiDecorate.Exp (HsListComp (HsLetStmt ds' stmts)))
where
isLast (HsLast e)=True
isLast _=False
expInLast (HsLast e)=Just e
expInLast _=Nothing
replaceDecls (TiDecorate.Exp (HsDo (HsLetStmt ds stmts))) ds'@(Decs x y)
=if x==[]
then (TiDecorate.Exp (HsDo stmts))
else (TiDecorate.Exp (HsDo (HsLetStmt ds' stmts)))
replaceDecls x ds'=x
isDeclaredIn pn (TiDecorate.Exp (HsLambda pats body))
= fromMaybe False (do (pf,pd) <-hsFreeAndDeclaredPNs pats
Just (elem pn pd))
isDeclaredIn pn (TiDecorate.Exp (HsLet decls e))
=fromMaybe False (do (df,dd)<- hsFreeAndDeclaredPNs decls
Just (elem pn dd))
isDeclaredIn pn _=False
instance HsDecls HsStmtP where
hsDecls (HsLetStmt ds@(Decs x y) stmts)=x
hsDecls _ = []
replaceDecls (HsLetStmt ds stmts) ds'@(Decs x y)
= if x/=[] then HsLetStmt ds' stmts
else stmts
isDeclaredIn pn (HsGenerator _ pat exp stmts) -- Claus
=fromMaybe False (do (pf,pd) <-hsFreeAndDeclaredPNs pat
Just (elem pn pd))
isDeclaredIn pn (HsLetStmt decls stmts)
=fromMaybe False (do (df,dd) <-hsFreeAndDeclaredPNs decls
Just (elem pn dd))
isDeclaredIn pn _=False
instance HsDecls HsAltP where
hsDecls (HsAlt _ p rhs ds@(Decs x y))=x
replaceDecls (HsAlt loc p rhs ds) ds'=HsAlt loc p rhs ds'
isDeclaredIn pn (HsAlt _ pat exp decls)
=fromMaybe False ( do (pf,pd) <- hsFreeAndDeclaredPNs pat
(df,dd) <- hsFreeAndDeclaredPNs decls
Just (elem pn (pd `union` dd)))
-------------------------------------------------------------------------------------------
class (Term a)=>FindEntity a where
-- | Returns True is a syntax phrase, say a, is part of another syntax phrase, say b.
findEntity:: (Term b)=> a->b->Bool
instance FindEntity HsExpP where
findEntity e b
=(fromMaybe False)(applyTU (once_tdTU (failTU `adhocTU` inExp)) b)
where
inExp (e1::HsExpP)
| e==e1 =Just True
inExp _ =Nothing
instance FindEntity PName where
findEntity pn b
=(fromMaybe False)(applyTU (once_tdTU (failTU `adhocTU` worker)) b)
where
worker (PNT pname _ _ )
|pname==pn= Just True
worker _ =Nothing
instance FindEntity PNT where
findEntity pnt b
=(fromMaybe False)(applyTU (once_tdTU (failTU `adhocTU` worker)) b)
where
worker (pnt1::PNT)
|sameOccurrence pnt pnt1 = Just True
worker _ =Nothing
-----------------------------------------------------------------------------------------
-- Get the toks for a declaration, and adjust its offset to 0.
getDeclAndToks pn incSig toks t
= ghead "getDeclAndToks" $ applyTU (stop_tdTU (failTU `adhocTU` inDecls)) t
where
inDecls decls
|snd (break (defines pn) decls) /=[]
= return $ getDeclAndToks' pn incSig decls toks
inDecls x = mzero
getDeclAndToks' pn incSig decls toks
= let typeSig = if (not incSig)
then Nothing
else let (decls1,decls2) =break (definesTypeSig pn) decls
in if decls2==[] then Nothing else Just (ghead "getDeclAndToks" decls2)
(decls1', decls2') = break (defines pn) decls
decl = if decls2' == [] then error "getDeclAndToks:: declaration does not exisit"
else ghead "getDeclAndToks2" decls2'
offset = getOffset toks (fst (startEndLoc toks decl))
declToks =removeOffset offset $ getToks' decl toks
sigToks = case typeSig of
Nothing -> []
Just (sig@(TiDecorate.Dec (HsTypeSig _ [i] _ _)))-> removeOffset offset $ getToks' sig toks
Just (TiDecorate.Dec (HsTypeSig loc is c ty))-> let sig' =(TiDecorate.Dec (HsTypeSig loc0 [nameToPNT (pNtoName pn)] c ty))
in tokenise (Pos 0 (-1111) 1) 0 True $ prettyprint sig'++"\n"
in (if isJust typeSig then [fromJust typeSig, decl] else [decl], (sigToks ++ declToks))
getToks' decl toks
= let (startPos, endPos) = startEndLocIncComments toks decl
(toks1, _) =let(ts1, (t:ts2'))= break (\t -> tokenPos t == endPos) toks
in (ts1++[t], ts2')
in dropWhile (\t -> tokenPos t /= startPos || isNewLn t) toks1
removeOffset offset toks
= let groupedToks = groupTokensByLine toks
in concatMap (doRmWhites offset) groupedToks
{-
-- THIS FUNCTION SHOULD NOT BE IN THE API.
-- | Get the list of tokens which represent the declaration that defines pn.
getDeclToks :: PName -- ^ The identifier.
-> Bool -- ^ True means type signature should be included.
-> [HsDeclP] -- ^ The declaration list in which the identifier is defined.
-> [PosToken] -- ^ The input token stream.
-> [PosToken] -- ^ The result.
-}
--- IMPORTANT: GET RID OF THE -1111*****************
getDeclToks pn incSig decls toks
= let (decls1,decls2) =break (definesTypeSig pn) decls
typeSig = if decls2==[] then Nothing else Just (ghead "getDeclToks1" decls2) --There may or may not type signature.
(decls1', decls2') = break (defines pn) decls
decl = if decls2' == [] then error "getDeclToks:: declaration does not exisit"
else ghead "getDeclToks2" decls2'
declToks = getToks' decl toks
sigToks
= case typeSig of
Nothing -> []
Just (sig@(TiDecorate.Dec (HsTypeSig _ [i] _ _)))-> getToks' sig toks
Just (TiDecorate.Dec (HsTypeSig loc is c ty))-> let sig' =(TiDecorate.Dec (HsTypeSig loc0 [nameToPNT (pNtoName pn)] c ty))
in tokenise (Pos 0 (-1111) 1) 0 True $ prettyprint sig'++"\n"
in if incSig then sigToks ++ declToks else declToks
where
getToks' decl toks
= let (startPos, endPos) = startEndLocIncComments toks decl
(toks1, _) =let(ts1, (t:ts2'))= break (\t -> tokenPos t == endPos) toks
in (ts1++[t], ts2')
in dropWhile (\t -> tokenPos t /= startPos || isNewLn t) toks1
inRegion t toks beginPos endPos
=let (sLoc', eLoc')={-getStartEndLoc-} startEndLoc toks t
(sLoc,eLoc)=extendBothSides toks sLoc' eLoc' isWhite isWhite
in beginPos>=sLoc && beginPos<=eLoc
applyRefac refac Nothing fileName
= do (inscps, exps, mod, toks)<-parseSourceFile fileName
(mod',((toks',m),_))<-runStateT (refac (inscps, exps, mod)) ((toks,False), (-1000,0))
return ((fileName,m),(toks',mod'))
applyRefac refac (Just (inscps, exps, mod, toks)) fileName
= do (mod',((toks',m),_))<-runStateT (refac (inscps, exps, mod)) ((toks,False), (-1000,0))
return ((fileName,m),(toks', mod'))
applyRefacToClientMods refac fileName
= do clients <- clientModsAndFiles =<< fileNameToModName fileName
mapM (applyRefac refac Nothing) (map snd clients)
{-
--this function try to find an identifier through a textual interface. More details will be added.
findPNByPath::String->HsModuleP->Either String PName
findPNByPath path mod
= case findDeclByPath path mod of
Left errMsg -> Left errMsg
Right decl -> Right $ head $ definedPNs decl
where
findDeclByPath path mod
= let names = extractPath path
in findPNByPath' names (hsModDecls mod)
extractPath path = extractPath' [] path
extractPath' r path =
case span (/='.') path of
(name, "") -> r++[name]
(name, subPath) -> extractPath' (r++[name]) (tail subPath)
findPNByPath' (name:names) [] = Left "Can not find the declaration"
findPNByPath' (name:names) decls
= let decl = findDeclByName name decls
in if decl==[] then Left "Can not find the declaration"
else if names==[] then Right (head decl)
else findPNByPath' names (hsDecls (head decl))
findDeclByName name decls = filter definesName decls
where
definesName (Dec (HsFunBind _ ((HsMatch _ (PNT pn _ _) _ _ _):_)))
= pNtoName pn == name
definesName (Dec (HsPatBind _ p _ _)) = name == (pNtoName.head.hsPNs) p
definesName _ = False
-}
-- THe following functions were added Chris Brown to work specifically with the Typed AST
-- created by the type checker
------------------------------------------------------------------------------------------
-- | Collect the free and declared variables (in the PName format) in a given syntax phrase t.
-- In the result, the first list contains the free variables, and the second list contains the declared variables.
removeFromInts :: (MonadPlus m, Term t) => t -> m t
removeFromInts mod
= do
let dName = findDname mod
newMod <- removeFromInts' dName mod
return newMod
where
findDname t
= fromMaybe (defaultExp)
(applyTU (once_tdTU (failTU `adhocTU` findDname))t )
where
findDname (TiDecorate.Exp (HsApp (TiDecorate.Exp (HsApp (TiSpec (HsVar (PNT (PN (UnQual "fromInteger") _)_ _))_ _) d)) x)::HsExpP)
= Just d
findDname _ = mzero
removeFromInts' :: (MonadPlus m, Term t) => HsExpP -> t -> m t
removeFromInts' dName t
= applyTP (full_tdTP (idTP `adhocTP` remFromInt `adhocTP` (remFromPat dName))) t
where
remFromInt (TiDecorate.Exp (HsApp (TiDecorate.Exp (HsApp (TiSpec (HsVar (PNT (PN (UnQual "fromInteger") _)_ _))_ _) d)) x)::HsExpP)
= return x
remFromInt e@(_) = return e
remFromPat (TiDecorate.Exp (HsId x)) ((HsMatch t1 t2 ((TiDecorate.Pat (HsPId y)):ps) e ds)::HsMatchI PNT HsExpP HsPatP HsDeclsP)
| x == y = return (HsMatch t1 t2 ps e ds)
remFromPat _ e@(_) = return e
------------------------------------------------------------------------------------------
-- | Takes a [HsDeclP] which is a data type and returns the data type name
getDataName :: Term t => t -> String
getDataName t
= fromMaybe ""
(applyTU (once_tdTU (failTU `adhocTU` inData)) t)
where
inData ((HsTyCon (PNT (PN (UnQual x)_) _ _)) :: TI PNT HsTypeP)
= Just x
inData _ = mzero
------------------------------------------------------------------------------------------
-- | CheckTypes takes a string represetation of a type. List types must be supplied in the form
-- | "[]Int" or "[]a"
-- | CheckTypes checks to see whether the type occurs within the syntax phrase
-- | (returns True if an identifier within the syntax phrase is of the type in question
checkTypes :: Term t => String -> t -> Bool
checkTypes ty t
= fromMaybe False ( applyTU (once_tdTU (failTU `adhocTU` inType)) t)
where
inType ((HsTyCon (PNT (PN (UnQual x) _) _ _)) :: TI PNT (HsTypeI PNT))
= if x == ty then Just True else mzero
inType _ = mzero
--| checkTypes takes a string representation of a type, and the name of a pattern match or function
--| checkTypes calls the ghc typechecker, and returns True if the data type appears within the
--| type of the function.
--| checkTypes also removes the return type of the fuction/pattern as we are only interested in
--| the type of the arguments.
-- checkTypes :: String -> String -> Bool
checkTypes dat name ses = dat `elem` (ghcTypeCheck1 ses name)
-- | getPNs take a declaration and returns all the PNames within that declaration
getPNs :: HsDeclP -> [PName]
getPNs (TiDecorate.Dec (HsFunBind _ (m:ms) ))
= checkMatch (m:ms)
where checkMatch [] = []
checkMatch ((HsMatch _ _ (p:ps) _ _):ms)
| (getPN p) /= defaultPN = (getPN p) : checkMatch ms
| otherwise = checkMatch ms
-- | getPNPats takes an expression and returns a list of PNames that occur
-- | within that expression.
getPNPats :: HsExpP -> [PName]
getPNPats (TiDecorate.Exp (HsCase e pats))
= checkAlt pats
where checkAlt [] = []
checkAlt ((HsAlt loc p e2 ds):ps)
| p /= (TiDecorate.Pat HsPWildCard) = (getPN p) : checkAlt ps
| otherwise = checkAlt ps
-- | getPN takes a pattern and returns the PName belonging to that Pattern.
getPN :: (Term t) => t -> PName
getPN p
= fromMaybe (defaultPN)
(applyTU (once_tdTU (failTU `adhocTU` inPat)) p)
where
inPat (pat::PName)
= Just pat
inPat _ = Nothing
-- | mapASTOverTAST maps the normal AST over the type decorated AST, preserving the type information
-- | but also preserving the information from the normal AST. This is to remove the things that the
-- | type checker places into the AST to resolve types. Such as dictionaries and fromIntegers.
-- | this function is called automatically when you parse a function.
mapASTOverTAST :: (MonadPlus m, Term t, Term t1) => t -> t1 -> m t1
mapASTOverTAST ast tast
= applyTP (full_tdTP (idTP `adhocTP` inTAST)) tast
where
inTAST a@(TiDecorate.Exp (HsApp e1 e2))
= do
x <- mapASTOverTAST ast e1
y <- mapASTOverTAST ast e2
if x == defaultExp then return y
else if y == defaultExp then return x
else return a
inTAST a@(TiSpec i _ _)
= do
return $ findExpAst ast a
inTAST a@(_) = return a
inTPAT a@(TiPSpec i _ _)
= do
return $ findPatAst ast a
findPatAst :: Term t => t -> HsPatP -> HsPatP
findPatAst ast pat
= fromMaybe (defaultPat)
(applyTU (once_tdTU (failTU `adhocTU` (inPat pat))) ast)
where
inPat a@(TiPSpec i _ _) b@(PosSyntax.Pat (HsPId i2))
| i == i2 = Just a
| otherwise = mzero
inPat a b = mzero
findExpAst :: Term t => t -> HsExpP -> HsExpP
findExpAst ast exp
= fromMaybe (defaultExp)
( applyTU (once_tdTU (failTU `adhocTU` (inExp exp))) ast)
where
inExp a@(TiSpec i _ _) b@(PosSyntax.Exp (HsInfixApp e1 i2 e2))
| i == i2 = Just a
| otherwise = mzero
inExp a@(TiSpec i _ _) b@(PosSyntax.Exp (HsLeftSection e i2))
| i == i2 = Just a
| otherwise = mzero
inExp a@(TiSpec i _ _) b@(PosSyntax.Exp (HsRightSection i2 e))
| i == i2 = Just a
| otherwise = mzero
inExp a@(TiSpec i _ _) b@(PosSyntax.Exp (HsId i2))
| i == i2 = Just a
| otherwise = mzero
inExp a b = mzero
|
kmate/HaRe
|
old/refactorer/RefacTypeUtils.hs
|
bsd-3-clause
| 142,300 | 97 | 31 | 44,912 | 37,212 | 19,433 | 17,779 | -1 | -1 |
import System.Posix.Time
import System.Posix.Unistd
import System.Posix.Signals
main = do start <- epochTime
blockSignals reservedSignals -- see #4504
sleep 1
finish <- epochTime
let slept = finish - start
if slept >= 1 && slept <= 2
then putStrLn "OK"
else do putStr "Started: "
print start
putStr "Finished: "
print finish
putStr "Slept: "
print slept
|
rimmington/unix
|
tests/libposix/posix006.hs
|
bsd-3-clause
| 544 | 0 | 10 | 246 | 126 | 57 | 69 | 16 | 2 |
module T5327 where
newtype Size = Size Int
{-# INLINABLE val2 #-}
val2 = Size 17
-- In the core, we should see a comparison against 34#, i.e. constant
-- folding should have happened. We actually see it twice: Once in f's
-- definition, and once in its unfolding.
f n = case val2 of Size s -> s + s > n
|
wxwxwwxxx/ghc
|
testsuite/tests/simplCore/should_compile/T5327.hs
|
bsd-3-clause
| 307 | 0 | 9 | 67 | 53 | 30 | 23 | 4 | 1 |
{-
Copyright (c) 2008, 2009
Russell O'Connor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-}
module Data.Colour.Internal where
import Data.List
import qualified Data.Colour.Chan as Chan
import Data.Colour.Chan (Chan(Chan))
import Data.Monoid
data Red = Red
data Green = Green
data Blue = Blue
-- |This type represents the human preception of colour.
-- The @a@ parameter is a numeric type used internally for the
-- representation.
--
-- The 'Monoid' instance allows one to add colours, but beware that adding
-- colours can take you out of gamut. Consider using 'blend' whenever
-- possible.
-- Internally we store the colour in linear ITU-R BT.709 RGB colour space.
data Colour a = RGB !(Chan Red a) !(Chan Green a) !(Chan Blue a)
deriving (Eq)
-- |Change the type used to represent the colour coordinates.
colourConvert :: (Fractional b, Real a) => Colour a -> Colour b
colourConvert (RGB r g b) =
RGB (Chan.convert r) (Chan.convert g) (Chan.convert b)
-- 'black' is the colourless colour. It is the identity colour in
-- additive colour spaces.
black :: (Num a) => Colour a
black = RGB Chan.empty Chan.empty Chan.empty
instance (Num a) => Monoid (Colour a) where
mempty = black
(RGB r1 g1 b1) `mappend` (RGB r2 g2 b2) =
RGB (r1 `Chan.add` r2) (g1 `Chan.add` g2) (b1 `Chan.add` b2)
mconcat l = RGB (Chan.sum lr) (Chan.sum lg) (Chan.sum lb)
where
(lr,lg,lb) = unzip3 (map toRGB l)
toRGB (RGB r g b) = (r,g,b)
data Alpha = Alpha
-- |This type represents a 'Colour' that may be semi-transparent.
--
-- The 'Monoid' instance allows you to composite colours.
--
-- >x `mappend` y == x `over` y
--
-- To get the (pre-multiplied) colour channel of an 'AlphaColour' @c@,
-- simply composite @c@ over black.
--
-- >c `over` black
-- Internally we use a premultiplied-alpha representation.
data AlphaColour a = RGBA !(Colour a) !(Chan Alpha a) deriving (Eq)
-- |This 'AlphaColour' is entirely transparent and has no associated
-- colour channel.
transparent :: (Num a) => AlphaColour a
transparent = RGBA (RGB Chan.empty Chan.empty Chan.empty) Chan.empty
-- |Change the type used to represent the colour coordinates.
alphaColourConvert :: (Fractional b, Real a) =>
AlphaColour a -> AlphaColour b
alphaColourConvert (RGBA c a) = RGBA (colourConvert c) (Chan.convert a)
-- |Creates an opaque 'AlphaColour' from a 'Colour'.
opaque :: (Num a) => Colour a -> AlphaColour a
opaque c = RGBA c Chan.full
-- |Returns an 'AlphaColour' more transparent by a factor of @o@.
dissolve :: (Num a) => a -> AlphaColour a -> AlphaColour a
dissolve o (RGBA c a) = RGBA (darken o c) (Chan.scale o a)
-- |Creates an 'AlphaColour' from a 'Colour' with a given opacity.
--
-- >c `withOpacity` o == dissolve o (opaque c)
withOpacity :: (Num a) => Colour a -> a -> AlphaColour a
c `withOpacity` o = RGBA (darken o c) (Chan o)
--------------------------------------------------------------------------
-- Blending
--------------------------------------------------------------------------
class AffineSpace f where
-- |Compute a affine Combination (weighted-average) of points.
-- The last parameter will get the remaining weight.
-- e.g.
--
-- >affineCombo [(0.2,a), (0.3,b)] c == 0.2*a + 0.3*b + 0.5*c
--
-- Weights can be negative, or greater than 1.0; however, be aware
-- that non-convex combinations may lead to out of gamut colours.
affineCombo :: (Num a) => [(a,f a)] -> f a -> f a
-- |Compute the weighted average of two points.
-- e.g.
--
-- >blend 0.4 a b = 0.4*a + 0.6*b
--
-- The weight can be negative, or greater than 1.0; however, be aware
-- that non-convex combinations may lead to out of gamut colours.
blend :: (Num a, AffineSpace f) => a -> f a -> f a -> f a
blend weight c1 c2 = affineCombo [(weight,c1)] c2
instance AffineSpace Colour where
affineCombo l z =
foldl1' mappend [darken w a | (w,a) <- (1-total,z):l]
where
total = sum $ map fst l
instance AffineSpace AlphaColour where
affineCombo l z =
foldl1' rgbaAdd [dissolve w a | (w,a) <- (1-total,z):l]
where
total = sum $ map fst l
--------------------------------------------------------------------------
-- composite
--------------------------------------------------------------------------
class ColourOps f where
-- |@c1 \`over\` c2@ returns the 'Colour' created by compositing the
-- 'AlphaColour' @c1@ over @c2@, which may be either a 'Colour' or
-- 'AlphaColour'.
over :: (Num a) => AlphaColour a -> f a -> f a
-- |@darken s c@ blends a colour with black without changing it's opacity.
--
-- For 'Colour', @darken s c = blend s c mempty@
darken :: (Num a) => a -> f a -> f a
instance ColourOps Colour where
(RGBA (RGB r0 g0 b0) (Chan a0)) `over` (RGB r1 g1 b1) =
RGB (Chan.over r0 a0 r1)
(Chan.over g0 a0 g1)
(Chan.over b0 a0 b1)
darken s (RGB r g b) = RGB (Chan.scale s r)
(Chan.scale s g)
(Chan.scale s b)
instance ColourOps AlphaColour where
c0@(RGBA _ a0@(Chan a0')) `over` (RGBA c1 a1) =
RGBA (c0 `over` c1) (Chan.over a0 a0' a1)
darken s (RGBA c a) = RGBA (darken s c) a
-- | 'AlphaColour' forms a monoid with 'over' and 'transparent'.
instance (Num a) => Monoid (AlphaColour a) where
mempty = transparent
mappend = over
-- | @c1 \`atop\` c2@ returns the 'AlphaColour' produced by covering
-- the portion of @c2@ visible by @c1@.
-- The resulting alpha channel is always the same as the alpha channel
-- of @c2@.
--
-- >c1 `atop` (opaque c2) == c1 `over` (opaque c2)
-- >AlphaChannel (c1 `atop` c2) == AlphaChannel c2
atop :: (Fractional a) => AlphaColour a -> AlphaColour a -> AlphaColour a
atop (RGBA c0 (Chan a0)) (RGBA c1 (Chan a1)) =
RGBA (darken a1 c0 `mappend` darken (1-a0) c1) (Chan a1)
-- |'round's and then clamps @x@ between 0 and 'maxBound'.
quantize :: (RealFrac a1, Integral a, Bounded a) => a1 -> a
quantize x | x <= fromIntegral l = l
| fromIntegral h <= x = h
| otherwise = round x
where
l = minBound
h = maxBound
{- Avoid using -}
-- |Returns the opacity of an 'AlphaColour'.
alphaChannel :: AlphaColour a -> a
alphaChannel (RGBA _ (Chan a)) = a
-- |Returns the colour of an 'AlphaColour'.
-- @colourChannel transparent@ is undefined and may result in @nan@ or an
-- error.
-- Its use is discouraged.
-- If you are desperate, use
--
-- >darken (recip (alphaChannel c)) (c `over` black)
colourChannel :: (Fractional a) => AlphaColour a -> Colour a
colourChannel (RGBA c (Chan a)) = darken (recip a) c
--------------------------------------------------------------------------
-- not for export
--------------------------------------------------------------------------
rgbaAdd (RGBA c1 a1) (RGBA c2 a2) =
RGBA (c1 `mappend` c2) (a1 `Chan.add` a2)
|
haasn/colour
|
Data/Colour/Internal.hs
|
mit
| 7,741 | 0 | 12 | 1,500 | 1,785 | 955 | 830 | 90 | 1 |
module Main
( main
)
where
-- doctest
import qualified Test.DocTest as DocTest
main :: IO ()
main =
DocTest.doctest
[ "-isrc"
, "src/JoinList.hs"
, "src/Scrabble.hs"
]
|
mauriciofierrom/cis194-homework
|
homework07/test/examples/Main.hs
|
mit
| 195 | 0 | 6 | 54 | 47 | 29 | 18 | 9 | 1 |
{-# LANGUAGE CPP, ForeignFunctionInterface #-}
module Regex where
import Foreign
import Foreign.C.Types
#include <pcre.h>
newtype PCREOption = PCREOption { unPCREOption :: CInt }
deriving (Eq, Show)
|
zhangjiji/real-world-haskell
|
ch17/Regex-hsc.hs
|
mit
| 222 | 0 | 6 | 49 | 39 | 26 | 13 | 6 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.