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
-- Enter your code here. Read input from STDIN. Print output to STDOUT f arr =[if x < 0 then x * (-1) else x | x <- arr] -- Complete this function here -- This section handles the Input/Output and can be used as it is. Do not modify it. main = do inputdata <- getContents mapM_ putStrLn $ map show $ f $ map (read :: String -> Int) $ lines inputdata
JsWatt/Free-Parking
hacker_rank/functional_programming/introduction/update_list.hs
mit
359
0
11
83
97
50
47
4
2
module Week2Sol where import Week2 import Data.List -- -- Question 1 - time spent: 1.5 hours -- data Shape = NoTriangle | Equilateral | Isosceles | Rectangular | Other deriving (Eq,Show) triangle :: Integer -> Integer -> Integer -> Shape triangle x y z | any (==0) [x,y,z] = NoTriangle -- VVZ: incorrect, counter-example: triangle 1 2 1000 | x == y && y == z = Equilateral | x^2 + y^2 == z^2 || x^2 + z^2 == y^2 || z^2 + y^2 == x^2 = Rectangular -- VVZ: correct, but slightly inefficient, you could've written another function that works with sorted triples | x == y || y == z || z == x = Isosceles | otherwise = Other -- -- Question 1 check cases -- checkTriangle = checkNoTriangle && checkEquilateral && checkRectangular && checkIsosceles && checkOther -- VVZ: kinda correct, but 40 lines of code for something that could have been generated by a Haskell oneliner is somewhat inefficient checkNoTriangle = triangle 0 0 0 == NoTriangle && triangle 0 0 1 == NoTriangle && triangle 0 1 0 == NoTriangle && triangle 1 0 0 == NoTriangle && triangle 1 1 0 == NoTriangle && triangle 1 0 1 == NoTriangle && triangle 0 1 1 == NoTriangle && triangle (-1) 1 1 == NoTriangle && triangle 1 (-1) 1 == NoTriangle && triangle 1 1 (-1) == NoTriangle && triangle 1 1 1 /= NoTriangle checkEquilateral = triangle 1 1 0 /= Equilateral && triangle 0 0 0 /= Equilateral && triangle 1 2 3 /= Equilateral && triangle 1 1 2 /= Equilateral && triangle 1 2 1 /= Equilateral && triangle 2 1 1 /= Equilateral && triangle 1 1 1 == Equilateral && triangle 2 2 2 == Equilateral && triangle 3 3 3 == Equilateral checkRectangular = triangle 0 0 0 /= Rectangular && triangle 1 1 2 /= Rectangular && triangle 3 4 5 == Rectangular && triangle 4 3 5 == Rectangular && triangle 5 4 3 == Rectangular && triangle 5 12 13 == Rectangular checkIsosceles = triangle 1 1 1 /= Isosceles && triangle 2 2 2 /= Isosceles && triangle 1 1 2 == Isosceles && triangle 1 2 1 == Isosceles && triangle 2 1 1 == Isosceles -- VVZ: Y U NO have positive tests? -- VVZ: btw, this is where generation could have helped you enormously: within triangles with sides between 1 and 5 there only two -- VVZ: which are correct but belong to "other" checkOther = triangle 0 0 0 /= Other && triangle 1 1 1 /= Other && triangle 3 4 5 /= Other && triangle 1 1 2 /= Other -- -- Question 2 - Time spent: 2 hours -- contradiction :: Form -> Bool -- VVZ: correct, but a shorter notation would be "contradiction = not . satisfiable" contradiction f = not (satisfiable f) tautology :: Form -> Bool tautology f = all (\ v -> eval v f) (allVals f) entails :: Form -> Form -> Bool entails f1 f2 = tautology (Impl f1 f2) equiv :: Form -> Form -> Bool equiv f1 f2 = tautology (Equiv f1 f2) -- -- Question 2 check cases -- checkQuestion2 = checkContradiction && checkTautology && checkEntails && checkEquiv -- these formulas are proved during the workshop form_Contradiction = Cnj [p, Neg p] form_Tautology = Dsj [p, Neg p] form1_Implication = Cnj [p, Neg p] form2_Implication = Dsj [p, Neg p] form1_Equivalence = Neg (Cnj [Neg p,Neg q]) form2_Equivalence = Dsj [p, q] checkContradiction = contradiction form_Contradiction && not(contradiction form_Tautology) && not(contradiction form1) && not(contradiction form2) && not(contradiction form3) checkTautology = tautology form_Tautology && not(tautology form_Contradiction) checkEntails = not(entails form_Tautology form_Contradiction) && entails form1_Implication form2_Implication checkEquiv = equiv form1_Equivalence form2_Equivalence && not(equiv form1_Equivalence form_Contradiction) && -- equivalence theorem formulas (see Theorem 2.10, Haskell Road to Logic, p.46) equiv (p) (Neg (Neg p)) && -- 1 equiv (p) (Cnj [p, p]) && -- 2a equiv (p) (Dsj [p, p]) && -- 2b equiv (Impl p q) (Dsj [Neg p, q]) && -- 3a equiv (Neg (Impl p q)) (Cnj [p, Neg q]) && -- 3b equiv (Impl (Neg p) (Neg q)) (Impl q p) && -- 4a equiv (Impl p (Neg q)) (Impl q (Neg p)) && -- 4b equiv (Impl (Neg p) q) (Impl (Neg q) p) && -- 4c equiv (Equiv p q) (Cnj [(Impl p q), (Impl q p)]) && -- 5a equiv (Equiv p q) (Dsj [(Cnj [p, q]), (Cnj [Neg p, Neg q])]) && -- 5b equiv (Cnj [p, q]) (Cnj [q, p]) && -- 6a equiv (Dsj [p, q]) (Dsj [q, p]) && -- 6b equiv (Neg (Cnj [p, q])) (Dsj [Neg p, Neg q]) && -- 7a equiv (Neg (Dsj [p, q])) (Cnj [Neg p, Neg q]) && -- 7b equiv (Cnj [p, Cnj [q, r]]) (Cnj [Cnj [p, q], r]) && -- 8a equiv (Dsj [p, Dsj [q, r]]) (Dsj [Dsj [p, q], r]) && -- 8b equiv (Cnj [p, Dsj [q, r]]) (Dsj [Cnj [p, q], Cnj [p, r]]) && -- 9a equiv (Dsj [p, Cnj [q, r]]) (Cnj [Dsj [p, q], Dsj [p, r]]) -- 9b -- -- Question 3 -- -- precondition: input is arrow-free and in nnf -- VVZ: incorrect, missing lots of cases. the simplest counterexample is from the first from above: (Neg (Neg p)) -- GROUP: according to the precondition the input must be arrow-free and in nnf, so no (Neg (Neg p)) can not occur anymore for the input and hence we don’t have to check it here anymore (same goes for De Morgan law which is already handled in nnf function) cnf:: Form -> Form cnf (Prop x) = Prop x cnf (Cnj fs) = Cnj (map cnf fs) cnf (Dsj [f1,f2]) = dist f1 f2 -- VVZ: treating of disjunction is incorrect: the Haskell implementation allows for three and more elements in a clause -- GROUP: Fixed this by adding the following line: cnf (Dsj (f:fs)) = dist f (cnf (Dsj fs)) -- VVZ: looks to me like it should be -- VVZ: cnf (Dsj (f:fs)) = dist (cnf f) (cnf (Dsj fs)) cnf f = f -- precondition: input is in cnf -- VVZ: incorrect, works correctly only on two-element lists, which is not reflected by the type (hence, the spec and the program don't agree) -- VVZ: also, a binary version could have been simplified (you don't need to use map if you know there are only two elements) -- GROUP : Fixed by making dist function accept two Form parameters dist:: Form -> Form -> Form dist (Cnj [f1,f2]) f3 = Cnj [dist f1 f3, dist f2 f3] dist f1 (Cnj [f2,f3]) = Cnj [dist f1 f2, dist f1 f3] dist f1 f2 = Dsj [f1,f2] -- function to convert any form to cnf -- VVZ: incorrect, counterexample: cnf (Cnj [Cnj [p,q], q]) -- GROUP: -- Is it not correct that the result is the same as the form for the counterexample you give here? This example form is already in CNF, isn't it? -- Or do you mean that the nested conjunctions need to be flattened out? So the cnf results in Cnj [p,q,q] or Cnj [p,q]?? -- Because the grammar of CNF does not - according to us - indicate this. -- VVZ: The grammar of CNF is slightly different than the data type definition in Haskell: -- VVZ: it needs to allow nested conjunctions since the conjunction there is binary -- VVZ: In the implementation, we go for the list-based conjunction/disjunction, which is easier to operate on a computer. fromAnyFormToCnf:: Form -> Form fromAnyFormToCnf f = cnf (nnf (arrowfree f)) -- -- Question 3 check cases -- -- VVZ: incorrect! -- VVZ: only tests if the transformation to CNF preserves the equivalence -- VVZ: never tests if the result actually conforms to the definition of CNF -- VVZ: (and it does not for many, try to run "cnf form1_Equivalence") -- GROUP: Almost fixed.. functionsBoundWithCnj function needs to be still implemented to make the check complete. checkCnfConvertionSampleForms = map checkCnf [form_Tautology, form1_Implication, form1_Equivalence, form_Contradiction] checkCnf :: Form -> Bool checkCnf f = equiv f f'&& checkConformityToCNF f' where f' = fromAnyFormToCnf f -- we need to check whether nnf and arrowFree were applied correctly, -- also whether functions are bound with conjunctions together, so disjunctions should be pushed to the inside functions checkConformityToCNF :: Form -> Bool checkConformityToCNF f = nnfApplied f' && arrowFreeApplied f'&& functionsBoundWithCnj f' where f' = show f -- VVZ: this is a bit hacky: I advise to find another way than to work on pretty-printed representations -- VVZ: we can talk more about limitations of lexical analysis w.r.t. syntactic one at the next lab -- VVZ: also, do not confuse infix with prefix (also with affix, postfix and confix ;) ) nnfApplied :: String -> Bool nnfApplied s | isInfixOf "-*" s = False | isInfixOf "-+" s = False | isInfixOf "-(" s = False | otherwise = True arrowFreeApplied :: String -> Bool arrowFreeApplied s | isInfixOf "==>" s = False | isInfixOf "<=>" s = False | otherwise = True -- Don't know yet how to check this functionsBoundWithCnj :: String -> Bool functionsBoundWithCnj s = True
stgm/prac-testing
week4/Week2Sol.hs
mit
9,079
104
27
2,252
2,609
1,349
1,260
144
1
module Str(str) where import Language.Haskell.TH import Language.Haskell.TH.Quote str = QuasiQuoter { quoteExp = stringE }
rickerbh/AoC
AoC2016/src/Str.hs
mit
127
0
6
19
35
23
12
4
1
module NonlinearSSM where import Control.Monad.Bayes.Class param :: MonadSample m => m (Double, Double) param = do let a = 0.01 let b = 0.01 precX <- gamma a b let sigmaX = 1 / sqrt precX precY <- gamma a b let sigmaY = 1 / sqrt precY return (sigmaX, sigmaY) -- | A nonlinear series model from Doucet et al. (2000) -- "On sequential Monte Carlo sampling methods" section VI.B model :: (MonadInfer m) => [Double] -- ^ observed data -> (Double, Double) -- ^ prior on the parameters -> m [Double] -- ^ list of latent states from t=1 model obs (sigmaX, sigmaY) = do let sq x = x * x simulate [] _ acc = return acc simulate (y:ys) x acc = do let n = length acc let mean = 0.5 * x + 25 * x / (1 + sq x) + 8 * cos (1.2 * fromIntegral n) x' <- normal mean sigmaX factor $ normalPdf (sq x' / 20) sigmaY y simulate ys x' (x':acc) x0 <- normal 0 (sqrt 5) xs <- simulate obs x0 [] return $ reverse xs generateData :: MonadSample m => Int -- ^ T -> m [(Double,Double)] -- ^ list of latent and observable states from t=1 generateData t = do (sigmaX, sigmaY) <- param let sq x = x * x simulate 0 _ acc = return acc simulate k x acc = do let n = length acc let mean = 0.5 * x + 25 * x / (1 + sq x) + 8 * cos (1.2 * fromIntegral n) x' <- normal mean sigmaX y' <- normal (sq x' / 20) sigmaY simulate (k-1) x' ((x',y'):acc) x0 <- normal 0 (sqrt 5) xys <- simulate t x0 [] return $ reverse xys
adscib/monad-bayes
models/NonlinearSSM.hs
mit
1,586
0
20
512
668
325
343
45
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE LambdaCase #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Keymap.Emacs -- License : GPL-2 -- Maintainer : yi-devel@googlegroups.com -- Stability : experimental -- Portability : portable -- -- This module aims at a mode that should be (mostly) intuitive to -- emacs users, but mapping things into the Yi world when convenient. -- Hence, do not go into the trouble of trying 100% emulation. For -- example, @M-x@ gives access to Yi (Haskell) functions, with their -- native names. module Yi.Keymap.Emacs ( keymap , mkKeymapSet , defKeymap , ModeMap(..) , eKeymap , completionCaseSensitive ) where import Control.Applicative (Alternative ((<|>), empty, some)) import Control.Monad (replicateM_, unless, void) import Control.Monad.State (gets) import Data.Char (digitToInt, isDigit) import Data.Maybe (fromMaybe) import Data.Prototype (Proto (Proto), extractValue) import Data.Text () import Lens.Micro.Platform ((.=), makeLenses, (%=)) import Yi.Buffer import Yi.Command (shellCommandE) import Yi.Core import Yi.Dired (dired) import Yi.Editor import Yi.File (fwriteE, fwriteToE) import Yi.Keymap (Keymap, KeymapSet, YiAction (..), YiM, modelessKeymapSet, write) import Yi.Keymap.Emacs.KillRing import Yi.Keymap.Emacs.Utils import Yi.Keymap.Keys import Yi.MiniBuffer import Yi.Misc (adjIndent, placeMark, selectAll) import Yi.Mode.Buffers (listBuffers) import Yi.Rectangle import Yi.Search (isearchFinishWithE, resetRegexE, getRegexE) import Yi.TextCompletion (resetComplete, wordComplete') data ModeMap = ModeMap { _eKeymap :: Keymap , _completionCaseSensitive :: Bool } $(makeLenses ''ModeMap) keymap :: KeymapSet keymap = mkKeymapSet defKeymap mkKeymapSet :: Proto ModeMap -> KeymapSet mkKeymapSet = modelessKeymapSet . _eKeymap . extractValue defKeymap :: Proto ModeMap defKeymap = Proto template where template self = ModeMap { _eKeymap = emacsKeymap , _completionCaseSensitive = False } where emacsKeymap :: Keymap emacsKeymap = selfInsertKeymap Nothing isDigit <|> completionKm (_completionCaseSensitive self) <|> do univArg <- readUniversalArg selfInsertKeymap univArg (not . isDigit) <|> emacsKeys univArg selfInsertKeymap :: Maybe Int -> (Char -> Bool) -> Keymap selfInsertKeymap univArg condition = do c <- printableChar unless (condition c) empty let n = argToInt univArg write (replicateM_ n (insertB c)) completionKm :: Bool -> Keymap completionKm caseSensitive = do void $ some (meta (char '/') ?>>! wordComplete' caseSensitive) deprioritize write resetComplete -- 'adjustPriority' is there to lift the ambiguity between "continuing" completion -- and resetting it (restarting at the 1st completion). deleteB' :: BufferM () deleteB' = deleteN 1 -- | Wrapper around 'moveE' which also cancels incremental search. See -- issue #499 for details. moveE :: TextUnit -> Direction -> EditorM () moveE u d = do getRegexE >>= \case -- let's check whether searching is in progress (issues #738, #610) Nothing -> return () _ -> isearchFinishWithE resetRegexE withCurrentBuffer (moveB u d) emacsKeys :: Maybe Int -> Keymap emacsKeys univArg = choice [ -- First all the special key bindings spec KTab ?>>! adjIndent IncreaseCycle , shift (spec KTab) ?>>! adjIndent DecreaseCycle , spec KEnter ?>>! repeatingArg newlineB , spec KDel ?>>! deleteRegionOr deleteForward , spec KBS ?>>! deleteRegionOr deleteBack , spec KHome ?>>! repeatingArg moveToSol , spec KEnd ?>>! repeatingArg moveToEol , spec KLeft ?>>! repeatingArg $ moveE Character Backward , spec KRight ?>>! repeatingArg $ moveE Character Forward , spec KUp ?>>! repeatingArg $ moveE VLine Backward , spec KDown ?>>! repeatingArg $ moveE VLine Forward , spec KPageDown ?>>! repeatingArg downScreenB , spec KPageUp ?>>! repeatingArg upScreenB , shift (spec KUp) ?>>! repeatingArg (scrollB (-1)) , shift (spec KDown) ?>>! repeatingArg (scrollB 1) -- All the keybindings of the form 'Ctrl + special key' , ctrl (spec KLeft) ?>>! repeatingArg prevWordB , ctrl (spec KRight) ?>>! repeatingArg nextWordB , ctrl (spec KHome) ?>>! repeatingArg topB , ctrl (spec KEnd) ?>>! repeatingArg botB , ctrl (spec KUp) ?>>! repeatingArg (prevNParagraphs 1) , ctrl (spec KDown) ?>>! repeatingArg (nextNParagraphs 1) -- All the keybindings of the form "C-c" where 'c' is some character , ctrlCh '@' ?>>! placeMark , ctrlCh ' ' ?>>! placeMark , ctrlCh '/' ?>>! repeatingArg undoB , ctrlCh '_' ?>>! repeatingArg undoB , ctrlCh 'a' ?>>! repeatingArg (maybeMoveB Line Backward) , ctrlCh 'b' ?>>! repeatingArg $ moveE Character Backward , ctrlCh 'd' ?>>! deleteForward , ctrlCh 'e' ?>>! repeatingArg (maybeMoveB Line Forward) , ctrlCh 'f' ?>>! repeatingArg $ moveE Character Forward , ctrlCh 'g' ?>>! setVisibleSelection False , ctrlCh 'h' ?>> char 'b' ?>>! acceptedInputsOtherWindow , ctrlCh 'i' ?>>! adjIndent IncreaseOnly , ctrlCh 'j' ?>>! newlineAndIndentB , ctrlCh 'k' ?>>! killLine univArg , ctrlCh 'l' ?>>! (withCurrentBuffer scrollToCursorB >> userForceRefresh) , ctrlCh 'm' ?>>! repeatingArg (insertB '\n') , ctrlCh 'n' ?>>! repeatingArg (moveE VLine Forward) , ctrlCh 'o' ?>>! repeatingArg (insertB '\n' >> leftB) , ctrlCh 'p' ?>>! repeatingArg (moveE VLine Backward) , ctrlCh 'q' ?>> insertNextC univArg , ctrlCh 'r' ?>> isearchKeymap Backward , ctrlCh 's' ?>> isearchKeymap Forward , ctrlCh 't' ?>>! repeatingArg swapB , ctrlCh 'v' ?>>! scrollDownE univArg , ctrlCh 'w' ?>>! killRegion , ctrlCh 'y' ?>>! yank , ctrlCh 'z' ?>>! suspendEditor , ctrlCh '+' ?>>! repeatingArg (increaseFontSize 1) , ctrlCh '-' ?>>! repeatingArg (decreaseFontSize 1) -- All the keybindings of the form "C-M-c" where 'c' is some character , ctrl (metaCh 'w') ?>>! appendNextKillE , ctrl (metaCh ' ') ?>>! layoutManagersNextE , ctrl (metaCh ',') ?>>! layoutManagerNextVariantE , ctrl (metaCh '.') ?>>! layoutManagerPreviousVariantE , ctrl (metaCh 'j') ?>>! nextWinE , ctrl (metaCh 'k') ?>>! prevWinE , ctrl (meta $ spec KEnter) ?>>! swapWinWithFirstE -- All the keybindings of the form "S-C-M-c" where 'c' is some key , shift (ctrl $ metaCh 'j') ?>>! moveWinNextE , shift (ctrl $ metaCh 'k') ?>>! moveWinPrevE , shift (ctrl $ meta $ spec KEnter) ?>>! pushWinToFirstE , Event (KASCII ' ') [MShift,MCtrl,MMeta] ?>>! layoutManagersPreviousE -- All the key-bindings which are preceded by a 'C-x' , ctrlCh 'x' ?>> ctrlX , ctrlCh 'c' ?>> ctrlC -- All The key-bindings of the form M-c where 'c' is some character. , metaCh ' ' ?>>! justOneSep univArg , metaCh 'v' ?>>! scrollUpE univArg , metaCh '!' ?>>! shellCommandE , metaCh '<' ?>>! repeatingArg topB , metaCh '>' ?>>! repeatingArg botB , metaCh '%' ?>>! queryReplaceE , metaCh '^' ?>>! joinLinesE univArg , metaCh ';' ?>>! commentRegion , metaCh 'a' ?>>! repeatingArg (moveE unitSentence Backward) , metaCh 'b' ?>>! repeatingArg prevWordB , metaCh 'c' ?>>! repeatingArg capitaliseWordB , metaCh 'd' ?>>! repeatingArg killWordB , metaCh 'e' ?>>! repeatingArg (moveE unitSentence Forward) , metaCh 'f' ?>>! repeatingArg nextWordB , metaCh 'h' ?>>! repeatingArg (selectNParagraphs 1) , metaCh 'k' ?>>! repeatingArg (deleteB unitSentence Forward) , metaCh 'l' ?>>! repeatingArg lowercaseWordB , metaCh 'm' ?>>! firstNonSpaceB , metaCh 'q' ?>>! withSyntax modePrettify , metaCh 'r' ?>>! repeatingArg moveToMTB , metaCh 'u' ?>>! repeatingArg uppercaseWordB , metaCh 't' ?>>! repeatingArg (transposeB unitWord Forward) , metaCh 'w' ?>>! killRingSave , metaCh 'x' ?>>! executeExtendedCommandE , metaCh 'y' ?>>! yankPopE , metaCh '.' ?>>! promptTag , metaCh '{' ?>>! repeatingArg (prevNParagraphs 1) , metaCh '}' ?>>! repeatingArg (nextNParagraphs 1) , metaCh '=' ?>>! countWordsRegion , metaCh '\\' ?>>! deleteHorizontalSpaceB univArg , metaCh '@' ?>>! repeatingArg markWord -- Other meta key-bindings , meta (spec KBS) ?>>! repeatingArg bkillWordB , metaCh 'g' ?>> optMod meta (char 'g') >>! (gotoLn . fromDoc :: Int ::: LineNumber -> BufferM Int) ] where -- inserting the empty string prevents the deletion from appearing in the killring -- which is a good thing when we are deleting individuals characters. See -- http://code.google.com/p/yi-editor/issues/detail?id=212 blockKillring = insertN "" withUnivArg :: YiAction (m ()) () => (Maybe Int -> m ()) -> YiM () withUnivArg cmd = runAction $ makeAction (cmd univArg) repeatingArg :: (Monad m, YiAction (m ()) ()) => m () -> YiM () repeatingArg f = withIntArg $ \n -> replicateM_ n f withIntArg :: YiAction (m ()) () => (Int -> m ()) -> YiM () withIntArg cmd = withUnivArg $ \arg -> cmd (fromMaybe 1 arg) deleteBack :: YiM () deleteBack = repeatingArg $ blockKillring >> bdeleteB deleteForward :: YiM () deleteForward = repeatingArg $ blockKillring >> deleteB' -- Deletes current region if any, otherwise executes the given -- action. deleteRegionOr :: (Show a, YiAction (m a) a) => m a -> YiM () deleteRegionOr f = do b <- gets currentBuffer r <- withGivenBuffer b getSelectRegionB if regionSize r == 0 then runAction $ makeAction f else withGivenBuffer b $ deleteRegionB r ctrlC = choice [ ctrlCh 'c' ?>>! commentRegion ] rectangleFunctions = choice [ char 'a' ?>>! alignRegionOn , char 'o' ?>>! openRectangle , char 't' ?>>! stringRectangle , char 'k' ?>>! killRectangle , char 'y' ?>>! yankRectangle ] tabFunctions :: Keymap tabFunctions = choice [ optMod ctrl (char 'n') >>! nextTabE , optMod ctrl (char 'p') >>! previousTabE , optMod ctrl (char 't') >>! newTabE , optMod ctrl (char 'e') >>! findFileNewTab , optMod ctrl (char 'd') >>! deleteTabE , charOf id '0' '9' >>=! moveTabE . Just . digitToInt ] -- These keybindings are all preceded by a 'C-x' so for example to -- quit the editor we do a 'C-x C-c' ctrlX = choice [ ctrlCh 'o' ?>>! deleteBlankLinesB , char '0' ?>>! closeWindowEmacs , char '1' ?>>! closeOtherE , char '2' ?>>! splitE , char 'h' ?>>! selectAll , char 's' ?>>! askSaveEditor , ctrlCh 'b' ?>>! listBuffers , ctrlCh 'c' ?>>! askQuitEditor , ctrlCh 'f' ?>>! findFile , ctrlCh 'r' ?>>! findFileReadOnly , ctrlCh 'q' ?>>! ((withCurrentBuffer (readOnlyA %= not)) :: EditorM ()) , ctrlCh 's' ?>>! fwriteE , ctrlCh 'w' ?>>! promptFile "Write file:" (void . fwriteToE) , ctrlCh 'x' ?>>! (exchangePointAndMarkB >> highlightSelectionA .= True) , char 'b' ?>>! switchBufferE , char 'd' ?>>! dired , char 'e' ?>> char 'e' ?>>! evalRegionE , char 'o' ?>>! nextWinE , char 'k' ?>>! killBufferE , char 'r' ?>> rectangleFunctions , char 'u' ?>>! repeatingArg undoB , optMod ctrl (char 't') >> tabFunctions ]
ethercrow/yi
yi-keymap-emacs/src/Yi/Keymap/Emacs.hs
gpl-2.0
13,766
0
15
4,863
3,177
1,614
1,563
-1
-1
module DownloaderTests where import Test.HUnit import Downloader loadContent a b c d k isJustOk = do mimg <- downloadHubble a b c d k case mimg of Just _ -> return isJustOk Nothing -> return $ not isJustOk downloadsTests = ["Load Existing content" ~: loadContent 0 5 0 1 'a' True@? "Load Existing content Failed" ,"Load NonExisting content" ~: loadContent 1 7 0 8 'a' False@? "Load NonExisting content Failed"]
gltronred/haskell-collage
test/DownloaderTests.hs
gpl-3.0
461
0
11
120
133
66
67
10
2
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE UnicodeSyntax #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Game.Osu.FreeTaiko.Types -- License : GPL-3 -- Copyright : © Mateusz Kowalczyk, 2014 -- Maintainer : fuuzetsu@fuuzetsu.co.uk -- Stability : experimental -- Portability : portable -- -- Types used in free-taiko module Game.Osu.FreeTaiko.Types where import Control.Lens import Control.Monad.State.Strict import Data.Default import qualified Data.List.PointedList as PL import qualified Data.Text as T import Data.Typeable import Data.UnixTime import FreeGame import Game.Osu.OszLoader.Types -- | Resolution used by the window. newtype Resolution = R { _unR ∷ BoundingBox2 } deriving (Show, Eq, Ord, Typeable) -- | 800x600 default resolution instance Default Resolution where def = R $ Box (V2 0 0) (V2 1920 1080) -- | Makes a 'Resolution', defaulting to 800x600 if either given Int -- is ≤ 0. mkR :: (Integral x, Integral y) ⇒ x → y → Resolution mkR x y | x <= 0 || y <= 0 = def | otherwise = R $ Box (V2 0 0) (V2 (fromIntegral x) (fromIntegral y)) makeLenses ''Resolution data TaikoData = TaikoData { _tdGeneral ∷ General , _tdMetadata ∷ Metadata , _tdDifficulty ∷ Difficulty , _tdTimingPoints ∷ [TimingPoint] , _tdHitObjects ∷ [HitObject] } deriving (Show, Eq) makeLenses ''TaikoData data Menu = M { _currentDirectory ∷ FilePath , _maps ∷ PL.PointedList (FilePath, Either T.Text TaikoData) , _picked ∷ Maybe (FilePath, TaikoData) } deriving (Show, Eq) makeLenses ''Menu -- | State of the window data WindowState = W { _windowMode ∷ WindowMode , _resolution ∷ Resolution } deriving (Show, Eq) instance Default WindowState where def = W { _windowMode = Windowed , _resolution = def } makeLenses ''WindowState data Hit = Perfect | Good | Bad | Wrong | Miss | NOP deriving (Show, Eq) data UserSettings = U { _outsideLeft ∷ Key , _outsideRight ∷ Key , _insideLeft ∷ Key , _insideRight ∷ Key , _quitKey ∷ Key } deriving (Show, Eq) instance Default UserSettings where def = U { _outsideLeft = KeyD , _insideLeft = KeyF , _insideRight = KeyJ , _outsideRight = KeyK , _quitKey = KeyEscape } makeLenses ''UserSettings data Score = Score { _scorePerfect ∷ Int , _scoreGood ∷ Int , _scoreBad ∷ Int , _scoreWrong ∷ Int , _scoreMiss ∷ Int , _scoreCalmDown ∷ Int , _scorePoints ∷ Int } deriving (Show, Eq) instance Default Score where def = Score 0 0 0 0 0 0 0 makeLenses ''Score -- | Time-parametrised animation. data Animation m a = A { _endTime ∷ UnixTime , _animate ∷ UnixTime → m a } makeLenses ''Animation data Images = Images { _smallRed ∷ Bitmap , _smallBlue ∷ Bitmap , _bigRed ∷ Bitmap , _bigBlue ∷ Bitmap , _goal ∷ Bitmap , _innerRightPressed ∷ Bitmap , _innerLeftPressed ∷ Bitmap , _outerRightPressed ∷ Bitmap , _outerLeftPressed ∷ Bitmap , _bg1080p ∷ Bitmap , _belt ∷ Bitmap , _drum ∷ Bitmap , _hitGreatL ∷ Bitmap , _hitGreatS ∷ Bitmap , _hitGoodL ∷ Bitmap , _hitGoodS ∷ Bitmap , _hitMiss ∷ Bitmap , _numbers ∷ [Bitmap] } makeLenses ''Images data Resources = Res { _font ∷ Font , _images ∷ Images } makeLenses ''Resources data ScreenState a = S { _windowState ∷ WindowState , _quit ∷ Bool , _targetFrameRate ∷ Int , _resources ∷ Resources , _userSettings ∷ UserSettings , _screenState ∷ a } makeLenses ''ScreenState mkMenu ∷ Menu → Resources → ScreenState Menu mkMenu m r = S { _windowState = def , _quit = False , _targetFrameRate = 60 , _resources = r , _userSettings = def , _screenState = m } type MenuLoop = StateT (ScreenState Menu) Game data Don = SmallRed | SmallBlue | BigRed | BigBlue deriving (Show, Eq, Enum) -- | Time-annotated elements data Annotated a = Annot { _annotTime ∷ !UnixTime , _unAnnot ∷ a } deriving (Show, Eq, Ord) makeLenses ''Annotated data Combo = Combo { _currentCombo ∷ Int , _maxCombo ∷ Int } deriving (Show, Eq) instance Default Combo where def = Combo { _currentCombo = 0, _maxCombo = 0 } makeLenses ''Combo data SongState = SS { _dons ∷ [Annotated Don] , _elapsed ∷ !Int , _lastTick ∷ !UnixTime , _waitingFor ∷ Maybe Don , _blocking ∷ [(Key, Bitmap)] -- ^ List of keys we're waiting to go -- up and bitmaps to render while -- doing so , _flyingOff ∷ [Annotated Don] , _score ∷ Score , _songCombo ∷ Combo , _taikoData ∷ TaikoData , _goalEffects ∷ [Animation SongLoop ()] } type SongLoop = StateT (ScreenState SongState) Game makeLenses ''SongState
Fuuzetsu/free-taiko
src/Game/Osu/FreeTaiko/Types.hs
gpl-3.0
6,085
0
12
2,281
1,309
768
541
141
1
module MaaS.Tools (clamp, remap) where clamp :: Ord a => a -> a -> a -> a clamp mn mx v = (max mn . min mx) v remap :: RealFrac a => a -> a -> a -> a -> a -> a remap x imin imax omin omax = (x-imin)*(omax-omin)/(imax-imin)+omin
maeln/MaaS
MaaS/Tools.hs
gpl-3.0
230
0
10
54
147
76
71
5
1
module Hadolint.Rule.DL3023 (rule) where import Hadolint.Rule import Language.Docker.Syntax rule :: Rule args rule = customRule check (emptyState Nothing) where code = "DL3023" severity = DLErrorC message = "COPY --from should reference a previously defined FROM alias" check _ st f@(From _) = st |> replaceWith (Just f) -- Remember the last FROM instruction found check line st@(State _ (Just fromInstr)) (Copy (CopyArgs _ _ _ _ (CopySource stageName))) | aliasMustBe (/= stageName) fromInstr = st | otherwise = st |> addFail CheckFailure {..} -- cannot copy from the same stage! check _ st _ = st {-# INLINEABLE rule #-}
lukasmartinelli/hadolint
src/Hadolint/Rule/DL3023.hs
gpl-3.0
668
0
13
145
204
108
96
-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.AdExchangeSeller.Accounts.Reports.Generate -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Generate an Ad Exchange report based on the report request sent in the -- query parameters. Returns the result as JSON; to retrieve output in CSV -- format specify \"alt=csv\" as a query parameter. -- -- /See:/ <https://developers.google.com/ad-exchange/seller-rest/ Ad Exchange Seller API Reference> for @adexchangeseller.accounts.reports.generate@. module Network.Google.Resource.AdExchangeSeller.Accounts.Reports.Generate ( -- * REST Resource AccountsReportsGenerateResource -- * Creating a Request , accountsReportsGenerate , AccountsReportsGenerate -- * Request Lenses , argDimension , argLocale , argEndDate , argStartDate , argAccountId , argMetric , argSort , argFilter , argStartIndex , argMaxResults ) where import Network.Google.AdExchangeSeller.Types import Network.Google.Prelude -- | A resource alias for @adexchangeseller.accounts.reports.generate@ method which the -- 'AccountsReportsGenerate' request conforms to. type AccountsReportsGenerateResource = "adexchangeseller" :> "v2.0" :> "accounts" :> Capture "accountId" Text :> "reports" :> QueryParam "startDate" Text :> QueryParam "endDate" Text :> QueryParams "dimension" Text :> QueryParam "locale" Text :> QueryParams "metric" Text :> QueryParams "sort" Text :> QueryParams "filter" Text :> QueryParam "startIndex" (Textual Word32) :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] Report :<|> "adexchangeseller" :> "v2.0" :> "accounts" :> Capture "accountId" Text :> "reports" :> QueryParam "startDate" Text :> QueryParam "endDate" Text :> QueryParams "dimension" Text :> QueryParam "locale" Text :> QueryParams "metric" Text :> QueryParams "sort" Text :> QueryParams "filter" Text :> QueryParam "startIndex" (Textual Word32) :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltMedia :> Get '[OctetStream] Stream -- | Generate an Ad Exchange report based on the report request sent in the -- query parameters. Returns the result as JSON; to retrieve output in CSV -- format specify \"alt=csv\" as a query parameter. -- -- /See:/ 'accountsReportsGenerate' smart constructor. data AccountsReportsGenerate = AccountsReportsGenerate' { _argDimension :: !(Maybe [Text]) , _argLocale :: !(Maybe Text) , _argEndDate :: !Text , _argStartDate :: !Text , _argAccountId :: !Text , _argMetric :: !(Maybe [Text]) , _argSort :: !(Maybe [Text]) , _argFilter :: !(Maybe [Text]) , _argStartIndex :: !(Maybe (Textual Word32)) , _argMaxResults :: !(Maybe (Textual Word32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AccountsReportsGenerate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'argDimension' -- -- * 'argLocale' -- -- * 'argEndDate' -- -- * 'argStartDate' -- -- * 'argAccountId' -- -- * 'argMetric' -- -- * 'argSort' -- -- * 'argFilter' -- -- * 'argStartIndex' -- -- * 'argMaxResults' accountsReportsGenerate :: Text -- ^ 'argEndDate' -> Text -- ^ 'argStartDate' -> Text -- ^ 'argAccountId' -> AccountsReportsGenerate accountsReportsGenerate pArgEndDate_ pArgStartDate_ pArgAccountId_ = AccountsReportsGenerate' { _argDimension = Nothing , _argLocale = Nothing , _argEndDate = pArgEndDate_ , _argStartDate = pArgStartDate_ , _argAccountId = pArgAccountId_ , _argMetric = Nothing , _argSort = Nothing , _argFilter = Nothing , _argStartIndex = Nothing , _argMaxResults = Nothing } -- | Dimensions to base the report on. argDimension :: Lens' AccountsReportsGenerate [Text] argDimension = lens _argDimension (\ s a -> s{_argDimension = a}) . _Default . _Coerce -- | Optional locale to use for translating report output to a local -- language. Defaults to \"en_US\" if not specified. argLocale :: Lens' AccountsReportsGenerate (Maybe Text) argLocale = lens _argLocale (\ s a -> s{_argLocale = a}) -- | End of the date range to report on in \"YYYY-MM-DD\" format, inclusive. argEndDate :: Lens' AccountsReportsGenerate Text argEndDate = lens _argEndDate (\ s a -> s{_argEndDate = a}) -- | Start of the date range to report on in \"YYYY-MM-DD\" format, -- inclusive. argStartDate :: Lens' AccountsReportsGenerate Text argStartDate = lens _argStartDate (\ s a -> s{_argStartDate = a}) -- | Account which owns the generated report. argAccountId :: Lens' AccountsReportsGenerate Text argAccountId = lens _argAccountId (\ s a -> s{_argAccountId = a}) -- | Numeric columns to include in the report. argMetric :: Lens' AccountsReportsGenerate [Text] argMetric = lens _argMetric (\ s a -> s{_argMetric = a}) . _Default . _Coerce -- | The name of a dimension or metric to sort the resulting report on, -- optionally prefixed with \"+\" to sort ascending or \"-\" to sort -- descending. If no prefix is specified, the column is sorted ascending. argSort :: Lens' AccountsReportsGenerate [Text] argSort = lens _argSort (\ s a -> s{_argSort = a}) . _Default . _Coerce -- | Filters to be run on the report. argFilter :: Lens' AccountsReportsGenerate [Text] argFilter = lens _argFilter (\ s a -> s{_argFilter = a}) . _Default . _Coerce -- | Index of the first row of report data to return. argStartIndex :: Lens' AccountsReportsGenerate (Maybe Word32) argStartIndex = lens _argStartIndex (\ s a -> s{_argStartIndex = a}) . mapping _Coerce -- | The maximum number of rows of report data to return. argMaxResults :: Lens' AccountsReportsGenerate (Maybe Word32) argMaxResults = lens _argMaxResults (\ s a -> s{_argMaxResults = a}) . mapping _Coerce instance GoogleRequest AccountsReportsGenerate where type Rs AccountsReportsGenerate = Report type Scopes AccountsReportsGenerate = '["https://www.googleapis.com/auth/adexchange.seller", "https://www.googleapis.com/auth/adexchange.seller.readonly"] requestClient AccountsReportsGenerate'{..} = go _argAccountId (Just _argStartDate) (Just _argEndDate) (_argDimension ^. _Default) _argLocale (_argMetric ^. _Default) (_argSort ^. _Default) (_argFilter ^. _Default) _argStartIndex _argMaxResults (Just AltJSON) adExchangeSellerService where go :<|> _ = buildClient (Proxy :: Proxy AccountsReportsGenerateResource) mempty instance GoogleRequest (MediaDownload AccountsReportsGenerate) where type Rs (MediaDownload AccountsReportsGenerate) = Stream type Scopes (MediaDownload AccountsReportsGenerate) = Scopes AccountsReportsGenerate requestClient (MediaDownload AccountsReportsGenerate'{..}) = go _argAccountId (Just _argStartDate) (Just _argEndDate) (_argDimension ^. _Default) _argLocale (_argMetric ^. _Default) (_argSort ^. _Default) (_argFilter ^. _Default) _argStartIndex _argMaxResults (Just AltMedia) adExchangeSellerService where _ :<|> go = buildClient (Proxy :: Proxy AccountsReportsGenerateResource) mempty
brendanhay/gogol
gogol-adexchange-seller/gen/Network/Google/Resource/AdExchangeSeller/Accounts/Reports/Generate.hs
mpl-2.0
8,974
0
38
2,556
1,448
809
639
197
1
{-# LANGUAGE PackageImports #-} {-# LANGUAGE NamedFieldPuns #-} import Prelude (show, read) import BasicPrelude hiding (show, read, forM, mapM, forM_, mapM_, getArgs, log) import System.IO (stdout, stderr, hSetBuffering, BufferMode(LineBuffering)) import Data.Char import Control.Concurrent import Control.Concurrent.STM import Data.Foldable (forM_, mapM_, toList) import Data.Traversable (forM, mapM) import System.Environment (getArgs) import Control.Error (readZ, MaybeT(..), hoistMaybe, headZ, justZ, hush, atZ) import Data.Time (UTCTime, addUTCTime, diffUTCTime, getCurrentTime) import Network.Socket (PortNumber) import Network.URI (parseURI, uriPath, escapeURIString) import System.Random (Random(randomR), getStdRandom) import System.Random.Shuffle (shuffleM) import Data.Digest.Pure.SHA (sha1, bytestringDigest, showDigest) import Network.StatsD (openStatsD) import qualified Network.StatsD as StatsD import Magic (Magic, MagicFlag(MagicMimeType), magicOpen, magicLoadDefault, magicFile) import Network.Mime (defaultMimeMap) import "monads-tf" Control.Monad.Error (catchError) -- ick import Data.XML.Types as XML (Element(..), Node(NodeContent, NodeElement), Content(ContentText), isNamed, hasAttributeText, elementText, elementChildren, attributeText, attributeContent, hasAttribute, nameNamespace) import UnexceptionalIO (Unexceptional, UIO) import qualified UnexceptionalIO as UIO import qualified Dhall import qualified Jingle import qualified Jingle.StoreChunks as Jingle import qualified Data.CaseInsensitive as CI import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Map as Map import qualified Data.Map.Strict as SMap import qualified Data.UUID as UUID ( toString ) import qualified Data.UUID.V1 as UUID ( nextUUID ) import qualified Data.ByteString.Lazy as LZ import qualified Data.ByteString as BS import qualified Data.ByteString.Base64 as Base64 import qualified Data.ByteString.Builder as Builder import qualified Database.Redis as Redis import qualified Text.Regex.PCRE.Light as PCRE import qualified Network.Http.Client as HTTP import qualified System.IO.Streams as Streams import Network.Protocol.XMPP as XMPP -- should import qualified import Util import IQManager import qualified ConfigureDirectMessageRoute import qualified Config import qualified DB import Adhoc (adhocBotSession, commandList, queryCommandList) import StanzaRec instance Ord JID where compare x y = compare (show x) (show y) mimeToExtMap :: SMap.Map String Text mimeToExtMap = SMap.fromList $ map (\(ext, mimeBytes) -> (textToString (decodeUtf8 mimeBytes), ext) ) $ SMap.toList defaultMimeMap queryDisco to from = (:[]) . mkStanzaRec <$> queryDiscoWithNode Nothing to from queryDiscoWithNode node to from = do uuid <- (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID return $ (queryDiscoWithNode' node to from) { iqID = uuid } fillFormField var value form = form { elementNodes = map (\node -> case node of NodeElement el | elementName el == fromString "{jabber:x:data}field" && (attributeText (fromString "{jabber:x:data}var") el == Just var || attributeText (fromString "var") el == Just var) -> NodeElement $ el { elementNodes = [ NodeElement $ Element (fromString "{jabber:x:data}value") [] [NodeContent $ ContentText value] ]} x -> x ) (elementNodes form) } data Invite = Invite { inviteMUC :: JID, inviteFrom :: JID, inviteText :: Maybe Text, invitePassword :: Maybe Text } deriving (Show) getMediatedInvitation m = do from <- messageFrom m x <- listToMaybe $ isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< messagePayloads m invite <- listToMaybe $ isNamed (fromString "{http://jabber.org/protocol/muc#user}invite") =<< elementChildren x inviteFrom <- parseJID =<< attributeText (fromString "from") invite return Invite { inviteMUC = from, inviteFrom = inviteFrom, inviteText = do txt <- mconcat . elementText <$> listToMaybe (isNamed (fromString "{http://jabber.org/protocol/muc#user}reason") =<< elementChildren invite) guard (not $ T.null txt) return txt, invitePassword = mconcat . elementText <$> listToMaybe (isNamed (fromString "{http://jabber.org/protocol/muc#user}password") =<< elementChildren x) } getDirectInvitation m = do x <- listToMaybe $ isNamed (fromString "{jabber:x:conference}x") =<< messagePayloads m Invite <$> (parseJID =<< attributeText (fromString "jid") x) <*> messageFrom m <*> Just (do txt <- attributeText (fromString "reason") x guard (not $ T.null txt) return txt ) <*> Just (attributeText (fromString "password") x) nickFor db jid existingRoom | fmap bareTxt existingRoom == Just bareFrom = return $ fromMaybe (s"nonick") resourceFrom | Just tel <- mfilter isE164 (strNode <$> jidNode jid) = do mnick <- DB.get db (DB.byNode jid ["nick"]) case mnick of Just nick -> return (tel <> s" \"" <> nick <> s"\"") Nothing -> return tel | otherwise = return bareFrom where bareFrom = bareTxt jid resourceFrom = strResource <$> jidResource jid code str status = hasAttributeText (fromString "{http://jabber.org/protocol/muc#user}code") (== fromString str) status <> hasAttributeText (fromString "code") (== fromString str) status cheogramDiscoInfo db componentJid sendIQ from q = do canVoice <- isJust <$> getSipProxy db componentJid sendIQ from return $ Element (s"{http://jabber.org/protocol/disco#info}query") (map (\node -> (s"{http://jabber.org/protocol/disco#info}node", [ContentText node])) $ maybeToList $ nodeAttribute =<< q) (catMaybes [ Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}identity") [ (s"category", [ContentText $ s"gateway"]), (s"type", [ContentText $ s"sms"]), (s"name", [ContentText $ s"Cheogram"]) ] [], mfilter (const canVoice) $ Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}identity") [ (s"category", [ContentText $ s"gateway"]), (s"type", [ContentText $ s"pstn"]), (s"name", [ContentText $ s"Cheogram"]) ] [], Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}feature") [ (s"var", [ContentText $ s"http://jabber.org/protocol/commands"]) ] [], Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}feature") [ (s"var", [ContentText $ s"jabber:iq:gateway"]) ] [], Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}feature") [ (s"var", [ContentText $ s"jabber:iq:register"]) ] [], Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}feature") [ (s"var", [ContentText $ s"urn:xmpp:ping"]) ] [], Just $ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}feature") [ (s"var", [ContentText $ s"vcard-temp"]) ] [] ]) cheogramAvailable db componentJid sendIQ from to = do disco <- cheogramDiscoInfo db componentJid sendIQ to Nothing let ver = T.decodeUtf8 $ Base64.encode $ discoToCapsHash disco return $ (emptyPresence PresenceAvailable) { presenceTo = Just to, presenceFrom = Just from, presencePayloads = [ Element (s"{http://jabber.org/protocol/caps}c") [ (s"{http://jabber.org/protocol/caps}hash", [ContentText $ fromString "sha-1"]), (s"{http://jabber.org/protocol/caps}node", [ContentText $ fromString "xmpp:cheogram.com"]), (s"{http://jabber.org/protocol/caps}ver", [ContentText ver]) ] [] ] } telDiscoFeatures = [ s"http://jabber.org/protocol/muc", s"jabber:x:conference", s"urn:xmpp:ping", s"urn:xmpp:receipts", s"vcard-temp", s"urn:xmpp:jingle:1", s"urn:xmpp:jingle:apps:file-transfer:3", s"urn:xmpp:jingle:apps:file-transfer:5", s"urn:xmpp:jingle:transports:s5b:1", s"urn:xmpp:jingle:transports:ibb:1" ] getSipProxy :: DB.DB -> JID -> (IQ -> UIO (STM (Maybe IQ))) -> JID -> IO (Maybe Text) getSipProxy db componentJid sendIQ jid = do maybeProxy <- DB.get db (DB.byJid jid ["sip-proxy"]) case maybeProxy of Just proxy -> return $ Just proxy Nothing -> (extractSip =<<) <$> routeQueryStateful db componentJid sendIQ jid Nothing query where query jidTo jidFrom = return $ (emptyIQ IQGet) { iqTo = Just jidTo, iqFrom = Just jidFrom, iqPayload = Just $ XML.Element (s"{urn:xmpp:extdisco:2}services") [ (s"type", [XML.ContentText $ s"sip"]) ] [] } extractSip (IQ { iqPayload = payload }) = headZ $ (mapMaybe (attributeText (s"host")) $ filter (\el -> attributeText (s"type") el == Just (s"sip")) $ isNamed (s"{urn:xmpp:extdisco:2}service") =<< elementChildren =<< (justZ payload)) getTelFeatures db componentJid sendIQ jid = do maybeProxy <- getSipProxy db componentJid sendIQ jid log "TELFEATURES" (jid, maybeProxy) return $ maybe [] (const $ [s"urn:xmpp:jingle:transports:ice-udp:1", s"urn:xmpp:jingle:apps:dtls:0", s"urn:xmpp:jingle:apps:rtp:1", s"urn:xmpp:jingle:apps:rtp:audio", s"urn:xmpp:jingle-message:0"]) maybeProxy telCapsStr extraVars = s"client/sms//Cheogram<" ++ mconcat (intersperse (s"<") (sort (nub (telDiscoFeatures ++ extraVars)))) ++ s"<" telAvailable from to disco = (emptyPresence PresenceAvailable) { presenceTo = Just to, presenceFrom = Just fromWithResource, presencePayloads = [ Element (s"{http://jabber.org/protocol/caps}c") [ (s"{http://jabber.org/protocol/caps}hash", [ContentText $ fromString "sha-1"]), (s"{http://jabber.org/protocol/caps}node", [ContentText $ fromString "xmpp:cheogram.com"]), (s"{http://jabber.org/protocol/caps}ver", [ContentText hash]) ] [] ] } where fromWithResource | Nothing <- jidResource from, Just newFrom <- parseJID (bareTxt from ++ s"/tel") = newFrom | otherwise = from hash = T.decodeUtf8 $ Base64.encode $ LZ.toStrict $ bytestringDigest $ sha1 $ LZ.fromStrict $ T.encodeUtf8 $ telCapsStr disco nodeAttribute el = attributeText (s"{http://jabber.org/protocol/disco#info}node") el <|> attributeText (s"node") el telDiscoInfo q id from to disco = (emptyIQ IQResult) { iqTo = Just to, iqFrom = Just from, iqID = Just id, iqPayload = Just $ Element (fromString "{http://jabber.org/protocol/disco#info}query") (map (\node -> (s"{http://jabber.org/protocol/disco#info}node", [ContentText node])) $ maybeToList $ nodeAttribute q) $ [ NodeElement $ Element (s"{http://jabber.org/protocol/disco#info}identity") [ (s"{http://jabber.org/protocol/disco#info}category", [ContentText $ s"client"]), (s"{http://jabber.org/protocol/disco#info}type", [ContentText $ s"sms"]), (s"{http://jabber.org/protocol/disco#info}name", [ContentText $ s"Cheogram"]) ] [] ] ++ map (\var -> NodeElement $ Element (fromString "{http://jabber.org/protocol/disco#info}feature") [ (fromString "{http://jabber.org/protocol/disco#info}var", [ContentText var]) ] [] ) (sort $ nub $ telDiscoFeatures ++ disco) } routeQueryOrReply db componentJid from smsJid resource query reply = do maybeRoute <- DB.get db (DB.byJid from ["direct-message-route"]) case (maybeRoute, maybeRouteFrom) of (Just route, Just routeFrom) -> let routeTo = fromMaybe componentJid $ parseJID $ (maybe mempty (++ s"@") $ strNode <$> jidNode smsJid) ++ route in query routeTo routeFrom _ -> return [mkStanzaRec $ reply] where maybeRouteFrom = parseJID $ escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid ++ s"/" ++ (fromString resource) routeQueryStateful db componentJid sendIQ from targetNode query = do maybeRoute <- DB.get db (DB.byJid from ["direct-message-route"]) case (maybeRoute, maybeRouteFrom) of (Just route, Just routeFrom) -> do let Just routeTo = parseJID $ (maybe mempty (++ s"@") $ strNode <$> targetNode) ++ route iqToSend <- query routeTo routeFrom result <- atomicUIO =<< UIO.lift (sendIQ iqToSend) return $ mfilter ((==IQResult) . iqType) result _ -> return Nothing where maybeRouteFrom = parseJID $ escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid ++ s"/IQMANAGER" routeDiscoStateful db componentJid sendIQ from targetNode node = routeQueryStateful db componentJid sendIQ from targetNode (queryDiscoWithNode node) routeDiscoOrReply db componentJid from smsJid resource node reply = routeQueryOrReply db componentJid from smsJid resource (fmap (pure . mkStanzaRec) .: queryDiscoWithNode node) reply deliveryReceipt id from to = (emptyMessage MessageNormal) { messageFrom = Just from, messageTo = Just to, messagePayloads = [ Element (s"{urn:xmpp:receipts}received") [(s"{urn:xmpp:receipts}id", [ContentText id])] [] ] } iqNotImplemented iq = iq { iqTo = iqFrom iq, iqFrom = iqTo iq, iqType = IQError, iqPayload = Just $ Element (s"{jabber:component:accept}error") [(s"{jabber:component:accept}type", [ContentText $ fromString "cancel"])] [NodeElement $ Element (s"{urn:ietf:params:xml:ns:xmpp-stanzas}feature-not-implemented") [] []] } stripOptionalSuffix suffix text = fromMaybe text $ T.stripSuffix suffix text -- https://otr.cypherpunks.ca/Protocol-v3-4.0.0.html stripOtrWhitespaceOnce body = foldl' (\body' suffix -> stripOptionalSuffix suffix body') body [ s"\x20\x20\x09\x09\x20\x20\x09\x09", s"\x20\x20\x09\x09\x20\x20\x09\x20", s"\x20\x09\x20\x09\x20\x20\x09\x20", s"\x20\x09\x20\x20\x09\x09\x09\x09", s"\x20\x09\x20\x09\x20\x09\x20\x20" ] stripOtrWhitespace = stripOtrWhitespaceOnce . stripOtrWhitespaceOnce . stripOtrWhitespaceOnce . stripOtrWhitespaceOnce . stripOtrWhitespaceOnce mapBody f (m@Message { messagePayloads = payloads }) = m { messagePayloads = map (\payload -> case isNamed (s"{jabber:component:accept}body") payload of [] -> payload _ -> payload { elementNodes = [NodeContent $ ContentText $ f (concat (elementText payload))] } ) payloads } unregisterDirectMessageRoute db componentJid userJid route = do maybeCheoJid <- (parseJID =<<) <$> DB.get db (DB.byJid userJid ["cheoJid"]) forM_ maybeCheoJid $ \cheoJid -> do DB.del db (DB.byJid userJid ["cheoJid"]) DB.srem db (DB.byNode cheoJid ["owners"]) [bareTxt userJid] uuid <- (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID return $ (emptyIQ IQSet) { iqTo = Just route, iqFrom = parseJID $ escapeJid (bareTxt userJid) ++ s"@" ++ formatJID componentJid ++ s"/CHEOGRAM%removed", iqID = uuid, iqPayload = Just $ Element (s"{jabber:iq:register}query") [] [ NodeElement $ Element (s"{jabber:iq:register}remove") [] [] ] } toRouteOrFallback db componentJid from smsJid m fallback = do maybeRoute <- DB.get db (DB.byJid from ["direct-message-route"]) case (maybeRoute, parseJID $ escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid ++ resourceSuffix) of (Just route, Just routeFrom) -> do return [mkStanzaRec $ m { messageFrom = Just routeFrom, messageTo = parseJID $ (fromMaybe mempty $ strNode <$> jidNode smsJid) ++ s"@" ++ route }] _ -> fallback where resourceSuffix = maybe mempty (s"/"++) (strResource <$> jidResource from) componentMessage db componentJid (m@Message { messageType = MessageError }) _ from smsJid body = do log "MESSAGE ERROR" m toRouteOrFallback db componentJid from smsJid m $ do log "DIRECT FROM GATEWAY" smsJid return [mkStanzaRec $ m { messageTo = Just smsJid, messageFrom = Just componentJid }] componentMessage db componentJid m@(Message { messageTo = Just to@JID{ jidNode = Just _ } }) existingRoom _ smsJid _ | Just invite <- getMediatedInvitation m <|> getDirectInvitation m = do forM_ (invitePassword invite) $ \password -> DB.set db (DB.byNode to [textToString $ formatJID $ inviteMUC invite, "muc_roomsecret"]) password existingInvite <- (parseJID =<<) <$> DB.get db (DB.byNode to ["invited"]) nick <- nickFor db (inviteFrom invite) existingRoom let txt = mconcat [ fromString "* ", nick, fromString " has invited you to a group", maybe mempty (\t -> fromString ", saying \"" <> t <> fromString "\"") (inviteText invite), fromString "\nYou can switch to this group by replying with /join" ] if (existingRoom /= Just (inviteMUC invite) && existingInvite /= Just (inviteMUC invite)) then do DB.set db (DB.byNode to ["invited"]) (formatJID $ inviteMUC invite) regJid <- (parseJID =<<) <$> DB.get db (DB.byNode to ["registered"]) fmap (((mkStanzaRec $ mkSMS componentJid smsJid txt):) . concat . toList) (forM regJid $ \jid -> sendInvite db jid (invite { inviteFrom = to })) else return [] componentMessage _ componentJid (m@Message { messageType = MessageGroupChat }) existingRoom from smsJid (Just body) = do if fmap bareTxt existingRoom == Just (bareTxt from) && ( existingRoom /= Just from || not (fromString "CHEOGRAM%" `T.isPrefixOf` fromMaybe mempty (messageID m))) then return [mkStanzaRec $ mkSMS componentJid smsJid txt] else do log "MESSAGE FROM WRONG GROUP" (fmap bareTxt existingRoom, from, m) return [] where txt = mconcat [fromString "(", fromMaybe (fromString "nonick") (strResource <$> jidResource from), fromString ") ", body] componentMessage db componentJid m@(Message { messageTo = Just to }) existingRoom from smsJid (Just body) = do ack <- case isNamed (fromString "{urn:xmpp:receipts}request") =<< messagePayloads m of (_:_) -> routeDiscoOrReply db componentJid from smsJid ("CHEOGRAM%query-then-send-ack%" ++ extra) Nothing (deliveryReceipt (fromMaybe mempty $ messageID m) to from) [] -> return [] fmap (++ack) $ toRouteOrFallback db componentJid from smsJid strippedM $ case PCRE.match autolinkRegex (encodeUtf8 body) [] of Just _ -> do log "WHISPER URL" m return [mkStanzaRec $ m { messageFrom = Just to, messageTo = Just from, messageType = MessageError, messagePayloads = messagePayloads m ++ [ Element (fromString "{jabber:component:accept}error") [(fromString "{jabber:component:accept}type", [ContentText $ fromString "auth"])] [NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}forbidden") [] []] ] }] Nothing -> do nick <- nickFor db from existingRoom let txt = mconcat [s"<", nick, s" says> ", strippedBody] return [mkStanzaRec $ mkSMS componentJid smsJid txt] where strippedM = mapBody (const strippedBody) m strippedBody = stripOtrWhitespace body extra = T.unpack $ escapeJid $ T.pack $ show (fromMaybe mempty (messageID m), maybe mempty strResource $ jidResource from) componentMessage _ _ m _ _ _ _ = do log "UNKNOWN MESSAGE" m return [] handleJoinPartRoom db toRoomPresences toRejoinManager toJoinPartDebouncer componentJid existingRoom from to smsJid payloads join | join, [x] <- isNamed (s"{http://jabber.org/protocol/muc#user}x") =<< payloads, not $ null $ code "110" =<< isNamed (fromString "{http://jabber.org/protocol/muc#user}status") =<< elementChildren x = do existingInvite <- (parseJID =<<) <$> DB.get db (DB.byNode to ["invited"]) when (existingInvite == parseJID bareMUC) $ DB.del db (DB.byNode to ["invited"]) DB.set db (DB.byNode to ["joined"]) (formatJID from) DB.sadd db (DB.byNode to ["bookmarks"]) [bareMUC] presences <- syncCall toRoomPresences $ GetRoomPresences to from atomically $ writeTChan toRoomPresences $ RecordSelfJoin to from (Just to) atomically $ writeTChan toRejoinManager $ Joined from case presences of [] -> do -- No one in the room, so we "created" uuid <- fromMaybe "UUIDFAIL" <$> (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID let fullid = if (resourceFrom `elem` map fst presences) then uuid else "CHEOGRAMCREATE%" <> uuid return [mkStanzaRec $ (emptyIQ IQGet) { iqTo = Just room, iqFrom = Just to, iqID = Just $ fromString fullid, iqPayload = Just $ Element (fromString "{http://jabber.org/protocol/muc#owner}query") [] [] }] (_:_) | isNothing (lookup resourceFrom presences) -> do fmap ((mkStanzaRec $ mkSMS componentJid smsJid $ mconcat [ s"* You have joined ", bareMUC, s" as ", resourceFrom, s" along with\n", intercalate (s", ") (filter (/= resourceFrom) $ map fst presences) ]):) (queryDisco room to) _ -> do log "JOINED" (to, from, "FALSE PRESENCE") queryDisco room to | not join, [x] <- isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< payloads, (_:_) <- code "303" =<< isNamed (fromString "{http://jabber.org/protocol/muc#user}status") =<< elementChildren x = do let mnick = attributeText (fromString "nick") =<< listToMaybe (isNamed (fromString "{http://jabber.org/protocol/muc#user}item") =<< elementChildren x) toList <$> forM mnick (\nick -> do atomically $ writeTChan toRoomPresences $ RecordNickChanged to from nick return $ mkStanzaRec $ mkSMS componentJid smsJid $ mconcat [ fromString "* ", resourceFrom, fromString " has changed their nick to ", nick ] ) | not join, [x] <- isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< payloads, (_:_) <- code "332" =<< isNamed (fromString "{http://jabber.org/protocol/muc#user}status") =<< elementChildren x = do log "SERVER RESTART, rejoin in 5s" (to, from) void $ forkIO $ threadDelay 5000000 >> atomically (writeTChan toRejoinManager $ ForceRejoin from to) return [] | not join && existingRoom == Just from = do DB.del db (DB.byNode to ["joined"]) atomically $ writeTChan toRoomPresences $ RecordPart to from atomically $ writeTChan toRoomPresences $ Clear to from return [mkStanzaRec $ mkSMS componentJid smsJid (fromString "* You have left " <> bareMUC)] | fmap bareTxt existingRoom == Just bareMUC && join = do atomically $ writeTChan toJoinPartDebouncer $ DebounceJoin to from (participantJid payloads) return [] | fmap bareTxt existingRoom == Just bareMUC && not join = do atomically $ writeTChan toJoinPartDebouncer $ DebouncePart to from return [] | join, (_:_) <- isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< payloads = do log "UNKNOWN JOIN" (existingRoom, from, to, payloads, join) atomically $ writeTChan toRoomPresences $ RecordJoin to from (participantJid payloads) return [] | (_:_) <- isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< payloads = do log "UNKNOWN NOT JOIN" (existingRoom, from, to, payloads, join) atomically $ writeTChan toRoomPresences $ RecordPart to from return [] | otherwise = -- This is just presence. It's not marked as MUC or from the room this user is in return [] where resourceFrom = fromMaybe mempty (strResource <$> jidResource from) Just room = parseJID bareMUC bareMUC = bareTxt from verificationResponse = Element (fromString "{jabber:iq:register}query") [] [ NodeElement $ Element (fromString "{jabber:iq:register}instructions") [] [ NodeContent $ ContentText $ fromString "Enter the verification code CheoGram texted you." ], NodeElement $ Element (fromString "{jabber:iq:register}password") [] [], NodeElement $ Element (fromString "{jabber:x:data}x") [ (fromString "{jabber:x:data}type", [ContentText $ fromString "form"]) ] [ NodeElement $ Element (fromString "{jabber:x:data}title") [] [NodeContent $ ContentText $ fromString "Verify Phone Number"], NodeElement $ Element (fromString "{jabber:x:data}instructions") [] [ NodeContent $ ContentText $ fromString "Enter the verification code CheoGram texted you." ], NodeElement $ Element (fromString "{jabber:x:data}field") [ (fromString "{jabber:x:data}type", [ContentText $ fromString "hidden"]), (fromString "{jabber:x:data}var", [ContentText $ fromString "FORM_TYPE"]) ] [ NodeElement $ Element (fromString "{jabber:x:data}value") [] [NodeContent $ ContentText $ fromString "jabber:iq:register"] ], NodeElement $ Element (fromString "{jabber:x:data}field") [ (fromString "{jabber:x:data}type", [ContentText $ fromString "text-single"]), (fromString "{jabber:x:data}var", [ContentText $ fromString "password"]), (fromString "{jabber:x:data}label", [ContentText $ fromString "Verification code"]) ] [] ] ] data RegistrationCode = RegistrationCode { regCode :: Int, cheoJid :: Text, expires :: UTCTime } deriving (Show, Read) registerVerification db componentJid to iq = do code <- getStdRandom (randomR (123457::Int,987653)) time <- getCurrentTime forM_ (iqFrom iq) $ \from -> DB.set db (DB.byJid from ["registration_code"]) $ tshow $ RegistrationCode code (formatJID to) time return [ mkStanzaRec $ mkSMS componentJid to $ fromString ("Enter this verification code to complete registration: " <> show code), mkStanzaRec $ iq { iqTo = iqFrom iq, iqFrom = iqTo iq, iqType = IQResult, iqPayload = Just verificationResponse } ] handleVerificationCode db componentJid password iq from = do time <- getCurrentTime codeAndTime <- fmap (readZ . textToString =<<) $ DB.get db (DB.byJid from ["registration_code"]) case codeAndTime of Just (RegistrationCode { regCode = code, cheoJid = cheoJidT }) | fmap expires codeAndTime > Just ((-300) `addUTCTime` time) -> case (show code == T.unpack password, iqTo iq, parseJID cheoJidT) of (True, Just to, Just cheoJid) -> do bookmarks <- DB.smembers db (DB.byNode cheoJid ["bookmarks"]) invites <- fmap concat $ forM (mapMaybe parseJID bookmarks) $ \bookmark -> sendInvite db from (Invite bookmark cheoJid (Just $ fromString "Cheogram registration") Nothing) let Just tel = strNode <$> jidNode cheoJid DB.set db (DB.byJid from ["registered"]) tel DB.set db (DB.byNode cheoJid ["registered"]) (bareTxt from) stuff <- runMaybeT $ do -- If there is a nick that doesn't end in _sms, add _sms nick <- MaybeT $ DB.get db (DB.byNode cheoJid ["nick"]) let nick' = (fromMaybe nick $ T.stripSuffix (s"_sms") nick) <> s"_sms" liftIO $ DB.set db (DB.byNode cheoJid ["nick"]) nick' room <- MaybeT $ (parseJID =<<) <$> DB.get db (DB.byNode cheoJid ["joined"]) toJoin <- hoistMaybe $ parseJID (bareTxt room <> fromString "/" <> nick') liftIO $ joinRoom db cheoJid toJoin return ((mkStanzaRec $ iq { iqTo = iqFrom iq, iqFrom = iqTo iq, iqType = IQResult, iqPayload = Just $ Element (fromString "{jabber:iq:register}query") [] [] }):invites) _ -> return [mkStanzaRec $ iq { iqTo = iqFrom iq, iqFrom = iqTo iq, iqType = IQError, iqPayload = Just $ Element (fromString "{jabber:component:accept}error") [(fromString "{jabber:component:accept}type", [ContentText $ fromString "auth"])] [NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}not-authorized") [] []] }] _ -> do DB.del db (DB.byJid from ["registration_code"]) return [] handleRegister db componentJid iq@(IQ { iqType = IQGet, iqFrom = Just from }) _ = do time <- getCurrentTime codeAndTime <- fmap (readZ . textToString =<<) $ DB.get db (DB.byJid from ["registration_code"]) if fmap expires codeAndTime > Just ((-300) `addUTCTime` time) then return [mkStanzaRec $ iq { iqTo = iqFrom iq, iqFrom = iqTo iq, iqType = IQResult, iqPayload = Just verificationResponse }] else return [mkStanzaRec $ iq { iqTo = iqFrom iq, iqFrom = iqTo iq, iqType = IQResult, iqPayload = Just $ Element (fromString "{jabber:iq:register}query") [] [ NodeElement $ Element (fromString "{jabber:iq:register}instructions") [] [ NodeContent $ ContentText $ fromString "CheoGram can verify your phone number and add you to the private groups you previously texted." ], NodeElement $ Element (fromString "{jabber:iq:register}phone") [] [], NodeElement $ Element (fromString "{jabber:x:data}x") [ (fromString "{jabber:x:data}type", [ContentText $ fromString "form"]) ] [ NodeElement $ Element (fromString "{jabber:x:data}title") [] [NodeContent $ ContentText $ fromString "Associate Phone Number"], NodeElement $ Element (fromString "{jabber:x:data}instructions") [] [ NodeContent $ ContentText $ fromString "CheoGram can verify your phone number and add you to the private groups you previously texted." ], NodeElement $ Element (fromString "{jabber:x:data}field") [ (fromString "{jabber:x:data}type", [ContentText $ fromString "hidden"]), (fromString "{jabber:x:data}var", [ContentText $ fromString "FORM_TYPE"]) ] [ NodeElement $ Element (fromString "{jabber:x:data}value") [] [NodeContent $ ContentText $ fromString "jabber:iq:register"] ], NodeElement $ Element (fromString "{jabber:x:data}field") [ (fromString "{jabber:x:data}type", [ContentText $ fromString "text-single"]), (fromString "{jabber:x:data}var", [ContentText $ fromString "phone"]), (fromString "{jabber:x:data}label", [ContentText $ fromString "Phone number"]) ] [] ] ] }] handleRegister db componentJid iq@(IQ { iqType = IQSet }) query | [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren query, Just to <- ((`telToJid` formatJID componentJid) . T.filter isDigit) =<< getFormField form (fromString "phone") = do registerVerification db componentJid to iq handleRegister db componentJid iq@(IQ { iqType = IQSet }) query | [phoneEl] <- isNamed (fromString "{jabber:iq:register}phone") =<< elementChildren query, Just to <- (`telToJid` formatJID componentJid) $ T.filter isDigit $ mconcat (elementText phoneEl) = do registerVerification db componentJid to iq handleRegister db componentJid iq@(IQ { iqType = IQSet, iqFrom = Just from }) query | [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren query, Just password <- getFormField form (fromString "password") = do handleVerificationCode db componentJid password iq from handleRegister db componentJid iq@(IQ { iqType = IQSet, iqPayload = Just payload, iqFrom = Just from }) query | [passwordEl] <- isNamed (fromString "{jabber:iq:register}password") =<< elementChildren query = do handleVerificationCode db componentJid (mconcat $ elementText passwordEl) iq from handleRegister db componentJid iq@(IQ { iqFrom = Just from, iqType = IQSet }) query | [_] <- isNamed (fromString "{jabber:iq:register}remove") =<< elementChildren query = do tel <- fromMaybe mempty <$> DB.get db (DB.byJid from ["registered"]) forM_ (telToJid tel (formatJID componentJid)) $ \cheoJid -> DB.del db (DB.byNode cheoJid ["registered"]) DB.del db (DB.byJid from ["registered"]) return [mkStanzaRec $ iq { iqTo = iqFrom iq, iqFrom = iqTo iq, iqType = IQResult, iqPayload = Just $ Element (fromString "{jabber:iq:register}query") [] [] }] handleRegister _ _ iq@(IQ { iqType = typ }) _ | typ `elem` [IQGet, IQSet] = do log "HANDLEREGISTER return error" iq return [mkStanzaRec $ iq { iqTo = iqFrom iq, iqFrom = iqTo iq, iqType = IQError, iqPayload = Just $ Element (fromString "{jabber:component:accept}error") [(fromString "{jabber:component:accept}type", [ContentText $ fromString "cancel"])] [NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}feature-not-implemented") [] []] }] handleRegister _ _ iq _ = do log "HANDLEREGISTER UNKNOWN" iq return [] data ComponentContext = ComponentContext { db :: DB.DB, smsJid :: Maybe JID, registrationJids :: [JID], adhocBotMessage :: Message -> STM (), ctxCacheOOB :: Message -> UIO Message, toRoomPresences :: TChan RoomPresences, toRejoinManager :: TChan RejoinManagerCommand, toJoinPartDebouncer :: TChan JoinPartDebounce, processDirectMessageRouteConfig :: IQ -> IO (Maybe IQ), componentJid :: JID, sendIQ :: IQ -> UIO (STM (Maybe IQ)), maybeAvatar :: Maybe Avatar } componentStanza :: ComponentContext -> ReceivedStanza -> IO [StanzaRec] componentStanza (ComponentContext { adhocBotMessage, ctxCacheOOB, componentJid }) (ReceivedMessage (m@Message { messageTo = Just (JID { jidNode = Nothing }) })) | Just reply <- groupTextPorcelein (formatJID componentJid) m = do -- TODO: only when from direct message route -- TODO: only if target does not understand stanza addressing reply' <- UIO.lift $ ctxCacheOOB reply return [mkStanzaRec reply'] | Just _ <- getBody "jabber:component:accept" m = do atomicUIO $ adhocBotMessage m return [] | otherwise = log "WEIRD BODYLESS MESSAGE DIRECT TO COMPONENT" m >> return [] componentStanza (ComponentContext { db, componentJid, sendIQ, smsJid = Just smsJid }) (ReceivedMessage (m@Message { messageTo = Just to, messageFrom = Just from})) | [propose] <- isNamed (fromString "{urn:xmpp:jingle-message:0}propose") =<< messagePayloads m = do let sid = fromMaybe mempty $ XML.attributeText (s"id") propose telFeatures <- getTelFeatures db componentJid sendIQ from stanzas <- routeDiscoOrReply db componentJid from smsJid "CHEOGRAM%query-then-send-presence" Nothing $ telAvailable to from telFeatures return $ (mkStanzaRec $ (XMPP.emptyMessage XMPP.MessageNormal) { XMPP.messageID = Just $ s"proceed%" ++ sid, XMPP.messageTo = Just from, XMPP.messageFrom = XMPP.parseJID $ bareTxt to ++ s"/tel", XMPP.messagePayloads = [ XML.Element (s"{urn:xmpp:jingle-message:0}proceed") [(s"id", [XML.ContentText sid])] [] ] }) : stanzas componentStanza _ (ReceivedMessage (m@Message { messageTo = Just to, messageFrom = Just from})) | [x] <- isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< messagePayloads m, not $ null $ code "104" =<< isNamed (fromString "{http://jabber.org/protocol/muc#user}status") =<< elementChildren x = do queryDisco from to componentStanza (ComponentContext { db, smsJid = (Just smsJid), componentJid }) (ReceivedMessage (m@Message { messageTo = Just to@(JID { jidNode = Just _ }), messageFrom = Just from})) = do existingRoom <- (parseJID =<<) <$> DB.get db (DB.byNode to ["joined"]) componentMessage db componentJid m existingRoom from smsJid $ getBody "jabber:component:accept" m componentStanza (ComponentContext { smsJid = (Just smsJid), toRejoinManager, componentJid }) (ReceivedPresence p@(Presence { presenceType = PresenceError, presenceFrom = Just from, presenceTo = Just to, presenceID = Just id })) | fromString "CHEOGRAMREJOIN%" `T.isPrefixOf` id = do log "FAILED TO REJOIN, try again in 10s" p void $ forkIO $ threadDelay 10000000 >> atomically (writeTChan toRejoinManager $ ForceRejoin from to) return [] | fromString "CHEOGRAMJOIN%" `T.isPrefixOf` id = do log "FAILED TO JOIN" p let errorText = maybe mempty (mconcat . (fromString "\n":) . elementText) $ listToMaybe $ isNamed (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}text") =<< elementChildren =<< isNamed (fromString "{jabber:component:accept}error") =<< presencePayloads p return [mkStanzaRec $ mkSMS componentJid smsJid (fromString "* Failed to join " <> bareTxt from <> errorText)] | otherwise = return [] -- presence error from a non-MUC, just ignore componentStanza (ComponentContext { db, smsJid = (Just smsJid), toRoomPresences, toRejoinManager, toJoinPartDebouncer, componentJid }) (ReceivedPresence (Presence { presenceType = typ, presenceFrom = Just from, presenceTo = Just to@(JID { jidNode = Just _ }), presencePayloads = payloads })) | typ `elem` [PresenceAvailable, PresenceUnavailable] = do existingRoom <- (parseJID =<<) <$> DB.get db (DB.byNode to ["joined"]) handleJoinPartRoom db toRoomPresences toRejoinManager toJoinPartDebouncer componentJid existingRoom from to smsJid payloads (typ == PresenceAvailable) componentStanza (ComponentContext { db, componentJid, sendIQ, maybeAvatar }) (ReceivedPresence (Presence { presenceType = PresenceSubscribe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Nothing } })) = do avail <- cheogramAvailable db componentJid sendIQ to from return $ [ mkStanzaRec $ (emptyPresence PresenceSubscribed) { presenceTo = Just from, presenceFrom = Just to }, mkStanzaRec $ (emptyPresence PresenceSubscribe) { presenceTo = Just from, presenceFrom = Just to }, mkStanzaRec avail ] ++ map (mkStanzaRec . (\payload -> ((emptyMessage MessageHeadline) { messageTo = Just from, messageFrom = Just to, messagePayloads = [payload] })) . avatarMetadata) (justZ maybeAvatar) componentStanza (ComponentContext { db, smsJid = (Just smsJid), componentJid }) (ReceivedPresence (Presence { presenceType = PresenceSubscribe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Just _ } })) = do stanzas <- routeDiscoOrReply db componentJid from smsJid "CHEOGRAM%query-then-send-presence" Nothing $ telAvailable to from [] return $ [ mkStanzaRec $ (emptyPresence PresenceSubscribed) { presenceTo = Just from, presenceFrom = Just to }, mkStanzaRec $ (emptyPresence PresenceSubscribe) { presenceTo = Just from, presenceFrom = Just to } ] ++ stanzas componentStanza (ComponentContext { smsJid = Nothing }) (ReceivedPresence (Presence { presenceType = PresenceSubscribe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Just node } })) | Just _ <- mapM localpartToURI (T.split (==',') $ strNode node) = do return $ [ mkStanzaRec $ (emptyPresence PresenceSubscribed) { presenceTo = Just from, presenceFrom = Just to }, mkStanzaRec $ (emptyPresence PresenceSubscribe) { presenceTo = Just from, presenceFrom = Just to }, mkStanzaRec $ telAvailable to from [] ] componentStanza (ComponentContext { db, componentJid, sendIQ, maybeAvatar }) (ReceivedPresence (Presence { presenceType = PresenceProbe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Nothing } })) = do avail <- cheogramAvailable db componentJid sendIQ to from return $ [mkStanzaRec avail] ++ map (mkStanzaRec . (\payload -> (emptyMessage (MessageHeadline)) { messageTo = Just from, messageFrom = Just to, messagePayloads = [payload] }) . avatarMetadata) (justZ maybeAvatar) componentStanza (ComponentContext { db, smsJid = (Just smsJid), componentJid }) (ReceivedPresence (Presence { presenceType = PresenceProbe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Just _ } })) = do routeDiscoOrReply db componentJid from smsJid "CHEOGRAM%query-then-send-presence" Nothing $ telAvailable to from [] componentStanza _ (ReceivedPresence (Presence { presenceType = PresenceProbe, presenceFrom = Just from, presenceTo = Just to@JID { jidNode = Just node } })) | Just multipleTo <- mapM localpartToURI (T.split (==',') $ strNode node) = do return $ [mkStanzaRec $ telAvailable to from []] componentStanza (ComponentContext { maybeAvatar = Just (Avatar hash _ b64) }) (ReceivedIQ (iq@IQ { iqType = IQGet, iqTo = Just to@JID { jidNode = Nothing }, iqFrom = Just from, iqID = Just id, iqPayload = Just p })) | [items] <- isNamed (s"{http://jabber.org/protocol/pubsub}items") =<< elementChildren =<< isNamed (s"{http://jabber.org/protocol/pubsub}pubsub") p, attributeText (s"node") items == Just (s"urn:xmpp:avatar:data"), [item] <- isNamed (s"{http://jabber.org/protocol/pubsub}item") =<< elementChildren items, attributeText (s"id") item == Just hash = return [mkStanzaRec $ iqReply (Just $ XML.Element (s"{http://jabber.org/protocol/pubsub}pubsub") [] [ XML.NodeElement $ XML.Element (s"{http://jabber.org/protocol/pubsub}items") [(s"node", [XML.ContentText $ s"urn:xmpp:avatar:data"])] [ XML.NodeElement $ XML.Element (s"{http://jabber.org/protocol/pubsub}item") [(s"id", [XML.ContentText hash])] [ XML.NodeElement $ mkElement (s"{urn:xmpp:avatar:data}data") b64 ] ] ] ) iq] componentStanza (ComponentContext { registrationJids, processDirectMessageRouteConfig, componentJid }) (ReceivedIQ (IQ { iqType = IQSet, iqTo = Just to, iqFrom = Just from, iqID = Just id, iqPayload = Just p })) | jidNode to == Nothing, [iqEl] <- isNamed (s"{jabber:client}iq") =<< elementChildren =<< isNamed (s"{urn:xmpp:forward:0}forwarded") p, [payload] <- isNamed (s"{http://jabber.org/protocol/commands}command") =<< elementChildren iqEl, Just asFrom <- parseJID =<< attributeText (s"from") iqEl, bareTxt from `elem` map bareTxt registrationJids = do replyIQ <- processDirectMessageRouteConfig $ (emptyIQ IQSet) { iqID = Just id, iqTo = Just to, iqFrom = Just asFrom, iqPayload = Just payload } fmap (fromMaybe []) $ forM replyIQ $ \replyIQ -> do --(\f -> maybe (return []) f replyIQ) $ \replyIQ -> do let fromLocalpart = maybe mempty (\localpart -> localpart++s"@") (fmap strNode . jidNode =<< iqFrom replyIQ) let subscribe = if attributeText (s"action") payload /= Just (s"complete") then [] else [ mkStanzaRec $ (emptyPresence PresenceSubscribe) { presenceTo = Just asFrom, presenceFrom = Just componentJid, presencePayloads = [ Element (s"{jabber:component:accept}status") [] [ NodeContent $ ContentText $ s"Add this contact and then you can SMS by sending messages to +1<phone-number>@" ++ formatJID componentJid ++ s" Jabber IDs." ] ] } ] return $ subscribe ++ [mkStanzaRec $ replyIQ { iqTo = if iqTo replyIQ == Just asFrom then Just from else iqTo replyIQ, iqID = if iqType replyIQ == IQResult then iqID replyIQ else Just $ fromString $ show (formatJID from, formatJID asFrom, iqID replyIQ), iqFrom = parseJID (fromLocalpart ++ formatJID componentJid ++ s"/CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName) }] componentStanza (ComponentContext { processDirectMessageRouteConfig, componentJid }) (ReceivedIQ iq@(IQ { iqTo = Just to })) | fmap strResource (jidResource to) == Just (s"CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName), Just (fwdBy, onBehalf, iqId) <- readZ . T.unpack =<< iqID iq = do replyIQ <- processDirectMessageRouteConfig (iq { iqID = iqId }) fmap (fromMaybe []) $ forM replyIQ $ \replyIQ -> do let fromLocalpart = maybe mempty (\localpart -> localpart++s"@") (fmap strNode . jidNode =<< iqFrom replyIQ) return [mkStanzaRec $ replyIQ { iqTo = if fmap bareTxt (iqTo replyIQ) == Just onBehalf then parseJID fwdBy else iqTo replyIQ, iqID = if iqType replyIQ == IQResult then iqID replyIQ else Just $ fromString $ show (fwdBy, onBehalf, iqID replyIQ), iqFrom = parseJID (fromLocalpart ++ formatJID componentJid ++ s"/CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName) }] componentStanza (ComponentContext { processDirectMessageRouteConfig, componentJid }) (ReceivedIQ iq@(IQ { iqTo = Just to, iqPayload = payload })) | (jidNode to == Nothing && fmap elementName payload == Just (s"{http://jabber.org/protocol/commands}command") && (attributeText (s"node") =<< payload) == Just ConfigureDirectMessageRoute.nodeName) || fmap strResource (jidResource to) == Just (s"CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName) = do replyIQ <- processDirectMessageRouteConfig iq fmap (fromMaybe []) $ forM replyIQ $ \replyIQ -> do let subscribe = if (attributeText (s"status") =<< iqPayload replyIQ) /= Just (s"completed") then [] else [ mkStanzaRec $ (emptyPresence PresenceSubscribe) { presenceTo = iqFrom iq, presenceFrom = Just componentJid, presencePayloads = [ Element (s"{jabber:component:accept}status") [] [ NodeContent $ ContentText $ s"Add this contact and then you can SMS by sending messages to +1<phone-number>@" ++ formatJID componentJid ++ s" Jabber IDs." ] ] } ] let fromLocalpart = maybe mempty (\localpart -> localpart++s"@") (fmap strNode . jidNode =<< iqFrom replyIQ) return $ subscribe ++ [mkStanzaRec $ replyIQ { iqFrom = parseJID (fromLocalpart ++ formatJID componentJid ++ s"/CHEOGRAM%" ++ ConfigureDirectMessageRoute.nodeName) }] componentStanza (ComponentContext { db, componentJid }) (ReceivedIQ iq@(IQ { iqTo = Just to, iqPayload = Just payload, iqFrom = Just from })) | jidNode to == Nothing, elementName payload == s"{http://jabber.org/protocol/commands}command", attributeText (s"node") payload == Just (s"sip-proxy-set"), [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren payload, Just proxy <- getFormField form (s"sip-proxy") = do if T.null proxy then DB.del db (DB.byJid from ["sip-proxy"]) else DB.set db (DB.byJid from ["sip-proxy"]) proxy return [mkStanzaRec $ iqReply Nothing iq] componentStanza (ComponentContext { db, componentJid }) (ReceivedIQ iq@(IQ { iqTo = Just to, iqPayload = Just payload, iqFrom = Just from })) | jidNode to == Nothing, jidNode from == Nothing, elementName payload == s"{http://jabber.org/protocol/commands}command", attributeText (s"node") payload == Just (s"push-register"), [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren payload, Just pushRegisterTo <- XMPP.parseJID =<< getFormField form (s"to") = do DB.set db (DB.byJid pushRegisterTo ["possible-route"]) (XMPP.formatJID from) return [ mkStanzaRec $ iqReply ( Just $ Element (s"{http://jabber.org/protocol/commands}command") [ (s"{http://jabber.org/protocol/commands}node", [ContentText $ s"push-register"]), (s"{http://jabber.org/protocol/commands}sessionid", [ContentText $ s"all-done"]), (s"{http://jabber.org/protocol/commands}status", [ContentText $ s"completed"]) ] [ NodeElement $ Element (fromString "{jabber:x:data}x") [ (fromString "{jabber:x:data}type", [ContentText $ s"result"]) ] [ NodeElement $ Element (fromString "{jabber:x:data}field") [ (fromString "{jabber:x:data}type", [ContentText $ s"jid-single"]), (fromString "{jabber:x:data}var", [ContentText $ s"from"]) ] [ NodeElement $ Element (fromString "{jabber:x:data}value") [] [NodeContent $ ContentText $ escapeJid (bareTxt pushRegisterTo) ++ s"@" ++ formatJID componentJid] ] ] ] ) iq, mkStanzaRec $ mkSMS componentJid pushRegisterTo $ s"To start registration with " ++ XMPP.formatJID from ++ s" reply with: register " ++ XMPP.formatJID from ++ s"\n(If you do not wish to start this registration, simply ignore this message.)" ] componentStanza _ (ReceivedIQ iq@(IQ { iqFrom = Just _, iqTo = Just (JID { jidNode = Nothing }), iqPayload = Just p })) | iqType iq `elem` [IQGet, IQSet], [_] <- isNamed (fromString "{jabber:iq:register}query") p = do return [mkStanzaRec $ iqNotImplemented iq] componentStanza (ComponentContext { db, componentJid, maybeAvatar, sendIQ }) (ReceivedIQ (IQ { iqType = IQGet, iqFrom = Just from, iqTo = Just to, iqID = id, iqPayload = Just p })) | Nothing <- jidNode to, [q] <- isNamed (fromString "{http://jabber.org/protocol/disco#info}query") p = do payload <- cheogramDiscoInfo db componentJid sendIQ from (Just q) return [mkStanzaRec $ (emptyIQ IQResult) { iqTo = Just from, iqFrom = Just to, iqID = id, iqPayload = Just payload }] | Nothing <- jidNode to, [s"http://jabber.org/protocol/commands"] == mapMaybe (attributeText (s"node")) (isNamed (fromString "{http://jabber.org/protocol/disco#items}query") p) = do routeQueryOrReply db componentJid from componentJid ("CHEOGRAM%query-then-send-command-list%" ++ extra) queryCommandList (commandList componentJid id to from []) | Nothing <- jidNode to, [_] <- isNamed (s"{vcard-temp}vCard") p = return [mkStanzaRec $ (emptyIQ IQResult) { iqTo = Just from, iqFrom = Just to, iqID = id, iqPayload = Just $ Element (s"{vcard-temp}vCard") [] $ [ NodeElement $ Element (s"{vcard-temp}URL") [] [NodeContent $ ContentText $ s"https://cheogram.com"], NodeElement $ Element (s"{vcard-temp}DESC") [] [NodeContent $ ContentText $ s"Cheogram provides stable JIDs for PSTN identifiers, with routing through many possible backends.\n\n© Stephen Paul Weber, licensed under AGPLv3+.\n\nSource code for this gateway is available from the listed homepage.\n\nPart of the Soprani.ca project."] ] ++ map (\(Avatar _ _ b64) -> NodeElement $ Element (s"{vcard-temp}PHOTO") [] [ NodeElement $ mkElement (s"{vcard-temp}TYPE") (s"image/png"), NodeElement $ mkElement (s"{vcard-temp}BINVAL") b64 ] ) (justZ maybeAvatar) }] where extra = T.unpack $ escapeJid $ T.pack $ show (id, fromMaybe mempty resourceFrom) resourceFrom = strResource <$> jidResource from componentStanza (ComponentContext { db, sendIQ, smsJid = (Just smsJid), componentJid }) (ReceivedIQ (IQ { iqType = IQGet, iqFrom = Just from, iqTo = Just to, iqID = Just id, iqPayload = Just p })) | Just _ <- jidNode to, [q] <- isNamed (fromString "{http://jabber.org/protocol/disco#info}query") p = do maybeDiscoResult <- routeDiscoStateful db componentJid sendIQ from (jidNode smsJid) (nodeAttribute q) telFeatures <- getTelFeatures db componentJid sendIQ from case maybeDiscoResult of Just (IQ { iqPayload = Just discoResult }) -> return [ mkStanzaRec $ telDiscoInfo q id to from $ (telFeatures ++) $ mapMaybe (attributeText (fromString "var")) $ isNamed (fromString "{http://jabber.org/protocol/disco#info}feature") =<< elementChildren discoResult ] Nothing -> return [mkStanzaRec $ telDiscoInfo q id to from telFeatures] | Just tel <- strNode <$> jidNode to, [_] <- isNamed (s"{vcard-temp}vCard") p = do --owners <- (fromMaybe [] . (readZ =<<)) <$> -- maybe (return Nothing) (TC.runTCM . TC.get db) (tcKey smsJid "owners") return [mkStanzaRec $ (emptyIQ IQResult) { iqTo = Just from, iqFrom = Just to, iqID = Just id, iqPayload = Just $ Element (s"{vcard-temp}vCard") [] ( [ NodeElement $ Element (s"{vcard-temp}TEL") [] [ NodeElement $ Element (s"{vcard-temp}NUMBER") [] [NodeContent $ ContentText tel] ] ] --map (\owner -> NodeElement (Element (s"{vcard-temp}JABBERID") [] [NodeContent $ ContentText owner])) owners ) }] where extra = T.unpack $ escapeJid $ T.pack $ show (id, fromMaybe mempty resourceFrom) resourceFrom = strResource <$> jidResource from componentStanza (ComponentContext { componentJid }) (ReceivedIQ (iq@IQ { iqType = IQSet, iqFrom = Just from, iqTo = Just (to@JID {jidNode = Nothing}), iqID = id, iqPayload = Just p })) | [query] <- isNamed (fromString "{jabber:iq:gateway}query") p, [prompt] <- isNamed (fromString "{jabber:iq:gateway}prompt") =<< elementChildren query = do case telToJid (T.filter isDigit $ mconcat $ elementText prompt) (formatJID componentJid) of Just jid -> return [mkStanzaRec $ (emptyIQ IQResult) { iqTo = Just from, iqFrom = Just to, iqID = id, iqPayload = Just $ Element (fromString "{jabber:iq:gateway}query") [] [NodeElement $ Element (fromString "{jabber:iq:gateway}jid") [ ] [NodeContent $ ContentText $ formatJID jid]] }] Nothing -> return [mkStanzaRec $ iq { iqTo = Just from, iqFrom = Just to, iqType = IQError, iqPayload = Just $ Element (fromString "{jabber:component:accept}error") [(fromString "{jabber:component:accept}type", [ContentText $ fromString "modify"])] [ NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}not-acceptable") [] [], NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}text") [(fromString "xml:lang", [ContentText $ fromString "en"])] [NodeContent $ ContentText $ fromString "Only US/Canada telephone numbers accepted"] ] }] componentStanza _ (ReceivedIQ (IQ { iqType = IQGet, iqFrom = Just from, iqTo = Just (to@JID {jidNode = Nothing}), iqID = id, iqPayload = Just p })) | [_] <- isNamed (fromString "{jabber:iq:gateway}query") p = do return [mkStanzaRec $ (emptyIQ IQResult) { iqTo = Just from, iqFrom = Just to, iqID = id, iqPayload = Just $ Element (fromString "{jabber:iq:gateway}query") [] [ NodeElement $ Element (fromString "{jabber:iq:gateway}desc") [ ] [NodeContent $ ContentText $ fromString "Please enter your contact's phone number"], NodeElement $ Element (fromString "{jabber:iq:gateway}prompt") [ ] [NodeContent $ ContentText $ fromString "Phone Number"] ] }] componentStanza (ComponentContext { db }) (ReceivedIQ (iq@IQ { iqType = IQError, iqFrom = Just from, iqTo = Just to })) | (strNode <$> jidNode to) == Just (fromString "create"), Just resource <- strResource <$> jidResource to = do log "create@ ERROR" (from, to, iq) case T.splitOn (fromString "|") resource of (cheoJidT:_) | Just cheoJid <- parseJID cheoJidT -> do mnick <- DB.get db (DB.byNode cheoJid ["nick"]) let nick = fromMaybe (maybe mempty strNode (jidNode cheoJid)) mnick let Just room = parseJID $ bareTxt from <> fromString "/" <> nick (++) <$> leaveRoom db cheoJid "Joined a different room." <*> joinRoom db cheoJid room _ -> return [] -- Invalid packet, ignore componentStanza (ComponentContext { componentJid }) (ReceivedIQ (IQ { iqType = IQResult, iqFrom = Just from, iqTo = Just to })) | (strNode <$> jidNode to) == Just (fromString "create"), Just resource <- strResource <$> jidResource to = do case T.splitOn (fromString "|") resource of (cheoJidT:name:[]) | Just cheoJid <- parseJID cheoJidT, Just tel <- strNode <$> jidNode cheoJid -> createRoom componentJid [strDomain $ jidDomain from] cheoJid (name <> fromString "_" <> tel) (cheoJidT:name:servers) | Just cheoJid <- parseJID cheoJidT -> createRoom componentJid servers cheoJid name _ -> return [] -- Invalid packet, ignore componentStanza (ComponentContext { toRejoinManager }) (ReceivedIQ (IQ { iqType = IQResult, iqID = Just id, iqFrom = Just from })) | fromString "CHEOGRAMPING%" `T.isPrefixOf` id = do atomically $ writeTChan toRejoinManager (PingReply from) return [] componentStanza (ComponentContext { toRejoinManager }) (ReceivedIQ (IQ { iqType = IQError, iqID = Just id, iqFrom = Just from })) | fromString "CHEOGRAMPING%" `T.isPrefixOf` id = do atomically $ writeTChan toRejoinManager (PingError from) return [] componentStanza _ (ReceivedIQ (IQ { iqType = IQResult, iqFrom = Just from, iqTo = Just to, iqID = Just id, iqPayload = Just p })) | [query] <- isNamed (fromString "{http://jabber.org/protocol/muc#owner}query") p, [form] <- isNamed (fromString "{jabber:x:data}x") =<< elementChildren query = do uuid <- fromMaybe "UUIDFAIL" <$> (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID let fullid = if fromString "CHEOGRAMCREATE%" `T.isPrefixOf` id then "CHEOGRAMCREATE%" <> uuid else uuid return [mkStanzaRec $ (emptyIQ IQSet) { iqTo = Just from, iqFrom = Just to, iqID = Just $ fromString fullid, iqPayload = Just $ Element (fromString "{http://jabber.org/protocol/muc#owner}query") [] [ NodeElement $ fillFormField (fromString "muc#roomconfig_publicroom") (fromString "0") $ fillFormField (fromString "muc#roomconfig_persistentroom") (fromString "1") $ fillFormField (fromString "muc#roomconfig_allowinvites") (fromString "1") $ fillFormField (fromString "muc#roomconfig_membersonly") (fromString "1") form { elementAttributes = [(fromString "{jabber:x:data}type", [ContentText $ fromString "submit"])] } ] }] componentStanza (ComponentContext { smsJid = (Just smsJid), componentJid }) (ReceivedIQ (IQ { iqType = IQResult, iqFrom = Just from, iqTo = Just to, iqID = Just id })) | fromString "CHEOGRAMCREATE%" `T.isPrefixOf` id = do fmap (((mkStanzaRec $ mkSMS componentJid smsJid (mconcat [fromString "* You have created ", bareTxt from])):) . concat . toList) $ forM (parseJID $ bareTxt to <> fromString "/create") $ queryDisco from componentStanza (ComponentContext { componentJid }) (ReceivedIQ (IQ { iqType = typ, iqTo = Just to@(JID { jidNode = Just toNode }), iqPayload = Just p })) | typ `elem` [IQResult, IQError], Just idAndResource <- T.stripPrefix (s"CHEOGRAM%query-then-send-command-list%") . strResource =<< jidResource to, Just (iqId, resource) <- readZ $ T.unpack $ unescapeJid idAndResource, Just routeTo <- parseJID (unescapeJid (strNode toNode) ++ if T.null resource then mempty else s"/" ++ resource) = if typ == IQError then do return [mkStanzaRec $ commandList componentJid iqId componentJid routeTo []] else do let items = isNamed (s"{http://jabber.org/protocol/disco#items}item") =<< elementChildren p return [mkStanzaRec $ commandList componentJid iqId componentJid routeTo items] componentStanza (ComponentContext { db, componentJid, sendIQ }) (ReceivedIQ (IQ { iqType = IQError, iqTo = Just to@(JID { jidNode = Just toNode }), iqFrom = Just from })) | fmap strResource (jidResource to) == Just (s"CHEOGRAM%query-then-send-presence"), Just routeTo <- parseJID (unescapeJid (strNode toNode)), Just fromNode <- jidNode from, Just routeFrom <- parseJID (strNode fromNode ++ s"@" ++ formatJID componentJid) = do telFeatures <- getTelFeatures db componentJid sendIQ routeTo return [ mkStanzaRec $ telAvailable routeFrom routeTo telFeatures ] componentStanza (ComponentContext { db, componentJid, sendIQ }) (ReceivedIQ (IQ { iqType = IQResult, iqTo = Just to@(JID { jidNode = Just toNode }), iqFrom = Just from, iqPayload = Just p })) | Just idAndResource <- T.stripPrefix (s"CHEOGRAM%query-then-send-ack%") . strResource =<< jidResource to, Just (messageId, resource) <- readZ $ T.unpack $ unescapeJid idAndResource, [query] <- isNamed (fromString "{http://jabber.org/protocol/disco#info}query") p, Just routeTo <- parseJID (unescapeJid (strNode toNode) ++ if T.null resource then mempty else s"/" ++ resource), Just fromNode <- jidNode from, Just routeFrom <- parseJID (strNode fromNode ++ s"@" ++ formatJID componentJid) = let features = mapMaybe (attributeText (fromString "var")) $ isNamed (fromString "{http://jabber.org/protocol/disco#info}feature") =<< elementChildren query in if (s"urn:xmpp:receipts") `elem` features then do return [] else do return [mkStanzaRec $ deliveryReceipt messageId routeFrom routeTo] | fmap strResource (jidResource to) == Just (s"CHEOGRAM%query-then-send-presence"), [query] <- isNamed (fromString "{http://jabber.org/protocol/disco#info}query") p, Just routeTo <- parseJID (unescapeJid (strNode toNode)), Just fromNode <- jidNode from, Just routeFrom <- parseJID (strNode fromNode ++ s"@" ++ formatJID componentJid) = do telFeatures <- getTelFeatures db componentJid sendIQ routeTo return [ mkStanzaRec $ telAvailable routeFrom routeTo $ (telFeatures ++) $ mapMaybe (attributeText (fromString "var")) $ isNamed (fromString "{http://jabber.org/protocol/disco#info}feature") =<< elementChildren query ] | [query] <- isNamed (fromString "{http://jabber.org/protocol/disco#info}query") p = do let vars = mapMaybe (attributeText (fromString "var")) $ isNamed (fromString "{http://jabber.org/protocol/disco#info}feature") =<< elementChildren query if s"muc_membersonly" `elem` vars then DB.setEnum db (DB.byJid from ["muc_membersonly"]) True else DB.del db (DB.byJid from ["muc_membersonly"]) return [] componentStanza _ (ReceivedIQ (iq@IQ { iqType = IQGet, iqFrom = Just from, iqTo = Just to, iqPayload = Just p })) | not $ null $ isNamed (fromString "{urn:xmpp:ping}ping") p = do return [mkStanzaRec $ iq { iqTo = Just from, iqFrom = Just to, iqType = IQResult, iqPayload = Nothing }] componentStanza (ComponentContext { db, smsJid = maybeSmsJid, componentJid }) (ReceivedIQ (iq@IQ { iqType = typ, iqFrom = Just from })) | fmap strResource (jidResource =<< iqTo iq) /= Just (s"capsQuery") = do let resourceSuffix = maybe mempty (s"/"++) $ fmap strResource (jidResource from) maybeRoute <- DB.get db (DB.byJid from ["direct-message-route"]) case (maybeRoute, parseJID $ escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid ++ resourceSuffix) of (Just route, Just routeFrom) -> do return [mkStanzaRec $ iq { iqFrom = Just routeFrom, iqTo = parseJID $ (maybe mempty (++s"@") $ strNode <$> (jidNode =<< maybeSmsJid)) ++ route }] _ | typ `elem` [IQGet, IQSet] -> do return [mkStanzaRec $ iqNotImplemented iq] _ | typ == IQError, Just smsJid <- maybeSmsJid -> do log "IQ ERROR" iq return [mkStanzaRec $ mkSMS componentJid smsJid (fromString "Error while querying or configuring " <> formatJID from)] _ -> log "IGNORE BOGUS REPLY (no route)" iq >> return [] componentStanza _ s = do log "UNKNOWN STANZA" s return [] participantJid payloads = listToMaybe $ mapMaybe (parseJID <=< attributeText (fromString "jid")) $ isNamed (fromString "{http://jabber.org/protocol/muc#user}item") =<< elementChildren =<< isNamed (fromString "{http://jabber.org/protocol/muc#user}x") =<< payloads cacheHTTP :: (Unexceptional m) => FilePath -> Text -> m (Either IOError FilePath) cacheHTTP jingleStore url = UIO.fromIO' (userError . show) $ HTTP.get (encodeUtf8 url) $ \response body -> UIO.runEitherIO $ if HTTP.getStatusCode response == 200 then fmap (fmap (\(fp,_,_,_) -> fp)) $ Jingle.storeChunks Nothing jingleStore (reverse $ take 240 $ reverse $ escapeURIString isAlphaNum (textToString url)) (hush <$> UIO.fromIO (fromMaybe mempty <$> Streams.read body)) else return $ Left $ userError "Response was not 200 OK" cacheOneOOB :: (Unexceptional m) => Magic -> ([StatsD.Stat] -> m ()) -> FilePath -> Text -> XML.Element -> m (Maybe (Text, Text), XML.Element) cacheOneOOB magic pushStatsd jingleStore jingleStoreURL oob | [url] <- (mconcat . XML.elementText) <$> urls = do cacheResult <- cacheHTTP jingleStore url case cacheResult of Left err -> do pushStatsd [StatsD.stat ["cache", "oob", "failure"] 1 "c" Nothing] log "cacheOneOOB" err return (Nothing, oob) Right path -> do pushStatsd [StatsD.stat ["cache", "oob", "success"] 1 "c" Nothing] mimeType <- fromIO_ $ magicFile magic path let extSuffix = maybe mempty (s"." ++) $ SMap.lookup mimeType mimeToExtMap let url' = jingleStoreURL ++ (T.takeWhileEnd (/='/') $ fromString path) ++ extSuffix return ( Just (url, url'), oob { XML.elementNodes = map XML.NodeElement (mkElement urlName url' : rest) } ) | otherwise = do log "cacheOneOOB MALFORMED" oob return (Nothing, oob) where urlName = s"{jabber:x:oob}url" (urls, rest) = partition (\el -> XML.elementName el == urlName) (elementChildren oob) cacheOOB :: (Unexceptional m) => Magic -> ([StatsD.Stat] -> m ()) -> FilePath -> Text -> XMPP.Message -> m XMPP.Message cacheOOB magic pushStatsd jingleStore jingleStoreURL m@(XMPP.Message { XMPP.messagePayloads = payloads }) = do (replacements, oobs') <- unzip <$> mapM (cacheOneOOB magic pushStatsd jingleStore jingleStoreURL) oobs let body' = (mkElement bodyName .: foldl (\body (a, b) -> T.replace a b body)) <$> (map (mconcat . XML.elementText) body) <*> pure (catMaybes replacements) return $ m { XMPP.messagePayloads = noOobsNoBody ++ oobs' ++ body' } where oobName = s"{jabber:x:oob}x" bodyName = s"{jabber:component:accept}body" (body, noOobsNoBody) = partition (\el -> XML.elementName el == bodyName) noOobs (oobs, noOobs) = partition (\el -> XML.elementName el == oobName) payloads component db redis pushStatsd backendHost did maybeAvatar cacheOOB sendIQ iqReceiver adhocBotMessage toRoomPresences toRejoinManager toJoinPartDebouncer toComponent toStanzaProcessor processDirectMessageRouteConfig jingleHandler componentJid registrationJids conferenceServers = do sendThread <- forkXMPP $ forever $ flip catchError (log "component EXCEPTION") $ do stanza <- liftIO $ atomically $ readTChan toComponent let tags = maybe "" (";domain=" ++) (textToString . strDomain . jidDomain <$> stanzaTo stanza) pushStatsd [StatsD.stat ["stanzas", "out" ++ tags] 1 "c" Nothing] putStanza =<< (liftIO . ensureId) stanza recvThread <- forkXMPP $ forever $ flip catchError (log "component read EXCEPTION") $ (atomicUIO . writeTChan toStanzaProcessor) =<< getStanza flip catchError (\e -> liftIO (log "component part 2 EXCEPTION" e >> killThread sendThread >> killThread recvThread)) $ forever $ do stanza <- atomicUIO $ readTChan toStanzaProcessor let tags = maybe "" (";domain=" ++) (textToString . strDomain . jidDomain <$> stanzaFrom (receivedStanza stanza)) pushStatsd [StatsD.stat ["stanzas", "in" ++ tags] 1 "c" Nothing] liftIO $ forkIO $ case stanza of (ReceivedPresence p@(Presence { presenceType = PresenceAvailable, presenceFrom = Just from, presenceTo = Just to })) | Just returnFrom <- parseJID (bareTxt to ++ s"/capsQuery") -> let cheogramBareJid = escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid caps = child (s"{http://jabber.org/protocol/caps}c") p show = maybe mempty mconcat $ elementText <$> child (s"{jabber:component:accept}show") p priority = fromMaybe 0 $ (readZ . textToString . mconcat =<< elementText <$> child (s"{jabber:component:accept}priority") p) pavailableness = availableness show priority in do -- Caps? case (XML.attributeText (s"ver") =<< caps, XML.attributeText (s"node") =<< caps) of -- Yes: write ver to <barejid>/resource and <cheoagramjid>/resource (Just ver, Just node) -> do let bver = Base64.decodeLenient $ encodeUtf8 ver let val = LZ.toStrict $ Builder.toLazyByteString (Builder.word16BE pavailableness ++ Builder.byteString bver) Right exists <- Redis.runRedis redis $ do Redis.hset (encodeUtf8 $ bareTxt from) (encodeUtf8 $ maybe mempty strResource $ jidResource from) val Redis.hset (encodeUtf8 $ cheogramBareJid) (encodeUtf8 $ maybe mempty strResource $ jidResource from) val -- ver in redis? Redis.exists bver -- Yes: done -- No: send disco query, with node when (not exists) $ sendToComponent . mkStanzaRec =<< queryDiscoWithNode (Just $ node ++ s"#" ++ ver) from returnFrom -- No: write only availableness to redis. send disco query, no node _ -> do let val = LZ.toStrict $ Builder.toLazyByteString (Builder.word16BE pavailableness) void $ Redis.runRedis redis $ do Redis.hset (encodeUtf8 $ bareTxt from) (encodeUtf8 $ maybe mempty strResource $ jidResource from) val Redis.hset (encodeUtf8 $ cheogramBareJid) (encodeUtf8 $ maybe mempty strResource $ jidResource from) val mapM_ sendToComponent =<< queryDisco from returnFrom (ReceivedPresence (Presence { presenceType = PresenceUnavailable, presenceFrom = Just from })) -> do let cheogramBareJid = escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid -- Delete <barejid>/resource and <cheogramjid>/resource void $ Redis.runRedis redis $ do Redis.hdel (encodeUtf8 $ bareTxt from) [encodeUtf8 $ maybe mempty strResource $ jidResource from] Redis.hdel (encodeUtf8 $ cheogramBareJid) [encodeUtf8 $ maybe mempty strResource $ jidResource from] (ReceivedIQ iq@(IQ { iqType = IQResult, iqFrom = Just from })) | Just query <- child (s"{http://jabber.org/protocol/disco#info}query") iq -> do let cheogramBareJid = escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid let bver = discoToCapsHash query -- Write <ver> with the list of features void $ Redis.runRedis redis $ do Redis.sadd bver (encodeUtf8 <$> discoVars query) -- Write ver to <barejid>/resource and <cheogramjid>/resource Right ravailableness <- (fmap . fmap) (maybe (BS.pack [0,0]) (BS.take 2)) $ Redis.hget (encodeUtf8 $ bareTxt from) (encodeUtf8 $ maybe mempty strResource $ jidResource from) let val = ravailableness ++ bver Redis.hset (encodeUtf8 $ bareTxt from) (encodeUtf8 $ maybe mempty strResource $ jidResource from) val Redis.hset (encodeUtf8 $ cheogramBareJid) (encodeUtf8 $ maybe mempty strResource $ jidResource from) val _ -> return () flip forkFinallyXMPP (either (log "RECEIVE ONE" . show) return) $ case (stanzaFrom $ receivedStanza stanza, stanzaTo $ receivedStanza stanza, mapToBackend backendHost =<< stanzaTo (receivedStanza stanza), fmap strNode . jidNode =<< stanzaTo (receivedStanza stanza), stanza) of (_, Just to, _, _, ReceivedIQ iq@(IQ { iqType = typ })) | typ `elem` [IQResult, IQError], (strResource <$> jidResource to) `elem` map Just [s"adhocbot", s"IQMANAGER"] -> iqReceiver iq (Just from, Just to, _, _, ReceivedMessage (Message { messageType = MessageError })) | strDomain (jidDomain from) == backendHost, to == componentJid -> log "backend error" stanza (Just from, Just to, _, _, ReceivedMessage m) | strDomain (jidDomain from) == backendHost, to == componentJid, Just txt <- getBody "jabber:component:accept" m, Just cheoJid <- mapToComponent from, fmap strNode (jidNode from) /= Just did -> liftIO (mapM_ sendToComponent =<< processSMS db componentJid conferenceServers from cheoJid txt) (Just from, Just to, Nothing, Just localpart, ReceivedMessage m) | Just txt <- getBody "jabber:component:accept" m, Just owner <- parseJID (unescapeJid localpart), (T.length txt == 144 || T.length txt == 145) && (s"CHEOGRAM") `T.isPrefixOf` txt -> liftIO $ do -- the length of our token messages log "POSSIBLE TOKEN" (from, to, txt) maybeRoute <- DB.get db (DB.byJid owner ["direct-message-route"]) when (Just (strDomain $ jidDomain from) == maybeRoute || bareTxt from == bareTxt owner) $ do maybeToken <- DB.get db (DB.byJid owner ["addtoken"]) case (fmap (first parseJID) (readZ . textToString =<< maybeToken)) of (Just (Just cheoJid, token)) | (s"CHEOGRAM"++token) == txt -> do log "SET OWNER" (cheoJid, owner) DB.set db (DB.byJid owner ["cheoJid"]) (formatJID cheoJid) DB.sadd db (DB.byNode cheoJid ["owners"]) [bareTxt owner] _ -> log "NO TOKEN FOUND, or mismatch" maybeToken (Just from, Just to, Nothing, Just localpart, _) | Just multipleTo <- mapM localpartToURI (T.split (==',') localpart), ReceivedMessage m <- stanza, Just backendJid <- parseJID backendHost -> liftIO $ let m' = m { messagePayloads = messagePayloads m ++ [ Element (s"{http://jabber.org/protocol/address}addresses") [] $ map (\oneto -> NodeElement $ Element (s"{http://jabber.org/protocol/address}address") [ (s"{http://jabber.org/protocol/address}type", [ContentText $ s"to"]), (s"{http://jabber.org/protocol/address}uri", [ContentText oneto]) ] [] ) multipleTo ] } in -- TODO: should check if backend supports XEP-0033 -- TODO: fallback for no-backend case should work mapM_ sendToComponent =<< componentMessage db componentJid m' Nothing from backendJid (getBody "jabber:component:accept" m') | (s"sip.cheogram.com") == strDomain (jidDomain from) -> liftIO $ do let (toResource, fromResource) | Just toResource <- T.stripPrefix (s"CHEOGRAM%outbound-sip%") =<< (strResource <$> jidResource to) = (toResource, s"tel") | otherwise = (fromMaybe mempty (strResource <$> jidResource to), s"sip:" ++ escapeJid (formatJID from)) case (mapLocalpartToBackend (formatJID componentJid) =<< sanitizeSipLocalpart (maybe mempty strNode $ jidNode from), parseJID (unescapeJid localpart ++ s"/" ++ toResource)) of (Just componentFrom, Just routeTo) -> liftIO $ do Just componentFromSip <- return $ parseJID (formatJID componentFrom ++ s"/" ++ fromResource) sendToComponent $ mkStanzaRec $ receivedStanza $ receivedStanzaFromTo componentFromSip routeTo stanza _ -> sendToComponent $ stanzaError stanza $ Element (fromString "{jabber:component:accept}error") [(fromString "{jabber:component:accept}type", [ContentText $ fromString "cancel"])] [NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}item-not-found") [] []] (Just from, Just to, Nothing, Just localpart, _) | Nothing <- mapM localpartToURI (T.split (==',') $ fromMaybe mempty $ fmap strNode $ jidNode to), Just routeTo <- parseJID (unescapeJid localpart ++ maybe mempty (s"/"++) (strResource <$> jidResource to)), fmap (((s"CHEOGRAM%") `T.isPrefixOf`) . strResource) (jidResource to) /= Just True -> liftIO $ do maybeRoute <- DB.get db (DB.byJid routeTo ["direct-message-route"]) case (maybeRoute, mapToComponent from) of (Just route, Just componentFrom) | route == strDomain (jidDomain from) -> (sendToComponent . receivedStanza) =<< mapReceivedMessageM (UIO.lift . cacheOOB) (receivedStanzaFromTo componentFrom routeTo stanza) (Just route, _) -- Alphanumeric senders | route == strDomain (jidDomain from), Just localpart <- strNode <$> jidNode from, Nothing <- T.find (\c -> not ((isAlphaNum c || c == ' ') && isAscii c)) localpart -> let localpart' = T.concatMap (\c -> tshow (ord c - 30)) localpart ++ s";phone-context=alphanumeric.phone-context.soprani.ca" Just componentFrom = parseJID (localpart' ++ s"@" ++ formatJID componentJid) in (sendToComponent . receivedStanza) =<< mapReceivedMessageM (fmap (addNickname localpart) . UIO.lift . cacheOOB) (receivedStanzaFromTo componentFrom routeTo stanza) _ | Just jid <- (`telToJid` formatJID componentJid) =<< strNode <$> jidNode to -> do sendToComponent $ stanzaError stanza $ Element (fromString "{jabber:component:accept}error") [(fromString "{jabber:component:accept}type", [ContentText $ fromString "cancel"])] [ NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}gone") [] [NodeContent $ ContentText $ formatJID jid], NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}text") [(fromString "xml:lang", [ContentText $ fromString "en"])] [NodeContent $ ContentText $ fromString "JID must include country code: " <> formatJID jid] ] | otherwise -> sendToComponent $ stanzaError stanza $ Element (fromString "{jabber:component:accept}error") [(fromString "{jabber:component:accept}type", [ContentText $ fromString "cancel"])] [NodeElement $ Element (fromString "{urn:ietf:params:xml:ns:xmpp-stanzas}item-not-found") [] []] (mfrom, to, backendTo, _, _) | Just sipJid <- parseJID =<< T.stripPrefix (s"sip:") =<< (unescapeJid . strResource <$> (jidResource =<< to)), Just from <- mfrom, resourceSuffix <- maybe mempty (s"/"++) (fmap strResource (jidResource =<< mfrom)), Just useFrom <- parseJID $ (escapeJid $ bareTxt from) ++ s"@" ++ formatJID componentJid ++ resourceSuffix -> do liftIO $ sendToComponent $ mkStanzaRec $ receivedStanza $ receivedStanzaFromTo useFrom sipJid stanza | ReceivedIQ (iq@IQ { iqType = IQSet, iqPayload = Just p }) <- stanza, (nameNamespace $ elementName p) `elem` [Just (s"urn:xmpp:jingle:1"), Just (s"http://jabber.org/protocol/ibb")] -> do jingleHandler iq | otherwise -> liftIO $ mapM_ sendToComponent =<< componentStanza (ComponentContext db backendTo registrationJids adhocBotMessage cacheOOB toRoomPresences toRejoinManager toJoinPartDebouncer processDirectMessageRouteConfig componentJid sendIQ maybeAvatar) stanza where mapToComponent = mapToBackend (formatJID componentJid) sendToComponent = atomically . writeTChan toComponent stanzaError (ReceivedMessage m) errorPayload = mkStanzaRec $ m { messageFrom = messageTo m, messageTo = messageFrom m, messageType = MessageError, messagePayloads = messagePayloads m ++ [errorPayload] } stanzaError (ReceivedPresence p) errorPayload = mkStanzaRec $ p { presenceFrom = presenceTo p, presenceTo = presenceFrom p, presenceType = PresenceError, presencePayloads = presencePayloads p ++ [errorPayload] } stanzaError (ReceivedIQ iq) errorPayload = mkStanzaRec $ iq { iqFrom = iqTo iq, iqTo = iqFrom iq, iqType = IQError, iqPayload = Just errorPayload } receivedStanzaFromTo from to (ReceivedMessage m) = ReceivedMessage $ m { messageFrom = Just from, messageTo = Just to } receivedStanzaFromTo from to (ReceivedPresence p) = ReceivedPresence $ p { presenceFrom = Just from, presenceTo = Just to } receivedStanzaFromTo from to (ReceivedIQ iq) = ReceivedIQ $ rewriteJingleInitiatorResponder $ iq { iqFrom = Just from, iqTo = Just to } receivedStanza (ReceivedMessage m) = mkStanzaRec m receivedStanza (ReceivedPresence p) = mkStanzaRec p receivedStanza (ReceivedIQ iq) = mkStanzaRec iq -- Jingle session-initiate and session-accept iqs contain the sending JID -- again for some reason, so make sure we keep those the same rewriteJingleInitiatorResponder iq | Just jingle <- child (s"{urn:xmpp:jingle:1}jingle") iq = iq { XMPP.iqPayload = Just $ jingle { XML.elementAttributes = map initiatorResponder (XML.elementAttributes jingle) } } | otherwise = iq where initiatorResponder (name, content) | name == s"initiator" = (name, [XML.ContentText $ maybe (s"") XMPP.formatJID (XMPP.iqFrom iq)]) | name == s"responder" = (name, [XML.ContentText $ maybe (s"") XMPP.formatJID (XMPP.iqFrom iq)]) | otherwise = (name, content) groupTextPorcelein :: Text -> Message -> Maybe Message groupTextPorcelein host m@(Message { messagePayloads = p, messageFrom = Just from }) | [addresses] <- isNamed (s"{http://jabber.org/protocol/address}addresses") =<< p, [body] <- isNamed (s"{jabber:component:accept}body") =<< p, (jids, uris) <- partition (maybe False (const True) . headZ . hasAttribute (s"jid")) (hasAttributeText (s"type") (`elem` [s"to", s"cc"]) =<< isNamed (s"{http://jabber.org/protocol/address}address") =<< elementChildren addresses), [Just to] <- (proxiedJidToReal <=< parseJID <=< attributeText (s"jid")) <$> jids, Just fromTel <- strNode <$> jidNode from, Just tels <- fmap (textToString fromTel:) $ mapM (fmap uriPath . parseURI . textToString <=< attributeText (s"uri")) uris = Just $ m { messageTo = Just to, messageFrom = parseJID (fromString (intercalate "," (sort tels)) ++ (s"@") ++ host), messagePayloads = body { elementNodes = (NodeContent $ ContentText $ s"<xmpp:") : (NodeContent $ ContentText fromTel) : (NodeContent $ ContentText $ s"@") : (NodeContent $ ContentText host) : (NodeContent $ ContentText $ s"> ") : elementNodes body } : filter (`notElem` [addresses, body]) p } groupTextPorcelein _ _ = Nothing proxiedJidToReal :: JID -> Maybe JID proxiedJidToReal jid = parseJID =<< fmap (maybe id (\r -> (++ (s"/" ++ r))) resource) bare where resource = strResource <$> jidResource jid bare = unescapeJid . strNode <$> jidNode jid mapToBackend backendHost (JID { jidNode = Just node }) = mapLocalpartToBackend backendHost (strNode node) mapToBackend backendHost (JID { jidNode = Nothing }) = parseJID backendHost mapLocalpartToBackend backendHost localpart | Just ('+', tel) <- T.uncons localpart, T.all isDigit tel = result | Just _ <- parsePhoneContext localpart = result | otherwise = Nothing where result = parseJID (localpart ++ s"@" ++ backendHost) localpartToURI localpart | Just ('+', tel) <- T.uncons localpart, T.all isDigit tel = result | Just _ <- parsePhoneContext localpart = result | otherwise = Nothing where result = Just (s"sms:" ++ localpart) isE164 fullTel | Just ('+',e164) <- T.uncons fullTel = T.all isDigit e164 | otherwise = False normalizeTel fullTel | isE164 fullTel = Just fullTel | T.length tel == 10 = Just (s"+1" ++ tel) | T.length tel == 11, s"1" `T.isPrefixOf` tel = Just (T.cons '+' tel) | T.length tel == 5 || T.length tel == 6 = Just (tel ++ s";phone-context=ca-us.phone-context.soprani.ca") | otherwise = Nothing where tel = T.filter isDigit fullTel telToJid tel host = parseJID =<< (<> fromString "@" <> host) <$> normalizeTel tel parseJIDrequireNode txt | Just _ <- jidNode =<< jid = jid | otherwise = Nothing where jid = parseJID txt stripCIPrefix prefix str | CI.mk prefix' == prefix = Just rest | otherwise = Nothing where (prefix', rest) = T.splitAt (T.length $ CI.original prefix) str data Command = Help | Create Text | Join JID | JoinInvited | JoinInvitedWrong | Debounce Int | Send Text | Who | List | Leave | InviteCmd JID | SetNick Text | Whisper JID Text | AddJid JID | DelJid JID | Jids deriving (Show, Eq) parseCommand txt room nick componentJid | Just jid <- stripCIPrefix (fromString "/invite ") txt = InviteCmd <$> ( (maybeStripProxy <$> parseJIDrequireNode jid) <|> telToJid jid (formatJID componentJid) ) | Just room <- stripCIPrefix (fromString "/join ") txt = Join <$> (parseJID (room <> fromString "/" <> nick) <|> parseJID room) | Just addjid <- stripCIPrefix (fromString "/addjid ") txt = AddJid <$> parseJID addjid | Just deljid <- stripCIPrefix (fromString "/deljid ") txt = DelJid <$> parseJID deljid | citxt == fromString "/jids" = Just Jids | Just t <- stripCIPrefix (fromString "/create ") txt = Just $ Create t | Just nick <- stripCIPrefix (fromString "/nick ") txt = Just $ SetNick nick | Just input <- stripCIPrefix (fromString "/msg ") txt = let (to, msg) = T.breakOn (fromString " ") input in Whisper <$> ( (maybeStripProxy <$> parseJIDrequireNode to) <|> telToJid to (formatJID componentJid) <|> (parseJID =<< fmap (\r -> bareTxt r <> fromString "/" <> to) room) ) <*> pure msg | Just stime <- stripCIPrefix (fromString "/debounce ") txt, Just time <- readMay stime = Just $ Debounce time | citxt == fromString "/join" = Just JoinInvited | citxt == fromString "join" = Just JoinInvitedWrong | citxt == fromString "/leave" = Just Leave | citxt == fromString "/part" = Just Leave | citxt == fromString "/who" = Just Who | citxt == fromString "/list" = Just List | citxt == fromString "/help" = Just Help | otherwise = Just $ Send txt where maybeStripProxy jid | jidDomain jid == jidDomain (componentJid) = fromMaybe jid $ proxiedJidToReal jid | otherwise = jid citxt = CI.mk txt getMessage (ReceivedMessage m) = Just m getMessage _ = Nothing sendToRoom cheoJid room msg = do uuid <- (fmap.fmap) UUID.toString UUID.nextUUID return [mkStanzaRec $ (emptyMessage MessageGroupChat) { messageTo = parseJID $ bareTxt room, messageFrom = Just cheoJid, messageID = Just $ fromString ("CHEOGRAM%" <> fromMaybe "UUIDFAIL" uuid), messagePayloads = [Element (fromString "{jabber:component:accept}body") [] [NodeContent $ ContentText msg]] }] leaveRoom :: DB.DB -> JID -> String -> IO [StanzaRec] leaveRoom db cheoJid@(JID { jidNode = Just _ }) reason = do existingRoom <- (parseJID =<<) <$> DB.get db (DB.byNode cheoJid ["joined"]) return $ (flip map) (toList existingRoom) $ \leaveRoom -> mkStanzaRec $ (emptyPresence PresenceUnavailable) { presenceTo = Just leaveRoom, presenceFrom = Just cheoJid, presencePayloads = [Element (fromString "{jabber:component:accept}status") [] [NodeContent $ ContentText $ fromString reason]] } leaveRoom _ cheoJid reason = do log "ERROR leaveRoom" (cheoJid, reason) return [] joinRoom db cheoJid room = rejoinRoom db cheoJid room False rejoinRoom db cheoJid@(JID { jidNode = Just _ }) room rejoin = do password <- DB.get db (DB.byNode cheoJid [textToString (bareTxt room), "muc_roomsecret"]) let pwEl = maybe [] (\pw -> [ NodeElement $ Element (s"{http://jabber.org/protocol/muc}password") [] [NodeContent $ ContentText pw] ]) password uuid <- fromMaybe "UUIDFAIL" <$> (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID return [mkStanzaRec $ (emptyPresence PresenceAvailable) { presenceID = Just $ fromString $ (if rejoin then "CHEOGRAMREJOIN%" else "CHEOGRAMJOIN%") <> uuid, presenceTo = Just room, presenceFrom = Just cheoJid, presencePayloads = [Element (s"{http://jabber.org/protocol/muc}x") [] ([ NodeElement $ Element (s"{http://jabber.org/protocol/muc}history") [(s"{http://jabber.org/protocol/muc}maxchars", [ContentText $ fromString "0"])] [] ] <> pwEl)] }] rejoinRoom _ cheoJid room rejoin = do log "ERROR rejoinRoom" (cheoJid, room, rejoin) return [] addMUCOwner room from jid = do uuid <- (fmap.fmap) UUID.toString UUID.nextUUID return [mkStanzaRec $ (emptyIQ IQSet) { iqTo = Just room, iqFrom = Just from, iqID = fmap fromString uuid, iqPayload = Just $ Element (s"{http://jabber.org/protocol/muc#admin}admin") [] [ NodeElement $ Element (s"{http://jabber.org/protocol/muc#admin}item") [ (s"{http://jabber.org/protocol/muc#admin}affiliation", [ContentText $ s"owner"]), (s"{http://jabber.org/protocol/muc#admin}jid", [ContentText $ formatJID jid]) ] [] ] }] createRoom :: JID -> [Text] -> JID -> Text -> IO [StanzaRec] createRoom componentJid (server:otherServers) cheoJid name -- First we check if this room exists on the server already | Just t <- to = queryDisco t jid | otherwise = return [] where to = parseJID $ name <> fromString "@" <> server Just jid = parseJID $ fromString "create@" <> formatJID componentJid <> fromString "/" <> intercalate (fromString "|") ((formatJID cheoJid):name:otherServers) createRoom _ [] _ _ = return [] mucShortMatch tel short muc = node == short || T.stripSuffix (fromString "_" <> tel) node == Just short where node = maybe mempty strNode (jidNode =<< parseJID muc) sendInvite db to (Invite { inviteMUC = room, inviteFrom = from }) = do membersonly <- fromMaybe False <$> DB.getEnum db (DB.byJid room ["muc_membersonly"]) -- Try to add everyone we invite as an owner also (++) <$> (if membersonly then addMUCOwner room from to else return []) <*> return [ mkStanzaRec $ (emptyMessage MessageNormal) { messageTo = Just room, messageFrom = Just from, messagePayloads = [ Element (fromString "{http://jabber.org/protocol/muc#user}x") [] [ NodeElement $ Element (fromString "{http://jabber.org/protocol/muc#user}invite") [ (fromString "{http://jabber.org/protocol/muc#user}to", [ContentText $ formatJID to]) ] [] ] ] }, mkStanzaRec $ (emptyMessage MessageNormal) { messageTo = Just to, messageFrom = Just from, messagePayloads = [ Element (fromString "{jabber:x:conference}x") [ (fromString "{jabber:x:conference}jid", [ContentText $ formatJID room]) ] [], Element (fromString "{jabber:component:accept}body") [] [NodeContent $ ContentText $ mconcat [formatJID from, fromString " has invited you to join ", formatJID room]] ] } ] registerToGateway componentJid gatewayJid did password = return [ mkStanzaRec $ (emptyIQ IQSet) { iqTo = Just gatewayJid, iqFrom = Just componentJid, iqPayload = Just $ Element (fromString "{jabber:iq:register}query") [] [ NodeElement $ Element (fromString "{jabber:iq:register}phone") [] [NodeContent $ ContentText did], NodeElement $ Element (fromString "{jabber:iq:register}password") [] [NodeContent $ ContentText password] ] } ] processSMS db componentJid conferenceServers smsJid cheoJid txt = do nick <- fromMaybe (maybe (formatJID cheoJid) strNode (jidNode cheoJid)) <$> DB.get db (DB.byNode cheoJid ["nick"]) existingRoom <- (fmap (\jid -> jid { jidResource = Nothing }) . parseJID =<<) <$> DB.get db (DB.byNode cheoJid ["joined"]) case parseCommand txt existingRoom nick componentJid of Just JoinInvited -> do invitedRoom <- (parseJID =<<) <$> DB.get db (DB.byNode cheoJid ["invited"]) let toJoin = invitedRoom >>= \jid -> parseJID (bareTxt jid <> s"/" <> nick) case toJoin of Just room -> (++) <$> leaveRoom db cheoJid "Joined a different room." <*> joinRoom db cheoJid room Nothing -> return [mkStanzaRec $ mkSMS componentJid smsJid (s"You have not recently been invited to a group")] Just JoinInvitedWrong | Just room <- existingRoom -> sendToRoom cheoJid room (s"Join") | otherwise -> do invitedRoom <- (parseJID =<<) <$> DB.get db (DB.byNode cheoJid ["invited"]) let toJoin = invitedRoom >>= \jid -> parseJID (bareTxt jid <> fromString "/" <> nick) case toJoin of Just room -> fmap ((mkStanzaRec $ mkSMS componentJid smsJid (s"I think you meant \"/join\", trying anyway...")):) (joinRoom db cheoJid room) Nothing -> return [mkStanzaRec $ mkSMS componentJid smsJid (s"You have not recently been invited to a group")] Just (Create name) -> do servers <- shuffleM conferenceServers roomCreateStanzas <- createRoom componentJid servers cheoJid name if null roomCreateStanzas then return [mkStanzaRec $ mkSMS componentJid smsJid (s"Invalid group name")] else return roomCreateStanzas Just (Join room) -> do leaveRoom db cheoJid "Joined a different room." bookmarks <- DB.smembers db (DB.byNode cheoJid ["bookmarks"]) let tel = maybe mempty strNode (jidNode cheoJid) joinRoom db cheoJid $ fromMaybe room $ parseJID =<< fmap (<> fromString "/" <> nick) (find (mucShortMatch tel (strDomain $ jidDomain room)) bookmarks) Just Leave -> leaveRoom db cheoJid "Typed /leave" Just Who -> do let room = maybe mempty bareTxt existingRoom presence <- DB.hgetall db (DB.Key ["presence", T.unpack room]) let presence' = filter (/= nick) $ map fst presence if null presence then return [mkStanzaRec $ mkSMS componentJid smsJid $ fromString $ "You are not joined to a group. Reply with /help to learn more" ] else return [mkStanzaRec $ mkSMS componentJid smsJid $ mconcat $ [ s"You are joined to ", room, s" as ", nick] ++ if null presence' then [] else [ s" along with\n", intercalate (s", ") presence' ]] Just List -> do bookmarks <- DB.smembers db (DB.byNode cheoJid ["bookmarks"]) return [mkStanzaRec $ mkSMS componentJid smsJid $ s"Groups you can /join\n" ++ intercalate (s"\n") bookmarks] Just (InviteCmd jid) | Just room <- existingRoom -> sendInvite db jid (Invite room cheoJid Nothing Nothing) | otherwise -> return [mkStanzaRec $ mkSMS componentJid smsJid (fromString "You are not joined to a group. Reply with /help to learn more")] Just (SetNick nick) -> do DB.set db (DB.byNode cheoJid ["nick"]) nick fmap (concat . toList) $ forM existingRoom $ \room -> do let toJoin = parseJID (bareTxt room <> fromString "/" <> nick) fmap (concat . toList) $ forM toJoin $ joinRoom db cheoJid Just (Whisper to msg) -> do uuid <- (fmap.fmap) UUID.toString UUID.nextUUID return [mkStanzaRec $ (emptyMessage MessageChat) { messageTo = Just to, messageFrom = Just cheoJid, messageID = Just $ fromString ("CHEOGRAM%" <> fromMaybe "UUIDFAIL" uuid), messagePayloads = [Element (fromString "{jabber:component:accept}body") [] [NodeContent $ ContentText msg]] }] Just (Send msg) | Just room <- existingRoom -> sendToRoom cheoJid room msg | otherwise -> return [mkStanzaRec $ mkSMS componentJid smsJid (fromString "You are not joined to a group")] Just (Debounce time) -> do DB.set db (DB.byNode cheoJid ["debounce"]) (tshow time) return [] Just Help -> return [ mkStanzaRec $ mkSMS componentJid smsJid $ fromString $ mconcat [ "Invite to group: /invite phone-number\n", "Show group participants: /who\n", "Set nick: /nick nickname\n", "List groups: /list\n", "Create a group: /create short-name" ], mkStanzaRec $ mkSMS componentJid smsJid $ fromString $ mconcat [ "Join existing group: /join group-name\n", "Whisper to user: /msg username message\n", "Leave group: /leave\n", "More info: http://cheogram.com" ] ] Just (AddJid addjid) -> do token <- genToken 100 DB.set db (DB.byJid addjid ["addtoken"]) (tshow (formatJID cheoJid, token)) return $ case parseJID (formatJID componentJid ++ s"/token") of Just sendFrom -> [mkStanzaRec $ mkSMS sendFrom smsJid (s"CHEOGRAM" ++ token)] Nothing -> [] Just (DelJid deljid) -> do -- Deleting a JID is much less dangerous since in the worst case SMS just go to the actual phone number DB.del db (DB.byJid deljid ["cheoJid"]) DB.srem db (DB.byNode cheoJid ["owners"]) [bareTxt deljid] return [mkStanzaRec $ mkSMS componentJid smsJid (bareTxt deljid ++ s" removed from your phone number")] Just Jids -> do owners <- DB.smembers db (DB.byNode cheoJid ["owners"]) return [mkStanzaRec $ mkSMS componentJid smsJid $ s"JIDs owning this phone number:\n" <> intercalate (s"\n") owners] Nothing -> return [mkStanzaRec $ mkSMS componentJid smsJid (fromString "You sent an invalid message")] syncCall chan req = do var <- atomically $ newEmptyTMVar atomically $ writeTChan chan (req var) atomically $ takeTMVar var data RejoinManagerCommand = CheckPings | PingReply JID | PingError JID | Joined JID | ForceRejoin JID JID data RejoinManagerState = PingSent JID | Rejoining rejoinManager db sendToComponent componentJid toRoomPresences toRejoinManager = next mempty where mkMucJid muc nick = parseJID $ bareTxt muc <> fromString "/" <> nick ourJids muc (x,y) | Just (JID { jidDomain = d }) <- yJid, strDomain d /= fromString componentJid = Nothing | otherwise = (,) <$> mkMucJid muc x <*> yJid where yJid = parseJID =<< y next state = atomically (readTChan toRejoinManager) >>= go state go state (PingReply mucJid) = next $! Map.delete mucJid state go state (PingError mucJid) = do forM_ (Map.lookup mucJid state) $ \x -> case x of PingSent cheoJid -> atomically $ writeTChan toRejoinManager (ForceRejoin mucJid cheoJid) _ -> return () next state go state (Joined mucJid) = next $! Map.delete mucJid state go state (ForceRejoin mucJid cheoJid) = do atomically $ writeTChan toRoomPresences (StartRejoin cheoJid mucJid) mapM_ sendToComponent =<< rejoinRoom db cheoJid mucJid True next $! Map.insert mucJid Rejoining state go state CheckPings = do (next =<<) $! DB.foldKeysM db (DB.Key ["presence"]) state $ \state pkey@(DB.Key keyparts) -> do let Just muc = parseJID . fromString =<< atZ keyparts 1 presences <- mapMaybe (ourJids muc) <$> DB.hgetall db pkey (\x -> foldM x state presences) $ \state (mucJid, cheoJid) -> case Map.lookup mucJid state of Nothing -> do uuid <- fromMaybe "UUIDFAIL" <$> (fmap.fmap) (fromString . UUID.toString) UUID.nextUUID sendToComponent $ mkStanzaRec $ (emptyIQ IQGet) { iqTo = Just mucJid, iqFrom = Just cheoJid, iqID = Just $ fromString $ "CHEOGRAMPING%" <> uuid, iqPayload = Just $ Element (fromString "{urn:xmpp:ping}ping") [] [] } return $! Map.insert mucJid (PingSent cheoJid) state Just (PingSent _) -> do -- Timeout, rejoin atomically $ writeTChan toRejoinManager (ForceRejoin mucJid cheoJid) return state Just Rejoining -> -- Don't ping, we're working on it return state -- tel@cheogram, from (bare is MUC, resource is nick), Maybe participantJID data RoomPresences = RecordSelfJoin JID JID (Maybe JID) | RecordJoin JID JID (Maybe JID) | RecordPart JID JID | RecordNickChanged JID JID Text | Clear JID JID | StartRejoin JID JID | GetRoomPresences JID JID (TMVar [(Text, Maybe Text)]) roomPresences db toRoomPresences = forever $ atomically (readTChan toRoomPresences) >>= go where go (RecordSelfJoin cheoJid from jid) = do -- After a join is done we have a full presence list, remove old ones DB.del db (DB.byNode cheoJid [muc from, "old_presence"]) globalAndLocal cheoJid from (\k -> DB.hset db k [(resource from, bareTxt <$> jid)]) go (RecordJoin cheoJid from jid) = globalAndLocal cheoJid from (\k -> DB.hset db k [(resource from, bareTxt <$> jid)]) go (RecordPart cheoJid from) = do globalAndLocal cheoJid from (\k -> DB.hdel db k [resource from]) go (RecordNickChanged cheoJid from nick) = globalAndLocal cheoJid from (\k -> DB.hset db k [(resource from, Just nick)]) go (Clear cheoJid from) = DB.del db (DB.byNode cheoJid [muc from, "presence"]) go (StartRejoin cheoJid from) = do -- Copy current presences to a holding space so we can clear when rejoin is over presences <- DB.hgetall db (DB.byNode cheoJid [muc from, "presence"]) DB.hset db (DB.byNode cheoJid [muc from, "old_presence"]) presences DB.del db (DB.byNode cheoJid [muc from, "presence"]) go (GetRoomPresences cheoJid from rtrn) = do presences <- DB.hgetall db (DB.byNode cheoJid [muc from, "presence"]) old_presences <- DB.hgetall db (DB.byNode cheoJid [muc from, "old_presence"]) atomically $ putTMVar rtrn $ presences ++ old_presences globalAndLocal cheoJid from f = do f (DB.Key ["presence", muc from]) f (DB.byNode cheoJid [muc from, "presence"]) muc = T.unpack . bareTxt resource x = fromMaybe mempty (strResource <$> jidResource x) data JoinPartDebounce = DebounceJoin JID JID (Maybe JID) | DebouncePart JID JID | DebounceExpire JID JID UTCTime deriving (Show) joinPartDebouncer db backendHost sendToComponent componentJid toRoomPresences toJoinPartDebouncer = next mempty where next state = do msg <- atomically (readTChan toJoinPartDebouncer) go state msg >>= next recordJoinPart cheoJid from mjid join | join = atomically $ writeTChan toRoomPresences $ RecordJoin cheoJid from mjid | otherwise = atomically $ writeTChan toRoomPresences $ RecordPart cheoJid from sendPart cheoJid from time = forM_ (mapToBackend backendHost cheoJid) $ \smsJid -> do atomically $ writeTChan toRoomPresences $ RecordPart cheoJid from now <- getCurrentTime sendToComponent $ mkStanzaRec $ mkSMS componentJid smsJid $ mconcat [ fromString "* ", fromMaybe mempty (strResource <$> jidResource from), fromString " left the group ", fromString $ show $ round ((now `diffUTCTime` time) / 60), fromString " minutes ago" ] sendJoin cheoJid from time mjid = forM_ (mapToBackend backendHost cheoJid) $ \smsJid -> do let nick = fromMaybe mempty (strResource <$> jidResource from) presences <- syncCall toRoomPresences $ GetRoomPresences cheoJid from now <- getCurrentTime when (isNothing $ lookup nick presences) $ do atomically $ writeTChan toRoomPresences $ RecordJoin cheoJid from mjid sendToComponent $ mkStanzaRec $ mkSMS componentJid smsJid $ mconcat [ fromString "* ", nick, fromString " joined the group ", fromString $ show $ round ((now `diffUTCTime` time) / 60), fromString " minutes ago" ] debounceCheck state cheoJid from mjid join = case Map.lookup (cheoJid, from) state of Just (_, _, j) | j /= join -> return $! Map.delete (cheoJid, from) state -- debounce Just (_, _, _) -> return state -- ignore dupe Nothing -> do expire <- fmap (fromMaybe (-1) . (readZ . textToString =<<)) (DB.get db (DB.byNode cheoJid ["debounce"])) time <- getCurrentTime if expire < 0 then recordJoinPart cheoJid from mjid join else void $ forkIO $ threadDelay (expire*1000000) >> atomically (writeTChan toJoinPartDebouncer $ DebounceExpire cheoJid from time) return $! Map.insert (cheoJid, from) (time, mjid, join) state go state (DebounceJoin cheoJid from mjid) = debounceCheck state cheoJid from mjid True go state (DebouncePart cheoJid from) = debounceCheck state cheoJid from Nothing False go state (DebounceExpire cheoJid from time) = case Map.updateLookupWithKey (\_ (t,m,j) -> if t == time then Nothing else Just (t,m,j)) (cheoJid, from) state of (Just (t, mjid, join), state') | t == time && join -> sendJoin cheoJid from time mjid >> return state' | t == time -> sendPart cheoJid from time >> return state' (_, state') -> return state' adhocBotManager :: (UIO.Unexceptional m) => DB.DB -> JID -> (XMPP.Message -> UIO.UIO ()) -> (XMPP.IQ -> UIO.UIO (STM (Maybe XMPP.IQ))) -> (STM XMPP.Message) -> m () adhocBotManager db componentJid sendMessage sendIQ messages = do cleanupChan <- atomicUIO newTChan statefulManager cleanupChan Map.empty where statefulManager cleanupChan sessions = do join $ atomicUIO $ (processMessage cleanupChan sessions <$> messages) <|> (cleanupSession cleanupChan sessions <$> readTChan cleanupChan) cleanupSession cleanupChan sessions sessionToClean = statefulManager cleanupChan $! (Map.delete sessionToClean sessions) processMessage cleanupChan sessions message = do -- XXX: At some point this should not include resource, but it makes it easy to test for now let key = bareTxt <$> (XMPP.stanzaFrom message) sessions' <- case Map.lookup key sessions of Just input -> input message >> return sessions Nothing -> do newChan <- atomicUIO newTChan UIO.forkFinally (adhocBotSession db componentJid sendMessage sendIQ (readTChan newChan) message) (\result -> do fromIO_ $ either (log "adhocBotManager") (const $ return ()) result atomicUIO $ writeTChan cleanupChan key ) let writer = (atomicUIO . writeTChan newChan) return $ Map.insert key writer sessions statefulManager cleanupChan sessions' data Avatar = Avatar Text Int64 Text mkAvatar :: FilePath -> IO Avatar mkAvatar path = do png <- LZ.readFile path return $! Avatar (T.pack $ showDigest $ sha1 png) (LZ.length png) (decodeUtf8 $ Base64.encode $ LZ.toStrict png) avatarMetadata :: Avatar -> XML.Element avatarMetadata (Avatar hash size _) = XML.Element (s"{http://jabber.org/protocol/pubsub#event}event") [] [ XML.NodeElement $ XML.Element (s"{http://jabber.org/protocol/pubsub#event}items") [(s"node", [XML.ContentText $ s"urn:xmpp:avatar:metadata"])] [ XML.NodeElement $ XML.Element (s"{http://jabber.org/protocol/pubsub#event}item") [(s"id", [XML.ContentText hash])] [ XML.NodeElement $ XML.Element (s"{urn:xmpp:avatar:metadata}metadata") [] [ XML.NodeElement $ XML.Element (s"{urn:xmpp:avatar:metadata}info") [ (s"id", [XML.ContentText hash]), (s"bytes", [XML.ContentText $ tshow size]), (s"type", [XML.ContentText $ s"image/png"]) ] [] ] ] ] ] main :: IO () main = do hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering magic <- magicOpen [MagicMimeType] magicLoadDefault magic args <- getArgs case args of ("register":componentHost:host:port:secret:backendHost:did:password:[]) -> do log "" "Registering..." let Just componentJid = parseJID (fromString componentHost) let Just gatewayJid = parseJID (fromString backendHost) void $ runComponent (Server componentJid host (read port)) (fromString secret) $ do mapM_ putStanza =<< registerToGateway componentJid gatewayJid (fromString did) (fromString password) liftIO $ threadDelay 1000000 [config] -> do (Config.Config componentJid (Config.ServerConfig host port) secret backendHost rawdid registrationJid conferences s5bListenOn (Config.ServerConfig s5bhost s5bport) jingleStore jingleStoreURL (Config.Redis presenceRCI stateRCI) (Config.ServerConfig statsdHost statsdPort) maybeAvatarPath) <- Dhall.input Dhall.auto (fromString config) log "" "Starting..." let Just did = normalizeTel rawdid db <- DB.mk stateRCI presenceRedis <- Redis.checkedConnect presenceRCI toJoinPartDebouncer <- atomically newTChan sendToComponent <- atomically newTChan toStanzaProcessor <- atomically newTChan toRoomPresences <- atomically newTChan toRejoinManager <- atomically newTChan statsd <- openStatsD statsdHost (show statsdPort) ["cheogram"] (sendIQ, iqReceiver) <- iqManager $ atomicUIO . writeTChan sendToComponent . mkStanzaRec adhocBotMessages <- atomically newTChan void $ forkIO $ adhocBotManager db componentJid (atomicUIO . writeTChan sendToComponent . mkStanzaRec) sendIQ (readTChan adhocBotMessages) void $ forkIO $ joinPartDebouncer db backendHost (atomically . writeTChan sendToComponent) componentJid toRoomPresences toJoinPartDebouncer void $ forkIO $ roomPresences db toRoomPresences void $ forkIO $ forever $ atomically (writeTChan toRejoinManager CheckPings) >> threadDelay 120000000 void $ forkIO $ rejoinManager db (atomically . writeTChan sendToComponent) (textToString $ formatJID componentJid) toRoomPresences toRejoinManager -- When we're talking to the adhoc bot we'll get a command from stuff\40example.com@cheogram.com -- When they're talking to us directly, we'll get the command from stuff@example.com -- In either case, we want to use the same key and understand it as coming from the same user let maybeUnescape userJid | jidDomain userJid == jidDomain componentJid, Just node <- jidNode userJid = let resource = maybe mempty strResource $ jidResource userJid in -- If we can't parse the thing we unescaped, just return the original fromMaybe userJid $ parseJID (unescapeJid (strNode node) ++ if T.null resource then mempty else s"/" ++ resource) | otherwise = userJid processDirectMessageRouteConfig <- ConfigureDirectMessageRoute.main (XMPP.jidDomain componentJid) (\userJid -> let userJid' = maybeUnescape userJid in (parseJID =<<) <$> DB.get db (DB.byJid userJid' ["possible-route"]) ) (\userJid -> let userJid' = maybeUnescape userJid in (parseJID =<<) <$> DB.get db (DB.byJid userJid' ["direct-message-route"]) ) (\userJid mgatewayJid -> do let userJid' = maybeUnescape userJid DB.del db (DB.byJid userJid' ["possible-route"]) case mgatewayJid of Just gatewayJid -> do maybeExistingRoute <- (parseJID =<<) <$> DB.get db (DB.byJid userJid' ["direct-message-route"]) forM_ maybeExistingRoute $ \existingRoute -> when (existingRoute /= gatewayJid) (atomically . writeTChan sendToComponent . mkStanzaRec =<< unregisterDirectMessageRoute db componentJid userJid' existingRoute) DB.set db (DB.byJid userJid' ["direct-message-route"]) (formatJID gatewayJid) forM_ (parseJID $ escapeJid (bareTxt userJid') ++ s"@" ++ formatJID componentJid) $ \from -> forM_ (parseJID $ did ++ s"@" ++ formatJID gatewayJid) $ \to -> atomically $ writeTChan sendToComponent $ mkStanzaRec $ mkSMS from to (s"/addjid " ++ bareTxt userJid') return () Nothing -> do maybeExistingRoute <- (parseJID =<<) <$> DB.get db (DB.byJid userJid' ["direct-message-route"]) DB.del db (DB.byJid userJid' ["direct-message-route"]) forM_ maybeExistingRoute $ \existingRoute -> atomically . writeTChan sendToComponent . mkStanzaRec =<< unregisterDirectMessageRoute db componentJid userJid' existingRoute ) jingleHandler <- UIO.runEitherIO $ Jingle.setupJingleHandlers jingleStore s5bListenOn (fromString s5bhost, s5bport) (log "JINGLE") (\iq@(IQ { iqPayload = Just jingle }) path -> forM_ (isNamed (s"{urn:xmpp:jingle:1}content") =<< elementChildren jingle) $ \content -> do let fileDesc = mfilter (/=mempty) $ fmap (mconcat . elementText) $ headZ (isNamed (s"{urn:xmpp:jingle:apps:file-transfer:5}desc") =<< elementChildren =<< isNamed (s"{urn:xmpp:jingle:apps:file-transfer:5}file") =<< elementChildren =<< isNamed (s"{urn:xmpp:jingle:apps:file-transfer:5}description") =<< elementChildren content) mimeType <- fromIO_ $ magicFile magic path let extSuffix = maybe mempty (s"." ++) $ SMap.lookup mimeType mimeToExtMap atomicUIO $ writeTChan toStanzaProcessor $ let url = jingleStoreURL ++ (T.takeWhileEnd (/='/') $ fromString path) ++ extSuffix in ReceivedMessage $ (emptyMessage MessageNormal) { messageFrom = iqFrom iq, messageTo = iqTo iq, messagePayloads = [ Element (s"{jabber:component:accept}body") [] [NodeContent $ ContentText $ maybe mempty (++s"\n") fileDesc ++ url], Element (s"{jabber:x:oob}x") [] ([ NodeElement $ Element (s"{jabber:x:oob}url") [] [NodeContent $ ContentText url] ] ++ (maybe [] (\desc -> pure $ NodeElement $ Element (s"{jabber:x:oob}desc") [] [NodeContent $ ContentText desc]) fileDesc)) ] } fromIO_ $ atomically $ writeTChan sendToComponent $ mkStanzaRec $ (emptyIQ IQSet) { iqTo = iqFrom iq, iqFrom = iqTo iq, iqPayload = Just $ Element (s"{urn:xmpp:jingle:1}jingle") [(s"action", [s"session-info"]), (s"sid", [ContentText $ fromMaybe mempty $ attributeText (s"sid") jingle])] [ NodeElement $ Element (s"{urn:xmpp:jingle:apps:file-transfer:5}received") [(s"creator", fromMaybe [] $ attributeContent (s"creator") content), (s"name", fromMaybe [] $ attributeContent (s"name") content)] [] ] } fromIO_ $ atomically $ writeTChan sendToComponent $ mkStanzaRec $ (emptyIQ IQSet) { iqTo = iqFrom iq, iqFrom = iqTo iq, iqID = Just $ s"id-session-terminate", iqPayload = Just $ Element (s"{urn:xmpp:jingle:1}jingle") [(s"action", [s"session-terminate"]), (s"sid", [ContentText $ fromMaybe mempty $ attributeText (s"sid") jingle])] [ NodeElement $ Element (s"{urn:xmpp:jingle:1}reason") [] [ NodeElement $ Element (s"{urn:xmpp:jingle:1}success") [] [] ] ] } ) (\iq@(IQ { iqFrom = Just from, iqTo = Just to }) -> do maybeProxy <- fmap (join . hush) $ UIO.fromIO $ getSipProxy db componentJid sendIQ from fromIO_ $ atomically $ writeTChan sendToComponent $ mkStanzaRec $ case maybeProxy of Just proxy -> rewriteJingleInitiatorResponder $ iq { iqFrom = parseJID $ escapeJid (bareTxt from) ++ s"@" ++ formatJID componentJid ++ s"/CHEOGRAM%outbound-sip%" ++ fromMaybe mempty (strResource <$> jidResource from), iqTo = parseJID $ escapeJid (fromMaybe mempty (strNode <$> jidNode to) ++ s"@" ++ proxy) ++ s"@sip.cheogram.com/sip" } Nothing -> iqNotImplemented iq ) let pushStatsd = void . UIO.fromIO . StatsD.push statsd maybeAvatar <- mapM mkAvatar maybeAvatarPath log "" "runComponent STARTING" log "runComponent ENDED" =<< runComponent (Server componentJid host port) secret (component db presenceRedis (UIO.lift . pushStatsd) backendHost did maybeAvatar (cacheOOB magic (UIO.lift . pushStatsd) jingleStore jingleStoreURL) sendIQ iqReceiver (writeTChan adhocBotMessages) toRoomPresences toRejoinManager toJoinPartDebouncer sendToComponent toStanzaProcessor processDirectMessageRouteConfig jingleHandler componentJid [registrationJid] conferences) _ -> log "ERROR" "Bad arguments"
singpolyma/cheogram
Main.hs
agpl-3.0
109,957
2,988
34
20,085
39,257
19,963
19,294
-1
-1
{-# LANGUAGE ScopedTypeVariables,CPP #-} -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA -- module Test.Framework.HaskellParser where import Data.Maybe import Data.Char ( isSpace, isDigit ) import qualified Data.List as List import Control.Exception ( evaluate, catch, SomeException ) #if !MIN_VERSION_base(4,6,0) import Prelude hiding ( catch ) #endif import qualified Language.Haskell.Exts as Exts import qualified Language.Haskell.Exts.Parser as Parser import qualified Language.Haskell.Exts.Syntax as Syn import qualified Language.Haskell.Exts.Extension as Ext import qualified Language.Haskell.Exts.Fixity as Fix import qualified Language.Haskell.Exts.SrcLoc as Src import Test.Framework.Location import Test.Framework.Utils type Name = String data Decl = Decl { decl_loc :: Location , decl_name :: Name } deriving (Show) data Pragma = Pragma { pr_name :: String , pr_args :: String , pr_loc :: Location } deriving (Show) data ParseResult a = ParseOK a | ParseError Location String data Module = Module { mod_name :: Name , mod_imports :: [ImportDecl] , mod_decls :: [Decl] , mod_htfPragmas :: [Pragma] } deriving (Show) data ImportDecl = ImportDecl { imp_moduleName :: Name , imp_qualified :: Bool , imp_alias :: Maybe Name , imp_loc :: Location } deriving (Show) -- Returns for lines of the form '# <number> "<filename>"' -- (see http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html#Preprocessor-Output) -- the value 'Just <number> "<filename>"' parseCppLineInfoOut :: String -> Maybe (String, String) parseCppLineInfoOut line = case line of '#':' ':c:rest | isDigit c -> case List.span isDigit rest of (restDigits, ' ' : '"' : rest) -> case dropWhile (/= '"') (reverse rest) of '"' : fileNameRev -> let line = (c:restDigits) file = "\"" ++ reverse fileNameRev ++ "\"" in Just (line, file) _ -> Nothing _ -> Nothing _ -> Nothing parse :: FilePath -> String -> IO (ParseResult Module) parse originalFileName input = do r <- (evaluate $ Exts.parseFileContentsWithComments parseMode fixedInput) `catch` (\(e::SomeException) -> return $ Parser.ParseFailed unknownLoc (show e)) case r of Parser.ParseFailed loc err -> return (ParseError (transformLoc loc) err) Parser.ParseOk (m, comments) -> return $ ParseOK (transformModule m comments) where -- fixedInput serves two purposes: -- 1. add a trailing \n -- 2. turn lines of the form '# <number> "<filename>"' into GHC line pragmas '{-# LINE <number> <filename> #-}' -- 2. turn lines of the form '#line <number> "<filename>"' into GHC line pragmas '{-# LINE <number> <filename> #-}' -- 3. comment out lines starting with # fixedInput :: String fixedInput = (unlines . map fixLine . lines) input where fixLine s = case parseCppLineInfoOut s of Just (line, file) -> "{-# LINE " ++ line ++ " " ++ file ++ " #-}" Nothing -> case dropWhile isSpace s of '#':'l':'i':'n':'e':rest -> "{-# LINE " ++ rest ++ " #-}" '#':_ -> "-- " ++ s _ -> s {- FIXME: fixities needed for all operators. Heuristic: all operators are considered to be any sequence of the symbols _:"'>!#$%&*+./<=>?@\^|-~ with at most length 8 -} parseMode :: Parser.ParseMode parseMode = Parser.ParseMode { Parser.parseFilename = originalFileName , Parser.baseLanguage = Ext.Haskell2010 , Parser.ignoreLanguagePragmas = False , Parser.ignoreLinePragmas = False , Parser.extensions = (map Ext.EnableExtension extensions) , Parser.fixities = Nothing } extensions = [ Ext.ForeignFunctionInterface , Ext.UnliftedFFITypes , Ext.GADTs , Ext.ScopedTypeVariables , Ext.UnboxedTuples , Ext.TypeSynonymInstances , Ext.StandaloneDeriving , Ext.DeriveDataTypeable , Ext.FlexibleContexts , Ext.FlexibleInstances , Ext.ConstrainedClassMethods , Ext.MultiParamTypeClasses , Ext.FunctionalDependencies , Ext.MagicHash , Ext.PolymorphicComponents , Ext.ExistentialQuantification , Ext.UnicodeSyntax , Ext.PostfixOperators , Ext.PatternGuards , Ext.LiberalTypeSynonyms , Ext.RankNTypes , Ext.ImpredicativeTypes , Ext.TypeOperators , Ext.RecursiveDo , Ext.ParallelListComp , Ext.EmptyDataDecls , Ext.KindSignatures , Ext.GeneralizedNewtypeDeriving , Ext.TypeFamilies , Ext.NamedFieldPuns , Ext.RecordWildCards , Ext.PackageImports , Ext.ViewPatterns , Ext.TupleSections , Ext.NondecreasingIndentation , Ext.DoAndIfThenElse ] unknownLoc :: Syn.SrcLoc unknownLoc = Syn.SrcLoc originalFileName 0 0 transformModule (Syn.Module _ (Syn.ModuleName moduleName) _ _ _ imports decls) comments = Module moduleName (map transformImport imports) (mapMaybe transformDecl decls) (mapMaybe transformComment comments) #if MIN_VERSION_haskell_src_exts(1,16,0) transformImport (Syn.ImportDecl loc (Syn.ModuleName s) qualified _ _ _ alias _) = let alias' = case alias of Nothing -> Nothing Just (Syn.ModuleName s) -> Just s in ImportDecl s qualified alias' (transformLoc loc) transformDecl (Syn.PatBind loc (Syn.PVar name) _ _) = Just $ Decl (transformLoc loc) (transformName name) #else transformImport (Syn.ImportDecl loc (Syn.ModuleName s) qualified _ _ alias _) = let alias' = case alias of Nothing -> Nothing Just (Syn.ModuleName s) -> Just s in ImportDecl s qualified alias' (transformLoc loc) transformDecl (Syn.PatBind loc (Syn.PVar name) _ _ _) = Just $ Decl (transformLoc loc) (transformName name) #endif transformDecl (Syn.FunBind (Syn.Match loc name _ _ _ _ : _)) = Just $ Decl (transformLoc loc) (transformName name) transformDecl _ = Nothing transformSpan span = makeLoc (Src.srcSpanFilename span) (Src.srcSpanStartLine span) transformLoc (Syn.SrcLoc f n _) = makeLoc f n transformName :: Syn.Name -> String transformName (Syn.Ident s) = s transformName (Syn.Symbol s) = s transformComment (Exts.Comment True span ('@':s)) = case reverse s of '@':r -> let stripped = strip (reverse r) in if "HTF_" `List.isPrefixOf` stripped then let (name, args) = List.span (not . isSpace) stripped argsStripped = dropWhile isSpace args loc = transformSpan span in Just $ Pragma name argsStripped loc else Nothing _ -> Nothing transformComment _ = Nothing
ekarayel/HTF
Test/Framework/HaskellParser.hs
lgpl-2.1
8,590
0
21
2,911
1,636
905
731
147
12
module Main where import Criterion.Main import qualified Data.Map as M import qualified Data.Set as S bumpIt (i, v) = (i + 1, v + 1) m :: M.Map Int Int m = M.fromList $ take 10000 stream where stream = iterate bumpIt (0, 0) s :: S.Set Int s = S.fromList $ take 10000 stream where stream = iterate (+1) 0 membersMap :: Int -> Bool membersMap i = M.member i m membersSet :: Int -> Bool membersSet i = S.member i s insertsMap :: Int -> M.Map Int Int insertsMap i = M.insert i 1 m insertsSet :: Int -> S.Set Int insertsSet i = S.insert i s main :: IO () main = defaultMain [ bench "member check map" $ whnf membersMap 9999 , bench "member check set" $ whnf membersSet 9999 , bench "insert check map #1" $ whnf membersMap 7777 , bench "insert check set #1" $ whnf membersSet 7777 , bench "insert check map #2" $ whnf membersMap 10001 , bench "insert check set #2" $ whnf membersSet 10001 ]
dmp1ce/Haskell-Programming-Exercises
Chapter 28/benchSet.hs
unlicense
912
0
8
202
359
185
174
27
1
module Main where splitWith :: (a -> Bool) -> [a] -> [[a]] splitWith _ [] = [] splitWith predicate xs = filter ((/=0) . length) $ let (pre, nxt) = break predicate xs in [pre] ++ (splitWith predicate (if null nxt then [] else tail nxt)) transpose :: [String] -> IO () transpose [] = return () transpose lines = putStrLn (map head lines) >> transpose (filter ((/=0) . length) $ map (\x -> if null x then [] else tail x) lines) main :: IO () --main = getLine >>= return . head . words >>= putStrLn >> main main = getContents >>= return . lines >>= transpose
shashikiranrp/RealWorldHaskell
Chapter 4/Main.hs
apache-2.0
560
0
13
114
268
141
127
9
2
module Assembler (assembleSource ) where {- A 8080 CPU assembler. -} -- import Debug.Trace -- import Data.Char (toUpper, toLower) import Data.List (intercalate, find) import Data.Word import Data.Bits import Data.Char (toUpper) import qualified Data.Map as M import Text.Printf import Control.Monad (liftM, liftM2) import Control.Applicative ((<*), (<$>), (<*>), pure) import Text.ParserCombinators.Parsec import qualified Data.ByteString as BS {- for debug use -} -- miatrace a = trace (show a) a {- Instruction Specification List Parsing instruction list can be generated with the tool below `utils/genInstList.hs` from a opcode html file. -} type LocalAddr = Word16 data Register = A | B | C | D | E | H | L | M | PSW | SP | IP deriving (Eq) instance Show Register where show A = "A" show B = "B" show C = "C" show D = "D" show E = "E" show H = "H" show L = "L" show M = "[HL]" show PSW = "PSW" show SP = "SP" show IP = "IP" data Parameter = Reg Register | Addr | Byte | Word | Parm Int instance Show Parameter where show (Reg r) = show r show Addr = "[addr]" show Byte = "xx" show Word = "xxxx" show (Parm i) = show i data Instruction = Inst { _instName :: String , _instCode :: BS.ByteString , _instParams :: [Parameter] } instance Show Instruction where show Inst { _instName = n , _instCode = c , _instParams = p } = unwords [showcode c, n, intercalate "," $ map show p] where showcode = concatMap (printf "%02x") . BS.unpack instLen :: Instruction -> Integer instLen (Inst { _instCode = c , _instParams = ps }) = fromIntegral (BS.length c) + sum (map paramLen ps) paramsLen :: [Parameter] -> Integer paramsLen = sum . map paramLen paramLen :: Parameter -> Integer paramLen Reg {} = 0 paramLen Addr {} = 2 paramLen Byte {} = 1 paramLen Word {} = 2 paramLen Parm {} = 0 parseInstList :: String -> [Instruction] parseInstList = concatMap parseline . lines where parseline str = case parse parseInstLine "" str of Left _ -> [] -- error 'parse failed' Right x -> [x] readInstList :: IO [Instruction] readInstList = liftM parseInstList $ readFile "instructions.macro" parseInstLine :: Parser Instruction parseInstLine = do code <- parseInstCode _ <- space name <- parseInstName _ <- optional space parm <- parseInstParams return Inst { _instCode = code , _instName = name , _instParams = parm } parseInstCode :: Parser BS.ByteString parseInstCode = liftM (BS.singleton . read . ("0x"++)) (count 2 hexDigit) parseInstName :: Parser String parseInstName = many1 upper parseInstParams :: Parser [Parameter] parseInstParams = parseInstParam `sepBy` char ',' parseRegister :: Parser Register parseRegister = (char 'A' >> return A) <|> (char 'B' >> return B) <|> (char 'C' >> return C) <|> (char 'D' >> return D) <|> (char 'E' >> return E) <|> (char 'H' >> return H) <|> (char 'L' >> return L) <|> (char 'M' >> return M) <|> (string "PSW" >> return PSW) <|> (string "SP" >> return SP) <|> (string "IP" >> return IP) parseInstParam :: Parser Parameter parseInstParam = liftM Reg parseRegister <|> (string "word" >> return Word) <|> (string "address" >> return Addr) <|> (string "byte" >> return Byte) <|> liftM (Parm . read) (many1 digit) {- End of instruction list parsing procedures -} {- Assembler Translate a list of operations (label or action) into byte codes. -} data AddrType = HexAddr LocalAddr -- | HexOffset LocalAddr Integer | LblOffset String Integer deriving Show data Argument = RegA Register | AddrA AddrType | ByteA Word8 | WordA Word16 | ParmA Int deriving Show data Operation = Label String | Action Instruction [Argument] deriving Show type LabelTable = M.Map String LocalAddr computeLabelTable :: [Operation] -> LabelTable computeLabelTable = snd . foldl accm (0, M.empty) where accm (ptr, m) (Label l) = (ptr, M.insert l ptr m) accm (ptr, m) (Action i _) = (ptr + fromIntegral (instLen i), m) expandOffset :: LabelTable -> AddrType -> LocalAddr expandOffset _ (HexAddr addr) = addr expandOffset tbl (LblOffset lbl off) = case M.lookup lbl tbl of Nothing -> error "Error: label not found" Just x -> x + fromIntegral off validateArguments :: [Parameter] -> [Argument] -> Bool validateArguments ps as = length ps == length as && and (zipWith validateArgument ps as) validateArgument :: Parameter -> Argument -> Bool validateArgument (Reg r) (RegA r') = r == r' validateArgument (Addr) (AddrA _) = True validateArgument (Byte) (ByteA _) = True validateArgument (Word) (WordA _) = True validateArgument (Parm i) (ParmA i') = i == i' validateArgument _ _ = False encodeWord16 :: Word16 -> [Word8] encodeWord16 x = map fromIntegral [x .&. 0xFF, (x .&. 0xFF00) `shiftR` 8] encodeAddress :: LocalAddr -> [Word8] encodeAddress = encodeWord16 extractArgumentByteCode :: Argument -> BS.ByteString extractArgumentByteCode (AddrA (HexAddr a)) = BS.pack $ encodeAddress a extractArgumentByteCode (AddrA _) = error "Please expand the offsets of addresses before assembling." extractArgumentByteCode (ByteA b) = BS.singleton b extractArgumentByteCode (WordA w) = BS.pack $ encodeWord16 w extractArgumentByteCode _ = BS.empty assembleArguments :: [Parameter] -> [Argument] -> BS.ByteString assembleArguments ps as = if validateArguments ps as then foldl BS.append BS.empty $ map extractArgumentByteCode as else error "Invalid Arguments" assembleInstruction :: Instruction -> [Argument] -> BS.ByteString assembleInstruction (Inst _ code params) args | paramsLen params == 0 = code | otherwise = code `BS.append` assembleArguments params args assemble :: [Operation] -> BS.ByteString assemble ops = foldl BS.append BS.empty $ map (curryOp assembleInstruction) ops_addrexpanded where tbl = computeLabelTable ops ops_addrexpanded = map mapargs $ filter notlabel ops notlabel (Label _) = False notlabel _ = True mapargs (Action i args) = Action i $ map mapaddr args mapargs _ = undefined mapaddr (AddrA a) = AddrA $ HexAddr $ expandOffset tbl a mapaddr a = a curryOp f (Action i a) = f i a curryOp _ _ = undefined {- end of the assembling functions definition -} {- Parsing Assembly File -} matchParamArg :: Parameter -> Argument -> Bool matchParamArg (Reg p) (RegA a) = p == a matchParamArg (Parm p) (ParmA a) = p == a matchParamArg Addr (AddrA _) = True matchParamArg Byte (ByteA _) = True matchParamArg Word (WordA _) = True matchParamArg _ _ = False matchParamsArgs :: [Parameter] -> [Argument] -> Bool matchParamsArgs [] [] = True matchParamsArgs ps as | length ps /= length as = False | otherwise = let (p:ps') = ps (a:as') = as in matchParamArg p a && matchParamsArgs ps' as' findInstByNameArgs :: [Instruction] -> String -> [Argument] -> Maybe Instruction findInstByNameArgs i s a = find matchInst i where matchInst Inst {_instName = n, _instParams = p} = map toUpper s == n && p `matchParamsArgs` a filterInstByName :: [Instruction] -> String -> [Instruction] filterInstByName i s = filter (\Inst {_instName = n} -> map toUpper s == n) i parseSource :: [Instruction] -> String -> [Operation] parseSource insttbl str = concatMap parseline $ lines str where parseline str' = case parse ( parseSourceLine insttbl <|> parseSourceLineEmpty ) "" str' of Left x -> error (show x) Right x -> x parseSourceLineEmpty :: Parser [Operation] parseSourceLineEmpty = many space >> eof >> return [] parseSourceLine :: [Instruction] -> Parser [Operation] parseSourceLine insttbl = do skipMany space content <- choice [ many1 (parseSourceLbl <* skipMany space) , liftM (:[]) $ parseSourceInst insttbl , parseSourceComment >> return [] ] skipMany space optional parseSourceComment return content parseLabelText :: Parser String parseLabelText = many1 (oneOf "._" <|> alphaNum) parseSourceLbl :: Parser Operation parseSourceLbl = try $ do text <- parseLabelText _ <- char ':' return $ Label text parseSourceInst :: [Instruction] -> Parser Operation parseSourceInst insttbl = try $ do instName <- many1 letter let candArgList = map (\Inst {_instParams = p} -> p) $ filterInstByName insttbl instName if null candArgList then fail "instruction not found" else do skipMany space args <- choice $ map (try . parseSourceArgs) candArgList case findInstByNameArgs insttbl instName args of Just inst -> return $ Action inst args Nothing -> error $ "instruction " ++ instName ++ " isn't found." parseSourceArgs :: [Parameter] -> Parser [Argument] parseSourceArgs [] = return [] parseSourceArgs [p] = liftM (:[]) $ parseSourceArg p parseSourceArgs (p:ps) = do a <- parseSourceArg p skipMany space >> char ',' >> skipMany space as <- parseSourceArgs ps return (a : as) parseSourceArg :: Parameter -> Parser Argument parseSourceArg (Reg A) = char 'A' >> return (RegA A) parseSourceArg (Reg B) = char 'B' >> return (RegA B) parseSourceArg (Reg C) = char 'C' >> return (RegA C) parseSourceArg (Reg D) = char 'D' >> return (RegA D) parseSourceArg (Reg E) = char 'E' >> return (RegA E) parseSourceArg (Reg H) = char 'H' >> return (RegA H) parseSourceArg (Reg L) = char 'L' >> return (RegA L) parseSourceArg (Reg M) = char 'M' >> return (RegA M) parseSourceArg (Reg PSW) = string "PSW" >> return (RegA PSW) parseSourceArg (Reg SP) = string "SP" >> return (RegA SP) parseSourceArg (Reg IP) = string "IP" >> return (RegA IP) parseSourceArg Addr = parseSourceAddr parseSourceArg Byte = parseSourceByte parseSourceArg Word = parseSourceWord parseSourceArg (Parm i) = parseSourceParm i parseSourceAddr :: Parser Argument parseSourceAddr = liftM (AddrA . HexAddr) (parseHex2 <* oneOf "hH") <|> parseSourceAddrOffset parseSourceAddrOffset :: Parser Argument parseSourceAddrOffset = do lbl <- parseLabelText skipMany space _ <- char '+' skipMany space ofs <- parseDec return $ AddrA $ LblOffset lbl ofs parseSourceByte :: Parser Argument parseSourceByte = try (liftM ByteA (parseHex <* oneOf "hH")) <|> liftM ByteA parseDec parseSourceWord :: Parser Argument parseSourceWord = try (liftM WordA (parseHex2 <* oneOf "hH")) <|> liftM WordA parseDec parseSourceParm :: Int -> Parser Argument parseSourceParm = liftM (ParmA . read) . string . show parseSourceComment :: Parser () parseSourceComment = char ';' >> manyTill anyChar eof >> return () parseHex :: Parser Word8 parseHex = liftM (read . ("0x"++)) (count 2 hexDigit) parseHex2 :: Parser Word16 parseHex2 = liftM (read . ("0x"++)) (count 4 hexDigit) parseDec :: (Read a, Integral a) => Parser a parseDec = liftM read $ many1 digit {- end of assembly file parsing -} pureAssembleSource :: [Instruction] -> String -> BS.ByteString pureAssembleSource = (assemble .) . parseSource assembleSource :: String -> IO BS.ByteString assembleSource src = pureAssembleSource <$> readInstList <*> pure src pipeLine :: IO () {-pipeLine = getContents >>= asm >>= putStrLn . show where asm str = do insttbl <- readInstList return $ parseSource insttbl str -} pipeLine = getContents >>= assembleSource >>= BS.putStr main :: IO () main = pipeLine
shouya/projz
assembler/Assembler.hs
bsd-2-clause
12,349
0
17
3,355
4,005
2,031
1,974
280
5
module Model where import Prelude import Yesod import Data.Text (Text) import Data.Time import Database.Persist.Quasi -- You can define all of your database entities in the entities file. -- You can find more information on persistent and how to declare entities -- at: -- http://www.yesodweb.com/book/persistent/ share [mkPersist sqlSettings, mkMigrate "migrateAll"] $(persistFileWith upperCaseSettings "config/models")
tanakh/hackage-mirror
Model.hs
bsd-2-clause
427
0
8
58
64
37
27
-1
-1
{-# LANGUAGE OverloadedStrings #-} module OpenRTB.Types.BidResponse.SeatBid where import Control.Applicative import Data.Aeson import Data.Maybe import Data.Text import OpenRTB.Types.BidResponse.SeatBid.Bid -- | A bid response can contain multiple `SeatBid` objects, each on behalf of a -- different bidder seat and each containing one or more individual bids. If -- multiple impressions are presented in the request, the `group` attribute -- can be used to specify if a seat is willing to accept any impressions that -- it can win (default) or if it is only interested in winning if it can win -- them all as a group. data SeatBid = SeatBid { -- | Array of 1+ `Bid` objects (Section 4.2.3) each related to an -- impression. bid :: [Bid] -- | ID of the bidder seat on whose behalf this bid is made. , seat :: Maybe Text -- | 0 = impressions can be won individually; 1 = impressions must be won or -- lose as a group. , group :: Bool -- | Placeholder for bidder-specific extensions to OpenRTB. , ext :: Maybe Value } deriving (Show, Eq) instance FromJSON SeatBid where parseJSON (Object v) = SeatBid <$> v .: "bid" <*> v .:? "seat" <*> (toEnum <$> v .:? "group" .!= 0) <*> v .:? "ext" instance ToJSON SeatBid where toJSON (SeatBid b s g e) = object (catMaybes [("seat" .=) <$> s ,("ext" .=) <$> e] ++ ["bid" .= b ,"group" .= fromEnum g])
ankhers/openRTB-hs
src/OpenRTB/Types/BidResponse/SeatBid.hs
bsd-3-clause
1,554
0
12
454
247
144
103
25
0
{-# LANGUAGE CPP #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} -- | Dealing with Cabal. module Stack.Package (readDotBuildinfo ,resolvePackage ,packageFromPackageDescription ,Package(..) ,PackageDescriptionPair(..) ,GetPackageFiles(..) ,GetPackageOpts(..) ,PackageConfig(..) ,buildLogPath ,PackageException (..) ,resolvePackageDescription ,packageDependencies ,applyForceCustomBuild ) where import Data.List (find, isPrefixOf, unzip) import qualified Data.Map.Strict as M import qualified Data.Set as S import qualified Data.Text as T import Distribution.Compiler import Distribution.ModuleName (ModuleName) import qualified Distribution.ModuleName as Cabal import qualified Distribution.Package as D import Distribution.Package hiding (Package,PackageName,packageName,packageVersion,PackageIdentifier) import qualified Distribution.PackageDescription as D import Distribution.PackageDescription hiding (FlagName) import Distribution.PackageDescription.Parsec import Distribution.Pretty (prettyShow) import Distribution.Simple.Glob (matchDirFileGlob) import Distribution.System (OS (..), Arch, Platform (..)) import qualified Distribution.Text as D import qualified Distribution.Types.CondTree as Cabal import qualified Distribution.Types.ExeDependency as Cabal import Distribution.Types.ForeignLib import qualified Distribution.Types.LegacyExeDependency as Cabal import Distribution.Types.LibraryName (libraryNameString, maybeToLibraryName) import Distribution.Types.MungedPackageName import qualified Distribution.Types.UnqualComponentName as Cabal import qualified Distribution.Verbosity as D import Distribution.Version (mkVersion, orLaterVersion, anyVersion) import qualified HiFileParser as Iface #if MIN_VERSION_path(0,7,0) import Path as FL hiding (replaceExtension) #else import Path as FL #endif import Path.Extra import Path.IO hiding (findFiles) import Stack.Build.Installed import Stack.Constants import Stack.Constants.Config import Stack.Prelude hiding (Display (..)) import Stack.Types.Compiler import Stack.Types.Config import Stack.Types.GhcPkgId import Stack.Types.NamedComponent import Stack.Types.Package import Stack.Types.Version import qualified System.Directory as D import System.FilePath (replaceExtension) import qualified System.FilePath as FilePath import System.IO.Error import RIO.Process import RIO.PrettyPrint import qualified RIO.PrettyPrint as PP (Style (Module)) data Ctx = Ctx { ctxFile :: !(Path Abs File) , ctxDistDir :: !(Path Abs Dir) , ctxBuildConfig :: !BuildConfig , ctxCabalVer :: !Version } instance HasPlatform Ctx instance HasGHCVariant Ctx instance HasLogFunc Ctx where logFuncL = configL.logFuncL instance HasRunner Ctx where runnerL = configL.runnerL instance HasStylesUpdate Ctx where stylesUpdateL = runnerL.stylesUpdateL instance HasTerm Ctx where useColorL = runnerL.useColorL termWidthL = runnerL.termWidthL instance HasConfig Ctx instance HasPantryConfig Ctx where pantryConfigL = configL.pantryConfigL instance HasProcessContext Ctx where processContextL = configL.processContextL instance HasBuildConfig Ctx where buildConfigL = lens ctxBuildConfig (\x y -> x { ctxBuildConfig = y }) -- | Read @<package>.buildinfo@ ancillary files produced by some Setup.hs hooks. -- The file includes Cabal file syntax to be merged into the package description -- derived from the package's .cabal file. -- -- NOTE: not to be confused with BuildInfo, an Stack-internal datatype. readDotBuildinfo :: MonadIO m => Path Abs File -> m HookedBuildInfo readDotBuildinfo buildinfofp = liftIO $ readHookedBuildInfo D.silent (toFilePath buildinfofp) -- | Resolve a parsed cabal file into a 'Package', which contains all of -- the info needed for stack to build the 'Package' given the current -- configuration. resolvePackage :: PackageConfig -> GenericPackageDescription -> Package resolvePackage packageConfig gpkg = packageFromPackageDescription packageConfig (genPackageFlags gpkg) (resolvePackageDescription packageConfig gpkg) packageFromPackageDescription :: PackageConfig -> [D.Flag] -> PackageDescriptionPair -> Package packageFromPackageDescription packageConfig pkgFlags (PackageDescriptionPair pkgNoMod pkg) = Package { packageName = name , packageVersion = pkgVersion pkgId , packageLicense = licenseRaw pkg , packageDeps = deps , packageFiles = pkgFiles , packageUnknownTools = unknownTools , packageGhcOptions = packageConfigGhcOptions packageConfig , packageCabalConfigOpts = packageConfigCabalConfigOpts packageConfig , packageFlags = packageConfigFlags packageConfig , packageDefaultFlags = M.fromList [(flagName flag, flagDefault flag) | flag <- pkgFlags] , packageAllDeps = S.fromList (M.keys deps) , packageLibraries = let mlib = do lib <- library pkg guard $ buildable $ libBuildInfo lib Just lib in case mlib of Nothing -> NoLibraries Just _ -> HasLibraries foreignLibNames , packageInternalLibraries = subLibNames , packageTests = M.fromList [(T.pack (Cabal.unUnqualComponentName $ testName t), testInterface t) | t <- testSuites pkgNoMod , buildable (testBuildInfo t) ] , packageBenchmarks = S.fromList [T.pack (Cabal.unUnqualComponentName $ benchmarkName b) | b <- benchmarks pkgNoMod , buildable (benchmarkBuildInfo b) ] -- Same comment about buildable applies here too. , packageExes = S.fromList [T.pack (Cabal.unUnqualComponentName $ exeName biBuildInfo) | biBuildInfo <- executables pkg , buildable (buildInfo biBuildInfo)] -- This is an action used to collect info needed for "stack ghci". -- This info isn't usually needed, so computation of it is deferred. , packageOpts = GetPackageOpts $ \installMap installedMap omitPkgs addPkgs cabalfp -> do (componentsModules,componentFiles,_,_) <- getPackageFiles pkgFiles cabalfp let internals = S.toList $ internalLibComponents $ M.keysSet componentsModules excludedInternals <- mapM (parsePackageNameThrowing . T.unpack) internals mungedInternals <- mapM (parsePackageNameThrowing . T.unpack . toInternalPackageMungedName) internals componentsOpts <- generatePkgDescOpts installMap installedMap (excludedInternals ++ omitPkgs) (mungedInternals ++ addPkgs) cabalfp pkg componentFiles return (componentsModules,componentFiles,componentsOpts) , packageHasExposedModules = maybe False (not . null . exposedModules) (library pkg) , packageBuildType = buildType pkg , packageSetupDeps = msetupDeps , packageCabalSpec = either orLaterVersion id $ specVersionRaw pkg } where extraLibNames = S.union subLibNames foreignLibNames subLibNames = S.fromList $ map (T.pack . Cabal.unUnqualComponentName) $ mapMaybe (libraryNameString . libName) -- this is a design bug in the Cabal API: this should statically be known to exist $ filter (buildable . libBuildInfo) $ subLibraries pkg foreignLibNames = S.fromList $ map (T.pack . Cabal.unUnqualComponentName . foreignLibName) $ filter (buildable . foreignLibBuildInfo) $ foreignLibs pkg toInternalPackageMungedName = T.pack . prettyShow . MungedPackageName (pkgName pkgId) . maybeToLibraryName . Just . Cabal.mkUnqualComponentName . T.unpack -- Gets all of the modules, files, build files, and data files that -- constitute the package. This is primarily used for dirtiness -- checking during build, as well as use by "stack ghci" pkgFiles = GetPackageFiles $ \cabalfp -> debugBracket ("getPackageFiles" <+> pretty cabalfp) $ do let pkgDir = parent cabalfp distDir <- distDirFromDir pkgDir bc <- view buildConfigL cabalVer <- view cabalVersionL (componentModules,componentFiles,dataFiles',warnings) <- runRIO (Ctx cabalfp distDir bc cabalVer) (packageDescModulesAndFiles pkg) setupFiles <- if buildType pkg == Custom then do let setupHsPath = pkgDir </> relFileSetupHs setupLhsPath = pkgDir </> relFileSetupLhs setupHsExists <- doesFileExist setupHsPath if setupHsExists then return (S.singleton setupHsPath) else do setupLhsExists <- doesFileExist setupLhsPath if setupLhsExists then return (S.singleton setupLhsPath) else return S.empty else return S.empty buildFiles <- liftM (S.insert cabalfp . S.union setupFiles) $ do let hpackPath = pkgDir </> relFileHpackPackageConfig hpackExists <- doesFileExist hpackPath return $ if hpackExists then S.singleton hpackPath else S.empty return (componentModules, componentFiles, buildFiles <> dataFiles', warnings) pkgId = package pkg name = pkgName pkgId (unknownTools, knownTools) = packageDescTools pkg deps = M.filterWithKey (const . not . isMe) (M.unionsWith (<>) [ asLibrary <$> packageDependencies packageConfig pkg -- We include all custom-setup deps - if present - in the -- package deps themselves. Stack always works with the -- invariant that there will be a single installed package -- relating to a package name, and this applies at the setup -- dependency level as well. , asLibrary <$> fromMaybe M.empty msetupDeps , knownTools ]) msetupDeps = fmap (M.fromList . map (depPkgName &&& depVerRange) . setupDepends) (setupBuildInfo pkg) asLibrary range = DepValue { dvVersionRange = range , dvType = AsLibrary } -- Is the package dependency mentioned here me: either the package -- name itself, or the name of one of the sub libraries isMe name' = name' == name || fromString (packageNameString name') `S.member` extraLibNames -- | Generate GHC options for the package's components, and a list of -- options which apply generally to the package, not one specific -- component. generatePkgDescOpts :: (HasEnvConfig env, MonadThrow m, MonadReader env m, MonadIO m) => InstallMap -> InstalledMap -> [PackageName] -- ^ Packages to omit from the "-package" / "-package-id" flags -> [PackageName] -- ^ Packages to add to the "-package" flags -> Path Abs File -> PackageDescription -> Map NamedComponent [DotCabalPath] -> m (Map NamedComponent BuildInfoOpts) generatePkgDescOpts installMap installedMap omitPkgs addPkgs cabalfp pkg componentPaths = do config <- view configL cabalVer <- view cabalVersionL distDir <- distDirFromDir cabalDir let generate namedComponent binfo = ( namedComponent , generateBuildInfoOpts BioInput { biInstallMap = installMap , biInstalledMap = installedMap , biCabalDir = cabalDir , biDistDir = distDir , biOmitPackages = omitPkgs , biAddPackages = addPkgs , biBuildInfo = binfo , biDotCabalPaths = fromMaybe [] (M.lookup namedComponent componentPaths) , biConfigLibDirs = configExtraLibDirs config , biConfigIncludeDirs = configExtraIncludeDirs config , biComponentName = namedComponent , biCabalVersion = cabalVer } ) return ( M.fromList (concat [ maybe [] (return . generate CLib . libBuildInfo) (library pkg) , mapMaybe (\sublib -> do let maybeLib = CInternalLib . T.pack . Cabal.unUnqualComponentName <$> (libraryNameString . libName) sublib flip generate (libBuildInfo sublib) <$> maybeLib ) (subLibraries pkg) , fmap (\exe -> generate (CExe (T.pack (Cabal.unUnqualComponentName (exeName exe)))) (buildInfo exe)) (executables pkg) , fmap (\bench -> generate (CBench (T.pack (Cabal.unUnqualComponentName (benchmarkName bench)))) (benchmarkBuildInfo bench)) (benchmarks pkg) , fmap (\test -> generate (CTest (T.pack (Cabal.unUnqualComponentName (testName test)))) (testBuildInfo test)) (testSuites pkg)])) where cabalDir = parent cabalfp -- | Input to 'generateBuildInfoOpts' data BioInput = BioInput { biInstallMap :: !InstallMap , biInstalledMap :: !InstalledMap , biCabalDir :: !(Path Abs Dir) , biDistDir :: !(Path Abs Dir) , biOmitPackages :: ![PackageName] , biAddPackages :: ![PackageName] , biBuildInfo :: !BuildInfo , biDotCabalPaths :: ![DotCabalPath] , biConfigLibDirs :: ![FilePath] , biConfigIncludeDirs :: ![FilePath] , biComponentName :: !NamedComponent , biCabalVersion :: !Version } -- | Generate GHC options for the target. Since Cabal also figures out -- these options, currently this is only used for invoking GHCI (via -- stack ghci). generateBuildInfoOpts :: BioInput -> BuildInfoOpts generateBuildInfoOpts BioInput {..} = BuildInfoOpts { bioOpts = ghcOpts ++ cppOptions biBuildInfo -- NOTE for future changes: Due to this use of nubOrd (and other uses -- downstream), these generated options must not rely on multiple -- argument sequences. For example, ["--main-is", "Foo.hs", "--main- -- is", "Bar.hs"] would potentially break due to the duplicate -- "--main-is" being removed. -- -- See https://github.com/commercialhaskell/stack/issues/1255 , bioOneWordOpts = nubOrd $ concat [extOpts, srcOpts, includeOpts, libOpts, fworks, cObjectFiles] , bioPackageFlags = deps , bioCabalMacros = componentAutogen </> relFileCabalMacrosH } where cObjectFiles = mapMaybe (fmap toFilePath . makeObjectFilePathFromC biCabalDir biComponentName biDistDir) cfiles cfiles = mapMaybe dotCabalCFilePath biDotCabalPaths installVersion = snd -- Generates: -package=base -package=base16-bytestring-0.1.1.6 ... deps = concat [ case M.lookup name biInstalledMap of Just (_, Stack.Types.Package.Library _ident ipid _) -> ["-package-id=" <> ghcPkgIdString ipid] _ -> ["-package=" <> packageNameString name <> maybe "" -- This empty case applies to e.g. base. ((("-" <>) . versionString) . installVersion) (M.lookup name biInstallMap)] | name <- pkgs] pkgs = biAddPackages ++ [ name | Dependency name _ _ <- targetBuildDepends biBuildInfo -- TODO: cabal 3 introduced multiple public libraries in a single dependency , name `notElem` biOmitPackages] PerCompilerFlavor ghcOpts _ = options biBuildInfo extOpts = map (("-X" ++) . D.display) (usedExtensions biBuildInfo) srcOpts = map (("-i" <>) . toFilePathNoTrailingSep) (concat [ [ componentBuildDir biCabalVersion biComponentName biDistDir ] , [ biCabalDir | null (hsSourceDirs biBuildInfo) ] , mapMaybe toIncludeDir (hsSourceDirs biBuildInfo) , [ componentAutogen ] , maybeToList (packageAutogenDir biCabalVersion biDistDir) , [ componentOutputDir biComponentName biDistDir ] ]) ++ [ "-stubdir=" ++ toFilePathNoTrailingSep (buildDir biDistDir) ] componentAutogen = componentAutogenDir biCabalVersion biComponentName biDistDir toIncludeDir "." = Just biCabalDir toIncludeDir relDir = concatAndColapseAbsDir biCabalDir relDir includeOpts = map ("-I" <>) (biConfigIncludeDirs <> pkgIncludeOpts) pkgIncludeOpts = [ toFilePathNoTrailingSep absDir | dir <- includeDirs biBuildInfo , absDir <- handleDir dir ] libOpts = map ("-l" <>) (extraLibs biBuildInfo) <> map ("-L" <>) (biConfigLibDirs <> pkgLibDirs) pkgLibDirs = [ toFilePathNoTrailingSep absDir | dir <- extraLibDirs biBuildInfo , absDir <- handleDir dir ] handleDir dir = case (parseAbsDir dir, parseRelDir dir) of (Just ab, _ ) -> [ab] (_ , Just rel) -> [biCabalDir </> rel] (Nothing, Nothing ) -> [] fworks = map (\fwk -> "-framework=" <> fwk) (frameworks biBuildInfo) -- | Make the .o path from the .c file path for a component. Example: -- -- @ -- executable FOO -- c-sources: cbits/text_search.c -- @ -- -- Produces -- -- <dist-dir>/build/FOO/FOO-tmp/cbits/text_search.o -- -- Example: -- -- λ> makeObjectFilePathFromC -- $(mkAbsDir "/Users/chris/Repos/hoogle") -- CLib -- $(mkAbsDir "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist") -- $(mkAbsFile "/Users/chris/Repos/hoogle/cbits/text_search.c") -- Just "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist/build/cbits/text_search.o" -- λ> makeObjectFilePathFromC -- $(mkAbsDir "/Users/chris/Repos/hoogle") -- (CExe "hoogle") -- $(mkAbsDir "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist") -- $(mkAbsFile "/Users/chris/Repos/hoogle/cbits/text_search.c") -- Just "/Users/chris/Repos/hoogle/.stack-work/Cabal-x.x.x/dist/build/hoogle/hoogle-tmp/cbits/text_search.o" -- λ> makeObjectFilePathFromC :: MonadThrow m => Path Abs Dir -- ^ The cabal directory. -> NamedComponent -- ^ The name of the component. -> Path Abs Dir -- ^ Dist directory. -> Path Abs File -- ^ The path to the .c file. -> m (Path Abs File) -- ^ The path to the .o file for the component. makeObjectFilePathFromC cabalDir namedComponent distDir cFilePath = do relCFilePath <- stripProperPrefix cabalDir cFilePath relOFilePath <- parseRelFile (replaceExtension (toFilePath relCFilePath) "o") return (componentOutputDir namedComponent distDir </> relOFilePath) -- | Make the global autogen dir if Cabal version is new enough. packageAutogenDir :: Version -> Path Abs Dir -> Maybe (Path Abs Dir) packageAutogenDir cabalVer distDir | cabalVer < mkVersion [2, 0] = Nothing | otherwise = Just $ buildDir distDir </> relDirGlobalAutogen -- | Make the autogen dir. componentAutogenDir :: Version -> NamedComponent -> Path Abs Dir -> Path Abs Dir componentAutogenDir cabalVer component distDir = componentBuildDir cabalVer component distDir </> relDirAutogen -- | See 'Distribution.Simple.LocalBuildInfo.componentBuildDir' componentBuildDir :: Version -> NamedComponent -> Path Abs Dir -> Path Abs Dir componentBuildDir cabalVer component distDir | cabalVer < mkVersion [2, 0] = buildDir distDir | otherwise = case component of CLib -> buildDir distDir CInternalLib name -> buildDir distDir </> componentNameToDir name CExe name -> buildDir distDir </> componentNameToDir name CTest name -> buildDir distDir </> componentNameToDir name CBench name -> buildDir distDir </> componentNameToDir name -- | The directory where generated files are put like .o or .hs (from .x files). componentOutputDir :: NamedComponent -> Path Abs Dir -> Path Abs Dir componentOutputDir namedComponent distDir = case namedComponent of CLib -> buildDir distDir CInternalLib name -> makeTmp name CExe name -> makeTmp name CTest name -> makeTmp name CBench name -> makeTmp name where makeTmp name = buildDir distDir </> componentNameToDir (name <> "/" <> name <> "-tmp") -- | Make the build dir. Note that Cabal >= 2.0 uses the -- 'componentBuildDir' above for some things. buildDir :: Path Abs Dir -> Path Abs Dir buildDir distDir = distDir </> relDirBuild -- NOTE: don't export this, only use it for valid paths based on -- component names. componentNameToDir :: Text -> Path Rel Dir componentNameToDir name = fromMaybe (error "Invariant violated: component names should always parse as directory names") (parseRelDir (T.unpack name)) -- | Get all dependencies of the package (buildable targets only). -- -- Note that for Cabal versions 1.22 and earlier, there is a bug where -- Cabal requires dependencies for non-buildable components to be -- present. We're going to use GHC version as a proxy for Cabal -- library version in this case for simplicity, so we'll check for GHC -- being 7.10 or earlier. This obviously makes our function a lot more -- fun to write... packageDependencies :: PackageConfig -> PackageDescription -> Map PackageName VersionRange packageDependencies pkgConfig pkg' = M.fromListWith intersectVersionRanges $ map (depPkgName &&& depVerRange) $ concatMap targetBuildDepends (allBuildInfo' pkg) ++ maybe [] setupDepends (setupBuildInfo pkg) where pkg | getGhcVersion (packageConfigCompilerVersion pkgConfig) >= mkVersion [8, 0] = pkg' -- Set all components to buildable. Only need to worry about -- library, exe, test, and bench, since others didn't exist in -- older Cabal versions | otherwise = pkg' { library = (\c -> c { libBuildInfo = go (libBuildInfo c) }) <$> library pkg' , executables = (\c -> c { buildInfo = go (buildInfo c) }) <$> executables pkg' , testSuites = if packageConfigEnableTests pkgConfig then (\c -> c { testBuildInfo = go (testBuildInfo c) }) <$> testSuites pkg' else testSuites pkg' , benchmarks = if packageConfigEnableBenchmarks pkgConfig then (\c -> c { benchmarkBuildInfo = go (benchmarkBuildInfo c) }) <$> benchmarks pkg' else benchmarks pkg' } go bi = bi { buildable = True } -- | Get all dependencies of the package (buildable targets only). -- -- This uses both the new 'buildToolDepends' and old 'buildTools' -- information. packageDescTools :: PackageDescription -> (Set ExeName, Map PackageName DepValue) packageDescTools pd = (S.fromList $ concat unknowns, M.fromListWith (<>) $ concat knowns) where (unknowns, knowns) = unzip $ map perBI $ allBuildInfo' pd perBI :: BuildInfo -> ([ExeName], [(PackageName, DepValue)]) perBI bi = (unknownTools, tools) where (unknownTools, knownTools) = partitionEithers $ map go1 (buildTools bi) tools = mapMaybe go2 (knownTools ++ buildToolDepends bi) -- This is similar to desugarBuildTool from Cabal, however it -- uses our own hard-coded map which drops tools shipped with -- GHC (like hsc2hs), and includes some tools from Stackage. go1 :: Cabal.LegacyExeDependency -> Either ExeName Cabal.ExeDependency go1 (Cabal.LegacyExeDependency name range) = case M.lookup name hardCodedMap of Just pkgName -> Right $ Cabal.ExeDependency pkgName (Cabal.mkUnqualComponentName name) range Nothing -> Left $ ExeName $ T.pack name go2 :: Cabal.ExeDependency -> Maybe (PackageName, DepValue) go2 (Cabal.ExeDependency pkg _name range) | pkg `S.member` preInstalledPackages = Nothing | otherwise = Just ( pkg , DepValue { dvVersionRange = range , dvType = AsBuildTool } ) -- | A hard-coded map for tool dependencies hardCodedMap :: Map String D.PackageName hardCodedMap = M.fromList [ ("alex", Distribution.Package.mkPackageName "alex") , ("happy", Distribution.Package.mkPackageName "happy") , ("cpphs", Distribution.Package.mkPackageName "cpphs") , ("greencard", Distribution.Package.mkPackageName "greencard") , ("c2hs", Distribution.Package.mkPackageName "c2hs") , ("hscolour", Distribution.Package.mkPackageName "hscolour") , ("hspec-discover", Distribution.Package.mkPackageName "hspec-discover") , ("hsx2hs", Distribution.Package.mkPackageName "hsx2hs") , ("gtk2hsC2hs", Distribution.Package.mkPackageName "gtk2hs-buildtools") , ("gtk2hsHookGenerator", Distribution.Package.mkPackageName "gtk2hs-buildtools") , ("gtk2hsTypeGen", Distribution.Package.mkPackageName "gtk2hs-buildtools") ] -- | Executable-only packages which come pre-installed with GHC and do -- not need to be built. Without this exception, we would either end -- up unnecessarily rebuilding these packages, or failing because the -- packages do not appear in the Stackage snapshot. preInstalledPackages :: Set D.PackageName preInstalledPackages = S.fromList [ D.mkPackageName "hsc2hs" , D.mkPackageName "haddock" ] -- | Variant of 'allBuildInfo' from Cabal that, like versions before -- 2.2, only includes buildable components. allBuildInfo' :: PackageDescription -> [BuildInfo] allBuildInfo' pkg_descr = [ bi | lib <- allLibraries pkg_descr , let bi = libBuildInfo lib , buildable bi ] ++ [ bi | flib <- foreignLibs pkg_descr , let bi = foreignLibBuildInfo flib , buildable bi ] ++ [ bi | exe <- executables pkg_descr , let bi = buildInfo exe , buildable bi ] ++ [ bi | tst <- testSuites pkg_descr , let bi = testBuildInfo tst , buildable bi ] ++ [ bi | tst <- benchmarks pkg_descr , let bi = benchmarkBuildInfo tst , buildable bi ] -- | Get all files referenced by the package. packageDescModulesAndFiles :: PackageDescription -> RIO Ctx (Map NamedComponent (Map ModuleName (Path Abs File)), Map NamedComponent [DotCabalPath], Set (Path Abs File), [PackageWarning]) packageDescModulesAndFiles pkg = do (libraryMods,libDotCabalFiles,libWarnings) <- maybe (return (M.empty, M.empty, [])) (asModuleAndFileMap libComponent libraryFiles) (library pkg) (subLibrariesMods,subLibDotCabalFiles,subLibWarnings) <- liftM foldTuples (mapM (asModuleAndFileMap internalLibComponent libraryFiles) (subLibraries pkg)) (executableMods,exeDotCabalFiles,exeWarnings) <- liftM foldTuples (mapM (asModuleAndFileMap exeComponent executableFiles) (executables pkg)) (testMods,testDotCabalFiles,testWarnings) <- liftM foldTuples (mapM (asModuleAndFileMap testComponent testFiles) (testSuites pkg)) (benchModules,benchDotCabalPaths,benchWarnings) <- liftM foldTuples (mapM (asModuleAndFileMap benchComponent benchmarkFiles) (benchmarks pkg)) dfiles <- resolveGlobFiles (specVersion pkg) (extraSrcFiles pkg ++ map (dataDir pkg FilePath.</>) (dataFiles pkg)) let modules = libraryMods <> subLibrariesMods <> executableMods <> testMods <> benchModules files = libDotCabalFiles <> subLibDotCabalFiles <> exeDotCabalFiles <> testDotCabalFiles <> benchDotCabalPaths warnings = libWarnings <> subLibWarnings <> exeWarnings <> testWarnings <> benchWarnings return (modules, files, dfiles, warnings) where libComponent = const CLib internalLibComponent = CInternalLib . T.pack . maybe "" Cabal.unUnqualComponentName . libraryNameString . libName exeComponent = CExe . T.pack . Cabal.unUnqualComponentName . exeName testComponent = CTest . T.pack . Cabal.unUnqualComponentName . testName benchComponent = CBench . T.pack . Cabal.unUnqualComponentName . benchmarkName asModuleAndFileMap label f lib = do (a,b,c) <- f (label lib) lib return (M.singleton (label lib) a, M.singleton (label lib) b, c) foldTuples = foldl' (<>) (M.empty, M.empty, []) -- | Resolve globbing of files (e.g. data files) to absolute paths. resolveGlobFiles :: Version -- ^ cabal file version -> [String] -> RIO Ctx (Set (Path Abs File)) resolveGlobFiles cabalFileVersion = liftM (S.fromList . catMaybes . concat) . mapM resolve where resolve name = if '*' `elem` name then explode name else liftM return (resolveFileOrWarn name) explode name = do dir <- asks (parent . ctxFile) names <- matchDirFileGlob' (FL.toFilePath dir) name mapM resolveFileOrWarn names matchDirFileGlob' dir glob = catch (liftIO (matchDirFileGlob minBound cabalFileVersion dir glob)) (\(e :: IOException) -> if isUserError e then do prettyWarnL [ flow "Wildcard does not match any files:" , style File $ fromString glob , line <> flow "in directory:" , style Dir $ fromString dir ] return [] else throwIO e) -- | Get all files referenced by the benchmark. benchmarkFiles :: NamedComponent -> Benchmark -> RIO Ctx (Map ModuleName (Path Abs File), [DotCabalPath], [PackageWarning]) benchmarkFiles component bench = do resolveComponentFiles component build names where names = bnames <> exposed exposed = case benchmarkInterface bench of BenchmarkExeV10 _ fp -> [DotCabalMain fp] BenchmarkUnsupported _ -> [] bnames = map DotCabalModule (otherModules build) build = benchmarkBuildInfo bench -- | Get all files referenced by the test. testFiles :: NamedComponent -> TestSuite -> RIO Ctx (Map ModuleName (Path Abs File), [DotCabalPath], [PackageWarning]) testFiles component test = do resolveComponentFiles component build names where names = bnames <> exposed exposed = case testInterface test of TestSuiteExeV10 _ fp -> [DotCabalMain fp] TestSuiteLibV09 _ mn -> [DotCabalModule mn] TestSuiteUnsupported _ -> [] bnames = map DotCabalModule (otherModules build) build = testBuildInfo test -- | Get all files referenced by the executable. executableFiles :: NamedComponent -> Executable -> RIO Ctx (Map ModuleName (Path Abs File), [DotCabalPath], [PackageWarning]) executableFiles component exe = do resolveComponentFiles component build names where build = buildInfo exe names = map DotCabalModule (otherModules build) ++ [DotCabalMain (modulePath exe)] -- | Get all files referenced by the library. libraryFiles :: NamedComponent -> Library -> RIO Ctx (Map ModuleName (Path Abs File), [DotCabalPath], [PackageWarning]) libraryFiles component lib = do resolveComponentFiles component build names where build = libBuildInfo lib names = bnames ++ exposed exposed = map DotCabalModule (exposedModules lib) bnames = map DotCabalModule (otherModules build) -- | Get all files referenced by the component. resolveComponentFiles :: NamedComponent -> BuildInfo -> [DotCabalDescriptor] -> RIO Ctx (Map ModuleName (Path Abs File), [DotCabalPath], [PackageWarning]) resolveComponentFiles component build names = do dirs <- mapMaybeM resolveDirOrWarn (hsSourceDirs build) dir <- asks (parent . ctxFile) agdirs <- autogenDirs (modules,files,warnings) <- resolveFilesAndDeps component ((if null dirs then [dir] else dirs) ++ agdirs) names cfiles <- buildOtherSources build return (modules, files <> cfiles, warnings) where autogenDirs = do cabalVer <- asks ctxCabalVer distDir <- asks ctxDistDir let compDir = componentAutogenDir cabalVer component distDir pkgDir = maybeToList $ packageAutogenDir cabalVer distDir filterM doesDirExist $ compDir : pkgDir -- | Get all C sources and extra source files in a build. buildOtherSources :: BuildInfo -> RIO Ctx [DotCabalPath] buildOtherSources build = do cwd <- liftIO getCurrentDir dir <- asks (parent . ctxFile) file <- asks ctxFile let resolveDirFiles files toCabalPath = forMaybeM files $ \fp -> do result <- resolveDirFile dir fp case result of Nothing -> do warnMissingFile "File" cwd fp file return Nothing Just p -> return $ Just (toCabalPath p) csources <- resolveDirFiles (cSources build) DotCabalCFilePath jsources <- resolveDirFiles (targetJsSources build) DotCabalFilePath return (csources <> jsources) -- | Get the target's JS sources. targetJsSources :: BuildInfo -> [FilePath] targetJsSources = jsSources -- | A pair of package descriptions: one which modified the buildable -- values of test suites and benchmarks depending on whether they are -- enabled, and one which does not. -- -- Fields are intentionally lazy, we may only need one or the other -- value. -- -- MSS 2017-08-29: The very presence of this data type is terribly -- ugly, it represents the fact that the Cabal 2.0 upgrade did _not_ -- go well. Specifically, we used to have a field to indicate whether -- a component was enabled in addition to buildable, but that's gone -- now, and this is an ugly proxy. We should at some point clean up -- the mess of Package, LocalPackage, etc, and probably pull in the -- definition of PackageDescription from Cabal with our additionally -- needed metadata. But this is a good enough hack for the -- moment. Odds are, you're reading this in the year 2024 and thinking -- "wtf?" data PackageDescriptionPair = PackageDescriptionPair { pdpOrigBuildable :: PackageDescription , pdpModifiedBuildable :: PackageDescription } -- | Evaluates the conditions of a 'GenericPackageDescription', yielding -- a resolved 'PackageDescription'. resolvePackageDescription :: PackageConfig -> GenericPackageDescription -> PackageDescriptionPair resolvePackageDescription packageConfig (GenericPackageDescription desc defaultFlags mlib subLibs foreignLibs' exes tests benches) = PackageDescriptionPair { pdpOrigBuildable = go False , pdpModifiedBuildable = go True } where go modBuildable = desc {library = fmap (resolveConditions rc updateLibDeps) mlib ,subLibraries = map (\(n, v) -> (resolveConditions rc updateLibDeps v){libName=LSubLibName n}) subLibs ,foreignLibs = map (\(n, v) -> (resolveConditions rc updateForeignLibDeps v){foreignLibName=n}) foreignLibs' ,executables = map (\(n, v) -> (resolveConditions rc updateExeDeps v){exeName=n}) exes ,testSuites = map (\(n,v) -> (resolveConditions rc (updateTestDeps modBuildable) v){testName=n}) tests ,benchmarks = map (\(n,v) -> (resolveConditions rc (updateBenchmarkDeps modBuildable) v){benchmarkName=n}) benches} flags = M.union (packageConfigFlags packageConfig) (flagMap defaultFlags) rc = mkResolveConditions (packageConfigCompilerVersion packageConfig) (packageConfigPlatform packageConfig) flags updateLibDeps lib deps = lib {libBuildInfo = (libBuildInfo lib) {targetBuildDepends = deps}} updateForeignLibDeps lib deps = lib {foreignLibBuildInfo = (foreignLibBuildInfo lib) {targetBuildDepends = deps}} updateExeDeps exe deps = exe {buildInfo = (buildInfo exe) {targetBuildDepends = deps}} -- Note that, prior to moving to Cabal 2.0, we would set -- testEnabled/benchmarkEnabled here. These fields no longer -- exist, so we modify buildable instead here. The only -- wrinkle in the Cabal 2.0 story is -- https://github.com/haskell/cabal/issues/1725, where older -- versions of Cabal (which may be used for actually building -- code) don't properly exclude build-depends for -- non-buildable components. Testing indicates that everything -- is working fine, and that this comment can be completely -- ignored. I'm leaving the comment anyway in case something -- breaks and you, poor reader, are investigating. updateTestDeps modBuildable test deps = let bi = testBuildInfo test bi' = bi { targetBuildDepends = deps , buildable = buildable bi && (if modBuildable then packageConfigEnableTests packageConfig else True) } in test { testBuildInfo = bi' } updateBenchmarkDeps modBuildable benchmark deps = let bi = benchmarkBuildInfo benchmark bi' = bi { targetBuildDepends = deps , buildable = buildable bi && (if modBuildable then packageConfigEnableBenchmarks packageConfig else True) } in benchmark { benchmarkBuildInfo = bi' } -- | Make a map from a list of flag specifications. -- -- What is @flagManual@ for? flagMap :: [Flag] -> Map FlagName Bool flagMap = M.fromList . map pair where pair :: Flag -> (FlagName, Bool) pair = flagName &&& flagDefault data ResolveConditions = ResolveConditions { rcFlags :: Map FlagName Bool , rcCompilerVersion :: ActualCompiler , rcOS :: OS , rcArch :: Arch } -- | Generic a @ResolveConditions@ using sensible defaults. mkResolveConditions :: ActualCompiler -- ^ Compiler version -> Platform -- ^ installation target platform -> Map FlagName Bool -- ^ enabled flags -> ResolveConditions mkResolveConditions compilerVersion (Platform arch os) flags = ResolveConditions { rcFlags = flags , rcCompilerVersion = compilerVersion , rcOS = os , rcArch = arch } -- | Resolve the condition tree for the library. resolveConditions :: (Semigroup target,Monoid target,Show target) => ResolveConditions -> (target -> cs -> target) -> CondTree ConfVar cs target -> target resolveConditions rc addDeps (CondNode lib deps cs) = basic <> children where basic = addDeps lib deps children = mconcat (map apply cs) where apply (Cabal.CondBranch cond node mcs) = if condSatisfied cond then resolveConditions rc addDeps node else maybe mempty (resolveConditions rc addDeps) mcs condSatisfied c = case c of Var v -> varSatisifed v Lit b -> b CNot c' -> not (condSatisfied c') COr cx cy -> condSatisfied cx || condSatisfied cy CAnd cx cy -> condSatisfied cx && condSatisfied cy varSatisifed v = case v of OS os -> os == rcOS rc Arch arch -> arch == rcArch rc Flag flag -> fromMaybe False $ M.lookup flag (rcFlags rc) -- NOTE: ^^^^^ This should never happen, as all flags -- which are used must be declared. Defaulting to -- False. Impl flavor range -> case (flavor, rcCompilerVersion rc) of (GHC, ACGhc vghc) -> vghc `withinRange` range _ -> False -- | Try to resolve the list of base names in the given directory by -- looking for unique instances of base names applied with the given -- extensions, plus find any of their module and TemplateHaskell -- dependencies. resolveFilesAndDeps :: NamedComponent -- ^ Package component name -> [Path Abs Dir] -- ^ Directories to look in. -> [DotCabalDescriptor] -- ^ Base names. -> RIO Ctx (Map ModuleName (Path Abs File),[DotCabalPath],[PackageWarning]) resolveFilesAndDeps component dirs names0 = do (dotCabalPaths, foundModules, missingModules) <- loop names0 S.empty warnings <- liftM2 (++) (warnUnlisted foundModules) (warnMissing missingModules) return (foundModules, dotCabalPaths, warnings) where loop [] _ = return ([], M.empty, []) loop names doneModules0 = do resolved <- resolveFiles dirs names let foundFiles = mapMaybe snd resolved foundModules = mapMaybe toResolvedModule resolved missingModules = mapMaybe toMissingModule resolved pairs <- mapM (getDependencies component dirs) foundFiles let doneModules = S.union doneModules0 (S.fromList (mapMaybe dotCabalModule names)) moduleDeps = S.unions (map fst pairs) thDepFiles = concatMap snd pairs modulesRemaining = S.difference moduleDeps doneModules -- Ignore missing modules discovered as dependencies - they may -- have been deleted. (resolvedFiles, resolvedModules, _) <- loop (map DotCabalModule (S.toList modulesRemaining)) doneModules return ( nubOrd $ foundFiles <> map DotCabalFilePath thDepFiles <> resolvedFiles , M.union (M.fromList foundModules) resolvedModules , missingModules) warnUnlisted foundModules = do let unlistedModules = foundModules `M.difference` M.fromList (mapMaybe (fmap (, ()) . dotCabalModule) names0) return $ if M.null unlistedModules then [] else [ UnlistedModulesWarning component (map fst (M.toList unlistedModules))] warnMissing _missingModules = do return [] -- TODO: bring this back - see -- https://github.com/commercialhaskell/stack/issues/2649 {- cabalfp <- asks ctxFile return $ if null missingModules then [] else [ MissingModulesWarning cabalfp component missingModules] -} -- TODO: In usages of toResolvedModule / toMissingModule, some sort -- of map + partition would probably be better. toResolvedModule :: (DotCabalDescriptor, Maybe DotCabalPath) -> Maybe (ModuleName, Path Abs File) toResolvedModule (DotCabalModule mn, Just (DotCabalModulePath fp)) = Just (mn, fp) toResolvedModule _ = Nothing toMissingModule :: (DotCabalDescriptor, Maybe DotCabalPath) -> Maybe ModuleName toMissingModule (DotCabalModule mn, Nothing) = Just mn toMissingModule _ = Nothing -- | Get the dependencies of a Haskell module file. getDependencies :: NamedComponent -> [Path Abs Dir] -> DotCabalPath -> RIO Ctx (Set ModuleName, [Path Abs File]) getDependencies component dirs dotCabalPath = case dotCabalPath of DotCabalModulePath resolvedFile -> readResolvedHi resolvedFile DotCabalMainPath resolvedFile -> readResolvedHi resolvedFile DotCabalFilePath{} -> return (S.empty, []) DotCabalCFilePath{} -> return (S.empty, []) where readResolvedHi resolvedFile = do dumpHIDir <- componentOutputDir component <$> asks ctxDistDir dir <- asks (parent . ctxFile) let sourceDir = fromMaybe dir $ find (`isProperPrefixOf` resolvedFile) dirs stripSourceDir d = stripProperPrefix d resolvedFile case stripSourceDir sourceDir of Nothing -> return (S.empty, []) Just fileRel -> do let hiPath = FilePath.replaceExtension (toFilePath (dumpHIDir </> fileRel)) ".hi" dumpHIExists <- liftIO $ D.doesFileExist hiPath if dumpHIExists then parseHI hiPath else return (S.empty, []) -- | Parse a .hi file into a set of modules and files. parseHI :: FilePath -> RIO Ctx (Set ModuleName, [Path Abs File]) parseHI hiPath = do dir <- asks (parent . ctxFile) result <- liftIO $ Iface.fromFile hiPath case result of Left msg -> do prettyStackDevL [ flow "Failed to decode module interface:" , style File $ fromString hiPath , flow "Decoding failure:" , style Error $ fromString msg ] pure (S.empty, []) Right iface -> do let moduleNames = fmap (fromString . T.unpack . decodeUtf8Lenient . fst) . Iface.unList . Iface.dmods . Iface.deps resolveFileDependency file = do resolved <- liftIO (forgivingAbsence (resolveFile dir file)) >>= rejectMissingFile when (isNothing resolved) $ prettyWarnL [ flow "Dependent file listed in:" , style File $ fromString hiPath , flow "does not exist:" , style File $ fromString file ] pure resolved resolveUsages = traverse (resolveFileDependency . Iface.unUsage) . Iface.unList . Iface.usage resolvedUsages <- catMaybes <$> resolveUsages iface pure (S.fromList $ moduleNames iface, resolvedUsages) -- | Try to resolve the list of base names in the given directory by -- looking for unique instances of base names applied with the given -- extensions. resolveFiles :: [Path Abs Dir] -- ^ Directories to look in. -> [DotCabalDescriptor] -- ^ Base names. -> RIO Ctx [(DotCabalDescriptor, Maybe DotCabalPath)] resolveFiles dirs names = forM names (\name -> liftM (name, ) (findCandidate dirs name)) data CabalFileNameParseFail = CabalFileNameParseFail FilePath | CabalFileNameInvalidPackageName FilePath deriving (Typeable) instance Exception CabalFileNameParseFail instance Show CabalFileNameParseFail where show (CabalFileNameParseFail fp) = "Invalid file path for cabal file, must have a .cabal extension: " ++ fp show (CabalFileNameInvalidPackageName fp) = "cabal file names must use valid package names followed by a .cabal extension, the following is invalid: " ++ fp -- | Parse a package name from a file path. parsePackageNameFromFilePath :: MonadThrow m => Path a File -> m PackageName parsePackageNameFromFilePath fp = do base <- clean $ toFilePath $ filename fp case parsePackageName base of Nothing -> throwM $ CabalFileNameInvalidPackageName $ toFilePath fp Just x -> return x where clean = liftM reverse . strip . reverse strip ('l':'a':'b':'a':'c':'.':xs) = return xs strip _ = throwM (CabalFileNameParseFail (toFilePath fp)) -- | Find a candidate for the given module-or-filename from the list -- of directories and given extensions. findCandidate :: [Path Abs Dir] -> DotCabalDescriptor -> RIO Ctx (Maybe DotCabalPath) findCandidate dirs name = do pkg <- asks ctxFile >>= parsePackageNameFromFilePath candidates <- liftIO makeNameCandidates case candidates of [candidate] -> return (Just (cons candidate)) [] -> do case name of DotCabalModule mn | D.display mn /= paths_pkg pkg -> logPossibilities dirs mn _ -> return () return Nothing (candidate:rest) -> do warnMultiple name candidate rest return (Just (cons candidate)) where cons = case name of DotCabalModule{} -> DotCabalModulePath DotCabalMain{} -> DotCabalMainPath DotCabalFile{} -> DotCabalFilePath DotCabalCFile{} -> DotCabalCFilePath paths_pkg pkg = "Paths_" ++ packageNameString pkg makeNameCandidates = liftM (nubOrd . concat) (mapM makeDirCandidates dirs) makeDirCandidates :: Path Abs Dir -> IO [Path Abs File] makeDirCandidates dir = case name of DotCabalMain fp -> resolveCandidate dir fp DotCabalFile fp -> resolveCandidate dir fp DotCabalCFile fp -> resolveCandidate dir fp DotCabalModule mn -> do let perExt ext = resolveCandidate dir (Cabal.toFilePath mn ++ "." ++ T.unpack ext) withHaskellExts <- mapM perExt haskellFileExts withPPExts <- mapM perExt haskellPreprocessorExts pure $ case (concat withHaskellExts, concat withPPExts) of -- If we have exactly 1 Haskell extension and exactly -- 1 preprocessor extension, assume the former file is -- generated from the latter -- -- See https://github.com/commercialhaskell/stack/issues/4076 ([_], [y]) -> [y] -- Otherwise, return everything (xs, ys) -> xs ++ ys resolveCandidate dir = fmap maybeToList . resolveDirFile dir -- | Resolve file as a child of a specified directory, symlinks -- don't get followed. resolveDirFile :: (MonadIO m, MonadThrow m) => Path Abs Dir -> FilePath.FilePath -> m (Maybe (Path Abs File)) resolveDirFile x y = do -- The standard canonicalizePath does not work for this case p <- parseCollapsedAbsFile (toFilePath x FilePath.</> y) exists <- doesFileExist p return $ if exists then Just p else Nothing -- | Warn the user that multiple candidates are available for an -- entry, but that we picked one anyway and continued. warnMultiple :: DotCabalDescriptor -> Path b t -> [Path b t] -> RIO Ctx () warnMultiple name candidate rest = -- TODO: figure out how to style 'name' and the dispOne stuff prettyWarnL [ flow "There were multiple candidates for the Cabal entry" , fromString . showName $ name , line <> bulletedList (map dispOne (candidate:rest)) , line <> flow "picking:" , dispOne candidate ] where showName (DotCabalModule name') = D.display name' showName (DotCabalMain fp) = fp showName (DotCabalFile fp) = fp showName (DotCabalCFile fp) = fp dispOne = fromString . toFilePath -- TODO: figure out why dispOne can't be just `display` -- (remove the .hlint.yaml exception if it can be) -- | Log that we couldn't find a candidate, but there are -- possibilities for custom preprocessor extensions. -- -- For example: .erb for a Ruby file might exist in one of the -- directories. logPossibilities :: HasTerm env => [Path Abs Dir] -> ModuleName -> RIO env () logPossibilities dirs mn = do possibilities <- liftM concat (makePossibilities mn) unless (null possibilities) $ prettyWarnL [ flow "Unable to find a known candidate for the Cabal entry" , (style PP.Module . fromString $ D.display mn) <> "," , flow "but did find:" , line <> bulletedList (map pretty possibilities) , flow "If you are using a custom preprocessor for this module" , flow "with its own file extension, consider adding the file(s)" , flow "to your .cabal under extra-source-files." ] where makePossibilities name = mapM (\dir -> do (_,files) <- listDir dir return (map filename (filter (isPrefixOf (D.display name) . toFilePath . filename) files))) dirs -- | Path for the package's build log. buildLogPath :: (MonadReader env m, HasBuildConfig env, MonadThrow m) => Package -> Maybe String -> m (Path Abs File) buildLogPath package' msuffix = do env <- ask let stack = getProjectWorkDir env fp <- parseRelFile $ concat $ packageIdentifierString (packageIdentifier package') : maybe id (\suffix -> ("-" :) . (suffix :)) msuffix [".log"] return $ stack </> relDirLogs </> fp -- Internal helper to define resolveFileOrWarn and resolveDirOrWarn resolveOrWarn :: Text -> (Path Abs Dir -> String -> RIO Ctx (Maybe a)) -> FilePath.FilePath -> RIO Ctx (Maybe a) resolveOrWarn subject resolver path = do cwd <- liftIO getCurrentDir file <- asks ctxFile dir <- asks (parent . ctxFile) result <- resolver dir path when (isNothing result) $ warnMissingFile subject cwd path file return result warnMissingFile :: Text -> Path Abs Dir -> FilePath -> Path Abs File -> RIO Ctx () warnMissingFile subject cwd path fromFile = prettyWarnL [ fromString . T.unpack $ subject -- TODO: needs style? , flow "listed in" , maybe (pretty fromFile) pretty (stripProperPrefix cwd fromFile) , flow "file does not exist:" , style Dir . fromString $ path ] -- | Resolve the file, if it can't be resolved, warn for the user -- (purely to be helpful). resolveFileOrWarn :: FilePath.FilePath -> RIO Ctx (Maybe (Path Abs File)) resolveFileOrWarn = resolveOrWarn "File" f where f p x = liftIO (forgivingAbsence (resolveFile p x)) >>= rejectMissingFile -- | Resolve the directory, if it can't be resolved, warn for the user -- (purely to be helpful). resolveDirOrWarn :: FilePath.FilePath -> RIO Ctx (Maybe (Path Abs Dir)) resolveDirOrWarn = resolveOrWarn "Directory" f where f p x = liftIO (forgivingAbsence (resolveDir p x)) >>= rejectMissingDir {- FIXME -- | Create a 'ProjectPackage' from a directory containing a package. mkProjectPackage :: forall env. (HasPantryConfig env, HasLogFunc env, HasProcessContext env) => PrintWarnings -> ResolvedPath Dir -> RIO env ProjectPackage mkProjectPackage printWarnings dir = do (gpd, name, cabalfp) <- loadCabalFilePath (resolvedAbsolute dir) return ProjectPackage { ppCabalFP = cabalfp , ppGPD' = gpd printWarnings , ppResolvedDir = dir , ppName = name } -- | Create a 'DepPackage' from a 'PackageLocation' mkDepPackage :: forall env. (HasPantryConfig env, HasLogFunc env, HasProcessContext env) => PackageLocation -> RIO env DepPackage mkDepPackage pl = do (name, gpdio) <- case pl of PLMutable dir -> do (gpdio, name, _cabalfp) <- loadCabalFilePath (resolvedAbsolute dir) pure (name, gpdio NoPrintWarnings) PLImmutable pli -> do PackageIdentifier name _ <- getPackageLocationIdent pli run <- askRunInIO pure (name, run $ loadCabalFileImmutable pli) return DepPackage { dpGPD' = gpdio , dpLocation = pl , dpName = name } -} -- | Force a package to be treated as a custom build type, see -- <https://github.com/commercialhaskell/stack/issues/4488> applyForceCustomBuild :: Version -- ^ global Cabal version -> Package -> Package applyForceCustomBuild cabalVersion package | forceCustomBuild = package { packageBuildType = Custom , packageDeps = M.insertWith (<>) "Cabal" (DepValue cabalVersionRange AsLibrary) $ packageDeps package , packageSetupDeps = Just $ M.fromList [ ("Cabal", cabalVersionRange) , ("base", anyVersion) ] } | otherwise = package where cabalVersionRange = packageCabalSpec package forceCustomBuild = packageBuildType package == Simple && not (cabalVersion `withinRange` cabalVersionRange)
juhp/stack
src/Stack/Package.hs
bsd-3-clause
58,234
0
24
17,132
12,043
6,276
5,767
1,060
11
{-# OPTIONS #-} ----------------------------------------------------------------------------- -- | -- Module : Language.Py.Lexer -- Copyright : (c) 2009 Bernie Pope -- License : BSD-style -- Maintainer : bjpop@csse.unimelb.edu.au -- Stability : experimental -- Portability : ghc -- -- Lexical analysis for Python version 2.x and 3.x programs. ----------------------------------------------------------------------------- module Language.Py.Lexer -- * Lexical analysis ( lex , lexOneToken ) where import Prelude hiding (lex) import Language.Py.Parser.Lexer (lexToken, initStartCodeStack) import Language.Py.Token as Token import Language.Py.SrcLocation (initialSrcLocation) import Language.Py.ParserMonad ( ParseState (input) , P , runParser , execParser , ParseError , initialState ) initLexState :: String -> String -> ParseState initLexState input srcName = initialState (initialSrcLocation srcName) input initStartCodeStack -- | Parse a string into a list of Python Tokens, or return an error. lex :: String -- ^ The input stream (python source code). -> String -- ^ The name of the python source (filename or input device). -> Either ParseError [Token] -- ^ An error or a list of tokens. lex input srcName = execParser lexer $ initLexState input srcName -- | Try to lex the first token in an input string. Return either a parse error -- or a pair containing the next token and the rest of the input after the token. lexOneToken :: String -- ^ The input stream (python source code). -> String -- ^ The name of the python source (filename or input device). -> Either ParseError (Token, String) -- ^ An error or the next token and the rest of the input after the token. lexOneToken source srcName = case runParser lexToken state of Left err -> Left err Right (tok, state) -> Right (tok, input state) where state = initLexState source srcName lexer :: P [Token] lexer = loop [] where loop toks = do tok <- lexToken case tok of EOFToken {} -> return (reverse toks) other -> loop (tok:toks)
codeq/language-py
src/Language/Py/Lexer.hs
bsd-3-clause
2,106
0
14
422
363
206
157
37
2
{-# LANGUAGE DeriveDataTypeable #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Types.Cron ( Cron(..) ) where import Data.Binary (Binary, get, getWord8, put, putWord8) import Data.Typeable (Typeable) import System.Cron newtype Cron = Cron CronSchedule deriving (Show, Eq, Typeable) instance Ord Cron where compare x y = show x `compare` show y instance Binary CronField where {-# INLINE put #-} put (Star) = putWord8 0 put (SpecificField x) = putWord8 1 >> put x put (RangeField x y) = putWord8 2 >> put x >> put y put (ListField x) = putWord8 3 >> put x put (StepField x y) = putWord8 4 >> put x >> put y {-# INLINE get #-} get = do x <- getWord8 case x of 0 -> return Star 1 -> SpecificField <$> get 2 -> RangeField <$> get <*> get 3 -> ListField <$> get 4 -> StepField <$> get <*> get _ -> fail "bad binary" instance Binary Cron where {-# INLINE put #-} put (Cron (CronSchedule (Minutes a) (Hours b) (DaysOfMonth c) (Months d) (DaysOfWeek e))) = put a >> put b >> put c >> put d >> put e {-# INLINE get #-} get = do a <- get b <- get c <- get d <- get e <- get return $! Cron (CronSchedule (Minutes a) (Hours b) (DaysOfMonth c) (Months d) (DaysOfWeek e))
chemist/fixmon
src/Types/Cron.hs
bsd-3-clause
1,419
0
13
483
523
261
262
37
0
{-# LANGUAGE FlexibleContexts,FlexibleInstances,KindSignatures,DeriveDataTypeable #-} {- | Implements the fixpoint construction for data types. Allows non-recursive data types to be made into recursive ones. -} module Data.Fix where import Data.Binary -- | A fixpoint data structure. -- Allows the construction of infinite data types from finite constructors. data Fix f = Fix { unfix :: f (Fix f) } -- | A helper class to allow the fixpoint of a data-type to be an instance of the 'Binary' class. class Binary2 (a :: * -> *) where get2 :: Binary b => Get (a b) put2 :: Binary b => a b -> Put instance Binary2 a => Binary (Fix a) where get = fmap Fix get2 put = put2 . unfix -- | A helper class to allow the fixpoint of a data-type to be an instance of the 'Eq' class. class Eq2 (a :: * -> *) where eq2 :: Eq b => a b -> a b -> Bool instance Eq2 a => Eq (Fix a) where x == y = eq2 (unfix x) (unfix y) -- | A helper class to allow the fixpoint of a data-type to be an instance of the 'Show' class. class Show2 (a :: * -> *) where showsPrec2 :: Show b => Int -> a b -> ShowS showsPrec2 _ x str = show2 x ++ str show2 :: Show b => a b -> String show2 x = showsPrec2 0 x "" instance Show2 a => Show (Fix a) where show x = show2 (unfix x) -- | A helper class to allow the fixpoint of a data-type to be an instance of the 'Ord' class. class Eq2 a => Ord2 (a :: * -> *) where compare2 :: Ord b => a b -> a b -> Ordering instance Ord2 a => Ord (Fix a) where compare x y = compare2 (unfix x) (unfix y) --instance (Binary (a b)) => Binary (Fix a) where -- get = undefined
hguenther/gtl
lib/Data/Fix.hs
bsd-3-clause
1,607
0
11
374
472
237
235
25
0
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Applicative import Control.Exception import Control.Monad import Data.Binary import Data.ByteString.Lazy (readFile, writeFile) import Data.ByteString.UTF8 (fromString, toString) import Data.DAWG.Static import Data.Monoid import Data.Text (Text, pack, unpack) import qualified Data.Text as T import Data.Vector (map) import qualified Data.Vector as V import Prelude hiding (lookup, map, readFile) import qualified Prelude as P import Control.Monad.IO.Class (liftIO) import Data import Data.Maybe import Data.Text.Encoding (decodeUtf8) import Grammem import Snap.Core import Snap.Http.Server import Snap.Util.FileServe (serveDirectory, serveFile) import qualified Text.Blaze.Html.Renderer.Text as H import qualified Text.Blaze.Html5 as H import Text.Blaze.Html5 ((!)) import qualified Text.Blaze.Html5.Attributes as A initMorph :: IO Morph initMorph = decode <$> readFile dawgDict main :: IO () main = do m <- initMorph web m getAllForm :: Morph -> Text -> V.Vector Text getAllForm m s = case lookup (unpack s) (dict m) of Nothing -> throw $ ErrorCall "unknown word" Just x -> map (showParadigm (tags m) s) $ map (form m) x where form (Morph t p _) i = p V.! i getAllForm' :: Morph -> Text -> H.Html getAllForm' m s = case lookup (unpack . T.toUpper $ s) (dict m) of Nothing -> H.div ! A.class_ "input" ! A.id "input" $ "Незнакомое слово" Just x -> showP (tags m) (T.toUpper s) $ map (form m) x where form (Morph t p _) i = p V.! i showP :: Tegs -> Text -> V.Vector TParadigm -> H.Html showP tegs s vtp = tabs tegs s $ V.toList vtp tabs :: Tegs -> Text -> [TParadigm] -> H.Html tabs tegs s xs = do let contentByPosition = zip [1 .. ] xs H.section ! A.class_ "tabs" $ do nnInput $ P.map (nInput . fst) contentByPosition nnLabel contentByPosition H.div ! A.style "clear:both" $ "" H.div ! A.class_ "tabs_cont" $ do nnCont contentByPosition where nInput :: Int -> H.Html nInput x = H.input ! A.id (H.toValue $ "tab_" ++ show x) ! A.type_ "radio" ! A.name "tab" nnInput :: [H.Html] -> H.Html nnInput (x:xs) = sequence_ ((x ! A.checked "checked") : xs) toName :: TParadigm -> H.Html toName x = do let lemma = toLemm s x (pref, suff, _) = head x H.toHtml $ pref <> lemma <> suff nLabel :: (Int, TParadigm) -> H.Html nLabel (x,y) = H.label ! A.for (H.toValue $ "tab_" ++ show x) ! A.id (H.toValue $ "tab_l" ++ show x) $ toName y nnLabel :: [(Int, TParadigm)] -> H.Html nnLabel xs = sequence_ $ P.map nLabel xs nCont (x,y) = H.div ! A.id (H.toValue $ "tab_c" ++ show x) $ paradigmToHtml tegs s y nnCont xs = sequence_ $ P.map nCont xs spm :: Tegs -> Text -> (Text, Text, Int) -> H.Html spm tegs w (pref, suff, t) = do H.div ! A.class_ "form" $ H.toHtml $ pref <> w <> suff H.div ! A.class_ "description" $ H.toHtml $ showTegs tegs t showParadigm :: Tegs -> Text -> TParadigm -> Text showParadigm tegs w xs = let lemma = toLemm w xs in foldl (\x y -> showParadigm' tegs lemma y <> x) "" xs paradigmToHtml :: Tegs -> Text -> TParadigm -> H.Html paradigmToHtml tegs w xs = do let lemma = toLemm w xs H.ul $ forM_ xs (\x -> H.li $ spm tegs lemma x) showParadigm' :: Tegs -> Text -> (Text, Text, Int) -> Text showParadigm' tegs w (pref, suff, t) = pref <> w <> suff <> " \t" <> showTegs tegs t <> "\n" showTegs :: Tegs -> Int -> Text showTegs tegs i = foldl fun "" $ tegs V.! i where fun x y = showFull y <> " ," <> x toLemm :: Text -> TParadigm -> Text toLemm s p = let (pref, suff, _) = maximum $ filter (\(x, y, _) -> T.take (T.length x) s == x && T.drop (T.length s - T.length y) s == y ) p in T.drop (T.length pref) $ T.take (T.length s - T.length suff) s web :: Morph -> IO () web m = quickHttpServe $ ifTop (writeLazyText $ H.renderHtml $ indexPage usage) <|> route [ ("all" , allForm m) , ("static", serveDirectory "static" ) ] normalForm = undefined allForm :: Morph -> Snap () allForm m = do w <- getParam "word" writeLazyText $ H.renderHtml $ indexPage $ getAllForm' m $ decodeUtf8 $ fromJust w indexPage :: H.Html -> H.Html indexPage body = H.docTypeHtml $ do H.head $ do H.title "Морфология" H.link ! A.type_ "text/css" ! A.rel "stylesheet" ! A.href "static/css/style.css" H.body $ do H.form ! A.class_ "input" ! A.id "input" $ do H.input ! A.name "word" H.button "all" ! A.formaction "all" H.br body usage :: H.Html usage = H.div ! A.class_ "input" ! A.id "input" $ "Наберите слово и нажмите кнопку"
chemist/russian-morphology
Main.hs
bsd-3-clause
5,168
0
19
1,530
2,027
1,038
989
113
2
{-# LANGUAGE GeneralizedNewtypeDeriving, TypeFamilies, FlexibleContexts, TupleSections, LambdaCase, FlexibleInstances, MultiParamTypeClasses #-} module Futhark.Pass.ExplicitAllocations ( explicitAllocations , simplifiable , arraySizeInBytesExp ) where import Control.Applicative import Control.Monad.State import Control.Monad.Writer import Control.Monad.Reader import Control.Monad.RWS.Strict import qualified Data.HashMap.Lazy as HM import qualified Data.HashSet as HS import Data.Maybe import qualified Futhark.Representation.Kernels as In import Futhark.Optimise.Simplifier.Lore (mkWiseBody, mkWiseLetBinding, removeExpWisdom, removePatternWisdom, removeScopeWisdom) import Futhark.MonadFreshNames import Futhark.Representation.ExplicitMemory import qualified Futhark.Representation.ExplicitMemory.IndexFunction as IxFun import Futhark.Tools import qualified Futhark.Analysis.SymbolTable as ST import qualified Futhark.Analysis.ScalExp as SE import Futhark.Optimise.Simplifier.Simple (SimpleOps (..)) import qualified Futhark.Optimise.Simplifier.Engine as Engine import Futhark.Pass import Prelude data AllocBinding = SizeComputation VName SE.ScalExp | Allocation VName SubExp Space | ArrayCopy VName Bindage VName deriving (Eq, Ord, Show) bindAllocBinding :: (MonadBinder m, Op (Lore m) ~ MemOp (Lore m)) => AllocBinding -> m () bindAllocBinding (SizeComputation name se) = do e <- SE.fromScalExp se letBindNames'_ [name] e bindAllocBinding (Allocation name size space) = letBindNames'_ [name] $ Op $ Alloc size space bindAllocBinding (ArrayCopy name bindage src) = letBindNames_ [(name,bindage)] $ PrimOp $ Copy src class (MonadFreshNames m, HasScope ExplicitMemory m) => Allocator m where addAllocBinding :: AllocBinding -> m () -- | The subexpression giving the number of elements we should -- allocate space for. See 'ChunkMap' comment. dimAllocationSize :: SubExp -> m SubExp allocateMemory :: Allocator m => String -> SubExp -> Space -> m VName allocateMemory desc size space = do v <- newVName desc addAllocBinding $ Allocation v size space return v computeSize :: Allocator m => String -> SE.ScalExp -> m SubExp computeSize desc se = do v <- newVName desc addAllocBinding $ SizeComputation v se return $ Var v -- | A mapping from chunk names to their maximum size. XXX FIXME -- HACK: This is part of a hack to add loop-invariant allocations to -- reduce kernels, because memory expansion does not use range -- analysis yet (it should). type ChunkMap = HM.HashMap VName SubExp -- | Monad for adding allocations to an entire program. newtype AllocM a = AllocM (BinderT ExplicitMemory (ReaderT ChunkMap (State VNameSource)) a) deriving (Applicative, Functor, Monad, MonadFreshNames, HasScope ExplicitMemory, LocalScope ExplicitMemory, MonadReader ChunkMap) instance MonadBinder AllocM where type Lore AllocM = ExplicitMemory mkLetM pat e = return $ Let pat () e mkLetNamesM names e = do pat <- patternWithAllocations names e return $ Let pat () e mkBodyM bnds res = return $ Body () bnds res addBinding binding = AllocM $ addBinderBinding binding collectBindings (AllocM m) = AllocM $ collectBinderBindings m instance Allocator AllocM where addAllocBinding (SizeComputation name se) = letBindNames'_ [name] =<< SE.fromScalExp se addAllocBinding (Allocation name size space) = letBindNames'_ [name] $ Op $ Alloc size space addAllocBinding (ArrayCopy name bindage src) = letBindNames_ [(name, bindage)] $ PrimOp $ SubExp $ Var src dimAllocationSize (Var v) = fromMaybe (Var v) <$> asks (HM.lookup v) dimAllocationSize size = return size runAllocM :: MonadFreshNames m => AllocM a -> m a runAllocM (AllocM m) = fmap fst $ modifyNameSource $ runState $ runReaderT (runBinderT m mempty) mempty -- | Monad for adding allocations to a single pattern. newtype PatAllocM a = PatAllocM (RWS (Scope ExplicitMemory) [AllocBinding] VNameSource a) deriving (Applicative, Functor, Monad, HasScope ExplicitMemory, MonadWriter [AllocBinding], MonadFreshNames) instance Allocator PatAllocM where addAllocBinding = tell . pure dimAllocationSize = return runPatAllocM :: MonadFreshNames m => PatAllocM a -> Scope ExplicitMemory -> m (a, [AllocBinding]) runPatAllocM (PatAllocM m) mems = modifyNameSource $ frob . runRWS m mems where frob (a,s,w) = ((a,w),s) arraySizeInBytesExp :: Type -> SE.ScalExp arraySizeInBytesExp t = SE.sproduct $ primByteSize (elemType t) : map (`SE.subExpToScalExp` int32) (arrayDims t) arraySizeInBytesExpM :: Allocator m => Type -> m SE.ScalExp arraySizeInBytesExpM t = SE.sproduct . (primByteSize (elemType t) :) . map (`SE.subExpToScalExp` int32) <$> mapM dimAllocationSize (arrayDims t) arraySizeInBytes :: Allocator m => Type -> m SubExp arraySizeInBytes = computeSize "bytes" <=< arraySizeInBytesExpM allocForArray :: Allocator m => Type -> Space -> m (SubExp, VName) allocForArray t space = do size <- arraySizeInBytes t m <- allocateMemory "mem" size space return (size, m) -- | Allocate local-memory array. allocForLocalArray :: Allocator m => SubExp -> Type -> m (SubExp, VName) allocForLocalArray workgroup_size t = do size <- computeSize "local_bytes" =<< (SE.intSubExpToScalExp workgroup_size*) <$> arraySizeInBytesExpM t m <- allocateMemory "local_mem" size $ Space "local" return (size, m) allocsForBinding :: Allocator m => [Ident] -> [(Ident,Bindage)] -> Exp -> m (Binding, [AllocBinding]) allocsForBinding sizeidents validents e = do rts <- expReturns e (ctxElems, valElems, postbnds) <- allocsForPattern sizeidents validents rts return (Let (Pattern ctxElems valElems) () e, postbnds) patternWithAllocations :: Allocator m => [(VName, Bindage)] -> Exp -> m Pattern patternWithAllocations names e = do (ts',sizes) <- instantiateShapes' =<< expExtType e let identForBindage name t BindVar = pure (Ident name t, BindVar) identForBindage name _ bindage@(BindInPlace _ src _) = do t <- lookupType src pure (Ident name t, bindage) vals <- sequence [ identForBindage name t bindage | ((name,bindage), t) <- zip names ts' ] (Let pat _ _, extrabnds) <- allocsForBinding sizes vals e case extrabnds of [] -> return pat _ -> fail $ "Cannot make allocations for pattern of " ++ pretty e allocsForPattern :: Allocator m => [Ident] -> [(Ident,Bindage)] -> [ExpReturns] -> m ([PatElem], [PatElem], [AllocBinding]) allocsForPattern sizeidents validents rts = do let sizes' = [ PatElem size BindVar $ Scalar int32 | size <- map identName sizeidents ] (vals,(memsizes, mems, postbnds)) <- runWriterT $ forM (zip validents rts) $ \((ident,bindage), rt) -> do let shape = arrayShape $ identType ident case rt of ReturnsScalar _ -> do summary <- lift $ summaryForBindage (identType ident) bindage return $ PatElem (identName ident) bindage summary ReturnsMemory size space -> return $ PatElem (identName ident) bindage $ MemMem size space ReturnsArray bt _ u (Just (ReturnsInBlock mem ixfun)) -> case bindage of BindVar -> return $ PatElem (identName ident) bindage $ ArrayMem bt shape u mem ixfun BindInPlace _ src is -> do (destmem,destixfun) <- lift $ lookupArraySummary src if destmem == mem && destixfun == ixfun then return $ PatElem (identName ident) bindage $ ArrayMem bt shape u mem ixfun else do -- The expression returns at some specific memory -- location, but we want to put the result somewhere -- else. This means we need to store it in the memory -- it wants to first, then copy it to our intended -- destination in an extra binding. tmp_buffer <- lift $ newIdent (baseString (identName ident)<>"_buffer") (stripArray (length is) $ identType ident) tell ([], [], [ArrayCopy (identName ident) bindage $ identName tmp_buffer]) return $ PatElem (identName tmp_buffer) BindVar $ ArrayMem bt (stripDims (length is) shape) u mem ixfun ReturnsArray _ extshape _ Nothing | Just _ <- knownShape extshape -> do summary <- lift $ summaryForBindage (identType ident) bindage return $ PatElem (identName ident) bindage summary ReturnsArray bt _ u (Just ReturnsNewBlock{}) | BindInPlace _ _ is <- bindage -> do -- The expression returns its own memory, but the pattern -- wants to store it somewhere else. We first let it -- store the value where it wants, then we copy it to the -- intended destination. In some cases, the copy may be -- optimised away later, but in some cases it may not be -- possible (e.g. function calls). tmp_buffer <- lift $ newIdent (baseString (identName ident)<>"_ext_buffer") (stripArray (length is) $ identType ident) (memsize,mem,(_,ixfun)) <- lift $ memForBindee tmp_buffer tell ([PatElem (identName memsize) BindVar $ Scalar int32], [PatElem (identName mem) BindVar $ MemMem (Var $ identName memsize) DefaultSpace], [ArrayCopy (identName ident) bindage $ identName tmp_buffer]) return $ PatElem (identName tmp_buffer) BindVar $ ArrayMem bt (stripDims (length is) shape) u (identName mem) ixfun ReturnsArray bt _ u _ -> do (memsize,mem,(ident',ixfun)) <- lift $ memForBindee ident tell ([PatElem (identName memsize) BindVar $ Scalar int32], [PatElem (identName mem) BindVar $ MemMem (Var $ identName memsize) DefaultSpace], []) return $ PatElem (identName ident') bindage $ ArrayMem bt shape u (identName mem) ixfun return (memsizes <> mems <> sizes', vals, postbnds) where knownShape = mapM known . extShapeDims known (Free v) = Just v known Ext{} = Nothing summaryForBindage :: Allocator m => Type -> Bindage -> m (MemBound NoUniqueness) summaryForBindage (Prim bt) BindVar = return $ Scalar bt summaryForBindage (Mem size space) BindVar = return $ MemMem size space summaryForBindage t@(Array bt shape u) BindVar = do (_, m) <- allocForArray t DefaultSpace return $ directIndexFunction bt shape u m t summaryForBindage _ (BindInPlace _ src _) = lookupMemBound src memForBindee :: (MonadFreshNames m) => Ident -> m (Ident, Ident, (Ident, IxFun.IxFun SE.ScalExp)) memForBindee ident = do size <- newIdent (memname <> "_size") (Prim int32) mem <- newIdent memname $ Mem (Var $ identName size) DefaultSpace return (size, mem, (ident, IxFun.iota $ map SE.intSubExpToScalExp $ arrayDims t)) where memname = baseString (identName ident) <> "_mem" t = identType ident directIndexFunction :: PrimType -> Shape -> u -> VName -> Type -> MemBound u directIndexFunction bt shape u mem t = ArrayMem bt shape u mem $ IxFun.iota $ map SE.intSubExpToScalExp $ arrayDims t patElemSummary :: PatElem -> (VName, NameInfo ExplicitMemory) patElemSummary bindee = (patElemName bindee, LetInfo $ patElemAttr bindee) bindeesSummary :: [PatElem] -> Scope ExplicitMemory bindeesSummary = HM.fromList . map patElemSummary fparamsSummary :: [FParam] -> Scope ExplicitMemory fparamsSummary = HM.fromList . map paramSummary where paramSummary fparam = (paramName fparam, FParamInfo $ paramAttr fparam) lparamsSummary :: [LParam] -> Scope ExplicitMemory lparamsSummary = HM.fromList . map paramSummary where paramSummary fparam = (paramName fparam, LParamInfo $ paramAttr fparam) allocInFParams :: [In.FParam] -> ([FParam] -> AllocM a) -> AllocM a allocInFParams params m = do (valparams, (memsizeparams, memparams)) <- runWriterT $ mapM allocInFParam params let params' = memsizeparams <> memparams <> valparams summary = fparamsSummary params' localScope summary $ m params' allocInFParam :: MonadFreshNames m => In.FParam -> WriterT ([FParam], [FParam]) m FParam allocInFParam param = case paramDeclType param of Array bt shape u -> do let memname = baseString (paramName param) <> "_mem" ixfun = IxFun.iota $ map SE.intSubExpToScalExp $ shapeDims shape memsize <- lift $ newVName (memname <> "_size") mem <- lift $ newVName memname tell ([Param memsize $ Scalar int32], [Param mem $ MemMem (Var memsize) DefaultSpace]) return param { paramAttr = ArrayMem bt shape u mem ixfun } Prim bt -> return param { paramAttr = Scalar bt } Mem size space -> return param { paramAttr = MemMem size space } allocInMergeParams :: [VName] -> [(In.FParam,SubExp)] -> ([FParam] -> [FParam] -> ([SubExp] -> AllocM ([SubExp], [SubExp])) -> AllocM a) -> AllocM a allocInMergeParams variant merge m = do ((valparams, handle_loop_subexps), (memsizeparams, memparams)) <- runWriterT $ unzip <$> mapM allocInMergeParam merge let mergeparams' = memsizeparams <> memparams <> valparams summary = fparamsSummary mergeparams' mk_loop_res :: [SubExp] -> AllocM ([SubExp], [SubExp]) mk_loop_res ses = do (valargs, (memsizeargs, memargs)) <- runWriterT $ zipWithM ($) handle_loop_subexps ses return (memsizeargs <> memargs, valargs) localScope summary $ m (memsizeparams<>memparams) valparams mk_loop_res where variant_names = variant ++ map (paramName . fst) merge loopInvariantShape = not . any (`elem` variant_names) . subExpVars . arrayDims . paramType allocInMergeParam (mergeparam, Var v) | Array bt shape Unique <- paramDeclType mergeparam, loopInvariantShape mergeparam = do (mem, ixfun) <- lift $ lookupArraySummary v return (mergeparam { paramAttr = ArrayMem bt shape Unique mem ixfun }, lift . ensureArrayIn (paramType mergeparam) mem ixfun) allocInMergeParam (mergeparam, _) = do mergeparam' <- allocInFParam mergeparam return (mergeparam', linearFuncallArg $ paramType mergeparam) ensureDirectArray :: VName -> AllocM (SubExp, VName, SubExp) ensureDirectArray v = do res <- lookupMemBound v case res of ArrayMem _ _ _ mem ixfun | IxFun.isDirect ixfun -> do memt <- lookupType mem case memt of Mem size _ -> return (size, mem, Var v) _ -> fail $ pretty mem ++ " should be a memory block but has type " ++ pretty memt _ -> -- We need to do a new allocation, copy 'v', and make a new -- binding for the size of the memory block. allocLinearArray (baseString v) v ensureArrayIn :: Type -> VName -> IxFun.IxFun SE.ScalExp -> SubExp -> AllocM SubExp ensureArrayIn _ _ _ (Constant v) = fail $ "ensureArrayIn: " ++ pretty v ++ " cannot be an array." ensureArrayIn t mem ixfun (Var v) = do (src_mem, src_ixfun) <- lookupArraySummary v if src_mem == mem && src_ixfun == ixfun then return $ Var v else do copy <- newIdent (baseString v ++ "_copy") t let summary = ArrayMem (elemType t) (arrayShape t) NoUniqueness mem ixfun pat = Pattern [] [PatElem (identName copy) BindVar summary] letBind_ pat $ PrimOp $ Copy v return $ Var $ identName copy allocLinearArray :: String -> VName -> AllocM (SubExp, VName, SubExp) allocLinearArray s v = do t <- lookupType v (size, mem) <- allocForArray t DefaultSpace v' <- newIdent s t let pat = Pattern [] [PatElem (identName v') BindVar $ directIndexFunction (elemType t) (arrayShape t) NoUniqueness mem t] addBinding $ Let pat () $ PrimOp $ Copy v return (size, mem, Var $ identName v') funcallArgs :: [(SubExp,Diet)] -> AllocM [(SubExp,Diet)] funcallArgs args = do (valargs, (memsizeargs, memargs)) <- runWriterT $ forM args $ \(arg,d) -> do t <- lift $ subExpType arg arg' <- linearFuncallArg t arg return (arg', d) return $ map (,Observe) (memsizeargs <> memargs) <> valargs linearFuncallArg :: Type -> SubExp -> WriterT ([SubExp], [SubExp]) AllocM SubExp linearFuncallArg Array{} (Var v) = do (size, mem, arg') <- lift $ ensureDirectArray v tell ([size], [Var mem]) return arg' linearFuncallArg _ arg = return arg explicitAllocations :: Pass In.Kernels ExplicitMemory explicitAllocations = simplePass "explicit allocations" "Transform program to explicit memory representation" $ intraproceduralTransformation allocInFun memoryInRetType :: In.RetType -> RetType memoryInRetType (ExtRetType ts) = evalState (mapM addAttr ts) $ startOfFreeIDRange ts where addAttr (Prim t) = return $ ReturnsScalar t addAttr Mem{} = fail "memoryInRetType: too much memory" addAttr (Array bt shape u) = do i <- get put $ i + 1 return $ ReturnsArray bt shape u $ ReturnsNewBlock i Nothing startOfFreeIDRange :: [TypeBase ExtShape u] -> Int startOfFreeIDRange = (1+) . HS.foldl' max 0 . shapeContext allocInFun :: MonadFreshNames m => In.FunDef -> m FunDef allocInFun (In.FunDef entry fname rettype params body) = runAllocM $ allocInFParams params $ \params' -> do body' <- insertBindingsM $ allocInBody body return $ FunDef entry fname (memoryInRetType rettype) params' body' allocInBody :: In.Body -> AllocM Body allocInBody (Body _ bnds res) = allocInBindings bnds $ \bnds' -> do (ses, allocs) <- collectBindings $ mapM ensureDirect res return $ Body () (bnds'<>allocs) ses where ensureDirect se@Constant{} = return se ensureDirect (Var v) = do bt <- primType <$> lookupType v if bt then return $ Var v else do (_, _, v') <- ensureDirectArray v return v' allocInBindings :: [In.Binding] -> ([Binding] -> AllocM a) -> AllocM a allocInBindings origbnds m = allocInBindings' origbnds [] where allocInBindings' [] bnds' = m bnds' allocInBindings' (x:xs) bnds' = do allocbnds <- allocInBinding' x let summaries = bindeesSummary $ concatMap (patternElements . bindingPattern) allocbnds localScope summaries $ allocInBindings' xs (bnds'++allocbnds) allocInBinding' bnd = do ((),bnds') <- collectBindings $ allocInBinding bnd return bnds' allocInBinding :: In.Binding -> AllocM () allocInBinding (Let (Pattern sizeElems valElems) _ e) = do e' <- allocInExp e let sizeidents = map patElemIdent sizeElems validents = [ (Ident name t, bindage) | PatElem name bindage t <- valElems ] (bnd, bnds) <- allocsForBinding sizeidents validents e' addBinding bnd mapM_ bindAllocBinding bnds allocInExp :: In.Exp -> AllocM Exp allocInExp (DoLoop ctx val form (Body () bodybnds bodyres)) = allocInMergeParams mempty ctx $ \_ ctxparams' _ -> allocInMergeParams (map paramName ctxparams') val $ \new_ctx_params valparams' mk_loop_val -> formBinds form $ do (valinit_ctx, valinit') <- mk_loop_val valinit body' <- insertBindingsM $ allocInBindings bodybnds $ \bodybnds' -> do ((val_ses,valres'),val_retbnds) <- collectBindings $ mk_loop_val valres return $ Body () (bodybnds'<>val_retbnds) (val_ses++ctxres++valres') return $ DoLoop (zip (new_ctx_params++ctxparams') (valinit_ctx++ctxinit)) (zip valparams' valinit') form body' where (_ctxparams, ctxinit) = unzip ctx (_valparams, valinit) = unzip val (ctxres, valres) = splitAt (length ctx) bodyres formBinds (ForLoop i _) = localScope $ HM.singleton i IndexInfo formBinds (WhileLoop _) = id allocInExp (Op (MapKernel cs w index ispace inps returns body)) = do inps' <- mapM allocInKernelInput inps let mem_map = lparamsSummary (map kernelInputParam inps') <> ispace_map localScope mem_map $ do body' <- allocInBindings (bodyBindings body) $ \bnds' -> return $ Body () bnds' $ bodyResult body return $ Op $ Inner $ MapKernel cs w index ispace inps' returns body' where ispace_map = HM.fromList [ (i, IndexInfo) | i <- index : map fst ispace ] allocInKernelInput inp = case kernelInputType inp of Prim bt -> return inp { kernelInputParam = Param (kernelInputName inp) $ Scalar bt } Array bt shape u -> do (mem, ixfun) <- lookupArraySummary $ kernelInputArray inp let ixfun' = IxFun.applyInd ixfun $ map SE.intSubExpToScalExp $ kernelInputIndices inp summary = ArrayMem bt shape u mem ixfun' return inp { kernelInputParam = Param (kernelInputName inp) summary } Mem size shape -> return inp { kernelInputParam = Param (kernelInputName inp) $ MemMem size shape } allocInExp (Op (ChunkedMapKernel cs w size o lam arrs)) = do arr_summaries <- mapM lookupMemBound arrs lam' <- allocInFoldLambda (case o of InOrder -> Noncommutative Disorder -> Commutative) (kernelElementsPerThread size) (kernelNumThreads size) lam arr_summaries return $ Op $ Inner $ ChunkedMapKernel cs w size o lam' arrs allocInExp (Op (ReduceKernel cs w size comm red_lam fold_lam arrs)) = do arr_summaries <- mapM lookupMemBound arrs fold_lam' <- allocInFoldLambda comm (kernelElementsPerThread size) (kernelNumThreads size) fold_lam arr_summaries red_lam' <- allocInReduceLambda red_lam (kernelWorkgroupSize size) return $ Op $ Inner $ ReduceKernel cs w size comm red_lam' fold_lam' arrs allocInExp (Op (ScanKernel cs w size order lam input)) = do lam' <- allocInReduceLambda lam (kernelWorkgroupSize size) return $ Op $ Inner $ ScanKernel cs w size order lam' input allocInExp (Op (WriteKernel cs t i v a)) = -- We require Write to be in-place, so there is no need to allocate any -- memory. return $ Op $ Inner $ WriteKernel cs t i v a allocInExp (Op GroupSize) = return $ Op $ Inner GroupSize allocInExp (Op NumGroups) = return $ Op $ Inner NumGroups allocInExp (Apply fname args rettype) = do args' <- funcallArgs args return $ Apply fname args' (memoryInRetType rettype) allocInExp e = mapExpM alloc e where alloc = identityMapper { mapOnBody = allocInBody , mapOnRetType = return . memoryInRetType , mapOnFParam = fail "Unhandled FParam in ExplicitAllocations" , mapOnOp = \op -> fail $ "Unhandled Op in ExplicitAllocations:\n" ++ pretty op } allocInFoldLambda :: Commutativity -> SubExp -> SubExp -> In.Lambda -> [MemBound NoUniqueness] -> AllocM Lambda allocInFoldLambda comm elems_per_thread num_threads lam arr_summaries = do let (i, chunk_size_param, chunked_params) = partitionChunkedKernelLambdaParameters $ lambdaParams lam chunked_params' <- forM (zip chunked_params arr_summaries) $ \(p,summary) -> case summary of Scalar _ -> fail $ "Passed a scalar for lambda parameter " ++ pretty p ArrayMem bt shape u mem ixfun -> case comm of Noncommutative -> do let newshape = [DimNew num_threads, DimNew elems_per_thread] return p { paramAttr = ArrayMem bt (arrayShape $ paramType p) u mem $ IxFun.applyInd (IxFun.reshape ixfun $ map (fmap SE.intSubExpToScalExp) $ newshape ++ map DimNew (drop 1 $ shapeDims shape)) [SE.Id i int32] } Commutative -> do let newshape = [DimNew elems_per_thread, DimNew num_threads] perm = [1,0] ++ [2..IxFun.rank ixfun] return p { paramAttr = ArrayMem bt (arrayShape $ paramType p) u mem $ IxFun.applyInd (IxFun.permute (IxFun.reshape ixfun $ map (fmap SE.intSubExpToScalExp) $ newshape ++ map DimNew (drop 1 $ shapeDims shape)) perm) [SE.Id i int32] } _ -> fail $ "Chunked lambda non-array lambda parameter " ++ pretty p local (HM.insert (paramName chunk_size_param) elems_per_thread) $ allocInLambda (Param i (Scalar int32) : Param (paramName chunk_size_param) (Scalar int32) : chunked_params') (lambdaBody lam) (lambdaReturnType lam) allocInReduceLambda :: In.Lambda -> SubExp -> AllocM Lambda allocInReduceLambda lam workgroup_size = do let (i, other_index_param, actual_params) = partitionChunkedKernelLambdaParameters $ lambdaParams lam (acc_params, arr_params) = splitAt (length actual_params `div` 2) actual_params this_index = SE.Id i int32 `SE.SRem` SE.intSubExpToScalExp workgroup_size other_index = SE.Id (paramName other_index_param) int32 acc_params' <- allocInReduceParameters workgroup_size this_index acc_params arr_params' <- forM (zip arr_params $ map paramAttr acc_params') $ \(param, attr) -> case attr of ArrayMem bt shape u mem _ -> return param { paramAttr = ArrayMem bt shape u mem $ IxFun.applyInd (IxFun.iota $ map SE.intSubExpToScalExp $ workgroup_size : arrayDims (paramType param)) [this_index + other_index] } _ -> return param { paramAttr = attr } allocInLambda (Param i (Scalar int32) : other_index_param { paramAttr = Scalar int32 } : acc_params' ++ arr_params') (lambdaBody lam) (lambdaReturnType lam) allocInReduceParameters :: SubExp -> SE.ScalExp -> [In.LParam] -> AllocM [LParam] allocInReduceParameters workgroup_size local_id = mapM allocInReduceParameter where allocInReduceParameter p = case paramType p of t@(Array bt shape u) -> do (_, shared_mem) <- allocForLocalArray workgroup_size t let ixfun = IxFun.applyInd (IxFun.iota $ map SE.intSubExpToScalExp $ workgroup_size : arrayDims t) [local_id] return p { paramAttr = ArrayMem bt shape u shared_mem ixfun } Prim bt -> return p { paramAttr = Scalar bt } Mem size space -> return p { paramAttr = MemMem size space } allocInLambda :: [LParam] -> In.Body -> [Type] -> AllocM Lambda allocInLambda params body rettype = do body' <- localScope (lparamsSummary params) $ allocInBindings (bodyBindings body) $ \bnds' -> return $ Body () bnds' $ bodyResult body return $ Lambda params body' rettype simplifiable :: (Engine.MonadEngine m, Engine.InnerLore m ~ ExplicitMemory) => SimpleOps m simplifiable = SimpleOps mkLetS' mkBodyS' mkLetNamesS' where mkLetS' _ pat e = return $ mkWiseLetBinding (removePatternWisdom pat) () e mkBodyS' _ bnds res = return $ mkWiseBody () bnds res mkLetNamesS' vtable names e = do pat' <- bindPatternWithAllocations env names $ removeExpWisdom e return $ mkWiseLetBinding pat' () e where env = removeScopeWisdom $ ST.typeEnv vtable bindPatternWithAllocations :: (MonadBinder m, Op (Lore m) ~ MemOp (Lore m)) => Scope ExplicitMemory -> [(VName, Bindage)] -> Exp -> m Pattern bindPatternWithAllocations types names e = do (pat,prebnds) <- runPatAllocM (patternWithAllocations names e) types mapM_ bindAllocBinding prebnds return pat
CulpaBS/wbBach
src/Futhark/Pass/ExplicitAllocations.hs
bsd-3-clause
29,829
0
32
8,925
8,930
4,442
4,488
622
9
-- Copyright 2013 Kevin Backhouse. {-| Utility functions for working with the 'UpdateThreadContext' argument of 'createInstrument'. This module is only relevant for Instrument authoring. -} module Control.Monad.MultiPass.Utils.UpdateCtx ( updateCtxFst, updateCtxSnd , updateCtxLeft, updateCtxRight ) where import Control.Exception ( assert ) import Control.Monad.MultiPass -- | If the thread context is a pair then 'updateCtxFst' creates a new -- 'UpdateThreadContext' function which can be used to update the -- first element of the pair. updateCtxFst :: UpdateThreadContext rootTC (x,y) -> UpdateThreadContext rootTC x updateCtxFst updateCtx f = do (x,_) <- updateCtx (cross f id) return x -- | If the thread context is a pair then 'updateCtxSnd' creates a new -- 'UpdateThreadContext' function which can be used to update the -- second element of the pair. updateCtxSnd :: UpdateThreadContext rootTC (x,y) -> UpdateThreadContext rootTC y updateCtxSnd updateCtx f = do (_,y) <- updateCtx (cross id f) return y cross :: (a -> a') -> (b -> b') -> (a,b) -> (a',b') cross f g (x,y) = (f x, g y) -- | If the thread context is an Either of two thread contexts then -- 'updateCtxLeft' creates a new 'UpdateThreadContext' function which -- can be used to update the 'Left' element. This function will assert -- if the thread context is a 'Right' element. updateCtxLeft :: UpdateThreadContext rootTC (Either x y) -> UpdateThreadContext rootTC x updateCtxLeft updateCtx f = let g (Left x) = Left (f x) g (Right _) = assert False $ error "updateCtxLeft" in do Left x <- updateCtx g return x -- | If the thread context is an Either of two thread contexts then -- 'updateCtxRight' creates a new 'UpdateThreadContext' function which -- can be used to update the 'Right' element. This function will assert -- if the thread context is a 'Left' element. updateCtxRight :: UpdateThreadContext rootTC (Either x y) -> UpdateThreadContext rootTC y updateCtxRight updateCtx f = let g (Left _) = assert False $ error "updateCtxRight" g (Right x) = Right (f x) in do Right x <- updateCtx g return x
kevinbackhouse/Control-Monad-MultiPass
src/Control/Monad/MultiPass/Utils/UpdateCtx.hs
bsd-3-clause
2,155
0
11
416
476
245
231
35
2
module Test.Property.EntityGen where import Bead.Domain.Entities import qualified Bead.Domain.Entity.Notification as Notification import Bead.Domain.TimeZone (utcZoneInfo, cetZoneInfo) import Bead.Domain.Shared.Evaluation import Test.Tasty.Arbitrary import Control.Monad (join, liftM) import Control.Applicative ((<$>),(<*>),pure) import Data.String (fromString) import qualified Data.ByteString.Char8 as BS (pack) word = listOf1 $ elements ['a' .. 'z' ] numbers = listOf1 $ elements ['0' .. '9'] manyWords = do w <- word ws <- manyWords' return $ w ++ " " ++ ws where manyWords' = listOf1 $ elements $ ' ':['a' .. 'z'] usernames = liftM Username (vectorOf 6 $ oneof [capital, digits]) where capital = elements ['A' .. 'Z'] digits = elements ['0' .. '9'] uids = fmap (usernameCata Uid) usernames roleGen = elements [Student, GroupAdmin, CourseAdmin, Admin] emails = do user <- word domain <- word return $ Email $ join [user, "@", domain, ".com"] familyNames = do first <- word last <- word return $ join [first, " ", last] languages = Language <$> word users = User <$> roleGen <*> usernames <*> emails <*> familyNames <*> (return utcZoneInfo) <*> languages <*> uids userAndEPwds = do user <- users code <- numbers return (user, code) courseCodes = liftM CourseCode word courseNames = word courseDescs = manyWords evalConfigs = oneof [ return binaryConfig , percentageConfig <$> percentage ] percentage = do (_,f) <- properFraction <$> arbitrary return $ case f < 0 of True -> (-1.0) * f False -> f courses = courseAppAna courseNames courseDescs (elements [TestScriptSimple, TestScriptZipped]) groupCodes = word groupNames = manyWords groupDescs = manyWords groupUsers' = liftM (map Username) (listOf1 word) groups = Group <$> groupNames <*> groupDescs timeZones = elements [utcZoneInfo, cetZoneInfo] assignments start end = assignmentAna assignmentNames assignmentDescs assignmentTypeGen (return start) (return end) evaluationConfigs assignmentNames = manyWords assignmentDescs = manyWords assignmentTCss = manyWords assignmentTypeGen = oneof [ (return emptyAspects) , (return $ aspectsFromList [BallotBox]) , (do pwd <- word; return $ aspectsFromList [Password pwd]) , (do pwd <- word; return $ aspectsFromList [Password pwd, BallotBox]) ] evaluationConfigs = oneof [ (return binaryConfig) , percentageConfig <$> percentage ] passwords = word solutionValues = oneof [ SimpleSubmission <$> solutionTexts , ZippedSubmission . fromString <$> solutionTexts ] submissions date = Submission <$> solutionValues <*> (return date) commentTypes = elements [CT_Student, CT_GroupAdmin, CT_CourseAdmin, CT_Admin] comments date = Comment <$> commentTexts <*> commentAuthors <*> (return date) <*> commentTypes solutionTexts = manyWords commentTexts = manyWords commentAuthors = manyWords evaluations :: EvConfig -> Gen Evaluation evaluations cfg = Evaluation <$> evaluationResults cfg <*> writtenEvaluations writtenEvaluations = manyWords evaluationResults = evConfigCata (binaryResult <$> elements [Passed, Failed]) (const (percentageResult <$> percentage)) arbitrary testScripts = testScriptAppAna word -- words manyWords -- desc manyWords -- notes manyWords -- script enumGen -- type testCases = oneof [ TestCase <$> word <*> manyWords <*> (SimpleTestCase <$> manyWords) <*> manyWords , TestCase <$> word <*> manyWords <*> (ZippedTestCase . BS.pack <$> manyWords) <*> manyWords ] testFeedbackInfo = oneof [ TestResult <$> arbitrary , MessageForStudent <$> manyWords , MessageForAdmin <$> manyWords ] feedbacks date = Feedback <$> testFeedbackInfo <*> (return date) scores :: Gen Score scores = arbitrary date = read "2016-01-22 14:41:26 UTC" assessments = Assessment <$> manyWords <*> manyWords <*> pure date <*> evalConfigs notifEvents = oneof [ Notification.NE_CourseAdminCreated <$> manyWords , Notification.NE_CourseAdminAssigned <$> manyWords <*> manyWords , Notification.NE_TestScriptCreated <$> manyWords <*> manyWords , Notification.NE_TestScriptUpdated <$> manyWords <*> manyWords <*> manyWords , Notification.NE_RemovedFromGroup <$> manyWords <*> manyWords , Notification.NE_GroupAdminCreated <$> manyWords <*> manyWords <*> manyWords , Notification.NE_GroupAssigned <$> manyWords <*> manyWords <*> manyWords <*> manyWords , Notification.NE_GroupCreated <$> manyWords <*> manyWords <*> manyWords , Notification.NE_GroupAssignmentCreated <$> manyWords <*> manyWords <*> manyWords <*> manyWords , Notification.NE_CourseAssignmentCreated <$> manyWords <*> manyWords <*> manyWords , Notification.NE_GroupAssessmentCreated <$> manyWords <*> manyWords <*> manyWords <*> manyWords , Notification.NE_CourseAssessmentCreated <$> manyWords <*> manyWords <*> manyWords , Notification.NE_AssessmentUpdated <$> manyWords <*> manyWords , Notification.NE_AssignmentUpdated <$> manyWords <*> manyWords , Notification.NE_EvaluationCreated <$> manyWords <*> manyWords , Notification.NE_AssessmentEvaluationUpdated <$> manyWords <*> manyWords , Notification.NE_AssignmentEvaluationUpdated <$> manyWords <*> manyWords , Notification.NE_CommentCreated <$> manyWords <*> manyWords <*> manyWords ] notifications = Notification.Notification <$> notifEvents <*> pure date <*> pure Notification.System
andorp/bead
test/Test/Property/EntityGen.hs
bsd-3-clause
5,556
0
13
1,039
1,507
813
694
150
2
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE FlexibleInstances,UndecidableInstances,OverlappingInstances #-} module QuickCover.Log where import Data.IORef import System.IO.Unsafe import GHC.Conc import Data.Data import Data.Generics.Instances() import Control.DeepSeq gShowConstr :: Data a => a -> String gShowConstr = showConstr . toConstr isLogging :: IORef Bool isLogging = unsafePerformIO (newIORef False) logger :: IORef ([(Int,Maybe String)]) {-# NOINLINE logger #-} logger = unsafePerformIO (newIORef []) class Data a => Log a where log :: String -> a -> a log x = let entry = (read x ::Int,Just $ gShowConstr x) in pseq (unsafePerformIO $ do b <- readIORef isLogging if b then modifyIORef' logger $ deepseq entry (entry :) else return ()) instance (Data a,Data b) => Log (a -> b) where log x = let entry = (read x :: Int,Nothing :: Maybe String) in pseq (unsafePerformIO $ do b <- readIORef isLogging if b then modifyIORef' logger $ deepseq entry (entry:) else return ()) instance Data a => Log a where {} {- class Log a where log :: String -> a -> a log x = pseq (unsafePerformIO $ modifyIORef logger $ (++ [(read x ::Int,Nothing)])) instance Log Bool where log x b = pseq (unsafePerformIO $ modifyIORef logger $ (++ [(read x :: Int,Just $ show b)])) b instance Log a where {} -}
shayan-najd/QuickCover
QuickCover/Log.hs
bsd-3-clause
1,569
0
17
499
386
202
184
32
1
{-# LANGUAGE GADTs #-} module Math.IRT.MLE.Internal.Generic ( MLEResult (..) , generic_mleEst , logLike ) where import Numeric.AD (Mode, Scalar) import Numeric.AD.Halley import Statistics.Distribution (Distribution, ContDistr) import Math.IRT.Fisher import Math.IRT.Internal.Distribution import Math.IRT.Internal.LogLikelihood import Math.IRT.MLE.Internal.MLEResult generic_mleEst :: (Distribution d, ContDistr d, DensityDeriv d, LogLikelihood d) => [Bool] -> [d] -> Int -> Double -> MLEResult generic_mleEst rs params steps vTheta = let est = (!! steps) $ extremumNoEq (logLike rs params) vTheta fisher = fisherInfoObserved est rs params in case fisher of (FisherInfo _ t s) -> MLEResult est t s logLike :: (Mode a, Floating a, Scalar a ~ Double, Distribution d, LogLikelihood d) => [Bool] -> [d] -> a -> a logLike responses params vTheta = let logLik = zipWith (\a b -> logLikelihood a b vTheta) responses params bmePrior = 1 in sum logLik + log bmePrior
argiopetech/irt
Math/IRT/MLE/Internal/Generic.hs
bsd-3-clause
1,018
0
12
199
347
191
156
23
1
module Syntax where data Clo = Bool Bool | Int Integer | Float Double | Symbol String | Keyword String | String String | List [Clo] | Vector [Clo] deriving (Eq, Ord) showClo :: Clo -> String showClo (Int i) = show i showClo (Float f) = show f showClo (Symbol s) = s showClo (Keyword s) = ":" ++ s showClo (String s) = show s showClo (List l) = "(" ++ unwords (map showClo l) ++ ")" showClo (Vector v) = "[" ++ unwords (map showClo v) ++ "]" instance Show Clo where show = showClo
ak1t0/Clover
src/Syntax.hs
bsd-3-clause
555
0
9
173
236
123
113
19
1
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS -Wall -fwarn-tabs -fno-warn-type-defaults -fno-warn-unused-do-bind #-} module Process where import System.Cmd import System.Exit import System.Process compileP :: String -> IO String -> IO FilePath -> IO ExitCode compileP name opt src = do src' <- src opt' <- opt case src' of [] -> do putStrLn "No source files found" return ExitSuccess _ -> system $ "javac -d ./target/" ++ name ++ " -classpath " ++ opt' ++ ". " ++ ( src')
mike-k-houghton/Builder
src/Process.hs
bsd-3-clause
578
0
15
183
133
66
67
16
2
{-# OPTIONS_GHC -fno-warn-orphans#-} ----------------------------------------------------------------------------- -- -- Module : Language.Haskell.Exts.QuickCheck.Arbitratry -- Copyright : (c) 2012 Lars Corbijn -- License : BSD-style (see the file /LICENSE) -- -- Maintainer : -- Stability : -- Portability : -- -- | Defines arbitrary instances for haskell-src-exts elements using the -- generators and shrinkers from "Language.Haskell.Exts.QuickCheck.Generators" -- ----------------------------------------------------------------------------- module Test.QuickCheck.Instances.HaskellSrcExts.Arbitratry ( ) where ----------------------------------------------------------------------------- import Test.QuickCheck import Language.Haskell.Exts.Syntax import Test.QuickCheck.Instances.HaskellSrcExts.Generators ----------------------------------------------------------------------------- -- Module ----------------------------------------------------------------------------- -- WarningText instance Arbitrary WarningText where arbitrary = warningTextGen shrink = shrinkWarningText ----------------------------------------------------------------------------- -- ExportSpec -- ImportDecl -- ImportSpec ----------------------------------------------------------------------------- -- Assoc instance Arbitrary Assoc where arbitrary = assocGen ----------------------------------------------------------------------------- -- Decl -- Binds -- IPBind -- ClassDecl -- InstDecl -- Deriving (Maybe this could be arbitrary?) -- DataOrNew (Cannot be arbitrary) -- ConDecl -- QualConDecl -- GadtDecl -- BangType -- Match -- Rhs -- GuardedRhs -- Context -- FunDep -- Asst -- Type ----------------------------------------------------------------------------- -- Boxed instance Arbitrary Boxed where arbitrary = boxedGen shrink = shrinkBoxed ----------------------------------------------------------------------------- -- Kind -- TyVarBind -- Exp -- Stmt -- QualStmt -- FieldUpdate -- Alt -- GuardedAlts -- GuardedAlt -- XAttr -- Pat -- PatField -- PXAttr -- RPat -- RPatOp ----------------------------------------------------------------------------- -- Literal instance Arbitrary Literal where arbitrary = literalGen ----------------------------------------------------------------------------- instance Arbitrary ModuleName where arbitrary = moduleNameGen Default shrink = shrinkModuleName ----------------------------------------------------------------------------- -- QName instance Arbitrary QName where arbitrary = qnameGen Default ----------------------------------------------------------------------------- -- Name instance Arbitrary Name where arbitrary = nameGen Default ----------------------------------------------------------------------------- -- QOp instance Arbitrary QOp where arbitrary = qopGen Default -- Op instance Arbitrary Op where arbitrary = opGen Default ----------------------------------------------------------------------------- -- SpecialCon instance Arbitrary SpecialCon where arbitrary = specialConGen ----------------------------------------------------------------------------- -- CName, as far as it's usefull instance Arbitrary CName where arbitrary = cnameGen Default ----------------------------------------------------------------------------- -- IPName -- XName -- Bracket -- Splice ----------------------------------------------------------------------------- instance Arbitrary Safety where arbitrary = safetyGen shrink = shrinkSafety instance Arbitrary CallConv where arbitrary = callConvGen ----------------------------------------------------------------------------- -- ModulePragma -- Tool -- Rule -- RuleVar -- Activation -- Annotation -----------------------------------------------------------------------------
Laar/haskell-src-exts-quickcheck
src/Test/QuickCheck/Instances/HaskellSrcExts/Arbitratry.hs
bsd-3-clause
3,888
0
6
453
330
223
107
35
0
module Convert.Misc.String ( NodeLabel , showNodeLabel , showValue , showBools , showBool ) where import Cryptol.Utils.PP (pretty) import Cryptol.Eval.Value (Value, WithBase(WithBase), defaultPPOpts, useAscii) type NodeLabel = Either [Bool] Value showNodeLabel :: NodeLabel -> String showNodeLabel = either showBools showValue showValue :: Value -> String showValue = pretty . WithBase defaultPPOpts { useAscii = True } showBools :: [Bool] -> String showBools = concatMap showBool showBool :: Bool -> String showBool False = "0" showBool True = "1"
GaloisInc/cryfsm
Convert/Misc/String.hs
bsd-3-clause
568
0
8
96
166
97
69
18
1
{-# LANGUAGE Trustworthy #-} module Pipes.Serial ( -- * Serial Ports fromSerial , toSerial -- * Re-exports -- $reexports , module System.Hardware.Serialport ) where import Control.Monad.IO.Class import Control.Monad (void) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy.Internal as I import System.Hardware.Serialport import Pipes fromSerial :: MonadIO m => SerialPort -> Producer' BS.ByteString m r fromSerial h = liftIO (recv h I.defaultChunkSize) >~ cat {-# INLINEABLE fromSerial #-} {-# RULES "fromSerial h >-> p" forall h p . fromSerial h >-> p = liftIO (recv h I.defaultChunkSize) >~ p #-} toSerial :: MonadIO m => SerialPort -> Consumer' BS.ByteString m r toSerial h = for cat $ \bs -> liftIO (void $ send h bs) {-# INLINEABLE toSerial #-} {-# RULES "p >-> toSerial" forall p h . p >-> toSerial h = for p (\bs -> liftIO (void $ send h bs)) #-} -- $reexports
kvanberendonck/pipes-serial
src/Pipes/Serial.hs
bsd-3-clause
985
0
10
235
184
107
77
22
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE CPP #-} -- | Internal utilities. module Safe.Util( fromNoteModule, fromNoteEitherModule, liftMay, (.^), (.^^), (.^^^), eitherToMaybe, withFrozenCallStack ) where import Data.Maybe import Safe.Partial -- Let things work through ghci alone #if __GLASGOW_HASKELL__ >= 800 import GHC.Stack #else withFrozenCallStack :: a -> a withFrozenCallStack = id #endif (.^) :: Partial => (b -> c) -> (a1 -> a2 -> b) -> a1 -> a2 -> c (.^) f g x1 x2 = f (g x1 x2) (.^^) :: Partial => (b -> c) -> (a1 -> a2 -> a3 -> b) -> a1 -> a2 -> a3 -> c (.^^) f g x1 x2 x3 = f (g x1 x2 x3) (.^^^) :: Partial => (b -> c) -> (a1 -> a2 -> a3 -> a4 -> b) -> a1 -> a2 -> a3 -> a4 -> c (.^^^) f g x1 x2 x3 x4 = f (g x1 x2 x3 x4) liftMay :: (a -> Bool) -> (a -> b) -> (a -> Maybe b) liftMay test func val = if test val then Nothing else Just $ func val fromNoteModule :: Partial => String -> String -> String -> Maybe a -> a fromNoteModule modu note func = fromMaybe (error msg) where msg = modu ++ "." ++ func ++ (if null note then "" else ", " ++ note) fromNoteEitherModule :: Partial => String -> String -> String -> Either String a -> a fromNoteEitherModule modu note func = either (error . msg) id where msg ex = modu ++ "." ++ func ++ " " ++ ex ++ (if null note then "" else ", " ++ note) eitherToMaybe :: Either a b -> Maybe b eitherToMaybe = either (const Nothing) Just
ndmitchell/safe
Safe/Util.hs
bsd-3-clause
1,478
0
12
351
606
326
280
29
2
{-# LANGUAGE OverloadedStrings #-} {- | Module : Network.MPD.Commands.Database Copyright : (c) Ben Sinclair 2005-2009, Joachim Fasting 2012 License : MIT (see LICENSE) Maintainer : joachim.fasting@gmail.com Stability : stable Portability : unportable The music database. -} module Network.MPD.Commands.Database ( count , find , findAdd , list , listAll , listAllInfo , lsInfo , search , update , rescan ) where import qualified Network.MPD.Applicative.Internal as A import qualified Network.MPD.Applicative.Database as A import Network.MPD.Commands.Query import Network.MPD.Commands.Types import Network.MPD.Core -- | Count the number of entries matching a query. count :: MonadMPD m => Query -> m Count count = A.runCommand . A.count -- | Search the database for entries exactly matching a query. find :: MonadMPD m => Query -> m [Song] find = A.runCommand . A.find -- | Adds songs matching a query to the current playlist. findAdd :: MonadMPD m => Query -> m () findAdd = A.runCommand . A.findAdd -- | List all tags of the specified type. list :: MonadMPD m => Metadata -- ^ Metadata to list -> Maybe Artist -> m [Value] list m = A.runCommand . A.list m -- | List the songs (without metadata) in a database directory recursively. listAll :: MonadMPD m => Path -> m [Path] listAll = A.runCommand . A.listAll -- | Recursive 'lsInfo'. listAllInfo :: MonadMPD m => Path -> m [LsResult] listAllInfo = A.runCommand . A.listAllInfo -- | Non-recursively list the contents of a database directory. lsInfo :: MonadMPD m => Path -> m [LsResult] lsInfo = A.runCommand . A.lsInfo -- | Search the database using case insensitive matching. search :: MonadMPD m => Query -> m [Song] search = A.runCommand . A.search -- | Update the server's database. -- -- If no path is given, the whole library will be scanned. Unreadable or -- non-existent paths are silently ignored. -- -- The update job id is returned. update :: MonadMPD m => Maybe Path -> m Integer update = A.runCommand . A.update -- | Like 'update' but also rescans unmodified files. rescan :: MonadMPD m => Maybe Path -> m Integer rescan = A.runCommand . A.rescan
beni55/libmpd-haskell
src/Network/MPD/Commands/Database.hs
mit
2,224
0
9
462
457
255
202
39
1
module Crypto.Gpgme.Crypto ( encrypt , encryptSign , encryptFd , encryptSignFd , encrypt' , encryptSign' , decrypt , decryptFd , decryptVerifyFd , decrypt' , decryptVerify , decryptVerify' , verify , verify' , verifyDetached , verifyDetached' , verifyPlain , verifyPlain' , sign ) where import System.Posix.Types (Fd(Fd)) import Bindings.Gpgme import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as C8 import Control.Monad (liftM) import Control.Monad.Trans.Except (ExceptT(ExceptT), runExceptT, mapExceptT) import Foreign import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) import GHC.Ptr import Crypto.Gpgme.Ctx import Crypto.Gpgme.Internal import Crypto.Gpgme.Key import Crypto.Gpgme.Types locale :: String locale = "C" -- | Convenience wrapper around 'withCtx' and 'withKey' to -- encrypt a single plaintext for a single recipient with -- its homedirectory. encrypt' :: String -> Fpr -> Plain -> IO (Either String Encrypted) encrypt' = encryptIntern' encrypt -- | Convenience wrapper around 'withCtx' and 'withKey' to -- encrypt and sign a single plaintext for a single recipient -- with its homedirectory. encryptSign' :: String -> Fpr -> Plain -> IO (Either String Encrypted) encryptSign' = encryptIntern' encryptSign orElse :: Monad m => m (Maybe a) -> e -> ExceptT e m a orElse action err = ExceptT $ maybe (Left err) return `liftM` action bimapExceptT :: Functor m => (x -> y) -> (a -> b) -> ExceptT x m a -> ExceptT y m b bimapExceptT f g = mapExceptT (fmap h) where h (Left e) = Left (f e) h (Right a) = Right (g a) encryptIntern' :: (Ctx -> [Key] -> Flag -> Plain -> IO (Either [InvalidKey] Encrypted) ) -> String -> Fpr -> Plain -> IO (Either String Encrypted) encryptIntern' encrFun gpgDir recFpr plain = withCtx gpgDir locale OpenPGP $ \ctx -> runExceptT $ do pubKey <- getKey ctx recFpr NoSecret `orElse` ("no such key: " ++ show recFpr) bimapExceptT show id $ ExceptT $ encrFun ctx [pubKey] NoFlag plain -- | encrypt for a list of recipients encrypt :: Ctx -> [Key] -> Flag -> Plain -> IO (Either [InvalidKey] Encrypted) encrypt = encryptIntern c'gpgme_op_encrypt -- | encrypt and sign for a list of recipients encryptSign :: Ctx -> [Key] -> Flag -> Plain -> IO (Either [InvalidKey] Encrypted) encryptSign = encryptIntern c'gpgme_op_encrypt_sign encryptIntern :: (C'gpgme_ctx_t -> GHC.Ptr.Ptr C'gpgme_key_t -> C'gpgme_encrypt_flags_t -> C'gpgme_data_t -> C'gpgme_data_t -> IO C'gpgme_error_t ) -> Ctx -> [Key] -> Flag -> Plain -> IO (Either [InvalidKey] Encrypted) encryptIntern enc_op (Ctx {_ctx=ctxPtr}) recPtrs flag plain = do -- init buffer with plaintext plainBufPtr <- malloc BS.useAsCString plain $ \bs -> do let copyData = 1 -- gpgme shall copy data, as bytestring will free it let plainlen = fromIntegral (BS.length plain) ret <- c'gpgme_data_new_from_mem plainBufPtr bs plainlen copyData checkError "data_new_from_mem" ret plainBuf <- peek plainBufPtr -- init buffer for result resultBufPtr <- newDataBuffer resultBuf <- peek resultBufPtr ctx <- peek ctxPtr -- encrypt withKeyPtrArray recPtrs $ \recArray -> checkError "op_encrypt" =<< enc_op ctx recArray (fromFlag flag) plainBuf resultBuf free plainBufPtr -- check whether all keys could be used for encryption encResPtr <- c'gpgme_op_encrypt_result ctx encRes <- peek encResPtr let recPtr = c'_gpgme_op_encrypt_result'invalid_recipients encRes let res = if recPtr /= nullPtr then Left (collectFprs recPtr) else Right (collectResult resultBuf) free resultBufPtr return res -- | Encrypt plaintext encryptFd :: Ctx -> [Key] -> Flag -> Fd -> Fd -> IO (Either [InvalidKey] ()) encryptFd = encryptFdIntern c'gpgme_op_encrypt -- | Encrypt and sign plaintext encryptSignFd :: Ctx -> [Key] -> Flag -> Fd -> Fd -> IO (Either [InvalidKey] ()) encryptSignFd = encryptFdIntern c'gpgme_op_encrypt_sign encryptFdIntern :: (C'gpgme_ctx_t -> GHC.Ptr.Ptr C'gpgme_key_t -> C'gpgme_encrypt_flags_t -> C'gpgme_data_t -> C'gpgme_data_t -> IO C'gpgme_error_t ) -> Ctx -> [Key] -> Flag -> Fd -- ^ Plaintext data -> Fd -- ^ Ciphertext data -> IO (Either [InvalidKey] ()) encryptFdIntern enc_op (Ctx {_ctx=ctxPtr}) recPtrs flag (Fd plainCInt) (Fd cipherCInt) = do -- Initialize plaintext buffer plainBufPtr <- malloc _ <- c'gpgme_data_new_from_fd plainBufPtr plainCInt plainBuf <- peek plainBufPtr -- Initialize ciphertext buffer cipherBufPtr <- malloc _ <- c'gpgme_data_new_from_fd cipherBufPtr cipherCInt cipherBuf <- peek cipherBufPtr ctx <- peek ctxPtr -- encrypt withKeyPtrArray recPtrs $ \recArray -> checkError "op_encrypt" =<< enc_op ctx recArray (fromFlag flag) plainBuf cipherBuf free plainBufPtr -- check whether all keys could be used for encryption encResPtr <- c'gpgme_op_encrypt_result ctx encRes <- peek encResPtr let recPtr = c'_gpgme_op_encrypt_result'invalid_recipients encRes let res = if recPtr /= nullPtr then Left (collectFprs recPtr) else Right (()) free cipherBufPtr return res -- | Build a null-terminated array of pointers from a list of 'Key's withKeyPtrArray :: [Key] -> (Ptr C'gpgme_key_t -> IO a) -> IO a withKeyPtrArray [] f = f nullPtr withKeyPtrArray keys f = do arr <- newArray0 nullPtr =<< mapM (peek . unsafeForeignPtrToPtr . unKey) keys f arr -- | Convenience wrapper around 'withCtx' and 'withKey' to -- decrypt a single ciphertext with its homedirectory. decrypt' :: String -> Encrypted -> IO (Either DecryptError Plain) decrypt' = decryptInternal' decrypt -- | Convenience wrapper around 'withCtx' and 'withKey' to -- decrypt and verify a single ciphertext with its homedirectory. decryptVerify' :: String -> Encrypted -> IO (Either DecryptError Plain) decryptVerify' = decryptInternal' decryptVerify decryptInternal' :: (Ctx -> Encrypted -> IO (Either DecryptError Plain)) -> String -> Encrypted -> IO (Either DecryptError Plain) decryptInternal' decrFun gpgDir cipher = withCtx gpgDir locale OpenPGP $ \ctx -> decrFun ctx cipher -- | Decrypts a ciphertext decrypt :: Ctx -> Encrypted -> IO (Either DecryptError Plain) decrypt = decryptIntern c'gpgme_op_decrypt -- | Decrypts and verifies a ciphertext decryptVerify :: Ctx -> Encrypted -> IO (Either DecryptError Plain) decryptVerify = decryptIntern c'gpgme_op_decrypt_verify decryptIntern :: (C'gpgme_ctx_t -> C'gpgme_data_t -> C'gpgme_data_t -> IO C'gpgme_error_t ) -> Ctx -> Encrypted -> IO (Either DecryptError Plain) decryptIntern dec_op (Ctx {_ctx=ctxPtr}) cipher = do -- init buffer with cipher cipherBufPtr <- malloc BS.useAsCString cipher $ \bs -> do let copyData = 1 -- gpgme shall copy data, as bytestring will free it let cipherlen = fromIntegral (BS.length cipher) ret <- c'gpgme_data_new_from_mem cipherBufPtr bs cipherlen copyData checkError "data_new_from_mem" ret cipherBuf <- peek cipherBufPtr -- init buffer for result resultBufPtr <- newDataBuffer resultBuf <- peek resultBufPtr ctx <- peek ctxPtr -- decrypt errcode <- dec_op ctx cipherBuf resultBuf let res = if errcode /= noError then Left (toDecryptError errcode) else Right (collectResult resultBuf) free cipherBufPtr free resultBufPtr return res -- | Decrypt a ciphertext decryptFd :: Ctx -> Fd -> Fd -> IO (Either DecryptError ()) decryptFd = decryptFdIntern c'gpgme_op_decrypt -- | Decrypt and verify ciphertext decryptVerifyFd :: Ctx -> Fd -> Fd -> IO (Either DecryptError ()) decryptVerifyFd = decryptFdIntern c'gpgme_op_decrypt_verify decryptFdIntern :: (C'gpgme_ctx_t -> C'gpgme_data_t -> C'gpgme_data_t -> IO C'gpgme_error_t ) -> Ctx -> Fd -> Fd -> IO (Either DecryptError ()) decryptFdIntern dec_op (Ctx {_ctx=ctxPtr}) (Fd cipherCInt) (Fd plainCInt)= do -- Initialize ciphertext buffer cipherBufPtr <- malloc _ <- c'gpgme_data_new_from_fd cipherBufPtr cipherCInt cipherBuf <- peek cipherBufPtr -- Initialize plaintext buffer plainBufPtr <- malloc _ <- c'gpgme_data_new_from_fd plainBufPtr plainCInt plainBuf <- peek plainBufPtr ctx <- peek ctxPtr -- decrypt errcode <- dec_op ctx cipherBuf plainBuf let res = if errcode /= noError then Left (toDecryptError errcode) else Right (()) free cipherBufPtr free plainBufPtr return res -- | Sign plaintext for a list of signers sign :: Ctx -- ^ Context to sign -> [Key] -- ^ Keys to used for signing. An empty list will use context's default key. -> SignMode -- ^ Signing mode -> Plain -- ^ Plain text to sign -> IO (Either [InvalidKey] Plain) sign = signIntern c'gpgme_op_sign signIntern :: ( C'gpgme_ctx_t -> C'gpgme_data_t -> C'gpgme_data_t -> C'gpgme_sig_mode_t -> IO C'gpgme_error_t ) -- ^ c'gpgme_op_sign type signature -> Ctx -> [Key] -> SignMode -> Plain -> IO (Either [InvalidKey] Encrypted) signIntern sign_op (Ctx {_ctx=ctxPtr}) signPtrs mode plain = do -- init buffer with plaintext plainBufPtr <- malloc BS.useAsCString plain $ \bs -> do let copyData = 1 -- gpgme shall copy data, as bytestring will free it let plainlen = fromIntegral (BS.length plain) ret <- c'gpgme_data_new_from_mem plainBufPtr bs plainlen copyData checkError "data_new_from_mem" ret plainBuf <- peek plainBufPtr -- init buffer for result resultBufPtr <- newDataBuffer resultBuf <- peek resultBufPtr ctx <- peek ctxPtr -- add signing keys _ <- mapM ( \kForPtr -> withForeignPtr (unKey kForPtr) (\kPtr -> do k <- peek kPtr c'gpgme_signers_add ctx k ) ) signPtrs -- sign let modeCode = case mode of Normal -> c'GPGME_SIG_MODE_NORMAL Detach -> c'GPGME_SIG_MODE_DETACH Clear -> c'GPGME_SIG_MODE_CLEAR checkError "op_sign" =<< sign_op ctx plainBuf resultBuf modeCode free plainBufPtr -- check whether all keys could be used for signingi signResPtr <- c'gpgme_op_sign_result ctx signRes <- peek signResPtr let recPtr = c'_gpgme_op_sign_result'invalid_signers signRes let res = if recPtr /= nullPtr then Left (collectFprs recPtr) else Right (collectResult resultBuf) free resultBufPtr return res -- | Verify a payload with a detached signature verifyDetached :: Ctx -- ^ GPG context -> Signature -- ^ Detached signature -> BS.ByteString -- ^ Signed text -> IO (Either GpgmeError VerificationResult) verifyDetached ctx sig dat = do res <- verifyInternal go ctx sig dat return $ fmap fst res where go ctx' sig' dat' = do errcode <- c'gpgme_op_verify ctx' sig' dat' 0 return (errcode, ()) -- | Convenience wrapper around 'withCtx' to -- verify a single detached signature with its homedirectory. verifyDetached' :: String -- ^ GPG context home directory -> Signature -- ^ Detached signature -> BS.ByteString -- ^ Signed text -> IO (Either GpgmeError VerificationResult) verifyDetached' gpgDir sig dat = withCtx gpgDir locale OpenPGP $ \ctx -> verifyDetached ctx sig dat {-# DEPRECATED verifyPlain "Use verify" #-} verifyPlain :: Ctx -> Signature -> BS.ByteString -> IO (Either GpgmeError (VerificationResult, BS.ByteString)) verifyPlain c s _ = verify c s {-# DEPRECATED verifyPlain' "Use verify'" #-} verifyPlain' :: String -> Signature -> BS.ByteString -> IO (Either GpgmeError (VerificationResult, BS.ByteString)) verifyPlain' str sig _ = verify' str sig -- | Verify a payload with a plain signature verify :: Ctx -> Signature -> IO (Either GpgmeError (VerificationResult, BS.ByteString)) verify c s = verifyInternal go c s (C8.pack "") where go ctx sig _ = do -- init buffer for result resultBufPtr <- newDataBuffer resultBuf <- peek resultBufPtr errcode <- c'gpgme_op_verify ctx sig 0 resultBuf let res = if errcode /= noError then mempty else collectResult resultBuf free resultBufPtr return (errcode, res) -- | Convenience wrapper around 'withCtx' to -- verify a single plain signature with its homedirectory. verify' :: String -> Signature -> IO (Either GpgmeError (VerificationResult, BS.ByteString)) verify' gpgDir sig = withCtx gpgDir locale OpenPGP $ \ctx -> verify ctx sig verifyInternal :: ( C'gpgme_ctx_t -> C'gpgme_data_t -> C'gpgme_data_t -> IO (C'gpgme_error_t, a) ) -> Ctx -> Signature -> BS.ByteString -> IO (Either GpgmeError (VerificationResult, a)) verifyInternal ver_op (Ctx {_ctx=ctxPtr}) sig dat = do -- init buffer with signature sigBufPtr <- malloc BS.useAsCString sig $ \bs -> do let copyData = 1 -- gpgme shall copy data, as bytestring will free it let siglen = fromIntegral (BS.length sig) ret <- c'gpgme_data_new_from_mem sigBufPtr bs siglen copyData checkError "data_new_from_mem" ret sigBuf <- peek sigBufPtr -- init buffer with data datBufPtr <- malloc BS.useAsCString dat $ \bs -> do let copyData = 1 -- gpgme shall copy data, as bytestring will free it let datlen = fromIntegral (BS.length dat) ret <- c'gpgme_data_new_from_mem datBufPtr bs datlen copyData checkError "data_new_from_mem" ret datBuf <- peek datBufPtr ctx <- peek ctxPtr -- verify (errcode, res) <- ver_op ctx sigBuf datBuf sigs <- collectSignatures' ctx let res' = if errcode /= noError then Left (GpgmeError errcode) else Right (sigs, res) free sigBufPtr free datBufPtr return res' newDataBuffer :: IO (Ptr C'gpgme_data_t) newDataBuffer = do resultBufPtr <- malloc checkError "data_new" =<< c'gpgme_data_new resultBufPtr return resultBufPtr
mmhat/h-gpgme
src/Crypto/Gpgme/Crypto.hs
mit
15,418
0
17
4,494
3,749
1,858
1,891
319
4
module Common where import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.Connect import Control.Monad.Reader rr :: Connection -> ReaderT Connection IO a -> IO a rr conn r = runReaderT r conn setupPG :: IO Connection setupPG = do cfg <- configFromEnv createConn' cfg
filopodia/open
postgresql-simple-expr/tests/Common.hs
mit
288
0
7
46
87
46
41
10
1
-- | Module for safe (zero-memory) signing. module Pos.Crypto.Signing.Safe ( changeEncPassphrase , safeSign , safeToPublic , safeKeyGen , safeDeterministicKeyGen , withSafeSigner , withSafeSignerUnsafe , withSafeSigners , fakeSigner , safeCreateProxyCert , safeCreatePsk , createProxyCert , createPsk , module Pos.Crypto.Signing.Types.Safe ) where import Universum import qualified Cardano.Crypto.Wallet as CC import Crypto.Random (MonadRandom, getRandomBytes) import qualified Data.ByteString as BS import Data.Coerce (coerce) import Pos.Binary.Class (Bi, Raw) import qualified Pos.Binary.Class as Bi import Pos.Crypto.Configuration (ProtocolMagic) import Pos.Crypto.Hashing (hash) import qualified Pos.Crypto.Scrypt as S import Pos.Crypto.Signing.Signing (ProxyCert (..), ProxySecretKey (..), PublicKey (..), SecretKey (..), Signature (..), sign, toPublic) import Pos.Crypto.Signing.Tag (SignTag (SignProxySK), signTag) import Pos.Crypto.Signing.Types.Safe -- | Regenerates secret key with new passphrase. -- Note: This operation keeps corresponding public key and derived (child) keys unchanged. changeEncPassphrase :: (MonadRandom m) => PassPhrase -> PassPhrase -> EncryptedSecretKey -> m (Maybe EncryptedSecretKey) changeEncPassphrase oldPass newPass esk@(EncryptedSecretKey sk _) | isJust $ checkPassMatches oldPass esk = Just <$> mkEncSecretUnsafe newPass (CC.xPrvChangePass oldPass newPass sk) | otherwise = return Nothing signRaw' :: ProtocolMagic -> Maybe SignTag -> PassPhrase -> EncryptedSecretKey -> ByteString -> Signature Raw signRaw' pm mbTag (PassPhrase pp) (EncryptedSecretKey sk _) x = Signature (CC.sign pp sk (tag <> x)) where tag = maybe mempty (signTag pm) mbTag sign' :: (Bi a) => ProtocolMagic -> SignTag -> PassPhrase -> EncryptedSecretKey -> a -> Signature a sign' pm t pp sk = coerce . signRaw' pm (Just t) pp sk . Bi.serialize' safeCreateKeypairFromSeed :: BS.ByteString -> PassPhrase -> (CC.XPub, CC.XPrv) safeCreateKeypairFromSeed seed (PassPhrase pp) = let prv = CC.generate seed pp in (CC.toXPub prv, prv) -- NB. It's recommended to run it with 'runSecureRandom' from -- "Pos.Crypto.Random" because the OpenSSL generator is probably safer than -- the default IO generator. safeKeyGen :: (MonadRandom m) => PassPhrase -> m (PublicKey, EncryptedSecretKey) safeKeyGen pp = do seed <- getRandomBytes 32 pure $ safeDeterministicKeyGen seed pp safeDeterministicKeyGen :: BS.ByteString -> PassPhrase -> (PublicKey, EncryptedSecretKey) safeDeterministicKeyGen seed pp = bimap PublicKey (mkEncSecretWithSaltUnsafe (S.mkSalt (hash seed)) pp) (safeCreateKeypairFromSeed seed pp) safeSign :: (Bi a) => ProtocolMagic -> SignTag -> SafeSigner -> a -> Signature a safeSign pm t (SafeSigner sk pp) = sign' pm t pp sk safeSign pm t (FakeSigner sk) = sign pm t sk safeToPublic :: SafeSigner -> PublicKey safeToPublic (SafeSigner sk _) = encToPublic sk safeToPublic (FakeSigner sk) = toPublic sk -- | We can make SafeSigner only inside IO bracket, so -- we can manually cleanup all IO buffers we use to store passphrase -- (when we'll actually use them) withSafeSigners :: (Monad m, Traversable t) => t EncryptedSecretKey -> m PassPhrase -> (t SafeSigner -> m a) -> m a withSafeSigners sks ppGetter action = do pp <- ppGetter let mss = map (\sk -> SafeSigner sk pp) sks action mss withSafeSigner :: (Monad m) => EncryptedSecretKey -> m PassPhrase -> (Maybe SafeSigner -> m a) -> m a withSafeSigner sk ppGetter action = do pp <- ppGetter withSafeSigners (Identity sk) (pure pp) $ action . (checkPassMatches pp sk $>) . runIdentity -- This function is like @withSafeSigner@ but doesn't check @checkPassMatches@ withSafeSignerUnsafe :: (Monad m) => EncryptedSecretKey -> m PassPhrase -> (SafeSigner -> m a) -> m a withSafeSignerUnsafe sk ppGetter action = do pp <- ppGetter withSafeSigners (Identity sk) (pure pp) $ action . runIdentity -- | We need this to be able to perform signing with unencrypted `SecretKey`s, -- where `SafeSigner` is required fakeSigner :: SecretKey -> SafeSigner fakeSigner = FakeSigner -- | Proxy certificate creation from secret key of issuer, public key -- of delegate and the message space ω. safeCreateProxyCert :: (Bi w) => ProtocolMagic -> SafeSigner -> PublicKey -> w -> ProxyCert w safeCreateProxyCert pm ss (PublicKey delegatePk) o = coerce $ ProxyCert sig where Signature sig = safeSign pm SignProxySK ss $ mconcat ["00", CC.unXPub delegatePk, Bi.serialize' o] -- | Creates proxy secret key safeCreatePsk :: (Bi w) => ProtocolMagic -> SafeSigner -> PublicKey -> w -> ProxySecretKey w safeCreatePsk pm ss delegatePk w = UnsafeProxySecretKey { pskOmega = w , pskIssuerPk = safeToPublic ss , pskDelegatePk = delegatePk , pskCert = safeCreateProxyCert pm ss delegatePk w } -- [CSL-1157] `createProxyCert` and `createProxySecretKey` are not safe and -- left here because of their implementation details -- in future should be removed completely, now left for compatibility with tests -- | Proxy certificate creation from secret key of issuer, public key -- of delegate and the message space ω. createProxyCert :: (Bi w) => ProtocolMagic -> SecretKey -> PublicKey -> w -> ProxyCert w createProxyCert pm = safeCreateProxyCert pm . fakeSigner -- | Creates proxy secret key createPsk :: (Bi w) => ProtocolMagic -> SecretKey -> PublicKey -> w -> ProxySecretKey w createPsk pm = safeCreatePsk pm . fakeSigner
input-output-hk/pos-haskell-prototype
crypto/Pos/Crypto/Signing/Safe.hs
mit
5,994
0
13
1,425
1,464
782
682
127
1
{-# LANGUAGE ExistentialQuantification, DeriveDataTypeable , OverlappingInstances #-} {- | Module : ./TopHybrid/AS_TopHybrid.der.hs License : GPLv2 or higher, see LICENSE.txt Maintainer : nevrenato@gmail.com Stability : experimental Portability : portable Description : Abstract syntax for an hybridized logic. Declaration of the basic specification. Underlying Spec; Declaration of nominals and modalities, and axioms. -} module TopHybrid.AS_TopHybrid where import Common.AS_Annotation import Common.Id import Common.Json import Common.ToXml import Logic.Logic import Unsafe.Coerce import Data.Data import Data.Monoid import Text.XML.Light -- DrIFT command {-! global: GetRange !-} {- Union of the the declaration of nominals/modalities and the spec correspondent to the underlying logic -} data TH_BSPEC s = Bspec { bitems :: [TH_BASIC_ITEM], und :: s } deriving (Show, Typeable, Data) -- Declaration of nominals/modalities data TH_BASIC_ITEM = Simple_mod_decl [MODALITY] | Simple_nom_decl [NOMINAL] deriving (Show, Typeable, Data) type MODALITY = SIMPLE_ID type NOMINAL = SIMPLE_ID {- The strucuture of an hybridized sentence, where f correponds to the underlying logic -} data TH_FORMULA f = At NOMINAL (TH_FORMULA f) | Uni NOMINAL (TH_FORMULA f) | Exist NOMINAL (TH_FORMULA f) | Box MODALITY (TH_FORMULA f) | Dia MODALITY (TH_FORMULA f) | UnderLogic f | Conjunction (TH_FORMULA f) (TH_FORMULA f) | Disjunction (TH_FORMULA f) (TH_FORMULA f) | Implication (TH_FORMULA f) (TH_FORMULA f) | BiImplication (TH_FORMULA f) (TH_FORMULA f) | Here NOMINAL | Neg (TH_FORMULA f) | Par (TH_FORMULA f) | TrueA | FalseA deriving (Show, Eq, Ord, Typeable, Data) instance ToJson f => ToJson (TH_FORMULA f) where asJson _ = mkJObj [] instance ToXml f => ToXml (TH_FORMULA f) where asXml _ = unode "missing" () {- Existential quantification is used, in the Sentences, Spec and Signature because, we need to hide that these datatypes are polymorphic, or else, haskell will complain that their types will vary with the same logic. Which is forbidden in Logic class by using functional dependencies. -} {- An hybridized formula has the hybrid constructors; the constructors of the hybridized logic and the logic identifier, so that we can identify the underlying logic, by only looking to the sentence. -} data Frm_Wrap = forall l sub bs f s sm si mo sy rw pf . (Logic l sub bs f s sm si mo sy rw pf) => Frm_Wrap l (TH_FORMULA f) deriving Typeable instance Show Frm_Wrap where show (Frm_Wrap l f) = "Frm_Wrap " ++ show l ++ " (" ++ show f ++ ")" instance ToJson Frm_Wrap where asJson (Frm_Wrap l f) = mkJObj [("Frm_Wrap:" ++ show l, asJson f)] instance ToXml Frm_Wrap where asXml (Frm_Wrap l f) = add_attr (mkAttr "language" $ show l) $ unode "Frm_Wrap" $ asXml f {- An hybridized specification has the basic specification; The declararation of nominals and modalities, and the axioms; -} data Spc_Wrap = forall l sub bs sen si smi sign mor symb raw pf . (Logic l sub bs sen si smi sign mor symb raw pf) => Spc_Wrap l (TH_BSPEC bs) [Annoted Frm_Wrap] deriving Typeable instance Show Spc_Wrap where show (Spc_Wrap l b a) = "Spc_Wrap " ++ show l ++ " (" ++ show b ++ ") " ++ show a instance Monoid Spc_Wrap where mempty = error "Not implemented!" mappend _ _ = error "Not implemented!" -- --- instances data Mor = Mor deriving (Show, Eq, Ord, Typeable, Data) -- Why do we need to compare specifications ? instance Ord Spc_Wrap where compare _ _ = GT instance Eq Spc_Wrap where (==) _ _ = False -- -------------- -- Who do we need to order formulas ? instance Ord Frm_Wrap where compare a b = if a == b then EQ else GT {- Need to use unsafe coerce here, as the typechecker as no way to know that if l == l' then type f == type f'. However, we know. -} instance Eq Frm_Wrap where (==) (Frm_Wrap l f) (Frm_Wrap l' f') = (show l == show l') && (unsafeCoerce f == f') -- Why do we need range ? instance GetRange Frm_Wrap where getRange (Frm_Wrap _ f) = getRange f rangeSpan (Frm_Wrap _ f) = rangeSpan f instance GetRange Spc_Wrap where getRange (Spc_Wrap _ s _) = getRange s rangeSpan (Spc_Wrap _ s _) = rangeSpan s
spechub/Hets
TopHybrid/AS_TopHybrid.der.hs
gpl-2.0
4,576
0
11
1,175
1,055
567
488
76
0
--Vigenere cipher module Vigenere where import Data.Char chrRg :: Int chrRg = length ['A'..'Z'] encode :: Char -> Int encode = subtract (ord 'A') . ord . toUpper decode :: Int -> Char decode = chr . (ord 'A' +) shiftr :: Char -> Char -> Char shiftr c k = decode $ mod (encode c + encode k) chrRg shiftl :: Char -> Char -> Char shiftl c k = decode $ mod (encode c - encode k) chrRg vigenere :: String -> String -> String vigenere = vigProc shiftr unVigenere :: String -> String -> String unVigenere = vigProc shiftl vigProc :: (Char -> Char -> Char) -> (String -> String -> String) vigProc s cs = vigProc' s cs . cycle vigProc' :: (Char -> Char -> Char) -> (String -> String -> String) vigProc' _ [] _ = [] vigProc' s (c:cs) (k:ks) | isLetter c = s c k : vigProc' s cs ks | otherwise = c : vigProc' s cs (k:ks) encrypt :: IO () encrypt = do putStrLn "Enter message to be encrypted: " mes <- getLine putStrLn "Enter key: " key <- getLine putStrLn "Encrypted message: " putStrLn $ vigenere mes key {- Ex. encrypt Enter message to be encrypted: "Hello, World!" Enter key: "World" Encrypted message: "CAZCZ, ZJMHR!" -} decrypt :: IO () decrypt = do putStrLn "Enter message to be decrypted: " mes <- getLine putStrLn "Enter key: " key <- getLine putStrLn "Decrypted message: " putStrLn $ unVigenere mes key {- Ex. decrypt Enter message to be decrypted: "CAZCZ, ZJMHR!" Enter key: "World" Decrypted message: "HELLO, WORLD!" -}
euronautic/cosmos
code/cryptography/vigenere_cipher/vigenere_cipher.hs
gpl-3.0
1,563
0
9
413
511
253
258
39
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.CognitoIdentity.GetIdentityPoolRoles -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the roles for an identity pool. -- -- You must use AWS Developer credentials to call this API. -- -- /See:/ <http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetIdentityPoolRoles.html AWS API Reference> for GetIdentityPoolRoles. module Network.AWS.CognitoIdentity.GetIdentityPoolRoles ( -- * Creating a Request getIdentityPoolRoles , GetIdentityPoolRoles -- * Request Lenses , giprIdentityPoolId -- * Destructuring the Response , getIdentityPoolRolesResponse , GetIdentityPoolRolesResponse -- * Response Lenses , giprrsRoles , giprrsIdentityPoolId , giprrsResponseStatus ) where import Network.AWS.CognitoIdentity.Types import Network.AWS.CognitoIdentity.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Input to the 'GetIdentityPoolRoles' action. -- -- /See:/ 'getIdentityPoolRoles' smart constructor. newtype GetIdentityPoolRoles = GetIdentityPoolRoles' { _giprIdentityPoolId :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'GetIdentityPoolRoles' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'giprIdentityPoolId' getIdentityPoolRoles :: Text -- ^ 'giprIdentityPoolId' -> GetIdentityPoolRoles getIdentityPoolRoles pIdentityPoolId_ = GetIdentityPoolRoles' { _giprIdentityPoolId = pIdentityPoolId_ } -- | An identity pool ID in the format REGION:GUID. giprIdentityPoolId :: Lens' GetIdentityPoolRoles Text giprIdentityPoolId = lens _giprIdentityPoolId (\ s a -> s{_giprIdentityPoolId = a}); instance AWSRequest GetIdentityPoolRoles where type Rs GetIdentityPoolRoles = GetIdentityPoolRolesResponse request = postJSON cognitoIdentity response = receiveJSON (\ s h x -> GetIdentityPoolRolesResponse' <$> (x .?> "Roles" .!@ mempty) <*> (x .?> "IdentityPoolId") <*> (pure (fromEnum s))) instance ToHeaders GetIdentityPoolRoles where toHeaders = const (mconcat ["X-Amz-Target" =# ("AWSCognitoIdentityService.GetIdentityPoolRoles" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON GetIdentityPoolRoles where toJSON GetIdentityPoolRoles'{..} = object (catMaybes [Just ("IdentityPoolId" .= _giprIdentityPoolId)]) instance ToPath GetIdentityPoolRoles where toPath = const "/" instance ToQuery GetIdentityPoolRoles where toQuery = const mempty -- | Returned in response to a successful 'GetIdentityPoolRoles' operation. -- -- /See:/ 'getIdentityPoolRolesResponse' smart constructor. data GetIdentityPoolRolesResponse = GetIdentityPoolRolesResponse' { _giprrsRoles :: !(Maybe (Map Text Text)) , _giprrsIdentityPoolId :: !(Maybe Text) , _giprrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'GetIdentityPoolRolesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'giprrsRoles' -- -- * 'giprrsIdentityPoolId' -- -- * 'giprrsResponseStatus' getIdentityPoolRolesResponse :: Int -- ^ 'giprrsResponseStatus' -> GetIdentityPoolRolesResponse getIdentityPoolRolesResponse pResponseStatus_ = GetIdentityPoolRolesResponse' { _giprrsRoles = Nothing , _giprrsIdentityPoolId = Nothing , _giprrsResponseStatus = pResponseStatus_ } -- | The map of roles associated with this pool. Currently only authenticated -- and unauthenticated roles are supported. giprrsRoles :: Lens' GetIdentityPoolRolesResponse (HashMap Text Text) giprrsRoles = lens _giprrsRoles (\ s a -> s{_giprrsRoles = a}) . _Default . _Map; -- | An identity pool ID in the format REGION:GUID. giprrsIdentityPoolId :: Lens' GetIdentityPoolRolesResponse (Maybe Text) giprrsIdentityPoolId = lens _giprrsIdentityPoolId (\ s a -> s{_giprrsIdentityPoolId = a}); -- | The response status code. giprrsResponseStatus :: Lens' GetIdentityPoolRolesResponse Int giprrsResponseStatus = lens _giprrsResponseStatus (\ s a -> s{_giprrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-cognito-identity/gen/Network/AWS/CognitoIdentity/GetIdentityPoolRoles.hs
mpl-2.0
5,188
0
14
1,109
688
409
279
88
1
{- Copyright (C) 2013 Peter Caspers This file is part of hql which is a reimplementation of QuantLib, a free-software/open-source library for financial quantitative analysts and developers. Please refer to the documentation available at <http://quantlib.org/> for the original copyright holders. -} -- | This module contains the schedule type definition and helper -- functions to construct schedules. It also contains standard -- conventions for schedule constructions. module Hql.Time.Schedule (Schedule(..), ScheduleConvention, eurSwapFixLegConv, eurSwapFloatLegConv, makeSchedule, schedule ) where import Hql.Time.Date import Hql.Time.Period import Hql.Time.Calendar -- | Rule determining how a schedule is build data DateGenerationRule = Backward | -- ^ Backward from termination date to effective date. Forward | -- ^ Forward from effective date to termination date. Zero | -- ^ No intermediate dates between effective date -- and termination date. ThirdWednesday | -- ^ All dates but effective date and termination -- date are taken to be on the third wednesday -- of their month (with forward calculation.) Twentieth | -- ^ All dates but the effective date are -- taken to be the twentieth of their -- month (used for CDS schedules in -- emerging markets.) The termination -- date is also modified. TwentiethIMM | -- ^ All dates but the effective date are -- taken to be the twentieth of an IMM -- month (used for CDS schedules.) The -- termination date is also modified. OldCDS | -- ^ Same as TwentiethIMM with unrestricted date -- ends and log/short stub coupon period (old -- CDS convention). CDS -- ^ Credit derivatives standard rule since 'Big -- Bang' changes in 2009. deriving (Eq, Show) -- | Schedule definition, it is nothing more than a list of dates type Schedule = [Date] -- | Schedule construction by effective and termination date, period, calendar, business day convention, -- business day convention for termination date, date generation rule, end of month flag, -- first date and next to last date schedule :: Date -- ^ Effective date -> Date -- ^ Termination date -> Period -- ^ Period between dates -> Calendar -- ^ Calendar for date adjustment -> BusinessDayConvention -- ^ Business day convention for date adjustment -> BusinessDayConvention -- ^ Business day convention for termination date adjustment -> DateGenerationRule -- ^ Rule for schedule generation -> Bool -- ^ End of month flag -> Maybe Date -- ^ First date (if not equal to effective date) -> Maybe Date -- ^ Next to last date (if not equal to termination date) -> Schedule -- ^ Resulting schedule schedule effective termination _ _ _ _ Zero _ _ _ = [effective, termination] schedule effective termination (Period n unit) calendar bdc terminationBdc Backward eom first nextToLast = nubSorted ([effective] ++ (backward 1) ++ [(adjust calendar seed bdc), (adjust calendar termination bdc)]) where exitDate = case first of Just d -> if d > effective && d < termination then d else error("first date out of effective-termination date range " ++ show effective ++ ", " ++ show termination) Nothing -> effective seed = case nextToLast of Just d -> if d > effective && d < termination then d else error("nextToLast date out of effective-termination date range " ++ show effective ++ ", " ++ show termination) Nothing -> termination backward periods | advanceByPeriod NullCalendar seed (Period (-periods*n) unit) bdc eom < exitDate = [adjust calendar exitDate bdc] | otherwise = (backward (periods+1)) ++ [(advanceByPeriod calendar seed (Period (-periods*n) unit) bdc eom)] -- | Schedule convention data type. Summarizes conventions needed for schedule construction. data ScheduleConvention = ScheduleConvention { tenor :: Period, calendar :: Calendar, bdc :: BusinessDayConvention, termBdc :: BusinessDayConvention, rule :: DateGenerationRule, eom :: Bool } deriving (Show, Eq) -- | Eur swap fixed leg standard conventions eurSwapFixLegConv = ScheduleConvention (Period 1 Years) TARGET ModifiedFollowing ModifiedFollowing Backward False -- | Eur swap float leg standard conventions eurSwapFloatLegConv = ScheduleConvention (Period 6 Months) TARGET ModifiedFollowing ModifiedFollowing Backward False -- | Simplified schedule generation by convention, effective and termination date makeSchedule :: ScheduleConvention -> Date -> Date -> Schedule makeSchedule conv from to = schedule from to (tenor conv) (calendar conv) (bdc conv) (termBdc conv) (rule conv) (eom conv) Nothing Nothing -- | same as nub, but works correct only on a sorted list (more precisely on a list -- where equal elements must be placed in direct neighbourhood of each other) nubSorted :: Eq a => [a] -> [a] nubSorted (x:y:rest) = if x==y then nubSorted (x:rest) else x:(nubSorted (y:rest)) nubSorted otherList = otherList
NunoEdgarGub1/hql
src/Hql/Time/Schedule.hs
bsd-3-clause
6,409
0
16
2,375
846
473
373
59
5
-- | Utilities for defining Read\/Show instances. module Data.Array.Parallel.Base.Text ( showsApp , readApp , readsApp , Read(..)) where import Text.Read showsApp :: Show a => Int -> String -> a -> ShowS showsApp k fn arg = showParen (k>10) (showString fn . showChar ' ' . showsPrec 11 arg) readApp :: Read a => String -> ReadPrec a readApp fn = parens $ prec 10 $ do Ident ide <- lexP if ide /= fn then pfail else step readPrec readsApp :: Read a => Int -> String -> ReadS a readsApp k fn = readPrec_to_S (readApp fn) k
mainland/dph
dph-base/Data/Array/Parallel/Base/Text.hs
bsd-3-clause
594
0
9
172
213
109
104
17
2
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DerivingStrategies #-} ----------------------------------------------------------------------------- -- | -- Module : Test.StateMachine.BoxDrawer -- Copyright : (C) 2017, ATS Advanced Telematic Systems GmbH -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Mats Daniel Gustafsson <daniel@advancedtelematic.com> -- Stability : provisional -- Portability : non-portable (GHC extensions) -- -- This module contains functions for visualing a history of a parallel -- execution. -- ----------------------------------------------------------------------------- module Test.StateMachine.BoxDrawer ( EventType(..) , Fork(..) , exec ) where import Prelude import Text.PrettyPrint.ANSI.Leijen (Doc, text, vsep) import Test.StateMachine.Types (Pid(..)) ------------------------------------------------------------------------ -- | Event invocation or response. data EventType = Open | Close deriving stock (Show) data Event = Event EventType Pid String data Cmd = Top | Start String | Active | Deactive | Ret String | Bottom compile :: [Event] -> ([Cmd], [Cmd]) compile = go (Deactive, Deactive) where infixr 9 `add` add :: (a,b) -> ([a], [b]) -> ([a], [b]) add (x,y) (xs, ys) = (x:xs, y:ys) set :: (a, a) -> Pid -> a -> (a, a) set (_x, y) (Pid 1) x' = (x', y) set (x, _y) (Pid 2) y' = (x, y') set _ pid _ = error $ "compile.set: unknown pid " ++ show pid go :: (Cmd, Cmd) -> [Event] -> ([Cmd], [Cmd]) go _ [] = ([], []) go st (Event Open pid l : rest) = set st pid Top `add` set st pid (Start l) `add` go (set st pid Active) rest go st (Event Close pid l : rest) = set st pid (Ret l) `add` set st pid Bottom `add` go (set st pid Deactive) rest size :: Cmd -> Int size Top = 4 size (Start l) = 6 + length l size Active = 2 size Deactive = 0 size (Ret l) = 4 + length l size Bottom = 4 adjust :: Int -> Cmd -> String adjust n Top = "┌" ++ replicate (n - 4) '─' ++ "┐" adjust n (Start l) = "│ " ++ l ++ replicate (n - length l - 6) ' ' ++ " │" adjust n Active = "│" ++ replicate (n - 4) ' ' ++ "│" adjust n Deactive = replicate (n - 2) ' ' adjust n (Ret l) = "│ " ++ replicate (n - 8 - length l) ' ' ++ "→ " ++ l ++ " │" adjust n Bottom = "└" ++ replicate (n - 4) '─' ++ "┘" next :: ([Cmd], [Cmd]) -> [String] next (left, right) = take (length left `max` length right) $ zipWith merge left' right' where left' = map (adjust $ maximum $ 0:map size left) (left ++ repeat Deactive) right' = map (adjust $ maximum $ 0:map size right) (right ++ repeat Deactive) merge x y = x ++ " │ " ++ y toEvent :: [(EventType, Pid)] -> ([String], [String]) -> [Event] toEvent [] ([], []) = [] toEvent [] ps = error $ "toEvent: residue inputs: " ++ show ps toEvent ((e , Pid 1):evT) (x:xs, ys) = Event e (Pid 1) x : toEvent evT (xs, ys) toEvent ((_e, Pid 1):_evT) ([] , _ys) = error "toEvent: no input from pid 1" toEvent ((e , Pid 2):evT) (xs , y:ys) = Event e (Pid 2) y : toEvent evT (xs, ys) toEvent ((_e, Pid 2):_evT) (_xs , []) = error "toEvent: no input from pid 2" toEvent (e : _) _ = error $ "toEvent: unknown pid " ++ show e compilePrefix :: [String] -> [Cmd] compilePrefix [] = [] compilePrefix (cmd:res:prefix) = Top : Start cmd : Ret res : Bottom : compilePrefix prefix compilePrefix [cmd] = error $ "compilePrefix: doesn't have response for cmd: " ++ cmd data Fork a = Fork a a a deriving stock Functor -- | Given a history, and output from processes generate Doc with boxes exec :: [(EventType, Pid)] -> Fork [String] -> Doc exec evT (Fork lops pops rops) = vsep $ map text (preBoxes ++ parBoxes) where preBoxes = map (adjust $ maximum $ 0:map ((2+) . length) (take 1 parBoxes)) $ compilePrefix pops parBoxes = next . compile $ toEvent evT (lops, rops)
advancedtelematic/quickcheck-state-machine-model
src/Test/StateMachine/BoxDrawer.hs
bsd-3-clause
3,970
0
14
941
1,615
880
735
67
5
module Baum.ZweiDrei.Ops where -- $Id$ import Baum.ZweiDrei.Type zwei :: Int zwei = 2 drei :: Int drei = 3 contains :: Ord a => Baum a -> a -> Bool contains Null x = False contains ( Baum bks ) x = let handle [] = False handle ( (b, k) : bks ) = if This x == k then True else if This x < k then contains b x else handle bks in handle bks contents :: Baum a -> [ a ] contents Null = [] contents ( Baum bks ) = do (b, k) <- bks contents b ++ [ x | This x <- [ k ] ] -------------------------------------------------------------------------- insert :: Ord a => Baum a -> a -> Baum a insert b x = case split_insert ( b, Infinity ) x of [ ( b', Infinity ) ] -> b' bks -> Baum bks list_insert :: Ord a => [ (Baum a, Key a) ] -> a -> [ (Baum a, Key a) ] list_insert bks @ ((b, k) : rest) x = if This x < k then split_insert (b, k) x ++ rest else (b, k) : list_insert rest x split_insert :: Ord a => ( Baum a, Key a ) -> a -> [ (Baum a, Key a) ] split_insert ( Null, k ) x = [ (Null, This x), ( Null, k ) ] split_insert ( Baum bks, k ) x = let bks' = list_insert bks x in if length bks' <= drei then [ ( Baum bks', k ) ] else let ( pre, post ) = splitAt (length bks' `div` 2 ) bks' ( last_b, last_k ) = last pre pre' = init pre ++ [ ( last_b, Infinity ) ] in [ ( Baum pre', last_k), ( Baum post, k ) ]
Erdwolf/autotool-bonn
src/Baum/ZweiDrei/Ops.hs
gpl-2.0
1,480
27
15
493
693
368
325
48
4
-- | This is a simple utility module to implement a publish-subscribe pattern. -- Note that this only allows communication in a single direction: pusing data -- from the server to connected clients (browsers). -- -- Usage: -- -- * Create a new 'PubSub' handle using 'newPubSub' -- -- * Subscribe your clients using the 'subscribe' call -- -- * Push new updates from the server using the 'publish' call -- {-# LANGUAGE Rank2Types, ScopedTypeVariables #-} module Network.WebSockets.Util.PubSub ( PubSub , newPubSub , publish , subscribe ) where import Control.Applicative ((<$>)) import Control.Exception (IOException, handle) import Control.Monad (foldM, forever) import Control.Monad.Trans (liftIO) import Data.IntMap (IntMap) import Data.List (foldl') import qualified Control.Concurrent.MVar as MV import qualified Data.IntMap as IM import Network.WebSockets data PubSub_ p = PubSub_ { pubSubNextId :: Int , pubSubSinks :: IntMap (Sink p) } addClient :: Sink p -> PubSub_ p -> (PubSub_ p, Int) addClient sink (PubSub_ nid sinks) = (PubSub_ (nid + 1) (IM.insert nid sink sinks), nid) removeClient :: Int -> PubSub_ p -> PubSub_ p removeClient ref ps = ps {pubSubSinks = IM.delete ref (pubSubSinks ps)} -- | A handle which keeps track of subscribed clients newtype PubSub p = PubSub (MV.MVar (PubSub_ p)) -- | Create a new 'PubSub' handle, with no clients initally connected newPubSub :: IO (PubSub p) newPubSub = PubSub <$> MV.newMVar PubSub_ { pubSubNextId = 0 , pubSubSinks = IM.empty } -- | Broadcast a message to all connected clients publish :: PubSub p -> Message p -> IO () publish (PubSub mvar) msg = MV.modifyMVar_ mvar $ \pubSub -> do -- Take care to detect and remove broken clients broken <- foldM publish' [] (IM.toList $ pubSubSinks pubSub) return $ foldl' (\p b -> removeClient b p) pubSub broken where -- Publish the message to a single client, add it to the broken list if an -- IOException occurs publish' broken (i, s) = handle (\(_ :: IOException) -> return (i : broken)) $ do sendSink s msg return broken -- | Blocks forever subscribe :: Protocol p => PubSub p -> WebSockets p () subscribe (PubSub mvar) = do sink <- getSink ref <- liftIO $ MV.modifyMVar mvar $ return . addClient sink catchWsError loop $ const $ liftIO $ MV.modifyMVar_ mvar $ return . removeClient ref where loop = forever $ do _ <- receiveDataMessage return ()
zodiac/websockets
src/Network/WebSockets/Util/PubSub.hs
bsd-3-clause
2,515
0
13
553
666
359
307
45
1
-------------------------------------------------------------------------------- -- | A module dealing with pandoc file extensions and associated file types module Hakyll.Web.Pandoc.FileType ( FileType (..) , fileType , itemFileType ) where -------------------------------------------------------------------------------- import System.FilePath (splitExtension) -------------------------------------------------------------------------------- import Hakyll.Core.Identifier import Hakyll.Core.Item -------------------------------------------------------------------------------- -- | Datatype to represent the different file types Hakyll can deal with by -- default data FileType = Binary | Css | DocBook | Html | LaTeX | LiterateHaskell FileType | Markdown | MediaWiki | OrgMode | PlainText | Rst | Textile deriving (Eq, Ord, Show, Read) -------------------------------------------------------------------------------- -- | Get the file type for a certain file. The type is determined by extension. fileType :: FilePath -> FileType fileType = uncurry fileType' . splitExtension where fileType' _ ".css" = Css fileType' _ ".dbk" = DocBook fileType' _ ".htm" = Html fileType' _ ".html" = Html fileType' f ".lhs" = LiterateHaskell $ case fileType f of -- If no extension is given, default to Markdown + LiterateHaskell Binary -> Markdown -- Otherwise, LaTeX + LiterateHaskell or whatever the user specified x -> x fileType' _ ".markdown" = Markdown fileType' _ ".mediawiki" = MediaWiki fileType' _ ".md" = Markdown fileType' _ ".mdn" = Markdown fileType' _ ".mdown" = Markdown fileType' _ ".mdwn" = Markdown fileType' _ ".mkd" = Markdown fileType' _ ".mkdwn" = Markdown fileType' _ ".org" = OrgMode fileType' _ ".page" = Markdown fileType' _ ".rst" = Rst fileType' _ ".tex" = LaTeX fileType' _ ".text" = PlainText fileType' _ ".textile" = Textile fileType' _ ".txt" = PlainText fileType' _ ".wiki" = MediaWiki fileType' _ _ = Binary -- Treat unknown files as binary -------------------------------------------------------------------------------- -- | Get the file type for the current file itemFileType :: Item a -> FileType itemFileType = fileType . toFilePath . itemIdentifier
Minoru/hakyll
src/Hakyll/Web/Pandoc/FileType.hs
bsd-3-clause
2,534
0
10
641
411
227
184
49
23
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="az-AZ"> <title>FuzzDB Files</title> <maps> <homeID>fuzzdb</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/fuzzdb/src/main/javahelp/help_az_AZ/helpset_az_AZ.hs
apache-2.0
960
77
66
156
407
206
201
-1
-1
module CreateWebhook where import Github.Repos.Webhooks import qualified Github.Auth as Auth import Github.Data.Definitions import qualified Data.Map as M main :: IO () main = do let auth = Auth.GithubOAuth "oauthtoken" let config = M.fromList [("url", "https://foo3.io"), ("content_type", "application/json"), ("insecure_ssl", "1")] let webhookDef = NewRepoWebhook { newRepoWebhookName = "web", newRepoWebhookConfig = config, newRepoWebhookEvents = Just [WebhookWildcardEvent], newRepoWebhookActive = Just True } newWebhook <- createRepoWebhook' auth "repoOwner" "repoName" webhookDef case newWebhook of (Left err) -> putStrLn $ "Error: " ++ (show err) (Right webhook) -> putStrLn $ formatRepoWebhook webhook formatRepoWebhook :: RepoWebhook -> String formatRepoWebhook (RepoWebhook _ _ _ name _ _ _ _ _ _) = show name
olorin/github
samples/Repos/Webhooks/CreateWebhook.hs
bsd-3-clause
879
0
13
165
258
140
118
20
2
{-# LANGUAGE Unsafe #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.ST -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (requires universal quantification for runST) -- -- This library provides support for /strict/ state threads, as -- described in the PLDI \'94 paper by John Launchbury and Simon Peyton -- Jones /Lazy Functional State Threads/. -- ----------------------------------------------------------------------------- module Control.Monad.ST ( -- * The 'ST' Monad ST, -- abstract, instance of Functor, Monad, Typeable. runST, -- :: (forall s. ST s a) -> a fixST, -- :: (a -> ST s a) -> ST s a -- * Converting 'ST' to 'IO' RealWorld, -- abstract stToIO, -- :: ST RealWorld a -> IO a -- * Unsafe Functions unsafeInterleaveST, unsafeIOToST, unsafeSTToIO ) where import Control.Monad.ST.Safe import qualified Control.Monad.ST.Unsafe as U {-# DEPRECATED unsafeInterleaveST, unsafeIOToST, unsafeSTToIO "Please import from Control.Monad.ST.Unsafe instead; This will be removed in the next release" #-} {-# INLINE unsafeInterleaveST #-} unsafeInterleaveST :: ST s a -> ST s a unsafeInterleaveST = U.unsafeInterleaveST {-# INLINE unsafeIOToST #-} unsafeIOToST :: IO a -> ST s a unsafeIOToST = U.unsafeIOToST {-# INLINE unsafeSTToIO #-} unsafeSTToIO :: ST s a -> IO a unsafeSTToIO = U.unsafeSTToIO
beni55/haste-compiler
libraries/ghc-7.8/base/Control/Monad/ST.hs
bsd-3-clause
1,720
0
6
411
152
100
52
22
1
{-# LANGUAGE DoRec #-} -- check that do-rec does not perform segmentation t :: IO [Int] t = do rec xs <- return (1:xs) print (length (take 10 xs)) -- would diverge without segmentation return (take 10 xs) -- should diverge when run -- currently it exhibits itself via a blocked MVar operation main :: IO () main = t >>= print
wxwxwwxxx/ghc
testsuite/tests/mdo/should_fail/mdofail006.hs
bsd-3-clause
362
0
13
98
95
48
47
7
1
-- See Trac #1606 module ShouldFail where f :: Int -> Int -> Bool -> Bool -> Int -> Int f a b = \ x y -> let { y1 = y; y2 = y1; y3 = y2; y4 = y3; y5 = y4; y6 = y5; y7 = y6 } in x
siddhanathan/ghc
testsuite/tests/typecheck/should_fail/tcfail185.hs
bsd-3-clause
196
2
9
71
98
58
40
4
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} module Futhark.IR.MCMem ( MCMem, -- * Simplification simplifyProg, -- * Module re-exports module Futhark.IR.Mem, module Futhark.IR.SegOp, module Futhark.IR.MC.Op, ) where import Futhark.Analysis.PrimExp.Convert import Futhark.IR.MC.Op import Futhark.IR.Mem import Futhark.IR.Mem.Simplify import Futhark.IR.SegOp import qualified Futhark.Optimise.Simplify.Engine as Engine import Futhark.Pass import Futhark.Pass.ExplicitAllocations (BuilderOps (..), mkLetNamesB', mkLetNamesB'') import qualified Futhark.TypeCheck as TC data MCMem instance RepTypes MCMem where type LetDec MCMem = LetDecMem type FParamInfo MCMem = FParamMem type LParamInfo MCMem = LParamMem type RetType MCMem = RetTypeMem type BranchType MCMem = BranchTypeMem type Op MCMem = MemOp (MCOp MCMem ()) instance ASTRep MCMem where expTypesFromPat = return . map snd . bodyReturnsFromPat instance OpReturns (MCOp MCMem ()) where opReturns (ParOp _ op) = segOpReturns op opReturns (OtherOp ()) = pure [] instance OpReturns (MCOp (Engine.Wise MCMem) ()) where opReturns (ParOp _ op) = segOpReturns op opReturns k = extReturns <$> opType k instance PrettyRep MCMem instance TC.CheckableOp MCMem where checkOp = typeCheckMemoryOp where typeCheckMemoryOp (Alloc size _) = TC.require [Prim int64] size typeCheckMemoryOp (Inner op) = typeCheckMCOp pure op instance TC.Checkable MCMem where checkFParamDec = checkMemInfo checkLParamDec = checkMemInfo checkLetBoundDec = checkMemInfo checkRetType = mapM_ (TC.checkExtType . declExtTypeOf) primFParam name t = return $ Param mempty name (MemPrim t) matchPat = matchPatToExp matchReturnType = matchFunctionReturnType matchBranchType = matchBranchReturnType matchLoopResult = matchLoopResultMem instance BuilderOps MCMem where mkExpDecB _ _ = return () mkBodyB stms res = return $ Body () stms res mkLetNamesB = mkLetNamesB' () instance BuilderOps (Engine.Wise MCMem) where mkExpDecB pat e = return $ Engine.mkWiseExpDec pat () e mkBodyB stms res = return $ Engine.mkWiseBody () stms res mkLetNamesB = mkLetNamesB'' instance TraverseOpStms (Engine.Wise MCMem) where traverseOpStms = traverseMemOpStms (traverseMCOpStms (const pure)) simplifyProg :: Prog MCMem -> PassM (Prog MCMem) simplifyProg = simplifyProgGeneric simpleMCMem simpleMCMem :: Engine.SimpleOps MCMem simpleMCMem = simpleGeneric (const mempty) $ simplifyMCOp $ const $ return ((), mempty)
HIPERFIT/futhark
src/Futhark/IR/MCMem.hs
isc
2,662
0
10
455
742
400
342
-1
-1
import Data.Generics hiding ((:*:))
Pnom/haskell-ast-pretty
Test/examples/ImportSymbol.hs
mit
36
0
5
4
14
9
5
1
0
#!/usr/bin/env stack -- stack --install-ghc runghc --package turtle --package exceptions {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveAnyClass #-} module Main where import Prelude hiding (FilePath) import Turtle import qualified Data.Text as T import Control.Monad.Catch pathToDefaultTemplate :: Text pathToDefaultTemplate = "~/git/stack-templates/skeleton" main :: IO () main = do name <- options "toggle the `.bk` extension on a file" parser sh . fromString . T.unpack $ "stack new " <> name <> " --bare " <> pathToDefaultTemplate parser :: Parser Text parser = argText "name" "The name of the project to create"
stites/scripts
hs/exe/StackNew.hs
mit
635
0
12
101
118
67
51
15
1
import Data.Char main = do print $ product $ map (\index -> digitToInt $ digits !! index) indices where digits = concatMap show [0..] indices = map (10^) [0..6]
dpieroux/euler
0/0040.hs
mit
182
0
12
50
77
41
36
5
1
-- Copyright © 2011 Bart Massey -- [This program is licensed under the "MIT License"] -- Please see the file COPYING in the source -- distribution of this software for license terms. {-# LANGUAGE DeriveDataTypeable #-} -- | This modules provides conversion routines to and from -- various \"something-separated value\" (SSV) formats. In -- particular, it converts the infamous \"comma separated -- value\" (CSV) format. module Text.SSV ( -- * SSV format descriptions -- | These records define a fairly flexible, if entirely -- kludgy, domain-specific language for describing -- \"something-separated value\" formats. An attempt is made -- in the reader and formatter to allow for fairly -- arbitrary combinations of features in a sane -- way. However, your mileage may undoubtedly vary; CSV is -- the only tested configuration. SSVFormat(..), SSVFormatQuote(..), -- * SSV read, show and IO routines readSSV, showSSV, hPutSSV, writeSSVFile, -- * CSV read, show and IO routines -- | CSV is a special case here. Partly this is by virtue -- of being the most common format. CSV also needs a -- little bit of \"special\" help with input line endings -- to conform to RFC 4180. readCSV, showCSV, hPutCSV, writeCSVFile, -- * Newline conversions toNL, fromNL, -- * Exceptions SSVReadException(..), SSVShowException(..), -- * Predefined formats csvFormat, pwfFormat ) where import Control.Exception import Data.Char import Data.List import Data.Maybe import qualified Data.Set as Set import Data.Typeable import System.IO -- | Formatting information for quoted strings for a -- particular SSV variant. data SSVFormatQuote = SSVFormatQuote { ssvFormatQuoteEscape :: Maybe Char, ssvFormatQuoteLeft :: Char, ssvFormatQuoteRight :: Char } -- | Formatting information for a particular SSV variant. data SSVFormat = SSVFormat { ssvFormatName :: String, ssvFormatTerminator :: Char, -- ^ End of row. ssvFormatSeparator :: Char, -- ^ Field separator. ssvFormatEscape :: Maybe Char, -- ^ Escape character outside of quotes. ssvFormatStripWhite :: Bool, -- ^ Strip "extraneous" whitespace next to separators on input. ssvFormatQuote :: Maybe SSVFormatQuote, -- ^ Quote format. ssvFormatWhiteChars :: String } -- ^ Characters regarded as whitespace. -- | 'SSVFormat' for CSV data. Closely follows RFC 4180. csvFormat :: SSVFormat csvFormat = SSVFormat { ssvFormatName = "CSV", ssvFormatTerminator = '\n', ssvFormatSeparator = ',', ssvFormatEscape = Nothing, ssvFormatStripWhite = True, ssvFormatQuote = Just $ SSVFormatQuote { ssvFormatQuoteEscape = Just '"', ssvFormatQuoteLeft = '"', ssvFormatQuoteRight = '"' }, ssvFormatWhiteChars = " \t" } -- | 'SSVFormat' for UNIX \"password file\" data, i.e. colon-separated -- fields with no escape convention. pwfFormat :: SSVFormat pwfFormat = SSVFormat { ssvFormatName = "Colon-separated values", ssvFormatTerminator = '\n', ssvFormatSeparator = ':', ssvFormatEscape = Nothing, ssvFormatStripWhite = False, ssvFormatQuote = Nothing, ssvFormatWhiteChars = "" } -- | Indicates format name, line and column and gives an error message. data SSVReadException = SSVReadException String (Int, Int) String | SSVEOFException String String deriving Typeable -- | Indicates format name and failed field and gives an -- error message. This should probably just be an 'error', -- as the calling program is really responsible for passing -- something formattable to the show routines. data SSVShowException = SSVShowException String String String deriving Typeable instance Show SSVReadException where show (SSVReadException fmt (line, col) msg) = fmt ++ ":" ++ show line ++ ":" ++ show col ++ ": " ++ "read error: " ++ msg show (SSVEOFException fmt msg) = fmt ++ ": read error at end of file: " ++ msg instance Show SSVShowException where show (SSVShowException fmt s msg) = fmt ++ ": field " ++ show s ++ ": show error: " ++ msg instance Exception SSVReadException instance Exception SSVShowException throwRE :: SSVFormat -> (Int, Int) -> String -> a throwRE fmt pos msg = throw $ SSVReadException (ssvFormatName fmt) pos msg throwSE :: SSVFormat -> String -> String -> a throwSE fmt s msg = throw $ SSVShowException (ssvFormatName fmt) s msg -- | Convert CR / LF sequences on input to LF (NL). Also convert -- other CRs to LF. This is probably the right way to handle CSV -- data. toNL :: String -> String toNL = foldr clean1 [] where clean1 :: Char -> String -> String clean1 '\r' cs@('\n' : _) = cs clean1 '\r' cs = '\n' : cs clean1 c cs = c : cs -- | Convert LF (NL) sequences on input to CR LF. Leaves -- | other CRs alone. fromNL :: String -> String fromNL = foldr dirty1 [] where dirty1 :: Char -> String -> String dirty1 '\n' cs = '\r' : '\n' : cs dirty1 c cs = c : cs -- | Read using an arbitrary 'SSVFormat'. The input is not -- cleaned with 'toNL'; if you want this, do it yourself. -- The standard SSV formats 'csvFormat' and 'pwfFormat' are -- provided. readSSV :: SSVFormat -> String -> [[String]] readSSV fmt = nextsw (1, 1) where -- State for initialization and fallback from end of field. nextsw p cs | ssvFormatStripWhite fmt = nextSW p cs | otherwise = nextSX p cs -- A bunch of abbreviations for concision. rs = ssvFormatTerminator fmt fs = ssvFormatSeparator fmt efmt = ssvFormatEscape fmt e = isJust efmt ec = fromJust efmt qfmt = ssvFormatQuote fmt q = isJust qfmt lq = ssvFormatQuoteLeft $ fromJust qfmt rq = ssvFormatQuoteRight $ fromJust qfmt qesc = ssvFormatQuoteEscape $ fromJust qfmt qe = isJust qesc eq = fromJust qesc -- Increment the position in the input various ways. incp (line, _) '\n' = (line + 1, 1) incp (line, col) '\t' = (line, tcol) where tcol = col + 8 - ((col + 7) `mod` 8) incp (line, _) '\r' = (line, 1) incp (line, col) _ = (line, col + 1) -- The actual state machine for the labeler. -- reading a whitespace char nextSW p (' ' : cs) = nextSW (incp p ' ') cs nextSW p ('\t' : cs) = nextSW (incp p '\t') cs nextSW p (c : cs) | c == rs = mkCRS $ nextsw (incp p c) cs | c == fs = mkCFS $ nextsw (incp p c) cs | e && c == ec = nextSE (incp p c) cs | q && c == lq = nextSQ (incp p c) cs | otherwise = mkCX c $ nextSX (incp p c) cs nextSW _ [] = [] -- reading a generic char nextSX p (c : cs) | c == rs = mkCRS $ nextsw (incp p c) cs | c == fs = mkCFS $ nextsw (incp p c) cs | e && c == ec = nextSE (incp p c) cs | q && c == lq = throwRE fmt p "illegal quote" | otherwise = mkCX c $ nextSX (incp p c) cs nextSX _ [] = [] -- reading a quoted char nextSQ p (c : cs) | c == rs = mkCX c $ nextSQ (incp p c) cs | q && qe && c == eq = nextSZ (incp p c) cs | q && c == rq = nextSD (incp p c) cs | otherwise = mkCX c $ nextSQ (incp p c) cs nextSQ _ [] = throw $ SSVEOFException (ssvFormatName fmt) "unclosed quote" -- reading an escaped char nextSE p (c : cs) = mkCX c $ nextSX (incp p c) cs nextSE _ [] = [] -- reading a quoted-escaped char nextSZ p (' ' : cs) = nextSD (incp p ' ') cs nextSZ p ('\t' : cs) = nextSD (incp p '\t') cs nextSZ p (c : cs) | c == rs = mkCRS $ nextsw (incp p c) cs | c == fs = mkCFS $ nextsw (incp p c) cs | q && qe && c == eq = mkCX c $ nextSQ (incp p c) cs | q && c == rq = mkCX c $ nextSQ (incp p c) cs | q && c == lq = mkCX c $ nextSQ (incp p c) cs | otherwise = throwRE fmt p "illegal escape" nextSZ _ [] = [] -- reading a post-quote char nextSD p (' ' : cs) = nextSD (incp p ' ') cs nextSD p ('\t' : cs) = nextSD (incp p '\t') cs nextSD p (c : cs) | c == fs = mkCFS $ nextsw (incp p c) cs | c == rs = mkCRS $ nextsw (incp p c) cs | otherwise = throwRE fmt p "junk after quoted field" nextSD _ [] = [] -- The collector functions for building up the list. -- character mkCX x [] = [[[x]]] mkCX x ([]:rss) = [[x]]:rss mkCX x ((w:wss):rss) = ((x:w):wss):rss -- field separator mkCFS [] = [["",""]] -- no newline at end of file mkCFS (r:rss) = ("":r):rss -- record separator mkCRS rss = [""]:rss -- | Convert a 'String' representing a CSV file into a -- properly-parsed list of rows, each a list of 'String' -- fields. Adheres to the spirit and (mostly) to the letter -- of RFC 4180, which defines the `text/csv` MIME type. -- -- 'toNL' is used on the input string to clean up the -- various line endings that might appear. Note that this -- may result in irreversible, undesired manglings of CRs -- and LFs. -- -- Fields are expected to be separated by commas. Per RFC -- 4180, fields may be double-quoted: only whitespace, which -- is discarded, may appear outside the double-quotes of a -- quoted field. For unquoted fields, whitespace to the left -- of the field is discarded, but whitespace to the right is -- retained; this is convenient for the parser, and probably -- corresponds to the typical intent of CSV authors. Whitespace -- on both sides of a quoted field is discarded. If a -- double-quoted fields contains two double-quotes in a row, -- these are treated as an escaped encoding of a single -- double-quote. -- -- The final line of the input may end with a line terminator, -- which will be ignored, or without one. readCSV :: String -> [[String]] readCSV = readSSV csvFormat . toNL -- | Show using an arbitrary 'SSVFormat'. The standard SSV -- formats 'csvFormat' and 'pwfFormat' are provided. Some -- effort is made to \"intelligently\" quote the fields; in -- the worst case an 'SSVShowException' will be thrown to -- indicate that a field had characters that could not be -- quoted. Spaces or tabs in input fields only causes quoting -- if they are adjacent to a separator, and then only if -- 'ssvFormatStripWhite' is 'True'. showSSV :: SSVFormat -> [[String]] -> String showSSV fmt = concatMap showRow where showRow = (++ "\n") . intercalate [ssvFormatSeparator fmt] . map showField where -- Quote the field as needed. showField s | any needsQuoteChar s || endIsWhite s = case ssvFormatQuote fmt of Just qfmt -> if isJust (ssvFormatQuoteEscape qfmt) || not (elem (ssvFormatQuoteRight qfmt) s) then quote qfmt s else case ssvFormatEscape fmt of Just ch -> escape ch s Nothing -> throwSE fmt s "unquotable character in field" Nothing -> case ssvFormatEscape fmt of Just ch -> escape ch s Nothing -> throwSE fmt s "unquotable character in field" | otherwise = s where needsQuoteChar c | Set.member c quotableChars = True | isPrint c = False | otherwise = True where -- Set of characters that require a field to be quoted. -- XXX This maybe could be kludgier, but I don't know how. quotableChars = Set.fromList $ concat $ catMaybes [ Just [ssvFormatTerminator fmt], Just [ssvFormatSeparator fmt], fmap (:[]) $ ssvFormatEscape fmt, fmap ((:[]) . ssvFormatQuoteLeft) $ ssvFormatQuote fmt ] endIsWhite _ | not (ssvFormatStripWhite fmt) = False endIsWhite "" = False endIsWhite s' = let firstChar = head s' lastChar = last s' in firstChar `elem` ssvFormatWhiteChars fmt || lastChar `elem` ssvFormatWhiteChars fmt quote qfmt s' = [ssvFormatQuoteLeft qfmt] ++ qescape qfmt s' ++ [ssvFormatQuoteRight qfmt] escape esc s' = foldr escape1 "" s' where escape1 c cs | needsQuoteChar c = esc : c : cs | otherwise = c : cs qescape qfmt s' = case ssvFormatQuoteEscape qfmt of Just qesc -> foldr (qescape1 qesc) "" s' Nothing -> s' where qescape1 qesc c cs | c == qesc || c == ssvFormatQuoteRight qfmt = qesc : c : cs | otherwise = c : cs -- | Convert a list of rows, each a list of 'String' fields, -- to a single 'String' CSV representation. Adheres to the -- spirit and (mostly) to the letter of RFC 4180, which -- defines the `text/csv` MIME type. -- -- Newline will be used as the end-of-line character, and no -- discardable whitespace will appear in fields. Fields that -- need to be quoted because they contain a special -- character or line terminator will be quoted; all other -- fields will be left unquoted. The final row of CSV will -- end with a newline. showCSV :: [[String]] -> String showCSV = showSSV csvFormat -- | Put a representation of the given SSV input out on a -- file handle using the given 'SSVFormat'. Uses CRLF as the -- line terminator character, as recommended by RFC 4180 for -- CSV. Otherwise, this function behaves as writing the -- output of 'showSSV' to the 'Handle'; if you want native -- line terminators, this latter method works for that. hPutSSV :: SSVFormat -> Handle -> [[String]] -> IO () hPutSSV fmt h csv = do hSetEncoding h utf8 let nlm = NewlineMode { inputNL = nativeNewline, outputNL = CRLF } hSetNewlineMode h nlm hPutStr h $ showSSV fmt csv -- | Perform 'hPutSSV' with 'csvFormat'. hPutCSV :: Handle -> [[String]] -> IO () hPutCSV = hPutSSV csvFormat -- | Write an SSV representation of the given input into a -- new file located at the given path, using the given -- 'SSVFormat'. As with 'hPutCSV', CRLF will be used as the -- line terminator. writeSSVFile :: SSVFormat -> String -> [[String]] -> IO () writeSSVFile fmt path csv = do h <- openFile path WriteMode hPutSSV fmt h csv hClose h -- | Perform 'writeSSVFile' with 'csvFormat'. writeCSVFile :: String -> [[String]] -> IO () writeCSVFile = writeSSVFile csvFormat
BartMassey/ssv
Text/SSV.hs
mit
14,956
0
21
4,455
3,351
1,766
1,585
238
19
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Network.HTTP.Client.Instances where import Data.Aeson (ToJSON, Value (String), object, toJSON, (.=)) import qualified Data.ByteString as BS import Data.CaseInsensitive (original) import qualified Data.HashMap.Strict as HM import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8With) import Data.Text.Encoding.Error (lenientDecode) import Network.HTTP.Client ( HttpException (HttpExceptionRequest, InvalidUrlException), HttpExceptionContent (ConnectionFailure, StatusCodeException), host, method, path, port, queryString, responseHeaders, responseStatus, ) import Network.HTTP.Types (Header, ResponseHeaders) import Network.HTTP.Types.Status (statusCode) -- Number of bytes we store for responses with exceptions: maxBodyBytes :: Int maxBodyBytes = 256 instance ToJSON HttpException where toJSON (InvalidUrlException url reason) = object [ "type" .= ("InvalidUrlException" :: Text), "url" .= url, "reason" .= reason ] toJSON (HttpExceptionRequest r (ConnectionFailure e)) = object [ "type" .= ("ConnectionFailure" :: Text), "host" .= lenientDecodeUtf8 (host r), "method" .= show (method r), "port" .= port r, "path" .= lenientDecodeUtf8 (path r), "query" .= lenientDecodeUtf8 (queryString r), "exception" .= toJSONString (show e) ] toJSON (HttpExceptionRequest _ (StatusCodeException res _)) = object [ "type" .= ("StatusCodeException" :: Text), "status" .= statusCode (responseStatus res), "headers" .= headersToJSON (responseHeaders res) ] toJSON e = String . T.pack . show $ e toJSONString :: String -> Value toJSONString = String . T.pack -- Duplicated from `RequestLogger`: toObject :: ToJSON a => [(Text, a)] -> Value toObject = toJSON . HM.fromList headersToJSON :: ResponseHeaders -> Value headersToJSON = toObject . map headerToJSON' where headerToJSON' ("Cookie", _) = ("Cookie" :: Text, "<redacted>" :: Text) headerToJSON' ("X-Response-Body-Start", v) = ( "X-Response-Body-Start" :: Text, lenientDecodeUtf8 $ BS.take maxBodyBytes v ) headerToJSON' hd = headerToJSON hd headerToJSON :: Header -> (Text, Text) headerToJSON (headerName, header) = (lenientDecodeUtf8 . original $ headerName, lenientDecodeUtf8 header) lenientDecodeUtf8 :: BS.ByteString -> Text lenientDecodeUtf8 = decodeUtf8With lenientDecode
zoomhub/zoomhub
src/Network/HTTP/Client/Instances.hs
mit
2,562
0
11
510
683
393
290
62
3
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE RankNTypes #-} {-# OPTIONS_GHC-fno-warn-orphans#-} module Pipes.Monoid where import Control.Category (Category(..)) import Control.Monad import Data.Monoid import Pipes import Prelude hiding ((.), id) {- helpers for moving up and down the transformer stack Up and Down may well be counter-intuitive These helpers are always an await followed by a yield (hence the cat prefix) Just as a convention, I take the `lift` metaphor as up, thus an await, followed by a lifted yield seems to be in an upwards direction, and vice-versa. The type system doesnt like "split" synonyms, so I have annotated where polymorphic synonym is happening in comments -} -- Prod' a (Cons' a) catDown :: Monad m => Producer' a (Proxy () a y' y m) r catDown = forever $ lift await >>= yield -- Prod' a (t (Cons' a)) catDown2 :: (Monad (t (Proxy () a y' y m)), Monad m, MonadTrans t) => Producer' a (t (Proxy () a y' y m)) r catDown2 = forever $ (lift . lift $ await) >>= yield -- Prod' a (t (t1 (Cons' a))) catDown3 :: (Monad (t (t1 (Proxy () a y' y m))), Monad (t1 (Proxy () a y' y m)), Monad m, MonadTrans t, MonadTrans t1) => Producer' a (t (t1 (Proxy () a y' y m))) r catDown3 = forever $ (lift . lift . lift $ await) >>= yield -- Consumer' a (Producer' a) catUp :: Monad m => Proxy () a y' y (Proxy x' x () a m) r catUp = forever $ await >>= lift . yield -- Consumer' a (t (Producer' a)) catUp2 :: (Monad (t (Proxy x' x () b m)), Monad m, MonadTrans t) => Proxy () b y' y (t (Proxy x' x () b m)) r catUp2 = forever $ await >>= (lift . lift . yield) -- Consumer' a (t (t1 (Producer' a))) catUp3 :: (Monad (t (t1 (Proxy x' x () a m))), Monad (t1 (Proxy x' x () a m)), Monad m, MonadTrans t, MonadTrans t1) => Proxy () a y' y (t (t1 (Proxy x' x () a m))) b catUp3 = forever $ await >>= (lift . lift . lift . yield) {- The Davorak Pipe Monoid method for reference λ> Pipes.toList $ (each [0..]) >-> Pipes.take 10 >-> (Pipes.map (^2) <> Pipes.take 5) [0,0,1,1,4,2,9,3,16,4] (<>) is strictly ordered, and the entire pipe closes down if one of the pipes does. λ> Pipes.toList $ (pd' (Pipes.take 3) (Pipes.map (+10))) <-< each [1..10] [1,11,2,12,3] -} doubler :: Monad m => Pipe a a m r doubler = forever $ await >>= \x -> replicateM_ 2 (yield x) routeCycle :: Monad m => Consumer a (Producer a (Producer a m)) b routeCycle = goF where goF = do x <- await lift (yield x) goS goS = do x <- await (lift . lift) $ yield x goF maPipe :: Monad m => Pipe a b m r -> Pipe a b m r -> Pipe a b m r maPipe x0 x1 = runEffect (runEffect (runEffect (catDown3 >-> doubler >-> routeCycle) >-> (hoist lift . hoist lift) x0 >-> catUp2) >-> hoist lift x1 >-> catUp) {- instance (Monad m) => Monoid (Pipe a b m r) where mempty = for cat discard mappend = maPipe -} ma :: (Monad m1) => Pipe a b m1 r -> Pipe a b m1 r -> Pipe a b m1 r ma = maPipe me :: (Monad m1) => Pipe a b m1 r me = for cat discard {- deconstruction of the Davorak example for pipes -} -- doubler awaits an a and yields twice step1 :: (Monad m) => Pipe a a m r step1 = doubler -- to feed into the route So we have a Consumer of a's and 2 producers in a three level transformer -- stack step2 :: (Monad m) => Consumer a (Producer a (Producer a m)) r step2 = doubler >-> routeCycle -- lift3AwaitYield provides a Producer which is connected to the top level Consumer that is the -- doubler/router. This Producer is matched to a polymorphic Consumer' layer (the lift x 3 await) -- which becomes an extra level. step3 :: (Monad m) => Effect (Producer a (Producer a (Proxy () a y' y m))) r step3 = catDown3 >-> doubler >-> routeCycle -- collapsing/fusing the top-level Effect (A pipe between the Router and the lowest level Consumer) -- gives us 3 levels in the stack. 1. A Producer of a's 2. Another Producer of a's (which are the -- exact same a's at the first layer) 3. A Consumer' (which can also be filled by a pipe) -- Prod a (Prod a (Cons' a)) step4 :: (Monad m) => Producer a (Producer a (Proxy () a y' y m)) r step4 = runEffect (catDown3 >-> doubler >-> routeCycle) hl2 :: (MFunctor t, MonadTrans t2, MonadTrans t1, Monad (t2 m), Monad m) => t m r -> t (t1 (t2 m)) r hl2 = hoist lift . hoist lift hl2Pipe :: (MonadTrans t2, MonadTrans t1, Monad (t2 m), Monad m) => Pipe a b m r -> Pipe a b (t1 (t2 m)) r hl2Pipe = hoist lift . hoist lift -- hl2 x >-> al2y ~ Pipe a b (t (t m)) >-> Cons' b (t (Prod' b m)) Cons' a (t (Prod' b m)) step5 :: (MonadTrans t1, Monad (t1 (Proxy x' x () b m)), Monad m) => Pipe a b m r -> Proxy () a c' c (t1 (Proxy x' x () b m)) r step5 x = hl2Pipe x >-> catUp2 -- between step5 and step6 we have altered the dev pipe from a Producer a (Producer a (Consumer' a) -- to a Producer b (Producer a (Consumer' a). This is the outgoing part of the new pipe being -- constructed. {- Connecting up step4 and step5 involves the resolution of the respective inner stacks of Consumer' a and Producer' b into a Pipe a b (!). Highly suggestive. -} -- Prod a (Prod a (Cons' a)) >-> Cons' a (t (Prod' b m)) Prod a (Pipe a b m) step6 :: Monad m => Pipe a b m r -> Producer a (Pipe a b m) r step6 x = runEffect $ step4 >-> step5 x -- Prod a (Pipe a b) >-> Pipe a b (t) >-> Cons' b (Prod' b) ~ Effect (Pipe a b) step7 :: Monad m => Pipe a b m r -> Pipe a b m r -> Pipe a b m r step7 x x' = runEffect $ step6 x >-> hoist lift x' >-> catUp
tonyday567/web-play
src/Pipes/Monoid.hs
mit
5,545
0
16
1,338
1,691
867
824
79
1
module Util ( getStore ) where import qualified Settings import Store.LevelDB as LevelDB import System.FilePath ( (</>) ) getStore :: IO LevelDB.Store getStore = do appDir <- Settings.getAppDir return $ LevelDB.createStore (appDir </> "leveldb")
danstiner/clod
src/Util.hs
mit
254
2
10
42
77
44
33
9
1
module Main where ------------------------------------------------------------------------------- import Boids import Model import Linear.V2 import Graphics.Gloss hiding (Point) import Graphics.Gloss.Interface.Pure.Simulate hiding (Point) import Control.Monad.Random import System.Environment( getArgs ) import System.Console.GetOpt import System.Exit ------------------------------------------------------------------------------- -- Option parsing stuff ------------------------------------------------------- data Options = Options { optDrawMode :: BoidArtist , optStep :: Step , optHeight :: Int , optWidth :: Int , optNumber :: Int , optRadius :: Float , optSpeed :: Float } -- Some sensible default configurations defaultOptions :: Options defaultOptions = Options { optDrawMode = drawPretty , optStep = eqWeightStep , optHeight = 800 , optWidth = 800 , optNumber = 20 , optRadius = 50.0 , optSpeed = 1000.0 } options :: [OptDescr (Options -> IO Options)] options = [ Option ['d'] ["debug"] (NoArg (\ opts -> return opts { optDrawMode = drawDebug })) "Draw boids in debug mode" , Option ['c'] ["cohesive"] (NoArg (\ opts -> return opts { optStep = cohesiveStep })) "Cohesive boid behaviour" , Option ['s'] ["swarm"] (NoArg (\ opts -> return opts { optStep = swarmStep })) "Swarming boid behaviour" , Option ['e'] ["equal"] (NoArg (\ opts -> return opts { optStep = eqWeightStep})) "Equal-weighted boid behaviour" , Option ['x'] ["height"] (ReqArg (\x opts -> return opts { optHeight = read x :: Int}) "HEIGHT") "Window height (pixels)" , Option ['y'] ["width"] (ReqArg (\x opts -> return opts { optWidth = read x :: Int}) "WIDTH") "Window width (pixels)" , Option ['n'] ["num"] (ReqArg (\x opts -> return opts { optNumber = read x :: Int}) "BOIDS") "Number of boids in the simulation" , Option ['v'] ["visibility"] (ReqArg (\x opts -> return opts { optRadius = read x :: Float}) "RADIUS") "Boid visibility radius\nDefault is 50" , Option ['p'] ["speed"] (ReqArg (\x opts -> return opts { optSpeed = read x :: Float}) "SPEED") "Higher values make boids move slower.\nDefault is 1000 at 30fps." , Option "h" ["help"] (NoArg (\_ -> do putStrLn (usageInfo "Boids" options) exitWith ExitSuccess)) "Show this help file" ] -- View --------------------------------------------------------------------- type BoidArtist = (Float, Float) -> Boid -> Picture drawPretty :: BoidArtist drawPretty dims boid = case boid of (Boid (V2 xpos ypos) _ _) -> Translate xpos ypos $ drawBoid dims boid drawBoid :: BoidArtist drawBoid (xtrans, ytrans) (Boid (V2 xpos ypos) (V2 xvel yvel) _) = Rotate theta $ Polygon [(-6,0), (0,3), (6,0)] where theta = toDegrees $ atan2 xdiff ydiff xdiff = (xvel + xtrans) - (xpos + xtrans) ydiff = (yvel + ytrans) - (ypos + ytrans) toDegrees rad = rad * 180 / pi drawDebug :: BoidArtist drawDebug dims boid = case boid of (Boid (V2 xpos ypos) (V2 xvel yvel) rad) -> Translate xpos ypos $ Pictures [ drawBoid dims boid , Color red $ Circle rad , Color green $ Line [(0,0), (xvel, yvel)] ] drawWorld :: (Int, Int) -> BoidArtist -> World -> Picture drawWorld (xdim, ydim) draw = Translate xtrans ytrans . Pictures . map (draw (xtrans, ytrans)) where xtrans = - fromIntegral xdim / 2 ytrans = - fromIntegral ydim / 2 -- Main simulation loop ------------------------------------------------------- advanceWorld :: (Int, Int) -> Action -> ViewPort -> Float -> World -> World advanceWorld dims step _ _ = boundsCheck dims . update step main :: IO () main = do args <- getArgs -- Parse options, getting a list of option actions let (actions, _, _) = getOpt RequireOrder options args -- Here we thread startOptions through all supplied option actions opts <- foldl (>>=) (return defaultOptions) actions let Options { optDrawMode = mode , optStep = step , optHeight = height , optWidth = width , optNumber = number , optRadius = rad , optSpeed = speed } = opts let dims = (height, width) pos_x <- evalRandIO (initPos ((fromIntegral height :: Float)/2) number) pos_y <- evalRandIO (initPos ((fromIntegral width :: Float)/2) number) simulate (InWindow "Boids" dims (0, 0)) (greyN 0.7) -- background color 30 -- updates per second (initWorld rad $ zip pos_x pos_y) (drawWorld dims mode) (advanceWorld dims (step speed))
cs383-final/cs383-finalproject
src/Main.hs
mit
4,777
1
15
1,215
1,486
817
669
108
1
module TigerAssem ( Assem(..) , Instr(..) , Lab , Offset , Addr , mkaddr , defs , uses , instrfmt ) where import TigerTemp import TigerRegisters import qualified Data.Map as Map import Data.Maybe (fromJust) type Addr = (Temp, Offset) type Lab = String type Offset = Int mkaddr :: Temp -> Offset -> Addr mkaddr reg offset = (reg, offset) data Assem = MOVRR Temp Temp | MOVRM Temp Addr | MOVMR Addr Temp | MOVCR Int Temp | MOVCM Int Addr | PUSH Temp | PUSHC Int | PUSHM Addr | PUSHA | PUSHL Lab | POP Temp | POPA | LEAL Lab Temp | LEAM Addr Temp | ADDRR Temp Temp | ADDRM Temp Addr | ADDMR Addr Temp | ADDCR Int Temp | ADDCM Int Addr | SUBRR Temp Temp -- subtract rl from rr | SUBRM Temp Addr -- subtract reg from mem | SUBMR Addr Temp -- subtract mem from reg | SUBCR Int Temp | SUBCM Int Addr | INCR Temp | INCM Addr | DECR Temp | DECM Addr | IMULRR Temp Temp | IMULRM Temp Addr | IMULRR2 Temp Temp Int | IMULRM2 Temp Addr Int | IDIVR Temp | IDIVM Addr | CDQ | ANDRR Temp Temp | ANDRM Temp Addr | ANDMR Addr Temp | ANDCR Int Temp | ANDCM Int Addr | ORRR Temp Temp | ORRM Temp Addr | ORMR Addr Temp | ORCR Int Temp | ORCM Int Addr | XORRR Temp Temp | XORRM Temp Addr | XORMR Addr Temp | XORCR Int Temp | XORCM Int Addr | NOTR Temp | NOTM Addr | NEGR Temp | NEGM Addr | JMP Lab | JE Lab | JNE Lab | JZ Lab | JG Lab | JGE Lab | JL Lab | JLE Lab | CMPRR Temp Temp | CMPRM Temp Addr | CMPMR Addr Temp | CMPCR Int Temp | CALLR Temp RetLabel | CALLL Lab RetLabel | RET | COMMENT String deriving (Show, Eq) data Instr = OPER { opAssem::Assem, opSrc::[Temp], opDst::[Temp], opJump::Maybe [Lab] } | LABEL { labLab::Lab } | MOV { movAssem::Assem, movSrc::Temp, movDst::Temp } | CMT Assem | DIRECTIVE String deriving (Show, Eq) defs :: Instr -> [Temp] defs instr = case instr of OPER _ _ ds _ -> ds LABEL _ -> [] MOV _ _ d -> [d] CMT _ -> [] DIRECTIVE _ -> [] uses :: Instr -> [Temp] uses instr = case instr of OPER _ us _ _ -> us LABEL _ -> [] MOV _ u _ -> [u] CMT _ -> [] DIRECTIVE _ -> [] instrfmt :: Instr -> Map.Map Temp Register -> String instrfmt instr allocation = let showtemp (SRC d) srcs dsts = showtemp (srcs !! d) srcs dsts showtemp (DST d) srcs dsts = showtemp (dsts !! d) srcs dsts showtemp t@(TEMP _) _ _ = show $ fromJust $ Map.lookup t allocation showtemp t _ _ = show t showaddr1 :: Addr -> [Temp] -> [Temp] -> String showaddr1 (t, off) srcs dsts = show off++"("++showtemp t srcs dsts++")" ispseudo (PSEUDO _) = True ispseudo _ = False map2pseudo (SRC d) srcs _ = (ispseudo $ fromJust $ Map.lookup (srcs!!d) allocation) map2pseudo (DST d) _ dsts = (ispseudo $ fromJust $ Map.lookup (dsts!!d) allocation) map2pseudo t _ _ = ispseudo $ fromJust $ Map.lookup t allocation showas as srcs dsts = let showtmp t = showtemp t srcs dsts showadr adr = showaddr1 adr srcs dsts in case as of MOVRR t1 t2 -> if map2pseudo t1 srcs dsts && map2pseudo t2 srcs dsts then error $ "Compiler error: " ++ show t1 ++ ", " ++ show t2 ++ ", " ++ show srcs ++ ", " ++ show dsts else "movl "++showtmp t1++", "++showtmp t2 MOVRM t1 addr -> if map2pseudo t1 srcs dsts then error $ "Compiler error: " ++ show t1 ++ show srcs ++ ", " ++ show dsts else "movl "++showtmp t1++", "++showadr addr MOVMR addr t2 -> if map2pseudo t2 srcs dsts then error $ "Compiler error: " ++ show t2 ++ show srcs ++ ", " ++ show dsts else "movl "++showadr addr++", "++showtmp t2 MOVCR d t -> "movl $"++show d++", "++showtmp t MOVCM d addr -> "movl $"++show d++", "++showadr addr PUSH t -> "pushl "++showtmp t PUSHC d -> "pushl $"++show d PUSHM addr -> "pushl "++showadr addr PUSHA -> "pusha" PUSHL l -> "pushl " ++ l POP t -> "popl "++showtmp t POPA -> "popa" LEAL lab t -> "leal "++lab++", "++showtmp t LEAM addr t -> "leal "++showadr addr++", "++showtmp t ADDRR t1 t2 -> "addl "++showtmp t1++", "++showtmp t2 ADDRM t addr -> "addl "++showtmp t++", "++showadr addr ADDMR addr t -> "addl "++showadr addr++", "++showtmp t ADDCR d t -> "addl $"++show d++", "++showtmp t ADDCM d addr -> "addl $"++show d++", "++showadr addr SUBRR t1 t2 -> "subl "++showtmp t1++", "++showtmp t2 SUBRM t addr -> "subl "++showtmp t++", "++showadr addr SUBMR addr t -> "subl "++showadr addr++", "++showtmp t SUBCR d t -> "subl $"++show d++", "++showtmp t SUBCM d addr -> "subl $"++show d++", "++showadr addr INCR t -> "incl "++showtmp t INCM addr -> "incl "++showadr addr DECR t -> "decl "++showtmp t DECM addr -> "decl "++showadr addr IMULRR t1 t2 -> "imul "++showtmp t1++", "++showtmp t2 IMULRM t addr -> "imul "++showtmp t++", "++showadr addr IMULRR2 t1 t2 d -> "imul "++showtmp t1++", "++showtmp t2++", $"++show d IMULRM2 t addr d -> "imul "++showtmp t++", "++showadr addr++", $"++show d IDIVR t -> "idivl "++showtmp t IDIVM addr -> "idivl "++showadr addr CDQ -> "cdq" ANDRR t1 t2 -> "andl "++showtmp t1++", "++showtmp t2 ANDRM t addr -> "andl "++showtmp t++", "++showadr addr ANDMR addr t -> "andl "++showadr addr++", "++showtmp t ANDCR d t -> "andl $"++show d++", "++showtmp t ANDCM d addr -> "andl $"++show d++", "++showadr addr ORRR t1 t2 -> "orl "++showtmp t1++", "++showtmp t2 ORRM t addr -> "orl "++showtmp t++", "++showadr addr ORMR addr t -> "orl "++showadr addr++", "++showtmp t ORCR d t -> "orl $"++show d++", "++showtmp t ORCM d addr -> "orl $"++show d++", "++showadr addr XORRR t1 t2 -> "xorl "++showtmp t1++", "++showtmp t2 XORRM t addr -> "xorl "++showtmp t++", "++showadr addr XORMR addr t -> "xorl "++showadr addr++", "++showtmp t XORCR d t -> "xorl $"++show d++", "++showtmp t XORCM d addr -> "xorl $"++show d++", "++showadr addr NOTR t -> "notl "++showtmp t NOTM addr -> "notl "++showadr addr NEGR t -> "negl "++showtmp t NEGM addr -> "negl "++showadr addr JMP lab -> "jmp "++lab JE lab -> "je "++lab JNE lab -> "jne "++lab JZ lab -> "jz "++lab JG lab -> "jg "++lab JGE lab -> "jge "++lab JL lab -> "jl "++lab JLE lab -> "jle "++lab CMPRR t1 t2 -> "cmpl "++showtmp t1++", "++showtmp t2 CMPRM t addr -> "cmpl "++showtmp t++", "++showadr addr CMPMR addr t -> "cmpl "++showadr addr++", "++showtmp t CMPCR d t -> "cmpl $"++show d++", "++showtmp t CALLR t _-> "call "++showtmp t CALLL lab _ -> "call "++lab RET -> "ret" COMMENT str -> "# "++str in case instr of LABEL lab -> lab++":" CMT (COMMENT cmt) -> "# "++cmt CMT _ -> error "Compiler error: Illegal CMT pattern." OPER as srcs dsts _ -> showas as srcs dsts MOV as src dst -> showas as [src] [dst] DIRECTIVE str -> str
hengchu/tiger-haskell
src/tigerassem.hs
mit
9,004
0
22
3,921
3,100
1,524
1,576
212
84
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeFamilies #-} #if __GLASGOW_HASKELL__ >= 800 {-# OPTIONS_GHC -fdefer-type-errors #-} #endif module AstTest where import Control.Monad (forM_) import Data.CallStack (srcLocStartLine) import Data.Data import Data.Monoid hiding (Sum, Product) import GHC.Generics import Testing import Control.DeepSeq (NFData (..)) import Control.Hspl.Internal.Ast import Control.Hspl.Internal.Tuple #if __GLASGOW_HASKELL__ >= 800 import Test.ShouldNotTypecheck #endif foo = predicate "foo" () bar = predicate "bar" True baz = predicate "baz" (True, ()) predNamed x = predicate x () data Tree a = Leaf a | Tree a (Tree a) (Tree a) deriving (Show, Eq, Typeable, Data, Generic) instance SubTerm a => Termable (Tree a) data PseudoTree a = PLeaf a | PTree a (PseudoTree a) (PseudoTree a) deriving (Show, Eq, Typeable, Data) data U = U deriving (Show, Eq, Typeable, Data, Generic) instance Termable U data PseudoU = PU deriving (Show, Eq, Typeable, Data) data Binary a = Binary a a deriving (Show, Eq, Typeable, Data, Generic) instance SubTerm a => Termable (Binary a) data TwoChars = TwoChars Char Char deriving (Show, Eq, Typeable, Data, Generic) instance Termable TwoChars instance NFData TwoChars where rnf (TwoChars c1 c2) = rnf c1 `seq` rnf c2 instance NFData Constr where rnf c = c `seq` () data NoDefaultTermableInstance = NoDefault Char deriving (Show, Eq, Typeable, Data) instance Termable NoDefaultTermableInstance where toTerm (NoDefault c) = adt NoDefault c -- When deriving Generic instances for sum types, GHC tries to balance the sum, e.g. -- (S1 :+: S2) :+: (S3 :+: S4), as opposed to S1 :+: (S2 :+: (S3 :+: S4)). This presents an edge -- case for GenericAdtTerm when extracting the type-erased arguments. This 4-ary sum type should -- force the tree-like representation and allow us to test this edge case. data Sum4 = S1 | S2 | S3 | S4 deriving (Show, Eq, Typeable, Data, Generic) instance Termable Sum4 -- GHC balances products the same way it does sums data Product4 = P4 Char Char Char Char deriving (Show, Eq, Typeable, Data, Generic) instance Termable Product4 newtype IntFrac = IntFrac { toDouble :: Double } deriving (Num, Fractional, Real, Ord, Enum, Typeable, Data, Show, Eq) instance Termable IntFrac where toTerm = Constant -- This is weird and, well, bad, but it makes parameterizing the tests for numerical operators a lot -- easier. Obviously we'll never want to depend on these operations actually behaving nicely. instance Integral IntFrac where quotRem (IntFrac d1) (IntFrac d2) = quotRem (floor d1) (floor d2) toInteger (IntFrac d) = floor d indeterminateConstructorError = unwords [ "ADT constructor could not be determined. The data constructor used in building terms must be" , "knowable without evaluating the term. In some cases, this means that using a function a -> b" , "as a constructor for a Term b is not sufficient, because the compiler does not know which" , "constructor will be used when the function is evaluated. Possible fix: use the data" , "constructor itself, rather than a function alias." ] nonAdtConstructorError c = unwords [ "Constructor " ++ show c ++ " is not an ADT constructor. Please only use ADT constructors where" , "expected by HSPL." ] reifyAdtTypeError i l term toType = unwords [ "Cannot convert " ++ term ++ " to type " ++ toType ++ " at position " ++ show i ++ " of the" , "argument list " ++ show l ++ "). This is most likely an HSPL bug." ] reifyAdtUnderflowError c n = unwords [ "Not enough arguments (" ++ show n ++ ") to constructor " ++ show c ++ ". This is most likely" , "an HSPL bug." ] reifyAdtOverflowError c expected actual = unwords [ "Too many arguments to constructor " ++ show c ++ ". Expected " ++ show expected ++ " but found" , show actual ++ ". This is most likely an HSPL bug." ] test = describeModule "Control.Hspl.Internal.Ast" $ do describe "variables" $ do it "should report the correct type" $ do varType (Var "x" :: Var Bool) `shouldBe` typeOf True varType (Var "x" :: Var (Bool, ())) `shouldBe` typeOf (True, ()) varType (Var "x" :: Var (Tree Bool)) `shouldBe` typeOf (Leaf True) varType (Anon :: Var Bool) `shouldBe` typeOf True varType (Anon :: Var (Bool, ())) `shouldBe` typeOf (True, ()) varType (Anon :: Var (Tree Bool)) `shouldBe` typeOf (Leaf True) varType (Fresh 0 :: Var Bool) `shouldBe` typeOf True varType (Fresh 0 :: Var (Bool, ())) `shouldBe` typeOf (True, ()) varType (Fresh 0 :: Var (Tree Bool)) `shouldBe` typeOf (Leaf True) it "should compare based on name" $ do (Var "x" :: Var Bool) `shouldEqual` (Var "x" :: Var Bool) (Var "x" :: Var ()) `shouldNotEqual` (Var "y" :: Var ()) (Anon :: Var Bool) `shouldEqual` (Anon :: Var Bool) (Fresh 0 :: Var Bool) `shouldEqual` (Fresh 0 :: Var Bool) (Fresh 0 :: Var ()) `shouldNotEqual` (Fresh 1 :: Var ()) (Var "x" :: Var Bool) `shouldNotEqual` Anon (Var "x" :: Var Bool) `shouldNotEqual` Fresh 0 (Fresh 0 :: Var Bool) `shouldNotEqual` Anon describe "terms" $ do it "can be constructed from HSPL primitives" $ do toTerm () `shouldBe` Constant () toTerm True `shouldBe` Constant True toTerm 'a' `shouldBe` Constant 'a' toTerm (42 :: Int) `shouldBe` Constant (42 :: Int) toTerm (42 :: Integer) `shouldBe` Constant (42 :: Integer) it "can be constructed from tuples" $ do toTerm (True, 'a') `shouldBe` Tup (Tuple2 (Constant True) (Constant 'a')) toTerm (True, 'a', ()) `shouldBe` Tup (TupleN (Constant True) (Tuple2 (Constant 'a') (Constant ()))) toTerm ((), (), ()) `shouldBe` Tup (TupleN (Constant ()) ( Tuple2 (Constant ()) (Constant ()))) toTerm ((), (), (), ()) `shouldBe` Tup (TupleN (Constant ()) ( TupleN (Constant ()) ( Tuple2 (Constant ()) (Constant ())))) toTerm ((), (), (), (), ()) `shouldBe` Tup (TupleN (Constant ()) ( TupleN (Constant ()) ( TupleN (Constant ()) ( Tuple2 (Constant ()) (Constant ()))))) toTerm ((), (), (), (), (), ()) `shouldBe` Tup (TupleN (Constant ()) ( TupleN (Constant ()) ( TupleN (Constant ()) ( TupleN (Constant ()) ( Tuple2 (Constant ()) (Constant ())))))) toTerm ((), (), (), (), (), (), ()) `shouldBe` Tup (TupleN (Constant ()) ( TupleN (Constant ()) ( TupleN (Constant ()) ( TupleN (Constant ()) ( TupleN (Constant ()) ( Tuple2 (Constant ()) (Constant ()))))))) toTerm (True, ('a', ())) `shouldBe` Tup (Tuple2 (Constant True) (Tup $ Tuple2 (Constant 'a') (Constant ()))) toTerm (True, 'a', (), 'b') `shouldBe` Tup (TupleN (Constant True) ( TupleN (Constant 'a') ( Tuple2 (Constant ()) (Constant 'b')))) toTerm (True, ('a', ((), 'b'))) `shouldBe` Tup (Tuple2 (Constant True) ( Tup (Tuple2 (Constant 'a') ( Tup (Tuple2 (Constant ()) (Constant 'b')))))) toTerm (True, ('a', (), 'b')) `shouldBe` Tup (Tuple2 (Constant True) ( Tup (TupleN (Constant 'a') ( Tuple2 (Constant ()) (Constant 'b'))))) it "can be constructed from lists" $ do toTerm "foo" `shouldBe` List (Cons (Constant 'f') (List $ Cons (Constant 'o') (List $ Cons (Constant 'o') $ List Nil))) toTerm ("foo", [True, False]) `shouldBe` Tup (Tuple2 (List $ Cons (Constant 'f') (List $ Cons (Constant 'o') (List $ Cons (Constant 'o') $ List Nil))) (List $ Cons (Constant True) (List $ Cons (Constant False) $ List Nil))) it "can be constructed from ADTs" $ do toTerm (Tree 'a' (Leaf 'b') (Leaf 'c')) `shouldBe` adt Tree ('a', Leaf 'b', Leaf 'c') toTerm (Leaf True) `shouldBe` adt Leaf True toTerm (Leaf ('a', 'b')) `shouldBe` adt Leaf ('a', 'b') toTerm (Binary 'a' 'b') `shouldBe` adt Binary ('a', 'b') toTerm U `shouldBe` Constructor (toConstr U) [] toTerm S1 `shouldBe` Constructor (toConstr S1) [] toTerm S2 `shouldBe` Constructor (toConstr S2) [] toTerm S3 `shouldBe` Constructor (toConstr S3) [] toTerm S4 `shouldBe` Constructor (toConstr S4) [] toTerm (P4 'a' 'b' 'c' 'd') `shouldBe` adt P4 ('a', 'b', 'c', 'd') -- Built-in instances toTerm (Just 'a') `shouldBe` adt Just 'a' toTerm (Nothing :: Maybe Char) `shouldBe` Constructor (toConstr (Nothing :: Maybe Char)) [] toTerm (Left 'a' :: Either Char Bool) `shouldBe` adt Left 'a' toTerm (Right True :: Either Char Bool) `shouldBe` adt Right True toTerm (NoDefault 'a') `shouldBe` adt NoDefault 'a' it "cannot be constructed from mismatched ADT constructors and arguments" $ do #if __GLASGOW_HASKELL__ >= 800 shouldNotTypecheck (adt TwoChars 'a') shouldNotTypecheck (adt TwoChars ('a', True)) shouldNotTypecheck (adt TwoChars (True, False)) shouldNotTypecheck (adt TwoChars ('a', 'b', 'c')) #else pendingWith "ShouldNotTypecheck tests require GHC >= 8.0" #endif it "cannot be constructed from ADTs with variable subterms (use AdtTerm for that)" $ #if __GLASGOW_HASKELL__ >= 800 shouldNotTypecheck (toTerm $ Just (Var "x" :: Var Char)) #else pendingWith "ShouldNotTypecheck tests require GHC >= 8.0" #endif it "should allow the representation of arithmetic expressions" $ do termType (Sum (toTerm (42 :: Int)) (toTerm (Var "x" :: Var Int))) `shouldBe` typeOf (42 :: Int) termType (Difference (toTerm (1.0 :: Double)) (toTerm (Var "x" :: Var Double))) `shouldBe` typeOf (1.0 :: Double) termType (Product (toTerm (42 :: Int)) (toTerm (Var "x" :: Var Int))) `shouldBe` typeOf (42 :: Int) termType (Quotient (toTerm (1.0 :: Double)) (toTerm (Var "x" :: Var Double))) `shouldBe` typeOf (1.0 :: Double) termType (IntQuotient (toTerm (42 :: Int)) (toTerm (Var "x" :: Var Int))) `shouldBe` typeOf (42 :: Int) termType (Modulus (toTerm (42 :: Int)) (toTerm (Var "x" :: Var Int))) `shouldBe` typeOf (42 :: Int) it "can be constructed from variables any type" $ do toTerm (Var "x" :: Var Bool) `shouldBe` Variable (Var "x" :: Var Bool) toTerm (Var "x" :: Var (Tree Bool)) `shouldBe` Variable (Var "x" :: Var (Tree Bool)) toTerm (Var "x" :: Var (Bool, String)) `shouldBe` Variable (Var "x" :: Var (Bool, String)) toTerm (Anon :: Var Bool) `shouldBe` Variable (Anon :: Var Bool) toTerm (Anon :: Var (Tree Bool)) `shouldBe` Variable (Anon :: Var (Tree Bool)) toTerm (Anon :: Var (Bool, String)) `shouldBe` Variable (Anon :: Var (Bool, String)) toTerm (Fresh 0 :: Var Bool) `shouldBe` Variable (Fresh 0 :: Var Bool) toTerm (Fresh 0 :: Var (Tree Bool)) `shouldBe` Variable (Fresh 0 :: Var (Tree Bool)) toTerm (Fresh 0 :: Var (Bool, String)) `shouldBe` Variable (Fresh 0 :: Var (Bool, String)) it "should permit embedded variables" $ do toTerm (True, Var "x" :: Var Bool) `shouldBe` Tup (Tuple2 (Constant True) (Variable (Var "x" :: Var Bool))) toTerm (True, (Var "x" :: Var Bool, False)) `shouldBe` Tup (Tuple2 (Constant True) (Tup $ Tuple2 (Variable $ Var "x") (Constant False))) toTerm [Var "x" :: Var Char, Var "y" :: Var Char] `shouldBe` List (Cons (toTerm (Var "x" :: Var Char)) (List $ Cons (toTerm (Var "y" :: Var Char)) $ List Nil)) it "should have type corresponding to the enclosed value" $ do termType (toTerm True) `shouldBe` typeOf True termType (toTerm ('a', True, ())) `shouldBe` typeOf ('a', True, ()) termType (toTerm ('a', (True, ()))) `shouldBe` typeOf ('a', (True, ())) termType (toTerm (Var "x" :: Var (Tree Bool))) `shouldBe` typeOf (Leaf True) termType (adt Leaf True) `shouldBe` typeOf (Leaf True) when "containing no variables" $ do it "should reify with the corresponding Haskell value" $ do fromTerm (toTerm ()) `shouldBe` Just () fromTerm (toTerm True) `shouldBe` Just True fromTerm (toTerm 'a') `shouldBe` Just 'a' fromTerm (toTerm (42 :: Int)) `shouldBe` Just (42 :: Int) fromTerm (toTerm (True, 'a')) `shouldBe` Just (True, 'a') fromTerm (List Nil :: Term [Int]) `shouldBe` Just [] fromTerm (toTerm "foo") `shouldBe` Just "foo" fromTerm (toTerm $ Tree 'a' (Leaf 'b') (Leaf 'c')) `shouldBe` Just (Tree 'a' (Leaf 'b') (Leaf 'c')) fromTerm (toTerm $ Leaf True) `shouldBe` Just (Leaf True) fromTerm (toTerm (Nothing :: Maybe Bool)) `shouldBe` Just Nothing -- Two tuples with the same AST can reify to different tuples depending on whether the type -- is flat or nested. fromTerm (toTerm (True, 'a', ())) `shouldBe` Just (True, 'a', ()) fromTerm (toTerm (True, ('a', ()))) `shouldBe` Just (True, ('a', ())) fromTerm (toTerm (True, 'a', (), 'b')) `shouldBe` Just (True, 'a', (), 'b') fromTerm (toTerm (True, ('a', ((), 'b')))) `shouldBe` Just (True, ('a', ((), 'b'))) fromTerm (toTerm (True, ('a', (), 'b'))) `shouldBe` Just (True, ('a', (), 'b')) -- Arithmetic expressions fromTerm (Sum (toTerm (41 :: Int)) (toTerm (1 :: Int))) `shouldBe` Just 42 fromTerm (Difference (toTerm (43 :: Int)) (toTerm (1 :: Int))) `shouldBe` Just 42 fromTerm (Product (toTerm (7 :: Int)) (toTerm (6 :: Int))) `shouldBe` Just 42 fromTerm (Quotient (toTerm (10.5 :: Double)) (toTerm (0.25 :: Double))) `shouldBe` Just 42.0 fromTerm (IntQuotient (toTerm (85 :: Int)) (toTerm (2 :: Int))) `shouldBe` Just 42 fromTerm (Modulus (toTerm (85 :: Int)) (toTerm (2 :: Int))) `shouldBe` Just 1 context "an ADT term" $ do let reify c x = reifyAdt c x :: TwoChars let constr = toConstr $ TwoChars 'a' 'b' it "should fall over when one argument is the wrong type" $ do let terms = [ETermEntry 'a', ETermEntry True] let term = "(" ++ show True ++ " :: " ++ show (typeOf True) ++ ")" assertError (reifyAdtTypeError 1 terms term (show $ typeOf 'a')) $ reify constr terms it "should fall over when given too many arguments" $ do let terms = [ETermEntry 'a', ETermEntry 'b', ETermEntry 'c'] assertError (reifyAdtOverflowError constr 2 3) $ reify constr terms it "should fall over when given too few arguments" $ do let terms = [ETermEntry 'a'] assertError (reifyAdtUnderflowError constr 1) $ reify constr terms when "containing variables" $ it "fromTerm should return Nothing" $ do fromTerm (toTerm (Var "x" :: Var ())) `shouldBe` (Nothing :: Maybe ()) fromTerm (toTerm (True, Var "x" :: Var Bool)) `shouldBe` (Nothing :: Maybe (Bool, Bool)) fromTerm (List $ Cons (toTerm $ Var "x") (toTerm "foo")) `shouldBe` Nothing fromTerm (List $ Cons (toTerm 'a') (toTerm $ Var "xs")) `shouldBe` Nothing fromTerm (List $ Append (Var "xs") $ toTerm "foo") `shouldBe` Nothing fromTerm (adt Leaf (Var "x" :: Var Char)) `shouldBe` Nothing fromTerm (adt Tree ('a', Leaf 'b', Var "x" :: Var (Tree Char))) `shouldBe` Nothing fromTerm (adt Tree ('a', Leaf 'b', adt Leaf (Var "x" :: Var Char))) `shouldBe` Nothing fromTerm (Sum (toTerm (42 :: Int)) (toTerm (Var "x" :: Var Int))) `shouldBe` Nothing when "type erased" $ it "can be mapped over" $ do termMap show (ETerm $ toTerm "foo") `shouldBe` show (toTerm "foo") termEntryMap show (ETermEntry "foo") `shouldBe` show "foo" describe "AdtConstructor" $ do it "should get the representation of a unit constructor" $ constructor U `shouldBe` toConstr U it "should get the representation of a curried constructor" $ do constructor (Leaf :: Char -> Tree Char) `shouldBe` toConstr (Leaf 'a') constructor TwoChars `shouldBe` toConstr (TwoChars 'a' 'b') it "should fall over if the constructor cannot be determined" $ do let constr x = if x then Leaf x else Tree x (Leaf x) (Leaf x) assertError indeterminateConstructorError $ constructor constr it "should fall over if the function is not an ADT constructor" $ do let f x = 42 :: Int assertError (nonAdtConstructorError $ toConstr (42 :: Int)) $ constructor f describe "AdtArgument" $ it "should convert a tuple of arguments to a type-erased term list" $ do getArgs (mkTuple 'a' :: Tuple Char One) `shouldBe` [ETerm $ toTerm 'a'] getArgs (mkTuple ('a', 'b') :: Tuple (Char, Char) One) `shouldBe` [ETerm $ toTerm ('a', 'b')] getArgs (mkTuple ('a', 'b') :: Tuple (Char, Char) Many) `shouldBe` [ETerm $ toTerm 'a', ETerm $ toTerm 'b'] getArgs (mkTuple ('a', 'b', 'c') :: Tuple (Char, Char, Char) Many) `shouldBe` [ETerm $ toTerm 'a', ETerm $ toTerm 'b', ETerm $ toTerm 'c'] describe "AdtTerm" $ do it "should convert a constructor and tuple of arguments to a Term" $ do adt Tree ('a', Leaf 'b', Leaf 'c') `shouldBe` Constructor (toConstr $ Tree 'a' (Leaf 'b') (Leaf 'c')) [ETerm $ toTerm 'a', ETerm $ toTerm (Leaf 'b'), ETerm $ toTerm (Leaf 'c')] adt Leaf True `shouldBe` Constructor (toConstr $ Leaf True) [ETerm $ toTerm True] adt Leaf ('a', 'b') `shouldBe` Constructor (toConstr $ Leaf True) [ETerm $ toTerm ('a', 'b')] adt Binary ('a', 'b') `shouldBe` Constructor (toConstr $ Binary 'a' 'b') [ETerm $ toTerm 'a', ETerm $ toTerm 'b'] it "should allow embedded variables" $ do adt Leaf (Var "x" :: Var Bool) `shouldBe` Constructor (toConstr $ Leaf True) [ETerm $ toTerm (Var "x" :: Var Bool)] adt Leaf ('a', Var "x" :: Var Bool) `shouldBe` Constructor (toConstr $ Leaf True) [ETerm $ toTerm ('a', Var "x" :: Var Bool)] adt Binary ('a', Var "x" :: Var Char) `shouldBe` Constructor (toConstr $ Binary 'a' 'b') [ETerm $ toTerm 'a', ETerm $ toTerm (Var "x" :: Var Char)] adt Tree (Var "x" :: Var Char, Leaf 'a', Leaf 'b') `shouldBe` Constructor (toConstr $ Tree 'a' (Leaf 'a') (Leaf 'b')) [ ETerm $ toTerm (Var "x" :: Var Char) , ETerm $ toTerm (Leaf 'a') , ETerm $ toTerm (Leaf 'b') ] adt Tree ('a', adt Leaf (Var "x" :: Var Char), Leaf 'b') `shouldBe` Constructor (toConstr $ Tree 'a' (Leaf 'b') (Leaf 'c')) [ ETerm $ toTerm 'a' , ETerm $ adt Leaf (Var "x" :: Var Char) , ETerm $ toTerm $ Leaf 'b' ] adt Tree ('a', Leaf 'b', Var "x" :: Var (Tree Char)) `shouldBe` Constructor (toConstr $ Tree 'a' (Leaf 'b') (Leaf 'c')) [ ETerm $ toTerm 'a' , ETerm $ toTerm $ Leaf 'b' , ETerm $ toTerm (Var "x" :: Var (Tree Char)) ] describe "alpha equivalence" $ do context "of variables" $ do it "should succeed" $ do (Var "x" :: Var Char) `shouldBeAlphaEquivalentTo` (Var "y" :: Var Char) (Var "x" :: Var Char) `shouldBeAlphaEquivalentTo` (Fresh 0 :: Var Char) (Fresh 0 :: Var Char) `shouldBeAlphaEquivalentTo` (Var "x" :: Var Char) it "should work for anonymous variables" $ do Anon `shouldBeAlphaEquivalentTo` (Anon :: Var Char) Anon `shouldBeAlphaEquivalentTo` (Var "x" :: Var Char) (Var "x" :: Var Char) `shouldBeAlphaEquivalentTo` Anon (Var "x" :: Var Char, Var "y" :: Var Char) `shouldBeAlphaEquivalentTo` (Anon, Anon) (Anon, Anon) `shouldBeAlphaEquivalentTo` (Var "x" :: Var Char, Var "y" :: Var Char) (Anon, Var "x" :: Var Char) `shouldBeAlphaEquivalentTo` (Var "y" :: Var Char, Anon) withParams [Var "x" :: Var Char, Fresh 0, Anon] $ \x -> context "of a variable and a non-variable" $ it "should fail" $ do toTerm x `shouldNotSatisfy` alphaEquivalent (Constant 'a') Constant 'a' `shouldNotSatisfy` alphaEquivalent (toTerm x) context "of constants" $ do it "should succeed when they are equal" $ Constant 'a' `shouldBeAlphaEquivalentTo` Constant 'a' it "should fail when they are not" $ Constant 'a' `shouldNotSatisfy` alphaEquivalent (Constant 'b') context "of tuples" $ do it "should succeed when the tuples are equal" $ toTerm ('a', True) `shouldBeAlphaEquivalentTo` toTerm ('a', True) it "should succeed when the tuples are alpha-equivalent" $ do toTerm ('a', Var "x" :: Var Char) `shouldBeAlphaEquivalentTo` toTerm ('a', Var "y" :: Var Char) toTerm (Var "x" :: Var Char, Var "y" :: Var Char) `shouldBeAlphaEquivalentTo` toTerm (Var "y" :: Var Char, Var "x" :: Var Char) toTerm (Var "x" :: Var Char, Var "x" :: Var Char) `shouldBeAlphaEquivalentTo` toTerm (Var "a" :: Var Char, Var "a" :: Var Char) it "should fail when the tuples can be unified but are not alpha-equivalent" $ do toTerm (Var "x" :: Var Char, Var "y" :: Var Char) `shouldNotSatisfy` alphaEquivalent (toTerm (Var "a" :: Var Char, Var "a" :: Var Char)) toTerm (Var "x" :: Var Char, Var "x" :: Var Char) `shouldNotSatisfy` alphaEquivalent (toTerm (Var "a" :: Var Char, Var "b" :: Var Char)) it "should fail when the tuples are not of the same form" $ toTerm ('a', 'b') `shouldNotSatisfy` alphaEquivalent (toTerm ('b', 'c')) context "of lists" $ do it "should succeed when the lists are equal" $ toTerm ['a', 'b', 'c'] `shouldBeAlphaEquivalentTo` toTerm ['a', 'b', 'c'] it "should succeed when the lists are alpha-equivalent" $ do toTerm ([Var "x", Var "y", Var "z"] :: [Var Char]) `shouldBeAlphaEquivalentTo` toTerm ([Var "a", Var "b", Var "c"] :: [Var Char]) toTerm ([Var "x", Var "y"] :: [Var Char]) `shouldBeAlphaEquivalentTo` toTerm ([Var "y", Var "x"] :: [Var Char]) toTerm ([Var "x", Var "x"] :: [Var Char]) `shouldBeAlphaEquivalentTo` toTerm ([Var "a", Var "a"] :: [Var Char]) List (Append (Var "xs") $ toTerm "foo") `shouldBeAlphaEquivalentTo` List (Append (Var "ys") $ toTerm "foo") List (Append (Var "xs" :: Var String) $ toTerm $ Var "ys") `shouldBeAlphaEquivalentTo` List (Append (Var "ys" :: Var String) $ toTerm $ Var "xs") it "should fail when the lists can be unified but are not alpha-equivalent" $ do toTerm [Var "x" :: Var Char, Var "y" :: Var Char] `shouldNotSatisfy` alphaEquivalent (toTerm [Var "a" :: Var Char, Var "a" :: Var Char]) toTerm [Var "x" :: Var Char, Var "x" :: Var Char] `shouldNotSatisfy` alphaEquivalent (toTerm [Var "a" :: Var Char, Var "b" :: Var Char]) toTerm "abcd" `shouldNotSatisfy` alphaEquivalent (List $ Append (Var "xs") $ toTerm "cd") it "should fail when the lists are not of the same form" $ toTerm ['a', 'b'] `shouldNotSatisfy` alphaEquivalent (toTerm ['b', 'c']) context "of adts" $ do it "should succeed when the terms are equal" $ toTerm (Just 'a') `shouldBeAlphaEquivalentTo` toTerm (Just 'a') it "should succeed when the terms are alpha-equivalent" $ adt Just (Var "x" :: Var Char) `shouldBeAlphaEquivalentTo` adt Just (Var "y" :: Var Char) it "should fail when the terms are not alpha-equivalent" $ adt Just (Var "x" :: Var Char, Var "y" :: Var Char) `shouldNotSatisfy` alphaEquivalent (adt Just (Var "a" :: Var Char, Var "a" :: Var Char)) it "should fail when the terms are not equal" $ do toTerm (Left 'a' :: Either Char Char) `shouldNotSatisfy` alphaEquivalent (toTerm (Right 'a' :: Either Char Char)) toTerm (Leaf 'a') `shouldNotSatisfy` alphaEquivalent (toTerm $ Leaf 'b') context "of binary operators" $ do let constrs :: [Term IntFrac -> Term IntFrac -> Term IntFrac] constrs = [Sum, Difference, Product, Quotient, IntQuotient, Modulus] let term :: Double -> Term IntFrac term = toTerm . IntFrac let var :: String -> Term IntFrac var = toTerm . Var withParams constrs $ \constr -> do it "should succeed when the terms are equal" $ constr (term 1) (term 2) `shouldBeAlphaEquivalentTo` constr (term 1) (term 2) it "should succeed when the terms are alpha-equivalent" $ do constr (var "x") (var "y") `shouldBeAlphaEquivalentTo` constr (var "a") (var "b") constr (var "x") (var "y") `shouldBeAlphaEquivalentTo` constr (var "y") (var "x") constr (var "x") (var "x") `shouldBeAlphaEquivalentTo` constr (var "a") (var "a") it "should fail when the terms can be unified but are not alpha-equivalent" $ do constr (var "x") (var "y") `shouldNotSatisfy` alphaEquivalent (constr (var "a") (var "a")) constr (var "x") (var "x") `shouldNotSatisfy` alphaEquivalent (constr (var "a") (var "b")) it "should fail when the terms are not of the same form" $ constr (term 1) (term 2) `shouldNotSatisfy` alphaEquivalent (constr (term 2) (term 3)) context "of different kinds of terms" $ it "should fail" $ toTerm (Sum (toTerm (1 :: Int)) (toTerm (2 :: Int))) `shouldNotSatisfy` alphaEquivalent (Difference (toTerm (1 :: Int)) (toTerm (2 :: Int))) describe "getListTerm" $ do it "should return the ListTerm for a term with a List constructor" $ do getListTerm (List Nil :: Term [Int]) `shouldBe` Right Nil getListTerm (List $ Cons (toTerm 'a') $ List Nil) `shouldBe` Right (Cons (toTerm 'a') $ List Nil) it "should return a variable when the term has a Variable constructor" $ getListTerm (toTerm (Var "xs" :: Var [Int])) `shouldBe` Left (Var "xs") describe "appendTerm" $ do it "should prepend a variable" $ appendTerm (toTerm $ Var "prefix") (toTerm "foo") `shouldBe` List (Append (Var "prefix") (toTerm "foo")) it "should ignore a preceding Nil" $ appendTerm (List Nil) (toTerm "foo") `shouldBe` toTerm "foo" it "should prepend a cons'ed list" $ appendTerm (List $ Cons (toTerm $ Var "x") (toTerm "oo")) (toTerm "bar") `shouldBe` List (Cons (toTerm $ Var "x") (toTerm "oobar")) it "should prened an appended list" $ appendTerm (List $ Append (Var "xs") (toTerm "bar")) (toTerm "baz") `shouldBe` List (Append (Var "xs") (toTerm "barbaz")) describe "predicates" $ do it "should have type corresponding to the type of the argument" $ do predType (predicate "foo" ()) `shouldBe` termType (toTerm ()) predType (predicate "foo" True) `shouldBe` termType (toTerm True) predType (predicate "foo" (True, False)) `shouldBe` termType (toTerm (True, False)) context "of the same name, type, scope, and location" $ it "should compare according to that type's comparison operator" $ do predicate "foo" True `shouldEqual` predicate "foo" (toTerm True) predicate "foo" (True, ()) `shouldEqual` predicate "foo" (toTerm (True, ())) predicate "foo" True `shouldNotEqual` predicate "foo" False predicate "foo" (True, ()) `shouldNotEqual` predicate "foo" (False, ()) let loc = Just srcLoc let scope = Just "scope" Predicate loc scope "foo" (toTerm True) `shouldEqual` Predicate loc scope "foo" (toTerm True) Predicate loc scope "foo" (toTerm True) `shouldNotEqual` Predicate loc scope "foo" (toTerm False) context "of the same type, but with different names" $ it "should compare unequal" $ do predicate "foo" True `shouldNotEqual` predicate "bar" True predicate "foo" (True, ()) `shouldNotEqual` predicate "bar" (True, ()) context "of different types" $ it "should compare unequal" $ predicate "foo" True `shouldNotEqual` predicate "foo" (True, False) context "of different locations" $ it "should compare unequal" $ do let loc1 = Just srcLoc let loc2 = Just srcLoc { srcLocStartLine = __LINE__ } Predicate loc1 Nothing "foo" (toTerm ()) `shouldNotEqual` Predicate loc2 Nothing "foo" (toTerm ()) context "of different scopes" $ it "should compare unequal" $ Predicate Nothing (Just "scope1") "foo" (toTerm ()) `shouldNotEqual` Predicate Nothing (Just "scope2") "foo" (toTerm ()) describe "Predicate goals" $ do it "should compare based on the predicate" $ do PredGoal (predicate "foo" ()) [] `shouldEqual` PredGoal (predicate "foo" ()) [] PredGoal (predicate "foo" ()) [] `shouldNotEqual` PredGoal (predicate "bar" ()) [] PredGoal (predicate "foo" True) [] `shouldNotEqual` PredGoal (predicate "foo" ()) [] PredGoal (predicate "foo" True) [] `shouldNotEqual` PredGoal (predicate "foo" False) [] PredGoal (Predicate (Just srcLoc) Nothing "foo" $ toTerm True) [] `shouldNotEqual` PredGoal (Predicate (Just srcLoc { srcLocStartLine = __LINE__ }) Nothing "foo" $ toTerm True) [] it "should compare successfully even when recursive" $ do let g = PredGoal (predicate "foo" 'a') [HornClause (predicate "foo" (Var "x" :: Var Char)) g] g `shouldEqual` g let g' = PredGoal (predicate "foo" 'b') [HornClause (predicate "foo" (Var "x" :: Var Char)) g'] g' `shouldNotEqual` g let g'' = PredGoal (predicate "bar" 'a') [HornClause (predicate "bar" (Var "x" :: Var Char)) g''] g'' `shouldNotEqual` g it "should be showable even when recursive" $ do let p = predicate "foo" (Var "x" :: Var Char) let pGoal = predicate "foo" 'a' let g = PredGoal pGoal [HornClause p g] show g `shouldBe` "y (\\recurse -> PredGoal (" ++ show pGoal ++ ") [HornClause (" ++ show p ++ ") (recurse)])" withParams [(IsUnified, IsUnified), (IsVariable, IsVariable)] $ \(char, bool) -> describe "unary term goals" $ do context "of the same type" $ it "should compare according to the arguments" $ do char (toTerm 'a') `shouldEqual` char (toTerm 'a') char (toTerm $ Var "x") `shouldEqual` char (toTerm $ Var "x") char (toTerm 'a') `shouldNotEqual` char (toTerm 'b') char (toTerm $ Var "x") `shouldNotEqual` char (toTerm $ Var "y") context "of different types" $ it "should compare unequal" $ do char (toTerm 'a') `shouldNotEqual` bool (toTerm True) char (toTerm $ Var "x") `shouldNotEqual` bool (toTerm $ Var "x") describe "binary term goals" $ do let constrs :: [(Term Char -> Term Char -> Goal, Term Bool -> Term Bool -> Goal)] constrs = [(CanUnify, CanUnify), (Identical, Identical), (Equal, Equal), (LessThan, LessThan)] context "of the same type" $ withParams constrs $ \(char, _) -> context "of the same type" $ it "should compare according to the arguments" $ do char (toTerm 'a') (toTerm 'b') `shouldEqual` char (toTerm 'a') (toTerm 'b') char (toTerm (Var "x" :: Var Char)) (toTerm 'b') `shouldEqual` char (toTerm (Var "x" :: Var Char)) (toTerm 'b') char (toTerm 'a') (toTerm 'b') `shouldNotEqual` char (toTerm 'a') (toTerm 'a') char (toTerm (Var "x" :: Var Char)) (toTerm 'b') `shouldNotEqual` char (toTerm (Var "y" :: Var Char)) (toTerm 'b') context "of different types" $ withParams constrs $ \(char, bool) -> it "should compare unequal" $ do char (toTerm 'a') (toTerm 'b') `shouldNotEqual` bool (toTerm True) (toTerm False) char (toTerm (Var "x" :: Var Char)) (toTerm (Var "y" :: Var Char)) `shouldNotEqual` bool (toTerm (Var "x" :: Var Bool)) (toTerm (Var "y" :: Var Bool)) describe "unary outer goals" $ withParams [CutFrame, Track, Once] $ \constr -> it "should compare according to the inner goal" $ do constr (PredGoal (predicate "foo" ()) []) `shouldEqual` constr (PredGoal (predicate "foo" ()) []) constr (PredGoal (predicate "foo" ()) []) `shouldNotEqual` constr (PredGoal (predicate "bar" ()) []) describe "binary outer goals" $ withParams [And, Or] $ \constr -> it "should compare according to the subgoals" $ do constr (PredGoal (predicate "foo" ()) []) (PredGoal (predicate "bar" ()) []) `shouldEqual` constr (PredGoal (predicate "foo" ()) []) (PredGoal (predicate "bar" ()) []) constr (PredGoal (predicate "foo" ()) []) (PredGoal (predicate "bar" ()) []) `shouldNotEqual` constr (PredGoal (predicate "foo'" ()) []) (PredGoal (predicate "bar" ()) []) constr (PredGoal (predicate "foo" ()) []) (PredGoal (predicate "bar" ()) []) `shouldNotEqual` constr (PredGoal (predicate "foo" ()) []) (PredGoal (predicate "bar'" ()) []) describe "ternary outer goals" $ withParams [If] $ \constr -> it "should compare according to the subgoals" $ do constr Top Bottom Cut `shouldEqual` constr Top Bottom Cut constr Top Bottom Cut `shouldNotEqual` constr Bottom Bottom Cut constr Top Bottom Cut `shouldNotEqual` constr Top Top Cut constr Top Bottom Cut `shouldNotEqual` constr Top Bottom Top describe "unitary goals" $ do let ugoals = [Top, Bottom, Cut] withParams ugoals $ \constr -> do it "should equal itself" $ constr `shouldEqual` constr it "should not equal any other goal" $ constr `shouldNotEqual` And constr constr describe "Alternatives goals" $ do withParams [Nothing, Just 42] $ \n -> context "with the same limit" $ do context "of the same type" $ it "should compare according to the subcomponents" $ do let g = Alternatives n (toTerm (Var "x" :: Var Char)) (Equal (toTerm 'a') (toTerm 'b')) (toTerm $ Var "xs") g `shouldEqual` g Alternatives n (toTerm (Var "x" :: Var Char)) (Equal (toTerm 'a') (toTerm 'b')) (toTerm $ Var "xs") `shouldNotEqual` Alternatives n (toTerm (Var "y" :: Var Char)) (Equal (toTerm 'a') (toTerm 'b')) (toTerm $ Var "xs") Alternatives n (toTerm (Var "x" :: Var Char)) (Equal (toTerm 'a') (toTerm 'b')) (toTerm $ Var "xs") `shouldNotEqual` Alternatives n (toTerm (Var "x" :: Var Char)) (Equal (toTerm 'b') (toTerm 'a')) (toTerm $ Var "xs") Alternatives n (toTerm (Var "x" :: Var Char)) (Equal (toTerm 'a') (toTerm 'b')) (toTerm $ Var "xs") `shouldNotEqual` Alternatives n (toTerm (Var "x" :: Var Char)) (Equal (toTerm 'a') (toTerm 'b')) (toTerm $ Var "ys") context "of different types" $ it "should compare unequal" $ Alternatives n (toTerm (Var "x" :: Var Char)) (Equal (toTerm 'a') (toTerm 'b')) (toTerm $ Var "xs") `shouldNotEqual` Alternatives n (toTerm (Var "x" :: Var Bool)) (Equal (toTerm 'a') (toTerm 'b')) (toTerm $ Var "xs") context "with different limits" $ it "should compare unequal" $ do let runTest n1 n2 = let g n = Alternatives n (toTerm (Var "x" :: Var Char)) Top (toTerm $ Var "xs") in do g n1 `shouldNotEqual` g n2 g n2 `shouldNotEqual` g n1 runTest Nothing (Just 42) runTest (Just 42) (Just 43) describe "goals" $ it "should form a monoid under conjunction" $ do mempty `shouldBe` Top mappend Top Bottom `shouldBe` And Top Bottom describe "clauses" $ do it "should have type corresponding to the type of the positive literal" $ do clauseType (HornClause foo Top) `shouldBe` predType foo clauseType (HornClause foo (PredGoal (predicate "P" ()) [])) `shouldBe` predType foo clauseType (HornClause foo (PredGoal (predicate "P" ()) [] <> PredGoal (predicate "Q" (True, 'a')) [])) `shouldBe` predType foo it "should compare according to the literals" $ do HornClause foo Top `shouldEqual` HornClause foo Top HornClause foo (PredGoal bar [] <> PredGoal baz []) `shouldEqual` HornClause foo (PredGoal bar [] <> PredGoal baz []) HornClause foo Top `shouldNotEqual` HornClause foo (PredGoal bar []) HornClause foo (PredGoal bar [] <> PredGoal baz []) `shouldNotEqual` HornClause bar (PredGoal foo [] <> PredGoal baz []) HornClause (predicate "P" ()) Top `shouldNotEqual` HornClause (predicate "P" True) Top
jbearer/hspl
test/AstTest.hs
mit
37,781
0
30
10,378
14,282
7,139
7,143
618
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sizeconstraintset-sizeconstraint.html module Stratosphere.ResourceProperties.WAFSizeConstraintSetSizeConstraint where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.WAFSizeConstraintSetFieldToMatch -- | Full data type definition for WAFSizeConstraintSetSizeConstraint. See -- 'wafSizeConstraintSetSizeConstraint' for a more convenient constructor. data WAFSizeConstraintSetSizeConstraint = WAFSizeConstraintSetSizeConstraint { _wAFSizeConstraintSetSizeConstraintComparisonOperator :: Val Text , _wAFSizeConstraintSetSizeConstraintFieldToMatch :: WAFSizeConstraintSetFieldToMatch , _wAFSizeConstraintSetSizeConstraintSize :: Val Integer , _wAFSizeConstraintSetSizeConstraintTextTransformation :: Val Text } deriving (Show, Eq) instance ToJSON WAFSizeConstraintSetSizeConstraint where toJSON WAFSizeConstraintSetSizeConstraint{..} = object $ catMaybes [ (Just . ("ComparisonOperator",) . toJSON) _wAFSizeConstraintSetSizeConstraintComparisonOperator , (Just . ("FieldToMatch",) . toJSON) _wAFSizeConstraintSetSizeConstraintFieldToMatch , (Just . ("Size",) . toJSON) _wAFSizeConstraintSetSizeConstraintSize , (Just . ("TextTransformation",) . toJSON) _wAFSizeConstraintSetSizeConstraintTextTransformation ] -- | Constructor for 'WAFSizeConstraintSetSizeConstraint' containing required -- fields as arguments. wafSizeConstraintSetSizeConstraint :: Val Text -- ^ 'wafscsscComparisonOperator' -> WAFSizeConstraintSetFieldToMatch -- ^ 'wafscsscFieldToMatch' -> Val Integer -- ^ 'wafscsscSize' -> Val Text -- ^ 'wafscsscTextTransformation' -> WAFSizeConstraintSetSizeConstraint wafSizeConstraintSetSizeConstraint comparisonOperatorarg fieldToMatcharg sizearg textTransformationarg = WAFSizeConstraintSetSizeConstraint { _wAFSizeConstraintSetSizeConstraintComparisonOperator = comparisonOperatorarg , _wAFSizeConstraintSetSizeConstraintFieldToMatch = fieldToMatcharg , _wAFSizeConstraintSetSizeConstraintSize = sizearg , _wAFSizeConstraintSetSizeConstraintTextTransformation = textTransformationarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sizeconstraintset-sizeconstraint.html#cfn-waf-sizeconstraintset-sizeconstraint-comparisonoperator wafscsscComparisonOperator :: Lens' WAFSizeConstraintSetSizeConstraint (Val Text) wafscsscComparisonOperator = lens _wAFSizeConstraintSetSizeConstraintComparisonOperator (\s a -> s { _wAFSizeConstraintSetSizeConstraintComparisonOperator = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sizeconstraintset-sizeconstraint.html#cfn-waf-sizeconstraintset-sizeconstraint-fieldtomatch wafscsscFieldToMatch :: Lens' WAFSizeConstraintSetSizeConstraint WAFSizeConstraintSetFieldToMatch wafscsscFieldToMatch = lens _wAFSizeConstraintSetSizeConstraintFieldToMatch (\s a -> s { _wAFSizeConstraintSetSizeConstraintFieldToMatch = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sizeconstraintset-sizeconstraint.html#cfn-waf-sizeconstraintset-sizeconstraint-size wafscsscSize :: Lens' WAFSizeConstraintSetSizeConstraint (Val Integer) wafscsscSize = lens _wAFSizeConstraintSetSizeConstraintSize (\s a -> s { _wAFSizeConstraintSetSizeConstraintSize = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sizeconstraintset-sizeconstraint.html#cfn-waf-sizeconstraintset-sizeconstraint-texttransformation wafscsscTextTransformation :: Lens' WAFSizeConstraintSetSizeConstraint (Val Text) wafscsscTextTransformation = lens _wAFSizeConstraintSetSizeConstraintTextTransformation (\s a -> s { _wAFSizeConstraintSetSizeConstraintTextTransformation = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/WAFSizeConstraintSetSizeConstraint.hs
mit
3,944
0
13
330
441
252
189
42
1
{-# LANGUAGE OverloadedStrings #-} module Machine (Machine(..), compute, checkMachine, checkInput) where import Prelude hiding (read, head) import qualified Data.Vector as V (toList) import qualified Data.HashMap.Strict as HM (lookup, toList) import Data.Aeson import Data.Aeson.Types import Data.List hiding (head) import Data.Text (Text, unpack) import Control.Applicative import Control.Arrow (first) import Utilities import Tape -- Data manipulation compute :: (Machine, Tape) -> (String, Maybe (Machine, Tape)) compute (machine, tape) = (show tape ++ " " ++ trStr, next) where tr = getTransition machine (head tape) trStr = either (\ x -> if ($ machine) hasHalted {- Reads like a fine wine, though I do not like alcohol -} then "Halted: (" ++ initial machine ++ ")" else x) (showTransition . (,) (initial machine, head tape)) tr next = either (const Nothing) (\ (nextState, symbol, move) -> Just (machine {initial = nextState}, applyTransition symbol move tape)) tr getTransition :: Machine -> Char -> Either String (String, Char, Action) getTransition machine symbol = maybeToEither err $ lookup (initial machine, symbol) (transitions machine) where err = "Could not find matching transition for the pair (" ++ initial machine ++ ", " ++ [symbol] ++ ")." applyTransition :: Char -> Action -> Tape -> Tape applyTransition c a = moveHead a . Tape.write c moveHead :: Action -> Tape -> Tape moveHead LEFT = left moveHead RIGHT = right hasHalted :: Machine -> Bool hasHalted m = initial m `elem` finals m -- Data definition data Machine = Machine { name :: String , alphabet :: [Char] , blank :: Char , states :: [String] , initial :: String , finals :: [String] , transitions :: [Transition] } instance Show Machine where show machine = unlines $ [replicate 80 '*' , "*" ++ filler ++ nameMachine ++ filler ++ "*" , replicate 80 '*' , "Alphabet: [" ++ intercalate ", " (map (:[]) $ alphabet machine) ++ "]" , "States : [" ++ intercalate ", " (states machine) ++ "]" , "Initial : " ++ initial machine , "Finals : [" ++ intercalate ", " (finals machine) ++ "]"] ++ map showTransition (transitions machine) ++ [replicate 80 '*'] where nameMachine = name machine ++ if even $ length (name machine) then "" else " " filler = replicate (39 - (length nameMachine `div` 2)) ' ' type Transition = ((String, Char), (String, Char, Action)) showTransition :: Transition -> String showTransition t = "(" ++ from_state t ++ ", " ++ [read t] ++ ") -> (" ++ to_state t ++ ", " ++ [Machine.write t] ++ ", " ++ show (action t) ++ ")" from_state :: Transition -> String read :: Transition -> Char to_state :: Transition -> String write :: Transition -> Char action :: Transition -> Action from_state ((f_s, _), _) = f_s read ((_, r), _) = r to_state (_, (t_s, _, _)) = t_s write (_, (_, w, _)) = w action (_, (_, _, a)) = a data JSONTransition = JSONTransition { read_ :: Char -- read , to_state_ :: String -- to_state , write_ :: Char -- write , action_ :: Action -- action } data Action = LEFT | RIGHT deriving (Show, Eq) -- Parsing instance FromJSON JSONTransition where parseJSON (Object v) = JSONTransition <$> v .: "read" <*> v .: "to_state" <*> v .: "write" <*> lookupAndParse (withText "action" parseAction) "action" v parseJSON _ = empty instance FromJSON Machine where parseJSON (Object v) = Machine <$> v .: "name" <*> lookupAndParse (withArray "alphabet" (mapM parseJSON . V.toList)) "alphabet" v <*> v .: "blank" <*> v .: "states" <*> v .: "initial" <*> v .: "finals" <*> lookupAndParse (withObject "transitions" (concatMapM parseTransition . extractTransitions)) "transitions" v parseJSON _ = empty parseTransition :: (String, Value) -> Parser [Transition] parseTransition (state, arr) = fmap (\ x -> ((state, read_ x), (to_state_ x, write_ x, action_ x))) <$> go arr where go = withArray state (mapM parseJSON . V.toList) :: Value -> Parser [JSONTransition] extractTransitions :: Object -> [(String, Value)] extractTransitions = map (first unpack) . HM.toList parseAction :: Text -> Parser Action parseAction "LEFT" = pure LEFT parseAction "RIGHT" = pure RIGHT parseAction txt = fail $ "key \"action\" expected either \"LEFT\" or \"RIGHT\" value instead of " ++ unpack txt lookupAndParse :: (Value -> Parser a) -> Text -> Object -> Parser a lookupAndParse f key obj = case HM.lookup key obj of Nothing -> fail $ "key " ++ show key ++ " not present" Just val -> f val -- Verification checkMachine :: Machine -> Bool checkMachine m = blank m `elem` alphabet m && initial m `elem` states m && null (finals m \\ states m) && all (checkTransition m) (transitions m) checkTransition :: Machine -> Transition -> Bool checkTransition m t = from_state t `elem` states m && Machine.read t `elem` alphabet m && to_state t `elem` states m && Machine.write t `elem` alphabet m checkInput :: Machine -> String -> Bool checkInput m = all (`elem` alphabet m)
Shakadak/ft_turing
src/Machine.hs
mit
5,804
0
21
1,784
1,857
1,003
854
110
2
{-# LANGUAGE DeriveDataTypeable, RecordWildCards #-} {-# OPTIONS_GHC -fno-cse #-} module Options( JBOpt(..) , ExplStrategy(..) , ReprType(..) , RTDetail(..) , Quotienting(..) , PreorderRed(..) , TypeInfAlg(..) , jbModes , whenLoud , isLoud , whenNormal , isNormal ) where import Version import System.Console.CmdArgs data JBOpt = Explore { -- interactive execution of operational semantics inputFile :: FilePath , strategy :: ExplStrategy , nonStop :: Bool , withStats :: Bool , colored :: Bool , strDotFile :: Maybe FilePath , optUnfolding :: Bool } | Analyse { -- generation of reachability tree inputFile :: FilePath -- , nonStop :: Bool , rtDetails :: [RTDetail] , maxPathLen :: Maybe Integer , maxDepth :: Maybe Integer , reachDotFile :: Maybe FilePath , reduction :: PreorderRed , quotienting :: Quotienting , colored :: Bool } | Convert { -- transformation of pi-terms into other representations inputFiles :: [FilePath] , inputTerm :: Maybe String , outputFile :: Maybe FilePath , extension :: Maybe String , withStats :: Bool , colored :: Bool , outType :: ReprType } | TypeInf { -- hierarchical type inference inputFiles :: [FilePath] , inputTerm :: Maybe String , skipUnsupported :: Bool , showFileNames :: Maybe Bool , colored :: Bool , algorithm :: TypeInfAlg , abstract :: Bool , withStats :: Bool } deriving (Show, Data, Typeable) data ExplStrategy = Ask | LeftMost | Random deriving (Show, Eq, Data, Typeable) data RTDetail = AllCovering | FstCovering | ShowCongr | TermSnippet | HideQuot | HideUnfLbl deriving (Show, Eq, Data, Typeable) data Quotienting = NoQuot | SiblingsQuot | GlobalQuot deriving (Show, Eq, Ord, Data, Typeable) data PreorderRed = NoRed | GroupUnf deriving (Show, Eq, Ord, Data, Typeable) data ReprType = NoOutput | Normalised | NormalForm | Standard | Restricted | StdPict | JavaScript -- | StrPict deriving (Show, Eq, Data, Typeable) data TypeInfAlg = AlgComplete | AlgAltCompl | AlgIncomplete | AlgSimple deriving (Eq, Data, Typeable) instance Show TypeInfAlg where show AlgComplete = "complete" show AlgAltCompl = "alternative" show AlgIncomplete = "incomplete" show AlgSimple = "simple typing" explore :: JBOpt explore = Explore { inputFile = def &= typFile &= argPos 0 -- &= help "File containing the input PiCalc program" , strategy = enum [ Ask &= help "Let the user select the redex (default)" , LeftMost &= help "Pick the leftmost redex" , Random &= help "Pick a redex at random" ] -- , strategy = Ask -- &= help ("Redex selection strategy in reductions. Choices: ask, leftmost, random") -- &= typ "STRATEGY" -- &= name "s" , optUnfolding = False &= name "group-unf" &= name "u" &= explicit &= help "Preorder reduction on successors" , nonStop = False &= name "n" &= help "Do not prompt the user after each reduction" , withStats = False &= name "stats" &= name "S" &= explicit &= typFile &= help "Print some stats about the input program" , colored = False &= help "Use colors in output" , strDotFile = Nothing &= typFile &= name "o" &= name "dump" &= explicit &= help "Save the current state as a dot graph in FILE" } &= auto &= details ["Execute the operational semantics of the term, step by step"] analyse :: JBOpt analyse = Analyse { inputFile = def &= typFile &= argPos 0 , reachDotFile = Nothing &= typFile &= name "o" &= name "dump" &= explicit &= help "Save the reachability graph as a dot file in FILE" , reduction = enum [ NoRed &= ignore , GroupUnf &= name "group-unf" &= name "u" &= explicit &= help "Performs unfolding actions together to reduce ininfluent interleaving" ] , quotienting = NoQuot &= typ "QUOT" &= name "Q" &= name "quot" &= explicit &= help "Quotient states by congruence (no, siblings, global)" -- , quotienting = enum [ -- NoQuot &= ignore -- , SiblingsQuot -- &= help "Quotient siblings by congruence" -- , GlobalQuot -- &= help "Quotient states by congruence" -- ] , rtDetails = enum [ [] &= ignore , [FstCovering] &= name "fst-cov" &= help "Show closest covered ancestor" , [AllCovering] &= name "all-cov" &= help "Show all covered ancestors (slow)" , [ShowCongr] &= name "congr" &= help "Show congruence relation (slow)" , [HideQuot] &= name "hide-quot" &= help "Hide edges to quotiented nodes" , [HideUnfLbl] &= name "hide-unf" &= help "Hide unfolding actions on edges" , [TermSnippet] &= name "snippet" &= help "Show a snippet of the term in the state nodes" ] -- &= typ "0-4" -- &= name "D" &= name "detail" &= explicit -- &= help "0 - successors, 1 - processes, 2 - closest covered ancestor, 3 - all covered ancestors, 4 - congruence." , maxPathLen = Nothing &= typ "N" &= name "p" &= help "Stop exploring a path when it's longer than N" , maxDepth = Nothing &= typ "N" &= name "d" &= help "Stop exploring a path when reaching a term exceeding N in depth" , colored = False &= help "Use colors in output" } &= details ["Generate the reachability tree"] convert :: JBOpt convert = Convert { -- TODO: 1. get args and default to stdin, -- 2. add --term piterm option skipping reading file -- 3. accept more than one file at once, option "--ext" allows to output to FILE.ext inputFiles = [] &= typFile &= args , outputFile = Nothing &= typFile &= name "output" &= name "o" &= explicit &= help "Converted output file (use `-` for stdout)" , inputTerm = Nothing &= name "term" &= name "t" &= explicit &= typ "PITERM" &= help "The term to be converted" , extension = Nothing &= typ "EXT" &= name "ext" &= name "e" &= explicit &= help "Converted term is output in INPUTFILEPATH.EXT" , withStats = False &= name "S" &= name "stats" &= explicit &= typFile &= help "Print some stats about the input program" , colored = False &= help "Use colors in output" , outType = enum [ Normalised &= help "No-confl and normalised (default)" , Standard &= help "Standard normal form" , NormalForm &= name "nf" &= help "Normal form (see hierarchical systems)" , Restricted &= help "Minimal restricted normal form" , StdPict &= name "graph" &= name "g" &= explicit &= help "Standard Normal Form graph" , JavaScript &= name "js" &= name "j" &= explicit &= help "JavaScript representation" -- , StrPict &= name "struct" &= explicit &= help "Structural graph" , NoOutput &= name "n" &= name "none" &= explicit &= help "Mainly useful with --stats" ] -- , outType = Normalised -- &= help "Redex selection strategy in reductions." -- &= typ "TYPE" -- &= name "t" &= name "type" &= explicit } &= details ["Transform the input pi term into different representations"] typeinf :: JBOpt typeinf = TypeInf { inputFiles = [] &= typ "[FILE..]" &= args , inputTerm = Nothing &= name "t" &= name "term" &= explicit &= typ "PITERM" &= help "The term to be typed" , skipUnsupported = False &= name "skip" &= name "u" &= explicit &= help "Skip unsupported input terms" , colored = False &= help "Use colors in output" , showFileNames = Nothing &= name "filenames" &= name "f" &= explicit &= help "Show filename of input" , algorithm = enum [ AlgComplete &= name "complete" &= explicit &= help "Default complete inference" , AlgAltCompl &= name "alternative" &= name "a" &= explicit &= help "Alternative implementation of complete inference" , AlgIncomplete &= name "incomplete" &= name "i" &= explicit &= help "Fast Incomplete inference" , AlgSimple &= name "simple" &= name "s" &= explicit &= help "Only perform simple typing" ] &= help "Inference algorithm" -- , simple = False -- &= help "Only perform simple typing" -- , incomplete = False -- &= help "Use incomplete type system" , abstract = False &= help "TODO! - Abstract a term until it can be proved depth-bounded" , withStats = False &= name "stats" &= name "S" &= explicit &= typFile &= help "TODO! - Print some stats about the typing" } &= details ["Infer hierarchical types from a pi term"] jbModes :: String -> IO JBOpt jbModes pun = cmdArgs $ modes [explore, analyse, convert, typeinf {- , verify, bound, cfa, abstract -}] &= program "jb" &= help "Play with π-calculus terms and their semantics" &= summary (versionInfoWith pun) &= verbosity test = jbModes "\n"
bordaigorl/jamesbound
src/Options.hs
gpl-2.0
9,545
0
15
2,956
1,942
1,044
898
179
1
{- Game2048.Board.Base • framework for representing the grid of tiles - Copyright ©2014 Christopher League <league@contrapunctus.net> - - This program is free software: you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by the Free - Software Foundation, either version 3 of the License, or (at your option) - any later version. -} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} module Game2048.Board.Base ( Move(..) , Board , Board'(..) , edges , moveViaCoordLists , movesByChar , placeRandom , rows, cols , rowsRev, colsRev , squeeze , start , straits ) where import Control.DeepSeq (NFData(..)) import Control.Monad (liftM) import Control.Monad.State (MonadState, state) import Data.Maybe (fromJust) import Game2048.Coord import Game2048.Tile import Game2048.Util import Prelude hiding (Left, Right, foldr) import System.Random (RandomGen, Random, random) data Move = Left | Right | Up | Down deriving (Enum, Bounded, Show, Eq) instance NFData Move where movesByChar :: [(Char, Move)] movesByChar = map f every where f :: Move -> (Char, Move) f m = (head (show m), m) class Board' b where foldr :: (Tile -> a -> a) -> a -> b Tile -> a freeCells :: b Tile -> [Coord] fromList :: [[Tile]] -> b Tile move :: b Tile -> Move -> b Tile placeTile :: Tile -> Coord -> b Tile -> b Tile show2D :: b Tile -> String tileAt :: b Tile -> Coord -> Tile foldr1 :: (Tile -> Tile -> Tile) -> b Tile -> Tile foldr1 f b = fromJust $ foldr g Nothing b where g t0 Nothing = Just t0 g t1 (Just t2) = Just $ f t1 t2 freeCount :: b Tile -> Int freeCount = length . freeCells show2D b = unlines (map eachRow rows) where eachRow = concat . map eachCol eachCol = padLeft 6 . show . tileAt b maybeMove :: Board b Tile => b Tile -> Move -> Maybe (Move, b Tile) maybeMove b m = if b' == b then Nothing else Just (m, b') where b' = move b m type Board b t = (Board' b, Eq (b t), Zero (b t)) squeeze' :: Int -> [Tile] -> [Tile] squeeze' k = loop k . filter (not . isEmpty) where loop n [] = replicate n zero loop n (t1:t2:ts') | t1 == t2 = succ t1 : loop (n-1) ts' loop n (t:ts) = t : loop (n-1) ts squeeze :: Int -> [(a,Tile)] -> [(a,Tile)] squeeze k cts = zip (map fst cts) $ squeeze' k $ map snd cts moveViaCoordLists :: Board b Tile => b Tile -> Move -> [(Int,Tile)] moveViaCoordLists b m = filter p $ concat $ map (squeeze k) cts where cts = map (map f) cc f c = (fromEnum c, tileAt b c) p = not . isEmpty . snd (k, cc) = case m of Left -> (rowSize, rows) Right -> (rowSize, rowsRev) Up -> (colSize, cols) Down -> (colSize, colsRev) rowRange, colRange :: [Int] rowRange = [0 .. row maxBound] colRange = [0 .. col maxBound] rows, cols, rowsRev, colsRev, straits, edges :: [[Coord]] rows = map (\i -> map (coord i) colRange) rowRange cols = map (\j -> map (flip coord j) rowRange) colRange straits = rows ++ cols rowsRev = map reverse rows colsRev = map reverse cols edges = [top, bottom, left, right] where r = row maxBound c = col maxBound top = map (coord 0) colRange bottom = map (coord r) colRange left = map (flip coord 0) rowRange right = map (flip coord c) rowRange placeRandom :: (RandomGen g, MonadState g m, Board b Tile) => b Tile -> m (Maybe (b Tile)) placeRandom b = case freeCells b of [] -> return Nothing cs -> do c <- choose cs t <- state random return $ Just $ placeTile t c b placeRandom' :: (RandomGen g, MonadState g m, Board b Tile) => b Tile -> m (b Tile) placeRandom' = liftM fromJust . placeRandom start :: (RandomGen g, MonadState g m, Board b Tile) => m (b Tile) start = placeRandom' zero >>= placeRandom'
league/game2048
src/Game2048/Board/Base.hs
gpl-3.0
4,018
0
12
1,091
1,565
834
731
98
4
module File ( buildJobList ) where -- Project Level Imports -- import Jobs (buildJob) import Macros (expandMacros) import Datatypes (Document (..), Job (..)) -- Global Level Imports -- import Data.Char (isSpace) import Data.List (isPrefixOf) import Control.DeepSeq (($!!)) import Control.Monad (liftM) import System.IO (withFile, IOMode (ReadMode), hGetContents) -- Public Functions -- buildJobList :: Document -> IO [Job] buildJobList doc = liftM (parseHeader . expandMacros doc) $ readHeader $ path doc -- Header Parsing Functions -- readHeader :: String -> IO [String] readHeader docPath = withFile docPath ReadMode $ \ docFile -> do -- readFile is not used to ensure the file handle is closed docStr <- hGetContents docFile let header = takeHeader docStr -- Ensures the header is extract before the handle is close return $!! header where takeHeader = takeWhile couldBeHeader . rstripWhitespace . lines couldBeHeader line = foldl (\ acc job -> job `isPrefixOf` line || acc) -- Must contain all types of jobs and macro any could appear in the header False ["%command", "%link", "%link-doc", "%clean", "%macro"] parseHeader :: [String] -> [Job] parseHeader headerLines = reverse $ foldl buildJobs [] headerLines where buildJobs acc line = buildJob (words line) : acc -- Helper Functions -- rstripWhitespace :: [String] -> [String] rstripWhitespace = map $ reverse . dropWhile isSpace . reverse
skejserjensen/AAUDOC
src/File.hs
gpl-3.0
1,559
0
12
375
391
218
173
25
1
-- Copyright (C) 2010 John Millikin <jmillikin@gmail.com> -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. module UI.NCurses.Types where import qualified Control.Applicative as A import Control.Monad (liftM, ap) import Control.Monad.Fix (MonadFix, mfix) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Trans.Reader (ReaderT) import Control.Monad.Trans.Class (lift) import qualified Foreign as F import qualified Foreign.C as F import qualified UI.NCurses.Enums as E -- | A small wrapper around 'IO', to ensure the @ncurses@ library is -- initialized while running. newtype Curses a = Curses { unCurses :: IO a } instance Monad Curses where return = Curses . return m >>= f = Curses (unCurses m >>= unCurses . f) instance MonadFix Curses where mfix f = Curses (mfix (unCurses . f)) instance MonadIO Curses where liftIO = Curses instance Functor Curses where fmap = liftM instance A.Applicative Curses where pure = return (<*>) = ap newtype Update a = Update { unUpdate :: ReaderT Window Curses a } instance Monad Update where return = Update . return m >>= f = Update (unUpdate m >>= unUpdate . f) instance MonadIO Update where liftIO io = Update$ lift (liftIO io) instance MonadFix Update where mfix f = Update (mfix (unUpdate . f)) instance Functor Update where fmap = liftM instance A.Applicative Update where pure = return (<*>) = ap newtype Window = Window { windowPtr :: F.Ptr Window } deriving Show checkRC :: String -> F.CInt -> IO () checkRC name rc = if toInteger rc == E.fromEnum E.ERR then error $ name ++ ": rc == ERR" else return () cToBool :: Integral a => a -> Bool cToBool 0 = False cToBool _ = True cFromBool :: Integral a => Bool -> a cFromBool False = 0 cFromBool True = 1
rrnewton/ncurses-haskell
lib/UI/NCurses/Types.hs
gpl-3.0
2,383
4
10
477
578
328
250
48
2
{-| Module : Database/Hedsql/Statements/Create.hs Description : Collection of CREATE statements. Copyright : (c) Leonard Monnier, 2015 License : GPL-3 Maintainer : leonard.monnier@gmail.com Stability : experimental Portability : portable A collection of CREATE statements to be used in tests or as examples. -} module Database.Hedsql.Statements.Create ( -- * Full examples countries , people -- * Basics , simpleTable , defaultVal -- * Constraints -- ** PRIMARY KEY , primaryKeyCol , primaryKeyColAuto , primaryKeyTable -- ** UNIQUE , createUnique , createUniqueT -- ** NOT NULL , noNulls -- ** FOREIGN KEY , createFK -- ** CHECK , createCheck , createChecks ) where -------------------------------------------------------------------------------- -- IMPORTS -------------------------------------------------------------------------------- import Database.Hedsql import Database.Hedsql.Ext() -------------------------------------------------------------------------------- -- PUBLIC -------------------------------------------------------------------------------- ---------------------------------------- -- Full examples ---------------------------------------- {-| MariaDB and SqLite: @ CREATE TABLE "Countries" ( "countryId" INTEGER PRIMARY KEY AUTOINCREMENT, "name" VARCHAR(256) NOT NULL, UNIQUE, "size" INTEGER, "inhabitants" INTEGER ) @ PostgreSQL: @ CREATE TABLE "Countries" ( "countryId" serial PRIMARY KEY, "name" varchar(256) NOT NUL, UNIQUE, "size" integer, "inhabitants" integer ) @ -} countries :: CreateTableStmt dbVendor countries = createTable "Countries" [ wrap (col "countryId" integer) /++ primary True , wrap (col "name" (varchar 256)) /++ [notNull, unique] , wrap $ col "size" integer , wrap $ col "inhabitants" integer ] {-| MariaDB and SqLite: @ CREATE TABLE "People" ( "personId" INTEGER PRIMARY KEY AUTOINCREMENT, "title" CHAR(2) DEFAULT('Ms') "firstName" VARCHAR(256) NOT NULL, "lastName" VARCHAR(256) NOT NULL, "age" INTEGER CHECK ("age" > -1), "married" BOOLEAN DEFAULT(FALSE), NOT NULL "father" INTEGER REFERENCES "People"("personId") "passportNo" VARCHAR(256) UNIQUE, "countryId" INTEGER REFERENCES "Countries"("countryId") ) @ PostgreSQL: @ CREATE TABLE "People" ( "personId" serial PRIMARY KEY, "title" char(2) DEFAULT('Ms') "firstName" varchar(256) NOT NULL, "lastName" varchar(256) NOT NULL, "age" integer CHECK ("age" > -1), "married" boolean DEFAULT(FALSE), NOT NULL "passportNo" varchar(256) UNIQUE, "father" integer REFERENCES "People"("personId") "countryId" integer REFERENCES "Countries"("countryId") ) @ -} people :: CreateTableStmt dbVendor people = createTable "People" [ wrap (col "personId" integer) /++ primary True , wrap (col "title" (char 2)) /++ defaultValue (value "Ms") , wrap (col "firstName" (varchar 256)) /++ notNull , wrap (col "lastName" (varchar 256)) /++ notNull , wrap age /++ check (age /> value (-1::Int)) , wrap (col "married" boolean) /++ [defaultValue (value False), notNull] , wrap (col "passportNo" (varchar 256)) /++ unique , wrap (col "father" integer) /++ foreignKey "People" "personId" , wrap (col "countryId" integer) /++ foreignKey "Countries" "countryId" ] where age = col "age" integer ---------------------------------------- -- Basics ---------------------------------------- -- | > CREATE TABLE "People" ("firstName" varchar(256)) simpleTable :: Create dbVendor simpleTable = createTable "People" [wrap (col "firstName" $ varchar 256)] |> end -- | CREATE TABLE "People" ("country" integer DEFAULT(1)) defaultVal :: CreateTableStmt dbVendor defaultVal = createTable "People" [wrap (col "country" integer) /++ defaultValue (value (1::Int))] ---------------------------------------- -- Constraints ---------------------------------------- -------------------- -- PRIMARY KEY -------------------- {-| Maria DB and SqLite: > CREATE TABLE "People" ("personId" INTEGER PRIMARY KEY) PostgreSQL: > CREATE TABLE "People" ("personId" integer PRIMARY KEY) -} primaryKeyCol :: CreateTableStmt dbVendor primaryKeyCol = createTable "People" [wrap (col "personId" integer) /++ primary False] {-| Maria DB and SqLite: > CREATE TABLE "People" ("id" INTEGER PRIMARY KEY AUTOINCREMENT) PostgreSQL: > CREATE TABLE "People" ("id" serial PRIMARY KEY) -} primaryKeyColAuto :: CreateTableStmt dbVendor primaryKeyColAuto = createTable "People" [wrap (col "personId" integer) /++ primary True] {-| CREATE TABLE "People" ( "firstName" varchar(256), "lastName" varchar(256), CONSTRAINT "pk" PRIMARY KEY ("firstName", "lastName") ) -} primaryKeyTable :: Create dbVendor primaryKeyTable = createTable "People" [ wrap $ col "firstName" (varchar 256) , wrap $ col "lastName" (varchar 256)] |> constraints (primaryT (Just "pk") ["firstName", "lastName"]) |> end -------------------- -- UNIQUE -------------------- -- | CREATE TABLE "People" ("passportNo" varchar(256) UNIQUE) createUnique :: CreateTableStmt dbVendor createUnique = createTable "People" [wrap (col "passportNo" (varchar 256)) /++ unique] {-| CREATE TABLE "People" ( "firstName" varchar(256), "lastName" varchar(256), UNIQUE ("firstName", "lastName") ) -} createUniqueT :: Create dbVendor createUniqueT = createTable "People" cs |> constraints (uniqueT Nothing cs) |> end where cs = [ wrap $ col "firstName" $ varchar 256 , wrap $ col "lastName" $ varchar 256 ] -------------------- -- NOT NULL -------------------- {-| CREATE TABLE "People" ( "firstName" varchar(256) CONSTRAINT "no_null" NOT NULL, "lastName" varchar(256) NOT NULL ) -} noNulls :: CreateTableStmt dbVendor noNulls = createTable "People" cs where cs = [ wrap (col "firstName" (varchar 256)) /++ colConstraint "no_null" notNull , wrap (col "lastName" (varchar 256)) /++ notNull ] -------------------- -- FOREIGN KEY -------------------- {-| CREATE TABLE "People" ("countryId" integer REFERENCES "Countries"("countryId")) -} createFK :: CreateTableStmt dbVendor createFK = createTable "People" [wrap (col "countryId" integer) /++ foreignKey "Countries" "countryId"] -------------------- -- CHECK -------------------- -- | CREATE TABLE "People" ("age" integer CHECK ("age" > -1)) createCheck :: CreateTableStmt dbVendor createCheck = createTable "People" [wrap age /++ check (age /> intVal (-1))] where age = col "age" integer {-| CREATE TABLE "People" ( "lastName" varchar(256), "age" integer, CONSTRAINT "checks" CHECK ("age" > -1 AND "lastName" <> '') ) -} createChecks :: Create dbVendor createChecks = createTable "People" [ wrap lastName , wrap age ] |> c1 |> end where age = col "age"integer lastName = col "lastName" $ varchar 256 c1 = constraints $ checkT (Just "checks") $ (age /> intVal (-1)) `and_` (lastName /<> value "")
momomimachli/Hedsql
tests/Database/Hedsql/Statements/Create.hs
gpl-3.0
7,246
0
13
1,479
1,144
607
537
97
1
{-# LANGUAGE OverloadedStrings #-} module MirakelBot.Handlers.Fun where import Control.Lens import Control.Monad import qualified Data.Map as M import qualified Data.Text as T import MirakelBot.HandlerHelpers import MirakelBot.Handlers import MirakelBot.Message.Send import MirakelBot.Types init :: Irc () init = void . registerBangHandlerWithHelp "parrot" "Parrot a user" $ \user -> do c <- getCurrentChannel ul <- getUserList c let nick = Nick user guard $ nick `M.member` ul i <- runIrc . registerHandler $ do msg <- getMessage guard $ msg ^? privateSender._Just == Just nick answer $ msg ^. privateMessage _ <- runIrc . registerBangHandler (T.pack "unparrot") $ \user' -> do guard (user' == user) runIrc $ unregisterHandler i unregisterSelf return ()
azapps/mirakelbot
src/MirakelBot/Handlers/Fun.hs
gpl-3.0
930
0
16
283
250
127
123
-1
-1
-- | A binary tree. module Data.BinTree where import Control.Monad.State import Data.Functor.Fixedpoint data BinTree a = Nil | Fork a (BinTree a) (BinTree a) deriving (Show, Eq) -- | Computes the leaves of a binary tree by straightforward recursion, -- using lists. leaves :: BinTree a -> [a] leaves Nil = [] leaves (Fork x Nil Nil) = [x] leaves (Fork _ lt rt) = leaves lt ++ leaves rt leavesT :: BinTree a -> [a] leavesT = leavesT' [] where leavesT' xs Nil = xs leavesT' xs (Fork x Nil Nil) = x : xs leavesT' xs (Fork _ lt rt) = leavesT' (leavesT' xs lt) rt -- | Recursion using difference lists. leavesC :: BinTree a -> [a] -> [a] leavesC Nil = id leavesC (Fork x Nil Nil) = \xs -> x : xs leavesC (Fork _ lt rt) = leavesC lt . leavesC rt -- | Computes the leaves of a binary tree by straightforward recursion, -- using difference lists. leaves' :: BinTree a -> [a] leaves' t = leavesC t [] -- | Compute the leaves in a state monad. leavesS :: BinTree a -> [a] leavesS t = execState (leavesS' t) [] where leavesS' :: BinTree a -> State [a] () leavesS' Nil = return () leavesS' (Fork x Nil Nil) = modify (\xs -> x:xs) leavesS' (Fork _ lt rt) = leavesS' lt >> leavesS' rt -- | Generate a tree from a list. mkTree :: [a] -> BinTree a mkTree [] = Nil mkTree (x:xs) = Fork x (mkTree lxs) (mkTree rxs) where (lxs, rxs) = splitAt ((length xs + 1) `div` 2) xs -- | Functor whose fixed point is a binary tree. data BinTreeF a b = NilF | ForkF a b b instance Functor (BinTreeF a) where fmap f NilF = NilF fmap f (ForkF x lt rt) = ForkF x (f lt) (f rt) -- | Same as BinTree, but defined as a fixed point of a functor. type BinTreeE a = Fix (BinTreeF a) toBinTreeE :: BinTree a -> BinTreeE a toBinTreeE Nil = Fix NilF toBinTreeE (Fork val lt rt) = Fix (ForkF val (toBinTreeE lt) (toBinTreeE rt)) mkTreeE :: [a] -> BinTreeE a mkTreeE = toBinTreeE . mkTree -- | Leaf enumeration routine implemented as a catamorphism. leavesCata :: BinTreeE a -> [a] leavesCata = cata gatherLeaves where gatherLeaves :: BinTreeF a [a] -> [a] gatherLeaves NilF = [] gatherLeaves (ForkF x [] []) = [x] gatherLeaves (ForkF _ xs ys) = xs ++ ys
capitanbatata/sandbox
leaves-of-a-tree/src/Data/BinTree.hs
gpl-3.0
2,215
0
12
525
875
454
421
47
3
module Control.Pipe.C3 ( -- * Pipes commandSender, commandReceiver ) where import Control.Monad ( forever ) import Control.Monad.Trans.Class ( lift ) import Control.Pipe.Serialize ( serializer, deserializer ) import Control.Pipe.Socket ( Handler ) import Data.Serialize ( Serialize ) import Pipes ( runEffect, await, yield, (<-<) ) -- | Send a single command over the outgoing pipe and wait for a -- response. If the incoming pipe is closed before a response -- arrives, returns @Nothing@. commandSender :: (Serialize a, Serialize b) => a -> Handler (Maybe b) commandSender command reader writer = runEffect $ do writer <-< serializer <-< sendCommand receiveResponse <-< (deserializer >> return Nothing) <-< (reader >> return Nothing) where sendCommand = do yield command receiveResponse = do res <- await return (Just res) -- | Wait for commands on the incoming pipe, handle them, and send the -- reponses over the outgoing pipe. commandReceiver :: (Serialize a, Serialize b) => (a -> IO b) -> Handler () commandReceiver executeCommand reader writer = runEffect $ writer <-< serializer <-< commandExecuter <-< deserializer <-< reader where commandExecuter = forever $ do comm <- await yield =<< lift (executeCommand comm)
scvalex/daemons
src/Control/Pipe/C3.hs
gpl-3.0
1,332
0
13
297
330
179
151
25
1
module Server where import Util import Control.Exception (bracket) import Control.Monad import Control.Monad.IO.Class import Control.Monad.Managed import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as BS import Data.Function import Data.Monoid import System.IO import System.Posix.IO import System.Posix.Types (Fd) import System.Process hiding (createPipe) import System.ZMQ4.Monadic import Text.Printf serverMain :: String -> Int -> [String] -> IO () serverMain endpoint port command = do hSetBuffering stdin LineBuffering hSetBuffering stdout NoBuffering hSetBuffering stderr NoBuffering -- Handles are not compatible with System.ZMQ4.Monadic.poll, so make raw -- file descriptors instead. (stdinReadFd, stdinWriteFd) <- createPipe (stdoutReadFd, stdoutWriteFd) <- createPipe (stderrReadFd, stderrWriteFd) <- createPipe runManaged $ do -- But, use handles everywhere else for convenience. stdinReadH <- managed (withHandle stdinReadFd) stdinWriteH <- managed (withHandle stdinWriteFd) stdoutReadH <- managed (withHandle stdoutReadFd) stdoutWriteH <- managed (withHandle stdoutWriteFd) stderrReadH <- managed (withHandle stderrReadFd) stderrWriteH <- managed (withHandle stderrWriteFd) liftIO $ do -- Don't buffer stdout/stderr so we can display things like prompts. hSetBuffering stdinReadH LineBuffering hSetBuffering stdinWriteH LineBuffering hSetBuffering stdoutReadH NoBuffering hSetBuffering stdoutWriteH NoBuffering hSetBuffering stderrReadH NoBuffering hSetBuffering stderrWriteH NoBuffering printf "Spawning '%s'\n" (unwords command) let (x:xs) = command void $ createProcess (proc x xs) { std_in = UseHandle stdinReadH , std_out = UseHandle stdoutWriteH , std_err = UseHandle stdoutWriteH } runZMQ $ do ident <- mkRandomId subscriber <- mkSubscriber publisher <- mkPublisher liftIO . putStrLn $ "Press enter when client(s) are ready." void $ liftIO getLine let stdin_callback _ = do bytes <- liftIO BS.getLine liftIO $ BS.hPutStrLn stdinWriteH bytes sendMulti publisher . serializeMessage . MsgStdin ident $ bytes client_in_callback _ = do msg@(MsgStdin _ contents) <- parseMessageStdin =<< receiveMulti subscriber liftIO $ BS.hPutStrLn stdinWriteH contents displayMessage msg sendMulti publisher (serializeMessage msg) proc_out_callback _ = do bytes <- hGetAvailable stdoutReadH liftIO $ BS.putStr bytes sendMulti publisher . serializeMessage . MsgStdout $ bytes proc_err_callback _ = do bytes <- hGetAvailable stderrReadH liftIO $ BS.hPutStr stderr bytes sendMulti publisher . serializeMessage . MsgStderr $ bytes fix $ \loop -> do evts <- concat <$> poll (-1) [ File stdInput [In] (Just stdin_callback) , Sock subscriber [In] (Just client_in_callback) , File stdoutReadFd [In] (Just proc_out_callback) , File stderrReadFd [In] (Just proc_err_callback) ] unless (Err `elem` evts) loop where mkSubscriber :: ZMQ z (Socket z Sub) mkSubscriber = do let subscriber_endpoint = printf "tcp://%s:%d" endpoint port liftIO $ printf "Subscribing to input on '%s'\n" subscriber_endpoint subscriber <- socket Sub bind subscriber subscriber_endpoint subscribe subscriber "" return subscriber mkPublisher :: ZMQ z (Socket z Pub) mkPublisher = do let publisher_endpoint = printf "tcp://%s:%d" endpoint (port+1) liftIO $ printf "Publishing input and output on '%s'\n" publisher_endpoint publisher <- socket Pub bind publisher publisher_endpoint return publisher withHandle :: Fd -> (Handle -> IO a) -> IO a withHandle fd = bracket (fdToHandle fd) hClose -- | Get all available bytes on a socket. hGetAvailable :: MonadIO m => Handle -> m ByteString hGetAvailable h = do bytes <- liftIO $ BS.hGetNonBlocking h blockSize if BS.length bytes == blockSize then (bytes <>) <$> hGetAvailable h else return bytes where blockSize = 2048
mitchellwrosen/coop
src/Server.hs
gpl-3.0
5,119
0
26
1,854
1,147
551
596
99
2
{-# 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.DynamoDB.BatchGetItem -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | The /BatchGetItem/ operation returns the attributes of one or more items from -- one or more tables. You identify requested items by primary key. -- -- A single operation can retrieve up to 16 MB of data, which can contain as -- many as 100 items. /BatchGetItem/ will return a partial result if the response -- size limit is exceeded, the table's provisioned throughput is exceeded, or an -- internal processing failure occurs. If a partial result is returned, the -- operation returns a value for /UnprocessedKeys/. You can use this value to -- retry the operation starting with the next item to get. -- -- For example, if you ask to retrieve 100 items, but each individual item is -- 300 KB in size, the system returns 52 items (so as not to exceed the 16 MB -- limit). It also returns an appropriate /UnprocessedKeys/ value so you can get -- the next page of results. If desired, your application can include its own -- logic to assemble the pages of results into one data set. -- -- If /none/ of the items can be processed due to insufficient provisioned -- throughput on all of the tables in the request, then /BatchGetItem/ will return -- a /ProvisionedThroughputExceededException/. If /at least one/ of the items is -- successfully processed, then /BatchGetItem/ completes successfully, while -- returning the keys of the unread items in /UnprocessedKeys/. -- -- If DynamoDB returns any unprocessed items, you should retry the batch -- operation on those items. However, /we strongly recommend that you use anexponential backoff algorithm/. If you retry the batch operation immediately, -- the underlying read or write requests can still fail due to throttling on the -- individual tables. If you delay the batch operation using exponential -- backoff, the individual requests in the batch are much more likely to succeed. -- -- For more information, go to <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#BatchOperations Batch Operations and Error Handling> in the /Amazon DynamoDB Developer Guide/. -- -- By default, /BatchGetItem/ performs eventually consistent reads on every -- table in the request. If you want strongly consistent reads instead, you can -- set /ConsistentRead/ to 'true' for any or all tables. -- -- In order to minimize response latency, /BatchGetItem/ retrieves items in -- parallel. -- -- When designing your application, keep in mind that DynamoDB does not return -- attributes in any particular order. To help parse the response by item, -- include the primary key values for the items in your request in the /AttributesToGet/ parameter. -- -- If a requested item does not exist, it is not returned in the result. -- Requests for nonexistent items consume the minimum read capacity units -- according to the type of read. For more information, see <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html#CapacityUnitCalculations Capacity UnitsCalculations> in the /Amazon DynamoDB Developer Guide/. -- -- <http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchGetItem.html> module Network.AWS.DynamoDB.BatchGetItem ( -- * Request BatchGetItem -- ** Request constructor , batchGetItem -- ** Request lenses , bgiRequestItems , bgiReturnConsumedCapacity -- * Response , BatchGetItemResponse -- ** Response constructor , batchGetItemResponse -- ** Response lenses , bgirConsumedCapacity , bgirResponses , bgirUnprocessedKeys ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.DynamoDB.Types import qualified GHC.Exts data BatchGetItem = BatchGetItem { _bgiRequestItems :: Map Text KeysAndAttributes , _bgiReturnConsumedCapacity :: Maybe ReturnConsumedCapacity } deriving (Eq, Read, Show) -- | 'BatchGetItem' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'bgiRequestItems' @::@ 'HashMap' 'Text' 'KeysAndAttributes' -- -- * 'bgiReturnConsumedCapacity' @::@ 'Maybe' 'ReturnConsumedCapacity' -- batchGetItem :: BatchGetItem batchGetItem = BatchGetItem { _bgiRequestItems = mempty , _bgiReturnConsumedCapacity = Nothing } -- | A map of one or more table names and, for each table, the corresponding -- primary keys for the items to retrieve. Each table name can be invoked only -- once. -- -- Each element in the map consists of the following: -- -- /Keys/ - An array of primary key attribute values that define specific items -- in the table. For each primary key, you must provide /all/ of the key -- attributes. For example, with a hash type primary key, you only need to -- provide the hash attribute. For a hash-and-range type primary key, you must -- provide /both/ the hash attribute and the range attribute. -- -- /AttributesToGet/ - One or more attributes to be retrieved from the table. -- By default, all attributes are returned. If a specified attribute is not -- found, it does not appear in the result. -- -- Note that /AttributesToGet/ has no effect on provisioned throughput -- consumption. DynamoDB determines capacity units consumed based on item size, -- not on the amount of data that is returned to an application. -- -- /ConsistentRead/ - If 'true', a strongly consistent read is used; if 'false' -- (the default), an eventually consistent read is used. -- -- bgiRequestItems :: Lens' BatchGetItem (HashMap Text KeysAndAttributes) bgiRequestItems = lens _bgiRequestItems (\s a -> s { _bgiRequestItems = a }) . _Map bgiReturnConsumedCapacity :: Lens' BatchGetItem (Maybe ReturnConsumedCapacity) bgiReturnConsumedCapacity = lens _bgiReturnConsumedCapacity (\s a -> s { _bgiReturnConsumedCapacity = a }) data BatchGetItemResponse = BatchGetItemResponse { _bgirConsumedCapacity :: List "ConsumedCapacity" ConsumedCapacity , _bgirResponses :: Map Text (List "Responses" (Map Text AttributeValue)) , _bgirUnprocessedKeys :: Map Text KeysAndAttributes } deriving (Eq, Read, Show) -- | 'BatchGetItemResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'bgirConsumedCapacity' @::@ ['ConsumedCapacity'] -- -- * 'bgirResponses' @::@ 'HashMap' 'Text' ['HashMap' 'Text' 'AttributeValue'] -- -- * 'bgirUnprocessedKeys' @::@ 'HashMap' 'Text' 'KeysAndAttributes' -- batchGetItemResponse :: BatchGetItemResponse batchGetItemResponse = BatchGetItemResponse { _bgirResponses = mempty , _bgirUnprocessedKeys = mempty , _bgirConsumedCapacity = mempty } -- | The read capacity units consumed by the operation. -- -- Each element consists of: -- -- /TableName/ - The table that consumed the provisioned throughput. -- -- /CapacityUnits/ - The total number of capacity units consumed. -- -- bgirConsumedCapacity :: Lens' BatchGetItemResponse [ConsumedCapacity] bgirConsumedCapacity = lens _bgirConsumedCapacity (\s a -> s { _bgirConsumedCapacity = a }) . _List -- | A map of table name to a list of items. Each object in /Responses/ consists of -- a table name, along with a map of attribute data consisting of the data type -- and attribute value. bgirResponses :: Lens' BatchGetItemResponse (HashMap Text [HashMap Text AttributeValue]) bgirResponses = lens _bgirResponses (\s a -> s { _bgirResponses = a }) . _Map -- | A map of tables and their respective keys that were not processed with the -- current response. The /UnprocessedKeys/ value is in the same form as /RequestItems/, so the value can be provided directly to a subsequent /BatchGetItem/ -- operation. For more information, see /RequestItems/ in the Request Parameters -- section. -- -- Each element consists of: -- -- /Keys/ - An array of primary key attribute values that define specific items -- in the table. -- -- /AttributesToGet/ - One or more attributes to be retrieved from the table or -- index. By default, all attributes are returned. If a requested attribute is -- not found, it does not appear in the result. -- -- /ConsistentRead/ - The consistency of a read operation. If set to 'true', then -- a strongly consistent read is used; otherwise, an eventually consistent read -- is used. -- -- If there are no unprocessed keys remaining, the response contains an empty /UnprocessedKeys/ map. bgirUnprocessedKeys :: Lens' BatchGetItemResponse (HashMap Text KeysAndAttributes) bgirUnprocessedKeys = lens _bgirUnprocessedKeys (\s a -> s { _bgirUnprocessedKeys = a }) . _Map instance ToPath BatchGetItem where toPath = const "/" instance ToQuery BatchGetItem where toQuery = const mempty instance ToHeaders BatchGetItem instance ToJSON BatchGetItem where toJSON BatchGetItem{..} = object [ "RequestItems" .= _bgiRequestItems , "ReturnConsumedCapacity" .= _bgiReturnConsumedCapacity ] instance AWSRequest BatchGetItem where type Sv BatchGetItem = DynamoDB type Rs BatchGetItem = BatchGetItemResponse request = post "BatchGetItem" response = jsonResponse instance FromJSON BatchGetItemResponse where parseJSON = withObject "BatchGetItemResponse" $ \o -> BatchGetItemResponse <$> o .:? "ConsumedCapacity" .!= mempty <*> o .:? "Responses" .!= mempty <*> o .:? "UnprocessedKeys" .!= mempty
dysinger/amazonka
amazonka-dynamodb/gen/Network/AWS/DynamoDB/BatchGetItem.hs
mpl-2.0
10,324
0
16
1,911
805
511
294
78
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.Blogger.Comments.ListByBlog -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists comments by blog. -- -- /See:/ <https://developers.google.com/blogger/docs/3.0/getting_started Blogger API v3 Reference> for @blogger.comments.listByBlog@. module Network.Google.Resource.Blogger.Comments.ListByBlog ( -- * REST Resource CommentsListByBlogResource -- * Creating a Request , commentsListByBlog , CommentsListByBlog -- * Request Lenses , clbbStatus , clbbXgafv , clbbUploadProtocol , clbbAccessToken , clbbEndDate , clbbUploadType , clbbBlogId , clbbStartDate , clbbFetchBodies , clbbPageToken , clbbMaxResults , clbbCallback ) where import Network.Google.Blogger.Types import Network.Google.Prelude -- | A resource alias for @blogger.comments.listByBlog@ method which the -- 'CommentsListByBlog' request conforms to. type CommentsListByBlogResource = "v3" :> "blogs" :> Capture "blogId" Text :> "comments" :> QueryParams "status" CommentsListByBlogStatus :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "endDate" Text :> QueryParam "uploadType" Text :> QueryParam "startDate" Text :> QueryParam "fetchBodies" Bool :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] CommentList -- | Lists comments by blog. -- -- /See:/ 'commentsListByBlog' smart constructor. data CommentsListByBlog = CommentsListByBlog' { _clbbStatus :: !(Maybe [CommentsListByBlogStatus]) , _clbbXgafv :: !(Maybe Xgafv) , _clbbUploadProtocol :: !(Maybe Text) , _clbbAccessToken :: !(Maybe Text) , _clbbEndDate :: !(Maybe Text) , _clbbUploadType :: !(Maybe Text) , _clbbBlogId :: !Text , _clbbStartDate :: !(Maybe Text) , _clbbFetchBodies :: !(Maybe Bool) , _clbbPageToken :: !(Maybe Text) , _clbbMaxResults :: !(Maybe (Textual Word32)) , _clbbCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CommentsListByBlog' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'clbbStatus' -- -- * 'clbbXgafv' -- -- * 'clbbUploadProtocol' -- -- * 'clbbAccessToken' -- -- * 'clbbEndDate' -- -- * 'clbbUploadType' -- -- * 'clbbBlogId' -- -- * 'clbbStartDate' -- -- * 'clbbFetchBodies' -- -- * 'clbbPageToken' -- -- * 'clbbMaxResults' -- -- * 'clbbCallback' commentsListByBlog :: Text -- ^ 'clbbBlogId' -> CommentsListByBlog commentsListByBlog pClbbBlogId_ = CommentsListByBlog' { _clbbStatus = Nothing , _clbbXgafv = Nothing , _clbbUploadProtocol = Nothing , _clbbAccessToken = Nothing , _clbbEndDate = Nothing , _clbbUploadType = Nothing , _clbbBlogId = pClbbBlogId_ , _clbbStartDate = Nothing , _clbbFetchBodies = Nothing , _clbbPageToken = Nothing , _clbbMaxResults = Nothing , _clbbCallback = Nothing } clbbStatus :: Lens' CommentsListByBlog [CommentsListByBlogStatus] clbbStatus = lens _clbbStatus (\ s a -> s{_clbbStatus = a}) . _Default . _Coerce -- | V1 error format. clbbXgafv :: Lens' CommentsListByBlog (Maybe Xgafv) clbbXgafv = lens _clbbXgafv (\ s a -> s{_clbbXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). clbbUploadProtocol :: Lens' CommentsListByBlog (Maybe Text) clbbUploadProtocol = lens _clbbUploadProtocol (\ s a -> s{_clbbUploadProtocol = a}) -- | OAuth access token. clbbAccessToken :: Lens' CommentsListByBlog (Maybe Text) clbbAccessToken = lens _clbbAccessToken (\ s a -> s{_clbbAccessToken = a}) clbbEndDate :: Lens' CommentsListByBlog (Maybe Text) clbbEndDate = lens _clbbEndDate (\ s a -> s{_clbbEndDate = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). clbbUploadType :: Lens' CommentsListByBlog (Maybe Text) clbbUploadType = lens _clbbUploadType (\ s a -> s{_clbbUploadType = a}) clbbBlogId :: Lens' CommentsListByBlog Text clbbBlogId = lens _clbbBlogId (\ s a -> s{_clbbBlogId = a}) clbbStartDate :: Lens' CommentsListByBlog (Maybe Text) clbbStartDate = lens _clbbStartDate (\ s a -> s{_clbbStartDate = a}) clbbFetchBodies :: Lens' CommentsListByBlog (Maybe Bool) clbbFetchBodies = lens _clbbFetchBodies (\ s a -> s{_clbbFetchBodies = a}) clbbPageToken :: Lens' CommentsListByBlog (Maybe Text) clbbPageToken = lens _clbbPageToken (\ s a -> s{_clbbPageToken = a}) clbbMaxResults :: Lens' CommentsListByBlog (Maybe Word32) clbbMaxResults = lens _clbbMaxResults (\ s a -> s{_clbbMaxResults = a}) . mapping _Coerce -- | JSONP clbbCallback :: Lens' CommentsListByBlog (Maybe Text) clbbCallback = lens _clbbCallback (\ s a -> s{_clbbCallback = a}) instance GoogleRequest CommentsListByBlog where type Rs CommentsListByBlog = CommentList type Scopes CommentsListByBlog = '["https://www.googleapis.com/auth/blogger", "https://www.googleapis.com/auth/blogger.readonly"] requestClient CommentsListByBlog'{..} = go _clbbBlogId (_clbbStatus ^. _Default) _clbbXgafv _clbbUploadProtocol _clbbAccessToken _clbbEndDate _clbbUploadType _clbbStartDate _clbbFetchBodies _clbbPageToken _clbbMaxResults _clbbCallback (Just AltJSON) bloggerService where go = buildClient (Proxy :: Proxy CommentsListByBlogResource) mempty
brendanhay/gogol
gogol-blogger/gen/Network/Google/Resource/Blogger/Comments/ListByBlog.hs
mpl-2.0
6,778
0
23
1,745
1,212
692
520
173
1
{-# LANGUAGE CPP, OverloadedStrings #-} module DatabraryMain ( main -- * for tests , Flag (..) , flagConfig ) where import Control.Exception (evaluate) import Control.Monad (void) import Data.Either (partitionEithers) import qualified System.Console.GetOpt as Opt import System.Environment (getProgName, getArgs) import System.Exit (exitFailure) import qualified Network.Wai.Route as WaiRoute import qualified Store.Config as Conf import Service.Init (withService) import Web.Rules (generateWebFiles) import Action (actionRouteApp, WaiRouteApp(..)) import Action.Servant (servantApp) import Routes (routeMapInvertible, routeMapWai) import Warp (runWarp) data Flag = FlagConfig FilePath | FlagWeb | FlagEZID deriving (Show, Eq) opts :: [Opt.OptDescr Flag] opts = [ Opt.Option "c" ["config"] (Opt.ReqArg FlagConfig "FILE") "Path to configuration file [./databrary.conf]" , Opt.Option "w" ["webgen"] (Opt.NoArg FlagWeb) "Generate web assets only" , Opt.Option "e" ["ezid"] (Opt.NoArg FlagEZID) "Update EZID DOIs" ] flagConfig :: Flag -> Either FilePath Flag flagConfig (FlagConfig f) = Left f flagConfig f = Right f main :: IO () -- TODO: optparse main = do putStrLn "Starting Main..." prog <- getProgName args <- getArgs let (flags, args', err) = Opt.getOpt Opt.Permute opts args (configs, flags') = partitionEithers $ map flagConfig flags conf <- mconcat <$> mapM Conf.load (case configs of [] -> ["databrary.conf"] l -> l) case (flags', args', err) of ([FlagWeb], [], []) -> do putStrLn "generating files..." void generateWebFiles putStrLn "finished generating web files..." {- seems like a good idea for testing and generally factoring out monolith, add back when used ([FlagEZID], [], []) -> do putStrLn "update EZID..." r <- withService False conf $ runContextM $ withBackgroundContextM updateEZID putStrLn "update EZID finished..." if r == Just True then pure () else exitFailure -} ([], [], []) -> do putStrLn "No flags or args...." putStrLn "evaluating routemap..." routes <- evaluate routeMapInvertible putStrLn "evaluating routemap...withService..." -- Note: True = run in foreground withService True conf $ \rc -> do -- used to run migrations on startup when not in devel mode -- should check migrations2 table for last migration against last entry in schema2 dir putStrLn "running warp" runWarp conf rc (servantApp (actionRouteApp routes (WaiRouteApp (WaiRoute.route (routeMapWai rc))) rc ) ) _ -> do mapM_ putStrLn err putStrLn $ Opt.usageInfo ("Usage: " ++ prog ++ " [OPTION...]") opts exitFailure
databrary/databrary
src/DatabraryMain.hs
agpl-3.0
2,872
0
26
716
676
361
315
66
4
module Main where import Control.Monad.Error (runErrorT) import Control.Monad.Mersenne.Random (evalRandom) import Numeric.IEEE (IEEE, epsilon) import System.Random.Mersenne.Pure64 (pureMT) import qualified Data.Vector.Unboxed as V import Statistics.Test.ApproxRand import Test.HUnit (Assertion, assertBool, assertEqual) import Test.Framework import Test.Framework.Providers.HUnit tests :: Test tests = testGroup "Paired approximate randomization tests" $ concat [statTests, randomizationTests] main :: IO () main = defaultMain [ tests ] -- Statistics tests statTests :: [Test] statTests = [meanDifferenceTest] meanDifferenceTest :: Test meanDifferenceTest = testIEEEEquality "mean difference robot competition" 1.8 $ meanDifference cohenRobotsAlpha cohenRobotsBeta -- Approximate andomization tests randomizationTests :: [Test] randomizationTests = [pairApproxExactTestScores] pairApproxExactTestScores :: Test pairApproxExactTestScores = testEquality "number of extreme values robot competition" (Right 21) $ V.length `fmap` V.filter (>= 1.8) `fmap` scores where test = runErrorT $ approxRandPairStats differenceMean 1024 cohenRobotsAlpha cohenRobotsBeta scores = evalRandom test $ pureMT 42 -- Helper functions testEquality :: (Show a, Eq a) => String -> a -> a -> Test testEquality msg a b = testCase msg $ assertEqual msg a b testIEEEEquality :: IEEE a => String -> a -> a -> Test testIEEEEquality msg a b = testCase msg $ assertEqualIEEE msg a b assertEqualIEEE :: IEEE a => String -> a -> a -> Assertion assertEqualIEEE msg a b = assertBool msg $ fracEq epsilon a b -- Suggested in The Floating Point Guide: http://floating-point-gui.de/ fracEq :: (Fractional a, Ord a) => a -> a -> a -> Bool fracEq eps a b | a == b = True | a * b == 0 = diff < (eps * eps) | otherwise = diff / (abs a + abs b) < eps where diff = abs (a - b) -- Example from Cohen, 1995 cohenRobotsAlpha :: V.Vector Double cohenRobotsAlpha = V.fromList [8,3,9,6,5,8,7,8,9,9] cohenRobotsBeta :: V.Vector Double cohenRobotsBeta = V.fromList [7,0,9,4,5,9,8,3,4,5]
danieldk/approx-rand-test
tests/tests.hs
apache-2.0
2,179
0
10
435
673
370
303
46
1
module DerivingVia00001 where newtype Foo = Foo Bar deriving stock (Generic, Eq, Show) deriving anyclass (Spam) deriving (ToJSON, FromJSON) via Bar deriving via Eggs instance ToJSON Baz
carymrobbins/intellij-haskforce
tests/gold/parser/DerivingVia00001.hs
apache-2.0
194
0
6
35
65
36
29
-1
-1
module Miscellaneous.A309978Spec (main, spec) where import Test.Hspec import Miscellaneous.A309978 (a309978) main :: IO () main = hspec spec spec :: Spec spec = describe "A309978" $ it "correctly computes the first 20 elements" $ map a309978 [1..20] `shouldBe` expectedValue where expectedValue = [0,1,1,2,1,3,1,2,1,3,1,3,1,2,1,2,1,3,1,3]
peterokagey/haskellOEIS
test/Miscellaneous/A309978Spec.hs
apache-2.0
353
0
8
57
154
92
62
10
1
module Tables.A342237Spec (main, spec) where import Test.Hspec import Tables.A342237 (a342237) main :: IO () main = hspec spec spec :: Spec spec = describe "A342237" $ it "correctly computes the first 20 elements" $ take 20 (map a342237 [1..]) `shouldBe` expectedValue where expectedValue = [0,0,1,0,2,1,0,3,6,1,0,4,15,14,1,0,5,28,51,30]
peterokagey/haskellOEIS
test/Tables/A342237Spec.hs
apache-2.0
352
0
10
59
160
95
65
10
1
-------------------------------------------------------------------------------- -- Copyright © 2011 National Institute of Aerospace / Galois, Inc. -------------------------------------------------------------------------------- -- | Comparison operators. {-# LANGUAGE Safe #-} module Copilot.Language.Operators.Ord ( (<=) , (>=) , (<) , (>) ) where import Copilot.Core (Typed, typeOf) import qualified Copilot.Core as Core import Copilot.Language.Prelude import Copilot.Language.Stream import qualified Prelude as P -------------------------------------------------------------------------------- (<=) :: (P.Ord a, Typed a) => Stream a -> Stream a -> Stream Bool (Const x) <= (Const y) = Const (x P.<= y) x <= y = Op2 (Core.Le typeOf) x y (>=) :: (P.Ord a, Typed a) => Stream a -> Stream a -> Stream Bool (Const x) >= (Const y) = Const (x P.>= y) x >= y = Op2 (Core.Ge typeOf) x y (<) :: (P.Ord a, Typed a) => Stream a -> Stream a -> Stream Bool (Const x) < (Const y) = Const (x P.< y) x < y = Op2 (Core.Lt typeOf) x y (>) :: (P.Ord a, Typed a) => Stream a -> Stream a -> Stream Bool (Const x) > (Const y) = Const (x P.> y) x > y = Op2 (Core.Gt typeOf) x y --------------------------------------------------------------------------------
niswegmann/copilot-language
src/Copilot/Language/Operators/Ord.hs
bsd-3-clause
1,324
0
8
273
484
257
227
23
1
-------------------------------------------------------------------------------- -- -- Copyright (c) 2011 - 2014 Tad Doxsee -- All rights reserved. -- -- Author: Tad Doxsee -- -------------------------------------------------------------------------------- module Main where -- base import Data.Either (rights) import Data.Maybe (fromJust) import System.Environment (getArgs) import System.IO -- (openFile, IOMode, hGetContents) import System.Exit -- (ExitCode, ExitSuccess) -- filepath import System.FilePath ((</>)) -- directory import System.Directory ( doesDirectoryExist , doesFileExist , createDirectory , createDirectoryIfMissing ) -- HSH import HSH.Command (run, runIO, (-|-)) main :: IO () main = do args <- getArgs :: IO [String] let nArgs = length args okNArgs = nArgs == 4 || nArgs == 5 if not okNArgs then do putStrLn "usage: regTester testListFile program differ stdsDir [testsDir]" else do let testListFile = args !! 0 :: FilePath program = args !! 1 :: String differ = args !! 2 :: String stdsDir = args !! 3 :: FilePath testsDir = case nArgs of 4 -> Nothing 5 -> Just $ args !! 4 testListFileExists <- doesFileExist testListFile case testListFileExists of False -> do putStrLn $ "regTester: test list file " ++ testListFile ++ " does not exist" exitSuccess _ -> do h <- openFile testListFile ReadMode :: IO Handle s <- hGetContents h :: IO String let testNames = lines s :: [String] results <- runRegTests program differ stdsDir testsDir testNames let rightRslts = rights results mapM_ showResults (zip testNames results) let result = if length rightRslts > 0 && and rightRslts then "Pass" else "Failure" putStrLn result showResults :: (String, Either String Bool) -> IO () showResults (testName, result) = do putStr $ testName ++ ": " case result of Left errMsg -> putStrLn errMsg Right b -> putStrLn "Pass" type ProgramName = String runRegTests :: ProgramName -> ProgramName -> FilePath -> Maybe FilePath -> [String] -> IO [Either String Bool] runRegTests program differ stdsDirName testsDir' testNames = do let testsDir :: FilePath testsDir = case testsDir' of Nothing -> "." _ -> fromJust testsDir' stdsDirExists <- doesDirectoryExist stdsDirName case stdsDirExists of False -> return [Left $ "runRegTest: standards directory " ++ show stdsDirName ++ " does not exist."] _ -> do testsDirExists <- doesDirectoryExist testsDir case testsDirExists of False -> return [Left $ "runRegTest: tests directory " ++ show testsDir ++ " does not exist."] _ -> mapM (runRegTest program differ stdsDirName testsDir) testNames runRegTest :: ProgramName -> ProgramName -> FilePath -> FilePath -> String -> IO (Either String Bool) runRegTest program differ stdsDirName testsDir testName = do -- putStrLn $ testName let stdDir = stdsDirName </> testName stdInDir = stdDir </> "i" stdOutDir = stdDir </> "o" stdOut = stdOutDir </> testName ++ "_out.txt" inputFile = stdInDir </> testName ++ "_in.txt" input = "." </> testName ++ "_in.txt" testDir = testsDir </> testName testOutDir = testDir </> "o" output = testOutDir </> testName ++ "_out.txt" inputExists <-doesFileExist inputFile case inputExists of False -> return $ Left $ "runRegTest: input file " ++ show input ++ " does not exist." _ -> do testDirExists <- doesDirectoryExist testDir case testDirExists of True -> return $ Left $ "runRegTest: test directory " ++ show testDir ++ " already exists." _ -> do stdOutExists <- doesFileExist stdOut case stdOutExists of False -> return $ Left $ "runRegTest: standard output " ++ show stdOut ++ " does not exist." _ -> do createDirectoryIfMissing True testOutDir let cmd = "cp " ++ stdInDir ++ "/* ." runIO $ "cp " ++ stdInDir ++ "/* ." runIO $ program ++ " " ++ input ++ " " ++ output runIO $ "rm " ++ input (diffs, action) <- run $ (differ ++ " " ++ stdOut ++ " " ++ output ) :: IO (String, IO (String, ExitCode)) (_, exitCode) <- action :: IO (String, ExitCode) -- putStrLn $ show exitCode writeFile (testDir </> "diff") diffs case exitCode of ExitSuccess -> return $ Right True _ -> return $ Left "Diff failure"
tdox/regTester
src/regTester.hs
bsd-3-clause
5,507
0
28
2,128
1,248
629
619
119
5
{-# LANGUAGE FlexibleContexts #-} {-| Module : Numeric.AERN.RealArithmetic.Bench Description : benchmarking utilities Copyright : (c) Michal Konecny License : BSD3 Maintainer : mikkonecny@gmail.com Stability : experimental Portability : portable Benchmarking utilities. -} module Numeric.AERN.RealArithmetic.Bench where import Numeric.AERN.Basics.Consistency import Numeric.AERN.NumericOrder.Operators import qualified Numeric.AERN.RealArithmetic.NumericOrderRounding as ArithUpDn import Numeric.AERN.RealArithmetic.ExactOps import Numeric.AERN.RealArithmetic.Measures import Numeric.AERN.Misc.Debug {-| Approximate the imprecision of an operation by measuring the distance between its outer rounded result and inner rounded result -} mkCommentImprecision1 :: (HasDistance t, ArithUpDn.Convertible (Distance t) Double, Show (Distance t)) => (ei -> t -> t) -> (ei -> t -> t) -> ei -> t -> String mkCommentImprecision1 opOut opIn effort a = show $ imprecisionD where imprecisionD :: Double imprecisionD = case ArithUpDn.convertUpEff (ArithUpDn.convertDefaultEffort imprecision sampleD) sampleD imprecision of Just imprecisionUp -> imprecisionUp Nothing -> error $ "mkCommentImprecision: cannot convert up to a Double: " ++ show imprecision sampleD = 0 :: Double imprecision = distanceBetweenEff (distanceDefaultEffort resultOut) resultOut resultIn resultOut = opOut effort a resultIn = opIn effort a mkCommentAreaImprecision op effort a = unsafePrint ( "mkCommentImprecision: " ++ "\n a = " ++ show a ++ "\n effort = " ++ show effort ++ "\n aE = " ++ show aE ++ "\n aD = " ++ show aD ++ "\n aExp = " ++ show aExp ++ "\n resultE = " ++ show resultE ++ "\n imprecisionE = " ++ show imprecisionE ++ "\n imprecisionD = " ++ show imprecisionD ++ "\n imprecisionExp = " ++ show imprecisionExp ++ "\n resultBinaryDigits = " ++ show resultBinaryDigits ) $ signOfaE ++ "x" ++ show aExp ++ "rd" ++ show resultBinaryDigits where signOfaE = case (aE >? zero, aE <? zero) of (Just True, _) -> "+" (_, Just True) -> "-" _ -> "" aE = getThinRepresentative a Just aD = ArithUpDn.convertUpEff (ArithUpDn.convertDefaultEffort a sampleD) sampleD aE aExp = exponent aD resultE = op effort aE Just resultD = ArithUpDn.convertUpEff (ArithUpDn.convertDefaultEffort a sampleD) sampleD resultE resultExp = exponent resultD imprecisionE = imprecisionOfEff (imprecisionDefaultEffort a) resultE Just imprecisionD = ArithUpDn.convertUpEff (ArithUpDn.convertDefaultEffort imprecisionE sampleD) sampleD imprecisionE imprecisionExp = exponent imprecisionD resultBinaryDigits = resultExp - imprecisionExp imprecisionD, aD, resultD, sampleD :: Double sampleD = 0
michalkonecny/aern
aern-real/src/Numeric/AERN/RealArithmetic/Bench.hs
bsd-3-clause
3,051
0
31
782
643
336
307
63
3
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Hasmin.Types.PercentageLength -- Copyright : (c) 2017 Cristian Adrián Ontivero -- License : BSD3 -- Stability : experimental -- Portability : non-portable -- ----------------------------------------------------------------------------- module Hasmin.Types.PercentageLength ( PercentageLength , isZero , isNonZeroPercentage , minifyPL ) where import Control.Monad.Reader (Reader) import Hasmin.Class import Hasmin.Config import Hasmin.Types.Dimension import Hasmin.Types.Numeric -- | CSS <length-percentage> data type, i.e.: [length | percentage] -- Though because of the name it would be more intuitive to define: -- type LengthPercentage = Either Length Percentage, -- they are inverted here to make use of Either's Functor instance, because it -- makes no sense to minify a Percentage. type PercentageLength = Either Percentage Length minifyPL :: PercentageLength -> Reader Config PercentageLength minifyPL x@(Right _) = mapM minify x minifyPL x@(Left p) | p == 0 = pure $ Right NullLength -- minifies 0% to 0 | otherwise = pure x isNonZeroPercentage :: PercentageLength -> Bool isNonZeroPercentage (Left p) = p /= 0 isNonZeroPercentage _ = False isZero :: (Num a, Eq a) => Either a Length -> Bool isZero = either (== 0) isZeroLen
contivero/hasmin
src/Hasmin/Types/PercentageLength.hs
bsd-3-clause
1,443
0
8
242
241
137
104
22
1
module Material where import Math data Material = Lambertian Vec3D | Metal Vec3D Double | Dielectric Double deriving (Show) data Scattered = Scattered { scattered :: Ray , attenuation :: Vec3D }
bendiksolheim/roy
src/Material.hs
bsd-3-clause
291
0
8
128
56
34
22
9
0
module App ( App(..), Action(..), Flag(..), compileApp, usageApp, failWithUsage ) where import System.Console.GetOpt import System.IO import System.Exit import Control.Monad (when) import System.Environment import Data.Char (toUpper) import Text.Read (readMaybe) data Flag = Flag { verbose :: Bool, global :: Bool, version :: Bool, help :: Bool, message :: String, port :: String } deriving (Show, Eq) defaultFlag :: Flag defaultFlag = Flag { verbose = False, global = False, version = False, help = False, message = "", port = "6091" } data App = App {action :: Action, flags :: Flag, args :: [String]} deriving (Show) data Action = Empty | Start | Status | Commit | Config | Cluster | Init | Diff | History | Rollback deriving (Show, Read) usageApp :: String usageApp = usageInfo header optionsDesc -- failWithUsage :: [String] -> IO () failWithUsage err = hPutStrLn stderr (concat err ++ usageApp) >> exitFailure compileApp :: IO (App) compileApp = do args <- getArgs (flgs, arguments) <- compileOpts args let isCommand = length arguments /= 0 when (not isCommand && flgs == defaultFlag) (failWithUsage ["Command missing\n"]) act <- if isCommand then compileAction $ head arguments else return Empty return $ App act flgs arguments optionsDesc :: [OptDescr (Flag -> Flag)] optionsDesc = [ Option "V" ["version"] (NoArg (\opts -> opts {version = True})) "Display version", Option "h" ["help"] (NoArg (\opts -> opts {help = True})) "Print help", Option "g" ["global"] (NoArg (\opts -> opts {global = True})) "Global command", Option "m" ["message"] (ReqArg (\m opts -> opts {message = m}) "message") "Add a message", Option "v" ["verbose"] (NoArg (\opts -> opts {verbose = True})) "Enable verbose messages", Option "p" ["port"] (ReqArg (\m opts -> opts {port = m}) "port") "Port of the server"] compileOpts :: [String] -> IO (Flag, [String]) compileOpts argv = case getOpt Permute optionsDesc argv of (o, n, []) -> return (foldl (flip id) defaultFlag o, n) (_, _, errs) -> failWithUsage errs compileAction :: String -> IO (Action) compileAction cmd = maybe (failWithUsage ["Unknow command\n"]) (return) (readMaybe cmd' :: Maybe Action) where cmd' = ((toUpper . head) cmd) : (tail cmd) header :: String header = "Usage: det COMMAND [--version] [--help]"
lambda-zorn/det
src/App.hs
bsd-3-clause
2,599
0
12
703
888
502
386
88
2
{-# LANGUAGE TemplateHaskell #-} module Monto.ProductMessage where import Data.Aeson.TH import Data.Aeson (Value) import Data.Vector (Vector) import qualified Data.Vector as V import qualified Data.Text as T import Data.Maybe (fromMaybe) import Monto.Types import Monto.ProductDependency data ProductMessage = ProductMessage { versionId :: Int , productId :: Int , source :: Source , product :: Product , language :: Language , contents :: Value , dependencies :: Maybe (Vector ProductDependency) } deriving (Eq) $(deriveJSON (defaultOptions { fieldLabelModifier = \s -> case s of "versionId" -> "version_id" "productId" -> "product_id" label -> label }) ''ProductMessage) productDependencies :: ProductMessage -> Vector ProductDependency productDependencies = fromMaybe V.empty . dependencies instance Show ProductMessage where show (ProductMessage i j s p l _ _) = concat [ "{", show i , ",", show j , ",", T.unpack s , ",", T.unpack p , ",", T.unpack l , "}" ]
wpmp/monto-broker
src/Monto/ProductMessage.hs
bsd-3-clause
1,174
0
14
350
305
174
131
36
1
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} module Cloud.AWS.EC2.Internal ( module Cloud.AWS.Class , EC2 , initialEC2Context , runEC2 , runEC2withManager , itemConduit , itemsSet , itemsPath , resourceTagConv , productCodeConv , stateReasonConv , volumeTypeConv , groupSetConv , networkInterfaceAttachmentConv ) where import Control.Monad (join) import Control.Monad.IO.Class (MonadIO) import Control.Monad.Trans.Resource (MonadThrow, MonadBaseControl) import qualified Network.HTTP.Conduit as HTTP import Data.ByteString.Char8 () import Control.Applicative import Data.Conduit import Data.Text (Text) import Cloud.AWS.Lib.Parser.Unordered (XmlElement, (.<), convertConduit, element, elements, ElementPath, tag, (.-), elementM, end) import Cloud.AWS.Class import Cloud.AWS.EC2.Types initialEC2Context :: HTTP.Manager -> AWSContext initialEC2Context mgr = AWSContext { manager = mgr , endpoint = "ec2.amazonaws.com" , lastRequestId = Nothing } type EC2 m a = AWS AWSContext m a runEC2 :: MonadIO m => AWS AWSContext m a -> m a runEC2 = runAWS initialEC2Context runEC2withManager :: Monad m => HTTP.Manager -> AWSSettings -> AWS AWSContext m a -> m a runEC2withManager mgr = runAWSwithManager mgr initialEC2Context itemConduit :: (MonadBaseControl IO m, MonadThrow m) => (XmlElement -> m o) -> Conduit XmlElement m o itemConduit inner = convertConduit $ element "item" inner itemsSet :: MonadThrow m => Text -> (XmlElement -> m o) -> XmlElement -> m [o] itemsSet t = elements t "item" itemsPath :: Text -> ElementPath itemsPath t = tag t .- end "item" volumeType :: MonadThrow m => Text -> Maybe Int -> m VolumeType volumeType t Nothing | t == "standard" = return $ VolumeTypeStandard volumeType t (Just i) | t == "io1" = return $ VolumeTypeIO1 i volumeType t _ = monadThrow $ FromTextError t resourceTagConv :: (MonadThrow m, Applicative m) => XmlElement -> m [ResourceTag] resourceTagConv = elements "tagSet" "item" conv where conv e = ResourceTag <$> e .< "key" <*> e .< "value" productCodeConv :: (MonadThrow m, Applicative m) => XmlElement -> m [ProductCode] productCodeConv = itemsSet "productCodes" conv where conv e = ProductCode <$> e .< "productCode" <*> e .< "type" stateReasonConv :: (MonadThrow m, Applicative m) => XmlElement -> m (Maybe StateReason) stateReasonConv = elementM "stateReason" conv where conv e = StateReason <$> e .< "code" <*> e .< "message" volumeTypeConv :: (MonadThrow m, Applicative m) => XmlElement -> m VolumeType volumeTypeConv xml = join $ volumeType <$> xml .< "volumeType" <*> xml .< "iops" groupSetConv :: (MonadThrow m, Applicative m) => XmlElement -> m [Group] groupSetConv = itemsSet "groupSet" conv where conv e = Group <$> e .< "groupId" <*> e .< "groupName" networkInterfaceAttachmentConv :: (MonadThrow m, Applicative m) => XmlElement -> m (Maybe NetworkInterfaceAttachment) networkInterfaceAttachmentConv = elementM "attachment" conv where conv e = NetworkInterfaceAttachment <$> e .< "attachmentId" <*> e .< "instanceId" <*> e .< "instanceOwnerId" <*> e .< "deviceIndex" <*> e .< "status" <*> e .< "attachTime" <*> e .< "deleteOnTermination"
worksap-ate/aws-sdk
Cloud/AWS/EC2/Internal.hs
bsd-3-clause
3,460
0
20
766
1,001
537
464
97
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Mafia.Hoogle ( HooglePackagesSandbox (..) , HooglePackagesCached (..) , hoogle , joinHooglePackages ) where import Control.Monad.Trans.Bifunctor (firstT) import Control.Monad.Trans.Either (EitherT, hoistEither, runEitherT, left) import qualified Data.List as L import Data.Map (Map) import qualified Data.Map as M import qualified Data.Text as T import qualified Data.Text.IO as T import Mafia.Cabal import Mafia.Error import Mafia.Hash import Mafia.Home import Mafia.IO import Mafia.Init import Mafia.Package import Mafia.Path import Mafia.Process import Mafia.P import System.IO (IO, stderr) newtype HooglePackagesSandbox = HooglePackagesSandbox [PackageId] newtype HooglePackagesCached = HooglePackagesCached [PackageId] data Hoogle = Hoogle { hooglePath :: File , _hoogleVersion :: HoogleVersion } data HoogleVersion = Hoogle4x | Hoogle5x hoogle :: Text -> [Argument] -> EitherT MafiaError IO () hoogle hackageRoot args = do hp <- hooglePackages hackageRoot hpc <- hooglePackagesCached hoogleIndex args $ joinHooglePackages hpc hp -- | Download all packages installed in the local sandbox into a global location hooglePackages :: Text -> EitherT MafiaError IO HooglePackagesSandbox hooglePackages hackageRoot = do firstT MafiaInitError $ initialize LatestSources Nothing Nothing db <- hoogleCacheDir hoogleExe <- findHoogle Out pkgStr <- liftCabal $ cabal "exec" ["--", "ghc-pkg", "list", "--simple-output"] let pkgs = T.splitOn " " . T.strip $ pkgStr fmap (HooglePackagesSandbox . catMaybes) . for pkgs $ \pkg -> do pkgId <- hoistEither . maybeToRight (MafiaParseError $ mconcat ["Invalid package: ", pkg]) . parsePackageId $ pkg let name = unPackageName . pkgName $ pkgId let txt = db </> pkg <> ".txt" let hoo = hoogleDbFile' hoogleExe db pkgId let skip = db </> pkg <> ".skip" ifM (doesFileExist skip) (pure Nothing) $ ifM (doesFileExist hoo) (pure $ Just pkgId) $ do liftIO . T.hPutStrLn stderr $ "Downloading: " <> pkg r <- runEitherT $ call MafiaProcessError "curl" ["-f", "-s", hackageRoot </> pkg </> "docs" </> name <> ".txt", "-o", txt] case r of Left _ -> do liftIO . T.hPutStrLn stderr $ "Missing: " <> pkg -- Technically we can "convert" a broken txt file and no one is the wiser, but we're not going to do that liftIO $ T.writeFile (T.unpack skip) "" pure Nothing Right Hush -> do case hoogleExe of Hoogle hoogleExe' Hoogle4x -> call_ MafiaProcessError hoogleExe' ["convert", txt] Hoogle _ Hoogle5x -> -- There isn't an associated hoogle 5.x command for this pure () pure $ Just pkgId hoogleIndex :: [Argument] -> [PackageId] -> EitherT MafiaError IO () hoogleIndex args pkgs = do -- By default hoogle will expect a 'default.hoo' file to exist in the database directory -- If we want the search to just be for _this_ sandbox, we have two options -- 1. Create a unique directory based on all the current packages and ensure the default.hoo -- 2. Specify/append all the packages from the global database by using "+$name-$version" -- Unfortunately hoogle doesn't like the "-$version" part :( let hash = renderHash . hashText . mconcat . fmap renderPackageId $ pkgs db <- hoogleCacheDir hoogleExe <- findHoogle db' <- (\d -> d </> "hoogle" </> hash) <$> liftCabal initSandbox case hoogleExe of Hoogle hoogleExe' Hoogle4x -> do unlessM (doesFileExist $ db' </> "default.hoo") $ do createDirectoryIfMissing True db' -- We may also want to copy/symlink all the hoo files here to allow for partial module searching call_ MafiaProcessError hoogleExe' $ ["combine", "--outfile", db' </> "default.hoo"] <> fmap (hoogleDbFile db) pkgs call_ MafiaProcessError (hooglePath hoogleExe) $ ["-d", db'] <> args Hoogle hoogleExe' Hoogle5x -> do unlessM (doesFileExist $ db' </> "default.hoo") $ do createDirectoryIfMissing True db' -- Link each hoogle file into `db'` directory forM_ pkgs $ \pkg -> do let src = db </> renderPackageId pkg <> ".txt" let dst = db' </> takeFileName src createSymbolicLink src dst let a = mconcat $ [ ["generate", "--database", db' </> "default.hoo" , "--local=" <> db'] ] call_ MafiaProcessError hoogleExe' a call_ MafiaProcessError (hooglePath hoogleExe) $ ["-d", db' </> "default.hoo"] <> args hooglePackagesCached :: (Functor m, MonadIO m) => m HooglePackagesCached hooglePackagesCached = do db <- hoogleCacheDir HooglePackagesCached . catMaybes . fmap ((=<<) parsePackageId . T.stripSuffix ".hoo" . takeFileName) <$> getDirectoryListing (RecursiveDepth 1) db -- | Keep everything from the current sandbox and append the latest of any remaining packages joinHooglePackages :: HooglePackagesCached -> HooglePackagesSandbox -> [PackageId] joinHooglePackages (HooglePackagesCached cached) (HooglePackagesSandbox current) = let index = mapFromListGrouped . fmap packageIdTuple extra = fmap (uncurry PackageId) . M.toList . M.mapMaybe (head . reverse . L.sort) $ M.difference (index cached) (index current) in current <> extra hoogleCacheDir :: MonadIO m => m Directory hoogleCacheDir = ensureMafiaDir "hoogle" -- | Find the 'hoogle' executable on $PATH and it if isn't there, install it. findHoogle :: EitherT MafiaError IO Hoogle findHoogle = do h <- findHoogleExe v <- detectHoogleVersion h pure $ Hoogle h v findHoogleExe :: EitherT MafiaError IO File findHoogleExe = do res <- runEitherT $ T.init . unOut <$> call MafiaProcessError "which" ["hoogle"] case res of Right path -> pure path Left x -> -- TODO More friendly error messages about expecting to find `hoogle` on $PATH left . MafiaParseError $ ("Invalid hoogle version: " <> renderMafiaError x) detectHoogleVersion :: File -> EitherT MafiaError IO HoogleVersion detectHoogleVersion hf = do res <- T.init . unOut <$> call MafiaProcessError hf ["--version"] if T.isPrefixOf "Hoogle v4." res then pure Hoogle4x else if T.isPrefixOf "Hoogle 5." res then pure Hoogle5x else left . MafiaParseError $ "Invalid hoogle version: " <> res hoogleDbFile :: Directory -> PackageId -> File hoogleDbFile db pkg = db </> renderPackageId pkg <> ".hoo" hoogleDbFile' :: Hoogle -> Directory -> PackageId -> File hoogleDbFile' v db pkg = case v of Hoogle _ Hoogle4x -> db </> renderPackageId pkg <> ".hoo" Hoogle _ Hoogle5x -> db </> renderPackageId pkg <> ".txt" mapFromListGrouped :: Ord a => [(a, b)] -> Map a [b] mapFromListGrouped = foldr (\(k, v) -> M.insertWith (<>) k [v]) M.empty
ambiata/mafia
src/Mafia/Hoogle.hs
bsd-3-clause
7,097
0
24
1,683
1,856
941
915
139
3
{-# LANGUAGE CPP #-} -- | Paths, host bitness and other environmental information about Haste. module Haste.Environment ( hasteSysDir, jsmodSysDir, pkgSysDir, pkgSysLibDir, jsDir, hasteUserDir, jsmodUserDir, pkgUserDir, pkgUserLibDir, hasteGhcLibDir, hostWordSize, ghcPkgBinary, ghcBinary, hasteBinDir, hasteBinary, hastePkgBinary, hasteInstHisBinary, hasteCabalBinary, hasteCopyPkgBinary, closureCompiler, bootFile, portableHaste, hasteNeedsReboot ) where import System.IO.Unsafe import Data.Bits import Foreign.C.Types (CIntPtr) import Control.Shell hiding (hClose) import Paths_haste_compiler import System.IO import System.Info import Haste.GHCPaths (ghcPkgBinary, ghcBinary) import Haste.Version #if defined(PORTABLE) import System.Environment (getExecutablePath) #endif -- | Subdirectory under Haste's root directory where all the stuff for this -- version lives. Use "windows" instead of "mingw32", since this is what -- cabal prefers. hasteVersionSubDir :: FilePath hasteVersionSubDir = arch ++ "-" ++ myos ++ "-" ++ myver where myos | os == "mingw32" = "windows" | otherwise = os myver = showBootVersion bootVersion -- | Directory to search for GHC settings. Always equal to 'hasteSysDir'. hasteGhcLibDir :: FilePath hasteGhcLibDir = hasteSysDir #if defined(PORTABLE) -- | Was Haste built in portable mode or not? portableHaste :: Bool portableHaste = True -- | Haste system directory. Identical to @hasteUserDir@ unless built with -- -f portable. hasteSysDir :: FilePath hasteSysDir = dir </> hasteVersionSubDir where dir = joinPath . init . init . splitPath $ unsafePerformIO getExecutablePath -- | Haste @bin@ directory. hasteBinDir :: FilePath hasteBinDir = takeDirectory $ unsafePerformIO getExecutablePath -- | Haste JS file directory. jsDir :: FilePath jsDir = hasteSysDir </> "js" #else -- | Was Haste built in portable mode or not? portableHaste :: Bool portableHaste = False -- | Haste system directory. Identical to 'hasteUserDir' unless built with -- -f portable. hasteSysDir :: FilePath hasteSysDir = hasteUserDir -- | Haste @bin@ directory. hasteBinDir :: FilePath hasteBinDir = unsafePerformIO $ getBinDir -- | Haste JS file directory. jsDir :: FilePath jsDir = unsafePerformIO $ getDataDir #endif -- | Haste user directory. Usually ~/.haste. hasteUserDir :: FilePath Right hasteUserDir = unsafePerformIO . shell . withAppDirectory "haste" $ \d -> do return $ d </> hasteVersionSubDir -- | Directory where user .jsmod files are stored. jsmodSysDir :: FilePath jsmodSysDir = hasteSysDir -- | Base directory for Haste's system libraries. pkgSysLibDir :: FilePath pkgSysLibDir = hasteSysDir -- | Directory housing package information. pkgSysDir :: FilePath pkgSysDir = hasteSysDir </> "package.conf.d" -- | Directory where user .jsmod files are stored. jsmodUserDir :: FilePath jsmodUserDir = hasteUserDir -- | Directory containing library information. pkgUserLibDir :: FilePath pkgUserLibDir = hasteUserDir -- | Directory housing package information. pkgUserDir :: FilePath pkgUserDir = hasteUserDir </> "package.conf.d" -- | Host word size in bits. hostWordSize :: Int #if __GLASGOW_HASKELL__ >= 708 hostWordSize = finiteBitSize (undefined :: CIntPtr) #else hostWordSize = bitSize (undefined :: CIntPtr) #endif -- | File extension of binaries on this system. binaryExt :: String binaryExt | os == "mingw32" = ".exe" | otherwise = "" -- | The main Haste compiler binary. hasteBinary :: FilePath hasteBinary = hasteBinDir </> "hastec" ++ binaryExt -- | Binary for haste-pkg. hastePkgBinary :: FilePath hastePkgBinary = hasteBinDir </> "haste-pkg" ++ binaryExt -- | Binary for haste-copy-pkg. hasteCopyPkgBinary :: FilePath hasteCopyPkgBinary = hasteBinDir </> "haste-copy-pkg" ++ binaryExt -- | Binary for haste-pkg. hasteCabalBinary :: FilePath hasteCabalBinary = hasteBinDir </> "haste-cabal" ++ binaryExt -- | Binary for haste-install-his. hasteInstHisBinary :: FilePath hasteInstHisBinary = hasteBinDir </> "haste-install-his" ++ binaryExt -- | JAR for Closure compiler. closureCompiler :: FilePath closureCompiler = hasteSysDir </> "compiler.jar" -- | File indicating whether Haste is booted or not, and for which Haste+GHC -- version combo. bootFile :: FilePath bootFile = hasteUserDir </> "booted" -- | Returns which parts of Haste need rebooting. A change in the boot file -- format triggers a full reboot. hasteNeedsReboot :: Bool #ifdef PORTABLE hasteNeedsReboot = False #else hasteNeedsReboot = unsafePerformIO $ do exists <- shell $ isFile bootFile case exists of Right True -> do fh <- openFile bootFile ReadMode bootedVerString <- hGetLine fh hClose fh case parseBootVersion bootedVerString of Just (BootVer hasteVer ghcVer) -> return $ hasteVer /= hasteVersion || ghcVer /= ghcVersion _ -> return True _ -> do return True #endif
santolucito/haste-compiler
src/Haste/Environment.hs
bsd-3-clause
4,985
0
10
880
632
377
255
87
3
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- | The STG language syntax tree, modeled after the description in the -- 1992 paper -- <http://research.microsoft.com/apps/pubs/default.aspx?id=67083 (link)>. -- -- A 'Program' is typically created using functionality provided by the -- "Stg.Parser" module, as opposed to manually combining the data types given -- in this module. -- -- For plenty of comparisons of STG language source and generated parse trees, -- have a look at the "Stg.Parser.QuasiQuoter" module. module Language.MiniStg ( Program (..), Binds (..), LambdaForm (..), prettyLambda, UpdateFlag (..), Rec (..), Expr (..), Alts (..), NonDefaultAlts (..), AlgebraicAlt (..), PrimitiveAlt (..), DefaultAlt (..), Literal (..), PrimOp (..), Var (..), Atom (..), Constr (..), Pretty (..), -- * Meta information classify, LambdaType(..), ) where import Control.DeepSeq import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as NonEmpty import Data.Map (Map) import qualified Data.Map as M import Data.Monoid hiding (Alt) import qualified Data.Semigroup as Semigroup import Data.Text (Text) import qualified Data.Text as T import GHC.Exts import GHC.Generics import Language.Haskell.TH.Lift import Text.PrettyPrint.ANSI.Leijen hiding ((<>)) import Language.MiniStg.Util -- $setup -- >>> :set -XQuasiQuotes -- >>> import Stg.Parser.QuasiQuoter -- | Package of style definitions used for prettyprinting the STG AST. data StgAstStyle = StgAstStyle { keyword :: Doc -> Doc -- ^ Keyword style , prim :: Doc -> Doc -- ^ Primitive style, for literals and functions , variable :: Doc -> Doc -- ^ Variable style , constructor :: Doc -> Doc -- ^ Constructor style , semicolon :: Doc -> Doc -- ^ Semicolons separating lists of bindings and alternatives } -- | Colour definitions used by the STG AST. style :: StgAstStyle style = StgAstStyle { keyword = id , prim = dullgreen , variable = dullyellow , constructor = dullmagenta , semicolon = dullwhite } -- | An STG 'Program' is the unit that can be loaded by the STG machine. It -- consists of a set of bindings. newtype Program = Program Binds deriving (Eq, Ord, Show, Generic) -- | __Right-biased union__ of the contained bindings. This makes for a poor man's -- module system by appending multiple, potentially partially incomplete, -- 'Programs' to each other. -- -- @ -- 'Stg.Prelude.map' <> 'Stg.Prelude.filter' <> ['Stg.Parser.QuasiQuoter.stg'| … actual source … |] -- @ instance Monoid Program where mempty = Program mempty mappend = (Semigroup.<>) instance Semigroup.Semigroup Program where Program x <> Program y = Program (x <> y) -- | Bindings are collections of lambda forms, indexed over variables. -- -- They exist at the top level, or as part of a let(rec) binding. newtype Binds = Binds (Map Var LambdaForm) deriving (Eq, Ord, Generic) -- | __Right-biased__ union. See 'Monoid' 'Program' for further information. instance Monoid Binds where mempty = Binds mempty mappend = (Semigroup.<>) instance Semigroup.Semigroup Binds where Binds x <> Binds y = Binds (x <> y) instance Show Binds where show (Binds binds) = "(Binds " <> show (M.assocs binds) <> ")" -- | A lambda form unifies free and bound variables associated with a function -- body. The lambda body must not be of primitive type, as this would imply -- the value is both boxed and unboxed. -- -- >>> [stg| \(x) y z -> expr x z |] -- LambdaForm [Var "x"] NoUpdate [Var "y",Var "z"] (AppF (Var "expr") [AtomVar (Var "x"),AtomVar (Var "z")]) data LambdaForm = LambdaForm ![Var] !UpdateFlag ![Var] !Expr -- ^ * Free variables (excluding globals) -- * Update flag -- * Bound variables -- * Body deriving (Eq, Ord, Show, Generic) -- | Possible classification of lambda forms. data LambdaType = LambdaCon -- ^ Data constructor ('AppC' as body) | LambdaFun -- ^ Function (lambda with non-empty argument list) | LambdaThunk -- ^ Thunk (everything else) deriving (Eq, Ord, Show) instance Pretty LambdaType where pretty = \case LambdaCon -> "Con" LambdaFun -> "Fun" LambdaThunk -> "Thunk" -- | Classify the type of a lambda form based on its shape. classify :: LambdaForm -> LambdaType classify = \case LambdaForm _ _ [] AppC{} -> LambdaCon LambdaForm _ _ (_:_) _ -> LambdaFun LambdaForm _ _ [] _ -> LambdaThunk -- | The update flag distinguishes updatable from non-updatable lambda forms. data UpdateFlag = Update -- ^ Overwrite the heap object in-place with its reduced value -- once available, making recurring access cheap | NoUpdate -- ^ Don't touch the heap object after evaluation deriving (Eq, Ord, Show, Generic, Enum, Bounded) -- | Distinguishes @let@ from @letrec@. data Rec = NonRecursive -- ^ Binings have no access to each other | Recursive -- ^ Bindings can be given to each other as free variables deriving (Eq, Ord, Show, Generic, Enum, Bounded) -- | An expression in the STG language. data Expr = Let !Rec !Binds !Expr -- ^ Let expression @let(rec) ... in ...@ | Case !Expr !Alts -- ^ Case expression @case ... of ... x -> y@ | AppF !Var ![Atom] -- ^ Function application @f x y z@ | AppC !Constr ![Atom] -- ^ Saturated constructor application @Just a@ | AppP !PrimOp !Atom !Atom -- ^ Primitive function application @+# 1# 2#@ | LitE !Literal -- ^ Literal expression @1#@ deriving (Eq, Ord, Show, Generic) -- | List of possible alternatives in a 'Case' expression. -- -- The list of alts has to be homogeneous. This is not ensured by the type -- system, and should be handled by the parser instead. data Alts = Alts !NonDefaultAlts !DefaultAlt deriving (Eq, Ord, Show, Generic) -- | The part of a 'Case' alternative that's not the default. data NonDefaultAlts = NoNonDefaultAlts -- ^ Used in 'case' statements that consist only of a default -- alternative. These can be useful to force or unpack values. | AlgebraicAlts !(NonEmpty AlgebraicAlt) -- ^ Algebraic alternative, like @Cons x xs@. | PrimitiveAlts !(NonEmpty PrimitiveAlt) -- ^ Primitive alternative, like @1#@. deriving (Eq, Ord, Show, Generic) -- | As in @True | False@ data AlgebraicAlt = AlgebraicAlt !Constr ![Var] !Expr deriving (Eq, Ord, Show, Generic) -- | As in @1#@, @2#@, @3#@ data PrimitiveAlt = PrimitiveAlt !Literal !Expr deriving (Eq, Ord, Show, Generic) -- | If no viable alternative is found in a pattern match, use a 'DefaultAlt' -- as fallback. data DefaultAlt = DefaultNotBound !Expr | DefaultBound !Var !Expr deriving (Eq, Ord, Show, Generic) -- | Literals are the basis of primitive operations. newtype Literal = Literal Integer deriving (Eq, Ord, Show, Generic) -- | Primitive operations. data PrimOp = Add -- ^ @+@ | Sub -- ^ @-@ | Mul -- ^ @*@ | Div -- ^ @/@ | Mod -- ^ @%@ | Eq -- ^ @==@ | Lt -- ^ @<@ | Leq -- ^ @<=@ | Gt -- ^ @>@ | Geq -- ^ @>=@ | Neq -- ^ @/=@ deriving (Eq, Ord, Show, Generic, Bounded, Enum) -- | Variable. newtype Var = Var Text deriving (Eq, Ord, Show, Generic) instance IsString Var where fromString = coerce . T.pack -- | Smallest unit of data. Atoms unify variables and literals, and are what -- functions take as arguments. data Atom = AtomVar !Var | AtomLit !Literal deriving (Eq, Ord, Show, Generic) -- | Constructors of algebraic data types. newtype Constr = Constr Text deriving (Eq, Ord, Show, Generic) instance IsString Constr where fromString = coerce . T.pack -------------------------------------------------------------------------------- -- Lift instances deriveLiftMany [ ''Program, ''Literal, ''LambdaForm, ''UpdateFlag, ''Rec , ''Expr, ''Alts, ''AlgebraicAlt, ''PrimitiveAlt, ''DefaultAlt , ''PrimOp, ''Atom ] instance Lift NonDefaultAlts where lift NoNonDefaultAlts = [| NoNonDefaultAlts |] lift (AlgebraicAlts alts) = [| AlgebraicAlts (NonEmpty.fromList $(lift (toList alts))) |] lift (PrimitiveAlts alts) = [| PrimitiveAlts (NonEmpty.fromList $(lift (toList alts))) |] instance Lift Binds where lift (Binds binds) = [| Binds (M.fromList $(lift (M.assocs binds))) |] instance Lift Constr where lift (Constr con) = [| Constr (T.pack $(lift (T.unpack con))) |] instance Lift Var where lift (Var var) = [| Var (T.pack $(lift (T.unpack var))) |] -------------------------------------------------------------------------------- -- Pretty instances semicolonTerminated :: [Doc] -> Doc semicolonTerminated = align . vsep . punctuate (semicolon style ";") instance Pretty Program where pretty (Program binds) = pretty binds instance Pretty Binds where pretty (Binds bs) = (semicolonTerminated . map prettyBinding . M.assocs) bs where prettyBinding (var, lambda) = pretty var <+> "=" <+> pretty lambda -- | Prettyprint a 'LambdaForm', given prettyprinters for the free variable -- list. -- -- Introduced so 'Stg.Machine.Types.Closure' can hijack it to display -- the free value list differently. prettyLambda :: ([Var] -> Doc) -- ^ Free variable list printer -> LambdaForm -> Doc prettyLambda pprFree (LambdaForm free upd bound expr) = (prettyExp . prettyUpd . prettyBound . prettyFree) "\\" where prettyFree | null free = id | otherwise = (<> lparen <> pprFree free <> rparen) prettyUpd = (<+> case upd of Update -> "=>" NoUpdate -> "->" ) prettyBound | null bound = id | null free = (<> prettyList bound) | otherwise = (<+> prettyList bound) prettyExp = (<+> pretty expr) instance Pretty LambdaForm where pretty = prettyLambda prettyList instance Pretty Rec where pretty = \case NonRecursive -> "" Recursive -> "rec" instance Pretty Expr where pretty = \case Let rec binds expr -> let inBlock = indent 4 (keyword style "in" <+> pretty expr) bindingBlock = line <> indent 4 ( keyword style ("let" <> pretty rec) <+> pretty binds ) in vsep [bindingBlock, inBlock] Case expr alts -> vsep [ hsep [ keyword style "case" , pretty expr , keyword style "of" ] , indent 4 (align (pretty alts)) ] AppF var [] -> pretty var AppF var args -> pretty var <+> prettyList args AppC con [] -> pretty con AppC con args -> pretty con <+> prettyList args AppP op arg1 arg2 -> pretty op <+> pretty arg1 <+> pretty arg2 LitE lit -> pretty lit instance Pretty Alts where pretty (Alts NoNonDefaultAlts def) = pretty def pretty (Alts (AlgebraicAlts alts) def) = semicolonTerminated (map pretty (toList alts) <> [pretty def]) pretty (Alts (PrimitiveAlts alts) def) = semicolonTerminated (map pretty (toList alts) <> [pretty def]) instance Pretty AlgebraicAlt where pretty (AlgebraicAlt con [] expr) = pretty con <+> "->" <+> pretty expr pretty (AlgebraicAlt con args expr) = pretty con <+> prettyList args <+> "->" <+> pretty expr instance Pretty PrimitiveAlt where pretty (PrimitiveAlt lit expr) = pretty lit <+> "->" <+> pretty expr instance Pretty DefaultAlt where pretty = \case DefaultNotBound expr -> "default" <+> "->" <+> pretty expr DefaultBound var expr -> pretty var <+> "->" <+> pretty expr instance Pretty Literal where pretty (Literal i) = prim style (integer i <> "#") instance Pretty PrimOp where pretty op = prim style (case op of Add -> "+#" Sub -> "-#" Mul -> "*#" Div -> "/#" Mod -> "%#" Eq -> "==#" Lt -> "<#" Leq -> "<=#" Gt -> ">#" Geq -> ">=#" Neq -> "/=#" ) instance Pretty Var where pretty (Var name) = variable style (string (T.unpack name)) prettyList = spaceSep instance Pretty Atom where pretty = \case AtomVar var -> pretty var AtomLit lit -> pretty lit prettyList = spaceSep instance Pretty Constr where pretty (Constr name) = constructor style (string (T.unpack name)) instance NFData Program instance NFData Binds instance NFData LambdaForm instance NFData UpdateFlag instance NFData Rec instance NFData Expr instance NFData Alts instance NFData NonDefaultAlts instance NFData AlgebraicAlt instance NFData PrimitiveAlt instance NFData DefaultAlt instance NFData Literal instance NFData PrimOp instance NFData Var instance NFData Atom instance NFData Constr
Neuromancer42/ministgwasm
src/Language/MiniStg.hs
bsd-3-clause
13,443
0
20
3,612
2,964
1,606
1,358
323
3
-- | Representation of a directed graph. In Hakyll, this is used for dependency -- tracking. -- module Hakyll.Core.DirectedGraph ( DirectedGraph , fromList , toList , member , nodes , neighbours , reverse , reachableNodes ) where import Prelude hiding (reverse) import Control.Arrow (second) import Data.Monoid (mconcat) import Data.Set (Set) import Data.Maybe (fromMaybe) import qualified Data.Map as M import qualified Data.Set as S import Hakyll.Core.DirectedGraph.Internal -- | Construction of directed graphs -- fromList :: Ord a => [(a, Set a)] -- ^ List of (node, reachable neighbours) -> DirectedGraph a -- ^ Resulting directed graph fromList = DirectedGraph . M.fromList . map (\(t, d) -> (t, Node t d)) -- | Deconstruction of directed graphs -- toList :: DirectedGraph a -> [(a, Set a)] toList = map (second nodeNeighbours) . M.toList . unDirectedGraph -- | Check if a node lies in the given graph -- member :: Ord a => a -- ^ Node to check for -> DirectedGraph a -- ^ Directed graph to check in -> Bool -- ^ If the node lies in the graph member n = M.member n . unDirectedGraph -- | Get all nodes in the graph -- nodes :: Ord a => DirectedGraph a -- ^ Graph to get the nodes from -> Set a -- ^ All nodes in the graph nodes = M.keysSet . unDirectedGraph -- | Get a set of reachable neighbours from a directed graph -- neighbours :: Ord a => a -- ^ Node to get the neighbours of -> DirectedGraph a -- ^ Graph to search in -> Set a -- ^ Set containing the neighbours neighbours x = fromMaybe S.empty . fmap nodeNeighbours . M.lookup x . unDirectedGraph -- | Reverse a directed graph (i.e. flip all edges) -- reverse :: Ord a => DirectedGraph a -> DirectedGraph a reverse = mconcat . map reverse' . M.toList . unDirectedGraph where reverse' (id', Node _ neighbours') = fromList $ zip (S.toList neighbours') $ repeat $ S.singleton id' -- | Find all reachable nodes from a given set of nodes in the directed graph -- reachableNodes :: Ord a => Set a -> DirectedGraph a -> Set a reachableNodes set graph = reachable (setNeighbours set) set where reachable next visited | S.null next = visited | otherwise = reachable (sanitize neighbours') (next `S.union` visited) where sanitize = S.filter (`S.notMember` visited) neighbours' = setNeighbours (sanitize next) setNeighbours = S.unions . map (`neighbours` graph) . S.toList
sol/hakyll
src/Hakyll/Core/DirectedGraph.hs
bsd-3-clause
2,626
0
13
706
643
351
292
53
1
module Handler.SharedSpec (spec) where import TestImport spec :: Spec spec = withApp $ do describe "getSharedR" $ do error "Spec not implemented: getSharedR"
sulami/hGM
test/Handler/SharedSpec.hs
bsd-3-clause
184
0
11
49
44
23
21
6
1
{-# LANGUAGE DeriveDataTypeable #-} -- The Timber compiler <timber-lang.org> -- -- Copyright 2008-2009 Johan Nordlander <nordland@csee.ltu.se> -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. Neither the names of the copyright holder and any identified -- contributors, nor the names of their affiliations, may be used to -- endorse or promote products derived from this software without -- specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS -- OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR -- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. module Reduce where import PP import Common import Core import Env import Kind import Depend import Termred import Data.Typeable import qualified Control.Exception as Exception type TSubst = Map TVar Type type TEqs = [(Type,Type)] data ClosePredException = CircularSubPred [Scheme] | AmbigSubPred Scheme Scheme deriving (Typeable) instance Show ClosePredException where show (CircularSubPred ps) = "Circular subtype predicates: " ++ render (hpr ',' ps) show (AmbigSubPred p1 p2) = "Ambiguous subtype predicates: " ++ render (hpr ',' [p1,p2]) instance Exception.Exception ClosePredException noreduce env eqs pe = do s0 <- unify env eqs return (s0, pe, id) fullreduce :: Env -> TEqs -> PEnv -> M s (TSubst, PEnv, Exp->Exp) fullreduce env eqs pe = do -- tr ("FULLREDUCE\n" ++ render (vpr pe)) (s1,pe1,f1) <- normalize env eqs pe -- tr ("Subst: " ++ show s1) let env1 = subst s1 env (s2,pe2,f2) <- resolve env1 pe1 -- tr ("END FULLREDUCE " ++ show pe2) return (s2@@s1, pe2, f2 . f1) topresolve env eqs pe bs = do -- if not (null pe) then tr ("TOPRESOLVE\n" ++ render (nest 4 (vpr pe))) else return () (s,qe,f) <- fullreduce env eqs pe -- if not (null qe) then tr ("TOPRESOLVE OUT:\n" ++ render (nest 4 (vpr qe))) else return () let Binds r te es = collect (f (ELit (lInt 0))) `catBinds` bs te' = subst s te mono = [ (x,t) | (x,t) <- te', not (null (tvars t)) ] -- if not (null mono) then tr ("AFTER TOPRESOLVE\n" ++ render (nest 4 (vpr te'))) else return () assert1 (null mono) "Illegal polymorphism in top-level type" mono return (Binds r (qe++te') es) where collect (ELet bs e) = bs `catBinds` collect e collect e = nullBinds normalize env eqs pe = do -- tr ("NORMALIZE: " ++ render (vpr pe)) s0 <- unify env eqs -- tr ("NORMALZE B: " ++ show s0) let env0 = subst s0 env (s1,pe1,f1) <- norm env0 (subst s0 pe) -- tr ("END NORMALZE ") return (s1@@s0, pe1, f1) norm env [] = return ([], [], id) norm env pe = do -- tr ("NORM A\n" ++ render (nest 8 (vpr pe))) (s1, pe1, f1) <- reduce env pe -- tr ("NORM B\n" ++ render (nest 8 (vpr pe1))) (s2, pe2, f2) <- simplify (subst s1 env) pe1 -- tr ("NORM C\n" ++ render (nest 8 (vpr pe2))) return (s2@@s1, pe2, f2 . f1) -- Auxiliary function for type error messages ------------------------------------------------- {- Type error messages are still a hack. The problem is to find reasonable error messages when the constraint-solver has failed after having backtracked and tried several alternatives. he present approach works reasonably well when failing in search for a witness of a typeclass, but gives a confusing message (only the last alternative tried) in other cases. Also, coding of various types of failure in the first character of the error message is not very elegant... -} data ErrType = Solve | Unify | Other typeError e env msg = char e : "Type error " ++ (show (errPos env)) ++ "\n" ++ msg where char Solve = '+' char Unify = '-' char Other = ' ' -- Conservative reduction ---------------------------------------------------------------------- reduce env pe = do -- tr ("###reduce\n" ++ render (nest 8 (vpr pe)) ) -- ++ "\n\n" ++ show (tvars (typeEnv env))) (s,q,[],es) <- red [] (map mkGoal pe) -- tr ("###result\n" ++ render (nest 8 (vpr q))) -- tr (" " ++ show s) return (s, q, eLet pe (dom pe `zip` es)) where mkGoal (v,p) = (tick env{errPos = posInfo v} (isCoercion v || isDummy v), p) -- Simplification ------------------------------------------------------------------------------ simplify env pe = do cs <- newNames skolemSym (length tvs) -- tr ("****SIMPLIFY\n" ++ render (nest 8 (vpr (subst (tvs`zip`map TId cs) pe)))) r <- expose (closePreds env [] (subst (tvs`zip`map TId cs) pe) (cs`zip`ks)) case r of Right (env',qe,eq) -> return (nullSubst, pe', eLet' (subst s bss)) where (pe',bss) = preferLocals env' pe qe eq s = cs `zip` map TVar tvs Left s -> case decodeError s of Nothing -> fail (typeError Other env s) Just (m,ids) | m == circularSubMsg -> do (t:ts) <- mapM sat tvs' -- tr ("Circular: " ++ showids ids) s <- unify env (repeat t `zip` ts) -- tr ("New: " ++ render (nest 8 (vpr (subst s pe)))) (s',pe',f) <- norm (subst s env) (subst s pe) return (s'@@s, pe', f) where tvs' = [ tv | (tv,c) <- tvs `zip` cs, c `elem` ids ] sat tv = do ts <- mapM newTVar (kArgs (tvKind tv)) return (tAp (TVar tv) ts) Just (m,ids) | m `elem` [ambigSubMsg, ambigInstMsg] -> do -- tr ("Ambiguous: " ++ showids ids) -- tr (render (nest 8 (vpr (t:ts)))) s <- unifyS env (repeat t `zip` ts) -- tr ("New:\n" ++ render (nest 8 (vpr (subst s pe)))) (s',pe',f) <- norm (subst s env) (subst s pe) return (s'@@s, pe', f) where (t:ts) = map (lookup' (pe ++ predEnv env ++ predEnv0 env)) ids where tvs = tvars pe ks = map tvKind tvs {- B x < C Int \\ x A x < B x \\ x, A x < C x \\ x A x < B x \\ x, A x < C x \\ x B x < C Int \\ x Show [a] \\ a Show [Char] \\ E a \\ a E a \\ a, F a b x < c Int \\ x, a x < b x \\ x, a x < c x \\ x a x < b x \\ x, a x < c x \\ x, b x < c Int \\ x -} -- Forced reduction ------------------------------------------------------------------------ resolve env pe = do -- tr ("############### Before resolve:\n" ++ render (nest 8 (vpr pe))) -- tr ("tevars: " ++ show env_tvs ++ ", reachable: " ++ show reachable_tvs) (s1,q1,[],es) <- red [] (map mkGoal pe) -- tr ("############### After resolve:\n" ++ render (nest 8 (vpr q1))) let f1 = eLet pe (dom pe `zip` es) badq = filter badDummy q1 -- assert1 (null badq) "Cannot resolve predicates" badq -- tr "DONE RESOLVING" (s2,q2,f2) <- simplify (subst s1 env) q1 return (s2@@s1, q2, f2 . f1) where env_tvs = tevars env reachable_tvs = vclose (map tvars pe) (ps ++ ns ++ env_tvs) where (ps,ns) = pols env mkGoal (v,p) = (force env' (coercion || ambig), p) where tvs = tvars p coercion = isCoercion v ambig = null (tvs `intersect` reachable_tvs) env' = tick env coercion badDummy (v,p) = isDummy v && null (tvars p `intersect` env_tvs) {- C1 x < C x C2 x < C Y C3 x < C y \\ x < y |- m aa < C b |- Int < Int (All a . Exists b . m a < C b) ------------------------------ (All a . m a < C b) |- C b -> Int < m aa -> Int --------------------------------------- (All a . (All b . m a < C b) => |- (All b . C b -> Int) < m aa -> Int ---------------------------------------------- |- All a . (All b . C b -> Int) < m a -> Int |- C1 aa < C aa |- Int < Int C1 / m, aa / b -------------------------------- |- C aa -> Int < C1 aa -> Int ---------------------------------------- |- (All b . C b -> Int) < C1 aa -> Int ----------------------------------------------- |- All a . (All b . C b -> Int) < C1 a -> Int |- C2 aa < C Y |- Int < Int C2 / m, Y / b ------------------------------- |- C Y -> Int < C2 aa -> Int ---------------------------------------- |- (All b . C b -> Int) < C2 aa -> Int ------------------------------------------------ |- All a . (All b . C b -> Int) < C2 ab -> Int All a . a < b |- aa < b C3 / m ----------------------- All a . a < b |- C3 aa < C b |- Int < Int --------------------------------------------- All a . a < b |- C b -> Int < C3 aa -> Int ----------------------------------------------------- All a . a < b |- (All b . C b -> Int) < m aa -> Int ------------------------------------------------------------ All a . a < b |- All a . (All b . C b -> Int) < m a -> Int -} -- Scheme reduction ----------------------------------------------------------------------------- -- -- If red cs ps == (s,q,es,es') then q |- es :: subst s cs and q |- es' :: subst s ps -- ------------------------------------------------------------------------------------------------- redg r i gs = do -- tr ("Chosen goal: " ++ render (pr (snd g)) ++ " at index " ++ show i ++ ", rank: " ++ show r) -- tr ("***All goals:") -- tr (render (nest 4 (vpr (rng gs)))) (s,q,e:es) <- solve r g (gs1++gs2) let (es1,es2) = splitAt i es return (s, q, es1++[e]++es2, []) where (gs1, g:gs2) = splitAt i gs red [] [] = return (nullSubst, [], [], []) red gs [] = do -- tr ("Ranks: " ++ show rs) case unique 0 gs of Just (r,i) -> redg r i gs -- goal can be selected without computing costly varInfo Nothing -> redg r i gs -- goal must be selected on basis of varInfo where rs = map (rank info) gs r = minimum rs i = length (takeWhile (/=r) rs) info = varInfo gs red gs ((env, p@(Scheme (F [sc1] t2) ps2 ke2)):ps) = do (t1,ps1) <- inst sc1 -- tr ("red: " ++ render (pr t1 <+> text "<" <+> pr t2)) pe <- newEnv assumptionSym ps2 v <- newName coercionSym (env',qe,eq) <- closePreds env (tvars sc1 ++ tvars t2 ++ tvars ps2) pe ke2 let ps' = repeat env' `zip` ps1 (s,q,es,e,es') <- redf gs env' t1 t2 (ps'++ps) pe1 <- wildify ke2 pe qe1 <- wildify ke2 qe let (es1,es2) = splitAt (length ps') es' bss = preferParams env' pe1 qe1 eq e' = eLet' bss (EAp e [eAp (EVar v) es1]) return (s, q, es, eLam pe1 (ELam [(v,sc1)] e') : es2) red gs ((env, Scheme (R t) ps' ke):ps) = do pe <- newEnv assumptionSym ps' (env',qe,eq) <- closePreds env (tvars t ++ tvars ps') pe ke (s,q,e:es,es') <- red ((env',t) : gs) ps pe1 <- wildify ke pe qe1 <- wildify ke qe let bss = preferParams env' pe1 qe1 eq return (s, q, es, eLam pe1 (eLet' bss e) : es') {- ts -> t < ts' -> t' ts1,ts2 -> t < ts1',ts2' -> t' es1 :: ts1' < ts1 e :: ts2->t < ts2'->t' e0 = \(v::ts->t) -> \(ys1:ts1',ys2:ts2') -> e1 e1 :: t' = e e2 ys2 e2 :: ts2->t = \(xs2:ts2) -> v (es3,xs2) es3 :: ts1 = es1@ys1 -} redf gs env (F ts t) (F ts' t') ps = do te1' <- newEnv assumptionSym ts1' te2' <- newEnv assumptionSym ts2' te2 <- newEnv assumptionSym ts2 v <- newName coercionSym (s,q,es,e,es1,es2) <- redf1 gs env (tFun ts2 t) (tFun ts2' t') ts1' ts1 ps let e0 = ELam [(v,scheme' (F ts t))] (ELam (te1'++te2') e1) e1 = eAp (EAp e [e2]) (map EVar (dom te2')) e2 = eLam te2 (EAp (EVar v) (es3 ++ map EVar (dom te2))) es3 = zipWith eAp1 es1 (map EVar (dom te1')) return (s, q, es, e0, es2) where (ts1 ,ts2 ) = splitAt (length ts') ts (ts1',ts2') = splitAt (length ts ) ts' redf gs env (R (TFun ts t)) b ps = redf gs env (F (map scheme ts) (R t)) b ps redf gs env a (R (TFun ts t)) ps = redf gs env a (F (map scheme ts) (R t)) ps redf gs env (R a@(TVar n)) b@(F ts _) ps | n `elem` tvars b = fail (typeError Other env "Infinite function type") | otherwise = do (t:ts') <- mapM newTVar (replicate (length ts + 1) Star) s <- unify env [(a, TFun ts' t)] redf2 s gs env (F (map scheme ts') (R t)) b ps redf gs env a@(F ts _) (R b@(TVar n)) ps | n `elem`tvars a = fail (typeError Other env "Infinite function type") | otherwise = do (t:ts') <- mapM newTVar (replicate (length ts + 1) Star) s <- unify env [(TFun ts' t, b)] redf2 s gs env a (F (map scheme ts') (R t)) ps redf gs env (R a) (R b) ps = do (s,q,e:es,es') <- red ((tick env True, a `sub` b) : gs) ps return (s,q,es,e,es') redf _ env t1 t2 _ = fail (typeError Other env ("Cannot solve " ++ render (pr t1) ++ " < " ++ render (pr t2))) redf1 gs env a b (sc1:ts1) (sc2:ts2) ps = do (s,q,es,e,es1,e2:es2) <- redf1 gs env a b ts1 ts2 ((env,sc):ps) return (s, q, es, e, flip e2 : es1, es2) where Scheme t2 ps2 ke2 = sc2 sc = Scheme (F [sc1] t2) ps2 ke2 flip e | null ps2 = e flip (ELam te2 (ELam te1 t)) = ELam te1 (ELam te2 t) redf1 gs env a b [] [] ps = do (s,q,es,e,es2) <- redf gs env a b ps return (s,q,es,e,[],es2) redf2 s gs env a b ps = do (s',q,es,e,es') <- redf (subst s gs) (subst s env) (subst s a) (subst s b) (subst s ps) return (s'@@s,q,es,e,es') -- Predicate reduction ---------------------------------------------------------------------- solve RFun (env,p) gs = do -- tr ("------ Resubmitting: " ++ render (pr p)) (s,q,es,[e]) <- red gs [(env, scheme' (F [scheme a] (R b)))] return (s, q, e:es) where (a,b) = subs p solve RUnif (env,p) gs = do -- tr ("------ Unifying: " ++ render (pr p)) s <- unify env [(a,b)] (s',q,es,[]) <- red (subst s gs) [] return (s'@@s, q, EVar (prim Refl) : es) where (a,b) = subs p solve RVar g gs = do -- tr ("------ Abstracting\n" ++ render (nest 4 (vpr (rng (g:gs))))) (qs,es) <- fmap unzip (mapM newHyp (g:gs)) return (nullSubst, concat qs, es) solve r g gs | mayLoop g = do assert0 (conservative g) "Recursive constraint" -- tr ("------ Avoiding loop: " ++ render (pr (snd g))) (s,q,es,_) <- red gs [] (q',e) <- newHyp (subst s g) return (s, q'++q, e:es) | otherwise = do -- tr ("------ Solving " ++ render (pr (snd g))) -- tr (render (nest 4 (vpr (rng gs)))) -- tr ("Witness graph: " ++ show (findWG r g)) try r (Left msg) (findWG r g) (logHistory g) gs where msg = typeError Solve (fst g) ("Cannot solve typing constraint "++render(prPred (snd g))) try r accum wg g gs | isNullWG wg || isNull accum = unexpose accum | otherwise = do -- tr ("Trying " ++ render (pr (snd g)) ++ " with " ++ render (pr (predOf wit))) res <- expose (hyp wit g gs) accum <- plus (g : gs) accum res -- tr ("New accum: " ++ show accum) try r accum (wg2 res) g gs where (wit,wg1) = takeWG wg wg2 res = if mayPrune res r g then pruneWG (nameOf wit) wg1 else wg1 mayPrune (Left _) _ _ = False mayPrune (Right r) (RClass _ _) (env,c) = forced env || subst (fst3 r) c == c mayPrune _ _ _ = True hyp (w,p) (env,c) gs = do (R c',ps) <- inst p -- tr ("### Trying: " ++ render (pr c) ++ " with " ++ render (pr (w,p))) s <- unify env [(c,c')] -- tr (" OK") let ps' = repeat (subst s env) `zip` subst s ps -- if not (null ps') then tr ("@@ Appending\n" ++ render (nest 4 (vpr (rng ps')))) else return () (s',q,es,es') <- red (subst s gs) ps' return (s'@@s, q, eAp (EVar w) es' : es) plus gs (Left a) (Left b) |head a == '+' && head b == '-' = return (Left a) |otherwise = return (Left b) plus gs (Left a) b = return b plus gs a (Left b) = return a plus gs (Right (s1,_,es1)) (Right (s2,_,es2)) = do s <- auSubst env s1 s2 (s',q,es) <- auTerms (subst s gs) es1 es2 return (Right (s'@@s, q, es)) where env = fst (head gs) -- Anti-unification -------------------------------------------------------------------------- auSubst env [] s2 = return [] auSubst env ((v1,t1):s1) s2 = case lookup v1 s2 of Just t2 | h1 == h2 -> do ts <- auTypes ts1 ts2 s <- auSubst env s1 s2 return ((v1, tAp h1 ts):s) where (h1,ts1) = tFlat t1 (h2,ts2) = tFlat t2 _ -> auSubst env s1 s2 where auType t1 t2 | h1 == h2 = do ts <- auTypes ts1 ts2 return (tAp h1 ts) | otherwise = newTVar (kindOfType env t1) where (h1,ts1) = tFlat t1 (h2,ts2) = tFlat t2 auTypes ts1 ts2 = sequence (zipWith auType ts1 ts2) auTerms gs es1 es2 = auZip auTerm gs es1 es2 where auZip f [] [] [] = return ([],[],[]) auZip f (g:gs) (e1:es1) (e2:es2) = do (s,q,e) <- f g e1 e2 (s',q',es) <- auZip f (subst s gs) es1 es2 return (s'@@s, subst s' q ++ q', e:es) auZip f gs es1 es2 = internalError0 ("auZip " ++ show gs ++"\n" ++ show es1 ++ "\n" ++ show es2) auTerm g@(env,c) e1 e2 = auTerm' g (eFlat e1) (eFlat e2) auTerm' g@(env,c) (EVar v1, es1) (EVar v2, es2) | v1 == v2 = do (R c',ps) <- inst (findPred env v1) let s = matchTs [(c,c')] (s',q,es) <- auZip auSc (repeat (subst s env) `zip` subst s ps) es1 es2 return (s'@@s, q, eAp (EVar v1) es) auTerm' g@(env,c) (ELam pe1 e1, es1) (ELam pe2 e2, es2) | ps1 == ps2 = do (s,q,e) <- auTerm g e1 (subst s0 e2) (s',q',es) <- auZip auSc (repeat (subst s env) `zip` subst s ps1) es1 es2 return (s'@@s, subst s' q ++ q', eAp (ELam pe1 e) es) where (vs1,ps1) = unzip pe1 (vs2,ps2) = unzip pe2 s0 = vs2 `zip` map EVar vs1 auTerm' g e1 e2 = do (q,e) <- newHyp g return ([], q, e) auSc (env,Scheme (R c) [] ke) e1 e2 = auTerm (addKEnv ke env,c) e1 e2 auSc (env,Scheme (R c) ps ke) (ELam pe1 e1) (ELam pe2 e2) = do (s,q,e) <- auTerm (env',c) e1 (subst s0 e2) return (s, q, ELam pe1 e) where s0 = dom pe2 `zip` map EVar (dom pe1) env' = addPEnv pe1 (addKEnv ke env) auSc _ _ _ = internalError0 "auTerms" newHyp (env,c) = do v <- newName (sym env) -- tr ("newHyp " ++ render (pr (v,p)) ++ ", ticked/forced: " ++ show (ticked env,forced env)) return ([(v,p)], eAp (EVar (annotExplicit v)) (map EVar vs)) where p = Scheme (R c) ps ke (vs,ps) = unzip (predEnv env) ke = kindEnv env sym env | forced env = dummySym -- unwanted garbage predicate, trap in resolve | ticked env = coercionSym -- originates from a coercion predicate | otherwise = assumptionSym -- ordinary predicate -- Unification ---------------------------------------------------------- unify env [] = return nullSubst unify env ((TVar n,t):eqs) | mayBind env n = tvarBind env n t eqs unify env ((t,TVar n):eqs) | mayBind env n = tvarBind env n t eqs unify env ((TAp t u,TAp t' u'):eqs) = unify env ((t,t'):(u,u'):eqs) unify env ((TId c,TId c'):eqs) | c == c' = unify env eqs unify env ((TFun ts t, TFun ts' t'):eqs) | length ts == length ts' = unify env ((t,t') : ts `zip` ts' ++ eqs) unify env ((t1,t2):_) = fail (typeError Unify env ("Cannot unify " ++ render(pr t1) ++ " with " ++ render(pr t2))) tvarBind env n t eqs | t == TVar n = unify env eqs | tvKind n /= kindOfType env t = fail (typeError Other env ("Kind mismatch in unify: " ++ show (tvKind n) ++ " and " ++ show (kindOfType env t))) | n `elem` tvars t = fail (typeError Other env "Occurs check failed in unify") | n `elem` skolEnvs env (tyvars t) = fail (typeError Other env "Skolem escape in unify") | otherwise = do s' <- unify (subst s env) (subst s eqs) return (s' @@ s) where s = n +-> t mayBind env n = not (frozen env && n `elem` pevars env) -- Unification lifted to type schemes: only used to resolve ambiguities found during simplification -------------------- unifyS env ((Scheme r ps ke,Scheme r' ps' ke'):eqs) | rng ke == rng ke' && length ps == length ps' = do s <- unifyR env (subst s0 r, subst s0 r') s' <- unifyS env (subst s (subst s0 ((ps `zip` ps') ++ eqs))) return (s' @@ s) | otherwise = fail (typeError Other env "Quantified predicates not unifiable") where s0 = dom ke `zip` map TId (dom ke') unifyS env [] = return nullSubst unifyR env (R t, R t') = unify env [(t,t')] unifyR env (F scs r, F scs' r') | length scs == length scs' = do s <- unifyS env (scs `zip` scs') s' <- unifyR env (subst s r, subst s r') return (s' @@ s) unifyR env _ = fail (typeError Other env "Subtype predicates not unifiable") -- Misc ---------------------------------------------------------------- mayLoop (env,c) = any (\c' -> equalTs [(c,c')]) (history env) isNull (Right ([],q,es)) | all varTerm es = True where varTerm (EAp e es) = varTerm e varTerm (ELam pe e) = varTerm e varTerm (EVar v) = v `elem` vs varTerm _ = False vs = dom q isNull _ = False -- Adding predicates to the environment ------------------------------------------------- closePreds0 env pe = do (env1,pe1,eq1) <- closeTransitive env0 pe (env2,pe2,eq2) <- closeSuperclass env1 pe return (env2, pe1++pe2, eq1++eq2) where env0 = addPEnv0 pe env closePreds env tvs pe ke = do (env1,pe1,eq1) <- closeTransitive env0 pe (env2,pe2,eq2) <- closeSuperclass env1 pe return (thaw env2, pe1++pe2, eq1++eq2) where se = mapSnd (const (tvs ++ pevars env)) ke env0 = freeze (addPEnv pe (addSkolEnv se (addKEnv ke env))) preferLocals env pe qe eq = walk [] (equalities env) where walk bs [] = let (pe1,pe2) = partition ((`elem` dom bs) . fst) pe in (pe2, groupBinds (Binds False (pe1++qe) (prune eq (dom bs) ++ mapSnd EVar bs))) walk bs ((x,y):eqs) | x `notElem` vs1 = walk bs eqs | y `notElem` vs1 = walk bs eqs | otherwise = case (x `elem` vs0, y `elem` vs0) of (True, True) -> walk ((x,y):bs) eqs (True, False) -> walk ((x,y):bs) eqs (False, True) -> walk ((y,x):bs) eqs (False, False) -> walk ((y,x):bs) eqs vs0 = dom pe vs1 = vs0 ++ dom qe preferParams env pe qe eq = walk [] [] (equalities env) where walk ws bs [] = groupBinds (Binds False (prune qe ws) (prune eq (ws ++ dom bs) ++ mapSnd EVar bs)) walk ws bs ((x,y):eqs) | x `notElem` vs1 = walk ws bs eqs | y `notElem` vs1 = walk ws bs eqs | otherwise = case (x `elem` vs0, y `elem` vs0) of (True, True) -> walk ws bs eqs (True, False) -> walk ws ((y,x):bs) eqs (False, True) -> walk (x:ws) bs eqs (False, False) -> walk (x:ws) bs eqs vs0 = dom pe vs1 = vs0 ++ dom qe {- Top-level & local reduction: Action during simplify: In (equalities env): Meaning: (prefer assumptions (v) in (pe)) (prefer local defs (w) in (qe)) (v,v') Two witness assumptions equal Ignore equality info Remove assumption v [only v' is in use] Add def "let v = v' in ..." (v,w') Witness assumption is equal to a Remove local def of w' [in use] Remove assumption v local def Add "let w' = v in ..." Add def "let v = w' in ..." (w,v') Witness assumption is equal to a Remove local def of w Remove assumption v' local def [only assumption v' is in use] Add def "let v' = w in ..." (w,w') Two local witness definitions Remove local def of w Remove local def of w' are equal [only w' is in use] Add def "let w' = w in ..." v and v' are witness assumptions (elements of (dom pe)) w and w' are locally generated witnesses (elements of (dom qe)) -} mapSuccess f xs = do xs' <- mapM (expose . f) xs return (unzip [ x | Right x <- xs' ]) -- Handle subtype predicates closeTransitive env [] = return (env, [], []) closeTransitive env ((w,p):pe) | isSub' p = do assert1 (a /= b) "Illegal subtype predicate" p (pe1,eq1) <- mapSuccess (mkTrans env) [ (n1,n2) | n1 <- below_a, n2 <- [(w,p)] ] (pe2,eq2) <- mapSuccess (mkTrans env) [ (n1,n2) | n1 <- (w,p):pe1, n2 <- above_b ] let cycles = filter (uncurry (==)) (map (subsyms . predOf) (pe1++pe2)) assert0 (null cycles) (encodeError circularSubMsg (nub (a:b:map fst cycles))) env2 <- addPreds env ((w,p):pe1++pe2) (env3,pe3,eq3) <- closeTransitive env2 pe return (env3, pe1++pe2++pe3, eq1++eq2++eq3) where (a,b) = subsyms p below_a = nodes (findBelow env a) above_b = nodes (findAbove env b) closeTransitive env (_:pe) = closeTransitive env pe mkTrans env ((w1,p1), (w2,p2)) = do (pe1, R c1, e1) <- instantiate p1 (EVar w1) (pe2, R c2, e2) <- instantiate p2 (EVar w2) let (t1,t1') = subs c1 (t2',t2) = subs c2 s <- unify env [(t1',t2')] let t = subst s t1 p = scheme (t `sub` subst s t2) (s',qe,f) <- norm (protect p env) (subst s (pe1++pe2)) x <- newName paramSym let e = ELam [(x,scheme (subst s' t))] (f (EAp e2 [EAp e1 [EVar x]])) (e',p') = qual qe e (subst s' p) sc <- gen (tevars env) p' w <- newNameMod (modName env) coercionSym e' <- redTerm (coercions env) e' return ((w,sc), (w, e')) -- Handle class predicates closeSuperclass env [] = return (env, [], []) closeSuperclass env ((w,p):pe) | isClass' p = do (pe1,eq1) <- mapSuccess (mkSuper env (w,p)) [ n | n <- above_c ] env1 <- addPreds env ((w,p):pe1) (env2,pe2,eq2) <- closeSuperclass env1 pe return (env2, pe1++pe2, eq1++eq2) where c = headsym p above_c = filter ((`elem` dom (classEnv env)) . uppersym . predOf) (nodes (findAbove env c)) closeSuperclass env (_:pe) = closeSuperclass env pe mkSuper env (w1,p1) (w2,p2) = do (pe1, R c1, e1) <- instantiate p1 (EVar w1) (pe2, R c2, e2) <- instantiate p2 (EVar w2) let (t2',t2) = subs c2 s <- unify env [(c1,t2')] let p = scheme (subst s t2) (s',qe,f) <- norm (protect p env) (subst s (pe1++pe2)) let e = f (EAp e2 [e1]) (e',p') = qual qe e (subst s' p) sc <- gen (tevars env) p' w <- newNameMod (modName env) witnessSym return ((w,sc), (w,e')) -- Add predicates to the environment and build overlap graph addPreds env [] = return env addPreds env (n@(w,p):pe) | isSub' p = case findCoercion env a b of Just (w',p') -> do r <- implications env p' p case r of Equal -> addPreds (addEqs [(w,w')] env) pe ImplyRight -> addPreds env pe ImplyLeft -> addPreds env pe -- Ignore w for now (should really replace w') Unrelated -> fail (encodeError ambigSubMsg [w,w']) Nothing -> do addPreds (insertSubPred n env) pe | isClass' p = do r <- cmpNode [] [] (nodes (findClass env c)) case r of Right (pre,post) -> addPreds (insertClassPred pre n post env) pe Left w' -> addPreds (addEqs [(w,w')] env) pe where (a,b) = subsyms p c = headsym p cmpNode pre post [] = return (Right (pre,post)) cmpNode pre post ((w',p'):pe') = do r <- implications env p' p case r of Equal | isGenerated w || isGenerated w' -> return (Left w') | otherwise -> fail (encodeError ambigInstMsg [w,w']) ImplyRight -> cmpNode pre (w':post) pe' ImplyLeft -> cmpNode (w':pre) post pe' Unrelated -> cmpNode pre post pe' data Implications = Equal | ImplyRight | ImplyLeft | Unrelated deriving (Eq,Show) implications env p1 p2 = do (R c1,ps1) <- inst p1 (R c2,ps2) <- inst p2 r1 <- expose (unify (addKEnv (quant p2) env) [(c1,body p2)]) r2 <- expose (unify (addKEnv (quant p1) env) [(body p1,c2)]) case (r1,r2) of (Right s, Right _) -> return Equal (Right _, Left _) -> return ImplyRight (Left _, Right _) -> return ImplyLeft (Left _, Left _) -> return Unrelated {- Ord a |- Ord a Ord a \\ a |- Ord Int C a \\ a |- D a => C a \\ a D a => C a \\ a |- D a => E a => C a \\ a a < b |- a < b m a < m a \\ a |- m Int < m Int m a < n a \\ a, C a |- m a < n a \\ a x : Eq a y : Eq a ==> eqid x : Eq a eqid y : Eq a ==> eqid x : Eq a |- (eqid x)/y : Eq a -} {- A<A:0 : A : 0:A<A [] B<B:0 : B : 0:B<B [] buildAbove 7:A<B, (a,b)=(A,B), syms = {A}, c = A, adding A<B after A<A to aboveEnv A (0,7) 0:A<A : A : 0:A<A,7:A<B buildBelow 7:A<B, (a,b)=(A,B), syms = {B}, c = B, adding A<B after B<B to belowEnv B (0,7) 7:A<B,0:B<B : B : 0:B<B -} {- Ord a => Ord [a] \\ a (b < a) => Ord a < Ord b \\ a,b (b < a) => Ord a < Eq b \\ a,b (a < b) => [a] < [b] \\ a,b ... Ord a, [b] < [a] => Eq [b] Ord a, b < a => Eq [b] Ord a => Eq [a] Eq a => Eq [a] Ord aa, Eq aa, Eq a => Eq [a] \\ a |- Eq aa --------------------------------------------- Ord aa, Eq a => Eq [a] \\ a |- Eq aa ---------------------------------------- Ord aa, Eq a => Eq [a] \\ a |- Eq [aa] --------------------------------------------- Eq a => Eq [a] \\ a |- Ord a => Eq [a] \\ a -} {- 1: A < A x < A [ A < A, B < A, C < A ] A < x [ A < A ] 2: B < A x < B [ B < B, C < B ] B < x [ B < B, B < A ] 3: B < B 4: C < A x < C [ C < C ] C < x [ C < C, C < B, C < A ] 5: C < B 6: C < C (1,2) (1,4) (2,3) (2,4) (3,5) (4,5) (4,6) (5,6) Show [a] \\ Show a Show [C] w : Eq A u : Eq B Eq C x -> T \\ x < A, Show [x] x -> T \\ x < A, Eq x x -> T \\ x < y, y < a f : A->T eq : Eq a => a->a->Bool |- w : Eq A |- id : A->A->Bool < A->A->Bool ----------------------------------------------------- |- \v.id (v w) : Eq A => A->A->Bool < A->A->Bool -------------------------------------------------- |- \v.v w : Eq a => a->a->Bool < A->A->Bool x:A |- eq : Eq a => a->a->Bool -------------------------------- x:A |- (\v.v w) eq : A->A->Bool x:A |- x : A -------------------------------- --------------- x:A |- eq w x x : Bool x:A |- f x : T ----------------------------------------------------------- x:A |- if eq w x x then f x else f x : T ----------------------------------------------------------- |- \x -> if eq w x x then f x else f x : A -> T |- u : Eq B |- id : B->B->Bool < B->B->Bool ---------------------------------------------------- |- \v.id (v u) : Eq B => B->B->Bool < B->B->Bool -------------------------------------------------- |- \v.v u : Eq a => a->a->Bool < B->B->Bool x:B |- eq : Eq a => a->a->Bool x.B |- x : B |- b : B < A ------------------------------------ ---------------------------- x:B |- (\v.v u) eq : B->B->Bool x:B |- b x : A ------------------------------- --------------- x:B |- eq u x x : Bool x:B |- f (b x) : T --------------------------------------------------------------- x:B |- if eq u x x then f (b x) else f (b x) : T --------------------------------------------------------------- |- \x -> if eq u x x then f (b x) else f (b x) : B -> T P = k:x<A, j:Eq x P |- j : Eq x P |- id : x->x->Bool < x->x->Bool ---------------------------------------------------- P |- \v.id (v j) : Eq B => x->x->Bool < x->x->Bool -------------------------------------------------- P |- \v.v j : Eq a => a->a->Bool < x->x->Bool P | x:x |- eq : Eq a => a->a->Bool P | x.x |- x : x P |- k : x < A ------------------------------------ ----------------------------------- P | x:x |- (\v.v j) eq : x->x->Bool P | x:x |- k x : A ----------------------------------- ---------------------- P | x:x |- eq j x x : Bool P | x:x |- f (k x) : T ---------------------------------------------------------------------- P | x:x |- if eq j x x then f (k x) else f (k x) : T --------------------------------------------------------------- P | |- \x -> if eq j x x then f (k x) else f (k x) : x -> T ------------------------------------------------------------------------------------ | |- \k j x -> if eq j x x then f (k x) else f (k x) : (x < A, Eq x) => x -> T x < A |- x < A x < A |- T < T ------------------------------------ x < A |- A -> T < x -> T -------------------------------- |- x < A => (A -> T < x -> T) -------------------------------- |- A -> T < (x < A => x < T) x < A, Eq x |- x < A x < A, Eq x |- T < T ------------------------------------------------ x < A, Eq x |- A -> T < x -> T ------------------------------------- |- (x < T, Eq x) => (A -> T < x -> T) -------------------------------------- |- A -> T < ((x < A, Eq x) => x < T) w : Eq A u : Eq B c : B < A eq : Eq a => a -> a -> Bool eq w (f b1) (f b2) == eq u b1 b2 ??? h . g . f == i2f : Int < Float neq : Num a => a -> a ni : Num Int nf : Num Float i2f (neg ni x) == neg nf (i2f x) ??? bind : Monad m => m a -> (a->m b) -> m b f : Request Int g : Int -> Action Monad m, Request Int < m Int, Action < m b Monad Cmd, Request Int < Cmd Int, Action < Cmd () Monad (O s), Request Int < O s Int, Action < O s () |- c : Monad m => m a -> (a -> m b) -> m b < Cmd Int -> (Int -> Cmd ()) -> Cmd () |- bind : Monad m => m a -> (a -> m b) -> m b --------------------------------------------------------------------------------------------------------- |- c bind : Cmd Int -> (Int -> Cmd ()) -> Cmd () ---------------------------------------------- |-> c bind f g : Cmd () -}
UBMLtonGroup/timberc
src/Reduce.hs
bsd-3-clause
48,749
0
22
23,835
11,003
5,634
5,369
434
10
module Main where import Android main :: IO () main = runAndroid $ do ( textView, setText, setContentView ) <- importAndroid myTV <- clone textView method myTV setText [ primStr "今日は、世界!" ] method myTV setContentView [ ] return ()
YoshikuniJujo/prototype
examples/android/testAndroid.hs
bsd-3-clause
250
0
10
46
88
43
45
9
1
import System.IO (getContents) import Codec.Binary.UTF8.String (encodeString, decodeString) import Data.Maybe (fromJust) import Morfeusz -- | Read word from stdin and analyse it with Morfeusz. main = do -- Set Morfeusz encoding to UTF-8 setEncoding utf8 -- Get unicode encoded word from stdin word <- getContents -- Encode word in UTF-8, send to analysis and print retrieved lemmas. analyse (encodeString word) >>= mapM put where put = putStrLn . decodeString . fromJust . lemma
kawu/morfeusz
examples/LemmasExample.hs
bsd-3-clause
525
4
10
118
111
54
57
9
1
-- @+leo-ver=4-thin -- @+node:gcross.20090709200011.8:@thin PrivatizationTests.hs -- @@language haskell -- @<< Language extensions >> -- @+node:gcross.20090709200011.9:<< Language extensions >> {-# LANGUAGE ScopedTypeVariables #-} -- @-node:gcross.20090709200011.9:<< Language extensions >> -- @nl module PrivatizationTests(tests) where -- @<< Imports >> -- @+node:gcross.20090709200011.10:<< Imports >> import Control.Exception import Control.Monad import Control.Monad.Reader import Control.Monad.RWS import qualified Data.ByteString as S import Data.Either.Unwrap import Data.Map (Map,keysSet) import qualified Data.Map as Map import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Language.C import Language.C.System.GCC import Language.C.System.Preprocess import System import System.Directory import System.Exit import System.FilePath import System.IO import System.Process import Test.Framework import Test.Framework.Providers.HUnit import Test.HUnit import Text.PrettyPrint import Algorithm.GlobalVariablePrivatization.Common import Algorithm.GlobalVariablePrivatization.Privatization import CommonTestUtils -- @-node:gcross.20090709200011.10:<< Imports >> -- @nl -- @+others -- @+node:gcross.20090715105401.29:Helpers -- @+node:gcross.20090715105401.27:makeFunctionFromMap makeFunctionFromMap map name = fromMaybe (error $ "unable to find global variable with name '" ++ name ++ "'") (Map.lookup name map) -- @-node:gcross.20090715105401.27:makeFunctionFromMap -- @+node:gcross.20090715105401.28:makeFunctionFromLocalStaticMap makeFunctionFromLocalStaticMap map = fmap makeFunctionFromMap . flip Map.lookup map -- @-node:gcross.20090715105401.28:makeFunctionFromLocalStaticMap -- @-node:gcross.20090715105401.29:Helpers -- @+node:gcross.20090709200011.36:Test makers -- @+node:gcross.20090709200011.11:makeTestFromSource makeTestFromSource :: String -> Assertion makeTestFromSource source = do temporary_directory <- getTemporaryDirectory (source_filepath, source_handle) <- openTempFile temporary_directory "test.c" (executable_filepath, executable_handle) <- openTempFile temporary_directory "test" finally (do hClose executable_handle hPutStr source_handle source hClose source_handle (rawSystem "cc" [source_filepath,"-o",executable_filepath]) >>= assertEqual "Were we able to compile the source code?" ExitSuccess (_, Just process_output, _, process_handle) <- createProcess (proc executable_filepath []) { std_out = CreatePipe } exit_code <- waitForProcess process_handle when (exit_code /= ExitSuccess) $ hGetContents process_output >>= assertFailure ) (deleteTemporaries [ source_filepath , executable_filepath ] ) -- @-node:gcross.20090709200011.11:makeTestFromSource -- @+node:gcross.20090711085032.33:makeTestFromPrivatizedSource makeTestFromPrivatizedSource :: String -> Map String Allocation -> Map String (Map String Allocation) -> Bool -> String -> String -> Assertion makeTestFromPrivatizedSource module_data_accessor_name global_variable_allocation_map local_static_variable_allocation_map print_source prelude = makeTestFromSource . (if print_source then echo id else id) . (prelude ++) . render . pretty . processTranslUnit module_data_accessor_name (keysSet global_variable_allocation_map) (makeFunctionFromMap global_variable_allocation_map) (makeFunctionFromLocalStaticMap local_static_variable_allocation_map) . parseTranslUnit -- @nonl -- @-node:gcross.20090711085032.33:makeTestFromPrivatizedSource -- @+node:gcross.20090709200011.35:makePrivatizeExprTest makePrivatizeExprTest :: Map String Allocation -> Map String Allocation -> String -> String -> Assertion makePrivatizeExprTest global_variable_allocation_map local_static_variable_allocation_map original_code privatized_code = assertEqual "is the privatized code correct?" privatized_code . unwords . words . render . pretty . (\(x,_,_) -> x) . (\expr -> runRWS (privatizeExpr expr) (FunctionProcessingEnvironment { globalModuleDataAccessorName = undefined , globalVariableAllocationMap = (makeFunctionFromMap global_variable_allocation_map) , localStaticVariableAllocationMap = (makeFunctionFromMap local_static_variable_allocation_map) } ) (keysSet global_variable_allocation_map, keysSet local_static_variable_allocation_map)) . parseExpression $ original_code -- @-node:gcross.20090709200011.35:makePrivatizeExprTest -- @+node:gcross.20090709200011.41:makePrivatizeStmtTest makePrivatizeStmtTest :: String -> Map String Allocation -> Set String -> Map String Allocation -> String -> String -> Assertion makePrivatizeStmtTest module_data_accessor_name global_variable_allocation_map local_static_variables_in_scope local_static_variable_allocation_map original_code privatized_code = assertEqual "is the privatized code correct?" (unwords . words . render . pretty . parseStatement $ privatized_code) . unwords . words . render . pretty . (\(x,_,_) -> x) . (\stat -> runRWS (privatizeStmt stat) (FunctionProcessingEnvironment { globalModuleDataAccessorName = module_data_accessor_name , globalVariableAllocationMap = (makeFunctionFromMap global_variable_allocation_map) , localStaticVariableAllocationMap = (makeFunctionFromMap local_static_variable_allocation_map) } ) (keysSet global_variable_allocation_map, local_static_variables_in_scope) ) . parseStatement $ original_code -- @-node:gcross.20090709200011.41:makePrivatizeStmtTest -- @+node:gcross.20090710174219.12:makePrivatizeFunctionTest makePrivatizeFunctionTest :: String -> Map String Allocation -> Map String Allocation -> String -> String -> Assertion makePrivatizeFunctionTest module_data_accessor_name global_variable_allocation_map local_static_variable_allocation_map original_code privatized_code = assertEqual "is the privatized code correct?" (unwords . words . render . pretty . parseDeclaration $ privatized_code) . unwords . words . render . pretty . privatizeFunction module_data_accessor_name (keysSet global_variable_allocation_map) (makeFunctionFromMap global_variable_allocation_map) (makeFunctionFromMap local_static_variable_allocation_map) . (\(CFDefExt x) -> x) . parseDeclaration $ original_code -- @-node:gcross.20090710174219.12:makePrivatizeFunctionTest -- @+node:gcross.20090711085032.9:makeProcessStmtTest makeProcessStmtTest :: String -> Map String Allocation -> Map String Allocation -> String -> String -> Assertion makeProcessStmtTest module_data_accessor_name global_variable_allocation_map local_static_variable_allocation_map original_code processed_code = assertEqual "is the processed code correct?" (unwords . words . render . pretty . parseStatement $ processed_code) . unwords . words . render . pretty . (\(x,_,_) -> x) . (\stat -> runRWS (processStmt stat) (FunctionProcessingEnvironment { globalModuleDataAccessorName = module_data_accessor_name , globalVariableAllocationMap = (makeFunctionFromMap global_variable_allocation_map) , localStaticVariableAllocationMap = (makeFunctionFromMap local_static_variable_allocation_map) } ) (keysSet global_variable_allocation_map, keysSet local_static_variable_allocation_map) ) . parseStatement $ original_code -- @-node:gcross.20090711085032.9:makeProcessStmtTest -- @+node:gcross.20090711085032.22:makeProcessFunctionTest makeProcessFunctionTest :: String -> Map String Allocation -> Map String Allocation -> String -> String -> Assertion makeProcessFunctionTest module_data_accessor_name global_variable_allocation_map local_static_variable_allocation_map original_code processed_code = assertEqual "is the processed code correct?" (unwords . words . render . pretty . parseDeclaration $ processed_code) . unwords . words . render . pretty . CFDefExt . processFunction module_data_accessor_name (keysSet global_variable_allocation_map) (makeFunctionFromMap global_variable_allocation_map) (makeFunctionFromMap local_static_variable_allocation_map) . (\(CFDefExt x) -> x) . parseDeclaration $ original_code -- @-node:gcross.20090711085032.22:makeProcessFunctionTest -- @+node:gcross.20090711085032.28:makeProcessToplevelDeclarationTest makeProcessToplevelDeclarationTest :: String -> Map String Allocation -> Map String (Map String Allocation) -> String -> String -> Assertion makeProcessToplevelDeclarationTest module_data_accessor_name global_variable_allocation_map local_static_variable_allocation_map original_code processed_code = assertEqual "is the processed code correct?" (unwords . words . render . pretty . parseTranslUnit $ processed_code) . unwords . words . render . pretty . (flip CTranslUnit internalNode) . processToplevelDeclaration module_data_accessor_name (keysSet global_variable_allocation_map) (makeFunctionFromMap global_variable_allocation_map) (makeFunctionFromLocalStaticMap local_static_variable_allocation_map) . parseDeclaration $ original_code -- @-node:gcross.20090711085032.28:makeProcessToplevelDeclarationTest -- @-node:gcross.20090709200011.36:Test makers -- @+node:gcross.20090709200011.12:Tests tests = -- @ @+others -- @+node:gcross.20090709200011.13:test [testCase "test" $ makeTestFromSource . unlines $ ["#include <stdio.h>" ,"int main() { printf(\"Nothing to see here; move along.\"); return 0; }" ] -- @-node:gcross.20090709200011.13:test -- @+node:gcross.20090709200011.15:makeAccessor ,testCase "makeAccessor" $ let accessor_source = render . pretty $ let size_const = CConst (CIntConst (cInteger.toInteger $ 6) internalNode) indirections = [CArrDeclr [] (CArrSize False size_const) internalNode] in makeAccessor "getGlobals" False "global_variable" (makeTypedefSpecifier "global_variable_type") indirections 6 source = unlines ["" ,"#include <stdio.h>" ,"#include <stdlib.h>" ,"" ,"char* global_string = \"wrong\\0right\";" ,"void* getGlobals() { return global_string; }" ,"" ,"typedef char global_variable_type;" ,"" ] ++ accessor_source ++ unlines ["" ,"int main() {" ," char (*string)[6] = __access__global_variable();" ," printf(\"Expected 'right' but got '%s'\",string);" ," return strcmp(string,\"right\");" ,"}" ] in makeTestFromSource source -- @-node:gcross.20090709200011.15:makeAccessor -- @+node:gcross.20090711085032.7:Privatization ,testGroup "Privatization" -- @ @+others -- @+node:gcross.20090709200011.33:privatizeExpr [testGroup "privatizeExpr" -- @ @+others -- @+node:gcross.20090709200011.34:global variable [testCase "global variable" $ makePrivatizeExprTest (Map.singleton "var" undefined) Map.empty "1 + var * 2" "1 + *__access__var() * 2" -- @-node:gcross.20090709200011.34:global variable -- @+node:gcross.20090711085032.37:nested global variable ,testCase "nested global variable" $ makePrivatizeExprTest (Map.singleton "c" undefined) Map.empty "strcpy(c, d)" "strcpy(*__access__c(), d)" -- @-node:gcross.20090711085032.37:nested global variable -- @+node:gcross.20090709200011.37:local static variable ,testCase "local static variable" $ makePrivatizeExprTest Map.empty (Map.singleton "var" undefined) "var * 2 == 5 ? i : j" "*var * 2 == 5 ? i : j" -- @-node:gcross.20090709200011.37:local static variable -- @+node:gcross.20090709200011.38:both ,testCase "both" $ makePrivatizeExprTest (Map.singleton "var" undefined) (Map.singleton "var" undefined) "(int) f(var++)" "(int) f((*var)++)" -- @-node:gcross.20090709200011.38:both -- @+node:gcross.20090709200011.39:neither ,testCase "neither" $ makePrivatizeExprTest (Map.singleton "var" undefined) (Map.singleton "var" undefined) "++nonvar" "++nonvar" -- @-node:gcross.20090709200011.39:neither -- @+node:gcross.20090928181847.1541:sizeof global variable ,testCase "sizeof global variable" $ makePrivatizeExprTest (Map.singleton "var" (Allocation {allocationSize = 42, allocationOffset = undefined})) Map.empty "sizeof(var)" "42" -- @-node:gcross.20090928181847.1541:sizeof global variable -- @+node:gcross.20090928181847.1543:sizeof local static variable ,testCase "sizeof local static variable" $ makePrivatizeExprTest Map.empty (Map.singleton "var" (Allocation {allocationSize = 42, allocationOffset = undefined})) "sizeof(var)" "42" -- @-node:gcross.20090928181847.1543:sizeof local static variable -- @+node:gcross.20090928181847.1545:sizeof both ,testCase "sizeof both" $ makePrivatizeExprTest (Map.singleton "var1" (Allocation {allocationSize = 24, allocationOffset = undefined})) (Map.singleton "var2" (Allocation {allocationSize = 42, allocationOffset = undefined})) "sizeof(var1)+sizeof(var2)" "24 + 42" -- @-node:gcross.20090928181847.1545:sizeof both -- @-others ] -- @-node:gcross.20090709200011.33:privatizeExpr -- @+node:gcross.20090709200011.42:privatizeStmt ,testGroup "privatizeStmt" -- @ @+others -- @+node:gcross.20090709200011.43:global variable [testCase "global variable" $ makePrivatizeStmtTest undefined (Map.singleton "var" undefined) Set.empty Map.empty "if (var == i) { return var; } else { return j; }" "if (*__access__var() == i) { return *__access__var(); } else { return j; }" -- @-node:gcross.20090709200011.43:global variable -- @+node:gcross.20090709200011.44:local static variable ,testCase "local static variable" $ makePrivatizeStmtTest undefined Map.empty (Set.singleton "var") (Map.singleton "var" undefined) "switch (var) { case 1: var = var + 1; case 2: ++var; }" "switch (*var) { case 1: *var = *var + 1; case 2: ++ (*var); }" -- @-node:gcross.20090709200011.44:local static variable -- @+node:gcross.20090709200011.45:both ,testCase "both" $ makePrivatizeStmtTest undefined (Map.singleton "var" undefined) (Set.singleton "var") (Map.singleton "var" undefined) "for (var = 0; var < 5; var++) { return var; }" "for (*var = 0; *var < 5; (*var)++) { return *var; }" -- @-node:gcross.20090709200011.45:both -- @+node:gcross.20090709200011.46:neither ,testCase "neither" $ makePrivatizeStmtTest undefined (Map.singleton "var" undefined) Set.empty (Map.singleton "var" undefined) "if (nonvar) return 4;" "if (nonvar) return 4;" -- @-node:gcross.20090709200011.46:neither -- @-others ] -- @-node:gcross.20090709200011.42:privatizeStmt -- @+node:gcross.20090710174219.5:privatizeBlockItem ,testGroup "privatizeBlockItem" -- @ @+others -- @+node:gcross.20090710174219.6:shadowing [testCase "shadowing" $ makePrivatizeStmtTest undefined (Map.singleton "var" undefined) (Set.singleton "var") (Map.singleton "var" undefined) "{ var++; int var; var++; }" "{ (*var)++; int var; var++; }" -- @-node:gcross.20090710174219.6:shadowing -- @+node:gcross.20090718130736.27:initializer handling ,testCase "shadowing" $ makePrivatizeStmtTest undefined (Map.singleton "other" undefined) Set.empty Map.empty "{ int* var = &other; }" "{ int* var = & (*__access__other());}" -- @-node:gcross.20090718130736.27:initializer handling -- @+node:gcross.20090710174219.7:static declaration ,testCase "static declaration" $ makePrivatizeStmtTest "getPtr" Map.empty Set.empty (Map.fromList [("var1",Allocation (error "Should not need to know size of var1!") 42),("var2",Allocation (error "Should not need to know size of var2!") 12)]) "{ ++var; static int var1, *var2; ++var1; var2 = &var1; }" "{ ++var; typedef int __type_of__var1; __type_of__var1 *var1 = (__type_of__var1*) (getPtr() + 42), **var2 = (__type_of__var1 **) (getPtr() + 12); ++ (*var1); *var2 = &(*var1); }" -- @-node:gcross.20090710174219.7:static declaration -- @+node:gcross.20090710174219.8:external global variable ,testCase "external global variable" $ makePrivatizeStmtTest undefined (Map.singleton "var" undefined) Set.empty Map.empty "{ var; extern int var; var; }" "{ *__access__var(); extern int *__access__var(); *__access__var(); }" -- @-node:gcross.20090710174219.8:external global variable -- @+node:gcross.20090710174219.9:emerging from the shadow ,testCase "emerging from the shadow" $ makePrivatizeStmtTest undefined Map.empty (Set.singleton "var") (Map.singleton "var" undefined) "{ if(1) { int var; var++; }; var++; }" "{ if(1) { int var; var++; }; (*var)++; }" -- @-node:gcross.20090710174219.9:emerging from the shadow -- @-others ] -- @-node:gcross.20090710174219.5:privatizeBlockItem -- @+node:gcross.20090710174219.13:privatizeFunction ,testGroup "privatizeFunction" -- @ @+others -- @+node:gcross.20090711085032.36:simple [testCase "simple" $ makePrivatizeFunctionTest undefined (Map.singleton "c" undefined) Map.empty "static char* f() { strcpy(c,d); }" "static char* f() { strcpy(*__access__c(),d); }" -- @-node:gcross.20090711085032.36:simple -- @+node:gcross.20090710174219.14:shadowing ,testCase "shadowing" $ makePrivatizeFunctionTest "getPtr" (Map.fromList [("gvar",undefined),("var",undefined)]) (Map.fromList [("svar",Allocation undefined 1)]) "void f(int var) { static int svar = 0; ++svar; return var + gvar + svar; }" "void f(int var) { typedef int __type_of__svar; __type_of__svar *svar = (__type_of__svar*)(getPtr()+1); ++(*svar); return var + *__access__gvar() + *svar; }" -- @-node:gcross.20090710174219.14:shadowing -- @+node:gcross.20090928192713.1543:with sizeof ,testCase "with sizeof" $ makePrivatizeFunctionTest undefined (Map.singleton "c" (Allocation 42 undefined)) Map.empty "static int f() { return sizeof(c); }" "static int f() { return 42; }" -- @-node:gcross.20090928192713.1543:with sizeof -- @-others ] -- @-node:gcross.20090710174219.13:privatizeFunction -- @-others ] -- @-node:gcross.20090711085032.7:Privatization -- @+node:gcross.20090711085032.8:Initializer Construction ,testGroup "Initializer Construction" -- @ @+others -- @+node:gcross.20090709200011.24:makeInitializer [testGroup "makeInitializer" -- @ @+others -- @+node:gcross.20090709200011.28:with initializer [testCase "with initializer" $ let initializer_source = render . pretty $ let init = CInitList [([],CInitExpr expr internalNode) | expr <- [ makeIntegerExpr 42 , makeFloatExpr 3.14 , makeStringExpr "right" ] ] internalNode in makeInitializer undefined undefined "global_variable" (makeTypedefSpecifier "global_variable_type") [] (Just init) source = unlines ["" ,"#include <stdio.h>" ,"#include <stdlib.h>" ,"#include <string.h>" ,"" ,"typedef struct {" ," int a;" ," float b;" ," char *c;" ,"} global_variable_type;" ,"" ,"global_variable_type global_variable = {0,0,\"wrong\"};" ,"global_variable_type* __access__global_variable() { return &global_variable; }" ,"" ] ++ initializer_source ++ unlines ["" ,"int main() {" ," __initialize__global_variable();" ," printf(\"Expected {42,3.14,'right'} but got {%i,%f,'%s',%i}\"," ," global_variable.a,global_variable.b,global_variable.c);" ," if( (global_variable.a != 42)" ," || (global_variable.b != 3.14f)" ," || (strcmp(global_variable.c,\"right\") != 0)" ," )" ," return -1;" ," else" ," return 0;" ,"}" ] in makeTestFromSource source -- @-node:gcross.20090709200011.28:with initializer -- @+node:gcross.20090709200011.29:without initializer ,testCase "without initializer" $ let initializer_source = render . pretty $ makeInitializer undefined undefined "global_variable" undefined [] Nothing source = unlines ["" ,"#include <stdio.h>" ,"" ,"typedef struct {" ," int a;" ," float b;" ," char *c;" ,"} global_variable_type;" ,"" ] ++ initializer_source ++ unlines ["" ,"int main() {" ," __initialize__global_variable();" ," return 0;" ,"}" ] in makeTestFromSource source -- @-node:gcross.20090709200011.29:without initializer -- @-others ] -- @-node:gcross.20090709200011.24:makeInitializer -- @+node:gcross.20090711085032.10:processStmt ,testGroup "processStmt" -- @ @+others -- @+node:gcross.20090711085032.13:single statement [testCase "single statement" $ makeProcessStmtTest undefined undefined undefined "return i;" "{ }" -- @-node:gcross.20090711085032.13:single statement -- @+node:gcross.20090711085032.16:multiple statements ,testCase "multiple statements" $ makeProcessStmtTest undefined undefined undefined "{ i = 1; ++i; }" "{ }" -- @-node:gcross.20090711085032.16:multiple statements -- @+node:gcross.20090711085032.17:non-static declarations ,testCase "non-static declarations" $ makeProcessStmtTest undefined undefined undefined "{ int i = 1; ++i; int j = i; }" "{ int i; int j; }" -- @-node:gcross.20090711085032.17:non-static declarations -- @+node:gcross.20090711085032.18:static declarations ,testCase "static declarations" $ makeProcessStmtTest "getPtr" undefined (Map.singleton "svar" (Allocation undefined 13)) "{ static int svar = 1; ++svar; int j = svar; }" "{ int svar = 1; memcpy(getPtr()+13,&svar,sizeof(svar)); int j; }" -- @-node:gcross.20090711085032.18:static declarations -- @+node:gcross.20090711085032.19:nesting ,testCase "nesting" $ makeProcessStmtTest "getPtr" undefined (Map.singleton "svar" (Allocation undefined 13)) "{ if (i == 1) {static int svar = 1; ++svar;} {for (i = 0; i < 2; ++i) { return 42; }} }" "{ { int svar = 1; memcpy(getPtr()+13,&svar,sizeof(svar)); } }" -- @-node:gcross.20090711085032.19:nesting -- @+node:gcross.20090718130736.31:aliased variable ,testCase "aliased variable" $ makeProcessStmtTest "getPtr" (Map.singleton "other" undefined) (Map.singleton "svar" (Allocation undefined 13)) "{ static int svar = &other; ++svar; }" "{ int svar = & (*__access__other()); memcpy(getPtr()+13,&svar,sizeof(svar)); }" -- @-node:gcross.20090718130736.31:aliased variable -- @-others ] -- @-node:gcross.20090711085032.10:processStmt -- @+node:gcross.20090711085032.23:processFunction ,testGroup "processFunction" -- @ @+others -- @+node:gcross.20090711085032.24:single statement [testCase "single statement" $ makeProcessFunctionTest undefined undefined undefined "const int f() { return i; }" "static void __initialize_statics_in__f() { }" -- @-node:gcross.20090711085032.24:single statement -- @+node:gcross.20090711085032.25:arguments ,testCase "arguments" $ makeProcessFunctionTest undefined undefined undefined "const int f(int a, restrict char* b, const short* c) { if (a == b) { return c; } else { ++(*b); }; }" "static void __initialize_statics_in__f() { int a; restrict char* b; const short* c; }" -- @-node:gcross.20090711085032.25:arguments -- @+node:gcross.20090711085032.26:arguments and statics ,testCase "arguments and statics" $ makeProcessFunctionTest "getPtr" undefined (Map.singleton "meaning_of_life" (Allocation undefined 24)) "static char* f(void ** data) { static int meaning_of_life = 42; }" "static void __initialize_statics_in__f() { void ** data; int meaning_of_life = 42; memcpy(getPtr()+24,&meaning_of_life,sizeof(meaning_of_life)); }" -- @-node:gcross.20090711085032.26:arguments and statics -- @+node:gcross.20090928192713.1549:embedded sizeof ,testCase "embedded sizeof" $ makeProcessFunctionTest "getPtr" (Map.singleton "global" (Allocation 42 undefined)) (Map.singleton "meaning_of_life" (Allocation undefined 24)) "static char* f(void ** data) { static int meaning_of_life = sizeof(global); }" "static void __initialize_statics_in__f() { void ** data; int meaning_of_life = 42; memcpy(getPtr()+24,&meaning_of_life,sizeof(meaning_of_life)); }" -- @-node:gcross.20090928192713.1549:embedded sizeof -- @-others ] -- @-node:gcross.20090711085032.23:processFunction -- @+node:gcross.20090711085032.29:processToplevelDeclaration ,testGroup "processToplevelDeclaration" -- @ @+others -- @+node:gcross.20090711085032.30:external declaration [testCase "external declaration" $ makeProcessToplevelDeclarationTest undefined (Map.singleton "ext_var" undefined) undefined "extern char var, ext_var;" "extern char var, *__access__ext_var();" -- @-node:gcross.20090711085032.30:external declaration -- @+node:gcross.20090711085032.35:function ,testCase "function" $ makeProcessToplevelDeclarationTest undefined (Map.singleton "c" undefined) Map.empty "static char* f() { strcpy(c,d); }" "static char* f() { strcpy(*__access__c(),d); }" -- @-node:gcross.20090711085032.35:function -- @+node:gcross.20090718130736.24:static forward function ,testCase "static forward function" $ makeProcessToplevelDeclarationTest undefined (Map.singleton "c" undefined) Map.empty "static char* f();" "static char* f();" -- @-node:gcross.20090718130736.24:static forward function -- @+node:gcross.20090711085032.34:global variable ,testCase "global variable" $ makeTestFromPrivatizedSource "getPtr" (Map.singleton "c" (Allocation undefined 3)) (Map.singleton "main" Map.empty) False (unlines ["#include <stdlib.h>" ,"#include <stdio.h>" ,"#include <string.h>" ,"" ,"char global_array[20];" ,"void* getPtr() { return global_array; }" ]) (unlines ["char c[7] = \"hello!\";" ,"" ,"int main() {" ," memset(global_array,0,sizeof(global_array));" ," __initialize__c();" ," if(strcmp(c,\"hello!\") != 0) {" ," printf(\"expected c='hello!', but saw '%s'\",c);" ," return -1;" ," }" ," if(strcmp(global_array+3,\"hello!\") != 0) {" ," printf(\"expected global_array+3='hello!', but saw '%s'\",c);" ," return -1;" ," }" ,"}" ]) -- @-node:gcross.20090711085032.34:global variable -- @+node:gcross.20090928192713.1547:global variable dependent on sizeof ,testCase "global variable dependent on sizeof" $ makeTestFromPrivatizedSource "getPtr" (Map.fromList [("c",Allocation 42 3),("d",Allocation undefined 20)]) (Map.singleton "main" Map.empty) False (unlines ["#include <stdlib.h>" ,"#include <stdio.h>" ,"#include <string.h>" ,"" ,"char global_array[100];" ,"void* getPtr() { return global_array; }" ]) (unlines ["char c[7] = \"hello!\";" ,"int d = sizeof(c);" ,"" ,"int main() {" ," memset(global_array,0,sizeof(global_array));" ," __initialize__c();" ," __initialize__d();" ," if(strcmp(global_array+3,\"hello!\") != 0) {" ," printf(\"expected global_array+3='hello!', but saw '%s'\",c);" ," return -1;" ," }" ," if(*(int*)(global_array+20) != 42) {" ," printf(\"expected global_array+20=42, but saw '%i'\",d);" ," return -1;" ," }" ,"}" ]) -- @-node:gcross.20090928192713.1547:global variable dependent on sizeof -- @-others ] -- @-node:gcross.20090711085032.29:processToplevelDeclaration -- @-others ] -- @-node:gcross.20090711085032.8:Initializer Construction -- @-others ] -- @-node:gcross.20090709200011.12:Tests -- @-others main = defaultMain tests -- @-node:gcross.20090709200011.8:@thin PrivatizationTests.hs -- @-leo
gcross/Privateer
tests/PrivatizationTests.hs
bsd-3-clause
33,639
0
25
10,365
3,980
2,157
1,823
508
2
-- | In addition to providing isomorphisms between GL and linear -- vector, point, and matrix types, this module also provides -- 'Uniform' instances for linear's matrix types. module Linear.OpenGL ( -- * Matrices m44GLmatrix -- * Points , vertex1P, vertex2P, vertex3P, vertex4P -- * Vectors , vector1V, vector2V, vector3V, vector4V ) where import Linear import Linear.Affine import Graphics.Rendering.OpenGL.GL import Control.Lens import Foreign hiding (unsafePerformIO) import System.IO.Unsafe (unsafePerformIO) import Linear.OpenGL.MatrixUniforms glMatrixToM44 :: MatrixComponent a => GLmatrix a -> IO (M44 a) glMatrixToM44 m = withMatrix m $ \order p -> traverse (traverse $ peekElemOff p) (go order) where go RowMajor = V4 (V4 0 1 2 3) (V4 4 5 6 7) (V4 8 9 10 11) (V4 12 13 14 15) go ColumnMajor = V4 (V4 0 4 8 12) (V4 1 5 9 13) (V4 2 6 10 14) (V4 3 7 11 15) {-# INLINABLE glMatrixToM44 #-} m44ToGLmatrix :: MatrixComponent a => M44 a -> IO (GLmatrix a) m44ToGLmatrix m = withNewMatrix RowMajor $ \p->poke (castPtr p) m {-# INLINABLE m44ToGLmatrix #-} -- | An isomorphism between GL and linear four-dimensional matrices m44GLmatrix :: MatrixComponent a => Iso' (M44 a) (GLmatrix a) m44GLmatrix = iso (unsafePerformIO . m44ToGLmatrix) (unsafePerformIO . glMatrixToM44) {-# INLINE m44GLmatrix #-} -- | An isomorphism between GL and linear one-dimensional points vertex1P :: Iso' (Point V1 a) (Vertex1 a) vertex1P = iso to from where to (P (V1 x)) = Vertex1 x from (Vertex1 x) = P (V1 x) {-# INLINABLE vertex1P #-} -- | An isomorphism between GL and linear two-dimensional points vertex2P :: Iso' (Point V2 a) (Vertex2 a) vertex2P = iso to from where to (P (V2 x y)) = Vertex2 x y from (Vertex2 x y) = P (V2 x y) {-# INLINABLE vertex2P #-} -- | An isomorphism between GL and linear three-dimensional points vertex3P :: Iso' (Point V3 a) (Vertex3 a) vertex3P = iso to from where to (P (V3 x y z)) = Vertex3 x y z from (Vertex3 x y z) = P (V3 x y z) {-# INLINABLE vertex3P #-} -- | An isomorphism between GL and linear four-dimensional points vertex4P :: Iso' (Point V4 a) (Vertex4 a) vertex4P = iso to from where to (P (V4 x y z w)) = Vertex4 x y z w from (Vertex4 x y z w) = P (V4 x y z w) {-# INLINABLE vertex4P #-} -- | An isomorphism between GL and linear one-dimensional vectors vector1V :: Iso' (V1 a) (Vector1 a) vector1V = iso to from where to (V1 x) = Vector1 x from (Vector1 x) = V1 x {-# INLINABLE vector1V #-} -- | An isomorphism between GL and linear two-dimensional vectors vector2V :: Iso' (V2 a) (Vector2 a) vector2V = iso to from where to (V2 x y) = Vector2 x y from (Vector2 x y) = V2 x y {-# INLINABLE vector2V #-} -- | An isomorphism between GL and linear three-dimensional vectors vector3V :: Iso' (V3 a) (Vector3 a) vector3V = iso to from where to (V3 x y z) = Vector3 x y z from (Vector3 x y z) = V3 x y z {-# INLINABLE vector3V #-} -- | An isomorphism between GL and linear four-dimensional vectors vector4V :: Iso' (V4 a) (Vector4 a) vector4V = iso to from where to (V4 x y z w) = Vector4 x y z w from (Vector4 x y z w) = V4 x y z w {-# INLINABLE vector4V #-}
bgamari/linear-opengl
src/Linear/OpenGL.hs
bsd-3-clause
3,324
0
11
818
1,118
573
545
62
2
module GraphRewrite.Internal.Test where import GraphRewrite.Internal.Rewrite import GraphRewrite.Internal.RewriteTypes hiding (PointedGraph) import System.IO.Unsafe --import Test.ChasingBottoms.TimeOut import Test.LazySmallCheck import qualified Data.IntMap as IM import Data.List import Data.Function {- Serial instance needed: Graph RewriteSystem -} --------------------------- helper functions infix 1 <=> (<=>) :: Bool -> Bool -> Bool (<=>) = (==) sameSet :: Ord a => [a] -> [a] -> Bool sameSet = (==) `on` sort {- timeOut2s :: a -> IO a timeOut2s x = do r <- timeOut 2 (return x) case r of NonTermination -> error "nontermination" Value x -> return x Exception e -> error (show e) -} --------------------------- Serial instances instance Serial Expr where series = cons1 SCons \/ cons2 SFun \/ cons1 SLit \/ cons1 SHole \/ cons1 (SRef . natToInt) \/ cons2 SApp newtype DataExpr = DataExpr { unDataExpr :: Expr } deriving Show instance Serial DataExpr where series = cons1 (DataExpr . SCons) \/ cons2 (\x -> DataExpr . SFun x) \/ cons1 (DataExpr . SLit) \/ cons1 (DataExpr . SRef . natToInt) \/ cons2 (\(DataExpr x) ys -> DataExpr $ SApp x $ map unDataExpr ys) newtype DataGraph = DataGraph Graph deriving Show instance Serial DataGraph where series = cons1 (DataGraph . IM.fromList . zip [0..] . map unDataExpr) data Nat = Zero | Succ Nat deriving (Eq, Ord, Show) instance Num Nat where fromInteger 0 = Zero fromInteger n | n < 0 = error "fromInteger/Num" fromInteger n = Succ (fromInteger (n-1)) (+) = undefined (*) = undefined abs = undefined signum = undefined instance Serial Nat where series = cons0 Zero \/ cons1 Succ natToInt :: Nat -> Int natToInt Zero = 0 natToInt (Succ n) = (1+) $! (natToInt n) --------------------------------- data PointedGraph = PGraph Expr Graph deriving (Show) instance Serial PointedGraph where series = cons1 mkDataGraph mkDataGraph :: Nat -> PointedGraph mkDataGraph n = PGraph (SLit "15") IM.empty --------------------------- auxiliary predicates and functions dataExpr :: Expr -> Bool dataExpr (SHole _) = False dataExpr (SApp e es) = dataExpr e && all dataExpr es dataExpr _ = True dataGraph :: Graph -> Bool dataGraph = all dataExpr . IM.elems ref :: Expr -> Bool ref (SRef _) = True ref _ = False collectRefs :: Expr -> [Int] collectRefs (SRef i) = [i] collectRefs (SApp e es) = collectRefs e ++ concatMap collectRefs es collectRefs _ = [] allReferenceDefined :: Expr -> Graph -> Bool allReferenceDefined e g = all (`IM.member` g) (collectRefs e ++ concatMap collectRefs (IM.elems g)) --------------------------- allTests :: IO () allTests = do let p (SCons _) = True p (SFun _ _) = True p (SLit _) = True p _ = False smallCheck 30 $ \(PGraph e g) -> -- unsafePerformIO $ timeOut2s $ not (ref e) && allReferenceDefined e g ==> p (fst (flattenSApp defaultRS e g)) {- sm $ interpreter "start = f True; f x = x" == "True" sm $ \s1 s2 s3 -> s1 /= s2 ==> freeVars (s1 ++ " = 3;" ++ s2 ++ " " ++ s3 ++ " = " ++ s3) `sameSet` [s1, s2] -}
zsol/visual-graphrewrite
GraphRewrite/Internal/Test.hs
bsd-3-clause
3,412
0
14
945
993
527
466
84
4
----------------------------------------------------------------------------- -- | -- Module : XMonad.Prompt.Directory -- Description : A directory prompt for XMonad. -- Copyright : (C) 2007 Andrea Rossato, David Roundy -- License : BSD3 -- -- Maintainer : -- Stability : unstable -- Portability : unportable -- -- A directory prompt for XMonad -- ----------------------------------------------------------------------------- module XMonad.Prompt.Directory ( -- * Usage -- $usage directoryPrompt, directoryMultipleModes, directoryMultipleModes', Dir ) where import XMonad.Prelude ( sort ) import XMonad import XMonad.Prompt import XMonad.Prompt.Shell ( compgenDirectories ) -- $usage -- For an example usage see "XMonad.Layout.WorkspaceDir" data Dir = Dir String ComplCaseSensitivity (String -> X ()) instance XPrompt Dir where showXPrompt (Dir x _ _) = x completionFunction (Dir _ csn _) = getDirCompl csn modeAction (Dir _ _ f) buf auto = let dir = if null auto then buf else auto in f dir directoryPrompt :: XPConfig -> String -> (String -> X ()) -> X () directoryPrompt c prom f = mkXPrompt (Dir prom csn f) c (getDirCompl csn) f where csn = complCaseSensitivity c -- | A @XPType@ entry suitable for using with @mkXPromptWithModes@. directoryMultipleModes :: String -- ^ Prompt. -> (String -> X ()) -- ^ Action. -> XPType directoryMultipleModes = directoryMultipleModes' CaseSensitive -- | Like @directoryMultipleModes@ with a parameter for completion case-sensitivity. directoryMultipleModes' :: ComplCaseSensitivity -- ^ Completion case sensitivity. -> String -- ^ Prompt. -> (String -> X ()) -- ^ Action. -> XPType directoryMultipleModes' csn p f = XPT (Dir p csn f) getDirCompl :: ComplCaseSensitivity -> String -> IO [String] getDirCompl csn s = sort . filter notboring . lines <$> compgenDirectories csn s notboring :: String -> Bool notboring ('.':'.':_) = True notboring ('.':_) = False notboring _ = True
xmonad/xmonad-contrib
XMonad/Prompt/Directory.hs
bsd-3-clause
2,329
0
11
691
462
251
211
34
1