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
{-# 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.ServiceUser.Projects.Services.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- List enabled services for the specified consumer. -- -- /See:/ <https://cloud.google.com/service-management/ Service User API Reference> for @serviceuser.projects.services.list@. module Network.Google.Resource.ServiceUser.Projects.Services.List ( -- * REST Resource ProjectsServicesListResource -- * Creating a Request , projectsServicesList , ProjectsServicesList -- * Request Lenses , pslParent , pslXgafv , pslUploadProtocol , pslAccessToken , pslUploadType , pslPageToken , pslPageSize , pslCallback ) where import Network.Google.Prelude import Network.Google.ServiceUser.Types -- | A resource alias for @serviceuser.projects.services.list@ method which the -- 'ProjectsServicesList' request conforms to. type ProjectsServicesListResource = "v1" :> Capture "parent" Text :> "services" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "pageToken" Text :> QueryParam "pageSize" (Textual Int32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ListEnabledServicesResponse -- | List enabled services for the specified consumer. -- -- /See:/ 'projectsServicesList' smart constructor. data ProjectsServicesList = ProjectsServicesList' { _pslParent :: !Text , _pslXgafv :: !(Maybe Xgafv) , _pslUploadProtocol :: !(Maybe Text) , _pslAccessToken :: !(Maybe Text) , _pslUploadType :: !(Maybe Text) , _pslPageToken :: !(Maybe Text) , _pslPageSize :: !(Maybe (Textual Int32)) , _pslCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsServicesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pslParent' -- -- * 'pslXgafv' -- -- * 'pslUploadProtocol' -- -- * 'pslAccessToken' -- -- * 'pslUploadType' -- -- * 'pslPageToken' -- -- * 'pslPageSize' -- -- * 'pslCallback' projectsServicesList :: Text -- ^ 'pslParent' -> ProjectsServicesList projectsServicesList pPslParent_ = ProjectsServicesList' { _pslParent = pPslParent_ , _pslXgafv = Nothing , _pslUploadProtocol = Nothing , _pslAccessToken = Nothing , _pslUploadType = Nothing , _pslPageToken = Nothing , _pslPageSize = Nothing , _pslCallback = Nothing } -- | List enabled services for the specified parent. An example valid parent -- would be: - projects\/my-project pslParent :: Lens' ProjectsServicesList Text pslParent = lens _pslParent (\ s a -> s{_pslParent = a}) -- | V1 error format. pslXgafv :: Lens' ProjectsServicesList (Maybe Xgafv) pslXgafv = lens _pslXgafv (\ s a -> s{_pslXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pslUploadProtocol :: Lens' ProjectsServicesList (Maybe Text) pslUploadProtocol = lens _pslUploadProtocol (\ s a -> s{_pslUploadProtocol = a}) -- | OAuth access token. pslAccessToken :: Lens' ProjectsServicesList (Maybe Text) pslAccessToken = lens _pslAccessToken (\ s a -> s{_pslAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pslUploadType :: Lens' ProjectsServicesList (Maybe Text) pslUploadType = lens _pslUploadType (\ s a -> s{_pslUploadType = a}) -- | Token identifying which result to start with; returned by a previous -- list call. pslPageToken :: Lens' ProjectsServicesList (Maybe Text) pslPageToken = lens _pslPageToken (\ s a -> s{_pslPageToken = a}) -- | Requested size of the next page of data. pslPageSize :: Lens' ProjectsServicesList (Maybe Int32) pslPageSize = lens _pslPageSize (\ s a -> s{_pslPageSize = a}) . mapping _Coerce -- | JSONP pslCallback :: Lens' ProjectsServicesList (Maybe Text) pslCallback = lens _pslCallback (\ s a -> s{_pslCallback = a}) instance GoogleRequest ProjectsServicesList where type Rs ProjectsServicesList = ListEnabledServicesResponse type Scopes ProjectsServicesList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only"] requestClient ProjectsServicesList'{..} = go _pslParent _pslXgafv _pslUploadProtocol _pslAccessToken _pslUploadType _pslPageToken _pslPageSize _pslCallback (Just AltJSON) serviceUserService where go = buildClient (Proxy :: Proxy ProjectsServicesListResource) mempty
brendanhay/gogol
gogol-serviceuser/gen/Network/Google/Resource/ServiceUser/Projects/Services/List.hs
mpl-2.0
5,635
0
18
1,334
883
511
372
126
1
{- passman Copyright (C) 2018-2021 Jonathan Lamothe <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. -} module Main where import Control.Monad.Trans.State as S import System.Console.HCL (Request, reqIO, runRequest) import System.EasyFile ( createDirectoryIfMissing , getAppUserDataDirectory , (</>) ) import System.Random (getStdGen) import Types import UI import Util main :: IO () main = runRequest setup >>= mapM_ (S.evalStateT mainMenu) setup :: Request Status setup = do g <- reqIO getStdGen p <- getDBPath db <- loadFrom p pw <- getMasterPass return $ Status g pw p db getDBPath :: Request FilePath getDBPath = reqIO $ do path <- getAppUserDataDirectory "passman" createDirectoryIfMissing True path return $ path </> "database.json" --jl
jlamothe/passman
app/Main.hs
lgpl-3.0
1,389
0
9
243
211
112
99
25
1
{-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} module Lib.InlineFormatting where ------------------------------------------------------------------------------------ import qualified Data.DList as DList import Data.Foldable (toList) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import Text.Blaze.Html (toHtml) import Text.Blaze.Html.Renderer.Text (renderHtml) ---- import Lib.DList (dlistConcat) import Lib.Text (showT, (+@)) import Lib.Formatting ------------------------------------------------------------------------------------ data FormatPos = Start | End deriving Eq flistToInlineStyleHtml :: FList -> Text flistToInlineStyleHtml = root where root flist = T.concat $ toList $ (before `DList.cons` (dlistConcat $ fmap (crux []) flist)) `DList.snoc` after crux _ (TPlain t) = DList.singleton (plain t) crux s (TForm f l) = ((html Start s f) `DList.cons` (dlistConcat (fmap (crux (f:s)) l))) `DList.snoc` (html End s f) delink x = T.replace "://" ":/&#8203;/" $ T.replace "." "&#8203;." x plain t = T.concat $ map delink $ TL.toChunks $ renderHtml $ toHtml t before = "" after = "" linkStart h = T.concat ["<a href=\"" , h, "\" style=\"text-decoration: none\">"] html Start _ MonospacePar = "<font size=\"3\"><div><pre style=\"line-height: 125%\">" html End _ MonospacePar = "</pre></div></font>" html Start _ Monospace = "<font size=\"3\"><span style=\"font-family: monospace\">" html End _ Monospace = "</span></font>" html Start _ Underline = "<div style=\"text-decoration: underline\">" html End _ Underline = "</div>" html Start _ LineThrough = "<div style=\"text-decoration: line-through\">" html End _ LineThrough = "</div>" html Start _ Emphesis = "<div style=\"font-weight: bold\">" html End _ Emphesis = "</div>" html Start _ List = "<ul>" html End _ List = "</ul>" html Start _ ListItem = "<li>" html End _ ListItem = "</li>" html Start _ Table = "<blockqoute><table cellpadding=\"2\">" html End _ Table = "</table></blockqoute>" html Start _ (Link t) = linkStart t html End _ (Link _) = "</a>" html Start _ (TableRow) = "<tr>" html End _ (TableRow) = "</tr>" html Start _ (TableCellPad i) = "<td width=\"" +@ showT i +@ "\">" html End _ (TableCellPad _) = "</td>" html Start _ (TableCol i) = "<td colspan=\"" +@ showT i +@ "\">" html End _ (TableCol _) = "</td>" html Start _ Dark = "<span style=\"color: #a0a0a0\">" html End _ Dark = "</span>" html Start _ Footer = "<div height=\"20\">&nbsp;</div><div style=\"color: #b0b0b0; font-size: 10px\">" html End _ Footer = "</div>" html Start _ _ = "<span>" html End _ _ = "</span>"
kernelim/gitomail
src/Lib/InlineFormatting.hs
apache-2.0
3,494
0
17
1,259
828
441
387
55
31
{- | Module : FileIO Description : Perform IO for the REPL Copyright : (c) 2014—2015 The F2J Project Developers (given in AUTHORS.txt) License : BSD3 Maintainer : Boya Peng <[email protected]> Stability : stable Portability : portable -} {-# LANGUAGE ScopedTypeVariables , DeriveDataTypeable #-} module FileIO where import qualified Control.Exception as E import Control.Monad (when) import Data.Data import System.Directory (doesFileExist) import System.IO import BackEnd import FrontEnd import JavaUtils (inferClassName, inferOutputPath) data TransMethod = Apply | Naive | SNaive | Stack | Unbox | StackAU1 | StackAU2 | BenchN | BenchS | BenchNA | BenchSA | BenchSAI1 | BenchSAI2 deriving (Eq, Show, Data, Typeable, Ord) type Connection = (Handle, Handle) type CompileOpt = (Int, Compilation, [TransMethod]) wrap :: Connection -> (Int -> Handle -> IO Int) -> CompileOpt -> Bool -> Bool -> String -> IO Int wrap (inP, outP) receMsg opt flagC flagS name = do exist <- doesFileExist name if not exist then do putStrLn $ name ++ " does not exist" return 1 else do correct <- send inP opt flagC flagS name case correct of True -> receMsg 0 outP False -> return 1 source2java :: Bool -> Bool -> DumpOption -> Compilation -> String -> (FilePath, String) -> IO String source2java supernaive optInline optDump compilation className (filePath, source) = do coreExpr <- source2core optDump "" (filePath, source) core2java supernaive optInline optDump compilation className coreExpr send :: Handle -> CompileOpt -> Bool -> Bool -> FilePath -> IO Bool send h (n, opt, method) flagC flagS f = do contents <- readFile f -- let path = dropFileName f let className = inferClassName . inferOutputPath $ f result <- E.try (if method == [SNaive] then source2java True False NoDump opt className (f, contents) else source2java False False NoDump opt className (f, contents)) case result of Left (_ :: E.SomeException) -> do putStrLn ("\x1b[31m" ++ "invalid expression sf2Java") putStrLn "\x1b[0m" return False Right javaFile -> do sendMsg h (className ++ ".java") let file = javaFile ++ "\n" ++ "//end of file" sendFile h file when flagS $ do putStrLn contents putStrLn file return True receiveMsg :: Int -> Handle -> IO Int receiveMsg err h = do msg <- hGetLine h if msg == "exit" then return err else do putStrLn msg receiveMsg err h sendMsg :: Handle -> String -> IO () sendMsg h msg = do hPutStrLn h msg sendFile :: Handle -> String -> IO () sendFile h f = do hPutStrLn h f
bixuanzju/fcore
lib/FileIO.hs
bsd-2-clause
3,119
0
16
1,061
827
420
407
76
3
module Evaluator ( evaluate ) where import Data.List (find) import Base termMap :: (Int -> Int -> Term) -> Term -> Term termMap onvar t = go 0 t where go index (TermVar var) = onvar index var go index (TermIfThenElse t1 t2 t3) = TermIfThenElse (go index t1) (go index t2) (go index t3) go index (TermAbs var ty t) = TermAbs var ty (go (index + 1) t) go index (TermApp t1 t2) = TermApp (go index t1) (go index t2) go index (TermRecord fields) = TermRecord (map (\(f, t) -> (f, go index t)) fields) go index (TermProj t field) = TermProj (go index t) field go index (TermAscribe t ty) = TermAscribe (go index t) ty go _ TermTrue = TermTrue go _ TermFalse = TermFalse -- | Shift up deBruijn indices of all free variables by delta. termShift :: Term -> Int -> Term termShift t delta = termMap (\index var -> if var >= index then TermVar (var + delta) else TermVar var) t -- | Substitute the variable with 0 deBruijn index in term to subterm. termSubstitute :: Term -> Term -> Term termSubstitute t subt = termMap (\index var -> if var == index then termShift subt index else TermVar var) t isValue :: Term -> Bool isValue TermTrue = True isValue TermFalse = True isValue (TermRecord fields) = all (\(_, t) -> isValue t) fields isValue (TermAbs _ _ _) = True isValue _ = False -- | One step evaluation, return Nothing if there is no rule applies. evaluate1 :: Term -> Maybe Term {- E-IfTrue -} evaluate1 (TermIfThenElse TermTrue t1 _) = Just t1 {- E-IfFalse -} evaluate1 (TermIfThenElse TermFalse _ t2) = Just t2 {- E-If -} evaluate1 (TermIfThenElse t t1 t2) = TermIfThenElse <$> evaluate1 t <*> pure t1 <*> pure t2 {- E-Rcd -} evaluate1 (TermRecord fields) = TermRecord <$> go fields where go [] = Nothing go ((f, t) : rest) | isValue t = do rest' <- go rest return ((f, t) : rest') | otherwise = do t' <- evaluate1 t return ((f, t') : rest) {- E-ProjRcd -} evaluate1 (TermProj v@(TermRecord fields) f) | isValue v = case find (\(f1, _) -> f1 == f) fields of Just (_, t) -> Just t Nothing -> undefined {- E-Proj -} evaluate1 (TermProj t f) = TermProj <$> evaluate1 t <*> pure f {- E-AppAbs -} evaluate1 (TermApp (TermAbs _ _ t) v) | isValue v = Just $ termShift (termSubstitute t (termShift v 1)) (-1) {- E-App2 -} evaluate1 (TermApp v t) | isValue v = TermApp v <$> evaluate1 t {- E-App1 -} evaluate1 (TermApp t1 t2) = TermApp <$> evaluate1 t1 <*> pure t2 {- E-NoRule -} evaluate1 _ = Nothing evaluate :: Term -> Term evaluate t = case evaluate1 t of Just t' -> evaluate t' Nothing -> t
foreverbell/unlimited-plt-toys
tapl/simplesub/Evaluator.hs
bsd-3-clause
2,650
0
13
646
1,089
547
542
53
9
{-# LANGUAGE DeriveDataTypeable #-} -------------------------------------------------------------------- -- | -- Copyright : (c) Edward Kmett 2013 -- License : BSD3 -- Maintainer: Edward Kmett <[email protected]> -- Stability : experimental -- Portability: non-portable -- -------------------------------------------------------------------- module Control.Task.Promise ( Promise(..) , promise , future ) where -- import Control.Concurrent.STM -- import Control.Monad -- import Control.Monad.Cont -- import Control.Task.STM import Control.Task.Monad import Data.Profunctor -- import Data.Traversable import Data.Typeable data Promise a b = Promise { fulfill :: a -> Task () , await :: Task b } deriving Typeable instance Profunctor Promise where dimap f g (Promise h b) = Promise (h . f) (fmap g b) {-# INLINE dimap #-} instance Functor (Promise a) where fmap f (Promise h b) = Promise h (fmap f b) {-# INLINE fmap #-} promise :: Task (Promise a a) promise = undefined {- promise = do queue <- newTChan result <- newEmptyTMV return $ Promise { fulfill = \a -> do q <- stm $ do putTMVar result a readTChan queue forM_ q $ \k -> spawn (k a) , await = callCC $ \k -> join $ stm $ do tryReadTMVar result >>= \ ma -> case ma of Just a -> return (k a) Nothing -> do writeTChan queue k; return undefined -- TODO: make some blocked arg for task to pass me to call instead } -} future :: Task a -> Task (Task a) future m = do p <- promise spawn $ m >>= fulfill p return (await p) {-# INLINE future #-}
ekmett/tasks
src/Control/Task/Promise.hs
bsd-3-clause
1,601
0
11
360
271
151
120
26
1
module DPLL where import Data.Foldable (asum) import Data.List (nub, (\\)) import Data.Map (Map ()) import qualified Data.Map as Map import Data.Maybe (listToMaybe, mapMaybe, fromJust) import Data.Set (Set ()) import qualified Data.Set as Set main = print (dpll ex ["p", "a", "c"] mempty) dpll :: Clauses -> Symbols -> Model -> Maybe Model dpll clauses symbols model | all (`isTrueIn` model) clauses = Just model | any (`isFalseIn` model) clauses = Nothing | otherwise = asum (map (>>= next) controlList) where next :: Assignment -> Maybe Model next (sym := val) = dpll clauses (symbols `minus` sym) (model `including` (sym := val)) controlList :: [Maybe Assignment] controlList = [ findPureSymbol symbols clauses model , findUnitClause clauses model , (:= False) <$> listToMaybe symbols , (:= True) <$> listToMaybe symbols ] -- Well, now we've done a rather remarkable amount of work without doing -- anything at all! Let's start defining some types and functions so the -- above transcription actually means something. -- Let's analyze what we're doing with the terms to get some idea of what -- data types will fit for them. -- A symbol could be anything -- but we'll just use a character for now. type Symbol = String -- We did commit to the list data structure for symbols with the `(x:xs)` -- pattern matching. A set is likely more appropriate, but we'll defer that -- performance improvement to later. type Symbols = [Symbol] minus :: Symbols -> Symbol -> Symbols minus xs = (xs \\) . pure -- Clauses is a collection of expressions. An expression is -- an organization of terms in CNF. type Clauses = [CNF] -- With CNF, juxtaposion is conjunctions. We can therefore represent -- a CNF expression as a list of literals. type CNF = [Literal] -- Finally, a literal is a pair of Sign and Symbol. type Literal = (Sign, Symbol) -- Of course, a sign is just a function that either negates or -- doesn't negate a boolean expression. data Sign = Pos | Neg deriving (Eq, Ord, Show) apply :: Sign -> Bool -> Bool apply Pos = id apply Neg = not n :: Symbol -> Literal n c = (Neg, c) p :: Symbol -> Literal p c = (Pos, c) -- We can now define the clauses given in the assignment: ex2 :: Clauses ex2 = [ [ n "p", p "a", p "c" ] , [ p "a" ] , [ p "p", n "c" ] ] ex :: Clauses ex = [ [ n "p", p "a", p "c" ] , [ n "a" ] , [ p "p", n "c" ] ] -- The main use we have for the clauses type is to map over it -- with `isTrueIn` and `isFalseIn`, checking every clause in the -- list against the model. The model is an assignment of symbols -- to truth values, so we'll use a map. type Model = Map Symbol Bool isTrueIn :: CNF -> Model -> Bool isTrueIn cnf model = or (mapMaybe f cnf) where f (sign, symbol) = apply sign <$> Map.lookup symbol model isFalseIn :: CNF -> Model -> Bool isFalseIn cnf model = all not literals where literals = map f cnf f (sign, symbol) = apply sign (Map.findWithDefault (apply sign True) symbol model) -- Right, where were we? We have the following terms not in scope: -- * := -- * findPureSymbol -- * including -- * findUnitClause -- Since `:=` starts with a colon, it has to be a data constructor. -- It's used to signify assignment of a symbol to a value, so... data Assignment = (:=) { getSymbol :: Symbol, getValue :: Bool } instance Show Assignment where show (s := v) = "(" ++ s ++ " := " ++ show v ++ ")" -- Which gives us a rather nice definition of the following: including :: Model -> Assignment -> Model including m (sym := val) = Map.insert sym val m -- The final remaining items that aren't defined are findPureSymbol and -- findUnitClause. -- From the textbook, -- > Pure symbol heuristic: A pure symbol is a symbol that always appears -- > with the same "sign" in all clauses. For example, in the three clauses -- > (A ∨ ¬B), (¬B ∨ ¬C), and (C ∨ A), the symbol A is pure because only -- > the positive literal appears, B is pure because only the negative -- > literal appears, and C is impure. -- If a symbol has all negative signs, then the returned assignment is -- False. If a symbol has all positive signs, then the returned assignment -- is True. -- We'll punt refining the clauses with the model to a future function... findPureSymbol :: Symbols -> Clauses -> Model -> Maybe Assignment findPureSymbol symbols clauses' model = asum (map makeAssignment symbols) where clauses = refinePure clauses' model makeAssignment :: Symbol -> Maybe Assignment makeAssignment sym = (sym :=) <$> negOrPos (signsForSymbol sym) signsForSymbol :: Symbol -> [Sign] signsForSymbol sym = clauses >>= signsForSymInClause sym signsForSymInClause :: Symbol -> CNF -> [Sign] signsForSymInClause sym = map fst . filter ((== sym) . snd) negOrPos :: [Sign] -> Maybe Bool negOrPos = getSingleton . nub . applyTrue applyTrue :: [Sign] -> [Bool] applyTrue = map (`apply` True) getSingleton :: [a] -> Maybe a getSingleton [x] = Just x getSingleton _ = Nothing -- Again, from the textbook, -- > Unit clause heuristic: A unit clause was defined earlier as a clause -- > with just one literal. In the context of DPLL, it also means clauses -- > in which all literals but one are already assigned false by the model. -- > For example, if the model contains B = true, then (¬B ∨ ¬C) simplifies -- > to ¬C, which is a unit clause. Obviously, for this clause to be true, -- > C must be set to false. The unit clause heuristic assigns all such symbols -- > before branching on the remainder. -- As above, we'll punt refining the clauses with the model. findUnitClause :: Clauses -> Model -> Maybe Assignment findUnitClause clauses' model = assignSymbol <$> firstUnitClause where clauses :: Clauses clauses = refineUnit clauses' model firstUnitClause :: Maybe Literal firstUnitClause = asum (map (getSingleton . mapMaybe ifInModel) clauses) ifInModel :: Literal -> Maybe Literal ifInModel (sign, symbol) = case Map.lookup symbol model of Just _ -> Nothing _ -> Just (sign, symbol) assignSymbol :: Literal -> Assignment assignSymbol (sign, symbol) = symbol := apply sign True {- Now, in the previous functions, we punted refining the clauses. It's time to do that. We'll start by folding the model and clauses into a new set of clauses. The helper function will go through each symbol in the model, find the relevant clauses, and modify them appropriately. For a pure symbol, the given optimization (from the book): > Note that, in determining the purity of a symbol, the algorithm can > ignore clauses that are already known to be true in the model constructed > so far. For example, if the model contains B = false, then the clause > (¬B ∨ ¬C) is already true, and in the remaining clauses C appears only > as a positive literal; therefore C becomes pure. The algorithm can then be described as: For each symbol in the model, find each clause in the clauses which is already true given the symbol's assigned value. In our representation of the above, we'd get: helper 'b' False so we'd want to first find the clauses with `(not, 'b')` as a member. Then, we'd remove the clauses that are true given the assignment. So the CNF: [(neg, 'b'), (neg, 'c')] would become [(neg, 'c')], a pure variable. -} refinePure :: Clauses -> Model -> Clauses refinePure = Map.foldrWithKey f where f :: Symbol -> Bool -> Clauses -> Clauses f sym val = map discardTrue where discardTrue = filter (not . clauseIsTrue) clauseIsTrue (sign, symbol) = symbol == sym && apply sign val {- The optimization from the text for the unit clause is: > In the context of DPLL, it also means clauses in which all literals but one > are already assigned false by the model. For example, if the model contains > B = true, then (¬B ∨ ¬C) simplifies to ¬C, which is a unit clause. Obviously, > for this clause to be true, C must be set to false. The unit clause > heuristic assigns all such symbols before branching on the remainder. Rather than folding the model, we'll fold the clauses. Given a model where (b, True) and a clause [(neg, 'b'), (neg, 'c')], this will transform it in the following steps: -} refineUnit :: Clauses -> Model -> Clauses refineUnit clauses model = map refine clauses where refine :: CNF -> CNF refine cnf = case allButOneFalse cnf of Just (s := True) -> [p s] Just (s := False) -> [n s] Nothing -> cnf allButOneFalse :: CNF -> Maybe Assignment allButOneFalse = getSingleton . filter (not . getValue) . map assign assign :: Literal -> Assignment assign (sign, sym) = sym := Map.findWithDefault (apply sign True) sym model test e = dpll e ["p", "a", "c"] mempty wat = Map.fromList [("a",False),("c",False),("p",False)] showModel :: Model -> String showModel = unlines . map (show . snd) . Map.toList . Map.mapWithKey (:=) showOnlyTrue :: Model -> String showOnlyTrue = unlines . map (show . snd) . filter (getValue . snd) . Map.toList . Map.mapWithKey (:=) {- Finally, we can encode the three coloring problem for Australia, and use the algorithm to solve it. To encode that a single state has a single color, that has the form: -} colors :: [Symbol] colors = [green, blue, red] green = "-green" blue = "-blue" red = "-red" states :: [Symbol] states = [ western , southern , northern , queensland , newSouthWales , victoria ] western = "Western" southern = "Southern" northern = "Northern" queensland = "Queensland" newSouthWales = "New South Wales" victoria = "Victoria" hasColor :: Symbol -> Clauses hasColor st = [ [ p $ st `is` green , p $ st `is` blue , p $ st `is` red ] , [ n $ st `is` blue , n $ st `is` red ] , [ n $ st `is` green , n $ st `is` red ] , [ n $ st `is` green , n $ st `is` blue ] ] is :: Symbol -> Symbol -> Symbol is = (++) (/\) :: Clauses -> Clauses -> Clauses (/\) = (++) (/\:) :: Monad m => m a -> (a -> m b) -> m b (/\:) = (>>=) initialConditions :: Clauses initialConditions = states /\: hasColor {- Now we've established that each state has a color that is either blue, green, or red. We'll encode a way of saying that adjacent states must be of different colors. With only two states and two colors, we could say: $$a_1 \lor \neg b_1 \land \neg a_1 \lor b_1 \land a_2 \lor \neg b_2 \land \neg a_2 \lor b_2$$ -} adjNotEqual :: (Symbol, Symbol) -> Clauses adjNotEqual (a, b) = colors /\: bothAreNot where bothAreNot color = [ [ n $ a `is` color , n $ b `is` color ] ] {- Now we need a list of adjacent states... -} adjStates :: [(Symbol, Symbol)] adjStates = [ (western, northern) , (western, southern) , (northern, southern) , (northern, queensland) , (southern, newSouthWales) , (southern, victoria) , (southern, queensland) , (newSouthWales, queensland) , (newSouthWales, victoria) ] {- And this gives us our final set of clauses: -} adjacentNotEqual = adjStates /\: adjNotEqual australiaClauses = initialConditions /\ adjacentNotEqual australiaSymbols = is <$> states <*> colors australiaSolution = dpll australiaClauses australiaSymbols mempty prettyAustralia = showModel <$> australiaSolution printPlease = putStrLn (fromJust prettyAustralia)
parsonsmatt/dpll
src/DPLL.hs
bsd-3-clause
11,539
185
11
2,629
2,378
1,342
1,036
188
3
#!/usr/bin/env runstaskell import Test.Hspec main :: IO () main = hspec $ describe "Prelude.head" $ do it "returns head of a list" $ do head [23..] `shouldBe` (23 :: Int)
soenkehahn/runstaskell
test/04.hs
bsd-3-clause
185
0
13
44
64
33
31
6
1
module Spring13.Week5.ExprT where data ExprT = Lit Integer | Add ExprT ExprT | Mul ExprT ExprT deriving (Show, Eq)
bibaijin/cis194
src/Spring13/Week5/ExprT.hs
bsd-3-clause
140
0
6
44
41
24
17
5
0
-- |A custom tokenizer that converts a string of hasp source code to a list of -- individual tokens, which can then be fed into the parser. module Tokenizer ( tokenize , Token ) where import Data.Sequence import Data.Foldable (toList) import Control.Monad (liftM) import Error type Token = String tokenize :: String -> ThrowsError [Token] tokenize source = liftM toList $ genTokenSeq False empty "" source keepDelim :: Seq Token -> Token -> Char -> String -> ThrowsError (Seq Token) keepDelim acc "" char = genTokenSeq False (acc |> [char]) "" keepDelim acc token char = genTokenSeq False (acc |> token |> [char]) "" dropDelim :: Seq Token -> Token -> Char -> String -> ThrowsError (Seq Token) dropDelim acc "" char = genTokenSeq False acc "" dropDelim acc token char = genTokenSeq False (acc |> token) "" appendChar :: Bool -> Seq Token -> Token -> Char -> String -> ThrowsError (Seq Token) appendChar isString acc token char = genTokenSeq isString acc (token ++ [char]) startString :: Seq Token -> Token -> Char -> String -> ThrowsError (Seq Token) startString acc "" char = genTokenSeq True acc [char] startString acc token char = genTokenSeq True (acc |> token) [char] endString :: Seq Token -> Token -> Char -> String -> ThrowsError (Seq Token) endString acc token curChar = genTokenSeq False (acc |> (token ++ [curChar])) "" fastForward :: Seq Token -> Token -> String -> ThrowsError (Seq Token) fastForward acc token input = genTokenSeq False acc token rest where rest = dropWhile (\c -> c /= '\n') input genTokenSeq :: Bool -> Seq Token -> Token -> String -> ThrowsError (Seq Token) genTokenSeq False acc "" "" = return acc genTokenSeq False acc token "" = return (acc |> token) genTokenSeq True acc token "" = throw $ SyntaxError "Unclosed string literal" genTokenSeq False acc token (curChar:nextInput) | curChar `elem` "()" = keepDelim acc token curChar nextInput | curChar `elem` " \n\t" = dropDelim acc token curChar nextInput | curChar == '"' = startString acc token curChar nextInput | curChar == ';' = fastForward acc token nextInput | otherwise = appendChar False acc token curChar nextInput genTokenSeq True acc token (curChar:nextInput) | curChar == '"' = endString acc token curChar nextInput | otherwise = appendChar True acc token curChar nextInput
aldld/hasp
src/Tokenizer.hs
bsd-3-clause
2,383
0
12
493
838
419
419
41
1
{-#LANGUAGE RecordWildCards #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies #-} {-# LANGUAGE OverloadedStrings, GADTs, FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving, MultiParamTypeClasses #-} module DirectoryServer where import Network hiding (accept, sClose) import Network.Socket hiding (send, recv, sendTo, recvFrom, Broadcast) import Network.Socket.ByteString import Data.ByteString.Char8 (pack, unpack) import System.Environment import System.IO import Control.Concurrent import Control.Concurrent.STM import Control.Exception import Control.Monad (forever, when, join) import Data.List.Split import Data.Word import Text.Printf (printf) import System.Directory import Data.Map (Map) -- from the `containers` library import Data.Time import System.Random import qualified Data.Map as M type Uuid = Int type Address = String type Port = String type Filename = String type Timestamp = IO String --Server data type allows me to pass address and port details easily data DirectoryServer = DirectoryServer { address :: String , port :: String , filemappings :: TVar (M.Map Filename Filemapping) , fileservers :: TVar (M.Map Uuid Fileserver) , fileservercount :: TVar Int } --Constructor newDirectoryServer :: String -> String -> IO DirectoryServer newDirectoryServer address port = atomically $ do DirectoryServer <$> return address <*> return port <*> newTVar M.empty <*> newTVar M.empty <*> newTVar 0 addFilemapping :: DirectoryServer -> Filename -> Uuid -> Address -> Port -> Timestamp -> STM () addFilemapping DirectoryServer{..} filename uuid fmaddress fmport timestamp = do fm <- newFilemapping filename uuid fmaddress fmport timestamp modifyTVar filemappings . M.insert filename $ fm addFileserver :: DirectoryServer -> Uuid -> Address -> Port -> STM () addFileserver DirectoryServer{..} uuid fsaddress fsport = do fs <- newFileserver uuid fsaddress fsport modifyTVar fileservers . M.insert uuid $ fs lookupFilemapping :: DirectoryServer -> Filename -> STM (Maybe Filemapping) lookupFilemapping DirectoryServer{..} filename = M.lookup filename <$> readTVar filemappings lookupFileserver :: DirectoryServer -> Uuid -> STM (Maybe Fileserver) lookupFileserver DirectoryServer{..} uuid = M.lookup uuid <$> readTVar fileservers data Filemapping = Filemapping { fmfilename :: Filename , fmuuid :: Uuid , fmaddress :: Address , fmport :: Port , fmtimestamp :: Timestamp } newFilemapping :: Filename -> Uuid -> Address -> Port -> Timestamp -> STM Filemapping newFilemapping fmfilename fmuuid fmaddress fmport fmtimestamp = Filemapping <$> return fmfilename <*> return fmuuid <*> return fmaddress <*> return fmport <*> return fmtimestamp getFilemappinguuid :: Filemapping -> Uuid getFilemappinguuid Filemapping{..} = fmuuid getFilemappingaddress :: Filemapping -> Address getFilemappingaddress Filemapping{..} = fmaddress getFilemappingport :: Filemapping -> Port getFilemappingport Filemapping{..} = fmport getFilemappingtimestamp :: Filemapping -> Timestamp getFilemappingtimestamp Filemapping{..} = fmtimestamp data Fileserver = Fileserver { fsuuid :: Uuid , fsaddress :: HostName , fsport :: Port } newFileserver :: Uuid -> Address -> Port -> STM Fileserver newFileserver fsuuid fsaddress fsport = Fileserver <$> return fsuuid <*> return fsaddress <*> return fsport getFileserveraddress :: Fileserver -> HostName getFileserveraddress Fileserver{..} = fsaddress getFileserverport :: Fileserver -> Port getFileserverport Fileserver{..} = fsport --4 is easy for testing the pooling maxnumThreads = 4 serverport :: String serverport = "7008" serverhost :: String serverhost = "localhost" dirrun:: IO () dirrun = withSocketsDo $ do --Command line arguments for port and address --args <- getArgs server <- newDirectoryServer serverhost serverport --sock <- listenOn (PortNumber (fromIntegral serverport)) addrinfos <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just serverport) let serveraddr = head addrinfos sock <- socket (addrFamily serveraddr) Stream defaultProtocol bindSocket sock (addrAddress serveraddr) listen sock 5 _ <- printf "Listening on port %s\n" serverport --Listen on port from command line argument --New Abstract FIFO Channel chan <- newChan --Tvars are variables Stored in memory, this way we can access the numThreads from any method numThreads <- atomically $ newTVar 0 --Spawns a new thread to handle the clientconnectHandler method, passes socket, channel, numThreads and server forkIO $ clientconnectHandler sock chan numThreads server --Calls the mainHandler which will monitor the FIFO channel mainHandler sock chan mainHandler :: Socket -> Chan String -> IO () mainHandler sock chan = do --Read current message on the FIFO channel chanMsg <- readChan chan --If KILL_SERVICE, stop mainHandler running, If anything else, call mainHandler again, keeping the service running case (chanMsg) of ("KILL_SERVICE") -> putStrLn "Terminating the Service!" _ -> mainHandler sock chan clientconnectHandler :: Socket -> Chan String -> TVar Int -> DirectoryServer -> IO () clientconnectHandler sock chan numThreads server = do --Accept the socket which returns a handle, host and port --(handle, host, port) <- accept sock (s,a) <- accept sock --handle <- socketToHandle s ReadWriteMode --Read numThreads from memory and print it on server console count <- atomically $ readTVar numThreads putStrLn $ "numThreads = " ++ show count --If there are still threads remaining create new thread and increment (exception if thread is lost -> decrement), else tell user capacity has been reached if (count < maxnumThreads) then do forkFinally (clientHandler s chan server) (\_ -> atomically $ decrementTVar numThreads) atomically $ incrementTVar numThreads else do send s (pack ("Maximum number of threads in use. try again soon"++"\n\n")) sClose s clientconnectHandler sock chan numThreads server clientHandler :: Socket -> Chan String -> DirectoryServer -> IO () clientHandler sock chan server@DirectoryServer{..} = forever $ do message <- recv sock 1024 let msg = unpack message print $ msg ++ "!ENDLINE!" let cmd = head $ words $ head $ splitOn ":" msg print cmd case cmd of ("HELO") -> heloCommand sock server $ (words msg) !! 1 ("KILL_SERVICE") -> killCommand chan sock ("DOWNLOAD") -> downloadCommand sock server msg ("UPLOAD") -> uploadCommand sock server msg ("JOIN") -> joinCommand sock server msg ("UPDATE") -> updateCommand sock server msg _ -> do send sock (pack ("Unknown Command - " ++ msg ++ "\n\n")) ; return () --Function called when HELO text command recieved heloCommand :: Socket -> DirectoryServer -> String -> IO () heloCommand sock DirectoryServer{..} msg = do send sock $ pack $ "HELO " ++ msg ++ "\n" ++ "IP:" ++ "192.168.6.129" ++ "\n" ++ "Port:" ++ port ++ "\n" ++ "StudentID:12306421\n\n" return () killCommand :: Chan String -> Socket -> IO () killCommand chan sock = do send sock $ pack $ "Service is now terminating!" writeChan chan "KILL_SERVICE" downloadCommand :: Socket -> DirectoryServer ->String -> IO () downloadCommand sock server@DirectoryServer{..} command = do let clines = splitOn "\\n" command filename = (splitOn ":" $ clines !! 1) !! 1 fm <- atomically $ lookupFilemapping server filename case fm of (Nothing) -> send sock $ pack $ "DOWNLOAD: " ++ filename ++ "\n" ++ "STATUS: " ++ "File not found" ++ "\n\n" (Just fm) -> do print (getFilemappingaddress fm) print (getFilemappingport fm) forkIO $ downloadmsg filename (getFilemappingaddress fm) (getFilemappingport fm) sock send sock $ pack $ "DOWNLOAD: " ++ filename ++ "\n" ++ "STATUS: " ++ "SUCCESSFUL" ++ "\n\n" return () downloadmsg :: String -> String -> String -> Socket -> IO() downloadmsg filename host port sock = do addrInfo <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just "7007") let serverAddr = head addrInfo clsock <- socket (addrFamily serverAddr) Stream defaultProtocol connect clsock (addrAddress serverAddr) send clsock $ pack $ "DOWNLOAD:FILE" ++ "\\n" ++ "FILENAME:" ++ filename ++ "\\n\n" resp <- recv clsock 1024 let msg = unpack resp let clines = splitOn "\\n" msg fdata = (splitOn ":" $ clines !! 1) !! 1 sClose clsock send sock $ pack $ "DOWNLOAD: " ++ filename ++ "\n" ++ "DATA: " ++ fdata ++ "\n\n" -- forkIO $ returndata filename sock fdata return () returndata :: String -> Socket -> String -> IO () returndata filename sock fdata = do send sock $ pack $ "DOWNLOAD: " ++ filename ++ "\\n" ++ "DATA: " ++ fdata ++ "\n\n" return () uploadCommand :: Socket -> DirectoryServer ->String -> IO () uploadCommand sock server@DirectoryServer{..} command = do let clines = splitOn "\\n" command filename = (splitOn ":" $ clines !! 1) !! 1 fdata = (splitOn ":" $ clines !! 2) !! 1 fm <- atomically $ lookupFilemapping server filename case fm of (Just fm) -> send sock $ pack $ "UPLOAD: " ++ filename ++ "\n" ++ "STATUS: " ++ "File Already Exists" ++ "\n\n" (Nothing) -> do numfs <- atomically $ M.size <$> readTVar fileservers rand <- randomRIO (0, (numfs-1)) fs <- atomically $ lookupFileserver server rand case fs of (Nothing) -> send sock $ pack $ "UPLOAD: " ++ filename ++ "\n"++ "FAILED: " ++ "No valid Fileserver found to host" ++ "\n\n" (Just fs) -> do forkIO $ uploadmsg sock filename fdata fs rand server fm <- atomically $ newFilemapping filename rand (getFileserveraddress fs) (getFileserverport fs) (fmap show getZonedTime) atomically $ addFilemapping server filename rand (getFileserveraddress fs) (getFileserverport fs) (fmap show getZonedTime) send sock $ pack $ "UPLOAD: " ++ filename ++ "\\n" ++ "STATUS: " ++ "Successfull" ++ "\n\n" return () uploadmsg :: Socket -> String -> String -> Fileserver -> Int -> DirectoryServer -> IO () uploadmsg sock filename fdata fs rand server@DirectoryServer{..} = withSocketsDo $ do addrInfo <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just (getFileserverport fs)) let serverAddr = head addrInfo clsock <- socket (addrFamily serverAddr) Stream defaultProtocol connect clsock (addrAddress serverAddr) send clsock $ pack $ "UPLOAD:FILE" ++ "\\n" ++ "FILENAME:" ++ filename ++ "\\n" ++ "DATA:" ++ fdata ++ "\\n" resp <- recv clsock 1024 sClose clsock let msg = unpack resp print $ msg ++ "!ENDLINE!" let clines = splitOn "\\n" msg status = (splitOn ":" $ clines !! 1) !! 1 return () joinCommand :: Socket -> DirectoryServer ->String -> IO () joinCommand sock server@DirectoryServer{..} command = do let clines = splitOn "\\n" command newaddress = (splitOn ":" $ clines !! 1) !! 1 newport = (splitOn ":" $ clines !! 2) !! 1 nodeID <- atomically $ readTVar fileservercount fs <- atomically $ newFileserver nodeID newaddress newport atomically $ addFileserver server nodeID newaddress newport atomically $ incrementFileserverCount fileservercount send sock $ pack $ "JOINED DISTRIBUTED FILE SERVICE as fileserver: " ++ (show nodeID) ++ "\n\n" return () updateCommand :: Socket -> DirectoryServer ->String -> IO () updateCommand sock server@DirectoryServer{..} command = do let clines = splitOn "\\n" command filename = (splitOn ":" $ clines !! 1) !! 1 fdata = (splitOn ":" $ clines !! 2) !! 1 fm <- atomically $ lookupFilemapping server filename case fm of (Nothing) -> send sock $ pack $ "UPDATE: " ++ filename ++ "\n" ++ "STATUS: " ++ "File Doesnt Exists" ++ "\n\n" (Just fm) -> do fs <- atomically $ lookupFileserver server (getFilemappinguuid fm) case fs of (Nothing) -> send sock $ pack $ "UPDATE: " ++ filename ++ "\n"++ "FAILED: " ++ "No valid Fileserver found to host" ++ "\n\n" (Just fs) -> do forkIO $ updatemsg sock filename fdata fs (getFilemappinguuid fm) server fm <- atomically $ newFilemapping filename (getFilemappinguuid fm) (getFileserveraddress fs) (getFileserverport fs) (fmap show getZonedTime) atomically $ addFilemapping server filename (getFilemappinguuid fm) (getFileserveraddress fs) (getFileserverport fs) (fmap show getZonedTime) send sock $ pack $ "UPDATE: " ++ filename ++ "\\n" ++ "STATUS: " ++ "Successfull" ++ "\n\n" return () updatemsg :: Socket -> String -> String -> Fileserver -> Int -> DirectoryServer -> IO () updatemsg sock filename fdata fs rand server@DirectoryServer{..} = withSocketsDo $ do addrInfo <- getAddrInfo (Just (defaultHints {addrFlags = [AI_PASSIVE]})) Nothing (Just (getFileserverport fs)) let serverAddr = head addrInfo clsock <- socket (addrFamily serverAddr) Stream defaultProtocol connect clsock (addrAddress serverAddr) send clsock $ pack $ "UPDATE:FILE" ++ "\\n" ++ "FILENAME:" ++ filename ++ "\\n" ++ "DATA:" ++ fdata ++ "\\n" resp <- recv clsock 1024 sClose clsock let msg = unpack resp print $ msg ++ "!ENDLINE!" let clines = splitOn "\\n" msg status = (splitOn ":" $ clines !! 1) !! 1 return () --Increment Tvar stored in memory i.e. numThreads incrementTVar :: TVar Int -> STM () incrementTVar tv = modifyTVar tv ((+) 1) --Decrement Tvar stored in memory i.e. numThreads decrementTVar :: TVar Int -> STM () decrementTVar tv = modifyTVar tv (subtract 1) incrementFileserverCount :: TVar Int -> STM () incrementFileserverCount tv = modifyTVar tv ((+) 1)
Garygunn94/DFS
.stack-work/intero/intero43064-Do.hs
bsd-3-clause
14,762
433
15
3,690
3,994
2,059
1,935
264
7
import System.Cmd (system) main :: IO () main = runTests tests runTests :: [(String, String)] -> IO () runTests ((desc, t):ts) = do putStrLn ("\nTesting " ++ desc ++ ":") system ("runhaskell ./tests/" ++ t ++ ".hs") runTests ts runTests [] = return () tests :: [(String, String)] tests = [("Partition", "Partition") ,("UTF8", "UTF8") ,("Matcher", "Matcher")]
radekm/crep
tests/run.hs
bsd-3-clause
398
0
10
95
190
98
92
13
1
module TIM.FunQuoter where import Language.Haskell.TH.Quote import qualified Language.Haskell.TH as TH import qualified Data.ByteString.Lazy.Char8 as C import Compiler import TIM.Compiler fun :: QuasiQuoter fun = QuasiQuoter { quoteExp = quoteExpFunTerm, quotePat = undefined, quoteType = undefined, quoteDec = undefined } quoteExpFunTerm :: String -> TH.Q TH.Exp quoteExpFunTerm = dataToExpQ (const Nothing) . compileProgram . parse . C.pack
thomkoehler/FunLang
src/TIM/FunQuoter.hs
bsd-3-clause
479
0
10
92
120
74
46
14
1
{-# LANGUAGE StandaloneDeriving, GeneralizedNewtypeDeriving #-} module Data.TrieMap.OrdMap.Tests where import Data.TrieMap.OrdMap () import Data.TrieMap.Modifiers import qualified Data.TrieMap.TrieKey.Tests as TrieKeyTests import Test.QuickCheck deriving instance Arbitrary a => Arbitrary (Ordered a) tests :: Property tests = TrieKeyTests.tests "Data.TrieMap.OrdMap" (Ord (0.0 :: Double))
lowasser/TrieMap
Data/TrieMap/OrdMap/Tests.hs
bsd-3-clause
393
0
8
42
89
54
35
9
1
module GHC.RTS.Events.Analyze.Options ( Options(..) , parseOptions ) where import Options.Applicative import GHC.RTS.Events.Analyze.Types import GHC.RTS.Events.Analyze.Script import GHC.RTS.Events.Analyze.Script.Standard parseOptions :: IO Options parseOptions = customExecParser (prefs showHelpOnError) opts where opts = info (helper <*> parserOptions) ( fullDesc <> progDesc "Quantize and visualize EVENTLOG" <> footer "If no output is selected, generates SVG and totals." ) parserOptions :: Parser Options parserOptions = infoOption scriptHelp ( long "help-script" <> help "Detailed information about scripts" ) <*> (selectDefaultOutput <$> (Options <$> switch ( long "timed" <> help "Generate timed report (in SVG format)" ) <*> switch ( long "timed-txt" <> help "Generate timed report (in textual format)" ) <*> switch ( long "totals" <> help "Generate totals report" ) <*> strOption ( long "window" <> metavar "NAME" <> help "Events named NAME act to mark bounds of visualization window." <> value "" ) <*> option auto( long "buckets" <> short 'b' <> metavar "INT" <> help "Use INT buckets for quantization." <> showDefault <> value 1000 ) <*> strOption ( long "start" <> metavar "STR" <> help "Use STR as the prefix for the start of user events" <> showDefault <> value "START " ) <*> strOption ( long "stop" <> metavar "STR" <> help "Use STR as the prefix for the end of user events" <> showDefault <> value "STOP " ) <*> strOption ( long "script-totals" <> metavar "PATH" <> help "Use the script in PATH for the totals report" <> value "" ) <*> strOption ( long "script-timed" <> metavar "PATH" <> help "Use the script in PATH for the timed reports" <> value "" ) <*> switch ( long "ms" <> help "Use milliseconds (rather than seconds) on SVG timeline" ) <*> argument str (metavar "EVENTLOG") )) scriptHelp :: String scriptHelp = unlines [ "Scripts are used to drive report generation. The syntax for scripts is" , "" , "<script> ::= <command>+" , "" , "<command> ::= \"section\" STRING" , " | <eventId> (\"as\" STRING)?" , " | \"sum\" <filter> (\"as\" STRING)?" , " | <filter> (\"by\" <sort>)?" , "" , "<eventId> ::= STRING -- user event" , " | INT -- thread event" , " | \"GC\" -- garbage collection" , "" , "<filter> ::= <eventId> -- single event" , " | \"user\" -- any user event" , " | \"thread\" -- any thread event" , " | \"any\" \"[\" <filter> (\",\" <filter>)* \"]\"" , "" , "<sort> ::= \"total\"" , " | \"name\"" , "" , "The default script for the timed reports is\n" ] ++ indent (unparseScript defaultScriptTimed) ++ "\nThe default script for the totals report is\n\n" ++ indent (unparseScript defaultScriptTotals) ++ unlines [ "\nCustom scripts are useful extract different kinds of data from the" , "eventlog, or for presentation purposes." ] where indent :: [String] -> String indent = unlines . map (" " ++) -- | Select which output is active if no output is selected at all selectDefaultOutput :: Options -> Options selectDefaultOutput options@Options{..} = if noOutputSelected then options { optionsGenerateTotalsText = True , optionsGenerateTimedSVG = True , optionsGenerateTimedText = True } else options where noOutputSelected = not optionsGenerateTotalsText && not optionsGenerateTimedSVG && not optionsGenerateTimedText
WillSewell/ghc-events-analyze
src/GHC/RTS/Events/Analyze/Options.hs
bsd-3-clause
4,508
0
23
1,778
707
366
341
-1
-1
-- | This module provides the 'Complexity' and 'Certificate' type. -- The complexity and certificate types are fixed and represent a class of bounding functions for lower and upper -- timebounds as well as lower and upper spacebounds. module Tct.Core.Data.Certificate ( -- * Complexity Functions Complexity (..) , constant , linear -- * Semiring/Composition , compose -- , iter -- * Certificates , Certificate (..) , unbounded , isUnbounded -- * Setter/Getter , spaceUBCert , spaceLBCert , timeUBCert , timeLBCert , yesNoCert , updateSpaceUBCert , updateSpaceLBCert , updateTimeUBCert , updateTimeLBCert , updateYesNoCert ) where import Data.Monoid ((<>)) import qualified Tct.Core.Common.Pretty as PP import Tct.Core.Common.SemiRing import qualified Tct.Core.Common.Xml as Xml -- | Type for asymptotic complexity. -- The 'Ord' and 'SemiRing' instances are the expected one for asymptotic complexity. data Complexity = Poly (Maybe Int) -- ^ Polynomial. If argument is @Just k@, then -- @k@ gives the degree of the polynomial | Exp (Maybe Int) -- ^ Exponential. If argument is @Nothing@, then -- represented bounding function is elementary. If argument -- is @Just k@, then bounding function is k-exponential. -- Hence @Exp (Just 1)@ represents an exponential bounding -- function. | Supexp -- ^ Super exponential. | Primrec -- ^ Primitive recursive. | Multrec -- ^ Multiple recursive. | Rec -- ^ Recursive. | Unknown -- ^ Unknown. deriving (Eq, Show) -- | > constant = Poly (Just 0) constant :: Complexity constant = Poly (Just 0) -- | > linear = Poly (Just 1) linear :: Complexity linear = Poly (Just 1) rank :: Complexity -> (Int, Int) rank (Poly (Just r)) = (42,r) rank (Poly _) = (43,0) rank (Exp (Just r)) = (44,r) rank (Exp _) = (45,0) rank Supexp = (46,0) rank Primrec = (47,0) rank Multrec = (48,0) rank Rec = (49,0) rank Unknown = (142,0) instance Ord Complexity where c1 <= c2 = a1 < a2 || (a1 == a2 && b1 <= b2) where (a1,b1) = rank c1 (a2,b2) = rank c2 instance Additive Complexity where add = max zero = Poly (Just 0) instance Multiplicative Complexity where (Poly (Just n)) `mul` (Poly (Just m)) = Poly $ Just $ n + m (Poly Nothing) `mul` (Poly _) = Poly Nothing (Poly _) `mul` (Poly Nothing) = Poly Nothing (Exp (Just n)) `mul` (Exp (Just m)) = Exp $ Just $ max n m (Exp Nothing) `mul` (Exp _) = Exp Nothing a `mul` b = max a b one = Poly (Just 0) -- | Composition of asymptotic complexities. compose :: Complexity -> Complexity -> Complexity (Poly (Just n)) `compose` a | n == 0 = Poly (Just 0) | n == 1 = a a `compose` (Poly (Just m)) | m == 0 = Poly (Just 0) | m == 1 = a (Poly (Just n)) `compose` (Poly (Just m)) = Poly . Just $ n * m (Poly Nothing) `compose` (Poly _) = Poly Nothing (Poly _) `compose` (Poly Nothing) = Poly Nothing (Exp (Just n)) `compose` (Poly _) = Exp . Just $ n + 1 (Poly _) `compose` (Exp (Just m)) = Exp $ Just m (Exp (Just n)) `compose` (Exp (Just m)) = Exp . Just $ n + m (Exp Nothing) `compose` (Exp _) = Exp Nothing (Exp _) `compose` (Exp Nothing) = Exp Nothing a `compose` b = maximum [Primrec, a, b] {- iter :: Complexity -> Complexity -> Complexity (Poly (Just n)) `iter` _ | n == 0 = Poly $ Just 0 (Poly (Just n)) `iter` (Poly m) | n == 1 = case m of Just 0 -> Poly $ Just 1 Just 1 -> Exp $ Just 1 _ -> Exp $ Just 2 (Poly n) `iter` (Exp _) | n == Just 0 = Exp Nothing | n == Just 1 = Supexp | otherwise = Primrec (Poly _) `iter` b = max Primrec b (Exp _) `iter` (Poly m) | m == Just 0 = Exp Nothing | m == Just 1 = Supexp | otherwise = Primrec a `iter` b = maximum [Primrec, a, b] -} -- | A fixed type for the complexity 'Certificate'. data Certificate = Certificate { spaceUB :: Complexity , spaceLB :: Complexity , timeUB :: Complexity , timeLB :: Complexity } | CertificateYesNo { outcome :: Bool } deriving Show instance Additive Certificate where add c1@Certificate{} c2@Certificate{} = Certificate { spaceUB = spaceUB c1 `add` spaceUB c2 , spaceLB = spaceLB c1 `add` spaceLB c2 , timeUB = timeUB c1 `add` timeUB c2 , timeLB = timeLB c1 `add` timeLB c2 } add (CertificateYesNo c1) (CertificateYesNo c2) = CertificateYesNo (c1 || c2) add _ _ = error "Certificate types cannot be added. Corrupted strategy?!?" zero = Certificate zero zero zero zero instance Multiplicative Certificate where mul c1@Certificate{} c2@Certificate{} = Certificate { spaceUB = spaceUB c1 `mul` spaceUB c2 , spaceLB = spaceLB c1 `mul` spaceLB c2 , timeUB = timeUB c1 `mul` timeUB c2 , timeLB = timeLB c1 `mul` timeLB c2 } mul (CertificateYesNo c1) (CertificateYesNo c2) = CertificateYesNo (c1 && c2) mul _ _ = error "Certificate types cannot be multipled. Corrupted strategy?!?" one = Certificate zero zero zero zero -- | Defines the identity 'Certificate'. Sets all components to 'Unknown'. unbounded :: Certificate unbounded = Certificate { spaceUB = Unknown , spaceLB = Unknown , timeUB = Unknown , timeLB = Unknown } -- | Checks wether all components of the given certificate are 'Unknown'. isUnbounded :: Certificate -> Bool isUnbounded Certificate { spaceUB = Unknown , spaceLB = Unknown , timeUB = Unknown , timeLB = Unknown } = True isUnbounded _ = False -- | Constructs a 'Certificate' from the given 'Complexity'. -- Sets only the specified component; all others are set to 'Unknown'. spaceUBCert, spaceLBCert, timeUBCert, timeLBCert :: Complexity -> Certificate spaceUBCert c = unbounded { spaceUB = c } spaceLBCert c = unbounded { spaceLB = c } timeUBCert c = unbounded { timeUB = c } timeLBCert c = unbounded { timeLB = c } yesNoCert :: Bool -> Certificate yesNoCert = CertificateYesNo -- | Updates a component in the 'Certificate'. updateSpaceUBCert, updateSpaceLBCert, updateTimeUBCert, updateTimeLBCert :: Certificate -> (Complexity -> Complexity) -> Certificate updateSpaceUBCert cert f = cert { spaceUB = f $ spaceUB cert } updateSpaceLBCert cert f = cert { spaceLB = f $ spaceLB cert } updateTimeUBCert cert f = cert { timeUB = f $ timeUB cert } updateTimeLBCert cert f = cert { timeLB = f $ timeLB cert } updateYesNoCert :: Certificate -> (Bool -> Bool) -> Certificate updateYesNoCert cert f = cert { outcome = f $ outcome cert } --- * ProofData ------------------------------------------------------------------------------------------------------ instance PP.Pretty Complexity where pretty c = case c of (Poly (Just 0)) -> asym $ PP.text "1" (Poly (Just k)) -> asym $ PP.text "n" <> PP.char '^' <> PP.int k (Poly Nothing) -> PP.text "POLY" (Exp Nothing) -> PP.text "ELEM" (Exp (Just 1)) -> PP.text "EXP" (Exp (Just k)) -> PP.text "EXP-" <> PP.int k Supexp -> PP.text "SUPEXP" Primrec -> PP.text "PRIMREC" Multrec -> PP.text "MULTREC" Rec -> PP.text "REC" Unknown -> PP.char '?' where asym p = PP.char 'O' <> PP.parens p instance PP.Pretty Certificate where pretty (Certificate su sl tu tl) = PP.text "TIME (" <> PP.pretty tl <> PP.char ',' <> PP.pretty tu <> PP.char ')' PP.<$$> PP.text "SPACE(" <> PP.pretty sl <> PP.char ',' <> PP.pretty su <> PP.char ')' pretty (CertificateYesNo True) = PP.text "YES" pretty (CertificateYesNo False) = PP.text "NO" instance Xml.Xml Complexity where toXml c = case c of (Poly Nothing) -> Xml.elt "polynomial" [] (Poly (Just k)) -> Xml.elt "polynomial" [Xml.int k] (Exp Nothing) -> Xml.elt "exponential" [] (Exp (Just k)) -> Xml.elt "exponential" [Xml.int k] Supexp -> Xml.elt "superexponential" [] Primrec -> Xml.elt "primitiverecursive" [] Multrec -> Xml.elt "multiplerecursive" [] Rec -> Xml.elt "recursive" [] Unknown -> Xml.elt "unknown" [] toCeTA (Poly (Just k)) = Xml.elt "polynomial" [Xml.int k] toCeTA _ = Xml.unsupported
ComputationWithBoundedResources/tct-core
src/Tct/Core/Data/Certificate.hs
bsd-3-clause
8,406
0
16
2,209
2,572
1,364
1,208
164
1
-- | Provides lots of bas instances, pulled over from `Storable'. module Foreign.CStorable.BaseInstances where import Data.Word import Data.Int import Foreign.CStorable.TypeClass import Foreign.C.Types import Foreign.Storable import System.Posix.Types import Foreign.Ptr #define C(x) \ instance CStorable x where\ cPeek = peek;\ cPoke = poke;\ cAlignment = alignment;\ cSizeOf = sizeOf\ C(Bool) C(Char) C(Double) C(Float) C(Int) C(Int8) C(Int16) C(Int32) C(Int64) C(Word) C(Word8) C(Word16) C(Word32) C(Word64) C(CUIntMax) C(CIntMax) C(CUIntPtr) C(CIntPtr) C(CTime) C(CClock) C(CSigAtomic) C(CWchar) C(CSize) C(CPtrdiff) C(CDouble) C(CFloat) C(CULLong) C(CLLong) C(CULong) C(CLong) C(CUInt) C(CInt) C(CUShort) C(CShort) C(CUChar) C(CSChar) C(CChar) C(IntPtr) C(WordPtr) C(Fd) #ifndef mingw32_HOST_OS C(CRLim) C(CTcflag) C(CSpeed) C(CCc) C(CUid) C(CNlink) C(CGid) #endif C(CSsize) C(CPid) C(COff) C(CMode) C(CIno) C(CDev) -- TODO Figure out how to pull these types in {- C(CTimeval) C(Event) C(Event) C(PollFd) C((StablePtr a)) -} C((Ptr a)) C((FunPtr a))
maurer/c-storable-deriving
Foreign/CStorable/BaseInstances.hs
bsd-3-clause
1,082
0
8
152
558
261
297
-1
-1
-- ----------------------------------------------------------------------------- -- | -- Module : PixelParty.CmdLine -- Copyright : (c) Andreas-Christoph Bernstein 2011 -- License : BSD3-style (see LICENSE) -- -- Maintainer : [email protected] -- Stability : unstable -- Portability : not portable -- -- Command line options. -- -------------------------------------------------------------------------------- module PixelParty.CmdLine ( CmdLine(..) , cmdLine ) where import PixelParty.Types import System.Console.CmdArgs showVersion = "1.0.0" frag = Fragment { fshader = def &= args &= typ "FRAGMENTSHADER" , vshader = def &= help "Vertex Shader" &= typ "VERTEXSHADER" , gshader = def &= help "Geometry Shader" &= typ "GEOMETRYSHADER" , width = 600 &= typ "WIDTH" , height = 600 &= typ "HEIGHT" , include = def &= help "Include Path" &= typDir , tex = def &= help "Textures" &= typ "IMAGE" &= name "tex" } &= summary ("pixelparty v" ++ showVersion ++ ", (C) Andreas-C. Bernstein 2010-2011\n") &= program "pixelparty" cmdLine :: IO CmdLine cmdLine = cmdArgs frag
bernstein/pixelparty
src/PixelParty/CmdLine.hs
bsd-3-clause
1,126
0
12
200
222
124
98
17
1
module DataReferenceSpec (spec) where import Data.ByteString.IsoBaseFileFormat.Boxes import Data.ByteString.IsoBaseFileFormat.Util.BoxContent import Test.Hspec spec :: Spec spec = describe "IsBoxContent" $ describe "LocalMediaEntry" $ describe "boxSize" $ it "returns 0" $ let actual = boxSize localMediaDataReference expected = drefHeader + entryField + durlHeader drefHeader = boxHeader + fullHeader entryField = 4 durlHeader = boxHeader + fullHeader boxHeader = 4 + 4 fullHeader = 4 in actual `shouldBe` expected
sheyll/isobmff-builder
spec/DataReferenceSpec.hs
bsd-3-clause
643
0
11
192
137
76
61
18
1
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable -} module Fragment.Let ( module X ) where import Fragment.Let.Ast as X import Fragment.Let.Helpers as X
dalaing/type-systems
src/Fragment/Let.hs
bsd-3-clause
261
0
4
51
29
21
8
4
0
{-# LANGUAGE ScopedTypeVariables, FlexibleContexts #-} module Generics.SingleRec.Arbitrary where import Prelude hiding (sum) import Control.Monad import Control.Applicative -- import System.Random import Test.QuickCheck import Generics.SingleRec.Base import Generics.SingleRec.Fixpoints -- Applicative and alternative instances for the random number generator. instance Applicative Gen where (<*>) = ap pure = return instance Alternative Gen where a <|> b = oneof [a, b] empty = oneof [] -- Generically create arbitrary instances for arbitrary data types. data ArbParams a = AP { rec :: ArbParams a -> Int -> Gen a , divisor :: Int } class GArbitrary f where garbitrary' :: ArbParams a -> Int -> Gen (f a) gcoarbitrary' :: (Int -> a -> Gen (g b) -> Gen (g b)) -> Int -> f a -> Gen (g b) -> Gen (g b) instance GArbitrary Unit where garbitrary' _ _ = pure Unit gcoarbitrary' _ _ _ = id instance GArbitrary Id where garbitrary' p@(AP r d) t = Id <$> r p (t `div` d) gcoarbitrary' r o (Id a) = r o a instance Arbitrary a => GArbitrary (K a) where garbitrary' _ _ = K <$> arbitrary gcoarbitrary' _ _ (K a) = coarbitrary a instance (GFixpoints f, GFixpoints g, GArbitrary f, GArbitrary g) => GArbitrary (Sum f g) where garbitrary' p s = frequency [rec fpl Inl, rec fpr Inr] where rec a b = (fr a, b <$> garbitrary' p {divisor = sum a} s) (Node fpl fpr) = gfixpoints' (undefined :: Sum f g a) fr = foldTree (f s) (+) f 0 0 = 1 -- if our size (s) is zero, we only give non-recursive constructors a chance f 0 _ = 0 f _ x = x + 1 gcoarbitrary' r o (Inl f) = gcoarbitrary' r o f gcoarbitrary' r o (Inr f) = gcoarbitrary' r (o + sum fpl) f where (Node fpl _) = gfixpoints' (undefined :: Sum f g a) instance (GArbitrary f, GArbitrary g) => GArbitrary (Prod f g) where garbitrary' p s = Prod <$> garbitrary' p s <*> garbitrary' p s gcoarbitrary' r _ (Prod f g) = gcoarbitrary' r 0 f . gcoarbitrary' r 0 g instance GArbitrary f => GArbitrary (Con f) where garbitrary' p s = Con "" <$> garbitrary' p s gcoarbitrary' f o (Con _ c) = variant o . gcoarbitrary' f 0 c instance GArbitrary f => GArbitrary (F f) where garbitrary' p s = F <$> garbitrary' p s gcoarbitrary' f o (F c) = gcoarbitrary' f o c -- The first undefined gets filled in with garbitraryFix, the second in the instance for Sum. garbitrary :: (GArbitrary (PF a), PFView a) => Int -> Gen a garbitrary s = garbitraryHelper (AP undefined 1) s garbitraryHelper :: (PFView a, GArbitrary (PF a)) => ArbParams a -> Int -> Gen a garbitraryHelper p s = to <$> garbitrary' p {rec = garbitraryHelper} s
sebastiaanvisser/garbitrary
src/Generics/SingleRec/Arbitrary.hs
bsd-3-clause
2,685
0
14
626
1,058
535
523
54
1
{- | Module : $Header$ Description : Describes the generic util functions Copyright : None License : None Maintainer : [email protected] Stability : provisional The $Header$ module describes the generic util functions. -} module Utils ( distance, mean, rmdups ) where import Data.Char import qualified Data.Set as Set import Text.EditDistance import Types {-| Computes the Leveinshtein distance between two strings, using an integer to represent how many letter operations is needed to transform a word into the other word. -} distance :: String -> String -> Distance distance n1 n2 = let lower = map toLower ln1 = lower n1 ln2 = lower n2 in levenshteinDistance defaultEditCosts ln1 ln2 -- |Computes the arithmetic mean of the specified list of numbers, excluding one number. mean :: [Int] -> Int mean [] = 0 mean nbs = (sum nbs) `div` (length nbs) -- |Deletes the dupplicated values from the specified list. rmdups :: Ord a => [a] -> [a] rmdups = rmdups' Set.empty where rmdups' _ [] = [] rmdups' a (b:c) = if Set.member b a then rmdups' a c else b : rmdups' (Set.insert b a) c
Tydax/ou-sont-les-femmes
src/Utils.hs
bsd-3-clause
1,163
0
12
269
252
136
116
24
3
-- | -- Module : $Header$ -- Copyright : (c) 2013-2015 Galois, Inc. -- License : BSD3 -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} module Notebook where import Cryptol.REPL.Monad (REPL(..), runREPL) import qualified Cryptol.REPL.Monad as REPL import qualified Cryptol.Parser as P import qualified Cryptol.Parser.AST as P import Cryptol.Parser.Names (allNamesD, tnamesNT) import Cryptol.Parser.Position (Located(..), emptyRange) import Cryptol.Utils.PP (PP(..), pp, hang, text) import qualified Control.Exception as X import Control.Monad (ap) import Control.Monad.IO.Class (MonadIO(..)) import Data.IORef (IORef, newIORef, readIORef, modifyIORef) import qualified Data.Set as Set import Data.Typeable (Typeable) import Prelude.Compat -- Notebook Environment -------------------------------------------------------- -- | All of the top-level declarations along with all of the names -- that they define. We need to associate the names in order to remove -- declarations from the module context when they're overwritten. type NamedDecls = [([P.PName], P.TopDecl P.PName)] data RW = RW { eNamedDecls :: NamedDecls } -- | The default environment is simple now but might get more -- complicated, so it's made in IO. defaultRW :: IO RW defaultRW = return RW { eNamedDecls = [] } -- Notebook Monad -------------------------------------------------------------- -- | The Notebook is just a REPL augmented with an incrementally-built module. newtype NB a = NB { unNB :: IORef RW -> REPL a } instance Functor NB where {-# INLINE fmap #-} fmap f m = NB (\ref -> fmap f (unNB m ref)) instance Applicative NB where {-# INLINE pure #-} pure = return {-# INLINE (<*>) #-} (<*>) = ap instance Monad NB where {-# INLINE return #-} return x = NB (\_ -> return x) {-# INLINE (>>=) #-} m >>= f = NB $ \ref -> do x <- unNB m ref unNB (f x) ref -- | Run a NB action with a fresh environment. runNB :: NB a -> IO a runNB m = do ref <- newIORef =<< defaultRW let initialize = liftREPL $ do -- `let` is confusing in notebook context (see #163) REPL.disableLet -- turn of warning noise (#163) REPL.setUser "warnDefaulting" "no" REPL.setUser "warnShadowing" "no" runREPL True $ unNB (initialize >> m) ref -- | Lift a REPL action into the NB monad. liftREPL :: REPL a -> NB a liftREPL m = NB (\_ -> m) instance MonadIO NB where liftIO = io -- Primitives ------------------------------------------------------------------ io :: IO a -> NB a io m = liftREPL (REPL.io m) getRW :: NB RW getRW = NB (\ref -> REPL.io (readIORef ref)) modifyRW_ :: (RW -> RW) -> NB () modifyRW_ f = NB (\ref -> REPL.io (modifyIORef ref f)) getTopDecls :: NB NamedDecls getTopDecls = eNamedDecls `fmap` getRW setTopDecls :: NamedDecls -> NB () setTopDecls nds = modifyRW_ (\rw -> rw { eNamedDecls = nds }) modifyTopDecls :: (NamedDecls -> NamedDecls) -> NB NamedDecls modifyTopDecls f = do nds <- f `fmap` getTopDecls setTopDecls nds return nds -- Exceptions ------------------------------------------------------------------ -- | Notebook exceptions. data NBException = REPLException REPL.REPLException | AutoParseError P.ParseError deriving (Show, Typeable) instance X.Exception NBException instance PP NBException where ppPrec _ nbe = case nbe of REPLException exn -> pp exn AutoParseError exn -> hang (text "[error] Failed to parse cell as a module or as interactive input") 4 (pp exn) -- | Raise an exception raise :: NBException -> NB a raise exn = io (X.throwIO exn) -- | Catch an exception catch :: NB a -> (NBException -> NB a) -> NB a catch m k = NB (\ref -> REPL (\replRef -> unREPL (unNB m ref) replRef `X.catches` -- catch a REPLException or a NBException [ X.Handler $ \e -> unREPL (unNB (k (REPLException e)) ref) replRef , X.Handler $ \e -> unREPL (unNB (k e) ref) replRef ])) -- | Try running a possibly-excepting computation try :: NB a -> NB (Either NBException a) try m = catch (Right `fmap` m) (return . Left) -- | Try running the given action, printing any exceptions that arise. runExns :: NB () -> NB () runExns m = m `catch` \x -> io $ print $ pp x -- Module Manipulation --------------------------------------------------------- nbName :: P.Located P.ModName nbName = Located { srcRange = emptyRange , thing = "Notebook" } -- | Distill a module into a list of decls along with the names -- defined by those decls. modNamedDecls :: P.Module P.PName -> NamedDecls modNamedDecls m = [(tdNames td, td) | td <- P.mDecls m] -- | Build a module of the given name using the given list of -- declarations. moduleFromDecls :: P.Located P.ModName -> NamedDecls -> P.Module P.PName moduleFromDecls name nds = P.Module { P.mName = name , P.mImports = [] , P.mDecls = map snd nds } -- | In @updateNamedDecls old new = result@, @result@ is a -- right-biased combination of @old@ and @new@ with the following -- semantics: -- -- If a name @x@ is defined in @old@ and not @new@, or in @new@ and -- not @old@, all declarations of @x@ are in @result@. -- -- If a name @x@ is defined in both @old@ and @new@, /none/ of the -- declarations of @x@ from @old@ are in @result@, and all -- declarations of @x@ from @new@ are in @result@. updateNamedDecls :: NamedDecls -> NamedDecls -> NamedDecls updateNamedDecls old new = filteredOld ++ new where newNames = Set.fromList $ concat $ map fst new containsNewName = any (\x -> Set.member x newNames) filteredOld = filter (\(xs,_) -> not (containsNewName xs)) old -- | The names defined by a top level declaration tdNames :: P.TopDecl P.PName -> [P.PName] tdNames (P.Decl d) = map P.thing $ allNamesD $ P.tlValue d tdNames (P.TDNewtype d) = map P.thing $ fst $ tnamesNT $ P.tlValue d tdNames (P.Include _) = [] removeIncludes :: P.Module P.PName -> P.Module P.PName removeIncludes m = m { P.mDecls = decls' } where decls' = filter (not . isInclude) $ P.mDecls m isInclude (P.Include _) = True isInclude _ = False removeImports :: P.Module P.PName -> P.Module P.PName removeImports m = m { P.mImports = [] }
GaloisInc/ICryptol
src/Notebook.hs
bsd-3-clause
6,511
0
21
1,496
1,723
932
791
114
2
{-# LANGUAGE ScopedTypeVariables #-} module Matterhorn.Emoji ( EmojiCollection , loadEmoji , emptyEmojiCollection , getMatchingEmoji , matchesEmoji ) where import Prelude () import Matterhorn.Prelude import qualified Control.Exception as E import Control.Monad.Except import qualified Data.Aeson as A import qualified Data.ByteString.Lazy as BSL import qualified Data.Foldable as F import qualified Data.Text as T import qualified Data.Sequence as Seq import Network.Mattermost.Types ( Session ) import qualified Network.Mattermost.Endpoints as MM newtype EmojiData = EmojiData (Seq.Seq T.Text) -- | The collection of all emoji names we loaded from a JSON disk file. -- You might rightly ask: why don't we use a Trie here, for efficient -- lookups? The answer is that we need infix lookups; prefix matches are -- not enough. In practice it seems not to matter that much; despite the -- O(n) search we get good enough performance that we aren't worried -- about this. If at some point this becomes an issue, other data -- structures with good infix lookup performance should be identified -- (full-text search, perhaps?). newtype EmojiCollection = EmojiCollection [T.Text] instance A.FromJSON EmojiData where parseJSON = A.withArray "EmojiData" $ \v -> do aliasVecs <- forM v $ \val -> flip (A.withObject "EmojiData Entry") val $ \obj -> do as <- obj A..: "aliases" forM as $ A.withText "Alias list element" return return $ EmojiData $ mconcat $ F.toList aliasVecs emptyEmojiCollection :: EmojiCollection emptyEmojiCollection = EmojiCollection mempty -- | Load an EmojiCollection from a JSON disk file. loadEmoji :: FilePath -> IO (Either String EmojiCollection) loadEmoji path = runExceptT $ do result <- lift $ E.try $ BSL.readFile path case result of Left (e::E.SomeException) -> throwError $ show e Right bs -> do EmojiData es <- ExceptT $ return $ A.eitherDecode bs return $ EmojiCollection $ T.toLower <$> F.toList es -- | Look up matching emoji in the collection using the provided search -- string. This does a case-insensitive infix match. The search string -- may be provided with or without leading and trailing colons. lookupEmoji :: EmojiCollection -> T.Text -> [T.Text] lookupEmoji (EmojiCollection es) search = filter (matchesEmoji search) es -- | Match a search string against an emoji. matchesEmoji :: T.Text -- ^ The search string (will be converted to lowercase and -- colons will be removed) -> T.Text -- ^ The emoji string (assumed to be lowercase and without -- leading/trailing colons) -> Bool matchesEmoji searchString e = sanitizeEmojiSearch searchString `T.isInfixOf` e sanitizeEmojiSearch :: T.Text -> T.Text sanitizeEmojiSearch = stripColons . T.toLower . T.strip -- | Perform an emoji search against both the local EmojiCollection as -- well as the server's custom emoji. Return the results, sorted. If the -- empty string is specified, all local and all custom emoji will be -- included in the returned list. getMatchingEmoji :: Session -> EmojiCollection -> T.Text -> IO [T.Text] getMatchingEmoji session em rawSearchString = do let localAlts = lookupEmoji em rawSearchString sanitized = sanitizeEmojiSearch rawSearchString customResult <- E.try $ case T.null sanitized of True -> MM.mmGetListOfCustomEmoji Nothing Nothing session False -> MM.mmSearchCustomEmoji sanitized session let custom = case customResult of Left (_::E.SomeException) -> [] Right result -> result return $ sort $ (MM.emojiName <$> custom) <> localAlts stripColons :: T.Text -> T.Text stripColons t = stripHeadColon $ stripTailColon t where stripHeadColon v = if ":" `T.isPrefixOf` v then T.tail v else v stripTailColon v = if ":" `T.isSuffixOf` v then T.init v else v
matterhorn-chat/matterhorn
src/Matterhorn/Emoji.hs
bsd-3-clause
4,134
0
19
1,019
815
438
377
67
3
module Lang.Lam ( module Lang.Lam.Syntax , module Lang.Lam.Passes.B_CPSConvert ) where import Lang.Lam.Syntax import Lang.Lam.CPS.Syntax () import Lang.Lam.CPS.Classes.Delta () import Lang.Lam.CPS.Instances.Delta () import Lang.Lam.CPS.Instances.Monads () import Lang.Lam.CPS.Instances.PrettySyntax () import Lang.Lam.CPS.MonadicSemantics () import Lang.Lam.Analyses () import Lang.Lam.Passes.A_Stamp () import Lang.Lam.Passes.B_CPSConvert (cps, stampCPS)
davdar/quals
src/Lang/Lam.hs
bsd-3-clause
463
0
5
47
127
89
38
13
0
{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeOperators #-} module Numeric.Matrix.QRTest (runTests) where import Control.Monad (join) import Data.Kind import Data.Monoid (All (..)) import Numeric.Arbitraries import Numeric.DataFrame import Numeric.Dimensions import Numeric.Matrix.QR import Test.QuickCheck validateQR :: forall (t :: Type) (n :: Nat) (m :: Nat) . ( KnownDim n, KnownDim m , RealFloatExtras t, Show t ) => Matrix t n m -> QR t n m -> Property validateQR x q@QR {..} = counterexample (unlines [ "failed m =~= qrQ %* qrR:" , "m: " ++ show x , "m': " ++ show x' , "qr:" ++ show q ] ) (x =~= x') .&&. counterexample (unlines [ "qrQ is not quite orthogonal:" , "qr:" ++ show q , "m:" ++ show x ] ) (eye =~= qrQ %* transpose qrQ) .&&. counterexample (unlines [ "qrR is not upper-triangular" , "qr:" ++ show q , "m:" ++ show x ] ) (getAll $ iwfoldMap @t @'[n,m] (\(Idx i :* Idx j :* U) a -> All (j >= i || a <= tol)) qrR ) where tol = M_EPS * max 1 (maxElem x) x' = qrQ %* qrR validateLQ :: forall (t :: Type) (n :: Nat) (m :: Nat) . ( KnownDim n, KnownDim m , RealFloatExtras t, Show t ) => Matrix t n m -> LQ t n m -> Property validateLQ x q@LQ {..} = counterexample (unlines [ "failed m =~= lqL %* lqQ:" , "m: " ++ show x , "m': " ++ show x' , "lq:" ++ show q ] ) (x =~= x') .&&. counterexample (unlines [ "lqQ is not quite orthogonal:" , "lq:" ++ show q , "m:" ++ show x ] ) (eye =~= lqQ %* transpose lqQ) .&&. counterexample (unlines [ "lqL is not lower-triangular" , "lq:" ++ show q , "m:" ++ show x ] ) (getAll $ iwfoldMap @t @'[n,m] (\(Idx i :* Idx j :* U) a -> All (j <= i || a <= tol)) lqL ) where tol = M_EPS * max 1 (maxElem x) x' = lqL %* lqQ manualMats :: [DataFrame Double '[XN 1, XN 1]] manualMats = join [ [mkM $ D2 :* D2 :* U, mkM $ D5 :* D2 :* U, mkM $ D3 :* D7 :* U] <*> [repeat 0, repeat 1, repeat 2] , mkM (D2 :* D2 :* U) <$> variants [3,2, 4,1] , mkM (D3 :* D3 :* U) <$> variants [0,0,1, 3,2,0, 4,1,0] , mkM (D4 :* D2 :* U) <$> variants [3,2, 4,1, 0,0, 0,2] , mkM (D2 :* D3 :* U) <$> variants [3,2,0, 4,1,2] , mkM (D2 :* D2 :* U) <$> variants [2, 0, 0, 0] , mkM (D2 :* D2 :* U) <$> variants [4, 1, 0, 0] , mkM (D2 :* D2 :* U) <$> variants [3, 1, -2, 0] , [mkM $ D2 :* D3 :* U, mkM $ D3 :* D2 :* U] <*> join [ variants [2, 0, 0, 0, 0, 0] , variants [4, 1, 0, 0, 0, 0] , variants [3, 1, -2, 0, 0, 0] , variants [3, 0, -2, 9, 0, 0] ] ] where mkM :: Dims [n,m] -> [Double] -> DataFrame Double '[XN 1, XN 1] mkM ds | Just (XDims ds'@Dims) <- constrainDims ds :: Maybe (Dims '[XN 1, XN 1]) = XFrame . fromFlatList ds' 0 mkM _ = error "prop_qrSimple: bad dims" variants :: Num a => [a] -> [[a]] variants as = rotateList as ++ rotateList (map negate as) prop_lqSimple :: Property prop_lqSimple = once . conjoin $ map prop_lq manualMats prop_lq :: DataFrame Double '[XN 1, XN 1] -> Property prop_lq (XFrame x) | n@D :* m@D :* U <- dims `inSpaceOf` x , D <- minDim n m = validateLQ x (lq x) #if !MIN_VERSION_GLASGOW_HASKELL(8,10,0,0) prop_lq _ = property False #endif prop_qrSimple :: Property prop_qrSimple = once . conjoin $ map prop_qr manualMats prop_qr :: DataFrame Double '[XN 1, XN 1] -> Property prop_qr (XFrame x) | n@D :* m@D :* U <- dims `inSpaceOf` x , D <- minDim n m = validateQR x (qr x) #if !MIN_VERSION_GLASGOW_HASKELL(8,10,0,0) prop_qr _ = property False #endif testQRSolve :: forall t n m . (MatrixQR t n m, Show t, RealFloatExtras t) => Matrix t n m -> Vector t n -> Property testQRSolve a b = counterexample (unlines [ "failed a' %* (a %* xr - b) =~= 0" , "a: " ++ show a , "b: " ++ show b , "xr: " ++ show xr , "zeroR: " ++ show zeroR , "zeroL: " ++ show zeroL ] ) (nonDeficient ==> approxEq mag2 zeroR 0) .&&. counterexample (unlines [ "failed (xl %* a' - b) %* a =~= 0" , "a': " ++ show a' , "b: " ++ show b , "xl: " ++ show xl ] ) (nonDeficient ==> approxEq mag2 zeroL 0) .&&. counterexample (unlines [ "failed xr =~= xl" , "a': " ++ show a' , "b: " ++ show b , "xl: " ++ show xl ] ) (approxEq mag xr xl) where qrr = qrR (qr a) nonDeficient = foldl (\r i -> r && abs (qrr ! i ! i) > M_EPS * mag) True [0 .. min (dimVal' @n) (dimVal' @m) - 1] nm = totalDim (dims `inSpaceOf` a) mag = max 1 (maxElem a `max` maxElem b) * fromIntegral nm mag2 = mag*mag a' = transpose a xr = qrSolveR a b xl = qrSolveL a' b zeroR = a' %* (a %* xr - b) zeroL = (xl %* a' - b) %* a prop_qrSolve :: Dim (XN 1) -> Dim (XN 1) -> Property prop_qrSolve (Dx (D :: Dim n)) (Dx (D :: Dim m)) = property $ do a <- arbitrary @(DataFrame Double '[n,m]) b <- arbitrary @(DataFrame Double '[n]) return $ testQRSolve a b return [] runTests :: Int -> IO Bool runTests n = $forAllProperties $ quickCheckWithResult stdArgs { maxSuccess = n }
achirkin/easytensor
easytensor/test/Numeric/Matrix/QRTest.hs
bsd-3-clause
6,018
2
16
2,154
2,393
1,270
1,123
169
2
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} #include "thyme.h" -- | FOR INTERNAL USE ONLY. module Data.Thyme.Internal.Micro where import Prelude import Control.DeepSeq import Data.AdditiveGroup import Data.Basis import Data.Data import Data.Hashable import Data.Int import Data.Ix import Data.Ratio #if __GLASGOW_HASKELL__ == 704 import qualified Data.Vector.Generic import qualified Data.Vector.Generic.Mutable #endif import Data.Vector.Unboxed.Deriving import Data.VectorSpace import GHC.Generics (Generic) import System.Random import Test.QuickCheck #if !SHOW_INTERNAL import Control.Monad import Data.Char import Data.Thyme.Format.Internal import Numeric import Text.ParserCombinators.ReadPrec import Text.ParserCombinators.ReadP import Text.Read #endif newtype Micro = Micro Int64 deriving (INSTANCES_MICRO) derivingUnbox "Micro" [t| Micro -> Int64 |] [| \ (Micro a) -> a |] [| Micro |] #if SHOW_INTERNAL deriving instance Show Micro deriving instance Read Micro #else instance Show Micro where {-# INLINEABLE showsPrec #-} showsPrec _ (Micro a) = sign . shows si . frac where sign = if a < 0 then (:) '-' else id (si, su) = abs a `divMod` 1000000 frac = if su == 0 then id else (:) '.' . fills06 su . drops0 su instance Read Micro where {-# INLINEABLE readPrec #-} readPrec = lift $ do sign <- (char '-' >> return negate) `mplus` return id s <- readS_to_P readDec us <- (`mplus` return 0) $ do _ <- char '.' [(us10, "")] <- (readDec . take 7 . (++ "000000")) `fmap` munch1 isDigit return (div (us10 + 5) 10) return . Micro . sign $ s * 1000000 + us #endif {-# INLINE microQuotRem #-} {-# INLINE microDivMod #-} microQuotRem, microDivMod :: Micro -> Micro -> (Int64, Micro) microQuotRem (Micro a) (Micro b) = (n, Micro f) where (n, f) = quotRem a b microDivMod (Micro a) (Micro b) = (n, Micro f) where (n, f) = divMod a b instance AdditiveGroup Micro where {-# INLINE zeroV #-} zeroV = Micro 0 {-# INLINE (^+^) #-} (^+^) = \ (Micro a) (Micro b) -> Micro (a + b) {-# INLINE negateV #-} negateV = \ (Micro a) -> Micro (negate a) instance VectorSpace Micro where type Scalar Micro = Rational {-# INLINE (*^) #-} s *^ Micro a = Micro . fromInteger $ -- 'round'-to-even case compare (2 * abs r) (denominator s) of LT -> n EQ -> if even n then n else m GT -> m where (n, r) = quotRem (toInteger a * numerator s) (denominator s) m = if r < 0 then n - 1 else n + 1 instance HasBasis Micro where type Basis Micro = () {-# INLINE basisValue #-} basisValue = \ _ -> Micro 1000000 {-# INLINE decompose #-} decompose = \ (Micro a) -> [((), fromIntegral a % 1000000)] {-# INLINE decompose' #-} decompose' = \ (Micro a) _ -> fromIntegral a % 1000000
liyang/thyme
src/Data/Thyme/Internal/Micro.hs
bsd-3-clause
3,138
0
11
745
660
380
280
78
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} module FPNLA.Operations.LAPACK.Strategies.POTRF.BlocksSeq ( ) where import FPNLA.Matrix (Matrix, MatrixVector, cantCols_m, cantRows_m, elem_m, fromCols_vm, generate_m, subMatrix_m, toCols_vm, transpose_m) import FPNLA.Operations.BLAS (GEMM (gemm), SYRK (syrk), TRSM (trsm)) import FPNLA.Operations.LAPACK (POTRF (potrf)) import FPNLA.Operations.LAPACK.Strategies.DataTypes (CholLLVBlocksSeq, getSqrBlockDim) import FPNLA.Operations.Parameters (Elt, ResM, TransType (..), TriangType (..), UnitType (..), blasResultM, getResultDataM) import FPNLA.Utils (iif) import Debug.Trace (trace) instance (Elt e, MatrixVector m v e, POTRF potrfs m v e, SYRK syrks m v e, GEMM gemms m v e, TRSM trsms m v e) => POTRF (CholLLVBlocksSeq syrks gemms trsms potrfs) m v e where potrf _ (Upper _) = trace "potrf" undefined potrf ctx (Lower mA) = blasResultM $ chol_blk_l ctx 0 mA (generate_m 0 0 undefined) where chol_blk_l ctx@(block_ctx, syrk_ctx, gemm_ctx, trsm_ctx, potrf_ctx) k mA mAL | k == 0 = let mA11' = call_chol_unb (Lower mA11) mA21' = transpose_m $ call_trsm 1 (NoTrans . Lower $ NoUnit mA11') (transpose_m mA21) mAx1 = iif (k == cantBlocks - 1) mA11' $ concatByCol_m mA11' mA21' in chol_blk_l ctx (k + 1) mA mAx1 | k == cantBlocks = mAL | otherwise = chol_blk_l ctx (k + 1) mA mAL' where mA_dim = cantCols_m mA mA10 = subMatrix_m (block * k) 0 block (block*k) mAL mA11 = subMatrix_m (block * k) (block * k) block block mA mA11' = call_syrk (-1) (NoTrans mA10) 1 (Lower mA11) mA11'' = call_chol_unb (Lower mA11') mA20 = subMatrix_m ((k + 1) * block) 0 (mA_dim - (k + 1)*block) (k*block) mAL mA21 = subMatrix_m ((k + 1) * block) (k * block) (mA_dim - (k + 1)*block) block mA mA21' = call_gemm (NoTrans mA20) (Trans mA10) (-1) 1 mA21 mA21'' = transpose_m $ call_trsm 1 (NoTrans . Lower $ NoUnit mA11'') (transpose_m mA21') mAx1 = add_zeros k block . iif (k == cantBlocks - 1) mA11'' $ concatByCol_m mA11'' mA21'' mAL' = fromCols_vm $ (toCols_vm mAL :: [v e]) ++ (toCols_vm mAx1 :: [v e]) call_syrk m1 alpha beta m2 = getResultDataM (syrk syrk_ctx m1 alpha beta m2 :: ResM syrks v m e) call_chol_unb m = getResultDataM (potrf potrf_ctx m :: ResM potrfs v m e) call_gemm m1 m2 alpha beta m3 = getResultDataM (gemm gemm_ctx m1 m2 alpha beta m3 :: ResM gemms v m e) call_trsm alpha m1 m2 = getResultDataM (trsm trsm_ctx alpha m1 m2 :: ResM trsms v m e) add_zeros :: (Matrix m e) => Int -> Int -> m e -> m e add_zeros k block = concatByCol_m (generate_m (k*block) block (\_ _ -> 0) :: m e) block = getSqrBlockDim block_ctx cantBlocks = mA_dim `div` block concatByCol_m :: (Matrix m e) => m e -> m e -> m e concatByCol_m m1 m2 = let rows_m1 = cantRows_m m1 cols_m1 = cantCols_m m1 rows_m2 = cantRows_m m2 in generate_m (rows_m1 + rows_m2) cols_m1 (\i j -> iif (i >= rows_m1) (elem_m (i - rows_m1) j m2) (elem_m i j m1))
mauroblanco/fpnla-examples
src/FPNLA/Operations/LAPACK/Strategies/POTRF/BlocksSeq.hs
bsd-3-clause
5,137
0
17
2,710
1,284
682
602
67
1
-- Thomas' misc utils (things that are missing in the standard libraries) module MUtils where import Monad(ap,unless,when) import List(groupBy,sortBy,sort) import Maybe(fromMaybe) --import ExceptM() -- all eta expansions because of the stupid monomorphism restriction infixl 1 #,#.,<#,@@, >#< -- Infix versions of two essential operators: f # x = fmap f x mf <# mx = ap mf mx --Kleisli composition, another essential operator, sadly lacking from the --Haskell 98 libraries: m1 @@ m2 = \ x -> m1 =<< m2 x f #. m = \ x -> f # m x done :: Monad m => m () done = return () unlessM m1 m2 = do b <- m1 unless b m2 whenM m1 m2 = do b <- m1 when b m2 ifM bM tM eM = do b <- bM; if b then tM else eM aM &&& bM = ifM aM bM (return False) andM ms = foldr (&&&) (return True) ms allM p = andM . map p seqMaybe m = maybe (return Nothing) (Just # ) m -- Property: f # x == return f <# x (f >#< g) (x,y) = (,) # f x <# g y mapFstM f = mapM (apFstM f) apFstM f (x,y) = flip (,) y # f x mapSndM f = mapM (apSndM f) apSndM f (x,y) = (,) x # f y concatMapM f xs = concat # mapM f xs mapFst f = map (apFst f) mapSnd f = map (apSnd f) apSnd f (x,y) = (x,f y) apFst f (x,y) = (f x,y) mapBoth f = map (apBoth f) apBoth f (x,y) = (f x,f y) dup x = (x,x) pairWith f x = (x,f x) -- pairWith f = apSnd f . dup mapPartition f [] = ([],[]) mapPartition f (x:xs) = either (apFst.(:)) (apSnd.(:)) (f x) (mapPartition f xs) collectBySnd x = map pick . groupBy eqSnd . sortBy cmpSnd $ x where pick xys@((_,y):_) = ({-sort $-} map fst xys,y) collectByFst x = map swap . collectBySnd . map swap $ x onFst f (x1,_) (x2,_) = f x1 x2 onSnd f (_,y1) (_,y2) = f y1 y2 cmpFst x = onFst compare x cmpSnd x = onSnd compare x eqFst x = onFst (==) x eqSnd x = onSnd (==) x swap (x,y) = (y,x) mapEither f g = either (Left . f) (Right . g) seqEither x = either (Left # ) (Right # ) x -- squeezeDups removes adjacent duplicates (cheaper than nub): squeezeDups (r1:rrs@(r2:_)) = if r1==r2 then squeezeDups rrs else r1:squeezeDups rrs squeezeDups rs = rs usort xs = squeezeDups (sort xs) read' s = read'' "MUtils.read'" s read'' msg s = case reads s of [(x,r)] | readAtEnd r -> x [] -> error $ msg++" no parse: "++take 60 s _ -> error $ msg++" ambiguous parse: "++take 60 s readAtEnd r = lex r == [("","")] fromJust' = fromMaybe . error --instance Functor ((->) a) where fmap = (.) {- instance Functor (Either err) where fmap = mapEither id instance Monad (Either err) where return = Right Left err >>= _ = Left err Right ans >>= m = m ans -}
forste/haReFork
tools/base/lib/MUtils.hs
bsd-3-clause
2,593
7
11
630
1,224
636
588
64
3
module Lichen.Plagiarism.WinnowSpec where import Lichen.Plagiarism.Winnow import qualified Data.List.NonEmpty as NE import Text.Megaparsec import Test.Hspec import Test.QuickCheck import Lichen.Lexer prop_windows_size :: Int -> [Int] -> Bool prop_windows_size k l | k > 0 && k <= length l = case windows k l of Just ws -> all (\x -> NE.length x == k) ws Nothing -> False | otherwise = case windows k l of Just _ -> False; Nothing -> True prop_windows_count :: Int -> [Int] -> Bool prop_windows_count k l | k > 0 && k <= length l = case windows k l of Just ws -> length ws == length l - k + 1 Nothing -> False | otherwise = case windows k l of Just _ -> False; Nothing -> True instance Arbitrary TokPos where arbitrary = TokPos <$> (unsafePos <$> (getPositive <$> (arbitrary :: Gen (Positive Word)))) <*> (unsafePos <$> (getPositive <$> (arbitrary :: Gen (Positive Word)))) <*> (unsafePos <$> (getPositive <$> (arbitrary :: Gen (Positive Word)))) <*> (unsafePos <$> (getPositive <$> (arbitrary :: Gen (Positive Word)))) instance Arbitrary a => Arbitrary (Tagged a) where arbitrary = Tagged <$> arbitrary <*> arbitrary prop_hashWin_bounds :: NE.NonEmpty (Tagged Int) -> Bool prop_hashWin_bounds l = let r = hashWin l in startLine (tpos r) == startLine (tpos $ NE.head l) && startCol (tpos r) == startCol (tpos $ NE.head l) && endLine (tpos r) == endLine (tpos $ NE.last l) && endCol (tpos r) == endCol (tpos $ NE.last l) spec :: Spec spec = do describe "windows k l" $ do it "produces windows of length k for positive k less than length of l" $ property prop_windows_size it "produces length l - k + 1 windows" $ property prop_windows_count describe "hashWin l" $ it "yields a fingerprint with the same bounds as the window l" $ property prop_hashWin_bounds
Submitty/AnalysisTools
test/Lichen/Plagiarism/WinnowSpec.hs
bsd-3-clause
2,289
0
18
837
703
349
354
35
3
module Name ( Name(..), name, freshName, freshNames ) where import Utilities import Data.Char import Data.Function import Data.Ord data Name = Name { name_string :: String, name_id :: Maybe Id } instance NFData Name where rnf (Name a b) = rnf a `seq` rnf b instance Show Name where show n = "(name " ++ show (show (pPrint n)) ++ ")" instance Eq Name where (==) = (==) `on` name_key instance Ord Name where compare = comparing name_key instance Pretty Name where pPrintPrec level _ n = text (escape $ name_string n) <> maybe empty (\i -> text "_" <> text (show i)) (name_id n) where escape | level == haskellLevel = concatMap escapeHaskellChar | otherwise = id escapeHaskellChar c | c == 'z' = "zz" | isAlphaNum c || c `elem` ['_', '\''] = [c] | otherwise = 'z' : show (ord c) name_key :: Name -> Either String Id name_key n = maybe (Left $ name_string n) Right (name_id n) name :: String -> Name name s = Name s Nothing freshName :: IdSupply -> String -> (IdSupply, Name) freshName ids s = second (Name s . Just) $ stepIdSupply ids freshNames :: IdSupply -> [String] -> (IdSupply, [Name]) freshNames = mapAccumL freshName
batterseapower/supercompilation-by-evaluation
Name.hs
bsd-3-clause
1,321
0
13
403
501
261
240
34
1
module Data.GI.GIR.Deprecation ( DeprecationInfo(..) , queryDeprecated ) where import qualified Data.Map as M import Data.Text (Text) import Text.XML (Element(elementAttributes)) import Data.GI.GIR.XMLUtils (firstChildWithLocalName, getElementContent) -- | Deprecation information on a symbol. data DeprecationInfo = DeprecationInfo { deprecatedSinceVersion :: Maybe Text, deprecationMessage :: Maybe Text } deriving (Show, Eq) -- | Parse the deprecation information for the given element of the GIR file. queryDeprecated :: Element -> Maybe DeprecationInfo queryDeprecated element = case M.lookup "deprecated" attrs of Just _ -> let version = M.lookup "deprecated-version" attrs msg = firstChildWithLocalName "doc-deprecated" element >>= getElementContent in Just (DeprecationInfo version msg) Nothing -> Nothing where attrs = elementAttributes element
ford-prefect/haskell-gi
lib/Data/GI/GIR/Deprecation.hs
lgpl-2.1
972
0
13
222
206
115
91
20
2
-- | Provides uniformMatrix functions with Linear. module UniformLinear ( uniformMatrix2fv , uniformMatrix3fv , uniformMatrix4fv , uniformMatrix2x3fv , uniformMatrix3x2fv , uniformMatrix2x4fv , uniformMatrix4x2fv , uniformMatrix3x4fv , uniformMatrix4x3fv ) where import Graphics.Rendering.OpenGL import Graphics.Rendering.OpenGL.Raw import Foreign.Ptr import Foreign.Marshal.Array import Foreign.Marshal.Utils import Linear -- | Returns the length of a list as a value of GLsizei. len :: [a] -> GLsizei len = fromIntegral . length -- | Specifies the value of a uniform variable which is an array of 2 rows and 2 columns matrix for the current program object. uniformMatrix2fv :: UniformLocation -> SettableStateVar [M22 GLfloat] uniformMatrix2fv (UniformLocation loc) = makeSettableStateVar (\mats -> withArray mats ((glUniformMatrix2fv loc (len mats) 1) . castPtr)) -- | Specifies the value of a uniform variable which is an array of 3 rows and 3 columns matrix for the current program object. uniformMatrix3fv :: UniformLocation -> SettableStateVar [M33 GLfloat] uniformMatrix3fv (UniformLocation loc) = makeSettableStateVar (\mats -> withArray mats ((glUniformMatrix3fv loc (len mats) 1) . castPtr)) -- | Specifies the value of a uniform variable which is an array of 4 rows and 4 columns matrix for the current program object. uniformMatrix4fv :: UniformLocation -> SettableStateVar [M44 GLfloat] uniformMatrix4fv (UniformLocation loc) = makeSettableStateVar (\mats -> withArray mats ((glUniformMatrix4fv loc (len mats) 1) . castPtr)) -- | Specifies the value of a uniform variable which is an array of 3 rows and 2 columns matrix for the current program object. uniformMatrix3x2fv :: UniformLocation -> SettableStateVar [V3 (V2 GLfloat)] uniformMatrix3x2fv (UniformLocation loc) = makeSettableStateVar (\mats -> withArray mats ((glUniformMatrix2x3fv loc (len mats) 1) . castPtr)) -- | Specifies the value of a uniform variable which is an array of 2 rows and 3 columns matrix for the current program object. uniformMatrix2x3fv :: UniformLocation -> SettableStateVar [V2 (V3 GLfloat)] uniformMatrix2x3fv (UniformLocation loc) = makeSettableStateVar (\mats -> withArray mats ((glUniformMatrix3x2fv loc (len mats) 1) . castPtr)) -- | Specifies the value of a uniform variable which is an array of 4 rows and 2 columns matrix for the current program object. uniformMatrix4x2fv :: UniformLocation -> SettableStateVar [V4 (V2 GLfloat)] uniformMatrix4x2fv (UniformLocation loc) = makeSettableStateVar (\mats -> withArray mats ((glUniformMatrix2x4fv loc (len mats) 1) . castPtr)) -- | Specifies the value of a uniform variable which is an array of 2 rows and 4 columns matrix for the current program object. uniformMatrix2x4fv :: UniformLocation -> SettableStateVar [V2 (V4 GLfloat)] uniformMatrix2x4fv (UniformLocation loc) = makeSettableStateVar (\mats -> withArray mats ((glUniformMatrix4x2fv loc (len mats) 1) . castPtr)) -- | Specifies the value of a uniform variable which is an array of 4 rows and 3 columns matrix for the current program object. uniformMatrix4x3fv :: UniformLocation -> SettableStateVar [V4 (V3 GLfloat)] uniformMatrix4x3fv (UniformLocation loc) = makeSettableStateVar (\mats -> withArray mats ((glUniformMatrix3x4fv loc (len mats) 1) . castPtr)) -- | Specifies the value of a uniform variable which is an array of 3 rows and 4 columns matrix for the current program object. uniformMatrix3x4fv :: UniformLocation -> SettableStateVar [V3 (V4 GLfloat)] uniformMatrix3x4fv (UniformLocation loc) = makeSettableStateVar (\mats -> withArray mats ((glUniformMatrix4x3fv loc (len mats) 1) . castPtr))
fujiyan/toriaezuzakki
haskell/opengl/uniform-matrix/UniformLinear.hs
bsd-2-clause
3,677
0
14
564
773
409
364
36
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module NanoML.Learn where import Control.Arrow (second) import Control.Monad import Data.Aeson import qualified Data.ByteString.Lazy as LBS import qualified Data.Csv as CSV import Data.Function import Data.List import qualified Data.List as List import Data.Maybe import qualified Data.Set as Set import qualified Data.Vector as V import GHC.Generics -- import Grenade import Numeric.LinearAlgebra hiding (rank) import Text.Read import NanoML.Classify import NanoML.Monad import NanoML.Types rankExprs :: Net -> [Feature] -> Prog -> [(Confidence, Constraint)] rankExprs net fs p = second getThing <$!> rank net samples where samples = [ s {getThing = c} | s <- concatMap mkfsD tbad , c <- maybeToList (List.find (\c -> getThing s == fromJust (constraintSpan c)) cores) ] (tbad, cores, me) = case runEval stdOpts (typeProg p) of Left e -> ([], [], Just e) Right (tp, cs) -> (tp, Set.toList (mconcat cs), Nothing) mkfsD (TDFun _ _ pes) = mconcat (map (mkTypeOut . snd) pes) mkfsD (TDEvl _ e) = mkTypeOut e mkfsD _ = mempty -- inSlice s = any (\c -> getSpan s == fromJust (constraintSpan c)) cores -- mkTypeOut :: TExpr -> [Sample ()] mkTypeOut te = ctfold f [] te where f p e acc = (:acc) $ MkSample { getThing = infoSpan (texprInfo e) , getSample = vector $ concatMap (\(_,c) -> c p e) fs } stdNet :: IO (Net, [Feature]) stdNet = loadNet "models/op+context+type-hidden-500.json" >>= \case Nothing -> fail "could not decode 'models/op+context+type-hidden-500.json'" Just net -> return (net, preds_tis ++ map only_ctx preds_tis_ctx ++ preds_tcon_ctx) data Prediction = Change | NoChange deriving (Eq, Show) -- predict :: Net -> Sample -> Prediction -- predict = undefined type Confidence = Double rank :: Net -> [Sample a] -> [(Confidence, Sample a)] rank net samples = sortBy (flip compare `on` fst) [ (r ! 1, s) | s <- samples , let r = runNet net (getSample s) ] data Net = MkNet { hidden :: [Weights] , output :: Weights } deriving (Eq, Show, Generic) instance FromJSON Net data Weights = MkWeights { weights :: Matrix Double , biases :: Vector Double } deriving (Eq, Show, Generic) instance FromJSON Weights where parseJSON = withObject "Weights" $ \v -> MkWeights <$> fmap mkmatrix (v .: "weights") <*> fmap vector (v .: "biases") where mkmatrix (ws :: [[Double]]) = matrix (length $ head ws) (concat ws) loadNet :: FilePath -> IO (Maybe Net) loadNet file = decode <$> LBS.readFile file runNet :: Net -> Vector Double -> Vector Double runNet MkNet{..} features = softmax (runLayer (foldl' runHidden features hidden) output) where runHidden fs ws = relu $ runLayer fs ws runLayer fs MkWeights{..} = fs <# weights + biases relu :: Vector Double -> Vector Double relu v = cmap (\x -> max 0 x) v softmax :: Vector Double -> Vector Double softmax v = cmap (\x -> exp x / summed) v where summed = sumElements (cmap exp v) data Sample a = MkSample { getThing :: a, getSample :: Vector Double } deriving (Eq, Show, Generic) instance CSV.FromRecord (Sample SrcSpan) where parseRecord r = MkSample <$> (maybe mzero return . readMaybe =<< CSV.parseField (r V.! 0)) <*> fmap vector (CSV.parseRecord (V.drop 4 r)) loadSamples :: FilePath -> IO (Either String (V.Vector (Sample SrcSpan))) loadSamples file = CSV.decode CSV.HasHeader <$> LBS.readFile file -- net2network :: Net -> Network ts ds -- net2network MkNet{..} = foldr addLayer NNil (output : reverse hidden) -- addLayer :: Weights -> Network ts ds -- -> Network (FullyConnected dx dy : Relu : ts) (d : d : ds) -- addLayer ws net = mkLayer ws :~> Relu :~> net
ucsd-progsys/nanomaly
src/NanoML/Learn.hs
bsd-3-clause
4,013
0
18
873
1,316
705
611
89
4
module Distribution.Nixpkgs.Haskell.Hackage ( readHashedHackage, module Distribution.Hackage.DB ) where import Data.ByteString.Lazy ( ByteString ) import Data.Digest.Pure.SHA ( sha256, showDigest ) import Distribution.Hackage.DB import qualified Distribution.Hackage.DB.Parsed as Unparsed ( parsePackage ) import qualified Distribution.Hackage.DB.Unparsed as Unparsed -- | A variant of 'readHackage' that adds the SHA256 digest of the -- original Cabal file to the parsed 'GenericPackageDescription'. That -- hash is required to build packages with an "edited" cabal file, -- because Nix needs to download the edited file and patch it into the -- original tarball. readHashedHackage :: IO Hackage readHashedHackage = fmap parseUnparsedHackage Unparsed.readHackage where parseUnparsedHackage :: Unparsed.Hackage -> Hackage parseUnparsedHackage = mapWithKey (mapWithKey . parsePackage) parsePackage :: String -> Version -> ByteString -> GenericPackageDescription parsePackage name version buf = let pkg = Unparsed.parsePackage name version buf hash = showDigest (sha256 buf) in pkg { packageDescription = (packageDescription pkg) { customFieldsPD = ("X-Cabal-File-Hash", hash) : customFieldsPD (packageDescription pkg) } }
psibi/cabal2nix
src/Distribution/Nixpkgs/Haskell/Hackage.hs
bsd-3-clause
1,315
0
16
244
234
138
96
16
1
{-# LANGUAGE CPP #-} module Bead.Config.Configuration ( InitTask(..) , Config(..) #ifdef SSO , SSOLoginConfig(..) , sSOLoginConfig #else , StandaloneLoginConfig(..) , standaloneLoginConfig #endif , defaultConfiguration , configCata , Usage(..) , substProgName #ifdef MYSQL , MySQLConfig(..) #else , FilePersistConfig(..) #endif ) where import System.FilePath (joinPath) import System.Directory (doesFileExist) import Bead.Domain.Types (readMaybe) -- Represents initalizer tasks to do before launch the service data InitTask = CreateAdmin deriving (Show, Eq) -- * Configuration -- Represents the hostname (and/or port) of the bead server type Hostname = String type Second = Int -- Represents the system parameters stored in a -- configuration file data Config = Config { -- Place of log messages coming from the UserStory layer -- Entries about the actions performed by the user userActionLogFile :: FilePath -- Session time out on the client side, the lifetime of a valid -- value stored in cookies. Measured in seconds, nonnegative value , sessionTimeout :: Second #ifdef EmailEnabled -- The hostname of the server, this hostname is placed in the registration emails , emailHostname :: Hostname -- The value for from field for every email sent by the system , emailFromAddress :: String #endif -- The default language of the login page if there is no language set in the session , defaultLoginLanguage :: String -- The default timezone for a newly registered user , defaultRegistrationTimezone :: String -- The directory where all the timezone informations can be found -- Eg: /usr/share/zoneinfo/ , timeZoneInfoDirectory :: FilePath -- The maximum upload size of a file given in Kbs , maxUploadSizeInKb :: Int -- Simple login configuration #ifdef SSO , loginConfig :: SSOLoginConfig #else , loginConfig :: StandaloneLoginConfig #endif #ifdef MYSQL , persistConfig :: MySQLConfig #else , persistConfig :: FilePersistConfig #endif } deriving (Eq, Show, Read) #ifdef EmailEnabled configCata fcfg f (Config useraction timeout host from dll dtz tz up cfg pcfg) = f useraction timeout host from dll dtz tz up (fcfg cfg) pcfg #else configCata fcfg f (Config useraction timeout dll dtz tz up cfg pcfg) = f useraction timeout dll dtz tz up (fcfg cfg) pcfg #endif #ifdef MYSQL data MySQLConfig = MySQLConfig { mySQLDbName :: String , mySQLHost :: String , mySQLPort :: Int , mySQLUser :: String , mySQLPass :: String , mySQLPoolSize :: Int } deriving (Eq, Read, Show) #else data FilePersistConfig = FilePersistConfig deriving (Eq, Read, Show) #endif #ifdef SSO -- Login configuration that is used in single sign-on (SSO) data SSOLoginConfig = SSOLoginConfig { -- Query timeout (in seconds) sSOTimeout :: Int -- Number of query threads , sSOThreads :: Int -- A format string that tells how to query LDAP attributes -- on the given system , sSOQueryCommand :: String -- Key for UserID in LDAP , sSOUserIdKey :: String -- Key for the user's full name in LDAP , sSOUserNameKey :: String -- Key for the user's email address in LDAP , sSOUserEmailKey :: String -- Enable login through a direct link, without SSO , sSODeveloperMode :: Bool } deriving (Eq, Show, Read) sSOLoginConfig f (SSOLoginConfig timeout threads cmd uik unk uek dev) = f timeout threads cmd uik unk uek dev #else -- Login configuration that is used in standalone registration and login mode data StandaloneLoginConfig = StandaloneLoginConfig { -- The default regular expression for the user registration usernameRegExp :: String -- The example that satisfies the given regexp for the username. These are -- rendered to the user as examples on the GUI. , usernameRegExpExample :: String } deriving (Eq, Show, Read) standaloneLoginConfig f (StandaloneLoginConfig reg exp) = f reg exp #endif -- The defualt system parameters defaultConfiguration = Config { userActionLogFile = joinPath ["log", "useractions.log"] , sessionTimeout = 1200 #ifdef EmailEnabled , emailHostname = "http://127.0.0.1:8000" , emailFromAddress = "[email protected]" #endif , defaultLoginLanguage = "en" , defaultRegistrationTimezone = "UTC" , timeZoneInfoDirectory = "/usr/share/zoneinfo" , maxUploadSizeInKb = 128 , loginConfig = defaultLoginConfig , persistConfig = defaultPersistConfig } defaultLoginConfig = #ifdef SSO SSOLoginConfig { sSOTimeout = 5 , sSOThreads = 4 , sSOQueryCommand = "ldapsearch" , sSOUserIdKey = "uid" , sSOUserNameKey = "name" , sSOUserEmailKey = "email" , sSODeveloperMode = False } #else StandaloneLoginConfig { usernameRegExp = "^[A-Za-z0-9]{6}$" , usernameRegExpExample = "QUER42" } #endif #ifdef MYSQL defaultPersistConfig = MySQLConfig { mySQLDbName = "bead" , mySQLHost = "localhost" , mySQLPort = 3306 , mySQLUser = "root" , mySQLPass = "password" , mySQLPoolSize = 30 } #else defaultPersistConfig = FilePersistConfig #endif readConfiguration :: FilePath -> IO Config readConfiguration path = do exist <- doesFileExist path case exist of False -> do putStrLn "Configuration file does not exist" putStrLn "!!! DEFAULT CONFIGURATION IS USED !!!" return defaultConfiguration True -> do content <- readFile path case readMaybe content of Nothing -> do putStrLn "Configuration is not parseable" putStrLn "!!! DEFAULT CONFIGURATION IS USED !!!" return defaultConfiguration Just c -> return c -- Represents a template for the usage message newtype Usage = Usage (String -> String) instance Show Usage where show _ = "Usage (...)" instance Eq Usage where _ == _ = False usageFold :: ((String -> String) -> a) -> Usage -> a usageFold g (Usage f) = g f -- Produces an usage string, substituting the given progname into the template substProgName :: String -> Usage -> String substProgName name = usageFold ($ name)
pgj/bead
src/Bead/Config/Configuration.hs
bsd-3-clause
6,138
0
17
1,338
909
545
364
76
3
module MoveDefSpec (main, spec) where import Test.Hspec import Language.Haskell.Refact.Refactoring.MoveDef import System.Directory import TestUtils -- --------------------------------------------------------------------- main :: IO () main = do hspec spec spec :: Spec spec = do -- ------------------------------------------------------------------- describe "liftToTopLevel" $ do it "cannot lift a top level declaration" $ do -- res <- catchException (liftToTopLevel logTestSettings testOptions "./test/testdata/MoveDef/Md1.hs" (4,1)) res <- catchException (ct $ liftToTopLevel defaultTestSettings testOptions "./MoveDef/Md1.hs" (4,1)) (show res) `shouldBe` "Just \"\\nThe identifier is not a local function/pattern name!\"" -- --------------------------------- it "checks for name clashes" $ do -- res <- catchException (doLiftToTopLevel ["./test/testdata/MoveDef/Md1.hs","17","5"]) res <- catchException (liftToTopLevel defaultTestSettings testOptions "./test/testdata/MoveDef/Md1.hs" (17,5)) (show res) `shouldBe` "Just \"The identifier(s): (ff, test/testdata/MoveDef/Md1.hs:17:5) will cause name clash/capture or ambiguity occurrence problem after lifting, please do renaming first!\"" {- it "checks for invalid new name" $ do res <- catchException (doDuplicateDef ["./test/testdata/DupDef/Dd1.hs","$c","5","1"]) (show res) `shouldBe` "Just \"Invalid new function name:$c!\"" it "notifies if no definition selected" $ do res <- catchException (doDuplicateDef ["./test/testdata/DupDef/Dd1.hs","ccc","14","13"]) (show res) `shouldBe` "Just \"The selected identifier is not a function/simple pattern name, or is not defined in this module \"" -} -- --------------------------------- it "lifts a definition to the top level" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/MoveDef/Md1.hs" (24,5) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/MoveDef/Md1.hs" (24,5) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/MoveDef/Md1.hs\"]" diff <- compareFiles "./test/testdata/MoveDef/Md1.hs.expected" "./test/testdata/MoveDef/Md1.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel D1 C1 A1 8 6" $ do r <- ct $ liftToTopLevel defaultTestSettings testOptions "./LiftToToplevel/D1.hs" (8,6) -- r <- ct $ liftToTopLevel logTestSettings testOptions "./LiftToToplevel/D1.hs" (8,6) r' <- ct $ mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"LiftToToplevel/D1.hs\",\"LiftToToplevel/C1.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/D1.hs.expected" "./test/testdata/LiftToToplevel/D1.refactored.hs" diff `shouldBe` [] diff2 <- compareFiles "./test/testdata/LiftToToplevel/C1.hs.expected" "./test/testdata/LiftToToplevel/C1.refactored.hs" diff2 `shouldBe` [] a1Refactored <- doesFileExist "./test/testdata/LiftToToplevel/A1.refactored.hs" a1Refactored `shouldBe` False -- --------------------------------- it "liftToTopLevel D2 C2 A2 8 6" $ do r <- ct $ liftToTopLevel defaultTestSettings testOptions "./LiftToToplevel/D2.hs" (8,6) r' <- ct $ mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"LiftToToplevel/D2.hs\",\"LiftToToplevel/C2.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/D2.hs.expected" "./test/testdata/LiftToToplevel/D2.refactored.hs" diff `shouldBe` [] diff2 <- compareFiles "./test/testdata/LiftToToplevel/C2.hs.expected" "./test/testdata/LiftToToplevel/C2.refactored.hs" diff2 `shouldBe` [] a1Refactored <- doesFileExist "./test/testdata/LiftToToplevel/A2.refactored.hs" a1Refactored `shouldBe` False -- --------------------------------- it "liftToTopLevel D3 C3 A3 8 6" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/D3.hs" (8,6) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/D3.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/D3.hs.expected" "./test/testdata/LiftToToplevel/D3.refactored.hs" diff `shouldBe` [] c3Refactored <- doesFileExist "./test/testdata/LiftToToplevel/C3.refactored.hs" c3Refactored `shouldBe` False a3Refactored <- doesFileExist "./test/testdata/LiftToToplevel/A3.refactored.hs" a3Refactored `shouldBe` False -- --------------------------------- it "liftToTopLevel WhereIn1 12 18" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/WhereIn1.hs" (12,18) -- r <- liftToTopLevel logTestSettings testOptions Nothing "./test/testdata/LiftToToplevel/WhereIn1.hs" (12,18) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/WhereIn1.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/WhereIn1.hs.expected" "./test/testdata/LiftToToplevel/WhereIn1.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel WhereIn6 13 29" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/WhereIn6.hs" (13,29) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/WhereIn6.hs" (13,29) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/WhereIn6.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/WhereIn6.hs.expected" "./test/testdata/LiftToToplevel/WhereIn6.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel WhereIn7 12 14" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/WhereIn7.hs" (12,14) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/WhereIn7.hs" (12,14) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/WhereIn7.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/WhereIn7.hs.expected" "./test/testdata/LiftToToplevel/WhereIn7.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel LetIn1 11 22" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/LetIn1.hs" (11,22) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/LetIn1.hs" (11,22) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/LetIn1.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/LetIn1.hs.expected" "./test/testdata/LiftToToplevel/LetIn1.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel LetIn2 10 22" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/LetIn2.hs" (10,22) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/LetIn2.hs" (10,22) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/LetIn2.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/LetIn2.hs.expected" "./test/testdata/LiftToToplevel/LetIn2.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel LetIn3 10 27" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/LetIn3.hs" (10,27) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/LetIn3.hs" (10,27) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/LetIn3.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/LetIn3.hs.expected" "./test/testdata/LiftToToplevel/LetIn3.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel PatBindIn1 18 7" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/PatBindIn1.hs" (18,7) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/PatBindIn1.hs" (18,7) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/PatBindIn1.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/PatBindIn1.hs.expected" "./test/testdata/LiftToToplevel/PatBindIn1.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel PatBindIn3 11 15" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/PatBindIn3.hs" (11,15) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/PatBindIn3.hs" (11,15) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/PatBindIn3.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/PatBindIn3.hs.expected" "./test/testdata/LiftToToplevel/PatBindIn3.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel CaseIn1 10 28" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/CaseIn1.hs" (10,28) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/CaseIn1.hs" (10,28) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/CaseIn1.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/CaseIn1.hs.expected" "./test/testdata/LiftToToplevel/CaseIn1.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel PatBindIn2 17 7 fails" $ do {- res <- catchException (doLiftToTopLevel ["./test/testdata/LiftToToplevel/PatBindIn2.hs","17","7"]) -- liftToTopLevel logTestSettings Nothing "./test/testdata/LiftToToplevel/PatBindIn2.hs" (17,7) (show res) `shouldBe` "Just \"\\nThe identifier is not a local function/pattern name!\"" -} pending -- Not clear that this was covered in the original, will -- come back to it -- --------------------------------- it "liftToTopLevel WhereIn2 11 18 fails" $ do -- res <- catchException (doLiftToTopLevel ["./test/testdata/LiftToToplevel/WhereIn2.hs","11","18"]) res <- catchException (liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/WhereIn2.hs" (11,18)) -- liftToTopLevel logTestSettings testOptions Nothing "./test/testdata/LiftToToplevel/WhereIn2.hs" (11,18) (show res) `shouldBe` "Just \"The identifier(s): (sq, test/testdata/LiftToToplevel/WhereIn2.hs:11:18) will cause name clash/capture or ambiguity occurrence problem after lifting, please do renaming first!\"" -- --------------------------------- it "liftToTopLevel Collapse1 8 6" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/Collapse1.hs" (8,6) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/Collapse1.hs" (8,6) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/Collapse1.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/Collapse1.expected.hs" "./test/testdata/LiftToToplevel/Collapse1.refactored.hs" diff `shouldBe` [] {- original tests positive=[(["D1.hs","C1.hs","A1.hs"],["8","6"]), (["D2.hs","C2.hs","A2.hs"],["8","6"]), (["D3.hs","C3.hs","A3.hs"],["8","6"]), (["WhereIn1.hs"],["12","18"]), (["WhereIn6.hs"],["13","29"]), (["WhereIn7.hs"],["12","14"]), (["LetIn1.hs"],["11","22"]), (["LetIn2.hs"],["10","22"]), (["LetIn3.hs"],["10","27"]), (["PatBindIn1.hs"],["18","7"]), (["PatBindIn3.hs"],["11","15"]), (["CaseIn1.hs"],["10","28"])], negative=[(["PatBindIn2.hs"],["17","7"]), (["WhereIn2.hs"],["11","18"]) ] -} -- --------------------------------- it "liftToTopLevel Zmapq" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/Zmapq.hs" (6,3) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/Zmapq.hs" (6,3) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/Zmapq.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/Zmapq.expected.hs" "./test/testdata/LiftToToplevel/Zmapq.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel LiftInLambda 10 5" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/LiftInLambda.hs" (10,5) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/LiftInLambda.hs" (10,5) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/LiftInLambda.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/LiftInLambda.expected.hs" "./test/testdata/LiftToToplevel/LiftInLambda.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel NoWhere" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/NoWhere.hs" (14,12) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/NoWhere.hs" (14,12) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/NoWhere.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/NoWhere.expected.hs" "./test/testdata/LiftToToplevel/NoWhere.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel Signature" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/Signature.hs" (9,5) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/Signature.hs" (9,5) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/Signature.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/Signature.expected.hs" "./test/testdata/LiftToToplevel/Signature.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel Signature2" $ do -- should throw exception for forall in signature res <- catchException (liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/Signature2.hs" (16,5)) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/Signature2.hs" (16,5) (show res) `shouldBe` "Just \"\\nNew type signature may fail type checking: :: (forall t. Num t => t -> t -> t) -> Int -> \\n\"" {- r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/Signature2.hs" (16,5) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/Signature2.hs" (16,5) (show r) `shouldBe` "[\"./test/testdata/LiftToToplevel/Signature2.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/Signature2.expected.hs" "./test/testdata/LiftToToplevel/Signature2.refactored.hs" diff `shouldBe` [] -} -- --------------------------------- it "liftToTopLevel Signature2r" $ do -- should throw exception for forall in signature r <- catchException (liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/Signature2r.hs" (12,5)) -- r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/Signature2r.hs" (12,5) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/Signature2r.hs" (12,5) (show r) `shouldBe` "Just \"\\nNew type signature may fail type checking: :: (forall t. Num t => t -> t -> t) -> Int -> \\n\"" {- (show r) `shouldBe` "[\"./test/testdata/LiftToToplevel/Signature2r.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/Signature2r.expected.hs" "./test/testdata/LiftToToplevel/Signature2r.refactored.hs" diff `shouldBe` [] -} -- --------------------------------- it "liftToTopLevel Signature3" $ do r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/Signature3.hs" (9,5) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/Signature3.hs" (9,5) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftToToplevel/Signature3.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/Signature3.expected.hs" "./test/testdata/LiftToToplevel/Signature3.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftToTopLevel Signature4" $ do -- should throw exception for forall in signature r <- catchException $ liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/Signature4.hs" (9,5) -- r <- liftToTopLevel defaultTestSettings testOptions "./test/testdata/LiftToToplevel/Signature4.hs" (9,5) -- r <- liftToTopLevel logTestSettings testOptions "./test/testdata/LiftToToplevel/Signature4.hs" (9,5) (show r) `shouldBe` "Just \"\\nNew type signature may fail type checking: :: (forall t. (Integral t, Num t) => t -> t -> Int) -> t -> \\n\"" {- (show r) `shouldBe` "[\"./test/testdata/LiftToToplevel/Signature4.hs\"]" diff <- compareFiles "./test/testdata/LiftToToplevel/Signature4.expected.hs" "./test/testdata/LiftToToplevel/Signature4.refactored.hs" diff `shouldBe` [] -} -- ------------------------------------------------------------------- describe "LiftOneLevel" $ do it "liftOneLevel.liftToMod D1 C1 A1 8 6" $ do r <- ct $ liftOneLevel defaultTestSettings testOptions "./LiftOneLevel/D1.hs" (8,6) -- r <- ct $ liftOneLevel logTestSettings testOptions "./LiftOneLevel/D1.hs" (8,6) r' <- ct $ mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"LiftOneLevel/D1.hs\",\"LiftOneLevel/C1.hs\"]" diff <- compareFiles "./test/testdata/LiftOneLevel/D1.hs.expected" "./test/testdata/LiftOneLevel/D1.refactored.hs" diff `shouldBe` [] diff2 <- compareFiles "./test/testdata/LiftOneLevel/C1.hs.expected" "./test/testdata/LiftOneLevel/C1.refactored.hs" diff2 `shouldBe` [] a1Refactored <- doesFileExist "./test/testdata/LiftOneLevel/A1.refactored.hs" a1Refactored `shouldBe` False -- --------------------------------- it "LiftOneLevel.liftToMod D2 C2 A2 8 6" $ do r <- ct $ liftOneLevel defaultTestSettings testOptions "./LiftOneLevel/D2.hs" (8,6) r' <- ct $ mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"LiftOneLevel/D2.hs\",\"LiftOneLevel/C2.hs\"]" diff <- compareFiles "./test/testdata/LiftOneLevel/D2.hs.expected" "./test/testdata/LiftOneLevel/D2.refactored.hs" diff `shouldBe` [] diff2 <- compareFiles "./test/testdata/LiftOneLevel/C2.hs.expected" "./test/testdata/LiftOneLevel/C2.refactored.hs" diff2 `shouldBe` [] a2Refactored <- doesFileExist "./test/testdata/LiftOneLevel/A2.refactored.hs" a2Refactored `shouldBe` False -- --------------------------------- it "LiftOneLevel.liftToMod D3 C3 A3 8 6" $ do r <- ct $ liftOneLevel defaultTestSettings testOptions "./LiftOneLevel/D3.hs" (8,6) r' <- ct $ mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"LiftOneLevel/D3.hs\"]" diff <- compareFiles "./test/testdata/LiftOneLevel/D3.hs.expected" "./test/testdata/LiftOneLevel/D3.refactored.hs" diff `shouldBe` [] c3Refactored <- doesFileExist "./test/testdata/LiftOneLevel/C3.refactored.hs" c3Refactored `shouldBe` False a3Refactored <- doesFileExist "./test/testdata/LiftOneLevel/A3.refactored.hs" a3Refactored `shouldBe` False -- --------------------------------- it "LiftOneLevel WhereIn1 12 18" $ do r <- liftOneLevel defaultTestSettings testOptions "./test/testdata/LiftOneLevel/WhereIn1.hs" (12,18) -- r <- liftOneLevel logTestSettings testOptions "./test/testdata/LiftOneLevel/WhereIn1.hs" (12,18) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftOneLevel/WhereIn1.hs\"]" diff <- compareFiles "./test/testdata/LiftOneLevel/WhereIn1.hs.expected" "./test/testdata/LiftOneLevel/WhereIn1.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "LiftOneLevel WhereIn6 13 29" $ do r <- liftOneLevel defaultTestSettings testOptions "./test/testdata/LiftOneLevel/WhereIn6.hs" (13,29) -- r <- liftOneLevel logTestSettings testOptions "./test/testdata/LiftOneLevel/WhereIn6.hs" (13,29) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftOneLevel/WhereIn6.hs\"]" diff <- compareFiles "./test/testdata/LiftOneLevel/WhereIn6.hs.expected" "./test/testdata/LiftOneLevel/WhereIn6.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftOneLevel WhereIn7 12 14" $ do r <- liftOneLevel defaultTestSettings testOptions "./test/testdata/LiftOneLevel/WhereIn7.hs" (12,14) -- r <- liftOneLevel logTestSettings testOptions "./test/testdata/LiftOneLevel/WhereIn7.hs" (12,14) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftOneLevel/WhereIn7.hs\"]" diff <- compareFiles "./test/testdata/LiftOneLevel/WhereIn7.hs.expected" "./test/testdata/LiftOneLevel/WhereIn7.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "LiftOneLevel WhereIn8 8 11" $ do r <- liftOneLevel defaultTestSettings testOptions "./test/testdata/LiftOneLevel/WhereIn8.hs" (8,11) -- r <- liftOneLevel logTestSettings testOptions "./test/testdata/LiftOneLevel/WhereIn8.hs" (8,11) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftOneLevel/WhereIn8.hs\"]" diff <- compareFiles "./test/testdata/LiftOneLevel/WhereIn8.hs.expected" "./test/testdata/LiftOneLevel/WhereIn8.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "LiftOneLevel LetIn1 11 22" $ do r <- liftOneLevel defaultTestSettings testOptions "./test/testdata/LiftOneLevel/LetIn1.hs" (11,22) -- r <- liftOneLevel logTestSettings testOptions "./test/testdata/LiftOneLevel/LetIn1.hs" (11,22) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftOneLevel/LetIn1.hs\"]" diff <- compareFiles "./test/testdata/LiftOneLevel/LetIn1.hs.expected" "./test/testdata/LiftOneLevel/LetIn1.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "LiftOneLevel LetIn2 11 22" $ do r <- liftOneLevel defaultTestSettings testOptions "./test/testdata/LiftOneLevel/LetIn2.hs" (11,22) -- r <- liftOneLevel logTestSettings testOptions "./test/testdata/LiftOneLevel/LetIn2.hs" (11,22) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftOneLevel/LetIn2.hs\"]" diff <- compareFiles "./test/testdata/LiftOneLevel/LetIn2.hs.expected" "./test/testdata/LiftOneLevel/LetIn2.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "LiftOneLevel LetIn3 10 27" $ do r <- liftOneLevel defaultTestSettings testOptions "./test/testdata/LiftOneLevel/LetIn3.hs" (10,27) -- r <- liftOneLevel logTestSettings testOptions "./test/testdata/LiftOneLevel/LetIn3.hs" (10,27) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftOneLevel/LetIn3.hs\"]" diff <- compareFiles "./test/testdata/LiftOneLevel/LetIn3.hs.expected" "./test/testdata/LiftOneLevel/LetIn3.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "LiftOneLevel PatBindIn3 11 15" $ do r <- liftOneLevel defaultTestSettings testOptions "./test/testdata/LiftOneLevel/PatBindIn3.hs" (11,15) -- r <- liftOneLevel logTestSettings testOptions "./test/testdata/LiftOneLevel/PatBindIn3.hs" (11,15) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftOneLevel/PatBindIn3.hs\"]" diff <- compareFiles "./test/testdata/LiftOneLevel/PatBindIn3.hs.expected" "./test/testdata/LiftOneLevel/PatBindIn3.refactored.hs" diff `shouldBe` [] -- --------------------------------- it "liftOneLevel CaseIn1 10 28" $ do r <- liftOneLevel defaultTestSettings testOptions "./test/testdata/LiftOneLevel/CaseIn1.hs" (10,28) -- r <- liftOneLevel logTestSettings testOptions "./test/testdata/LiftOneLevel/CaseIn1.hs" (10,28) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/LiftOneLevel/CaseIn1.hs\"]" diff <- compareFiles "./test/testdata/LiftOneLevel/CaseIn1.hs.expected" "./test/testdata/LiftOneLevel/CaseIn1.refactored.hs" diff `shouldBe` [] -- ----------------------------------------------------------------- it "fails PatBindIn2 17 7" $ do {- res <- catchException (liftOneLevel defaultTestSettings testOptions Nothing "./test/testdata/LiftOneLevel/PatBindIn2.hs" (17,7)) -- liftOneLevel logTestSettings testOptions Nothing "./test/testdata/LiftOneLevel/PatBindIn2.hs" (17,7) (show res) `shouldBe` "Just \"Lifting this definition failed. This might be because that the definition to be lifted is defined in a class/instance declaration.\"" -} pending -- Not clear that this was covered in the original, will -- come back to it -- ----------------------------------------------------------------- it "fails WhereIn2 8 18" $ do res <- catchException (liftOneLevel defaultTestSettings testOptions "./test/testdata/LiftOneLevel/WhereIn2.hs" (8,18)) -- liftOneLevel logTestSettings testOptions "./test/testdata/LiftOneLevel/WhereIn2.hs" (8,18) (show res) `shouldBe` "Just \"The identifier(s): (sq, test/testdata/LiftOneLevel/WhereIn2.hs:8:18) will cause name clash/capture or ambiguity occurrence problem after lifting, please do renaming first!\"" -- TODO: check that other declarations in a list that make use of the -- one being lifted also have params changed. {- original tests TestCases{refactorCmd="liftOneLevel", positive=[(["D1.hs","C1.hs","A1.hs"],["8","6"]), (["D2.hs","C2.hs","A2.hs"],["8","6"]), (["D3.hs","C3.hs","A3.hs"],["8","6"]), (["WhereIn1.hs"],["12","18"]), (["WhereIn6.hs"],["15","29"]), (["WhereIn7.hs"],["12","14"]), (["WhereIn8.hs"],["8","11"]), (["LetIn1.hs"],["11","22"]), (["LetIn2.hs"],["10","22"]), (["LetIn3.hs"],["10","27"]), (["PatBindIn3.hs"],["11","15"]), (["CaseIn1.hs"],["10","28"])], negative=[(["PatBindIn2.hs"],["17","7"]), (["WhereIn2.hs"],["8","18"])] } -} -- ------------------------------------------------------------------- describe "demote" $ do it "notifies if no definition selected" $ do -- res <- catchException (doDemote ["./test/testdata/MoveDef/Md1.hs","14","13"]) res <- catchException (demote defaultTestSettings testOptions "./test/testdata/MoveDef/Md1.hs" (14,13)) (show res) `shouldBe` "Just \"\\nInvalid cursor position!\"" it "will not demote if nowhere to go" $ do res <- catchException (demote defaultTestSettings testOptions "./test/testdata/MoveDef/Md1.hs" (8,1)) -- res <- demote logTestSettings testOptions "./test/testdata/MoveDef/Md1.hs" (8,1) (show res) `shouldBe` "Just \"\\n Nowhere to demote this function!\\n\"" -- ----------------------------------------------------------------- it "demotes a definition from the top level 1" $ do r <- demote defaultTestSettings testOptions "./test/testdata/MoveDef/Demote.hs" (7,1) -- r <- demote logTestSettings testOptions "./test/testdata/MoveDef/Demote.hs" (7,1) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/MoveDef/Demote.hs\"]" diff <- compareFiles "./test/testdata/MoveDef/Demote.refactored.hs" "./test/testdata/MoveDef/Demote.hs.expected" diff `shouldBe` [] -- ----------------------------------------------------------------- it "demotes a definition from the top level D1" $ do r <- demote defaultTestSettings testOptions "./test/testdata/Demote/D1.hs" (9,1) -- r <- demote logTestSettings testOptions "./test/testdata/Demote/D1.hs" (9,1) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/Demote/D1.hs\"]" diff <- compareFiles "./test/testdata/Demote/D1.refactored.hs" "./test/testdata/Demote/D1.hs.expected" diff `shouldBe` [] -- ----------------------------------------------------------------- it "demotes WhereIn1 12 1" $ do r <- demote defaultTestSettings testOptions "./test/testdata/Demote/WhereIn1.hs" (12,1) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/Demote/WhereIn1.hs\"]" diff <- compareFiles "./test/testdata/Demote/WhereIn1.refactored.hs" "./test/testdata/Demote/WhereIn1.hs.expected" diff `shouldBe` [] -- ----------------------------------------------------------------- it "demotes WhereIn3 14 1" $ do r <- demote defaultTestSettings testOptions "./test/testdata/Demote/WhereIn3.hs" (14,1) -- r <- demote logTestSettings testOptions "./test/testdata/Demote/WhereIn3.hs" (14,1) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/Demote/WhereIn3.hs\"]" diff <- compareFiles "./test/testdata/Demote/WhereIn3.refactored.hs" "./test/testdata/Demote/WhereIn3.hs.expected" diff `shouldBe` [] -- ----------------------------------------------------------------- it "demotes WhereIn4 14 1" $ do -- r <- doDemote ["./test/testdata/Demote/WhereIn4.hs","14","1"] r <- demote defaultTestSettings testOptions "./test/testdata/Demote/WhereIn4.hs" (14,1) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/Demote/WhereIn4.hs\"]" diff <- compareFiles "./test/testdata/Demote/WhereIn4.refactored.hs" "./test/testdata/Demote/WhereIn4.hs.expected" diff `shouldBe` [] -- ----------------------------------------------------------------- it "demotes WhereIn5 14 1" $ do r <- demote defaultTestSettings testOptions "./test/testdata/Demote/WhereIn5.hs" (14,1) -- r <- demote logTestSettings testOptions "./test/testdata/Demote/WhereIn5.hs" (14,1) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/Demote/WhereIn5.hs\"]" diff <- compareFiles "./test/testdata/Demote/WhereIn5.refactored.hs" "./test/testdata/Demote/WhereIn5.hs.expected" diff `shouldBe` [] -- ----------------------------------------------------------------- it "demotes WhereIn6 13 1" $ do r <- demote defaultTestSettings testOptions "./test/testdata/Demote/WhereIn6.hs" (13,1) -- r <- demote logTestSettings testOptions "./test/testdata/Demote/WhereIn6.hs" (13,1) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/Demote/WhereIn6.hs\"]" diff <- compareFiles "./test/testdata/Demote/WhereIn6.refactored.hs" "./test/testdata/Demote/WhereIn6.hs.expected" diff `shouldBe` [] -- ----------------------------------------------------------------- it "demotes WhereIn7 13 1" $ do r <- demote defaultTestSettings testOptions "./test/testdata/Demote/WhereIn7.hs" (13,1) -- r <- demote logTestSettings testOptions "./test/testdata/Demote/WhereIn7.hs" (13,1) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/Demote/WhereIn7.hs\"]" diff <- compareFiles "./test/testdata/Demote/WhereIn7.refactored.hs" "./test/testdata/Demote/WhereIn7.hs.expected" diff `shouldBe` [] -- ----------------------------------------------------------------- it "demotes CaseIn1 16 1" $ do r <- demote defaultTestSettings testOptions "./test/testdata/Demote/CaseIn1.hs" (16,1) -- r <- demote logTestSettings testOptions "./test/testdata/Demote/CaseIn1.hs" (16,1) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/Demote/CaseIn1.hs\"]" diff <- compareFiles "./test/testdata/Demote/CaseIn1.refactored.hs" "./test/testdata/Demote/CaseIn1.hs.expected" diff `shouldBe` [] -- ----------------------------------------------------------------- it "demotes LetIn1 12 22" $ do r <- demote defaultTestSettings testOptions "./test/testdata/Demote/LetIn1.hs" (12,22) -- r <- demote logTestSettings testOptions "./test/testdata/Demote/LetIn1.hs" (12,22) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/Demote/LetIn1.hs\"]" diff <- compareFiles "./test/testdata/Demote/LetIn1.refactored.hs" "./test/testdata/Demote/LetIn1.hs.expected" diff `shouldBe` [] -- ----------------------------------------------------------------- it "demotes PatBindIn1 19 1" $ do r <- demote defaultTestSettings testOptions "./test/testdata/Demote/PatBindIn1.hs" (19,1) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/Demote/PatBindIn1.hs\"]" diff <- compareFiles "./test/testdata/Demote/PatBindIn1.refactored.hs" "./test/testdata/Demote/PatBindIn1.hs.expected" diff `shouldBe` [] -- ----------------------------------------------------------------- it "demotes D2 5 1 when not imported by other module" $ do r <- demote defaultTestSettings testOptions "./test/testdata/Demote/D2.hs" (5,1) -- r <- demote logTestSettings testOptions "./test/testdata/Demote/D2.hs" (5,1) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/Demote/D2.hs\"]" diff <- compareFiles "./test/testdata/Demote/D2.refactored.hs" "./test/testdata/Demote/D2.hs.expected" diff `shouldBe` [] -- ----------------------------------------------------------------- it "fails WhereIn2 14 1" $ do -- res <- catchException (doDemote ["./test/testdata/Demote/WhereIn2.hs","14","1"]) res <- catchException (demote defaultTestSettings testOptions "./test/testdata/Demote/WhereIn2.hs" (14,1)) -- demote (Just logSettings) testOptions Nothing "./test/testdata/Demote/WhereIn2.hs" (14,1) (show res) `shouldBe` "Just \"\\n Nowhere to demote this function!\\n\"" -- ----------------------------------------------------------------- it "fails LetIn2 11 22" $ do -- res <- catchException (doDemote ["./test/testdata/Demote/LetIn2.hs","11","22"]) res <- catchException (demote defaultTestSettings testOptions "./test/testdata/Demote/LetIn2.hs" (11,22)) (show res) `shouldBe` "Just \"This function can not be demoted as it is used in current level!\\n\"" -- ----------------------------------------------------------------- it "fails PatBindIn4 18 1" $ do -- res <- catchException (doDemote ["./test/testdata/Demote/PatBindIn4.hs","18","1"]) res <- catchException (demote defaultTestSettings testOptions "./test/testdata/Demote/PatBindIn4.hs" (18,1)) -- (show res) `shouldBe` "Just \"\\n Nowhere to demote this function!\\n\"" (show res) `shouldBe` "Just \"\\nThis function/pattern binding is used by more than one friend bindings\\n\"" -- ----------------------------------------------------------------- it "fails WhereIn8 16 1" $ do -- res <- catchException (doDemote ["./test/testdata/Demote/WhereIn8.hs","16","1"]) res <- catchException (demote defaultTestSettings testOptions "./test/testdata/Demote/WhereIn8.hs" (16,1)) (show res) `shouldBe` "Just \"\\n Nowhere to demote this function!\\n\"" -- ----------------------------------------------------------------- it "fails D2 5 1" $ do res <- catchException (ct $ demote defaultTestSettings testOptions "./Demote/D2.hs" (5,1)) -- res <- catchException (ct $ demote logTestSettings testOptions "./Demote/D2.hs" (5,1)) (show res) `shouldBe` "Just \"This definition can not be demoted, as it is used in the client module 'Demote.A2'!\"" -- ----------------------------------------------------------------- it "fails for re-export in client module" $ do pending -- ----------------------------------------------------------------- it "fails D3 5 1" $ do -- res <- catchException (doDemote ["./test/testdata/Demote/D3.hs","5","1"]) res <- catchException (demote defaultTestSettings testOptions "./test/testdata/Demote/D3.hs" (5,1)) (show res) `shouldBe` "Just \"This definition can not be demoted, as it is explicitly exported by the current module!\"" {- Original test cases. These files are now in testdata/Demote TestCases{refactorCmd="demote", positive=[(["D1.hs","C1.hs","A1.hs"],["9","1"]), x (["WhereIn1.hs"],["12","1"]), x (["WhereIn3.hs"],["14","1"]), x (["WhereIn4.hs"],["14","1"]), x (["WhereIn5.hs"],["14","1"]), x (["WhereIn6.hs"],["13","1"]), x (["WhereIn7.hs"],["13","1"]), x (["CaseIn1.hs"],["16","1"]), x (["LetIn1.hs"],["12","22"]), x (["PatBindIn1.hs"],["19","1"])], x negative=[(["WhereIn2.hs"],["14","1"]), x (["LetIn2.hs"],["11","22"]), x (["PatBindIn4.hs"],["18","1"]), x (["WhereIn8.hs"],["16","1"]), x (["D2.hs","C2.hs","A2.hs"],["5","1"]), x (["D3.hs"],["5","1"])] x } -} -- ----------------------------------------------------------------- it "fails MultiLeg.hs" $ do res <- catchException (demote defaultTestSettings testOptions "./test/testdata/Demote/MultiLeg.hs" (14,1)) -- demote logTestSettings testOptions "./test/testdata/Demote/MultiLeg.hs" (14,1) (show res) `shouldBe` "Just \"\\nThis function/pattern binding is used by more than one friend bindings\\n\"" -- ----------------------------------------------------------------- it "passes MultiLeg2.hs" $ do r <- demote defaultTestSettings testOptions "./test/testdata/Demote/MultiLeg2.hs" (14,1) -- demote logTestSettings testOptions "./test/testdata/Demote/MultiLeg2.hs" (14,1) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/Demote/MultiLeg2.hs\"]" diff <- compareFiles "./test/testdata/Demote/MultiLeg2.refactored.hs" "./test/testdata/Demote/MultiLeg2.hs.expected" diff `shouldBe` [] -- ----------------------------------------------------------------- it "passes UsedAtLevel.hs" $ do r <- demote defaultTestSettings testOptions "./test/testdata/Demote/UsedAtLevel.hs" (19,12) -- demote logTestSettings testOptions "./test/testdata/Demote/UsedAtLevel.hs" (19,12) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/Demote/UsedAtLevel.hs\"]" diff <- compareFiles "./test/testdata/Demote/UsedAtLevel.refactored.hs" "./test/testdata/Demote/UsedAtLevel.expected.hs" diff `shouldBe` [] -- ----------------------------------------------------------------- it "passes UsedAtLevel.hs2" $ do r <- demote defaultTestSettings testOptions "./test/testdata/Demote/UsedAtLevel2.hs" (23,12) -- demote logTestSettings testOptions "./test/testdata/Demote/UsedAtLevel2.hs" (23,12) r' <- mapM makeRelativeToCurrentDirectory r (show r') `shouldBe` "[\"test/testdata/Demote/UsedAtLevel2.hs\"]" diff <- compareFiles "./test/testdata/Demote/UsedAtLevel2.refactored.hs" "./test/testdata/Demote/UsedAtLevel2.expected.hs" diff `shouldBe` [] -- --------------------------------------------------------------------- -- Helper functions
kmate/HaRe
test/MoveDefSpec.hs
bsd-3-clause
41,665
0
18
7,561
5,189
2,560
2,629
417
1
module LdapImport where import CSH.LDAP import CSH.Eval.Model import CSH.Eval.Cacheable.Prim import CSH.Eval.Cacheable.Make import Data.UUID import Data.Maybe import Data.ByteString.Char8 as B import Data.Text as T import Ldap.Client.Search import System.Log.Logger ldapImport = withConfig $ \l -> do lgr <- getRootLogger cache <- initCacheFromConfig lgr ldapres <- search l (Dn userBaseTxt) (typesOnly False) (Present (Attr "uid")) [ Attr "uid" , Attr "cn" , Attr "entryUUID" , Attr "housingPoints" ] let attrlst = fmap (\(SearchEntry _ x)-> x) ldapres let usrs = fmap (fmap (\((Attr x), (y:_))-> (T.unpack x, B.unpack y))) attrlst mapM_ (mkUsrFromLDAP cache logger) usrs mkUsrFromLDAP cache logger usr = do let uuid = fromJust (fromString (jlookup "entryUUID" usr)) let uid = T.pack (jlookup "uid" usr) let cn = maybe "" T.pack (lookup "cn" usr) let pts = (read (maybe "0" id (lookup "housingPoints" usr)) :: Int) execCacheable cache (mkExtantMember uuid uid cn pts False) where jlookup x xs = fromJust (lookup x xs)
robgssp/csh-eval
ldapImport.hs
mit
1,244
0
19
376
439
226
213
31
1
{-# LANGUAGE OverloadedStrings, FlexibleInstances, RecordWildCards #-} -- | Docker types. module Stack.Types.Docker where import Control.Applicative import Data.Aeson.Extended import Data.Monoid import Data.Text (Text) import Path -- | Docker configuration. data DockerOpts = DockerOpts {dockerEnable :: !Bool -- ^ Is using Docker enabled? ,dockerImage :: !String -- ^ Exact Docker image tag or ID. Overrides docker-repo-*/tag. ,dockerRegistryLogin :: !Bool -- ^ Does registry require login for pulls? ,dockerRegistryUsername :: !(Maybe String) -- ^ Optional username for Docker registry. ,dockerRegistryPassword :: !(Maybe String) -- ^ Optional password for Docker registry. ,dockerAutoPull :: !Bool -- ^ Automatically pull new images. ,dockerDetach :: !Bool -- ^ Whether to run a detached container ,dockerPersist :: !Bool -- ^ Create a persistent container (don't remove it when finished). Implied by -- `dockerDetach`. ,dockerContainerName :: !(Maybe String) -- ^ Container name to use, only makes sense from command-line with `dockerPersist` -- or `dockerDetach`. ,dockerRunArgs :: ![String] -- ^ Arguments to pass directly to @docker run@. ,dockerMount :: ![Mount] -- ^ Volumes to mount in the container. ,dockerPassHost :: !Bool -- ^ Pass Docker daemon connection information into container. ,dockerDatabasePath :: !(Path Abs File) -- ^ Location of image usage database. } deriving (Show) -- | An uninterpreted representation of docker options. -- Configurations may be "cascaded" using mappend (left-biased). data DockerOptsMonoid = DockerOptsMonoid {dockerMonoidExists :: !(Maybe Bool) -- ^ Does a @docker:@ section exist in the top-level (usually project) config? ,dockerMonoidEnable :: !(Maybe Bool) -- ^ Is using Docker enabled? ,dockerMonoidRepoOrImage :: !(Maybe DockerMonoidRepoOrImage) -- ^ Docker repository name (e.g. @fpco/stack-build@ or @fpco/stack-full:lts-2.8@) ,dockerMonoidRegistryLogin :: !(Maybe Bool) -- ^ Does registry require login for pulls? ,dockerMonoidRegistryUsername :: !(Maybe String) -- ^ Optional username for Docker registry. ,dockerMonoidRegistryPassword :: !(Maybe String) -- ^ Optional password for Docker registry. ,dockerMonoidAutoPull :: !(Maybe Bool) -- ^ Automatically pull new images. ,dockerMonoidDetach :: !(Maybe Bool) -- ^ Whether to run a detached container ,dockerMonoidPersist :: !(Maybe Bool) -- ^ Create a persistent container (don't remove it when finished). Implied by -- `dockerDetach`. ,dockerMonoidContainerName :: !(Maybe String) -- ^ Container name to use, only makes sense from command-line with `dockerPersist` -- or `dockerDetach`. ,dockerMonoidRunArgs :: ![String] -- ^ Arguments to pass directly to @docker run@ ,dockerMonoidMount :: ![Mount] -- ^ Volumes to mount in the container ,dockerMonoidPassHost :: !(Maybe Bool) -- ^ Pass Docker daemon connection information into container. ,dockerMonoidDatabasePath :: !(Maybe String) -- ^ Location of image usage database. } deriving (Show) -- | Decode uninterpreted docker options from JSON/YAML. instance FromJSON DockerOptsMonoid where parseJSON = withObject "DockerOptsMonoid" (\o -> do dockerMonoidExists <- pure (Just True) dockerMonoidEnable <- o .:? dockerEnableArgName dockerMonoidRepoOrImage <- ((Just . DockerMonoidImage) <$> o .: dockerImageArgName) <|> ((Just . DockerMonoidRepo) <$> o .: dockerRepoArgName) <|> pure Nothing dockerMonoidRegistryLogin <- o .:? dockerRegistryLoginArgName dockerMonoidRegistryUsername <- o .:? dockerRegistryUsernameArgName dockerMonoidRegistryPassword <- o .:? dockerRegistryPasswordArgName dockerMonoidAutoPull <- o .:? dockerAutoPullArgName dockerMonoidDetach <- o .:? dockerDetachArgName dockerMonoidPersist <- o .:? dockerPersistArgName dockerMonoidContainerName <- o .:? dockerContainerNameArgName dockerMonoidRunArgs <- o .:? dockerRunArgsArgName .!= [] dockerMonoidMount <- o .:? dockerMountArgName .!= [] dockerMonoidPassHost <- o .:? dockerPassHostArgName dockerMonoidDatabasePath <- o .:? dockerDatabasePathArgName return DockerOptsMonoid{..}) -- | Left-biased combine Docker options instance Monoid DockerOptsMonoid where mempty = DockerOptsMonoid {dockerMonoidExists = Just False ,dockerMonoidEnable = Nothing ,dockerMonoidRepoOrImage = Nothing ,dockerMonoidRegistryLogin = Nothing ,dockerMonoidRegistryUsername = Nothing ,dockerMonoidRegistryPassword = Nothing ,dockerMonoidAutoPull = Nothing ,dockerMonoidDetach = Nothing ,dockerMonoidPersist = Nothing ,dockerMonoidContainerName = Nothing ,dockerMonoidRunArgs = [] ,dockerMonoidMount = [] ,dockerMonoidPassHost = Nothing ,dockerMonoidDatabasePath = Nothing } mappend l r = DockerOptsMonoid {dockerMonoidExists = dockerMonoidExists l <|> dockerMonoidExists r ,dockerMonoidEnable = dockerMonoidEnable l <|> dockerMonoidEnable r ,dockerMonoidRepoOrImage = dockerMonoidRepoOrImage l <|> dockerMonoidRepoOrImage r ,dockerMonoidRegistryLogin = dockerMonoidRegistryLogin l <|> dockerMonoidRegistryLogin r ,dockerMonoidRegistryUsername = dockerMonoidRegistryUsername l <|> dockerMonoidRegistryUsername r ,dockerMonoidRegistryPassword = dockerMonoidRegistryPassword l <|> dockerMonoidRegistryPassword r ,dockerMonoidAutoPull = dockerMonoidAutoPull l <|> dockerMonoidAutoPull r ,dockerMonoidDetach = dockerMonoidDetach l <|> dockerMonoidDetach r ,dockerMonoidPersist = dockerMonoidPersist l <|> dockerMonoidPersist r ,dockerMonoidContainerName = dockerMonoidContainerName l <|> dockerMonoidContainerName r ,dockerMonoidRunArgs = dockerMonoidRunArgs r <> dockerMonoidRunArgs l ,dockerMonoidMount = dockerMonoidMount r <> dockerMonoidMount l ,dockerMonoidPassHost = dockerMonoidPassHost l <|> dockerMonoidPassHost r ,dockerMonoidDatabasePath = dockerMonoidDatabasePath l <|> dockerMonoidDatabasePath r } -- | Docker volume mount. data Mount = Mount String String -- | For optparse-applicative. instance Read Mount where readsPrec _ s = case break (== ':') s of (a,':':b) -> [(Mount a b,"")] (a,[]) -> [(Mount a a,"")] _ -> fail "Invalid value for Docker mount (expect '/host/path:/container/path')" -- | Show instance. instance Show Mount where show (Mount a b) = if a == b then a else concat [a,":",b] -- | For YAML. instance FromJSON Mount where parseJSON v = fmap read (parseJSON v) -- | Options for Docker repository or image. data DockerMonoidRepoOrImage = DockerMonoidRepo String | DockerMonoidImage String deriving (Show) -- | Docker enable argument name. dockerEnableArgName :: Text dockerEnableArgName = "enable" -- | Docker repo arg argument name. dockerRepoArgName :: Text dockerRepoArgName = "repo" -- | Docker image argument name. dockerImageArgName :: Text dockerImageArgName = "image" -- | Docker registry login argument name. dockerRegistryLoginArgName :: Text dockerRegistryLoginArgName = "registry-login" -- | Docker registry username argument name. dockerRegistryUsernameArgName :: Text dockerRegistryUsernameArgName = "registry-username" -- | Docker registry password argument name. dockerRegistryPasswordArgName :: Text dockerRegistryPasswordArgName = "registry-password" -- | Docker auto-pull argument name. dockerAutoPullArgName :: Text dockerAutoPullArgName = "auto-pull" -- | Docker detach argument name. dockerDetachArgName :: Text dockerDetachArgName = "detach" -- | Docker run args argument name. dockerRunArgsArgName :: Text dockerRunArgsArgName = "run-args" -- | Docker mount argument name. dockerMountArgName :: Text dockerMountArgName = "mount" -- | Docker container name argument name. dockerContainerNameArgName :: Text dockerContainerNameArgName = "container-name" -- | Docker persist argument name. dockerPersistArgName :: Text dockerPersistArgName = "persist" -- | Docker pass host argument name. dockerPassHostArgName :: Text dockerPassHostArgName = "pass-host" -- | Docker database path argument name. dockerDatabasePathArgName :: Text dockerDatabasePathArgName = "database-path"
CRogers/stack
src/Stack/Types/Docker.hs
bsd-3-clause
8,817
0
18
1,936
1,362
762
600
187
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="az-AZ"> <title>JSON View</title> <maps> <homeID>jsonview</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>
kingthorin/zap-extensions
addOns/jsonview/src/main/javahelp/help_az_AZ/helpset_az_AZ.hs
apache-2.0
959
77
66
156
407
206
201
-1
-1
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- -- Module : IDE.Command.VCS.Common.Workspaces -- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GPL Nothing -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : -- -- | -- ----------------------------------------------------------------------------- module IDE.Command.VCS.Common.Workspaces ( onWorkspaceOpen , onWorkspaceClose ) where -- VCS imports import IDE.Utils.FileUtils(getConfigFilePathForLoad) import qualified IDE.Utils.GUIUtils as GUIUtils import IDE.Core.Types import IDE.Core.State import qualified IDE.Command.VCS.Common as Common import qualified IDE.Command.VCS.SVN as SVN (mkSVNActions) import qualified IDE.Command.VCS.GIT as GIT (mkGITActions) import qualified IDE.Command.VCS.Common.GUI as GUI import qualified VCSWrapper.Common as VCS import qualified VCSGui.Common as VCSGUI import Data.IORef(writeIORef, readIORef, IORef(..)) import Control.Monad.Reader(liftIO,ask,when) import Graphics.UI.Frame.Panes import Graphics.UI.Gtk ( menuNew, menuItemNewWithLabel, menuItemActivate, menuShellAppend, menuItemSetSubmenu ,widgetShowAll, menuItemNewWithMnemonic, menuItemGetSubmenu, widgetHide, widgetDestroy, menuItemRemoveSubmenu) import Data.Maybe import Data.List import System.Log.Logger (debugM) import Data.Monoid ((<>)) import qualified Data.Text as T (unpack, pack) onWorkspaceClose :: IDEAction onWorkspaceClose = do vcsItem <- GUIUtils.getVCS liftIO $ menuItemRemoveSubmenu vcsItem onWorkspaceOpen :: Workspace -> IDEAction onWorkspaceOpen ws = do liftIO $ debugM "leksah" "onWorkspaceOpen" let mbPackages = wsAllPackages ws packages <- mapM (mapper ws) mbPackages vcsItem <- GUIUtils.getVCS vcsMenu <- liftIO menuNew ideR <- ask --for each package add an extra menu containing vcs specific menuitems mapM_ (\(p,mbVcsConf) -> do Common.setMenuForPackage vcsMenu (ipdCabalFile p) mbVcsConf liftIO $ menuItemSetSubmenu vcsItem vcsMenu ) packages liftIO $ widgetShowAll vcsItem return () where mapper :: Workspace -> IDEPackage -> IDEM (IDEPackage, Maybe VCSConf) mapper workspace p = do let fp = ipdCabalFile p eErrConf <- Common.getVCSConf' workspace fp case eErrConf of Left error -> do liftIO . putStrLn . T.unpack $ "Could not retrieve vcs-conf due to '"<>error<>"'." return (p, Nothing) Right mbConf -> case mbConf of Nothing -> do liftIO $ putStrLn "Could not retrieve vcs-conf for active package. No vcs-conf set up." return (p, Nothing) Just vcsConf -> return (p, Just vcsConf)
573/leksah
src/IDE/Command/VCS/Common/Workspaces.hs
gpl-2.0
3,054
0
18
761
628
357
271
58
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module T14723 () where import Data.Coerce( coerce ) import Data.Kind (Type) import Data.Proxy (Proxy(..)) import Data.String (fromString) import Data.Int (Int64) import GHC.Stack (HasCallStack) import GHC.TypeLits (Nat, Symbol) data JType = Iface Symbol data J (a :: JType) newIterator :: IO (J ('Iface "java.util.Iterator")) newIterator = do let tblPtr :: Int64 tblPtr = undefined iterator <- (qqMarker (Proxy :: Proxy "wuggle") (Proxy :: Proxy "waggle") (Proxy :: Proxy "tblPtr") (Proxy :: Proxy 106) (tblPtr, ()) Proxy (undefined :: IO Int)) undefined class Coercible (a :: Type) where type Ty a :: JType instance Coercible Int64 where type Ty Int64 = Iface "Int64" instance Coercible Int where type Ty Int = Iface "Int" class Coercibles xs (tys :: k) | xs -> tys instance Coercibles () () instance (ty ~ Ty x, Coercible x, Coercibles xs tys) => Coercibles (x, xs) '(ty, tys) qqMarker :: forall k -- the kind variable shows up in Core (args_tys :: k) -- JType's of arguments tyres -- JType of result (input :: Symbol) -- input string of the quasiquoter (mname :: Symbol) -- name of the method to generate (antiqs :: Symbol) -- antiquoted variables as a comma-separated list (line :: Nat) -- line number of the quasiquotation args_tuple -- uncoerced argument types b. -- uncoerced result type (tyres ~ Ty b, Coercibles args_tuple args_tys, Coercible b, HasCallStack) => Proxy input -> Proxy mname -> Proxy antiqs -> Proxy line -> args_tuple -> Proxy args_tys -> IO b -> IO b qqMarker = undefined
sdiehl/ghc
testsuite/tests/polykinds/T14723.hs
bsd-3-clause
2,021
0
14
578
522
296
226
-1
-1
module ChangeCount_Test where import ChangeCount(changeCount) import Test.HUnit testWithEmptyCoinsList = TestCase $ assertEqual "changeCount 4 [] == 0" 0 (changeCount 4 []) testWithZeroMoney = TestCase $ assertEqual "changeCount 0 [1, 2, 5] == 18" 0 (changeCount 0 [1, 2, 5]) testWithUnSortedCoins = TestCase $ assertEqual "changeCount 15 [1, 2, 5] == 18" 18 (changeCount 15 [2, 5, 1]) main = runTestTT $ TestList [testWithEmptyCoinsList, testWithZeroMoney, testWithUnSortedCoins]
slon1024/functional_programming
haskell/ChangeCount_Test.hs
mit
501
0
9
85
130
72
58
10
1
{-# OPTIONS_GHC -fno-warn-missing-signatures -fno-warn-orphans #-} {-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Config -- Copyright : (c) Spencer Janssen 2007 -- License : BSD3-style (see LICENSE) -- -- Maintainer : [email protected] -- Stability : stable -- Portability : portable -- -- This module specifies the default configuration values for xmonad. -- -- DO NOT MODIFY THIS FILE! It won't work. You may configure xmonad -- by providing your own @~\/.xmonad\/xmonad.hs@ that overrides -- specific fields in the default config, 'def'. For a starting point, you can -- copy the @xmonad.hs@ found in the @man@ directory, or look at -- examples on the xmonad wiki. -- ------------------------------------------------------------------------ module XMonad.Config (defaultConfig, Default(..)) where -- -- Useful imports -- import XMonad.Core as XMonad hiding (workspaces,manageHook,keys,logHook,startupHook,borderWidth,mouseBindings ,layoutHook,modMask,terminal,normalBorderColor,focusedBorderColor,focusFollowsMouse ,handleEventHook,clickJustFocuses,rootMask,clientMask) import qualified XMonad.Core as XMonad (workspaces,manageHook,keys,logHook,startupHook,borderWidth,mouseBindings ,layoutHook,modMask,terminal,normalBorderColor,focusedBorderColor,focusFollowsMouse ,handleEventHook,clickJustFocuses,rootMask,clientMask) import XMonad.Layout import XMonad.Operations import XMonad.ManageHook import qualified XMonad.StackSet as W import Data.Bits ((.|.)) import Data.Default import Data.Monoid import qualified Data.Map as M import System.Exit import Graphics.X11.Xlib import Graphics.X11.Xlib.Extras -- | The default number of workspaces (virtual screens) and their names. -- By default we use numeric strings, but any string may be used as a -- workspace name. The number of workspaces is determined by the length -- of this list. -- -- A tagging example: -- -- > workspaces = ["web", "irc", "code" ] ++ map show [4..9] -- workspaces :: [WorkspaceId] workspaces = map show [1 .. 9 :: Int] -- | modMask lets you specify which modkey you want to use. The default -- is mod1Mask ("left alt"). You may also consider using mod3Mask -- ("right alt"), which does not conflict with emacs keybindings. The -- "windows key" is usually mod4Mask. -- defaultModMask :: KeyMask defaultModMask = mod1Mask -- | Width of the window border in pixels. -- borderWidth :: Dimension borderWidth = 1 -- | Border colors for unfocused and focused windows, respectively. -- normalBorderColor, focusedBorderColor :: String normalBorderColor = "gray" -- "#dddddd" focusedBorderColor = "red" -- "#ff0000" don't use hex, not <24 bit safe ------------------------------------------------------------------------ -- Window rules -- | Execute arbitrary actions and WindowSet manipulations when managing -- a new window. You can use this to, for example, always float a -- particular program, or have a client always appear on a particular -- workspace. -- -- To find the property name associated with a program, use -- xprop | grep WM_CLASS -- and click on the client you're interested in. -- manageHook :: ManageHook manageHook = composeAll [ className =? "MPlayer" --> doFloat , className =? "mplayer2" --> doFloat ] ------------------------------------------------------------------------ -- Logging -- | Perform an arbitrary action on each internal state change or X event. -- Examples include: -- -- * do nothing -- -- * log the state to stdout -- -- See the 'DynamicLog' extension for examples. -- logHook :: X () logHook = return () ------------------------------------------------------------------------ -- Event handling -- | Defines a custom handler function for X Events. The function should -- return (All True) if the default handler is to be run afterwards. -- To combine event hooks, use mappend or mconcat from Data.Monoid. handleEventHook :: Event -> X All handleEventHook _ = return (All True) -- | Perform an arbitrary action at xmonad startup. startupHook :: X () startupHook = return () ------------------------------------------------------------------------ -- Extensible layouts -- -- You can specify and transform your layouts by modifying these values. -- If you change layout bindings be sure to use 'mod-shift-space' after -- restarting (with 'mod-q') to reset your layout state to the new -- defaults, as xmonad preserves your old layout settings by default. -- -- | The available layouts. Note that each layout is separated by |||, which -- denotes layout choice. layout = tiled ||| Mirror tiled ||| Full where -- default tiling algorithm partitions the screen into two panes tiled = Tall nmaster delta ratio -- The default number of windows in the master pane nmaster = 1 -- Default proportion of screen occupied by master pane ratio = 1/2 -- Percent of screen to increment by when resizing panes delta = 3/100 ------------------------------------------------------------------------ -- Event Masks: -- | The client events that xmonad is interested in clientMask :: EventMask clientMask = structureNotifyMask .|. enterWindowMask .|. propertyChangeMask -- | The root events that xmonad is interested in rootMask :: EventMask rootMask = substructureRedirectMask .|. substructureNotifyMask .|. enterWindowMask .|. leaveWindowMask .|. structureNotifyMask .|. buttonPressMask ------------------------------------------------------------------------ -- Key bindings: -- | The preferred terminal program, which is used in a binding below and by -- certain contrib modules. terminal :: String terminal = "xterm" -- | Whether focus follows the mouse pointer. focusFollowsMouse :: Bool focusFollowsMouse = True -- | Whether a mouse click select the focus or is just passed to the window clickJustFocuses :: Bool clickJustFocuses = True -- | The xmonad key bindings. Add, modify or remove key bindings here. -- -- (The comment formatting character is used when generating the manpage) -- keys :: XConfig Layout -> M.Map (KeyMask, KeySym) (X ()) keys conf@(XConfig {XMonad.modMask = modMask}) = M.fromList $ -- launching and killing programs [ ((modMask .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf) -- %! Launch terminal , ((modMask, xK_p ), spawn "dmenu_run") -- %! Launch dmenu , ((modMask .|. shiftMask, xK_p ), spawn "gmrun") -- %! Launch gmrun , ((modMask .|. shiftMask, xK_c ), kill) -- %! Close the focused window , ((modMask, xK_space ), sendMessage NextLayout) -- %! Rotate through the available layout algorithms , ((modMask .|. shiftMask, xK_space ), setLayout $ XMonad.layoutHook conf) -- %! Reset the layouts on the current workspace to default , ((modMask, xK_n ), refresh) -- %! Resize viewed windows to the correct size -- move focus up or down the window stack , ((modMask, xK_Tab ), windows W.focusDown) -- %! Move focus to the next window , ((modMask .|. shiftMask, xK_Tab ), windows W.focusUp ) -- %! Move focus to the previous window , ((modMask, xK_j ), windows W.focusDown) -- %! Move focus to the next window , ((modMask, xK_k ), windows W.focusUp ) -- %! Move focus to the previous window , ((modMask, xK_m ), windows W.focusMaster ) -- %! Move focus to the master window -- modifying the window order , ((modMask, xK_Return), windows W.swapMaster) -- %! Swap the focused window and the master window , ((modMask .|. shiftMask, xK_j ), windows W.swapDown ) -- %! Swap the focused window with the next window , ((modMask .|. shiftMask, xK_k ), windows W.swapUp ) -- %! Swap the focused window with the previous window -- resizing the master/slave ratio , ((modMask, xK_h ), sendMessage Shrink) -- %! Shrink the master area , ((modMask, xK_l ), sendMessage Expand) -- %! Expand the master area -- floating layer support , ((modMask, xK_t ), withFocused $ windows . W.sink) -- %! Push window back into tiling -- increase or decrease number of windows in the master area , ((modMask , xK_comma ), sendMessage (IncMasterN 1)) -- %! Increment the number of windows in the master area , ((modMask , xK_period), sendMessage (IncMasterN (-1))) -- %! Deincrement the number of windows in the master area -- quit, or restart , ((modMask .|. shiftMask, xK_q ), io (exitWith ExitSuccess)) -- %! Quit xmonad , ((modMask , xK_q ), spawn "if type xmonad; then xmonad --recompile && xmonad --restart; else xmessage xmonad not in \\$PATH: \"$PATH\"; fi") -- %! Restart xmonad , ((modMask .|. shiftMask, xK_slash ), helpCommand) -- repeat the binding for non-American layout keyboards , ((modMask , xK_question), helpCommand) ] ++ -- mod-[1..9] %! Switch to workspace N -- mod-shift-[1..9] %! Move client to workspace N [((m .|. modMask, k), windows $ f i) | (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9] , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]] ++ -- mod-{w,e,r} %! Switch to physical/Xinerama screens 1, 2, or 3 -- mod-shift-{w,e,r} %! Move client to screen 1, 2, or 3 [((m .|. modMask, key), screenWorkspace sc >>= flip whenJust (windows . f)) | (key, sc) <- zip [xK_w, xK_e, xK_r] [0..] , (f, m) <- [(W.view, 0), (W.shift, shiftMask)]] where helpCommand :: X () helpCommand = spawn ("echo " ++ show help ++ " | xmessage -file -") -- %! Run xmessage with a summary of the default keybindings (useful for beginners) -- | Mouse bindings: default actions bound to mouse events mouseBindings :: XConfig Layout -> M.Map (KeyMask, Button) (Window -> X ()) mouseBindings (XConfig {XMonad.modMask = modMask}) = M.fromList -- mod-button1 %! Set the window to floating mode and move by dragging [ ((modMask, button1), \w -> focus w >> mouseMoveWindow w >> windows W.shiftMaster) -- mod-button2 %! Raise the window to the top of the stack , ((modMask, button2), windows . (W.shiftMaster .) . W.focusWindow) -- mod-button3 %! Set the window to floating mode and resize by dragging , ((modMask, button3), \w -> focus w >> mouseResizeWindow w >> windows W.shiftMaster) -- you may also bind events to the mouse scroll wheel (button4 and button5) ] instance (a ~ Choose Tall (Choose (Mirror Tall) Full)) => Default (XConfig a) where def = XConfig { XMonad.borderWidth = borderWidth , XMonad.workspaces = workspaces , XMonad.layoutHook = layout , XMonad.terminal = terminal , XMonad.normalBorderColor = normalBorderColor , XMonad.focusedBorderColor = focusedBorderColor , XMonad.modMask = defaultModMask , XMonad.keys = keys , XMonad.logHook = logHook , XMonad.startupHook = startupHook , XMonad.mouseBindings = mouseBindings , XMonad.manageHook = manageHook , XMonad.handleEventHook = handleEventHook , XMonad.focusFollowsMouse = focusFollowsMouse , XMonad.clickJustFocuses = clickJustFocuses , XMonad.clientMask = clientMask , XMonad.rootMask = rootMask , XMonad.handleExtraArgs = \ xs theConf -> case xs of [] -> return theConf _ -> fail ("unrecognized flags:" ++ show xs) } -- | The default set of configuration values itself {-# DEPRECATED defaultConfig "Use def (from Data.Default, and re-exported by XMonad and XMonad.Config) instead." #-} defaultConfig :: XConfig (Choose Tall (Choose (Mirror Tall) Full)) defaultConfig = def -- | Finally, a copy of the default bindings in simple textual tabular format. help :: String help = unlines ["The default modifier key is 'alt'. Default keybindings:", "", "-- launching and killing programs", "mod-Shift-Enter Launch xterminal", "mod-p Launch dmenu", "mod-Shift-p Launch gmrun", "mod-Shift-c Close/kill the focused window", "mod-Space Rotate through the available layout algorithms", "mod-Shift-Space Reset the layouts on the current workSpace to default", "mod-n Resize/refresh viewed windows to the correct size", "", "-- move focus up or down the window stack", "mod-Tab Move focus to the next window", "mod-Shift-Tab Move focus to the previous window", "mod-j Move focus to the next window", "mod-k Move focus to the previous window", "mod-m Move focus to the master window", "", "-- modifying the window order", "mod-Return Swap the focused window and the master window", "mod-Shift-j Swap the focused window with the next window", "mod-Shift-k Swap the focused window with the previous window", "", "-- resizing the master/slave ratio", "mod-h Shrink the master area", "mod-l Expand the master area", "", "-- floating layer support", "mod-t Push window back into tiling; unfloat and re-tile it", "", "-- increase or decrease number of windows in the master area", "mod-comma (mod-,) Increment the number of windows in the master area", "mod-period (mod-.) Deincrement the number of windows in the master area", "", "-- quit, or restart", "mod-Shift-q Quit xmonad", "mod-q Restart xmonad", "", "-- Workspaces & screens", "mod-[1..9] Switch to workSpace N", "mod-Shift-[1..9] Move client to workspace N", "mod-{w,e,r} Switch to physical/Xinerama screens 1, 2, or 3", "mod-Shift-{w,e,r} Move client to screen 1, 2, or 3", "", "-- Mouse bindings: default actions bound to mouse events", "mod-button1 Set the window to floating mode and move by dragging", "mod-button2 Raise the window to the top of the stack", "mod-button3 Set the window to floating mode and resize by dragging"]
ssavitzky/Honu
dotfiles/=xmonad/Config.hs
mit
14,378
0
15
3,275
2,074
1,278
796
175
1
-------------------------------------------------------------------------- -- Copyright (c) 2007-2010, ETH Zurich. -- All rights reserved. -- -- This file is distributed under the terms in the attached LICENSE file. -- If you do not find this file, copies can be found by writing to: -- ETH Zurich D-INFK, Universitätstasse 6, CH-8092 Zurich. Attn: Systems Group. -- -- Architectural definitions for Barrelfish on ARMv5 ISA. -- -- The build target is the integratorcp board on QEMU with the default -- ARM926EJ-S cpu. -- -------------------------------------------------------------------------- module ARMv7 where import HakeTypes import qualified Config import qualified ArchDefaults ------------------------------------------------------------------------- -- -- Architecture specific definitions for ARM -- ------------------------------------------------------------------------- arch = "armv7" archFamily = "arm" compiler = Config.arm_cc objcopy = Config.arm_objcopy objdump = Config.arm_objdump ar = Config.arm_ar ranlib = Config.arm_ranlib cxxcompiler = Config.arm_cxx ourCommonFlags = [ Str "-fno-unwind-tables", Str "-Wno-packed-bitfield-compat", Str "-marm", Str "-fno-stack-protector", Str "-mcpu=cortex-a9", Str "-march=armv7-a", Str "-mapcs", Str "-mabi=aapcs-linux", Str "-msingle-pic-base", Str "-mpic-register=r10", Str "-DPIC_REGISTER=R10", Str "-fPIE", Str "-ffixed-r9", Str "-DTHREAD_REGISTER=R9", Str "-D__ARM_CORTEX__", Str "-D__ARM_ARCH_7A__", Str "-Wno-unused-but-set-variable", Str "-Wno-format", Str ("-D__" ++ Config.armv7_platform ++ "__") ] cFlags = ArchDefaults.commonCFlags ++ ArchDefaults.commonFlags ++ ourCommonFlags cxxFlags = ArchDefaults.commonCxxFlags ++ ArchDefaults.commonFlags ++ ourCommonFlags cDefines = ArchDefaults.cDefines options ourLdFlags = [ Str "-Wl,-section-start,.text=0x400000", Str "-Wl,-section-start,.data=0x600000", Str "-Wl,--build-id=none" ] ldFlags = ArchDefaults.ldFlags arch ++ ourLdFlags ldCxxFlags = ArchDefaults.ldCxxFlags arch ++ ourLdFlags stdLibs = ArchDefaults.stdLibs arch ++ [ Str "-lgcc" ] options = (ArchDefaults.options arch archFamily) { optFlags = cFlags, optCxxFlags = cxxFlags, optDefines = cDefines, optDependencies = [ PreDep InstallTree arch "/include/trace_definitions/trace_defs.h", PreDep InstallTree arch "/include/errors/errno.h", PreDep InstallTree arch "/include/barrelfish_kpi/capbits.h", PreDep InstallTree arch "/include/asmoffsets.h" ], optLdFlags = ldFlags, optLdCxxFlags = ldCxxFlags, optLibs = stdLibs, optInterconnectDrivers = ["lmp", "ump"], optFlounderBackends = ["lmp", "ump"] } -- -- Compilers -- cCompiler = ArchDefaults.cCompiler arch compiler Config.cOptFlags cxxCompiler = ArchDefaults.cxxCompiler arch cxxcompiler Config.cOptFlags makeDepend = ArchDefaults.makeDepend arch compiler makeCxxDepend = ArchDefaults.makeCxxDepend arch cxxcompiler cToAssembler = ArchDefaults.cToAssembler arch compiler Config.cOptFlags assembler = ArchDefaults.assembler arch compiler Config.cOptFlags archive = ArchDefaults.archive arch linker = ArchDefaults.linker arch compiler cxxlinker = ArchDefaults.cxxlinker arch cxxcompiler -- -- The kernel is "different" -- kernelCFlags = [ Str s | s <- [ "-fno-builtin", "-fno-unwind-tables", "-nostdinc", "-std=c99", "-marm", "-mcpu=cortex-a9", "-march=armv7-a", "-mapcs", "-mabi=aapcs-linux", "-mfloat-abi=soft", "-fPIE", "-U__linux__", "-Wall", "-Wshadow", "-Wstrict-prototypes", "-Wold-style-definition", "-Wmissing-prototypes", "-Wmissing-declarations", "-Wmissing-field-initializers", "-Wredundant-decls", "-Werror", "-imacros deputy/nodeputy.h", "-fno-stack-check", "-ffreestanding", "-fomit-frame-pointer", "-mno-long-calls", "-Wmissing-noreturn", "-mno-apcs-stack-check", "-mno-apcs-reentrant", "-msingle-pic-base", "-mpic-register=r10", "-DPIC_REGISTER=R10", "-ffixed-r9", "-DTHREAD_REGISTER=R9", "-D__ARM_CORTEX__", "-D__ARM_ARCH_7A__", "-Wno-unused-but-set-variable", "-Wno-format", "-D__" ++ Config.armv7_platform ++ "__" ]] kernelLdFlags = [ Str "-Wl,-N", Str "-fno-builtin", Str "-nostdlib", Str "-pie", Str "-Wl,--fatal-warnings" ] -- -- Link the kernel (CPU Driver) -- linkKernel :: Options -> [String] -> [String] -> String -> HRule linkKernel opts objs libs name = let linkscript = "/kernel/" ++ name ++ ".lds" kernelmap = "/kernel/" ++ name ++ ".map" kasmdump = "/kernel/" ++ name ++ ".asm" kbinary = "/sbin/" ++ name kbootable = kbinary ++ ".bin" in Rules [ Rule ([ Str compiler ] ++ map Str Config.cOptFlags ++ [ NStr "-T", In BuildTree arch linkscript, Str "-o", Out arch kbinary, NStr "-Wl,-Map,", Out arch kernelmap ] ++ (optLdFlags opts) ++ [ In BuildTree arch o | o <- objs ] ++ [ In BuildTree arch l | l <- libs ] ++ [ Str "-lgcc" ] ), -- Generate kernel assembly dump Rule [ Str objdump, Str "-d", Str "-M reg-names-raw", In BuildTree arch kbinary, Str ">", Out arch kasmdump ], Rule [ Str "cpp", NStr "-I", NoDep SrcTree "src" "/kernel/include/arch/armv7", Str "-D__ASSEMBLER__", Str ("-D__" ++ Config.armv7_platform ++ "__"), Str "-P", In SrcTree "src" "/kernel/arch/armv7/linker.lds.in", Out arch linkscript ] ]
8l/barrelfish
hake/ARMv7.hs
mit
7,630
0
18
3,127
1,139
629
510
141
1
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-name-shadowing -fno-warn-unused-binds -fno-warn-unused-imports #-} module Network.Slack where import Network.Slack.Api
owainlewis/slack
src/Network/Slack.hs
mit
191
0
4
26
14
10
4
4
0
module Sound.Wave where import qualified Data.ByteString as B import System.IO import System.FilePath ((</>)) import Data.Word import Data.List import Data.List.Split import Control.Monad.Trans.Maybe import Control.Monad.IO.Class import Control.Monad import Data.Functor data WaveFile = WaveFile { handle :: Handle , numChannels :: Int , sampleRate :: Int , sampleSize :: Int , readStart :: Int , samplesRead :: Int , totalSamples :: Int } deriving Show checkRiffHeader :: B.ByteString -> Bool checkRiffHeader header = riff == [82, 73, 70, 70] && format == [87, 65, 86, 69] where riff = B.unpack $ B.take 4 header format = B.unpack . B.take 4 $ B.drop 8 header readLittleEndian :: [Word8] -> Int readLittleEndian = foldr (\num prod -> 256 * prod + fromIntegral num) 0 readFmtSubChunk :: Handle -> MaybeT IO B.ByteString readFmtSubChunk handle = do header <- liftIO $ B.hGet handle 8 guard $ (B.unpack $ B.take 4 header) == [0x66, 0x6d, 0x74, 0x20] let sizeBytes = B.unpack . B.take 4 $ B.drop 4 header let size = readLittleEndian sizeBytes chunkData <- liftIO $ B.hGet handle size return chunkData splitByteString :: B.ByteString -> [Int] -> [B.ByteString] splitByteString string [] = [string] splitByteString string (x:xs) = (B.take x string) : splitByteString (B.drop x string) xs makeWaveFile :: Handle -> B.ByteString -> WaveFile makeWaveFile handle formatChunk = WaveFile handle channels sampleRate (sampleSize `div` 8) (riffChunkSize + fmtChunkSize) 0 0 where formatData:channelData:sampleRateData:_:_:sampleSizeData:_ = splitByteString formatChunk [2, 2, 4, 4, 2, 2] 1 = readLittleEndian $ B.unpack formatData channels = readLittleEndian $ B.unpack channelData sampleRate = readLittleEndian $ B.unpack sampleRateData sampleSize = readLittleEndian $ B.unpack sampleSizeData riffChunkSize = 12 fmtChunkSize = B.length formatChunk + 8 setupWaveFile :: WaveFile -> MaybeT IO WaveFile setupWaveFile file = do header <- liftIO $ B.hGet (handle file) 8 guard $ (B.unpack $ B.take 4 header) == [0x64, 0x61, 0x74, 0x61] let chunkSize = readLittleEndian $ B.unpack $ B.take 4 $ B.drop 4 header return file { totalSamples = chunkSize `div` (numChannels file) `div` (sampleSize file) , readStart = (readStart file) + 8 } readSamples :: WaveFile -> Int -> IO (WaveFile, [Int]) readSamples file num = do sampleData <- B.hGet (handle file) dataSize let samples = map readLittleEndian $ chunksOf (sampleSize file) $ B.unpack sampleData return (file { samplesRead = (samplesRead file) + toRead }, samples) where toRead = min num (totalSamples file - samplesRead file) dataSize = toRead * (numChannels file) * (sampleSize file) rewindWaveFile :: WaveFile -> IO WaveFile rewindWaveFile file = do hSeek (handle file) AbsoluteSeek (fromIntegral $ readStart file) return file { samplesRead = 0 } createWaveFile :: FilePath -> MaybeT IO WaveFile createWaveFile path = do file <- liftIO $ openFile path ReadMode headerCorrect <- liftIO $ checkRiffHeader <$> B.hGet file 12 guard headerCorrect subChunk <- readFmtSubChunk file let waveFile = makeWaveFile file subChunk setupWaveFile waveFile deleteWaveFile :: WaveFile -> IO () deleteWaveFile file = do hClose (handle file)
xymostech/hpong
src/Sound/Wave.hs
mit
3,317
0
14
632
1,222
632
590
80
1
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} module Y2017.M10.D23.Exercise where {-- Here I am! Rock me like a Hurricane! The NYT archives has a plethora of articles classified by subject, as we saw last week. This week, we're going to start teasing apart the archives by subject. Select a subject, get its index, and from the index, extract the articles on that subject. As for me, I'm picking 'Hurricanes.' --} import Data.Aeson import Data.Aeson.Encode.Pretty import qualified Data.ByteString.Lazy.Char8 as BL import Data.Time import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.SqlQQ import Database.PostgreSQL.Simple.FromRow -- below imports available via 1HaskellADay git repository import Store.SQL.Connection import Store.SQL.Util.Indexed import Store.SQL.Util.Pivots import Y2017.M10.D04.Exercise (Topic, fetchSubjects, Subject) -- from fetchSubjects we get subject and their ids. Now get an id for a subject: subjectId :: Topic -> [Subject] -> Maybe Integer subjectId subj subjs = undefined -- Now, from that subject id, get the associated article ids from the pivot table articleIdsFromSubject :: Connection -> Integer -> IO [Integer] articleIdsFromSubject conn = undefined -- the SQL for that: articleSubjectPivotStmt :: Query articleSubjectPivotStmt = [sql|SELECT article_id FROM article_subject WHERE subject_id IN ?|] -- save out your article Ids, prettily, to file for later analyses artIds2File :: FilePath -> [Integer] -> IO () artIds2File file artIds = undefined -- Now we have our article ids. Get the articles articlesStmt :: Query articlesStmt = [sql|SELECT src_id, title, author, publish_dt, abstract, url, section, full_text, people, locations FROM article WHERE id IN ?|] -- Okay, this is neat. I have a structure for storing articles (Article), but -- I don't have a structure for extracting them. So, guess what we're doing now? data ArticleProxy = ArtProxy Integer String (Maybe String) Day String FilePath (Maybe String) String String String instance FromRow ArticleProxy where fromRow = undefined -- oh, boy. -- but the article proxy exists only for a moment, we hope... articles :: Connection -> [Integer] -> IO [Article] articles conn artIds = undefined prxy2art :: Integer -> ArticleProxy -> Article prxy2art idx proxy = undefined -- ...because we immediately reify them as articles: data Article = Art { artIdx, srcIdx :: Integer, title :: String, author :: Maybe String, published :: Day, abstract :: Maybe String, url :: Maybe FilePath, section :: Maybe String, fullText :: String, people, locations :: Maybe String } deriving (Eq, Show) -- How many articles are in the subject you chose? -- How many articles are relevant? ... hm. -- Save out your articles to file as JSON for further study: instance ToJSON Article where toJSON art = undefined writeArticles :: FilePath -> [Article] -> IO () writeArticles file arts = undefined -- we'll be studying articles by topic this week
geophf/1HaskellADay
exercises/HAD/Y2017/M10/D23/Exercise.hs
mit
3,181
0
9
685
472
283
189
49
1
module GiveYouAHead.Build ( build ) where import System.Directory(getDirectoryContents,doesFileExist) import System.Process(createProcess,shell,waitForProcess) import GiveYouAHead.Common(getDataDir,writeF,readF) import GiveYouAHead.Build.File(getFilesList,getOptionsFromFile) import Data.GiveYouAHead(USettings(..)) import Data.GiveYouAHead.JSON(getUSettings) import Macro.MacroParser(MacroNode(..)) import Macro.MacroIO(getMacroFromFile) import Macro.MacroReplace(findMacro,splitMacroDef,toText) build :: String -- build template if null means default -> [String] -- list -> IO() build tp list' = do ignore <- readIgnore ".gyah/build.ignore" us' <- getDataDir >>= (getUSettings.(++"/usettings")) let (Just us) =us' cc <- getDirectoryContents "." mnode <- getMacroFromFile $ if null tp then "build.default" else "build." ++ tp bsnode <- getMacroFromFile "global.build.macros" let (as,bs) = splitMacroDef mnode (files,fileeos) <- getEO cc as ignore let bsmacro = fst $ splitMacroDef bsnode writeF (".makefile"++findMacro bsmacro "makefileBack") $ concatMap show $ toText (mn' as files fileeos,bs) (_,_,_,pHandle) <- createProcess $ shell $ sysShell us ++ " .makefile" ++ findMacro bsmacro "makefileBack" _ <- waitForProcess pHandle return () where list ccontents mn ignore= if null list' then delIgnore (lines ignore) $ getFilesList (findMacro mn "FE") ccontents else getFilesList (findMacro mn "FE") $ map ((++ findMacro mn "numRight").(findMacro mn "numLeft" ++)) list' mn' mn files fileeos= List "files" files:List "fileeos" fileeos:mn delIgnore _ [] = [] delIgnore is (x:xs) | x `elem` is = delIgnore is xs | otherwise = x : delIgnore is xs readIgnore x = do y <- doesFileExist x if y then readF x else return "" getEO :: [String] -> [MacroNode] -> String -> IO ([String],[String]) getEO cc mn ig = l $ list cc mn ig where l :: [String] -> IO ([String],[String]) l [] = return ([],[]) l (x:xs) = do (rtx,rty) <- getOptionsFromFile (findMacro mn "commitmark") (findMacro mn "eobegin") (findMacro mn "eoend") x (sx,sy) <- l xs return (rtx:sx,rty:sy)
Qinka/GiveYouAHead
lib/GiveYouAHead/Build.hs
mit
2,618
2
14
836
860
444
416
54
6
module Main where import Graphics.GLUtil (offset0) import Control.Monad (unless) import Graphics.Rendering.OpenGL import Graphics.UI.GLUT hiding (exit) import Foreign.Marshal.Array (withArray) import Foreign.Storable (sizeOf) import System.Exit (exitFailure) main :: IO () main = do getArgsAndInitialize initialDisplayMode $= [DoubleBuffered, RGBAMode] initialWindowSize $= Size 1024 768 initialWindowPosition $= Position 100 100 createWindow "Tutorial 04" vbo <- createVertexBuffer compileShaders initializeGlutCallbacks vbo clearColor $= Color4 0 0 0 0 mainLoop initializeGlutCallbacks :: BufferObject -> IO () initializeGlutCallbacks vbo = displayCallback $= renderSceneCB vbo createVertexBuffer :: IO BufferObject createVertexBuffer = do vbo <- genObjectName bindBuffer ArrayBuffer $= Just vbo withArray vertices $ \ptr -> bufferData ArrayBuffer $= (size, ptr, StaticDraw) return vbo where vertices :: [Vertex3 GLfloat] vertices = [ Vertex3 (-1) (-1) 0 , Vertex3 1 (-1) 0 , Vertex3 0 1 0 ] numVertices = length vertices vertexSize = sizeOf (head vertices) size = fromIntegral (numVertices * vertexSize) compileShaders :: IO () compileShaders = do shaderProgram <- createProgram addShader shaderProgram "tutorial04/shader.vs" VertexShader addShader shaderProgram "tutorial04/shader.fs" FragmentShader linkProgram shaderProgram linkStatus shaderProgram >>= \ status -> unless status $ do errorLog <- programInfoLog shaderProgram putStrLn $ "Error linking shader program: '" ++ errorLog ++ "'" exitFailure validateProgram shaderProgram validateStatus shaderProgram >>= \ status -> unless status $ do errorLog <- programInfoLog shaderProgram putStrLn $ "Invalid shader program: '" ++ errorLog ++ "'" exitFailure currentProgram $= Just shaderProgram addShader :: Program -> FilePath -> ShaderType -> IO () addShader shaderProgram shaderFile shaderType = do shaderText <- readFile shaderFile shaderObj <- createShader shaderType shaderSourceBS shaderObj $= packUtf8 shaderText compileShader shaderObj compileStatus shaderObj >>= \ status -> unless status $ do errorLog <- shaderInfoLog shaderObj putStrLn ("Error compiling shader type " ++ show shaderType ++ ": '" ++ errorLog ++ "'") exitFailure attachShader shaderProgram shaderObj renderSceneCB :: BufferObject -> IO () renderSceneCB vbo = do clear [ColorBuffer] vertexAttribArray vPosition $= Enabled bindBuffer ArrayBuffer $= Just vbo vertexAttribPointer vPosition $= (ToFloat, VertexArrayDescriptor 3 Float 0 offset0) drawArrays Triangles 0 3 vertexAttribArray vPosition $= Disabled swapBuffers where vPosition = AttribLocation 0
triplepointfive/hogldev
tutorial04/Tutorial04.hs
mit
2,993
0
18
737
788
372
416
76
1
{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE DeriveGeneric #-} ----------------------------------------------------------------------------- -- -- Module : Network.Google.FusionTables -- Copyright : (c) 2013 Ryan Newton -- License : MIT -- -- Maintainer : Ryan Newton <[email protected]> -- Stability : Stable -- Portability : Portable -- -- | Functions for accessing the Fusion Tables API, see -- <https://developers.google.com/fusiontables/>. -- -- This provides a very limited subset of the complete (v1) API at present. ----------------------------------------------------------------------------- module Network.Google.FusionTables ( -- * Types TableId, TableMetadata(..), ColumnMetadata(..), CellType(..) -- * One-to-one wrappers around API routines, with parsing of JSON results , createTable, createColumn , listTables, listColumns -- , sqlQuery -- * Higher level interface to common SQL queries , insertRows -- , filterRows , bulkImportRows -- js experimentation , getData, ColData(..), FTValue(..), tableSelect , tableSQLQuery ) where import Control.Monad (liftM, unless) import Data.Maybe (mapMaybe) import Data.List as L import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as BL import Network.Google (AccessToken, ProjectId, doRequest, makeRequest, appendBody, appendHeaders) import Network.HTTP.Conduit (Request(..), RequestBody(..),parseUrl) import qualified Network.HTTP as H import Text.XML.Light (Element(elContent), QName(..), filterChildrenName, findChild, strContent) -- TODO: Ideally this dependency wouldn't exist here and the user could select their -- own JSON parsing lib (e.g. Aeson). import Text.JSON (JSObject(..), JSValue(..), Result(Ok,Error), decode, valFromObj, toJSObject, toJSString, fromJSString,readJSON) import Text.JSON.Pretty (pp_value) -- For easy pretty printing: import Text.PrettyPrint.GenericPretty (Out(doc,docPrec), Generic) import Text.PrettyPrint.HughesPJ (text, render) import Text.Printf (printf) -------------------------------------------------------------------------------- -- Haskell Types corresponding to JSON responses -- This could include non-ASCII characters: -- TODO: Use Data.Text -- type FTString = B.ByteString type FTString = String -- | An incomplete representation of <https://developers.google.com/fusiontables/docs/v1/reference/table#resource> data TableMetadata = TableMetadata { tab_name :: FTString , tab_tableId :: FTString , tab_columns :: [ColumnMetadata] } deriving (Eq, Show, Read, Ord, Generic) data ColumnMetadata = ColumnMetadata { col_columnId :: Int , col_name :: FTString , col_type :: FTString } deriving (Eq, Show, Read, Ord, Generic) -- TODO: Use Data.Aeson.TH instance Out TableMetadata instance Out ColumnMetadata -- instance Out B.ByteString where docPrec _ = text . B.unpack; doc = docPrec 0 -- | ID for a specific fusion table type TableId = FTString -------------------------------------------------------------------------------- -- | The host for API access. fusiontableHost :: String -- fusiontableHost = "https://www.googleapis.com/fusiontables/v1" fusiontableHost = "www.googleapis.com" -- | The API version used here. fusiontableApi :: (String, String) -- FIXME: This is meaningless because we're using the new discovery-based API, *NOT* -- the old GData APIs. fusiontableApi = ("Gdata-version", "999") -- | Create an (exportable) table with a given name and list of columns. createTable :: AccessToken -> String -> [(FTString,CellType)] -> IO TableMetadata createTable tok name cols = do response <- doRequest req let Ok final = parseTable response return final where req = appendHeaders [("Content-Type", "application/json")] $ appendBody (BL.pack json) (makeRequest tok fusiontableApi "POST" (fusiontableHost, "fusiontables/v1/tables" )) json :: String json = render$ pp_value$ JSObject$ toJSObject$ [ ("name",str name) , ("isExportable", JSBool True) , ("columns", colsJS) ] colsJS = JSArray (map fn cols) fn (colName, colTy) = JSObject$ toJSObject [ ("name", str colName) , ("kind", str "fusiontables#column") , ("type", str$ show colTy) ] str = JSString . toJSString -- | Create a new column in a given table. Returns the metadata for the new column. createColumn :: AccessToken -> TableId -> (FTString,CellType) -> IO ColumnMetadata createColumn tok tab_tableId (colName,colTy) = do response <- doRequest req let Ok final = parseColumn response return final where req = appendHeaders [("Content-Type", "application/json")] $ appendBody (BL.pack json) (makeRequest tok fusiontableApi "POST" (fusiontableHost, "fusiontables/v1/tables/"++tab_tableId++"/columns" )) json :: String json = render$ pp_value$ JSObject$ toJSObject$ [ ("name",str colName) , ("type",str$ show colTy) ] str = JSString . toJSString -- | Designed to mirror the types listed here: -- <https://developers.google.com/fusiontables/docs/v1/reference/column> data CellType = NUMBER | STRING | LOCATION | DATETIME deriving (Show,Eq,Ord,Read) -- | List all tables belonging to a user. -- See <https://developers.google.com/fusiontables/docs/v1/reference/table/list>. listTables :: AccessToken -- ^ The OAuth 2.0 access token. -> IO [TableMetadata] listTables accessToken = do resp <- doRequest req case parseTables resp of Ok x -> return x Error err -> error$ "listTables: failed to parse JSON response, error was:\n " ++err++"\nJSON response was:\n "++show resp where req = makeRequest accessToken fusiontableApi "GET" ( fusiontableHost, "fusiontables/v1/tables" ) -- | Construct a simple Haskell representation of the result of `listTables`. parseTables :: JSValue -> Result [TableMetadata] parseTables (JSObject ob) = do JSArray allTables <- valFromObj "items" ob mapM parseTable allTables parseTable :: JSValue -> Result TableMetadata parseTable (JSObject ob) = do tab_name <- valFromObj "name" ob tab_tableId <- valFromObj "tableId" ob tab_columns <- mapM parseColumn =<< valFromObj "columns" ob return TableMetadata {tab_name, tab_tableId, tab_columns} parseTable oth = Error$ "parseTable: Expected JSObject, got "++show oth parseColumn :: JSValue -> Result ColumnMetadata parseColumn (JSObject ob) = do col_name <- valFromObj "name" ob col_columnId <- valFromObj "columnId" ob col_type <- valFromObj "type" ob return ColumnMetadata {col_name, col_type, col_columnId} parseColumn oth = Error$ "parseColumn: Expected JSObject, got "++show oth -- | List the columns within a specific table. -- See <https://developers.google.com/fusiontables/docs/v1/reference/column/list>. listColumns :: AccessToken -- ^ The OAuth 2.0 access token. -> TableId -- ^ which table -> IO [ColumnMetadata] listColumns accessToken tid = do resp <- doRequest req case parseColumns resp of Ok x -> return x Error err -> error$ "listColumns: failed to parse JSON response:\n"++err where req = makeRequest accessToken fusiontableApi "GET" ( fusiontableHost, "fusiontables/v1/tables/"++tid++"/columns" ) -- | Parse the output of `listColumns`. parseColumns :: JSValue -> Result [ColumnMetadata] parseColumns (JSObject ob) = do JSArray cols <- valFromObj "items" ob mapM parseColumn cols -------------------------------------------------------------------------------- sqlQuery = error "sqlQuery" -- | Insert one or more rows into a table. Rows are represented as lists of strings. -- The columns being written are passed in as a separate list. The length of all -- rows must match eachother and must match the list of column names. -- -- NOTE: this method has a major limitation. SQL queries are encoded into the URL, -- and it is very easy to exceed the maximum URL length accepted by Google APIs. insertRows :: AccessToken -> TableId -> [FTString] -- ^ Which columns to write. -> [[FTString]] -- ^ Rows -> IO () insertRows tok tid cols rows = doRequest req where req = (makeRequest tok fusiontableApi "POST" (fusiontableHost, "fusiontables/v1/query" )) { queryString = B.pack$ H.urlEncodeVars [("sql",query)] } query = concat $ L.intersperse ";\n" $ map (("INSERT INTO "++tid++" "++ colstr ++" VALUES ")++) vals numcols = length cols colstr = parens$ concat$ L.intersperse ", " cols vals = map fn rows fn row = if length row == numcols then parens$ concat$ L.intersperse ", " $ map singQuote row else error$ "insertRows: got a row with an incorrect number of arguments, expected " ++ show numcols ++": "++ show row parens s = "(" ++ s ++ ")" singQuote x = "'"++x++"'" -- | Implement a larger quantity of rows, but with the caveat that the number and order -- of columns must exactly match the schema of the fusion table on the server. -- `bulkImportRows` will perform a listing of the columns to verify this before uploading. -- -- This function also checks that the server reports receiving the same number of -- rows as were uploaded. -- -- NOTE: also use this function for LONG rows, even if there is only one. Really, -- you should almost always use this function rather thna `insertRows`. bulkImportRows :: AccessToken -> TableId -> [FTString] -- ^ Which columns to write. -> [[FTString]] -- ^ Rows -> IO () bulkImportRows tok tid cols rows = do targetSchema <- fmap (map col_name) $ listColumns tok tid unless (targetSchema == cols) $ error$ "bulkImportRows: upload schema (1) did not match server side schema (2):\n (1) "++ show cols ++"\n (2) " ++ show targetSchema let csv = unlines rowlns -- (header : rowlns) -- ARGH, they don't accept the header. -- All sanity checking must be client side [2013.11.30]. -- header = concat$ intersperse "," $ map show cols rowlns = [ concat$ intersperse "," [ "\"" ++f++"\"" | f <- row ] | row <- rows ] req = appendBody (BL.pack csv) $ (makeRequest tok fusiontableApi "POST" (fusiontableHost, "upload/fusiontables/v1/tables/"++tid++"/import" )) { queryString = B.pack $ H.urlEncodeVars [("isStrict", "true")] } resp <- doRequest req let Ok received = parseResponse resp unless (received == length rows) $ error$ "attempted to upload "++show (length rows)++ " rows, but "++show received++" received by server." return () where parseResponse :: JSValue -> Result Int parseResponse (JSObject ob) = do -- JS allTables <- valFromObj "items" ob -- JSString "fusiontables#import" <- valFromObj "kind" ob -- Sanity check. JSString num <- valFromObj "numRowsReceived" ob return$ read$ fromJSString num -- TODO: provide some basic select functionality filterRows = error "implement filterRows" --getData :: AccessToken -- -> String -- -> String -- -> Request m getData :: AccessToken -> String -- ^ Table ID -> String -- ^ The SQL expression following "SELECT" -> Maybe String -- ^ Optional expression to follow "WHERE" -> IO ColData getData = tableSelect -- tableSelect token table_id str cond -- = let req = (makeRequest token fusiontableApi "GET" -- (fusiontableHost, "/fusiontables/v1/query")) -- { -- queryString = B.pack$ H.urlEncodeVars [("sql",query)] -- } -- query = case cond of -- Nothing -> "SELECT " ++ str ++ " FROM " ++ table_id -- Just c -> "SELECT " ++ str ++ " FROM " ++ table_id ++ " WHERE " ++ c -- in do resp <- doRequest req -- case parseResponse resp of -- Ok x -> return x -- Error err -> error$ "getData: failed to parse JSON response:\n"++err -- where -- parseResponse :: JSValue -> Result ColData -- parseResponse (JSArray as) = Error "GOT ARRAY EARLY" -- parseResponse (JSObject ob) = do -- -- get array of column names (headings) -- (JSArray cols) <- valFromObj "columns" ob -- let colNom = map (\(JSString s) -> fromJSString s) cols -- -- Get array of array of data values -- (JSArray rows) <- valFromObj "rows" ob -- rows' <- mapM parseVal' rows -- return $ ColData colNom rows' -- parseVal' (JSArray ar) = mapM parseVal ar -- parseVal :: JSValue -> Result FTValue -- parseVal r@(JSRational _ _) = do -- d <- readJSON r -- return $ DoubleValue d -- parseVal (JSString s) = return $ StringValue $ fromJSString s -- parseVal _ = Error "I imagined there'd be Rationals here" -- Leave this here for backwards compat tableSelect :: AccessToken -> String -- ^ Table ID -> String -- ^ The SQL expression following "SELECT" -> Maybe String -- ^ Optional expression to follow "WHERE" -> IO ColData tableSelect token table_id str cond = tableSQLQuery token table_id query where query = case cond of Nothing -> "SELECT " ++ str ++ " FROM " ++ table_id Just c -> "SELECT " ++ str ++ " FROM " ++ table_id ++ " WHERE " ++ c -- | Run a supported SQL query to retrieve data from a fusion table. tableSQLQuery :: AccessToken -> String -- ^ Table ID -> String -- ^ Complete SQL expression. -> IO ColData tableSQLQuery token table_id query = let req = (makeRequest token fusiontableApi "GET" (fusiontableHost, "/fusiontables/v1/query")) { queryString = B.pack$ H.urlEncodeVars [("sql",query)] } -- query = case cond of -- Nothing -> "SELECT " ++ str ++ " FROM " ++ table_id -- Just c -> "SELECT " ++ str ++ " FROM " ++ table_id ++ " WHERE " ++ c in do resp <- doRequest req case parseResponse resp of Ok x -> return x Error err -> error$ "getData: failed to parse JSON response:\n"++err where parseResponse :: JSValue -> Result ColData parseResponse (JSArray as) = Error "GOT ARRAY EARLY" parseResponse (JSObject ob) = do -- get array of column names (headings) (JSArray cols) <- valFromObj "columns" ob let colNom = map (\(JSString s) -> fromJSString s) cols -- Get array of array of data values (JSArray rows) <- valFromObj "rows" ob rows' <- mapM parseVal' rows return $ ColData colNom rows' parseVal' (JSArray ar) = mapM parseVal ar parseVal :: JSValue -> Result FTValue parseVal r@(JSRational _ _) = do d <- readJSON r return $ DoubleValue d parseVal (JSString s) = return $ StringValue $ fromJSString s parseVal _ = Error "I imagined there'd be Rationals here" data FTValue = StringValue FTString | DoubleValue Double deriving (Eq, Show ) data ColData = ColData {colName :: [FTString], values :: [[FTValue]]} deriving (Eq, Show)
rrnewton/hgdata
src/Network/Google/FusionTables.hs
mit
15,662
0
16
3,929
2,908
1,581
1,327
-1
-1
-- Roles {- Roles are a further level of specification for type variables parameters of datatypes. nominal representational phantom They were added to the language to address a rather nasty and long-standing bug around the correspondence between a newtype and its runtime representation. The fundamental distinction that roles introduce is there are two notions of type equality. Two types are nominally equal when they have the same name. This is the usual equality in Haskell or Core. Two types are representationally equal when they have the same representation. (If a type is higher-kinded, all nominally equal instantiations lead to representationally equal types.) nominal - Two types are the same. representational - Two types have the same runtime representation. -} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} newtype Age = MkAge { unAge :: Int } type family Inspect x type instance Inspect Age = Int type instance Inspect Int = Bool class Boom a where boom :: a -> Inspect a instance Boom Int where boom = (== 0) deriving instance Boom Age -- GHC 7.6.3 exhibits undefined behavior failure = boom (MkAge 3) -- -6341068275333450897 -- Roles are normally inferred automatically, but with the RoleAnnotations extension they can be manually annotated. Except in rare cases this should not be necessary although it is helpful to know what is going on under the hood. {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE RoleAnnotations #-} data Nat = Zero | Suc Nat type role Vec nominal representational data Vec :: Nat -> * -> * where Nil :: Vec Zero a (:*) :: a -> Vec n a -> Vec (Suc n) a type role App representational nominal data App (f :: k -> *) (a :: k) = App (f a) type role Mu nominal nominal data Mu (f :: (k -> *) -> k -> *) (a :: k) = Roll (f (Mu f) a) type role Proxy phantom data Proxy (a :: k) = Proxy coerce :: Coercible * a b => a -> b class (~R#) k k a b => Coercible k a b
Airtnp/Freshman_Simple_Haskell_Lib
Intro/WIW/TypeFamiles/Roles.hs
mit
2,082
3
10
411
359
208
151
-1
-1
module StrawPoll.ListHelpers where dropTrailing :: (Eq a) => a -> [a] -> [a] dropTrailing item = reverse . (dropWhile (== item)) . reverse -- Add an empty item to the end of the list if we're editing the last item -- This is slow since it repeatedly calls length. padToMinLength :: Int -> a -> [a] -> [a] padToMinLength l val arr = if length arr < l then padToMinLength l val (arr ++ [val]) else arr
cschneid/strawpollhs
src/shared/StrawPoll/ListHelpers.hs
mit
457
0
9
134
129
72
57
7
2
module Proteome.Data.Replace where import Prelude hiding (lines) import Ribosome.Data.Scratch (Scratch) import Proteome.Data.GrepOutputLine (GrepOutputLine) data Replace = Replace { _scratch :: Scratch, _lines :: NonEmpty GrepOutputLine } deriving stock (Eq, Show) makeClassy ''Replace
tek/proteome
packages/proteome/lib/Proteome/Data/Replace.hs
mit
304
0
9
50
83
49
34
-1
-1
import DartShots(findFinish, showFinish) tableCounts = [40..180] checkoutTable = map finishWithCount tableCounts where finishWithCount count = show count ++ ": " ++ (showFinish . findFinish $ count) main = putStr . unlines $ checkoutTable
urmastalimaa/darts-calculator
src/CheckoutTable.hs
mit
243
0
10
37
77
41
36
5
1
module Main where import Control.Monad import Control.Concurrent import Control.Concurrent.STM import System.Random import Text.Printf import Debug.Trace -- Forks type Fork = TMVar Int newFork :: Int -> IO Fork newFork i = newTMVarIO i takeFork :: Fork -> STM Int takeFork fork = takeTMVar fork releaseFork :: Int -> Fork -> STM () releaseFork i fork = putTMVar fork i -- Philosophers runPhilosopher :: String -> (Fork, Fork) -> IO () runPhilosopher name (left, right) = forever $ do putStrLn (name ++ " is hungry.") (leftNum, rightNum) <- atomically $ do leftNum <- trace (name ++ " trying to grab left fork") takeFork left rightNum <- trace (name ++ " trying to grab right fork") takeFork right return (leftNum, rightNum) putStrLn $ printf "%s got forks %d and %d and is now eating" name leftNum rightNum delay <- randomRIO (1, 3) threadDelay (delay * 1000000) putStrLn (name ++ " is done eating. Going back to thinking.") atomically $ do releaseFork leftNum left releaseFork rightNum right delay <- randomRIO (1, 3) threadDelay (delay * 1000000) philosophers :: [String] philosophers = ["Aristotle", "Kant", "Spinoza", "Marx", "Russel"] main = do forks <- mapM newFork [1 .. 5] let namedPhilosophers = map runPhilosopher philosophers forkPairs = zip forks (tail . cycle $ forks) philosophersWithForks = zipWith ($) namedPhilosophers forkPairs putStrLn "Running the philosophers. Press enter to quit." mapM_ forkIO philosophersWithForks -- All threads exit when the main thread exits. getLine
NickAger/LearningHaskell
ParallelConcurrent/diningPhilosophers/app/Main.hs
mit
1,706
0
15
446
481
244
237
40
1
{-# LANGUAGE ExistentialQuantification, RankNTypes, Rank2Types #-} module Pitch.Game (mkRoundState ,mkGameState ,playGame ,Player (..) ,defaultPlayer ,Hand (..) ,Bid (..) ,Play (..) ,Trick (..) ,validateBidAmount ,validateBidSuit ,validateCard ,validateBid ,GameState (..) ,RoundState (..) ) where import Control.Monad import Control.Monad.State import Data.List import Data.Maybe import Data.Monoid import Data.Ord import Pitch.Card import Pitch.Deck import Pitch.Parser import Pitch.Utils import System.Random import Text.Printf (printf) import qualified Pitch.Internal.Game as G import Pitch.Internal.PartialGame import Pitch.Internal.Common type Pitch = StateT G.GameState IO newTrick :: Trick newTrick = Trick [] (-1) mkRoundState :: StdGen -> [PlayerId] -> (G.RoundState, StdGen) mkRoundState g ps = (G.Round {G.deck = deck' ,G.hands = zipWith Hand hs ps ,G.bids = [] ,G.trump = minBound ,G.tricks = [] } ,g' ) where (hs, deck') = runState (forM ps (const $ deal 6)) d (d, g') = mkDeck g partialRound :: G.RoundState -> RoundState partialRound G.Round{G.bids=bids ,G.trump=trump ,G.tricks=tricks } = Round bids trump tricks partialGame :: PlayerId -> G.GameState -> GameState partialGame pid G.Game{G.scores=scores ,G.players=players ,G.rounds=rounds } = Game scores (map show players) (map partialRound rounds) hand where hand = cards $ fromMaybe (Hand [] pid) . find ((== pid) . ownerIdx) $ G.hands (head rounds) wonBid :: Int -> G.RoundState -> Bool wonBid n rs = bidderIdx (maximumBy (comparing amount) (G.bids rs)) == n mkGameState :: StdGen -> [Player] -> G.GameState mkGameState g ps = G.Game {G.players = playerList ,G.scores = map (\(pid,_) -> (pid, 0)) playerList ,G.generator = g ,G.rounds = [] ,G.dealers = cycle playerList } where playerList = zip [1..] ps lastRound :: G.GameState -> G.RoundState lastRound = head . G.rounds checkForWinner :: Pitch (Maybe (PlayerId, Int)) checkForWinner = do [email protected]{G.scores=ss} <- get if any ((>= 11) . snd) ss then let overScores = filter ((>= 11) . snd) ss in return $ find (\(widx, _) -> wonBid widx (lastRound gs)) overScores else return Nothing validateBidAmount :: PlayerId -> GameState -> Int -> Maybe String validateBidAmount pid gs@(Game scores ps (r@(Round bids trump tricks):rs) hand) x | x `notElem` [0, 2, 3, 4] = Just "A valid bid is 0 (pass), 2, 3, or 4" | x /= 0 && any (>= x) (map amount bids) = Just $ "You need to bid more than " ++ show (maximum $ map amount bids) | x == 0 && length bids + 1 == length ps && maximum (map amount bids) == 0 = Just "Since you are the last player to bid and everyone else has passed, you must bid at least 2" | otherwise = Nothing validateBidSuit :: PlayerId -> GameState -> Int -> Maybe Suit -> Maybe String validateBidSuit _ _ x Nothing | x /= 0 = Just "You must specify a suit" | otherwise = Nothing validateBidSuit pid Game{hand=hand} x (Just s) | s `notElem` map suit hand = Just "You don't have any cards of that suit" | otherwise = Nothing validateBid :: PlayerId -> GameState -> (Int, Maybe Suit) -> Maybe String validateBid pid q (x, s) = getFirst $ First (validateBidAmount pid q x) <> First (validateBidSuit pid q x s) validateCard :: PlayerId -> GameState -> Card -> Maybe String validateCard pid (Game scoresp ps (Round bids trump (Trick{played=played}:ts):rs) hand) c | c `notElem` hand = Just "You don't have that card" | null ts && null played && suit c /= trump = Just "You must lead trump" | suit c /= trump && not (null played) && suit c /= suit (card (last played)) && suit (card (last played)) `elem` map suit hand = Just "You must play trump or follow suit" | otherwise = Nothing doBid :: (PlayerId, Player) -> Pitch () doBid (pid, p) = do [email protected]{G.players=ps ,[email protected]{G.hands=hands ,G.bids=bs }:rs } <- get (amount, suit) <- liftIO $ (mkBid p) pid $ partialGame pid g let newBid = Bid amount suit pid newState = g{G.rounds=r{G.bids=newBid:bs}:rs} put newState liftIO $ forM_ ps (\(pid, p) -> (postBidHook p) pid newBid $ partialGame pid newState) doPlay :: (PlayerId, Player) -> Pitch () doPlay (pid, p) = do [email protected]{G.players=ps ,[email protected]{G.hands=hands ,G.tricks=t@Trick{played=played}:ts}:rs } <- get card <- liftIO $ (mkPlay p) pid $ partialGame pid g let newPlay = Play card pid newGS = g{G.rounds=r{G.tricks=t{played=newPlay:played}:ts ,G.hands=removeCard card hands }:rs } put newGS liftIO $ forM_ ps (\(pid, p) -> (postPlayHook p) pid newPlay $ partialGame pid newGS) where removeCard c [] = [] removeCard c (h@Hand{cards=cs,ownerIdx=i}:hs) | i == pid = h{cards=delete c cs}:hs | otherwise = h:removeCard c hs trickWinner :: Suit -> Trick -> Trick trickWinner trump trick@(Trick plays winner) | winner /= -1 = trick | otherwise = let trumpPlayed = filter ((== trump) . suit . card) plays firstPlayed = card $ last plays Play _ idx = maximumBy (comparing (rank . card)) $ if not $ null trumpPlayed then trumpPlayed else filter ((== suit firstPlayed) . suit . card) plays in Trick plays idx tallyScore :: Suit -> [Trick] -> (PlayerId, Player) -> (PlayerId, (Int, Int)) tallyScore trump tricks (pid, _) = let tricksWon = filter ((== pid) . winnerIdx) tricks cardsWon = map card $ concatMap played tricksWon trumpWon = filter ((== trump) . suit) cardsWon allCards = map card $ concatMap played tricks allTrump = filter ((== trump) . suit) allCards jack = if Card Jack trump `elem` cardsWon then 1 else 0 hi = if not (null trumpWon) && maximumBy (comparing rank) trumpWon == maximumBy (comparing rank) allTrump then 1 else 0 lo = if not (null trumpWon) && minimumBy (comparing rank) trumpWon == minimumBy (comparing rank) allTrump then 1 else 0 game = sum $ map gamePoints cardsWon in (pid, (hi + lo + jack, game)) gamePoints :: Card -> Int gamePoints (Card r _) = rankToGame r where rankToGame Jack = 1 rankToGame Queen = 2 rankToGame King = 3 rankToGame Ace = 4 rankToGame (Number 10) = 10 rankToGame _ = 0 playTrick :: Pitch Trick playTrick = do [email protected] {[email protected]{G.bids=bids ,G.tricks=ts }:rs ,G.dealers=ds ,G.players=ps } <- get let startingPlayerIdx = if null ts then bidderIdx $ maximumBy (comparing amount) bids else winnerIdx $ head ts put g{G.rounds=r{G.tricks=newTrick:ts}:rs} let playOrder = take (length ps) $ dropWhile ((/= startingPlayerIdx) . fst) (cycle ps) forM_ playOrder doPlay [email protected] {[email protected]{G.tricks=t:ts ,G.trump=trump }:rs } <- get let t' = trickWinner trump t put g{G.rounds=r{G.tricks=t':ts}:rs} return t' playRound :: Pitch () playRound = do liftIO $ putStrLn "playing a round" [email protected] {G.players=ps ,G.generator=gtr ,G.rounds=rs ,G.dealers=ds ,G.scores=ss } <- get lift $ print g let (r, gtr') = mkRoundState gtr (map fst ps) newState = g{G.rounds=r:rs ,G.generator=gtr' } lift $ print newState liftIO $ forM_ ps (\(pid, p) -> (initGameState p) pid $ partialGame pid newState) put newState forM_ (take (length ps) ds) doBid [email protected] {G.dealers=d:ds ,[email protected]{G.bids=bids}:rs } <- get let maxBid = maximumBy (comparing amount) bids trump = fromJust $ bidSuit maxBid put g{G.dealers=ds ,G.rounds=r{G.trump=trump}:rs } liftIO $ forM_ ps (\(pid, p) -> (acknowledgeTrump p) pid maxBid $ partialGame pid g) tricks <- forM [1 .. 6] (const playTrick) let roundTalliesAndGame = map (tallyScore trump tricks) ps roundTallies = map (\(pid, (pts, game)) -> if game == maximum (map (snd . snd) roundTalliesAndGame) then (pid, pts + 1) else (pid, pts)) roundTalliesAndGame roundScores = map (\(pid, score) -> if pid /= bidderIdx maxBid || score >= amount maxBid then score else (-1 * amount maxBid)) roundTallies newScores = zipWith (\(pid, s1) s2 -> (pid, s1 + s2)) ss roundScores liftIO . putStr $ "Scores: " ++ show newScores g <- get put g{G.scores=newScores} return () playGame :: Pitch (PlayerId, Int) playGame = do playRound maybeWinner <- checkForWinner let winnerSt = case maybeWinner of Nothing -> playGame Just x -> return x (winP, score) <- winnerSt liftIO $ putStrLn "we have a winner" liftIO $ print score winnerSt
benweitzman/Pitch
src/Pitch/Game.hs
mit
11,889
0
21
5,228
3,759
1,968
1,791
236
6
-- The prime factors of 13195 are 5, 7, 13 and 29. -- What is the largest prime factor of the number 600851475143 ? import Data.List value :: Int value = 600851475143 sqrt' :: Int -> Int sqrt' n = ceiling $ sqrt(fromIntegral(n)) firstFactor :: Int -> [Int] firstFactor n = take 1 $ filter (\x -> (n `rem` x == 0)) [2..sqrt'(n-1)] primeFactors :: Int -> [Int] primeFactors n | firstFactor n == [] = [n] | otherwise = (firstFactor n) ++ primeFactors (n `div` (head $ firstFactor n)) calc :: [Int] calc = primeFactors value main :: IO () main = do print calc
daniel-beard/projecteulerhaskell
Problems/p3.hs
mit
579
0
12
129
235
124
111
16
1
{-# LANGUAGE BangPatterns #-} module System.Random.SplitMix.Gen ( SplitMix64(..) , toSeedGamma , withSystemRandom , newSplitMix64 , newSeededSplitMix64 , nextInt32 , nextInt64 , nextDouble ) where import Data.Word (Word32, Word64) import Data.Int (Int64) import Data.Bits ((.|.), shiftR, testBit) import System.Random (RandomGen, next, split) import Control.Applicative ((<$>), (<*>)) import Control.Arrow (first) import Test.QuickCheck (Arbitrary(arbitrary)) import System.Random.SplitMix.MathOperations (c_mix32, c_mix64, c_mixGamma) import System.Random.SplitMix.Utils (goldenGamma, acquireSeedSystem) -- | SplitMix64 generator structure, holding all the needed -- information for random number generation data SplitMix64 = SplitMix64 {-# UNPACK #-} !Word64 -- ^ seed of SplitMix64 generator {-# UNPACK #-} !Word64 -- ^ gamma of SplitMix64 generator, always odd deriving (Show, Eq) instance Arbitrary SplitMix64 where arbitrary = SplitMix64 <$> arbitrary <*> (fmap makeGammaOdd arbitrary) -- | Make gammas odd, so Arbitrary instance has a correct invariant makeGammaOdd :: Word64 -> Word64 makeGammaOdd gamma = if testBit gamma 0 then gamma else gamma .|. 1 -- | Produces a new seed value from an existing one and a gamma and -- returns an updated generator nextSeed :: SplitMix64 -> (Word64, SplitMix64) nextSeed (SplitMix64 seed gamma) = (newSeed, SplitMix64 newSeed gamma) where !newSeed = seed + gamma -- | Constant used to mix values for nextDouble function doubleUlp :: Double doubleUlp = 1.0 / 2097152 -- 1.0 / 1L << 53 -- | Unwraps the generator for reproducible testing toSeedGamma :: SplitMix64 -> (Word64, Word64) toSeedGamma (SplitMix64 seed gamma) = (seed, gamma) -- | Produces a new value of the type 'a' and an updated generator nextValue :: (Word64 -> a) -> SplitMix64 -> (a, SplitMix64) nextValue mixer = first mixer . nextSeed -- | Produces a new Int64 value and an updated generator nextInt64 :: SplitMix64 -> (Word64, SplitMix64) nextInt64 = nextValue c_mix64 -- | Produces a new Int32 value and an updated generator nextInt32 :: SplitMix64 -> (Word32, SplitMix64) nextInt32 = nextValue (fromIntegral . c_mix32) -- | Produces a new Int value and an updated generator nextInt :: SplitMix64 -> (Int, SplitMix64) nextInt = nextValue (fromIntegral . c_mix32) -- | Produces a new Double value from 53 bits of the number using 'doubleUlp' -- for mixing and an updated generator nextDouble :: SplitMix64 -> (Double, SplitMix64) nextDouble gen = (doubleUlp * fromIntegral (shiftR int64 11), newGen) where (int64, newGen) = nextInt64 gen -- | Splits the given generator into two, returning updated first generator -- and a new one with seed and gamma got from the first splitGen :: SplitMix64 -> (SplitMix64, SplitMix64) splitGen oldGen = (updatedGen', SplitMix64 (c_mix64 newSeed) (c_mixGamma newGamma)) where (!newSeed, !updatedGen) = nextSeed oldGen (!newGamma, !updatedGen') = nextSeed updatedGen -- | Uses provided seed to make a new SplitMix64 generator instance newSeededSplitMix64 :: Word64 -> SplitMix64 newSeededSplitMix64 = flip SplitMix64 $ goldenGamma -- | Makes a new instance of SplitMix64 generator using system provided -- sources of randomness. -- Will return a poorly seeded generator instance on Windows newSplitMix64 :: IO SplitMix64 newSplitMix64 = do unmixedSeed <- acquireSeedSystem return $ SplitMix64 (c_mix64 unmixedSeed) $ c_mixGamma $! unmixedSeed + goldenGamma -- | Performs a computation using a newly made SplitMix64 generator instance withSystemRandom :: (SplitMix64 -> a) -> IO a withSystemRandom f = fmap f newSplitMix64 instance RandomGen SplitMix64 where next = nextInt split = splitGen
nkartashov/SplitMix
src/System/Random/SplitMix/Gen.hs
mit
3,745
0
13
639
774
444
330
61
2
{-# LANGUAGE OverloadedStrings #-} module Main (main) where import Application import Settings import System.Random import Test.Hspec import Test.Hspec.Wai import WordList import Yesod.Core main :: IO () main = hspec spec spec :: Spec spec = withApp $ do describe "getting passphrases" $ do it "returns random passphrases" $ do get "/" `shouldRespondWith` "balk il climb stu\n" get "/" `shouldRespondWith` "mask doria one spin\n" get "/" `shouldRespondWith` "lobo hertz minor e'er\n" get "/" `shouldRespondWith` "bulge franz sturm qr\n" it "accepts a size parameter" $ do get "/?size=3" `shouldRespondWith` "balk il climb\n" withApp :: SpecWith Application -> Spec withApp = before $ do setStdGen $ mkStdGen 1 Right wordlist <- readWordList "wordlist" let settings = AppSettings { appDefaultSize = 4 , appRandomApiKey = "" , appRandomRequestSize = 20 , appWordList = wordlist } foundation <- makeFoundation settings $ do ints <- randomRs keyRange <$> newStdGen pure $ Right $ take (appRandomRequestSize settings) ints toWaiAppPlain foundation
pbrisbin/passphrase.me
test/Spec.hs
mit
1,238
0
15
348
297
150
147
35
1
{-# LANGUAGE DoAndIfThenElse #-} module DebCheck where import System.Process import Text.XML.HaXml hiding ((!),when) import Text.XML.HaXml.Posn (noPos) import System.FilePath import Control.Monad import Data.Maybe import System.IO import Data.Char import Data.Functor import qualified Data.ByteString.Char8 as BS import qualified Data.Strict as ST import qualified System.IO.Strict as ST import qualified Data.Map as M import Debug.Trace import Types import AtomIndex import Arches import qualified IndexSet as IxS findUninstallablePackages :: Config -> AtomIndex -> SuiteInfo -> FilePath -> Arch -> IO (IxS.Set Binary) findUninstallablePackages config ai suite dir arch = do let file = dir </> "Packages_" ++ show arch -- edos-debcheck does not like empty files str <- readFile file if all isSpace str then return IxS.empty else do uninstallable <- collectEdosOutput file return $ IxS.fromList $ map (\bin -> case ai `indexBin` bin of Just binI -> binI Nothing -> -- Work around http://bugs.debian.org/665248 case M.lookup (binName bin, arch) (binaryNames suite) of Nothing -> error $ show bin ++ " not found in AtomIndex or suite" Just (binI':_) -> --trace ("edos-debcheck returned " ++ show bin ++ ", using " ++ show (ai `lookupBin` binI')) $ binI' ) $ map (\(name,arch,version) -> Binary (BinName (BS.pack name)) (DebianVersion (BS.pack version)) (if arch == "all" then ST.Nothing else ST.Just (read arch))) $ uninstallable collectEdosOutput :: FilePath -> IO [(String, String, String)] collectEdosOutput file = do pkgFile <- openFile file ReadMode (_, Just edosOutH, _, pid) <- createProcess $ (proc "edos-debcheck" ["-quiet", "-xml","-failures"]) { std_in = UseHandle pkgFile, std_out = CreatePipe } edosOut <- ST.hGetContents edosOutH waitForProcess pid let Document _ _ root _ = xmlParse "edos output" edosOut -- How do you actually use this HaXmL? This can not be the correct way: let filter = concatMap ((attributed "package" `x` attributed "architecture" `x` attributed "version" `x` extracted (concat . mapMaybe fst . textlabelled (txt `o` children)) ) keep) . (elm `o` children) return $ map (\((((p,a),v),_),_) -> (p, a, v)) (filter (CElem root noPos))
nomeata/sat-britney
DebCheck.hs
gpl-2.0
2,598
0
24
748
742
405
337
53
5
module Parser ( exec, execString, dynDeepScope, dynShallowScope, staticShallowScope, staticDeepScope, ScopeConfig, SymbolValue(..), Environment, Log, Logunit(..), symtableValues, symtableName, envStack, wGetLine, staticChain ) where import Prelude hiding (foldr,concatMap,concat) import Text.ParserCombinators.Parsec hiding ((<|>), many) import qualified Text.ParserCombinators.Parsec.Token as Tok import Text.ParserCombinators.Parsec.Language import Text.ParserCombinators.Parsec.Expr import Data.Map as Map hiding (map,foldr) import Data.Functor import Data.List (intercalate,isPrefixOf) import Data.Maybe import Data.Foldable import Control.Applicative import qualified Control.Monad.RWS as RWS import Control.Monad import Control.DeepSeq import System.IO.Unsafe import qualified Data.Sequence as S import Debug.Trace import Data.Monoid flagDebug :: Bool flagDebug = True type Ident = String type FunctArgs = [(Ident,Type)] data Block = Block Int Integer [Stmt] deriving Show instance Eq Block where (Block _ a _) == (Block _ b _) = a == b class WithLine a where wGetLine :: a -> Int data Stmt = DeclVar Int Ident Type | DeclFunct Int Ident FunctArgs Type Block | Assign Int Ident Expr | CallProc Int Ident [Expr] | ControlIf Int Expr Block Block | CallPrint Int Expr | CallPrintLn Int Expr | Return Int (Maybe Expr) | EndProg {-deriving Show-} instance Show Stmt where show = stmtShow instance WithLine Stmt where wGetLine (DeclVar n _ _) = n wGetLine (DeclFunct n _ _ _ _) = n wGetLine (Assign n _ _) = n wGetLine (CallProc n _ _) = n wGetLine (ControlIf n _ _ _) = n wGetLine (CallPrint n _) = n wGetLine (CallPrintLn n _) = n wGetLine (Return n _ ) = n wGetLine (EndProg) = -1 stmtShow :: Stmt -> String stmtShow (DeclVar l name typ) = show l ++ ": var "++name++" : "++ show typ stmtShow (DeclFunct l name fargs typ _) = show l ++ ": sub "++name++ fargs'++" : "++ show typ ++" {...}" where fargs' = "(" ++ intercalate "," (map (\(x,y) -> x ++":" ++ show y) fargs) ++ ")" stmtShow (Assign l name expression) = show l ++ ": "++name++" = "++ show expression stmtShow (CallProc l name fargs) = show l ++ ": "++name++" ("++ intercalate "," (map show fargs) ++ ") " stmtShow (ControlIf l expression _ _) = show l ++ ": if ("++show expression++") " stmtShow (CallPrint l expression) = show l ++ ": print("++show expression++") " stmtShow (CallPrintLn l expression) = show l ++ ": printLn("++show expression++") " stmtShow (Return l expression) = show l ++ ": return "++show expression stmtShow (EndProg) = "Program ended" data Type = TInt | TFunct | TBool | TString | TVoid deriving (Eq) {-deriving (Show,Eq)-} instance Show Type where show = typeShow typeShow :: Type -> String typeShow (TInt) = "int" typeShow (TFunct) = "sub" typeShow (TBool) = "bool" typeShow (TString) = "String" typeShow (TVoid) = "Void" data Expr = Var Int Ident | IntLiteral Int Integer | BoolLiteral Int Bool | StringLiteral Int String | CallFunct Int Ident [Expr] | UnaryExp Int UnaryOP Expr | BinaryExp Int BinaryOP Expr Expr {-deriving Show-} instance Show Expr where show = exprShow instance WithLine Expr where wGetLine (Var n _) = n wGetLine (IntLiteral n _) = n wGetLine (BoolLiteral n _) = n wGetLine (StringLiteral n _) = n wGetLine (CallFunct n _ _) = n wGetLine (UnaryExp n _ _) = n wGetLine (BinaryExp n _ _ _) = n exprShow :: Expr -> Ident exprShow (Var _ name) = name exprShow (IntLiteral _ n) = show n exprShow (BoolLiteral _ b) = show b exprShow (StringLiteral _ s) = s exprShow (CallFunct _ name fargs) = name ++ "(" ++ intercalate "," (map show fargs) ++ ")" exprShow (UnaryExp _ op expr') = "(" ++ show op ++" "++ show expr' ++ ")" exprShow (BinaryExp _ op expr1 expr2 ) = "(" ++show expr1 ++" "++ show op ++" "++ show expr2 ++ ")" data UnaryOP = Negate | Not {-deriving(Show)-} instance Show UnaryOP where show = uopShow uopShow :: UnaryOP -> String uopShow (Negate) = "-" uopShow (Not) = "!" data BinaryOP = Add {-Aritmetic-} | Mult | Div | Minus | Mod | And {-Boolean-} | Or | LessT {-Comparisons-} | LessTE | GreaterT | GreaterTE | Equals | NEquals {-deriving Show-} instance Show BinaryOP where show = bopShow bopShow :: BinaryOP -> String bopShow (Add) = "+" bopShow (Mult) = "*" bopShow (Div) = "/" bopShow (Minus) = "-" bopShow (Mod) = "%" bopShow (And) = "&&" bopShow (Or) = "||" bopShow (LessT) = "<" bopShow (LessTE) = "<=" bopShow (GreaterT) = ">" bopShow (GreaterTE) = ">=" bopShow (Equals) = "==" bopShow (NEquals) = "!=" -- Tokens dymanikStyle :: LanguageDef st dymanikStyle = emptyDef { commentStart = "/*", commentEnd = "*/", commentLine = "//", identStart = letter, identLetter = alphaNum <|> char '_', reservedOpNames = ["+","-","/","*","=","&&","||","<",">", "<=",">=","==","!=","!", ":"], reservedNames = ["sub","return","proc","if","else","var", "int","bool", "Void", "print", "printLn" ] } lexer = Tok.makeTokenParser dymanikStyle semi = Tok.semi lexer reserved = Tok.reserved lexer reservedOp = Tok.reservedOp lexer identifier = Tok.identifier lexer integer = Tok.integer lexer stringLiteral = Tok.stringLiteral lexer braces = Tok.braces lexer parens = Tok.parens lexer commaSep = Tok.commaSep lexer whiteSpace = Tok.whiteSpace lexer -- Parser Grammar -- --Parse the whole program prog = whiteSpace *> manyTill stmt eof -- Statments blocks stmts = Block <$> (sourceLine <$> getPosition) <*> (updateState (+1) >> getState ) <*> many stmt stmt = declFunct <|> funReturn <|> controlIf <|> (declVar <|> callPrintLn <|> callPrint <|> (identifier >>=( \x-> flip CallProc x <$> (sourceLine <$> getPosition) <*> parens args <|> (flip Assign x <$> (sourceLine <$> getPosition) <*> (reservedOp "=" *> expr) <?> "Subroutine Call o Assignment"))) ) <* semi funReturn = Return <$> (sourceLine <$> getPosition) <*> (reserved "return" *> optionMaybe expr <* semi) <?> "return" --Variable Declaration declVar = DeclVar <$> (sourceLine <$> getPosition) <*> (reserved "var" *> identifier) <*> (varType) <?> "variable declaration" varType = reservedOp ":" *>( (reserved "int" *> return TInt) <|> (reserved "sub" *> return TFunct) <|> (reserved "bool" *> return TBool)) <?> "type declaration" funcType = reservedOp ":" *>( (reserved "int" *> return TInt) <|> (reserved "sub" *> return TFunct) <|> (reserved "bool" *> return TBool) <|> (reserved "Void" *> return TVoid)) <?> "type declaration" --Function Declaration declFunct = DeclFunct <$> (sourceLine <$> getPosition) <*> (reserved "sub" *> identifier) <*> parens functdeclargs <*> (funcType) <*> braces stmts <?> "function declaration" functdeclargs = commaSep ((,) <$> identifier <*> ( varType)) callPrint = CallPrint <$> (sourceLine <$> getPosition) <*> (reserved "print" *> parens expr) callPrintLn = CallPrintLn <$> (sourceLine <$> getPosition) <*> (reserved "printLn" *> parens expr) args = commaSep expr controlIf = ControlIf <$> (sourceLine <$> getPosition) <*> (reserved "if" *> parens expr) <*> braces stmts <*> (reserved "else" *> braces stmts <|> Block <$> (sourceLine <$> getPosition) <*> getState <*> return []) --Expresion Parsers opTable :: [[Operator Char st Expr]] opTable = [[ prefix "-" (flip UnaryExp Negate), prefix "!" (flip UnaryExp Not)], [ binary "*" (flip BinaryExp Mult) AssocLeft, binary "/" (flip BinaryExp Div) AssocLeft, binary "%" (flip BinaryExp Mod) AssocLeft ], [ binary "+" (flip BinaryExp Add) AssocLeft, binary "-" (flip BinaryExp Minus) AssocLeft], [ binary "<" (flip BinaryExp LessT) AssocLeft, binary "<=" (flip BinaryExp LessTE) AssocLeft, binary ">" (flip BinaryExp GreaterT) AssocLeft, binary ">=" (flip BinaryExp GreaterTE) AssocLeft], [ binary "==" (flip BinaryExp Equals) AssocLeft, binary "!=" (flip BinaryExp NEquals) AssocLeft], [ binary "&&" (flip BinaryExp And) AssocLeft], [ binary "||" (flip BinaryExp Or) AssocLeft] ] where prefix op f = Prefix (reservedOp op >> f <$> (sourceLine <$> getPosition)) binary op f = Infix (reservedOp op >> f <$> (sourceLine <$> getPosition)) expr = buildExpressionParser opTable term term = parens expr <|> IntLiteral <$> (sourceLine <$> getPosition) <*> integer <|> (reserved "true" >> BoolLiteral <$> (sourceLine <$> getPosition) <*> return True) <|> (reserved "false" >> BoolLiteral <$> (sourceLine <$> getPosition) <*> return False) <|> StringLiteral <$> (sourceLine <$> getPosition) <*> stringLiteral <|> (identifier >>=( \x-> flip CallFunct x <$> (sourceLine <$> getPosition) <*> parens args <|> Var <$> (sourceLine <$> getPosition) <*> return x)) <?> "an expression" --------------evaluation -------- data SymbolTable = SymbolTable { symtableValues :: Map Ident (Int,(Type,[SymbolValue])), symtableEnv :: Maybe (Map String (Integer,Int)), symtableStackPos :: Integer, symtableFramePointer :: Int, symtableName :: String, symtableLexicalParent :: (String,Int) } deriving Show data SymbolValue = Uninitialized | ValInt Integer | ValBool Bool | ValString String | ValFun{ valFunargs::FunctArgs, valFunType::Type, valFunBlock::Block, valFunParent::(String,Int), valFunEnv::Maybe (Map String (Integer,Int)) } | Void | Exit SymbolValue {-deriving (Show,Eq)-} deriving (Eq) instance NFData SymbolValue where rnf a = a `seq` () instance Show SymbolValue where show = showValue data Environment = Environment { envStack :: [SymbolTable], envRetType :: [Type], envScope :: Integer } deriving Show data ScopeConfig = ScopeConfig { deepBinding :: Bool, staticScoping :: Bool, lookupScope :: Ident-> RWS.RWST ScopeConfig Log Environment (Either EvalError) (Maybe (Type,SymbolValue)), assignScope :: Ident->(Type,SymbolValue) -> RWS.RWST ScopeConfig Log Environment (Either EvalError) () } data Logunit = Logunit { logStatic::Bool, logDeep::Bool, logInst::Stmt, logEnv::Environment } deriving Show type Log = S.Seq Logunit {-- EXCEPTION --} data EvalError = NotInScope Int Ident | VariableNotInitialized Int Ident | WrongType Int Type Type | LessArgs Int Ident Int Int | AlreadyDeclared Int Ident instance Show EvalError where show (NotInScope l n) = show l ++": identifier "++show n++" not in scope" show (VariableNotInitialized l n) = show l ++ ": variable "++show n++" has not been initialized" show (WrongType l a b) = show l ++ ": unexpected "++show a++" expected "++show b show (LessArgs l n a b) = show l ++ ": called sub "++show n++" with "++show a++" arguments expected "++ show b show (AlreadyDeclared l n) = show l ++ ": the name "++show n++" is already declared in this scope." {-getFreeVariables :: FunctArgs -> Block -> [String]-} {-getFreeVariables fargs (Block _ _ blk) = snd $ head $ map (go) blk-} getFreeVariables :: FunctArgs -> Block -> Map Ident Ident getFreeVariables fargs (Block _ _ blk) = flip Map.difference (Map.fromList fargs) $ snd $ Data.Foldable.foldl (\(decl,acc) (new,free) -> (mappend decl new, mappend (difference free decl) (acc) )) (mempty,mempty) $ map go blk where go :: Stmt -> (Map Ident Ident,Map Ident Ident) go (DeclVar _ ident _) = (Map.singleton ident ident,mempty) go (DeclFunct _ ident fargs' _ blok) = (Map.singleton ident ident,getFreeVariables fargs' blok) go (Assign _ ident expr') = (mempty,mappend (Map.singleton ident ident) (goexpr expr')) go (CallProc _ ident args') = (mempty,mappend (Map.singleton ident ident) (foldMap goexpr args')) go (ControlIf _ bexpr tblk fblk) = (mempty,(goexpr bexpr) `mappend` (getFreeVariables [] tblk) `mappend` (getFreeVariables [] fblk)) go (CallPrint _ expr') = (mempty, goexpr expr') go (CallPrintLn _ expr') = (mempty, goexpr expr') go (Return _ expr') = (mempty, maybe mempty goexpr expr') go (EndProg) = error "endProg is a dummy value" goexpr (Var _ ident) = Map.singleton ident ident goexpr (IntLiteral{} ) = mempty goexpr (BoolLiteral{}) = mempty goexpr (StringLiteral{}) = mempty goexpr (CallFunct _ ident args') = mappend (Map.singleton ident ident) (foldMap goexpr args') goexpr (UnaryExp _ _ expr') = goexpr expr' goexpr (BinaryExp _ _ expr1 expr2) = mappend (goexpr expr1) (goexpr expr2) addLog :: (Applicative m,Monad m) => Stmt -> RWS.RWST ScopeConfig Log Environment m () addLog inst = RWS.tell =<< (\a b c d -> S.singleton $ Logunit a b c d ) <$> RWS.asks (staticScoping) <*> RWS.asks deepBinding <*> return inst <*> RWS.get {-Logunit <$> RWS.asks (staticScoping) <*> RWS.asks deepBinding <*> return inst <*> RWS.get-} getBindings :: (String,Int) -> RWS.RWST ScopeConfig Log Environment (Either EvalError) (Map String (Integer,Int)) getBindings (parent,off) = RWS.asks staticScoping >>= \x-> if x then foldr go Map.empty <$>RWS.gets (staticChain . g . dropWhile ((/= parent).symtableName) . envStack) else foldr go Map.empty <$>RWS.gets (dropWhile (\y->"args.of." `isPrefixOf` symtableName y) . envStack) where go = union . (\y -> fmap (\(n,_) -> (symtableStackPos y,n)) (symtableValues y) ) g [] = error "empty stack / Parent not Found" g (y:ys) = y{symtableValues=cleanMap y} : ys cleanMap y = Map.filter (\(n,_) -> n <= (off + symtableFramePointer y)) (symtableValues y) dynShallowScope :: ScopeConfig dynShallowScope = ScopeConfig False False lookupDyn assignDyn dynDeepScope :: ScopeConfig dynDeepScope = ScopeConfig True False lookupDyn assignDyn staticShallowScope :: ScopeConfig staticShallowScope = ScopeConfig False True lookupStatic assignStatic staticDeepScope :: ScopeConfig staticDeepScope = ScopeConfig True True lookupStatic assignStatic staticChain :: [SymbolTable] -> [SymbolTable] staticChain [] = [] staticChain (x:xs) = x : f xs where f = staticChain . g . dropWhile (\n-> symtableName n /= fst (symtableLexicalParent x)) g [] = [] g (y:ys) = y{symtableValues=cleanMap y} : ys cleanMap y = Map.filter (\(n,_) -> fromIntegral n <= (fromIntegral (snd $ symtableLexicalParent x) + symtableFramePointer y)) (symtableValues y) {- dinamic scopes -} lookupDyn :: String -> RWS.RWST ScopeConfig Log Environment (Either EvalError) (Maybe (Type, SymbolValue)) lookupDyn name = RWS.asks deepBinding >>= (\x -> if x then fmap (\(_,(t, v:_ )) -> (t,v)) . findDeep <$> RWS.gets envStack else fmap (\(_,(t, v:_ )) -> (t,v)) . find' <$> RWS.gets envStack ) where findDeep [] = Nothing findDeep l@(x:xs) = Map.lookup name (symtableValues x) `mplus` maybe (findDeep xs) (aux l . fst <=< Map.lookup name) (symtableEnv x) aux l n = Map.lookup name $ symtableValues $ head $ dropWhile ( (n/=).symtableStackPos) l find' = foldr (mplus . Map.lookup name .symtableValues) Nothing assignDyn :: String -> (Type, SymbolValue) -> RWS.RWST ScopeConfig Log Environment (Either EvalError) () assignDyn name value = RWS.asks deepBinding >>= (\x -> if x then RWS.modify (\y -> y{envStack=assignDeep $ envStack y}) else RWS.modify (\y -> y{envStack=assign $ envStack y}) ) where assignDeep [] = error (name++" variable not in scope") assignDeep l@(x:xs) = case assign' (symtableValues x) of (Nothing,_) -> maybe (x:assignDeep xs) (aux l . fst . fromJust . Map.lookup name) (symtableEnv x) (Just _,m) -> x{symtableValues = m} : xs aux l n = (\(x,y) -> x ++ assign y) $ break ((n==) . symtableStackPos) l assign [] = error (name++" variable not in scope") assign (x:xs) = case assign' (symtableValues x) of (Nothing,_) -> x:assign xs (Just _,m) -> x{symtableValues=m}:xs assign' = insertLookupWithKey (\_ (_,(tnew,a)) (n,(told,old)) -> if tnew==told then (n,(told,a++old)) else error ("expected" ++ show told ++ " got " ++ show tnew)) name value' value' = (\(b,c) -> (0,(b,[c]))) value {- static scope -} lookupStatic :: String -> RWS.RWST ScopeConfig Log Environment (Either EvalError) (Maybe (Type, SymbolValue)) lookupStatic name = RWS.asks deepBinding >>= \x-> if x then (\y -> fmap (\(_,(t, z:_ )) -> (t,z)) . findDeep y ) <$> RWS.gets envStack <*> RWS.gets (staticChain . envStack) else fmap (\(_,(t, y:_ )) -> (t,y)) . find' <$> RWS.gets (staticChain . envStack) where findDeep _ [] = Nothing findDeep stack (x:xs) = Map.lookup name (symtableValues x) `mplus` maybe (findDeep stack xs) (aux stack . fst <=< Map.lookup name) (symtableEnv x) aux s n = Map.lookup name $ symtableValues $ head $ dropWhile ((n/=) . symtableStackPos) s find' = foldr (mplus . Map.lookup name . symtableValues ) Nothing assignStatic :: String -> (Type, SymbolValue) -> RWS.RWST ScopeConfig Log Environment (Either EvalError) () assignStatic name value = do b<-RWS.asks deepBinding if b then RWS.modify (\x -> x{envStack=assignDeep (-1) $ envStack x}) else RWS.modify (\x -> x{envStack=assign (-1) $ envStack x}) where assignDeep _ [] = error (name ++ "variable not in scope") assignDeep parent l@(x:xs) = case clean parent x of (False, _) -> maybe (x: next assignDeep (symtableLexicalParent x) xs) (aux l . fst . fromJust . Map.lookup name) (symtableEnv x) (True, m) -> x{symtableValues=m}:xs aux l n = (\(x,y) -> x ++ assign (-1) y) $ break ((n==) . symtableStackPos) l assign _ [] = error (name ++ "variable not in scope") assign parent (x:xs) = case clean parent x of (False, _) -> x : next assign (symtableLexicalParent x) xs (True,m) -> x{symtableValues=m}:xs clean (-1) table = (member name $ symtableValues table , assign' $ symtableValues table) clean (offset) table = (member name $ Map.filter (\(n,_) -> n <= offset + symtableFramePointer table) (symtableValues table) ,assign' $ symtableValues table) assign' = insertWithKey (\_ (_,(tnew,a)) (n,(told,old)) -> if tnew==told then (n,(told,a++old)) else error ("expected" ++ show told ++ " got " ++ show tnew)) name value' next f (p,off) = (\(x,y) -> x ++ f off y) . span (\n -> symtableName n /= p) value' = (\(b,c) -> (0,(b,[c]))) value emptySymtable :: Maybe (Map String (Integer, Int))-> Integer -> Int -> String -> (String,Int) -> SymbolTable emptySymtable = SymbolTable Map.empty newScope :: String -> (String,Int) -> Maybe (Map String (Integer,Int)) -> RWS.RWST ScopeConfig Log Environment (Either EvalError) () newScope name (parent,off) env= do pos <- stackPos fp <- stackSP off' <- if off<0 then offset else return off RWS.modify (\x -> x{envStack= emptySymtable env pos fp name (parent,off') : envStack x,envScope=1+envScope x}) where stackPos = RWS.gets envScope offset = RWS.gets ( Map.size . symtableValues . head . envStack) stackSP = (\x -> symtableFramePointer x + Map.size (symtableValues x)) <$> RWS.gets (head . envStack) exitScope :: RWS.RWST ScopeConfig Log Environment (Either EvalError) () exitScope = RWS.modify (\x -> x{envStack = tail (envStack x) ,envScope=envScope x-1}) insertSymbol :: Int->Bool -> String -> (Type, SymbolValue) -> RWS.RWST ScopeConfig Log Environment (Either EvalError) () insertSymbol lineno toBind name val = do env<- RWS.get sp <- stackSP val' <- getValWithBindings if notMember name (symtableValues $ head $ envStack env) then do let x = insert' name (sp,val') (envStack env) RWS.put $ env{envStack=x} else RWS.lift $ Left $ AlreadyDeclared lineno name where insert' _ _ [] = error "inserting symbol on empty environment" insert' a b (x:xs) = x{symtableValues=insert a b (symtableValues x)} : xs stackSP = (\x -> symtableFramePointer x + fromIntegral (Map.size (symtableValues x))) <$> RWS.gets (head . envStack) getValWithBindings = case val of (t,vf@(ValFun{valFunEnv=env})) -> if toBind then do binds <- flip intersection (getFreeVariables (valFunargs vf) (valFunBlock vf)) <$> getBindings (valFunParent vf) return (t,[vf{valFunEnv=env `mplus` Just binds}]) else return (t,[vf{valFunEnv=Nothing}]) (t,v) -> return (t,[v]) assignSymbol :: String-> (Type, SymbolValue)-> RWS.RWST ScopeConfig Log Environment (Either EvalError) () assignSymbol name val = RWS.asks assignScope >>= (\f -> f name val) lookupSymbol :: Int -> String-> RWS.RWST ScopeConfig Log Environment (Either EvalError) (Type, SymbolValue) lookupSymbol lineno name = RWS.asks lookupScope >>= (\f -> f name) >>= maybe (RWS.lift $ Left $ NotInScope lineno name) return getCurrentStack :: RWS.RWST ScopeConfig Log Environment (Either EvalError) (String,Int) getCurrentStack = RWS.gets ((\y -> (symtableName y, Map.size $ symtableValues y)) . head . envStack) newEnvironment :: Environment newEnvironment = Environment { envStack=[emptySymtable Nothing (-1) 0 "Global" ("",0)], envScope=0, envRetType=[TVoid] } printVal :: Monad m => SymbolValue -> m SymbolValue printVal x = trace' (showValue x) (return Void) where trace' s v = let str = ( unsafePerformIO . putStr) s in deepseq str v printValLn :: Monad m => SymbolValue -> m SymbolValue printValLn x = trace' (showValue x) (return Void) where trace' s v = let str = ( unsafePerformIO . putStrLn) s in deepseq str v showValue :: SymbolValue -> String showValue (ValBool b) = show b showValue (ValInt n) = show n showValue (ValString s) = s showValue (Void ) = "Void" showValue (Uninitialized) = "Uninitialized" showValue Exit{} = "exit" showValue ValFun{valFunargs=fargs,valFunType=typ} = "("++ concatMap ((++",") . show . snd) fargs ++"):"++show typ valueType :: SymbolValue -> Type valueType (Void{}) = TVoid valueType (ValFun{}) = TFunct valueType (ValBool{}) = TBool valueType (ValInt{}) = TInt valueType (ValString{}) = TString valueType (Uninitialized) = error "uninitialized value on return" valueType (Exit v) = valueType v evalProg :: ScopeConfig -> [Stmt] ->Either EvalError (SymbolValue, Environment, Log) evalProg conf block = RWS.runRWST (do ret<-evalBlock (Block 0 0 block) "Global" addLog EndProg return ret) conf newEnvironment eval :: Stmt-> RWS.RWST ScopeConfig Log Environment (Either EvalError) SymbolValue eval inst@(CallPrint _ e) = do addLog inst evalType e evalExpr e >>= printVal eval inst@(CallPrintLn _ e) = do addLog inst evalType e evalExpr e >>= printValLn eval inst@(DeclVar lineno name typ) =do addLog inst insertSymbol lineno False name (typ,Uninitialized) return Void eval inst@(DeclFunct lineno name arg typ block) = do addLog inst getCurrentStack >>= (\x -> insertSymbol lineno False name (TFunct, ValFun{ valFunargs=arg, valFunType=typ, valFunBlock=block, valFunParent=x, valFunEnv=Nothing })) return Void eval inst@(Assign lineno name e) = do addLog inst (t1,_)<-lookupSymbol lineno name t2<- evalType e if t1/=t2 then RWS.lift $ Left $ WrongType lineno t1 t2 else do x <- (,)t2<$> evalExpr e assignSymbol name x return Void eval inst@(CallProc lineno name arg) = do addLog inst evalType (CallFunct lineno name arg) lookupSymbol lineno name >>= (\x -> case x of (TFunct,ValFun{ valFunargs=fargs, valFunBlock=block@(Block _lineno' n _), valFunParent=parent, valFunEnv=env, valFunType=typ }) -> do mapM evalExpr arg >>= insertArgs n parent fargs env ret <- typecheck typ =<< evalBlock block name exitScope return ret (t,_) -> RWS.lift $ Left $ WrongType lineno t TFunct ) where typecheck typ val =if typ == valueType val then case val of Exit v -> return v Void -> return Void else RWS.lift $ Left $ WrongType lineno (valueType val) typ insertArgs n parent fargs env args' = do newScope ("args.of."++name++"|"++show n) parent env zipWithM (\(nam,t) v-> insertSymbol lineno True nam (t,v)) fargs args' eval inst@(ControlIf lineno cond tblock fblock) = do addLog inst evalType cond >>= (\x -> unless (x == TBool) (RWS.lift $ Left $ WrongType lineno x TBool)) (ValBool x) <- evalExpr cond if x then evalBlock tblock "ifTbranch" else evalBlock fblock "ifFbranch" eval inst@(Return _ a) = addLog inst >>liftM Exit (maybe (return Void) evalExpr a) eval (EndProg) = error "EndProg is a dummy value" evalBlock :: Block-> String -> RWS.RWST ScopeConfig Log Environment (Either EvalError) SymbolValue evalBlock (Block _ n b) name = do getCurrentStack >>= flip (newScope (name++"|"++show n)) Nothing when (flagDebug) $ flip trace (return ()) . show =<< RWS.get retVal <-eval' b exitScope return retVal where eval' [] = return Void eval' (x:xs) = do ret <- eval x case ret of Void -> eval' xs a@(Exit val) -> return a _ -> eval' xs evalType :: Expr -> RWS.RWST ScopeConfig Log Environment (Either EvalError) Type evalType (IntLiteral{}) = return TInt evalType (BoolLiteral{}) = return TBool evalType (StringLiteral{}) = return TString evalType (Var lineno n) = RWS.asks lookupScope >>= (\f -> f n) >>= maybe (RWS.lift $ Left $ NotInScope lineno n) (return.fst) evalType (UnaryExp lineno op e) = evalType e >>= (\x -> if x==t' then return x else RWS.lift $ Left $ WrongType lineno x t') where t' = case op of Negate -> TInt Not -> TBool evalType (BinaryExp lineno op a b) = do evalType a >>= check evalType b >>= check where check e = if e==opT then return resT else RWS.lift $ Left $ WrongType lineno e opT where (opT, resT) = case op of Add -> (TInt , TInt) Minus -> (TInt , TInt) Mult -> (TInt , TInt) Div -> (TInt , TInt) Mod -> (TInt , TInt) Or -> (TBool ,TBool) And -> (TBool ,TBool) LessTE -> (TInt ,TBool) LessT -> (TInt ,TBool) GreaterTE -> (TInt ,TBool) GreaterT ->( TInt ,TBool) Equals -> (e ,TBool) NEquals ->( e ,TBool) evalType (CallFunct lineno n callargs) = RWS.asks lookupScope >>= (\f -> f n) >>= maybe (RWS.lift $ Left $ NotInScope lineno n) go where check (_,typ) ex = evalType ex >>= (\x -> if x==typ then return typ else RWS.lift $ Left $ WrongType lineno x typ) go (TFunct,ValFun{valFunargs=declargs,valFunType=t}) = do when (callen /= declen) (RWS.lift $ Left $ LessArgs lineno n callen declen) zipWithM_ check declargs callargs return t where callen = length callargs declen = length declargs go (t,_) = RWS.lift $ Left $ WrongType lineno t TFunct evalExpr :: Expr -> RWS.RWST ScopeConfig Log Environment (Either EvalError) SymbolValue evalExpr (IntLiteral _ n) = return $ ValInt n evalExpr (BoolLiteral _ b) = return $ ValBool b evalExpr (StringLiteral _ s) = return $ ValString s evalExpr (Var lineno n) = do x <- RWS.asks lookupScope >>= (\f -> f n) case fromJust x of (_,Uninitialized) -> RWS.lift $ Left $ VariableNotInitialized lineno n (_,m) -> return m evalExpr (UnaryExp _lineno op e) = evalExpr e >>= f' op where f' Negate (ValInt n) = return $ValInt (-n) f' Not (ValBool b) = return $ValBool (not b) f' _ _ = error "unsupported unary expression" evalExpr (BinaryExp _lineno op aexp bexp) = f' op <$> evalExpr aexp <*> evalExpr bexp where f' Add (ValInt a) (ValInt b) = ValInt $ a + b f' Minus (ValInt a) (ValInt b) =ValInt $ a - b f' Mult (ValInt a) (ValInt b) =ValInt $ a * b f' Div (ValInt a) (ValInt b) =ValInt $ a `div` b f' Mod (ValInt a) (ValInt b) =ValInt $ a `mod` b f' And (ValBool a) (ValBool b) =ValBool $ a && b f' Or (ValBool a) (ValBool b) =ValBool $ a || b f' LessT (ValInt a) (ValInt b) =ValBool $ a < b f' LessTE (ValInt a) (ValInt b) =ValBool $ a <= b f' GreaterT (ValInt a) (ValInt b) =ValBool $ a > b f' GreaterTE (ValInt a) (ValInt b) =ValBool $ a >= b f' Equals a b = ValBool $ a == b f' NEquals a b = ValBool $ a /= b f' _ _ _ = error "unsupported binary expression" evalExpr (CallFunct lineno n cargs) = eval (CallProc lineno n cargs) execString :: ScopeConfig -> String -> Either ParseError (Either EvalError (SymbolValue, Environment, Log)) execString mode = liftM (evalProg mode) . runParser prog 0 "Input" exec :: ScopeConfig -> SourceName -> IO (Either ParseError (Either EvalError (SymbolValue, Environment, Log))) {-exec mode file = return . liftM (evalProg mode) . runParser prog 0 file =<< readFile file-} exec mode file = return . execString mode =<< readFile file
Dymanik/dymscope
src/Parser.hs
gpl-2.0
29,510
541
22
6,818
11,184
6,025
5,159
-1
-1
----------------------------------------------------------------------------- -- | -- Module : DSP.Filter.IIR.IIR -- Copyright : (c) Matthew Donadio 2003 -- License : GPL -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- IIR functions -- -- IMPORTANT NOTE: -- -- Except in integrator, we use the convention that -- -- @y[n] = sum(k=0..M) b_k*x[n-k] - sum(k=1..N) a_k*y[n-k]@ -- -- -- -- @ sum(k=0..M) b_k*z^-1@ -- -- @H(z) = ------------------------@ -- -- @ 1 + sum(k=1..N) a_k*z^-1@ -- ----------------------------------------------------------------------------- -- TODO: Should these use Arrays for a and b? Tuples? {- Reference: @Book{dsp, author = "Alan V. Oppenheim and Ronald W. Schafer", title = "Discrete-Time Signal Processing", publisher = "Prentice-Hall", year = 1989, address = "Englewood Cliffs", series = {Prentice-Hall Signal Processing Series} } However, we differ in the convention of the sign of the poles, as noted in the module header. -} module DSP.Filter.IIR.IIR (integrator, fos_df1, fos_df2, fos_df2t, biquad_df1, biquad_df2, biquad_df2t, iir_df1, iir_df2, -- for testing xt, yt, f1, f2, f3, f4, f5, ) where import Data.Array import DSP.Filter.FIR.FIR -- | This is an integrator when a==1, and a leaky integrator when @0 \< a \< 1@. -- -- @y[n] = a * y[n-1] + x[n]@ {-# specialize integrator :: Float -> [Float] -> [Float] #-} {-# specialize integrator :: Double -> [Double] -> [Double] #-} integrator :: Num a => a -- ^ a -> [a] -- ^ x[n] -> [a] -- ^ y[n] integrator a x = integrator' a 0 x integrator' :: Num a => a -> a-> [a] -> [a] integrator' _ _ [] = [] integrator' a y1 (x:xs) = y : integrator' a y xs where y = a * y1 + x -- | First order section, DF1 -- -- @v[n] = b0 * x[n] + b1 * x[n-1]@ -- -- @y[n] = v[n] - a1 * y[n-1]@ {-# specialize fos_df1 :: Float -> Float -> Float -> [Float] -> [Float] #-} {-# specialize fos_df1 :: Double -> Double -> Double -> [Double] -> [Double] #-} fos_df1 :: Num a => a -- ^ a_1 -> a -- ^ b_0 -> a -- ^ b_1 -> [a] -- ^ x[n] -> [a] -- ^ y[n] fos_df1 a1 b0 b1 x = fos_df1' a1 b0 b1 0 0 x fos_df1' :: Num a => a -> a -> a -> a -> a -> [a] -> [a] fos_df1' _ _ _ _ _ [] = [] fos_df1' a1 b0 b1 x1 y1 (x:xs) = y : fos_df1' a1 b0 b1 x y xs where v = b0 * x + b1 * x1 y = v - a1 * y1 -- | First order section, DF2 -- -- @w[n] = -a1 * w[n-1] + x[n]@ -- -- @y[n] = b0 * w[n] + b1 * w[n-1]@ {-# specialize fos_df2 :: Float -> Float -> Float -> [Float] -> [Float] #-} {-# specialize fos_df2 :: Double -> Double -> Double -> [Double] -> [Double] #-} fos_df2 :: Num a => a -- ^ a_1 -> a -- ^ b_0 -> a -- ^ b_1 -> [a] -- ^ x[n] -> [a] -- ^ y[n] fos_df2 a1 b0 b1 x = fos_df2' a1 b0 b1 0 x fos_df2' :: Num a => a -> a -> a -> a -> [a] -> [a] fos_df2' _ _ _ _ [] = [] fos_df2' a1 b0 b1 w1 (x:xs) = y : fos_df2' a1 b0 b1 w xs where w = x - a1 * w1 y = b0 * w + b1 * w1 -- | First order section, DF2T -- -- @v0[n] = b0 * x[n] + v1[n-1]@ -- -- @y[n] = v0[n]@ -- -- @v1[n] = -a1 * y[n] + b1 * x[n]@ {-# specialize fos_df2t :: Float -> Float -> Float -> [Float] -> [Float] #-} {-# specialize fos_df2t :: Double -> Double -> Double -> [Double] -> [Double] #-} fos_df2t :: Num a => a -- ^ a_1 -> a -- ^ b_0 -> a -- ^ b_1 -> [a] -- ^ x[n] -> [a] -- ^ y[n] fos_df2t a1 b0 b1 x = fos_df2t' a1 b0 b1 0 x fos_df2t' :: Num a => a -> a -> a -> a -> [a] -> [a] fos_df2t' _ _ _ _ [] = [] fos_df2t' a1 b0 b1 v11 (x:xs) = y : fos_df2t' a1 b0 b1 v1 xs where v0 = b0 * x + v11 y = v0 v1 = -a1 * y + b1 * x -- | Direct Form I for a second order section -- -- @v[n] = b0 * x[n] + b1 * x[n-1] + b2 * x[n-2]@ -- -- @y[n] = v[n] - a1 * y[n-1] - a2 * y[n-2]@ {-# specialize biquad_df1 :: Float -> Float -> Float -> Float -> Float -> [Float] -> [Float] #-} {-# specialize biquad_df1 :: Double -> Double -> Double -> Double -> Double -> [Double] -> [Double] #-} biquad_df1 :: Num a => a -- ^ a_1 -> a -- ^ a_2 -> a -- ^ b_0 -> a -- ^ b_1 -> a -- ^ b_2 -> [a] -- ^ x[n] -> [a] -- ^ y[n] biquad_df1 a1 a2 b0 b1 b2 x = df1 a1 a2 b0 b1 b2 0 0 0 0 x df1 :: Num a => a -> a -> a -> a -> a -> a -> a -> a -> a -> [a] -> [a] df1 _ _ _ _ _ _ _ _ _ [] = [] df1 a1 a2 b0 b1 b2 x1 x2 y1 y2 (x:xs) = y : df1 a1 a2 b0 b1 b2 x x1 y y1 xs where v = b0 * x + b1 * x1 + b2 * x2 y = v - a1 * y1 - a2 * y2 -- | Direct Form II for a second order section (biquad) -- -- @w[n] = -a1 * w[n-1] - a2 * w[n-2] + x[n]@ -- -- @y[n] = b0 * w[n] + b1 * w[n-1] + b2 * w[n-2]@ {-# specialize biquad_df2 :: Float -> Float -> Float -> Float -> Float -> [Float] -> [Float] #-} {-# specialize biquad_df2 :: Double -> Double -> Double -> Double -> Double -> [Double] -> [Double] #-} biquad_df2 :: Num a => a -- ^ a_1 -> a -- ^ a_2 -> a -- ^ b_0 -> a -- ^ b_1 -> a -- ^ b_2 -> [a] -- ^ x[n] -> [a] -- ^ y[n] biquad_df2 a1 a2 b0 b1 b2 x = df2 a1 a2 b0 b1 b2 0 0 x df2 :: Num a => a -> a -> a -> a -> a -> a -> a -> [a] -> [a] df2 _ _ _ _ _ _ _ [] = [] df2 a1 a2 b0 b1 b2 w1 w2 (x:xs) = y : df2 a1 a2 b0 b1 b2 w w1 xs where w = x - a1 * w1 - a2 * w2 y = b0 * w + b1 * w1 + b2 * w2 -- | Transposed Direct Form II for a second order section -- -- @v0[n] = b0 * x[n] + v1[n-1]@ -- -- @y[n] = v0[n]@ -- -- @v1[n] = -a1 * y[n] + b1 * x[n] + v2[n-1]@ -- -- @v2[n] = -a2 * y[n] + b2 * x[n]@ {-# specialize biquad_df2t :: Float -> Float -> Float -> Float -> Float -> [Float] -> [Float] #-} {-# specialize biquad_df2t :: Double -> Double -> Double -> Double -> Double -> [Double] -> [Double] #-} biquad_df2t :: Num a => a -- ^ a_1 -> a -- ^ a_2 -> a -- ^ b_0 -> a -- ^ b_1 -> a -- ^ b_2 -> [a] -- ^ x[n] -> [a] -- ^ y[n] biquad_df2t a1 a2 b0 b1 b2 x = df2t a1 a2 b0 b1 b2 0 0 x df2t :: Num a => a -> a -> a -> a -> a -> a -> a -> [a] -> [a] df2t _ _ _ _ _ _ _ [] = [] df2t a1 a2 b0 b1 b2 v11 v21 (x:xs) = y : df2t a1 a2 b0 b1 b2 v1 v2 xs where v0 = b0 * x + v11 y = v0 v1 = -a1 * y + b1 * x + v21 v2 = -a2 * y + b2 * x -- | Direct Form I IIR -- -- @v[n] = sum(k=0..M) b_k*x[n-k]@ -- -- @y[n] = v[n] - sum(k=1..N) a_k*y[n-k]@ -- -- @v[n]@ is calculated with 'fir' {- specialize iir_df1 :: (Array Int Float, Array Int Float) -> [Float] -> [Float] -} {- specialize iir_df1 :: (Array Int Double, Array Int Double) -> [Double] -> [Double] -} iir_df1 :: (Num a, Eq a) => (Array Int a, Array Int a) -- ^ (b,a) -> [a] -- ^ x[n] -> [a] -- ^ y[n] iir_df1 (b,a) x = y where v = fir b x y = iir'df1 a w v w = listArray (1,n) $ repeat 0 n = snd $ bounds a {- specialize iir'df1 :: Array Int Float -> Array Int Float -> [Float] -> [Float] -} {- specialize iir'df1 :: Array Int Double -> Array Int Double -> [Double] -> [Double] -} iir'df1 :: (Num a) => Array Int a -> Array Int a -> [a] -> [a] iir'df1 _ _ [] = [] iir'df1 a w (v:vs) = y : iir'df1 a w' vs where y = v - sum [ a!i * w!i | i <- [1..n] ] w' = listArray (1,n) $ y : elems w n = snd $ bounds a -- | Direct Form II IIR -- -- @w[n] = x[n] - sum(k=1..N) a_k*w[n-k]@ -- -- @y[n] = sum(k=0..M) b_k*w[n-k]@ {- specialize iir_df2 :: (Array Int Float, Array Int Float) -> [Float] -> [Float] -} {- specialize iir_df2 :: (Array Int Double, Array Int Double) -> [Double] -> [Double] -} iir_df2 :: (Num a) => (Array Int a, Array Int a) -- ^ (b,a) -> [a] -- ^ x[n] -> [a] -- ^ y[n] iir_df2 (b,a) x = y where y = iir'df2 (b,a) w x w = listArray (0,mn) $ repeat 0 m = snd $ bounds b n = snd $ bounds a mn = max m n {- specialize iir'df2 :: Array Int Float -> Array Int Float -> [Float] -> [Float] -} {- specialize iir'df2 :: Array Int Double -> Array Int Double -> [Double] -> [Double] -} iir'df2 :: (Num a) => (Array Int a,Array Int a) -> Array Int a -> [a] -> [a] iir'df2 _ _ [] = [] iir'df2 (b,a) w (x:xs) = y : iir'df2 (b,a) w' xs where y = sum [ b!i * w'!i | i <- [0..m] ] w0 = x - sum [ a!i * w'!i | i <- [1..m] ] w' = listArray (0,mn) $ w0 : elems w m = snd $ bounds b mn = snd $ bounds w --------- -- test xt :: [Double] xt = [ 1, 0, 0, 0, 0, 0, 0, 0 ] :: [Double] yt :: [Double] yt = integrator 0.5 xt f1 :: Fractional a => [a] -> [a] f1 x = biquad_df1 (-0.4) 0.3 0.5 0.4 (-0.3) x f2 :: Fractional a => [a] -> [a] f2 x = biquad_df2 (-0.4) 0.3 0.5 0.4 (-0.3) x f3 :: Fractional a => [a] -> [a] f3 x = biquad_df2t (-0.4) 0.3 0.5 0.4 (-0.3) x at :: Array Int Double at = listArray (1,2) [ -0.4, 0.3 ] bt :: Array Int Double bt = listArray (0,2) [ 0.5, 0.4, -0.3 ] f4 :: [Double] -> [Double] f4 x = iir_df1 (bt,at) x f5 :: [Double] -> [Double] f5 x = iir_df2 (bt,at) x
tolysz/dsp
DSP/Filter/IIR/IIR.hs
gpl-2.0
9,303
0
16
2,944
2,748
1,517
1,231
153
1
-- | module HuffmanSpec where import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck import Compression import Data.ByteString.Lazy as L import ArbInstances compress = caCompress huffmanAlg extract = caExtract huffmanAlg spec :: Spec spec = modifyMaxSuccess (const 1000) $ do describe "Basic sanity" $ do it "compresses empty to empty" $ compress (pure L.empty) `shouldReturn` L.empty it "extracts empty to empty" $ extract (pure L.empty) `shouldReturn` L.empty it "isomorphic on one byte" $ extract (compress (pure $ L.singleton 42)) `shouldReturn` L.singleton 42 it "isomorphic on random ByteString" $ property $ \(ArbRandByteString s) -> extract (compress (pure s)) `shouldReturn` s it "ismorphic on random chunked ByteString" $ property $ \(ArbByteStringRepChunks s) -> extract (compress (pure s)) `shouldReturn` s
kravitz/har
test/HuffmanSpec.hs
gpl-3.0
890
0
19
170
276
142
134
22
1
-- Copyright (c) 2012, Diego Souza -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright notice, -- this list of conditions and the following disclaimer in the documentation -- and/or other materials provided with the distribution. -- * Neither the name of the <ORGANIZATION> nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. module Main where import System.IO import System.Environment import Control.Exception import qualified Data.ByteString as B import Data.Maybe import SSSFS.Storage (showKeyS) import SSSFS.Filesystem.Types main :: IO () main = do { f <- fmap head getArgs ; contents <- myGetContents f ; case (eulav contents) of Left msg -> putStrLn "Error decoding unit" >> putStrLn msg Right u -> putStrLn f >> render (decodeUnit u) } where myGetContents "-" = B.getContents myGetContents f = bracket (openBinaryFile f ReadMode) hClose (B.hGetContents) render [] = return () render ((a,b):xs) = putStrLn (a ++ ": " ++ b) >> render xs decodeUnit (DataBlockUnit o ix _) = [ ("type", "datablock") , ("oid", show o) , ("index", show ix) ] decodeUnit (DirEntUnit n o) = [ ("type", "dirent") , ("name", n) , ("oid", showKeyS $ iFromOID o) ] decodeUnit u@(INodeUnit _ _ _) = [ ("type", "inode") , ("inode", showKeyS $ iFromOID $ inode inum) , ("itype", show (itype inum)) , ("atime", show (atime inum)) , ("mtime", show (mtime inum)) , ("ctime", show (ctime inum)) , ("blksz", show (blksz inum)) , ("size", show (size inum)) , ("blocks", show (blocks inum)) ] where inum = fromJust (unitToINode u)
dgvncsz0f/sssfs
src/sssfs_stat.hs
gpl-3.0
3,598
0
13
1,316
561
315
246
34
6
{-# OPTIONS_GHC -fno-warn-orphans #-} {- COPIED FROM http://hackage.haskell.org/package/altfloat-0.3.1 -} {- - Copyright (C) 2009 Nick Bowler. - - License BSD2: 2-clause BSD license. See LICENSE for full terms. - This is free software: you are free to change and redistribute it. - There is NO WARRANTY, to the extent permitted by law. -} -- | Partially ordered data types. The standard 'Prelude.Ord' class is for -- total orders and therefore not suitable for floating point. However, we can -- still define meaningful 'max' and 'sortWith functions for these types. -- -- We define our own 'Ord' class which is intended as a replacement for -- 'Prelude.Ord'. Should the user wish to take advantage of existing libraries -- which use 'Prelude.Ord', just let Prelude.compare = (totalOrder .) . compare module Database.Design.Ampersand.Core.Poset ( Poset(..), Sortable(..), Ordering(..), Ord, comparableClass,greatest,least,maxima,minima,sortWith ) where import qualified Prelude (Ordering(..)) import Prelude hiding (Ord(..), Ordering(..)) import Database.Design.Ampersand.Basics import Database.Design.Ampersand.Core.Poset.Instances() --required for instance Int of Poset only import Database.Design.Ampersand.Core.Poset.Internal import qualified Data.List as List -- | makePartialOrder makes a partial order containing local partial orders, i.e. comparable classes. -- it makes sense to sort comparable classes. -- example: A and B are in a comparable class -- A and B are not LT, not GT, not EQ => CP -- if you sortBy comparableClass then A and B are considered EQ (comparableClass CP = Prelude.EQ) -- when the comparable classes have a top, then join can be defined on them -- when the comparable classes have a bottom, then meet can be defined on them -- -- When A_Concept should be a collection of total orders change f a b guard (| or [ a `elem` cl && b `elem` cl | cl <- cls ] = NC) -- -- examples on data X = A | B | C | D | E | F deriving (Eq,Show): -- [bottom] (makePartialOrder [(A,B),(C,D),(B,D),(A,C),(D,E),(D,F)]) :: (A <= B /\ C <= B \/ C <= D <= E /\ F <= E \/ F) -- [ringish] (makePartialOrder [(A,B),(C,D),(B,D),(A,C),(D,E),(D,F),(E,A),(F,A)]) _ _ = LT -- [ringish] (makePartialOrder [(A,B),(C,D),(B,D),(A,C),(D,E),(D,F),(E,A)]) F A = GT -- (makePartialOrder [(A,B),(C,D),(B,D),(A,C),(D,E),(D,F),(E,A)]) _ _ = LT -- [bottom,total] (makePartialOrder [(A,B),(C,D),(B,D),(A,C),(E,F)]) :: ( A <= B /\ C <= B \/ C <= D , E <= F ) -- [2x total] (makePartialOrder [(A,B),(B,C),(C,D),(E,F)]) :: ( A <= B <= C <= D , E <= F ) -- [total] (makePartialOrder [(A,B),(B,C),(C,D),(D,E),(E,F)]) :: ( A <= B <= C <= D <= E <= F ) -- [3x total] (makePartialOrder [(A,B),(B,C),(C,D)]) :: ( A <= B <= C <= D , E , F ) -- [partial] (makePartialOrder [(A,B),(C,D),(B,D),(D,E),(D,F)]) :: ( (A <= B <= D <= E /\ F <= E \/ F) + (C <= D <= E /\ F <= E \/ F) ) -- -- a sorted list will have the x left of y for all x and y. x <= y -- like x==y, the intraposition of x and y is without meaning for all x and y. x `compare` y = CP -- for example given a (makePartialOrder [(A,B),(C,D),(B,D),(D,E),(F,C)]): -- + sort [F,E,D,C,B,A] = [F,C,A,B,D,E] -- + sort [F,E,D,B,A,C] = [F,A,B,C,D,E] -- + sort [B,F,E,C,D,A] = [A,B,F,C,D,E] instance Poset a => Poset (Maybe a) where Just x <= Just y = x <= y Nothing <= _ = True _ <= _ = False instance Poset a => Poset [a] where compare = (mconcat .) . zipWith compare {- -- | Sort a list using the default comparison function. sort :: Sortable a => [a] -> [a] sort = sortBy compare -- | Apply a function to values before comparing. comparing :: Poset b => (a -> b) -> a -> a -> Ordering comparing = on compare -} -- example where b=A_Concept: sortWith (snd . order , concs fSpec) idCpt (vIndices fSpec) sortWith :: (Show b,Poset b) => (b -> [[b]], [b]) -> (a -> b) -> [a] -> [a] sortWith _ _ [] = [] sortWith (tos,allb) f xs = let xtos = [ [x | x<-xs, elem (f x) to] --group xs such that each elem of (map f xtos) is a total order | to<-(tos . f . head) xs --non-trivial total orders ++ [[b] | b<-allb, not( elem b (concat((tos . f . head) xs))) ] --trivial total orders ] sortwith = List.sortBy (\x y -> comparableClass(compare (f x) (f y))) --sortwith of Poset, which should be a total order in concat(map sortwith xtos) --sortwith each total order and concat them -- | Elements can be arranged into classes of comparable elements, not necessarily a total order -- It makes sense to sort such a class. -- Take for example instance Sortable A_Concept. -- When A_Concept should be a collection of total orders: comparableClass CP = fatal 118 "Elements in totally ordered class, which are not LT, not GT and not EQ." comparableClass :: Ordering -> Prelude.Ordering comparableClass LT = Prelude.LT comparableClass EQ = Prelude.EQ comparableClass GT = Prelude.GT comparableClass NC = fatal 123 "Uncomparable elements in comparable class." comparableClass CP = Prelude.EQ --the position of two comparable concepts is equal {- -- | If elements are in a total order, then they can be sortedBy totalOrder using the Prelude.Ordering -- When A_Concept should be in a total order with an Anything and Nothing: sortBy f = Data.List.sortBy ((totalOrder .) . f) totalOrder :: Ordering -> Prelude.Ordering totalOrder LT = Prelude.LT totalOrder EQ = Prelude.EQ totalOrder GT = Prelude.GT totalOrder NC = fatal 132 "Uncomparable elements in total order." totalOrder CP = fatal 133 "Uncomparable elements in total order." -} -- | takes the greatest a of comparables greatest :: (Show a,Sortable a) => [a] -> a greatest xs = case maxima (List.nub xs) of [] -> fatal 138 "there is no greatest" [x] -> x xs' -> fatal 140 ("there is more than one greatest: "++ show (List.nub xs')) -- | takes all a without anything larger maxima :: Sortable a => [a] -> [a] maxima [] = fatal 144 "the empty list has no maximum" maxima xs = [x | x<-List.nub xs,not (or [x < y | y<-List.nub xs])] -- | takes the least a of comparables if there is only one least :: Sortable a => [a] -> a least xs = case minima (List.nub xs) of [] -> fatal 150 "there is no least" [x] -> x _ -> fatal 150 "there is more than one least. " -- | takes all a without anything less minima :: Sortable a => [a] -> [a] minima [] = fatal 156 "the empty list has no minimum" minima xs = [x | x<-List.nub xs,not (or [y < x | y<-List.nub xs])]
4ZP6Capstone2015/ampersand
src/Database/Design/Ampersand/Core/Poset.hs
gpl-3.0
6,600
0
24
1,411
973
545
428
47
3
module Text.MoodleMD.Reader (pandoc2questions, parseMoodleMD, readMoodleMDFile) where import Control.Applicative (pure, (<$>), (<*>), (*>), (<$), empty) import Control.Arrow import Control.Monad (mfilter) import Data.Maybe (fromMaybe) import Data.Tuple (swap) import GHC.Float import Text.MoodleMD.Types import Text.Pandoc import Text.Pandoc.Shared (stringify) import Text.Parsec hiding ((<*>)) import Text.Parsec.String import Numeric (readSigned, readFloat) type BlockP a = Parsec [Block] () a -- | Parse a double value. This is exactly the same code as in Real World -- Haskell, p. 400. -- -- TODO There are some strange 'floating point numbers' running around in the -- wild that can not be parsed using this code. (eg.: +.5) or (+0.5) parseFloat :: GenParser Char st Double parseFloat = do s <- getInput case readSigned readFloat s of [(n,s')] -> n <$ setInput s' _ -> empty -- |Helper to increment Source position parsing arbitrary lists with Parsec incPos pos _ _ = incSourceColumn pos 1 -- |Convert to normal string. textToString :: Text -> String textToString = stringify -- |For converting the question title to a normal string. inlinesToString :: [Inline] -> String inlinesToString = stringify seqFirst :: Monad m => (m a,b) -> m (a,b) seqFirst (ma,b) = do a <- ma; return (a,b) seqSecond :: Monad m => (a,m b) -> m (a,b) seqSecond (a,mb) = do b <- mb; return (a,b) mapLeft :: (a -> b) -> Either a c -> Either b c mapLeft f (Left x) = Left $ f x mapLeft _ (Right r) = Right r -- |lifts a parse result back into the parser reparse = either (unexpected . show) return -- |the direct parse result for answer sections, common to all answer types data AnswerBlock = AnswerBlock { abTitle :: String -- ^Answer title, will be appended to question title , abType :: String -- ^type of question , abPrefix :: Text -- ^specific answer text, will be appended to question body , abAnswers :: [(Text,AnswerProp)] } -- ^fraction, then answer/feedback combinations pNumericAnswer :: Text -> Either ParseError (NumType,NumType) pNumericAnswer = parse pNumBlock "numeric answer option" . stringify where pNumBlock = do target <- double2Float <$> parseFloat tol <- optionMaybe $ double2Float <$> (spaces *> string "+-" *> spaces *> parseFloat) return (target,fromMaybe 1e-3 tol) processAnswerBlock :: AnswerBlock -> Either ParseError (String,Text,Answers) processAnswerBlock (AnswerBlock aTitle aType aPrefix aAnswers) |aType == "numerical" = fmap ((\a -> (aTitle,aPrefix,a)) . Numerical) . sequence . fmap seqFirst $ first pNumericAnswer <$> aAnswers |otherwise = Right (aTitle, aPrefix, either (error "unknown question type") id $ makeStringAnswers aType aAnswers) pAnswerBlock :: BlockP AnswerBlock pAnswerBlock = do ((_,classes,_),title) <- headerN 2 qClass <- reparse $ parse pClass "question type" classes --parse a [String] and convert back to BlockP parser prefix <- many noHeaderNoDefList definitions <- defList :: BlockP [([Inline],[Text])] answers <- reparse $ do d <- Right definitions withFracs <- convertFractions d :: Either ParseError [(Int,[Text])] let withFeedback = second (fmap splitFeedback) <$> withFracs :: [(Int,[(Text,Text)])] return $ makeAnswerProp <$> distributeFractions withFeedback return $ AnswerBlock title (head classes) prefix answers where convertFractions :: [([Inline],a)] -> Either ParseError [(Int,a)] convertFractions = sequence . fmap (seqFirst . first parseFraction) splitFeedback :: Text -> (Text,Text) splitFeedback = either (error "could not split feedback") id . parse pSplitFeedback "answer with feedback" where pSplitFeedback = do answer <- noBlockQuotes feedback <- optionMaybe blockQuote return (answer, fromMaybe [] feedback) distributeFractions :: [(a,[(b,c)])] -> [(a,b,c)] distributeFractions = fmap flatTup . concat . (seqSecond <$>) where flatTup (a,(b,c)) = (a,b,c) makeAnswerProp :: (Int,Text,Text) -> (Text,AnswerProp) makeAnswerProp (f,a,fb) = (a,AnswerProp f fb) -- |parse the list of header classes to find the question type pClass :: Parsec [String] () String pClass = tokenPrim show incPos $ mfilter (`elem` questionClasses) . Just -- |parse the faction definition (the amount of points for an answer) parseFraction :: [Inline] -> Either ParseError Int parseFraction = parse fraction "answer header" . inlinesToString where fraction = fracTrue <|> fracFalse <|> numericFraction fracTrue = (string "true" <|> string "True" <|> string "correct" <|> string "Correct") >> return 100 fracFalse = (string "false" <|> string "False" <|> string "wrong" <|> string "Wrong") >> return 0 numericFraction = read <$> many1 digit defList :: BlockP [([Inline],[Text])] defList = tokenPrim show incPos (\blk -> case blk of DefinitionList defs -> Just defs _ -> Nothing) noHeader :: BlockP Block noHeader = tokenPrim show incPos (\blk -> case blk of Header {} -> Nothing x -> Just x) noHeaderNoDefList :: BlockP Block noHeaderNoDefList = tokenPrim show incPos (\blk -> case blk of Header {} -> Nothing DefinitionList _ -> Nothing x -> Just x) headerN :: Int -> BlockP (Attr, String) headerN level = second inlinesToString <$> tokenPrim show incPos (\blk -> case blk of Header lvl' attr inls | lvl' == level -> Just (attr,inls) _ -> Nothing) blockQuote :: BlockP Text blockQuote = tokenPrim show incPos (\blk -> case blk of BlockQuote x -> Just x _ -> Nothing) noBlockQuotes :: BlockP Text noBlockQuotes = many $ tokenPrim show incPos (\blk -> case blk of BlockQuote _ -> Nothing x -> Just x) pandoc2questions :: Pandoc -> Either ParseError [Question] pandoc2questions (Pandoc _ text) = concat <$> parse (many pQuestionBlock) "input" text where -- returns (answer title, answer prefix, answers) pAnswerSection :: BlockP (String, [Block], Answers) pAnswerSection = reparse =<< (processAnswerBlock <$> pAnswerBlock) pQuestionBlock :: BlockP [Question] pQuestionBlock = do (_, questionTitle) <- headerN 1 qBody <- many noHeader answerSections <- many pAnswerSection return $ fmap (buildQuestion questionTitle qBody) answerSections -- Make a question from: question title, question body, (answer title, answer prefix, answers) buildQuestion :: String -> Text -> (String, Text, Answers) -> Question buildQuestion qTitle qBody (aTitle,aPrefix,aBody) = Question (qTitle ++ " - " ++ aTitle) (qBody ++ aPrefix) aBody parseMoodleMD :: String -> Either ParseError [Question] parseMoodleMD = pandoc2questions . readMarkdown def readMoodleMDFile :: FilePath -> IO (Either ParseError [Question]) readMoodleMDFile file = parseMoodleMD <$> readFile file
uulm-ai/moodle-md
src/Text/MoodleMD/Reader.hs
gpl-3.0
7,635
0
17
2,122
2,162
1,156
1,006
120
3
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE ViewPatterns #-} -- FIXME: Better solution for absTerm {-# LANGUAGE FlexibleContexts #-} -- | -- Copyright : (c) 2012 Benedikt Schmidt & Simon Meier -- License : GPL v3 (see LICENSE) -- -- Maintainer : Simon Meier <[email protected]> -- -- Abstract intepretation for partial evaluation of multiset rewriting -- systems. module Theory.Tools.AbstractInterpretation ( -- * Combinator to define abstract interpretations interpretAbstractly -- ** Actual interpretations , EvaluationStyle(..) , partialEvaluation ) where import Debug.Trace import Control.Basics import Control.Monad.Bind import Control.Monad.Reader import Data.Label import Data.List import qualified Data.Set as S import Data.Traversable (traverse) import Term.Substitution import Theory.Model import Theory.Text.Pretty ------------------------------------------------------------------------------ -- Abstract enough versions of builtin rules for computing ------------------------------------------------------------------------------ -- | Higher-order combinator to construct abstract interpreters. interpretAbstractly :: (Eq s, HasFrees i, Apply i, Show i) => ([Equal LNFact] -> [LNSubstVFresh]) -- ^ Unification of equalities over facts. We assume that facts with -- different tags are never unified. -> s -- ^ Initial abstract state. -> (LNFact -> s -> s) -- ^ Add a fact to the abstract state -> (s -> [LNFact]) -- ^ Facts of a state. -> [Rule i] -- ^ Multiset rewriting rules to apply abstractly. -> [(s, [Rule i])] -- ^ Sequence of abstract states and refined versions of all given -- multiset rewriting rules. interpretAbstractly unifyFactEqs initState addFact stateFacts rus = go st0 where st0 = addFact (freshFact (varTerm (LVar "z" LSortFresh 0))) $ addFact (inFact (varTerm (LVar "z" LSortMsg 0))) $ initState -- Repeatedly refine all rules and add all their conclusions until the -- state doesn't change anymore. go st = (st, rus') : if st == st' then [] else go st' where rus' = concatMap refineRule rus st' = foldl' (flip addFact) st $ concatMap (get rConcs) rus' -- Refine a rule in the context of an abstract state: for all premise -- to state facts combinations, try to solve the corresponding -- E-unification problem. If successful, return the rule with the -- unifier applied. refineRule ru = (`evalFreshT` avoid ru) $ do eqs <- forM (get rPrems ru) $ \prem -> msum $ do fa <- stateFacts st guard (factTag prem == factTag fa) -- we compute a list of 'FreshT []' actions for the outer msum return (Equal prem <$> rename fa) subst <- msum $ freshToFree <$> unifyFactEqs eqs return $ apply subst ru -- | How to report on performing a partial evaluation. data EvaluationStyle = Silent | Summary | Tracing -- | Concrete partial evaluator activated with flag: --partial-evaluation partialEvaluation :: EvaluationStyle -> [ProtoRuleE] -> WithMaude (S.Set LNFact, [ProtoRuleE]) partialEvaluation evalStyle ruEs = reader $ \hnd -> consumeEvaluation $ interpretAbstractly ((`runReader` hnd) . unifyLNFactEqs) -- FIXME: Use E-unification here S.empty (S.insert . absFact) S.toList ruEs where consumeEvaluation [] = error "partialEvaluation: impossible" consumeEvaluation ((st0, rus0) : rest0) = go (0 :: Int) st0 rus0 rest0 where go _ st rus [] = ( st , nubBy eqModuloFreshnessNoAC $ -- remove duplicates map ((`evalFresh` nothingUsed) . rename) rus ) go i st _ ((st', rus') : rest) = withTrace (go (i + 1) st' rus' rest) where incDesc = " partial evaluation: step " ++ show i ++ " added " ++ show (S.size st' - S.size st) ++ " facts" withTrace = case evalStyle of Silent -> id Summary -> trace incDesc Tracing -> trace $ incDesc ++ "\n\n" ++ ( render $ nest 2 $ numbered' $ map prettyLNFact $ S.toList $ st' `S.difference` st ) ++ "\n" -- NOTE: We should use an abstract state that identifies all variables at -- the same position provided they have the same sort. absFact :: LNFact -> LNFact absFact fa = case fa of Fact OutFact _ -> outFact (varTerm (LVar "z" LSortMsg 0)) Fact tag ts -> Fact tag $ evalAbstraction $ traverse absTerm ts where evalAbstraction = (`evalBind` noBindings) . (`evalFreshT` nothingUsed) absTerm t = case viewTerm t of Lit (Con _) -> pure t FApp (sym@(NoEq _)) ts -> fApp sym <$> traverse absTerm ts _ -> importBinding mkVar t (varName t) where mkVar name idx = varTerm (LVar name (sortOfLNTerm t) idx) varName (viewTerm -> Lit (Var v)) = lvarName v varName _ = "z" {- FIXME: Implement -- | Perform a simple propagation of sorts at the fact level. propagateSorts :: [ProtoRuleE] -> WithMaude (M.Map FactTag [LSort], [ProtoRuleE]) propagateSorts ruEs = reader $ \hnd -> -}
ekr/tamarin-prover
lib/theory/src/Theory/Tools/AbstractInterpretation.hs
gpl-3.0
5,641
0
23
1,755
1,170
628
542
82
9
{-# LANGUAGE RankNTypes, NoMonomorphismRestriction, FlexibleInstances, TypeSynonymInstances, MultiParamTypeClasses #-} {-| Local handlers to import and export bibliogräphic RDF. essentially defines our local terminology. -} module Data.RDF.Bibliography where import Data.List import Data.Maybe import Control.Applicative import qualified Data.Map as M import qualified Data.Text as T import qualified Data.RDF as R import qualified Data.RDF.Namespace as N -- import Debug.Hood.Observe import RdfHandler bibliographyMappings = N.mergePrefixMappings N.standard_ns_mappings $ N.ns_mappings [ bibo ] pubGraph:: R.Triples -> RDFdb pubGraph triples = R.mkRdf triples Nothing bibliographyMappings where addPubPrefix g = R.addPrefixMappings g bibliographyMappings True bibo:: N.Namespace bibo = N.mkPrefixedNS' "bibo" "http://purl.org/ontology/bibo/#" publicationNode id = (R.bnode $ T.pack $ ":" ++ id) authorPred = mkUnode' dct "creator" editorPred = mkUnode' bibo "editor" author:: TripleGenFkt author = flip literalTriple authorPred titlePred = mkUnode' dct "title" title:: TripleGenFkt title = flip literalTriple titlePred namePred = mkUnode' dct "name" name:: TripleGenFkt name = flip literalTriple namePred booktitlePred = mkUnode' dct "partOf" booktitle:: TripleGenFkt booktitle = flip literalTriple booktitlePred publisherPred = mkUnode' dct "publisher" publisher:: TripleGenFkt publisher = flip literalTriple publisherPred -- TODO parse time sensibly -- FIXME rename year to created yearPred = mkUnode' dct "created" year:: TripleGenFkt year = flip literalTriple yearPred timestampPred = R.unode$ T.pack ":timestamp" dbDateInserted:: TripleGenFkt dbDateInserted s t = flip literalTriple timestampPred s t filePred = strRnode ":file" urlPred = strRnode ":url" url:: TripleGenFkt url = flip literalTriple urlPred pdfurlPred = strRnode ":pdfUrl" pdfurl:: TripleGenFkt pdfurl = flip literalTriple pdfurlPred pagesPred = mkUnode' bibo "numPages" startPagePred = mkUnode' bibo "pageStart" endPagePred = mkUnode' bibo "pageEnd" pages:: R.Subject -> T.Text -> R.Triples pages s t = case T.splitOn (T.pack "-") t of (p:[]) -> [literalTriple s pagesPred p] (start:end:_) -> [ literalTriple s startPagePred start , literalTriple s endPagePred end ] abbreviationPred = R.unode $ T.pack ":abbreviation" ------------- RDF Handling -------------------------- listhead = Data.List.head typesOf = objectsByPred typePred typeOf = (listToMaybe.).typesOf -- listhead.(typesOf g) authorsOf = objectsByPred authorPred editorsOf = objectsByPred editorPred titlesOf = objectsByPred titlePred titleOf = (listToMaybe.).titlesOf namesOf = objectsByPred namePred nameOf = (listToMaybe.).namesOf abbreviationsOf = objectsByPred abbreviationPred yearsOf = objectsByPred yearPred yearOf = (listToMaybe.).yearsOf booktitlesOf = objectsByPred booktitlePred booktitleOf = (listToMaybe.).booktitlesOf pdfurlOf = objectsByPred pdfurlPred -- flip (queryObjects g) pdfurlPred timestampsOf = objectsByPred timestampPred timestampOf = (listToMaybe.).timestampsOf {- Group subjects by year-attribute -} groupByYear:: RDFdb -> [R.Subject] -> [[R.Subject]] groupByYear g = groupBy (\s s' -> (yearInt g s) == (yearInt g s')) -- map (\s -> (s, yearOf g s)) xs cmpSubjYear:: RDFdb -> R.Subject -> R.Subject -> Maybe Ordering cmpSubjYear g s s' = pure compare <*> (yearInt g s) <*> (yearInt g s') {- Comparision function for Year Attributes -} compareSubjectYear:: RDFdb -> R.Subject -> R.Subject -> Ordering compareSubjectYear g s s' = case cmpSubjYear g s s' of (Nothing) -> EQ (Just x ) -> x yearInt:: RDFdb -> R.Subject -> Maybe Integer yearInt g s = pure (read.(R.view)) <*> (yearOf g s)
FiskerLars/scorg
src/Data/RDF/Bibliography.hs
gpl-3.0
3,797
1
10
619
1,000
536
464
82
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.ContainerAnalysis.Projects.Notes.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists notes for the specified project. -- -- /See:/ <https://cloud.google.com/container-analysis/api/reference/rest/ Container Analysis API Reference> for @containeranalysis.projects.notes.list@. module Network.Google.Resource.ContainerAnalysis.Projects.Notes.List ( -- * REST Resource ProjectsNotesListResource -- * Creating a Request , projectsNotesList , ProjectsNotesList -- * Request Lenses , pnlParent , pnlXgafv , pnlUploadProtocol , pnlAccessToken , pnlUploadType , pnlFilter , pnlPageToken , pnlPageSize , pnlCallback ) where import Network.Google.ContainerAnalysis.Types import Network.Google.Prelude -- | A resource alias for @containeranalysis.projects.notes.list@ method which the -- 'ProjectsNotesList' request conforms to. type ProjectsNotesListResource = "v1beta1" :> Capture "parent" Text :> "notes" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "filter" Text :> QueryParam "pageToken" Text :> QueryParam "pageSize" (Textual Int32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ListNotesResponse -- | Lists notes for the specified project. -- -- /See:/ 'projectsNotesList' smart constructor. data ProjectsNotesList = ProjectsNotesList' { _pnlParent :: !Text , _pnlXgafv :: !(Maybe Xgafv) , _pnlUploadProtocol :: !(Maybe Text) , _pnlAccessToken :: !(Maybe Text) , _pnlUploadType :: !(Maybe Text) , _pnlFilter :: !(Maybe Text) , _pnlPageToken :: !(Maybe Text) , _pnlPageSize :: !(Maybe (Textual Int32)) , _pnlCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsNotesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pnlParent' -- -- * 'pnlXgafv' -- -- * 'pnlUploadProtocol' -- -- * 'pnlAccessToken' -- -- * 'pnlUploadType' -- -- * 'pnlFilter' -- -- * 'pnlPageToken' -- -- * 'pnlPageSize' -- -- * 'pnlCallback' projectsNotesList :: Text -- ^ 'pnlParent' -> ProjectsNotesList projectsNotesList pPnlParent_ = ProjectsNotesList' { _pnlParent = pPnlParent_ , _pnlXgafv = Nothing , _pnlUploadProtocol = Nothing , _pnlAccessToken = Nothing , _pnlUploadType = Nothing , _pnlFilter = Nothing , _pnlPageToken = Nothing , _pnlPageSize = Nothing , _pnlCallback = Nothing } -- | Required. The name of the project to list notes for in the form of -- \`projects\/[PROJECT_ID]\`. pnlParent :: Lens' ProjectsNotesList Text pnlParent = lens _pnlParent (\ s a -> s{_pnlParent = a}) -- | V1 error format. pnlXgafv :: Lens' ProjectsNotesList (Maybe Xgafv) pnlXgafv = lens _pnlXgafv (\ s a -> s{_pnlXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pnlUploadProtocol :: Lens' ProjectsNotesList (Maybe Text) pnlUploadProtocol = lens _pnlUploadProtocol (\ s a -> s{_pnlUploadProtocol = a}) -- | OAuth access token. pnlAccessToken :: Lens' ProjectsNotesList (Maybe Text) pnlAccessToken = lens _pnlAccessToken (\ s a -> s{_pnlAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pnlUploadType :: Lens' ProjectsNotesList (Maybe Text) pnlUploadType = lens _pnlUploadType (\ s a -> s{_pnlUploadType = a}) -- | The filter expression. pnlFilter :: Lens' ProjectsNotesList (Maybe Text) pnlFilter = lens _pnlFilter (\ s a -> s{_pnlFilter = a}) -- | Token to provide to skip to a particular spot in the list. pnlPageToken :: Lens' ProjectsNotesList (Maybe Text) pnlPageToken = lens _pnlPageToken (\ s a -> s{_pnlPageToken = a}) -- | Number of notes to return in the list. Must be positive. Max allowed -- page size is 1000. If not specified, page size defaults to 20. pnlPageSize :: Lens' ProjectsNotesList (Maybe Int32) pnlPageSize = lens _pnlPageSize (\ s a -> s{_pnlPageSize = a}) . mapping _Coerce -- | JSONP pnlCallback :: Lens' ProjectsNotesList (Maybe Text) pnlCallback = lens _pnlCallback (\ s a -> s{_pnlCallback = a}) instance GoogleRequest ProjectsNotesList where type Rs ProjectsNotesList = ListNotesResponse type Scopes ProjectsNotesList = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsNotesList'{..} = go _pnlParent _pnlXgafv _pnlUploadProtocol _pnlAccessToken _pnlUploadType _pnlFilter _pnlPageToken _pnlPageSize _pnlCallback (Just AltJSON) containerAnalysisService where go = buildClient (Proxy :: Proxy ProjectsNotesListResource) mempty
brendanhay/gogol
gogol-containeranalysis/gen/Network/Google/Resource/ContainerAnalysis/Projects/Notes/List.hs
mpl-2.0
5,855
0
19
1,419
960
554
406
134
1
module HelperSequences.A002262Spec (main, spec) where import Test.Hspec import HelperSequences.A002262 (a002262) main :: IO () main = hspec spec spec :: Spec spec = describe "A002262" $ it "correctly computes the first 22 elements" $ take 22 (map a002262 [0..]) `shouldBe` expectedValue where expectedValue = [0,0,1,0,1,2,0,1,2,3,0,1,2,3,4,0,1,2,3,4,5,0]
peterokagey/haskellOEIS
test/HelperSequences/A002262Spec.hs
apache-2.0
369
0
10
59
166
99
67
10
1
{-# LANGUAGE ForeignFunctionInterface #-} ----------------------------------------------------------------------------- -- | -- Module : Haddock.Utils -- Copyright : (c) The University of Glasgow 2001-2002, -- Simon Marlow 2003-2006, -- David Waern 2006-2009 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable ----------------------------------------------------------------------------- module Haddock.Utils ( -- * Misc utilities restrictTo, toDescription, toInstalledDescription, -- * Filename utilities moduleHtmlFile, contentsHtmlFile, indexHtmlFile, frameIndexHtmlFile, moduleIndexFrameName, mainFrameName, synopsisFrameName, subIndexHtmlFile, jsFile, framesFile, -- * Anchor and URL utilities moduleNameUrl, moduleUrl, nameAnchorId, makeAnchorId, -- * Miscellaneous utilities getProgramName, bye, die, dieMsg, noDieMsg, mapSnd, mapMaybeM, escapeStr, -- * HTML cross reference mapping html_xrefs_ref, -- * Doc markup markup, idMarkup, -- * List utilities replace, spanWith, -- * MTL stuff MonadIO(..), -- * Logging parseVerbosity, out, -- * System tools getProcessID ) where import Haddock.Types import Haddock.GhcUtils import GHC import Name import Control.Monad ( liftM ) import Data.Char ( isAlpha, isAlphaNum, isAscii, ord, chr ) import Numeric ( showIntAtBase ) import Data.Map ( Map ) import qualified Data.Map as Map hiding ( Map ) import Data.IORef ( IORef, newIORef, readIORef ) import Data.List ( isSuffixOf ) import Data.Maybe ( fromJust ) import System.Environment ( getProgName ) import System.Exit ( exitWith, ExitCode(..) ) import System.IO ( hPutStr, stderr ) import System.IO.Unsafe ( unsafePerformIO ) import qualified System.FilePath.Posix as HtmlPath import Distribution.Verbosity import Distribution.ReadE #ifndef mingw32_HOST_OS import qualified System.Posix.Internals #endif import MonadUtils ( MonadIO(..) ) -------------------------------------------------------------------------------- -- * Logging -------------------------------------------------------------------------------- parseVerbosity :: String -> Either String Verbosity parseVerbosity = runReadE flagToVerbosity -- | Print a message to stdout, if it is not too verbose out :: MonadIO m => Verbosity -- ^ program verbosity -> Verbosity -- ^ message verbosity -> String -> m () out progVerbosity msgVerbosity msg | msgVerbosity <= progVerbosity = liftIO $ putStrLn msg | otherwise = return () -------------------------------------------------------------------------------- -- * Some Utilities -------------------------------------------------------------------------------- -- | Extract a module's short description. toDescription :: Interface -> Maybe (Doc Name) toDescription = hmi_description . ifaceInfo -- | Extract a module's short description. toInstalledDescription :: InstalledInterface -> Maybe (Doc Name) toInstalledDescription = hmi_description . instInfo -------------------------------------------------------------------------------- -- * Making abstract declarations -------------------------------------------------------------------------------- restrictTo :: [Name] -> LHsDecl Name -> LHsDecl Name restrictTo names (L loc decl) = L loc $ case decl of TyClD d | isDataDecl d && tcdND d == DataType -> TyClD (d { tcdCons = restrictCons names (tcdCons d) }) TyClD d | isDataDecl d && tcdND d == NewType -> case restrictCons names (tcdCons d) of [] -> TyClD (d { tcdND = DataType, tcdCons = [] }) [con] -> TyClD (d { tcdCons = [con] }) _ -> error "Should not happen" TyClD d | isClassDecl d -> TyClD (d { tcdSigs = restrictDecls names (tcdSigs d), tcdATs = restrictATs names (tcdATs d) }) _ -> decl restrictCons :: [Name] -> [LConDecl Name] -> [LConDecl Name] restrictCons names decls = [ L p d | L p (Just d) <- map (fmap keep) decls ] where keep d | unLoc (con_name d) `elem` names = case con_details d of PrefixCon _ -> Just d RecCon fields | all field_avail fields -> Just d | otherwise -> Just (d { con_details = PrefixCon (field_types fields) }) -- if we have *all* the field names available, then -- keep the record declaration. Otherwise degrade to -- a constructor declaration. This isn't quite right, but -- it's the best we can do. InfixCon _ _ -> Just d where field_avail (ConDeclField n _ _) = unLoc n `elem` names field_types flds = [ t | ConDeclField _ t _ <- flds ] keep _ | otherwise = Nothing restrictDecls :: [Name] -> [LSig Name] -> [LSig Name] restrictDecls names decls = filter keep decls where keep d = fromJust (sigName d) `elem` names -- has to have a name, since it's a class method type signature restrictATs :: [Name] -> [LTyClDecl Name] -> [LTyClDecl Name] restrictATs names ats = [ at | at <- ats , tcdName (unL at) `elem` names ] -------------------------------------------------------------------------------- -- * Filename mangling functions stolen from s main/DriverUtil.lhs. -------------------------------------------------------------------------------- moduleHtmlFile :: Module -> FilePath moduleHtmlFile mdl = case Map.lookup mdl html_xrefs of Nothing -> mdl' ++ ".html" Just fp0 -> HtmlPath.joinPath [fp0, mdl' ++ ".html"] where mdl' = map (\c -> if c == '.' then '-' else c) (moduleNameString (moduleName mdl)) contentsHtmlFile, indexHtmlFile :: String contentsHtmlFile = "index.html" indexHtmlFile = "doc-index.html" -- | The name of the module index file to be displayed inside a frame. -- Modules are display in full, but without indentation. Clicking opens in -- the main window. frameIndexHtmlFile :: String frameIndexHtmlFile = "index-frames.html" moduleIndexFrameName, mainFrameName, synopsisFrameName :: String moduleIndexFrameName = "modules" mainFrameName = "main" synopsisFrameName = "synopsis" subIndexHtmlFile :: Char -> String subIndexHtmlFile a = "doc-index-" ++ b ++ ".html" where b | isAlpha a = [a] | otherwise = show (ord a) ------------------------------------------------------------------------------- -- * Anchor and URL utilities -- -- NB: Anchor IDs, used as the destination of a link within a document must -- conform to XML's NAME production. That, taken with XHTML and HTML 4.01's -- various needs and compatibility constraints, means these IDs have to match: -- [A-Za-z][A-Za-z0-9:_.-]* -- Such IDs do not need to be escaped in any way when used as the fragment part -- of a URL. Indeed, %-escaping them can lead to compatibility issues as it -- isn't clear if such fragment identifiers should, or should not be unescaped -- before being matched with IDs in the target document. ------------------------------------------------------------------------------- moduleUrl :: Module -> String moduleUrl = moduleHtmlFile moduleNameUrl :: Module -> OccName -> String moduleNameUrl mdl n = moduleUrl mdl ++ '#' : nameAnchorId n nameAnchorId :: OccName -> String nameAnchorId name = makeAnchorId (prefix : ':' : occNameString name) where prefix | isValOcc name = 'v' | otherwise = 't' -- | Takes an arbitrary string and makes it a valid anchor ID. The mapping is -- identity preserving. makeAnchorId :: String -> String makeAnchorId [] = [] makeAnchorId (f:r) = escape isAlpha f ++ concatMap (escape isLegal) r where escape p c | p c = [c] | otherwise = '-' : (show (ord c)) ++ "-" isLegal ':' = True isLegal '_' = True isLegal '.' = True isLegal c = isAscii c && isAlphaNum c -- NB: '-' is legal in IDs, but we use it as the escape char ------------------------------------------------------------------------------- -- * Files we need to copy from our $libdir ------------------------------------------------------------------------------- jsFile, framesFile :: String jsFile = "haddock-util.js" framesFile = "frames.html" ------------------------------------------------------------------------------- -- * Misc. ------------------------------------------------------------------------------- getProgramName :: IO String getProgramName = liftM (`withoutSuffix` ".bin") getProgName where str `withoutSuffix` suff | suff `isSuffixOf` str = take (length str - length suff) str | otherwise = str bye :: String -> IO a bye s = putStr s >> exitWith ExitSuccess die :: String -> IO a die s = hPutStr stderr s >> exitWith (ExitFailure 1) dieMsg :: String -> IO a dieMsg s = getProgramName >>= \prog -> die (prog ++ ": " ++ s) noDieMsg :: String -> IO () noDieMsg s = getProgramName >>= \prog -> hPutStr stderr (prog ++ ": " ++ s) mapSnd :: (b -> c) -> [(a,b)] -> [(a,c)] mapSnd _ [] = [] mapSnd f ((x,y):xs) = (x,f y) : mapSnd f xs mapMaybeM :: Monad m => (a -> m b) -> Maybe a -> m (Maybe b) mapMaybeM _ Nothing = return Nothing mapMaybeM f (Just a) = liftM Just (f a) escapeStr :: String -> String escapeStr = escapeURIString isUnreserved -- Following few functions are copy'n'pasted from Network.URI module -- to avoid depending on the network lib, since doing so gives a -- circular build dependency between haddock and network -- (at least if you want to build network with haddock docs) -- NB: These functions do NOT escape Unicode strings for URLs as per the RFCs escapeURIChar :: (Char -> Bool) -> Char -> String escapeURIChar p c | p c = [c] | otherwise = '%' : myShowHex (ord c) "" where myShowHex :: Int -> ShowS myShowHex n r = case showIntAtBase 16 toChrHex n r of [] -> "00" [a] -> ['0',a] cs -> cs toChrHex d | d < 10 = chr (ord '0' + fromIntegral d) | otherwise = chr (ord 'A' + fromIntegral (d - 10)) escapeURIString :: (Char -> Bool) -> String -> String escapeURIString = concatMap . escapeURIChar isUnreserved :: Char -> Bool isUnreserved c = isAlphaNumChar c || (c `elem` "-_.~") isAlphaChar, isDigitChar, isAlphaNumChar :: Char -> Bool isAlphaChar c = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') isDigitChar c = c >= '0' && c <= '9' isAlphaNumChar c = isAlphaChar c || isDigitChar c ----------------------------------------------------------------------------- -- * HTML cross references -- -- For each module, we need to know where its HTML documentation lives -- so that we can point hyperlinks to it. It is extremely -- inconvenient to plumb this information to all the places that need -- it (basically every function in HaddockHtml), and furthermore the -- mapping is constant for any single run of Haddock. So for the time -- being I'm going to use a write-once global variable. ----------------------------------------------------------------------------- {-# NOINLINE html_xrefs_ref #-} html_xrefs_ref :: IORef (Map Module FilePath) html_xrefs_ref = unsafePerformIO (newIORef (error "module_map")) {-# NOINLINE html_xrefs #-} html_xrefs :: Map Module FilePath html_xrefs = unsafePerformIO (readIORef html_xrefs_ref) ----------------------------------------------------------------------------- -- * List utils ----------------------------------------------------------------------------- replace :: Eq a => a -> a -> [a] -> [a] replace a b = map (\x -> if x == a then b else x) spanWith :: (a -> Maybe b) -> [a] -> ([b],[a]) spanWith _ [] = ([],[]) spanWith p xs@(a:as) | Just b <- p a = let (bs,cs) = spanWith p as in (b:bs,cs) | otherwise = ([],xs) ----------------------------------------------------------------------------- -- * Put here temporarily ----------------------------------------------------------------------------- markup :: DocMarkup id a -> Doc id -> a markup m DocEmpty = markupEmpty m markup m (DocAppend d1 d2) = markupAppend m (markup m d1) (markup m d2) markup m (DocString s) = markupString m s markup m (DocParagraph d) = markupParagraph m (markup m d) markup m (DocIdentifier ids) = markupIdentifier m ids markup m (DocModule mod0) = markupModule m mod0 markup m (DocEmphasis d) = markupEmphasis m (markup m d) markup m (DocMonospaced d) = markupMonospaced m (markup m d) markup m (DocUnorderedList ds) = markupUnorderedList m (map (markup m) ds) markup m (DocOrderedList ds) = markupOrderedList m (map (markup m) ds) markup m (DocDefList ds) = markupDefList m (map (markupPair m) ds) markup m (DocCodeBlock d) = markupCodeBlock m (markup m d) markup m (DocURL url) = markupURL m url markup m (DocAName ref) = markupAName m ref markup m (DocPic img) = markupPic m img markup m (DocExamples e) = markupExample m e markupPair :: DocMarkup id a -> (Doc id, Doc id) -> (a, a) markupPair m (a,b) = (markup m a, markup m b) -- | The identity markup idMarkup :: DocMarkup a (Doc a) idMarkup = Markup { markupEmpty = DocEmpty, markupString = DocString, markupParagraph = DocParagraph, markupAppend = DocAppend, markupIdentifier = DocIdentifier, markupModule = DocModule, markupEmphasis = DocEmphasis, markupMonospaced = DocMonospaced, markupUnorderedList = DocUnorderedList, markupOrderedList = DocOrderedList, markupDefList = DocDefList, markupCodeBlock = DocCodeBlock, markupURL = DocURL, markupAName = DocAName, markupPic = DocPic, markupExample = DocExamples } ----------------------------------------------------------------------------- -- * System tools ----------------------------------------------------------------------------- #ifdef mingw32_HOST_OS foreign import ccall unsafe "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows #else getProcessID :: IO Int getProcessID = fmap fromIntegral System.Posix.Internals.c_getpid #endif
nominolo/haddock2
src/Haddock/Utils.hs
bsd-2-clause
14,095
0
18
2,858
3,440
1,842
1,598
220
6
{-# LANGUAGE CPP, RecordWildCards, NamedFieldPuns, RankNTypes #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE NoMonoLocalBinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFunctor #-} -- | Planning how to build everything in a project. -- module Distribution.Client.ProjectPlanning ( -- * elaborated install plan types ElaboratedInstallPlan, ElaboratedConfiguredPackage(..), ElaboratedPlanPackage, ElaboratedSharedConfig(..), ElaboratedReadyPackage, BuildStyle(..), CabalFileText, -- * Producing the elaborated install plan rebuildProjectConfig, rebuildInstallPlan, -- * Build targets availableTargets, AvailableTarget(..), AvailableTargetStatus(..), TargetRequested(..), ComponentTarget(..), SubComponentTarget(..), showComponentTarget, nubComponentTargets, -- * Selecting a plan subset pruneInstallPlanToTargets, TargetAction(..), pruneInstallPlanToDependencies, CannotPruneDependencies(..), -- * Utils required for building pkgHasEphemeralBuildTargets, elabBuildTargetWholeComponents, -- * Setup.hs CLI flags for building setupHsScriptOptions, setupHsConfigureFlags, setupHsConfigureArgs, setupHsBuildFlags, setupHsBuildArgs, setupHsReplFlags, setupHsReplArgs, setupHsTestFlags, setupHsTestArgs, setupHsBenchFlags, setupHsBenchArgs, setupHsCopyFlags, setupHsRegisterFlags, setupHsHaddockFlags, packageHashInputs, -- * Path construction binDirectoryFor, ) where import Prelude () import Distribution.Client.Compat.Prelude import Distribution.Client.ProjectPlanning.Types as Ty import Distribution.Client.PackageHash import Distribution.Client.RebuildMonad import Distribution.Client.Store import Distribution.Client.ProjectConfig import Distribution.Client.ProjectPlanOutput import Distribution.Client.Types import qualified Distribution.Client.InstallPlan as InstallPlan import qualified Distribution.Client.SolverInstallPlan as SolverInstallPlan import Distribution.Client.Dependency import Distribution.Client.Dependency.Types import qualified Distribution.Client.IndexUtils as IndexUtils import Distribution.Client.Targets (userToPackageConstraint) import Distribution.Client.DistDirLayout import Distribution.Client.SetupWrapper import Distribution.Client.JobControl import Distribution.Client.FetchUtils import qualified Hackage.Security.Client as Sec import Distribution.Client.Setup hiding (packageName, cabalVersion) import Distribution.Utils.NubList import Distribution.Utils.LogProgress import Distribution.Utils.MapAccum import qualified Distribution.Solver.Types.ComponentDeps as CD import Distribution.Solver.Types.ComponentDeps (ComponentDeps) import Distribution.Solver.Types.ConstraintSource import Distribution.Solver.Types.LabeledPackageConstraint import Distribution.Solver.Types.OptionalStanza import Distribution.Solver.Types.PkgConfigDb import Distribution.Solver.Types.ResolverPackage import Distribution.Solver.Types.SolverId import Distribution.Solver.Types.SolverPackage import Distribution.Solver.Types.InstSolverPackage import Distribution.Solver.Types.SourcePackage import Distribution.Solver.Types.Settings import Distribution.ModuleName import Distribution.Package hiding (InstalledPackageId, installedPackageId) import Distribution.Types.AnnotatedId import Distribution.Types.ComponentName import Distribution.Types.PkgconfigDependency import Distribution.Types.UnqualComponentName import Distribution.System import qualified Distribution.PackageDescription as Cabal import qualified Distribution.PackageDescription as PD import qualified Distribution.PackageDescription.Configuration as PD import Distribution.Simple.PackageIndex (InstalledPackageIndex) import Distribution.Simple.Compiler hiding (Flag) import qualified Distribution.Simple.GHC as GHC --TODO: [code cleanup] eliminate import qualified Distribution.Simple.GHCJS as GHCJS --TODO: [code cleanup] eliminate import Distribution.Simple.Program import Distribution.Simple.Program.Db import Distribution.Simple.Program.Find import qualified Distribution.Simple.Setup as Cabal import Distribution.Simple.Setup (Flag, toFlag, flagToMaybe, flagToList, fromFlagOrDefault) import qualified Distribution.Simple.Configure as Cabal import qualified Distribution.Simple.LocalBuildInfo as Cabal import Distribution.Simple.LocalBuildInfo ( Component(..), pkgComponents, componentBuildInfo , componentName ) import qualified Distribution.Simple.InstallDirs as InstallDirs import qualified Distribution.InstalledPackageInfo as IPI import Distribution.Backpack.ConfiguredComponent import Distribution.Backpack.LinkedComponent import Distribution.Backpack.ComponentsGraph import Distribution.Backpack.ModuleShape import Distribution.Backpack.FullUnitId import Distribution.Backpack import Distribution.Types.ComponentInclude import Distribution.Simple.Utils hiding (matchFileGlob) import Distribution.Version import Distribution.Verbosity import Distribution.Text import qualified Distribution.Compat.Graph as Graph import Distribution.Compat.Graph(IsNode(..)) import Text.PrettyPrint hiding ((<>)) import qualified Text.PrettyPrint as Disp import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Control.Monad import qualified Data.Traversable as T import Control.Monad.State as State import Control.Exception import Data.List (groupBy) import Data.Either import Data.Function import System.FilePath ------------------------------------------------------------------------------ -- * Elaborated install plan ------------------------------------------------------------------------------ -- "Elaborated" -- worked out with great care and nicety of detail; -- executed with great minuteness: elaborate preparations; -- elaborate care. -- -- So here's the idea: -- -- Rather than a miscellaneous collection of 'ConfigFlags', 'InstallFlags' etc -- all passed in as separate args and which are then further selected, -- transformed etc during the execution of the build. Instead we construct -- an elaborated install plan that includes everything we will need, and then -- during the execution of the plan we do as little transformation of this -- info as possible. -- -- So we're trying to split the work into two phases: construction of the -- elaborated install plan (which as far as possible should be pure) and -- then simple execution of that plan without any smarts, just doing what the -- plan says to do. -- -- So that means we need a representation of this fully elaborated install -- plan. The representation consists of two parts: -- -- * A 'ElaboratedInstallPlan'. This is a 'GenericInstallPlan' with a -- representation of source packages that includes a lot more detail about -- that package's individual configuration -- -- * A 'ElaboratedSharedConfig'. Some package configuration is the same for -- every package in a plan. Rather than duplicate that info every entry in -- the 'GenericInstallPlan' we keep that separately. -- -- The division between the shared and per-package config is /not set in stone -- for all time/. For example if we wanted to generalise the install plan to -- describe a situation where we want to build some packages with GHC and some -- with GHCJS then the platform and compiler would no longer be shared between -- all packages but would have to be per-package (probably with some sanity -- condition on the graph structure). -- -- Refer to ProjectPlanning.Types for details of these important types: -- type ElaboratedInstallPlan = ... -- type ElaboratedPlanPackage = ... -- data ElaboratedSharedConfig = ... -- data ElaboratedConfiguredPackage = ... -- data BuildStyle = -- | Check that an 'ElaboratedConfiguredPackage' actually makes -- sense under some 'ElaboratedSharedConfig'. sanityCheckElaboratedConfiguredPackage :: ElaboratedSharedConfig -> ElaboratedConfiguredPackage -> a -> a sanityCheckElaboratedConfiguredPackage sharedConfig elab@ElaboratedConfiguredPackage{..} = (case elabPkgOrComp of ElabPackage pkg -> sanityCheckElaboratedPackage elab pkg ElabComponent comp -> sanityCheckElaboratedComponent elab comp) -- either a package is being built inplace, or the -- 'installedPackageId' we assigned is consistent with -- the 'hashedInstalledPackageId' we would compute from -- the elaborated configured package . assert (elabBuildStyle == BuildInplaceOnly || elabComponentId == hashedInstalledPackageId (packageHashInputs sharedConfig elab)) -- the stanzas explicitly disabled should not be available . assert (Set.null (Map.keysSet (Map.filter not elabStanzasRequested) `Set.intersection` elabStanzasAvailable)) -- either a package is built inplace, or we are not attempting to -- build any test suites or benchmarks (we never build these -- for remote packages!) . assert (elabBuildStyle == BuildInplaceOnly || Set.null elabStanzasAvailable) sanityCheckElaboratedComponent :: ElaboratedConfiguredPackage -> ElaboratedComponent -> a -> a sanityCheckElaboratedComponent ElaboratedConfiguredPackage{..} ElaboratedComponent{..} = -- Should not be building bench or test if not inplace. assert (elabBuildStyle == BuildInplaceOnly || case compComponentName of Nothing -> True Just CLibName -> True Just (CSubLibName _) -> True Just (CExeName _) -> True -- This is interesting: there's no way to declare a dependency -- on a foreign library at the moment, but you may still want -- to install these to the store Just (CFLibName _) -> True Just (CBenchName _) -> False Just (CTestName _) -> False) sanityCheckElaboratedPackage :: ElaboratedConfiguredPackage -> ElaboratedPackage -> a -> a sanityCheckElaboratedPackage ElaboratedConfiguredPackage{..} ElaboratedPackage{..} = -- we should only have enabled stanzas that actually can be built -- (according to the solver) assert (pkgStanzasEnabled `Set.isSubsetOf` elabStanzasAvailable) -- the stanzas that the user explicitly requested should be -- enabled (by the previous test, they are also available) . assert (Map.keysSet (Map.filter id elabStanzasRequested) `Set.isSubsetOf` pkgStanzasEnabled) ------------------------------------------------------------------------------ -- * Deciding what to do: making an 'ElaboratedInstallPlan' ------------------------------------------------------------------------------ -- | Return the up-to-date project config and information about the local -- packages within the project. -- rebuildProjectConfig :: Verbosity -> DistDirLayout -> ProjectConfig -> IO (ProjectConfig, [UnresolvedSourcePackage]) rebuildProjectConfig verbosity distDirLayout@DistDirLayout { distProjectRootDirectory, distDirectory, distProjectCacheFile, distProjectCacheDirectory } cliConfig = do (projectConfig, localPackages) <- runRebuild distProjectRootDirectory $ rerunIfChanged verbosity fileMonitorProjectConfig () $ do projectConfig <- phaseReadProjectConfig localPackages <- phaseReadLocalPackages projectConfig return (projectConfig, localPackages) return (projectConfig <> cliConfig, localPackages) where ProjectConfigShared { projectConfigConfigFile } = projectConfigShared cliConfig fileMonitorProjectConfig = newFileMonitor (distProjectCacheFile "config") -- Read the cabal.project (or implicit config) and combine it with -- arguments from the command line -- phaseReadProjectConfig :: Rebuild ProjectConfig phaseReadProjectConfig = do liftIO $ do info verbosity "Project settings changed, reconfiguring..." createDirectoryIfMissingVerbose verbosity True distDirectory createDirectoryIfMissingVerbose verbosity True distProjectCacheDirectory readProjectConfig verbosity projectConfigConfigFile distDirLayout -- Look for all the cabal packages in the project -- some of which may be local src dirs, tarballs etc -- phaseReadLocalPackages :: ProjectConfig -> Rebuild [UnresolvedSourcePackage] phaseReadLocalPackages projectConfig = do localCabalFiles <- findProjectPackages distDirLayout projectConfig mapM (readSourcePackage verbosity) localCabalFiles -- | Return an up-to-date elaborated install plan. -- -- Two variants of the install plan are returned: with and without packages -- from the store. That is, the \"improved\" plan where source packages are -- replaced by pre-existing installed packages from the store (when their ids -- match), and also the original elaborated plan which uses primarily source -- packages. -- The improved plan is what we use for building, but the original elaborated -- plan is useful for reporting and configuration. For example the @freeze@ -- command needs the source package info to know about flag choices and -- dependencies of executables and setup scripts. -- rebuildInstallPlan :: Verbosity -> DistDirLayout -> CabalDirLayout -> ProjectConfig -> [UnresolvedSourcePackage] -> IO ( ElaboratedInstallPlan -- with store packages , ElaboratedInstallPlan -- with source packages , ElaboratedSharedConfig ) -- ^ @(improvedPlan, elaboratedPlan, _, _)@ rebuildInstallPlan verbosity distDirLayout@DistDirLayout { distProjectRootDirectory, distProjectCacheFile } CabalDirLayout { cabalStoreDirLayout } = \projectConfig localPackages -> runRebuild distProjectRootDirectory $ do progsearchpath <- liftIO $ getSystemSearchPath let projectConfigMonitored = projectConfig { projectConfigBuildOnly = mempty } -- The overall improved plan is cached rerunIfChanged verbosity fileMonitorImprovedPlan -- react to changes in the project config, -- the package .cabal files and the path (projectConfigMonitored, localPackages, progsearchpath) $ do -- And so is the elaborated plan that the improved plan based on (elaboratedPlan, elaboratedShared) <- rerunIfChanged verbosity fileMonitorElaboratedPlan (projectConfigMonitored, localPackages, progsearchpath) $ do compilerEtc <- phaseConfigureCompiler projectConfig _ <- phaseConfigurePrograms projectConfig compilerEtc (solverPlan, pkgConfigDB) <- phaseRunSolver projectConfig compilerEtc localPackages (elaboratedPlan, elaboratedShared) <- phaseElaboratePlan projectConfig compilerEtc pkgConfigDB solverPlan localPackages phaseMaintainPlanOutputs elaboratedPlan elaboratedShared return (elaboratedPlan, elaboratedShared) -- The improved plan changes each time we install something, whereas -- the underlying elaborated plan only changes when input config -- changes, so it's worth caching them separately. improvedPlan <- phaseImprovePlan elaboratedPlan elaboratedShared return (improvedPlan, elaboratedPlan, elaboratedShared) where fileMonitorCompiler = newFileMonitorInCacheDir "compiler" fileMonitorSolverPlan = newFileMonitorInCacheDir "solver-plan" fileMonitorSourceHashes = newFileMonitorInCacheDir "source-hashes" fileMonitorElaboratedPlan = newFileMonitorInCacheDir "elaborated-plan" fileMonitorImprovedPlan = newFileMonitorInCacheDir "improved-plan" newFileMonitorInCacheDir :: Eq a => FilePath -> FileMonitor a b newFileMonitorInCacheDir = newFileMonitor . distProjectCacheFile -- Configure the compiler we're using. -- -- This is moderately expensive and doesn't change that often so we cache -- it independently. -- phaseConfigureCompiler :: ProjectConfig -> Rebuild (Compiler, Platform, ProgramDb) phaseConfigureCompiler ProjectConfig { projectConfigShared = ProjectConfigShared { projectConfigHcFlavor, projectConfigHcPath, projectConfigHcPkg }, projectConfigLocalPackages = PackageConfig { packageConfigProgramPaths, packageConfigProgramArgs, packageConfigProgramPathExtra } } = do progsearchpath <- liftIO $ getSystemSearchPath rerunIfChanged verbosity fileMonitorCompiler (hcFlavor, hcPath, hcPkg, progsearchpath, packageConfigProgramPaths, packageConfigProgramArgs, packageConfigProgramPathExtra) $ do liftIO $ info verbosity "Compiler settings changed, reconfiguring..." result@(_, _, progdb') <- liftIO $ Cabal.configCompilerEx hcFlavor hcPath hcPkg progdb verbosity -- Note that we added the user-supplied program locations and args -- for /all/ programs, not just those for the compiler prog and -- compiler-related utils. In principle we don't know which programs -- the compiler will configure (and it does vary between compilers). -- We do know however that the compiler will only configure the -- programs it cares about, and those are the ones we monitor here. monitorFiles (programsMonitorFiles progdb') return result where hcFlavor = flagToMaybe projectConfigHcFlavor hcPath = flagToMaybe projectConfigHcPath hcPkg = flagToMaybe projectConfigHcPkg progdb = userSpecifyPaths (Map.toList (getMapLast packageConfigProgramPaths)) . userSpecifyArgss (Map.toList (getMapMappend packageConfigProgramArgs)) . modifyProgramSearchPath (++ [ ProgramSearchPathDir dir | dir <- fromNubList packageConfigProgramPathExtra ]) $ defaultProgramDb -- Configuring other programs. -- -- Having configred the compiler, now we configure all the remaining -- programs. This is to check we can find them, and to monitor them for -- changes. -- -- TODO: [required eventually] we don't actually do this yet. -- -- We rely on the fact that the previous phase added the program config for -- all local packages, but that all the programs configured so far are the -- compiler program or related util programs. -- phaseConfigurePrograms :: ProjectConfig -> (Compiler, Platform, ProgramDb) -> Rebuild () phaseConfigurePrograms projectConfig (_, _, compilerprogdb) = do -- Users are allowed to specify program locations independently for -- each package (e.g. to use a particular version of a pre-processor -- for some packages). However they cannot do this for the compiler -- itself as that's just not going to work. So we check for this. liftIO $ checkBadPerPackageCompilerPaths (configuredPrograms compilerprogdb) (getMapMappend (projectConfigSpecificPackage projectConfig)) --TODO: [required eventually] find/configure other programs that the -- user specifies. --TODO: [required eventually] find/configure all build-tools -- but note that some of them may be built as part of the plan. -- Run the solver to get the initial install plan. -- This is expensive so we cache it independently. -- phaseRunSolver :: ProjectConfig -> (Compiler, Platform, ProgramDb) -> [UnresolvedSourcePackage] -> Rebuild (SolverInstallPlan, PkgConfigDb) phaseRunSolver projectConfig@ProjectConfig { projectConfigShared, projectConfigBuildOnly } (compiler, platform, progdb) localPackages = rerunIfChanged verbosity fileMonitorSolverPlan (solverSettings, localPackages, localPackagesEnabledStanzas, compiler, platform, programDbSignature progdb) $ do installedPkgIndex <- getInstalledPackages verbosity compiler progdb platform corePackageDbs sourcePkgDb <- getSourcePackages verbosity withRepoCtx (solverSettingIndexState solverSettings) pkgConfigDB <- getPkgConfigDb verbosity progdb --TODO: [code cleanup] it'd be better if the Compiler contained the -- ConfiguredPrograms that it needs, rather than relying on the progdb -- since we don't need to depend on all the programs here, just the -- ones relevant for the compiler. liftIO $ do solver <- chooseSolver verbosity (solverSettingSolver solverSettings) (compilerInfo compiler) notice verbosity "Resolving dependencies..." plan <- foldProgress logMsg (die' verbosity) return $ planPackages verbosity compiler platform solver solverSettings installedPkgIndex sourcePkgDb pkgConfigDB localPackages localPackagesEnabledStanzas return (plan, pkgConfigDB) where corePackageDbs = [GlobalPackageDB] withRepoCtx = projectConfigWithSolverRepoContext verbosity projectConfigShared projectConfigBuildOnly solverSettings = resolveSolverSettings projectConfig logMsg message rest = debugNoWrap verbosity message >> rest localPackagesEnabledStanzas = Map.fromList [ (pkgname, stanzas) | pkg <- localPackages , let pkgname = packageName pkg testsEnabled = lookupLocalPackageConfig packageConfigTests projectConfig pkgname benchmarksEnabled = lookupLocalPackageConfig packageConfigBenchmarks projectConfig pkgname stanzas = Map.fromList $ [ (TestStanzas, enabled) | enabled <- flagToList testsEnabled ] ++ [ (BenchStanzas , enabled) | enabled <- flagToList benchmarksEnabled ] ] -- Elaborate the solver's install plan to get a fully detailed plan. This -- version of the plan has the final nix-style hashed ids. -- phaseElaboratePlan :: ProjectConfig -> (Compiler, Platform, ProgramDb) -> PkgConfigDb -> SolverInstallPlan -> [SourcePackage loc] -> Rebuild ( ElaboratedInstallPlan , ElaboratedSharedConfig ) phaseElaboratePlan ProjectConfig { projectConfigShared, projectConfigLocalPackages, projectConfigSpecificPackage, projectConfigBuildOnly } (compiler, platform, progdb) pkgConfigDB solverPlan localPackages = do liftIO $ debug verbosity "Elaborating the install plan..." sourcePackageHashes <- rerunIfChanged verbosity fileMonitorSourceHashes (packageLocationsSignature solverPlan) $ getPackageSourceHashes verbosity withRepoCtx solverPlan defaultInstallDirs <- liftIO $ userInstallDirTemplates compiler (elaboratedPlan, elaboratedShared) <- liftIO . runLogProgress verbosity $ elaborateInstallPlan verbosity platform compiler progdb pkgConfigDB distDirLayout cabalStoreDirLayout solverPlan localPackages sourcePackageHashes defaultInstallDirs projectConfigShared projectConfigLocalPackages (getMapMappend projectConfigSpecificPackage) let instantiatedPlan = instantiateInstallPlan elaboratedPlan liftIO $ debugNoWrap verbosity (InstallPlan.showInstallPlan instantiatedPlan) return (instantiatedPlan, elaboratedShared) where withRepoCtx = projectConfigWithSolverRepoContext verbosity projectConfigShared projectConfigBuildOnly -- Update the files we maintain that reflect our current build environment. -- In particular we maintain a JSON representation of the elaborated -- install plan (but not the improved plan since that reflects the state -- of the build rather than just the input environment). -- phaseMaintainPlanOutputs :: ElaboratedInstallPlan -> ElaboratedSharedConfig -> Rebuild () phaseMaintainPlanOutputs elaboratedPlan elaboratedShared = liftIO $ do debug verbosity "Updating plan.json" writePlanExternalRepresentation distDirLayout elaboratedPlan elaboratedShared -- Improve the elaborated install plan. The elaborated plan consists -- mostly of source packages (with full nix-style hashed ids). Where -- corresponding installed packages already exist in the store, replace -- them in the plan. -- -- Note that we do monitor the store's package db here, so we will redo -- this improvement phase when the db changes -- including as a result of -- executing a plan and installing things. -- phaseImprovePlan :: ElaboratedInstallPlan -> ElaboratedSharedConfig -> Rebuild ElaboratedInstallPlan phaseImprovePlan elaboratedPlan elaboratedShared = do liftIO $ debug verbosity "Improving the install plan..." storePkgIdSet <- getStoreEntries cabalStoreDirLayout compid let improvedPlan = improveInstallPlanWithInstalledPackages storePkgIdSet elaboratedPlan liftIO $ debugNoWrap verbosity (InstallPlan.showInstallPlan improvedPlan) -- TODO: [nice to have] having checked which packages from the store -- we're using, it may be sensible to sanity check those packages -- by loading up the compiler package db and checking everything -- matches up as expected, e.g. no dangling deps, files deleted. return improvedPlan where compid = compilerId (pkgConfigCompiler elaboratedShared) programsMonitorFiles :: ProgramDb -> [MonitorFilePath] programsMonitorFiles progdb = [ monitor | prog <- configuredPrograms progdb , monitor <- monitorFileSearchPath (programMonitorFiles prog) (programPath prog) ] -- | Select the bits of a 'ProgramDb' to monitor for value changes. -- Use 'programsMonitorFiles' for the files to monitor. -- programDbSignature :: ProgramDb -> [ConfiguredProgram] programDbSignature progdb = [ prog { programMonitorFiles = [] , programOverrideEnv = filter ((/="PATH") . fst) (programOverrideEnv prog) } | prog <- configuredPrograms progdb ] getInstalledPackages :: Verbosity -> Compiler -> ProgramDb -> Platform -> PackageDBStack -> Rebuild InstalledPackageIndex getInstalledPackages verbosity compiler progdb platform packagedbs = do monitorFiles . map monitorFileOrDirectory =<< liftIO (IndexUtils.getInstalledPackagesMonitorFiles verbosity compiler packagedbs progdb platform) liftIO $ IndexUtils.getInstalledPackages verbosity compiler packagedbs progdb {- --TODO: [nice to have] use this but for sanity / consistency checking getPackageDBContents :: Verbosity -> Compiler -> ProgramDb -> Platform -> PackageDB -> Rebuild InstalledPackageIndex getPackageDBContents verbosity compiler progdb platform packagedb = do monitorFiles . map monitorFileOrDirectory =<< liftIO (IndexUtils.getInstalledPackagesMonitorFiles verbosity compiler [packagedb] progdb platform) liftIO $ do createPackageDBIfMissing verbosity compiler progdb packagedb Cabal.getPackageDBContents verbosity compiler packagedb progdb -} getSourcePackages :: Verbosity -> (forall a. (RepoContext -> IO a) -> IO a) -> Maybe IndexUtils.IndexState -> Rebuild SourcePackageDb getSourcePackages verbosity withRepoCtx idxState = do (sourcePkgDb, repos) <- liftIO $ withRepoCtx $ \repoctx -> do sourcePkgDb <- IndexUtils.getSourcePackagesAtIndexState verbosity repoctx idxState return (sourcePkgDb, repoContextRepos repoctx) mapM_ needIfExists . IndexUtils.getSourcePackagesMonitorFiles $ repos return sourcePkgDb getPkgConfigDb :: Verbosity -> ProgramDb -> Rebuild PkgConfigDb getPkgConfigDb verbosity progdb = do dirs <- liftIO $ getPkgConfigDbDirs verbosity progdb -- Just monitor the dirs so we'll notice new .pc files. -- Alternatively we could monitor all the .pc files too. mapM_ monitorDirectoryStatus dirs liftIO $ readPkgConfigDb verbosity progdb -- | Select the config values to monitor for changes package source hashes. packageLocationsSignature :: SolverInstallPlan -> [(PackageId, PackageLocation (Maybe FilePath))] packageLocationsSignature solverPlan = [ (packageId pkg, packageSource pkg) | SolverInstallPlan.Configured (SolverPackage { solverPkgSource = pkg}) <- SolverInstallPlan.toList solverPlan ] -- | Get the 'HashValue' for all the source packages where we use hashes, -- and download any packages required to do so. -- -- Note that we don't get hashes for local unpacked packages. -- getPackageSourceHashes :: Verbosity -> (forall a. (RepoContext -> IO a) -> IO a) -> SolverInstallPlan -> Rebuild (Map PackageId PackageSourceHash) getPackageSourceHashes verbosity withRepoCtx solverPlan = do -- Determine if and where to get the package's source hash from. -- let allPkgLocations :: [(PackageId, PackageLocation (Maybe FilePath))] allPkgLocations = [ (packageId pkg, packageSource pkg) | SolverInstallPlan.Configured (SolverPackage { solverPkgSource = pkg}) <- SolverInstallPlan.toList solverPlan ] -- Tarballs that were local in the first place. -- We'll hash these tarball files directly. localTarballPkgs :: [(PackageId, FilePath)] localTarballPkgs = [ (pkgid, tarball) | (pkgid, LocalTarballPackage tarball) <- allPkgLocations ] -- Tarballs from remote URLs. We must have downloaded these already -- (since we extracted the .cabal file earlier) --TODO: [required eventually] finish remote tarball functionality -- allRemoteTarballPkgs = -- [ (pkgid, ) -- | (pkgid, RemoteTarballPackage ) <- allPkgLocations ] -- Tarballs from repositories, either where the repository provides -- hashes as part of the repo metadata, or where we will have to -- download and hash the tarball. repoTarballPkgsWithMetadata :: [(PackageId, Repo)] repoTarballPkgsWithoutMetadata :: [(PackageId, Repo)] (repoTarballPkgsWithMetadata, repoTarballPkgsWithoutMetadata) = partitionEithers [ case repo of RepoSecure{} -> Left (pkgid, repo) _ -> Right (pkgid, repo) | (pkgid, RepoTarballPackage repo _ _) <- allPkgLocations ] -- For tarballs from repos that do not have hashes available we now have -- to check if the packages were downloaded already. -- (repoTarballPkgsToDownload, repoTarballPkgsDownloaded) <- fmap partitionEithers $ liftIO $ sequence [ do mtarball <- checkRepoTarballFetched repo pkgid case mtarball of Nothing -> return (Left (pkgid, repo)) Just tarball -> return (Right (pkgid, tarball)) | (pkgid, repo) <- repoTarballPkgsWithoutMetadata ] (hashesFromRepoMetadata, repoTarballPkgsNewlyDownloaded) <- -- Avoid having to initialise the repository (ie 'withRepoCtx') if we -- don't have to. (The main cost is configuring the http client.) if null repoTarballPkgsToDownload && null repoTarballPkgsWithMetadata then return (Map.empty, []) else liftIO $ withRepoCtx $ \repoctx -> do -- For tarballs from repos that do have hashes available as part of the -- repo metadata we now load up the index for each repo and retrieve -- the hashes for the packages -- hashesFromRepoMetadata <- Sec.uncheckClientErrors $ --TODO: [code cleanup] wrap in our own exceptions fmap (Map.fromList . concat) $ sequence -- Reading the repo index is expensive so we group the packages by repo [ repoContextWithSecureRepo repoctx repo $ \secureRepo -> Sec.withIndex secureRepo $ \repoIndex -> sequence [ do hash <- Sec.trusted <$> -- strip off Trusted tag Sec.indexLookupHash repoIndex pkgid -- Note that hackage-security currently uses SHA256 -- but this API could in principle give us some other -- choice in future. return (pkgid, hashFromTUF hash) | pkgid <- pkgids ] | (repo, pkgids) <- map (\grp@((_,repo):_) -> (repo, map fst grp)) . groupBy ((==) `on` (remoteRepoName . repoRemote . snd)) . sortBy (compare `on` (remoteRepoName . repoRemote . snd)) $ repoTarballPkgsWithMetadata ] -- For tarballs from repos that do not have hashes available, download -- the ones we previously determined we need. -- repoTarballPkgsNewlyDownloaded <- sequence [ do tarball <- fetchRepoTarball verbosity repoctx repo pkgid return (pkgid, tarball) | (pkgid, repo) <- repoTarballPkgsToDownload ] return (hashesFromRepoMetadata, repoTarballPkgsNewlyDownloaded) -- Hash tarball files for packages where we have to do that. This includes -- tarballs that were local in the first place, plus tarballs from repos, -- either previously cached or freshly downloaded. -- let allTarballFilePkgs :: [(PackageId, FilePath)] allTarballFilePkgs = localTarballPkgs ++ repoTarballPkgsDownloaded ++ repoTarballPkgsNewlyDownloaded hashesFromTarballFiles <- liftIO $ fmap Map.fromList $ sequence [ do srchash <- readFileHashValue tarball return (pkgid, srchash) | (pkgid, tarball) <- allTarballFilePkgs ] monitorFiles [ monitorFile tarball | (_pkgid, tarball) <- allTarballFilePkgs ] -- Return the combination return $! hashesFromRepoMetadata <> hashesFromTarballFiles -- ------------------------------------------------------------ -- * Installation planning -- ------------------------------------------------------------ planPackages :: Verbosity -> Compiler -> Platform -> Solver -> SolverSettings -> InstalledPackageIndex -> SourcePackageDb -> PkgConfigDb -> [UnresolvedSourcePackage] -> Map PackageName (Map OptionalStanza Bool) -> Progress String String SolverInstallPlan planPackages verbosity comp platform solver SolverSettings{..} installedPkgIndex sourcePkgDb pkgConfigDB localPackages pkgStanzasEnable = resolveDependencies platform (compilerInfo comp) pkgConfigDB solver resolverParams where --TODO: [nice to have] disable multiple instances restriction in the solver, but then -- make sure we can cope with that in the output. resolverParams = setMaxBackjumps solverSettingMaxBackjumps . setIndependentGoals solverSettingIndependentGoals . setReorderGoals solverSettingReorderGoals . setCountConflicts solverSettingCountConflicts --TODO: [required eventually] should only be configurable for custom installs -- . setAvoidReinstalls solverSettingAvoidReinstalls --TODO: [required eventually] should only be configurable for custom installs -- . setShadowPkgs solverSettingShadowPkgs . setStrongFlags solverSettingStrongFlags . setAllowBootLibInstalls solverSettingAllowBootLibInstalls . setSolverVerbosity verbosity --TODO: [required eventually] decide if we need to prefer installed for -- global packages, or prefer latest even for global packages. Perhaps -- should be configurable but with a different name than "upgrade-dependencies". . setPreferenceDefault PreferLatestForSelected {-(if solverSettingUpgradeDeps then PreferAllLatest else PreferLatestForSelected)-} . removeLowerBounds solverSettingAllowOlder . removeUpperBounds solverSettingAllowNewer . addDefaultSetupDependencies (defaultSetupDeps comp platform . PD.packageDescription . packageDescription) . addSetupCabalMinVersionConstraint (mkVersion [1,20]) -- While we can talk to older Cabal versions (we need to be able to -- do so for custom Setup scripts that require older Cabal lib -- versions), we have problems talking to some older versions that -- don't support certain features. -- -- For example, Cabal-1.16 and older do not know about build targets. -- Even worse, 1.18 and older only supported the --constraint flag -- with source package ids, not --dependency with installed package -- ids. That is bad because we cannot reliably select the right -- dependencies in the presence of multiple instances (i.e. the -- store). See issue #3932. So we require Cabal 1.20 as a minimum. . addPreferences -- preferences from the config file or command line [ PackageVersionPreference name ver | Dependency name ver <- solverSettingPreferences ] . addConstraints -- version constraints from the config file or command line [ LabeledPackageConstraint (userToPackageConstraint pc) src | (pc, src) <- solverSettingConstraints ] . addPreferences -- enable stanza preference where the user did not specify [ PackageStanzasPreference pkgname stanzas | pkg <- localPackages , let pkgname = packageName pkg stanzaM = Map.findWithDefault Map.empty pkgname pkgStanzasEnable stanzas = [ stanza | stanza <- [minBound..maxBound] , Map.lookup stanza stanzaM == Nothing ] , not (null stanzas) ] . addConstraints -- enable stanza constraints where the user asked to enable [ LabeledPackageConstraint (PackageConstraint (scopeToplevel pkgname) (PackagePropertyStanzas stanzas)) ConstraintSourceConfigFlagOrTarget | pkg <- localPackages , let pkgname = packageName pkg stanzaM = Map.findWithDefault Map.empty pkgname pkgStanzasEnable stanzas = [ stanza | stanza <- [minBound..maxBound] , Map.lookup stanza stanzaM == Just True ] , not (null stanzas) ] . addConstraints --TODO: [nice to have] should have checked at some point that the -- package in question actually has these flags. [ LabeledPackageConstraint (PackageConstraint (scopeToplevel pkgname) (PackagePropertyFlags flags)) ConstraintSourceConfigFlagOrTarget | (pkgname, flags) <- Map.toList solverSettingFlagAssignments ] . addConstraints --TODO: [nice to have] we have user-supplied flags for unspecified -- local packages (as well as specific per-package flags). For the -- former we just apply all these flags to all local targets which -- is silly. We should check if the flags are appropriate. [ LabeledPackageConstraint (PackageConstraint (scopeToplevel pkgname) (PackagePropertyFlags flags)) ConstraintSourceConfigFlagOrTarget | let flags = solverSettingFlagAssignment , not (null flags) , pkg <- localPackages , let pkgname = packageName pkg ] $ stdResolverParams stdResolverParams = -- Note: we don't use the standardInstallPolicy here, since that uses -- its own addDefaultSetupDependencies that is not appropriate for us. basicInstallPolicy installedPkgIndex sourcePkgDb (map SpecificSourcePackage localPackages) ------------------------------------------------------------------------------ -- * Install plan post-processing ------------------------------------------------------------------------------ -- This phase goes from the InstallPlan we get from the solver and has to -- make an elaborated install plan. -- -- We go in two steps: -- -- 1. elaborate all the source packages that the solver has chosen. -- 2. swap source packages for pre-existing installed packages wherever -- possible. -- -- We do it in this order, elaborating and then replacing, because the easiest -- way to calculate the installed package ids used for the replacement step is -- from the elaborated configuration for each package. ------------------------------------------------------------------------------ -- * Install plan elaboration ------------------------------------------------------------------------------ -- Note [SolverId to ConfiguredId] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Dependency solving is a per package affair, so after we're done, we -- end up with 'SolverInstallPlan' that records in 'solverPkgLibDeps' -- and 'solverPkgExeDeps' what packages provide the libraries and executables -- needed by each component of the package (phew!) For example, if I have -- -- library -- build-depends: lib -- build-tool-depends: pkg:exe1 -- build-tools: alex -- -- After dependency solving, I find out that this library component has -- library dependencies on lib-0.2, and executable dependencies on pkg-0.1 -- and alex-0.3 (other components of the package may have different -- dependencies). Note that I've "lost" the knowledge that I depend -- *specifically* on the exe1 executable from pkg. -- -- So, we have a this graph of packages, and we need to transform it into -- a graph of components which we are actually going to build. In particular: -- -- NODE changes from PACKAGE (SolverPackage) to COMPONENTS (ElaboratedConfiguredPackage) -- EDGE changes from PACKAGE DEP (SolverId) to COMPONENT DEPS (ConfiguredId) -- -- In both cases, what was previously a single node/edge may turn into multiple -- nodes/edges. Multiple components, because there may be multiple components -- in a package; multiple component deps, because we may depend upon multiple -- executables from the same package (and maybe, some day, multiple libraries -- from the same package.) -- -- Let's talk about how to do this transformation. Naively, we might consider -- just processing each package, converting it into (zero or) one or more -- components. But we also have to update the edges; this leads to -- two complications: -- -- 1. We don't know what the ConfiguredId of a component is until -- we've configured it, but we cannot configure a component unless -- we know the ConfiguredId of all its dependencies. Thus, we must -- process the 'SolverInstallPlan' in topological order. -- -- 2. When we process a package, we know the SolverIds of its -- dependencies, but we have to do some work to turn these into -- ConfiguredIds. For example, in the case of build-tool-depends, the -- SolverId isn't enough to uniquely determine the ConfiguredId we should -- elaborate to: we have to look at the executable name attached to -- the package name in the package description to figure it out. -- At the same time, we NEED to use the SolverId, because there might -- be multiple versions of the same package in the build plan -- (due to setup dependencies); we can't just look up the package name -- from the package description. -- -- However, we do have the following INVARIANT: a component never directly -- depends on multiple versions of the same package. Thus, we can -- adopt the following strategy: -- -- * When a package is transformed into components, record -- a mapping from SolverId to ALL of the components -- which were elaborated. -- -- * When we look up an edge, we use our knowledge of the -- component name to *filter* the list of components into -- the ones we actually wanted to refer to. -- -- By the way, we can tell that SolverInstallPlan is not the "right" type -- because a SolverId cannot adequately represent all possible dependency -- solver states: we may need to record foo-0.1 multiple times in -- the solver install plan with different dependencies. The solver probably -- doesn't handle this correctly... but it should. The right way to solve -- this is to come up with something very much like a 'ConfiguredId', in that -- it incorporates the version choices of its dependencies, but less -- fine grained. Fortunately, this doesn't seem to have affected anyone, -- but it is good to watch out about. -- | Produce an elaborated install plan using the policy for local builds with -- a nix-style shared store. -- -- In theory should be able to make an elaborated install plan with a policy -- matching that of the classic @cabal install --user@ or @--global@ -- elaborateInstallPlan :: Verbosity -> Platform -> Compiler -> ProgramDb -> PkgConfigDb -> DistDirLayout -> StoreDirLayout -> SolverInstallPlan -> [SourcePackage loc] -> Map PackageId PackageSourceHash -> InstallDirs.InstallDirTemplates -> ProjectConfigShared -> PackageConfig -> Map PackageName PackageConfig -> LogProgress (ElaboratedInstallPlan, ElaboratedSharedConfig) elaborateInstallPlan verbosity platform compiler compilerprogdb pkgConfigDB distDirLayout@DistDirLayout{..} storeDirLayout@StoreDirLayout{storePackageDBStack} solverPlan localPackages sourcePackageHashes defaultInstallDirs sharedPackageConfig localPackagesConfig perPackageConfig = do x <- elaboratedInstallPlan return (x, elaboratedSharedConfig) where elaboratedSharedConfig = ElaboratedSharedConfig { pkgConfigPlatform = platform, pkgConfigCompiler = compiler, pkgConfigCompilerProgs = compilerprogdb } preexistingInstantiatedPkgs = Map.fromList (mapMaybe f (SolverInstallPlan.toList solverPlan)) where f (SolverInstallPlan.PreExisting inst) | let ipkg = instSolverPkgIPI inst , not (IPI.indefinite ipkg) = Just (IPI.installedUnitId ipkg, (FullUnitId (IPI.installedComponentId ipkg) (Map.fromList (IPI.instantiatedWith ipkg)))) f _ = Nothing elaboratedInstallPlan = flip InstallPlan.fromSolverInstallPlanWithProgress solverPlan $ \mapDep planpkg -> case planpkg of SolverInstallPlan.PreExisting pkg -> return [InstallPlan.PreExisting (instSolverPkgIPI pkg)] SolverInstallPlan.Configured pkg -> let inplace_doc | shouldBuildInplaceOnly pkg = text "inplace" | otherwise = Disp.empty in addProgressCtx (text "In the" <+> inplace_doc <+> text "package" <+> quotes (disp (packageId pkg))) $ map InstallPlan.Configured <$> elaborateSolverToComponents mapDep pkg -- NB: We don't INSTANTIATE packages at this point. That's -- a post-pass. This makes it simpler to compute dependencies. elaborateSolverToComponents :: (SolverId -> [ElaboratedPlanPackage]) -> SolverPackage UnresolvedPkgLoc -> LogProgress [ElaboratedConfiguredPackage] elaborateSolverToComponents mapDep spkg@(SolverPackage _ _ _ deps0 exe_deps0) = case mkComponentsGraph (elabEnabledSpec elab0) pd of Right g -> do let src_comps = componentsGraphToList g infoProgress $ hang (text "Component graph for" <+> disp pkgid <<>> colon) 4 (dispComponentsWithDeps src_comps) (_, comps) <- mapAccumM buildComponent (Map.empty, Map.empty, Map.empty) (map fst src_comps) let not_per_component_reasons = why_not_per_component src_comps if null not_per_component_reasons then return comps else do checkPerPackageOk comps not_per_component_reasons return [elaborateSolverToPackage mapDep spkg g $ comps ++ maybeToList setupComponent] Left cns -> dieProgress $ hang (text "Dependency cycle between the following components:") 4 (vcat (map (text . componentNameStanza) cns)) where -- You are eligible to per-component build if this list is empty why_not_per_component g = cuz_custom ++ cuz_spec ++ cuz_length ++ cuz_flag where cuz reason = [text reason] -- At this point in time, only non-Custom setup scripts -- are supported. Implementing per-component builds with -- Custom would require us to create a new 'ElabSetup' -- type, and teach all of the code paths how to handle it. -- Once you've implemented this, swap it for the code below. cuz_custom = case PD.buildType (elabPkgDescription elab0) of Nothing -> cuz "build-type is not specified" Just PD.Custom -> cuz "build-type is Custom" Just _ -> [] -- cabal-format versions prior to 1.8 have different build-depends semantics -- for now it's easier to just fallback to legacy-mode when specVersion < 1.8 -- see, https://github.com/haskell/cabal/issues/4121 cuz_spec | PD.specVersion pd >= mkVersion [1,8] = [] | otherwise = cuz "cabal-version is less than 1.8" -- In the odd corner case that a package has no components at all -- then keep it as a whole package, since otherwise it turns into -- 0 component graph nodes and effectively vanishes. We want to -- keep it around at least for error reporting purposes. cuz_length | length g > 0 = [] | otherwise = cuz "there are no buildable components" -- For ease of testing, we let per-component builds be toggled -- at the top level cuz_flag | fromFlagOrDefault True (projectConfigPerComponent sharedPackageConfig) = [] | otherwise = cuz "you passed --disable-per-component" -- | Sometimes a package may make use of features which are only -- supported in per-package mode. If this is the case, we should -- give an error when this occurs. checkPerPackageOk comps reasons = do let is_sublib (CSubLibName _) = True is_sublib _ = False when (any (matchElabPkg is_sublib) comps) $ dieProgress $ text "Internal libraries only supported with per-component builds." $$ text "Per-component builds were disabled because" <+> fsep (punctuate comma reasons) -- TODO: Maybe exclude Backpack too elab0 = elaborateSolverToCommon mapDep spkg pkgid = elabPkgSourceId elab0 pd = elabPkgDescription elab0 -- TODO: This is just a skeleton to get elaborateSolverToPackage -- working correctly -- TODO: When we actually support building these components, we -- have to add dependencies on this from all other components setupComponent :: Maybe ElaboratedConfiguredPackage setupComponent | fromMaybe PD.Custom (PD.buildType (elabPkgDescription elab0)) == PD.Custom = Just elab0 { elabModuleShape = emptyModuleShape, elabUnitId = notImpl "elabUnitId", elabComponentId = notImpl "elabComponentId", elabLinkedInstantiatedWith = Map.empty, elabInstallDirs = notImpl "elabInstallDirs", elabPkgOrComp = ElabComponent (ElaboratedComponent {..}) } | otherwise = Nothing where compSolverName = CD.ComponentSetup compComponentName = Nothing dep_pkgs = elaborateLibSolverId mapDep =<< CD.setupDeps deps0 compLibDependencies = map configuredId dep_pkgs compLinkedLibDependencies = notImpl "compLinkedLibDependencies" compOrderLibDependencies = notImpl "compOrderLibDependencies" -- Not supported: compExeDependencies = [] compExeDependencyPaths = [] compPkgConfigDependencies = [] notImpl f = error $ "Distribution.Client.ProjectPlanning.setupComponent: " ++ f ++ " not implemented yet" buildComponent :: (ConfiguredComponentMap, LinkedComponentMap, Map ComponentId FilePath) -> Cabal.Component -> LogProgress ((ConfiguredComponentMap, LinkedComponentMap, Map ComponentId FilePath), ElaboratedConfiguredPackage) buildComponent (cc_map, lc_map, exe_map) comp = addProgressCtx (text "In the stanza" <+> quotes (text (componentNameStanza cname))) $ do -- 1. Configure the component, but with a place holder ComponentId. cc0 <- toConfiguredComponent pd (error "Distribution.Client.ProjectPlanning.cc_cid: filled in later") (Map.unionWith Map.union external_cc_map cc_map) comp -- 2. Read out the dependencies from the ConfiguredComponent cc0 let compLibDependencies = -- Nub because includes can show up multiple times ordNub (map (annotatedIdToConfiguredId . ci_ann_id) (cc_includes cc0)) compExeDependencies = map annotatedIdToConfiguredId (cc_exe_deps cc0) compExeDependencyPaths = [ (annotatedIdToConfiguredId aid', path) | aid' <- cc_exe_deps cc0 , Just path <- [Map.lookup (ann_id aid') exe_map1]] elab_comp = ElaboratedComponent {..} -- 3. Construct a preliminary ElaboratedConfiguredPackage, -- and use this to compute the component ID. Fix up cc_id -- correctly. let elab1 = elab0 { elabPkgOrComp = ElabComponent $ elab_comp } cid = case elabBuildStyle elab0 of BuildInplaceOnly -> mkComponentId $ display pkgid ++ "-inplace" ++ (case Cabal.componentNameString cname of Nothing -> "" Just s -> "-" ++ display s) BuildAndInstall -> hashedInstalledPackageId (packageHashInputs elaboratedSharedConfig elab1) -- knot tied cc = cc0 { cc_ann_id = fmap (const cid) (cc_ann_id cc0) } infoProgress $ dispConfiguredComponent cc -- 4. Perform mix-in linking let lookup_uid def_uid = case Map.lookup (unDefUnitId def_uid) preexistingInstantiatedPkgs of Just full -> full Nothing -> error ("lookup_uid: " ++ display def_uid) lc <- toLinkedComponent verbosity lookup_uid (elabPkgSourceId elab0) (Map.union external_lc_map lc_map) cc infoProgress $ dispLinkedComponent lc -- NB: elab is setup to be the correct form for an -- indefinite library, or a definite library with no holes. -- We will modify it in 'instantiateInstallPlan' to handle -- instantiated packages. -- 5. Construct the final ElaboratedConfiguredPackage let elab = elab1 { elabModuleShape = lc_shape lc, elabUnitId = abstractUnitId (lc_uid lc), elabComponentId = lc_cid lc, elabLinkedInstantiatedWith = Map.fromList (lc_insts lc), elabPkgOrComp = ElabComponent $ elab_comp { compLinkedLibDependencies = ordNub (map ci_id (lc_includes lc)), compOrderLibDependencies = ordNub (map (abstractUnitId . ci_id) (lc_includes lc ++ lc_sig_includes lc)) }, elabInstallDirs = install_dirs cid } -- 6. Construct the updated local maps let cc_map' = extendConfiguredComponentMap cc cc_map lc_map' = extendLinkedComponentMap lc lc_map exe_map' = Map.insert cid (inplace_bin_dir elab) exe_map return ((cc_map', lc_map', exe_map'), elab) where compLinkedLibDependencies = error "buildComponent: compLinkedLibDependencies" compOrderLibDependencies = error "buildComponent: compOrderLibDependencies" cname = Cabal.componentName comp compComponentName = Just cname compSolverName = CD.componentNameToComponent cname -- NB: compLinkedLibDependencies and -- compOrderLibDependencies are defined when we define -- 'elab'. external_lib_dep_sids = CD.select (== compSolverName) deps0 external_exe_dep_sids = CD.select (== compSolverName) exe_deps0 -- TODO: The fact that lib SolverIds and exe SolverIds are -- jammed together here means that we're losing information! external_dep_sids = external_lib_dep_sids ++ external_exe_dep_sids external_dep_pkgs = concatMap mapDep external_dep_sids external_exe_map = Map.fromList $ [ (getComponentId pkg, path) | pkg <- external_dep_pkgs , Just path <- [planPackageExePath pkg] ] exe_map1 = Map.union external_exe_map exe_map external_cc_map = Map.fromListWith Map.union $ map mkCCMapping external_dep_pkgs external_lc_map = Map.fromList (map mkShapeMapping external_dep_pkgs) compPkgConfigDependencies = [ (pn, fromMaybe (error $ "compPkgConfigDependencies: impossible! " ++ display pn ++ " from " ++ display (elabPkgSourceId elab0)) (pkgConfigDbPkgVersion pkgConfigDB pn)) | PkgconfigDependency pn _ <- PD.pkgconfigDepends (Cabal.componentBuildInfo comp) ] install_dirs cid | shouldBuildInplaceOnly spkg -- use the ordinary default install dirs = (InstallDirs.absoluteInstallDirs pkgid (newSimpleUnitId cid) (compilerInfo compiler) InstallDirs.NoCopyDest platform defaultInstallDirs) { -- absoluteInstallDirs sets these as 'undefined' but we have -- to use them as "Setup.hs configure" args InstallDirs.libsubdir = "", InstallDirs.libexecsubdir = "", InstallDirs.datasubdir = "" } | otherwise -- use special simplified install dirs = storePackageInstallDirs storeDirLayout (compilerId compiler) cid inplace_bin_dir elab = binDirectoryFor distDirLayout elaboratedSharedConfig elab $ case Cabal.componentNameString cname of Just n -> display n Nothing -> "" -- | Given a 'SolverId' referencing a dependency on a library, return -- the 'ElaboratedPlanPackage' corresponding to the library. This -- returns at most one result. elaborateLibSolverId :: (SolverId -> [ElaboratedPlanPackage]) -> SolverId -> [ElaboratedPlanPackage] elaborateLibSolverId mapDep = filter (matchPlanPkg (== CLibName)) . mapDep -- | Given an 'ElaboratedPlanPackage', return the path to where the -- executable that this package represents would be installed. planPackageExePath :: ElaboratedPlanPackage -> Maybe FilePath planPackageExePath = -- Pre-existing executables are assumed to be in PATH -- already. In fact, this should be impossible. InstallPlan.foldPlanPackage (const Nothing) $ \elab -> Just $ binDirectoryFor distDirLayout elaboratedSharedConfig elab $ case elabPkgOrComp elab of ElabPackage _ -> "" ElabComponent comp -> case fmap Cabal.componentNameString (compComponentName comp) of Just (Just n) -> display n _ -> "" elaborateSolverToPackage :: (SolverId -> [ElaboratedPlanPackage]) -> SolverPackage UnresolvedPkgLoc -> ComponentsGraph -> [ElaboratedConfiguredPackage] -> ElaboratedConfiguredPackage elaborateSolverToPackage mapDep pkg@(SolverPackage (SourcePackage pkgid _gdesc _srcloc _descOverride) _flags _stanzas _deps0 _exe_deps0) compGraph comps = -- Knot tying: the final elab includes the -- pkgInstalledId, which is calculated by hashing many -- of the other fields of the elaboratedPackage. elab where elab0@ElaboratedConfiguredPackage{..} = elaborateSolverToCommon mapDep pkg elab = elab0 { elabUnitId = newSimpleUnitId pkgInstalledId, elabComponentId = pkgInstalledId, elabLinkedInstantiatedWith = Map.empty, elabInstallDirs = install_dirs, elabPkgOrComp = ElabPackage $ ElaboratedPackage {..}, elabModuleShape = modShape } modShape = case find (matchElabPkg (== CLibName)) comps of Nothing -> emptyModuleShape Just e -> Ty.elabModuleShape e pkgInstalledId | shouldBuildInplaceOnly pkg = mkComponentId (display pkgid ++ "-inplace") | otherwise = assert (isJust elabPkgSourceHash) $ hashedInstalledPackageId (packageHashInputs elaboratedSharedConfig elab) -- recursive use of elab | otherwise = error $ "elaborateInstallPlan: non-inplace package " ++ " is missing a source hash: " ++ display pkgid -- Need to filter out internal dependencies, because they don't -- correspond to anything real anymore. isExt confid = confSrcId confid /= pkgid filterExt = filter isExt filterExt' = filter (isExt . fst) pkgLibDependencies = buildComponentDeps (filterExt . compLibDependencies) pkgExeDependencies = buildComponentDeps (filterExt . compExeDependencies) pkgExeDependencyPaths = buildComponentDeps (filterExt' . compExeDependencyPaths) -- TODO: Why is this flat? pkgPkgConfigDependencies = CD.flatDeps $ buildComponentDeps compPkgConfigDependencies pkgDependsOnSelfLib = CD.fromList [ (CD.componentNameToComponent cn, [()]) | Graph.N _ cn _ <- fromMaybe [] mb_closure ] where mb_closure = Graph.revClosure compGraph [ k | k <- Graph.keys compGraph, is_lib k ] is_lib CLibName = True -- NB: this case should not occur, because sub-libraries -- are not supported without per-component builds is_lib (CSubLibName _) = True is_lib _ = False buildComponentDeps f = CD.fromList [ (compSolverName comp, f comp) | ElaboratedConfiguredPackage{ elabPkgOrComp = ElabComponent comp } <- comps ] -- Filled in later pkgStanzasEnabled = Set.empty install_dirs | shouldBuildInplaceOnly pkg -- use the ordinary default install dirs = (InstallDirs.absoluteInstallDirs pkgid (newSimpleUnitId pkgInstalledId) (compilerInfo compiler) InstallDirs.NoCopyDest platform defaultInstallDirs) { -- absoluteInstallDirs sets these as 'undefined' but we have to -- use them as "Setup.hs configure" args InstallDirs.libsubdir = "", InstallDirs.libexecsubdir = "", InstallDirs.datasubdir = "" } | otherwise -- use special simplified install dirs = storePackageInstallDirs storeDirLayout (compilerId compiler) pkgInstalledId elaborateSolverToCommon :: (SolverId -> [ElaboratedPlanPackage]) -> SolverPackage UnresolvedPkgLoc -> ElaboratedConfiguredPackage elaborateSolverToCommon mapDep pkg@(SolverPackage (SourcePackage pkgid gdesc srcloc descOverride) flags stanzas deps0 _exe_deps0) = elaboratedPackage where elaboratedPackage = ElaboratedConfiguredPackage {..} -- These get filled in later elabUnitId = error "elaborateSolverToCommon: elabUnitId" elabComponentId = error "elaborateSolverToCommon: elabComponentId" elabInstantiatedWith = Map.empty elabLinkedInstantiatedWith = error "elaborateSolverToCommon: elabLinkedInstantiatedWith" elabPkgOrComp = error "elaborateSolverToCommon: elabPkgOrComp" elabInstallDirs = error "elaborateSolverToCommon: elabInstallDirs" elabModuleShape = error "elaborateSolverToCommon: elabModuleShape" elabIsCanonical = True elabPkgSourceId = pkgid elabPkgDescription = let Right (desc, _) = PD.finalizePD flags elabEnabledSpec (const True) platform (compilerInfo compiler) [] gdesc in desc elabFlagAssignment = flags elabFlagDefaults = [ (Cabal.flagName flag, Cabal.flagDefault flag) | flag <- PD.genPackageFlags gdesc ] elabEnabledSpec = enableStanzas stanzas elabStanzasAvailable = Set.fromList stanzas elabStanzasRequested = -- NB: even if a package stanza is requested, if the package -- doesn't actually have any of that stanza we omit it from -- the request, to ensure that we don't decide that this -- package needs to be rebuilt. (It needs to be done here, -- because the ElaboratedConfiguredPackage is where we test -- whether or not there have been changes.) Map.fromList $ [ (TestStanzas, v) | v <- maybeToList tests , _ <- PD.testSuites elabPkgDescription ] ++ [ (BenchStanzas, v) | v <- maybeToList benchmarks , _ <- PD.benchmarks elabPkgDescription ] where tests, benchmarks :: Maybe Bool tests = perPkgOptionMaybe pkgid packageConfigTests benchmarks = perPkgOptionMaybe pkgid packageConfigBenchmarks -- This is a placeholder which will get updated by 'pruneInstallPlanPass1' -- and 'pruneInstallPlanPass2'. We can't populate it here -- because whether or not tests/benchmarks should be enabled -- is heuristically calculated based on whether or not the -- dependencies of the test suite have already been installed, -- but this function doesn't know what is installed (since -- we haven't improved the plan yet), so we do it in another pass. -- Check the comments of those functions for more details. elabBuildTargets = [] elabTestTargets = [] elabBenchTargets = [] elabReplTarget = Nothing elabBuildHaddocks = False elabPkgSourceLocation = srcloc elabPkgSourceHash = Map.lookup pkgid sourcePackageHashes elabLocalToProject = isLocalToProject pkg elabBuildStyle = if shouldBuildInplaceOnly pkg then BuildInplaceOnly else BuildAndInstall elabBuildPackageDBStack = buildAndRegisterDbs elabRegisterPackageDBStack = buildAndRegisterDbs elabSetupScriptStyle = packageSetupScriptStyle elabPkgDescription -- Computing the deps here is a little awful deps = fmap (concatMap (elaborateLibSolverId mapDep)) deps0 elabSetupScriptCliVersion = packageSetupScriptSpecVersion elabSetupScriptStyle elabPkgDescription deps elabSetupPackageDBStack = buildAndRegisterDbs buildAndRegisterDbs | shouldBuildInplaceOnly pkg = inplacePackageDbs | otherwise = storePackageDbs elabPkgDescriptionOverride = descOverride elabVanillaLib = perPkgOptionFlag pkgid True packageConfigVanillaLib --TODO: [required feature]: also needs to be handled recursively elabSharedLib = pkgid `Set.member` pkgsUseSharedLibrary elabStaticLib = perPkgOptionFlag pkgid False packageConfigStaticLib elabDynExe = perPkgOptionFlag pkgid False packageConfigDynExe elabGHCiLib = perPkgOptionFlag pkgid False packageConfigGHCiLib --TODO: [required feature] needs to default to enabled on windows still elabProfExe = perPkgOptionFlag pkgid False packageConfigProf elabProfLib = pkgid `Set.member` pkgsUseProfilingLibrary (elabProfExeDetail, elabProfLibDetail) = perPkgOptionLibExeFlag pkgid ProfDetailDefault packageConfigProfDetail packageConfigProfLibDetail elabCoverage = perPkgOptionFlag pkgid False packageConfigCoverage elabOptimization = perPkgOptionFlag pkgid NormalOptimisation packageConfigOptimization elabSplitObjs = perPkgOptionFlag pkgid False packageConfigSplitObjs elabStripLibs = perPkgOptionFlag pkgid False packageConfigStripLibs elabStripExes = perPkgOptionFlag pkgid False packageConfigStripExes elabDebugInfo = perPkgOptionFlag pkgid NoDebugInfo packageConfigDebugInfo -- Combine the configured compiler prog settings with the user-supplied -- config. For the compiler progs any user-supplied config was taken -- into account earlier when configuring the compiler so its ok that -- our configured settings for the compiler override the user-supplied -- config here. elabProgramPaths = Map.fromList [ (programId prog, programPath prog) | prog <- configuredPrograms compilerprogdb ] <> perPkgOptionMapLast pkgid packageConfigProgramPaths elabProgramArgs = Map.fromList [ (programId prog, args) | prog <- configuredPrograms compilerprogdb , let args = programOverrideArgs prog , not (null args) ] <> perPkgOptionMapMappend pkgid packageConfigProgramArgs elabProgramPathExtra = perPkgOptionNubList pkgid packageConfigProgramPathExtra elabConfigureScriptArgs = perPkgOptionList pkgid packageConfigConfigureArgs elabExtraLibDirs = perPkgOptionList pkgid packageConfigExtraLibDirs elabExtraFrameworkDirs = perPkgOptionList pkgid packageConfigExtraFrameworkDirs elabExtraIncludeDirs = perPkgOptionList pkgid packageConfigExtraIncludeDirs elabProgPrefix = perPkgOptionMaybe pkgid packageConfigProgPrefix elabProgSuffix = perPkgOptionMaybe pkgid packageConfigProgSuffix elabHaddockHoogle = perPkgOptionFlag pkgid False packageConfigHaddockHoogle elabHaddockHtml = perPkgOptionFlag pkgid False packageConfigHaddockHtml elabHaddockHtmlLocation = perPkgOptionMaybe pkgid packageConfigHaddockHtmlLocation elabHaddockForeignLibs = perPkgOptionFlag pkgid False packageConfigHaddockForeignLibs elabHaddockForHackage = perPkgOptionFlag pkgid Cabal.ForDevelopment packageConfigHaddockForHackage elabHaddockExecutables = perPkgOptionFlag pkgid False packageConfigHaddockExecutables elabHaddockTestSuites = perPkgOptionFlag pkgid False packageConfigHaddockTestSuites elabHaddockBenchmarks = perPkgOptionFlag pkgid False packageConfigHaddockBenchmarks elabHaddockInternal = perPkgOptionFlag pkgid False packageConfigHaddockInternal elabHaddockCss = perPkgOptionMaybe pkgid packageConfigHaddockCss elabHaddockHscolour = perPkgOptionFlag pkgid False packageConfigHaddockHscolour elabHaddockHscolourCss = perPkgOptionMaybe pkgid packageConfigHaddockHscolourCss elabHaddockContents = perPkgOptionMaybe pkgid packageConfigHaddockContents perPkgOptionFlag :: PackageId -> a -> (PackageConfig -> Flag a) -> a perPkgOptionMaybe :: PackageId -> (PackageConfig -> Flag a) -> Maybe a perPkgOptionList :: PackageId -> (PackageConfig -> [a]) -> [a] perPkgOptionFlag pkgid def f = fromFlagOrDefault def (lookupPerPkgOption pkgid f) perPkgOptionMaybe pkgid f = flagToMaybe (lookupPerPkgOption pkgid f) perPkgOptionList pkgid f = lookupPerPkgOption pkgid f perPkgOptionNubList pkgid f = fromNubList (lookupPerPkgOption pkgid f) perPkgOptionMapLast pkgid f = getMapLast (lookupPerPkgOption pkgid f) perPkgOptionMapMappend pkgid f = getMapMappend (lookupPerPkgOption pkgid f) perPkgOptionLibExeFlag pkgid def fboth flib = (exe, lib) where exe = fromFlagOrDefault def bothflag lib = fromFlagOrDefault def (bothflag <> libflag) bothflag = lookupPerPkgOption pkgid fboth libflag = lookupPerPkgOption pkgid flib lookupPerPkgOption :: (Package pkg, Monoid m) => pkg -> (PackageConfig -> m) -> m lookupPerPkgOption pkg f -- the project config specifies values that apply to packages local to -- but by default non-local packages get all default config values -- the project, and can specify per-package values for any package, | isLocalToProject pkg = local `mappend` perpkg | otherwise = perpkg where local = f localPackagesConfig perpkg = maybe mempty f (Map.lookup (packageName pkg) perPackageConfig) inplacePackageDbs = storePackageDbs ++ [ distPackageDB (compilerId compiler) ] storePackageDbs = storePackageDBStack (compilerId compiler) -- For this local build policy, every package that lives in a local source -- dir (as opposed to a tarball), or depends on such a package, will be -- built inplace into a shared dist dir. Tarball packages that depend on -- source dir packages will also get unpacked locally. shouldBuildInplaceOnly :: SolverPackage loc -> Bool shouldBuildInplaceOnly pkg = Set.member (packageId pkg) pkgsToBuildInplaceOnly pkgsToBuildInplaceOnly :: Set PackageId pkgsToBuildInplaceOnly = Set.fromList $ map packageId $ SolverInstallPlan.reverseDependencyClosure solverPlan [ PlannedId (packageId pkg) | pkg <- localPackages ] isLocalToProject :: Package pkg => pkg -> Bool isLocalToProject pkg = Set.member (packageId pkg) pkgsLocalToProject pkgsLocalToProject :: Set PackageId pkgsLocalToProject = Set.fromList [ packageId pkg | pkg <- localPackages ] pkgsUseSharedLibrary :: Set PackageId pkgsUseSharedLibrary = packagesWithLibDepsDownwardClosedProperty needsSharedLib where needsSharedLib pkg = fromMaybe compilerShouldUseSharedLibByDefault (liftM2 (||) pkgSharedLib pkgDynExe) where pkgid = packageId pkg pkgSharedLib = perPkgOptionMaybe pkgid packageConfigSharedLib pkgDynExe = perPkgOptionMaybe pkgid packageConfigDynExe --TODO: [code cleanup] move this into the Cabal lib. It's currently open -- coded in Distribution.Simple.Configure, but should be made a proper -- function of the Compiler or CompilerInfo. compilerShouldUseSharedLibByDefault = case compilerFlavor compiler of GHC -> GHC.isDynamic compiler GHCJS -> GHCJS.isDynamic compiler _ -> False pkgsUseProfilingLibrary :: Set PackageId pkgsUseProfilingLibrary = packagesWithLibDepsDownwardClosedProperty needsProfilingLib where needsProfilingLib pkg = fromFlagOrDefault False (profBothFlag <> profLibFlag) where pkgid = packageId pkg profBothFlag = lookupPerPkgOption pkgid packageConfigProf profLibFlag = lookupPerPkgOption pkgid packageConfigProfLib --TODO: [code cleanup] unused: the old deprecated packageConfigProfExe libDepGraph = Graph.fromDistinctList $ map NonSetupLibDepSolverPlanPackage (SolverInstallPlan.toList solverPlan) packagesWithLibDepsDownwardClosedProperty property = Set.fromList . map packageId . fromMaybe [] $ Graph.closure libDepGraph [ Graph.nodeKey pkg | pkg <- SolverInstallPlan.toList solverPlan , property pkg ] -- just the packages that satisfy the property --TODO: [nice to have] this does not check the config consistency, -- e.g. a package explicitly turning off profiling, but something -- depending on it that needs profiling. This really needs a separate -- package config validation/resolution pass. --TODO: [nice to have] config consistency checking: -- + profiling libs & exes, exe needs lib, recursive -- + shared libs & exes, exe needs lib, recursive -- + vanilla libs & exes, exe needs lib, recursive -- + ghci or shared lib needed by TH, recursive, ghc version dependent -- TODO: Drop matchPlanPkg/matchElabPkg in favor of mkCCMapping -- | Given a 'ElaboratedPlanPackage', report if it matches a 'ComponentName'. matchPlanPkg :: (ComponentName -> Bool) -> ElaboratedPlanPackage -> Bool matchPlanPkg p = InstallPlan.foldPlanPackage (p . ipiComponentName) (matchElabPkg p) -- | Get the appropriate 'ComponentName' which identifies an installed -- component. ipiComponentName :: IPI.InstalledPackageInfo -> ComponentName ipiComponentName ipkg = case IPI.sourceLibName ipkg of Nothing -> CLibName Just n -> (CSubLibName n) -- | Given a 'ElaboratedConfiguredPackage', report if it matches a -- 'ComponentName'. matchElabPkg :: (ComponentName -> Bool) -> ElaboratedConfiguredPackage -> Bool matchElabPkg p elab = case elabPkgOrComp elab of ElabComponent comp -> maybe False p (compComponentName comp) ElabPackage _ -> -- So, what should we do here? One possibility is to -- unconditionally return 'True', because whatever it is -- that we're looking for, it better be in this package. -- But this is a bit dodgy if the package doesn't actually -- have, e.g., a library. Fortunately, it's not possible -- for the build of the library/executables to be toggled -- by 'pkgStanzasEnabled', so the only thing we have to -- test is if the component in question is *buildable.* any (p . componentName) (Cabal.pkgBuildableComponents (elabPkgDescription elab)) -- | Given an 'ElaboratedPlanPackage', generate the mapping from 'PackageName' -- and 'ComponentName' to the 'ComponentId' that that should be used -- in this case. mkCCMapping :: ElaboratedPlanPackage -> (PackageName, Map ComponentName (AnnotatedId ComponentId)) mkCCMapping = InstallPlan.foldPlanPackage (\ipkg -> (packageName ipkg, Map.singleton (ipiComponentName ipkg) -- TODO: libify (AnnotatedId { ann_id = IPI.installedComponentId ipkg, ann_pid = packageId ipkg, ann_cname = IPI.sourceComponentName ipkg }))) $ \elab -> let mk_aid cn = AnnotatedId { ann_id = elabComponentId elab, ann_pid = packageId elab, ann_cname = cn } in (packageName elab, case elabPkgOrComp elab of ElabComponent comp -> case compComponentName comp of Nothing -> Map.empty Just n -> Map.singleton n (mk_aid n) ElabPackage _ -> Map.fromList $ map (\comp -> let cn = Cabal.componentName comp in (cn, mk_aid cn)) (Cabal.pkgBuildableComponents (elabPkgDescription elab))) -- | Given an 'ElaboratedPlanPackage', generate the mapping from 'ComponentId' -- to the shape of this package, as per mix-in linking. mkShapeMapping :: ElaboratedPlanPackage -> (ComponentId, (OpenUnitId, ModuleShape)) mkShapeMapping dpkg = (getComponentId dpkg, (indef_uid, shape)) where (dcid, shape) = InstallPlan.foldPlanPackage -- Uses Monad (->) (liftM2 (,) IPI.installedComponentId shapeInstalledPackage) (liftM2 (,) elabComponentId elabModuleShape) dpkg indef_uid = IndefFullUnitId dcid (Map.fromList [ (req, OpenModuleVar req) | req <- Set.toList (modShapeRequires shape)]) -- | A newtype for 'SolverInstallPlan.SolverPlanPackage' for which the -- dependency graph considers only dependencies on libraries which are -- NOT from setup dependencies. Used to compute the set -- of packages needed for profiling and dynamic libraries. newtype NonSetupLibDepSolverPlanPackage = NonSetupLibDepSolverPlanPackage { unNonSetupLibDepSolverPlanPackage :: SolverInstallPlan.SolverPlanPackage } instance Package NonSetupLibDepSolverPlanPackage where packageId = packageId . unNonSetupLibDepSolverPlanPackage instance IsNode NonSetupLibDepSolverPlanPackage where type Key NonSetupLibDepSolverPlanPackage = SolverId nodeKey = nodeKey . unNonSetupLibDepSolverPlanPackage nodeNeighbors (NonSetupLibDepSolverPlanPackage spkg) = ordNub $ CD.nonSetupDeps (resolverPackageLibDeps spkg) type InstS = Map UnitId ElaboratedPlanPackage type InstM a = State InstS a getComponentId :: ElaboratedPlanPackage -> ComponentId getComponentId (InstallPlan.PreExisting dipkg) = IPI.installedComponentId dipkg getComponentId (InstallPlan.Configured elab) = elabComponentId elab getComponentId (InstallPlan.Installed elab) = elabComponentId elab instantiateInstallPlan :: ElaboratedInstallPlan -> ElaboratedInstallPlan instantiateInstallPlan plan = InstallPlan.new (IndependentGoals False) (Graph.fromDistinctList (Map.elems ready_map)) where pkgs = InstallPlan.toList plan cmap = Map.fromList [ (getComponentId pkg, pkg) | pkg <- pkgs ] instantiateUnitId :: ComponentId -> Map ModuleName Module -> InstM DefUnitId instantiateUnitId cid insts = state $ \s -> case Map.lookup uid s of Nothing -> -- Knot tied let (r, s') = runState (instantiateComponent uid cid insts) (Map.insert uid r s) in (def_uid, Map.insert uid r s') Just _ -> (def_uid, s) where def_uid = mkDefUnitId cid insts uid = unDefUnitId def_uid instantiateComponent :: UnitId -> ComponentId -> Map ModuleName Module -> InstM ElaboratedPlanPackage instantiateComponent uid cid insts | Just planpkg <- Map.lookup cid cmap = case planpkg of InstallPlan.Configured (elab@ElaboratedConfiguredPackage { elabPkgOrComp = ElabComponent comp }) -> do deps <- mapM (substUnitId insts) (compLinkedLibDependencies comp) let getDep (Module dep_uid _) = [dep_uid] return $ InstallPlan.Configured elab { elabUnitId = uid, elabComponentId = cid, elabInstantiatedWith = insts, elabIsCanonical = Map.null insts, elabPkgOrComp = ElabComponent comp { compOrderLibDependencies = (if Map.null insts then [] else [newSimpleUnitId cid]) ++ ordNub (map unDefUnitId (deps ++ concatMap getDep (Map.elems insts))) } } _ -> return planpkg | otherwise = error ("instantiateComponent: " ++ display cid) substUnitId :: Map ModuleName Module -> OpenUnitId -> InstM DefUnitId substUnitId _ (DefiniteUnitId uid) = return uid substUnitId subst (IndefFullUnitId cid insts) = do insts' <- substSubst subst insts instantiateUnitId cid insts' -- NB: NOT composition substSubst :: Map ModuleName Module -> Map ModuleName OpenModule -> InstM (Map ModuleName Module) substSubst subst insts = T.mapM (substModule subst) insts substModule :: Map ModuleName Module -> OpenModule -> InstM Module substModule subst (OpenModuleVar mod_name) | Just m <- Map.lookup mod_name subst = return m | otherwise = error "substModule: non-closing substitution" substModule subst (OpenModule uid mod_name) = do uid' <- substUnitId subst uid return (Module uid' mod_name) indefiniteUnitId :: ComponentId -> InstM UnitId indefiniteUnitId cid = do let uid = newSimpleUnitId cid r <- indefiniteComponent uid cid state $ \s -> (uid, Map.insert uid r s) indefiniteComponent :: UnitId -> ComponentId -> InstM ElaboratedPlanPackage indefiniteComponent _uid cid | Just planpkg <- Map.lookup cid cmap = return planpkg | otherwise = error ("indefiniteComponent: " ++ display cid) ready_map = execState work Map.empty work = forM_ pkgs $ \pkg -> case pkg of InstallPlan.Configured elab | not (Map.null (elabLinkedInstantiatedWith elab)) -> indefiniteUnitId (elabComponentId elab) >> return () _ -> instantiateUnitId (getComponentId pkg) Map.empty >> return () --------------------------- -- Build targets -- -- Refer to ProjectPlanning.Types for details of these important types: -- data ComponentTarget = ... -- data SubComponentTarget = ... -- One step in the build system is to translate higher level intentions like -- "build this package", "test that package", or "repl that component" into -- a more detailed specification of exactly which components to build (or other -- actions like repl or build docs). This translation is somewhat different for -- different commands. For example "test" for a package will build a different -- set of components than "build". In addition, the translation of these -- intentions can fail. For example "run" for a package is only unambiguous -- when the package has a single executable. -- -- So we need a little bit of infrastructure to make it easy for the command -- implementations to select what component targets are meant when a user asks -- to do something with a package or component. To do this (and to be able to -- produce good error messages for mistakes and when targets are not available) -- we need to gather and summarise accurate information about all the possible -- targets, both available and unavailable. Then a command implementation can -- decide which of the available component targets should be selected. -- | An available target represents a component within a package that a user -- command could plausibly refer to. In this sense, all the components defined -- within the package are things the user could refer to, whether or not it -- would actually be possible to build that component. -- -- In particular the available target contains an 'AvailableTargetStatus' which -- informs us about whether it's actually possible to select this component to -- be built, and if not why not. This detail makes it possible for command -- implementations (like @build@, @test@ etc) to accurately report why a target -- cannot be used. -- -- Note that the type parameter is used to help enforce that command -- implementations can only select targets that can actually be built (by -- forcing them to return the @k@ value for the selected targets). -- In particular 'resolveTargets' makes use of this (with @k@ as -- @('UnitId', ComponentName')@) to identify the targets thus selected. -- data AvailableTarget k = AvailableTarget { availableTargetPackageId :: PackageId, availableTargetComponentName :: ComponentName, availableTargetStatus :: AvailableTargetStatus k, availableTargetLocalToProject :: Bool } deriving (Eq, Show, Functor) -- | The status of a an 'AvailableTarget' component. This tells us whether -- it's actually possible to select this component to be built, and if not -- why not. -- data AvailableTargetStatus k = TargetDisabledByUser -- ^ When the user does @tests: False@ | TargetDisabledBySolver -- ^ When the solver could not enable tests | TargetNotBuildable -- ^ When the component has @buildable: False@ | TargetNotLocal -- ^ When the component is non-core in a non-local package | TargetBuildable k TargetRequested -- ^ The target can or should be built deriving (Eq, Ord, Show, Functor) -- | This tells us whether a target ought to be built by default, or only if -- specifically requested. The policy is that components like libraries and -- executables are built by default by @build@, but test suites and benchmarks -- are not, unless this is overridden in the project configuration. -- data TargetRequested = TargetRequestedByDefault -- ^ To be built by default | TargetNotRequestedByDefault -- ^ Not to be built by default deriving (Eq, Ord, Show) -- | Given the install plan, produce the set of 'AvailableTarget's for each -- package-component pair. -- -- Typically there will only be one such target for each component, but for -- example if we have a plan with both normal and profiling variants of a -- component then we would get both as available targets, or similarly if we -- had a plan that contained two instances of the same version of a package. -- This approach makes it relatively easy to select all instances\/variants -- of a component. -- availableTargets :: ElaboratedInstallPlan -> Map (PackageId, ComponentName) [AvailableTarget (UnitId, ComponentName)] availableTargets installPlan = let rs = [ (pkgid, cname, fake, target) | pkg <- InstallPlan.toList installPlan , (pkgid, cname, fake, target) <- case pkg of InstallPlan.PreExisting ipkg -> availableInstalledTargets ipkg InstallPlan.Installed elab -> availableSourceTargets elab InstallPlan.Configured elab -> availableSourceTargets elab ] in Map.union (Map.fromListWith (++) [ ((pkgid, cname), [target]) | (pkgid, cname, fake, target) <- rs, not fake]) (Map.fromList [ ((pkgid, cname), [target]) | (pkgid, cname, fake, target) <- rs, fake]) -- The normal targets mask the fake ones. We get all instances of the -- normal ones and only one copy of the fake ones (as there are many -- duplicates of the fake ones). See 'availableSourceTargets' below for -- more details on this fake stuff is about. availableInstalledTargets :: IPI.InstalledPackageInfo -> [(PackageId, ComponentName, Bool, AvailableTarget (UnitId, ComponentName))] availableInstalledTargets ipkg = let unitid = installedUnitId ipkg cname = CLibName status = TargetBuildable (unitid, cname) TargetRequestedByDefault target = AvailableTarget (packageId ipkg) cname status False fake = False in [(packageId ipkg, cname, fake, target)] availableSourceTargets :: ElaboratedConfiguredPackage -> [(PackageId, ComponentName, Bool, AvailableTarget (UnitId, ComponentName))] availableSourceTargets elab = -- We have a somewhat awkward problem here. We need to know /all/ the -- components from /all/ the packages because these are the things that -- users could refer to. Unfortunately, at this stage the elaborated install -- plan does /not/ contain all components: some components have already -- been deleted because they cannot possibly be built. This is the case -- for components that are marked @buildable: False@ in their .cabal files. -- (It's not unreasonable that the unbuildable components have been pruned -- as the plan invariant is considerably simpler if all nodes can be built) -- -- We can recover the missing components but it's not exactly elegant. For -- a graph node corresponding to a component we still have the information -- about the package that it came from, and this includes the names of -- /all/ the other components in the package. So in principle this lets us -- find the names of all components, plus full details of the buildable -- components. -- -- Consider for example a package with 3 exe components: foo, bar and baz -- where foo and bar are buildable, but baz is not. So the plan contains -- nodes for the components foo and bar. Now we look at each of these two -- nodes and look at the package they come from and the names of the -- components in this package. This will give us the names foo, bar and -- baz, twice (once for each of the two buildable components foo and bar). -- -- We refer to these reconstructed missing components as fake targets. -- It is an invariant that they are not available to be built. -- -- To produce the final set of targets we put the fake targets in a finite -- map (thus eliminating the duplicates) and then we overlay that map with -- the normal buildable targets. (This is done above in 'availableTargets'.) -- [ (packageId elab, cname, fake, target) | component <- pkgComponents (elabPkgDescription elab) , let cname = componentName component status = componentAvailableTargetStatus component target = AvailableTarget { availableTargetPackageId = packageId elab, availableTargetComponentName = cname, availableTargetStatus = status, availableTargetLocalToProject = elabLocalToProject elab } fake = isFakeTarget cname -- TODO: The goal of this test is to exclude "instantiated" -- packages as available targets. This means that you can't -- ask for a particular instantiated component to be built; -- it will only get built by a dependency. Perhaps the -- correct way to implement this is to run selection -- prior to instantiating packages. If you refactor -- this, then you can delete this test. , elabIsCanonical elab -- Filter out some bogus parts of the cross product that are never needed , case status of TargetBuildable{} | fake -> False _ -> True ] where isFakeTarget cname = case elabPkgOrComp elab of ElabPackage _ -> False ElabComponent elabComponent -> compComponentName elabComponent /= Just cname componentAvailableTargetStatus :: Component -> AvailableTargetStatus (UnitId, ComponentName) componentAvailableTargetStatus component = case componentOptionalStanza (componentName component) of -- it is not an optional stanza, so a library, exe or foreign lib Nothing | not buildable -> TargetNotBuildable | otherwise -> TargetBuildable (elabUnitId elab, cname) TargetRequestedByDefault -- it is not an optional stanza, so a testsuite or benchmark Just stanza -> case (Map.lookup stanza (elabStanzasRequested elab), Set.member stanza (elabStanzasAvailable elab)) of _ | not withinPlan -> TargetNotLocal (Just False, _) -> TargetDisabledByUser (Nothing, False) -> TargetDisabledBySolver _ | not buildable -> TargetNotBuildable (Just True, True) -> TargetBuildable (elabUnitId elab, cname) TargetRequestedByDefault (Nothing, True) -> TargetBuildable (elabUnitId elab, cname) TargetNotRequestedByDefault (Just True, False) -> error "componentAvailableTargetStatus: impossible" where cname = componentName component buildable = PD.buildable (componentBuildInfo component) withinPlan = elabLocalToProject elab || case elabPkgOrComp elab of ElabComponent elabComponent -> compComponentName elabComponent == Just cname ElabPackage _ -> case componentName component of CLibName -> True CExeName _ -> True --TODO: what about sub-libs and foreign libs? _ -> False -- | Merge component targets that overlap each other. Specially when we have -- multiple targets for the same component and one of them refers to the whole -- component (rather than a module or file within) then all the other targets -- for that component are subsumed. -- -- We also allow for information associated with each component target, and -- whenever we targets subsume each other we aggregate their associated info. -- nubComponentTargets :: [(ComponentTarget, a)] -> [(ComponentTarget, [a])] nubComponentTargets = concatMap (wholeComponentOverrides . map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst) . map (\t@((ComponentTarget cname _, _)) -> (cname, t)) . map compatSubComponentTargets where -- If we're building the whole component then that the only target all we -- need, otherwise we can have several targets within the component. wholeComponentOverrides :: [(ComponentTarget, a )] -> [(ComponentTarget, [a])] wholeComponentOverrides ts = case [ t | (t@(ComponentTarget _ WholeComponent), _) <- ts ] of (t:_) -> [ (t, map snd ts) ] [] -> [ (t,[x]) | (t,x) <- ts ] -- Not all Cabal Setup.hs versions support sub-component targets, so switch -- them over to the whole component compatSubComponentTargets :: (ComponentTarget, a) -> (ComponentTarget, a) compatSubComponentTargets target@(ComponentTarget cname _subtarget, x) | not setupHsSupportsSubComponentTargets = (ComponentTarget cname WholeComponent, x) | otherwise = target -- Actually the reality is that no current version of Cabal's Setup.hs -- build command actually support building specific files or modules. setupHsSupportsSubComponentTargets = False -- TODO: when that changes, adjust this test, e.g. -- | pkgSetupScriptCliVersion >= Version [x,y] [] pkgHasEphemeralBuildTargets :: ElaboratedConfiguredPackage -> Bool pkgHasEphemeralBuildTargets elab = isJust (elabReplTarget elab) || (not . null) (elabTestTargets elab) || (not . null) (elabBenchTargets elab) || (not . null) [ () | ComponentTarget _ subtarget <- elabBuildTargets elab , subtarget /= WholeComponent ] -- | The components that we'll build all of, meaning that after they're built -- we can skip building them again (unlike with building just some modules or -- other files within a component). -- elabBuildTargetWholeComponents :: ElaboratedConfiguredPackage -> Set ComponentName elabBuildTargetWholeComponents elab = Set.fromList [ cname | ComponentTarget cname WholeComponent <- elabBuildTargets elab ] ------------------------------------------------------------------------------ -- * Install plan pruning ------------------------------------------------------------------------------ -- | How 'pruneInstallPlanToTargets' should interpret the per-package -- 'ComponentTarget's: as build, repl or haddock targets. -- data TargetAction = TargetActionBuild | TargetActionRepl | TargetActionTest | TargetActionBench | TargetActionHaddock -- | Given a set of per-package\/per-component targets, take the subset of the -- install plan needed to build those targets. Also, update the package config -- to specify which optional stanzas to enable, and which targets within each -- package to build. -- pruneInstallPlanToTargets :: TargetAction -> Map UnitId [ComponentTarget] -> ElaboratedInstallPlan -> ElaboratedInstallPlan pruneInstallPlanToTargets targetActionType perPkgTargetsMap elaboratedPlan = InstallPlan.new (InstallPlan.planIndepGoals elaboratedPlan) . Graph.fromDistinctList -- We have to do the pruning in two passes . pruneInstallPlanPass2 . pruneInstallPlanPass1 -- Set the targets that will be the roots for pruning . setRootTargets targetActionType perPkgTargetsMap . InstallPlan.toList $ elaboratedPlan -- | This is a temporary data type, where we temporarily -- override the graph dependencies of an 'ElaboratedPackage', -- so we can take a closure over them. We'll throw out the -- overriden dependencies when we're done so it's strictly temporary. -- -- For 'ElaboratedComponent', this the cached unit IDs always -- coincide with the real thing. data PrunedPackage = PrunedPackage ElaboratedConfiguredPackage [UnitId] instance Package PrunedPackage where packageId (PrunedPackage elab _) = packageId elab instance HasUnitId PrunedPackage where installedUnitId = nodeKey instance IsNode PrunedPackage where type Key PrunedPackage = UnitId nodeKey (PrunedPackage elab _) = nodeKey elab nodeNeighbors (PrunedPackage _ deps) = deps fromPrunedPackage :: PrunedPackage -> ElaboratedConfiguredPackage fromPrunedPackage (PrunedPackage elab _) = elab -- | Set the build targets based on the user targets (but not rev deps yet). -- This is required before we can prune anything. -- setRootTargets :: TargetAction -> Map UnitId [ComponentTarget] -> [ElaboratedPlanPackage] -> [ElaboratedPlanPackage] setRootTargets targetAction perPkgTargetsMap = assert (not (Map.null perPkgTargetsMap)) $ assert (all (not . null) (Map.elems perPkgTargetsMap)) $ map (mapConfiguredPackage setElabBuildTargets) where -- Set the targets we'll build for this package/component. This is just -- based on the root targets from the user, not targets implied by reverse -- dependencies. Those comes in the second pass once we know the rev deps. -- setElabBuildTargets elab = case (Map.lookup (installedUnitId elab) perPkgTargetsMap, targetAction) of (Nothing, _) -> elab (Just tgts, TargetActionBuild) -> elab { elabBuildTargets = tgts } (Just tgts, TargetActionTest) -> elab { elabTestTargets = tgts } (Just tgts, TargetActionBench) -> elab { elabBenchTargets = tgts } (Just [tgt], TargetActionRepl) -> elab { elabReplTarget = Just tgt } (Just _, TargetActionHaddock) -> elab { elabBuildHaddocks = True } (Just _, TargetActionRepl) -> error "pruneInstallPlanToTargets: multiple repl targets" -- | Assuming we have previously set the root build targets (i.e. the user -- targets but not rev deps yet), the first pruning pass does two things: -- -- * A first go at determining which optional stanzas (testsuites, benchmarks) -- are needed. We have a second go in the next pass. -- * Take the dependency closure using pruned dependencies. We prune deps that -- are used only by unneeded optional stanzas. These pruned deps are only -- used for the dependency closure and are not persisted in this pass. -- pruneInstallPlanPass1 :: [ElaboratedPlanPackage] -> [ElaboratedPlanPackage] pruneInstallPlanPass1 pkgs = map (mapConfiguredPackage fromPrunedPackage) (fromMaybe [] $ Graph.closure graph roots) where pkgs' = map (mapConfiguredPackage prune) pkgs graph = Graph.fromDistinctList pkgs' roots = mapMaybe find_root pkgs' prune elab = PrunedPackage elab' (pruneOptionalDependencies elab') where elab' = pruneOptionalStanzas elab find_root (InstallPlan.Configured (PrunedPackage elab _)) = if not (null (elabBuildTargets elab) && null (elabTestTargets elab) && null (elabBenchTargets elab) && isNothing (elabReplTarget elab) && not (elabBuildHaddocks elab)) then Just (installedUnitId elab) else Nothing find_root _ = Nothing -- Decide whether or not to enable testsuites and benchmarks -- -- The testsuite and benchmark targets are somewhat special in that we need -- to configure the packages with them enabled, and we need to do that even -- if we only want to build one of several testsuites. -- -- There are two cases in which we will enable the testsuites (or -- benchmarks): if one of the targets is a testsuite, or if all of the -- testsuite dependencies are already cached in the store. The rationale -- for the latter is to minimise how often we have to reconfigure due to -- the particular targets we choose to build. Otherwise choosing to build -- a testsuite target, and then later choosing to build an exe target -- would involve unnecessarily reconfiguring the package with testsuites -- disabled. Technically this introduces a little bit of stateful -- behaviour to make this "sticky", but it should be benign. -- pruneOptionalStanzas :: ElaboratedConfiguredPackage -> ElaboratedConfiguredPackage pruneOptionalStanzas elab@ElaboratedConfiguredPackage{ elabPkgOrComp = ElabPackage pkg } = elab { elabPkgOrComp = ElabPackage (pkg { pkgStanzasEnabled = stanzas }) } where stanzas :: Set OptionalStanza stanzas = optionalStanzasRequiredByTargets elab <> optionalStanzasRequestedByDefault elab <> optionalStanzasWithDepsAvailable availablePkgs elab pkg pruneOptionalStanzas elab = elab -- Calculate package dependencies but cut out those needed only by -- optional stanzas that we've determined we will not enable. -- These pruned deps are not persisted in this pass since they're based on -- the optional stanzas and we'll make further tweaks to the optional -- stanzas in the next pass. -- pruneOptionalDependencies :: ElaboratedConfiguredPackage -> [UnitId] pruneOptionalDependencies elab@ElaboratedConfiguredPackage{ elabPkgOrComp = ElabComponent _ } = InstallPlan.depends elab -- no pruning pruneOptionalDependencies ElaboratedConfiguredPackage{ elabPkgOrComp = ElabPackage pkg } = (CD.flatDeps . CD.filterDeps keepNeeded) (pkgOrderDependencies pkg) where keepNeeded (CD.ComponentTest _) _ = TestStanzas `Set.member` stanzas keepNeeded (CD.ComponentBench _) _ = BenchStanzas `Set.member` stanzas keepNeeded _ _ = True stanzas = pkgStanzasEnabled pkg optionalStanzasRequiredByTargets :: ElaboratedConfiguredPackage -> Set OptionalStanza optionalStanzasRequiredByTargets pkg = Set.fromList [ stanza | ComponentTarget cname _ <- elabBuildTargets pkg ++ elabTestTargets pkg ++ elabBenchTargets pkg ++ maybeToList (elabReplTarget pkg) , stanza <- maybeToList (componentOptionalStanza cname) ] optionalStanzasRequestedByDefault :: ElaboratedConfiguredPackage -> Set OptionalStanza optionalStanzasRequestedByDefault = Map.keysSet . Map.filter (id :: Bool -> Bool) . elabStanzasRequested availablePkgs = Set.fromList [ installedUnitId pkg | InstallPlan.PreExisting pkg <- pkgs ] -- | Given a set of already installed packages @availablePkgs@, -- determine the set of available optional stanzas from @pkg@ -- which have all of their dependencies already installed. This is used -- to implement "sticky" testsuites, where once we have installed -- all of the deps needed for the test suite, we go ahead and -- enable it always. optionalStanzasWithDepsAvailable :: Set UnitId -> ElaboratedConfiguredPackage -> ElaboratedPackage -> Set OptionalStanza optionalStanzasWithDepsAvailable availablePkgs elab pkg = Set.fromList [ stanza | stanza <- Set.toList (elabStanzasAvailable elab) , let deps :: [UnitId] deps = CD.select (optionalStanzaDeps stanza) -- TODO: probably need to select other -- dep types too eventually (pkgOrderDependencies pkg) , all (`Set.member` availablePkgs) deps ] where optionalStanzaDeps TestStanzas (CD.ComponentTest _) = True optionalStanzaDeps BenchStanzas (CD.ComponentBench _) = True optionalStanzaDeps _ _ = False -- The second pass does three things: -- -- * A second go at deciding which optional stanzas to enable. -- * Prune the dependencies based on the final choice of optional stanzas. -- * Extend the targets within each package to build, now we know the reverse -- dependencies, ie we know which libs are needed as deps by other packages. -- -- Achieving sticky behaviour with enabling\/disabling optional stanzas is -- tricky. The first approximation was handled by the first pass above, but -- it's not quite enough. That pass will enable stanzas if all of the deps -- of the optional stanza are already installed /in the store/. That's important -- but it does not account for dependencies that get built inplace as part of -- the project. We cannot take those inplace build deps into account in the -- pruning pass however because we don't yet know which ones we're going to -- build. Once we do know, we can have another go and enable stanzas that have -- all their deps available. Now we can consider all packages in the pruned -- plan to be available, including ones we already decided to build from -- source. -- -- Deciding which targets to build depends on knowing which packages have -- reverse dependencies (ie are needed). This requires the result of first -- pass, which is another reason we have to split it into two passes. -- -- Note that just because we might enable testsuites or benchmarks (in the -- first or second pass) doesn't mean that we build all (or even any) of them. -- That depends on which targets we picked in the first pass. -- pruneInstallPlanPass2 :: [ElaboratedPlanPackage] -> [ElaboratedPlanPackage] pruneInstallPlanPass2 pkgs = map (mapConfiguredPackage setStanzasDepsAndTargets) pkgs where setStanzasDepsAndTargets elab = elab { elabBuildTargets = ordNub $ elabBuildTargets elab ++ libTargetsRequiredForRevDeps ++ exeTargetsRequiredForRevDeps, elabPkgOrComp = case elabPkgOrComp elab of ElabPackage pkg -> let stanzas = pkgStanzasEnabled pkg <> optionalStanzasWithDepsAvailable availablePkgs elab pkg keepNeeded (CD.ComponentTest _) _ = TestStanzas `Set.member` stanzas keepNeeded (CD.ComponentBench _) _ = BenchStanzas `Set.member` stanzas keepNeeded _ _ = True in ElabPackage $ pkg { pkgStanzasEnabled = stanzas, pkgLibDependencies = CD.filterDeps keepNeeded (pkgLibDependencies pkg), pkgExeDependencies = CD.filterDeps keepNeeded (pkgExeDependencies pkg), pkgExeDependencyPaths = CD.filterDeps keepNeeded (pkgExeDependencyPaths pkg) } r@(ElabComponent _) -> r } where libTargetsRequiredForRevDeps = [ ComponentTarget Cabal.defaultLibName WholeComponent | installedUnitId elab `Set.member` hasReverseLibDeps ] exeTargetsRequiredForRevDeps = -- TODO: allow requesting executable with different name -- than package name [ ComponentTarget (Cabal.CExeName $ packageNameToUnqualComponentName $ packageName $ elabPkgSourceId elab) WholeComponent | installedUnitId elab `Set.member` hasReverseExeDeps ] availablePkgs :: Set UnitId availablePkgs = Set.fromList (map installedUnitId pkgs) hasReverseLibDeps :: Set UnitId hasReverseLibDeps = Set.fromList [ depid | InstallPlan.Configured pkg <- pkgs , depid <- elabOrderLibDependencies pkg ] hasReverseExeDeps :: Set UnitId hasReverseExeDeps = Set.fromList [ depid | InstallPlan.Configured pkg <- pkgs , depid <- elabOrderExeDependencies pkg ] mapConfiguredPackage :: (srcpkg -> srcpkg') -> InstallPlan.GenericPlanPackage ipkg srcpkg -> InstallPlan.GenericPlanPackage ipkg srcpkg' mapConfiguredPackage f (InstallPlan.Configured pkg) = InstallPlan.Configured (f pkg) mapConfiguredPackage f (InstallPlan.Installed pkg) = InstallPlan.Installed (f pkg) mapConfiguredPackage _ (InstallPlan.PreExisting pkg) = InstallPlan.PreExisting pkg componentOptionalStanza :: Cabal.ComponentName -> Maybe OptionalStanza componentOptionalStanza (Cabal.CTestName _) = Just TestStanzas componentOptionalStanza (Cabal.CBenchName _) = Just BenchStanzas componentOptionalStanza _ = Nothing ------------------------------------ -- Support for --only-dependencies -- -- | Try to remove the given targets from the install plan. -- -- This is not always possible. -- pruneInstallPlanToDependencies :: Set UnitId -> ElaboratedInstallPlan -> Either CannotPruneDependencies ElaboratedInstallPlan pruneInstallPlanToDependencies pkgTargets installPlan = assert (all (isJust . InstallPlan.lookup installPlan) (Set.toList pkgTargets)) $ fmap (InstallPlan.new (InstallPlan.planIndepGoals installPlan)) . checkBrokenDeps . Graph.fromDistinctList . filter (\pkg -> installedUnitId pkg `Set.notMember` pkgTargets) . InstallPlan.toList $ installPlan where -- Our strategy is to remove the packages we don't want and then check -- if the remaining graph is broken or not, ie any packages with dangling -- dependencies. If there are then we cannot prune the given targets. checkBrokenDeps :: Graph.Graph ElaboratedPlanPackage -> Either CannotPruneDependencies (Graph.Graph ElaboratedPlanPackage) checkBrokenDeps graph = case Graph.broken graph of [] -> Right graph brokenPackages -> Left $ CannotPruneDependencies [ (pkg, missingDeps) | (pkg, missingDepIds) <- brokenPackages , let missingDeps = mapMaybe lookupDep missingDepIds ] where -- lookup in the original unpruned graph lookupDep = InstallPlan.lookup installPlan -- | It is not always possible to prune to only the dependencies of a set of -- targets. It may be the case that removing a package leaves something else -- that still needed the pruned package. -- -- This lists all the packages that would be broken, and their dependencies -- that would be missing if we did prune. -- newtype CannotPruneDependencies = CannotPruneDependencies [(ElaboratedPlanPackage, [ElaboratedPlanPackage])] deriving (Show) --------------------------- -- Setup.hs script policy -- -- Handling for Setup.hs scripts is a bit tricky, part of it lives in the -- solver phase, and part in the elaboration phase. We keep the helper -- functions for both phases together here so at least you can see all of it -- in one place. -- -- There are four major cases for Setup.hs handling: -- -- 1. @build-type@ Custom with a @custom-setup@ section -- 2. @build-type@ Custom without a @custom-setup@ section -- 3. @build-type@ not Custom with @cabal-version > $our-cabal-version@ -- 4. @build-type@ not Custom with @cabal-version <= $our-cabal-version@ -- -- It's also worth noting that packages specifying @cabal-version: >= 1.23@ -- or later that have @build-type@ Custom will always have a @custom-setup@ -- section. Therefore in case 2, the specified @cabal-version@ will always be -- less than 1.23. -- -- In cases 1 and 2 we obviously have to build an external Setup.hs script, -- while in case 4 we can use the internal library API. In case 3 we also have -- to build an external Setup.hs script because the package needs a later -- Cabal lib version than we can support internally. -- -- data SetupScriptStyle = ... -- see ProjectPlanning.Types -- | Work out the 'SetupScriptStyle' given the package description. -- packageSetupScriptStyle :: PD.PackageDescription -> SetupScriptStyle packageSetupScriptStyle pkg | buildType == PD.Custom , Just setupbi <- PD.setupBuildInfo pkg -- does have a custom-setup stanza , not (PD.defaultSetupDepends setupbi) -- but not one we added internally = SetupCustomExplicitDeps | buildType == PD.Custom , Just setupbi <- PD.setupBuildInfo pkg -- we get this case post-solver as , PD.defaultSetupDepends setupbi -- the solver fills in the deps = SetupCustomImplicitDeps | buildType == PD.Custom , Nothing <- PD.setupBuildInfo pkg -- we get this case pre-solver = SetupCustomImplicitDeps | PD.specVersion pkg > cabalVersion -- one cabal-install is built against = SetupNonCustomExternalLib | otherwise = SetupNonCustomInternalLib where buildType = fromMaybe PD.Custom (PD.buildType pkg) -- | Part of our Setup.hs handling policy is implemented by getting the solver -- to work out setup dependencies for packages. The solver already handles -- packages that explicitly specify setup dependencies, but we can also tell -- the solver to treat other packages as if they had setup dependencies. -- That's what this function does, it gets called by the solver for all -- packages that don't already have setup dependencies. -- -- The dependencies we want to add is different for each 'SetupScriptStyle'. -- -- Note that adding default deps means these deps are actually /added/ to the -- packages that we get out of the solver in the 'SolverInstallPlan'. Making -- implicit setup deps explicit is a problem in the post-solver stages because -- we still need to distinguish the case of explicit and implict setup deps. -- See 'rememberImplicitSetupDeps'. -- -- Note in addition to adding default setup deps, we also use -- 'addSetupCabalMinVersionConstraint' (in 'planPackages') to require -- @Cabal >= 1.20@ for Setup scripts. -- defaultSetupDeps :: Compiler -> Platform -> PD.PackageDescription -> Maybe [Dependency] defaultSetupDeps compiler platform pkg = case packageSetupScriptStyle pkg of -- For packages with build type custom that do not specify explicit -- setup dependencies, we add a dependency on Cabal and a number -- of other packages. SetupCustomImplicitDeps -> Just $ [ Dependency depPkgname anyVersion | depPkgname <- legacyCustomSetupPkgs compiler platform ] ++ [ Dependency cabalPkgname cabalConstraint | packageName pkg /= cabalPkgname ] where -- The Cabal dep is slightly special: -- * We omit the dep for the Cabal lib itself, since it bootstraps. -- * We constrain it to be < 1.25 -- -- Note: we also add a global constraint to require Cabal >= 1.20 -- for Setup scripts (see use addSetupCabalMinVersionConstraint). -- cabalConstraint = orLaterVersion (PD.specVersion pkg) `intersectVersionRanges` earlierVersion cabalCompatMaxVer -- The idea here is that at some point we will make significant -- breaking changes to the Cabal API that Setup.hs scripts use. -- So for old custom Setup scripts that do not specify explicit -- constraints, we constrain them to use a compatible Cabal version. cabalCompatMaxVer = mkVersion [1,25] -- For other build types (like Simple) if we still need to compile an -- external Setup.hs, it'll be one of the simple ones that only depends -- on Cabal and base. SetupNonCustomExternalLib -> Just [ Dependency cabalPkgname cabalConstraint , Dependency basePkgname anyVersion ] where cabalConstraint = orLaterVersion (PD.specVersion pkg) -- The internal setup wrapper method has no deps at all. SetupNonCustomInternalLib -> Just [] -- This case gets ruled out by the caller, planPackages, see the note -- above in the SetupCustomImplicitDeps case. SetupCustomExplicitDeps -> error $ "defaultSetupDeps: called for a package with explicit " ++ "setup deps: " ++ display (packageId pkg) -- | Work out which version of the Cabal spec we will be using to talk to the -- Setup.hs interface for this package. -- -- This depends somewhat on the 'SetupScriptStyle' but most cases are a result -- of what the solver picked for us, based on the explicit setup deps or the -- ones added implicitly by 'defaultSetupDeps'. -- packageSetupScriptSpecVersion :: Package pkg => SetupScriptStyle -> PD.PackageDescription -> ComponentDeps [pkg] -> Version -- We're going to be using the internal Cabal library, so the spec version of -- that is simply the version of the Cabal library that cabal-install has been -- built with. packageSetupScriptSpecVersion SetupNonCustomInternalLib _ _ = cabalVersion -- If we happen to be building the Cabal lib itself then because that -- bootstraps itself then we use the version of the lib we're building. packageSetupScriptSpecVersion SetupCustomImplicitDeps pkg _ | packageName pkg == cabalPkgname = packageVersion pkg -- In all other cases we have a look at what version of the Cabal lib the -- solver picked. Or if it didn't depend on Cabal at all (which is very rare) -- then we look at the .cabal file to see what spec version it declares. packageSetupScriptSpecVersion _ pkg deps = case find ((cabalPkgname ==) . packageName) (CD.setupDeps deps) of Just dep -> packageVersion dep Nothing -> PD.specVersion pkg cabalPkgname, basePkgname :: PackageName cabalPkgname = mkPackageName "Cabal" basePkgname = mkPackageName "base" legacyCustomSetupPkgs :: Compiler -> Platform -> [PackageName] legacyCustomSetupPkgs compiler (Platform _ os) = map mkPackageName $ [ "array", "base", "binary", "bytestring", "containers" , "deepseq", "directory", "filepath", "old-time", "pretty" , "process", "time", "transformers" ] ++ [ "Win32" | os == Windows ] ++ [ "unix" | os /= Windows ] ++ [ "ghc-prim" | isGHC ] ++ [ "template-haskell" | isGHC ] where isGHC = compilerCompatFlavor GHC compiler -- The other aspects of our Setup.hs policy lives here where we decide on -- the 'SetupScriptOptions'. -- -- Our current policy for the 'SetupCustomImplicitDeps' case is that we -- try to make the implicit deps cover everything, and we don't allow the -- compiler to pick up other deps. This may or may not be sustainable, and -- we might have to allow the deps to be non-exclusive, but that itself would -- be tricky since we would have to allow the Setup access to all the packages -- in the store and local dbs. setupHsScriptOptions :: ElaboratedReadyPackage -> ElaboratedSharedConfig -> FilePath -> FilePath -> Bool -> Lock -> SetupScriptOptions -- TODO: Fix this so custom is a separate component. Custom can ALWAYS -- be a separate component!!! setupHsScriptOptions (ReadyPackage elab@ElaboratedConfiguredPackage{..}) ElaboratedSharedConfig{..} srcdir builddir isParallelBuild cacheLock = SetupScriptOptions { useCabalVersion = thisVersion elabSetupScriptCliVersion, useCabalSpecVersion = Just elabSetupScriptCliVersion, useCompiler = Just pkgConfigCompiler, usePlatform = Just pkgConfigPlatform, usePackageDB = elabSetupPackageDBStack, usePackageIndex = Nothing, useDependencies = [ (uid, srcid) | ConfiguredId srcid (Just CLibName) uid <- elabSetupDependencies elab ], useDependenciesExclusive = True, useVersionMacros = elabSetupScriptStyle == SetupCustomExplicitDeps, useProgramDb = pkgConfigCompilerProgs, useDistPref = builddir, useLoggingHandle = Nothing, -- this gets set later useWorkingDir = Just srcdir, useExtraPathEnv = elabExeDependencyPaths elab, useWin32CleanHack = False, --TODO: [required eventually] forceExternalSetupMethod = isParallelBuild, setupCacheLock = Just cacheLock, isInteractive = False } -- | To be used for the input for elaborateInstallPlan. -- -- TODO: [code cleanup] make InstallDirs.defaultInstallDirs pure. -- userInstallDirTemplates :: Compiler -> IO InstallDirs.InstallDirTemplates userInstallDirTemplates compiler = do InstallDirs.defaultInstallDirs (compilerFlavor compiler) True -- user install False -- unused storePackageInstallDirs :: StoreDirLayout -> CompilerId -> InstalledPackageId -> InstallDirs.InstallDirs FilePath storePackageInstallDirs StoreDirLayout{storePackageDirectory} compid ipkgid = InstallDirs.InstallDirs {..} where prefix = storePackageDirectory compid (newSimpleUnitId ipkgid) bindir = prefix </> "bin" libdir = prefix </> "lib" libsubdir = "" dynlibdir = libdir flibdir = libdir libexecdir = prefix </> "libexec" libexecsubdir= "" includedir = libdir </> "include" datadir = prefix </> "share" datasubdir = "" docdir = datadir </> "doc" mandir = datadir </> "man" htmldir = docdir </> "html" haddockdir = htmldir sysconfdir = prefix </> "etc" --TODO: [code cleanup] perhaps reorder this code -- based on the ElaboratedInstallPlan + ElaboratedSharedConfig, -- make the various Setup.hs {configure,build,copy} flags setupHsConfigureFlags :: ElaboratedReadyPackage -> ElaboratedSharedConfig -> Verbosity -> FilePath -> Cabal.ConfigFlags setupHsConfigureFlags (ReadyPackage elab@ElaboratedConfiguredPackage{..}) sharedConfig@ElaboratedSharedConfig{..} verbosity builddir = sanityCheckElaboratedConfiguredPackage sharedConfig elab (Cabal.ConfigFlags {..}) where configArgs = mempty -- unused, passed via args configDistPref = toFlag builddir configCabalFilePath = mempty configVerbosity = toFlag verbosity configInstantiateWith = Map.toList elabInstantiatedWith configDeterministic = mempty -- doesn't matter, configIPID/configCID overridese configIPID = case elabPkgOrComp of ElabPackage pkg -> toFlag (display (pkgInstalledId pkg)) ElabComponent _ -> mempty configCID = case elabPkgOrComp of ElabPackage _ -> mempty ElabComponent _ -> toFlag elabComponentId configProgramPaths = Map.toList elabProgramPaths configProgramArgs | {- elabSetupScriptCliVersion < mkVersion [1,24,3] -} True -- workaround for <https://github.com/haskell/cabal/issues/4010> -- -- It turns out, that even with Cabal 2.0, there's still cases such as e.g. -- custom Setup.hs scripts calling out to GHC even when going via -- @runProgram ghcProgram@, as e.g. happy does in its -- <http://hackage.haskell.org/package/happy-1.19.5/src/Setup.lhs> -- (see also <https://github.com/haskell/cabal/pull/4433#issuecomment-299396099>) -- -- So for now, let's pass the rather harmless and idempotent -- `-hide-all-packages` flag to all invocations (which has -- the benefit that every GHC invocation starts with a -- conistently well-defined clean slate) until we find a -- better way. = Map.toList $ Map.insertWith (++) "ghc" ["-hide-all-packages"] elabProgramArgs | otherwise = Map.toList elabProgramArgs configProgramPathExtra = toNubList elabProgramPathExtra configHcFlavor = toFlag (compilerFlavor pkgConfigCompiler) configHcPath = mempty -- we use configProgramPaths instead configHcPkg = mempty -- we use configProgramPaths instead configVanillaLib = toFlag elabVanillaLib configSharedLib = toFlag elabSharedLib configStaticLib = toFlag elabStaticLib configDynExe = toFlag elabDynExe configGHCiLib = toFlag elabGHCiLib configProfExe = mempty configProfLib = toFlag elabProfLib configProf = toFlag elabProfExe -- configProfDetail is for exe+lib, but overridden by configProfLibDetail -- so we specify both so we can specify independently configProfDetail = toFlag elabProfExeDetail configProfLibDetail = toFlag elabProfLibDetail configCoverage = toFlag elabCoverage configLibCoverage = mempty configOptimization = toFlag elabOptimization configSplitObjs = toFlag elabSplitObjs configStripExes = toFlag elabStripExes configStripLibs = toFlag elabStripLibs configDebugInfo = toFlag elabDebugInfo configConfigurationsFlags = elabFlagAssignment configConfigureArgs = elabConfigureScriptArgs configExtraLibDirs = elabExtraLibDirs configExtraFrameworkDirs = elabExtraFrameworkDirs configExtraIncludeDirs = elabExtraIncludeDirs configProgPrefix = maybe mempty toFlag elabProgPrefix configProgSuffix = maybe mempty toFlag elabProgSuffix configInstallDirs = fmap (toFlag . InstallDirs.toPathTemplate) elabInstallDirs -- we only use configDependencies, unless we're talking to an old Cabal -- in which case we use configConstraints -- NB: This does NOT use InstallPlan.depends, which includes executable -- dependencies which should NOT be fed in here (also you don't have -- enough info anyway) configDependencies = [ (case mb_cn of -- Special case for internal libraries Just (CSubLibName uqn) | packageId elab == srcid -> mkPackageName (unUnqualComponentName uqn) _ -> packageName srcid, cid) | ConfiguredId srcid mb_cn cid <- elabLibDependencies elab ] configConstraints = case elabPkgOrComp of ElabPackage _ -> [ thisPackageVersion srcid | ConfiguredId srcid _ _uid <- elabLibDependencies elab ] ElabComponent _ -> [] -- explicitly clear, then our package db stack -- TODO: [required eventually] have to do this differently for older Cabal versions configPackageDBs = Nothing : map Just elabBuildPackageDBStack configTests = case elabPkgOrComp of ElabPackage pkg -> toFlag (TestStanzas `Set.member` pkgStanzasEnabled pkg) ElabComponent _ -> mempty configBenchmarks = case elabPkgOrComp of ElabPackage pkg -> toFlag (BenchStanzas `Set.member` pkgStanzasEnabled pkg) ElabComponent _ -> mempty configExactConfiguration = toFlag True configFlagError = mempty --TODO: [research required] appears not to be implemented configRelocatable = mempty --TODO: [research required] ??? configScratchDir = mempty -- never use configUserInstall = mempty -- don't rely on defaults configPrograms_ = mempty -- never use, shouldn't exist configUseResponseFiles = mempty setupHsConfigureArgs :: ElaboratedConfiguredPackage -> [String] setupHsConfigureArgs (ElaboratedConfiguredPackage { elabPkgOrComp = ElabPackage _ }) = [] setupHsConfigureArgs elab@(ElaboratedConfiguredPackage { elabPkgOrComp = ElabComponent comp }) = [showComponentTarget (packageId elab) (ComponentTarget cname WholeComponent)] where cname = fromMaybe (error "setupHsConfigureArgs: trying to configure setup") (compComponentName comp) setupHsBuildFlags :: ElaboratedConfiguredPackage -> ElaboratedSharedConfig -> Verbosity -> FilePath -> Cabal.BuildFlags setupHsBuildFlags _ _ verbosity builddir = Cabal.BuildFlags { buildProgramPaths = mempty, --unused, set at configure time buildProgramArgs = mempty, --unused, set at configure time buildVerbosity = toFlag verbosity, buildDistPref = toFlag builddir, buildNumJobs = mempty, --TODO: [nice to have] sometimes want to use toFlag (Just numBuildJobs), buildArgs = mempty -- unused, passed via args not flags } setupHsBuildArgs :: ElaboratedConfiguredPackage -> [String] setupHsBuildArgs elab@(ElaboratedConfiguredPackage { elabPkgOrComp = ElabPackage _ }) -- Fix for #3335, don't pass build arguments if it's not supported | elabSetupScriptCliVersion elab >= mkVersion [1,17] = map (showComponentTarget (packageId elab)) (elabBuildTargets elab) | otherwise = [] setupHsBuildArgs (ElaboratedConfiguredPackage { elabPkgOrComp = ElabComponent _ }) = [] setupHsTestFlags :: ElaboratedConfiguredPackage -> ElaboratedSharedConfig -> Verbosity -> FilePath -> Cabal.TestFlags setupHsTestFlags _ _ verbosity builddir = Cabal.TestFlags { testDistPref = toFlag builddir , testVerbosity = toFlag verbosity , testMachineLog = mempty , testHumanLog = mempty , testShowDetails = toFlag Cabal.Always , testKeepTix = mempty , testOptions = mempty } setupHsTestArgs :: ElaboratedConfiguredPackage -> [String] -- TODO: Does the issue #3335 affects test as well setupHsTestArgs elab = mapMaybe (showTestComponentTarget (packageId elab)) (elabTestTargets elab) setupHsBenchFlags :: ElaboratedConfiguredPackage -> ElaboratedSharedConfig -> Verbosity -> FilePath -> Cabal.BenchmarkFlags setupHsBenchFlags _ _ verbosity builddir = Cabal.BenchmarkFlags { benchmarkDistPref = toFlag builddir , benchmarkVerbosity = toFlag verbosity , benchmarkOptions = mempty } setupHsBenchArgs :: ElaboratedConfiguredPackage -> [String] setupHsBenchArgs elab = mapMaybe (showBenchComponentTarget (packageId elab)) (elabBenchTargets elab) setupHsReplFlags :: ElaboratedConfiguredPackage -> ElaboratedSharedConfig -> Verbosity -> FilePath -> Cabal.ReplFlags setupHsReplFlags _ _ verbosity builddir = Cabal.ReplFlags { replProgramPaths = mempty, --unused, set at configure time replProgramArgs = mempty, --unused, set at configure time replVerbosity = toFlag verbosity, replDistPref = toFlag builddir, replReload = mempty --only used as callback from repl } setupHsReplArgs :: ElaboratedConfiguredPackage -> [String] setupHsReplArgs elab = maybe [] (\t -> [showComponentTarget (packageId elab) t]) (elabReplTarget elab) --TODO: should be able to give multiple modules in one component setupHsCopyFlags :: ElaboratedConfiguredPackage -> ElaboratedSharedConfig -> Verbosity -> FilePath -> FilePath -> Cabal.CopyFlags setupHsCopyFlags _ _ verbosity builddir destdir = Cabal.CopyFlags { copyArgs = [], -- TODO: could use this to only copy what we enabled copyDest = toFlag (InstallDirs.CopyTo destdir), copyDistPref = toFlag builddir, copyVerbosity = toFlag verbosity } setupHsRegisterFlags :: ElaboratedConfiguredPackage -> ElaboratedSharedConfig -> Verbosity -> FilePath -> FilePath -> Cabal.RegisterFlags setupHsRegisterFlags ElaboratedConfiguredPackage{..} _ verbosity builddir pkgConfFile = Cabal.RegisterFlags { regPackageDB = mempty, -- misfeature regGenScript = mempty, -- never use regGenPkgConf = toFlag (Just pkgConfFile), regInPlace = case elabBuildStyle of BuildInplaceOnly -> toFlag True _ -> toFlag False, regPrintId = mempty, -- never use regDistPref = toFlag builddir, regArgs = [], regVerbosity = toFlag verbosity } setupHsHaddockFlags :: ElaboratedConfiguredPackage -> ElaboratedSharedConfig -> Verbosity -> FilePath -> Cabal.HaddockFlags -- TODO: reconsider whether or not Executables/TestSuites/... -- needed for component setupHsHaddockFlags (ElaboratedConfiguredPackage{..}) _ verbosity builddir = Cabal.HaddockFlags { haddockProgramPaths = mempty, --unused, set at configure time haddockProgramArgs = mempty, --unused, set at configure time haddockHoogle = toFlag elabHaddockHoogle, haddockHtml = toFlag elabHaddockHtml, haddockHtmlLocation = maybe mempty toFlag elabHaddockHtmlLocation, haddockForHackage = toFlag elabHaddockForHackage, haddockForeignLibs = toFlag elabHaddockForeignLibs, haddockExecutables = toFlag elabHaddockExecutables, haddockTestSuites = toFlag elabHaddockTestSuites, haddockBenchmarks = toFlag elabHaddockBenchmarks, haddockInternal = toFlag elabHaddockInternal, haddockCss = maybe mempty toFlag elabHaddockCss, haddockHscolour = toFlag elabHaddockHscolour, haddockHscolourCss = maybe mempty toFlag elabHaddockHscolourCss, haddockContents = maybe mempty toFlag elabHaddockContents, haddockDistPref = toFlag builddir, haddockKeepTempFiles = mempty, --TODO: from build settings haddockVerbosity = toFlag verbosity } {- setupHsTestFlags :: ElaboratedConfiguredPackage -> ElaboratedSharedConfig -> Verbosity -> FilePath -> Cabal.TestFlags setupHsTestFlags _ _ verbosity builddir = Cabal.TestFlags { } -} ------------------------------------------------------------------------------ -- * Sharing installed packages ------------------------------------------------------------------------------ -- -- Nix style store management for tarball packages -- -- So here's our strategy: -- -- We use a per-user nix-style hashed store, but /only/ for tarball packages. -- So that includes packages from hackage repos (and other http and local -- tarballs). For packages in local directories we do not register them into -- the shared store by default, we just build them locally inplace. -- -- The reason we do it like this is that it's easy to make stable hashes for -- tarball packages, and these packages benefit most from sharing. By contrast -- unpacked dir packages are harder to hash and they tend to change more -- frequently so there's less benefit to sharing them. -- -- When using the nix store approach we have to run the solver *without* -- looking at the packages installed in the store, just at the source packages -- (plus core\/global installed packages). Then we do a post-processing pass -- to replace configured packages in the plan with pre-existing ones, where -- possible. Where possible of course means where the nix-style package hash -- equals one that's already in the store. -- -- One extra wrinkle is that unless we know package tarball hashes upfront, we -- will have to download the tarballs to find their hashes. So we have two -- options: delay replacing source with pre-existing installed packages until -- the point during the execution of the install plan where we have the -- tarball, or try to do as much up-front as possible and then check again -- during plan execution. The former isn't great because we would end up -- telling users we're going to re-install loads of packages when in fact we -- would just share them. It'd be better to give as accurate a prediction as -- we can. The latter is better for users, but we do still have to check -- during plan execution because it's important that we don't replace existing -- installed packages even if they have the same package hash, because we -- don't guarantee ABI stability. -- TODO: [required eventually] for safety of concurrent installs, we must make sure we register but -- not replace installed packages with ghc-pkg. packageHashInputs :: ElaboratedSharedConfig -> ElaboratedConfiguredPackage -> PackageHashInputs packageHashInputs pkgshared elab@(ElaboratedConfiguredPackage { elabPkgSourceHash = Just srchash }) = PackageHashInputs { pkgHashPkgId = packageId elab, pkgHashComponent = case elabPkgOrComp elab of ElabPackage _ -> Nothing ElabComponent comp -> Just (compSolverName comp), pkgHashSourceHash = srchash, pkgHashPkgConfigDeps = Set.fromList (elabPkgConfigDependencies elab), pkgHashDirectDeps = case elabPkgOrComp elab of ElabPackage (ElaboratedPackage{..}) -> Set.fromList $ [ confInstId dep | dep <- CD.select relevantDeps pkgLibDependencies ] ++ [ confInstId dep | dep <- CD.select relevantDeps pkgExeDependencies ] ElabComponent comp -> Set.fromList (map confInstId (compLibDependencies comp ++ compExeDependencies comp)), pkgHashOtherConfig = packageHashConfigInputs pkgshared elab } where -- Obviously the main deps are relevant relevantDeps CD.ComponentLib = True relevantDeps (CD.ComponentSubLib _) = True relevantDeps (CD.ComponentFLib _) = True relevantDeps (CD.ComponentExe _) = True -- Setup deps can affect the Setup.hs behaviour and thus what is built relevantDeps CD.ComponentSetup = True -- However testsuites and benchmarks do not get installed and should not -- affect the result, so we do not include them. relevantDeps (CD.ComponentTest _) = False relevantDeps (CD.ComponentBench _) = False packageHashInputs _ pkg = error $ "packageHashInputs: only for packages with source hashes. " ++ display (packageId pkg) packageHashConfigInputs :: ElaboratedSharedConfig -> ElaboratedConfiguredPackage -> PackageHashConfigInputs packageHashConfigInputs ElaboratedSharedConfig{..} ElaboratedConfiguredPackage{..} = PackageHashConfigInputs { pkgHashCompilerId = compilerId pkgConfigCompiler, pkgHashPlatform = pkgConfigPlatform, pkgHashFlagAssignment = elabFlagAssignment, pkgHashConfigureScriptArgs = elabConfigureScriptArgs, pkgHashVanillaLib = elabVanillaLib, pkgHashSharedLib = elabSharedLib, pkgHashDynExe = elabDynExe, pkgHashGHCiLib = elabGHCiLib, pkgHashProfLib = elabProfLib, pkgHashProfExe = elabProfExe, pkgHashProfLibDetail = elabProfLibDetail, pkgHashProfExeDetail = elabProfExeDetail, pkgHashCoverage = elabCoverage, pkgHashOptimization = elabOptimization, pkgHashSplitObjs = elabSplitObjs, pkgHashStripLibs = elabStripLibs, pkgHashStripExes = elabStripExes, pkgHashDebugInfo = elabDebugInfo, pkgHashProgramArgs = elabProgramArgs, pkgHashExtraLibDirs = elabExtraLibDirs, pkgHashExtraFrameworkDirs = elabExtraFrameworkDirs, pkgHashExtraIncludeDirs = elabExtraIncludeDirs, pkgHashProgPrefix = elabProgPrefix, pkgHashProgSuffix = elabProgSuffix } -- | Given the 'InstalledPackageIndex' for a nix-style package store, and an -- 'ElaboratedInstallPlan', replace configured source packages by installed -- packages from the store whenever they exist. -- improveInstallPlanWithInstalledPackages :: Set UnitId -> ElaboratedInstallPlan -> ElaboratedInstallPlan improveInstallPlanWithInstalledPackages installedPkgIdSet = InstallPlan.installed canPackageBeImproved where canPackageBeImproved pkg = installedUnitId pkg `Set.member` installedPkgIdSet --TODO: sanity checks: -- * the installed package must have the expected deps etc -- * the installed package must not be broken, valid dep closure --TODO: decide what to do if we encounter broken installed packages, -- since overwriting is never safe. -- Path construction ------ -- | The path to the directory that contains a specific executable. -- NB: For inplace NOT InstallPaths.bindir installDirs; for an -- inplace build those values are utter nonsense. So we -- have to guess where the directory is going to be. -- Fortunately this is "stable" part of Cabal API. -- But the way we get the build directory is A HORRIBLE -- HACK. binDirectoryFor :: DistDirLayout -> ElaboratedSharedConfig -> ElaboratedConfiguredPackage -> FilePath -> FilePath binDirectoryFor layout config package exe = case elabBuildStyle package of BuildAndInstall -> installedBinDirectory package BuildInplaceOnly -> inplaceBinRoot layout config package </> exe -- package has been built and installed. installedBinDirectory :: ElaboratedConfiguredPackage -> FilePath installedBinDirectory = InstallDirs.bindir . elabInstallDirs -- | The path to the @build@ directory for an inplace build. inplaceBinRoot :: DistDirLayout -> ElaboratedSharedConfig -> ElaboratedConfiguredPackage -> FilePath inplaceBinRoot layout config package = distBuildDirectory layout (elabDistDirParams config package) </> "build"
themoritz/cabal
cabal-install/Distribution/Client/ProjectPlanning.hs
bsd-3-clause
156,063
0
29
46,138
20,645
11,144
9,501
2,039
20
module Main where import Lib import Data.List main :: IO () main = someFunc
tkasu/haskellbook-adventure
app/Main.hs
bsd-3-clause
78
0
6
16
27
16
11
5
1
{-# LANGUAGE Arrows #-} module Karamaan.Opaleye.Nullable where import Karamaan.Opaleye.QueryArr (QueryArr, Query) import Karamaan.Opaleye.Wire (Wire) import qualified Karamaan.Opaleye.ExprArr as E import qualified Karamaan.Opaleye.Wire as Wire import qualified Karamaan.Opaleye.Operators2 as Op2 import Control.Arrow (arr) import Database.HaskellDB.PrimQuery (UnOp(OpIsNull)) -- TODO: At the appropriate time we will replace the Nullable type -- synonym to Maybe with its own type, and then the transition to -- Nullable will be complete! -- This is just used a phantom type in 'Wire's. -- It's not actually used for values. --data Nullable a = PhantomNullable -- For now just use a type synonym. We will switch to a type later. -- Don't use Maybe in Wires in new code! type Nullable = Maybe -- TODO: perhaps this belongs elsewhere, but we need to work out how to avoid -- circular dependencies unsafeCoerce :: QueryArr (Wire a) (Wire b) unsafeCoerce = arr Wire.unsafeCoerce isNullExpr :: E.ExprArr (Wire (Nullable a)) (Wire Bool) isNullExpr = E.unOp OpIsNull "is_null" isNull :: QueryArr (Wire (Nullable a)) (Wire Bool) isNull = E.toQueryArrDef isNullExpr fromNullable :: QueryArr (Wire a, Wire (Maybe a)) (Wire a) fromNullable = proc (d, m) -> do isNull' <- isNull -< m Op2.ifThenElse -< (isNull', d, Wire.unsafeCoerce m) fromNullable' :: Query (Wire a) -> QueryArr (Wire (Nullable a)) (Wire a) fromNullable' d = proc m -> do d' <- d -< () fromNullable -< (d', m) toNullable :: QueryArr (Wire a) (Wire (Nullable a)) toNullable = unsafeCoerce
karamaan/karamaan-opaleye
Karamaan/Opaleye/Nullable.hs
bsd-3-clause
1,564
2
11
256
414
230
184
26
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE TypeSynonymInstances #-} {-| Module : Auto.BitString Description : Functions for operating on BitStrings Copyright : (c) Bo Joel Svensson, 2015 Michael Vollmer, 2015 License : GPL-3 Maintainer : Stability : experimental Portability : Some functions and data types for handling bit strings, which are arrays of booleans that represent numbers. There's a good reason to use a bit string rather than a normal int when doing local search. What is the neighborhood of an int? You could have its successor and predecessor, and maybe some others (double, half, etc). On the other hand, if we make our search space over binary numbers, the "dimensions" of our search is equal to the number of bits in the number. The neighbors of a number are all the other numbers that differ in their binary representation by one bit. -} module Auto.BitString ( BitString(..) , MultiBitString , Population , bitStringToNum , numToBitString , makeIndividual , makePopulation , flipBitAt , nthParam , nthIndividual , nthIndividualParam , crossBitString , mutateBitString ) where import Auto.Genome import Control.Monad.Random import Data.Array.Unboxed -- | A bit string data structure. -- It's an unboxed array of bools, and an int -- for the length. Of course you can get the -- length from the array, so this could be -- simplified to just a type synonym for the -- array. data BitString = BitString { str :: UArray Int Bool , len :: Int } -- | An instance of Genome for bit strings. -- The "value" you get from a bit string is an -- int. instance Genome Int BitString where toValue = bitStringToNum mutate = mutateBitStringGenome cross = crossBitStringGenome -- | An alias for a list of bit strings. type MultiBitString = [BitString] -- | An alias for a list of lists of bit strings. type Population = [MultiBitString] -- | Make a bitstring of size i. makeBitString :: Int -> BitString makeBitString i = BitString { str = array (0,i-1) [(j,False) | j <- [0..i-1]], len = i } -- | Convert bitstring to number. bitStringToNum :: BitString -> Int bitStringToNum (BitString {str}) = go $ assocs str where go [] = 0 go ((_,False):xs) = go xs go ((i,True):xs) = (2^i) + (go xs) -- | Flip bit at i in bitstring. mutateBitString :: BitString -> Int -> BitString mutateBitString (BitString {str,len}) i = BitString str' len where b = not $ str ! i str' = str // [(i,b)] mutateBitStringGenome :: (RandomGen g, Fractional f, Ord f, Random f) => g -> f -> BitString -> BitString mutateBitStringGenome g prob bstr@(BitString _ i) = if flip < prob then mutateBitString bstr bit else bstr where (bit,_) = randomR (0,i) g' (flip,g') = randomR (0.0,1.0) g -- | Crossover bitstrings arr1 and arr2. crossBitString :: BitString -> BitString -> Int -> BitString crossBitString (BitString {str=arr1, len}) (BitString {str=arr2}) i = BitString (array s l) len where s = bounds arr1 l = zipWith f (assocs arr1) (assocs arr2) f (i1,v1) (_,v2) | (i1 < i) = (i1,v1) | otherwise = (i1,v2) crossBitStringGenome :: (RandomGen g) => g -> BitString -> BitString -> BitString crossBitStringGenome g bstr1 bstr2 = crossBitString bstr1 bstr2 point where (point,_) = randomR (0, len bstr1) g -- | Convert int to list of 0s and 1s. numToBits :: Int -> [Int] numToBits 0 = [] numToBits y = let (a,b) = quotRem y 2 in [b] ++ numToBits a -- | Make bitstring of number i and length s. numToBitString :: Int -> Int -> BitString numToBitString i s = BitString (str // nstr) s where nstr = zip [0..] $ map (== 1) $ numToBits i BitString {str} = makeBitString s makeIndividual :: Int -> Int -> StdGen -> MultiBitString makeIndividual bits params g = map (flip numToBitString bits) nums where nums = take params $ randomRs (0, 2 ^ bits - 1) g makePopulation :: Int -> Int -> Int -> StdGen -> Population makePopulation 0 _ _ _ = [] makePopulation popSize bits params g = ind : restPop where (g',g'') = split g restPop = makePopulation (popSize-1) bits params g'' ind = makeIndividual bits params g' flipBitAt :: Int -> Int -> MultiBitString -> MultiBitString flipBitAt _ _ [] = [] flipBitAt b 0 (bs:bss) = newBs:bss where newBs = mutateBitString bs b flipBitAt b p (bs:bss) = bs:(flipBitAt b (p-1) bss) nthParam :: MultiBitString -> Int -> BitString nthParam = (!!) nthIndividual :: Population -> Int -> MultiBitString nthIndividual = (!!) nthIndividualParam :: Population -> Int -> Int -> BitString nthIndividualParam p i j = (p `nthIndividual` i) `nthParam` j
iu-parfunc/AutoObsidian
src/Auto/BitString.hs
bsd-3-clause
4,908
0
12
1,173
1,291
710
581
-1
-1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ViewPatterns #-} -- | Support serializing Dalvik code in SSA form. -- -- This is binary serialization and it preserves sharing. Explicit -- functions are provided (as opposed to class instances) for two -- reasons: -- -- 1) Decoupling from a specific serialization library -- -- 2) Some trickiness was required to deal with knot tying during -- deserialization. The trick did not fit in the instance declaration -- cleanly. module Dalvik.SSA.Internal.Serialize ( deserializeDex, serializeDex, -- Helpers dexFields, dexMethodRefs ) where import Control.Applicative import Control.Arrow ( first, second ) import Control.Monad ( unless ) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy.Builder as LBS import qualified Data.ByteString.Lazy as LBS import qualified Data.Foldable as F import qualified Data.HashMap.Strict as HM import Data.IntMap ( IntMap ) import qualified Data.IntMap as IM import qualified Data.List.NonEmpty as NEL import Data.Map ( Map ) import qualified Data.Map as M import Data.Maybe ( fromMaybe ) import Data.Monoid import qualified Data.Serialize as S import qualified Data.Vector as V import Prelude import Dalvik.SSA.Internal.Pretty () import Dalvik.SSA.Types formatVersion :: Int formatVersion = 1 -- | This file header is a clone of the PNG header, but with a -- different ASCII tag. fileHeader :: BS.ByteString fileHeader = LBS.toStrict $ LBS.toLazyByteString bldr where bldr = mconcat [ LBS.word8 0x89 , LBS.string8 "DLVK" , LBS.word8 0x0d , LBS.word8 0x0a , LBS.word8 0x1a , LBS.word8 0x0a ] -- | Deserialize a previously serialized Dex file from a strict 'ByteString' -- -- This operation preserves the sharing of the original dex file. deserializeDex :: BS.ByteString -> Either String DexFile deserializeDex bs = let getKnot = snd . either error id res = S.runGet (getDex (getKnot res)) bs in case res of Left err -> Left err Right (df, _) -> Right df serializeDex :: DexFile -> BS.ByteString serializeDex = S.runPut . putDex -- | A type holding state for the knot tying procedure. data Knot = Knot { knotTypeTable :: !(IntMap Type) , knotClasses :: !(IntMap Class) , knotMethods :: !(IntMap Method) , knotValues :: !(IntMap Value) , knotBlocks :: !(IntMap BasicBlock) , knotMethodRefs :: !(IntMap MethodRef) , knotFields :: !(IntMap Field) } emptyKnot :: Knot emptyKnot = Knot { knotTypeTable = IM.empty , knotClasses = IM.empty , knotMethods = IM.empty , knotValues = IM.empty , knotBlocks = IM.empty , knotMethodRefs = IM.empty , knotFields = IM.empty } -- | Format: -- -- Int (id source) -- Type list -- Constant list -- Field list -- Method ref list -- Class list putDex :: DexFile -> S.Put putDex df = do S.putByteString fileHeader S.put formatVersion S.put (dexIdSrc df) tt <- putTypeTable (dexTypes df) putList (putConstant tt) (dexConstants df) putList (putField tt) (dexFields df) putList (putMethodRef tt) (dexMethodRefs df) putList (putClass tt) (dexClasses df) putList (putAnnotations tt) (map (first classId) (HM.toList (_dexClassAnnotations df))) putList (putAnnotations tt) (map (first methodRefId . snd) (HM.toList (_dexMethodAnnotations df))) getDex :: Knot -> S.Get (DexFile, Knot) getDex fknot = do sig <- S.getByteString $ fromIntegral $ BS.length fileHeader unless (sig == fileHeader) $ fail ("Deserialize: Signature mismatch, got " ++ show sig) fv <- S.get unless (fv == formatVersion) $ fail ("Deserialize: File format mismatch, got " ++ show fv ++ " but was expecting " ++ show formatVersion) idSrc <- S.get tt <- getTypeTable constants <- getList (getConstant tt) let knot0 = emptyKnot { knotTypeTable = tt , knotValues = foldr (\c -> IM.insert (constantId c) (toValue c)) IM.empty constants } -- We don't need the method refs here, we just need to populate the -- state with them (_, knot1) <- getListAccum getField knot0 (_, knot2) <- getListAccum getMethodRef knot1 (classes, knot3) <- getListAccum (getClass fknot) knot2 let cache = foldr (\klass -> HM.insert (classType klass) klass) HM.empty classes ncache = foldr (\klass -> HM.insert (className klass) klass) HM.empty classes -- We added support for annotations after the rest of the -- serialization infrastructure was in place. Some existing data -- files exist without annotations; this check lets us safely -- deserialize them (without annotations, of course). isE <- S.isEmpty (classAnnots, methodAnnots) <- case isE of False -> do classAnnots <- getList (getClassAnnotation knot3) methodAnnots <- getList (getMethodAnnotation knot3) return (classAnnots, methodAnnots) True -> return ([], []) return (DexFile { _dexClasses = V.fromList classes , _dexConstants = V.fromList constants , _dexTypes = V.fromList (IM.elems tt) , dexIdSrc = idSrc , _dexClassesByType = cache , _dexClassesByName = ncache , _dexClassAnnotations = HM.fromList classAnnots , _dexMethodAnnotations = HM.fromList [ (mkMethodRefKey mref, (mref, annots)) | (mref, annots) <- methodAnnots ] }, knot3) where mkMethodRefKey mref = (methodRefClass mref, methodRefName mref, methodRefParameterTypes mref) putAnnotations :: Map Type Int -> (UniqueId, [VisibleAnnotation]) -> S.Put putAnnotations tt (cid, annots) = do S.put cid putList putVisibleAnnotation annots where putVisibleAnnotation :: VisibleAnnotation -> S.Put putVisibleAnnotation va = do putAnnotationVisibility (annotationVisibility va) putAnnotation tt (annotationValue va) putAnnotation :: Map Type Int -> Annotation -> S.Put putAnnotation tt a = do putType tt (annotationType a) putList putAnnotationArgument (annotationArguments a) where putAnnotationArgument (name, val) = do S.put name putAnnotationValue tt val getAnnotation :: Knot -> S.Get Annotation getAnnotation k0 = do t <- getType (knotTypeTable k0) args <- getList getAnnotationArgument return Annotation { annotationType = t , annotationArguments = args } where getAnnotationArgument = do name <- S.get v <- getAnnotationValue k0 return (name, v) putAnnotationValue :: Map Type Int -> AnnotationValue -> S.Put putAnnotationValue tt val = case val of AVInt i -> S.putWord8 0 >> S.put i AVChar c -> S.putWord8 1 >> S.put c AVFloat f -> S.putWord8 2 >> S.put f AVDouble d -> S.putWord8 3 >> S.put d AVString s -> S.putWord8 4 >> S.put s AVType t -> S.putWord8 5 >> putType tt t AVField f -> S.putWord8 6 >> S.put (fieldId f) AVMethod m -> S.putWord8 7 >> S.put (methodRefId m) AVEnum f -> S.putWord8 8 >> S.put (fieldId f) AVArray vs -> S.putWord8 9 >> putList (putAnnotationValue tt) vs AVAnnotation a -> S.putWord8 10 >> putAnnotation tt a AVNull -> S.putWord8 11 AVBool b -> S.putWord8 12 >> S.put b getAnnotationValue :: Knot -> S.Get AnnotationValue getAnnotationValue k = do tag <- S.getWord8 case tag of 0 -> AVInt <$> S.get 1 -> AVChar <$> S.get 2 -> AVFloat <$> S.get 3 -> AVDouble <$> S.get 4 -> AVString <$> S.get 5 -> AVType <$> getType (knotTypeTable k) 6 -> AVField <$> getField' k 7 -> AVMethod <$> getMethodRef' k 8 -> AVEnum <$> getField' k 9 -> AVArray <$> getList (getAnnotationValue k) 10 -> AVAnnotation <$> getAnnotation k 11 -> return AVNull 12 -> AVBool <$> S.get _ -> error ("Unknown annotation value tag while deserializing: " ++ show tag) putAnnotationVisibility :: AnnotationVisibility -> S.Put putAnnotationVisibility v = case v of AVBuild -> S.putWord8 0 AVRuntime -> S.putWord8 1 AVSystem -> S.putWord8 2 getAnnotationVisibility :: S.Get AnnotationVisibility getAnnotationVisibility = do b <- S.getWord8 case b of 0 -> return AVBuild 1 -> return AVRuntime 2 -> return AVSystem _ -> error ("Invalid annotation visibility while deserializing: " ++ show b) getClassAnnotation :: Knot -> S.Get (Class, [VisibleAnnotation]) getClassAnnotation k0 = do cls <- getClass' k0 annots <- getList (getVisibleAnnotation k0) return (cls, annots) getMethodAnnotation :: Knot -> S.Get (MethodRef, [VisibleAnnotation]) getMethodAnnotation k0 = do m <- getMethodRef' k0 annots <- getList (getVisibleAnnotation k0) return (m, annots) getVisibleAnnotation :: Knot -> S.Get VisibleAnnotation getVisibleAnnotation k0 = do vis <- getAnnotationVisibility a <- getAnnotation k0 return VisibleAnnotation { annotationVisibility = vis , annotationValue = a } getTypeTable :: S.Get (IntMap Type) getTypeTable = do lst :: [(Int, Type)] <- S.get return $ foldr (\(i, t) -> IM.insert i t) IM.empty lst putTypeTable :: [Type] -> S.PutM (Map Type Int) putTypeTable (zip [0..] -> ts) = do let m = foldr (\(i, t) -> M.insert t i) M.empty ts S.put ts return m putConstant :: Map Type Int -> Constant -> S.Put putConstant tt c = case c of ConstantInt uid i -> do S.putWord8 0 S.put uid S.put i ConstantString uid s -> do S.putWord8 1 S.put uid S.put s ConstantClass uid t -> do S.putWord8 2 S.put uid putType tt t getConstant :: IntMap Type -> S.Get Constant getConstant tt = do tag <- S.getWord8 case tag of 0 -> ConstantInt <$> S.get <*> S.get 1 -> ConstantString <$> S.get <*> S.get 2 -> do uid <- S.get t <- getType tt return $ ConstantClass uid t _ -> error ("Deserializing invalid constant tag: " ++ show tag) putType :: Map Type Int -> Type -> S.Put putType tt t = case M.lookup t tt of Just tid -> S.put tid Nothing -> error ("Serializing type with no id: " ++ show t) getType :: IntMap Type -> S.Get Type getType tt = do tid <- S.get case IM.lookup tid tt of Just t -> return t Nothing -> error ("Deserializing type with unknown id: " ++ show tid) getField' :: Knot -> S.Get Field getField' k0 = do fid <- S.get let flds = knotFields k0 case IM.lookup fid (knotFields k0) of Nothing -> error ("Deserializing field with unknown id: " ++ show (fid, IM.findMin flds, IM.findMax flds, IM.size flds)) Just f -> return f getClass' :: Knot -> S.Get Class getClass' k0 = do cid <- S.get case IM.lookup cid (knotClasses k0) of Nothing -> error ("Deserializing class with unknown id: " ++ show cid) Just cls -> return cls getMethodRef' :: Knot -> S.Get MethodRef getMethodRef' k = do mid <- S.get case IM.lookup mid (knotMethodRefs k) of Nothing -> error ("Deserializing unknown method ref id: " ++ show mid) Just mref -> return mref putClass :: Map Type Int -> Class -> S.Put putClass tt klass = do S.put (classId klass) putType tt (classType klass) S.put (className klass) S.put (classSourceName klass) S.put (classAccessFlags klass) S.putMaybeOf (putType tt) (classParent klass) S.putMaybeOf S.put (fmap classId (classParentReference klass)) S.putListOf (putType tt) (classInterfaces klass) putList (putMethod tt) (classDirectMethods klass) putList (putMethod tt) (classVirtualMethods klass) putList putAccessField (classStaticFields klass) putList putAccessField (classInstanceFields klass) getClass :: Knot -> Knot -> S.Get (Class, Knot) getClass fknot k0 = do let tt = knotTypeTable k0 cid <- S.get ct <- getType tt name <- S.get sourceName <- S.get flags <- S.get parent <- S.getMaybeOf (getType tt) mparentRefId <- S.get let classErr = error ("Unknown class parent while decoding " ++ show cid) parentRef = fmap (\p -> fromMaybe classErr $ IM.lookup p (knotClasses fknot)) mparentRefId ifaces <- S.getListOf (getType tt) (dms, k1) <- getListAccum (getMethod fknot) k0 (vms, k2) <- getListAccum (getMethod fknot) k1 sfields <- getList (getAccessField fknot) ifields <- getList (getAccessField fknot) let klass = Class { classId = cid , classType = ct , className = name , classSourceName = sourceName , classAccessFlags = flags , classParent = parent , classParentReference = parentRef , _classInterfaces = V.fromList ifaces , _classDirectMethods = V.fromList dms , _classVirtualMethods = V.fromList vms , _classStaticFields = V.fromList sfields , _classInstanceFields = V.fromList ifields , _classStaticFieldMap = indexFields sfields , _classInstanceFieldMap = indexFields ifields , _classMethodMap = indexMethods (vms ++ dms) } k3 = k2 { knotClasses = IM.insert cid klass (knotClasses k2) } return (klass, k3) where indexFields = foldr (\(_, f) -> HM.insert (fieldName f) f) HM.empty indexMethods = foldr (\m -> HM.insert (methodName m, methodSignature m) m) HM.empty putAccessField :: (AccessFlags, Field) -> S.Put putAccessField (flags, f) = S.put flags >> S.put (fieldId f) getAccessField :: Knot -> S.Get (AccessFlags, Field) getAccessField fknot = do flags <- S.get fid <- S.get let errMsg = error ("No field for id " ++ show fid) f = fromMaybe errMsg $ IM.lookup fid (knotFields fknot) return (flags, f) putField :: Map Type Int -> Field -> S.Put putField tt f = do S.put (fieldId f) S.put (fieldName f) putType tt (fieldType f) putType tt (fieldClass f) getField :: Knot -> S.Get (Field, Knot) getField k0 = do fid <- S.get name <- S.get ft <- getType tt fc <- getType tt let f = Field { fieldId = fid , fieldName = name , fieldType = ft , fieldClass = fc } k1 = k0 { knotFields = IM.insert fid f (knotFields k0) } return (f, k1) where tt = knotTypeTable k0 putMethod :: Map Type Int -> Method -> S.Put putMethod tt m = do S.put (methodId m) S.put (methodName m) putType tt (methodReturnType m) S.put (methodAccessFlags m) putList (putParameter tt) (methodParameters m) -- Encode the body as a list since that is a bit easier to decode. putList (putBlock tt) (fromMaybe [] (methodBody m)) S.put (classId (methodClass m)) getMethod :: Knot -> Knot -> S.Get (Method, Knot) getMethod fknot k0 = do mid <- S.get name <- S.get rt <- getType (knotTypeTable k0) flags <- S.get (ps, k1) <- getListAccum (getParameter fknot) k0 (b, k2) <- getListAccum (getBlock fknot) k1 cid <- S.get let errMsg = error ("No class " ++ show cid ++ " while decoding method " ++ show mid) klass = fromMaybe errMsg $ IM.lookup cid (knotClasses fknot) m = Method { methodId = mid , methodName = name , methodReturnType = rt , methodAccessFlags = flags , _methodParameters = V.fromList ps , _methodBody = if null b then Nothing else Just (V.fromList b) , methodClass = klass } k3 = k2 { knotMethods = IM.insert mid m (knotMethods k2) } return (m, k3) putParameter :: Map Type Int -> Parameter -> S.Put putParameter tt p = do S.put (parameterId p) putType tt (parameterType p) S.put (parameterName p) S.put (parameterIndex p) S.put (methodId (parameterMethod p)) getParameter :: Knot -> Knot -> S.Get (Parameter, Knot) getParameter fknot k = do pid <- S.get pt <- getType (knotTypeTable k) name <- S.get ix <- S.get mix <- S.get let errMsg = error ("No method " ++ show mix ++ " for parameter " ++ show pid) m = fromMaybe errMsg $ IM.lookup mix (knotMethods fknot) p = Parameter { parameterId = pid , parameterType = pt , parameterName = name , parameterIndex = ix , parameterMethod = m } k' = k { knotValues = IM.insert pid (toValue p) (knotValues k) } return (p, k') putBlock :: Map Type Int -> BasicBlock -> S.Put putBlock tt b = do S.put (basicBlockId b) S.put (basicBlockNumber b) putList (putInstruction tt) (basicBlockInstructions b) S.put (basicBlockPhiCount b) S.put (map basicBlockId (basicBlockSuccessors b)) S.put (map basicBlockId (basicBlockPredecessors b)) S.put (methodId (basicBlockMethod b)) getBlock :: Knot -> Knot -> S.Get (BasicBlock, Knot) getBlock fknot k0 = do bid <- S.get bnum <- S.get (is, k1) <- getListAccum (getInstruction fknot) k0 phis <- S.get sids <- S.get pids <- S.get mid <- S.get let errMsg = error ("Could not find method " ++ show mid ++ " while decoding block " ++ show bid) m = fromMaybe errMsg $ IM.lookup mid (knotMethods fknot) berrMsg i = error ("Could not translate block id " ++ show i ++ " while decoding block " ++ show bid) fromBlockId i = fromMaybe (berrMsg i) $ IM.lookup i (knotBlocks fknot) b = BasicBlock { basicBlockId = bid , basicBlockNumber = bnum , _basicBlockInstructions = V.fromList is , basicBlockPhiCount = phis , _basicBlockSuccessors = V.fromList $ map fromBlockId sids , _basicBlockPredecessors = V.fromList $ map fromBlockId pids , basicBlockMethod = m } k2 = k1 { knotBlocks = IM.insert bid b (knotBlocks k1) } return (b, k2) -- | Output the common values for each instruction, followed by a tag, -- followed by instruction-specific data. putInstruction :: Map Type Int -> Instruction -> S.Put putInstruction tt i = do S.put (instructionId i) putType tt (instructionType i) S.put (basicBlockId (instructionBasicBlock i)) case i of Return { returnValue = rv } -> do S.putWord8 0 S.put (fmap valueId rv) MoveException {} -> do S.putWord8 1 MonitorEnter { monitorReference = r } -> do S.putWord8 2 S.put (valueId r) MonitorExit { monitorReference = r } -> do S.putWord8 3 S.put (valueId r) CheckCast { castReference = r, castType = t } -> do S.putWord8 4 S.put (valueId r) putType tt t InstanceOf { instanceOfReference = r , instanceOfType = t } -> do S.putWord8 5 S.put (valueId r) putType tt t ArrayLength { arrayReference = r } -> do S.putWord8 6 S.put (valueId r) NewInstance {} -> do S.putWord8 7 NewArray { newArrayLength = len, newArrayContents = vs } -> do S.putWord8 8 S.put (valueId len) S.put (fmap (map valueId) vs) FillArray { fillArrayReference = r, fillArrayContents = is } -> do S.putWord8 9 S.put (valueId r) S.put is Throw { throwReference = r } -> do S.putWord8 10 S.put (valueId r) ConditionalBranch { branchOperand1 = op1 , branchOperand2 = op2 , branchTestType = ty , branchTarget = dest , branchFallthrough = ft } -> do S.putWord8 11 S.put (valueId op1) S.put (valueId op2) S.put ty S.put (basicBlockId dest) S.put (basicBlockId ft) UnconditionalBranch { branchTarget = bt } -> do S.putWord8 12 S.put (basicBlockId bt) Switch { switchValue = sv , switchTargets = ts , switchFallthrough = ft } -> do S.putWord8 13 S.put (valueId sv) S.put (map (second basicBlockId) ts) S.put (basicBlockId ft) Compare { compareOperation = op , compareOperand1 = op1 , compareOperand2 = op2 } -> do S.putWord8 14 S.put op S.put (valueId op1) S.put (valueId op2) UnaryOp { unaryOperand = v , unaryOperation = op } -> do S.putWord8 15 S.put (valueId v) S.put op BinaryOp { binaryOperand1 = op1 , binaryOperand2 = op2 , binaryOperation = op } -> do S.putWord8 16 S.put (valueId op1) S.put (valueId op2) S.put op ArrayGet { arrayReference = r, arrayIndex = ix } -> do S.putWord8 17 S.put (valueId r) S.put (valueId ix) ArrayPut { arrayReference = r , arrayIndex = ix , arrayPutValue = v } -> do S.putWord8 18 S.put (valueId r) S.put (valueId ix) S.put (valueId v) StaticGet { staticOpField = f } -> do S.putWord8 19 S.put (fieldId f) StaticPut { staticOpField = f, staticOpPutValue = v } -> do S.putWord8 20 S.put (fieldId f) S.put (valueId v) InstanceGet { instanceOpReference = r, instanceOpField = f } -> do S.putWord8 21 S.put (valueId r) S.put (fieldId f) InstancePut { instanceOpReference = r , instanceOpField = f , instanceOpPutValue = v } -> do S.putWord8 22 S.put (valueId r) S.put (fieldId f) S.put (valueId v) InvokeVirtual { invokeVirtualKind = k , invokeVirtualMethod = mref , invokeVirtualArguments = args } -> do S.putWord8 23 S.put k S.put (methodRefId mref) S.put $ F.toList $ fmap valueId args InvokeDirect { invokeDirectKind = k , invokeDirectMethod = mref , invokeDirectMethodDef = mdef , invokeDirectArguments = args } -> do S.putWord8 24 S.put k S.put (methodRefId mref) S.put (fmap methodId mdef) S.put (fmap valueId args) Phi { phiValues = ivs } -> do S.putWord8 25 S.put (map (\(b, v) -> (basicBlockId b, valueId v)) ivs) getInstruction :: Knot -> Knot -> S.Get (Instruction, Knot) getInstruction fknot k0 = do iid <- S.get it <- getType (knotTypeTable k0) let blockErr b = error ("No block with id " ++ show b ++ " while decoding instruction " ++ show iid) toBlock b = fromMaybe (blockErr b) $ IM.lookup b (knotBlocks fknot) valueErr v = error ("No value with id " ++ show v ++ " while decoding instruction " ++ show iid) toVal v = fromMaybe (valueErr v) $ IM.lookup v (knotValues fknot) mrefErr m = error ("No method ref with id " ++ show m ++ " while decoding instruction " ++ show iid) toMethodRef m = fromMaybe (mrefErr m) $ IM.lookup m (knotMethodRefs fknot) getValue = toVal <$> S.get getBB = toBlock <$> S.get getMRef = toMethodRef <$> S.get bb <- getBB tag <- S.getWord8 let fieldErr f = error ("No field with id " ++ show f ++ " while decoding instruction " ++ show iid ++ " tag " ++ show tag) toField f = fromMaybe (fieldErr f) $ IM.lookup f (knotFields fknot) getF = toField <$> S.get case tag of 0 -> do mrvid <- S.get let i = Return { instructionId = iid , instructionType = it , instructionBasicBlock = bb , returnValue = fmap toVal mrvid } return (i, addInstruction i k0) 1 -> do let i = MoveException { instructionId = iid , instructionType = it , instructionBasicBlock = bb } return (i, addInstruction i k0) 2 -> do r <- getValue let i = MonitorEnter { instructionId = iid , instructionType = it , instructionBasicBlock = bb , monitorReference = r } return (i, addInstruction i k0) 3 -> do r <- getValue let i = MonitorExit { instructionId = iid , instructionType = it , instructionBasicBlock = bb , monitorReference = r } return (i, addInstruction i k0) 4 -> do r <- getValue t <- getType tt let i = CheckCast { instructionId = iid , instructionType = it , instructionBasicBlock = bb , castReference = r , castType = t } return (i, addInstruction i k0) 5 -> do r <- getValue t <- getType tt let i = InstanceOf { instructionId = iid , instructionType = it , instructionBasicBlock = bb , instanceOfReference = r , instanceOfType = t } return (i, addInstruction i k0) 6 -> do r <- getValue let i = ArrayLength { instructionId = iid , instructionType = it , instructionBasicBlock = bb , arrayReference = r } return (i, addInstruction i k0) 7 -> do let i = NewInstance { instructionId = iid , instructionType = it , instructionBasicBlock = bb } return (i, addInstruction i k0) 8 -> do len <- getValue cids <- S.get let i = NewArray { instructionId = iid , instructionType = it , instructionBasicBlock = bb , newArrayLength = len , newArrayContents = fmap (map toVal) cids } return (i, addInstruction i k0) 9 -> do r <- getValue contents <- S.get let i = FillArray { instructionId = iid , instructionType = it , instructionBasicBlock = bb , fillArrayReference = r , fillArrayContents = contents } return (i, addInstruction i k0) 10 -> do r <- getValue let i = Throw { instructionId = iid , instructionType = it , instructionBasicBlock = bb , throwReference = r } return (i, addInstruction i k0) 11 -> do op1 <- getValue op2 <- getValue test <- S.get dest <- getBB fallthrough <- getBB let i = ConditionalBranch { instructionId = iid , instructionType = it , instructionBasicBlock = bb , branchOperand1 = op1 , branchOperand2 = op2 , branchTestType = test , branchTarget = dest , branchFallthrough = fallthrough } return (i, addInstruction i k0) 12 -> do t <- getBB let i = UnconditionalBranch { instructionId = iid , instructionType = it , instructionBasicBlock = bb , branchTarget = t } return (i, addInstruction i k0) 13 -> do sv <- getValue rawTs <- S.get ft <- getBB let i = Switch { instructionId = iid , instructionType = it , instructionBasicBlock = bb , switchValue = sv , switchTargets = map (second toBlock) rawTs , switchFallthrough = ft } return (i, addInstruction i k0) 14 -> do op <- S.get op1 <- getValue op2 <- getValue let i = Compare { instructionId = iid , instructionType = it , instructionBasicBlock = bb , compareOperation = op , compareOperand1 = op1 , compareOperand2 = op2 } return (i, addInstruction i k0) 15 -> do v <- getValue op <- S.get let i = UnaryOp { instructionId = iid , instructionType = it , instructionBasicBlock = bb , unaryOperand = v , unaryOperation = op } return (i, addInstruction i k0) 16 -> do op1 <- getValue op2 <- getValue op <- S.get let i = BinaryOp { instructionId = iid , instructionType = it , instructionBasicBlock = bb , binaryOperand1 = op1 , binaryOperand2 = op2 , binaryOperation = op } return (i, addInstruction i k0) 17 -> do r <- getValue ix <- getValue let i = ArrayGet { instructionId = iid , instructionType = it , instructionBasicBlock = bb , arrayReference = r , arrayIndex = ix } return (i, addInstruction i k0) 18 -> do r <- getValue ix <- getValue v <- getValue let i = ArrayPut { instructionId = iid , instructionType = it , instructionBasicBlock = bb , arrayReference = r , arrayIndex = ix , arrayPutValue = v } return (i, addInstruction i k0) 19 -> do f <- getF let i = StaticGet { instructionId = iid , instructionType = it , instructionBasicBlock = bb , staticOpField = f } return (i, addInstruction i k0) 20 -> do f <- getF v <- getValue let i = StaticPut { instructionId = iid , instructionType = it , instructionBasicBlock = bb , staticOpField = f , staticOpPutValue = v } return (i, addInstruction i k0) 21 -> do r <- getValue f <- getF let i = InstanceGet { instructionId = iid , instructionType = it , instructionBasicBlock = bb , instanceOpReference = r , instanceOpField = f } return (i, addInstruction i k0) 22 -> do r <- getValue f <- getF v <- getValue let i = InstancePut { instructionId = iid , instructionType = it , instructionBasicBlock = bb , instanceOpReference = r , instanceOpField = f , instanceOpPutValue = v } return (i, addInstruction i k0) 23 -> do k <- S.get mref <- getMRef args <- map toVal <$> S.get case NEL.nonEmpty args of Nothing -> error ("Encountered an empty argument list for InvokeVirtual at instruction " ++ show iid) Just args' -> do let i = InvokeVirtual { instructionId = iid , instructionType = it , instructionBasicBlock = bb , invokeVirtualKind = k , invokeVirtualMethod = mref , invokeVirtualArguments = args' } return (i, addInstruction i k0) 24 -> do let methodErr m = error ("No method for id " ++ show m ++ " while decoding instruction " ++ show iid) toM m = fromMaybe (methodErr m) $ IM.lookup m (knotMethods fknot) k <- S.get mref <- getMRef m <- fmap toM <$> S.get args <- map toVal <$> S.get let i = InvokeDirect { instructionId = iid , instructionType = it , instructionBasicBlock = bb , invokeDirectKind = k , invokeDirectMethod = mref , invokeDirectMethodDef = m , invokeDirectArguments = args } return (i, addInstruction i k0) 25 -> do ivs <- map (\(b, v) -> (toBlock b, toVal v)) <$> S.get let i = Phi { instructionId = iid , instructionType = it , instructionBasicBlock = bb , phiValues = ivs } return (i, addInstruction i k0) _ -> error ("Unexpected instruction tag " ++ show tag) where tt = knotTypeTable k0 {-# INLINE addInstruction #-} addInstruction :: Instruction -> Knot -> Knot addInstruction i k = k { knotValues = IM.insert (instructionId i) (toValue i) (knotValues k) } putMethodRef :: Map Type Int -> MethodRef -> S.Put putMethodRef tt mref = do S.put (methodRefId mref) putType tt (methodRefClass mref) putType tt (methodRefReturnType mref) putList (putType tt) (methodRefParameterTypes mref) S.put (methodRefName mref) getMethodRef :: Knot -> S.Get (MethodRef, Knot) getMethodRef k0 = do rid <- S.get let tt = knotTypeTable k0 ct <- getType tt rt <- getType tt pts <- getList (getType tt) name <- S.get let mref = MethodRef { methodRefId = rid , methodRefClass = ct , methodRefReturnType = rt , methodRefParameterTypes = pts , methodRefName = name } k1 = k0 { knotMethodRefs = IM.insert rid mref (knotMethodRefs k0) } return (mref, k1) putList :: (a -> S.PutM ()) -> [a] -> S.Put putList p l = do S.putWord64le (fromIntegral (length l)) mapM_ p l getList :: S.Get a -> S.Get [a] getList p = S.getWord64le >>= go [] where go lst 0 = return (reverse lst) go lst !n = do elt <- p go (elt : lst) (n - 1) getListAccum :: (k -> S.Get (a, k)) -> k -> S.Get ([a], k) getListAccum p knot0 = S.getWord64le >>= go ([], knot0) where go (lst, !k) 0 = return (reverse lst, k) go (lst, !k) !n = do (elt, k') <- p k go (elt : lst, k') (n - 1)
travitch/dalvik
src/Dalvik/SSA/Internal/Serialize.hs
bsd-3-clause
35,087
0
21
12,343
10,922
5,459
5,463
877
28
{-# LANGUAGE TemplateHaskell, ScopedTypeVariables, TypeOperators, GADTs, EmptyDataDecls #-} module Reflex.Dynamic.TH (qDyn, unqDyn) where import Reflex.Dynamic import Language.Haskell.TH import Data.Data import Control.Monad.State -- | Quote a Dynamic expression. Within the quoted expression, you can use '$(unqDyn [| x |])' to refer to any expression 'x' of type 'Dynamic t a'; the unquoted result will be of type 'a' qDyn :: Q Exp -> Q Exp qDyn qe = do e <- qe let f :: forall d. Data d => d -> StateT [(Name, Exp)] Q d f d = case eqT of Just (Refl :: d :~: Exp) | AppE (VarE m) eInner <- d , m == 'unqMarker -> do n <- lift $ newName "dyn" modify ((n, eInner):) return $ VarE n _ -> gmapM f d (e', exprsReversed) <- runStateT (gmapM f e) [] let exprs = reverse exprsReversed arg = foldr (\a b -> ConE 'FHCons `AppE` a `AppE` b) (ConE 'FHNil) $ map snd exprs param = foldr (\a b -> ConP 'HCons [VarP a, b]) (ConP 'HNil []) $ map fst exprs [| mapDyn $(return $ LamE [param] e') =<< distributeFHListOverDyn $(return arg) |] unqDyn :: Q Exp -> Q Exp unqDyn e = [| unqMarker $e |] -- | This type represents an occurrence of unqDyn before it has been processed by qDyn. If you see it in a type error, it probably means that unqDyn has been used outside of a qDyn context. data UnqDyn -- unqMarker must not be exported; it is used only as a way of smuggling data from unqDyn to qDyn --TODO: It would be much nicer if the TH AST was extensible to support this kind of thing without trickery unqMarker :: a -> UnqDyn unqMarker = error "An unqDyn expression was used outside of a qDyn expression"
bennofs/reflex
src/Reflex/Dynamic/TH.hs
bsd-3-clause
1,705
0
19
415
425
224
201
-1
-1
-- ------------------------------------------------------------ {- | Module : Yuuko.Text.XML.HXT.Arrow.Namespace Copyright : Copyright (C) 2005-2008 Uwe Schmidt License : MIT Maintainer : Uwe Schmidt ([email protected]) Stability : experimental Portability: portable namespace specific arrows -} -- ------------------------------------------------------------ module Yuuko.Text.XML.HXT.Arrow.Namespace ( attachNsEnv , cleanupNamespaces , collectNamespaceDecl , collectPrefixUriPairs , isNamespaceDeclAttr , getNamespaceDecl , processWithNsEnv , processWithNsEnvWithoutAttrl , propagateNamespaces , uniqueNamespaces , uniqueNamespacesFromDeclAndQNames , validateNamespaces ) where import Control.Arrow -- arrow classes import Yuuko.Control.Arrow.ArrowList import Yuuko.Control.Arrow.ArrowIf import Yuuko.Control.Arrow.ArrowTree import Yuuko.Control.Arrow.ListArrow import Yuuko.Text.XML.HXT.DOM.Interface import Yuuko.Text.XML.HXT.Arrow.XmlArrow import Data.Maybe ( isNothing , fromJust ) import Data.List ( nub ) -- ------------------------------------------------------------ -- | test whether an attribute node contains an XML Namespace declaration isNamespaceDeclAttr :: ArrowXml a => a XmlTree XmlTree isNamespaceDeclAttr = fromLA $ (getAttrName >>> isA isNameSpaceName) `guards` this -- | get the namespace prefix and the namespace URI out of -- an attribute tree with a namespace declaration (see 'isNamespaceDeclAttr') -- for all other nodes this arrow fails getNamespaceDecl :: ArrowXml a => a XmlTree (String, String) getNamespaceDecl = fromLA $ isNamespaceDeclAttr >>> ( ( getAttrName >>> arr getNsPrefix ) &&& xshow getChildren ) where getNsPrefix = drop 6 . qualifiedName -- drop "xmlns:" -- ------------------------------------------------------------ -- | collect all namespace declarations contained in a document -- -- apply 'getNamespaceDecl' to a whole XmlTree collectNamespaceDecl :: LA XmlTree (String, String) collectNamespaceDecl = multi getAttrl >>> getNamespaceDecl -- | collect all (namePrefix, namespaceUri) pairs from a tree -- -- all qualified names are inspected, whether a namespace uri is defined, -- for these uris the prefix and uri is returned. This arrow is useful for -- namespace cleanup, e.g. for documents generated with XSLT. It can be used -- together with 'collectNamespaceDecl' to 'cleanupNamespaces' collectPrefixUriPairs :: LA XmlTree (String, String) collectPrefixUriPairs = multi (isElem <+> getAttrl <+> isPi) >>> getQName >>> arrL getPrefixUri where getPrefixUri :: QName -> [(String, String)] getPrefixUri n | null uri = [] | px == a_xmlns || px == a_xml = [] -- these ones are reserved an predefined | otherwise = [(namePrefix n, uri)] where uri = namespaceUri n px = namePrefix n -- ------------------------------------------------------------ -- | generate unique namespaces and add all namespace declarations to the root element -- -- Calls 'cleanupNamespaces' with 'collectNamespaceDecl' uniqueNamespaces :: ArrowXml a => a XmlTree XmlTree uniqueNamespaces = fromLA $ cleanupNamespaces collectNamespaceDecl -- | generate unique namespaces and add all namespace declarations for all prefix-uri pairs in all qualified names -- -- useful for cleanup of namespaces in generated documents. -- Calls 'cleanupNamespaces' with @ collectNamespaceDecl \<+> collectPrefixUriPairs @ uniqueNamespacesFromDeclAndQNames :: ArrowXml a => a XmlTree XmlTree uniqueNamespacesFromDeclAndQNames = fromLA $ cleanupNamespaces (collectNamespaceDecl <+> collectPrefixUriPairs) -- | does the real work for namespace cleanup. -- -- The parameter is used for collecting namespace uris and prefixes from the input tree cleanupNamespaces :: LA XmlTree (String, String) -> LA XmlTree XmlTree cleanupNamespaces collectNamespaces = renameNamespaces $< (listA collectNamespaces >>^ (toNsEnv >>> nub)) where renameNamespaces :: NsEnv -> LA XmlTree XmlTree renameNamespaces env = processBottomUp ( processAttrl ( ( none `when` isNamespaceDeclAttr ) -- remove all namespace declarations >>> changeQName renamePrefix -- update namespace prefix of attribute names, if namespace uri is set ) >>> changeQName renamePrefix -- update namespace prefix of element names ) >>> attachEnv env1 -- all all namespaces as attributes to the root node attribute list where renamePrefix :: QName -> QName renamePrefix n | isNullXName uri = n | isNothing newPx = n | otherwise = setNamePrefix' (fromJust newPx) n where uri = namespaceUri' n newPx = lookup uri revEnv1 revEnv1 = map (\ (x, y) -> (y, x)) env1 env1 :: NsEnv env1 = newEnv [] uris uris :: [XName] uris = nub . map snd $ env genPrefixes :: [XName] genPrefixes = map (newXName . ("ns" ++) . show) [(0::Int)..] newEnv :: NsEnv -> [XName] -> NsEnv newEnv env' [] = env' newEnv env' (uri:rest) = newEnv env'' rest where env'' = (prefix, uri) : env' prefix = head (filter notAlreadyUsed $ preferedPrefixes ++ genPrefixes) preferedPrefixes = map fst . filter ((==uri).snd) $ env notAlreadyUsed s = isNothing . lookup s $ env' -- ------------------------------------------------------------ -- | auxiliary arrow for processing with a namespace environment -- -- process a document tree with an arrow, containing always the -- valid namespace environment as extra parameter. -- The namespace environment is implemented as a 'Yuuko.Data.AssocList.AssocList'. -- Processing of attributes can be controlled by a boolean parameter processWithNsEnv1 :: ArrowXml a => Bool -> (NsEnv -> a XmlTree XmlTree) -> NsEnv -> a XmlTree XmlTree processWithNsEnv1 withAttr f env = ifA isElem -- the test is just an optimization ( processWithExtendedEnv $< arr (extendEnv env) ) -- only element nodes contain namespace declarations ( processWithExtendedEnv env ) where processWithExtendedEnv env' = f env' -- apply the env filter >>> ( ( if withAttr then processAttrl (f env') -- apply the env to all attributes else this ) >>> processChildren (processWithNsEnv f env') -- apply the env recursively to all children ) `when` isElem -- attrl and children only need processing for elem nodes extendEnv :: NsEnv -> XmlTree -> NsEnv extendEnv env' t' = addEntries (toNsEnv newDecls) env' where newDecls = runLA ( getAttrl >>> getNamespaceDecl ) t' -- ------------------------------------------------------------ -- | process a document tree with an arrow, containing always the -- valid namespace environment as extra parameter. -- -- The namespace environment is implemented as a 'Yuuko.Data.AssocList.AssocList' processWithNsEnv :: ArrowXml a => (NsEnv -> a XmlTree XmlTree) -> NsEnv -> a XmlTree XmlTree processWithNsEnv = processWithNsEnv1 True -- | process all element nodes of a document tree with an arrow, containing always the -- valid namespace environment as extra parameter. Attribute lists are not processed. -- -- See also: 'processWithNsEnv' processWithNsEnvWithoutAttrl :: ArrowXml a => (NsEnv -> a XmlTree XmlTree) -> NsEnv -> a XmlTree XmlTree processWithNsEnvWithoutAttrl = processWithNsEnv1 False -- ----------------------------------------------------------------------------- -- | attach all valid namespace declarations to the attribute list of element nodes. -- -- This arrow is useful for document processing, that requires access to all namespace -- declarations at any element node, but which cannot be done with a simple 'processWithNsEnv'. attachNsEnv :: ArrowXml a => NsEnv -> a XmlTree XmlTree attachNsEnv initialEnv = fromLA $ processWithNsEnvWithoutAttrl attachEnv initialEnv where attachEnv :: NsEnv -> LA XmlTree XmlTree attachEnv env = ( processAttrl (none `when` isNamespaceDeclAttr) >>> addAttrl (catA nsAttrl) ) `when` isElem where nsAttrl :: [LA XmlTree XmlTree] nsAttrl = map nsDeclToAttr env nsDeclToAttr :: (XName, XName) -> LA XmlTree XmlTree nsDeclToAttr (n, uri) = mkAttr qn (txt (show uri)) where qn :: QName qn | isNullXName n = mkQName' nullXName xmlnsXName xmlnsNamespaceXName | otherwise = mkQName' xmlnsXName n xmlnsNamespaceXName -- ----------------------------------------------------------------------------- -- | -- propagate all namespace declarations \"xmlns:ns=...\" to all element and attribute nodes of a document. -- -- This arrow does not check for illegal use of namespaces. -- The real work is done by 'propagateNamespaceEnv'. -- -- The arrow may be applied repeatedly if neccessary. propagateNamespaces :: ArrowXml a => a XmlTree XmlTree propagateNamespaces = fromLA $ propagateNamespaceEnv [ (xmlXName, xmlNamespaceXName) , (xmlnsXName, xmlnsNamespaceXName) ] -- | -- attaches the namespace info given by the namespace table -- to a tag node and its attributes and children. propagateNamespaceEnv :: NsEnv -> LA XmlTree XmlTree propagateNamespaceEnv = processWithNsEnv addNamespaceUri where addNamespaceUri :: NsEnv -> LA XmlTree XmlTree addNamespaceUri env' = choiceA [ isElem :-> changeElemName (setNamespace env') , isAttr :-> attachNamespaceUriToAttr env' , isPi :-> changePiName (setNamespace env') , this :-> this ] attachNamespaceUriToAttr :: NsEnv -> LA XmlTree XmlTree attachNamespaceUriToAttr attrEnv = ( ( getQName >>> isA (not . null . namePrefix) ) `guards` changeAttrName (setNamespace attrEnv) ) `orElse` ( changeAttrName (const xmlnsQN) `when` hasName a_xmlns ) -- ----------------------------------------------------------------------------- -- | -- validate the namespace constraints in a whole tree. -- -- Result is the list of errors concerning namespaces. -- Predicates 'isWellformedQName', 'isWellformedQualifiedName', 'isDeclaredNamespace' -- and 'isWellformedNSDecl' are applied to the appropriate elements and attributes. validateNamespaces :: ArrowXml a => a XmlTree XmlTree validateNamespaces = fromLA validateNamespaces1 validateNamespaces1 :: LA XmlTree XmlTree validateNamespaces1 = choiceA [ isRoot :-> ( getChildren >>> validateNamespaces1 ) -- root is correct by definition , this :-> multi validate1Namespaces ] -- | -- a single node for namespace constrains. validate1Namespaces :: LA XmlTree XmlTree validate1Namespaces = choiceA [ isElem :-> catA [ ( getQName >>> isA ( not . isWellformedQName ) ) `guards` nsError (\ n -> "element name " ++ show n ++ " is not a wellformed qualified name" ) , ( getQName >>> isA ( not . isDeclaredNamespace ) ) `guards` nsError (\ n -> "namespace for prefix in element name " ++ show n ++ " is undefined" ) , doubleOcc $< ( (getAttrl >>> getUniversalName) >>. doubles ) , getAttrl >>> validate1Namespaces ] , isAttr :-> catA [ ( getQName >>> isA ( not . isWellformedQName ) ) `guards` nsError (\ n -> "attribute name " ++ show n ++ " is not a wellformed qualified name" ) , ( getQName >>> isA ( not . isDeclaredNamespace ) ) `guards` nsError (\ n -> "namespace for prefix in attribute name " ++ show n ++ " is undefined" ) , ( hasNamePrefix a_xmlns >>> xshow getChildren >>> isA null ) `guards` nsError (\ n -> "namespace value of namespace declaration for " ++ show n ++ " has no value" ) , ( getQName >>> isA (not . isWellformedNSDecl ) ) `guards` nsError (\ n -> "illegal namespace declaration for name " ++ n ++ " starting with reserved prefix " ++ show "xml" ) ] , isDTD :-> catA [ isDTDDoctype <+> isDTDAttlist <+> isDTDElement <+> isDTDName >>> getDTDAttrValue a_name >>> ( isA (not . isWellformedQualifiedName) `guards` nsErr (\ n -> "a DTD part contains a not wellformed qualified Name: " ++ show n) ) , isDTDAttlist >>> getDTDAttrValue a_value >>> ( isA (not . isWellformedQualifiedName) `guards` nsErr (\ n -> "an ATTLIST declaration contains as attribute name a not wellformed qualified Name: " ++ show n) ) , isDTDEntity <+> isDTDPEntity <+> isDTDNotation >>> getDTDAttrValue a_name >>> ( isA (not . isNCName) `guards` nsErr (\ n -> "an entity or notation declaration contains a not wellformed NCName: " ++ show n) ) ] , isPi :-> catA [ getName >>> ( isA (not . isNCName) `guards` nsErr (\ n -> "a PI contains a not wellformed NCName: " ++ show n) ) ] ] where nsError :: (String -> String) -> LA XmlTree XmlTree nsError msg = (getQName >>> arr show) >>> nsErr msg nsErr :: (String -> String) -> LA String XmlTree nsErr msg = arr msg >>> mkError c_err doubleOcc :: String -> LA XmlTree XmlTree doubleOcc an = nsError (\ n -> "multiple occurences of universal name for attributes of tag " ++ show n ++ " : " ++ show an ) -- ------------------------------------------------------------
nfjinjing/yuuko
src/Yuuko/Text/XML/HXT/Arrow/Namespace.hs
bsd-3-clause
13,516
316
19
3,043
2,700
1,495
1,205
221
2
{-# LANGUAGE Rank2Types, TypeSynonymInstances, QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, GADTs, FlexibleContexts #-} module Model where import Yesod import Database.Persist.GenericSql import Data.Maybe (fromJust, isJust, isNothing) import Data.Time.Clock(getCurrentTime, UTCTime(..)) import Data.Text (Text) import Model.Keys import Control.Monad.IO.Class import Yesod.Auth.HashDB (HashDBUser(..)) import Prelude data RoleType = AdminRole | DomainAdminRole | InvSideRole | RefSideRole deriving (Show, Read, Enum, Eq) derivePersistField "RoleType" type ReferenceKey = KeyT LQFBReferenceKey derivePersistField "ReferenceKey" type InviteKey = KeyT LQFBInviteKey derivePersistField "InviteKey" share [mkPersist sqlSettings, mkMigrate "migrateAll"] $(persistFile "config/models") type Database a = (MonadBaseControl IO m, Control.Monad.IO.Class.MonadIO m) => SqlPersist m a userInRole :: UserId -> RoleType -> DomainId -> Database Bool userInRole uid role domid = do r <- selectFirst [RoleUser ==. uid, RoleType ==. role, RoleDomain ==. domid] [LimitTo 1] return $ isJust r selectDomain :: Text -> Database (Maybe DomainId) selectDomain dom = do val <- selectFirst [DomainName ==. dom] [LimitTo 1] return $ maybe Nothing (Just . fst) val insertKeyset :: DomainId -> Text -> Int -> UserId -> Database KeysetId insertKeyset dom name n uid = do t <- liftIO getCurrentTime insert $ Keyset dom name n uid t False False activateKeyset :: KeysetId -> Database () activateKeyset set = update set [KeysetActive =. True] deactivateKeyset :: KeysetId -> Database () deactivateKeyset set = update set [KeysetActive =. False] keysetStats :: KeysetId -> Database (Maybe (KeysetId, (Int, Int))) keysetStats set = do kset' <- get set case (kset') of Nothing -> return Nothing Just kset -> do ks <- selectList [KeypairKeyset ==. set] [] return $ Just (set, (keysetSize kset, length ks)) selectIncompleteKeysets :: Database [KeysetId] selectIncompleteKeysets = do ksets' <- selectList [KeysetImported ==. False] [] let ksets = map fst ksets' stats <- sequence $ map keysetStats ksets return $ (map $ fst . fromJust) $ filter statsFilter stats where statsFilter Nothing = False statsFilter (Just (_, (s, l))) = l < s completeKeyset :: KeysetId -> Database Int completeKeyset set = do stats <- keysetStats set case stats of Nothing -> return 0 Just (_, (s, l)) -> do k <- getJust set let dom = keysetDomain k ids <- sequence $ replicate (s-l) $ insertRandomKeyPair dom set activateKeyset set return $ length ids completeKeysets :: Database Int completeKeysets = do iks <- selectIncompleteKeysets r <- sequence $ map completeKeyset iks return $ sum r uniqueRefKey :: DomainId -> Database ReferenceKey uniqueRefKey dom = do key <- liftIO randomKey key' <- getBy $ UniqueRefKey dom $ key case key' of Nothing -> return key Just _ -> uniqueRefKey dom uniqueInvKey :: DomainId -> Database InviteKey uniqueInvKey dom = do key <- liftIO randomKey key' <- getBy $ UniqueInvKey dom $ key case key' of Nothing -> return key Just _ -> uniqueInvKey dom randomUniqueKeyPair :: DomainId -> Database (ReferenceKey, InviteKey) randomUniqueKeyPair d = do refKey <- uniqueRefKey d invKey <- uniqueInvKey d return (refKey, invKey) insertKeyPair :: DomainId -> KeysetId -> ReferenceKey -> InviteKey -> UTCTime -> Maybe UTCTime -> Maybe UTCTime -> Maybe UserId -> Database KeypairId insertKeyPair dom set refKey invKey creation checkout deaktivated deactivatedBy = let kp = Keypair dom set refKey invKey creation checkout deaktivated deactivatedBy in insert kp insertRandomKeyPair :: DomainId -> KeysetId -> Database KeypairId insertRandomKeyPair dom set = do (refKey, invKey) <- randomUniqueKeyPair dom t <- liftIO getCurrentTime insertKeyPair dom set refKey invKey t Nothing Nothing Nothing deactivateKeys :: UserId -> [ReferenceKey] -> Database [Maybe (InviteKey, Bool)] deactivateKeys uid rks = sequence $ map (deactivateKey uid) rks lookupRefKey :: ReferenceKey -> Database (Maybe InviteKey) lookupRefKey refKey = do kp' <- selectFirst [KeypairRefKey ==. refKey] [] case (kp') of Nothing -> return Nothing Just (_, kp) -> return . Just $ keypairInvKey kp deactivateKey :: UserId -> ReferenceKey -> Database (Maybe (InviteKey, Bool)) deactivateKey uid refKey = do kp' <- selectFirst [KeypairRefKey ==. refKey] [] case (kp') of Nothing -> return Nothing Just (kpid, kp) -> do let invKey = keypairInvKey kp let checkout = isJust $ keypairCheckout kp let deactive = isJust $ keypairDeactivated kp if (not deactive) then do t <- liftIO getCurrentTime update kpid [KeypairDeactivated =. (Just t) ,KeypairDeactivatedBy =. (Just uid)] else return () return $ Just $ (invKey, checkout) checkoutKey :: DomainId -> ReferenceKey -> Database (Maybe InviteKey) checkoutKey dom refKey = do k' <- getBy $ UniqueRefKey dom refKey case k' of Nothing -> return Nothing Just (kid, k) -> do let set' = (keypairKeyset k) set <- getJust set' if (or [isJust $ keypairCheckout k ,isJust $ keypairDeactivated k ,not $ keysetActive set]) then return Nothing else do t <- liftIO getCurrentTime update kid [KeypairCheckout =. (Just t)] return $ Just $ keypairInvKey k cleanupKeys :: DomainId -> [InviteKey] -> Database [Maybe ReferenceKey] cleanupKeys dom invKeys = sequence $ map (cleanupKey dom) invKeys cleanupKey :: DomainId -> InviteKey -> Database (Maybe ReferenceKey) cleanupKey dom invKey = do key' <- getBy $ UniqueInvKey dom invKey case key' of Nothing -> return Nothing Just (_, key) -> do return $ Just $ keypairRefKey key instance HashDBUser (UserGeneric b) where userPasswordHash = userPassword userPasswordSalt = userSalt setSaltAndPasswordHash s h u = u { userSalt = Just s , userPassword = Just h }
alios/clearingstelle
Model.hs
bsd-3-clause
6,475
0
19
1,646
2,101
1,032
1,069
159
3
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Dimensions.EL ( allDimensions ) where import Duckling.Dimensions.Types allDimensions :: [Seal Dimension] allDimensions = [ Seal Duration , Seal Numeral , Seal Ordinal , Seal Time ]
facebookincubator/duckling
Duckling/Dimensions/EL.hs
bsd-3-clause
420
0
6
80
63
38
25
9
1
module Main where {- You should be able to pass as many .wav files as you like to this program and it should be able to parse them all and show their information on STDOUT. You should start by implementing a verbose mode by default and then you can consider implementing a quiet mode. You should have such data as: - Audio Format - Bit Rate - Calculated length of audio in seconds (or even hours, minutes, seconds) - Name of the file and name of the piece in the info section - Absolutely everything from the info section of the file -} import System.Environment (getArgs) import Data.Either (partitionEithers) import Data.List (intersperse, null) import Control.Monad (when) import qualified Data.ByteString.Lazy as BL import Sound.Wav main = do files <- getArgs if null files then putStrLn "No files were given, nothing was parsed." else mapM decodeWaveFileOrFail files >>= handleData files handleData :: [FilePath] -> [Either (ByteOffset, String) WaveFile] -> IO () handleData files parseData = do mapM_ handleError $ zip files errors sequence_ . spreadNewlines . fmap displayWaveFile $ zip files results where (errors, results) = partitionEithers parseData spreadNewlines :: [IO ()] -> [IO ()] spreadNewlines = intersperse $ putStrLn "" handleError :: (FilePath, (ByteOffset, String)) -> IO () handleError (filename, (offset, errorMessage)) = do putStrLn $ "Error parsing: " ++ filename putStrLn $ " " ++ errorMessage displayWaveFile :: (FilePath, WaveFile) -> IO () displayWaveFile (filename, file) = do displayName filename file putStr " - " displayTime . audioTime $ file putStrLn "" displayFormatSection . waveFormat $ file putStrLn "" displayInfoSection . waveInfo $ file displayName :: String -> WaveFile -> IO () displayName filename file = case name $ getInfoData file of Nothing -> putStr $ "File: " ++ filename Just name -> putStr $ name ++ " (" ++ filename ++ ")" -- TODO copied from elsewhere, common code divRoundUp :: Integral a => a -> a -> a divRoundUp a b = res + signum rem where (res, rem) = a `divMod` b displayTime :: (Integer, Integer, Integer) -> IO () displayTime (hours, minutes, seconds) = do when isHours $ putStr (show hours ++ "h") when isMinutes $ putStr (show minutes ++ "m") when (isSeconds || not (isHours && isMinutes)) $ putStr (show seconds ++ "s") where isHours = hours /= 0 isMinutes = minutes /= 0 isSeconds = seconds /= 0 audioTime :: WaveFile -> (Integer, Integer, Integer) audioTime file = (hours, minutes, seconds) where totalSeconds = countSamples file `divRoundUp` fromIntegral (waveSampleRate format) (totalMinutes, seconds) = totalSeconds `divMod` 60 (hours, minutes) = totalMinutes `divMod` 60 format = waveFormat file countSamples :: WaveFile -> Integer countSamples waveFile = (fromIntegral . BL.length . waveData $ waveFile) `div` factor where format = waveFormat waveFile numChannels :: Integer numChannels = fromIntegral . waveNumChannels $ format bytesPerSample :: Integer bytesPerSample = flip div 8 . fromIntegral . waveBitsPerSample $ format factor = numChannels * bytesPerSample prefix = (" " ++) displayFormatSection :: WaveFormat -> IO () displayFormatSection format = do putStrLn " Format" putStrLn $ prefix "Audio Format: \t" ++ (prettyShowAudioFormat . waveAudioFormat $ format) putStrLn $ prefix "Channels: \t\t" ++ (show . waveNumChannels $ format) putStrLn $ prefix "Sample Rate: \t" ++ (show . waveSampleRate $ format) putStrLn $ prefix "Bits Per Sample: \t" ++ (show . waveBitsPerSample $ format) putStrLn $ prefix "Byte Rate: \t" ++ (show . waveByteRate $ format) putStrLn $ prefix "Block Alignment: \t" ++ (show . waveBlockAlignment $ format) infoHeader = " INFO Metadata" displayInfoSection :: Maybe WaveInfo -> IO () displayInfoSection Nothing = putStrLn $ infoHeader ++ " (None Present in File)" displayInfoSection (Just infoData) = do putStrLn infoHeader pp archiveLocation "Archive Location" pp artist "Artist" pp commissionedBy "Comissioned By" pp comments "Comments" ppList copyrights "Copyrights" pp creationDate "Creation Date" pp croppedDetails "Cropped Details" pp originalDimensions "Original Dimensions" ppShow dotsPerInch "Dots Per Inch" ppList engineers "Engineers" pp genre "Genre" ppList keywords "Keywords" pp lightness "Lightness" pp originalMedium "Original Medium" ppShow coloursInPalette "Colours in Palette" pp originalProduct "Original Product" pp subject "Subject" pp creationSoftware "Creation Software" pp sharpness "Sharpness" pp contentSource "Content Source" pp originalForm "Original Form" pp technician "Technician" where pp = prettyShowInfo infoData ppList = prettyShowListInfo infoData ppShow = prettyShowConvert infoData prettyShowConvert :: (Show a) => WaveInfo -> (WaveInfo -> Maybe a) -> String -> IO () prettyShowConvert chunk convert prefixWords = displayIfPresent (convert chunk) $ \showData -> do putStr $ prefix prefixWords putStr ": " print showData prettyShowInfo :: WaveInfo -> (WaveInfo -> Maybe String) -> String -> IO () prettyShowInfo chunk convert prefixWords = displayIfPresent (convert chunk) $ \showData -> do putStr $ prefix prefixWords putStr ": " putStrLn showData prettyShowListInfo :: WaveInfo -> (WaveInfo -> Maybe [String]) -> String -> IO () prettyShowListInfo chunk convert prefixWords = displayIfPresent (convert chunk) $ \showData -> do putStr $ prefix prefixWords putStr ": " sequence_ $ fmap (\x -> putStrLn $ prefix " - " ++ x) showData displayIfPresent :: (Show a) => Maybe a -> (a -> IO ()) -> IO () displayIfPresent Nothing _ = return () displayIfPresent (Just x) f = f x
CIFASIS/wavy
src/Info.hs
bsd-3-clause
6,003
0
15
1,328
1,712
842
870
124
2
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-| This module contains the core Heist data types. Edward Kmett wrote most of the HeistT monad code and associated instances, liberating us from the unused writer portion of RWST. -} module Heist.Internal.Types.HeistState where ------------------------------------------------------------------------------ import Blaze.ByteString.Builder (Builder) import Control.Applicative (Alternative (..)) import Control.Arrow (first) import Control.Monad (MonadPlus (..), ap) import Control.Monad.Base import Control.Monad.Cont (MonadCont (..)) #if MIN_VERSION_mtl(2,2,1) import Control.Monad.Except (MonadError (..)) #else import Control.Monad.Error (MonadError (..)) #endif import Control.Monad.Fix (MonadFix (..)) import Control.Monad.Reader (MonadReader (..)) import Control.Monad.State.Strict (MonadState (..), StateT) import Control.Monad.Trans (MonadIO (..), MonadTrans (..)) import Control.Monad.Trans.Control import Data.ByteString.Char8 (ByteString) import Data.DList (DList) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as H import Data.HeterogeneousEnvironment (HeterogeneousEnvironment) import qualified Data.HeterogeneousEnvironment as HE import Data.Map.Syntax import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8) #if MIN_VERSION_base (4,7,0) import Data.Typeable (Typeable) #else import Data.Typeable (TyCon, Typeable(..), Typeable1(..), mkTyCon, mkTyConApp) #endif #if !MIN_VERSION_base(4,8,0) import Control.Applicative (Applicative (..), (<$>)) import Data.Monoid (Monoid(..)) #endif import qualified Text.XmlHtml as X ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | Convenient type alies for splices. type Splices s = MapSyntax Text s ------------------------------------------------------------------------------ -- | A 'Template' is a forest of XML nodes. Here we deviate from the \"single -- root node\" constraint of well-formed XML because we want to allow -- templates to contain document fragments that may not have a single root. type Template = [X.Node] ------------------------------------------------------------------------------ -- | MIME Type. The type alias is here to make the API clearer. type MIMEType = ByteString ------------------------------------------------------------------------------ -- | Reversed list of directories. This holds the path to the template -- currently being processed. type TPath = [ByteString] ------------------------------------------------------------------------------ -- | Holds data about templates read from disk. data DocumentFile = DocumentFile { dfDoc :: X.Document , dfFile :: Maybe FilePath } deriving ( Eq, Show #if MIN_VERSION_base(4,7,0) , Typeable #endif ) ------------------------------------------------------------------------------ -- | Designates whether a document should be treated as XML or HTML. data Markup = Xml | Html ------------------------------------------------------------------------------ -- | Monad used for runtime splice execution. newtype RuntimeSplice m a = RuntimeSplice { unRT :: StateT HeterogeneousEnvironment m a } deriving ( Applicative , Functor , Monad , MonadIO , MonadState HeterogeneousEnvironment , MonadTrans #if MIN_VERSION_base(4,7,0) , Typeable #endif ) ------------------------------------------------------------------------------ instance (Monad m, Monoid a) => Monoid (RuntimeSplice m a) where mempty = return mempty a `mappend` b = do !x <- a !y <- b return $! x `mappend` y ------------------------------------------------------------------------------ -- | Opaque type representing pieces of output from compiled splices. data Chunk m = Pure !ByteString -- ^ output known at load time | RuntimeHtml !(RuntimeSplice m Builder) -- ^ output computed at run time | RuntimeAction !(RuntimeSplice m ()) -- ^ runtime action used only for its side-effect #if MIN_VERSION_base(4,7,0) deriving Typeable #endif instance Show (Chunk m) where show (Pure _) = "Pure" show (RuntimeHtml _) = "RuntimeHtml" show (RuntimeAction _) = "RuntimeAction" showChunk :: Chunk m -> String showChunk (Pure b) = T.unpack $ decodeUtf8 b showChunk (RuntimeHtml _) = "RuntimeHtml" showChunk (RuntimeAction _) = "RuntimeAction" isPureChunk :: Chunk m -> Bool isPureChunk (Pure _) = True isPureChunk _ = False ------------------------------------------------------------------------------ -- | Type alias for attribute splices. The function parameter is the value of -- the bound attribute splice. The return value is a list of attribute -- key/value pairs that get substituted in the place of the bound attribute. type AttrSplice m = Text -> RuntimeSplice m [(Text, Text)] ------------------------------------------------------------------------------ -- | Holds all the state information needed for template processing. You will -- build a @HeistState@ using 'initHeist' and any of Heist's @HeistState -> -- HeistState@ \"filter\" functions. Then you use the resulting @HeistState@ -- in calls to 'renderTemplate'. -- -- m is the runtime monad data HeistState m = HeistState { -- | A mapping of splice names to splice actions _spliceMap :: HashMap Text (HeistT m m Template) -- | A mapping of template names to templates , _templateMap :: HashMap TPath DocumentFile -- | A mapping of splice names to splice actions , _compiledSpliceMap :: HashMap Text (HeistT m IO (DList (Chunk m))) -- | A mapping of template names to templates --, _compiledTemplateMap :: HashMap TPath (m Builder, MIMEType) , _compiledTemplateMap :: !(HashMap TPath ([Chunk m], MIMEType)) , _attrSpliceMap :: HashMap Text (AttrSplice m) -- | A flag to control splice recursion , _recurse :: Bool -- | The path to the template currently being processed. , _curContext :: TPath -- | A counter keeping track of the current recursion depth to prevent -- infinite loops. , _recursionDepth :: Int -- | The doctypes encountered during template processing. , _doctypes :: [X.DocType] -- | The full path to the current template's file on disk. , _curTemplateFile :: Maybe FilePath -- | A key generator used to produce new unique Promises. , _keygen :: HE.KeyGen -- | Flag indicating whether we're in preprocessing mode. During -- preprocessing, errors should stop execution and be reported. During -- template rendering, it's better to skip the errors and render the page. , _preprocessingMode :: Bool -- | This is needed because compiled templates are generated with a bunch -- of calls to renderFragment rather than a single call to render. , _curMarkup :: Markup -- | A prefix for all splices (namespace ++ ":"). , _splicePrefix :: Text -- | List of errors encountered during splice processing. , _spliceErrors :: [Text] -- | Whether to throw an error when a tag wih the heist namespace does not -- correspond to a bound splice. When not using a namespace, this flag is -- ignored. , _errorNotBound :: Bool , _numNamespacedTags :: Int #if MIN_VERSION_base(4,7,0) } deriving (Typeable) #else } #endif #if !MIN_VERSION_base(4,7,0) -- NOTE: We got rid of the Monoid instance because it is absolutely not safe -- to combine two compiledTemplateMaps. All compiled templates must be known -- at load time and processed in a single call to initHeist/loadTemplates or -- whatever we end up calling it.. instance (Typeable1 m) => Typeable (HeistState m) where typeOf _ = mkTyConApp templateStateTyCon [typeOf1 (undefined :: m ())] #endif ------------------------------------------------------------------------------ -- | HeistT is the monad transformer used for splice processing. HeistT -- intentionally does not expose any of its functionality via MonadState or -- MonadReader functions. We define passthrough instances for the most common -- types of monads. These instances allow the user to use HeistT in a monad -- stack without needing calls to `lift`. -- -- @n@ is the runtime monad (the parameter to HeistState). -- -- @m@ is the monad being run now. In this case, \"now\" is a variable -- concept. The type @HeistT n n@ means that \"now\" is runtime. The type -- @HeistT n IO@ means that \"now\" is @IO@, and more importantly it is NOT -- runtime. In Heist, the rule of thumb is that @IO@ means load time and @n@ -- means runtime. newtype HeistT n m a = HeistT { runHeistT :: X.Node -> HeistState n -> m (a, HeistState n) #if MIN_VERSION_base(4,7,0) } deriving Typeable #else } #endif ------------------------------------------------------------------------------ -- | Gets the names of all the templates defined in a HeistState. templateNames :: HeistState m -> [TPath] templateNames ts = H.keys $ _templateMap ts ------------------------------------------------------------------------------ -- | Gets the names of all the templates defined in a HeistState. compiledTemplateNames :: HeistState m -> [TPath] compiledTemplateNames ts = H.keys $ _compiledTemplateMap ts ------------------------------------------------------------------------------ -- | Gets the names of all the interpreted splices defined in a HeistState. spliceNames :: HeistState m -> [Text] spliceNames ts = H.keys $ _spliceMap ts ------------------------------------------------------------------------------ -- | Gets the names of all the compiled splices defined in a HeistState. compiledSpliceNames :: HeistState m -> [Text] compiledSpliceNames ts = H.keys $ _compiledSpliceMap ts #if !MIN_VERSION_base(4,7,0) ------------------------------------------------------------------------------ -- | The Typeable instance is here so Heist can be dynamically executed with -- Hint. templateStateTyCon :: TyCon templateStateTyCon = mkTyCon "Heist.HeistState" {-# NOINLINE templateStateTyCon #-} #endif ------------------------------------------------------------------------------ -- | Evaluates a template monad as a computation in the underlying monad. evalHeistT :: (Monad m) => HeistT n m a -> X.Node -> HeistState n -> m a evalHeistT m r s = do (a, _) <- runHeistT m r s return a {-# INLINE evalHeistT #-} ------------------------------------------------------------------------------ -- | Functor instance instance Functor m => Functor (HeistT n m) where fmap f (HeistT m) = HeistT $ \r s -> first f <$> m r s ------------------------------------------------------------------------------ -- | Applicative instance instance (Monad m, Functor m) => Applicative (HeistT n m) where pure = return (<*>) = ap ------------------------------------------------------------------------------ -- | Monad instance instance Monad m => Monad (HeistT n m) where return a = HeistT (\_ s -> return (a, s)) {-# INLINE return #-} HeistT m >>= k = HeistT $ \r s -> do (a, s') <- m r s runHeistT (k a) r s' {-# INLINE (>>=) #-} ------------------------------------------------------------------------------ -- | MonadIO instance instance MonadIO m => MonadIO (HeistT n m) where liftIO = lift . liftIO ------------------------------------------------------------------------------ -- | MonadTrans instance instance MonadTrans (HeistT n) where lift m = HeistT $ \_ s -> do a <- m return (a, s) instance MonadBase b m => MonadBase b (HeistT n m) where liftBase = lift . liftBase #if MIN_VERSION_monad_control(1,0,0) instance MonadTransControl (HeistT n) where type StT (HeistT n) a = (a, HeistState n) liftWith f = HeistT $ \n s -> do res <- f $ \(HeistT g) -> g n s return (res, s) restoreT k = HeistT $ \_ _ -> k {-# INLINE liftWith #-} {-# INLINE restoreT #-} instance MonadBaseControl b m => MonadBaseControl b (HeistT n m) where type StM (HeistT n m) a = ComposeSt (HeistT n) m a liftBaseWith = defaultLiftBaseWith restoreM = defaultRestoreM {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} #else instance MonadTransControl (HeistT n) where newtype StT (HeistT n) a = StHeistT {unStHeistT :: (a, HeistState n)} liftWith f = HeistT $ \n s -> do res <- f $ \(HeistT g) -> liftM StHeistT $ g n s return (res, s) restoreT k = HeistT $ \_ _ -> liftM unStHeistT k {-# INLINE liftWith #-} {-# INLINE restoreT #-} instance MonadBaseControl b m => MonadBaseControl b (HeistT n m) where newtype StM (HeistT n m) a = StMHeist {unStMHeist :: ComposeSt (HeistT n) m a} liftBaseWith = defaultLiftBaseWith StMHeist restoreM = defaultRestoreM unStMHeist {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} #endif ------------------------------------------------------------------------------ -- | MonadFix passthrough instance instance MonadFix m => MonadFix (HeistT n m) where mfix f = HeistT $ \r s -> mfix $ \ (a, _) -> runHeistT (f a) r s ------------------------------------------------------------------------------ -- | Alternative passthrough instance instance (Functor m, MonadPlus m) => Alternative (HeistT n m) where empty = mzero (<|>) = mplus ------------------------------------------------------------------------------ -- | MonadPlus passthrough instance instance MonadPlus m => MonadPlus (HeistT n m) where mzero = lift mzero m `mplus` n = HeistT $ \r s -> runHeistT m r s `mplus` runHeistT n r s ------------------------------------------------------------------------------ -- | MonadState passthrough instance instance MonadState s m => MonadState s (HeistT n m) where get = lift get {-# INLINE get #-} put = lift . put {-# INLINE put #-} ------------------------------------------------------------------------------ -- | MonadReader passthrough instance instance MonadReader r m => MonadReader r (HeistT n m) where ask = HeistT $ \_ s -> do r <- ask return (r,s) local f (HeistT m) = HeistT $ \r s -> local f (m r s) ------------------------------------------------------------------------------ -- | Helper for MonadError instance. _liftCatch :: (m (a,HeistState n) -> (e -> m (a,HeistState n)) -> m (a,HeistState n)) -> HeistT n m a -> (e -> HeistT n m a) -> HeistT n m a _liftCatch ce m h = HeistT $ \r s -> (runHeistT m r s `ce` (\e -> runHeistT (h e) r s)) ------------------------------------------------------------------------------ -- | MonadError passthrough instance instance (MonadError e m) => MonadError e (HeistT n m) where throwError = lift . throwError catchError = _liftCatch catchError ------------------------------------------------------------------------------ -- | Helper for MonadCont instance. _liftCallCC :: ((((a,HeistState n) -> m (b, HeistState n)) -> m (a, HeistState n)) -> m (a, HeistState n)) -> ((a -> HeistT n m b) -> HeistT n m a) -> HeistT n m a _liftCallCC ccc f = HeistT $ \r s -> ccc $ \c -> runHeistT (f (\a -> HeistT $ \_ _ -> c (a, s))) r s ------------------------------------------------------------------------------ -- | MonadCont passthrough instance instance (MonadCont m) => MonadCont (HeistT n m) where callCC = _liftCallCC callCC #if !MIN_VERSION_base(4,7,0) ------------------------------------------------------------------------------ -- | The Typeable instance is here so Heist can be dynamically executed with -- Hint. templateMonadTyCon :: TyCon templateMonadTyCon = mkTyCon "Heist.HeistT" {-# NOINLINE templateMonadTyCon #-} instance (Typeable1 m) => Typeable1 (HeistT n m) where typeOf1 _ = mkTyConApp templateMonadTyCon [typeOf1 (undefined :: m ())] #endif ------------------------------------------------------------------------------ -- Functions for our monad. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | Gets the node currently being processed. -- -- > <speech author="Shakespeare"> -- > To sleep, perchance to dream. -- > </speech> -- -- When you call @getParamNode@ inside the code for the @speech@ splice, it -- returns the Node for the @speech@ tag and its children. @getParamNode >>= -- childNodes@ returns a list containing one 'TextNode' containing part of -- Hamlet's speech. @liftM (getAttribute \"author\") getParamNode@ would -- return @Just \"Shakespeare\"@. getParamNode :: Monad m => HeistT n m X.Node getParamNode = HeistT $ curry return {-# INLINE getParamNode #-} ------------------------------------------------------------------------------ -- | HeistT's 'local'. localParamNode :: Monad m => (X.Node -> X.Node) -> HeistT n m a -> HeistT n m a localParamNode f m = HeistT $ \r s -> runHeistT m (f r) s {-# INLINE localParamNode #-} ------------------------------------------------------------------------------ -- | HeistT's 'gets'. getsHS :: Monad m => (HeistState n -> r) -> HeistT n m r getsHS f = HeistT $ \_ s -> return (f s, s) {-# INLINE getsHS #-} ------------------------------------------------------------------------------ -- | HeistT's 'get'. getHS :: Monad m => HeistT n m (HeistState n) getHS = HeistT $ \_ s -> return (s, s) {-# INLINE getHS #-} ------------------------------------------------------------------------------ -- | HeistT's 'put'. putHS :: Monad m => HeistState n -> HeistT n m () putHS s = HeistT $ \_ _ -> return ((), s) {-# INLINE putHS #-} ------------------------------------------------------------------------------ -- | HeistT's 'modify'. modifyHS :: Monad m => (HeistState n -> HeistState n) -> HeistT n m () modifyHS f = HeistT $ \_ s -> return ((), f s) {-# INLINE modifyHS #-} ------------------------------------------------------------------------------ -- | Restores the HeistState. This function is almost like putHS except it -- preserves the current doctypes and splice errors. You should use this -- function instead of @putHS@ to restore an old state. This was needed -- because doctypes needs to be in a "global scope" as opposed to the template -- call "local scope" of state items such as recursionDepth, curContext, and -- spliceMap. restoreHS :: Monad m => HeistState n -> HeistT n m () restoreHS old = modifyHS (\cur -> old { _doctypes = _doctypes cur , _spliceErrors = _spliceErrors cur }) {-# INLINE restoreHS #-} ------------------------------------------------------------------------------ -- | Abstracts the common pattern of running a HeistT computation with -- a modified heist state. localHS :: Monad m => (HeistState n -> HeistState n) -> HeistT n m a -> HeistT n m a localHS f k = do ts <- getHS putHS $ f ts res <- k restoreHS ts return res {-# INLINE localHS #-} ------------------------------------------------------------------------------ -- | Modifies the recursion depth. modRecursionDepth :: Monad m => (Int -> Int) -> HeistT n m () modRecursionDepth f = modifyHS (\st -> st { _recursionDepth = f (_recursionDepth st) }) ------------------------------------------------------------------------------ -- | Increments the namespaced tag count incNamespacedTags :: Monad m => HeistT n m () incNamespacedTags = modifyHS (\st -> st { _numNamespacedTags = _numNamespacedTags st + 1 }) ------------------------------------------------------------------------------ -- | AST to hold attribute parsing structure. This is necessary because -- attoparsec doesn't support parsers running in another monad. data AttAST = Literal Text | Ident Text deriving (Show) ------------------------------------------------------------------------------ isIdent :: AttAST -> Bool isIdent (Ident _) = True isIdent _ = False
sopvop/heist
src/Heist/Internal/Types/HeistState.hs
bsd-3-clause
21,473
0
17
4,769
3,550
1,988
1,562
263
1
{- Fastest when compiled as follows: ghc -O2 -optc-O3 -funbox-strict-fields -} ----------------------------------------------------------------------------- -- | -- Module : Data.SuffixTree -- Copyright : (c) Bryan O'Sullivan 2007 -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- A lazy, efficient suffix tree implementation. -- -- Since many function names (but not the type name) clash with -- "Prelude" names, this module is usually imported @qualified@, e.g. -- -- > import Data.SuffixTree (STree) -- > import qualified Data.SuffixTree as T -- -- The implementation is based on the first of those described in the -- following paper: -- -- * Robert Giegerich and Stefan Kurtz, \"/A comparison of -- imperative and purely functional suffix tree constructions/\", -- Science of Computer Programming 25(2-3):187-218, 1995, -- <http://citeseer.ist.psu.edu/giegerich95comparison.html> -- -- This implementation constructs the suffix tree lazily, so subtrees -- are not created until they are traversed. Two construction -- functions are provided, 'constructWith' for sequences composed of -- small alphabets, and 'construct' for larger alphabets. -- -- Estimates are given for performance. The value /k/ is a constant; -- /n/ is the length of a query string; and /t/ is the number of -- elements (nodes and leaves) in a suffix tree. module Data.SuffixTree ( -- * Types Alphabet , Edge , Prefix , STree(..) -- * Construction , constructWith , construct -- * Querying , elem , findEdge , findTree , findPath , countLeaves , countRepeats -- * Traversal , foldr , foldl , fold -- * Other useful functions , mkPrefix , prefix , suffixes ) where import Prelude hiding (elem, foldl, foldr) import qualified Data.Map as M import Control.Arrow (second) import qualified Data.ByteString as SB import qualified Data.ByteString.Lazy as LB import qualified Data.List as L import Data.Maybe (listToMaybe, mapMaybe) -- | The length of a prefix list. This type is formulated to do cheap -- work eagerly (to avoid constructing a pile of deferred thunks), -- while deferring potentially expensive work (computing the length of -- a list). data Length a = Exactly {-# UNPACK #-} !Int | Sum {-# UNPACK #-} !Int [a] deriving (Show) -- | The list of symbols that 'constructWith' can possibly see in its -- input. type Alphabet a = [a] -- | The prefix string associated with an 'Edge'. Use 'mkPrefix' to -- create a value of this type, and 'prefix' to deconstruct one. newtype Prefix a = Prefix ([a], Length a) instance (Eq a) => Eq (Prefix a) where a == b = prefix a == prefix b instance (Ord a) => Ord (Prefix a) where compare a b = compare (prefix a) (prefix b) instance (Show a) => Show (Prefix a) where show a = "mkPrefix " ++ show (prefix a) type EdgeFunction a = [[a]] -> (Length a, [[a]]) -- | An edge in the suffix tree. type Edge a = (Prefix a, STree a) -- | /O(1)/. Construct a 'Prefix' value. mkPrefix :: [a] -> Prefix a mkPrefix xs = Prefix (xs, Sum 0 xs) pmap :: (a -> b) -> Prefix a -> Prefix b pmap f = mkPrefix . map f . prefix instance Functor Prefix where fmap = pmap -- | The suffix tree type. The implementation is exposed to ease the -- development of custom traversal functions. Note that @('Prefix' a, -- 'STree' a)@ pairs are not stored in any order. data STree a = Node [Edge a] | Leaf deriving (Show) smap :: (a -> b) -> STree a -> STree b smap _ Leaf = Leaf smap f (Node es) = Node (map (\(p, t) -> (fmap f p, smap f t)) es) instance Functor STree where fmap = smap -- | /O(n)/. Obtain the list stored in a 'Prefix'. prefix :: Prefix a -> [a] prefix (Prefix (ys, Exactly n)) = take n ys prefix (Prefix (ys, Sum n xs)) = tk n ys where tk 0 ys = zipWith (const id) xs ys tk n (y:ys) = y : tk (n-1) ys -- | /O(t)/. Folds the edges in a tree, using post-order traversal. -- Suitable for lazy use. foldr :: (Prefix a -> b -> b) -> b -> STree a -> b foldr _ z Leaf = z foldr f z (Node es) = L.foldr (\(p,t) v -> f p (foldr f v t)) z es -- | /O(t)/. Folds the edges in a tree, using pre-order traversal. The -- step function is evaluated strictly. foldl :: (a -> Prefix b -> a) -- ^ step function (evaluated strictly) -> a -- ^ initial state -> STree b -> a foldl _ z Leaf = z foldl f z (Node es) = L.foldl' (\v (p,t) -> f (foldl f v t) p) z es -- | /O(t)/. Generic fold over a tree. -- -- A few simple examples. -- -- >countLeaves == fold id id (const const) (1+) 0 -- -- >countEdges = fold id id (\_ a _ -> a+1) id 0 -- -- This more complicated example generates a tree of the same shape, -- but new type, with annotated leaves. -- -- @ --data GenTree a b = GenNode [('Prefix' a, GenTree a b)] -- | GenLeaf b -- deriving ('Show') -- @ -- -- @ --gentree :: 'STree' a -> GenTree a Int --gentree = 'fold' reset id fprefix reset leaf -- where leaf = GenLeaf 1 -- reset = 'const' leaf -- fprefix p t (GenLeaf _) = GenNode [(p, t)] -- fprefix p t (GenNode es) = GenNode ((p, t):es) -- @ fold :: (a -> a) -- ^ downwards state transformer -> (a -> a) -- ^ upwards state transformer -> (Prefix b -> a -> a -> a) -- ^ edge state transformer -> (a -> a) -- ^ leaf state transformer -> a -- ^ initial state -> STree b -- ^ tree -> a fold fdown fup fprefix fleaf = go where go v Leaf = fleaf v go v (Node es) = fup (L.foldr edge v es) edge (p, t) v = fprefix p (go (fdown v) t) v -- | Increments the length of a prefix. inc :: Length a -> Length a inc (Exactly n) = Exactly (n+1) inc (Sum n xs) = Sum (n+1) xs lazyTreeWith :: (Eq a) => EdgeFunction a -> Alphabet a -> [a] -> STree a lazyTreeWith edge alphabet = suf . suffixes where suf [[]] = Leaf suf ss = Node [(Prefix (a:sa, inc cpl), suf ssr) | a <- alphabet, n@(sa:_) <- [ss `clusterBy` a], (cpl,ssr) <- [edge n]] clusterBy ss a = [cs | c:cs <- ss, c == a] -- | /O(n)/. Returns all non-empty suffixes of the argument, longest -- first. Behaves as follows: -- -- >suffixes xs == init (tails xs) suffixes :: [a] -> [[a]] suffixes xs@(_:xs') = xs : suffixes xs' suffixes _ = [] lazyTree :: (Ord a) => EdgeFunction a -> [a] -> STree a lazyTree edge = suf . suffixes where suf [[]] = Leaf suf ss = Node [(Prefix (a:sa, inc cpl), suf ssr) | (a, n@(sa:_)) <- suffixMap ss, (cpl,ssr) <- [edge n]] suffixMap :: Ord a => [[a]] -> [(a, [[a]])] suffixMap = map (second reverse) . M.toList . L.foldl' step M.empty where step m (x:xs) = M.alter (f xs) x m step m _ = m f x Nothing = Just [x] f x (Just xs) = Just (x:xs) cst :: Eq a => EdgeFunction a cst [s] = (Sum 0 s, [[]]) cst awss@((a:w):ss) | null [c | c:_ <- ss, a /= c] = let cpl' = inc cpl in seq cpl' (cpl', rss) | otherwise = (Exactly 0, awss) where (cpl, rss) = cst (w:[u | _:u <- ss]) pst :: Eq a => EdgeFunction a pst = g . dropNested where g [s] = (Sum 0 s, [[]]) g ss = (Exactly 0, ss) dropNested ss@[_] = ss dropNested awss@((a:w):ss) | null [c | c:_ <- ss, a /= c] = [a:s | s <- rss] | otherwise = awss where rss = dropNested (w:[u | _:u <- ss]) {-# SPECIALISE constructWith :: [Char] -> [Char] -> STree Char #-} {-# SPECIALISE constructWith :: [[Char]] -> [[Char]] -> STree [Char] #-} {-# SPECIALISE constructWith :: [SB.ByteString] -> [SB.ByteString] -> STree SB.ByteString #-} {-# SPECIALISE constructWith :: [LB.ByteString] -> [LB.ByteString] -> STree LB.ByteString #-} {-# SPECIALISE constructWith :: (Eq a) => [[a]] -> [[a]] -> STree [a] #-} -- | /O(k n log n)/. Constructs a suffix tree using the given -- alphabet. The performance of this function is linear in the size -- /k/ of the alphabet. That makes this function suitable for small -- alphabets, such as DNA nucleotides. For an alphabet containing -- more than a few symbols, 'construct' is usually several orders of -- magnitude faster. constructWith :: (Eq a) => Alphabet a -> [a] -> STree a constructWith = lazyTreeWith cst {-# SPECIALISE construct :: [Char] -> STree Char #-} {-# SPECIALISE construct :: [[Char]] -> STree [Char] #-} {-# SPECIALISE construct :: [SB.ByteString] -> STree SB.ByteString #-} {-# SPECIALISE construct :: [LB.ByteString] -> STree LB.ByteString #-} {-# SPECIALISE construct :: (Ord a) => [[a]] -> STree [a] #-} -- | /O(n log n)/. Constructs a suffix tree. construct :: (Ord a) => [a] -> STree a construct = lazyTree cst suffix :: (Eq a) => [a] -> [a] -> Maybe [a] suffix (p:ps) (x:xs) | p == x = suffix ps xs | otherwise = Nothing suffix _ xs = Just xs {-# SPECIALISE elem :: [Char] -> STree Char -> Bool #-} {-# SPECIALISE elem :: [[Char]] -> STree [Char] -> Bool #-} {-# SPECIALISE elem :: [SB.ByteString] -> STree SB.ByteString -> Bool #-} {-# SPECIALISE elem :: [LB.ByteString] -> STree LB.ByteString -> Bool #-} {-# SPECIALISE elem :: (Eq a) => [[a]] -> STree [a] -> Bool #-} -- | /O(n)/. Indicates whether the suffix tree contains the given -- sublist. Performance is linear in the length /n/ of the -- sublist. elem :: (Eq a) => [a] -> STree a -> Bool elem [] _ = True elem _ Leaf = False elem xs (Node es) = any pfx es where pfx (e, t) = maybe False (`elem` t) (suffix (prefix e) xs) {-# SPECIALISE findEdge :: [Char] -> STree Char -> Maybe (Edge Char, Int) #-} {-# SPECIALISE findEdge :: [String] -> STree String -> Maybe (Edge String, Int) #-} {-# SPECIALISE findEdge :: [SB.ByteString] -> STree SB.ByteString -> Maybe (Edge SB.ByteString, Int) #-} {-# SPECIALISE findEdge :: [ LB.ByteString] -> STree LB.ByteString -> Maybe (Edge LB.ByteString, Int) #-} {-# SPECIALISE findEdge :: (Eq a) => [[a]] -> STree [a] -> Maybe (Edge [a], Int) #-} -- | /O(n)/. Finds the given subsequence in the suffix tree. On -- failure, returns 'Nothing'. On success, returns the 'Edge' in the -- suffix tree at which the subsequence ends, along with the number of -- elements to drop from the prefix of the 'Edge' to get the \"real\" -- remaining prefix. -- -- Here is an example: -- -- >> find "ssip" (construct "mississippi") -- >Just ((mkPrefix "ppi",Leaf),1) -- -- This indicates that the edge @('mkPrefix' \"ppi\",'Leaf')@ matches, -- and that we must strip 1 character from the string @\"ppi\"@ to get -- the remaining prefix string @\"pi\"@. -- -- Performance is linear in the length /n/ of the query list. findEdge :: (Eq a) => [a] -> STree a -> Maybe (Edge a, Int) findEdge _ Leaf = Nothing findEdge xs (Node es) = listToMaybe (mapMaybe pfx es) where pfx e@(p, t) = let p' = prefix p in suffix p' xs >>= \suf -> case suf of [] -> return (e, length (zipWith const xs p')) s -> findEdge s t -- | /O(n)/. Finds the subtree rooted at the end of the given query -- sequence. On failure, returns 'Nothing'. -- -- Performance is linear in the length /n/ of the query list. findTree :: (Eq a) => [a] -> STree a -> Maybe (STree a) findTree s t = (snd . fst) `fmap` findEdge s t -- | /O(n)/. Returns the path from the 'Edge' in the suffix tree at -- which the given subsequence ends, up to the root of the tree. If -- the subsequence is not found, returns the empty list. -- -- Performance is linear in the length of the query list. findPath :: (Eq a) => [a] -> STree a -> [Edge a] findPath = go [] where go _ _ Leaf = [] go me xs (Node es) = pfx me es where pfx _ [] = [] pfx me (e@(p, t):es) = case suffix (prefix p) xs of Nothing -> pfx me es Just [] -> e:me Just s -> go (e:me) s t -- | /O(t)/. Count the number of leaves in a tree. -- -- Performance is linear in the number /t/ of elements in the tree. countLeaves :: STree a -> Int countLeaves Leaf = 1 countLeaves (Node es) = L.foldl' (\v (_, t) -> countLeaves t + v) 0 es -- | /O(n + r)/. Count the number of times a sequence is repeated -- in the input sequence that was used to construct the suffix tree. -- -- Performance is linear in the length /n/ of the input sequence, plus -- the number of times /r/ the sequence is repeated. countRepeats :: (Eq a) => [a] -> STree a -> Int countRepeats s t = maybe 0 countLeaves (findTree s t)
bos/suffixtree
Data/SuffixTree.hs
bsd-3-clause
13,050
0
18
3,566
3,094
1,700
1,394
186
5
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.BuildTargets -- Copyright : (c) Duncan Coutts 2012 -- License : BSD-like -- -- Maintainer : [email protected] -- -- Handling for user-specified build targets ----------------------------------------------------------------------------- module Distribution.Simple.BuildTarget ( -- * Build targets BuildTarget(..), readBuildTargets, -- * Parsing user build targets UserBuildTarget, readUserBuildTargets, UserBuildTargetProblem(..), reportUserBuildTargetProblems, -- * Resolving build targets resolveBuildTargets, BuildTargetProblem(..), reportBuildTargetProblems, ) where import Distribution.Package ( Package(..), PackageId, packageName ) import Distribution.PackageDescription ( PackageDescription , Executable(..) , TestSuite(..), TestSuiteInterface(..), testModules , Benchmark(..), BenchmarkInterface(..), benchmarkModules , BuildInfo(..), libModules, exeModules ) import Distribution.ModuleName ( ModuleName, toFilePath ) import Distribution.Simple.LocalBuildInfo ( Component(..), ComponentName(..) , pkgComponents, componentName, componentBuildInfo ) import Distribution.Text ( display ) import Distribution.Simple.Utils ( die, lowercase, equating ) import Data.List ( nub, stripPrefix, sortBy, groupBy, partition, intercalate ) import Data.Ord import Data.Maybe ( listToMaybe, catMaybes ) import Data.Either ( partitionEithers ) import qualified Data.Map as Map import Control.Monad #if __GLASGOW_HASKELL__ < 710 import Control.Applicative (Applicative(..)) #endif import Control.Applicative (Alternative(..)) import qualified Distribution.Compat.ReadP as Parse import Distribution.Compat.ReadP ( (+++), (<++) ) import Data.Char ( isSpace, isAlphaNum ) import System.FilePath as FilePath ( dropExtension, normalise, splitDirectories, joinPath, splitPath , hasTrailingPathSeparator ) import System.Directory ( doesFileExist, doesDirectoryExist ) -- ------------------------------------------------------------ -- * User build targets -- ------------------------------------------------------------ -- | Various ways that a user may specify a build target. -- data UserBuildTarget = -- | A target specified by a single name. This could be a component -- module or file. -- -- > cabal build foo -- > cabal build Data.Foo -- > cabal build Data/Foo.hs Data/Foo.hsc -- UserBuildTargetSingle String -- | A target specified by a qualifier and name. This could be a component -- name qualified by the component namespace kind, or a module or file -- qualified by the component name. -- -- > cabal build lib:foo exe:foo -- > cabal build foo:Data.Foo -- > cabal build foo:Data/Foo.hs -- | UserBuildTargetDouble String String -- A fully qualified target, either a module or file qualified by a -- component name with the component namespace kind. -- -- > cabal build lib:foo:Data/Foo.hs exe:foo:Data/Foo.hs -- > cabal build lib:foo:Data.Foo exe:foo:Data.Foo -- | UserBuildTargetTriple String String String deriving (Show, Eq, Ord) -- ------------------------------------------------------------ -- * Resolved build targets -- ------------------------------------------------------------ -- | A fully resolved build target. -- data BuildTarget = -- | A specific component -- BuildTargetComponent ComponentName -- | A specific module within a specific component. -- | BuildTargetModule ComponentName ModuleName -- | A specific file within a specific component. -- | BuildTargetFile ComponentName FilePath deriving (Show,Eq) -- ------------------------------------------------------------ -- * Do everything -- ------------------------------------------------------------ readBuildTargets :: PackageDescription -> [String] -> IO [BuildTarget] readBuildTargets pkg targetStrs = do let (uproblems, utargets) = readUserBuildTargets targetStrs reportUserBuildTargetProblems uproblems utargets' <- mapM checkTargetExistsAsFile utargets let (bproblems, btargets) = resolveBuildTargets pkg utargets' reportBuildTargetProblems bproblems return btargets checkTargetExistsAsFile :: UserBuildTarget -> IO (UserBuildTarget, Bool) checkTargetExistsAsFile t = do fexists <- existsAsFile (fileComponentOfTarget t) return (t, fexists) where existsAsFile f = do exists <- doesFileExist f case splitPath f of (d:_) | hasTrailingPathSeparator d -> doesDirectoryExist d (d:_:_) | not exists -> doesDirectoryExist d _ -> return exists fileComponentOfTarget (UserBuildTargetSingle s1) = s1 fileComponentOfTarget (UserBuildTargetDouble _ s2) = s2 fileComponentOfTarget (UserBuildTargetTriple _ _ s3) = s3 -- ------------------------------------------------------------ -- * Parsing user targets -- ------------------------------------------------------------ readUserBuildTargets :: [String] -> ([UserBuildTargetProblem] ,[UserBuildTarget]) readUserBuildTargets = partitionEithers . map readUserBuildTarget readUserBuildTarget :: String -> Either UserBuildTargetProblem UserBuildTarget readUserBuildTarget targetstr = case readPToMaybe parseTargetApprox targetstr of Nothing -> Left (UserBuildTargetUnrecognised targetstr) Just tgt -> Right tgt where parseTargetApprox :: Parse.ReadP r UserBuildTarget parseTargetApprox = (do a <- tokenQ return (UserBuildTargetSingle a)) +++ (do a <- token _ <- Parse.char ':' b <- tokenQ return (UserBuildTargetDouble a b)) +++ (do a <- token _ <- Parse.char ':' b <- token _ <- Parse.char ':' c <- tokenQ return (UserBuildTargetTriple a b c)) token = Parse.munch1 (\x -> not (isSpace x) && x /= ':') tokenQ = parseHaskellString <++ token parseHaskellString :: Parse.ReadP r String parseHaskellString = Parse.readS_to_P reads readPToMaybe :: Parse.ReadP a a -> String -> Maybe a readPToMaybe p str = listToMaybe [ r | (r,s) <- Parse.readP_to_S p str , all isSpace s ] data UserBuildTargetProblem = UserBuildTargetUnrecognised String deriving Show reportUserBuildTargetProblems :: [UserBuildTargetProblem] -> IO () reportUserBuildTargetProblems problems = do case [ target | UserBuildTargetUnrecognised target <- problems ] of [] -> return () target -> die $ unlines [ "Unrecognised build target '" ++ name ++ "'." | name <- target ] ++ "Examples:\n" ++ " - build foo -- component name " ++ "(library, executable, test-suite or benchmark)\n" ++ " - build Data.Foo -- module name\n" ++ " - build Data/Foo.hsc -- file name\n" ++ " - build lib:foo exe:foo -- component qualified by kind\n" ++ " - build foo:Data.Foo -- module qualified by component\n" ++ " - build foo:Data/Foo.hsc -- file qualified by component" showUserBuildTarget :: UserBuildTarget -> String showUserBuildTarget = intercalate ":" . components where components (UserBuildTargetSingle s1) = [s1] components (UserBuildTargetDouble s1 s2) = [s1,s2] components (UserBuildTargetTriple s1 s2 s3) = [s1,s2,s3] -- ------------------------------------------------------------ -- * Resolving user targets to build targets -- ------------------------------------------------------------ {- stargets = [ BuildTargetComponent (CExeName "foo") , BuildTargetModule (CExeName "foo") (mkMn "Foo") , BuildTargetModule (CExeName "tst") (mkMn "Foo") ] where mkMn :: String -> ModuleName mkMn = fromJust . simpleParse ex_pkgid :: PackageIdentifier Just ex_pkgid = simpleParse "thelib" -} -- | Given a bunch of user-specified targets, try to resolve what it is they -- refer to. -- resolveBuildTargets :: PackageDescription -> [(UserBuildTarget, Bool)] -> ([BuildTargetProblem], [BuildTarget]) resolveBuildTargets pkg = partitionEithers . map (uncurry (resolveBuildTarget pkg)) resolveBuildTarget :: PackageDescription -> UserBuildTarget -> Bool -> Either BuildTargetProblem BuildTarget resolveBuildTarget pkg userTarget fexists = case findMatch (matchBuildTarget pkg userTarget fexists) of Unambiguous target -> Right target Ambiguous targets -> Left (BuildTargetAmbigious userTarget targets') where targets' = disambiguateBuildTargets (packageId pkg) userTarget targets None errs -> Left (classifyMatchErrors errs) where classifyMatchErrors errs | not (null expected) = let (things, got:_) = unzip expected in BuildTargetExpected userTarget things got | not (null nosuch) = BuildTargetNoSuch userTarget nosuch | otherwise = error $ "resolveBuildTarget: internal error in matching" where expected = [ (thing, got) | MatchErrorExpected thing got <- errs ] nosuch = [ (thing, got) | MatchErrorNoSuch thing got <- errs ] data BuildTargetProblem = BuildTargetExpected UserBuildTarget [String] String -- ^ [expected thing] (actually got) | BuildTargetNoSuch UserBuildTarget [(String, String)] -- ^ [(no such thing, actually got)] | BuildTargetAmbigious UserBuildTarget [(UserBuildTarget, BuildTarget)] deriving Show disambiguateBuildTargets :: PackageId -> UserBuildTarget -> [BuildTarget] -> [(UserBuildTarget, BuildTarget)] disambiguateBuildTargets pkgid original = disambiguate (userTargetQualLevel original) where disambiguate ql ts | null amb = unamb | otherwise = unamb ++ disambiguate (succ ql) amb where (amb, unamb) = step ql ts userTargetQualLevel (UserBuildTargetSingle _ ) = QL1 userTargetQualLevel (UserBuildTargetDouble _ _ ) = QL2 userTargetQualLevel (UserBuildTargetTriple _ _ _) = QL3 step :: QualLevel -> [BuildTarget] -> ([BuildTarget], [(UserBuildTarget, BuildTarget)]) step ql = (\(amb, unamb) -> (map snd $ concat amb, concat unamb)) . partition (\g -> length g > 1) . groupBy (equating fst) . sortBy (comparing fst) . map (\t -> (renderBuildTarget ql t pkgid, t)) data QualLevel = QL1 | QL2 | QL3 deriving (Enum, Show) renderBuildTarget :: QualLevel -> BuildTarget -> PackageId -> UserBuildTarget renderBuildTarget ql target pkgid = case ql of QL1 -> UserBuildTargetSingle s1 where s1 = single target QL2 -> UserBuildTargetDouble s1 s2 where (s1, s2) = double target QL3 -> UserBuildTargetTriple s1 s2 s3 where (s1, s2, s3) = triple target where single (BuildTargetComponent cn ) = dispCName cn single (BuildTargetModule _ m) = display m single (BuildTargetFile _ f) = f double (BuildTargetComponent cn ) = (dispKind cn, dispCName cn) double (BuildTargetModule cn m) = (dispCName cn, display m) double (BuildTargetFile cn f) = (dispCName cn, f) triple (BuildTargetComponent _ ) = error "triple BuildTargetComponent" triple (BuildTargetModule cn m) = (dispKind cn, dispCName cn, display m) triple (BuildTargetFile cn f) = (dispKind cn, dispCName cn, f) dispCName = componentStringName pkgid dispKind = showComponentKindShort . componentKind reportBuildTargetProblems :: [BuildTargetProblem] -> IO () reportBuildTargetProblems problems = do case [ (t, e, g) | BuildTargetExpected t e g <- problems ] of [] -> return () targets -> die $ unlines [ "Unrecognised build target '" ++ showUserBuildTarget target ++ "'.\n" ++ "Expected a " ++ intercalate " or " expected ++ ", rather than '" ++ got ++ "'." | (target, expected, got) <- targets ] case [ (t, e) | BuildTargetNoSuch t e <- problems ] of [] -> return () targets -> die $ unlines [ "Unknown build target '" ++ showUserBuildTarget target ++ "'.\nThere is no " ++ intercalate " or " [ mungeThing thing ++ " '" ++ got ++ "'" | (thing, got) <- nosuch ] ++ "." | (target, nosuch) <- targets ] where mungeThing "file" = "file target" mungeThing thing = thing case [ (t, ts) | BuildTargetAmbigious t ts <- problems ] of [] -> return () targets -> die $ unlines [ "Ambiguous build target '" ++ showUserBuildTarget target ++ "'. It could be:\n " ++ unlines [ " "++ showUserBuildTarget ut ++ " (" ++ showBuildTargetKind bt ++ ")" | (ut, bt) <- amb ] | (target, amb) <- targets ] where showBuildTargetKind (BuildTargetComponent _ ) = "component" showBuildTargetKind (BuildTargetModule _ _) = "module" showBuildTargetKind (BuildTargetFile _ _) = "file" ---------------------------------- -- Top level BuildTarget matcher -- matchBuildTarget :: PackageDescription -> UserBuildTarget -> Bool -> Match BuildTarget matchBuildTarget pkg = \utarget fexists -> case utarget of UserBuildTargetSingle str1 -> matchBuildTarget1 cinfo str1 fexists UserBuildTargetDouble str1 str2 -> matchBuildTarget2 cinfo str1 str2 fexists UserBuildTargetTriple str1 str2 str3 -> matchBuildTarget3 cinfo str1 str2 str3 fexists where cinfo = pkgComponentInfo pkg matchBuildTarget1 :: [ComponentInfo] -> String -> Bool -> Match BuildTarget matchBuildTarget1 cinfo str1 fexists = matchComponent1 cinfo str1 `matchPlusShadowing` matchModule1 cinfo str1 `matchPlusShadowing` matchFile1 cinfo str1 fexists matchBuildTarget2 :: [ComponentInfo] -> String -> String -> Bool -> Match BuildTarget matchBuildTarget2 cinfo str1 str2 fexists = matchComponent2 cinfo str1 str2 `matchPlusShadowing` matchModule2 cinfo str1 str2 `matchPlusShadowing` matchFile2 cinfo str1 str2 fexists matchBuildTarget3 :: [ComponentInfo] -> String -> String -> String -> Bool -> Match BuildTarget matchBuildTarget3 cinfo str1 str2 str3 fexists = matchModule3 cinfo str1 str2 str3 `matchPlusShadowing` matchFile3 cinfo str1 str2 str3 fexists data ComponentInfo = ComponentInfo { cinfoName :: ComponentName, cinfoStrName :: ComponentStringName, cinfoSrcDirs :: [FilePath], cinfoModules :: [ModuleName], cinfoHsFiles :: [FilePath], -- other hs files (like main.hs) cinfoCFiles :: [FilePath], cinfoJsFiles :: [FilePath], cinfoJavaFiles :: [FilePath] } type ComponentStringName = String pkgComponentInfo :: PackageDescription -> [ComponentInfo] pkgComponentInfo pkg = [ ComponentInfo { cinfoName = componentName c, cinfoStrName = componentStringName pkg (componentName c), cinfoSrcDirs = hsSourceDirs bi, cinfoModules = componentModules c, cinfoHsFiles = componentHsFiles c, cinfoCFiles = cSources bi, cinfoJsFiles = jsSources bi, cinfoJavaFiles = javaSources bi } | c <- pkgComponents pkg , let bi = componentBuildInfo c ] componentStringName :: Package pkg => pkg -> ComponentName -> ComponentStringName componentStringName pkg CLibName = display (packageName pkg) componentStringName _ (CExeName name) = name componentStringName _ (CTestName name) = name componentStringName _ (CBenchName name) = name componentModules :: Component -> [ModuleName] componentModules (CLib lib) = libModules lib componentModules (CExe exe) = exeModules exe componentModules (CTest test) = testModules test componentModules (CBench bench) = benchmarkModules bench componentHsFiles :: Component -> [FilePath] componentHsFiles (CExe exe) = [modulePath exe] componentHsFiles (CTest TestSuite { testInterface = TestSuiteExeV10 _ mainfile }) = [mainfile] componentHsFiles (CBench Benchmark { benchmarkInterface = BenchmarkExeV10 _ mainfile }) = [mainfile] componentHsFiles _ = [] {- ex_cs :: [ComponentInfo] ex_cs = [ (mkC (CExeName "foo") ["src1", "src1/src2"] ["Foo", "Src2.Bar", "Bar"]) , (mkC (CExeName "tst") ["src1", "test"] ["Foo"]) ] where mkC n ds ms = ComponentInfo n (componentStringName pkgid n) ds (map mkMn ms) mkMn :: String -> ModuleName mkMn = fromJust . simpleParse pkgid :: PackageIdentifier Just pkgid = simpleParse "thelib" -} ------------------------------ -- Matching component kinds -- data ComponentKind = LibKind | ExeKind | TestKind | BenchKind deriving (Eq, Ord, Show) componentKind :: ComponentName -> ComponentKind componentKind CLibName = LibKind componentKind (CExeName _) = ExeKind componentKind (CTestName _) = TestKind componentKind (CBenchName _) = BenchKind cinfoKind :: ComponentInfo -> ComponentKind cinfoKind = componentKind . cinfoName matchComponentKind :: String -> Match ComponentKind matchComponentKind s | s `elem` ["lib", "library"] = increaseConfidence >> return LibKind | s `elem` ["exe", "executable"] = increaseConfidence >> return ExeKind | s `elem` ["tst", "test", "test-suite"] = increaseConfidence >> return TestKind | s `elem` ["bench", "benchmark"] = increaseConfidence >> return BenchKind | otherwise = matchErrorExpected "component kind" s showComponentKind :: ComponentKind -> String showComponentKind LibKind = "library" showComponentKind ExeKind = "executable" showComponentKind TestKind = "test-suite" showComponentKind BenchKind = "benchmark" showComponentKindShort :: ComponentKind -> String showComponentKindShort LibKind = "lib" showComponentKindShort ExeKind = "exe" showComponentKindShort TestKind = "test" showComponentKindShort BenchKind = "bench" ------------------------------ -- Matching component targets -- matchComponent1 :: [ComponentInfo] -> String -> Match BuildTarget matchComponent1 cs = \str1 -> do guardComponentName str1 c <- matchComponentName cs str1 return (BuildTargetComponent (cinfoName c)) matchComponent2 :: [ComponentInfo] -> String -> String -> Match BuildTarget matchComponent2 cs = \str1 str2 -> do ckind <- matchComponentKind str1 guardComponentName str2 c <- matchComponentKindAndName cs ckind str2 return (BuildTargetComponent (cinfoName c)) -- utils: guardComponentName :: String -> Match () guardComponentName s | all validComponentChar s && not (null s) = increaseConfidence | otherwise = matchErrorExpected "component name" s where validComponentChar c = isAlphaNum c || c == '.' || c == '_' || c == '-' || c == '\'' matchComponentName :: [ComponentInfo] -> String -> Match ComponentInfo matchComponentName cs str = orNoSuchThing "component" str $ increaseConfidenceFor $ matchInexactly caseFold [ (cinfoStrName c, c) | c <- cs ] str matchComponentKindAndName :: [ComponentInfo] -> ComponentKind -> String -> Match ComponentInfo matchComponentKindAndName cs ckind str = orNoSuchThing (showComponentKind ckind ++ " component") str $ increaseConfidenceFor $ matchInexactly (\(ck, cn) -> (ck, caseFold cn)) [ ((cinfoKind c, cinfoStrName c), c) | c <- cs ] (ckind, str) ------------------------------ -- Matching module targets -- matchModule1 :: [ComponentInfo] -> String -> Match BuildTarget matchModule1 cs = \str1 -> do guardModuleName str1 nubMatchErrors $ do c <- tryEach cs let ms = cinfoModules c m <- matchModuleName ms str1 return (BuildTargetModule (cinfoName c) m) matchModule2 :: [ComponentInfo] -> String -> String -> Match BuildTarget matchModule2 cs = \str1 str2 -> do guardComponentName str1 guardModuleName str2 c <- matchComponentName cs str1 let ms = cinfoModules c m <- matchModuleName ms str2 return (BuildTargetModule (cinfoName c) m) matchModule3 :: [ComponentInfo] -> String -> String -> String -> Match BuildTarget matchModule3 cs str1 str2 str3 = do ckind <- matchComponentKind str1 guardComponentName str2 c <- matchComponentKindAndName cs ckind str2 guardModuleName str3 let ms = cinfoModules c m <- matchModuleName ms str3 return (BuildTargetModule (cinfoName c) m) -- utils: guardModuleName :: String -> Match () guardModuleName s | all validModuleChar s && not (null s) = increaseConfidence | otherwise = matchErrorExpected "module name" s where validModuleChar c = isAlphaNum c || c == '.' || c == '_' || c == '\'' matchModuleName :: [ModuleName] -> String -> Match ModuleName matchModuleName ms str = orNoSuchThing "module" str $ increaseConfidenceFor $ matchInexactly caseFold [ (display m, m) | m <- ms ] str ------------------------------ -- Matching file targets -- matchFile1 :: [ComponentInfo] -> String -> Bool -> Match BuildTarget matchFile1 cs str1 exists = nubMatchErrors $ do c <- tryEach cs filepath <- matchComponentFile c str1 exists return (BuildTargetFile (cinfoName c) filepath) matchFile2 :: [ComponentInfo] -> String -> String -> Bool -> Match BuildTarget matchFile2 cs str1 str2 exists = do guardComponentName str1 c <- matchComponentName cs str1 filepath <- matchComponentFile c str2 exists return (BuildTargetFile (cinfoName c) filepath) matchFile3 :: [ComponentInfo] -> String -> String -> String -> Bool -> Match BuildTarget matchFile3 cs str1 str2 str3 exists = do ckind <- matchComponentKind str1 guardComponentName str2 c <- matchComponentKindAndName cs ckind str2 filepath <- matchComponentFile c str3 exists return (BuildTargetFile (cinfoName c) filepath) matchComponentFile :: ComponentInfo -> String -> Bool -> Match FilePath matchComponentFile c str fexists = expecting "file" str $ matchPlus (matchFileExists str fexists) (matchPlusShadowing (msum [ matchModuleFileRooted dirs ms str , matchOtherFileRooted dirs hsFiles str ]) (msum [ matchModuleFileUnrooted ms str , matchOtherFileUnrooted hsFiles str , matchOtherFileUnrooted cFiles str , matchOtherFileUnrooted jsFiles str , matchOtherFileUnrooted javaFiles str ])) where dirs = cinfoSrcDirs c ms = cinfoModules c hsFiles = cinfoHsFiles c cFiles = cinfoCFiles c jsFiles = cinfoJsFiles c javaFiles = cinfoJavaFiles c -- utils matchFileExists :: FilePath -> Bool -> Match a matchFileExists _ False = mzero matchFileExists fname True = do increaseConfidence matchErrorNoSuch "file" fname matchModuleFileUnrooted :: [ModuleName] -> String -> Match FilePath matchModuleFileUnrooted ms str = do let filepath = normalise str _ <- matchModuleFileStem ms filepath return filepath matchModuleFileRooted :: [FilePath] -> [ModuleName] -> String -> Match FilePath matchModuleFileRooted dirs ms str = nubMatches $ do let filepath = normalise str filepath' <- matchDirectoryPrefix dirs filepath _ <- matchModuleFileStem ms filepath' return filepath matchModuleFileStem :: [ModuleName] -> FilePath -> Match ModuleName matchModuleFileStem ms = increaseConfidenceFor . matchInexactly caseFold [ (toFilePath m, m) | m <- ms ] . dropExtension matchOtherFileRooted :: [FilePath] -> [FilePath] -> FilePath -> Match FilePath matchOtherFileRooted dirs fs str = do let filepath = normalise str filepath' <- matchDirectoryPrefix dirs filepath _ <- matchFile fs filepath' return filepath matchOtherFileUnrooted :: [FilePath] -> FilePath -> Match FilePath matchOtherFileUnrooted fs str = do let filepath = normalise str _ <- matchFile fs filepath return filepath matchFile :: [FilePath] -> FilePath -> Match FilePath matchFile fs = increaseConfidenceFor . matchInexactly caseFold [ (f, f) | f <- fs ] matchDirectoryPrefix :: [FilePath] -> FilePath -> Match FilePath matchDirectoryPrefix dirs filepath = exactMatches $ catMaybes [ stripDirectory (normalise dir) filepath | dir <- dirs ] where stripDirectory :: FilePath -> FilePath -> Maybe FilePath stripDirectory dir fp = joinPath `fmap` stripPrefix (splitDirectories dir) (splitDirectories fp) ------------------------------ -- Matching monad -- -- | A matcher embodies a way to match some input as being some recognised -- value. In particular it deals with multiple and ambigious matches. -- -- There are various matcher primitives ('matchExactly', 'matchInexactly'), -- ways to combine matchers ('ambigiousWith', 'shadows') and finally we can -- run a matcher against an input using 'findMatch'. -- data Match a = NoMatch Confidence [MatchError] | ExactMatch Confidence [a] | InexactMatch Confidence [a] deriving Show type Confidence = Int data MatchError = MatchErrorExpected String String | MatchErrorNoSuch String String deriving (Show, Eq) instance Alternative Match where empty = mzero (<|>) = mplus instance MonadPlus Match where mzero = matchZero mplus = matchPlus matchZero :: Match a matchZero = NoMatch 0 [] -- | Combine two matchers. Exact matches are used over inexact matches -- but if we have multiple exact, or inexact then the we collect all the -- ambigious matches. -- matchPlus :: Match a -> Match a -> Match a matchPlus (ExactMatch d1 xs) (ExactMatch d2 xs') = ExactMatch (max d1 d2) (xs ++ xs') matchPlus a@(ExactMatch _ _ ) (InexactMatch _ _ ) = a matchPlus a@(ExactMatch _ _ ) (NoMatch _ _ ) = a matchPlus (InexactMatch _ _ ) b@(ExactMatch _ _ ) = b matchPlus (InexactMatch d1 xs) (InexactMatch d2 xs') = InexactMatch (max d1 d2) (xs ++ xs') matchPlus a@(InexactMatch _ _ ) (NoMatch _ _ ) = a matchPlus (NoMatch _ _ ) b@(ExactMatch _ _ ) = b matchPlus (NoMatch _ _ ) b@(InexactMatch _ _ ) = b matchPlus a@(NoMatch d1 ms) b@(NoMatch d2 ms') | d1 > d2 = a | d1 < d2 = b | otherwise = NoMatch d1 (ms ++ ms') -- | Combine two matchers. This is similar to 'ambigiousWith' with the -- difference that an exact match from the left matcher shadows any exact -- match on the right. Inexact matches are still collected however. -- matchPlusShadowing :: Match a -> Match a -> Match a matchPlusShadowing a@(ExactMatch _ _) (ExactMatch _ _) = a matchPlusShadowing a b = matchPlus a b instance Functor Match where fmap _ (NoMatch d ms) = NoMatch d ms fmap f (ExactMatch d xs) = ExactMatch d (fmap f xs) fmap f (InexactMatch d xs) = InexactMatch d (fmap f xs) instance Applicative Match where pure = return (<*>) = ap instance Monad Match where return a = ExactMatch 0 [a] NoMatch d ms >>= _ = NoMatch d ms ExactMatch d xs >>= f = addDepth d $ foldr matchPlus matchZero (map f xs) InexactMatch d xs >>= f = addDepth d . forceInexact $ foldr matchPlus matchZero (map f xs) addDepth :: Confidence -> Match a -> Match a addDepth d' (NoMatch d msgs) = NoMatch (d'+d) msgs addDepth d' (ExactMatch d xs) = ExactMatch (d'+d) xs addDepth d' (InexactMatch d xs) = InexactMatch (d'+d) xs forceInexact :: Match a -> Match a forceInexact (ExactMatch d ys) = InexactMatch d ys forceInexact m = m ------------------------------ -- Various match primitives -- matchErrorExpected, matchErrorNoSuch :: String -> String -> Match a matchErrorExpected thing got = NoMatch 0 [MatchErrorExpected thing got] matchErrorNoSuch thing got = NoMatch 0 [MatchErrorNoSuch thing got] expecting :: String -> String -> Match a -> Match a expecting thing got (NoMatch 0 _) = matchErrorExpected thing got expecting _ _ m = m orNoSuchThing :: String -> String -> Match a -> Match a orNoSuchThing thing got (NoMatch 0 _) = matchErrorNoSuch thing got orNoSuchThing _ _ m = m increaseConfidence :: Match () increaseConfidence = ExactMatch 1 [()] increaseConfidenceFor :: Match a -> Match a increaseConfidenceFor m = m >>= \r -> increaseConfidence >> return r nubMatches :: Eq a => Match a -> Match a nubMatches (NoMatch d msgs) = NoMatch d msgs nubMatches (ExactMatch d xs) = ExactMatch d (nub xs) nubMatches (InexactMatch d xs) = InexactMatch d (nub xs) nubMatchErrors :: Match a -> Match a nubMatchErrors (NoMatch d msgs) = NoMatch d (nub msgs) nubMatchErrors (ExactMatch d xs) = ExactMatch d xs nubMatchErrors (InexactMatch d xs) = InexactMatch d xs -- | Lift a list of matches to an exact match. -- exactMatches, inexactMatches :: [a] -> Match a exactMatches [] = matchZero exactMatches xs = ExactMatch 0 xs inexactMatches [] = matchZero inexactMatches xs = InexactMatch 0 xs tryEach :: [a] -> Match a tryEach = exactMatches ------------------------------ -- Top level match runner -- -- | Given a matcher and a key to look up, use the matcher to find all the -- possible matches. There may be 'None', a single 'Unambiguous' match or -- you may have an 'Ambiguous' match with several possibilities. -- findMatch :: Eq b => Match b -> MaybeAmbigious b findMatch match = case match of NoMatch _ msgs -> None (nub msgs) ExactMatch _ xs -> checkAmbigious xs InexactMatch _ xs -> checkAmbigious xs where checkAmbigious xs = case nub xs of [x] -> Unambiguous x xs' -> Ambiguous xs' data MaybeAmbigious a = None [MatchError] | Unambiguous a | Ambiguous [a] deriving Show ------------------------------ -- Basic matchers -- {- -- | A primitive matcher that looks up a value in a finite 'Map'. The -- value must match exactly. -- matchExactly :: forall a b. Ord a => [(a, b)] -> (a -> Match b) matchExactly xs = \x -> case Map.lookup x m of Nothing -> matchZero Just ys -> ExactMatch 0 ys where m :: Ord a => Map a [b] m = Map.fromListWith (++) [ (k,[x]) | (k,x) <- xs ] -} -- | A primitive matcher that looks up a value in a finite 'Map'. It checks -- for an exact or inexact match. We get an inexact match if the match -- is not exact, but the canonical forms match. It takes a canonicalisation -- function for this purpose. -- -- So for example if we used string case fold as the canonicalisation -- function, then we would get case insensitive matching (but it will still -- report an exact match when the case matches too). -- matchInexactly :: (Ord a, Ord a') => (a -> a') -> [(a, b)] -> (a -> Match b) matchInexactly cannonicalise xs = \x -> case Map.lookup x m of Just ys -> exactMatches ys Nothing -> case Map.lookup (cannonicalise x) m' of Just ys -> inexactMatches ys Nothing -> matchZero where m = Map.fromListWith (++) [ (k,[x]) | (k,x) <- xs ] -- the map of canonicalised keys to groups of inexact matches m' = Map.mapKeysWith (++) cannonicalise m ------------------------------ -- Utils -- caseFold :: String -> String caseFold = lowercase
typelead/epm
Cabal/Distribution/Simple/BuildTarget.hs
bsd-3-clause
32,945
0
22
8,651
7,941
4,093
3,848
593
9
{-# OPTIONS_GHC -Wall #-} -- | API for this package module Classy ( -- * refernce frames newtonianBases , rotXYZ , rotX, rotY, rotZ , basesWithAngVel -- * classy state transformer and convenience functions , System , StateT , State , Identity , getSystem , getSystemT , liftIO , debugShow , debugPrint -- * needed to write type signatures , Sca , Vec , Bases -- * some primitives , XYZ(..) , Point(N0) , addCoord , addSpeed , addParam , addAction , relativePoint , derivIsSpeed , setDeriv -- * vector/frame operations , xyzVec , basisVec , xVec, yVec, zVec , scaleBasis -- * vector/frame math , cross , dot , dyadDot , dyadicDot , scale -- * rigid bodies , simpleDyadic , getCMPos -- * differentiation , ddt , ddtN , ddtNp , ddtF , partial , partialV -- * mechanical system and dynamics , addRigidBody , addParticle , addMoment , addForce , kineticEnergy , generalizedForce , generalizedEffectiveForce , kanes ) where import Classy.Convenience import Classy.Differentiation import Classy.DebugShow import Classy.State import Classy.System import Classy.Types import Classy.VectorMath
ghorn/classy-dvda
src/Classy.hs
bsd-3-clause
1,930
0
5
1,022
222
150
72
62
0
{-# LANGUAGE OverloadedStrings #-} module Auth ( basicAuth ) where import Control.Monad.IO.Class (liftIO) import qualified Data.Aeson.Types as JS import qualified Data.ByteString as BS import qualified Data.ByteString.Base64 as Base import qualified Data.ByteString.Char8 as C import qualified Data.List as List import qualified Data.Map as Map import qualified Data.Text as T import Network.HTTP.Types.Header (hAuthorization, RequestHeaders) import Network.Wai import Web.JWT import Web.Scotty (ActionM, raise) basicAuth :: Request -> ActionM () basicAuth req = do (user, pass) <- maybe (raise "No Auth.") return $ decodeAuthHeader (requestHeaders req) let jwt = makeJWT ((T.pack . C.unpack) user) liftIO $ print jwt liftIO $ print (user, pass) decodeAuthHeader :: RequestHeaders -> Maybe (BS.ByteString, BS.ByteString) decodeAuthHeader hds = do val <- List.lookup hAuthorization hds case Base.decode (BS.drop 6 val) of Left _ -> Nothing Right bs -> case C.split ':' bs of [u,p] -> return (u,p) _ -> Nothing makeJWT :: T.Text -> JSON makeJWT user = let cs = def { iss = stringOrURI "ashutoshr.com", sub = stringOrURI "login", unregisteredClaims = Map.fromList [ ("name", JS.String "John Doe") , ("user", JS.String user) ] } key = secret "temporary" in encodeSigned HS256 key cs
ashutoshrishi/blogserver
src/Auth.hs
bsd-3-clause
1,599
0
15
504
459
254
205
40
3
module BatchTests where import Common handleReq :: Handler (Req a) (Writer [[a]]) handleReq reqs = let results = map unReq reqs in tell [results] >> pure results run = execWriter . runBatch handleReq prop_batchAp x y = run (pair (req x) (req y)) === [[x, y]] prop_noBatchM x y = run (req x >> req y) === [[x], [y]] prop_batchLeftBindAp x y z = run (pair (req x >> req z) (req y)) === [[x, y], [z]] prop_batchRightBindAp x y z = run (pair (req x) (req y >> req z)) === [[x, y], [z]] prop_twoBatches x y z w = run (pair (req x >> req z) (req y >> req w)) === [[x, y], [z, w]] prop_anyBatches xs ys = run (pair (mapM_ req xs) (mapM_ req ys)) === zipWith (\a b -> [a,b]) xs ys ++ map return (leftovers xs ys) leftovers xs ys = drop n xs ++ drop n ys where n = min (length xs) (length ys) prop_twoBatchesWithLift x y z w = run (pair (lift (return 0) >> req x >> req z) (req y >> req w)) === [[x, y], [z, w]] return [] runTests = $quickCheckAll
zyla/monad-batch
test/BatchTests.hs
bsd-3-clause
980
0
14
236
596
305
291
-1
-1
{-# LANGUAGE RecordWildCards #-} module Network.HTTP2.Encode ( encodeFrame , encodeFrameChunks , encodeFrameHeader , encodeFrameHeaderBuf , encodeFramePayload , EncodeInfo(..) , encodeInfo ) where import Data.Bits (shiftR, (.&.)) import qualified Data.ByteString as BS import Data.ByteString.Internal (ByteString, unsafeCreate) import Data.Word (Word8, Word16, Word32) import Foreign.Ptr (Ptr, plusPtr) import Foreign.Storable (poke) import Network.HTTP2.Types ---------------------------------------------------------------- type Builder = [ByteString] -> [ByteString] -- | Auxiliary information for frame encoding. data EncodeInfo = EncodeInfo { -- | Flags to be set in a frame header encodeFlags :: FrameFlags -- | Stream id to be set in a frame header , encodeStreamId :: StreamId -- | Padding if any. In the case where this value is set but the priority flag is not set, this value gets preference over the priority flag. So, if this value is set, the priority flag is also set. , encodePadding :: Maybe Padding } deriving (Show,Read) ---------------------------------------------------------------- -- | A smart builder of 'EncodeInfo'. -- -- >>> encodeInfo setAck 0 -- EncodeInfo {encodeFlags = 1, encodeStreamId = 0, encodePadding = Nothing} encodeInfo :: (FrameFlags -> FrameFlags) -> Int -- ^ stream identifier -> EncodeInfo encodeInfo set sid = EncodeInfo (set defaultFlags) sid Nothing ---------------------------------------------------------------- -- | Encoding an HTTP/2 frame to 'ByteString'. -- This function is not efficient enough for high performace -- program because of the concatenation of 'ByteString'. -- -- >>> encodeFrame (encodeInfo id 1) (DataFrame "body") -- "\NUL\NUL\EOT\NUL\NUL\NUL\NUL\NUL\SOHbody" encodeFrame :: EncodeInfo -> FramePayload -> ByteString encodeFrame einfo payload = BS.concat $ encodeFrameChunks einfo payload -- | Encoding an HTTP/2 frame to ['ByteString']. -- This is suitable for sendMany. encodeFrameChunks :: EncodeInfo -> FramePayload -> [ByteString] encodeFrameChunks einfo payload = bs : bss where ftid = framePayloadToFrameTypeId payload bs = encodeFrameHeader ftid header (header, bss) = encodeFramePayload einfo payload -- | Encoding an HTTP/2 frame header. -- The frame header must be completed. encodeFrameHeader :: FrameTypeId -> FrameHeader -> ByteString encodeFrameHeader ftid fhdr = unsafeCreate frameHeaderLength $ encodeFrameHeaderBuf ftid fhdr -- | Writing an encoded HTTP/2 frame header to the buffer. -- The length of the buffer must be larger than or equal to 9 bytes. encodeFrameHeaderBuf :: FrameTypeId -> FrameHeader -> Ptr Word8 -> IO () encodeFrameHeaderBuf ftid FrameHeader{..} ptr = do poke24 ptr payloadLength poke8 ptr 3 typ poke8 ptr 4 flags poke32 (ptr `plusPtr` 5) sid where typ = fromFrameTypeId ftid sid = fromIntegral streamId -- | Encoding an HTTP/2 frame payload. -- This returns a complete frame header and chunks of payload. encodeFramePayload :: EncodeInfo -> FramePayload -> (FrameHeader, [ByteString]) encodeFramePayload einfo payload = (header, builder []) where (header, builder) = buildFramePayload einfo payload ---------------------------------------------------------------- buildFramePayload :: EncodeInfo -> FramePayload -> (FrameHeader, Builder) buildFramePayload einfo (DataFrame body) = buildFramePayloadData einfo body buildFramePayload einfo (HeadersFrame mpri hdr) = buildFramePayloadHeaders einfo mpri hdr buildFramePayload einfo (PriorityFrame pri) = buildFramePayloadPriority einfo pri buildFramePayload einfo (RSTStreamFrame e) = buildFramePayloadRSTStream einfo e buildFramePayload einfo (SettingsFrame settings) = buildFramePayloadSettings einfo settings buildFramePayload einfo (PushPromiseFrame sid hdr) = buildFramePayloadPushPromise einfo sid hdr buildFramePayload einfo (PingFrame opaque) = buildFramePayloadPing einfo opaque buildFramePayload einfo (GoAwayFrame sid e debug) = buildFramePayloadGoAway einfo sid e debug buildFramePayload einfo (WindowUpdateFrame size) = buildFramePayloadWindowUpdate einfo size buildFramePayload einfo (ContinuationFrame hdr) = buildFramePayloadContinuation einfo hdr buildFramePayload einfo (UnknownFrame _ opaque) = buildFramePayloadUnknown einfo opaque ---------------------------------------------------------------- buildPadding :: EncodeInfo -> Builder -> Int -- ^ Payload length. -> (FrameHeader, Builder) buildPadding EncodeInfo{ encodePadding = Nothing, ..} builder len = (header, builder) where header = FrameHeader len encodeFlags encodeStreamId buildPadding EncodeInfo{ encodePadding = Just padding, ..} btarget targetLength = (header, builder) where header = FrameHeader len newflags encodeStreamId builder = (b1 :) . btarget . (padding :) b1 = BS.singleton $ fromIntegral paddingLength paddingLength = BS.length padding len = targetLength + paddingLength + 1 newflags = setPadded encodeFlags buildPriority :: Priority -> Builder buildPriority Priority{..} = builder where builder = (priority :) estream | exclusive = setExclusive streamDependency | otherwise = streamDependency priority = unsafeCreate 5 $ \ptr -> do poke32 ptr $ fromIntegral estream poke8 ptr 4 $ fromIntegral $ weight - 1 ---------------------------------------------------------------- buildFramePayloadData :: EncodeInfo -> ByteString -> (FrameHeader, Builder) buildFramePayloadData einfo body = buildPadding einfo builder len where builder = (body :) len = BS.length body buildFramePayloadHeaders :: EncodeInfo -> Maybe Priority -> HeaderBlockFragment -> (FrameHeader, Builder) buildFramePayloadHeaders einfo Nothing hdr = buildPadding einfo builder len where builder = (hdr :) len = BS.length hdr buildFramePayloadHeaders einfo (Just pri) hdr = buildPadding einfo' builder len where builder = buildPriority pri . (hdr :) len = BS.length hdr + 5 einfo' = einfo { encodeFlags = setPriority (encodeFlags einfo) } buildFramePayloadPriority :: EncodeInfo -> Priority -> (FrameHeader, Builder) buildFramePayloadPriority EncodeInfo{..} p = (header, builder) where builder = buildPriority p header = FrameHeader 5 encodeFlags encodeStreamId buildFramePayloadRSTStream :: EncodeInfo -> ErrorCodeId -> (FrameHeader, Builder) buildFramePayloadRSTStream EncodeInfo{..} e = (header, builder) where builder = (b4 :) b4 = bytestring4 $ fromErrorCodeId e header = FrameHeader 4 encodeFlags encodeStreamId buildFramePayloadSettings :: EncodeInfo -> SettingsList -> (FrameHeader, Builder) buildFramePayloadSettings EncodeInfo{..} alist = (header, builder) where builder = (settings :) settings = unsafeCreate len $ \ptr -> go ptr alist go _ [] = return () go p ((k,v):kvs) = do poke16 p $ fromSettingsKeyId k poke32 (p `plusPtr` 2) $ fromIntegral v go (p `plusPtr` 6) kvs len = length alist * 6 header = FrameHeader len encodeFlags encodeStreamId buildFramePayloadPushPromise :: EncodeInfo -> StreamId -> HeaderBlockFragment -> (FrameHeader, Builder) buildFramePayloadPushPromise einfo sid hdr = buildPadding einfo builder len where builder = (b4 :) . (hdr :) b4 = bytestring4 $ fromIntegral sid len = 4 + BS.length hdr buildFramePayloadPing :: EncodeInfo -> ByteString -> (FrameHeader, Builder) buildFramePayloadPing EncodeInfo{..} odata = (header, builder) where builder = (odata :) header = FrameHeader 8 encodeFlags encodeStreamId buildFramePayloadGoAway :: EncodeInfo -> StreamId -> ErrorCodeId -> ByteString -> (FrameHeader, Builder) buildFramePayloadGoAway EncodeInfo{..} sid e debug = (header, builder) where builder = (b8 :) . (debug :) len0 = 8 b8 = unsafeCreate len0 $ \ptr -> do poke32 ptr $ fromIntegral sid poke32 (ptr `plusPtr` 4) $ fromErrorCodeId e len = len0 + BS.length debug header = FrameHeader len encodeFlags encodeStreamId buildFramePayloadWindowUpdate :: EncodeInfo -> WindowSize -> (FrameHeader, Builder) buildFramePayloadWindowUpdate EncodeInfo{..} size = (header, builder) where -- fixme: reserve bit builder = (b4 :) b4 = bytestring4 $ fromIntegral size header = FrameHeader 4 encodeFlags encodeStreamId buildFramePayloadContinuation :: EncodeInfo -> HeaderBlockFragment -> (FrameHeader, Builder) buildFramePayloadContinuation EncodeInfo{..} hdr = (header, builder) where builder = (hdr :) len = BS.length hdr header = FrameHeader len encodeFlags encodeStreamId buildFramePayloadUnknown :: EncodeInfo -> ByteString -> (FrameHeader, Builder) buildFramePayloadUnknown = buildFramePayloadData ---------------------------------------------------------------- poke8 :: Ptr Word8 -> Int -> Word8 -> IO () poke8 ptr n w = poke (ptr `plusPtr` n) w poke16 :: Ptr Word8 -> Word16 -> IO () poke16 ptr i = do poke ptr w0 poke8 ptr 1 w1 where w0 = fromIntegral ((i `shiftR` 8) .&. 0xff) w1 = fromIntegral (i .&. 0xff) poke24 :: Ptr Word8 -> Int -> IO () poke24 ptr i = do poke ptr w0 poke8 ptr 1 w1 poke8 ptr 2 w2 where w0 = fromIntegral ((i `shiftR` 16) .&. 0xff) w1 = fromIntegral ((i `shiftR` 8) .&. 0xff) w2 = fromIntegral (i .&. 0xff) poke32 :: Ptr Word8 -> Word32 -> IO () poke32 ptr i = do poke ptr w0 poke8 ptr 1 w1 poke8 ptr 2 w2 poke8 ptr 3 w3 where w0 = fromIntegral ((i `shiftR` 24) .&. 0xff) w1 = fromIntegral ((i `shiftR` 16) .&. 0xff) w2 = fromIntegral ((i `shiftR` 8) .&. 0xff) w3 = fromIntegral (i .&. 0xff) bytestring4 :: Word32 -> ByteString bytestring4 i = unsafeCreate 4 $ \ptr -> poke32 ptr i
bergmark/http2
Network/HTTP2/Encode.hs
bsd-3-clause
9,952
0
14
1,957
2,576
1,374
1,202
186
2
{-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | This is just a stub executable that uses dyre to read the config file and -- recompile itself. module Main ( main ) where import Data.Default (def) import Data.Semigroup ((<>)) import Data.Version import Options.Applicative import System.Directory import System.Log.Logger import System.Taffybar import System.Taffybar.Context import System.Taffybar.Example import Text.Printf import Paths_taffybar (version) logP :: Parser Priority logP = option auto ( long "log-level" <> short 'l' <> help "Set the log level" <> metavar "LEVEL" <> value WARNING ) versionOption :: Parser (a -> a) versionOption = infoOption (printf "taffybar %s" $ showVersion version) ( long "version" <> help "Show the version number of taffybar" ) main :: IO () main = do logLevel <- execParser $ info (helper <*> versionOption <*> logP) ( fullDesc <> progDesc "Start taffybar, recompiling if necessary" ) logger <- getLogger "System.Taffybar" saveGlobalLogger $ setLevel logLevel logger taffyFilepath <- getTaffyFile "taffybar.hs" configurationExists <- doesFileExist taffyFilepath if configurationExists -- XXX: The configuration record here does not get used, this just calls in to dyre. then dyreTaffybar def else do logM "System.Taffybar" WARNING $ ( printf "No taffybar configuration file found at %s." taffyFilepath ++ " Starting with example configuration." ) startTaffybar exampleTaffybarConfig
teleshoes/taffybar
app/Main.hs
bsd-3-clause
1,617
0
13
390
327
168
159
42
2
module Commands.Test.Types where
sboosali/commands-core
tests/Commands/Test/Types.hs
mit
33
0
3
3
7
5
2
1
0
{-# OPTIONS_JHC -fno-prelude -fffi -funboxed-tuples #-} module Foreign.StablePtr( StablePtr(), castStablePtrToPtr, castPtrToStablePtr, newStablePtr, deRefStablePtr, freeStablePtr ) where import Jhc.Prim.Rts import Jhc.IO import Jhc.Type.Ptr import Jhc.Basics data StablePtr a castPtrToStablePtr :: Ptr () -> StablePtr a castPtrToStablePtr (Ptr (Addr_ p)) = fromBang_ (bangFromRaw p) castStablePtrToPtr :: StablePtr a -> Ptr () castStablePtrToPtr p = Ptr (Addr_ (bangToRaw (toBang_ p))) freeStablePtr :: StablePtr a -> IO () freeStablePtr p = c_freeStablePtr (toBang_ p) -- | newStablePtr will seq its argument to get rid of nasty GC issues and be -- compatible with FFI calling conventions, if this is an issue, you can put an -- extra box around it. newStablePtr :: a -> IO (StablePtr a) newStablePtr x = do fromUIO $ \w -> case c_newStablePtr (toBang_ x) w of (# w', s #) -> (# w', fromBang_ s #) deRefStablePtr :: StablePtr a -> IO a deRefStablePtr x = do fromUIO $ \w -> case c_derefStablePtr (toBang_ x) w of (# w', s #) -> (# w', fromBang_ s #) foreign import ccall unsafe "rts/stableptr.c c_freeStablePtr" c_freeStablePtr :: Bang_ (StablePtr a) -> IO () foreign import ccall unsafe "rts/stableptr.c c_newStablePtr" c_newStablePtr :: Bang_ a -> UIO (Bang_ (StablePtr a)) foreign import ccall unsafe "rts/stableptr.c c_derefStablePtr" c_derefStablePtr :: Bang_ (StablePtr a) -> UIO (Bang_ a)
m-alvarez/jhc
lib/haskell-extras/Foreign/StablePtr.hs
mit
1,465
0
13
280
430
222
208
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.RDS.AuthorizeDBSecurityGroupIngress -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Enables ingress to a DBSecurityGroup using one of two forms of -- authorization. First, EC2 or VPC security groups can be added to the -- DBSecurityGroup if the application using the database is running on EC2 -- or VPC instances. Second, IP ranges are available if the application -- accessing your database is running on the Internet. Required parameters -- for this API are one of CIDR range, EC2SecurityGroupId for VPC, or -- (EC2SecurityGroupOwnerId and either EC2SecurityGroupName or -- EC2SecurityGroupId for non-VPC). -- -- You cannot authorize ingress from an EC2 security group in one region to -- an Amazon RDS DB instance in another. You cannot authorize ingress from -- a VPC security group in one VPC to an Amazon RDS DB instance in another. -- -- For an overview of CIDR ranges, go to the -- <http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing Wikipedia Tutorial>. -- -- /See:/ <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_AuthorizeDBSecurityGroupIngress.html AWS API Reference> for AuthorizeDBSecurityGroupIngress. module Network.AWS.RDS.AuthorizeDBSecurityGroupIngress ( -- * Creating a Request authorizeDBSecurityGroupIngress , AuthorizeDBSecurityGroupIngress -- * Request Lenses , adsgiEC2SecurityGroupOwnerId , adsgiEC2SecurityGroupName , adsgiCIdRIP , adsgiEC2SecurityGroupId , adsgiDBSecurityGroupName -- * Destructuring the Response , authorizeDBSecurityGroupIngressResponse , AuthorizeDBSecurityGroupIngressResponse -- * Response Lenses , adsgirsDBSecurityGroup , adsgirsResponseStatus ) where import Network.AWS.Prelude import Network.AWS.RDS.Types import Network.AWS.RDS.Types.Product import Network.AWS.Request import Network.AWS.Response -- | -- -- /See:/ 'authorizeDBSecurityGroupIngress' smart constructor. data AuthorizeDBSecurityGroupIngress = AuthorizeDBSecurityGroupIngress' { _adsgiEC2SecurityGroupOwnerId :: !(Maybe Text) , _adsgiEC2SecurityGroupName :: !(Maybe Text) , _adsgiCIdRIP :: !(Maybe Text) , _adsgiEC2SecurityGroupId :: !(Maybe Text) , _adsgiDBSecurityGroupName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AuthorizeDBSecurityGroupIngress' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'adsgiEC2SecurityGroupOwnerId' -- -- * 'adsgiEC2SecurityGroupName' -- -- * 'adsgiCIdRIP' -- -- * 'adsgiEC2SecurityGroupId' -- -- * 'adsgiDBSecurityGroupName' authorizeDBSecurityGroupIngress :: Text -- ^ 'adsgiDBSecurityGroupName' -> AuthorizeDBSecurityGroupIngress authorizeDBSecurityGroupIngress pDBSecurityGroupName_ = AuthorizeDBSecurityGroupIngress' { _adsgiEC2SecurityGroupOwnerId = Nothing , _adsgiEC2SecurityGroupName = Nothing , _adsgiCIdRIP = Nothing , _adsgiEC2SecurityGroupId = Nothing , _adsgiDBSecurityGroupName = pDBSecurityGroupName_ } -- | AWS account number of the owner of the EC2 security group specified in -- the 'EC2SecurityGroupName' parameter. The AWS Access Key ID is not an -- acceptable value. For VPC DB security groups, 'EC2SecurityGroupId' must -- be provided. Otherwise, 'EC2SecurityGroupOwnerId' and either -- 'EC2SecurityGroupName' or 'EC2SecurityGroupId' must be provided. adsgiEC2SecurityGroupOwnerId :: Lens' AuthorizeDBSecurityGroupIngress (Maybe Text) adsgiEC2SecurityGroupOwnerId = lens _adsgiEC2SecurityGroupOwnerId (\ s a -> s{_adsgiEC2SecurityGroupOwnerId = a}); -- | Name of the EC2 security group to authorize. For VPC DB security groups, -- 'EC2SecurityGroupId' must be provided. Otherwise, -- 'EC2SecurityGroupOwnerId' and either 'EC2SecurityGroupName' or -- 'EC2SecurityGroupId' must be provided. adsgiEC2SecurityGroupName :: Lens' AuthorizeDBSecurityGroupIngress (Maybe Text) adsgiEC2SecurityGroupName = lens _adsgiEC2SecurityGroupName (\ s a -> s{_adsgiEC2SecurityGroupName = a}); -- | The IP range to authorize. adsgiCIdRIP :: Lens' AuthorizeDBSecurityGroupIngress (Maybe Text) adsgiCIdRIP = lens _adsgiCIdRIP (\ s a -> s{_adsgiCIdRIP = a}); -- | Id of the EC2 security group to authorize. For VPC DB security groups, -- 'EC2SecurityGroupId' must be provided. Otherwise, -- 'EC2SecurityGroupOwnerId' and either 'EC2SecurityGroupName' or -- 'EC2SecurityGroupId' must be provided. adsgiEC2SecurityGroupId :: Lens' AuthorizeDBSecurityGroupIngress (Maybe Text) adsgiEC2SecurityGroupId = lens _adsgiEC2SecurityGroupId (\ s a -> s{_adsgiEC2SecurityGroupId = a}); -- | The name of the DB security group to add authorization to. adsgiDBSecurityGroupName :: Lens' AuthorizeDBSecurityGroupIngress Text adsgiDBSecurityGroupName = lens _adsgiDBSecurityGroupName (\ s a -> s{_adsgiDBSecurityGroupName = a}); instance AWSRequest AuthorizeDBSecurityGroupIngress where type Rs AuthorizeDBSecurityGroupIngress = AuthorizeDBSecurityGroupIngressResponse request = postQuery rDS response = receiveXMLWrapper "AuthorizeDBSecurityGroupIngressResult" (\ s h x -> AuthorizeDBSecurityGroupIngressResponse' <$> (x .@? "DBSecurityGroup") <*> (pure (fromEnum s))) instance ToHeaders AuthorizeDBSecurityGroupIngress where toHeaders = const mempty instance ToPath AuthorizeDBSecurityGroupIngress where toPath = const "/" instance ToQuery AuthorizeDBSecurityGroupIngress where toQuery AuthorizeDBSecurityGroupIngress'{..} = mconcat ["Action" =: ("AuthorizeDBSecurityGroupIngress" :: ByteString), "Version" =: ("2014-10-31" :: ByteString), "EC2SecurityGroupOwnerId" =: _adsgiEC2SecurityGroupOwnerId, "EC2SecurityGroupName" =: _adsgiEC2SecurityGroupName, "CIDRIP" =: _adsgiCIdRIP, "EC2SecurityGroupId" =: _adsgiEC2SecurityGroupId, "DBSecurityGroupName" =: _adsgiDBSecurityGroupName] -- | /See:/ 'authorizeDBSecurityGroupIngressResponse' smart constructor. data AuthorizeDBSecurityGroupIngressResponse = AuthorizeDBSecurityGroupIngressResponse' { _adsgirsDBSecurityGroup :: !(Maybe DBSecurityGroup) , _adsgirsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AuthorizeDBSecurityGroupIngressResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'adsgirsDBSecurityGroup' -- -- * 'adsgirsResponseStatus' authorizeDBSecurityGroupIngressResponse :: Int -- ^ 'adsgirsResponseStatus' -> AuthorizeDBSecurityGroupIngressResponse authorizeDBSecurityGroupIngressResponse pResponseStatus_ = AuthorizeDBSecurityGroupIngressResponse' { _adsgirsDBSecurityGroup = Nothing , _adsgirsResponseStatus = pResponseStatus_ } -- | Undocumented member. adsgirsDBSecurityGroup :: Lens' AuthorizeDBSecurityGroupIngressResponse (Maybe DBSecurityGroup) adsgirsDBSecurityGroup = lens _adsgirsDBSecurityGroup (\ s a -> s{_adsgirsDBSecurityGroup = a}); -- | The response status code. adsgirsResponseStatus :: Lens' AuthorizeDBSecurityGroupIngressResponse Int adsgirsResponseStatus = lens _adsgirsResponseStatus (\ s a -> s{_adsgirsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-rds/gen/Network/AWS/RDS/AuthorizeDBSecurityGroupIngress.hs
mpl-2.0
8,116
0
13
1,437
883
534
349
108
1
module FilePath where import qualified System.Directory as D checkPath :: Bool -> FilePath -> String -> IO (Maybe String) checkPath dir path name = do exists <- predicate path return $ if exists then Nothing else Just $ "missing " ++ path_type ++ " of " ++ name where (predicate, path_type) = if dir then (D.doesDirectoryExist, "dir") else (D.doesFileExist, "file") checkDir :: FilePath -> String -> IO (Maybe String) checkDir = checkPath True checkFile :: FilePath -> String -> IO (Maybe String) checkFile = checkPath False
jfeltz/dash-haskell
src/FilePath.hs
lgpl-3.0
560
0
12
121
189
101
88
14
3
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Num -- Copyright : (c) The University of Glasgow 1994-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- The 'Num' class and the 'Integer' type. -- ----------------------------------------------------------------------------- module GHC.Num ( module GHC.Integer , Num(..) , subtract ) where import GHC.Base import GHC.Integer infixl 7 * infixl 6 +, - default () -- Double isn't available yet, -- and we shouldn't be using defaults anyway -- | Basic numeric class. class Num a where {-# MINIMAL (+), (*), abs, signum, fromInteger, (negate | (-)) #-} (+), (-), (*) :: a -> a -> a -- | Unary negation. negate :: a -> a -- | Absolute value. abs :: a -> a -- | Sign of a number. -- The functions 'abs' and 'signum' should satisfy the law: -- -- > abs x * signum x == x -- -- For real numbers, the 'signum' is either @-1@ (negative), @0@ (zero) -- or @1@ (positive). signum :: a -> a -- | Conversion from an 'Integer'. -- An integer literal represents the application of the function -- 'fromInteger' to the appropriate value of type 'Integer', -- so such literals have type @('Num' a) => a@. fromInteger :: Integer -> a {-# INLINE (-) #-} {-# INLINE negate #-} x - y = x + negate y negate x = 0 - x -- | the same as @'flip' ('-')@. -- -- Because @-@ is treated specially in the Haskell grammar, -- @(-@ /e/@)@ is not a section, but an application of prefix negation. -- However, @('subtract'@ /exp/@)@ is equivalent to the disallowed section. {-# INLINE subtract #-} subtract :: (Num a) => a -> a -> a subtract x y = y - x instance Num Int where I# x + I# y = I# (x +# y) I# x - I# y = I# (x -# y) negate (I# x) = I# (negateInt# x) I# x * I# y = I# (x *# y) abs n = if n `geInt` 0 then n else negate n signum n | n `ltInt` 0 = negate 1 | n `eqInt` 0 = 0 | otherwise = 1 {-# INLINE fromInteger #-} -- Just to be sure! fromInteger i = I# (integerToInt i) instance Num Word where (W# x#) + (W# y#) = W# (x# `plusWord#` y#) (W# x#) - (W# y#) = W# (x# `minusWord#` y#) (W# x#) * (W# y#) = W# (x# `timesWord#` y#) negate (W# x#) = W# (int2Word# (negateInt# (word2Int# x#))) abs x = x signum 0 = 0 signum _ = 1 fromInteger i = W# (integerToWord i) instance Num Integer where (+) = plusInteger (-) = minusInteger (*) = timesInteger negate = negateInteger fromInteger x = x abs = absInteger signum = signumInteger
green-haskell/ghc
libraries/base/GHC/Num.hs
bsd-3-clause
3,118
0
12
981
670
373
297
55
1
-- | Atomic monads for handling atomic game state transformations. module Game.LambdaHack.Atomic.MonadAtomic ( MonadAtomic(..) , broadcastUpdAtomic, broadcastSfxAtomic ) where import Data.Key (mapWithKeyM_) import Game.LambdaHack.Atomic.CmdAtomic import Game.LambdaHack.Common.Faction import Game.LambdaHack.Common.MonadStateRead import Game.LambdaHack.Common.State -- | The monad for executing atomic game state transformations. class MonadStateRead m => MonadAtomic m where -- | Execute an arbitrary atomic game state transformation. execAtomic :: CmdAtomic -> m () -- | Execute an atomic command that really changes the state. execUpdAtomic :: UpdAtomic -> m () execUpdAtomic = execAtomic . UpdAtomic -- | Execute an atomic command that only displays special effects. execSfxAtomic :: SfxAtomic -> m () execSfxAtomic = execAtomic . SfxAtomic -- | Create and broadcast a set of atomic updates, one for each client. broadcastUpdAtomic :: MonadAtomic m => (FactionId -> UpdAtomic) -> m () broadcastUpdAtomic fcmd = do factionD <- getsState sfactionD mapWithKeyM_ (\fid _ -> execUpdAtomic $ fcmd fid) factionD -- | Create and broadcast a set of atomic special effects, one for each client. broadcastSfxAtomic :: MonadAtomic m => (FactionId -> SfxAtomic) -> m () broadcastSfxAtomic fcmd = do factionD <- getsState sfactionD mapWithKeyM_ (\fid _ -> execSfxAtomic $ fcmd fid) factionD
Concomitant/LambdaHack
Game/LambdaHack/Atomic/MonadAtomic.hs
bsd-3-clause
1,458
0
11
268
286
155
131
24
1
{- (c) The University of Glasgow 2006 (c) The GRASP Project, Glasgow University, 1992-2000 Defines basic functions for printing error messages. It's hard to put these functions anywhere else without causing some unnecessary loops in the module dependency graph. -} {-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-} module Panic ( GhcException(..), showGhcException, throwGhcException, throwGhcExceptionIO, handleGhcException, progName, pgmError, panic, sorry, assertPanic, trace, panicDoc, sorryDoc, pgmErrorDoc, Exception.Exception(..), showException, safeShowException, try, tryMost, throwTo, installSignalHandlers, ) where #include "HsVersions.h" import {-# SOURCE #-} Outputable (SDoc, showSDocUnsafe) import Config import Exception import Control.Concurrent import Data.Dynamic import Debug.Trace ( trace ) import System.IO.Unsafe import System.Environment #ifndef mingw32_HOST_OS import System.Posix.Signals #endif #if defined(mingw32_HOST_OS) import GHC.ConsoleHandler #endif import GHC.Stack import System.Mem.Weak ( deRefWeak ) -- | GHC's own exception type -- error messages all take the form: -- -- @ -- <location>: <error> -- @ -- -- If the location is on the command line, or in GHC itself, then -- <location>="ghc". All of the error types below correspond to -- a <location> of "ghc", except for ProgramError (where the string is -- assumed to contain a location already, so we don't print one). data GhcException -- | Some other fatal signal (SIGHUP,SIGTERM) = Signal Int -- | Prints the short usage msg after the error | UsageError String -- | A problem with the command line arguments, but don't print usage. | CmdLineError String -- | The 'impossible' happened. | Panic String | PprPanic String SDoc -- | The user tickled something that's known not to work yet, -- but we're not counting it as a bug. | Sorry String | PprSorry String SDoc -- | An installation problem. | InstallationError String -- | An error in the user's code, probably. | ProgramError String | PprProgramError String SDoc deriving (Typeable) instance Exception GhcException instance Show GhcException where showsPrec _ e@(ProgramError _) = showGhcException e showsPrec _ e@(CmdLineError _) = showString "<command line>: " . showGhcException e showsPrec _ e = showString progName . showString ": " . showGhcException e -- | The name of this GHC. progName :: String progName = unsafePerformIO (getProgName) {-# NOINLINE progName #-} -- | Short usage information to display when we are given the wrong cmd line arguments. short_usage :: String short_usage = "Usage: For basic information, try the `--help' option." -- | Show an exception as a string. showException :: Exception e => e -> String showException = show -- | Show an exception which can possibly throw other exceptions. -- Used when displaying exception thrown within TH code. safeShowException :: Exception e => e -> IO String safeShowException e = do -- ensure the whole error message is evaluated inside try r <- try (return $! forceList (showException e)) case r of Right msg -> return msg Left e' -> safeShowException (e' :: SomeException) where forceList [] = [] forceList xs@(x : xt) = x `seq` forceList xt `seq` xs -- | Append a description of the given exception to this string. -- -- Note that this uses 'DynFlags.unsafeGlobalDynFlags', which may have some -- uninitialized fields if invoked before 'GHC.initGhcMonad' has been called. -- If the error message to be printed includes a pretty-printer document -- which forces one of these fields this call may bottom. showGhcException :: GhcException -> ShowS showGhcException exception = case exception of UsageError str -> showString str . showChar '\n' . showString short_usage CmdLineError str -> showString str PprProgramError str sdoc -> showString str . showString "\n\n" . showString (showSDocUnsafe sdoc) ProgramError str -> showString str InstallationError str -> showString str Signal n -> showString "signal: " . shows n PprPanic s sdoc -> panicMsg $ showString s . showString "\n\n" . showString (showSDocUnsafe sdoc) Panic s -> panicMsg (showString s) PprSorry s sdoc -> sorryMsg $ showString s . showString "\n\n" . showString (showSDocUnsafe sdoc) Sorry s -> sorryMsg (showString s) where sorryMsg :: ShowS -> ShowS sorryMsg s = showString "sorry! (unimplemented feature or known bug)\n" . showString (" (GHC version " ++ cProjectVersion ++ " for " ++ TargetPlatform_NAME ++ "):\n\t") . s . showString "\n" panicMsg :: ShowS -> ShowS panicMsg s = showString "panic! (the 'impossible' happened)\n" . showString (" (GHC version " ++ cProjectVersion ++ " for " ++ TargetPlatform_NAME ++ "):\n\t") . s . showString "\n\n" . showString "Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug\n" throwGhcException :: GhcException -> a throwGhcException = Exception.throw throwGhcExceptionIO :: GhcException -> IO a throwGhcExceptionIO = Exception.throwIO handleGhcException :: ExceptionMonad m => (GhcException -> m a) -> m a -> m a handleGhcException = ghandle -- | Panics and asserts. panic, sorry, pgmError :: String -> a panic x = unsafeDupablePerformIO $ do stack <- ccsToStrings =<< getCurrentCCS x if null stack then throwGhcException (Panic x) else throwGhcException (Panic (x ++ '\n' : renderStack stack)) sorry x = throwGhcException (Sorry x) pgmError x = throwGhcException (ProgramError x) panicDoc, sorryDoc, pgmErrorDoc :: String -> SDoc -> a panicDoc x doc = throwGhcException (PprPanic x doc) sorryDoc x doc = throwGhcException (PprSorry x doc) pgmErrorDoc x doc = throwGhcException (PprProgramError x doc) -- | Throw an failed assertion exception for a given filename and line number. assertPanic :: String -> Int -> a assertPanic file line = Exception.throw (Exception.AssertionFailed ("ASSERT failed! file " ++ file ++ ", line " ++ show line)) -- | Like try, but pass through UserInterrupt and Panic exceptions. -- Used when we want soft failures when reading interface files, for example. -- TODO: I'm not entirely sure if this is catching what we really want to catch tryMost :: IO a -> IO (Either SomeException a) tryMost action = do r <- try action case r of Left se -> case fromException se of -- Some GhcException's we rethrow, Just (Signal _) -> throwIO se Just (Panic _) -> throwIO se -- others we return Just _ -> return (Left se) Nothing -> case fromException se of -- All IOExceptions are returned Just (_ :: IOException) -> return (Left se) -- Anything else is rethrown Nothing -> throwIO se Right v -> return (Right v) -- | Install standard signal handlers for catching ^C, which just throw an -- exception in the target thread. The current target thread is the -- thread at the head of the list in the MVar passed to -- installSignalHandlers. installSignalHandlers :: IO () installSignalHandlers = do main_thread <- myThreadId wtid <- mkWeakThreadId main_thread let interrupt = do r <- deRefWeak wtid case r of Nothing -> return () Just t -> throwTo t UserInterrupt #if !defined(mingw32_HOST_OS) _ <- installHandler sigQUIT (Catch interrupt) Nothing _ <- installHandler sigINT (Catch interrupt) Nothing -- see #3656; in the future we should install these automatically for -- all Haskell programs in the same way that we install a ^C handler. let fatal_signal n = throwTo main_thread (Signal (fromIntegral n)) _ <- installHandler sigHUP (Catch (fatal_signal sigHUP)) Nothing _ <- installHandler sigTERM (Catch (fatal_signal sigTERM)) Nothing return () #else -- GHC 6.3+ has support for console events on Windows -- NOTE: running GHCi under a bash shell for some reason requires -- you to press Ctrl-Break rather than Ctrl-C to provoke -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know -- why --SDM 17/12/2004 let sig_handler ControlC = interrupt sig_handler Break = interrupt sig_handler _ = return () _ <- installHandler (Catch sig_handler) return () #endif
GaloisInc/halvm-ghc
compiler/utils/Panic.hs
bsd-3-clause
9,101
0
18
2,469
1,652
850
802
138
10
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ViewPatterns #-} ----------------------------------------------------------------------------- -- | -- Module : Main -- Copyright : (c) 2012 Andreas-C. Bernstein -- License : BSD-style (see LICENSE) -- Maintainer : [email protected] -- -- Main. -- ----------------------------------------------------------------------------- module Main (main) where import SdlAdapter import Rendering import UnitBox import ReactiveUtils import Data.Maybe (isJust) import Control.Arrow (first,second) import System.Exit (exitSuccess) import qualified Data.Active as Active import Diagrams.Prelude import Reactive.Banana as R import qualified Graphics.UI.SDL as SDL --import qualified Graphics.UI.GLUT as GLUT import qualified Graphics.Rendering.OpenGL.Raw as GL initSDL :: String -> Int -> Int -> IO SDL.Surface initSDL title w h = do SDL.init [SDL.InitVideo] -- s <- SDL.setVideoMode w h 32 [SDL.OpenGL, SDL.Resizable, SDL.DoubleBuf,SDL.Fullscreen] --s <- SDL.setVideoMode w h 32 [SDL.OpenGL, SDL.DoubleBuf,SDL.Fullscreen] s <- SDL.setVideoMode w h 32 [SDL.OpenGL, SDL.DoubleBuf {-,SDL.NoFrame -} ] SDL.glSetAttribute SDL.glDoubleBuffer 1 SDL.setCaption title title GL.glViewport 0 0 (fromIntegral w) (fromIntegral h) let aspect = fromIntegral w / fromIntegral h GL.glOrtho (-1) 1 (-aspect) aspect (-1) 1 GL.glClearColor 1 1 1 1 GL.glClearDepth 1 GL.glDepthFunc GL.gl_LESS GL.glEnable GL.gl_BLEND GL.glBlendFunc GL.gl_SRC_ALPHA GL.gl_ONE_MINUS_SRC_ALPHA return s main :: IO () main = adapt dt game type Velocity = R2 instance Semigroup (Behavior t Picture) where (<>) = liftA2 (<>) instance Monoid (Behavior t Picture) where mempty = pure mempty mappend = (<>) fps :: Integer fps = 60 dt :: Integer dt = 1000 `div` fps game :: forall t. GameNetworkDescription t game frame time ui = do let title = "a breakout clone" (w,h) = (800,800) s <- liftIO $ initSDL title w h ctx <- liftIO createCtx let quit = exitSuccess <$ filterE (\(_,k) -> (k == SDL.SDLK_ESCAPE)) (key ui) scene :: Behavior t Picture scene = mconcat [ paddle, ball , pure wallPic , bricks smashed] -- ball ballPos = (p2 (0,0.5) .+^) <$> integral (time <@ frame) ballVel ballVel = r2 (0.4,0.5) `accumB` collision ball = moveTo <$> ballPos <*> pure ballPic paddle :: Behavior t Picture paddle = moveTo <$> paddlePos <*> pure paddlePic paddlePos :: Behavior t P2 paddlePos = curry p2 <$> (fitMouseX w <$> mouse ui) <*> pure 0 smashed = smash ballPos frame collision = R.unions [ wallHit ballPos frame , paddleHit paddlePos ballPos frame , R.unions smashed ] return $ (>>) <$> (display ctx <$> scene) <*> stepper (return ()) quit display :: Ctx -> Picture -> IO () display ctx dia = renderPic dia ctx fitMouseX :: Int -> (Int, Int) -> Double fitMouseX w (x,_) = 2*(fromIntegral x / fromIntegral w) - 1 paddlePic :: Picture paddlePic = unitBox # fc blue # scaleY 0.02 # scaleX 0.1 ballPic :: Picture ballPic = unitBox # fc gray # scale 0.04 paddleHit :: Behavior t P2 -> Behavior t P2 -> Event t () -> Event t (Velocity -> Velocity) paddleHit paddlePos ballPos frame = let c = colliding paddlePic <$> paddlePos <*> pure ballPic <*> ballPos response v@(unr2 -> (vx,vy)) = if vy < 0 then r2 (vx,-vy) else v in response <$ whenE c frame brickPic :: Picture brickPic = unitBox # scaleY 0.04 # scaleX 0.2 # fc yellow brick :: P2 -> Event t (Velocity -> Velocity) -> Behavior t Picture brick p e = moveTo p brickPic `stepper` (mempty <$ e) brickPositions :: [P2] brickPositions = map (p2 . flip (,) 0.98) [-0.9,-0.7..0.9] ++ map (p2 . flip (,) 0.94) [-0.9,-0.7..0.9] brickHit :: P2 -> Behavior t P2 -> Event t () -> Event t (Velocity -> Velocity) brickHit p ballPos frame = once response where c = whenE (colliding brickPic p ballPic <$> ballPos) frame response = (r2.second (negate.abs).unr2) <$ c smash :: Behavior t P2 -> Event t () -> [Event t (Velocity -> Velocity)] smash ballPos frame = map (\p -> brickHit p ballPos frame) brickPositions bricks :: [Event t (Velocity -> Velocity)] -> Behavior t Picture bricks smashed = mconcat $ zipWith brick brickPositions smashed ceilingPic :: Picture ceilingPic = unitBox # scaleX 2 # scaleY 0.04 # fc grey sidePic :: Picture sidePic = unitBox # scaleX 0.04 # fc grey wallPic :: Picture wallPic = moveTo ceilingPos ceilingPic <> moveTo wallLeftPos sidePic <> moveTo wallRightPos sidePic ceilingPos,wallLeftPos,wallRightPos :: P2 ceilingPos = p2 (0,1.02) wallLeftPos = p2 (-1.0,0.5) wallRightPos = p2 (1.0,0.5) wallHit :: Behavior t P2 -> Event t () -> Event t (Velocity -> Velocity) wallHit ballPos frame = R.unions [top,left,right] where cTop = colliding ceilingPic ceilingPos ballPic <$> ballPos top = (r2.second (negate.abs).unr2) <$ whenE cTop frame cLeft = colliding sidePic wallLeftPos ballPic <$> ballPos left = (r2.first abs.unr2) <$ whenE cLeft frame cRight = colliding sidePic wallRightPos ballPic <$> ballPos right = (r2.first (negate.abs).unr2) <$ whenE cRight frame reflect :: R2 -> R2 -> R2 reflect n i = i ^+^ negateV ((2.0 * (n <.> i)) *^ n) -- work around for bug in boundingBox, for more info: -- http://code.google.com/p/diagrams/issues/detail?id=87 -- will be removed! colliding :: Picture -> P2 -> Picture -> P2 -> Bool colliding d1 p1 d2 p2 = not $ isEmptyBox $ intersection (bbox d1 p1) (bbox d2 p2) bbox :: Picture -> P2 -> BoundingBox R2 bbox pic p = moveTo p (boundingBox pic)
bernstein/breakout
src/Main.hs
bsd-3-clause
5,820
0
16
1,272
2,017
1,051
966
122
2
import Data.Char import Data.List import System.IO import Data.List.Split import qualified Data.Map as M import qualified Data.Set as S import System.Directory inDir = ""--HAS TO BE ADDED BEFORE COMPILING AND EXECUTING; example: "/home/user/Documents/document_set/" stopWordFile = ""--HAS TO BE ADDED BEFORE COMPILING AND EXECUTING; example: "stopwords.txt" morphLexicon = ""--HAS TO BE ADDED BEFORE COMPILING AND EXECUTING; example: "morphLexicon.txt" stemN = 5 :: Int takeNumber = 960 :: Int getDict :: String -> M.Map String [String] -> M.Map String [String] getDict s m = M.insert fi le m where w = words s le = filter (\w' -> (isUpper $ head w') && length w' == 1) $ tail w fi = map toLower $ head w getLemma :: String -> M.Map String String -> M.Map String String getLemma s m = M.insert fi le m where w = words s fi = map toLower $ head w le = map (\c -> toLower c) $ head $ tail $ w lemmatize :: [String] -> M.Map String String -> [String] lemmatize ws m = map (\w -> solve w (M.lookup w m)) ws where solve w (Nothing) = w solve _ (Just a) = a getComb :: [String] -> [String] -> M.Map String [String] -> [String] getComb [] l _ = l getComb ss [] m = getComb (tail ss) el m where el = fin $ M.lookup (head ss) m fin (Just x) = x fin (Nothing) = ["X"] getComb ss l m = getComb (tail ss) con m where el = fin $ M.lookup (head ss) m fin (Just x) = x fin (Nothing) = ["X"] con = concat $ map (\el' -> map (\l' -> l' ++ el') l) el posPat = ["N","AN","NN","X","NSN","V"] filterPOS :: [String] -> M.Map String [String] -> Bool filterPOS phr m = any (\pat' -> elem pat' posPat) pat where pat = getComb phr [] m takeTuple :: [String] -> [[String]] takeTuple [] = [] takeTuple w | l >= 4 = [take 4 w] ++ [take 3 w] ++ [take 2 w] ++ [[head w]] ++ (takeTuple $ tail w) | l == 3 = [w] ++ [take 2 w] ++ [[head w]] ++ (takeTuple $ tail w) | l >= 2 = [w] ++ [[head w]] ++ [tail w] | otherwise = [w] where l = length w splitText :: String -> String -> [String] splitText word [] = [word] splitText word (t:ts) | not (isAlpha t || isSpace t || isDigit t || elem t "-'\"") = [word] ++ splitText "" ts | isDigit t || elem t "-'\"" = splitText word ts | isSpace t = splitText (word ++ " ") ts | otherwise = splitText (word ++ [toLower t]) ts makeTuples :: String -> [[String]] makeTuples = concat . map takeTuple . map words . splitText "" . filter (\x -> not (elem x "€—£§«»<@♦¬°►•[_{„¥©>^~■®▼]")) --krati riječ stem2 :: String -> String stem2 "" = error "stemming empty string" stem2 s | i >= stemN && i > div (length s) 2 = take i s | otherwise = s where i = if fi == [] then 10 else maximum fi fi = findIndices (\a -> elem a "aeiouAEIOU") s stem :: [String] -> [String] stem (x:[]) = [stem2 x] stem xs = map (take 5) xs getWordFreq :: [[String]] -> M.Map [String] Int getWordFreq = foldl (\map key -> M.insert (stem key) 1 map) M.empty getTextOnly :: String -> String getTextOnly s = ttl ++ " . " ++ txt where txt = head $ splitOn "</body>" $ last $ splitOn "<body>" s ttl = head $ splitOn "</title>" $ last $ splitOn "<title>" s filterFiles [] = error "empty folder" filterFiles fs = map (\f -> inDir ++ f) $ sort $ filter (\f -> isSuffixOf ".xml" f) fs getFileText stopW lem lemmas m' fn = do s <- readFile fn m <- m' let nm = getWordFreq $ map (\ph -> lemmatize ph lemmas) $ filter (\ph -> filterPOS ph lem) $ filter (removeStop stopW) $ makeTuples $ getTextOnly s return $ M.unionWith (+) m nm main = do sws <- readFile stopWordFile let stopW = S.fromList $ lines sws pos <- readFile morphLexicon let lem = foldl (\m a' -> (getDict a' m)) M.empty $ lines pos let lemmas = foldl (\m a' -> (getLemma a' m)) M.empty $ lines pos fns <- getDirectoryContents inDir let a = take takeNumber $ filterFiles fns let b = foldl (getFileText stopW lem lemmas) emptyMap a b' <- b writeFile "phraseFreq.txt" $ show $ M.toList b' emptyMap :: IO (M.Map [String] Int) emptyMap = return M.empty removeStop stopW (a:[]) = not (S.member a stopW) removeStop stopW (a:b:[]) = not (S.member a stopW) && not (S.member b stopW) removeStop stopW (a:b:c:[]) = not (S.member a stopW) && not (S.member c stopW) removeStop stopW (a:b:c:d:[]) = not (S.member a stopW) && not (S.member d stopW)
TakeLab/gpkex
getPhrFreq.hs
bsd-3-clause
4,400
0
18
1,033
2,139
1,078
1,061
98
3
{- | Module : $Header$ Description : Pretty printing for COL Copyright : (c) Wiebke Herding, C. Maeder, Uni Bremen 2004-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable pretty printing -} module COL.Print_AS where import qualified Data.Set as Set import qualified Data.Map as Map import Common.Doc import Common.DocUtils import CASL.ToDoc import COL.AS_COL import COL.COLSign instance Pretty COL_SIG_ITEM where pretty = printCOL_SIG_ITEM printCOL_SIG_ITEM :: COL_SIG_ITEM -> Doc printCOL_SIG_ITEM csi = case csi of Constructor_items ls _ -> keyword (constructorS ++ pluralS ls) <+> semiAnnos idDoc ls Observer_items ls _ -> keyword observerS <+> semiAnnos (printPair idDoc (printMaybe pretty)) ls instance Pretty COLSign where pretty = printCOLSign printCOLSign :: COLSign -> Doc printCOLSign s = keyword constructorS <+> fsep (punctuate semi $ map idDoc (Set.toList $ constructors s)) $+$ keyword observerS <+> fsep (punctuate semi $ map (printPair idDoc pretty) (Map.toList $ observers s))
keithodulaigh/Hets
COL/Print_AS.hs
gpl-2.0
1,160
0
14
230
268
138
130
24
2