code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
import Utils
import Data.Array
import Debug.Trace
nmax = 999999
arrMax = 6*(factorial 9)
factorialArr = array (0,9) $ zip [0..9] $ map factorial [0..9]
sumFactorialDigits n = sumFactDigArr ! n
sumFactDigArr = listArray (0,arrMax) $ (map factorial [0..9]) ++ [ sumFactorialDigits' i | i <- [10..arrMax] ]
where sumFactorialDigits' j = (factorialArr ! (j `mod` 10)) + (sumFactDigArr ! (j `div` 10))
--loopLength n | trace ("call: " ++ show n) False = undefined
loopLength n | n==40585 || n==145 || n==1 || n==2 = 1
| n==169 || n==363601 || n==1454 = 3
| n==871 || n==45361 || n==872 || n==45362 = 2
| otherwise = let next = sumFactDigArr ! n
in 1 + (nonRepLenArr ! next)
nonRepeatingLength n = (length nonRep) + (loopLength $ head rep)
where (nonRep, rep) = span (\m -> (loopLength m)==0) $ iterate sumFactorialDigits n
nonRepLenArr = listArray (1,arrMax) [ loopLength i | i <- [1..arrMax] ]
lens = map (nonRepLenArr !) [1..nmax]
answer = length $ filter (==60) lens
|
arekfu/project_euler
|
p0074/p0074.hs
|
mit
| 1,049 | 0 | 14 | 251 | 474 | 249 | 225 | 19 | 1 |
data Doggies a = Husky a | Mastiff a deriving (Eq, Show)
data DogueDeBordeaux doge = DogueDeBordeaux doge
|
candu/haskellbook
|
ch11/doggies.hs
|
mit
| 106 | 0 | 6 | 18 | 37 | 21 | 16 | 2 | 0 |
-- Copyright (c) 2011 Alexander Poluektov ([email protected])
--
-- Use, modification and distribution are subject to the MIT license
-- (See accompanying file MIT-LICENSE)
import Distribution.Simple
main = defaultMain
|
predee/heroes2
|
Setup.hs
|
mit
| 232 | 0 | 4 | 30 | 15 | 10 | 5 | 2 | 1 |
module Main where
import Graphics.Gloss
import Graphics.Gloss.Interface.Pure.Game
import Draw
import Game
import Debug.Trace
import Data.Maybe
main :: IO ()
main = do
let game = newGame
graphics <- loadGraphics
let window = InWindow "Chess in Haskell" (windowWidth, windowHeight) (0, 0)
play window black 10 game (drawGame graphics) handleEvent stepGame
handleEvent :: Event -> Game -> Game
handleEvent (EventKey (MouseButton LeftButton) Down _ pos) g = handleClick pos g
handleEvent _ g = g
handleClick :: Point -> Game -> Game
handleClick pos game = case posToSq pos of
Just sq -> move game sq
Nothing -> game
stepGame :: Float -> Game -> Game
stepGame _ g = g
|
mtak/chess-hs
|
src/Main.hs
|
mit
| 684 | 0 | 11 | 130 | 245 | 127 | 118 | 22 | 2 |
import Data.List
countBy f = length . filter f
isVowel = flip elem ['a', 'e', 'i', 'o', 'u']
dontContainBadWords str = not $ any (\x -> isInfixOf x str) ["ab", "cd", "pq", "xy"]
isNiceStringPt1 str =
3 <= countBy isVowel str && (any (\x->length x >= 2) $ group str) &&
dontContainBadWords str
isNiceStringPt2 str = containsPair str && containsTrio str
containsPair (x:y:xs) = if isInfixOf [x,y] xs then True else containsPair (y:xs)
containsPair _ = False
containsTrio (x:y:x':xs)
|x==x' = True
|otherwise = containsTrio (y:x':xs)
containsTrio _ = False
getAnswer predicate = print . countBy predicate . lines
main = do
file <- readFile "inputDay5.txt"
getAnswer isNiceStringPt1 file
getAnswer isNiceStringPt2 file
|
bruno-cadorette/AdventOfCode
|
Day 5/Day5.hs
|
mit
| 776 | 0 | 13 | 173 | 332 | 166 | 166 | 19 | 2 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
-- Run as: pv cur/sentences.tsv | ./countPairs
import Control.Exception (bracket)
import Control.Monad (liftM2)
--import qualified Data.Text as T
import qualified Data.Text.Lazy as T
--import qualified Data.Text.IO as T
import qualified Data.Text.Lazy.IO as T
import Data.Hashable (Hashable, hashWithSalt)
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HM
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import Data.List (foldl', sortBy)
import Data.Maybe (fromMaybe)
import Data.Ord (comparing)
import System.Directory (getHomeDirectory)
import System.FilePath ((</>))
import System.IO (hClose, hGetLine, hIsEOF, openFile, readFile, stdin, Handle, IOMode(ReadMode))
type I = Int
type L = T -- Lang abbrs are just used directly.
type T = T.Text
data P2 a = P2 {i1 :: !a, i2 :: !a} deriving (Eq, Ord, Show)
instance Hashable a => Hashable (P2 a) where
hashWithSalt s (P2 a b) = hashWithSalt s (a, b)
--type Count = HashMap (P2 L) [P2 I]
type Count = HashMap (P2 L) I
--type Count = I
{-# INLINE test #-}
--test = take 10000000
test = id
tInt :: T -> Int
tInt = read . T.unpack
accumCount :: IntMap L -> Count -> P2 I -> Count
accumCount idToLang !c (P2 id1 id2) =
--HM.insertWith (++) (P2 l1 l2) [P2 id1 id2] c
HM.insertWith (+) (P2 l1 l2) 1 c
--c + 1
where
l1 = fromMaybe "err" $ IM.lookup id1 idToLang
l2 = fromMaybe "err" $ IM.lookup id2 idToLang
{-
hReadLs :: Handle -> Int -> (T -> a) -> IO [a]
hReadLs _ 0 _ = return []
hReadLs h i f = do
e <- hIsEOF h
if e then return [] else liftM2 (:) (f <$> T.hGetLine h) (hReadLs h (i - 1))
fReadLs f = bracket (openFile f ReadMode) hClose hReadLs
-}
main :: IO ()
main = do
home <- getHomeDirectory
let curTatDir = home </> "data" </> "tatoeba" </> "cur"
idToLang <- IM.fromList .
map ((\(id:lang:_) -> (tInt id, lang)) . T.split (== '\t')) .
test . T.lines <$> T.readFile (curTatDir </> "sentences.tsv")
-- test <$> fReadLs "cur/sentences.tsv"
-- test <$> hReadLs stdin
putStrLn $ "Number of sentences: " ++ show (IM.size idToLang)
--putStrLn $ "Number of links: " ++ show c
putStrLn "Number of sentences from lang1 to lang2: "
c <- foldl' (accumCount idToLang) HM.empty .
--c <- foldl' (accumCount idToLang) 0 .
map ((\(id1:id2:_) -> P2 (tInt id1) (tInt id2)) . T.split (== '\t')) .
-- test <$> fReadLs "cur/links.tsv"
-- test <$> hReadLs stdin
test . T.lines <$> T.getContents
mapM_ (\(P2 l1 l2, i) ->
T.putStrLn $ l1 <> " " <> l2 <> " " <> T.pack (show i)
) . sortBy (comparing snd) $ HM.toList c
|
dancor/melang
|
src/Main/tat-count-pairs.hs
|
mit
| 2,731 | 0 | 19 | 603 | 790 | 438 | 352 | 52 | 1 |
-- | Integration of complex and real functions along straight lines
module Data.Complex.Integrate (
integrate
) where
-- We will work with complex numbers
import Data.Complex
-- | Integration of complex function using Simpson's rule
integrate :: (Fractional v) =>
(v -> v) -- ^ Function to be integrated
-> Integer -- ^ Number of discretization segments
-> v -- ^ Lower limit of the integration, and it's complex number
-> v -- ^ Upper limit of the integration, and it's complex number, too
-> v -- ^ Integration result
integrate f n a b =
(f a + (4 * f_o) + (2 * f_e) + f b) * h / 3
where
h = getQuantizer a b n
f_o = sum $ map (f . (+ a) . (* h) . fromInteger) [nn | nn <- [1..(n-1)], odd nn]
f_e = sum $ map (f . (+ a) . (* h) . fromInteger) [nn | nn <- [2..(n-2)], even nn]
-- Yes, I know that function and data in maps should be refactored out, but every time I'm doing this, I am became stunned, because the integrate itself is losing clarity.
-- | Get step between <a> and <b> given number <n> of steps
getQuantizer :: (Fractional a) => a -> a -> Integer -> a
getQuantizer a b n = (b - a) / fromInteger n
|
hijarian/complex-integrate
|
Data/Complex/Integrate.hs
|
cc0-1.0
| 1,210 | 0 | 14 | 327 | 321 | 178 | 143 | 16 | 1 |
choose n k = product [k+1..n] `div` product [1..n-k]
solution = choose 40 20
main = print solution
|
drcabana/euler-fp
|
source/hs/P15.hs
|
epl-1.0
| 101 | 0 | 8 | 20 | 59 | 30 | 29 | 3 | 1 |
{- |
Module : Solver
Description : Solver
Copyright : (c) Frédéric BISSON, 2015
License : GPL-3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
The Solver can take a 'Grid' and a 'Dictionary' and searches for all 'DictWord's
that can be constructed in the 'Grid' that appears in the 'Dictionary'.
-}
module Solver.Score (letterScores, lengthScores, evalScore) where
import Solver.Types ( Letter (..), Multiplier (..), Cell (..)
, Score, Grid, LetterScores, Path
)
import Solver.Path (pathToCells)
import Data.Array
{- |
This function returns an 'Array' containing the 'Score's for each letter. The
'Array' is indexed by the 'Letter'.
-}
letterScores :: LetterScores
letterScores = array
(La, Lz)
(concat
[ [ (l, 1) | l <- [La, Le, Li, Ll, Ln, Lo, Lr, Ls, Lt, Lu] ]
, [ (l, 2) | l <- [Ld, Lg, Lm] ]
, [ (l, 3) | l <- [Lb, Lc, Lp] ]
, [ (l, 4) | l <- [Lf, Lh, Lv] ]
, [ (l, 8) | l <- [Lj, Lq] ]
, [ (l, 10) | l <- [Lk, Lw, Lx, Ly, Lz] ]
]
)
{- |
This function returns an additional length 'Score' based on the length of a
word.
-}
lengthScores :: Int -> Score
lengthScores 15 = 25
lengthScores 14 = 25
lengthScores 13 = 25
lengthScores 12 = 25
lengthScores 11 = 25
lengthScores 10 = 25
lengthScores 9 = 25
lengthScores 8 = 20
lengthScores 7 = 15
lengthScores 6 = 10
lengthScores 5 = 5
lengthScores _ = 0
{- |
Calculates an intermediate score in the form of a tuple ('Score', 'Int') where
the first is the current score and the second the current word multiplier.
-}
plus :: (Score, Int) -> Cell -> (Score, Int)
plus (s, m) cell = (s + (letterScores ! letter cell) * mletter, m * mword)
where (mletter, mword) = case multiplier cell of
MultiplyLetter m' -> (m', 1)
MultiplyWord m' -> (1, m')
{- |
Calculates the 'Score' from a 'Path' in a 'Grid'.
-}
evalScore :: Grid -> Path -> Score
evalScore grid path = score * mult + (lengthScores . length) path
where (score, mult) = (foldl plus (0, 1) . pathToCells grid) path
|
Zigazou/RuzzSolver
|
src/Solver/Score.hs
|
gpl-3.0
| 2,263 | 0 | 12 | 691 | 606 | 351 | 255 | 36 | 2 |
{-# LANGUAGE EmptyDataDecls,
FlexibleContexts,
FlexibleInstances,
GADTs,
GeneralizedNewtypeDeriving,
MultiParamTypeClasses,
OverloadedStrings,
DeriveGeneric,
QuasiQuotes,
TemplateHaskell,
TypeFamilies,
DeriveGeneric #-}
{-|
Description: The database schema (and some helpers).
This module defines the database schema. It uses Template Haskell to also
create new types for these values so that they can be used in the rest of
the application.
Though types and typeclass instances are created automatically, we currently
have a few manually-generated spots to clean up. This should be rather
straightforward.
-}
module Database.Tables where
import Database.Persist.TH
import Database.DataType
import qualified Data.Text as T
import qualified Data.Vector as V
import Data.Aeson
import GHC.Generics
-- | A data type representing a list of times for a course.
data Time = Time { timeField :: [Double] } deriving (Show, Read, Eq)
derivePersistField "Time"
-- | A two-dimensional point.
type Point = (Double, Double)
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Courses json
code T.Text
title T.Text Maybe
description T.Text Maybe
manualTutorialEnrolment Bool Maybe
manualPracticalEnrolment Bool Maybe
prereqs T.Text Maybe
exclusions T.Text Maybe
breadth T.Text Maybe
distribution T.Text Maybe
prereqString T.Text Maybe
coreqs T.Text Maybe
videoUrls [T.Text]
deriving Show
Lectures
code T.Text
session T.Text
section T.Text
times [Time]
capacity Int
instructor T.Text
enrolled Int
waitlist Int
extra Int
timeStr T.Text
deriving Show
Tutorials
code T.Text
section T.Text Maybe
session T.Text
times [Time]
timeStr T.Text
deriving Show
Breadth
bId Int
description String
deriving Show
Distribution
dId Int
description String
deriving Show
Graph json
title String
deriving Show
Text
graph GraphId
rId String
pos Point
text String
align String
fill String
deriving Show
Shape
graph GraphId
id_ String
pos Point
width Double
height Double
fill String
stroke String
text [Text]
tolerance Double
type_ ShapeType
Path
graph GraphId
id_ String
points [Point]
fill String
stroke String
isRegion Bool
source String
target String
deriving Show
FacebookTest
fId String
testString String
deriving Show
|]
-- ** TODO: Remove these extra types and class instances
-- | A Lecture.
data Lecture =
Lecture { extra :: Int,
section :: T.Text,
cap :: Int,
time_str :: T.Text,
time :: [[Double]],
instructor :: T.Text,
enrol :: Maybe Int,
wait :: Maybe Int
} deriving Show
-- | A Tutorial.
data Tutorial =
Tutorial { tutorialSection :: Maybe T.Text,
times :: [[Double]],
timeStr :: T.Text
} deriving Show
-- | A Session.
data Session =
Session { lectures :: [Lecture],
tutorials :: [Tutorial]
} deriving (Show, Generic)
-- | A Course.
-- each element of prereqs can be one of three things:
--
-- * a one-element list containing a course code
-- * a list starting with "and", and 2 or more course codes
-- * a list starting with "or", and 2 or more course codes
data Course =
Course { breadth :: Maybe T.Text,
description :: Maybe T.Text,
title :: Maybe T.Text,
prereqString :: Maybe T.Text,
fallSession :: Maybe Session,
springSession :: Maybe Session,
yearSession :: Maybe Session,
name :: !T.Text,
exclusions :: Maybe T.Text,
manualTutorialEnrolment :: Maybe Bool,
manualPracticalEnrolment :: Maybe Bool,
distribution :: Maybe T.Text,
prereqs :: Maybe T.Text,
coreqs :: Maybe T.Text,
videoUrls :: [T.Text]
} deriving (Show, Generic)
instance ToJSON Course
instance ToJSON Session
instance ToJSON Lecture where
toJSON (Lecture lectureExtra lectureSection lectureCap lectureTimeStr lectureTime lectureInstructor lectureEnrol lectureWait)
= object ["extra" .= lectureExtra,
"section" .= lectureSection,
"cap" .= lectureCap,
"time_str" .= lectureTimeStr,
"time" .= map convertTimeToString lectureTime,
"instructor" .= lectureInstructor,
"enrol" .= lectureEnrol,
"wait" .= lectureWait
]
instance ToJSON Tutorial where
toJSON (Tutorial Nothing tutorialTimes tutorialTimeStr) =
Array $ V.fromList [toJSON (map convertTimeToString tutorialTimes), toJSON tutorialTimeStr]
toJSON (Tutorial (Just value) tutorialTimes tutorialTimeStr) =
Array $ V.fromList [toJSON value, toJSON (map convertTimeToString tutorialTimes), toJSON tutorialTimeStr]
-- | Converts a Double to a T.Text.
-- This removes the period from the double, as the JavaScript code,
-- uses the output in an element's ID, which is then later used in
-- jQuery. @.@ is a jQuery meta-character, and must be removed from the ID.
convertTimeToString :: [Double] -> [T.Text]
convertTimeToString [day, timeNum] =
[T.pack . show . floor $ day,
T.replace "." "-" . T.pack . show $ timeNum]
|
arkon/courseography
|
hs/Database/Tables.hs
|
gpl-3.0
| 5,664 | 0 | 11 | 1,696 | 768 | 436 | 332 | 82 | 1 |
{-# LANGUAGE NoImplicitPrelude, LambdaCase, GeneralizedNewtypeDeriving, TemplateHaskell, QuasiQuotes, OverloadedStrings, PolymorphicComponents #-}
-- | Compile Lamdu vals to Javascript
module Lamdu.Eval.JS.Compiler
( Actions(..)
, ValId(..)
, compile, Mode(..), loggingEnabled
) where
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Control.Lens.Tuple
import Control.Monad (void)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.RWS.Strict (RWST(..))
import qualified Control.Monad.Trans.RWS.Strict as RWS
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base16 as Hex
import qualified Data.ByteString.UTF8 as UTF8
import qualified Data.Char as Char
import Data.Default () -- instances
import Data.List (isPrefixOf)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.UUID.Types (UUID)
import qualified Data.UUID.Utils as UUIDUtils
import qualified Lamdu.Builtins.Anchors as Builtins
import qualified Lamdu.Builtins.PrimVal as PrimVal
import Lamdu.Calc.Identifier (identHex)
import qualified Lamdu.Calc.Type as T
import qualified Lamdu.Calc.Val as V
import Lamdu.Calc.Val.Annotated (Val(..))
import qualified Lamdu.Calc.Val.Annotated as Val
import qualified Lamdu.Compiler.Flatten as Flatten
import qualified Lamdu.Data.Definition as Definition
import qualified Lamdu.Expr.Lens as ExprLens
import qualified Lamdu.Expr.UniqueId as UniqueId
import qualified Language.ECMAScript3.PrettyPrint as JSPP
import qualified Language.ECMAScript3.Syntax as JSS
import qualified Language.ECMAScript3.Syntax.CodeGen as JS
import Language.ECMAScript3.Syntax.QuasiQuote (jsstmt)
import Numeric.Lens (hex)
import Prelude.Compat
import qualified Text.PrettyPrint.Leijen as Pretty
newtype ValId = ValId UUID
data Mode = FastSilent | SlowLogging LoggingInfo
deriving Show
data Actions m = Actions
{ readAssocName :: UUID -> m String
, readGlobal :: V.Var -> m (Definition.Body (Val ValId))
, output :: String -> m ()
, loggingMode :: Mode
}
type LocalVarName = JSS.Id ()
type GlobalVarName = JSS.Id ()
newtype LoggingInfo = LoggingInfo
{ _liScopeDepth :: Int
} deriving Show
Lens.makeLenses ''LoggingInfo
data Env m = Env
{ _envActions :: Actions m
, _envLocals :: Map V.Var LocalVarName
, _envMode :: Mode
}
Lens.makeLenses ''Env
data State = State
{ _freshId :: Int
, _names :: Map String (Map UUID String)
, _compiled :: Map V.Var GlobalVarName
}
Lens.makeLenses ''State
data LogUsed
= LogUnused
| LogUsed
deriving (Eq, Ord, Show)
instance Monoid LogUsed where
mempty = LogUnused
mappend LogUsed _ = LogUsed
mappend _ LogUsed = LogUsed
mappend _ _ = LogUnused
newtype M m a = M { unM :: RWST (Env m) LogUsed State m a }
deriving (Functor, Applicative, Monad)
infixl 4 $.
($.) :: JSS.Expression () -> JSS.Id () -> JSS.Expression ()
($.) = JS.dot
infixl 3 $$
($$) :: JSS.Expression () -> JSS.Expression () -> JSS.Expression ()
f $$ x = f `JS.call` [x]
pp :: JSS.Statement () -> String
pp = (`Pretty.displayS`"") . Pretty.renderPretty 1.0 90 . JSPP.prettyPrint
performAction :: Monad m => (Actions m -> m a) -> M m a
performAction f = RWS.asks (f . _envActions) >>= lift & M
ppOut :: Monad m => JSS.Statement () -> M m ()
ppOut stmt = performAction (`output` pp stmt)
-- Multiple vars using a single "var" is badly formatted and generally
-- less readable than a vardecl for each:
varinit :: JSS.Id () -> JSS.Expression () -> JSS.Statement ()
varinit ident expr = JS.vardecls [JS.varinit ident expr]
scopeIdent :: Int -> JSS.Id ()
scopeIdent depth = "scopeId_" ++ show depth & JS.ident
declLog :: Int -> JSS.Statement ()
declLog depth =
varinit "log" $
JS.lambda ["exprId", "result"]
[ (JS.var "rts" $. "logResult") `JS.call`
[ JS.var (scopeIdent depth)
, JS.var "exprId"
, JS.var "result"
] & JS.returns
]
-- | Taken from http://www.ecma-international.org/ecma-262/6.0/#sec-keywords
jsReservedKeywords :: Set String
jsReservedKeywords =
Set.fromList
[ "break" , "do" , "in" , "typeof"
, "case" , "else" , "instanceof", "var"
, "catch" , "export" , "new" , "void"
, "class" , "extends" , "return" , "while"
, "const" , "finally" , "super" , "with"
, "continue" , "for" , "switch" , "yield"
, "debugger" , "function" , "this" , "default"
, "if" , "throw" , "delete" , "import"
, "try" , "let" , "static" , "enum"
, "await" , "implements", "package" , "protected"
, "interface", "private" , "public"
]
jsReservedNamespace :: Set String
jsReservedNamespace =
Set.fromList
[ "x", "repl"
, "Object", "console", "repl"
, "log", "scopeCounter", "rts"
]
jsAllReserved :: Set String
jsAllReserved = jsReservedNamespace `mappend` jsReservedKeywords
isReservedName :: String -> Bool
isReservedName name =
name `Set.member` jsAllReserved
|| any (`isPrefixOf` name)
[ "global_"
, "local_"
, "scopeId_"
]
topLevelDecls :: [JSS.Statement ()]
topLevelDecls =
( [ [jsstmt|"use strict";|]
, [jsstmt|var scopeId_0 = 0;|]
, [jsstmt|var scopeCounter = 1;|]
, [jsstmt|var rts = require('rts.js');|]
] <&> void
) ++
[ declLog 0
]
loggingEnabled :: Mode
loggingEnabled = SlowLogging LoggingInfo { _liScopeDepth = 0 }
compile :: Monad m => Actions m -> Val ValId -> m ()
compile actions val = compileVal val & run actions
run :: Monad m => Actions m -> M m CodeGen -> m ()
run actions act =
runRWST
(traverse ppOut topLevelDecls
>> act
<&> codeGenExpression
<&> JS.call (JS.var "rts" $. "logRepl") . (:[])
<&> JS.expr
>>= ppOut & unM)
Env
{ _envActions = actions
, _envLocals = mempty
, _envMode = loggingMode actions
}
State
{ _freshId = 0
, _names = mempty
, _compiled = mempty
}
<&> (^. _1)
-- | Reset reader/writer components of RWS for a new global compilation context
resetRW :: Monad m => M m a -> M m a
resetRW (M act) =
act
& RWS.censor (const LogUnused)
& RWS.local (envLocals .~ mempty)
& RWS.local (\x -> x & envMode .~ loggingMode (x ^. envActions))
& M
freshName :: Monad m => String -> M m String
freshName prefix =
do
newId <- freshId <+= 1
prefix ++ show newId & return
& M
avoidReservedNames :: String -> String
avoidReservedNames name
| isReservedName name = "_" ++ name
| otherwise = name
escapeName :: String -> String
escapeName (d:xs)
| Char.isDigit d = '_' : d : replaceSpecialChars xs
escapeName xs = replaceSpecialChars xs
replaceSpecialChars :: String -> String
replaceSpecialChars = concatMap replaceSpecial
where
replaceSpecial x
| Char.isAlphaNum x = [x]
| x == '_' = "__"
| otherwise = '_' : ((hex #) . Char.ord) x ++ "_"
readName :: (UniqueId.ToUUID a, Monad m) => a -> M m String -> M m String
readName g act =
do
name <-
performAction (`readAssocName` uuid)
<&> avoidReservedNames
<&> escapeName
>>= \case
"" -> act
name -> return name
names . Lens.at name %%= \case
Nothing -> (name, Just (Map.singleton uuid name))
Just uuidMap ->
uuidMap
& Lens.at uuid %%~
\case
Nothing -> (newName, Just newName)
where
newName = name ++ show (Map.size uuidMap)
Just oldName -> (oldName, Just oldName)
<&> Just
& M
where
uuid = UniqueId.toUUID g
freshStoredName :: (Monad m, UniqueId.ToUUID a) => a -> String -> M m String
freshStoredName g prefix = readName g (freshName prefix)
tagString :: Monad m => T.Tag -> M m String
tagString tag@(T.Tag ident) = readName tag ("tag" ++ identHex ident & return)
tagIdent :: Monad m => T.Tag -> M m (JSS.Id ())
tagIdent = fmap JS.ident . tagString
local :: Monad m => (Env m -> Env m) -> M m a -> M m a
local f (M act) = M (RWS.local f act)
withLocalVar :: Monad m => V.Var -> M m a -> M m (LocalVarName, a)
withLocalVar v act =
do
varName <- freshStoredName v "local_" <&> JS.ident
res <- local (envLocals . Lens.at v ?~ varName) act
return (varName, res)
compileGlobal :: Monad m => V.Var -> M m (JSS.Expression ())
compileGlobal globalId =
performAction (`readGlobal` globalId) >>=
\case
Definition.BodyBuiltin (Definition.Builtin ffiName _scheme) ->
ffiCompile ffiName & return
Definition.BodyExpr (Definition.Expr val _type _usedDefs) ->
compileVal val <&> codeGenExpression
& resetRW
compileGlobalVar :: Monad m => V.Var -> M m CodeGen
compileGlobalVar var =
Lens.use (compiled . Lens.at var) & M
>>= maybe newGlobal return
<&> JS.var
<&> codeGenFromExpr
where
newGlobal =
do
varName <- freshStoredName var "global_" <&> JS.ident
compiled . Lens.at var ?= varName & M
compileGlobal var
<&> varinit varName
>>= ppOut
return varName
compileLocalVar :: JSS.Id () -> CodeGen
compileLocalVar = codeGenFromExpr . JS.var
compileVar :: Monad m => V.Var -> M m CodeGen
compileVar v =
Lens.view (envLocals . Lens.at v) & M
>>= maybe (compileGlobalVar v) (return . compileLocalVar)
data CodeGen = CodeGen
{ codeGenLamStmts :: [JSS.Statement ()]
, codeGenExpression :: JSS.Expression ()
}
unitRedex :: [JSS.Statement ()] -> JSS.Expression ()
unitRedex stmts = JS.lambda [] stmts `JS.call` []
throwStr :: String -> CodeGen
throwStr str =
go [JS.throw (JS.string str)]
where
go stmts =
CodeGen
{ codeGenLamStmts = stmts
, codeGenExpression = unitRedex stmts
}
codeGenFromLamStmts :: [JSS.Statement ()] -> CodeGen
codeGenFromLamStmts stmts =
CodeGen
{ codeGenLamStmts = stmts
, codeGenExpression = JS.lambda [] stmts `JS.call` []
}
codeGenFromExpr :: JSS.Expression () -> CodeGen
codeGenFromExpr expr =
CodeGen
{ codeGenLamStmts = [JS.returns expr]
, codeGenExpression = expr
}
lam ::
Monad m => String ->
(JSS.Expression () -> M m [JSS.Statement ()]) ->
M m (JSS.Expression ())
lam prefix code =
do
var <- freshName prefix <&> JS.ident
code (JS.var var) <&> JS.lambda [var]
inject :: JSS.Expression () -> JSS.Expression () -> JSS.Expression ()
inject tagStr dat' =
JS.object
[ (JS.propId "tag", tagStr)
, (JS.propId "data", dat')
]
ffiCompile :: Definition.FFIName -> JSS.Expression ()
ffiCompile (Definition.FFIName modul funcName) =
foldl ($.) (JS.var "rts" $. "builtins") (modul <&> JS.ident)
`JS.brack` JS.string funcName
compileLiteral :: V.PrimVal -> CodeGen
compileLiteral literal =
case PrimVal.toKnown literal of
PrimVal.Bytes bytes ->
JS.var "rts" $. "bytes" $$ JS.array ints & codeGenFromExpr
where
ints = [JS.int (fromIntegral byte) | byte <- BS.unpack bytes]
PrimVal.Float num -> JS.number num & codeGenFromExpr
compileRecExtend :: Monad m => V.RecExtend (Val ValId) -> M m CodeGen
compileRecExtend x =
do
Flatten.Composite tags mRest <- Flatten.recExtend x & Lens.traverse compileVal
strTags <-
Map.toList tags
<&> _2 %~ codeGenExpression
& Lens.traversed . _1 %%~ tagString
case mRest of
Nothing ->
strTags <&> _1 %~ JS.propId . JS.ident
& JS.object & codeGenFromExpr
Just rest ->
CodeGen
{ codeGenLamStmts = stmts
, codeGenExpression = unitRedex stmts
}
where
stmts =
varinit "rest"
(JS.var "Object" $. "create" $$ codeGenExpression rest)
: ( strTags
<&> _1 %~ JS.ldot (JS.var "rest")
<&> uncurry JS.assign
<&> JS.expr )
++ [JS.var "rest" & JS.returns]
& return
compileInject :: Monad m => V.Inject (Val ValId) -> M m CodeGen
compileInject (V.Inject tag dat) =
do
tagStr <- tagString tag <&> JS.string
dat' <- compileVal dat
inject tagStr (codeGenExpression dat') & codeGenFromExpr & return
compileCase :: Monad m => V.Case (Val ValId) -> M m CodeGen
compileCase = fmap codeGenFromExpr . lam "x" . compileCaseOnVar
compileCaseOnVar ::
Monad m => V.Case (Val ValId) -> JSS.Expression () -> M m [JSS.Statement ()]
compileCaseOnVar x scrutineeVar =
do
tagsStr <- Map.toList tags & Lens.traverse . _1 %%~ tagString
cases <- traverse makeCase tagsStr
defaultCase <-
case mRestHandler of
Nothing ->
return [JS.throw (JS.string "Unhandled case? This is a type error!")]
Just restHandler ->
compileAppliedFunc restHandler scrutineeVar
<&> codeGenLamStmts
<&> JS.defaultc
return [JS.switch (scrutineeVar $. "tag") (cases ++ [defaultCase])]
where
Flatten.Composite tags mRestHandler = Flatten.case_ x
makeCase (tagStr, handler) =
compileAppliedFunc handler (scrutineeVar $. "data")
<&> codeGenLamStmts
<&> JS.casee (JS.string tagStr)
compileGetField :: Monad m => V.GetField (Val ValId) -> M m CodeGen
compileGetField (V.GetField record tag) =
do
tagId <- tagIdent tag
compileVal record
<&> codeGenExpression <&> (`JS.dot` tagId)
<&> codeGenFromExpr
declMyScopeDepth :: Int -> JSS.Statement ()
declMyScopeDepth depth =
varinit (scopeIdent depth) $
JS.uassign JSS.PostfixInc "scopeCounter"
jsValId :: ValId -> JSS.Expression ()
jsValId (ValId uuid) = (JS.string . UTF8.toString . Hex.encode . UUIDUtils.toSBS16) uuid
callLogNewScope :: Int -> Int -> ValId -> JSS.Expression () -> JSS.Statement ()
callLogNewScope parentDepth myDepth lamValId argVal =
(JS.var "rts" $. "logNewScope") `JS.call`
[ JS.var (scopeIdent parentDepth)
, JS.var (scopeIdent myDepth)
, jsValId lamValId
, argVal
] & JS.expr
slowLoggingLambdaPrefix ::
LogUsed -> Int -> ValId -> JSS.Expression () -> [JSS.Statement ()]
slowLoggingLambdaPrefix logUsed parentScopeDepth lamValId argVal =
[ declMyScopeDepth myScopeDepth
, callLogNewScope parentScopeDepth myScopeDepth lamValId argVal
] ++
[ declLog myScopeDepth | LogUsed <- [logUsed] ]
where
myScopeDepth = parentScopeDepth + 1
listenNoTellLogUsed :: Monad m => M m a -> M m (a, LogUsed)
listenNoTellLogUsed act =
act & unM & RWS.listen & RWS.censor (const LogUnused) & M
compileLambda :: Monad m => V.Lam (Val ValId) -> ValId -> M m CodeGen
compileLambda (V.Lam v res) valId =
Lens.view envMode & M
>>= \case
FastSilent -> compileRes <&> mkLambda
SlowLogging loggingInfo ->
do
((varName, lamStmts), logUsed) <-
compileRes
& local
(envMode .~ SlowLogging (loggingInfo & liScopeDepth .~ 1 + parentScopeDepth))
& listenNoTellLogUsed
let stmts =
slowLoggingLambdaPrefix logUsed parentScopeDepth valId
(JS.var varName)
fastLam <- compileRes & local (envMode .~ FastSilent) <&> mkLambda
(JS.var "rts" $. "wrap") `JS.call`
[fastLam, JS.lambda [varName] (stmts ++ lamStmts)] & return
where
parentScopeDepth = loggingInfo ^. liScopeDepth
<&> codeGenFromExpr
where
mkLambda (varId, lamStmts) = JS.lambda [varId] lamStmts
compileRes = compileVal res <&> codeGenLamStmts & withLocalVar v
compileApply :: Monad m => V.Apply (Val ValId) -> M m CodeGen
compileApply (V.Apply func arg) =
do
arg' <- compileVal arg <&> codeGenExpression
compileAppliedFunc func arg'
maybeLogSubexprResult :: Monad m => ValId -> CodeGen -> M m CodeGen
maybeLogSubexprResult valId codeGen =
Lens.view envMode & M
>>= \case
FastSilent -> return codeGen
SlowLogging _ -> logSubexprResult valId codeGen
logSubexprResult :: Monad m => ValId -> CodeGen -> M m CodeGen
logSubexprResult valId codeGen =
do
RWS.tell LogUsed & M
JS.var "log" `JS.call` [jsValId valId, codeGenExpression codeGen]
& codeGenFromExpr
& return
compileAppliedFunc :: Monad m => Val ValId -> JSS.Expression () -> M m CodeGen
compileAppliedFunc func arg' =
do
mode <- Lens.view envMode & M
case (func ^. Val.body, mode) of
(V.BCase case_, FastSilent) ->
compileCaseOnVar case_ (JS.var "x")
<&> (varinit "x" arg' :)
<&> codeGenFromLamStmts
(V.BLam (V.Lam v res), FastSilent) ->
do
(vId, lamStmts) <- compileVal res <&> codeGenLamStmts & withLocalVar v
return CodeGen
{ codeGenLamStmts = varinit vId arg' : lamStmts
, codeGenExpression =
-- Can't really optimize a redex in expr
-- context, as at least 1 redex must be paid
JS.lambda [vId] lamStmts $$ arg'
}
_ ->
do
func' <- compileVal func <&> codeGenExpression
func' $$ arg' & codeGenFromExpr & return
compileLeaf :: Monad m => V.Leaf -> ValId -> M m CodeGen
compileLeaf leaf valId =
case leaf of
V.LHole -> throwStr "Reached hole!" & return
V.LRecEmpty -> JS.object [] & codeGenFromExpr & return
V.LAbsurd -> throwStr "Reached absurd!" & return
V.LVar var -> compileVar var >>= maybeLogSubexprResult valId
V.LLiteral literal -> compileLiteral literal & return
compileToNom :: Monad m => V.Nom (Val ValId) -> ValId -> M m CodeGen
compileToNom (V.Nom tId val) valId =
case val ^? ExprLens.valLiteral <&> PrimVal.toKnown of
Just (PrimVal.Bytes bytes) | tId == Builtins.textTid ->
JS.var "rts" $. "bytesFromString" $$ JS.string (UTF8.toString bytes)
& codeGenFromExpr & return
_ -> compileVal val >>= maybeLogSubexprResult valId
compileVal :: Monad m => Val ValId -> M m CodeGen
compileVal (Val valId body) =
case body of
V.BLeaf leaf -> compileLeaf leaf valId
V.BApp x -> compileApply x >>= maybeLog
V.BGetField x -> compileGetField x >>= maybeLog
V.BLam x -> compileLambda x valId
V.BInject x -> compileInject x >>= maybeLog
V.BRecExtend x -> compileRecExtend x
V.BCase x -> compileCase x
V.BFromNom (V.Nom _tId val) -> compileVal val >>= maybeLog
V.BToNom x -> compileToNom x valId
where
maybeLog = maybeLogSubexprResult valId
|
da-x/lamdu
|
Lamdu/Eval/JS/Compiler.hs
|
gpl-3.0
| 19,621 | 0 | 23 | 5,733 | 6,159 | 3,180 | 2,979 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{- |
Module : Types.hs
Description : Central data type and Yesod typeclass instances.
Copyright : (c) 2011 Cedric Staub
License : GPL-3
Maintainer : Simon Meier <[email protected]>
Stability : experimental
Portability : non-portable
-}
module Web.Types
( WebUI(..)
, Route (..)
, resourcesWebUI
, TheoryInfo(..)
, DiffTheoryInfo(..)
, EitherTheoryInfo(..)
, isTheoryInfo
, isDiffTheoryInfo
, getEitherTheoryName
, getEitherTheoryTime
, getEitherTheoryPrimary
, getEitherTheoryOrigin
, getEitherTheoryIndex
, TheoryPath(..)
, DiffTheoryPath(..)
, TheoryOrigin(..)
, JsonResponse(..)
, TheoryIdx
, TheoryMap
, ThreadMap
-- , GenericHandler
, Handler
-- , URL rendering function
, RenderUrl
-- , GenericWidget
, Widget
-- Image rendering
, ImageFormat(..)
, imageFormatMIME
)
where
-- import Control.Applicative
import Control.Concurrent
import Data.Label
import qualified Data.Map as M
import Data.Maybe (listToMaybe)
-- import Data.Monoid (mconcat)
import Data.Ord (comparing)
import qualified Data.Text as T
import Data.Time.LocalTime
import qualified Data.Binary as Bin
import Data.Binary.Orphans()
import Control.DeepSeq
import Control.Monad
-- import Control.Monad
import GHC.Generics (Generic)
import Text.Hamlet
import Yesod.Core
import Yesod.Static
import Theory
------------------------------------------------------------------------------
-- Types
------------------------------------------------------------------------------
-- | Type synonym for a generic handler inside our site.
-- type GenericHandler m = Handler WebUI WebUI m
-- type Handler a = Handler WebUI WebUI a
-- | Type synonym for a generic widget inside our site.
-- type GenericWidget m = Widget WebUI (GenericHandler m)
-- type Widget a = Widget WebUI WebUI a
-- | Type synonym representing a numeric index for a theory.
type TheoryIdx = Int
-- | Type synonym representing a map of theories.
type TheoryMap = M.Map TheoryIdx (EitherTheoryInfo)
-- | Type synonym representing a map of threads.
type ThreadMap = M.Map T.Text ThreadId
-- | The image format used for rendering graphs.
data ImageFormat = PNG | SVG
instance Show ImageFormat where
show PNG = "png"
show SVG = "svg"
-- | convert image format to MIME type.
imageFormatMIME :: ImageFormat -> String
imageFormatMIME PNG = "image/png"
imageFormatMIME SVG = "image/svg+xml"
-- | The so-called site argument for our application, which can hold various
-- information that can use to keep info that needs to be available to the
-- handler functions.
data WebUI = WebUI
{ getStatic :: Static
-- ^ Settings for static file serving.
, cacheDir :: FilePath
-- ^ The caching directory (for storing rendered graphs).
, workDir :: FilePath
-- ^ The working directory (for storing/loading theories).
-- , parseThy :: MonadIO m => String -> GenericHandler m ClosedTheory
, parseThy :: String -> IO (Either String (ClosedTheory))
-- ^ Close an open theory according to command-line arguments.
, diffParseThy :: String -> IO (Either String (ClosedDiffTheory))
-- ^ Close an open theory according to command-line arguments.
, thyWf :: String -> IO String
-- ^ Report on the wellformedness of a theory according to command-line arguments.
, theoryVar :: MVar (TheoryMap)
-- ^ MVar that holds the theory map
, threadVar :: MVar ThreadMap
-- ^ MVar that holds the thread map
, autosaveProofstate :: Bool
-- ^ Automatically store theory map
, graphCmd :: (String, FilePath)
-- ^ The dot or json command with additional flag to indicate choice dot, json, ...
, imageFormat :: ImageFormat
-- ^ The image-format used for rendering graphs
, defaultAutoProver :: AutoProver
-- ^ The default prover to use for automatic proving.
, debug :: Bool
-- ^ Output debug messages
, isDiffTheory :: Bool
-- ^ Output debug messages
}
-- | Simple data type for generating JSON responses.
data JsonResponse
= JsonHtml T.Text Content -- ^ Title and HTML content
| JsonAlert T.Text -- ^ Alert/dialog box with message
| JsonRedirect T.Text -- ^ Redirect to given URL
-- | Data type representing origin of theory.
-- Command line with file path, upload with filename (not path),
-- or created by interactive mode (e.g. through editing).
data TheoryOrigin = Local FilePath | Upload String | Interactive
deriving (Show, Eq, Ord, Generic, Bin.Binary, NFData)
-- | Data type containg both the theory and it's index, making it easier to
-- pass the two around (since they are always tied to each other). We also
-- keep some extra bookkeeping information.
data TheoryInfo = TheoryInfo
{ tiIndex :: TheoryIdx -- ^ Index of theory.
, tiTheory :: ClosedTheory -- ^ The closed theory.
, tiTime :: ZonedTime -- ^ Time theory was loaded.
, tiParent :: Maybe TheoryIdx -- ^ Prev theory in history
, tiPrimary :: Bool -- ^ This is the orginally loaded theory.
, tiOrigin :: TheoryOrigin -- ^ Origin of theory.
, tiAutoProver :: AutoProver -- ^ The automatic prover to use.
} deriving (Generic, Bin.Binary)
-- | Data type containg both the theory and it's index, making it easier to
-- pass the two around (since they are always tied to each other). We also
-- keep some extra bookkeeping information.
data DiffTheoryInfo = DiffTheoryInfo
{ dtiIndex :: TheoryIdx -- ^ Index of theory.
, dtiTheory :: ClosedDiffTheory -- ^ The closed theory.
, dtiTime :: ZonedTime -- ^ Time theory was loaded.
, dtiParent :: Maybe TheoryIdx -- ^ Prev theory in history
, dtiPrimary :: Bool -- ^ This is the orginally loaded theory.
, dtiOrigin :: TheoryOrigin -- ^ Origin of theory.
, dtiAutoProver :: AutoProver -- ^ The automatic prover to use.
} deriving (Generic, Bin.Binary)
-- | We use the ordering in order to display loaded theories to the user.
-- We first compare by name, then by time loaded, and then by source: Theories
-- that were loaded from the command-line are displayed earlier then
-- interactively loaded ones.
compareTI :: TheoryInfo -> TheoryInfo -> Ordering
compareTI (TheoryInfo _ i1 t1 p1 a1 o1 _) (TheoryInfo _ i2 t2 p2 a2 o2 _) =
mconcat
[ comparing (get thyName) i1 i2
, comparing zonedTimeToUTC t1 t2
, compare a1 a2
, compare p1 p2
, compare o1 o2
]
-- | We use the ordering in order to display loaded theories to the user.
-- We first compare by name, then by time loaded, and then by source: Theories
-- that were loaded from the command-line are displayed earlier then
-- interactively loaded ones.
compareDTI :: DiffTheoryInfo -> DiffTheoryInfo -> Ordering
compareDTI (DiffTheoryInfo _ i1 t1 p1 a1 o1 _) (DiffTheoryInfo _ i2 t2 p2 a2 o2 _) =
mconcat
[ comparing (get diffThyName) i1 i2
, comparing zonedTimeToUTC t1 t2
, compare a1 a2
, compare p1 p2
, compare o1 o2
]
data EitherTheoryInfo = Trace TheoryInfo | Diff DiffTheoryInfo deriving (Generic, Bin.Binary)
-- instance Bin.Binary TheoryInfo
-- instance Bin.Binary DiffTheoryInfo
-- instance Bin.Binary EitherTheoryInfo
{- instance Bin.Binary EitherTheoryInfo where
put (Trace i) = do Bin.put (0 :: Bin.Word8)
Bin.put i
put (Diff i) = do Bin.put (1 :: Bin.Word8)
Bin.put i -}
{- get = do t <- get :: Bin.Get Bin.Word8
case t of
0 -> do i <- Bin.get
return (Trace i)
1 -> do i <- Bin.get
return (Diff i) -}
{- get = do tag <- Bin.getWord8
case tag of
0 -> liftM Trace get
1 -> liftM Diff get -}
-- Direct access functionf for Either Theory Type
getEitherTheoryName :: EitherTheoryInfo -> String
getEitherTheoryName (Trace i) = get thyName (tiTheory i)
getEitherTheoryName (Diff i) = get diffThyName (dtiTheory i)
isTheoryInfo :: EitherTheoryInfo -> Bool
isTheoryInfo (Trace _) = True
isTheoryInfo (Diff _) = False
isDiffTheoryInfo :: EitherTheoryInfo -> Bool
isDiffTheoryInfo (Trace _) = False
isDiffTheoryInfo (Diff _) = True
getEitherTheoryTime :: EitherTheoryInfo -> ZonedTime
getEitherTheoryTime (Trace i) = (tiTime i)
getEitherTheoryTime (Diff i) = (dtiTime i)
getEitherTheoryPrimary :: EitherTheoryInfo -> Bool
getEitherTheoryPrimary (Trace i) = (tiPrimary i)
getEitherTheoryPrimary (Diff i) = (dtiPrimary i)
getEitherTheoryOrigin :: EitherTheoryInfo -> TheoryOrigin
getEitherTheoryOrigin (Trace i) = (tiOrigin i)
getEitherTheoryOrigin (Diff i) = (dtiOrigin i)
getEitherTheoryIndex :: EitherTheoryInfo -> TheoryIdx
getEitherTheoryIndex (Trace i) = (tiIndex i)
getEitherTheoryIndex (Diff i) = (dtiIndex i)
-- | We use the ordering in order to display loaded theories to the user.
-- We first compare by name, then by time loaded, and then by source: Theories
-- that were loaded from the command-line are displayed earlier then
-- interactively loaded ones.
compareEDTI :: EitherTheoryInfo -> EitherTheoryInfo -> Ordering
compareEDTI (Trace (TheoryInfo _ i1 t1 p1 a1 o1 _)) (Trace (TheoryInfo _ i2 t2 p2 a2 o2 _)) =
mconcat
[ comparing (get thyName) i1 i2
, comparing zonedTimeToUTC t1 t2
, compare a1 a2
, compare p1 p2
, compare o1 o2
]
compareEDTI (Diff (DiffTheoryInfo _ i1 t1 p1 a1 o1 _)) (Diff (DiffTheoryInfo _ i2 t2 p2 a2 o2 _)) =
mconcat
[ comparing (get diffThyName) i1 i2
, comparing zonedTimeToUTC t1 t2
, compare a1 a2
, compare p1 p2
, compare o1 o2
]
compareEDTI (Diff (DiffTheoryInfo _ i1 t1 p1 a1 o1 _)) (Trace (TheoryInfo _ i2 t2 p2 a2 o2 _)) =
mconcat
[ compare ((get diffThyName) i1) ((get thyName) i2)
, comparing zonedTimeToUTC t1 t2
, compare a1 a2
, compare p1 p2
, compare o1 o2
]
compareEDTI (Trace (TheoryInfo _ i1 t1 p1 a1 o1 _)) (Diff (DiffTheoryInfo _ i2 t2 p2 a2 o2 _)) =
mconcat
[ compare ((get thyName) i1) ((get diffThyName) i2)
, comparing zonedTimeToUTC t1 t2
, compare a1 a2
, compare p1 p2
, compare o1 o2
]
instance Eq (TheoryInfo) where
(==) t1 t2 = compareTI t1 t2 == EQ
instance Ord (TheoryInfo) where
compare = compareTI
instance Eq (DiffTheoryInfo) where
(==) t1 t2 = compareDTI t1 t2 == EQ
instance Ord (DiffTheoryInfo) where
compare = compareDTI
instance Eq (EitherTheoryInfo) where
(==) t1 t2 = compareEDTI t1 t2 == EQ
instance Ord (EitherTheoryInfo) where
compare = compareEDTI
-- | Simple data type for specifying a path to a specific
-- item within a theory.
data TheoryPath
= TheoryHelp -- ^ The help view (help and info about theory)
| TheoryLemma String -- ^ Theory lemma with given name
| TheorySource SourceKind Int Int -- ^ Required cases (i'th source, j'th case)
| TheoryProof String ProofPath -- ^ Proof path within proof for given lemma
| TheoryMethod String ProofPath Int -- ^ Apply the proof method to proof path
| TheoryRules -- ^ Theory rules
| TheoryMessage -- ^ Theory message deduction
deriving (Eq, Show, Read)
-- | Simple data type for specifying a path to a specific
-- item within a theory.
data DiffTheoryPath
= DiffTheoryHelp -- ^ The help view (help and info about theory)
| DiffTheoryLemma Side String -- ^ Theory lemma with given name and side
| DiffTheoryDiffLemma String -- ^ Theory DiffLemma with given name
| DiffTheorySource Side SourceKind Bool Int Int -- ^ Required cases (i'th source, j'th case)
| DiffTheoryProof Side String ProofPath -- ^ Proof path within proof for given lemma
| DiffTheoryDiffProof String ProofPath -- ^ Proof path within proof for given lemma
| DiffTheoryMethod Side String ProofPath Int -- ^ Apply the proof method to proof path
| DiffTheoryDiffMethod String ProofPath Int -- ^ Apply the proof method to proof path
| DiffTheoryRules Side Bool -- ^ Theory rules per side
| DiffTheoryDiffRules -- ^ Theory rules unprocessed
| DiffTheoryMessage Side Bool -- ^ Theory message deduction per side
deriving (Eq, Show, Read)
-- | Render a theory path to a list of strings. Note that we prefix an
-- underscore to the empty string and strings starting with an underscore.
-- This avoids empty path segments, which seem to trip up certain versions of
-- Yesod.
renderTheoryPath :: TheoryPath -> [String]
renderTheoryPath =
map prefixWithUnderscore . go
where
go TheoryHelp = ["help"]
go TheoryRules = ["rules"]
go TheoryMessage = ["message"]
go (TheoryLemma name) = ["lemma", name]
go (TheorySource k i j) = ["cases", show k, show i, show j]
go (TheoryProof lemma path) = "proof" : lemma : path
go (TheoryMethod lemma path idx) = "method" : lemma : show idx : path
-- | Render a theory path to a list of strings. Note that we prefix an
-- underscore to the empty string and strings starting with an underscore.
-- This avoids empty path segments, which seem to trip up certain versions of
-- Yesod.
renderDiffTheoryPath :: DiffTheoryPath -> [String]
renderDiffTheoryPath =
map prefixWithUnderscore . go
where
go DiffTheoryHelp = ["help"]
go (DiffTheoryLemma s name) = ["lemma", show s, name]
go (DiffTheoryDiffLemma name) = ["difflemma", name]
go (DiffTheorySource s k i j d) = ["cases", show s, show k, show i, show j, show d]
go (DiffTheoryProof s lemma path) = "proof" : show s : lemma : path
go (DiffTheoryDiffProof lemma path) = "diffProof" : lemma : path
go (DiffTheoryMethod s lemma path idx) = "method" : show s : lemma : show idx : path
go (DiffTheoryDiffMethod lemma path idx) = "diffMethod" : lemma : show idx : path
go (DiffTheoryRules s d) = ["rules", show s, show d]
go (DiffTheoryDiffRules) = ["diffrules"]
go (DiffTheoryMessage s d) = ["message", show s, show d]
-- | Prefix an underscore to the empty string and strings starting with an
-- underscore.
prefixWithUnderscore :: String -> String
prefixWithUnderscore "" = "_"
prefixWithUnderscore cs@('_':_) = '_' : cs
prefixWithUnderscore cs = cs
-- | Remove an underscore prefix. It holds that
--
-- > unprefixUnderscore . prefixWithUnderscore = id
--
-- The inverted composition holds for all strings except the empty string and
-- strings starting with an underscore.
unprefixUnderscore :: String -> String
unprefixUnderscore "_" = ""
unprefixUnderscore ('_':cs@('_':_)) = cs
unprefixUnderscore cs = cs
-- | Parse a list of strings into a theory path.
parseTheoryPath :: [String] -> Maybe TheoryPath
parseTheoryPath =
parse . map unprefixUnderscore
where
parse [] = Nothing
parse (x:xs) = case x of
"help" -> Just TheoryHelp
"rules" -> Just TheoryRules
"message" -> Just TheoryMessage
"lemma" -> parseLemma xs
"cases" -> parseCases xs
"proof" -> parseProof xs
"method" -> parseMethod xs
_ -> Nothing
safeRead = listToMaybe . map fst . reads
parseLemma ys = TheoryLemma <$> listToMaybe ys
parseProof (y:ys) = Just (TheoryProof y ys)
parseProof _ = Nothing
parseMethod (y:z:zs) = safeRead z >>= Just . TheoryMethod y zs
parseMethod _ = Nothing
parseCases (kind:y:z:_) = do
k <- case kind of "refined" -> return RefinedSource
"raw" -> return RawSource
_ -> Nothing
m <- safeRead y
n <- safeRead z
return (TheorySource k m n)
parseCases _ = Nothing
-- | Parse a list of strings into a theory path.
parseDiffTheoryPath :: [String] -> Maybe DiffTheoryPath
parseDiffTheoryPath =
parse . map unprefixUnderscore
where
parse [] = Nothing
parse (x:xs) = case x of
"help" -> Just DiffTheoryHelp
"diffrules" -> Just DiffTheoryDiffRules
"rules" -> parseRules xs
"message" -> parseMessage xs
"lemma" -> parseLemma xs
"difflemma" -> parseDiffLemma xs
"cases" -> parseCases xs
"proof" -> parseProof xs
"diffProof" -> parseDiffProof xs
"method" -> parseMethod xs
"diffMethod"-> parseDiffMethod xs
_ -> Nothing
safeRead :: Read a => String -> Maybe a
safeRead = listToMaybe . map fst . reads
parseRules :: [String] -> Maybe DiffTheoryPath
parseRules (y:z:_) = do
s <- case y of "LHS" -> return LHS
"RHS" -> return RHS
_ -> Nothing
d <- case z of "True" -> return True
"False" -> return False
_ -> Nothing
return (DiffTheoryRules s d)
parseRules _ = Nothing
parseMessage :: [String] -> Maybe DiffTheoryPath
parseMessage (y:z:_) = do
s <- case y of "LHS" -> return LHS
"RHS" -> return RHS
_ -> Nothing
d <- case z of "True" -> return True
"False" -> return False
_ -> Nothing
return (DiffTheoryMessage s d)
parseMessage _ = Nothing
parseLemma :: [String] -> Maybe DiffTheoryPath
parseLemma (y:ys) = do
s <- case y of "LHS" -> return LHS
"RHS" -> return RHS
_ -> Nothing
return (DiffTheoryLemma s (head ys))
parseLemma _ = Nothing
parseDiffLemma :: [String] -> Maybe DiffTheoryPath
parseDiffLemma ys = DiffTheoryDiffLemma <$> listToMaybe ys
parseProof :: [String] -> Maybe DiffTheoryPath
parseProof (y:z:zs) = do
s <- case y of "LHS" -> return LHS
"RHS" -> return RHS
_ -> Nothing
return (DiffTheoryProof s z zs)
parseProof _ = Nothing
parseDiffProof :: [String] -> Maybe DiffTheoryPath
parseDiffProof (z:zs) = do
return (DiffTheoryDiffProof z zs)
parseDiffProof _ = Nothing
parseMethod :: [String] -> Maybe DiffTheoryPath
parseMethod (x:y:z:zs) = do
s <- case x of "LHS" -> return LHS
"RHS" -> return RHS
_ -> Nothing
i <- safeRead z
return (DiffTheoryMethod s y zs i)
parseMethod _ = Nothing
parseDiffMethod :: [String] -> Maybe DiffTheoryPath
parseDiffMethod (y:z:zs) = do
i <- safeRead z
return (DiffTheoryDiffMethod y zs i)
parseDiffMethod _ = Nothing
parseCases :: [String] -> Maybe DiffTheoryPath
parseCases (x:kind:pd:y:z:_) = do
s <- case x of "LHS" -> return LHS
"RHS" -> return RHS
_ -> Nothing
k <- case kind of "refined" -> return RefinedSource
"raw" -> return RawSource
_ -> Nothing
d <- case pd of "True" -> return True
"False" -> return False
_ -> Nothing
m <- safeRead y
n <- safeRead z
return (DiffTheorySource s k d m n)
parseCases _ = Nothing
type RenderUrl = Route (WebUI) -> T.Text
------------------------------------------------------------------------------
-- Routing
------------------------------------------------------------------------------
-- | Static routing for our application.
-- Note that handlers ending in R are general handlers,
-- whereas handlers ending in MR are for the main view
-- and the ones ending in DR are for the debug view.
mkYesodData "WebUI" [parseRoutes|
/ RootR GET POST
/thy/trace/#Int/overview/*TheoryPath OverviewR GET
/thy/trace/#Int/source TheorySourceR GET
/thy/trace/#Int/message TheoryMessageDeductionR GET
/thy/trace/#Int/main/*TheoryPath TheoryPathMR GET
-- /thy/trace/#Int/debug/*TheoryPath TheoryPathDR GET
/thy/trace/#Int/graph/*TheoryPath TheoryGraphR GET
/thy/trace/#Int/autoprove/#SolutionExtractor/#Int/*TheoryPath AutoProverR GET
/thy/trace/#Int/next/#String/*TheoryPath NextTheoryPathR GET
/thy/trace/#Int/prev/#String/*TheoryPath PrevTheoryPathR GET
-- /thy/trace/#Int/save SaveTheoryR GET
/thy/trace/#Int/download/#String DownloadTheoryR GET
-- /thy/trace/#Int/edit/source EditTheoryR GET POST
-- /thy/trace/#Int/edit/path/*TheoryPath EditPathR GET POST
/thy/trace/#Int/del/path/*TheoryPath DeleteStepR GET
/thy/trace/#Int/unload UnloadTheoryR GET
/thy/equiv/#Int/overview/*DiffTheoryPath OverviewDiffR GET
/thy/equiv/#Int/source TheorySourceDiffR GET
/thy/equiv/#Int/message TheoryMessageDeductionDiffR GET
/thy/equiv/#Int/main/*DiffTheoryPath TheoryPathDiffMR GET
-- /thy/equiv/#Int/debug/*DiffTheoryPath TheoryPathDiffDR GET
/thy/equiv/#Int/graph/*DiffTheoryPath TheoryGraphDiffR GET
/thy/equiv/#Int/mirror/*DiffTheoryPath TheoryMirrorDiffR GET
/thy/equiv/#Int/autoprove/#SolutionExtractor/#Int/#Side/*DiffTheoryPath AutoProverDiffR GET
/thy/equiv/#Int/autoproveDiff/#SolutionExtractor/#Int/*DiffTheoryPath AutoDiffProverR GET
/thy/equiv/#Int/next/#String/*DiffTheoryPath NextTheoryPathDiffR GET
/thy/equiv/#Int/prev/#String/*DiffTheoryPath PrevTheoryPathDiffR GET
-- /thy/equiv/#Int/save SaveTheoryR GET
/thy/equiv/#Int/download/#String DownloadTheoryDiffR GET
-- /thy/equiv/#Int/edit/source EditTheoryR GET POST
-- /thy/equiv/#Int/edit/path/*DiffTheoryPath EditPathDiffR GET POST
/thy/equiv/#Int/del/path/*DiffTheoryPath DeleteStepDiffR GET
/thy/equiv/#Int/unload UnloadTheoryDiffR GET
/kill KillThreadR GET
-- /threads ThreadsR GET
/robots.txt RobotsR GET
/favicon.ico FaviconR GET
/static StaticR Static getStatic
|]
instance PathPiece SolutionExtractor where
toPathPiece CutNothing = "characterize"
toPathPiece CutDFS = "idfs"
toPathPiece CutBFS = "bfs"
fromPathPiece "characterize" = Just CutNothing
fromPathPiece "idfs" = Just CutDFS
fromPathPiece "bfs" = Just CutBFS
fromPathPiece _ = Nothing
instance PathPiece Side where
toPathPiece LHS = "LHS"
toPathPiece RHS = "RHS"
fromPathPiece "LHS" = Just LHS
fromPathPiece "RHS" = Just RHS
fromPathPiece _ = Nothing
-- | MultiPiece instance for TheoryPath.
instance PathMultiPiece TheoryPath where
toPathMultiPiece = map T.pack . renderTheoryPath
fromPathMultiPiece = parseTheoryPath . map T.unpack
-- | MultiPiece instance for DiffTheoryPath.
instance PathMultiPiece DiffTheoryPath where
toPathMultiPiece = map T.pack . renderDiffTheoryPath
fromPathMultiPiece = parseDiffTheoryPath . map T.unpack
-- Instance of the Yesod typeclass.
instance Yesod WebUI where
-- | The approot. We can leave this empty because the
-- application is always served from the root of the server.
approot = ApprootStatic T.empty
-- | The default layout for rendering.
defaultLayout = defaultLayout'
-- | The path cleaning function. We make sure empty strings
-- are not scrubbed from the end of the list. The default
-- cleanPath function forces canonical URLs.
cleanPath _ = Right
------------------------------------------------------------------------------
-- Default layout
------------------------------------------------------------------------------
-- | Our application's default layout template.
-- Note: We define the default layout here even tough it doesn't really
-- belong in the "types" module in order to avoid mutually recursive modules.
-- defaultLayout' :: (Yesod master, Route master ~ WebUIRoute)
-- => Widget master () -- ^ Widget to embed in layout
-- -> Handler master Html
defaultLayout' :: Widget -> Handler Html
defaultLayout' w = do
page <- widgetToPageContent w
message <- getMessage
withUrlRenderer [hamlet|
$newline never
!!!
<html>
<head>
<title>#{pageTitle page}
<link rel=stylesheet href=/static/css/tamarin-prover-ui.css>
<link rel=stylesheet href=/static/css/jquery-contextmenu.css>
<link rel=stylesheet href=/static/css/smoothness/jquery-ui.css>
<script src=/static/js/jquery.js></script>
<script src=/static/js/jquery-ui.js></script>
<script src=/static/js/jquery-layout.js></script>
<script src=/static/js/jquery-cookie.js></script>
<script src=/static/js/jquery-superfish.js></script>
<script src=/static/js/jquery-contextmenu.js></script>
<script src=/static/js/tamarin-prover-ui.js></script>
^{pageHead page}
<body>
$maybe msg <- message
<p.message>#{msg}
<p.loading>
Loading, please wait...
\ <a id=cancel href='#'>Cancel</a>
^{pageBody page}
<div#dialog>
<ul#contextMenu>
<li.autoprove>
<a href="#autoprove">Autoprove</a>
|]
-- <li.delstep>
-- <a href="#del/path">Remove step</a>
|
kelnage/tamarin-prover
|
src/Web/Types.hs
|
gpl-3.0
| 26,803 | 0 | 13 | 7,625 | 4,575 | 2,442 | 2,133 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
import Haste.HPlay.View
import Haste.HPlay.Cell
import Haste.Perch
import Haste
import Haste.LocalStorage
import Control.Applicative
import Prelude hiding (div,span,id,all)
import Data.Typeable
import Control.Monad(when)
import Control.Monad.IO.Class
import qualified Data.IntMap as M
import Data.Monoid
import Haste.Serialize
import Haste.JSON (JSON(..))
data Status= Completed | Active deriving (Show,Eq,Read)
type Tasks = M.IntMap (String,Status)
instance Serialize Status where
toJSON= Str . toJSString . show
parseJSON (Str jss)= return . read $ fromJSStr jss
data PresentationMode= Mode String deriving Typeable
all= ""
active= "active"
completed= "completed"
main= do
addHeader $ link ! atr "rel" "stylesheet" ! href "base.css"
runBody todo
todo :: Widget ()
todo = do
section ! id "todoapp" $ do
nelem "header" ! id "header"
section ! id "main" $ do
ul ! id "todo-list" $ noHtml
footer ! id "footer" $ do
span ! id "todo-count" $ noHtml
ul ! id "filters" $ noHtml
span ! id "clear-holder" $ noHtml
footer ! id "info" $ do
p "Double-click to edit a todo"
p $ do
toElem "Created by "
a ! href "http://twitter.com/agocorona" $ "Alberto G. Corona"
p $ do
toElem "Part of "
a ! href "http://todomvc.com" $ "TodoMVC"
++> header -- ++> add HTML to a widget
**> toggleAll
**> filters all
**> itemsLeft
**> showClearCompleted -- **> is the *> applicative operator
where
itemsLeft= at "todo-count" Insert $ do
n <- getTasks >>= return . M.size . M.filter ((==) Active . snd) . fst
wraw $ do strong (show n)
toElem $ case n of
1 -> " item left"
_ -> " items left"
showClearCompleted= at "clear-holder" Insert $ do
(tasks,_) <- getTasks
let n = M.size . M.filter ((==) Completed . snd) $ tasks
when (n >0) $ do
(button ! id "clear-completed" $ "Clear completed") `pass` OnClick
setTasks $ M.filter ((==) Active . snd) tasks
displayFiltered
filters op =at "filters" Insert $ filters' op
where
filters' op= (links op `wake` OnClick)
`wcallback` (\op' -> do
setSData $ Mode op'
displayFiltered **> return ()
filters' op')
links op=
li ! clas op all <<< wlink all (toElem "All") <|>
li ! clas op active <<< wlink active (toElem "Active") <|>
li ! clas op completed <<< wlink completed (toElem "Completed")
clas current op= atr "class" $ if current== op then "selected" else "unsel"
header = at "header" Insert $ h1 "todos" ++> newTodo
toggleAll = at "main" Prepend $ do
t <- getCheckBoxes $ setCheckBox False "toggle" `wake` OnClick ! atr "class" "toggle-all"
let newst= case t of
[] -> Active
_ -> Completed
(tasks,_) <- getTasks
filtered <- getFiltered tasks
let filtered' = M.map (\(t,_) -> (t,newst)) filtered
tasks' = M.union filtered' tasks
setTasks tasks'
displayFiltered
itemsLeft
displayFiltered = do
(tasks,_) <- getTasks
filtered <- getFiltered tasks
at "todo-list" Insert $ foldl (<|>) mempty $ reverse
[display i | i <- M.keys filtered]
**> return ()
getFiltered tasks= do
Mode todisplay <- getSData <|> return (Mode all)
return $ M.filter (fil todisplay) tasks
where
fil f (t,st)
| f==all= True
| f==active = case st of
Active -> True
_ -> False
| otherwise = case st of
Completed -> True
_ -> False
newTodo= do
let entry= boxCell "new-todo"
task <- mk entry Nothing `wake` OnKeyUp
! atr "placeholder" "What needs to be done?"
! atr "autofocus" ""
EventData evname evdata <- getEventData
when( evdata == Key 13) $ do
entry .= ""
idtask <- addTask task Active
Mode m <- getSData <|> return (Mode all)
when (m /= completed) $ at "todo-list" Prepend $ display idtask
itemsLeft
display idtask =
(li <<< ( toggleActive **> destroy)) `wcallback` const (delTask idtask)
where
toggleActive = do
Just (task,st) <- getTask idtask
let checked= case st of Completed -> True; Active -> False
ch <- getCheckBoxes $ setCheckBox checked "check" `wake` OnClick ! atr "class" "toggle"
case ch of
["check"] -> changeState idtask Completed task
_ -> changeState idtask Active task
destroy= (button ! atr "class" "destroy" $ noHtml) `pass` OnClick
changeState i stat task=
insertTask i task stat
**> itemsLeft
**> showClearCompleted
**> viewEdit i stat task
viewEdit idtask st task = do
let lab= case st of
Completed -> label ! atr "class" "completed"
Active -> label
lab task `pass` OnDblClick
`wcallback` const (do
ntask <- inputString (Just task) `wake` OnKeyUp ! atr "class" "edit"
EventData _ (Key k) <- getEventData
continueIf (k== 13) ntask
`wcallback` (\ntask -> do
insertTask idtask ntask st
viewEdit idtask st ntask))
-- Model, using LocalStorage
getTasks :: MonadIO m => m (Tasks, Int)
getTasks= liftIO $ do
mt <- getItem "tasks"
case mt of
Left _ -> setItem "tasks" (M.toList (M.empty :: Tasks),0 :: Int) >> getTasks
Right (ts,n) -> return (M.fromList ts, n)
getTask i= liftIO $ do
(tasks,id) <- getTasks
return $ M.lookup i tasks
setTasks :: MonadIO m => Tasks -> m ()
setTasks tasks= liftIO $ do
(_,n) <- getTasks
setItem "tasks" (M.toList tasks,n)
addTask :: String -> Status -> Widget Int
addTask task state= liftIO $ do
(tasks,id) <- getTasks
let tasks'= M.insert id (task, state) tasks
setItem "tasks" (M.toList tasks', id+1)
return id
insertTask id task state= liftIO $ do
(tasks,i) <- getTasks
let tasks'= M.insert id (task,state) tasks
setItem "tasks" (M.toList tasks', i)
return tasks'
delTask i= liftIO $ do
(tasks,_) <- getTasks
setTasks $ M.delete i tasks
|
agocorona/hplay-todo
|
src/todo.hs
|
gpl-3.0
| 6,462 | 0 | 23 | 2,037 | 2,284 | 1,121 | 1,163 | 170 | 9 |
{-
Copyright (C) 2015 Michael Dunsmuir
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
import Control.Applicative
import Data.Char (isSpace)
import Data.Aeson
import qualified Data.ByteString.Lazy.Char8 as B
import Network.HTTP
import Text.ProtocolBuffers.WireMessage
import Com.Google.Transit.Realtime.FeedMessage (FeedMessage)
import RoutequeryService.GTFSRealtime
main = do
writeJsonForRequest "http://api.pugetsound.onebusaway.org/api/gtfs_realtime/trip-updates-for-agency/1.pb?key=" "trip_updates"
writeJsonForRequest "http://api.pugetsound.onebusaway.org/api/gtfs_realtime/vehicle-positions-for-agency/1.pb?key=" "vehicle_positions"
writeJsonForRequest request name = do
key <- loadKey
http <- simpleHTTP (getRequest (request ++ key))
message <- B.pack <$> getResponseBody http
let getted = messageGet message :: Either String (FeedMessage, B.ByteString)
case getted of
Left error -> putStrLn error
Right (update, _) -> B.writeFile (name ++ ".json") (encode update)
loadKey :: IO String
loadKey = trim <$> readFile "key.txt"
where
trim :: String -> String
trim = f . f
where f = reverse . dropWhile isSpace
|
mdunsmuir/routequery-service
|
src/Main.hs
|
gpl-3.0
| 1,771 | 0 | 12 | 308 | 274 | 143 | 131 | 24 | 2 |
{- ============================================================================
| Copyright 2011 Matthew D. Steele <[email protected]> |
| |
| This file is part of Fallback. |
| |
| Fallback 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. |
| |
| Fallback 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 Fallback. If not, see <http://www.gnu.org/licenses/>. |
============================================================================ -}
module Fallback.Preferences
(Preferences(..), loadPreferencesFromDisk, getPreferences, setPreferences)
where
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Data.Maybe (fromMaybe)
import System.FilePath (combine)
import System.IO.Unsafe (unsafePerformIO)
import Fallback.Control.Error (runEO, runIOEO)
import Fallback.Resource (getGameDataDir, readFromFile, saveToFile)
-------------------------------------------------------------------------------
data Preferences = Preferences
{ prefEnableMusic :: Bool,
prefEnableSound :: Bool,
prefFullscreen :: Bool }
deriving (Read, Show)
-- | Load and set the global preferences from disk.
loadPreferencesFromDisk :: IO Preferences
loadPreferencesFromDisk = do
prefsFile <- getPrefsFilePath
-- TODO use parseFromFile/weaveBracesCommas/meshKeyDefault here
mbPreferences <- readFromFile prefsFile
let prefs = fromMaybe defaultPreferences mbPreferences
writeIORef globalPrefs prefs
return prefs
-- | Get the current global preferences. If neither 'loadPreferencesFromDisk'
-- nor 'setPreferences' has yet been called, this will simply return the
-- default preferences.
getPreferences :: IO Preferences
getPreferences = readIORef globalPrefs
-- | Set the global preferences, and also save them to disk.
setPreferences :: Preferences -> IO ()
setPreferences prefs = do
writeIORef globalPrefs prefs
prefsFile <- getPrefsFilePath
eo <- runIOEO $ saveToFile prefsFile (shows prefs)
case runEO eo of
Left errors -> mapM_ putStrLn errors
Right () -> return ()
-------------------------------------------------------------------------------
{-# NOINLINE globalPrefs #-} -- needed for unsafePerformIO
globalPrefs :: IORef Preferences
globalPrefs = unsafePerformIO $ newIORef defaultPreferences
defaultPreferences :: Preferences
defaultPreferences = Preferences
{ prefEnableMusic = True,
prefEnableSound = True,
prefFullscreen = False }
getPrefsFilePath :: IO FilePath
getPrefsFilePath = do
dataDir <- getGameDataDir
return $ combine dataDir "preferences"
-------------------------------------------------------------------------------
|
mdsteele/fallback
|
src/Fallback/Preferences.hs
|
gpl-3.0
| 3,594 | 0 | 11 | 972 | 409 | 222 | 187 | 42 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.BigtableAdmin.Projects.Instances.Tables.SetIAMPolicy
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Sets the access control policy on a Table resource. Replaces any
-- existing policy.
--
-- /See:/ <https://cloud.google.com/bigtable/ Cloud Bigtable Admin API Reference> for @bigtableadmin.projects.instances.tables.setIamPolicy@.
module Network.Google.Resource.BigtableAdmin.Projects.Instances.Tables.SetIAMPolicy
(
-- * REST Resource
ProjectsInstancesTablesSetIAMPolicyResource
-- * Creating a Request
, projectsInstancesTablesSetIAMPolicy
, ProjectsInstancesTablesSetIAMPolicy
-- * Request Lenses
, pitsipXgafv
, pitsipUploadProtocol
, pitsipAccessToken
, pitsipUploadType
, pitsipPayload
, pitsipResource
, pitsipCallback
) where
import Network.Google.BigtableAdmin.Types
import Network.Google.Prelude
-- | A resource alias for @bigtableadmin.projects.instances.tables.setIamPolicy@ method which the
-- 'ProjectsInstancesTablesSetIAMPolicy' request conforms to.
type ProjectsInstancesTablesSetIAMPolicyResource =
"v2" :>
CaptureMode "resource" "setIamPolicy" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] SetIAMPolicyRequest :>
Post '[JSON] Policy
-- | Sets the access control policy on a Table resource. Replaces any
-- existing policy.
--
-- /See:/ 'projectsInstancesTablesSetIAMPolicy' smart constructor.
data ProjectsInstancesTablesSetIAMPolicy =
ProjectsInstancesTablesSetIAMPolicy'
{ _pitsipXgafv :: !(Maybe Xgafv)
, _pitsipUploadProtocol :: !(Maybe Text)
, _pitsipAccessToken :: !(Maybe Text)
, _pitsipUploadType :: !(Maybe Text)
, _pitsipPayload :: !SetIAMPolicyRequest
, _pitsipResource :: !Text
, _pitsipCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsInstancesTablesSetIAMPolicy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pitsipXgafv'
--
-- * 'pitsipUploadProtocol'
--
-- * 'pitsipAccessToken'
--
-- * 'pitsipUploadType'
--
-- * 'pitsipPayload'
--
-- * 'pitsipResource'
--
-- * 'pitsipCallback'
projectsInstancesTablesSetIAMPolicy
:: SetIAMPolicyRequest -- ^ 'pitsipPayload'
-> Text -- ^ 'pitsipResource'
-> ProjectsInstancesTablesSetIAMPolicy
projectsInstancesTablesSetIAMPolicy pPitsipPayload_ pPitsipResource_ =
ProjectsInstancesTablesSetIAMPolicy'
{ _pitsipXgafv = Nothing
, _pitsipUploadProtocol = Nothing
, _pitsipAccessToken = Nothing
, _pitsipUploadType = Nothing
, _pitsipPayload = pPitsipPayload_
, _pitsipResource = pPitsipResource_
, _pitsipCallback = Nothing
}
-- | V1 error format.
pitsipXgafv :: Lens' ProjectsInstancesTablesSetIAMPolicy (Maybe Xgafv)
pitsipXgafv
= lens _pitsipXgafv (\ s a -> s{_pitsipXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pitsipUploadProtocol :: Lens' ProjectsInstancesTablesSetIAMPolicy (Maybe Text)
pitsipUploadProtocol
= lens _pitsipUploadProtocol
(\ s a -> s{_pitsipUploadProtocol = a})
-- | OAuth access token.
pitsipAccessToken :: Lens' ProjectsInstancesTablesSetIAMPolicy (Maybe Text)
pitsipAccessToken
= lens _pitsipAccessToken
(\ s a -> s{_pitsipAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pitsipUploadType :: Lens' ProjectsInstancesTablesSetIAMPolicy (Maybe Text)
pitsipUploadType
= lens _pitsipUploadType
(\ s a -> s{_pitsipUploadType = a})
-- | Multipart request metadata.
pitsipPayload :: Lens' ProjectsInstancesTablesSetIAMPolicy SetIAMPolicyRequest
pitsipPayload
= lens _pitsipPayload
(\ s a -> s{_pitsipPayload = a})
-- | REQUIRED: The resource for which the policy is being specified. See the
-- operation documentation for the appropriate value for this field.
pitsipResource :: Lens' ProjectsInstancesTablesSetIAMPolicy Text
pitsipResource
= lens _pitsipResource
(\ s a -> s{_pitsipResource = a})
-- | JSONP
pitsipCallback :: Lens' ProjectsInstancesTablesSetIAMPolicy (Maybe Text)
pitsipCallback
= lens _pitsipCallback
(\ s a -> s{_pitsipCallback = a})
instance GoogleRequest
ProjectsInstancesTablesSetIAMPolicy
where
type Rs ProjectsInstancesTablesSetIAMPolicy = Policy
type Scopes ProjectsInstancesTablesSetIAMPolicy =
'["https://www.googleapis.com/auth/bigtable.admin",
"https://www.googleapis.com/auth/bigtable.admin.table",
"https://www.googleapis.com/auth/cloud-bigtable.admin",
"https://www.googleapis.com/auth/cloud-bigtable.admin.table",
"https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsInstancesTablesSetIAMPolicy'{..}
= go _pitsipResource _pitsipXgafv
_pitsipUploadProtocol
_pitsipAccessToken
_pitsipUploadType
_pitsipCallback
(Just AltJSON)
_pitsipPayload
bigtableAdminService
where go
= buildClient
(Proxy ::
Proxy ProjectsInstancesTablesSetIAMPolicyResource)
mempty
|
brendanhay/gogol
|
gogol-bigtableadmin/gen/Network/Google/Resource/BigtableAdmin/Projects/Instances/Tables/SetIAMPolicy.hs
|
mpl-2.0
| 6,253 | 0 | 16 | 1,336 | 793 | 465 | 328 | 125 | 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.DFAReporting.AdvertiserGroups.Patch
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates an existing advertiser group. This method supports patch
-- semantics.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.advertiserGroups.patch@.
module Network.Google.Resource.DFAReporting.AdvertiserGroups.Patch
(
-- * REST Resource
AdvertiserGroupsPatchResource
-- * Creating a Request
, advertiserGroupsPatch
, AdvertiserGroupsPatch
-- * Request Lenses
, agpProFileId
, agpPayload
, agpId
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.advertiserGroups.patch@ method which the
-- 'AdvertiserGroupsPatch' request conforms to.
type AdvertiserGroupsPatchResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"advertiserGroups" :>
QueryParam "id" (Textual Int64) :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] AdvertiserGroup :>
Patch '[JSON] AdvertiserGroup
-- | Updates an existing advertiser group. This method supports patch
-- semantics.
--
-- /See:/ 'advertiserGroupsPatch' smart constructor.
data AdvertiserGroupsPatch = AdvertiserGroupsPatch'
{ _agpProFileId :: !(Textual Int64)
, _agpPayload :: !AdvertiserGroup
, _agpId :: !(Textual Int64)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AdvertiserGroupsPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'agpProFileId'
--
-- * 'agpPayload'
--
-- * 'agpId'
advertiserGroupsPatch
:: Int64 -- ^ 'agpProFileId'
-> AdvertiserGroup -- ^ 'agpPayload'
-> Int64 -- ^ 'agpId'
-> AdvertiserGroupsPatch
advertiserGroupsPatch pAgpProFileId_ pAgpPayload_ pAgpId_ =
AdvertiserGroupsPatch'
{ _agpProFileId = _Coerce # pAgpProFileId_
, _agpPayload = pAgpPayload_
, _agpId = _Coerce # pAgpId_
}
-- | User profile ID associated with this request.
agpProFileId :: Lens' AdvertiserGroupsPatch Int64
agpProFileId
= lens _agpProFileId (\ s a -> s{_agpProFileId = a})
. _Coerce
-- | Multipart request metadata.
agpPayload :: Lens' AdvertiserGroupsPatch AdvertiserGroup
agpPayload
= lens _agpPayload (\ s a -> s{_agpPayload = a})
-- | Advertiser group ID.
agpId :: Lens' AdvertiserGroupsPatch Int64
agpId
= lens _agpId (\ s a -> s{_agpId = a}) . _Coerce
instance GoogleRequest AdvertiserGroupsPatch where
type Rs AdvertiserGroupsPatch = AdvertiserGroup
type Scopes AdvertiserGroupsPatch =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient AdvertiserGroupsPatch'{..}
= go _agpProFileId (Just _agpId) (Just AltJSON)
_agpPayload
dFAReportingService
where go
= buildClient
(Proxy :: Proxy AdvertiserGroupsPatchResource)
mempty
|
rueshyna/gogol
|
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/AdvertiserGroups/Patch.hs
|
mpl-2.0
| 3,888 | 0 | 15 | 886 | 509 | 300 | 209 | 75 | 1 |
module Widgets.ProjectPledges where
import Import
import Model.User (fetchUserPledgesDB)
import Model.Project
import Model.Currency
-- | A summary without ticket or discussion counts.
summarizeProject' :: Entity Project -> [Entity Pledge] -> ProjectSummary
summarizeProject' a b = summarizeProject a b [] []
-- |The summary of pledging to projects shown on user's page
projectPledgeSummary :: UserId -> Widget
projectPledgeSummary user_id = do
project_summary <- handlerToWidget $ runDB $
map (uncurry summarizeProject') <$> fetchUserPledgesDB user_id
toWidget [hamlet|
$if null project_summary
not pledged to any projects
$else
<a href=@{UserPledgesR user_id}>
<p>Patron to #{plural (length project_summary) "project" "projects"}
|]
-- |The listing of all pledges for a given user, shown on u/#/pledges
projectPledges :: UserId -> Widget
projectPledges user_id = do
project_summaries <- handlerToWidget $ runDB $
map (uncurry summarizeProject') <$> fetchUserPledgesDB user_id
let cost = summaryShareCost
shares = getCount . summaryShares
mills = millMilray . shares
total x = cost x $* fromIntegral (shares x)
toWidget [hamlet|
$if null project_summaries
not pledged to any projects
$else
<p>
Note: For testing purposes only. No real money is changing hands yet.
<table .table>
$forall summary <- project_summaries
<tr>
<td>
<a href=@{ProjectR (summaryProjectHandle summary)}>
#{summaryName summary}
<td>#{show (cost summary)}/pledge
<td>#{show (mills summary)}
<td>#{show (total summary)}
|]
|
akegalj/snowdrift
|
Widgets/ProjectPledges.hs
|
agpl-3.0
| 1,883 | 0 | 13 | 587 | 244 | 126 | 118 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{- |
Module : $Header$
Description : JSON stuff for tests.
Copyright : (c) plaimi 2014
License : AGPL-3
Maintainer : [email protected]
-} module Tempuhs.Spoc.JSON where
import Data.Aeson
(
ToJSON,
Value,
(.=),
encode,
object,
)
import qualified Data.ByteString.Lazy.Char8 as L8
jsonSuccess :: Value
-- | 'jsonSuccess' is the result of a successful operation without any data to
-- return.
jsonSuccess = object []
jsonKey :: Integer -> Value
-- | 'jsonKey' is the JSON representation of a database key.
jsonKey k = object ["id" .= k]
showJSON :: ToJSON a => a -> String
-- | 'showJSON' returns the JSON representation of the given value as a
-- 'String'.
showJSON = L8.unpack . encode
|
plaimi/tempuhs-server
|
test/Tempuhs/Spoc/JSON.hs
|
agpl-3.0
| 757 | 0 | 7 | 155 | 118 | 73 | 45 | 16 | 1 |
import Graphics.UI.Gtk
import Graphics.UI.Gtk.ModelView as New
import Data.Tree
main = do
initGUI
win <- windowNew
-- Create a tree model with some unsorted data.
rawmodel <- New.treeStoreNew
[Node ("zoo",8) [], Node ("foo",5) [],
Node ("bar",20) [], Node ("baz",2) []]
-- Create a sorting proxy model, that is, a model that permutates the
-- rows of a different model such that they appear to be sorted.
model <- New.treeModelSortNewWithModel rawmodel
-- Define two sorting functions, one being the default sorting function and
-- the other one being the sorting function for the 'SortColumnId' 2.
-- 'SortColumnId's are arbitrary positive numbers, i.e., we could have chosen
-- any other unique number.
New.treeSortableSetDefaultSortFunc model $ \iter1 iter2 -> do
(t1,_) <- New.treeModelGetRow rawmodel iter1
(t2,_) <- New.treeModelGetRow rawmodel iter2
return (compare t1 t2)
New.treeSortableSetSortFunc model 2 $ \iter1 iter2 -> do
(_,n1) <- New.treeModelGetRow rawmodel iter1
(_,n2) <- New.treeModelGetRow rawmodel iter2
return (compare n1 n2)
-- Create the view.
view <- New.treeViewNewWithModel model
-- Create and insert two columns, one with the heading Name, one with the
-- heading Number. Associate the 'SortColumnId' 2 with the latter column such
-- that clicking on the Number header will sort the rows by the numbers.
col <- New.treeViewColumnNew
New.treeViewColumnSetTitle col "Name"
rend <- New.cellRendererTextNew
New.cellLayoutPackStart col rend True
New.cellLayoutSetAttributeFunc col rend model $ \iter -> do
cIter <- New.treeModelSortConvertIterToChildIter model iter
(n,_) <- New.treeModelGetRow rawmodel cIter
set rend [New.cellText := n]
New.treeViewAppendColumn view col
col' <- New.treeViewColumnNew
New.treeViewColumnSetTitle col' "Number"
rend <- New.cellRendererTextNew
New.cellLayoutPackStart col' rend True
New.cellLayoutSetAttributeFunc col' rend model $ \iter -> do
cIter <- New.treeModelSortConvertIterToChildIter model iter
(_,c) <- New.treeModelGetRow rawmodel cIter
set rend [New.cellText := show c]
New.treeViewAppendColumn view col'
New.treeViewColumnSetSortColumnId col' 2
-- Create a button that shows information on the current state of the sorting
-- settings.
button <- buttonNewWithLabel "Dump Info"
button `onClicked` do
sId <- New.treeViewColumnGetSortColumnId col
putStrLn ("tvc1 sort id is "++show sId)
sId <- New.treeViewColumnGetSortColumnId col'
putStrLn ("tvc2 sort id is "++show sId)
sId <- New.treeSortableGetSortColumnId model
putStrLn ("sort id is "++show sId)
-- Show all entries of the proxy model
let recurse Nothing = return ()
recurse (Just iter) = do
cIter <- New.treeModelSortConvertIterToChildIter model iter
row <- New.treeModelGetRow rawmodel cIter
putStrLn ("iter "++show cIter++": "++show row)
mIter <- New.treeModelIterNext model iter
recurse mIter
mIter <- New.treeModelGetIterFirst model
recurse mIter
-- Put it all together.
vBox <- vBoxNew False 3
boxPackStartDefaults vBox view
boxPackEnd vBox button PackNatural 0
containerAdd win vBox
widgetShowAll win
win `onDestroy` mainQuit
mainGUI
|
thiagoarrais/gtk2hs
|
demo/treeList/TreeSort.hs
|
lgpl-2.1
| 3,316 | 0 | 20 | 664 | 841 | 395 | 446 | 62 | 2 |
{-# OPTIONS_GHC -Wall #-}
-- !! WARNING: SPOILERS AHEAD !! --
-- CIS 194: Homework 2
-- Log file parsing
module LogAnalysis where
import Provided.Log
import Control.Applicative ( liftA2 )
import Data.Ord ( comparing )
import Data.List ( unfoldr )
import Text.Read ( readMaybe )
readSeverity :: String -> Maybe Int
readSeverity s = (readMaybe s :: Maybe Int) >>= \svty -> if 0 <= svty && svty <=100
then Just svty
else Nothing
parseMessage :: String -> LogMessage
parseMessage l = case words l of
("I": t:rest) -> maybe (Unknown l) (\ time -> LogMessage Info time $ unwords rest) (readMaybe t :: Maybe Int)
("W": t:rest) -> maybe (Unknown l) (\ time -> LogMessage Warning time $ unwords rest) (readMaybe t :: Maybe Int)
("E":s:t:rest) -> maybe (Unknown l) (\(svty,time) -> LogMessage (Error svty) time $ unwords rest) ((uncurry $ liftA2 (,)) (readSeverity s, readMaybe t :: Maybe Int))
_ -> Unknown l
-- LogMessage is not defined with record syntax
timeStamp :: LogMessage -> Maybe TimeStamp
timeStamp (LogMessage _ t _) = Just t
timeStamp (Unknown _) = Nothing
message :: LogMessage -> String
message (LogMessage _ _ m) = m
message (Unknown m) = m
-- The exercise doesn't expect us to rebalance the MessageTree so 'insert' is easy
insert :: LogMessage -> MessageTree -> MessageTree
insert (Unknown _) t = t
insert x Leaf = Node Leaf x Leaf
insert x (Node l y r)
| (comparing timeStamp) x y == LT = Node (insert x l) y r
| otherwise = Node l y (insert x r)
-- Combinators are awesome!
build :: [LogMessage] -> MessageTree
build = foldr insert Leaf
inOrder :: MessageTree -> [LogMessage]
inOrder = unfoldr tearDown
where
tearDown Leaf = Nothing
tearDown (Node Leaf x r ) = Just (x, r)
tearDown (Node l x r ) = let Just (y, l') = tearDown l in Just (y, Node l' x r)
-- Log file postmortem
relevant :: LogMessage -> Bool
relevant (LogMessage (Error s) _ _) = 50 <= s
relevant _ = False
whatWentWrong :: [LogMessage] -> [String]
whatWentWrong = map message . inOrder . build . filter relevant
-- Brent provides a small test case in the exercise description:
smallTestMsgs :: [String]
smallTestMsgs = [ "I 6 Completed armadillo processing"
, "I 1 Nothing to report"
, "E 99 10 Flange failed!"
, "I 4 Everything normal"
, "I 11 Initiating self-destruct sequence"
, "E 70 3 Way too many pickles"
, "E 65 8 Bad pickle-flange interaction detected"
, "W 5 Flange is due for a check-up"
, "I 7 Out for lunch, back in two time steps"
, "E 20 2 Too many pickles"
, "I 9 Back from lunch" ]
smallTestExpected :: [String]
smallTestExpected = [ "Way too many pickles"
, "Bad pickle-flange interaction detected"
, "Flange failed!" ]
runSmallTest :: Bool
runSmallTest = smallTestExpected == (whatWentWrong . map parseMessage $ smallTestMsgs)
runBigTest :: IO [String]
runBigTest = fmap (whatWentWrong . map parseMessage . lines) . readFile $ "Provided/error.log"
-- Answer to exercise 6:
-- Apparently the Mad Hatter? In the Alice in Wonderland animated film
-- he refused to put mustard into the Rabbit's watch.
|
nilthehuman/cis194
|
Homework2.hs
|
unlicense
| 3,627 | 0 | 14 | 1,166 | 956 | 503 | 453 | 61 | 4 |
{-# LANGUAGE OverloadedStrings #-}
-- Copyright 2014 (c) Diego Souza <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module Leela.Data.Time
( Time
, Date (..)
, TimeSpec (..)
, TimeCache
, NominalDiffTime
, add
, now
, diff
, sleep
, alignBy
, expired
, seconds
, dateTime
, snapshot
, timeCache
, readCache
, fromSeconds
, fromDateTime
, milliseconds
) where
import Data.Time
import Data.IORef
import System.Clock
import Control.Monad
import Data.Serialize
import Control.DeepSeq
import Control.Concurrent
import Control.Applicative
import Data.Time.Clock.POSIX
newtype TimeCache = TimeCache (IORef Time)
newtype Time = Time { unTime :: Double }
deriving (Show, Eq, Ord)
newtype Date = Date (Int, Int, Int)
deriving (Show, Eq, Ord)
add :: NominalDiffTime -> Time -> Time
add increment (Time t) = Time (t + realToFrac increment)
alignBy :: Int -> Time -> Time
alignBy by t = let offset = fromIntegral (truncate (seconds t) `mod` by)
in (negate offset) `add` t
seconds :: Time -> Double
seconds = unTime
sleep :: Int -> IO ()
sleep s = threadDelay (s * 1000000)
milliseconds :: Time -> Double
milliseconds = (* 1000) . unTime
dateTime :: Time -> (Date, Double)
dateTime (Time s) = let u = posixSecondsToUTCTime (realToFrac s)
time = realToFrac $ utctDayTime u
(year, month, dayOfMonth) = toGregorian $ utctDay u
in (Date (fromIntegral year, month, dayOfMonth), time)
diff :: Time -> Time -> Time
diff (Time a) (Time b) = Time (abs $ a - b)
fromSeconds :: Double -> Time
fromSeconds = Time
fromDateTime :: Date -> Double -> Time
fromDateTime date time = fromSeconds $ realToFrac $ utcTimeToPOSIXSeconds $ UTCTime (fromDate date) (realToFrac time)
fromDate :: Date -> Day
fromDate (Date (y, m, d)) = fromGregorian (fromIntegral y) m d
toDate :: Day -> Date
toDate day = let (year, month, dayOfMonth) = toGregorian day
in Date (fromIntegral year, month, dayOfMonth)
fromTimeSpec :: TimeSpec -> Time
fromTimeSpec t = let a = fromIntegral $ sec t
b = fromIntegral (nsec t) / 1e9
in Time (a + b)
snapshot :: IO Time
snapshot = fromTimeSpec <$> getTime Monotonic
expired :: (Time, NominalDiffTime) -> Time -> Bool
expired (t1, limit) t0 = (t1 < tMin || t1 > tMax)
where
pLim = abs limit
tMax = pLim `add` t0
tMin = (negate pLim) `add` t0
now :: IO Time
now = fromTimeSpec <$> getTime Realtime
timeCache :: IO TimeCache
timeCache = do
cache <- now >>= newIORef
_ <- forkIO (forever $ sleep 1 >> now >>= atomicWriteIORef cache)
return (TimeCache cache)
readCache :: TimeCache -> IO Time
readCache (TimeCache cache) = readIORef cache
instance Enum Date where
succ = toDate . succ . fromDate
pred = toDate . pred . fromDate
toEnum = toDate . toEnum
fromEnum = fromEnum . fromDate
instance NFData Time where
rnf (Time v) = rnf v
instance Serialize Time where
put (Time t) = put t
get = Time <$> get
|
locaweb/leela
|
src/warpdrive/src/Leela/Data/Time.hs
|
apache-2.0
| 3,738 | 0 | 14 | 993 | 1,104 | 600 | 504 | 92 | 1 |
ans [] = []
ans ((a:b:_):xs) = (gcd a b):(ans xs)
main = do
c <- getContents
let i = map (map read) $ map words $ lines c :: [[Int]]
o = ans i
mapM_ print o
|
a143753/AOJ
|
1009.hs
|
apache-2.0
| 170 | 0 | 14 | 51 | 126 | 62 | 64 | 7 | 1 |
{-# LANGUAGE Rank2Types, ImpredicativeTypes, FlexibleInstances, UndecidableInstances #-}
module Data.Torrent.MetaInfo (PieceID, MetaInfo (..), SHA1, MetaInfoConduits (..)) where
import Prelude hiding (FilePath)
import Data.Maybe (fromJust)
import Data.Torrent.Types
import Crypto.Hash.SHA1
import Data.Map (Map)
import qualified Data.Map as Map
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Conduit
import Data.Conduit.Binary
import Crypto.Conduit
import System.IO hiding (FilePath, openFile)
import System.IO.Error (catchIOError)
import qualified Data.Serialize as Ser
import Filesystem
import Filesystem.Path.CurrentOS as FP
-- | Metainfo files (also known as .torrent files) are bencoded dictionaries
class MetaInfo t where
-- | This maps to a dictionary, with keys described below.
metaInfo :: t -> Map String BEncodedT
-- | The URL of the tracker.
announce :: t -> String
announce = beStringUTF8 . fromJust . Map.lookup "announce" . metaInfo
-- | This maps to a dictionary, with keys described below.
info :: t -> Map String BEncodedT
-- | The 20 byte sha1 hash of the bencoded form of the info value from the metainfo file.
infoHash :: t -> (Monad m, MonadThrow m) => m SHA1
-- | The name key maps to a UTF-8 encoded string which is the suggested name to save the file (or directory) as. It is purely advisory.
infoName :: t -> String
-- | Maps to a UTF-8 encoded string which is the suggested name to save the file (or directory) as. It is purely advisory.
infoName = beStringUTF8 . fromJust . Map.lookup "name" . info
-- | Maps to the number of bytes in each piece the file is split into. For the purposes of transfer, files are split into fixed-size pieces which are all the same length except for possibly the last one which may be truncated. piece length is almost always a power of two, most commonly 2 18 = 256 K (BitTorrent prior to version 3.2 uses 2 20 = 1 M as default).
infoPieceLength :: t -> Integer
infoPieceLength = beInteger . fromJust . Map.lookup "piece length" . info
-- | Maps to a string whose length is a multiple of 20. It is to be subdivided into strings of length 20, each of which is the SHA1 hash of the piece at the corresponding index.
infoPieces :: t -> [ByteString]
infoPieces mi =
let f bs
| (bs == BS.empty) = []
| (BS.length bs >= 20) = (BS.take 20 bs) : f (BS.drop 20 bs)
| otherwise = error $ "found invalid piece of length: " ++ show (BS.length bs)
in f $ beString' . fromJust . Map.lookup "pieces" $ info mi
-- | If length is present then the download represents a single file, otherwise it represents a set of files which go in a directory structure.
infoLength :: t -> Maybe Integer
infoLength m = case (Map.lookup "length" $ info m) of
Nothing -> Nothing
Just d -> Just $ beInteger d
infoFiles :: t -> Maybe (Map FilePath Integer)
-- | For the purposes of the other keys, the multi-file case is treated as only having a single file by concatenating the files in the order they appear in the files list. The files list is the value files maps to, and is a list of dictionaries containing the following keys: 'length', 'path'.
infoFiles m = case (infoFilesL m) of
Nothing -> Nothing
Just d -> Just $ Map.fromList d
infoFilesL :: t -> Maybe [(FilePath, Integer)]
infoFilesL m = case (Map.lookup "files" $ info m) of
Nothing -> Nothing
Just d ->
let dds = map beDictUTF8 $ beList d
dp x =
let ps = map beStringUTF8 $ beList $ fromJust $ Map.lookup "path" x
in FP.concat $ map decodeString ps
dl x = beInteger $ fromJust $ Map.lookup "length" x
in Just $ [(dp dd, dl dd)| dd <- dds]
infoLengthFiles :: t -> Either Integer (Map FilePath Integer)
infoLengthFiles m = case infoLengthFilesL m of
Left l -> Left l
Right fs -> Right $ Map.fromList fs
infoLengthFilesL :: t -> Either Integer [(FilePath, Integer)]
infoLengthFilesL m =
let l = infoLength m
fs = infoFilesL m
i = info m
lfs = (l,fs)
in case lfs of
(Nothing, Nothing) -> error $ "unable to lookup either 'length' or 'files' in: " ++ show i
(Just l', Nothing) -> Left l'
(Nothing, Just fs') -> Right fs'
(Just _, Just _) -> error $ "error, both 'length' and 'files' in: " ++ show i
type PieceID = Integer
createDirectoryP = createDirectory True
instance (MetaInfo t) => MetaInfoConduits t
class (MetaInfo t) => MetaInfoConduits t where
metaInit :: t -> FilePath -> IO [Bool]
metaInit m dir = do
-- init the directory
createDirectoryP dir
let dir' = dir </> (decodeString $ infoName m)
let ioActions = case (infoLengthFilesL m) of
Left l -> do
setFileSize dir' l
Right fs ->
let fileA (f,l) = do
let fn = dir' </> f
createDirectoryP $ directory fn
setFileSize fn l
in do
_ <- sequence $ map fileA fs
return ()
catchIOError ioActions $ \e -> fail $ show e
let pcount = length . infoPieces $ m
sequence [pieceValid m dir (toInteger i) | i <- [0 .. (pcount - 1)]]
pieceValid :: t -> FilePath -> PieceID -> IO Bool
pieceValid m fp i = runResourceT $ do
let (_, src) = pieceConduits m fp i
src $$ pieceValidator m i
pieceValidator :: (MonadResource m) => t -> PieceID -> Consumer ByteString m Bool
pieceValidator m i =
let p :: Either String SHA1
p = Ser.decode $ (infoPieces m) !! fromInteger i
in case (p) of
Left err -> do fail err
Right d -> do
d' <- (isolate $ fromInteger $ infoPieceLength m) =$= sinkHash
return $ d' == d
pieceConduits :: (MonadResource m) =>
t -> FilePath -> PieceID -> (Consumer ByteString m (), Producer m ByteString)
pieceConduits m fp i =
let pl = infoPieceLength m
i'' = pl * i
iName = (decodeString $ infoName m)
ps = findPieces i'' pl $ case (infoLengthFilesL m) of
Right fs' -> fs'
Left l -> [(iName, l)]
dir = case (infoLengthFilesL m) of
Right _ -> fp </> iName
Left _ -> fp
in (piecesSink dir ps, piecesSource dir ps)
piecesSink :: (MonadResource m) =>
FilePath -> [(FilePath, Integer, Integer)] -> Consumer ByteString m ()
piecesSink _ [] = return ()
piecesSink d ((fn, p, l):fs) =
let sink = sinkIOHandle $ openBin WriteMode p l (d </> fn)
in do
(isolate $ fromInteger l) =$= sink
piecesSink d fs
piecesSource :: (MonadResource m) =>
FilePath -> [(FilePath, Integer, Integer)] -> Producer m ByteString
piecesSource _ [] = return ()
piecesSource d ((fn, p, l):fs) =
let src = sourceIOHandle $ openBin ReadMode p l (d </> fn)
in do
src =$= (isolate $ fromInteger l)
piecesSource d fs
openBin :: IOMode -> Integer -> Integer -> FilePath -> IO Handle
openBin mode p l dir = do
h <- openBinaryFile (encodeString dir) mode
hSeek h AbsoluteSeek p
return h
findPieces :: Integer -> Integer -> [(FilePath, Integer)] -> [(FilePath, Integer, Integer)]
findPieces _ _ [] = []
findPieces p l ((fn, fl):fs) =
let pb = p < fl
pe = (p + l) < fl
in if (not pb)
then findPieces (p - fl) l fs
else (fn, p, l) :
if (pe) then []
else findPieces 0 (l - fl) fs
setFileSize :: FilePath -> Integer -> IO ()
setFileSize fp l = do
h <- openFile fp WriteMode;
hSetFileSize h l
hClose h;
|
alios/lcars2
|
Data/Torrent/MetaInfo.hs
|
bsd-3-clause
| 7,604 | 0 | 24 | 2,019 | 2,328 | 1,186 | 1,142 | 152 | 3 |
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NegativeLiterals #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | Tests for the flat module
module Main where
import Control.Monad
import Data.Bits
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Short as SBS
import Data.Char
import Data.Either
import Flat
import Flat.Bits
import Flat.Decoder
import qualified Flat.Encoder as E
import qualified Flat.Encoder.Prim as E
import qualified Flat.Encoder.Strict as E
import Data.Int
import Data.Proxy
import qualified Data.Sequence as Seq
import Data.String (fromString)
import qualified Data.Text as T
import Data.Word
import Numeric.Natural
import System.Exit
import Test.Data
import Test.Data.Arbitrary ()
import Test.Data.Flat
import Test.Data.Values hiding (lbs, ns)
import Test.E
import Test.E.Arbitrary ()
import Test.E.Flat
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck as QC hiding (getSize)
import Flat.Endian
import Data.FloatCast
import Data.Text.Arbitrary
-- import Test.QuickCheck.Arbitrary
import qualified Data.Complex as B
import qualified Data.Ratio as B
import qualified Data.Map as C
import qualified Data.Map.Strict as CS
import qualified Data.Map.Lazy as CL
import qualified Data.IntMap.Strict as CS
import qualified Data.IntMap.Lazy as CL
-- import Data.List
-- import Data.Ord
#if MIN_VERSION_base(4,9,0)
import qualified Data.List.NonEmpty as BI
#endif
instance Arbitrary UTF8Text where
arbitrary = UTF8Text <$> arbitrary
shrink t = UTF8Text <$> shrink (unUTF8 t)
#if! defined(ghcjs_HOST_OS) && ! defined (ETA_VERSION)
instance Arbitrary UTF16Text where
arbitrary = UTF16Text <$> arbitrary
shrink t = UTF16Text <$> shrink (unUTF16 t)
#endif
-- instance Flat [Int16]
-- instance Flat [Word8]
-- instance Flat [Bool]
main = do
-- #ifdef ghcjs_HOST_OS
-- print "GHCJS"
-- #endif
-- printInfo
-- print $ flat asciiStrT
mainTest
-- print $ flatRaw 18446744073709551615::Word64
-- print $ B.unpack . flat $ (True,0::Word64,18446744073709551615::Word64)
-- print (2^56::Word64,fromIntegral (1::Word8) `shiftL` 56 :: Word64,(18446744073709551615::Word64) `shiftR` 1)
-- mainShow
-- eWord64E id 0b
mainShow = do
mapM_ (\_ -> generate (arbitrary :: Gen Int) >>= print) [1 .. 10]
exitFailure
mainTest = defaultMain tests
tests :: TestTree
tests = testGroup "Tests" [testPrimitives, testEncDec, testFlat]
testPrimitives =
testGroup "conversion/memory primitives" [testEndian, testFloatingConvert]
--,testShifts -- ghcjs fails this
testEncDec = testGroup
"encode/decode primitives"
[ testEncodingPrim
, testDecodingPrim
#ifdef TEST_DECBITS
, testDecBits
#endif
]
testFlat = testGroup
"flat/unflat"
[testSize, testLargeEnum, testContainers, flatUnflatRT, flatTests]
-- Flat.Endian tests (to run, need to modify imports and cabal file)
testEndian = testGroup
"Endian"
[ convBE toBE16 (2 ^ 10 + 3) (2 ^ 9 + 2 ^ 8 + 4)
, convBE toBE32 (2 ^ 18 + 3) 50332672
, convBE toBE64 (2 ^ 34 + 3) 216172782180892672
, convBE toBE16 0x1234 0x3412
, convBE toBE32 0x11223344 0x44332211
, convBE toBE64 0x0123456789ABCDEF 0xEFCDAB8967452301]
testFloatingConvert = testGroup
"Floating conversions"
[ conv floatToWord (-0.15625) 3189768192
, conv wordToFloat 3189768192 (-0.15625)
, conv doubleToWord (-0.15625) 13818169556679524352
, conv wordToDouble 13818169556679524352 (-0.15625)
, rt "floatToWord" (prop_float_conv :: RT Float)
, rt "doubleToWord" (prop_double_conv :: RT Double)]
convBE f v littleEndianE =
let e = if isBigEndian
then v
else littleEndianE
in testCase (unwords ["conv BigEndian", sshow v, "to", sshow e]) $ f v @?= e
conv f v e = testCase
(unwords ["conv", sshow v, showB . flat $ v, "to", sshow e])
$ f v @?= e
-- ghcjs bug on shiftR 0, see: https://github.com/ghcjs/ghcjs/issues/706
testShifts = testGroup "Shifts" $ map tst [0 .. 33]
where
tst n = testCase ("shiftR " ++ show n)
$ let val = 4294967295 :: Word32
s = val `shift` (-n)
r = val `shiftR` n
in r @?= s
-- shR = shiftR
-- shR = unsafeShiftR
shR val 0 = val
shR val n = shift val (-n)
testEncodingPrim = testGroup
"Encoding Primitives"
[ encRawWith 1 E.eTrueF [0b10000001]
, encRawWith 3 (E.eTrueF >=> E.eFalseF >=> E.eTrueF) [0b10100001]
-- Depends on endianess
--,encRawWith 32 (E.eWord32E id $ 2^18 + 3) [3,0,4,0,1]
-- ,encRawWith 64 (E.eWord64E id $ 0x1122334455667788) [0x88,0x77,0x66,0x55,0x44,0x33,0x22,0x11,1]
--,encRawWith 65 (E.eTrueF >=> E.eWord64E id (2^34 + 3)) [1,0,0,0,2,0,0,128,129]
--,encRawWith 65 (E.eFalseF >=> E.eWord64E id (2^34 + 3)) [1,0,0,0,2,0,0,0,129]
-- Big Endian
, encRawWith 32 (E.eWord32BEF $ 2 ^ 18 + 3) [0, 4, 0, 3, 1]
, encRawWith 64 (E.eWord64BEF $ 2 ^ 34 + 3) [0, 0, 0, 4, 0, 0, 0, 3, 1]
, encRawWith
65
(E.eTrueF >=> E.eWord64BEF (2 ^ 34 + 3))
[128, 0, 0, 2, 0, 0, 0, 1, 129]
, encRawWith
65
(E.eFalseF >=> E.eWord64BEF (2 ^ 34 + 3))
[0, 0, 0, 2, 0, 0, 0, 1, 129]]
where
encRawWith sz enc exp = testCase
(unwords ["encode raw with size", show sz])
$ flatRawWith sz enc @?= exp
testDecodingPrim = testGroup
"Decoding Primitives"
[ dec
((,,,) <$> dropBits 13 <*> dBool <*> dBool <*> dBool)
[0b10111110, 0b10011010]
((), False, True, False)
, dec
((,,,) <$> dropBits 1 <*> dBE16 <*> dBool <*> dropBits 6)
[0b11000000, 0b00000001, 0b01000000]
((), 2 ^ 15 + 2, True, ())
, dec
((,,,) <$> dropBits 1 <*> dBE32 <*> dBool <*> dropBits 6)
[0b11000000, 0b00000000, 0b00000000, 0b00000001, 0b01000000]
((), 2 ^ 31 + 2, True, ())
, dec
dBE64
[ 0b10000000
, 0b00000000
, 0b00000000
, 0b00000000
, 0b00000000
, 0b00000000
, 0b00000000
, 0b00000010]
(2 ^ 63 + 2)
, dec
((,,,) <$> dropBits 1 <*> dBE64 <*> dBool <*> dropBits 6)
[ 0b11000000
, 0b00000000
, 0b00000000
, 0b00000000
, 0b00000000
, 0b00000000
, 0b00000000
, 0b00000001
, 0b01000000]
((), 2 ^ 63 + 2, True, ())]
where
dec decOp v e = testCase (unwords ["decode", sshow v])
$ unflatRawWith decOp (B.pack v) @?= Right e
testDecBits = testGroup "Decode Bits"
$ concat
[ decBitsN dBEBits8
, decBitsN dBEBits16
, decBitsN dBEBits32
, decBitsN dBEBits64]
-- Test dBEBits8/16/32/64, extraction of up to 8/16/32/bits from various positions
where
decBitsN :: forall a.
(Num a, FiniteBits a, Show a, Flat a)
=> (Int -> Get a)
-> [TestTree]
decBitsN dec = let s = finiteBitSize (undefined :: a)
in [decBits_ dec val numBitsToTake pre
| numBitsToTake <- [0 .. s]
, val <- [ 0 :: a
, 1 + 2 ^ (s - 2) + 2 ^ (s - 5)
, fromIntegral $ (2 ^ s :: Integer) - 1]
, pre <- [0, 1, 7]]
decBits_ :: forall a.
(FiniteBits a, Show a, Flat a)
=> (Int -> Get a)
-> a
-> Int
-> Int
-> TestTree
decBits_ deco val numBitsToTake pre =
-- a sequence composed by pre zero bits followed by the val and zero bits till the next byte boundary
let vs = B.pack . asBytes . fromBools
$ replicate pre False ++ toBools (asBits val)
len = B.length vs
sz = finiteBitSize (undefined :: a)
dec :: Get a
dec = do
dropBits pre
r <- deco numBitsToTake
dropBits (len * 8 - numBitsToTake - pre)
return r
-- we expect the first numBitsToTake bits of the value
expectedD@(Right expected) :: Decoded a = Right
$ val `shR` (sz - numBitsToTake) -- ghcjs: shiftR fails, see: https://github.com/ghcjs/ghcjs/issues/706
actualD@(Right actual) :: Decoded a = unflatRawWith dec vs
in testCase
(unwords
[ "take"
, show numBitsToTake
, "bits from"
, show val
, "of size"
, show sz
, "with prefix"
, show pre
, "sequence"
, showB vs
, show expected
, show actual
, show $ val == actual
, show $ expected == actual
, show $ expected /= actual
, show $ show expected == show actual
, show $ flat expected == flat actual])
$ actualD @?= expectedD
testSize = testGroup "Size"
$ concat
[ sz () 0
, sz True 1
, sz One 2
, sz Two 2
, sz Three 2
, sz Four 3
, sz Five 3
, sz 'a' 8
, sz 'à' 16
, sz '经' 24
, sz (0 :: Word8) 8
, sz (1 :: Word8) 8
, concatMap (uncurry sz) ns
, concatMap (uncurry sz) nsI
, concatMap (uncurry sz) nsII
, sz (1.1 :: Float) 32
, sz (1.1 :: Double) 64
, sz "" 1
, sz "abc" (4 + 3 * 8)
, sz ((), (), Unit) 0
, sz (True, False, One, Five) 7
, sz map1 7
, sz bs (4 + 3 * 8)
, sz stBS bsSize
, sz lzBS bsSize
#ifndef ghcjs_HOST_OS
, sz shBS bsSize
#endif
, sz tx utf8Size
, sz (UTF8Text tx) utf8Size
#if! defined(ghcjs_HOST_OS) && ! defined (ETA_VERSION)
, sz (UTF16Text tx) utf16Size
#endif
]
where
tx = T.pack "txt"
utf8Size = 8 + 8 + 3 * 32 + 8
utf16Size = 8 + 8 + 3 * 16 + 8
bsSize = 8 + 8 + 3 * 8 + 8
sz v e = [testCase (unwords ["size of", sshow v]) $ getSize v @?= e]
-- E258_256 = 11111110 _257 = 111111110 _258 = 111111111
testLargeEnum = testGroup "test enum with more than 256 constructors"
$ concat
[
#ifdef ENUM_LARGE
sz E258_256 8
, sz E258_257 9
, sz E258_258 9
-- As encodes are inlined, this is going to take for ever if this is compiled with -O1 or -O2
-- , encRaw (E258_256) [0b11111110]
-- , encRaw (E258_257) [0b11111111,0b00000000]
-- , encRaw (E258_258) [0b11111111,0b10000000]
-- , encRaw (E258_256,E258_257,E258_258) [0b11111110,0b11111111,0b01111111,0b11000000]
, map trip [E258_1, E258_256, E258_257, E258_258]
, map trip [E256_1, E256_134, E256_256]
#endif
]
testContainers =
testGroup "containers" [trip longSeq, trip dataMap, trip listMap]
-- , trip intMap
flatUnflatRT = testGroup
"unflat (flat v) == v"
[ rt "()" (prop_Flat_roundtrip :: RT ())
, rt "Bool" (prop_Flat_roundtrip :: RT Bool)
, rt "Char" (prop_Flat_roundtrip :: RT Char)
, rt "Complex" (prop_Flat_roundtrip :: RT (B.Complex Float))
, rt "Either N Bool" (prop_Flat_roundtrip :: RT (Either N Bool))
, rt "Either Int Char" (prop_Flat_roundtrip :: RT (Either Int Char))
, rt "Int8" (prop_Flat_Large_roundtrip :: RTL Int8)
, rt "Int16" (prop_Flat_Large_roundtrip :: RTL Int16)
, rt "Int32" (prop_Flat_Large_roundtrip :: RTL Int32)
, rt "Int64" (prop_Flat_Large_roundtrip :: RTL Int64)
, rt "Int" (prop_Flat_Large_roundtrip :: RTL Int)
, rt "[Int16]" (prop_Flat_roundtrip :: RT [Int16])
, rt "String" (prop_Flat_roundtrip :: RT String)
#if MIN_VERSION_base(4,9,0)
, rt "NonEmpty" (prop_Flat_roundtrip :: RT (BI.NonEmpty Bool))
#endif
, rt "Maybe N" (prop_Flat_roundtrip :: RT (Maybe N))
, rt "Ratio" (prop_Flat_roundtrip :: RT (B.Ratio Int32))
, rt "Word8" (prop_Flat_Large_roundtrip :: RTL Word8)
, rt "Word16" (prop_Flat_Large_roundtrip :: RTL Word16)
, rt "Word32" (prop_Flat_Large_roundtrip :: RTL Word32)
, rt "Word64" (prop_Flat_Large_roundtrip :: RTL Word64)
, rt "Word" (prop_Flat_Large_roundtrip :: RTL Word)
, rt "Natural" (prop_Flat_roundtrip :: RT Natural)
, rt "Integer" (prop_Flat_roundtrip :: RT Integer)
, rt "Float" (prop_Flat_roundtrip :: RT Float)
, rt "Double" (prop_Flat_roundtrip :: RT Double)
, rt "Text" (prop_Flat_roundtrip :: RT T.Text)
, rt "UTF8 Text" (prop_Flat_roundtrip :: RT UTF8Text)
#if! defined(ghcjs_HOST_OS) && ! defined (ETA_VERSION)
, rt "UTF16 Text" (prop_Flat_roundtrip :: RT UTF16Text)
#endif
, rt "ByteString" (prop_Flat_roundtrip :: RT B.ByteString)
, rt "Lazy ByteString" (prop_Flat_roundtrip :: RT L.ByteString)
#ifndef ghcjs_HOST_OS
, rt "Short ByteString" (prop_Flat_roundtrip :: RT SBS.ShortByteString)
#endif
, rt "Map.Strict" (prop_Flat_roundtrip :: RT (CS.Map Int Bool))
, rt "Map.Lazy" (prop_Flat_roundtrip :: RT (CL.Map Int Bool))
, rt "IntMap.Strict" (prop_Flat_roundtrip :: RT (CS.IntMap Bool))
, rt "IntMap.Lazy" (prop_Flat_roundtrip :: RT (CL.IntMap Bool))
, rt "Unit" (prop_Flat_roundtrip :: RT Unit)
, rt "Un" (prop_Flat_roundtrip :: RT Un)
, rt "N" (prop_Flat_roundtrip :: RT N)
, rt "E2" (prop_Flat_roundtrip :: RT E2)
, rt "E3" (prop_Flat_roundtrip :: RT E3)
, rt "E4" (prop_Flat_roundtrip :: RT E4)
, rt "E8" (prop_Flat_roundtrip :: RT E8)
, rt "E16" (prop_Flat_roundtrip :: RT E16)
, rt "E17" (prop_Flat_roundtrip :: RT E17)
, rt "E32" (prop_Flat_roundtrip :: RT E32)
, rt "A" (prop_Flat_roundtrip :: RT A)
, rt "B" (prop_Flat_roundtrip :: RT B)
-- ,rt "Tree Bool" (prop_Flat_roundtrip:: RT (Tree Bool))
-- ,rt "Tree N" (prop_Flat_roundtrip:: RT (Tree N))
, rt "List N" (prop_Flat_roundtrip :: RT (List N))]
rt n = QC.testProperty (unwords ["round trip", n])
flatTests = testGroup "flat/unflat Unit tests"
$ concat
[ -- Expected errors
errDec (Proxy :: Proxy Bool) [] -- no data
, errDec (Proxy :: Proxy Bool) [128] -- no filler
, errDec (Proxy :: Proxy Bool) [128 + 1, 1, 2, 4, 8] -- additional bytes
, errDec (Proxy :: Proxy Text) (B.unpack (flat ((fromString "\x80") :: B.ByteString))) -- invalid UTF-8
, encRaw () []
, encRaw ((), (), Unit) []
, encRaw (Unit, 'a', Unit, 'a', Unit, 'a', Unit) [97, 97, 97]
, a () [1]
, a True [128 + 1]
, a (True, True) [128 + 64 + 1]
, a (True, False, True) [128 + 32 + 1]
, a (True, False, True, True) [128 + 32 + 16 + 1]
, a (True, False, True, True, True) [128 + 32 + 16 + 8 + 1]
, a (True, False, True, True, True, True) [128 + 32 + 16 + 8 + 4 + 1]
, a
(True, False, True, True, True, True, True)
[128 + 32 + 16 + 8 + 4 + 2 + 1]
, a
(True, False, True, True, (True, True, True, True))
[128 + 32 + 16 + 8 + 4 + 2 + 1, 1]
, encRaw (True, False, True, True) [128 + 32 + 16]
, encRaw
( (True, True, False, True, False)
, (False, False, True, False, True, True))
[128 + 64 + 16 + 1, 64 + 32]
, encRaw ('\0', '\1', '\127') [0, 1, 127]
, encRaw (33 :: Word32, 44 :: Word32) [33, 44]
--,s (Elem True) [64]
--,s (NECons True (NECons False (Elem True))) [128+64+32+4]
, encRaw (0 :: Word8) [0]
, encRaw (1 :: Word8) [1]
, encRaw (255 :: Word8) [255]
, encRaw (0 :: Word16) [0]
, encRaw (1 :: Word16) [1]
, encRaw (255 :: Word16) [255, 1]
, encRaw (256 :: Word16) [128, 2]
, encRaw (65535 :: Word16) [255, 255, 3]
, encRaw (127 :: Word32) [127]
, encRaw (128 :: Word32) [128, 1]
, encRaw (129 :: Word32) [129, 1]
, encRaw (255 :: Word32) [255, 1]
, encRaw (16383 :: Word32) [255, 127]
, encRaw (16384 :: Word32) [128, 128, 1]
, encRaw (16385 :: Word32) [129, 128, 1]
, encRaw (32767 :: Word32) [255, 255, 1]
, encRaw (32768 :: Word32) [128, 128, 2]
, encRaw (32769 :: Word32) [129, 128, 2]
, encRaw (65535 :: Word32) [255, 255, 3]
, encRaw (2097151 :: Word32) [255, 255, 127]
, encRaw (2097152 :: Word32) [128, 128, 128, 1]
, encRaw (2097153 :: Word32) [129, 128, 128, 1]
, encRaw (4294967295 :: Word32) [255, 255, 255, 255, 15]
, encRaw (255 :: Word64) [255, 1]
, encRaw (65535 :: Word64) [255, 255, 3]
, encRaw (4294967295 :: Word64) [255, 255, 255, 255, 15]
, encRaw
(18446744073709551615 :: Word64)
[255, 255, 255, 255, 255, 255, 255, 255, 255, 1]
, encRaw
(False, 18446744073709551615 :: Word64)
[127, 255, 255, 255, 255, 255, 255, 255, 255, 128, 128]
, encRaw (255 :: Word) [255, 1]
, encRaw (65535 :: Word) [255, 255, 3]
, encRaw (4294967295 :: Word) [255, 255, 255, 255, 15]
, tstI [0 :: Int8, 2, -2]
, encRaw (127 :: Int8) [254]
, encRaw (-128 :: Int8) [255]
, tstI [0 :: Int16, 2, -2, 127, -128]
, tstI [0 :: Int32, 2, -2, 127, -128]
, tstI [0 :: Int64, 2, -2, 127, -128]
, encRaw (-1024 :: Int64) [255, 15]
, encRaw (maxBound :: Word8) [255]
, encRaw (True, maxBound :: Word8) [255, 128]
, encRaw (maxBound :: Word16) [255, 255, 3]
, encRaw (True, maxBound :: Word16) [255, 255, 129, 128]
, encRaw (maxBound :: Word32) [255, 255, 255, 255, 15]
, encRaw (True, maxBound :: Word32) [255, 255, 255, 255, 135, 128]
, encRaw
(maxBound :: Word64)
[255, 255, 255, 255, 255, 255, 255, 255, 255, 1]
, encRaw
(True, maxBound :: Word64)
[255, 255, 255, 255, 255, 255, 255, 255, 255, 128, 128]
, encRaw
(minBound :: Int64)
[255, 255, 255, 255, 255, 255, 255, 255, 255, 1]
, encRaw
(maxBound :: Int64)
[254, 255, 255, 255, 255, 255, 255, 255, 255, 1]
, tstI [0 :: Int, 2, -2, 127, -128]
, tstI [0 :: Integer, 2, -2, 127, -128, -256, -512]
, encRaw (-1024 :: Integer) [255, 15]
, encRaw (0 :: Float) [0, 0, 0, 0]
, encRaw (-2 :: Float) [0b11000000, 0, 0, 0]
, encRaw (0.085 :: Float) [0b00111101, 0b10101110, 0b00010100, 0b01111011]
, encRaw (0 :: Double) [0, 0, 0, 0, 0, 0, 0, 0]
, encRaw (-2 :: Double) [0b11000000, 0, 0, 0, 0, 0, 0, 0]
, encRaw (23 :: Double) [0b01000000, 0b00110111, 0, 0, 0, 0, 0, 0]
, encRaw (-0.15625 :: Float) [0b10111110, 0b00100000, 0, 0]
, encRaw (-0.15625 :: Double) [0b10111111, 0b11000100, 0, 0, 0, 0, 0, 0]
, encRaw
(-123.2325E-23 :: Double)
[ 0b10111011
, 0b10010111
, 0b01000111
, 0b00101000
, 0b01110101
, 0b01111011
, 0b01000111
, 0b10111010]
, encRaw (Left True :: Either Bool (Double, Double)) [0b01000000]
, encRaw (-2.1234E15 :: Double) [195, 30, 44, 226, 90, 221, 64, 0]
, encRaw (1.1234E-22 :: Double) [59, 96, 249, 241, 120, 219, 249, 174]
, encRaw
((False, -2.1234E15) :: (Bool, Double))
[97, 143, 22, 113, 45, 110, 160, 0, 0]
, encRaw
((True, -2.1234E15) :: (Bool, Double))
[225, 143, 22, 113, 45, 110, 160, 0, 0]
, encRaw ((-2.1234E15, 1.1234E-22) :: (Double, Double))
$ [0b11000011, 30, 44, 226, 90, 221, 64, 0]
++ [59, 96, 249, 241, 120, 219, 249, 174]
, encRaw
((True, -2.1234E15, 1.1234E-22) :: (Bool, Double, Double))
[ 0b11100001
, 143
, 22
, 113
, 45
, 110
, 160
, 0
, 29
, 176
, 124
, 248
, 188
, 109
, 252
, 215
, 0]
, encRaw
(Right (-2.1234E15, 1.1234E-22) :: Either Bool (Double, Double))
[ 0b11100001
, 143
, 22
, 113
, 45
, 110
, 160
, 0
, 29
, 176
, 124
, 248
, 188
, 109
, 252
, 215
, 0]
, encRaw (Left True :: Either Bool Direction) [0b01000000]
, encRaw (Right West :: Either Bool Direction) [0b11110000]
, map trip [minBound, maxBound :: Word8]
, map trip [minBound, maxBound :: Word16]
, map trip [minBound, maxBound :: Word32]
, map trip [minBound, maxBound :: Word64]
, map trip [minBound :: Int8, maxBound :: Int8]
, map trip [minBound :: Int16, maxBound :: Int16]
, map trip [minBound :: Int32, maxBound :: Int32]
, map trip [minBound :: Int64, maxBound :: Int64]
, map tripShow [0 :: Float, -0 :: Float, 0 / 0 :: Float, 1 / 0 :: Float]
, map
tripShow
[0 :: Double, -0 :: Double, 0 / 0 :: Double, 1 / 0 :: Double]
, encRaw '\0' [0]
, encRaw '\1' [1]
, encRaw '\127' [127]
, encRaw 'a' [97]
, encRaw 'à' [224, 1]
, encRaw '经' [207, 253, 1]
, [trip [chr 0x10FFFF]]
, encRaw Unit []
, encRaw (Un False) [0]
, encRaw (One, Two, Three) [16 + 8]
, encRaw (Five, Five, Five) [255, 128]
--,s (NECons True (Elem True)) [128+64+16]
, encRaw "" [0]
#ifdef LIST_BIT
, encRaw "abc" [176, 216, 172, 96]
, encRaw [False, True, False, True] [128 + 32 + 16 + 8 + 2 + 1, 0]
#elif defined(LIST_BYTE)
, s "abc" s3
, s (cs 600) s600
#endif
-- Aligned structures
--,s (T.pack "") [1,0]
--,s (Just $ T.pack "abc") [128+1,3,97,98,99,0]
--,s (T.pack "abc") (al s3)
--,s (T.pack $ cs 600) (al s600)
, encRaw map1 [0b10111000]
, encRaw (B.pack $ csb 3) (bsl c3)
, encRaw (B.pack $ csb 600) (bsl s600)
, encRaw (L.pack $ csb 3) (bsl c3)
-- Long LazyStrings can have internal sections shorter than 255
--,s (L.pack $ csb 600) (bsl s600)
, [trip [1 .. 100 :: Int16]]
-- See https://github.com/typelead/eta/issues/901
#ifndef ETA_VERSION
, [trip longAsciiStrT]
, [trip longBoolListT]
#endif
, [trip asciiTextT]
, [trip english]
, [trip "维护和平正"]
, [trip (T.pack "abc")]
, [trip unicodeText]
, [trip unicodeTextUTF8T]
, [trip longBS, trip longLBS]
#ifndef ghcjs_HOST_OS
, [trip longSBS]
#endif
#if! defined(ghcjs_HOST_OS) && ! defined (ETA_VERSION)
, [trip unicodeTextUTF16T]
#endif
]
--al = (1:) -- prealign
where
bsl = id -- noalign
tstI = map ti
ti v
| v >= 0 = testCase (unwords ["Int", show v])
$ teq v (2 * fromIntegral v :: Word64)
| otherwise = testCase (unwords ["Int", show v])
$ teq v (2 * fromIntegral (-v) - 1 :: Word64)
teq a b = ser a @?= ser b
--,testCase (unwords ["unflat raw",sshow v]) $ desRaw e @?= Right v]
-- Aligned values unflat to the original value, modulo the added filler.
a v e = [ testCase (unwords ["flat", sshow v]) $ ser v @?= e
, testCase (unwords ["unflat", sshow v])
$ let Right v' = des e
in v @?= v']
-- a v e = [testCase (unwords ["flat postAligned",show v]) $ ser (postAligned v) @?= e
-- ,testCase (unwords ["unflat postAligned",show v]) $ let Right (PostAligned v' _) = des e in v @?= v']
encRaw :: forall a. (Show a, Flat a) => a -> [Word8] -> [TestTree]
encRaw v e =
[ testCase (unwords ["flat raw", sshow v, show . B.unpack . flat $ v])
$ serRaw v @?= e]
trip :: forall a. (Show a, Flat a, Eq a) => a -> TestTree
trip v = testCase (unwords ["roundtrip", sshow v])
$
-- direct comparison
(unflat (flat v :: B.ByteString) :: Decoded a) @?= (Right v :: Decoded a)
tripShow :: forall a. (Show a, Flat a, Eq a) => a -> TestTree
tripShow v = testCase (unwords ["roundtrip", sshow v])
$
-- we use show to get Right NaN == Right NaN
show (unflat (flat v :: B.ByteString) :: Decoded a)
@?= show (Right v :: Decoded a)
-- Test Data
lzBS = L.pack bs
stBS = B.pack bs
bs = [32, 32, 32 :: Word8]
s3 = [3, 97, 98, 99, 0]
c3a = [3, 99, 99, 99, 0] -- Array Word8
c3 = pre c3a
s600 = pre s600a
pre = (1:)
s600a = concat [[255], csb 255, [255], csb 255, [90], csb 90, [0]]
s600B =
concat [[55], csb 55, [255], csb 255, [90], csb 90, [200], csb 200, [0]]
longSeq :: Seq.Seq Word8
longSeq = Seq.fromList lbs
longBS = B.pack lbs
longLBS = L.concat $ concat $ replicate 10 [L.pack lbs]
lbs = concat $ replicate 100 [234, 123, 255, 0]
cs n = replicate n 'c' -- take n $ cycle ['a'..'z']
csb = map (fromIntegral . ord) . cs
map1 = C.fromList [(False, True), (True, False)]
ns :: [(Word64, Int)]
ns = [((-) (2 ^ (i * 7)) 1, fromIntegral (8 * i)) | i <- [1 .. 10]]
nsI :: [(Int64, Int)]
nsI = nsI_
nsII :: [(Integer, Int)]
nsII = nsI_
nsI_ = [((-) (2 ^ (((-) i 1) * 7)) 1, fromIntegral (8 * i)) | i <- [1 .. 10]]
#ifndef ghcjs_HOST_OS
shBS = SBS.toShort stBS
longSBS = SBS.toShort longBS
#endif
sshow = take 80 . show
showB = show . B.unpack
errDec :: forall a. (Flat a, Eq a, Show a) => Proxy a -> [Word8] -> [TestTree]
--errDec _ bs = [testCase "bad decode" $ let ev = (des bs::Decoded a) in ev @?= Left ""]
errDec _ bs = [ testCase "bad decode"
$ let ev = (des bs :: Decoded a)
in isRight ev @?= False]
ser :: Flat a => a -> [Word8]
ser = B.unpack . flat
des :: Flat a => [Word8] -> Decoded a
des = unflat
flatRawWith sz enc = B.unpack
$ E.strictEncoder (sz + 8) (E.Encoding $ enc >=> E.eFillerF)
serRaw :: Flat a => a -> [Word8]
-- serRaw = B.unpack . flatRaw
-- serRaw = L.unpack . flatRaw
serRaw = asBytes . bits
--desRaw :: Flat a => [Word8] -> Decoded a
--desRaw = unflatRaw . L.pack
type RT a = a -> Bool
type RTL a = Large a -> Bool
prop_Flat_roundtrip :: (Flat a, Eq a) => a -> Bool
prop_Flat_roundtrip = roundTripExt
prop_Flat_Large_roundtrip :: (Eq b, Flat b) => Large b -> Bool
prop_Flat_Large_roundtrip (Large x) = roundTripExt x
roundTrip x = unflat (flat x :: B.ByteString) == Right x
-- Test roundtrip for both the value and the value embedded between bools
roundTripExt x = roundTrip x && roundTrip (True, x, False)
prop_double_conv d = wordToDouble (doubleToWord d) == d
prop_float_conv d = wordToFloat (floatToWord d) == d
{-
prop_common_unsigned :: (Num l,Num h,Flat l,Flat h) => l -> h -> Bool
prop_common_unsigned n _ = let n2 :: h = fromIntegral n
in flat n == flat n2
-}
-- e :: Stream Bool
-- e = unflatIncremental . flat $ stream1
-- el :: List Bool
-- el = unflatIncremental . flat $ infList
-- deflat = unflat
-- b1 :: BLOB UTF8
-- b1 = BLOB UTF8 (preAligned (List255 [97,98,99]))
-- -- b1 = BLOB (preAligned (UTF8 (List255 [97,98,99])))
|
tittoassini/flat
|
test/Spec.hs
|
bsd-3-clause
| 26,353 | 0 | 17 | 7,393 | 9,095 | 5,170 | 3,925 | 56 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DataKinds #-}
module Main ( main ) where
import GHC.Generics (Generic)
import Control.Monad (void)
import Control.Monad.Fix (MonadFix)
import Control.Applicative ((<*>), (<$>))
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy.Char8 as L8
import Data.ByteString (ByteString)
import Data.Proxy
import Data.Hex (hex, unhex)
import qualified Data.Map as M
import qualified Data.Text as T
import Data.Text (Text)
import Data.Map (Map, fromList)
import Data.Monoid ((<>))
import Data.Maybe
import Reflex.Dom.Core
import Reflex.Dom.SemanticUI
import Reflex.Dom.Path
import Servant.API
import Servant.Reflex
import Servant.Reflex.Multi
import Safe (readMay)
import Zero.Argon2 (Hash(..), Options(..), performCredentialsHash, performHash, credentialsFromHash, defaultOptions)
import Zero.GHCJS
import Zero.View (View(..))
import Zero.Index (Index(..))
import Zero.Authentication.Internal
import Zero.Identification.API
import Zero.Identification.Internal (Certificate(..), buildIdentityAssertion)
import Zero.Identification.Client
import Zero.SessionToken.Internal
import Zero.KeyFetchToken.Internal (KeyFetchState(..))
import Zero.KeyFetchToken.Client
import Zero.Settings.Client (baseUrl)
import Zero.Sjcl.BitArray
import qualified Zero.Sjcl.BitArray as BitArray
import Zero.Token
import Zero.Navigation
import Zero.Widget
import Zero.Registration.Widget
import Zero.Verification.Widget
import Zero.Authentication.Widget
import Zero.Account.Profile.Widget
------------------------------------------------------------------------------
routePath :: forall t m. (
SupportsServantReflex t m
, MonadWidget t m
) => Behavior t (Maybe WidgetState) -> Route -> m (Event t Route, Event t WidgetState)
routePath bhRouteEvent RegistrationRoute =
registrationLayout
routePath bhRouteEvent VerificationRoute =
verificationLayout bhRouteEvent
routePath bhRouteEvent AuthenticationRoute =
authenticationLayout
routePath bhRouteEvent ProfileRoute = do
(evRoute, evState) <- profileWidget bhRouteEvent
return ( (\_ -> ProfileRoute) <$> evRoute
, ProfileRouteState <$> evState
)
------------------------------------------------------------------------------
main :: IO ()
main = do
mainWidgetWithCss (B8.pack $ T.unpack semanticCSS) $ run
run :: forall t m. ( SupportsServantReflex t m,
DomBuilder t m,
DomBuilderSpace m ~ GhcjsDomSpace,
MonadFix m,
PostBuild t m,
MonadHold t m,
MonadWidget t m
) => m ()
run = do
-- routeEventGen has type Dynamic t (Event t WidgetState), meaning
-- an event which changes the state of the next widget is produced
-- on creation of the pathWidget.
-- We extract the Event from the dynamic and freeze the value which
-- occurs in a behavior and then pass that to the next widget because
-- the event fires before the next widget has had the chance to load.
rec routeEventGen <- pathWidget (routePath bhRouteEvent)
let evRouteEvent = switchPromptlyDyn routeEventGen
bhRouteEvent <- hold Nothing (Just <$> evRouteEvent)
divClass "ui hidden divider" (return ())
footer
|
et4te/zero
|
frontend/Main.hs
|
bsd-3-clause
| 3,970 | 0 | 12 | 1,044 | 766 | 455 | 311 | 85 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.VertexBlend
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ARB/vertex_blend.txt ARB_vertex_blend> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.VertexBlend (
-- * Enums
gl_ACTIVE_VERTEX_UNITS_ARB,
gl_CURRENT_WEIGHT_ARB,
gl_MAX_VERTEX_UNITS_ARB,
gl_MODELVIEW0_ARB,
gl_MODELVIEW10_ARB,
gl_MODELVIEW11_ARB,
gl_MODELVIEW12_ARB,
gl_MODELVIEW13_ARB,
gl_MODELVIEW14_ARB,
gl_MODELVIEW15_ARB,
gl_MODELVIEW16_ARB,
gl_MODELVIEW17_ARB,
gl_MODELVIEW18_ARB,
gl_MODELVIEW19_ARB,
gl_MODELVIEW1_ARB,
gl_MODELVIEW20_ARB,
gl_MODELVIEW21_ARB,
gl_MODELVIEW22_ARB,
gl_MODELVIEW23_ARB,
gl_MODELVIEW24_ARB,
gl_MODELVIEW25_ARB,
gl_MODELVIEW26_ARB,
gl_MODELVIEW27_ARB,
gl_MODELVIEW28_ARB,
gl_MODELVIEW29_ARB,
gl_MODELVIEW2_ARB,
gl_MODELVIEW30_ARB,
gl_MODELVIEW31_ARB,
gl_MODELVIEW3_ARB,
gl_MODELVIEW4_ARB,
gl_MODELVIEW5_ARB,
gl_MODELVIEW6_ARB,
gl_MODELVIEW7_ARB,
gl_MODELVIEW8_ARB,
gl_MODELVIEW9_ARB,
gl_VERTEX_BLEND_ARB,
gl_WEIGHT_ARRAY_ARB,
gl_WEIGHT_ARRAY_POINTER_ARB,
gl_WEIGHT_ARRAY_SIZE_ARB,
gl_WEIGHT_ARRAY_STRIDE_ARB,
gl_WEIGHT_ARRAY_TYPE_ARB,
gl_WEIGHT_SUM_UNITY_ARB,
-- * Functions
glVertexBlendARB,
glWeightPointerARB,
glWeightbvARB,
glWeightdvARB,
glWeightfvARB,
glWeightivARB,
glWeightsvARB,
glWeightubvARB,
glWeightuivARB,
glWeightusvARB
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/ARB/VertexBlend.hs
|
bsd-3-clause
| 1,832 | 0 | 4 | 238 | 199 | 140 | 59 | 55 | 0 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
----------------------------------------------------------------------
-- Now, can we define pure and <*> so they work on indexed OR
-- non-indexed things? With clever use of type families, perhaps?
--
-- Hmmm... really not sure whether this is possible.
----------------------------------------------------------------------
-- this works...
type family AppClass (f :: k) :: k -> Constraint
type instance AppClass (f :: * -> *) = Applicative
type instance AppClass (f :: i -> * -> *) = IApplicative
-- ...but not sure how to make this work.
-- pure :: forall (f :: k -> *) (a :: *). AppClass f f => a -> f a
-- pure = undefined
-- Attempt #2, with type classes that dispatch on kind!
class Applicativey (f :: k) a b i j where
type AppC (f :: k) :: k -> Constraint
type PureType f a b :: *
type AppType f a b i j :: *
pure :: PureType f a b
(<*>) :: AppType f a b i j
instance Applicative f => Applicativey (f :: * -> *) (a :: *) (b :: *) i j where
type AppC f = Applicative
type PureType f a b = a -> f a
type AppType f a b i j = f (a -> b) -> f a -> f b
pure = P.pure
(<*>) = (P.<*>)
instance IApplicative f => Applicativey (f :: k -> * -> *) (a :: *) (b :: *) (i :: k) (j :: k) where
type AppC f = IApplicative
type PureType f a b = a -> f Id a
type AppType f a b i j = f i (a -> b) -> f j a -> f (i :*: j) b
pure = ipure
(<*>) = (<:*>)
-- The above type checks! But when I try to use it...
{-
<interactive>:106:1:
Could not deduce (AppType f0 a0 b0 i0 j0
~ (Maybe a1 -> Maybe a2 -> f a))
from the context (Functor f,
Num a,
Num a4,
Applicativey f1 a3 b i j,
AppType f1 a3 b i j ~ (Maybe a4 -> Maybe a5 -> f a))
bound by the inferred type for ‘it’:
(Functor f, Num a, Num a4, Applicativey f1 a3 b i j,
AppType f1 a3 b i j ~ (Maybe a4 -> Maybe a5 -> f a)) =>
f (a -> a)
at <interactive>:106:1-26
The type variables ‘f0’, ‘a0’, ‘b0’, ‘i0’, ‘j0’, ‘a1’, ‘a2’ are ambiguous
When checking that ‘it’ has the inferred type
it :: forall (f :: * -> *) a f1 a1 b i j a2 a3.
(Functor f, Num a, Num a2, Applicativey f1 a1 b i j,
AppType f1 a1 b i j ~ (Maybe a2 -> Maybe a3 -> f a)) =>
f (a -> a)
Probable cause: the inferred type is ambiguous
-}
|
byorgey/new-active
|
src/Control/IApplicative/Unified.hs
|
bsd-3-clause
| 2,961 | 0 | 10 | 898 | 473 | 279 | 194 | 34 | 0 |
{-
(c) The University of Glasgow, 1992-2006
Here we collect a variety of helper functions that construct or
analyse HsSyn. All these functions deal with generic HsSyn; functions
which deal with the instantiated versions are located elsewhere:
Parameterised by Module
---------------- -------------
RdrName parser/RdrHsSyn
Name rename/RnHsSyn
Id typecheck/TcHsSyn
-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
module HsUtils(
-- Terms
mkHsPar, mkHsApp, mkHsConApp, mkSimpleHsAlt,
mkSimpleMatch, unguardedGRHSs, unguardedRHS,
mkMatchGroup, mkMatchGroupName, mkMatch, mkHsLam, mkHsIf,
mkHsWrap, mkLHsWrap, mkHsWrapCo, mkHsWrapCoR, mkLHsWrapCo,
mkHsDictLet, mkHsLams,
mkHsOpApp, mkHsDo, mkHsComp, mkHsWrapPat, mkHsWrapPatCo,
mkLHsPar, mkHsCmdWrap, mkLHsCmdWrap, isLHsTypeExpr_maybe, isLHsTypeExpr,
nlHsTyApp, nlHsTyApps, nlHsVar, nlHsLit, nlHsApp, nlHsApps, nlHsSyntaxApps,
nlHsIntLit, nlHsVarApps,
nlHsDo, nlHsOpApp, nlHsLam, nlHsPar, nlHsIf, nlHsCase, nlList,
mkLHsTupleExpr, mkLHsVarTuple, missingTupArg,
toLHsSigWcType,
-- * Constructing general big tuples
-- $big_tuples
mkChunkified, chunkify,
-- Bindings
mkFunBind, mkVarBind, mkHsVarBind, mk_easy_FunBind, mkTopFunBind,
mkPatSynBind,
isInfixFunBind,
-- Literals
mkHsIntegral, mkHsFractional, mkHsIsString, mkHsString, mkHsStringPrimLit,
-- Patterns
mkNPat, mkNPlusKPat, nlVarPat, nlLitPat, nlConVarPat, nlConVarPatName, nlConPat,
nlConPatName, nlInfixConPat, nlNullaryConPat, nlWildConPat, nlWildPat,
nlWildPatName, nlWildPatId, nlTuplePat, mkParPat,
mkBigLHsVarTup, mkBigLHsTup, mkBigLHsVarPatTup, mkBigLHsPatTup,
-- Types
mkHsAppTy, mkHsAppTys, userHsTyVarBndrs, userHsLTyVarBndrs,
mkLHsSigType, mkLHsSigWcType, mkClassOpSigs,
nlHsAppTy, nlHsTyVar, nlHsFunTy, nlHsTyConApp,
-- Stmts
mkTransformStmt, mkTransformByStmt, mkBodyStmt, mkBindStmt, mkTcBindStmt,
mkLastStmt,
emptyTransStmt, mkGroupUsingStmt, mkGroupByUsingStmt,
emptyRecStmt, emptyRecStmtName, emptyRecStmtId, mkRecStmt,
-- Template Haskell
mkHsSpliceTy, mkHsSpliceE, mkHsSpliceTE, mkUntypedSplice,
mkHsQuasiQuote, unqualQuasiQuote,
-- Flags
noRebindableInfo,
-- Collecting binders
collectLocalBinders, collectHsValBinders, collectHsBindListBinders,
collectHsIdBinders,
collectHsBindsBinders, collectHsBindBinders, collectMethodBinders,
collectPatBinders, collectPatsBinders,
collectLStmtsBinders, collectStmtsBinders,
collectLStmtBinders, collectStmtBinders,
hsLTyClDeclBinders, hsTyClForeignBinders, hsPatSynBinders,
hsForeignDeclsBinders, hsGroupBinders, hsDataFamInstBinders,
-- Collecting implicit binders
lStmtsImplicits, hsValBindsImplicits, lPatImplicits
) where
#include "HsVersions.h"
import HsDecls
import HsBinds
import HsExpr
import HsPat
import HsTypes
import HsLit
import PlaceHolder
import TcEvidence
import RdrName
import Var
import TyCoRep
import Type ( filterOutInvisibleTypes )
import TysWiredIn ( unitTy )
import TcType
import DataCon
import Name
import NameSet
import BasicTypes
import SrcLoc
import FastString
import Util
import Bag
import Outputable
import Constants
import Data.Either
import Data.Function
import Data.List
{-
************************************************************************
* *
Some useful helpers for constructing syntax
* *
************************************************************************
These functions attempt to construct a not-completely-useless SrcSpan
from their components, compared with the nl* functions below which
just attach noSrcSpan to everything.
-}
mkHsPar :: LHsExpr id -> LHsExpr id
mkHsPar e = L (getLoc e) (HsPar e)
mkSimpleMatch :: [LPat id] -> Located (body id) -> LMatch id (Located (body id))
mkSimpleMatch pats rhs
= L loc $
Match NonFunBindMatch pats Nothing (unguardedGRHSs rhs)
where
loc = case pats of
[] -> getLoc rhs
(pat:_) -> combineSrcSpans (getLoc pat) (getLoc rhs)
unguardedGRHSs :: Located (body id) -> GRHSs id (Located (body id))
unguardedGRHSs rhs@(L loc _)
= GRHSs (unguardedRHS loc rhs) (noLoc emptyLocalBinds)
unguardedRHS :: SrcSpan -> Located (body id) -> [LGRHS id (Located (body id))]
unguardedRHS loc rhs = [L loc (GRHS [] rhs)]
mkMatchGroup :: Origin -> [LMatch RdrName (Located (body RdrName))]
-> MatchGroup RdrName (Located (body RdrName))
mkMatchGroup origin matches = MG { mg_alts = mkLocatedList matches
, mg_arg_tys = []
, mg_res_ty = placeHolderType
, mg_origin = origin }
mkLocatedList :: [Located a] -> Located [Located a]
mkLocatedList [] = noLoc []
mkLocatedList ms = L (combineLocs (head ms) (last ms)) ms
mkMatchGroupName :: Origin -> [LMatch Name (Located (body Name))]
-> MatchGroup Name (Located (body Name))
mkMatchGroupName origin matches = MG { mg_alts = mkLocatedList matches
, mg_arg_tys = []
, mg_res_ty = placeHolderType
, mg_origin = origin }
mkHsApp :: LHsExpr name -> LHsExpr name -> LHsExpr name
mkHsApp e1 e2 = addCLoc e1 e2 (HsApp e1 e2)
mkHsLam :: [LPat RdrName] -> LHsExpr RdrName -> LHsExpr RdrName
mkHsLam pats body = mkHsPar (L (getLoc body) (HsLam matches))
where
matches = mkMatchGroup Generated [mkSimpleMatch pats body]
mkHsLams :: [TyVar] -> [EvVar] -> LHsExpr Id -> LHsExpr Id
mkHsLams tyvars dicts expr = mkLHsWrap (mkWpTyLams tyvars
<.> mkWpLams dicts) expr
mkHsConApp :: DataCon -> [Type] -> [HsExpr Id] -> LHsExpr Id
-- Used for constructing dictionary terms etc, so no locations
mkHsConApp data_con tys args
= foldl mk_app (nlHsTyApp (dataConWrapId data_con) tys) args
where
mk_app f a = noLoc (HsApp f (noLoc a))
mkSimpleHsAlt :: LPat id -> (Located (body id)) -> LMatch id (Located (body id))
-- A simple lambda with a single pattern, no binds, no guards; pre-typechecking
mkSimpleHsAlt pat expr
= mkSimpleMatch [pat] expr
nlHsTyApp :: name -> [Type] -> LHsExpr name
nlHsTyApp fun_id tys = noLoc (HsWrap (mkWpTyApps tys) (HsVar (noLoc fun_id)))
nlHsTyApps :: name -> [Type] -> [LHsExpr name] -> LHsExpr name
nlHsTyApps fun_id tys xs = foldl nlHsApp (nlHsTyApp fun_id tys) xs
--------- Adding parens ---------
mkLHsPar :: LHsExpr name -> LHsExpr name
-- Wrap in parens if hsExprNeedsParens says it needs them
-- So 'f x' becomes '(f x)', but '3' stays as '3'
mkLHsPar le@(L loc e) | hsExprNeedsParens e = L loc (HsPar le)
| otherwise = le
mkParPat :: LPat name -> LPat name
mkParPat lp@(L loc p) | hsPatNeedsParens p = L loc (ParPat lp)
| otherwise = lp
-------------------------------
-- These are the bits of syntax that contain rebindable names
-- See RnEnv.lookupSyntaxName
mkHsIntegral :: String -> Integer -> PostTc RdrName Type -> HsOverLit RdrName
mkHsFractional :: FractionalLit -> PostTc RdrName Type -> HsOverLit RdrName
mkHsIsString :: String -> FastString -> PostTc RdrName Type -> HsOverLit RdrName
mkHsDo :: HsStmtContext Name -> [ExprLStmt RdrName] -> HsExpr RdrName
mkHsComp :: HsStmtContext Name -> [ExprLStmt RdrName] -> LHsExpr RdrName
-> HsExpr RdrName
mkNPat :: Located (HsOverLit RdrName) -> Maybe (SyntaxExpr RdrName) -> Pat RdrName
mkNPlusKPat :: Located RdrName -> Located (HsOverLit RdrName) -> Pat RdrName
mkLastStmt :: Located (bodyR idR) -> StmtLR idL idR (Located (bodyR idR))
mkBodyStmt :: Located (bodyR RdrName)
-> StmtLR idL RdrName (Located (bodyR RdrName))
mkBindStmt :: (PostTc idR Type ~ PlaceHolder)
=> LPat idL -> Located (bodyR idR)
-> StmtLR idL idR (Located (bodyR idR))
mkTcBindStmt :: LPat Id -> Located (bodyR Id) -> StmtLR Id Id (Located (bodyR Id))
emptyRecStmt :: StmtLR idL RdrName bodyR
emptyRecStmtName :: StmtLR Name Name bodyR
emptyRecStmtId :: StmtLR Id Id bodyR
mkRecStmt :: [LStmtLR idL RdrName bodyR] -> StmtLR idL RdrName bodyR
mkHsIntegral src i = OverLit (HsIntegral src i) noRebindableInfo noExpr
mkHsFractional f = OverLit (HsFractional f) noRebindableInfo noExpr
mkHsIsString src s = OverLit (HsIsString src s) noRebindableInfo noExpr
noRebindableInfo :: PlaceHolder
noRebindableInfo = PlaceHolder -- Just another placeholder;
mkHsDo ctxt stmts = HsDo ctxt (mkLocatedList stmts) placeHolderType
mkHsComp ctxt stmts expr = mkHsDo ctxt (stmts ++ [last_stmt])
where
last_stmt = L (getLoc expr) $ mkLastStmt expr
mkHsIf :: LHsExpr id -> LHsExpr id -> LHsExpr id -> HsExpr id
mkHsIf c a b = HsIf (Just noSyntaxExpr) c a b
mkNPat lit neg = NPat lit neg noSyntaxExpr placeHolderType
mkNPlusKPat id lit = NPlusKPat id lit (unLoc lit) noSyntaxExpr noSyntaxExpr placeHolderType
mkTransformStmt :: (PostTc idR Type ~ PlaceHolder)
=> [ExprLStmt idL] -> LHsExpr idR
-> StmtLR idL idR (LHsExpr idL)
mkTransformByStmt :: (PostTc idR Type ~ PlaceHolder)
=> [ExprLStmt idL] -> LHsExpr idR -> LHsExpr idR
-> StmtLR idL idR (LHsExpr idL)
mkGroupUsingStmt :: (PostTc idR Type ~ PlaceHolder)
=> [ExprLStmt idL] -> LHsExpr idR
-> StmtLR idL idR (LHsExpr idL)
mkGroupByUsingStmt :: (PostTc idR Type ~ PlaceHolder)
=> [ExprLStmt idL] -> LHsExpr idR -> LHsExpr idR
-> StmtLR idL idR (LHsExpr idL)
emptyTransStmt :: (PostTc idR Type ~ PlaceHolder) => StmtLR idL idR (LHsExpr idR)
emptyTransStmt = TransStmt { trS_form = panic "emptyTransStmt: form"
, trS_stmts = [], trS_bndrs = []
, trS_by = Nothing, trS_using = noLoc noExpr
, trS_ret = noSyntaxExpr, trS_bind = noSyntaxExpr
, trS_bind_arg_ty = PlaceHolder
, trS_fmap = noExpr }
mkTransformStmt ss u = emptyTransStmt { trS_form = ThenForm, trS_stmts = ss, trS_using = u }
mkTransformByStmt ss u b = emptyTransStmt { trS_form = ThenForm, trS_stmts = ss, trS_using = u, trS_by = Just b }
mkGroupUsingStmt ss u = emptyTransStmt { trS_form = GroupForm, trS_stmts = ss, trS_using = u }
mkGroupByUsingStmt ss b u = emptyTransStmt { trS_form = GroupForm, trS_stmts = ss, trS_using = u, trS_by = Just b }
mkLastStmt body = LastStmt body False noSyntaxExpr
mkBodyStmt body = BodyStmt body noSyntaxExpr noSyntaxExpr placeHolderType
mkBindStmt pat body = BindStmt pat body noSyntaxExpr noSyntaxExpr PlaceHolder
mkTcBindStmt pat body = BindStmt pat body noSyntaxExpr noSyntaxExpr unitTy
-- don't use placeHolderTypeTc above, because that panics during zonking
emptyRecStmt' :: forall idL idR body.
PostTc idR Type -> StmtLR idL idR body
emptyRecStmt' tyVal =
RecStmt
{ recS_stmts = [], recS_later_ids = []
, recS_rec_ids = []
, recS_ret_fn = noSyntaxExpr
, recS_mfix_fn = noSyntaxExpr
, recS_bind_fn = noSyntaxExpr, recS_bind_ty = tyVal
, recS_later_rets = []
, recS_rec_rets = [], recS_ret_ty = tyVal }
emptyRecStmt = emptyRecStmt' placeHolderType
emptyRecStmtName = emptyRecStmt' placeHolderType
emptyRecStmtId = emptyRecStmt' unitTy -- a panic might trigger during zonking
mkRecStmt stmts = emptyRecStmt { recS_stmts = stmts }
-------------------------------
--- A useful function for building @OpApps@. The operator is always a
-- variable, and we don't know the fixity yet.
mkHsOpApp :: LHsExpr id -> id -> LHsExpr id -> HsExpr id
mkHsOpApp e1 op e2 = OpApp e1 (noLoc (HsVar (noLoc op)))
(error "mkOpApp:fixity") e2
unqualSplice :: RdrName
unqualSplice = mkRdrUnqual (mkVarOccFS (fsLit "splice"))
mkUntypedSplice :: LHsExpr RdrName -> HsSplice RdrName
mkUntypedSplice e = HsUntypedSplice unqualSplice e
mkHsSpliceE :: LHsExpr RdrName -> HsExpr RdrName
mkHsSpliceE e = HsSpliceE (mkUntypedSplice e)
mkHsSpliceTE :: LHsExpr RdrName -> HsExpr RdrName
mkHsSpliceTE e = HsSpliceE (HsTypedSplice unqualSplice e)
mkHsSpliceTy :: LHsExpr RdrName -> HsType RdrName
mkHsSpliceTy e = HsSpliceTy (HsUntypedSplice unqualSplice e) placeHolderKind
mkHsQuasiQuote :: RdrName -> SrcSpan -> FastString -> HsSplice RdrName
mkHsQuasiQuote quoter span quote = HsQuasiQuote unqualSplice quoter span quote
unqualQuasiQuote :: RdrName
unqualQuasiQuote = mkRdrUnqual (mkVarOccFS (fsLit "quasiquote"))
-- A name (uniquified later) to
-- identify the quasi-quote
mkHsString :: String -> HsLit
mkHsString s = HsString s (mkFastString s)
mkHsStringPrimLit :: FastString -> HsLit
mkHsStringPrimLit fs
= HsStringPrim (unpackFS fs) (fastStringToByteString fs)
-------------
userHsLTyVarBndrs :: SrcSpan -> [Located name] -> [LHsTyVarBndr name]
-- Caller sets location
userHsLTyVarBndrs loc bndrs = [ L loc (UserTyVar v) | v <- bndrs ]
userHsTyVarBndrs :: SrcSpan -> [name] -> [LHsTyVarBndr name]
-- Caller sets location
userHsTyVarBndrs loc bndrs = [ L loc (UserTyVar (L loc v)) | v <- bndrs ]
{-
************************************************************************
* *
Constructing syntax with no location info
* *
************************************************************************
-}
nlHsVar :: id -> LHsExpr id
nlHsVar n = noLoc (HsVar (noLoc n))
nlHsLit :: HsLit -> LHsExpr id
nlHsLit n = noLoc (HsLit n)
nlVarPat :: id -> LPat id
nlVarPat n = noLoc (VarPat (noLoc n))
nlLitPat :: HsLit -> LPat id
nlLitPat l = noLoc (LitPat l)
nlHsApp :: LHsExpr id -> LHsExpr id -> LHsExpr id
nlHsApp f x = noLoc (HsApp f x)
nlHsSyntaxApps :: SyntaxExpr id -> [LHsExpr id] -> LHsExpr id
nlHsSyntaxApps (SyntaxExpr { syn_expr = fun
, syn_arg_wraps = arg_wraps
, syn_res_wrap = res_wrap }) args
| [] <- arg_wraps -- in the noSyntaxExpr case
= ASSERT( isIdHsWrapper res_wrap )
foldl nlHsApp (noLoc fun) args
| otherwise
= mkLHsWrap res_wrap (foldl nlHsApp (noLoc fun) (zipWithEqual "nlHsSyntaxApps"
mkLHsWrap arg_wraps args))
nlHsIntLit :: Integer -> LHsExpr id
nlHsIntLit n = noLoc (HsLit (HsInt (show n) n))
nlHsApps :: id -> [LHsExpr id] -> LHsExpr id
nlHsApps f xs = foldl nlHsApp (nlHsVar f) xs
nlHsVarApps :: id -> [id] -> LHsExpr id
nlHsVarApps f xs = noLoc (foldl mk (HsVar (noLoc f)) (map (HsVar . noLoc) xs))
where
mk f a = HsApp (noLoc f) (noLoc a)
nlConVarPat :: RdrName -> [RdrName] -> LPat RdrName
nlConVarPat con vars = nlConPat con (map nlVarPat vars)
nlConVarPatName :: Name -> [Name] -> LPat Name
nlConVarPatName con vars = nlConPatName con (map nlVarPat vars)
nlInfixConPat :: id -> LPat id -> LPat id -> LPat id
nlInfixConPat con l r = noLoc (ConPatIn (noLoc con) (InfixCon l r))
nlConPat :: RdrName -> [LPat RdrName] -> LPat RdrName
nlConPat con pats = noLoc (ConPatIn (noLoc con) (PrefixCon pats))
nlConPatName :: Name -> [LPat Name] -> LPat Name
nlConPatName con pats = noLoc (ConPatIn (noLoc con) (PrefixCon pats))
nlNullaryConPat :: id -> LPat id
nlNullaryConPat con = noLoc (ConPatIn (noLoc con) (PrefixCon []))
nlWildConPat :: DataCon -> LPat RdrName
nlWildConPat con = noLoc (ConPatIn (noLoc (getRdrName con))
(PrefixCon (nOfThem (dataConSourceArity con)
nlWildPat)))
nlWildPat :: LPat RdrName
nlWildPat = noLoc (WildPat placeHolderType ) -- Pre-typechecking
nlWildPatName :: LPat Name
nlWildPatName = noLoc (WildPat placeHolderType ) -- Pre-typechecking
nlWildPatId :: LPat Id
nlWildPatId = noLoc (WildPat placeHolderTypeTc ) -- Post-typechecking
nlHsDo :: HsStmtContext Name -> [LStmt RdrName (LHsExpr RdrName)]
-> LHsExpr RdrName
nlHsDo ctxt stmts = noLoc (mkHsDo ctxt stmts)
nlHsOpApp :: LHsExpr id -> id -> LHsExpr id -> LHsExpr id
nlHsOpApp e1 op e2 = noLoc (mkHsOpApp e1 op e2)
nlHsLam :: LMatch RdrName (LHsExpr RdrName) -> LHsExpr RdrName
nlHsPar :: LHsExpr id -> LHsExpr id
nlHsIf :: LHsExpr id -> LHsExpr id -> LHsExpr id -> LHsExpr id
nlHsCase :: LHsExpr RdrName -> [LMatch RdrName (LHsExpr RdrName)]
-> LHsExpr RdrName
nlList :: [LHsExpr RdrName] -> LHsExpr RdrName
nlHsLam match = noLoc (HsLam (mkMatchGroup Generated [match]))
nlHsPar e = noLoc (HsPar e)
nlHsIf cond true false = noLoc (mkHsIf cond true false)
nlHsCase expr matches = noLoc (HsCase expr (mkMatchGroup Generated matches))
nlList exprs = noLoc (ExplicitList placeHolderType Nothing exprs)
nlHsAppTy :: LHsType name -> LHsType name -> LHsType name
nlHsTyVar :: name -> LHsType name
nlHsFunTy :: LHsType name -> LHsType name -> LHsType name
nlHsAppTy f t = noLoc (HsAppTy f t)
nlHsTyVar x = noLoc (HsTyVar (noLoc x))
nlHsFunTy a b = noLoc (HsFunTy a b)
nlHsTyConApp :: name -> [LHsType name] -> LHsType name
nlHsTyConApp tycon tys = foldl nlHsAppTy (nlHsTyVar tycon) tys
-- | Extract a type argument from an HsExpr, with the list of wildcards in
-- the type
isLHsTypeExpr_maybe :: LHsExpr name -> Maybe (LHsWcType name)
isLHsTypeExpr_maybe (L _ (HsPar e)) = isLHsTypeExpr_maybe e
isLHsTypeExpr_maybe (L _ (HsType ty)) = Just ty
-- the HsTypeOut case is ill-typed. We never need it here anyway.
isLHsTypeExpr_maybe _ = Nothing
-- | Is an expression a visible type application?
isLHsTypeExpr :: LHsExpr name -> Bool
isLHsTypeExpr (L _ (HsPar e)) = isLHsTypeExpr e
isLHsTypeExpr (L _ (HsType _)) = True
isLHsTypeExpr (L _ (HsTypeOut _)) = True
isLHsTypeExpr _ = False
{-
Tuples. All these functions are *pre-typechecker* because they lack
types on the tuple.
-}
mkLHsTupleExpr :: [LHsExpr a] -> LHsExpr a
-- Makes a pre-typechecker boxed tuple, deals with 1 case
mkLHsTupleExpr [e] = e
mkLHsTupleExpr es = noLoc $ ExplicitTuple (map (noLoc . Present) es) Boxed
mkLHsVarTuple :: [a] -> LHsExpr a
mkLHsVarTuple ids = mkLHsTupleExpr (map nlHsVar ids)
nlTuplePat :: [LPat id] -> Boxity -> LPat id
nlTuplePat pats box = noLoc (TuplePat pats box [])
missingTupArg :: HsTupArg RdrName
missingTupArg = Missing placeHolderType
mkLHsPatTup :: [LPat id] -> LPat id
mkLHsPatTup [] = noLoc $ TuplePat [] Boxed []
mkLHsPatTup [lpat] = lpat
mkLHsPatTup lpats = L (getLoc (head lpats)) $ TuplePat lpats Boxed []
-- The Big equivalents for the source tuple expressions
mkBigLHsVarTup :: [id] -> LHsExpr id
mkBigLHsVarTup ids = mkBigLHsTup (map nlHsVar ids)
mkBigLHsTup :: [LHsExpr id] -> LHsExpr id
mkBigLHsTup = mkChunkified mkLHsTupleExpr
-- The Big equivalents for the source tuple patterns
mkBigLHsVarPatTup :: [id] -> LPat id
mkBigLHsVarPatTup bs = mkBigLHsPatTup (map nlVarPat bs)
mkBigLHsPatTup :: [LPat id] -> LPat id
mkBigLHsPatTup = mkChunkified mkLHsPatTup
-- $big_tuples
-- #big_tuples#
--
-- GHCs built in tuples can only go up to 'mAX_TUPLE_SIZE' in arity, but
-- we might concievably want to build such a massive tuple as part of the
-- output of a desugaring stage (notably that for list comprehensions).
--
-- We call tuples above this size \"big tuples\", and emulate them by
-- creating and pattern matching on >nested< tuples that are expressible
-- by GHC.
--
-- Nesting policy: it's better to have a 2-tuple of 10-tuples (3 objects)
-- than a 10-tuple of 2-tuples (11 objects), so we want the leaves of any
-- construction to be big.
--
-- If you just use the 'mkBigCoreTup', 'mkBigCoreVarTupTy', 'mkTupleSelector'
-- and 'mkTupleCase' functions to do all your work with tuples you should be
-- fine, and not have to worry about the arity limitation at all.
-- | Lifts a \"small\" constructor into a \"big\" constructor by recursive decompositon
mkChunkified :: ([a] -> a) -- ^ \"Small\" constructor function, of maximum input arity 'mAX_TUPLE_SIZE'
-> [a] -- ^ Possible \"big\" list of things to construct from
-> a -- ^ Constructed thing made possible by recursive decomposition
mkChunkified small_tuple as = mk_big_tuple (chunkify as)
where
-- Each sub-list is short enough to fit in a tuple
mk_big_tuple [as] = small_tuple as
mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s))
chunkify :: [a] -> [[a]]
-- ^ Split a list into lists that are small enough to have a corresponding
-- tuple arity. The sub-lists of the result all have length <= 'mAX_TUPLE_SIZE'
-- But there may be more than 'mAX_TUPLE_SIZE' sub-lists
chunkify xs
| n_xs <= mAX_TUPLE_SIZE = [xs]
| otherwise = split xs
where
n_xs = length xs
split [] = []
split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
{-
************************************************************************
* *
LHsSigType and LHsSigWcType
* *
********************************************************************* -}
mkLHsSigType :: LHsType RdrName -> LHsSigType RdrName
mkLHsSigType ty = mkHsImplicitBndrs ty
mkLHsSigWcType :: LHsType RdrName -> LHsSigWcType RdrName
mkLHsSigWcType ty = mkHsImplicitBndrs (mkHsWildCardBndrs ty)
mkClassOpSigs :: [LSig RdrName] -> [LSig RdrName]
-- Convert TypeSig to ClassOpSig
-- The former is what is parsed, but the latter is
-- what we need in class/instance declarations
mkClassOpSigs sigs
= map fiddle sigs
where
fiddle (L loc (TypeSig nms ty)) = L loc (ClassOpSig False nms (dropWildCards ty))
fiddle sig = sig
toLHsSigWcType :: Type -> LHsSigWcType RdrName
-- ^ Converting a Type to an HsType RdrName
-- This is needed to implement GeneralizedNewtypeDeriving.
--
-- Note that we use 'getRdrName' extensively, which
-- generates Exact RdrNames rather than strings.
toLHsSigWcType ty
= mkLHsSigWcType (go ty)
where
go :: Type -> LHsType RdrName
go ty@(ForAllTy (Anon arg) _)
| isPredTy arg
, (theta, tau) <- tcSplitPhiTy ty
= noLoc (HsQualTy { hst_ctxt = noLoc (map go theta)
, hst_body = go tau })
go (ForAllTy (Anon arg) res) = nlHsFunTy (go arg) (go res)
go ty@(ForAllTy {})
| (tvs, tau) <- tcSplitForAllTys ty
= noLoc (HsForAllTy { hst_bndrs = map go_tv tvs
, hst_body = go tau })
go (TyVarTy tv) = nlHsTyVar (getRdrName tv)
go (AppTy t1 t2) = nlHsAppTy (go t1) (go t2)
go (LitTy (NumTyLit n)) = noLoc $ HsTyLit (HsNumTy "" n)
go (LitTy (StrTyLit s)) = noLoc $ HsTyLit (HsStrTy "" s)
go (TyConApp tc args) = nlHsTyConApp (getRdrName tc) (map go args')
where
args' = filterOutInvisibleTypes tc args
go (CastTy ty _) = go ty
go (CoercionTy co) = pprPanic "toLHsSigWcType" (ppr co)
-- Source-language types have _invisible_ kind arguments,
-- so we must remove them here (Trac #8563)
go_tv :: TyVar -> LHsTyVarBndr RdrName
go_tv tv = noLoc $ KindedTyVar (noLoc (getRdrName tv))
(go (tyVarKind tv))
{- *********************************************************************
* *
--------- HsWrappers: type args, dict args, casts ---------
* *
********************************************************************* -}
mkLHsWrap :: HsWrapper -> LHsExpr id -> LHsExpr id
mkLHsWrap co_fn (L loc e) = L loc (mkHsWrap co_fn e)
mkHsWrap :: HsWrapper -> HsExpr id -> HsExpr id
mkHsWrap co_fn e | isIdHsWrapper co_fn = e
| otherwise = HsWrap co_fn e
mkHsWrapCo :: TcCoercionN -- A Nominal coercion a ~N b
-> HsExpr id -> HsExpr id
mkHsWrapCo co e = mkHsWrap (mkWpCastN co) e
mkHsWrapCoR :: TcCoercionR -- A Representational coercion a ~R b
-> HsExpr id -> HsExpr id
mkHsWrapCoR co e = mkHsWrap (mkWpCastR co) e
mkLHsWrapCo :: TcCoercionN -> LHsExpr id -> LHsExpr id
mkLHsWrapCo co (L loc e) = L loc (mkHsWrapCo co e)
mkHsCmdWrap :: HsWrapper -> HsCmd id -> HsCmd id
mkHsCmdWrap w cmd | isIdHsWrapper w = cmd
| otherwise = HsCmdWrap w cmd
mkLHsCmdWrap :: HsWrapper -> LHsCmd id -> LHsCmd id
mkLHsCmdWrap w (L loc c) = L loc (mkHsCmdWrap w c)
mkHsWrapPat :: HsWrapper -> Pat id -> Type -> Pat id
mkHsWrapPat co_fn p ty | isIdHsWrapper co_fn = p
| otherwise = CoPat co_fn p ty
mkHsWrapPatCo :: TcCoercionN -> Pat id -> Type -> Pat id
mkHsWrapPatCo co pat ty | isTcReflCo co = pat
| otherwise = CoPat (mkWpCastN co) pat ty
mkHsDictLet :: TcEvBinds -> LHsExpr Id -> LHsExpr Id
mkHsDictLet ev_binds expr = mkLHsWrap (mkWpLet ev_binds) expr
{-
l
************************************************************************
* *
Bindings; with a location at the top
* *
************************************************************************
-}
mkFunBind :: Located RdrName -> [LMatch RdrName (LHsExpr RdrName)]
-> HsBind RdrName
-- Not infix, with place holders for coercion and free vars
mkFunBind fn ms = FunBind { fun_id = fn
, fun_matches = mkMatchGroup Generated ms
, fun_co_fn = idHsWrapper
, bind_fvs = placeHolderNames
, fun_tick = [] }
mkTopFunBind :: Origin -> Located Name -> [LMatch Name (LHsExpr Name)]
-> HsBind Name
-- In Name-land, with empty bind_fvs
mkTopFunBind origin fn ms = FunBind { fun_id = fn
, fun_matches = mkMatchGroupName origin ms
, fun_co_fn = idHsWrapper
, bind_fvs = emptyNameSet -- NB: closed
-- binding
, fun_tick = [] }
mkHsVarBind :: SrcSpan -> RdrName -> LHsExpr RdrName -> LHsBind RdrName
mkHsVarBind loc var rhs = mk_easy_FunBind loc var [] rhs
mkVarBind :: id -> LHsExpr id -> LHsBind id
mkVarBind var rhs = L (getLoc rhs) $
VarBind { var_id = var, var_rhs = rhs, var_inline = False }
mkPatSynBind :: Located RdrName -> HsPatSynDetails (Located RdrName)
-> LPat RdrName -> HsPatSynDir RdrName -> HsBind RdrName
mkPatSynBind name details lpat dir = PatSynBind psb
where
psb = PSB{ psb_id = name
, psb_args = details
, psb_def = lpat
, psb_dir = dir
, psb_fvs = placeHolderNames }
-- |If any of the matches in the 'FunBind' are infix, the 'FunBind' is
-- considered infix.
isInfixFunBind :: HsBindLR id1 id2 -> Bool
isInfixFunBind (FunBind _ (MG matches _ _ _) _ _ _)
= any (isInfixMatch . unLoc) (unLoc matches)
isInfixFunBind _ = False
------------
mk_easy_FunBind :: SrcSpan -> RdrName -> [LPat RdrName]
-> LHsExpr RdrName -> LHsBind RdrName
mk_easy_FunBind loc fun pats expr
= L loc $ mkFunBind (L loc fun) [mkMatch pats expr (noLoc emptyLocalBinds)]
------------
mkMatch :: [LPat id] -> LHsExpr id -> Located (HsLocalBinds id)
-> LMatch id (LHsExpr id)
mkMatch pats expr lbinds
= noLoc (Match NonFunBindMatch (map paren pats) Nothing
(GRHSs (unguardedRHS noSrcSpan expr) lbinds))
where
paren lp@(L l p) | hsPatNeedsParens p = L l (ParPat lp)
| otherwise = lp
{-
************************************************************************
* *
Collecting binders
* *
************************************************************************
Get all the binders in some HsBindGroups, IN THE ORDER OF APPEARANCE. eg.
...
where
(x, y) = ...
f i j = ...
[a, b] = ...
it should return [x, y, f, a, b] (remember, order important).
Note [Collect binders only after renaming]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
These functions should only be used on HsSyn *after* the renamer,
to return a [Name] or [Id]. Before renaming the record punning
and wild-card mechanism makes it hard to know what is bound.
So these functions should not be applied to (HsSyn RdrName)
-}
----------------- Bindings --------------------------
collectLocalBinders :: HsLocalBindsLR idL idR -> [idL]
collectLocalBinders (HsValBinds binds) = collectHsIdBinders binds
-- No pattern synonyms here
collectLocalBinders (HsIPBinds _) = []
collectLocalBinders EmptyLocalBinds = []
collectHsIdBinders, collectHsValBinders :: HsValBindsLR idL idR -> [idL]
-- Collect Id binders only, or Ids + pattern synonmys, respectively
collectHsIdBinders = collect_hs_val_binders True
collectHsValBinders = collect_hs_val_binders False
collectHsBindBinders :: HsBindLR idL idR -> [idL]
-- Collect both Ids and pattern-synonym binders
collectHsBindBinders b = collect_bind False b []
collectHsBindsBinders :: LHsBindsLR idL idR -> [idL]
collectHsBindsBinders binds = collect_binds False binds []
collectHsBindListBinders :: [LHsBindLR idL idR] -> [idL]
-- Same as collectHsBindsBinders, but works over a list of bindings
collectHsBindListBinders = foldr (collect_bind False . unLoc) []
collect_hs_val_binders :: Bool -> HsValBindsLR idL idR -> [idL]
collect_hs_val_binders ps (ValBindsIn binds _) = collect_binds ps binds []
collect_hs_val_binders ps (ValBindsOut binds _) = collect_out_binds ps binds
collect_out_binds :: Bool -> [(RecFlag, LHsBinds id)] -> [id]
collect_out_binds ps = foldr (collect_binds ps . snd) []
collect_binds :: Bool -> LHsBindsLR idL idR -> [idL] -> [idL]
-- Collect Ids, or Ids + pattern synonyms, depending on boolean flag
collect_binds ps binds acc = foldrBag (collect_bind ps . unLoc) acc binds
collect_bind :: Bool -> HsBindLR idL idR -> [idL] -> [idL]
collect_bind _ (PatBind { pat_lhs = p }) acc = collect_lpat p acc
collect_bind _ (FunBind { fun_id = L _ f }) acc = f : acc
collect_bind _ (VarBind { var_id = f }) acc = f : acc
collect_bind _ (AbsBinds { abs_exports = dbinds }) acc = map abe_poly dbinds ++ acc
-- I don't think we want the binders from the abe_binds
-- The only time we collect binders from a typechecked
-- binding (hence see AbsBinds) is in zonking in TcHsSyn
collect_bind _ (AbsBindsSig { abs_sig_export = poly }) acc = poly : acc
collect_bind omitPatSyn (PatSynBind (PSB { psb_id = L _ ps })) acc =
if omitPatSyn then acc else ps : acc
collectMethodBinders :: LHsBindsLR RdrName idR -> [Located RdrName]
-- Used exclusively for the bindings of an instance decl which are all FunBinds
collectMethodBinders binds = foldrBag (get . unLoc) [] binds
where
get (FunBind { fun_id = f }) fs = f : fs
get _ fs = fs
-- Someone else complains about non-FunBinds
----------------- Statements --------------------------
collectLStmtsBinders :: [LStmtLR idL idR body] -> [idL]
collectLStmtsBinders = concatMap collectLStmtBinders
collectStmtsBinders :: [StmtLR idL idR body] -> [idL]
collectStmtsBinders = concatMap collectStmtBinders
collectLStmtBinders :: LStmtLR idL idR body -> [idL]
collectLStmtBinders = collectStmtBinders . unLoc
collectStmtBinders :: StmtLR idL idR body -> [idL]
-- Id Binders for a Stmt... [but what about pattern-sig type vars]?
collectStmtBinders (BindStmt pat _ _ _ _)= collectPatBinders pat
collectStmtBinders (LetStmt (L _ binds)) = collectLocalBinders binds
collectStmtBinders (BodyStmt {}) = []
collectStmtBinders (LastStmt {}) = []
collectStmtBinders (ParStmt xs _ _ _) = collectLStmtsBinders
$ [s | ParStmtBlock ss _ _ <- xs, s <- ss]
collectStmtBinders (TransStmt { trS_stmts = stmts }) = collectLStmtsBinders stmts
collectStmtBinders (RecStmt { recS_stmts = ss }) = collectLStmtsBinders ss
collectStmtBinders ApplicativeStmt{} = []
----------------- Patterns --------------------------
collectPatBinders :: LPat a -> [a]
collectPatBinders pat = collect_lpat pat []
collectPatsBinders :: [LPat a] -> [a]
collectPatsBinders pats = foldr collect_lpat [] pats
-------------
collect_lpat :: LPat name -> [name] -> [name]
collect_lpat (L _ pat) bndrs
= go pat
where
go (VarPat (L _ var)) = var : bndrs
go (WildPat _) = bndrs
go (LazyPat pat) = collect_lpat pat bndrs
go (BangPat pat) = collect_lpat pat bndrs
go (AsPat (L _ a) pat) = a : collect_lpat pat bndrs
go (ViewPat _ pat _) = collect_lpat pat bndrs
go (ParPat pat) = collect_lpat pat bndrs
go (ListPat pats _ _) = foldr collect_lpat bndrs pats
go (PArrPat pats _) = foldr collect_lpat bndrs pats
go (TuplePat pats _ _) = foldr collect_lpat bndrs pats
go (ConPatIn _ ps) = foldr collect_lpat bndrs (hsConPatArgs ps)
go (ConPatOut {pat_args=ps}) = foldr collect_lpat bndrs (hsConPatArgs ps)
-- See Note [Dictionary binders in ConPatOut]
go (LitPat _) = bndrs
go (NPat {}) = bndrs
go (NPlusKPat (L _ n) _ _ _ _ _)= n : bndrs
go (SigPatIn pat _) = collect_lpat pat bndrs
go (SigPatOut pat _) = collect_lpat pat bndrs
go (SplicePat _) = bndrs
go (CoPat _ pat _) = go pat
{-
Note [Dictionary binders in ConPatOut] See also same Note in DsArrows
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Do *not* gather (a) dictionary and (b) dictionary bindings as binders
of a ConPatOut pattern. For most calls it doesn't matter, because
it's pre-typechecker and there are no ConPatOuts. But it does matter
more in the desugarer; for example, DsUtils.mkSelectorBinds uses
collectPatBinders. In a lazy pattern, for example f ~(C x y) = ...,
we want to generate bindings for x,y but not for dictionaries bound by
C. (The type checker ensures they would not be used.)
Desugaring of arrow case expressions needs these bindings (see DsArrows
and arrowcase1), but SPJ (Jan 2007) says it's safer for it to use its
own pat-binder-collector:
Here's the problem. Consider
data T a where
C :: Num a => a -> Int -> T a
f ~(C (n+1) m) = (n,m)
Here, the pattern (C (n+1)) binds a hidden dictionary (d::Num a),
and *also* uses that dictionary to match the (n+1) pattern. Yet, the
variables bound by the lazy pattern are n,m, *not* the dictionary d.
So in mkSelectorBinds in DsUtils, we want just m,n as the variables bound.
-}
hsGroupBinders :: HsGroup Name -> [Name]
hsGroupBinders (HsGroup { hs_valds = val_decls, hs_tyclds = tycl_decls,
hs_instds = inst_decls, hs_fords = foreign_decls })
= collectHsValBinders val_decls
++ hsTyClForeignBinders tycl_decls inst_decls foreign_decls
hsTyClForeignBinders :: [TyClGroup Name] -> [LInstDecl Name]
-> [LForeignDecl Name] -> [Name]
-- We need to look at instance declarations too,
-- because their associated types may bind data constructors
hsTyClForeignBinders tycl_decls inst_decls foreign_decls
= map unLoc (hsForeignDeclsBinders foreign_decls)
++ getSelectorNames (foldMap (foldMap hsLTyClDeclBinders . group_tyclds) tycl_decls
`mappend` foldMap hsLInstDeclBinders inst_decls)
where
getSelectorNames :: ([Located Name], [LFieldOcc Name]) -> [Name]
getSelectorNames (ns, fs) = map unLoc ns ++ map (selectorFieldOcc.unLoc) fs
-------------------
hsLTyClDeclBinders :: Located (TyClDecl name) -> ([Located name], [LFieldOcc name])
-- ^ Returns all the /binding/ names of the decl. The first one is
-- guaranteed to be the name of the decl. The first component
-- represents all binding names except record fields; the second
-- represents field occurrences. For record fields mentioned in
-- multiple constructors, the SrcLoc will be from the first occurrence.
--
-- Each returned (Located name) has a SrcSpan for the /whole/ declaration.
-- See Note [SrcSpan for binders]
hsLTyClDeclBinders (L loc (FamDecl { tcdFam = FamilyDecl { fdLName = L _ name } }))
= ([L loc name], [])
hsLTyClDeclBinders (L loc (SynDecl { tcdLName = L _ name })) = ([L loc name], [])
hsLTyClDeclBinders (L loc (ClassDecl { tcdLName = L _ cls_name
, tcdSigs = sigs, tcdATs = ats }))
= (L loc cls_name :
[ L fam_loc fam_name | L fam_loc (FamilyDecl { fdLName = L _ fam_name }) <- ats ] ++
[ L mem_loc mem_name | L mem_loc (ClassOpSig False ns _) <- sigs, L _ mem_name <- ns ]
, [])
hsLTyClDeclBinders (L loc (DataDecl { tcdLName = L _ name, tcdDataDefn = defn }))
= (\ (xs, ys) -> (L loc name : xs, ys)) $ hsDataDefnBinders defn
-------------------
hsForeignDeclsBinders :: [LForeignDecl name] -> [Located name]
-- See Note [SrcSpan for binders]
hsForeignDeclsBinders foreign_decls
= [ L decl_loc n
| L decl_loc (ForeignImport { fd_name = L _ n }) <- foreign_decls]
-------------------
hsPatSynBinders :: HsValBinds RdrName
-> ([Located RdrName], [Located RdrName])
-- Collect pattern-synonym binders only, not Ids
-- See Note [SrcSpan for binders]
hsPatSynBinders (ValBindsIn binds _) = foldrBag addPatSynBndr ([],[]) binds
hsPatSynBinders _ = panic "hsPatSynBinders"
addPatSynBndr :: LHsBindLR id id -> ([Located id], [Located id])
-> ([Located id], [Located id]) -- (selectors, other)
-- See Note [SrcSpan for binders]
addPatSynBndr bind (sels, pss)
| L bind_loc (PatSynBind (PSB { psb_id = L _ n
, psb_args = RecordPatSyn as })) <- bind
= (map recordPatSynSelectorId as ++ sels, L bind_loc n : pss)
| L bind_loc (PatSynBind (PSB { psb_id = L _ n})) <- bind
= (sels, L bind_loc n : pss)
| otherwise
= (sels, pss)
-------------------
hsLInstDeclBinders :: LInstDecl name -> ([Located name], [LFieldOcc name])
hsLInstDeclBinders (L _ (ClsInstD { cid_inst = ClsInstDecl { cid_datafam_insts = dfis } }))
= foldMap (hsDataFamInstBinders . unLoc) dfis
hsLInstDeclBinders (L _ (DataFamInstD { dfid_inst = fi }))
= hsDataFamInstBinders fi
hsLInstDeclBinders (L _ (TyFamInstD {})) = mempty
-------------------
-- the SrcLoc returned are for the whole declarations, not just the names
hsDataFamInstBinders :: DataFamInstDecl name -> ([Located name], [LFieldOcc name])
hsDataFamInstBinders (DataFamInstDecl { dfid_defn = defn })
= hsDataDefnBinders defn
-- There can't be repeated symbols because only data instances have binders
-------------------
-- the SrcLoc returned are for the whole declarations, not just the names
hsDataDefnBinders :: HsDataDefn name -> ([Located name], [LFieldOcc name])
hsDataDefnBinders (HsDataDefn { dd_cons = cons })
= hsConDeclsBinders cons
-- See Note [Binders in family instances]
-------------------
hsConDeclsBinders :: [LConDecl name] -> ([Located name], [LFieldOcc name])
-- See hsLTyClDeclBinders for what this does
-- The function is boringly complicated because of the records
-- And since we only have equality, we have to be a little careful
hsConDeclsBinders cons = go id cons
where go :: ([LFieldOcc name] -> [LFieldOcc name])
-> [LConDecl name] -> ([Located name], [LFieldOcc name])
go _ [] = ([], [])
go remSeen (r:rs) =
-- don't re-mangle the location of field names, because we don't
-- have a record of the full location of the field declaration anyway
case r of
-- remove only the first occurrence of any seen field in order to
-- avoid circumventing detection of duplicate fields (#9156)
L loc (ConDeclGADT { con_names = names
, con_type = HsIB { hsib_body = res_ty}}) ->
case tau of
L _ (HsFunTy
(L _ (HsAppsTy
[L _ (HsAppPrefix (L _ (HsRecTy flds)))])) _res_ty)
-> record_gadt flds
L _ (HsFunTy (L _ (HsRecTy flds)) _res_ty)
-> record_gadt flds
_other -> (map (L loc . unLoc) names ++ ns, fs)
where (ns, fs) = go remSeen rs
where
(_tvs, _cxt, tau) = splitLHsSigmaTy res_ty
record_gadt flds = (map (L loc . unLoc) names ++ ns, r' ++ fs)
where r' = remSeen (concatMap (cd_fld_names . unLoc) flds)
remSeen' = foldr (.) remSeen
[deleteBy ((==) `on`
unLoc . rdrNameFieldOcc . unLoc) v
| v <- r']
(ns, fs) = go remSeen' rs
L loc (ConDeclH98 { con_name = name
, con_details = RecCon flds }) ->
([L loc (unLoc name)] ++ ns, r' ++ fs)
where r' = remSeen (concatMap (cd_fld_names . unLoc)
(unLoc flds))
remSeen'
= foldr (.) remSeen
[deleteBy ((==) `on`
unLoc . rdrNameFieldOcc . unLoc) v | v <- r']
(ns, fs) = go remSeen' rs
L loc (ConDeclH98 { con_name = name }) ->
([L loc (unLoc name)] ++ ns, fs)
where (ns, fs) = go remSeen rs
{-
Note [SrcSpan for binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~
When extracting the (Located RdrNme) for a binder, at least for the
main name (the TyCon of a type declaration etc), we want to give it
the @SrcSpan@ of the whole /declaration/, not just the name itself
(which is how it appears in the syntax tree). This SrcSpan (for the
entire declaration) is used as the SrcSpan for the Name that is
finally produced, and hence for error messages. (See Trac #8607.)
Note [Binders in family instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a type or data family instance declaration, the type
constructor is an *occurrence* not a binding site
type instance T Int = Int -> Int -- No binders
data instance S Bool = S1 | S2 -- Binders are S1,S2
************************************************************************
* *
Collecting binders the user did not write
* *
************************************************************************
The job of this family of functions is to run through binding sites and find the set of all Names
that were defined "implicitly", without being explicitly written by the user.
The main purpose is to find names introduced by record wildcards so that we can avoid
warning the user when they don't use those names (#4404)
-}
lStmtsImplicits :: [LStmtLR Name idR (Located (body idR))] -> NameSet
lStmtsImplicits = hs_lstmts
where
hs_lstmts :: [LStmtLR Name idR (Located (body idR))] -> NameSet
hs_lstmts = foldr (\stmt rest -> unionNameSet (hs_stmt (unLoc stmt)) rest) emptyNameSet
hs_stmt :: StmtLR Name idR (Located (body idR)) -> NameSet
hs_stmt (BindStmt pat _ _ _ _) = lPatImplicits pat
hs_stmt (ApplicativeStmt args _ _) = unionNameSets (map do_arg args)
where do_arg (_, ApplicativeArgOne pat _) = lPatImplicits pat
do_arg (_, ApplicativeArgMany stmts _ _) = hs_lstmts stmts
hs_stmt (LetStmt binds) = hs_local_binds (unLoc binds)
hs_stmt (BodyStmt {}) = emptyNameSet
hs_stmt (LastStmt {}) = emptyNameSet
hs_stmt (ParStmt xs _ _ _) = hs_lstmts [s | ParStmtBlock ss _ _ <- xs, s <- ss]
hs_stmt (TransStmt { trS_stmts = stmts }) = hs_lstmts stmts
hs_stmt (RecStmt { recS_stmts = ss }) = hs_lstmts ss
hs_local_binds (HsValBinds val_binds) = hsValBindsImplicits val_binds
hs_local_binds (HsIPBinds _) = emptyNameSet
hs_local_binds EmptyLocalBinds = emptyNameSet
hsValBindsImplicits :: HsValBindsLR Name idR -> NameSet
hsValBindsImplicits (ValBindsOut binds _)
= foldr (unionNameSet . lhsBindsImplicits . snd) emptyNameSet binds
hsValBindsImplicits (ValBindsIn binds _)
= lhsBindsImplicits binds
lhsBindsImplicits :: LHsBindsLR Name idR -> NameSet
lhsBindsImplicits = foldBag unionNameSet (lhs_bind . unLoc) emptyNameSet
where
lhs_bind (PatBind { pat_lhs = lpat }) = lPatImplicits lpat
lhs_bind _ = emptyNameSet
lPatImplicits :: LPat Name -> NameSet
lPatImplicits = hs_lpat
where
hs_lpat (L _ pat) = hs_pat pat
hs_lpats = foldr (\pat rest -> hs_lpat pat `unionNameSet` rest) emptyNameSet
hs_pat (LazyPat pat) = hs_lpat pat
hs_pat (BangPat pat) = hs_lpat pat
hs_pat (AsPat _ pat) = hs_lpat pat
hs_pat (ViewPat _ pat _) = hs_lpat pat
hs_pat (ParPat pat) = hs_lpat pat
hs_pat (ListPat pats _ _) = hs_lpats pats
hs_pat (PArrPat pats _) = hs_lpats pats
hs_pat (TuplePat pats _ _) = hs_lpats pats
hs_pat (SigPatIn pat _) = hs_lpat pat
hs_pat (SigPatOut pat _) = hs_lpat pat
hs_pat (CoPat _ pat _) = hs_pat pat
hs_pat (ConPatIn _ ps) = details ps
hs_pat (ConPatOut {pat_args=ps}) = details ps
hs_pat _ = emptyNameSet
details (PrefixCon ps) = hs_lpats ps
details (RecCon fs) = hs_lpats explicit `unionNameSet` mkNameSet (collectPatsBinders implicit)
where (explicit, implicit) = partitionEithers [if pat_explicit then Left pat else Right pat
| (i, fld) <- [0..] `zip` rec_flds fs
, let pat = hsRecFieldArg
(unLoc fld)
pat_explicit = maybe True (i<) (rec_dotdot fs)]
details (InfixCon p1 p2) = hs_lpat p1 `unionNameSet` hs_lpat p2
|
oldmanmike/ghc
|
compiler/hsSyn/HsUtils.hs
|
bsd-3-clause
| 46,930 | 0 | 27 | 12,268 | 12,134 | 6,255 | 5,879 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
module Network.DHT.Kademlia.Util (
dumpRT
, secToMicro
, storeChunks
, tryReassemble
, forkIO_
, prunePings
) where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import Data.Binary
import Data.Time.Clock
import Data.Word
import GHC.IO.Handle
import GHC.IO.Handle.FD
import Network.DHT.Kademlia.Def
import Util.Integral
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Vector as V
pStdOut = hPutStr stdout
pStdErr = hPutStr stderr
dumpRT :: RoutingTable -> IO ()
dumpRT kbuckets = do
V.mapM_ dumpBuckets $ V.zip (V.fromList [0..V.length kbuckets-1]) kbuckets
where
dumpBuckets (bit, tvb) = do
putStrLn $ show bit ++ " -----------------------------"
KBucket{..} <- atomically $ readTVar tvb
mapM_ (putStrLn . show) $ V.toList kContent
secToMicro :: Int -> Int
secToMicro t = t * fromIntegral (10 ** 6 :: Double)
storeChunks :: B.ByteString -> B.ByteString -> [RPC]
storeChunks k v = loop 0 k v
where
totalChunks :: Word32
totalChunks = fromIntegral
$ ceiling
$ (fromIntegral $ B.length v) / (fromIntegral chunkBytes)
loop i k v
| B.null v = []
| otherwise = rpc : loop (i+1) k rest
where
rpc = RPC_STORE_REQ k i totalChunks chunkLen chunk
(chunk, rest) = B.splitAt chunkBytes v
chunkLen = fromIntegral $ B.length chunk
-- TODO validate checksum
tryReassemble :: V.Vector B.ByteString -> Maybe B.ByteString
tryReassemble v = if V.null v || V.any (== B.empty) v
then Nothing
else Just $ V.foldl1 B.append v
prunePings :: V.Vector (UTCTime, Node)
-- ^ the list to prune
-> Node
-- ^ the id to prune
-> Maybe (V.Vector (UTCTime, Node))
-- ^ Nothing if the node wasn't found. Otherwise the pruned list
prunePings pings thatNode = case V.foldl f (False, V.empty) pings of
(True, v) -> Just v
otherwise -> Nothing
where
f (True, v) t = (True, V.snoc v t)
f (False, v) (_, p) | p == thatNode = (True, v)
f (False, v) t = (False, V.snoc v t)
{-# INLINE forkIO_ #-}
forkIO_ :: IO () -> IO ()
forkIO_ = void . forkIO
|
phylake/kademlia
|
Network/DHT/Kademlia/Util.hs
|
bsd-3-clause
| 2,329 | 0 | 14 | 632 | 774 | 415 | 359 | 60 | 4 |
-- | Parsing and evaluation of strict Goto.
module Language.LoopGotoWhile.Goto.Strict
( run
, eval
, parse
, prettyPrint
) where
import Control.Monad
import Control.Monad.ST
import qualified Data.Vector as V
import Data.Vector ((!))
import Data.List (genericLength)
import Text.ParserCombinators.Parsec hiding (parse, label)
import Language.LoopGotoWhile.Shared.Util (mkStdParser, mkStdRunner)
import Language.LoopGotoWhile.Shared.Evaluation (Env, nullEnv, getVar, setVar)
import Language.LoopGotoWhile.Goto.StrictAS
-- * Main Functions
-- ==============
-- | Given a string representation of a strict Goto program and a list of
-- arguments parse & evaluate the program and return either an error string or
-- the value of 'x0'.
run :: String -> [Integer] -> Either String Integer
run = mkStdRunner parse eval
-- | Given a strict Goto AST and a list of arguments evaluate the program
-- and return the value of 'x0'.
eval :: Program -> [Integer] -> Integer
eval ast args = runST $ do
envRef <- nullEnv
let (Seq stats) = case ast of
Seq ss -> Seq ss
other -> Seq [other]
let statsArr = V.fromList stats
forM_ [1..length args] $ \i ->
setVar envRef (toInteger i) (args !! (i-1))
eval' envRef statsArr 1
getVar envRef 0
-- | Given a string representation of a strict Goto program parse it and
-- return either an error string or the AST.
parse :: String -> Either String Program
parse = mkStdParser parseStats (1, False) spaces
-- * Evaluation
-- ==========
eval' :: Env s -> V.Vector Stat -> Integer -> ST s ()
eval' env arr index = do
let stat = arr ! ((fromInteger index) - 1)
case stat of
Assign l i j Plus c -> do
xj <- getVar env j
setVar env i $! (xj + c)
eval' env arr $ succ l
Assign l i j Minus c -> do
xj <- getVar env j
setVar env i $! (max (xj - c) 0)
eval' env arr $ succ l
IfGoto l1 i c l2 -> do
xi <- getVar env i
if xi == c
then eval' env arr l2
else eval' env arr $ succ l1
Goto _ l -> eval' env arr l
Halt _ -> return ()
Seq _ -> error "Impossible! Seq must not appear here!"
-- * Parsing
-- =======
-- In order to check if labels have successive indices starting at 1 and to
-- check if the last statement is either 'HALT' or 'GOTO Mx' state must be
-- carried along. In this case the integer represents the currenct and correct
-- index. If the index of a label is not equal to this integer an error is
-- thrown. Likewise, the bool value is set to true if the current statement is
-- either 'HALT' or 'GOTO Mx' otherwise it is set to false. If the bool value
-- is not true when the last statement has been reached an error is thrown.
type GotoParser a = GenParser Char (Integer, Bool) a
parseConst :: GotoParser Const
parseConst = liftM read (many1 digit <?> "constant")
parseVar :: GotoParser VIndex
parseVar = liftM read (char 'x' >> many1 (digit <?> "") <?> "variable")
parseLabel' :: GotoParser LIndex
parseLabel' = do
_ <- char 'M'
x <- many1 (digit <?> "") <?> "label"
spaces
return $ read x
parseLabel :: GotoParser LIndex
parseLabel = do
x <- parseLabel'
(l,_) <- getState
when (x /= l) $ fail "label numbers not successive"
updateState (\(i,j) -> (i + 1, j)) >> spaces >> char ':' >> spaces >> return x
parseOp :: GotoParser Op
parseOp = do
op <- oneOf "+-"
case op of
'+' -> return Plus
'-' -> return Minus
_ -> fail "Wrong operator"
parseAssign :: GotoParser Stat
parseAssign = do
lab <- parseLabel
spaces
x <- parseVar
spaces
_ <- string ":="
spaces
y <- parseVar
spaces
o <- parseOp
spaces
c <- parseConst
spaces
updateState $ \(l,_) -> (l,False)
return $ Assign lab x y o c
parseHalt :: GotoParser Stat
parseHalt = do
lab <- parseLabel
spaces
_ <- string "HALT"
spaces
updateState $ \(l,_) -> (l,True)
return $ Halt lab
parseGoto :: GotoParser Stat
parseGoto = do
l1 <- parseLabel
spaces
_ <- string "GOTO"
spaces
l2 <- parseLabel'
spaces
updateState $ \(l,_) -> (l,True)
return $ Goto l1 l2
parseIfGoto :: GotoParser Stat
parseIfGoto = do
l1 <- parseLabel
spaces
_ <- string "IF"
spaces
x <- parseVar
spaces
_ <- string "="
spaces
c <- parseConst
spaces
_ <- string "THEN"
spaces
_ <- string "GOTO"
spaces
l2 <- parseLabel'
spaces
updateState $ \(l,_) -> (l,False)
return $ IfGoto l1 x c l2
parseStats :: GotoParser Program
parseStats = do
stats <- parseStat `sepBy` (string ";" >> spaces)
(_,b) <- getState
if b then return $ case stats of
[x] -> x
x -> Seq x
else fail "last statement is neither HALT nor GOTO"
where parseStat = try parseAssign
<|> try parseGoto
<|> try parseIfGoto
<|> parseHalt
|
eugenkiss/loopgotowhile
|
src/Language/LoopGotoWhile/Goto/Strict.hs
|
bsd-3-clause
| 5,092 | 0 | 16 | 1,471 | 1,525 | 758 | 767 | 139 | 7 |
{-# LANGUAGE DeriveGeneric #-}
module Csv
( readCSV
, writeCSV
, LogCsv(..)
) where
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Csv
import Data.Vector (Vector)
import GHC.Generics (Generic)
readCSV :: FromRecord a => FilePath -> IO (Either String (Vector a))
readCSV csvFile = decode NoHeader . BL.fromStrict <$> BS.readFile csvFile
writeCSV :: ToRecord a => FilePath -> [a] -> IO ()
writeCSV outPath csv = BL.writeFile outPath $ encode csv
data LogCsv = LogCsv
{ reposC :: String
, commitC :: String
, dateC :: String
, issueIdC :: String
} deriving (Show, Generic)
instance FromRecord LogCsv
instance ToRecord LogCsv
|
matonix/BTScraper
|
src/Csv.hs
|
bsd-3-clause
| 844 | 0 | 11 | 222 | 241 | 135 | 106 | 24 | 1 |
module Main where
import Data.Monoid
import System.Console.GetOpt
import System.Environment (getArgs)
import System.Exit
import System.IO
import Finance.Halifax.CSV
import Finance.Halifax.Ledger
import Finance.Halifax.QIF
import Finance.Halifax.Options
import Finance.Halifax.Rules
import Finance.Halifax.RulesParser (parseRules)
import Finance.Halifax.StatementParser (parseStatement)
import Finance.Halifax.Utilities
main :: IO ()
main = do
args <- getArgs
let (optionss, page_paths, errors) = getOpt Permute option_descriptions args
if notNull errors
then do
mapM_ putStrLn errors
putStrLn $ usageInfo "halifax-ledger" option_descriptions
exitWith (ExitFailure 1)
else do
let options = mconcat optionss
-- Read the page files and the statement they contain.
-- For some reason, the Halifax files contain character 0xA0 (160).
-- This terminates the file reading process in text mode for some reason,
-- so let's just read in binary mode for now.
pages <- mapM readBinaryFile page_paths
let (account, transactions) = parseStatement pages
--hPutStrLn stderr (show transactions)
-- Read the rules (if any) and apply them to the transactions from the pages
rules <- maybe (return []) (fmap parseRules . readFile) $ opt_rules_file options
let transactions' = map (applyRules rules) transactions
-- Output the data in the appropriate format
let output_method = case opt_output_method options `orElse` QIF of
QIF -> outputQIF
Ledger -> outputLedger
CSV -> outputCSV
output_method options account transactions'
readBinaryFile :: FilePath -> IO String
readBinaryFile fp = withBinaryFile fp ReadMode $ \h -> do
res <- hGetContents h
length res `seq` return res
|
batterseapower/halifax-import
|
Finance/Halifax/Main.hs
|
bsd-3-clause
| 2,003 | 0 | 15 | 571 | 403 | 208 | 195 | 38 | 4 |
module MatSpec where
import Data.Ratio
import Toys.Mat.Field
import Toys.Mat.Vector
import Toys.Mat.Mat
import Test.Hspec
import Test.Hspec.QuickCheck (prop)
import Test.QuickCheck hiding ((.&.))
-- Supports only 4 dimension vector
instance Arbitrary f => Arbitrary (Vector f) where
arbitrary = do
xs <- sequence [arbitrary, arbitrary, arbitrary, arbitrary]
return $ Vec xs
-- Supports only 4 dimension matrix
instance Arbitrary f => Arbitrary (Matrix f) where
arbitrary = do
vectors <- sequence [arbitrary, arbitrary, arbitrary, arbitrary]
return $ Mat vectors
vec0_4 :: Vector Rational
vec0_4 = gzero 4
mat0_4 :: Matrix Rational
mat0_4 = gzero 4
mat1_4 :: Matrix Rational
mat1_4 = mone 4
mat2_4 :: Matrix Rational
mat2_4 = msmul (2 % 1) mat1_4
spec :: Spec
spec = do
describe "gadd for Matrix" $ do
it "one `gadd` one = two" $
(mat1_4 `gadd` mat1_4) `shouldBe` mat2_4
it "one `gadd` zero = one" $
(mat1_4 `gadd` mat0_4) `shouldBe` mat1_4
describe "gsub for Matrix" $ do
it "one `gsub` one = zero" $
(mat1_4 `gsub` mat1_4) `shouldBe` mat0_4
it "two `gsub` one = one" $
(mat2_4 `gsub` mat1_4) `shouldBe` mat1_4
describe "mvmul" $ do
prop "zero `mvmul` any vector == zero vector" $ \ v_4 ->
(mat0_4 `mvmul` v_4) == vec0_4
prop "one `mvmul` any vector == same vector" $ \v_4 ->
(mat1_4 `mvmul` v_4) == v_4
describe "mmul" $ do
it "one `mmul` zero = zero" $
(mat1_4 `mmul` mat0_4) `shouldBe` mat0_4
it "one `mmul` one = one" $
(mat1_4 `mmul` mat1_4) `shouldBe` mat1_4
prop "zero `mmul` arbitrary == zero" $ \m_4 ->
mat0_4 `mmul` m_4 == mat0_4
prop "one `mmul` arbitrary == same matrix" $ \m_4 ->
mat1_4 `mmul` m_4 == m_4
describe "minv" $ do
it "minv one == one" $
(minv mat1_4) `shouldBe` mat1_4
it "(minv two) `mmul` two == one" $
((minv mat2_4) `mmul` mat2_4) `shouldBe` mat1_4
prop "(minv any mat) `mmul` same mat == one or invertible" $ \m_4 ->
mdet m_4 == gzero 1 || (minv m_4) `mmul` m_4 == mat1_4
|
dagezi/ToysMat
|
test/MatSpec.hs
|
bsd-3-clause
| 2,171 | 0 | 16 | 594 | 661 | 350 | 311 | 57 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- Module : Data.Git.Storage.CacheFile
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : unix
--
module Data.Git.Storage.CacheFile (CacheFile, newCacheVal, getCacheVal) where
import Control.Concurrent.MVar
import qualified Control.Exception as E
import Prelude hiding (FilePath)
import System.PosixCompat.Files (getFileStatus, modificationTime)
import System.PosixCompat.Types (EpochTime)
import Data.Git.Imports
data CacheFile a = CacheFile
{ cacheFilepath :: FilePath
, cacheRefresh :: IO a
, cacheIniVal :: a
, cacheLock :: MVar (MTime, a)
}
timeZero = 0
newCacheVal :: FilePath -> IO a -> a -> IO (CacheFile a)
newCacheVal path refresh initialVal =
CacheFile path refresh initialVal <$> newMVar (MTime timeZero, initialVal)
getCacheVal :: CacheFile a -> IO a
getCacheVal cachefile = modifyMVar (cacheLock cachefile) getOrRefresh
where getOrRefresh s@(mtime, cachedVal) = do
cMTime <- getMTime $ cacheFilepath cachefile
case cMTime of
Nothing -> return ((MTime timeZero, cacheIniVal cachefile), cacheIniVal cachefile)
Just newMtime | newMtime > mtime -> cacheRefresh cachefile >>= \v -> return ((newMtime, v), v)
| otherwise -> return (s, cachedVal)
newtype MTime = MTime EpochTime deriving (Eq,Ord)
getMTime filepath = (Just . MTime . modificationTime <$> getFileStatus (encodeString filepath))
`E.catch` \(_ :: E.SomeException) -> return Nothing
|
NicolasDP/hit
|
Data/Git/Storage/CacheFile.hs
|
bsd-3-clause
| 1,640 | 0 | 17 | 372 | 440 | 243 | 197 | 28 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module Analysis.FFT_Py (peakListPython) where
import Types.Common
import qualified Settings as S
import Shelly (shelly, silently, run)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.ByteString.Lazy as B
import Data.String
import Utils
import Data.Csv
import qualified Data.Vector as V
import Data.Either
import Utils
default (T.Text)
-- Use the python script to get sliding window fft results
-- I would rather not to this, but the Haskell one just isnt working
peakListPython :: FilePath -> IO (OverTime (OverFreq Peak))
peakListPython audio_fp = do
results <- shelly $ silently $ run (fromString "python")
[ "PythonUtils/fft.py"
, T.pack $ audio_fp
, T.pack $ show S.frameRes
, T.pack $ show S.overlap]
return $ parseCSV results
-- Expects the python module to return a single string, with '#' for each time slice
parseCSV :: T.Text -> [[(Int, Double)]]
parseCSV resultString = let
csvList = T.split (=='#') resultString
decodeTimeSlice csv = decode NoHeader (B.fromStrict $ T.encodeUtf8 csv) :: Either String (V.Vector (Double, Double))
toPeak = map (\(f,a) -> (floor f, a))
peakList = map (either (\e -> trace e undefined) (toPeak. V.toList) . decodeTimeSlice) $! csvList
in
peakList
|
aedanlombardo/HaskellPS
|
DSP-PBE/src/Analysis/FFT_Py.hs
|
bsd-3-clause
| 1,431 | 0 | 16 | 275 | 392 | 223 | 169 | 32 | 1 |
{-# LANGUAGE TemplateHaskell, QuasiQuotes #-}
{-# LANGUAGE TypeFamilies, EmptyDataDecls, GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RecordWildCards, OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module Network.DNS.Pocket.Type where
import Data.Default
import Data.IP
import Network.DNS hiding (lookup)
import Database.Persist
import Database.Persist.Sqlite (SqliteConf)
import Database.Persist.Zookeeper (ZookeeperConf)
instance PersistField IP where
toPersistValue (IPv4 ip) = toPersistValue $ fromIPv4 ip
toPersistValue (IPv6 ip) = toPersistValue $ fromIPv6 ip
fromPersistValue value = do
v <- fromPersistValue value
if length v == 4
then return $ IPv4 $ toIPv4 $ v
else return $ IPv6 $ toIPv6 $ v
data DnsConf = DnsConf {
bufSize :: Int
, timeOut :: Int
}
instance Default DnsConf where
def = DnsConf {
bufSize = 512
, timeOut = 3 * 1000 * 1000
}
class DnsBackend p where
type Conn p
load :: FilePath -> IO (Maybe p)
setup :: p -> IO (Maybe (Conn p))
getRecord :: p -> Domain -> Conn p -> IO [IP]
setRecord :: p -> Domain -> [IP] -> Conn p -> IO Bool
deleteRecord :: p -> Domain -> Conn p -> IO ()
listRecord :: p -> Conn p -> IO [(Domain,[IP])]
data Conf =
Zookeeper ZookeeperConf
| Sqlite SqliteConf
|
junjihashimoto/pocket-dns
|
Network/DNS/Pocket/Type.hs
|
bsd-3-clause
| 1,359 | 0 | 12 | 284 | 409 | 221 | 188 | 39 | 0 |
module Main
( main
) where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad (when)
import Data.List (find)
import Data.Maybe (isJust)
import System.Environment (getArgs)
import System.Console.GetOpt
import System.Log.Logger
import System.Log.Handler.Simple
import System.Log.Handler (setFormatter)
import System.Log.Formatter
import System.IO
import System.Random
import Process
import Process.Console as Console
-- import Process.Status as Status
-- import Process.TorrentManager as TorrentManager
-- import Process.TorrentManagerChan (TorrentManagerMessage(AddTorrent))
import Torrent
import Protocol.Types
import Version (version)
import Server
import Supervisor
main :: IO ()
main = do
args <- getArgs
opts <- handleArgs args
run opts
printVersion :: IO ()
printVersion = putStrLn $ "PROGRAM version " ++ version ++ "\n"
data Option
= Version
| Debug
| Help
deriving (Show, Eq)
options :: [OptDescr Option]
options =
[ Option ['h', '?'] ["help"] (NoArg Help) "Выводит это сообщение"
, Option ['d'] ["debug"] (NoArg Debug) "Печатает дополнительную информацию"
, Option ['v'] ["version"] (NoArg Version) "Показывает версию программы"
]
getOption :: Option -> [Option] -> Maybe Option
getOption x = find (x ~=)
where
(~=) :: Option -> Option -> Bool
Version ~= Version = True
Debug ~= Debug = True
Help ~= Help = True
_ ~= _ = False
handleArgs :: [String] -> IO ([Option], [String])
handleArgs args = case getOpt Permute options args of
(o, n, [] ) -> return (o, n)
(_, _, err) -> error (concat err ++ usageMessage)
usageMessage = usageInfo header options
where
header = "Usage: PROGRAM [option...] FILE"
run :: ([Option], [String]) -> IO ()
run (opts, files) =
if showHelp then putStrLn usageMessage
else if showVersion then printVersion
else if null files then putStrLn "No torrent file"
else download opts files
where
showHelp = Help `elem` opts
showVersion = Version `elem` opts
setupLogging :: [Option] -> IO ()
setupLogging opts = do
logStream <- streamHandler stdout DEBUG >>= \l -> return $
setFormatter l (tfLogFormatter "%F %X" "[$time] $prio $loggername: $msg")
when True $
-- when (Debug `elem` opts) $
updateGlobalLogger rootLoggerName $
(setHandlers [logStream]) . (setLevel DEBUG)
download :: [Option] -> [String] -> IO ()
download opts files = do
setupLogging opts
debugM "Main" "Инициализация"
peerId <- newStdGen >>= (return . mkPeerId)
debugM "Main" $ "Присвоен peer_id: " ++ peerId
statusTV <- newTVarIO []
statusChan <- newTChanIO
torrentChan <- newTChanIO
waitMutex <- newEmptyTMVarIO
runDownload waitMutex
-- _ <- Status.start statusTV statusChan
-- _ <- Console.start waitMutex statusChan
-- _ <- TorrentManager.start peerId statusTV statusChan torrentChan
-- atomically $ writeTChan torrentChan (map AddTorrent files)
-- atomically $ takeTMVar waitMutex
debugM "Main" "Завершаем работу"
threadDelay 1000
return ()
runDownload :: TMVar () -> IO Reason
runDownload waitMutex = do
superChan <- newTChanIO
let specs =
[ ("console", Console.specConsole waitMutex superChan)
]
runSupervisor OneForOne 5 60 superChan specs
|
artems/FlashBit
|
cli/Main.hs
|
bsd-3-clause
| 3,501 | 0 | 13 | 760 | 952 | 506 | 446 | 87 | 4 |
{-# LANGUAGE PolyKinds, KindSignatures, GADTs #-}
module Geordi.Util.Exists where
data Exists :: (x -> *) -> * where
ExI :: a b -> Exists a
|
liamoc/geordi
|
Geordi/Util/Exists.hs
|
bsd-3-clause
| 143 | 0 | 7 | 28 | 41 | 24 | 17 | 4 | 0 |
module AWS.EC2.Types.Tag
( Tag(..)
) where
import AWS.Lib.FromText
data Tag = Tag
{ tagResourceId :: Text
, tagResourceType :: Text
, tagKey :: Text
, tagValue :: Maybe Text
}
deriving (Show, Read, Eq)
|
IanConnolly/aws-sdk-fork
|
AWS/EC2/Types/Tag.hs
|
bsd-3-clause
| 234 | 0 | 9 | 66 | 74 | 46 | 28 | 9 | 0 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
[lq| data Wrapper a <p :: a -> Prop, r :: a -> a -> Prop >
= Wrap (rgref_ref :: a<p>) |]
data Wrapper a = Wrap (a)
-- Two measures
[lq| measure fwdextends :: Int -> Int -> Prop |]
[lq| measure actionP :: Int -> Prop |]
[lq| data Wrapper2 = Wrapper2 (unwrapper :: (Wrapper<{\x -> (true)},{\x y -> (fwdextends y x)}> Int )) |]
{- data Wrapper2 = Wrapper2 (unwrapper :: (Wrapper<{\x -> (actionP x)},{\x y -> (true)}> Int )) @-}
data Wrapper2 = Wrapper2 (Wrapper (Int) )
|
spinda/liquidhaskell
|
tests/gsoc15/unknown/pos/Measures.hs
|
bsd-3-clause
| 534 | 0 | 9 | 115 | 66 | 43 | 23 | 8 | 0 |
-- Pos.Chain.Txp.Memstate
module Pos.DB.Txp.MemState
( module Pos.DB.Txp.MemState.Class
, module Pos.DB.Txp.MemState.Holder
, module Pos.DB.Txp.MemState.Metrics
, module Pos.DB.Txp.MemState.Types
) where
import Pos.DB.Txp.MemState.Class
import Pos.DB.Txp.MemState.Holder
import Pos.DB.Txp.MemState.Metrics
import Pos.DB.Txp.MemState.Types
|
input-output-hk/pos-haskell-prototype
|
db/src/Pos/DB/Txp/MemState.hs
|
mit
| 415 | 0 | 5 | 102 | 79 | 60 | 19 | 9 | 0 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Review the imported data, and the analysis upon that data.
module DataAnalysis.Application.Handler.Review where
import Control.Applicative
import Data.Aeson
import Data.Conduit
import qualified Data.Conduit.List as CL
import Data.Default
import Data.IORef
import Data.Text (Text)
import Data.Text.Lazy.Encoding
import Data.Time
import DataAnalysis.Application.Foundation
import System.Locale
import Yesod
import Yesod.Default.Util
import DataAnalysis.Application.Analyze
import DataAnalysis.Application.Types
-- | Review the imported data, and the analysis upon that data.
getReviewR :: Text -> Handler Html
getReviewR ident = do
app <- getYesod
source <- getById ident
currentRoute <- getCurrentRoute
let title = toHtml (formatTime defaultTimeLocale "Import %T" (srcTimestamp source))
SomeAnalysis{..} <- return (appAnalysis app)
((result, widget), enctype) <- runFormGet (renderDivs ((,) <$> analysisForm <*> graphType))
let params =
case result of
FormSuccess (p,_::Text) -> p
_ -> analysisDefaultParams
countRef <- liftIO (newIORef 0)
start <- liftIO getCurrentTime
!datapoints <- analysisSource ident >>= ($$ CL.consume)
rowsProcessed :: Int <- liftIO (readIORef countRef)
now <- liftIO getCurrentTime
defaultLayout $ do
setTitle title
let datapointsJson = toHtml (decodeUtf8 (encode (take 100 datapoints)))
generationTime = diffUTCTime now start
$(widgetFileReload def "review")
where graphType =
areq hiddenField
"" {fsName = l,fsId = l}
(Just "Bar")
where l = Just "graph_type"
-- | Show a number that's counting something so 1234 is 1,234.
showCount :: (Show n,Integral n) => n -> String
showCount = reverse . foldr merge "" . zip ("000,00,00,00"::String) . reverse . show where
merge (f,c) rest | f == ',' = "," ++ [c] ++ rest
| otherwise = [c] ++ rest
-- | Review the imported data, and the analysis upon that data.
postReviewR :: Text -> Handler Html
postReviewR = getReviewR
|
glebovitz/demo
|
src/DataAnalysis/Application/Handler/Review.hs
|
mit
| 2,432 | 0 | 19 | 629 | 599 | 314 | 285 | 55 | 2 |
module Utils.KeyVal(formatKeyValList)
where
import Data.List(intercalate)
import qualified Data.Text as T
import Text.Printf(printf)
import BDCS.DB(KeyVal)
import BDCS.KeyValue(formatKeyValue)
formatKeyValList :: [KeyVal] -> String
formatKeyValList [] = ""
formatKeyValList lst = printf " [%s]" (intercalate ", " (map (T.unpack . formatKeyValue) lst))
|
atodorov/bdcs
|
src/tools/inspect/Utils/KeyVal.hs
|
lgpl-2.1
| 377 | 0 | 12 | 64 | 119 | 68 | 51 | 9 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="fil-PH">
<title>Mag-import nga mga URL | Extensyon ng ZAP</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Mga Nilalaman</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Indeks</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Maghanap</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Mga paborito</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
secdec/zap-extensions
|
addOns/importurls/src/main/javahelp/org/zaproxy/zap/extension/importurls/resources/help_fil_PH/helpset_fil_PH.hs
|
apache-2.0
| 998 | 78 | 67 | 164 | 429 | 216 | 213 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="de-DE">
<title>Code Dx | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_de_DE/helpset_de_DE.hs
|
apache-2.0
| 969 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
module Tandoori.Typing.Instantiate (instantiate, instantiatePolyTy, instantiateTyping) where
import Tandoori.Typing
import Tandoori.Typing.Monad
import Tandoori.Typing.MonoEnv
import qualified Data.Map as Map
import Control.Monad.State
type TvMap = Map.Map Tv Tv
type Instantiate = StateT TvMap Typing
lookupTv :: Tv -> Instantiate (Maybe Tv)
lookupTv = gets . Map.lookup
ensureTv :: Tv -> Instantiate Tv
ensureTv α = do lookup <- lookupTv α
case lookup of
Just α' -> return α'
Nothing -> do α' <- lift mkTv
modify (Map.insert α α')
return α'
instantiateM :: Ty -> Instantiate Ty
instantiateM = mapTy ensureTv
-- instantiateM τ@(TyCon _) = return τ
-- instantiateM τ@(TyVar α) = TyVar <$> ensureTv α
-- instantiateM τ@(TyFun τ1 τ2) = liftM2 TyFun (instantiateM τ1) (instantiateM τ2)
-- instantiateM τ@(TyApp τ1 τ2) = liftM2 TyApp (instantiateM τ1) (instantiateM τ2)
-- instantiateM τ@(TyTuple _) = return τ
instantiatePredM :: OverPred -> Instantiate OverPred
instantiatePredM (cls, τ) = do τ' <- instantiateM τ
return (cls, τ')
instantiatePolyPredM :: PolyPred -> Instantiate PolyPred
instantiatePolyPredM (cls, α) = do α' <- ensureTv α
return (cls, α')
runInst inst = evalStateT inst Map.empty
instantiate :: Ty -> Typing Ty
instantiate = runInst . instantiateM
instantiatePolyTy :: PolyTy -> Typing PolyTy
instantiatePolyTy = runInst . instantiatePolyTyM
instantiatePolyTyM :: PolyTy -> Instantiate PolyTy
instantiatePolyTyM (PolyTy ctx τ) = liftM2 PolyTy (mapM instantiatePolyPredM ctx) (instantiateM τ)
instantiateTypingM :: (MonoEnv, Ty) -> Instantiate (MonoEnv, Ty)
instantiateTypingM (m, τ) = do τ' <- instantiateM τ
m' <- mapMonoM ensureTv m
return (m', τ')
instantiateTyping :: (MonoEnv, Ty) -> Typing (MonoEnv, Ty)
instantiateTyping = runInst . instantiateTypingM
|
bitemyapp/tandoori
|
src/Tandoori/Typing/Instantiate.hs
|
bsd-3-clause
| 2,182 | 0 | 15 | 623 | 521 | 271 | 250 | 38 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
module Ros.Geometry_msgs.TwistStamped where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import Ros.Internal.Msg.HeaderSupport
import qualified Ros.Geometry_msgs.Twist as Twist
import qualified Ros.Std_msgs.Header as Header
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data TwistStamped = TwistStamped { _header :: Header.Header
, _twist :: Twist.Twist
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''TwistStamped)
instance RosBinary TwistStamped where
put obj' = put (_header obj') *> put (_twist obj')
get = TwistStamped <$> get <*> get
putMsg = putStampedMsg
instance HasHeader TwistStamped where
getSequence = view (header . Header.seq)
getFrame = view (header . Header.frame_id)
getStamp = view (header . Header.stamp)
setSequence = set (header . Header.seq)
instance MsgInfo TwistStamped where
sourceMD5 _ = "98d34b0043a2093cf9d9345ab6eef12e"
msgTypeName _ = "geometry_msgs/TwistStamped"
instance D.Default TwistStamped
|
acowley/roshask
|
msgs/Geometry_msgs/Ros/Geometry_msgs/TwistStamped.hs
|
bsd-3-clause
| 1,423 | 1 | 9 | 255 | 364 | 215 | 149 | 35 | 0 |
module Main where
import Control.Monad.Reader
import Control.Monad.Except
import Control.Exception (try)
import Data.List
import Data.Time
import System.Directory
import System.FilePath
import System.Environment
import System.Console.GetOpt
import System.Console.Haskeline
import System.Console.Haskeline.History
import Text.Printf
import Exp.Lex
import Exp.Par
import Exp.Print
import Exp.Abs hiding (NoArg)
import Exp.Layout
import Exp.ErrM
import CTT
import Resolver
import qualified TypeChecker as TC
import qualified Eval as E
type Interpreter a = InputT IO a
-- Flag handling
data Flag = Debug | Help | Version | Time
deriving (Eq,Show)
options :: [OptDescr Flag]
options = [ Option "d" ["debug"] (NoArg Debug) "run in debugging mode"
, Option "" ["help"] (NoArg Help) "print help"
, Option "-t" ["time"] (NoArg Time) "measure time spent computing"
, Option "" ["version"] (NoArg Version) "print version number" ]
-- Version number, welcome message, usage and prompt strings
version, welcome, usage, prompt :: String
version = "1.0"
welcome = "cubical, version: " ++ version ++ " (:h for help)\n"
usage = "Usage: cubical [options] <file.ctt>\nOptions:"
prompt = "> "
lexer :: String -> [Token]
lexer = resolveLayout True . myLexer
showTree :: (Show a, Print a) => a -> IO ()
showTree tree = do
putStrLn $ "\n[Abstract Syntax]\n\n" ++ show tree
putStrLn $ "\n[Linearized tree]\n\n" ++ printTree tree
-- Used for auto completion
searchFunc :: [String] -> String -> [Completion]
searchFunc ns str = map simpleCompletion $ filter (str `isPrefixOf`) ns
settings :: [String] -> Settings IO
settings ns = Settings
{ historyFile = Nothing
, complete = completeWord Nothing " \t" $ return . searchFunc ns
, autoAddHistory = True }
main :: IO ()
main = do
args <- getArgs
case getOpt Permute options args of
(flags,files,[])
| Help `elem` flags -> putStrLn $ usageInfo usage options
| Version `elem` flags -> putStrLn version
| otherwise -> case files of
[] -> do
putStrLn welcome
runInputT (settings []) (loop flags [] [] TC.verboseEnv)
[f] -> do
putStrLn welcome
putStrLn $ "Loading " ++ show f
initLoop flags f emptyHistory
_ -> putStrLn $ "Input error: zero or one file expected\n\n" ++
usageInfo usage options
(_,_,errs) -> putStrLn $ "Input error: " ++ concat errs ++ "\n" ++
usageInfo usage options
shrink :: String -> String
shrink s = s -- if length s > 1000 then take 1000 s ++ "..." else s
-- Initialize the main loop
initLoop :: [Flag] -> FilePath -> History -> IO ()
initLoop flags f hist = do
-- Parse and type check files
(_,_,mods) <- imports True ([],[],[]) f
-- Translate to TT
let res = runResolver $ resolveModules mods
case res of
Left err -> do
putStrLn $ "Resolver failed: " ++ err
runInputT (settings []) (putHistory hist >> loop flags f [] TC.verboseEnv)
Right (adefs,names) -> do
(merr,tenv) <-
TC.runDeclss TC.verboseEnv (takeWhile (\x -> fst (head x) /= "stop") adefs)
case merr of
Just err -> putStrLn $ "Type checking failed: " ++ shrink err
Nothing -> putStrLn "File loaded."
-- Compute names for auto completion
runInputT (settings [n | (n,_) <- names]) (putHistory hist >> loop flags f names tenv)
-- The main loop
loop :: [Flag] -> FilePath -> [(CTT.Ident,SymKind)] -> TC.TEnv -> Interpreter ()
loop flags f names tenv = do
input <- getInputLine prompt
case input of
Nothing -> outputStrLn help >> loop flags f names tenv
Just ":q" -> return ()
Just ":r" -> getHistory >>= lift . initLoop flags f
Just (':':'l':' ':str)
| ' ' `elem` str -> do outputStrLn "Only one file allowed after :l"
loop flags f names tenv
| otherwise -> getHistory >>= lift . initLoop flags str
Just (':':'c':'d':' ':str) -> do lift (setCurrentDirectory str)
loop flags f names tenv
Just ":h" -> outputStrLn help >> loop flags f names tenv
Just str' ->
let (msg,str,mod) = case str' of
(':':'n':' ':str) ->
("NORMEVAL: ",str,E.normal [])
str -> ("EVAL: ",str,id)
in case pExp (lexer str) of
Bad err -> outputStrLn ("Parse error: " ++ err) >> loop flags f names tenv
Ok exp ->
case runResolver $ local (insertIdents names) $ resolveExp exp of
Left err -> do outputStrLn ("Resolver failed: " ++ err)
loop flags f names tenv
Right body -> do
x <- liftIO $ TC.runInfer tenv body
case x of
Left err -> do outputStrLn ("Could not type-check: " ++ err)
loop flags f names tenv
Right _ -> do
start <- liftIO getCurrentTime
let e = mod $ E.eval (TC.env tenv) body
-- Let's not crash if the evaluation raises an error:
liftIO $ catch (putStrLn (msg ++ shrink (show e)))
-- (writeFile "examples/nunivalence3.ctt" (show e))
(\e -> putStrLn ("Exception: " ++
show (e :: SomeException)))
stop <- liftIO getCurrentTime
-- Compute time and print nicely
let time = diffUTCTime stop start
secs = read (takeWhile (/='.') (init (show time)))
rest = read ('0':dropWhile (/='.') (init (show time)))
mins = secs `quot` 60
sec = printf "%.3f" (fromInteger (secs `rem` 60) + rest :: Float)
when (Time `elem` flags) $
outputStrLn $ "Time: " ++ show mins ++ "m" ++ sec ++ "s"
-- Only print in seconds:
-- when (Time `elem` flags) $ outputStrLn $ "Time: " ++ show time
loop flags f names tenv
-- (not ok,loaded,already loaded defs) -> to load ->
-- (new not ok, new loaded, new defs)
-- the bool determines if it should be verbose or not
imports :: Bool -> ([String],[String],[Module]) -> String ->
IO ([String],[String],[Module])
imports v st@(notok,loaded,mods) f
| f `elem` notok = putStrLn ("Looping imports in " ++ f) >> return ([],[],[])
| f `elem` loaded = return st
| otherwise = do
b <- doesFileExist f
let prefix = dropFileName f
if not b
then putStrLn (f ++ " does not exist") >> return ([],[],[])
else do
s <- readFile f
let ts = lexer s
case pModule ts of
Bad s -> do
putStrLn $ "Parse failed in " ++ show f ++ "\n" ++ show s
return ([],[],[])
Ok mod@(Module (AIdent (_,name)) imp decls) ->
let imp_ctt = [prefix ++ i ++ ".ctt" | Import (AIdent (_,i)) <- imp]
in do
when (name /= dropExtension (takeFileName f)) $
error $ "Module name mismatch " ++ show (f,name)
(notok1,loaded1,mods1) <-
foldM (imports v) (f:notok,loaded,mods) imp_ctt
when v $ putStrLn $ "Parsed " ++ show f ++ " successfully!"
return (notok,f:loaded1,mods1 ++ [mod])
help :: String
help = "\nAvailable commands:\n" ++
" <statement> infer type and evaluate statement\n" ++
" :n <statement> normalize statement\n" ++
" :q quit\n" ++
" :l <filename> loads filename (and resets environment before)\n" ++
" :cd <path> change directory to path\n" ++
" :r reload\n" ++
" :h display this message\n"
|
abooij/cubicaltt
|
Main.hs
|
mit
| 7,830 | 1 | 35 | 2,479 | 2,505 | 1,280 | 1,225 | 165 | 11 |
-- | An architecture independent description of a register.
-- This needs to stay architecture independent because it is used
-- by NCGMonad and the register allocators, which are shared
-- by all architectures.
--
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
-- http://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details
module Reg (
RegNo,
Reg(..),
regPair,
regSingle,
isRealReg, takeRealReg,
isVirtualReg, takeVirtualReg,
VirtualReg(..),
renameVirtualReg,
classOfVirtualReg,
getHiVirtualRegFromLo,
getHiVRegFromLo,
RealReg(..),
regNosOfRealReg,
realRegsAlias,
liftPatchFnToRegReg
)
where
import Outputable
import Unique
import RegClass
import Data.List
-- | An identifier for a primitive real machine register.
type RegNo
= Int
-- VirtualRegs are virtual registers. The register allocator will
-- eventually have to map them into RealRegs, or into spill slots.
--
-- VirtualRegs are allocated on the fly, usually to represent a single
-- value in the abstract assembly code (i.e. dynamic registers are
-- usually single assignment).
--
-- The single assignment restriction isn't necessary to get correct code,
-- although a better register allocation will result if single
-- assignment is used -- because the allocator maps a VirtualReg into
-- a single RealReg, even if the VirtualReg has multiple live ranges.
--
-- Virtual regs can be of either class, so that info is attached.
--
data VirtualReg
= VirtualRegI {-# UNPACK #-} !Unique
| VirtualRegHi {-# UNPACK #-} !Unique -- High part of 2-word register
| VirtualRegF {-# UNPACK #-} !Unique
| VirtualRegD {-# UNPACK #-} !Unique
| VirtualRegSSE {-# UNPACK #-} !Unique
deriving (Eq, Show, Ord)
instance Uniquable VirtualReg where
getUnique reg
= case reg of
VirtualRegI u -> u
VirtualRegHi u -> u
VirtualRegF u -> u
VirtualRegD u -> u
VirtualRegSSE u -> u
instance Outputable VirtualReg where
ppr reg
= case reg of
VirtualRegI u -> text "%vI_" <> pprUnique u
VirtualRegHi u -> text "%vHi_" <> pprUnique u
VirtualRegF u -> text "%vF_" <> pprUnique u
VirtualRegD u -> text "%vD_" <> pprUnique u
VirtualRegSSE u -> text "%vSSE_" <> pprUnique u
renameVirtualReg :: Unique -> VirtualReg -> VirtualReg
renameVirtualReg u r
= case r of
VirtualRegI _ -> VirtualRegI u
VirtualRegHi _ -> VirtualRegHi u
VirtualRegF _ -> VirtualRegF u
VirtualRegD _ -> VirtualRegD u
VirtualRegSSE _ -> VirtualRegSSE u
classOfVirtualReg :: VirtualReg -> RegClass
classOfVirtualReg vr
= case vr of
VirtualRegI{} -> RcInteger
VirtualRegHi{} -> RcInteger
VirtualRegF{} -> RcFloat
VirtualRegD{} -> RcDouble
VirtualRegSSE{} -> RcDoubleSSE
-- Determine the upper-half vreg for a 64-bit quantity on a 32-bit platform
-- when supplied with the vreg for the lower-half of the quantity.
-- (NB. Not reversible).
getHiVirtualRegFromLo :: VirtualReg -> VirtualReg
getHiVirtualRegFromLo reg
= case reg of
-- makes a pseudo-unique with tag 'H'
VirtualRegI u -> VirtualRegHi (newTagUnique u 'H')
_ -> panic "Reg.getHiVirtualRegFromLo"
getHiVRegFromLo :: Reg -> Reg
getHiVRegFromLo reg
= case reg of
RegVirtual vr -> RegVirtual (getHiVirtualRegFromLo vr)
RegReal _ -> panic "Reg.getHiVRegFromLo"
------------------------------------------------------------------------------------
-- | RealRegs are machine regs which are available for allocation, in
-- the usual way. We know what class they are, because that's part of
-- the processor's architecture.
--
-- RealRegPairs are pairs of real registers that are allocated together
-- to hold a larger value, such as with Double regs on SPARC.
--
data RealReg
= RealRegSingle {-# UNPACK #-} !RegNo
| RealRegPair {-# UNPACK #-} !RegNo {-# UNPACK #-} !RegNo
deriving (Eq, Show, Ord)
instance Uniquable RealReg where
getUnique reg
= case reg of
RealRegSingle i -> mkRegSingleUnique i
RealRegPair r1 r2 -> mkRegPairUnique (r1 * 65536 + r2)
instance Outputable RealReg where
ppr reg
= case reg of
RealRegSingle i -> text "%r" <> int i
RealRegPair r1 r2 -> text "%r(" <> int r1 <> text "|" <> int r2 <> text ")"
regNosOfRealReg :: RealReg -> [RegNo]
regNosOfRealReg rr
= case rr of
RealRegSingle r1 -> [r1]
RealRegPair r1 r2 -> [r1, r2]
realRegsAlias :: RealReg -> RealReg -> Bool
realRegsAlias rr1 rr2
= not $ null $ intersect (regNosOfRealReg rr1) (regNosOfRealReg rr2)
--------------------------------------------------------------------------------
-- | A register, either virtual or real
data Reg
= RegVirtual !VirtualReg
| RegReal !RealReg
deriving (Eq, Ord)
regSingle :: RegNo -> Reg
regSingle regNo = RegReal $ RealRegSingle regNo
regPair :: RegNo -> RegNo -> Reg
regPair regNo1 regNo2 = RegReal $ RealRegPair regNo1 regNo2
-- We like to have Uniques for Reg so that we can make UniqFM and UniqSets
-- in the register allocator.
instance Uniquable Reg where
getUnique reg
= case reg of
RegVirtual vr -> getUnique vr
RegReal rr -> getUnique rr
-- | Print a reg in a generic manner
-- If you want the architecture specific names, then use the pprReg
-- function from the appropriate Ppr module.
instance Outputable Reg where
ppr reg
= case reg of
RegVirtual vr -> ppr vr
RegReal rr -> ppr rr
isRealReg :: Reg -> Bool
isRealReg reg
= case reg of
RegReal _ -> True
RegVirtual _ -> False
takeRealReg :: Reg -> Maybe RealReg
takeRealReg reg
= case reg of
RegReal rr -> Just rr
_ -> Nothing
isVirtualReg :: Reg -> Bool
isVirtualReg reg
= case reg of
RegReal _ -> False
RegVirtual _ -> True
takeVirtualReg :: Reg -> Maybe VirtualReg
takeVirtualReg reg
= case reg of
RegReal _ -> Nothing
RegVirtual vr -> Just vr
-- | The patch function supplied by the allocator maps VirtualReg to RealReg
-- regs, but sometimes we want to apply it to plain old Reg.
--
liftPatchFnToRegReg :: (VirtualReg -> RealReg) -> (Reg -> Reg)
liftPatchFnToRegReg patchF reg
= case reg of
RegVirtual vr -> RegReal (patchF vr)
RegReal _ -> reg
|
lukexi/ghc-7.8-arm64
|
compiler/nativeGen/Reg.hs
|
bsd-3-clause
| 6,224 | 155 | 12 | 1,194 | 1,320 | 718 | 602 | 141 | 5 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
#ifdef TRUSTWORTHY
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Cons
-- Copyright : (C) 2012-15 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-----------------------------------------------------------------------------
module Control.Lens.Cons
(
-- * Cons
Cons(..)
, (<|)
, cons
, uncons
, _head, _tail
-- * Snoc
, Snoc(..)
, (|>)
, snoc
, unsnoc
, _init, _last
) where
import Control.Lens.Equality (simply)
import Control.Lens.Fold
import Control.Lens.Prism
import Control.Lens.Review
import Control.Lens.Tuple
import Control.Lens.Type
import qualified Data.ByteString as StrictB
import qualified Data.ByteString.Lazy as LazyB
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NonEmpty
import Data.Monoid
import qualified Data.Sequence as Seq
import Data.Sequence hiding ((<|), (|>))
import qualified Data.Text as StrictT
import qualified Data.Text.Lazy as LazyT
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import Data.Vector.Storable (Storable)
import qualified Data.Vector.Storable as Storable
import Data.Vector.Primitive (Prim)
import qualified Data.Vector.Primitive as Prim
import Data.Vector.Unboxed (Unbox)
import qualified Data.Vector.Unboxed as Unbox
import Data.Word
import Prelude
{-# ANN module "HLint: ignore Eta reduce" #-}
-- $setup
-- >>> :set -XNoOverloadedStrings
-- >>> import Control.Lens
-- >>> import Debug.SimpleReflect.Expr
-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g)
-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f
-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g
infixr 5 <|, `cons`
infixl 5 |>, `snoc`
------------------------------------------------------------------------------
-- Cons
------------------------------------------------------------------------------
-- | This class provides a way to attach or detach elements on the left
-- side of a structure in a flexible manner.
class Cons s t a b | s -> a, t -> b, s b -> t, t a -> s where
-- |
--
-- @
-- '_Cons' :: 'Prism' [a] [b] (a, [a]) (b, [b])
-- '_Cons' :: 'Prism' ('Seq' a) ('Seq' b) (a, 'Seq' a) (b, 'Seq' b)
-- '_Cons' :: 'Prism' ('Vector' a) ('Vector' b) (a, 'Vector' a) (b, 'Vector' b)
-- '_Cons' :: 'Prism'' 'String' ('Char', 'String')
-- '_Cons' :: 'Prism'' 'StrictT.Text' ('Char', 'StrictT.Text')
-- '_Cons' :: 'Prism'' 'StrictB.ByteString' ('Word8', 'StrictB.ByteString')
-- @
_Cons :: Prism s t (a,s) (b,t)
instance Cons [a] [b] a b where
_Cons = prism (uncurry (:)) $ \ aas -> case aas of
(a:as) -> Right (a, as)
[] -> Left []
{-# INLINE _Cons #-}
instance a~b => Cons (NonEmpty a) (NonEmpty b) a b where
_Cons = prism' (uncurry NonEmpty.cons) $ \ xyz -> case xyz of
(x:|y:z) -> Just (x,y:|z)
_ -> Nothing
{-# INLINE _Cons #-}
instance Cons (Seq a) (Seq b) a b where
_Cons = prism (uncurry (Seq.<|)) $ \aas -> case viewl aas of
a :< as -> Right (a, as)
EmptyL -> Left mempty
{-# INLINE _Cons #-}
instance Cons StrictB.ByteString StrictB.ByteString Word8 Word8 where
_Cons = prism' (uncurry StrictB.cons) StrictB.uncons
{-# INLINE _Cons #-}
instance Cons LazyB.ByteString LazyB.ByteString Word8 Word8 where
_Cons = prism' (uncurry LazyB.cons) LazyB.uncons
{-# INLINE _Cons #-}
instance Cons StrictT.Text StrictT.Text Char Char where
_Cons = prism' (uncurry StrictT.cons) StrictT.uncons
{-# INLINE _Cons #-}
instance Cons LazyT.Text LazyT.Text Char Char where
_Cons = prism' (uncurry LazyT.cons) LazyT.uncons
{-# INLINE _Cons #-}
instance Cons (Vector a) (Vector b) a b where
_Cons = prism (uncurry Vector.cons) $ \v ->
if Vector.null v
then Left Vector.empty
else Right (Vector.unsafeHead v, Vector.unsafeTail v)
{-# INLINE _Cons #-}
instance (Prim a, Prim b) => Cons (Prim.Vector a) (Prim.Vector b) a b where
_Cons = prism (uncurry Prim.cons) $ \v ->
if Prim.null v
then Left Prim.empty
else Right (Prim.unsafeHead v, Prim.unsafeTail v)
{-# INLINE _Cons #-}
instance (Storable a, Storable b) => Cons (Storable.Vector a) (Storable.Vector b) a b where
_Cons = prism (uncurry Storable.cons) $ \v ->
if Storable.null v
then Left Storable.empty
else Right (Storable.unsafeHead v, Storable.unsafeTail v)
{-# INLINE _Cons #-}
instance (Unbox a, Unbox b) => Cons (Unbox.Vector a) (Unbox.Vector b) a b where
_Cons = prism (uncurry Unbox.cons) $ \v ->
if Unbox.null v
then Left Unbox.empty
else Right (Unbox.unsafeHead v, Unbox.unsafeTail v)
{-# INLINE _Cons #-}
-- | 'cons' an element onto a container.
--
-- This is an infix alias for 'cons'.
--
-- >>> a <| []
-- [a]
--
-- >>> a <| [b, c]
-- [a,b,c]
--
-- >>> a <| Seq.fromList []
-- fromList [a]
--
-- >>> a <| Seq.fromList [b, c]
-- fromList [a,b,c]
(<|) :: Cons s s a a => a -> s -> s
(<|) = curry (simply review _Cons)
{-# INLINE (<|) #-}
-- | 'cons' an element onto a container.
--
-- >>> cons a []
-- [a]
--
-- >>> cons a [b, c]
-- [a,b,c]
--
-- >>> cons a (Seq.fromList [])
-- fromList [a]
--
-- >>> cons a (Seq.fromList [b, c])
-- fromList [a,b,c]
cons :: Cons s s a a => a -> s -> s
cons = curry (simply review _Cons)
{-# INLINE cons #-}
-- | Attempt to extract the left-most element from a container, and a version of the container without that element.
--
-- >>> uncons []
-- Nothing
--
-- >>> uncons [a, b, c]
-- Just (a,[b,c])
uncons :: Cons s s a a => s -> Maybe (a, s)
uncons = simply preview _Cons
{-# INLINE uncons #-}
-- | A 'Traversal' reading and writing to the 'head' of a /non-empty/ container.
--
-- >>> [a,b,c]^? _head
-- Just a
--
-- >>> [a,b,c] & _head .~ d
-- [d,b,c]
--
-- >>> [a,b,c] & _head %~ f
-- [f a,b,c]
--
-- >>> [] & _head %~ f
-- []
--
-- >>> [1,2,3]^?!_head
-- 1
--
-- >>> []^?_head
-- Nothing
--
-- >>> [1,2]^?_head
-- Just 1
--
-- >>> [] & _head .~ 1
-- []
--
-- >>> [0] & _head .~ 2
-- [2]
--
-- >>> [0,1] & _head .~ 2
-- [2,1]
--
-- This isn't limited to lists.
--
-- For instance you can also 'Data.Traversable.traverse' the head of a 'Seq':
--
-- >>> Seq.fromList [a,b,c,d] & _head %~ f
-- fromList [f a,b,c,d]
--
-- >>> Seq.fromList [] ^? _head
-- Nothing
--
-- >>> Seq.fromList [a,b,c,d] ^? _head
-- Just a
--
-- @
-- '_head' :: 'Traversal'' [a] a
-- '_head' :: 'Traversal'' ('Seq' a) a
-- '_head' :: 'Traversal'' ('Vector' a) a
-- @
_head :: Cons s s a a => Traversal' s a
_head = _Cons._1
{-# INLINE _head #-}
-- | A 'Traversal' reading and writing to the 'tail' of a /non-empty/ container.
--
-- >>> [a,b] & _tail .~ [c,d,e]
-- [a,c,d,e]
--
-- >>> [] & _tail .~ [a,b]
-- []
--
-- >>> [a,b,c,d,e] & _tail.traverse %~ f
-- [a,f b,f c,f d,f e]
--
-- >>> [1,2] & _tail .~ [3,4,5]
-- [1,3,4,5]
--
-- >>> [] & _tail .~ [1,2]
-- []
--
-- >>> [a,b,c]^?_tail
-- Just [b,c]
--
-- >>> [1,2]^?!_tail
-- [2]
--
-- >>> "hello"^._tail
-- "ello"
--
-- >>> ""^._tail
-- ""
--
-- This isn't limited to lists. For instance you can also 'Control.Traversable.traverse' the tail of a 'Seq'.
--
-- >>> Seq.fromList [a,b] & _tail .~ Seq.fromList [c,d,e]
-- fromList [a,c,d,e]
--
-- >>> Seq.fromList [a,b,c] ^? _tail
-- Just (fromList [b,c])
--
-- >>> Seq.fromList [] ^? _tail
-- Nothing
--
-- @
-- '_tail' :: 'Traversal'' [a] [a]
-- '_tail' :: 'Traversal'' ('Seq' a) ('Seq' a)
-- '_tail' :: 'Traversal'' ('Vector' a) ('Vector' a)
-- @
_tail :: Cons s s a a => Traversal' s s
_tail = _Cons._2
{-# INLINE _tail #-}
------------------------------------------------------------------------------
-- Snoc
------------------------------------------------------------------------------
-- | This class provides a way to attach or detach elements on the right
-- side of a structure in a flexible manner.
class Snoc s t a b | s -> a, t -> b, s b -> t, t a -> s where
-- |
--
-- @
-- '_Snoc' :: 'Prism' [a] [b] ([a], a) ([b], b)
-- '_Snoc' :: 'Prism' ('Seq' a) ('Seq' b) ('Seq' a, a) ('Seq' b, b)
-- '_Snoc' :: 'Prism' ('Vector' a) ('Vector' b) ('Vector' a, a) ('Vector' b, b)
-- '_Snoc' :: 'Prism'' 'String' ('String', 'Char')
-- '_Snoc' :: 'Prism'' 'StrictT.Text' ('StrictT.Text', 'Char')
-- '_Snoc' :: 'Prism'' 'StrictB.ByteString' ('StrictB.ByteString', 'Word8')
-- @
_Snoc :: Prism s t (s,a) (t,b)
instance Snoc [a] [b] a b where
_Snoc = prism (\(as,a) -> as Prelude.++ [a]) $ \aas -> if Prelude.null aas
then Left []
else Right (Prelude.init aas, Prelude.last aas)
{-# INLINE _Snoc #-}
instance a~b => Snoc (NonEmpty a) (NonEmpty b) a b where
_Snoc = prism' (\(x:|y,z) -> x:|y++[z]) $ \xyz -> case xyz of
x:|y
| Prelude.null y -> Nothing
| otherwise -> Just (x :| Prelude.init y, Prelude.last y)
instance Snoc (Seq a) (Seq b) a b where
_Snoc = prism (uncurry (Seq.|>)) $ \aas -> case viewr aas of
as :> a -> Right (as, a)
EmptyR -> Left mempty
{-# INLINE _Snoc #-}
instance Snoc (Vector a) (Vector b) a b where
_Snoc = prism (uncurry Vector.snoc) $ \v -> if Vector.null v
then Left Vector.empty
else Right (Vector.unsafeInit v, Vector.unsafeLast v)
{-# INLINE _Snoc #-}
instance (Prim a, Prim b) => Snoc (Prim.Vector a) (Prim.Vector b) a b where
_Snoc = prism (uncurry Prim.snoc) $ \v -> if Prim.null v
then Left Prim.empty
else Right (Prim.unsafeInit v, Prim.unsafeLast v)
{-# INLINE _Snoc #-}
instance (Storable a, Storable b) => Snoc (Storable.Vector a) (Storable.Vector b) a b where
_Snoc = prism (uncurry Storable.snoc) $ \v -> if Storable.null v
then Left Storable.empty
else Right (Storable.unsafeInit v, Storable.unsafeLast v)
{-# INLINE _Snoc #-}
instance (Unbox a, Unbox b) => Snoc (Unbox.Vector a) (Unbox.Vector b) a b where
_Snoc = prism (uncurry Unbox.snoc) $ \v -> if Unbox.null v
then Left Unbox.empty
else Right (Unbox.unsafeInit v, Unbox.unsafeLast v)
{-# INLINE _Snoc #-}
instance Snoc StrictB.ByteString StrictB.ByteString Word8 Word8 where
_Snoc = prism (uncurry StrictB.snoc) $ \v -> if StrictB.null v
then Left StrictB.empty
else Right (StrictB.init v, StrictB.last v)
{-# INLINE _Snoc #-}
instance Snoc LazyB.ByteString LazyB.ByteString Word8 Word8 where
_Snoc = prism (uncurry LazyB.snoc) $ \v -> if LazyB.null v
then Left LazyB.empty
else Right (LazyB.init v, LazyB.last v)
{-# INLINE _Snoc #-}
instance Snoc StrictT.Text StrictT.Text Char Char where
_Snoc = prism (uncurry StrictT.snoc) $ \v -> if StrictT.null v
then Left StrictT.empty
else Right (StrictT.init v, StrictT.last v)
{-# INLINE _Snoc #-}
instance Snoc LazyT.Text LazyT.Text Char Char where
_Snoc = prism (uncurry LazyT.snoc) $ \v -> if LazyT.null v
then Left LazyT.empty
else Right (LazyT.init v, LazyT.last v)
{-# INLINE _Snoc #-}
-- | A 'Traversal' reading and replacing all but the a last element of a /non-empty/ container.
--
-- >>> [a,b,c,d]^?_init
-- Just [a,b,c]
--
-- >>> []^?_init
-- Nothing
--
-- >>> [a,b] & _init .~ [c,d,e]
-- [c,d,e,b]
--
-- >>> [] & _init .~ [a,b]
-- []
--
-- >>> [a,b,c,d] & _init.traverse %~ f
-- [f a,f b,f c,d]
--
-- >>> [1,2,3]^?_init
-- Just [1,2]
--
-- >>> [1,2,3,4]^?!_init
-- [1,2,3]
--
-- >>> "hello"^._init
-- "hell"
--
-- >>> ""^._init
-- ""
--
-- @
-- '_init' :: 'Traversal'' [a] [a]
-- '_init' :: 'Traversal'' ('Seq' a) ('Seq' a)
-- '_init' :: 'Traversal'' ('Vector' a) ('Vector' a)
-- @
_init :: Snoc s s a a => Traversal' s s
_init = _Snoc._1
{-# INLINE _init #-}
-- | A 'Traversal' reading and writing to the last element of a /non-empty/ container.
--
-- >>> [a,b,c]^?!_last
-- c
--
-- >>> []^?_last
-- Nothing
--
-- >>> [a,b,c] & _last %~ f
-- [a,b,f c]
--
-- >>> [1,2]^?_last
-- Just 2
--
-- >>> [] & _last .~ 1
-- []
--
-- >>> [0] & _last .~ 2
-- [2]
--
-- >>> [0,1] & _last .~ 2
-- [0,2]
--
-- This 'Traversal' is not limited to lists, however. We can also work with other containers, such as a 'Vector'.
--
-- >>> Vector.fromList "abcde" ^? _last
-- Just 'e'
--
-- >>> Vector.empty ^? _last
-- Nothing
--
-- >>> (Vector.fromList "abcde" & _last .~ 'Q') == Vector.fromList "abcdQ"
-- True
--
-- @
-- '_last' :: 'Traversal'' [a] a
-- '_last' :: 'Traversal'' ('Seq' a) a
-- '_last' :: 'Traversal'' ('Vector' a) a
-- @
_last :: Snoc s s a a => Traversal' s a
_last = _Snoc._2
{-# INLINE _last #-}
-- | 'snoc' an element onto the end of a container.
--
-- This is an infix alias for 'snoc'.
--
-- >>> Seq.fromList [] |> a
-- fromList [a]
--
-- >>> Seq.fromList [b, c] |> a
-- fromList [b,c,a]
--
-- >>> LazyT.pack "hello" |> '!'
-- "hello!"
(|>) :: Snoc s s a a => s -> a -> s
(|>) = curry (simply review _Snoc)
{-# INLINE (|>) #-}
-- | 'snoc' an element onto the end of a container.
--
-- >>> snoc (Seq.fromList []) a
-- fromList [a]
--
-- >>> snoc (Seq.fromList [b, c]) a
-- fromList [b,c,a]
--
-- >>> snoc (LazyT.pack "hello") '!'
-- "hello!"
snoc :: Snoc s s a a => s -> a -> s
snoc = curry (simply review _Snoc)
{-# INLINE snoc #-}
-- | Attempt to extract the right-most element from a container, and a version of the container without that element.
--
-- >>> unsnoc (LazyT.pack "hello!")
-- Just ("hello",'!')
--
-- >>> unsnoc (LazyT.pack "")
-- Nothing
--
-- >>> unsnoc (Seq.fromList [b,c,a])
-- Just (fromList [b,c],a)
--
-- >>> unsnoc (Seq.fromList [])
-- Nothing
unsnoc :: Snoc s s a a => s -> Maybe (s, a)
unsnoc s = simply preview _Snoc s
{-# INLINE unsnoc #-}
|
rpglover64/lens
|
src/Control/Lens/Cons.hs
|
bsd-3-clause
| 13,810 | 0 | 16 | 2,817 | 3,017 | 1,764 | 1,253 | 186 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
import Conduit
import Data.List (stripPrefix)
import Options.Generic
import RIO
import RIO.Char (toLower)
import RIO.Directory hiding (findExecutable)
import RIO.FilePath
import RIO.List (isInfixOf, partition)
import qualified RIO.Map as Map
import RIO.Process
import qualified RIO.Set as Set
import qualified RIO.Text as T
import System.Environment (lookupEnv, getExecutablePath)
import System.Info (os)
import System.PosixCompat.Files
-- This code does not use a test framework so that we get direct
-- control of how the output is displayed.
main :: IO ()
main = runSimpleApp $ do
logInfo "Initiating Stack integration test running"
options <- getRecord "Stack integration tests"
results <- runApp options $ do
logInfo "Running with the following environment"
proc "env" [] runProcess_
tests <- asks appTestDirs
let count = Set.size tests
loop !idx rest !accum =
case rest of
[] -> pure accum
next:rest' -> do
logInfo $ "Running integration test "
<> display idx
<> "/"
<> display count
<> ": "
<> fromString (takeFileName next)
res <- test next
loop (idx + 1) rest' (res <> accum)
loop (1 :: Int) (Set.toList tests) mempty
let (successes, failures) = partition ((== ExitSuccess) . snd)
$ Map.toList results
unless (null successes) $ do
logInfo "Successful tests:"
for_ successes $ \(x, _) -> logInfo $ "- " <> display x
logInfo ""
if null failures
then logInfo "No failures!"
else do
logInfo "Failed tests:"
for_ failures $ \(x, ec) -> logInfo $ "- " <> display x <> " - " <> displayShow ec
exitFailure
data Options = Options
{ optSpeed :: Maybe Speed
, optMatch :: Maybe String
} deriving Generic
instance ParseRecord Options where
parseRecord = parseRecordWithModifiers modifiers
where
optName = map toLower . drop 3
modifiers = defaultModifiers { fieldNameModifier = optName
, shortNameModifier = firstLetter . optName
}
data Speed = Fast | Normal | Superslow
deriving (Read, Generic)
instance ParseField Speed
exeExt :: String
exeExt = if isWindows then ".exe" else ""
isWindows :: Bool
isWindows = os == "mingw32"
runApp :: Options -> RIO App a -> RIO SimpleApp a
runApp options inner = do
let speed = fromMaybe Normal $ optSpeed options
simpleApp <- ask
runghc <- findExecutable "runghc" >>= either throwIO pure
srcDir <- canonicalizePath ""
testsRoot <- canonicalizePath $ srcDir </> "test/integration"
libdir <- canonicalizePath $ testsRoot </> "lib"
myPath <- liftIO getExecutablePath
stack <- canonicalizePath $ takeDirectory myPath </> "stack" ++ exeExt
logInfo $ "Using stack located at " <> fromString stack
proc stack ["--version"] runProcess_
let matchTest = case optMatch options of
Nothing -> const True
Just str -> (str `isInfixOf`)
testDirs
<- runConduitRes
$ sourceDirectory (testsRoot </> "tests")
.| filterMC (liftIO . hasTest)
.| filterC matchTest
.| foldMapC Set.singleton
let modifyEnvCommon
= Map.insert "SRC_DIR" (fromString srcDir)
. Map.insert "STACK_EXE" (fromString stack)
. Map.delete "GHC_PACKAGE_PATH"
. Map.insert "STACK_TEST_SPEED"
(case speed of
Superslow -> "SUPERSLOW"
_ -> "NORMAL")
. Map.fromList
. map (first T.toUpper)
. Map.toList
case speed of
Fast -> do
let app = App
{ appSimpleApp = simpleApp
, appRunghc = runghc
, appLibDir = libdir
, appSetupHome = id
, appTestDirs = testDirs
}
runRIO app $ withModifyEnvVars modifyEnvCommon inner
_ -> do
morigStackRoot <- liftIO $ lookupEnv "STACK_ROOT"
origStackRoot <-
case morigStackRoot of
Nothing -> getAppUserDataDirectory "stack"
Just x -> pure x
logInfo "Initializing/updating the original Pantry store"
proc stack ["update"] runProcess_
pantryRoot <- canonicalizePath $ origStackRoot </> "pantry"
let modifyEnv
= Map.insert "PANTRY_ROOT" (fromString pantryRoot)
. modifyEnvCommon
app = App
{ appSimpleApp = simpleApp
, appRunghc = runghc
, appLibDir = libdir
, appSetupHome = \inner' -> withSystemTempDirectory "home" $ \newHome -> do
let newStackRoot = newHome </> ".stack"
createDirectoryIfMissing True newStackRoot
let modifyEnv'
= Map.insert "HOME" (fromString newHome)
. Map.insert "APPDATA" (fromString newHome)
. Map.insert "STACK_ROOT" (fromString newStackRoot)
writeFileBinary (newStackRoot </> "config.yaml") "system-ghc: true\ninstall-ghc: false\n"
withModifyEnvVars modifyEnv' inner'
, appTestDirs = testDirs
}
runRIO app $ withModifyEnvVars modifyEnv inner
hasTest :: FilePath -> IO Bool
hasTest dir = doesFileExist $ dir </> "Main.hs"
data App = App
{ appRunghc :: !FilePath
, appLibDir :: !FilePath
, appSetupHome :: !(forall a. RIO App a -> RIO App a)
, appSimpleApp :: !SimpleApp
, appTestDirs :: !(Set FilePath)
}
simpleAppL :: Lens' App SimpleApp
simpleAppL = lens appSimpleApp (\x y -> x { appSimpleApp = y })
instance HasLogFunc App where
logFuncL = simpleAppL.logFuncL
instance HasProcessContext App where
processContextL = simpleAppL.processContextL
-- | Call 'appSetupHome' on the inner action
withHome :: RIO App a -> RIO App a
withHome inner = do
app <- ask
appSetupHome app inner
test :: FilePath -- ^ test dir
-> RIO App (Map Text ExitCode)
test testDir = withDir $ \dir -> withHome $ do
runghc <- asks appRunghc
libDir <- asks appLibDir
let mainFile = testDir </> "Main.hs"
copyTree (testDir </> "files") dir
withSystemTempFile (name <.> "log") $ \logfp logh -> do
ec <- withWorkingDir dir
$ withModifyEnvVars (Map.insert "TEST_DIR" $ fromString testDir)
$ proc runghc
[ "-clear-package-db"
, "-global-package-db"
, "-i" ++ libDir
, mainFile
]
$ runProcess
. setStdin closed
. setStdout (useHandleOpen logh)
. setStderr (useHandleOpen logh)
hClose logh
case ec of
ExitSuccess -> logInfo "Success!"
_ -> do
logError "Failure, dumping log\n\n"
withSourceFile logfp $ \src ->
runConduit $ src .| stderrC
logError $ "\n\nEnd of log for " <> fromString name
pure $ Map.singleton (fromString name) ec
where
name = takeFileName testDir
withDir = withSystemTempDirectory ("stack-integration-" ++ name)
copyTree :: MonadIO m => FilePath -> FilePath -> m ()
copyTree src dst =
liftIO $
runResourceT (sourceDirectoryDeep False src `connect` mapM_C go)
`catch` \(_ :: IOException) -> return ()
where
go srcfp = liftIO $ do
Just suffix <- return $ stripPrefix src srcfp
let dstfp = dst </> stripHeadSeparator suffix
createDirectoryIfMissing True $ takeDirectory dstfp
-- copying yaml files so lock files won't get created in
-- the source directory
if takeFileName srcfp /= "package.yaml" &&
(takeExtensions srcfp == ".yaml" || takeExtensions srcfp == ".yml")
then
copyFile srcfp dstfp
else
createSymbolicLink srcfp dstfp `catch` \(_ :: IOException) ->
copyFile srcfp dstfp -- for Windows
stripHeadSeparator :: FilePath -> FilePath
stripHeadSeparator [] = []
stripHeadSeparator fp@(x:xs) = if isPathSeparator x
then xs
else fp
|
juhp/stack
|
test/integration/IntegrationSpec.hs
|
bsd-3-clause
| 8,590 | 3 | 29 | 2,779 | 2,207 | 1,095 | 1,112 | 216 | 5 |
{-# LANGUAGE MagicHash #-}
module ShouldFail where
import GHC.Base
die :: Int -> ByteArray#
die _ = undefined
|
hvr/jhc
|
regress/tests/1_typecheck/4_fail/ghc/tcfail090.hs
|
mit
| 113 | 0 | 5 | 21 | 27 | 16 | 11 | 5 | 1 |
{-# LANGUAGE UnboxedTuples #-}
-- | State monad for the linear register allocator.
-- Here we keep all the state that the register allocator keeps track
-- of as it walks the instructions in a basic block.
module RegAlloc.Linear.State (
RA_State(..),
RegM,
runR,
spillR,
loadR,
getFreeRegsR,
setFreeRegsR,
getAssigR,
setAssigR,
getBlockAssigR,
setBlockAssigR,
setDeltaR,
getDeltaR,
getUniqueR,
recordSpill
)
where
import GhcPrelude
import RegAlloc.Linear.Stats
import RegAlloc.Linear.StackMap
import RegAlloc.Linear.Base
import RegAlloc.Liveness
import Instruction
import Reg
import DynFlags
import Unique
import UniqSupply
import Control.Monad (liftM, ap)
-- | The register allocator monad type.
newtype RegM freeRegs a
= RegM { unReg :: RA_State freeRegs -> (# RA_State freeRegs, a #) }
instance Functor (RegM freeRegs) where
fmap = liftM
instance Applicative (RegM freeRegs) where
pure a = RegM $ \s -> (# s, a #)
(<*>) = ap
instance Monad (RegM freeRegs) where
m >>= k = RegM $ \s -> case unReg m s of { (# s, a #) -> unReg (k a) s }
instance HasDynFlags (RegM a) where
getDynFlags = RegM $ \s -> (# s, ra_DynFlags s #)
-- | Run a computation in the RegM register allocator monad.
runR :: DynFlags
-> BlockAssignment freeRegs
-> freeRegs
-> RegMap Loc
-> StackMap
-> UniqSupply
-> RegM freeRegs a
-> (BlockAssignment freeRegs, StackMap, RegAllocStats, a)
runR dflags block_assig freeregs assig stack us thing =
case unReg thing
(RA_State
{ ra_blockassig = block_assig
, ra_freeregs = freeregs
, ra_assig = assig
, ra_delta = 0{-???-}
, ra_stack = stack
, ra_us = us
, ra_spills = []
, ra_DynFlags = dflags })
of
(# state'@RA_State
{ ra_blockassig = block_assig
, ra_stack = stack' }
, returned_thing #)
-> (block_assig, stack', makeRAStats state', returned_thing)
-- | Make register allocator stats from its final state.
makeRAStats :: RA_State freeRegs -> RegAllocStats
makeRAStats state
= RegAllocStats
{ ra_spillInstrs = binSpillReasons (ra_spills state) }
spillR :: Instruction instr
=> Reg -> Unique -> RegM freeRegs (instr, Int)
spillR reg temp = RegM $ \ s@RA_State{ra_delta=delta, ra_stack=stack} ->
let dflags = ra_DynFlags s
(stack',slot) = getStackSlotFor stack temp
instr = mkSpillInstr dflags reg delta slot
in
(# s{ra_stack=stack'}, (instr,slot) #)
loadR :: Instruction instr
=> Reg -> Int -> RegM freeRegs instr
loadR reg slot = RegM $ \ s@RA_State{ra_delta=delta} ->
let dflags = ra_DynFlags s
in (# s, mkLoadInstr dflags reg delta slot #)
getFreeRegsR :: RegM freeRegs freeRegs
getFreeRegsR = RegM $ \ s@RA_State{ra_freeregs = freeregs} ->
(# s, freeregs #)
setFreeRegsR :: freeRegs -> RegM freeRegs ()
setFreeRegsR regs = RegM $ \ s ->
(# s{ra_freeregs = regs}, () #)
getAssigR :: RegM freeRegs (RegMap Loc)
getAssigR = RegM $ \ s@RA_State{ra_assig = assig} ->
(# s, assig #)
setAssigR :: RegMap Loc -> RegM freeRegs ()
setAssigR assig = RegM $ \ s ->
(# s{ra_assig=assig}, () #)
getBlockAssigR :: RegM freeRegs (BlockAssignment freeRegs)
getBlockAssigR = RegM $ \ s@RA_State{ra_blockassig = assig} ->
(# s, assig #)
setBlockAssigR :: BlockAssignment freeRegs -> RegM freeRegs ()
setBlockAssigR assig = RegM $ \ s ->
(# s{ra_blockassig = assig}, () #)
setDeltaR :: Int -> RegM freeRegs ()
setDeltaR n = RegM $ \ s ->
(# s{ra_delta = n}, () #)
getDeltaR :: RegM freeRegs Int
getDeltaR = RegM $ \s -> (# s, ra_delta s #)
getUniqueR :: RegM freeRegs Unique
getUniqueR = RegM $ \s ->
case takeUniqFromSupply (ra_us s) of
(uniq, us) -> (# s{ra_us = us}, uniq #)
-- | Record that a spill instruction was inserted, for profiling.
recordSpill :: SpillReason -> RegM freeRegs ()
recordSpill spill
= RegM $ \s -> (# s { ra_spills = spill : ra_spills s}, () #)
|
shlevy/ghc
|
compiler/nativeGen/RegAlloc/Linear/State.hs
|
bsd-3-clause
| 4,270 | 0 | 13 | 1,203 | 1,238 | 687 | 551 | 109 | 1 |
module Syntax where
import Data.List
------------------------------------------------------------------
-- Abstract syntax -----------------------------------------------
------------------------------------------------------------------
-- info for all primops; the totality of the info in primops.txt(.pp)
data Info
= Info [Option] [Entry] -- defaults, primops
deriving Show
-- info for one primop
data Entry
= PrimOpSpec { cons :: String, -- PrimOp name
name :: String, -- name in prog text
ty :: Ty, -- type
cat :: Category, -- category
desc :: String, -- description
opts :: [Option] } -- default overrides
| PrimVecOpSpec { cons :: String, -- PrimOp name
name :: String, -- name in prog text
prefix :: String, -- prefix for generated names
veclen :: Int, -- vector length
elemrep :: String, -- vector ElemRep
ty :: Ty, -- type
cat :: Category, -- category
desc :: String, -- description
opts :: [Option] } -- default overrides
| PseudoOpSpec { name :: String, -- name in prog text
ty :: Ty, -- type
desc :: String, -- description
opts :: [Option] } -- default overrides
| PrimTypeSpec { ty :: Ty, -- name in prog text
desc :: String, -- description
opts :: [Option] } -- default overrides
| PrimVecTypeSpec { ty :: Ty, -- name in prog text
prefix :: String, -- prefix for generated names
veclen :: Int, -- vector length
elemrep :: String, -- vector ElemRep
desc :: String, -- description
opts :: [Option] } -- default overrides
| Section { title :: String, -- section title
desc :: String } -- description
deriving Show
is_primop :: Entry -> Bool
is_primop (PrimOpSpec _ _ _ _ _ _) = True
is_primop _ = False
is_primtype :: Entry -> Bool
is_primtype (PrimTypeSpec {}) = True
is_primtype _ = False
-- a binding of property to value
data Option
= OptionFalse String -- name = False
| OptionTrue String -- name = True
| OptionString String String -- name = { ... unparsed stuff ... }
| OptionInteger String Int -- name = <int>
| OptionVector [(String,String,Int)] -- name = [(,...),...]
| OptionFixity (Maybe Fixity) -- fixity = infix{,l,r} <int> | Nothing
deriving Show
-- categorises primops
data Category
= Dyadic | Monadic | Compare | GenPrimOp
deriving Show
-- types
data Ty
= TyF Ty Ty
| TyC Ty Ty -- We only allow one constraint, keeps the grammar simpler
| TyApp TyCon [Ty]
| TyVar TyVar
| TyUTup [Ty] -- unboxed tuples; just a TyCon really,
-- but convenient like this
deriving (Eq,Show)
type TyVar = String
data TyCon = TyCon String
| SCALAR
| VECTOR
| VECTUPLE
| VecTyCon String String
deriving (Eq, Ord)
instance Show TyCon where
show (TyCon tc) = tc
show SCALAR = "SCALAR"
show VECTOR = "VECTOR"
show VECTUPLE = "VECTUPLE"
show (VecTyCon tc _) = tc
-- Follow definitions of Fixity and FixityDirection in GHC
-- The String exists so that it matches the SourceText field in
-- BasicTypes.Fixity
data Fixity = Fixity String Int FixityDirection
deriving (Eq, Show)
data FixityDirection = InfixN | InfixL | InfixR
deriving (Eq, Show)
------------------------------------------------------------------
-- Sanity checking -----------------------------------------------
------------------------------------------------------------------
{- Do some simple sanity checks:
* all the default field names are unique
* for each PrimOpSpec, all override field names are unique
* for each PrimOpSpec, all overriden field names
have a corresponding default value
* that primop types correspond in certain ways to the
Category: eg if Comparison, the type must be of the form
T -> T -> Bool.
Dies with "error" if there's a problem, else returns ().
-}
myseqAll :: [()] -> a -> a
myseqAll (():ys) x = myseqAll ys x
myseqAll [] x = x
sanityTop :: Info -> ()
sanityTop (Info defs entries)
= let opt_names = map get_attrib_name defs
primops = filter is_primop entries
in
if length opt_names /= length (nub opt_names)
then error ("non-unique default attribute names: " ++ show opt_names ++ "\n")
else myseqAll (map (sanityPrimOp opt_names) primops) ()
sanityPrimOp :: [String] -> Entry -> ()
sanityPrimOp def_names p
= let p_names = map get_attrib_name (opts p)
p_names_ok
= length p_names == length (nub p_names)
&& all (`elem` def_names) p_names
ty_ok = sane_ty (cat p) (ty p)
in
if not p_names_ok
then error ("attribute names are non-unique or have no default in\n" ++
"info for primop " ++ cons p ++ "\n")
else
if not ty_ok
then error ("type of primop " ++ cons p ++ " doesn't make sense w.r.t" ++
" category " ++ show (cat p) ++ "\n")
else ()
sane_ty :: Category -> Ty -> Bool
sane_ty Compare (TyF t1 (TyF t2 td))
| t1 == t2 && td == TyApp (TyCon "Int#") [] = True
sane_ty Monadic (TyF t1 td)
| t1 == td = True
sane_ty Dyadic (TyF t1 (TyF t2 td))
| t1 == td && t2 == td = True
sane_ty GenPrimOp _
= True
sane_ty _ _
= False
get_attrib_name :: Option -> String
get_attrib_name (OptionFalse nm) = nm
get_attrib_name (OptionTrue nm) = nm
get_attrib_name (OptionString nm _) = nm
get_attrib_name (OptionInteger nm _) = nm
get_attrib_name (OptionVector _) = "vector"
get_attrib_name (OptionFixity _) = "fixity"
lookup_attrib :: String -> [Option] -> Maybe Option
lookup_attrib _ [] = Nothing
lookup_attrib nm (a:as)
= if get_attrib_name a == nm then Just a else lookup_attrib nm as
is_vector :: Entry -> Bool
is_vector i = case lookup_attrib "vector" (opts i) of
Nothing -> False
_ -> True
|
tjakway/ghcjvm
|
utils/genprimopcode/Syntax.hs
|
bsd-3-clause
| 6,550 | 0 | 16 | 2,160 | 1,405 | 788 | 617 | 128 | 3 |
import Test.Cabal.Prelude
main = setupAndCabalTest $ do
skipUnless =<< hasCabalForGhc
-- On Travis OSX, Cabal shipped with GHC 7.8 does not work
-- with error "setup: /usr/bin/ar: permission denied"; see
-- also https://github.com/haskell/cabal/issues/3938
-- This is a hack to make the test not run in this case.
skipIf =<< liftM2 (&&) isOSX (ghcVersionIs (< mkVersion [7,10]))
setup' "configure" [] >>= assertOutputContains "ThisIsCustomYeah"
setup' "build" [] >>= assertOutputContains "ThisIsCustomYeah"
|
mydaum/cabal
|
cabal-testsuite/PackageTests/CustomPlain/setup.test.hs
|
bsd-3-clause
| 543 | 0 | 14 | 104 | 96 | 49 | 47 | 6 | 1 |
compareDouble :: Double -> Double -> Ordering
compareDouble x y =
case (isNaN x, isNaN y) of
(True, True) -> EQ
(True, False) -> LT
(False, True) -> GT
(False, False) ->
-- Make -0 less than 0
case (x == 0, y == 0, isNegativeZero x, isNegativeZero y) of
(True, True, True, False) -> LT
(True, True, False, True) -> GT
_ -> x `compare` y
main = do
let l = [-0, 0]
print [ (x, y, compareDouble x y) | x <- l, y <- l ]
|
ezyang/ghc
|
testsuite/tests/deSugar/should_run/T9238.hs
|
bsd-3-clause
| 538 | 0 | 11 | 212 | 228 | 126 | 102 | 14 | 6 |
{-# LANGUAGE CPP #-}
-- | SimpleForm implementation that works along with digestive-functors
--
-- The Combined module both renders to 'Html' and also parses input.
module SimpleForm.Digestive.Combined (
SimpleForm,
SimpleForm',
postSimpleForm,
getSimpleForm,
simpleForm',
-- * Create forms
input,
input_,
toForm,
-- * Subforms
withFields,
withFields',
wrap,
fieldset
) where
import Data.Monoid
import Control.Monad.Trans.Reader
import Control.Monad.Trans.Writer
import Data.Text (Text)
import qualified Data.Text as T
import Text.Blaze.Html (Html)
import Text.Digestive.View
import Text.Digestive.Form
import Text.Digestive.Types (Env)
import SimpleForm.Digestive (toForm, wrap, simpleForm')
import qualified SimpleForm.Digestive (withFields, fieldset)
import SimpleForm.Combined
import SimpleForm.Digestive.Internal
import SimpleForm.Digestive.Validation
import SimpleForm.Render
-- | Convenience type synonym for combined forms
type SimpleForm' m a = SimpleForm a (Form Html m a)
-- | Render a 'SimpleForm' to 'Html'
--
-- This produces the contents of the form, but you must still wrap it in
-- the actual \<form\> element.
getSimpleForm :: (Monad m) =>
Renderer
-> Maybe a -- ^ Default values for the form
-> SimpleForm' m a -- ^ The simple form to render
-> m Html
getSimpleForm render val form = do
view <- getForm T.empty initialForm
return $ snd $ simpleForm' render (view, val) form
where
(initialForm, _) = simpleForm' render (noView, val) form
noView :: View Html
noView = error "SimpleForm.Digestive.Combined: cannot use View in generating Form"
-- | Render a 'SimpleForm' to 'Html' in the presence of input
--
-- This also parses the input to the correct datatype.
--
-- The 'Html' is the contents of the form, but you must still wrap it in
-- the actual \<form\> element.
postSimpleForm :: (Monad m) =>
Renderer
-> m (Env m) -- ^ The digestive-functors input environment
-> SimpleForm' m a -- ^ The simple form to render
-> m (Html, Maybe a)
postSimpleForm render env form = do
#if MIN_VERSION_digestive_functors(0,7,0)
(view, val) <- postForm T.empty initialForm (const env)
#else
env' <- env
(view, val) <- postForm T.empty initialForm env'
#endif
let html = snd $ simpleForm' render (view, val) form
return (html, val)
where
(initialForm, _) = simpleForm' render (noView, Nothing) form
noView :: View Html
noView = error "SimpleForm.Digestive.Combined: cannot use View in generating Form"
-- | Create an input element for a 'SimpleForm'
--
-- > input "username" (Just . username) (wdef,vdef) mempty
input :: (Eq a, Monad m) =>
Text -- ^ Form element name
-> (r -> Maybe a) -- ^ Get value from parsed data
-> (Widget a, Validation a) -- ^ Widget and validation to use
-> InputOptions -- ^ Other options
-> SimpleForm r (Form Html m a)
input n sel (w,v) opt = SimpleForm $ ReaderT $ \env -> do
tell $ input' n sel w opt env
return $ validationToForm n v
-- | Same as 'input', but just use the default options
input_ :: (DefaultWidget a, DefaultValidation a, Eq a, Monad m) =>
Text -- ^ Form element name
-> (r -> Maybe a) -- ^ Get value from parsed data
-> SimpleForm r (Form Html m a)
input_ n sel = input n sel (wdef,vdef) mempty
-- | Project out some part of the parsed data (does not add name to subview)
withFields' ::
Maybe Text -- ^ Optional subview name
-> (r' -> r) -- ^ Projection function
-> SimpleForm r a
-> SimpleForm r' a
withFields' = SimpleForm.Digestive.withFields
-- | Project out some part of the parsed data and name the subview
withFields :: (Monad m) =>
Text -- ^ Subview name
-> (r' -> r) -- ^ Projection function
-> SimpleForm r (Form Html m a)
-> SimpleForm r' (Form Html m a)
withFields n f = fmap (n .:) . withFields' (Just n) f
-- | Like 'withFields'', but also wrap in fieldset tag
fieldset' :: Maybe Text -> (r' -> r) -> SimpleForm r a -> SimpleForm r' a
fieldset' = SimpleForm.Digestive.fieldset
-- | Like 'withFields', but also wrap in fieldset tag
fieldset :: (Monad m) => Text -> (r' -> r) -> SimpleForm r (Form Html m a) -> SimpleForm r' (Form Html m a)
fieldset n f = fmap (n .:) . fieldset' (Just n) f
|
singpolyma/simple-form-haskell
|
SimpleForm/Digestive/Combined.hs
|
isc
| 4,242 | 124 | 15 | 867 | 1,105 | 628 | 477 | 84 | 1 |
module HW1.TowersOfHanoiSpec (main, spec) where
import HW1.TowersOfHanoi
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec =
describe "hanoi" $
it "returns a list of moves required to stack pegs in order" $
hanoi 2 'a' 'b' 'c' `shouldBe` [('a','c'), ('a','b'), ('c','b')]
|
wstrinz/school-of-haskell
|
cis194/homework-1/test/HW1/TowersOfHanoiSpec.hs
|
mit
| 307 | 0 | 8 | 64 | 108 | 62 | 46 | 10 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Y2018.M05.D18.Solution where
import Data.Aeson
import Data.ByteString.Lazy.Char8 (ByteString)
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Time.Clock
import Database.PostgreSQL.Simple
import Network.HTTP.Conduit
-- below imports available via 1HaskellADay git repository
import Data.LookupTable
import Store.SQL.Connection
import Store.SQL.Util.Logging
-- Before we insert new articles, let's step back in time for a moment. Recall
import Y2018.M04.D06.Solution (cats2lk)
import Y2018.M04.D09.Solution
{--
where we uploaded tags, we uploaded a sample set of 10 tags. There are a lot
more tags than 10 for the World Policy Journal. Today we're going to find out
how many.
The REST endpoint for the tags is as follows:
--}
import Y2018.M04.D11.Solution (PageNumber)
import Y2018.M04.D13.Solution (Tries)
tagEndpoint :: PageNumber -> FilePath
tagEndpoint pn = "https://worldpolicy.org/wp-json/wp/v2/tags?per_page=100&page="
++ show pn
-- The JSON format we already know and parse (see above exercise) and the
-- tags are exhausted when the Value returned is the empty list.
-- How many tags are there for this REST endpoint?
downloadTags :: IO [Tag]
downloadTags = tr' 0 [] 1
-- You may want to use some pagination function to help define downloadTags
-- hint: see definitions in Y2018.M04.D13 for downloading packets and use
-- a similar approach
tr' :: Tries -> [Tag] -> PageNumber -> IO [Tag]
tr' tries accum pn =
if tries > 3
then error ("Tried three times at offset " ++ show pn ++ "; quitting")
else tagReader 60 pn >>=
either (accumTags (succ pn) accum) (logErr pn (succ tries) accum)
tagReader :: Int -> PageNumber -> IO (Either [Tag] String)
tagReader secs pn =
newManager tlsManagerSettings >>= \mgr ->
parseRequest (tagEndpoint pn) >>= \req ->
let req' = req { responseTimeout = responseTimeoutMicro (secs * 1000000) } in
httpLbs req' mgr >>= return . eitherify decode . responseBody
eitherify :: (ByteString -> Maybe [Tag]) -> ByteString
-> Either [Tag] String
eitherify f str = case f str of
Just tags -> Left tags
Nothing -> Right (BL.unpack str)
accumTags :: PageNumber -> [Tag] -> [Tag] -> IO [Tag]
accumTags n accum [] = return accum
accumTags n accum tags@(_:_) = tr' 0 (accum ++ tags) n
logErr :: PageNumber -> Tries -> [Tag] -> String -> IO [Tag]
logErr pn tr accum msg =
putStrLn ("Failed on on tag-loader page " ++ show pn ++ ", try: " ++ show tr
++ ", with string " ++ msg) >>
tr' tr accum pn
{--
>>> tags <- downloadTags
... (after 30 seconds) ...
>>> length tags
5916
>>> mapM_ (print . (idx &&& mouse . val)) (take 5 tags)
(8813,"#MeToo")
(8511,"#OneArctic Symposium")
(3904,"12x12")
(4095,"18th National Congress")
(4133,"18th Party Congress")
--}
{-- BONUS -----------------------------------------------------------------
Create an application that downloads all the tags from the REST endpoint and
then uploads those tags to a PostgreSQL data table as described in the module
Y2018.M04.D09.
--}
main' :: [String] -> IO ()
main' [] =
putStrLn "Initialzing tag-loader for WPJ" >>
downloadTags >>= \tags ->
withConnection WPJ (\conn -> initLogger conn >>= uploadTags conn tags) >>
putStrLn "Populated database with WPJ tags."
uploadTags :: Connection -> [Tag] -> LookupTable -> IO ()
uploadTags conn tags sevlk =
roff' conn ("Downloaded " ++ show (length tags)
++ " tags from WPJ REST enpoint") >>
insertTags conn (cats2lk tags)
where roff' = mkInfo "Tag uploader" "Y2018.M05.D18.Solution" sevlk
go :: IO ()
go = getCurrentTime >>= \start ->
main' [] >>
getCurrentTime >>=
putStrLn . ("Executed in " ++) . (++ " seconds") . show
. flip diffUTCTime start
{-- BONUS-BONUS ------------------------------------------------------------
Create an application that does the same thing, but for categories this time.
See Y2018.M04.D06 for information on categories (very (VERY)) much like tags.
--}
|
geophf/1HaskellADay
|
exercises/HAD/Y2018/M05/D18/Solution.hs
|
mit
| 4,053 | 0 | 17 | 780 | 884 | 472 | 412 | 63 | 2 |
module Level.Grid.GrowingTree where
import Coord.Types
import Level.Grid.Types
import System.Random
import System.Random.PCG
-- Using FRecBT as the frontier results in a recursive backtracker
newtype FRecBT = FRecBT [Coord]
-- Using FPrim as the frontier results in Prim's algorithm
newtype FPrim = FPrim [Coord]
data FOldest = FOldest [Coord] [Coord]
-- Type for supported algorithms
data MazeAlgo = MazeRecBT | MazePrim | MazeOldest
class Frontier a where
fadd :: Coord -> a -> a
fremove :: Coord -> a -> a
fselect :: a -> IO (Maybe Coord)
instance Frontier FRecBT where
fadd c (FRecBT cs) = FRecBT $ c : cs
fremove c (FRecBT cs) = FRecBT $ filter (/=c) cs
fselect (FRecBT []) = pure Nothing
fselect (FRecBT cs) = pure $ Just $ head cs
instance Frontier FPrim where
fadd c (FPrim cs) = FPrim $ c : cs
fremove c (FPrim cs) = FPrim $ filter (/=c) cs
fselect (FPrim []) = pure Nothing
fselect (FPrim cs) = do
mc <- randomElt cs
pure mc
instance Frontier FOldest where
fadd c (FOldest [] _) = FOldest [c] []
fadd c (FOldest xs ys) = FOldest xs (c:ys)
fremove _ (FOldest [] _) = FOldest [] []
fremove _ (FOldest [_] ys) = FOldest (reverse ys) []
fremove _ (FOldest (_:xs) ys) = FOldest xs ys
fselect (FOldest [] _) = pure Nothing
fselect (FOldest (x:_) _) = pure $ Just x
randomElt :: [a] -> IO (Maybe a)
randomElt [] = pure Nothing
randomElt xs = do
i <- getPCGRandom $ randomR (0, length xs - 1)
pure $ Just $ xs !! i
randomUnvisited :: Coord -> Grid -> IO (Maybe Coord)
randomUnvisited c g = randomElt $ unvisitedNodes c g
unvisitedNodes :: Coord -> Grid -> [Coord]
unvisitedNodes = adjacentNodesOf (== GridEmpty)
-- unvisitedNodesR :: Coord -> Grid -> IO [Coord]
-- unvisitedNodesR x g = shuffleM $ unvisitedNodes x g
emptyNodeR :: Grid -> IO (Maybe Coord)
emptyNodeR g = randomElt $ filter predicate $ nodeCoords g
where
predicate x = node x g == GridEmpty
mazify' :: (Frontier a) => Grid -> a -> IO Grid
mazify' grid front = do
maybeCell <- fselect front
case maybeCell of
Nothing -> pure grid
Just x -> do
unvisited <- randomUnvisited x grid
case unvisited of
Nothing -> mazify' grid $ fremove x front
Just n -> mazify' (carve grid x n) $ fadd n front
mazify :: MazeAlgo -> Grid -> IO Grid
mazify MazeRecBT grid = mazeGrid' (FRecBT []) grid
mazify MazePrim grid = mazeGrid' (FPrim []) grid
mazify MazeOldest grid = mazeGrid' (FOldest [] []) grid
mazeGrid :: MazeAlgo -> Coord -> Coord -> IO Grid
mazeGrid MazeRecBT = makeMazeGrid $ FRecBT []
mazeGrid MazePrim = makeMazeGrid $ FPrim []
mazeGrid MazeOldest = makeMazeGrid $ FOldest [] []
mazeGrid' :: (Frontier a) => a -> Grid -> IO Grid
mazeGrid' front grid = do
xMaybe <- emptyNodeR grid
case xMaybe of
Nothing -> pure grid
Just x -> do
newGrid <- mazify' (visit grid x) (fadd x front)
mazeGrid' front newGrid
makeMazeGrid :: (Frontier a) => a -> Coord -> Coord -> IO Grid
makeMazeGrid front gmin gmax = mazeGrid' front $ emptyUnlinkedGrid gmin gmax
|
wmarvel/haskellrogue
|
src/Level/Grid/GrowingTree.hs
|
mit
| 3,049 | 0 | 18 | 676 | 1,239 | 615 | 624 | 73 | 3 |
-- -------------------------------------------------------------------------------------
-- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
-- For email, run on linux (perl v5.8.5):
-- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
-- -------------------------------------------------------------------------------------
import Data.Array
import Data.List
nmax = 100
mmax = nmax
kmax = 100
data Direction = DOWN | RIGHT deriving (Show, Eq)
type PathVal = (Integer, Int) -- (ways to get here, in these many turns)
type CacheVal = ([PathVal], [PathVal]) -- various paths with these many number of turns, to end up at current cell, facing (DOWN, RIGHT)
mergeLists :: [PathVal] -> [PathVal] -> [PathVal]
mergeLists pvs [] = pvs
mergeLists [] pvs = pvs
mergeLists ((lw, lt) : lhs) ((rw, rt) : rhs) =
if lt == rt
then (lw + rw, lt) : mergeLists lhs rhs
else if lt < rt
then (lw, lt) : mergeLists lhs ((rw, rt) : rhs)
else (rw, rt) : mergeLists ((lw, lt) : lhs) rhs
-- at each point, I look at top cell, and left cell
-- either i can keep moving in the same direction in top (down) or switch top (right) to top(down) by adding 1 more turn
-- either i can keep moving in the same direction in left (right) or switch left (down) to left (right) by adding 1 more turn
waysToGetHere :: CacheVal -> CacheVal -> CacheVal
waysToGetHere top@(topkdowns, topkrights) left@(leftkdowns, leftkrights) =
let mykdowns = mergeLists topkdowns (map (\(n, t) -> (n, t+1)) topkrights)
mykrights = mergeLists leftkrights (map (\(n, t) -> (n, t+1)) leftkdowns)
in (mykdowns, mykrights)
computeCache :: Array (Int, Int) CacheVal
computeCache = cache
where
-- how to get from (1, 1) to (r, c)
sherlockMaze :: Int -> Int -> CacheVal
sherlockMaze r c
| r == 1 && c == 1 = ([(1,0)], [(1,0)])
| r == 1 = ([ ], [(1, 0)])
| c == 1 = ([(1, 0)], [ ])
| otherwise = waysToGetHere (cache ! (r-1, c)) (cache ! (r, c-1))
cache = listArray ((0, 0), (nmax+1, mmax+1)) [ sherlockMaze ri ci | ri <- [0..(nmax+1)], ci <- [0..(mmax+1)] ]
main :: IO ()
main = do
ip <- getContents
let nmks = map (map read . words) . tail . lines $ ip
let cachedVals = computeCache
mapM_ (putStrLn . show) $
map (\[n, m, k] -> let (ds, rs) = (cachedVals ! (n, m))
in if n == 1 && m == 1
then 1
else ((`mod` (10^9 + 7)) . sum . map fst . filter ((<=k) . snd) $ ds ++ rs)) nmks
|
cbrghostrider/Hacking
|
HackerRank/FunctionalProgramming/MemoizationAndDP/sherlockMaze.hs
|
mit
| 2,679 | 0 | 23 | 730 | 898 | 506 | 392 | 41 | 3 |
module Apl1 where
import Control.Applicative
import Data.Monoid
import Test.QuickCheck
import Test.QuickCheck.Checkers
import Test.QuickCheck.Classes
-- unfortunate orphan instances. Try to avoid these
-- in code you're going to keep or release.
-- this isn't going to work properly
instance Monoid a => Monoid (ZipList a) where
mempty = pure mempty
mappend = liftA2 mappend
instance Arbitrary a => Arbitrary (ZipList a) where
arbitrary = ZipList <$> arbitrary
instance Arbitrary a => Arbitrary (Sum a) where
arbitrary = Sum <$> arbitrary
instance Eq a => EqProp (ZipList a) where
(=-=) = eq
|
NickAger/LearningHaskell
|
HaskellProgrammingFromFirstPrinciples/Chapter17/Apl1/src/Apl1.hs
|
mit
| 608 | 0 | 7 | 106 | 159 | 86 | 73 | 15 | 0 |
module Backends.D16Hoopl.Backend where
|
d16-processor/Haskell-C-
|
src/Backends/D16Hoopl/Backend.hs
|
mit
| 39 | 0 | 3 | 3 | 7 | 5 | 2 | 1 | 0 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGAnimatedNumber
(js_setBaseVal, setBaseVal, js_getBaseVal, getBaseVal,
js_getAnimVal, getAnimVal, SVGAnimatedNumber,
castToSVGAnimatedNumber, gTypeSVGAnimatedNumber)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"baseVal\"] = $2;"
js_setBaseVal :: JSRef SVGAnimatedNumber -> Float -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedNumber.baseVal Mozilla SVGAnimatedNumber.baseVal documentation>
setBaseVal :: (MonadIO m) => SVGAnimatedNumber -> Float -> m ()
setBaseVal self val
= liftIO (js_setBaseVal (unSVGAnimatedNumber self) val)
foreign import javascript unsafe "$1[\"baseVal\"]" js_getBaseVal ::
JSRef SVGAnimatedNumber -> IO Float
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedNumber.baseVal Mozilla SVGAnimatedNumber.baseVal documentation>
getBaseVal :: (MonadIO m) => SVGAnimatedNumber -> m Float
getBaseVal self = liftIO (js_getBaseVal (unSVGAnimatedNumber self))
foreign import javascript unsafe "$1[\"animVal\"]" js_getAnimVal ::
JSRef SVGAnimatedNumber -> IO Float
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedNumber.animVal Mozilla SVGAnimatedNumber.animVal documentation>
getAnimVal :: (MonadIO m) => SVGAnimatedNumber -> m Float
getAnimVal self = liftIO (js_getAnimVal (unSVGAnimatedNumber self))
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/JSFFI/Generated/SVGAnimatedNumber.hs
|
mit
| 2,195 | 20 | 9 | 264 | 524 | 314 | 210 | 32 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Y2017.M02.D23.Solution where
import Control.Arrow (second, app)
import Control.Comonad
import Data.List (intercalate)
import Data.Maybe (catMaybes)
import Network.HTTP
-- below imports from 1HaskellADay git repository 'may' help reading FASTA files
import Control.List -- for Comonadic lists
import Control.Scan.CSV (rend)
import Rosalind.Types
import Rosalind.Scan.FASTA
{--
Finding a Protein Motif solved by 2726 as of February 22nd, 2017
Rosalind problem: http://rosalind.info/problems/mprt/
Motif Implies Functionclick to collapse
As mentioned in “Translating RNA into Protein”, proteins perform every practical
function in the cell. A structural and functional unit of the protein is a
domain: in terms of the protein's primary structure, the domain is an interval
of amino acids that can evolve and function independently.
Each domain usually corresponds to a single function of the protein (e.g.,
binding the protein to DNA, creating or breaking specific chemical bonds, etc.).
Some proteins, such as myoglobin and the Cytochrome complex, have only one
domain, but many proteins are multifunctional and therefore possess several
domains. It is even possible to artificially fuse different domains into a
protein molecule with definite properties, creating a chimeric protein.
Just like species, proteins can evolve, forming homologous groups called protein
families. Proteins from one family usually have the same set of domains,
performing similar functions; see Figure 1.
Figure 1. The human cyclophilin family, as represented by the structures of the
isomerase domains of some of its members.
A component of a domain essential for its function is called a motif, a term
that in general has the same meaning as it does in nucleic acids, although many
other terms are also used (blocks, signatures, fingerprints, etc.) Usually
protein motifs are evolutionarily conservative, meaning that they appear without
much change in different species.
Proteins are identified in different labs around the world and gathered into
freely accessible databases. A central repository for protein data is UniProt,
which provides detailed protein annotation, including function description,
domain structure, and post-translational modifications. UniProt also supports
protein similarity search, taxonomy analysis, and literature citations.
Problem
To allow for the presence of its varying forms, a protein motif is represented
by a shorthand as follows: [XY] means "either X or Y" and {X} means "any amino
acid except X." For example, the N-glycosylation motif is written as N{P}[ST]{P}.
You can see the complete description and features of a particular protein by its
access ID "uniprot_id" in the UniProt database, by inserting the ID number into
--}
baseURL :: String
baseURL = "http://www.uniprot.org/uniprot/"
{--
Alternatively, you can obtain a protein sequence in FASTA format by following
http://www.uniprot.org/uniprot/uniprot_id.fasta
For example, the data for protein B5ZC00 can be found at
http://www.uniprot.org/uniprot/B5ZC00.
Given: At most 15 UniProt Protein Database access IDs.
Return: For each protein possessing the N-glycosylation motif, output its given
access ID followed by a list of locations in the protein string where the motif
can be found.
--}
type AccessID = String
type Location = Int
sample :: AccessID
sample = unlines ["A2Z669","B5ZC00","P07204_TRBM_HUMAN","P20840_SAG1_YEAST"]
result :: [(AccessID, [Location])]
result = map (second (map read . words))
[("B5ZC00","85 118 142 306 395"),
("P07204_TRBM_HUMAN","47 115 116 382 409"),
("P20840_SAG1_YEAST","79 109 135 248 306 348 364 402 485 501 614")]
-- or:
output :: String
output = unlines ["B5ZC00","85 118 142 306 395","P07204_TRBM_HUMAN",
"47 115 116 382 409","P20840_SAG1_YEAST",
"79 109 135 248 306 348 364 402 485 501 614"]
{--
To read in a FASTA file from an URL we do:
>>> fmap (readStrands . lines)
(simpleHTTP (getRequest (baseURL ++ "A2Z669.fasta")) >>= getResponseBody)
Now we just need to look for the protein-motif by writing a protein-motif-compiler.
But maybe we'll do that another day, as we have the rules of engagement already.
--}
type Proneme = Char -> Bool
-- the nGlycos proneme motif is:
nglycos :: [Proneme]
nglycos = [(== 'N'),(/= 'P'),(||) . (== 'S') <*> (== 'T'),(/= 'P')]
isMotif :: [Proneme] -> String -> Bool
isMotif motif = and . zipWith (curry app) motif
{--
>>> zipWith (curry app) nglycos "MKNKFKTQEELVNHLKT"
[False,True,False,True]
--}
-- as expected output
readFASTAfromURL :: AccessID -> IO IdxStrand
readFASTAfromURL id = fmap (IS id . strand . head . readStrands . lines)
(simpleHTTP (getRequest (constructURL id)) >>= getResponseBody)
constructURL :: AccessID -> FilePath
constructURL id = baseURL ++ (head (rend '_' id)) ++ ".fasta"
-- okay, from a set of pronemes and a protein string, let's parse out locations
scanner :: [Proneme] -> DNAStrand -> [Location]
scanner motif strand = enumerateTrues 1 (strand =>> isMotif motif)
enumerateTrues :: Int -> [Bool] -> [Location]
enumerateTrues _ [] = []
enumerateTrues x (pred:rest) = (if pred then (x:) else id)
(enumerateTrues (succ x) rest)
motifNglycos :: AccessID -> IO (Maybe (AccessID, [Location]))
motifNglycos id = fmap (orNada id . scanner nglycos . strand) $ readFASTAfromURL id
orNada :: AccessID -> [Location] -> Maybe (AccessID, [Location])
orNada _ [] = Nothing
orNada id loc@(_:_) = Just (id, loc)
{-- verify that the sample access IDs produce the set of results
>>> motifNglycos "B5ZC00"
Just ("B5ZC00",[85,118,142,306,395])
SWEET!
--}
-- Now, sew the definitions together to produce the expected output
motifs :: String -> IO String
motifs ids = mapM motifNglycos (lines ids) >>= \ans ->
let ens = concatMap enstringify (catMaybes ans) in
mapM_ putStrLn ens >> return (unlines ens)
enstringify :: (AccessID, [Location]) -> [String]
enstringify (id, locs) = [id, intercalate " " (map show locs)]
{--
>>> fmap (== output) $ motifs sample
B5ZC00
85 118 142 306 395
P07204_TRBM_HUMAN
47 115 116 382 409
P20840_SAG1_YEAST
79 109 135 248 306 348 364 402 485 501 614
True
Note
Some entries in UniProt have one primary (citable) accession number and some
secondary numbers, appearing due to merging or demerging entries. In this
problem, you may be given any type of ID. If you type the secondary ID into the
UniProt query, then you will be automatically redirected to the page containing
the primary ID. You can find more information about UniProt IDs at this URL:
http://www.uniprot.org/help/accession_numbers
--}
{-- BONUS -----------------------------------------------------------------
For the file rosalind_mprt-3.txt at this directory or at the URL:
https://raw.githubusercontent.com/geophf/1HaskellADay/master/exercises/HAD/Y2017/M02/D23/rosalind_mprt-3.txt
read in that file and find the Nglycos motifs of the proteins there enumerated
>>> readFile "rosalind_mprt-3.txt" >>= motifs
P01217_GLHA_BOVIN
80 106
Q05865
389
P42098_ZP3_PIG
124 146 179 271
Q16775
41
P06765_PLF4_RAT
82
P08514_ITAB_HUMAN
46 280 601 711 962
P22457_FA7_BOVIN
185 243
P00744_PRTZ_BOVIN
59 191 289
P10761_ZP3_MOUSE
146 273 304 327 330
P12763_A2HS_BOVIN
99 156 176
P47002
35 552 608
Q8LCP6
259 464 484
A4J5V5
24 38 230
P07306_LECH_HUMAN
79 147
--}
|
geophf/1HaskellADay
|
exercises/HAD/Y2017/M02/D23/Solution.hs
|
mit
| 7,458 | 0 | 13 | 1,279 | 844 | 477 | 367 | 53 | 2 |
module Root.Test.Test2SpecWE where
import Test.Hspec
import Test.QuickCheck
import Control.Exception (evaluate)
main :: IO ()
main = hspec spec
spec::Spec
spec = do
describe "Prelude.head" $ do
it "returns the first element of a list" $ do
head [23 ..] `shouldBe` (23 :: Int)
|
codeboardio/kali
|
test/src_examples/haskell/several_files/Root/Test/Test2SpecWE.hs
|
mit
| 284 | 0 | 15 | 51 | 97 | 53 | 44 | 11 | 1 |
{-# htermination fromInt :: Num a => Int -> a #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_fromInt_1.hs
|
mit
| 50 | 0 | 2 | 11 | 3 | 2 | 1 | 1 | 0 |
------------------------------------------------------------------------------------
-- |
-- Module : Conversion
-- Copyright : (C) 2015 Sajith Sasidharan
-- License : MIT (see LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : unknown
--
------------------------------------------------------------------------------------
module Conversion where
-----------------------------------------------------------------------------
import qualified Data.Map as M
import qualified Data.Text.Lazy as T
import Data.Word (Word8)
-- In theory we need only one of 'Formatting' and 'Text.Printf', but
-- in practice I don't know how to correctly format XPM palette using
-- 'Formatting'. But 'Formatting' performs so much better, so using
-- it where possible is a good idea.
import Formatting as F
import qualified Control.DeepSeq as D
import qualified Control.Parallel.Strategies as P
import qualified Data.Text.Lazy.IO as T (hPutStr)
import System.FilePath (takeBaseName)
import System.IO (IOMode (ReadMode, WriteMode),
withBinaryFile, withFile)
import Bmp
import Xpm
-----------------------------------------------------------------------------
-- Convert BMP file to XPM file.
bmpToXpm :: BitmapName -> BmpFile -> XpmData
bmpToXpm name (BmpFile _ info bitmap) = xpmData
where
xpmLeader = xpmFormHeader name info
colorStr = T.pack "/* colors */\n"
xpmColors = T.append colorStr (T.concat xpmColorLines)
xpmHeader = T.append xpmLeader xpmColors
pixelStr = T.pack "/* pixels */\n"
xpmBitmap = T.append pixelStr (translateBitmap bitmap)
xpmBody = T.append xpmHeader xpmBitmap
xpmData = T.append xpmBody (T.pack "\n};")
-----------------------------------------------------------------------------
-- Convert a BMP pixel to a color in our palette.
toPaletteColor :: BmpPixel -> XpmPaletteColor
toPaletteColor (BmpPixel b g r) = xpmPalette !! fromEnum idx
where
-- BGR -> RGB, sort of.
idx = paletteIndex r * 36 + paletteIndex g * 6 + paletteIndex b
{-# INLINE toPaletteColor #-}
-- Find palette position from the given color intensity.
paletteIndex :: Word8 -> Word8
paletteIndex c =
if c `mod` paletteDelta == 0
then pos
else paletteApprox c pos
where
pos = c `div` paletteDelta
{-# INLINE paletteIndex #-}
-- Find the closest palette color.
paletteApprox :: Word8 -> Word8 -> Word8
paletteApprox c pos =
if d1 > d2 then pos+1 else pos
where d1 = abs $ fromEnum c - fromEnum (xpmPalette !! fromEnum pos)
d2 = abs $ fromEnum c - fromEnum (xpmPalette !! fromEnum (pos+1))
{-# INLINE paletteApprox #-}
-----------------------------------------------------------------------------
-- 'splitBy' (originally 'split') and 'chunk' are from Simon Marlow's
-- "Parallel and Concurrent Programming in Haskell", 1st ed, pp 40.
splitBy :: Int -> [a] -> [[a]]
splitBy n xs = chunk (length xs `quot` n) xs
chunk :: Int -> [a] -> [[a]]
chunk _ [] = []
chunk n xs = as : chunk n bs
where
(as, bs) = splitAt n xs
-- Good news: threadscope shows parallelism, and productivity now is
-- "82.7% of total user, 280.4% of total elapsed"
translateBitmap :: BmpBitmap -> XpmBitmap
translateBitmap rows = T.intercalate (T.pack ",\n") res
where
[a, b, c, d] = splitBy 4 rows
res = P.runEval $ do
a' <- P.rpar $ D.force $ map translatePixelRow a
b' <- P.rpar $ D.force $ map translatePixelRow b
c' <- P.rpar $ D.force $ map translatePixelRow c
d' <- P.rseq $ D.force $ map translatePixelRow d
return (a' ++ b' ++ c' ++ d')
-----------------------------------------------------------------------------
-- The commented out stuff below is of historic interest: the first
-- one is the original sequential version of translateBitmap.
--
-- The second one answered the question "what if I use rpar/rseq this
-- way?" And the answer was: that would actually be sequential, you
-- silly person!
{--
-- Translate from BMP bitmap to XPM bitmap, the sequential version.
translateBitmap :: BmpBitmap -> XpmBitmap
translateBitmap rows = T.intercalate (T.pack ",\n")
$ map translatePixelRow rows
--}
{--
-- First attempt with rpar/rseq.
translateBitmap :: BmpBitmap -> XpmBitmap
translateBitmap rows = T.intercalate (T.pack ",\n") $ map parPixelRow rows
-- This is essentially sequential!
parPixelRow :: BmpPixelRow -> XpmPixelRow
parPixelRow row = P.runEval $ do
new <- P.rpar $ D.force $ translatePixelRow row
_ <- P.rseq new
return new
--}
-----------------------------------------------------------------------------
-- Translate a row of pixels.
translatePixelRow :: BmpPixelRow -> XpmPixelRow
translatePixelRow row = quote $ T.concat $ map translatePixel row
-----------------------------------------------------------------------------
-- XXX: This function is the hot-spot. How can I improve it?
translatePixel :: BmpPixel -> XpmPixel
translatePixel p = F.format (left 2 ' ' %. text)
$ xpmColorMap M.! toPaletteColor p
-----------------------------------------------------------------------------
-- Put double quotes around text.
quote :: T.Text -> T.Text
quote txt = T.snoc (T.cons dq txt) dq where dq = '"'
-----------------------------------------------------------------------------
runConversion :: FilePath -> FilePath -> IO ()
runConversion infile outfile = do
let name = takeBaseName infile
-- TODO: Leaves an empty output file when conversion fails. Fix.
withBinaryFile infile ReadMode
(\inh -> do
bmpdata <- readBmpFile inh
withFile outfile WriteMode
(\outh -> T.hPutStr outh (bmpToXpm name bmpdata)))
-----------------------------------------------------------------------------
|
sajith/bmp2xpm
|
src/Conversion.hs
|
mit
| 6,131 | 0 | 17 | 1,405 | 1,060 | 580 | 480 | 70 | 2 |
module Atom.Marker where
import GHCJS.Types
data Marker_
type Marker = JSRef Marker_
|
CRogers/stack-ide-atom
|
haskell/src/Atom/Marker.hs
|
mit
| 88 | 0 | 5 | 15 | 23 | 14 | 9 | -1 | -1 |
module Main (main) where
import Data.Monoid (mempty)
import Debug.Trace
import Test.Framework.Options (TestOptions, TestOptions'(..))
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.Framework.Runners.Options (RunnerOptions, RunnerOptions'(..))
import qualified Test.Framework as T
import qualified Test.QuickCheck as Q
import qualified Test.QuickCheck.Property as QP
import qualified Text.Parsec
import qualified NginxLint.Parse
main :: IO ()
main = do
let empty_test_opts = mempty :: TestOptions
let my_test_opts = empty_test_opts {
topt_maximum_generated_tests = Just 2000
, topt_maximum_unsuitable_generated_tests = Just 10000
, topt_maximum_test_size = Just 500
}
let empty_runner_opts = mempty :: RunnerOptions
let my_runner_opts = empty_runner_opts {
ropt_test_options = Just my_test_opts
, ropt_color_mode = Just T.ColorAuto
}
T.defaultMainWithOpts tests my_runner_opts
where
tests = [
T.testGroup "Parser" $ [
testProperty "comment-01" $ Q.forAll genComment checkFile
, testProperty "arg-01" $ Q.forAll genArg checkArg
, testProperty "decl-01" $ Q.forAll genRewrite checkDecl
, testProperty "block-01" $ Q.forAll genBlock checkDecl
]
]
genArg :: Q.Gen String
genArg = Q.oneof [genPlainString]
genBlock :: Q.Gen String
genBlock = do
name <- Q.oneof [return "events", return "http", return "server", genIdentifier]
args <- Q.resize 3 $ Q.listOf genArg
decls <- Q.resize 5 $ Q.listOf genDecl
return $ name ++ " " ++ unwords args ++ " {" ++ concat decls ++ "}"
genComment :: Q.Gen String
genComment = do
s <- Q.listOf $ Q.arbitrary `Q.suchThat` (/= '\n')
return $ "#" ++ s
genDecl :: Q.Gen String
genDecl = Q.frequency [
(1, genBlock)
, (2, genDeclIf)
, (10, genDeclSimple)
]
genDeclIf :: Q.Gen String
genDeclIf = do
args <- Q.resize 3 $ Q.listOf1 genArg
decls <- Q.resize 5 $ Q.listOf genDeclSimple
return $ "if (" ++ unwords args ++ ") {" ++ concat decls ++ "}"
genDeclSimple :: Q.Gen String
genDeclSimple = do
name <- genIdentifier
args <- Q.resize 3 $ Q.listOf genArg
return $ name ++ " " ++ unwords args ++ ";"
genIdentifier :: Q.Gen String
genIdentifier = Q.resize 20 $ Q.listOf1 $ Q.elements identChars
genPlainString :: Q.Gen String
genPlainString = Q.listOf1 $ Q.elements plainStringChars
genRegex :: Q.Gen String
genRegex = do
prefix <- genFreqMaybe 2 begin
suffix <- genFreqMaybe 2 end
middle <- fmap concat $ Q.resize 10 $ Q.listOf genoptions
return $ prefix ++ middle ++ suffix
where
genoptions = Q.frequency [
(1, group)
, (3, klass)
, (5, raw0)
]
klass = do
m <- fmap concat $ Q.resize 5 $ Q.listOf1 klassoptions
flag <- genFreqMaybe 3 begin
return $ "[" ++ flag ++ m ++ "]"
klassoptions = Q.frequency [
(3, raw1)
, (1, return "a-z")
, (1, return "0-9")
]
group = do
flag <- genFreqMaybe 1 (return "?:")
m <- fmap concat $ Q.resize 5 $ Q.listOf1 groupgenoptions
q <- genquant
return $ "(" ++ flag ++ m ++ ")" ++ q
groupgenoptions = Q.frequency [
(1, return "|")
, (1, genEmpty)
, (1, begin)
, (1, end)
, (2, group)
, (3, klass)
, (10, raw1)
]
genquant = Q.frequency [
(10, genEmpty)
, (1, return "?")
, (1, return "*")
]
begin = return "^"
end = return "$"
raw0 = Q.resize 10 $ Q.listOf genchar
raw1 = Q.resize 10 $ Q.listOf1 genchar
genchar = Q.elements $ letterChars ++ digitChars ++ "~!@%&."
genRewrite :: Q.Gen String
genRewrite = do
rule <- genRegex
target <- gtarget
flag <- gflag
return $ concat ["rewrite ", rule, " ", target, flag, ";"]
where
gtarget = Q.elements ["/", "/$1_2x.$2", "http://example$request_uri?"]
gflag = Q.elements ["", " break", " last", " permanent"]
-- Begin utils
genEmpty :: Q.Gen String
genEmpty = return ""
genFreqMaybe :: Int -> Q.Gen String -> Q.Gen String
genFreqMaybe n g = Q.frequency [(n, g), (10, genEmpty)]
assertParsed :: Either Text.Parsec.ParseError a -> QP.Result
assertParsed a = case a of
(Right _) -> QP.succeeded
(Left e) -> QP.failed { QP.expect = True, QP.reason = show e }
checkFile :: String -> QP.Property
checkFile = checkParsed NginxLint.Parse.parseFile
checkArg :: String -> QP.Property
checkArg = checkParsed NginxLint.Parse.argument
checkDecl :: String -> QP.Property
checkDecl = checkParsed NginxLint.Parse.decl
checkParsed :: Text.Parsec.Parsec [a] () a1 -> [a] -> QP.Property
checkParsed p s = Q.collect (length s) $ Q.within 100000 $ assertParsed $ Text.Parsec.parse p "" s
digitChars :: String
digitChars = ['0'..'9']
letterChars :: String
letterChars = ['A'..'Z'] ++ ['a'..'z']
identChars :: String
identChars = letterChars ++ digitChars ++ "_"
plainStringChars :: String
plainStringChars = identChars ++ "~!?@%^&*"
-- End utils
|
temoto/nginx-lint
|
test/Main.hs
|
mit
| 5,279 | 0 | 13 | 1,444 | 1,755 | 921 | 834 | 132 | 2 |
-- | Main entry point to the application.
module Main where
type Peg = String
type Move = (Peg, Peg)
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
hanoi 0 _ _ _ = []
hanoi 1 sourcePeg destPeg _ = [(sourcePeg, destPeg)]
hanoi n sourcePeg destPeg tempPeg = hanoi (n - 1) sourcePeg tempPeg destPeg ++ [(sourcePeg, destPeg)] ++ hanoi (n - 1) tempPeg destPeg sourcePeg
hanoi' :: Integer -> Peg -> Peg -> Peg -> Peg -> [Move]
hanoi' 0 _ _ _ _ = []
hanoi' 1 sourcePeg destPeg _ _ = [(sourcePeg, destPeg)]
hanoi' n p1 p2 p3 rest = hanoi' k p1 p3 p2 rest ++
hanoi' (n - k) p1 p2 rest p3 ++
hanoi' k p3 p2 p1 rest
where k = n `div` 2
-- hanoi for n disks and r pegs [p1, p2, ..., pr]
hanoiR :: Integer -> [a] -> [(a, a)]
-- zero disks: no moves needed.
hanoiR 0 _ = []
-- one disk: one move and two pegs needed.
hanoiR 1 (p1 : p2 : rest) = [(p1, p2)] -- only needed for smart-alecks?
-- n disks and r > 3 pegs: use Frame-Stewart algorithm
hanoiR n (p1 : p2 : p3 : rest) =
hanoiR k (p1 : p3 : p2 : rest) ++
hanoiR (n - k) (p1 : p2 : rest) ++
hanoiR k (p3 : p2 : p1 : rest)
where k
| (null rest) = n - 1
| otherwise = n `div` 2
main = do
numOfDiscs <- readLn :: IO Integer
--print $ length $ hanoi numOfDiscs "1" "2" "3"
--print $ length $ hanoi' numOfDiscs "1" "2" "3" "4"
print $ hanoi' numOfDiscs "a" "b" "c" "d"
print $ hanoiR numOfDiscs ['a', 'b', 'c', 'd']
|
gscalzo/HaskellTheHardWay
|
cis194/week1/hanoi.hs
|
mit
| 1,600 | 0 | 11 | 546 | 565 | 303 | 262 | 28 | 1 |
-- |
--
-- Checks that namespaces /can/ be nested
module Main where
import Control.Biegunka
import System.Exit (ExitCode)
main :: IO ExitCode
main = biegunka id run $ do
namespace "outer" $
namespace "inner" $
return ()
namespace "outer" $
namespace "inner" $
return ()
|
biegunka/biegunka
|
test/typecheck/should_compile/OK6.hs
|
mit
| 297 | 0 | 10 | 72 | 88 | 44 | 44 | 11 | 1 |
import Data.List
import Math
exp2 n
| m == 1 && r == 0 = True
| r /= 0 = False
| otherwise = exp2 m
where m = quot n 2
r = rem n 2
specPrimes lim = [x|i <- [1.. (ceiling $ logBase 2 lim)], let x = 2^i + 1, prime x]
powerFor2 lim = [ m | m <- [1..lim], (rem m 2) == 0,
((rem (succ m) 3) == 0) || ((rem (m + 3) 3) == 0) || ((rem (m +7) 3) == 0) ||
((rem (m + 15) 3) == 0)]
useful2 lim = [m | m <- powerFor2 lim, 2^m < 10^10]
spPrimePow lim = [round res| p <- [5, 17, 257, 65537], i <- [1.. (ceiling (logBase 5 lim))],
let res = p^i , res < lim]
-- notes
-- pm => 2,4
-- p => 5,17
aForP :: (Integral a) => a -> a -> [a]
aForP pm lim = [m | m <- [2,4.. (ceiling $ logBase 2 (fromIntegral lim))],
((rem (m + pm - 1) 3) == 0)]
pPowers :: (Integral b) => b -> b -> [b]
pPowers p lim = [pn | n <- [4,6.. (ceiling $ logBase (fromIntegral p) (fromIntegral lim))],
((rem (succ n) 3) == 0), let pn = p^n, pn < lim]
pByPm :: (Integral c) => c -> c
pByPm pm = (2^pm) + 1
nByPm :: (Integral d) => d -> d -> [d]
nByPm pm lim = [res | a <- (aForP pm lim), q <- (pPowers (succ (2^pm)) lim),
let res = (2^a) * (((2^pm)+1)^q), res < lim]
|
zeniuseducation/poly-euler
|
haskell/prob301-400.hs
|
epl-1.0
| 1,249 | 8 | 19 | 402 | 811 | 423 | 388 | 26 | 1 |
-- Copyright (C) 2002-2004 David Roundy
-- Copyright (C) 2005 Juliusz Chroboczek
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2, or (at your option)
-- any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; see the file COPYING. If not, write to
-- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-- Boston, MA 02110-1301, USA.
{-# LANGUAGE CPP, ScopedTypeVariables #-}
module Darcs.Repository
( Repository
, HashedDir(..)
, Cache(..)
, CacheLoc(..)
, WritableOrNot(..)
, RepoJob(..)
, maybeIdentifyRepository
, identifyRepositoryFor
, withRecorded
, withRepoLock
, withRepoLockCanFail
, withRepository
, withRepositoryDirectory
, writePatchSet
, findRepository
, amInRepository
, amNotInRepository
, amInHashedRepository
, replacePristine
, readRepo
, prefsUrl
, repoPatchType
, readRepoUsingSpecificInventory
, addToPending
, addPendingDiffToPending
, tentativelyAddPatch
, tentativelyRemovePatches
, tentativelyAddToPending
, tentativelyReplacePatches
, readTentativeRepo
, withManualRebaseUpdate
, tentativelyMergePatches
, considerMergeToWorking
, revertRepositoryChanges
, finalizeRepositoryChanges
, createRepository
, cloneRepository
, patchSetToRepository
, unrevertUrl
, applyToWorking
, patchSetToPatches
, createPristineDirectoryTree
, createPartialsPristineDirectoryTree
, reorderInventory
, cleanRepository
, PatchSet
, SealedPatchSet
, PatchInfoAnd
, setScriptsExecutable
, setScriptsExecutablePatches
, checkUnrelatedRepos
, testTentative
, modifyCache
, reportBadSources
-- * Recorded and unrecorded and pending.
, readRecorded
, readUnrecorded
, unrecordedChanges
, unrecordedChangesWithPatches
, filterOutConflicts
, readPending
, readRecordedAndPending
-- * Index.
, readIndex
, invalidateIndex
-- * Used as command arguments
, listFiles
, listRegisteredFiles
, listUnregisteredFiles
) where
import Prelude hiding ( catch, pi )
import System.Exit ( exitSuccess )
import Data.List ( (\\), isPrefixOf )
import Data.Maybe( catMaybes, isJust, listToMaybe )
import Darcs.Repository.State
( readRecorded
, readUnrecorded
, readWorking
, unrecordedChanges
, unrecordedChangesWithPatches
, readPendingAndWorking
, readPending
, readIndex
, invalidateIndex
, readRecordedAndPending
, restrictDarcsdir
, restrictBoring
, applyTreeFilter
, filterOutConflicts
)
import Darcs.Repository.Internal
(Repository(..)
, maybeIdentifyRepository
, identifyRepositoryFor
, identifyRepository
, IdentifyRepo(..)
, findRepository
, amInRepository
, amNotInRepository
, amInHashedRepository
, readRepo
, readTentativeRepo
, readRepoUsingSpecificInventory
, prefsUrl
, withRecorded
, tentativelyAddPatch
, tentativelyRemovePatches
, tentativelyReplacePatches
, tentativelyAddToPending
, revertRepositoryChanges
, finalizeRepositoryChanges
, unrevertUrl
, applyToWorking
, patchSetToPatches
, createPristineDirectoryTree
, createPartialsPristineDirectoryTree
, reorderInventory
, cleanRepository
, setScriptsExecutable
, setScriptsExecutablePatches
, makeNewPending
, seekRepo
)
import Darcs.Repository.Job
( RepoJob(..)
, withRepoLock
, withRepoLockCanFail
, withRepository
, withRepositoryDirectory
)
import Darcs.Repository.Rebase ( withManualRebaseUpdate )
import Darcs.Repository.Test
( testTentative )
import Darcs.Repository.Merge( tentativelyMergePatches
, considerMergeToWorking
)
import Darcs.Repository.Cache ( unionRemoteCaches
, fetchFileUsingCache
, speculateFileUsingCache
, HashedDir(..)
, Cache(..)
, CacheLoc(..)
, WritableOrNot(..)
, hashedDir
, bucketFolder
, CacheType(Directory)
, reportBadSources
)
import Darcs.Patch ( RepoPatch
, apply
, invert
, effect
, PrimOf
)
import Darcs.Patch.Set ( Origin
, PatchSet(..)
, SealedPatchSet
, newset2RL
, newset2FL
, progressPatchSet
)
import Darcs.Patch.Match ( MatchFlag(..), havePatchsetMatch )
import Darcs.Patch.Commute( commuteFL )
import Darcs.Patch.Permutations ( genCommuteWhatWeCanRL )
import Control.Exception ( catch, Exception, throwIO, finally, IOException )
import Control.Concurrent ( forkIO )
import Control.Concurrent.MVar ( MVar
, newMVar
, putMVar
, takeMVar
)
import Control.Monad ( unless, when, void )
import Control.Applicative( (<$>) )
import System.Directory ( createDirectory
, createDirectoryIfMissing
, renameFile
, doesFileExist
, removeFile
, getDirectoryContents
, getCurrentDirectory
, setCurrentDirectory
)
import System.IO ( stderr )
import System.IO.Error ( isAlreadyExistsError )
import System.Posix.Files ( createLink )
import qualified Darcs.Repository.HashedRepo as HashedRepo
import Darcs.Patch.PatchInfoAnd ( PatchInfoAnd, extractHash, hopefully )
import Darcs.Repository.ApplyPatches ( applyPatches, runDefault )
import Darcs.Repository.HashedRepo ( applyToTentativePristine
, pris2inv
, inv2pris
, revertTentativeChanges
, copySources
)
import Darcs.Repository.InternalTypes ( modifyCache )
import Darcs.Patch.Apply( ApplyState )
import Darcs.Patch.Witnesses.Sealed ( Sealed(..), FreeLeft, unFreeLeft )
import Darcs.Patch.Witnesses.Ordered
((:>)(..), reverseRL, reverseFL, lengthFL, mapFL_FL, FL(..),
RL(..), bunchFL, mapFL, mapRL, lengthRL, (+>+), (:\/:)(..))
import Darcs.Repository.Format ( RepoProperty ( HashedInventory, Darcs2 )
, RepoFormat
, createRepoFormat
, formatHas
, writeRepoFormat
, readProblem
)
import Darcs.Repository.Prefs ( writeDefaultPrefs, addRepoSource, deleteSources )
import Darcs.Repository.Match ( getOnePatchset )
import Darcs.Patch.Depends ( areUnrelatedRepos, findUncommon, findCommonWithThem
, countUsThem )
import Darcs.Patch.Type ( PatchType(..) )
import Darcs.Util.Exception ( catchall )
import Darcs.Util.File ( withCurrentDirectory )
import Darcs.Util.Prompt ( promptYorn )
import Darcs.Util.English ( englishNum, Noun(..) )
import Darcs.Repository.External
( copyFileOrUrl
, Cachable(..)
, fetchFileLazyPS
, gzFetchFilePS
)
import Darcs.Util.Progress ( debugMessage
, tediousSize
, beginTedious
, endTedious
)
import Darcs.Patch.Progress
( progressRLShowTags
, progressFL
)
import Darcs.Repository.Lock
( writeBinFile
, writeDocBinFile
, withTemp
)
import Darcs.Repository.Flags
( UpdateWorking(..)
, UseCache(..)
, UseIndex(..)
, ScanKnown(..)
, RemoteDarcs (..)
, Reorder (..)
, Compression (..)
, CloneKind (..)
, Verbosity (..)
, DryRun (..)
, UMask (..)
, AllowConflicts (..)
, ExternalMerge (..)
, WantGuiPause (..)
, SetScriptsExecutable (..)
, RemoteRepos (..)
, SetDefault (..)
, DiffAlgorithm (..)
, WithWorkingDir (..)
, ForgetParent (..)
, WithPatchIndex (..)
)
import Darcs.Util.Download ( maxPipelineLength )
import Darcs.Util.Global ( darcsdir )
import Darcs.Util.URL ( isValidLocalPath )
import Darcs.Util.SignalHandler ( catchInterrupt )
import Darcs.Util.Printer ( Doc, text, hPutDocLn, putDocLn, errorDoc, RenderMode(..) )
import Storage.Hashed.Plain( readPlainTree )
import Storage.Hashed.Tree( Tree, emptyTree, expand, list )
import Storage.Hashed.Hash( encodeBase16 )
import Darcs.Util.Path( anchorPath )
import Storage.Hashed.Darcs( writeDarcsHashed, darcsAddMissingHashes )
import Darcs.Util.ByteString( gzReadFilePS )
import System.FilePath( (</>)
, takeFileName
, splitPath
, joinPath
, takeDirectory
)
import qualified Codec.Archive.Tar as Tar
import Codec.Compression.GZip ( compress, decompress )
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import Darcs.Repository.PatchIndex (createOrUpdatePatchIndexDisk, doesPatchIndexExist, createPIWithInterrupt)
#include "impossible.h"
-- @createRepository useFormat1 useNoWorkingDir patchIndex@
createRepository :: Bool -> WithWorkingDir -> WithPatchIndex -> IO ()
createRepository useFormat1 withWorkingDir createPatchIndex = do
createDirectory darcsdir `catch`
(\e-> if isAlreadyExistsError e
then fail "Tree has already been initialized!"
else fail $ "Error creating directory `"++darcsdir++"'.")
cwd <- getCurrentDirectory
x <- seekRepo
when (isJust x) $ do
setCurrentDirectory cwd
putStrLn "WARNING: creating a nested repository."
createDirectory $ darcsdir ++ "/pristine.hashed"
createDirectory $ darcsdir ++ "/patches"
createDirectory $ darcsdir ++ "/inventories"
createDirectory $ darcsdir ++ "/prefs"
writeDefaultPrefs
let repoFormat = createRepoFormat useFormat1 withWorkingDir
writeRepoFormat repoFormat (darcsdir++"/format")
writeBinFile (darcsdir++"/hashed_inventory") ""
writePristine "." emptyTree
withRepository NoUseCache $ RepoJob $ \repo -> case createPatchIndex of
NoPatchIndex -> return () -- default
YesPatchIndex -> createOrUpdatePatchIndexDisk repo
repoPatchType :: Repository p wR wU wT -> PatchType p
repoPatchType _ = PatchType
cloneRepository ::
String -- origin repository path
-> String -- new repository name (for relative path)
-> Verbosity -> UseCache
-> CloneKind
-> UMask -> RemoteDarcs
-> SetScriptsExecutable
-> RemoteRepos -> SetDefault
-> [MatchFlag]
-> RepoFormat
-> WithWorkingDir
-> WithPatchIndex -- use patch index
-> Bool -- use packs
-> Bool -- --to-match given
-> ForgetParent
-> IO ()
cloneRepository repodir mysimplename v uc cloneKind um rdarcs sse remoteRepos
setDefault matchFlags rfsource withWorkingDir usePatchIndex usePacks toMatch forget = do
createDirectory mysimplename
setCurrentDirectory mysimplename
createRepository (not $ formatHas Darcs2 rfsource)
withWorkingDir
(if cloneKind == LazyClone then NoPatchIndex else usePatchIndex)
debugMessage "Finished initializing new directory."
addRepoSource repodir NoDryRun remoteRepos setDefault
if toMatch && cloneKind /= LazyClone
then withRepository uc $ RepoJob $ \repository -> do
debugMessage "Using economical clone --to-match handling"
fromrepo <- identifyRepositoryFor repository uc repodir
Sealed patches_to_get <- getOnePatchset fromrepo matchFlags
patchSetToRepository fromrepo patches_to_get uc rdarcs
debugMessage "Finished converting selected patch set to new repository"
else copyRepoAndGoToChosenVersion repodir v uc cloneKind um rdarcs sse
matchFlags withWorkingDir usePacks forget
-- assumes that the target repo of the get is the current directory,
-- and that an inventory in the right format has already been created.
copyRepoAndGoToChosenVersion ::
String -- repository directory
-> Verbosity -> UseCache
-> CloneKind
-> UMask -> RemoteDarcs
-> SetScriptsExecutable
-> [MatchFlag]
-> WithWorkingDir -> Bool
-> ForgetParent
-> IO ()
copyRepoAndGoToChosenVersion repodir v uc gk um rdarcs sse matchFlags withWorkingDir usePacks forget =
withRepository uc $ RepoJob $ \repository -> do
debugMessage "Identifying and copying repository..."
fromRepo@(Repo fromDir rffrom _ _) <- identifyRepositoryFor repository uc repodir
case readProblem rffrom of
Just e -> fail $ "Incompatibility with repository " ++ fromDir ++ ":\n" ++ e
Nothing -> return ()
debugMessage "Copying prefs"
copyFileOrUrl rdarcs (fromDir ++ "/" ++ darcsdir ++ "/prefs/prefs")
(darcsdir ++ "/prefs/prefs") (MaxAge 600) `catchall` return ()
if formatHas HashedInventory rffrom
then do
-- copying basic repository (hashed_inventory and pristine)
if usePacks && (not . isValidLocalPath) fromDir
then copyBasicRepoPacked fromRepo v uc um rdarcs withWorkingDir
else copyBasicRepoNotPacked fromRepo v uc um rdarcs withWorkingDir
when (gk /= LazyClone) $ do
when (gk /= CompleteClone) $
putInfo v $ text "Copying patches, to get lazy repository hit ctrl-C..."
-- copying complete repository (inventories and patches)
if usePacks && (not . isValidLocalPath) fromDir
then copyCompleteRepoPacked fromRepo v uc um gk
else copyCompleteRepoNotPacked fromRepo v uc um gk
else
-- old-fashioned repositories are cloned diferently since
-- we need to copy all patches first and then build pristine
copyRepoOldFashioned fromRepo v uc um withWorkingDir
when (sse == YesSetScriptsExecutable) setScriptsExecutable
when (havePatchsetMatch matchFlags) $ do
putStrLn "Going to specified version..."
-- read again repository on disk to get caches and sources right
withRepoLock NoDryRun uc YesUpdateWorking um $ RepoJob $ \repository' -> do
patches <- readRepo repository'
Sealed context <- getOnePatchset repository' matchFlags
when (snd (countUsThem patches context) > 0) $
errorDoc $ text "Missing patches from context!" -- FIXME : - (
_ :> us' <- return $ findCommonWithThem patches context
let ps = mapFL_FL hopefully us'
putInfo v $ text $ "Unapplying " ++ show (lengthFL ps) ++ " " ++
englishNum (lengthFL ps) (Noun "patch") ""
invalidateIndex repository'
_ <- tentativelyRemovePatches repository' GzipCompression YesUpdateWorking us'
tentativelyAddToPending repository' YesUpdateWorking $ invert $ effect us'
finalizeRepositoryChanges repository' YesUpdateWorking GzipCompression
runDefault (apply (invert $ effect ps)) `catch` \(e :: IOException) ->
fail ("Couldn't undo patch in working dir.\n" ++ show e)
when (sse == YesSetScriptsExecutable) $ setScriptsExecutablePatches (invert $ effect ps)
when (forget == YesForgetParent) deleteSources
putInfo :: Verbosity -> Doc -> IO ()
putInfo Quiet _ = return ()
putInfo _ d = hPutDocLn Encode stderr d
putVerbose :: Verbosity -> Doc -> IO ()
putVerbose Verbose d = putDocLn d
putVerbose _ _ = return ()
copyBasicRepoNotPacked :: forall p wR wU wT. (RepoPatch p, ApplyState p ~ Tree)
=> Repository p wR wU wT
-> Verbosity -> UseCache
-> UMask -> RemoteDarcs
-> WithWorkingDir
-> IO ()
copyBasicRepoNotPacked (Repo fromDir _ _ fromCache) verb useCache umask rdarcs withWorkingDir = do
toRepo@(Repo toDir toFormat toPristine toCache) <- identifyRepository useCache "."
let (_dummy :: Repository p wR wU wT) = toRepo --The witnesses are wrong, but cannot escape
toCache2 <- unionRemoteCaches toCache fromCache fromDir
let toRepo2 :: Repository p wR wU wT
toRepo2 = Repo toDir toFormat toPristine toCache2
HashedRepo.copyHashedInventory toRepo2 rdarcs fromDir
HashedRepo.copySources toRepo2 fromDir
debugMessage "Grabbing lock in new repository to copy basic repo..."
withRepoLock NoDryRun useCache YesUpdateWorking umask
$ RepoJob $ \torepository -> do
putVerbose verb $ text "Writing pristine and working directory contents..."
createPristineDirectoryTree torepository "." withWorkingDir
copyCompleteRepoNotPacked :: forall p wR wU wT. (RepoPatch p, ApplyState p ~ Tree)
=> Repository p wR wU wT
-> Verbosity -> UseCache
-> UMask -> CloneKind
-> IO ()
copyCompleteRepoNotPacked _ verb useCache umask cloneKind = do
debugMessage "Grabbing lock in new repository to copy complete repo..."
withRepoLock NoDryRun useCache YesUpdateWorking umask
$ RepoJob $ \torepository@(Repo todir _ _ _) -> do
let cleanup = putInfo verb $ text "Using lazy repository."
allowCtrlC cloneKind cleanup $ do
fetchPatchesIfNecessary torepository
pi <- doesPatchIndexExist todir
when pi $ createPIWithInterrupt torepository
packsDir :: String
packsDir = "/" ++ darcsdir ++ "/packs/"
copyBasicRepoPacked ::
forall p wR wU wT. (RepoPatch p, ApplyState (PrimOf p) ~ Tree, ApplyState p ~ Tree)
=> Repository p wR wU wT
-> Verbosity -> UseCache
-> UMask -> RemoteDarcs
-> WithWorkingDir
-> IO ()
copyBasicRepoPacked r@(Repo fromDir _ _ _) verb useCache umask rdarcs withWorkingDir =
do let hashURL = fromDir ++ packsDir ++ "pristine"
mPackHash <- (Just <$> gzFetchFilePS hashURL Uncachable) `catchall` (return Nothing)
let hiURL = fromDir ++ "/" ++ darcsdir ++ "/hashed_inventory"
i <- gzFetchFilePS hiURL Uncachable
let currentHash = BS.pack $ inv2pris i
let copyNormally = copyBasicRepoNotPacked r verb useCache umask rdarcs withWorkingDir
case mPackHash of
Just packHash | packHash == currentHash
-> ( copyBasicRepoPacked2 r verb useCache withWorkingDir
`catchall` do putStrLn "Problem while copying basic pack, copying normally."
copyNormally)
_ -> do putVerbose verb $ text "Remote repo has no basic pack or outdated basic pack, copying normally."
copyNormally
copyBasicRepoPacked2 ::
forall p wR wU wT. (RepoPatch p, ApplyState (PrimOf p) ~ Tree, ApplyState p ~ Tree)
=> Repository p wR wU wT
-> Verbosity -> UseCache
-> WithWorkingDir -> IO ()
copyBasicRepoPacked2 fromRepo@(Repo fromDir _ _ fromCache) verb useCache withWorkingDir = do
b <- fetchFileLazyPS (fromDir ++ packsDir ++ "basic.tar.gz") Uncachable
putVerbose verb $ text "Cloning packed basic repository."
Repo toDir toFormat toPristine toCache <-
identifyRepositoryFor fromRepo useCache "."
toCache2 <- unionRemoteCaches toCache fromCache fromDir
let toRepo :: Repository p wR wU wR -- In empty repo, t(entative) = r(ecorded)
toRepo = Repo toDir toFormat toPristine toCache2
copySources toRepo fromDir
Repo _ _ _ toCache3 <-
identifyRepositoryFor toRepo useCache "."
-- unpack inventory & pristine cache
cleanDir "pristine.hashed"
removeFile $ darcsdir </> "hashed_inventory"
unpackBasic toCache3 . Tar.read $ decompress b
createPristineDirectoryTree toRepo "." withWorkingDir
putVerbose verb $ text "Basic repository unpacked. Will now see if there are new patches."
-- pull new patches
us <- readRepo toRepo
them <- readRepo fromRepo
us' :\/: them' <- return $ findUncommon us them
revertTentativeChanges
Sealed pw <- tentativelyMergePatches toRepo "clone" NoAllowConflicts YesUpdateWorking NoExternalMerge NoWantGuiPause GzipCompression verb NoReorder ( UseIndex, ScanKnown, MyersDiff ) us' them'
invalidateIndex toRepo
finalizeRepositoryChanges toRepo YesUpdateWorking GzipCompression
when (withWorkingDir == WithWorkingDir) $ void $ applyToWorking toRepo verb pw
where
cleanDir d = mapM_ (\x -> removeFile $ darcsdir </> d </> x) .
filter (\x -> head x /= '.') =<< getDirectoryContents (darcsdir </> d)
copyCompleteRepoPacked ::
forall p wR wU wT. (RepoPatch p, ApplyState (PrimOf p) ~ Tree, ApplyState p ~ Tree)
=> Repository p wR wU wT
-> Verbosity -> UseCache
-> UMask
-> CloneKind
-> IO ()
copyCompleteRepoPacked r verb useCache umask cloneKind =
( copyCompleteRepoPacked2 r verb useCache cloneKind
`catchall` do putVerbose verb $ text "Problem while copying patches pack, copying normally."
copyCompleteRepoNotPacked r verb useCache umask cloneKind )
copyCompleteRepoPacked2 ::
forall p wR wU wT. (RepoPatch p, ApplyState (PrimOf p) ~ Tree, ApplyState p ~ Tree)
=> Repository p wR wU wT
-> Verbosity -> UseCache
-> CloneKind
-> IO ()
copyCompleteRepoPacked2 fromRepo@(Repo fromDir _ _ fromCache) verb useCache cloneKind = do
Repo toDir toFormat toPristine toCache <- identifyRepositoryFor fromRepo useCache "."
toCache2 <- unionRemoteCaches toCache fromCache fromDir
let toRepo :: Repository p wR wU wR -- In empty repo, t(entative) = r(ecorded)
toRepo = Repo toDir toFormat toPristine toCache2
Repo _ _ _ toCache3 <- identifyRepositoryFor toRepo useCache "."
us <- readRepo toRepo
-- get old patches
let cleanup = putInfo verb $ text "Using lazy repository."
allowCtrlC cloneKind cleanup $ do
cleanDir "patches"
putVerbose verb $ text "Using patches pack."
unpackPatches toCache3 (mapRL hashedPatchFileName $ newset2RL us) .
Tar.read . decompress =<< fetchFileLazyPS (fromDir ++ packsDir ++ "patches.tar.gz") Uncachable
pi <- doesPatchIndexExist toDir
when pi $ createPIWithInterrupt toRepo
where
cleanDir d = mapM_ (\x -> removeFile $ darcsdir </> d </> x) .
filter (\x -> head x /= '.') =<< getDirectoryContents (darcsdir </> d)
allowCtrlC :: CloneKind -> IO () -> IO () -> IO ()
allowCtrlC CompleteClone _ action = action
allowCtrlC _ cleanup action = action `catchInterrupt` cleanup
copyRepoOldFashioned :: forall p wR wU wT. (RepoPatch p, ApplyState p ~ Tree)
=> Repository p wR wU wT
-> Verbosity -> UseCache
-> UMask
-> WithWorkingDir
-> IO ()
copyRepoOldFashioned fromrepository verb useCache umask withWorkingDir = do
toRepo@(Repo _ _ _ toCache) <- identifyRepository useCache "."
let (_dummy :: Repository p wR wU wT) = toRepo --The witnesses are wrong, but cannot escape
-- copy all patches from remote
HashedRepo.revertTentativeChanges
patches <- readRepo fromrepository
let k = "Copying patch"
beginTedious k
tediousSize k (lengthRL $ newset2RL patches)
let patches' = progressPatchSet k patches
HashedRepo.writeTentativeInventory toCache GzipCompression patches'
endTedious k
HashedRepo.finalizeTentativeChanges toRepo GzipCompression
-- apply all patches into current hashed repository
debugMessage "Grabbing lock in new repository..."
withRepoLock NoDryRun useCache YesUpdateWorking umask
$ RepoJob $ \torepository -> do
local_patches <- readRepo torepository
replacePristine torepository emptyTree
let patchesToApply = progressFL "Applying patch" $ newset2FL local_patches
sequence_ $ mapFL applyToTentativePristine $ bunchFL 100 patchesToApply
finalizeRepositoryChanges torepository YesUpdateWorking GzipCompression
putVerbose verb $ text "Writing pristine and working directory contents..."
createPristineDirectoryTree torepository "." withWorkingDir
withControlMVar :: (MVar () -> IO ()) -> IO ()
withControlMVar f = do
mv <- newMVar ()
f mv
takeMVar mv
forkWithControlMVar :: MVar () -> IO () -> IO ()
forkWithControlMVar mv f = do
takeMVar mv
_ <- forkIO $ finally f (putMVar mv ())
return ()
removeMetaFiles :: IO ()
removeMetaFiles = mapM_ (removeFile . (darcsdir </>)) .
filter ("meta-" `isPrefixOf`) =<< getDirectoryContents darcsdir
unpackBasic :: Exception e => Cache -> Tar.Entries e -> IO ()
unpackBasic c x = do
withControlMVar $ \mv -> unpackTar c (basicMetaHandler c mv) x
removeMetaFiles
unpackPatches :: Exception e => Cache -> [String] -> Tar.Entries e -> IO ()
unpackPatches c ps x = do
withControlMVar $ \mv -> unpackTar c (patchesMetaHandler c ps mv) x
removeMetaFiles
unpackTar :: Exception e => Cache -> IO () -> Tar.Entries e -> IO ()
unpackTar _ _ Tar.Done = return ()
unpackTar _ _ (Tar.Fail e)= throwIO e
unpackTar c mh (Tar.Next x xs) = case Tar.entryContent x of
Tar.NormalFile x' _ -> do
let p = Tar.entryPath x
if "meta-" `isPrefixOf` takeFileName p
then do
BL.writeFile p x'
mh
unpackTar c mh xs
else do
ex <- doesFileExist p
if ex
then debugMessage $ "Tar thread: STOP " ++ p
else do
if p == darcsdir </> "hashed_inventory"
then writeFile' Nothing p x'
else writeFile' (cacheDir c) p $ compress x'
debugMessage $ "Tar thread: GET " ++ p
unpackTar c mh xs
_ -> fail "Unexpected non-file tar entry"
where
writeFile' Nothing path content = withTemp $ \tmp -> do
BL.writeFile tmp content
renameFile tmp path
writeFile' (Just ca) path content = do
let fileFullPath = case splitPath path of
_:hDir:hFile:_ -> joinPath [ca, hDir, bucketFolder hFile, hFile]
_ -> fail "Unexpected file path"
createDirectoryIfMissing True $ takeDirectory path
createLink fileFullPath path `catch` (\(ex :: IOException) -> do
if isAlreadyExistsError ex then
return () -- so much the better
else
-- ignore cache if we cannot link
writeFile' Nothing path content)
basicMetaHandler :: Cache -> MVar () -> IO ()
basicMetaHandler ca mv = do
ex <- doesFileExist $ darcsdir </> "meta-filelist-pristine"
when ex . forkWithControlMVar mv $
fetchFilesUsingCache ca HashedPristineDir . lines =<<
readFile (darcsdir </> "meta-filelist-pristine")
patchesMetaHandler :: Cache -> [String] -> MVar () -> IO ()
patchesMetaHandler ca ps mv = do
ex <- doesFileExist $ darcsdir </> "meta-filelist-inventories"
when ex $ do
forkWithControlMVar mv $ fetchFilesUsingCache ca HashedPristineDir .
lines =<< readFile (darcsdir </> "meta-filelist-inventories")
forkWithControlMVar mv $ fetchFilesUsingCache ca HashedPatchesDir ps
cacheDir :: Cache -> Maybe String
cacheDir (Ca cs) = listToMaybe . catMaybes .flip map cs $ \x -> case x of
Cache Directory Writable x' -> Just x'
_ -> Nothing
hashedPatchFileName :: PatchInfoAnd p wA wB -> String
hashedPatchFileName x = case extractHash x of
Left _ -> fail "unexpected unhashed patch"
Right h -> h
-- | fetchFilesUsingCache is similar to mapM fetchFileUsingCache, exepts
-- it stops execution if file it's going to fetch already exists.
fetchFilesUsingCache :: Cache -> HashedDir -> [FilePath] -> IO ()
fetchFilesUsingCache _ _ [] = return ()
fetchFilesUsingCache c d (f:fs) = do
ex <- doesFileExist $ darcsdir </> hashedDir d </> f
if ex
then debugMessage $ "Cache thread: STOP " ++
(darcsdir </> hashedDir d </> f)
else do
debugMessage $ "Cache thread: GET " ++
(darcsdir </> hashedDir d </> f)
_ <- fetchFileUsingCache c d f
fetchFilesUsingCache c d fs
-- | writePatchSet is like patchSetToRepository, except that it doesn't
-- touch the working directory or pristine cache.
writePatchSet :: (RepoPatch p, ApplyState p ~ Tree)
=> PatchSet p Origin wX
-> UseCache
-> IO (Repository p wR wU wT)
writePatchSet patchset useCache = do
maybeRepo <- maybeIdentifyRepository useCache "."
let repo@(Repo _ _ _ c) =
case maybeRepo of
GoodRepository r -> r
BadRepository e -> bug ("Current directory is a bad repository in writePatchSet: " ++ e)
NonRepository e -> bug ("Current directory not a repository in writePatchSet: " ++ e)
debugMessage "Writing inventory"
HashedRepo.writeTentativeInventory c GzipCompression patchset
HashedRepo.finalizeTentativeChanges repo GzipCompression
return repo
-- | patchSetToRepository takes a patch set, and writes a new repository
-- in the current directory that contains all the patches in the patch
-- set. This function is used when 'darcs get'ing a repository with
-- the --to-match flag.
patchSetToRepository :: (RepoPatch p, ApplyState p ~ Tree)
=> Repository p wR1 wU1 wR1
-> PatchSet p Origin wX
-> UseCache -> RemoteDarcs
-> IO ()
patchSetToRepository (Repo fromrepo rf _ _) patchset useCache remoteDarcs = do
when (formatHas HashedInventory rf) $ -- set up sources and all that
do writeFile (darcsdir </> "tentative_pristine") "" -- this is hokey
repox <- writePatchSet patchset useCache
HashedRepo.copyHashedInventory repox remoteDarcs fromrepo
HashedRepo.copySources repox fromrepo
repo <- writePatchSet patchset useCache
readRepo repo >>= (runDefault . applyPatches . newset2FL)
debugMessage "Writing the pristine"
pristineFromWorking repo
checkUnrelatedRepos :: RepoPatch p
=> Bool
-> PatchSet p wStart wX
-> PatchSet p wStart wY
-> IO ()
checkUnrelatedRepos allowUnrelatedRepos us them =
when ( not allowUnrelatedRepos && areUnrelatedRepos us them ) $
do confirmed <- promptYorn "Repositories seem to be unrelated. Proceed?"
unless confirmed $ do putStrLn "Cancelled."
exitSuccess
-- | This function fetches all patches that the given repository has
-- with fetchFileUsingCache, unless --lazy is passed.
fetchPatchesIfNecessary :: forall p wR wU wT. (RepoPatch p, ApplyState p ~ Tree)
=> Repository p wR wU wT
-> IO ()
fetchPatchesIfNecessary torepository@(Repo _ _ _ c) =
do r <- readRepo torepository
pipelineLength <- maxPipelineLength
let patches = newset2RL r
ppatches = progressRLShowTags "Copying patches" patches
(first, other) = splitAt (pipelineLength - 1) $ tail $ hashes patches
speculate | pipelineLength > 1 = [] : first : map (:[]) other
| otherwise = []
mapM_ fetchAndSpeculate $ zip (hashes ppatches) (speculate ++ repeat [])
where hashes :: forall wX wY . RL (PatchInfoAnd p) wX wY -> [String]
hashes = catMaybes . mapRL (either (const Nothing) Just . extractHash)
fetchAndSpeculate :: (String, [String]) -> IO ()
fetchAndSpeculate (f, ss) = do
_ <- fetchFileUsingCache c HashedPatchesDir f
mapM_ (speculateFileUsingCache c HashedPatchesDir) ss
-- | Add an FL of patches started from the pending state to the pending patch.
-- TODO: add witnesses for pending so we can make the types precise: currently
-- the passed patch can be applied in any context, not just after pending.
addPendingDiffToPending :: (RepoPatch p, ApplyState p ~ Tree)
=> Repository p wR wU wT -> UpdateWorking
-> FreeLeft (FL (PrimOf p)) -> IO ()
addPendingDiffToPending _ NoUpdateWorking _ = return ()
addPendingDiffToPending repo@(Repo{}) uw@YesUpdateWorking newP = do
(toPend :> _) <-
readPendingAndWorking (UseIndex, ScanKnown, MyersDiff) repo Nothing
invalidateIndex repo
case unFreeLeft newP of
(Sealed p) -> makeNewPending repo uw $ toPend +>+ p
-- | Add a FL of patches starting from the working state to the pending patch,
-- including as much extra context as is necessary (context meaning
-- dependencies), by commuting the patches to be added past as much of the
-- changes between pending and working as is possible, and including anything
-- that doesn't commute, and the patch itself in the new pending patch.
addToPending :: (RepoPatch p, ApplyState p ~ Tree)
=> Repository p wR wU wT -> UpdateWorking -> FL (PrimOf p) wU wY -> IO ()
addToPending _ NoUpdateWorking _ = return ()
addToPending repo@(Repo{}) uw@YesUpdateWorking p = do
(toPend :> toUnrec) <- readPendingAndWorking (UseIndex, ScanKnown, MyersDiff) repo Nothing
invalidateIndex repo
case genCommuteWhatWeCanRL commuteFL (reverseFL toUnrec :> p) of
(toP' :> p' :> _excessUnrec) ->
makeNewPending repo uw $ toPend +>+ reverseRL toP' +>+ p'
-- | Replace the existing pristine with a new one (loaded up in a Tree object).
replacePristine :: Repository p wR wU wT -> Tree IO -> IO ()
replacePristine (Repo r _ _ _) = writePristine r
writePristine :: FilePath -> Tree IO -> IO ()
writePristine r tree = withCurrentDirectory r $
do let t = darcsdir </> "hashed_inventory"
i <- gzReadFilePS t
tree' <- darcsAddMissingHashes tree
root <- writeDarcsHashed tree' $ darcsdir </> "pristine.hashed"
writeDocBinFile t $ pris2inv (BS.unpack $ encodeBase16 root) i
pristineFromWorking :: RepoPatch p => Repository p wR wU wT -> IO ()
pristineFromWorking repo@(Repo dir _ _ _) =
withCurrentDirectory dir $ readWorking >>= replacePristine repo
-- | Get a list of all files and directories in the working copy, including
-- boring files if necessary
listFiles :: Bool -> IO [String]
listFiles takeBoring =
do
nonboring <- considered emptyTree
working <- expand =<< applyTreeFilter nonboring <$> readPlainTree "."
return $ map (anchorPath "" . fst) $ list working
where
considered = if takeBoring
then const (return restrictDarcsdir)
else restrictBoring
-- | 'listUnregisteredFiles' returns the list of all non-boring unregistered
-- files in the repository.
listUnregisteredFiles :: Bool -> IO [String]
listUnregisteredFiles includeBoring =
do unregd <- listFiles includeBoring
regd <- listRegisteredFiles
return $ unregd \\ regd -- (inefficient)
-- | 'listRegisteredFiles' returns the list of all registered files in the repository.
listRegisteredFiles :: IO [String]
listRegisteredFiles =
do recorded <- expand =<< withRepository YesUseCache (RepoJob readRecordedAndPending)
return $ map (anchorPath "" . fst) $ list recorded
|
DavidAlphaFox/darcs
|
src/Darcs/Repository.hs
|
gpl-2.0
| 35,578 | 398 | 23 | 9,234 | 7,985 | 4,310 | 3,675 | 726 | 8 |
instance Functor Tree where
fmap f (Leaf a) = Leaf (f a)
fmap f (Node t t') = Node (fmap f t) (fmap f t')
|
hmemcpy/milewski-ctfp-pdf
|
src/content/1.8/code/haskell/snippet15.hs
|
gpl-3.0
| 113 | 0 | 8 | 32 | 73 | 35 | 38 | 3 | 0 |
--
---- Copyright (c) 2015 Scott Wakeling - http://www.diskfish.org/
---- GPL version 3 or later (see http://www.gnu.org/licenses/gpl.html)
--
module Compile
(
compileSrc,
getSrcFilesRecursive
) where
import Control.Monad (forM)
import Data.List.Utils
import System.Process
import System.Directory
import System.FilePath.Posix
import Text.Regex.Posix
import Compile.Internal
import Yaml
{- A class of types that can be compiled and post-processed. -}
class SourceFiles f where
compile :: f -> String -> FilePath -> IO ()
postProcess :: f -> String -> FilePath -> IO ()
data SourceFile = MarkdownFile FilePath | ImageFile FilePath
{- TODO: Represent steps in compile and postProcess with some IR? -}
instance SourceFiles SourceFile where
{- Compile markdown to html. -}
compile (MarkdownFile path) theme etcDir = do
let dst = addExtension (dropExtension ("public_html/" ++ path)) "html"
putStrLn $ "Compiling " ++ path ++ " to " ++ dst
createDirectoryIfMissing True (fst (splitFileName dst))
rawSystem "pandoc" [ "-B"
, etcDir ++ "/themes/" ++ theme ++ "/pre.mdwn"
, "-A"
, etcDir ++ "/themes/" ++ theme ++ "/post.mdwn"
, path
, "-o"
, dst
]
return ()
{- Compile images by copying them into place. -}
compile (ImageFile path) _ _ = do
let dst = addExtension (dropExtension ("public_html/" ++ path)) "jpg"
putStrLn $ "Copying " ++ path ++ " to " ++ dst
createDirectoryIfMissing True (fst (splitFileName dst))
rawSystem "cp" [path, dst]
return ()
{- Patches 'href="stylesheets' occurrences to be relative to the output
- file in the publish directory, e.g. 'href="../stylesheets' where the
- output file location is one dir deep. -}
postProcess (MarkdownFile path) theme etcDir = do
let ss = "stylesheets"
let html = addExtension (dropExtension ("public_html/" ++ path)) "html"
replace ("href=\"" ++ ss) ("href=\"" ++ (srcRoot html) ++ ss) html
return ()
where
count str c = length $ filter (== c) str
srcRoot path = foldl (++) "" (take (count path '/' -2) $ repeat "../")
replace string replacement output = do
rawSystem "sed" [ "-i"
, "s~" ++ string ++ "~" ++ replacement ++ "~g"
, output]
postProcess (ImageFile path) _ _ = do
return ()
{-
- Compiles an input list of SourceFiles to the default output location,
- replacing the .mdwn extensions with .html
- TOOD: Should not assume public_html is in .
- -}
compileSrc :: (SourceFiles f) => [f] -> String -> FilePath -> IO ()
compileSrc [] _ _ = do
return ()
compileSrc (x:xs) theme etcDir = do
compile x theme etcDir
postProcess x theme etcDir
compileSrc xs theme etcDir
return ()
{-
- Returns a recursive list of all markdown file paths beneath 'root'.
- -}
getSrcFilesRecursive :: FilePath -> IO [SourceFile]
getSrcFilesRecursive root = do
names <- getDirectoryContents root
let properNames = filter (isSrcFileOrDir) names
paths <- forM properNames $ \name -> do
let path = root </> name
isDirectory <- doesDirectoryExist path
case isDirectory of
True -> getSrcFilesRecursive path
False -> case isMarkdown path of
True -> return [MarkdownFile path]
False -> return [ImageFile path]
return (concat paths)
where
isSrcFileOrDir :: FilePath -> Bool
isSrcFileOrDir x = do
case hasExtension x of
True -> case isMarkdown x of
True -> True
False -> isImage x
False -> notElem x [".", "..", ".git"]
|
scottwakeling/hikiwiki
|
Compile.hs
|
gpl-3.0
| 3,975 | 35 | 22 | 1,256 | 948 | 489 | 459 | 76 | 5 |
import Sound.SC3
import qualified Data.ByteString.Lazy as B
import Sound.OpenSoundControl (Datum(..), OSC(..), Time(..), encodeOSC, utcr)
blobFromOSC :: OSC -> Datum
blobFromOSC = Blob . B.unpack . encodeOSC
d_load' :: String -> OSC -> OSC
d_load' p c = Message "/d_load" [String p, blobFromOSC c]
complMess _ = s_new "default" 1001 AddToTail 0 [("freq", 440)]
complBund = flip Bundle [s_new "default" 1001 AddToTail 0 [("freq", 440)],
s_new "default" 1002 AddToTail 0 [("freq", 550)],
s_new "default" 1003 AddToTail 0 [("freq", 660)]]
compl = complBund
main = do
t <- (UTCr . (+5)) `fmap` utcr
withSC3 $ \fd -> do
send fd $ d_load'
"/Users/sk/scwork/synthdefs/default.scsyndef"
(compl t)
|
kaoskorobase/mescaline
|
tests/scsynth/completion.hs
|
gpl-3.0
| 799 | 0 | 14 | 213 | 287 | 160 | 127 | 18 | 1 |
module Main where
import System.Random
import Test.Tasty
import Test.Tasty.QuickCheck as QC
import ABSFeedbackTests
import ABSDataTests
-- to generate html from coverage use hpc:
-- hpc markup --hpcdir=/home/io.nathan/phd/coding/reports/verificationABS/Testing/.stack-work/dist/x86_64-linux-tinfo6/Cabal-2.0.1.0/hpc SIRABS.tix
main :: IO ()
main = do
g <- getStdGen
let tests = [absDataTests g] --[ absFeedbackTests g, absDataTests g ]
defaultMain $ testGroup "SIR ABS Tests" tests
|
thalerjonathan/phd
|
coding/papers/pfe/testing/src/Main.hs
|
gpl-3.0
| 494 | 0 | 11 | 68 | 80 | 45 | 35 | 11 | 1 |
{-# LANGUAGE Arrows #-}
{-# LANGUAGE FlexibleContexts #-}
module SugarScape.Agent
( agentSF
, dieOfAge
, agentMetabolism
, agentDies
, starvedToDeath
) where
import Control.Monad.Random
import Control.Monad.State.Strict
import FRP.BearRiver
import SugarScape.AgentMonad
import SugarScape.Common
import SugarScape.Discrete
import SugarScape.Model
import SugarScape.Random
import SugarScape.Utils
------------------------------------------------------------------------------------------------------------------------
agentSF :: RandomGen g
=> SugarScapeParams
-> AgentId
-> SugAgentState
-> SugAgent g
agentSF params aid s0 = feedback s0 (proc (_, s) -> do
t <- time -< ()
let age = floor t
(ao, s') <- arrM (\(age, s) -> lift $ runStateT (agentBehaviour params aid age) s) -< (age, s)
returnA -< (ao, s'))
------------------------------------------------------------------------------------------------------------------------
-- Chapter II: Life And Death On The Sugarscape
------------------------------------------------------------------------------------------------------------------------
agentBehaviour :: RandomGen g
=> SugarScapeParams
-> AgentId
-> Int
-> StateT SugAgentState (SugAgentMonadT g) (SugAgentOut g)
agentBehaviour params aid age = do
agentAgeing age
harvestAmount <- agentMove params aid
metabAmount <- agentMetabolism
agentPolute params harvestAmount (fromIntegral metabAmount)
ifThenElseM
(starvedToDeath `orM` dieOfAge)
(agentDies params)
observable
agentMove :: RandomGen g
=> SugarScapeParams
-> AgentId
-> StateT SugAgentState (SugAgentMonadT g) Double
agentMove params aid = do
cellsInSight <- agentLookout
coord <- agentProperty sugAgCoord
let uoc = filter (cellUnoccupied . snd) cellsInSight
ifThenElse
(null uoc)
(agentHarvestCell coord)
(do
-- NOTE included self but this will be always kicked out because self is occupied by self, need to somehow add this
-- what we want is that in case of same sugar on all fields (including self), the agent does not move because staying is the lowest distance (=0)
selfCell <- lift $ lift $ cellAtM coord
let uoc' = (coord, selfCell) : uoc
bf = bestCellFunc params
bcs = selectBestCells bf coord uoc'
(cellCoord, _) <- lift $ lift $ lift $ randomElemM bcs
agentMoveTo aid cellCoord
agentHarvestCell cellCoord)
agentLookout :: RandomGen g
=> StateT SugAgentState (SugAgentMonadT g) [(Discrete2dCoord, SugEnvCell)]
agentLookout = do
vis <- agentProperty sugAgVision
coord <- agentProperty sugAgCoord
lift $ lift $ neighboursInNeumannDistanceM coord vis False
agentMoveTo :: RandomGen g
=> AgentId
-> Discrete2dCoord
-> StateT SugAgentState (SugAgentMonadT g) ()
agentMoveTo aid cellCoord = do
unoccupyPosition
updateAgentState (\s -> s { sugAgCoord = cellCoord })
cell <- lift $ lift $ cellAtM cellCoord
let co = cell { sugEnvCellOccupier = Just aid }
lift $ lift $ changeCellAtM cellCoord co
agentHarvestCell :: RandomGen g
=> Discrete2dCoord
-> StateT SugAgentState (SugAgentMonadT g) Double
agentHarvestCell cellCoord = do
cell <- lift $ lift $ cellAtM cellCoord
sugarLevelAgent <- agentProperty sugAgSugarLevel
let sugarLevelCell = sugEnvCellSugarLevel cell
let newSugarLevelAgent = sugarLevelCell + sugarLevelAgent
updateAgentState (\s -> s { sugAgSugarLevel = newSugarLevelAgent })
let cellHarvested = cell { sugEnvCellSugarLevel = 0 }
lift $ lift $ changeCellAtM cellCoord cellHarvested
return sugarLevelCell
agentMetabolism :: MonadState SugAgentState m
=> m Int
agentMetabolism = do
sugarMetab <- agentProperty sugAgSugarMetab
sugarLevel <- agentProperty sugAgSugarLevel
let sugarLevel' = max 0 (sugarLevel - fromIntegral sugarMetab)
updateAgentState (\s' -> s' { sugAgSugarLevel = sugarLevel' })
return sugarMetab
agentPolute :: RandomGen g
=> SugarScapeParams
-> Double
-> Double
-> StateT SugAgentState (SugAgentMonadT g) ()
agentPolute params s m = agentPoluteAux $ spPolutionFormation params
where
agentPoluteAux :: RandomGen g
=> PolutionFormation
-> StateT SugAgentState (SugAgentMonadT g) ()
agentPoluteAux NoPolution = return ()
agentPoluteAux (Polute a b) = do
let polution = a * s + b * m
(coord, c) <- agentCellOnCoord
let c' = c { sugEnvCellPolutionLevel = sugEnvCellPolutionLevel c + polution }
lift $ lift $ changeCellAtM coord c'
-- this is rule R implemented, see page 32/33 "when an agent dies it is replaced by an agent
-- of agent 0 having random genetic attributes, random position on the sugarscape..."
-- => will happen if agent starves to death (spice or sugar) or dies from age
agentDies :: RandomGen g
=> SugarScapeParams
-> StateT SugAgentState (SugAgentMonadT g) (SugAgentOut g)
agentDies params = do
unoccupyPosition
let ao = kill agentOut
if spReplaceAgents params
then do
(_, newA) <- birthNewAgent params
return $ newAgent newA ao
else return ao
birthNewAgent :: RandomGen g
=> SugarScapeParams
-> StateT SugAgentState (SugAgentMonadT g) (AgentId, SugAgentDef g)
birthNewAgent params = do
newAid <- lift nextAgentId
(newCoord, newCell) <- findUnoccpiedRandomPosition
(newA, _) <- lift $ lift $ lift $ randomAgent params (newAid, newCoord) (agentSF params) id
-- need to occupy the cell to prevent other agents occupying it
let newCell' = newCell { sugEnvCellOccupier = Just newAid }
lift $ lift $ changeCellAtM newCoord newCell'
return (newAid, newA)
where
-- the more cells occupied the less likely an unoccupied position will be found
-- => restrict number of recursions and if not found then take up same position
findUnoccpiedRandomPosition :: RandomGen g
=> StateT SugAgentState (SugAgentMonadT g) (Discrete2dCoord, SugEnvCell)
findUnoccpiedRandomPosition = do
e <- lift $ lift get
(c, coord) <- lift $ lift $ lift $ randomCell e -- TODO: replace by randomCellM
ifThenElse
(cellOccupied c)
findUnoccpiedRandomPosition
(return (coord, c))
agentAgeing :: MonadState SugAgentState m
=> Int
-> m ()
agentAgeing age = updateAgentState (\s' -> s' { sugAgAge = age })
dieOfAge :: MonadState SugAgentState m
=> m Bool
dieOfAge = do
ageSpan <- agentProperty sugAgMaxAge
case ageSpan of
Nothing -> return False
Just maxAge -> do
age <- agentProperty sugAgAge
return $ age >= maxAge
starvedToDeath :: MonadState SugAgentState m
=> m Bool
starvedToDeath = do
sugar <- agentProperty sugAgSugarLevel
return $ sugar <= 0
unoccupyPosition :: RandomGen g
=> StateT SugAgentState (SugAgentMonadT g) ()
unoccupyPosition = do
(coord, cell) <- agentCellOnCoord
let cell' = cell { sugEnvCellOccupier = Nothing }
lift $ lift $ changeCellAtM coord cell'
agentCellOnCoord :: RandomGen g
=> StateT SugAgentState (SugAgentMonadT g) (Discrete2dCoord, SugEnvCell)
agentCellOnCoord = do
coord <- agentProperty sugAgCoord
cell <- lift $ lift $ cellAtM coord
return (coord, cell)
updateAgentState :: MonadState SugAgentState m
=> (SugAgentState -> SugAgentState)
-> m ()
updateAgentState = modify
agentProperty :: MonadState SugAgentState m
=> (SugAgentState -> p)
-> m p
agentProperty = gets
observable :: (MonadState SugAgentState m, RandomGen g)
=> m (SugAgentOut g)
observable
= get >>= \s -> return $ agentOutObservable $ sugObservableFromState s
|
thalerjonathan/phd
|
public/towards/SugarScape/experimental/chapter2/src/SugarScape/Agent.hs
|
gpl-3.0
| 8,336 | 1 | 17 | 2,283 | 2,032 | 1,004 | 1,028 | 183 | 2 |
-- |
-- Module : Commands.RpmBuild
-- Copyright : (C) 2007-2008 Bryan O'Sullivan
-- (C) 2012-2014 Jens Petersen
--
-- Maintainer : Jens Petersen <[email protected]>
-- Stability : alpha
-- Portability : portable
--
-- Explanation: Support for building RPM packages. Can also generate
-- an RPM spec file if you need a basic one to hand-customize.
-- 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.
module Commands.RpmBuild (
rpmBuild, rpmBuild_
) where
import Commands.Spec (createSpecFile)
import Dependencies (missingPackages)
import PackageUtils (copyTarball, isScmDir, PackageData (..), packageName,
packageVersion, rpmbuild, RpmStage (..))
import Setup (RpmFlags (..))
import SysCmd (cmd, pkgInstall, (+-+))
--import Control.Exception (bracket)
import Control.Monad (unless, void, when)
import Distribution.PackageDescription (PackageDescription (..))
--import Distribution.Version (VersionRange, foldVersionRange')
import System.Directory (createDirectoryIfMissing, doesDirectoryExist,
doesFileExist)
import System.FilePath (takeDirectory, (</>))
-- autoreconf :: Verbosity -> PackageDescription -> IO ()
-- autoreconf verbose pkgDesc = do
-- ac <- doesFileExist "configure.ac"
-- when ac $ do
-- c <- doesFileExist "configure"
-- when (not c) $ do
-- setupMessage verbose "Running autoreconf" pkgDesc
-- cmd_ "autoreconf" []
rpmBuild :: PackageData -> RpmFlags -> RpmStage ->
IO FilePath
rpmBuild pkgdata flags stage = do
-- let verbose = rpmVerbosity flags
-- bracket (setFileCreationMask 0o022) setFileCreationMask $ \ _ -> do
-- autoreconf verbose pkgDesc
let pkgDesc = packageDesc pkgdata
mspec = specFilename pkgdata
cabalPath = cabalFilename pkgdata
specFile <- maybe (createSpecFile pkgdata flags Nothing)
(\ s -> putStrLn ("Using existing" +-+ s) >> return s)
mspec
let pkg = package pkgDesc
name = packageName pkg
when (stage `elem` [Binary,BuildDep]) $ do
missing <- missingPackages pkgDesc
pkgInstall missing (stage == Binary)
unless (stage == BuildDep) $ do
srcdir <- cmd "rpm" ["--eval", "%{_sourcedir}"]
let version = packageVersion pkg
tarFile = srcdir </> name ++ "-" ++ version ++ ".tar.gz"
tarFileExists <- doesFileExist tarFile
unless tarFileExists $ do
scmRepo <- isScmDir $ takeDirectory cabalPath
when scmRepo $
error "No tarball for source repo"
destExists <- doesDirectoryExist srcdir
unless destExists $
createDirectoryIfMissing True srcdir
copyTarball name version False srcdir
rpmbuild stage False Nothing specFile
return specFile
rpmBuild_ :: PackageData -> RpmFlags -> RpmStage -> IO ()
rpmBuild_ pkgdata flags stage =
void (rpmBuild pkgdata flags stage)
|
mathstuf/cabal-rpm
|
src/Commands/RpmBuild.hs
|
gpl-3.0
| 3,103 | 0 | 16 | 693 | 579 | 313 | 266 | 45 | 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.AndroidEnterprise.Enterprises.GenerateSignupURL
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Generates a sign-up URL.
--
-- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.enterprises.generateSignupUrl@.
module Network.Google.Resource.AndroidEnterprise.Enterprises.GenerateSignupURL
(
-- * REST Resource
EnterprisesGenerateSignupURLResource
-- * Creating a Request
, enterprisesGenerateSignupURL
, EnterprisesGenerateSignupURL
-- * Request Lenses
, egsuCallbackURL
) where
import Network.Google.AndroidEnterprise.Types
import Network.Google.Prelude
-- | A resource alias for @androidenterprise.enterprises.generateSignupUrl@ method which the
-- 'EnterprisesGenerateSignupURL' request conforms to.
type EnterprisesGenerateSignupURLResource =
"androidenterprise" :>
"v1" :>
"enterprises" :>
"signupUrl" :>
QueryParam "callbackUrl" Text :>
QueryParam "alt" AltJSON :> Post '[JSON] SignupInfo
-- | Generates a sign-up URL.
--
-- /See:/ 'enterprisesGenerateSignupURL' smart constructor.
newtype EnterprisesGenerateSignupURL = EnterprisesGenerateSignupURL'
{ _egsuCallbackURL :: Maybe Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'EnterprisesGenerateSignupURL' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'egsuCallbackURL'
enterprisesGenerateSignupURL
:: EnterprisesGenerateSignupURL
enterprisesGenerateSignupURL =
EnterprisesGenerateSignupURL'
{ _egsuCallbackURL = Nothing
}
-- | The callback URL to which the Admin will be redirected after
-- successfully creating an enterprise. Before redirecting there the system
-- will add a single query parameter to this URL named \"enterpriseToken\"
-- which will contain an opaque token to be used for the CompleteSignup
-- request. Beware that this means that the URL will be parsed, the
-- parameter added and then a new URL formatted, i.e. there may be some
-- minor formatting changes and, more importantly, the URL must be
-- well-formed so that it can be parsed.
egsuCallbackURL :: Lens' EnterprisesGenerateSignupURL (Maybe Text)
egsuCallbackURL
= lens _egsuCallbackURL
(\ s a -> s{_egsuCallbackURL = a})
instance GoogleRequest EnterprisesGenerateSignupURL
where
type Rs EnterprisesGenerateSignupURL = SignupInfo
type Scopes EnterprisesGenerateSignupURL =
'["https://www.googleapis.com/auth/androidenterprise"]
requestClient EnterprisesGenerateSignupURL'{..}
= go _egsuCallbackURL (Just AltJSON)
androidEnterpriseService
where go
= buildClient
(Proxy :: Proxy EnterprisesGenerateSignupURLResource)
mempty
|
rueshyna/gogol
|
gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Enterprises/GenerateSignupURL.hs
|
mpl-2.0
| 3,638 | 0 | 13 | 734 | 311 | 193 | 118 | 50 | 1 |
{-# 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.CognitoIdentity.DeleteIdentityPool
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Deletes a user pool. Once a pool is deleted, users will not be able to
-- authenticate with the pool.
--
-- <http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_DeleteIdentityPool.html>
module Network.AWS.CognitoIdentity.DeleteIdentityPool
(
-- * Request
DeleteIdentityPool
-- ** Request constructor
, deleteIdentityPool
-- ** Request lenses
, dip1IdentityPoolId
-- * Response
, DeleteIdentityPoolResponse
-- ** Response constructor
, deleteIdentityPoolResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.CognitoIdentity.Types
import qualified GHC.Exts
newtype DeleteIdentityPool = DeleteIdentityPool
{ _dip1IdentityPoolId :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeleteIdentityPool' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dip1IdentityPoolId' @::@ 'Text'
--
deleteIdentityPool :: Text -- ^ 'dip1IdentityPoolId'
-> DeleteIdentityPool
deleteIdentityPool p1 = DeleteIdentityPool
{ _dip1IdentityPoolId = p1
}
-- | An identity pool ID in the format REGION:GUID.
dip1IdentityPoolId :: Lens' DeleteIdentityPool Text
dip1IdentityPoolId =
lens _dip1IdentityPoolId (\s a -> s { _dip1IdentityPoolId = a })
data DeleteIdentityPoolResponse = DeleteIdentityPoolResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DeleteIdentityPoolResponse' constructor.
deleteIdentityPoolResponse :: DeleteIdentityPoolResponse
deleteIdentityPoolResponse = DeleteIdentityPoolResponse
instance ToPath DeleteIdentityPool where
toPath = const "/"
instance ToQuery DeleteIdentityPool where
toQuery = const mempty
instance ToHeaders DeleteIdentityPool
instance ToJSON DeleteIdentityPool where
toJSON DeleteIdentityPool{..} = object
[ "IdentityPoolId" .= _dip1IdentityPoolId
]
instance AWSRequest DeleteIdentityPool where
type Sv DeleteIdentityPool = CognitoIdentity
type Rs DeleteIdentityPool = DeleteIdentityPoolResponse
request = post "DeleteIdentityPool"
response = nullResponse DeleteIdentityPoolResponse
|
dysinger/amazonka
|
amazonka-cognito-identity/gen/Network/AWS/CognitoIdentity/DeleteIdentityPool.hs
|
mpl-2.0
| 3,206 | 0 | 9 | 658 | 346 | 211 | 135 | 48 | 1 |
--
-- Copyright 2017-2018 Azad Bolour
-- Licensed under GNU Affero General Public License v3.0 -
-- https://github.com/azadbolour/boardgame/blob/master/LICENSE.md
--
{-# LANGUAGE DeriveGeneric #-}
module BoardGame.Server.Domain.ServerConfig (
DeployEnv(..)
, ServerConfig(..)
, defaultServerConfig
, readServerConfig
, getServerConfig
, maxDictionaries
, dictionaryMaxMaskedLetters
) where
import Data.Aeson (FromJSON, ToJSON, toJSON)
import GHC.Generics (Generic)
import qualified Data.Yaml as Yaml
import qualified Data.Yaml.Config as YamlConf
import Bolour.Util.DbConfig (DbConfig, DbConfig(DbConfig))
import qualified Bolour.Util.DbConfig as DbConfig
-- | The deployment environment of the application.
data DeployEnv = Dev | Test | Prod
deriving (Eq, Show, Read, Generic)
instance FromJSON DeployEnv
instance ToJSON DeployEnv
-- | Maximum number of language dictionaries (different language codes that can be used).
maxDictionaries :: Int
maxDictionaries = 100
dictionaryMaxMaskedLetters :: Int
dictionaryMaxMaskedLetters = 3
-- | Configuration parameters of the application.
data ServerConfig = ServerConfig {
deployEnv :: DeployEnv
, serverPort :: Int
, maxActiveGames :: Int
, maxGameMinutes :: Int
, dictionaryDir :: String
, languageCodes :: [String]
, dbConfig :: DbConfig
} deriving (Show, Generic)
instance FromJSON ServerConfig
instance ToJSON ServerConfig
defaultAppEnv = Dev
defaultGameServerPort = 6587
defaultMaxActiveGames = 100
defaultMaxGameMinutes = 30
defaultDictionaryDir = "dict"
defaultLanguageCodes = ["en"]
-- | Default configuration parameters of the application.
defaultServerConfig :: ServerConfig
defaultServerConfig = ServerConfig
defaultAppEnv
defaultGameServerPort
defaultMaxActiveGames
defaultMaxGameMinutes
defaultDictionaryDir
defaultLanguageCodes
DbConfig.defaultPostgresDbConfig -- TODO. Use defaultDbConfig (in-memory) sqlite not postgres.
-- | Generic JSON-like representation of the default configuration.
defaultServerConfigObj :: Yaml.Value
defaultServerConfigObj = toJSON defaultServerConfig
-- | Read the configuration parameters from a configuration file
-- and use default values for parameters not present in the file.
readServerConfig :: String -> IO ServerConfig
readServerConfig configFilePath =
YamlConf.loadYamlSettings [configFilePath] [defaultServerConfigObj] YamlConf.ignoreEnv
-- | Get the application's YAML configuration parameters. If the configuration
-- file is not given or a parameter is not present in the given file,
-- the default value of the parameter is returned.
getServerConfig :: Maybe String -> IO ServerConfig
getServerConfig maybeConfigFilePath =
case maybeConfigFilePath of
Nothing -> return defaultServerConfig
Just path -> readServerConfig path
|
azadbolour/boardgame
|
haskell-server/src/BoardGame/Server/Domain/ServerConfig.hs
|
agpl-3.0
| 2,816 | 0 | 9 | 415 | 431 | 258 | 173 | 59 | 2 |
module SimpleJSON
(
JValue(..) -- .. means export that type and all its constructors
, getString
, getInt
, getDouble
, getBool
, getObject
, getArray
, isNull
) where
-- from Haskell type to JSON type
data JValue = JString String
| JNumber Double
| JBool Bool
| JNull
| JObject [(String, JValue)]
| JArray [JValue]
deriving (Eq, Ord, Show)
-- from JSON type to Haskell type
getString (JString s) = Just s
getString _ = Nothing
getInt (JNumber n) = Just (truncate n)
getInt _ = Nothing
getDouble (JNumber n) = Just n
getDouble _ = Nothing
getBool (JBool b) = Just b
getBool _ = Nothing
getObject (JObject o) = Just o
getObject _ = Nothing
getArray (JArray a) = Just a
getArray _ = Nothing
isNull v = v == JNull
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/book/2009-Real_World_Haskell/SimpleJSON.hs
|
unlicense
| 922 | 0 | 8 | 346 | 264 | 142 | 122 | 30 | 1 |
module GridPolytopes.A338885 (a338885_row) where
import Helpers.Primes (divisors)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.List (genericLength)
-- https://codegolf.stackexchange.com/q/213754/53884
a338885_row :: Integer -> [Integer]
a338885_row n = Set.toAscList $ Set.fromList factorProducts where
factorProducts = [d + (i * (n - i) `div` d) | i <- [1..n `div` 2], d <- divisors $ i * (n - i)]
a338885_list :: [Integer]
a338885_list = concatMap a338885_row [2..]
a338885 :: Int -> Integer
a338885 n = a338885_list !! (n - 2)
a338886 :: Integer -> Integer
a338886 = genericLength . a338885_row
|
peterokagey/haskellOEIS
|
src/Sandbox/Rectangles_in_rectangles.hs
|
apache-2.0
| 625 | 0 | 13 | 95 | 224 | 128 | 96 | 14 | 1 |
-- x first parameter and y second parameter
doubleUs x y = x*2 + y*2
|
tonilopezmr/Learning-Haskell
|
Functions/doubleUs.hs
|
apache-2.0
| 68 | 0 | 7 | 14 | 24 | 12 | 12 | 1 | 1 |
-- | This module contains a number of benchmarks for the different streaming
-- functions
--
-- Tested in this benchmark:
--
-- * Most streaming functions
--
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveGeneric, RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Benchmarks.Stream
( initEnv
, benchmark
) where
import Control.DeepSeq (NFData (..))
import Test.Tasty.Bench (Benchmark, bgroup, bench, nf)
import qualified Data.Text as T
import qualified Data.ByteString as B
import qualified Data.Text.Lazy as TL
import qualified Data.ByteString.Lazy as BL
import Data.Text.Internal.Fusion.Types (Step (..), Stream (..))
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as E
import qualified Data.Text.Internal.Encoding.Fusion as T
import qualified Data.Text.Internal.Encoding.Fusion.Common as F
import qualified Data.Text.Internal.Fusion as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Text.Internal.Lazy.Encoding.Fusion as TL
import qualified Data.Text.Internal.Lazy.Fusion as TL
import qualified Data.Text.Lazy.IO as TL
import GHC.Generics (Generic)
instance NFData a => NFData (Stream a) where
-- Currently, this implementation does not force evaluation of the size hint
rnf (Stream next s0 _) = go s0
where
go !s = case next s of
Done -> ()
Skip s' -> go s'
Yield x s' -> rnf x `seq` go s'
data Env = Env
{ t :: !T.Text
, utf8 :: !B.ByteString
, utf16le :: !B.ByteString
, utf16be :: !B.ByteString
, utf32le :: !B.ByteString
, utf32be :: !B.ByteString
, tl :: !TL.Text
, utf8L :: !BL.ByteString
, utf16leL :: !BL.ByteString
, utf16beL :: !BL.ByteString
, utf32leL :: !BL.ByteString
, utf32beL :: !BL.ByteString
, s :: T.Stream Char
} deriving (Generic)
instance NFData Env
initEnv :: FilePath -> IO Env
initEnv fp = do
-- Different formats
t <- T.readFile fp
let !utf8 = T.encodeUtf8 t
!utf16le = T.encodeUtf16LE t
!utf16be = T.encodeUtf16BE t
!utf32le = T.encodeUtf32LE t
!utf32be = T.encodeUtf32BE t
-- Once again for the lazy variants
tl <- TL.readFile fp
let !utf8L = TL.encodeUtf8 tl
!utf16leL = TL.encodeUtf16LE tl
!utf16beL = TL.encodeUtf16BE tl
!utf32leL = TL.encodeUtf32LE tl
!utf32beL = TL.encodeUtf32BE tl
-- For the functions which operate on streams
let !s = T.stream t
return Env{..}
benchmark :: Env -> Benchmark
benchmark ~Env{..} =
bgroup "Stream"
-- Fusion
[ bgroup "stream" $
[ bench "Text" $ nf T.stream t
, bench "LazyText" $ nf TL.stream tl
]
-- Encoding.Fusion
, bgroup "streamUtf8"
[ bench "Text" $ nf (T.streamUtf8 E.lenientDecode) utf8
, bench "LazyText" $ nf (TL.streamUtf8 E.lenientDecode) utf8L
]
, bgroup "streamUtf16LE"
[ bench "Text" $ nf (T.streamUtf16LE E.lenientDecode) utf16le
, bench "LazyText" $ nf (TL.streamUtf16LE E.lenientDecode) utf16leL
]
, bgroup "streamUtf16BE"
[ bench "Text" $ nf (T.streamUtf16BE E.lenientDecode) utf16be
, bench "LazyText" $ nf (TL.streamUtf16BE E.lenientDecode) utf16beL
]
, bgroup "streamUtf32LE"
[ bench "Text" $ nf (T.streamUtf32LE E.lenientDecode) utf32le
, bench "LazyText" $ nf (TL.streamUtf32LE E.lenientDecode) utf32leL
]
, bgroup "streamUtf32BE"
[ bench "Text" $ nf (T.streamUtf32BE E.lenientDecode) utf32be
, bench "LazyText" $ nf (TL.streamUtf32BE E.lenientDecode) utf32beL
]
-- Encoding.Fusion.Common
, bench "restreamUtf16LE" $ nf F.restreamUtf16LE s
, bench "restreamUtf16BE" $ nf F.restreamUtf16BE s
, bench "restreamUtf32LE" $ nf F.restreamUtf32LE s
, bench "restreamUtf32BE" $ nf F.restreamUtf32BE s
]
|
bos/text
|
benchmarks/haskell/Benchmarks/Stream.hs
|
bsd-2-clause
| 4,110 | 0 | 13 | 1,111 | 1,112 | 597 | 515 | 111 | 1 |
module Code.Generating.Utils.Exports (
mergeExportSpec, addExportSpec
) where
------------------------------------------------------------------------
import Data.List(union)
import Language.Haskell.Exts.Syntax
import Code.Generating.InternalUtils
------------------------------------------------------------------------
addExportSpec :: ExportSpec -> [ExportSpec] -> [ExportSpec]
addExportSpec = mergeUpdate mergeExportSpec
------------------------------------------------------------------------
-- | Tries to merge two `ExportSpec`s, when they can be merged return
-- `Just` the result else `Nothing`. Two `ExportSpec`s can be merged
-- when there is an `ExportSpec` that exports exactly as much as the two
-- different `ExportSpec`s would export together.
mergeExportSpec :: ExportSpec -> ExportSpec -> Maybe ExportSpec
mergeExportSpec e1 e2 = case (e1,e2) of
-- Easy cases
-- EVar
(EVar n1 q1, EVar n2 q2) -> onEq (n1, q1) (n2, q2) e1
-- +EAbs
(EVar _ _, EAbs _) -> Nothing
(EAbs q1 , EAbs q2) -> onEq q1 q2 e1
(EAbs _ , EVar _ _) -> Nothing
-- +EThingAll
(EThingAll q1, EThingAll q2) -> onEq q1 q2 e1
(EVar _ _, EThingAll _) -> Nothing
(EThingAll _, EVar _ _) -> Nothing
(EThingAll q1, EAbs q2) -> onEq q1 q2 e1
(EAbs q1, EThingAll q2) -> onEq q1 q2 e2
-- +EModuleContents
(EModuleContents m1, EModuleContents m2) -> onEq m1 m2 e1
(EModuleContents _, _) -> Nothing
( _, EModuleContents _) -> Nothing
-- and now the more complicated cases EThingWith
(EThingWith q1 c1, EThingWith q2 c2) -> onEq q1 q2 .
EThingWith q1 $ c1 `union` c2
(EThingWith q1 _, EAbs q2 ) -> onEq q1 q2 e1
(EAbs q1 , EThingWith q2 _) -> onEq q1 q2 e2
(EThingWith q1 _, EThingAll q2 ) -> onEq q1 q2 e2
(EThingAll q1 , EThingWith q2 _) -> onEq q1 q2 e1
-- don't attempt to merge EVars, though it might be possible
(EThingWith _ _, EVar _ _) -> Nothing
(EVar _ _, EThingWith _ _) -> Nothing
------------------------------------------------------------------------
|
Laar/CodeGenerating
|
src/Code/Generating/Utils/Exports.hs
|
bsd-3-clause
| 2,180 | 0 | 11 | 535 | 589 | 309 | 280 | 29 | 19 |
-- |
-- Module: $Header$
-- Description: Find and execute external subcommands.
-- Copyright: (c) 2018-2020 Peter Trško
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: experimental
-- Portability: GHC specific language extensions.
--
-- Find and execute external subcommands.
module CommandWrapper.Toolset.ExternalSubcommand
( Command
, run
, executeCommand
, executeCommandWith
, findSubcommands
-- * Utilities
, getSubcommandConfigPathToEdit
)
where
import Control.Applicative (pure)
import Control.Exception (onException)
import Control.Monad ((>>=), filterM)
import Data.Bool (Bool(False, True), otherwise)
import Data.Foldable (length)
import Data.Function ((.), ($))
import Data.Functor ((<$>), (<&>), fmap)
import qualified Data.List as List (drop, isPrefixOf, nub)
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NonEmpty (toList)
import Data.Maybe (Maybe(Just, Nothing), catMaybes, listToMaybe, maybe)
import Data.Semigroup ((<>))
import Data.String (String, fromString)
import Data.Traversable (mapM)
import System.Exit (ExitCode(ExitFailure), exitWith)
import System.IO (FilePath, IO, stderr)
import Text.Show (show)
import Data.Text.Prettyprint.Doc (pretty, (<+>))
import qualified Data.Text.Prettyprint.Doc as Pretty (colon)
import qualified Data.Text.Prettyprint.Doc.Util as Pretty (reflow)
import qualified Mainplate (ExternalCommand(..))
import System.Directory
( doesDirectoryExist
, doesFileExist
, executable
, findExecutablesInDirectories
, getPermissions
, listDirectory
)
import System.FilePath ((</>), (<.>), takeFileName)
import System.Posix.Process (executeFile)
import qualified CommandWrapper.Core.Environment as Environment
( AppNames(AppNames, exePath, names, usedName)
, Params
( Params
, colour
, config
, exePath
, name
, subcommand
, verbosity
, version
)
, commandWrapperEnv
, getEnv
, mkEnvVars
, subcommandProtocolVersion
)
import CommandWrapper.Core.Message
( debugMsg
, dieUnableToExecuteSubcommand
, dieUnableToFindSubcommandExecutable
, errorMsg
)
import qualified CommandWrapper.Toolset.Config.Global as Global
( Config(Config, colourOutput, configPaths, verbosity)
, ConfigPaths(ConfigPaths, local, system, user)
, getSearchPath
)
type Command = Mainplate.ExternalCommand
run :: Environment.AppNames -> Command -> Global.Config -> IO ()
run appNames (Mainplate.ExternalCommand command arguments) config =
executeCommand appNames config command arguments
executeCommand
:: Environment.AppNames
-- ^ Names and paths under which this instance of @command-wrapper@ is
-- known.
-> Global.Config
-> String
-- ^ Subcommand name.
-> [String]
-- ^ Command line arguments passed to the subcommand.
-> IO a
executeCommand = executeCommandWith executeFile
executeCommandWith
:: (FilePath -> Bool -> [String] -> Maybe [(String, String)] -> IO a)
-- ^ Use this function to execute the subcommand, if found.
-> Environment.AppNames
-- ^ Names and paths under which this instance of @command-wrapper@ is
-- known.
-> Global.Config
-> String
-- ^ Subcommand name.
-> [String]
-- ^ Command line arguments passed to the subcommand.
-> IO a
executeCommandWith f appNames globalConfig subcommand arguments =
findSubcommandExecutable globalConfig usedName commands >>= \case
Nothing ->
dieUnableToFindSubcommandExecutable (fromString usedName) verbosity
colourOutput stderr (fromString subcommand)
Just (prefix, command, executable) -> do
debugMsg (fromString usedName) verbosity colourOutput stderr
$ "Trying to execute: " <> fromString (show executable)
extraEnvVars <- Environment.mkEnvVars <$> getParams prefix command
currentEnv <- Environment.getEnv
let -- When combining environments with '<>' the first environment
-- has precedence if the key is in both. If our environment
-- already contains Command Wrapper environment variables we
-- need to override them.
envBuilder = extraEnvVars <> currentEnv
env = Environment.commandWrapperEnv appNames envBuilder
f executable False arguments (Just env)
`onException` dieUnableToExecuteSubcommand
(fromString usedName) verbosity colourOutput stderr
(fromString subcommand) (fromString executable)
where
commands = commandNames appNames subcommand
Environment.AppNames{exePath, usedName} = appNames
Global.Config{colourOutput, configPaths, verbosity} = globalConfig
getParams prefix command = do
config
<- getSubcommandConfigPath' appNames configPaths prefix command
False
pure Environment.Params
{ exePath
, name = usedName
, subcommand
, config =
-- TODO: We should put contents of the file in here. See
-- Subcommand Protocol for details.
maybe "" fromString config
, verbosity
, colour = colourOutput
, version = Environment.subcommandProtocolVersion
}
-- | Find configuration file for a subcommand. This function fails if there
-- is no such subcommand, even if there is a configuration file that could
-- potentially be what user was referring to.
getSubcommandConfigPathToEdit
:: Environment.AppNames
-> Global.Config
-> String
-- ^ Subcommand name.
-> IO FilePath
getSubcommandConfigPathToEdit appNames globalConfig subcommand =
findSubcommandExecutable globalConfig usedName commands >>= \case
Nothing ->
dieUnableToFindSubcommandExecutable (fromString usedName) verbosity
colourOutput stderr (fromString subcommand)
Just (prefix, command, _executable) -> do
config
<- getSubcommandConfigPath' appNames configPaths prefix command
True
case config of
Just file -> do
debugMsg (fromString usedName) verbosity colourOutput stderr
( pretty subcommand <> Pretty.colon
<+> Pretty.reflow "Subcommand config found:"
<+> fromString (show file)
)
pure file
Nothing -> do
errorMsg (fromString usedName) verbosity colourOutput stderr
( pretty subcommand <> Pretty.colon
<+> Pretty.reflow "Unable to find configuration file\
\ for this subcommand."
)
exitWith (ExitFailure 1)
where
commands = commandNames appNames subcommand
Environment.AppNames{usedName} = appNames
Global.Config{colourOutput, verbosity, configPaths} = globalConfig
getSubcommandConfigPath'
:: Environment.AppNames
-> Global.ConfigPaths
-> String
-- ^ Prefix of subcommand executable name.
-> String
-- ^ Subcommand executable name.
-> Bool
-- ^ If 'True' then the purpose is to edit the file, i.e. we want to
-- provide result even if the configuration file doesn't exists so that it
-- can be created.
-> IO (Maybe FilePath)
getSubcommandConfigPath'
Environment.AppNames{usedName}
Global.ConfigPaths{local, system, user}
_prefix
command
isForEditing = do
-- TODO: For some external subcommands it would be useful if we could
-- fallback to (prefix </> command <.> "dhall")
--
-- For example if we file '${config}/yx/command-wrapper-cd.dhall' is
-- missing then we could default to
-- '${config}/command-wrapper/command-wrapper-cd.dhall'.
--
-- TODO: There is a lot of open questions on how to handle subcommand
-- config files properly. Especially if subcommands want allow coexistence
-- of multiple configuration files.
let systemConfig = system <&> \dir ->
dir </> usedName </> command <.> "dhall"
userConfig = user </> usedName </> command <.> "dhall"
localConfig = local <&> \dir ->
dir </> usedName </> command <.> "dhall"
haveSystemConfig <- maybe (pure False) doesFileExist systemConfig
haveUserConfig <- doesFileExist userConfig
haveLocalConfig <- maybe (pure False) doesFileExist localConfig
pure if
| haveLocalConfig ->
localConfig
| haveUserConfig ->
Just userConfig
| haveSystemConfig ->
systemConfig
| isForEditing, Just _ <- localConfig ->
localConfig
| isForEditing ->
Just userConfig
| otherwise ->
Nothing
-- | Possible executable names for an external subcommand.
commandNames
:: Environment.AppNames
-> String
-- ^ External subcommand that we are looking for.
-> NonEmpty (String, String)
-- ^ List of possible subcommand executable names. First element of the
-- tuple is prefix (name under which this toolset is known) and the second
-- one is external subcommand executable name associated with that prefix.
commandNames Environment.AppNames{names} subcommand =
names <&> \prefix ->
(prefix, prefix <> "-" <> subcommand)
findSubcommandExecutable
:: Global.Config
-> String
-> NonEmpty (String, String)
-> IO (Maybe (String, String, FilePath))
findSubcommandExecutable config usedName subcommands = do
searchPath <- Global.getSearchPath config
debugMsg (fromString usedName) verbosity colourOutput stderr
$ "Using following subcommand executable search path: "
<> fromString (show searchPath)
loop searchPath (NonEmpty.toList subcommands)
where
loop searchPath = \case
[] -> pure Nothing
(prefix, subcommand) : untriedSubcommands ->
findSubcommandExecutable' searchPath subcommand >>= \case
r@(Just _) -> pure ((prefix, subcommand, ) <$> r)
Nothing -> loop searchPath untriedSubcommands
findSubcommandExecutable' searchPath =
fmap listToMaybe . findExecutablesInDirectories searchPath
Global.Config{verbosity, colourOutput} = config
-- | Find all (unique) external subcommands.
findSubcommands :: Environment.AppNames -> Global.Config -> IO [String]
findSubcommands Environment.AppNames{Environment.names} config = do
searchPath <- Global.getSearchPath config
executablesToSubcommands <$> mapM listDirectoryExecutables searchPath
where
prefixes :: NonEmpty String
prefixes = (<> "-") <$> names
listDirectoryExecutables :: FilePath -> IO [FilePath]
listDirectoryExecutables dir = do
directoryExists <- doesDirectoryExist dir
if directoryExists
then listDirectory dir >>= filterM (`isExecutableIn` dir)
else pure []
isExecutableIn :: FilePath -> FilePath -> IO Bool
isExecutableIn file dir = executable <$> getPermissions (dir </> file)
executablesToSubcommands :: [[FilePath]] -> [String]
executablesToSubcommands =
List.nub . (>>= (>>= executableToSubcommand))
executableToSubcommand :: FilePath -> [String]
executableToSubcommand filePath =
catMaybes $ matchSubcommand fileName <$> NonEmpty.toList prefixes
where
fileName = takeFileName filePath
matchSubcommand :: String -> String -> Maybe String
matchSubcommand fileName prefix =
if prefix `List.isPrefixOf` fileName
then Just $ List.drop (length prefix) fileName
else Nothing
|
trskop/command-wrapper
|
command-wrapper/src/CommandWrapper/Toolset/ExternalSubcommand.hs
|
bsd-3-clause
| 11,889 | 80 | 21 | 3,103 | 2,204 | 1,258 | 946 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Language.CFamily.Data
-- Copyright : (c) 2008 Benedikt Huber
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : ghc
--
-- Common data types for Language.C: Identifiers, unique names, source code locations,
-- ast node attributes and extensible errors.
-----------------------------------------------------------------------------
module Language.CFamily.Data (
module Language.CFamily.Data.Error,
module Language.CFamily.Data.Ident,
module Language.CFamily.Data.InputStream,
module Language.CFamily.Data.Name,
module Language.CFamily.Data.Node,
module Language.CFamily.Data.Position,
module Language.CFamily.Data.RList
)
where
import Language.CFamily.Data.Error
import Language.CFamily.Data.Ident
import Language.CFamily.Data.InputStream
import Language.CFamily.Data.Name
import Language.CFamily.Data.Node
import Language.CFamily.Data.Position
import Language.CFamily.Data.RList
|
micknelso/language-c
|
src/Language/CFamily/OldData.hs
|
bsd-3-clause
| 1,084 | 0 | 5 | 136 | 126 | 95 | 31 | 15 | 0 |
-- |
-- Module: Data.Aeson
-- Copyright: (c) 2011-2015 Bryan O'Sullivan
-- (c) 2011 MailRank, Inc.
-- License: Apache
-- Maintainer: Bryan O'Sullivan <[email protected]>
-- Stability: experimental
-- Portability: portable
--
-- Types and functions for working efficiently with JSON data.
--
-- (A note on naming: in Greek mythology, Aeson was the father of Jason.)
module Data.Aeson
(
-- * How to use this library
-- $use
-- ** Writing instances by hand
-- $manual
-- ** Working with the AST
-- $ast
-- ** Decoding to a Haskell value
-- $haskell
-- ** Decoding a mixed-type object
-- $mixed
-- * Encoding and decoding
-- $encoding_and_decoding
decode
, decode'
, eitherDecode
, eitherDecode'
, encode
-- ** Variants for strict bytestrings
, decodeStrict
, decodeStrict'
, eitherDecodeStrict
, eitherDecodeStrict'
-- * Core JSON types
, Value(..)
, Encoding
, fromEncoding
, Array
, Object
-- * Convenience types
, DotNetTime(..)
-- * Type conversion
, FromJSON(..)
, Result(..)
, fromJSON
, ToJSON(..)
, KeyValue(..)
-- ** Generic JSON classes
, GFromJSON(..)
, GToJSON(..)
, genericToJSON
, genericToEncoding
, genericParseJSON
-- * Inspecting @'Value's@
, withObject
, withText
, withArray
, withNumber
, withScientific
, withBool
-- * Constructors and accessors
, Series
, pairs
, foldable
, (.:)
, (.:?)
, (.!=)
, object
-- * Parsing
, json
, json'
) where
import Data.Aeson.Encode (encode)
import Data.Aeson.Parser.Internal (decodeWith, decodeStrictWith,
eitherDecodeWith, eitherDecodeStrictWith,
jsonEOF, json, jsonEOF', json')
import Data.Aeson.Types
import Data.Aeson.Types.Internal (JSONPath, formatError)
import Data.Aeson.Types.Instances (ifromJSON)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
-- | Efficiently deserialize a JSON value from a lazy 'L.ByteString'.
-- If this fails due to incomplete or invalid input, 'Nothing' is
-- returned.
--
-- The input must consist solely of a JSON document, with no trailing
-- data except for whitespace.
--
-- This function parses immediately, but defers conversion. See
-- 'json' for details.
decode :: (FromJSON a) => L.ByteString -> Maybe a
decode = decodeWith jsonEOF fromJSON
{-# INLINE decode #-}
-- | Efficiently deserialize a JSON value from a strict 'B.ByteString'.
-- If this fails due to incomplete or invalid input, 'Nothing' is
-- returned.
--
-- The input must consist solely of a JSON document, with no trailing
-- data except for whitespace.
--
-- This function parses immediately, but defers conversion. See
-- 'json' for details.
decodeStrict :: (FromJSON a) => B.ByteString -> Maybe a
decodeStrict = decodeStrictWith jsonEOF fromJSON
{-# INLINE decodeStrict #-}
-- | Efficiently deserialize a JSON value from a lazy 'L.ByteString'.
-- If this fails due to incomplete or invalid input, 'Nothing' is
-- returned.
--
-- The input must consist solely of a JSON document, with no trailing
-- data except for whitespace.
--
-- This function parses and performs conversion immediately. See
-- 'json'' for details.
decode' :: (FromJSON a) => L.ByteString -> Maybe a
decode' = decodeWith jsonEOF' fromJSON
{-# INLINE decode' #-}
-- | Efficiently deserialize a JSON value from a lazy 'L.ByteString'.
-- If this fails due to incomplete or invalid input, 'Nothing' is
-- returned.
--
-- The input must consist solely of a JSON document, with no trailing
-- data except for whitespace.
--
-- This function parses and performs conversion immediately. See
-- 'json'' for details.
decodeStrict' :: (FromJSON a) => B.ByteString -> Maybe a
decodeStrict' = decodeStrictWith jsonEOF' fromJSON
{-# INLINE decodeStrict' #-}
eitherFormatError :: Either (JSONPath, String) a -> Either String a
eitherFormatError = either (Left . uncurry formatError) Right
{-# INLINE eitherFormatError #-}
-- | Like 'decode' but returns an error message when decoding fails.
eitherDecode :: (FromJSON a) => L.ByteString -> Either String a
eitherDecode = eitherFormatError . eitherDecodeWith jsonEOF ifromJSON
{-# INLINE eitherDecode #-}
-- | Like 'decodeStrict' but returns an error message when decoding fails.
eitherDecodeStrict :: (FromJSON a) => B.ByteString -> Either String a
eitherDecodeStrict =
eitherFormatError . eitherDecodeStrictWith jsonEOF ifromJSON
{-# INLINE eitherDecodeStrict #-}
-- | Like 'decode'' but returns an error message when decoding fails.
eitherDecode' :: (FromJSON a) => L.ByteString -> Either String a
eitherDecode' = eitherFormatError . eitherDecodeWith jsonEOF' ifromJSON
{-# INLINE eitherDecode' #-}
-- | Like 'decodeStrict'' but returns an error message when decoding fails.
eitherDecodeStrict' :: (FromJSON a) => B.ByteString -> Either String a
eitherDecodeStrict' =
eitherFormatError . eitherDecodeStrictWith jsonEOF' ifromJSON
{-# INLINE eitherDecodeStrict' #-}
-- $use
--
-- This section contains basic information on the different ways to
-- work with data using this library. These range from simple but
-- inflexible, to complex but flexible.
--
-- The most common way to use the library is to define a data type,
-- corresponding to some JSON data you want to work with, and then
-- write either a 'FromJSON' instance, a to 'ToJSON' instance, or both
-- for that type.
--
-- For example, given this JSON data:
--
-- > { "name": "Joe", "age": 12 }
--
-- we create a matching data type:
--
-- > {-# LANGUAGE DeriveGeneric #-}
-- >
-- > import GHC.Generics
-- >
-- > data Person = Person {
-- > name :: Text
-- > , age :: Int
-- > } deriving (Generic, Show)
--
-- The @LANGUAGE@ pragma and 'Generic' instance let us write empty
-- 'FromJSON' and 'ToJSON' instances for which the compiler will
-- generate sensible default implementations.
--
-- > instance ToJSON Person
-- > instance FromJSON Person
--
-- We can now encode a value like so:
--
-- > >>> encode (Person {name = "Joe", age = 12})
-- > "{\"name\":\"Joe\",\"age\":12}"
-- $manual
--
-- When necessary, we can write 'ToJSON' and 'FromJSON' instances by
-- hand. This is valuable when the JSON-on-the-wire and Haskell data
-- are different or otherwise need some more carefully managed
-- translation. Let's revisit our JSON data:
--
-- > { "name": "Joe", "age": 12 }
--
-- We once again create a matching data type, without bothering to add
-- a 'Generic' instance this time:
--
-- > data Person = Person {
-- > name :: Text
-- > , age :: Int
-- > } deriving Show
--
-- To decode data, we need to define a 'FromJSON' instance:
--
-- > {-# LANGUAGE OverloadedStrings #-}
-- >
-- > instance FromJSON Person where
-- > parseJSON (Object v) = Person <$>
-- > v .: "name" <*>
-- > v .: "age"
-- > -- A non-Object value is of the wrong type, so fail.
-- > parseJSON _ = empty
--
-- We can now parse the JSON data like so:
--
-- > >>> decode "{\"name\":\"Joe\",\"age\":12}" :: Maybe Person
-- > Just (Person {name = "Joe", age = 12})
--
-- To encode data, we need to define a 'ToJSON' instance:
--
-- > instance ToJSON Person where
-- > -- this generates a Value
-- > toJSON (Person name age) =
-- > object ["name" .= name, "age" .= age]
-- >
-- > -- this encodes directly to a ByteString Builder
-- > toEncoding (Person name age) =
-- > pairs $ "name" .= name <> "age" .= age
--
-- We can now encode a value like so:
--
-- > >>> encode (Person {name = "Joe", age = 12})
-- > "{\"name\":\"Joe\",\"age\":12}"
--
-- There are predefined 'FromJSON' and 'ToJSON' instances for many
-- types. Here's an example using lists and 'Int's:
--
-- > >>> decode "[1,2,3]" :: Maybe [Int]
-- > Just [1,2,3]
--
-- And here's an example using the 'Data.Map.Map' type to get a map of
-- 'Int's.
--
-- > >>> decode "{\"foo\":1,\"bar\":2}" :: Maybe (Map String Int)
-- > Just (fromList [("bar",2),("foo",1)])
-- While the notes below focus on decoding, you can apply almost the
-- same techniques to /encoding/ data. (The main difference is that
-- encoding always succeeds, but decoding has to handle the
-- possibility of failure, where an input doesn't match our
-- expectations.)
--
-- See the documentation of 'FromJSON' and 'ToJSON' for some examples
-- of how you can automatically derive instances in many common
-- circumstances.
-- $ast
--
-- Sometimes you want to work with JSON data directly, without first
-- converting it to a custom data type. This can be useful if you want
-- to e.g. convert JSON data to YAML data, without knowing what the
-- contents of the original JSON data was. The 'Value' type, which is
-- an instance of 'FromJSON', is used to represent an arbitrary JSON
-- AST (abstract syntax tree). Example usage:
--
-- > >>> decode "{\"foo\": 123}" :: Maybe Value
-- > Just (Object (fromList [("foo",Number 123)]))
--
-- > >>> decode "{\"foo\": [\"abc\",\"def\"]}" :: Maybe Value
-- > Just (Object (fromList [("foo",Array (fromList [String "abc",String "def"]))]))
--
-- Once you have a 'Value' you can write functions to traverse it and
-- make arbitrary transformations.
-- $haskell
--
-- We can decode to any instance of 'FromJSON':
--
-- > λ> decode "[1,2,3]" :: Maybe [Int]
-- > Just [1,2,3]
--
-- Alternatively, there are instances for standard data types, so you
-- can use them directly. For example, use the 'Data.Map.Map' type to
-- get a map of 'Int's.
--
-- > λ> import Data.Map
-- > λ> decode "{\"foo\":1,\"bar\":2}" :: Maybe (Map String Int)
-- > Just (fromList [("bar",2),("foo",1)])
-- $mixed
--
-- The above approach with maps of course will not work for mixed-type
-- objects that don't follow a strict schema, but there are a couple
-- of approaches available for these.
--
-- The 'Object' type contains JSON objects:
--
-- > λ> decode "{\"name\":\"Dave\",\"age\":2}" :: Maybe Object
-- > Just (fromList) [("name",String "Dave"),("age",Number 2)]
--
-- You can extract values from it with a parser using 'parse',
-- 'parseEither' or, in this example, 'parseMaybe':
--
-- > λ> do result <- decode "{\"name\":\"Dave\",\"age\":2}"
-- > flip parseMaybe result $ \obj -> do
-- > age <- obj .: "age"
-- > name <- obj .: "name"
-- > return (name ++ ": " ++ show (age*2))
-- >
-- > Just "Dave: 4"
--
-- Considering that any type that implements 'FromJSON' can be used
-- here, this is quite a powerful way to parse JSON. See the
-- documentation in 'FromJSON' for how to implement this class for
-- your own data types.
--
-- The downside is that you have to write the parser yourself; the
-- upside is that you have complete control over the way the JSON is
-- parsed.
-- $encoding_and_decoding
--
-- Decoding is a two-step process.
--
-- * When decoding a value, the process is reversed: the bytes are
-- converted to a 'Value', then the 'FromJSON' class is used to
-- convert to the desired type.
--
-- There are two ways to encode a value.
--
-- * Convert to a 'Value' using 'toJSON', then possibly further
-- encode. This was the only method available in aeson 0.9 and
-- earlier.
--
-- * Directly encode (to what will become a 'L.ByteString') using
-- 'toEncoding'. This is much more efficient (about 3x faster, and
-- less memory intensive besides), but is only available in aeson
-- 0.10 and newer.
--
-- For convenience, the 'encode' and 'decode' functions combine both
-- steps.
|
nurpax/aeson
|
Data/Aeson.hs
|
bsd-3-clause
| 11,643 | 0 | 8 | 2,441 | 862 | 619 | 243 | 80 | 1 |
{-# LANGUAGE UndecidableInstances, FlexibleContexts, MultiWayIf #-}
module SearchTree where
import Control.Monad
import Control.Monad.Trans.Class
import Control.Applicative
import Data.Maybe
data Tree a = Node [Tree a] | Leaf a deriving (Show, Eq)
instance Functor Tree where
fmap = liftM
instance Applicative Tree where
pure = return
(<*>) = ap
instance Monad Tree where
return = Leaf
Leaf a >>= f = f a
Node ls >>= f = Node $ map (>>=f) ls
toList :: Tree a -> [a]
toList (Leaf a) = [a]
toList (Node ls) = concatMap toList ls
getbranches :: Tree a -> [Tree a]
getbranches (Leaf a) = [Leaf a]
getbranches (Node as) = as
instance Alternative Tree where
empty = mzero
(<|>) = mplus
instance MonadPlus Tree where
mzero = Node []
mplus a@(Leaf _) b = Node $ a : getbranches b
mplus (Node as) b = Node $ as ++ getbranches b
newtype TreeT m a = TreeT {run :: m (Tree a)} --TODO renam run
instance Monad m => Functor (TreeT m) where
fmap = liftM
instance Monad m => Applicative (TreeT m ) where
pure = return
(<*>) = ap
instance Monad m => Monad (TreeT m) where
return = TreeT . return . return
m >>= f = TreeT $ run m >>= \ a ->
case a of
Leaf l -> run (f l)
Node ls -> Node <$> mapM (run . (>>= f) . TreeT . return) ls
instance MonadTrans TreeT where
lift = TreeT . fmap return
instance Monad m => Alternative (TreeT m) where
empty = mzero
(<|>) = mplus
instance Monad m => MonadPlus (TreeT m ) where
mzero = TreeT $ return $ Node []
mplus ma mb = TreeT $ liftM2 mplus (run ma) (run mb)
toListT :: Functor m => TreeT m a -> m [a]
toListT tree = toList <$> run tree
newtype SearchTree m a = Search {search :: TreeT m (Maybe a)}
instance Eq (m (Tree (Maybe a))) => Eq (SearchTree m a) where
(Search (TreeT a)) == (Search (TreeT b)) = a == b
instance Show (m (Tree (Maybe a))) => Show (SearchTree m a) where
show (Search (TreeT a)) = show a
instance Monad m => Functor (SearchTree m) where
fmap = liftM
instance Monad m => Applicative (SearchTree m ) where
pure = return
(<*>) = ap
instance Monad m => Monad (SearchTree m) where
return = Search . return . Just
m >>= f = Search $ TreeT $ (run . search) m >>= \ a ->
case a of
Leaf l -> case l of
Nothing -> return $ Leaf Nothing
Just l' -> run . search $ f l'
Node ls -> Node <$> mapM (run . search . (>>= f) . Search . TreeT . return) ls
instance MonadTrans SearchTree where
lift = Search . TreeT . fmap (return . Just)
instance Monad m => Alternative (SearchTree m) where
empty = mzero
(<|>) = mplus
instance Monad m => MonadPlus (SearchTree m ) where
mzero = Search $ TreeT $ return $ Leaf Nothing
mplus ma mb = Search $ TreeT $ liftM2 mplus (run $ search ma) (run $ search mb)
foundT :: Functor m => SearchTree m a -> m [a]
foundT tree = catMaybes <$> toListT ( search tree)
pruneT :: Functor m => Int -> SearchTree m a -> m [a]
pruneT maxfailures = fmap (prune maxfailures ) . run . search
-- try redo depth search from lowest depth upward
-- try till a number of fails, then jumpback
-- if depth > highest depth then jump to depth - 1
-- if previous jumpback depth > depth jump to depth - 1
-- otherwise jump back to previous jumpback point - 1
prune :: Int -> Tree (Maybe a ) -> [a]
prune maxfailures = go [] 0 (100000000,0)
where
failure :: [Tree (Maybe a)] -> Int ->(Int,Int) -> [a]
failure stack failures bounds@(previousJumpDepth,highestDepth) =
let depth = length stack
in if failures + 1 >= maxfailures
then if
|depth > highestDepth -> jumpback 1 stack (depth-1 ,depth)
-- depth < previousJumpDepth -> jumpback 1 stack (depth-1 ,depth)
-- this already happend because a negative jumpback is a next
|otherwise -> jumpback (depth - previousJumpDepth +1 ) stack (previousJumpDepth-1,highestDepth)
else next stack (failures + 1) bounds
jumpback :: Int -> [Tree (Maybe a)] -> (Int, Int) -> [a]
jumpback jumps stack bounds = next (drop jumps stack) 0 bounds
next [] _ _ = []
next (nextTry : rest) failures bounds = go rest failures bounds nextTry
go :: [Tree (Maybe a)] -> Int -> (Int,Int) -> Tree (Maybe a) -> [a]
go stack failures bounds tree = case tree of
(Leaf Nothing) -> failure stack failures bounds
(Leaf (Just a)) -> a : next stack 0 bounds
(Node []) -> next stack failures bounds
(Node (l : ls)) -> go (Node ls : stack) failures bounds l
|
kwibus/myLang
|
tests/SearchTree.hs
|
bsd-3-clause
| 4,611 | 0 | 18 | 1,233 | 1,880 | 963 | 917 | 101 | 7 |
{-# LANGUAGE TemplateHaskell #-}
-- | Static files.
module HL.Static where
import Control.Monad.IO.Class
import Yesod.Static
staticFiles "static/"
-- | Get the directory for static files. In development returns the
-- local copy, in production mode uses the Cabal data-files
-- functionality.
getStaticDir :: MonadIO m => m FilePath
getStaticDir =
return "static/"
|
haskell-lang/haskell-lang
|
src/HL/Static.hs
|
bsd-3-clause
| 372 | 0 | 6 | 59 | 52 | 30 | 22 | 8 | 1 |
{-# LANGUAGE CPP #-}
------------------------------------------------------------------------
-- © 1998 Peter Thiemann
-- some default settings
--
module Defaults (afmPathDefault, ebnfInputDefault, rgbPathDefault)
where
afmPathDefault = [
#include "afmpath.h"
, "/usr/local/tex/lib/TeXPS/afm"]
ebnfInputDefault = ["."]
rgbPathDefault = [
#include "rgbpath.h"
, "/usr/X11R6/lib/X11"]
|
FranklinChen/Ebnf2ps
|
src/Defaults.hs
|
bsd-3-clause
| 441 | 6 | 5 | 96 | 52 | 35 | 17 | -1 | -1 |
{-
Problem 15
How many routes are there through a 20*20 grid?
Result
137846528820
0.00 s
Comment
To traverse the 20*20 grid, one has to take 20 steps right and
another 20 down. The problem thus reduces in "how many different
ways are there to arrange right and down", which is simply the
binomial coefficient.
-}
module Problem15 (solution) where
import CommonFunctions
solution = (20 + 20) `choose` 20
|
quchen/HaskellEuler
|
src/Problem15.hs
|
bsd-3-clause
| 508 | 0 | 7 | 174 | 31 | 20 | 11 | 3 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Prelude hiding ((+),(-),(*),(==))
import Verbal
import System.Environment (getArgs)
import Data.String (fromString)
-- for ghci
-- :set -XOverloadedStrings
test1 = print $ findConditions $ "debt" + "star" == "death"
test2 = print $ findConditions $ "send" + "more" == "money"
test3 = do
ex1:ex2:ex3:_ <- getArgs
print $ findConditions $ fromString ex1 + fromString ex2 == fromString ex3
test4 = print $ findConditions $ "debt + star = death"
test5 = print $ findConditions $ "send + more = money"
test6 = do
equ:_ <- getArgs
print $ findConditions $ fromString equ
test7 = print $ findConditions $ "give" + "me" + "rice" == "demo"
main = test6
|
mitsuji/verbal-arithmetic
|
app/General.hs
|
bsd-3-clause
| 729 | 2 | 10 | 140 | 236 | 130 | 106 | 18 | 1 |
module Scheme.Eval.Primitives (ioPrimitives, basicPrimitives) where
import Control.Monad
import Data.Maybe
import Data.Complex as C
import Data.Ratio
import Control.Monad.Error
import Scheme.Types
import System.IO
import Scheme.Eval.DynamicTypes
prim = undefined
convert typ wrap = expect typ >=> return . wrap
foldlOnType typ f = foldM (\acc e -> if check typ e
then return (acc `f` e)
else errorNeedType typ (show e))
foldlOnType1 typ f initPrep l = do expect typ (head l)
foldlOnType typ f (initPrep $ head l) (init l)
basicPrimitives :: [(String, [LispVal] -> ThrowsErrorIO LispVal)]
basicPrimitives =
let toBool = return . Bool
dol = dottedOrPlainListType
in
-- number type checking
[ ("number?",
oneArgOnly >=> toBool . isNum)
, ("real?",
oneArgOnly >=> toBool . checkNum isDouble)
, ("rational?",
oneArgOnly >=> toBool . checkNum isRational)
, ("integer?",
oneArgOnly >=> toBool . checkNum isInt)
, ("complex?",
oneArgOnly >=> toBool . checkNum isComplex)
-- only nice rationals and integers are exact
, ("exact?",
oneArgOnly >=> \n -> toBool $ any ($n) [checkNum isRational, checkNum isInt])
-- arithmetic, preserve exactness in this order: integer, rational, float, complex
, ("+",
minArgs 2 >=> expect (listOf numType) . List >=> return . Num . sum)
, ("-",
minArgs 2 >=> expect (listOf numType) . List >=> return . Num . foldl1 (-))
, ("*",
minArgs 2 >=> expect (listOf numType) . List >=> return . Num . product)
, ("/",
onlyArgs 2 >=> \[_a, _b] -> do a <- expect numType _a
b <- expect numType _b
return . Num $ a / b)
, ("negate",
oneArgOnly >=> expect numType >=> return . Num . negate)
, ("signum",
oneArgOnly >=> expect numType >=> return . Num . signum)
, ("abs",
oneArgOnly >=> expect numType >=> return . Num . abs)
, ("recip",
oneArgOnly >=> expect numType >=> return . Num . recip)
-- integer arithmetic functions
, ("mod",
minArgs 2 >=> foldlOnType1 numIntType (\(Num (Int a)) (Num (Int b))
-> Num . Int $ a `mod` b) id)
, ("quotient",
minArgs 2 >=> foldlOnType1 numIntType (\(Num (Int a)) (Num (Int b))
-> Num . Int $ a `quot` b) id)
, ("remainder",
minArgs 2 >=> foldlOnType1 numIntType (\(Num (Int a)) (Num (Int b))
-> Num . Int $ a `rem` b) id)
-- boolean
, ("boolean?", oneArgOnly >=> toBool . isBool)
, ("&&",
minArgs 1 >=> liftM Bool . foldlOnType boolType (\a b -> a && fromJust (getBool b)) True)
, ("||",
minArgs 1 >=> liftM Bool . foldlOnType boolType (\a b -> a || fromJust (getBool b)) False)
-- list processing !
, ("list?",
oneArgOnly >=> \l -> toBool $ any ($l) [isList, isDottedList, isVector])
, ("dottedlist?",
oneArgOnly >=> toBool . isDottedList)
, ("car",
oneArgOnly >=> expect dol >=> return .
(return . either id fst >=> safeHead)
>=> maybe (throwError $ Default "head-less list given to car") return)
, ("cdr",
oneArgOnly >=> expect dol >=> return .
--extract the dotted/normal list
either (liftM List . safeTail)
-- handle two cases for dotted lists
(\(xs, dot) -> Just $ if null xs then dot else DottedList (tail xs) dot)
-- handle bad tail
>=> maybe (throwError $ Default "tail-less list given to cdr") return)
, ("cons", onlyArgs 2 >=> (\(a:b:[]) ->
maybe (return $ List [a,b]) return
(get dol b >>= either (Just . List . (a:)) (\(xs, dot) -> Just $ DottedList (a:xs) dot))
))
, ("vector?",
oneArgOnly >=> toBool . isVector)
, ("vector-ref", prim)
, ("vector-set", prim)
, ("list->vector",
oneArgOnly >=> prim)
, ("vector->list",
oneArgOnly >=> prim)
-- symbol processing
, ("symbol?",
oneArgOnly >=> toBool . isAtom)
, ("string->symbol",
oneArgOnly >=> convert stringType Atom)
, ("symbol->string",
oneArgOnly >=> convert atomType String)
-- string processing
, ("string?",
oneArgOnly >=> toBool . isString)
, ("string-ref",
onlyArgs 2 >=> \([lispstr, lispix]) -> do
str <- expect stringType lispstr
ix <- expect numIntType lispix
char <- maybe (throwError $ BadExpr "index out of bounds" lispix) return (safeIndex (fromIntegral ix) str)
return . Character $ char)
-- string construction
, ("string->list",
oneArgOnly >=> convert stringType (List . map Character))
, ("list->string",
convert (listOf charType) String . List)
-- characters
, ("character?",
oneArgOnly >=> toBool . isCharacter)
, ("character=", minArgs 1 >=> liftM (Bool . fst) . foldlOnType charType (\(res, prev) c -> (isNothing prev || getCharacter c == prev, getCharacter c)) (True, Nothing))
-- equivalence
, ("eq?", onlyArgs 2 >=> return . eqv)
, ("eqv?", onlyArgs 2 >=> return . eqv)
, ("=", onlyArgs 2 >=> return . eqv)
, ("equal?", onlyArgs 2 >=> return . equal)
, ("==", onlyArgs 2 >=> return . equal)
]
ioPrimitives =
[ ("open-input-file", oneArgOnly >=> expect stringType >=> makePort ReadMode)
, ("open-output-file", oneArgOnly >=> expect stringType >=> makePort WriteMode)
, ("close-port", closePort)
, ("close-input-port", closePort)
, ("close-output-port", closePort)
, ("read-contents", oneArgOnly >=> expect portType >=> liftM String . liftIO . hGetContents)
, ("write", maxArgs 2 >=> minArgs 1 >=> \l -> case l of
[obj] -> safeLiftIO (print obj) >> lispNull
[obj, p] -> expect portType p >>= \port -> safeLiftIO (hPrint port (show obj)) >> lispNull)
]
closePort = oneArgOnly >=> liftIO . hClose . fromJust . getPort >=> const lispNull
makePort mode = liftM Port . safeLiftIO . flip openFile mode
eqv [a,b]
| a == List [] && a == b = Bool True
| all (\x -> check (dottedListType `orType` listType `orType` vectorType) x) [a,b] = Bool False
| otherwise = equal [a,b]
equal [a,b] = Bool $ a == b
|
hucal/SCMinHS
|
Scheme/Eval/Primitives.hs
|
bsd-3-clause
| 6,606 | 0 | 21 | 2,070 | 2,261 | 1,217 | 1,044 | -1 | -1 |
{-# LANGUAGE BangPatterns, TypeFamilies #-}
module Main where
import Control.Category
import Prelude hiding ((.), log)
import Foreign.C
import System.FilePath
import qualified Vision.Image as F hiding (mean)
import Pipes
import qualified Pipes.Prelude as P
import Control.Monad
import Data.VectorSpace
import Data.List
import System.Mem
import System.Directory
import qualified Data.Vector.Storable as V
import qualified Database.LevelDB as LDB
import Control.Monad.Trans.Resource
import HNN as HNN
mean :: (TensorDataType a) => Tensor a -> a
mean t = (sum $ toList t) / (fromIntegral $ product $ shape t)
std :: (TensorDataType a, Real a) => Tensor a -> a
std t = let m = mean t in
sqrt $ (sum $ fmap (\x -> (x - m)**2) $ toList t) / (fromIntegral $ product $ shape t)
print_stats :: (VectorSpace w, CFloat ~ Scalar w, MonadIO m)
=> Consumer (CFloat,w) m ()
print_stats = forever $ do
liftIO $ putStrLn "Waiting for weights..."
(cost, w) <- await
liftIO $ performGC
liftIO $ do
putStrLn $ "Current cost: " ++ show cost
return ()
print_info :: String -> Tensor CFloat -> GPU ()
print_info name t = liftIO $ do
putStrLn $ name ++ ": " ++ show t
putStrLn $ name ++ ": mean " ++ show (mean t) ++ ", std " ++ show (std t)
putStrLn $ name ++ ": min " ++ show (minimum $ toList t) ++ ", max " ++ show (maximum $ toList t)
grey_to_float :: (Integral a) => a -> CFloat
grey_to_float i = (fromIntegral i - 128) / 255
he_init :: [Int] -> CFloat -> GPU (Tensor CFloat)
he_init shp fan_in = normal 0 (1 / sqrt fan_in) shp
main :: IO ()
main = do
-- Attempts to load the leveldb for mnist.
-- Populates it if doesn't exist.
let train_ldb_path = "data" </> "mnist" </> "train_ldb"
test_ldb_path = "data" </> "mnist" </> "test_ldb"
train_img_path = "data" </> "mnist" </> "train"
test_img_path = "data" </> "mnist" </> "test"
putStrLn "Building training data leveldb if not existing..."
runResourceT $ runEffect
$ (load_mnist_lazy train_img_path :: Producer (F.Grey, Int) (ResourceT IO) ())
>-> makeleveldb train_ldb_path Nothing
putStrLn "Building test data leveldb if not existing..."
runResourceT $ runEffect
$ (load_mnist_lazy test_img_path :: Producer (F.Grey, Int) (ResourceT IO) ())
>-> makeleveldb test_img_path Nothing
mnist_train <- runResourceT $ LDB.open train_ldb_path LDB.defaultOptions
mnist_test <- runResourceT $ LDB.open test_ldb_path LDB.defaultOptions
let batch_size = 128
convLayer = convolution2d convolution_fwd_algo_implicit_gemm (1,1) (1,1) (1,1)
>+> activation activation_relu
>+> pooling2d pooling_max (2,2) (1,1) (2,2)
fcLayer = lreshape [batch_size,64*4]
>+> linear
>+> lreshape [batch_size,10,1,1]
>+> activation activation_relu
nnet =
transformTensor nhwc nchw
>+> convLayer
>+> convLayer
>+> convLayer
>+> convLayer
>+> fcLayer
>+> lreshape [batch_size,10]
input_shape = [batch_size,1,28,28]
cost_grad w (batch, labels) = do
let fullNet = nnet >+> mlrCost batch_size 10 -< labels
(cost, bwd) <- lift $ forwardBackward fullNet (w,batch)
let (w',_) = bwd 1
return $ (cost, w')
runGPU 42 $ do
conv_w1 <- he_init [8,1,3,3] (3*3)
conv_w2 <- he_init [16,8,3,3] (3*3*8)
conv_w3 <- he_init [32,16,3,3] (3*3*16)
conv_w4 <- he_init [64,32,3,3] (3*3*32)
fc_w <- normal 0 (1/ sqrt (64*4)) [64*4,10]
let init_weights =
HLS $ conv_w1 `HCons` conv_w2 `HCons` conv_w3 `HCons` conv_w4 `HCons` fc_w `HCons` HNil
runResourceT $ runEffect $
(leveldb_random_loader mnist_train :: Producer (F.Grey, [Int]) (ResourceT GPU) ())
>-> batch_images 10 batch_size
>-> P.map (\(b,bs,l,ls) -> (V.map (\p -> (fromIntegral p - 128) / 255 :: CFloat) b,
bs,l,ls))
>-> batch_to_gpu
>-> runMomentum 0.01 0.9 (sgd momentum cost_grad init_weights)
>-> runEvery 10 (\(c,w) -> do
liftIO $ putStrLn "saving..."
serializeTo ("data" </> "mnist" </> "model") w)
>-> P.take 20000
>-> print_stats
return ()
|
alexisVallet/hnn
|
examples/mnist/Main.hs
|
bsd-3-clause
| 4,252 | 0 | 26 | 1,063 | 1,596 | 838 | 758 | 100 | 1 |
module PFDS.Commons.Heap where
class Heap h where
empty :: Ord e => h e
isEmpty :: Ord e => h e -> Bool
insert :: Ord e => e -> h e -> h e
merge :: Ord e => h e -> h e -> h e
findMin :: Ord e => h e -> e
deleteMin :: Ord e => h e -> h e
-- impl leftist heap
data LHeap e = E | T Int e (LHeap e) (LHeap e) deriving (Show)
instance Heap LHeap where
empty = E
isEmpty E = True
isEmpty _ = False
merge h E = h
merge E h = h
merge h1@(T _ x a1 b1) h2@(T _ y a2 b2) = if x <= y
then makeT x a1 $ merge b1 h2
else makeT y a2 $ merge h1 b2
insert x = merge (T 1 x E E)
findMin E = error "Empty"
findMin (T _ x _ _) = x
deleteMin E = error "Empty"
deleteMin (T _ _ a b) = merge a b
-- 補助関数
rank :: LHeap e -> Int
rank E = 0
rank (T r _ _ _) = r
makeT :: e -> LHeap e -> LHeap e -> LHeap e
makeT x' a b = if rank a >= rank b
then T (rank b + 1) x' a b
else T (rank a + 1) x' b a
|
matonix/pfds
|
src/PFDS/Commons/Heap.hs
|
bsd-3-clause
| 934 | 0 | 10 | 298 | 539 | 265 | 274 | 30 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.