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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..), Counts(..))
import System.Exit (ExitCode(..), exitWith)
import DNA (toRNA)
exitProperly :: IO Counts -> IO ()
exitProperly m = do
counts <- m
exitWith $ if failures counts /= 0 || errors counts /= 0 then ExitFailure 1 else ExitSuccess
testCase :: String -> Assertion -> Test
testCase label assertion = TestLabel label (TestCase assertion)
toRNATests :: [Test]
toRNATests =
[ testCase "transcribes cytidine to guanosine" $
"G" @=? toRNA "C"
, testCase "transcribes guanosine to cytidine" $
"C" @=? toRNA "G"
, testCase "transcribes adenosine to uracil" $
"U" @=? toRNA "A"
, testCase "transcribes thymidine to adenosine" $
"A" @=? toRNA "T"
, testCase "transcribes all ACGT to UGCA" $
"UGCACCAGAAUU" @=? toRNA "ACGTGGTCTTAA"
]
main :: IO ()
main = exitProperly (runTestTT (TestList toRNATests))
| basbossink/exercism | haskell/rna-transcription/rna-transcription_test.hs | gpl-3.0 | 892 | 0 | 12 | 172 | 288 | 150 | 138 | 23 | 2 |
{-# LANGUAGE QuasiQuotes #-}
module Nirum.Docs.HtmlSpec where
import Test.Hspec.Meta
import Text.InterpolatedString.Perl6 (q)
import Nirum.Docs (Html)
import Nirum.Docs.Html (render)
import Nirum.DocsSpec (sampleDocument)
expectedHtml :: Html
expectedHtml = [q|<h1>Hello</h1>
<p>Tight list:</p>
<ul>
<li>List test</li>
<li>test2</li>
</ul>
<p>Loose list:</p>
<ol>
<li><p>a</p></li>
<li><p>b</p></li>
</ol>
<p>A <a href="http://nirum.org/" title="Nirum">complex <em>link</em></a>.</p>
|]
spec :: Spec
spec =
describe "Docs.Html" $
specify "render" $
render sampleDocument `shouldBe` expectedHtml
| spoqa/nirum | test/Nirum/Docs/HtmlSpec.hs | gpl-3.0 | 623 | 0 | 8 | 89 | 103 | 63 | 40 | 14 | 1 |
{-|
A simple 'Amount' is some quantity of money, shares, or anything else.
It has a (possibly null) 'CommoditySymbol' and a numeric quantity:
@
$1
£-50
EUR 3.44
GOOG 500
1.5h
90 apples
0
@
It may also have an assigned 'Price', representing this amount's per-unit
or total cost in a different commodity. If present, this is rendered like
so:
@
EUR 2 \@ $1.50 (unit price)
EUR 2 \@\@ $3 (total price)
@
A 'MixedAmount' is zero or more simple amounts, so can represent multiple
commodities; this is the type most often used:
@
0
$50 + EUR 3
16h + $13.55 + AAPL 500 + 6 oranges
@
A mixed amount is always \"normalised\", it has no more than one amount
in each commodity and price. When calling 'amounts' it will have no zero
amounts, or just a single zero amount and no other amounts.
Limited arithmetic with simple and mixed amounts is supported, best used
with similar amounts since it mostly ignores assigned prices and commodity
exchange rates.
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Hledger.Data.Amount (
-- * Commodity
showCommoditySymbol,
isNonsimpleCommodityChar,
quoteCommoditySymbolIfNeeded,
-- * Amount
amount,
nullamt,
missingamt,
num,
usd,
eur,
gbp,
per,
hrs,
at,
(@@),
amountWithCommodity,
-- ** arithmetic
amountCost,
amountIsZero,
amountLooksZero,
divideAmount,
multiplyAmount,
amountTotalPriceToUnitPrice,
-- ** rendering
AmountDisplayOpts(..),
noColour,
noPrice,
oneLine,
csvDisplay,
amountstyle,
styleAmount,
styleAmountExceptPrecision,
amountUnstyled,
showAmountB,
showAmount,
showAmountPrice,
cshowAmount,
showAmountWithZeroCommodity,
showAmountDebug,
showAmountWithoutPrice,
amountSetPrecision,
withPrecision,
amountSetFullPrecision,
setAmountInternalPrecision,
withInternalPrecision,
setAmountDecimalPoint,
withDecimalPoint,
amountStripPrices,
canonicaliseAmount,
-- * MixedAmount
nullmixedamt,
missingmixedamt,
isMissingMixedAmount,
mixed,
mixedAmount,
maAddAmount,
maAddAmounts,
amounts,
amountsRaw,
maCommodities,
filterMixedAmount,
filterMixedAmountByCommodity,
mapMixedAmount,
unifyMixedAmount,
mixedAmountStripPrices,
-- ** arithmetic
mixedAmountCost,
maNegate,
maPlus,
maMinus,
maSum,
divideMixedAmount,
multiplyMixedAmount,
averageMixedAmounts,
isNegativeAmount,
isNegativeMixedAmount,
mixedAmountIsZero,
maIsZero,
maIsNonZero,
mixedAmountLooksZero,
mixedAmountTotalPriceToUnitPrice,
-- ** rendering
styleMixedAmount,
mixedAmountUnstyled,
showMixedAmount,
showMixedAmountOneLine,
showMixedAmountDebug,
showMixedAmountWithoutPrice,
showMixedAmountOneLineWithoutPrice,
showMixedAmountElided,
showMixedAmountWithZeroCommodity,
showMixedAmountB,
showMixedAmountLinesB,
wbToText,
wbUnpack,
mixedAmountSetPrecision,
mixedAmountSetFullPrecision,
canonicaliseMixedAmount,
-- * misc.
ltraceamount,
tests_Amount
) where
import Control.Applicative (liftA2)
import Control.Monad (foldM)
import Data.Char (isDigit)
import Data.Decimal (DecimalRaw(..), decimalPlaces, normalizeDecimal, roundTo)
import Data.Default (Default(..))
import Data.Foldable (toList)
import Data.List (find, foldl', intercalate, intersperse, mapAccumL, partition)
import Data.List.NonEmpty (NonEmpty(..), nonEmpty)
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import Data.Maybe (fromMaybe, isNothing, isJust)
import Data.Semigroup (Semigroup(..))
import qualified Data.Text as T
import qualified Data.Text.Lazy.Builder as TB
import Data.Word (Word8)
import Safe (headDef, lastDef, lastMay)
import System.Console.ANSI (Color(..),ColorIntensity(..))
import Debug.Trace (trace)
import Test.Tasty (testGroup)
import Test.Tasty.HUnit ((@?=), assertBool, testCase)
import Hledger.Data.Types
import Hledger.Utils (colorB)
import Hledger.Utils.Text (textQuoteIfNeeded)
import Text.WideString (WideBuilder(..), wbFromText, wbToText, wbUnpack)
-- A 'Commodity' is a symbol representing a currency or some other kind of
-- thing we are tracking, and some display preferences that tell how to
-- display 'Amount's of the commodity - is the symbol on the left or right,
-- are thousands separated by comma, significant decimal places and so on.
-- | Show space-containing commodity symbols quoted, as they are in a journal.
showCommoditySymbol :: T.Text -> T.Text
showCommoditySymbol = textQuoteIfNeeded
-- characters that may not be used in a non-quoted commodity symbol
isNonsimpleCommodityChar :: Char -> Bool
isNonsimpleCommodityChar = liftA2 (||) isDigit isOther
where
otherChars = "-+.@*;\t\n \"{}=" :: T.Text
isOther c = T.any (==c) otherChars
quoteCommoditySymbolIfNeeded :: T.Text -> T.Text
quoteCommoditySymbolIfNeeded s
| T.any isNonsimpleCommodityChar s = "\"" <> s <> "\""
| otherwise = s
-- | Options for the display of Amount and MixedAmount.
data AmountDisplayOpts = AmountDisplayOpts
{ displayPrice :: Bool -- ^ Whether to display the Price of an Amount.
, displayZeroCommodity :: Bool -- ^ If the Amount rounds to 0, whether to display its commodity string.
, displayThousandsSep :: Bool -- ^ Whether to display thousands separators.
, displayColour :: Bool -- ^ Whether to colourise negative Amounts.
, displayOneLine :: Bool -- ^ Whether to display on one line.
, displayMinWidth :: Maybe Int -- ^ Minimum width to pad to
, displayMaxWidth :: Maybe Int -- ^ Maximum width to clip to
-- | Display amounts in this order (without the commodity symbol) and display
-- a 0 in case a corresponding commodity does not exist
, displayOrder :: Maybe [CommoditySymbol]
} deriving (Show)
-- | Display Amount and MixedAmount with no colour.
instance Default AmountDisplayOpts where def = noColour
-- | Display Amount and MixedAmount with no colour.
noColour :: AmountDisplayOpts
noColour = AmountDisplayOpts { displayPrice = True
, displayColour = False
, displayZeroCommodity = False
, displayThousandsSep = True
, displayOneLine = False
, displayMinWidth = Just 0
, displayMaxWidth = Nothing
, displayOrder = Nothing
}
-- | Display Amount and MixedAmount with no prices.
noPrice :: AmountDisplayOpts
noPrice = def{displayPrice=False}
-- | Display Amount and MixedAmount on one line with no prices.
oneLine :: AmountDisplayOpts
oneLine = def{displayOneLine=True, displayPrice=False}
-- | Display Amount and MixedAmount in a form suitable for CSV output.
csvDisplay :: AmountDisplayOpts
csvDisplay = oneLine{displayThousandsSep=False}
-------------------------------------------------------------------------------
-- Amount styles
-- | Default amount style
amountstyle = AmountStyle L False (Precision 0) (Just '.') Nothing
-------------------------------------------------------------------------------
-- Amount
instance Num Amount where
abs a@Amount{aquantity=q} = a{aquantity=abs q}
signum a@Amount{aquantity=q} = a{aquantity=signum q}
fromInteger i = nullamt{aquantity=fromInteger i}
negate = transformAmount negate
(+) = similarAmountsOp (+)
(-) = similarAmountsOp (-)
(*) = similarAmountsOp (*)
-- | The empty simple amount.
amount, nullamt :: Amount
amount = Amount{acommodity="", aquantity=0, aprice=Nothing, astyle=amountstyle}
nullamt = amount
-- | A temporary value for parsed transactions which had no amount specified.
missingamt :: Amount
missingamt = amount{acommodity="AUTO"}
-- Handy amount constructors for tests.
-- usd/eur/gbp round their argument to a whole number of pennies/cents.
num n = amount{acommodity="", aquantity=n}
hrs n = amount{acommodity="h", aquantity=n, astyle=amountstyle{asprecision=Precision 2, ascommodityside=R}}
usd n = amount{acommodity="$", aquantity=roundTo 2 n, astyle=amountstyle{asprecision=Precision 2}}
eur n = amount{acommodity="€", aquantity=roundTo 2 n, astyle=amountstyle{asprecision=Precision 2}}
gbp n = amount{acommodity="£", aquantity=roundTo 2 n, astyle=amountstyle{asprecision=Precision 2}}
per n = amount{acommodity="%", aquantity=n, astyle=amountstyle{asprecision=Precision 1, ascommodityside=R, ascommodityspaced=True}}
amt `at` priceamt = amt{aprice=Just $ UnitPrice priceamt}
amt @@ priceamt = amt{aprice=Just $ TotalPrice priceamt}
-- | Apply a binary arithmetic operator to two amounts, which should
-- be in the same commodity if non-zero (warning, this is not checked).
-- A zero result keeps the commodity of the second amount.
-- The result's display style is that of the second amount, with
-- precision set to the highest of either amount.
-- Prices are ignored and discarded.
-- Remember: the caller is responsible for ensuring both amounts have the same commodity.
similarAmountsOp :: (Quantity -> Quantity -> Quantity) -> Amount -> Amount -> Amount
similarAmountsOp op Amount{acommodity=_, aquantity=q1, astyle=AmountStyle{asprecision=p1}}
Amount{acommodity=c2, aquantity=q2, astyle=s2@AmountStyle{asprecision=p2}} =
-- trace ("a1:"++showAmountDebug a1) $ trace ("a2:"++showAmountDebug a2) $ traceWith (("= :"++).showAmountDebug)
amount{acommodity=c2, aquantity=q1 `op` q2, astyle=s2{asprecision=max p1 p2}}
-- c1==c2 || q1==0 || q2==0 =
-- otherwise = error "tried to do simple arithmetic with amounts in different commodities"
-- | Convert an amount to the specified commodity, ignoring and discarding
-- any assigned prices and assuming an exchange rate of 1.
amountWithCommodity :: CommoditySymbol -> Amount -> Amount
amountWithCommodity c a = a{acommodity=c, aprice=Nothing}
-- | Convert a amount to its "cost" or "selling price" in another commodity,
-- using its attached transaction price if it has one. Notes:
--
-- - price amounts must be MixedAmounts with exactly one component Amount
-- (or there will be a runtime error XXX)
--
-- - price amounts should be positive in the Journal
-- (though this is currently not enforced)
amountCost :: Amount -> Amount
amountCost a@Amount{aquantity=q, aprice=mp} =
case mp of
Nothing -> a
Just (UnitPrice p@Amount{aquantity=pq}) -> p{aquantity=pq * q}
Just (TotalPrice p@Amount{aquantity=pq}) -> p{aquantity=pq}
-- | Replace an amount's TotalPrice, if it has one, with an equivalent UnitPrice.
-- Has no effect on amounts without one.
-- Also increases the unit price's display precision to show one extra decimal place,
-- to help keep transaction amounts balancing.
-- Does Decimal division, might be some rounding/irrational number issues.
amountTotalPriceToUnitPrice :: Amount -> Amount
amountTotalPriceToUnitPrice
a@Amount{aquantity=q, aprice=Just (TotalPrice pa@Amount{aquantity=pq, astyle=ps})}
= a{aprice = Just $ UnitPrice pa{aquantity=abs (pq/q), astyle=ps{asprecision=pp}}}
where
-- Increase the precision by 1, capping at the max bound.
pp = case asprecision ps of
NaturalPrecision -> NaturalPrecision
Precision p -> Precision $ if p == maxBound then maxBound else p + 1
amountTotalPriceToUnitPrice a = a
-- | Apply a function to an amount's quantity (and its total price, if it has one).
transformAmount :: (Quantity -> Quantity) -> Amount -> Amount
transformAmount f a@Amount{aquantity=q,aprice=p} = a{aquantity=f q, aprice=f' <$> p}
where
f' (TotalPrice a@Amount{aquantity=pq}) = TotalPrice a{aquantity = f pq}
f' p = p
-- | Divide an amount's quantity (and its total price, if it has one) by a constant.
divideAmount :: Quantity -> Amount -> Amount
divideAmount n = transformAmount (/n)
-- | Multiply an amount's quantity (and its total price, if it has one) by a constant.
multiplyAmount :: Quantity -> Amount -> Amount
multiplyAmount n = transformAmount (*n)
-- | Is this amount negative ? The price is ignored.
isNegativeAmount :: Amount -> Bool
isNegativeAmount Amount{aquantity=q} = q < 0
-- | Round an Amount's Quantity to its specified display precision. If that is
-- NaturalPrecision, this does nothing.
amountRoundedQuantity :: Amount -> Quantity
amountRoundedQuantity Amount{aquantity=q, astyle=AmountStyle{asprecision=p}} = case p of
NaturalPrecision -> q
Precision p' -> roundTo p' q
-- | Apply a test to both an Amount and its total price, if it has one.
testAmountAndTotalPrice :: (Amount -> Bool) -> Amount -> Bool
testAmountAndTotalPrice f amt = case aprice amt of
Just (TotalPrice price) -> f amt && f price
_ -> f amt
-- | Do this Amount and (and its total price, if it has one) appear to be zero when rendered with its
-- display precision ?
amountLooksZero :: Amount -> Bool
amountLooksZero = testAmountAndTotalPrice looksZero
where
looksZero Amount{aquantity=Decimal e q, astyle=AmountStyle{asprecision=p}} = case p of
Precision d -> if e > d then abs q <= 5*10^(e-d-1) else q == 0
NaturalPrecision -> q == 0
-- | Is this Amount (and its total price, if it has one) exactly zero, ignoring its display precision ?
amountIsZero :: Amount -> Bool
amountIsZero = testAmountAndTotalPrice (\Amount{aquantity=Decimal _ q} -> q == 0)
-- | Set an amount's display precision, flipped.
withPrecision :: Amount -> AmountPrecision -> Amount
withPrecision = flip amountSetPrecision
-- | Set an amount's display precision.
amountSetPrecision :: AmountPrecision -> Amount -> Amount
amountSetPrecision p a@Amount{astyle=s} = a{astyle=s{asprecision=p}}
-- | Increase an amount's display precision, if needed, to enough decimal places
-- to show it exactly (showing all significant decimal digits, excluding trailing
-- zeros).
amountSetFullPrecision :: Amount -> Amount
amountSetFullPrecision a = amountSetPrecision p a
where
p = max displayprecision naturalprecision
displayprecision = asprecision $ astyle a
naturalprecision = Precision . decimalPlaces . normalizeDecimal $ aquantity a
-- | Set an amount's internal precision, ie rounds the Decimal representing
-- the amount's quantity to some number of decimal places.
-- Rounding is done with Data.Decimal's default roundTo function:
-- "If the value ends in 5 then it is rounded to the nearest even value (Banker's Rounding)".
-- Does not change the amount's display precision.
-- Intended mainly for internal use, eg when comparing amounts in tests.
setAmountInternalPrecision :: Word8 -> Amount -> Amount
setAmountInternalPrecision p a@Amount{ aquantity=q, astyle=s } = a{
astyle=s{asprecision=Precision p}
,aquantity=roundTo p q
}
-- | Set an amount's internal precision, flipped.
-- Intended mainly for internal use, eg when comparing amounts in tests.
withInternalPrecision :: Amount -> Word8 -> Amount
withInternalPrecision = flip setAmountInternalPrecision
-- | Set (or clear) an amount's display decimal point.
setAmountDecimalPoint :: Maybe Char -> Amount -> Amount
setAmountDecimalPoint mc a@Amount{ astyle=s } = a{ astyle=s{asdecimalpoint=mc} }
-- | Set (or clear) an amount's display decimal point, flipped.
withDecimalPoint :: Amount -> Maybe Char -> Amount
withDecimalPoint = flip setAmountDecimalPoint
-- | Strip all prices from an Amount
amountStripPrices :: Amount -> Amount
amountStripPrices a = a{aprice=Nothing}
showAmountPrice :: Amount -> WideBuilder
showAmountPrice amt = case aprice amt of
Nothing -> mempty
Just (UnitPrice pa) -> WideBuilder (TB.fromString " @ ") 3 <> showAmountB noColour pa
Just (TotalPrice pa) -> WideBuilder (TB.fromString " @@ ") 4 <> showAmountB noColour (sign pa)
where sign = if aquantity amt < 0 then negate else id
showAmountPriceDebug :: Maybe AmountPrice -> String
showAmountPriceDebug Nothing = ""
showAmountPriceDebug (Just (UnitPrice pa)) = " @ " ++ showAmountDebug pa
showAmountPriceDebug (Just (TotalPrice pa)) = " @@ " ++ showAmountDebug pa
-- | Given a map of standard commodity display styles, apply the
-- appropriate one to this amount. If there's no standard style for
-- this amount's commodity, return the amount unchanged.
-- Also apply the style to the price (except for precision)
styleAmount :: M.Map CommoditySymbol AmountStyle -> Amount -> Amount
styleAmount styles a = styledAmount{aprice = stylePrice styles (aprice styledAmount)}
where
styledAmount = case M.lookup (acommodity a) styles of
Just s -> a{astyle=s}
Nothing -> a
stylePrice :: M.Map CommoditySymbol AmountStyle -> Maybe AmountPrice -> Maybe AmountPrice
stylePrice styles (Just (UnitPrice a)) = Just (UnitPrice $ styleAmountExceptPrecision styles a)
stylePrice styles (Just (TotalPrice a)) = Just (TotalPrice $ styleAmountExceptPrecision styles a)
stylePrice _ _ = Nothing
-- | Like styleAmount, but keep the number of decimal places unchanged.
styleAmountExceptPrecision :: M.Map CommoditySymbol AmountStyle -> Amount -> Amount
styleAmountExceptPrecision styles a@Amount{astyle=AmountStyle{asprecision=origp}} =
case M.lookup (acommodity a) styles of
Just s -> a{astyle=s{asprecision=origp}}
Nothing -> a
-- | Reset this amount's display style to the default.
amountUnstyled :: Amount -> Amount
amountUnstyled a = a{astyle=amountstyle}
-- | Get the string representation of an amount, based on its
-- commodity's display settings. String representations equivalent to
-- zero are converted to just \"0\". The special "missing" amount is
-- displayed as the empty string.
--
-- > showAmount = wbUnpack . showAmountB noColour
showAmount :: Amount -> String
showAmount = wbUnpack . showAmountB noColour
-- | General function to generate a WideBuilder for an Amount, according the
-- supplied AmountDisplayOpts. The special "missing" amount is displayed as
-- the empty string. This is the main function to use for showing
-- Amounts, constructing a builder; it can then be converted to a Text with
-- wbToText, or to a String with wbUnpack.
showAmountB :: AmountDisplayOpts -> Amount -> WideBuilder
showAmountB _ Amount{acommodity="AUTO"} = mempty
showAmountB opts a@Amount{astyle=style} =
color $ case ascommodityside style of
L -> showC (wbFromText c) space <> quantity' <> price
R -> quantity' <> showC space (wbFromText c) <> price
where
quantity = showamountquantity $ if displayThousandsSep opts then a else a{astyle=(astyle a){asdigitgroups=Nothing}}
(quantity',c) | amountLooksZero a && not (displayZeroCommodity opts) = (WideBuilder (TB.singleton '0') 1,"")
| otherwise = (quantity, quoteCommoditySymbolIfNeeded $ acommodity a)
space = if not (T.null c) && ascommodityspaced style then WideBuilder (TB.singleton ' ') 1 else mempty
showC l r = if isJust (displayOrder opts) then mempty else l <> r
price = if displayPrice opts then showAmountPrice a else mempty
color = if displayColour opts && isNegativeAmount a then colorB Dull Red else id
-- | Colour version. For a negative amount, adds ANSI codes to change the colour,
-- currently to hard-coded red.
--
-- > cshowAmount = wbUnpack . showAmountB def{displayColour=True}
cshowAmount :: Amount -> String
cshowAmount = wbUnpack . showAmountB def{displayColour=True}
-- | Get the string representation of an amount, without any \@ price.
--
-- > showAmountWithoutPrice = wbUnpack . showAmountB noPrice
showAmountWithoutPrice :: Amount -> String
showAmountWithoutPrice = wbUnpack . showAmountB noPrice
-- | Like showAmount, but show a zero amount's commodity if it has one.
--
-- > showAmountWithZeroCommodity = wbUnpack . showAmountB noColour{displayZeryCommodity=True}
showAmountWithZeroCommodity :: Amount -> String
showAmountWithZeroCommodity = wbUnpack . showAmountB noColour{displayZeroCommodity=True}
-- | Get a string representation of an amount for debugging,
-- appropriate to the current debug level. 9 shows maximum detail.
showAmountDebug :: Amount -> String
showAmountDebug Amount{acommodity="AUTO"} = "(missing)"
showAmountDebug Amount{..} =
"Amount {acommodity=" ++ show acommodity ++ ", aquantity=" ++ show aquantity
++ ", aprice=" ++ showAmountPriceDebug aprice ++ ", astyle=" ++ show astyle ++ "}"
-- | Get a Text Builder for the string representation of the number part of of an amount,
-- using the display settings from its commodity. Also returns the width of the
-- number.
showamountquantity :: Amount -> WideBuilder
showamountquantity amt@Amount{astyle=AmountStyle{asdecimalpoint=mdec, asdigitgroups=mgrps}} =
signB <> intB <> fracB
where
Decimal e n = amountRoundedQuantity amt
strN = T.pack . show $ abs n
len = T.length strN
intLen = max 1 $ len - fromIntegral e
dec = fromMaybe '.' mdec
padded = T.replicate (fromIntegral e + 1 - len) "0" <> strN
(intPart, fracPart) = T.splitAt intLen padded
intB = applyDigitGroupStyle mgrps intLen $ if e == 0 then strN else intPart
signB = if n < 0 then WideBuilder (TB.singleton '-') 1 else mempty
fracB = if e > 0 then WideBuilder (TB.singleton dec <> TB.fromText fracPart) (fromIntegral e + 1) else mempty
-- | Split a string representation into chunks according to DigitGroupStyle,
-- returning a Text builder and the number of separators used.
applyDigitGroupStyle :: Maybe DigitGroupStyle -> Int -> T.Text -> WideBuilder
applyDigitGroupStyle Nothing l s = WideBuilder (TB.fromText s) l
applyDigitGroupStyle (Just (DigitGroups _ [])) l s = WideBuilder (TB.fromText s) l
applyDigitGroupStyle (Just (DigitGroups c (g:gs))) l s = addseps (g:|gs) (toInteger l) s
where
addseps (g:|gs) l s
| l' > 0 = addseps gs' l' rest <> WideBuilder (TB.singleton c <> TB.fromText part) (fromIntegral g + 1)
| otherwise = WideBuilder (TB.fromText s) (fromInteger l)
where
(rest, part) = T.splitAt (fromInteger l') s
gs' = fromMaybe (g:|[]) $ nonEmpty gs
l' = l - toInteger g
-- like journalCanonicaliseAmounts
-- | Canonicalise an amount's display style using the provided commodity style map.
canonicaliseAmount :: M.Map CommoditySymbol AmountStyle -> Amount -> Amount
canonicaliseAmount styles a@Amount{acommodity=c, astyle=s} = a{astyle=s'}
where s' = M.findWithDefault s c styles
-------------------------------------------------------------------------------
-- MixedAmount
instance Semigroup MixedAmount where
(<>) = maPlus
sconcat = maSum
stimes n = multiplyMixedAmount (fromIntegral n)
instance Monoid MixedAmount where
mempty = nullmixedamt
mconcat = maSum
instance Num MixedAmount where
fromInteger = mixedAmount . fromInteger
negate = maNegate
(+) = maPlus
(*) = error "error, mixed amounts do not support multiplication" -- PARTIAL:
abs = error "error, mixed amounts do not support abs"
signum = error "error, mixed amounts do not support signum"
-- | Calculate the key used to store an Amount within a MixedAmount.
amountKey :: Amount -> MixedAmountKey
amountKey amt@Amount{acommodity=c} = case aprice amt of
Nothing -> MixedAmountKeyNoPrice c
Just (TotalPrice p) -> MixedAmountKeyTotalPrice c (acommodity p)
Just (UnitPrice p) -> MixedAmountKeyUnitPrice c (acommodity p) (aquantity p)
-- | The empty mixed amount.
nullmixedamt :: MixedAmount
nullmixedamt = Mixed mempty
-- | A temporary value for parsed transactions which had no amount specified.
missingmixedamt :: MixedAmount
missingmixedamt = mixedAmount missingamt
-- | Whether a MixedAmount has a missing amount
isMissingMixedAmount :: MixedAmount -> Bool
isMissingMixedAmount (Mixed ma) = amountKey missingamt `M.member` ma
-- | Convert amounts in various commodities into a mixed amount.
mixed :: Foldable t => t Amount -> MixedAmount
mixed = maAddAmounts nullmixedamt
-- | Create a MixedAmount from a single Amount.
mixedAmount :: Amount -> MixedAmount
mixedAmount a = Mixed $ M.singleton (amountKey a) a
-- | Add an Amount to a MixedAmount, normalising the result.
maAddAmount :: MixedAmount -> Amount -> MixedAmount
maAddAmount (Mixed ma) a = Mixed $ M.insertWith sumSimilarAmountsUsingFirstPrice (amountKey a) a ma
-- | Add a collection of Amounts to a MixedAmount, normalising the result.
maAddAmounts :: Foldable t => MixedAmount -> t Amount -> MixedAmount
maAddAmounts = foldl' maAddAmount
-- | Negate mixed amount's quantities (and total prices, if any).
maNegate :: MixedAmount -> MixedAmount
maNegate = transformMixedAmount negate
-- | Sum two MixedAmount.
maPlus :: MixedAmount -> MixedAmount -> MixedAmount
maPlus (Mixed as) (Mixed bs) = Mixed $ M.unionWith sumSimilarAmountsUsingFirstPrice as bs
-- | Subtract a MixedAmount from another.
maMinus :: MixedAmount -> MixedAmount -> MixedAmount
maMinus a = maPlus a . maNegate
-- | Sum a collection of MixedAmounts.
maSum :: Foldable t => t MixedAmount -> MixedAmount
maSum = foldl' maPlus nullmixedamt
-- | Divide a mixed amount's quantities (and total prices, if any) by a constant.
divideMixedAmount :: Quantity -> MixedAmount -> MixedAmount
divideMixedAmount n = transformMixedAmount (/n)
-- | Multiply a mixed amount's quantities (and total prices, if any) by a constant.
multiplyMixedAmount :: Quantity -> MixedAmount -> MixedAmount
multiplyMixedAmount n = transformMixedAmount (*n)
-- | Apply a function to a mixed amount's quantities (and its total prices, if it has any).
transformMixedAmount :: (Quantity -> Quantity) -> MixedAmount -> MixedAmount
transformMixedAmount f = mapMixedAmountUnsafe (transformAmount f)
-- | Calculate the average of some mixed amounts.
averageMixedAmounts :: [MixedAmount] -> MixedAmount
averageMixedAmounts as = fromIntegral (length as) `divideMixedAmount` maSum as
-- | Is this mixed amount negative, if we can tell that unambiguously?
-- Ie when normalised, are all individual commodity amounts negative ?
isNegativeMixedAmount :: MixedAmount -> Maybe Bool
isNegativeMixedAmount m =
case amounts $ mixedAmountStripPrices m of
[] -> Just False
[a] -> Just $ isNegativeAmount a
as | all isNegativeAmount as -> Just True
as | not (any isNegativeAmount as) -> Just False
_ -> Nothing -- multiple amounts with different signs
-- | Does this mixed amount appear to be zero when rendered with its display precision?
-- i.e. does it have zero quantity with no price, zero quantity with a total price (which is also zero),
-- and zero quantity for each unit price?
mixedAmountLooksZero :: MixedAmount -> Bool
mixedAmountLooksZero (Mixed ma) = all amountLooksZero ma
-- | Is this mixed amount exactly zero, ignoring its display precision?
-- i.e. does it have zero quantity with no price, zero quantity with a total price (which is also zero),
-- and zero quantity for each unit price?
mixedAmountIsZero :: MixedAmount -> Bool
mixedAmountIsZero (Mixed ma) = all amountIsZero ma
-- | Is this mixed amount exactly zero, ignoring its display precision?
--
-- A convenient alias for mixedAmountIsZero.
maIsZero :: MixedAmount -> Bool
maIsZero = mixedAmountIsZero
-- | Is this mixed amount non-zero, ignoring its display precision?
--
-- A convenient alias for not . mixedAmountIsZero.
maIsNonZero :: MixedAmount -> Bool
maIsNonZero = not . mixedAmountIsZero
-- | Get a mixed amount's component amounts.
--
-- * amounts in the same commodity are combined unless they have different prices or total prices
--
-- * multiple zero amounts, all with the same non-null commodity, are replaced by just the last of them, preserving the commodity and amount style (all but the last zero amount are discarded)
--
-- * multiple zero amounts with multiple commodities, or no commodities, are replaced by one commodity-less zero amount
--
-- * an empty amount list is replaced by one commodity-less zero amount
--
-- * the special "missing" mixed amount remains unchanged
--
amounts :: MixedAmount -> [Amount]
amounts (Mixed ma)
| isMissingMixedAmount (Mixed ma) = [missingamt] -- missingamt should always be alone, but detect it even if not
| M.null nonzeros = [newzero]
| otherwise = toList nonzeros
where
newzero = fromMaybe nullamt $ find (not . T.null . acommodity) zeros
(zeros, nonzeros) = M.partition amountIsZero ma
-- | Get a mixed amount's component amounts without normalising zero and missing
-- amounts. This is used for JSON serialisation, so the order is important. In
-- particular, we want the Amounts given in the order of the MixedAmountKeys,
-- i.e. lexicographically first by commodity, then by price commodity, then by
-- unit price from most negative to most positive.
amountsRaw :: MixedAmount -> [Amount]
amountsRaw (Mixed ma) = toList ma
-- | Get this mixed amount's commodities as a set.
-- Returns an empty set if there are no amounts.
maCommodities :: MixedAmount -> S.Set CommoditySymbol
maCommodities = S.fromList . fmap acommodity . amounts'
where amounts' ma@(Mixed m) = if M.null m then [] else amounts ma
-- | Unify a MixedAmount to a single commodity value if possible.
-- This consolidates amounts of the same commodity and discards zero
-- amounts; but this one insists on simplifying to a single commodity,
-- and will return Nothing if this is not possible.
unifyMixedAmount :: MixedAmount -> Maybe Amount
unifyMixedAmount = foldM combine 0 . amounts
where
combine amount result
| amountIsZero amount = Just result
| amountIsZero result = Just amount
| acommodity amount == acommodity result = Just $ amount + result
| otherwise = Nothing
-- | Sum same-commodity amounts in a lossy way, applying the first
-- price to the result and discarding any other prices. Only used as a
-- rendering helper.
sumSimilarAmountsUsingFirstPrice :: Amount -> Amount -> Amount
sumSimilarAmountsUsingFirstPrice a b = (a + b){aprice=p}
where
p = case (aprice a, aprice b) of
(Just (TotalPrice ap), Just (TotalPrice bp))
-> Just . TotalPrice $ ap{aquantity = aquantity ap + aquantity bp }
_ -> aprice a
-- -- | Sum same-commodity amounts. If there were different prices, set
-- -- the price to a special marker indicating "various". Only used as a
-- -- rendering helper.
-- sumSimilarAmountsNotingPriceDifference :: [Amount] -> Amount
-- sumSimilarAmountsNotingPriceDifference [] = nullamt
-- sumSimilarAmountsNotingPriceDifference as = undefined
-- | Filter a mixed amount's component amounts by a predicate.
filterMixedAmount :: (Amount -> Bool) -> MixedAmount -> MixedAmount
filterMixedAmount p (Mixed ma) = Mixed $ M.filter p ma
-- | Return an unnormalised MixedAmount containing exactly one Amount
-- with the specified commodity and the quantity of that commodity
-- found in the original. NB if Amount's quantity is zero it will be
-- discarded next time the MixedAmount gets normalised.
filterMixedAmountByCommodity :: CommoditySymbol -> MixedAmount -> MixedAmount
filterMixedAmountByCommodity c (Mixed ma)
| M.null ma' = mixedAmount nullamt{acommodity=c}
| otherwise = Mixed ma'
where ma' = M.filter ((c==) . acommodity) ma
-- | Apply a transform to a mixed amount's component 'Amount's.
mapMixedAmount :: (Amount -> Amount) -> MixedAmount -> MixedAmount
mapMixedAmount f (Mixed ma) = mixed . map f $ toList ma
-- | Apply a transform to a mixed amount's component 'Amount's, which does not
-- affect the key of the amount (i.e. doesn't change the commodity, price
-- commodity, or unit price amount). This condition is not checked.
mapMixedAmountUnsafe :: (Amount -> Amount) -> MixedAmount -> MixedAmount
mapMixedAmountUnsafe f (Mixed ma) = Mixed $ M.map f ma -- Use M.map instead of fmap to maintain strictness
-- | Convert all component amounts to cost/selling price where
-- possible (see amountCost).
mixedAmountCost :: MixedAmount -> MixedAmount
mixedAmountCost (Mixed ma) =
foldl' (\m a -> maAddAmount m (amountCost a)) (Mixed noPrices) withPrices
where (noPrices, withPrices) = M.partition (isNothing . aprice) ma
-- -- | MixedAmount derived Eq instance in Types.hs doesn't know that we
-- -- want $0 = EUR0 = 0. Yet we don't want to drag all this code over there.
-- -- For now, use this when cross-commodity zero equality is important.
-- mixedAmountEquals :: MixedAmount -> MixedAmount -> Bool
-- mixedAmountEquals a b = amounts a' == amounts b' || (mixedAmountLooksZero a' && mixedAmountLooksZero b')
-- where a' = mixedAmountStripPrices a
-- b' = mixedAmountStripPrices b
-- | Given a map of standard commodity display styles, apply the
-- appropriate one to each individual amount.
styleMixedAmount :: M.Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
styleMixedAmount styles = mapMixedAmountUnsafe (styleAmount styles)
-- | Reset each individual amount's display style to the default.
mixedAmountUnstyled :: MixedAmount -> MixedAmount
mixedAmountUnstyled = mapMixedAmountUnsafe amountUnstyled
-- | Get the string representation of a mixed amount, after
-- normalising it to one amount per commodity. Assumes amounts have
-- no or similar prices, otherwise this can show misleading prices.
--
-- > showMixedAmount = wbUnpack . showMixedAmountB noColour
showMixedAmount :: MixedAmount -> String
showMixedAmount = wbUnpack . showMixedAmountB noColour
-- | Get the one-line string representation of a mixed amount.
--
-- > showMixedAmountOneLine = wbUnpack . showMixedAmountB oneLine
showMixedAmountOneLine :: MixedAmount -> String
showMixedAmountOneLine = wbUnpack . showMixedAmountB oneLine
-- | Like showMixedAmount, but zero amounts are shown with their
-- commodity if they have one.
--
-- > showMixedAmountWithZeroCommodity = wbUnpack . showMixedAmountB noColour{displayZeroCommodity=True}
showMixedAmountWithZeroCommodity :: MixedAmount -> String
showMixedAmountWithZeroCommodity = wbUnpack . showMixedAmountB noColour{displayZeroCommodity=True}
-- | Get the string representation of a mixed amount, without showing any transaction prices.
-- With a True argument, adds ANSI codes to show negative amounts in red.
--
-- > showMixedAmountWithoutPrice c = wbUnpack . showMixedAmountB noPrice{displayColour=c}
showMixedAmountWithoutPrice :: Bool -> MixedAmount -> String
showMixedAmountWithoutPrice c = wbUnpack . showMixedAmountB noPrice{displayColour=c}
-- | Get the one-line string representation of a mixed amount, but without
-- any \@ prices.
-- With a True argument, adds ANSI codes to show negative amounts in red.
--
-- > showMixedAmountOneLineWithoutPrice c = wbUnpack . showMixedAmountB oneLine{displayColour=c}
showMixedAmountOneLineWithoutPrice :: Bool -> MixedAmount -> String
showMixedAmountOneLineWithoutPrice c = wbUnpack . showMixedAmountB oneLine{displayColour=c}
-- | Like showMixedAmountOneLineWithoutPrice, but show at most the given width,
-- with an elision indicator if there are more.
-- With a True argument, adds ANSI codes to show negative amounts in red.
--
-- > showMixedAmountElided w c = wbUnpack . showMixedAmountB oneLine{displayColour=c, displayMaxWidth=Just w}
showMixedAmountElided :: Int -> Bool -> MixedAmount -> String
showMixedAmountElided w c = wbUnpack . showMixedAmountB oneLine{displayColour=c, displayMaxWidth=Just w}
-- | Get an unambiguous string representation of a mixed amount for debugging.
showMixedAmountDebug :: MixedAmount -> String
showMixedAmountDebug m | m == missingmixedamt = "(missing)"
| otherwise = "Mixed [" ++ as ++ "]"
where as = intercalate "\n " $ map showAmountDebug $ amounts m
-- | General function to generate a WideBuilder for a MixedAmount, according to the
-- supplied AmountDisplayOpts. This is the main function to use for showing
-- MixedAmounts, constructing a builder; it can then be converted to a Text with
-- wbToText, or to a String with wbUnpack.
--
-- If a maximum width is given then:
-- - If displayed on one line, it will display as many Amounts as can
-- fit in the given width, and further Amounts will be elided. There
-- will always be at least one amount displayed, even if this will
-- exceed the requested maximum width.
-- - If displayed on multiple lines, any Amounts longer than the
-- maximum width will be elided.
showMixedAmountB :: AmountDisplayOpts -> MixedAmount -> WideBuilder
showMixedAmountB opts ma
| displayOneLine opts = showMixedAmountOneLineB opts ma
| otherwise = WideBuilder (wbBuilder . mconcat $ intersperse sep lines) width
where
lines = showMixedAmountLinesB opts ma
width = headDef 0 $ map wbWidth lines
sep = WideBuilder (TB.singleton '\n') 0
-- | Helper for showMixedAmountB to show a list of Amounts on multiple lines. This returns
-- the list of WideBuilders: one for each Amount, and padded/elided to the appropriate
-- width. This does not honour displayOneLine: all amounts will be displayed as if
-- displayOneLine were False.
showMixedAmountLinesB :: AmountDisplayOpts -> MixedAmount -> [WideBuilder]
showMixedAmountLinesB opts@AmountDisplayOpts{displayMaxWidth=mmax,displayMinWidth=mmin} ma =
map (adBuilder . pad) elided
where
astrs = amtDisplayList (wbWidth sep) (showAmountB opts) . orderedAmounts opts $
if displayPrice opts then ma else mixedAmountStripPrices ma
sep = WideBuilder (TB.singleton '\n') 0
width = maximum $ map (wbWidth . adBuilder) elided
pad amt
| Just mw <- mmin =
let w = (max width mw) - wbWidth (adBuilder amt)
in amt{ adBuilder = WideBuilder (TB.fromText $ T.replicate w " ") w <> adBuilder amt }
| otherwise = amt
elided = maybe id elideTo mmax astrs
elideTo m xs = maybeAppend elisionStr short
where
elisionStr = elisionDisplay (Just m) (wbWidth sep) (length long) $ lastDef nullAmountDisplay short
(short, long) = partition ((m>=) . wbWidth . adBuilder) xs
-- | Helper for showMixedAmountB to deal with single line displays. This does not
-- honour displayOneLine: all amounts will be displayed as if displayOneLine
-- were True.
showMixedAmountOneLineB :: AmountDisplayOpts -> MixedAmount -> WideBuilder
showMixedAmountOneLineB opts@AmountDisplayOpts{displayMaxWidth=mmax,displayMinWidth=mmin} ma =
WideBuilder (wbBuilder . pad . mconcat . intersperse sep $ map adBuilder elided)
. max width $ fromMaybe 0 mmin
where
width = maybe 0 adTotal $ lastMay elided
astrs = amtDisplayList (wbWidth sep) (showAmountB opts) . orderedAmounts opts $
if displayPrice opts then ma else mixedAmountStripPrices ma
sep = WideBuilder (TB.fromString ", ") 2
n = length astrs
pad = (WideBuilder (TB.fromText $ T.replicate w " ") w <>)
where w = fromMaybe 0 mmin - width
elided = maybe id elideTo mmax astrs
elideTo m = addElide . takeFitting m . withElided
-- Add the last elision string to the end of the display list
addElide [] = []
addElide xs = maybeAppend (snd $ last xs) $ map fst xs
-- Return the elements of the display list which fit within the maximum width
-- (including their elision strings). Always display at least one amount,
-- regardless of width.
takeFitting _ [] = []
takeFitting m (x:xs) = x : dropWhileRev (\(a,e) -> m < adTotal (fromMaybe a e)) xs
dropWhileRev p = foldr (\x xs -> if null xs && p x then [] else x:xs) []
-- Add the elision strings (if any) to each amount
withElided = zipWith (\num amt -> (amt, elisionDisplay Nothing (wbWidth sep) num amt)) [n-1,n-2..0]
orderedAmounts :: AmountDisplayOpts -> MixedAmount -> [Amount]
orderedAmounts dopts = maybe id (mapM pad) (displayOrder dopts) . amounts
where
pad c = fromMaybe (amountWithCommodity c nullamt) . find ((c==) . acommodity)
data AmountDisplay = AmountDisplay
{ adBuilder :: !WideBuilder -- ^ String representation of the Amount
, adTotal :: !Int -- ^ Cumulative length of MixedAmount this Amount is part of,
-- including separators
} deriving (Show)
nullAmountDisplay :: AmountDisplay
nullAmountDisplay = AmountDisplay mempty 0
amtDisplayList :: Int -> (Amount -> WideBuilder) -> [Amount] -> [AmountDisplay]
amtDisplayList sep showamt = snd . mapAccumL display (-sep)
where
display tot amt = (tot', AmountDisplay str tot')
where
str = showamt amt
tot' = tot + (wbWidth str) + sep
-- The string "m more", added to the previous running total
elisionDisplay :: Maybe Int -> Int -> Int -> AmountDisplay -> Maybe AmountDisplay
elisionDisplay mmax sep n lastAmt
| n > 0 = Just $ AmountDisplay (WideBuilder (TB.fromText str) len) (adTotal lastAmt + len)
| otherwise = Nothing
where
fullString = T.pack $ show n ++ " more.."
-- sep from the separator, 7 from " more..", 1 + floor (logBase 10 n) from number
fullLength = sep + 8 + floor (logBase 10 $ fromIntegral n)
str | Just m <- mmax, fullLength > m = T.take (m - 2) fullString <> ".."
| otherwise = fullString
len = case mmax of Nothing -> fullLength
Just m -> max 2 $ min m fullLength
maybeAppend :: Maybe a -> [a] -> [a]
maybeAppend Nothing = id
maybeAppend (Just a) = (++[a])
-- | Compact labelled trace of a mixed amount, for debugging.
ltraceamount :: String -> MixedAmount -> MixedAmount
ltraceamount s a = trace (s ++ ": " ++ showMixedAmount a) a
-- | Set the display precision in the amount's commodities.
mixedAmountSetPrecision :: AmountPrecision -> MixedAmount -> MixedAmount
mixedAmountSetPrecision p = mapMixedAmountUnsafe (amountSetPrecision p)
-- | In each component amount, increase the display precision sufficiently
-- to render it exactly (showing all significant decimal digits).
mixedAmountSetFullPrecision :: MixedAmount -> MixedAmount
mixedAmountSetFullPrecision = mapMixedAmountUnsafe amountSetFullPrecision
-- | Remove all prices from a MixedAmount.
mixedAmountStripPrices :: MixedAmount -> MixedAmount
mixedAmountStripPrices (Mixed ma) =
foldl' (\m a -> maAddAmount m a{aprice=Nothing}) (Mixed noPrices) withPrices
where (noPrices, withPrices) = M.partition (isNothing . aprice) ma
-- | Canonicalise a mixed amount's display styles using the provided commodity style map.
canonicaliseMixedAmount :: M.Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
canonicaliseMixedAmount styles = mapMixedAmountUnsafe (canonicaliseAmount styles)
-- | Replace each component amount's TotalPrice, if it has one, with an equivalent UnitPrice.
-- Has no effect on amounts without one.
-- Does Decimal division, might be some rounding/irrational number issues.
mixedAmountTotalPriceToUnitPrice :: MixedAmount -> MixedAmount
mixedAmountTotalPriceToUnitPrice = mapMixedAmount amountTotalPriceToUnitPrice
-------------------------------------------------------------------------------
-- tests
tests_Amount = testGroup "Amount" [
testGroup "Amount" [
testCase "amountCost" $ do
amountCost (eur 1) @?= eur 1
amountCost (eur 2){aprice=Just $ UnitPrice $ usd 2} @?= usd 4
amountCost (eur 1){aprice=Just $ TotalPrice $ usd 2} @?= usd 2
amountCost (eur (-1)){aprice=Just $ TotalPrice $ usd (-2)} @?= usd (-2)
,testCase "amountLooksZero" $ do
assertBool "" $ amountLooksZero amount
assertBool "" $ amountLooksZero $ usd 0
,testCase "negating amounts" $ do
negate (usd 1) @?= (usd 1){aquantity= -1}
let b = (usd 1){aprice=Just $ UnitPrice $ eur 2} in negate b @?= b{aquantity= -1}
,testCase "adding amounts without prices" $ do
(usd 1.23 + usd (-1.23)) @?= usd 0
(usd 1.23 + usd (-1.23)) @?= usd 0
(usd (-1.23) + usd (-1.23)) @?= usd (-2.46)
sum [usd 1.23,usd (-1.23),usd (-1.23),-(usd (-1.23))] @?= usd 0
-- highest precision is preserved
asprecision (astyle $ sum [usd 1 `withPrecision` Precision 1, usd 1 `withPrecision` Precision 3]) @?= Precision 3
asprecision (astyle $ sum [usd 1 `withPrecision` Precision 3, usd 1 `withPrecision` Precision 1]) @?= Precision 3
-- adding different commodities assumes conversion rate 1
assertBool "" $ amountLooksZero (usd 1.23 - eur 1.23)
,testCase "showAmount" $ do
showAmount (usd 0 + gbp 0) @?= "0"
]
,testGroup "MixedAmount" [
testCase "comparing mixed amounts compares based on quantities" $ do
let usdpos = mixed [usd 1]
usdneg = mixed [usd (-1)]
eurneg = mixed [eur (-12)]
compare usdneg usdpos @?= LT
compare eurneg usdpos @?= LT
,testCase "adding mixed amounts to zero, the commodity and amount style are preserved" $
maSum (map mixedAmount
[usd 1.25
,usd (-1) `withPrecision` Precision 3
,usd (-0.25)
])
@?= mixedAmount (usd 0 `withPrecision` Precision 3)
,testCase "adding mixed amounts with total prices" $ do
maSum (map mixedAmount
[usd 1 @@ eur 1
,usd (-2) @@ eur 1
])
@?= mixedAmount (usd (-1) @@ eur 2)
,testCase "showMixedAmount" $ do
showMixedAmount (mixedAmount (usd 1)) @?= "$1.00"
showMixedAmount (mixedAmount (usd 1 `at` eur 2)) @?= "$1.00 @ €2.00"
showMixedAmount (mixedAmount (usd 0)) @?= "0"
showMixedAmount nullmixedamt @?= "0"
showMixedAmount missingmixedamt @?= ""
,testCase "showMixedAmountWithoutPrice" $ do
let a = usd 1 `at` eur 2
showMixedAmountWithoutPrice False (mixedAmount (a)) @?= "$1.00"
showMixedAmountWithoutPrice False (mixed [a, -a]) @?= "0"
,testGroup "amounts" [
testCase "a missing amount overrides any other amounts" $
amounts (mixed [usd 1, missingamt]) @?= [missingamt]
,testCase "unpriced same-commodity amounts are combined" $
amounts (mixed [usd 0, usd 2]) @?= [usd 2]
,testCase "amounts with same unit price are combined" $
amounts (mixed [usd 1 `at` eur 1, usd 1 `at` eur 1]) @?= [usd 2 `at` eur 1]
,testCase "amounts with different unit prices are not combined" $
amounts (mixed [usd 1 `at` eur 1, usd 1 `at` eur 2]) @?= [usd 1 `at` eur 1, usd 1 `at` eur 2]
,testCase "amounts with total prices are combined" $
amounts (mixed [usd 1 @@ eur 1, usd 1 @@ eur 1]) @?= [usd 2 @@ eur 2]
]
,testCase "mixedAmountStripPrices" $ do
amounts (mixedAmountStripPrices nullmixedamt) @?= [nullamt]
assertBool "" $ mixedAmountLooksZero $ mixedAmountStripPrices
(mixed [usd 10
,usd 10 @@ eur 7
,usd (-10)
,usd (-10) @@ eur (-7)
])
]
]
| adept/hledger | hledger-lib/Hledger/Data/Amount.hs | gpl-3.0 | 46,894 | 0 | 20 | 9,211 | 9,917 | 5,329 | 4,588 | 604 | 7 |
{-# 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.DeleteCluster
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Deletes the specified cluster. You must deregister all container instances
-- from this cluster before you may delete it. You can list the container
-- instances in a cluster with 'ListContainerInstances' and deregister them with 'DeregisterContainerInstance'.
--
-- <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeleteCluster.html>
module Network.AWS.ECS.DeleteCluster
(
-- * Request
DeleteCluster
-- ** Request constructor
, deleteCluster
-- ** Request lenses
, dcCluster
-- * Response
, DeleteClusterResponse
-- ** Response constructor
, deleteClusterResponse
-- ** Response lenses
, dcrCluster
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.ECS.Types
import qualified GHC.Exts
newtype DeleteCluster = DeleteCluster
{ _dcCluster :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeleteCluster' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dcCluster' @::@ 'Text'
--
deleteCluster :: Text -- ^ 'dcCluster'
-> DeleteCluster
deleteCluster p1 = DeleteCluster
{ _dcCluster = p1
}
-- | The short name or full Amazon Resource Name (ARN) of the cluster that you
-- want to delete.
dcCluster :: Lens' DeleteCluster Text
dcCluster = lens _dcCluster (\s a -> s { _dcCluster = a })
newtype DeleteClusterResponse = DeleteClusterResponse
{ _dcrCluster :: Maybe Cluster
} deriving (Eq, Read, Show)
-- | 'DeleteClusterResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dcrCluster' @::@ 'Maybe' 'Cluster'
--
deleteClusterResponse :: DeleteClusterResponse
deleteClusterResponse = DeleteClusterResponse
{ _dcrCluster = Nothing
}
-- | The full description of the deleted cluster.
dcrCluster :: Lens' DeleteClusterResponse (Maybe Cluster)
dcrCluster = lens _dcrCluster (\s a -> s { _dcrCluster = a })
instance ToPath DeleteCluster where
toPath = const "/"
instance ToQuery DeleteCluster where
toQuery = const mempty
instance ToHeaders DeleteCluster
instance ToJSON DeleteCluster where
toJSON DeleteCluster{..} = object
[ "cluster" .= _dcCluster
]
instance AWSRequest DeleteCluster where
type Sv DeleteCluster = ECS
type Rs DeleteCluster = DeleteClusterResponse
request = post "DeleteCluster"
response = jsonResponse
instance FromJSON DeleteClusterResponse where
parseJSON = withObject "DeleteClusterResponse" $ \o -> DeleteClusterResponse
<$> o .:? "cluster"
| romanb/amazonka | amazonka-ecs/gen/Network/AWS/ECS/DeleteCluster.hs | mpl-2.0 | 3,636 | 0 | 9 | 787 | 452 | 276 | 176 | 56 | 1 |
module Data.Conf (Conf, readConf, getConf, parseConf) where
import Control.Monad
import Text.Read
import Data.Conf.Parser
getConf :: Read a => String -> Conf -> Maybe a
getConf key conf = lookup key conf >>= readMaybe
readConf :: String -> IO [(String, String)]
readConf = liftM parseConf . readFile
| carymrobbins/intellij-haskforce | tests/gold/cabal/completion/Module00001/src/Data/Conf.hs | apache-2.0 | 303 | 0 | 8 | 49 | 111 | 61 | 50 | 8 | 1 |
module Main (main) where
import RIO
-- import Criterion.Main
import qualified Test001
-- import qualified Test002
-- import qualified Test003
-- import qualified Test004
-- import qualified Test005
-- import qualified Test006
-- import qualified Test007
-- import qualified Test008
-- import qualified Test009
-- import qualified Test010
-- import qualified Test011
-- import qualified Test012
main :: IO ()
-- main = defaultMain [
-- bgroup "fib" [ bench "100" $ whnf Test012.tescik100 100
-- , bench "100000" $ whnf Test012.tescik100 1000
-- --, bench "79" $ whnf Test012.tescik20 79
-- -- , bench "430" $ whnf Test012.tescik200 430
-- ]]
main =
-- Test012.test1
Test001.test1
-- Test002.test1
-- Test003.test5
-- Test004.test1
-- Test005.test1
-- Test006.test
-- Test007.test31
-- Test007.test32
-- Test008.test1
-- Test008.test2
-- Test009.test1
-- Test010.test1
| kongra/kask-base | app/Main.hs | bsd-3-clause | 973 | 0 | 6 | 235 | 63 | 50 | 13 | 6 | 1 |
{-# LANGUAGE CPP, UnboxedTuples, MagicHash #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
--
-- (c) The University of Glasgow 2002-2006
--
-- ---------------------------------------------------------------------------
-- The dynamic linker for object code (.o .so .dll files)
-- ---------------------------------------------------------------------------
-- | Primarily, this module consists of an interface to the C-land
-- dynamic linker.
module GHCi.ObjLink
( initObjLinker, ShouldRetainCAFs(..)
, loadDLL
, loadArchive
, loadObj
, unloadObj
, lookupSymbol
, lookupClosure
, resolveObjs
, addLibrarySearchPath
, removeLibrarySearchPath
, findSystemLibrary
) where
import GHCi.RemoteTypes
import Control.Monad ( when )
import Foreign.C
import Foreign.Marshal.Alloc ( free )
import Foreign ( nullPtr )
import GHC.Exts
import System.Posix.Internals ( CFilePath, withFilePath, peekFilePath )
import System.FilePath ( dropExtension, normalise )
-- ---------------------------------------------------------------------------
-- RTS Linker Interface
-- ---------------------------------------------------------------------------
data ShouldRetainCAFs
= RetainCAFs
-- ^ Retain CAFs unconditionally in linked Haskell code.
-- Note that this prevents any code from being unloaded.
-- It should not be necessary unless you are GHCi or
-- hs-plugins, which needs to be able call any function
-- in the compiled code.
| DontRetainCAFs
-- ^ Do not retain CAFs. Everything reachable from foreign
-- exports will be retained, due to the StablePtrs
-- created by the module initialisation code. unloadObj
-- frees these StablePtrs, which will allow the CAFs to
-- be GC'd and the code to be removed.
initObjLinker :: ShouldRetainCAFs -> IO ()
initObjLinker RetainCAFs = c_initLinker_ 1
initObjLinker _ = c_initLinker_ 0
lookupSymbol :: String -> IO (Maybe (Ptr a))
lookupSymbol str_in = do
let str = prefixUnderscore str_in
withCAString str $ \c_str -> do
addr <- c_lookupSymbol c_str
if addr == nullPtr
then return Nothing
else return (Just addr)
lookupClosure :: String -> IO (Maybe HValueRef)
lookupClosure str = do
m <- lookupSymbol str
case m of
Nothing -> return Nothing
Just (Ptr addr) -> case addrToAny# addr of
(# a #) -> Just <$> mkRemoteRef (HValue a)
prefixUnderscore :: String -> String
prefixUnderscore
| cLeadingUnderscore = ('_':)
| otherwise = id
-- | loadDLL loads a dynamic library using the OS's native linker
-- (i.e. dlopen() on Unix, LoadLibrary() on Windows). It takes either
-- an absolute pathname to the file, or a relative filename
-- (e.g. "libfoo.so" or "foo.dll"). In the latter case, loadDLL
-- searches the standard locations for the appropriate library.
--
loadDLL :: String -> IO (Maybe String)
-- Nothing => success
-- Just err_msg => failure
loadDLL str0 = do
let
-- On Windows, addDLL takes a filename without an extension, because
-- it tries adding both .dll and .drv. To keep things uniform in the
-- layers above, loadDLL always takes a filename with an extension, and
-- we drop it here on Windows only.
str | isWindowsHost = dropExtension str0
| otherwise = str0
--
maybe_errmsg <- withFilePath (normalise str) $ \dll -> c_addDLL dll
if maybe_errmsg == nullPtr
then return Nothing
else do str <- peekCString maybe_errmsg
free maybe_errmsg
return (Just str)
loadArchive :: String -> IO ()
loadArchive str = do
withFilePath str $ \c_str -> do
r <- c_loadArchive c_str
when (r == 0) (error ("loadArchive " ++ show str ++ ": failed"))
loadObj :: String -> IO ()
loadObj str = do
withFilePath str $ \c_str -> do
r <- c_loadObj c_str
when (r == 0) (error ("loadObj " ++ show str ++ ": failed"))
unloadObj :: String -> IO ()
unloadObj str =
withFilePath str $ \c_str -> do
r <- c_unloadObj c_str
when (r == 0) (error ("unloadObj " ++ show str ++ ": failed"))
addLibrarySearchPath :: String -> IO (Ptr ())
addLibrarySearchPath str =
withFilePath str c_addLibrarySearchPath
removeLibrarySearchPath :: Ptr () -> IO Bool
removeLibrarySearchPath = c_removeLibrarySearchPath
findSystemLibrary :: String -> IO (Maybe String)
findSystemLibrary str = do
result <- withFilePath str c_findSystemLibrary
case result == nullPtr of
True -> return Nothing
False -> do path <- peekFilePath result
free result
return $ Just path
resolveObjs :: IO Bool
resolveObjs = do
r <- c_resolveObjs
return (r /= 0)
-- ---------------------------------------------------------------------------
-- Foreign declarations to RTS entry points which does the real work;
-- ---------------------------------------------------------------------------
foreign import ccall unsafe "addDLL" c_addDLL :: CFilePath -> IO CString
foreign import ccall unsafe "initLinker_" c_initLinker_ :: CInt -> IO ()
foreign import ccall unsafe "lookupSymbol" c_lookupSymbol :: CString -> IO (Ptr a)
foreign import ccall unsafe "loadArchive" c_loadArchive :: CFilePath -> IO Int
foreign import ccall unsafe "loadObj" c_loadObj :: CFilePath -> IO Int
foreign import ccall unsafe "unloadObj" c_unloadObj :: CFilePath -> IO Int
foreign import ccall unsafe "resolveObjs" c_resolveObjs :: IO Int
foreign import ccall unsafe "addLibrarySearchPath" c_addLibrarySearchPath :: CFilePath -> IO (Ptr ())
foreign import ccall unsafe "findSystemLibrary" c_findSystemLibrary :: CFilePath -> IO CFilePath
foreign import ccall unsafe "removeLibrarySearchPath" c_removeLibrarySearchPath :: Ptr() -> IO Bool
-- -----------------------------------------------------------------------------
-- Configuration
#include "ghcautoconf.h"
cLeadingUnderscore :: Bool
#ifdef LEADING_UNDERSCORE
cLeadingUnderscore = True
#else
cLeadingUnderscore = False
#endif
isWindowsHost :: Bool
#if mingw32_HOST_OS
isWindowsHost = True
#else
isWindowsHost = False
#endif
| olsner/ghc | libraries/ghci/GHCi/ObjLink.hs | bsd-3-clause | 6,297 | 0 | 17 | 1,410 | 1,235 | 641 | 594 | 104 | 2 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
--
-- | Parsing the top of a Haskell source file to get its module name,
-- imports and options.
--
-- (c) Simon Marlow 2005
-- (c) Lemmih 2006
--
-----------------------------------------------------------------------------
module HeaderInfo ( getImports
, mkPrelImports -- used by the renamer too
, getOptionsFromFile, getOptions
, optionsErrorMsgs,
checkProcessArgsResult ) where
#include "HsVersions.h"
import RdrName
import HscTypes
import Parser ( parseHeader )
import Lexer
import FastString
import HsSyn
import Module
import PrelNames
import StringBuffer
import SrcLoc
import DynFlags
import ErrUtils
import Util
import Outputable
import Pretty ()
import Maybes
import Bag ( emptyBag, listToBag, unitBag )
import MonadUtils
import Exception
import BasicTypes
import qualified GHC.LanguageExtensions as LangExt
import Control.Monad
import System.IO
import System.IO.Unsafe
import Data.List
------------------------------------------------------------------------------
-- | Parse the imports of a source file.
--
-- Throws a 'SourceError' if parsing fails.
getImports :: DynFlags
-> StringBuffer -- ^ Parse this.
-> FilePath -- ^ Filename the buffer came from. Used for
-- reporting parse error locations.
-> FilePath -- ^ The original source filename (used for locations
-- in the function result)
-> IO ([(Maybe FastString, Located ModuleName)],
[(Maybe FastString, Located ModuleName)],
Located ModuleName)
-- ^ The source imports, normal imports, and the module name.
getImports dflags buf filename source_filename = do
let loc = mkRealSrcLoc (mkFastString filename) 1 1
case unP parseHeader (mkPState dflags buf loc) of
PFailed span err -> parseError dflags span err
POk pst rdr_module -> do
let _ms@(_warns, errs) = getMessages pst
-- don't log warnings: they'll be reported when we parse the file
-- for real. See #2500.
ms = (emptyBag, errs)
-- logWarnings warns
if errorsFound dflags ms
then throwIO $ mkSrcErr errs
else
case rdr_module of
L _ (HsModule mb_mod _ imps _ _ _) ->
let
main_loc = srcLocSpan (mkSrcLoc (mkFastString source_filename) 1 1)
mod = mb_mod `orElse` L main_loc mAIN_NAME
(src_idecls, ord_idecls) = partition (ideclSource.unLoc) imps
-- GHC.Prim doesn't exist physically, so don't go looking for it.
ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc . ideclName . unLoc)
ord_idecls
implicit_prelude = xopt LangExt.ImplicitPrelude dflags
implicit_imports = mkPrelImports (unLoc mod) main_loc
implicit_prelude imps
convImport (L _ i) = (fmap sl_fs (ideclPkgQual i), ideclName i)
in
return (map convImport src_idecls,
map convImport (implicit_imports ++ ordinary_imps),
mod)
mkPrelImports :: ModuleName
-> SrcSpan -- Attribute the "import Prelude" to this location
-> Bool -> [LImportDecl RdrName]
-> [LImportDecl RdrName]
-- Consruct the implicit declaration "import Prelude" (or not)
--
-- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
-- because the former doesn't even look at Prelude.hi for instance
-- declarations, whereas the latter does.
mkPrelImports this_mod loc implicit_prelude import_decls
| this_mod == pRELUDE_NAME
|| explicit_prelude_import
|| not implicit_prelude
= []
| otherwise = [preludeImportDecl]
where
explicit_prelude_import
= notNull [ () | L _ (ImportDecl { ideclName = mod
, ideclPkgQual = Nothing })
<- import_decls
, unLoc mod == pRELUDE_NAME ]
preludeImportDecl :: LImportDecl RdrName
preludeImportDecl
= L loc $ ImportDecl { ideclSourceSrc = Nothing,
ideclName = L loc pRELUDE_NAME,
ideclPkgQual = Nothing,
ideclSource = False,
ideclSafe = False, -- Not a safe import
ideclQualified = False,
ideclImplicit = True, -- Implicit!
ideclAs = Nothing,
ideclHiding = Nothing }
parseError :: DynFlags -> SrcSpan -> MsgDoc -> IO a
parseError dflags span err = throwOneError $ mkPlainErrMsg dflags span err
--------------------------------------------------------------
-- Get options
--------------------------------------------------------------
-- | Parse OPTIONS and LANGUAGE pragmas of the source file.
--
-- Throws a 'SourceError' if flag parsing fails (including unsupported flags.)
getOptionsFromFile :: DynFlags
-> FilePath -- ^ Input file
-> IO [Located String] -- ^ Parsed options, if any.
getOptionsFromFile dflags filename
= Exception.bracket
(openBinaryFile filename ReadMode)
(hClose)
(\handle -> do
opts <- fmap (getOptions' dflags)
(lazyGetToks dflags' filename handle)
seqList opts $ return opts)
where -- We don't need to get haddock doc tokens when we're just
-- getting the options from pragmas, and lazily lexing them
-- correctly is a little tricky: If there is "\n" or "\n-"
-- left at the end of a buffer then the haddock doc may
-- continue past the end of the buffer, despite the fact that
-- we already have an apparently-complete token.
-- We therefore just turn Opt_Haddock off when doing the lazy
-- lex.
dflags' = gopt_unset dflags Opt_Haddock
blockSize :: Int
-- blockSize = 17 -- for testing :-)
blockSize = 1024
lazyGetToks :: DynFlags -> FilePath -> Handle -> IO [Located Token]
lazyGetToks dflags filename handle = do
buf <- hGetStringBufferBlock handle blockSize
unsafeInterleaveIO $ lazyLexBuf handle (pragState dflags buf loc) False blockSize
where
loc = mkRealSrcLoc (mkFastString filename) 1 1
lazyLexBuf :: Handle -> PState -> Bool -> Int -> IO [Located Token]
lazyLexBuf handle state eof size = do
case unP (lexer False return) state of
POk state' t -> do
-- pprTrace "lazyLexBuf" (text (show (buffer state'))) (return ())
if atEnd (buffer state') && not eof
-- if this token reached the end of the buffer, and we haven't
-- necessarily read up to the end of the file, then the token might
-- be truncated, so read some more of the file and lex it again.
then getMore handle state size
else case t of
L _ ITeof -> return [t]
_other -> do rest <- lazyLexBuf handle state' eof size
return (t : rest)
_ | not eof -> getMore handle state size
| otherwise -> return [L (RealSrcSpan (last_loc state)) ITeof]
-- parser assumes an ITeof sentinel at the end
getMore :: Handle -> PState -> Int -> IO [Located Token]
getMore handle state size = do
-- pprTrace "getMore" (text (show (buffer state))) (return ())
let new_size = size * 2
-- double the buffer size each time we read a new block. This
-- counteracts the quadratic slowdown we otherwise get for very
-- large module names (#5981)
nextbuf <- hGetStringBufferBlock handle new_size
if (len nextbuf == 0) then lazyLexBuf handle state True new_size else do
newbuf <- appendStringBuffers (buffer state) nextbuf
unsafeInterleaveIO $ lazyLexBuf handle state{buffer=newbuf} False new_size
getToks :: DynFlags -> FilePath -> StringBuffer -> [Located Token]
getToks dflags filename buf = lexAll (pragState dflags buf loc)
where
loc = mkRealSrcLoc (mkFastString filename) 1 1
lexAll state = case unP (lexer False return) state of
POk _ t@(L _ ITeof) -> [t]
POk state' t -> t : lexAll state'
_ -> [L (RealSrcSpan (last_loc state)) ITeof]
-- | Parse OPTIONS and LANGUAGE pragmas of the source file.
--
-- Throws a 'SourceError' if flag parsing fails (including unsupported flags.)
getOptions :: DynFlags
-> StringBuffer -- ^ Input Buffer
-> FilePath -- ^ Source filename. Used for location info.
-> [Located String] -- ^ Parsed options.
getOptions dflags buf filename
= getOptions' dflags (getToks dflags filename buf)
-- The token parser is written manually because Happy can't
-- return a partial result when it encounters a lexer error.
-- We want to extract options before the buffer is passed through
-- CPP, so we can't use the same trick as 'getImports'.
getOptions' :: DynFlags
-> [Located Token] -- Input buffer
-> [Located String] -- Options.
getOptions' dflags toks
= parseToks toks
where
getToken (L _loc tok) = tok
getLoc (L loc _tok) = loc
parseToks (open:close:xs)
| IToptions_prag str <- getToken open
, ITclose_prag <- getToken close
= case toArgs str of
Left err -> panic ("getOptions'.parseToks: " ++ err)
Right args -> map (L (getLoc open)) args ++ parseToks xs
parseToks (open:close:xs)
| ITinclude_prag str <- getToken open
, ITclose_prag <- getToken close
= map (L (getLoc open)) ["-#include",removeSpaces str] ++
parseToks xs
parseToks (open:close:xs)
| ITdocOptions str <- getToken open
, ITclose_prag <- getToken close
= map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
++ parseToks xs
parseToks (open:xs)
| ITdocOptionsOld str <- getToken open
= map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
++ parseToks xs
parseToks (open:xs)
| ITlanguage_prag <- getToken open
= parseLanguage xs
parseToks (comment:xs) -- Skip over comments
| isComment (getToken comment)
= parseToks xs
parseToks _ = []
parseLanguage (L loc (ITconid fs):rest)
= checkExtension dflags (L loc fs) :
case rest of
(L _loc ITcomma):more -> parseLanguage more
(L _loc ITclose_prag):more -> parseToks more
(L loc _):_ -> languagePragParseError dflags loc
[] -> panic "getOptions'.parseLanguage(1) went past eof token"
parseLanguage (tok:_)
= languagePragParseError dflags (getLoc tok)
parseLanguage []
= panic "getOptions'.parseLanguage(2) went past eof token"
isComment :: Token -> Bool
isComment c =
case c of
(ITlineComment {}) -> True
(ITblockComment {}) -> True
(ITdocCommentNext {}) -> True
(ITdocCommentPrev {}) -> True
(ITdocCommentNamed {}) -> True
(ITdocSection {}) -> True
_ -> False
-----------------------------------------------------------------------------
-- | Complain about non-dynamic flags in OPTIONS pragmas.
--
-- Throws a 'SourceError' if the input list is non-empty claiming that the
-- input flags are unknown.
checkProcessArgsResult :: MonadIO m => DynFlags -> [Located String] -> m ()
checkProcessArgsResult dflags flags
= when (notNull flags) $
liftIO $ throwIO $ mkSrcErr $ listToBag $ map mkMsg flags
where mkMsg (L loc flag)
= mkPlainErrMsg dflags loc $
(text "unknown flag in {-# OPTIONS_GHC #-} pragma:" <+>
text flag)
-----------------------------------------------------------------------------
checkExtension :: DynFlags -> Located FastString -> Located String
checkExtension dflags (L l ext)
-- Checks if a given extension is valid, and if so returns
-- its corresponding flag. Otherwise it throws an exception.
= let ext' = unpackFS ext in
if ext' `elem` supportedLanguagesAndExtensions
then L l ("-X"++ext')
else unsupportedExtnError dflags l ext'
languagePragParseError :: DynFlags -> SrcSpan -> a
languagePragParseError dflags loc =
throw $ mkSrcErr $ unitBag $
(mkPlainErrMsg dflags loc $
vcat [ text "Cannot parse LANGUAGE pragma"
, text "Expecting comma-separated list of language options,"
, text "each starting with a capital letter"
, nest 2 (text "E.g. {-# LANGUAGE TemplateHaskell, GADTs #-}") ])
unsupportedExtnError :: DynFlags -> SrcSpan -> String -> a
unsupportedExtnError dflags loc unsup =
throw $ mkSrcErr $ unitBag $
mkPlainErrMsg dflags loc $
text "Unsupported extension: " <> text unsup $$
if null suggestions then Outputable.empty else text "Perhaps you meant" <+> quotedListWithOr (map text suggestions)
where
suggestions = fuzzyMatch unsup supportedLanguagesAndExtensions
optionsErrorMsgs :: DynFlags -> [String] -> [Located String] -> FilePath -> Messages
optionsErrorMsgs dflags unhandled_flags flags_lines _filename
= (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
where unhandled_flags_lines = [ L l f | f <- unhandled_flags,
L l f' <- flags_lines, f == f' ]
mkMsg (L flagSpan flag) =
ErrUtils.mkPlainErrMsg dflags flagSpan $
text "unknown flag in {-# OPTIONS_GHC #-} pragma:" <+> text flag
| nushio3/ghc | compiler/main/HeaderInfo.hs | bsd-3-clause | 14,338 | 0 | 26 | 4,519 | 2,968 | 1,524 | 1,444 | 233 | 19 |
{-# LANGUAGE TypeFamilies #-}
module T9840 where
import Data.Kind (Type)
import T9840a
type family X :: Type -> Type where
type family F (a :: Type -> Type) where
foo :: G (F X) -> G (F X)
foo x = x
| sdiehl/ghc | testsuite/tests/indexed-types/should_compile/T9840.hs | bsd-3-clause | 204 | 0 | 8 | 47 | 83 | 48 | 35 | -1 | -1 |
{-
(c) Bartosz Nitka, Facebook, 2015
UniqDFM: Specialised deterministic finite maps, for things with @Uniques@.
Basically, the things need to be in class @Uniquable@, and we use the
@getUnique@ method to grab their @Uniques@.
This is very similar to @UniqFM@, the major difference being that the order of
folding is not dependent on @Unique@ ordering, giving determinism.
Currently the ordering is determined by insertion order.
See Note [Unique Determinism] in Unique for explanation why @Unique@ ordering
is not deterministic.
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -Wall #-}
module UniqDFM (
-- * Unique-keyed deterministic mappings
UniqDFM, -- abstract type
-- ** Manipulating those mappings
emptyUDFM,
unitUDFM,
addToUDFM,
addToUDFM_C,
addListToUDFM,
delFromUDFM,
delListFromUDFM,
adjustUDFM,
alterUDFM,
mapUDFM,
plusUDFM,
plusUDFM_C,
lookupUDFM, lookupUDFM_Directly,
elemUDFM,
foldUDFM,
eltsUDFM,
filterUDFM, filterUDFM_Directly,
isNullUDFM,
sizeUDFM,
intersectUDFM, udfmIntersectUFM,
intersectsUDFM,
disjointUDFM, disjointUdfmUfm,
minusUDFM,
listToUDFM,
udfmMinusUFM,
partitionUDFM,
anyUDFM, allUDFM,
pprUDFM,
udfmToList,
udfmToUfm,
nonDetFoldUDFM,
alwaysUnsafeUfmToUdfm,
) where
import GhcPrelude
import Unique ( Uniquable(..), Unique, getKey )
import Outputable
import qualified Data.IntMap as M
import Data.Data
import Data.List (sortBy)
import Data.Function (on)
import qualified Data.Semigroup as Semi
import UniqFM (UniqFM, listToUFM_Directly, nonDetUFMToList, ufmToIntMap)
-- Note [Deterministic UniqFM]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- A @UniqDFM@ is just like @UniqFM@ with the following additional
-- property: the function `udfmToList` returns the elements in some
-- deterministic order not depending on the Unique key for those elements.
--
-- If the client of the map performs operations on the map in deterministic
-- order then `udfmToList` returns them in deterministic order.
--
-- There is an implementation cost: each element is given a serial number
-- as it is added, and `udfmToList` sorts it's result by this serial
-- number. So you should only use `UniqDFM` if you need the deterministic
-- property.
--
-- `foldUDFM` also preserves determinism.
--
-- Normal @UniqFM@ when you turn it into a list will use
-- Data.IntMap.toList function that returns the elements in the order of
-- the keys. The keys in @UniqFM@ are always @Uniques@, so you end up with
-- with a list ordered by @Uniques@.
-- The order of @Uniques@ is known to be not stable across rebuilds.
-- See Note [Unique Determinism] in Unique.
--
--
-- There's more than one way to implement this. The implementation here tags
-- every value with the insertion time that can later be used to sort the
-- values when asked to convert to a list.
--
-- An alternative would be to have
--
-- data UniqDFM ele = UDFM (M.IntMap ele) [ele]
--
-- where the list determines the order. This makes deletion tricky as we'd
-- only accumulate elements in that list, but makes merging easier as you
-- can just merge both structures independently.
-- Deletion can probably be done in amortized fashion when the size of the
-- list is twice the size of the set.
-- | A type of values tagged with insertion time
data TaggedVal val =
TaggedVal
val
{-# UNPACK #-} !Int -- ^ insertion time
deriving Data
taggedFst :: TaggedVal val -> val
taggedFst (TaggedVal v _) = v
taggedSnd :: TaggedVal val -> Int
taggedSnd (TaggedVal _ i) = i
instance Eq val => Eq (TaggedVal val) where
(TaggedVal v1 _) == (TaggedVal v2 _) = v1 == v2
instance Functor TaggedVal where
fmap f (TaggedVal val i) = TaggedVal (f val) i
-- | Type of unique deterministic finite maps
data UniqDFM ele =
UDFM
!(M.IntMap (TaggedVal ele)) -- A map where keys are Unique's values and
-- values are tagged with insertion time.
-- The invariant is that all the tags will
-- be distinct within a single map
{-# UNPACK #-} !Int -- Upper bound on the values' insertion
-- time. See Note [Overflow on plusUDFM]
deriving (Data, Functor)
emptyUDFM :: UniqDFM elt
emptyUDFM = UDFM M.empty 0
unitUDFM :: Uniquable key => key -> elt -> UniqDFM elt
unitUDFM k v = UDFM (M.singleton (getKey $ getUnique k) (TaggedVal v 0)) 1
addToUDFM :: Uniquable key => UniqDFM elt -> key -> elt -> UniqDFM elt
addToUDFM m k v = addToUDFM_Directly m (getUnique k) v
addToUDFM_Directly :: UniqDFM elt -> Unique -> elt -> UniqDFM elt
addToUDFM_Directly (UDFM m i) u v
= UDFM (M.insertWith tf (getKey u) (TaggedVal v i) m) (i + 1)
where
tf (TaggedVal new_v _) (TaggedVal _ old_i) = TaggedVal new_v old_i
-- Keep the old tag, but insert the new value
-- This means that udfmToList typically returns elements
-- in the order of insertion, rather than the reverse
addToUDFM_Directly_C
:: (elt -> elt -> elt) -- old -> new -> result
-> UniqDFM elt
-> Unique -> elt
-> UniqDFM elt
addToUDFM_Directly_C f (UDFM m i) u v
= UDFM (M.insertWith tf (getKey u) (TaggedVal v i) m) (i + 1)
where
tf (TaggedVal new_v _) (TaggedVal old_v old_i)
= TaggedVal (f old_v new_v) old_i
-- Flip the arguments, because M.insertWith uses (new->old->result)
-- but f needs (old->new->result)
-- Like addToUDFM_Directly, keep the old tag
addToUDFM_C
:: Uniquable key => (elt -> elt -> elt) -- old -> new -> result
-> UniqDFM elt -- old
-> key -> elt -- new
-> UniqDFM elt -- result
addToUDFM_C f m k v = addToUDFM_Directly_C f m (getUnique k) v
addListToUDFM :: Uniquable key => UniqDFM elt -> [(key,elt)] -> UniqDFM elt
addListToUDFM = foldl (\m (k, v) -> addToUDFM m k v)
addListToUDFM_Directly :: UniqDFM elt -> [(Unique,elt)] -> UniqDFM elt
addListToUDFM_Directly = foldl (\m (k, v) -> addToUDFM_Directly m k v)
addListToUDFM_Directly_C
:: (elt -> elt -> elt) -> UniqDFM elt -> [(Unique,elt)] -> UniqDFM elt
addListToUDFM_Directly_C f = foldl (\m (k, v) -> addToUDFM_Directly_C f m k v)
delFromUDFM :: Uniquable key => UniqDFM elt -> key -> UniqDFM elt
delFromUDFM (UDFM m i) k = UDFM (M.delete (getKey $ getUnique k) m) i
plusUDFM_C :: (elt -> elt -> elt) -> UniqDFM elt -> UniqDFM elt -> UniqDFM elt
plusUDFM_C f udfml@(UDFM _ i) udfmr@(UDFM _ j)
-- we will use the upper bound on the tag as a proxy for the set size,
-- to insert the smaller one into the bigger one
| i > j = insertUDFMIntoLeft_C f udfml udfmr
| otherwise = insertUDFMIntoLeft_C f udfmr udfml
-- Note [Overflow on plusUDFM]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- There are multiple ways of implementing plusUDFM.
-- The main problem that needs to be solved is overlap on times of
-- insertion between different keys in two maps.
-- Consider:
--
-- A = fromList [(a, (x, 1))]
-- B = fromList [(b, (y, 1))]
--
-- If you merge them naively you end up with:
--
-- C = fromList [(a, (x, 1)), (b, (y, 1))]
--
-- Which loses information about ordering and brings us back into
-- non-deterministic world.
--
-- The solution I considered before would increment the tags on one of the
-- sets by the upper bound of the other set. The problem with this approach
-- is that you'll run out of tags for some merge patterns.
-- Say you start with A with upper bound 1, you merge A with A to get A' and
-- the upper bound becomes 2. You merge A' with A' and the upper bound
-- doubles again. After 64 merges you overflow.
-- This solution would have the same time complexity as plusUFM, namely O(n+m).
--
-- The solution I ended up with has time complexity of
-- O(m log m + m * min (n+m, W)) where m is the smaller set.
-- It simply inserts the elements of the smaller set into the larger
-- set in the order that they were inserted into the smaller set. That's
-- O(m log m) for extracting the elements from the smaller set in the
-- insertion order and O(m * min(n+m, W)) to insert them into the bigger
-- set.
plusUDFM :: UniqDFM elt -> UniqDFM elt -> UniqDFM elt
plusUDFM udfml@(UDFM _ i) udfmr@(UDFM _ j)
-- we will use the upper bound on the tag as a proxy for the set size,
-- to insert the smaller one into the bigger one
| i > j = insertUDFMIntoLeft udfml udfmr
| otherwise = insertUDFMIntoLeft udfmr udfml
insertUDFMIntoLeft :: UniqDFM elt -> UniqDFM elt -> UniqDFM elt
insertUDFMIntoLeft udfml udfmr = addListToUDFM_Directly udfml $ udfmToList udfmr
insertUDFMIntoLeft_C
:: (elt -> elt -> elt) -> UniqDFM elt -> UniqDFM elt -> UniqDFM elt
insertUDFMIntoLeft_C f udfml udfmr =
addListToUDFM_Directly_C f udfml $ udfmToList udfmr
lookupUDFM :: Uniquable key => UniqDFM elt -> key -> Maybe elt
lookupUDFM (UDFM m _i) k = taggedFst `fmap` M.lookup (getKey $ getUnique k) m
lookupUDFM_Directly :: UniqDFM elt -> Unique -> Maybe elt
lookupUDFM_Directly (UDFM m _i) k = taggedFst `fmap` M.lookup (getKey k) m
elemUDFM :: Uniquable key => key -> UniqDFM elt -> Bool
elemUDFM k (UDFM m _i) = M.member (getKey $ getUnique k) m
-- | Performs a deterministic fold over the UniqDFM.
-- It's O(n log n) while the corresponding function on `UniqFM` is O(n).
foldUDFM :: (elt -> a -> a) -> a -> UniqDFM elt -> a
foldUDFM k z m = foldr k z (eltsUDFM m)
-- | Performs a nondeterministic fold over the UniqDFM.
-- It's O(n), same as the corresponding function on `UniqFM`.
-- If you use this please provide a justification why it doesn't introduce
-- nondeterminism.
nonDetFoldUDFM :: (elt -> a -> a) -> a -> UniqDFM elt -> a
nonDetFoldUDFM k z (UDFM m _i) = foldr k z $ map taggedFst $ M.elems m
eltsUDFM :: UniqDFM elt -> [elt]
eltsUDFM (UDFM m _i) =
map taggedFst $ sortBy (compare `on` taggedSnd) $ M.elems m
filterUDFM :: (elt -> Bool) -> UniqDFM elt -> UniqDFM elt
filterUDFM p (UDFM m i) = UDFM (M.filter (\(TaggedVal v _) -> p v) m) i
filterUDFM_Directly :: (Unique -> elt -> Bool) -> UniqDFM elt -> UniqDFM elt
filterUDFM_Directly p (UDFM m i) = UDFM (M.filterWithKey p' m) i
where
p' k (TaggedVal v _) = p (getUnique k) v
-- | Converts `UniqDFM` to a list, with elements in deterministic order.
-- It's O(n log n) while the corresponding function on `UniqFM` is O(n).
udfmToList :: UniqDFM elt -> [(Unique, elt)]
udfmToList (UDFM m _i) =
[ (getUnique k, taggedFst v)
| (k, v) <- sortBy (compare `on` (taggedSnd . snd)) $ M.toList m ]
isNullUDFM :: UniqDFM elt -> Bool
isNullUDFM (UDFM m _) = M.null m
sizeUDFM :: UniqDFM elt -> Int
sizeUDFM (UDFM m _i) = M.size m
intersectUDFM :: UniqDFM elt -> UniqDFM elt -> UniqDFM elt
intersectUDFM (UDFM x i) (UDFM y _j) = UDFM (M.intersection x y) i
-- M.intersection is left biased, that means the result will only have
-- a subset of elements from the left set, so `i` is a good upper bound.
udfmIntersectUFM :: UniqDFM elt1 -> UniqFM elt2 -> UniqDFM elt1
udfmIntersectUFM (UDFM x i) y = UDFM (M.intersection x (ufmToIntMap y)) i
-- M.intersection is left biased, that means the result will only have
-- a subset of elements from the left set, so `i` is a good upper bound.
intersectsUDFM :: UniqDFM elt -> UniqDFM elt -> Bool
intersectsUDFM x y = isNullUDFM (x `intersectUDFM` y)
disjointUDFM :: UniqDFM elt -> UniqDFM elt -> Bool
disjointUDFM (UDFM x _i) (UDFM y _j) = M.null (M.intersection x y)
disjointUdfmUfm :: UniqDFM elt -> UniqFM elt2 -> Bool
disjointUdfmUfm (UDFM x _i) y = M.null (M.intersection x (ufmToIntMap y))
minusUDFM :: UniqDFM elt1 -> UniqDFM elt2 -> UniqDFM elt1
minusUDFM (UDFM x i) (UDFM y _j) = UDFM (M.difference x y) i
-- M.difference returns a subset of a left set, so `i` is a good upper
-- bound.
udfmMinusUFM :: UniqDFM elt1 -> UniqFM elt2 -> UniqDFM elt1
udfmMinusUFM (UDFM x i) y = UDFM (M.difference x (ufmToIntMap y)) i
-- M.difference returns a subset of a left set, so `i` is a good upper
-- bound.
-- | Partition UniqDFM into two UniqDFMs according to the predicate
partitionUDFM :: (elt -> Bool) -> UniqDFM elt -> (UniqDFM elt, UniqDFM elt)
partitionUDFM p (UDFM m i) =
case M.partition (p . taggedFst) m of
(left, right) -> (UDFM left i, UDFM right i)
-- | Delete a list of elements from a UniqDFM
delListFromUDFM :: Uniquable key => UniqDFM elt -> [key] -> UniqDFM elt
delListFromUDFM = foldl delFromUDFM
-- | This allows for lossy conversion from UniqDFM to UniqFM
udfmToUfm :: UniqDFM elt -> UniqFM elt
udfmToUfm (UDFM m _i) =
listToUFM_Directly [(getUnique k, taggedFst tv) | (k, tv) <- M.toList m]
listToUDFM :: Uniquable key => [(key,elt)] -> UniqDFM elt
listToUDFM = foldl (\m (k, v) -> addToUDFM m k v) emptyUDFM
listToUDFM_Directly :: [(Unique, elt)] -> UniqDFM elt
listToUDFM_Directly = foldl (\m (u, v) -> addToUDFM_Directly m u v) emptyUDFM
-- | Apply a function to a particular element
adjustUDFM :: Uniquable key => (elt -> elt) -> UniqDFM elt -> key -> UniqDFM elt
adjustUDFM f (UDFM m i) k = UDFM (M.adjust (fmap f) (getKey $ getUnique k) m) i
-- | The expression (alterUDFM f k map) alters value x at k, or absence
-- thereof. alterUDFM can be used to insert, delete, or update a value in
-- UniqDFM. Use addToUDFM, delFromUDFM or adjustUDFM when possible, they are
-- more efficient.
alterUDFM
:: Uniquable key
=> (Maybe elt -> Maybe elt) -- How to adjust
-> UniqDFM elt -- old
-> key -- new
-> UniqDFM elt -- result
alterUDFM f (UDFM m i) k =
UDFM (M.alter alterf (getKey $ getUnique k) m) (i + 1)
where
alterf Nothing = inject $ f Nothing
alterf (Just (TaggedVal v _)) = inject $ f (Just v)
inject Nothing = Nothing
inject (Just v) = Just $ TaggedVal v i
-- | Map a function over every value in a UniqDFM
mapUDFM :: (elt1 -> elt2) -> UniqDFM elt1 -> UniqDFM elt2
mapUDFM f (UDFM m i) = UDFM (M.map (fmap f) m) i
anyUDFM :: (elt -> Bool) -> UniqDFM elt -> Bool
anyUDFM p (UDFM m _i) = M.foldr ((||) . p . taggedFst) False m
allUDFM :: (elt -> Bool) -> UniqDFM elt -> Bool
allUDFM p (UDFM m _i) = M.foldr ((&&) . p . taggedFst) True m
instance Semi.Semigroup (UniqDFM a) where
(<>) = plusUDFM
instance Monoid (UniqDFM a) where
mempty = emptyUDFM
mappend = (Semi.<>)
-- This should not be used in commited code, provided for convenience to
-- make ad-hoc conversions when developing
alwaysUnsafeUfmToUdfm :: UniqFM elt -> UniqDFM elt
alwaysUnsafeUfmToUdfm = listToUDFM_Directly . nonDetUFMToList
-- Output-ery
instance Outputable a => Outputable (UniqDFM a) where
ppr ufm = pprUniqDFM ppr ufm
pprUniqDFM :: (a -> SDoc) -> UniqDFM a -> SDoc
pprUniqDFM ppr_elt ufm
= brackets $ fsep $ punctuate comma $
[ ppr uq <+> text ":->" <+> ppr_elt elt
| (uq, elt) <- udfmToList ufm ]
pprUDFM :: UniqDFM a -- ^ The things to be pretty printed
-> ([a] -> SDoc) -- ^ The pretty printing function to use on the elements
-> SDoc -- ^ 'SDoc' where the things have been pretty
-- printed
pprUDFM ufm pp = pp (eltsUDFM ufm)
| ezyang/ghc | compiler/utils/UniqDFM.hs | bsd-3-clause | 15,285 | 0 | 13 | 3,410 | 3,703 | 1,947 | 1,756 | 206 | 3 |
{-# LANGUAGE CPP #-}
module RegAlloc.Graph.TrivColorable (
trivColorable,
)
where
#include "HsVersions.h"
import RegClass
import Reg
import GraphBase
import UniqFM
import Platform
import Panic
-- trivColorable ---------------------------------------------------------------
-- trivColorable function for the graph coloring allocator
--
-- This gets hammered by scanGraph during register allocation,
-- so needs to be fairly efficient.
--
-- NOTE: This only works for arcitectures with just RcInteger and RcDouble
-- (which are disjoint) ie. x86, x86_64 and ppc
--
-- The number of allocatable regs is hard coded in here so we can do
-- a fast comparison in trivColorable.
--
-- It's ok if these numbers are _less_ than the actual number of free
-- regs, but they can't be more or the register conflict
-- graph won't color.
--
-- If the graph doesn't color then the allocator will panic, but it won't
-- generate bad object code or anything nasty like that.
--
-- There is an allocatableRegsInClass :: RegClass -> Int, but doing
-- the unboxing is too slow for us here.
-- TODO: Is that still true? Could we use allocatableRegsInClass
-- without losing performance now?
--
-- Look at includes/stg/MachRegs.h to get the numbers.
--
-- Disjoint registers ----------------------------------------------------------
--
-- The definition has been unfolded into individual cases for speed.
-- Each architecture has a different register setup, so we use a
-- different regSqueeze function for each.
--
accSqueeze
:: Int
-> Int
-> (reg -> Int)
-> UniqFM reg
-> Int
accSqueeze count maxCount squeeze ufm = acc count (nonDetEltsUFM ufm)
-- See Note [Unique Determinism and code generation]
where acc count [] = count
acc count _ | count >= maxCount = count
acc count (r:rs) = acc (count + squeeze r) rs
{- Note [accSqueeze]
~~~~~~~~~~~~~~~~~~~~
BL 2007/09
Doing a nice fold over the UniqSet makes trivColorable use
32% of total compile time and 42% of total alloc when compiling SHA1.hs from darcs.
Therefore the UniqFM is made non-abstract and we use custom fold.
MS 2010/04
When converting UniqFM to use Data.IntMap, the fold cannot use UniqFM internal
representation any more. But it is imperative that the accSqueeze stops
the folding if the count gets greater or equal to maxCount. We thus convert
UniqFM to a (lazy) list, do the fold and stops if necessary, which was
the most efficient variant tried. Benchmark compiling 10-times SHA1.hs follows.
(original = previous implementation, folding = fold of the whole UFM,
lazyFold = the current implementation,
hackFold = using internal representation of Data.IntMap)
original folding hackFold lazyFold
-O -fasm (used everywhere) 31.509s 30.387s 30.791s 30.603s
100.00% 96.44% 97.72% 97.12%
-fregs-graph 67.938s 74.875s 62.673s 64.679s
100.00% 110.21% 92.25% 95.20%
-fregs-iterative 89.761s 143.913s 81.075s 86.912s
100.00% 160.33% 90.32% 96.83%
-fnew-codegen 38.225s 37.142s 37.551s 37.119s
100.00% 97.17% 98.24% 97.11%
-fnew-codegen -fregs-graph 91.786s 91.51s 87.368s 86.88s
100.00% 99.70% 95.19% 94.65%
-fnew-codegen -fregs-iterative 206.72s 343.632s 194.694s 208.677s
100.00% 166.23% 94.18% 100.95%
-}
trivColorable
:: Platform
-> (RegClass -> VirtualReg -> Int)
-> (RegClass -> RealReg -> Int)
-> Triv VirtualReg RegClass RealReg
trivColorable platform virtualRegSqueeze realRegSqueeze RcInteger conflicts exclusions
| let cALLOCATABLE_REGS_INTEGER
= (case platformArch platform of
ArchX86 -> 3
ArchX86_64 -> 5
ArchPPC -> 16
ArchSPARC -> 14
ArchSPARC64 -> panic "trivColorable ArchSPARC64"
ArchPPC_64 _ -> panic "trivColorable ArchPPC_64"
ArchARM _ _ _ -> panic "trivColorable ArchARM"
ArchARM64 -> panic "trivColorable ArchARM64"
ArchAlpha -> panic "trivColorable ArchAlpha"
ArchMipseb -> panic "trivColorable ArchMipseb"
ArchMipsel -> panic "trivColorable ArchMipsel"
ArchJavaScript-> panic "trivColorable ArchJavaScript"
ArchUnknown -> panic "trivColorable ArchUnknown")
, count2 <- accSqueeze 0 cALLOCATABLE_REGS_INTEGER
(virtualRegSqueeze RcInteger)
conflicts
, count3 <- accSqueeze count2 cALLOCATABLE_REGS_INTEGER
(realRegSqueeze RcInteger)
exclusions
= count3 < cALLOCATABLE_REGS_INTEGER
trivColorable platform virtualRegSqueeze realRegSqueeze RcFloat conflicts exclusions
| let cALLOCATABLE_REGS_FLOAT
= (case platformArch platform of
ArchX86 -> 0
ArchX86_64 -> 0
ArchPPC -> 0
ArchSPARC -> 22
ArchSPARC64 -> panic "trivColorable ArchSPARC64"
ArchPPC_64 _ -> panic "trivColorable ArchPPC_64"
ArchARM _ _ _ -> panic "trivColorable ArchARM"
ArchARM64 -> panic "trivColorable ArchARM64"
ArchAlpha -> panic "trivColorable ArchAlpha"
ArchMipseb -> panic "trivColorable ArchMipseb"
ArchMipsel -> panic "trivColorable ArchMipsel"
ArchJavaScript-> panic "trivColorable ArchJavaScript"
ArchUnknown -> panic "trivColorable ArchUnknown")
, count2 <- accSqueeze 0 cALLOCATABLE_REGS_FLOAT
(virtualRegSqueeze RcFloat)
conflicts
, count3 <- accSqueeze count2 cALLOCATABLE_REGS_FLOAT
(realRegSqueeze RcFloat)
exclusions
= count3 < cALLOCATABLE_REGS_FLOAT
trivColorable platform virtualRegSqueeze realRegSqueeze RcDouble conflicts exclusions
| let cALLOCATABLE_REGS_DOUBLE
= (case platformArch platform of
ArchX86 -> 6
ArchX86_64 -> 0
ArchPPC -> 26
ArchSPARC -> 11
ArchSPARC64 -> panic "trivColorable ArchSPARC64"
ArchPPC_64 _ -> panic "trivColorable ArchPPC_64"
ArchARM _ _ _ -> panic "trivColorable ArchARM"
ArchARM64 -> panic "trivColorable ArchARM64"
ArchAlpha -> panic "trivColorable ArchAlpha"
ArchMipseb -> panic "trivColorable ArchMipseb"
ArchMipsel -> panic "trivColorable ArchMipsel"
ArchJavaScript-> panic "trivColorable ArchJavaScript"
ArchUnknown -> panic "trivColorable ArchUnknown")
, count2 <- accSqueeze 0 cALLOCATABLE_REGS_DOUBLE
(virtualRegSqueeze RcDouble)
conflicts
, count3 <- accSqueeze count2 cALLOCATABLE_REGS_DOUBLE
(realRegSqueeze RcDouble)
exclusions
= count3 < cALLOCATABLE_REGS_DOUBLE
trivColorable platform virtualRegSqueeze realRegSqueeze RcDoubleSSE conflicts exclusions
| let cALLOCATABLE_REGS_SSE
= (case platformArch platform of
ArchX86 -> 8
ArchX86_64 -> 10
ArchPPC -> 0
ArchSPARC -> 0
ArchSPARC64 -> panic "trivColorable ArchSPARC64"
ArchPPC_64 _ -> panic "trivColorable ArchPPC_64"
ArchARM _ _ _ -> panic "trivColorable ArchARM"
ArchARM64 -> panic "trivColorable ArchARM64"
ArchAlpha -> panic "trivColorable ArchAlpha"
ArchMipseb -> panic "trivColorable ArchMipseb"
ArchMipsel -> panic "trivColorable ArchMipsel"
ArchJavaScript-> panic "trivColorable ArchJavaScript"
ArchUnknown -> panic "trivColorable ArchUnknown")
, count2 <- accSqueeze 0 cALLOCATABLE_REGS_SSE
(virtualRegSqueeze RcDoubleSSE)
conflicts
, count3 <- accSqueeze count2 cALLOCATABLE_REGS_SSE
(realRegSqueeze RcDoubleSSE)
exclusions
= count3 < cALLOCATABLE_REGS_SSE
-- Specification Code ----------------------------------------------------------
--
-- The trivColorable function for each particular architecture should
-- implement the following function, but faster.
--
{-
trivColorable :: RegClass -> UniqSet Reg -> UniqSet Reg -> Bool
trivColorable classN conflicts exclusions
= let
acc :: Reg -> (Int, Int) -> (Int, Int)
acc r (cd, cf)
= case regClass r of
RcInteger -> (cd+1, cf)
RcFloat -> (cd, cf+1)
_ -> panic "Regs.trivColorable: reg class not handled"
tmp = nonDetFoldUFM acc (0, 0) conflicts
(countInt, countFloat) = nonDetFoldUFM acc tmp exclusions
squeese = worst countInt classN RcInteger
+ worst countFloat classN RcFloat
in squeese < allocatableRegsInClass classN
-- | Worst case displacement
-- node N of classN has n neighbors of class C.
--
-- We currently only have RcInteger and RcDouble, which don't conflict at all.
-- This is a bit boring compared to what's in RegArchX86.
--
worst :: Int -> RegClass -> RegClass -> Int
worst n classN classC
= case classN of
RcInteger
-> case classC of
RcInteger -> min n (allocatableRegsInClass RcInteger)
RcFloat -> 0
RcDouble
-> case classC of
RcFloat -> min n (allocatableRegsInClass RcFloat)
RcInteger -> 0
-- allocatableRegs is allMachRegNos with the fixed-use regs removed.
-- i.e., these are the regs for which we are prepared to allow the
-- register allocator to attempt to map VRegs to.
allocatableRegs :: [RegNo]
allocatableRegs
= let isFree i = freeReg i
in filter isFree allMachRegNos
-- | The number of regs in each class.
-- We go via top level CAFs to ensure that we're not recomputing
-- the length of these lists each time the fn is called.
allocatableRegsInClass :: RegClass -> Int
allocatableRegsInClass cls
= case cls of
RcInteger -> allocatableRegsInteger
RcFloat -> allocatableRegsDouble
allocatableRegsInteger :: Int
allocatableRegsInteger
= length $ filter (\r -> regClass r == RcInteger)
$ map RealReg allocatableRegs
allocatableRegsFloat :: Int
allocatableRegsFloat
= length $ filter (\r -> regClass r == RcFloat
$ map RealReg allocatableRegs
-}
| snoyberg/ghc | compiler/nativeGen/RegAlloc/Graph/TrivColorable.hs | bsd-3-clause | 12,313 | 0 | 15 | 4,752 | 1,061 | 527 | 534 | 116 | 49 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Haddock
-- Copyright : Isaac Jones 2003-2005
-- License : BSD3
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module deals with the @haddock@ and @hscolour@ commands.
-- It uses information about installed packages (from @ghc-pkg@) to find the
-- locations of documentation for dependent packages, so it can create links.
--
-- The @hscolour@ support allows generating HTML versions of the original
-- source, with coloured syntax highlighting.
module Distribution.Simple.Haddock (
haddock, hscolour,
haddockPackagePaths
) where
import qualified Distribution.Simple.GHC as GHC
import qualified Distribution.Simple.GHCJS as GHCJS
-- local
import Distribution.Package
( PackageIdentifier(..)
, Package(..)
, PackageName(..), packageName, ComponentId(..) )
import qualified Distribution.ModuleName as ModuleName
import Distribution.PackageDescription as PD
( PackageDescription(..), BuildInfo(..), usedExtensions
, hcSharedOptions
, Library(..), hasLibs, Executable(..)
, TestSuite(..), TestSuiteInterface(..)
, Benchmark(..), BenchmarkInterface(..) )
import Distribution.Simple.Compiler
( Compiler, compilerInfo, CompilerFlavor(..)
, compilerFlavor, compilerCompatVersion )
import Distribution.Simple.Program.GHC
( GhcOptions(..), GhcDynLinkMode(..), renderGhcOptions )
import Distribution.Simple.Program
( ConfiguredProgram(..), lookupProgramVersion, requireProgramVersion
, rawSystemProgram, rawSystemProgramStdout
, hscolourProgram, haddockProgram )
import Distribution.Simple.PreProcess
( PPSuffixHandler, preprocessComponent)
import Distribution.Simple.Setup
( defaultHscolourFlags
, Flag(..), toFlag, flagToMaybe, flagToList, fromFlag
, HaddockFlags(..), HscolourFlags(..) )
import Distribution.Simple.Build (initialBuildSteps)
import Distribution.Simple.InstallDirs
( InstallDirs(..)
, PathTemplateEnv, PathTemplate, PathTemplateVariable(..)
, toPathTemplate, fromPathTemplate
, substPathTemplate, initialPathTemplateEnv )
import Distribution.Simple.LocalBuildInfo
( LocalBuildInfo(..), Component(..), ComponentLocalBuildInfo(..)
, withAllComponentsInBuildOrder )
import Distribution.Simple.BuildPaths
( haddockName, hscolourPref, autogenModulesDir)
import Distribution.Simple.PackageIndex (dependencyClosure)
import qualified Distribution.Simple.PackageIndex as PackageIndex
import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
( InstalledPackageInfo(..) )
import Distribution.InstalledPackageInfo
( InstalledPackageInfo )
import Distribution.Simple.Utils
( die, copyFileTo, warn, notice, intercalate, setupMessage
, createDirectoryIfMissingVerbose
, TempFileOptions(..), defaultTempFileOptions
, withTempFileEx, copyFileVerbose
, withTempDirectoryEx, matchFileGlob
, findFileWithExtension, findFile )
import Distribution.Text
( display, simpleParse )
import Distribution.Utils.NubList
( toNubListR )
import Distribution.Verbosity
import Language.Haskell.Extension
import Control.Monad ( when, forM_ )
import Data.Either ( rights )
import Data.Foldable ( traverse_ )
import Data.Monoid
import Data.Maybe ( fromMaybe, listToMaybe )
import System.Directory (doesFileExist)
import System.FilePath ( (</>), (<.>)
, normalise, splitPath, joinPath, isAbsolute )
import System.IO (hClose, hPutStrLn, hSetEncoding, utf8)
import Distribution.Version
-- ------------------------------------------------------------------------------
-- Types
-- | A record that represents the arguments to the haddock executable, a product
-- monoid.
data HaddockArgs = HaddockArgs {
argInterfaceFile :: Flag FilePath,
-- ^ Path to the interface file, relative to argOutputDir, required.
argPackageName :: Flag PackageIdentifier,
-- ^ Package name, required.
argHideModules :: (All,[ModuleName.ModuleName]),
-- ^ (Hide modules ?, modules to hide)
argIgnoreExports :: Any,
-- ^ Ignore export lists in modules?
argLinkSource :: Flag (Template,Template,Template),
-- ^ (Template for modules, template for symbols, template for lines).
argCssFile :: Flag FilePath,
-- ^ Optional custom CSS file.
argContents :: Flag String,
-- ^ Optional URL to contents page.
argVerbose :: Any,
argOutput :: Flag [Output],
-- ^ HTML or Hoogle doc or both? Required.
argInterfaces :: [(FilePath, Maybe String)],
-- ^ [(Interface file, URL to the HTML docs for links)].
argOutputDir :: Directory,
-- ^ Where to generate the documentation.
argTitle :: Flag String,
-- ^ Page title, required.
argPrologue :: Flag String,
-- ^ Prologue text, required.
argGhcOptions :: Flag (GhcOptions, Version),
-- ^ Additional flags to pass to GHC.
argGhcLibDir :: Flag FilePath,
-- ^ To find the correct GHC, required.
argTargets :: [FilePath]
-- ^ Modules to process.
}
-- | The FilePath of a directory, it's a monoid under '(</>)'.
newtype Directory = Dir { unDir' :: FilePath } deriving (Read,Show,Eq,Ord)
unDir :: Directory -> FilePath
unDir = joinPath . filter (\p -> p /="./" && p /= ".") . splitPath . unDir'
type Template = String
data Output = Html | Hoogle
-- ------------------------------------------------------------------------------
-- Haddock support
haddock :: PackageDescription
-> LocalBuildInfo
-> [PPSuffixHandler]
-> HaddockFlags
-> IO ()
haddock pkg_descr _ _ haddockFlags
| not (hasLibs pkg_descr)
&& not (fromFlag $ haddockExecutables haddockFlags)
&& not (fromFlag $ haddockTestSuites haddockFlags)
&& not (fromFlag $ haddockBenchmarks haddockFlags) =
warn (fromFlag $ haddockVerbosity haddockFlags) $
"No documentation was generated as this package does not contain "
++ "a library. Perhaps you want to use the --executables, --tests or"
++ " --benchmarks flags."
haddock pkg_descr lbi suffixes flags' = do
let verbosity = flag haddockVerbosity
comp = compiler lbi
flags
| fromFlag (haddockForHackage flags') = flags'
{ haddockHoogle = Flag True
, haddockHtml = Flag True
, haddockHtmlLocation = Flag (pkg_url ++ "/docs")
, haddockContents = Flag (toPathTemplate pkg_url)
, haddockHscolour = Flag True
}
| otherwise = flags'
pkg_url = "/package/$pkg-$version"
flag f = fromFlag $ f flags
tmpFileOpts = defaultTempFileOptions
{ optKeepTempFiles = flag haddockKeepTempFiles }
htmlTemplate = fmap toPathTemplate . flagToMaybe . haddockHtmlLocation
$ flags
setupMessage verbosity "Running Haddock for" (packageId pkg_descr)
(confHaddock, version, _) <-
requireProgramVersion verbosity haddockProgram
(orLaterVersion (Version [2,0] [])) (withPrograms lbi)
-- various sanity checks
when ( flag haddockHoogle
&& version < Version [2,2] []) $
die "haddock 2.0 and 2.1 do not support the --hoogle flag."
haddockGhcVersionStr <- rawSystemProgramStdout verbosity confHaddock
["--ghc-version"]
case (simpleParse haddockGhcVersionStr, compilerCompatVersion GHC comp) of
(Nothing, _) -> die "Could not get GHC version from Haddock"
(_, Nothing) -> die "Could not get GHC version from compiler"
(Just haddockGhcVersion, Just ghcVersion)
| haddockGhcVersion == ghcVersion -> return ()
| otherwise -> die $
"Haddock's internal GHC version must match the configured "
++ "GHC version.\n"
++ "The GHC version is " ++ display ghcVersion ++ " but "
++ "haddock is using GHC version " ++ display haddockGhcVersion
-- the tools match the requests, we can proceed
initialBuildSteps (flag haddockDistPref) pkg_descr lbi verbosity
when (flag haddockHscolour) $
hscolour' (warn verbosity) pkg_descr lbi suffixes
(defaultHscolourFlags `mappend` haddockToHscolour flags)
libdirArgs <- getGhcLibDir verbosity lbi
let commonArgs = mconcat
[ libdirArgs
, fromFlags (haddockTemplateEnv lbi (packageId pkg_descr)) flags
, fromPackageDescription pkg_descr ]
let pre c = preprocessComponent pkg_descr c lbi False verbosity suffixes
withAllComponentsInBuildOrder pkg_descr lbi $ \component clbi -> do
pre component
let
doExe com = case (compToExe com) of
Just exe -> do
withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $
\tmp -> do
exeArgs <- fromExecutable verbosity tmp lbi exe clbi htmlTemplate
version
let exeArgs' = commonArgs `mappend` exeArgs
runHaddock verbosity tmpFileOpts comp confHaddock exeArgs'
Nothing -> do
warn (fromFlag $ haddockVerbosity flags)
"Unsupported component, skipping..."
return ()
case component of
CLib lib -> do
withTempDirectoryEx verbosity tmpFileOpts (buildDir lbi) "tmp" $
\tmp -> do
libArgs <- fromLibrary verbosity tmp lbi lib clbi htmlTemplate
version
let libArgs' = commonArgs `mappend` libArgs
runHaddock verbosity tmpFileOpts comp confHaddock libArgs'
CExe _ -> when (flag haddockExecutables) $ doExe component
CTest _ -> when (flag haddockTestSuites) $ doExe component
CBench _ -> when (flag haddockBenchmarks) $ doExe component
forM_ (extraDocFiles pkg_descr) $ \ fpath -> do
files <- matchFileGlob fpath
forM_ files $ copyFileTo verbosity (unDir $ argOutputDir commonArgs)
-- ------------------------------------------------------------------------------
-- Contributions to HaddockArgs.
fromFlags :: PathTemplateEnv -> HaddockFlags -> HaddockArgs
fromFlags env flags =
mempty {
argHideModules = (maybe mempty (All . not)
$ flagToMaybe (haddockInternal flags), mempty),
argLinkSource = if fromFlag (haddockHscolour flags)
then Flag ("src/%{MODULE/./-}.html"
,"src/%{MODULE/./-}.html#%{NAME}"
,"src/%{MODULE/./-}.html#line-%{LINE}")
else NoFlag,
argCssFile = haddockCss flags,
argContents = fmap (fromPathTemplate . substPathTemplate env)
(haddockContents flags),
argVerbose = maybe mempty (Any . (>= deafening))
. flagToMaybe $ haddockVerbosity flags,
argOutput =
Flag $ case [ Html | Flag True <- [haddockHtml flags] ] ++
[ Hoogle | Flag True <- [haddockHoogle flags] ]
of [] -> [ Html ]
os -> os,
argOutputDir = maybe mempty Dir . flagToMaybe $ haddockDistPref flags
}
fromPackageDescription :: PackageDescription -> HaddockArgs
fromPackageDescription pkg_descr =
mempty { argInterfaceFile = Flag $ haddockName pkg_descr,
argPackageName = Flag $ packageId $ pkg_descr,
argOutputDir = Dir $ "doc" </> "html"
</> display (packageName pkg_descr),
argPrologue = Flag $ if null desc then synopsis pkg_descr
else desc,
argTitle = Flag $ showPkg ++ subtitle
}
where
desc = PD.description pkg_descr
showPkg = display (packageId pkg_descr)
subtitle | null (synopsis pkg_descr) = ""
| otherwise = ": " ++ synopsis pkg_descr
componentGhcOptions :: Verbosity -> LocalBuildInfo
-> BuildInfo -> ComponentLocalBuildInfo -> FilePath
-> GhcOptions
componentGhcOptions verbosity lbi bi clbi odir =
let f = case compilerFlavor (compiler lbi) of
GHC -> GHC.componentGhcOptions
GHCJS -> GHCJS.componentGhcOptions
_ -> error $
"Distribution.Simple.Haddock.componentGhcOptions:" ++
"haddock only supports GHC and GHCJS"
in f verbosity lbi bi clbi odir
fromLibrary :: Verbosity
-> FilePath
-> LocalBuildInfo -> Library -> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> Version
-> IO HaddockArgs
fromLibrary verbosity tmp lbi lib clbi htmlTemplate haddockVersion = do
inFiles <- map snd `fmap` getLibSourceFiles lbi lib
ifaceArgs <- getInterfaces verbosity lbi clbi htmlTemplate
let vanillaOpts = (componentGhcOptions normal lbi bi clbi (buildDir lbi)) {
-- Noooooooooo!!!!!111
-- haddock stomps on our precious .hi
-- and .o files. Workaround by telling
-- haddock to write them elsewhere.
ghcOptObjDir = toFlag tmp,
ghcOptHiDir = toFlag tmp,
ghcOptStubDir = toFlag tmp
} `mappend` getGhcCppOpts haddockVersion bi
sharedOpts = vanillaOpts {
ghcOptDynLinkMode = toFlag GhcDynamicOnly,
ghcOptFPic = toFlag True,
ghcOptHiSuffix = toFlag "dyn_hi",
ghcOptObjSuffix = toFlag "dyn_o",
ghcOptExtra =
toNubListR $ hcSharedOptions GHC bi
}
opts <- if withVanillaLib lbi
then return vanillaOpts
else if withSharedLib lbi
then return sharedOpts
else die $ "Must have vanilla or shared libraries "
++ "enabled in order to run haddock"
ghcVersion <- maybe (die "Compiler has no GHC version")
return
(compilerCompatVersion GHC (compiler lbi))
return ifaceArgs {
argHideModules = (mempty,otherModules $ bi),
argGhcOptions = toFlag (opts, ghcVersion),
argTargets = inFiles
}
where
bi = libBuildInfo lib
fromExecutable :: Verbosity
-> FilePath
-> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> Version
-> IO HaddockArgs
fromExecutable verbosity tmp lbi exe clbi htmlTemplate haddockVersion = do
inFiles <- map snd `fmap` getExeSourceFiles lbi exe
ifaceArgs <- getInterfaces verbosity lbi clbi htmlTemplate
let vanillaOpts = (componentGhcOptions normal lbi bi clbi (buildDir lbi)) {
-- Noooooooooo!!!!!111
-- haddock stomps on our precious .hi
-- and .o files. Workaround by telling
-- haddock to write them elsewhere.
ghcOptObjDir = toFlag tmp,
ghcOptHiDir = toFlag tmp,
ghcOptStubDir = toFlag tmp
} `mappend` getGhcCppOpts haddockVersion bi
sharedOpts = vanillaOpts {
ghcOptDynLinkMode = toFlag GhcDynamicOnly,
ghcOptFPic = toFlag True,
ghcOptHiSuffix = toFlag "dyn_hi",
ghcOptObjSuffix = toFlag "dyn_o",
ghcOptExtra =
toNubListR $ hcSharedOptions GHC bi
}
opts <- if withVanillaLib lbi
then return vanillaOpts
else if withSharedLib lbi
then return sharedOpts
else die $ "Must have vanilla or shared libraries "
++ "enabled in order to run haddock"
ghcVersion <- maybe (die "Compiler has no GHC version")
return
(compilerCompatVersion GHC (compiler lbi))
return ifaceArgs {
argGhcOptions = toFlag (opts, ghcVersion),
argOutputDir = Dir (exeName exe),
argTitle = Flag (exeName exe),
argTargets = inFiles
}
where
bi = buildInfo exe
compToExe :: Component -> Maybe Executable
compToExe comp =
case comp of
CTest test@TestSuite { testInterface = TestSuiteExeV10 _ f } ->
Just Executable {
exeName = testName test,
modulePath = f,
buildInfo = testBuildInfo test
}
CBench bench@Benchmark { benchmarkInterface = BenchmarkExeV10 _ f } ->
Just Executable {
exeName = benchmarkName bench,
modulePath = f,
buildInfo = benchmarkBuildInfo bench
}
CExe exe -> Just exe
_ -> Nothing
getInterfaces :: Verbosity
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate -- ^ template for HTML location
-> IO HaddockArgs
getInterfaces verbosity lbi clbi htmlTemplate = do
(packageFlags, warnings) <- haddockPackageFlags lbi clbi htmlTemplate
traverse_ (warn verbosity) warnings
return $ mempty {
argInterfaces = packageFlags
}
getGhcCppOpts :: Version
-> BuildInfo
-> GhcOptions
getGhcCppOpts haddockVersion bi =
mempty {
ghcOptExtensions = toNubListR [EnableExtension CPP | needsCpp],
ghcOptCppOptions = toNubListR defines
}
where
needsCpp = EnableExtension CPP `elem` usedExtensions bi
defines = [haddockVersionMacro]
haddockVersionMacro = "-D__HADDOCK_VERSION__="
++ show (v1 * 1000 + v2 * 10 + v3)
where
[v1, v2, v3] = take 3 $ versionBranch haddockVersion ++ [0,0]
getGhcLibDir :: Verbosity -> LocalBuildInfo
-> IO HaddockArgs
getGhcLibDir verbosity lbi = do
l <- case compilerFlavor (compiler lbi) of
GHC -> GHC.getLibDir verbosity lbi
GHCJS -> GHCJS.getLibDir verbosity lbi
_ -> error "haddock only supports GHC and GHCJS"
return $ mempty { argGhcLibDir = Flag l }
-- ------------------------------------------------------------------------------
-- | Call haddock with the specified arguments.
runHaddock :: Verbosity
-> TempFileOptions
-> Compiler
-> ConfiguredProgram
-> HaddockArgs
-> IO ()
runHaddock verbosity tmpFileOpts comp confHaddock args = do
let haddockVersion = fromMaybe (error "unable to determine haddock version")
(programVersion confHaddock)
renderArgs verbosity tmpFileOpts haddockVersion comp args $
\(flags,result)-> do
rawSystemProgram verbosity confHaddock flags
notice verbosity $ "Documentation created: " ++ result
renderArgs :: Verbosity
-> TempFileOptions
-> Version
-> Compiler
-> HaddockArgs
-> (([String], FilePath) -> IO a)
-> IO a
renderArgs verbosity tmpFileOpts version comp args k = do
let haddockSupportsUTF8 = version >= Version [2,14,4] []
haddockSupportsResponseFiles = version > Version [2,16,1] []
createDirectoryIfMissingVerbose verbosity True outputDir
withTempFileEx tmpFileOpts outputDir "haddock-prologue.txt" $
\prologueFileName h -> do
do
when haddockSupportsUTF8 (hSetEncoding h utf8)
hPutStrLn h $ fromFlag $ argPrologue args
hClose h
let pflag = "--prologue=" ++ prologueFileName
renderedArgs = pflag : renderPureArgs version comp args
if haddockSupportsResponseFiles
then
withTempFileEx tmpFileOpts outputDir "haddock-response.txt" $
\responseFileName hf -> do
when haddockSupportsUTF8 (hSetEncoding hf utf8)
mapM_ (hPutStrLn hf) renderedArgs
hClose hf
let respFile = "@" ++ responseFileName
k ([respFile], result)
else
k (renderedArgs, result)
where
outputDir = (unDir $ argOutputDir args)
result = intercalate ", "
. map (\o -> outputDir </>
case o of
Html -> "index.html"
Hoogle -> pkgstr <.> "txt")
$ arg argOutput
where
pkgstr = display $ packageName pkgid
pkgid = arg argPackageName
arg f = fromFlag $ f args
renderPureArgs :: Version -> Compiler -> HaddockArgs -> [String]
renderPureArgs version comp args = concat
[ (:[]) . (\f -> "--dump-interface="++ unDir (argOutputDir args) </> f)
. fromFlag . argInterfaceFile $ args
, if isVersion 2 16
then (\pkg -> [ "--package-name=" ++ display (pkgName pkg)
, "--package-version="++display (pkgVersion pkg)
])
. fromFlag . argPackageName $ args
else []
, (\(All b,xs) -> bool (map (("--hide=" ++). display) xs) [] b)
. argHideModules $ args
, bool ["--ignore-all-exports"] [] . getAny . argIgnoreExports $ args
, maybe [] (\(m,e,l) ->
["--source-module=" ++ m
,"--source-entity=" ++ e]
++ if isVersion 2 14 then ["--source-entity-line=" ++ l]
else []
) . flagToMaybe . argLinkSource $ args
, maybe [] ((:[]) . ("--css="++)) . flagToMaybe . argCssFile $ args
, maybe [] ((:[]) . ("--use-contents="++)) . flagToMaybe . argContents $ args
, bool [] [verbosityFlag] . getAny . argVerbose $ args
, map (\o -> case o of Hoogle -> "--hoogle"; Html -> "--html")
. fromFlag . argOutput $ args
, renderInterfaces . argInterfaces $ args
, (:[]) . ("--odir="++) . unDir . argOutputDir $ args
, (:[]) . ("--title="++)
. (bool (++" (internal documentation)")
id (getAny $ argIgnoreExports args))
. fromFlag . argTitle $ args
, [ "--optghc=" ++ opt | (opts, _ghcVer) <- flagToList (argGhcOptions args)
, opt <- renderGhcOptions comp opts ]
, maybe [] (\l -> ["-B"++l]) $
flagToMaybe (argGhcLibDir args) -- error if Nothing?
, argTargets $ args
]
where
renderInterfaces =
map (\(i,mh) -> "--read-interface=" ++
maybe "" (++",") mh ++ i)
bool a b c = if c then a else b
isVersion major minor = version >= Version [major,minor] []
verbosityFlag
| isVersion 2 5 = "--verbosity=1"
| otherwise = "--verbose"
---------------------------------------------------------------------------------
-- | Given a list of 'InstalledPackageInfo's, return a list of interfaces and
-- HTML paths, and an optional warning for packages with missing documentation.
haddockPackagePaths :: [InstalledPackageInfo]
-> Maybe (InstalledPackageInfo -> FilePath)
-> IO ([(FilePath, Maybe FilePath)], Maybe String)
haddockPackagePaths ipkgs mkHtmlPath = do
interfaces <- sequence
[ case interfaceAndHtmlPath ipkg of
Nothing -> return (Left (packageId ipkg))
Just (interface, html) -> do
exists <- doesFileExist interface
if exists
then return (Right (interface, html))
else return (Left pkgid)
| ipkg <- ipkgs, let pkgid = packageId ipkg
, pkgName pkgid `notElem` noHaddockWhitelist
]
let missing = [ pkgid | Left pkgid <- interfaces ]
warning = "The documentation for the following packages are not "
++ "installed. No links will be generated to these packages: "
++ intercalate ", " (map display missing)
flags = rights interfaces
return (flags, if null missing then Nothing else Just warning)
where
-- Don't warn about missing documentation for these packages. See #1231.
noHaddockWhitelist = map PackageName [ "rts" ]
-- Actually extract interface and HTML paths from an 'InstalledPackageInfo'.
interfaceAndHtmlPath :: InstalledPackageInfo
-> Maybe (FilePath, Maybe FilePath)
interfaceAndHtmlPath pkg = do
interface <- listToMaybe (InstalledPackageInfo.haddockInterfaces pkg)
html <- case mkHtmlPath of
Nothing -> fmap fixFileUrl
(listToMaybe (InstalledPackageInfo.haddockHTMLs pkg))
Just mkPath -> Just (mkPath pkg)
return (interface, if null html then Nothing else Just html)
where
-- The 'haddock-html' field in the hc-pkg output is often set as a
-- native path, but we need it as a URL. See #1064.
fixFileUrl f | isAbsolute f = "file://" ++ f
| otherwise = f
haddockPackageFlags :: LocalBuildInfo
-> ComponentLocalBuildInfo
-> Maybe PathTemplate
-> IO ([(FilePath, Maybe FilePath)], Maybe String)
haddockPackageFlags lbi clbi htmlTemplate = do
let allPkgs = installedPkgs lbi
directDeps = map fst (componentPackageDeps clbi)
transitiveDeps <- case dependencyClosure allPkgs directDeps of
Left x -> return x
Right inf -> die $ "internal error when calculating transitive "
++ "package dependencies.\nDebug info: " ++ show inf
haddockPackagePaths (PackageIndex.allPackages transitiveDeps) mkHtmlPath
where
mkHtmlPath = fmap expandTemplateVars htmlTemplate
expandTemplateVars tmpl pkg =
fromPathTemplate . substPathTemplate (env pkg) $ tmpl
env pkg = haddockTemplateEnv lbi (packageId pkg)
haddockTemplateEnv :: LocalBuildInfo -> PackageIdentifier -> PathTemplateEnv
haddockTemplateEnv lbi pkg_id =
(PrefixVar, prefix (installDirTemplates lbi))
: initialPathTemplateEnv pkg_id (ComponentId (display pkg_id)) (compilerInfo (compiler lbi))
(hostPlatform lbi)
-- ------------------------------------------------------------------------------
-- hscolour support.
hscolour :: PackageDescription
-> LocalBuildInfo
-> [PPSuffixHandler]
-> HscolourFlags
-> IO ()
hscolour pkg_descr lbi suffixes flags = do
-- we preprocess even if hscolour won't be found on the machine
-- will this upset someone?
initialBuildSteps distPref pkg_descr lbi verbosity
hscolour' die pkg_descr lbi suffixes flags
where
verbosity = fromFlag (hscolourVerbosity flags)
distPref = fromFlag $ hscolourDistPref flags
hscolour' :: (String -> IO ()) -- ^ Called when the 'hscolour' exe is not found.
-> PackageDescription
-> LocalBuildInfo
-> [PPSuffixHandler]
-> HscolourFlags
-> IO ()
hscolour' onNoHsColour pkg_descr lbi suffixes flags =
either onNoHsColour (\(hscolourProg, _, _) -> go hscolourProg) =<<
lookupProgramVersion verbosity hscolourProgram
(orLaterVersion (Version [1,8] [])) (withPrograms lbi)
where
go :: ConfiguredProgram -> IO ()
go hscolourProg = do
setupMessage verbosity "Running hscolour for" (packageId pkg_descr)
createDirectoryIfMissingVerbose verbosity True $
hscolourPref distPref pkg_descr
let pre c = preprocessComponent pkg_descr c lbi False verbosity suffixes
withAllComponentsInBuildOrder pkg_descr lbi $ \comp _ -> do
pre comp
let
doExe com = case (compToExe com) of
Just exe -> do
let outputDir = hscolourPref distPref pkg_descr
</> exeName exe </> "src"
runHsColour hscolourProg outputDir =<< getExeSourceFiles lbi exe
Nothing -> do
warn (fromFlag $ hscolourVerbosity flags)
"Unsupported component, skipping..."
return ()
case comp of
CLib lib -> do
let outputDir = hscolourPref distPref pkg_descr </> "src"
runHsColour hscolourProg outputDir =<< getLibSourceFiles lbi lib
CExe _ -> when (fromFlag (hscolourExecutables flags)) $ doExe comp
CTest _ -> when (fromFlag (hscolourTestSuites flags)) $ doExe comp
CBench _ -> when (fromFlag (hscolourBenchmarks flags)) $ doExe comp
stylesheet = flagToMaybe (hscolourCSS flags)
verbosity = fromFlag (hscolourVerbosity flags)
distPref = fromFlag (hscolourDistPref flags)
runHsColour prog outputDir moduleFiles = do
createDirectoryIfMissingVerbose verbosity True outputDir
case stylesheet of -- copy the CSS file
Nothing | programVersion prog >= Just (Version [1,9] []) ->
rawSystemProgram verbosity prog
["-print-css", "-o" ++ outputDir </> "hscolour.css"]
| otherwise -> return ()
Just s -> copyFileVerbose verbosity s (outputDir </> "hscolour.css")
forM_ moduleFiles $ \(m, inFile) ->
rawSystemProgram verbosity prog
["-css", "-anchor", "-o" ++ outFile m, inFile]
where
outFile m = outputDir </>
intercalate "-" (ModuleName.components m) <.> "html"
haddockToHscolour :: HaddockFlags -> HscolourFlags
haddockToHscolour flags =
HscolourFlags {
hscolourCSS = haddockHscolourCss flags,
hscolourExecutables = haddockExecutables flags,
hscolourTestSuites = haddockTestSuites flags,
hscolourBenchmarks = haddockBenchmarks flags,
hscolourVerbosity = haddockVerbosity flags,
hscolourDistPref = haddockDistPref flags
}
---------------------------------------------------------------------------------
-- TODO these should be moved elsewhere.
getLibSourceFiles :: LocalBuildInfo
-> Library
-> IO [(ModuleName.ModuleName, FilePath)]
getLibSourceFiles lbi lib = getSourceFiles searchpaths modules
where
bi = libBuildInfo lib
modules = PD.exposedModules lib ++ otherModules bi
searchpaths = autogenModulesDir lbi : buildDir lbi : hsSourceDirs bi
getExeSourceFiles :: LocalBuildInfo
-> Executable
-> IO [(ModuleName.ModuleName, FilePath)]
getExeSourceFiles lbi exe = do
moduleFiles <- getSourceFiles searchpaths modules
srcMainPath <- findFile (hsSourceDirs bi) (modulePath exe)
return ((ModuleName.main, srcMainPath) : moduleFiles)
where
bi = buildInfo exe
modules = otherModules bi
searchpaths = autogenModulesDir lbi : exeBuildDir lbi exe : hsSourceDirs bi
getSourceFiles :: [FilePath]
-> [ModuleName.ModuleName]
-> IO [(ModuleName.ModuleName, FilePath)]
getSourceFiles dirs modules = flip mapM modules $ \m -> fmap ((,) m) $
findFileWithExtension ["hs", "lhs"] dirs (ModuleName.toFilePath m)
>>= maybe (notFound m) (return . normalise)
where
notFound module_ = die $ "can't find source for module " ++ display module_
-- | The directory where we put build results for an executable
exeBuildDir :: LocalBuildInfo -> Executable -> FilePath
exeBuildDir lbi exe = buildDir lbi </> exeName exe </> exeName exe ++ "-tmp"
-- ------------------------------------------------------------------------------
-- Boilerplate Monoid instance.
instance Monoid HaddockArgs where
mempty = HaddockArgs {
argInterfaceFile = mempty,
argPackageName = mempty,
argHideModules = mempty,
argIgnoreExports = mempty,
argLinkSource = mempty,
argCssFile = mempty,
argContents = mempty,
argVerbose = mempty,
argOutput = mempty,
argInterfaces = mempty,
argOutputDir = mempty,
argTitle = mempty,
argPrologue = mempty,
argGhcOptions = mempty,
argGhcLibDir = mempty,
argTargets = mempty
}
mappend a b = HaddockArgs {
argInterfaceFile = mult argInterfaceFile,
argPackageName = mult argPackageName,
argHideModules = mult argHideModules,
argIgnoreExports = mult argIgnoreExports,
argLinkSource = mult argLinkSource,
argCssFile = mult argCssFile,
argContents = mult argContents,
argVerbose = mult argVerbose,
argOutput = mult argOutput,
argInterfaces = mult argInterfaces,
argOutputDir = mult argOutputDir,
argTitle = mult argTitle,
argPrologue = mult argPrologue,
argGhcOptions = mult argGhcOptions,
argGhcLibDir = mult argGhcLibDir,
argTargets = mult argTargets
}
where mult f = f a `mappend` f b
instance Monoid Directory where
mempty = Dir "."
mappend (Dir m) (Dir n) = Dir $ m </> n
| enolan/cabal | Cabal/Distribution/Simple/Haddock.hs | bsd-3-clause | 33,763 | 0 | 26 | 10,385 | 7,568 | 3,973 | 3,595 | 624 | 7 |
module Meas () where
import Language.Haskell.Liquid.Prelude
prop1 = map choo [[True]] -- replace [[1]] with [[]] for UNSAT
choo (x:xs) = liquidAssertB False
-- choo [] = liquidAssertB False
-- import qualified Data.Map as M
-- import Data.List (foldl')
--keyvals :: [(Int, Int)]
--keyvals = [(1, 1), (2, 2), (3, 3)]
--
--group :: (Ord k) => [(k, v)] -> M.Map k [v]
--group = foldl' addKV M.empty
--
--addKV m (k, v) = let boo = liquidAssertB False in M.insert k vs' m
-- where vs' = v : (M.findWithDefault [] k m)
--
--checkNN m = M.foldrWithKey reduceKV False m
--
--reduceKV _ _ acc = liquidAssertB False
--
--prop = checkNN (group keyvals)
| mightymoose/liquidhaskell | tests/neg/mapreduce-tiny.hs | bsd-3-clause | 665 | 0 | 7 | 138 | 66 | 46 | 20 | 4 | 1 |
module Cmp () where
import Language.Haskell.Liquid.Prelude
foo x y
= case compare x y of
EQ -> liquidAssertB (x == y)
LT -> liquidAssertB (x < y)
GT -> liquidAssertB (x > y)
prop = foo n m
where n = choose 0
m = choose 1
| mightymoose/liquidhaskell | tests/pos/compare.hs | bsd-3-clause | 249 | 0 | 10 | 75 | 109 | 57 | 52 | 10 | 3 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds, PolyKinds #-}
module T11407 where
import Data.Kind
type Const a b = a
data family UhOh (f :: k1) (a :: k2) (b :: k3)
data instance UhOh (f :: * -> * -> *) (a :: x a) (b :: Const * a) = UhOh
| sdiehl/ghc | testsuite/tests/dependent/should_fail/T11407.hs | bsd-3-clause | 247 | 0 | 9 | 56 | 94 | 59 | 35 | 7 | 0 |
{-# LANGUAGE PackageImports #-}
import qualified Network.CGI
import qualified Network.Wai.Handler.SimpleServer
import qualified Network.Wai.Frontend.MonadCGI
import "mtl" Control.Monad.Reader
main :: IO ()
main = Network.Wai.Handler.SimpleServer.run 3000
$ Network.Wai.Frontend.MonadCGI.cgiToAppGeneric
monadToIO
mainCGI
mainCGI :: Network.CGI.CGIT (Reader String) Network.CGI.CGIResult
mainCGI = do
s <- lift ask
Network.CGI.output s
monadToIO :: Reader String a -> IO a
monadToIO = return . (flip runReader) "This is a generic test"
| jberryman/wai | wai-frontend-monadcgi/samples/wai_cgi_generic.hs | mit | 565 | 0 | 8 | 92 | 149 | 83 | 66 | 16 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
module API where
import Control.DeepSeq
import Data.Aeson
import Data.Aeson.Casing
import Data.Text (Text)
import Data.Time
import GHC.Generics
import Servant.API
type Email = Text
type API
= "player" :> ReqBody '[JSON] NewPlayer :> Post '[JSON] ()
:<|> "fortune" :> "trade"
:> Capture "email" Text :> Capture "email" Text :> Get '[JSON] FortunePair
data NewPlayer
= NewPlayer
{ npEmail :: Email
, npFortune :: Text
}
deriving (Eq, Ord, Show, Generic)
instance NFData NewPlayer
instance FromJSON NewPlayer where
parseJSON = genericParseJSON $ aesonPrefix snakeCase
data Fortune
= Fortune
{ fFortune :: Text
, fCreatedAt :: UTCTime
}
deriving (Eq, Ord, Show, Generic)
instance NFData Fortune
instance ToJSON Fortune where
toJSON = genericToJSON $ aesonPrefix snakeCase
data FortunePair
= FortunePair
{ fpFortuneGiven :: Fortune
, fpFortuneReceived :: Fortune
}
deriving (Eq, Ord, Show, Generic)
instance NFData FortunePair
instance ToJSON FortunePair where
toJSON = genericToJSON $ aesonPrefix snakeCase
| AndrewRademacher/whimsy | src/API.hs | mit | 1,365 | 0 | 14 | 397 | 332 | 182 | 150 | 41 | 0 |
module Main
( main
) where
import Prelude
import Test.DocTest
main :: IO ()
main = doctest ["-isrc", "src/"]
| pbrisbin/yesod-paginator | doctest/Main.hs | mit | 120 | 0 | 6 | 30 | 41 | 24 | 17 | 6 | 1 |
module Level ( readLevel
, isWall
, isGoal
, isBlock
, pushBlock
, isComplete
) where
--------------------------------------------------
import qualified Data.Set as S
import Coord
import Types
--------------------------------------------------
-- | Read a Level from a file.
readLevel :: String -> IO Level
readLevel filename = do
map <- readFile filename
let map' = strsToLevel (lines map)
return map'
{-|
Read a String representation of a map and convert
it to the internal Level structure.
Key:
* '#' = Wall
* '_' = Goal
* 'O' = Block
* '@' = Player starting location
-}
strsToLevel :: [String] -> Level
strsToLevel str = foldl populate emptyLevel { lMax = maxXY } asciiMap
where
asciiMap = concat $ zipWith zip coords str
coords = [[(Coord x y) | x <- [0..]] | y <- [0..]]
maxX = maximum . map (x . fst) $ asciiMap
maxY = maximum . map (y . fst) $ asciiMap
maxXY = Coord maxX maxY
populate lvl (coord, tile) =
case tile of
'#' -> lvl { lWalls = S.insert coord w}
'_' -> lvl { lGoals = S.insert coord g}
'O' -> lvl { lBlocks = S.insert coord b}
'@' -> lvl { lStart = coord }
_ -> lvl
where
w = lWalls lvl
g = lGoals lvl
b = lBlocks lvl
-- | True if (x, y) is a Wall tile, else False.
isWall coord lvl = S.member coord (lWalls lvl)
-- | True if (x, y) is a Goal tile, else False.
isGoal coord lvl = S.member coord (lGoals lvl)
-- | True if (x, y) is a Block tile, else False.
isBlock coord lvl = S.member coord (lBlocks lvl)
{-|
True when the level is complete.
A level is complete when all Goal tiles
contain blocks.
-}
isComplete :: Level -> Bool
isComplete (Level _ _ _ _ _ goals blocks) =
goals `S.isSubsetOf` blocks
-- | Move Block from pos to newPos
moveBlock :: Level -> Coord -> Coord -> Level
moveBlock lvl pos newPos
| S.member pos blocks = lvl { lBlocks = blocks' }
| otherwise = lvl
where
blocks = lBlocks lvl
blocks' = S.insert newPos $ S.delete pos blocks
-- | Push a block at coord 1 position in the given
-- direction.
pushBlock :: Level -> Coord -> Direction -> Level
pushBlock lvl pos dir
| S.member pos blocks = moveBlock lvl' pos newPos
| otherwise = lvl
where
blocks = lBlocks lvl
newPos = pos + dirToCoord dir
lvl' = pushBlock lvl newPos dir
| stuhacking/Sokoban | src/Level.hs | mit | 2,485 | 0 | 13 | 736 | 676 | 353 | 323 | 50 | 5 |
module Oodle.ParseTree where
import Oodle.Token (Token, fakeToken)
data Start
= Start [Class]
deriving (Show, Eq)
data Class
-- [first] Id = Class Name
-- [second] Id = Parent Name
= Class Token Id Id [Var] [Method]
deriving (Show, Eq)
data Var
= Var Token Id Type Expression
deriving (Show, Eq)
data Method
-- Id = Method name
-- Type = return type
-- [Argument] = arguments
-- [Var] = variable declarations
-- [Statement] = statments
= Method Token Id Type [Argument] [Var] [Statement]
deriving (Show, Eq)
data Argument = Argument Token Id {- Id is an IdArray -} Type
deriving (Show, Eq)
data Statement
= AssignStatement Token Id {- Id is an IdArray -} Expression
-- conditional if stmts else stmts
| IfStatement Token Expression [Statement] [Statement]
-- conditional do stmts
| LoopStatement Token Expression [Statement]
-- scope name arguments
| CallStatement Token Expression Id [Expression]
deriving (Show, Eq)
data Id
= Id { getIdString :: String }
| IdArray String [Expression]
deriving (Show, Eq)
data Type
= TypeInt
| TypeBoolean
| TypeId { getId :: Id }
| TypeExp Type Expression
| TypeArray Type
| TypeNoop
typeNull :: Type
typeNull = TypeId (Id "null")
typeString :: Type
typeString = TypeId (Id "String")
instance Show Type where
(show) TypeInt = "Int"
(show) TypeBoolean = "Boolean"
(show) (TypeId (Id t)) = t
(show) (TypeId (IdArray t _)) = t
(show) (TypeExp t _ ) = show t
(show) (TypeArray t) = "[]" ++ show t
(show) TypeNoop = "Noop"
instance Eq Type where
(==) (TypeId _) (TypeId (Id "null")) = True
(==) (TypeId (Id "null")) (TypeId _) = True
(==) (TypeId (Id t)) (TypeId (Id t')) = t == t'
(==) TypeInt TypeInt = True
(==) TypeBoolean TypeBoolean = True
(==) TypeNoop TypeNoop = True
(==) (TypeExp t e) (TypeExp t' e') = t == t' && e == e'
(==) (TypeArray t) (TypeArray t') = t == t'
(==) _ _ = False
isArrayType :: Type -> Bool
isArrayType (TypeArray _) = True
isArrayType _ = False
isNullType :: Type -> Bool
isNullType (TypeId (Id "null")) = True
isNullType _ = False
data Expression
= ExpressionInt Token Int
| ExpressionId Token Id
| ExpressionStr Token String
| ExpressionTrue Token
| ExpressionFalse Token
| ExpressionMe Token
| ExpressionNew Token Type
| ExpressionCall Token Expression Id [Expression]
| ExpressionIdArray Token Id
| ExpressionNot Token Expression
| ExpressionNeg Token Expression
| ExpressionPos Token Expression
| ExpressionMul Token Expression Expression
| ExpressionDiv Token Expression Expression
| ExpressionAdd Token Expression Expression
| ExpressionSub Token Expression Expression
| ExpressionStrCat Token Expression Expression
| ExpressionEq Token Expression Expression
| ExpressionGt Token Expression Expression
| ExpressionGtEq Token Expression Expression
| ExpressionAnd Token Expression Expression
| ExpressionOr Token Expression Expression
| ExpressionNull Token
| ExpressionNoop -- noop
deriving (Show, Eq)
getExprToken :: Expression -> Token
getExprToken expr =
case expr of
ExpressionInt tk _ -> tk
ExpressionId tk _ -> tk
ExpressionStr tk _ -> tk
ExpressionTrue tk -> tk
ExpressionFalse tk -> tk
ExpressionMe tk -> tk
ExpressionNew tk _ -> tk
ExpressionCall tk _ _ _ -> tk
ExpressionIdArray tk _ -> tk
ExpressionNot tk _ -> tk
ExpressionNeg tk _ -> tk
ExpressionPos tk _ -> tk
ExpressionMul tk _ _ -> tk
ExpressionDiv tk _ _ -> tk
ExpressionAdd tk _ _ -> tk
ExpressionSub tk _ _ -> tk
ExpressionStrCat tk _ _ -> tk
ExpressionEq tk _ _ -> tk
ExpressionGt tk _ _ -> tk
ExpressionGtEq tk _ _ -> tk
ExpressionAnd tk _ _ -> tk
ExpressionOr tk _ _ -> tk
ExpressionNull tk -> tk
ExpressionNoop -> fakeToken
| lseelenbinder/oodle-compiler | Oodle/ParseTree.hs | mit | 4,344 | 5 | 10 | 1,375 | 1,262 | 679 | 583 | 114 | 24 |
{- Wojciech Pratkowiecki nr indeksu: 281417 -}
import Slownie
import qualified System.Environment as SE
aud = Waluta "dolar australijski" "dolary australijskie" "dolarów australijskich" Meski
bgn = Waluta "lew bułgarski" "lewy bułgarskie" "lewów bułgarskich" Meski
brl = Waluta "real" "reale" "realów" Meski
byr = Waluta "rubel białoruski" "ruble białoruskie" "rubli białoruskich" Meski
cad = Waluta "dolar kanadyjski" "dolary kanadyjskie" "dolarów kanadyjskich" Meski
chf = Waluta "frank szwajcarski" "franki szwajcarskie" "franków szwajcarskich" Meski
cny = Waluta "juan" "juany" "juanów" Meski
czk = Waluta "korona czeska" "korony czeskie" "koron czeskich" Zenski
dkk = Waluta "korona duńska" "korony duńskie" "koron duńskich" Zenski
eur = Waluta "euro" "euro" "euro" Nijaki
gbp = Waluta "funt brytysjki" "funty brytyjskie" "funtów brytyjkich" Meski
hkd = Waluta "dolar hongkoński" "dolary hongkońskie" "dolarów hongkońskich" Meski
hrk = Waluta "kuna chorwacka" "kuny chorwackie" "kun chorwackich" Zenski
huf = Waluta "forin węgierski" "foriny węgierskie" "forinów węgierskich" Meski
idr = Waluta "rupia" "rupie" "rupii" Zenski
isk = Waluta "korona islandzka" "korony islandzkie" "koron islandzkich" Zenski
jpy = Waluta "jen japoński" "jeny japońskie" "jenów japońskich" Meski
krw = Waluta "won" "wony" "wonów" Meski
mxn = Waluta "peso" "peso" "peso" Nijaki
myr = Waluta "ringgit malezyjski" "riggity malezyjskie" "ringgitów malezyjskich" Meski
nok = Waluta "korona norweska" "korony norweskie" "koron norweskich" Zenski
nzd = Waluta "dolar nowozelandzki" "dolary nowozelandzkie" "dolarów nowozelandzkich" Meski
php = Waluta "peso filipińskie" "peso filipińskie" "peso filipińskich" Nijaki
pln = Waluta "złoty" "złote" "złotych" Meski
ron = Waluta "lej rumuński" "leje rumuńskie" "lejów rumuńskich" Meski
rub = Waluta "rubel rosyjski" "ruble rosyjskie" "rubli rosyjskich" Meski
sdr = Waluta "specjalne prawo ciągnienia" "specjalne prawa ciągnienia" "specjalnych praw ciągnienia" Nijaki
sek = Waluta "korona szwedzka" "korony szwedzkie" "koron szwedzkich" Zenski
sgd = Waluta "dolar singapurski" "dolary singapurskie" "dolarów singapurskich" Meski
thb = Waluta "baht" "bahty" "bahtów" Meski
try = Waluta "lira turecka" "liry tureckie" "lir tureckich" Zenski
uah = Waluta "hrywna" "hrywny" "hrywien" Zenski
usd = Waluta "dolar amerykański" "dolary amerykańskie" "dolarów amerykańskich" Meski
zar = Waluta "rand" "randy" "randów" Meski
get_waluta :: String -> Waluta
get_waluta nazwa =
case nazwa of
"AUD" -> aud
"BGN" -> bgn
"BRL" -> brl
"BYR" -> byr
"CAD" -> cad
"CHF" -> chf
"CNY" -> cny
"CZK" -> czk
"DKK" -> dkk
"EUR" -> eur
"GBP" -> gbp
"HKD" -> hkd
"HRK" -> hrk
"HUF" -> huf
"IDR" -> idr
"ISK" -> isk
"JPY" -> jpy
"KRW" -> krw
"MXN" -> mxn
"MYR" -> myr
"NOK" -> nok
"NZD" -> nzd
"PHP" -> php
"PLN" -> pln
"RON" -> ron
"RUB" -> rub
"SDR" -> sdr
"SEK" -> sek
"SGD" -> sgd
"THB" -> thb
"TRY" -> try
"UAH" -> uah
"USD" -> usd
"ZAR" -> zar
main = do
(n : waluta : _) <- SE.getArgs
putStrLn $ Slownie.slownie (get_waluta waluta) (read n)
| wiatrak2/Metody_programowania | waluty_slownie/Main.hs | mit | 3,168 | 2 | 10 | 535 | 767 | 386 | 381 | 76 | 34 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module Language.BrainHask.Interpreter ( MachineMemory, MachineIO(..), Machine(..), MachineM, interpretBF) where
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.RWS
import Data.Tape
import Data.Word (Word8)
import Language.BrainHask.Types
type MachineMemory = Tape Word8
data MachineIO = MachineIO { _read :: IO Word8, _write :: [Word8] -> IO () }
data Machine = Machine MachineMemory MachineIO
type MachineM = RWST MachineIO () MachineMemory IO
interpretOpIO :: Op Int -> MachineM (Op Int)
interpretOpIO (Get n)
| n <= 0 = return NoOp
| otherwise = do
(MachineIO read' _) <- ask
c <- liftIO read'
return $ Set $ fromIntegral c
interpretOpIO (Put n)
| n <= 0 = return NoOp
| otherwise = do
(MachineIO _ write') <- ask
c <- _cursor <$> get
liftIO $ write' $ replicate n c
return NoOp
interpretOpIO c = return c
interpretTapeOp :: Op Int -> MachineM ()
interpretTapeOp NoOp = return ()
interpretTapeOp (Move n) = modify $! moveRight n
interpretTapeOp (Add n) = modify $! modifyCursor $ (+) (fromIntegral n)
interpretTapeOp (Set n) = modify $! replaceCursor $ fromIntegral n
interpretTapeOp (Loop []) = return ()
interpretTapeOp (Loop ops) = do
c <- _cursor <$> get
when (c /= 0) $! interpret (ops ++ [Loop ops])
interpretTapeOp _ = return ()
interpret :: BFProgram Int -> MachineM ()
interpret = mapM_ $ interpretOpIO >=> interpretTapeOp
interpretBF :: Machine -> BFProgram Int -> IO ()
interpretBF (Machine mMemory mIO) = void . (\x -> runRWST x mIO mMemory) . interpret
| damianfral/BrainHask | src/Language/BrainHask/Interpreter.hs | mit | 1,891 | 0 | 12 | 495 | 636 | 322 | 314 | 45 | 1 |
module Parametricity where
-- Try to create a fully polymorphic function that changes it's parameter
-- Impossible but try anyway
polyForDays a = a ++ " impossible"
-- Two versions of a -> a -> a
versionOne a = a + a
versionTwo a = a ++ a
-- a -> b -> b, as many implementations as you can
aAndBOne a b = a + b
aAndBTwo a b = a ++ b
aAndBThree a b = max a b
aAndBFour a b = min a b
aAndBFive a b = a == b
-- Could go on forever
| rasheedja/HaskellFromFirstPrinciples | Chapter5/parametricity.hs | mit | 431 | 0 | 5 | 103 | 117 | 61 | 56 | 9 | 1 |
{-# LANGUAGE TypeFamilies #-}
module SoOSiM.Components.MemoryManager.Interface where
import SoOSiM
import {-# SOURCE #-} SoOSiM.Components.MemoryManager.Behaviour (memMgr)
import SoOSiM.Components.MemoryManager.Types
data MemoryManager = MemoryManager
instance ComponentInterface MemoryManager where
type State MemoryManager = MM_State
type Receive MemoryManager = MM_Cmd
type Send MemoryManager = MM_Msg
initState = const memMgrIState
componentName = const "Memory Manager"
componentBehaviour = const memMgr
createMemoryManager :: (Maybe NodeId) -> Maybe ComponentId -> Sim ComponentId
createMemoryManager n p = componentLookupN n MemoryManager >>= \x -> case x of
Nothing -> createComponentNPS n Nothing (Just iState) MemoryManager
Just cId -> return cId
where
iState = memMgrIState { _parentMM = p }
registerMem :: (Maybe ComponentId) -> Int -> Int -> Sim ()
registerMem (Just cId) base size = invoke MemoryManager cId (Register base size) >> return ()
registerMem Nothing base size = componentLookup MemoryManager >>= \x -> case x of
Nothing -> error "no instantiated memory manager"
Just cId -> invoke MemoryManager cId (Register base size) >> return ()
readMem :: Int -> Int -> Sim ()
readMem base size = componentLookup MemoryManager >>= \x -> case x of
Nothing -> error "no instantiated memory manager"
Just cId -> do (MM_ACK s) <- invoke MemoryManager cId (Read base size)
runUntilAll cId size [s]
writeMem :: Int -> Int -> Sim ()
writeMem base size = componentLookup MemoryManager >>= \x -> case x of
Nothing -> error "no instantiated memory manager"
Just cId -> do (MM_ACK s) <- invoke MemoryManager cId (Write base size)
runUntilAll cId size [s]
runUntilAll :: ComponentId -> Int -> [Int] -> Sim ()
runUntilAll cId s ss = case compare s (sum ss) of
LT -> do (MM_ACK s') <- expect MemoryManager cId
runUntilAll cId s (s':ss)
_ -> return ()
| christiaanb/SoOSiM-components | src/SoOSiM/Components/MemoryManager/Interface.hs | mit | 2,010 | 0 | 15 | 441 | 649 | 323 | 326 | 38 | 2 |
module Main (main) where
import qualified Graphics.UI.SDL as SDL
import qualified Graphics.UI.SDL.Image as Image
import Shared.Input
import Shared.Lifecycle
import Shared.Polling
import Shared.Utilities
title :: String
title = "lesson07"
size :: ScreenSize
size = (640, 480)
inWindow :: (SDL.Window -> IO ()) -> IO ()
inWindow = withSDL . withWindow title size
main :: IO ()
main = inWindow $ \window -> Image.withImgInit [Image.InitPNG] $ do
_ <- setHint "SDL_RENDER_SCALE_QUALITY" "1" >>= logWarning
renderer <- createRenderer window (-1) [SDL.SDL_RENDERER_ACCELERATED] >>= either throwSDLError return
_ <- SDL.setRenderDrawColor renderer 0xFF 0xFF 0xFF 0xFF
texture <- Image.imgLoadTexture renderer "./assets/texture.png" >>= either throwSDLError return
repeatUntilTrue $ draw renderer texture >> handleNoInput pollEvent
SDL.destroyTexture texture
SDL.destroyRenderer renderer
draw :: SDL.Renderer -> SDL.Texture -> IO ()
draw renderer texture = do
_ <- SDL.renderClear renderer
_ <- SDL.renderCopy renderer texture nullPtr nullPtr
SDL.renderPresent renderer
| oldmanmike/haskellSDL2Examples | src/lesson07.hs | gpl-2.0 | 1,110 | 0 | 14 | 185 | 351 | 178 | 173 | 27 | 1 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances #-}
{-
Instance of class Logic for EVTs
-}
module EVT.Logic where
import Common.DocUtils
import Common.Id
import Data.Monoid
import Logic.Logic
import EVT.AS
import EVT.Sign
import EVT.ParseEVT
import EVT.ATC_EVT ()
--import EVT.StaticAnalysis
import CASL.Logic_CASL
data EVT = EVT deriving (Show)
instance Language EVT where
description _ =
"Logic for the Institution EVT"
-- | Instance of Category for EVT
instance Category
EVTSign -- sign
EVTMorphism -- mor
where
dom = domain
cod = codomain
-- ide = idMor
-- composeMorphisms = comp_mor
-- | Instance of Sentences for EVT
instance Sentences EVT EVENT EVTSign EVTMorphism EVTSymbol where
-- there is nothing to leave out
simplify_sen EVT _ form = form
print_named _ = printAnnoted pretty . fromLabelledSen
--map_sen EVT = map_evt
instance Pretty EVENT where
instance Pretty MACHINE where
instance Pretty EVTMorphism where
instance Pretty EVTSign where
instance Pretty EVTSymbol where
instance Monoid EVENT where
mempty = EVENT (stringToId "") [] []
mappend (EVENT n1 g1 a1) (EVENT n2 g2 a2) = EVENT (mappend n1 n2) (mappend g1 g2) (mappend a1 a2)
instance Monoid MACHINE where
mempty = MACHINE []
mappend (MACHINE m1) (MACHINE m2) = MACHINE (mappend m1 m2)
instance Monoid EVTSign where
mempty = emptyEVTSign
mappend (EVTSign e1 g1) (EVTSign e2 g2) = EVTSign (mappend e1 e2) (mappend g1 g2)
instance Monoid Id
-- | Syntax of EVT
instance Syntax EVT MACHINE EVTSymbol () () where--EVTMorphism () () where
parse_basic_spec _ = Just $ evtBasicSpec
parse_symb_items _ = Nothing
parse_symb_map_items _ = Nothing
instance Logic EVT
-- Sublogics (missing)
()
-- basic_spec
MACHINE
EVENT
-- sentence
() -- symb_items
() --symb map items
EVTSign -- Signature
-- symb_map_items
-- CspSymbMapItems
-- signature
-- morphism
EVTMorphism
EVTSymbol -- Symbol
EVTRawSymbol
-- proof_tree (missing)
()
where
stability (EVT)= Experimental
data_logic (EVT) = Just (Logic CASL)
empty_proof_tree _ = ()
-- provers (GenCspCASL _) = cspProvers (undefined :: a)
{-- | Instance of Logic for EVT
instance Logic EVT
() -- Sublogics
EVENT -- basic_spec
EVENT -- sentence
() -- symb_items
() -- symb_map_items
Sign -- sign
EVTMorphism -- morphism
EVTSymbol -- symbol
() -- EVTRawSymbol -- raw_symbol
() -- proof_tree
where
stability EVT = Experimental
- | Static Analysis for EVT-}
instance StaticAnalysis EVT
MACHINE -- basic_spec
EVENT-- Sentence
() -- symb_items
() -- symb_map_items
EVTSign -- sign
EVTMorphism -- morphism
EVTSymbol -- symbol
EVTRawSymbol -- raw_symbol
where
--basic_analysis EVT = Just basic_analysis
empty_signature EVT = emptyEVTSign
--is_subsig EVT = isEVTSubsig
-- subsig_inclusion EVT = evtInclusion
-- signature_union EVT = uniteSig-}
| mariefarrell/Hets | EVT/Logic.hs | gpl-2.0 | 3,492 | 5 | 8 | 1,163 | 597 | 324 | 273 | 66 | 0 |
--
-- Copyright (c) 2014 Citrix Systems, Inc.
--
-- 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
--
{-# LANGUAGE PatternGuards #-}
module NetworkUtils ( listNetworkInterfaces
, listPhyInterfaces
, isVifOrTunInterface
, isBridgeInterface
, isWirelessInterface
, isSerialInterface
, isPhyInterface
, disableReversePathFilter
, enableIpForwarding
, enableBridgeNetfilter
, disableBridgeNetfilter
, logAndExecuteIptables
, memberOf
, bridgeExists
, joinBridge
, leaveBridge
, checkAndAddBridge
, checkAndAddBridgeFwd
, checkAndJoinBridge
, checkAndLeaveBridge
, removeBridge
, interfaceUp
, interfaceDown
, interfaceSubnet
, interfaceIndex
, interfaceMac
, interfaceType
, interfaceExists
, changeIfaceMac
, addIptableRulesIfMissing
, isValidMac
) where
import Data.Maybe
import Data.Char
import Data.Bits
import Data.Ord
import Data.List
import Text.Regex.Posix
import Text.Printf (printf)
import Directory
import System.Exit
import System.FilePath
import System.Posix.Files
import Control.Monad
import Control.Applicative
import Control.Monad.Error (catchError)
import Tools.Process
import Tools.Log
import Tools.Text
import Tools.Misc
import Tools.File
import Utils
import Error
data PciBusAddr = BDF Integer Integer Integer Integer
sysfsnet = "/sys/class/net"
sysfsnetContents = getDirectoryContents_nonDotted sysfsnet
-- network interface sysfs locations ordered by their pci bus address.
-- if address can't be worked out, iface gets put towards the end of the list.
sysfsnetOrderedContents =
order =<< sysfsnetContents where
order faces = map snd . sortBy (comparing fst) <$> weightedFaces
where
weightedFaces = mapM (\f -> (,) <$> weight f <*> pure f) faces
weight face = f <$> ifacePciBusAddr face where
f Nothing = 0xfffffffff
f (Just (BDF a b c d)) =
(a `shiftL` 20)
.|. (b `shiftL` 12)
.|. (c `shiftL` 4)
.|. d
-- try to work out pci bus address of network interface from its sysfs path
ifacePciBusAddr :: String -> IO (Maybe PciBusAddr)
ifacePciBusAddr face = do
p <- (sysfsnet </>) <$> readSymbolicLink (sysfsnet </> face)
scan (reverse $ splitPath p)
where
fromHex s = maybeRead ("0x" ++ s)
scan :: [String] -> IO (Maybe PciBusAddr)
scan [] = return Nothing
scan ("../" : _) = return Nothing
scan (iname : "net/" : addr : xs) = return $
let addr' = reverse $ drop 1 (reverse addr) in
case () of
_ | [a,b,x] <- split ':' addr'
, [c,d] <- split '.' x ->
let h = fromHex in
BDF <$> h a <*> h b <*> h c <*> h d
| otherwise -> Nothing
scan (x : xs) = scan xs
listNetworkInterfaces = sysfsnetOrderedContents
listPhyInterfaces = catMaybes <$> (mapM isPhy =<< sysfsnetOrderedContents)
where isPhy iface = isPhyInterface iface >>= f where f True = return (Just iface)
f False = return Nothing
isVifOrTunInterface :: FilePath -> IO (Bool)
isVifOrTunInterface iface = do
devtype <- strip <$> getFileContents (sysfsnet </> iface </> "device" </> "devtype")
return ((devtype =~ "vif" :: Bool) || (devtype =~ "vwif" :: Bool) || (iface =~ "tap" :: Bool))
isBridgeInterface :: String -> IO (Bool)
isBridgeInterface iface = doesDirectoryExist (sysfsnet </> iface </> "bridge")
memberOf :: String -> IO String
memberOf iface = do
bridgeDetails <- getFileContents (sysfsnet </> iface </> "brport" </> "bridge" </> "uevent")
return $ case bridgeDetails of
"" -> ""
other -> let grps = (other `matchG` "INTERFACE=(\\S+)$") in
case grps of
[x] -> x
other -> ""
isWirelessInterface :: String -> IO (Bool)
isWirelessInterface iface = doesDirectoryExist (sysfsnet </> iface </> "wireless")
isSerialInterface :: String -> IO (Bool)
isSerialInterface iface = do
devtype <- getFileContents (sysfsnet </> iface </> "type")
return $ case (devtype , (iface =~ "^(ppp)" :: Bool)) of
("512", _) -> True
(_, True) -> True
otherwise -> False
isPhyInterface :: String -> IO Bool
isPhyInterface iface = do
devExists <- doesDirectoryExist(sysfsnet </> iface </> "device")
isVif <- isVifOrTunInterface iface
case (devExists, isVif) of
(True, False) -> return True
otherwise -> return False
disableReversePathFilter iface = spawnShell $ printf "echo 0 > /proc/sys/net/ipv4/conf/%s/rp_filter" iface
enableIpForwarding = spawnShell "echo 1 > /proc/sys/net/ipv4/ip_forward"
enableBridgeNetfilter = do
spawnShell "echo 1 > /proc/sys/net/bridge/bridge-nf-call-iptables"
spawnShell "echo 1 > /proc/sys/net/bridge/bridge-nf-call-ip6tables"
spawnShell "echo 1 > /proc/sys/net/bridge/bridge-nf-call-arptables"
logAndExecuteIptables $ printf "-t nat -I POSTROUTING -m physdev --physdev-is-bridge -j ACCEPT"
disableBridgeNetfilter = void $ do
spawnShell "echo 0 > /proc/sys/net/bridge/bridge-nf-call-iptables"
spawnShell "echo 0 > /proc/sys/net/bridge/bridge-nf-call-ip6tables"
spawnShell "echo 0 > /proc/sys/net/bridge/bridge-nf-call-arptables"
logAndExecuteIptables cmd = void $ do
debug cmd
spawnShell $ "iptables " ++ cmd
bridgeExists :: String -> IO Bool
bridgeExists bridge = doesDirectoryExist (sysfsnet </> bridge </> "brif")
joinBridge bridge interface = unless (null bridge) $ void $ do
debug $ printf "Joining %s to %s" interface bridge
spawnShell $ printf "brctl setfd %s 0" bridge
spawnShell $ printf "brctl addif %s %s" bridge interface
spawnShell $ printf "ifconfig %s inet 0.0.0.0 promisc up" interface
leaveBridge bridge interface = unless (null bridge) $ void $ do
spawnShell $ printf "brctl delif %s %s" bridge interface
spawnShell $ printf "ip link set %s down" interface
_checkAndAddBridge :: String -> String -> IO ()
_checkAndAddBridge bridge fwd_mask = do
exists <- bridgeExists bridge
case exists of
False -> do debug $ "Adding bridge " ++ bridge
readProcessOrDie "ip" ["link", "add", bridge, "type", "bridge", "forward_delay", "0", "stp_state", "0", "group_fwd_mask", fwd_mask] []
return ()
otherwise -> do debug $ bridge ++ " already exists"
return ()
checkAndAddBridge :: String -> IO ()
checkAndAddBridge bridge = _checkAndAddBridge bridge "0"
checkAndAddBridgeFwd :: String -> IO ()
checkAndAddBridgeFwd bridge = _checkAndAddBridge bridge "0xfff8"
checkAndJoinBridge :: String -> String -> IO Bool
checkAndJoinBridge bridge interface = do
curBridge <- memberOf interface
case (null curBridge, curBridge == bridge) of
(True,_) -> do joinBridge bridge interface
return True
(_, True) -> do debug $ printf "%s is already added to %s" interface bridge
return True
(_, False) -> do error $ printf "%s cannot be added to %s when it is already added to %s"
return False
checkAndLeaveBridge :: String -> String -> IO Bool
checkAndLeaveBridge bridge interface = do
curBridge <- memberOf interface
if (curBridge == bridge)
then do leaveBridge bridge interface
return True
else do error $ printf "%s is not on %s bridge" interface bridge
return False
removeBridge :: String -> IO ()
removeBridge bridge = do
exists <- doesDirectoryExist (sysfsnet </> bridge </> "brif")
when exists $ do
ifs <- getDirectoryContents (sysfsnet </> bridge </> "brif")
mapM_ (delif bridge) ifs
readProcessWithExitCode_closeFds "ifconfig" [bridge, "down"] []
readProcessWithExitCode_closeFds "brctl" ["delbr", bridge] []
return ()
delif bridge iface = readProcessWithExitCode_closeFds "brctl" ["delif", bridge, iface] []
interfaceUp iface = readProcessWithExitCode_closeFds "ifconfig" [iface, "inet", "0.0.0.0", "up"] []
interfaceDown iface = readProcessWithExitCode_closeFds "ifconfig" [iface, "down"] []
interfaceSubnet iface = do out <- spawnShell $ printf "ip addr show %s | grep inet" iface
case (out `matchG` "([0-9]+\\.[0-9]+\\.[0-9]+)\\.[0-9]+") of
[prefix] -> return $ prefix ++ ".0"
_ -> return ""
interfaceIndex :: String -> IO String
interfaceIndex interface = strip <$> getFileContents (sysfsnet </> interface </> "ifindex")
interfaceMac :: String -> IO String
interfaceMac interface = strip <$> getFileContents (sysfsnet </> interface </> "address")
interfaceType :: String -> IO String
interfaceType interface = strip <$> getFileContents (sysfsnet </> interface </> "type")
interfaceExists :: String -> IO Bool
interfaceExists interface = doesDirectoryExist (sysfsnet </> interface)
changeIfaceMac iface mac = do
interfaceDown iface
readProcessWithExitCode_closeFds "ifconfig" [iface, "hw", "ether", mac] []
interfaceUp iface
addIptableRulesIfMissing :: [String] -> String -> IO ()
addIptableRulesIfMissing iptablesOut iptablesArgs = do
unless (any (match iptablesArgs) iptablesOut) $ do
(exitCode, _,err) <- do
debug $ "iptables " ++ iptablesArgs
readProcessWithExitCode_closeFds "iptables" (words iptablesArgs) []
case exitCode of
ExitSuccess -> return ()
_ -> error $ printf "cannot add rule %s : %s" iptablesArgs err
where match template rule = rule =~ template :: Bool
isValidMac mac = ((map toUpper mac) =~ "^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$" :: Bool)
| OpenXT/network | nws/NetworkUtils.hs | gpl-2.0 | 11,151 | 0 | 20 | 3,201 | 2,635 | 1,338 | 1,297 | 213 | 4 |
module CornerPoints.FaceExtractAndConvert(getFrontFaceAsBackFace, getFrontLeftLineAsBackFace, getLeftFaceAsBackFace,
getFrontRightLineAsBackFace, getRightFaceAsBackFace, getBackRightLineAsBackFace) where
import CornerPoints.FaceConversions
import CornerPoints.FaceExtraction
{- | Convenience functions combining FaceConversions and FaceExtraction. These combinations are used when doing unions and differences of shapes.
Tests are in Tests.FaceExtractAndConvertTest-}
getFrontFaceAsBackFace cornerPoint = toBackFace $ extractFrontFace cornerPoint
getFrontLeftLineAsBackFace cornerPoint = toBackFace $ extractFrontLeftLine cornerPoint
getLeftFaceAsBackFace cornerPoint = toBackFace $ extractLeftFace cornerPoint
getFrontRightLineAsBackFace cornerPoint = toBackFace $ extractFrontRightLine cornerPoint
getRightFaceAsBackFace cornerPoint = toBackFace $ extractRightFace cornerPoint
getBackRightLineAsBackFace cornerPoint = toBackFace $ extractBackRightLine cornerPoint
| heathweiss/Tricad | src/CornerPoints/FaceExtractAndConvert.hs | gpl-2.0 | 1,016 | 0 | 6 | 127 | 127 | 66 | 61 | 10 | 1 |
-- BEE_Reinas.hs
-- El problema de las n reinas mediante BEE.
-- José A. Alonso Jiménez https://jaalonso.github.com
-- =====================================================================
module Tema_23.BEE_Reinas where
-- Hay que elegir una implementación
import Tema_23.BusquedaEnEspaciosDeEstados
-- import I1M.BusquedaEnEspaciosDeEstados
-- El problema de las n reinas consiste en colocar n reinas en un
-- tablero cuadrado de dimensiones n por n de forma que no se encuentren
-- más de una en la misma línea: horizontal, vertical o diagonal.
-- Las posiciones de las reinas en el tablero se representan por su
-- columna y su fila.
type Columna = Int
type Fila = Int
-- Una solución del problema de las n reinas es una lista de
-- posiciones.
type SolNR = [(Columna,Fila)]
-- (valida sp p) se verifica si la posición p es válida respecto de la
-- solución parcial sp; es decir, la reina en la posición p no amenaza a
-- ninguna de las reinas de la sp (se supone que están en distintas
-- columnas). Por ejemplo,
-- valida [(1,1)] (2,2) == False
-- valida [(1,1)] (2,3) == True
valida :: SolNR -> (Columna,Fila) -> Bool
valida solp (c,r) = and [test s | s <- solp]
where test (c',r') = c'+r'/=c+r && c'-r'/=c-r && r'/=r
-- Los nodos del problema de las n reinas son ternas formadas por la
-- columna de la última reina colocada, el número de columnas del
-- tablero y la solución parcial de las reinas colocadas anteriormente.
type NodoNR = (Columna,Columna,SolNR)
-- (sucesoresNR e) es la lista de los sucesores del estado e en el
-- problema de las n reinas. Por ejemplo,
-- λ> sucesoresNR (1,4,[])
-- [(2,4,[(1,1)]),(2,4,[(1,2)]),(2,4,[(1,3)]),(2,4,[(1,4)])]
sucesoresNR :: NodoNR -> [NodoNR]
sucesoresNR (c,n,solp) =
[(c+1,n,solp++[(c,r)]) | r <- [1..n] , valida solp (c,r)]
-- (esFinalNR e) se verifica si e es un estado final del problema de las
-- n reinas.
esFinalNR :: NodoNR -> Bool
esFinalNR (c,n,_) = c > n
-- (buscaEE_NR n) es la primera solución del problema de las n reinas,
-- por búsqueda en espacio de estados. Por ejemplo,
-- λ> buscaEE_NR 8
-- [(1,1),(2,5),(3,8),(4,6),(5,3),(6,7),(7,2),(8,4)]
buscaEE_NR :: Columna -> SolNR
buscaEE_NR n = s
where ((_,_,s):_) = buscaEE sucesoresNR esFinalNR (1,n,[])
-- (nSolucionesNR n) es el número de soluciones del problema de las n
-- reinas, por búsqueda en espacio de estados. Por ejemplo,
-- nSolucionesNR 8 == 92
nSolucionesNR :: Columna -> Int
nSolucionesNR n =
length (buscaEE sucesoresNR
esFinalNR
(1,n,[]))
| jaalonso/I1M-Cod-Temas | src/Tema_23/BEE_Reinas.hs | gpl-2.0 | 2,584 | 0 | 15 | 490 | 408 | 247 | 161 | 22 | 1 |
{-# LANGUAGE LambdaCase #-}
module Utils.Yukari.Crawler (crawlFromURL, crawlFromFile
, getSinglePage, torrentFilter) where
import Control.Lens hiding ((<.>))
import Control.Applicative
import Control.Arrow ((&&&))
import Control.Monad
import qualified Data.ByteString as BS
import Data.List
import Network.Curl
import Network.Curl.Download
import Network.HTTP hiding (password)
import System.Directory
import System.Exit
import System.FilePath
import Utils.Yukari.Formatter
import Utils.Yukari.Parser (parsePage)
import Utils.Yukari.Settings
import Utils.Yukari.Types
type URL = String
-- | Filter out unwanated torrents as per specified function, removing
-- groups without any torrents remaining post-filtering.
torrentFilter :: (ABTorrent -> Bool) -> [ABTorrentGroup] -> [ABTorrentGroup]
torrentFilter p = filter (not . null . view torrents)
. map (torrents %~ filter p)
-- | Use the curl session to fetch a possibly login restricted page.
getInternalPage :: YukariSettings -> Curl -> String -> IO (Maybe String)
getInternalPage ys curl url = do
r <- do_curl_ curl url method_GET :: IO CurlResponse
if respCurlCode r /= CurlOK
then retryFetch r $ _connectionRetries ys
else return . Just $ respBody r
where
retryFetch :: CurlResponse -> Integer -> IO (Maybe String)
retryFetch r ret
| ret <= 0 = do
verbPrint Low ys [ "Failed to fetch:", url, ";"
, show $ respCurlCode r, "--"
, respStatusLine r
]
return Nothing
| otherwise = do
verbPrint High ys [ "Failed to fetch", url
, show $ ret - 1
, attemptFormat $ ret - 1
, "remaining."
]
getInternalPage (ys { _connectionRetries = ret - 1 }) curl url
where
attemptFormat 1 = "attempt"
attemptFormat _ = "attempts"
-- | We check if we're banned first before we even try to log in.
-- While it is an extra GET, we don't POST account information needlessly
-- and this is only done once per log in anyway.
banned :: SiteSettings -> IO Bool
banned s = do
(_, body) <- curlGetString (s ^. loginSite) []
return $ "You are banned from logging in for another " `isInfixOf` body
-- | As someone thought that _obviously_ the best way to inform
-- the user about a failed login would be a JavaScript pop-up, we have to hack
-- around the braindead defaults.
--
-- We try to fetch the index page and if we can see the forums.php in the body,
-- we probably made it.
loggedIn :: YukariSettings -> Curl -> IO Bool
loggedIn s c = do
let settings = s ^. siteSettings
body <- getInternalPage s c (settings ^. baseSite)
case body of
Nothing -> error "Failed to successfully grab the login page."
Just body' -> do
let b = "forums.php" `isInfixOf` body'
unless b $ verbPrint Debug s [ "Failed to log in. username:"
, settings ^. username
, "password:"
, settings ^. password
++ "\nBody:\n" ++ body'
]
return $ "forums.php" `isInfixOf` body'
-- | Log in to the site.
logonCurl :: YukariSettings -> IO Curl
logonCurl ys = do
let s = ys ^. siteSettings
b <- banned s
when b $ do
putStrLn "Seems you have been banned from logging in. Check the site."
exitFailure
let fields = CurlPostFields [ "username=" ++ s ^. username
, "password=" ++ s ^. password ] : method_POST
curl <- initialize
setopts curl [ CurlCookieJar "cookies", CurlUserAgent defaultUserAgent
, CurlTimeout 15 ]
r <- do_curl_ curl (s ^. loginSite) fields :: IO CurlResponse
l <- loggedIn ys curl
if respCurlCode r /= CurlOK || not l
then error $ concat ["Failed to log in as ", s ^. username, ": "
, show $ respCurlCode r, " -- ", respStatusLine r]
else return curl
-- | Crawl the page according to user settings and using a specified curl
-- session. We can obtain the appropiate session using 'logonCurl'.
crawl :: YukariSettings -> Curl -> String -> IO ()
crawl _ _ "" = return ()
crawl ys curl url
| ys ^. maxPages <= 0 = return ()
| otherwise = do
let settings = ys ^. siteSettings
verbPrint Low ys ["Crawling", url]
body <- getInternalPage ys curl url
case body of
Nothing -> error $ "Failed to crawl " ++ url
Just body' -> do
verbPrint Debug ys ['\n' : body']
pa@(nextPage, groups) <- parsePage ys body'
when (ys ^. logVerbosity >= High) (prettyPage pa)
verbPrint Low ys ["Have", show . sum $ map (length . _torrents) groups
, "torrents pre-filter."]
let filtered' = torrentFilter (_filterFunc settings) groups
let tPaths = concatMap (buildTorrentPaths settings) filtered'
verbPrint Low ys ["Have", show $ length tPaths, "torrents post-filter."]
mapM_ (\(fp, url') -> download fp url' ys) tPaths
crawl (ys { _maxPages = _maxPages ys - 1 }) curl nextPage
-- | We take settings for the site and a torrent group listing and we try to
-- assign a file path to each torrent in the group to which the download
-- will be made.
buildTorrentPaths :: SiteSettings -> ABTorrentGroup -> [(Maybe FilePath, URL)]
buildTorrentPaths sett g =
map (makePath &&& _torrentDownloadURI) $ _torrents g
where
makePath :: ABTorrent -> Maybe FilePath
makePath tor = case _torrentCategory g of
Nothing -> Nothing
Just cat -> foldl (liftA2 (</>)) (_topWatch sett)
[ _watchFunc sett cat
, Just $ unwords [ _torrentName g, "-"
, show cat
, "~"
, _torrentInfoSuffix tor <.> "torrent"
]
]
-- | Starts the crawl from a saved page.
crawlFromFile :: YukariSettings -> FilePath -> IO ()
crawlFromFile ys f = do
curl <- logonCurl ys
body' <- readFile f
(n, _) <- parsePage ys body'
crawl ys curl n
-- | Starts the crawl from the URL specified in the settings.
crawlFromURL :: YukariSettings -> IO ()
crawlFromURL ys = do
let settings = ys ^. siteSettings
curl <- logonCurl ys
crawl ys curl $ _searchSite settings
-- | Logs the user in with 'logonCurl' and fetches a single page using
-- 'getInternalPage'. Useful when we just want to grab something quickly.
getSinglePage :: YukariSettings -> String -> IO (Maybe String)
getSinglePage ys url = logonCurl ys >>= flip (getInternalPage ys) url
-- | Downloads a file to the specified location. If the file path is Nothing,
-- the download isn't performed.
download :: Maybe FilePath -- ^ The file to save to.
-> URL -- ^ The URL to download from.
-> YukariSettings -> IO ()
download path url ys =
let clobber = ys ^. siteSettings . clobberFiles
dry = DryRun `elem` ys ^. programSettings
in
case path of
Nothing -> verbPrint Low ys ["Skipping empty path."]
Just p -> do
b <- doesFileExist p
when b $ verbPrint Low ys ["Skipping already downloaded", p]
if dry
then verbPrint Debug ys [ "Dry run enabled, would download", url
, "to", p, "otherwise."]
else when (clobber || not b) $ openURI url >>= \case
Left e -> putStrLn $ unwords [ "Error ", e
, " occured when downloading from "
, url]
Right bs -> verbPrint Low ys ["Downloading ", p]
>> createDirectoryIfMissing True (takeDirectory p)
>> BS.writeFile p bs
| Fuuzetsu/yukari | src/Utils/Yukari/Crawler.hs | gpl-3.0 | 8,033 | 0 | 21 | 2,561 | 1,965 | 998 | 967 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DeploymentManager.Deployments.Insert
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a deployment and all of the resources described by the
-- deployment manifest.
--
-- /See:/ <https://cloud.google.com/deployment-manager/ Google Cloud Deployment Manager API Reference> for @deploymentmanager.deployments.insert@.
module Network.Google.Resource.DeploymentManager.Deployments.Insert
(
-- * REST Resource
DeploymentsInsertResource
-- * Creating a Request
, deploymentsInsert
, DeploymentsInsert
-- * Request Lenses
, diProject
, diPayload
, diPreview
) where
import Network.Google.DeploymentManager.Types
import Network.Google.Prelude
-- | A resource alias for @deploymentmanager.deployments.insert@ method which the
-- 'DeploymentsInsert' request conforms to.
type DeploymentsInsertResource =
"deploymentmanager" :>
"v2" :>
"projects" :>
Capture "project" Text :>
"global" :>
"deployments" :>
QueryParam "preview" Bool :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Deployment :> Post '[JSON] Operation
-- | Creates a deployment and all of the resources described by the
-- deployment manifest.
--
-- /See:/ 'deploymentsInsert' smart constructor.
data DeploymentsInsert = DeploymentsInsert'
{ _diProject :: !Text
, _diPayload :: !Deployment
, _diPreview :: !(Maybe Bool)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeploymentsInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'diProject'
--
-- * 'diPayload'
--
-- * 'diPreview'
deploymentsInsert
:: Text -- ^ 'diProject'
-> Deployment -- ^ 'diPayload'
-> DeploymentsInsert
deploymentsInsert pDiProject_ pDiPayload_ =
DeploymentsInsert'
{ _diProject = pDiProject_
, _diPayload = pDiPayload_
, _diPreview = Nothing
}
-- | The project ID for this request.
diProject :: Lens' DeploymentsInsert Text
diProject
= lens _diProject (\ s a -> s{_diProject = a})
-- | Multipart request metadata.
diPayload :: Lens' DeploymentsInsert Deployment
diPayload
= lens _diPayload (\ s a -> s{_diPayload = a})
-- | If set to true, creates a deployment and creates \"shell\" resources but
-- does not actually instantiate these resources. This allows you to
-- preview what your deployment looks like. After previewing a deployment,
-- you can deploy your resources by making a request with the update()
-- method or you can use the cancelPreview() method to cancel the preview
-- altogether. Note that the deployment will still exist after you cancel
-- the preview and you must separately delete this deployment if you want
-- to remove it.
diPreview :: Lens' DeploymentsInsert (Maybe Bool)
diPreview
= lens _diPreview (\ s a -> s{_diPreview = a})
instance GoogleRequest DeploymentsInsert where
type Rs DeploymentsInsert = Operation
type Scopes DeploymentsInsert =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/ndev.cloudman"]
requestClient DeploymentsInsert'{..}
= go _diProject _diPreview (Just AltJSON) _diPayload
deploymentManagerService
where go
= buildClient
(Proxy :: Proxy DeploymentsInsertResource)
mempty
| rueshyna/gogol | gogol-deploymentmanager/gen/Network/Google/Resource/DeploymentManager/Deployments/Insert.hs | mpl-2.0 | 4,202 | 0 | 16 | 945 | 482 | 290 | 192 | 73 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Run.Namespaces.Configurations.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- List configurations.
--
-- /See:/ <https://cloud.google.com/run/ Cloud Run Admin API Reference> for @run.namespaces.configurations.list@.
module Network.Google.Resource.Run.Namespaces.Configurations.List
(
-- * REST Resource
NamespacesConfigurationsListResource
-- * Creating a Request
, namespacesConfigurationsList
, NamespacesConfigurationsList
-- * Request Lenses
, nclParent
, nclXgafv
, nclFieldSelector
, nclUploadProtocol
, nclAccessToken
, nclResourceVersion
, nclLabelSelector
, nclUploadType
, nclLimit
, nclIncludeUninitialized
, nclContinue
, nclWatch
, nclCallback
) where
import Network.Google.Prelude
import Network.Google.Run.Types
-- | A resource alias for @run.namespaces.configurations.list@ method which the
-- 'NamespacesConfigurationsList' request conforms to.
type NamespacesConfigurationsListResource =
"apis" :>
"serving.knative.dev" :>
"v1" :>
Capture "parent" Text :>
"configurations" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "fieldSelector" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "resourceVersion" Text :>
QueryParam "labelSelector" Text :>
QueryParam "uploadType" Text :>
QueryParam "limit" (Textual Int32) :>
QueryParam "includeUninitialized" Bool :>
QueryParam "continue" Text :>
QueryParam "watch" Bool :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListConfigurationsResponse
-- | List configurations.
--
-- /See:/ 'namespacesConfigurationsList' smart constructor.
data NamespacesConfigurationsList =
NamespacesConfigurationsList'
{ _nclParent :: !Text
, _nclXgafv :: !(Maybe Xgafv)
, _nclFieldSelector :: !(Maybe Text)
, _nclUploadProtocol :: !(Maybe Text)
, _nclAccessToken :: !(Maybe Text)
, _nclResourceVersion :: !(Maybe Text)
, _nclLabelSelector :: !(Maybe Text)
, _nclUploadType :: !(Maybe Text)
, _nclLimit :: !(Maybe (Textual Int32))
, _nclIncludeUninitialized :: !(Maybe Bool)
, _nclContinue :: !(Maybe Text)
, _nclWatch :: !(Maybe Bool)
, _nclCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'NamespacesConfigurationsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'nclParent'
--
-- * 'nclXgafv'
--
-- * 'nclFieldSelector'
--
-- * 'nclUploadProtocol'
--
-- * 'nclAccessToken'
--
-- * 'nclResourceVersion'
--
-- * 'nclLabelSelector'
--
-- * 'nclUploadType'
--
-- * 'nclLimit'
--
-- * 'nclIncludeUninitialized'
--
-- * 'nclContinue'
--
-- * 'nclWatch'
--
-- * 'nclCallback'
namespacesConfigurationsList
:: Text -- ^ 'nclParent'
-> NamespacesConfigurationsList
namespacesConfigurationsList pNclParent_ =
NamespacesConfigurationsList'
{ _nclParent = pNclParent_
, _nclXgafv = Nothing
, _nclFieldSelector = Nothing
, _nclUploadProtocol = Nothing
, _nclAccessToken = Nothing
, _nclResourceVersion = Nothing
, _nclLabelSelector = Nothing
, _nclUploadType = Nothing
, _nclLimit = Nothing
, _nclIncludeUninitialized = Nothing
, _nclContinue = Nothing
, _nclWatch = Nothing
, _nclCallback = Nothing
}
-- | The namespace from which the configurations should be listed. For Cloud
-- Run (fully managed), replace {namespace_id} with the project ID or
-- number.
nclParent :: Lens' NamespacesConfigurationsList Text
nclParent
= lens _nclParent (\ s a -> s{_nclParent = a})
-- | V1 error format.
nclXgafv :: Lens' NamespacesConfigurationsList (Maybe Xgafv)
nclXgafv = lens _nclXgafv (\ s a -> s{_nclXgafv = a})
-- | Allows to filter resources based on a specific value for a field name.
-- Send this in a query string format. i.e. \'metadata.name%3Dlorem\'. Not
-- currently used by Cloud Run.
nclFieldSelector :: Lens' NamespacesConfigurationsList (Maybe Text)
nclFieldSelector
= lens _nclFieldSelector
(\ s a -> s{_nclFieldSelector = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
nclUploadProtocol :: Lens' NamespacesConfigurationsList (Maybe Text)
nclUploadProtocol
= lens _nclUploadProtocol
(\ s a -> s{_nclUploadProtocol = a})
-- | OAuth access token.
nclAccessToken :: Lens' NamespacesConfigurationsList (Maybe Text)
nclAccessToken
= lens _nclAccessToken
(\ s a -> s{_nclAccessToken = a})
-- | The baseline resource version from which the list or watch operation
-- should start. Not currently used by Cloud Run.
nclResourceVersion :: Lens' NamespacesConfigurationsList (Maybe Text)
nclResourceVersion
= lens _nclResourceVersion
(\ s a -> s{_nclResourceVersion = a})
-- | Allows to filter resources based on a label. Supported operations are =,
-- !=, exists, in, and notIn.
nclLabelSelector :: Lens' NamespacesConfigurationsList (Maybe Text)
nclLabelSelector
= lens _nclLabelSelector
(\ s a -> s{_nclLabelSelector = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
nclUploadType :: Lens' NamespacesConfigurationsList (Maybe Text)
nclUploadType
= lens _nclUploadType
(\ s a -> s{_nclUploadType = a})
-- | Optional. The maximum number of records that should be returned.
nclLimit :: Lens' NamespacesConfigurationsList (Maybe Int32)
nclLimit
= lens _nclLimit (\ s a -> s{_nclLimit = a}) .
mapping _Coerce
-- | Not currently used by Cloud Run.
nclIncludeUninitialized :: Lens' NamespacesConfigurationsList (Maybe Bool)
nclIncludeUninitialized
= lens _nclIncludeUninitialized
(\ s a -> s{_nclIncludeUninitialized = a})
-- | Optional. Encoded string to continue paging.
nclContinue :: Lens' NamespacesConfigurationsList (Maybe Text)
nclContinue
= lens _nclContinue (\ s a -> s{_nclContinue = a})
-- | Flag that indicates that the client expects to watch this resource as
-- well. Not currently used by Cloud Run.
nclWatch :: Lens' NamespacesConfigurationsList (Maybe Bool)
nclWatch = lens _nclWatch (\ s a -> s{_nclWatch = a})
-- | JSONP
nclCallback :: Lens' NamespacesConfigurationsList (Maybe Text)
nclCallback
= lens _nclCallback (\ s a -> s{_nclCallback = a})
instance GoogleRequest NamespacesConfigurationsList
where
type Rs NamespacesConfigurationsList =
ListConfigurationsResponse
type Scopes NamespacesConfigurationsList =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient NamespacesConfigurationsList'{..}
= go _nclParent _nclXgafv _nclFieldSelector
_nclUploadProtocol
_nclAccessToken
_nclResourceVersion
_nclLabelSelector
_nclUploadType
_nclLimit
_nclIncludeUninitialized
_nclContinue
_nclWatch
_nclCallback
(Just AltJSON)
runService
where go
= buildClient
(Proxy :: Proxy NamespacesConfigurationsListResource)
mempty
| brendanhay/gogol | gogol-run/gen/Network/Google/Resource/Run/Namespaces/Configurations/List.hs | mpl-2.0 | 8,273 | 0 | 25 | 2,025 | 1,293 | 743 | 550 | 180 | 1 |
#! /usr/bin/env runhaskell
import Debug.Trace
import Control.DeepSeq
loadProblem :: IO [[Int]]
loadProblem = do
fileStr <- readFile "euler-011.txt"
let fileLined = lines fileStr
fileWords = fmap words fileLined
fileInt = fmap (fmap read) fileWords
return fileInt
getItem :: Int -> Int -> [[a]] -> a
getItem row col xss = x
where
xs = xss !! row
x = xs !! col
getHoriz :: Int -> Int -> [[a]] -> [a]
getHoriz row col xss = [a, b, c, d]
where
[a, b, c, d] = [getItem row (col + i) xss | i <- [0..3]]
getVert :: Int -> Int -> [[a]] -> [a]
getVert row col xss = [a, b, c, d]
where
[a, b, c, d] = [getItem (row + i) col xss | i <- [0..3]]
getSlash :: Int -> Int -> [[a]] -> [a]
getSlash row col xss = [a, b, c, d]
where
[a, b, c, d] = [getItem (row + 3 - i) (col + i) xss | i <- [0..3]]
getBackslash :: Int -> Int -> [[a]] -> [a]
getBackslash row col xss = [a, b, c, d]
where
[a, b, c, d] = [getItem (row + i) (col + 3 - i) xss | i <- [0..3]]
getFours :: Show a => [[a]] -> [[a]]
getFours xss = trace (show . map length $ fours) foursConcat
where
horizes = [getHoriz row col xss | row <- [0..19], col <- [0..16]]
verts = [getVert row col xss | row <- [0..16], col <- [0..19]]
slashes = [getSlash row col xss | row <- [0..16], col <- [0..16]]
backslashes = [getBackslash row col xss | row <- [0..16], col <- [0..16]]
fours = [horizes, verts, slashes, backslashes]
foursConcat = concat [horizes, verts, slashes, backslashes]
main :: IO ()
main = do
nums <- loadProblem
print $ maximum . map product . getFours $ nums
| yuvallanger/project-euler | euler-011.hs | agpl-3.0 | 1,651 | 0 | 12 | 453 | 864 | 474 | 390 | 37 | 1 |
module Utils.STM where
import Control.Concurrent.STM
import Control.Exception
import Gonimo.Server.Error (ServerError (TransactionTimeout),
makeServantErr)
import Utils.Constants
gTimeoutSTM :: Exception e => Int -> STM (Maybe a) -> e -> IO a
-- | retries to execute an 'STM' action for for some specified 'Microseconds'
gTimeoutSTM μs action ex = do
isDelayOver <- registerDelay μs
atomically $ do isOver <- readTVar isDelayOver
if isOver
then throwSTM ex
else do result <- action
maybe retry {-or-} return result
timeoutSTM :: Microseconds -> STM (Maybe a) -> IO a
timeoutSTM μs action = gTimeoutSTM μs action (makeServantErr TransactionTimeout)
| gonimo/gonimo-back | src/Utils/STM.hs | agpl-3.0 | 832 | 0 | 13 | 273 | 196 | 99 | 97 | 16 | 2 |
-- http://adventofcode.com/2015/day/2
import Data.List.Split
import Data.List
main :: IO()
main = do
stdin <- getContents
let squareFeet = inputToSquareFeet stdin
putStrLn $ "The elves require " ++ show squareFeet ++ " feet of ribbon"
-- use Int insead of Word for simplicity/performance's sake
-- I used a guard instead, but I feel like that too is wrong
-- seems like there are interesting cases for negative surface area
computeRibbonFeet :: Int -> Int -> Int -> Int
computeRibbonFeet smallDimension medDimension bigDimension
| smallDimension <= 0 = 0
| medDimension <= 0 = 0
| bigDimension <= 0 = 0
| otherwise =
let wrap = smallDimension * 2 + medDimension * 2
bow = smallDimension * medDimension * bigDimension
in wrap + bow
dimensionsToSurfaceArea :: [Int] -> Int
-- this feels really dumb, yay knowledge gaps
dimensionsToSurfaceArea dims =
let middle = head . tail
srtd = sort dims
in computeRibbonFeet (head srtd) (middle srtd) (last srtd)
-- could blow up if not a valid Int :(
strToInt :: String -> Int
strToInt val = read val :: Int
textDimensionsToDimensions :: String -> [Int]
textDimensionsToDimensions text = map strToInt (splitOn "x" text)
textDimensionsToSurfaceArea :: String -> Int
textDimensionsToSurfaceArea = dimensionsToSurfaceArea . textDimensionsToDimensions
textDimListToSurfaceAreaList :: [String] -> [Int]
textDimListToSurfaceAreaList = map textDimensionsToSurfaceArea
inputToSquareFeet :: String -> Int
inputToSquareFeet input =
let surfaceAreaList = textDimListToSurfaceAreaList (lines input)
in foldl (+) 0 surfaceAreaList
| bennett000/advent-of-code | src/2015/2/b/hs/solution.hs | lgpl-3.0 | 1,628 | 0 | 12 | 303 | 395 | 201 | 194 | 33 | 1 |
module DistinctMidpoints.A285492Spec (main, spec) where
import Test.Hspec
import DistinctMidpoints.A285492 (a285492)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A285492" $
it "correctly computes the first 20 elements" $
take 20 (map a285492 [1..]) `shouldBe` expectedValue where
expectedValue = [1,2,3,5,4,8,11,6,15,12,9,7,20,25,16,30,36,10,18,47]
| peterokagey/haskellOEIS | test/DistinctMidpoints/A285492Spec.hs | apache-2.0 | 380 | 0 | 10 | 59 | 160 | 95 | 65 | 10 | 1 |
module Database.Neo4j.Util.BinaryValue(
BinaryValue,
toBinaryValue,
fromBinaryValue
) where
import Control.Applicative (liftA)
import Data.Binary (Binary, get, put)
import Database.Neo4j.Internal.Packstream.Atom (Atom)
import Database.Neo4j.Internal.ValueCodec
import Database.Neo4j.Util.ShowBytes (showBytes)
newtype BinaryValue a = MkBinaryValue { binaryValue :: Atom }
toBinaryValue :: ValueCodec a => a -> BinaryValue a
toBinaryValue = MkBinaryValue . unEncode . encodeValue
fromBinaryValue :: ValueCodec a => BinaryValue a -> Maybe a
fromBinaryValue = decodeValue . Encode . binaryValue
instance ValueCodec a => Show (BinaryValue a) where
show = showBytes
instance ValueCodec a => Binary (BinaryValue a) where
put = put . binaryValue
get = liftA MkBinaryValue get
| boggle/neo4j-haskell-driver | src/Database/Neo4j/Util/BinaryValue.hs | apache-2.0 | 895 | 0 | 7 | 221 | 224 | 127 | 97 | 19 | 1 |
module Database.CDB.Read (
CDB(),
cdbInit,
cdbGet,
cdbGetAll,
cdbHasKey,
cdbCount
) where
import Control.Monad
import Data.Bits
import qualified Data.ByteString as ByteString
import Data.ByteString (ByteString)
import Data.Word
import Database.CDB.Packable
import Database.CDB.Util
import System.IO.Posix.MMap
-- |Internal representation of a CDB file on disk.
data CDB = CDB { cdbMem :: ByteString }
-- |Loads a CDB from a file.
cdbInit :: FilePath -> IO CDB
cdbInit f = liftM CDB $ unsafeMMapFile f
-- |Finds the first entry associated with a key in a CDB.
cdbGet :: (Packable k, Unpackable v) => CDB -> k -> Maybe v
cdbGet cdb key = case cdbFind cdb (pack key) of
[] -> Nothing
(x:_) -> return $ unpack $ readData cdb x
-- |Finds all entries associated with a key in a CDB.
cdbGetAll :: (Packable k, Unpackable v) => CDB -> k -> [v]
cdbGetAll cdb key = map (unpack . readData cdb) (cdbFind cdb (pack key))
-- |Returns True if the CDB has a value associated with the given key.
cdbHasKey :: (Packable k) => CDB -> k -> Bool
cdbHasKey cdb key = case cdbFind cdb (pack key) of
[] -> False
_ -> True
-- |Returns the number of values a CDB has for a given key.
cdbCount :: (Packable k) => CDB -> k -> Int
cdbCount cdb key = length $ cdbFind cdb (pack key)
substr :: ByteString -> Int -> Int -> ByteString
substr bs i n = ByteString.take n (snd $ ByteString.splitAt i bs)
cdbRead32 :: CDB -> Word32 -> Word32
cdbRead32 cdb i =
bytesToWord $ ByteString.unpack $ substr (cdbMem cdb) (fromIntegral i) 4
bytesToWord :: [Word8] -> Word32
bytesToWord = foldr (\x y -> (y `shiftL` 8) .|. fromIntegral x) 0
tableLength :: CDB -> Word8 -> Word32
tableLength cdb n = cdb `cdbRead32` ((fromIntegral n * 8) + 4)
tableOffset :: CDB -> Word8 -> Word32
tableOffset cdb n = cdb `cdbRead32` (fromIntegral n * 8)
-- finds the indices of hash table entries for a given key
cdbFind :: CDB -> ByteString -> [Word32]
cdbFind cdb key =
let hash = cdbHash key
tableNum = fromIntegral $ hash `mod` 256
tl = tableLength cdb tableNum
in
if tl == 0
then []
else
let slotNum = hash `div` 256 `mod` tl
linearSearch slotNum = case probe cdb tableNum slotNum of
Just (recordOffset, hash') ->
let nextSlot = (slotNum + 1) `mod` tl in
if hash == hash' && key == readKey cdb recordOffset
then recordOffset : linearSearch nextSlot
else linearSearch nextSlot
Nothing -> []
in
linearSearch slotNum
-- returns a tuple (offset, hash) if the slot contains anything
probe :: CDB -> Word8 -> Word32 -> Maybe (Word32, Word32)
probe cdb tableNum slotNum =
let offset = tableOffset cdb tableNum + (slotNum * 8)
recordOffset = cdb `cdbRead32` (offset + 4)
in
if recordOffset == 0 then Nothing
else return (recordOffset, cdb `cdbRead32` offset)
readKey :: CDB -> Word32 -> ByteString
readKey cdb offset =
let len = cdb `cdbRead32` offset in
substr (cdbMem cdb) (fromIntegral $ offset + 8) (fromIntegral len)
readData :: CDB -> Word32 -> ByteString
readData cdb offset =
let keyLen = cdb `cdbRead32` offset
dataLen = cdb `cdbRead32` (offset + 4)
in
substr (cdbMem cdb) (fromIntegral $ offset + 8 + keyLen)
(fromIntegral dataLen)
| adamsmasher/hs-cdb | Database/CDB/Read.hs | bsd-2-clause | 3,388 | 0 | 21 | 857 | 1,116 | 597 | 519 | 75 | 4 |
module Llvm.Pass.PassManager where
import Llvm.Hir.Data
import Llvm.Pass.Mem2Reg
import Llvm.Pass.Liveness
import qualified Data.Set as Ds
import Llvm.Pass.Optimizer
import Compiler.Hoopl
data Step = Mem2Reg | Dce
| PrepareRw
deriving (Show,Eq)
toPass :: (CheckpointMonad m, FuelMonad m) => Step -> Optimization m (Ds.Set (Dtype, GlobalId)) a
toPass Mem2Reg = mem2reg
toPass Dce = dce
applyPasses1 :: (CheckpointMonad m, FuelMonad m) => [Optimization m (Ds.Set (Dtype, GlobalId)) a] -> Module a -> m (Module a)
applyPasses1 steps m = foldl (\p e -> p >>= optModule e) (return m) steps
applySteps :: (CheckpointMonad m, FuelMonad m) => [Step] -> Module a -> m (Module a)
applySteps steps m = let passes = map toPass steps
in applyPasses1 passes m
| sanjoy/hLLVM | src/Llvm/Pass/PassManager.hs | bsd-3-clause | 794 | 0 | 11 | 163 | 307 | 165 | 142 | 18 | 1 |
import TestName
| YoshikuniJujo/papillon | test/testName.hs | bsd-3-clause | 16 | 0 | 3 | 2 | 4 | 2 | 2 | 1 | 0 |
import Text.Regex.PDeriv.Debug.Refine10
import System.Environment
import qualified Data.ByteString.Char8 as S
g = [(1::Int, Pair 0 (Any 90) (Star 0 (Any 90)))]
main :: IO ()
main = do
(filename:args) <- getArgs
file <- S.readFile filename
print $ test2 g ".*<h1 class=\"header-gray\">[\n\r]*([a-zA-Z;&, \\\n\t\r]*)</h1>.*" file
-- print $ test2 g ".*aa(b*)aa.*" (S.pack "cabac")
| luzhuomi/pddebug | test/File.hs | bsd-3-clause | 391 | 0 | 11 | 62 | 123 | 67 | 56 | 9 | 1 |
module HGraph.Edge where
import Control.Monad.State
import qualified Data.Map as M
import qualified Data.Maybe as MB
import qualified Data.Text as T
import HGraph.Graph
import HGraph.Label
import HGraph.Node
import HGraph.Types
edgeKeyBlacklist :: [T.Text]
edgeKeyBlacklist = map T.pack [idKey]
emptyEdge :: LabelIndex -> Id -> Node -> Node -> Edge
emptyEdge li i sn en = Edge li i M.empty (nodeId sn, nodeId en)
saveEdge :: Edge -> GS Edge
saveEdge e = do g <- get
alterEdges (M.insert (edgeId e) e $ edges g)
return e
alterEdgeLabelIndex :: LabelIndex -> Edge -> Edge
alterEdgeLabelIndex li e = Edge li (edgeId e) (edgeProperties e) (connection e)
alterEdgeProperties :: Properties -> Edge -> Edge
alterEdgeProperties p e = Edge (edgeLabelIndex e) (edgeId e) p (connection e)
createEdgeNUnsafe :: Label -> Node -> Node -> GS (Edge, Node, Node)
createEdgeNUnsafe l sn en = do i <- incrementEdgeId
eli <- createEdgeLabel l
let e = emptyEdge eli i sn en
n1 <- addOutEdge e en eli sn
n2 <- addInEdge e sn eli en
se <- saveEdge e
return (se, n1, n2)
createEdgeRE :: Label -> Id -> Id -> GS (Edge, Node, Node)
createEdgeRE l snid enid = do sn <- getNodeByIdUnsafe snid
en <- getNodeByIdUnsafe enid
createEdgeNUnsafe l sn en
createEdge :: Label -> Id -> Id -> GS Id
createEdge l snid enid = do (e, _, _) <- createEdgeRE l snid enid
return $ edgeId e
createEdgeN :: Label -> Node -> Node -> GS (Edge, Node, Node)
createEdgeN l sn en = createEdgeRE l (nodeId sn) (nodeId en)
createEdgePairRE :: Label -> Id -> Id -> GS (Edge, Edge, Node, Node)
createEdgePairRE l snid enid = do (e1, _, _) <- createEdgeRE l snid enid
(e2, en2, sn2) <- createEdgeRE l enid snid
return (e1, e2, sn2, en2)
createEdgePair :: Label -> Id -> Id -> GS (Id, Id)
createEdgePair l snid enid = do (e1, _, _) <- createEdgeRE l snid enid
(e2, _, _) <- createEdgeRE l enid snid
return (edgeId e1, edgeId e2)
createEdgeNPair :: Label -> Node -> Node -> GS (Edge, Edge, Node, Node)
createEdgeNPair l sn en = do (e1, sn1, en1) <- createEdgeN l sn en
(e2, en2, sn2) <- createEdgeN l en1 sn1
return (e1, e2, sn2, en2)
createEdgeNPairUnsafe :: Label -> Node -> Node -> GS (Edge, Edge, Node, Node)
createEdgeNPairUnsafe l sn en = do (e1, sn1, en1) <- createEdgeNUnsafe l sn en
(e2, en2, sn2) <- createEdgeNUnsafe l en1 sn1
return (e1, e2, sn2, en2)
setEdgePropertyE :: Key -> Value -> Edge -> GS Edge
setEdgePropertyE k v e = if k `elem` edgeKeyBlacklist then return e else saveEdge newEdge
where
newEdge = alterEdgeProperties (M.insert k v $ edgeProperties e) e
setEdgeProperty :: Key -> Value -> Id -> GS Edge
setEdgeProperty k v i = getEdgeByIdUnsafe i >>= setEdgePropertyE k v
setEdgePropertiesE :: [(Key, Value)] -> Edge -> GS Edge
setEdgePropertiesE kvs e = foldl (\a (k, v) -> a >>= setEdgePropertyE k v) (return e) kvs
setEdgeProperties :: [(Key, Value)] -> Id -> GS Edge
setEdgeProperties kvs i = getEdgeByIdUnsafe i >>= setEdgePropertiesE kvs
removeEdgePropertyE :: Key -> Edge -> GS Edge
removeEdgePropertyE k e = if k `elem` nodeKeyBlacklist then return e else saveEdge newEdge
where
newEdge = alterEdgeProperties (M.delete k $ edgeProperties e) e
removeEdgeProperty :: Key -> Id -> GS Edge
removeEdgeProperty k i = getEdgeByIdUnsafe i >>= removeEdgePropertyE k
getEdgePropertySE :: Key -> Edge -> Maybe Value
getEdgePropertySE k e = M.lookup k (edgeProperties e)
getEdgePropertyE :: Key -> Edge -> GS (Maybe Value)
getEdgePropertyE k e = return $ getEdgePropertySE k e
getEdgeProperty :: Key -> Id -> GS (Maybe Value)
getEdgeProperty k i = getEdgeByIdUnsafe i >>= getEdgePropertyE k
isEdgePropertyEqualSE :: Key -> Value -> Edge -> Bool
isEdgePropertyEqualSE k v e = maybe False (==v) $ getEdgePropertySE k e
isEdgePropertyEqualE :: Key -> Value -> Edge -> GS Bool
isEdgePropertyEqualE k v e = return $ isEdgePropertyEqualSE k v e
isEdgePropertyEqual :: Key -> Value -> Id -> GS Bool
isEdgePropertyEqual k v i = getEdgeByIdUnsafe i >>= isEdgePropertyEqualE k v
hasEdgeLabelIndexSE :: LabelIndex -> Edge -> Bool
hasEdgeLabelIndexSE li e = edgeLabelIndex e == li
hasEdgeLabelIndexE :: LabelIndex -> Edge -> GS Bool
hasEdgeLabelIndexE li e = return $ hasEdgeLabelIndexSE li e
hasEdgeLabelIndex :: LabelIndex -> Id -> GS Bool
hasEdgeLabelIndex li i = getEdgeByIdUnsafe i >>= hasEdgeLabelIndexE li
hasEdgeLabelE :: Label -> Edge -> GS Bool
hasEdgeLabelE l e = do li <- getEdgeLabelIndex l
return $ maybe False (`hasEdgeLabelIndexSE` e) li
hasEdgeLabel :: Label -> Id -> GS Bool
hasEdgeLabel l i = getEdgeByIdUnsafe i >>= hasEdgeLabelE l
edgeLabelE :: Edge -> GS Label
edgeLabelE e = do l <- getEdgeLabel $ edgeLabelIndex e
return $ MB.fromMaybe (error "incorrect edge in function edgeLabel") l
edgeLabel :: Id -> GS Label
edgeLabel i = getEdgeByIdUnsafe i >>= edgeLabelE
edgeLabelSE :: Graph -> Edge -> Label
edgeLabelSE = unpackStateValue edgeLabelE
edgeLabelS :: Graph -> Id -> Label
edgeLabelS = unpackStateValue edgeLabel
changeEdgeLabelE :: Label -> Edge -> GS Edge
changeEdgeLabelE l e = do let oeli = edgeLabelIndex e
neli <- createEdgeLabel l
ne <- saveEdge $ alterEdgeLabelIndex neli e
sn <- getStartNodeN e
en <- getEndNodeE e
sn1 <- removeOutEdge e oeli sn
en1 <- removeOutEdge e oeli en
_ <- addOutEdge ne en1 neli sn1
_ <- addInEdge ne sn1 neli en1
return ne
changeEdgeLabel :: Label -> Id -> GS Edge
changeEdgeLabel l i = getEdgeByIdUnsafe i >>= changeEdgeLabelE l
getStartNodeN :: Edge -> GS Node
getStartNodeN e = getNodeByIdUnsafe $ fst $ connection e
getStartNode :: Id -> GS Node
getStartNode i = getEdgeByIdUnsafe i >>= getStartNodeN
getEndNodeE :: Edge -> GS Node
getEndNodeE e = getNodeByIdUnsafe $ snd $ connection e
getEndNode :: Id -> GS Node
getEndNode i = getEdgeByIdUnsafe i >>= getEndNodeE
deleteEdge :: Edge -> GS ()
deleteEdge e = do g <- get
let eid = edgeId e
let eli = edgeLabelIndex e
alterEdges $ M.delete eid (edges g)
sn <- getStartNodeN e
en <- getEndNodeE e
_ <- removeOutEdge e eli sn
_ <- removeInEdge e eli en
return ()
deleteNodeN :: Node -> GS ()
deleteNodeN n = do es <- getAllEdgesN n
foldl (>>) (return ()) $ map deleteEdge es
deleteNode' n
deleteNode :: Id -> GS ()
deleteNode i = getNodeByIdUnsafe i >>= deleteNodeN
| gpahal/hgraph | src/HGraph/Edge.hs | bsd-3-clause | 7,307 | 0 | 12 | 2,236 | 2,505 | 1,240 | 1,265 | 137 | 2 |
module Util where
-- use tick
-- use lastBlock
import Import
import Data.Int (Int64)
import Control.Monad (mzero)
import Data.Aeson
import Data.Time.Clock
import Data.Text (unpack)
import Network.HTTP.Types.URI (urlEncode)
import Numeric (showEFloat, fromRat)
import qualified Data.HashMap.Strict as HM
import Data.Scientific as Scientific
import qualified Data.Attoparsec.Number as AN
import qualified Data.ByteString.Lazy as B
import Data.ByteString.Lex.Lazy.Double (readDouble)
import qualified Data.ByteString as BS
import Network.HTTP.Conduit (simpleHttp)
blockReward :: Block -> Rational
blockReward b = toRational (reward $ blockHeight b) / 100000000
reward :: Int64 -> Int64
reward height =
reward_ind height 5000000000
reward_ind :: Int64 -> Int64 -> Int64
reward_ind height init =
if height < 210000
then init
else reward_ind (height - 210000) $ init `div` 2
data TickResult = TickResult !Object deriving (Show)
data Tick = Tick Rational deriving (Show)
unTick :: Tick -> Rational
unTick (Tick r) = r
instance FromJSON Tick where
parseJSON (Object v) = Tick <$> v .: "last"
parseJSON _ = mzero
-- jsonFile :: FilePath
-- jsonFile = "./ticker.json"
tickerURL :: String
tickerURL = "https://blockchain.info/ticker"
lastBlockURL :: String
lastBlockURL = "https://blockchain.info/latestblock"
rawBlockURL :: Hash -> String
rawBlockURL h = "https://blockchain.info/rawblock/" ++ (unpack (unHash h)) -- dangerous
-- urlEncodeString :: String -> String
-- urlEncodeString = BS.unpack . urlEncode True . BS.pack
difficultyURL :: String
difficultyURL = "https://blockchain.info/q/getdifficulty"
tickerJSON :: IO B.ByteString
tickerJSON = simpleHttp tickerURL
lastBlockJSON :: IO B.ByteString
lastBlockJSON = simpleHttp lastBlockURL
rawBlockJSON :: Hash -> IO B.ByteString
rawBlockJSON = simpleHttp . rawBlockURL
difficultyText :: IO B.ByteString
difficultyText = simpleHttp difficultyURL
rawBlockResult :: Hash -> IO (Either String (HM.HashMap Text Value))
rawBlockResult h = eitherDecode <$> rawBlockJSON h
tickerResult :: IO (Either String (HM.HashMap Text Value))
tickerResult = eitherDecode <$> tickerJSON
lastBlockResult :: IO (Either String (HM.HashMap Text Value))
lastBlockResult = eitherDecode <$> lastBlockJSON
l2v :: Value -> Maybe Value
l2v (Object m) = HM.lookup "last" m
l2v _ = Nothing
v2t :: Value -> Maybe Tick
v2t (Number n) = Just $ Tick $ toRational n
v2t _ = Nothing
l2t :: Value -> Maybe Tick
l2t l = l2v l >>= v2t
fetchTick :: IO (Maybe Tick)
fetchTick = do
outer <- tickerResult
case outer of
Left _ -> return Nothing
Right out ->
case HM.lookup "USD" out of
Nothing -> return Nothing
Just p -> return $ l2t p
data RawBlock = RawBlock
{ rawBlockHash :: Text
, rawBlockFee :: Int64
, rawBlockHeight :: Int64
, rawBlockTime :: Int64
}
parseRawBlock :: HM.HashMap Text Value -> Maybe RawBlock
parseRawBlock p = do
hashV <- look "hash"
hash <- readText hashV
feeV <- look "fee"
fee <- readNumber feeV
heightV <- look "height"
height <- readNumber heightV
timeV <- look "time"
time <- readNumber timeV
return $ RawBlock
{ rawBlockHash = unHash hash
, rawBlockFee = fee
, rawBlockHeight = height
, rawBlockTime = time
}
where
look label = HM.lookup label p
fetchRawBlock :: Hash -> IO (Maybe RawBlock)
fetchRawBlock h = do
outer <- rawBlockResult h
case outer of
Left _ -> return Nothing
Right out ->
return $ parseRawBlock out
fetchDifficulty :: IO (Maybe Double)
fetchDifficulty = do
str <- difficultyText
case readDouble str of
Nothing -> return Nothing
Just (d, _) -> return $ Just d
fetchBlock :: Hash -> IO (Maybe Block)
fetchBlock h = do
current <- getCurrentTime
fR <- fetchRawBlock h
fD <- fetchDifficulty
case (fR, fD) of
(Nothing, _) -> return Nothing
(_, Nothing) -> return Nothing
(Just rb, Just diff) -> do
return $ Just
$ Block
{ blockHash = rawBlockHash rb
, blockDifficulty = diff
, blockFee = rawBlockFee rb
, blockHeight = rawBlockHeight rb
, blockTime = rawBlockTime rb
, blockCreatedAt = current
}
fiveMinAgo :: Handler UTCTime
fiveMinAgo = do
curTime <- liftIO getCurrentTime
return $ addUTCTime (-5 * 60) curTime
recentBlock :: Handler (Maybe Block)
recentBlock = do
thr <- fiveMinAgo
result <- runDB $ selectFirst [BlockCreatedAt >=. thr] [Desc BlockCreatedAt]
case result of
Nothing -> return Nothing
Just (Entity _ b) ->
return $ Just b
recentTick :: Handler (Maybe Tick)
recentTick = do
thr <- fiveMinAgo
result <- runDB $ selectFirst [TickerCreatedAt >=. thr] [Desc TickerCreatedAt]
case result of
Nothing -> return Nothing
Just (Entity _ ticker) ->
return $ Just $ Tick (tickerUsdbtc ticker)
saveBlock :: Block -> Handler BlockId
saveBlock b = runDB $ insert b
saveTick :: Tick -> Handler TickerId
saveTick t = do
current <- liftIO getCurrentTime
runDB $ insert
$ Ticker
{ tickerUsdbtc = unTick t
, tickerCreatedAt = current
}
fetchSaveBlock :: Hash -> Handler Block
fetchSaveBlock h = do
b <- liftIO $ fetchBlock h
case b of
Nothing -> notFound
Just bl -> do
_ <- saveBlock bl
return bl
fetchSaveTick :: Handler Tick
fetchSaveTick = do
t <- liftIO fetchTick
case t of
Nothing -> notFound
Just tic -> do
_ <- saveTick tic
return tic
tick :: Handler Tick
tick = do
recent <- recentTick
case recent of
Just tic -> return tic
Nothing -> fetchSaveTick
block :: Handler Block
block = do
recent <- recentBlock
case recent of
Just bl -> return bl
Nothing -> do
lb <- liftIO lastB
case lb of
Nothing -> notFound
Just h -> do
hashBlock h
data Hash = Hash Text deriving (Show, Eq)
unHash :: Hash -> Text
unHash (Hash h) = h
readNumber :: Value -> Maybe Int64
readNumber (Number n) = Just $ round n
readNumber _ = Nothing
readText :: Value -> Maybe Hash
readText (String t) = Just $ Hash t
readText _ = Nothing
lastB :: IO (Maybe Hash)
lastB = do
outer <- lastBlockResult
case outer of
Left _ -> return Nothing
Right out ->
case HM.lookup "hash" out of
Nothing -> return Nothing
Just p -> return $ readText p
savelb :: Hash -> Handler LastBlockId
savelb h = do
current <- liftIO getCurrentTime
runDB $ insert
$ LastBlock
{ lastBlockHash = unHash h
, lastBlockObtainedAt = current
}
getSaveLastBlock :: Handler Hash
getSaveLastBlock = do
l <- liftIO lastB
case l of
Nothing -> notFound
Just lb -> do
_ <- savelb lb
return lb
lastBlock :: Handler Hash
lastBlock = do
thr <- fiveMinAgo
found <- runDB $ selectFirst [LastBlockObtainedAt >=. thr] [Desc LastBlockObtainedAt]
case found of
Just (Entity _ lb) -> return $ Hash $ lastBlockHash lb
Nothing -> getSaveLastBlock
hashBlock :: Hash -> Handler Block
hashBlock h = do
found <- runDB $ selectFirst [BlockHash ==. unHash h] []
case found of
Just (Entity _ b) -> return b
_ -> fetchSaveBlock h -- obtain from blockchain.info here
getSaveBlock :: Hash -> Handler Block
getSaveBlock h = do
b <- liftIO (fetchBlock h)
case b of
Nothing -> notFound
Just bb -> do
_ <- saveBlock bb
return bb
totalHashUntilBlock :: Block -> Double
totalHashUntilBlock b = blockDifficulty b * (2 ** 32)
btcHash :: Block -> Rational
btcHash b = ( blockReward b + ((toRational . blockFee) b / 100000000)) / (toRational $ totalHashUntilBlock b)
hashPrice :: Block -> Tick -> Rational
hashPrice b t = unTick t * btcHash b
getPrice :: Handler String
getPrice = do
b <- block
t <- tick
let s = hashPrice b t
return $ showEFloat (Just 3) (fromRat s) ""
| pirapira/hashprice | Util.hs | bsd-3-clause | 7,797 | 0 | 17 | 1,780 | 2,672 | 1,327 | 1,345 | 253 | 3 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -Wno-missing-signatures #-}
module Main
( main
)
where
import AutoApply
import qualified Codec.Picture as JP
import Control.Exception.Safe
import Control.Monad.IO.Class
import Control.Monad.Trans.Maybe ( MaybeT(..) )
import Control.Monad.Trans.Reader
import Control.Monad.Trans.Resource
import Data.Bits
import qualified Data.ByteString.Lazy as BSL
import Data.Foldable
import Data.List ( partition )
import Data.Maybe ( catMaybes )
import Data.Ord ( comparing )
import Data.Text ( Text )
import qualified Data.Text as T
import Data.Text.Encoding ( decodeUtf8 )
import qualified Data.Vector as V
import Data.Word
import Foreign.Marshal.Array ( peekArray )
import Foreign.Ptr
import Foreign.Storable ( sizeOf )
import Say
import Vulkan.CStruct.Extends
import Vulkan.CStruct.Utils ( FixedArray
, lowerArrayPtr
)
import Vulkan.Core10 as Vk
hiding ( withBuffer
, withImage
)
import Vulkan.Extensions.VK_EXT_debug_utils
import Vulkan.Extensions.VK_EXT_validation_features
import Vulkan.Utils.Debug
import Vulkan.Utils.ShaderQQ.GLSL.Glslang
import Vulkan.Zero
import VulkanMemoryAllocator as VMA
hiding ( getPhysicalDeviceProperties )
----------------------------------------------------------------
-- Define the monad in which most of the program will run
----------------------------------------------------------------
-- | @V@ keeps track of a bunch of "global" handles and performs resource
-- management.
newtype V a = V { unV :: ReaderT GlobalHandles (ResourceT IO) a }
deriving newtype ( Functor
, Applicative
, Monad
, MonadFail
, MonadThrow
, MonadCatch
, MonadMask
, MonadIO
, MonadResource
)
runV
:: Instance
-> PhysicalDevice
-> Word32
-> Device
-> Allocator
-> V a
-> ResourceT IO a
runV ghInstance ghPhysicalDevice ghComputeQueueFamilyIndex ghDevice ghAllocator
= flip runReaderT GlobalHandles { .. } . unV
data GlobalHandles = GlobalHandles
{ ghInstance :: Instance
, ghPhysicalDevice :: PhysicalDevice
, ghDevice :: Device
, ghAllocator :: Allocator
, ghComputeQueueFamilyIndex :: Word32
}
-- Getters for global handles
getInstance :: V Instance
getInstance = V (asks ghInstance)
getComputeQueueFamilyIndex :: V Word32
getComputeQueueFamilyIndex = V (asks ghComputeQueueFamilyIndex)
getPhysicalDevice :: V PhysicalDevice
getPhysicalDevice = V (asks ghPhysicalDevice)
getDevice :: V Device
getDevice = V (asks ghDevice)
getAllocator :: V Allocator
getAllocator = V (asks ghAllocator)
noAllocationCallbacks :: Maybe AllocationCallbacks
noAllocationCallbacks = Nothing
--
-- Wrap a bunch of Vulkan commands so that they automatically pull global
-- handles from 'V'
--
-- Wrapped functions are suffixed with "'"
--
autoapplyDecs
(<> "'")
[ 'getDevice
, 'getPhysicalDevice
, 'getInstance
, 'getAllocator
, 'noAllocationCallbacks
]
-- Allocate doesn't subsume the continuation type on the "with" commands, so
-- put it in the unifying group.
['allocate]
[ 'invalidateAllocation
, 'withBuffer
, 'deviceWaitIdle
, 'getDeviceQueue
, 'waitForFences
, 'withCommandBuffers
, 'withCommandPool
, 'withFence
, 'withComputePipelines
, 'withInstance
, 'withPipelineLayout
, 'withShaderModule
, 'withDescriptorPool
, 'allocateDescriptorSets
, 'withDescriptorSetLayout
, 'updateDescriptorSets
]
----------------------------------------------------------------
-- The program
----------------------------------------------------------------
main :: IO ()
main = runResourceT $ do
-- Create Instance, PhysicalDevice, Device and Allocator
inst <- Main.createInstance
(phys, pdi, dev) <- Main.createDevice inst
(_, allocator) <- withAllocator
zero { flags = zero
, physicalDevice = physicalDeviceHandle phys
, device = deviceHandle dev
, instance' = instanceHandle inst
, vulkanApiVersion = myApiVersion
}
allocate
-- Run our application
-- Wait for the device to become idle before tearing down any resourecs.
runV inst phys (pdiComputeQueueFamilyIndex pdi) dev allocator
. (`finally` deviceWaitIdle')
$ do
image <- render
let filename = "julia.png"
sayErr $ "Writing " <> filename
liftIO $ BSL.writeFile filename (JP.encodePng image)
-- Render the Julia set
render :: V (JP.Image JP.PixelRGBA8)
render = do
-- Some things to reuse, make sure these are the same as the values in the
-- compute shader. TODO: reduce this duplication.
let width, height, workgroupX, workgroupY :: Int
width = 512
height = width
workgroupX = 32
workgroupY = 4
-- Create a buffer into which to render
--
-- Use ALLOCATION_CREATE_MAPPED_BIT and MEMORY_USAGE_GPU_TO_CPU to make sure
-- it's readable on the host and starts in the mapped state
(_, (buffer, bufferAllocation, bufferAllocationInfo)) <- withBuffer'
zero { size = fromIntegral $ width * height * 4 * sizeOf (0 :: Float)
, usage = BUFFER_USAGE_STORAGE_BUFFER_BIT
}
zero { flags = ALLOCATION_CREATE_MAPPED_BIT
, usage = MEMORY_USAGE_GPU_TO_CPU
}
-- Create a descriptor set and layout for this buffer
(descriptorSet, descriptorSetLayout) <- do
-- Create a descriptor pool
(_, descriptorPool) <- withDescriptorPool' zero
{ maxSets = 1
, poolSizes = [DescriptorPoolSize DESCRIPTOR_TYPE_STORAGE_BUFFER 1]
}
-- Create a set layout
(_, descriptorSetLayout) <- withDescriptorSetLayout' zero
{ bindings = [ zero { binding = 0
, descriptorType = DESCRIPTOR_TYPE_STORAGE_BUFFER
, descriptorCount = 1
, stageFlags = SHADER_STAGE_COMPUTE_BIT
}
]
}
-- Allocate a descriptor set from the pool with that layout
-- Don't use `withDescriptorSets` here as the set will be cleaned up when
-- the pool is destroyed.
[descriptorSet] <- allocateDescriptorSets' zero
{ descriptorPool = descriptorPool
, setLayouts = [descriptorSetLayout]
}
pure (descriptorSet, descriptorSetLayout)
-- Assign the buffer in this descriptor set
updateDescriptorSets'
[ SomeStruct zero { dstSet = descriptorSet
, dstBinding = 0
, descriptorType = DESCRIPTOR_TYPE_STORAGE_BUFFER
, descriptorCount = 1
, bufferInfo = [DescriptorBufferInfo buffer 0 WHOLE_SIZE]
}
]
[]
-- Create our shader and compute pipeline
shader <- createShader
(_, pipelineLayout) <- withPipelineLayout' zero
{ setLayouts = [descriptorSetLayout]
}
let pipelineCreateInfo :: ComputePipelineCreateInfo '[]
pipelineCreateInfo = zero { layout = pipelineLayout
, stage = shader
, basePipelineHandle = zero
}
(_, (_, [computePipeline])) <- withComputePipelines'
zero
[SomeStruct pipelineCreateInfo]
-- Create a command buffer
computeQueueFamilyIndex <- getComputeQueueFamilyIndex
let commandPoolCreateInfo :: CommandPoolCreateInfo
commandPoolCreateInfo =
zero { queueFamilyIndex = computeQueueFamilyIndex }
(_, commandPool) <- withCommandPool' commandPoolCreateInfo
let commandBufferAllocateInfo = zero { commandPool = commandPool
, level = COMMAND_BUFFER_LEVEL_PRIMARY
, commandBufferCount = 1
}
(_, [commandBuffer]) <- withCommandBuffers' commandBufferAllocateInfo
-- Fill command buffer
useCommandBuffer commandBuffer
zero { flags = COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT }
$ do
-- Set up our state, pipeline and descriptor set
cmdBindPipeline commandBuffer
PIPELINE_BIND_POINT_COMPUTE
computePipeline
cmdBindDescriptorSets commandBuffer
PIPELINE_BIND_POINT_COMPUTE
pipelineLayout
0
[descriptorSet]
[]
-- Dispatch the compute shader
cmdDispatch
commandBuffer
(ceiling (realToFrac width / realToFrac @_ @Float workgroupX))
(ceiling (realToFrac height / realToFrac @_ @Float workgroupY))
1
-- Create a fence so we can know when render is finished
(_, fence) <- withFence' zero
-- Submit the command buffer and wait for it to execute
let submitInfo =
zero { commandBuffers = [commandBufferHandle commandBuffer] }
computeQueue <- getDeviceQueue' computeQueueFamilyIndex 0
queueSubmit computeQueue [SomeStruct submitInfo] fence
let fenceTimeout = 1e9 -- 1 second
waitForFences' [fence] True fenceTimeout >>= \case
TIMEOUT -> throwString "Timed out waiting for compute"
_ -> pure ()
-- If the buffer allocation is not HOST_COHERENT this will ensure the changes
-- are present on the CPU.
invalidateAllocation' bufferAllocation 0 WHOLE_SIZE
-- TODO: speed this bit up, it's hopelessly slow
let pixelAddr :: Int -> Int -> Ptr (FixedArray 4 Float)
pixelAddr x y = plusPtr (mappedData bufferAllocationInfo)
(((y * width) + x) * 4 * sizeOf (0 :: Float))
liftIO $ JP.withImage
width
height
(\x y -> do
let ptr = pixelAddr x y
[r, g, b, a] <- fmap (\f -> round (f * 255))
<$> peekArray 4 (lowerArrayPtr ptr)
pure $ JP.PixelRGBA8 r g b a
)
-- | Create a compute shader
createShader :: V (SomeStruct PipelineShaderStageCreateInfo)
createShader = do
let compCode = [comp|
#version 450
#extension GL_ARB_separate_shader_objects : enable
const int width = 512;
const int height = width;
const int workgroup_x = 32;
const int workgroup_y = 4;
// r^2 - r = |c|
const vec2 c = vec2(-0.8, 0.156);
const float r = 0.5 * (1 + sqrt (4 * dot(c,c) + 1));
layout (local_size_x = workgroup_x, local_size_y = workgroup_y, local_size_z = 1 ) in;
layout(std140, binding = 0) buffer buf
{
vec4 imageData[];
};
// From https://iquilezles.org/www/articles/palettes/palettes.htm
//
// Traditional Julia blue and orange
vec3 color(const float t) {
const vec3 a = vec3(0.5);
const vec3 b = vec3(0.5);
const vec3 c = vec3(8);
const vec3 d = vec3(0.5, 0.6, 0.7);
return a + b * cos(6.28318530718 * (c * t + d));
}
// complex multiplication
vec2 mulC(const vec2 a, const vec2 b) {
return vec2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
}
vec2 f(const vec2 z) {
return mulC(z,z) + c;
}
// Algorithm from https://en.wikipedia.org/wiki/Julia_set
void main() {
vec2 z = vec2
( float(gl_GlobalInvocationID.y) / float(height) * 2 * r - r
, float(gl_GlobalInvocationID.x) / float(width) * 2 * r - r
);
uint iteration = 0;
const int max_iteration = 1000;
while (dot(z,z) < dot(r,r) && iteration < max_iteration) {
z = f(z);
iteration++;
}
const uint i = width * gl_GlobalInvocationID.y + gl_GlobalInvocationID.x;
if (iteration == max_iteration) {
imageData[i] = vec4(0,0,0,1);
} else {
imageData[i] = vec4(color(float(iteration) / float(max_iteration)),1);
}
}
|]
(_, compModule) <- withShaderModule' zero { code = compCode }
let compShaderStageCreateInfo = zero { stage = SHADER_STAGE_COMPUTE_BIT
, module' = compModule
, name = "main"
}
pure $ SomeStruct compShaderStageCreateInfo
----------------------------------------------------------------
-- Initialization
----------------------------------------------------------------
myApiVersion :: Word32
myApiVersion = API_VERSION_1_0
-- | Create an instance with a debug messenger
createInstance :: MonadResource m => m Instance
createInstance = do
availableExtensionNames <-
toList
. fmap extensionName
. snd
<$> enumerateInstanceExtensionProperties Nothing
availableLayerNames <-
toList . fmap layerName . snd <$> enumerateInstanceLayerProperties
let requiredLayers = []
optionalLayers = ["VK_LAYER_KHRONOS_validation"]
requiredExtensions = [EXT_DEBUG_UTILS_EXTENSION_NAME]
optionalExtensions = [EXT_VALIDATION_FEATURES_EXTENSION_NAME]
extensions <- partitionOptReq "extension"
availableExtensionNames
optionalExtensions
requiredExtensions
layers <- partitionOptReq "layer"
availableLayerNames
optionalLayers
requiredLayers
let debugMessengerCreateInfo = zero
{ messageSeverity = DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT
.|. DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT
, messageType = DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT
.|. DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT
.|. DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT
, pfnUserCallback = debugCallbackPtr
}
instanceCreateInfo =
zero
{ applicationInfo = Just zero { applicationName = Nothing
, apiVersion = myApiVersion
}
, enabledLayerNames = V.fromList layers
, enabledExtensionNames = V.fromList extensions
}
::& debugMessengerCreateInfo
:& ValidationFeaturesEXT
[VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT]
[]
:& ()
(_, inst) <- withInstance' instanceCreateInfo
_ <- withDebugUtilsMessengerEXT inst debugMessengerCreateInfo Nothing allocate
pure inst
createDevice
:: (MonadResource m, MonadThrow m)
=> Instance
-> m (PhysicalDevice, PhysicalDeviceInfo, Device)
createDevice inst = do
(pdi, phys) <- pickPhysicalDevice inst physicalDeviceInfo
sayErr . ("Using device: " <>) =<< physicalDeviceName phys
let deviceCreateInfo = zero
{ queueCreateInfos =
[ SomeStruct zero { queueFamilyIndex = pdiComputeQueueFamilyIndex pdi
, queuePriorities = [1]
}
]
}
(_, dev) <- withDevice phys deviceCreateInfo Nothing allocate
pure (phys, pdi, dev)
----------------------------------------------------------------
-- Physical device tools
----------------------------------------------------------------
-- | Get a single PhysicalDevice deciding with a scoring function
pickPhysicalDevice
:: (MonadIO m, MonadThrow m, Ord a)
=> Instance
-> (PhysicalDevice -> m (Maybe a))
-- ^ Some "score" for a PhysicalDevice, Nothing if it is not to be chosen.
-> m (a, PhysicalDevice)
pickPhysicalDevice inst devScore = do
(_, devs) <- enumeratePhysicalDevices inst
scores <- catMaybes
<$> sequence [ fmap (, d) <$> devScore d | d <- toList devs ]
case scores of
[] -> throwString "Unable to find appropriate PhysicalDevice"
_ -> pure (maximumBy (comparing fst) scores)
-- | The Ord instance prioritises devices with more memory
data PhysicalDeviceInfo = PhysicalDeviceInfo
{ pdiTotalMemory :: Word64
, pdiComputeQueueFamilyIndex :: Word32
-- ^ The queue family index of the first compute queue
}
deriving (Eq, Ord)
physicalDeviceInfo
:: MonadIO m => PhysicalDevice -> m (Maybe PhysicalDeviceInfo)
physicalDeviceInfo phys = runMaybeT $ do
pdiTotalMemory <- do
heaps <- memoryHeaps <$> getPhysicalDeviceMemoryProperties phys
pure $ sum ((size :: MemoryHeap -> DeviceSize) <$> heaps)
pdiComputeQueueFamilyIndex <- do
queueFamilyProperties <- getPhysicalDeviceQueueFamilyProperties phys
let isComputeQueue q =
(QUEUE_COMPUTE_BIT .&&. queueFlags q) && (queueCount q > 0)
computeQueueIndices = fromIntegral . fst <$> V.filter
(isComputeQueue . snd)
(V.indexed queueFamilyProperties)
MaybeT (pure $ computeQueueIndices V.!? 0)
pure PhysicalDeviceInfo { .. }
physicalDeviceName :: MonadIO m => PhysicalDevice -> m Text
physicalDeviceName phys = do
props <- getPhysicalDeviceProperties phys
pure $ decodeUtf8 (deviceName props)
----------------------------------------------------------------
-- Utils
----------------------------------------------------------------
partitionOptReq
:: (Show a, Eq a, MonadIO m) => Text -> [a] -> [a] -> [a] -> m [a]
partitionOptReq type' available optional required = do
let (optHave, optMissing) = partition (`elem` available) optional
(reqHave, reqMissing) = partition (`elem` available) required
tShow = T.pack . show
for_ optMissing
$ \n -> sayErr $ "Missing optional " <> type' <> ": " <> tShow n
case reqMissing of
[] -> pure ()
[x] -> sayErr $ "Missing required " <> type' <> ": " <> tShow x
xs -> sayErr $ "Missing required " <> type' <> "s: " <> tShow xs
pure (reqHave <> optHave)
----------------------------------------------------------------
-- Bit utils
----------------------------------------------------------------
(.&&.) :: Bits a => a -> a -> Bool
x .&&. y = (/= zeroBits) (x .&. y)
| expipiplus1/vulkan | examples/compute/Main.hs | bsd-3-clause | 19,088 | 0 | 20 | 6,004 | 3,212 | 1,756 | 1,456 | -1 | -1 |
module Database.Algebra.SQL.Query where
import Data.Scientific
import qualified Data.Text as T
import qualified Data.Time.Calendar as C
-- TODO Do we have to check for validity of types?
-- TODO is window clause standard?
-- | Mixed datatype for sequences of both types of queries.
data Query = QValueQuery
{ valueQuery :: ValueQuery
}
| QDefinitionQuery
{ definitionQuery :: DefinitionQuery
} deriving Show
-- | A query which defines something (DDL).
data DefinitionQuery = -- CREATE MATERIALIZED VIEW foo AS ...
DQMatView
{ sourceQuery :: ValueQuery
, viewName :: String
}
-- A temporary table which is only existent in the current
-- session.
| DQTemporaryTable
{ sourceQuery :: ValueQuery
, tTableName :: String
} deriving Show
-- | A Query which has a table as a result.
data ValueQuery = VQSelect
-- The contained select statement.
{ selectStmt :: SelectStmt
}
-- Literal tables (e.g. "VALUES (1, 2), (2, 4)").
| VQLiteral
{ rows :: [[ColumnExpr]] -- ^ The values contained.
}
-- The with query to bind value queries to names.
| VQWith
{ -- | The bindings of the with query as a list of tuples, each
-- containing the table alias, the optional column names and
-- the used query.
cBindings :: [(String, Maybe [String], ValueQuery)]
, cBody :: ValueQuery
}
-- A binary set operation
-- (e.g. "TABLE foo UNION ALL TABLE bar").
| VQBinarySetOperation
{ leftQuery :: ValueQuery -- ^ The left query.
, rightQuery :: ValueQuery -- ^ The right query.
-- The used (multi-) set operation.
, operation :: SetOperation
} deriving Show
-- | A (multi-) set operation for two sets.
data SetOperation = -- The union of two sets.
SOUnionAll
-- The difference of two sets.
| SOExceptAll
deriving Show
-- | Represents a SQL query using select and other optional clauses. The
-- reason this type is seperated (and not within VQSelect) is the use within
-- tile merging in earlier steps.
data SelectStmt = SelectStmt -- TODO do we need a window clause ?
{ -- | The constituents of the select clause.
selectClause :: [SelectColumn] -- TODO should not be empty
, -- | Indicates whether duplicates are removed.
distinct :: Bool
, -- | The constituents of the from clause.
fromClause :: [FromPart]
, -- | A list of conjunctive column expression.
whereClause :: [ColumnExpr]
, -- | The values to group by.
groupByClause :: [ColumnExpr]
, -- | The values and direction to order the table after.
orderByClause :: [OrderExpr]
} deriving Show
-- | Tells which column to sort by and in which direction.
data OrderExpr = OE
{ -- | The expression to order after.
oExpr :: ExtendedExpr
, sortDirection :: SortDirection
} deriving Show
-- | The direction to sort in.
data SortDirection = Ascending
| Descending
deriving Show
-- | Represents a subset of possible statements which can occur in a from
-- clause.
data FromPart = -- Used as "... FROM foo AS bar ...", but also as
-- "... FROM foo ...", where the table reference is the alias.
FPAlias
{ fExpr :: FromExpr -- ^ The aliased expression.
, fName :: String -- ^ The name of the alias.
, optColumns :: Maybe [String] -- ^ Optional column names.
} deriving Show
-- A reference type used for placeholders.
type ReferenceType = Int
data FromExpr = -- Contains a subquery (e.g. "SELECT * FROM (TABLE foo) f;"),
-- where "TABLE foo" is the sub query.
FESubQuery
{ subQuery :: ValueQuery -- ^ The sub query.
}
| -- A placeholder which is substituted later.
FEVariable
{ vIdentifier :: ReferenceType
}
-- Reference to an existing table.
| FETableReference
{ tableReferenceName :: String -- ^ The name of the table.
}
-- Explicit join syntax
| FEExplicitJoin
{ joinType :: JoinOperator
, leftArg :: FromPart
, rightArg :: FromPart
}
deriving Show
data JoinOperator = LeftOuterJoin ColumnExpr
deriving Show
-- | Represents a subset of possible statements which can occur in a
-- select clause.
data SelectColumn = -- | @SELECT foo AS bar ...@
SCAlias
{ sExpr :: ExtendedExpr -- ^ The value expression aliased.
, sName :: String -- ^ The name of the alias.
}
| SCExpr ExtendedExpr
deriving Show
-- | Basic value expressions extended by aggregates and window functions.
data ExtendedExpr =
-- | Encapsulates the base cases.
EEBase
{ valueExpr :: ValueExprTemplate ExtendedExpr -- ^ The value expression.
}
-- | @f() OVER (PARTITION BY p ORDER BY s framespec)@
| EEWinFun
{ -- | Function to be computed over the window
winFun :: WindowFunction
-- | The expressions to partition by
, partCols :: [AggrExpr]
-- | Optional partition ordering
, orderBy :: [WindowOrderExpr]
-- | Optional frame specification
, frameSpec :: Maybe FrameSpec
}
-- | Aggregate function expression.
| EEAggrExpr
{ aggrExpr :: AggrExpr
} deriving Show
-- | Shorthand for the value expression base part of 'ExtendedExpr'.
type ExtendedExprBase = ValueExprTemplate ExtendedExpr
-- | A special order expression, which is used in windows of window functions.
-- This is needed because we can use window functions in the ORDER BY clause,
-- but not in window functions.
data WindowOrderExpr = WOE
{ woExpr :: AggrExpr
, wSortDirection :: SortDirection
} deriving Show
data FrameSpec = FHalfOpen FrameStart
| FClosed FrameStart FrameEnd
deriving (Show)
-- | Window frame start specification
data FrameStart = FSUnboundPrec -- ^ UNBOUNDED PRECEDING
| FSValPrec Int -- ^ <value> PRECEDING
| FSCurrRow -- ^ CURRENT ROW
deriving (Show)
-- | Window frame end specification
data FrameEnd = FECurrRow -- ^ CURRENT ROW
| FEValFol Int -- ^ <value> FOLLOWING
| FEUnboundFol -- ^ UNBOUNDED FOLLOWING
deriving (Show)
-- | Window functions
data WindowFunction = WFMax ColumnExpr
| WFMin ColumnExpr
| WFSum ColumnExpr
| WFAvg ColumnExpr
| WFAll ColumnExpr
| WFAny ColumnExpr
| WFFirstValue ColumnExpr
| WFLastValue ColumnExpr
| WFCount
| WFRank
| WFDenseRank
| WFRowNumber
deriving (Show)
-- | Basic value expressions extended only by aggregates.
data AggrExpr = AEBase (ValueExprTemplate AggrExpr)
| AEAggregate
{ aFunction :: AggregateFunction
} deriving Show
-- | Shorthand for the value expression base part of 'AggrExpr'.
type AggrExprBase = ValueExprTemplate AggrExpr
-- | Aggregate functions.
data AggregateFunction = AFAvg ColumnExpr
| AFMax ColumnExpr
| AFMin ColumnExpr
| AFSum ColumnExpr
| AFCount ColumnExpr
| AFCountDistinct ColumnExpr
| AFCountStar
| AFAll ColumnExpr
| AFAny ColumnExpr
deriving Show
-- | A template which allows the definition of a mutual recursive type for value
-- expressions, such that it can be extended with further constructors by other
-- data definitions.
data ValueExprTemplate rec =
-- | Encapsulates a representation of a SQL value.
VEValue
{ value :: Value -- ^ The value contained.
}
-- | A column.
| VEColumn
{ cName :: String -- ^ The name of the column.
-- | The optional prefix of the column.
, cPrefix :: Maybe String
}
-- | Application of a binary function.
| VEBinApp
{ binFun :: BinaryFunction -- ^ The applied function.
, firstExpr :: rec -- ^ The first operand.
, secondExpr :: rec -- ^ The second operand.
}
| VEUnApp
{ unFun :: UnaryFunction -- ^ The applied function
, arg :: rec -- ^ The operand
}
-- | e.g. @EXISTS (VALUES (1))@
| VEExists
{ existsQuery :: ValueQuery -- ^ The query to check on.
}
-- | e.g. @1 IN (VALUES (1))@
| VEIn
{ inExpr :: rec -- ^ The value to check for.
, inQuery :: ValueQuery -- ^ The query to check in.
}
-- | @testExpr BETWEEN lowerExpr AND upperExpr@
| VEBetween
{ testExpr :: rec
, lowerExpr :: rec
, upperExpr :: rec
}
-- | @CASE WHEN ELSE@ (restricted to one WHEN branch)
| VECase
{ condExpr :: rec
, thenBranch :: rec
, elseBranch :: rec
} deriving Show
-- FIXME merge VECast and VENot into UnaryFunction (maybe not possible)
-- | A type which does not extend basic value expressions, and therefore can
-- appear in any SQL clause.
newtype ColumnExpr = CEBase (ValueExprTemplate ColumnExpr)
deriving Show
-- | Shorthand for the value expression base part of 'ColumnExpr'.
type ColumnExprBase = (ValueExprTemplate ColumnExpr)
-- | Types of binary functions.
data BinaryFunction = BFPlus
| BFMinus
| BFTimes
| BFDiv
| BFModulo
| BFContains
| BFSimilarTo
| BFLike
| BFConcat
| BFGreaterThan
| BFGreaterEqual
| BFLowerThan
| BFLowerEqual
| BFEqual
| BFNotEqual
| BFAnd
| BFOr
| BFCoalesce
deriving Show
-- | Types of unary functions
data UnaryFunction = UFSin
| UFCos
| UFTan
| UFASin
| UFACos
| UFATan
| UFSqrt
| UFExp
| UFLog
| UFLn
| UFSubString Integer Integer
| UFExtract ExtractField
| UFNot
-- A type cast (e.g. @CAST(1 AS DOUBLE PRECISION)@).
| UFCast DataType
| UFIsNull
deriving (Show)
-- | Fields that can be extracted from date/time types
data ExtractField = ExtractDay
| ExtractMonth
| ExtractYear
deriving (Show)
-- | Types of valid SQL 99 datatypes (most likely a small subset) as stated in
-- 'SQL 1999: Understanding Relational Language Components' (Melton, Simon)
data DataType = -- | @INTEGER@
DTInteger
-- | @DECIMAL@
| DTDecimal
-- | @DECIMAL(precision, scale)@
| DTDecimalFixed Int Int
-- | @DOUBLE PRECISION@
| DTDoublePrecision
| DTText
-- | @BOOLEAN@
| DTBoolean
-- | @DATE@
| DTDate
deriving Show
data Value = -- | @42@
VInteger Integer
-- | Arbitrary precision numeric type
| VDecimal Scientific
-- | A double precision floating point number.
| VDoublePrecision Double
-- | e.g. @'foo'@
| VText T.Text
-- | e.g. @TRUE@, @FALSE@ (but not UNKOWN in this variant)
| VBoolean Bool
-- | Standard SQL dates (Gregorian calendar)
| VDate C.Day
-- | Representation of a null value. (While this can basically be
-- part of any nullable type, it is added here for simplicity.
-- Values aren't linked to types anyways.)
| VNull
deriving Show
--------------------------------------------------------------------------------
literalBaseExpr :: ValueExprTemplate r -> Bool
literalBaseExpr (VEValue _) = True
literalBaseExpr _ = False
literalAggrExpr :: AggrExpr -> Bool
literalAggrExpr (AEBase b) = literalBaseExpr b
literalAggrExpr _ = False
| ulricha/algebra-sql | src/Database/Algebra/SQL/Query.hs | bsd-3-clause | 13,687 | 0 | 12 | 5,533 | 1,373 | 896 | 477 | 223 | 1 |
module Main where
import Data.Vector as V
import Data.Array.Repa
import Data.Array.Repa.Repr.Vector
import Data.Array.Repa.Algorithms.Matrix
import Numeric.Algorithms.HSVO.SVM
import Numeric.Algorithms.HSVO.Detail
import Control.Monad.State
import Control.Monad.Writer
import Control.Monad.Reader
bVec = V.fromList [0, 1 , 3 ] :: V.Vector Integer
s1 = [0.1, 0.2]
listToSample :: [Value] -> Sample
listToSample a = Sample $ fromListUnboxed (Z :. Prelude.length a) a
scalarToRepa :: Value -> BaseScalar
scalarToRepa a = fromListUnboxed (Z) [a]
sv1 = SupportVector {
_alpha= scalarToRepa 0.3
, _vector = listToSample s1
}
tsvO = TrainingSV {
_trueLabel = Class1
, _predLabel = PredictClass2 0.2
, _classError = calcClassError Class1 $ PredictClass2 0.2
, _supvec = sv1
}
stupidKernel :: Kernel
stupidKernel _ _ = scalarToRepa 0.1
params = SVMParameters {
_kernel = stupidKernel
, _threshold = scalarToRepa 0.1
, _margin = scalarToRepa 0.1
, _epsillon = 0.3
}
tData = TrainingData {_training = V.fromList [tsvO]}
{-
So I want to see what happens if I have various things in the StateT monad.
-}
temp :: StateT WorkingState IO ()
temp =
do
a <- get
pure ()
main :: IO ()
main = putStrLn $ show bVec
| johnny555/HSVO | app/Main.hs | bsd-3-clause | 1,490 | 0 | 10 | 479 | 374 | 214 | 160 | 39 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
-- |This module defines core functions for tracking the consumption of a
-- ByteString, as well as several helper functions for making tracking
-- ByteStrings easier.
module Data.ByteString.Lazy.Progress(
trackProgress
, trackProgressWithChunkSize
--
, trackProgressString
, trackProgressStringWithChunkSize
--
, bytesToUnittedStr
)
where
import Control.Applicative ((<$>))
import qualified Data.ByteString as BSS
import Data.ByteString.Lazy(ByteString)
import qualified Data.ByteString.Lazy as BS
import Data.Maybe (isJust)
import Data.Time.Clock (getCurrentTime,diffUTCTime,UTCTime)
import Data.Word (Word64)
import System.IO.Unsafe (unsafeInterleaveIO)
-- |Given a function, return a bytestring that will call that function when it
-- is partially consumed. The Words provided to the function will be the number
-- of bytes that were just consumed and the total bytes consumed thus far.
trackProgress :: (Word64 -> Word64 -> IO ()) ->
ByteString ->
IO ByteString
trackProgress tracker inputBS =
BS.fromChunks <$> runTrack 0 (BS.toChunks inputBS)
where
runTrack _ [] = return []
runTrack x (fst:rest) = unsafeInterleaveIO $ do
let amtRead = fromIntegral $ BSS.length fst
tracker amtRead (x + amtRead)
(fst :) <$> runTrack (x + amtRead) rest
-- |Works like 'trackProgress', except uses fixed-size chunks of the given
-- size. Thus, for this function, the first number passed to your function
-- will always be the given size *except* for the last call to the function,
-- which will be less then or equal to the final size.
trackProgressWithChunkSize :: Word64 -> (Word64 -> Word64 -> IO ()) ->
ByteString ->
IO ByteString
trackProgressWithChunkSize chunkSize tracker inputBS = runLoop 0 inputBS
where
runLoop x bstr | BS.null bstr = return BS.empty
| otherwise = unsafeInterleaveIO $ do
let (first,rest) = BS.splitAt (fromIntegral chunkSize) bstr
amtRead = fromIntegral (BS.length first)
tracker amtRead (x + amtRead)
(first `BS.append`) <$> runLoop (x + amtRead) rest
-- |Given a format string (described below), track the progress of a function.
-- The argument to the callback will be the string expanded with the given
-- progress information.
--
-- Format string items:
--
-- * %b is the number of bytes read
--
-- * %B is the number of bytes read, formatted into a human-readable string
--
-- * %c is the size of the last chunk read
--
-- * %C is the size of the last chunk read, formatted human-readably
--
-- * %r is the rate in bytes per second
--
-- * %R is the rate, formatted human-readably
--
-- * %% is the character '%'
--
-- If you provide a total size (the maybe argument, in bytes), then you may
-- also use the following items:
--
-- * %t is the estimated time to completion in seconds
--
-- * %T is the estimated time to completion, formatted as HH:MM:SS
--
-- * %p is the percentage complete
--
trackProgressString :: String -> Maybe Word64 -> (String -> IO ()) ->
IO (ByteString -> IO ByteString)
trackProgressString formatStr mTotal tracker = do
startTime <- getCurrentTime
return (trackProgress (handler startTime))
where
handler startTime chunkSize total = do
now <- getCurrentTime
tracker (buildString formatStr startTime now mTotal chunkSize total)
-- |Exactly as 'trackProgressString', but use the given chunkSize instead
-- of the default chunk size.
trackProgressStringWithChunkSize :: String -- ^the format string
-> Word64 -- ^the chunk size
-> Maybe Word64 -- ^total size (opt.)
-> (String -> IO ()) -- ^the action
-> IO (ByteString -> IO ByteString)
trackProgressStringWithChunkSize formatStr chunk mTotal tracker = do
startTime <- getCurrentTime
return (trackProgressWithChunkSize chunk (handler startTime))
where
handler startTime chunkSize total = do
now <- getCurrentTime
tracker (buildString formatStr startTime now mTotal chunkSize total)
-- build a progress string for trackProgressString et al
buildString :: String ->
UTCTime -> UTCTime -> Maybe Word64 -> Word64 -> Word64 ->
String
buildString form startTime curTime mTotal chunkSize amtRead = subPercents form
where
per_b = show amtRead
per_B = bytesToUnittedStr amtRead
per_c = show chunkSize
per_C = bytesToUnittedStr chunkSize
diff = max 1 (round $ toRational $ diffUTCTime curTime startTime)
rate = amtRead `div` diff
per_r = show rate
per_R = bytesToUnittedStr rate ++ "ps"
total = case mTotal of
Just t -> t
Nothing -> error "INTERNAL ERROR (needed total w/ Nothing)"
tleft = (total - amtRead) `div` rate
per_t = show tleft
hLeft = tleft `div` (60 * 60)
mLeft = (tleft `div` 60) `mod` 60
sLeft = tleft `mod` 60
per_T = showPadded hLeft ++ ":" ++ showPadded mLeft ++
":" ++ showPadded sLeft
perc = 100 * (fromIntegral amtRead / fromIntegral total) :: Double
per_p = show (round perc) ++ "%"
oktot = isJust mTotal
--
subPercents [] = []
subPercents ('%':rest) = subPercents' rest
subPercents (x:rest) = x : subPercents rest
--
subPercents' [] = []
subPercents' ('b':rest) = per_b ++ subPercents rest
subPercents' ('B':rest) = per_B ++ subPercents rest
subPercents' ('c':rest) = per_c ++ subPercents rest
subPercents' ('C':rest) = per_C ++ subPercents rest
subPercents' ('r':rest) = per_r ++ subPercents rest
subPercents' ('R':rest) = per_R ++ subPercents rest
subPercents' ('t':rest) | oktot = per_t ++ subPercents rest
subPercents' ('T':rest) | oktot = per_T ++ subPercents rest
subPercents' ('p':rest) | oktot = per_p ++ subPercents rest
subPercents' ('%':rest) = "%" ++ subPercents rest
subPercents' (x:rest) = '%' : ('x' : subPercents rest)
-- show a number padded to force at least two digits.
showPadded :: Show a => a -> String
showPadded x = prefix ++ base
where
base = show x
prefix = case base of
[] -> "00"
[x] -> "0"
_ -> ""
-- |Convert a number of bytes to a string represenation that uses a reasonable
-- unit to make the number human-readable.
bytesToUnittedStr :: Word64 -> String
bytesToUnittedStr x
| x < bk_brk = show x ++ "b"
| x < km_brk = showHundredthsDiv x k ++ "k"
| x < mg_brk = showHundredthsDiv x m ++ "m"
| otherwise = showHundredthsDiv x g ++ "g"
where
bk_brk = 4096
km_brk = 768 * k
mg_brk = 768 * m
--
k = 1024
m = 1024 * k
g = 1024 * m
-- Divide the first number by the second, and convert to a string showing two
-- decimal places.
showHundredthsDiv _ 0 = error "Should never happen!"
showHundredthsDiv amt size = show ones ++ "." ++ show tenths ++ show hundreths
where
divRes :: Double = fromIntegral amt / fromIntegral size
divRes100 = round (divRes * 100)
ones = divRes100 `div` 100
tenths = (divRes100 `div` 10) `mod` 10
hundreths = divRes100 `mod` 10
| acw/bytestring-progress | Data/ByteString/Lazy/Progress.hs | bsd-3-clause | 7,473 | 0 | 17 | 2,011 | 1,761 | 926 | 835 | 120 | 15 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE UnicodeSyntax #-}
{-|
[@ISO639-1@] -
[@ISO639-2@] -
[@ISO639-3@] lld
[@Native name@] Ladin
[@English name@] Ladin
-}
module Text.Numeral.Language.LLD
( -- * Language entry
entry
-- * Conversions
, cardinal
-- * Structure
, struct
-- * Bounds
, bounds
) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "base" Data.Bool ( otherwise )
import "base" Data.Function ( ($), const )
import "base" Data.Maybe ( Maybe(Just) )
import "base" Prelude ( Integral, (-), negate )
import "base-unicode-symbols" Data.Function.Unicode ( (∘) )
import "base-unicode-symbols" Data.Bool.Unicode ( (∧), (∨) )
import "base-unicode-symbols" Data.Eq.Unicode ( (≡), (≢) )
import "base-unicode-symbols" Data.Ord.Unicode ( (≤) )
import qualified "containers" Data.Map as M ( fromList, lookup )
import "this" Text.Numeral
import qualified "this" Text.Numeral.BigNum as BN
import qualified "this" Text.Numeral.Exp as E
import qualified "this" Text.Numeral.Grammar as G
import "this" Text.Numeral.Misc ( dec )
import "this" Text.Numeral.Entry
import "this" Text.Numeral.Language.FUR ( struct )
import "this" Text.Numeral.Render.Utils ( addCtx, mulCtx )
import "text" Data.Text ( Text )
--------------------------------------------------------------------------------
-- LLD
--------------------------------------------------------------------------------
entry ∷ Entry
entry = emptyEntry
{ entIso639_3 = Just "lld"
, entNativeNames = ["Ladin"]
, entEnglishName = Just "Ladin"
, entCardinal = Just Conversion
{ toNumeral = cardinal
, toStructure = struct
}
}
cardinal ∷ (G.Masculine i, G.Feminine i, Integral α, E.Scale α)
⇒ i → α → Maybe Text
cardinal inf = cardinalRepr inf ∘ struct
bounds ∷ (Integral α) ⇒ (α, α)
bounds = let x = dec 12 - 1 in (negate x, x)
cardinalRepr ∷ (G.Feminine i, G.Masculine i) ⇒ i → Exp i → Maybe Text
cardinalRepr = render defaultRepr
{ reprValue = \inf n → M.lookup n (syms inf)
, reprAdd = Just (⊞)
, reprMul = Just (⊡)
, reprScale = BN.pelletierRepr
(BN.quantityName "ilion" "ilion")
(BN.quantityName "iliard" "iliard")
[]
}
where
( Lit 20 ⊞ Lit n) _ | n ≢ 1 ∧ n ≢ 8 = "e"
((Lit t `Mul` Lit 10) ⊞ Lit n) _ | n ≢ 1 ∧ (t ≡ 3 ∨ n ≢ 8) = "e"
( Lit 100 ⊞ _) _ = "e"
((_ `Mul` Lit 100) ⊞ _) _ = "e"
((_ `Mul` Scale{}) ⊞ _) _ = "e"
(_ ⊞ _) _ = ""
(_ ⊡ Scale {}) _ = " "
(_ ⊡ _ ) _ = ""
syms inf =
M.fromList
[ (0, const "zero")
, (1, addCtx 10 "un"
$ \c → case c of
_ | G.isFeminine inf → "una"
| otherwise → "un"
)
, (2, addCtx 10 "do"
$ \c → case c of
_ | G.isFeminine inf → "does"
| otherwise → "doi"
)
, (3, addCtx 10 "tre" $ mulCtx 10 "tr" $ const "trei")
, (4, addCtx 10 "cator" $ mulCtx 10 "car" $ const "cater")
, (5, addCtx 10 "chin" $ mulCtx 10 "cinc" $ const "cinch")
, (6, addCtx 10 "sei" $ mulCtx 10 "sess" $ const "sies")
, (7, const "set")
, (8, addCtx 10 "dot" $ const "ot")
, (9, mulCtx 10 "non" $ const "nuef")
, (10, \c → case c of
CtxAdd _ (Lit n) _
| n ≤ 6 → "desc"
| n ≡ 7 → "dejes"
| n ≤ 9 → "deje"
CtxMul _ (Lit 3) (CtxAdd {}) → "ent"
CtxMul _ (Lit 3) _ → "enta"
CtxMul _ (Lit _) (CtxAdd {}) → "ant"
CtxMul _ (Lit _) _ → "anta"
_ → "diesc"
)
, (20, const "vint")
, (100, mulCtx 6 "çent" $ const "cent")
, (1000, const "mile")
]
| telser/numerals | src/Text/Numeral/Language/LLD.hs | bsd-3-clause | 4,636 | 12 | 15 | 1,714 | 1,324 | 746 | 578 | 89 | 12 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Stack.Options
(BuildCommand(..)
,GlobalOptsContext(..)
,benchOptsParser
,buildOptsParser
,cleanOptsParser
,configCmdSetParser
,configOptsParser
,dockerOptsParser
,dockerCleanupOptsParser
,dotOptsParser
,execOptsParser
,evalOptsParser
,globalOptsParser
,initOptsParser
,newOptsParser
,nixOptsParser
,logLevelOptsParser
,ghciOptsParser
,solverOptsParser
,testOptsParser
,hpcReportOptsParser
,pvpBoundsOption
,globalOptsFromMonoid
) where
import Control.Monad.Logger (LogLevel (..))
import Data.Char (isSpace, toLower)
import Data.List (intercalate)
import Data.List.Split (splitOn)
import qualified Data.Map as Map
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Monoid
import qualified Data.Set as Set
import qualified Data.Text as T
import Data.Text.Read (decimal)
import Distribution.Version (anyVersion)
import Options.Applicative
import Options.Applicative.Args
import Options.Applicative.Builder.Extra
import Options.Applicative.Types (fromM, oneM, readerAsk)
import Stack.Clean (CleanOpts (..))
import Stack.Config (packagesParser)
import Stack.ConfigCmd
import Stack.Constants (stackProgName)
import Stack.Coverage (HpcReportOpts (..))
import Stack.Docker
import qualified Stack.Docker as Docker
import Stack.Dot
import Stack.Ghci (GhciOpts (..))
import Stack.Init
import Stack.New
import Stack.Nix
import Stack.Types
import Stack.Types.TemplateName
-- | Command sum type for conditional arguments.
data BuildCommand
= Build
| Test
| Haddock
| Bench
| Install
deriving (Eq)
-- | Allows adjust global options depending on their context
-- Note: This was being used to remove ambibuity between the local and global
-- implementation of stack init --resolver option. Now that stack init has no
-- local --resolver this is not being used anymore but the code is kept for any
-- similar future use cases.
data GlobalOptsContext
= OuterGlobalOpts -- ^ Global options before subcommand name
| OtherCmdGlobalOpts -- ^ Global options following any other subcommand
deriving (Show, Eq)
-- | Parser for bench arguments.
benchOptsParser :: Parser BenchmarkOpts
benchOptsParser = BenchmarkOpts
<$> optional (strOption (long "benchmark-arguments" <>
metavar "BENCH_ARGS" <>
help ("Forward BENCH_ARGS to the benchmark suite. " <>
"Supports templates from `cabal bench`")))
<*> switch (long "no-run-benchmarks" <>
help "Disable running of benchmarks. (Benchmarks will still be built.)")
-- | Parser for build arguments.
buildOptsParser :: BuildCommand
-> Parser BuildOpts
buildOptsParser cmd =
transform <$> trace <*> profile <*> options
where transform tracing profiling = enable
where enable opts
| tracing || profiling =
opts {boptsLibProfile = True
,boptsExeProfile = True
,boptsGhcOptions = ["-auto-all","-caf-all"]
,boptsBenchmarkOpts =
bopts {beoAdditionalArgs =
beoAdditionalArgs bopts <>
Just (" " <> unwords additionalArgs)}
,boptsTestOpts =
topts {toAdditionalArgs =
(toAdditionalArgs topts) <>
additionalArgs}}
| otherwise = opts
where bopts = boptsBenchmarkOpts opts
topts = boptsTestOpts opts
additionalArgs = "+RTS" : catMaybes [trac, prof, Just "-RTS"]
trac = if tracing
then Just "-xc"
else Nothing
prof = if profiling
then Just "-p"
else Nothing
profile =
flag False True
( long "profile"
<> help "Enable profiling in libraries, executables, etc. \
\for all expressions and generate a profiling report\
\ in exec or benchmarks")
trace =
flag False True
( long "trace"
<> help "Enable profiling in libraries, executables, etc. \
\for all expressions and generate a backtrace on \
\exception")
options =
BuildOpts <$> target <*> libProfiling <*> exeProfiling <*>
haddock <*> haddockDeps <*> dryRun <*> ghcOpts <*>
flags <*> copyBins <*> preFetch <*> buildSubset <*>
fileWatch' <*> keepGoing <*> forceDirty <*> tests <*>
testOptsParser <*> benches <*> benchOptsParser <*>
many exec <*> onlyConfigure <*> reconfigure <*> cabalVerbose
target =
many (textArgument
(metavar "TARGET" <>
help "If none specified, use all packages"))
libProfiling =
boolFlags False
"library-profiling"
"library profiling for TARGETs and all its dependencies"
idm
exeProfiling =
boolFlags False
"executable-profiling"
"executable profiling for TARGETs and all its dependencies"
idm
haddock =
boolFlags (cmd == Haddock)
"haddock"
"generating Haddocks the package(s) in this directory/configuration"
idm
haddockDeps =
maybeBoolFlags
"haddock-deps"
"building Haddocks for dependencies"
idm
copyBins = boolFlags (cmd == Install)
"copy-bins"
"copying binaries to the local-bin-path (see 'stack path')"
idm
dryRun = switch (long "dry-run" <>
help "Don't build anything, just prepare to")
ghcOpts = (\x y z -> concat [x, y, z])
<$> flag [] ["-Wall", "-Werror"]
( long "pedantic"
<> help "Turn on -Wall and -Werror"
)
<*> flag [] ["-O0"]
( long "fast"
<> help "Turn off optimizations (-O0)"
)
<*> many (textOption (long "ghc-options" <>
metavar "OPTION" <>
help "Additional options passed to GHC"))
flags = Map.unionsWith Map.union <$> many
(option readFlag
(long "flag" <>
metavar "PACKAGE:[-]FLAG" <>
help ("Override flags set in stack.yaml " <>
"(applies to local packages and extra-deps)")))
preFetch = switch
(long "prefetch" <>
help "Fetch packages necessary for the build immediately, useful with --dry-run")
buildSubset =
flag' BSOnlyDependencies
(long "dependencies-only" <>
help "A synonym for --only-dependencies")
<|> flag' BSOnlySnapshot
(long "only-snapshot" <>
help "Only build packages for the snapshot database, not the local database")
<|> flag' BSOnlyDependencies
(long "only-dependencies" <>
help "Only build packages that are dependencies of targets on the command line")
<|> pure BSAll
fileWatch' =
flag' FileWatch
(long "file-watch" <>
help "Watch for changes in local files and automatically rebuild. Ignores files in VCS boring/ignore file")
<|> flag' FileWatchPoll
(long "file-watch-poll" <>
help "Like --file-watch, but polling the filesystem instead of using events")
<|> pure NoFileWatch
keepGoing = maybeBoolFlags
"keep-going"
"continue running after a step fails (default: false for build, true for test/bench)"
idm
forceDirty = switch
(long "force-dirty" <>
help "Force treating all local packages as having dirty files (useful for cases where stack can't detect a file change)")
tests = boolFlags (cmd == Test)
"test"
"testing the package(s) in this directory/configuration"
idm
benches = boolFlags (cmd == Bench)
"bench"
"benchmarking the package(s) in this directory/configuration"
idm
exec = cmdOption
( long "exec" <>
metavar "CMD [ARGS]" <>
help "Command and arguments to run after a successful build" )
onlyConfigure = switch
(long "only-configure" <>
help "Only perform the configure step, not any builds. Intended for tool usage, may break when used on multiple packages at once!")
reconfigure = switch
(long "reconfigure" <>
help "Perform the configure step even if unnecessary. Useful in some corner cases with custom Setup.hs files")
cabalVerbose = switch
(long "cabal-verbose" <>
help "Ask Cabal to be verbose in its output")
-- | Parser for package:[-]flag
readFlag :: ReadM (Map (Maybe PackageName) (Map FlagName Bool))
readFlag = do
s <- readerAsk
case break (== ':') s of
(pn, ':':mflag) -> do
pn' <-
case parsePackageNameFromString pn of
Nothing
| pn == "*" -> return Nothing
| otherwise -> readerError $ "Invalid package name: " ++ pn
Just x -> return $ Just x
let (b, flagS) =
case mflag of
'-':x -> (False, x)
_ -> (True, mflag)
flagN <-
case parseFlagNameFromString flagS of
Nothing -> readerError $ "Invalid flag name: " ++ flagS
Just x -> return x
return $ Map.singleton pn' $ Map.singleton flagN b
_ -> readerError "Must have a colon"
-- | Command-line parser for the clean command.
cleanOptsParser :: Parser CleanOpts
cleanOptsParser = CleanTargets <$> packages <|> CleanFull <$> doFullClean
where
packages =
many
(packageNameArgument
(metavar "PACKAGE" <>
help "If none specified, clean all local packages"))
doFullClean =
switch
(long "full" <>
help "Remove whole the work dir, default is .stack-work")
-- | Command-line arguments parser for configuration.
configOptsParser :: Bool -> Parser ConfigMonoid
configOptsParser hide0 =
(\workDir dockerOpts nixOpts systemGHC installGHC arch os ghcVariant jobs includes libs skipGHCCheck skipMsys localBin modifyCodePage -> mempty
{ configMonoidWorkDir = workDir
, configMonoidDockerOpts = dockerOpts
, configMonoidNixOpts = nixOpts
, configMonoidSystemGHC = systemGHC
, configMonoidInstallGHC = installGHC
, configMonoidSkipGHCCheck = skipGHCCheck
, configMonoidArch = arch
, configMonoidOS = os
, configMonoidGHCVariant = ghcVariant
, configMonoidJobs = jobs
, configMonoidExtraIncludeDirs = includes
, configMonoidExtraLibDirs = libs
, configMonoidSkipMsys = skipMsys
, configMonoidLocalBinPath = localBin
, configMonoidModifyCodePage = modifyCodePage
})
<$> optional (strOption
( long "work-dir"
<> metavar "WORK-DIR"
<> help "Override work directory (default: .stack-work)"
<> hide
))
<*> dockerOptsParser True
<*> nixOptsParser True
<*> maybeBoolFlags
"system-ghc"
"using the system installed GHC (on the PATH) if available and a matching version"
hide
<*> maybeBoolFlags
"install-ghc"
"downloading and installing GHC if necessary (can be done manually with stack setup)"
hide
<*> optional (strOption
( long "arch"
<> metavar "ARCH"
<> help "System architecture, e.g. i386, x86_64"
<> hide
))
<*> optional (strOption
( long "os"
<> metavar "OS"
<> help "Operating system, e.g. linux, windows"
<> hide
))
<*> optional (ghcVariantParser hide0)
<*> optional (option auto
( long "jobs"
<> short 'j'
<> metavar "JOBS"
<> help "Number of concurrent jobs to run"
<> hide
))
<*> fmap Set.fromList (many (textOption
( long "extra-include-dirs"
<> metavar "DIR"
<> help "Extra directories to check for C header files"
<> hide
)))
<*> fmap Set.fromList (many (textOption
( long "extra-lib-dirs"
<> metavar "DIR"
<> help "Extra directories to check for libraries"
<> hide
)))
<*> maybeBoolFlags
"skip-ghc-check"
"skipping the GHC version and architecture check"
hide
<*> maybeBoolFlags
"skip-msys"
"skipping the local MSYS installation (Windows only)"
hide
<*> optional (strOption
( long "local-bin-path"
<> metavar "DIR"
<> help "Install binaries to DIR"
<> hide
))
<*> maybeBoolFlags
"modify-code-page"
"setting the codepage to support UTF-8 (Windows only)"
hide
where hide = hideMods hide0
nixOptsParser :: Bool -> Parser NixOptsMonoid
nixOptsParser hide0 = overrideActivation <$>
(NixOptsMonoid
<$> pure False
<*> maybeBoolFlags nixCmdName
"use of a Nix-shell"
hide
<*> maybeBoolFlags "nix-pure"
"use of a pure Nix-shell"
hide
<*> (fmap (map T.pack)
<$> optional (argsOption (long "nix-packages" <>
metavar "NAMES" <>
help "List of packages that should be available in the nix-shell (space separated)" <>
hide)))
<*> optional (option str (long "nix-shell-file" <>
metavar "FILEPATH" <>
help "Nix file to be used to launch a nix-shell (for regular Nix users)" <>
hide))
<*> (fmap (map T.pack)
<$> optional (argsOption (long "nix-shell-options" <>
metavar "OPTIONS" <>
help "Additional options passed to nix-shell" <>
hide)))
<*> (fmap (map T.pack)
<$> optional (argsOption (long "nix-path" <>
metavar "PATH_OPTIONS" <>
help "Additional options to override NIX_PATH parts (notably 'nixpkgs')" <>
hide)))
)
where
hide = hideMods hide0
overrideActivation m =
if m /= mempty then m { nixMonoidEnable = Just . fromMaybe True $ nixMonoidEnable m }
else m
-- | Options parser configuration for Docker.
dockerOptsParser :: Bool -> Parser DockerOptsMonoid
dockerOptsParser hide0 =
DockerOptsMonoid
<$> pure False
<*> maybeBoolFlags dockerCmdName
"using a Docker container"
hide
<*> ((Just . DockerMonoidRepo) <$> option str (long (dockerOptName dockerRepoArgName) <>
hide <>
metavar "NAME" <>
help "Docker repository name") <|>
(Just . DockerMonoidImage) <$> option str (long (dockerOptName dockerImageArgName) <>
hide <>
metavar "IMAGE" <>
help "Exact Docker image ID (overrides docker-repo)") <|>
pure Nothing)
<*> maybeBoolFlags (dockerOptName dockerRegistryLoginArgName)
"registry requires login"
hide
<*> maybeStrOption (long (dockerOptName dockerRegistryUsernameArgName) <>
hide <>
metavar "USERNAME" <>
help "Docker registry username")
<*> maybeStrOption (long (dockerOptName dockerRegistryPasswordArgName) <>
hide <>
metavar "PASSWORD" <>
help "Docker registry password")
<*> maybeBoolFlags (dockerOptName dockerAutoPullArgName)
"automatic pulling latest version of image"
hide
<*> maybeBoolFlags (dockerOptName dockerDetachArgName)
"running a detached Docker container"
hide
<*> maybeBoolFlags (dockerOptName dockerPersistArgName)
"not deleting container after it exits"
hide
<*> maybeStrOption (long (dockerOptName dockerContainerNameArgName) <>
hide <>
metavar "NAME" <>
help "Docker container name")
<*> argsOption (long (dockerOptName dockerRunArgsArgName) <>
hide <>
value [] <>
metavar "'ARG1 [ARG2 ...]'" <>
help "Additional options to pass to 'docker run'")
<*> many (option auto (long (dockerOptName dockerMountArgName) <>
hide <>
metavar "(PATH | HOST-PATH:CONTAINER-PATH)" <>
help ("Mount volumes from host in container " ++
"(may specify multiple times)")))
<*> many (option str (long (dockerOptName dockerEnvArgName) <>
hide <>
metavar "NAME=VALUE" <>
help ("Set environment variable in container " ++
"(may specify multiple times)")))
<*> maybeStrOption (long (dockerOptName dockerDatabasePathArgName) <>
hide <>
metavar "PATH" <>
help "Location of image usage tracking database")
<*> maybeStrOption
(long(dockerOptName dockerStackExeArgName) <>
hide <>
metavar (intercalate "|"
[ dockerStackExeDownloadVal
, dockerStackExeHostVal
, dockerStackExeImageVal
, "PATH" ]) <>
help (concat [ "Location of "
, stackProgName
, " executable used in container" ]))
<*> maybeBoolFlags (dockerOptName dockerSetUserArgName)
"setting user in container to match host"
hide
<*> pure anyVersion
where
dockerOptName optName = dockerCmdName ++ "-" ++ T.unpack optName
maybeStrOption = optional . option str
hide = hideMods hide0
-- | Parser for docker cleanup arguments.
dockerCleanupOptsParser :: Parser Docker.CleanupOpts
dockerCleanupOptsParser =
Docker.CleanupOpts <$>
(flag' Docker.CleanupInteractive
(short 'i' <>
long "interactive" <>
help "Show cleanup plan in editor and allow changes (default)") <|>
flag' Docker.CleanupImmediate
(short 'y' <>
long "immediate" <>
help "Immediately execute cleanup plan") <|>
flag' Docker.CleanupDryRun
(short 'n' <>
long "dry-run" <>
help "Display cleanup plan but do not execute") <|>
pure Docker.CleanupInteractive) <*>
opt (Just 14) "known-images" "LAST-USED" <*>
opt Nothing "unknown-images" "CREATED" <*>
opt (Just 0) "dangling-images" "CREATED" <*>
opt Nothing "stopped-containers" "CREATED" <*>
opt Nothing "running-containers" "CREATED"
where opt def' name mv =
fmap Just
(option auto
(long name <>
metavar (mv ++ "-DAYS-AGO") <>
help ("Remove " ++
toDescr name ++
" " ++
map toLower (toDescr mv) ++
" N days ago" ++
case def' of
Just n -> " (default " ++ show n ++ ")"
Nothing -> ""))) <|>
flag' Nothing
(long ("no-" ++ name) <>
help ("Do not remove " ++
toDescr name ++
case def' of
Just _ -> ""
Nothing -> " (default)")) <|>
pure def'
toDescr = map (\c -> if c == '-' then ' ' else c)
-- | Parser for arguments to `stack dot`
dotOptsParser :: Parser DotOpts
dotOptsParser = DotOpts
<$> includeExternal
<*> includeBase
<*> depthLimit
<*> fmap (maybe Set.empty Set.fromList . fmap splitNames) prunedPkgs
where includeExternal = boolFlags False
"external"
"inclusion of external dependencies"
idm
includeBase = boolFlags True
"include-base"
"inclusion of dependencies on base"
idm
depthLimit =
optional (option auto
(long "depth" <>
metavar "DEPTH" <>
help ("Limit the depth of dependency resolution " <>
"(Default: No limit)")))
prunedPkgs = optional (strOption
(long "prune" <>
metavar "PACKAGES" <>
help ("Prune each package name " <>
"from the comma separated list " <>
"of package names PACKAGES")))
splitNames :: String -> [String]
splitNames = map (takeWhile (not . isSpace) . dropWhile isSpace) . splitOn ","
ghciOptsParser :: Parser GhciOpts
ghciOptsParser = GhciOpts
<$> switch (long "no-build" <> help "Don't build before launching GHCi")
<*> fmap concat (many (argsOption (long "ghci-options" <>
metavar "OPTION" <>
help "Additional options passed to GHCi")))
<*> optional
(strOption (long "with-ghc" <>
metavar "GHC" <>
help "Use this GHC to run GHCi"))
<*> (not <$> boolFlags True "load" "load modules on start-up" idm)
<*> packagesParser
<*> optional
(textOption
(long "main-is" <>
metavar "TARGET" <>
help "Specify which target should contain the main \
\module to load, such as for an executable for \
\test suite or benchmark."))
<*> switch (long "load-local-deps" <> help "Load all local dependencies of your targets")
<*> switch (long "skip-intermediate-deps" <> help "Skip loading intermediate target dependencies")
<*> boolFlags True "package-hiding" "package hiding" idm
<*> buildOptsParser Build
-- | Parser for exec command
execOptsParser :: Maybe SpecialExecCmd -> Parser ExecOpts
execOptsParser mcmd =
ExecOpts
<$> maybe eoCmdParser pure mcmd
<*> eoArgsParser
<*> execOptsExtraParser
where
eoCmdParser = ExecCmd <$> strArgument (metavar "CMD")
eoArgsParser = many (strArgument (metavar "-- ARGS (e.g. stack ghc -- X.hs -o x)"))
evalOptsParser :: String -- ^ metavar
-> Parser EvalOpts
evalOptsParser meta =
EvalOpts
<$> eoArgsParser
<*> execOptsExtraParser
where
eoArgsParser :: Parser String
eoArgsParser = strArgument (metavar meta)
-- | Parser for extra options to exec command
execOptsExtraParser :: Parser ExecOptsExtra
execOptsExtraParser = eoPlainParser <|>
ExecOptsEmbellished
<$> eoEnvSettingsParser
<*> eoPackagesParser
where
eoEnvSettingsParser :: Parser EnvSettings
eoEnvSettingsParser = EnvSettings
<$> pure True
<*> boolFlags True
"ghc-package-path"
"setting the GHC_PACKAGE_PATH variable for the subprocess"
idm
<*> boolFlags True
"stack-exe"
"setting the STACK_EXE environment variable to the path for the stack executable"
idm
<*> pure False
eoPackagesParser :: Parser [String]
eoPackagesParser = many (strOption (long "package" <> help "Additional packages that must be installed"))
eoPlainParser :: Parser ExecOptsExtra
eoPlainParser = flag' ExecOptsPlain
(long "plain" <>
help "Use an unmodified environment (only useful with Docker)")
-- | Parser for global command-line options.
globalOptsParser :: GlobalOptsContext -> Maybe LogLevel -> Parser GlobalOptsMonoid
globalOptsParser kind defLogLevel =
GlobalOptsMonoid <$>
optional (strOption (long Docker.reExecArgName <> hidden <> internal)) <*>
optional (option auto (long dockerEntrypointArgName <> hidden <> internal)) <*>
logLevelOptsParser hide0 defLogLevel <*>
configOptsParser hide0 <*>
optional (abstractResolverOptsParser hide0) <*>
optional (compilerOptsParser hide0) <*>
maybeBoolFlags
"terminal"
"overriding terminal detection in the case of running in a false terminal"
hide <*>
optional (strOption (long "stack-yaml" <>
metavar "STACK-YAML" <>
help ("Override project stack.yaml file " <>
"(overrides any STACK_YAML environment variable)") <>
hide))
where
hide = hideMods hide0
hide0 = kind /= OuterGlobalOpts
-- | Create GlobalOpts from GlobalOptsMonoid.
globalOptsFromMonoid :: Bool -> GlobalOptsMonoid -> GlobalOpts
globalOptsFromMonoid defaultTerminal GlobalOptsMonoid{..} = GlobalOpts
{ globalReExecVersion = globalMonoidReExecVersion
, globalDockerEntrypoint = globalMonoidDockerEntrypoint
, globalLogLevel = fromMaybe defaultLogLevel globalMonoidLogLevel
, globalConfigMonoid = globalMonoidConfigMonoid
, globalResolver = globalMonoidResolver
, globalCompiler = globalMonoidCompiler
, globalTerminal = fromMaybe defaultTerminal globalMonoidTerminal
, globalStackYaml = globalMonoidStackYaml }
initOptsParser :: Parser InitOpts
initOptsParser =
InitOpts <$> searchDirs
<*> solver <*> omitPackages
<*> overwrite <*> fmap not ignoreSubDirs
where
searchDirs =
many (textArgument
(metavar "DIRS" <>
help "Directories to include, default is current directory."))
ignoreSubDirs = switch (long "ignore-subdirs" <>
help "Do not search for .cabal files in sub directories")
overwrite = switch (long "force" <>
help "Force overwriting an existing stack.yaml")
omitPackages = switch (long "omit-packages" <>
help "Exclude conflicting or incompatible user packages")
solver = switch (long "solver" <>
help "Use a dependency solver to determine extra dependencies")
-- | Parser for a logging level.
logLevelOptsParser :: Bool -> Maybe LogLevel -> Parser (Maybe LogLevel)
logLevelOptsParser hide defLogLevel =
fmap (Just . parse)
(strOption (long "verbosity" <>
metavar "VERBOSITY" <>
help "Verbosity: silent, error, warn, info, debug" <>
hideMods hide)) <|>
flag' (Just verboseLevel)
(short 'v' <> long "verbose" <>
help ("Enable verbose mode: verbosity level \"" <> showLevel verboseLevel <> "\"") <>
hideMods hide) <|>
pure defLogLevel
where verboseLevel = LevelDebug
showLevel l =
case l of
LevelDebug -> "debug"
LevelInfo -> "info"
LevelWarn -> "warn"
LevelError -> "error"
LevelOther x -> T.unpack x
parse s =
case s of
"debug" -> LevelDebug
"info" -> LevelInfo
"warn" -> LevelWarn
"error" -> LevelError
_ -> LevelOther (T.pack s)
-- | Parser for the resolver
abstractResolverOptsParser :: Bool -> Parser AbstractResolver
abstractResolverOptsParser hide =
option readAbstractResolver
(long "resolver" <>
metavar "RESOLVER" <>
help "Override resolver in project file" <>
hideMods hide)
readAbstractResolver :: ReadM AbstractResolver
readAbstractResolver = do
s <- readerAsk
case s of
"global" -> return ARGlobal
"nightly" -> return ARLatestNightly
"lts" -> return ARLatestLTS
'l':'t':'s':'-':x | Right (x', "") <- decimal $ T.pack x ->
return $ ARLatestLTSMajor x'
_ ->
case parseResolverText $ T.pack s of
Left e -> readerError $ show e
Right x -> return $ ARResolver x
compilerOptsParser :: Bool -> Parser CompilerVersion
compilerOptsParser hide =
option readCompilerVersion
(long "compiler" <>
metavar "COMPILER" <>
help "Use the specified compiler" <>
hideMods hide)
readCompilerVersion :: ReadM CompilerVersion
readCompilerVersion = do
s <- readerAsk
case parseCompilerVersion (T.pack s) of
Nothing -> readerError $ "Failed to parse compiler: " ++ s
Just x -> return x
-- | GHC variant parser
ghcVariantParser :: Bool -> Parser GHCVariant
ghcVariantParser hide =
option
readGHCVariant
(long "ghc-variant" <> metavar "VARIANT" <>
help
"Specialized GHC variant, e.g. integersimple (implies --no-system-ghc)" <>
hideMods hide
)
where
readGHCVariant = do
s <- readerAsk
case parseGHCVariant s of
Left e -> readerError (show e)
Right v -> return v
-- | Parser for @solverCmd@
solverOptsParser :: Parser Bool
solverOptsParser = boolFlags False
"update-config"
"Automatically update stack.yaml with the solver's recommendations"
idm
-- | Parser for test arguments.
testOptsParser :: Parser TestOpts
testOptsParser = TestOpts
<$> boolFlags True
"rerun-tests"
"running already successful tests"
idm
<*> fmap (fromMaybe [])
(optional (argsOption(long "test-arguments" <>
metavar "TEST_ARGS" <>
help "Arguments passed in to the test suite program")))
<*> switch (long "coverage" <>
help "Generate a code coverage report")
<*> switch (long "no-run-tests" <>
help "Disable running of tests. (Tests will still be built.)")
-- | Parser for @stack new@.
newOptsParser :: Parser (NewOpts,InitOpts)
newOptsParser = (,) <$> newOpts <*> initOptsParser
where
newOpts =
NewOpts <$>
packageNameArgument
(metavar "PACKAGE_NAME" <> help "A valid package name.") <*>
switch
(long "bare" <>
help "Do not create a subdirectory for the project") <*>
optional (templateNameArgument
(metavar "TEMPLATE_NAME" <>
help "Name of a template or a local template in a file or a URL.\
\ For example: foo or foo.hsfiles or ~/foo or\
\ https://example.com/foo.hsfiles")) <*>
fmap
M.fromList
(many
(templateParamArgument
(short 'p' <> long "param" <> metavar "KEY:VALUE" <>
help
"Parameter for the template in the format key:value")))
-- | Parser for @stack hpc report@.
hpcReportOptsParser :: Parser HpcReportOpts
hpcReportOptsParser = HpcReportOpts
<$> many (textArgument $ metavar "TARGET_OR_TIX")
<*> switch (long "all" <> help "Use results from all packages and components")
<*> optional (strOption (long "destdir" <> help "Output directy for HTML report"))
pvpBoundsOption :: Parser PvpBounds
pvpBoundsOption =
option
readPvpBounds
(long "pvp-bounds" <> metavar "PVP-BOUNDS" <>
help
"How PVP version bounds should be added to .cabal file: none, lower, upper, both")
where
readPvpBounds = do
s <- readerAsk
case parsePvpBounds $ T.pack s of
Left e ->
readerError e
Right v ->
return v
configCmdSetParser :: Parser ConfigCmdSet
configCmdSetParser =
fromM
(do field <-
oneM
(strArgument
(metavar "FIELD VALUE"))
oneM (fieldToValParser field))
where
fieldToValParser :: String -> Parser ConfigCmdSet
fieldToValParser s =
case s of
"resolver" ->
ConfigCmdSetResolver <$>
argument
readAbstractResolver
idm
_ ->
error "parse stack config set field: only set resolver is implemented"
-- | If argument is True, hides the option from usage and help
hideMods :: Bool -> Mod f a
hideMods hide = if hide then internal <> hidden else idm
| harendra-kumar/stack | src/Stack/Options.hs | bsd-3-clause | 35,432 | 0 | 32 | 13,778 | 6,190 | 3,087 | 3,103 | 764 | 9 |
{-# LANGUAGE OverloadedStrings #-}
module PerformanceTextTest (doText) where
import qualified Data.List as L
import qualified Data.Vector as V
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Data.Monoid
import Debug.Trace
import Lib
type Token = (TokenSpan, T.Text)
type Acc = ((Int, Int), T.Text)
f :: (Int, [Int]) -> Char -> (Int, [Int])
f (offset, xs) c = case c of
'\n' -> (offset + 1, offset + 1 : xs)
_ -> (offset + 1, xs)
doText :: T.Text -> [Token] -> T.Text
doText src ts =
let ls = V.fromList $ L.reverse $ snd $ T.foldl' f (-1, [-1]) src
result = L.foldl' (foldText ls src) ((1, 1), T.empty) ts
lastOff = toOffset ls (fst result)
end = T.drop (lastOff + 1) src
in
snd result <> end
foldText :: V.Vector Int -> T.Text -> Acc -> Token -> Acc
foldText ls src ((l, c), src') ((Pos l1 c1, Pos l2 c2), token) =
let
ws = substrText src ls (l, c) 1 (l1, c1) 0
lexeme = substrText src ls (l1, c1) 0 (l2, c2) 1
in
-- ((l2, c2), (T.append (T.append (T.append (T.append (T.append (T.append src' ws) ":") token) ":") lexeme) ":"))
((l2, c2), src' <> ws <> ":" <> token <> ":" <> lexeme <> ":")
| clojj/haskell-view | test/PerformanceTextTest.hs | bsd-3-clause | 1,252 | 0 | 13 | 344 | 517 | 294 | 223 | 28 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Examples.Basics.QRem
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Testing the sQuotRem and sDivMod
-----------------------------------------------------------------------------
module Examples.Basics.QRem where
import Data.SBV
-- check: if (a, b) = x `quotRem` y then x = y*a + b
-- same is also true for divMod
-- being careful about y = 0. When divisor is 0, then quotient is
-- defined to be 0 and the remainder is the numerator
qrem :: (Num a, EqSymbolic a, SDivisible a) => a -> a -> SBool
qrem x y = ite (y .== 0)
((0, x) .== (q, r) &&& (0, x) .== (d, m))
(x .== y * q + r &&& x .== y * d + m)
where (q, r) = x `sQuotRem` y
(d, m) = x `sDivMod` y
check :: IO ()
check = do print =<< prove (qrem :: SWord8 -> SWord8 -> SBool)
print =<< prove (qrem :: SInt8 -> SInt8 -> SBool)
print =<< prove (qrem :: SInteger -> SInteger -> SBool)
| Copilot-Language/sbv-for-copilot | SBVUnitTest/Examples/Basics/QRem.hs | bsd-3-clause | 1,099 | 0 | 13 | 278 | 279 | 159 | 120 | 12 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Network.HTTP.Dispatch where
import Network.HTTP.Dispatch.Types
import Network.HTTP.Dispatch.Request
import Network.HTTP.Dispatch.Core
| owainlewis/http-dispatch | src/Network/HTTP/Dispatch.hs | bsd-3-clause | 177 | 0 | 4 | 14 | 29 | 21 | 8 | 5 | 0 |
-- | Download and import feeds from various sources.
module HN.Model.Feeds where
import HN.Data
import HN.Monads
import HN.Model.Items
import HN.Types
import HN.Curl
import Control.Applicative
import Network.URI
import Snap.App
import System.Locale
import Text.Feed.Import
import Text.Feed.Query
import Text.Feed.Types
--------------------------------------------------------------------------------
-- Various service feeds
importHaskellCafe = do
importGenerically HaskellCafe
"https://groups.google.com/forum/feed/haskell-cafe/msgs/rss_v2_0.xml"
(\item -> return (item { niTitle = strip (niTitle item) }))
where strip x | isPrefixOf "re: " (map toLower x) = strip (drop 4 x)
| isPrefixOf label x = drop (length label) x
| otherwise = x
label = "[Haskell-cafe]"
importPlanetHaskell =
importGeneric PlanetHaskell "http://planet.haskell.org/rss20.xml"
importJobs =
importGeneric Jobs "http://www.haskellers.com/feed/jobs"
importStackOverflow = do
importGeneric StackOverflow "http://stackoverflow.com/feeds/tag/haskell"
importGeneric StackOverflow "http://programmers.stackexchange.com/feeds/tag/haskell"
importGeneric StackOverflow "http://codereview.stackexchange.com/feeds/tag/haskell"
importHaskellWiki =
importGeneric HaskellWiki "http://www.haskell.org/haskellwiki/index.php?title=Special:RecentChanges&feed=rss"
importHackage =
importGeneric Hackage "http://hackage.haskell.org/packages/recent.rss"
-- Old feed is gone:
-- importGeneric Hackage "http://hackage.haskell.org/recent.rss"
-- Old feed is gone:
-- importGeneric Hackage "http://hackage.haskell.org/packages/archive/recent.rss"
-- | Import all vimeo content.
importVimeo = do
importGeneric Vimeo "http://vimeo.com/channels/haskell/videos/rss"
importGeneric Vimeo "http://vimeo.com/channels/galois/videos/rss"
importGenerically Vimeo
"http://vimeo.com/rickasaurus/videos/rss"
(\ni -> if isInfixOf "haskell" (map toLower (niTitle ni)) then return ni else Nothing)
-- | Import @remember'd IRC quotes from ircbrowse.
importIrcQuotes = do
importGeneric IrcQuotes
"http://ircbrowse.net/quotes.rss"
-- | Import pastes about Haskell.
importPastes = do
importGeneric Pastes
"http://lpaste.net/channel/haskell/rss"
--------------------------------------------------------------------------------
-- Reddit
-- | Get /r/haskell.
importRedditHaskell = do
result <- io $ getReddit "haskell"
case result of
Left e -> return (Left e)
Right items -> do
mapM_ (addItem Reddit) items
return (Right ())
-- | Import from proggit.
importProggit = do
result <- io $ getReddit "programming"
case result of
Left e -> return (Left e)
Right items -> do
mapM_ (addItem Reddit) (filter (hasHaskell . niTitle) items)
return (Right ())
where hasHaskell = isInfixOf "haskell" . map toLower
-- | Get Reddit feed.
getReddit subreddit = do
result <- downloadFeed ("http://www.reddit.com/r/" ++ subreddit ++ "/.rss")
case result of
Left e -> return (Left e)
Right e -> return (mapM makeItem (feedItems e))
--------------------------------------------------------------------------------
-- Get feeds
-- | Import from a generic feed source.
importGeneric :: Source -> String -> Model c s (Either String ())
importGeneric source uri = do
importGenerically source uri return
-- | Import from a generic feed source.
importGenerically :: Source -> String -> (NewItem -> Maybe NewItem) -> Model c s (Either String ())
importGenerically source uri f = do
result <- io $ downloadFeed uri
case result >>= mapM (fmap f . makeItem) . feedItems of
Left e -> do
return (Left e)
Right items -> do
mapM_ (addItem source) (catMaybes items)
return (Right ())
-- | Make an item from a feed item.
makeItem :: Item -> Either String NewItem
makeItem item =
NewItem <$> extract "item" (getItemTitle item)
<*> extract "publish date" (join (getItemPublishDate item))
<*> extract "description" (getItemDescription item)
<*> extract "link" (getItemLink item >>= parseURILeniently)
where extract label = maybe (Left ("Unable to extract " ++ label)) Right
-- | Escape any characters not allowed in URIs because at least one
-- feed (I'm looking at you, reddit) do not escape characters like ö.
parseURILeniently :: String -> Maybe URI
parseURILeniently = parseURI . escapeURIString isAllowedInURI
-- | Download and parse a feed.
downloadFeed :: String -> IO (Either String Feed)
downloadFeed uri = do
result <- downloadString uri
case result of
Left e -> return (Left (show e))
Right str -> case parseFeedString str of
Nothing -> do
writeFile "/tmp/feed.xml" str
return (Left ("Unable to parse feed from: " ++ uri))
Just feed -> return (Right feed)
--------------------------------------------------------------------------------
-- Utilities
-- | Parse one of the two dates that might occur out there.
parseDate x = parseRFC822 x <|> parseRFC3339 x
-- | Parse an RFC 3339 timestamp.
parseRFC3339 :: String -> Maybe ZonedTime
parseRFC3339 = parseTime defaultTimeLocale "%Y-%m-%dT%TZ"
-- | Parse an RFC 822 timestamp.
parseRFC822 :: String -> Maybe ZonedTime
parseRFC822 = parseTime defaultTimeLocale rfc822DateFormat
| erantapaa/haskellnews | src/HN/Model/Feeds.hs | bsd-3-clause | 5,374 | 3 | 19 | 984 | 1,216 | 598 | 618 | 101 | 3 |
module Scene.World where
-- friends
import Vec3
import Scene.Light
import Scene.Object
-- frenemies
import Data.Array.Accelerate as A
import Graphics.Gloss.Accelerate.Data.Color.RGB
makeLights :: Float -> Lights
makeLights _time
= A.fromList (Z :. 1) [ Light (XYZ 300 (-300) (-100))
(RGB 150000 150000 150000)
]
makeObjects :: Float -> Objects
makeObjects time
= let
spheres = A.fromList (Z :. 4)
[ Sphere (XYZ (40 * sin time) 80 0.0)
20
(RGB 1.0 0.3 1.0)
0.4
, Sphere (XYZ (200 * sin time) (-40 * sin (time + pi/2)) (200 * cos time))
100.0
(RGB 0.4 0.4 1.0)
0.8
, Sphere (XYZ (-200.0 * sin time) (-40 * sin (time - pi/2)) (-200 * cos time))
100.0
(RGB 0.4 0.4 1.0)
0.5
, Sphere (XYZ 0.0 (-150.0) (-100.0))
50.0
(RGB 1.0 1.0 1.0)
0.8
]
planes = A.fromList (Z :. 1)
[ Plane (XYZ 0.0 100.0 0.0)
(XYZ 0.0 (-0.9805807) (-0.19611613))
(RGB 1.0 1.0 1.0)
0.2
]
in
(spheres, planes)
| tmcdonell/accelerate-ray | Scene/World.hs | bsd-3-clause | 1,357 | 0 | 19 | 638 | 464 | 246 | 218 | 36 | 1 |
{-# LANGUAGE Strict #-}
module D16Lib where
import Util
curve :: Int -> String -> String
curve len = seq' $ take len . until ((>=len) . length) curveStep
curveStep :: String -> String
curveStep a = seq' $ a ++ "0" ++ b
where
b = (map swap . reverse) a
swap c = case c of
'0' -> '1'
'1' -> '0'
_ -> c
checksum :: String -> String
checksum input
| null input = error "can't calc checksum of empty str"
| odd (length input) = error "can't calc checksum of odd length str"
| otherwise = until (odd . length) cs input
where
cs str = seq' (reverse $ cs' "" str)
cs' memo (c0:c1:t) = cs' (seq' nextMemo) t
where
nextChar = if c0 == c1 then '1' else '0'
nextMemo = nextChar : memo
cs' memo [] = memo
| wfleming/advent-of-code-2016 | 2016/src/D16Lib.hs | bsd-3-clause | 778 | 0 | 10 | 232 | 305 | 154 | 151 | 22 | 3 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
module High.Category.Semigroupal where
import High.Functor.Bifunctor (Bifunctor)
import High.Isomorphism (Isomorphism)
data Semigroupal :: ((* -> *) -> (* -> *) -> *) -> ((* -> *) -> (* -> *) -> (* -> *)) -> * where
Semigroupal ::
{ tensor_product :: Bifunctor cat cat cat pro
, associator :: (forall f g h. Isomorphism cat (pro (pro f g) h) (pro f (pro g h)))
} -> Semigroupal cat pro
| Hexirp/untypeclass | src/High/Category/Semigroupal.hs | bsd-3-clause | 534 | 0 | 14 | 116 | 187 | 108 | 79 | 12 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Zodiac.Cli.TSRP.Error(
TSRPError(..)
, ParamError(..)
, renderTSRPError
) where
import qualified Data.Text as T
import P
import qualified Zodiac.Raw as Z
data TSRPError =
TSRPNotImplementedError
| TSRPParamError !ParamError
| TSRPRequestError !Z.RequestError
| TSRPRequestNotVerifiedError
| TSRPVerificationError
deriving (Eq, Show)
renderTSRPError :: TSRPError -> Text
renderTSRPError TSRPNotImplementedError = "Implement me!"
renderTSRPError (TSRPParamError e) = renderParamError e
renderTSRPError (TSRPRequestError e) = Z.renderRequestError e
renderTSRPError TSRPRequestNotVerifiedError = "Request not verified (everything was successful, but the request doesn't match the signature)."
renderTSRPError TSRPVerificationError = "Verification error (unable to verify because something is malformed)."
data ParamError =
MissingRequiredParam !Text
| InvalidParam !Text !Text
deriving (Eq, Show)
renderParamError :: ParamError -> Text
renderParamError (MissingRequiredParam p) =
"missing required parameter: " <> p
renderParamError (InvalidParam var val) = T.unwords [
"invalid parameter"
, var
, ": failed to parse"
, val
]
| ambiata/zodiac | zodiac-cli/src/Zodiac/Cli/TSRP/Error.hs | bsd-3-clause | 1,264 | 0 | 8 | 207 | 245 | 137 | 108 | 44 | 1 |
module Tc.TcInst where
import qualified Data.Map as Map
import Language.Haskell.Exts
import Tc.Class
import Tc.Assumption
import Utils.Debug
-- this module implements the type instantiation
-- algorithm.
type Var = Type -- INVARIANT: Always a type variable
type InstMap = Map.Map Var Type
-- a type class for the instantiation process
class Instantiate t where
inst :: InstMap -> t -> t
instance Instantiate t => Instantiate [t] where
inst m = map (inst m)
instance Instantiate Asst where
inst m (ClassA n ts) = ClassA n (inst m ts)
inst m (InfixA l n r) = InfixA (inst m l) n (inst m r)
instance Instantiate Inst where
inst m (Inst n ts ps) = Inst n (inst m ts) (inst m ps)
instance Instantiate Class where
inst m (Class n ts ss ms is)
= Class n (inst m ts) (inst m ss) (inst m ms) (inst m is)
instance Instantiate Type where
inst m (TyForall x ctx t)
= TyForall x (inst m ctx) (inst m t)
inst m (TyFun l r)
= TyFun (inst m l) (inst m r)
inst m (TyTuple b ts)
= TyTuple b (inst m ts)
inst m (TyList t)
= TyList (inst m t)
inst m (TyParen t)
= TyParen (inst m t)
inst m (TyInfix l n r)
= TyInfix (inst m l) n (inst m r)
inst m v@(TyVar _)
= case Map.lookup v m of
Just t -> t
Nothing -> v
inst m (TyApp l r)
= TyApp (inst m l) (inst m r)
inst m t = t
instance Instantiate Assumption where
inst m (i :>: t) = i :>: (inst m t)
instantiate :: (Instantiate t) => [Var] -> [Type] -> t -> t
instantiate vs ts t = inst tymap t
where
tymap = Map.fromList (zip vs ts) | rodrigogribeiro/mptc | src/Tc/TcInst.hs | bsd-3-clause | 1,789 | 0 | 9 | 632 | 741 | 375 | 366 | 45 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE RankNTypes #-}
module Proof where
import Language.Haskell.TH
import Data.Data (Data)
import Data.Typeable (Typeable)
import Data.Maybe
import Data.Function
import Data.List
import Control.Applicative
import Control.Monad
import Data.Tuple.HT
import Test.QuickCheck hiding (Prop)
import TH
import Data.Thorn
data Prop
= Prop Type
| Arrow Prop Prop
deriving (Eq, Show, Data, Typeable)
instance Arbitrary Name where
arbitrary = mkName <$> arbitrary
instance Arbitrary Lit where
arbitrary = oneof
[ CharL <$> arbitrary
, StringL <$> arbitrary
, IntegerL <$> arbitrary
, RationalL <$> arbitrary
, IntPrimL <$> arbitrary
, WordPrimL <$> arbitrary
, FloatPrimL <$> arbitrary
, DoublePrimL <$> arbitrary
, StringPrimL <$> arbitrary
]
instance Arbitrary Type where
arbitrary = frequency
[ (,) 9 $ VarT <$> arbitrary
, (,) 9 $ ConT <$> arbitrary
, (,) 2 $ AppT ListT <$> arbitrary
, (,) 1 $ AppT <$> arbitrary <*> arbitrary
, (,) 1 $ (\ x y -> (ArrowT `AppT` x) `AppT` y) <$> arbitrary <*> arbitrary
]
instance Arbitrary Exp where
arbitrary = frequency
[ (,) 2 $ VarE <$> arbitrary
, (,) 2 $ ConE <$> arbitrary
, (,) 2 $ LitE <$> arbitrary
, (,) 1 $ AppE <$> arbitrary <*> arbitrary
]
instance Arbitrary Prop where
arbitrary = frequency
[ (,) 2 $ Prop <$> arbitrary
, (,) 1 $ Arrow <$> arbitrary <*> arbitrary
]
-- | prop> \ p q -> (p ~> q) == (p `Arrow` q)
-- prop> \ p q r -> (p ~> q ~> r) == (p ~> (q ~> r))
(~>) :: Prop -> Prop -> Prop
p ~> q = p `Arrow` q
infixr ~>
data Proof
= Proof Exp
| Apply Proof Proof
deriving (Eq, Show, Data, Typeable)
-- | prop> \ p q -> (p ~$ q) == (p `Apply` q)
-- prop> \ p q r -> (p ~$ q ~$ r) == (p ~$ (q ~$ r))
(~$) :: Proof -> Proof -> Proof
p ~$ q = p `Apply` q
infixr ~$
instance Arbitrary Proof where
arbitrary = frequency
[ (,) 2 $ Proof <$> arbitrary
, (,) 1 $ Apply <$> arbitrary <*> arbitrary
]
catamorphism ''Prop "foldProp"
catamorphism ''Proof "foldProof"
-- | @splitProp@ returns a list whose length is one or more.
--
-- prop> \ p -> not . null $ splitProp p
-- prop> \ t -> let p = Prop t in splitProp p == [([], p)]
--
-- prop> \ s t u -> let [p,q,r] = map Prop [s,t,u] in splitProp (p ~> q ~> r) == [([], p ~> q ~> r), ([p], q ~> r), ([p, q], r)]
-- prop> \ t ts -> let ps = map Prop (t:ts) in length (splitProp (foldr1 (~>) ps)) == length ps
splitProp :: Prop -> [([Prop], Prop)]
splitProp = nub . f where
f p@(Prop _) = [([], p)]
f r@(Arrow p q) = ([], r) : ([p], q) : map (mapFst (p :)) (f q)
-- | prop> \ p -> not . null $ conclusions p
conclusions :: Prop -> [Prop]
conclusions = nub . map snd . splitProp
{-
unTupleName :: Name -> Maybe Int
unTupleName a = f $ nameBase a where
f ('(' : xs) = g 0 xs
f _ = Nothing
g n ")" = Just n
g n (',' : xs) = g (n+1) xs
g _ _ = Nothing
propToType :: Prop -> Type
propToType (App a b) = (AppT `on` propToType) a b
propToType (Var a) = VarT a
propToType Arrow = ArrowT
propToType (Con a)
= if a == ''[] then ListT
else case unTupleName a of
Just n -> TupleT n
Nothing -> ConT a
proveQ :: [Name] -> Prop -> Q Prop
proveQ hypos targ = do
hypos' <- (`sequence` hypos) $ \ hypo -> do
info <- reify hypo
case info of
(TyConI (DataD ctxt name)) ->
(DataConI _ typ _ _) -> (hypo, typ)
(VarI _ typ _ _) -> (hypo, typ)
_ -> fail $ "not supported name: " ++ show hypo
-- -}
| kmyk/proof-haskell | Proof.hs | mit | 3,841 | 0 | 15 | 1,166 | 841 | 468 | 373 | 73 | 2 |
{-# LANGUAGE OverloadedStrings, TypeFamilies #-}
{- |
Module : Routes.ContentTypes
Copyright : (c) Anupam Jain 2013
License : MIT (see the file LICENSE)
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (uses ghc extensions)
Defines the commonly used content types
-}
module Routes.ContentTypes
( -- * Construct content Type
acceptContentType
, contentType, contentTypeFromFile
-- * Various common content types
, typeAll
, typeHtml, typePlain, typeJson
, typeXml, typeAtom, typeRss
, typeJpeg, typePng, typeGif
, typeSvg, typeJavascript, typeCss
, typeFlv, typeOgv, typeOctet
)
where
import qualified Data.Text as T (pack)
import Data.ByteString (ByteString)
import Data.ByteString.Char8 () -- Import IsString instance for ByteString
import Network.HTTP.Types.Header (HeaderName())
import Network.Mime (defaultMimeLookup)
import System.FilePath (takeFileName)
-- | The request header for accpetable content types
acceptContentType :: HeaderName
acceptContentType = "Accept"
-- | Construct an appropriate content type header from a file name
contentTypeFromFile :: FilePath -> ByteString
contentTypeFromFile = defaultMimeLookup . T.pack . takeFileName
-- | Creates a content type header
-- Ready to be passed to `responseLBS`
contentType :: HeaderName
contentType = "Content-Type"
typeAll :: ByteString
typeAll = "*/*"
typeHtml :: ByteString
typeHtml = "text/html; charset=utf-8"
typePlain :: ByteString
typePlain = "text/plain; charset=utf-8"
typeJson :: ByteString
typeJson = "application/json; charset=utf-8"
typeXml :: ByteString
typeXml = "text/xml"
typeAtom :: ByteString
typeAtom = "application/atom+xml"
typeRss :: ByteString
typeRss = "application/rss+xml"
typeJpeg :: ByteString
typeJpeg = "image/jpeg"
typePng :: ByteString
typePng = "image/png"
typeGif :: ByteString
typeGif = "image/gif"
typeSvg :: ByteString
typeSvg = "image/svg+xml"
typeJavascript :: ByteString
typeJavascript = "text/javascript; charset=utf-8"
typeCss :: ByteString
typeCss = "text/css; charset=utf-8"
typeFlv :: ByteString
typeFlv = "video/x-flv"
typeOgv :: ByteString
typeOgv = "video/ogg"
typeOctet :: ByteString
typeOctet = "application/octet-stream"
| ajnsit/snap-routes | src/Routes/ContentTypes.hs | mit | 2,266 | 0 | 7 | 366 | 345 | 216 | 129 | 55 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-
Copyright (C) 2010 John MacFarlane <[email protected]>
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(-1)307 USA
-}
{- |
Module : Text.Pandoc.Pretty
Copyright : Copyright (C) 2010 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
A prettyprinting library for the production of text documents,
including wrapped text, indentated blocks, and tables.
-}
module Text.Pandoc.Pretty (
Doc
, render
, cr
, blankline
, space
, text
, char
, prefixed
, flush
, nest
, hang
, beforeNonBlank
, nowrap
, offset
, height
, lblock
, cblock
, rblock
, (<>)
, (<+>)
, ($$)
, ($+$)
, isEmpty
, empty
, cat
, hcat
, hsep
, vcat
, vsep
, chomp
, inside
, braces
, brackets
, parens
, quotes
, doubleQuotes
, charWidth
, realLength
)
where
import Data.DList (DList, fromList, toList, cons, singleton)
import Data.List (intercalate)
import Data.Monoid
import Data.String
import Control.Monad.State
import Data.Char (isSpace)
data Monoid a =>
RenderState a = RenderState{
output :: [a] -- ^ In reverse order
, prefix :: String
, usePrefix :: Bool
, lineLength :: Maybe Int -- ^ 'Nothing' means no wrapping
, column :: Int
, newlines :: Int -- ^ Number of preceding newlines
}
type DocState a = State (RenderState a) ()
data D = Text Int String
| Block Int [String]
| Prefixed String Doc
| BeforeNonBlank Doc
| Flush Doc
| BreakingSpace
| CarriageReturn
| NewLine
| BlankLine
deriving (Show)
newtype Doc = Doc { unDoc :: DList D }
deriving (Monoid)
instance Show Doc where
show = render Nothing
instance IsString Doc where
fromString = text
isBlank :: D -> Bool
isBlank BreakingSpace = True
isBlank CarriageReturn = True
isBlank NewLine = True
isBlank BlankLine = True
isBlank (Text _ (c:_)) = isSpace c
isBlank _ = False
-- | True if the document is empty.
isEmpty :: Doc -> Bool
isEmpty = null . toList . unDoc
-- | The empty document.
empty :: Doc
empty = mempty
-- | @a <> b@ is the result of concatenating @a@ with @b@.
(<>) :: Doc -> Doc -> Doc
(<>) = mappend
-- | Concatenate a list of 'Doc's.
cat :: [Doc] -> Doc
cat = mconcat
-- | Same as 'cat'.
hcat :: [Doc] -> Doc
hcat = mconcat
-- | Concatenate a list of 'Doc's, putting breakable spaces
-- between them.
(<+>) :: Doc -> Doc -> Doc
(<+>) x y = if isEmpty x
then y
else if isEmpty y
then x
else x <> space <> y
-- | Same as 'cat', but putting breakable spaces between the
-- 'Doc's.
hsep :: [Doc] -> Doc
hsep = foldr (<+>) empty
-- | @a $$ b@ puts @a@ above @b@.
($$) :: Doc -> Doc -> Doc
($$) x y = if isEmpty x
then y
else if isEmpty y
then x
else x <> cr <> y
-- | @a $$ b@ puts @a@ above @b@, with a blank line between.
($+$) :: Doc -> Doc -> Doc
($+$) x y = if isEmpty x
then y
else if isEmpty y
then x
else x <> blankline <> y
-- | List version of '$$'.
vcat :: [Doc] -> Doc
vcat = foldr ($$) empty
-- | List version of '$+$'.
vsep :: [Doc] -> Doc
vsep = foldr ($+$) empty
-- | Chomps trailing blank space off of a 'Doc'.
chomp :: Doc -> Doc
chomp d = Doc (fromList dl')
where dl = toList (unDoc d)
dl' = reverse $ dropWhile removeable $ reverse dl
removeable BreakingSpace = True
removeable CarriageReturn = True
removeable NewLine = True
removeable BlankLine = True
removeable _ = False
outp :: (IsString a, Monoid a)
=> Int -> String -> DocState a
outp off s | off <= 0 = do
st' <- get
let rawpref = prefix st'
when (column st' == 0 && usePrefix st' && not (null rawpref)) $ do
let pref = reverse $ dropWhile isSpace $ reverse rawpref
modify $ \st -> st{ output = fromString pref : output st
, column = column st + realLength pref }
when (off < 0) $ do
modify $ \st -> st { output = fromString s : output st
, column = 0
, newlines = newlines st + 1 }
outp off s = do
st' <- get
let pref = prefix st'
when (column st' == 0 && usePrefix st' && not (null pref)) $ do
modify $ \st -> st{ output = fromString pref : output st
, column = column st + realLength pref }
modify $ \st -> st{ output = fromString s : output st
, column = column st + off
, newlines = 0 }
-- | Renders a 'Doc'. @render (Just n)@ will use
-- a line length of @n@ to reflow text on breakable spaces.
-- @render Nothing@ will not reflow text.
render :: (Monoid a, IsString a)
=> Maybe Int -> Doc -> a
render linelen doc = fromString . mconcat . reverse . output $
execState (renderDoc doc) startingState
where startingState = RenderState{
output = mempty
, prefix = ""
, usePrefix = True
, lineLength = linelen
, column = 0
, newlines = 2 }
renderDoc :: (IsString a, Monoid a)
=> Doc -> DocState a
renderDoc = renderList . toList . unDoc
renderList :: (IsString a, Monoid a)
=> [D] -> DocState a
renderList [] = return ()
renderList (Text off s : xs) = do
outp off s
renderList xs
renderList (Prefixed pref d : xs) = do
st <- get
let oldPref = prefix st
put st{ prefix = prefix st ++ pref }
renderDoc d
modify $ \s -> s{ prefix = oldPref }
renderList xs
renderList (Flush d : xs) = do
st <- get
let oldUsePrefix = usePrefix st
put st{ usePrefix = False }
renderDoc d
modify $ \s -> s{ usePrefix = oldUsePrefix }
renderList xs
renderList (BeforeNonBlank d : xs) =
case xs of
(x:_) | isBlank x -> renderList xs
| otherwise -> renderDoc d >> renderList xs
[] -> renderList xs
renderList (BlankLine : xs) = do
st <- get
case output st of
_ | newlines st > 1 || null xs -> return ()
_ | column st == 0 -> do
outp (-1) "\n"
_ -> do
outp (-1) "\n"
outp (-1) "\n"
renderList xs
renderList (CarriageReturn : xs) = do
st <- get
if newlines st > 0 || null xs
then renderList xs
else do
outp (-1) "\n"
renderList xs
renderList (NewLine : xs) = do
outp (-1) "\n"
renderList xs
renderList (BreakingSpace : CarriageReturn : xs) = renderList (CarriageReturn:xs)
renderList (BreakingSpace : NewLine : xs) = renderList (NewLine:xs)
renderList (BreakingSpace : BlankLine : xs) = renderList (BlankLine:xs)
renderList (BreakingSpace : BreakingSpace : xs) = renderList (BreakingSpace:xs)
renderList (BreakingSpace : xs) = do
let isText (Text _ _) = True
isText (Block _ _) = True
isText _ = False
let isBreakingSpace BreakingSpace = True
isBreakingSpace _ = False
let xs' = dropWhile isBreakingSpace xs
let next = takeWhile isText xs'
st <- get
let off = sum $ map offsetOf next
case lineLength st of
Just l | column st + 1 + off > l -> do
outp (-1) "\n"
renderList xs'
_ -> do
outp 1 " "
renderList xs'
renderList (b1@Block{} : b2@Block{} : xs) =
renderList (mergeBlocks False b1 b2 : xs)
renderList (b1@Block{} : BreakingSpace : b2@Block{} : xs) =
renderList (mergeBlocks True b1 b2 : xs)
renderList (Block width lns : xs) = do
st <- get
let oldPref = prefix st
case column st - realLength oldPref of
n | n > 0 -> modify $ \s -> s{ prefix = oldPref ++ replicate n ' ' }
_ -> return ()
renderDoc $ blockToDoc width lns
modify $ \s -> s{ prefix = oldPref }
renderList xs
mergeBlocks :: Bool -> D -> D -> D
mergeBlocks addSpace (Block w1 lns1) (Block w2 lns2) =
Block (w1 + w2 + if addSpace then 1 else 0) $
zipWith (\l1 l2 -> pad w1 l1 ++ l2) (lns1 ++ empties) (map sp lns2 ++ empties)
where empties = replicate (abs $ length lns1 - length lns2) ""
pad n s = s ++ replicate (n - realLength s) ' '
sp "" = ""
sp xs = if addSpace then (' ' : xs) else xs
mergeBlocks _ _ _ = error "mergeBlocks tried on non-Block!"
blockToDoc :: Int -> [String] -> Doc
blockToDoc _ lns = text $ intercalate "\n" lns
offsetOf :: D -> Int
offsetOf (Text o _) = o
offsetOf (Block w _) = w
offsetOf BreakingSpace = 1
offsetOf _ = 0
-- | A literal string.
text :: String -> Doc
text = Doc . toChunks
where toChunks :: String -> DList D
toChunks [] = mempty
toChunks s = case break (=='\n') s of
([], _:ys) -> NewLine `cons` toChunks ys
(xs, _:ys) -> Text (realLength xs) xs `cons`
NewLine `cons` toChunks ys
(xs, []) -> singleton $ Text (realLength xs) xs
-- | A character.
char :: Char -> Doc
char c = text [c]
-- | A breaking (reflowable) space.
space :: Doc
space = Doc $ singleton BreakingSpace
-- | A carriage return. Does nothing if we're at the beginning of
-- a line; otherwise inserts a newline.
cr :: Doc
cr = Doc $ singleton CarriageReturn
-- | Inserts a blank line unless one exists already.
-- (@blankline <> blankline@ has the same effect as @blankline@.
-- If you want multiple blank lines, use @text "\\n\\n"@.
blankline :: Doc
blankline = Doc $ singleton BlankLine
-- | Uses the specified string as a prefix for every line of
-- the inside document (except the first, if not at the beginning
-- of the line).
prefixed :: String -> Doc -> Doc
prefixed pref doc = Doc $ singleton $ Prefixed pref doc
-- | Makes a 'Doc' flush against the left margin.
flush :: Doc -> Doc
flush doc = Doc $ singleton $ Flush doc
-- | Indents a 'Doc' by the specified number of spaces.
nest :: Int -> Doc -> Doc
nest ind = prefixed (replicate ind ' ')
-- | A hanging indent. @hang ind start doc@ prints @start@,
-- then @doc@, leaving an indent of @ind@ spaces on every
-- line but the first.
hang :: Int -> Doc -> Doc -> Doc
hang ind start doc = start <> nest ind doc
-- | @beforeNonBlank d@ conditionally includes @d@ unless it is
-- followed by blank space.
beforeNonBlank :: Doc -> Doc
beforeNonBlank d = Doc $ singleton (BeforeNonBlank d)
-- | Makes a 'Doc' non-reflowable.
nowrap :: Doc -> Doc
nowrap doc = Doc $ fromList $ map replaceSpace $ toList $ unDoc doc
where replaceSpace BreakingSpace = Text 1 " "
replaceSpace x = x
-- | Returns the width of a 'Doc'.
offset :: Doc -> Int
offset d = case map realLength . lines . render Nothing $ d of
[] -> 0
os -> maximum os
block :: (String -> String) -> Int -> Doc -> Doc
block filler width = Doc . singleton . Block width .
map filler . chop width . render (Just width)
-- | @lblock n d@ is a block of width @n@ characters, with
-- text derived from @d@ and aligned to the left.
lblock :: Int -> Doc -> Doc
lblock = block id
-- | Like 'lblock' but aligned to the right.
rblock :: Int -> Doc -> Doc
rblock w = block (\s -> replicate (w - realLength s) ' ' ++ s) w
-- | Like 'lblock' but aligned centered.
cblock :: Int -> Doc -> Doc
cblock w = block (\s -> replicate ((w - realLength s) `div` 2) ' ' ++ s) w
-- | Returns the height of a block or other 'Doc'.
height :: Doc -> Int
height = length . lines . render Nothing
chop :: Int -> String -> [String]
chop _ [] = []
chop n cs = case break (=='\n') cs of
(xs, ys) -> if len <= n
then case ys of
[] -> [xs]
(_:[]) -> [xs, ""]
(_:zs) -> xs : chop n zs
else take n xs : chop n (drop n xs ++ ys)
where len = realLength xs
-- | Encloses a 'Doc' inside a start and end 'Doc'.
inside :: Doc -> Doc -> Doc -> Doc
inside start end contents =
start <> contents <> end
-- | Puts a 'Doc' in curly braces.
braces :: Doc -> Doc
braces = inside (char '{') (char '}')
-- | Puts a 'Doc' in square brackets.
brackets :: Doc -> Doc
brackets = inside (char '[') (char ']')
-- | Puts a 'Doc' in parentheses.
parens :: Doc -> Doc
parens = inside (char '(') (char ')')
-- | Wraps a 'Doc' in single quotes.
quotes :: Doc -> Doc
quotes = inside (char '\'') (char '\'')
-- | Wraps a 'Doc' in double quotes.
doubleQuotes :: Doc -> Doc
doubleQuotes = inside (char '"') (char '"')
-- | Returns width of a character in a monospace font: 0 for a combining
-- character, 1 for a regular character, 2 for an East Asian wide character.
charWidth :: Char -> Int
charWidth c =
case c of
_ | c < '\x0300' -> 1
| c >= '\x0300' && c <= '\x036F' -> 0 -- combining
| c >= '\x0370' && c <= '\x10FC' -> 1
| c >= '\x1100' && c <= '\x115F' -> 2
| c >= '\x1160' && c <= '\x11A2' -> 1
| c >= '\x11A3' && c <= '\x11A7' -> 2
| c >= '\x11A8' && c <= '\x11F9' -> 1
| c >= '\x11FA' && c <= '\x11FF' -> 2
| c >= '\x1200' && c <= '\x2328' -> 1
| c >= '\x2329' && c <= '\x232A' -> 2
| c >= '\x232B' && c <= '\x2E31' -> 1
| c >= '\x2E80' && c <= '\x303E' -> 2
| c == '\x303F' -> 1
| c >= '\x3041' && c <= '\x3247' -> 2
| c >= '\x3248' && c <= '\x324F' -> 1 -- ambiguous
| c >= '\x3250' && c <= '\x4DBF' -> 2
| c >= '\x4DC0' && c <= '\x4DFF' -> 1
| c >= '\x4E00' && c <= '\xA4C6' -> 2
| c >= '\xA4D0' && c <= '\xA95F' -> 1
| c >= '\xA960' && c <= '\xA97C' -> 2
| c >= '\xA980' && c <= '\xABF9' -> 1
| c >= '\xAC00' && c <= '\xD7FB' -> 2
| c >= '\xD800' && c <= '\xDFFF' -> 1
| c >= '\xE000' && c <= '\xF8FF' -> 1 -- ambiguous
| c >= '\xF900' && c <= '\xFAFF' -> 2
| c >= '\xFB00' && c <= '\xFDFD' -> 1
| c >= '\xFE00' && c <= '\xFE0F' -> 1 -- ambiguous
| c >= '\xFE10' && c <= '\xFE19' -> 2
| c >= '\xFE20' && c <= '\xFE26' -> 1
| c >= '\xFE30' && c <= '\xFE6B' -> 2
| c >= '\xFE70' && c <= '\x16A38' -> 1
| c >= '\x1B000' && c <= '\x1B001' -> 2
| c >= '\x1D000' && c <= '\x1F1FF' -> 1
| c >= '\x1F200' && c <= '\x1F251' -> 2
| c >= '\x1F300' && c <= '\x1F773' -> 1
| c >= '\x20000' && c <= '\x3FFFD' -> 2
| otherwise -> 1
-- | Get real length of string, taking into account combining and double-wide
-- characters.
realLength :: String -> Int
realLength = sum . map charWidth
| sol/pandoc | src/Text/Pandoc/Pretty.hs | gpl-2.0 | 15,859 | 0 | 16 | 5,172 | 4,872 | 2,507 | 2,365 | 363 | 10 |
module Hans.Buffer.Signal where
import Control.Concurrent (MVar,newEmptyMVar,tryPutMVar,takeMVar,tryTakeMVar)
type Signal = MVar ()
newSignal :: IO Signal
newSignal = newEmptyMVar
signal :: Signal -> IO ()
signal var =
do _ <- tryPutMVar var ()
return ()
waitSignal :: Signal -> IO ()
waitSignal = takeMVar
tryWaitSignal :: Signal -> IO Bool
tryWaitSignal var =
do mb <- tryTakeMVar var
case mb of
Just () -> return True
Nothing -> return False
| GaloisInc/HaNS | src/Hans/Buffer/Signal.hs | bsd-3-clause | 481 | 0 | 11 | 106 | 176 | 89 | 87 | 17 | 2 |
{-# OPTIONS_GHC -Wall #-}
module Reporting.Render.Code
( render
)
where
import Control.Applicative ((<|>))
import Text.PrettyPrint.ANSI.Leijen (Doc, (<>), hardline, dullred, empty, text)
import qualified Reporting.Region as R
(|>) :: a -> (a -> b) -> b
(|>) a f =
f a
(<==>) :: Doc -> Doc -> Doc
(<==>) a b =
a <> hardline <> b
render :: Maybe R.Region -> R.Region -> String -> Doc
render maybeSubRegion region@(R.Region start end) source =
let
(R.Position startLine startColumn) = start
(R.Position endLine endColumn) = end
relevantLines =
lines source
|> drop (startLine - 1)
|> take (endLine - startLine + 1)
in
case relevantLines of
[] ->
empty
[sourceLine] ->
singleLineRegion startLine sourceLine $
case maybeSubRegion of
Nothing ->
(0, startColumn, endColumn, length sourceLine)
Just (R.Region s e) ->
(startColumn, R.column s, R.column e, endColumn)
firstLine : rest ->
let
filteredFirstLine =
replicate (startColumn - 1) ' '
++ drop (startColumn - 1) firstLine
filteredLastLine =
take (endColumn) (last rest)
focusedRelevantLines =
filteredFirstLine : init rest ++ [filteredLastLine]
lineNumbersWidth =
length (show endLine)
subregion =
maybeSubRegion <|> Just region
numberedLines =
zipWith
(addLineNumber subregion lineNumbersWidth)
[startLine .. endLine]
focusedRelevantLines
in
foldr (<==>) empty numberedLines
addLineNumber :: Maybe R.Region -> Int -> Int -> String -> Doc
addLineNumber maybeSubRegion width n line =
let
number =
if n < 0 then " " else show n
lineNumber =
replicate (width - length number) ' ' ++ number ++ "|"
spacer (R.Region start end) =
if R.line start <= n && n <= R.line end then
dullred (text ">")
else
text " "
in
text lineNumber
<> maybe (text " ") spacer maybeSubRegion
<> text line
singleLineRegion :: Int -> String -> (Int, Int, Int, Int) -> Doc
singleLineRegion lineNum sourceLine (start, innerStart, innerEnd, end) =
let
width =
length (show lineNum)
underline =
text (replicate (innerStart + width + 1) ' ')
<>
dullred (text (replicate (max 1 (innerEnd - innerStart)) '^'))
trimmedSourceLine =
sourceLine
|> drop (start - 1)
|> take (end - start + 1)
|> (++) (replicate (start - 1) ' ')
in
addLineNumber Nothing width lineNum trimmedSourceLine
<==>
underline
| mgold/Elm | src/Reporting/Render/Code.hs | bsd-3-clause | 2,840 | 0 | 18 | 987 | 896 | 471 | 425 | 81 | 4 |
-- | The monad for writing to the game state and related operations.
module Game.LambdaHack.Atomic.MonadStateWrite
( MonadStateWrite(..)
, updateLevel, updateActor, updateFaction
, insertItemContainer, insertItemActor, deleteItemContainer, deleteItemActor
, updatePrio, updateFloor, updateTile, updateSmell
) where
import Control.Exception.Assert.Sugar
import qualified Data.EnumMap.Strict as EM
import Game.LambdaHack.Common.Actor
import Game.LambdaHack.Common.ActorState
import Game.LambdaHack.Common.Faction
import Game.LambdaHack.Common.Item
import Game.LambdaHack.Common.Level
import Game.LambdaHack.Common.Misc
import Game.LambdaHack.Common.MonadStateRead
import Game.LambdaHack.Common.Point
import Game.LambdaHack.Common.State
class MonadStateRead m => MonadStateWrite m where
modifyState :: (State -> State) -> m ()
putState :: State -> m ()
-- | Update the actor time priority queue.
updatePrio :: (ActorPrio -> ActorPrio) -> Level -> Level
updatePrio f lvl = lvl {lprio = f (lprio lvl)}
-- | Update the items on the ground map.
updateFloor :: (ItemFloor -> ItemFloor) -> Level -> Level
updateFloor f lvl = lvl {lfloor = f (lfloor lvl)}
-- | Update the items embedded in a tile on the level.
updateEmbed :: (ItemFloor -> ItemFloor) -> Level -> Level
updateEmbed f lvl = lvl {lembed = f (lembed lvl)}
-- | Update the tile map.
updateTile :: (TileMap -> TileMap) -> Level -> Level
updateTile f lvl = lvl {ltile = f (ltile lvl)}
-- | Update the smell map.
updateSmell :: (SmellMap -> SmellMap) -> Level -> Level
updateSmell f lvl = lvl {lsmell = f (lsmell lvl)}
-- | Update a given level data within state.
updateLevel :: MonadStateWrite m => LevelId -> (Level -> Level) -> m ()
updateLevel lid f = modifyState $ updateDungeon $ EM.adjust f lid
updateActor :: MonadStateWrite m => ActorId -> (Actor -> Actor) -> m ()
updateActor aid f = do
let alt Nothing = assert `failure` "no body to update" `twith` aid
alt (Just b) = Just $ f b
modifyState $ updateActorD $ EM.alter alt aid
updateFaction :: MonadStateWrite m => FactionId -> (Faction -> Faction) -> m ()
updateFaction fid f = do
let alt Nothing = assert `failure` "no faction to update" `twith` fid
alt (Just fact) = Just $ f fact
modifyState $ updateFactionD $ EM.alter alt fid
insertItemContainer :: MonadStateWrite m
=> ItemId -> ItemQuant -> Container -> m ()
insertItemContainer iid kit c = case c of
CFloor lid pos -> insertItemFloor iid kit lid pos
CEmbed lid pos -> insertItemEmbed iid kit lid pos
CActor aid store -> insertItemActor iid kit aid store
CTrunk{} -> return ()
-- New @kit@ lands at the front of the list.
insertItemFloor :: MonadStateWrite m
=> ItemId -> ItemQuant -> LevelId -> Point -> m ()
insertItemFloor iid kit lid pos =
let bag = EM.singleton iid kit
mergeBag = EM.insertWith (EM.unionWith mergeItemQuant) pos bag
in updateLevel lid $ updateFloor mergeBag
insertItemEmbed :: MonadStateWrite m
=> ItemId -> ItemQuant -> LevelId -> Point -> m ()
insertItemEmbed iid kit lid pos =
let bag = EM.singleton iid kit
mergeBag = EM.insertWith (EM.unionWith mergeItemQuant) pos bag
in updateLevel lid $ updateEmbed mergeBag
insertItemActor :: MonadStateWrite m
=> ItemId -> ItemQuant -> ActorId -> CStore -> m ()
insertItemActor iid kit aid cstore = case cstore of
CGround -> do
b <- getsState $ getActorBody aid
insertItemFloor iid kit (blid b) (bpos b)
COrgan -> insertItemBody iid kit aid
CEqp -> insertItemEqp iid kit aid
CInv -> insertItemInv iid kit aid
CSha -> do
b <- getsState $ getActorBody aid
insertItemSha iid kit (bfid b)
insertItemBody :: MonadStateWrite m
=> ItemId -> ItemQuant -> ActorId -> m ()
insertItemBody iid kit aid = do
let bag = EM.singleton iid kit
upd = EM.unionWith mergeItemQuant bag
updateActor aid $ \b -> b {borgan = upd (borgan b)}
insertItemEqp :: MonadStateWrite m
=> ItemId -> ItemQuant -> ActorId -> m ()
insertItemEqp iid kit aid = do
let bag = EM.singleton iid kit
upd = EM.unionWith mergeItemQuant bag
updateActor aid $ \b -> b {beqp = upd (beqp b)}
insertItemInv :: MonadStateWrite m
=> ItemId -> ItemQuant -> ActorId -> m ()
insertItemInv iid kit aid = do
let bag = EM.singleton iid kit
upd = EM.unionWith mergeItemQuant bag
updateActor aid $ \b -> b {binv = upd (binv b)}
insertItemSha :: MonadStateWrite m
=> ItemId -> ItemQuant -> FactionId -> m ()
insertItemSha iid kit fid = do
let bag = EM.singleton iid kit
upd = EM.unionWith mergeItemQuant bag
updateFaction fid $ \fact -> fact {gsha = upd (gsha fact)}
deleteItemContainer :: MonadStateWrite m
=> ItemId -> ItemQuant -> Container -> m ()
deleteItemContainer iid kit c = case c of
CFloor lid pos -> deleteItemFloor iid kit lid pos
CEmbed lid pos -> deleteItemEmbed iid kit lid pos
CActor aid store -> deleteItemActor iid kit aid store
CTrunk{} -> assert `failure` c
deleteItemFloor :: MonadStateWrite m
=> ItemId -> ItemQuant -> LevelId -> Point -> m ()
deleteItemFloor iid kit lid pos =
let rmFromFloor (Just bag) =
let nbag = rmFromBag kit iid bag
in if EM.null nbag then Nothing else Just nbag
rmFromFloor Nothing = assert `failure` "item already removed"
`twith` (iid, kit, lid, pos)
in updateLevel lid $ updateFloor $ EM.alter rmFromFloor pos
deleteItemEmbed :: MonadStateWrite m
=> ItemId -> ItemQuant -> LevelId -> Point -> m ()
deleteItemEmbed iid kit lid pos =
let rmFromFloor (Just bag) =
let nbag = rmFromBag kit iid bag
in if EM.null nbag then Nothing else Just nbag
rmFromFloor Nothing = assert `failure` "item already removed"
`twith` (iid, kit, lid, pos)
in updateLevel lid $ updateEmbed $ EM.alter rmFromFloor pos
deleteItemActor :: MonadStateWrite m
=> ItemId -> ItemQuant -> ActorId -> CStore -> m ()
deleteItemActor iid kit aid cstore = case cstore of
CGround -> do
b <- getsState $ getActorBody aid
deleteItemFloor iid kit (blid b) (bpos b)
COrgan -> deleteItemBody iid kit aid
CEqp -> deleteItemEqp iid kit aid
CInv -> deleteItemInv iid kit aid
CSha -> do
b <- getsState $ getActorBody aid
deleteItemSha iid kit (bfid b)
deleteItemBody :: MonadStateWrite m => ItemId -> ItemQuant -> ActorId -> m ()
deleteItemBody iid kit aid =
updateActor aid $ \b -> b {borgan = rmFromBag kit iid (borgan b) }
deleteItemEqp :: MonadStateWrite m => ItemId -> ItemQuant -> ActorId -> m ()
deleteItemEqp iid kit aid =
updateActor aid $ \b -> b {beqp = rmFromBag kit iid (beqp b)}
deleteItemInv :: MonadStateWrite m => ItemId -> ItemQuant -> ActorId -> m ()
deleteItemInv iid kit aid =
updateActor aid $ \b -> b {binv = rmFromBag kit iid (binv b)}
deleteItemSha :: MonadStateWrite m => ItemId -> ItemQuant -> FactionId -> m ()
deleteItemSha iid kit fid =
updateFaction fid $ \fact -> fact {gsha = rmFromBag kit iid (gsha fact)}
-- Removing the part of the kit from the front of the list,
-- so that @DestroyItem kit (CreateItem kit x) == x@.
rmFromBag :: ItemQuant -> ItemId -> ItemBag -> ItemBag
rmFromBag kit@(k, rmIt) iid bag =
let rfb Nothing = assert `failure` "rm from empty slot" `twith` (k, iid, bag)
rfb (Just (n, it)) =
case compare n k of
LT -> assert `failure` "rm more than there is"
`twith` (n, kit, iid, bag)
EQ -> Nothing -- TODO: assert as below
GT -> assert (rmIt == take k it
`blame` (rmIt, take k it, n, kit, iid, bag))
$ Just (n - k, drop k it)
in EM.alter rfb iid bag
| Concomitant/LambdaHack | Game/LambdaHack/Atomic/MonadStateWrite.hs | bsd-3-clause | 7,801 | 0 | 17 | 1,836 | 2,689 | 1,365 | 1,324 | 157 | 5 |
module IO (
Handle, HandlePosn,
IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
BufferMode(NoBuffering,LineBuffering,BlockBuffering),
SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
stdin, stdout, stderr,
openFile, hClose, hFileSize, hIsEOF, isEOF,
hSetBuffering, hGetBuffering, hFlush,
hGetPosn, hSetPosn, hSeek,
hWaitForInput, hReady, hGetChar, hGetLine, hLookAhead, hGetContents,
hPutChar, hPutStr, hPutStrLn, hPrint,
hIsOpen, hIsClosed, hIsReadable, hIsWritable, hIsSeekable,
isAlreadyExistsError, isDoesNotExistError, isAlreadyInUseError,
isFullError, isEOFError,
isIllegalOperation, isPermissionError, isUserError,
ioeGetErrorString, ioeGetHandle, ioeGetFileName,
try, bracket, bracket_,
-- ...and what the Prelude exports
IO, FilePath, IOError, ioError, userError, catch, interact,
putChar, putStr, putStrLn, print, getChar, getLine, getContents,
readFile, writeFile, appendFile, readIO, readLn
) where
import System.IO
import System.IO.Error
-- | The 'bracket' function captures a common allocate, compute, deallocate
-- idiom in which the deallocation step must occur even in the case of an
-- error during computation. This is similar to try-catch-finally in Java.
--
-- This version handles only IO errors, as defined by Haskell 98.
-- The version of @bracket@ in "Control.Exception" handles all exceptions,
-- and should be used instead.
bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket before after m = do
x <- before
rs <- try (m x)
after x
case rs of
Right r -> return r
Left e -> ioError e
-- | A variant of 'bracket' where the middle computation doesn't want @x@.
--
-- This version handles only IO errors, as defined by Haskell 98.
-- The version of @bracket_@ in "Control.Exception" handles all exceptions,
-- and should be used instead.
bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c
bracket_ before after m = do
x <- before
rs <- try m
after x
case rs of
Right r -> return r
Left e -> ioError e
| alekar/hugs | packages/haskell98/IO.hs | bsd-3-clause | 2,162 | 0 | 10 | 505 | 474 | 278 | 196 | 44 | 2 |
module Numeric.Semiring.Class
( Semiring
) where
import Numeric.Algebra.Class
| athanclark/algebra | src/Numeric/Semiring/Class.hs | bsd-3-clause | 85 | 0 | 4 | 15 | 18 | 12 | 6 | 3 | 0 |
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
module Network.AWS.S3SimpleTypes where
import Control.Applicative
import GHC.Generics
import qualified Data.ByteString as B
import qualified Data.Aeson as A
import Data.Yaml (parseJSON, FromJSON, (.:))
data S3Region = US | EU | USWest | APSouthEast | UndefinedRegion deriving (Generic, Eq, Show)
data S3Host = S3Host {
s3HostName :: String
,s3Port :: Int
} deriving (Read, Eq, Show)
instance FromJSON S3Host where
parseJSON (A.Object tObj) = S3Host <$>
tObj .: "s3HostName" <*>
tObj .: "s3Port"
data S3Connection = S3Connection {
s3Host :: S3Host
,s3AccessKey :: String
,s3SecretKey :: String
} deriving (Read, Show,Eq)
instance FromJSON S3Connection where
parseJSON (A.Object tObj) = S3Connection <$>
tObj .: "s3Host" <*>
tObj .: "s3AccessKey" <*>
tObj .: "s3SecretKey"
parseJSON _ = fail "Rule: Expecting MongoDB Config Object Received, Other"
data S3Object = S3Object{
s3ObjectName :: String
,s3ObjectContents :: B.ByteString
,s3ObjectBucket :: String
,s3ObjectPath :: String
,s3ContentType :: String
} deriving (Generic, Eq, Show)
data S3Bucket = S3Bucket {
s3BucketName :: String
,s3BucketCreationDate :: String
,s3BucketRegion :: S3Region
} deriving (Generic, Eq, Show)
data S3NetworkError = S3NetworkError String deriving (Generic, Eq, Show)
data S3AuthError = S3AuthError {
errorMessage :: String
} deriving (Generic, Eq, Show)
data S3Result a = S3Error (Either S3NetworkError S3AuthError) | S3Success a deriving (Generic, Eq, Show) | KevinCotrone/S3-Simple | src/Network/AWS/S3SimpleTypes.hs | bsd-3-clause | 1,650 | 0 | 11 | 365 | 453 | 261 | 192 | 44 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Crypto.Internal.Nat
( type IsDivisibleBy8
, type IsAtMost, type IsAtLeast
, byteLen
, integralNatVal
, type Div8
, type Mod8
) where
import GHC.TypeLits
byteLen :: (KnownNat bitlen, IsDivisibleBy8 bitlen, Num a) => proxy bitlen -> a
byteLen d = fromInteger (natVal d `div` 8)
integralNatVal :: (KnownNat bitlen, Num a) => proxy bitlen -> a
integralNatVal = fromInteger . natVal
type family IsLE (bitlen :: Nat) (n :: Nat) (c :: Bool) where
IsLE bitlen n 'True = 'True
#if MIN_VERSION_base(4,9,0)
IsLE bitlen n 'False = TypeError
( ('Text "bitlen " ':<>: 'ShowType bitlen ':<>: 'Text " is greater than " ':<>: 'ShowType n)
':$$: ('Text "You have tried to use an invalid Digest size. Please, refer to the documentation.")
)
#else
IsLE bitlen n 'False = 'False
#endif
-- | ensure the given `bitlen` is lesser or equal to `n`
--
type IsAtMost (bitlen :: Nat) (n :: Nat) = IsLE bitlen n (bitlen <=? n) ~ 'True
type family IsGE (bitlen :: Nat) (n :: Nat) (c :: Bool) where
IsGE bitlen n 'True = 'True
#if MIN_VERSION_base(4,9,0)
IsGE bitlen n 'False = TypeError
( ('Text "bitlen " ':<>: 'ShowType bitlen ':<>: 'Text " is lesser than " ':<>: 'ShowType n)
':$$: ('Text "You have tried to use an invalid Digest size. Please, refer to the documentation.")
)
#else
IsGE bitlen n 'False = 'False
#endif
-- | ensure the given `bitlen` is greater or equal to `n`
--
type IsAtLeast (bitlen :: Nat) (n :: Nat) = IsGE bitlen n (n <=? bitlen) ~ 'True
type family Div8 (bitLen :: Nat) where
Div8 0 = 0
Div8 1 = 0
Div8 2 = 0
Div8 3 = 0
Div8 4 = 0
Div8 5 = 0
Div8 6 = 0
Div8 7 = 0
Div8 8 = 1
Div8 9 = 1
Div8 10 = 1
Div8 11 = 1
Div8 12 = 1
Div8 13 = 1
Div8 14 = 1
Div8 15 = 1
Div8 16 = 2
Div8 17 = 2
Div8 18 = 2
Div8 19 = 2
Div8 20 = 2
Div8 21 = 2
Div8 22 = 2
Div8 23 = 2
Div8 24 = 3
Div8 25 = 3
Div8 26 = 3
Div8 27 = 3
Div8 28 = 3
Div8 29 = 3
Div8 30 = 3
Div8 31 = 3
Div8 32 = 4
Div8 33 = 4
Div8 34 = 4
Div8 35 = 4
Div8 36 = 4
Div8 37 = 4
Div8 38 = 4
Div8 39 = 4
Div8 40 = 5
Div8 41 = 5
Div8 42 = 5
Div8 43 = 5
Div8 44 = 5
Div8 45 = 5
Div8 46 = 5
Div8 47 = 5
Div8 48 = 6
Div8 49 = 6
Div8 50 = 6
Div8 51 = 6
Div8 52 = 6
Div8 53 = 6
Div8 54 = 6
Div8 55 = 6
Div8 56 = 7
Div8 57 = 7
Div8 58 = 7
Div8 59 = 7
Div8 60 = 7
Div8 61 = 7
Div8 62 = 7
Div8 63 = 7
Div8 64 = 8
Div8 n = 8 + Div8 (n - 64)
type family IsDiv8 (bitLen :: Nat) (n :: Nat) where
IsDiv8 bitLen 0 = 'True
#if MIN_VERSION_base(4,9,0)
IsDiv8 bitLen 1 = TypeError ('Text "bitLen " ':<>: 'ShowType bitLen ':<>: 'Text " is not divisible by 8")
IsDiv8 bitLen 2 = TypeError ('Text "bitLen " ':<>: 'ShowType bitLen ':<>: 'Text " is not divisible by 8")
IsDiv8 bitLen 3 = TypeError ('Text "bitLen " ':<>: 'ShowType bitLen ':<>: 'Text " is not divisible by 8")
IsDiv8 bitLen 4 = TypeError ('Text "bitLen " ':<>: 'ShowType bitLen ':<>: 'Text " is not divisible by 8")
IsDiv8 bitLen 5 = TypeError ('Text "bitLen " ':<>: 'ShowType bitLen ':<>: 'Text " is not divisible by 8")
IsDiv8 bitLen 6 = TypeError ('Text "bitLen " ':<>: 'ShowType bitLen ':<>: 'Text " is not divisible by 8")
IsDiv8 bitLen 7 = TypeError ('Text "bitLen " ':<>: 'ShowType bitLen ':<>: 'Text " is not divisible by 8")
#else
IsDiv8 bitLen 1 = 'False
IsDiv8 bitLen 2 = 'False
IsDiv8 bitLen 3 = 'False
IsDiv8 bitLen 4 = 'False
IsDiv8 bitLen 5 = 'False
IsDiv8 bitLen 6 = 'False
IsDiv8 bitLen 7 = 'False
#endif
IsDiv8 bitLen n = IsDiv8 n (Mod8 n)
type family Mod8 (n :: Nat) where
Mod8 0 = 0
Mod8 1 = 1
Mod8 2 = 2
Mod8 3 = 3
Mod8 4 = 4
Mod8 5 = 5
Mod8 6 = 6
Mod8 7 = 7
Mod8 8 = 0
Mod8 9 = 1
Mod8 10 = 2
Mod8 11 = 3
Mod8 12 = 4
Mod8 13 = 5
Mod8 14 = 6
Mod8 15 = 7
Mod8 16 = 0
Mod8 17 = 1
Mod8 18 = 2
Mod8 19 = 3
Mod8 20 = 4
Mod8 21 = 5
Mod8 22 = 6
Mod8 23 = 7
Mod8 24 = 0
Mod8 25 = 1
Mod8 26 = 2
Mod8 27 = 3
Mod8 28 = 4
Mod8 29 = 5
Mod8 30 = 6
Mod8 31 = 7
Mod8 32 = 0
Mod8 33 = 1
Mod8 34 = 2
Mod8 35 = 3
Mod8 36 = 4
Mod8 37 = 5
Mod8 38 = 6
Mod8 39 = 7
Mod8 40 = 0
Mod8 41 = 1
Mod8 42 = 2
Mod8 43 = 3
Mod8 44 = 4
Mod8 45 = 5
Mod8 46 = 6
Mod8 47 = 7
Mod8 48 = 0
Mod8 49 = 1
Mod8 50 = 2
Mod8 51 = 3
Mod8 52 = 4
Mod8 53 = 5
Mod8 54 = 6
Mod8 55 = 7
Mod8 56 = 0
Mod8 57 = 1
Mod8 58 = 2
Mod8 59 = 3
Mod8 60 = 4
Mod8 61 = 5
Mod8 62 = 6
Mod8 63 = 7
Mod8 n = Mod8 (n - 64)
type IsDivisibleBy8 bitLen = IsDiv8 bitLen bitLen ~ 'True
| tekul/cryptonite | Crypto/Internal/Nat.hs | bsd-3-clause | 5,108 | 0 | 14 | 1,742 | 1,942 | 1,003 | 939 | -1 | -1 |
-- | Infer the remote IP address using headers
module Network.Wai.Middleware.RealIp
( realIp
, realIpHeader
, realIpTrusted
, defaultTrusted
, ipInRange
) where
import qualified Data.ByteString.Char8 as B8 (unpack, split)
import qualified Data.IP as IP
import Data.Maybe (fromMaybe, mapMaybe, listToMaybe)
import Network.HTTP.Types (HeaderName, RequestHeaders)
import Network.Wai
import Text.Read (readMaybe)
-- | Infer the remote IP address from the @X-Forwarded-For@ header,
-- trusting requests from any private IP address. See 'realIpHeader' and
-- 'realIpTrusted' for more information and options.
--
-- @since 3.1.5
realIp :: Middleware
realIp = realIpHeader "X-Forwarded-For"
-- | Infer the remote IP address using the given header, trusting
-- requests from any private IP address. See 'realIpTrusted' for more
-- information and options.
--
-- @since 3.1.5
realIpHeader :: HeaderName -> Middleware
realIpHeader header =
realIpTrusted header $ \ip -> any (ipInRange ip) defaultTrusted
-- | Infer the remote IP address using the given header, but only if the
-- request came from an IP that is trusted by the provided predicate.
--
-- The last non-trusted address is used to replace the 'remoteHost' in
-- the 'Request', unless all present IP addresses are trusted, in which
-- case the first address is used. Invalid IP addresses are ignored, and
-- the remoteHost value remains unaltered if no valid IP addresses are
-- found.
--
-- Examples:
--
-- @ realIpTrusted "X-Forwarded-For" $ flip ipInRange "10.0.0.0/8" @
--
-- @ realIpTrusted "X-Real-Ip" $ \\ip -> any (ipInRange ip) defaultTrusted @
--
-- @since 3.1.5
realIpTrusted :: HeaderName -> (IP.IP -> Bool) -> Middleware
realIpTrusted header isTrusted app req respond = app req' respond
where
req' = fromMaybe req $ do
(ip, port) <- IP.fromSockAddr (remoteHost req)
ip' <- if isTrusted ip
then findRealIp (requestHeaders req) header isTrusted
else Nothing
Just $ req { remoteHost = IP.toSockAddr (ip', port) }
-- | Standard private IP ranges.
--
-- @since 3.1.5
defaultTrusted :: [IP.IPRange]
defaultTrusted = [ "127.0.0.0/8"
, "10.0.0.0/8"
, "172.16.0.0/12"
, "192.168.0.0/16"
, "::1/128"
, "fc00::/7"
]
-- | Check if the given IP address is in the given range.
--
-- IPv4 addresses can be checked against IPv6 ranges, but testing an
-- IPv6 address against an IPv4 range is always 'False'.
--
-- @since 3.1.5
ipInRange :: IP.IP -> IP.IPRange -> Bool
ipInRange (IP.IPv4 ip) (IP.IPv4Range r) = ip `IP.isMatchedTo` r
ipInRange (IP.IPv6 ip) (IP.IPv6Range r) = ip `IP.isMatchedTo` r
ipInRange (IP.IPv4 ip) (IP.IPv6Range r) = IP.ipv4ToIPv6 ip `IP.isMatchedTo` r
ipInRange _ _ = False
findRealIp :: RequestHeaders -> HeaderName -> (IP.IP -> Bool) -> Maybe IP.IP
findRealIp reqHeaders header isTrusted =
case (nonTrusted, ips) of
([], xs) -> listToMaybe xs
(xs, _) -> listToMaybe $ reverse xs
where
-- account for repeated headers
headerVals = [ v | (k, v) <- reqHeaders, k == header ]
ips = mapMaybe (readMaybe . B8.unpack) $ concatMap (B8.split ',') headerVals
nonTrusted = filter (not . isTrusted) ips
| kazu-yamamoto/wai | wai-extra/Network/Wai/Middleware/RealIp.hs | mit | 3,324 | 0 | 14 | 742 | 662 | 379 | 283 | 45 | 2 |
module Main where
import Happstack.Server
import Control.Monad
{-
interesting urls:
/?string=hello+world
-}
data MyStructure = MyStructure String
instance FromData MyStructure where
fromData = do str <- look "string"
return $ MyStructure str
main :: IO ()
main = do simpleHTTP nullConf $ msum
[
do
(MyStructure str) <- getData >>= maybe mzero return
ok $ "You entered: " ++ str
, ok "Sorry, I don't understand."
]
| erantapaa/happstack-server | attic/Examples/set/FromData/Basics.hs | bsd-3-clause | 540 | 0 | 14 | 193 | 127 | 63 | 64 | 14 | 1 |
module HTTP (
sendGET
, sendGETwH
, sendHEAD
, sendHEADwH
, responseBody
, responseStatus
, responseHeaders
, getHeaderValue
, HeaderName
) where
import Network.HTTP.Client
import Network.HTTP.Types
import Data.ByteString
import qualified Data.ByteString.Lazy as BL
sendGET :: String -> IO (Response BL.ByteString)
sendGET url = sendGETwH url []
sendGETwH :: String -> [Header] -> IO (Response BL.ByteString)
sendGETwH url hdr = do
manager <- newManager defaultManagerSettings
request <- parseRequest url
let request' = request { requestHeaders = hdr }
response <- httpLbs request' manager
return response
sendHEAD :: String -> IO (Response BL.ByteString)
sendHEAD url = sendHEADwH url []
sendHEADwH :: String -> [Header] -> IO (Response BL.ByteString)
sendHEADwH url hdr = do
manager <- newManager defaultManagerSettings
request <- parseRequest url
let request' = request { requestHeaders = hdr, method = methodHead }
response <- httpLbs request' manager
return response
getHeaderValue :: HeaderName -> [Header] -> Maybe ByteString
getHeaderValue = lookup
| creichert/wai | warp/test/HTTP.hs | mit | 1,125 | 0 | 11 | 217 | 343 | 177 | 166 | 34 | 1 |
module System.Taffybar.Widget.Generic.DynamicMenu where
import Control.Monad.IO.Class
import qualified GI.Gtk as Gtk
data DynamicMenuConfig = DynamicMenuConfig
{ dmClickWidget :: Gtk.Widget
, dmPopulateMenu :: Gtk.Menu -> IO ()
}
dynamicMenuNew :: MonadIO m => DynamicMenuConfig -> m Gtk.Widget
dynamicMenuNew DynamicMenuConfig
{ dmClickWidget = clickWidget
, dmPopulateMenu = populateMenu
} = do
button <- Gtk.menuButtonNew
menu <- Gtk.menuNew
Gtk.containerAdd button clickWidget
Gtk.menuButtonSetPopup button $ Just menu
_ <- Gtk.onButtonPressed button $ emptyMenu menu >> populateMenu menu
Gtk.widgetShowAll button
Gtk.toWidget button
emptyMenu :: (Gtk.IsContainer a, MonadIO m) => a -> m ()
emptyMenu menu =
Gtk.containerForeach menu $ \item ->
Gtk.containerRemove menu item >> Gtk.widgetDestroy item
| teleshoes/taffybar | src/System/Taffybar/Widget/Generic/DynamicMenu.hs | bsd-3-clause | 899 | 0 | 11 | 195 | 256 | 129 | 127 | 22 | 1 |
{-# LANGUAGE GADTs #-}
{-# OPTIONS_GHC -Wall #-}
module Parse (parseCode) where
import Control.Monad
import Prelude hiding (id, last, succ)
-- Note: We do not need to import Hoopl to build an AST.
import Ast
import Expr
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr
import Text.ParserCombinators.Parsec.Language
import qualified Text.ParserCombinators.Parsec.Token as P
-- I'm stealing this parser almost directly from Daan Leijen's Parsec guide.
lexer :: P.TokenParser ()
lexer = P.makeTokenParser (haskellDef {reservedOpNames = ["+", "-", "*", "/", "=", "<"]})
-- Common lexers:
lexeme, parens, braces :: CharParser () a -> CharParser () a
lexeme = P.lexeme lexer
parens = P.parens lexer
braces = P.braces lexer
commaSep :: CharParser () a -> CharParser () [a]
commaSep = P.commaSep lexer
reserved :: String -> CharParser () ()
reserved = P.reserved lexer
ign :: GenParser Char st a -> GenParser Char st ()
ign p = p >> return ()
char' :: Char -> GenParser Char st ()
char' c = ign $ char c
identifier :: CharParser () String
identifier = P.identifier lexer
natural :: CharParser () Integer
natural = P.natural lexer
reservedOp :: String -> CharParser () ()
reservedOp = P.reservedOp lexer
whitespace :: CharParser () ()
whitespace = P.whiteSpace lexer
-- Expressions:
expr :: Parser Expr
expr = buildExpressionParser table factor
<?> "Expression"
where
table = [[op "*" (Binop Mul) AssocLeft, op "/" (Binop Div) AssocLeft],
[op "+" (Binop Add) AssocLeft, op "-" (Binop Sub) AssocLeft],
[op "=" (Binop Eq) AssocLeft, op "/=" (Binop Ne) AssocLeft,
op ">" (Binop Gt) AssocLeft, op "<" (Binop Lt) AssocLeft,
op ">=" (Binop Gte) AssocLeft, op "<=" (Binop Lte) AssocLeft]]
op o f assoc = Infix (do {reservedOp o; return f} <?> "operator") assoc
factor = parens expr
<|> lit
<|> fetchVar
<|> load
<?> "simple Expression"
bool :: Parser Bool
bool = (try $ lexeme (string "True") >> return True)
<|> (try $ lexeme (string "False") >> return False)
lit :: Parser Expr
lit = (natural >>= (return . Lit . Int))
<|> (bool >>= (return . Lit . Bool))
<|> (bool >>= (return . Lit . Bool))
<?> "lit"
loc :: Char -> Parser x -> Parser x
loc s addr = try (lexeme (do { char' s
; char' '['
; a <- addr
; char' ']'
; return a
}))
<?> "loc"
var :: Parser String
var = identifier
<?> "var"
mem :: Parser Expr -- address
mem = loc 'm' expr
<?> "mem"
fetchVar, load :: Parser Expr
fetchVar = var >>= return . Var
load = mem >>= return . Load
labl :: Parser Lbl
labl = lexeme (do { id <- identifier
; char' ':'
; return id
})
<?> "label"
mid :: Parser Insn
mid = asst
<|> store
<?> "assignment or store"
asst :: Parser Insn
asst = do { v <- lexeme var
; lexeme (char' '=')
; e <- expr
; return $ Assign v e
}
<?> "asst"
store :: Parser Insn
store = do { addr <- lexeme mem
; lexeme (char' '=')
; e <- expr
; return $ Store addr e
}
<?> "store"
control :: Parser Control
control = branch
<|> cond
<|> call
<|> ret
<?> "control-transfer"
goto :: Parser Lbl
goto = do { lexeme (reserved "goto")
; identifier
}
<?> "goto"
branch :: Parser Control
branch =
do { l <- goto
; return $ Branch l
}
<?> "branch"
cond, call, ret :: Parser Control
cond =
do { lexeme (reserved "if")
; cnd <- expr
; lexeme (reserved "then")
; thn <- goto
; lexeme (reserved "else")
; els <- goto
; return $ Cond cnd thn els
}
<?> "cond"
call =
do { results <- tuple var
; lexeme (char' '=')
; f <- identifier
; params <- tuple expr
; succ <- goto
; return $ Call results f params succ
}
<?> "call"
ret =
do { lexeme (reserved "ret")
; results <- tuple expr
; return $ Return results
}
<?> "ret"
block :: Parser Block
block =
do { f <- lexeme labl
; ms <- many $ try mid
; l <- lexeme control
; return $ Block { first = f, mids = ms, last = l }
}
<?> "Expected basic block; maybe you forgot a label following a control-transfer?"
tuple :: Parser a -> Parser [a]
tuple = parens . commaSep
proc :: Parser Proc
proc = do { whitespace
; f <- identifier
; params <- tuple var
; bdy <- braces $ do { b <- block
; bs <- many block
; return (b : bs)
} -- procedure must have at least one block
; return $ Proc { name = f, args = params, body = bdy }
}
<?> "proc"
parseCode :: String -> String -> Either ParseError [Proc]
parseCode file inp = parse (many proc) file inp
| ezyang/hoopl | testing/Parse.hs | bsd-3-clause | 5,156 | 0 | 14 | 1,723 | 1,762 | 914 | 848 | 150 | 1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Aws.DynamoDb.Commands.Query
-- Copyright : Soostone Inc
-- License : BSD3
--
-- Maintainer : Ozgun Ataman <[email protected]>
-- Stability : experimental
--
-- Implementation of Amazon DynamoDb Query command.
--
-- See: @http:\/\/docs.aws.amazon.com\/amazondynamodb\/latest\/APIReference\/API_Query.html@
----------------------------------------------------------------------------
module Aws.DynamoDb.Commands.Query
( Query (..)
, Slice (..)
, query
, QueryResponse (..)
) where
-------------------------------------------------------------------------------
import Control.Applicative
import Data.Aeson
import Data.Default
import Data.Maybe
import qualified Data.Text as T
import Data.Typeable
import qualified Data.Vector as V
-------------------------------------------------------------------------------
import Aws.Core
import Aws.DynamoDb.Core
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- | 'Slice' is the primary constraint in a 'Query' command, per AWS
-- requirements.
--
-- All 'Query' commands must specify a hash attribute via 'DEq' and
-- optionally provide a secondary range attribute.
data Slice = Slice {
sliceHash :: Attribute
-- ^ Hash value of the primary key or index being used
, sliceCond :: Maybe Condition
-- ^ An optional condition specified on the range component, if
-- present, of the primary key or index being used.
} deriving (Eq,Show,Read,Ord,Typeable)
-- | A Query command that uses primary keys for an expedient scan.
data Query = Query {
qTableName :: T.Text
-- ^ Required.
, qKeyConditions :: Slice
-- ^ Required. Hash or hash-range main condition.
, qFilter :: Conditions
-- ^ Whether to filter results before returning to client
, qStartKey :: Maybe [Attribute]
-- ^ Exclusive start key to resume a previous query.
, qLimit :: Maybe Int
-- ^ Whether to limit result set size
, qForwardScan :: Bool
-- ^ Set to False for descending results
, qSelect :: QuerySelect
-- ^ What to return from 'Query'
, qRetCons :: ReturnConsumption
, qIndex :: Maybe T.Text
-- ^ Whether to use a secondary/global index
, qConsistent :: Bool
} deriving (Eq,Show,Read,Ord,Typeable)
-------------------------------------------------------------------------------
instance ToJSON Query where
toJSON Query{..} = object $
catMaybes
[ (("ExclusiveStartKey" .= ) . attributesJson) <$> qStartKey
, ("Limit" .= ) <$> qLimit
, ("IndexName" .= ) <$> qIndex
] ++
conditionsJson "QueryFilter" qFilter ++
querySelectJson qSelect ++
[ "ScanIndexForward" .= qForwardScan
, "TableName".= qTableName
, "KeyConditions" .= sliceJson qKeyConditions
, "ReturnConsumedCapacity" .= qRetCons
, "ConsistentRead" .= qConsistent
]
-------------------------------------------------------------------------------
-- | Construct a minimal 'Query' request.
query
:: T.Text
-- ^ Table name
-> Slice
-- ^ Primary key slice for query
-> Query
query tn sl = Query tn sl def Nothing Nothing True def def Nothing False
-- | Response to a 'Query' query.
data QueryResponse = QueryResponse {
qrItems :: V.Vector Item
, qrLastKey :: Maybe [Attribute]
, qrCount :: Int
, qrScanned :: Int
, qrConsumed :: Maybe ConsumedCapacity
} deriving (Eq,Show,Read,Ord)
instance FromJSON QueryResponse where
parseJSON (Object v) = QueryResponse
<$> v .:? "Items" .!= V.empty
<*> ((do o <- v .: "LastEvaluatedKey"
Just <$> parseAttributeJson o)
<|> pure Nothing)
<*> v .: "Count"
<*> v .: "ScannedCount"
<*> v .:? "ConsumedCapacity"
parseJSON _ = fail "QueryResponse must be an object."
instance Transaction Query QueryResponse
instance SignQuery Query where
type ServiceConfiguration Query = DdbConfiguration
signQuery gi = ddbSignQuery "Query" gi
instance ResponseConsumer r QueryResponse where
type ResponseMetadata QueryResponse = DdbResponse
responseConsumer _ ref resp = ddbResponseConsumer ref resp
instance AsMemoryResponse QueryResponse where
type MemoryResponse QueryResponse = QueryResponse
loadToMemory = return
instance ListResponse QueryResponse Item where
listResponse = V.toList . qrItems
instance IteratedTransaction Query QueryResponse where
nextIteratedRequest request response = case qrLastKey response of
Nothing -> Nothing
key -> Just request { qStartKey = key }
sliceJson :: Slice -> Value
sliceJson Slice{..} = object (map conditionJson cs)
where
cs = maybe [] return sliceCond ++ [hashCond]
hashCond = Condition (attrName sliceHash) (DEq (attrVal sliceHash))
| Soostone/aws | Aws/DynamoDb/Commands/Query.hs | bsd-3-clause | 5,233 | 1 | 19 | 1,205 | 891 | 504 | 387 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module WebParsing.TimeConverter
(makeTimeSlots) where
import qualified Data.Text as T
import Database.Tables
-- | Converts days into numbers, returns a tuple of the rest of the string (the times)
-- and a list of number representations of days
convertTime :: (T.Text, [Double]) -> (T.Text, [Double])
convertTime (str, times)
|T.null str = ("", times)
|T.head str == 'M' = convertTime (T.drop 1 str, 0:times)
|T.head str == 'T' = convertTime (T.drop 1 str, 1:times)
|T.head str == 'W' = convertTime (T.drop 1 str, 2:times)
|T.head str == 'R' = convertTime (T.drop 1 str, 3:times)
|T.head str == 'F' = convertTime (T.drop 1 str, 4:times)
|otherwise = (str, times)
-- | Given to numbers, creates a list of half-hours intervals between them
-- modifies 12-hour representation to 24
makeSlots :: Double -> Double -> [Double]
makeSlots start end
| end < start = halfHourSlots start (12 + end)
| start < 8.5 = halfHourSlots (start + 12) (end + 12)
| otherwise = halfHourSlots start end
-- | Extends functionality of makeSlots
halfHourSlots :: Double -> Double -> [Double]
halfHourSlots start end =
let hours = [start .. end - 1]
in concatMap (\h -> [h, h + 0.5]) hours
-- | Converts the textual representation of time into numbers
toDouble :: T.Text -> Double
toDouble double
| null list = 0.0
| otherwise = fst (head list) + halfHour
where
splitIt = T.split (== ':') double
list = reads $ T.unpack (head splitIt)
halfHour = if length splitIt > 1
then 0.5
else 0
-- | Zips together time slots with their days
addList :: [a] -> [a] -> [[a]]
addList days slots =
concatMap (\day -> map (\time -> [day,time]) slots) days
-- | Returns a list of days and half-hour timeslots.
makeTimeSlots :: T.Text -> [Time]
makeTimeSlots str =
let (times, days) = convertTime (str, [])
doubles = map toDouble ( T.split (== '-') times)
slots = if length doubles == 1
then makeSlots (head doubles) (head doubles + 1)
else makeSlots (head doubles) (head (tail doubles))
in map Time (addList days slots)
| tamaralipowski/courseography | hs/WebParsing/TimeConverter.hs | gpl-3.0 | 2,200 | 0 | 14 | 538 | 791 | 412 | 379 | 43 | 2 |
{-# LANGUAGE CPP, ForeignFunctionInterface #-}
module Test where
import Control.Concurrent
import Control.Monad
import Foreign.C
-- See also conc059_c.c
--
-- This test fires off some threads that will return after the RTS has
-- shut down. This should not crash or confuse the RTS.
f :: Int -> IO ()
f x = do
print x
replicateM_ 10 $ forkIO $ do usleep (fromIntegral x); putStrLn "hello"
return ()
foreign export ccall "f" f :: Int -> IO ()
#ifdef mingw32_HOST_OS
foreign import stdcall safe "Sleep" _sleep :: Int -> IO ()
usleep n = _sleep (n `quot` 1000)
#else
foreign import ccall safe "usleep" usleep :: Int -> IO ()
#endif
| urbanslug/ghc | testsuite/tests/concurrent/should_run/conc059.hs | bsd-3-clause | 642 | 0 | 12 | 125 | 160 | 84 | 76 | 12 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{- TODO
- Support configuration of match rules
- Configuration for iptables stuff
- Rename (e.g. botblock)
-}
module Main where
import Prelude hiding (lines)
import Control.Monad (forM_)
import Data.ByteString (ByteString, hGetContents)
import Data.ByteString.Char8 (lines)
import Data.Either (rights)
import Data.Semigroup ((<>))
import Options.Applicative --(*)
import System.Exit (exitFailure, exitSuccess)
import System.IO (BufferMode(..), hPutStrLn, hSetBuffering, stderr, stdout)
import System.Posix.Process (getProcessID)
import System.Posix.Signals (Handler(..), installHandler, sigHUP)
import System.Process (createProcess, proc, std_out, StdStream(CreatePipe))
import Config (copyText, descText, headerText, ipCmd, offsetHelp)
import Rules (Address(..), findAbusiveAddress, findNotTooAbusiveAddress, toString)
import Sqlite (initDatabase, existsOrInsert, blindDelete)
import Tailf (tailf)
data Args = Args { filename :: String, offset :: Integer }
args :: Parser Args
args = Args
<$> argument str (metavar "FILE")
<*> option auto (long "offset" <> metavar "N" <> value 0 <> help offsetHelp)
main :: IO ()
main = execParser magic >>= authbanner
where
magic = info (args <**> helper) $
fullDesc <> progDesc descText <> header (headerText Nothing)
authbanner :: Args -> IO ()
authbanner (Args filename offset) = do
pid <- show <$> getProcessID
hSetBuffering stdout LineBuffering
putStrLn $ headerText (Just pid)
putStrLn copyText
putStrLn "Initializing database"
initDatabase
putStrLn "Installing SIGHUP handler"
installHandler sigHUP pruneTable Nothing
putStrLn "Following log file"
tailf filename offset (banOrElse . findAbusiveAddress)
pruneTable :: Handler
pruneTable = Catch $ do
let args = ["-L", "BLACKLIST", "-n", "-v"]
(_, Just h, _, _) <- createProcess (proc ipCmd args){ std_out = CreatePipe }
output <- hGetContents h
let addresses = rights $ map findNotTooAbusiveAddress (lines output) -- :: [Address]
forM_ (toString <$> addresses) $ \addr -> do
blindDelete addr
liftBan addr
banOrElse :: Either String Address -> IO ()
banOrElse (Left _) = return ()
banOrElse (Right a) = do
let addr = toString a
let args = ["-A", "BLACKLIST", "-s", addr, "-j", "DROP"]
changes <- existsOrInsert addr
case changes of
0 -> do
return ()
1 -> do
createProcess (proc ipCmd args){ std_out = CreatePipe }
putStrLn $ "Banning " ++ addr
otherwise -> exitFailure
liftBan :: String -> IO ()
liftBan addr = do
let args = ["-D", "BLACKLIST", "-s", addr, "-j", "DROP"]
createProcess (proc ipCmd args){ std_out = CreatePipe }
putStrLn $ "Unbanning " ++ addr
| humppa/auth-banner | app/Main.hs | isc | 2,830 | 0 | 15 | 607 | 895 | 474 | 421 | 66 | 3 |
{-# LANGUAGE CPP, NoImplicitPrelude #-}
module Data.Functor.Product.Compat (
#if MIN_VERSION_base(4,9,0)
module Base
#endif
) where
#if MIN_VERSION_base(4,9,0)
import Data.Functor.Product as Base
#endif
| haskell-compat/base-compat | base-compat/src/Data/Functor/Product/Compat.hs | mit | 206 | 0 | 4 | 25 | 27 | 21 | 6 | 2 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Pladen.Beets (
module Pladen.Beets.Types,
module Pladen.Beets.DB,
)where
import Pladen.Beets.Types
import Pladen.Beets.DB
| geigerzaehler/pladen | Pladen/Beets.hs | mit | 173 | 0 | 5 | 25 | 36 | 25 | 11 | 6 | 0 |
-------------------------------------------------------------------------------
-- |
-- Module : System.Hardware.Arduino.Data
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Underlying data structures
-------------------------------------------------------------------------------
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RankNTypes #-}
module System.Hardware.Arduino.Data where
import Control.Applicative (Applicative)
import Control.Concurrent (Chan, MVar, modifyMVar, modifyMVar_, withMVar, ThreadId)
import Control.Monad (when)
import Control.Monad.State (StateT, MonadIO, MonadState, gets, liftIO)
import Data.Bits ((.&.), (.|.), setBit)
import Data.List (intercalate)
import Data.Maybe (fromMaybe, listToMaybe)
import Data.Word (Word8, Word32)
import System.Hardware.Serialport (SerialPort)
import qualified Data.Map as M
import qualified Data.Set as S
import System.Hardware.Arduino.Utils
-- | A port (containing 8 pins)
data Port = Port { portNo :: Word8 -- ^ The port number
}
deriving (Eq, Ord)
instance Show Port where
show p = "Port" ++ show (portNo p)
-- | A pin on the Arduino, as specified by the user via 'pin', 'digital', and 'analog' functions.
data Pin = DigitalPin {userPinNo :: Word8}
| AnalogPin {userPinNo :: Word8}
| MixedPin {userPinNo :: Word8}
instance Show Pin where
show (DigitalPin w) = "DPin" ++ show w
show (AnalogPin w) = "APin" ++ show w
show (MixedPin w) = "Pin" ++ show w
-- | A pin on the Arduino, as viewed by the library; i.e., real-pin numbers
data IPin = InternalPin { pinNo :: Word8 }
deriving (Eq, Ord)
instance Show IPin where
show (InternalPin w) = "IPin" ++ show w
-- | Declare a pin by its index. For maximum portability, prefer 'digital'
-- and 'analog' functions, which will adjust pin indexes properly based on
-- which board the program is running on at run-time, as Arduino boards
-- differ in their pin numbers. This function is provided for cases where
-- a pin is used in mixed-mode, i.e., both for digital and analog purposes,
-- as Arduino does not really distinguish pin usage. In these cases, the
-- user has the proof obligation to make sure that the index used is supported
-- on the board with appropriate capabilities.
pin :: Word8 -> Pin
pin = MixedPin
-- | Declare an digital pin on the board. For instance, to refer to digital pin no 12
-- use 'digital' @12@.
digital :: Word8 -> Pin
digital = DigitalPin
-- | Declare an analog pin on the board. For instance, to refer to analog pin no 0
-- simply use 'analog' @0@.
--
-- Note that 'analog' @0@ on an Arduino UNO will be appropriately adjusted
-- internally to refer to pin 14, since UNO has 13 digital pins, while on an
-- Arduino MEGA, it will refer to internal pin 55, since MEGA has 54 digital pins;
-- and similarly for other boards depending on their capabilities.
-- (Also see the note on 'pin' for pin mappings.)
analog :: Word8 -> Pin
analog = AnalogPin
-- | On the Arduino, pins are grouped into banks of 8.
-- Given a pin, this function determines which port it belongs to
pinPort :: IPin -> Port
pinPort p = Port (pinNo p `quot` 8)
-- | On the Arduino, pins are grouped into banks of 8.
-- Given a pin, this function determines which index it belongs to in its port
pinPortIndex :: IPin -> Word8
pinPortIndex p = pinNo p `rem` 8
-- | The mode for a pin.
data PinMode = INPUT -- ^ Digital input
| OUTPUT -- ^ Digital output
| ANALOG -- ^ Analog input
| PWM -- ^ PWM (Pulse-Width-Modulation) output
| SERVO -- ^ Servo Motor controller
| SHIFT -- ^ Shift controller
| I2C -- ^ I2C (Inter-Integrated-Circuit) connection
| ONEWIRE
| STEPPER
| ENCODER
| SERIAL
| PULLUP
deriving (Eq, Show, Enum)
-- | A request, as sent to Arduino
data Request = SystemReset -- ^ Send system reset
| QueryFirmware -- ^ Query the Firmata version installed
| CapabilityQuery -- ^ Query the capabilities of the board
| AnalogMappingQuery -- ^ Query the mapping of analog pins
| SetPinMode IPin PinMode -- ^ Set the mode on a pin
| DigitalReport Port Bool -- ^ Digital report values on port enable/disable
| AnalogReport IPin Bool -- ^ Analog report values on pin enable/disable
| DigitalPortWrite Port Word8 Word8 -- ^ Set the values on a port digitally
| AnalogPinWrite IPin Word8 Word8 -- ^ Send an analog-write; used for servo control
| SamplingInterval Word8 Word8 -- ^ Set the sampling interval
| Pulse IPin Bool Word32 Word32 -- ^ Request for a pulse reading on a pin, value, duration, timeout
deriving Show
-- | A response, as returned from the Arduino
data Response = Firmware Word8 Word8 String -- ^ Firmware version (maj/min and indentifier
| Capabilities BoardCapabilities -- ^ Capabilities report
| AnalogMapping [Word8] -- ^ Analog pin mappings
| DigitalMessage Port Word8 Word8 -- ^ Status of a port
| AnalogMessage IPin Word8 Word8 -- ^ Status of an analog pin
| PulseResponse IPin Word32 -- ^ Repsonse to a PulseInCommand
| Unimplemented (Maybe String) [Word8] -- ^ Represents messages currently unsupported
instance Show Response where
show (Firmware majV minV n) = "Firmware v" ++ show majV ++ "." ++ show minV ++ " (" ++ n ++ ")"
show (Capabilities b) = "Capabilities:\n" ++ show b
show (AnalogMapping bs) = "AnalogMapping: " ++ showByteList bs
show (DigitalMessage p l h) = "DigitalMessage " ++ show p ++ " = " ++ showByte l ++ " " ++ showByte h
show (AnalogMessage p l h) = "AnalogMessage " ++ show p ++ " = " ++ showByte l ++ " " ++ showByte h
show (PulseResponse p v) = "PulseResponse " ++ show p ++ " = " ++ show v ++ " (microseconds)"
show (Unimplemented mbc bs) = "Unimplemeneted " ++ fromMaybe "" mbc ++ " " ++ showByteList bs
-- | Resolution, as referred to in http://firmata.org/wiki/Protocol#Capability_Query
-- TODO: Not quite sure how this is used, so merely keep it as a Word8 now
type Resolution = Word8
-- | Capabilities of a pin
data PinCapabilities = PinCapabilities {
analogPinNumber :: Maybe Word8 -- ^ Analog pin number, if any
, allowedModes :: [(PinMode, Resolution)] -- ^ Allowed modes and resolutions
}
-- | What the board is capable of and current settings
newtype BoardCapabilities = BoardCapabilities (M.Map IPin PinCapabilities)
instance Show BoardCapabilities where
show (BoardCapabilities m) = intercalate "\n" (map sh (M.toAscList m))
where sh (p, PinCapabilities{analogPinNumber, allowedModes}) = show p ++ sep ++ unwords [show md | (md, _) <- allowedModes]
where sep = maybe ": " (\i -> "[A" ++ show i ++ "]: ") analogPinNumber
-- | Data associated with a pin
data PinData = PinData {
pinMode :: PinMode
, pinValue :: Maybe (Either Bool Int)
}
deriving Show
-- | LCD's connected to the board
newtype LCD = LCD Int
deriving (Eq, Ord, Show)
-- | Hitachi LCD controller: See: <http://en.wikipedia.org/wiki/Hitachi_HD44780_LCD_controller>.
-- We model only the 4-bit variant, with RS and EN lines only. (The most common Arduino usage.)
-- The data sheet can be seen at: <http://lcd-linux.sourceforge.net/pdfdocs/hd44780.pdf>.
data LCDController = Hitachi44780 {
lcdRS :: Pin -- ^ Hitachi pin @ 4@: Register-select
, lcdEN :: Pin -- ^ Hitachi pin @ 6@: Enable
, lcdD4 :: Pin -- ^ Hitachi pin @11@: Data line @4@
, lcdD5 :: Pin -- ^ Hitachi pin @12@: Data line @5@
, lcdD6 :: Pin -- ^ Hitachi pin @13@: Data line @6@
, lcdD7 :: Pin -- ^ Hitachi pin @14@: Data line @7@
, lcdRows :: Int -- ^ Number of rows (typically 1 or 2, upto 4)
, lcdCols :: Int -- ^ Number of cols (typically 16 or 20, upto 40)
, dotMode5x10 :: Bool -- ^ Set to True if 5x10 dots are used
}
deriving Show
-- | State of the LCD, a mere 8-bit word for the Hitachi
data LCDData = LCDData {
lcdDisplayMode :: Word8 -- ^ Display mode (left/right/scrolling etc.)
, lcdDisplayControl :: Word8 -- ^ Display control (blink on/off, display on/off etc.)
, lcdGlyphCount :: Word8 -- ^ Count of custom created glyphs (typically at most 8)
, lcdController :: LCDController -- ^ Actual controller
}
-- | State of the board
data BoardState = BoardState {
boardCapabilities :: BoardCapabilities -- ^ Capabilities of the board
, analogReportingPins :: S.Set IPin -- ^ Which analog pins are reporting
, digitalReportingPins :: S.Set IPin -- ^ Which digital pins are reporting
, pinStates :: M.Map IPin PinData -- ^ For-each pin, store its data
, digitalWakeUpQueue :: [MVar ()] -- ^ Semaphore list to wake-up upon receiving a digital message
, lcds :: M.Map LCD LCDData -- ^ LCD's attached to the board
}
-- | State of the computation
data ArduinoState = ArduinoState {
message :: String -> IO () -- ^ Current debugging routine
, bailOut :: forall a. String -> [String] -> IO a -- ^ Clean-up and quit with a hopefully informative message
, port :: SerialPort -- ^ Serial port we are communicating on
, firmataID :: String -- ^ The ID of the board (as identified by the Board itself)
, boardState :: MVar BoardState -- ^ Current state of the board
, deviceChannel :: Chan Response -- ^ Incoming messages from the board
, capabilities :: BoardCapabilities -- ^ Capabilities of the board
, listenerTid :: MVar ThreadId -- ^ ThreadId of the listener
}
-- | The Arduino monad.
newtype Arduino a = Arduino (StateT ArduinoState IO a)
deriving (Functor, Applicative, Monad, MonadIO, MonadState ArduinoState)
-- | Debugging only: print the given string on stdout.
debug :: String -> Arduino ()
debug s = do f <- gets message
liftIO $ f s
-- | Bailing out: print the given string on stdout and die
die :: String -> [String] -> Arduino a
die m ms = do f <- gets bailOut
liftIO $ f m ms
-- | Which modes does this pin support?
getPinModes :: IPin -> Arduino [PinMode]
getPinModes p = do
BoardCapabilities caps <- gets capabilities
case p `M.lookup` caps of
Nothing -> return []
Just PinCapabilities{allowedModes} -> return $ map fst allowedModes
-- | Current state of the pin
getPinData :: IPin -> Arduino PinData
getPinData p = do
bs <- gets boardState
err <- gets bailOut
liftIO $ withMVar bs $ \bst ->
case p `M.lookup` pinStates bst of
Nothing -> err ("Trying to access " ++ show p ++ " without proper configuration.")
["Make sure that you use 'setPinMode' to configure this pin first."]
Just pd -> return pd
-- | Given a pin, collect the digital value corresponding to the
-- port it belongs to, where the new value of the current pin is given
-- The result is two bytes:
--
-- * First lsb: pins 0-6 on the port
-- * Second msb: pins 7-13 on the port
--
-- In particular, the result is suitable to be sent with a digital message
computePortData :: IPin -> Bool -> Arduino (Word8, Word8)
computePortData curPin newValue = do
let curPort = pinPort curPin
let curIndex = pinPortIndex curPin
bs <- gets boardState
liftIO $ modifyMVar bs $ \bst -> do
let values = [(pinPortIndex p, pinValue pd) | (p, pd) <- M.assocs (pinStates bst), curPort == pinPort p, pinMode pd `elem` [INPUT, OUTPUT]]
getVal i
| i == curIndex = newValue
| Just (Just (Left v)) <- i `lookup` values = v
| True = False
[b0, b1, b2, b3, b4, b5, b6, b7] = map getVal [0 .. 7]
lsb = foldr (\(i, b) m -> if b then m `setBit` i else m) 0 (zip [0..] [b0, b1, b2, b3, b4, b5, b6])
msb = foldr (\(i, b) m -> if b then m `setBit` (i-7) else m) 0 (zip [7..] [b7])
bst' = bst{pinStates = M.insert curPin PinData{pinMode = OUTPUT, pinValue = Just (Left newValue)}(pinStates bst)}
return (bst', (lsb, msb))
-- | Keep track of listeners on a digital message
digitalWakeUp :: MVar () -> Arduino ()
digitalWakeUp semaphore = do
bs <- gets boardState
liftIO $ modifyMVar_ bs $ \bst -> return bst{digitalWakeUpQueue = semaphore : digitalWakeUpQueue bst}
-- | Firmata commands, see: http://firmata.org/wiki/Protocol#Message_Types
data FirmataCmd = ANALOG_MESSAGE IPin -- ^ @0xE0@ pin
| DIGITAL_MESSAGE Port -- ^ @0x90@ port
| REPORT_ANALOG_PIN IPin -- ^ @0xC0@ pin
| REPORT_DIGITAL_PORT Port -- ^ @0xD0@ port
| START_SYSEX -- ^ @0xF0@
| SET_PIN_MODE -- ^ @0xF4@
| END_SYSEX -- ^ @0xF7@
| PROTOCOL_VERSION -- ^ @0xF9@
| SYSTEM_RESET -- ^ @0xFF@
deriving Show
-- | Compute the numeric value of a command
firmataCmdVal :: FirmataCmd -> Word8
firmataCmdVal (ANALOG_MESSAGE p) = 0xE0 .|. pinNo p
firmataCmdVal (DIGITAL_MESSAGE p) = 0x90 .|. portNo p
firmataCmdVal (REPORT_ANALOG_PIN p) = 0xC0 .|. pinNo p
firmataCmdVal (REPORT_DIGITAL_PORT p) = 0xD0 .|. portNo p
firmataCmdVal START_SYSEX = 0xF0
firmataCmdVal SET_PIN_MODE = 0xF4
firmataCmdVal END_SYSEX = 0xF7
firmataCmdVal PROTOCOL_VERSION = 0xF9
firmataCmdVal SYSTEM_RESET = 0xFF
-- | Convert a byte to a Firmata command
getFirmataCmd :: Word8 -> Either Word8 FirmataCmd
getFirmataCmd w = classify
where extract m | w .&. m == m = Just $ fromIntegral (w .&. 0x0F)
| True = Nothing
classify | w == 0xF0 = Right START_SYSEX
| w == 0xF4 = Right SET_PIN_MODE
| w == 0xF7 = Right END_SYSEX
| w == 0xF9 = Right PROTOCOL_VERSION
| w == 0xFF = Right SYSTEM_RESET
| Just i <- extract 0xE0 = Right $ ANALOG_MESSAGE (InternalPin i)
| Just i <- extract 0x90 = Right $ DIGITAL_MESSAGE (Port i)
| Just i <- extract 0xC0 = Right $ REPORT_ANALOG_PIN (InternalPin i)
| Just i <- extract 0xD0 = Right $ REPORT_DIGITAL_PORT (Port i)
| True = Left w
-- | Sys-ex commands, see: http://firmata.org/wiki/Protocol#Sysex_Message_Format
data SysExCmd = RESERVED_COMMAND -- ^ @0x00@ 2nd SysEx data byte is a chip-specific command (AVR, PIC, TI, etc).
| ANALOG_MAPPING_QUERY -- ^ @0x69@ ask for mapping of analog to pin numbers
| ANALOG_MAPPING_RESPONSE -- ^ @0x6A@ reply with mapping info
| CAPABILITY_QUERY -- ^ @0x6B@ ask for supported modes and resolution of all pins
| CAPABILITY_RESPONSE -- ^ @0x6C@ reply with supported modes and resolution
| PIN_STATE_QUERY -- ^ @0x6D@ ask for a pin's current mode and value
| PIN_STATE_RESPONSE -- ^ @0x6E@ reply with a pin's current mode and value
| EXTENDED_ANALOG -- ^ @0x6F@ analog write (PWM, Servo, etc) to any pin
| SERVO_CONFIG -- ^ @0x70@ set max angle, minPulse, maxPulse, freq
| STRING_DATA -- ^ @0x71@ a string message with 14-bits per char
| PULSE -- ^ @0x74@ Pulse, see: https://github.com/rwldrn/johnny-five/issues/18
| SHIFT_DATA -- ^ @0x75@ shiftOut config/data message (34 bits)
| I2C_REQUEST -- ^ @0x76@ I2C request messages from a host to an I/O board
| I2C_REPLY -- ^ @0x77@ I2C reply messages from an I/O board to a host
| I2C_CONFIG -- ^ @0x78@ Configure special I2C settings such as power pins and delay times
| REPORT_FIRMWARE -- ^ @0x79@ report name and version of the firmware
| SAMPLING_INTERVAL -- ^ @0x7A@ sampling interval
| SYSEX_NON_REALTIME -- ^ @0x7E@ MIDI Reserved for non-realtime messages
| SYSEX_REALTIME -- ^ @0x7F@ MIDI Reserved for realtime messages
deriving Show
-- | Convert a 'SysExCmd' to a byte
sysExCmdVal :: SysExCmd -> Word8
sysExCmdVal RESERVED_COMMAND = 0x00
sysExCmdVal ANALOG_MAPPING_QUERY = 0x69
sysExCmdVal ANALOG_MAPPING_RESPONSE = 0x6A
sysExCmdVal CAPABILITY_QUERY = 0x6B
sysExCmdVal CAPABILITY_RESPONSE = 0x6C
sysExCmdVal PIN_STATE_QUERY = 0x6D
sysExCmdVal PIN_STATE_RESPONSE = 0x6E
sysExCmdVal EXTENDED_ANALOG = 0x6F
sysExCmdVal SERVO_CONFIG = 0x70
sysExCmdVal STRING_DATA = 0x71
sysExCmdVal PULSE = 0x74
sysExCmdVal SHIFT_DATA = 0x75
sysExCmdVal I2C_REQUEST = 0x76
sysExCmdVal I2C_REPLY = 0x77
sysExCmdVal I2C_CONFIG = 0x78
sysExCmdVal REPORT_FIRMWARE = 0x79
sysExCmdVal SAMPLING_INTERVAL = 0x7A
sysExCmdVal SYSEX_NON_REALTIME = 0x7E
sysExCmdVal SYSEX_REALTIME = 0x7F
-- | Convert a byte into a 'SysExCmd'
getSysExCommand :: Word8 -> Either Word8 SysExCmd
getSysExCommand 0x00 = Right RESERVED_COMMAND
getSysExCommand 0x69 = Right ANALOG_MAPPING_QUERY
getSysExCommand 0x6A = Right ANALOG_MAPPING_RESPONSE
getSysExCommand 0x6B = Right CAPABILITY_QUERY
getSysExCommand 0x6C = Right CAPABILITY_RESPONSE
getSysExCommand 0x6D = Right PIN_STATE_QUERY
getSysExCommand 0x6E = Right PIN_STATE_RESPONSE
getSysExCommand 0x6F = Right EXTENDED_ANALOG
getSysExCommand 0x70 = Right SERVO_CONFIG
getSysExCommand 0x71 = Right STRING_DATA
getSysExCommand 0x75 = Right SHIFT_DATA
getSysExCommand 0x76 = Right I2C_REQUEST
getSysExCommand 0x77 = Right I2C_REPLY
getSysExCommand 0x78 = Right I2C_CONFIG
getSysExCommand 0x79 = Right REPORT_FIRMWARE
getSysExCommand 0x7A = Right SAMPLING_INTERVAL
getSysExCommand 0x7E = Right SYSEX_NON_REALTIME
getSysExCommand 0x7F = Right SYSEX_REALTIME
getSysExCommand 0x74 = Right PULSE
getSysExCommand n = Left n
-- | Keep track of pin-mode changes
registerPinMode :: IPin -> PinMode -> Arduino [Request]
registerPinMode p m = do
-- first check that the requested mode is supported for this pin
BoardCapabilities caps <- gets capabilities
case p `M.lookup` caps of
Nothing
-> die ("Invalid access to unsupported pin: " ++ show p)
("Available pins are: " : [" " ++ show k | (k, _) <- M.toAscList caps])
Just PinCapabilities{allowedModes}
| m `notElem` map fst allowedModes
-> die ("Invalid mode " ++ show m ++ " set for " ++ show p)
["Supported modes for this pin are: " ++ unwords (if null allowedModes then ["NONE"] else map show allowedModes)]
_ -> return ()
-- see if there was a mode already set for this pin
bs <- gets boardState
mbOldMode <- liftIO $ withMVar bs $ \bst ->
case p `M.lookup` pinStates bst of
Nothing -> return Nothing -- completely new, register
Just pd -> return $ Just $ pinMode pd
-- depending on old/new mode, determine what actions to take
let registerNewMode = modifyMVar_ bs $ \bst -> return bst{pinStates = M.insert p PinData{pinMode = m, pinValue = Nothing} (pinStates bst) }
case mbOldMode of
Nothing -> do liftIO registerNewMode
getModeActions p m
Just m' | m == m' -> return [] -- no mode change, nothing to do
| True -> do liftIO registerNewMode
remActs <- getRemovalActions p m'
addActs <- getModeActions p m
return $ remActs ++ addActs
-- | A mode was removed from this pin, update internal state and determine any necessary actions to remove it
getRemovalActions :: IPin -> PinMode -> Arduino [Request]
getRemovalActions p INPUT = do -- This pin is no longer digital input
bs <- gets boardState
liftIO $ modifyMVar bs $ \bst -> do
let dPins = p `S.delete` digitalReportingPins bst
port = pinPort p
acts = [DigitalReport port False | port `notElem` map pinPort (S.elems dPins)] -- no need for a digital report on this port anymore
bst' = bst { digitalReportingPins = dPins }
return (bst', acts)
getRemovalActions p ANALOG = do -- This pin is no longer analog
bs <- gets boardState
liftIO $ modifyMVar bs $ \bst -> do
let aPins = analogReportingPins bst
acts = [AnalogReport p False | p `S.member` aPins] -- no need for an analog report on this port anymore
bst' = bst { analogReportingPins = p `S.delete` aPins }
return (bst', acts)
getRemovalActions _ OUTPUT = return []
getRemovalActions p m = die ("hArduino: getRemovalActions: TBD: Unsupported mode: " ++ show m) ["On pin " ++ show p]
-- | Depending on a mode-set call, determine what further
-- actions should be executed, such as enabling/disabling pin/port reporting
getModeActions :: IPin -> PinMode -> Arduino [Request]
getModeActions p INPUT = do -- This pin is just configured for digital input
bs <- gets boardState
liftIO $ modifyMVar bs $ \bst -> do
let aPins = analogReportingPins bst
dPins = digitalReportingPins bst
port = pinPort p
acts1 = [AnalogReport p False | p `S.member` aPins] -- there was an analog report, remove it
acts2 = [DigitalReport port True | port `notElem` map pinPort (S.elems dPins)] -- there was no digital report, add it
bst' = bst { analogReportingPins = p `S.delete` analogReportingPins bst
, digitalReportingPins = p `S.insert` digitalReportingPins bst
}
return (bst', acts1 ++ acts2)
getModeActions p ANALOG = do -- This pin just configured for analog
bs <- gets boardState
liftIO $ modifyMVar bs $ \bst -> do
let aPins = analogReportingPins bst
dPins = p `S.delete` digitalReportingPins bst
port = pinPort p
acts1 = [AnalogReport p True | p `S.notMember` aPins] -- there was no analog report, add it
acts2 = [DigitalReport port False | port `notElem` map pinPort (S.elems dPins)] -- no need for a digital report, remove it
bst' = bst { analogReportingPins = p `S.insert` analogReportingPins bst
, digitalReportingPins = dPins
}
return (bst', acts1 ++ acts2)
getModeActions _ PWM = return []
getModeActions _ OUTPUT = return []
getModeActions _ SERVO = return []
getModeActions p m = die ("hArduino: getModeActions: TBD: Unsupported mode: " ++ show m) ["On pin " ++ show p]
-- | On the arduino, digital pin numbers are in 1-to-1 match with
-- the board pins. However, ANALOG pins come at an offset, determined by
-- the capabilities query. Users of the library refer to these pins
-- simply by their natural numbers, which makes for portable programs
-- between boards that have different number of digital pins. We adjust
-- for this shift here.
getInternalPin :: Pin -> Arduino IPin
getInternalPin (MixedPin p) = return $ InternalPin p
getInternalPin (DigitalPin p) = return $ InternalPin p
getInternalPin (AnalogPin p)
= do BoardCapabilities caps <- gets capabilities
case listToMaybe [realPin | (realPin, PinCapabilities{analogPinNumber = Just n}) <- M.toAscList caps, p == n] of
Nothing -> die ("hArduino: " ++ show p ++ " is not a valid analog-pin on this board.")
-- Try to be helpful in case they are trying to use a large value thinking it needs to be offset
["Hint: To refer to analog pin number k, simply use 'pin k', not 'pin (k+noOfDigitalPins)'" | p > 13]
Just rp -> return rp
-- | Similar to getInternalPin above, except also makes sure the pin is in a required mode.
convertAndCheckPin :: String -> Pin -> PinMode -> Arduino (IPin, PinData)
convertAndCheckPin what p' m = do
p <- getInternalPin p'
pd <- getPinData p
let user = userPinNo p'
board = pinNo p
bInfo
| user == board = ""
| True = " (On board " ++ show p ++ ")"
when (pinMode pd /= m) $ die ("Invalid " ++ what ++ " call on pin " ++ show p' ++ bInfo)
[ "The current mode for this pin is: " ++ show (pinMode pd)
, "For " ++ what ++ ", it must be set to: " ++ show m
, "via a proper call to setPinMode"
]
return (p, pd)
| aufheben/lambda-arduino | packages/hArduino-0.9/System/Hardware/Arduino/Data.hs | mit | 26,896 | 0 | 22 | 8,793 | 5,075 | 2,701 | 2,374 | 360 | 6 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
-- | This is a cleaned up `HelHUG.Part1` module.
--
-- The code is re-arranged into library, user and test code sections
module HelHUG.Part1b where
------------------------------------------------------------------------
-- Library code
--
import Control.Applicative
import Data.List (intercalate, sort)
import Data.Traversable (traverse)
import HelHUG.DB
import HelHUG.DB.Attribute
import Control.Monad.Error (throwError)
-- | We use DataKinds!
data Nat = Zero | Succ Nat
newtype Reference (e :: Nat -> *) = Reference { unReference :: EntityId }
type family Ref (n :: Nat) (e :: Nat -> *) :: * where
Ref Zero e = Reference e
Ref (Succ n) e = e n
------------------------------------------------------------------------
-- User code:
--
data PL (n :: Nat) = PL
{ plId :: EntityId
, plName :: String
, plUrl :: String
, plAppearedIn :: Maybe Int
, plTypingDis :: [String]
, plInfluenced :: [Ref n PL]
}
toPL :: Entity -> Maybe (PL Zero)
toPL ent = PL (entityId ent) <$> getAttr "title" ent
<*> getAttr "url" ent
<*> pure (getAttr "appearedIn" ent)
<*> getAttr "typingDiscipline" ent
<*> (fmap Reference <$> getAttr "influenced" ent)
-- Let's write some magic!
class IsEntity (e :: Nat -> *) n where
unwrap :: Ref n e -> DBMonad (e n)
instance IsEntity PL Zero where
unwrap (Reference eid) = do
entity <- askEntity eid
case toPL entity of
Just pl -> return pl
Nothing -> throwError $ "can't parse entity as PL -- " ++ show eid
instance IsEntity PL n => IsEntity PL (Succ n) where
unwrap pl = mk <$> traverse unwrap (plInfluenced pl)
where mk influenced = pl { plInfluenced = influenced }
------------------------------------------------------------------------
-- Test code
--
-- $setup
-- >>> Right db <- readDB "pl.json"
mlEntityId :: EntityId
mlEntityId = EntityId 89
-- | Let's try ML
-- >>> fmap plName <$> runDBMonad ml db
-- Right (Just "ML")
ml :: DBMonad (Maybe (PL Zero))
ml = toPL <$> askEntity mlEntityId
-- And we can port what we had:
prettyPL' :: PL n -> String -> String
prettyPL' PL {..} influencedStr =
intercalate "\n" [ "name: " ++ plName
, "url: " ++ plUrl
, "appeared in: " ++ maybe "-" show plAppearedIn
, "typing: " ++ intercalate ", " plTypingDis
, "influenced: " ++ influencedStr
]
-- | And we can continue with what we had:
--
-- >>> let Right (Just pl) = runDBMonad ml db
-- >>> putStrLn $ prettyPL pl
-- name: ML
-- url: http://en.wikipedia.org/wiki/ML_(programming_language)
-- appeared in: 1973
-- typing: static, strong, inferred, safe
-- influenced: [88,98,105,108,117,122,185,277,287,288]
prettyPL :: PL Zero -> String
prettyPL pl @ PL { plInfluenced = influenced } =
prettyPL' pl . show . sort . map (unEntityId . unReference) $ influenced
-- | Let's write more human friendly renderer:
--
-- >>> let Right (Just pl) = runDBMonad ml db
-- >>> let Right pl' = runDBMonad (unwrap pl) db
-- >>> putStrLn $ prettierPL pl'
-- name: ML
-- url: http://en.wikipedia.org/wiki/ML_(programming_language)
-- appeared in: 1973
-- typing: static, strong, inferred, safe
-- influenced: C++, Clojure, Cyclone, Erlang, F Sharp, Felix, Haskell, Miranda, Opa, Scala
prettierPL :: PL (Succ Zero) -> String
prettierPL pl @ PL { plInfluenced = influenced } =
prettyPL' pl . intercalate ", " . sort . map plName $ influenced
-- | And we can generalise:
--
-- >>> let Right (Just pl) = runDBMonad ml db
-- >>> let Right pl' = runDBMonad (unwrap pl) db
-- >>> putStrLn $ prettierPL' pl'
-- name: ML
-- url: http://en.wikipedia.org/wiki/ML_(programming_language)
-- appeared in: 1973
-- typing: static, strong, inferred, safe
-- influenced: C++, Clojure, Cyclone, Erlang, F Sharp, Felix, Haskell, Miranda, Opa, Scala
prettierPL' :: PL (Succ n) -> String
prettierPL' pl @ PL { plInfluenced = influenced } =
prettyPL' pl . intercalate ", " . sort . map plName $ influenced
-- So now we could go deeper into the influence hierarchy:
mlUnwrappedTwice :: DBMonad (PL (Succ (Succ Zero)))
mlUnwrappedTwice = return (Reference mlEntityId) >>= unwrap >>= unwrap >>= unwrap
-- | But we could apply `prettierPL'` still
--
-- >>> let Right pl = runDBMonad mlUnwrappedTwice db
-- >>> putStrLn $ prettierPL' pl
-- name: ML
-- url: http://en.wikipedia.org/wiki/ML_(programming_language)
-- appeared in: 1973
-- typing: static, strong, inferred, safe
-- influenced: C++, Clojure, Cyclone, Erlang, F Sharp, Felix, Haskell, Miranda, Opa, Scala
-- | An we can get influenced influenced:
--
-- >>> runDBMonad (Data.List.nub . sort . map plName . concatMap plInfluenced . plInfluenced <$> mlUnwrappedTwice) db
-- Right ["Ada","Agda","Akka (toolkit)","Bluespec, Inc.","C Sharp","C++11","C99",...
-- | GHC is smart enough to infer types for complicated expressions like that:
--
-- >>> :t \pl -> Data.List.nub . sort . map plName . concatMap plInfluenced . plInfluenced $ pl
-- \pl -> Data.List.nub . sort . map plName . concatMap plInfluenced . plInfluenced $ pl
-- :: (Ref n2 PL ~ PL n1, Ref n1 PL ~ PL n) => PL n2 -> [String]
-- | Error case!
--
-- >>> runDBMonad (prettierPL' <$> return (Reference mlEntityId) >>= unwrap) db
-- ...
-- Couldn't match expected type ...
-- ...
| phadej/helhug-types | src/HelHUG/Part1b.hs | mit | 5,724 | 3 | 12 | 1,294 | 948 | 531 | 417 | 65 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module BasisBladeTests where
import Test.Framework.TH
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck hiding ( (.&.) )
import Data.AEq
import Data.Bits
import Numeric.GeometricAlgebra.BasisBlade
import Numeric.LinearCombination
tests = $(testGroupGenerator)
prop_outerAntisymmetry x y =
isVector x && isVector y && (x /= y) ==> c == - c'
where c :* _ = x `out` y
c' :* _ = y `out` x
prop_outerGrade x y =
(outProd /= 0) ==> grade outProd == grade x + grade y
where _ :* outProd = x `out` y
prop_geoGrade x y =
grade geoProd == grade x + grade y - 2*common
where common = popCount $ x .&. y
_ :* geoProd = x `geo` y | pnutus/geometric-algebra | tests/BasisBladeTests.hs | mit | 735 | 0 | 9 | 162 | 263 | 143 | 120 | 22 | 1 |
module Data.SQP
( Problem (..)
, optimize
) where
import Numeric.LinearAlgebra.HMatrix
import Numeric.Minimization.QuadProgPP
import Debug.Trace
data Problem = Problem
{ _cost :: Vector Double -> Double
, _approxCost :: Vector Double
-> (Matrix Double, Vector Double, Double)
, _trueIneqs :: Vector Double -> Vector Double
, _approxAffineIneqs :: Vector Double
-> (Matrix Double, Vector Double)
, _eqs :: Vector Double -> Vector Double
, _approxEqs :: Vector Double -> (Matrix Double, Vector Double)
, _numVariables :: Int
, _numIneqs :: Int
, _numEqs :: Int
}
stepAcceptanceThreshold :: Double
stepAcceptanceThreshold = 0.25
trustShrinkFactor :: Double
trustShrinkFactor = 0.1
trustExpandFactor :: Double
trustExpandFactor = 1.5
constraintPenaltyScalingFactor :: Double
constraintPenaltyScalingFactor = 10
minTrustSize :: Double
minTrustSize = 1e-4
minModelImprove :: Double
minModelImprove = 1e-4
minModelImproveRatio :: Double
minModelImproveRatio = negate $ read "Infinity"
constraintSatisfactionThreshold :: Double
constraintSatisfactionThreshold = 1e-4
initTrustSize :: Double
initTrustSize = 0.1
initPenalty :: Double
initPenalty = 10
evalMerit :: Problem -> Double -> Vector Double -> Double
evalMerit problem penaltyParam x =
let cost = _cost problem x
penalty =
penaltyParam * sum (map (max 0.0) $ toList $ _trueIneqs problem x) +
penaltyParam * sum (map abs $ toList $ _eqs problem x)
in cost + penalty
optimize :: Problem
-> Vector Double -- xInitial
-> (Vector Double, Double)
optimize problem xInit =
findSuitableConstraintPenalty problem xInit initTrustSize initPenalty
findSuitableConstraintPenalty :: Problem
-> Vector Double -- x
-> Double -- trust region size
-> Double -- constraint penalty
-- xNew, trueMerit
-> (Vector Double, Double)
findSuitableConstraintPenalty problem x trustSize penaltyParam =
let (xNew, trueMerit, newTrustSize) =
reconvexify problem x trustSize penaltyParam
ineqsSatisfied = all (<= constraintSatisfactionThreshold) $
toList $ _trueIneqs problem xNew
eqsSatisfied = all ((<= constraintSatisfactionThreshold) . abs) $
toList $ _eqs problem xNew
constraintsSatisfied = ineqsSatisfied && eqsSatisfied
in if constraintsSatisfied
then (xNew, trueMerit)
else let penalty' = penaltyParam * constraintPenaltyScalingFactor
in findSuitableConstraintPenalty
problem xNew newTrustSize penalty'
evalQuadratic :: (Matrix Double, Vector Double, Double)
-> Vector Double
-> Double
evalQuadratic (m, b, c) x =
(x `dot` ((0.5 * (m #> x)) + b)) + c
evalLinear :: (Matrix Double, Vector Double)
-> Vector Double
-> Vector Double
evalLinear (m, b) x = (m #> x) + b
reconvexify :: Problem
-> Vector Double -- x
-> Double -- trust region size
-> Double -- constraint penalty
-- xNew, newTrueMerit, newTrustSize
-> (Vector Double, Double, Double)
reconvexify problem x trustSize penaltyParam =
let convexCost = _approxCost problem x
convexIneqs = _approxAffineIneqs problem x
convexEqs = _approxEqs problem x
trueMerit = evalMerit problem penaltyParam x
trustResult = findSuitableTrustStep problem x convexCost
convexIneqs convexEqs trueMerit trustSize
penaltyParam
in case trustResult of
Reconvexify xNew newMerit newTrustSize ->
reconvexify problem xNew newTrustSize penaltyParam
Finished xNew newMerit newTrustSize ->
(xNew, newMerit, newTrustSize)
data TrustStepResult = -- x merit trustSize
Reconvexify (Vector Double) Double Double
| Finished (Vector Double) Double Double
deriving (Show)
findSuitableTrustStep :: Problem
-> Vector Double -- x
-- convexified cost
-> (Matrix Double, Vector Double, Double)
-- convexified inequality constraints
-> (Matrix Double, Vector Double)
-- convexified equality constraints
-> (Matrix Double, Vector Double)
-> Double -- old true merit
-> Double -- trust region size
-> Double -- constraint penalty parameter
-- xNew, newTrueMerit, newTrustSize
-> TrustStepResult
findSuitableTrustStep
problem x convexCost convexIneq convexEq oldTrueMerit trustSize penaltyParam =
let trustStep =
trustRegionStep problem x convexCost convexIneq convexEq oldTrueMerit
trustSize penaltyParam
in case trace (show trustStep) trustStep of
Reject -> let newTrustSize = trustSize * trustShrinkFactor
in findSuitableTrustStep problem x convexCost convexIneq
convexEq oldTrueMerit newTrustSize penaltyParam
Accept xNew newTrueMerit ->
let newTrustSize = trustSize * trustExpandFactor
in Reconvexify xNew newTrueMerit newTrustSize
Converged xNew newTrueMerit ->
let newTrustSize =
max trustSize $ (minTrustSize / trustShrinkFactor) * 1.5
in Finished xNew newTrueMerit newTrustSize
data IterationResult = Reject
-- xNew newMerit
| Accept (Vector Double) Double
| Converged (Vector Double) Double
deriving (Show)
trustRegionStep :: Problem
-> Vector Double -- x
-- convexified cost
-> (Matrix Double, Vector Double, Double)
-- convexified inequality constraints
-> (Matrix Double, Vector Double)
-- convexified equality constraints
-> (Matrix Double, Vector Double)
-> Double -- old true merit
-> Double -- trust region size
-> Double -- constraint penalty parameter
-> IterationResult
trustRegionStep
problem x convexCost convexIneq convexEq oldTrueMerit trustSize penaltyParam =
let (xNew, modelMerit) = solveQuadraticSubproblem problem x convexCost
convexIneq convexEq trustSize penaltyParam
trueMerit = evalMerit problem penaltyParam xNew
trueImprove = oldTrueMerit - trueMerit
modelImprove = oldTrueMerit - modelMerit
in if modelImprove < -1e-2 -- why so high? our convexification?
then error $ "Model improvement got worse: " ++
show (modelImprove, modelMerit, oldTrueMerit, trueMerit)
else
if trustSize < minTrustSize ||
modelImprove < minModelImprove ||
modelImprove / oldTrueMerit < minModelImproveRatio
then Converged x oldTrueMerit
else
if trueImprove > 0.0 &&
trueImprove / modelImprove > stepAcceptanceThreshold
then Accept xNew trueMerit
else Reject
solveQuadraticSubproblem :: Problem
-> Vector Double
-- convex cost
-> (Matrix Double, Vector Double, Double)
-- convexified inequality constraints
-> (Matrix Double, Vector Double)
-- convexified equality constraints
-> (Matrix Double, Vector Double)
-> Double -- trust region size
-> Double -- constraint penalty parameter
-> (Vector Double, Double) -- new x, model merit
solveQuadraticSubproblem
problem x (costMatrix, costVector, costConstant)
(approxIneqMatrix, approxIneqVector) (approxEqMatrix, approxEqVector)
trustSize penaltyParam =
-- We approximate each nonlinear inequality as |ax + b|^+. For each
-- of these, we introduce a new optimization variable t (i.e., a
-- slack variable) that comes with two inequalities:
--
-- 0 <= t
--
-- ax + b <= t
--
-- Each nonlinear equality as |ax + b|. For each of these, two new
-- optimization variables s and t with following properties:
--
-- -s <= 0
-- -t <= 0
-- s - t = ax + b
let numIneqs = _numIneqs problem
numEqs = _numEqs problem
numVariables = _numVariables problem
costMatrixWithSlacks =
diagBlock [ costMatrix
, konst 0.0 (numIneqs, numIneqs)
, konst 0.0 (2 * numEqs, 2 * numEqs)]
-- LET'S MAKE COST SPD
(l, v) = eigSH costMatrixWithSlacks
positiveEigVals = cmap (max 1e-12) l
augmentedCostMatrix = v <> diag positiveEigVals <> tr v
augmentedCostVector = vjoin [costVector
, konst 1.0 numIneqs
, konst 1.0 $ 2 * numEqs]
augmentedIneqMatrix =
((scalar penaltyParam * approxIneqMatrix) |||
negate (ident numIneqs) |||
konst 0.0 (numIneqs, 2 * numEqs)) ===
(konst 0.0 (numIneqs + 2 * numEqs, numVariables) |||
negate (ident $ numIneqs + 2 * numEqs))
augmentedIneqVector =
vjoin [ scalar penaltyParam * approxIneqVector
, konst 0.0 $ numIneqs + 2 * numEqs ]
ineqMatrixWithTrustConstraints =
augmentedIneqMatrix ===
(ident numVariables ||| konst 0.0 (numVariables, numIneqs + 2 * numEqs)) ===
(negate (ident numVariables) ||| konst 0.0 (numVariables, numIneqs + 2 * numEqs))
ineqVectorWithTrustConstraints =
vjoin [ augmentedIneqVector
, negate (x + scalar trustSize)
, x - scalar trustSize ]
augmentedEqMatrix =
scalar penaltyParam * approxEqMatrix |||
konst 0.0 (numEqs, numIneqs) |||
negate (ident numEqs) |||
ident numEqs
augmentedEqVector = scalar penaltyParam * approxEqVector
-- inequalities are given as ax + b <= 0, but quadprog++ wants
-- a'x + b' >= 0
result = solveQuadProg
(augmentedCostMatrix, augmentedCostVector)
(Just (augmentedEqMatrix, augmentedEqVector)) $
Just ((-ineqMatrixWithTrustConstraints),
(-ineqVectorWithTrustConstraints))
in case result of
Left e -> error $ show e
Right (xNewAugmented, newMeritHomogenous) ->
let xNew = subVector 0 numVariables xNewAugmented
newMerit = newMeritHomogenous + costConstant
-- Compute the merit of the approximation without regularization
cost = evalQuadratic (costMatrix, costVector, costConstant) xNew
ineqViolations =
evalLinear (approxIneqMatrix, approxIneqVector) xNew
ineqPenalty =
penaltyParam * (sum $ map (max 0.0) $ toList ineqViolations)
eqViolations = evalLinear (approxEqMatrix, approxEqVector) xNew
eqPenalty =
penaltyParam * (sum $ map abs $ toList eqViolations)
meritNoReg = cost + ineqPenalty + eqPenalty
-- DEBUG
meritError = abs $ newMerit - meritNoReg
in if meritError / (abs meritNoReg) > 0.5
then error $ "merits don't match!" ++ show (meritNoReg, newMerit)
else (xNew, meritNoReg)
| giogadi/hs-trajopt | lib-src/Data/SQP.hs | mit | 11,798 | 0 | 20 | 3,944 | 2,493 | 1,323 | 1,170 | 226 | 4 |
module Hablog.Data
( Page, PageT
, getConfig, runDatabase
) where
import Hablog.Data.RequestState
import Hablog.Data.Page
type Page = PageT RequestState IO
| garrettpauls/Hablog | src/Hablog/Data.hs | mit | 159 | 0 | 5 | 23 | 43 | 27 | 16 | 6 | 0 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
module Lib where
import Control.Monad.Trans
import Crypto.Hash ( Digest
, SHA256
, digestFromByteString
)
import Crypto.Hash.SHA256
import Text.Read (readMaybe)
import Data.Aeson
import Data.Binary
import Data.ByteString.Char8 (pack)
import Data.Time.Clock.POSIX
import GHC.Generics
import Text.PrettyPrint.GenericPretty
-- the main data type for our blockchain
data Block = Block { index :: Int
, previousHash :: String
, timestamp :: Int
, blockData :: String
, nonce :: Int
, blockHash :: String
} deriving (Show, Read, Eq, Generic)
-- http params to add a block to the chain
newtype BlockArgs = BlockArgs{blockBody :: String}
deriving (Show, Eq, Generic)
instance ToJSON BlockArgs
instance FromJSON BlockArgs
instance ToJSON Block
instance FromJSON Block
instance Binary Block
instance Out Block
-- unix timestamp as an int
epoch :: IO Int
epoch = round `fmap` getPOSIXTime
-- hashes a string and returns a hex digest
sha256 :: String -> Maybe (Digest SHA256)
sha256 = digestFromByteString . hash . pack
-- abstracted hash function that takes a string
-- to hash and returns a hex string
hashString :: String -> String
hashString =
maybe (error "Something went wrong generating a hash") show . sha256
calculateBlockHash :: Block -> String
calculateBlockHash (Block i p t b n _) =
hashString $ concat [show i, p, show t, b, show n]
-- returns a copy of the block with the hash set
setBlockHash :: Block -> Block
setBlockHash block = block {blockHash = calculateBlockHash block}
-- returns a copy of the block with a valid nonce and hash set
setNonceAndHash :: Block -> Block
setNonceAndHash block = setBlockHash $ block {nonce = findNonce block}
-- Rudimentary proof-of-work (POW): ensures that a block hash
-- is less than a certain value (i.e. contains a certain
-- amount of leading zeroes).
-- In our case, it's 4 leading zeroes. We're using the Integer type
-- since the current target is higher than the max for Int.
-- POW is useful because with this imposed difficulty to add values to
-- the blockchain, it becomes exponentially less feasible to edit the
-- chain - one would need to regenerate an entirely new valid chain
-- after the edited block(s)
difficultyTarget :: Integer
difficultyTarget =
0x0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
-- checks whether the provided block hash satisfies
-- our PoW requirement
satisfiesPow :: String -> Bool
satisfiesPow bHash =
maybe
(error $ "Something is wrong with the provided hash: " ++ bHash)
(< difficultyTarget)
(readMaybe ("0x" ++ bHash) :: Maybe Integer)
-- Recursively finds a nonce that satisfies the difficulty target
-- If our blockHash already satisfies the PoW, return the current nonce
-- If not, increment the nonce and try again
-- TODO - Handle nonce overflow.
findNonce :: Block -> Int
findNonce block = do
let bHash = calculateBlockHash block
currentNonce = nonce block
if satisfiesPow bHash
then currentNonce
else findNonce $ block {nonce = currentNonce + 1}
-- a hardcoded initial block, we need this to make sure all
-- nodes have the same starting point, so we have a hard coded
-- frame of reference to detect validity
initialBlock :: Block
initialBlock = do
let block = Block 0 "0" 0 "initial data" 0 ""
setNonceAndHash block
-- a new block is valid if its index is 1 higher, its
-- previous hash points to our last block, and its hash is computed
-- correctly
isValidNewBlock :: Block -> Block -> Bool
isValidNewBlock prev next
| index prev + 1 == index next &&
blockHash prev == previousHash next &&
blockHash next == calculateBlockHash next &&
satisfiesPow (blockHash next) = True
| otherwise = False
-- a chain is valid if it starts with our hardcoded initial
-- block and every block is valid with respect to the previous
isValidChain :: [Block] -> Bool
isValidChain chain = case chain of
[] -> True
[x] -> x == initialBlock
(x:xs) ->
let blockPairs = zip chain xs in
x == initialBlock &&
all (uncurry isValidNewBlock) blockPairs
-- return the next block given a previous block and some data to put in it
mineBlockFrom :: (MonadIO m) => Block -> String -> m Block
mineBlockFrom lastBlock stringData = do
time <- liftIO epoch
let block = Block { index = index lastBlock + 1
, previousHash = blockHash lastBlock
, timestamp = time
, blockData = stringData
, nonce = 0
, blockHash = "will be changed"
}
return $ setNonceAndHash block
| aviaviavi/legion | src/Lib.hs | mit | 5,221 | 0 | 15 | 1,469 | 926 | 507 | 419 | 92 | 3 |
{-# LANGUAGE NamedFieldPuns, FlexibleInstances, FlexibleContexts, GeneralizedNewtypeDeriving #-}
{-
Copyright (C) 2012-2017 Jimmy Liang, Kacper Bak, Michal Antkiewicz <http://gsd.uwaterloo.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}
module Language.Clafer.Intermediate.ResolverType (resolveTModule) where
import Language.ClaferT
import Language.Clafer.Common
import Language.Clafer.Intermediate.Intclafer hiding (uid)
import Language.Clafer.Intermediate.Desugarer
import Language.Clafer.Intermediate.TypeSystem
import Language.Clafer.Front.PrintClafer
import Control.Applicative
import Control.Exception (assert)
import Control.Lens ((&), (%~), traversed)
import Control.Monad.Except
import Control.Monad.List
import Control.Monad.Reader
import Data.Either
import Data.List
import Data.Maybe
import Prelude hiding (exp)
type TypeDecls = [(String, IType)]
data TypeInfo = TypeInfo {iTypeDecls::TypeDecls, iUIDIClaferMap::UIDIClaferMap, iCurThis::IClafer, iCurPath::Maybe IType}
newtype TypeAnalysis a = TypeAnalysis (ReaderT TypeInfo (Either ClaferSErr) a)
deriving (MonadError ClaferSErr, Monad, Functor, MonadReader TypeInfo, Applicative)
-- return the type of a UID but give preference to local declarations in quantified expressions, which shadow global names
typeOfUid :: MonadTypeAnalysis m => UID -> m IType
typeOfUid uid = (fromMaybe (TClafer [uid]) . lookup uid) <$> typeDecls
class (Functor m, Monad m) => MonadTypeAnalysis m where
-- What "this" refers to
curThis :: m IClafer
localCurThis :: IClafer -> m a -> m a
-- The next path is a child of curPath (or Nothing)
curPath :: m (Maybe IType)
localCurPath :: IType -> m a -> m a
-- Extra declarations
typeDecls :: m TypeDecls
localDecls :: TypeDecls -> m a -> m a
instance MonadTypeAnalysis TypeAnalysis where
curThis = TypeAnalysis $ asks iCurThis
localCurThis newThis (TypeAnalysis d) =
TypeAnalysis $ local setCurThis d
where
setCurThis t = t{iCurThis = newThis}
curPath = TypeAnalysis $ asks iCurPath
localCurPath newPath (TypeAnalysis d) =
TypeAnalysis $ local setCurPath d
where
setCurPath t = t{iCurPath = Just newPath}
typeDecls = TypeAnalysis $ asks iTypeDecls
localDecls extra (TypeAnalysis d) =
TypeAnalysis $ local addTypeDecls d
where
addTypeDecls t@TypeInfo{iTypeDecls = c} = t{iTypeDecls = extra ++ c}
instance MonadTypeAnalysis m => MonadTypeAnalysis (ListT m) where
curThis = lift curThis
localCurThis = mapListT . localCurThis
curPath = lift curPath
localCurPath = mapListT . localCurPath
typeDecls = lift typeDecls
localDecls = mapListT . localDecls
instance MonadTypeAnalysis m => MonadTypeAnalysis (ExceptT ClaferSErr m) where
curThis = lift curThis
localCurThis = mapExceptT . localCurThis
curPath = lift curPath
localCurPath = mapExceptT . localCurPath
typeDecls = lift typeDecls
localDecls = mapExceptT . localDecls
-- | Type inference and checking
runTypeAnalysis :: TypeAnalysis a -> IModule -> Either ClaferSErr a
runTypeAnalysis (TypeAnalysis tc) imodule = runReaderT tc $ TypeInfo [] (createUidIClaferMap imodule) undefined Nothing
claferWithUid :: (Monad m) => UIDIClaferMap -> String -> m IClafer
claferWithUid uidIClaferMap' u = case findIClafer uidIClaferMap' u of
Just c -> return c
Nothing -> fail $ "ResolverType.claferWithUid: " ++ u ++ " not found!"
parentOf :: (Monad m) => UIDIClaferMap -> UID -> m UID
parentOf uidIClaferMap' c = case _parentUID <$> findIClafer uidIClaferMap' c of
Just u -> return u
Nothing -> fail $ "ResolverType.parentOf: " ++ c ++ " not found!"
{-
- C is an direct child of B.
-
- abstract A
- C // C - child
- B : A // B - parent
-}
isIndirectChild :: (Monad m) => UIDIClaferMap -> UID -> UID -> m Bool
isIndirectChild uidIClaferMap' child parent = do
(_:allSupers) <- hierarchy uidIClaferMap' parent
childOfSupers <- mapM ((isChild uidIClaferMap' child)._uid) allSupers
return $ or childOfSupers
isChild :: (Monad m) => UIDIClaferMap -> UID -> UID -> m Bool
isChild uidIClaferMap' child parent =
case findIClafer uidIClaferMap' child of
Nothing -> return False
Just childIClafer -> do
let directChild = (parent == _parentUID childIClafer)
indirectChild <- isIndirectChild uidIClaferMap' child parent
return $ directChild || indirectChild
str :: IType -> String
str t =
case unionType t of
[t'] -> t'
ts -> "[" ++ intercalate "," ts ++ "]"
showType :: PExp -> String
showType PExp{ _iType=Nothing } = "unknown type"
showType PExp{ _iType=(Just t) } = show t
data TAMode
= TAReferences -- ^ Phase one: only process references
| TAExpressions -- ^ Phase two: only process constraints and goals
resolveTModule :: (IModule, GEnv) -> Either ClaferSErr IModule
resolveTModule (imodule, _) =
case runTypeAnalysis (analysisReferences $ _mDecls imodule) imodule of
Right mDecls' -> case runTypeAnalysis (analysisExpressions $ mDecls') imodule{_mDecls = mDecls'} of
Right mDecls'' -> return imodule{_mDecls = mDecls''}
Left err -> throwError err
Left err -> throwError err
where
analysisReferences = mapM (resolveTElement TAReferences rootIdent)
analysisExpressions = mapM (resolveTElement TAExpressions rootIdent)
-- Phase one: only process references
resolveTElement :: TAMode -> String -> IElement -> TypeAnalysis IElement
resolveTElement TAReferences _ (IEClafer iclafer) =
do
uidIClaferMap' <- asks iUIDIClaferMap
reference' <- case _reference iclafer of
Nothing -> return Nothing
Just originalReference -> do
refs' <- resolveTPExp $ _ref originalReference
case refs' of
[] -> return Nothing
[ref'] -> return $ refWithNewType uidIClaferMap' originalReference ref'
(ref':_) -> return $ refWithNewType uidIClaferMap' originalReference ref'
elements' <- mapM (resolveTElement TAReferences (_uid iclafer)) (_elements iclafer)
return $ IEClafer iclafer{_elements = elements', _reference=reference'}
where
refWithNewType uMap oRef r = let
r' = r & iType.traversed %~ (addHierarchy uMap)
in case _iType r' of
Nothing -> Nothing
Just t -> if isTBoolean t
then Nothing
else Just $ oRef{_ref=r'}
resolveTElement TAReferences _ iec@IEConstraint{} = return iec
resolveTElement TAReferences _ ieg@IEGoal{} = return ieg
-- Phase two: only process constraints and goals
resolveTElement TAExpressions _ (IEClafer iclafer) =
do
elements' <- mapM (resolveTElement TAExpressions (_uid iclafer)) (_elements iclafer)
return $ IEClafer iclafer{_elements = elements'}
resolveTElement TAExpressions parent' (IEConstraint _isHard _pexp) =
IEConstraint _isHard <$> (testBoolean =<< resolveTConstraint parent' _pexp)
where
testBoolean pexp' =
do
unless (isTBoolean $ typeOf pexp') $
throwError $ SemanticErr (_inPos pexp') ("A constraint requires an expression of type 'TBoolean' but got '" ++ showType pexp' ++ "'")
return pexp'
resolveTElement TAExpressions parent' (IEGoal isMaximize' pexp') =
IEGoal isMaximize' <$> resolveTConstraint parent' pexp'
resolveTConstraint :: String -> PExp -> TypeAnalysis PExp
resolveTConstraint curThis' constraint =
do
uidIClaferMap' <- asks iUIDIClaferMap
curThis'' <- claferWithUid uidIClaferMap' curThis'
head <$> localCurThis curThis'' (resolveTPExp constraint :: TypeAnalysis [PExp])
resolveTPExp :: PExp -> TypeAnalysis [PExp]
resolveTPExp p =
do
x <- resolveTPExp' p
case partitionEithers x of
(f:_, []) -> throwError f -- Case 1: Only fails. Complain about the first one.
([], []) -> throwError $ SemanticErr (_inPos p) ("No results but no errors for " ++ show p) -- Case 2: No success and no error message. Bug.
(_, xs) -> return xs -- Case 3: At least one success.
resolveTPExp' :: PExp -> TypeAnalysis [Either ClaferSErr PExp]
resolveTPExp' p@PExp{_inPos, _exp = IClaferId{_sident = "dref"}} = do
uidIClaferMap' <- asks iUIDIClaferMap
runListT $ runExceptT $ do
curPath' <- curPath
case curPath' of
Just curPath'' -> do
case concatMap (getTMaps uidIClaferMap') $ getTClafers uidIClaferMap' curPath'' of
[t'] -> return $ p `withType` t'
(t':_) -> return $ p `withType` t'
[] -> throwError $ SemanticErr _inPos ("Cannot deref from type '" ++ str curPath'' ++ "'")
Nothing -> throwError $ SemanticErr _inPos ("Cannot deref at the start of a path")
resolveTPExp' p@PExp{_inPos, _exp = IClaferId{_sident = "parent"}} = do
uidIClaferMap' <- asks iUIDIClaferMap
runListT $ runExceptT $ do
curPath' <- curPath
case curPath' of
Just curPath'' -> do
parent' <- fromUnionType <$> runListT (parentOf uidIClaferMap' =<< liftList (unionType curPath''))
when (isNothing parent') $
throwError $ SemanticErr _inPos "Cannot parent from root"
let result = p `withType` fromJust parent'
return result
Nothing -> throwError $ SemanticErr _inPos "Cannot parent at the start of a path"
resolveTPExp' p@PExp{_exp = IClaferId{_sident = "integer"}} = runListT $ runExceptT $ return $ p `withType` TInteger
resolveTPExp' p@PExp{_exp = IClaferId{_sident = "int"}} = runListT $ runExceptT $ return $ p `withType` TInteger
resolveTPExp' p@PExp{_exp = IClaferId{_sident = "string"}} = runListT $ runExceptT $ return $ p `withType` TString
resolveTPExp' p@PExp{_exp = IClaferId{_sident = "double"}} = runListT $ runExceptT $ return $ p `withType` TDouble
resolveTPExp' p@PExp{_exp = IClaferId{_sident = "real"}} = runListT $ runExceptT $ return $ p `withType` TReal
resolveTPExp' p@PExp{_inPos, _exp = IClaferId{_sident="this"}} =
runListT $ runExceptT $ do
sident' <- _uid <$> curThis
result <- (p `withType`) <$> typeOfUid sident'
return result
<++>
addDref result -- Case 2: Dereference the sident 1..* times
resolveTPExp' p@PExp{_inPos, _exp = IClaferId{_sident, _isTop}} = do
uidIClaferMap' <- asks iUIDIClaferMap
runListT $ runExceptT $ do
curPath' <- curPath
sident' <- if _sident == "this" then _uid <$> curThis else return _sident
when (isJust curPath') $ do
c <- mapM (isChild uidIClaferMap' sident') $ unionType $ fromJust curPath'
let parentId' = str (fromJust curPath')
unless (or c || parentId' == "root") $ throwError $ SemanticErr _inPos ("'" ++ sident' ++ "' is not a child of type '" ++ parentId' ++ "'")
result <- (p `withType`) <$> typeOfUid sident'
if _isTop
then return result -- Case 1: Use the sident
<++>
addDref result -- Case 2: Dereference the sident 1..* times
<++>
addSome result
else return result -- all not top-level identifiers must be in a path
resolveTPExp' p@PExp{_inPos, _exp} =
runListT $ runExceptT $ (case _exp of
e@IFunExp {_op = ".", _exps = [arg1, arg2]} -> do
(iType', exp') <- do
arg1' <- lift $ ListT $ resolveTPExp arg1
localCurPath (typeOf arg1') $ do
arg2' <- liftError $ lift $ ListT $ resolveTPExp arg2
(case _iType arg2' of
Just (t'@TClafer{}) -> return (t', e{_exps = [arg1', arg2']})
Just (TMap{_ta=t'}) -> return (t', e{_exps = [arg1', arg2']})
_ -> fail $ "Function '.' cannot be performed on " ++ showType arg1' ++ "\n.\n " ++ showType arg2')
let result = p{_iType = Just iType', _exp = exp'}
return result -- Case 1: Use the sident
<++>
addDref result -- Case 2: Dereference the sident 1..* times
<++>
addSome result
_ -> do
(iType', exp') <- ExceptT $ ListT $ resolveTExp _exp
return p{_iType = Just iType', _exp = exp'})
where
resolveTExp :: IExp -> TypeAnalysis [Either ClaferSErr (IType, IExp)]
resolveTExp e@(IInt _) = runListT $ runExceptT $ return (TInteger, e)
resolveTExp e@(IDouble _) = runListT $ runExceptT $ return (TDouble, e)
resolveTExp e@(IReal _) = runListT $ runExceptT $ return (TReal, e)
resolveTExp e@(IStr _) = runListT $ runExceptT $ return (TString, e)
resolveTExp e@IFunExp {_op, _exps = [arg]} =
runListT $ runExceptT $ do
arg' <- lift $ ListT $ resolveTPExp arg
let t = typeOf arg'
let
test c =
unless c $
throwError $ SemanticErr _inPos ("Function '" ++ _op ++ "' cannot be performed on " ++ _op ++ " '" ++ showType arg' ++ "'")
let result
| _op == iNot = test (isTBoolean t) >> return TBoolean
| _op == iCSet = return TInteger
| _op == iSumSet = test (isTInteger t) >> return TInteger
| _op == iProdSet = test (isTInteger t) >> return TInteger
| _op `elem` [iMin, iMinimum, iMaximum, iMinimize, iMaximize] = test (numeric t) >> return t
| otherwise = assert False $ error $ "Unknown op '" ++ _op ++ "'"
result' <- result
return (result', e{_exps = [arg']})
resolveTExp e@IFunExp {_op = "++", _exps = [arg1, arg2]} = do
-- arg1s' <- resolveTPExp arg1
-- arg2s' <- resolveTPExp arg2
-- let union' a b = typeOf a +++ typeOf b
-- return [ return (union' arg1' arg2', e{_exps = [arg1', arg2']})
-- | (arg1', arg2') <- sortBy (comparing $ length . unionType . uncurry union') $ liftM2 (,) arg1s' arg2s'
-- , not (isTBoolean $ typeOf arg1') && not (isTBoolean $ typeOf arg2') ]
runListT $ runExceptT $ do
arg1' <- lift $ ListT $ resolveTPExp arg1
arg2' <- lift $ ListT $ resolveTPExp arg2
let t1 = typeOf arg1'
let t2 = typeOf arg2'
return (t1 +++ t2, e{_exps = [arg1', arg2']})
resolveTExp e@IFunExp {_op, _exps = [arg1, arg2]} = do
uidIClaferMap' <- asks iUIDIClaferMap
runListT $ runExceptT $ do
arg1' <- lift $ ListT $ resolveTPExp arg1
arg2' <- lift $ ListT $ resolveTPExp arg2
let t1 = typeOf arg1'
let t2 = typeOf arg2'
let testIntersect e1 e2 =
do
it <- intersection uidIClaferMap' e1 e2
case it of
Just it' -> if isTBoolean it'
then throwError $ SemanticErr _inPos ("Function '" ++ _op ++ "' cannot be performed on\n" ++ showType arg1' ++ "\n" ++ _op ++ "\n" ++ showType arg2')
else return it'
Nothing -> throwError $ SemanticErr _inPos ("Function '" ++ _op ++ "' cannot be performed on\n" ++ showType arg1' ++ "\n" ++ _op ++ "\n" ++ showType arg2')
let testNotSame e1 e2 =
when (e1 `sameAs` e2) $
throwError $ SemanticErr _inPos ("Function '" ++ _op ++ "' is redundant because the two subexpressions are always equivalent")
let test c =
unless c $
throwError $ SemanticErr _inPos ("Function '" ++ _op ++ "' cannot be performed on\n" ++ showType arg1' ++ "\n" ++ _op ++ "\n" ++ showType arg2')
let result
| _op `elem` logBinOps = test (isTBoolean t1 && isTBoolean t2) >> return TBoolean
| _op `elem` [iLt, iGt, iLte, iGte] = test (numeric t1 && numeric t2) >> return TBoolean
| _op `elem` [iEq, iNeq] = testNotSame arg1' arg2' >> testIntersect t1 t2 >> return TBoolean
| _op == iDifference = testNotSame arg1' arg2' >> testIntersect t1 t2 >> return t1
| _op == iIntersection = testNotSame arg1' arg2' >> testIntersect t1 t2
| _op `elem` [iDomain, iRange] = testIntersect t1 t2
| _op `elem` relSetBinOps = testIntersect t1 t2 >> return TBoolean
| _op `elem` [iSub, iMul, iDiv, iRem] = test (numeric t1 && numeric t2) >> return (coerce t1 t2)
| _op == iPlus =
(test (isTString t1 && isTString t2) >> return TString) -- Case 1: String concatenation
`catchError`
const (test (numeric t1 && numeric t2) >> return (coerce t1 t2)) -- Case 2: Addition
| otherwise = error $ "ResolverType: Unknown op: " ++ show e
result' <- result
return (result', e{_exps = [arg1', arg2']})
resolveTExp e@(IFunExp "ifthenelse" [arg1, arg2, arg3]) = do
uidIClaferMap' <- asks iUIDIClaferMap
runListT $ runExceptT $ do
arg1' <- lift $ ListT $ resolveTPExp arg1
arg2' <- lift $ ListT $ resolveTPExp arg2
arg3' <- lift $ ListT $ resolveTPExp arg3
let t1 = typeOf arg1'
let t2 = typeOf arg2'
let t3 = typeOf arg3'
unless (isTBoolean t1) $
throwError $ SemanticErr _inPos ("The type of condition in 'if/then/else' must be 'TBoolean', insted it is " ++ showType arg1')
it <- getIfThenElseType uidIClaferMap' t2 t3
t <- case it of
Just it' -> return it'
Nothing -> throwError $ SemanticErr _inPos ("Function 'if/then/else' cannot be performed on \nif\n" ++ showType arg1' ++ "\nthen\n" ++ showType arg2' ++ "\nelse\n" ++ showType arg3')
return (t, e{_exps = [arg1', arg2', arg3']})
-- some P, no P, one P
-- P must not be TBoolean
resolveTExp e@IDeclPExp{_oDecls=[], _bpexp} =
runListT $ runExceptT $ do
bpexp' <- liftError $ lift $ ListT $ resolveTPExp _bpexp
case _iType bpexp' of
Nothing -> fail $ "resolveTExp@IDeclPExp: No type computed for body\n" ++ show bpexp'
Just t' -> if isTBoolean t'
then throwError $ SemanticErr _inPos "The type of body of a quantified expression without local declarations must not be 'TBoolean'"
else return $ (TBoolean, e{_bpexp = bpexp'})
-- some x : X | P, no x : X | P, one x : X | P
-- X must not be TBoolean, P must be TBoolean
resolveTExp e@IDeclPExp{_oDecls, _bpexp} =
runListT $ runExceptT $ do
oDecls' <- mapM resolveTDecl _oDecls
let extraDecls = [(decl, typeOf $ _body oDecl) | oDecl <- oDecls', decl <- _decls oDecl]
localDecls extraDecls $ do
bpexp' <- liftError $ lift $ ListT $ resolveTPExp _bpexp
case _iType bpexp' of
Nothing -> fail $ "resolveTExp@IDeclPExp: No type computed for body\n" ++ show bpexp'
Just t' -> if isTBoolean t'
then return $ (TBoolean, e{_oDecls = oDecls', _bpexp = bpexp'})
else throwError $ SemanticErr _inPos $ "The type of body of a quantified expression with local declarations must be 'TBoolean', instead it is\n" ++ showType bpexp'
where
resolveTDecl d@IDecl{_body} =
do
body' <- lift $ ListT $ resolveTPExp _body
case _iType body' of
Nothing -> fail $ "resolveTExp@IDeclPExp: No type computed for local declaration\n" ++ show body'
Just t' -> if isTBoolean t'
then throwError $ SemanticErr _inPos "The type of declaration of a quantified expression must not be 'TBoolean'"
else return $ d{_body = body'}
resolveTExp e = error $ "Unknown iexp: " ++ show e
-- Adds "dref"s at the end, effectively dereferencing Clafers when needed.
addDref :: PExp -> ExceptT ClaferSErr (ListT TypeAnalysis) PExp
addDref pexp =
do
localCurPath (typeOf pexp) $ do
deref <- (ExceptT $ ListT $ resolveTPExp' $ newPExp $ IClaferId "" "dref" False Nothing) `catchError` const (lift mzero)
let result = (newPExp $ IFunExp "." [pexp, deref]) `withType` typeOf deref
return result <++> addDref result
where
newPExp = PExp Nothing "" $ _inPos pexp
-- Adds a quantifier "some" at the beginning, effectively turning an identifier into a TBoolean expression
addSome :: PExp -> ExceptT ClaferSErr (ListT TypeAnalysis) PExp
addSome pexp =
do
localCurPath (typeOf pexp) $ return $ (newPExp $ IDeclPExp ISome [] pexp) `withType` TBoolean
where
newPExp = PExp Nothing "" $ _inPos pexp
typeOf :: PExp -> IType
typeOf pexp = fromMaybe (error "No type") $ _iType pexp
withType :: PExp -> IType -> PExp
withType p t = p{_iType = Just t}
(<++>) :: MonadPlus m => ExceptT e m a -> ExceptT e m a -> ExceptT e m a
(ExceptT a) <++> (ExceptT b) = ExceptT $ a `mplus` b
liftError :: MonadError e m => ExceptT e m a -> ExceptT e m a
liftError e =
liftCatch catchError e throwError
where
liftCatch catchError' m h = ExceptT $ runExceptT m `catchError'` (runExceptT . h)
{-
-
- Utility functions
-
-}
liftList :: Monad m => [a] -> ListT m a
liftList = ListT . return
comparing :: Ord b => (a -> b) -> a -> a -> Ordering
comparing f a b = f a `compare` f b
syntaxOf :: PExp -> String
syntaxOf = printTree . sugarExp
-- Returns true iff the left and right expressions are syntactically identical
sameAs :: PExp -> PExp -> Bool
sameAs e1 e2 = syntaxOf e1 == syntaxOf e2 -- Not very efficient but hopefully correct
| juodaspaulius/clafer | src/Language/Clafer/Intermediate/ResolverType.hs | mit | 21,961 | 0 | 30 | 5,398 | 6,352 | 3,190 | 3,162 | -1 | -1 |
module Dicom.StorageSOP.SCU where
| danplubell/dicom-network | library/Dicom/StorageSOP/SCU.hs | mit | 34 | 0 | 3 | 3 | 7 | 5 | 2 | 1 | 0 |
{-# htermination foldFM_GE :: (Char -> b -> c -> c) -> c -> Char -> FiniteMap Char b -> c #-}
import FiniteMap
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/FiniteMap_foldFM_GE_3.hs | mit | 111 | 0 | 3 | 24 | 5 | 3 | 2 | 1 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
module SFML.SFException where
import Control.Exception
import Data.Typeable
data SFException = SFException String deriving (Show, Typeable)
instance Exception SFException
| SFML-haskell/SFML | src/SFML/SFException.hs | mit | 219 | 0 | 6 | 34 | 44 | 25 | 19 | 6 | 0 |
module SpaceAge (Planet(..), ageOn) where
data Planet = Mercury
| Venus
| Earth
| Mars
| Jupiter
| Saturn
| Uranus
| Neptune
earthAge :: Float
earthAge = 31557600.0
ageOn :: Planet -> Float -> Float
ageOn planet seconds =
case planet of
Mercury -> seconds / (0.2408467 * earthAge)
Venus -> seconds / (0.61519726 * earthAge)
Earth -> seconds / earthAge
Mars -> seconds / (1.8808158 * earthAge)
Jupiter -> seconds / (11.862615 * earthAge)
Saturn -> seconds / (29.447498 * earthAge)
Neptune -> seconds / (164.79132 * earthAge)
Uranus -> seconds / (84.016846 * earthAge)
| mukeshtiwari/Excercism | haskell/space-age/src/SpaceAge.hs | mit | 691 | 0 | 10 | 221 | 210 | 117 | 93 | 22 | 8 |
module CommonSpec where
import qualified Common as C
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "fib" $
it "0,1から始まるフィボナッチ数列" $
take 10 C.fib `shouldBe` [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
describe "primes" $
it "素数列" $
take 10 C.primes `shouldBe` [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
describe "isPrime" $ do
it "1以下の場合はFalse" $
map C.isPrime [-1, 0, 1] `shouldBe` [False, False, False]
it "2以上の場合は素数判定" $ do
let t = True
let f = False
map C.isPrime [2..20] `shouldBe` [t,t,f,t,f,t,f,f,f,t,f,t,f,f,f,t,f,t,f]
describe "primeFactors" $ do
it "1以下の場合は空" $
map C.primeFactors [-1, 0, 1] `shouldBe` [[], [], []]
it "2以上の場合は素因数分解 - 1" $
map C.primeFactors [2..9] `shouldBe`
[[(1,2)], [(1,3)], [(2,2)], [(1,5)], [(1,2), (1,3)], [(1,7)], [(3,2)], [(2,3)]]
it "2以上の場合は素因数分解 - 2" $
C.primeFactors 13195 `shouldBe` [(1,5),(1,7),(1,13),(1,29)]
describe "digits" $ do
it "負の場合は空" $
C.digits (-1::Int) `shouldBe` []
it "1以上の場合は桁に分解 - 1" $
map C.digits [1::Int, 10, 11, 200, 201] `shouldBe` [[1], [1, 0], [1, 1], [2, 0, 0], [2, 0, 1]]
it "1以上の場合は桁に分解 - 2" $
C.digits (12345::Integer) `shouldBe` [1..5]
describe "permutation" $
it "順列 nPr" $
map (uncurry C.permutation) [(-1,-2), (-1,-1), (1,-1), (-1,1),
(0,0),
(1,0), (1,1), (1,2),
(2,0), (2,1), (2,2), (2,3),
(3,0), (3,1), (3,2), (3,3), (3,4),
(4,0), (4,1), (4,2), (4,3), (4,4), (4,5)]
`shouldBe`
[0, 0, 0, 0,
1,
1, 1, 0,
1, 2, 2, 0,
1, 3, 6, 6, 0,
1, 4, 12, 24, 24, 0]
describe "fact" $
it "階乗 n!" $
map C.fact [-1, 0, 1, 2, 3, 4, 5] `shouldBe` [0, 1, 1, 2, 6, 24, 120]
describe "combination" $
it "組み合わせ nCr" $
map (uncurry C.combination) [(-1,-1), (1,-1), (-1,1),
(0,0),
(1,0), (1,1), (1,2),
(2,0), (2,1), (2,2), (2,3),
(3,0), (3,1), (3,2), (3,3), (3,4),
(4,0), (4,1), (4,2), (4,3), (4,4), (4,5),
(5,0), (5,1), (5,2), (5,3), (5,4), (5,5), (5,6)]
`shouldBe`
[0, 0, 0,
1,
1, 1, 0,
1, 2, 1, 0,
1, 3, 3, 1, 0,
1, 4, 6, 4, 1, 0,
1, 5, 10, 10, 5, 1, 0]
describe "sumDivisors" $
it "約数の和" $
map C.sumDivisors [0,1,2,3,4,24] `shouldBe` [1,1,3,4,7,60]
describe "divisors" $
it "約数" $
map C.divisors [1,2,3,4,24] `shouldBe` [[1],[1,2],[1,3],[1,2,4],[1,2,3,4,6,8,12,24]]
describe "factoradic" $
it "階乗進数の各桁の数" $
map C.factoradic [0..23] `shouldBe` [[], [1],
[1,0], [1,1], [2,0], [2,1],
[1,0,0], [1,0,1], [1,1,0], [1,1,1], [1,2,0], [1,2,1],
[2,0,0], [2,0,1], [2,1,0], [2,1,1], [2,2,0], [2,2,1],
[3,0,0], [3,0,1], [3,1,0], [3,1,1], [3,2,0], [3,2,1]]
describe "nthPermutation" $ do
it "N番目の順列 - 1" $
C.nthPermutation "" 1 `shouldBe` ""
it "N番目の順列 - 2" $
map (C.nthPermutation [1::Int, 2]) [1, 2] `shouldBe` [[1, 2], [2, 1]]
it "N番目の順列 - 3" $
map (C.nthPermutation [0::Int, 1, 2]) [1..6] `shouldBe` [[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]]
| yyotti/euler_haskell | test/CommonSpec.hs | mit | 4,176 | 4 | 32 | 1,646 | 2,191 | 1,348 | 843 | 90 | 1 |
{-|
Module : McCarthy
Copyright : (c) Eric Bailey, 2016
License : MIT
Maintainer : Eric Bailey
Stability : experimental
Portability : portable
Chapter 8: McCarthy 91
-}
module McCarthy
( mc91
) where
-- | The McCarthy 91 function yields @n - 10@ when @n > 100@ and @91@ otherwise.
-- The function is recursive.
-- <<resources/mc91.png The McCarthy 91 function>>
mc91 :: (Num a, Ord a) => a -> a
mc91 n | n > 100 = n - 10
| otherwise = mc91 . mc91 $ n + 11
| yurrriq/haskell-programming | src/McCarthy.hs | mit | 497 | 0 | 8 | 133 | 80 | 43 | 37 | 5 | 1 |
module OrdTest where
data Test = A | B deriving Eq
instance Ord Test where
A <= _ = True
B <= B = True
_ <= _ = False | antalsz/hs-to-coq | examples/base-tests/OrdTest.hs | mit | 125 | 2 | 8 | 37 | 59 | 30 | 29 | 6 | 0 |
module Main where
import Control.Monad (unless)
import Data.IORef
import Graphics.Rendering.OpenGL
import Graphics.GLUtil
import Graphics.UI.GLUT hiding (exit)
import Foreign.Marshal.Array (withArray)
import Foreign.Storable (sizeOf)
import System.Exit (exitFailure)
import Hogldev.Camera (initCamera)
import Hogldev.Pipeline (
Pipeline(..), getTrans,
PersProj(..), Camera(..)
)
windowWidth = 1024
windowHeight = 768
persProjection = PersProj
{ persFOV = 30
, persWidth = fromIntegral windowWidth
, persHeigh = fromIntegral windowHeight
, persZNear = 1
, persZFar = 1000
}
main :: IO ()
main = do
getArgsAndInitialize
initialDisplayMode $= [DoubleBuffered, RGBAMode]
initialWindowSize $= Size windowWidth windowHeight
initialWindowPosition $= Position 100 100
createWindow "Tutorial 13"
vbo <- createVertexBuffer
ibo <- createIndexBuffer
gWorldLocation <- compileShaders
gScale <- newIORef 0.0
initializeGlutCallbacks vbo ibo gWorldLocation gScale
clearColor $= Color4 0 0 0 0
mainLoop
initializeGlutCallbacks :: BufferObject
-> BufferObject
-> UniformLocation
-> IORef GLfloat
-> IO ()
initializeGlutCallbacks vbo ibo gWorldLocation gScale = do
displayCallback $= renderSceneCB vbo ibo gWorldLocation gScale
idleCallback $= Just (idleCB gScale)
idleCB :: IORef GLfloat -> IdleCallback
idleCB gScale = do
gScale $~! (+ 0.1)
postRedisplay Nothing
createVertexBuffer :: IO BufferObject
createVertexBuffer = do
vbo <- genObjectName
bindBuffer ArrayBuffer $= Just vbo
withArray vertices $ \ptr ->
bufferData ArrayBuffer $= (size, ptr, StaticDraw)
return vbo
where
vertices :: [Vertex3 GLfloat]
vertices = [ Vertex3 (-1) (-1) 0
, Vertex3 0 (-1) 1
, Vertex3 1 (-1) 0
, Vertex3 0 1 0 ]
numVertices = length vertices
vertexSize = sizeOf (head vertices)
size = fromIntegral (numVertices * vertexSize)
createIndexBuffer :: IO BufferObject
createIndexBuffer = do
ibo <- genObjectName
bindBuffer ElementArrayBuffer $= Just ibo
withArray indices $ \ptr ->
bufferData ElementArrayBuffer $= (size, ptr, StaticDraw)
return ibo
where
indices :: [GLuint]
indices = [ 0, 3, 1
, 1, 3, 2
, 2, 3, 0
, 0, 2, 1 ]
numIndices = length indices
indexSize = sizeOf (head indices)
size = fromIntegral (numIndices * indexSize)
compileShaders :: IO UniformLocation
compileShaders = do
shaderProgram <- createProgram
addShader shaderProgram "tutorial13/shader.vs" VertexShader
addShader shaderProgram "tutorial13/shader.fs" FragmentShader
linkProgram shaderProgram
linkStatus shaderProgram >>= \ status -> unless status $ do
errorLog <- programInfoLog shaderProgram
putStrLn $ "Error linking shader program: '" ++ errorLog ++ "'"
exitFailure
validateProgram shaderProgram
validateStatus shaderProgram >>= \ status -> unless status $ do
errorLog <- programInfoLog shaderProgram
putStrLn $ "Invalid shader program: '" ++ errorLog ++ "'"
exitFailure
currentProgram $= Just shaderProgram
uniformLocation shaderProgram "gWVP"
addShader :: Program -> FilePath -> ShaderType -> IO ()
addShader shaderProgram shaderFile shaderType = do
shaderText <- readFile shaderFile
shaderObj <- createShader shaderType
shaderSourceBS shaderObj $= packUtf8 shaderText
compileShader shaderObj
compileStatus shaderObj >>= \ status -> unless status $ do
errorLog <- shaderInfoLog shaderObj
putStrLn ("Error compiling shader type " ++ show shaderType
++ ": '" ++ errorLog ++ "'")
exitFailure
attachShader shaderProgram shaderObj
renderSceneCB :: BufferObject
-> BufferObject
-> UniformLocation
-> IORef GLfloat
-> DisplayCallback
renderSceneCB vbo ibo gWorldLocation gScale = do
clear [ColorBuffer]
gScaleVal <- readIORef gScale
uniformMat gWorldLocation $= getTrans
WVPPipeline {
worldInfo = Vector3 0 0 5,
scaleInfo = Vector3 1 1 1,
rotateInfo = Vector3 0 gScaleVal 0,
persProj = persProjection,
pipeCamera =
( initCamera Nothing windowWidth windowHeight )
{ cameraPos = Vector3 0 0 (-3)
, cameraTarget = Vector3 0 0 2
, cameraUp = Vector3 0 1 0
}
}
vertexAttribArray vPosition $= Enabled
bindBuffer ArrayBuffer $= Just vbo
vertexAttribPointer vPosition $=
(ToFloat, VertexArrayDescriptor 3 Float 0 offset0)
bindBuffer ElementArrayBuffer $= Just ibo
drawIndexedTris 4
vertexAttribArray vPosition $= Disabled
swapBuffers
where
vPosition = AttribLocation 0
| triplepointfive/hogldev | tutorial13/Tutorial13.hs | mit | 5,275 | 0 | 18 | 1,643 | 1,328 | 657 | 671 | 134 | 1 |
{-# Language BlockArguments #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.OS
-- Copyright : (c) ChaosGroup, 2020
-- License : MIT
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Get the name of the current operating system.
-----------------------------------------------------------------------------
module System.OS
(
-- * 'OS'
OS(..), os
) where
import Foreign.C.String (CWString, peekCWString)
import Foreign.Marshal.Alloc (free)
import Foreign.Ptr (nullPtr)
import System.IO.Unsafe (unsafePerformIO)
-- | The name of the current operating system.
newtype OS = OS { unOS :: String }
-- | Try to get the name of the current operating system.
os :: Maybe OS
os = unsafePerformIO do
-- unsafePerformIO and NOINLINE guarantee that c_getOS won't be called more than once
osptr <- c_getOS
if osptr == nullPtr
then pure Nothing
else do
res <- peekCWString osptr
free osptr
pure $ Just $ OS res
{-# NOINLINE os #-}
foreign import ccall safe "getOS"
c_getOS :: IO CWString
| ChaosGroup/system-info | src/System/OS.hs | mit | 1,118 | 0 | 12 | 211 | 182 | 108 | 74 | -1 | -1 |
module Y2016.M12.D01.Exercise where
import Data.Time
import Network.HTTP.Conduit
-- below import available from 1HaskellADay git repository
import Data.Monetary.BitCoin
{--
Okay, 7 or 8 data points, one thing.
How about a year's worth of data? And instead of monotonically increasing,
let's take a data set that goes anywhere, say, stocks in the markets or bitcoin.
Everything should work as before, right? But does it? Is there an 'average
gain'? And does the curve fit well in the new data set as it so happened to do
in the old data set?
Let's see.
We have a set of quotes for BitCoin closing prices by making the following REST
call:
https://api.blockchain.info/charts/market-price?timespan=52weeks&rollingAverage=24hours&format=csv
make that call, get the CSV back, and parse that into a set of BTC prices:
--}
btcPriceHistoryFromURL :: FilePath -> IO BitCoinPrices
btcPriceHistoryFromURL url = undefined
{-- BONUS -----------------------------------------------------------------
Okay, now that you have these data, plot the BitCoin price over time.
Question: is there a mean gain over the year? Answer: yes.
Question: does a mean gain curve make sense with the fluxuations in BTC prices?
Let's see.
--}
chartBTC :: FilePath -> BitCoinPrices -> IO ()
chartBTC outputWithMeanGain btcprices = undefined
-- we'll look at other curve fitting algorithms, but not today.
| geophf/1HaskellADay | exercises/HAD/Y2016/M12/D01/Exercise.hs | mit | 1,389 | 0 | 8 | 221 | 77 | 45 | 32 | 8 | 1 |
import Criterion.Main
import Control.Monad
import Control.DeepSeq
import Control.Exception
import AuthBench
import OneTimeAuthBench
import BoxBench
import SecretBoxBench
import ConstantTimeBench
import HashBench
import RandomBench
import ScalarMultBench
import SignBench
import StreamBench
import PasswordBench
import AES256GCMBench
import ChaCha20Poly1305Bench
import ChaCha20Poly1305IETFBench
import XChaCha20Poly1305Bench
main :: IO ()
main = do
authKeyToEval <- authEnv
authKey <- evaluate $ force authKeyToEval
oneTimeAuthKeyToEval <- oneTimeAuthEnv
oneTimeAuthKey <- evaluate $ force oneTimeAuthKeyToEval
boxToEval <- boxEnv
boxKeys <- evaluate $ force boxToEval
secretboxKeyToEval <- secretboxEnv
secretboxKey <- evaluate $ force secretboxKeyToEval
scmlToEval <- scalarMultEnv
scml <- evaluate $ force scmlToEval
signToEval <- signEnv
signKey <- evaluate $ force signToEval
streamKeyToEval <- streamEnv
streamKey <- evaluate $ force streamKeyToEval
passwordSaltToEval <- passwordEnv
passwordSalt <- evaluate $ force passwordSaltToEval
hashKeysToEval <- hashEnv
hashKeys <- evaluate $ force hashKeysToEval
aes256GCMKeyToEval <- aes256GCMEnv
aes256GCMKey <- evaluate $ force aes256GCMKeyToEval
chaCha20Poly1305KeyToEval <- chaCha20Poly1305Env
chaCha20Poly1305Key <- evaluate $ force chaCha20Poly1305KeyToEval
chaCha20Poly1305IETFKeyToEval <- chaCha20Poly1305IETFEnv
chaCha20Poly1305IETFKey <- evaluate $ force chaCha20Poly1305IETFKeyToEval
xChaCha20Poly1305KeyToEval <- xChaCha20Poly1305Env
xChaCha20Poly1305Key <- evaluate $ force xChaCha20Poly1305KeyToEval
defaultMain [
benchAuth authKey
, benchOneTimeAuth oneTimeAuthKey
, benchBox boxKeys
, benchSecretbox secretboxKey
, benchHash hashKeys
, benchScalarMult scml
, benchSign signKey
, benchStream streamKey
, benchPassword passwordSalt
, benchComparison
, benchAes256GCM aes256GCMKey
, benchChaCha20Poly1305 chaCha20Poly1305Key
, benchChaCha20Poly1305IETF chaCha20Poly1305IETFKey
, benchXChaCha20Poly1305 xChaCha20Poly1305Key
]
| tel/saltine | bench/Main.hs | mit | 2,120 | 0 | 9 | 337 | 441 | 210 | 231 | 62 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-dataset-triggeringdataset.html
module Stratosphere.ResourceProperties.IoTAnalyticsDatasetTriggeringDataset where
import Stratosphere.ResourceImports
-- | Full data type definition for IoTAnalyticsDatasetTriggeringDataset. See
-- 'ioTAnalyticsDatasetTriggeringDataset' for a more convenient constructor.
data IoTAnalyticsDatasetTriggeringDataset =
IoTAnalyticsDatasetTriggeringDataset
{ _ioTAnalyticsDatasetTriggeringDatasetDatasetName :: Val Text
} deriving (Show, Eq)
instance ToJSON IoTAnalyticsDatasetTriggeringDataset where
toJSON IoTAnalyticsDatasetTriggeringDataset{..} =
object $
catMaybes
[ (Just . ("DatasetName",) . toJSON) _ioTAnalyticsDatasetTriggeringDatasetDatasetName
]
-- | Constructor for 'IoTAnalyticsDatasetTriggeringDataset' containing
-- required fields as arguments.
ioTAnalyticsDatasetTriggeringDataset
:: Val Text -- ^ 'itadtdDatasetName'
-> IoTAnalyticsDatasetTriggeringDataset
ioTAnalyticsDatasetTriggeringDataset datasetNamearg =
IoTAnalyticsDatasetTriggeringDataset
{ _ioTAnalyticsDatasetTriggeringDatasetDatasetName = datasetNamearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-dataset-triggeringdataset.html#cfn-iotanalytics-dataset-triggeringdataset-datasetname
itadtdDatasetName :: Lens' IoTAnalyticsDatasetTriggeringDataset (Val Text)
itadtdDatasetName = lens _ioTAnalyticsDatasetTriggeringDatasetDatasetName (\s a -> s { _ioTAnalyticsDatasetTriggeringDatasetDatasetName = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/IoTAnalyticsDatasetTriggeringDataset.hs | mit | 1,727 | 0 | 13 | 164 | 174 | 100 | 74 | 23 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Y2021.M02.D05.Solution where
{--
Okay, yesterday we found lots of duplicates of wine-labels and, digging further,
we saw some wines had multiple reviews from the same reviewer, but also, some
wines had multiple reviews from multiple reviewers.
This begs the question, however: so?
Why do I say this?
Well, down the road (not today), because a wine may have multiple reviews from
a reviewer, that means there are going to be multiple RATES_WINE relations
between the same two nodes (wine, taster), and to CREATE multiple relations,
we cannot add to one relation, no: we have to create a new relation for each
review.
Which means, in which case, that we want all the current relations to go away,
so that we can add relations between wines and tasters as we add each review
(and rating ... and possibly price).
So: there 'tis.
What does that mean for us now?
What that means, tactically-speaking, is that for each wine with wine ids, (h:t)
* for h, we delete the relation r of (wine { id: h })-[r]-(taster); and,
* for a ids in t, we detach delete w (the redundant wine).
We do this for every wine in our graph-store, we then should have a newly-
cleaned state by which we can (re-)start uploading reviews to our graph.
Let's do it.
Yesterday we got a mapping of all wines to their (possibly multiple) ids:
--}
import Y2021.M02.D04.Solution (dupes, NodeIds)
import Y2021.M01.D21.Solution (Idx)
import Graph.Query (getGraphResponse, graphEndpoint, Endpoint)
import Graph.JSON.Cypher (Cypher)
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as T
removeDuplicateWines :: Endpoint -> NodeIds -> IO String
removeDuplicateWines url =
getGraphResponse url
. map (removeWinesQuery . tail . Set.toList)
. Map.elems
{--
-- what removeDuplicateWines does is, for the first wine id (the head of the
-- list), we remove the relation:
removeRelationQuery :: Idx -> Cypher
removeRelationQuery wineId =
T.pack (unwords ["MATCH (w:Wine)<-[r:RATES_WINE]-()",
"WHERE id(w) =", show wineId, "DELETE r"])
Actually, we don't need to do this if we remove all (wine)<-[:RATES_WINE]-(t)
relations in the database with:
neo4j$ match (:Wine)<-[r:RATES_WINE]-(:Taster) delete r
Deleted 119981 relationships, completed after 2288 ms.
This further means that we only have to work with the duplicates, not with
the entire wine-set.
--}
-- For the rest of the wine ids (the rest of the wine ids for a wine), we want
-- to detach and delete those wines, because they are duplicates.
removeWinesQuery :: [Idx] -> Cypher
removeWinesQuery [] = ""
removeWinesQuery l@(_:_) =
T.pack (unwords ["MATCH (w:Wine) WHERE id(w) IN", show l,"DETACH DELETE w"])
-- Remove all the duplicate wines and all RATES_WINE relations. You may want
-- to try this on one wine, then 10 wines, then 100 wines, ... just to see how
-- work flows.
-- Verify, after running removeDuplicateWines, that there are, in fact, no
-- duplicate wines remaining in the graph store.
-- When you verify no dupes, run an index on the Wine.title.
{--
>>> graphEndpoint
...
>>> let url =it
>>> :set -XOverloadedStrings
>>> dupes url "Wine" "title"
...
>>> let vinos = it
>>> let vino = Map.fromList . return . head $ Map.toList vinos
>>> removeDuplicateWines url vino
"{\"results\":[{\"columns\":[],\"data\":[]}],\"errors\":[]}"
Boom, we go from vinos to vino, removing the duplicates for one wine.
That was easy. Now: 10 wines:
>>> let vino = Map.fromList . take 10 . tail $ Map.toList vinos
>>> removeDuplicateWines url vino
...
also instantaneous.
>>> let vinos1 = Map.fromList . drop 11 $ Map.toList vinos
>>> Map.size vinos1
923
We have a ways to go. Let's try 50?
>>> let vino = Map.fromList . take 50 $ Map.toList vinos1
>>> removeDuplicateWines url vino
That took a second.
How about 100?
>>> let vinos2 = Map.fromList . drop 50 $ Map.toList vinos1
>>> let vino = Map.fromList . take 100 $ Map.toList vinos2
>>> removeDuplicateWines url vino
...
Barely any delay at all. 200?
>>> let vinos3 = Map.fromList . drop 100 $ Map.toList vinos2
>>> let vino = Map.fromList . take 200 $ Map.toList vinos3
>>> removeDuplicateWines url vino
...
Quick! ... 500? ... wait. What's the size now?
>>> let vinos4 = Map.fromList . drop 200 $ Map.toList vinos3
>>> Map.size vinos4
573
Well, well, well. How about 573, then.
>>> removeDuplicateWines url vinos4
...
... annnnnnddddd, ... we're done? Let's check.
>>> dupes url "Wine" "title"
fromList []
Yup! We're done.
... now: how about Wineries?
>>> dupes url "Winery" "name"
fromList []
Cool beans! Good night!
--}
| geophf/1HaskellADay | exercises/HAD/Y2021/M02/D05/Solution.hs | mit | 4,663 | 0 | 10 | 847 | 214 | 131 | 83 | 18 | 1 |
{-# language TemplateHaskell #-}
{-# language DeriveDataTypeable #-}
{-# language FlexibleInstances #-}
{-# language MultiParamTypeClasses #-}
{-# language DisambiguateRecordFields #-}
module DPLL.Top where
import DPLL.Data
import DPLL.Trace
-- import DPLL.Pattern
import DPLL.Roll
import Challenger.Partial
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Reporter
import Inter.Types hiding ( Var )
import Inter.Quiz
import Data.Typeable
import System.Random
data DPLL = DPLL deriving Typeable
data Instance =
Instance { modus :: Modus
, cnf :: CNF
, max_solution_length :: Maybe Int
}
deriving Typeable
instance0 :: Instance
instance0 = Instance
{ modus = modus0
, cnf = read "[[1,2,3],[-1,4],[2,-3],[1,-2,3,-4],[-2,3]]"
, max_solution_length = Nothing
}
derives [makeReader, makeToDoc] [''DPLL, ''Instance ]
instance Show DPLL where show = render . toDoc
instance OrderScore DPLL where
scoringOrder _ = None
instance Partial DPLL Instance [Step] where
describe _ i = vcat
[ text "Gesucht ist eine vollständige DPLL-Rechnung" </>
case max_solution_length i of
Nothing -> empty
Just l -> text "mit höchstens" <+> toDoc l <+> text "Schritten"
, text "mit diesen Eigenschaften:" </> toDoc (DPLL.Top.modus i)
, text "für diese Formel:" </> toDoc (cnf i)
]
initial _ i =
let p = case clause_learning $ DPLL.Top.modus i of
True -> Backjump 1 [4,-1]
False -> Backtrack
in [ Decide (-2), Propagate [2,-3] (-3), Conflict [1,-2], p, SAT ]
partial _ i steps = do
DPLL.Trace.execute (DPLL.Top.modus i) (cnf i) steps
return ()
total _ i steps = do
case max_solution_length i of
Nothing -> return ()
Just l -> when (length steps > l) $ reject
$ text "Die Anzahl der Schritte" <+> parens (toDoc $ length steps)
<+> text "ist größer als" <+> toDoc l
case reverse steps of
SAT : _ -> return ()
UNSAT : _ -> return ()
_ -> reject $ text "die Rechnung soll vollständig sein (mit SAT oder UNSAT enden)"
make_fixed = direct DPLL instance0
instance Generator DPLL Config ( Instance, [Step] ) where
generator p conf key = do
(c, s, o) <- roll conf
return ( Instance { modus = DPLL.Roll.modus conf
, max_solution_length = case require_max_solution_length conf of
DPLL.Roll.No -> Nothing
Yes { allow_extra = e } -> Just $ o + e
, cnf = c
} , s )
instance Project DPLL ( Instance, [Step] ) Instance where
project p (c, s) = c
make_quiz = quiz DPLL config0
| marcellussiegburg/autotool | collection/src/DPLL/Top.hs | gpl-2.0 | 2,896 | 0 | 19 | 933 | 820 | 431 | 389 | 71 | 1 |
Subsets and Splits