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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# OPTIONS -fno-warn-orphans #-}
#include "HsConfigure.h"
-- #hide
module Data.Time.Format.Parse
(
-- * UNIX-style parsing
#if LANGUAGE_Rank2Types
parseTime, readTime, readsTime,
#endif
ParseTime(..)
) where
import Data.Time.Clock.POSIX
import Data.Time.Clock
import Data.Time.Calendar
import Data.Time.Calendar.OrdinalDate
import Data.Time.Calendar.WeekDate
import Data.Time.LocalTime
#if LANGUAGE_Rank2Types
import Control.Monad
#endif
import Data.Char
import Data.Fixed
import Data.List
import Data.Maybe
import Data.Ratio
import System.Locale
#if LANGUAGE_Rank2Types
import Text.ParserCombinators.ReadP hiding (char, string)
#endif
#if LANGUAGE_Rank2Types
-- | Case-insensitive version of 'Text.ParserCombinators.ReadP.char'.
char :: Char -> ReadP Char
char c = satisfy (\x -> toUpper c == toUpper x)
-- | Case-insensitive version of 'Text.ParserCombinators.ReadP.string'.
string :: String -> ReadP String
string this = do s <- look; scan this s
where
scan [] _ = do return this
scan (x:xs) (y:ys) | toUpper x == toUpper y = do _ <- get; scan xs ys
scan _ _ = do pfail
#endif
-- | Convert string to upper case.
up :: String -> String
up = map toUpper
-- | The class of types which can be parsed given a UNIX-style time format
-- string.
class ParseTime t where
-- | Builds a time value from a parsed input string.
-- If the input does not include all the information needed to
-- construct a complete value, any missing parts should be taken
-- from 1970-01-01 00:00:00 +0000 (which was a Thursday).
-- In the absence of @%C@ or @%Y@, century is 1969 - 2068.
buildTime :: TimeLocale -- ^ The time locale.
-> [(Char,String)] -- ^ Pairs of format characters and the
-- corresponding part of the input.
-> t
#if LANGUAGE_Rank2Types
-- | Parses a time value given a format string.
-- Supports the same %-codes as 'formatTime', including @%-@, @%_@ and @%0@ modifiers.
-- Leading and trailing whitespace is accepted. Case is not significant.
-- Some variations in the input are accepted:
--
-- [@%z@] accepts any of @-HHMM@ or @-HH:MM@.
--
-- [@%Z@] accepts any string of letters, or any of the formats accepted by @%z@.
--
-- [@%0Y@] accepts exactly four digits.
--
-- [@%0G@] accepts exactly four digits.
--
-- [@%0C@] accepts exactly two digits.
--
-- [@%0f@] accepts exactly two digits.
--
parseTime :: ParseTime t =>
TimeLocale -- ^ Time locale.
-> String -- ^ Format string.
-> String -- ^ Input string.
-> Maybe t -- ^ The time value, or 'Nothing' if the input could
-- not be parsed using the given format.
parseTime l fmt s = case goodReadsTime l fmt s of
[t] -> Just t
_ -> Nothing
-- | Parse a time value given a format string. Fails if the input could
-- not be parsed using the given format. See 'parseTime' for details.
readTime :: ParseTime t =>
TimeLocale -- ^ Time locale.
-> String -- ^ Format string.
-> String -- ^ Input string.
-> t -- ^ The time value.
readTime l fmt s = case goodReadsTime l fmt s of
[t] -> t
[] -> error $ "readTime: no parse of " ++ show s
_ -> error $ "readTime: multiple parses of " ++ show s
goodReadsTime :: ParseTime t =>
TimeLocale -- ^ Time locale.
-> String -- ^ Format string
-> String -- ^ Input string.
-> [t]
goodReadsTime l fmt s = [t | (t,r) <- readsTime l fmt s, all isSpace r]
-- | Parse a time value given a format string. See 'parseTime' for details.
readsTime :: ParseTime t =>
TimeLocale -- ^ Time locale.
-> String -- ^ Format string
-> ReadS t
readsTime l f = readP_to_S (liftM (buildTime l) r)
where r = skipSpaces >> parseInput l (parseFormat l f)
--
-- * Internals
--
data Padding = NoPadding | SpacePadding | ZeroPadding
deriving Show
type DateFormat = [DateFormatSpec]
data DateFormatSpec = Value (Maybe Padding) Char
| WhiteSpace
| Literal Char
deriving Show
parseFormat :: TimeLocale -> String -> DateFormat
parseFormat l = p
where p "" = []
p ('%': '-' : c :cs) = (pc (Just NoPadding) c) ++ p cs
p ('%': '_' : c :cs) = (pc (Just SpacePadding) c) ++ p cs
p ('%': '0' : c :cs) = (pc (Just ZeroPadding) c) ++ p cs
p ('%': c :cs) = (pc Nothing c) ++ p cs
p (c:cs) | isSpace c = WhiteSpace : p cs
p (c:cs) = Literal c : p cs
pc _ 'c' = p (dateTimeFmt l)
pc _ 'R' = p "%H:%M"
pc _ 'T' = p "%H:%M:%S"
pc _ 'X' = p (timeFmt l)
pc _ 'r' = p (time12Fmt l)
pc _ 'D' = p "%m/%d/%y"
pc _ 'F' = p "%Y-%m-%d"
pc _ 'x' = p (dateFmt l)
pc _ 'h' = p "%b"
pc _ '%' = [Literal '%']
pc mpad c = [Value mpad c]
parseInput :: TimeLocale -> DateFormat -> ReadP [(Char,String)]
parseInput _ [] = return []
parseInput l (Value mpad c:ff) = do
s <- parseValue l mpad c
r <- parseInput l ff
return ((c,s):r)
parseInput l (Literal c:ff) = do
_ <- char c
parseInput l ff
parseInput l (WhiteSpace:ff) = do
_ <- satisfy isSpace
case ff of
(WhiteSpace:_) -> return ()
_ -> skipSpaces
parseInput l ff
-- | Get the string corresponding to the given format specifier.
parseValue :: TimeLocale -> Maybe Padding -> Char -> ReadP String
parseValue l mpad c =
case c of
-- century
'C' -> digits SpacePadding 2
'f' -> digits SpacePadding 2
-- year
'Y' -> digits SpacePadding 4
'G' -> digits SpacePadding 4
-- year of century
'y' -> digits ZeroPadding 2
'g' -> digits ZeroPadding 2
-- month of year
'B' -> oneOf (map fst (months l))
'b' -> oneOf (map snd (months l))
'm' -> digits ZeroPadding 2
-- day of month
'd' -> digits ZeroPadding 2
'e' -> digits SpacePadding 2
-- week of year
'V' -> digits ZeroPadding 2
'U' -> digits ZeroPadding 2
'W' -> digits ZeroPadding 2
-- day of week
'u' -> oneOf $ map (:[]) ['1'..'7']
'a' -> oneOf (map snd (wDays l))
'A' -> oneOf (map fst (wDays l))
'w' -> oneOf $ map (:[]) ['0'..'6']
-- day of year
'j' -> digits ZeroPadding 3
-- dayhalf of day (i.e. AM or PM)
'P' -> oneOf (let (am,pm) = amPm l in [am, pm])
'p' -> oneOf (let (am,pm) = amPm l in [am, pm])
-- hour of day (i.e. 24h)
'H' -> digits ZeroPadding 2
'k' -> digits SpacePadding 2
-- hour of dayhalf (i.e. 12h)
'I' -> digits ZeroPadding 2
'l' -> digits SpacePadding 2
-- minute of hour
'M' -> digits ZeroPadding 2
-- second of minute
'S' -> digits ZeroPadding 2
-- picosecond of second
'q' -> digits ZeroPadding 12
'Q' -> liftM2 (:) (char '.') (munch isDigit) <++ return ""
-- time zone
'z' -> numericTZ
'Z' -> munch1 isAlpha <++
numericTZ <++
return "" -- produced by %Z for LocalTime
-- seconds since epoch
's' -> (char '-' >> liftM ('-':) (munch1 isDigit))
<++ munch1 isDigit
_ -> fail $ "Unknown format character: " ++ show c
where
oneOf = choice . map string
digitsforce ZeroPadding n = count n (satisfy isDigit)
digitsforce SpacePadding _n = skipSpaces >> many1 (satisfy isDigit)
digitsforce NoPadding _n = many1 (satisfy isDigit)
digits pad = digitsforce (fromMaybe pad mpad)
numericTZ = do s <- choice [char '+', char '-']
h <- digitsforce ZeroPadding 2
optional (char ':')
m <- digitsforce ZeroPadding 2
return (s:h++m)
#endif
--
-- * Instances for the time package types
--
data DayComponent = Century Integer -- century of all years
| CenturyYear Integer -- 0-99, last two digits of both real years and week years
| YearMonth Int -- 1-12
| MonthDay Int -- 1-31
| YearDay Int -- 1-366
| WeekDay Int -- 1-7 (mon-sun)
| YearWeek WeekType Int -- 1-53 or 0-53
data WeekType = ISOWeek | SundayWeek | MondayWeek
instance ParseTime Day where
buildTime l = buildDay . concatMap (uncurry f)
where
f c x =
case c of
-- %C: century (all but the last two digits of the year), 00 - 99
'C' -> [Century (read x)]
-- %f century (all but the last two digits of the year), 00 - 99
'f' -> [Century (read x)]
-- %Y: year
'Y' -> let y = read x in [Century (y `div` 100), CenturyYear (y `mod` 100)]
-- %G: year for Week Date format
'G' -> let y = read x in [Century (y `div` 100), CenturyYear (y `mod` 100)]
-- %y: last two digits of year, 00 - 99
'y' -> [CenturyYear (read x)]
-- %g: last two digits of year for Week Date format, 00 - 99
'g' -> [CenturyYear (read x)]
-- %B: month name, long form (fst from months locale), January - December
'B' -> [YearMonth (1 + fromJust (elemIndex (up x) (map (up . fst) (months l))))]
-- %b: month name, short form (snd from months locale), Jan - Dec
'b' -> [YearMonth (1 + fromJust (elemIndex (up x) (map (up . snd) (months l))))]
-- %m: month of year, leading 0 as needed, 01 - 12
'm' -> [YearMonth (read x)]
-- %d: day of month, leading 0 as needed, 01 - 31
'd' -> [MonthDay (read x)]
-- %e: day of month, leading space as needed, 1 - 31
'e' -> [MonthDay (read x)]
-- %V: week for Week Date format, 01 - 53
'V' -> [YearWeek ISOWeek (read x)]
-- %U: week number of year, where weeks start on Sunday (as sundayStartWeek), 01 - 53
'U' -> [YearWeek SundayWeek (read x)]
-- %W: week number of year, where weeks start on Monday (as mondayStartWeek), 01 - 53
'W' -> [YearWeek MondayWeek (read x)]
-- %u: day for Week Date format, 1 - 7
'u' -> [WeekDay (read x)]
-- %a: day of week, short form (snd from wDays locale), Sun - Sat
'a' -> [WeekDay (1 + (fromJust (elemIndex (up x) (map (up . snd) (wDays l))) + 6) `mod` 7)]
-- %A: day of week, long form (fst from wDays locale), Sunday - Saturday
'A' -> [WeekDay (1 + (fromJust (elemIndex (up x) (map (up . fst) (wDays l))) + 6) `mod` 7)]
-- %w: day of week number, 0 (= Sunday) - 6 (= Saturday)
'w' -> [WeekDay (((read x + 6) `mod` 7) + 1)]
-- %j: day of year for Ordinal Date format, 001 - 366
'j' -> [YearDay (read x)]
_ -> []
buildDay cs = rest cs
where
y = let
d = safeLast 70 [x | CenturyYear x <- cs]
c = safeLast (if d >= 69 then 19 else 20) [x | Century x <- cs]
in 100 * c + d
rest (YearMonth m:_) = let d = safeLast 1 [x | MonthDay x <- cs]
in fromGregorian y m d
rest (YearDay d:_) = fromOrdinalDate y d
rest (YearWeek wt w:_) = let d = safeLast 4 [x | WeekDay x <- cs]
in case wt of
ISOWeek -> fromWeekDate y w d
SundayWeek -> fromSundayStartWeek y w (d `mod` 7)
MondayWeek -> fromMondayStartWeek y w d
rest (_:xs) = rest xs
rest [] = rest [YearMonth 1]
safeLast x xs = last (x:xs)
instance ParseTime TimeOfDay where
buildTime l = foldl f midnight
where
f t@(TimeOfDay h m s) (c,x) =
case c of
'P' -> if up x == fst (amPm l) then am else pm
'p' -> if up x == fst (amPm l) then am else pm
'H' -> TimeOfDay (read x) m s
'I' -> TimeOfDay (read x) m s
'k' -> TimeOfDay (read x) m s
'l' -> TimeOfDay (read x) m s
'M' -> TimeOfDay h (read x) s
'S' -> TimeOfDay h m (fromInteger (read x))
'q' -> TimeOfDay h m (mkPico (truncate s) (read x))
'Q' -> if null x then t
else let ps = read $ take 12 $ rpad 12 '0' $ drop 1 x
in TimeOfDay h m (mkPico (truncate s) ps)
_ -> t
where am = TimeOfDay (h `mod` 12) m s
pm = TimeOfDay (if h < 12 then h + 12 else h) m s
rpad :: Int -> a -> [a] -> [a]
rpad n c xs = xs ++ replicate (n - length xs) c
mkPico :: Integer -> Integer -> Pico
mkPico i f = fromInteger i + fromRational (f % 1000000000000)
instance ParseTime LocalTime where
buildTime l xs = LocalTime (buildTime l xs) (buildTime l xs)
instance ParseTime TimeZone where
buildTime _ = foldl f (minutesToTimeZone 0)
where
f t@(TimeZone offset dst name) (c,x) =
case c of
'z' -> zone
'Z' | null x -> t
| isAlpha (head x) -> let y = up x in
case lookup y _TIMEZONES_ of
Just (offset', dst') -> TimeZone offset' dst' y
Nothing -> TimeZone offset dst y
| otherwise -> zone
_ -> t
where zone = TimeZone (readTzOffset x) dst name
instance ParseTime ZonedTime where
buildTime l xs = foldl f (ZonedTime (buildTime l xs) (buildTime l xs)) xs
where
f t@(ZonedTime (LocalTime _ tod) z) (c,x) =
case c of
's' -> let s = fromInteger (read x)
(_,ps) = properFraction (todSec tod) :: (Integer,Pico)
s' = s + fromRational (toRational ps)
in utcToZonedTime z (posixSecondsToUTCTime s')
_ -> t
instance ParseTime UTCTime where
buildTime l = zonedTimeToUTC . buildTime l
-- * Read instances for time package types
#if LANGUAGE_Rank2Types
instance Read Day where
readsPrec _ = readParen False $ readsTime defaultTimeLocale "%Y-%m-%d"
instance Read TimeOfDay where
readsPrec _ = readParen False $ readsTime defaultTimeLocale "%H:%M:%S%Q"
instance Read LocalTime where
readsPrec _ = readParen False $ readsTime defaultTimeLocale "%Y-%m-%d %H:%M:%S%Q"
instance Read TimeZone where
readsPrec _ = readParen False $ readsTime defaultTimeLocale "%Z"
instance Read ZonedTime where
readsPrec n = readParen False $ \s ->
[(ZonedTime t z, r2) | (t,r1) <- readsPrec n s, (z,r2) <- readsPrec n r1]
instance Read UTCTime where
readsPrec n s = [ (zonedTimeToUTC t, r) | (t,r) <- readsPrec n s ]
#endif
readTzOffset :: String -> Int
readTzOffset str =
case str of
(s:h1:h2:':':m1:m2:[]) -> calc s h1 h2 m1 m2
(s:h1:h2:m1:m2:[]) -> calc s h1 h2 m1 m2
_ -> 0
where calc s h1 h2 m1 m2 = sign * (60 * h + m)
where sign = if s == '-' then -1 else 1
h = read [h1,h2]
m = read [m1,m2]
-- Dubious
_TIMEZONES_ :: [(String, (Int, Bool))]
_TIMEZONES_ =
-- New Zealand Daylight-Saving Time
[("NZDT", (readTzOffset "+13:00", True))
-- International Date Line, East
,("IDLE", (readTzOffset "+12:00", False))
-- New Zealand Standard Time
,("NZST", (readTzOffset "+12:00", False))
-- New Zealand Time
,("NZT", (readTzOffset "+12:00", False))
-- Australia Eastern Summer Standard Time
,("AESST", (readTzOffset "+11:00", False))
-- Central Australia Summer Standard Time
,("ACSST", (readTzOffset "+10:30", False))
-- Central Australia Daylight-Saving Time
,("CADT", (readTzOffset "+10:30", True))
-- South Australian Daylight-Saving Time
,("SADT", (readTzOffset "+10:30", True))
-- Australia Eastern Standard Time
,("AEST", (readTzOffset "+10:00", False))
-- East Australian Standard Time
,("EAST", (readTzOffset "+10:00", False))
-- Guam Standard Time, Russia zone 9
,("GST", (readTzOffset "+10:00", False))
-- Melbourne, Australia
,("LIGT", (readTzOffset "+10:00", False))
-- South Australia Standard Time
,("SAST", (readTzOffset "+09:30", False))
-- Central Australia Standard Time
,("CAST", (readTzOffset "+09:30", False))
-- Australia Western Summer Standard Time
,("AWSST", (readTzOffset "+09:00", False))
-- Japan Standard Time, Russia zone 8
,("JST", (readTzOffset "+09:00", False))
-- Korea Standard Time
,("KST", (readTzOffset "+09:00", False))
-- Kwajalein Time
,("MHT", (readTzOffset "+09:00", False))
-- West Australian Daylight-Saving Time
,("WDT", (readTzOffset "+09:00", True))
-- Moluccas Time
,("MT", (readTzOffset "+08:30", False))
-- Australia Western Standard Time
,("AWST", (readTzOffset "+08:00", False))
-- China Coastal Time
,("CCT", (readTzOffset "+08:00", False))
-- West Australian Daylight-Saving Time
,("WADT", (readTzOffset "+08:00", True))
-- West Australian Standard Time
,("WST", (readTzOffset "+08:00", False))
-- Java Time
,("JT", (readTzOffset "+07:30", False))
-- Almaty Summer Time
,("ALMST", (readTzOffset "+07:00", False))
-- West Australian Standard Time
,("WAST", (readTzOffset "+07:00", False))
-- Christmas (Island) Time
,("CXT", (readTzOffset "+07:00", False))
-- Myanmar Time
,("MMT", (readTzOffset "+06:30", False))
-- Almaty Time
,("ALMT", (readTzOffset "+06:00", False))
-- Mawson (Antarctica) Time
,("MAWT", (readTzOffset "+06:00", False))
-- Indian Chagos Time
,("IOT", (readTzOffset "+05:00", False))
-- Maldives Island Time
,("MVT", (readTzOffset "+05:00", False))
-- Kerguelen Time
,("TFT", (readTzOffset "+05:00", False))
-- Afghanistan Time
,("AFT", (readTzOffset "+04:30", False))
-- Antananarivo Summer Time
,("EAST", (readTzOffset "+04:00", False))
-- Mauritius Island Time
,("MUT", (readTzOffset "+04:00", False))
-- Reunion Island Time
,("RET", (readTzOffset "+04:00", False))
-- Mahe Island Time
,("SCT", (readTzOffset "+04:00", False))
-- Iran Time
,("IRT", (readTzOffset "+03:30", False))
-- Iran Time
,("IT", (readTzOffset "+03:30", False))
-- Antananarivo, Comoro Time
,("EAT", (readTzOffset "+03:00", False))
-- Baghdad Time
,("BT", (readTzOffset "+03:00", False))
-- Eastern Europe Daylight-Saving Time
,("EETDST", (readTzOffset "+03:00", True))
-- Hellas Mediterranean Time (?)
,("HMT", (readTzOffset "+03:00", False))
-- British Double Summer Time
,("BDST", (readTzOffset "+02:00", False))
-- Central European Summer Time
,("CEST", (readTzOffset "+02:00", False))
-- Central European Daylight-Saving Time
,("CETDST", (readTzOffset "+02:00", True))
-- Eastern European Time, Russia zone 1
,("EET", (readTzOffset "+02:00", False))
-- French Winter Time
,("FWT", (readTzOffset "+02:00", False))
-- Israel Standard Time
,("IST", (readTzOffset "+02:00", False))
-- Middle European Summer Time
,("MEST", (readTzOffset "+02:00", False))
-- Middle Europe Daylight-Saving Time
,("METDST", (readTzOffset "+02:00", True))
-- Swedish Summer Time
,("SST", (readTzOffset "+02:00", False))
-- British Summer Time
,("BST", (readTzOffset "+01:00", False))
-- Central European Time
,("CET", (readTzOffset "+01:00", False))
-- Dansk Normal Tid
,("DNT", (readTzOffset "+01:00", False))
-- French Summer Time
,("FST", (readTzOffset "+01:00", False))
-- Middle European Time
,("MET", (readTzOffset "+01:00", False))
-- Middle European Winter Time
,("MEWT", (readTzOffset "+01:00", False))
-- Mitteleuropaeische Zeit
,("MEZ", (readTzOffset "+01:00", False))
-- Norway Standard Time
,("NOR", (readTzOffset "+01:00", False))
-- Seychelles Time
,("SET", (readTzOffset "+01:00", False))
-- Swedish Winter Time
,("SWT", (readTzOffset "+01:00", False))
-- Western European Daylight-Saving Time
,("WETDST", (readTzOffset "+01:00", True))
-- Greenwich Mean Time
,("GMT", (readTzOffset "+00:00", False))
-- Universal Time
,("UT", (readTzOffset "+00:00", False))
-- Universal Coordinated Time
,("UTC", (readTzOffset "+00:00", False))
-- Same as UTC
,("Z", (readTzOffset "+00:00", False))
-- Same as UTC
,("ZULU", (readTzOffset "+00:00", False))
-- Western European Time
,("WET", (readTzOffset "+00:00", False))
-- West Africa Time
,("WAT", (readTzOffset "-01:00", False))
-- Fernando de Noronha Summer Time
,("FNST", (readTzOffset "-01:00", False))
-- Fernando de Noronha Time
,("FNT", (readTzOffset "-02:00", False))
-- Brasilia Summer Time
,("BRST", (readTzOffset "-02:00", False))
-- Newfoundland Daylight-Saving Time
,("NDT", (readTzOffset "-02:30", True))
-- Atlantic Daylight-Saving Time
,("ADT", (readTzOffset "-03:00", True))
-- (unknown)
,("AWT", (readTzOffset "-03:00", False))
-- Brasilia Time
,("BRT", (readTzOffset "-03:00", False))
-- Newfoundland Standard Time
,("NFT", (readTzOffset "-03:30", False))
-- Newfoundland Standard Time
,("NST", (readTzOffset "-03:30", False))
-- Atlantic Standard Time (Canada)
,("AST", (readTzOffset "-04:00", False))
-- Atlantic/Porto Acre Summer Time
,("ACST", (readTzOffset "-04:00", False))
-- Eastern Daylight-Saving Time
,("EDT", (readTzOffset "-04:00", True))
-- Atlantic/Porto Acre Standard Time
,("ACT", (readTzOffset "-05:00", False))
-- Central Daylight-Saving Time
,("CDT", (readTzOffset "-05:00", True))
-- Eastern Standard Time
,("EST", (readTzOffset "-05:00", False))
-- Central Standard Time
,("CST", (readTzOffset "-06:00", False))
-- Mountain Daylight-Saving Time
,("MDT", (readTzOffset "-06:00", True))
-- Mountain Standard Time
,("MST", (readTzOffset "-07:00", False))
-- Pacific Daylight-Saving Time
,("PDT", (readTzOffset "-07:00", True))
-- Alaska Daylight-Saving Time
,("AKDT", (readTzOffset "-08:00", True))
-- Pacific Standard Time
,("PST", (readTzOffset "-08:00", False))
-- Yukon Daylight-Saving Time
,("YDT", (readTzOffset "-08:00", True))
-- Alaska Standard Time
,("AKST", (readTzOffset "-09:00", False))
-- Hawaii/Alaska Daylight-Saving Time
,("HDT", (readTzOffset "-09:00", True))
-- Yukon Standard Time
,("YST", (readTzOffset "-09:00", False))
-- Marquesas Time
,("MART", (readTzOffset "-09:30", False))
-- Alaska/Hawaii Standard Time
,("AHST", (readTzOffset "-10:00", False))
-- Hawaii Standard Time
,("HST", (readTzOffset "-10:00", False))
-- Central Alaska Time
,("CAT", (readTzOffset "-10:00", False))
-- Nome Time
,("NT", (readTzOffset "-11:00", False))
-- International Date Line, West
,("IDLW", (readTzOffset "-12:00", False))
]
| jwiegley/ghc-release | libraries/time/Data/Time/Format/Parse.hs | gpl-3.0 | 23,703 | 0 | 24 | 7,273 | 6,625 | 3,635 | 2,990 | 234 | 4 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.ECS.StopTask
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Stops a running task.
--
-- <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_StopTask.html>
module Network.AWS.ECS.StopTask
(
-- * Request
StopTask
-- ** Request constructor
, stopTask
-- ** Request lenses
, stCluster
, stTask
-- * Response
, StopTaskResponse
-- ** Response constructor
, stopTaskResponse
-- ** Response lenses
, strTask
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.ECS.Types
import qualified GHC.Exts
data StopTask = StopTask
{ _stCluster :: Maybe Text
, _stTask :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'StopTask' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'stCluster' @::@ 'Maybe' 'Text'
--
-- * 'stTask' @::@ 'Text'
--
stopTask :: Text -- ^ 'stTask'
-> StopTask
stopTask p1 = StopTask
{ _stTask = p1
, _stCluster = Nothing
}
-- | The short name or full Amazon Resource Name (ARN) of the cluster that hosts
-- the task you want to stop. If you do not specify a cluster, the default
-- cluster is assumed..
stCluster :: Lens' StopTask (Maybe Text)
stCluster = lens _stCluster (\s a -> s { _stCluster = a })
-- | The task UUIDs or full Amazon Resource Name (ARN) entry of the task you would
-- like to stop.
stTask :: Lens' StopTask Text
stTask = lens _stTask (\s a -> s { _stTask = a })
newtype StopTaskResponse = StopTaskResponse
{ _strTask :: Maybe Task
} deriving (Eq, Read, Show)
-- | 'StopTaskResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'strTask' @::@ 'Maybe' 'Task'
--
stopTaskResponse :: StopTaskResponse
stopTaskResponse = StopTaskResponse
{ _strTask = Nothing
}
strTask :: Lens' StopTaskResponse (Maybe Task)
strTask = lens _strTask (\s a -> s { _strTask = a })
instance ToPath StopTask where
toPath = const "/"
instance ToQuery StopTask where
toQuery = const mempty
instance ToHeaders StopTask
instance ToJSON StopTask where
toJSON StopTask{..} = object
[ "cluster" .= _stCluster
, "task" .= _stTask
]
instance AWSRequest StopTask where
type Sv StopTask = ECS
type Rs StopTask = StopTaskResponse
request = post "StopTask"
response = jsonResponse
instance FromJSON StopTaskResponse where
parseJSON = withObject "StopTaskResponse" $ \o -> StopTaskResponse
<$> o .:? "task"
| kim/amazonka | amazonka-ecs/gen/Network/AWS/ECS/StopTask.hs | mpl-2.0 | 3,512 | 0 | 9 | 847 | 517 | 313 | 204 | 62 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ur-PK">
<title>Ruby Scripting</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/jruby/src/main/javahelp/org/zaproxy/zap/extension/jruby/resources/help_ur_PK/helpset_ur_PK.hs | apache-2.0 | 960 | 79 | 66 | 157 | 409 | 207 | 202 | -1 | -1 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE OverloadedStrings #-}
module Socket (watchFile) where
import Control.Concurrent (forkIO, threadDelay)
import Control.Exception (SomeException, catch)
import qualified Data.ByteString.Char8 as BS
import qualified Network.WebSockets as WS
import qualified System.FSNotify.Devel as Notify
import qualified System.FSNotify as Notify
watchFile :: FilePath -> WS.PendingConnection -> IO ()
watchFile watchedFile pendingConnection =
do connection <- WS.acceptRequest pendingConnection
Notify.withManager $ \mgmt ->
do stop <- Notify.treeExtAny mgmt "." ".elm" print
tend connection
stop
tend :: WS.Connection -> IO ()
tend connection =
let
pinger :: Integer -> IO a
pinger n =
do threadDelay (5 * 1000 * 1000)
WS.sendPing connection (BS.pack (show n))
pinger (n + 1)
receiver :: IO ()
receiver =
do _ <- WS.receiveDataMessage connection
receiver
shutdown :: SomeException -> IO ()
shutdown _ =
return ()
in
do _pid <- forkIO (receiver `catch` shutdown)
pinger 1 `catch` shutdown
| rehno-lindeque/elm-reactor | src/backend/Socket.hs | bsd-3-clause | 1,153 | 0 | 15 | 284 | 346 | 180 | 166 | 33 | 1 |
{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE BangPatterns, OverloadedStrings #-}
module SecondTransfer.MainLoop.Logging (
nonce
#ifdef SECONDTRANSFER_MONITORING
,logit
#endif
) where
import System.IO (stderr,openFile)
import qualified System.IO as SIO
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as Bch
-- Logging utilities
--import System.Log.Formatter (simpleLogFormatter)
--import System.Log.Handler (setFormatter, LogHandler)
--import System.Log.Handler.Simple
-- import System.Log.Handler.Syslog (Facility (..), Option (..), openlog)
--import System.Log.Logger
import System.IO.Unsafe (unsafePerformIO)
import System.Clock as Cl
--import Control.Concurrent.MVar
import Control.Concurrent.Chan
import Control.Concurrent
-- Simple thing to have a more generic logging utility
nonce :: ()
nonce = undefined
-- configureLoggingToSyslog :: IO ()
-- configureLoggingToSyslog = do
-- s <- openlog "RehMimic" [PID] DAEMON INFO >>=
-- \lh -> return $ setFormatter lh (simpleLogFormatter "[$time : $loggername : $prio] $msg")
-- setLoggerLevels s
#ifdef SECONDTRANSFER_MONITORING
data Logit = Logit Cl.TimeSpec B.ByteString
loggerChan :: Chan Logit
{-# NOINLINE loggerChan #-}
loggerChan = unsafePerformIO $ do
chan <- newChan
log_file <- openFile "LOGIT" SIO.WriteMode
SIO.hSetBuffering log_file SIO.LineBuffering
start_of_time <- Cl.getTime Cl.Monotonic
forkIO $ readLoggerChan chan log_file start_of_time
return chan
readLoggerChan :: Chan Logit -> SIO.Handle -> Cl.TimeSpec -> IO ()
readLoggerChan chan_logit file_handle origin_time = do
Logit timespec bs <- readChan chan_logit
let
Cl.TimeSpec sec' nsec' = timespec - origin_time
SIO.hPutStr file_handle (show sec')
SIO.hPutStr file_handle "|"
SIO.hPutStr file_handle (show nsec')
SIO.hPutStr file_handle "|"
Bch.hPutStrLn file_handle bs
SIO.hFlush file_handle
readLoggerChan chan_logit file_handle origin_time
-- Simple logging function. It logs everything to a file named
-- "logit" in the current directory, adding a time-stamp
logit :: B.ByteString -> IO ()
logit !msg = do
time <- Cl.getTime Cl.Monotonic
let
lg = Logit time msg
writeChan loggerChan lg
#endif
| shimmercat/second-transfer | hs-src/SecondTransfer/MainLoop/Logging.hs | bsd-3-clause | 2,466 | 0 | 11 | 586 | 433 | 225 | 208 | 14 | 1 |
{-# LANGUAGE PartialTypeSignatures #-}
{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
module Tut6_Testing where
-- This file demonstrates programming testing Feldspar functions with
-- QuickCheck.
import qualified Prelude
import Feldspar.Run
import Feldspar.Data.Vector
import Test.QuickCheck
import Test.QuickCheck.Monadic as QC
-- The function `marshalled` can be used to turn a Feldspar function
-- `a -> Run b` into a corresponding Haskell function `a' -> IO b'`. The type
-- family `HaskellRep` is used to relate `a` and `a'` resp. `b` and `b'`:
-- `a' ~ HaskellRep a` and `b' ~ HaskellRep b`.
-- Since `marshalled` is defined in continuation passing style (in order to be
-- able to share generated files and clean up afterwards), it is convenient to
-- make our properties parameterized on the function under test.
-- The following property tests that a given function indeed computes the scalar
-- product:
prop_scProd :: (([Int32],[Int32]) -> IO Int32) -> Property
prop_scProd f = monadicIO $ do
as <- pick arbitrary
bs <- pick arbitrary
x <- run $ f (as,bs)
QC.assert (x Prelude.== scProdList as bs)
where
scProdList as bs = Prelude.sum $ Prelude.zipWith (*) as bs
-- Note that we have to use QuickCheck's monadic API because the function under
-- test is in `IO`.
--------------------------------------------------------------------------------
scProdRun = return . uncurry (scProd :: DPull Int32 -> DPull _ -> _)
testAll =
marshalled scProdRun $ \scProd' ->
quickCheck $ prop_scProd scProd'
-- Due to the sharing provided by `marshalled`, the function `scProdRun` is only
-- compiled once and then `quickCheck` calls the resulting program 100 times.
| kmate/raw-feldspar | examples/Tut6_Testing.hs | bsd-3-clause | 1,722 | 0 | 11 | 307 | 240 | 135 | 105 | 19 | 1 |
{-# LANGUAGE CPP, DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
#if __GLASGOW_HASKELL__ < 707
{-# LANGUAGE StandaloneDeriving #-}
#endif
-- Hack approach to support bootstrapping.
-- Assume binary <0.8 when MIN_VERSION_binary marco is not available.
-- Starting with GHC>=8.0, the compiler will hopefully provide this macros too.
-- https://ghc.haskell.org/trac/ghc/ticket/10970
--
-- Otherwise, one can specify -DMIN_VERSION_binary_0_8_0=1, when bootstrapping
-- with binary >=0.8.0.0.
#ifdef MIN_VERSION_binary
#define MIN_VERSION_binary_0_8_0 MIN_VERSION_binary(0,8,0)
#else
#ifndef MIN_VERSION_binary_0_8_0
#define MIN_VERSION_binary_0_8_0 0
#endif
#endif
#if !MIN_VERSION_binary_0_8_0
{-# OPTIONS_GHC -fno-warn-orphans #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Version
-- Copyright : Isaac Jones, Simon Marlow 2003-2004
-- Duncan Coutts 2008
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- Exports the 'Version' type along with a parser and pretty printer. A version
-- is something like @\"1.3.3\"@. It also defines the 'VersionRange' data
-- types. Version ranges are like @\">= 1.2 && < 2\"@.
module Distribution.Version (
-- * Package versions
Version(..),
-- * Version ranges
VersionRange(..),
-- ** Constructing
anyVersion, noVersion,
thisVersion, notThisVersion,
laterVersion, earlierVersion,
orLaterVersion, orEarlierVersion,
unionVersionRanges, intersectVersionRanges,
invertVersionRange,
withinVersion,
betweenVersionsInclusive,
-- ** Inspection
withinRange,
isAnyVersion,
isNoVersion,
isSpecificVersion,
simplifyVersionRange,
foldVersionRange,
foldVersionRange',
hasUpperBound,
hasLowerBound,
-- ** Modification
removeUpperBound,
-- * Version intervals view
asVersionIntervals,
VersionInterval,
LowerBound(..),
UpperBound(..),
Bound(..),
-- ** 'VersionIntervals' abstract type
-- | The 'VersionIntervals' type and the accompanying functions are exposed
-- primarily for completeness and testing purposes. In practice
-- 'asVersionIntervals' is the main function to use to
-- view a 'VersionRange' as a bunch of 'VersionInterval's.
--
VersionIntervals,
toVersionIntervals,
fromVersionIntervals,
withinIntervals,
versionIntervals,
mkVersionIntervals,
unionVersionIntervals,
intersectVersionIntervals,
invertVersionIntervals
) where
import Distribution.Compat.Binary ( Binary(..) )
import Data.Data ( Data )
import Data.Typeable ( Typeable )
import Data.Version ( Version(..) )
import GHC.Generics ( Generic )
import Distribution.Text ( Text(..) )
import qualified Distribution.Compat.ReadP as Parse
import Distribution.Compat.ReadP ((+++))
import qualified Text.PrettyPrint as Disp
import Text.PrettyPrint ((<>), (<+>))
import qualified Data.Char as Char (isDigit)
import Control.Exception (assert)
-- -----------------------------------------------------------------------------
-- Version ranges
-- Todo: maybe move this to Distribution.Package.Version?
-- (package-specific versioning scheme).
data VersionRange
= AnyVersion
| ThisVersion Version -- = version
| LaterVersion Version -- > version (NB. not >=)
| EarlierVersion Version -- < version
| WildcardVersion Version -- == ver.* (same as >= ver && < ver+1)
| UnionVersionRanges VersionRange VersionRange
| IntersectVersionRanges VersionRange VersionRange
| VersionRangeParens VersionRange -- just '(exp)' parentheses syntax
deriving (Data, Eq, Generic, Read, Show, Typeable)
instance Binary VersionRange
#if __GLASGOW_HASKELL__ < 707
-- starting with ghc-7.7/base-4.7 this instance is provided in "Data.Data"
deriving instance Data Version
#endif
#if !(MIN_VERSION_binary_0_8_0)
-- Deriving this instance from Generic gives trouble on GHC 7.2 because the
-- Generic instance has to be standalone-derived. So, we hand-roll our own.
-- We can't use a generic Binary instance on later versions because we must
-- maintain compatibility between compiler versions.
instance Binary Version where
get = do
br <- get
tags <- get
return $ Version br tags
put (Version br tags) = put br >> put tags
#endif
{-# DEPRECATED AnyVersion "Use 'anyVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED ThisVersion "use 'thisVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED LaterVersion "use 'laterVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED EarlierVersion "use 'earlierVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED WildcardVersion "use 'anyVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED UnionVersionRanges "use 'unionVersionRanges', 'foldVersionRange' or 'asVersionIntervals'" #-}
{-# DEPRECATED IntersectVersionRanges "use 'intersectVersionRanges', 'foldVersionRange' or 'asVersionIntervals'" #-}
-- | The version range @-any@. That is, a version range containing all
-- versions.
--
-- > withinRange v anyVersion = True
--
anyVersion :: VersionRange
anyVersion = AnyVersion
-- | The empty version range, that is a version range containing no versions.
--
-- This can be constructed using any unsatisfiable version range expression,
-- for example @> 1 && < 1@.
--
-- > withinRange v noVersion = False
--
noVersion :: VersionRange
noVersion = IntersectVersionRanges (LaterVersion v) (EarlierVersion v)
where v = Version [1] []
-- | The version range @== v@
--
-- > withinRange v' (thisVersion v) = v' == v
--
thisVersion :: Version -> VersionRange
thisVersion = ThisVersion
-- | The version range @< v || > v@
--
-- > withinRange v' (notThisVersion v) = v' /= v
--
notThisVersion :: Version -> VersionRange
notThisVersion v = UnionVersionRanges (EarlierVersion v) (LaterVersion v)
-- | The version range @> v@
--
-- > withinRange v' (laterVersion v) = v' > v
--
laterVersion :: Version -> VersionRange
laterVersion = LaterVersion
-- | The version range @>= v@
--
-- > withinRange v' (orLaterVersion v) = v' >= v
--
orLaterVersion :: Version -> VersionRange
orLaterVersion v = UnionVersionRanges (ThisVersion v) (LaterVersion v)
-- | The version range @< v@
--
-- > withinRange v' (earlierVersion v) = v' < v
--
earlierVersion :: Version -> VersionRange
earlierVersion = EarlierVersion
-- | The version range @<= v@
--
-- > withinRange v' (orEarlierVersion v) = v' <= v
--
orEarlierVersion :: Version -> VersionRange
orEarlierVersion v = UnionVersionRanges (ThisVersion v) (EarlierVersion v)
-- | The version range @vr1 || vr2@
--
-- > withinRange v' (unionVersionRanges vr1 vr2)
-- > = withinRange v' vr1 || withinRange v' vr2
--
unionVersionRanges :: VersionRange -> VersionRange -> VersionRange
unionVersionRanges = UnionVersionRanges
-- | The version range @vr1 && vr2@
--
-- > withinRange v' (intersectVersionRanges vr1 vr2)
-- > = withinRange v' vr1 && withinRange v' vr2
--
intersectVersionRanges :: VersionRange -> VersionRange -> VersionRange
intersectVersionRanges = IntersectVersionRanges
-- | The inverse of a version range
--
-- > withinRange v' (invertVersionRange vr)
-- > = not (withinRange v' vr)
--
invertVersionRange :: VersionRange -> VersionRange
invertVersionRange =
fromVersionIntervals . invertVersionIntervals . VersionIntervals . asVersionIntervals
-- | The version range @== v.*@.
--
-- For example, for version @1.2@, the version range @== 1.2.*@ is the same as
-- @>= 1.2 && < 1.3@
--
-- > withinRange v' (laterVersion v) = v' >= v && v' < upper v
-- > where
-- > upper (Version lower t) = Version (init lower ++ [last lower + 1]) t
--
withinVersion :: Version -> VersionRange
withinVersion = WildcardVersion
-- | The version range @>= v1 && <= v2@.
--
-- In practice this is not very useful because we normally use inclusive lower
-- bounds and exclusive upper bounds.
--
-- > withinRange v' (laterVersion v) = v' > v
--
betweenVersionsInclusive :: Version -> Version -> VersionRange
betweenVersionsInclusive v1 v2 =
IntersectVersionRanges (orLaterVersion v1) (orEarlierVersion v2)
{-# DEPRECATED betweenVersionsInclusive
"In practice this is not very useful because we normally use inclusive lower bounds and exclusive upper bounds" #-}
-- | Given a version range, remove the highest upper bound. Example: @(>= 1 && <
-- 3) || (>= 4 && < 5)@ is converted to @(>= 1 && < 3) || (>= 4)@.
removeUpperBound :: VersionRange -> VersionRange
removeUpperBound = fromVersionIntervals . relaxLastInterval . toVersionIntervals
where
relaxLastInterval (VersionIntervals intervals) =
VersionIntervals (relaxLastInterval' intervals)
relaxLastInterval' [] = []
relaxLastInterval' [(l,_)] = [(l, NoUpperBound)]
relaxLastInterval' (i:is) = i : relaxLastInterval' is
-- | Fold over the basic syntactic structure of a 'VersionRange'.
--
-- This provides a syntactic view of the expression defining the version range.
-- The syntactic sugar @\">= v\"@, @\"<= v\"@ and @\"== v.*\"@ is presented
-- in terms of the other basic syntax.
--
-- For a semantic view use 'asVersionIntervals'.
--
foldVersionRange :: a -- ^ @\"-any\"@ version
-> (Version -> a) -- ^ @\"== v\"@
-> (Version -> a) -- ^ @\"> v\"@
-> (Version -> a) -- ^ @\"< v\"@
-> (a -> a -> a) -- ^ @\"_ || _\"@ union
-> (a -> a -> a) -- ^ @\"_ && _\"@ intersection
-> VersionRange -> a
foldVersionRange anyv this later earlier union intersect = fold
where
fold AnyVersion = anyv
fold (ThisVersion v) = this v
fold (LaterVersion v) = later v
fold (EarlierVersion v) = earlier v
fold (WildcardVersion v) = fold (wildcard v)
fold (UnionVersionRanges v1 v2) = union (fold v1) (fold v2)
fold (IntersectVersionRanges v1 v2) = intersect (fold v1) (fold v2)
fold (VersionRangeParens v) = fold v
wildcard v = intersectVersionRanges
(orLaterVersion v)
(earlierVersion (wildcardUpperBound v))
-- | An extended variant of 'foldVersionRange' that also provides a view of the
-- expression in which the syntactic sugar @\">= v\"@, @\"<= v\"@ and @\"==
-- v.*\"@ is presented explicitly rather than in terms of the other basic
-- syntax.
--
foldVersionRange' :: a -- ^ @\"-any\"@ version
-> (Version -> a) -- ^ @\"== v\"@
-> (Version -> a) -- ^ @\"> v\"@
-> (Version -> a) -- ^ @\"< v\"@
-> (Version -> a) -- ^ @\">= v\"@
-> (Version -> a) -- ^ @\"<= v\"@
-> (Version -> Version -> a) -- ^ @\"== v.*\"@ wildcard. The
-- function is passed the
-- inclusive lower bound and the
-- exclusive upper bounds of the
-- range defined by the wildcard.
-> (a -> a -> a) -- ^ @\"_ || _\"@ union
-> (a -> a -> a) -- ^ @\"_ && _\"@ intersection
-> (a -> a) -- ^ @\"(_)\"@ parentheses
-> VersionRange -> a
foldVersionRange' anyv this later earlier orLater orEarlier
wildcard union intersect parens = fold
where
fold AnyVersion = anyv
fold (ThisVersion v) = this v
fold (LaterVersion v) = later v
fold (EarlierVersion v) = earlier v
fold (UnionVersionRanges (ThisVersion v)
(LaterVersion v')) | v==v' = orLater v
fold (UnionVersionRanges (LaterVersion v)
(ThisVersion v')) | v==v' = orLater v
fold (UnionVersionRanges (ThisVersion v)
(EarlierVersion v')) | v==v' = orEarlier v
fold (UnionVersionRanges (EarlierVersion v)
(ThisVersion v')) | v==v' = orEarlier v
fold (WildcardVersion v) = wildcard v (wildcardUpperBound v)
fold (UnionVersionRanges v1 v2) = union (fold v1) (fold v2)
fold (IntersectVersionRanges v1 v2) = intersect (fold v1) (fold v2)
fold (VersionRangeParens v) = parens (fold v)
-- | Does this version fall within the given range?
--
-- This is the evaluation function for the 'VersionRange' type.
--
withinRange :: Version -> VersionRange -> Bool
withinRange v = foldVersionRange
True
(\v' -> versionBranch v == versionBranch v')
(\v' -> versionBranch v > versionBranch v')
(\v' -> versionBranch v < versionBranch v')
(||)
(&&)
-- | View a 'VersionRange' as a union of intervals.
--
-- This provides a canonical view of the semantics of a 'VersionRange' as
-- opposed to the syntax of the expression used to define it. For the syntactic
-- view use 'foldVersionRange'.
--
-- Each interval is non-empty. The sequence is in increasing order and no
-- intervals overlap or touch. Therefore only the first and last can be
-- unbounded. The sequence can be empty if the range is empty
-- (e.g. a range expression like @< 1 && > 2@).
--
-- Other checks are trivial to implement using this view. For example:
--
-- > isNoVersion vr | [] <- asVersionIntervals vr = True
-- > | otherwise = False
--
-- > isSpecificVersion vr
-- > | [(LowerBound v InclusiveBound
-- > ,UpperBound v' InclusiveBound)] <- asVersionIntervals vr
-- > , v == v' = Just v
-- > | otherwise = Nothing
--
asVersionIntervals :: VersionRange -> [VersionInterval]
asVersionIntervals = versionIntervals . toVersionIntervals
-- | Does this 'VersionRange' place any restriction on the 'Version' or is it
-- in fact equivalent to 'AnyVersion'.
--
-- Note this is a semantic check, not simply a syntactic check. So for example
-- the following is @True@ (for all @v@).
--
-- > isAnyVersion (EarlierVersion v `UnionVersionRanges` orLaterVersion v)
--
isAnyVersion :: VersionRange -> Bool
isAnyVersion vr = case asVersionIntervals vr of
[(LowerBound v InclusiveBound, NoUpperBound)] | isVersion0 v -> True
_ -> False
-- | This is the converse of 'isAnyVersion'. It check if the version range is
-- empty, if there is no possible version that satisfies the version range.
--
-- For example this is @True@ (for all @v@):
--
-- > isNoVersion (EarlierVersion v `IntersectVersionRanges` LaterVersion v)
--
isNoVersion :: VersionRange -> Bool
isNoVersion vr = case asVersionIntervals vr of
[] -> True
_ -> False
-- | Is this version range in fact just a specific version?
--
-- For example the version range @\">= 3 && <= 3\"@ contains only the version
-- @3@.
--
isSpecificVersion :: VersionRange -> Maybe Version
isSpecificVersion vr = case asVersionIntervals vr of
[(LowerBound v InclusiveBound
,UpperBound v' InclusiveBound)]
| v == v' -> Just v
_ -> Nothing
-- | Simplify a 'VersionRange' expression. For non-empty version ranges
-- this produces a canonical form. Empty or inconsistent version ranges
-- are left as-is because that provides more information.
--
-- If you need a canonical form use
-- @fromVersionIntervals . toVersionIntervals@
--
-- It satisfies the following properties:
--
-- > withinRange v (simplifyVersionRange r) = withinRange v r
--
-- > withinRange v r = withinRange v r'
-- > ==> simplifyVersionRange r = simplifyVersionRange r'
-- > || isNoVersion r
-- > || isNoVersion r'
--
simplifyVersionRange :: VersionRange -> VersionRange
simplifyVersionRange vr
-- If the version range is inconsistent then we just return the
-- original since that has more information than ">1 && < 1", which
-- is the canonical inconsistent version range.
| null (versionIntervals vi) = vr
| otherwise = fromVersionIntervals vi
where
vi = toVersionIntervals vr
----------------------------
-- Wildcard range utilities
--
wildcardUpperBound :: Version -> Version
wildcardUpperBound (Version lowerBound ts) = Version upperBound ts
where
upperBound = init lowerBound ++ [last lowerBound + 1]
isWildcardRange :: Version -> Version -> Bool
isWildcardRange (Version branch1 _) (Version branch2 _) = check branch1 branch2
where check (n:[]) (m:[]) | n+1 == m = True
check (n:ns) (m:ms) | n == m = check ns ms
check _ _ = False
------------------
-- Intervals view
--
-- | A complementary representation of a 'VersionRange'. Instead of a boolean
-- version predicate it uses an increasing sequence of non-overlapping,
-- non-empty intervals.
--
-- The key point is that this representation gives a canonical representation
-- for the semantics of 'VersionRange's. This makes it easier to check things
-- like whether a version range is empty, covers all versions, or requires a
-- certain minimum or maximum version. It also makes it easy to check equality
-- or containment. It also makes it easier to identify \'simple\' version
-- predicates for translation into foreign packaging systems that do not
-- support complex version range expressions.
--
newtype VersionIntervals = VersionIntervals [VersionInterval]
deriving (Eq, Show)
-- | Inspect the list of version intervals.
--
versionIntervals :: VersionIntervals -> [VersionInterval]
versionIntervals (VersionIntervals is) = is
type VersionInterval = (LowerBound, UpperBound)
data LowerBound = LowerBound Version !Bound deriving (Eq, Show)
data UpperBound = NoUpperBound | UpperBound Version !Bound deriving (Eq, Show)
data Bound = ExclusiveBound | InclusiveBound deriving (Eq, Show)
minLowerBound :: LowerBound
minLowerBound = LowerBound (Version [0] []) InclusiveBound
isVersion0 :: Version -> Bool
isVersion0 (Version [0] _) = True
isVersion0 _ = False
instance Ord LowerBound where
LowerBound ver bound <= LowerBound ver' bound' = case compare ver ver' of
LT -> True
EQ -> not (bound == ExclusiveBound && bound' == InclusiveBound)
GT -> False
instance Ord UpperBound where
_ <= NoUpperBound = True
NoUpperBound <= UpperBound _ _ = False
UpperBound ver bound <= UpperBound ver' bound' = case compare ver ver' of
LT -> True
EQ -> not (bound == InclusiveBound && bound' == ExclusiveBound)
GT -> False
invariant :: VersionIntervals -> Bool
invariant (VersionIntervals intervals) = all validInterval intervals
&& all doesNotTouch' adjacentIntervals
where
doesNotTouch' :: (VersionInterval, VersionInterval) -> Bool
doesNotTouch' ((_,u), (l',_)) = doesNotTouch u l'
adjacentIntervals :: [(VersionInterval, VersionInterval)]
adjacentIntervals
| null intervals = []
| otherwise = zip intervals (tail intervals)
checkInvariant :: VersionIntervals -> VersionIntervals
checkInvariant is = assert (invariant is) is
-- | Directly construct a 'VersionIntervals' from a list of intervals.
--
-- Each interval must be non-empty. The sequence must be in increasing order
-- and no intervals may overlap or touch. If any of these conditions are not
-- satisfied the function returns @Nothing@.
--
mkVersionIntervals :: [VersionInterval] -> Maybe VersionIntervals
mkVersionIntervals intervals
| invariant (VersionIntervals intervals) = Just (VersionIntervals intervals)
| otherwise = Nothing
validVersion :: Version -> Bool
validVersion (Version [] _) = False
validVersion (Version vs _) = all (>=0) vs
validInterval :: (LowerBound, UpperBound) -> Bool
validInterval i@(l, u) = validLower l && validUpper u && nonEmpty i
where
validLower (LowerBound v _) = validVersion v
validUpper NoUpperBound = True
validUpper (UpperBound v _) = validVersion v
-- Check an interval is non-empty
--
nonEmpty :: VersionInterval -> Bool
nonEmpty (_, NoUpperBound ) = True
nonEmpty (LowerBound l lb, UpperBound u ub) =
(l < u) || (l == u && lb == InclusiveBound && ub == InclusiveBound)
-- Check an upper bound does not intersect, or even touch a lower bound:
--
-- ---| or ---) but not ---] or ---) or ---]
-- |--- (--- (--- [--- [---
--
doesNotTouch :: UpperBound -> LowerBound -> Bool
doesNotTouch NoUpperBound _ = False
doesNotTouch (UpperBound u ub) (LowerBound l lb) =
u < l
|| (u == l && ub == ExclusiveBound && lb == ExclusiveBound)
-- | Check an upper bound does not intersect a lower bound:
--
-- ---| or ---) or ---] or ---) but not ---]
-- |--- (--- (--- [--- [---
--
doesNotIntersect :: UpperBound -> LowerBound -> Bool
doesNotIntersect NoUpperBound _ = False
doesNotIntersect (UpperBound u ub) (LowerBound l lb) =
u < l
|| (u == l && not (ub == InclusiveBound && lb == InclusiveBound))
-- | Test if a version falls within the version intervals.
--
-- It exists mostly for completeness and testing. It satisfies the following
-- properties:
--
-- > withinIntervals v (toVersionIntervals vr) = withinRange v vr
-- > withinIntervals v ivs = withinRange v (fromVersionIntervals ivs)
--
withinIntervals :: Version -> VersionIntervals -> Bool
withinIntervals v (VersionIntervals intervals) = any withinInterval intervals
where
withinInterval (lowerBound, upperBound) = withinLower lowerBound
&& withinUpper upperBound
withinLower (LowerBound v' ExclusiveBound) = v' < v
withinLower (LowerBound v' InclusiveBound) = v' <= v
withinUpper NoUpperBound = True
withinUpper (UpperBound v' ExclusiveBound) = v' > v
withinUpper (UpperBound v' InclusiveBound) = v' >= v
-- | Convert a 'VersionRange' to a sequence of version intervals.
--
toVersionIntervals :: VersionRange -> VersionIntervals
toVersionIntervals = foldVersionRange
( chkIvl (minLowerBound, NoUpperBound))
(\v -> chkIvl (LowerBound v InclusiveBound, UpperBound v InclusiveBound))
(\v -> chkIvl (LowerBound v ExclusiveBound, NoUpperBound))
(\v -> if isVersion0 v then VersionIntervals [] else
chkIvl (minLowerBound, UpperBound v ExclusiveBound))
unionVersionIntervals
intersectVersionIntervals
where
chkIvl interval = checkInvariant (VersionIntervals [interval])
-- | Convert a 'VersionIntervals' value back into a 'VersionRange' expression
-- representing the version intervals.
--
fromVersionIntervals :: VersionIntervals -> VersionRange
fromVersionIntervals (VersionIntervals []) = noVersion
fromVersionIntervals (VersionIntervals intervals) =
foldr1 UnionVersionRanges [ interval l u | (l, u) <- intervals ]
where
interval (LowerBound v InclusiveBound)
(UpperBound v' InclusiveBound) | v == v'
= ThisVersion v
interval (LowerBound v InclusiveBound)
(UpperBound v' ExclusiveBound) | isWildcardRange v v'
= WildcardVersion v
interval l u = lowerBound l `intersectVersionRanges'` upperBound u
lowerBound (LowerBound v InclusiveBound)
| isVersion0 v = AnyVersion
| otherwise = orLaterVersion v
lowerBound (LowerBound v ExclusiveBound) = LaterVersion v
upperBound NoUpperBound = AnyVersion
upperBound (UpperBound v InclusiveBound) = orEarlierVersion v
upperBound (UpperBound v ExclusiveBound) = EarlierVersion v
intersectVersionRanges' vr AnyVersion = vr
intersectVersionRanges' AnyVersion vr = vr
intersectVersionRanges' vr vr' = IntersectVersionRanges vr vr'
unionVersionIntervals :: VersionIntervals -> VersionIntervals
-> VersionIntervals
unionVersionIntervals (VersionIntervals is0) (VersionIntervals is'0) =
checkInvariant (VersionIntervals (union is0 is'0))
where
union is [] = is
union [] is' = is'
union (i:is) (i':is') = case unionInterval i i' of
Left Nothing -> i : union is (i' :is')
Left (Just i'') -> union is (i'':is')
Right Nothing -> i' : union (i :is) is'
Right (Just i'') -> union (i'':is) is'
unionInterval :: VersionInterval -> VersionInterval
-> Either (Maybe VersionInterval) (Maybe VersionInterval)
unionInterval (lower , upper ) (lower', upper')
-- Non-intersecting intervals with the left interval ending first
| upper `doesNotTouch` lower' = Left Nothing
-- Non-intersecting intervals with the right interval first
| upper' `doesNotTouch` lower = Right Nothing
-- Complete or partial overlap, with the left interval ending first
| upper <= upper' = lowerBound `seq`
Left (Just (lowerBound, upper'))
-- Complete or partial overlap, with the left interval ending first
| otherwise = lowerBound `seq`
Right (Just (lowerBound, upper))
where
lowerBound = min lower lower'
intersectVersionIntervals :: VersionIntervals -> VersionIntervals
-> VersionIntervals
intersectVersionIntervals (VersionIntervals is0) (VersionIntervals is'0) =
checkInvariant (VersionIntervals (intersect is0 is'0))
where
intersect _ [] = []
intersect [] _ = []
intersect (i:is) (i':is') = case intersectInterval i i' of
Left Nothing -> intersect is (i':is')
Left (Just i'') -> i'' : intersect is (i':is')
Right Nothing -> intersect (i:is) is'
Right (Just i'') -> i'' : intersect (i:is) is'
intersectInterval :: VersionInterval -> VersionInterval
-> Either (Maybe VersionInterval) (Maybe VersionInterval)
intersectInterval (lower , upper ) (lower', upper')
-- Non-intersecting intervals with the left interval ending first
| upper `doesNotIntersect` lower' = Left Nothing
-- Non-intersecting intervals with the right interval first
| upper' `doesNotIntersect` lower = Right Nothing
-- Complete or partial overlap, with the left interval ending first
| upper <= upper' = lowerBound `seq`
Left (Just (lowerBound, upper))
-- Complete or partial overlap, with the right interval ending first
| otherwise = lowerBound `seq`
Right (Just (lowerBound, upper'))
where
lowerBound = max lower lower'
invertVersionIntervals :: VersionIntervals
-> VersionIntervals
invertVersionIntervals (VersionIntervals xs) =
case xs of
-- Empty interval set
[] -> VersionIntervals [(noLowerBound, NoUpperBound)]
-- Interval with no lower bound
((lb, ub) : more) | lb == noLowerBound -> VersionIntervals $ invertVersionIntervals' ub more
-- Interval with a lower bound
((lb, ub) : more) ->
VersionIntervals $ (noLowerBound, invertLowerBound lb) : invertVersionIntervals' ub more
where
-- Invert subsequent version intervals given the upper bound of
-- the intervals already inverted.
invertVersionIntervals' :: UpperBound
-> [(LowerBound, UpperBound)]
-> [(LowerBound, UpperBound)]
invertVersionIntervals' NoUpperBound [] = []
invertVersionIntervals' ub0 [] = [(invertUpperBound ub0, NoUpperBound)]
invertVersionIntervals' ub0 [(lb, NoUpperBound)] =
[(invertUpperBound ub0, invertLowerBound lb)]
invertVersionIntervals' ub0 ((lb, ub1) : more) =
(invertUpperBound ub0, invertLowerBound lb)
: invertVersionIntervals' ub1 more
invertLowerBound :: LowerBound -> UpperBound
invertLowerBound (LowerBound v b) = UpperBound v (invertBound b)
invertUpperBound :: UpperBound -> LowerBound
invertUpperBound (UpperBound v b) = LowerBound v (invertBound b)
invertUpperBound NoUpperBound = error "NoUpperBound: unexpected"
invertBound :: Bound -> Bound
invertBound ExclusiveBound = InclusiveBound
invertBound InclusiveBound = ExclusiveBound
noLowerBound :: LowerBound
noLowerBound = LowerBound (Version [0] []) InclusiveBound
-------------------------------
-- Parsing and pretty printing
--
instance Text VersionRange where
disp = fst
. foldVersionRange' -- precedence:
( Disp.text "-any" , 0 :: Int)
(\v -> (Disp.text "==" <> disp v , 0))
(\v -> (Disp.char '>' <> disp v , 0))
(\v -> (Disp.char '<' <> disp v , 0))
(\v -> (Disp.text ">=" <> disp v , 0))
(\v -> (Disp.text "<=" <> disp v , 0))
(\v _ -> (Disp.text "==" <> dispWild v , 0))
(\(r1, p1) (r2, p2) -> (punct 2 p1 r1 <+> Disp.text "||" <+> punct 2 p2 r2 , 2))
(\(r1, p1) (r2, p2) -> (punct 1 p1 r1 <+> Disp.text "&&" <+> punct 1 p2 r2 , 1))
(\(r, _) -> (Disp.parens r, 0))
where dispWild (Version b _) =
Disp.hcat (Disp.punctuate (Disp.char '.') (map Disp.int b))
<> Disp.text ".*"
punct p p' | p < p' = Disp.parens
| otherwise = id
parse = expr
where
expr = do Parse.skipSpaces
t <- term
Parse.skipSpaces
(do _ <- Parse.string "||"
Parse.skipSpaces
e <- expr
return (UnionVersionRanges t e)
+++
return t)
term = do f <- factor
Parse.skipSpaces
(do _ <- Parse.string "&&"
Parse.skipSpaces
t <- term
return (IntersectVersionRanges f t)
+++
return f)
factor = Parse.choice $ parens expr
: parseAnyVersion
: parseNoVersion
: parseWildcardRange
: map parseRangeOp rangeOps
parseAnyVersion = Parse.string "-any" >> return AnyVersion
parseNoVersion = Parse.string "-none" >> return noVersion
parseWildcardRange = do
_ <- Parse.string "=="
Parse.skipSpaces
branch <- Parse.sepBy1 digits (Parse.char '.')
_ <- Parse.char '.'
_ <- Parse.char '*'
return (WildcardVersion (Version branch []))
parens p = Parse.between (Parse.char '(' >> Parse.skipSpaces)
(Parse.char ')' >> Parse.skipSpaces)
(do a <- p
Parse.skipSpaces
return (VersionRangeParens a))
digits = do
first <- Parse.satisfy Char.isDigit
if first == '0'
then return 0
else do rest <- Parse.munch Char.isDigit
return (read (first : rest))
parseRangeOp (s,f) = Parse.string s >> Parse.skipSpaces >> fmap f parse
rangeOps = [ ("<", EarlierVersion),
("<=", orEarlierVersion),
(">", LaterVersion),
(">=", orLaterVersion),
("==", ThisVersion) ]
-- | Does the version range have an upper bound?
--
-- @since 1.24.0.0
hasUpperBound :: VersionRange -> Bool
hasUpperBound = foldVersionRange
False
(const True)
(const False)
(const True)
(&&) (||)
-- | Does the version range have an explicit lower bound?
--
-- Note: this function only considers the user-specified lower bounds, but not
-- the implicit >=0 lower bound.
--
-- @since 1.24.0.0
hasLowerBound :: VersionRange -> Bool
hasLowerBound = foldVersionRange
False
(const True)
(const True)
(const False)
(&&) (||)
| trskop/cabal | Cabal/Distribution/Version.hs | bsd-3-clause | 32,681 | 0 | 17 | 8,793 | 6,304 | 3,397 | 2,907 | 455 | 12 |
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.FramebufferObjects.RenderbufferObjects
-- Copyright : (c) Sven Panne, Lars Corbijn 2011-2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-----------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.FramebufferObjects.RenderbufferObjects (
RenderbufferObject,
noRenderbufferObject,
RenderbufferTarget(..),
RenderbufferSize(..), Samples(..),
bindRenderbuffer,
renderbufferStorage, renderbufferStorageMultiSample,
) where
import Graphics.Rendering.OpenGL.GL.FramebufferObjects.RenderbufferObject
import Graphics.Rendering.OpenGL.GL.FramebufferObjects.RenderbufferTarget
import Graphics.Rendering.OpenGL.GL.QueryUtils
import Graphics.Rendering.OpenGL.GL.StateVar
import Graphics.Rendering.OpenGL.GL.Texturing.PixelInternalFormat
import Graphics.Rendering.OpenGL.Raw
-----------------------------------------------------------------------------
noRenderbufferObject :: RenderbufferObject
noRenderbufferObject = RenderbufferObject 0
-----------------------------------------------------------------------------
data RenderbufferSize = RenderbufferSize !GLsizei !GLsizei
deriving ( Eq, Ord, Show )
-----------------------------------------------------------------------------
bindRenderbuffer :: RenderbufferTarget -> StateVar RenderbufferObject
bindRenderbuffer rbt =
makeStateVar (getBoundRenderbuffer rbt) (setRenderbuffer rbt)
marshalRenderbufferTargetBinding :: RenderbufferTarget -> PName1I
marshalRenderbufferTargetBinding x = case x of
Renderbuffer -> GetRenderbufferBinding
getBoundRenderbuffer :: RenderbufferTarget -> IO RenderbufferObject
getBoundRenderbuffer =
getInteger1 (RenderbufferObject . fromIntegral) . marshalRenderbufferTargetBinding
setRenderbuffer :: RenderbufferTarget -> RenderbufferObject -> IO ()
setRenderbuffer rbt = glBindRenderbuffer (marshalRenderbufferTarget rbt)
. renderbufferID
-----------------------------------------------------------------------------
renderbufferStorageMultiSample :: RenderbufferTarget -> Samples
-> PixelInternalFormat -> RenderbufferSize -> IO ()
renderbufferStorageMultiSample rbt (Samples s) pif (RenderbufferSize w h) =
glRenderbufferStorageMultisample (marshalRenderbufferTarget rbt) s
(marshalPixelInternalFormat' pif) w h
renderbufferStorage :: RenderbufferTarget -> PixelInternalFormat
-> RenderbufferSize -> IO ()
renderbufferStorage rbt pif (RenderbufferSize w h) =
glRenderbufferStorage (marshalRenderbufferTarget rbt)
(marshalPixelInternalFormat' pif) w h
| hesiod/OpenGL | src/Graphics/Rendering/OpenGL/GL/FramebufferObjects/RenderbufferObjects.hs | bsd-3-clause | 2,805 | 0 | 10 | 299 | 430 | 246 | 184 | 44 | 1 |
{-# LANGUAGE BangPatterns, CPP, MultiParamTypeClasses, TypeFamilies, FlexibleContexts #-}
#if __GLASGOW_HASKELL__ >= 707
{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-}
#endif
{-# OPTIONS_HADDOCK hide #-}
-- |
-- Module : Data.Vector.Unboxed.Base
-- Copyright : (c) Roman Leshchinskiy 2009-2010
-- License : BSD-style
--
-- Maintainer : Roman Leshchinskiy <rl@cse.unsw.edu.au>
-- Stability : experimental
-- Portability : non-portable
--
-- Adaptive unboxed vectors: basic implementation
--
module Data.Vector.Unboxed.Base (
MVector(..), IOVector, STVector, Vector(..), Unbox
) where
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as M
import qualified Data.Vector.Primitive as P
import Control.DeepSeq ( NFData(rnf) )
import Control.Monad.Primitive
import Control.Monad ( liftM )
import Data.Word ( Word, Word8, Word16, Word32, Word64 )
import Data.Int ( Int8, Int16, Int32, Int64 )
import Data.Complex
#if __GLASGOW_HASKELL__ >= 707
import Data.Typeable ( Typeable )
#else
import Data.Typeable ( Typeable1(..), Typeable2(..), mkTyConApp,
#if MIN_VERSION_base(4,4,0)
mkTyCon3
#else
mkTyCon
#endif
)
#endif
import Data.Data ( Data(..) )
-- Data.Vector.Internal.Check is unused
#define NOT_VECTOR_MODULE
#include "vector.h"
data family MVector s a
data family Vector a
type IOVector = MVector RealWorld
type STVector s = MVector s
type instance G.Mutable Vector = MVector
class (G.Vector Vector a, M.MVector MVector a) => Unbox a
instance NFData (Vector a) where rnf !_ = ()
instance NFData (MVector s a) where rnf !_ = ()
-- -----------------
-- Data and Typeable
-- -----------------
#if __GLASGOW_HASKELL__ >= 707
deriving instance Typeable Vector
deriving instance Typeable MVector
#else
#if MIN_VERSION_base(4,4,0)
vectorTyCon = mkTyCon3 "vector"
#else
vectorTyCon m s = mkTyCon $ m ++ "." ++ s
#endif
instance Typeable1 Vector where
typeOf1 _ = mkTyConApp (vectorTyCon "Data.Vector.Unboxed" "Vector") []
instance Typeable2 MVector where
typeOf2 _ = mkTyConApp (vectorTyCon "Data.Vector.Unboxed.Mutable" "MVector") []
#endif
instance (Data a, Unbox a) => Data (Vector a) where
gfoldl = G.gfoldl
toConstr _ = error "toConstr"
gunfold _ _ = error "gunfold"
dataTypeOf _ = G.mkType "Data.Vector.Unboxed.Vector"
dataCast1 = G.dataCast
-- ----
-- Unit
-- ----
newtype instance MVector s () = MV_Unit Int
newtype instance Vector () = V_Unit Int
instance Unbox ()
instance M.MVector MVector () where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicOverlaps #-}
{-# INLINE basicUnsafeNew #-}
{-# INLINE basicInitialize #-}
{-# INLINE basicUnsafeRead #-}
{-# INLINE basicUnsafeWrite #-}
{-# INLINE basicClear #-}
{-# INLINE basicSet #-}
{-# INLINE basicUnsafeCopy #-}
{-# INLINE basicUnsafeGrow #-}
basicLength (MV_Unit n) = n
basicUnsafeSlice _ m (MV_Unit _) = MV_Unit m
basicOverlaps _ _ = False
basicUnsafeNew n = return (MV_Unit n)
-- Nothing to initialize
basicInitialize _ = return ()
basicUnsafeRead (MV_Unit _) _ = return ()
basicUnsafeWrite (MV_Unit _) _ () = return ()
basicClear _ = return ()
basicSet (MV_Unit _) () = return ()
basicUnsafeCopy (MV_Unit _) (MV_Unit _) = return ()
basicUnsafeGrow (MV_Unit n) m = return $ MV_Unit (n+m)
instance G.Vector Vector () where
{-# INLINE basicUnsafeFreeze #-}
basicUnsafeFreeze (MV_Unit n) = return $ V_Unit n
{-# INLINE basicUnsafeThaw #-}
basicUnsafeThaw (V_Unit n) = return $ MV_Unit n
{-# INLINE basicLength #-}
basicLength (V_Unit n) = n
{-# INLINE basicUnsafeSlice #-}
basicUnsafeSlice _ m (V_Unit _) = V_Unit m
{-# INLINE basicUnsafeIndexM #-}
basicUnsafeIndexM (V_Unit _) _ = return ()
{-# INLINE basicUnsafeCopy #-}
basicUnsafeCopy (MV_Unit _) (V_Unit _) = return ()
{-# INLINE elemseq #-}
elemseq _ = seq
-- ---------------
-- Primitive types
-- ---------------
#define primMVector(ty,con) \
instance M.MVector MVector ty where { \
{-# INLINE basicLength #-} \
; {-# INLINE basicUnsafeSlice #-} \
; {-# INLINE basicOverlaps #-} \
; {-# INLINE basicUnsafeNew #-} \
; {-# INLINE basicInitialize #-} \
; {-# INLINE basicUnsafeReplicate #-} \
; {-# INLINE basicUnsafeRead #-} \
; {-# INLINE basicUnsafeWrite #-} \
; {-# INLINE basicClear #-} \
; {-# INLINE basicSet #-} \
; {-# INLINE basicUnsafeCopy #-} \
; {-# INLINE basicUnsafeGrow #-} \
; basicLength (con v) = M.basicLength v \
; basicUnsafeSlice i n (con v) = con $ M.basicUnsafeSlice i n v \
; basicOverlaps (con v1) (con v2) = M.basicOverlaps v1 v2 \
; basicUnsafeNew n = con `liftM` M.basicUnsafeNew n \
; basicInitialize (con v) = M.basicInitialize v \
; basicUnsafeReplicate n x = con `liftM` M.basicUnsafeReplicate n x \
; basicUnsafeRead (con v) i = M.basicUnsafeRead v i \
; basicUnsafeWrite (con v) i x = M.basicUnsafeWrite v i x \
; basicClear (con v) = M.basicClear v \
; basicSet (con v) x = M.basicSet v x \
; basicUnsafeCopy (con v1) (con v2) = M.basicUnsafeCopy v1 v2 \
; basicUnsafeMove (con v1) (con v2) = M.basicUnsafeMove v1 v2 \
; basicUnsafeGrow (con v) n = con `liftM` M.basicUnsafeGrow v n }
#define primVector(ty,con,mcon) \
instance G.Vector Vector ty where { \
{-# INLINE basicUnsafeFreeze #-} \
; {-# INLINE basicUnsafeThaw #-} \
; {-# INLINE basicLength #-} \
; {-# INLINE basicUnsafeSlice #-} \
; {-# INLINE basicUnsafeIndexM #-} \
; {-# INLINE elemseq #-} \
; basicUnsafeFreeze (mcon v) = con `liftM` G.basicUnsafeFreeze v \
; basicUnsafeThaw (con v) = mcon `liftM` G.basicUnsafeThaw v \
; basicLength (con v) = G.basicLength v \
; basicUnsafeSlice i n (con v) = con $ G.basicUnsafeSlice i n v \
; basicUnsafeIndexM (con v) i = G.basicUnsafeIndexM v i \
; basicUnsafeCopy (mcon mv) (con v) = G.basicUnsafeCopy mv v \
; elemseq _ = seq }
newtype instance MVector s Int = MV_Int (P.MVector s Int)
newtype instance Vector Int = V_Int (P.Vector Int)
instance Unbox Int
primMVector(Int, MV_Int)
primVector(Int, V_Int, MV_Int)
newtype instance MVector s Int8 = MV_Int8 (P.MVector s Int8)
newtype instance Vector Int8 = V_Int8 (P.Vector Int8)
instance Unbox Int8
primMVector(Int8, MV_Int8)
primVector(Int8, V_Int8, MV_Int8)
newtype instance MVector s Int16 = MV_Int16 (P.MVector s Int16)
newtype instance Vector Int16 = V_Int16 (P.Vector Int16)
instance Unbox Int16
primMVector(Int16, MV_Int16)
primVector(Int16, V_Int16, MV_Int16)
newtype instance MVector s Int32 = MV_Int32 (P.MVector s Int32)
newtype instance Vector Int32 = V_Int32 (P.Vector Int32)
instance Unbox Int32
primMVector(Int32, MV_Int32)
primVector(Int32, V_Int32, MV_Int32)
newtype instance MVector s Int64 = MV_Int64 (P.MVector s Int64)
newtype instance Vector Int64 = V_Int64 (P.Vector Int64)
instance Unbox Int64
primMVector(Int64, MV_Int64)
primVector(Int64, V_Int64, MV_Int64)
newtype instance MVector s Word = MV_Word (P.MVector s Word)
newtype instance Vector Word = V_Word (P.Vector Word)
instance Unbox Word
primMVector(Word, MV_Word)
primVector(Word, V_Word, MV_Word)
newtype instance MVector s Word8 = MV_Word8 (P.MVector s Word8)
newtype instance Vector Word8 = V_Word8 (P.Vector Word8)
instance Unbox Word8
primMVector(Word8, MV_Word8)
primVector(Word8, V_Word8, MV_Word8)
newtype instance MVector s Word16 = MV_Word16 (P.MVector s Word16)
newtype instance Vector Word16 = V_Word16 (P.Vector Word16)
instance Unbox Word16
primMVector(Word16, MV_Word16)
primVector(Word16, V_Word16, MV_Word16)
newtype instance MVector s Word32 = MV_Word32 (P.MVector s Word32)
newtype instance Vector Word32 = V_Word32 (P.Vector Word32)
instance Unbox Word32
primMVector(Word32, MV_Word32)
primVector(Word32, V_Word32, MV_Word32)
newtype instance MVector s Word64 = MV_Word64 (P.MVector s Word64)
newtype instance Vector Word64 = V_Word64 (P.Vector Word64)
instance Unbox Word64
primMVector(Word64, MV_Word64)
primVector(Word64, V_Word64, MV_Word64)
newtype instance MVector s Float = MV_Float (P.MVector s Float)
newtype instance Vector Float = V_Float (P.Vector Float)
instance Unbox Float
primMVector(Float, MV_Float)
primVector(Float, V_Float, MV_Float)
newtype instance MVector s Double = MV_Double (P.MVector s Double)
newtype instance Vector Double = V_Double (P.Vector Double)
instance Unbox Double
primMVector(Double, MV_Double)
primVector(Double, V_Double, MV_Double)
newtype instance MVector s Char = MV_Char (P.MVector s Char)
newtype instance Vector Char = V_Char (P.Vector Char)
instance Unbox Char
primMVector(Char, MV_Char)
primVector(Char, V_Char, MV_Char)
-- ----
-- Bool
-- ----
fromBool :: Bool -> Word8
{-# INLINE fromBool #-}
fromBool True = 1
fromBool False = 0
toBool :: Word8 -> Bool
{-# INLINE toBool #-}
toBool 0 = False
toBool _ = True
newtype instance MVector s Bool = MV_Bool (P.MVector s Word8)
newtype instance Vector Bool = V_Bool (P.Vector Word8)
instance Unbox Bool
instance M.MVector MVector Bool where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicOverlaps #-}
{-# INLINE basicUnsafeNew #-}
{-# INLINE basicInitialize #-}
{-# INLINE basicUnsafeReplicate #-}
{-# INLINE basicUnsafeRead #-}
{-# INLINE basicUnsafeWrite #-}
{-# INLINE basicClear #-}
{-# INLINE basicSet #-}
{-# INLINE basicUnsafeCopy #-}
{-# INLINE basicUnsafeGrow #-}
basicLength (MV_Bool v) = M.basicLength v
basicUnsafeSlice i n (MV_Bool v) = MV_Bool $ M.basicUnsafeSlice i n v
basicOverlaps (MV_Bool v1) (MV_Bool v2) = M.basicOverlaps v1 v2
basicUnsafeNew n = MV_Bool `liftM` M.basicUnsafeNew n
basicInitialize (MV_Bool v) = M.basicInitialize v
basicUnsafeReplicate n x = MV_Bool `liftM` M.basicUnsafeReplicate n (fromBool x)
basicUnsafeRead (MV_Bool v) i = toBool `liftM` M.basicUnsafeRead v i
basicUnsafeWrite (MV_Bool v) i x = M.basicUnsafeWrite v i (fromBool x)
basicClear (MV_Bool v) = M.basicClear v
basicSet (MV_Bool v) x = M.basicSet v (fromBool x)
basicUnsafeCopy (MV_Bool v1) (MV_Bool v2) = M.basicUnsafeCopy v1 v2
basicUnsafeMove (MV_Bool v1) (MV_Bool v2) = M.basicUnsafeMove v1 v2
basicUnsafeGrow (MV_Bool v) n = MV_Bool `liftM` M.basicUnsafeGrow v n
instance G.Vector Vector Bool where
{-# INLINE basicUnsafeFreeze #-}
{-# INLINE basicUnsafeThaw #-}
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicUnsafeIndexM #-}
{-# INLINE elemseq #-}
basicUnsafeFreeze (MV_Bool v) = V_Bool `liftM` G.basicUnsafeFreeze v
basicUnsafeThaw (V_Bool v) = MV_Bool `liftM` G.basicUnsafeThaw v
basicLength (V_Bool v) = G.basicLength v
basicUnsafeSlice i n (V_Bool v) = V_Bool $ G.basicUnsafeSlice i n v
basicUnsafeIndexM (V_Bool v) i = toBool `liftM` G.basicUnsafeIndexM v i
basicUnsafeCopy (MV_Bool mv) (V_Bool v) = G.basicUnsafeCopy mv v
elemseq _ = seq
-- -------
-- Complex
-- -------
newtype instance MVector s (Complex a) = MV_Complex (MVector s (a,a))
newtype instance Vector (Complex a) = V_Complex (Vector (a,a))
instance (RealFloat a, Unbox a) => Unbox (Complex a)
instance (RealFloat a, Unbox a) => M.MVector MVector (Complex a) where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicOverlaps #-}
{-# INLINE basicUnsafeNew #-}
{-# INLINE basicInitialize #-}
{-# INLINE basicUnsafeReplicate #-}
{-# INLINE basicUnsafeRead #-}
{-# INLINE basicUnsafeWrite #-}
{-# INLINE basicClear #-}
{-# INLINE basicSet #-}
{-# INLINE basicUnsafeCopy #-}
{-# INLINE basicUnsafeGrow #-}
basicLength (MV_Complex v) = M.basicLength v
basicUnsafeSlice i n (MV_Complex v) = MV_Complex $ M.basicUnsafeSlice i n v
basicOverlaps (MV_Complex v1) (MV_Complex v2) = M.basicOverlaps v1 v2
basicUnsafeNew n = MV_Complex `liftM` M.basicUnsafeNew n
basicInitialize (MV_Complex v) = M.basicInitialize v
basicUnsafeReplicate n (x :+ y) = MV_Complex `liftM` M.basicUnsafeReplicate n (x,y)
basicUnsafeRead (MV_Complex v) i = uncurry (:+) `liftM` M.basicUnsafeRead v i
basicUnsafeWrite (MV_Complex v) i (x :+ y) = M.basicUnsafeWrite v i (x,y)
basicClear (MV_Complex v) = M.basicClear v
basicSet (MV_Complex v) (x :+ y) = M.basicSet v (x,y)
basicUnsafeCopy (MV_Complex v1) (MV_Complex v2) = M.basicUnsafeCopy v1 v2
basicUnsafeMove (MV_Complex v1) (MV_Complex v2) = M.basicUnsafeMove v1 v2
basicUnsafeGrow (MV_Complex v) n = MV_Complex `liftM` M.basicUnsafeGrow v n
instance (RealFloat a, Unbox a) => G.Vector Vector (Complex a) where
{-# INLINE basicUnsafeFreeze #-}
{-# INLINE basicUnsafeThaw #-}
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicUnsafeIndexM #-}
{-# INLINE elemseq #-}
basicUnsafeFreeze (MV_Complex v) = V_Complex `liftM` G.basicUnsafeFreeze v
basicUnsafeThaw (V_Complex v) = MV_Complex `liftM` G.basicUnsafeThaw v
basicLength (V_Complex v) = G.basicLength v
basicUnsafeSlice i n (V_Complex v) = V_Complex $ G.basicUnsafeSlice i n v
basicUnsafeIndexM (V_Complex v) i
= uncurry (:+) `liftM` G.basicUnsafeIndexM v i
basicUnsafeCopy (MV_Complex mv) (V_Complex v)
= G.basicUnsafeCopy mv v
elemseq _ (x :+ y) z = G.elemseq (undefined :: Vector a) x
$ G.elemseq (undefined :: Vector a) y z
-- ------
-- Tuples
-- ------
#define DEFINE_INSTANCES
#include "unbox-tuple-instances"
| seckcoder/vector | Data/Vector/Unboxed/Base.hs | bsd-3-clause | 14,617 | 1 | 9 | 3,637 | 3,392 | 1,794 | 1,598 | -1 | -1 |
{-# LANGUAGE RankNTypes #-}
-- This program must be called with GHC's libdir as the single command line
-- argument.
module Main where
-- import Data.Generics
import Data.Data
import Data.List
import System.IO
import GHC
import BasicTypes
import DynFlags
import MonadUtils
import Outputable
import ApiAnnotation
import Bag (filterBag,isEmptyBag)
import System.Directory (removeFile)
import System.Environment( getArgs )
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Dynamic ( fromDynamic,Dynamic )
main::IO()
main = do
[libdir] <- getArgs
testOneFile libdir "Test10312"
testOneFile libdir fileName = do
((anns,cs),p) <- runGhc (Just libdir) $ do
dflags <- getSessionDynFlags
setSessionDynFlags dflags
let mn =mkModuleName fileName
addTarget Target { targetId = TargetModule mn
, targetAllowObjCode = True
, targetContents = Nothing }
load LoadAllTargets
modSum <- getModSummary mn
p <- parseModule modSum
return (pm_annotations p,p)
let spans = Set.fromList $ getAllSrcSpans (pm_parsed_source p)
problems = filter (\(s,a) -> not (Set.member s spans))
$ getAnnSrcSpans (anns,cs)
putStrLn "---Problems---------------------"
putStrLn (intercalate "\n" [showAnns $ Map.fromList $ map snd problems])
putStrLn "--------------------------------"
putStrLn (intercalate "\n" [showAnns anns])
where
getAnnSrcSpans :: ApiAnns -> [(SrcSpan,(ApiAnnKey,[SrcSpan]))]
getAnnSrcSpans (anns,_) = map (\a@((ss,_),_) -> (ss,a)) $ Map.toList anns
getAllSrcSpans :: (Data t) => t -> [SrcSpan]
getAllSrcSpans ast = everything (++) ([] `mkQ` getSrcSpan) ast
where
getSrcSpan :: SrcSpan -> [SrcSpan]
getSrcSpan ss = [ss]
showAnns anns = "[\n" ++ (intercalate "\n"
$ map (\((s,k),v)
-> ("(AK " ++ pp s ++ " " ++ show k ++" = " ++ pp v ++ ")\n"))
$ Map.toList anns)
++ "]\n"
pp a = showPpr unsafeGlobalDynFlags a
-- ---------------------------------------------------------------------
-- Copied from syb for the test
-- | Generic queries of type \"r\",
-- i.e., take any \"a\" and return an \"r\"
--
type GenericQ r = forall a. Data a => a -> r
-- | Make a generic query;
-- start from a type-specific case;
-- return a constant otherwise
--
mkQ :: ( Typeable a
, Typeable b
)
=> r
-> (b -> r)
-> a
-> r
(r `mkQ` br) a = case cast a of
Just b -> br b
Nothing -> r
-- | Summarise all nodes in top-down, left-to-right order
everything :: (r -> r -> r) -> GenericQ r -> GenericQ r
-- Apply f to x to summarise top-level node;
-- use gmapQ to recurse into immediate subterms;
-- use ordinary foldl to reduce list of intermediate results
everything k f x = foldl k (f x) (gmapQ (everything k f) x)
| fmthoma/ghc | testsuite/tests/ghc-api/annotations/t10312.hs | bsd-3-clause | 3,159 | 1 | 20 | 967 | 862 | 462 | 400 | 64 | 2 |
{-# OPTIONS_JHC -fm4 -fno-prelude -fffi #-}
module Jhc.Order(
module Jhc.Class.Ord,
Bool(..),
Ordering(..),
Eq(..),
Ord(..),
(&&),
(||),
not,
otherwise
) where
import Jhc.Prim.Basics
import Jhc.Class.Ord
import Jhc.Basics
m4_include(Jhc/Order.m4)
deriving instance Eq Bool
deriving instance Ord Bool
deriving instance Eq Ordering
deriving instance Ord Ordering
instance Eq () where
() == () = True
() /= () = False
instance Ord () where
() <= () = True
() < () = False
() >= () = True
() > () = False
max () () = ()
min () () = ()
compare () () = EQ
instance Eq a => Eq [a] where
[] == [] = True
(x:xs) == (y:ys) | x == y = xs == ys
_ == _ = False
instance Ord a => Ord [a] where
compare (x:xs) (y:ys) = case compare x y of
EQ -> compare xs ys
z -> z
compare [] [] = EQ
compare [] _ = LT
compare _ [] = GT
_ < [] = False
[] < _ = True
(x:xs) < (y:ys) = if x == y then xs < ys else x < y
x > y = y < x
x >= y = not (x < y)
x <= y = not (y < x)
INST_EQORDER(Char,Char,Char_,U)
INST_EQORDER(Int,,Int,)
INST_EQORDER(Integer,,Integer,)
infixr 3 &&
infixr 2 ||
{-# INLINE (&&), (||), not, otherwise #-}
(&&), (||) :: Bool -> Bool -> Bool
True && x = x
False && _ = False
True || _ = True
False || x = x
not :: Bool -> Bool
not x = if x then False else True
| hvr/jhc | lib/jhc/Jhc/Order.hs | mit | 1,458 | 0 | 9 | 477 | 742 | 388 | 354 | -1 | -1 |
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2015 Galois, Inc.
-- License : BSD3
-- Maintainer : cryptol@galois.com
-- Stability : provisional
-- Portability : portable
{-# LANGUAGE CPP #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import OptParser
import Cryptol.REPL.Command (loadCmd,loadPrelude)
import Cryptol.REPL.Monad (REPL,updateREPLTitle,setUpdateREPLTitle,
io,prependSearchPath,setSearchPath)
import qualified Cryptol.REPL.Monad as REPL
import REPL.Haskeline
import REPL.Logo
import Cryptol.Utils.PP
import Cryptol.Version (commitHash, commitBranch, commitDirty)
import Paths_cryptol (version)
import Data.Version (showVersion)
import GHC.IO.Encoding (setLocaleEncoding, utf8)
import System.Console.GetOpt
(OptDescr(..),ArgOrder(..),ArgDescr(..),getOpt,usageInfo)
import System.Environment (getArgs, getProgName, lookupEnv)
import System.Exit (exitFailure)
import System.FilePath (searchPathSeparator, splitSearchPath, takeDirectory)
#if __GLASGOW_HASKELL__ < 710
import Data.Monoid (mconcat)
#endif
data Options = Options
{ optLoad :: [FilePath]
, optVersion :: Bool
, optHelp :: Bool
, optBatch :: Maybe FilePath
, optCryptolrc :: Cryptolrc
, optCryptolPathOnly :: Bool
} deriving (Show)
defaultOptions :: Options
defaultOptions = Options
{ optLoad = []
, optVersion = False
, optHelp = False
, optBatch = Nothing
, optCryptolrc = CryrcDefault
, optCryptolPathOnly = False
}
options :: [OptDescr (OptParser Options)]
options =
[ Option "b" ["batch"] (ReqArg setBatchScript "FILE")
"run the script provided and exit"
, Option "v" ["version"] (NoArg setVersion)
"display version number"
, Option "h" ["help"] (NoArg setHelp)
"display this message"
, Option "" ["ignore-cryptolrc"] (NoArg setCryrcDisabled)
"disable reading of .cryptolrc files"
, Option "" ["cryptolrc-script"] (ReqArg addCryrc "FILE")
"read additional .cryptolrc files"
, Option "" ["cryptolpath-only"] (NoArg setCryptolPathOnly)
"only look for .cry files in CRYPTOLPATH; don't use built-in locations"
]
-- | Set a single file to be loaded. This should be extended in the future, if
-- we ever plan to allow multiple files to be loaded at the same time.
addFile :: String -> OptParser Options
addFile path = modify $ \ opts -> opts { optLoad = [ path ] }
-- | Set a batch script to be run.
setBatchScript :: String -> OptParser Options
setBatchScript path = modify $ \ opts -> opts { optBatch = Just path }
-- | Signal that version should be displayed.
setVersion :: OptParser Options
setVersion = modify $ \ opts -> opts { optVersion = True }
-- | Signal that help should be displayed.
setHelp :: OptParser Options
setHelp = modify $ \ opts -> opts { optHelp = True }
-- | Disable .cryptolrc files entirely
setCryrcDisabled :: OptParser Options
setCryrcDisabled = modify $ \ opts -> opts { optCryptolrc = CryrcDisabled }
-- | Add another file to read as a @.cryptolrc@ file, unless @.cryptolrc@
-- files have been disabled
addCryrc :: String -> OptParser Options
addCryrc path = modify $ \ opts ->
case optCryptolrc opts of
CryrcDefault -> opts { optCryptolrc = CryrcFiles [path] }
CryrcDisabled -> opts
CryrcFiles xs -> opts { optCryptolrc = CryrcFiles (path:xs) }
setCryptolPathOnly :: OptParser Options
setCryptolPathOnly = modify $ \opts -> opts { optCryptolPathOnly = True }
-- | Parse arguments.
parseArgs :: [String] -> Either [String] Options
parseArgs args = case getOpt (ReturnInOrder addFile) options args of
(ps,[],[]) -> runOptParser defaultOptions (mconcat ps)
(_,_,errs) -> Left errs
displayVersion :: IO ()
displayVersion = do
let ver = showVersion version
putStrLn ("Cryptol " ++ ver)
putStrLn ("Git commit " ++ commitHash)
putStrLn (" branch " ++ commitBranch ++ dirtyLab)
where
dirtyLab | commitDirty = " (non-committed files present during build)"
| otherwise = ""
displayHelp :: [String] -> IO ()
displayHelp errs = do
prog <- getProgName
let banner = "Usage: " ++ prog ++ " [OPTIONS]"
paraLines = fsep . map text . words . unlines
ppEnv (varname, desc) = hang varname 4 (paraLines $ desc)
envs = [
( "CRYPTOLPATH"
, [ "A `" ++ [searchPathSeparator] ++ "`-separated"
, "list of directories to be searched for Cryptol modules in"
, "addition to the default locations"
]
)
, ( "SBV_{ABC,BOOLECTOR,CVC4,MATHSAT,YICES,Z3}_OPTIONS"
, [ "A string of command-line arguments to be passed to the"
, "corresponding solver invoked for `:sat` and `:prove`"
]
)
]
putStrLn (usageInfo (concat (errs ++ [banner])) options)
print $ hang "Influential environment variables:"
4 (vcat (map ppEnv envs))
main :: IO ()
main = do
setLocaleEncoding utf8
args <- getArgs
case parseArgs args of
Left errs -> do
displayHelp errs
exitFailure
Right opts
| optHelp opts -> displayHelp []
| optVersion opts -> displayVersion
| otherwise -> repl (optCryptolrc opts)
(optBatch opts)
(setupREPL opts)
setupREPL :: Options -> REPL ()
setupREPL opts = do
smoke <- REPL.smokeTest
case smoke of
[] -> return ()
_ -> io $ do
print (hang "Errors encountered on startup; exiting:"
4 (vcat (map pp smoke)))
exitFailure
displayLogo True
setUpdateREPLTitle setREPLTitle
updateREPLTitle
mCryptolPath <- io $ lookupEnv "CRYPTOLPATH"
case mCryptolPath of
Nothing -> return ()
Just path | optCryptolPathOnly opts -> setSearchPath path'
| otherwise -> prependSearchPath path'
#if defined(mingw32_HOST_OS) || defined(__MINGW32__)
-- Windows paths search from end to beginning
where path' = reverse (splitSearchPath path)
#else
where path' = splitSearchPath path
#endif
case optBatch opts of
Nothing -> return ()
-- add the directory containing the batch file to the module search path
Just file -> prependSearchPath [ takeDirectory file ]
case optLoad opts of
[] -> loadPrelude `REPL.catch` \x -> io $ print $ pp x
[l] -> loadCmd l `REPL.catch` \x -> io $ print $ pp x
_ -> io $ putStrLn "Only one file may be loaded at the command line."
| ntc2/cryptol | cryptol/Main.hs | bsd-3-clause | 6,575 | 0 | 19 | 1,610 | 1,616 | 866 | 750 | 138 | 6 |
{-# LANGUAGE OverloadedStrings #-}
module SearchRepos where
import qualified Github.Search as Github
import qualified Github.Data as Github
import Control.Monad (forM,forM_)
import Data.Maybe (fromMaybe)
import Data.List (intercalate)
import System.Environment (getArgs)
import Text.Printf (printf)
import Data.Time.Clock (getCurrentTime, UTCTime(..))
import Data.Time.LocalTime (utc,utcToLocalTime,localDay,localTimeOfDay,TimeOfDay(..))
import Data.Time.Calendar (toGregorian)
main = do
args <- getArgs
date <- case args of
(x:_) -> return x
otherwise -> today
let query = "q=language%3Ahaskell created%3A>" ++ date ++ "&per_page=100"
let auth = Nothing
result <- Github.searchRepos' auth query
case result of
Left e -> putStrLn $ "Error: " ++ show e
Right r -> do forM_ (Github.searchReposRepos r) (\r -> do
putStrLn $ formatRepo r
putStrLn ""
)
putStrLn $ "Count: " ++ show n ++ " Haskell repos created since " ++ date
where n = Github.searchReposTotalCount r
-- | return today (in UTC) formatted as YYYY-MM-DD
today :: IO String
today = do
now <- getCurrentTime
let day = localDay $ utcToLocalTime utc now
(y,m,d) = toGregorian day
in return $ printf "%d-%02d-%02d" y m d
formatRepo :: Github.Repo -> String
formatRepo r =
let fields = [ ("Name", Github.repoName)
,("URL", Github.repoHtmlUrl)
,("Description", orEmpty . Github.repoDescription)
,("Created-At", formatDate . Github.repoCreatedAt)
,("Pushed-At", formatMaybeDate . Github.repoPushedAt)
]
in intercalate "\n" $ map fmt fields
where fmt (s,f) = fill 12 (s ++ ":") ++ " " ++ f r
orEmpty = fromMaybe ""
fill n s = s ++ replicate n' ' '
where n' = max 0 (n - length s)
formatMaybeDate = maybe "???" formatDate
formatDate = show . Github.fromGithubDate
| rom1504/github | samples/Search/SearchRepos.hs | bsd-3-clause | 1,991 | 0 | 18 | 529 | 618 | 328 | 290 | 47 | 3 |
module Test3 where
-- fold against a function with more than 1 argument, both used in the expression
f x y = x + y
g = f 1 2
h = f 1 1
| kmate/HaRe | old/testing/refacFunDef/Test3_TokOut.hs | bsd-3-clause | 138 | 0 | 5 | 38 | 39 | 21 | 18 | 4 | 1 |
{-# LANGUAGE TypeFamilies, QuasiQuotes, TemplateHaskell, MultiParamTypeClasses, OverloadedStrings #-}
module YesodCoreTest.Csrf (csrfSpec, Widget, resourcesApp) where
import Yesod.Core
import Test.Hspec
import Network.Wai
import Network.Wai.Test
import Web.Cookie
import qualified Data.Map as Map
import Data.ByteString.Lazy (fromStrict)
import Data.Monoid ((<>))
data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET POST
|]
instance Yesod App where
yesodMiddleware = defaultYesodMiddleware . defaultCsrfMiddleware
getHomeR :: Handler Html
getHomeR = defaultLayout
[whamlet|
<p>
Welcome to my test application.
|]
postHomeR :: Handler Html
postHomeR = defaultLayout
[whamlet|
<p>
Welcome to my test application.
|]
runner :: Session () -> IO ()
runner f = toWaiApp App >>= runSession f
csrfSpec :: Spec
csrfSpec = describe "A Yesod application with the defaultCsrfMiddleware" $ do
it "serves a includes a cookie in a GET request" $ runner $ do
res <- request defaultRequest
assertStatus 200 res
assertClientCookieExists "Should have an XSRF-TOKEN cookie" defaultCsrfCookieName
it "uses / as the path of the cookie" $ runner $ do -- https://github.com/yesodweb/yesod/issues/1247
res <- request defaultRequest
assertStatus 200 res
cookiePath <- fmap setCookiePath requireCsrfCookie
liftIO $ cookiePath `shouldBe` Just "/"
it "200s write requests with the correct CSRF header, but no param" $ runner $ do
getRes <- request defaultRequest
assertStatus 200 getRes
csrfValue <- fmap setCookieValue requireCsrfCookie
postRes <- request (defaultRequest { requestMethod = "POST", requestHeaders = [(defaultCsrfHeaderName, csrfValue)] })
assertStatus 200 postRes
it "200s write requests with the correct CSRF param, but no header" $ runner $ do
getRes <- request defaultRequest
assertStatus 200 getRes
csrfValue <- fmap setCookieValue requireCsrfCookie
let body = "_token=" <> csrfValue
postRes <- srequest $ SRequest (defaultRequest { requestMethod = "POST", requestHeaders = [("Content-Type","application/x-www-form-urlencoded")] }) (fromStrict body)
assertStatus 200 postRes
it "403s write requests without the CSRF header" $ runner $ do
res <- request (defaultRequest { requestMethod = "POST" })
assertStatus 403 res
it "403s write requests with the wrong CSRF header" $ runner $ do
getRes <- request defaultRequest
assertStatus 200 getRes
csrfValue <- fmap setCookieValue requireCsrfCookie
res <- request (defaultRequest { requestMethod = "POST", requestHeaders = [(defaultCsrfHeaderName, csrfValue <> "foo")] })
assertStatus 403 res
it "403s write requests with the wrong CSRF param" $ runner $ do
getRes <- request defaultRequest
assertStatus 200 getRes
csrfValue <- fmap setCookieValue requireCsrfCookie
let body = "_token=" <> (csrfValue <> "foo")
postRes <- srequest $ SRequest (defaultRequest { requestMethod = "POST", requestHeaders = [("Content-Type","application/x-www-form-urlencoded")] }) (fromStrict body)
assertStatus 403 postRes
requireCsrfCookie :: Session SetCookie
requireCsrfCookie = do
cookies <- getClientCookies
case Map.lookup defaultCsrfCookieName cookies of
Just c -> return c
Nothing -> error "Failed to lookup CSRF cookie"
| s9gf4ult/yesod | yesod-core/test/YesodCoreTest/Csrf.hs | mit | 3,536 | 0 | 18 | 810 | 817 | 405 | 412 | 68 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-
Copyright (C) 2009 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- Functions and data structures for wiki page layout.
-}
module Network.Gitit.Layout ( defaultPageLayout
, defaultRenderPage
, formattedPage
, filledPageTemplate
, uploadsAllowed
)
where
import Network.Gitit.Server
import Network.Gitit.Framework
import Network.Gitit.State
import Network.Gitit.Types
import Network.Gitit.Export (exportFormats)
import Network.HTTP (urlEncodeVars)
import qualified Text.StringTemplate as T
import Text.XHtml hiding ( (</>), dir, method, password, rev )
import Text.XHtml.Strict ( stringToHtmlString )
import Data.Maybe (isNothing, isJust, fromJust)
defaultPageLayout :: PageLayout
defaultPageLayout = PageLayout
{ pgPageName = ""
, pgRevision = Nothing
, pgPrintable = False
, pgMessages = []
, pgTitle = ""
, pgScripts = []
, pgShowPageTools = True
, pgShowSiteNav = True
, pgMarkupHelp = Nothing
, pgTabs = [ViewTab, EditTab, HistoryTab, DiscussTab]
, pgSelectedTab = ViewTab
, pgLinkToFeed = False
}
-- | Returns formatted page
formattedPage :: PageLayout -> Html -> Handler
formattedPage layout htmlContents = do
renderer <- queryGititState renderPage
renderer layout htmlContents
-- | Given a compiled string template, returns a page renderer.
defaultRenderPage :: T.StringTemplate String -> PageLayout -> Html -> Handler
defaultRenderPage templ layout htmlContents = do
cfg <- getConfig
base' <- getWikiBase
ok . setContentType "text/html; charset=utf-8" . toResponse . T.render .
filledPageTemplate base' cfg layout htmlContents $ templ
-- | Returns a page template with gitit variables filled in.
filledPageTemplate :: String -> Config -> PageLayout -> Html ->
T.StringTemplate String -> T.StringTemplate String
filledPageTemplate base' cfg layout htmlContents templ =
let rev = pgRevision layout
page = pgPageName layout
prefixedScript x = case x of
'h':'t':'t':'p':_ -> x
_ -> base' ++ "/js/" ++ x
scripts = ["jquery-1.2.6.min.js", "jquery-ui-combined-1.6rc2.min.js", "footnotes.js"] ++ pgScripts layout
scriptLink x = script ! [src (prefixedScript x),
thetype "text/javascript"] << noHtml
javascriptlinks = renderHtmlFragment $ concatHtml $ map scriptLink scripts
article = if isDiscussPage page then drop 1 page else page
discussion = '@':article
tabli tab = if tab == pgSelectedTab layout
then li ! [theclass "selected"]
else li
tabs' = [x | x <- pgTabs layout,
not (x == EditTab && page `elem` noEdit cfg)]
tabs = ulist ! [theclass "tabs"] << map (linkForTab tabli base' page rev) tabs'
setStrAttr attr = T.setAttribute attr . stringToHtmlString
setBoolAttr attr test = if test then T.setAttribute attr "true" else id
in T.setAttribute "base" base' .
T.setAttribute "feed" (pgLinkToFeed layout) .
setStrAttr "wikititle" (wikiTitle cfg) .
setStrAttr "pagetitle" (pgTitle layout) .
T.setAttribute "javascripts" javascriptlinks .
setStrAttr "pagename" page .
setStrAttr "articlename" article .
setStrAttr "discussionname" discussion .
setStrAttr "pageUrl" (urlForPage page) .
setStrAttr "articleUrl" (urlForPage article) .
setStrAttr "discussionUrl" (urlForPage discussion) .
setBoolAttr "ispage" (isPage page) .
setBoolAttr "isarticlepage" (isPage page && not (isDiscussPage page)) .
setBoolAttr "isdiscusspage" (isDiscussPage page) .
setBoolAttr "pagetools" (pgShowPageTools layout) .
setBoolAttr "sitenav" (pgShowSiteNav layout) .
maybe id (T.setAttribute "markuphelp") (pgMarkupHelp layout) .
setBoolAttr "printable" (pgPrintable layout) .
maybe id (T.setAttribute "revision") rev .
T.setAttribute "exportbox"
(renderHtmlFragment $ exportBox base' cfg page rev) .
(if null (pgTabs layout) then id else T.setAttribute "tabs"
(renderHtmlFragment tabs)) .
(\f x xs -> if null xs then x else f xs) (T.setAttribute "messages") id (pgMessages layout) .
T.setAttribute "usecache" (useCache cfg) .
T.setAttribute "content" (renderHtmlFragment htmlContents) .
setBoolAttr "wikiupload" ( uploadsAllowed cfg) $
templ
exportBox :: String -> Config -> String -> Maybe String -> Html
exportBox base' cfg page rev | not (isSourceCode page) =
gui (base' ++ urlForPage page) ! [identifier "exportbox"] <<
([ textfield "revision" ! [thestyle "display: none;",
value (fromJust rev)] | isJust rev ] ++
[ select ! [name "format"] <<
map ((\f -> option ! [value f] << f) . fst) (exportFormats cfg)
, primHtmlChar "nbsp"
, submit "export" "Export" ])
exportBox _ _ _ _ = noHtml
-- auxiliary functions:
linkForTab :: (Tab -> Html -> Html) -> String -> String -> Maybe String -> Tab -> Html
linkForTab tabli base' page _ HistoryTab =
tabli HistoryTab << anchor ! [href $ base' ++ "/_history" ++ urlForPage page] << "history"
linkForTab tabli _ _ _ DiffTab =
tabli DiffTab << anchor ! [href ""] << "diff"
linkForTab tabli base' page rev ViewTab =
let origPage s = if isDiscussPage s
then drop 1 s
else s
in if isDiscussPage page
then tabli DiscussTab << anchor !
[href $ base' ++ urlForPage (origPage page)] << "page"
else tabli ViewTab << anchor !
[href $ base' ++ urlForPage page ++
case rev of
Just r -> "?revision=" ++ r
Nothing -> ""] << "view"
linkForTab tabli base' page _ DiscussTab =
tabli (if isDiscussPage page then ViewTab else DiscussTab) <<
anchor ! [href $ base' ++ if isDiscussPage page then "" else "/_discuss" ++
urlForPage page] << "discuss"
linkForTab tabli base' page rev EditTab =
tabli EditTab << anchor !
[href $ base' ++ "/_edit" ++ urlForPage page ++
case rev of
Just r -> "?revision=" ++ r ++ "&" ++
urlEncodeVars [("logMsg", "Revert to " ++ r)]
Nothing -> ""] << if isNothing rev
then "edit"
else "revert"
uploadsAllowed :: Config -> Bool
uploadsAllowed = (0 <) . maxUploadSize
| bergmannf/gitit | src/Network/Gitit/Layout.hs | gpl-2.0 | 7,738 | 0 | 34 | 2,387 | 1,882 | 968 | 914 | 132 | 8 |
{-# LANGUAGE CPP #-}
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 1993-2004
--
-- The native code generator's monad.
--
-- -----------------------------------------------------------------------------
module NCGMonad (
NatM_State(..), mkNatM_State,
NatM, -- instance Monad
initNat,
addImportNat,
getUniqueNat,
mapAccumLNat,
setDeltaNat,
getDeltaNat,
getThisModuleNat,
getBlockIdNat,
getNewLabelNat,
getNewRegNat,
getNewRegPairNat,
getPicBaseMaybeNat,
getPicBaseNat,
getDynFlags,
getModLoc,
getFileId,
getDebugBlock,
DwarfFiles
)
where
#include "HsVersions.h"
import Reg
import Size
import TargetReg
import BlockId
import CLabel ( CLabel, mkAsmTempLabel )
import Debug
import FastString ( FastString )
import UniqFM
import UniqSupply
import Unique ( Unique )
import DynFlags
import Module
import Control.Monad ( liftM, ap )
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative ( Applicative(..) )
#endif
import Compiler.Hoopl ( LabelMap, Label )
data NatM_State
= NatM_State {
natm_us :: UniqSupply,
natm_delta :: Int,
natm_imports :: [(CLabel)],
natm_pic :: Maybe Reg,
natm_dflags :: DynFlags,
natm_this_module :: Module,
natm_modloc :: ModLocation,
natm_fileid :: DwarfFiles,
natm_debug_map :: LabelMap DebugBlock
}
type DwarfFiles = UniqFM (FastString, Int)
newtype NatM result = NatM (NatM_State -> (result, NatM_State))
unNat :: NatM a -> NatM_State -> (a, NatM_State)
unNat (NatM a) = a
mkNatM_State :: UniqSupply -> Int -> DynFlags -> Module -> ModLocation ->
DwarfFiles -> LabelMap DebugBlock -> NatM_State
mkNatM_State us delta dflags this_mod
= NatM_State us delta [] Nothing dflags this_mod
initNat :: NatM_State -> NatM a -> (a, NatM_State)
initNat init_st m
= case unNat m init_st of { (r,st) -> (r,st) }
instance Functor NatM where
fmap = liftM
instance Applicative NatM where
pure = return
(<*>) = ap
instance Monad NatM where
(>>=) = thenNat
return = returnNat
thenNat :: NatM a -> (a -> NatM b) -> NatM b
thenNat expr cont
= NatM $ \st -> case unNat expr st of
(result, st') -> unNat (cont result) st'
returnNat :: a -> NatM a
returnNat result
= NatM $ \st -> (result, st)
mapAccumLNat :: (acc -> x -> NatM (acc, y))
-> acc
-> [x]
-> NatM (acc, [y])
mapAccumLNat _ b []
= return (b, [])
mapAccumLNat f b (x:xs)
= do (b__2, x__2) <- f b x
(b__3, xs__2) <- mapAccumLNat f b__2 xs
return (b__3, x__2:xs__2)
getUniqueNat :: NatM Unique
getUniqueNat = NatM $ \ st ->
case takeUniqFromSupply $ natm_us st of
(uniq, us') -> (uniq, st {natm_us = us'})
instance HasDynFlags NatM where
getDynFlags = NatM $ \ st -> (natm_dflags st, st)
getDeltaNat :: NatM Int
getDeltaNat = NatM $ \ st -> (natm_delta st, st)
setDeltaNat :: Int -> NatM ()
setDeltaNat delta = NatM $ \ st -> ((), st {natm_delta = delta})
getThisModuleNat :: NatM Module
getThisModuleNat = NatM $ \ st -> (natm_this_module st, st)
addImportNat :: CLabel -> NatM ()
addImportNat imp
= NatM $ \ st -> ((), st {natm_imports = imp : natm_imports st})
getBlockIdNat :: NatM BlockId
getBlockIdNat
= do u <- getUniqueNat
return (mkBlockId u)
getNewLabelNat :: NatM CLabel
getNewLabelNat
= do u <- getUniqueNat
return (mkAsmTempLabel u)
getNewRegNat :: Size -> NatM Reg
getNewRegNat rep
= do u <- getUniqueNat
dflags <- getDynFlags
return (RegVirtual $ targetMkVirtualReg (targetPlatform dflags) u rep)
getNewRegPairNat :: Size -> NatM (Reg,Reg)
getNewRegPairNat rep
= do u <- getUniqueNat
dflags <- getDynFlags
let vLo = targetMkVirtualReg (targetPlatform dflags) u rep
let lo = RegVirtual $ targetMkVirtualReg (targetPlatform dflags) u rep
let hi = RegVirtual $ getHiVirtualRegFromLo vLo
return (lo, hi)
getPicBaseMaybeNat :: NatM (Maybe Reg)
getPicBaseMaybeNat
= NatM (\state -> (natm_pic state, state))
getPicBaseNat :: Size -> NatM Reg
getPicBaseNat rep
= do mbPicBase <- getPicBaseMaybeNat
case mbPicBase of
Just picBase -> return picBase
Nothing
-> do
reg <- getNewRegNat rep
NatM (\state -> (reg, state { natm_pic = Just reg }))
getModLoc :: NatM ModLocation
getModLoc
= NatM $ \ st -> (natm_modloc st, st)
getFileId :: FastString -> NatM Int
getFileId f = NatM $ \st ->
case lookupUFM (natm_fileid st) f of
Just (_,n) -> (n, st)
Nothing -> let n = 1 + sizeUFM (natm_fileid st)
fids = addToUFM (natm_fileid st) f (f,n)
in n `seq` fids `seq` (n, st { natm_fileid = fids })
getDebugBlock :: Label -> NatM (Maybe DebugBlock)
getDebugBlock l = NatM $ \st -> (mapLookup l (natm_debug_map st), st)
| green-haskell/ghc | compiler/nativeGen/NCGMonad.hs | bsd-3-clause | 5,312 | 0 | 18 | 1,563 | 1,624 | 885 | 739 | 144 | 2 |
{-# LANGUAGE TemplateHaskell, RankNTypes, TypeOperators, DataKinds,
PolyKinds, TypeFamilies, GADTs, TypeInType #-}
module RAE_T32a where
import Data.Kind
data family Sing (k :: *) :: k -> *
data TyArr' (a :: *) (b :: *) :: *
type TyArr (a :: *) (b :: *) = TyArr' a b -> *
type family (a :: TyArr k1 k2) @@ (b :: k1) :: k2
data TyPi' (a :: *) (b :: TyArr a *) :: *
type TyPi (a :: *) (b :: TyArr a *) = TyPi' a b -> *
type family (a :: TyPi k1 k2) @@@ (b :: k1) :: k2 @@ b
$(return [])
data MkStar (p :: *) (x :: TyArr' p *)
type instance MkStar p @@ x = *
$(return [])
data Sigma (p :: *) (r :: TyPi p (MkStar p)) :: * where
Sigma ::
forall (p :: *) (r :: TyPi p (MkStar p)) (a :: p) (b :: r @@@ a).
Sing * p -> Sing (TyPi p (MkStar p)) r -> Sing p a -> Sing (r @@@ a) b -> Sigma p r
$(return [])
data instance Sing Sigma (Sigma p r) x where
SSigma ::
forall (p :: *) (r :: TyPi p (MkStar p)) (a :: p) (b :: r @@@ a)
(sp :: Sing * p) (sr :: Sing (TyPi p (MkStar p)) r) (sa :: Sing p a) (sb :: Sing (r @@@ a) b).
Sing (Sing (r @@@ a) b) sb ->
Sing (Sigma p r) ('Sigma sp sr sa sb)
-- I (RAE) believe this last definition is ill-typed.
| snoyberg/ghc | testsuite/tests/dependent/should_fail/RAE_T32a.hs | bsd-3-clause | 1,183 | 1 | 13 | 317 | 609 | 350 | 259 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
module T12062 where
import C
$(nothing)
| ezyang/ghc | testsuite/tests/driver/T12062/T12062.hs | bsd-3-clause | 75 | 0 | 6 | 12 | 15 | 9 | 6 | 4 | 0 |
-- | Module that consolidates persistent and volatile storage for various
-- components.
--
{-# LANGUAGE Rank2Types #-}
module Dfterm3.Dfterm3State
( openStorage
, Storage() )
where
import Dfterm3.Dfterm3State.Internal.Transactions()
import Dfterm3.GameSubscription.Internal.Types
import Dfterm3.Admin.Internal.Types
import Dfterm3.Dfterm3State.Internal.Types
import System.Directory
import Control.Concurrent.MVar
import Data.Acid
import Data.IORef
import qualified Data.Map as M
import qualified Data.Set as S
openStorage :: FilePath -> IO Storage
openStorage directory = do
lock <- newMVar ()
ref <- newIORef VolatileStorageState
{ _gameSubscriptionsVolatile =
SubscriptionStateVolatile M.empty M.empty lock
, _loggedInUsers = S.empty }
createDirectoryIfMissing True directory
st <- openLocalStateFrom directory
PersistentStorageState
{ _gameSubscriptions = initialSubscriptionStatePersistent
, _admin = initialAdminStatePersistent }
return $ Storage ( st, ref )
| Noeda/dfterm3 | src/Dfterm3/Dfterm3State.hs | isc | 1,062 | 0 | 12 | 202 | 208 | 121 | 87 | 30 | 1 |
{-# LANGUAGE TemplateHaskell, CPP #-}
module Yesod.Routes.TH.RenderRoute
( -- ** RenderRoute
mkRenderRouteInstance
, mkRenderRouteInstance'
, mkRouteCons
, mkRenderRouteClauses
) where
import Yesod.Routes.TH.Types
#if MIN_VERSION_template_haskell(2,11,0)
import Language.Haskell.TH (conT)
#endif
import Language.Haskell.TH.Syntax
import Data.Maybe (maybeToList)
import Control.Monad (replicateM)
import Data.Text (pack)
import Web.PathPieces (PathPiece (..), PathMultiPiece (..))
import Yesod.Routes.Class
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative ((<$>))
import Data.Monoid (mconcat)
#endif
-- | Generate the constructors of a route data type.
mkRouteCons :: [ResourceTree Type] -> Q ([Con], [Dec])
mkRouteCons rttypes =
mconcat <$> mapM mkRouteCon rttypes
where
mkRouteCon (ResourceLeaf res) =
return ([con], [])
where
con = NormalC (mkName $ resourceName res)
$ map (\x -> (notStrict, x))
$ concat [singles, multi, sub]
singles = concatMap toSingle $ resourcePieces res
toSingle Static{} = []
toSingle (Dynamic typ) = [typ]
multi = maybeToList $ resourceMulti res
sub =
case resourceDispatch res of
Subsite { subsiteType = typ } -> [ConT ''Route `AppT` typ]
_ -> []
mkRouteCon (ResourceParent name _check pieces children) = do
(cons, decs) <- mkRouteCons children
#if MIN_VERSION_template_haskell(2,12,0)
dec <- DataD [] (mkName name) [] Nothing cons <$> fmap (pure . DerivClause Nothing) (mapM conT [''Show, ''Read, ''Eq])
#elif MIN_VERSION_template_haskell(2,11,0)
dec <- DataD [] (mkName name) [] Nothing cons <$> mapM conT [''Show, ''Read, ''Eq]
#else
let dec = DataD [] (mkName name) [] cons [''Show, ''Read, ''Eq]
#endif
return ([con], dec : decs)
where
con = NormalC (mkName name)
$ map (\x -> (notStrict, x))
$ singles ++ [ConT $ mkName name]
singles = concatMap toSingle pieces
toSingle Static{} = []
toSingle (Dynamic typ) = [typ]
-- | Clauses for the 'renderRoute' method.
mkRenderRouteClauses :: [ResourceTree Type] -> Q [Clause]
mkRenderRouteClauses =
mapM go
where
isDynamic Dynamic{} = True
isDynamic _ = False
go (ResourceParent name _check pieces children) = do
let cnt = length $ filter isDynamic pieces
dyns <- replicateM cnt $ newName "dyn"
child <- newName "child"
let pat = ConP (mkName name) $ map VarP $ dyns ++ [child]
pack' <- [|pack|]
tsp <- [|toPathPiece|]
let piecesSingle = mkPieces (AppE pack' . LitE . StringL) tsp pieces dyns
childRender <- newName "childRender"
let rr = VarE childRender
childClauses <- mkRenderRouteClauses children
a <- newName "a"
b <- newName "b"
colon <- [|(:)|]
let cons y ys = InfixE (Just y) colon (Just ys)
let pieces' = foldr cons (VarE a) piecesSingle
let body = LamE [TupP [VarP a, VarP b]] (TupE [pieces', VarE b]) `AppE` (rr `AppE` VarE child)
return $ Clause [pat] (NormalB body) [FunD childRender childClauses]
go (ResourceLeaf res) = do
let cnt = length (filter isDynamic $ resourcePieces res) + maybe 0 (const 1) (resourceMulti res)
dyns <- replicateM cnt $ newName "dyn"
sub <-
case resourceDispatch res of
Subsite{} -> return <$> newName "sub"
_ -> return []
let pat = ConP (mkName $ resourceName res) $ map VarP $ dyns ++ sub
pack' <- [|pack|]
tsp <- [|toPathPiece|]
let piecesSingle = mkPieces (AppE pack' . LitE . StringL) tsp (resourcePieces res) dyns
piecesMulti <-
case resourceMulti res of
Nothing -> return $ ListE []
Just{} -> do
tmp <- [|toPathMultiPiece|]
return $ tmp `AppE` VarE (last dyns)
body <-
case sub of
[x] -> do
rr <- [|renderRoute|]
a <- newName "a"
b <- newName "b"
colon <- [|(:)|]
let cons y ys = InfixE (Just y) colon (Just ys)
let pieces = foldr cons (VarE a) piecesSingle
return $ LamE [TupP [VarP a, VarP b]] (TupE [pieces, VarE b]) `AppE` (rr `AppE` VarE x)
_ -> do
colon <- [|(:)|]
let cons a b = InfixE (Just a) colon (Just b)
return $ TupE [foldr cons piecesMulti piecesSingle, ListE []]
return $ Clause [pat] (NormalB body) []
mkPieces _ _ [] _ = []
mkPieces toText tsp (Static s:ps) dyns = toText s : mkPieces toText tsp ps dyns
mkPieces toText tsp (Dynamic{}:ps) (d:dyns) = tsp `AppE` VarE d : mkPieces toText tsp ps dyns
mkPieces _ _ (Dynamic _ : _) [] = error "mkPieces 120"
-- | Generate the 'RenderRoute' instance.
--
-- This includes both the 'Route' associated type and the
-- 'renderRoute' method. This function uses both 'mkRouteCons' and
-- 'mkRenderRouteClasses'.
mkRenderRouteInstance :: Type -> [ResourceTree Type] -> Q [Dec]
mkRenderRouteInstance = mkRenderRouteInstance' []
-- | A more general version of 'mkRenderRouteInstance' which takes an
-- additional context.
mkRenderRouteInstance' :: Cxt -> Type -> [ResourceTree Type] -> Q [Dec]
mkRenderRouteInstance' cxt typ ress = do
cls <- mkRenderRouteClauses ress
(cons, decs) <- mkRouteCons ress
#if MIN_VERSION_template_haskell(2,12,0)
did <- DataInstD [] ''Route [typ] Nothing cons <$> fmap (pure . DerivClause Nothing) (mapM conT clazzes)
#elif MIN_VERSION_template_haskell(2,11,0)
did <- DataInstD [] ''Route [typ] Nothing cons <$> mapM conT clazzes
#else
let did = DataInstD [] ''Route [typ] cons clazzes
#endif
return $ instanceD cxt (ConT ''RenderRoute `AppT` typ)
[ did
, FunD (mkName "renderRoute") cls
] : decs
where
clazzes = [''Show, ''Eq, ''Read]
#if MIN_VERSION_template_haskell(2,11,0)
notStrict :: Bang
notStrict = Bang NoSourceUnpackedness NoSourceStrictness
#else
notStrict :: Strict
notStrict = NotStrict
#endif
instanceD :: Cxt -> Type -> [Dec] -> Dec
#if MIN_VERSION_template_haskell(2,11,0)
instanceD = InstanceD Nothing
#else
instanceD = InstanceD
#endif
| tolysz/yesod | yesod-core/Yesod/Routes/TH/RenderRoute.hs | mit | 6,448 | 0 | 21 | 1,825 | 2,008 | 1,030 | 978 | 117 | 9 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
module LambdaCmsOrg.Page.Message
( PageMessage (..)
, defaultMessage
-- * All languages
, englishMessage
) where
import Data.Monoid ((<>))
import Data.Text (Text)
data PageMessage =
MenuPage
| PageIndex
| NewPage
| EditPage
| SaveSuccess
| UpdateSuccess
| DeleteSuccess
| Type
| Content
| Save
| Back
| Delete
| CreatedOn
| ChangePageSettings
| NoPagesFound
| LogCreatedPage { title :: Text}
| LogUpdatedPage { title :: Text}
| LogDeletedPage { title :: Text}
defaultMessage :: PageMessage -> Text
defaultMessage = englishMessage
englishMessage :: PageMessage -> Text
englishMessage MenuPage = "Pages"
englishMessage PageIndex = "Page overview"
englishMessage NewPage = "New page"
englishMessage EditPage = "Edit page"
englishMessage SaveSuccess = "Successfully saved"
englishMessage UpdateSuccess = "Successfully updated"
englishMessage DeleteSuccess = "Successfully deleted"
englishMessage Type = "Type"
englishMessage Content = "Content"
englishMessage Save = "Save"
englishMessage Back = "Back"
englishMessage Delete = "Delete"
englishMessage CreatedOn = "Created on"
englishMessage ChangePageSettings = "Change page settings"
englishMessage NoPagesFound = "No pages found"
englishMessage (LogCreatedPage title) = "Created page \"" <> title <> "\""
englishMessage (LogUpdatedPage title) = "Updated page \"" <> title <> "\""
englishMessage (LogDeletedPage title) = "Deleted page \"" <> title <> "\""
| lambdacms/lambdacms.org | lambdacmsorg-page/LambdaCmsOrg/Page/Message.hs | mit | 1,750 | 0 | 8 | 463 | 338 | 191 | 147 | 48 | 1 |
module Model.Snippet (
Snippet(..),
SnippetFile(..),
MetaSnippet(..),
snippetContentHash,
snippetContentHash',
) where
import ClassyPrelude.Yesod
import Util.Hash (sha1Text)
import Data.Aeson (decode)
import Data.Maybe (fromJust)
import qualified Data.ByteString.Lazy as L
data Snippet = Snippet {
snippetId :: Text,
snippetLanguage :: Text,
snippetTitle :: Text,
snippetPublic :: Bool,
snippetOwner :: Text,
snippetFilesHash :: Text,
snippetModified :: Text,
snippetCreated :: Text,
snippetFiles :: [SnippetFile]
} deriving (Show)
data SnippetFile = SnippetFile {
snippetFileName :: Text,
snippetFileContent :: Text
} deriving (Show)
instance FromJSON SnippetFile where
parseJSON (Object v) = SnippetFile <$>
v .: "name" <*>
v .: "content"
parseJSON _ = mzero
data SnippetFilesObject = SnippetFilesObject {
objectFiles :: [SnippetFile]
} deriving (Show)
instance FromJSON SnippetFilesObject where
parseJSON (Object v) = SnippetFilesObject <$>
v .: "files"
parseJSON _ = mzero
data MetaSnippet = MetaSnippet {
metaSnippetId :: Text,
metaSnippetLanguage :: Text,
metaSnippetTitle :: Text,
metaSnippetPublic :: Bool,
metaSnippetOwner :: Text,
metaSnippetModified :: Text,
metaSnippetCreated :: Text
} deriving (Show)
snippetContentHash :: Snippet -> Text
snippetContentHash s = filesContentHash $ snippetFiles s
snippetContentHash' :: L.ByteString -> Text
snippetContentHash' bs = filesContentHash $ objectFiles $ fromJust $ (decode bs :: Maybe SnippetFilesObject)
filesContentHash :: [SnippetFile] -> Text
filesContentHash files = sha1Text . concat $ map snippetFileContent files
| vinnymac/glot-www | Model/Snippet.hs | mit | 1,725 | 0 | 9 | 345 | 448 | 262 | 186 | 53 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Graphics.Urho3D.UI.Slider(
Slider
, sliderContext
, SharedSlider
, sliderSetOrientation
, sliderSetRange
, sliderSetValue
, sliderChangeValue
, sliderSetRepeatRate
, sliderGetOrientation
, sliderGetRange
, sliderGetValue
, sliderGetKnob
, sliderGetRepeatRate
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C
import Graphics.Urho3D.UI.Internal.Slider
import Graphics.Urho3D.Core.Context
import Graphics.Urho3D.Creatable
import Graphics.Urho3D.Container.Ptr
import Graphics.Urho3D.Monad
import Data.Monoid
import Foreign
import System.IO.Unsafe (unsafePerformIO)
import Graphics.Urho3D.Core.Object
import Graphics.Urho3D.Math.StringHash
import Graphics.Urho3D.Math.Vector2
import Graphics.Urho3D.Parent
import Graphics.Urho3D.Scene.Animatable
import Graphics.Urho3D.Scene.Serializable
import Graphics.Urho3D.UI.BorderImage
import Graphics.Urho3D.UI.Element
C.context (C.cppCtx
<> sharedSliderPtrCntx
<> sliderCntx
<> contextContext
<> uiElementContext
<> borderImageContext
<> objectContext
<> animatableContext
<> serializableContext
<> vector2Context
)
C.include "<Urho3D/UI/Slider.h>"
C.using "namespace Urho3D"
sliderContext :: C.Context
sliderContext = sharedSliderPtrCntx
<> sliderCntx
instance Creatable (Ptr Slider) where
type CreationOptions (Ptr Slider) = Ptr Context
newObject ptr = liftIO $ [C.exp| Slider* { new Slider( $(Context* ptr) ) } |]
deleteObject ptr = liftIO $ [C.exp| void { delete $(Slider* ptr) } |]
deriveParents [''Object, ''Serializable, ''Animatable, ''UIElement, ''BorderImage] ''Slider
instance UIElem Slider where
uiElemType _ = unsafePerformIO $ StringHash . fromIntegral <$> [C.exp|
unsigned int { Slider::GetTypeStatic().Value() } |]
sharedPtr "Slider"
-- | Set orientation type.
-- void SetOrientation(Orientation orientation);
sliderSetOrientation :: (Parent Slider a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to slider or ascentor
-> Orientation
-> m ()
sliderSetOrientation p v = liftIO $ do
let ptr = parentPointer p
v' = fromIntegral . fromEnum $ v
[C.exp| void {$(Slider* ptr)->SetOrientation((Orientation)$(int v'))} |]
-- | Set slider range maximum value (minimum value is always 0.)
-- void SetRange(float range);
sliderSetRange :: (Parent Slider a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to slider or ascentor
-> Float -- ^ range
-> m ()
sliderSetRange p v = liftIO $ do
let ptr = parentPointer p
v' = realToFrac v
[C.exp| void {$(Slider* ptr)->SetRange($(float v'))} |]
-- | Set slider current value.
-- void SetValue(float value);
sliderSetValue :: (Parent Slider a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to slider or ascentor
-> Float -- ^ value
-> m ()
sliderSetValue p v = liftIO $ do
let ptr = parentPointer p
v' = realToFrac v
[C.exp| void {$(Slider* ptr)->SetValue($(float v'))} |]
-- | Change value by a delta.
-- void ChangeValue(float delta);
sliderChangeValue :: (Parent Slider a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to slider or ascentor
-> Float -- ^ delta
-> m ()
sliderChangeValue p v = liftIO $ do
let ptr = parentPointer p
v' = realToFrac v
[C.exp| void {$(Slider* ptr)->ChangeValue($(float v'))} |]
-- | Set paging minimum repeat rate (number of events per second).
-- void SetRepeatRate(float rate);
sliderSetRepeatRate :: (Parent Slider a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to slider or ascentor
-> Float -- ^ rate
-> m ()
sliderSetRepeatRate p v = liftIO $ do
let ptr = parentPointer p
v' = realToFrac v
[C.exp| void {$(Slider* ptr)->SetRepeatRate($(float v'))} |]
-- | Return orientation type.
-- Orientation GetOrientation() const { return orientation_; }
sliderGetOrientation :: (Parent Slider a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to slider or ascentor
-> m Orientation
sliderGetOrientation p = liftIO $ do
let ptr = parentPointer p
toEnum . fromIntegral <$> [C.exp| int {(int)$(Slider* ptr)->GetOrientation()} |]
-- | Return slider range.
-- float GetRange() const { return range_; }
sliderGetRange :: (Parent Slider a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to slider or ascentor
-> m Float
sliderGetRange p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Slider* ptr)->GetRange()} |]
-- | Return slider current value.
-- float GetValue() const { return value_; }
sliderGetValue :: (Parent Slider a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to slider or ascentor
-> m Float
sliderGetValue p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Slider* ptr)->GetValue()} |]
-- | Return knob element.
-- BorderImage* GetKnob() const { return knob_; }
sliderGetKnob :: (Parent Slider a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to slider or ascentor
-> m (Ptr BorderImage)
sliderGetKnob p = liftIO $ do
let ptr = parentPointer p
[C.exp| BorderImage* {$(Slider* ptr)->GetKnob()} |]
-- | Return paging minimum repeat rate (number of events per second).
-- float GetRepeatRate() const { return repeatRate_; }
sliderGetRepeatRate :: (Parent Slider a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to slider or ascentor
-> m Float
sliderGetRepeatRate p = liftIO $ do
let ptr = parentPointer p
realToFrac <$> [C.exp| float {$(Slider* ptr)->GetRepeatRate()} |]
| Teaspot-Studio/Urho3D-Haskell | src/Graphics/Urho3D/UI/Slider.hs | mit | 5,429 | 0 | 16 | 964 | 1,246 | 691 | 555 | -1 | -1 |
x :: Int
x = 3
| vyder/learn-haskell | play.hsproj/play.hs | mit | 15 | 0 | 4 | 6 | 11 | 6 | 5 | 2 | 1 |
module UI.BreveUI where
import qualified BreveLang
import qualified BreveEval
import qualified Synth
import Control.Monad.IO.Class (liftIO)
import Data.List ((\\))
import Data.Maybe (fromJust)
import Text.Parsec hiding (string)
import Text.Parsec.Char hiding (string)
import Text.Parsec.Language (haskell)
import Text.Parsec.String (Parser)
import Text.Parsec.Token
import qualified Graphics.UI.Threepenny as UI
import Graphics.UI.Threepenny.Core hiding ((<|>))
main :: IO ()
main = startGUI defaultConfig {jsCustomHTML = Just "index.html", jsStatic = Just "static"} setup
setup :: Window -> UI ()
setup window = do
return window # set UI.title "Script-n-Scribe"
codeBox <- codebox
traceBox <- codebox # set UI.value "Music goes here..."
snippetBox <- codebox # set UI.style [("display", "none")] # set (UI.attr "readonly") "readonly"
syncProg <- controlButton "Sync -->"
syncMusic <- controlButton "<-- Sync"
play <- controlButton "Play"
viewSnips <- controlButton "View Snippets"
viewTraces <- controlButton "View Traces" # set UI.enabled False
controls <- UI.div #. "controls" #+
map element [syncProg, syncMusic, play, viewTraces, viewSnips]
mainbox <- UI.div #. "container" #+
[ element codeBox
, element controls
, element traceBox
, element snippetBox
]
getBody window #+
[ UI.div #. "header" #+ [string "Script-N-Scribe"]
, element mainbox
]
on UI.click syncProg $ const $ do
source <- get UI.value codeBox
if null source then return syncProg else
let (_,t) = BreveEval.parseEval source in
element traceBox # set UI.value (unlines $ map show t)
on UI.click syncMusic $ const $ do
source <- get UI.value codeBox
updates <- get UI.value traceBox
if null source || null updates then return syncMusic else
let traces = snd $ BreveEval.parseEval source
upTraces = (map runParseVal $ lines updates)
subst = fromJust $ Synth.synthFaithfulLive traces upTraces in
element codeBox # set UI.value (show $ Synth.updateProgram subst (BreveEval.parse source))
on UI.click play $ const $ do
source <- get UI.value codeBox
liftIO (BreveEval.perform source)
on UI.click viewTraces $ const $ do
source <- get UI.value codeBox
if null source then return codeBox
-- no traces to get, still swap to window
else
let traces = snd $ BreveEval.parseEval source in
element traceBox # set UI.value (unlines $ map show traces)
-- switch out right-side boxes
element traceBox # set UI.style [("display", "inline-block")]
element snippetBox # set UI.style [("display", "none")]
-- disable this button
element viewTraces # set UI.enabled False
-- enable the other two
element viewSnips # set UI.enabled True
-- element viewMusic # set UI.enabled True
on UI.click viewSnips $ const $ do
-- get snippets
source <- get UI.value codeBox
let snippets = getSnippets $ fst $ BreveEval.parseEval source
-- show snippets
element snippetBox # set UI.value (unlines $ map showSnippet snippets)
-- switch out right-side boxes
element snippetBox # set UI.style [("display", "inline-block")]
element traceBox # set UI.style [("display", "none")]
-- disable this button
element viewSnips # set UI.enabled False
-- enable the other two
element viewTraces # set UI.enabled True
-- element viewMusic # set UI.enabled True
codebox :: UI Element
codebox = do
input <- UI.textarea #. "codebox" # set (UI.attr "wrap") "off"
return input
controlButton :: String -> UI Element
controlButton name = UI.button #. "controlbutton" # set UI.text name
-- readVal :: String -> BreveEval.Val
-- readVal s = case words s of
-- ("Pitch":p:t) -> BreveEval.Vp (read p) (read $ unwords t)
-- ("Int":n:t) -> BreveEval.Vn (read n) (read $ unwords t)
-- ("Double":d:t) -> BreveEval.Vd (read d) (read $ unwords t)
getSnippets :: BreveEval.EvalRes -> BreveEval.EvalRes
getSnippets = filter isMusic
where isMusic (_, v) = case v of
(BreveEval.Vnote{}) -> True
(BreveEval.Vrest{}) -> True
(BreveEval.Vpar{}) -> True
(BreveEval.Vseq{}) -> True
_ -> False
showSnippet :: BreveEval.Binding -> String
showSnippet (s, v) = s ++ ": " ++ showSnipVal v
showSnipVal :: BreveEval.Val -> String
showSnipVal v = case v of
(BreveEval.Vnote (BreveEval.Vp p _) o d) -> '(' : shows p (' ' : showsNum o (' ' : showsNum d ")"))
(BreveEval.Vrest d) -> "(rest " ++ showsNum d ")"
(BreveEval.Vseq a b) -> '(': showSnipVal a ++ ") :+: (" ++ showSnipVal b ++ ")"
(BreveEval.Vpar a b) -> '(': showSnipVal a ++ ") :=: (" ++ showSnipVal b ++ ")"
showsNum :: BreveEval.Val -> (String -> String)
showsNum (BreveEval.Vn n _) = shows n
showsNum (BreveEval.Vd d _) = shows d
-- The easiest way to get traces back from the user is to parse them.
-- This is much, MUCH neater and easier to maintain than trying to do Read
-- instances for each type (TrLoc, Val, BinOp, UnOp...)
TokenParser
{ natural = parseN
, float = parseD
, symbol = parseSymbol
, parens = parseParens
} = haskell
runParseVal :: String -> BreveEval.Val
runParseVal s = case parse parseVal "" s of
Left _ -> error $ "Failed to parse " ++ s
Right v -> v
parseVal :: Parser BreveEval.Val
parseVal = parsePitch <|> parseInt <|> parseDouble
parsePitch :: Parser BreveEval.Val
parsePitch = BreveEval.Vp
<$> (parseSymbol "Pitch" *> (read <$> parser))
<*> parseTrace
where parser = choice (map (try . parseSymbol) BreveLang.pitchClasses)
parseInt :: Parser BreveEval.Val
parseInt = BreveEval.Vn
<$> (parseSymbol "Int" *> parseN)
<*> parseTrace
parseDouble :: Parser BreveEval.Val
parseDouble = BreveEval.Vd
<$> (parseSymbol "Double" *> parseD)
<*> parseTrace
parseTrace :: Parser BreveEval.Trace
parseTrace = try parseTrLoc <|> try parseTrOp <|> try parseTrUn
parseTrLoc :: Parser BreveEval.Trace
parseTrLoc = do
parseSymbol "TrLoc"
loc <- parseParens ((,) <$> (fromInteger <$> parseN <* parseSymbol ",") <*> (fromInteger <$> parseN))
return $ BreveEval.TrLoc loc
parseTrOp :: Parser BreveEval.Trace
parseTrOp = do
parseSymbol "TrOp"
opS <- choice (map parseSymbol BreveLang.mathOps)
let op = case opS of
"+" -> BreveLang.Add
"*" -> BreveLang.Mult
"-" -> BreveLang.Sub
"/" -> BreveLang.Div
BreveEval.TrOp op <$> parseParens parseTrace <*> parseParens parseTrace
parseTrUn :: Parser BreveEval.Trace
parseTrUn = do
parseSymbol "TrUn"
opS <- choice (map parseSymbol BreveLang.unOps)
let op = case opS of
"-" -> BreveLang.Neg
BreveEval.TrUn op <$> parseParens parseTrace
| Solumin/ScriptNScribe | src/UI/BreveUI.hs | mit | 7,024 | 0 | 20 | 1,746 | 2,140 | 1,063 | 1,077 | 144 | 5 |
module Main where
import Test.Hspec
import qualified Physics.Broadphase.AabbSpec
main :: IO ()
main = hspec $
describe "TemplateSpec" Physics.Broadphase.AabbSpec.spec
| ublubu/shapes | shapes/test/Spec.hs | mit | 172 | 0 | 7 | 24 | 44 | 26 | 18 | 6 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TemplateHaskell #-}
module Greek.Dictionary.Types (
MorphEntry(..)
, Noun(..)
, Verb(..)
, Preposition(..)
, Adverb(..)
, Participle(..)
, Adjective(..)
, Pronoun(..)
, NumberGr(..)
, Gender(..)
, Case(..)
, Dialect
, Person(..)
, Tense(..)
, Mood(..)
, Voice(..)
, MorphLookup
, Morphology(..)
, Infinitive(..)
, Exclamation(..)
, Adverbial(..)
, Conjunction(..)
, Particle(..)
, Article(..)
, Numeral(..)
, Degree(..)
, Irregular(..)
, DictEntry(..)
, Translation(..)
, Feature
) where
import Data.Typeable
import Data.SafeCopy
import qualified Data.Text as T
import qualified Data.Map as M
data NumberGr = Singular
| Plural
| Dual deriving (Eq,Show,Typeable)
data Degree = NoDegree
| Comparative
| Superlative deriving (Eq,Show,Typeable)
data Gender = Masculine
| Feminine
| Neuter deriving (Eq,Show,Typeable)
data Case = Nominative
| Genitive
| Accusative
| Dative
| Vocative deriving (Eq,Show,Typeable)
type Dialect = T.Text
data Person = First
| Second
| Third deriving (Eq,Show,Typeable)
data Tense = Present
| Imperfect
| Aorist
| Perfect
| Future
| FuturePerfect
| Pluperfect deriving (Eq,Show,Typeable)
data Mood = Indicative
| Imperative
| Subjunctive
| Optative deriving (Eq,Show,Typeable)
data Voice = Active
| Passive
| Middle
| MidPass deriving (Eq,Show,Typeable)
type Feature = T.Text
type MorphLookup = M.Map T.Text [MorphEntry]
data MorphEntry = MorphEntry {
lemma :: T.Text
, wordForm :: T.Text
, morphology :: Morphology
, dialect :: [Dialect]
, feature :: Feature } deriving (Eq,Show,Typeable)
data Morphology = MorphNoun Noun
| MorphVerb Verb
| MorphPrep Preposition
| MorphPart Participle
| MorphAdj Adjective
| MorphAdv Adverb
| MorphInf Infinitive
| MorphExcl Exclamation
| MorphPron Pronoun
| MorphConj Conjunction
| MorphParc Particle
| MorphArt Article
| MorphNum Numeral
| MorphAdvl Adverbial
| MorphIrr Irregular deriving (Eq,Show,Typeable)
data Noun = Noun {
nounNumber :: Maybe NumberGr
, nounGender :: Maybe Gender
, nounCase :: Maybe Case
} deriving (Eq,Show,Typeable)
data Verb = Verb {
verbPerson :: Maybe Person
, verbNumber :: Maybe NumberGr
, verbTense :: Maybe Tense
, verbMood :: Maybe Mood
, verbVoice :: Maybe Voice
} deriving (Eq,Show,Typeable)
data Preposition = Preposition {
prepDegree :: Maybe Degree
} deriving (Eq,Show,Typeable)
data Exclamation = Exclamation deriving (Eq,Show,Typeable)
data Participle = Participle {
partNumber :: Maybe NumberGr
, partTense :: Maybe Tense
, partVoice :: Maybe Voice
, partGender :: Maybe Gender
, partCase :: Maybe Case
} deriving (Eq,Show,Typeable)
data Adjective = Adjective {
adjNumber :: Maybe NumberGr
, adjGender :: Maybe Gender
, adjCase :: Maybe Case
, adjDeg :: Maybe Degree
} deriving (Eq,Show,Typeable)
data Adverb = Adverb {
advDegree :: Maybe Degree
} deriving (Eq,Show,Typeable)
data Pronoun = Pronoun {
pronPerson :: Maybe Person
, pronNumber :: Maybe NumberGr
, pronGender :: Maybe Gender
, pronCase :: Maybe Case
} deriving (Eq,Show,Typeable)
data Infinitive = Infinitive {
infTense :: Maybe Tense
, infVoice :: Maybe Voice
} deriving (Eq,Show,Typeable)
data Article = Article {
artNumber :: Maybe NumberGr
, artGender :: Maybe Gender
, artCase :: Maybe Case
} deriving (Eq,Show,Typeable)
data Adverbial = Adverbial {
advlDegree :: Maybe Degree
} deriving (Eq,Show,Typeable)
data Conjunction = Conjunction deriving (Eq,Show,Typeable)
data Particle = Particle deriving (Eq,Show,Typeable)
data Numeral = Numeral {
numlNumber :: Maybe NumberGr
, numlGender :: Maybe Gender
, numlCase :: Maybe Case
} deriving (Eq,Show,Typeable)
data Irregular = Irregular deriving (Eq,Show,Typeable)
data DictEntry = DictEntry {
dictKey :: T.Text
, dictID :: T.Text
, dictOrth :: T.Text
, dictTrans :: [Translation]
} deriving (Eq,Show,Typeable)
data Translation = Translation {
transLevel :: Int
, transN :: Int
, transID :: T.Text
, translation :: T.Text
} deriving (Eq,Show,Typeable)
$(deriveSafeCopy 0 'base ''Case)
$(deriveSafeCopy 0 'base ''Degree)
$(deriveSafeCopy 0 'base ''NumberGr)
$(deriveSafeCopy 0 'base ''Gender)
$(deriveSafeCopy 0 'base ''Tense)
$(deriveSafeCopy 0 'base ''Voice)
$(deriveSafeCopy 0 'base ''Mood)
$(deriveSafeCopy 0 'base ''Person)
$(deriveSafeCopy 0 'base ''Adverb)
$(deriveSafeCopy 0 'base ''Adverbial)
$(deriveSafeCopy 0 'base ''Conjunction)
$(deriveSafeCopy 0 'base ''Infinitive)
$(deriveSafeCopy 0 'base ''Irregular)
$(deriveSafeCopy 0 'base ''Numeral)
$(deriveSafeCopy 0 'base ''Pronoun)
$(deriveSafeCopy 0 'base ''Adjective)
$(deriveSafeCopy 0 'base ''Noun)
$(deriveSafeCopy 0 'base ''Exclamation)
$(deriveSafeCopy 0 'base ''Preposition)
$(deriveSafeCopy 0 'base ''Article)
$(deriveSafeCopy 0 'base ''Participle)
$(deriveSafeCopy 0 'base ''Particle)
$(deriveSafeCopy 0 'base ''Verb)
$(deriveSafeCopy 0 'base ''Morphology)
$(deriveSafeCopy 0 'base ''MorphEntry)
$(deriveSafeCopy 0 'base ''Translation)
$(deriveSafeCopy 0 'base ''DictEntry) | boundedvariation/ntbible | Greek/Dictionary/Types.hs | mit | 5,531 | 4 | 9 | 1,278 | 1,886 | 1,058 | 828 | 191 | 0 |
-----------------------------------------------------------------------------
--
-- Module : PhyQ.Test.Units.SISpec
-- Copyright :
-- License : MIT
--
-- Maintainer : -
-- Stability :
-- Portability :
--
-- |
--
module PhyQ.Test.Units.SISpec (spec) where
import PhyQ.Test.Common
import PhyQ.SI
import PhysicalQuantities.Decomposition (tDecomposition)
-----------------------------------------------------------------------------
spec = describe "Unit" $ do
it "can be decomposed to base quantities (including at type level)" $ do
tDecomposition (unitInstance :: Kilogramm) `shouldBe` [("Kilogramm", 1)]
tDecomposition (unitInstance :: Newton) `shouldBe` [ ("Kilogramm", 1)
, ("Meter", 1)
, ("Second", -2)
]
it "can be compared at type level" $ do
correct (B::B( EqU Newton (Kilogramm:*Meter:/(Second:^2)) ))
correct (B::B( EqU (Newton:*Second) (Kilogramm:*Meter:/Second) ))
correct (B::B( EqU (Newton:/Kilogramm) (Meter:/(Second:^2)) ))
correct (B::B( EqU (Meter:/Second:/Newton) (Second:/Kilogramm) ))
it "can be converted to standard unit representation" $ example pending
| fehu/PhysicalQuantities | test/PhyQ/Test/Units/SISpec.hs | mit | 1,305 | 0 | 20 | 355 | 333 | 185 | 148 | -1 | -1 |
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
{-# LANGUAGE OverloadedStrings #-}
{-|
Copyright : (c) Microsoft
License : MIT
Maintainer : adamsap@microsoft.com
Stability : alpha
Portability : portable
Helper functions for combining elements into common constructs. These functions
can be used in code generation to lazily combine 'Text' elements but they are
more generic and work for any 'Monoid'.
-}
module Language.Bond.Util
( sepBy
, sepEndBy
, sepBeginBy
, optional
, angles
, brackets
, braces
, parens
, between
) where
import Data.Monoid
import Data.String (IsString)
import Prelude
-- | Maps elements of a list and combines them with 'mappend' using given
-- separator, ending with a separator.
sepEndBy :: (Monoid a, Eq a) => a -> (t -> a) -> [t] -> a
sepEndBy _ _ [] = mempty
sepEndBy s f (x:xs)
| next == mempty = rest
| otherwise = next <> s <> rest
where
next = f x
rest = sepEndBy s f xs
-- | Maps elements of a list and combines them with 'mappend' using given
-- separator, starting with a separator.
sepBeginBy :: (Monoid a, Eq a) => a -> (t -> a) -> [t] -> a
sepBeginBy _ _ [] = mempty
sepBeginBy s f (x:xs)
| next == mempty = rest
| otherwise = s <> next <> rest
where
next = f x
rest = sepBeginBy s f xs
-- | Maps elements of a list and combines them with 'mappend' using given
-- separator.
sepBy :: (Monoid a, Eq a) => a -> (t -> a) -> [t] -> a
sepBy _ _ [] = mempty
sepBy s f (x:xs)
| null xs = next
| next == mempty = rest
| otherwise = next <> sepBeginBy s f xs
where
next = f x
rest = sepBy s f xs
-- | The function takes a function and a Maybe value. If the Maybe value is
-- Nothing, the function returns 'mempty', otherwise, it applies the function
-- to the value inside 'Just' and returns the result.
optional :: (Monoid m) => (a -> m) -> Maybe a -> m
optional = maybe mempty
-- | If the 3rd argument is not 'mempty' the function wraps it between the
-- first and second argument using 'mappend', otherwise it return 'mempty'.
between :: (Monoid a, Eq a) => a -> a -> a -> a
between l r m
| m == mempty = mempty
| otherwise = l <> m <> r
angles, brackets, braces, parens :: (Monoid a, IsString a, Eq a) => a -> a
-- | Wraps the string argument between @<@ and @>@, unless the argument is
-- 'mempty' in which case the function returns 'mempty'.
angles m = between "<" ">" m
-- | Wraps the string argument between @[@ and @]@, unless the argument is
-- 'mempty' in which case the function returns 'mempty'.
brackets m = between "[" "]" m
-- | Wraps the string argument between @{@ and @}@, unless the argument is
-- 'mempty' in which case the function returns 'mempty'.
braces m = between "{" "}" m
-- | Wraps the string argument between @(@ and @)@, unless the argument is
-- 'mempty' in which case the function returns 'mempty'.
parens m = between "(" ")" m
| upsoft/bond | compiler/src/Language/Bond/Util.hs | mit | 3,082 | 0 | 9 | 754 | 671 | 359 | 312 | 47 | 1 |
module Type.Subst
( skolemise
, subst
, subst_
, freeVars
, getFreeVars
) where
import qualified Data.Map as M
import qualified Data.Set as S
import Type.Meta
import Type.Types
skolemise :: Sigma -> TI ([TyVar], Rho)
skolemise (TyForall tvs rho) = do
sks1 <- mapM newSkolemTyVar tvs
(sks2, rho') <- skolemise (subst_ tvs (map TyVar sks1) rho)
return (sks1 ++ sks2, rho')
skolemise (TyArr sigma1 sigma2) = do
(sks, rho2) <- skolemise sigma2
return (sks, TyArr sigma1 rho2)
skolemise tau = return ([], tau)
subst :: M.Map TyVar Tau -> Type -> Type
subst env (TyForall tvs rho) = mkForall tvs (subst env' rho)
where env' = foldr M.delete env tvs
subst env (TyArr sigma1 sigma2) = TyArr (subst env sigma1) (subst env sigma2)
subst env tau@(TyCon _) = tau
subst env tau@(TyVar tv) = M.findWithDefault tau tv env
subst env (TyAp tau1 tau2) = TyAp (subst env tau1) (subst env tau2)
subst env tau@(TyMeta _) = tau
subst_ :: [TyVar] -> [Tau] -> Type -> Type
subst_ tvs = subst . M.fromList . zip tvs
freeVars :: Type -> S.Set TyVar
freeVars (TyForall tvs rho) = freeVars rho S.\\ S.fromList tvs
freeVars (TyArr sigma1 sigma2) = S.union tvs1 tvs2
where tvs1 = freeVars sigma1
tvs2 = freeVars sigma2
freeVars tau = go tau S.empty
where go (TyCon _) = id
go (TyVar tv) = S.insert tv
go (TyAp tau1 tau2) = go tau1 . go tau2
go (TyMeta _) = id
getFreeVars :: [Type] -> TI (S.Set TyVar)
getFreeVars = fmap (S.unions . map freeVars) . mapM zonk
| meimisaki/Rin | src/Type/Subst.hs | mit | 1,483 | 0 | 12 | 312 | 696 | 354 | 342 | 41 | 4 |
module Widget.Languages (
languagesWidget
) where
import Import
import qualified Glot.Language as Language
languagesWidget :: [Language.Language] -> Widget
languagesWidget languages =
$(widgetFile "widgets/languages")
| prasmussen/glot-www | Widget/Languages.hs | mit | 228 | 0 | 7 | 33 | 51 | 30 | 21 | -1 | -1 |
{-# LANGUAGE BangPatterns, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
module MachineLearning.Protobufs.Algorithm (Algorithm(..)) where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data Algorithm = BOOSTING
| RANDOM_FOREST
deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable Algorithm
instance Prelude'.Bounded Algorithm where
minBound = BOOSTING
maxBound = RANDOM_FOREST
instance P'.Default Algorithm where
defaultValue = BOOSTING
toMaybe'Enum :: Prelude'.Int -> P'.Maybe Algorithm
toMaybe'Enum 1 = Prelude'.Just BOOSTING
toMaybe'Enum 2 = Prelude'.Just RANDOM_FOREST
toMaybe'Enum _ = Prelude'.Nothing
instance Prelude'.Enum Algorithm where
fromEnum BOOSTING = 1
fromEnum RANDOM_FOREST = 2
toEnum
= P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type MachineLearning.Protobufs.Algorithm") .
toMaybe'Enum
succ BOOSTING = RANDOM_FOREST
succ _ = Prelude'.error "hprotoc generated code: succ failure for type MachineLearning.Protobufs.Algorithm"
pred RANDOM_FOREST = BOOSTING
pred _ = Prelude'.error "hprotoc generated code: pred failure for type MachineLearning.Protobufs.Algorithm"
instance P'.Wire Algorithm 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 Algorithm
instance P'.MessageAPI msg' (msg' -> Algorithm) Algorithm where
getVal m' f' = f' m'
instance P'.ReflectEnum Algorithm where
reflectEnum = [(1, "BOOSTING", BOOSTING), (2, "RANDOM_FOREST", RANDOM_FOREST)]
reflectEnumInfo _
= P'.EnumInfo (P'.makePNF (P'.pack ".protobufs.Algorithm") ["MachineLearning"] ["Protobufs"] "Algorithm")
["MachineLearning", "Protobufs", "Algorithm.hs"]
[(1, "BOOSTING"), (2, "RANDOM_FOREST")] | ajtulloch/haskell-ml | MachineLearning/Protobufs/Algorithm.hs | mit | 2,225 | 0 | 11 | 344 | 569 | 308 | 261 | 46 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-instanceipv6address.html
module Stratosphere.ResourceProperties.EC2InstanceInstanceIpv6Address where
import Stratosphere.ResourceImports
-- | Full data type definition for EC2InstanceInstanceIpv6Address. See
-- 'ec2InstanceInstanceIpv6Address' for a more convenient constructor.
data EC2InstanceInstanceIpv6Address =
EC2InstanceInstanceIpv6Address
{ _eC2InstanceInstanceIpv6AddressIpv6Address :: Val Text
} deriving (Show, Eq)
instance ToJSON EC2InstanceInstanceIpv6Address where
toJSON EC2InstanceInstanceIpv6Address{..} =
object $
catMaybes
[ (Just . ("Ipv6Address",) . toJSON) _eC2InstanceInstanceIpv6AddressIpv6Address
]
-- | Constructor for 'EC2InstanceInstanceIpv6Address' containing required
-- fields as arguments.
ec2InstanceInstanceIpv6Address
:: Val Text -- ^ 'eciiiaIpv6Address'
-> EC2InstanceInstanceIpv6Address
ec2InstanceInstanceIpv6Address ipv6Addressarg =
EC2InstanceInstanceIpv6Address
{ _eC2InstanceInstanceIpv6AddressIpv6Address = ipv6Addressarg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-instanceipv6address.html#cfn-ec2-instance-instanceipv6address-ipv6address
eciiiaIpv6Address :: Lens' EC2InstanceInstanceIpv6Address (Val Text)
eciiiaIpv6Address = lens _eC2InstanceInstanceIpv6AddressIpv6Address (\s a -> s { _eC2InstanceInstanceIpv6AddressIpv6Address = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/EC2InstanceInstanceIpv6Address.hs | mit | 1,601 | 0 | 13 | 164 | 174 | 100 | 74 | 23 | 1 |
{-------------------------------------------------------------------------------
Copyright: The Hatchet Team (see file Contributors)
Module: DependAnalysis
Description: Compute the dependencies between values. Can
be used for computing the dependencies in
variables and also the dependencies in types.
The code is used in type inference and
also kind inference.
Primary Authors: Bernie Pope, Robert Shelton
Notes: See the file License for license information
-------------------------------------------------------------------------------}
module FrontEnd.DependAnalysis (getBindGroups, debugBindGroups) where
import Data.Graph(stronglyConnComp, SCC(..))
import Data.List (nub)
-- Given a list of nodes, a function to convert nodes to a unique name, a function
-- to convert nodes to a list of names on which the node is dependendant, bindgroups
-- will return a list of bind groups generater from the list of nodes given.
getBindGroups :: Ord name =>
[node] -> -- List of nodes
(node -> name) -> -- Function to convert nodes to a unique name
(node -> [name]) -> -- Function to return dependencies of this node
[[node]] -- Bindgroups
getBindGroups ns fn fd = map f $ stronglyConnComp [ (n, fn n, fd n) | n <- ns] where
f (AcyclicSCC x) = [x]
f (CyclicSCC xs) = xs
{-
getBindGroups ns getName getDeps
= [ mapOnList nameToNodeFM group | group <- nameGroups ]
where
nameGroups = buildNameGroups nameList nameEdges
nameList = map getName ns
nameEdges = buildNameEdges ns getName getDeps
nameToNodeFM = listToFM [ (getName x, x) | x <- ns ]
getBindGroups ns toName getDeps = filter (not . null) (map (concatMap f) $ Scc.scc ds) where
f n = case M.lookup n m of
--Nothing -> error $ "cannot find " ++ show n ++ " in " ++ unlines (map show (sort ds))
--Just x -> x
Nothing -> fail "Nothing"
Just x -> return x
ds = [ (toName x, getDeps x) | x <- ns ]
m = M.fromList [ (toName x,x) | x <- ns]
-}
--
-- Create a list of edges from a list of nodes.
--
buildNameEdges :: [node] -> -- List of nodes
(node -> name) -> -- Function to convert nodes to a unique name
(node -> [name]) -> -- Function to return dependencies of this node
[(name,name)] -- Edges from list of nodes.
buildNameEdges [] _ _
= []
buildNameEdges (n:ns) getName getDeps
= map mapFunc (getDeps n) ++ (buildNameEdges ns getName getDeps)
where
mapFunc = ( \ s -> (getName n, s) )
--
-- Create a list of groups from a list of names.
--
{-
buildNameGroups :: Ord name =>
[name] -> -- list of names
[(name,name)] -> -- List of edges
[[name]] -- List of bindgroups
buildNameGroups ns es
= [ mapOnList intToNameFM group | group <- intGroups ]
where
intGroups = map preorder $ scc $ buildG (1, sizeFM nameToIntFM) intEdges
intEdges = mapOnTuple nameToIntFM es
nameToIntFM = listToFM nameIntList
intToNameFM = listToFM [ (y,x) | (x,y) <- nameIntList ]
nameIntList = zip ns [1..]
--
-- Use a finitemap to convert a list of type A into a list of type B
-- NB, not being able to find an element in the FM is not considered
-- an error.
--
mapOnList :: Ord a =>
FiniteMap a b -> -- Finite map from a to b
[a] -> -- List of a
[b] -- List of b
mapOnList _ [] = []
mapOnList fm (a:as)
= case (lookupFM fm a) of
Just b -> b : mapOnList fm as
Nothing -> mapOnList fm as
--
-- Use a finitemap to convert a 2 tuple to a different type.
-- NB, not being able to find an element in the FM is not considered
-- an error.
--
mapOnTuple :: Ord a =>
FiniteMap a b ->
[(a,a)] ->
[(b,b)]
mapOnTuple _ [] = []
mapOnTuple fm ((a1,a2):as)
= case (lookupFM fm a1) of
Just x ->
case (lookupFM fm a2) of
Just y -> (x,y) : (mapOnTuple fm as)
Nothing -> mapOnTuple fm as
Nothing -> mapOnTuple fm as
-}
--------------------------------------------------------------------------------
-- showBindGroups
--------------------------------------------------------------------------------
--
-- Display bind group information in a human readable (or as close to) form.
--
showBindGroups :: [[node]] -> -- List of nodes
(node->String) -> -- Function to convert a node to a string
String -- Printable string
showBindGroups ns getAlias
= showBindGroups_ ns getAlias 0
--
-- Recursive function which does the work of showBindGroups.
--
showBindGroups_ :: [[node]] -> -- List of nodes
(node->String) -> -- Function to convert a node to a string
Int -> -- Bind group number
String -- Printable string
showBindGroups_ [] _ _
= ""
showBindGroups_ (n:ns) getAlias groupNum
= "Bindgroup " ++ show groupNum ++ " = "
++ bgString ++ "\n"
++ showBindGroups_ ns getAlias (groupNum + 1)
where
bgString = wrapString "EMPTY" (listToString n getAlias)
--------------------------------------------------------------------------------
-- debugBindGroups
--------------------------------------------------------------------------------
--
-- Display bind group information in a human readable (or as close to) form.
-- Also display dependencie and error information. Warning this function is slow
-- and fat. But without forcing name to be of type Ord, it is hard to improve
-- the algorithm.
--
debugBindGroups :: (Eq name) =>
[[node]] -> -- List of nodes
(node->String) -> -- Function to produce a printable name for the node
(node->name) -> -- Function to convert nodes to a unique name
(node->[name]) -> -- Function to return dependencies of this node
String -- Printable string
debugBindGroups ns getAlias getName getDeps
= debugBindGroups_ ns getAlias getName getDeps 0 []
--
-- Recursive function which does the work of showBindGroups.
--
debugBindGroups_ :: (Eq name) =>
[[node]] -> -- List of nodes
(node->String) -> -- Function to produce a printable name for the node
(node->name) -> -- Function to convert nodes to a unique name
(node->[name]) -> -- Function to return dependencies of this node
Int -> -- Bind group number
[(Int,[name])] -> -- History information of names already processed
String -- Printable string
debugBindGroups_ [] _ _ _ _ _
= ""
debugBindGroups_ (n:ns) getAlias getName getDeps groupNum history
= show groupNum ++ " = "
++ bgString ++ "\n"
++ debugBindGroups_ ns getAlias getName getDeps (groupNum + 1) newHistory
where
bgString = showBindGroup (expandBindGroup n getAlias getDeps newHistory)
newHistory = history ++ [(groupNum, [ getName x | x <- n ])]
--
-- Expand bindgroups, generating dependancie and error information.
--
expandBindGroup :: (Eq name) =>
[node] -> -- List of nodes
(node->String) -> -- Function to produce a printable name for the node
(node->[name]) -> -- Function to return dependencies of this node
[(Int,[name])] -> -- History information of names already processed
([String], [Int], [String]) -- Printable string in form (bindgroup, bgnums, Errors)
expandBindGroup [] _ _ _
= ([],[],[])
expandBindGroup (n:ns) getAlias getDeps history
= if err
then (name:a, bgs++b, name:c)
else (name:a, bgs++b, c)
where
name = getAlias n
(bgs, err) = inHistory (getDeps n) history
(a,b,c) = expandBindGroup ns getAlias getDeps history
-- NB ticti, you should not be calling inHistory on the name, but instead on the deps.
--
-- Convert the information generated by expandBindGroup into a printable
-- form.
--
showBindGroup :: ([String],[Int],[String]) -> String
showBindGroup (bg, deps, errors)
= bgString ++ " " ++ depString ++ " " ++ errString
where
bgString = wrapString [] $ listToString bg id
depString = wrapString [] $ listToString (nub deps) show
errString = wrapString [] $ listToString errors id
--
-- Convert a list of something, into a printable string.
--
listToString :: [a] -> -- List of things
(a->String) -> -- Function to convert things to Strings
String -- Single printable String.
listToString [] _
= ""
listToString [l] lFunc
= (lFunc l)
listToString (l:ls) lFunc
= (lFunc l) ++ ", " ++ listToString ls lFunc
--
-- Given a list of names and the history of visited names, this function
-- generates a list of bindgroups that are depended upon as well as returning
-- a boolean value indicating whether all these dependencies are satisfied.
--
-- True -> ERROR, a name needed now has not been resolved.
--
inHistory :: Eq name =>
[name] -> -- List of names to be searched for
[(Int,[name])] -> -- History information of names already processed
([Int],Bool) -- Number of bind group that name is in, or its own alias.
inHistory [] _
= ([],False)
inHistory (name:names) history
= if location < 0
then (bgs, False)
else (location : bgs, err)
where
location = searchHistory name history
(bgs, err) = inHistory names history
--
-- Check whether a particular name has occured befor and return the number
-- of the bindgroup it occured in.
--
searchHistory :: Eq name =>
name -> -- List of names to be searched for
[(Int,[name])] -> -- History information of names already processed
Int -- Bindgroup num that name occurred in (-1 is error)
searchHistory _ []
= -1
searchHistory name ((bgnum, bgnames):history)
= if elem name bgnames
then bgnum
else searchHistory name history
--
-- Neatly brackets a string using a replacement string (rep) if empty.
--
wrapString :: String -> String -> String
wrapString rep "" = "[" ++ rep ++ "]"
wrapString _ s = "[" ++ s ++ "]"
| dec9ue/jhc_copygc | src/FrontEnd/DependAnalysis.hs | gpl-2.0 | 10,624 | 62 | 14 | 3,122 | 1,657 | 942 | 715 | 115 | 2 |
-- (1.5 балла)
module Eval
( Eval, runEval
, Error, Store
, update, getVar
) where
import qualified Data.Map as M
import Data.List
import Control.Monad
import Expr
type Error = String
type Store = M.Map String Value
newtype Eval a = Eval { runEval :: Store -> (Maybe a, [Error], Store) }
instance Monad Eval where
return x = Eval undefined
Eval m >>= k = Eval undefined
-- MonadPlus - аналог Alternative для монад
-- mzero - вычисление, которое ничего не делает, сразу завершается неуспехом
-- mplus m1 m2 пытается выполнить m1, если тот завершился неуспехом, выполняет m2
-- Примеры использования этого класса есть в Utils.hs
instance MonadPlus Eval where
mzero = Eval undefined
mplus (Eval l) (Eval r) = Eval undefined
update :: String -> Value -> Eval ()
update k v = Eval undefined
getVar :: String -> Eval Value
getVar v = Eval undefined
| nkartashov/haskell | hw10/Interpreter/Eval.hs | gpl-2.0 | 1,046 | 0 | 9 | 188 | 233 | 129 | 104 | 21 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
import Control.Applicative
import Control.Monad.IO.Class
import Control.Monad.State
import Control.Concurrent.MVar
import qualified Data.Text as T
import Network.IRC
import Network.IRC.Action
import Module.CatDetection
import Module.Scheme
ircNick, ircAltNick, ircRealname :: T.Text
ircNick = "exampleBot"
ircAltNick = ircNick `T.append` "_"
ircRealname = ircAltNick `T.append` "_"
freenode :: IrcServer
freenode = IrcServer
{ host = "irc.freenode.org"
, port = 6667
, channels = ["#felixsch"]
, nick = ircNick
, altNick = ircAltNick
, realName = ircRealname
, password = Nothing }
data ExampleBot = ExampleBot
{ recordedWords :: Int
, quit :: MVar Bool
, admins :: [Cloak]
, schemeEnv :: Env ExampleBot
, catEnv :: CatEnv ExampleBot }
instance WithPriviliges ExampleBot where
hasPrivilige "admin" cloak = do
adms <- admins <$> get
logM "privs" $ cloak `T.append` " == " `T.append` "admin?!"
return $ cloak `elem` adms
hasPrivilige _ _ = return False
instance WithScheme ExampleBot where
getEnv = schemeEnv <$> get
putEnv s = modify (\dat -> dat { schemeEnv = s })
instance WithCatDetection ExampleBot where
catTmpImage = return "/tmp/ircbot-catscanner"
catModel = return "cat.xml"
catFoundMsg = return "Awww I love cats. What a cute one!"
catRememberMsg = return "Ah I remember this kitten"
catGetEnv = catEnv <$> get
catSetEnv s = modify (\env -> env { catEnv = s})
initExampleBot :: IO ExampleBot
initExampleBot = do
trigger <- newEmptyMVar
return ExampleBot
{ recordedWords = 0
, quit = trigger
, admins = []
, schemeEnv = newEnvWith 4000
, catEnv = newCatEnv }
runExampleBot :: ExampleBot -> IO (Maybe IrcError)
runExampleBot bot = do
status <- runIrcMonad [freenode] bot (defaultIrcLogger True Nothing) (start exampleBotBehaviour)
waitUntil $ quit bot
return status
where
waitUntil = void . readMVar
exampleBotBehaviour :: Action ExampleBot ()
exampleBotBehaviour = countWords >> checkForCat
>> catStats "!catStats"
>> quitBot "!die"
>> schemeEval ">"
>> schemeGetDefined "!defined"
>> schemeClearState "!clearState" (newEnvWith 4000)
main :: IO ()
main = do
bot <- initExampleBot
status <- runExampleBot bot
case status of
Just err -> print err
Nothing -> putStrLn "Bye Bye!"
quitBot :: T.Text -> Action ExampleBot ()
quitBot tr = whenAdmin $ whenTrigger tr $ \dest _ -> do
trigger <- quit <$> get
me dest "is going offline"
liftIO $ putMVar trigger True
countWords :: Action ExampleBot ()
countWords = onPrivMsg checkTrigger
where
checkTrigger dest (x:xs)
| x == "?recorded" = showCountedWords dest
| otherwise = modify (\dat -> dat { recordedWords = recordedWords dat + (length xs) + 1})
showCountedWords dest = do
count <- recordedWords <$> get
say dest $ "Recorded " `T.append` T.pack (show count) `T.append` " words."
| felixsch/ircbot | src/Example.hs | gpl-2.0 | 3,363 | 0 | 16 | 989 | 908 | 480 | 428 | 88 | 2 |
module QHaskell.Expression.ADTUntypedDebruijn
(Exp(..),Fun(..)) where
import QHaskell.MyPrelude
import QHaskell.Variable.Plain
import qualified QHaskell.Type.ADT as TA
data Fun = Fun Exp
deriving instance Eq Fun
deriving instance Show Fun
data Exp = ConI Word32
| ConB Bool
| ConF Float
| Var Var
| Prm Var [Exp]
| Abs Fun
| App Exp Exp
| Cnd Exp Exp Exp
| Tpl Exp Exp
| Fst Exp
| Snd Exp
| LeT Exp Fun
| Typ TA.Typ Exp
| Int Word32
| Mem Exp
| Fix Exp
deriving instance Eq Exp
deriving instance Show Exp
| shayan-najd/QHaskell | QHaskell/Expression/ADTUntypedDebruijn.hs | gpl-3.0 | 669 | 0 | 7 | 255 | 187 | 111 | 76 | -1 | -1 |
import GHC.Exts
showUnboxedInt :: Int# -> String
showUnboxedInt n = (show $ I# n) ++ "#"
main = do
print $ showUnboxedInt 1
| adarqui/ToyBox | haskell/haskell/ghc-exts/src/ex1.hs | gpl-3.0 | 127 | 0 | 8 | 26 | 52 | 26 | 26 | -1 | -1 |
-- TabCode - A parser for the Tabcode lute tablature language
--
-- Copyright (C) 2015-2017 Richard Lewis
-- Author: Richard Lewis <richard@rjlewis.me.uk>
-- This file is part of TabCode
-- TabCode is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- TabCode 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 TabCode. If not, see <http://www.gnu.org/licenses/>.
module TabCode.Types where
import Data.Set (size, fromList)
import Data.Vector (Vector)
import Text.ParserCombinators.Parsec.Pos (Line, Column)
data Duration
= Fermata
| Breve
| Semibreve
| Minim
| Crotchet
| Quaver
| Semiquaver
| Demisemiquaver
| Hemidemisemiquaver
| Semihemidemisemiquaver
deriving (Eq, Show)
data Dot
= Dot
| NoDot
deriving (Eq, Show)
data Beam a
= BeamOpen a
| BeamClose a
deriving (Eq, Show)
beamDuration :: Int -> Duration
beamDuration 1 = Quaver
beamDuration 2 = Semiquaver
beamDuration 3 = Demisemiquaver
beamDuration 4 = Hemidemisemiquaver
beamDuration 5 = Semihemidemisemiquaver
beamDuration _ = error "Invalid beam count"
data Beat
= Simple
| Compound
deriving (Eq, Show)
data RhythmSign = RhythmSign Duration Beat Dot (Maybe (Beam Duration)) deriving (Eq, Show)
-- FIXME Perhaps this data model should rather be a numeric fret
-- number and then any symbol from the source should be captured as
-- another part of the Note type
data Fret = A | B | C | D | E | F | G | H | I | J | K | L | M | N deriving (Eq, Show, Ord)
data Course
= One
| Two
| Three
| Four
| Five
| Six
| Bass Int
deriving (Eq, Show, Ord)
data Attachment
= PosAboveLeft
| PosAbove
| PosAboveRight
| PosLeft
| PosRight
| PosBelowLeft
| PosBelow
| PosBelowRight
deriving (Eq, Show)
data Finger
= FingerOne
| FingerTwo
| FingerThree
| FingerFour
| Thumb deriving (Eq, Show)
data Fingering
= FingeringLeft Finger (Maybe Attachment)
| FingeringRight Finger (Maybe Attachment)
deriving (Eq, Show)
type OrnSubtype = Int
-- FIXME Work out the proper ornament names
data Ornament
= OrnA (Maybe OrnSubtype) (Maybe Attachment)
| OrnB (Maybe OrnSubtype) (Maybe Attachment)
| OrnC (Maybe OrnSubtype) (Maybe Attachment)
| OrnD (Maybe OrnSubtype) (Maybe Attachment)
| OrnE (Maybe OrnSubtype) (Maybe Attachment)
| OrnF (Maybe OrnSubtype) (Maybe Attachment)
| OrnG (Maybe OrnSubtype) (Maybe Attachment)
| OrnH (Maybe OrnSubtype) (Maybe Attachment)
| OrnI (Maybe OrnSubtype) (Maybe Attachment)
| OrnJ (Maybe OrnSubtype) (Maybe Attachment)
| OrnK (Maybe OrnSubtype) (Maybe Attachment)
| OrnL (Maybe OrnSubtype) (Maybe Attachment)
| OrnM (Maybe OrnSubtype) (Maybe Attachment)
deriving (Eq, Show)
data SepareePosition
= SepareeLeft
| SepareeRight
| SepareeCentre
deriving (Eq, Show)
data SepareeDirection
= SepareeUp
| SepareeDown
deriving (Eq, Show)
data Articulation
= Ensemble
| Separee (Maybe SepareeDirection) (Maybe SepareePosition)
deriving (Eq, Show)
data SlurDirection
= SlurUp
| SlurDown
deriving (Eq, Show)
type ConnectingId = Int
data Connecting
= Slur SlurDirection
| StraightFrom ConnectingId (Maybe Attachment)
| StraightTo ConnectingId (Maybe Attachment)
| CurvedUpFrom ConnectingId (Maybe Attachment)
| CurvedUpTo ConnectingId (Maybe Attachment)
| CurvedDownFrom ConnectingId (Maybe Attachment)
| CurvedDownTo ConnectingId (Maybe Attachment)
deriving (Eq, Show)
data Note = Note Course Fret (Maybe Fingering, Maybe Fingering) (Maybe Ornament) (Maybe Articulation) (Maybe Connecting) deriving (Eq, Show)
duplicateCoursesInNotes :: [Note] -> Bool
duplicateCoursesInNotes ns =
length cs > size (fromList cs)
where cs = coursesFromNotes ns
duplicateCourses :: TabWord -> Bool
duplicateCourses (Chord _ _ _ ns _) = duplicateCoursesInNotes ns
duplicateCourses _ = False
data Counting
= Counting
| NotCounting
deriving (Eq, Show)
data Dashed
= Dashed
| NotDashed
deriving (Eq, Show)
data RepeatMark
= RepeatLeft
| RepeatRight
| RepeatBoth
deriving (Eq, Show)
data Repetition
= Reprise
| NthTime Int
deriving (Eq, Show)
data Bar
= SingleBar (Maybe RepeatMark) (Maybe Repetition) Dashed Counting
| DoubleBar (Maybe RepeatMark) (Maybe Repetition) Dashed Counting
deriving (Eq, Show)
data Mensuration
= PerfectMajor
| PerfectMinor
| ImperfectMajor
| ImperfectMinor
| HalfPerfectMajor
| HalfPerfectMinor
| HalfImperfectMajor
| HalfImperfectMinor
| Beats Int
deriving (Eq, Show)
data MeterSign
= SingleMeterSign Mensuration
| VerticalMeterSign Mensuration Mensuration
| HorizontalMeterSign Mensuration Mensuration
deriving (Eq, Show)
data Comment
= Comment String
deriving (Eq, Show)
data TabWord
= Chord Line Column (Maybe RhythmSign) [Note] (Maybe Comment)
| Rest Line Column RhythmSign (Maybe Comment)
| BarLine Line Column Bar (Maybe Comment)
| Meter Line Column MeterSign (Maybe Comment)
| CommentWord Line Column Comment
| SystemBreak Line Column (Maybe Comment)
| PageBreak Line Column (Maybe Comment)
| Invalid String Line Column String
deriving (Eq, Show)
twPos :: TabWord -> (Line, Column)
twPos (Chord l c _ _ _) = (l, c)
twPos (Rest l c _ _) = (l, c)
twPos (BarLine l c _ _) = (l, c)
twPos (Meter l c _ _) = (l, c)
twPos (CommentWord l c _) = (l, c)
twPos (SystemBreak l c _) = (l, c)
twPos (PageBreak l c _) = (l, c)
twPos (Invalid _ l c _) = (l, c)
twLine :: TabWord -> Line
twLine = fst . twPos
twColumn :: TabWord -> Column
twColumn = snd . twPos
coursesFromNotes :: [Note] -> [Course]
coursesFromNotes ns = map (\(Note crs _ _ _ _ _) -> crs) ns
courses :: TabWord -> [Course]
courses (Chord _ _ _ ns _) = coursesFromNotes ns
courses _ = []
data Rule = Rule String String deriving (Eq, Show)
ruleLkup :: [Rule] -> String -> Maybe String
ruleLkup rls rl = lookup rl rlsMap
where
rlsMap = map (\(Rule r v) -> (r, v)) rls
notation :: [Rule] -> Maybe String
notation = (flip ruleLkup) "notation"
title :: [Rule] -> Maybe String
title = (flip ruleLkup) "title"
data TabCode = TabCode [Rule] (Vector TabWord)
| TransformingMusicology/tabcode-haskell | src/TabCode/Types.hs | gpl-3.0 | 6,509 | 0 | 11 | 1,288 | 2,024 | 1,120 | 904 | 194 | 1 |
module OpenGL.GLFW.Types
(
GLvoid,
GLchar,
GLenum,
GLboolean,
GLbitfield,
GLbyte,
GLshort,
GLint,
GLsizei,
GLubyte,
GLushort,
GLuint,
GLfloat,
GLclampf,
GLfixed,
GLclampx,
GLintptr,
GLsizeiptr,
) where
import Foreign.C.Types
type GLvoid =
()
type GLchar =
CChar
type GLenum =
CUInt
type GLboolean =
CUChar
type GLbitfield =
CUInt
type GLbyte =
CSChar
type GLshort =
CShort
type GLint =
CInt
type GLsizei =
CInt
type GLubyte =
CUChar
type GLushort =
CUShort
type GLuint =
CUInt
type GLfloat =
CFloat
type GLclampf =
CFloat
type GLfixed =
CInt
type GLclampx =
CInt
type GLintptr =
CLong
type GLsizeiptr =
CLong
| karamellpelle/grid | designer/source/OpenGL/GLFW/Types.hs | gpl-3.0 | 781 | 0 | 5 | 269 | 180 | 120 | 60 | 57 | 0 |
{-|
Defines a 3-layered Vector and relative utilties.
-}
module Game.TicTacToe3D.Vector3 where
import Data.List (unfoldr)
import Data.Vector (Vector)
import qualified Data.Vector as V
{-|
Represents a 3-layered structure.
-}
type Dim3 a b = a (a (a b))
{-|
Represents a 3-layered vector.
-}
type V3 a = Dim3 Vector a
{-|
Represents an index of a 3-layered vector.
-}
type I3 = (Int, Int, Int)
{-|
>>> base 2 10
[0, 1, 0, 1]
-}
base :: Int -> Int -> [Int]
base i n = unfoldr f n ++ repeat 0 where
f b = if b /= 0 then Just (pair b i) else Nothing where
pair n i = (n `mod` i, n `div` i)
{-|
>>> i3 1
(1, 0, 0)
>>> i3 26
(1, 1, 1)
-}
i3 :: Int -> I3
i3 i = t $ base 3 i where t (x:y:z:_) = (x, y, z)
{-|
Retrieves the specified location's element.
-}
(!) :: V3 a -> I3 -> a
v ! (x, y, z) = v V.! x V.! y V.! z
{-|
Replaces the specified location's element
and retrieves the updated vector.
-}
(//) ::V3 a -> (I3, a) -> V3 a
v // ((x, y, z), n) = (setf x $ setf y $ setv z n) v where
setf i f y = setv i (f $ y V.! i) y
setv i m y = y V.// [(i, m)]
{-|
Initializes a vector with the given values.
-}
init :: Int -> (I3 -> a) -> V3 a
init i f =
V.generate i $ \x ->
V.generate i $ \y ->
V.generate i $ \z ->
f (x, y, z)
| ryo0ka/tictactoe3d | src/Game/TicTacToe3D/Vector3.hs | gpl-3.0 | 1,309 | 8 | 12 | 377 | 545 | 300 | 245 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-
hbot - a simple Haskell chat bot for Hipchat
Copyright (C) 2014 Louis J. Scoras
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
module Hbot.MsgParser.Test where
import Data.Maybe (fromJust)
import Test.Tasty
import Test.Tasty.HUnit
import Hbot.MsgParser
tests = testGroup "Parser Tests"
[ testCase "Return nothing if prefix isn't matched" noPrefix
, prefixWhitespaceTests
, testCase "Splits the command from the rest of the content" endToEnd
]
noPrefix :: Assertion
noPrefix = parseMsg ">>" ": Not prefixed correctly" @=? Nothing
prefixWhitespaceTests :: TestTree
prefixWhitespaceTests = testGroup "Prefix whitespace" $
[ testCase "Removes leading space" $ try " >> foo bar baz"
, testCase "Removes trailing spaces" $ try ">> foo bar baz"
, testCase "Removes all spaces around prefix" $ try " >> foo bar baz"
]
where
try msg = case parseMsg ">>" msg of
Just command -> pluginName command @=? "foo"
Nothing -> fail "Should have parsed correctly"
endToEnd :: Assertion
endToEnd = case parseMsg ":" ":command the rest " of
Just cmd -> (pluginName cmd, messageText cmd) @=? ("command", "the rest ")
Nothing -> fail "Should have parsed correctly"
| ljsc/hbot | tests/Hbot/MsgParser/Test.hs | gpl-3.0 | 1,899 | 0 | 11 | 432 | 242 | 125 | 117 | 24 | 2 |
module GGen.Geometry.Face ( moveVertex
) where
import Data.VectorSpace
import GGen.Geometry.Types
-- | If the given point v is a vertex of the face, move it to v'. Otherwise
-- return the original face.
moveVertex :: Face -> P3 -> P3 -> Face
moveVertex (Face n (a,b,c)) v v' = let a' = if a =~ v then v' else a
b' = if b =~ v then v' else b
c' = if c =~ v then v' else c
in Face n (a',b',c')
| bgamari/GGen | GGen/Geometry/Face.hs | gpl-3.0 | 533 | 0 | 10 | 225 | 142 | 82 | 60 | 8 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module Endpoints.ProjectEndpoints where
import Data.Acid
import Data.Text
import Data.Maybe (fromMaybe)
import qualified Data.Text.Lazy as LT (fromStrict)
import qualified Data.Text.Encoding as TE (encodeUtf8, decodeUtf8)
import qualified Data.ByteString.Lazy as LBS (fromStrict, toStrict)
import qualified Data.Map as Map
import Data.Monoid
import Pages.Core
import Pages.ProjectPage
import Auth
import AcidDatabase
import AbsDatabase
import Endpoints.Common
import Network.HTTP.Types
import Network.Wai.Parse
import Control.Monad.IO.Class (liftIO, MonadIO)
import Control.Monad (liftM, when, unless)
import qualified Web.Scotty as S
import qualified Web.Scotty.Cookie as SC
getProjectFile :: AcidState Database -> S.ActionM ()
getProjectFile db = do
projName <- S.param "project"
filename <- S.param "filename"
mproj <- liftIO $ query db (GetProject projName)
case mproj of
Nothing -> S.status badRequest400
Just project -> do
let fm = projectFilesMap project
case Map.lookup filename fm of
Nothing -> S.status badRequest400
Just (File _ fileData) -> do
S.setHeader "Content-Disposition" $ LT.fromStrict $TE.decodeUtf8 filename
S.raw $ LBS.fromStrict fileData
updateProjectFile :: AcidState Database -> S.ActionM ()
updateProjectFile db = do
uri <- getServerUri db
authenticated <- isAuthenticated uri
if authenticated
then do
projectName <- S.param "project"
(Just project) <- liftIO $ query db (GetProject projectName)
((_, fileinfo): _) <- S.files
let filesMap' = Map.insert (fileName fileinfo) file (projectFilesMap project)
file = File (fileName fileinfo) (LBS.toStrict (fileContent fileinfo))
project' = project {projectFilesMap = filesMap'}
liftIO $ update db (UpdateProject project')
liftIO $ print $ mconcat ["file ", fileName fileinfo, " added"]
S.redirect $ LT.fromStrict uri
`S.rescue` (\msg -> do
S.status badRequest400
S.text msg)
else
S.status unauthorized401
updateProjectPost :: AcidState Database -> S.ActionM ()
updateProjectPost db =
do
projectName <- S.param "project"
(Just project) <- liftIO $ query db (GetProject projectName)
contentType <- S.header "Content-Type"
authorName <- S.param "author-name"
authorImage <- S.param "author-image"
authorUri <- S.param "author-uri"
heading <- S.param "heading"
date <- S.param "date"
content <- S.param "content"
let author = Author authorName authorImage authorUri
post = Post author heading date content []
postsMap' = Map.insert heading post (projectPostsMap project)
project' = project {projectPostsMap = postsMap'}
liftIO $ update db (UpdateProject project')
uri <- getServerUri db
S.redirect $ LT.fromStrict uri
`S.rescue` (\msg -> do
S.status badRequest400
S.text msg)
presentProject :: AcidState Database -> Text -> Text -> S.ActionM ()
presentProject db "" _ = do
(Project n _ _ _ _) <- liftIO $ query db GetMainProject
presentProject db n ""
presentProject db projName postHeading = do
mproj <- liftIO $ query db (GetProject projName)
mpost <- liftIO $ query db (GetPost projName postHeading)
uri <- getServerUri db
case mproj of
Nothing -> S.redirect $ LT.fromStrict uri
Just proj -> do
cookieCode <- liftM (fromMaybe "") $ SC.getCookie $ getCookieName uri
let authenticated = cookieCode /= ""
vs <- liftIO $ query db GetVerificationUris
S.html $ renderCore vs uri$ do
renderProject mpost proj
renderAdminBar authenticated uri
| DunderRoffe/sjolind.se | src/Endpoints/ProjectEndpoints.hs | gpl-3.0 | 3,965 | 0 | 20 | 1,074 | 1,215 | 597 | 618 | 94 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : Postmaster.FSM.DataHandler
Copyright : (c) 2004-2008 by Peter Simons
License : GPL2
Maintainer : simons@cryp.to
Stability : provisional
Portability : Haskell 2-pre
-}
module Postmaster.FSM.DataHandler where
import Data.Typeable
import Postmaster.Base
newtype DH = DH DataHandler
deriving (Typeable)
dataHandler :: SmtpdVariable
dataHandler = defineLocal "datahandler"
setDataHandler :: DataHandler -> Smtpd ()
setDataHandler f = dataHandler (`setVar` DH f)
getDataHandler :: Smtpd DataHandler
getDataHandler = dataHandler getVar_ >>= \(DH f) -> return f
feed :: DataHandler
feed buf = getDataHandler >>= ($ buf)
| richardfontana/postmaster | Postmaster/FSM/DataHandler.hs | gpl-3.0 | 720 | 0 | 8 | 146 | 136 | 76 | 60 | 14 | 1 |
module FrSIRSNetwork.Init (
createFrSIRSNetworkRandInfected,
createFrSIRSNetworkNumInfected
) where
import FrSIRSNetwork.Model
import FrSIRSNetwork.Agent
import FRP.Yampa
import FRP.FrABS
import Data.List
import System.Random
import Control.Monad.Random
createFrSIRSNetworkRandInfected :: Double
-> NetworkType
-> IO ([FrSIRSNetworkAgentDef], FrSIRSNetworkEnvironment)
createFrSIRSNetworkRandInfected p network =
do
e <- evalRandIO $ createNetwork network unitEdgeLabeler
let agentIds = nodesOfNetwork e
adefs <- mapM (randomFrSIRSNetworkAgent p) agentIds
return (adefs, e)
-- NOTE: numInfected > agentCount = error ("Can't create more infections (" ++ show numInfected ++ ") than there are agents (" ++ show agentCount)
createFrSIRSNetworkNumInfected :: Int
-> NetworkType
-> IO ([FrSIRSNetworkAgentDef], FrSIRSNetworkEnvironment)
createFrSIRSNetworkNumInfected numInfected network =
do
e <- evalRandIO $ createNetwork network unitEdgeLabeler
let degs = networkDegrees e
let sortedDegs = Data.List.sortBy highestDegree degs
let infectedIds = take numInfected $ map fst sortedDegs
let susceptibleIds = drop numInfected $ map fst sortedDegs
adefsSusceptible <- mapM (frSIRSNetworkAgent Susceptible) susceptibleIds
adefsInfected <- mapM (frSIRSNetworkAgent Infected) infectedIds
return (adefsSusceptible ++ adefsInfected, e)
where
highestDegree :: (AgentId, Int) -> (AgentId, Int) -> Ordering
highestDegree = (\(_, d1) (_, d2) -> compare d2 d1)
lowestDegree :: (AgentId, Int) -> (AgentId, Int) -> Ordering
lowestDegree = (\(_, d1) (_, d2) -> compare d1 d2)
frSIRSNetworkAgent :: SIRSState
-> AgentId
-> IO FrSIRSNetworkAgentDef
frSIRSNetworkAgent initS aid =
do
rng <- newStdGen
let beh = sirsNetworkAgentBehaviour rng initS
return $ createFrSIRSNetworkDef aid initS beh rng
randomFrSIRSNetworkAgent :: Double
-> AgentId
-> IO FrSIRSNetworkAgentDef
randomFrSIRSNetworkAgent p aid =
do
rng <- newStdGen
r <- getStdRandom (randomR(0.0, 1.0))
let isInfected = r <= p
let initS = if isInfected then Infected else Susceptible
let beh = sirsNetworkAgentBehaviour rng initS
return $ createFrSIRSNetworkDef aid initS beh rng
createFrSIRSNetworkDef :: AgentId
-> SIRSState
-> FrSIRSNetworkAgentBehaviour
-> StdGen
-> FrSIRSNetworkAgentDef
createFrSIRSNetworkDef aid sirsState beh rng =
AgentDef { adId = aid,
adState = sirsState,
adBeh = beh,
adInitMessages = NoEvent,
adConversation = Nothing,
adRng = rng }
------------------------------------------------------------------------------------------------------------------------ | thalerjonathan/phd | coding/libraries/chimera/examples/ABS/SIRExamples/FrSIRSNetwork/Init.hs | gpl-3.0 | 3,247 | 0 | 11 | 1,032 | 686 | 355 | 331 | 67 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Analytics.Management.Experiments.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists experiments to which the user has access.
--
-- /See:/ <https://developers.google.com/analytics/ Google Analytics API Reference> for @analytics.management.experiments.list@.
module Network.Google.Resource.Analytics.Management.Experiments.List
(
-- * REST Resource
ManagementExperimentsListResource
-- * Creating a Request
, managementExperimentsList
, ManagementExperimentsList
-- * Request Lenses
, melWebPropertyId
, melProFileId
, melAccountId
, melStartIndex
, melMaxResults
) where
import Network.Google.Analytics.Types
import Network.Google.Prelude
-- | A resource alias for @analytics.management.experiments.list@ method which the
-- 'ManagementExperimentsList' request conforms to.
type ManagementExperimentsListResource =
"analytics" :>
"v3" :>
"management" :>
"accounts" :>
Capture "accountId" Text :>
"webproperties" :>
Capture "webPropertyId" Text :>
"profiles" :>
Capture "profileId" Text :>
"experiments" :>
QueryParam "start-index" (Textual Int32) :>
QueryParam "max-results" (Textual Int32) :>
QueryParam "alt" AltJSON :> Get '[JSON] Experiments
-- | Lists experiments to which the user has access.
--
-- /See:/ 'managementExperimentsList' smart constructor.
data ManagementExperimentsList =
ManagementExperimentsList'
{ _melWebPropertyId :: !Text
, _melProFileId :: !Text
, _melAccountId :: !Text
, _melStartIndex :: !(Maybe (Textual Int32))
, _melMaxResults :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ManagementExperimentsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'melWebPropertyId'
--
-- * 'melProFileId'
--
-- * 'melAccountId'
--
-- * 'melStartIndex'
--
-- * 'melMaxResults'
managementExperimentsList
:: Text -- ^ 'melWebPropertyId'
-> Text -- ^ 'melProFileId'
-> Text -- ^ 'melAccountId'
-> ManagementExperimentsList
managementExperimentsList pMelWebPropertyId_ pMelProFileId_ pMelAccountId_ =
ManagementExperimentsList'
{ _melWebPropertyId = pMelWebPropertyId_
, _melProFileId = pMelProFileId_
, _melAccountId = pMelAccountId_
, _melStartIndex = Nothing
, _melMaxResults = Nothing
}
-- | Web property ID to retrieve experiments for.
melWebPropertyId :: Lens' ManagementExperimentsList Text
melWebPropertyId
= lens _melWebPropertyId
(\ s a -> s{_melWebPropertyId = a})
-- | View (Profile) ID to retrieve experiments for.
melProFileId :: Lens' ManagementExperimentsList Text
melProFileId
= lens _melProFileId (\ s a -> s{_melProFileId = a})
-- | Account ID to retrieve experiments for.
melAccountId :: Lens' ManagementExperimentsList Text
melAccountId
= lens _melAccountId (\ s a -> s{_melAccountId = a})
-- | An index of the first experiment to retrieve. Use this parameter as a
-- pagination mechanism along with the max-results parameter.
melStartIndex :: Lens' ManagementExperimentsList (Maybe Int32)
melStartIndex
= lens _melStartIndex
(\ s a -> s{_melStartIndex = a})
. mapping _Coerce
-- | The maximum number of experiments to include in this response.
melMaxResults :: Lens' ManagementExperimentsList (Maybe Int32)
melMaxResults
= lens _melMaxResults
(\ s a -> s{_melMaxResults = a})
. mapping _Coerce
instance GoogleRequest ManagementExperimentsList
where
type Rs ManagementExperimentsList = Experiments
type Scopes ManagementExperimentsList =
'["https://www.googleapis.com/auth/analytics",
"https://www.googleapis.com/auth/analytics.edit",
"https://www.googleapis.com/auth/analytics.readonly"]
requestClient ManagementExperimentsList'{..}
= go _melAccountId _melWebPropertyId _melProFileId
_melStartIndex
_melMaxResults
(Just AltJSON)
analyticsService
where go
= buildClient
(Proxy :: Proxy ManagementExperimentsListResource)
mempty
| brendanhay/gogol | gogol-analytics/gen/Network/Google/Resource/Analytics/Management/Experiments/List.hs | mpl-2.0 | 5,122 | 0 | 20 | 1,203 | 674 | 392 | 282 | 104 | 1 |
-- GSoC 2015 - Haskell bindings for OpenCog.
{-# LANGUAGE GADTs #-}
-- | Simple example on inserting and removing many atoms in a new AtomSpace.
import OpenCog.AtomSpace (AtomSpace,insert,get,remove,
debug,runOnNewAtomSpace,printAtom,(|>),(\>),
Atom(..),TruthVal(..),Gen(..),noTv,stv)
import Control.Monad.IO.Class (liftIO)
main :: IO ()
main = runOnNewAtomSpace program
program :: AtomSpace ()
program = let a = AndLink (stv 0.5 0.5)
|> ConceptNode "John" noTv
\> ConceptNode "Carlos" noTv
in do
liftIO $ putStrLn "Let's insert some new nodes:"
liftIO $ printAtom $ ConceptNode "Tall" noTv
insert $ ConceptNode "Tall" noTv
insert a
liftIO $ printAtom a
liftIO $ putStrLn $ replicate 60 '-'
liftIO $ putStrLn "After Insert:"
debug
liftIO $ putStrLn $ replicate 60 '-'
n <- get a
case n of
Just at -> liftIO $ putStrLn "AndLink found:" >> printAtom at
Nothing -> liftIO $ putStrLn "No AndLink found."
remove a
liftIO $ putStrLn $ replicate 60 '-'
liftIO $ putStrLn "After Remove:"
debug
liftIO $ putStrLn $ replicate 60 '-'
n <- get a
case n of
Just (AndLink _ _) -> liftIO $ putStrLn "AndLink found:"
Nothing -> liftIO $ putStrLn "No AndLink found."
let list = ListLink [ Gen $ NumberNode 4
, Gen $ ConceptNode "hello" noTv
, Gen $ NumberNode 4]
insert list
liftIO $ putStrLn "Inserted:"
liftIO $ printAtom list
| virneo/atomspace | examples/haskell/example.hs | agpl-3.0 | 1,725 | 0 | 15 | 627 | 481 | 231 | 250 | 40 | 3 |
import Graphics.Implicit
import Graphics.Implicit.Definitions
import Graphics.Implicit.Primitives
roundbox:: SymbolicObj3
roundbox = implicit (\(x,y,z) -> x^4 + y^4 + z^4 - 15000) ((-20,-20,-20),(20,20,20))
main = writeSTL 2 "example16.stl" roundbox
| krakrjak/ImplicitCAD | Examples/example16.hs | agpl-3.0 | 252 | 0 | 13 | 29 | 116 | 67 | 49 | 6 | 1 |
-- file: ch13/buildmap.hs
import qualified Data.Map as Map
-- Functions to generate a Map that represents an association list
-- as a map
al = [(1, "one"), (2, "two"), (3, "three"), (4, "four")]
{- | Create a map representation of 'al' by converting the association
- list using Map.fromList -}
mapFromAL =
Map.fromList al
{- | Create a map representation of 'al' by doing a fold -}
mapFold =
foldl (\map (k, v) -> Map.insert k v map) Map.empty al
{- | Manually create a map with the elements of 'al' in it -}
mapManual =
Map.insert 2 "two" .
Map.insert 4 "four" .
Map.insert 1 "one" .
Map.insert 3 "three" $ Map.empty
| caiorss/Functional-Programming | haskell/rwh/ch13/buildmap.hs | unlicense | 651 | 0 | 10 | 144 | 156 | 89 | 67 | 11 | 1 |
import Control.Parallel.Strategies
n = 100000000
main = print . sum . withStrategy (parListChunk n r0) $ map (*2) [1..100000000]
| Crazycolorz5/Haskell-Code | parTest.hs | unlicense | 132 | 0 | 9 | 22 | 54 | 29 | 25 | 3 | 1 |
slice :: [a] -> Int -> Int -> [a]
slice (x:xs) _ 1 = [x]
slice (x:xs) 1 b = (x:slice xs 1 (b-1))
slice (x:xs) a b = slice xs (a-1) (b-1)
| plilja/h99 | p18.hs | apache-2.0 | 138 | 0 | 9 | 34 | 126 | 67 | 59 | 4 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Actions.ManagePlans.Delete.Handler (handler) where
import qualified Data.Text.Lazy as TL
import Web.Scotty (params, redirect)
import App (Action, PGPool, Cookies, runQuery)
import Auth (checkLogged)
import Persistence.Plan (deletePlan)
import Actions.Responses (errorResponse)
import Actions.ManagePlans.Url (url)
handler :: PGPool -> Cookies -> Action
handler pool cookies = checkLogged pool cookies (\_ -> do
ps <- params
case lookup "planId" ps of
Nothing -> errorResponse "planId parametre missing -- probably a system error, please contact the administrator."
Just planIdStr -> do
let planId = read $ TL.unpack planIdStr :: Int
_ <- runQuery pool $ deletePlan planId
redirect $ TL.pack url
)
| DataStewardshipPortal/ds-wizard | DSServer/app/Actions/ManagePlans/Delete/Handler.hs | apache-2.0 | 793 | 0 | 20 | 154 | 217 | 118 | 99 | 18 | 2 |
module RayCaster.Quaternion where
import RayCaster.Utils
import RayCaster.Vector
data Quaternion =
Quaternion Double
Vector
vectorToQuaternion :: Vector -> Quaternion
vectorToQuaternion = Quaternion 0
quaternionToVector :: Quaternion -> Vector
quaternionToVector (Quaternion _ vector) = vector
rotationQuaternion :: Vector -> Double -> Quaternion
rotationQuaternion (Vector x y z) angle =
let halfAngle = 0.5 * angle
c = cos halfAngle
s = sin halfAngle
in Quaternion c (Vector (x * s) (y * s) (z * s))
conjugate :: Quaternion -> Quaternion
conjugate (Quaternion w vector) = Quaternion w (neg vector)
quatMult :: Quaternion -> Quaternion -> Quaternion
(Quaternion w1 v1) `quatMult` (Quaternion w2 v2) =
Quaternion
(w1 * w2 - (v1 `dot` v2))
((v1 `cross` v2) `add` (w1 `scalarMult` v2) `add` (w2 `scalarMult` v1))
rotate :: Vector -> Double -> Vector -> Vector
rotate axis angleInDegrees point =
let angle = degreesToRadians angleInDegrees
normalizedAxis = normalize axis
rotQuat = rotationQuaternion normalizedAxis angle
rotQuatConjugate = conjugate rotQuat
pointQuat = vectorToQuaternion point
in quaternionToVector $
(rotQuat `quatMult` pointQuat) `quatMult` rotQuatConjugate
| bkach/HaskellRaycaster | src/RayCaster/Quaternion.hs | apache-2.0 | 1,278 | 0 | 11 | 268 | 410 | 221 | 189 | 32 | 1 |
{-
Implement an addressable symbolic memory that can store cells as
well as native bytes.
-}
module Language.Forth.Interpreter.CellMemory (CellMemory, dpOffset, StorageUnit(..),
newCellMemory,
readCell, writeCell, read8CM, write8CM,
blockMoveTextCM, alignDP,
updateDataPointer, validAddressCM) where
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.Vector.Storable.ByteString as B
import Data.Word
import Language.Forth.Interpreter.Address
import Language.Forth.CellVal
import Language.Forth.Target
import Util.Address
import Util.Endian
data CellMemory a = CellMemory
{ contents :: IntMap (StorageUnit a)
, target :: Target
, dpOffset :: Int
}
data StorageUnit a = Part Int (CellVal a) | Byte Word8
newCellMemory :: Target -> Int -> CellMemory a
newCellMemory target size = CellMemory IntMap.empty target size
readCell :: Addr -> CellMemory a -> Maybe (CellVal a)
readCell (Addr _ i) mem =
case IntMap.lookup i (contents mem) of
Just (Part _ cell) -> Just cell
otherwise -> Nothing
writeCell :: CellVal a -> Addr -> CellMemory a -> CellMemory a
writeCell val (Addr _ i) mem =
mem { contents = IntMap.insert i (Part 0 val) (contents mem) }
read8CM :: Addr -> CellMemory a -> Maybe (StorageUnit a)
read8CM (Addr _ i) mem = IntMap.lookup i (contents mem)
write8CM :: Word8 -> Addr -> CellMemory a -> CellMemory a
write8CM val (Addr _ i) mem = mem { contents = IntMap.insert i (Byte val) (contents mem) }
-- | Apply a function to the datapointer to advance it, return the
-- previous value of it
updateDataPointer :: (Int -> Int) -> CellMemory a -> (Int, CellMemory a)
updateDataPointer f mem = (dpOffset mem, mem { dpOffset = f (dpOffset mem) })
blockMoveTextCM text (Addr _ offset) cm =
let im' = IntMap.fromList $ zip [offset..] (map Byte $ B.unpack text)
in cm { contents = IntMap.union im' (contents cm) }
validAddressCM (Addr _ offset) cm = offset < dpOffset cm && offset >= 0
alignDP mem target = mem { dpOffset = alignOffset (dpOffset mem) target }
| hth313/hthforth | src/Language/Forth/Interpreter/CellMemory.hs | bsd-2-clause | 2,231 | 0 | 14 | 552 | 712 | 380 | 332 | 40 | 2 |
{-# LANGUAGE BangPatterns #-}
import Data.Array.Unboxed
import Data.Monoid
mkIndices rows cols = [ (x, y) | x <- [1..rows], y <- [1..cols]]
type Graph = UArray (Int, Int) Int
mkGraph :: [[Int]] -> Graph
mkGraph words = array ((1,1),(rows, cols)) elems :: Graph
where rows = length words
cols = length (head words)
indices = mkIndices rows cols
elems = zip indices (concat words)
ex1 = [ [9,9,4]
, [4,6,8]
, [2,1,1] ] :: [[Int]]
gr1 = mkGraph ex1
-- find adjcent nodes
nexts :: Graph -> (Int, Int) -> Int -> Int -> [(Int, Int)]
nexts g (x, y) rows cols = filter (connected (x, y)) . filter (uncurry valid) $ [ (x-1, y), (x+1, y), (x, y-1), (x, y+1)]
where valid i j | i < 1 || j < 1 || i > rows || j > cols = False
| otherwise = True
connected from to = (g ! from) < (g ! to)
data Matched = Matched Int [Int]
instance Monoid Matched where
mempty = Matched 0 []
a@(Matched x xs) `mappend` b@(Matched y ys) | y > x = b
| y <= x = a
instance Show Matched where
show (Matched _ xs) = show (reverse xs)
append x (Matched y ys) = (Matched (succ y) (x:ys))
dfsHelper :: Graph -> Matched -> UArray (Int, Int) Bool -> (Int, Int) -> Matched
dfsHelper g m v s | null adjs = m'
| otherwise = foldMap (uncurry (dfsHelper g m')) (zip vs adjs)
where (_, (!rows, !cols)) = bounds g
adjs = filter (\t -> not (v ! t)) (nexts g s rows cols)
vs = fmap (\t -> v // [ (s, True) ]) adjs -- mark s as visited
m' = append (g ! s) m
dfs g s = dfsHelper g mempty (amap (\_ -> False) g) s
dff g = mconcat [ dfs g (x, y) | x <- [1..rows], y <- [1..cols]]
where (_, (!rows, !cols)) = bounds g
| wangbj/leet | 329.hs | bsd-2-clause | 1,751 | 0 | 16 | 520 | 942 | 507 | 435 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.Hoodle.Render.Debug
-- Copyright : (c) 2011-2013 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <ianwookim@gmail.com>
-- Stability : experimental
-- Portability : GHC
--
-- collection of rendering routine
--
-----------------------------------------------------------------------------
module Graphics.Hoodle.Render.Debug
(
-- * dummy rendering
renderRBkg_Dummy
-- * render in bbox using non R-structure
-- , renderBkg_InBBox
-- * nopdf
, renderRBkg_NoPDF
-- * render only bbox (for debug purpose)
, renderStrkBBx_BBoxOnly
, renderImgBBx_BBoxOnly
, renderRItem_BBoxOnly
, renderRLayer_BBoxOnly
, renderRPage_BBoxOnly
-- * render using buf
, renderRBkg_Buf
, renderRLayer_InBBoxBuf
) where
import Control.Lens
import Control.Monad.State hiding (mapM,mapM_)
import Data.Foldable
import qualified Data.Map as M
import Graphics.Rendering.Cairo
-- from hoodle-platform
import Data.Hoodle.Generic
import Data.Hoodle.Simple
import Data.Hoodle.BBox
import Data.Hoodle.Predefined
-- from this package
import Graphics.Hoodle.Render
import Graphics.Hoodle.Render.Type
--
import Prelude hiding (curry,uncurry,mapM,mapM_,concatMap)
-----
-- Dummy (for testing)
-----
renderRBkg_Dummy :: (RBackground,Dimension) -> Render ()
renderRBkg_Dummy (_,Dim w h) = do
setSourceRGBA 1 1 1 1
rectangle 0 0 w h
fill
-----------
-- NoPDF --
-----------
-- | render background without pdf
renderRBkg_NoPDF :: (RBackground,Dimension) -> Render ()
renderRBkg_NoPDF r@(RBkgSmpl _ _ _,_) = renderRBkg r >> return ()
renderRBkg_NoPDF (RBkgPDF _ _ _ _ _,_) = return ()
renderRBkg_NoPDF (RBkgEmbedPDF _ _ _,_) = return ()
--------------
-- BBoxOnly --
--------------
-- | render only bounding box of a StrokeBBox
renderStrkBBx_BBoxOnly :: BBoxed Stroke -> Render ()
renderStrkBBx_BBoxOnly sbbox = do
let s = bbxed_content sbbox
case M.lookup (stroke_color s) predefined_pencolor of
Just (r,g,b,a) -> setSourceRGBA r g b a
Nothing -> setSourceRGBA 0 0 0 1
setSourceRGBA 0 0 0 1
setLineWidth (stroke_width s)
let BBox (x1,y1) (x2,y2) = getBBox sbbox
rectangle x1 y1 (x2-x1) (y2-y1)
stroke
-- |
renderImgBBx_BBoxOnly :: BBoxed Image -> Render ()
renderImgBBx_BBoxOnly ibbox = do
setSourceRGBA 0 0 0 1
setLineWidth 10
let BBox (x1,y1) (x2,y2) = getBBox ibbox
rectangle x1 y1 (x2-x1) (y2-y1)
stroke
renderSVGBBx_BBoxOnly :: BBoxed SVG -> Render ()
renderSVGBBx_BBoxOnly svg = do
setSourceRGBA 0 0 0 1
setLineWidth 10
let BBox (x1,y1) (x2,y2) = getBBox svg
rectangle x1 y1 (x2-x1) (y2-y1)
stroke
renderLnkBBx_BBoxOnly :: BBoxed Link -> Render ()
renderLnkBBx_BBoxOnly lnk = do
setSourceRGBA 0 0 0 1
setLineWidth 10
let BBox (x1,y1) (x2,y2) = getBBox lnk
rectangle x1 y1 (x2-x1) (y2-y1)
stroke
-- |
renderRItem_BBoxOnly :: RItem -> Render ()
renderRItem_BBoxOnly (RItemStroke sbbox) = renderStrkBBx_BBoxOnly sbbox
renderRItem_BBoxOnly (RItemImage ibbox _) = renderImgBBx_BBoxOnly ibbox
renderRItem_BBoxOnly (RItemSVG svg _) = renderSVGBBx_BBoxOnly svg
renderRItem_BBoxOnly (RItemLink lnk _) = renderLnkBBx_BBoxOnly lnk
-- |
renderRLayer_BBoxOnly :: RLayer -> Render ()
renderRLayer_BBoxOnly = mapM_ renderRItem_BBoxOnly . view gitems
-- | render only bounding box of a StrokeBBox
renderRPage_BBoxOnly :: RPage -> Render ()
renderRPage_BBoxOnly page = do
let dim = view gdimension page
bkg = view gbackground page
lyrs = view glayers page
renderRBkg_NoPDF (bkg,dim)
mapM_ renderRLayer_BBoxOnly lyrs
| wavewave/hoodle-render | src/Graphics/Hoodle/Render/Debug.hs | bsd-2-clause | 3,819 | 0 | 11 | 762 | 1,035 | 542 | 493 | 80 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import Network.AMQP
import qualified Data.ByteString.Lazy as BL
import Data.Binary.Put
import System.Random
import Control.Monad (replicateM)
import Control.Concurrent as Concurrent
randomList :: (Random a) => Int -> a -> a -> IO([a])
randomList n min max = replicateM n $ randomRIO (min, max)
data Thing = Thing {
x :: Float,
y :: Float,
xVel :: Float,
yVel :: Float,
xSize :: Float,
ySize :: Float,
r :: Int,
g :: Int,
b :: Int
}
createRandomThing :: [Float] -> [Float] -> [Float] -> [Int] -> Thing
createRandomThing pos vel sz col =
Thing (pos!!0) (pos!!1) (vel!!0) (vel!!1) (sz!!0) (sz!!1) (col!!0) (col!!1) (col!!2)
serialiseAThing :: Thing -> Put
serialiseAThing thing = do
putFloatbe $ x thing
putFloatbe $ y thing
putFloatbe $ xVel thing
putFloatbe $ yVel thing
putFloatbe $ xSize thing
putFloatbe $ ySize thing
putWord32be $ fromIntegral $ r thing
putWord32be $ fromIntegral $ g thing
putWord32be $ fromIntegral $ b thing
publishAThing :: Thing -> Channel -> IO (Maybe Int)
publishAThing thing channel = do
let serialisedThing = serialiseAThing thing
publishMsg channel "myExchange" "myKey"
newMsg {msgBody = (runPut $ serialisedThing),
msgDeliveryMode = Just Persistent}
createRandomThings :: [Float] -> [Float] -> [Float] -> [Int] -> [Thing]
createRandomThings (x:y:pos) (xVel:yVel:vel) (xSize:ySize:size) (r:g:b:colors) = [createRandomThing (x:y:[]) (xVel:yVel:[]) (xSize:ySize:[]) (r:g:b:[])] ++ createRandomThings pos vel size colors
createRandomThings _ _ _ _ = []
publishThingsWithDelay :: [Thing] -> Channel -> IO ()
publishThingsWithDelay (x:xs) channel = do
publishAThing x channel
Concurrent.threadDelay(1000000)
publishThingsWithDelay xs channel
publishThingsWithDelay [] channel = return ()
data World = World {
things :: [Thing]
}
serialiseThings :: [Thing] -> Put
serialiseThings (thing:things) = do
serialiseAThing thing
serialiseThings things
serialiseThings [] = return ()
serialiseWorld :: World -> Put
serialiseWorld world = do
putWord32be $ fromIntegral (length (things world))
serialiseThings (things world)
displayWorld :: World -> Channel -> IO (Maybe Int)
displayWorld world channel = do
Concurrent.threadDelay(1000*16)
publishMsg channel "myExchange" "myKey"
newMsg {msgBody = (runPut $ serialiseWorld world), msgDeliveryMode = Just Persistent}
flipThingColors :: Thing -> Thing
flipThingColors thing = Thing
((x thing) + (xVel thing)) ((y thing) + (yVel thing))
(xVel thing) (yVel thing)
(xSize thing) (ySize thing)
(r thing) (g thing) (b thing)
gameLoop :: World -> World
gameLoop world = World $ fmap flipThingColors (things world)
simulation initWorld chan =
loop initWorld chan
where loop w chan = displayWorld w chan >> loop (gameLoop w) chan
main = do
conn <- openConnection "127.0.0.1" "/" "guest" "guest"
chan <- openChannel conn
let numThings = 5000
randomPos <- randomList (2*numThings) ( -50 :: Float) ( 50 :: Float)
randomVel <- randomList (2*numThings) (-0.2 :: Float) ( 0.2 :: Float)
randomSize <- randomList (2*numThings) ( 1.0 :: Float) ( 10 :: Float)
randomColors <- randomList (3*numThings) (0 :: Int) (255 :: Int)
let randomThings = createRandomThings randomPos randomVel randomSize randomColors
-- declare a queue, exchange and binding
declareQueue chan newQueue {queueName = "hello_machine", queueDurable = False}
declareExchange chan newExchange {exchangeName = "myExchange", exchangeType = "direct"}
bindQueue chan "hello_machine" "myExchange" "myKey"
-- publishThingsWithDelay randomThings chan
let world = World randomThings
let numThingsInWorld = length (things world)
putStrLn (show numThingsInWorld)
-- displayWorld world chan
simulation world chan
getLine -- wait for keypress
closeConnection conn
putStrLn "connection closed" | PlausibleReality/the-subtle-machine | app/Main.hs | bsd-3-clause | 3,966 | 0 | 12 | 767 | 1,498 | 768 | 730 | 94 | 1 |
-- Copyright (c) 2011, Colin Hill
--
-- Loosely based on implementation of libnoise by Jason Bevins Copyright (C) 2003, 2004
-- http://libnoise.sourceforge.net
-- | Contains 'Noise' class as well as a general coherent noise generating function which
-- the specific noise implementations are based on.
module Numeric.Noise (
Point,
Seed,
Noise(noiseValue),
pmap,
clamp,
coherentNoise
) where
import Data.Bits
import Data.Vector.Unboxed (Vector, fromList, (!))
-- | A point in 3-space.
type Point = (Double, Double, Double)
-- | A seed for a random function.
type Seed = Int
-- | Class of noise functions.
class Noise a where
-- | Maps 3-space points to a noise value between -1 and 1 for the given noise function.
noiseValue :: a -> Point -> Double
-- | Map a function on a 'Point'.
pmap :: (Double -> Double) -> Point -> Point
pmap f (x, y, z) = (f x, f y, f z)
-- | Returns a clamped value between a min and max value.
clamp :: Ord a => a -> a -> a -> a
clamp v m m' = max m (min m' v)
-- | Returns a coherent noise value between -1 and 1 given a seed and a point in 3-space.
coherentNoise :: Seed -> Point -> Double
coherentNoise seed (x, y, z) = clamp noise (-1) 1
where (ox, oy, oz) = (clampToIntRange x, clampToIntRange y, clampToIntRange z)
x0 = if ox > 0.0 then floor ox else floor ox - 1
x1 = x0 + 1
y0 = if oy > 0.0 then floor oy else floor oy - 1
y1 = y0 + 1
z0 = if oz > 0.0 then floor oz else floor oz - 1
z1 = z0 + 1
sx = scurve (ox - fromIntegral x0)
sy = scurve (oy - fromIntegral y0)
sz = scurve (oz - fromIntegral z0)
n0 = gradientNoise seed ox oy oz x0 y0 z0
n1 = gradientNoise seed ox oy oz x1 y0 z0
n2 = gradientNoise seed ox oy oz x0 y1 z0
n3 = gradientNoise seed ox oy oz x1 y1 z0
n4 = gradientNoise seed ox oy oz x0 y0 z1
n5 = gradientNoise seed ox oy oz x1 y0 z1
n6 = gradientNoise seed ox oy oz x0 y1 z1
n7 = gradientNoise seed ox oy oz x1 y1 z1
ix0 = lerp sx n0 n1
ix1 = lerp sx n2 n3
ix2 = lerp sx n4 n5
ix3 = lerp sx n6 n7
iy0 = lerp sy ix0 ix1
iy1 = lerp sy ix2 ix3
noise = lerp sz iy0 iy1
-- | Returns a gradient noise value given a seed, a point in 3-space, and a nearby integer
-- point in 3-space.
gradientNoise :: Seed -> Double -> Double -> Double -> Int -> Int -> Int -> Double
gradientNoise seed fx fy fz ix iy iz = 2.12 * (gx * ox + gy * oy + gz * oz)
where (gx, gy, gz) = (vectorTable ! shiftL i 2,
vectorTable ! (shiftL i 2 + 1),
vectorTable ! (shiftL i 2 + 2))
(ox, oy, oz) = (fx - fromIntegral ix,
fy - fromIntegral iy,
fz - fromIntegral iz)
i = (i' `xor` shiftR i' 8) .&. 0xff
i' = (1619 * ix + 31337 * iy + 6971 * iz + 1013 * seed) .&. 0xffffffff
-- | Returns the linearly interpolated value between two values given a delta.
lerp :: Double -> Double -> Double -> Double
lerp t a b = (1.0 - t) * a + t * b
-- | Maps a value onto a quintic s-curve.
scurve :: Double -> Double
scurve a = (6.0 * a5) - (15.0 * a4) + (10.0 * a3)
where a3 = a * a * a
a4 = a3 * a
a5 = a4 * a
-- | Clamps a 'Double' to the range of an 'Int'.
clampToIntRange :: Double -> Double
clampToIntRange n | n >= maxInt = 2.0 * fmod n maxInt - maxInt
| n <= (-maxInt) = 2.0 * fmod n maxInt + maxInt
| otherwise = n
where maxInt = 1073741824.0 -- Max 32 bit signed Int. Should not be hardcoded.
-- | Floating point modulus function.
fmod :: Double -> Double -> Double
fmod x y = x - fromIntegral (floor (x / y) :: Int) * y
-- | Table of random normalized vectors.
vectorTable :: Vector Double
vectorTable = fromList [
-0.763874, -0.596439, -0.246489, 0.0,
0.396055, 0.904518, -0.158073, 0.0,
-0.499004, -0.8665, -0.0131631, 0.0,
0.468724, -0.824756, 0.316346, 0.0,
0.829598, 0.43195, 0.353816, 0.0,
-0.454473, 0.629497, -0.630228, 0.0,
-0.162349, -0.869962, -0.465628, 0.0,
0.932805, 0.253451, 0.256198, 0.0,
-0.345419, 0.927299, -0.144227, 0.0,
-0.715026, -0.293698, -0.634413, 0.0,
-0.245997, 0.717467, -0.651711, 0.0,
-0.967409, -0.250435, -0.037451, 0.0,
0.901729, 0.397108, -0.170852, 0.0,
0.892657, -0.0720622, -0.444938, 0.0,
0.0260084, -0.0361701, 0.999007, 0.0,
0.949107, -0.19486, 0.247439, 0.0,
0.471803, -0.807064, -0.355036, 0.0,
0.879737, 0.141845, 0.453809, 0.0,
0.570747, 0.696415, 0.435033, 0.0,
-0.141751, -0.988233, -0.0574584, 0.0,
-0.58219, -0.0303005, 0.812488, 0.0,
-0.60922, 0.239482, -0.755975, 0.0,
0.299394, -0.197066, -0.933557, 0.0,
-0.851615, -0.220702, -0.47544, 0.0,
0.848886, 0.341829, -0.403169, 0.0,
-0.156129, -0.687241, 0.709453, 0.0,
-0.665651, 0.626724, 0.405124, 0.0,
0.595914, -0.674582, 0.43569, 0.0,
0.171025, -0.509292, 0.843428, 0.0,
0.78605, 0.536414, -0.307222, 0.0,
0.18905, -0.791613, 0.581042, 0.0,
-0.294916, 0.844994, 0.446105, 0.0,
0.342031, -0.58736, -0.7335, 0.0,
0.57155, 0.7869, 0.232635, 0.0,
0.885026, -0.408223, 0.223791, 0.0,
-0.789518, 0.571645, 0.223347, 0.0,
0.774571, 0.31566, 0.548087, 0.0,
-0.79695, -0.0433603, -0.602487, 0.0,
-0.142425, -0.473249, -0.869339, 0.0,
-0.0698838, 0.170442, 0.982886, 0.0,
0.687815, -0.484748, 0.540306, 0.0,
0.543703, -0.534446, -0.647112, 0.0,
0.97186, 0.184391, -0.146588, 0.0,
0.707084, 0.485713, -0.513921, 0.0,
0.942302, 0.331945, 0.043348, 0.0,
0.499084, 0.599922, 0.625307, 0.0,
-0.289203, 0.211107, 0.9337, 0.0,
0.412433, -0.71667, -0.56239, 0.0,
0.87721, -0.082816, 0.47291, 0.0,
-0.420685, -0.214278, 0.881538, 0.0,
0.752558, -0.0391579, 0.657361, 0.0,
0.0765725, -0.996789, 0.0234082, 0.0,
-0.544312, -0.309435, -0.779727, 0.0,
-0.455358, -0.415572, 0.787368, 0.0,
-0.874586, 0.483746, 0.0330131, 0.0,
0.245172, -0.0838623, 0.965846, 0.0,
0.382293, -0.432813, 0.81641, 0.0,
-0.287735, -0.905514, 0.311853, 0.0,
-0.667704, 0.704955, -0.239186, 0.0,
0.717885, -0.464002, -0.518983, 0.0,
0.976342, -0.214895, 0.0240053, 0.0,
-0.0733096, -0.921136, 0.382276, 0.0,
-0.986284, 0.151224, -0.0661379, 0.0,
-0.899319, -0.429671, 0.0812908, 0.0,
0.652102, -0.724625, 0.222893, 0.0,
0.203761, 0.458023, -0.865272, 0.0,
-0.030396, 0.698724, -0.714745, 0.0,
-0.460232, 0.839138, 0.289887, 0.0,
-0.0898602, 0.837894, 0.538386, 0.0,
-0.731595, 0.0793784, 0.677102, 0.0,
-0.447236, -0.788397, 0.422386, 0.0,
0.186481, 0.645855, -0.740335, 0.0,
-0.259006, 0.935463, 0.240467, 0.0,
0.445839, 0.819655, -0.359712, 0.0,
0.349962, 0.755022, -0.554499, 0.0,
-0.997078, -0.0359577, 0.0673977, 0.0,
-0.431163, -0.147516, -0.890133, 0.0,
0.299648, -0.63914, 0.708316, 0.0,
0.397043, 0.566526, -0.722084, 0.0,
-0.502489, 0.438308, -0.745246, 0.0,
0.0687235, 0.354097, 0.93268, 0.0,
-0.0476651, -0.462597, 0.885286, 0.0,
-0.221934, 0.900739, -0.373383, 0.0,
-0.956107, -0.225676, 0.186893, 0.0,
-0.187627, 0.391487, -0.900852, 0.0,
-0.224209, -0.315405, 0.92209, 0.0,
-0.730807, -0.537068, 0.421283, 0.0,
-0.0353135, -0.816748, 0.575913, 0.0,
-0.941391, 0.176991, -0.287153, 0.0,
-0.154174, 0.390458, 0.90762, 0.0,
-0.283847, 0.533842, 0.796519, 0.0,
-0.482737, -0.850448, 0.209052, 0.0,
-0.649175, 0.477748, 0.591886, 0.0,
0.885373, -0.405387, -0.227543, 0.0,
-0.147261, 0.181623, -0.972279, 0.0,
0.0959236, -0.115847, -0.988624, 0.0,
-0.89724, -0.191348, 0.397928, 0.0,
0.903553, -0.428461, -0.00350461, 0.0,
0.849072, -0.295807, -0.437693, 0.0,
0.65551, 0.741754, -0.141804, 0.0,
0.61598, -0.178669, 0.767232, 0.0,
0.0112967, 0.932256, -0.361623, 0.0,
-0.793031, 0.258012, 0.551845, 0.0,
0.421933, 0.454311, 0.784585, 0.0,
-0.319993, 0.0401618, -0.946568, 0.0,
-0.81571, 0.551307, -0.175151, 0.0,
-0.377644, 0.00322313, 0.925945, 0.0,
0.129759, -0.666581, -0.734052, 0.0,
0.601901, -0.654237, -0.457919, 0.0,
-0.927463, -0.0343576, -0.372334, 0.0,
-0.438663, -0.868301, -0.231578, 0.0,
-0.648845, -0.749138, -0.133387, 0.0,
0.507393, -0.588294, 0.629653, 0.0,
0.726958, 0.623665, 0.287358, 0.0,
0.411159, 0.367614, -0.834151, 0.0,
0.806333, 0.585117, -0.0864016, 0.0,
0.263935, -0.880876, 0.392932, 0.0,
0.421546, -0.201336, 0.884174, 0.0,
-0.683198, -0.569557, -0.456996, 0.0,
-0.117116, -0.0406654, -0.992285, 0.0,
-0.643679, -0.109196, -0.757465, 0.0,
-0.561559, -0.62989, 0.536554, 0.0,
0.0628422, 0.104677, -0.992519, 0.0,
0.480759, -0.2867, -0.828658, 0.0,
-0.228559, -0.228965, -0.946222, 0.0,
-0.10194, -0.65706, -0.746914, 0.0,
0.0689193, -0.678236, 0.731605, 0.0,
0.401019, -0.754026, 0.52022, 0.0,
-0.742141, 0.547083, -0.387203, 0.0,
-0.00210603, -0.796417, -0.604745, 0.0,
0.296725, -0.409909, -0.862513, 0.0,
-0.260932, -0.798201, 0.542945, 0.0,
-0.641628, 0.742379, 0.192838, 0.0,
-0.186009, -0.101514, 0.97729, 0.0,
0.106711, -0.962067, 0.251079, 0.0,
-0.743499, 0.30988, -0.592607, 0.0,
-0.795853, -0.605066, -0.0226607, 0.0,
-0.828661, -0.419471, -0.370628, 0.0,
0.0847218, -0.489815, -0.8677, 0.0,
-0.381405, 0.788019, -0.483276, 0.0,
0.282042, -0.953394, 0.107205, 0.0,
0.530774, 0.847413, 0.0130696, 0.0,
0.0515397, 0.922524, 0.382484, 0.0,
-0.631467, -0.709046, 0.313852, 0.0,
0.688248, 0.517273, 0.508668, 0.0,
0.646689, -0.333782, -0.685845, 0.0,
-0.932528, -0.247532, -0.262906, 0.0,
0.630609, 0.68757, -0.359973, 0.0,
0.577805, -0.394189, 0.714673, 0.0,
-0.887833, -0.437301, -0.14325, 0.0,
0.690982, 0.174003, 0.701617, 0.0,
-0.866701, 0.0118182, 0.498689, 0.0,
-0.482876, 0.727143, 0.487949, 0.0,
-0.577567, 0.682593, -0.447752, 0.0,
0.373768, 0.0982991, 0.922299, 0.0,
0.170744, 0.964243, -0.202687, 0.0,
0.993654, -0.035791, -0.106632, 0.0,
0.587065, 0.4143, -0.695493, 0.0,
-0.396509, 0.26509, -0.878924, 0.0,
-0.0866853, 0.83553, -0.542563, 0.0,
0.923193, 0.133398, -0.360443, 0.0,
0.00379108, -0.258618, 0.965972, 0.0,
0.239144, 0.245154, -0.939526, 0.0,
0.758731, -0.555871, 0.33961, 0.0,
0.295355, 0.309513, 0.903862, 0.0,
0.0531222, -0.91003, -0.411124, 0.0,
0.270452, 0.0229439, -0.96246, 0.0,
0.563634, 0.0324352, 0.825387, 0.0,
0.156326, 0.147392, 0.976646, 0.0,
-0.0410141, 0.981824, 0.185309, 0.0,
-0.385562, -0.576343, -0.720535, 0.0,
0.388281, 0.904441, 0.176702, 0.0,
0.945561, -0.192859, -0.262146, 0.0,
0.844504, 0.520193, 0.127325, 0.0,
0.0330893, 0.999121, -0.0257505, 0.0,
-0.592616, -0.482475, -0.644999, 0.0,
0.539471, 0.631024, -0.557476, 0.0,
0.655851, -0.027319, -0.754396, 0.0,
0.274465, 0.887659, 0.369772, 0.0,
-0.123419, 0.975177, -0.183842, 0.0,
-0.223429, 0.708045, 0.66989, 0.0,
-0.908654, 0.196302, 0.368528, 0.0,
-0.95759, -0.00863708, 0.288005, 0.0,
0.960535, 0.030592, 0.276472, 0.0,
-0.413146, 0.907537, 0.0754161, 0.0,
-0.847992, 0.350849, -0.397259, 0.0,
0.614736, 0.395841, 0.68221, 0.0,
-0.503504, -0.666128, -0.550234, 0.0,
-0.268833, -0.738524, -0.618314, 0.0,
0.792737, -0.60001, -0.107502, 0.0,
-0.637582, 0.508144, -0.579032, 0.0,
0.750105, 0.282165, -0.598101, 0.0,
-0.351199, -0.392294, -0.850155, 0.0,
0.250126, -0.960993, -0.118025, 0.0,
-0.732341, 0.680909, -0.0063274, 0.0,
-0.760674, -0.141009, 0.633634, 0.0,
0.222823, -0.304012, 0.926243, 0.0,
0.209178, 0.505671, 0.836984, 0.0,
0.757914, -0.56629, -0.323857, 0.0,
-0.782926, -0.339196, 0.52151, 0.0,
-0.462952, 0.585565, 0.665424, 0.0,
0.61879, 0.194119, -0.761194, 0.0,
0.741388, -0.276743, 0.611357, 0.0,
0.707571, 0.702621, 0.0752872, 0.0,
0.156562, 0.819977, 0.550569, 0.0,
-0.793606, 0.440216, 0.42, 0.0,
0.234547, 0.885309, -0.401517, 0.0,
0.132598, 0.80115, -0.58359, 0.0,
-0.377899, -0.639179, 0.669808, 0.0,
-0.865993, -0.396465, 0.304748, 0.0,
-0.624815, -0.44283, 0.643046, 0.0,
-0.485705, 0.825614, -0.287146, 0.0,
-0.971788, 0.175535, 0.157529, 0.0,
-0.456027, 0.392629, 0.798675, 0.0,
-0.0104443, 0.521623, -0.853112, 0.0,
-0.660575, -0.74519, 0.091282, 0.0,
-0.0157698, -0.307475, -0.951425, 0.0,
-0.603467, -0.250192, 0.757121, 0.0,
0.506876, 0.25006, 0.824952, 0.0,
0.255404, 0.966794, 0.00884498, 0.0,
0.466764, -0.874228, -0.133625, 0.0,
0.475077, -0.0682351, -0.877295, 0.0,
-0.224967, -0.938972, -0.260233, 0.0,
-0.377929, -0.814757, -0.439705, 0.0,
-0.305847, 0.542333, -0.782517, 0.0,
0.26658, -0.902905, -0.337191, 0.0,
0.0275773, 0.322158, -0.946284, 0.0,
0.0185422, 0.716349, 0.697496, 0.0,
-0.20483, 0.978416, 0.0273371, 0.0,
-0.898276, 0.373969, 0.230752, 0.0,
-0.00909378, 0.546594, 0.837349, 0.0,
0.6602, -0.751089, 0.000959236, 0.0,
0.855301, -0.303056, 0.420259, 0.0,
0.797138, 0.0623013, -0.600574, 0.0,
0.48947, -0.866813, 0.0951509, 0.0,
0.251142, 0.674531, 0.694216, 0.0,
-0.578422, -0.737373, -0.348867, 0.0,
-0.254689, -0.514807, 0.818601, 0.0,
0.374972, 0.761612, 0.528529, 0.0,
0.640303, -0.734271, -0.225517, 0.0,
-0.638076, 0.285527, 0.715075, 0.0,
0.772956, -0.15984, -0.613995, 0.0,
0.798217, -0.590628, 0.118356, 0.0,
-0.986276, -0.0578337, -0.154644, 0.0,
-0.312988, -0.94549, 0.0899272, 0.0,
-0.497338, 0.178325, 0.849032, 0.0,
-0.101136, -0.981014, 0.165477, 0.0,
-0.521688, 0.0553434, -0.851339, 0.0,
-0.786182, -0.583814, 0.202678, 0.0,
-0.565191, 0.821858, -0.0714658, 0.0,
0.437895, 0.152598, -0.885981, 0.0,
-0.92394, 0.353436, -0.14635, 0.0,
0.212189, -0.815162, -0.538969, 0.0,
-0.859262, 0.143405, -0.491024, 0.0,
0.991353, 0.112814, 0.0670273, 0.0,
0.0337884, -0.979891, -0.196654, 0.0]
| colinhect/hsnoise | src/Numeric/Noise.hs | bsd-3-clause | 14,558 | 0 | 15 | 3,554 | 5,086 | 3,098 | 1,988 | 328 | 4 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
The Desugarer: turning HsSyn into Core.
-}
{-# LANGUAGE CPP #-}
module Desugar (
-- * Desugaring operations
deSugar, deSugarExpr,
-- * Dependency/fingerprinting code (used by MkIface)
mkUsageInfo, mkUsedNames, mkDependencies
) where
#include "HsVersions.h"
import DynFlags
import HscTypes
import HsSyn
import TcRnTypes
import TcRnMonad ( finalSafeMode, fixSafeInstances )
import Id
import Name
import Type
import FamInstEnv
import InstEnv
import Class
import Avail
import CoreSyn
import CoreFVs( exprsSomeFreeVarsList )
import CoreSubst
import PprCore
import DsMonad
import DsExpr
import DsBinds
import DsForeign
import PrelNames ( coercibleTyConKey )
import TysPrim ( eqReprPrimTyCon )
import Unique ( hasKey )
import Coercion ( mkCoVarCo )
import TysWiredIn ( coercibleDataCon )
import DataCon ( dataConWrapId )
import MkCore ( mkCoreLet )
import Module
import NameSet
import NameEnv
import Rules
import BasicTypes ( Activation(.. ), competesWith, pprRuleName )
import CoreMonad ( CoreToDo(..) )
import CoreLint ( endPassIO )
import VarSet
import FastString
import ErrUtils
import Outputable
import SrcLoc
import Coverage
import Util
import MonadUtils
import OrdList
import UniqFM
import ListSetOps
import Fingerprint
import Maybes
import Data.Function
import Data.List
import Data.IORef
import Control.Monad( when )
import Data.Map (Map)
import qualified Data.Map as Map
-- | Extract information from the rename and typecheck phases to produce
-- a dependencies information for the module being compiled.
mkDependencies :: TcGblEnv -> IO Dependencies
mkDependencies
TcGblEnv{ tcg_mod = mod,
tcg_imports = imports,
tcg_th_used = th_var
}
= do
-- Template Haskell used?
th_used <- readIORef th_var
let dep_mods = eltsUFM (delFromUFM (imp_dep_mods imports) (moduleName mod))
-- M.hi-boot can be in the imp_dep_mods, but we must remove
-- it before recording the modules on which this one depends!
-- (We want to retain M.hi-boot in imp_dep_mods so that
-- loadHiBootInterface can see if M's direct imports depend
-- on M.hi-boot, and hence that we should do the hi-boot consistency
-- check.)
pkgs | th_used = insertList thUnitId (imp_dep_pkgs imports)
| otherwise = imp_dep_pkgs imports
-- Set the packages required to be Safe according to Safe Haskell.
-- See Note [RnNames . Tracking Trust Transitively]
sorted_pkgs = sortBy stableUnitIdCmp pkgs
trust_pkgs = imp_trust_pkgs imports
dep_pkgs' = map (\x -> (x, x `elem` trust_pkgs)) sorted_pkgs
return Deps { dep_mods = sortBy (stableModuleNameCmp `on` fst) dep_mods,
dep_pkgs = dep_pkgs',
dep_orphs = sortBy stableModuleCmp (imp_orphs imports),
dep_finsts = sortBy stableModuleCmp (imp_finsts imports) }
-- sort to get into canonical order
-- NB. remember to use lexicographic ordering
mkUsedNames :: TcGblEnv -> NameSet
mkUsedNames TcGblEnv{ tcg_dus = dus } = allUses dus
mkUsageInfo :: HscEnv -> Module -> ImportedMods -> NameSet -> [FilePath] -> IO [Usage]
mkUsageInfo hsc_env this_mod dir_imp_mods used_names dependent_files
= do
eps <- hscEPS hsc_env
hashes <- mapM getFileHash dependent_files
let mod_usages = mk_mod_usage_info (eps_PIT eps) hsc_env this_mod
dir_imp_mods used_names
let usages = mod_usages ++ [ UsageFile { usg_file_path = f
, usg_file_hash = hash }
| (f, hash) <- zip dependent_files hashes ]
usages `seqList` return usages
-- seq the list of Usages returned: occasionally these
-- don't get evaluated for a while and we can end up hanging on to
-- the entire collection of Ifaces.
mk_mod_usage_info :: PackageIfaceTable
-> HscEnv
-> Module
-> ImportedMods
-> NameSet
-> [Usage]
mk_mod_usage_info pit hsc_env this_mod direct_imports used_names
= mapMaybe mkUsage usage_mods
where
hpt = hsc_HPT hsc_env
dflags = hsc_dflags hsc_env
this_pkg = thisPackage dflags
used_mods = moduleEnvKeys ent_map
dir_imp_mods = moduleEnvKeys direct_imports
all_mods = used_mods ++ filter (`notElem` used_mods) dir_imp_mods
usage_mods = sortBy stableModuleCmp all_mods
-- canonical order is imported, to avoid interface-file
-- wobblage.
-- ent_map groups together all the things imported and used
-- from a particular module
ent_map :: ModuleEnv [OccName]
ent_map = nonDetFoldUFM add_mv emptyModuleEnv used_names
-- nonDetFoldUFM is OK here. If you follow the logic, we sort by OccName
-- in ent_hashs
where
add_mv name mv_map
| isWiredInName name = mv_map -- ignore wired-in names
| otherwise
= case nameModule_maybe name of
Nothing -> ASSERT2( isSystemName name, ppr name ) mv_map
-- See Note [Internal used_names]
Just mod -> -- This lambda function is really just a
-- specialised (++); originally came about to
-- avoid quadratic behaviour (trac #2680)
extendModuleEnvWith (\_ xs -> occ:xs) mv_map mod [occ]
where occ = nameOccName name
-- We want to create a Usage for a home module if
-- a) we used something from it; has something in used_names
-- b) we imported it, even if we used nothing from it
-- (need to recompile if its export list changes: export_fprint)
mkUsage :: Module -> Maybe Usage
mkUsage mod
| isNothing maybe_iface -- We can't depend on it if we didn't
-- load its interface.
|| mod == this_mod -- We don't care about usages of
-- things in *this* module
= Nothing
| moduleUnitId mod /= this_pkg
= Just UsagePackageModule{ usg_mod = mod,
usg_mod_hash = mod_hash,
usg_safe = imp_safe }
-- for package modules, we record the module hash only
| (null used_occs
&& isNothing export_hash
&& not is_direct_import
&& not finsts_mod)
= Nothing -- Record no usage info
-- for directly-imported modules, we always want to record a usage
-- on the orphan hash. This is what triggers a recompilation if
-- an orphan is added or removed somewhere below us in the future.
| otherwise
= Just UsageHomeModule {
usg_mod_name = moduleName mod,
usg_mod_hash = mod_hash,
usg_exports = export_hash,
usg_entities = Map.toList ent_hashs,
usg_safe = imp_safe }
where
maybe_iface = lookupIfaceByModule dflags hpt pit mod
-- In one-shot mode, the interfaces for home-package
-- modules accumulate in the PIT not HPT. Sigh.
Just iface = maybe_iface
finsts_mod = mi_finsts iface
hash_env = mi_hash_fn iface
mod_hash = mi_mod_hash iface
export_hash | depend_on_exports = Just (mi_exp_hash iface)
| otherwise = Nothing
(is_direct_import, imp_safe)
= case lookupModuleEnv direct_imports mod of
Just (imv : _xs) -> (True, imv_is_safe imv)
Just _ -> pprPanic "mkUsage: empty direct import" Outputable.empty
Nothing -> (False, safeImplicitImpsReq dflags)
-- Nothing case is for implicit imports like 'System.IO' when 'putStrLn'
-- is used in the source code. We require them to be safe in Safe Haskell
used_occs = lookupModuleEnv ent_map mod `orElse` []
-- Making a Map here ensures that (a) we remove duplicates
-- when we have usages on several subordinates of a single parent,
-- and (b) that the usages emerge in a canonical order, which
-- is why we use Map rather than OccEnv: Map works
-- using Ord on the OccNames, which is a lexicographic ordering.
ent_hashs :: Map OccName Fingerprint
ent_hashs = Map.fromList (map lookup_occ used_occs)
lookup_occ occ =
case hash_env occ of
Nothing -> pprPanic "mkUsage" (ppr mod <+> ppr occ <+> ppr used_names)
Just r -> r
depend_on_exports = is_direct_import
{- True
Even if we used 'import M ()', we have to register a
usage on the export list because we are sensitive to
changes in orphan instances/rules.
False
In GHC 6.8.x we always returned true, and in
fact it recorded a dependency on *all* the
modules underneath in the dependency tree. This
happens to make orphans work right, but is too
expensive: it'll read too many interface files.
The 'isNothing maybe_iface' check above saved us
from generating many of these usages (at least in
one-shot mode), but that's even more bogus!
-}
{-
************************************************************************
* *
* The main function: deSugar
* *
************************************************************************
-}
-- | Main entry point to the desugarer.
deSugar :: HscEnv -> ModLocation -> TcGblEnv -> IO (Messages, Maybe ModGuts)
-- Can modify PCS by faulting in more declarations
deSugar hsc_env
mod_loc
tcg_env@(TcGblEnv { tcg_mod = mod,
tcg_src = hsc_src,
tcg_type_env = type_env,
tcg_imports = imports,
tcg_exports = exports,
tcg_keep = keep_var,
tcg_th_splice_used = tc_splice_used,
tcg_rdr_env = rdr_env,
tcg_fix_env = fix_env,
tcg_inst_env = inst_env,
tcg_fam_inst_env = fam_inst_env,
tcg_warns = warns,
tcg_anns = anns,
tcg_binds = binds,
tcg_imp_specs = imp_specs,
tcg_dependent_files = dependent_files,
tcg_ev_binds = ev_binds,
tcg_fords = fords,
tcg_rules = rules,
tcg_vects = vects,
tcg_patsyns = patsyns,
tcg_tcs = tcs,
tcg_insts = insts,
tcg_fam_insts = fam_insts,
tcg_hpc = other_hpc_info})
= do { let dflags = hsc_dflags hsc_env
print_unqual = mkPrintUnqualified dflags rdr_env
; withTiming (pure dflags)
(text "Desugar"<+>brackets (ppr mod))
(const ()) $
do { -- Desugar the program
; let export_set =
-- Used to be 'availsToNameSet', but we now export selectors
-- only when necessary. See #12125.
availsToNameSetWithSelectors exports
target = hscTarget dflags
hpcInfo = emptyHpcInfo other_hpc_info
; (binds_cvr, ds_hpc_info, modBreaks)
<- if not (isHsBootOrSig hsc_src)
then addTicksToBinds hsc_env mod mod_loc
export_set (typeEnvTyCons type_env) binds
else return (binds, hpcInfo, Nothing)
; (msgs, mb_res) <- initDs hsc_env mod rdr_env type_env fam_inst_env $
do { ds_ev_binds <- dsEvBinds ev_binds
; core_prs <- dsTopLHsBinds binds_cvr
; (spec_prs, spec_rules) <- dsImpSpecs imp_specs
; (ds_fords, foreign_prs) <- dsForeigns fords
; ds_rules <- mapMaybeM dsRule rules
; ds_vects <- mapM dsVect vects
; let hpc_init
| gopt Opt_Hpc dflags = hpcInitCode mod ds_hpc_info
| otherwise = empty
; return ( ds_ev_binds
, foreign_prs `appOL` core_prs `appOL` spec_prs
, spec_rules ++ ds_rules, ds_vects
, ds_fords `appendStubC` hpc_init) }
; case mb_res of {
Nothing -> return (msgs, Nothing) ;
Just (ds_ev_binds, all_prs, all_rules, vects0, ds_fords) ->
do { -- Add export flags to bindings
keep_alive <- readIORef keep_var
; let (rules_for_locals, rules_for_imps) = partition isLocalRule all_rules
final_prs = addExportFlagsAndRules target export_set keep_alive
rules_for_locals (fromOL all_prs)
final_pgm = combineEvBinds ds_ev_binds final_prs
-- Notice that we put the whole lot in a big Rec, even the foreign binds
-- When compiling PrelFloat, which defines data Float = F# Float#
-- we want F# to be in scope in the foreign marshalling code!
-- You might think it doesn't matter, but the simplifier brings all top-level
-- things into the in-scope set before simplifying; so we get no unfolding for F#!
#ifdef DEBUG
-- Debug only as pre-simple-optimisation program may be really big
; endPassIO hsc_env print_unqual CoreDesugar final_pgm rules_for_imps
#endif
; (ds_binds, ds_rules_for_imps, ds_vects)
<- simpleOptPgm dflags mod final_pgm rules_for_imps vects0
-- The simpleOptPgm gets rid of type
-- bindings plus any stupid dead code
; endPassIO hsc_env print_unqual CoreDesugarOpt ds_binds ds_rules_for_imps
; let used_names = mkUsedNames tcg_env
; deps <- mkDependencies tcg_env
; used_th <- readIORef tc_splice_used
; dep_files <- readIORef dependent_files
; safe_mode <- finalSafeMode dflags tcg_env
; usages <- mkUsageInfo hsc_env mod (imp_mods imports) used_names dep_files
; let mod_guts = ModGuts {
mg_module = mod,
mg_hsc_src = hsc_src,
mg_loc = mkFileSrcSpan mod_loc,
mg_exports = exports,
mg_usages = usages,
mg_deps = deps,
mg_used_th = used_th,
mg_rdr_env = rdr_env,
mg_fix_env = fix_env,
mg_warns = warns,
mg_anns = anns,
mg_tcs = tcs,
mg_insts = fixSafeInstances safe_mode insts,
mg_fam_insts = fam_insts,
mg_inst_env = inst_env,
mg_fam_inst_env = fam_inst_env,
mg_patsyns = patsyns,
mg_rules = ds_rules_for_imps,
mg_binds = ds_binds,
mg_foreign = ds_fords,
mg_hpc_info = ds_hpc_info,
mg_modBreaks = modBreaks,
mg_vect_decls = ds_vects,
mg_vect_info = noVectInfo,
mg_safe_haskell = safe_mode,
mg_trust_pkg = imp_trust_own_pkg imports
}
; return (msgs, Just mod_guts)
}}}}
mkFileSrcSpan :: ModLocation -> SrcSpan
mkFileSrcSpan mod_loc
= case ml_hs_file mod_loc of
Just file_path -> mkGeneralSrcSpan (mkFastString file_path)
Nothing -> interactiveSrcSpan -- Presumably
dsImpSpecs :: [LTcSpecPrag] -> DsM (OrdList (Id,CoreExpr), [CoreRule])
dsImpSpecs imp_specs
= do { spec_prs <- mapMaybeM (dsSpec Nothing) imp_specs
; let (spec_binds, spec_rules) = unzip spec_prs
; return (concatOL spec_binds, spec_rules) }
combineEvBinds :: [CoreBind] -> [(Id,CoreExpr)] -> [CoreBind]
-- Top-level bindings can include coercion bindings, but not via superclasses
-- See Note [Top-level evidence]
combineEvBinds [] val_prs
= [Rec val_prs]
combineEvBinds (NonRec b r : bs) val_prs
| isId b = combineEvBinds bs ((b,r):val_prs)
| otherwise = NonRec b r : combineEvBinds bs val_prs
combineEvBinds (Rec prs : bs) val_prs
= combineEvBinds bs (prs ++ val_prs)
{-
Note [Top-level evidence]
~~~~~~~~~~~~~~~~~~~~~~~~~
Top-level evidence bindings may be mutually recursive with the top-level value
bindings, so we must put those in a Rec. But we can't put them *all* in a Rec
because the occurrence analyser doesn't teke account of type/coercion variables
when computing dependencies.
So we pull out the type/coercion variables (which are in dependency order),
and Rec the rest.
-}
deSugarExpr :: HscEnv -> LHsExpr Id -> IO (Messages, Maybe CoreExpr)
deSugarExpr hsc_env tc_expr
= do { let dflags = hsc_dflags hsc_env
icntxt = hsc_IC hsc_env
rdr_env = ic_rn_gbl_env icntxt
type_env = mkTypeEnvWithImplicits (ic_tythings icntxt)
fam_insts = snd (ic_instances icntxt)
fam_inst_env = extendFamInstEnvList emptyFamInstEnv fam_insts
-- This stuff is a half baked version of TcRnDriver.setInteractiveContext
; showPass dflags "Desugar"
-- Do desugaring
; (msgs, mb_core_expr) <- initDs hsc_env (icInteractiveModule icntxt) rdr_env
type_env fam_inst_env $
dsLExpr tc_expr
; case mb_core_expr of
Nothing -> return ()
Just expr -> dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr expr)
; return (msgs, mb_core_expr) }
{-
************************************************************************
* *
* Add rules and export flags to binders
* *
************************************************************************
-}
addExportFlagsAndRules
:: HscTarget -> NameSet -> NameSet -> [CoreRule]
-> [(Id, t)] -> [(Id, t)]
addExportFlagsAndRules target exports keep_alive rules prs
= mapFst add_one prs
where
add_one bndr = add_rules name (add_export name bndr)
where
name = idName bndr
---------- Rules --------
-- See Note [Attach rules to local ids]
-- NB: the binder might have some existing rules,
-- arising from specialisation pragmas
add_rules name bndr
| Just rules <- lookupNameEnv rule_base name
= bndr `addIdSpecialisations` rules
| otherwise
= bndr
rule_base = extendRuleBaseList emptyRuleBase rules
---------- Export flag --------
-- See Note [Adding export flags]
add_export name bndr
| dont_discard name = setIdExported bndr
| otherwise = bndr
dont_discard :: Name -> Bool
dont_discard name = is_exported name
|| name `elemNameSet` keep_alive
-- In interactive mode, we don't want to discard any top-level
-- entities at all (eg. do not inline them away during
-- simplification), and retain them all in the TypeEnv so they are
-- available from the command line.
--
-- isExternalName separates the user-defined top-level names from those
-- introduced by the type checker.
is_exported :: Name -> Bool
is_exported | targetRetainsAllBindings target = isExternalName
| otherwise = (`elemNameSet` exports)
{-
Note [Adding export flags]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Set the no-discard flag if either
a) the Id is exported
b) it's mentioned in the RHS of an orphan rule
c) it's in the keep-alive set
It means that the binding won't be discarded EVEN if the binding
ends up being trivial (v = w) -- the simplifier would usually just
substitute w for v throughout, but we don't apply the substitution to
the rules (maybe we should?), so this substitution would make the rule
bogus.
You might wonder why exported Ids aren't already marked as such;
it's just because the type checker is rather busy already and
I didn't want to pass in yet another mapping.
Note [Attach rules to local ids]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Find the rules for locally-defined Ids; then we can attach them
to the binders in the top-level bindings
Reason
- It makes the rules easier to look up
- It means that transformation rules and specialisations for
locally defined Ids are handled uniformly
- It keeps alive things that are referred to only from a rule
(the occurrence analyser knows about rules attached to Ids)
- It makes sure that, when we apply a rule, the free vars
of the RHS are more likely to be in scope
- The imported rules are carried in the in-scope set
which is extended on each iteration by the new wave of
local binders; any rules which aren't on the binding will
thereby get dropped
************************************************************************
* *
* Desugaring transformation rules
* *
************************************************************************
-}
dsRule :: LRuleDecl Id -> DsM (Maybe CoreRule)
dsRule (L loc (HsRule name rule_act vars lhs _tv_lhs rhs _fv_rhs))
= putSrcSpanDs loc $
do { let bndrs' = [var | L _ (RuleBndr (L _ var)) <- vars]
; lhs' <- unsetGOptM Opt_EnableRewriteRules $
unsetWOptM Opt_WarnIdentities $
dsLExpr lhs -- Note [Desugaring RULE left hand sides]
; rhs' <- dsLExpr rhs
; this_mod <- getModule
; (bndrs'', lhs'', rhs'') <- unfold_coerce bndrs' lhs' rhs'
-- Substitute the dict bindings eagerly,
-- and take the body apart into a (f args) form
; case decomposeRuleLhs bndrs'' lhs'' of {
Left msg -> do { warnDs NoReason msg; return Nothing } ;
Right (final_bndrs, fn_id, args) -> do
{ let is_local = isLocalId fn_id
-- NB: isLocalId is False of implicit Ids. This is good because
-- we don't want to attach rules to the bindings of implicit Ids,
-- because they don't show up in the bindings until just before code gen
fn_name = idName fn_id
final_rhs = simpleOptExpr rhs'' -- De-crap it
rule_name = snd (unLoc name)
final_bndrs_set = mkVarSet final_bndrs
arg_ids = filterOut (`elemVarSet` final_bndrs_set) $
exprsSomeFreeVarsList isId args
; dflags <- getDynFlags
; rule <- dsMkUserRule this_mod is_local
rule_name rule_act fn_name final_bndrs args
final_rhs
; when (wopt Opt_WarnInlineRuleShadowing dflags) $
warnRuleShadowing rule_name rule_act fn_id arg_ids
; return (Just rule)
} } }
warnRuleShadowing :: RuleName -> Activation -> Id -> [Id] -> DsM ()
-- See Note [Rules and inlining/other rules]
warnRuleShadowing rule_name rule_act fn_id arg_ids
= do { check False fn_id -- We often have multiple rules for the same Id in a
-- module. Maybe we should check that they don't overlap
-- but currently we don't
; mapM_ (check True) arg_ids }
where
check check_rules_too lhs_id
| isLocalId lhs_id || canUnfold (idUnfolding lhs_id)
-- If imported with no unfolding, no worries
, idInlineActivation lhs_id `competesWith` rule_act
= warnDs (Reason Opt_WarnInlineRuleShadowing)
(vcat [ hang (text "Rule" <+> pprRuleName rule_name
<+> text "may never fire")
2 (text "because" <+> quotes (ppr lhs_id)
<+> text "might inline first")
, text "Probable fix: add an INLINE[n] or NOINLINE[n] pragma for"
<+> quotes (ppr lhs_id)
, ifPprDebug (ppr (idInlineActivation lhs_id) $$ ppr rule_act) ])
| check_rules_too
, bad_rule : _ <- get_bad_rules lhs_id
= warnDs (Reason Opt_WarnInlineRuleShadowing)
(vcat [ hang (text "Rule" <+> pprRuleName rule_name
<+> text "may never fire")
2 (text "because rule" <+> pprRuleName (ruleName bad_rule)
<+> text "for"<+> quotes (ppr lhs_id)
<+> text "might fire first")
, text "Probable fix: add phase [n] or [~n] to the competing rule"
, ifPprDebug (ppr bad_rule) ])
| otherwise
= return ()
get_bad_rules lhs_id
= [ rule | rule <- idCoreRules lhs_id
, ruleActivation rule `competesWith` rule_act ]
-- See Note [Desugaring coerce as cast]
unfold_coerce :: [Id] -> CoreExpr -> CoreExpr -> DsM ([Var], CoreExpr, CoreExpr)
unfold_coerce bndrs lhs rhs = do
(bndrs', wrap) <- go bndrs
return (bndrs', wrap lhs, wrap rhs)
where
go :: [Id] -> DsM ([Id], CoreExpr -> CoreExpr)
go [] = return ([], id)
go (v:vs)
| Just (tc, [k, t1, t2]) <- splitTyConApp_maybe (idType v)
, tc `hasKey` coercibleTyConKey = do
u <- newUnique
let ty' = mkTyConApp eqReprPrimTyCon [k, k, t1, t2]
v' = mkLocalCoVar
(mkDerivedInternalName mkRepEqOcc u (getName v)) ty'
box = Var (dataConWrapId coercibleDataCon) `mkTyApps`
[k, t1, t2] `App`
Coercion (mkCoVarCo v')
(bndrs, wrap) <- go vs
return (v':bndrs, mkCoreLet (NonRec v box) . wrap)
| otherwise = do
(bndrs,wrap) <- go vs
return (v:bndrs, wrap)
{- Note [Desugaring RULE left hand sides]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For the LHS of a RULE we do *not* want to desugar
[x] to build (\cn. x `c` n)
We want to leave explicit lists simply as chains
of cons's. We can achieve that slightly indirectly by
switching off EnableRewriteRules. See DsExpr.dsExplicitList.
That keeps the desugaring of list comprehensions simple too.
Nor do we want to warn of conversion identities on the LHS;
the rule is precisly to optimise them:
{-# RULES "fromRational/id" fromRational = id :: Rational -> Rational #-}
Note [Desugaring coerce as cast]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We want the user to express a rule saying roughly “mapping a coercion over a
list can be replaced by a coercion”. But the cast operator of Core (▷) cannot
be written in Haskell. So we use `coerce` for that (#2110). The user writes
map coerce = coerce
as a RULE, and this optimizes any kind of mapped' casts aways, including `map
MkNewtype`.
For that we replace any forall'ed `c :: Coercible a b` value in a RULE by
corresponding `co :: a ~#R b` and wrap the LHS and the RHS in
`let c = MkCoercible co in ...`. This is later simplified to the desired form
by simpleOptExpr (for the LHS) resp. the simplifiers (for the RHS).
See also Note [Getting the map/coerce RULE to work] in CoreSubst.
Note [Rules and inlining/other rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you have
f x = ...
g x = ...
{-# RULES "rule-for-f" forall x. f (g x) = ... #-}
then there's a good chance that in a potential rule redex
...f (g e)...
then 'f' or 'g' will inline befor the rule can fire. Solution: add an
INLINE [n] or NOINLINE [n] pragma to 'f' and 'g'.
Note that this applies to all the free variables on the LHS, both the
main function and things in its arguments.
We also check if there are Ids on the LHS that have competing RULES.
In the above example, suppose we had
{-# RULES "rule-for-g" forally. g [y] = ... #-}
Then "rule-for-f" and "rule-for-g" would compete. Better to add phase
control, so "rule-for-f" has a chance to fire before "rule-for-g" becomes
active; or perhpas after "rule-for-g" has become inactive. This is checked
by 'competesWith'
Class methods have a built-in RULE to select the method from the dictionary,
so you can't change the phase on this. That makes id very dubious to
match on class methods in RULE lhs's. See Trac #10595. I'm not happy
about this. For exmaple in Control.Arrow we have
{-# RULES "compose/arr" forall f g .
(arr f) . (arr g) = arr (f . g) #-}
and similar, which will elicit exactly these warnings, and risk never
firing. But it's not clear what to do instead. We could make the
class methocd rules inactive in phase 2, but that would delay when
subsequent transformations could fire.
************************************************************************
* *
* Desugaring vectorisation declarations
* *
************************************************************************
-}
dsVect :: LVectDecl Id -> DsM CoreVect
dsVect (L loc (HsVect _ (L _ v) rhs))
= putSrcSpanDs loc $
do { rhs' <- dsLExpr rhs
; return $ Vect v rhs'
}
dsVect (L _loc (HsNoVect _ (L _ v)))
= return $ NoVect v
dsVect (L _loc (HsVectTypeOut isScalar tycon rhs_tycon))
= return $ VectType isScalar tycon' rhs_tycon
where
tycon' | Just ty <- coreView $ mkTyConTy tycon
, (tycon', []) <- splitTyConApp ty = tycon'
| otherwise = tycon
dsVect vd@(L _ (HsVectTypeIn _ _ _ _))
= pprPanic "Desugar.dsVect: unexpected 'HsVectTypeIn'" (ppr vd)
dsVect (L _loc (HsVectClassOut cls))
= return $ VectClass (classTyCon cls)
dsVect vc@(L _ (HsVectClassIn _ _))
= pprPanic "Desugar.dsVect: unexpected 'HsVectClassIn'" (ppr vc)
dsVect (L _loc (HsVectInstOut inst))
= return $ VectInst (instanceDFunId inst)
dsVect vi@(L _ (HsVectInstIn _))
= pprPanic "Desugar.dsVect: unexpected 'HsVectInstIn'" (ppr vi)
| vikraman/ghc | compiler/deSugar/Desugar.hs | bsd-3-clause | 31,524 | 1 | 20 | 10,726 | 4,835 | 2,568 | 2,267 | 412 | 5 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
module User.RequireAuth where
import Servant
import Servant.Server.Internal (succeedWith, RouteResult)
import Network.Wai
import Network.HTTP.Types
import Data.ByteString.Char8 (unpack)
import User.Enums
instance forall a r. (HasLink a, RoleClass r)
=> HasLink (RequireAuth r :> a) where
type MkLink (RequireAuth r :> a) = MkLink a
toLink _ = toLink (Proxy :: Proxy a)
roleExist :: RoleType -> Request -> Bool
roleExist role rq =
maybe False (not . null . filter (== role))
(fmap (read . unpack) (lookup "Roles" (requestHeaders rq)))
denyAccess :: RouteResult Response
denyAccess =
succeedWith (responseLBS status401 [] "You don't have permission to do this")
data RequireAuth r
class RoleClass a
data LopcUserRole'
instance RoleClass LopcUserRole'
instance forall a. HasServer a
=> HasServer (RequireAuth LopcUserRole' :> a) where
type ServerT (RequireAuth LopcUserRole' :> a) m = ServerT a m
route (Proxy :: Proxy (RequireAuth LopcUserRole' :> a)) a rq k =
if roleExist LopcUserRole rq
then route (Proxy :: Proxy a) a rq k
else k denyAccess
type instance IsElem' e (RequireAuth LopcUserRole' :> a) = IsElem e a
data LopcAdminRole'
instance RoleClass LopcAdminRole'
instance forall a. HasServer a
=> HasServer (RequireAuth LopcAdminRole' :> a) where
type ServerT (RequireAuth LopcAdminRole' :> a) m = ServerT a m
route (Proxy :: Proxy (RequireAuth LopcAdminRole' :> a)) a rq k =
if roleExist LopcAdminRole rq
then route (Proxy :: Proxy a) a rq k
else k denyAccess
type instance IsElem' e (RequireAuth LopcAdminRole' :> a) = IsElem e a
data ControlAdminRole'
instance RoleClass ControlAdminRole'
instance forall a. HasServer a
=> HasServer (RequireAuth ControlAdminRole' :> a) where
type ServerT (RequireAuth ControlAdminRole' :> a) m = ServerT a m
route (Proxy :: Proxy (RequireAuth ControlAdminRole' :> a)) a rq k =
if roleExist ControlAdminRole rq
then route (Proxy :: Proxy a) a rq k
else k denyAccess
type instance IsElem' e (RequireAuth ControlAdminRole' :> a) = IsElem e a
data AreaAdminRole'
instance RoleClass AreaAdminRole'
instance forall a. HasServer a
=> HasServer (RequireAuth AreaAdminRole' :> a) where
type ServerT (RequireAuth AreaAdminRole' :> a) m = ServerT a m
route (Proxy :: Proxy (RequireAuth AreaAdminRole' :> a)) a rq k =
if roleExist AreaAdminRole rq
then route (Proxy :: Proxy a) a rq k
else k denyAccess
type instance IsElem' e (RequireAuth AreaAdminRole' :> a) = IsElem e a
data ManageUsersRole'
instance RoleClass ManageUsersRole'
instance forall a. HasServer a
=> HasServer (RequireAuth ManageUsersRole' :> a) where
type ServerT (RequireAuth ManageUsersRole' :> a) m = ServerT a m
route (Proxy :: Proxy (RequireAuth ManageUsersRole' :> a)) a rq k =
if roleExist ManageUsersRole rq
then route (Proxy :: Proxy a) a rq k
else k denyAccess
type instance IsElem' e (RequireAuth ManageUsersRole' :> a) = IsElem e a
data SysAdminRole'
instance RoleClass SysAdminRole'
instance forall a. HasServer a
=> HasServer (RequireAuth SysAdminRole' :> a) where
type ServerT (RequireAuth SysAdminRole' :> a) m = ServerT a m
route (Proxy :: Proxy (RequireAuth SysAdminRole' :> a)) a rq k =
if roleExist SysAdminRole rq
then route (Proxy :: Proxy a) a rq k
else k denyAccess
type instance IsElem' e (RequireAuth SysAdminRole' :> a) = IsElem e a
| hectorhon/autotrace2 | app/User/RequireAuth.hs | bsd-3-clause | 3,604 | 0 | 12 | 685 | 1,219 | 626 | 593 | -1 | -1 |
-- | This module is for internal functions used in more than one place
module Language.KansasLava.Internal where
import Data.Maybe as Maybe
import Language.KansasLava.Stream as Stream
import Prelude hiding (tail, lookup)
takeMaybe :: Maybe Int -> [a] -> [a]
takeMaybe = maybe id take
-- surely this exists in the prelude?
mergeWith :: (a -> a -> a) -> [[a]] -> [a]
mergeWith _ [] = []
mergeWith f ls = foldr1 (Prelude.zipWith f) ls
splitLists :: [[a]] -> [Int] -> [[[a]]]
splitLists xs (i:is) = map (take i) xs : splitLists (map (drop i) xs) is
splitLists _ [] = [[]]
-- | Stepify allows us to make a stream element-strict.
class Stepify a where
stepify :: a -> a
-- | Strictly apply a function to each element of a Stream.
stepifyStream :: (a -> ()) -> Stream a -> Stream a
stepifyStream f (Cons a r) = Cons a (f a `seq` stepifyStream f r)
-- | A 'Radix' is a trie indexed by bitvectors.
data Radix a
= Res !a -- ^ A value stored in the tree
| NoRes -- ^ Non-present value
-- | A split-node, left corresponds to 'True' key bit, right corresponds to 'False' key bit.
| Choose !(Radix a) !(Radix a)
deriving Show
-- | The empty tree
empty :: Radix a
empty = NoRes
-- | Add a value (keyed by the list of bools) into a tree
insert :: [Bool] -> a -> Radix a -> Radix a
insert [] y (Res _) = Res $! y
insert [] y NoRes = Res $! y
insert [] _ (Choose _ _) = error "inserting with short key"
insert xs y NoRes = insert xs y (Choose NoRes NoRes)
insert _ _ (Res _) = error "inserting with too long a key"
insert (True:a) y (Choose l r) = Choose (insert a y l) r
insert (False:a) y (Choose l r) = Choose l (insert a y r)
-- | Find a value in a radix tree
find :: [Bool] -> Radix a -> Maybe a
find [] (Res v) = Just v
find [] NoRes = Nothing
find [] _ = error "find error with short key"
find (_:_) (Res _) = error "find error with long key"
find (_:_) NoRes = Nothing
find (True:a) (Choose l _) = find a l
find (False:a) (Choose _ r) = find a r
| andygill/kansas-lava | Language/KansasLava/Internal.hs | bsd-3-clause | 1,996 | 2 | 10 | 461 | 783 | 410 | 373 | 45 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module Test.Mismi.Autoscaling.Core.Data where
import Mismi.Autoscaling.Core.Data
import P
import Test.Mismi.Autoscaling.Core.Arbitrary ()
import Test.QuickCheck
prop_scale_in p =
protectedFromScaleInFromBool (protectedFromScaleInToBool p) === p
prop_propagate p =
propagateFromBool (propagateToBool p) === p
return []
tests = $quickCheckAll
| ambiata/mismi | mismi-autoscaling-core/test/Test/Mismi/Autoscaling/Core/Data.hs | bsd-3-clause | 543 | 0 | 8 | 99 | 95 | 55 | 40 | 15 | 1 |
-- Redirect to the URL given by the url parameter.
import Network.CGI (MonadCGI, CGIResult, runCGI, getInput, output, redirect)
redirectToURL :: MonadCGI m => m CGIResult
redirectToURL =
getInput "url" >>= maybe (output "url parameter not set!\n") redirect
main =
runCGI redirectToURL
| andersk/haskell-cgi | examples/redirect.hs | bsd-3-clause | 296 | 0 | 8 | 52 | 73 | 39 | 34 | 6 | 1 |
module Lib ( runVm ) where
import qualified Data.Binary.Get as G
import Data.Bits
import qualified Data.ByteString.Lazy as BS
import Data.Char (chr, ord)
import Data.Serialize
import qualified Data.Vector.Unboxed as V
import Debug.Trace
import System.IO (hFlush, stdout)
-- == architecture ==
-- three storage regions
data State = State { mem :: V.Vector Int -- memory with 15-bit address space
-- storing 16-bit values
, reg :: V.Vector Int -- eight registers
, stack :: [Int] -- an unbounded stack which holds
-- individual 16-bit values
, pc :: Int
, outBuf :: Maybe Char
, inBuf :: String
, status :: Status
}
deriving (Eq, Show, Read)
data Val = Lit Int | Reg Int
deriving (Eq, Show)
data Op = Halt
| Set Val Val
| Push Val
| Pop Val
| Equ Val Val Val
| Gt Val Val Val
| Jmp Val
| Jt Val Val
| Jf Val Val
| Add Val Val Val
| Mult Val Val Val
| Mod Val Val Val
| And Val Val Val
| Or Val Val Val
| Not Val Val
| Rmem Val Val
| Wmem Val Val
| Call Val
| Ret
| Out Val
| In Val
| Noop
| Data Val
deriving (Eq, Show)
-- all numbers are unsigned integers 0..32767 (15-bit)
-- all math is modulo 32768; 32758 + 15 => 5
maxLit :: Int
maxLit = 32768
data Status = Running | Reading | Halted
deriving (Eq, Show, Read)
prog :: IO (V.Vector Int)
prog = do
f <- BS.readFile "challenge.bin"
let p = V.fromList $ G.runGet getWords f
-- the binary doesn't take up the full memory, so zero pad to get
-- the full 15 bit address space
return $ p V.++ V.replicate (maxLit - V.length p) 0
-- each number is stored as a 16-bit little-endian pair
-- (low byte, high byte)
getWords :: G.Get [Int]
getWords = do
empty <- G.isEmpty
if empty
then return []
else do
w <- G.getWord16le
ws <- getWords
return (fromEnum w : ws)
readOp :: State -> Int -> (Op, Int)
readOp s p = let m = mem s in
case m V.! p of
0 -> (Halt, 1)
1 -> (Set (parseVal s p 1) (parseVal s p 2), 3)
2 -> (Push (parseVal s p 1), 2)
3 -> (Pop (parseVal s p 1), 2)
4 -> (Equ (parseVal s p 1) (parseVal s p 2) (parseVal s p 3), 4)
5 -> (Gt (parseVal s p 1) (parseVal s p 2) (parseVal s p 3), 4)
6 -> (Jmp $ parseVal s p 1, 2)
7 -> (Jt (parseVal s p 1) (parseVal s p 2), 3)
8 -> (Jf (parseVal s p 1) (parseVal s p 2), 3)
9 -> (Add (parseVal s p 1) (parseVal s p 2) (parseVal s p 3), 4)
10 -> (Mult (parseVal s p 1) (parseVal s p 2) (parseVal s p 3), 4)
11 -> (Mod (parseVal s p 1) (parseVal s p 2) (parseVal s p 3), 4)
12 -> (And (parseVal s p 1) (parseVal s p 2) (parseVal s p 3), 4)
13 -> (Or (parseVal s p 1) (parseVal s p 2) (parseVal s p 3), 4)
14 -> (Not (parseVal s p 1) (parseVal s p 2), 3)
15 -> (Rmem (parseVal s p 1) (parseVal s p 2), 3)
16 -> (Wmem (parseVal s p 1) (parseVal s p 2), 3)
17 -> (Call (parseVal s p 1), 2)
18 -> (Ret, 1)
19 -> (Out $ parseVal s p 1, 2)
20 -> (In $ parseVal s p 1, 2)
21 -> (Noop, 1)
_ -> (Data $ parseVal s p 1, 1)
-- numbers 0..32767 mean a literal value
-- numbers 32768..32775 instead mean registers 0..7
parseVal :: State -> Int -> Int -> Val
parseVal (State m _ _ _ _ _ _) p i =
let v = m V.! (p + i) in
if v < maxLit then Lit v
else Reg $ v `mod` maxLit
deVal :: State -> Val -> Int
deVal _ (Lit i) = i
deVal (State _ rs _ _ _ _ _) (Reg i) = rs V.! i
initState :: V.Vector Int -> State
initState prog = State prog
(V.fromList [ 0, 0, 0, 0, 0, 0, 0, 0 ])
[]
0
Nothing
[]
Running
setPc :: State -> Int -> State
setPc (State m r st _ o i s) j =
State m r st j o i s
incPc :: State -> Int -> State
incPc s j = setPc s (j + pc s)
setReg :: State -> Val -> Int -> State
setReg (State m rs st p o i s) (Reg r) v =
State m (rs V.// [(r, v)]) st p o i s
setStatus :: State -> Status -> State
setStatus (State m r st p o i _) s =
State m r st p o i s
push :: State -> Int -> State
push (State m r st p o i s) v =
State m r (v : st) p o i s
pop :: State -> (State, Int)
pop (State m r (v:st) p o i s) =
(State m r st p o i s, v)
rmem :: State -> Val -> Int -> State
rmem (State m r st p o i s) (Reg a) from = State m nr st p o i s
where nr = r V.// [(a, m V.! from)]
wmem :: State -> Int -> Int -> State
wmem (State m r st p o i s) to v = State nm r st p o i s
where nm = m V.// [(to, v)]
setOut :: State -> Int -> State
setOut (State m r st p _ i s) o =
State m r st p (Just $ chr o) i s
clearOut :: State -> State
clearOut (State m r st p _ i s) =
State m r st p Nothing i s
readChar :: State -> Val -> State
readChar (State m rs st p o (i:is) s) (Reg r) =
State m (rs V.// [(r, ord i)]) st p o is s
setInput :: State -> String -> State
setInput (State m r st p o _ s) i =
State m r st p o i s
execOp :: State -> (Op, Int) -> State
execOp s (Halt, n) = setStatus s Halted
execOp s (Set a b, n) = incPc (setReg s a (deVal s b)) n
execOp s (Push a, n) = incPc (push s (deVal s a)) n
execOp s (Pop a, n) = let (ns, b) = pop s in
incPc (setReg ns a b) n
execOp s (Equ a b c, n) =
incPc (setReg s a (if (deVal s b) == (deVal s c) then 1 else 0)) n
execOp s (Gt a b c, n) =
incPc (setReg s a (if (deVal s b) > (deVal s c) then 1 else 0)) n
execOp s (Jmp v, _) = setPc s (deVal s v)
execOp s (Jt a b, n) = if deVal s a /= 0
then setPc s (deVal s b)
else incPc s n
execOp s (Jf a b, n) = if deVal s a == 0
then setPc s (deVal s b)
else incPc s n
execOp s (Add a b c, n) =
incPc (setReg s a ((deVal s b + deVal s c) `mod` maxLit)) n
execOp s (Mult a b c, n) =
incPc (setReg s a ((deVal s b * deVal s c) `mod` maxLit)) n
execOp s (Mod a b c, n) =
incPc (setReg s a (deVal s b `mod` deVal s c)) n
execOp s (And a b c, n) = incPc (setReg s a (deVal s b .&. deVal s c)) n
execOp s (Or a b c, n) = incPc (setReg s a (deVal s b .|. deVal s c)) n
execOp s (Not a b, n) = let neg = complement (deVal s b) .&. 32767
in
incPc (setReg s a neg) n
execOp s (Rmem a b, n) = incPc (rmem s a (deVal s b)) n
execOp s (Wmem a b, n) = incPc (wmem s (deVal s a) (deVal s b)) n
execOp s (Call a, n) = let t = deVal s a in
setPc (push s (n + pc s)) t
execOp s (Ret, n) = if null $ stack s
then setStatus s Halted
else let (ns, b) = pop s
in
setPc ns b
execOp s (Out c, n) = setOut (incPc s n) (deVal s c)
execOp s (In c, n) = if null $ inBuf s
then setStatus s Reading
else incPc (readChar s c) n
execOp s (Noop, n) = incPc s n
stepVm :: State -> State
stepVm s = execOp s (readOp s (pc s))
runVm :: IO ()
runVm = do
p <- prog
go (initState p)
where
go s = case status s of
Halted -> return ()
Running -> let ns = case outBuf s of
Just c -> do
putChar c
return $ clearOut s
Nothing -> return s
in do
a <- ns
go $ stepVm a
Reading -> do
l <- getLine
case l of
":debug" -> do
putStrLn "Entering debug mode..."
ds <- debugMode $ return s
putStrLn "Exiting debug mode..."
go ds
"_fix_teleporter" -> go $ fixTeleporter s
_ -> go $ setStatus (setInput s (l ++ "\n")) Running
debugMode :: IO State -> IO State
debugMode is = do
putStr "Debug> "
hFlush stdout
l <- getLine
case l of
"exit" -> is
"save" -> do
handleSave is
debugMode is
"load" -> do
a <- handleLoad is
debugMode $ return a
"dump" -> do
handleDump is
debugMode is
_ -> do
putStrLn "I don't understand"
debugMode is
handleSave :: IO State -> IO ()
handleSave is = do
putStr "File name to save state into: "
hFlush stdout
f <- getLine
s <- is
writeFile f (show s)
return ()
handleLoad :: IO State -> IO State
handleLoad is = do
putStr "File name to load: "
hFlush stdout
f <- getLine
g <- readFile f
let ns = read g
return ns
handleDump :: IO State -> IO ()
handleDump is = let dumpMem :: State -> Int -> [String]
dumpMem s p = if p >= (V.length $ mem s)
then []
else let (op, n) = readOp s p
in
(show p ++ ": " ++ show op ++ "\n") :
dumpMem s (p + n)
in do
s <- is
writeFile "mem-dump" $ concat $ dumpMem s 0
return ()
fixTeleporter :: State -> State
fixTeleporter s = let a = setReg s (Reg 7) 25734
b = wmem a 5489 21
c = wmem b 5490 21
in
wmem c 5493 6
| shaunplee/synacor-challenge-hs | src/Lib.hs | bsd-3-clause | 9,998 | 0 | 20 | 4,164 | 4,380 | 2,225 | 2,155 | 255 | 23 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : dave.laing.80@gmail.com
Stability : experimental
Portability : non-portable
-}
module Fragment.Variant.Ast (
module X
) where
import Fragment.Variant.Ast.Type as X
import Fragment.Variant.Ast.Error as X
import Fragment.Variant.Ast.Pattern as X
import Fragment.Variant.Ast.Term as X
| dalaing/type-systems | src/Fragment/Variant/Ast.hs | bsd-3-clause | 363 | 0 | 4 | 59 | 50 | 38 | 12 | 6 | 0 |
{-# LANGUAGe BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGe TemplateHaskell #-}
module Mandelbrot.NikolaV2 (mandelbrotImageGenerator) where
import Control.Monad (replicateM_)
import Data.IORef
import Data.Int
import Data.Word
import Data.Array.Nikola.Backend.CUDA.TH
import Data.Array.Repa
import Data.Array.Repa.Eval
import Data.Array.Repa.Mutable
import Data.Array.Repa.Repr.ForeignPtr as F
import Data.Array.Repa.Repr.UnboxedForeign as UF
import Data.Array.Repa.Repr.CUDA.UnboxedForeign as CUF
import qualified Data.Vector.UnboxedForeign as VUF
import qualified Data.Vector.Storable as V
import qualified Mandelbrot.NikolaV2.Implementation as I
type R = Double
type Complex = (R, R)
type RGBA = Word32
type Bitmap r = Array r DIM2 RGBA
type MBitmap r = MArray r DIM2 RGBA
type ComplexPlane r = Array r DIM2 Complex
type MComplexPlane r = MArray r DIM2 Complex
type StepPlane r = Array r DIM2 (Complex, Int32)
type MStepPlane r = MArray r DIM2 (Complex, Int32)
step :: ComplexPlane CUF -> MStepPlane CUF -> IO ()
step = $(compile I.step)
genPlane :: R
-> R
-> R
-> R
-> Int32
-> Int32
-> MComplexPlane CUF
-> IO ()
genPlane = $(compile I.genPlane)
mkinit :: ComplexPlane CUF -> MStepPlane CUF -> IO ()
mkinit = $(compile I.mkinit)
prettyMandelbrot :: Int32 -> StepPlane CUF -> MBitmap CUF -> IO ()
prettyMandelbrot = $(compile I.prettyMandelbrot)
type MandelFun = R
-> R
-> R
-> R
-> Int
-> Int
-> Int
-> IO (Bitmap F)
data MandelState = MandelState
{ manDim :: DIM2
, manMBmapH :: MVec UF RGBA
, manMBmapD :: MBitmap CUF
, manMCs :: MComplexPlane CUF
, manMZs :: MStepPlane CUF
}
mandelbrotImageGenerator :: IO MandelFun
mandelbrotImageGenerator = do
state <- newState (ix2 0 0)
stateRef <- newIORef state
return $ mandelbrotImage stateRef
where
mandelbrotImage :: IORef MandelState -> MandelFun
mandelbrotImage stateRef lowx lowy highx highy viewx viewy depth = do
let sh = ix2 viewy viewx
state <- updateState stateRef sh
let mbmapH = manMBmapH state
mbmapD = manMBmapD state
mcs = manMCs state
mzs = manMZs state
genPlane lowx' lowy' highx' highy' viewx' viewy' mcs
cs <- unsafeFreezeMArray mcs
mkinit cs mzs
replicateM_ depth (step cs mzs)
zs <- unsafeFreezeMArray mzs
prettyMandelbrot depth' zs mbmapD
bmapD <- unsafeFreezeMArray mbmapD
loadHostP bmapD mbmapH
bmapH <- unsafeFreezeMVec sh mbmapH
return (convertBitmap bmapH)
where
lowx', lowy', highx', highy' :: R
lowx' = realToFrac lowx
lowy' = realToFrac lowy
highx' = realToFrac highx
highy' = realToFrac highy
viewx', viewy', depth' :: Int32
viewx' = fromIntegral viewx
viewy' = fromIntegral viewy
depth' = fromIntegral depth
convertBitmap :: Bitmap UF -> Bitmap F
convertBitmap bmap =
let VUF.V_Word32 v = UF.toUnboxedForeign bmap
(fp, _) = V.unsafeToForeignPtr0 v
in
F.fromForeignPtr (extent bmap) fp
newState :: DIM2 -> IO MandelState
newState sh = do
mbmapH <- newMVec (size sh)
mbmapD <- newMArray sh
mcs <- newMArray sh
mzs <- newMArray sh
return $ MandelState sh mbmapH mbmapD mcs mzs
updateState :: IORef MandelState -> DIM2 -> IO MandelState
updateState stateRef sh = do
state <- readIORef stateRef
if manDim state == sh
then return state
else do state' <- newState sh
writeIORef stateRef state'
return state'
| mainland/nikola | examples/mandelbrot/Mandelbrot/NikolaV2.hs | bsd-3-clause | 3,903 | 0 | 14 | 1,189 | 1,099 | 569 | 530 | 108 | 2 |
-- | Overall duration of fragmented media.
module Data.ByteString.IsoBaseFileFormat.Boxes.MovieExtendsHeader where
import Data.ByteString.IsoBaseFileFormat.Box
import Data.ByteString.IsoBaseFileFormat.ReExports
import Data.ByteString.IsoBaseFileFormat.Util.BoxContent
import Data.ByteString.IsoBaseFileFormat.Util.BoxFields
import Data.ByteString.IsoBaseFileFormat.Util.FullBox
import Data.ByteString.IsoBaseFileFormat.Util.Versioned
-- * @mehd@ Box
-- | Construct a 'MovieHeader' box.
movieExtendsHeader ::
(KnownNat version) =>
MovieExtendsHeader version ->
Box (FullBox (MovieExtendsHeader version) version)
movieExtendsHeader = fullBox 0
-- | Movie length incorporating all fragments.
newtype MovieExtendsHeader (version :: Nat) where
MovieExtendsHeader ::
Versioned (U32 "fragment_duration") (U64 "fragment_duration") version ->
MovieExtendsHeader version
deriving (IsBoxContent)
instance IsBox (MovieExtendsHeader version)
type instance BoxTypeSymbol (MovieExtendsHeader v) = "mehd"
| sheyll/isobmff-builder | src/Data/ByteString/IsoBaseFileFormat/Boxes/MovieExtendsHeader.hs | bsd-3-clause | 1,013 | 0 | 11 | 110 | 183 | 110 | 73 | -1 | -1 |
module ExThreeSpec (main, spec) where
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Find the Kth element of a list. First element is number 1" $ do
it "should find the Kth element as a Maybe" $ do
elementAt [1,2,3] 2 `shouldBe` Just 2
it "should return Nothing for empty list" $ do
elementAt ([]::[Char]) 2 `shouldBe` Nothing
it "should return Nothing when k < 1" $ do
elementAt [1] 0 `shouldBe` Nothing
it "should return Nothing when k < length list" $ do
elementAt [1] 2 `shouldBe` Nothing
it "should be polymorphic" $ do
elementAt ['a'..'z'] 25 `shouldBe` Just 'y'
elementAt :: [a] -> Int -> Maybe a
elementAt [] _ = Nothing
elementAt (x:_) 1 = Just x
elementAt (_:xs) k
| k < 1 = Nothing
| otherwise = elementAt xs (k - 1)
| abinr/nine | test/ExThreeSpec.hs | bsd-3-clause | 824 | 0 | 16 | 206 | 311 | 156 | 155 | 23 | 1 |
{-# LANGUAGE CPP, ConstraintKinds, DeriveDataTypeable, FlexibleContexts, MultiWayIf, NamedFieldPuns,
OverloadedStrings, RankNTypes, RecordWildCards, ScopedTypeVariables, TemplateHaskell,
TupleSections #-}
-- | Run commands in Docker containers
module Stack.Docker
(cleanup
,CleanupOpts(..)
,CleanupAction(..)
,dockerCleanupCmdName
,dockerCmdName
,dockerPullCmdName
,execWithOptionalContainer
,preventInContainer
,pull
,reexecWithOptionalContainer
,reset
,reExecArgName
) where
import Control.Applicative
import Control.Exception.Lifted
import Control.Monad
import Control.Monad.Catch (MonadThrow,throwM,MonadCatch,MonadMask)
import Control.Monad.IO.Class (MonadIO,liftIO)
import Control.Monad.Logger (MonadLogger,logError,logInfo,logWarn)
import Control.Monad.Reader (MonadReader,asks)
import Control.Monad.Writer (execWriter,runWriter,tell)
import Control.Monad.Trans.Control (MonadBaseControl)
import Data.Aeson.Extended (FromJSON(..),(.:),(.:?),(.!=),eitherDecode)
import Data.ByteString.Builder (stringUtf8,charUtf8,toLazyByteString)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Char (isSpace,toUpper,isAscii,isDigit)
import Data.Conduit.List (sinkNull)
import Data.List (dropWhileEnd,intercalate,isPrefixOf,isInfixOf,foldl',sortBy)
import Data.List.Extra (trim)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Streaming.Process (ProcessExitedUnsuccessfully(..))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Time (UTCTime,LocalTime(..),diffDays,utcToLocalTime,getZonedTime,ZonedTime(..))
import Data.Typeable (Typeable)
import Data.Version (showVersion)
import Distribution.System (Platform (Platform), Arch (X86_64), OS (Linux))
import Distribution.Text (display)
import Network.HTTP.Client.Conduit (HasHttpManager)
import Path
import Path.Extra (toFilePathNoTrailingSep)
import Path.IO (getWorkingDir,listDirectory,createTree,removeFile,removeTree,dirExists)
import qualified Paths_stack as Meta
import Prelude -- Fix redundant import warnings
import Stack.Constants (projectDockerSandboxDir,stackProgName,stackRootEnvVar)
import Stack.Docker.GlobalDB
import Stack.Types
import Stack.Types.Internal
import Stack.Setup (ensureDockerStackExe)
import System.Directory (canonicalizePath, getModificationTime)
import System.Environment (lookupEnv,getProgName, getArgs,getExecutablePath)
import System.Exit (exitSuccess, exitWith)
import System.FilePath (takeBaseName)
import System.IO (stderr,stdin,stdout,hIsTerminalDevice)
import System.Process.PagerEditor (editByteString)
import System.Process.Read
import System.Process.Run
import System.Process (CreateProcess(delegate_ctlc))
import Text.Printf (printf)
#ifndef WINDOWS
import Control.Monad.Trans.Control (liftBaseWith)
import System.Posix.Signals
#endif
-- | If Docker is enabled, re-runs the currently running OS command in a Docker container.
-- Otherwise, runs the inner action.
--
-- This takes an optional release action which should be taken IFF control is
-- transfering away from the current process to the intra-container one. The main use
-- for this is releasing a lock. After launching reexecution, the host process becomes
-- nothing but an manager for the call into docker and thus may not hold the lock.
reexecWithOptionalContainer
:: M env m
=> Maybe (Path Abs Dir)
-> Maybe (m ())
-> IO ()
-> Maybe (m ())
-> Maybe (m ())
-> m ()
reexecWithOptionalContainer mprojectRoot =
execWithOptionalContainer mprojectRoot getCmdArgs
where
getCmdArgs envOverride imageInfo = do
config <- asks getConfig
args <-
fmap
(("--" ++ reExecArgName ++ "=" ++ showVersion Meta.version) :)
(liftIO getArgs)
case dockerStackExe (configDocker config) of
Just DockerStackExeHost
| configPlatform config == dockerContainerPlatform ->
fmap (cmdArgs args) (liftIO getExecutablePath)
| otherwise -> throwM UnsupportedStackExeHostPlatformException
Just DockerStackExeImage -> do
progName <- liftIO getProgName
return (takeBaseName progName, args, [], [])
Just (DockerStackExePath path) ->
fmap
(cmdArgs args)
(liftIO $ canonicalizePath (toFilePath path))
Just DockerStackExeDownload -> exeDownload args
Nothing
| configPlatform config == dockerContainerPlatform -> do
(exePath,exeTimestamp,misCompatible) <-
liftIO $
do exePath <- liftIO getExecutablePath
exeTimestamp <- liftIO (getModificationTime exePath)
isKnown <-
liftIO $
getDockerImageExe
config
(iiId imageInfo)
exePath
exeTimestamp
return (exePath, exeTimestamp, isKnown)
case misCompatible of
Just True -> return (cmdArgs args exePath)
Just False -> exeDownload args
Nothing -> do
e <-
try $
sinkProcessStderrStdout
Nothing
envOverride
"docker"
[ "run"
, "-v"
, exePath ++ ":" ++ "/tmp/stack"
, iiId imageInfo
, "/tmp/stack"
, "--version"]
sinkNull
sinkNull
let compatible =
case e of
Left (ProcessExitedUnsuccessfully _ _) ->
False
Right _ -> True
liftIO $
setDockerImageExe
config
(iiId imageInfo)
exePath
exeTimestamp
compatible
if compatible
then return (cmdArgs args exePath)
else exeDownload args
Nothing -> exeDownload args
exeDownload args =
fmap
(cmdArgs args . toFilePath)
(ensureDockerStackExe dockerContainerPlatform)
cmdArgs args exePath =
let mountPath = concat ["/opt/host/bin/", takeBaseName exePath]
in (mountPath, args, [], [Mount exePath mountPath])
-- | If Docker is enabled, re-runs the OS command returned by the second argument in a
-- Docker container. Otherwise, runs the inner action.
--
-- This takes an optional release action just like `reexecWithOptionalContainer`.
execWithOptionalContainer
:: M env m
=> Maybe (Path Abs Dir)
-> (EnvOverride -> Inspect -> m (FilePath,[String],[(String,String)],[Mount]))
-> Maybe (m ())
-> IO ()
-> Maybe (m ())
-> Maybe (m ())
-> m ()
execWithOptionalContainer mprojectRoot getCmdArgs mbefore inner mafter mrelease =
do config <- asks getConfig
inContainer <- getInContainer
isReExec <- asks getReExec
if | inContainer && not isReExec && (isJust mbefore || isJust mafter) ->
throwM OnlyOnHostException
| inContainer ->
liftIO (do inner
exitSuccess)
| not (dockerEnable (configDocker config)) ->
do fromMaybeAction mbefore
liftIO inner
fromMaybeAction mafter
liftIO exitSuccess
| otherwise ->
do fromMaybeAction mrelease
runContainerAndExit
getCmdArgs
mprojectRoot
(fromMaybeAction mbefore)
(fromMaybeAction mafter)
where
fromMaybeAction Nothing = return ()
fromMaybeAction (Just hook) = hook
-- | Error if running in a container.
preventInContainer :: (MonadIO m,MonadThrow m) => m () -> m ()
preventInContainer inner =
do inContainer <- getInContainer
if inContainer
then throwM OnlyOnHostException
else inner
-- | 'True' if we are currently running inside a Docker container.
getInContainer :: (MonadIO m) => m Bool
getInContainer = liftIO (isJust <$> lookupEnv inContainerEnvVar)
-- | Run a command in a new Docker container, then exit the process.
runContainerAndExit :: M env m
=> (EnvOverride -> Inspect -> m (FilePath,[String],[(String,String)],[Mount]))
-> Maybe (Path Abs Dir)
-> m ()
-> m ()
-> m ()
runContainerAndExit getCmdArgs
mprojectRoot
before
after =
do config <- asks getConfig
let docker = configDocker config
envOverride <- getEnvOverride (configPlatform config)
checkDockerVersion envOverride docker
(dockerHost,dockerCertPath,bamboo,jenkins) <-
liftIO ((,,,) <$> lookupEnv "DOCKER_HOST"
<*> lookupEnv "DOCKER_CERT_PATH"
<*> lookupEnv "bamboo_buildKey"
<*> lookupEnv "JENKINS_HOME")
let isRemoteDocker = maybe False (isPrefixOf "tcp://") dockerHost
userEnvVars <-
if fromMaybe (not isRemoteDocker) (dockerSetUser docker)
then do
uidOut <- readProcessStdout Nothing envOverride "id" ["-u"]
gidOut <- readProcessStdout Nothing envOverride "id" ["-g"]
return
[ "-e","WORK_UID=" ++ dropWhileEnd isSpace (decodeUtf8 uidOut)
, "-e","WORK_GID=" ++ dropWhileEnd isSpace (decodeUtf8 gidOut) ]
else return []
isStdoutTerminal <- asks getTerminal
(isStdinTerminal,isStderrTerminal) <-
liftIO ((,) <$> hIsTerminalDevice stdin
<*> hIsTerminalDevice stderr)
pwd <- getWorkingDir
when (isRemoteDocker &&
maybe False (isInfixOf "boot2docker") dockerCertPath)
($logWarn "Warning: Using boot2docker is NOT supported, and not likely to perform well.")
let image = dockerImage docker
maybeImageInfo <- inspect envOverride image
imageInfo <- case maybeImageInfo of
Just ii -> return ii
Nothing
| dockerAutoPull docker ->
do pullImage envOverride docker image
mii2 <- inspect envOverride image
case mii2 of
Just ii2 -> return ii2
Nothing -> throwM (InspectFailedException image)
| otherwise -> throwM (NotPulledException image)
(cmnd,args,envVars,extraMount) <- getCmdArgs envOverride imageInfo
let imageEnvVars = map (break (== '=')) (icEnv (iiConfig imageInfo))
sandboxID = fromMaybe "default" (lookupImageEnv sandboxIDEnvVar imageEnvVars)
sandboxIDDir <- parseRelDir (sandboxID ++ "/")
let stackRoot = configStackRoot config
sandboxDir = projectDockerSandboxDir projectRoot
sandboxSandboxDir = sandboxDir </> $(mkRelDir "_sandbox/") </> sandboxIDDir
sandboxHomeDir = sandboxDir </> homeDirName
sandboxRepoDir = sandboxDir </> sandboxIDDir
sandboxSubdirs = map (\d -> sandboxRepoDir </> d)
sandboxedHomeSubdirectories
isTerm = not (dockerDetach docker) &&
isStdinTerminal &&
isStdoutTerminal &&
isStderrTerminal
keepStdinOpen = not (dockerDetach docker) &&
-- Workaround for https://github.com/docker/docker/issues/12319
(isTerm || (isNothing bamboo && isNothing jenkins))
liftIO
(do updateDockerImageLastUsed config
(iiId imageInfo)
(toFilePath projectRoot)
mapM_ createTree
(concat [[sandboxHomeDir, sandboxSandboxDir, stackRoot] ++
sandboxSubdirs]))
containerID <- (trim . decodeUtf8) <$> readDockerProcess
envOverride
(concat
[["create"
,"--net=host"
,"-e",inContainerEnvVar ++ "=1"
,"-e",stackRootEnvVar ++ "=" ++ toFilePathNoTrailingSep stackRoot
,"-e","WORK_WD=" ++ toFilePathNoTrailingSep pwd
,"-e","WORK_HOME=" ++ toFilePathNoTrailingSep sandboxRepoDir
,"-e","WORK_ROOT=" ++ toFilePathNoTrailingSep projectRoot
,"-v",toFilePathNoTrailingSep stackRoot ++ ":" ++ toFilePathNoTrailingSep stackRoot
,"-v",toFilePathNoTrailingSep projectRoot ++ ":" ++ toFilePathNoTrailingSep projectRoot
,"-v",toFilePathNoTrailingSep sandboxSandboxDir ++ ":" ++ toFilePathNoTrailingSep sandboxDir
,"-v",toFilePathNoTrailingSep sandboxHomeDir ++ ":" ++ toFilePathNoTrailingSep sandboxRepoDir
,"-v",toFilePathNoTrailingSep stackRoot ++ ":" ++
toFilePathNoTrailingSep (sandboxRepoDir </> $(mkRelDir ("." ++ stackProgName ++ "/")))]
,userEnvVars
,concatMap (\(k,v) -> ["-e", k ++ "=" ++ v]) envVars
,concatMap sandboxSubdirArg sandboxSubdirs
,concatMap mountArg (extraMount ++ dockerMount docker)
,concatMap (\nv -> ["-e", nv]) (dockerEnv docker)
,case dockerContainerName docker of
Just name -> ["--name=" ++ name]
Nothing -> []
,["-t" | isTerm]
,["-i" | keepStdinOpen]
,dockerRunArgs docker
,[image]
,[cmnd]
,args])
before
#ifndef WINDOWS
runInBase <- liftBaseWith $ \run -> return (void . run)
oldHandlers <- forM (concat [[(sigINT,sigTERM) | not keepStdinOpen]
,[(sigTERM,sigTERM)]]) $ \(sigIn,sigOut) -> do
let sigHandler = runInBase (readProcessNull Nothing envOverride "docker"
["kill","--signal=" ++ show sigOut,containerID])
oldHandler <- liftIO $ installHandler sigIn (Catch sigHandler) Nothing
return (sigIn, oldHandler)
#endif
e <- try (callProcess'
(if keepStdinOpen then id else (\cp -> cp { delegate_ctlc = False }))
Nothing
envOverride
"docker"
(concat [["start"]
,["-a" | not (dockerDetach docker)]
,["-i" | keepStdinOpen]
,[containerID]]))
#ifndef WINDOWS
forM_ oldHandlers $ \(sig,oldHandler) ->
liftIO $ installHandler sig oldHandler Nothing
#endif
unless (dockerPersist docker || dockerDetach docker)
(readProcessNull Nothing envOverride "docker" ["rm","-f",containerID])
case e of
Left (ProcessExitedUnsuccessfully _ ec) -> liftIO (exitWith ec)
Right () -> do after
liftIO exitSuccess
where
lookupImageEnv name vars =
case lookup name vars of
Just ('=':val) -> Just val
_ -> Nothing
mountArg (Mount host container) = ["-v",host ++ ":" ++ container]
sandboxSubdirArg subdir = ["-v",toFilePathNoTrailingSep subdir++ ":" ++ toFilePathNoTrailingSep subdir]
projectRoot = fromMaybeProjectRoot mprojectRoot
-- | Clean-up old docker images and containers.
cleanup :: M env m
=> CleanupOpts -> m ()
cleanup opts =
do config <- asks getConfig
let docker = configDocker config
envOverride <- getEnvOverride (configPlatform config)
checkDockerVersion envOverride docker
let runDocker = readDockerProcess envOverride
imagesOut <- runDocker ["images","--no-trunc","-f","dangling=false"]
danglingImagesOut <- runDocker ["images","--no-trunc","-f","dangling=true"]
runningContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=running"]
restartingContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=restarting"]
exitedContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=exited"]
pausedContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=paused"]
let imageRepos = parseImagesOut imagesOut
danglingImageHashes = Map.keys (parseImagesOut danglingImagesOut)
runningContainers = parseContainersOut runningContainersOut ++
parseContainersOut restartingContainersOut
stoppedContainers = parseContainersOut exitedContainersOut ++
parseContainersOut pausedContainersOut
inspectMap <- inspects envOverride
(Map.keys imageRepos ++
danglingImageHashes ++
map fst stoppedContainers ++
map fst runningContainers)
(imagesLastUsed,curTime) <-
liftIO ((,) <$> getDockerImagesLastUsed config
<*> getZonedTime)
let planWriter = buildPlan curTime
imagesLastUsed
imageRepos
danglingImageHashes
stoppedContainers
runningContainers
inspectMap
plan = toLazyByteString (execWriter planWriter)
plan' <- case dcAction opts of
CleanupInteractive ->
liftIO (editByteString (intercalate "-" [stackProgName
,dockerCmdName
,dockerCleanupCmdName
,"plan"])
plan)
CleanupImmediate -> return plan
CleanupDryRun -> do liftIO (LBS.hPut stdout plan)
return LBS.empty
mapM_ (performPlanLine envOverride)
(reverse (filter filterPlanLine (lines (LBS.unpack plan'))))
allImageHashesOut <- runDocker ["images","-aq","--no-trunc"]
liftIO (pruneDockerImagesLastUsed config (lines (decodeUtf8 allImageHashesOut)))
where
filterPlanLine line =
case line of
c:_ | isSpace c -> False
_ -> True
performPlanLine envOverride line =
case filter (not . null) (words (takeWhile (/= '#') line)) of
[] -> return ()
(c:_):t:v:_ ->
do args <- if | toUpper c == 'R' && t == imageStr ->
do $logInfo (concatT ["Removing image: '",v,"'"])
return ["rmi",v]
| toUpper c == 'R' && t == containerStr ->
do $logInfo (concatT ["Removing container: '",v,"'"])
return ["rm","-f",v]
| otherwise -> throwM (InvalidCleanupCommandException line)
e <- try (readDockerProcess envOverride args)
case e of
Left (ReadProcessException{}) ->
$logError (concatT ["Could not remove: '",v,"'"])
Left e' -> throwM e'
Right _ -> return ()
_ -> throwM (InvalidCleanupCommandException line)
parseImagesOut = Map.fromListWith (++) . map parseImageRepo . drop 1 . lines . decodeUtf8
where parseImageRepo :: String -> (String, [String])
parseImageRepo line =
case words line of
repo:tag:hash:_
| repo == "<none>" -> (hash,[])
| tag == "<none>" -> (hash,[repo])
| otherwise -> (hash,[repo ++ ":" ++ tag])
_ -> throw (InvalidImagesOutputException line)
parseContainersOut = map parseContainer . drop 1 . lines . decodeUtf8
where parseContainer line =
case words line of
hash:image:rest -> (hash,(image,last rest))
_ -> throw (InvalidPSOutputException line)
buildPlan curTime
imagesLastUsed
imageRepos
danglingImageHashes
stoppedContainers
runningContainers
inspectMap =
do case dcAction opts of
CleanupInteractive ->
do buildStrLn
(concat
["# STACK DOCKER CLEANUP PLAN"
,"\n#"
,"\n# When you leave the editor, the lines in this plan will be processed."
,"\n#"
,"\n# Lines that begin with 'R' denote an image or container that will be."
,"\n# removed. You may change the first character to/from 'R' to remove/keep"
,"\n# and image or container that would otherwise be kept/removed."
,"\n#"
,"\n# To cancel the cleanup, delete all lines in this file."
,"\n#"
,"\n# By default, the following images/containers will be removed:"
,"\n#"])
buildDefault dcRemoveKnownImagesLastUsedDaysAgo "Known images last used"
buildDefault dcRemoveUnknownImagesCreatedDaysAgo "Unknown images created"
buildDefault dcRemoveDanglingImagesCreatedDaysAgo "Dangling images created"
buildDefault dcRemoveStoppedContainersCreatedDaysAgo "Stopped containers created"
buildDefault dcRemoveRunningContainersCreatedDaysAgo "Running containers created"
buildStrLn
(concat
["#"
,"\n# The default plan can be adjusted using command-line arguments."
,"\n# Run '" ++ unwords [stackProgName, dockerCmdName, dockerCleanupCmdName] ++
" --help' for details."
,"\n#"])
_ -> buildStrLn
(unlines
["# Lines that begin with 'R' denote an image or container that will be."
,"# removed."])
buildSection "KNOWN IMAGES (pulled/used by stack)"
imagesLastUsed
buildKnownImage
buildSection "UNKNOWN IMAGES (not managed by stack)"
(sortCreated (Map.toList (foldl' (\m (h,_) -> Map.delete h m)
imageRepos
imagesLastUsed)))
buildUnknownImage
buildSection "DANGLING IMAGES (no named references and not depended on by other images)"
(sortCreated (map (,()) danglingImageHashes))
buildDanglingImage
buildSection "STOPPED CONTAINERS"
(sortCreated stoppedContainers)
(buildContainer (dcRemoveStoppedContainersCreatedDaysAgo opts))
buildSection "RUNNING CONTAINERS"
(sortCreated runningContainers)
(buildContainer (dcRemoveRunningContainersCreatedDaysAgo opts))
where
buildDefault accessor description =
case accessor opts of
Just days -> buildStrLn ("# - " ++ description ++ " at least " ++ showDays days ++ ".")
Nothing -> return ()
sortCreated l =
reverse (sortBy (\(_,_,a) (_,_,b) -> compare a b)
(catMaybes (map (\(h,r) -> fmap (\ii -> (h,r,iiCreated ii))
(Map.lookup h inspectMap))
l)))
buildSection sectionHead items itemBuilder =
do let (anyWrote,b) = runWriter (forM items itemBuilder)
when (or anyWrote) $
do buildSectionHead sectionHead
tell b
buildKnownImage (imageHash,lastUsedProjects) =
case Map.lookup imageHash imageRepos of
Just repos@(_:_) ->
do case lastUsedProjects of
(l,_):_ -> forM_ repos (buildImageTime (dcRemoveKnownImagesLastUsedDaysAgo opts) l)
_ -> forM_ repos buildKeepImage
forM_ lastUsedProjects buildProject
buildInspect imageHash
return True
_ -> return False
buildUnknownImage (hash, repos, created) =
case repos of
[] -> return False
_ -> do forM_ repos (buildImageTime (dcRemoveUnknownImagesCreatedDaysAgo opts) created)
buildInspect hash
return True
buildDanglingImage (hash, (), created) =
do buildImageTime (dcRemoveDanglingImagesCreatedDaysAgo opts) created hash
buildInspect hash
return True
buildContainer removeAge (hash,(image,name),created) =
do let disp = name ++ " (image: " ++ image ++ ")"
buildTime containerStr removeAge created disp
buildInspect hash
return True
buildProject (lastUsedTime, projectPath) =
buildInfo ("Last used " ++
showDaysAgo lastUsedTime ++
" in " ++
projectPath)
buildInspect hash =
case Map.lookup hash inspectMap of
Just (Inspect{iiCreated,iiVirtualSize}) ->
buildInfo ("Created " ++
showDaysAgo iiCreated ++
maybe ""
(\s -> " (size: " ++
printf "%g" (fromIntegral s / 1024.0 / 1024.0 :: Float) ++
"M)")
iiVirtualSize)
Nothing -> return ()
showDays days =
case days of
0 -> "today"
1 -> "yesterday"
n -> show n ++ " days ago"
showDaysAgo oldTime = showDays (daysAgo oldTime)
daysAgo oldTime =
let ZonedTime (LocalTime today _) zone = curTime
LocalTime oldDay _ = utcToLocalTime zone oldTime
in diffDays today oldDay
buildImageTime = buildTime imageStr
buildTime t removeAge time disp =
case removeAge of
Just d | daysAgo time >= d -> buildStrLn ("R " ++ t ++ " " ++ disp)
_ -> buildKeep t disp
buildKeep t d = buildStrLn (" " ++ t ++ " " ++ d)
buildKeepImage = buildKeep imageStr
buildSectionHead s = buildStrLn ("\n#\n# " ++ s ++ "\n#\n")
buildInfo = buildStrLn . (" # " ++)
buildStrLn l = do buildStr l
tell (charUtf8 '\n')
buildStr = tell . stringUtf8
imageStr = "image"
containerStr = "container"
-- | Inspect Docker image or container.
inspect :: (MonadIO m,MonadThrow m,MonadLogger m,MonadBaseControl IO m,MonadCatch m)
=> EnvOverride -> String -> m (Maybe Inspect)
inspect envOverride image =
do results <- inspects envOverride [image]
case Map.toList results of
[] -> return Nothing
[(_,i)] -> return (Just i)
_ -> throwM (InvalidInspectOutputException "expect a single result")
-- | Inspect multiple Docker images and/or containers.
inspects :: (MonadIO m, MonadThrow m, MonadLogger m, MonadBaseControl IO m, MonadCatch m)
=> EnvOverride -> [String] -> m (Map String Inspect)
inspects _ [] = return Map.empty
inspects envOverride images =
do maybeInspectOut <-
try (readDockerProcess envOverride ("inspect" : images))
case maybeInspectOut of
Right inspectOut ->
-- filtering with 'isAscii' to workaround @docker inspect@ output containing invalid UTF-8
case eitherDecode (LBS.pack (filter isAscii (decodeUtf8 inspectOut))) of
Left msg -> throwM (InvalidInspectOutputException msg)
Right results -> return (Map.fromList (map (\r -> (iiId r,r)) results))
Left (ReadProcessException{}) -> return Map.empty
Left e -> throwM e
-- | Pull latest version of configured Docker image from registry.
pull :: M env m => m ()
pull =
do config <- asks getConfig
let docker = configDocker config
envOverride <- getEnvOverride (configPlatform config)
checkDockerVersion envOverride docker
pullImage envOverride docker (dockerImage docker)
-- | Pull Docker image from registry.
pullImage :: (MonadLogger m,MonadIO m,MonadThrow m,MonadBaseControl IO m)
=> EnvOverride -> DockerOpts -> String -> m ()
pullImage envOverride docker image =
do $logInfo (concatT ["Pulling image from registry: '",image,"'"])
when (dockerRegistryLogin docker)
(do $logInfo "You may need to log in."
callProcess
Nothing
envOverride
"docker"
(concat
[["login"]
,maybe [] (\n -> ["--username=" ++ n]) (dockerRegistryUsername docker)
,maybe [] (\p -> ["--password=" ++ p]) (dockerRegistryPassword docker)
,[takeWhile (/= '/') image]]))
e <- try (callProcess Nothing envOverride "docker" ["pull",image])
case e of
Left (ProcessExitedUnsuccessfully _ _) -> throwM (PullFailedException image)
Right () -> return ()
-- | Check docker version (throws exception if incorrect)
checkDockerVersion
:: (MonadIO m, MonadThrow m, MonadLogger m, MonadBaseControl IO m, MonadCatch m)
=> EnvOverride -> DockerOpts -> m ()
checkDockerVersion envOverride docker =
do dockerExists <- doesExecutableExist envOverride "docker"
unless dockerExists (throwM DockerNotInstalledException)
dockerVersionOut <- readDockerProcess envOverride ["--version"]
case words (decodeUtf8 dockerVersionOut) of
(_:_:v:_) -> do
case parseVersionFromString (dropWhileEnd (not . isDigit) v) of
Just v'
| v' < minimumDockerVersion ->
throwM (DockerTooOldException minimumDockerVersion v')
| v' `elem` prohibitedDockerVersions ->
throwM (DockerVersionProhibitedException prohibitedDockerVersions v')
| not (v' `withinRange` dockerRequireDockerVersion docker) ->
(throwM (BadDockerVersionException (dockerRequireDockerVersion docker) v'))
| otherwise ->
return ()
_ -> throwM InvalidVersionOutputException
_ -> throwM InvalidVersionOutputException
where minimumDockerVersion = $(mkVersion "1.3.0")
prohibitedDockerVersions = [$(mkVersion "1.2.0")]
-- | Remove the project's Docker sandbox.
reset :: (MonadIO m) => Maybe (Path Abs Dir) -> Bool -> m ()
reset maybeProjectRoot keepHome =
liftIO (removeDirectoryContents
(projectDockerSandboxDir projectRoot)
[homeDirName | keepHome]
[])
where projectRoot = fromMaybeProjectRoot maybeProjectRoot
-- | Remove the contents of a directory, without removing the directory itself.
-- This is used instead of 'FS.removeTree' to clear bind-mounted directories, since
-- removing the root of the bind-mount won't work.
removeDirectoryContents :: Path Abs Dir -- ^ Directory to remove contents of
-> [Path Rel Dir] -- ^ Top-level directory names to exclude from removal
-> [Path Rel File] -- ^ Top-level file names to exclude from removal
-> IO ()
removeDirectoryContents path excludeDirs excludeFiles =
do isRootDir <- dirExists path
when isRootDir
(do (lsd,lsf) <- listDirectory path
forM_ lsd
(\d -> unless (dirname d `elem` excludeDirs)
(removeTree d))
forM_ lsf
(\f -> unless (filename f `elem` excludeFiles)
(removeFile f)))
-- | Produce a strict 'S.ByteString' from the stdout of a
-- process. Throws a 'ReadProcessException' exception if the
-- process fails. Logs process's stderr using @$logError@.
readDockerProcess
:: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m)
=> EnvOverride -> [String] -> m BS.ByteString
readDockerProcess envOverride args =
readProcessStdout Nothing envOverride "docker" args
-- | Subdirectories of the home directory to sandbox between GHC/Stackage versions.
sandboxedHomeSubdirectories :: [Path Rel Dir]
sandboxedHomeSubdirectories =
[$(mkRelDir ".ghc/")
,$(mkRelDir ".cabal/")
,$(mkRelDir ".ghcjs/")]
-- | Name of home directory within docker sandbox.
homeDirName :: Path Rel Dir
homeDirName = $(mkRelDir "_home/")
-- | Convenience function to decode ByteString to String.
decodeUtf8 :: BS.ByteString -> String
decodeUtf8 bs = T.unpack (T.decodeUtf8 bs)
-- | Convenience function constructing message for @$log*@.
concatT :: [String] -> Text
concatT = T.pack . concat
-- | Fail with friendly error if project root not set.
fromMaybeProjectRoot :: Maybe (Path Abs Dir) -> Path Abs Dir
fromMaybeProjectRoot = fromMaybe (throw CannotDetermineProjectRootException)
-- | Environment variable that contains the sandbox ID.
sandboxIDEnvVar :: String
sandboxIDEnvVar = "DOCKER_SANDBOX_ID"
-- | Environment variable used to indicate stack is running in container.
inContainerEnvVar :: String
inContainerEnvVar = concat [map toUpper stackProgName,"_IN_CONTAINER"]
-- | Command-line argument for "docker"
dockerCmdName :: String
dockerCmdName = "docker"
-- | Command-line argument for @docker pull@.
dockerPullCmdName :: String
dockerPullCmdName = "pull"
-- | Command-line argument for @docker cleanup@.
dockerCleanupCmdName :: String
dockerCleanupCmdName = "cleanup"
-- | Command-line option for @--internal-re-exec@.
reExecArgName :: String
reExecArgName = "internal-re-exec-version"
-- | Options for 'cleanup'.
data CleanupOpts = CleanupOpts
{ dcAction :: !CleanupAction
, dcRemoveKnownImagesLastUsedDaysAgo :: !(Maybe Integer)
, dcRemoveUnknownImagesCreatedDaysAgo :: !(Maybe Integer)
, dcRemoveDanglingImagesCreatedDaysAgo :: !(Maybe Integer)
, dcRemoveStoppedContainersCreatedDaysAgo :: !(Maybe Integer)
, dcRemoveRunningContainersCreatedDaysAgo :: !(Maybe Integer) }
deriving (Show)
-- | Cleanup action.
data CleanupAction = CleanupInteractive
| CleanupImmediate
| CleanupDryRun
deriving (Show)
-- | Parsed result of @docker inspect@.
data Inspect = Inspect
{iiConfig :: ImageConfig
,iiCreated :: UTCTime
,iiId :: String
,iiVirtualSize :: Maybe Integer }
deriving (Show)
-- | Parse @docker inspect@ output.
instance FromJSON Inspect where
parseJSON v =
do o <- parseJSON v
(Inspect <$> o .: T.pack "Config"
<*> o .: T.pack "Created"
<*> o .: T.pack "Id"
<*> o .:? T.pack "VirtualSize")
-- | Parsed @Config@ section of @docker inspect@ output.
data ImageConfig = ImageConfig
{icEnv :: [String]}
deriving (Show)
-- | Parse @Config@ section of @docker inspect@ output.
instance FromJSON ImageConfig where
parseJSON v =
do o <- parseJSON v
ImageConfig <$> o .:? T.pack "Env" .!= []
-- | Exceptions thrown by Stack.Docker.
data StackDockerException
= DockerMustBeEnabledException
-- ^ Docker must be enabled to use the command.
| OnlyOnHostException
-- ^ Command must be run on host OS (not in a container).
| InspectFailedException String
-- ^ @docker inspect@ failed.
| NotPulledException String
-- ^ Image does not exist.
| InvalidCleanupCommandException String
-- ^ Input to @docker cleanup@ has invalid command.
| InvalidImagesOutputException String
-- ^ Invalid output from @docker images@.
| InvalidPSOutputException String
-- ^ Invalid output from @docker ps@.
| InvalidInspectOutputException String
-- ^ Invalid output from @docker inspect@.
| PullFailedException String
-- ^ Could not pull a Docker image.
| DockerTooOldException Version Version
-- ^ Installed version of @docker@ below minimum version.
| DockerVersionProhibitedException [Version] Version
-- ^ Installed version of @docker@ is prohibited.
| BadDockerVersionException VersionRange Version
-- ^ Installed version of @docker@ is out of range specified in config file.
| InvalidVersionOutputException
-- ^ Invalid output from @docker --version@.
| HostStackTooOldException Version (Maybe Version)
-- ^ Version of @stack@ on host is too old for version in image.
| ContainerStackTooOldException Version Version
-- ^ Version of @stack@ in container/image is too old for version on host.
| CannotDetermineProjectRootException
-- ^ Can't determine the project root (where to put docker sandbox).
| DockerNotInstalledException
-- ^ @docker --version@ failed.
| UnsupportedStackExeHostPlatformException
-- ^ Using host stack-exe on unsupported platform.
deriving (Typeable)
-- | Exception instance for StackDockerException.
instance Exception StackDockerException
-- | Show instance for StackDockerException.
instance Show StackDockerException where
show DockerMustBeEnabledException =
concat ["Docker must be enabled in your configuration file to use this command."]
show OnlyOnHostException =
"This command must be run on host OS (not in a Docker container)."
show (InspectFailedException image) =
concat ["'docker inspect' failed for image after pull: ",image,"."]
show (NotPulledException image) =
concat ["The Docker image referenced by your configuration file"
," has not\nbeen downloaded:\n "
,image
,"\n\nRun '"
,unwords [stackProgName, dockerCmdName, dockerPullCmdName]
,"' to download it, then try again."]
show (InvalidCleanupCommandException line) =
concat ["Invalid line in cleanup commands: '",line,"'."]
show (InvalidImagesOutputException line) =
concat ["Invalid 'docker images' output line: '",line,"'."]
show (InvalidPSOutputException line) =
concat ["Invalid 'docker ps' output line: '",line,"'."]
show (InvalidInspectOutputException msg) =
concat ["Invalid 'docker inspect' output: ",msg,"."]
show (PullFailedException image) =
concat ["Could not pull Docker image:\n "
,image
,"\nThere may not be an image on the registry for your resolver's LTS version in\n"
,"your configuration file."]
show (DockerTooOldException minVersion haveVersion) =
concat ["Minimum docker version '"
,versionString minVersion
,"' is required by "
,stackProgName
," (you have '"
,versionString haveVersion
,"')."]
show (DockerVersionProhibitedException prohibitedVersions haveVersion) =
concat ["These Docker versions are incompatible with "
,stackProgName
," (you have '"
,versionString haveVersion
,"'): "
,intercalate ", " (map versionString prohibitedVersions)
,"."]
show (BadDockerVersionException requiredRange haveVersion) =
concat ["The version of 'docker' you are using ("
,show haveVersion
,") is outside the required\n"
,"version range specified in stack.yaml ("
,T.unpack (versionRangeText requiredRange)
,")."]
show InvalidVersionOutputException =
"Cannot get Docker version (invalid 'docker --version' output)."
show (HostStackTooOldException minVersion (Just hostVersion)) =
concat ["The host's version of '"
,stackProgName
,"' is too old for this Docker image.\nVersion "
,versionString minVersion
," is required; you have "
,versionString hostVersion
,"."]
show (HostStackTooOldException minVersion Nothing) =
concat ["The host's version of '"
,stackProgName
,"' is too old.\nVersion "
,versionString minVersion
," is required."]
show (ContainerStackTooOldException requiredVersion containerVersion) =
concat ["The Docker container's version of '"
,stackProgName
,"' is too old.\nVersion "
,versionString requiredVersion
," is required; the container has "
,versionString containerVersion
,"."]
show CannotDetermineProjectRootException =
"Cannot determine project root directory for Docker sandbox."
show DockerNotInstalledException =
"Cannot find 'docker' in PATH. Is Docker installed?"
show UnsupportedStackExeHostPlatformException = concat
[ "Using host's "
, stackProgName
, " executable in Docker container is only supported on "
, display dockerContainerPlatform
, " platform" ]
-- | Platform that Docker containers run
dockerContainerPlatform :: Platform
dockerContainerPlatform = Platform X86_64 Linux
type M env m = (MonadIO m,MonadReader env m,MonadLogger m,MonadBaseControl IO m,MonadCatch m
,HasConfig env,HasTerminal env,HasReExec env,HasHttpManager env,MonadMask m)
| mathhun/stack | src/Stack/Docker.hs | bsd-3-clause | 42,102 | 0 | 28 | 13,556 | 9,036 | 4,653 | 4,383 | 822 | 21 |
-- 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 GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.HR.Rules
( rules ) where
import Data.Maybe
import Data.String
import Data.Text (Text)
import Prelude
import qualified Data.Text as Text
import Duckling.Dimensions.Types
import Duckling.Numeral.Helpers
import Duckling.Numeral.Types (NumeralData (..))
import Duckling.Regex.Types
import Duckling.Types
import qualified Duckling.Numeral.Types as TNumeral
ruleNumbersPrefixWithNegativeOrMinus :: Rule
ruleNumbersPrefixWithNegativeOrMinus = Rule
{ name = "numbers prefix with -, negative or minus"
, pattern =
[ regex "-|minus|negativ"
, dimension Numeral
]
, prod = \tokens -> case tokens of
(_:Token Numeral nd:_) -> double (TNumeral.value nd * (-1))
_ -> Nothing
}
ruleIntegerNumeric :: Rule
ruleIntegerNumeric = Rule
{ name = "integer (numeric)"
, pattern =
[ regex "(\\d{1,18})"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> do
v <- toInteger <$> parseInt match
integer v
_ -> Nothing
}
ruleFew :: Rule
ruleFew = Rule
{ name = "few"
, pattern =
[ regex "nekoliko"
]
, prod = \_ -> integer 3
}
ruleTen :: Rule
ruleTen = Rule
{ name = "ten"
, pattern =
[ regex "deset|cener"
]
, prod = \_ -> integer 10 >>= withGrain 1
}
ruleDecimalWithThousandsSeparator :: Rule
ruleDecimalWithThousandsSeparator = Rule
{ name = "decimal with thousands separator"
, pattern =
[ regex "(\\d+(\\.\\d\\d\\d)+\\,\\d+)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
let dot = Text.singleton '.'
comma = Text.singleton ','
fmt = Text.replace comma dot $ Text.replace dot Text.empty match
in parseDouble fmt >>= double
_ -> Nothing
}
ruleDecimalNumber :: Rule
ruleDecimalNumber = Rule
{ name = "decimal number"
, pattern =
[ regex "(\\d*,\\d+)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):
_) -> parseDecimal False match
_ -> Nothing
}
ruleInteger3 :: Rule
ruleInteger3 = Rule
{ name = "integer (100..900)"
, pattern =
[ regex "(sto|dvjest(o|a)|tristo|(c|\x010d)etiristo|petsto|(\x0161|s)esto|sedamsto|osamsto|devetsto)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"sto" -> integer 100
"dvjesta" -> integer 200
"dvjesto" -> integer 200
"tristo" -> integer 300
"cetiristo" -> integer 400
"\269etiristo" -> integer 400
"petsto" -> integer 500
"\353esto" -> integer 600
"sesto" -> integer 600
"sedamsto" -> integer 700
"osamsto" -> integer 800
"devetsto" -> integer 900
_ -> Nothing
_ -> Nothing
}
ruleSingle :: Rule
ruleSingle = Rule
{ name = "single"
, pattern =
[ regex "sam"
]
, prod = \_ -> integer 1 >>= withGrain 1
}
rulePowersOfTen :: Rule
rulePowersOfTen = Rule
{ name = "powers of tens"
, pattern =
[ regex "(stotin(u|a|e)|tisu(c|\x0107)(a|u|e)|milij(u|o)na?)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"stotinu" -> double 1e2 >>= withGrain 2 >>= withMultipliable
"stotina" -> double 1e2 >>= withGrain 2 >>= withMultipliable
"stotine" -> double 1e2 >>= withGrain 2 >>= withMultipliable
"tisuca" -> double 1e3 >>= withGrain 3 >>= withMultipliable
"tisucu" -> double 1e3 >>= withGrain 3 >>= withMultipliable
"tisuce" -> double 1e3 >>= withGrain 3 >>= withMultipliable
"tisu\263a" -> double 1e3 >>= withGrain 3 >>= withMultipliable
"tisu\263u" -> double 1e3 >>= withGrain 3 >>= withMultipliable
"tisu\263e" -> double 1e3 >>= withGrain 3 >>= withMultipliable
"milijun" -> double 1e6 >>= withGrain 6 >>= withMultipliable
"milijuna" -> double 1e6 >>= withGrain 6 >>= withMultipliable
"milijon" -> double 1e6 >>= withGrain 6 >>= withMultipliable
"milijona" -> double 1e6 >>= withGrain 6 >>= withMultipliable
_ -> Nothing
_ -> Nothing
}
ruleNumbersI :: Rule
ruleNumbersI = Rule
{ name = "numbers i"
, pattern =
[ oneOf [70, 20, 60, 50, 40, 90, 30, 80]
, regex "i"
, numberBetween 1 10
]
, prod = \tokens -> case tokens of
(Token Numeral (NumeralData {TNumeral.value = v1}):
_:
Token Numeral (NumeralData {TNumeral.value = v2}):
_) -> double $ v1 + v2
_ -> Nothing
}
ruleSum :: Rule
ruleSum = Rule
{ name = "intersect"
, pattern =
[ numberWith (fromMaybe 0 . TNumeral.grain) (>1)
, numberWith TNumeral.multipliable not
]
, prod = \tokens -> case tokens of
(Token Numeral (NumeralData {TNumeral.value = val1, TNumeral.grain = Just g}):
Token Numeral (NumeralData {TNumeral.value = val2}):
_) | (10 ** fromIntegral g) > val2 -> double $ val1 + val2
_ -> Nothing
}
ruleNumbersSuffixesKMG :: Rule
ruleNumbersSuffixesKMG = Rule
{ name = "numbers suffixes (K, M, G)"
, pattern =
[ dimension Numeral
, regex "([kmg])(?=[\\W\\$\x20ac]|$)"
]
, prod = \tokens -> case tokens of
(Token Numeral (NumeralData {TNumeral.value = v}):
Token RegexMatch (GroupMatch (match:_)):
_) -> case Text.toLower match of
"k" -> double $ v * 1e3
"m" -> double $ v * 1e6
"g" -> double $ v * 1e9
_ -> Nothing
_ -> Nothing
}
ruleAPair :: Rule
ruleAPair = Rule
{ name = "a pair"
, pattern =
[ regex "par"
]
, prod = \_ -> integer 2 >>= withGrain 1
}
ruleDozen :: Rule
ruleDozen = Rule
{ name = "dozen"
, pattern =
[ regex "tucet?"
]
, prod = \_ -> integer 12 >>= withGrain 1
}
ruleInteger :: Rule
ruleInteger = Rule
{ name = "integer (0..19)"
, pattern =
[ regex "(ni(s|\x0161)ta|ni(s|\x0161)tica|nula|jedanaest|dvanaest|trinaest|jeda?n(a|u|o(ga?)?)?|dv(i?je)?(a|o)?(ma)?|tri(ma)?|(\x010d|c)etiri|(\x010d|c)etrnaest|petnaest|pet|(s|\x0161)esnaest|(\x0161|s)est|sedamnaest|sedam|osamnaest|osam|devetnaest|devet)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"ni\353ta" -> integer 0
"ni\353tica" -> integer 0
"nistica" -> integer 0
"nista" -> integer 0
"nula" -> integer 0
"jednoga" -> integer 1
"jedna" -> integer 1
"jednog" -> integer 1
"jednu" -> integer 1
"jedan" -> integer 1
"dvoma" -> integer 2
"dvije" -> integer 2
"dvje" -> integer 2
"dva" -> integer 2
"dvama" -> integer 2
"trima" -> integer 3
"tri" -> integer 3
"\269etiri" -> integer 4
"cetiri" -> integer 4
"pet" -> integer 5
"\353est" -> integer 6
"sedam" -> integer 7
"osam" -> integer 8
"devet" -> integer 9
"jedanaest" -> integer 11
"dvanaest" -> integer 12
"trinaest" -> integer 13
"cetrnaest" -> integer 14
"\269etrnaest" -> integer 14
"petnaest" -> integer 15
"\353esnaest" -> integer 16
"sesnaest" -> integer 16
"sedamnaest" -> integer 17
"osamnaest" -> integer 18
"devetnaest" -> integer 19
_ -> Nothing
_ -> Nothing
}
ruleInteger4 :: Rule
ruleInteger4 = Rule
{ name = "integer 21..99"
, pattern =
[ oneOf [70, 20, 60, 50, 40, 90, 30, 80]
, numberBetween 1 10
]
, prod = \tokens -> case tokens of
(Token Numeral (NumeralData {TNumeral.value = v1}):
Token Numeral (NumeralData {TNumeral.value = v2}):
_) -> double $ v1 + v2
_ -> Nothing
}
ruleInteger2 :: Rule
ruleInteger2 = Rule
{ name = "integer (20..90)"
, pattern =
[ regex "(dvadeset|trideset|(c|\x010d)etrdeset|pedeset|(\x0161|s)esdeset|sedamdeset|osamdeset|devedeset)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"dvadeset" -> integer 20
"trideset" -> integer 30
"cetrdeset" -> integer 40
"\269etrdeset" -> integer 40
"pedeset" -> integer 50
"sesdeset" -> integer 60
"\353esdeset" -> integer 60
"sedamdeset" -> integer 70
"osamdeset" -> integer 80
"devedeset" -> integer 90
_ -> Nothing
_ -> Nothing
}
ruleNumbers :: Rule
ruleNumbers = Rule
{ name = "numbers 100..999"
, pattern =
[ numberBetween 1 10
, numberWith TNumeral.value (== 100)
, numberBetween 0 100
]
, prod = \tokens -> case tokens of
(Token Numeral (NumeralData {TNumeral.value = v1}):
_:
Token Numeral (NumeralData {TNumeral.value = v2}):
_) -> double $ 100 * v1 + v2
_ -> Nothing
}
ruleNumberDotNumber :: Rule
ruleNumberDotNumber = Rule
{ name = "number dot number"
, pattern =
[ dimension Numeral
, regex "cijela|to(c|\x010d)ka|zarez"
, numberWith TNumeral.grain isNothing
]
, prod = \tokens -> case tokens of
(Token Numeral (NumeralData {TNumeral.value = v1}):
_:
Token Numeral (NumeralData {TNumeral.value = v2}):
_) -> double $ v1 + decimalsToDouble v2
_ -> Nothing
}
ruleIntegerWithThousandsSeparator :: Rule
ruleIntegerWithThousandsSeparator = Rule
{ name = "integer with thousands separator ."
, pattern =
[ regex "(\\d{1,3}(\\.\\d\\d\\d){1,5})"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):
_) -> let fmt = Text.replace (Text.singleton '.') Text.empty match
in parseDouble fmt >>= double
_ -> Nothing
}
ruleMultiply :: Rule
ruleMultiply = Rule
{ name = "compose by multiplication"
, pattern =
[ dimension Numeral
, numberWith TNumeral.multipliable id
]
, prod = \tokens -> case tokens of
(token1:token2:_) -> multiply token1 token2
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleAPair
, ruleDecimalNumber
, ruleDecimalWithThousandsSeparator
, ruleDozen
, ruleFew
, ruleInteger
, ruleInteger2
, ruleInteger3
, ruleInteger4 , ruleIntegerNumeric
, ruleIntegerWithThousandsSeparator
, ruleMultiply
, ruleNumberDotNumber
, ruleNumbers
, ruleNumbersI
, ruleNumbersPrefixWithNegativeOrMinus
, ruleNumbersSuffixesKMG
, rulePowersOfTen
, ruleSingle
, ruleSum
, ruleTen
]
| rfranek/duckling | Duckling/Numeral/HR/Rules.hs | bsd-3-clause | 10,850 | 0 | 19 | 2,924 | 3,142 | 1,664 | 1,478 | 308 | 37 |
{-# LANGUAGE NamedFieldPuns #-}
{-
** *********************************************************************
* *
* (c) Kathleen Fisher <kathleen.fisher@gmail.com> *
* John Launchbury <john.launchbury@gmail.com> *
* *
************************************************************************
-}
module Language.Pads.PadsParser where
-- These are the combinators used to build PADS parsers
import qualified Language.Pads.Source as S
import Language.Pads.Errors
import Language.Pads.MetaData
import Language.Pads.RegExp
import Data.Char
import Control.Monad
import Control.Applicative (Applicative(..))
parseStringInput :: PadsParser a -> String -> (a,String)
parseStringInput pp cs = case pp # (S.padsSourceFromString cs) of
((r,rest),b) -> (r, S.padsSourceToString rest)
parseStringInputWithDisc :: S.RecordDiscipline -> PadsParser a -> String -> (a,String)
parseStringInputWithDisc d pp cs = case pp # (S.padsSourceFromStringWithDisc d cs) of
((r,rest),b) -> (r, S.padsSourceToString rest)
parseByteStringInput :: PadsParser a -> S.RawStream -> (a, S.RawStream)
parseByteStringInput pp cs = case pp # (S.padsSourceFromByteString cs) of
((r,rest),b) -> (r, S.padsSourceToByteString rest)
parseByteStringInputWithDisc :: S.RecordDiscipline -> PadsParser a -> S.RawStream -> (a, S.RawStream)
parseByteStringInputWithDisc d pp cs = case pp # (S.padsSourceFromByteStringWithDisc d cs) of
((r,rest),b) -> (r, S.padsSourceToByteString rest)
parseFileInput :: PadsParser a -> FilePath -> IO a
parseFileInput pp file = do
{ source <- S.padsSourceFromFile file
; case pp # source of ((r,rest),b) -> return r
}
parseFileInputWithDisc :: S.RecordDiscipline -> PadsParser a -> FilePath -> IO a
parseFileInputWithDisc d pp file = do
{ source <- S.padsSourceFromFileWithDisc d file
; case pp # source of ((r,rest),b) -> return r
}
------------------------------------------------------------------
{- Parsing Monad -}
newtype PadsParser a = PadsParser { (#) :: S.Source -> Result (a,S.Source) }
type Result a = (a,Bool)
instance Functor PadsParser where
fmap f p = PadsParser $ \bs -> let ((x,bs'),b) = p # bs in
((f x, bs'),b)
instance Applicative PadsParser where
pure = return
(<*>) = ap
-- if any results on the way are bad, then the whole thing will be bad
instance Monad PadsParser where
return r = PadsParser $ \bs -> ((r,bs), True)
p >>= f = PadsParser $ \bs -> let ((v,bs'),b) = p # bs
((w,bs''),b') = f v # bs'
in ((w,bs''), b && b')
badReturn r = PadsParser $ \bs -> ((r,bs), False)
mdReturn (rep,md) = PadsParser $
\bs -> (((rep,md),bs), numErrors (get_md_header md) == 0)
returnClean :: t -> PadsParser (t, Base_md)
returnClean x = return (x, cleanBasePD)
returnError :: t -> ErrMsg -> PadsParser (t, Base_md)
returnError x err = do loc <- getLoc
badReturn (x, mkErrBasePDfromLoc err loc)
infixl 5 =@=, =@
p =@= q = do {(f,g) <- p; (rep,md) <- q; return (f rep, g md) }
p =@ q = do {(f,g) <- p; (rep,md) <- q; return (f, g md) }
--------------------------
-- Source manipulation functions
queryP :: (S.Source -> a) -> PadsParser a
queryP f = PadsParser $ \bs -> ((f bs,bs), True)
primPads :: (S.Source -> (a,S.Source)) -> PadsParser a
primPads f = PadsParser $ \bs -> ((f bs), True)
liftStoP :: (S.Source -> Maybe (a,S.Source)) -> a -> PadsParser a
liftStoP f def = PadsParser $ \bs ->
case f bs of
Nothing -> ((def,bs), False)
Just (v,bs') -> ((v,bs'), True)
replaceSource :: S.Source -> Result (a,S.Source) -> Result (a,S.Source)
replaceSource bs ((v,_),b) = ((v,bs),b)
-------------------------
-- The monad is non-backtracking. The only choice point is at ChoiceP
choiceP :: [PadsParser a] -> PadsParser a
choiceP ps = foldr1 (<||>) ps
(<||>) :: PadsParser a -> PadsParser a -> PadsParser a
p <||> q = PadsParser $ \bs -> (p # bs) <++> (q # bs)
(<++>) :: Result a -> Result a -> Result a
(r, True) <++> _ = (r, True)
(r1, False) <++> r2 = r2 -- A number of functions rely on this being r2
-----------------------
parseTry :: PadsParser a -> PadsParser a
parseTry p = PadsParser $ \bs -> replaceSource bs (p # bs)
-------------
parseConstraint :: PadsMD md =>
PadsParser(rep,md) -> (rep -> md -> Bool) -> PadsParser(rep, md)
parseConstraint p pred = do
(rep,md) <- p
mdReturn (rep, replace_md_header md (constraintReport (pred rep md) md))
constraintReport isGood md = Base_md {numErrors = totErrors, errInfo = errors}
where
Base_md {numErrors, errInfo} = get_md_header md
totErrors = if isGood then numErrors else numErrors + 1
errors = if totErrors == 0 then Nothing else
Just(ErrInfo {msg = if isGood then UnderlyingTypedefFail
else PredicateFailure,
position = join $ fmap position errInfo})
-------------------------------------------------
parseTransform :: PadsMD dmd =>
PadsParser (sr,smd) -> (S.Pos->(sr,smd)->(dr,dmd)) -> PadsParser (dr,dmd)
parseTransform sParser transform = do
{ begin_loc <- getLoc
; src_result <- sParser
; end_loc <- getLoc
; let src_pos = S.locsToPos begin_loc end_loc
; return (transform src_pos src_result)
}
-------------------------------------------------
parsePartition :: PadsMD md =>
PadsParser(rep,md) -> S.RecordDiscipline -> PadsParser(rep, md)
parsePartition p newDisc = do
{ oldDisc <- queryP S.getRecordDiscipline
; primPads (S.setRecordDiscipline newDisc)
; x <- p
; primPads (S.setRecordDiscipline oldDisc)
; return x
}
-------------------------------------------------
parseListNoSepNoTerm :: PadsMD md =>
PadsParser (rep,md) -> PadsParser ([rep], (Base_md, [md]))
parseListNoSepNoTerm p = listReport (parseMany p)
parseListSepNoTerm :: (PadsMD md, PadsMD mdSep) =>
PadsParser (repSep,mdSep) -> PadsParser(rep, md) -> PadsParser ([rep], (Base_md, [md]))
parseListSepNoTerm sep p = listReport (parseManySep sep p)
parseListNoSepLength :: (PadsMD md) =>
Int -> PadsParser(rep, md) -> PadsParser ([rep], (Base_md, [md]))
parseListNoSepLength i p = listReport (parseCount i p)
parseListSepLength :: (PadsMD md, PadsMD mdSep) =>
PadsParser (repSep,mdSep) -> Int -> PadsParser(rep, md) -> PadsParser ([rep], (Base_md, [md]))
parseListSepLength sep n p = listReport (parseCountSep n sep p)
parseListNoSepTerm :: (PadsMD md, PadsMD mdTerm) =>
PadsParser (repTerm,mdTerm) -> PadsParser(rep, md) -> PadsParser ([rep], (Base_md, [md]))
parseListNoSepTerm term p = listReport (parseManyTerm term p)
parseListSepTerm :: (PadsMD md, PadsMD mdSep, PadsMD mdTerm) =>
PadsParser (repSep,mdSep) -> PadsParser (repTerm,mdTerm) ->
PadsParser(rep, md) -> PadsParser ([rep], (Base_md, [md]))
parseListSepTerm sep term p = listReport (parseManySepTerm sep term p)
listReport :: PadsMD b => PadsParser [(a, b)] -> PadsParser ([a], (Base_md, [b]))
listReport p = do
listElems <- p
let (reps, mds) = unzip listElems
let hmds = map get_md_header mds
return (reps, (mergeBaseMDs hmds, mds))
-----------------------------------
parseMany :: PadsMD md => PadsParser (rep,md) -> PadsParser [(rep,md)]
parseMany p = do (r,m) <- p
if (numErrors (get_md_header m) == 0)
then do { rms <- parseMany p
; return ((r,m) : rms)}
else badReturn []
<||> return []
parseManySep :: (PadsMD md, PadsMD mdSep) => PadsParser (repSep,mdSep) -> PadsParser(rep, md) -> PadsParser [(rep,md)]
parseManySep sep p = do { rm <- p
; rms <- parseManySep1 sep p
; return (rm : rms)
}
parseManySep1 :: (PadsMD md, PadsMD mdSep) => PadsParser (repSep,mdSep) -> PadsParser(rep, md) -> PadsParser [(rep,md)]
parseManySep1 sep p = do (r,m) <- sep
if (numErrors (get_md_header m) == 0)
then parseManySep sep p
else badReturn []
<||> return []
-----------------------------------
parseCount :: (PadsMD md) => Int -> PadsParser(rep, md) -> PadsParser [(rep,md)]
parseCount n p = sequence (replicate n p)
parseCountSep :: (PadsMD md) =>
Int -> PadsParser rmdSep -> PadsParser(rep, md) -> PadsParser [(rep,md)]
parseCountSep n sep p | n <= 0 = return []
parseCountSep n sep p = do
rm <- p
rms <- sequence $ replicate (n-1) (sep >> p)
return (rm:rms)
-----------------------------------
parseManyTerm :: (PadsMD md, PadsMD mdTerm) =>
PadsParser (repTerm,mdTerm) -> PadsParser(rep, md) -> PadsParser [(rep,md)]
parseManyTerm term p = (term >> return [])
<||> (ifEOFP >> return [])
<||> do { rm <- p
; rms <- parseManyTerm term p
; return (rm:rms) }
parseManySepTerm :: (PadsMD md, PadsMD mdSep, PadsMD mdTerm) =>
PadsParser (repSep,mdSep) -> PadsParser (repTerm,mdTerm) -> PadsParser(rep, md) -> PadsParser [(rep,md)]
parseManySepTerm sep term p = (term >> return [])
<||> (ifEOFP >> return [])
<||> scan
where
scan = do (rep, md) <- p
(terminated,junk) <- seekSep sep term
case junk of
[] -> if terminated then return [(rep,md)] else
do rms <- scan
return ((rep,md):rms)
_ -> do sepLoc <- getLoc
let report = junkReport md sepLoc junk
if terminated then
badReturn [(rep,report)]
else do
rms <- scan
badReturn ((rep,report) : rms)
seekSep sep term = (term >> return (True, []))
<||> (ifEOFP >> return (True, []))
<||> (sep >> return (False, []))
<||> do { b <- isEORP
; if b then badReturn (False, []) else
do { c <- takeHeadP
; (b,cs) <- seekSep sep term
; badReturn (b, c:cs)
}
}
junkReport md loc junk = replace_md_header md mergeMD
where
mdSep = mkErrBasePDfromLoc (ExtraStuffBeforeTy junk "seperator" ) loc
mergeMD = mergeBaseMDs [get_md_header md, mdSep]
-------------------------------------------------
getLoc :: PadsParser S.Loc
getLoc = queryP S.getSrcLoc
isEOFP, isEORP :: PadsParser Bool
isEOFP = queryP S.isEOF
isEORP = queryP S.isEOR
ifEOFP, ifEORP :: PadsParser ()
ifEOFP = do { b <- isEOFP; if b then return () else badReturn ()}
ifEORP = do { b <- isEORP; if b then return () else badReturn ()}
takeP :: Integral a => a -> PadsParser String
takeP n = primPads (S.take (fromInt n))
takeBytesP :: Integral a => a -> PadsParser S.RawStream
takeBytesP n = primPads (S.takeBytes (fromInt n))
fromInt :: (Integral a1, Num a) => a1 -> a
fromInt n = fromInteger $ toInteger n
-------------------------------------------------
peekHeadP :: PadsParser Char
peekHeadP = queryP S.head
takeHeadP :: PadsParser Char
takeHeadP = primPads S.takeHead
takeHeadStrP :: String -> PadsParser Bool
takeHeadStrP str = primPads (S.takeHeadStr str)
-- Return string is junk before found string
scanStrP :: String -> PadsParser (Maybe String)
scanStrP str = primPads (S.scanStr str)
regexMatchP ::RE -> PadsParser (Maybe String)
regexMatchP re = primPads (S.regexMatch re)
regexStopP :: RE -> PadsParser (Maybe String)
regexStopP re = primPads (S.regexStop re)
scanP :: Char -> PadsParser Bool
scanP c = primPads (\s -> let (f,r,e) = S.scanTo c s in (f,r))
getAllP :: PadsParser String
getAllP = primPads S.drainSource
getAllBinP :: PadsParser S.RawStream
getAllBinP = primPads S.rawSource
satisfy p = primPads loop
where loop s = if S.isEOF s || S.isEOR s then ([],s) else
let c = S.head s in
if p c then
let (xs,s') = loop (S.tail s) in
(c:xs, s')
else
([],s)
digitListToInt :: Bool -> [Char] -> Int
digitListToInt isNeg digits = if isNeg then negate raw else raw
where
raw = foldl (\a d ->10*a + digitToInt d) 0 digits
-------------------------
doLineBegin :: PadsParser ((), Base_md)
doLineBegin = do
rbegErr <- primPads S.srcLineBegin
case rbegErr of
Nothing -> returnClean ()
Just err -> returnError () (LineError err)
doLineEnd :: PadsParser ((), Base_md)
doLineEnd = do
rendErr <- primPads S.srcLineEnd
case rendErr of
Nothing -> returnClean ()
Just err -> returnError () (LineError err)
| athleens/pads-haskell | Language/Pads/PadsParser.hs | bsd-3-clause | 13,165 | 41 | 20 | 3,606 | 4,607 | 2,491 | 2,116 | 242 | 4 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.DrawBuffersBlend
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.DrawBuffersBlend (
-- * Extension Support
glGetARBDrawBuffersBlend,
gl_ARB_draw_buffers_blend,
-- * Functions
glBlendEquationSeparateiARB,
glBlendEquationiARB,
glBlendFuncSeparateiARB,
glBlendFunciARB
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Functions
| haskell-opengl/OpenGLRaw | src/Graphics/GL/ARB/DrawBuffersBlend.hs | bsd-3-clause | 706 | 0 | 4 | 95 | 53 | 40 | 13 | 9 | 0 |
module Data.Workshop.HashMap
(
HashMap(..)
, empty
, size
, isEmpty
, keys
, values
, contains
, put
, get
, delete
, clear
, dump
)
where
import qualified Data.Vector as V
import qualified Data.Hashable as H
type MapKey = String
data MapPair a = MapPair MapKey a
deriving (Eq,Show)
pairKey :: MapPair a -> MapKey
pairKey (MapPair k _) = k
pairValue :: MapPair a -> a
pairValue (MapPair _ v) = v
type Buckets a = (V.Vector (Maybe (MapPair a)))
data HashMap a = HashMap (Buckets a)
-- create an empty map
empty :: Eq a => HashMap a
empty = undefined
-- return the number of items in the map
size :: Eq a => HashMap a -> Int
size (HashMap b) = undefined
-- determine whether the map is empty
isEmpty :: Eq a => HashMap a -> Bool
isEmpty m = undefined
-- return all keys in the map
keys :: HashMap a -> [MapKey]
keys (HashMap b) = undefined
-- return all values in the map
values :: HashMap a -> [a]
values (HashMap b) = undefined
-- determine whether the map contains a key or not
contains :: HashMap a -> MapKey -> Bool
contains (HashMap b) k = undefined
-- insert a value into the map
put :: HashMap a -> MapKey -> a -> HashMap a
put (HashMap b) k value = undefined
-- retrieve a value from the map
get :: HashMap a -> MapKey -> Maybe a
get (HashMap b) k = undefined
-- delete a value from the map
delete :: HashMap a -> MapKey -> HashMap a
delete (HashMap b) k = undefined
-- clear all values from the map
clear :: Eq a => HashMap a -> HashMap a
clear _ = undefined
dump :: Show a => HashMap a -> String
dump (HashMap b) = undefined
| wiggly/workshop | src/Data/Workshop/HashMap.hs | bsd-3-clause | 1,675 | 0 | 10 | 453 | 547 | 293 | 254 | 47 | 1 |
module Data.MRF.Generic.ParamSet
( ParamCore (..)
, ParamSet (..)
, mkParamSet
) where
import qualified Data.Set as Set
import SGD
import Data.MRF.Generic.Feature
-- | TODO: c, x type variables superfluous.
class (Feature f c x, ParamCore p) => ParamSet p f c x | p -> f where
-- | Make parameter set from a list of (feature, value) pairs.
-- There should be no repetitions in the input list.
fromList :: [(f, Double)] -> p
phi :: p -> f -> Double
-- | Index of the given feature. It can be assumed, that
-- feature f is present in the parameter set.
featureToIx :: f -> p -> Int
-- | Make params from a list of features with initial weights set to 0.0.
-- There may be repetitions in the input list.
mkParamSet :: (Ord f, ParamSet p f c x) => [f] -> p
mkParamSet fs =
let fSet = Set.fromList fs
fs' = Set.toList fSet
vs = replicate (Set.size fSet) 0.0
in fromList (zip fs' vs)
| kawu/mrf | Data/MRF/Generic/ParamSet.hs | bsd-3-clause | 964 | 0 | 12 | 256 | 232 | 133 | 99 | -1 | -1 |
module Data.Deciparsec.Internal where
import Data.Monoid
import Data.Deciparsec.Internal.Types
import Data.Deciparsec.TokenSeq (TokenSeq)
import qualified Data.Deciparsec.TokenSeq as TS
ensure :: (Monad m, TokenSeq s t) => Int -> ParserT s u m s
ensure !n = ParserT $ \s0 i0 a0 m0 kf ks ->
if TS.length (unI i0) >= n then ks s0 i0 a0 m0 (unI i0)
else ensure' n s0 i0 a0 m0 kf ks
ensure' :: (Monad m, TokenSeq s t) =>
Int -> ParserState u -> Input s -> Added s -> More
-> Failure s u m r
-> Success s u s m r
-> m (IResult s u m r)
ensure' !n s0 i0 a0 m0 kf0 ks0 = runParserT_ (demandInput >> go) s0 i0 a0 m0 kf0 ks0
where go = ParserT $ \s i a m kf ks ->
if TS.length (unI i) >= n then ks s i a m (unI i)
else runParserT_ (demandInput >> go) s i a m kf ks
wantInput :: (Monad m, TokenSeq s t) => ParserT s u m Bool
wantInput =
ParserT $ \s0 i0 a0 m0 _ ks ->
case () of
_ | not (TS.null (unI i0)) -> ks s0 i0 a0 m0 True
| m0 == Complete -> ks s0 i0 a0 m0 False
| otherwise -> let { kf' i a m = ks s0 i a m False
; ks' i a m = ks s0 i a m True }
in prompt i0 a0 m0 kf' ks'
demandInput :: (Monad m, TokenSeq s t) => ParserT s u m ()
demandInput =
ParserT $ \s0 i0 a0 m0 kf ks ->
if m0 == Complete then kf s0 i0 a0 m0 (ParseError (psPos s0) [Message "demandInput"]) -- FIXME
else let kf' i a m = kf s0 i a m (ParseError (psPos s0) [Message "demandInput"]) -- FIXME TOO
ks' i a m = ks s0 i a m ()
in prompt i0 a0 m0 kf' ks'
prompt :: (Monad m, TokenSeq s t) =>
Input s -> Added s -> More
-> (Input s -> Added s -> More -> m (IResult s u m r))
-> (Input s -> Added s -> More -> m (IResult s u m r))
-> m (IResult s u m r)
prompt i0 a0 _ kf ks =
return $ Partial $ \s ->
if TS.null s then kf i0 a0 Complete
else ks (i0 <> I s) (a0 <> A s) Incomplete
getI :: ParserT s u m s
getI = ParserT $ \s i a m _ ks -> ks s i a m (unI i)
putI :: s -> ParserT s u m ()
putI i = ParserT $ \s _ a m _ ks -> ks s (I i) a m ()
-- |Return the current source position.
getSourcePos :: ParserT s u m SourcePos
getSourcePos = ParserT $ \s i a m _ ks -> ks s i a m (psPos s)
-- |Set the current source position. Note that modifying the source position will affect
-- error reporting.
putSourcePos :: SourcePos -> ParserT s u m ()
putSourcePos p = ParserT $ \s i a m _ ks -> ks ( s { psPos = p}) i a m ()
-- |Modify the current source position with the given function. Note that modifying the
-- source position will affect error reporting.
modifySourcePos :: (SourcePos -> SourcePos) -> ParserT s u m ()
modifySourcePos f = ParserT $ \s i a m _ ks -> ks (s { psPos = f $ psPos s }) i a m ()
-- |Update the current source position based on the given token.
updatePosTok :: TokenSeq s t => t -> ParserT s u m ()
updatePosTok = modifySourcePos . TS.updateSourcePos
-- |Update the current source position based on the given token sequence.
updatePosSeq :: TokenSeq s t => s -> ParserT s u m ()
updatePosSeq s = modifySourcePos $ \sp -> TS.fold (flip TS.updateSourcePos) sp s
-- |Return the current user state.
getUserState :: ParserT s u m u
getUserState = ParserT $ \s i a m _ ks -> ks s i a m (psState s)
-- |Set the current user state.
putUserState :: u -> ParserT s u m ()
putUserState u = ParserT $ \s i a m _ ks -> ks (s { psState = u }) i a m ()
-- |Modify the current user state with the given function.
modifyUserState :: (u -> u) -> ParserT s u m ()
modifyUserState f = ParserT $ \s i a m _ ks -> ks (s { psState = f $ psState s }) i a m ()
setErrMsg :: Message -> ParseError -> ParseError
setErrMsg msg pe = pe { errMsgs = msg : filter (/= msg) (errMsgs pe) }
| d3tucker/deciparsec | src/Data/Deciparsec/Internal.hs | bsd-3-clause | 3,903 | 10 | 20 | 1,171 | 1,618 | 836 | 782 | -1 | -1 |
module Graphics.Volume.MarchingCubesTables
( mcEdges
, mcTriangles
) where
import qualified Data.Vector as V
import Linear
-- | Intersecting cube edges for each cube configuration
mcEdges :: V.Vector Int
mcEdges = V.fromList
[ 0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00
, 0x190, 0x099, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90
, 0x230, 0x339, 0x033, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30
, 0x3a0, 0x2a9, 0x1a3, 0x0aa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0
, 0x460, 0x569, 0x663, 0x76a, 0x066, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60
, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0x0ff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0
, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x055, 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950
, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0x0cc, 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0
, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0x0cc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0
, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x055, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650
, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0x0ff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0
, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x066, 0x76a, 0x663, 0x569, 0x460
, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0x0aa, 0x1a3, 0x2a9, 0x3a0
, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x033, 0x339, 0x230
, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x099, 0x190
, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000
]
-- | Triangle indices of the isosurface for each cube configuration
mcTriangles :: V.Vector [V3 Int]
mcTriangles = V.fromList
[ []
, [V3 0 8 3]
, [V3 0 1 9]
, [V3 1 8 3,V3 9 8 1]
, [V3 1 2 10]
, [V3 0 8 3,V3 1 2 10]
, [V3 9 2 10,V3 0 2 9]
, [V3 2 8 3,V3 2 10 8,V3 10 9 8]
, [V3 3 11 2]
, [V3 0 11 2,V3 8 11 0]
, [V3 1 9 0,V3 2 3 11]
, [V3 1 11 2,V3 1 9 11,V3 9 8 11]
, [V3 3 10 1,V3 11 10 3]
, [V3 0 10 1,V3 0 8 10,V3 8 11 10]
, [V3 3 9 0,V3 3 11 9,V3 11 10 9]
, [V3 9 8 10,V3 10 8 11]
, [V3 4 7 8]
, [V3 4 3 0,V3 7 3 4]
, [V3 0 1 9,V3 8 4 7]
, [V3 4 1 9,V3 4 7 1,V3 7 3 1]
, [V3 1 2 10,V3 8 4 7]
, [V3 3 4 7,V3 3 0 4,V3 1 2 10]
, [V3 9 2 10,V3 9 0 2,V3 8 4 7]
, [V3 2 10 9,V3 2 9 7,V3 2 7 3,V3 7 9 4]
, [V3 8 4 7,V3 3 11 2]
, [V3 11 4 7,V3 11 2 4,V3 2 0 4]
, [V3 9 0 1,V3 8 4 7,V3 2 3 11]
, [V3 4 7 11,V3 9 4 11,V3 9 11 2,V3 9 2 1]
, [V3 3 10 1,V3 3 11 10,V3 7 8 4]
, [V3 1 11 10,V3 1 4 11,V3 1 0 4,V3 7 11 4]
, [V3 4 7 8,V3 9 0 11,V3 9 11 10,V3 11 0 3]
, [V3 4 7 11,V3 4 11 9,V3 9 11 10]
, [V3 9 5 4]
, [V3 9 5 4,V3 0 8 3]
, [V3 0 5 4,V3 1 5 0]
, [V3 8 5 4,V3 8 3 5,V3 3 1 5]
, [V3 1 2 10,V3 9 5 4]
, [V3 3 0 8,V3 1 2 10,V3 4 9 5]
, [V3 5 2 10,V3 5 4 2,V3 4 0 2]
, [V3 2 10 5,V3 3 2 5,V3 3 5 4,V3 3 4 8]
, [V3 9 5 4,V3 2 3 11]
, [V3 0 11 2,V3 0 8 11,V3 4 9 5]
, [V3 0 5 4,V3 0 1 5,V3 2 3 11]
, [V3 2 1 5,V3 2 5 8,V3 2 8 11,V3 4 8 5]
, [V3 10 3 11,V3 10 1 3,V3 9 5 4]
, [V3 4 9 5,V3 0 8 1,V3 8 10 1,V3 8 11 10]
, [V3 5 4 0,V3 5 0 11,V3 5 11 10,V3 11 0 3]
, [V3 5 4 8,V3 5 8 10,V3 10 8 11]
, [V3 9 7 8,V3 5 7 9]
, [V3 9 3 0,V3 9 5 3,V3 5 7 3]
, [V3 0 7 8,V3 0 1 7,V3 1 5 7]
, [V3 1 5 3,V3 3 5 7]
, [V3 9 7 8,V3 9 5 7,V3 10 1 2]
, [V3 10 1 2,V3 9 5 0,V3 5 3 0,V3 5 7 3]
, [V3 8 0 2,V3 8 2 5,V3 8 5 7,V3 10 5 2]
, [V3 2 10 5,V3 2 5 3,V3 3 5 7]
, [V3 7 9 5,V3 7 8 9,V3 3 11 2]
, [V3 9 5 7,V3 9 7 2,V3 9 2 0,V3 2 7 11]
, [V3 2 3 11,V3 0 1 8,V3 1 7 8,V3 1 5 7]
, [V3 11 2 1,V3 11 1 7,V3 7 1 5]
, [V3 9 5 8,V3 8 5 7,V3 10 1 3,V3 10 3 11]
, [V3 5 7 0,V3 5 0 9,V3 7 11 0,V3 1 0 10,V3 11 10 0]
, [V3 11 10 0,V3 11 0 3,V3 10 5 0,V3 8 0 7,V3 5 7 0]
, [V3 11 10 5,V3 7 11 5]
, [V3 10 6 5]
, [V3 0 8 3,V3 5 10 6]
, [V3 9 0 1,V3 5 10 6]
, [V3 1 8 3,V3 1 9 8,V3 5 10 6]
, [V3 1 6 5,V3 2 6 1]
, [V3 1 6 5,V3 1 2 6,V3 3 0 8]
, [V3 9 6 5,V3 9 0 6,V3 0 2 6]
, [V3 5 9 8,V3 5 8 2,V3 5 2 6,V3 3 2 8]
, [V3 2 3 11,V3 10 6 5]
, [V3 11 0 8,V3 11 2 0,V3 10 6 5]
, [V3 0 1 9,V3 2 3 11,V3 5 10 6]
, [V3 5 10 6,V3 1 9 2,V3 9 11 2,V3 9 8 11]
, [V3 6 3 11,V3 6 5 3,V3 5 1 3]
, [V3 0 8 11,V3 0 11 5,V3 0 5 1,V3 5 11 6]
, [V3 3 11 6,V3 0 3 6,V3 0 6 5,V3 0 5 9]
, [V3 6 5 9,V3 6 9 11,V3 11 9 8]
, [V3 5 10 6,V3 4 7 8]
, [V3 4 3 0,V3 4 7 3,V3 6 5 10]
, [V3 1 9 0,V3 5 10 6,V3 8 4 7]
, [V3 10 6 5,V3 1 9 7,V3 1 7 3,V3 7 9 4]
, [V3 6 1 2,V3 6 5 1,V3 4 7 8]
, [V3 1 2 5,V3 5 2 6,V3 3 0 4,V3 3 4 7]
, [V3 8 4 7,V3 9 0 5,V3 0 6 5,V3 0 2 6]
, [V3 7 3 9,V3 7 9 4,V3 3 2 9,V3 5 9 6,V3 2 6 9]
, [V3 3 11 2,V3 7 8 4,V3 10 6 5]
, [V3 5 10 6,V3 4 7 2,V3 4 2 0,V3 2 7 11]
, [V3 0 1 9,V3 4 7 8,V3 2 3 11,V3 5 10 6]
, [V3 9 2 1,V3 9 11 2,V3 9 4 11,V3 7 11 4,V3 5 10 6]
, [V3 8 4 7,V3 3 11 5,V3 3 5 1,V3 5 11 6]
, [V3 5 1 11,V3 5 11 6,V3 1 0 11,V3 7 11 4,V3 0 4 11]
, [V3 0 5 9,V3 0 6 5,V3 0 3 6,V3 11 6 3,V3 8 4 7]
, [V3 6 5 9,V3 6 9 11,V3 4 7 9,V3 7 11 9]
, [V3 10 4 9,V3 6 4 10]
, [V3 4 10 6,V3 4 9 10,V3 0 8 3]
, [V3 10 0 1,V3 10 6 0,V3 6 4 0]
, [V3 8 3 1,V3 8 1 6,V3 8 6 4,V3 6 1 10]
, [V3 1 4 9,V3 1 2 4,V3 2 6 4]
, [V3 3 0 8,V3 1 2 9,V3 2 4 9,V3 2 6 4]
, [V3 0 2 4,V3 4 2 6]
, [V3 8 3 2,V3 8 2 4,V3 4 2 6]
, [V3 10 4 9,V3 10 6 4,V3 11 2 3]
, [V3 0 8 2,V3 2 8 11,V3 4 9 10,V3 4 10 6]
, [V3 3 11 2,V3 0 1 6,V3 0 6 4,V3 6 1 10]
, [V3 6 4 1,V3 6 1 10,V3 4 8 1,V3 2 1 11,V3 8 11 1]
, [V3 9 6 4,V3 9 3 6,V3 9 1 3,V3 11 6 3]
, [V3 8 11 1,V3 8 1 0,V3 11 6 1,V3 9 1 4,V3 6 4 1]
, [V3 3 11 6,V3 3 6 0,V3 0 6 4]
, [V3 6 4 8,V3 11 6 8]
, [V3 7 10 6,V3 7 8 10,V3 8 9 10]
, [V3 0 7 3,V3 0 10 7,V3 0 9 10,V3 6 7 10]
, [V3 10 6 7,V3 1 10 7,V3 1 7 8,V3 1 8 0]
, [V3 10 6 7,V3 10 7 1,V3 1 7 3]
, [V3 1 2 6,V3 1 6 8,V3 1 8 9,V3 8 6 7]
, [V3 2 6 9,V3 2 9 1,V3 6 7 9,V3 0 9 3,V3 7 3 9]
, [V3 7 8 0,V3 7 0 6,V3 6 0 2]
, [V3 7 3 2,V3 6 7 2]
, [V3 2 3 11,V3 10 6 8,V3 10 8 9,V3 8 6 7]
, [V3 2 0 7,V3 2 7 11,V3 0 9 7,V3 6 7 10,V3 9 10 7]
, [V3 1 8 0,V3 1 7 8,V3 1 10 7,V3 6 7 10,V3 2 3 11]
, [V3 11 2 1,V3 11 1 7,V3 10 6 1,V3 6 7 1]
, [V3 8 9 6,V3 8 6 7,V3 9 1 6,V3 11 6 3,V3 1 3 6]
, [V3 0 9 1,V3 11 6 7]
, [V3 7 8 0,V3 7 0 6,V3 3 11 0,V3 11 6 0]
, [V3 7 11 6]
, [V3 7 6 11]
, [V3 3 0 8,V3 11 7 6]
, [V3 0 1 9,V3 11 7 6]
, [V3 8 1 9,V3 8 3 1,V3 11 7 6]
, [V3 10 1 2,V3 6 11 7]
, [V3 1 2 10,V3 3 0 8,V3 6 11 7]
, [V3 2 9 0,V3 2 10 9,V3 6 11 7]
, [V3 6 11 7,V3 2 10 3,V3 10 8 3,V3 10 9 8]
, [V3 7 2 3,V3 6 2 7]
, [V3 7 0 8,V3 7 6 0,V3 6 2 0]
, [V3 2 7 6,V3 2 3 7,V3 0 1 9]
, [V3 1 6 2,V3 1 8 6,V3 1 9 8,V3 8 7 6]
, [V3 10 7 6,V3 10 1 7,V3 1 3 7]
, [V3 10 7 6,V3 1 7 10,V3 1 8 7,V3 1 0 8]
, [V3 0 3 7,V3 0 7 10,V3 0 10 9,V3 6 10 7]
, [V3 7 6 10,V3 7 10 8,V3 8 10 9]
, [V3 6 8 4,V3 11 8 6]
, [V3 3 6 11,V3 3 0 6,V3 0 4 6]
, [V3 8 6 11,V3 8 4 6,V3 9 0 1]
, [V3 9 4 6,V3 9 6 3,V3 9 3 1,V3 11 3 6]
, [V3 6 8 4,V3 6 11 8,V3 2 10 1]
, [V3 1 2 10,V3 3 0 11,V3 0 6 11,V3 0 4 6]
, [V3 4 11 8,V3 4 6 11,V3 0 2 9,V3 2 10 9]
, [V3 10 9 3,V3 10 3 2,V3 9 4 3,V3 11 3 6,V3 4 6 3]
, [V3 8 2 3,V3 8 4 2,V3 4 6 2]
, [V3 0 4 2,V3 4 6 2]
, [V3 1 9 0,V3 2 3 4,V3 2 4 6,V3 4 3 8]
, [V3 1 9 4,V3 1 4 2,V3 2 4 6]
, [V3 8 1 3,V3 8 6 1,V3 8 4 6,V3 6 10 1]
, [V3 10 1 0,V3 10 0 6,V3 6 0 4]
, [V3 4 6 3,V3 4 3 8,V3 6 10 3,V3 0 3 9,V3 10 9 3]
, [V3 10 9 4,V3 6 10 4]
, [V3 4 9 5,V3 7 6 11]
, [V3 0 8 3,V3 4 9 5,V3 11 7 6]
, [V3 5 0 1,V3 5 4 0,V3 7 6 11]
, [V3 11 7 6,V3 8 3 4,V3 3 5 4,V3 3 1 5]
, [V3 9 5 4,V3 10 1 2,V3 7 6 11]
, [V3 6 11 7,V3 1 2 10,V3 0 8 3,V3 4 9 5]
, [V3 7 6 11,V3 5 4 10,V3 4 2 10,V3 4 0 2]
, [V3 3 4 8,V3 3 5 4,V3 3 2 5,V3 10 5 2,V3 11 7 6]
, [V3 7 2 3,V3 7 6 2,V3 5 4 9]
, [V3 9 5 4,V3 0 8 6,V3 0 6 2,V3 6 8 7]
, [V3 3 6 2,V3 3 7 6,V3 1 5 0,V3 5 4 0]
, [V3 6 2 8,V3 6 8 7,V3 2 1 8,V3 4 8 5,V3 1 5 8]
, [V3 9 5 4,V3 10 1 6,V3 1 7 6,V3 1 3 7]
, [V3 1 6 10,V3 1 7 6,V3 1 0 7,V3 8 7 0,V3 9 5 4]
, [V3 4 0 10,V3 4 10 5,V3 0 3 10,V3 6 10 7,V3 3 7 10]
, [V3 7 6 10,V3 7 10 8,V3 5 4 10,V3 4 8 10]
, [V3 6 9 5,V3 6 11 9,V3 11 8 9]
, [V3 3 6 11,V3 0 6 3,V3 0 5 6,V3 0 9 5]
, [V3 0 11 8,V3 0 5 11,V3 0 1 5,V3 5 6 11]
, [V3 6 11 3,V3 6 3 5,V3 5 3 1]
, [V3 1 2 10,V3 9 5 11,V3 9 11 8,V3 11 5 6]
, [V3 0 11 3,V3 0 6 11,V3 0 9 6,V3 5 6 9,V3 1 2 10]
, [V3 11 8 5,V3 11 5 6,V3 8 0 5,V3 10 5 2,V3 0 2 5]
, [V3 6 11 3,V3 6 3 5,V3 2 10 3,V3 10 5 3]
, [V3 5 8 9,V3 5 2 8,V3 5 6 2,V3 3 8 2]
, [V3 9 5 6,V3 9 6 0,V3 0 6 2]
, [V3 1 5 8,V3 1 8 0,V3 5 6 8,V3 3 8 2,V3 6 2 8]
, [V3 1 5 6,V3 2 1 6]
, [V3 1 3 6,V3 1 6 10,V3 3 8 6,V3 5 6 9,V3 8 9 6]
, [V3 10 1 0,V3 10 0 6,V3 9 5 0,V3 5 6 0]
, [V3 0 3 8,V3 5 6 10]
, [V3 10 5 6]
, [V3 11 5 10,V3 7 5 11]
, [V3 11 5 10,V3 11 7 5,V3 8 3 0]
, [V3 5 11 7,V3 5 10 11,V3 1 9 0]
, [V3 10 7 5,V3 10 11 7,V3 9 8 1,V3 8 3 1]
, [V3 11 1 2,V3 11 7 1,V3 7 5 1]
, [V3 0 8 3,V3 1 2 7,V3 1 7 5,V3 7 2 11]
, [V3 9 7 5,V3 9 2 7,V3 9 0 2,V3 2 11 7]
, [V3 7 5 2,V3 7 2 11,V3 5 9 2,V3 3 2 8,V3 9 8 2]
, [V3 2 5 10,V3 2 3 5,V3 3 7 5]
, [V3 8 2 0,V3 8 5 2,V3 8 7 5,V3 10 2 5]
, [V3 9 0 1,V3 5 10 3,V3 5 3 7,V3 3 10 2]
, [V3 9 8 2,V3 9 2 1,V3 8 7 2,V3 10 2 5,V3 7 5 2]
, [V3 1 3 5,V3 3 7 5]
, [V3 0 8 7,V3 0 7 1,V3 1 7 5]
, [V3 9 0 3,V3 9 3 5,V3 5 3 7]
, [V3 9 8 7,V3 5 9 7]
, [V3 5 8 4,V3 5 10 8,V3 10 11 8]
, [V3 5 0 4,V3 5 11 0,V3 5 10 11,V3 11 3 0]
, [V3 0 1 9,V3 8 4 10,V3 8 10 11,V3 10 4 5]
, [V3 10 11 4,V3 10 4 5,V3 11 3 4,V3 9 4 1,V3 3 1 4]
, [V3 2 5 1,V3 2 8 5,V3 2 11 8,V3 4 5 8]
, [V3 0 4 11,V3 0 11 3,V3 4 5 11,V3 2 11 1,V3 5 1 11]
, [V3 0 2 5,V3 0 5 9,V3 2 11 5,V3 4 5 8,V3 11 8 5]
, [V3 9 4 5,V3 2 11 3]
, [V3 2 5 10,V3 3 5 2,V3 3 4 5,V3 3 8 4]
, [V3 5 10 2,V3 5 2 4,V3 4 2 0]
, [V3 3 10 2,V3 3 5 10,V3 3 8 5,V3 4 5 8,V3 0 1 9]
, [V3 5 10 2,V3 5 2 4,V3 1 9 2,V3 9 4 2]
, [V3 8 4 5,V3 8 5 3,V3 3 5 1]
, [V3 0 4 5,V3 1 0 5]
, [V3 8 4 5,V3 8 5 3,V3 9 0 5,V3 0 3 5]
, [V3 9 4 5]
, [V3 4 11 7,V3 4 9 11,V3 9 10 11]
, [V3 0 8 3,V3 4 9 7,V3 9 11 7,V3 9 10 11]
, [V3 1 10 11,V3 1 11 4,V3 1 4 0,V3 7 4 11]
, [V3 3 1 4,V3 3 4 8,V3 1 10 4,V3 7 4 11,V3 10 11 4]
, [V3 4 11 7,V3 9 11 4,V3 9 2 11,V3 9 1 2]
, [V3 9 7 4,V3 9 11 7,V3 9 1 11,V3 2 11 1,V3 0 8 3]
, [V3 11 7 4,V3 11 4 2,V3 2 4 0]
, [V3 11 7 4,V3 11 4 2,V3 8 3 4,V3 3 2 4]
, [V3 2 9 10,V3 2 7 9,V3 2 3 7,V3 7 4 9]
, [V3 9 10 7,V3 9 7 4,V3 10 2 7,V3 8 7 0,V3 2 0 7]
, [V3 3 7 10,V3 3 10 2,V3 7 4 10,V3 1 10 0,V3 4 0 10]
, [V3 1 10 2,V3 8 7 4]
, [V3 4 9 1,V3 4 1 7,V3 7 1 3]
, [V3 4 9 1,V3 4 1 7,V3 0 8 1,V3 8 7 1]
, [V3 4 0 3,V3 7 4 3]
, [V3 4 8 7]
, [V3 9 10 8,V3 10 11 8]
, [V3 3 0 9,V3 3 9 11,V3 11 9 10]
, [V3 0 1 10,V3 0 10 8,V3 8 10 11]
, [V3 3 1 10,V3 11 3 10]
, [V3 1 2 11,V3 1 11 9,V3 9 11 8]
, [V3 3 0 9,V3 3 9 11,V3 1 2 9,V3 2 11 9]
, [V3 0 2 11,V3 8 0 11]
, [V3 3 2 11]
, [V3 2 3 8,V3 2 8 10,V3 10 8 9]
, [V3 9 10 2,V3 0 9 2]
, [V3 2 3 8,V3 2 8 10,V3 0 1 8,V3 1 10 8]
, [V3 1 10 2]
, [V3 1 3 8,V3 9 1 8]
, [V3 0 9 1]
, [V3 0 3 8]
, []
]
| fatho/volume | src/Graphics/Volume/MarchingCubesTables.hs | bsd-3-clause | 11,546 | 0 | 8 | 3,875 | 9,814 | 5,169 | 4,645 | 281 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Confluence.Sync.SyncTool (
sync
, ConfluenceConfig(..)
, TitleCaseConversion(..)
, confluenceXmlApi
) where
import Debug.Trace
import Prelude hiding (readFile)
import Control.Monad.Except
import Control.Monad.Reader
import Data.CaseInsensitive (CI)
import qualified Data.CaseInsensitive as CI
import Data.Char
import Data.String.Utils
import Data.List (break, intercalate, nubBy, find, foldl', sortOn, (\\))
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Data.Tree.Zipper
import Data.Tuple (swap)
import qualified Data.ByteString as BS
import Data.MIME.Types
import System.FilePath
import Text.Heredoc
import Confluence.Sync.LocalSite
import Confluence.Sync.Content
import Confluence.Sync.ReferenceResolver
import Confluence.Sync.PageNames
import qualified Confluence.Sync.XmlRpc.Api as Api
import Confluence.Sync.XmlRpc.Types
import Confluence.Sync.XmlRpc.Requests (ApiCall, runApiCall)
import Confluence.Sync.Internal.RateLimiter
data ConfluenceConfig = ConfluenceConfig {
user :: String
, password :: String
, confluenceUrl :: String
-- Used as a prefix for all pages.
, syncTitle :: String
-- Id of the page to use as the sync base.
, syncSpaceKey :: String
, syncPageId :: Maybe String
, titleCaseConversion :: TitleCaseConversion
} deriving Show
-- Address of the XML-RPC Api root
confluenceXmlApi :: ConfluenceConfig -> String
confluenceXmlApi config = (confluenceUrl config) ++ "/rpc/xmlrpc"
createRootPage :: ConfluenceConfig -> ApiCall Page
createRootPage (ConfluenceConfig { syncSpaceKey, syncTitle }) = do
let newRootPage = NewPage {
newPageSpace = syncSpaceKey
, newPageParentId = Nothing
, newPageTitle = syncTitle
, newPageContent = "Root page for synchronization (not initialized yet)"
, newPagePermissions = Nothing
}
liftIO . putStrLn $ "Creating new root page (\"" ++ syncTitle ++ "\") for synchronization (in space \"" ++ syncSpaceKey ++ "\")"
newPage <- Api.createPage newRootPage
liftIO . putStrLn $ "Root page (\"" ++ syncTitle ++ "\") successfully created (in space \"" ++ syncSpaceKey ++ "\"): page id = " ++ (show $ pageId newPage) ++ ", url = " ++ (show $ pageUrl newPage)
return newPage
createOrFindPage :: ConfluenceConfig -> ApiCall Page
createOrFindPage (config@ConfluenceConfig { syncSpaceKey, syncTitle }) = do
liftIO . putStrLn $ "No page id provided - looking up page \"" ++ syncTitle ++ "\" in \"" ++ syncSpaceKey ++ "\""
findPage `catchError` (\_ -> createTheRootPage)
where findPage = do
page <- (Api.getPageByName syncSpaceKey syncTitle)
liftIO . putStrLn $ "Found root page (by name lookup): page id = " ++ (show $ pageId page) ++ ", url = " ++ (show $ pageUrl page)
return page
createTheRootPage = do
liftIO . putStrLn $ "Could not find page with name \"" ++ syncTitle ++ "\" (in space \"" ++ syncSpaceKey ++ "\"). Creating new page..."
createRootPage config
-------------------------------------------------------------------------------
-- Meta Pages
-------------------------------------------------------------------------------
-- | True if the page is a meta page.
isMetaPage :: ConfluenceConfig -> String -> Bool
isMetaPage config other = other == (metaPageName config) || other == (metaTrashPageName config)
-- | Creates or updates all of the meta pages as necessary.
createMetaPages :: ConfluenceConfig -> Page -> ApiCall (Page, Page)
createMetaPages config rootPage = do
metaPage <- createOrFindMetaPage config rootPage
trashPage <- createOrFindMetaTrashPage config metaPage
return (metaPage, trashPage)
metaPageName :: ConfluenceConfig -> String
metaPageName (ConfluenceConfig { syncTitle }) = "Meta (" ++ syncTitle ++ ")"
createOrFindMetaPage :: ConfluenceConfig -> Page -> ApiCall Page
createOrFindMetaPage (config@ConfluenceConfig { syncSpaceKey }) (rootPage@Page { pageId = rootPageId, pageTitle = rootPageTitle }) = do
liftIO . putStrLn $ "No page id provided - looking up page \"" ++ pageTitle ++ "\" in \"" ++ syncSpaceKey ++ "\""
page <- findPage `catchError` (\_ -> createMetaPage)
-- If the pages are not in the correct location - we require the user to manually move them.
-- It means that someone has come in manually and moved them. The user should verify what has happened
-- (we don't want to cause data loss or break something).
if ((pageParentId page) /= rootPageId)
then throwError $ "Metadata page (id = " ++ (pageId page) ++ ", name =\"" ++ pageTitle ++ "\") is not under the root page (id = " ++ rootPageId ++ ",name = \"" ++ rootPageTitle ++ "\"). Please move it to the correct location."
else return ()
return page
where pageTitle = metaPageName config
findPage = do
page <- (Api.getPageByName syncSpaceKey pageTitle)
liftIO . putStrLn $ "Found meta page (by name lookup): page id = " ++ (show $ pageId page) ++ ", url = " ++ (show $ pageUrl page)
return page
createMetaPage = do
liftIO . putStrLn $ "Could not find page with name \"" ++ pageTitle ++ "\" (in space \"" ++ syncSpaceKey ++ "\"). Creating new page..."
let newMetaPage = NewPage {
newPageSpace = syncSpaceKey
, newPageParentId = Just rootPageId
, newPageTitle = pageTitle
, newPageContent = "This page is the parent for all synchronization support pages (e.g. Trash)."
, newPagePermissions = Nothing
}
liftIO . putStrLn $ "Creating new meta page (\"" ++ pageTitle ++ "\") for synchronization (in space \"" ++ syncSpaceKey ++ "\")"
newPage <- Api.createPage newMetaPage
liftIO . putStrLn $ "Meta page (\"" ++ pageTitle ++ "\") successfully created (in space \"" ++ syncSpaceKey ++ "\"): page id = " ++ (show $ pageId newPage) ++ ", url = " ++ (show $ pageUrl newPage)
return newPage
metaTrashPageName :: ConfluenceConfig -> String
metaTrashPageName (ConfluenceConfig { syncTitle }) = "Meta / Trash (" ++ syncTitle ++ ")"
createOrFindMetaTrashPage :: ConfluenceConfig -> Page -> ApiCall Page
createOrFindMetaTrashPage (config@ConfluenceConfig { syncSpaceKey }) (metaPage@Page { pageId = metaPageId, pageTitle = metaPageTitle }) = do
liftIO . putStrLn $ "No page id provided - looking up page \"" ++ pageTitle ++ "\" in \"" ++ syncSpaceKey ++ "\""
page <- findPage `catchError` (\_ -> createTrashPage)
-- If the pages are not in the correct location - we require the user to manually move them.
-- It means that someone has come in manually and moved them. The user should verify what has happened
-- (we don't want to cause data loss or break something).
if ((pageParentId page) /= metaPageId)
then throwError $ "Trash page (id = " ++ (pageId page) ++ ", name =\"" ++ pageTitle ++ "\") is not under the meta page (id = " ++ metaPageId ++ ",name = \"" ++ metaPageTitle ++ "\"). Please move it to the correct location."
else return ()
return page
where pageTitle = metaTrashPageName config
findPage = do
page <- (Api.getPageByName syncSpaceKey pageTitle)
liftIO . putStrLn $ "Found trash page (by name lookup): page id = " ++ (show $ pageId page) ++ ", url = " ++ (show $ pageUrl page)
return page
createTrashPage = do
liftIO . putStrLn $ "Could not find page with name \"" ++ pageTitle ++ "\" (in space \"" ++ syncSpaceKey ++ "\"). Creating new page..."
let newMetaPage = NewPage {
newPageSpace = syncSpaceKey
, newPageParentId = Just metaPageId
, newPageTitle = pageTitle
, newPageContent = "All pages that have been deleted are moved to under this page (to hide them)."
, newPagePermissions = Nothing
}
liftIO . putStrLn $ "Creating new trash page (\"" ++ pageTitle ++ "\") for synchronization (in space \"" ++ syncSpaceKey ++ "\")"
newPage <- Api.createPage newMetaPage
liftIO . putStrLn $ "Trash page (\"" ++ pageTitle ++ "\") successfully created (in space \"" ++ syncSpaceKey ++ "\"): page id = " ++ (show $ pageId newPage) ++ ", url = " ++ (show $ pageUrl newPage)
return newPage
-------------------------------------------------------------------------------
-- Content manipulation.
-------------------------------------------------------------------------------
-- | Creates placeholder pages for all new pages to be created.
-- These pages will be subsequently updated below.
createContentPage :: Page -> String -> ApiCall Page
createContentPage (Page { pageId = rootPageId, pageSpace }) title = do
let newPage = NewPage {
newPageSpace = pageSpace
, newPageParentId = Just rootPageId
, newPageTitle = title
, newPageContent = newPagePlaceholderMessage
, newPagePermissions = Nothing
}
liftIO . putStrLn $ "Synchronizing - creating page \"" ++ title ++ "\""
page <- Api.createPage newPage
liftIO . putStrLn $ "Synchronizing - created page \"" ++ title ++ "\" (\"" ++ (pageUrl page) ++ "\")"
return page
updateContentPage :: ConfluenceConfig -> (Map String String) -> ConfluenceZipper -> ApiCall Page
updateContentPage config renames zipper = do
let pageSummary = remotePage . label $ zipper
pageId = pageSummaryId pageSummary
originalTitle = pageSummaryTitle pageSummary
title = Map.findWithDefault originalTitle originalTitle renames
fullPath = maybe "<root>" id $ (filePath . label) <$> (pageSource . pagePosition . label $ zipper)
parentPageId = maybe (pageSummaryParentId pageSummary) id ((pageSummaryId . remotePage . label) <$> (parent zipper))
liftIO . putStrLn $ "Synchronizing - updating page \"" ++ title ++ "\" (\"" ++ fullPath ++ "\")"
if (title /= originalTitle)
then liftIO . putStrLn $ "Renaming page from \"" ++ originalTitle ++ "\" to \"" ++ title ++ "\""
else return ()
page <- Api.getPage pageId
localAttachments <- liftIO $ getAttachments zipper
remoteAttachments <- Api.getAttachments pageId
attachmentMapping <- syncAttachments pageId localAttachments remoteAttachments
localContents <- liftIO $ getPageContents zipper attachmentMapping
let updatedPage = page { pageTitle = title, pageContent = localContents, pageParentId = parentPageId}
if (page == updatedPage)
then liftIO . putStrLn $ "Synchronizing - page \"" ++ title ++ "\" is identical to the local copy."
else do
liftIO . putStrLn $ "Synchronizing - page \"" ++ title ++ "\" is different and requires updating."
Api.storePage updatedPage
liftIO . putStrLn $ "Synchronizing - page \"" ++ title ++ "\" update successfully: " ++ (pageUrl page)
return page
syncAttachments :: String -> [ LocalAttachment ] -> [ Attachment ] -> ApiCall [ (LocalAttachment, Attachment) ]
syncAttachments pageId localAttachments remoteAttachments = do
let localRemoteNames = map attachmentRemoteName localAttachments
let localRemotesNamesWithLocals = zip localRemoteNames localAttachments
let nameToLocal = Map.fromList $ localRemotesNamesWithLocals
let nameToRemote = Map.fromList $ zip (fmap attachmentFileName remoteAttachments) remoteAttachments
let localSet = Set.fromList $ localRemoteNames
let remoteSet = Set.fromList $ (fmap attachmentFileName remoteAttachments)
let completeSet = localSet `Set.union` remoteSet
let toRemove = completeSet `Set.difference` localSet
let toAdd = completeSet `Set.difference` remoteSet
let remaining = localSet `Set.intersection` remoteSet
-- Log the attachment actions to take.
liftIO $ putStrLn $ "Attachments to create: " ++ (if (Set.null toAdd) then "none." else "")
liftIO . sequence $ map (\t -> putStrLn $ " - " ++ show t) (Set.toList toAdd)
liftIO $ putStrLn ""
liftIO $ putStrLn $ "Attachments to delete: " ++ (if (Set.null toRemove) then "none." else "")
liftIO . sequence $ map (\t -> putStrLn $ " - " ++ show t) (Set.toList toRemove)
liftIO $ putStrLn ""
-- Actual perform the actions.
forM (Set.toList toRemove) $ (\attachmentName -> do
let attachment = nameToRemote Map.! attachmentName
liftIO $ putStrLn $ "Removing attachment " ++ attachmentName
(do
Api.removeAttachment (attachmentPageId attachment) attachmentName
liftIO $ putStrLn $ "Attachment removed: " ++ attachmentName
) `catchError` (\_ ->
liftIO $ putStrLn $ "WARN: failed to remove attachment " ++ attachmentName ++ " from page (id = " ++ pageId ++ ")"
)
)
added <- forM (Set.toList toAdd) $ (\attachmentName -> do
let local = nameToLocal Map.! attachmentName
liftIO $ putStrLn $ "Adding attachment " ++ attachmentName
contents <- liftIO $ BS.readFile (filePath . label . resolvedAttachment $ local)
let (mimeTypeGuess, encodingGuess) = guessType defaultmtd False attachmentName
let contentType = maybe "application/unknown" id mimeTypeGuess
remote <- Api.addAttachment pageId (NewAttachment attachmentName contentType) contents
liftIO $ putStrLn $ "Attachment added: " ++ attachmentName
return $ (local, remote)
)
-- Now we want to create a list of local files mapped to remote attachments.
-- NB. the list of local files is more like a list of references (and thus there may be duplicates).
let addedNameToRemote = Map.fromList $ (fmap (\a -> ((attachmentFileName a), a)) (fmap snd added))
let allRemote = addedNameToRemote `Map.union` nameToRemote
forM localRemotesNamesWithLocals $ (\(remoteName, local) -> do
return $ (local, allRemote Map.! remoteName)
)
trashContentPage :: Page -> PageSummary -> ApiCall Page
trashContentPage (trashPage@Page { pageId = trashPageId }) (PageSummary { pageSummaryId = pageId, pageSummaryTitle = title }) = do
liftIO . putStrLn $ "Synchronizing - trashing page \"" ++ title ++ "\""
page <- Api.getPage pageId
Api.storePage page { pageContent = deletedPageMessage, pageParentId = trashPageId}
liftIO . putStrLn $ "Synchronizing - page \"" ++ title ++ "\" has been moved to the trash successfully: " ++ (pageUrl page)
return page
-------------------------------------------------------------------------------
-- Sync Messages
-------------------------------------------------------------------------------
newPagePlaceholderMessage = [here|
<ac:structured-macro ac:name="info">
<ac:rich-text-body>
<p>This page is currently being synchronized - please check back again soon.</p>
</ac:rich-text-body>
</ac:structured-macro>
|]
deletedPageMessage = [here|
<ac:structured-macro ac:name="info">
<ac:rich-text-body>
<p>This page has been deleted and is no longer available.</p>
</ac:rich-text-body>
</ac:structured-macro>
|]
-------------------------------------------------------------------------------
-- Sync implementation.
-------------------------------------------------------------------------------
type LocalPageTitle = String
type RemotePageTitle = String
sync :: Throttle -> ConfluenceConfig -> FilePath -> IO ()
sync throttle config path = do
siteTree <- buildSiteTree path
let pageTree = buildPageTree siteTree
let pageZipper = fromTree pageTree
let localPages :: [PageZipper]
localPages = filter (notShadowReference . label) (traverseZipper pageZipper)
-- Get all the potential page titles.
let potentialPageTitles :: Set String
potentialPageTitles = Set.fromList $ localPages >>= (potentialPageNames (titleCaseConversion config) (syncTitle config))
-- Get all the pages with their potential titles.
let localPagesWithPotentialTitles :: [(PageZipper, [String])]
localPagesWithPotentialTitles = zip localPages ((potentialPageNames (titleCaseConversion config) (syncTitle config)) `fmap` localPages)
-- Deduplicates potential page titles within the site.
-- Note page titles are deduplicated on a case-insensitive basis.
let flattenedPotentialPagesWithTitles :: [(PageZipper, CI String)]
flattenedPotentialPagesWithTitles = localPagesWithPotentialTitles >>= (\(page, titles) -> (\title -> (page, CI.mk title)) `fmap` titles)
let localPagesWithUniqueTitles :: [(PageZipper, CI String)]
localPagesWithUniqueTitles = nubBy (\a b -> (snd $ a) == (snd $ b)) flattenedPotentialPagesWithTitles
-- Map from page to titles (sorted from most human friendly to most unique).
let localPagesWithTitles :: Map PageZipper [CI String]
localPagesWithTitles = (sortOn $ length . CI.original) `Map.map` (foldl' (\m (page, title) -> Map.insertWithKey (\_ a b -> b ++ a) page [title] m) Map.empty localPagesWithUniqueTitles)
-- Map from title to the corresponding page.
let titleToLocalPage :: Map (CI String) PageZipper
titleToLocalPage = Map.fromList (swap `fmap` localPagesWithUniqueTitles)
putStrLn "Logging into Confluence"
token <- Api.login (confluenceXmlApi config) (user config) (password config)
putStrLn $ "Successfully logged into Confluence: token = " ++ token
result <- runApiCall throttle (confluenceXmlApi config) token $ do
rootPage <- case (syncPageId config) of
Just pageId -> Api.getPage pageId
Nothing -> createOrFindPage config
-- Create/find the meta pages.
(metaPage, trashPage) <- createMetaPages config rootPage
-- Now we have the root page get the descendants.
descendants <- Api.getDescendents (pageId rootPage)
let remotePages = filter (\p -> not $ (isMetaPage config) (pageSummaryTitle p)) descendants
let remoteTitles = Set.fromList $ (syncTitle config) : (map pageSummaryTitle remotePages)
-- Match each remote page with a potential local page.
-- This allows us to do renames without creating/deleting excess pages.
-- This match is done in a case-insensitive manner.
let matchedPages :: [(PageZipper, RemotePageTitle, LocalPageTitle)]
matchedPages = catMaybes $ lookupLocalPageFromTitle `fmap` (Set.toList remoteTitles)
where lookupLocalPageFromTitle :: String -> Maybe (PageZipper, String, String)
lookupLocalPageFromTitle = ((\t -> (\p -> (p, t, (getLocalTitle p t))) `fmap` (Map.lookup (CI.mk t) titleToLocalPage)))
getLocalTitle :: PageZipper -> String -> String
getLocalTitle pageZipper remoteTitle = CI.original . fromJust $ find (== (CI.mk remoteTitle)) (localPagesWithTitles Map.! pageZipper)
-- Calculate the possible renames.
let possiblePageRenames :: [(String, [String])]
possiblePageRenames = hasBetterAlternativePageNames `filter` pagesWithBetterTitles
where pagesWithBetterTitles = ((\(p, t, _) -> (t, extractBetterTitles p t)) `fmap` matchedPages)
extractBetterTitles :: PageZipper -> String -> [String]
extractBetterTitles page currentTitle = CI.original <$> (fst $ break (== (CI.mk currentTitle)) (titlesForPage page))
titlesForPage :: PageZipper -> [CI String]
titlesForPage page = localPagesWithTitles Map.! page
hasBetterAlternativePageNames :: (String, [String]) -> Bool
hasBetterAlternativePageNames (current, others) = not . null $ others
-- Pages to rename.
-- A page rename can be done where the page doesn't already exist.
-- For each possible rename we need to lookup the page by name to see if it exists.
renames <- catMaybes <$> (forM possiblePageRenames $ (\(originalName, others) -> do
-- A name is optimal if it doesn't already exist.
-- The list of other names is sorted by order of human-friendliness.
optimalName <- findM (\other -> ((\_ -> Nothing) `fmap` (Api.getPageByName (syncSpaceKey config) other)) `catchError` (\_ -> return $ Just other)) others
return $ (\optimal -> (originalName, optimal)) `fmap` optimalName
))
-- Pages which we need to rename where the only difference is the case.
let extractLocalName (pageZipper, remote, local) = local
let differenceInCaseRenames :: [(RemotePageTitle, LocalPageTitle)]
differenceInCaseRenames = pairNotEqual `filter` (extractRemoteAndLocal <$> matchedPages)
where extractRemoteAndLocal (_, remote, local) = (remote, local)
pairNotEqual (a, b) = a /= b
-- Generate the combined map of renames
let renameMap = Map.fromList (renames ++ differenceInCaseRenames)
-- Pages to create.
-- Where we are creating a new page, we need to find the most optimal title for it.
let pagesToCreate = (\\) (Map.keys localPagesWithTitles) ((\(a, _, _) -> a) `fmap` matchedPages)
titlesToCreate <- (Set.fromList . catMaybes) <$> (forM pagesToCreate $ (\page -> do
let possibleTitles = CI.original <$> (localPagesWithTitles Map.! page)
-- A name is optimal if it doesn't already exist.
-- The list of other names is sorted by order of human-friendliness.
optimalName <- findM (\title -> ((\_ -> Nothing) `fmap` (Api.getPageByName (syncSpaceKey config) title)) `catchError` (\_ -> return $ Just title)) possibleTitles
return optimalName
))
let titlesAlreadyDeleted = Set.fromList $ map pageSummaryTitle (filter (\p -> (pageSummaryParentId p) == (pageId trashPage)) remotePages)
-- Calculate the page-level actions to take.
let titlesToUpdate = titlesToCreate `Set.union` (Set.fromList (snd `fmap` renames)) `Set.union` (Set.fromList (extractLocalName `fmap` matchedPages))
-- The titles to remove are all remote pages which we are not going to update, and which are not being renamed, or already deleted.
let titlesToRemove = (remoteTitles `Set.difference` titlesToUpdate) `Set.difference` (Map.keysSet renameMap) `Set.difference` titlesAlreadyDeleted
-- Log the page-level actions that will be taken.
liftIO $ putStrLn $ "Pages to create: " ++ (if (Set.null titlesToCreate) then "none." else "")
liftIO . sequence $ map (\t -> putStrLn $ " - " ++ show t) (Set.toList titlesToCreate)
liftIO $ putStrLn ""
liftIO $ putStrLn $ "Pages to rename: " ++ (if (Map.null renameMap) then "none." else "")
liftIO . sequence $ map (\t -> putStrLn $ " - " ++ t) ((\(original, updated) -> original ++ " -> " ++ updated) `fmap` (Map.toList renameMap))
liftIO $ putStrLn ""
liftIO $ putStrLn $ "Pages to update: " ++ (if (Set.null titlesToUpdate) then "none." else "")
liftIO . sequence $ map (\t -> putStrLn $ " - " ++ show t) (Set.toList titlesToUpdate)
liftIO $ putStrLn ""
liftIO $ putStrLn $ "Pages to delete: " ++ (if (Set.null titlesToRemove) then "none." else "")
liftIO . sequence $ map (\t -> putStrLn $ " - " ++ show t) (Set.toList titlesToRemove)
liftIO $ putStrLn ""
-- Create all the placeholder pages first.
createdPages <- sequence $ map (\title -> createContentPage rootPage title) (Set.toList titlesToCreate)
let createdPageSummaries = pageSummaryFromPage <$> createdPages
-- Create a list of page name to actual created page mappings.
-- This is needed to map relative URLs/links between pages to absolute URLs.
--
-- This is the complete list of all possible pages (this is used for updating/creating links between pages).
-- The root page is added in here because it will have the same name as the root directory page.
let allRemotePages = remotePages ++ createdPageSummaries ++ [ (pageSummaryFromPage rootPage) ]
let allRemotePagesMap :: Map String PageSummary
allRemotePagesMap = Map.fromList $ zip (map pageSummaryTitle allRemotePages) allRemotePages
-- Filter out remote pages that don't have a corresponding local page.
-- (otherwise it breaks the mapKeys below because we can't find a local page for the given title)
let remotePagesWithLocalPage = (Map.filterWithKey (\k _ -> Map.member (CI.mk k) titleToLocalPage) allRemotePagesMap)
let localToRemoteMap :: Map PageZipper PageSummary
localToRemoteMap = (\title -> titleToLocalPage Map.! (CI.mk title)) `Map.mapKeys` remotePagesWithLocalPage
let localToRemoteLookup :: PageZipper -> PageSummary
localToRemoteLookup local = localToRemoteMap Map.! local
-- Create the tree of pages to sync (and the zipper on that tree).
let syncTree = pageTreeToSyncTree pageZipper localToRemoteLookup
let syncZipper = fromTree syncTree
-- Update the content of all pages (including renaming where appropriate).
let pagesToUpdate = filter (notShadowReference . pagePosition . label) (traverseZipper syncZipper)
sequence $ map (updateContentPage config renameMap) pagesToUpdate
-- Delete any old pages.
sequence $ map (\title -> trashContentPage trashPage (allRemotePagesMap Map.! title)) (Set.toList titlesToRemove)
---
liftIO $ putStrLn "Logging out of Confluence."
Api.logout
liftIO $ putStrLn "Logged out successfully."
either (\err -> fail $ "ERROR: " ++ err) (\_ -> return ()) result
findM :: Monad m => (a -> m (Maybe b)) -> [a] -> m (Maybe b)
findM _ [] = return Nothing
findM f (x:xs) =
(f x) >>= recurse
where recurse (Just value) = return $ Just value
recurse Nothing = findM f xs
| laurencer/confluence-sync | src/Confluence/Sync/SyncTool.hs | bsd-3-clause | 25,964 | 0 | 29 | 5,587 | 6,091 | 3,211 | 2,880 | 322 | 6 |
module Categorizer.Util.IO
( readFileSafe
, safeGetEnv
, safeReadEnv ) where
import Control.Monad(liftM)
import Categorizer.Util.Maybe(readSafe)
import System.Environment(getEnv)
import qualified Control.Exception as E(catch, IOException)
readFileSafe :: FilePath -> IO (Maybe String)
readFileSafe path =
liftM Just (readFile path) `E.catch` handler
where
handler :: E.IOException -> IO (Maybe String)
handler e = print e >> return Nothing
safeGetEnv :: String -> IO (Maybe String)
safeGetEnv s = liftM Just (getEnv s) `E.catch` handler
where
handler :: IOError -> IO (Maybe String)
handler e = print e >> return Nothing
safeReadEnv :: Read a => String -> IO (Maybe a)
safeReadEnv s =
safeGetEnv s >>= \x -> case x of
Nothing -> return Nothing
Just p -> (return . readSafe) p
| ameingast/categorizer | src/Categorizer/Util/IO.hs | bsd-3-clause | 858 | 0 | 12 | 200 | 310 | 162 | 148 | 22 | 2 |
{- |
- NFA type and related utilities.
-
- This can be thought of as an upgrade to the Match type, in that it
- not only compares values to some possible values, but has sequences, and
- branches (splits) of comparisons.
-
- This can be used for, most notably, regular expressions.
-}
module Data.NFA (NFA(..), matches) where
import Data.Match (Match, (~=))
data NFA a = Step (Match a) (NFA a)
| Split (NFA a) (NFA a)
| MatchEnd
deriving (Eq, Show)
data State a = State [a] [NFA a]
-- | Does string match given regular expression?
matches :: Ord a => [a] -> NFA a -> Bool
matches s = isMatch . until isComplete runNFA . State s . expandSplit
where runNFA (State (x:xs) rs) = State xs (advanceStates x rs)
isComplete (State xs rs) = null xs || null rs
isMatch (State _ rs) = any (MatchEnd ==) rs
-- | Advance regex states
advanceStates :: Ord a => a -> [NFA a] -> [NFA a]
advanceStates c = concat . map step
where step (Step m r) | c ~= m = expandSplit r
step _ = []
-- | Advance new split states
expandSplit :: NFA a -> [NFA a]
expandSplit (Split l r) = [l, r]
expandSplit r = [r]
| awagner83/haskell-regex-nfa | src/Data/NFA.hs | bsd-3-clause | 1,217 | 0 | 11 | 354 | 397 | 208 | 189 | 19 | 2 |
-- 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 GADTs #-}
module Duckling.Rules.SW
( defaultRules
, langRules
, localeRules
) where
import Duckling.Dimensions.Types
import Duckling.Locale
import Duckling.Types
import qualified Duckling.Numeral.SW.Rules as Numeral
defaultRules :: Seal Dimension -> [Rule]
defaultRules = langRules
localeRules :: Region -> Seal Dimension -> [Rule]
localeRules region (Seal (CustomDimension dim)) = dimLocaleRules region dim
localeRules _ _ = []
langRules :: Seal Dimension -> [Rule]
langRules (Seal AmountOfMoney) = []
langRules (Seal CreditCardNumber) = []
langRules (Seal Distance) = []
langRules (Seal Duration) = []
langRules (Seal Email) = []
langRules (Seal Numeral) = Numeral.rules
langRules (Seal Ordinal) = []
langRules (Seal PhoneNumber) = []
langRules (Seal Quantity) = []
langRules (Seal RegexMatch) = []
langRules (Seal Temperature) = []
langRules (Seal Time) = []
langRules (Seal TimeGrain) = []
langRules (Seal Url) = []
langRules (Seal Volume) = []
langRules (Seal (CustomDimension dim)) = dimLangRules SW dim
| facebookincubator/duckling | Duckling/Rules/SW.hs | bsd-3-clause | 1,244 | 0 | 9 | 196 | 408 | 216 | 192 | 31 | 1 |
module Adventofcode where
import Control.Arrow
import Data.Foldable
advent01 :: Integral a => String -> a
advent01 = sum . map matchParens
advent02 :: Integral a => String -> Maybe a
advent02 = maybeResult . dropWhile ((>= 0) . snd) . zip [1..] . accum 0 . map matchParens
where
accum :: Integral a => a -> [a] -> [a]
accum acc (x:xs) = (acc + x) : accum (acc + x) xs
maybeResult ((i, _):xs) = Just i
maybeResult _ = Nothing
appendSum :: Integral a => [(a, a)] -> Char -> [(a, a)]
appendSum rest@((counter, addendum):_) x = (counter + 1, addendum + matchParens x) : rest
matchParens :: Integral a => Char -> a
matchParens '(' = 1
matchParens ')' = -1
matchParens _ = 0
| nadirs/adventofcode | src/Adventofcode.hs | bsd-3-clause | 693 | 0 | 12 | 152 | 335 | 178 | 157 | 17 | 2 |
module Paths_immigrate_haskell (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
version :: Version
version = Version [0,1,0,0] []
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/Users/max/develop/immigrate-haskell/.cabal-sandbox/bin"
libdir = "/Users/max/develop/immigrate-haskell/.cabal-sandbox/lib/x86_64-osx-ghc-7.10.1/immig_ByjsJ0j8jcnHRlqnbQBTmS"
datadir = "/Users/max/develop/immigrate-haskell/.cabal-sandbox/share/x86_64-osx-ghc-7.10.1/immigrate-haskell-0.1.0.0"
libexecdir = "/Users/max/develop/immigrate-haskell/.cabal-sandbox/libexec"
sysconfdir = "/Users/max/develop/immigrate-haskell/.cabal-sandbox/etc"
getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "immigrate_haskell_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "immigrate_haskell_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "immigrate_haskell_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "immigrate_haskell_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "immigrate_haskell_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| maxgurewitz/immigrate-haskell | dist/dist-sandbox-fd22d9f3/build/autogen/Paths_immigrate_haskell.hs | mit | 1,551 | 0 | 10 | 177 | 362 | 206 | 156 | 28 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.StorageGateway.DeleteSnapshotSchedule
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- This operation deletes a snapshot of a volume.
--
-- You can take snapshots of your gateway volumes on a scheduled or ad-hoc
-- basis. This API enables you to delete a snapshot schedule for a volume.
-- For more information, see
-- <http://docs.aws.amazon.com/storagegateway/latest/userguide/WorkingWithSnapshots.html Working with Snapshots>.
-- In the 'DeleteSnapshotSchedule' request, you identify the volume by
-- providing its Amazon Resource Name (ARN).
--
-- To list or delete a snapshot, you must use the Amazon EC2 API. in
-- /Amazon Elastic Compute Cloud API Reference/.
--
-- /See:/ <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DeleteSnapshotSchedule.html AWS API Reference> for DeleteSnapshotSchedule.
module Network.AWS.StorageGateway.DeleteSnapshotSchedule
(
-- * Creating a Request
deleteSnapshotSchedule
, DeleteSnapshotSchedule
-- * Request Lenses
, dVolumeARN
-- * Destructuring the Response
, deleteSnapshotScheduleResponse
, DeleteSnapshotScheduleResponse
-- * Response Lenses
, dsssrsVolumeARN
, dsssrsResponseStatus
) where
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
import Network.AWS.StorageGateway.Types
import Network.AWS.StorageGateway.Types.Product
-- | /See:/ 'deleteSnapshotSchedule' smart constructor.
newtype DeleteSnapshotSchedule = DeleteSnapshotSchedule'
{ _dVolumeARN :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteSnapshotSchedule' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dVolumeARN'
deleteSnapshotSchedule
:: Text -- ^ 'dVolumeARN'
-> DeleteSnapshotSchedule
deleteSnapshotSchedule pVolumeARN_ =
DeleteSnapshotSchedule'
{ _dVolumeARN = pVolumeARN_
}
-- | Undocumented member.
dVolumeARN :: Lens' DeleteSnapshotSchedule Text
dVolumeARN = lens _dVolumeARN (\ s a -> s{_dVolumeARN = a});
instance AWSRequest DeleteSnapshotSchedule where
type Rs DeleteSnapshotSchedule =
DeleteSnapshotScheduleResponse
request = postJSON storageGateway
response
= receiveJSON
(\ s h x ->
DeleteSnapshotScheduleResponse' <$>
(x .?> "VolumeARN") <*> (pure (fromEnum s)))
instance ToHeaders DeleteSnapshotSchedule where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("StorageGateway_20130630.DeleteSnapshotSchedule" ::
ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON DeleteSnapshotSchedule where
toJSON DeleteSnapshotSchedule'{..}
= object
(catMaybes [Just ("VolumeARN" .= _dVolumeARN)])
instance ToPath DeleteSnapshotSchedule where
toPath = const "/"
instance ToQuery DeleteSnapshotSchedule where
toQuery = const mempty
-- | /See:/ 'deleteSnapshotScheduleResponse' smart constructor.
data DeleteSnapshotScheduleResponse = DeleteSnapshotScheduleResponse'
{ _dsssrsVolumeARN :: !(Maybe Text)
, _dsssrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteSnapshotScheduleResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dsssrsVolumeARN'
--
-- * 'dsssrsResponseStatus'
deleteSnapshotScheduleResponse
:: Int -- ^ 'dsssrsResponseStatus'
-> DeleteSnapshotScheduleResponse
deleteSnapshotScheduleResponse pResponseStatus_ =
DeleteSnapshotScheduleResponse'
{ _dsssrsVolumeARN = Nothing
, _dsssrsResponseStatus = pResponseStatus_
}
-- | Undocumented member.
dsssrsVolumeARN :: Lens' DeleteSnapshotScheduleResponse (Maybe Text)
dsssrsVolumeARN = lens _dsssrsVolumeARN (\ s a -> s{_dsssrsVolumeARN = a});
-- | The response status code.
dsssrsResponseStatus :: Lens' DeleteSnapshotScheduleResponse Int
dsssrsResponseStatus = lens _dsssrsResponseStatus (\ s a -> s{_dsssrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-storagegateway/gen/Network/AWS/StorageGateway/DeleteSnapshotSchedule.hs | mpl-2.0 | 4,930 | 0 | 13 | 1,008 | 588 | 354 | 234 | 78 | 1 |
{-# LANGUAGE TupleSections #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.WindowBringer
-- Copyright : Devin Mullins <me@twifkak.com>
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Devin Mullins <me@twifkak.com>
-- Stability : stable
-- Portability : unportable
--
-- dmenu operations to bring windows to you, and bring you to windows.
-- That is to say, it pops up a dmenu with window names, in case you forgot
-- where you left your XChat.
--
-----------------------------------------------------------------------------
module XMonad.Actions.WindowBringer (
-- * Usage
-- $usage
WindowBringerConfig(..),
gotoMenu, gotoMenuConfig, gotoMenu', gotoMenuArgs, gotoMenuArgs',
bringMenu, bringMenuConfig, bringMenu', bringMenuArgs, bringMenuArgs',
windowMap, windowMap', bringWindow, actionMenu
) where
import Control.Applicative((<$>))
import qualified Data.Map as M
import qualified XMonad.StackSet as W
import XMonad
import qualified XMonad as X
import XMonad.Util.Dmenu (menuMapArgs)
import XMonad.Util.NamedWindows (getName)
-- $usage
--
-- Import the module into your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Actions.WindowBringer
--
-- and define appropriate key bindings:
--
-- > , ((modm .|. shiftMask, xK_g ), gotoMenu)
-- > , ((modm .|. shiftMask, xK_b ), bringMenu)
--
-- For detailed instructions on editing your key bindings, see
-- "XMonad.Doc.Extending#Editing_key_bindings".
data WindowBringerConfig = WindowBringerConfig
{ menuCommand :: String -- ^ The shell command that will handle window selection
, menuArgs :: [String] -- ^ Arguments to be passed to menuCommand
, windowTitler :: X.WindowSpace -> Window -> X String -- ^ A function that produces window titles given a workspace and a window
}
instance Default WindowBringerConfig where
def = WindowBringerConfig{ menuCommand = "dmenu"
, menuArgs = ["-i"]
, windowTitler = decorateName
}
-- | Pops open a dmenu with window titles. Choose one, and you will be
-- taken to the corresponding workspace.
gotoMenu :: X ()
gotoMenu = gotoMenuConfig def
-- | Pops open a dmenu with window titles. Choose one, and you will be
-- taken to the corresponding workspace. This version accepts a configuration
-- object.
gotoMenuConfig :: WindowBringerConfig -> X ()
gotoMenuConfig wbConfig = actionMenu wbConfig W.focusWindow
-- | Pops open a dmenu with window titles. Choose one, and you will be
-- taken to the corresponding workspace. This version takes a list of
-- arguments to pass to dmenu.
gotoMenuArgs :: [String] -> X ()
gotoMenuArgs args = gotoMenuConfig def { menuArgs = args }
-- | Pops open an application with window titles given over stdin. Choose one,
-- and you will be taken to the corresponding workspace.
gotoMenu' :: String -> X ()
gotoMenu' cmd = gotoMenuConfig def { menuArgs = [], menuCommand = cmd }
-- | Pops open an application with window titles given over stdin. Choose one,
-- and you will be taken to the corresponding workspace. This version takes a
-- list of arguments to pass to dmenu.
gotoMenuArgs' :: String -> [String] -> X ()
gotoMenuArgs' cmd args = gotoMenuConfig def { menuCommand = cmd, menuArgs = args }
-- | Pops open a dmenu with window titles. Choose one, and it will be
-- dragged, kicking and screaming, into your current workspace.
bringMenu :: X ()
bringMenu = bringMenuArgs def
-- | Pops open a dmenu with window titles. Choose one, and it will be
-- dragged, kicking and screaming, into your current workspace. This version
-- accepts a configuration object.
bringMenuConfig :: WindowBringerConfig -> X ()
bringMenuConfig wbConfig = actionMenu wbConfig bringWindow
-- | Pops open a dmenu with window titles. Choose one, and it will be
-- dragged, kicking and screaming, into your current workspace. This version
-- takes a list of arguments to pass to dmenu.
bringMenuArgs :: [String] -> X ()
bringMenuArgs args = bringMenuConfig def { menuArgs = args }
-- | Pops open an application with window titles given over stdin. Choose one,
-- and it will be dragged, kicking and screaming, into your current
-- workspace.
bringMenu' :: String -> X ()
bringMenu' cmd = bringMenuConfig def { menuArgs = [], menuCommand = cmd }
-- | Pops open an application with window titles given over stdin. Choose one,
-- and it will be dragged, kicking and screaming, into your current
-- workspace. This version allows arguments to the chooser to be specified.
bringMenuArgs' :: String -> [String] -> X ()
bringMenuArgs' cmd args = bringMenuConfig def { menuArgs = args, menuCommand = cmd }
-- | Brings the specified window into the current workspace.
bringWindow :: Window -> X.WindowSet -> X.WindowSet
bringWindow w ws = W.shiftWin (W.currentTag ws) w ws
-- | Calls dmenuMap to grab the appropriate Window, and hands it off to action
-- if found.
actionMenu :: WindowBringerConfig -> (Window -> X.WindowSet -> X.WindowSet) -> X ()
actionMenu WindowBringerConfig{ menuCommand = cmd
, menuArgs = args
, windowTitler = titler
} action
= windowMap' titler >>= menuMapFunction >>= flip X.whenJust (windows . action)
where
menuMapFunction :: M.Map String a -> X (Maybe a)
menuMapFunction = menuMapArgs cmd args
-- | A map from window names to Windows.
windowMap :: X (M.Map String Window)
windowMap = windowMap' decorateName
-- | A map from window names to Windows, given a windowTitler function.
windowMap' :: (X.WindowSpace -> Window -> X String) -> X (M.Map String Window)
windowMap' titler = do
ws <- gets X.windowset
M.fromList . concat <$> mapM keyValuePairs (W.workspaces ws)
where keyValuePairs ws = mapM (keyValuePair ws) $ W.integrate' (W.stack ws)
keyValuePair ws w = flip (,) w <$> titler ws w
-- | Returns the window name as will be listed in dmenu.
-- Tagged with the workspace ID, to guarantee uniqueness, and to let the user
-- know where he's going.
decorateName :: X.WindowSpace -> Window -> X String
decorateName ws w = do
name <- show <$> getName w
return $ name ++ " [" ++ W.tag ws ++ "]"
| f1u77y/xmonad-contrib | XMonad/Actions/WindowBringer.hs | bsd-3-clause | 6,440 | 0 | 11 | 1,410 | 1,016 | 576 | 440 | 63 | 1 |
----------------------------------------------------------------------------
--
-- Pretty-printing of Cmm as (a superset of) C--
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
--
-- This is where we walk over CmmNode emitting an external representation,
-- suitable for parsing, in a syntax strongly reminiscent of C--. This
-- is the "External Core" for the Cmm layer.
--
-- As such, this should be a well-defined syntax: we want it to look nice.
-- Thus, we try wherever possible to use syntax defined in [1],
-- "The C-- Reference Manual", http://www.cminusminus.org/. We differ
-- slightly, in some cases. For one, we use I8 .. I64 for types, rather
-- than C--'s bits8 .. bits64.
--
-- We try to ensure that all information available in the abstract
-- syntax is reproduced, or reproducible, in the concrete syntax.
-- Data that is not in printed out can be reconstructed according to
-- conventions used in the pretty printer. There are at least two such
-- cases:
-- 1) if a value has wordRep type, the type is not appended in the
-- output.
-- 2) MachOps that operate over wordRep type are printed in a
-- C-style, rather than as their internal MachRep name.
--
-- These conventions produce much more readable Cmm output.
--
-- A useful example pass over Cmm is in nativeGen/MachCodeGen.hs
{-# LANGUAGE GADTs, TypeFamilies, FlexibleContexts #-}
module PprCmm
( module PprCmmDecl
, module PprCmmExpr
)
where
import BlockId ()
import CLabel
import Cmm
import CmmUtils
import FastString
import Outputable
import PprCmmDecl
import PprCmmExpr
import Util
import BasicTypes
import Platform
import Compiler.Hoopl
import Data.List
import Prelude hiding (succ)
-------------------------------------------------
-- Outputable instances
instance Outputable CmmStackInfo where
ppr = pprStackInfo
instance PlatformOutputable CmmTopInfo where
pprPlatform = pprTopInfo
instance PlatformOutputable (CmmNode e x) where
pprPlatform = pprNode
instance Outputable Convention where
ppr = pprConvention
instance Outputable ForeignConvention where
ppr = pprForeignConvention
instance PlatformOutputable ForeignTarget where
pprPlatform = pprForeignTarget
instance PlatformOutputable (Block CmmNode C C) where
pprPlatform = pprBlock
instance PlatformOutputable (Block CmmNode C O) where
pprPlatform = pprBlock
instance PlatformOutputable (Block CmmNode O C) where
pprPlatform = pprBlock
instance PlatformOutputable (Block CmmNode O O) where
pprPlatform = pprBlock
instance PlatformOutputable (Graph CmmNode e x) where
pprPlatform = pprGraph
instance PlatformOutputable CmmGraph where
pprPlatform platform = pprCmmGraph platform
----------------------------------------------------------
-- Outputting types Cmm contains
pprStackInfo :: CmmStackInfo -> SDoc
pprStackInfo (StackInfo {arg_space=arg_space, updfr_space=updfr_space}) =
ptext (sLit "arg_space: ") <> ppr arg_space <+>
ptext (sLit "updfr_space: ") <> ppr updfr_space
pprTopInfo :: Platform -> CmmTopInfo -> SDoc
pprTopInfo platform (TopInfo {info_tbl=info_tbl, stack_info=stack_info}) =
vcat [ptext (sLit "info_tbl: ") <> pprPlatform platform info_tbl,
ptext (sLit "stack_info: ") <> ppr stack_info]
----------------------------------------------------------
-- Outputting blocks and graphs
pprBlock :: IndexedCO x SDoc SDoc ~ SDoc
=> Platform -> Block CmmNode e x -> IndexedCO e SDoc SDoc
pprBlock platform block
= foldBlockNodesB3 ( ($$) . pprPlatform platform
, ($$) . (nest 4) . pprPlatform platform
, ($$) . (nest 4) . pprPlatform platform
)
block
empty
pprGraph :: Platform -> Graph CmmNode e x -> SDoc
pprGraph _ GNil = empty
pprGraph platform (GUnit block) = pprPlatform platform block
pprGraph platform (GMany entry body exit)
= text "{"
$$ nest 2 (pprMaybeO entry $$ (vcat $ map (pprPlatform platform) $ bodyToBlockList body) $$ pprMaybeO exit)
$$ text "}"
where pprMaybeO :: PlatformOutputable (Block CmmNode e x)
=> MaybeO ex (Block CmmNode e x) -> SDoc
pprMaybeO NothingO = empty
pprMaybeO (JustO block) = pprPlatform platform block
pprCmmGraph :: Platform -> CmmGraph -> SDoc
pprCmmGraph platform g
= text "{" <> text "offset"
$$ nest 2 (vcat $ map (pprPlatform platform) blocks)
$$ text "}"
where blocks = postorderDfs g
---------------------------------------------
-- Outputting CmmNode and types which it contains
pprConvention :: Convention -> SDoc
pprConvention (NativeNodeCall {}) = text "<native-node-call-convention>"
pprConvention (NativeDirectCall {}) = text "<native-direct-call-convention>"
pprConvention (NativeReturn {}) = text "<native-ret-convention>"
pprConvention Slow = text "<slow-convention>"
pprConvention GC = text "<gc-convention>"
pprConvention PrimOpCall = text "<primop-call-convention>"
pprConvention PrimOpReturn = text "<primop-ret-convention>"
pprConvention (Foreign c) = ppr c
pprConvention (Private {}) = text "<private-convention>"
pprForeignConvention :: ForeignConvention -> SDoc
pprForeignConvention (ForeignConvention c as rs) = ppr c <> ppr as <> ppr rs
pprForeignTarget :: Platform -> ForeignTarget -> SDoc
pprForeignTarget platform (ForeignTarget fn c) = ppr_fc c <+> ppr_target fn
where ppr_fc :: ForeignConvention -> SDoc
ppr_fc (ForeignConvention c args res) =
doubleQuotes (ppr c) <+> text "arg hints: " <+> ppr args <+> text " result hints: " <+> ppr res
ppr_target :: CmmExpr -> SDoc
ppr_target t@(CmmLit _) = pprPlatform platform t
ppr_target fn' = parens (pprPlatform platform fn')
pprForeignTarget platform (PrimTarget op)
-- HACK: We're just using a ForeignLabel to get this printed, the label
-- might not really be foreign.
= pprPlatform platform
(CmmLabel (mkForeignLabel
(mkFastString (show op))
Nothing ForeignLabelInThisPackage IsFunction))
pprNode :: Platform -> CmmNode e x -> SDoc
pprNode platform node = pp_node <+> pp_debug
where
pp_node :: SDoc
pp_node = case node of
-- label:
CmmEntry id -> ppr id <> colon
-- // text
CmmComment s -> text "//" <+> ftext s
-- reg = expr;
CmmAssign reg expr -> ppr reg <+> equals <+> pprPlatform platform expr <> semi
-- rep[lv] = expr;
CmmStore lv expr -> rep <> brackets(pprPlatform platform lv) <+> equals <+> pprPlatform platform expr <> semi
where
rep = ppr ( cmmExprType expr )
-- call "ccall" foo(x, y)[r1, r2];
-- ToDo ppr volatile
CmmUnsafeForeignCall target results args ->
hsep [ ppUnless (null results) $
parens (commafy $ map ppr results) <+> equals,
ptext $ sLit "call",
pprPlatform platform target <> parens (commafy $ map (pprPlatform platform) args) <> semi]
-- goto label;
CmmBranch ident -> ptext (sLit "goto") <+> ppr ident <> semi
-- if (expr) goto t; else goto f;
CmmCondBranch expr t f ->
hsep [ ptext (sLit "if")
, parens(pprPlatform platform expr)
, ptext (sLit "goto")
, ppr t <> semi
, ptext (sLit "else goto")
, ppr f <> semi
]
CmmSwitch expr maybe_ids ->
hang (hcat [ ptext (sLit "switch [0 .. ")
, int (length maybe_ids - 1)
, ptext (sLit "] ")
, if isTrivialCmmExpr expr
then pprPlatform platform expr
else parens (pprPlatform platform expr)
, ptext (sLit " {")
])
4 (vcat ( map caseify pairs )) $$ rbrace
where pairs = groupBy snds (zip [0 .. ] maybe_ids )
snds a b = (snd a) == (snd b)
caseify ixs@((_,Nothing):_) = ptext (sLit "/* impossible: ")
<> hcat (intersperse comma (map (int.fst) ixs)) <> ptext (sLit " */")
caseify as = let (is,ids) = unzip as
in hsep [ ptext (sLit "case")
, hcat (punctuate comma (map int is))
, ptext (sLit ": goto")
, ppr (head [ id | Just id <- ids]) <> semi ]
CmmCall tgt k out res updfr_off ->
hcat [ ptext (sLit "call"), space
, pprFun tgt, ptext (sLit "(...)"), space
, ptext (sLit "returns to") <+> ppr k <+> parens (ppr out)
<+> parens (ppr res)
, ptext (sLit " with update frame") <+> ppr updfr_off
, semi ]
where pprFun f@(CmmLit _) = pprPlatform platform f
pprFun f = parens (pprPlatform platform f)
CmmForeignCall {tgt=t, res=rs, args=as, succ=s, updfr=u, intrbl=i} ->
hcat $ if i then [ptext (sLit "interruptible"), space] else [] ++
[ ptext (sLit "foreign call"), space
, pprPlatform platform t, ptext (sLit "(...)"), space
, ptext (sLit "returns to") <+> ppr s
<+> ptext (sLit "args:") <+> parens (pprPlatform platform as)
<+> ptext (sLit "ress:") <+> parens (ppr rs)
, ptext (sLit " with update frame") <+> ppr u
, semi ]
pp_debug :: SDoc
pp_debug =
if not debugIsOn then empty
else case node of
CmmEntry {} -> empty -- Looks terrible with text " // CmmEntry"
CmmComment {} -> empty -- Looks also terrible with text " // CmmComment"
CmmAssign {} -> text " // CmmAssign"
CmmStore {} -> text " // CmmStore"
CmmUnsafeForeignCall {} -> text " // CmmUnsafeForeignCall"
CmmBranch {} -> text " // CmmBranch"
CmmCondBranch {} -> text " // CmmCondBranch"
CmmSwitch {} -> text " // CmmSwitch"
CmmCall {} -> text " // CmmCall"
CmmForeignCall {} -> text " // CmmForeignCall"
commafy :: [SDoc] -> SDoc
commafy xs = hsep $ punctuate comma xs
| mcmaniac/ghc | compiler/cmm/PprCmm.hs | bsd-3-clause | 10,613 | 0 | 23 | 3,131 | 2,580 | 1,316 | 1,264 | 174 | 24 |
{-# LANGUAGE CPP, MagicHash #-}
-- |
-- Module : Data.Primitive.MachDeps
-- Copyright : (c) Roman Leshchinskiy 2009-2012
-- License : BSD-style
--
-- Maintainer : Roman Leshchinskiy <rl@cse.unsw.edu.au>
-- Portability : non-portable
--
-- Machine-dependent constants
--
module Data.Primitive.MachDeps where
#include "MachDeps.h"
import GHC.Prim
sIZEOF_CHAR,
aLIGNMENT_CHAR,
sIZEOF_INT,
aLIGNMENT_INT,
sIZEOF_WORD,
aLIGNMENT_WORD,
sIZEOF_DOUBLE,
aLIGNMENT_DOUBLE,
sIZEOF_FLOAT,
aLIGNMENT_FLOAT,
sIZEOF_PTR,
aLIGNMENT_PTR,
sIZEOF_FUNPTR,
aLIGNMENT_FUNPTR,
sIZEOF_STABLEPTR,
aLIGNMENT_STABLEPTR,
sIZEOF_INT8,
aLIGNMENT_INT8,
sIZEOF_WORD8,
aLIGNMENT_WORD8,
sIZEOF_INT16,
aLIGNMENT_INT16,
sIZEOF_WORD16,
aLIGNMENT_WORD16,
sIZEOF_INT32,
aLIGNMENT_INT32,
sIZEOF_WORD32,
aLIGNMENT_WORD32,
sIZEOF_INT64,
aLIGNMENT_INT64,
sIZEOF_WORD64,
aLIGNMENT_WORD64 :: Int
sIZEOF_CHAR = SIZEOF_HSCHAR
aLIGNMENT_CHAR = ALIGNMENT_HSCHAR
sIZEOF_INT = SIZEOF_HSINT
aLIGNMENT_INT = ALIGNMENT_HSINT
sIZEOF_WORD = SIZEOF_HSWORD
aLIGNMENT_WORD = ALIGNMENT_HSWORD
sIZEOF_DOUBLE = SIZEOF_HSDOUBLE
aLIGNMENT_DOUBLE = ALIGNMENT_HSDOUBLE
sIZEOF_FLOAT = SIZEOF_HSFLOAT
aLIGNMENT_FLOAT = ALIGNMENT_HSFLOAT
sIZEOF_PTR = SIZEOF_HSPTR
aLIGNMENT_PTR = ALIGNMENT_HSPTR
sIZEOF_FUNPTR = SIZEOF_HSFUNPTR
aLIGNMENT_FUNPTR = ALIGNMENT_HSFUNPTR
sIZEOF_STABLEPTR = SIZEOF_HSSTABLEPTR
aLIGNMENT_STABLEPTR = ALIGNMENT_HSSTABLEPTR
sIZEOF_INT8 = SIZEOF_INT8
aLIGNMENT_INT8 = ALIGNMENT_INT8
sIZEOF_WORD8 = SIZEOF_WORD8
aLIGNMENT_WORD8 = ALIGNMENT_WORD8
sIZEOF_INT16 = SIZEOF_INT16
aLIGNMENT_INT16 = ALIGNMENT_INT16
sIZEOF_WORD16 = SIZEOF_WORD16
aLIGNMENT_WORD16 = ALIGNMENT_WORD16
sIZEOF_INT32 = SIZEOF_INT32
aLIGNMENT_INT32 = ALIGNMENT_INT32
sIZEOF_WORD32 = SIZEOF_WORD32
aLIGNMENT_WORD32 = ALIGNMENT_WORD32
sIZEOF_INT64 = SIZEOF_INT64
aLIGNMENT_INT64 = ALIGNMENT_INT64
sIZEOF_WORD64 = SIZEOF_WORD64
aLIGNMENT_WORD64 = ALIGNMENT_WORD64
#if WORD_SIZE_IN_BITS == 32
type Word64_# = Word64#
type Int64_# = Int64#
#else
type Word64_# = Word#
type Int64_# = Int#
#endif
| dolio/primitive | Data/Primitive/MachDeps.hs | bsd-3-clause | 2,093 | 0 | 4 | 278 | 266 | 192 | 74 | 69 | 1 |
module Meetup (Weekday(..), Schedule(..), meetupDay) where
import Data.Time.Calendar (Day, addDays, fromGregorian, addGregorianMonthsClip)
import Data.Time.Calendar.WeekDate (toWeekDate)
data Weekday = Monday
| Tuesday
| Wednesday
| Thursday
| Friday
| Saturday
| Sunday
deriving (Enum)
data Schedule = First
| Second
| Third
| Fourth
| Last
| Teenth
deriving (Enum)
type Year = Integer
type Month = Int
addWeeks :: Int -> Day -> Day
addWeeks = addDays . (7 *) . fromIntegral
weekdayNum :: Weekday -> Int
weekdayNum = succ . fromEnum
toWeekday :: Weekday -> Day -> Day
toWeekday w d = fromIntegral offset `addDays` d
where offset | wnum >= wd = wnum - wd
| otherwise = 7 + wnum - wd
wnum = weekdayNum w
(_, _, wd) = toWeekDate d
meetupDay :: Schedule -> Weekday -> Year -> Month -> Day
meetupDay schedule weekday year month =
case schedule of
Last -> (-1) `addWeeks` calcDay nextMonthStart
Teenth -> calcDay $ 12 `addDays` monthStart
enum -> fromEnum enum `addWeeks` firstDay
where
calcDay = toWeekday weekday
monthStart = fromGregorian year month 1
nextMonthStart = addGregorianMonthsClip 1 monthStart
firstDay = calcDay monthStart
| pminten/xhaskell | meetup/example.hs | mit | 1,385 | 0 | 10 | 436 | 402 | 227 | 175 | 40 | 3 |
module PackageTests.BuildDeps.TargetSpecificDeps2.Check where
import Test.HUnit
import PackageTests.PackageTester
import System.FilePath
import qualified Control.Exception as E
suite :: FilePath -> Test
suite ghcPath = TestCase $ do
let spec = PackageSpec ("PackageTests" </> "BuildDeps" </> "TargetSpecificDeps2") []
result <- cabal_build spec ghcPath
do
assertEqual "cabal build should succeed - see test-log.txt" True (successful result)
`E.catch` \exc -> do
putStrLn $ "Cabal result was "++show result
E.throwIO (exc :: E.SomeException)
| jwiegley/ghc-release | libraries/Cabal/cabal/tests/PackageTests/BuildDeps/TargetSpecificDeps2/Check.hs | gpl-3.0 | 586 | 0 | 14 | 112 | 153 | 80 | 73 | 14 | 1 |
{-# LANGUAGE GADTs, BangPatterns #-}
module CmmCommonBlockElim
( elimCommonBlocks
)
where
import BlockId
import Cmm
import CmmUtils
import CmmSwitch (eqSwitchTargetWith)
import CmmContFlowOpt
-- import PprCmm ()
import Prelude hiding (iterate, succ, unzip, zip)
import Hoopl hiding (ChangeFlag)
import Data.Bits
import Data.Maybe (mapMaybe)
import qualified Data.List as List
import Data.Word
import qualified Data.Map as M
import Outputable
import UniqFM
import UniqDFM
import qualified TrieMap as TM
import Unique
import Control.Arrow (first, second)
-- -----------------------------------------------------------------------------
-- Eliminate common blocks
-- If two blocks are identical except for the label on the first node,
-- then we can eliminate one of the blocks. To ensure that the semantics
-- of the program are preserved, we have to rewrite each predecessor of the
-- eliminated block to proceed with the block we keep.
-- The algorithm iterates over the blocks in the graph,
-- checking whether it has seen another block that is equal modulo labels.
-- If so, then it adds an entry in a map indicating that the new block
-- is made redundant by the old block.
-- Otherwise, it is added to the useful blocks.
-- To avoid comparing every block with every other block repeatedly, we group
-- them by
-- * a hash of the block, ignoring labels (explained below)
-- * the list of outgoing labels
-- The hash is invariant under relabeling, so we only ever compare within
-- the same group of blocks.
--
-- The list of outgoing labels is updated as we merge blocks (that is why they
-- are not included in the hash, which we want to calculate only once).
--
-- All in all, two blocks should never be compared if they have different
-- hashes, and at most once otherwise. Previously, we were slower, and people
-- rightfully complained: #10397
-- TODO: Use optimization fuel
elimCommonBlocks :: CmmGraph -> CmmGraph
elimCommonBlocks g = replaceLabels env $ copyTicks env g
where
env = iterate mapEmpty blocks_with_key
groups = groupByInt hash_block (postorderDfs g)
blocks_with_key = [ [ (successors b, [b]) | b <- bs] | bs <- groups]
-- Invariant: The blocks in the list are pairwise distinct
-- (so avoid comparing them again)
type DistinctBlocks = [CmmBlock]
type Key = [Label]
type Subst = BlockEnv BlockId
-- The outer list groups by hash. We retain this grouping throughout.
iterate :: Subst -> [[(Key, DistinctBlocks)]] -> Subst
iterate subst blocks
| mapNull new_substs = subst
| otherwise = iterate subst' updated_blocks
where
grouped_blocks :: [[(Key, [DistinctBlocks])]]
grouped_blocks = map groupByLabel blocks
merged_blocks :: [[(Key, DistinctBlocks)]]
(new_substs, merged_blocks) = List.mapAccumL (List.mapAccumL go) mapEmpty grouped_blocks
where
go !new_subst1 (k,dbs) = (new_subst1 `mapUnion` new_subst2, (k,db))
where
(new_subst2, db) = mergeBlockList subst dbs
subst' = subst `mapUnion` new_substs
updated_blocks = map (map (first (map (lookupBid subst')))) merged_blocks
mergeBlocks :: Subst -> DistinctBlocks -> DistinctBlocks -> (Subst, DistinctBlocks)
mergeBlocks subst existing new = go new
where
go [] = (mapEmpty, existing)
go (b:bs) = case List.find (eqBlockBodyWith (eqBid subst) b) existing of
-- This block is a duplicate. Drop it, and add it to the substitution
Just b' -> first (mapInsert (entryLabel b) (entryLabel b')) $ go bs
-- This block is not a duplicate, keep it.
Nothing -> second (b:) $ go bs
mergeBlockList :: Subst -> [DistinctBlocks] -> (Subst, DistinctBlocks)
mergeBlockList _ [] = pprPanic "mergeBlockList" empty
mergeBlockList subst (b:bs) = go mapEmpty b bs
where
go !new_subst1 b [] = (new_subst1, b)
go !new_subst1 b1 (b2:bs) = go new_subst b bs
where
(new_subst2, b) = mergeBlocks subst b1 b2
new_subst = new_subst1 `mapUnion` new_subst2
-- -----------------------------------------------------------------------------
-- Hashing and equality on blocks
-- Below here is mostly boilerplate: hashing blocks ignoring labels,
-- and comparing blocks modulo a label mapping.
-- To speed up comparisons, we hash each basic block modulo jump labels.
-- The hashing is a bit arbitrary (the numbers are completely arbitrary),
-- but it should be fast and good enough.
-- We want to get as many small buckets as possible, as comparing blocks is
-- expensive. So include as much as possible in the hash. Ideally everything
-- that is compared with (==) in eqBlockBodyWith.
type HashCode = Int
hash_block :: CmmBlock -> HashCode
hash_block block =
fromIntegral (foldBlockNodesB3 (hash_fst, hash_mid, hash_lst) block (0 :: Word32) .&. (0x7fffffff :: Word32))
-- UniqFM doesn't like negative Ints
where hash_fst _ h = h
hash_mid m h = hash_node m + h `shiftL` 1
hash_lst m h = hash_node m + h `shiftL` 1
hash_node :: CmmNode O x -> Word32
hash_node n | dont_care n = 0 -- don't care
hash_node (CmmUnwind _ e) = hash_e e
hash_node (CmmAssign r e) = hash_reg r + hash_e e
hash_node (CmmStore e e') = hash_e e + hash_e e'
hash_node (CmmUnsafeForeignCall t _ as) = hash_tgt t + hash_list hash_e as
hash_node (CmmBranch _) = 23 -- NB. ignore the label
hash_node (CmmCondBranch p _ _ _) = hash_e p
hash_node (CmmCall e _ _ _ _ _) = hash_e e
hash_node (CmmForeignCall t _ _ _ _ _ _) = hash_tgt t
hash_node (CmmSwitch e _) = hash_e e
hash_node _ = error "hash_node: unknown Cmm node!"
hash_reg :: CmmReg -> Word32
hash_reg (CmmLocal localReg) = hash_unique localReg -- important for performance, see #10397
hash_reg (CmmGlobal _) = 19
hash_e :: CmmExpr -> Word32
hash_e (CmmLit l) = hash_lit l
hash_e (CmmLoad e _) = 67 + hash_e e
hash_e (CmmReg r) = hash_reg r
hash_e (CmmMachOp _ es) = hash_list hash_e es -- pessimal - no operator check
hash_e (CmmRegOff r i) = hash_reg r + cvt i
hash_e (CmmStackSlot _ _) = 13
hash_lit :: CmmLit -> Word32
hash_lit (CmmInt i _) = fromInteger i
hash_lit (CmmFloat r _) = truncate r
hash_lit (CmmVec ls) = hash_list hash_lit ls
hash_lit (CmmLabel _) = 119 -- ugh
hash_lit (CmmLabelOff _ i) = cvt $ 199 + i
hash_lit (CmmLabelDiffOff _ _ i) = cvt $ 299 + i
hash_lit (CmmBlock _) = 191 -- ugh
hash_lit (CmmHighStackMark) = cvt 313
hash_tgt (ForeignTarget e _) = hash_e e
hash_tgt (PrimTarget _) = 31 -- lots of these
hash_list f = foldl (\z x -> f x + z) (0::Word32)
cvt = fromInteger . toInteger
hash_unique :: Uniquable a => a -> Word32
hash_unique = cvt . getKey . getUnique
-- | Ignore these node types for equality
dont_care :: CmmNode O x -> Bool
dont_care CmmComment {} = True
dont_care CmmTick {} = True
dont_care _other = False
-- Utilities: equality and substitution on the graph.
-- Given a map ``subst'' from BlockID -> BlockID, we define equality.
eqBid :: BlockEnv BlockId -> BlockId -> BlockId -> Bool
eqBid subst bid bid' = lookupBid subst bid == lookupBid subst bid'
lookupBid :: BlockEnv BlockId -> BlockId -> BlockId
lookupBid subst bid = case mapLookup bid subst of
Just bid -> lookupBid subst bid
Nothing -> bid
-- Middle nodes and expressions can contain BlockIds, in particular in
-- CmmStackSlot and CmmBlock, so we have to use a special equality for
-- these.
--
eqMiddleWith :: (BlockId -> BlockId -> Bool)
-> CmmNode O O -> CmmNode O O -> Bool
eqMiddleWith eqBid (CmmAssign r1 e1) (CmmAssign r2 e2)
= r1 == r2 && eqExprWith eqBid e1 e2
eqMiddleWith eqBid (CmmStore l1 r1) (CmmStore l2 r2)
= eqExprWith eqBid l1 l2 && eqExprWith eqBid r1 r2
eqMiddleWith eqBid (CmmUnsafeForeignCall t1 r1 a1)
(CmmUnsafeForeignCall t2 r2 a2)
= t1 == t2 && r1 == r2 && and (zipWith (eqExprWith eqBid) a1 a2)
eqMiddleWith _ _ _ = False
eqExprWith :: (BlockId -> BlockId -> Bool)
-> CmmExpr -> CmmExpr -> Bool
eqExprWith eqBid = eq
where
CmmLit l1 `eq` CmmLit l2 = eqLit l1 l2
CmmLoad e1 _ `eq` CmmLoad e2 _ = e1 `eq` e2
CmmReg r1 `eq` CmmReg r2 = r1==r2
CmmRegOff r1 i1 `eq` CmmRegOff r2 i2 = r1==r2 && i1==i2
CmmMachOp op1 es1 `eq` CmmMachOp op2 es2 = op1==op2 && es1 `eqs` es2
CmmStackSlot a1 i1 `eq` CmmStackSlot a2 i2 = eqArea a1 a2 && i1==i2
_e1 `eq` _e2 = False
xs `eqs` ys = and (zipWith eq xs ys)
eqLit (CmmBlock id1) (CmmBlock id2) = eqBid id1 id2
eqLit l1 l2 = l1 == l2
eqArea Old Old = True
eqArea (Young id1) (Young id2) = eqBid id1 id2
eqArea _ _ = False
-- Equality on the body of a block, modulo a function mapping block
-- IDs to block IDs.
eqBlockBodyWith :: (BlockId -> BlockId -> Bool) -> CmmBlock -> CmmBlock -> Bool
eqBlockBodyWith eqBid block block'
{-
| equal = pprTrace "equal" (vcat [ppr block, ppr block']) True
| otherwise = pprTrace "not equal" (vcat [ppr block, ppr block']) False
-}
= equal
where (_,m,l) = blockSplit block
nodes = filter (not . dont_care) (blockToList m)
(_,m',l') = blockSplit block'
nodes' = filter (not . dont_care) (blockToList m')
equal = and (zipWith (eqMiddleWith eqBid) nodes nodes') &&
eqLastWith eqBid l l'
eqLastWith :: (BlockId -> BlockId -> Bool) -> CmmNode O C -> CmmNode O C -> Bool
eqLastWith eqBid (CmmBranch bid1) (CmmBranch bid2) = eqBid bid1 bid2
eqLastWith eqBid (CmmCondBranch c1 t1 f1 l1) (CmmCondBranch c2 t2 f2 l2) =
c1 == c2 && l1 == l2 && eqBid t1 t2 && eqBid f1 f2
eqLastWith eqBid (CmmCall t1 c1 g1 a1 r1 u1) (CmmCall t2 c2 g2 a2 r2 u2) =
t1 == t2 && eqMaybeWith eqBid c1 c2 && a1 == a2 && r1 == r2 && u1 == u2 && g1 == g2
eqLastWith eqBid (CmmSwitch e1 ids1) (CmmSwitch e2 ids2) =
e1 == e2 && eqSwitchTargetWith eqBid ids1 ids2
eqLastWith _ _ _ = False
eqMaybeWith :: (a -> b -> Bool) -> Maybe a -> Maybe b -> Bool
eqMaybeWith eltEq (Just e) (Just e') = eltEq e e'
eqMaybeWith _ Nothing Nothing = True
eqMaybeWith _ _ _ = False
-- | Given a block map, ensure that all "target" blocks are covered by
-- the same ticks as the respective "source" blocks. This not only
-- means copying ticks, but also adjusting tick scopes where
-- necessary.
copyTicks :: BlockEnv BlockId -> CmmGraph -> CmmGraph
copyTicks env g
| mapNull env = g
| otherwise = ofBlockMap (g_entry g) $ mapMap copyTo blockMap
where -- Reverse block merge map
blockMap = toBlockMap g
revEnv = mapFoldWithKey insertRev M.empty env
insertRev k x = M.insertWith (const (k:)) x [k]
-- Copy ticks and scopes into the given block
copyTo block = case M.lookup (entryLabel block) revEnv of
Nothing -> block
Just ls -> foldr copy block $ mapMaybe (flip mapLookup blockMap) ls
copy from to =
let ticks = blockTicks from
CmmEntry _ scp0 = firstNode from
(CmmEntry lbl scp1, code) = blockSplitHead to
in CmmEntry lbl (combineTickScopes scp0 scp1) `blockJoinHead`
foldr blockCons code (map CmmTick ticks)
-- Group by [Label]
groupByLabel :: [(Key, a)] -> [(Key, [a])]
groupByLabel = go (TM.emptyTM :: TM.ListMap UniqDFM a)
where
go !m [] = TM.foldTM (:) m []
go !m ((k,v) : entries) = go (TM.alterTM k' adjust m) entries
where k' = map getUnique k
adjust Nothing = Just (k,[v])
adjust (Just (_,vs)) = Just (k,v:vs)
groupByInt :: (a -> Int) -> [a] -> [[a]]
groupByInt f xs = nonDetEltsUFM $ List.foldl' go emptyUFM xs
-- See Note [Unique Determinism and code generation]
where go m x = alterUFM (Just . maybe [x] (x:)) m (f x)
| snoyberg/ghc | compiler/cmm/CmmCommonBlockElim.hs | bsd-3-clause | 11,972 | 0 | 15 | 2,939 | 3,441 | 1,791 | 1,650 | 182 | 25 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE UndecidableInstances #-} -- for compiling instances of (==)
{-# OPTIONS_GHC -XNoImplicitPrelude #-}
{-| This module is an internal GHC module. It declares the constants used
in the implementation of type-level natural numbers. The programmer interface
for working with type-level naturals should be defined in a separate library.
/Since: 4.6.0.0/
-}
module GHC.TypeLits
( -- * Kinds
Nat, Symbol
-- * Linking type and value level
, KnownNat, natVal
, KnownSymbol, symbolVal
, SomeNat(..), SomeSymbol(..)
, someNatVal, someSymbolVal
, sameNat, sameSymbol
-- * Functions on type literals
, type (<=), type (<=?), type (+), type (*), type (^), type (-)
, CmpNat, CmpSymbol
) where
import GHC.Base(Eq(..), Ord(..), Bool(True,False), Ordering(..), otherwise)
import GHC.Num(Integer)
import GHC.Base(String)
import GHC.Show(Show(..))
import GHC.Read(Read(..))
import GHC.Prim(magicDict)
import Data.Maybe(Maybe(..))
import Data.Proxy(Proxy(..))
import Data.Type.Equality(type (==), (:~:)(Refl))
import Unsafe.Coerce(unsafeCoerce)
-- | (Kind) This is the kind of type-level natural numbers.
data Nat
-- | (Kind) This is the kind of type-level symbols.
data Symbol
--------------------------------------------------------------------------------
-- | This class gives the integer associated with a type-level natural.
-- There are instances of the class for every concrete literal: 0, 1, 2, etc.
--
-- /Since: 4.7.0.0/
class KnownNat (n :: Nat) where
natSing :: SNat n
-- | This class gives the integer associated with a type-level symbol.
-- There are instances of the class for every concrete literal: "hello", etc.
--
-- /Since: 4.7.0.0/
class KnownSymbol (n :: Symbol) where
symbolSing :: SSymbol n
-- | /Since: 4.7.0.0/
natVal :: forall n proxy. KnownNat n => proxy n -> Integer
natVal _ = case natSing :: SNat n of
SNat x -> x
-- | /Since: 4.7.0.0/
symbolVal :: forall n proxy. KnownSymbol n => proxy n -> String
symbolVal _ = case symbolSing :: SSymbol n of
SSymbol x -> x
-- | This type represents unknown type-level natural numbers.
data SomeNat = forall n. KnownNat n => SomeNat (Proxy n)
-- ^ /Since: 4.7.0.0/
-- | This type represents unknown type-level symbols.
data SomeSymbol = forall n. KnownSymbol n => SomeSymbol (Proxy n)
-- ^ /Since: 4.7.0.0/
-- | Convert an integer into an unknown type-level natural.
--
-- /Since: 4.7.0.0/
someNatVal :: Integer -> Maybe SomeNat
someNatVal n
| n >= 0 = Just (withSNat SomeNat (SNat n) Proxy)
| otherwise = Nothing
-- | Convert a string into an unknown type-level symbol.
--
-- /Since: 4.7.0.0/
someSymbolVal :: String -> SomeSymbol
someSymbolVal n = withSSymbol SomeSymbol (SSymbol n) Proxy
instance Eq SomeNat where
SomeNat x == SomeNat y = natVal x == natVal y
instance Ord SomeNat where
compare (SomeNat x) (SomeNat y) = compare (natVal x) (natVal y)
instance Show SomeNat where
showsPrec p (SomeNat x) = showsPrec p (natVal x)
instance Read SomeNat where
readsPrec p xs = do (a,ys) <- readsPrec p xs
case someNatVal a of
Nothing -> []
Just n -> [(n,ys)]
instance Eq SomeSymbol where
SomeSymbol x == SomeSymbol y = symbolVal x == symbolVal y
instance Ord SomeSymbol where
compare (SomeSymbol x) (SomeSymbol y) = compare (symbolVal x) (symbolVal y)
instance Show SomeSymbol where
showsPrec p (SomeSymbol x) = showsPrec p (symbolVal x)
instance Read SomeSymbol where
readsPrec p xs = [ (someSymbolVal a, ys) | (a,ys) <- readsPrec p xs ]
type family EqNat (a :: Nat) (b :: Nat) where
EqNat a a = True
EqNat a b = False
type instance a == b = EqNat a b
type family EqSymbol (a :: Symbol) (b :: Symbol) where
EqSymbol a a = True
EqSymbol a b = False
type instance a == b = EqSymbol a b
--------------------------------------------------------------------------------
infix 4 <=?, <=
infixl 6 +, -
infixl 7 *
infixr 8 ^
-- | Comparison of type-level naturals, as a constraint.
type x <= y = (x <=? y) ~ True
-- | Comparison of type-level symbols, as a function.
--
-- /Since: 4.7.0.0/
type family CmpSymbol (m :: Symbol) (n :: Symbol) :: Ordering
-- | Comparison of type-level naturals, as a function.
--
-- /Since: 4.7.0.0/
type family CmpNat (m :: Nat) (n :: Nat) :: Ordering
{- | Comparison of type-level naturals, as a function.
NOTE: The functionality for this function should be subsumed
by 'CmpNat', so this might go away in the future.
Please let us know, if you encounter discrepancies between the two. -}
type family (m :: Nat) <=? (n :: Nat) :: Bool
-- | Addition of type-level naturals.
type family (m :: Nat) + (n :: Nat) :: Nat
-- | Multiplication of type-level naturals.
type family (m :: Nat) * (n :: Nat) :: Nat
-- | Exponentiation of type-level naturals.
type family (m :: Nat) ^ (n :: Nat) :: Nat
-- | Subtraction of type-level naturals.
--
-- /Since: 4.7.0.0/
type family (m :: Nat) - (n :: Nat) :: Nat
--------------------------------------------------------------------------------
-- | We either get evidence that this function was instantiated with the
-- same type-level numbers, or 'Nothing'.
--
-- /Since: 4.7.0.0/
sameNat :: (KnownNat a, KnownNat b) =>
Proxy a -> Proxy b -> Maybe (a :~: b)
sameNat x y
| natVal x == natVal y = Just (unsafeCoerce Refl)
| otherwise = Nothing
-- | We either get evidence that this function was instantiated with the
-- same type-level symbols, or 'Nothing'.
--
-- /Since: 4.7.0.0/
sameSymbol :: (KnownSymbol a, KnownSymbol b) =>
Proxy a -> Proxy b -> Maybe (a :~: b)
sameSymbol x y
| symbolVal x == symbolVal y = Just (unsafeCoerce Refl)
| otherwise = Nothing
--------------------------------------------------------------------------------
-- PRIVATE:
newtype SNat (n :: Nat) = SNat Integer
newtype SSymbol (s :: Symbol) = SSymbol String
data WrapN a b = WrapN (KnownNat a => Proxy a -> b)
data WrapS a b = WrapS (KnownSymbol a => Proxy a -> b)
-- See Note [magicDictId magic] in "basicType/MkId.hs"
withSNat :: (KnownNat a => Proxy a -> b)
-> SNat a -> Proxy a -> b
withSNat f x y = magicDict (WrapN f) x y
-- See Note [magicDictId magic] in "basicType/MkId.hs"
withSSymbol :: (KnownSymbol a => Proxy a -> b)
-> SSymbol a -> Proxy a -> b
withSSymbol f x y = magicDict (WrapS f) x y
| jtojnar/haste-compiler | libraries/ghc-7.8/base/GHC/TypeLits.hs | bsd-3-clause | 6,857 | 5 | 12 | 1,466 | 1,694 | 960 | 734 | -1 | -1 |
-- (c) The University of Glasgow 2006
-- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
--
-- Storage manager representation of closures
{-# LANGUAGE CPP,GeneralizedNewtypeDeriving #-}
module SMRep (
-- * Words and bytes
WordOff, ByteOff,
wordsToBytes, bytesToWordsRoundUp,
roundUpToWords,
StgWord, fromStgWord, toStgWord,
StgHalfWord, fromStgHalfWord, toStgHalfWord,
hALF_WORD_SIZE, hALF_WORD_SIZE_IN_BITS,
-- * Closure repesentation
SMRep(..), -- CmmInfo sees the rep; no one else does
IsStatic,
ClosureTypeInfo(..), ArgDescr(..), Liveness,
ConstrDescription,
-- ** Construction
mkHeapRep, blackHoleRep, indStaticRep, mkStackRep, mkRTSRep, arrPtrsRep,
smallArrPtrsRep, arrWordsRep,
-- ** Predicates
isStaticRep, isConRep, isThunkRep, isFunRep, isStaticNoCafCon,
isStackRep,
-- ** Size-related things
heapClosureSizeW,
fixedHdrSizeW, arrWordsHdrSize, arrWordsHdrSizeW, arrPtrsHdrSize,
arrPtrsHdrSizeW, profHdrSize, thunkHdrSize, nonHdrSize, nonHdrSizeW,
smallArrPtrsHdrSize, smallArrPtrsHdrSizeW, hdrSize, hdrSizeW,
fixedHdrSize,
-- ** RTS closure types
rtsClosureType, rET_SMALL, rET_BIG,
aRG_GEN, aRG_GEN_BIG,
-- ** Arrays
card, cardRoundUp, cardTableSizeB, cardTableSizeW,
-- * Operations over [Word8] strings that don't belong here
pprWord8String, stringToWord8s
) where
#include "../HsVersions.h"
#include "../includes/MachDeps.h"
import DynFlags
import Outputable
import Platform
import FastString
import Data.Char( ord )
import Data.Word
import Data.Bits
{-
************************************************************************
* *
Words and bytes
* *
************************************************************************
-}
-- | Word offset, or word count
type WordOff = Int
-- | Byte offset, or byte count
type ByteOff = Int
-- | Round up the given byte count to the next byte count that's a
-- multiple of the machine's word size.
roundUpToWords :: DynFlags -> ByteOff -> ByteOff
roundUpToWords dflags n =
(n + (wORD_SIZE dflags - 1)) .&. (complement (wORD_SIZE dflags - 1))
-- | Convert the given number of words to a number of bytes.
--
-- This function morally has type @WordOff -> ByteOff@, but uses @Num
-- a@ to allow for overloading.
wordsToBytes :: Num a => DynFlags -> a -> a
wordsToBytes dflags n = fromIntegral (wORD_SIZE dflags) * n
{-# SPECIALIZE wordsToBytes :: DynFlags -> Int -> Int #-}
{-# SPECIALIZE wordsToBytes :: DynFlags -> Word -> Word #-}
{-# SPECIALIZE wordsToBytes :: DynFlags -> Integer -> Integer #-}
-- | First round the given byte count up to a multiple of the
-- machine's word size and then convert the result to words.
bytesToWordsRoundUp :: DynFlags -> ByteOff -> WordOff
bytesToWordsRoundUp dflags n = (n + word_size - 1) `quot` word_size
where word_size = wORD_SIZE dflags
-- StgWord is a type representing an StgWord on the target platform.
-- A Word64 is large enough to hold a Word for either a 32bit or 64bit platform
newtype StgWord = StgWord Word64
deriving (Eq, Bits)
fromStgWord :: StgWord -> Integer
fromStgWord (StgWord i) = toInteger i
toStgWord :: DynFlags -> Integer -> StgWord
toStgWord dflags i
= case platformWordSize (targetPlatform dflags) of
-- These conversions mean that things like toStgWord (-1)
-- do the right thing
4 -> StgWord (fromIntegral (fromInteger i :: Word32))
8 -> StgWord (fromInteger i :: Word64)
w -> panic ("toStgWord: Unknown platformWordSize: " ++ show w)
instance Outputable StgWord where
ppr (StgWord i) = integer (toInteger i)
--
-- A Word32 is large enough to hold half a Word for either a 32bit or
-- 64bit platform
newtype StgHalfWord = StgHalfWord Word32
deriving Eq
fromStgHalfWord :: StgHalfWord -> Integer
fromStgHalfWord (StgHalfWord w) = toInteger w
toStgHalfWord :: DynFlags -> Integer -> StgHalfWord
toStgHalfWord dflags i
= case platformWordSize (targetPlatform dflags) of
-- These conversions mean that things like toStgHalfWord (-1)
-- do the right thing
4 -> StgHalfWord (fromIntegral (fromInteger i :: Word16))
8 -> StgHalfWord (fromInteger i :: Word32)
w -> panic ("toStgHalfWord: Unknown platformWordSize: " ++ show w)
instance Outputable StgHalfWord where
ppr (StgHalfWord w) = integer (toInteger w)
hALF_WORD_SIZE :: DynFlags -> ByteOff
hALF_WORD_SIZE dflags = platformWordSize (targetPlatform dflags) `shiftR` 1
hALF_WORD_SIZE_IN_BITS :: DynFlags -> Int
hALF_WORD_SIZE_IN_BITS dflags = platformWordSize (targetPlatform dflags) `shiftL` 2
{-
************************************************************************
* *
\subsubsection[SMRep-datatype]{@SMRep@---storage manager representation}
* *
************************************************************************
-}
-- | A description of the layout of a closure. Corresponds directly
-- to the closure types in includes/rts/storage/ClosureTypes.h.
data SMRep
= HeapRep -- GC routines consult sizes in info tbl
IsStatic
!WordOff -- # ptr words
!WordOff -- # non-ptr words INCLUDING SLOP (see mkHeapRep below)
ClosureTypeInfo -- type-specific info
| ArrayPtrsRep
!WordOff -- # ptr words
!WordOff -- # card table words
| SmallArrayPtrsRep
!WordOff -- # ptr words
| ArrayWordsRep
!WordOff -- # bytes expressed in words, rounded up
| StackRep -- Stack frame (RET_SMALL or RET_BIG)
Liveness
| RTSRep -- The RTS needs to declare info tables with specific
Int -- type tags, so this form lets us override the default
SMRep -- tag for an SMRep.
-- | True <=> This is a static closure. Affects how we garbage-collect it.
-- Static closure have an extra static link field at the end.
type IsStatic = Bool
-- From an SMRep you can get to the closure type defined in
-- includes/rts/storage/ClosureTypes.h. Described by the function
-- rtsClosureType below.
data ClosureTypeInfo
= Constr ConstrTag ConstrDescription
| Fun FunArity ArgDescr
| Thunk
| ThunkSelector SelectorOffset
| BlackHole
| IndStatic
type ConstrTag = Int
type ConstrDescription = [Word8] -- result of dataConIdentity
type FunArity = Int
type SelectorOffset = Int
-------------------------
-- We represent liveness bitmaps as a Bitmap (whose internal
-- representation really is a bitmap). These are pinned onto case return
-- vectors to indicate the state of the stack for the garbage collector.
--
-- In the compiled program, liveness bitmaps that fit inside a single
-- word (StgWord) are stored as a single word, while larger bitmaps are
-- stored as a pointer to an array of words.
type Liveness = [Bool] -- One Bool per word; True <=> non-ptr or dead
-- False <=> ptr
-------------------------
-- An ArgDescr describes the argument pattern of a function
data ArgDescr
= ArgSpec -- Fits one of the standard patterns
!Int -- RTS type identifier ARG_P, ARG_N, ...
| ArgGen -- General case
Liveness -- Details about the arguments
-----------------------------------------------------------------------------
-- Construction
mkHeapRep :: DynFlags -> IsStatic -> WordOff -> WordOff -> ClosureTypeInfo
-> SMRep
mkHeapRep dflags is_static ptr_wds nonptr_wds cl_type_info
= HeapRep is_static
ptr_wds
(nonptr_wds + slop_wds)
cl_type_info
where
slop_wds
| is_static = 0
| otherwise = max 0 (minClosureSize dflags - (hdr_size + payload_size))
hdr_size = closureTypeHdrSize dflags cl_type_info
payload_size = ptr_wds + nonptr_wds
mkRTSRep :: Int -> SMRep -> SMRep
mkRTSRep = RTSRep
mkStackRep :: [Bool] -> SMRep
mkStackRep liveness = StackRep liveness
blackHoleRep :: SMRep
blackHoleRep = HeapRep False 0 0 BlackHole
indStaticRep :: SMRep
indStaticRep = HeapRep True 1 0 IndStatic
arrPtrsRep :: DynFlags -> WordOff -> SMRep
arrPtrsRep dflags elems = ArrayPtrsRep elems (cardTableSizeW dflags elems)
smallArrPtrsRep :: WordOff -> SMRep
smallArrPtrsRep elems = SmallArrayPtrsRep elems
arrWordsRep :: DynFlags -> ByteOff -> SMRep
arrWordsRep dflags bytes = ArrayWordsRep (bytesToWordsRoundUp dflags bytes)
-----------------------------------------------------------------------------
-- Predicates
isStaticRep :: SMRep -> IsStatic
isStaticRep (HeapRep is_static _ _ _) = is_static
isStaticRep (RTSRep _ rep) = isStaticRep rep
isStaticRep _ = False
isStackRep :: SMRep -> Bool
isStackRep StackRep{} = True
isStackRep (RTSRep _ rep) = isStackRep rep
isStackRep _ = False
isConRep :: SMRep -> Bool
isConRep (HeapRep _ _ _ Constr{}) = True
isConRep _ = False
isThunkRep :: SMRep -> Bool
isThunkRep (HeapRep _ _ _ Thunk{}) = True
isThunkRep (HeapRep _ _ _ ThunkSelector{}) = True
isThunkRep (HeapRep _ _ _ BlackHole{}) = True
isThunkRep (HeapRep _ _ _ IndStatic{}) = True
isThunkRep _ = False
isFunRep :: SMRep -> Bool
isFunRep (HeapRep _ _ _ Fun{}) = True
isFunRep _ = False
isStaticNoCafCon :: SMRep -> Bool
-- This should line up exactly with CONSTR_NOCAF_STATIC above
-- See Note [Static NoCaf constructors]
isStaticNoCafCon (HeapRep True 0 _ Constr{}) = True
isStaticNoCafCon _ = False
-----------------------------------------------------------------------------
-- Size-related things
fixedHdrSize :: DynFlags -> ByteOff
fixedHdrSize dflags = wordsToBytes dflags (fixedHdrSizeW dflags)
-- | Size of a closure header (StgHeader in includes/rts/storage/Closures.h)
fixedHdrSizeW :: DynFlags -> WordOff
fixedHdrSizeW dflags = sTD_HDR_SIZE dflags + profHdrSize dflags
-- | Size of the profiling part of a closure header
-- (StgProfHeader in includes/rts/storage/Closures.h)
profHdrSize :: DynFlags -> WordOff
profHdrSize dflags
| gopt Opt_SccProfilingOn dflags = pROF_HDR_SIZE dflags
| otherwise = 0
-- | The garbage collector requires that every closure is at least as
-- big as this.
minClosureSize :: DynFlags -> WordOff
minClosureSize dflags = fixedHdrSizeW dflags + mIN_PAYLOAD_SIZE dflags
arrWordsHdrSize :: DynFlags -> ByteOff
arrWordsHdrSize dflags
= fixedHdrSize dflags + sIZEOF_StgArrBytes_NoHdr dflags
arrWordsHdrSizeW :: DynFlags -> WordOff
arrWordsHdrSizeW dflags =
fixedHdrSizeW dflags +
(sIZEOF_StgArrBytes_NoHdr dflags `quot` wORD_SIZE dflags)
arrPtrsHdrSize :: DynFlags -> ByteOff
arrPtrsHdrSize dflags
= fixedHdrSize dflags + sIZEOF_StgMutArrPtrs_NoHdr dflags
arrPtrsHdrSizeW :: DynFlags -> WordOff
arrPtrsHdrSizeW dflags =
fixedHdrSizeW dflags +
(sIZEOF_StgMutArrPtrs_NoHdr dflags `quot` wORD_SIZE dflags)
smallArrPtrsHdrSize :: DynFlags -> ByteOff
smallArrPtrsHdrSize dflags
= fixedHdrSize dflags + sIZEOF_StgSmallMutArrPtrs_NoHdr dflags
smallArrPtrsHdrSizeW :: DynFlags -> WordOff
smallArrPtrsHdrSizeW dflags =
fixedHdrSizeW dflags +
(sIZEOF_StgSmallMutArrPtrs_NoHdr dflags `quot` wORD_SIZE dflags)
-- Thunks have an extra header word on SMP, so the update doesn't
-- splat the payload.
thunkHdrSize :: DynFlags -> WordOff
thunkHdrSize dflags = fixedHdrSizeW dflags + smp_hdr
where smp_hdr = sIZEOF_StgSMPThunkHeader dflags `quot` wORD_SIZE dflags
hdrSize :: DynFlags -> SMRep -> ByteOff
hdrSize dflags rep = wordsToBytes dflags (hdrSizeW dflags rep)
hdrSizeW :: DynFlags -> SMRep -> WordOff
hdrSizeW dflags (HeapRep _ _ _ ty) = closureTypeHdrSize dflags ty
hdrSizeW dflags (ArrayPtrsRep _ _) = arrPtrsHdrSizeW dflags
hdrSizeW dflags (SmallArrayPtrsRep _) = smallArrPtrsHdrSizeW dflags
hdrSizeW dflags (ArrayWordsRep _) = arrWordsHdrSizeW dflags
hdrSizeW _ _ = panic "SMRep.hdrSizeW"
nonHdrSize :: DynFlags -> SMRep -> ByteOff
nonHdrSize dflags rep = wordsToBytes dflags (nonHdrSizeW rep)
nonHdrSizeW :: SMRep -> WordOff
nonHdrSizeW (HeapRep _ p np _) = p + np
nonHdrSizeW (ArrayPtrsRep elems ct) = elems + ct
nonHdrSizeW (SmallArrayPtrsRep elems) = elems
nonHdrSizeW (ArrayWordsRep words) = words
nonHdrSizeW (StackRep bs) = length bs
nonHdrSizeW (RTSRep _ rep) = nonHdrSizeW rep
-- | The total size of the closure, in words.
heapClosureSizeW :: DynFlags -> SMRep -> WordOff
heapClosureSizeW dflags (HeapRep _ p np ty)
= closureTypeHdrSize dflags ty + p + np
heapClosureSizeW dflags (ArrayPtrsRep elems ct)
= arrPtrsHdrSizeW dflags + elems + ct
heapClosureSizeW dflags (SmallArrayPtrsRep elems)
= smallArrPtrsHdrSizeW dflags + elems
heapClosureSizeW dflags (ArrayWordsRep words)
= arrWordsHdrSizeW dflags + words
heapClosureSizeW _ _ = panic "SMRep.heapClosureSize"
closureTypeHdrSize :: DynFlags -> ClosureTypeInfo -> WordOff
closureTypeHdrSize dflags ty = case ty of
Thunk{} -> thunkHdrSize dflags
ThunkSelector{} -> thunkHdrSize dflags
BlackHole{} -> thunkHdrSize dflags
IndStatic{} -> thunkHdrSize dflags
_ -> fixedHdrSizeW dflags
-- All thunks use thunkHdrSize, even if they are non-updatable.
-- this is because we don't have separate closure types for
-- updatable vs. non-updatable thunks, so the GC can't tell the
-- difference. If we ever have significant numbers of non-
-- updatable thunks, it might be worth fixing this.
-- ---------------------------------------------------------------------------
-- Arrays
-- | The byte offset into the card table of the card for a given element
card :: DynFlags -> Int -> Int
card dflags i = i `shiftR` mUT_ARR_PTRS_CARD_BITS dflags
-- | Convert a number of elements to a number of cards, rounding up
cardRoundUp :: DynFlags -> Int -> Int
cardRoundUp dflags i =
card dflags (i + ((1 `shiftL` mUT_ARR_PTRS_CARD_BITS dflags) - 1))
-- | The size of a card table, in bytes
cardTableSizeB :: DynFlags -> Int -> ByteOff
cardTableSizeB dflags elems = cardRoundUp dflags elems
-- | The size of a card table, in words
cardTableSizeW :: DynFlags -> Int -> WordOff
cardTableSizeW dflags elems =
bytesToWordsRoundUp dflags (cardTableSizeB dflags elems)
-----------------------------------------------------------------------------
-- deriving the RTS closure type from an SMRep
#include "../includes/rts/storage/ClosureTypes.h"
#include "../includes/rts/storage/FunTypes.h"
-- Defines CONSTR, CONSTR_1_0 etc
-- | Derives the RTS closure type from an 'SMRep'
rtsClosureType :: SMRep -> Int
rtsClosureType rep
= case rep of
RTSRep ty _ -> ty
HeapRep False 1 0 Constr{} -> CONSTR_1_0
HeapRep False 0 1 Constr{} -> CONSTR_0_1
HeapRep False 2 0 Constr{} -> CONSTR_2_0
HeapRep False 1 1 Constr{} -> CONSTR_1_1
HeapRep False 0 2 Constr{} -> CONSTR_0_2
HeapRep False _ _ Constr{} -> CONSTR
HeapRep False 1 0 Fun{} -> FUN_1_0
HeapRep False 0 1 Fun{} -> FUN_0_1
HeapRep False 2 0 Fun{} -> FUN_2_0
HeapRep False 1 1 Fun{} -> FUN_1_1
HeapRep False 0 2 Fun{} -> FUN_0_2
HeapRep False _ _ Fun{} -> FUN
HeapRep False 1 0 Thunk{} -> THUNK_1_0
HeapRep False 0 1 Thunk{} -> THUNK_0_1
HeapRep False 2 0 Thunk{} -> THUNK_2_0
HeapRep False 1 1 Thunk{} -> THUNK_1_1
HeapRep False 0 2 Thunk{} -> THUNK_0_2
HeapRep False _ _ Thunk{} -> THUNK
HeapRep False _ _ ThunkSelector{} -> THUNK_SELECTOR
-- Approximation: we use the CONSTR_NOCAF_STATIC type for static
-- constructors -- that have no pointer words only.
HeapRep True 0 _ Constr{} -> CONSTR_NOCAF_STATIC -- See isStaticNoCafCon below
HeapRep True _ _ Constr{} -> CONSTR_STATIC
HeapRep True _ _ Fun{} -> FUN_STATIC
HeapRep True _ _ Thunk{} -> THUNK_STATIC
HeapRep False _ _ BlackHole{} -> BLACKHOLE
HeapRep False _ _ IndStatic{} -> IND_STATIC
_ -> panic "rtsClosureType"
-- We export these ones
rET_SMALL, rET_BIG, aRG_GEN, aRG_GEN_BIG :: Int
rET_SMALL = RET_SMALL
rET_BIG = RET_BIG
aRG_GEN = ARG_GEN
aRG_GEN_BIG = ARG_GEN_BIG
{-
Note [Static NoCaf constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we know that a top-level binding 'x' is not Caffy (ie no CAFs are
reachable from 'x'), then a statically allocated constructor (Just x)
is also not Caffy, and the garbage collector need not follow its
argument fields. Exploiting this would require two static info tables
for Just, for the two cases where the argument was Caffy or non-Caffy.
Currently we don't do this; instead we treat nullary constructors
as non-Caffy, and the others as potentially Caffy.
************************************************************************
* *
Pretty printing of SMRep and friends
* *
************************************************************************
-}
instance Outputable ClosureTypeInfo where
ppr = pprTypeInfo
instance Outputable SMRep where
ppr (HeapRep static ps nps tyinfo)
= hang (header <+> lbrace) 2 (ppr tyinfo <+> rbrace)
where
header = ptext (sLit "HeapRep")
<+> if static then ptext (sLit "static") else empty
<+> pp_n "ptrs" ps <+> pp_n "nonptrs" nps
pp_n :: String -> Int -> SDoc
pp_n _ 0 = empty
pp_n s n = int n <+> text s
ppr (ArrayPtrsRep size _) = ptext (sLit "ArrayPtrsRep") <+> ppr size
ppr (SmallArrayPtrsRep size) = ptext (sLit "SmallArrayPtrsRep") <+> ppr size
ppr (ArrayWordsRep words) = ptext (sLit "ArrayWordsRep") <+> ppr words
ppr (StackRep bs) = ptext (sLit "StackRep") <+> ppr bs
ppr (RTSRep ty rep) = ptext (sLit "tag:") <> ppr ty <+> ppr rep
instance Outputable ArgDescr where
ppr (ArgSpec n) = ptext (sLit "ArgSpec") <+> ppr n
ppr (ArgGen ls) = ptext (sLit "ArgGen") <+> ppr ls
pprTypeInfo :: ClosureTypeInfo -> SDoc
pprTypeInfo (Constr tag descr)
= ptext (sLit "Con") <+>
braces (sep [ ptext (sLit "tag:") <+> ppr tag
, ptext (sLit "descr:") <> text (show descr) ])
pprTypeInfo (Fun arity args)
= ptext (sLit "Fun") <+>
braces (sep [ ptext (sLit "arity:") <+> ppr arity
, ptext (sLit ("fun_type:")) <+> ppr args ])
pprTypeInfo (ThunkSelector offset)
= ptext (sLit "ThunkSel") <+> ppr offset
pprTypeInfo Thunk = ptext (sLit "Thunk")
pprTypeInfo BlackHole = ptext (sLit "BlackHole")
pprTypeInfo IndStatic = ptext (sLit "IndStatic")
-- XXX Does not belong here!!
stringToWord8s :: String -> [Word8]
stringToWord8s s = map (fromIntegral . ord) s
pprWord8String :: [Word8] -> SDoc
-- Debug printing. Not very clever right now.
pprWord8String ws = text (show ws)
| wxwxwwxxx/ghc | compiler/cmm/SMRep.hs | bsd-3-clause | 19,439 | 0 | 14 | 4,644 | 3,965 | 2,075 | 1,890 | 322 | 27 |
module C3 where
import D3
instance Same Double
where
isSame a b = a == b
isNotSame a b = a /= b
myFringe :: (Tree a) -> [a]
myFringe (Leaf x) = [x]
myFringe (Branch left right) = myFringe left
| kmate/HaRe | old/testing/renaming/C3_AstOut.hs | bsd-3-clause | 212 | 0 | 7 | 60 | 97 | 51 | 46 | 8 | 1 |
{-# LANGUAGE TypeFamilies #-}
module T4200 where
class C a where
type In a :: *
op :: In a -> Int
-- Should be ok; no -XUndecidableInstances required
instance (In c ~ Int) => C [c] where
type In [c] = In c
op x = 3
| forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/indexed-types/should_compile/T4200.hs | bsd-3-clause | 239 | 0 | 8 | 72 | 82 | 45 | 37 | 8 | 0 |
{-# LANGUAGE PartialTypeSignatures, ScopedTypeVariables #-}
module PatternSig where
bar :: Bool -> Bool
bar (x :: _) = True
| forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/partial-sigs/should_compile/PatternSig.hs | bsd-3-clause | 125 | 0 | 7 | 20 | 29 | 17 | 12 | 4 | 1 |
module Main (main) where
import Control.Monad
import System.IO
import System.Random
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
let q = fold $ zip [1..] (take 200 [500.0,400.0..])
print q
putStrLn "Before atMost"
let (xs,q') = atMost 0.5 q -- this causes seqfault with -O2
print xs
print q'
putStrLn "After atMost"
fold :: [(Key, Prio)] -> PSQ
fold [] = Void
fold ((u,r):xs) = insert u r $ fold xs
data Elem = E
{ _key :: Key
, prio :: Prio
} deriving (Eq, Show)
type Prio = Double
type Key = Int
data PSQ = Void
| Winner Elem Tree
deriving (Eq, Show)
singleton :: Key -> Prio -> PSQ
singleton k p = Winner (E k p) Start
insert :: Key -> Prio -> PSQ -> PSQ
insert k p q = case q of
Void -> singleton k p
Winner e t -> Winner (E k p) (Fork e Start t)
atMost :: Prio -> PSQ -> ([Elem], PSQ)
atMost pt q = case q of
(Winner e _)
| prio e > pt -> ([], q)
Void -> ([], Void)
Winner e Start -> ([e], Void)
Winner e (Fork e' tl tr) ->
let (sequ, q') = atMost pt (Winner e' tl)
(sequ', q'') = atMost pt (Winner e tr)
in (sequ ++ sequ', q' `play` q'')
data Tree = Start
| Fork Elem Tree Tree
deriving (Eq, Show)
lloser :: Key -> Prio -> Tree -> Tree -> Tree
lloser k p tl tr = Fork (E k p) tl tr
play :: PSQ -> PSQ -> PSQ
Void `play` t' = t'
t `play` Void = t
Winner e@(E k p) t `play` Winner e'@(E k' p') t'
| p <= p' = Winner e (lloser k' p' t t')
| otherwise = Winner e' (lloser k p t t')
| siddhanathan/ghc | testsuite/tests/codeGen/should_run/T7953.hs | bsd-3-clause | 1,594 | 0 | 14 | 508 | 790 | 407 | 383 | 53 | 4 |
module Plivo (
callAPI,
APIError(..),
InclusiveOrdering(..),
-- * Enpoints
CreateOutboundCall(..),
createOutboundCall,
GetCompletedCalls(..),
getCompletedCalls
) where
import Prelude hiding (Ordering(..))
import Data.Maybe (catMaybes)
import Data.List (intercalate)
import Data.String (IsString, fromString)
import UnexceptionalIO (fromIO, runUnexceptionalIO)
import Control.Exception (fromException)
import Control.Error (EitherT, fmapLT, throwT, runEitherT)
import Network.URI (URI(..), URIAuth(..))
import Network.Http.Client (withConnection, establishConnection, sendRequest, buildRequest, http, setAccept, setContentType, Response, receiveResponse, RequestBuilder, inputStreamBody, emptyBody, getStatusCode, setAuthorizationBasic, setContentLength)
import qualified Network.Http.Client as HttpStreams
import Blaze.ByteString.Builder (Builder)
import System.IO.Streams (OutputStream, InputStream, fromLazyByteString)
import System.IO.Streams.Attoparsec (parseFromStream, ParseException(..))
import Network.HTTP.Types.QueryLike (QueryLike, toQuery, toQueryValue)
import Network.HTTP.Types.URI (renderQuery)
import Network.HTTP.Types.Method (Method)
import Network.HTTP.Types.Status (Status)
import Data.Aeson (encode, ToJSON, toJSON, FromJSON, fromJSON, Result(..), object, (.=), json', Value)
import Data.Time (UTCTime, formatTime)
import System.Locale (defaultTimeLocale)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LZ
import qualified Data.ByteString.Char8 as BS8 -- eww
s :: (IsString a) => String -> a
s = fromString
class Endpoint a where
endpoint :: String -> RequestBuilder () -> a -> IO (Either APIError Value)
-- | The endpoint to place an outbound call
data CreateOutboundCall = CreateOutboundCall {
from :: String,
to :: String,
answer_url :: URI,
answer_method :: Maybe Method,
ring_url :: Maybe URI,
ring_method :: Maybe Method,
hangup_url :: Maybe URI,
hangup_method :: Maybe Method,
fallback_url :: Maybe URI,
fallback_method :: Maybe Method,
caller_name :: Maybe String,
send_digits :: Maybe String,
send_on_preanswer :: Maybe Bool,
time_limit :: Maybe Int,
hangup_on_ring :: Maybe Int,
machine_detection :: Maybe String,
machine_detection_time :: Maybe Int,
sip_headers :: [(String,String)],
ring_timeout :: Maybe Int
} deriving (Show, Eq)
-- | Helper for constructing simple 'MakeCall'
createOutboundCall ::
String -- ^ from
-> String -- ^ to
-> URI -- ^ answer_url
-> CreateOutboundCall
createOutboundCall from to answer_url = CreateOutboundCall from to answer_url
Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
Nothing Nothing Nothing Nothing Nothing [] Nothing
instance ToJSON CreateOutboundCall where
toJSON (CreateOutboundCall from to answer_url answer_method ring_url
ring_method hangup_url hangup_method fallback_url fallback_method
caller_name send_digits send_on_preanswer time_limit hangup_on_ring
machine_detection machine_detection_time sip_headers ring_timeout
) = object $ catMaybes [
Just $ s"from" .= from,
Just $ s"to" .= to,
Just $ s"answer_url" .= show answer_url,
fmap (s"answer_method" .=) answer_method,
fmap ((s"ring_url" .=) . show) ring_url,
fmap (s"ring_method" .=) ring_method,
fmap ((s"hangup_url" .=) . show) hangup_url,
fmap (s"hangup_method" .=) hangup_method,
fmap ((s"fallback_url" .=) . show) fallback_url,
fmap (s"fallback_method" .=) fallback_method,
fmap (s"caller_name" .=) caller_name,
fmap (s"send_digits" .=) send_digits,
fmap (s"send_on_preanswer" .=) send_on_preanswer,
fmap (s"time_limit" .=) time_limit,
fmap (s"hangup_on_ring" .=) hangup_on_ring,
fmap (s"machine_detection" .=) machine_detection,
fmap (s"machine_detection_time" .=) machine_detection_time,
fmap (s"sip_headers" .=) (sipFmt sip_headers),
fmap (s"ring_timeout" .=) ring_timeout
]
where
sipFmt [] = Nothing
sipFmt xs = Just $ intercalate "," $ map (\(k,v) -> k ++ "=" ++ v) xs
instance Endpoint CreateOutboundCall where
endpoint aid = post (apiCall ("Account/" ++ aid ++ "/Call/"))
data InclusiveOrdering = EQ | LT | LTE | GT | GTE deriving (Show, Eq)
orderSuf :: InclusiveOrdering -> String
orderSuf EQ = ""
orderSuf LT = "__lt"
orderSuf LTE = "__lte"
orderSuf GT = "__gt"
orderSuf GTE = "__gte"
-- | The endpoint to list completed calls
data GetCompletedCalls = GetCompletedCalls {
subaccount :: Maybe String,
call_direction :: Maybe String,
from_number :: Maybe String,
to_number :: Maybe String,
bill_duration :: Maybe (InclusiveOrdering, Int),
end_time :: Maybe (InclusiveOrdering, UTCTime),
limit :: Maybe Int,
offset :: Maybe Int
} deriving (Eq, Show)
-- | Helper for constructing simple 'GetCompletedCalls'
getCompletedCalls :: GetCompletedCalls
getCompletedCalls = GetCompletedCalls Nothing Nothing Nothing Nothing Nothing
Nothing Nothing Nothing
instance QueryLike GetCompletedCalls where
toQuery (GetCompletedCalls subaccount call_duration from_number to_number
bill_duration end_time limit offset) = catMaybes [
fmap (k "subaccount") subaccount,
fmap (k "call_duration") call_duration,
fmap (k "from_number") from_number,
fmap (k "to_number") to_number,
fmap (\(o,d)-> k ("bill_duration"++orderSuf o) (show d)) bill_duration,
fmap (\(o,d)-> k ("end_time"++orderSuf o) (utcFmt d)) end_time,
fmap (k "limit" . show) limit,
fmap (k "offset" . show) offset
]
where
utcFmt = formatTime defaultTimeLocale "%Y-%m-%d %H:%M[:%S[%Q]]"
k str = (,) (fromString str) . toQueryValue
instance Endpoint GetCompletedCalls where
endpoint aid = get (apiCall ("Account/" ++ aid ++ "/Call/"))
-- | Call a Plivo API endpoint
--
-- You must wrap your app in a call to 'OpenSSL.withOpenSSL'
callAPI :: (Endpoint a) =>
String -- ^ AuthID
-> String -- ^ AuthToken
-> a -- ^ Endpoint data
-> IO (Either APIError Value)
callAPI aid atok = endpoint aid auth
where
-- These should be ASCII
auth = setAuthorizationBasic (BS8.pack aid) (BS8.pack atok)
-- Construct URIs
baseURI :: URI
baseURI = URI "https:" (Just $ URIAuth "" "api.plivo.com" "") "/v1/" "" ""
apiCall :: String -> URI
apiCall ('/':path) = apiCall path
apiCall path = baseURI { uriPath = uriPath baseURI ++ path }
-- HTTP requests
post :: (ToJSON a, FromJSON b) => URI -> RequestBuilder () -> a -> IO (Either APIError b)
post uri req payload = do
let req' = do
setAccept (BS8.pack "application/json")
setContentType (BS8.pack "application/json")
setContentLength (LZ.length body)
req
bodyStream <- fromLazyByteString body
oneShotHTTP HttpStreams.POST uri req' (inputStreamBody bodyStream) responseHandler
where
body = encode payload
get :: (QueryLike a, FromJSON b) => URI -> RequestBuilder () -> a -> IO (Either APIError b)
get uri req payload = do
let req' = do
setAccept (BS8.pack "application/json")
req
oneShotHTTP HttpStreams.GET uri' req' emptyBody responseHandler
where
uri' = uri { uriQuery = BS8.unpack $ renderQuery True (toQuery payload)}
data APIError = APIParamError | APIAuthError | APINotFoundError | APIParseError | APIRequestError Status | APIOtherError
deriving (Show, Eq)
responseHandler :: (FromJSON a) => Response -> InputStream ByteString -> IO (Either APIError a)
responseHandler resp i = runUnexceptionalIO $ runEitherT $ do
case getStatusCode resp of
code | code >= 200 && code < 300 -> return ()
400 -> throwT APIParamError
401 -> throwT APIAuthError
404 -> throwT APINotFoundError
code -> throwT $ APIRequestError $ toEnum code
v <- fmapLT (handle . fromException) $ fromIO $ parseFromStream json' i
case fromJSON v of
Success a -> return a
Error _ -> throwT APIParseError
where
handle (Just (ParseException _)) = APIParseError
handle _ = APIOtherError
oneShotHTTP :: HttpStreams.Method -> URI -> RequestBuilder () -> (OutputStream Builder -> IO ()) -> (Response -> InputStream ByteString -> IO b) -> IO b
oneShotHTTP method uri req body handler = do
req' <- buildRequest $ do
http method (BS8.pack $ uriPath uri)
req
withConnection (establishConnection url) $ \conn -> do
sendRequest conn req' body
receiveResponse conn handler
where
url = BS8.pack $ show uri -- URI can only have ASCII, so should be safe
| singpolyma/plivo-haskell | Plivo.hs | isc | 8,281 | 392 | 12 | 1,367 | 2,733 | 1,516 | 1,217 | 182 | 7 |
{-# LANGUAGE OverloadedStrings #-}
module Web.Larceny.Types ( Blank(..)
, Fill(..)
, Attributes
, Name(..)
, Substitutions
, subs
, fallbackSub
, Template(..)
, Path
, Library
, Overrides(..)
, defaultOverrides
, FromAttribute(..)
, AttrError(..)
, ApplyError(..)) where
import Control.Exception
import Control.Monad.State (StateT)
import Data.Hashable (Hashable, hash, hashWithSalt)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Text (Text)
import qualified Data.Text as T
import Text.Read (readMaybe)
-- | Corresponds to a "blank" in the template that can be filled in
-- with some value when the template is rendered. Blanks can be tags
-- or they can be all or parts of attribute values in tags.
--
-- Example blanks:
--
-- @
-- \<skater> \<- "skater"
-- \<p class=${name}> \<- "name"
-- \<skater name="${name}"> \<- both "skater" and "name"
-- \<a href="teams\/${team}\/{$number}"> \<- both "team" and number"
-- @
data Blank = Blank Text | FallbackBlank deriving (Eq, Show, Ord)
instance Hashable Blank where
hashWithSalt s (Blank tn) = s + hash tn
hashWithSalt s FallbackBlank = s + hash ("FallbackBlank" :: Text)
-- | A Fill is how to fill in a Blank.
--
-- In most cases, you can use helper functions like `textFill` or
-- `fillChildrenWith` to create your fills. You can also write Fills
-- from scratch.
--
-- @
-- Fill $ \attrs _tpl _lib ->
-- return $ T.pack $ show $ M.keys attrs)
-- @
--
-- With that Fill, a Blank like this:
--
-- > <displayAttrs attribute="hello!" another="goodbye!"/>
--
-- would be rendered as:
--
-- > ["attribute", "another"]
--
-- Fills (and Substitutions and Templates) have the type `StateT s IO
-- Text` in case you need templates to depend on IO actions (like
-- looking something up in a database) or store state (perhaps keeping
-- track of what's already been rendered).
newtype Fill s = Fill { unFill :: Attributes
-> (Path, Template s)
-> Library s
-> StateT s IO Text }
-- | The Blank's attributes, a map from the attribute name to
-- it's value.
type Attributes = Map Text Text
data Name = Name { nNamespace :: Maybe Text
, nName :: Text } deriving (Eq, Ord, Show)
-- | A map from a Blank to how to fill in that Blank.
type Substitutions s = Map Blank (Fill s)
-- | Turn tuples of text and fills to Substitutions.
--
-- @
-- subs [("blank", textFill "the fill")
-- ,("another-blank", textFill "another fill")]
-- @
subs :: [(Text, Fill s)] -> Substitutions s
subs = M.fromList . map (\(x, y) -> (Blank x, y))
-- | Say how to fill in Blanks with missing Fills.
--
-- @
-- \<nonexistent \/>
-- fallbackSub (textFill "I'm a fallback.")
-- @
-- > I'm a fallback.
--
-- You can add the resulting Substitutions to your regular Substitutions using
-- `mappend` or `(<>)`
--
-- @
-- \<blank \/>, <nonexistent \/>
-- subs [("blank", textFill "a fill")] <> fallbackSub (textFill "a fallback")
-- @
-- > a fill, a fallback
fallbackSub :: Fill s -> Substitutions s
fallbackSub fill = M.fromList [(FallbackBlank, fill)]
-- | When you run a Template with the path, some substitutions, and the
-- template library, you'll get back some stateful text.
--
-- Use `loadTemplates` to load the templates from some directory
-- into a template library. Use the `render` functions to render
-- templates from a Library by path.
newtype Template s = Template { runTemplate :: Path
-> Substitutions s
-> Library s
-> StateT s IO Text }
-- | The path to a template.
type Path = [Text]
-- | A collection of templates.
type Library s = Map Path (Template s)
-- | If no substitutions are given, Larceny only understands valid
-- HTML 5 tags. It won't attempt to "fill in" tags that are already
-- valid HTML 5. Use Overrides to use non-HTML 5 tags without
-- providing your own substitutions, or to provide your own fills for
-- standard HTML tags.
--
-- @
-- -- Use the deprecated "marquee" and "blink" tags and write your
-- -- own fill for the "a" tag.
-- Overrides ["marquee", "blink"] ["a"]
-- @
data Overrides = Overrides { customPlainNodes :: [Text]
, overrideNodes :: [Text]
, selfClosingNodes :: [Text]}
instance Semigroup Overrides where
(Overrides p o sc) <> (Overrides p' o' sc') =
Overrides (p <> p') (o <> o') (sc <> sc')
instance Monoid Overrides where
mempty = Overrides [] [] []
mappend = (<>)
-- | Default uses no overrides.
defaultOverrides :: Overrides
defaultOverrides = Overrides mempty mempty mempty
type AttrName = Text
-- | If an attribute is required but missing, or unparsable, one of
-- these errors is thrown.
data AttrError = AttrMissing AttrName
| AttrUnparsable Text AttrName
| OtherAttrError Text AttrName deriving (Eq)
instance Exception AttrError
instance Show AttrError where
show (AttrMissing name) = "Missing attribute \"" <> T.unpack name <> "\"."
show (AttrUnparsable toType name) = "Attribute with name \""
<> T.unpack name <> "\" can't be parsed to type \""
<> T.unpack toType <> "\"."
show (OtherAttrError e name) = "Error parsing attribute \""
<> T.unpack name <> "\": " <> T.unpack e
-- | A typeclass for things that can be parsed from attributes.
class FromAttribute a where
fromAttribute :: Maybe Text -> Either (Text -> AttrError) a
instance FromAttribute Text where
fromAttribute = maybe (Left AttrMissing) Right
instance FromAttribute Int where
fromAttribute (Just attr) = maybe (Left $ AttrUnparsable "Int") Right $ readMaybe $ T.unpack attr
fromAttribute Nothing = Left AttrMissing
instance FromAttribute a => FromAttribute (Maybe a) where
fromAttribute = traverse $ fromAttribute . Just
instance FromAttribute Bool where
fromAttribute (Just attr) = maybe (Left $ AttrUnparsable "Bool") Right $ readMaybe $ T.unpack attr
fromAttribute Nothing = Left AttrMissing
data ApplyError = ApplyError Path Path deriving (Eq)
instance Show ApplyError where
show (ApplyError tplPth pth) =
"Couldn't find " <> show tplPth <> " relative to " <> show pth <> "."
instance Exception ApplyError
{-# ANN module ("HLint: ignore Use first" :: String) #-}
| positiondev/larceny | src/Web/Larceny/Types.hs | isc | 6,877 | 0 | 11 | 1,962 | 1,202 | 691 | 511 | 87 | 1 |
-- Finally tagless interpreter
-- https://www.codewars.com/kata/5424e3bc430ca2e577000048
{-# LANGUAGE RankNTypes #-}
module Tagless where
import Data.Function (fix)
import Prelude hiding (and, or)
class Language r where
here :: r (a, h) a
before :: r h a -> r (any, h) a
lambda :: r (a, h) b -> r h (a -> b)
apply :: r h (a -> b) -> (r h a -> r h b)
loop :: r h (a -> a) -> r h a
int :: Int -> r h Int
add :: r h Int -> r h Int -> r h Int
down :: r h Int -> r h Int -- \x -> x - 1
up :: r h Int -> r h Int -- \x -> x + 1
mult :: r h Int -> r h Int -> r h Int
gte :: r h Int -> r h Int -> r h Bool
bool :: Bool -> r h Bool
and :: r h Bool -> r h Bool -> r h Bool
or :: r h Bool -> r h Bool -> r h Bool
neg :: r h Bool -> r h Bool
ifte :: r h Bool -> r h a -> r h a -> r h a
newtype L h a = L { run :: h -> a }
arity0 :: a -> L h a
arity0 = L . const
arity1 :: (a -> b) -> L h a -> L h b
arity1 op e = L (op . run e)
arity2 :: (a -> b -> c) -> L h a -> L h b -> L h c
arity2 op e1 e2 = L $ \h -> op (run e1 h) (run e2 h)
instance Language L where
here = L fst
before e = L (run e . snd)
lambda e = L $ \h x -> run e (x, h)
loop e = L (fix . run e)
ifte e1 e2 e3 = L $ \h -> if run e1 h then run e2 h else run e3 h
int = arity0
bool = arity0
down = arity1 pred
up = arity1 succ
neg = arity1 not
add = arity2 (+)
mult = arity2 (*)
gte = arity2 (>=)
apply = arity2 ($)
and = arity2 (&&)
or = arity2 (||)
type Term a = forall r h . Language r => r h a
interpret :: Term a -> a
interpret t = run t ()
| gafiatulin/codewars | src/2 kyu/Tagless.hs | mit | 1,663 | 0 | 10 | 590 | 897 | 460 | 437 | 48 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.