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
module SpacialGameMsg.RunSGMsg where import SpacialGameMsg.SGModelMsg import qualified PureAgents2DDiscrete as Front import qualified Graphics.Gloss as GLO import Graphics.Gloss.Interface.IO.Simulate import qualified PureAgentsPar as PA import System.Random import Data.Maybe import Data.List winSize = (1000, 1000) winTitle = "Spacial Game MSG Par" runSGMsgWithRendering :: IO () runSGMsgWithRendering = do let dt = 1.0 let dims = (49, 49) let rngSeed = 42 let defectorsRatio = 0.0 let g = mkStdGen rngSeed let (as, g') = createRandomSGAgents g dims defectorsRatio let asWithDefector = setDefector as (24, 24) dims let env = sgEnvironmentFromAgents asWithDefector let hdl = PA.initStepSimulation asWithDefector env stepWithRendering dims hdl dt runSGMsgStepsAndRender :: IO () runSGMsgStepsAndRender = do let dt = 1.0 let dims = (99, 99) let rngSeed = 42 let steps = 2 * 218 let defectorsRatio = 0.0 let g = mkStdGen rngSeed let (as, g') = createRandomSGAgents g dims defectorsRatio let asWithDefector = setDefector as (49, 49) dims let env = sgEnvironmentFromAgents asWithDefector let (as', _) = PA.stepSimulation asWithDefector env dt steps let observableAgentStates = map (sgAgentToRenderCell dims) as' let frameRender = (Front.renderFrame observableAgentStates winSize dims) GLO.display (Front.display winTitle winSize) GLO.white frameRender return () setDefector :: [SGAgent] -> (Int, Int) -> (Int, Int) -> [SGAgent] setDefector as pos cells | isNothing mayAgentAtPos = as | otherwise = infront ++ [defectedAgentAtPos] ++ (tail behind) where mayAgentAtPos = find (\a -> pos == (agentToCell a cells)) as agentAtPos = (fromJust mayAgentAtPos) agentAtPosId = PA.agentId agentAtPos defectedAgentAtPos = PA.updateState agentAtPos (\s -> s { sgCurrState = Defector, sgPrevState = Defector, sgBestPayoff = (Defector, 0.0) } ) (infront, behind) = splitAt agentAtPosId as stepWithRendering :: (Int, Int) -> SGSimHandle -> Double -> IO () stepWithRendering dims hdl dt = simulateIO (Front.display winTitle winSize) GLO.white 2 hdl (modelToPicture dims) (stepIteration dt) modelToPicture :: (Int, Int) -> SGSimHandle -> IO GLO.Picture modelToPicture dims hdl = do let as = PA.extractHdlAgents hdl let cells = map (sgAgentToRenderCell dims) as return (Front.renderFrame cells winSize dims) stepIteration :: Double -> ViewPort -> Float -> SGSimHandle -> IO SGSimHandle stepIteration fixedDt viewport dtRendering hdl = return (PA.advanceSimulation hdl fixedDt) sgAgentToRenderCell :: (Int, Int) -> SGAgent -> Front.RenderCell sgAgentToRenderCell (xDim, yDim) a = Front.RenderCell { Front.renderCellCoord = (ax, ay), Front.renderCellColor = ss } where id = PA.agentId a s = PA.state a ax = mod id yDim ay = floor((fromIntegral id) / (fromIntegral xDim)) curr = sgCurrState s prev = sgPrevState s ss = sgAgentStateToColor prev curr sgAgentStateToColor :: SGState -> SGState -> (Double, Double, Double) sgAgentStateToColor Cooperator Cooperator = blueC sgAgentStateToColor Defector Defector = redC sgAgentStateToColor Defector Cooperator = greenC sgAgentStateToColor Cooperator Defector = yellowC blueC :: (Double, Double, Double) blueC = (0.0, 0.0, 0.7) greenC :: (Double, Double, Double) greenC = (0.0, 0.4, 0.0) redC :: (Double, Double, Double) redC = (0.7, 0.0, 0.0) yellowC :: (Double, Double, Double) yellowC = (1.0, 0.9, 0.0)
thalerjonathan/phd
public/ArtIterating/code/haskell/PureAgentsPar/src/SpacialGameMsg/RunSGMsg.hs
gpl-3.0
4,559
0
12
1,703
1,195
629
566
87
1
module Helium.StaticAnalysis.Messages.Information where import Top.Types import Helium.Main.CompileUtils import Helium.Parser.OperatorTable import Helium.StaticAnalysis.Messages.Messages hiding (Constructor) import Helium.Syntax.UHA_Syntax hiding (Fixity) import Helium.Syntax.UHA_Utils import Helium.Syntax.UHA_Range import qualified Data.Map as M type Fixity = (Int, Assoc) data InfoItem = Function Name TpScheme (Maybe Fixity) | ValueConstructor Name TpScheme (Maybe Fixity) | TypeSynonym Name Int (Tps -> Tp) | DataTypeConstructor Name Int [(Name, TpScheme)] | TypeClass String Class | NotDefined String showInformation :: Bool -> [Option] -> ImportEnvironment -> IO () showInformation reportNotFound options importEnv = let items = concat [ makeInfoItem name | Information name <- options ] in showMessages items where makeInfoItem :: String -> [InfoItem] makeInfoItem string = let notFound items = if null items && reportNotFound then [ NotDefined string ] else items function = case lookupWithKey (nameFromString string) (typeEnvironment importEnv) of Just (name, scheme) -> [Function name scheme (M.lookup name (operatorTable importEnv))] Nothing -> [] constructor = case lookupWithKey (nameFromString string) (valueConstructors importEnv) of Just (name, scheme) -> [ValueConstructor name scheme (M.lookup name (operatorTable importEnv))] Nothing -> [] synonyms = case lookupWithKey (nameFromString string) (typeSynonyms importEnv) of Just (name, (i, f)) -> [TypeSynonym name i f] Nothing -> [] datatypeconstructor = case lookupWithKey (nameFromString string) (typeConstructors importEnv) of Just (name, i) | not (M.member name (typeSynonyms importEnv)) -> [DataTypeConstructor name i (findValueConstructors name importEnv)] _ -> [] typeclass = case M.lookup string standardClasses of Just cl -> [TypeClass string cl] Nothing -> [] in notFound (function ++ constructor ++ synonyms ++ datatypeconstructor ++ typeclass) itemDescription :: InfoItem -> [String] itemDescription infoItem = case infoItem of Function name ts _ -> let tp = unqualify (unquantify ts) start | isOperatorName name = "operator" | isFunctionType tp = "function" | otherwise = "value" in [ "-- " ++ start ++ " " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ] ValueConstructor name _ _ -> [ "-- value constructor " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ] TypeSynonym name _ _ -> [ "-- type synonym " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ] DataTypeConstructor name _ _ -> [ "-- type constructor " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ] TypeClass s _ -> [ " -- type class " ++ s ] NotDefined _ -> [ ] definedOrImported :: Range -> String definedOrImported range | isImportRange range = "imported from " ++ show range | otherwise = "defined at " ++ show range showMaybeFixity :: Name -> Maybe Fixity -> MessageBlocks showMaybeFixity name = let f (prio', associativity) = show associativity ++ " " ++ show prio' ++ " " ++ showNameAsOperator name in maybe [] ((:[]) . MessageString . f) instance HasMessage InfoItem where getMessage infoItem = map (MessageOneLiner . MessageString) (itemDescription infoItem) ++ case infoItem of Function name ts mFixity -> map MessageOneLiner ( MessageString (showNameAsVariable name ++ " :: " ++ show ts) : showMaybeFixity name mFixity ) ValueConstructor name ts mFixity -> map MessageOneLiner ( MessageString (showNameAsVariable name ++ " :: " ++ show ts) : showMaybeFixity name mFixity ) TypeSynonym name i f -> let tps = take i [ TCon [c] | c <- ['a'..] ] text = unwords ("type" : show name : map show tps ++ ["=", show (f tps)]) in [ MessageOneLiner (MessageString text) ] DataTypeConstructor name i cons -> let tps = take i [ TCon [c] | c <- ['a'..] ] text = unwords ("data" : show name : map show tps) related = let f (name', ts) = " " ++ showNameAsVariable name' ++ " :: " ++ show ts in if null cons then [] else " -- value constructors" : map f cons in map MessageOneLiner ( MessageString text : map MessageString related ) TypeClass name (supers, theInstances) -> let f s = s ++ " a" text = "class " ++ showContextSimple (map f supers) ++ f name related = let ef (p, ps) = " instance " ++ show (generalizeAll (ps .=>. p)) in if null theInstances then [] else " -- instances" : map ef theInstances in map MessageOneLiner ( MessageString text : map MessageString related ) NotDefined name -> map MessageOneLiner [ MessageString (show name ++ " not defined") ] findValueConstructors :: Name -> ImportEnvironment -> [(Name, TpScheme)] findValueConstructors name = let test = isName . fst . leftSpine . snd . functionSpine . unqualify . unquantify isName (TCon s) = s == show name isName _ = False in M.assocs . M.filter test . valueConstructors lookupWithKey :: Ord key => key -> M.Map key a -> Maybe (key, a) lookupWithKey key = M.lookup key . M.mapWithKey (,)
roberth/uu-helium
src/Helium/StaticAnalysis/Messages/Information.hs
gpl-3.0
6,163
0
23
2,068
1,837
919
918
121
7
{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving, TupleSections #-} module Lamdu.GUI.IOTrans ( IOTrans(..), ioTrans, trans, liftTrans, liftIO, liftIOT, liftTIO ) where import qualified Control.Lens as Lens import Data.Functor.Compose (Compose(..)) import Revision.Deltum.Transaction (Transaction) import Lamdu.Prelude type T = Transaction -- | IOTrans is an applicative that allows 3 phases of execution: -- A. IO action (e.g: to read a JSON file) -- B. A transaction (allowed to depend on A) -- C. A final IO action (allowed to depend on B) (e.g: -- to write a JSON file) newtype IOTrans m a = IOTrans { _ioTrans :: Compose IO (Compose (T m) ((,) (IO ()))) a } deriving newtype (Functor, Applicative) Lens.makeLenses ''IOTrans trans :: Lens.Setter (IOTrans m a) (IOTrans n b) (T m (IO (), a)) (T n (IO (), b)) trans f (IOTrans (Compose act)) = (Lens.mapped . Lens._Wrapped) f act <&> Compose <&> IOTrans liftTrans :: Functor m => T m a -> IOTrans m a liftTrans = IOTrans . Compose . pure . Compose . fmap pure -- | IOTrans is not a Monad, so it isn't a MonadTrans. But it can lift IO actions liftIO :: Monad m => IO a -> IOTrans m a liftIO act = act <&> pure & Compose & IOTrans liftIOT :: Functor m => IO (T m a) -> IOTrans m a liftIOT = IOTrans . Compose . fmap (Compose . fmap pure) -- | Run T / IO liftTIO :: Functor m => T m (IO ()) -> IOTrans m () liftTIO act = act <&> (, ()) & Compose & pure & Compose & IOTrans
lamdu/lamdu
src/Lamdu/GUI/IOTrans.hs
gpl-3.0
1,544
0
14
379
501
269
232
-1
-1
import Control.Arrow ((&&&)) import Test.Hspec (Spec, describe, it, shouldBe, shouldNotBe) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) import qualified Data.Vector as Vector (fromList) import Matrix ( Matrix , cols , column , flatten , fromList , fromString , reshape , row , rows , shape , transpose ) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = describe "matrix" $ do -- As of 2016-08-08, there was no reference file -- for the test cases in `exercism/x-common`. let intMatrix = fromString :: String -> Matrix Int let vector = Vector.fromList it "extract first row" $ do row 0 (intMatrix "1 2\n10 20") `shouldBe` vector [1, 2] row 0 (intMatrix "9 7\n8 6" ) `shouldBe` vector [9, 7] it "extract second row" $ do row 1 (intMatrix "9 8 7\n19 18 17") `shouldBe` vector [19, 18, 17] row 1 (intMatrix "1 4 9\n16 25 36") `shouldBe` vector [16, 25, 36] it "extract first column" $ do column 0 (intMatrix "1 2 3\n4 5 6\n7 8 9\n 8 7 6") `shouldBe` vector [1, 4, 7, 8] column 1 (intMatrix "89 1903 3\n18 3 1\n9 4 800") `shouldBe` vector [1903, 3, 4] it "shape" $ do shape (intMatrix "" ) `shouldBe` (0, 0) shape (intMatrix "1" ) `shouldBe` (1, 1) shape (intMatrix "1\n2" ) `shouldBe` (2, 1) shape (intMatrix "1 2" ) `shouldBe` (1, 2) shape (intMatrix "1 2\n3 4") `shouldBe` (2, 2) it "rows & cols" $ (rows &&& cols) (intMatrix "1 2") `shouldBe` (1, 2) it "eq" $ do intMatrix "1 2" `shouldBe` intMatrix "1 2" intMatrix "2 3" `shouldNotBe` intMatrix "1 2 3" it "fromList" $ do fromList [[1 , 2]] `shouldBe` intMatrix "1 2" fromList [[1], [2]] `shouldBe` intMatrix "1\n2" it "transpose" $ do transpose (intMatrix "1\n2\n3" ) `shouldBe` intMatrix "1 2 3" transpose (intMatrix "1 4\n2 5\n3 6") `shouldBe` intMatrix "1 2 3\n4 5 6" it "reshape" $ reshape (2, 2) (intMatrix "1 2 3 4") `shouldBe` intMatrix "1 2\n3 4" it "flatten" $ flatten (intMatrix "1 2\n3 4") `shouldBe` vector [1, 2, 3, 4] it "matrix of chars" $ fromString "'f' 'o' 'o'\n'b' 'a' 'r'" `shouldBe` fromList ["foo", "bar"] it "matrix of strings" $ fromString "\"this one\"\n\"may be tricky!\"" `shouldBe` fromList [ ["this one" ] , ["may be tricky!"] ] it "matrix of strings 2" $ fromString "\"this one\" \"one\" \n\"may be tricky!\" \"really tricky\"" `shouldBe` fromList [ ["this one" , "one" ] , ["may be tricky!", "really tricky"] ]
daewon/til
exercism/haskell/matrix/test/Tests.hs
mpl-2.0
2,760
0
14
805
898
475
423
64
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Directory.OrgUnits.Insert -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Adds an organizational unit. -- -- /See:/ <https://developers.google.com/admin-sdk/ Admin SDK API Reference> for @directory.orgunits.insert@. module Network.Google.Resource.Directory.OrgUnits.Insert ( -- * REST Resource OrgUnitsInsertResource -- * Creating a Request , orgUnitsInsert , OrgUnitsInsert -- * Request Lenses , ouiXgafv , ouiUploadProtocol , ouiAccessToken , ouiUploadType , ouiPayload , ouiCustomerId , ouiCallback ) where import Network.Google.Directory.Types import Network.Google.Prelude -- | A resource alias for @directory.orgunits.insert@ method which the -- 'OrgUnitsInsert' request conforms to. type OrgUnitsInsertResource = "admin" :> "directory" :> "v1" :> "customer" :> Capture "customerId" Text :> "orgunits" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] OrgUnit :> Post '[JSON] OrgUnit -- | Adds an organizational unit. -- -- /See:/ 'orgUnitsInsert' smart constructor. data OrgUnitsInsert = OrgUnitsInsert' { _ouiXgafv :: !(Maybe Xgafv) , _ouiUploadProtocol :: !(Maybe Text) , _ouiAccessToken :: !(Maybe Text) , _ouiUploadType :: !(Maybe Text) , _ouiPayload :: !OrgUnit , _ouiCustomerId :: !Text , _ouiCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OrgUnitsInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ouiXgafv' -- -- * 'ouiUploadProtocol' -- -- * 'ouiAccessToken' -- -- * 'ouiUploadType' -- -- * 'ouiPayload' -- -- * 'ouiCustomerId' -- -- * 'ouiCallback' orgUnitsInsert :: OrgUnit -- ^ 'ouiPayload' -> Text -- ^ 'ouiCustomerId' -> OrgUnitsInsert orgUnitsInsert pOuiPayload_ pOuiCustomerId_ = OrgUnitsInsert' { _ouiXgafv = Nothing , _ouiUploadProtocol = Nothing , _ouiAccessToken = Nothing , _ouiUploadType = Nothing , _ouiPayload = pOuiPayload_ , _ouiCustomerId = pOuiCustomerId_ , _ouiCallback = Nothing } -- | V1 error format. ouiXgafv :: Lens' OrgUnitsInsert (Maybe Xgafv) ouiXgafv = lens _ouiXgafv (\ s a -> s{_ouiXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ouiUploadProtocol :: Lens' OrgUnitsInsert (Maybe Text) ouiUploadProtocol = lens _ouiUploadProtocol (\ s a -> s{_ouiUploadProtocol = a}) -- | OAuth access token. ouiAccessToken :: Lens' OrgUnitsInsert (Maybe Text) ouiAccessToken = lens _ouiAccessToken (\ s a -> s{_ouiAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ouiUploadType :: Lens' OrgUnitsInsert (Maybe Text) ouiUploadType = lens _ouiUploadType (\ s a -> s{_ouiUploadType = a}) -- | Multipart request metadata. ouiPayload :: Lens' OrgUnitsInsert OrgUnit ouiPayload = lens _ouiPayload (\ s a -> s{_ouiPayload = a}) -- | The unique ID for the customer\'s Google Workspace account. As an -- account administrator, you can also use the \`my_customer\` alias to -- represent your account\'s \`customerId\`. The \`customerId\` is also -- returned as part of the [Users -- resource](\/admin-sdk\/directory\/v1\/reference\/users). ouiCustomerId :: Lens' OrgUnitsInsert Text ouiCustomerId = lens _ouiCustomerId (\ s a -> s{_ouiCustomerId = a}) -- | JSONP ouiCallback :: Lens' OrgUnitsInsert (Maybe Text) ouiCallback = lens _ouiCallback (\ s a -> s{_ouiCallback = a}) instance GoogleRequest OrgUnitsInsert where type Rs OrgUnitsInsert = OrgUnit type Scopes OrgUnitsInsert = '["https://www.googleapis.com/auth/admin.directory.orgunit"] requestClient OrgUnitsInsert'{..} = go _ouiCustomerId _ouiXgafv _ouiUploadProtocol _ouiAccessToken _ouiUploadType _ouiCallback (Just AltJSON) _ouiPayload directoryService where go = buildClient (Proxy :: Proxy OrgUnitsInsertResource) mempty
brendanhay/gogol
gogol-admin-directory/gen/Network/Google/Resource/Directory/OrgUnits/Insert.hs
mpl-2.0
5,167
0
20
1,252
794
463
331
116
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AdExchangeBuyer2.Accounts.Creatives.Watch -- 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) -- -- Watches a creative. Will result in push notifications being sent to the -- topic when the creative changes status. -- -- /See:/ <https://developers.google.com/authorized-buyers/apis/reference/rest/ Ad Exchange Buyer API II Reference> for @adexchangebuyer2.accounts.creatives.watch@. module Network.Google.Resource.AdExchangeBuyer2.Accounts.Creatives.Watch ( -- * REST Resource AccountsCreativesWatchResource -- * Creating a Request , accountsCreativesWatch , AccountsCreativesWatch -- * Request Lenses , acwXgafv , acwUploadProtocol , acwAccessToken , acwUploadType , acwCreativeId , acwPayload , acwAccountId , acwCallback ) where import Network.Google.AdExchangeBuyer2.Types import Network.Google.Prelude -- | A resource alias for @adexchangebuyer2.accounts.creatives.watch@ method which the -- 'AccountsCreativesWatch' request conforms to. type AccountsCreativesWatchResource = "v2beta1" :> "accounts" :> Capture "accountId" Text :> "creatives" :> CaptureMode "creativeId" "watch" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] WatchCreativeRequest :> Post '[JSON] Empty -- | Watches a creative. Will result in push notifications being sent to the -- topic when the creative changes status. -- -- /See:/ 'accountsCreativesWatch' smart constructor. data AccountsCreativesWatch = AccountsCreativesWatch' { _acwXgafv :: !(Maybe Xgafv) , _acwUploadProtocol :: !(Maybe Text) , _acwAccessToken :: !(Maybe Text) , _acwUploadType :: !(Maybe Text) , _acwCreativeId :: !Text , _acwPayload :: !WatchCreativeRequest , _acwAccountId :: !Text , _acwCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AccountsCreativesWatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acwXgafv' -- -- * 'acwUploadProtocol' -- -- * 'acwAccessToken' -- -- * 'acwUploadType' -- -- * 'acwCreativeId' -- -- * 'acwPayload' -- -- * 'acwAccountId' -- -- * 'acwCallback' accountsCreativesWatch :: Text -- ^ 'acwCreativeId' -> WatchCreativeRequest -- ^ 'acwPayload' -> Text -- ^ 'acwAccountId' -> AccountsCreativesWatch accountsCreativesWatch pAcwCreativeId_ pAcwPayload_ pAcwAccountId_ = AccountsCreativesWatch' { _acwXgafv = Nothing , _acwUploadProtocol = Nothing , _acwAccessToken = Nothing , _acwUploadType = Nothing , _acwCreativeId = pAcwCreativeId_ , _acwPayload = pAcwPayload_ , _acwAccountId = pAcwAccountId_ , _acwCallback = Nothing } -- | V1 error format. acwXgafv :: Lens' AccountsCreativesWatch (Maybe Xgafv) acwXgafv = lens _acwXgafv (\ s a -> s{_acwXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). acwUploadProtocol :: Lens' AccountsCreativesWatch (Maybe Text) acwUploadProtocol = lens _acwUploadProtocol (\ s a -> s{_acwUploadProtocol = a}) -- | OAuth access token. acwAccessToken :: Lens' AccountsCreativesWatch (Maybe Text) acwAccessToken = lens _acwAccessToken (\ s a -> s{_acwAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). acwUploadType :: Lens' AccountsCreativesWatch (Maybe Text) acwUploadType = lens _acwUploadType (\ s a -> s{_acwUploadType = a}) -- | The creative ID to watch for status changes. Specify \"-\" to watch all -- creatives under the above account. If both creative-level and -- account-level notifications are sent, only a single notification will be -- sent to the creative-level notification topic. acwCreativeId :: Lens' AccountsCreativesWatch Text acwCreativeId = lens _acwCreativeId (\ s a -> s{_acwCreativeId = a}) -- | Multipart request metadata. acwPayload :: Lens' AccountsCreativesWatch WatchCreativeRequest acwPayload = lens _acwPayload (\ s a -> s{_acwPayload = a}) -- | The account of the creative to watch. acwAccountId :: Lens' AccountsCreativesWatch Text acwAccountId = lens _acwAccountId (\ s a -> s{_acwAccountId = a}) -- | JSONP acwCallback :: Lens' AccountsCreativesWatch (Maybe Text) acwCallback = lens _acwCallback (\ s a -> s{_acwCallback = a}) instance GoogleRequest AccountsCreativesWatch where type Rs AccountsCreativesWatch = Empty type Scopes AccountsCreativesWatch = '["https://www.googleapis.com/auth/adexchange.buyer"] requestClient AccountsCreativesWatch'{..} = go _acwAccountId _acwCreativeId _acwXgafv _acwUploadProtocol _acwAccessToken _acwUploadType _acwCallback (Just AltJSON) _acwPayload adExchangeBuyer2Service where go = buildClient (Proxy :: Proxy AccountsCreativesWatchResource) mempty
brendanhay/gogol
gogol-adexchangebuyer2/gen/Network/Google/Resource/AdExchangeBuyer2/Accounts/Creatives/Watch.hs
mpl-2.0
6,043
0
19
1,387
865
505
360
127
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.Tracing -- 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) -- -- Send and retrieve trace data from Google Stackdriver Trace. -- -- /See:/ <https://cloud.google.com/trace Google Tracing API Reference> module Network.Google.Tracing ( -- * Service Configuration tracingService -- * OAuth Scopes , traceAppendScope , traceReadOnlyScope , cloudPlatformScope -- * API Declaration , TracingAPI -- * Resources -- ** tracing.projects.traces.batchWrite , module Network.Google.Resource.Tracing.Projects.Traces.BatchWrite -- ** tracing.projects.traces.list , module Network.Google.Resource.Tracing.Projects.Traces.List -- ** tracing.projects.traces.listSpans , module Network.Google.Resource.Tracing.Projects.Traces.ListSpans -- ** tracing.projects.traces.spans.create , module Network.Google.Resource.Tracing.Projects.Traces.Spans.Create -- * Types -- ** Span , Span , span , sStatus , sStartTime , sName , sStackTrace , sAttributes , sEndTime , sTimeEvents , sDisplayName , sParentSpanId , sLinks , sSpanId -- ** TruncatableString , TruncatableString , truncatableString , tsTruncatedCharacterCount , tsValue -- ** Status , Status , status , sDetails , sCode , sMessage -- ** AttributesAttributeMap , AttributesAttributeMap , attributesAttributeMap , aamAddtional -- ** Annotation , Annotation , annotation , aAttributes , aDescription -- ** AttributeValue , AttributeValue , attributeValue , avBoolValue , avIntValue , avStringValue -- ** NetworkEventType , NetworkEventType (..) -- ** Empty , Empty , empty -- ** Link , Link , link , lTraceId , lType , lSpanId -- ** StatusDetailsItem , StatusDetailsItem , statusDetailsItem , sdiAddtional -- ** ListSpansResponse , ListSpansResponse , listSpansResponse , lsrNextPageToken , lsrSpans -- ** StackTrace , StackTrace , stackTrace , stStackTraceHashId , stStackFrames -- ** BatchWriteSpansRequest , BatchWriteSpansRequest , batchWriteSpansRequest , bwsrSpans -- ** Attributes , Attributes , attributes , aDroppedAttributesCount , aAttributeMap -- ** NetworkEvent , NetworkEvent , networkEvent , neTime , neMessageSize , neType , neMessageId -- ** Module , Module , module' , mBuildId , mModule -- ** TimeEvents , TimeEvents , timeEvents , teDroppedAnnotationsCount , teDroppedNetworkEventsCount , teTimeEvent -- ** Xgafv , Xgafv (..) -- ** StackFrames , StackFrames , stackFrames , sfDroppedFramesCount , sfFrame -- ** LinkType , LinkType (..) -- ** StackFrame , StackFrame , stackFrame , sfLoadModule , sfOriginalFunctionName , sfLineNumber , sfSourceVersion , sfFunctionName , sfColumnNumber , sfFileName -- ** Links , Links , links , lDroppedLinksCount , lLink -- ** ListTracesResponse , ListTracesResponse , listTracesResponse , ltrNextPageToken , ltrTraces -- ** TimeEvent , TimeEvent , timeEvent , teAnnotation , teTime , teNetworkEvent -- ** Trace , Trace , trace , tName ) where import Network.Google.Prelude import Network.Google.Resource.Tracing.Projects.Traces.BatchWrite import Network.Google.Resource.Tracing.Projects.Traces.List import Network.Google.Resource.Tracing.Projects.Traces.ListSpans import Network.Google.Resource.Tracing.Projects.Traces.Spans.Create import Network.Google.Tracing.Types {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Google Tracing API service. type TracingAPI = ProjectsTracesSpansCreateResource :<|> ProjectsTracesListResource :<|> ProjectsTracesBatchWriteResource :<|> ProjectsTracesListSpansResource
brendanhay/gogol
gogol-tracing/gen/Network/Google/Tracing.hs
mpl-2.0
4,519
0
7
1,164
523
378
145
133
0
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} -- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. -- In addition, you can configure a number of different aspects of Yesod -- by overriding methods in the Yesod typeclass. That instance is -- declared in the Foundation.hs file. module Settings ( hamletFile , cassiusFile , juliusFile , luciusFile , widgetFile , connStr , ConnectionPool , withConnectionPool , runConnectionPool , approot , staticroot , staticdir ) where import qualified Text.Hamlet as H import qualified Text.Cassius as H import qualified Text.Julius as H import qualified Text.Lucius as H import Language.Haskell.TH.Syntax import Database.Persist.Sqlite import Yesod (MonadControlIO, addWidget, addCassius, addJulius, addLucius) import Data.Monoid (mempty, mappend) import System.Directory (doesFileExist) import Data.Text (Text) -- | The base URL for your application. This will usually be different for -- development and production. Yesod automatically constructs URLs for you, -- so this value must be accurate to create valid links. -- Please note that there is no trailing slash. approot :: Text approot = #ifdef PRODUCTION -- You probably want to change this. If your domain name was "yesod.com", -- you would probably want it to be: -- > "http://yesod.com" "http://localhost:3000" #else "http://localhost:3000" #endif -- | The location of static files on your system. This is a file system -- path. The default value works properly with your scaffolded site. staticdir :: FilePath staticdir = "static" -- | The base URL for your static files. As you can see by the default -- value, this can simply be "static" appended to your application root. -- A powerful optimization can be serving static files from a separate -- domain name. This allows you to use a web server optimized for static -- files, more easily set expires and cache values, and avoid possibly -- costly transference of cookies on static files. For more information, -- please see: -- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain -- -- If you change the resource pattern for StaticR in Foundation.hs, you will -- have to make a corresponding change here. -- -- To see how this value is used, see urlRenderOverride in Foundation.hs staticroot :: Text staticroot = approot `mappend` "/static" -- | The database connection string. The meaning of this string is backend- -- specific. connStr :: Text connStr = #ifdef PRODUCTION "production.db3" #else "debug.db3" #endif -- | Your application will keep a connection pool and take connections from -- there as necessary instead of continually creating new connections. This -- value gives the maximum number of connections to be open at a given time. -- If your application requests a connection when all connections are in -- use, that request will fail. Try to choose a number that will work well -- with the system resources available to you while providing enough -- connections for your expected load. -- -- Also, connections are returned to the pool as quickly as possible by -- Yesod to avoid resource exhaustion. A connection is only considered in -- use while within a call to runDB. connectionCount :: Int connectionCount = 10 -- The rest of this file contains settings which rarely need changing by a -- user. -- The following three functions are used for calling HTML, CSS and -- Javascript templates from your Haskell code. During development, -- the "Debug" versions of these functions are used so that changes to -- the templates are immediately reflected in an already running -- application. When making a production compile, the non-debug version -- is used for increased performance. -- -- You can see an example of how to call these functions in Handler/Root.hs -- -- Note: due to polymorphic Hamlet templates, hamletFileDebug is no longer -- used; to get the same auto-loading effect, it is recommended that you -- use the devel server. -- | expects a root folder for each type, e.g: hamlet/ lucius/ julius/ globFile :: String -> String -> FilePath globFile kind x = kind ++ "/" ++ x ++ "." ++ kind hamletFile :: FilePath -> Q Exp hamletFile = H.hamletFile . globFile "hamlet" cassiusFile :: FilePath -> Q Exp cassiusFile = #ifdef PRODUCTION H.cassiusFile . globFile "cassius" #else H.cassiusFileDebug . globFile "cassius" #endif luciusFile :: FilePath -> Q Exp luciusFile = #ifdef PRODUCTION H.luciusFile . globFile "lucius" #else H.luciusFileDebug . globFile "lucius" #endif juliusFile :: FilePath -> Q Exp juliusFile = #ifdef PRODUCTION H.juliusFile . globFile "julius" #else H.juliusFileDebug . globFile "julius" #endif widgetFile :: FilePath -> Q Exp widgetFile x = do let h = unlessExists (globFile "hamlet") hamletFile let c = unlessExists (globFile "cassius") cassiusFile let j = unlessExists (globFile "julius") juliusFile let l = unlessExists (globFile "lucius") luciusFile [|addWidget $h >> addCassius $c >> addJulius $j >> addLucius $l|] where unlessExists tofn f = do e <- qRunIO $ doesFileExist $ tofn x if e then f x else [|mempty|] -- The next two functions are for allocating a connection pool and running -- database actions using a pool, respectively. It is used internally -- by the scaffolded application, and therefore you will rarely need to use -- them yourself. withConnectionPool :: MonadControlIO m => (ConnectionPool -> m a) -> m a withConnectionPool = withSqlitePool connStr connectionCount runConnectionPool :: MonadControlIO m => SqlPersist m a -> ConnectionPool -> m a runConnectionPool = runSqlPool
tehgeekmeister/apters-web
config/Settings.hs
agpl-3.0
5,799
0
12
1,024
641
386
255
65
2
zItazySunefp twgq nlyo lwojjoBiecao = let mhIarjyai = ukwAausnfcn $ XojlsTOSR.vuwOvuvdAZUOJaa $ XojlsTOSR.vkesForanLiufjeDI $ XojlsTOSR.vkesForanLiufjeDI $ XojlsTOSR.popjAyijoWarueeP $ XojlsTOSR.jpwuPmafuDqlbkt nlyo $ XojlsTOSR.jpwuPmafuDqlbkt xxneswWhxwng $ XojlsTOSR.jpwuPmafuDqlbkt oloCuxeDdow $ XojlsTOSR.jpwuPmafuDqlbkt (uwurrvoNnukzefuDjeh lwojjoBiecao nlyo) $ etOslnoz lwojjoBiecao in kucotg $ (bbbr, Yoxe.Dwzbuzi.zrLokoTnuy piv)
lspitzner/brittany
data/Test345.hs
agpl-3.0
540
0
18
143
115
55
60
13
1
-- yammat - Yet Another MateMAT -- Copyright (C) 2015 Amedeo Molnár -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero 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 Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. module Handler.Buy where import Import import Handler.Common import Text.Shakespeare.Text getBuyR :: UserId -> BeverageId -> Handler Html getBuyR uId bId = do (_, bev) <- checkData uId bId master <- getYesod (buyWidget, enctype) <- generateFormPost $ renderBootstrap3 BootstrapBasicForm $ buyForm defaultLayout $ $(widgetFile "buy") postBuyR :: UserId -> BeverageId -> Handler Html postBuyR uId bId = do (user, bev) <- checkData uId bId ((res, _), _) <- runFormPost $ renderBootstrap3 BootstrapBasicForm $ buyForm case res of FormSuccess quant -> do if quant > beverageAmount bev then do setMessageI MsgNotEnoughItems redirect $ BuyR uId bId else do let price = quant * (beveragePrice bev) let sw = price > (userBalance user) today <- liftIO $ return . utctDay =<< getCurrentTime runDB $ do update uId [UserTimestamp =. today] update uId [UserBalance -=. price] update bId [BeverageAmount -=. quant] checkAlert bId master <- getYesod liftIO $ notifyUser user bev quant price master case sw of False -> do setMessageI MsgPurchaseSuccess redirect HomeR True -> do let level = case userBalance user - price of balance | balance <= -5000 -> 3 | balance <= -1000 -> 2 | otherwise -> 1 redirect $ DemandR level _ -> do setMessageI MsgErrorOccured redirect HomeR notifyUser :: User -> Beverage -> Int -> Int -> App -> IO () notifyUser user bev quant price master = do case userEmail user of Just email -> do addendum <- if (userBalance user - price) < 0 then return $ "\n\nDein Guthaben Beträgt im Moment " ++ formatIntCurrency (userBalance user - price) ++ appCurrency (appSettings master) ++ ".\n" ++ "LADE DEIN GUTHABEN AUF!\n" ++ "VERDAMMT NOCHMAL!!!" else return "" liftIO $ sendMail email "Einkauf beim Matematen" [lt| Hallo #{userIdent user}, Du hast gerade beim Matematen #{quant} x #{beverageIdent bev} für #{formatIntCurrency price}#{appCurrency $ appSettings master} eingekauft.#{addendum} Viele Grüße, Dein Matemat |] Nothing -> return () getBuyCashR :: BeverageId -> Handler Html getBuyCashR bId = do mBev <- runDB $ get bId case mBev of Just bev -> do master <- getYesod (buyCashWidget, enctype) <- generateFormPost $ renderBootstrap3 BootstrapBasicForm $ buyForm defaultLayout $ $(widgetFile "buyCash") Nothing -> do setMessageI MsgItemUnknown redirect HomeR postBuyCashR :: BeverageId -> Handler Html postBuyCashR bId = isBeverage bId HomeR >>= (\bev -> do ((res, _), _) <- runFormPost $ renderBootstrap3 BootstrapBasicForm $ buyForm case res of FormSuccess quant -> do if quant > beverageAmount bev then do setMessageI MsgNotEnoughItems redirect $ BuyCashR bId else do master <- getYesod let price = quant * (beveragePrice bev + appCashCharge (appSettings master)) runDB $ update bId [BeverageAmount -=. quant] updateCashier price "Barzahlung" checkAlert bId let currency = appCurrency $ appSettings master setMessageI $ MsgPurchaseSuccessCash price currency redirect HomeR _ -> do setMessageI MsgItemDisappeared redirect HomeR ) checkData :: UserId -> BeverageId -> Handler (User, Beverage) checkData uId bId = isUser uId HomeR >>= (\user -> do isBeverage bId HomeR >>= (\bev -> return (user, bev) ) ) buyForm :: AForm Handler Int buyForm = areq amountField (bfs MsgAmount) (Just 1) <* bootstrapSubmit (msgToBSSubmit MsgPurchase)
Mic92/yammat
Handler/Buy.hs
agpl-3.0
4,826
0
30
1,468
1,162
557
605
-1
-1
module Lupo.Backends.View ( makeViewFactory ) where import Lupo.Application import qualified Lupo.Backends.View.Views as V import Lupo.View makeViewFactory :: ViewFactory LupoHandler makeViewFactory = ViewFactory { _singleDayView = V.singleDayView , _multiDaysView = V.multiDaysView , _monthView = V.monthView , _searchResultView = V.searchResultView , _loginView = V.loginView , _initAccountView = V.initAccountView , _adminView = V.adminView , _entryEditorView = V.entryEditorView , _entryPreviewView = V.entryPreviewView , _entriesFeed = V.entriesFeed }
keitax/lupo
src/Lupo/Backends/View.hs
lgpl-3.0
585
0
7
91
127
80
47
17
1
module Main where import qualified Data.ByteString.Lazy.Char8 as BL import System.Environment (getArgs) import Data.Aeson (decode, Value) import Data.Aeson.Encode.Pretty (encodePretty) import Data.Aeson.Query printJson j = BL.putStrLn $ encodePretty j main = do arg <- fmap head getArgs case parseFilter arg of Left e -> error $ show e Right filter -> do Just ast <- fmap decode $ BL.getContents printJson $ applyFilter filter ast
jaimeMF/aeson-query
aeson-query.hs
unlicense
493
0
14
124
155
81
74
14
2
-- | -- Module : DMSS.Crypto -- License : Public Domain -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : untested -- -- Dead Man Switch System crypto functions -- --{-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE DataKinds #-} module DMSS.Crypto where import DMSS.Storage.Types ( BoxKeypairStore (..) , SignKeypairStore (..) , HashSalt, toHashSalt , CheckInProof, unCheckInProof, mkCheckInProof ) import Crypto.Lithium.SecretBox ( Key , secretBox , getCiphertext , openSecretBox ) import qualified Crypto.Lithium.Box as B import qualified Crypto.Lithium.Sign as S import qualified Crypto.Lithium.Unsafe.Sign as SU import qualified Crypto.Lithium.SecretBox as SB import qualified Crypto.Lithium.Password as P import Crypto.Lithium.Unsafe.Types ( Plaintext (..) , Secret (..) -- , BytesN ) import Data.String (fromString) import Data.ByteArray import Data.ByteArray.Sized import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Base64 as B64 encryptBoxKeypair :: Key -> B.Keypair -> IO BoxKeypairStore encryptBoxKeypair symKey (B.Keypair sk pk) = do skText <- getCiphertext <$> (secretBox symKey . unSized . reveal . B.unSecretKey) sk let pkText = (fromPlaintext . unSized . B.unPublicKey) pk return $ BoxKeypairStore (B64.encode skText) (B64.encode pkText) encryptSignKeypair :: Key -> S.Keypair -> IO SignKeypairStore encryptSignKeypair symKey (S.Keypair sk pk) = do skText <- getCiphertext <$> (secretBox symKey . reveal . S.unSecretKey) sk let pkText = (fromPlaintext . S.unPublicKey) pk return $ SignKeypairStore (B64.encode skText) (B64.encode pkText) decryptSignKeypair :: Key -> SignKeypairStore -> Either String S.Keypair decryptSignKeypair symKey (SignKeypairStore ske pk) = let eSK = case B64.decode ske of Right ske' -> case (openSecretBox symKey (SB.SecretBox ske') :: Maybe (Sized SU.SecretKeyBytes ScrubbedBytes)) of Just sk -> Right $ S.SecretKey $ Conceal sk Nothing -> Left "Failed to decrypt secret key" Left e -> Left e ePK = decodeSignPublicKey (SignKeypairStore ske pk) in S.Keypair <$> eSK <*> ePK decodeSignPublicKey :: SignKeypairStore -> Either String S.PublicKey decodeSignPublicKey (SignKeypairStore _ p) = case toPlaintext <$> B64.decode p of Right (Just p') -> Right $ S.PublicKey p' Right Nothing -> Left "Failed to decode public key" Left e -> Left e fromSigned :: S.Signed BS.ByteString -> CheckInProof fromSigned = mkCheckInProof . S.unSigned toSigned :: CheckInProof -> S.Signed BS.ByteString toSigned = S.Signed . unCheckInProof {- | Create a HashSalt This type is our internal representation of a hashed password with a salt for deriving a symmetric key. -} createHashSalt :: String -> IO HashSalt createHashSalt p = do s <- P.newSalt sp <- P.storePassword P.sensitivePolicy (fromString p) return $ toHashSalt sp s
dmp1ce/DMSS
src-lib/DMSS/Crypto.hs
unlicense
3,448
0
17
1,021
809
433
376
59
3
{-# LANGUAGE UnicodeSyntax, CPP #-} module Swift where import Data.List (intercalate) import Data.Maybe (fromMaybe) import Static import Language hiding (generate) import Util swift ∷ Bool → Typename → Typename → Language swift overload transport interface = Language generate wrapEnts (intDefs transport interface) where wrapEnts e = "\nimport Foundation\n" ⧺ e ⧺ entDefs ⧺ if overload then overloaded else [] generate ∷ Declaration → String generate (Record idr vars super) = struct idr vars super generate method = func name remoteName args rawRetType where (Method (Identifier name remoteName) args rawRetType) = method func ∷ Name → Name → [Variable] → Type → String func name rpc args t = s 4 ⧺ "public func " ⧺ name ⧺ "(" ⧺ list fromArg [] args ⧺ tf ⧺ "completion: " ⧺ ret ⧺ " -> Void)" ⧺ " -> T.CancellationToken" ⧺ " {\n" ⧺ body ⧺ "\n" ⧺ s 4 ⧺ "}\n" ⧺ s 4 ⧺ "public let " ⧺ name ⧺ ": String = \"" ⧺ name ⧺ "\"\n\n" where body = s 6 ⧺ "return transport.call(\"" ⧺ rpc ⧺ "\", arguments: " ⧺ passedArgs ⧺ ") { " ⧺ mapReply fromArg (Variable n t _) = n ⧺ ": " ⧺ fromType t ⧺ ", " noRet = (t ≡ TypeName "Void") ∨ (t ≡ TypeName "()") ret = if noRet then "Void" else fromType t ⧺ "?" tf = if noRet then [] else "tf: ((" ⧺ ret ⧺ ", [String : AnyObject]) -> " ⧺ ret ⧺ ") = idTf, " passedArgs = if null args then "[:]" else "[" ⧺ list serialize ", " args ⧺ "]" serialize (Variable n t _) = "\"" ⧺ n ⧺ "\": " ⧺ if primitive t then n else n ⧺ ".json" mapReply = if noRet then " _ in }" else "r in\n" ⧺ s 8 ⧺ "let v = tf(" ⧺ fromType t ⧺ "(json: r), r)\n" ⧺ s 8 ⧺ "completion(v)\n" ⧺ s 6 ⧺ "}" struct ∷ Identifier → [Variable] → Maybe Typename → String struct (Identifier name remote) vars super = "\npublic struct " ⧺ name ⧺ conforms ⧺ " {\n" ⧺ concat decls ⧺ "}\n" ⧺ equatable where decls = map varDecl vars' ⧺ [statics, optInit, initDecl, create, description] conforms | (Just s) ← super = jsonProtocols ⧺ ", " ⧺ s | otherwise = jsonProtocols where jsonProtocols = ": JSONEncodable, JSONDecodable" protocols = map trim (separateBy ',' (fromMaybe [] super)) equatable = if "Equatable" ∉ protocols then [] else "public func == (lhs: " ⧺ name ⧺ " , rhs: " ⧺ name ⧺ " ) -> Bool { " ⧺ "return lhs.json.description == rhs.json.description }\n" description = if "Printable" ∉ protocols then [] else s 4 ⧺ "public var description: String" ⧺ " { return Name + \": \" + json.description }\n" vars' = Variable "json" (TypeName "[String : AnyObject]") Nothing : vars create = s 4 ⧺ "static func create" ⧺ list curriedArg "" vars' ⧺ " -> " ⧺ name ⧺ " {\n" ⧺ s 8 ⧺ "return " ⧺ name ⧺ "(json" ⧺ (if null vars then "" else ", ") ⧺ list passArg ", " vars ⧺ ")\n" ⧺ s 4 ⧺ "}\n" passArg (Variable n _ _) = n ⧺ ": " ⧺ n curriedArg (Variable n t _) = "(" ⧺ n ⧺ ": " ⧺ fromType t ⧺ ")" optInit = s 4 ⧺ "public init?(json: [String : AnyObject]) {\n" ⧺ s 8 ⧺ "let (c, json) = (" ⧺ name ⧺ ".create(json), json)\n" ⧺ batchOps vars 0 ⧺ s 4 ⧺ "}\n" mapVar (Variable n (Optional t) dv) = "~~? \"" ⧺ n ⧺ "\"" -- TODO: use default value mapVar (Variable n _ _) = "~~ \"" ⧺ n ⧺ "\"" maxOpsInS = 3 -- NOTE: swiftc can't parse long op chains, batchOps should be list mapVar " " batchOps [] 0 = s 8 ⧺ "self = c; return\n" batchOps vars 0 = batchOps vars 1 ⧺ s 8 ⧺ "return nil\n" batchOps vars l = let ind = 6 + 2*l in if length vars > maxOpsInS then s ind ⧺ "if let (c" ⧺ n_ l ⧺ ", json) " ⧺ "= (c" ⧺ n_ (l-1) ⧺ ", json) " ⧺ " " ⧺ list mapVar " " (take maxOpsInS vars) ⧺ " {\n" ⧺ dshow (take maxOpsInS vars) ⧺ batchOps (drop maxOpsInS vars) (l+1) ⧺ s ind ⧺ "}\n" else s ind ⧺ "if let c" ⧺ n_ l ⧺ " = (c" ⧺ n_ (l-1) ⧺ ", json)" ⧺ " " ⧺ list mapVar " " vars ⧺ " { self = c" ⧺ n_ l ⧺ "; return }\n" initDecl = s 4 ⧺ "public init(_ json: [String : AnyObject]" ⧺ (if null vars then "" else ", ") ⧺ list arg ", " vars ⧺ ") {\n" ⧺ s 8 ⧺ list initVar "; " vars' ⧺ "; self.Name = \"" ⧺ name ⧺ "\"\n" ⧺ s 4 ⧺ "}\n" initVar (Variable n _ _) = "self." ⧺ n ⧺ " = " ⧺ n arg (Variable n t _) = n ⧺ ": " ⧺ fromType t statics = s 4 ⧺ "public let Name: String\n" ⧺ s 4 ⧺ "public static let Name = \"" ⧺ name ⧺ "\"\n" ⧺ s 4 ⧺ "public static let remoteName = \"" ⧺ remote ⧺ "\"\n" ⧺ list staticName "\n" vars' ⧺ "\n" staticName (Variable n _ _) = s 4 ⧺ "public static let " ⧺ n ⧺ " = \"" ⧺ n ⧺ "\"" varDecl (Variable n t dv) = s 4 ⧺ "public let " ⧺ n ⧺ ": " ⧺ fromType t ⧺ defVal ⧺ "\n" where defVal = "" -- maybe "" (" = " ⧺) dv dshow x = #ifdef DEBUG "/* " ⧺ show x ⧺ " */\n" #else [] #endif list ∷ (α → String) → String → [α] → String list gen separator = intercalate separator ∘ map gen fromType ∷ Type → String fromType (Array t) = "[" ⧺ fromType t ⧺ "]" fromType (Optional t) = fromType t ⧺ "?" fromType (Dictionary tk tv) = "[" ⧺ fromType tk ⧺ ": " ⧺ fromType tv ⧺ "]" fromType (TypeName typename) = typename
cfr/burningbar
src/Swift.hs
unlicense
5,983
0
25
1,863
1,906
955
951
86
9
{-# LANGUAGE PackageImports , MultiWayIf #-} module Main where import Data.List ( isPrefixOf , delete ) import Data.Char ( isUpper , toUpper , toLower ) import Text.PrettyPrint ( Doc , empty , render , char , text , nest , (<+>) , ($+$) ) import qualified Data.Map as M import Text.Printf (printf) import System.Environment (getArgs) -- import System.Directory (createDirectoryIfMissing) import "language-c" Language.C import "language-c" Language.C.System.GCC import "language-c" Language.C.Analysis main :: IO () main = do args <- getArgs if null args then putStrLn "Please provide a path to OSKAR source directory." else an (head args) >>= pr an :: FilePath -> IO GlobalDecls an path_to_oskar = do parse_result <- parseCFile (newGCC "gcc") Nothing ["-I" ++ path_to_oskar ++ "/settings/struct"] "oskar_Settings_fixed.h" case parse_result of Left parse_err -> error (show parse_err) Right ast -> let Right (gd, _) = runTrav_ (analyseAST ast) in return gd pr :: GlobalDecls -> IO () pr gd = do -- createDirectoryIfMissing True "generated" writeFile "../OskarCfg.hs" . render $ text "module OskarCfg where" $+$ (M.foldr (\tag doc -> prtag tag $+$ doc) empty (gTags gd)) upperCase :: String -> String upperCase (s:ss) = toUpper s : ss upperCase [] = [] fixName :: Pretty a => a -> String fixName sueref = let s = render $ pretty sueref in if | "oskar_" `isPrefixOf` s -> "Oskar" ++ drop 6 s | '$' `elem` s -> "ENUM_" ++ delete '$' s | True -> s -- Make prefix for record fields genPrefix :: String -> String genPrefix = (++ "_") . map toLower . filter isUpper -- We ignore _expr, because all relevant OSKAR enums -- are "good". pprEnumVal :: Enumerator -> Doc pprEnumVal (Enumerator ident _expr _etyp _info) = pretty ident showTn :: TypeName -> String showTn (TyIntegral TyInt) = "Int" showTn (TyFloating TyDouble) = "Double" showTn _ = error "Unrecognized type name" printfPtr :: String -> String -- printfPtr = printf "[%s]" -- Use custom list to overload 'show'. printfPtr = printf "OList %s" showPtr :: Type -> String showPtr (DirectType (TyIntegral TyChar) _ _) = "String" showPtr (DirectType tn _ _) = printfPtr $ showTn tn showPtr (PtrType pt _ _) = printfPtr $ showPtr pt showPtr td@(TypeDefType {}) = printfPtr $ showVarType td showPtr _ = error "Unrecognized * type" showVarType :: Type -> String showVarType (DirectType tn _ _) = showTn tn showVarType (PtrType pt _ _) = showPtr pt showVarType (TypeDefType (TypeDefRef ident _ _) _ _) = fixName ident showVarType (ArrayType (DirectType tn _ _) (ArraySize _ (CConst(CIntConst (CInteger 2 _ _) _))) _ _) = let ts = showTn tn in printf "(%s, %s)" ts ts showVarType x = error $ "Unrecognized type " ++ (render $ pretty x) prtag :: TagDef -> Doc prtag (EnumDef (EnumType sueref (e:erest) _attrs _info)) = text "data" <+> text (fixName sueref) <+> char '=' $+$ (nest 4 $ pprEnumVal e) $+$ (nest 2 $ foldr (\enum doc -> text "|" <+> pprEnumVal enum $+$ doc) empty erest) $+$ (nest 2 $ text "deriving Enum") -- We ignore _cty_kind because have only relevant structs here -- no unions. prtag (CompDef (CompType sueref _cty_kind (m:mrest) _attrs _info)) = let tname = fixName sueref tnamedoc = text tname prefix = genPrefix tname pprStrucVal (MemberDecl (VarDecl varname _attrs vartype) _expr _info) = (text . (prefix ++) . render . pretty $ varname) <+> text "::" <+> text (showVarType vartype) pprStrucVal _ = error "Unrecognised input." in text "data" <+> tnamedoc <+> char '=' <+> tnamedoc <+> char '{' $+$ (nest 4 $ pprStrucVal m) $+$ (nest 2 $ foldr (\var doc -> text "," <+> pprStrucVal var $+$ doc) empty mrest) $+$ (nest 2 $ char '}') prtag _ = error "Impossible happened. Check if only 'gTags' is used."
SKA-ScienceDataProcessor/RC
MS2/lib/OskarCfg/generator/OskarCfgGenerator.hs
apache-2.0
3,859
0
16
818
1,363
691
672
94
3
<?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="ru-RU"> <title>HTTPS Info Add-on</title> <maps> <homeID>httpsinfo</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>
secdec/zap-extensions
addOns/httpsInfo/src/main/javahelp/org/zaproxy/zap/extension/httpsinfo/resources/help_ru_RU/helpset_ru_RU.hs
apache-2.0
968
77
67
157
413
209
204
-1
-1
import Data.Char main = do contents <- getContents putStr $ map toUpper contents
EricYT/Haskell
src/chapter-9-1.hs
apache-2.0
90
0
8
22
30
14
16
4
1
-- Reverse Sequence main = do c <- getContents let i = (lines c)!!0 o = reverse i putStrLn o
a143753/AOJ
0006.hs
apache-2.0
106
0
12
33
47
22
25
5
1
module JDBC.Types.Ref ( getBaseTypeNameRef, getObjectRef, getObjectRef2, setObjectRef) where import Java import JDBC.Types foreign import java unsafe "@interface getBaseTypeName" getBaseTypeNameRef :: Java Ref JString foreign import java unsafe "@interface getObject" getObjectRef :: Java Ref Object foreign import java unsafe "@interface getObject" getObjectRef2_ :: Map JString (JClass b) -> Java Ref Object --Wrapper getObjectRef2 :: forall b. [(JString, JClass b)] -> Java Ref Object getObjectRef2 t = getObjectRef2_ (toJava t :: Map JString (JClass b)) --End Wrapper foreign import java unsafe "@interface setObject" setObjectRef :: Object -> Java Ref ()
Jyothsnasrinivas/eta-jdbc
src/JDBC/Types/Ref.hs
apache-2.0
682
12
10
110
191
103
88
-1
-1
{-# LANGUAGE OverloadedStrings #-} -- | CouchDB document attachments. -- -- /Note about attachment paths:/ Attachments may have embedded @\/@ -- characters that are sent unescaped to CouchDB. You can use this to -- provide a subtree of attachments under a document. A DocID must have -- any @\/@ escaped as @%2F@. So if you have document @a\/b\/c@ with an -- attachment @d\/e\/f.txt@, you would be able to access it at -- @http:\/\/couchdb\/db\/a%2fb%2fc\/d\/e\/f.txt@. -- -- @couchdb-conduit@ automaticaly normalizes attachment paths. module Database.CouchDB.Conduit.Attachment ( couchGetAttach, couchPutAttach, couchDeleteAttach ) where import Control.Exception.Lifted (throw) import Data.Maybe (fromMaybe) import Data.ByteString (ByteString) import Data.ByteString.Char8 (split) import qualified Data.Aeson as A import Data.Conduit (ResumableSource, ($$+-)) import qualified Data.Conduit.Attoparsec as CA import qualified Network.HTTP.Conduit as H import qualified Network.HTTP.Types as HT import Database.CouchDB.Conduit.Internal.Connection (MonadCouch (..), Path, Revision, mkPath) import Database.CouchDB.Conduit.Internal.Parser (extractRev) import Database.CouchDB.Conduit.LowLevel (couch, protect') -- | Get document attachment and @Content-Type@. couchGetAttach :: MonadCouch m => Path -- ^ Database -> Path -- ^ Document -> ByteString -- ^ Attachment path -> m (ResumableSource m ByteString, ByteString) couchGetAttach db doc att = do response <- couch HT.methodGet (attachPath db doc att) [] [] (H.RequestBodyBS "") protect' return ((H.responseBody response), fromMaybe "" . lookup "Content-Type" $ (H.responseHeaders response)) -- | Put or update document attachment couchPutAttach :: MonadCouch m => Path -- ^ Database -> Path -- ^ Document -> ByteString -- ^ Attachment path -> Revision -- ^ Document revision -> ByteString -- ^ Attacment @Content-Type@ -> H.RequestBody m -- ^ Attachment body -> m Revision couchPutAttach db doc att rev contentType body = do response <- couch HT.methodPut (attachPath db doc att) [(HT.hContentType, contentType)] [("rev", Just rev)] body protect' j <- (H.responseBody response) $$+- CA.sinkParser A.json either throw return $ extractRev j -- | Delete document attachment couchDeleteAttach :: MonadCouch m => Path -- ^ Database -> Path -- ^ Document -> ByteString -- ^ Attachment path -> Revision -- ^ Document revision -> m Revision couchDeleteAttach db doc att rev = do response <- couch HT.methodDelete (attachPath db doc att) [] [("rev", Just rev)] (H.RequestBodyBS "") protect' j <- (H.responseBody response) $$+- CA.sinkParser A.json either throw return $ extractRev j ------------------------------------------------------------------------------ -- Internal ------------------------------------------------------------------------------ -- | Make normalized attachment path attachPath :: Path -> Path -> ByteString -> Path attachPath db doc att = mkPath $ db : doc : attP where attP = split '/' att
akaspin/couchdb-conduit
src/Database/CouchDB/Conduit/Attachment.hs
bsd-2-clause
3,506
0
13
944
683
381
302
67
1
-- -- Copyright (c) 2013, Carl Joachim Svenn -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- 1. Redistributions of source code must retain the above copyright notice, this -- list of conditions and the following disclaimer. -- 2. Redistributions in binary form must reproduce the above copyright notice, -- this list of conditions and the following disclaimer in the documentation -- and/or other materials provided with the distribution. -- -- 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 Game.Data.Shape ( Shape (..), shapeOfSize, shapeWth, shapeHth, ) where import MyPrelude -- | Shape is normalized rectangles data Shape = Shape !Float !Float deriving Eq -- | Shape from rectangle shapeOfSize :: UInt -> UInt -> Shape shapeOfSize wth hth = let a = 1.0 / fI (max wth hth) in Shape (a * fI wth) (a * fI hth) shapeWth :: Shape -> Float shapeWth (Shape wth hth) = wth shapeHth :: Shape -> Float shapeHth (Shape wth hth) = hth
karamellpelle/MEnv
source/Game/Data/Shape.hs
bsd-2-clause
1,953
0
12
446
195
116
79
24
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QStyleOptionGraphicsItem.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:35 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Gui.QStyleOptionGraphicsItem ( QStyleOptionGraphicsItemStyleOptionType , QStyleOptionGraphicsItemStyleOptionVersion ) where import Foreign.C.Types import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CQStyleOptionGraphicsItemStyleOptionType a = CQStyleOptionGraphicsItemStyleOptionType a type QStyleOptionGraphicsItemStyleOptionType = QEnum(CQStyleOptionGraphicsItemStyleOptionType Int) ieQStyleOptionGraphicsItemStyleOptionType :: Int -> QStyleOptionGraphicsItemStyleOptionType ieQStyleOptionGraphicsItemStyleOptionType x = QEnum (CQStyleOptionGraphicsItemStyleOptionType x) instance QEnumC (CQStyleOptionGraphicsItemStyleOptionType Int) where qEnum_toInt (QEnum (CQStyleOptionGraphicsItemStyleOptionType x)) = x qEnum_fromInt x = QEnum (CQStyleOptionGraphicsItemStyleOptionType x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> QStyleOptionGraphicsItemStyleOptionType -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () instance QeType QStyleOptionGraphicsItemStyleOptionType where eType = ieQStyleOptionGraphicsItemStyleOptionType $ 17 data CQStyleOptionGraphicsItemStyleOptionVersion a = CQStyleOptionGraphicsItemStyleOptionVersion a type QStyleOptionGraphicsItemStyleOptionVersion = QEnum(CQStyleOptionGraphicsItemStyleOptionVersion Int) ieQStyleOptionGraphicsItemStyleOptionVersion :: Int -> QStyleOptionGraphicsItemStyleOptionVersion ieQStyleOptionGraphicsItemStyleOptionVersion x = QEnum (CQStyleOptionGraphicsItemStyleOptionVersion x) instance QEnumC (CQStyleOptionGraphicsItemStyleOptionVersion Int) where qEnum_toInt (QEnum (CQStyleOptionGraphicsItemStyleOptionVersion x)) = x qEnum_fromInt x = QEnum (CQStyleOptionGraphicsItemStyleOptionVersion x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> QStyleOptionGraphicsItemStyleOptionVersion -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () instance QeVersion QStyleOptionGraphicsItemStyleOptionVersion where eVersion = ieQStyleOptionGraphicsItemStyleOptionVersion $ 1
keera-studios/hsQt
Qtc/Enums/Gui/QStyleOptionGraphicsItem.hs
bsd-2-clause
4,829
0
18
921
1,080
532
548
90
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} module Network.HTTPMock.Interactions (getResponse) where import ClassyPrelude import Control.Lens import Debug.Trace (traceShow) import Data.NonEmpty ((!:)) import qualified Data.NonEmpty as NE import Network.HTTPMock.Types --TODO: record the request, update canned response and junk -- < edwardk> a Lens is defined as -- < edwardk> forall f. Functor f => (a -> f b) -> s -> f t -- < edwardk> findAndUpdateInteraction :: [FakedInteraction] -> f [FakedInteraction] -- < NemesisD> and what's the t in Lens s t a b? -- < Taneb> target -- < edwardk> where f = (,) (Maybe Response) -- < edwardk> interactions :: Functor f => ([Interaction] -> f [Interaction]) -> Mocker -> f Mocker -- < edwardk> when f = (,) (Maybe Response) that is -- < edwardk> interactions :: Functor f => ([Interaction] -> (Maybe Response, [Interaction])) -> Mocker -> (Maybe Response, Mocker) -- < edwardk> interactions :: ([Interaction] -> (Maybe Response, [Interaction])) -> Mocker -> (Maybe Response, Mocker) -- < edwardk> well, we have one of those lying around, so we pass it findAndUpdateInteraction and get the signature you want -- < edwardk> for interactions: s = t = Mocker, a = b = [Interaction] getResponse :: Request -> HTTPMocker -> (Maybe FakeResponse, HTTPMocker) getResponse req mocker = mocker' & responder . fakedInteractions %%~ findAndUpdateInteraction where findAndUpdateInteraction = matchResponse req mocker' = mocker & recordedRequests <>~ singleton req -- something like (uncurry (++) . (id *** f) . break predicate) -- At 0 might help with implementing f -- replace f with onHead update, onHead _ [] = [] ; onHead f (x:xs) = f x:xs -- (\p u -> over (taking 1 (traverse . filtered p)) u) even (+2) [1..5] matchResponse :: Request -> [FakedInteraction] -> (Maybe FakeResponse, [FakedInteraction]) matchResponse req interactions = findResponse $ break (match . fst) interactions where match rMatcher = rMatcher ^. matcher $ req findResponse (misses, []) = (Nothing, misses) findResponse (misses, ((m, cResp):rest)) = let (resp, cResp') = modifyOnMatch cResp in (Just resp, misses ++ ((m, cResp'):rest)) modifyOnMatch :: CannedResponse -> (FakeResponse, CannedResponse) modifyOnMatch unmodified@(ReturnsSequence (NE.Cons resp [])) = (resp, unmodified) modifyOnMatch (ReturnsSequence (NE.Cons curResp (nextResp:rest))) = (curResp, ReturnsSequence $ nextResp !: rest) modifyOnMatch cResp@(AlwaysReturns resp) = (resp, cResp)
MichaelXavier/HTTPMock
src/Network/HTTPMock/Interactions.hs
bsd-2-clause
2,592
0
13
451
432
250
182
-1
-1
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-} module DecisionProcedure.Opra8 ( module DecisionProcedure.Opra ) where -- standard modules -- local modules import Basics import Calculus.Opra8 import DecisionProcedure import DecisionProcedure.AlgebraicClosure --import DecisionProcedure.AlgebraicGeometric import DecisionProcedure.Opra instance HasBinAClosureGqr ARel Opra8 instance HasBinAClosureGqr GRel Opra8 instance HasBinAClosureSparq ARel Opra8 instance HasBinAClosureSparq GRel Opra8 --instance HasAReasoning ARel Opra8 --instance HasAReasoning GRel Opra8 instance HasDecisionProcedure (ARel Opra8) where procedures _ = [ algebraicClosureGQR , algebraicClosure -- , algebraicClosureSpS -- , algebraicReasoning ] ++ map (firstApply opramNetToOpraNetAtomic) (procedures (undefined :: ARel Opra)) instance HasDecisionProcedure (GRel Opra8) where procedures _ = [ -- algebraicClosure ]
spatial-reasoning/zeno
src/DecisionProcedure/Opra8.hs
bsd-2-clause
1,016
0
11
211
162
89
73
21
0
module Main where import StringMatching import System.Environment import System.Exit import Data.RString.RString main :: IO () main = do args <- getArgs case args of (i:j:fname:target:_) -> do input <- fromString <$> readFile fname let parfactor = (read i :: Integer ) let chunksize = (read j :: Integer) if parfactor <= 0 || chunksize <= 0 then putStrLn "Chunksize and Parallel Factor should be positive numbers" >> return () else runMatching parfactor chunksize input target _ -> putStrLn $ "Wrong input: You need to provide the chunksize," ++ "the input filename and the target string. For example:\n\n\n" ++ "verified-string-indexing 1000 1000 input.txt abcab\n\n"
nikivazou/verified_string_matching
src/Main.hs
bsd-3-clause
990
0
16
424
189
96
93
18
3
module System.Build.Access.Public where class Public r where setPublic :: r -> r unsetPublic :: r -> r
tonymorris/lastik
System/Build/Access/Public.hs
bsd-3-clause
128
0
7
42
35
20
15
8
0
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE FlexibleInstances #-} module Network.Libtorrent.FileStorage.FileSlice (FileSlice(..) , getFileIndex , getFileSliceOffset , getFileSliceSize ) where import Control.Monad.IO.Class (MonadIO, liftIO) import Foreign.C.Types (CInt) import Foreign.ForeignPtr ( ForeignPtr, withForeignPtr ) import qualified Language.C.Inline as C import qualified Language.C.Inline.Cpp as C import qualified Language.C.Inline.Unsafe as CU import Network.Libtorrent.Inline import Network.Libtorrent.Internal import Network.Libtorrent.Types C.context libtorrentCtx C.include "<libtorrent/file_storage.hpp>" C.using "namespace libtorrent" C.using "namespace std" newtype FileSlice = FileSlice { unFileSlice :: ForeignPtr (CType FileSlice)} instance Show FileSlice where show _ = "FileSlice" instance Inlinable FileSlice where type (CType FileSlice) = C'FileSlice instance FromPtr FileSlice where fromPtr = objFromPtr FileSlice $ \ptr -> [CU.exp| void { delete $(file_slice * ptr); } |] instance WithPtr FileSlice where withPtr (FileSlice fptr) = withForeignPtr fptr getFileIndex :: MonadIO m => FileSlice -> m CInt getFileIndex ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| int { $(file_slice * hoPtr)->file_index } |] getFileSliceOffset :: MonadIO m => FileSlice -> m C.CSize getFileSliceOffset ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| size_t { $(file_slice * hoPtr)->offset } |] getFileSliceSize :: MonadIO m => FileSlice -> m C.CSize getFileSliceSize ho = liftIO . withPtr ho $ \hoPtr -> [CU.exp| size_t { $(file_slice * hoPtr)->size } |]
eryx67/haskell-libtorrent
src/Network/Libtorrent/FileStorage/FileSlice.hs
bsd-3-clause
1,986
0
9
543
415
237
178
44
1
import System.Random import Control.Concurrent import System.ProgressBar import System.IO ( hSetBuffering, BufferMode(NoBuffering), stdout ) main = do hSetBuffering stdout NoBuffering c <- randomRIO ('a','z') putStrLn "\n+---------+---------+---------+---------+---------+---------+---------+---------+---------+" putStrLn "| Prénom | Ville | Pays | Végétal | Animal |Célébrité| Métier | Objet | Points |" putStrLn "+---------+---------+---------+---------+---------+---------+---------+---------+---------+\n" mapM (\s -> reboursLettre s) [0..5] putStrLn $ "\n---\nLetter : " ++ show c ++ "\n---" putStrLn "You have 2 minutes ..." mapM (\s -> reloadPB s) [0..120] putStrLn "End !" where reloadPB s = do progressBar (msg $ show s ++ "s") percentage 60 s 120 threadDelay 1000000 reboursLettre s = do progressBar (msg $ "I search letter") percentage 60 s 5 threadDelay 1000000
j4/baccalaureat
baccalaureat.hs
bsd-3-clause
955
0
13
183
240
114
126
21
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {- | Module : Data.Conduit.Network.Stream Copyright : Nils Schweinsberg License : BSD-style Maintainer : Nils Schweinsberg <[email protected]> Stability : experimental Easy to use network streaming with conduits. This library properly encodes conduit blocks over a network connection such that - each `await` corresponds to exactly one `yield` and - each `receive` corresponds to exactly one `send`. It also supports sending and receiving of custom data types via the `Sendable` and `Receivable` instances. A simple server/client example (using @-XOverloadedStrings@): > import Control.Monad.Trans > import qualified Data.ByteString as Strict > import qualified Data.ByteString.Lazy as Lazy > import Data.Conduit > import qualified Data.Conduit.List as CL > import Data.Conduit.Network > import Data.Conduit.Network.Stream > > client :: IO () > client = runResourceT $ runTCPClient (clientSettings ..) $ \appData -> do > > streamData <- toStreamData appData > > send streamData $ mapM_ yield (["ab", "cd", "ef"] :: [Strict.ByteString]) > send streamData $ mapM_ yield (["123", "456"] :: [Strict.ByteString]) > > closeStream streamData > > server :: IO () > server = runResourceT $ runTCPServer (serverSettings ..) $ \appData -> do > > streamData <- toStreamData appData > > bs <- receive streamData $ CL.consume > liftIO $ print (bs :: [Lazy.ByteString]) > > bs' <- receive streamData $ CL.consume > liftIO $ print (bs' :: [Lazy.ByteString]) > > closeStream streamData -} module Data.Conduit.Network.Stream ( -- * Network streams StreamData, toStreamData, closeStream -- ** Sending , send , Sendable(..), EncodedBS -- ** Receiving , receive , Receivable(..) -- ** Bi-directional conversations , streamSink , withElementSink ) where import Control.Concurrent.MVar import Control.Monad.Reader import Control.Monad.Trans.Resource import Data.ByteString (ByteString) import Data.Conduit hiding (($$)) import Data.Conduit.Network import qualified Data.Conduit as C import qualified Data.Conduit.List as CL import qualified Data.Conduit.Internal as CI import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import Data.Conduit.Network.Stream.Exceptions import Data.Conduit.Network.Stream.Header import Data.Conduit.Network.Stream.Internal sinkCondStart, sinkCondEnd :: Monad m => StreamData m -> Sink a m () sinkCondStart sd = yield (BS.pack condStart) =$ streamDataSink sd sinkCondEnd sd = yield (BS.pack condEnd) =$ streamDataSink sd sinkCondElems :: (Monad m, Sendable m a) => StreamData m -> Sink a m () sinkCondElems sd = encode =$ CL.map (\(EncodedBS bs) -> bs) =$ streamDataSink sd toStreamData :: MonadIO n => AppData m -> n (StreamData m) toStreamData ad = do src <- liftIO $ newMVar (NewSource ad) let sd = StreamData src (appSink ad) --register $ closeStream sd return sd -- | Close current stream. In order to guarantee process resource finalization, -- you /must/ use this operator after using `receive`. closeStream :: MonadResource m => StreamData m -> m () closeStream sd = do src <- liftIO $ takeMVar (streamDataSource sd) case src of OpenSource s -> s $$+- return () _ -> return () -------------------------------------------------------------------------------- -- Receiving data -- | `decode` is used after receiving the individual conduit block elements. -- It is therefore not necessary to reuse other `decode` instances (in -- contrast to `Sendable` instance definitions). class Receivable a m where decode :: Conduit BL.ByteString m a -- | Instance for strict bytestrings. Note that this uses `BL.toStrict` for the -- conversion from lazy bytestrings, which is rather expensive. Try to use lazy -- bytestrings if possible. instance Monad m => Receivable ByteString m where decode = CL.map BL.toStrict -- | For lazy bytestrings, `decode` is the identity conduit. instance Monad m => Receivable BL.ByteString m where decode = CI.ConduitM $ CI.idP -- | Receive the next conduit block. Might fail with the `ClosedStream` -- exception if used on a stream that has been closed by `closeStream`. receive :: (MonadResource m, Receivable a m) => StreamData m -> Sink a m b -> m b receive sd sink = do -- get current source (and block MVar, just in case) src <- liftIO $ takeMVar (streamDataSource sd) (next,a) <- case src of NewSource ad -> appSource ad $$+ decodeCondBlock =$= decode =$ sink OpenSource rsrc -> rsrc $$++ decodeCondBlock =$= decode =$ sink ClosedSource -> monadThrow $ ClosedStream liftIO $ putMVar (streamDataSource sd) (OpenSource next) return a -------------------------------------------------------------------------------- -- Sending data -- | Newtype for properly encoded bytestrings. newtype EncodedBS = EncodedBS ByteString -- | To define your own `Sendable` instances, reuse the instances for strict and -- lazy bytestrings, for example for "Data.Text": -- -- > instance (Monad m, Sendable m Data.ByteString.ByteString) => Sendable m Text where -- > encode = Data.Conduit.List.map encodeUtf8 =$= encode class Sendable m a where -- | `encode` is called before sending out conduit block elements. Each -- element has to be encoded either as strict `ByteString` or as lazy `BL.ByteString` -- with a known length. encode :: Conduit a m EncodedBS -- | Instance for strict bytestrings, using a specialized version of `encode`. instance Monad m => Sendable m ByteString where encode = encodeBS =$= CL.map EncodedBS -- | Instance for lazy bytestrings with a known length, using a specialized -- version of `encode`. instance Monad m => Sendable m (Int, BL.ByteString) where encode = encodeLazyBS =$= CL.map EncodedBS -- | Instance for lazy bytestrings which calculates the length of the -- `BL.ByteString` before calling the @(Int, Data.ByteString.Lazy.ByteString)@ -- instance of `Sendable`. instance Monad m => Sendable m BL.ByteString where encode = CL.map (\bs -> (len bs, bs)) =$= encode where len :: BL.ByteString -> Int len bs = fromIntegral $ BL.length bs -- | Send one conduit block. send :: (Monad m, Sendable m a) => StreamData m -> Source m a -> m () send sd src = src C.$$ streamSink sd -------------------------------------------------------------------------------- -- Bi-directional conversations -- | For bi-directional conversations you sometimes need the sink of the current -- stream, since you can't use `send` within another `receive`. -- -- A simple example: -- -- > receive streamData $ -- > myConduit =$ streamSink streamData -- -- Note, that each `streamSink` marks its own conduit block. If you want to sink -- single block elements, use `withElementSink` instead. streamSink :: (Monad m, Sendable m a) => StreamData m -> Sink a m () streamSink sd = do sinkCondStart sd sinkCondElems sd sinkCondEnd sd -- | Sink single elements inside the same conduit block. Example: -- -- > receive streamData $ withElementSink $ \sinkElem -> do -- > yield singleElem =$ sinkElem -- > mapM_ yield moreElems =$ sinkElem withElementSink :: (Monad m, Sendable m a) => StreamData m -> (Sink a m () -> Sink b m c) -> Sink b m c withElementSink sd run = do sinkCondStart sd res <- run (sinkCondElems sd) sinkCondEnd sd return res
mcmaniac/conduit-network-stream
src/Data/Conduit/Network/Stream.hs
bsd-3-clause
7,561
0
14
1,483
1,223
652
571
94
3
{-# LANGUAGE ScopedTypeVariables #-} module Astro.Time.AtSpec where import Data.List (sort) import Test.Hspec import Test.QuickCheck (property, (==>)) import Numeric.Units.Dimensional.Prelude import qualified Prelude import Astro.Time import Astro.Time.At import TestInstances main = hspec spec spec = do spec_allIn spec_zipAtWith -- Utility -- | Checks that all elements in the first list are contained in the -- second list. allIn :: (Eq a, Ord a) => [a] -> [a] -> Bool allIn xs ys = allIn' (sort xs) (sort ys) -- | Checks that all elements in the first list are contained in the -- second list. The lists must be sorted. allIn' :: Eq a => [a] -> [a] -> Bool allIn' [] _ = True allIn' _ [] = False allIn' (a:as) (b:bs) = if a == b then allIn' as bs else allIn' (a:as) bs spec_allIn = describe "allIn" $ do it "is True when it should be" $ allIn [1,2,3] [1..100] && allIn [2,4] [1..100] && allIn [2,4] [1..4] it "is False when it should be" $ not (allIn [1,2,3] [2..100]) && not (allIn [3,4] [1..3]) it "works with a single element" $ property $ \(x::Double) xs -> allIn [x] xs == elem x xs -- Actual tests. spec_zipAtWith = describe "zipAtWith" $ do it "drops values when time doesn't match" $ property $ \(xs::[At UT1 Double Int]) ys -> let ts = map epoch $ zipAtWith (Prelude.+) (sort xs) (sort ys) in ts `allIn` map epoch xs && ts `allIn` map epoch ys it "works for some handrolled cases" $ let ats = map (At 0 . mjd') :: [Double] -> [At UT1 Double Int] in zipAtWith const (ats [1..10]) (ats [5..20]) == ats [5..10] && zipAtWith const (ats [5..20]) (ats [1..10]) == ats [5..10] && zipAtWith const (ats [5..20]) (ats [1..10]) == ats [5..10] && zipAtWith const (ats [4]) (ats [1..10]) == ats [4] && zipAtWith const (ats [1,3..10]) (ats [2,4..10]) == [] && zipAtWith const (ats [1..11]) (ats [2,4..28]) == ats [2,4..10] -- Beware of broken Enum for Double!
bjornbm/astro
test/Astro/Time/AtSpec.hs
bsd-3-clause
2,069
0
25
542
879
465
414
44
2
{-# LANGUAGE OverloadedStrings, QuasiQuotes, ViewPatterns #-} module Grin.PrimOpsPrelude where import Grin.Grin import Grin.TH {- These predefined primitive operations are optional. This is a utility module for front-ends and the grin CLI use `grin --no-prelude` to exclude these predefined primitive operations -} primPrelude :: Program primPrelude = [progConst| ffi effectful _prim_int_print :: T_Int64 -> T_Unit _prim_usleep :: T_Int64 -> T_Unit _prim_string_print :: T_String -> T_Unit _prim_read_string :: T_String _prim_error :: T_String -> T_Unit _prim_ffi_file_eof :: T_Int64 -> T_Int64 -- Everything that handles Strings are FFI implemented now. ffi pure -- String _prim_string_concat :: T_String -> T_String -> T_String _prim_string_reverse :: T_String -> T_String _prim_string_lt :: T_String -> T_String -> T_Int64 _prim_string_eq :: T_String -> T_String -> T_Int64 _prim_string_head :: T_String -> T_Int64 -- TODO: Change to Char _prim_string_tail :: T_String -> T_String _prim_string_cons :: T_Int64 -> T_String -> T_String _prim_string_len :: T_String -> T_Int64 ffi pure -- Conversion _prim_int_str :: T_Int64 -> T_String _prim_str_int :: T_String -> T_Int64 _prim_int_float :: T_Int64 -> T_Float _prim_float_string :: T_Float -> T_String _prim_char_int :: T_Char -> T_Int64 primop pure -- Int _prim_int_shr :: T_Int64 -> T_Int64 -- TODO: Remove? _prim_int_add :: T_Int64 -> T_Int64 -> T_Int64 _prim_int_sub :: T_Int64 -> T_Int64 -> T_Int64 _prim_int_mul :: T_Int64 -> T_Int64 -> T_Int64 _prim_int_div :: T_Int64 -> T_Int64 -> T_Int64 _prim_int_ashr :: T_Int64 -> T_Int64 -> T_Int64 _prim_int_eq :: T_Int64 -> T_Int64 -> T_Bool _prim_int_ne :: T_Int64 -> T_Int64 -> T_Bool _prim_int_gt :: T_Int64 -> T_Int64 -> T_Bool _prim_int_ge :: T_Int64 -> T_Int64 -> T_Bool _prim_int_lt :: T_Int64 -> T_Int64 -> T_Bool _prim_int_le :: T_Int64 -> T_Int64 -> T_Bool -- Word _prim_word_add :: T_Word64 -> T_Word64 -> T_Word64 _prim_word_sub :: T_Word64 -> T_Word64 -> T_Word64 _prim_word_mul :: T_Word64 -> T_Word64 -> T_Word64 _prim_word_div :: T_Word64 -> T_Word64 -> T_Word64 _prim_word_eq :: T_Word64 -> T_Word64 -> T_Bool _prim_word_ne :: T_Word64 -> T_Word64 -> T_Bool _prim_word_gt :: T_Word64 -> T_Word64 -> T_Bool _prim_word_ge :: T_Word64 -> T_Word64 -> T_Bool _prim_word_lt :: T_Word64 -> T_Word64 -> T_Bool _prim_word_le :: T_Word64 -> T_Word64 -> T_Bool -- Float _prim_float_add :: T_Float -> T_Float -> T_Float _prim_float_sub :: T_Float -> T_Float -> T_Float _prim_float_mul :: T_Float -> T_Float -> T_Float _prim_float_div :: T_Float -> T_Float -> T_Float _prim_float_eq :: T_Float -> T_Float -> T_Bool _prim_float_ne :: T_Float -> T_Float -> T_Bool _prim_float_gt :: T_Float -> T_Float -> T_Bool _prim_float_ge :: T_Float -> T_Float -> T_Bool _prim_float_lt :: T_Float -> T_Float -> T_Bool _prim_float_le :: T_Float -> T_Float -> T_Bool -- Bool _prim_bool_eq :: T_Bool -> T_Bool -> T_Bool _prim_bool_ne :: T_Bool -> T_Bool -> T_Bool |] withPrimPrelude :: Program -> Program withPrimPrelude p = concatPrograms [primPrelude, p]
andorp/grin
grin/src/Grin/PrimOpsPrelude.hs
bsd-3-clause
3,429
0
6
818
58
36
22
8
1
module Week6 where fib :: Integer -> Integer fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib(n-2) fibs1 :: [Integer] fibs1 = map fib [0,1..] {- take 5 element of fibsl fibsl = fib 4 + fib 3 = fib 3 + fib 2 + fib 2 + fib 1 = fib 2 + fib 1 + fib 1 + fib 0 + fib 1 + fib 0 + fib1 -} data Stream a = Cons a (Stream a) instance Show a => Show (Stream a )where show = show . take 20 .streamToList streamToList :: Stream a -> [a] streamToList (Cons y c) = y : streamToList c streamRepeat :: a -> Stream a streamRepeat n = Cons n (streamRepeat n) streamMap :: (a -> b) -> Stream a -> Stream b streamMap f (Cons x ys) = Cons (f x) (streamMap f ys) streamFromSeed :: (a -> a) -> a -> Stream a streamFromSeed f y = Cons y (streamFromSeed f (f y)) nats :: Stream Integer nats =streamFromSeed (+1) 0
zach007/cis194
src/Week6.hs
bsd-3-clause
824
1
9
220
347
178
169
20
1
{-# LANGUAGE OverloadedStrings #-} module Stashh.Repos.Model where import Stashh.Table import Stashh.Model.Type import qualified Stashh.AnsiColor as C import Data.Maybe import Control.Applicative import qualified Data.Vector as V import Data.Aeson ---------------------------------------------- -- Repos data ReposResult = ReposResult { start :: Int , size :: Int , limit :: Int , filter :: Maybe String , isLastPage :: Bool , values :: V.Vector Repo } deriving (Show, Eq) data Repo = Repo { repoId :: Int , slug :: String , repoName :: String , scmId :: String , state :: String , statusMessage :: String , forkable :: Maybe Bool {- , project :: Project -} , cloneUrl :: String , link :: Link } deriving (Show, Eq) instance FromJSON ReposResult where parseJSON (Object v) = ReposResult <$> v .: "start" <*> v .: "size" <*> v .: "limit" <*> v .:? "filter" <*> v .: "isLastPage" <*> v .:? "values" .!= V.empty parseJSON _ = fail "ReposResult" instance FromJSON Repo where parseJSON (Object v) = Repo <$> v .: "id" <*> v .: "slug" <*> v .: "name" <*> v .: "scmId" <*> v .: "state" <*> v .: "statusMessage" <*> v .:? "forkable" <*> v .: "cloneUrl" <*> v .: "link" parseJSON _ = fail "Repo" instance TableDef Repo where columnsDef = [ ColDesc center "Id" right C.cyan (show . repoId) , ColDesc center "Slug" left C.green slug , ColDesc center "Name" left id repoName , ColDesc center "ScmId" left id scmId , ColDesc center "StatusMessage" left C.blue statusMessage , ColDesc center "Forkable" left id (showMaybe forkable) , ColDesc left "CloneUrl" left id cloneUrl , ColDesc left "Link" left id (linkUrl . link) ] instance PagingDef ReposResult where paging_start r = start r paging_size r = size r paging_limit r = limit r paging_last r = isLastPage r
yuroyoro/stashh
src/Stashh/Repos/Model.hs
bsd-3-clause
2,460
0
23
1,008
589
319
270
64
0
{-# LANGUAGE TupleSections #-} module Handler.Resource where import Import import Model.List import Model.Resource import Model.User (thisUserHasAuthorityOverDB) import View.Browse import View.Resource import qualified Data.Set as S getResourceR :: ResourceId -> Handler Html getResourceR res_id = do (res@Resource{..}, authors, tags, colls) <- runDB $ (,,,) <$> get404 res_id <*> (map authorName <$> fetchResourceAuthorsDB res_id) <*> (map tagName <$> fetchResourceTagsDB res_id) <*> (map collectionName <$> fetchResourceCollectionsDB res_id) let info_widget = resourceInfoWidget (Entity res_id res) edit_widget = editResourceFormWidget res_id (Just resourceTitle) (Just authors) (Just resourcePublished) (Just resourceType) (Just tags) (Just colls) defaultLayout $ do setTitle . toHtml $ "dohaskell | " <> resourceTitle $(widgetFile "resource") getEditResourceR :: ResourceId -> Handler Html getEditResourceR res_id = do (Resource{..}, authors, tags, colls) <- runDB $ (,,,) <$> get404 res_id <*> (map authorName <$> fetchResourceAuthorsDB res_id) <*> (map tagName <$> fetchResourceTagsDB res_id) <*> (map collectionName <$> fetchResourceCollectionsDB res_id) defaultLayout $ editResourceFormWidget res_id (Just resourceTitle) (Just authors) (Just resourcePublished) (Just resourceType) (Just tags) (Just colls) postEditResourceR :: ResourceId -> Handler Html postEditResourceR res_id = do res <- runDB (get404 res_id) ((result, _), _) <- runFormPost (editResourceForm Nothing Nothing Nothing Nothing Nothing Nothing) case result of FormSuccess (new_title, new_authors, new_published, new_type, new_tags, new_colls) -> do ok <- thisUserHasAuthorityOverDB (resourceUserId res) if ok then do runDB $ updateResourceDB res_id new_title (map Author $ new_authors) new_published new_type (map Tag $ new_tags) (map Collection $ new_colls) setMessage "Resource updated." redirect $ ResourceR res_id -- An authenticated, unprivileged user is the same as an -- unauthenticated user - their edits result in pending -- edits. else doPendingEdit res where doPendingEdit :: Resource -> Handler Html doPendingEdit Resource{..} = do pendingEditField resourceTitle new_title EditTitle pendingEditField resourcePublished new_published EditPublished pendingEditField resourceType new_type EditType (old_authors, old_tags, old_colls) <- runDB $ (,,) <$> (map authorName <$> fetchResourceAuthorsDB res_id) <*> (map tagName <$> fetchResourceTagsDB res_id) <*> (map collectionName <$> fetchResourceCollectionsDB res_id) -- Authors are a little different than tags/collections, because -- order matters. So, -- we don't duplicate the fine-grained tag -- edits (individual add/remove), but rather, if *anything* -- about the authors changed, just make an edit containing all -- of them. when (old_authors /= new_authors) $ void $ runDB (insertUnique (EditAuthors res_id new_authors)) pendingEditRelation (S.fromList new_tags) (S.fromList old_tags) EditAddTag EditRemoveTag pendingEditRelation (S.fromList new_colls) (S.fromList old_colls) EditAddCollection EditRemoveCollection setMessage "Your edit has been submitted for approval. Thanks!" redirect $ ResourceR res_id where pendingEditField :: (Eq a, PersistEntity val, PersistEntityBackend val ~ SqlBackend) => a -- Old field value -> a -- New field value -> (ResourceId -> a -> val) -- PersistEntity constructor -> Handler () pendingEditField old_value new_value entityConstructor = when (old_value /= new_value) $ void . runDB . insertUnique $ entityConstructor res_id new_value pendingEditRelation :: (PersistEntity a, PersistEntityBackend a ~ SqlBackend, PersistEntity b, PersistEntityBackend b ~ SqlBackend, Ord field) => Set field -> Set field -> (ResourceId -> field -> a) -> (ResourceId -> field -> b) -> Handler () pendingEditRelation new_fields old_fields edit_add edit_remove = do pendingEditRelation' new_fields old_fields edit_add -- find any NEW not in OLD: pending ADD. pendingEditRelation' old_fields new_fields edit_remove -- find any OLD not in NEW: pending REMOVE. -- If we find any needles NOT in the haystack, insert the needle into the database -- with the supplied constructor. pendingEditRelation' :: (Ord field, PersistEntity val, PersistEntityBackend val ~ SqlBackend) => Set field -> Set field -> (ResourceId -> field -> val) -> Handler () pendingEditRelation' needles haystack edit_constructor = forM_ needles $ \needle -> unless (S.member needle haystack) $ void . runDB . insertUnique $ edit_constructor res_id needle FormFailure errs -> do setMessage . toHtml $ "Form error: " <> intercalate ", " errs redirect $ ResourceR res_id FormMissing -> redirect $ ResourceR res_id getResourceListR :: Text -> Handler Html getResourceListR list_name = requireAuthId >>= runDB . flip fetchListResourcesDB list_name >>= defaultLayout . resourceListWidget postResourceListAddR, postResourceListDelR :: Text -> ResourceId -> Handler Html postResourceListAddR = postResourceListAddDel addListItemDB postResourceListDelR = postResourceListAddDel deleteListItemDB postResourceListAddDel :: (UserId -> Text -> ResourceId -> YesodDB App ()) -> Text -> ResourceId -> Handler Html postResourceListAddDel action list_name res_id = do user_id <- requireAuthId runDB (action user_id list_name res_id) return "ok"
mitchellwrosen/dohaskell
src/Handler/Resource.hs
bsd-3-clause
7,372
0
23
2,795
1,473
731
742
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} import qualified Data.ByteString.Lazy.Char8 as L8 import Network.HTTP.Types (status200) import Network.Wai (pathInfo, rawPathInfo, requestMethod, responseLBS) import Yesod import Data.IORef import MyRest.Api data App = App (IORef [Int]) mkYesod "App" [parseRoutes| /only-get OnlyGetR GET /any-method AnyMethodR /has-param/#Int HasParamR GET /my-subsite MySubsiteR WaiSubsite getMySubsite /rest RestR WaiSubsite getSilkRestApp |] instance Yesod App getOnlyGetR :: Handler Html getOnlyGetR = defaultLayout [whamlet| <p>Accessed via GET method <form method=post action=@{AnyMethodR}> <button>POST to /any-method |] handleAnyMethodR :: Handler Html handleAnyMethodR = do req <- waiRequest defaultLayout [whamlet| <p>In any-method, method == #{show $ requestMethod req} |] getHasParamR :: Int -> Handler String getHasParamR i = return $ show i getMySubsite :: App -> WaiSubsite getMySubsite _ = WaiSubsite app where app req sendResponse = sendResponse $ responseLBS status200 [("Content-Type", "text/plain")] $ L8.pack $ concat [ "pathInfo == " , show $ pathInfo req , ", rawPathInfo == " , show $ rawPathInfo req ] getSilkRestApp :: App -> WaiSubsite getSilkRestApp (App y) = WaiSubsite $ silkApiExample y main :: IO () main = do sras <- newIORef [0] warp 3000 (App sras)
tolysz/Diag
Main.hs
bsd-3-clause
1,754
0
12
524
334
182
152
43
1
module Jade.Decode.Coord where import Jade.Decode.Types transformX rot x y = case fromEnum rot of 0 -> x 1 -> -y 2 -> -x 3 -> y 4 -> -x 5 -> -y 6 -> x 7 -> y transformY rot x y = case fromEnum rot of 1 -> x 7 -> x 2 -> -y 6 -> -y 3 -> -x 5 -> -x 0 -> y 4 -> y c3ToPoint :: Coord3 -> (Integer, Integer) c3ToPoint (Coord3 x y r) = (transformX r x y, transformY r x y) -- https://github.com/6004x/jade/blob/ccb840c91a4248aab1764b1f9d27d832167b32a5/model.js -- rotation matrix found at the above link, from the JADE project. composeRot :: Rot -> Rot -> Rot composeRot r1 r2 = toEnum $ [ 0, 1, 2, 3, 4, 5, 6, 7 -- NORTH (identity) , 1, 2, 3, 0, 7, 4, 5, 6 -- EAST (rot270) rotcw , 2, 3, 0, 1, 6, 7, 4, 5 -- SOUTH (rot180) , 3, 0, 1, 2, 5, 6, 7, 4 -- WEST (rot90) rotccw , 4, 5, 6, 7, 0, 1, 2, 3 -- RNORTH (negx) fliph , 5, 6, 7, 4, 3, 0, 1, 2 -- REAST (int-neg) , 6, 7, 4, 5, 2, 3, 0, 1 -- RSOUTH (negy) flipy , 7, 4, 5, 6, 1, 2, 3, 0 -- RWEST (int-pos) ] !! (fromEnum r1 * 8 + fromEnum r2) coord5ends p@(Coord5 x y rot dx dy) = let n1 = (x, y) Coord3 x' y' _ = rotate (Coord3 dx dy Rot0) rot 0 0 n2 = (x + x', y + y') in (n1, n2) xMinC5 c5 = let ((x1, _), (x2, _)) = coord5ends c5 in min x1 x2 xMaxC5 c5 = let ((x1, _), (x2, _)) = coord5ends c5 in max x1 x2 yMinC5 c5 = let ((_, y1), (_, y2)) = coord5ends c5 in min y1 y2 yMaxC5 c5 = let ((_, y1), (_, y2)) = coord5ends c5 in max y1 y2 c3x (Coord3 x _ _) = x --fst . c3ToPoint c3y (Coord3 _ y _) = y -- = snd . c3ToPoint rotate :: LocRot a => a -> Rot -> Integer -> Integer -> Coord3 locs :: Coord5 -> [Coord3] locs c5 = let ((x1, y1), (x2, y2)) = coord5ends c5 in [ Coord3 x1 y1 Rot0 , Coord3 x2 y2 Rot0] points :: Coord5 -> [Point] points c5 = let ((x1, y1), (x2, y2)) = coord5ends c5 in [ Point x1 y1 , Point x2 y2 ] rotate item rotation cx cy = let Coord3 x y r = locrot item rx = x - cx ry = y - cy newX = cx + transformX rotation rx ry newY = cy + transformY rotation rx ry newR = composeRot r rotation in Coord3 newX newY newR
drhodes/jade2hdl
jade-decode/src/Jade/Decode/Coord.hs
bsd-3-clause
2,239
0
11
722
1,060
581
479
67
8
{-# LANGUAGE CPP #-} {-# LANGUAGE GADTSyntax, ExistentialQuantification, RankNTypes, ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} module Notate.Interpret where import Control.Concurrent import Control.DeepSeq import Control.Monad import Control.Monad.Catch import Control.Exception (AsyncException(UserInterrupt), evaluate) import Data.Typeable import Text.Read (readMaybe) import System.Environment as System -- Haskell interpreter import Language.Haskell.Interpreter hiding (eval, setImports) import qualified Language.Haskell.Interpreter as Hint -- web import Data.Aeson (toJSON, (.=)) import qualified Data.Aeson as JSON import qualified Data.ByteString.Char8 as B import Data.Text (Text) import Data.String (fromString) import Web.Scotty -- Interpreter import Hyper.Internal say = putStrLn defaultPort :: Int defaultPort = 8024 main :: IO () main = do env <- System.getEnvironment let port = maybe defaultPort id $ readMaybe =<< Prelude.lookup "PORT" env (hint, interpreterLoop) <- newInterpreter forkIO $ scotty port (jsonAPI hint) interpreterLoop -- See NOTE [MainThread] {- NOTE [MainThread] We fork the web server and run GHC in the main thread. This is because GHC registers handlers for signals like SIGTERM, but for some reason, these handlers only work correctly if GHC also has the main thread. -} jsonAPI :: Hint -> ScottyM () jsonAPI hint = do post "/cancel" $ do liftIO $ cancel hint json $ JSON.object [ "status" .= t "ok" ] post "/setImports" $ json . result =<< liftIO . setImports hint =<< param "query" post "/loadFiles" $ json . result =<< liftIO . loadFiles hint =<< param "query" post "/eval" $ do json . result =<< liftIO . eval hint =<< param "query" t s = fromString s :: Text result :: JSON.ToJSON a => Result a -> JSON.Value result (Left e) = JSON.object [ "status" .= t "error", "errors" .= err e] where err e = toJSON $ case e of UnknownError s -> [t s] WontCompile xs -> map (t . errMsg) xs NotAllowed s -> [t s] GhcException s -> [t s] result (Right x) = JSON.object [ "status" .= t "ok", "value" .= toJSON x ] instance JSON.ToJSON Graphic where toJSON g = JSON.object [ "type" .= t "html", "value" .= gHtml g ] setImports :: Hint -> [String] -> IO (Result ()) loadFiles :: Hint -> [FilePath] -> IO (Result ()) eval :: Hint -> String -> IO (Result Graphic) -- NOTE: We implicitely load the Prelude and Hyper modules setImports hint = run hint . Hint.setImports . (++ ["Prelude", "Hyper"]) . filter (not . null) loadFiles hint = run hint . Hint.loadModules . filter (not . null) eval hint expr = run hint $ do -- NOTE: We wrap results into an implicit call to Hyper.display m <- Hint.interpret ("Hyper.displayIO " ++ Hint.parens expr) (as :: IO Graphic) liftIO $ do g <- m evaluate (force g) -- See NOTE [EvaluateToNF] {- NOTE [EvaluateToNF] We evaluate the result in the interpreter thread to full normal form, because it may be that this evaluation does not terminate, in which case the user is likely to trigger a `UserInterrupt` asynchronous exception. But this exception is only delivered to and handled by the interpreter thread. Otherwise, the web server would be stuck trying to evaluate the result in order to serialize it, with no way for the user to interrupt this. -} type Result a = Either InterpreterError a toInterpreterError :: SomeException -> InterpreterError toInterpreterError e = case fromException e of Just e -> e Nothing -> UnknownError (displayException e) #if MIN_VERSION_base(4,8,0) #else displayException :: SomeException -> String displayException = show #endif -- | Haskell Interpreter. data Hint = Hint { run :: forall a. Interpreter a -> IO (Result a) , cancel :: IO () } data Action where Action :: Interpreter a -> MVar (Result a) -> Action debug s = liftIO $ putStrLn s -- | Create and initialize a Haskell interpreter. newInterpreter :: IO (Hint, IO ()) -- ^ (send commands, interpreter loop) newInterpreter = do vin <- newEmptyMVar evalThreadId <- newEmptyMVar -- ThreadID of the thread responsible for evaluation let handler :: Interpreter () handler = do debug "Waiting for Haskell expression" Action ma vout <- liftIO $ takeMVar vin let right = liftIO . putMVar vout . Right =<< ma let left = liftIO . putMVar vout . Left . toInterpreterError debug "Got Haskell expression, evaluating" right `catch` left debug "Wrote result" run :: Interpreter a -> IO (Result a) run ma = do vout <- newEmptyMVar putMVar vin (Action ma vout) a <- takeMVar vout case a of Right _ -> return () Left e -> debug $ show e return a cancel :: IO () cancel = do t <- readMVar evalThreadId throwTo t UserInterrupt -- NOTE: `throwTo` may block if the thread `t` has masked asynchronous execptions. debug "UserInterrupt, evaluation cancelled" interpreterLoop :: IO () interpreterLoop = do putMVar evalThreadId =<< myThreadId -- NOTE: The failure branch of `catch` will `mask` asynchronous exceptions. let go = forever $ handler `catch` (\UserInterrupt -> return ()) void $ runInterpreter go return (Hint run cancel, interpreterLoop)
ejconlon/notate
src/Notate/Interpret.hs
bsd-3-clause
5,743
0
19
1,560
1,440
724
716
-1
-1
module Type ( typeEqual , typeOf , typeOfPattern , simplifyType ) where import Base import Context import Data.List (find) import qualified Data.HashSet as S typeMap :: (Int -> TermType) -> TermType -> TermType typeMap onvar ty = go ty where go TypeBool = TypeBool go TypeNat = TypeNat go (TypeList ty) = TypeList (go ty) go TypeUnit = TypeUnit go (TypeRecord fields) = TypeRecord (map (\(f, ty) -> (f, go ty)) fields) go (TypeArrow ty1 ty2) = TypeArrow (go ty1) (go ty2) go (TypeVar var) = onvar var typeShift :: TermType -> Int -> TermType typeShift ty delta = typeMap (\var -> TypeVar (var + delta)) ty getBindingType :: Context -> Int -> TermType getBindingType ctx index = typeShift ty (index + 1) -- Shift all type variables to meet the current context. where ty = case snd (indexToBinding ctx index) of BindTypeAlias tyalias -> tyalias BindVar tyvar -> tyvar BindTermAlias _ ty -> ty _ -> undefined -- | Simplify type so that the outer most is not TypeVar. simplifyType :: Context -> TermType -> TermType simplifyType ctx (TypeVar var) = simplifyType ctx (getBindingType ctx var) simplifyType _ ty = ty typeEqual :: Context -> TermType -> TermType -> Bool typeEqual ctx ty1 ty2 = case (ty1, ty2) of (TypeBool, TypeBool) -> True (TypeNat, TypeNat) -> True (TypeList ty1, TypeList ty2) -> typeEqual ctx ty1 ty2 (TypeUnit, TypeUnit) -> True (TypeRecord fields1, TypeRecord fields2) -> length fields1 == length fields2 && all (\((f1, ty1), (f2, ty2)) -> f1 == f2 && typeEqual ctx ty1 ty2) (zip fields1 fields2) (TypeArrow tya1 tya2, TypeArrow tyb1 tyb2) -> typeEqual ctx tya1 tyb1 && typeEqual ctx tya2 tyb2 (TypeVar i, TypeVar j) -> i == j (TypeVar _, _) -> typeEqual ctx (simplifyType ctx ty1) ty2 (_, TypeVar _) -> typeEqual ctx ty1 (simplifyType ctx ty2) _ -> False -- | Return the type of the given term. For the sake of `TermAscribe`, type is not evaluated or simplified. typeOf :: Context -> Term -> TermType typeOf ctx (TermIfThenElse t t1 t2) = if typeEqual ctx (typeOf ctx t) TypeBool then let ty1 = typeOf ctx t1 ty2 = typeOf ctx t2 in if typeEqual ctx ty1 ty2 then ty1 else error "type error: arms of conditional have different types" else error "type error: guard of conditional not a boolean" typeOf _ TermTrue = TypeBool typeOf _ TermFalse = TypeBool typeOf _ TermZero = TypeNat typeOf ctx (TermSucc t) = if typeEqual ctx (typeOf ctx t) TypeNat then TypeNat else error "type error: argument of succ is not a number" typeOf ctx (TermPred t) = if typeEqual ctx (typeOf ctx t) TypeNat then TypeNat else error "type error: argument of pred is not a number" typeOf ctx (TermIsZero t) = if typeEqual ctx (typeOf ctx t) TypeNat then TypeBool else error "type error: argument of iszero is not a number" -- Our syntax and typechecker are slightly different from TAPL's original implenmentation, see ex 11.12.2. typeOf _ (TermNil ty) = TypeList ty typeOf ctx (TermCons t1 t2) = case simplifyType ctx tyList of TypeList ty -> if typeEqual ctx ty (typeOf ctx t1) then tyList else error "type error: list head and rest are incompatible" _ -> error "type error: expect list type" where tyList = typeOf ctx t2 typeOf ctx (TermIsNil t) = case simplifyType ctx (typeOf ctx t) of TypeList _ -> TypeBool _ -> error "type error: expect list type" typeOf ctx (TermHead t) = case simplifyType ctx (typeOf ctx t) of TypeList ty -> ty _ -> error "type error: expect list type" typeOf ctx (TermTail t) = case simplifyType ctx (typeOf ctx t) of TypeList ty -> TypeList ty _ -> error "type error: expect list type" typeOf _ TermUnit = TypeUnit typeOf ctx (TermRecord fields) = if unique then TypeRecord (map (\(f, t) -> (f, typeOf ctx t)) fields) else error "type error: record contains duplicate field" where unique = S.size (S.fromList (map fst fields)) == length fields typeOf ctx (TermProj t field) = case simplifyType ctx (typeOf ctx t) of TypeRecord fields -> case find (\(f, _) -> f == field) fields of Just (_, ty) -> ty Nothing -> error $ "type error: field " ++ field ++ " not found" _ -> error "type error: expected record type" typeOf ctx (TermLet pat t1 t2) = typeShift (typeOf ctx' t2) (-1) where ty1 = typeOf ctx t1 ctx' = foldr add ctx (typeOfPattern ctx ty1 pat) where add (var, ty) ctx = addBinding ctx var (BindVar ty) typeOf ctx (TermFix t) = case simplifyType ctx (typeOf ctx t) of TypeArrow ty1 ty2 -> if typeEqual ctx ty1 ty2 then ty1 else error "result of body not compatible with domain" _ -> error "arrow type expected" typeOf ctx (TermVar var) = getBindingType ctx var typeOf ctx (TermAbs var ty t) = TypeArrow ty (typeShift (typeOf ctx' t) (-1)) where ctx' = addBinding ctx var (BindVar ty) typeOf ctx (TermApp t1 t2) = case ty1 of TypeArrow ty3 ty4 -> if typeEqual ctx ty3 ty2 then ty4 else error "type error: parameter type mismatch" _ -> error "type error: arrow type expected" where ty1 = simplifyType ctx (typeOf ctx t1) ty2 = typeOf ctx t2 typeOf ctx (TermAscribe t ty) = if typeEqual ctx ty ty0 then ty else error "type error: body of as-term does not have the expected type" where ty0 = typeOf ctx t typeOfPattern :: Context -> TermType -> Pattern -> [(String, TermType)] typeOfPattern _ ty (PatternVar var) = [(var, ty)] typeOfPattern ctx ty (PatternRecord pats) = case simplifyType ctx ty of TypeRecord fields -> go pats where go :: [(String, Pattern)] -> [(String, TermType)] go [] = [] go ((index, pat) : pats) = case find (\(index2, _) -> index == index2) fields of Just (_, ty) -> go pats ++ typeOfPattern ctx ty pat Nothing -> error $ "type error: field " ++ index ++ " not found in pattern matching" _ -> error "type error: expected record type"
foreverbell/unlimited-plt-toys
tapl/fullsimple/Type.hs
bsd-3-clause
6,158
0
15
1,575
2,104
1,067
1,037
129
19
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.ARB.PointSprite -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/ARB/point_sprite.txt ARB_point_sprite> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.ARB.PointSprite ( -- * Enums gl_COORD_REPLACE_ARB, gl_POINT_SPRITE_ARB ) where import Graphics.Rendering.OpenGL.Raw.Tokens
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/ARB/PointSprite.hs
bsd-3-clause
668
0
4
81
40
33
7
4
0
module Chapter12 where import Data.Maybe notThe :: String -> Maybe String notThe x | x == "the" = Nothing | otherwise = Just x replaceThe :: String -> String replaceThe x = case words x of (h : t) -> (fromMaybe "a" . notThe) h ++ (replaceThe . unwords) t [] -> [] vowels :: String vowels = "aeiou" countTheBeforeVowel :: String -> Integer countTheBeforeVowel x = let countTheRest = countTheBeforeVowel . unwords in case words x of ("the" : (x' : _) : xs) -> if x' `elem` vowels then 1 + countTheRest xs else countTheRest xs _ -> 0 countVowels ::String -> Integer countVowels x = let onlyVowels = filter (`elem` vowels) count = fromIntegral . length in count [ v | w <- words x, v <- onlyVowels w ] newtype Word' = Word' String deriving (Eq, Show) mkWord :: String -> Maybe Word' mkWord "" = Just (Word' "") mkWord x = let allVowels = filter (`elem` vowels) x count = fromIntegral . length numVowels = count allVowels allChars = count $ filter (/= ' ') x in if numVowels / allChars > 0.5 then Nothing else Just (Word' x) data Nat = Zero | Succ Nat deriving (Eq, Show) natToInteger :: Nat -> Integer natToInteger Zero = 0 natToInteger (Succ x) = 1 + natToInteger x integerToNat :: Integer -> Maybe Nat integerToNat x | x < 0 = Nothing | x == 0 = Just Zero | otherwise = if x - 1 == 0 then Just (Succ Zero) else Succ <$> integerToNat (x - 1) isJust' :: Maybe a -> Bool isJust' (Just _) = True isJust' _ = False isNothing' :: Maybe a -> Bool isNothing' = not . isJust' mayybee :: b -> (a -> b) -> Maybe a -> b mayybee x f y = fromMaybe x (f <$> y) fromMaybe' :: a -> Maybe a -> a fromMaybe' x Nothing = x fromMaybe' _ (Just x') = x' data BinaryTree a = Leaf | Node (BinaryTree a) a (BinaryTree a) deriving (Eq, Ord, Show) unfold :: (a -> Maybe (a, b, a)) -> a -> BinaryTree b unfold f x = fromMaybe Leaf $ (\(x0, y, x1) -> Node (unfold f x0) y (unfold f x1)) <$> f x treeBuild :: Integer -> BinaryTree Integer treeBuild x | x < 1 = Leaf | otherwise = let expand y = if y > x - 1 then Nothing else Just (y + 1, y, y + 1) leaf = unfold expand 1 in Node leaf 0 leaf
taojang/haskell-programming-book-exercise
src/ch12/Chapter12.hs
bsd-3-clause
2,395
0
14
764
992
507
485
72
3
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverlappingInstances #-} module CrispMain ( main ) where import Parser import Emit import Options import Syntax import System.Console.Haskeline import System.Environment (getArgs) import qualified LLVM.General.AST as AST import Data.Functor (void) import Data.Maybe (fromJust) import Control.Applicative (Applicative) import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Except (ExceptT(..), throwE) import Control.Monad.Trans (MonadTrans(..), MonadIO) import Control.Monad.Trans.Error (ErrorT(..)) import Control.Monad.Error.Class (throwError, catchError) import Control.Monad.State (get, put) import Control.Monad.State.Strict (StateT(..), MonadState) import Control.Monad.Reader (ReaderT(..), MonadReader, ask) main :: IO () main = do args <- getArgs opts <- getOptions args either putStrLn (const $ return ()) =<< runCrispComputation cc opts emptyModule where cc = do CompilerOptions{..} <- ask initModule (not optReplMode) "default module" if optReplMode then repl else compile compile :: CrispComputation () compile = do processFile writeTargetCode liftIO $ putStrLn "Compiled successfully." repl :: CrispComputation () repl = do opts <- ask runInputT defaultSettings loop where loop = do modl <- lift get minput <- getInputLine "ready> " case minput of Nothing -> outputStrLn "Goodbye." Just input -> do lift $ catchError (process input) (liftIO . putStrLn) loop processFile :: CrispComputation () processFile = do CompilerOptions{..} <- ask liftIO (readFile optInputFilePath) >>= process process :: String -> CrispComputation () process source = do opts <- ask modl <- get exprs <- parseComputation let defExprs' = filter isDefinition exprs ++ defExprs modl nonDefExprs = filter (not . isDefinition) exprs updatedAstMod <- liftIO $ codegen opts (astModule modl) nonDefExprs defExprs' put $ CompilerState updatedAstMod defExprs' where isDefinition (DefExp {}) = True isDefinition _ = False parseComputation = liftErrorT . ErrorT . return $ parseExpr source
talw/crisp-compiler
src/CrispMain.hs
bsd-3-clause
2,191
0
17
428
669
355
314
69
2
{-# LANGUAGE TypeOperators #-} module Evaluator.Syntax where import Evaluator.Deeds import Core.FreeVars import Core.Renaming import Core.Size import Core.Syntax import Core.Tag import Renaming import Utilities import qualified Data.Map as M type Anned = Tagged :.: Sized :.: FVed type AnnedTerm = Anned (TermF Anned) type AnnedValue = ValueF Anned type AnnedAlt = AltF Anned annee :: Anned a -> a annee = extract annedSize :: Anned a -> Size annedSize = size . unComp . tagee . unComp annedFreeVars :: Anned a -> FreeVars annedFreeVars = freeVars . sizee . unComp . tagee . unComp annedTag :: Anned a -> Tag annedTag = tag . unComp annedVarFreeVars' = taggedSizedFVedVarFreeVars' annedTermFreeVars = taggedSizedFVedTermFreeVars annedTermFreeVars' = taggedSizedFVedTermFreeVars' annedValueFreeVars = taggedSizedFVedValueFreeVars annedValueFreeVars' = taggedSizedFVedValueFreeVars' annedAltsFreeVars = taggedSizedFVedAltsFreeVars annedVarSize' = taggedSizedFVedVarSize' annedTermSize' = taggedSizedFVedTermSize' annedTermSize = taggedSizedFVedTermSize annedValueSize' = taggedSizedFVedValueSize' annedValueSize = taggedSizedFVedValueSize annedAltsSize = taggedSizedFVedAltsSize renameAnnedTerm = renameTaggedSizedFVedTerm :: IdSupply -> Renaming -> AnnedTerm -> AnnedTerm renameAnnedValue = renameTaggedSizedFVedValue renameAnnedValue' = renameTaggedSizedFVedValue' renameAnnedAlts = renameTaggedSizedFVedAlts detagAnnedTerm = taggedSizedFVedTermToFVedTerm detagAnnedValue = taggedSizedFVedValueToFVedValue detagAnnedValue' = taggedSizedFVedValue'ToFVedValue' detagAnnedAlts = taggedSizedFVedAltsToFVedAlts annedVar :: Tag -> Var -> Anned Var annedVar tg x = Comp (Tagged tg (Comp (Sized (annedVarSize' x) (FVed (annedVarFreeVars' x) x)))) annedTerm :: Tag -> TermF Anned -> AnnedTerm annedTerm tg e = Comp (Tagged tg (Comp (Sized (annedTermSize' e) (FVed (annedTermFreeVars' e) e)))) annedValue :: Tag -> ValueF Anned -> Anned AnnedValue annedValue tg v = Comp (Tagged tg (Comp (Sized (annedValueSize' v) (FVed (annedValueFreeVars' v) v)))) toAnnedTerm :: IdSupply -> Term -> AnnedTerm toAnnedTerm tag_ids = tagFVedTerm tag_ids . reflect data QA = Question Var | Answer (ValueF Anned) deriving (Show) instance Pretty QA where pPrintPrec level prec = pPrintPrec level prec . qaToAnnedTerm' qaToAnnedTerm' :: QA -> TermF Anned qaToAnnedTerm' (Question x) = Var x qaToAnnedTerm' (Answer v) = Value v type UnnormalisedState = (Deeds, Heap, Stack, In AnnedTerm) type State = (Deeds, Heap, Stack, In (Anned QA)) denormalise :: State -> UnnormalisedState denormalise (deeds, h, k, (rn, qa)) = (deeds, h, k, (rn, fmap qaToAnnedTerm' qa)) -- Invariant: LetBound things cannot refer to LambdaBound things. -- -- This is motivated by: -- 1. There is no point lambda-abstracting over things referred to by LetBounds because the resulting h-function would be -- trapped under the appropriate let-binding anyway, at which point all the lambda-abstracted things would be in scope as FVs. -- 2. It allows (but does not require) the matcher to look into the RHS of LetBound stuff (rather than just doing nominal -- matching). data HowBound = InternallyBound | LambdaBound | LetBound deriving (Eq, Show) instance Pretty HowBound where pPrint = text . show instance NFData HowBound data HeapBinding = HB { howBound :: HowBound, heapBindingMeaning :: Either (Maybe Tag) (In AnnedTerm) } deriving (Show) instance NFData HeapBinding where rnf (HB a b) = rnf a `seq` rnf b instance NFData Heap where rnf (Heap a b) = rnf a `seq` rnf b instance Pretty HeapBinding where pPrintPrec level prec (HB how mb_in_e) = case how of InternallyBound -> either (const empty) (pPrintPrec level prec . renameIn (renameAnnedTerm prettyIdSupply)) mb_in_e LambdaBound -> text "λ" <> angles (either (const empty) (pPrintPrec level noPrec . renameIn (renameAnnedTerm prettyIdSupply)) mb_in_e) LetBound -> text "l" <> angles (either (const empty) (pPrintPrec level noPrec . renameIn (renameAnnedTerm prettyIdSupply)) mb_in_e) lambdaBound :: HeapBinding lambdaBound = HB LambdaBound (Left Nothing) internallyBound :: In AnnedTerm -> HeapBinding internallyBound in_e = HB InternallyBound (Right in_e) environmentallyBound :: Tag -> HeapBinding environmentallyBound tg = HB LetBound (Left (Just tg)) type PureHeap = M.Map (Out Var) HeapBinding data Heap = Heap PureHeap IdSupply deriving (Show) instance Pretty Heap where pPrintPrec level prec (Heap h _) = pPrintPrec level prec h type Stack = [Tagged StackFrame] data StackFrame = Apply (Out Var) | Scrutinise (In [AnnedAlt]) | PrimApply PrimOp [In (Anned AnnedValue)] [In AnnedTerm] | Update (Out Var) deriving (Show) instance NFData StackFrame where rnf (Apply a) = rnf a rnf (Scrutinise a) = rnf a rnf (PrimApply a b c) = rnf a `seq` rnf b `seq` rnf c rnf (Update a) = rnf a instance Pretty StackFrame where pPrintPrec level prec kf = case kf of Apply x' -> pPrintPrecApp level prec (text "[_]") x' Scrutinise in_alts -> pPrintPrecCase level prec (text "[_]") (renameIn (renameAnnedAlts prettyIdSupply) in_alts) PrimApply pop in_vs in_es -> pPrintPrecPrimOp level prec pop (map SomePretty in_vs ++ map SomePretty in_es) Update x' -> pPrintPrecApp level prec (text "update") x' heapBindingTerm :: HeapBinding -> Maybe (In AnnedTerm) heapBindingTerm = either (const Nothing) Just . heapBindingMeaning heapBindingTag :: HeapBinding -> Maybe Tag heapBindingTag = either id (Just . annedTag . snd) . heapBindingMeaning -- | Size of HeapBinding for Deeds purposes heapBindingSize :: HeapBinding -> Size heapBindingSize (HB InternallyBound (Right (_, e))) = annedSize e heapBindingSize _ = 0 -- | Size of StackFrame for Deeds purposes stackFrameSize :: StackFrame -> Size stackFrameSize kf = 1 + case kf of Apply _ -> 0 Scrutinise (_, alts) -> annedAltsSize alts PrimApply _ in_vs in_es -> sum (map (annedValueSize . snd) in_vs ++ map (annedTermSize . snd) in_es) Update _ -> 0 stateSize :: State -> Size stateSize (_deeds, h, k, in_qa) = heapSize h + stackSize k + qaSize (snd in_qa) where qaSize = annedSize . fmap qaToAnnedTerm' heapSize (Heap h _) = sum (map heapBindingSize (M.elems h)) stackSize = sum . map (stackFrameSize . tagee) addStateDeeds :: Deeds -> (Deeds, Heap, Stack, In (Anned a)) -> (Deeds, Heap, Stack, In (Anned a)) addStateDeeds extra_deeds (deeds, h, k, in_e) = (extra_deeds + deeds, h, k, in_e) releaseHeapBindingDeeds :: Deeds -> HeapBinding -> Deeds releaseHeapBindingDeeds deeds hb = deeds + heapBindingSize hb releasePureHeapDeeds :: Deeds -> PureHeap -> Deeds releasePureHeapDeeds = M.fold (flip releaseHeapBindingDeeds) releaseStackDeeds :: Deeds -> Stack -> Deeds releaseStackDeeds = foldl' (\deeds kf -> deeds + stackFrameSize (tagee kf)) releaseStateDeed :: (Deeds, Heap, Stack, In (Anned a)) -> Deeds releaseStateDeed (deeds, Heap h _, k, (_, e)) = releaseStackDeeds (releasePureHeapDeeds (deeds + annedSize e) h) k
batterseapower/chsc
Evaluator/Syntax.hs
bsd-3-clause
7,346
0
17
1,482
2,237
1,169
1,068
135
4
{-# LANGUAGE NoImplicitPrelude #-} module Utils where import Data.Natural import Prelude (Bool, Int, Maybe (..), Show, String, id, ($), (&&), (+), (-), (.), (<), (<=), (>), (>=)) import Types -- Helpers needed to dealing with the View/Natural encoding of natural numbers -- These are not needed in Ruby because we only use Integer/Fixnums and basic -- arithemic operations on them. Because we restrict the values of to being -- zero or positive to represent natural numbers appropriate, we have some -- extra work, which - in fairness - should have been provided by the library -- author, not needing to be written by application developers inside their apps. -- | Decrement the SellIn value -- -- Examples: -- -- >>> decr $ Fresh Zero -- Stale Zero -- -- >>> decr $ Stale (Succ 2) -- Stale (Succ 3) decr :: SellIn -> SellIn decr (Fresh Zero) = Stale Zero decr (Fresh (Succ n)) = Fresh $ view n decr (Stale (Succ n)) = Stale $ view $ monus (n+2) 0 -- | Decrement by N given a starting point -- -- Examples: -- -- >>> decrVN 2 $ Succ 7 -- Succ 5 -- -- >> decrVN 5 $ Succ 12 -- Succ 7 -- -- >> decrVN 2 $ Succ 1 -- Zero decrVN :: Natural -> View -> View decrVN n Zero = Zero decrVN n (Succ m) = view $ monus (m+1) n decrV :: View -> View decrV = decrVN 1 -- | Increment by N given a starting point -- -- Examples: -- -- >>> incrVN 5 (Succ 1) -- Succ 6 -- -- >>> incrVN 1 Zero -- Succ 1 incrVN :: Natural -> View -> View incrVN n Zero = Succ n incrVN n (Succ m) = Succ (n+m) incrV :: View -> View incrV = incrVN 1 -- | Inclusive range predicate -- -- Examples: -- -- >>> between 0 4 5 -- False -- -- >>> between 10 20 18 -- True -- -- >>> between 0 5 0 -- True -- -- >>> between 0 5 5 -- True -- -- >>> between 1 5 0 -- False between :: Natural -> Natural -> Natural -> Bool between n m p = p >= n && p <= m
mbbx6spp/animated-fiesta
src/Utils.hs
bsd-3-clause
1,893
0
9
468
414
256
158
22
1
module Control.Yield.Flat where import Control.Monad (liftM) data Producing o i m r = Yield o (i -> Producing o i m r) | M (m (Producing o i m r)) | R r newtype Consuming r m i o = Consuming { provide :: i -> Producing o i m r } data ProducerState o i m r = Produced o (Consuming r m i o) | Done r fromStep :: Monad m => m (ProducerState o i m r) -> Producing o i m r fromStep m = M $ liftM f m where f (Done r) = R r f (Produced o (Consuming k)) = Yield o k resume :: Monad m => Producing o i m r -> m (ProducerState o i m r) resume (M m) = m >>= resume resume (R r) = return (Done r) resume (Yield o k) = return (Produced o (Consuming k))
DanBurton/yield
Control/Yield/Flat.hs
bsd-3-clause
666
0
11
176
355
186
169
19
2
module Ttlv.Validator.Types ( string , stringEq , tStruct , tEnum , tByteString , tString , tBigInt , tInt , tLong , tInterval , tDateTime , tBool) where import Data.Text import Ttlv.Data import Ttlv.Tag import Ttlv.Validator.Structures -- | on: Ttlv -- check Ttlv data type string :: TtlvParser Ttlv string = TtlvParser $ \t -> case getTtlvData t of TtlvString _ -> Right t _ -> Left ["not a string"] -- | on: Ttlv -- check Ttlv data type and value stringEq :: Text -> TtlvParser Ttlv stringEq s = TtlvParser $ \t -> case getTtlvData t of TtlvString x -> if x == s then Right t else Left ["mismatch in expected value"] _ -> Left ["not a string"] -- | on: Ttlv -- check Ttlv data type tStruct :: TtlvParser Ttlv tStruct = TtlvParser $ \t -> case getTtlvData t of TtlvStructure _ -> Right t _ -> Left ["not a structure"] -- | on: Ttlv -- check Ttlv data type tEnum :: TtlvParser Ttlv tEnum = TtlvParser $ \t -> case getTtlvData t of TtlvEnum _ -> Right t _ -> Left ["not an enum"] tByteString :: TtlvParser Ttlv tByteString = TtlvParser $ \t -> case getTtlvData t of TtlvByteString _ -> Right t _ -> Left ["not a byte-string"] tString :: TtlvParser Ttlv tString = TtlvParser $ \t -> case getTtlvData t of TtlvString _ -> Right t _ -> Left ["not a string"] tBigInt :: TtlvParser Ttlv tBigInt = TtlvParser $ \t -> case getTtlvData t of TtlvBigInt _ -> Right t _ -> Left ["not a big int"] tInt :: TtlvParser Ttlv tInt = TtlvParser $ \t -> case getTtlvData t of TtlvInt _ -> Right t _ -> Left ["not an int"] tLong :: TtlvParser Ttlv tLong = TtlvParser $ \t -> case getTtlvData t of TtlvLongInt _ -> Right t _ -> Left ["not an int"] tInterval :: TtlvParser Ttlv tInterval = TtlvParser $ \t -> case getTtlvData t of TtlvInterval _ -> Right t _ -> Left ["not an int"] tDateTime :: TtlvParser Ttlv tDateTime = TtlvParser $ \t -> case getTtlvData t of TtlvDateTime _ -> Right t _ -> Left ["not an int"] tBool :: TtlvParser Ttlv tBool = TtlvParser $ \t -> case getTtlvData t of TtlvBool _ -> Right t _ -> Left ["not a bool"]
nymacro/hs-kmip
src/Ttlv/Validator/Types.hs
bsd-3-clause
2,469
0
12
843
735
376
359
66
3
-- | -- Module: Pin -- Copyright: (c) 2012 Mark Hibberd -- License: BSD3 -- Maintainer: Mark Hibberd <[email protected]> -- Portability: portable -- -- Library for pin.net.au HTTP Api -- module Network.Api.Pin (module X) where import Network.Api.Pin.Core as X import Network.Api.Pin.Data as X import Network.Api.Pin.Defaults as X
markhibberd/pin
src/Network/Api/Pin.hs
bsd-3-clause
344
0
4
60
49
39
10
4
0
{-# LANGUAGE OverloadedStrings, TypeFamilies, TupleSections, FlexibleContexts, PackageImports #-} module Server (xmpp, SHandle(..)) where import Control.Arrow import Control.Monad import "monads-tf" Control.Monad.State import Control.Concurrent (forkIO) import Data.Maybe import Data.Pipe import Data.HandleLike import Text.XML.Pipe import Network import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Base64 as B64 import DigestSv data SHandle s h = SHandle h instance HandleLike h => HandleLike (SHandle s h) where type HandleMonad (SHandle s h) = StateT s (HandleMonad h) type DebugLevel (SHandle s h) = DebugLevel h hlPut (SHandle h) = lift . hlPut h hlGet (SHandle h) = lift . hlGet h hlClose (SHandle h) = lift $ hlClose h hlDebug (SHandle h) = (lift .) . hlDebug h main :: IO () main = do socket <- listenOn $ PortNumber 5222 forever $ do (h, _, _) <- accept socket voidM . forkIO . (`evalStateT` (0 :: Int)) . xmpp $ SHandle h type XmppState = Int xmpp :: (MonadState (HandleMonad h), StateType (HandleMonad h) ~ Int, HandleLike h) => h -> HandleMonad h () xmpp h = do hlPut h . xmlString $ begin ++ authFeatures hlPut h . xmlString $ challengeXml voidM . runPipe $ handleP h =$= xmlEvent =$= convert fromJust -- =$= (xmlBegin >>= xmlNode) =$= xmlPipe =$= convert showResponse =$= processResponse h =$= printP h hlDebug h "critical" "finished" hlPut h "</stream:stream>" hlClose h xmlPipe :: Monad m => Pipe XmlEvent XmlNode m () xmlPipe = do c <- xmlBegin >>= xmlNode when c $ xmlPipe data ShowResponse = SRStream [(Tag, BS.ByteString)] | SRAuth [(Tag, BS.ByteString)] | SRResponse BS.ByteString | SRResponseNull | SRIq [(Tag, BS.ByteString)] [Iq] | SRPresence [(Tag, BS.ByteString)] [XmlNode] | SRRaw XmlNode deriving Show data Iq = IqBind [XmlNode] | IqBindReq Requirement Bind | IqSession | IqRoster | IqRaw XmlNode deriving Show toIq :: XmlNode -> Iq toIq (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-bind"), "bind") _ [] [n, n']) | Just r <- toRequirement n = IqBindReq r $ toBind n' toIq (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-session"), "session") _ [] []) = IqSession toIq (XmlNode ((_, Just "jabber:iq:roster"), "query") _ [] []) = IqRoster toIq n = IqRaw n data Requirement = Optional | Required deriving Show toRequirement :: XmlNode -> Maybe Requirement toRequirement (XmlNode (_, "optional") _ [] []) = Just Optional toRequirement (XmlNode (_, "required") _ [] []) = Just Required toRequirement _ = Nothing data Bind = Resource BS.ByteString | BindRaw XmlNode deriving Show toBind :: XmlNode -> Bind toBind (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-bind"), "resource") [] [] [XmlCharData cd]) = Resource cd toBind n = BindRaw n showResponse :: XmlNode -> ShowResponse showResponse (XmlStart ((_, Just "http://etherx.jabber.org/streams"), "stream") _ as) = SRStream $ map (first toTag) as showResponse (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-sasl"), "auth") _ as []) = SRAuth $ map (first toTag) as showResponse (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-sasl"), "response") _ [] []) = SRResponseNull showResponse (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-sasl"), "response") _ [] [XmlCharData cd]) = SRResponse . (\(Right s) -> s) $ B64.decode cd showResponse (XmlNode ((_, Just "jabber:client"), "iq") _ as ns) = SRIq (map (first toTag) as) (map toIq ns) showResponse (XmlNode ((_, Just "jabber:client"), "presence") _ as ns) = SRPresence (map (first toTag) as) ns showResponse n = SRRaw n data Tag = To | Lang | Version | Mechanism | Id | Type | TagRaw QName deriving (Eq, Show) toTag :: QName -> Tag toTag ((_, Just "jabber:client"), "to") = To toTag (("xml", Nothing), "lang") = Lang toTag ((_, Just "jabber:client"), "version") = Version toTag ((_, Just "urn:ietf:params:xml:ns:xmpp-sasl"), "mechanism") = Mechanism toTag ((_, Just "jabber:client"), "id") = Id toTag ((_, Just "jabber:client"), "type") = Type toTag n = TagRaw n processResponse :: (MonadState (HandleMonad h), StateType (HandleMonad h) ~ XmppState, HandleLike h) => h -> Pipe ShowResponse ShowResponse (HandleMonad h) () processResponse h = do mr <- await case mr of Just r -> lift (procR h r) >> yield r >> processResponse h _ -> return () procR :: (MonadState (HandleMonad h), StateType (HandleMonad h) ~ XmppState, HandleLike h) => h -> ShowResponse -> HandleMonad h () procR h (SRResponse _) = do let sret = B64.encode . ("rspauth=" `BS.append`) . fromJust . lookup "response" $ responseToKvs False sampleDR hlPut h . xmlString . (: []) $ XmlNode (nullQ "challenge") [("", "urn:ietf:params:xml:ns:xmpp-sasl")] [] [XmlCharData sret] hlDebug h "critical" $ sret `BS.append` "\n" procR h SRResponseNull = hlPut h . xmlString . (: []) $ XmlNode (nullQ "success") [("", "urn:ietf:params:xml:ns:xmpp-sasl")] [] [] procR h (SRStream _) = do n <- get modify (+ 1) hlDebug h "critical" . BSC.pack . (++ "\n") $ show n when (n == 1) . hlPut h . xmlString $ begin' ++ capsFeatures -- hlPut h $ xmlString begin' return () procR h (SRIq [(Id, i), (Type, "set")] [IqBindReq Required (Resource _n)]) = do hlPut h . xmlString . (: []) $ XmlNode (nullQ "iq") [] [(nullQ "id", i), (nullQ "type", "result")] [XmlNode (nullQ "jid") [] [] [XmlCharData "yoshikuni@localhost/profanity"]] procR h (SRIq [(Id, i), (Type, "set")] [IqSession]) = do hlPut h . xmlString . (: []) $ XmlNode (nullQ "iq") [] [ (nullQ "id", i), (nullQ "type", "result"), (nullQ "to", "yoshikuni@localhost/profanity") ] [] procR h (SRIq [(Id, i), (Type, "get")] [IqRoster]) = do hlPut h . xmlString . (: []) $ XmlNode (nullQ "iq") [] [ (nullQ "id", i), (nullQ "type", "result"), (nullQ "to", "yoshikuni@localhost/profanity") ] [XmlNode (nullQ "query") [("", "jabber:iq:roster")] [(nullQ "ver", "1")] []] procR h (SRPresence _ _) = hlPut h . xmlString . (: []) $ XmlNode (nullQ "message") [] [ (nullQ "type", "chat"), (nullQ "to", "yoshikuni@localhost"), (nullQ "from", "yoshio@localhost/profanity"), (nullQ "id", "hoge") ] [XmlNode (nullQ "body") [] [] [XmlCharData "Hogeru"]] procR _ _ = return () handleP :: HandleLike h => h -> Pipe () BS.ByteString (HandleMonad h) () handleP h = do c <- lift $ hlGetContent h yield c handleP h printP :: (Show a, HandleLike h) => h -> Pipe a () (HandleMonad h) () printP h = await >>= maybe (return ()) (\x -> lift (hlDebug h "critical" $ showBS x) >> printP h) showBS :: Show a => a -> BS.ByteString showBS = BSC.pack . (++ "\n") . show voidM :: Monad m => m a -> m () voidM = (>> return ()) nullQ :: BS.ByteString -> QName nullQ = (("", Nothing) ,) begin, begin' :: [XmlNode] begin = [ XmlDecl (1, 0), XmlStart (("stream", Nothing), "stream") [ ("", "jabber:client"), ("stream", "http://etherx.jabber.org/streams") ] [ (nullQ "id", "83e074ac-c014-432e-9f21-d06e73f5777e"), (nullQ "from", "localhost"), (nullQ "version", "1.0"), ((("xml", Nothing), "lang"), "en") ] ] begin' = [ XmlDecl (1, 0), XmlStart (("stream", Nothing), "stream") [ ("", "jabber:client"), ("stream", "http://etherx.jabber.org/streams") ] [ (nullQ "id", "5b5b55ce-8a9c-4879-b4eb-0231b25a54a4"), (nullQ "from", "localhost"), (nullQ "version", "1.0"), ((("xml", Nothing), "lang"), "en") ] ] authFeatures :: [XmlNode] authFeatures = [XmlNode (("stream", Nothing), "features") [] [] [mechanisms]] capsFeatures :: [XmlNode] capsFeatures = (: []) $ XmlNode (("stream", Nothing), "features") [] [] [caps, rosterver, bind, session] caps :: XmlNode caps = XmlNode (nullQ "c") [("", "http://jabber.org/protocol/caps")] [ (nullQ "hash", "sha-1"), (nullQ "ver", "k07nuHawZqmndRtf3ZfBm54FwL0="), (nullQ "node", "http://prosody.im") ] [] rosterver :: XmlNode rosterver = XmlNode (nullQ "ver") [("", "urn:xmpp:features:rosterver")] [] [XmlNode (nullQ "optional") [] [] []] bind :: XmlNode bind = XmlNode (nullQ "bind") [("", "urn:ietf:params:xml:ns:xmpp-bind")] [] [XmlNode (nullQ "required") [] [] []] session :: XmlNode session = XmlNode (nullQ "session") [("", "urn:ietf:params:xml:ns:xmpp-session")] [] [XmlNode (nullQ "optional") [] [] []] mechanisms :: XmlNode mechanisms = XmlNode (nullQ "mechanisms") [("", "urn:ietf:params:xml:ns:xmpp-sasl")] [] [ XmlNode (nullQ "mechanism") [] [] [XmlCharData "SCRAM-SHA-1"], XmlNode (nullQ "mechanism") [] [] [XmlCharData "DIGEST-MD5"] ] convert :: Monad m => (a -> b) -> Pipe a b m () convert f = await >>= maybe (return ()) (\x -> yield (f x) >> convert f) challengeXml :: [XmlNode] challengeXml = (: []) $ XmlNode (nullQ "challenge") [("", "urn:ietf:params:xml:ns:xmpp-sasl")] [] [XmlCharData challenge] challenge :: BS.ByteString challenge = B64.encode $ BS.concat [ "realm=\"localhost\",", "nonce=\"90972262-92fe-451d-9526-911f5b8f6e34\",", "qop=\"auth\",", "charset=utf-8,", "algorithm=md5-sess" ]
YoshikuniJujo/forest
subprojects/xmpipe/Server.hs
bsd-3-clause
8,944
198
14
1,548
3,983
2,123
1,860
241
2
-- | Infinite supplies of unique values. module Control.Monad.Supply.Class ( MonadSupply , fresh ) where class MonadSupply a m | m -> a where fresh :: m a
iron-codegen/iron
library/Control/Monad/Supply/Class.hs
bsd-3-clause
164
0
7
37
42
25
17
-1
-1
{-# LANGUAGE CPP, GeneralizedNewtypeDeriving, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses, FunctionalDependencies, TypeSynonymInstances, RankNTypes #-} module System.File.Tree ( -- *Directory tree structure FSTree(..), mkFSTree, FSForest -- *Generic rose trees -- |Re-exported from "Data.Tree" , Tree(..), Forest -- * Overloaded tree lenses , TreeLens(..) -- *Retrieve directory trees from the filesystem , getDirectory, getDirectory' -- *IO operations on directory trees -- **copy , copyTo, copyTo_ -- **move , moveTo, moveTo_ , mergeInto, mergeInto_ -- **remove , remove, tryRemove, tryRemoveWith -- * Operations on directory trees -- **basic operations , pop, pop_, flatten, flattenPostOrder, levels -- ** map over subtrees , map, mapM, mapM_ -- **find subtrees , find, findM -- **filter subtrees , filter, filterM -- ***useful predicates , isFile, isDir, isSymLink, isSymDir, isSymFile, isRealFile, isRealDir -- **extract subtrees , extract, extractM -- **truncate tree to a maximum level , truncateAt -- **zip with destination tree , zipWithDest, zipWithDestM, zipWithDestM_ ) where import System.IO.Unsafe (unsafeInterleaveIO) import Unsafe.Coerce (unsafeCoerce) import System.Directory (getDirectoryContents, doesDirectoryExist, doesFileExist, copyFile, renameFile, removeFile, createDirectory, createDirectoryIfMissing, removeDirectory, removeDirectoryRecursive) import System.FilePath ((</>)) #if !mingw32_HOST_OS import System.Posix.Files (getSymbolicLinkStatus, isSymbolicLink) #endif import Data.Tree (Tree(..), Forest) import qualified Data.Tree as Tree (flatten, levels) import Data.DList as DL (DList, cons, append, toList, empty, concat, snoc) import Control.Exception (throwIO, catch, IOException) import System.IO.Error (ioeGetErrorType, doesNotExistErrorType) import Control.Monad (forM, liftM, liftM2, void) import Control.Monad.Identity (runIdentity) import Control.Applicative ((<$>), (<*>), (<*)) import Control.Arrow (second) import Data.Foldable (foldrM) import qualified Data.Traversable as T (mapM) import Data.Maybe (mapMaybe, catMaybes) import Data.Lens.Light (Lens, lens, getL, setL, modL) import Control.DeepSeq (NFData(..), deepseq) import Control.Conditional (ifM, (<&&>), (<||>), notM, condM, otherwiseM) import Data.Word (Word) import Data.Typeable (Typeable) import Data.Data (Data) import Prelude hiding (filter, catch, map, mapM, mapM_) import qualified Prelude as P -- |A representation of a filesystem tree. The root label contains the -- path context, and every child node is a single file/directory name. -- -- For example, say we have the following directory structure on our -- filesystem: -- -- @ -- /example$ tree foo --charset ASCII -- foo -- `-- bar -- `-- test -- |-- a -- |-- A -- | |-- x -- | `-- y -- |-- b -- `-- B -- @ -- -- then calling 'getDirectory' \"\/example\/foo\/bar\/test\" will yield a FSTree with -- the following structure: -- -- > /example$ ghci -- > Prelude Data.Tree System.Directory.Tree> putStrLn . drawTree . toTree =<< getDirectory "/example/foo/bar/test" -- > /example/foo/bar/test -- > | -- > +- A -- > | | -- > | +- x -- > | | -- > | `- y -- > | -- > +- B -- > | -- > +- a -- > | -- > `- b newtype FSTree = FSTree { toTree :: Tree FilePath } deriving (Typeable, Data, Eq, Read, Show) instance NFData FSTree where rnf t = getL label t `deepseq` rnf (getL children t) type FSForest = [FSTree] -- |A pseudo-constructor for 'FSTree'. mkFSTree :: FilePath -> FSForest -> FSTree mkFSTree a = FSTree . Node a . mapToTree -- |Efficiently maps 'FSTree' over a list. This is more efficient than map FSTree mapFSTree :: Forest FilePath -> FSForest mapFSTree = unsafeCoerce {-# NOINLINE mapFSTree #-} -- |Efficiently maps toTree over a list. This is more effficient than map toTree mapToTree :: FSForest -> Forest FilePath mapToTree = unsafeCoerce {-# NOINLINE mapToTree #-} -- |Overloaded lenses for 'Tree' and 'FSTree' class TreeLens t a | t -> a where -- |Lens for the value at a tree node label :: Lens t a -- |Lens for a list of children nodes children :: Lens t [t] instance TreeLens (Tree a) a where label = lens rootLabel (\a t -> t {rootLabel = a}) children = lens subForest (\c t -> t {subForest = c}) instance TreeLens FSTree FilePath where label = lens (rootLabel . toTree) (\a fs -> FSTree $ (toTree fs) {rootLabel = a}) children = lens (mapFSTree . subForest . toTree) (\c fs -> FSTree $ (toTree fs) {subForest = mapToTree c}) -- |Lazily retrieves a representation of a directory and its contents recursively. -- -- Relative paths are not converted to absolute. Thus, a FSTree formed from a -- relative path will contain a \"relative tree\", and the usual caveats of -- current directories and relative paths apply to the tree as a whole. getDirectory :: FilePath -> IO FSTree getDirectory = getDir_ unsafeInterleaveIO {-# NOINLINE getDirectory #-} -- |A strict variant of 'getDirectory'. -- -- Though race conditionals are still a possibility, this function will avoid some -- race conditions that could be caused from the use of lazy IO. For large -- directories, this function can easily cause memory leaks. getDirectory' :: FilePath -> IO FSTree getDirectory' = getDir_ id getDir_ :: (forall a. IO a -> IO a) -> FilePath -> IO FSTree getDir_ f p = mkFSTree p <$> getChildren p where getChildren path = do cs <- P.filter (`notElem` [".",".."]) <$> f (getDirectoryContents path) forM cs $ \c -> let c' = path </> c in ifM (isRealDir c') ( f . fmap (mkFSTree c) . getChildren $ c' ) ( return $ mkFSTree c [] ) -- |Checks if a path refers to a file. isFile :: FilePath -> IO Bool isFile = doesFileExist -- |Checks if a path refers to a directory. isDir :: FilePath -> IO Bool isDir = doesDirectoryExist -- |Checks if a path refers to a symbolic link. -- NOTE: always returns False on Windows isSymLink :: FilePath -> IO Bool #if mingw32_HOST_OS isSymLink p = return False #else isSymLink p = (isSymbolicLink <$> getSymbolicLinkStatus p) `catch` handler where handler :: IOError -> IO Bool handler e | ioeGetErrorType e == doesNotExistErrorType = return False | otherwise = throwIO e #endif -- |Checks if a path refers to a symbolically linked directory isSymDir :: FilePath -> IO Bool isSymDir p = isDir p <&&> isSymLink p -- |Checks if a path refers to a symbolically linked file isSymFile :: FilePath -> IO Bool isSymFile p = isFile p <&&> isSymLink p -- |Checks if a path refers to a real directory (not a symbolic link) isRealDir :: FilePath -> IO Bool isRealDir p = isDir p <&&> notM (isSymLink p) -- |Checks if a path refers to a real file (not a symbolic link) isRealFile :: FilePath -> IO Bool isRealFile p = isFile p <&&> notM (isSymLink p) -- |Remove the root node of a filesystem tree, while preserving the paths of -- its children. In other words, this function does not alter where any paths point -- to. pop :: FSTree -> (FilePath, FSForest) pop fs = (path, P.map prepend cs) where path = getL label fs cs = getL children fs prepend = modL label (path </>) -- | > pop_ = snd . pop pop_ :: FSTree -> FSForest pop_ = snd . pop -- |Flattens a filesystem tree into a list of its contents. This is a pre-order -- traversal of the tree. flatten :: FSTree -> [FilePath] flatten = Tree.flatten . prependPaths -- |A post-order traversal of the filesystem tree. flattenPostOrder :: FSTree -> [FilePath] flattenPostOrder = toList . flatten' . prependPaths where flatten' (Node p cs) = DL.concat (P.map flatten' cs) `snoc` p -- |List of file paths at each level of the tree. levels :: FSTree -> [[FilePath]] levels = Tree.levels . prependPaths -- |Applies a function over the filepaths of a directory tree. -- -- Because we can't guarantee that the internal 'FSTree' representation is preserved -- in any way, the result is a regular 'Tree'. map :: (FilePath -> b) -> FSTree -> Tree b map f = fmap f . toTree -- |Applies a monadic action to every filepath in a filesystem tree. mapM :: Monad m => (FilePath -> m b) -> FSTree -> m (Tree b) mapM f = T.mapM f . toTree -- |'mapM' with the result discarded. mapM_ :: Monad m => (FilePath -> m b) -> FSTree -> m () mapM_ f t = mapM f t >> return () -- |Applies a predicate to each path name in a filesystem forest, and removes -- all unsuccessful paths from the result. If a directory fails the predicate test, -- then it will only be removed if all of its children also fail the test filter :: (FilePath -> Bool) -> FSForest -> FSForest filter p = runIdentity . filterM (return . p) -- |Find all sub-forests within a forest that match the given predicate. find :: (FilePath -> Bool) -> FSForest -> FSForest find p = snd . extract p -- |The first element of the result represents the forest after removing all -- subtrees that match the given predicate, and the second element is a list of -- trees that matched. This could be useful if you want to handle certain -- directories specially from others within a sub-filesystem. extract :: (FilePath -> Bool) -> FSForest -> (FSForest, FSForest) extract p = runIdentity . extractM (return . p) -- |Monadic 'filter'. filterM :: Monad m => (FilePath -> m Bool) -> FSForest -> m FSForest filterM p = foldrM (filter' "") [] . mapToTree where filter' d (Node file cs) ts = do let path = d </> file cs' <- foldrM (filter' path) [] cs b <- p path return $ if b then mkFSTree file cs' : ts else case cs' of [] -> ts _ -> mkFSTree file cs' : ts -- |Monadic 'find'. findM :: Monad m => (FilePath -> m Bool) -> FSForest -> m FSForest findM p = liftM snd . extractM p -- |Monadic 'extract'. extractM :: Monad m => (FilePath -> m Bool) -> FSForest -> m (FSForest, FSForest) extractM p = liftM (second toList) . extractM_ p extractM_ :: Monad m => (FilePath -> m Bool) -> FSForest -> m (FSForest, DList FSTree) extractM_ p = foldrM extract' ([], DL.empty) . P.map prependPaths where extract' t@(Node path cs) (ts, es) = ifM (p path) ( return (ts, FSTree t `cons` es) ) (do (cs', es') <- foldrM extract' ([], DL.empty) cs let t' = mkFSTree path cs' return (t' : ts, es' `append` es) ) -- |Truncate a tree to a given maximum level, where root is level 0. truncateAt :: TreeLens t a => Word -> t -> t truncateAt n = modL children (mapMaybe (truncate' 1)) where truncate' i t | i > n = Nothing | otherwise = Just . modL children (mapMaybe (truncate' (i+1))) $ t -- |Converts a 'FSTree' to a 'Tree' where each node in the 'Tree' contains the -- full path name of the filesystem node it represents. prependPaths :: FSTree -> Tree FilePath prependPaths (FSTree root) = modL children (P.map (prepend' rootPath)) root where rootPath = rootLabel root prepend' parentPath = prependChildren . modL label (parentPath </>) prependChildren fs = modL children (P.map (prepend' (rootLabel fs))) fs -- |Copy a filesystem tree to a new location, creating directories as necessary. -- The resulting 'FSTree' represents all of the copied directories/files in their -- new home. -- -- Note that an single exception will halt the entire operation. copyTo :: FilePath -> FSTree -> IO FSTree copyTo = zipWithDestM_ $ \src dest ->ifM (isRealDir src) (createDirectoryIfMissing False dest) (copyFile src dest) copyTo_ :: FilePath -> FSTree -> IO () copyTo_ = (void .) . copyTo -- |Move a filesystem tree to a new location, deleting any file/directory that -- was present at the given destination path. -- -- Directories listed in the source filesystem tree are removed from disk if the move -- operation empties their contents completely. The resulting 'FSTree' represents -- all the moved directories/files in their new home. -- -- Note that an single exception will halt the entire operation. moveTo :: FilePath -> FSTree -> IO FSTree moveTo dest fs = do condM [(isSymLink dest <||> isFile dest, removeFile dest) ,(isDir dest, removeDirectoryRecursive dest) ,(otherwiseM, return ()) ] zipWithDestM_ (\s d -> ifM (isRealDir s) (createDirectory d) (renameFile s d) ) dest fs <* removeEmptyDirectories fs moveTo_ :: FilePath -> FSTree -> IO () moveTo_ = (void .) . moveTo -- |This is similar to 'moveTo', except that whatever was present at the destination -- path isn't deleted before the move operation commences. -- -- Note that an single exception will halt the entire operation. mergeInto :: FilePath -> FSTree -> IO FSTree mergeInto dest fs = zipWithDestM_ (\s d -> ifM (isRealDir s) (createDirectoryIfMissing False d) (renameFile s d) ) dest fs <* removeEmptyDirectories fs mergeInto_ :: FilePath -> FSTree -> IO () mergeInto_ = (void .) . mergeInto -- |Remove a given filesystem tree. Directories are only removed -- if the remove operation empties its contents. -- -- Note that an single exception will halt the entire operation. remove :: FSTree -> IO () remove = void . tryRemoveWith throwIO -- |A variant of 'remove'. 'IOExceptions' do not stop the removal -- process, and all 'IOExceptions' are accumulated into a list as the result of -- the operation. tryRemove :: FSTree -> IO [IOException] tryRemove = tryRemoveWith return -- |A variant of 'remove'. Allows you to specify your own exception handler to handle -- exceptions for each removal operation. tryRemoveWith :: (IOException -> IO a) -> FSTree -> IO [a] tryRemoveWith handler = fmap (catMaybes . DL.toList) . remove' . prependPaths where remove' (Node p cs) = DL.snoc <$> (fmap DL.concat . P.mapM remove' $ cs) <*> ifM (doesDirectoryExist p) (tryRemoveDirectory p >> return Nothing) (removeFile p >> return Nothing) `catch` (fmap Just . handler) -- |Helper function for removals. removeEmptyDirectories :: FSTree -> IO () removeEmptyDirectories = P.mapM_ tryRemoveDirectory . flattenPostOrder -- |Helper function for removals. tryRemoveDirectory :: FilePath -> IO () tryRemoveDirectory path = removeDirectory path `catch` handler where handler :: IOException -> IO () handler = const (return ()) -- |A generalization of the various move, copy, and remove operations. This -- operation pairs each node of a 'FSTree' with a second path formed by rerooting -- the filesystem tree to the given destination path. zipWithDest :: (FilePath -> FilePath -> a) -> FilePath -> FSTree -> [a] zipWithDest f dest fs = runIdentity $ zipWithDestM ((return .) . f) dest fs -- |Monadic 'zipWithDest' zipWithDestM :: Monad m => (FilePath -> FilePath -> m a) -> FilePath -> FSTree -> m [a] zipWithDestM f dest fs = liftM fst $ zipWithDestM__ f dest fs -- |A variant of 'zipWithDestM' where the result is discarded and instead the -- rerooted filesystem tree is returned. zipWithDestM_ :: Monad m => (FilePath -> FilePath -> m a) -> FilePath -> FSTree -> m FSTree zipWithDestM_ f dest fs = liftM snd $ zipWithDestM__ f dest fs -- |Internal implementation of the zipWithDest* operations. zipWithDestM__ :: Monad m => (FilePath -> FilePath -> m a) -> FilePath -> FSTree -> m ([a], FSTree) zipWithDestM__ f rootDest fs = liftM2 (,) (sequence $ zipWith f (flatten fs) (flatten destFs)) (return destFs) where destFs = setL label rootDest fs
kallisti-dev/filesystem-trees
src/System/File/Tree.hs
bsd-3-clause
16,588
0
20
4,248
3,672
2,020
1,652
240
3
{- Glossary: a simple glossary generator for Barrelfish Copyright (c) 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, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group. -} module Main where import System.Exit import System.IO import Text.Printf import Data.List import qualified Data.Char data Entry = Entry { entry_title :: String, entry_aliases :: [ String ], entry_description :: String } deriving (Show,Eq) glossary :: [ Entry ] glossary = [ Entry "dispatcher control block" [ "DCB" ] "The kernel object representing the dispatcher. DCBs are \ \referred to by specially typed capabilities.", Entry "kernel control block" ["KCB"] "The kernel object representing all per-core state. KCBs are \ \referred to by special capability types.", Entry "Driver Domain" [] "A driver domain executes one or more drivers. It is special in the sense that \ \it communicates with Kaluga to act on requests to spawn or destroy new driver \ \instances.", Entry "Driver Module" [] "A Barrelfish driver module is a piece of code (typically a library) that describes the logic \ \for interacting with a device. It follows a well defined structure that allows Kaluga to interface with an \ \instantiated driver (see Driver Instance) to control its life-cycle.", Entry "Driver Instance" [] "A driver is the runtime object instantiated from a given driver module. In practice any number of instances\ \can be created from a driver module and executed within one or more driver domains.", Entry "Boot driver" [] "A piece of code running on a ``home core'' to manage a ``target core''. \ \It encapsulates the hardware functionality to boot, suspend, resume, \ \and power-down the latter.", Entry "CPU driver" [] "The code running on a core which executes in kernel or \ \privileged mode. CPU drivers are the Barrelfish \ \equivalent of a kernel, except that there is one per \ \core, and they share no state or synchronization. CPU \ \drivers are typically non-preemptible, \ \single-threaded, and mostly stateless.", Entry "Mackerel" [] "The Domain Specific Language used in Barrelfish to specify \ \device hardware registers and hardware-defined in-memory \ \data structures. The Mackerel compiler takes such a \ \description and outputs a \ \C header file containing inline functions to read and \ \write named bitfields for a device or data structure, \ \together with string formatting code to aid in \ \debugging. Mackerel input files are found in the \ \\\texttt{/devices} directory of the source tree, and end \ \in \\texttt{.dev}. Generated header files are found in \ \the \\texttt{/include/dev} subdirectory of the build \ \tree.", Entry "interconnect driver" [ "ICD" ] "A partial abstraction of low-level message passing \ \mechanism, such as a shared-memory buffer or hardware \ \message passing primitive. ICDs do not present a uniform \ \interface, and therefore require specific stubs to be \ \generated by Flounder. Similarly, they do not present \ \any particular semantics with regard to flow control, \ \polled or upcall-based delivery, etc. A special case of \ \an ICD is the local message passing (LMP) mechanism, \ \which is implemented for every type of core and provide \ \communication between dispatchers running on that core.", Entry "notification driver" [ "ND" ] "A partial abstraction of a low-level message passing \ \mechanism which performs notification (sending an \ \event), rather than transferring data per se. In \ \Barrelfish these mechanisms are separated where \ \possible for flexibility and to further decouple \ \sender and receiver. Notification drivers exist in \ \Barrelfish for sending inter-processor interrupts on \ \most architectures, for example.", Entry "Flounder" [] "The Interface Definition Language used for \ \communication between domains in Barrelfish. Flounder \ \supports message type signatures, various concrete type \ \constructors like structs and arrays, and also some \ \opaque types like capabilities and interface \ \references. The Flounder compiler is written in \ \Haskell and generates code in C or THC. Flounder \ \generates specialized code for each Interconnect Driver \ \in a system.", Entry "Hake" [ "Hakefile" ] "The build system for Barrelfish. The Barrelfish source \ \tree consists of a Hakefile in each relevant source \ \directory, which contains a single Haskell expression \ \specifying a list of targets to be built. Hake itself \ \aggregates all these Hakefiles, and uses them to generate \ \a single Makefile in a separate, build directory. This \ \Makefile contains an explicit target for \\emph{every} \ \file that can be built for Barrelfish for every \ \appropriate architecture. A separate, manually-edited \ \Makefile contains convenient symbolic targets for \ \creating boot images, etc. Since the contents of \ \Hakefiles are Haskell expressions, quite powerful \ \constructs can be used to specify how to build files for \ \different targets.", Entry "Elver" [] "An intermediate boot loader for booting 64-bit \ \ELF images on Intel-architecture machines where the main \ \boot loader (such as Grub) does not support entering a \ \kernel in long mode. Elver is specified as the first \ \module of the multiboot image, and puts the boot \ \processor into long mode before jumping to the CPU \ \driver, which is assumed to be in the second multiboot \ \module.", Entry "Filet-o-Fish" [ "FoF" ] "An embedding of C into Haskell, used for writing C code \ \generators for Haskell-based domain specific languages. \ \Instead of using C syntax combinators (as used in \ \Flounder and Mackerel) FoF-based DSLs (such as Fugu and \ \Hamlet) use backend which are actually semantic \ \specifications of behavior, from which FoF can generates \ \C code which is guaranteed to implement the given \ \semantics.", Entry "Fugu" [ "errno.h" ] "A small domain-specific language (implemented using \ \Filet-o-Fish) to express error conditions and messages \ \for Barrelfish. Fugu offloads the problem of tracking \ \error messages and code, and also implements a short \ \error ``stack'' in machine word to provide more detailed \ \error information. Fugu generates the \\texttt{errno.h} \ \file.", Entry "THC" [] "A dialect of C with extensions to support the \ \asynchronous message passing flavor of most Barrelfish \ \services by providing an \\texttt{async} construct and \ \continuations. THC also integrates with specially generated \ \Flounder stubs.", Entry "System Knowledge Base" [ "SKB" ] "A repository for hardware-derived system information in \ \a running Barrelfish system. The SKB is currently a port \ \of the ECLiPse Constraint Logic Programming system, and is \ \used for (among other things) PCI bridge programming, \ \interrupt routing, and constructing routing trees for \ \intra-machine multicast. The SKB runs as a system service \ \accessed by message passing.", Entry "Octopus" [] "A service built on (and colocated with) the SKB which \ \provides locking functionality inspired by Chubby and \ \Zookeeper, and publish/subscribe notification for \ \Barrelfish processes.", Entry "Kaluga" [] "The Barrelfish device manager. Kaluga is responsible \ \to starting and stopping device drivers in response to \ \hardware events, and based on configurable system \ \policies.", Entry "capability space" [ "cspace" ] "The set of capabilities held by a dispatcher on a core \ \is organized in a guarded page table structure \ \implemented as a tree of CNodes, where internal nodes are \ \CNodes and leaf nodes are non-CNode capabilities. This \ \allows any capability held by a dispatcher to be referred \ \to using a 32-bit address; when invoking a capability, \ \the CPU driver walks the cspace structure resolving a \ \variable number of bits of this address at each level. \ \This means that capabilities used frequently should be \ \stored near the top of the tree, preferably in the root \ \CNode. Some CPU drivers allow a fast path where the \ \32-bit address is implicitly assumed to simply an offset \ \in the root CNode. The capability for the root CNode can \ \be efficiently found from the DCB; note that, unlike the \ \vspace, the cspace is purely local to a core and cannot \ \be shared between dispatchers on difference cores.", Entry "vspace" [] "An object representing a virtual address space. Unlike \ \a cspace, a vspace can under some circumstances be shared \ \between cores. However, a vspace is tied to a particular \ \core architecture, and a particular physical address \ \space, though vspaces can be manipulated on other cores \ \and even cores of other architectures. Mappings are \ \created in a vspace by specifying capabilities to regions \ \of memory that are mappable (such as frame \ \capabilities).", Entry "Aquarium" [] "A visualization tool for Barrelfish trace data. Aquarium \ \is written in C\\# and can accept data as a stream over \ \the network from a running Barrelfish machine, or from a \ \trace file. It displays a time line showing which \ \dispatchers are running on which cores, messages between \ \dispatchers, and other system events.", Entry "Hamlet" [] "The language used to specify all Barrelfish capability \ \types, together with their in-memory formats and \ \transformation rules when transferring a capability from \ \one core to another. Hamlet is implemented using \ \Filet-o-Fish and generates capability dispatch code for \ \CPU drivers, among other things. \ \Surprisingly, Hamlet is a type of fish.", Entry "Local Message Passing" [ "LMP" ] "Each Barrelfish CPU driver includes a special \ \Interconnect Driver for passing messages between \ \dispatchers on the same core, often based on the \ \concepts from LRPC and L4 IPC. This is referred to as \ \LMP.", Entry "dispatcher" [] "The data structure representing an application's \ \runnability on a core. Dispatchers contain scheduling \ \state, message end points, and upcall entry points; they \ \are the nearest equivalent to processes in Unix. \ \Dispatchers are always tied to a core. A Barrelfish \ \application can be viewed as a collection of dispatchers \ \spread across the set of cores on which the application \ \might run, together with associated other resources. \ \The term is from K42. Multiple dispatchers may share a vspace\ \or cspace.", Entry "monitor" [] "A privileged process running on a core which handles \ \most core OS functionality not provided by the CPU \ \driver. Since CPU drivers do not directly communicate \ \with each other, the task of state coordination in \ \Barrelfish is mostly handled by Monitors. Monitors are \ \also responsible for setting up inter-core communication \ \channels (``binding''), and transferring capabilities \ \between cores. When a capability is retyped or revoked, \ \the monitors are responsible for ensuring that this \ \occurs consistently system-wide. The monitor for a core \ \holds a special capability (the kernel capability) which \ \allows it to manipulate certain data structures in the \ \CPU driver, such as the capability database.", Entry "User-level Message Passing" [ "UMP", "CC-UMP" ] "A series of Interconnect Drivers which use \ \cache-coherent shared memory to send cache-line \ \sized frames between cores. UMP is based on ideas \ \from URPC, and avoids kernel transitions on message \ \send and receive. It is the preferred channel for \ \communication between cores on an Intel-architecture \ \PC, for example. However, because it operates \ \entirely in user space, it cannot send capabilities \ \between cores. Instead, the Flounder stubs for UMP \ \send capabilities via another channel through LMP to \ \the local monitor, which forwards them correctly to \ \the destination.", Entry "capability" [ "cap" ] "Barrelfish uses ``partitioned capabilities'' to refer to \ \most OS resources (most of which are actually typed areas \ \of memory). Operations on such resources are typically \ \carried out ``invoking'' an operation on the capability \ \via a system call to the local CPU driver. Capabilities \ \are fixed-size data structures which are held in areas of \ \memory called CNodes, and which cannot be directly read \ \from or written to by user mode programs. Instead, users \ \move capabilities between CNodes by invoking operations \ \on the capability that refers to the CNode. Capabilities \ \can be ``retyped'' and progressively refined from pure \ \memory capabilities to ones which can be mapped into an \ \address space, for example, or used as CNodes. The set \ \of capability types understood by Barrelfish is defined \ \using the Hamlet language.", Entry "physical address capability" [] "A capability referring to a raw region of physical \ \address space. This is the most basic type of \ \capability; all other capability types which refer to \ \memory are ultimately subtypes of this.", Entry "RAM capability" [] "A capability type which refers to a region of Random \ \Access Memory. A direct subtype of a Physical Address \ \capability.", Entry "device frame capability" [] "A capability type which refers to a region of physical \ \address space containing memory-mapped I/O registers. A \ \direct subtype of a Physical Address capability.", Entry "CNode capability" [] "A capability type referring to a CNode.", Entry "foreign capability" [] "A capability referring to a resource which only makes \ \sense on a different core to the one it exists on. For \ \example, since the cspace is purely local to core, \ \transferring a CNode capability to another core \ \transforms it into a Foreign CNode capability, whose only \ \operations are to remotely manipulate (principally copy \ \capabilities from) the original CNode.", Entry "dispatcher capability" [] "A capability referring to the memory region occupied by \ \a Dispatcher Control Block.", Entry "endpoint capability" [] "A capability referring to a (core-local) communication \ \endpoint. Posession of such a capability enables the \ \holder to send a message to endpoint.", Entry "frame capability" [] "A capability refering to a \ \set of page frames which can be mapped into a \ \virtual address space. Frame capabilities are a \ \subtype of RAM capabilities; the latter cannot be \ \mapped.", Entry "kernel capability" [] "A capability enabling the holder to manipulate CPU \ \driver data structures (in particular, the capability \ \database). The kernel capability for a core is only held \ \by the core's monitor.", Entry "vnode capability" [] "One of a set of capability types, one for each format of \ \page table page for each architecture supported by \ \Barrelfish. For example, there are four Vnode capability \ \types for the x86-64 architecture, corresponding to the \ \PML4, PDPT, PDIR, and PTABLE pages in a page table.", Entry "IO capability" [] "A capability enabling the holder to perform IO space \ \operations on Intel architecture machines. Each IO \ \capability grants access to a range of IO space addresses \ \on a specific core.", Entry "capability node" [ "cnode" ] "A region of RAM containing capabilities. A CNode cannot \ \be mapped into a virtual address space, and so can only \ \be accessed by operations on the CNode capability which \ \refers to it -- this is how strict partitioning of \ \capability memory from normal memory is achieved. The \ \set of CNodes which can be referenced by a single \ \dispatcher is called the cspace.", Entry "scheduler manifest" [] "A description of the scheduling requirements of \ \multiprocessor application, used to inform the various \ \system schedulers about how best to dispatch the \ \application's threads.", Entry "dite" [] "A tool used to build a boot image in the proprietary Intel \ \``32.obj'' format, for booting on the Single-chip Cloud \ \Computer.", Entry "Pleco" [] "The Domain Specific Language used in Barrelfish to specify \ \constants for the tracing infrastructure. The Pleco \ \compiler takes such description and outputs a \ \C header file containing the definitions, a C source \ \file with the constants, and a JSON file to be used by \ \host visualization tools.", Entry "Beehive" [] "Beehive was an experimental soft-core processor \ \designed by Chuck Thacker at Microsoft Research Silicon \ \Valley. Beehive was implemented in a simulator and on \ \FPGAs, in particular the BEE3 processor emulation board \ \(which could run up to 15 Beehive cores at a time). \ \The architecture had a number of unusual features, in \ \particular, a ring interconnect for message passing, a \ \software-visible FIFO on each core for incoming messages, \ \and a memory system implemented using message passing \ \(loads and stores became RPCs to the memory system). \ \Barrelfish was ported to the Beehive processor but \ \support for the architecture was eventually dropped \ \after the Beehive project completed.", Entry "BSP Core" [] "Refers to the bootstrap processor, meaning the first \ \processor that is usually booted by the boot-loader or firmware on a hardware \ \architecture.", Entry "APP Core" [] "Application processor, processors booted either by the BSP \ \or other APP cores and not the initial boot-loader or firmware.", Entry "Domain" [] "The word domain is used to refer to the user-level \ \code sharing a protection domain and (usually) an address space. \ \A domain consists of one or more dispatchers.", Entry "Channel" [] "A uni-directional kernel-mediated communication path \ \between dispatchers. All messages travel over channels. Holding a \ \capability for a channel guarantees the right to send a message to it \ \(although the message may not be sent for reasons other than \ \protection).", Entry "Mapping Database" [] "The mapping database is used to facilitate retype and revoke operations. \ \A capability that is not of type dispatcher, can only be retyped once. \ \The mapping database facilitates this check. \ \When a capability is revoked, all its descendants and copies are deleted. \ \The mapping database keeps track of descendants and copies of a capability \ \allowing for proper execution of a revoke operation. \ \Each core has a single private mapping database. \ \All capabilities on the core must be included in the database.", Entry "Descendant" [] "A capability X is a descendant of a capability A if: \ \X was retyped from A, \ \or X is a descendant of A1 and A1 is a copy of A, \ \or X is a descendant of B and B is a descendant of A, \ \or X is a copy of X1 and X1 is a descendant of A.", Entry "Ancestor" [] "A capability A is an ancestor of a capability X if X is a descendant of A.", Entry "ZZZ terms yet to be added" [] "asmoffsets, retype, iref" ] compare_entry :: Entry -> Entry -> Ordering compare_entry (Entry k1 _ _) (Entry k2 _ _) = compare (map Data.Char.toLower k1) (map Data.Char.toLower k2) format_glossary :: [Entry] -> String format_glossary gl = let full_gl = gl ++ (expand_aliases gl) sort_gl = sortBy compare_entry full_gl in unlines [ format_entry e | e <- sort_gl ] format_entry :: Entry -> String format_entry (Entry title aliases description) = printf "\\item[%s:] %s\n" (format_aliases title aliases) description format_aliases :: String -> [String] -> String format_aliases t [] = t format_aliases t al = printf "%s \\textrm{\\textit{(%s)}}" t (concat $ intersperse ", " al) expand_aliases :: [Entry] -> [Entry] expand_aliases el = let expand_alias (Entry name alist _) = [ Entry a [] ("See \\textit{" ++ name ++ "}.") | a <- alist ] in nub $ concat [ expand_alias e | e <- el ] main :: IO () main = do hPutStrLn stdout $ format_glossary glossary exitWith ExitSuccess
BarrelfishOS/barrelfish
doc/001-glossary/Main.hs
mit
24,650
0
13
8,200
1,095
565
530
140
1
-- The University of New Mexico's Haskell Image Processing Library -- Copyright (C) 2013 Joseph Collard -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. {-# LANGUAGE TypeFamilies, ViewPatterns, FlexibleContexts #-} module Data.Image.IO(DisplayFormat(..), GrayPixel(..), RGBPixel(..), writeImage, toPGM, toPPM) where import Data.Image.Internal --base>=4 import Data.List(intercalate) -- | A DisplayFormat for writing to a file class DisplayFormat df where format :: df -> String -- | GrayPixels will be converted using this class class RealFrac (GrayVal px) => GrayPixel px where type GrayVal px :: * toGray :: px -> GrayVal px -- | RGBPixels will be converted using this class class RealFrac (ColorVal px) => RGBPixel px where type ColorVal px :: * toRGB :: px -> (ColorVal px, ColorVal px, ColorVal px) -- Converts an image into a PGM string -- | Converts an image an ASCII PPM scaled between pixel values of 0 and 255 toPGM :: (Image img, GrayPixel (Pixel img)) => img -> [Char] toPGM img@(dimensions -> (rows, cols)) = "P2 " ++ (show cols) ++ " " ++ (show rows) ++ " 255 " ++ px where px = intercalate " " . map (show . round . (*scale) . (flip (-) min)) $ pixels pixels = map toGray . pixelList $ img min = (minimum (0:pixels)) max = maximum pixels scale = 255 / (max - min) -- | Converts an image to an ASCII PPM scaled between pixel values of 0 and 255 toPPM :: (Image img, RGBPixel (Pixel img)) => img -> [Char] toPPM img@(dimensions -> (rows, cols)) = "P3 " ++ (show cols) ++ " " ++ (show rows) ++ " 255 " ++ px where px = intercalate " " rgbs rgbs = map (showRGB . scaleRGB) pixels pixels = map toRGB . pixelList $ img min = comp 0 min' pixels max = comp (-10e10) max' pixels scale = 255 / (max - min) scaleRGB (r, g, b) = (scale*(r-min), scale*(g-min), scale*(b-min)) showRGB (r, g, b) = (show . round $ r) ++ " " ++ (show . floor $ g) ++ " " ++ (show . floor $ b) min' :: RealFrac a => a -> a -> a min' = comp' (<) max' :: RealFrac a => a -> a -> a max' = comp' (>) comp' :: RealFrac a => (a -> a -> Bool) -> a -> a -> a comp' f d0 d1 | f d0 d1 = d0 | otherwise = d1 comp :: RealFrac a => a -> (a -> a -> a) -> [(a, a, a)] -> a comp seed f = compare' (seed,seed,seed) where compare' (r,g,b) [] = foldr1 f [r,g,b] compare' (r,g,b) ((r',g',b'):xs) = compare' (f r r', f g g', f b b') xs {-| Given a file name and a formatable image, writes the image to that file with the format. >>>frog <- readImage "images/frog.pgm" >>>writeImage "transposeFrog.pgm" (transpose frog) <https://raw.github.com/jcollard/unm-hip/master/examples/frog.jpg> <https://raw.github.com/jcollard/unm-hip/master/examples/transposefrog.jpg> >>>cacti <- readColorImage "images/cacti.ppm" >>>writeImage "inverseCacti.ppm" (imageMap (*(-1)) cacti) <https://raw.github.com/jcollard/unm-hip/master/examples/cacti.jpg> <https://raw.github.com/jcollard/unm-hip/master/examples/inversecacti.jpg> -} writeImage :: (DisplayFormat df) => FilePath -> df -> IO () writeImage file = writeFile file . format
jcollard/unm-hip
Data/Image/IO.hs
gpl-3.0
3,852
0
13
896
1,034
570
464
50
2
-- | Support for running propellor, as built outside a docker container, -- inside the container. -- -- Note: This is currently Debian specific, due to glibcLibs. module Propellor.Property.Docker.Shim (setup, cleanEnv, file) where import Propellor import Utility.LinuxMkLibs import Utility.SafeCommand import Utility.Path import Utility.FileMode import Data.List import System.Posix.Files -- | Sets up a shimmed version of the program, in a directory, and -- returns its path. setup :: FilePath -> FilePath -> IO FilePath setup propellorbin dest = do createDirectoryIfMissing True dest libs <- parseLdd <$> readProcess "ldd" [propellorbin] glibclibs <- glibcLibs let libs' = nub $ libs ++ glibclibs libdirs <- map (dest ++) . nub . catMaybes <$> mapM (installLib installFile dest) libs' let linker = (dest ++) $ fromMaybe (error "cannot find ld-linux linker") $ headMaybe $ filter ("ld-linux" `isInfixOf`) libs' let gconvdir = (dest ++) $ parentDir $ fromMaybe (error "cannot find gconv directory") $ headMaybe $ filter ("/gconv/" `isInfixOf`) glibclibs let linkerparams = ["--library-path", intercalate ":" libdirs ] let shim = file propellorbin dest writeFile shim $ unlines [ "#!/bin/sh" , "GCONV_PATH=" ++ shellEscape gconvdir , "export GCONV_PATH" , "exec " ++ unwords (map shellEscape $ linker : linkerparams) ++ " " ++ shellEscape propellorbin ++ " \"$@\"" ] modifyFileMode shim (addModes executeModes) return shim cleanEnv :: IO () cleanEnv = void $ unsetEnv "GCONV_PATH" file :: FilePath -> FilePath -> FilePath file propellorbin dest = dest </> takeFileName propellorbin installFile :: FilePath -> FilePath -> IO () installFile top f = do createDirectoryIfMissing True destdir nukeFile dest createLink f dest `catchIO` (const copy) where copy = void $ boolSystem "cp" [Param "-a", Param f, Param dest] destdir = inTop top $ parentDir f dest = inTop top f
abailly/propellor-test2
src/Propellor/Property/Docker/Shim.hs
bsd-2-clause
1,922
17
18
340
581
295
286
44
1
module Main where ------------------------------------------------------------------------ -- Imports ------------------------------------------------------------------------ import Prelude hiding (head, take, drop, takeWhile, dropWhile, break, span, length, map) import Data.Monoid (Monoid (..)) import qualified Data.List as List import Data.Iteratee.List import Control.Monad.Identity import Test.QuickCheck ------------------------------------------------------------------------ -- Utilities ------------------------------------------------------------------------ run' :: Identity (Iteratee s Identity a) -> a run' = runIdentity . run . runIdentity enum' = enumChunk 3 ------------------------------------------------------------------------ -- Basic ------------------------------------------------------------------------ prop_const :: Eq a => a -> String -> Bool prop_const x xs = const x xs == run' (enum' xs (return x)) prop_id :: Eq a => [a] -> Bool prop_id xs = id xs == run' (enum' xs ident) prop_length :: Eq a => [a] -> Bool prop_length xs = List.length xs == run' (enum' xs length) prop_drop :: Eq a => Int -> [a] -> Bool prop_drop n xs = List.drop n xs == run' (enum' xs (drop n >> ident)) p_dropWhile :: Eq a => (a -> Bool) -> [a] -> Bool p_dropWhile p xs = List.dropWhile p xs == run' (enum' xs (dropWhile p >> ident)) prop_dropWhile :: Eq a => a -> [a] -> Bool prop_dropWhile x = p_dropWhile (==x) --prop_dropWhile1 = p_dropWhile (const True) --prop_dropWhile2 = p_dropWhile (const False) p_break :: Eq a => (a -> Bool) -> [a] -> Bool p_break p xs = fst (List.break p xs) == run' (enum' xs (break p)) prop_break :: Eq a => a -> [a] -> Bool prop_break x = p_break (==x) --prop_break1 = p_break (const True) --prop_break2 = p_break (const False) p_span :: Eq a => (a -> Bool) -> [a] -> Bool p_span p xs = fst (List.span p xs) == run' (enum' xs (span p)) prop_span :: Eq a => a -> [a] -> Bool prop_span x = p_span (==x) --prop_span1 = p_span (const True) --prop_span2 = p_span (const False) prop_take :: Eq a => Int -> [a] -> Bool prop_take n xs = List.take n xs == run' (enum' xs (take n)) ------------------------------------------------------------------------------ -- Enumerators ------------------------------------------------------------------------------ p_enum :: (Eq a) => Iteratee [a] Identity [a] -> [a] -> Bool p_enum iter xs = run' (enum xs iter) == run' (enum' xs iter) prop_enum_take :: Int -> String -> Bool prop_enum_take n xs = run' (enum' xs (take n)) == runIdentity (run =<< run =<< enum' xs (enumTake n ident))
tanimoto/iteratee
tests/checks.hs
bsd-3-clause
2,638
0
11
466
890
468
422
66
1
{-# LANGUAGE FlexibleContexts #-} ----------------------------------------------------------------------------- -- | -- Module : Diagrams.TwoD.Layout.CirclePacking -- Copyright : (c) 2012 Joachim Breitner -- License : BSD-style (see LICENSE) -- Maintainer : [email protected] -- -- A method for laying out diagrams using a circle packing algorithm. For -- details on the algorithm, see "Optimisation.CirclePacking" in the module -- circle-packing. -- -- Here is an example: -- -- > import Optimisation.CirclePacking -- > import Diagrams.TwoD.Vector (e) -- > -- > colorize = zipWith fc $ -- > cycle [red,blue,yellow,magenta,cyan,bisque,firebrick,indigo] -- > -- > objects = colorize $ -- > [ circle r | r <- [0.1,0.2..1.6] ] ++ -- > [ hexagon r | r <- [0.1,0.2..0.7] ] ++ -- > [ decagon r | r <- [0.1,0.2..0.7] ] -- > -- > -- Just a approximation, diagram objects do not have an exact radius -- > radiusApproximation o = maximum [ radius (e (alpha @@ turn)) o | alpha <- [0,0.1..1.0]] -- > -- > circlePackingExample = -- > position $ map (\(o,(x,y)) -> (p2 (x,y),o)) $ -- > packCircles radiusApproximation objects -- -- <<diagrams/src_Diagrams_TwoD_Layout_CirclePacking_circlePackingExample.svg#diagram=circlePackingExample&width=400>> module Diagrams.TwoD.Layout.CirclePacking ( renderCirclePacking , createCirclePacking , RadiusFunction , approxRadius , circleRadius ) where import Optimisation.CirclePacking import Diagrams.Core.Envelope import Diagrams.Prelude import Diagrams.TwoD.Vector (e) -- | Combines the passed objects, whose radius is estimated using the given -- 'RadiusFunction', so that they do not overlap (according to the radius -- function) and otherwise form, as far as possible, a tight circle. renderCirclePacking :: (Monoid' m, Floating (N b), Ord (N b)) => RadiusFunction b m -> [QDiagram b V2 (N b) m] -> QDiagram b V2 (N b) m renderCirclePacking radiusFunc = createCirclePacking radiusFunc id toFractional :: (Real a, Fractional b) => a -> b toFractional = fromRational . toRational -- | More general version of 'renderCirclePacking'. You can use this if you -- have more information available in the values of type @a@ that allows you to -- calculate the radius better (or even exactly). createCirclePacking :: (Monoid' m, Ord (N b), Floating (N b)) => (a -> Double) -> (a -> QDiagram b V2 (N b) m) -> [a] -> QDiagram b V2 (N b) m createCirclePacking radiusFunc diagramFunc = position . map (\(o,(x,y)) -> (p2 (toFractional x, toFractional y), diagramFunc o)) . packCircles radiusFunc -- | The type of radius-estimating functions for Diagrams such as -- 'approxRadius' and 'circleRadius'. When you can calculate the radius better, -- but not any more once you converted your data to a diagram, use 'createCirclePacking'. type RadiusFunction b m = QDiagram b V2 (N b) m -> Double -- | A safe approximation. Calculates the outer radius of the smallest -- axis-aligned polygon with the given number of edges that contains the -- object. A parameter of 4 up to 8 should be sufficient for most applications. approxRadius :: (Monoid' m, Floating (N b), Real (N b), Ord (N b)) => Int -> RadiusFunction b m approxRadius n = if n < 3 then error "circleRadius: n needs to be at least 3" else \o -> outByIn * maximum [ toFractional (envelopeS (e alpha) o) | i <- [1..n] , let alpha = (fromIntegral i + 0.5) / fromIntegral n @@ turn ] -- incircle radius: a / (2 * tan (tau/n)) -- outcircle radius: a / (2 * sin (tau /n)) -- hence factor is : out/in = tan (tau/n) / sin (tau/n) where outByIn = Prelude.tan (pi / (2 * fromIntegral n)) / sin (pi / (2 * fromIntegral n)) -- -- | An unsafe approximation. This is the radius of the largest circle that -- fits in the rectangular bounding box of the object, so it may be too small. -- It is, however, exact for circles, and there is no function that is safe for -- all diagrams and exact for circles. circleRadius :: (Monoid' m, Floating (N b), Real (N b)) => RadiusFunction b m circleRadius o = toFractional $ maximum [ envelopeS (e (alpha @@ turn)) o | alpha <- [0,0.25,0.5,0.75]]
kuribas/diagrams-contrib
src/Diagrams/TwoD/Layout/CirclePacking.hs
bsd-3-clause
4,305
0
18
923
737
413
324
31
2
{- ProcessRing benchmarks. To run the benchmarks, select a value for the ring size (sz) and the number of times to send a message around the ring -} import Control.Monad import Control.Distributed.Process hiding (catch) import Control.Distributed.Process.Node import Control.Exception (catch, SomeException) import Network.Transport.TCP (createTransport, defaultTCPParameters) import System.Environment import System.Console.GetOpt data Options = Options { optRingSize :: Int , optIterations :: Int , optForward :: Bool , optParallel :: Bool , optUnsafe :: Bool } deriving Show initialProcess :: Options -> Process () initialProcess op = let ringSz = optRingSize op msgCnt = optIterations op fwd = optForward op unsafe = optUnsafe op msg = ("foobar", "baz") in do self <- getSelfPid ring <- makeRing fwd unsafe ringSz self forM_ [1..msgCnt] (\_ -> send ring msg) collect msgCnt where relay fsend pid = do msg <- expect :: Process (String, String) fsend pid msg relay fsend pid forward' pid = receiveWait [ matchAny (\m -> forward m pid) ] >> forward' pid makeRing :: Bool -> Bool -> Int -> ProcessId -> Process ProcessId makeRing !f !u !n !pid | n == 0 = go f u pid | otherwise = go f u pid >>= makeRing f u (n - 1) go :: Bool -> Bool -> ProcessId -> Process ProcessId go False False next = spawnLocal $ relay send next go False True next = spawnLocal $ relay unsafeSend next go True _ next = spawnLocal $ forward' next collect :: Int -> Process () collect !n | n == 0 = return () | otherwise = do receiveWait [ matchIf (\(a, b) -> a == "foobar" && b == "baz") (\_ -> return ()) , matchAny (\_ -> error "unexpected input!") ] collect (n - 1) defaultOptions :: Options defaultOptions = Options { optRingSize = 10 , optIterations = 100 , optForward = False , optParallel = False , optUnsafe = False } options :: [OptDescr (Options -> Options)] options = [ Option ['s'] ["ring-size"] (OptArg optSz "SIZE") "# of processes in ring" , Option ['i'] ["iterations"] (OptArg optMsgCnt "ITER") "# of times to send" , Option ['f'] ["forward"] (NoArg (\opts -> opts { optForward = True })) "use `forward' instead of send - default = False" , Option ['u'] ["unsafe-send"] (NoArg (\opts -> opts { optUnsafe = True })) "use 'unsafeSend' (ignored with -f) - default = False" , Option ['p'] ["parallel"] (NoArg (\opts -> opts { optParallel = True })) "send in parallel and consume sequentially - default = False" ] optMsgCnt :: Maybe String -> Options -> Options optMsgCnt Nothing opts = opts optMsgCnt (Just c) opts = opts { optIterations = ((read c) :: Int) } optSz :: Maybe String -> Options -> Options optSz Nothing opts = opts optSz (Just s) opts = opts { optRingSize = ((read s) :: Int) } parseArgv :: [String] -> IO (Options, [String]) parseArgv argv = do pn <- getProgName case getOpt Permute options argv of (o,n,[] ) -> return (foldl (flip id) defaultOptions o, n) (_,_,errs) -> ioError (userError (concat errs ++ usageInfo (header pn) options)) where header pn' = "Usage: " ++ pn' ++ " [OPTION...]" main :: IO () main = do argv <- getArgs (opt, _) <- parseArgv argv putStrLn $ "options: " ++ (show opt) Right transport <- createTransport "127.0.0.1" "8090" defaultTCPParameters node <- newLocalNode transport initRemoteTable catch (void $ runProcess node $ initialProcess opt) (\(e :: SomeException) -> putStrLn $ "ERROR: " ++ (show e))
hackern/network-transport-ivc
benchmarks/ProcessRing.hs
mit
3,841
97
14
1,083
1,225
656
569
-1
-1
module Sortier.Programm.Merge_Insertion where import Sortier.Programm.Type import Autolib.TES.Identifier type Stack = [ Identifier ] sort :: [ Stack ] -> [ Statement ] sort xs | length xs < 2 = [] sort xs = let ( ps, rest ) = pairs xs mkpairs = do [ y, x ] <- ps return $ If_Greater_Else ( head x ) ( head y ) ( Sequence $ swaps x y ) ( Sequence [] ) in mkpairs ++ sort ps ++ insertions ps rest insertions ps rest = pairs [] = ( [], [] ) pairs [x] = ( [], [x] ) pairs x : y : zs = let ( ps, rest ) = pairs zs in ( [y,x] : ps, rest ) -- | result is in x : ys (ascending) insert :: Stack -> [ Stack ] -> [ Statement ] insert x [] = [] insert x ys = let ( pre, mid : post ) = splitAt ( length ys `div` 2 ) ys ripple = do ( x, y ) <- zip (x : pre) ( pre ++ [mid] ) swaps x y in return $ If_Greater_Else ( head x ) ( head mid ) ( Sequence $ ripple ++ insert mid post ) ( Sequence $ insert x pre ) swaps x y = do ( xx, yy ) <- zip x y return $ Swap xx yy
florianpilz/autotool
src/Sortier/Programm/Merge_Insertion.hs
gpl-2.0
1,187
2
15
471
508
262
246
-1
-1
----------------------------------------------------------------------------------------- {-| Module : HaskellNames Copyright : (c) Daan Leijen 2003 License : BSD-style Maintainer : [email protected] Stability : provisional Portability : portable Utility module to create Haskell compatible names. -} ----------------------------------------------------------------------------------------- module HaskellNames( haskellDeclName , haskellName, haskellTypeName, haskellUnBuiltinTypeName , haskellUnderscoreName, haskellArgName , isBuiltin , getPrologue ) where import qualified Data.Set as Set import Data.Char( toLower, toUpper, isLower, isUpper ) import Data.List( isPrefixOf ) {----------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------} builtinObjects :: Set.Set String builtinObjects = Set.fromList ["wxColour","wxString"] {- [ "Bitmap" , "Brush" , "Colour" , "Cursor" , "DateTime" , "Icon" , "Font" , "FontData" , "ListItem" , "PageSetupData" , "Pen" , "PrintData" , "PrintDialogData" , "TreeItemId" ] -} reservedVarNames :: Set.Set String reservedVarNames = Set.fromList ["data" ,"int" ,"init" ,"module" ,"raise" ,"type" ,"objectDelete" ] reservedTypeNames :: Set.Set String reservedTypeNames = Set.fromList [ "Object" , "Managed" , "ManagedPtr" , "Array" , "Date" , "Dir" , "DllLoader" , "Expr" , "File" , "Point" , "Size" , "String" , "Rect" ] {----------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------} haskellDeclName :: String -> String haskellDeclName name | isPrefixOf "wxMDI" name = haskellName ("mdi" ++ drop 5 name) | isPrefixOf "wxDC_" name = haskellName ("dc" ++ drop 5 name) | isPrefixOf "wxGL" name = haskellName ("gl" ++ drop 4 name) | isPrefixOf "wxSVG" name = haskellName ("svg" ++ drop 5 name) | isPrefixOf "expEVT_" name = ("wxEVT_" ++ drop 7 name) -- keep underscores | isPrefixOf "exp" name = ("wx" ++ drop 3 name) | isPrefixOf "wxc" name = haskellName name | isPrefixOf "wx" name = haskellName (drop 2 name) | isPrefixOf "ELJ" name = haskellName ("wxc" ++ drop 3 name) | isPrefixOf "DDE" name = haskellName ("dde" ++ drop 3 name) | otherwise = haskellName name haskellArgName :: String -> String haskellArgName name = haskellName (dropWhile (=='_') name) haskellName :: String -> String haskellName name | Set.member suggested reservedVarNames = "wx" ++ suggested | otherwise = suggested where suggested = case name of (c:cs) -> toLower c : filter (/='_') cs [] -> "wx" haskellUnderscoreName :: String -> String haskellUnderscoreName name | Set.member suggested reservedVarNames = "wx" ++ suggested | otherwise = suggested where suggested = case name of ('W':'X':cs) -> "wx" ++ cs (c:cs) -> toLower c : cs [] -> "wx" haskellTypeName :: String -> String haskellTypeName name | isPrefixOf "ELJ" name = haskellTypeName ("WXC" ++ drop 3 name) | Set.member suggested reservedTypeNames = "Wx" ++ suggested | otherwise = suggested where suggested = case name of 'W':'X':'C':cs -> "WXC" ++ cs 'w':'x':'c':cs -> "WXC" ++ cs 'w':'x':cs -> firstUpper cs _ -> firstUpper name firstUpper name' = case name' of c:cs | isLower c -> toUpper c : cs | not (isUpper c) -> "Wx" ++ name' | otherwise -> name' [] -> "Wx" haskellUnBuiltinTypeName :: String -> String haskellUnBuiltinTypeName name | isBuiltin name = haskellTypeName name ++ "Object" | otherwise = haskellTypeName name isBuiltin :: String -> Bool isBuiltin name = Set.member name builtinObjects {----------------------------------------------------------------------------------------- Haddock prologue -----------------------------------------------------------------------------------------} getPrologue :: String -> String -> String -> [String] -> [String] getPrologue moduleName content contains inputFiles = [line ,"{-|" ,"Module : " ++ moduleName ,"Copyright : Copyright (c) Daan Leijen 2003, 2004" ,"License : wxWindows" ,"" ,"Maintainer : [email protected]" ,"Stability : provisional" ,"Portability : portable" ,"" ,"Haskell " ++ content ++ " definitions for the wxWidgets C library (@wxc.dll@)." ,"" ,"Do not edit this file manually!" ,"This file was automatically generated by wxDirect." ] ++ (if (null inputFiles) then [] else (["","From the files:"] ++ concatMap showFile inputFiles)) ++ ["" ,"And contains " ++ contains ,"-}" ,line ] where line = replicate 80 '-' showFile fname = [""," * @" ++ removeDirName fname ++ "@"] removeDirName = reverse . takeWhile (/= '\\') . takeWhile (/= '/') . reverse {- escapeSlash c | c == '/' = "\\/" | c == '\"' = "\\\"" | otherwise = [c] -}
sherwoodwang/wxHaskell
wxdirect/src/HaskellNames.hs
lgpl-2.1
5,733
0
15
1,617
1,245
639
606
123
5
{-@ LIQUID "--no-termination" @-} module RedBlackTree where import Language.Haskell.Liquid.Prelude data RBTree a = Leaf | Node Color a !(RBTree a) !(RBTree a) deriving (Show) data Color = B -- ^ Black | R -- ^ Red deriving (Eq,Show) --------------------------------------------------------------------------- -- | Add an element ------------------------------------------------------- --------------------------------------------------------------------------- {-@ add :: (Ord a) => a -> RBT a -> RBT a @-} add x s = makeBlack (ins x s) {-@ ins :: (Ord a) => a -> t:RBT a -> {v: ARBTN a {(bh t)} | ((IsB t) => (isRB v))} @-} ins kx Leaf = Node R kx Leaf Leaf ins kx s@(Node B x l r) = case compare kx x of LT -> let t = lbal x (ins kx l) r in t GT -> let t = rbal x l (ins kx r) in t EQ -> s ins kx s@(Node R x l r) = case compare kx x of LT -> Node R x (ins kx l) r GT -> Node R x l (ins kx r) EQ -> s --------------------------------------------------------------------------- -- | Delete an element ---------------------------------------------------- --------------------------------------------------------------------------- {-@ remove :: (Ord a) => a -> RBT a -> RBT a @-} remove x t = makeBlack (del x t) {-@ predicate HDel T V = (bh V) = (if (isB T) then (bh T) - 1 else (bh T)) @-} {-@ del :: (Ord a) => a -> t:RBT a -> {v:ARBT a | ((HDel t v) && ((isB t) || (isRB v)))} @-} del x Leaf = Leaf del x (Node _ y a b) = case compare x y of EQ -> append y a b LT -> case a of Leaf -> Node R y Leaf b Node B _ _ _ -> lbalS y (del x a) b _ -> let t = Node R y (del x a) b in t GT -> case b of Leaf -> Node R y a Leaf Node B _ _ _ -> rbalS y a (del x b) _ -> Node R y a (del x b) {-@ append :: y:a -> l:RBT a -> r:RBTN a {(bh l)} -> (ARBT2 a l r) @-} append :: a -> RBTree a -> RBTree a -> RBTree a append _ Leaf r = r append _ l Leaf = l append piv (Node R lx ll lr) (Node R rx rl rr) = case append piv lr rl of Node R x lr' rl' -> Node R x (Node R lx ll lr') (Node R rx rl' rr) lrl -> Node R lx ll (Node R rx lrl rr) append piv (Node B lx ll lr) (Node B rx rl rr) = case append piv lr rl of Node R x lr' rl' -> Node R x (Node B lx ll lr') (Node B rx rl' rr) lrl -> lbalS lx ll (Node B rx lrl rr) append piv l@(Node B _ _ _) (Node R rx rl rr) = Node R rx (append piv l rl) rr append piv l@(Node R lx ll lr) r@(Node B _ _ _) = Node R lx ll (append piv lr r) --------------------------------------------------------------------------- -- | Delete Minimum Element ----------------------------------------------- --------------------------------------------------------------------------- {-@ deleteMin :: RBT a -> RBT a @-} deleteMin (Leaf) = Leaf deleteMin (Node _ x l r) = makeBlack t where (_, t) = deleteMin' x l r {-@ deleteMin' :: k:a -> l:RBT a -> r:RBTN a {(bh l)} -> (a, ARBT2 a l r) @-} deleteMin' k Leaf r = (k, r) deleteMin' x (Node R lx ll lr) r = (k, Node R x l' r) where (k, l') = deleteMin' lx ll lr deleteMin' x (Node B lx ll lr) r = (k, lbalS x l' r ) where (k, l') = deleteMin' lx ll lr --------------------------------------------------------------------------- -- | Rotations ------------------------------------------------------------ --------------------------------------------------------------------------- {-@ lbalS :: k:a -> l:ARBT a -> r:RBTN a {1 + (bh l)} -> {v: ARBTN a {1 + (bh l)} | ((IsB r) => (isRB v))} @-} lbalS k (Node R x a b) r = Node R k (Node B x a b) r lbalS k l (Node B y a b) = let t = rbal k l (Node R y a b) in t lbalS k l (Node R z (Node B y a b) c) = Node R y (Node B k l a) (rbal z b (makeRed c)) lbalS k l r = liquidError "nein" -- Node R l k r {-@ rbalS :: k:a -> l:RBT a -> r:ARBTN a {(bh l) - 1} -> {v: ARBTN a {(bh l)} | ((IsB l) => (isRB v))} @-} rbalS k l (Node R y b c) = Node R k l (Node B y b c) rbalS k (Node B x a b) r = let t = lbal k (Node R x a b) r in t rbalS k (Node R x a (Node B y b c)) r = Node R y (lbal x (makeRed a) b) (Node B k c r) rbalS k l r = liquidError "nein" -- Node R l k r {-@ lbal :: k:a -> l:ARBT a -> RBTN a {(bh l)} -> RBTN a {1 + (bh l)} @-} lbal k (Node R y (Node R x a b) c) r = Node R y (Node B x a b) (Node B k c r) lbal k (Node R x a (Node R y b c)) r = Node R y (Node B x a b) (Node B k c r) lbal k l r = Node B k l r {-@ rbal :: k:a -> l:RBT a -> ARBTN a {(bh l)} -> RBTN a {1 + (bh l)} @-} rbal x a (Node R y b (Node R z c d)) = Node R y (Node B x a b) (Node B z c d) rbal x a (Node R z (Node R y b c) d) = Node R y (Node B x a b) (Node B z c d) rbal x l r = Node B x l r --------------------------------------------------------------------------- --------------------------------------------------------------------------- --------------------------------------------------------------------------- {-@ type BlackRBT a = {v: RBT a | ((IsB v) && (bh v) > 0)} @-} {-@ makeRed :: l:BlackRBT a -> ARBTN a {(bh l) - 1} @-} makeRed (Node _ x l r) = Node R x l r makeRed Leaf = liquidError "nein" {-@ makeBlack :: ARBT a -> RBT a @-} makeBlack Leaf = Leaf makeBlack (Node _ x l r) = Node B x l r --------------------------------------------------------------------------- -- | Specifications ------------------------------------------------------- --------------------------------------------------------------------------- -- | Red-Black Trees {-@ type RBT a = {v: RBTree a | ((isRB v) && (isBH v)) } @-} {-@ type RBTN a N = {v: (RBT a) | (bh v) = N } @-} {-@ measure isRB :: RBTree a -> Prop isRB (Leaf) = true isRB (Node c x l r) = ((isRB l) && (isRB r) && ((c == R) => ((IsB l) && (IsB r)))) @-} -- | Almost Red-Black Trees {-@ type ARBT a = {v: RBTree a | ((isARB v) && (isBH v))} @-} {-@ type ARBTN a N = {v: ARBT a | (bh v) = N } @-} {-@ measure isARB :: (RBTree a) -> Prop isARB (Leaf) = true isARB (Node c x l r) = ((isRB l) && (isRB r)) @-} -- | Conditionally Red-Black Tree {-@ type ARBT2 a L R = {v:ARBTN a {(bh L)} | (((IsB L) && (IsB R)) => (isRB v))} @-} -- | Color of a tree {-@ measure col :: RBTree a -> Color col (Node c x l r) = c col (Leaf) = B @-} {-@ measure isB :: RBTree a -> Prop isB (Leaf) = false isB (Node c x l r) = c == B @-} {-@ predicate IsB T = not ((col T) == R) @-} -- | Black Height {-@ measure isBH :: RBTree a -> Prop isBH (Leaf) = true isBH (Node c x l r) = ((isBH l) && (isBH r) && (bh l) = (bh r)) @-} {-@ measure bh :: RBTree a -> Int bh (Leaf) = 0 bh (Node c x l r) = (bh l) + (if (c == R) then 0 else 1) @-} ------------------------------------------------------------------------------- -- Auxiliary Invariants ------------------------------------------------------- ------------------------------------------------------------------------------- {-@ predicate Invs V = ((Inv1 V) && (Inv2 V) && (Inv3 V)) @-} {-@ predicate Inv1 V = (((isARB V) && (IsB V)) => (isRB V)) @-} {-@ predicate Inv2 V = ((isRB V) => (isARB V)) @-} {-@ predicate Inv3 V = 0 <= (bh V) @-} {-@ invariant {v: Color | (v = R || v = B)} @-} {-@ invariant {v: RBTree a | (Invs v)} @-} {-@ inv :: RBTree a -> {v:RBTree a | (Invs v)} @-} inv Leaf = Leaf inv (Node c x l r) = Node c x (inv l) (inv r)
ssaavedra/liquidhaskell
tests/pos/RBTree-col-height.hs
bsd-3-clause
8,121
0
17
2,609
2,029
1,031
998
77
7
{-# LANGUAGE OverloadedStrings #-} import Text.LaTeX import Text.LaTeX.Packages.Inputenc import Text.LaTeX.Packages.AMSMath import Data.Ratio import Data.Matrix main :: IO () main = renderFile "texy.tex" example example :: LaTeX example = thePreamble <> document theBody thePreamble :: LaTeX thePreamble = documentclass [] article <> usepackage [utf8] inputenc <> usepackage [] amsmath <> title "Using the Texy Class" <> author "Daniel Díaz" theBody :: LaTeX theBody = maketitle <> "Different types pretty-printed using the " <> texttt "Texy" <> " class:" <> itemize theItems theItems :: LaTeX theItems = item Nothing <> math (texy (2 :: Int ,3 :: Integer)) <> item Nothing <> math (texy [True,False,False]) <> item Nothing <> math (texy (1 % 2 :: Rational,2.5 :: Float)) <> item Nothing <> equation_ (texy $ fromList 3 3 [1 .. 9 :: Int]) <> item Nothing <> math (texy ("This is a String" :: String))
dmcclean/HaTeX
Examples/texy.hs
bsd-3-clause
932
16
10
173
328
168
160
27
1
import StackTest import System.Directory main :: IO () main = do copyFile "orig-stack.yaml" "stack.yaml" stack ["--resolver", "lts-9.14", "solver", "--update-config"] stack ["build"]
anton-dessiatov/stack
test/integration/tests/3533-extra-deps-solver/Main.hs
bsd-3-clause
196
0
8
34
59
30
29
7
1
{-# LANGUAGE CPP, NondecreasingIndentation #-} {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-} ----------------------------------------------------------------------------- -- -- GHC Driver program -- -- (c) The University of Glasgow 2005 -- ----------------------------------------------------------------------------- module Main (main) where -- The official GHC API import qualified GHC import GHC ( -- DynFlags(..), HscTarget(..), -- GhcMode(..), GhcLink(..), Ghc, GhcMonad(..), LoadHowMuch(..) ) import CmdLineParser -- Implementations of the various modes (--show-iface, mkdependHS. etc.) import LoadIface ( showIface ) import HscMain ( newHscEnv ) import DriverPipeline ( oneShot, compileFile ) import DriverMkDepend ( doMkDependHS ) #ifdef GHCI import InteractiveUI ( interactiveUI, ghciWelcomeMsg, defaultGhciSettings ) #endif -- Various other random stuff that we need import Config import Constants import HscTypes import Packages ( pprPackages, pprPackagesSimple, pprModuleMap ) import DriverPhases import BasicTypes ( failed ) import StaticFlags import DynFlags import ErrUtils import FastString import Outputable import SrcLoc import Util import Panic import MonadUtils ( liftIO ) -- Imports for --abi-hash import LoadIface ( loadUserInterface ) import Module ( mkModuleName ) import Finder ( findImportedModule, cannotFindInterface ) import TcRnMonad ( initIfaceCheck ) import Binary ( openBinMem, put_, fingerprintBinMem ) -- Standard Haskell libraries import System.IO import System.Environment import System.Exit import System.FilePath import Control.Monad import Data.Char import Data.List import Data.Maybe ----------------------------------------------------------------------------- -- ToDo: -- time commands when run with -v -- user ways -- Win32 support: proper signal handling -- reading the package configuration file is too slow -- -K<size> ----------------------------------------------------------------------------- -- GHC's command-line interface main :: IO () main = do initGCStatistics -- See Note [-Bsymbolic and hooks] hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering GHC.defaultErrorHandler defaultFatalMessager defaultFlushOut $ do -- 1. extract the -B flag from the args argv0 <- getArgs let (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0 mbMinusB | null minusB_args = Nothing | otherwise = Just (drop 2 (last minusB_args)) let argv1' = map (mkGeneralLocated "on the commandline") argv1 (argv2, staticFlagWarnings) <- parseStaticFlags argv1' -- 2. Parse the "mode" flags (--make, --interactive etc.) (mode, argv3, modeFlagWarnings) <- parseModeFlags argv2 let flagWarnings = staticFlagWarnings ++ modeFlagWarnings -- If all we want to do is something like showing the version number -- then do it now, before we start a GHC session etc. This makes -- getting basic information much more resilient. -- In particular, if we wait until later before giving the version -- number then bootstrapping gets confused, as it tries to find out -- what version of GHC it's using before package.conf exists, so -- starting the session fails. case mode of Left preStartupMode -> do case preStartupMode of ShowSupportedExtensions -> showSupportedExtensions ShowVersion -> showVersion ShowNumVersion -> putStrLn cProjectVersion ShowOptions isInteractive -> showOptions isInteractive Right postStartupMode -> -- start our GHC session GHC.runGhc mbMinusB $ do dflags <- GHC.getSessionDynFlags case postStartupMode of Left preLoadMode -> liftIO $ do case preLoadMode of ShowInfo -> showInfo dflags ShowGhcUsage -> showGhcUsage dflags ShowGhciUsage -> showGhciUsage dflags PrintWithDynFlags f -> putStrLn (f dflags) Right postLoadMode -> main' postLoadMode dflags argv3 flagWarnings main' :: PostLoadMode -> DynFlags -> [Located String] -> [Located String] -> Ghc () main' postLoadMode dflags0 args flagWarnings = do -- set the default GhcMode, HscTarget and GhcLink. The HscTarget -- can be further adjusted on a module by module basis, using only -- the -fvia-C and -fasm flags. If the default HscTarget is not -- HscC or HscAsm, -fvia-C and -fasm have no effect. let dflt_target = hscTarget dflags0 (mode, lang, link) = case postLoadMode of DoInteractive -> (CompManager, HscInterpreted, LinkInMemory) DoEval _ -> (CompManager, HscInterpreted, LinkInMemory) DoMake -> (CompManager, dflt_target, LinkBinary) DoMkDependHS -> (MkDepend, dflt_target, LinkBinary) DoAbiHash -> (OneShot, dflt_target, LinkBinary) _ -> (OneShot, dflt_target, LinkBinary) let dflags1 = case lang of HscInterpreted -> let platform = targetPlatform dflags0 dflags0a = updateWays $ dflags0 { ways = interpWays } dflags0b = foldl gopt_set dflags0a $ concatMap (wayGeneralFlags platform) interpWays dflags0c = foldl gopt_unset dflags0b $ concatMap (wayUnsetGeneralFlags platform) interpWays in dflags0c _ -> dflags0 dflags2 = dflags1{ ghcMode = mode, hscTarget = lang, ghcLink = link, verbosity = case postLoadMode of DoEval _ -> 0 _other -> 1 } -- turn on -fimplicit-import-qualified for GHCi now, so that it -- can be overriden from the command-line -- XXX: this should really be in the interactive DynFlags, but -- we don't set that until later in interactiveUI dflags3 | DoInteractive <- postLoadMode = imp_qual_enabled | DoEval _ <- postLoadMode = imp_qual_enabled | otherwise = dflags2 where imp_qual_enabled = dflags2 `gopt_set` Opt_ImplicitImportQualified -- The rest of the arguments are "dynamic" -- Leftover ones are presumably files (dflags4, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags3 args GHC.prettyPrintGhcErrors dflags4 $ do let flagWarnings' = flagWarnings ++ dynamicFlagWarnings handleSourceError (\e -> do GHC.printException e liftIO $ exitWith (ExitFailure 1)) $ do liftIO $ handleFlagWarnings dflags4 flagWarnings' -- make sure we clean up after ourselves GHC.defaultCleanupHandler dflags4 $ do liftIO $ showBanner postLoadMode dflags4 let -- To simplify the handling of filepaths, we normalise all filepaths right -- away - e.g., for win32 platforms, backslashes are converted -- into forward slashes. normal_fileish_paths = map (normalise . unLoc) fileish_args (srcs, objs) = partition_args normal_fileish_paths [] [] dflags5 = dflags4 { ldInputs = map (FileOption "") objs ++ ldInputs dflags4 } -- we've finished manipulating the DynFlags, update the session _ <- GHC.setSessionDynFlags dflags5 dflags6 <- GHC.getSessionDynFlags hsc_env <- GHC.getSession ---------------- Display configuration ----------- case verbosity dflags6 of v | v == 4 -> liftIO $ dumpPackagesSimple dflags6 | v >= 5 -> liftIO $ dumpPackages dflags6 | otherwise -> return () when (verbosity dflags6 >= 3) $ do liftIO $ hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags) when (dopt Opt_D_dump_mod_map dflags6) . liftIO $ printInfoForUser (dflags6 { pprCols = 200 }) (pkgQual dflags6) (pprModuleMap dflags6) ---------------- Final sanity checking ----------- liftIO $ checkOptions postLoadMode dflags6 srcs objs ---------------- Do the business ----------- handleSourceError (\e -> do GHC.printException e liftIO $ exitWith (ExitFailure 1)) $ do case postLoadMode of ShowInterface f -> liftIO $ doShowIface dflags6 f DoMake -> doMake srcs DoMkDependHS -> doMkDependHS (map fst srcs) StopBefore p -> liftIO (oneShot hsc_env p srcs) DoInteractive -> ghciUI srcs Nothing DoEval exprs -> ghciUI srcs $ Just $ reverse exprs DoAbiHash -> abiHash (map fst srcs) ShowPackages -> liftIO $ showPackages dflags6 liftIO $ dumpFinalStats dflags6 ghciUI :: [(FilePath, Maybe Phase)] -> Maybe [String] -> Ghc () #ifndef GHCI ghciUI _ _ = throwGhcException (CmdLineError "not built for interactive use") #else ghciUI = interactiveUI defaultGhciSettings #endif -- ----------------------------------------------------------------------------- -- Splitting arguments into source files and object files. This is where we -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source -- file indicating the phase specified by the -x option in force, if any. partition_args :: [String] -> [(String, Maybe Phase)] -> [String] -> ([(String, Maybe Phase)], [String]) partition_args [] srcs objs = (reverse srcs, reverse objs) partition_args ("-x":suff:args) srcs objs | "none" <- suff = partition_args args srcs objs | StopLn <- phase = partition_args args srcs (slurp ++ objs) | otherwise = partition_args rest (these_srcs ++ srcs) objs where phase = startPhase suff (slurp,rest) = break (== "-x") args these_srcs = zip slurp (repeat (Just phase)) partition_args (arg:args) srcs objs | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs | otherwise = partition_args args srcs (arg:objs) {- We split out the object files (.o, .dll) and add them to ldInputs for use by the linker. The following things should be considered compilation manager inputs: - haskell source files (strings ending in .hs, .lhs or other haskellish extension), - module names (not forgetting hierarchical module names), - things beginning with '-' are flags that were not recognised by the flag parser, and we want them to generate errors later in checkOptions, so we class them as source files (#5921) - and finally we consider everything not containing a '.' to be a comp manager input, as shorthand for a .hs or .lhs filename. Everything else is considered to be a linker object, and passed straight through to the linker. -} looks_like_an_input :: String -> Bool looks_like_an_input m = isSourceFilename m || looksLikeModuleName m || "-" `isPrefixOf` m || '.' `notElem` m -- ----------------------------------------------------------------------------- -- Option sanity checks -- | Ensure sanity of options. -- -- Throws 'UsageError' or 'CmdLineError' if not. checkOptions :: PostLoadMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO () -- Final sanity checking before kicking off a compilation (pipeline). checkOptions mode dflags srcs objs = do -- Complain about any unknown flags let unknown_opts = [ f | (f@('-':_), _) <- srcs ] when (notNull unknown_opts) (unknownFlagsErr unknown_opts) when (notNull (filter wayRTSOnly (ways dflags)) && isInterpretiveMode mode) $ hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi") -- -prof and --interactive are not a good combination when ((filter (not . wayRTSOnly) (ways dflags) /= interpWays) && isInterpretiveMode mode) $ do throwGhcException (UsageError "--interactive can't be used with -prof or -unreg.") -- -ohi sanity check if (isJust (outputHi dflags) && (isCompManagerMode mode || srcs `lengthExceeds` 1)) then throwGhcException (UsageError "-ohi can only be used when compiling a single source file") else do -- -o sanity checking if (srcs `lengthExceeds` 1 && isJust (outputFile dflags) && not (isLinkMode mode)) then throwGhcException (UsageError "can't apply -o to multiple source files") else do let not_linking = not (isLinkMode mode) || isNoLink (ghcLink dflags) when (not_linking && not (null objs)) $ hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs) -- Check that there are some input files -- (except in the interactive case) if null srcs && (null objs || not_linking) && needsInputsMode mode then throwGhcException (UsageError "no input files") else do -- Verify that output files point somewhere sensible. verifyOutputFiles dflags -- Compiler output options -- Called to verify that the output files point somewhere valid. -- -- The assumption is that the directory portion of these output -- options will have to exist by the time 'verifyOutputFiles' -- is invoked. -- -- We create the directories for -odir, -hidir, -outputdir etc. ourselves if -- they don't exist, so don't check for those here (#2278). verifyOutputFiles :: DynFlags -> IO () verifyOutputFiles dflags = do let ofile = outputFile dflags when (isJust ofile) $ do let fn = fromJust ofile flg <- doesDirNameExist fn when (not flg) (nonExistentDir "-o" fn) let ohi = outputHi dflags when (isJust ohi) $ do let hi = fromJust ohi flg <- doesDirNameExist hi when (not flg) (nonExistentDir "-ohi" hi) where nonExistentDir flg dir = throwGhcException (CmdLineError ("error: directory portion of " ++ show dir ++ " does not exist (used with " ++ show flg ++ " option.)")) ----------------------------------------------------------------------------- -- GHC modes of operation type Mode = Either PreStartupMode PostStartupMode type PostStartupMode = Either PreLoadMode PostLoadMode data PreStartupMode = ShowVersion -- ghc -V/--version | ShowNumVersion -- ghc --numeric-version | ShowSupportedExtensions -- ghc --supported-extensions | ShowOptions Bool {- isInteractive -} -- ghc --show-options showVersionMode, showNumVersionMode, showSupportedExtensionsMode, showOptionsMode :: Mode showVersionMode = mkPreStartupMode ShowVersion showNumVersionMode = mkPreStartupMode ShowNumVersion showSupportedExtensionsMode = mkPreStartupMode ShowSupportedExtensions showOptionsMode = mkPreStartupMode (ShowOptions False) mkPreStartupMode :: PreStartupMode -> Mode mkPreStartupMode = Left isShowVersionMode :: Mode -> Bool isShowVersionMode (Left ShowVersion) = True isShowVersionMode _ = False isShowNumVersionMode :: Mode -> Bool isShowNumVersionMode (Left ShowNumVersion) = True isShowNumVersionMode _ = False data PreLoadMode = ShowGhcUsage -- ghc -? | ShowGhciUsage -- ghci -? | ShowInfo -- ghc --info | PrintWithDynFlags (DynFlags -> String) -- ghc --print-foo showGhcUsageMode, showGhciUsageMode, showInfoMode :: Mode showGhcUsageMode = mkPreLoadMode ShowGhcUsage showGhciUsageMode = mkPreLoadMode ShowGhciUsage showInfoMode = mkPreLoadMode ShowInfo printSetting :: String -> Mode printSetting k = mkPreLoadMode (PrintWithDynFlags f) where f dflags = fromMaybe (panic ("Setting not found: " ++ show k)) $ lookup k (compilerInfo dflags) mkPreLoadMode :: PreLoadMode -> Mode mkPreLoadMode = Right . Left isShowGhcUsageMode :: Mode -> Bool isShowGhcUsageMode (Right (Left ShowGhcUsage)) = True isShowGhcUsageMode _ = False isShowGhciUsageMode :: Mode -> Bool isShowGhciUsageMode (Right (Left ShowGhciUsage)) = True isShowGhciUsageMode _ = False data PostLoadMode = ShowInterface FilePath -- ghc --show-iface | DoMkDependHS -- ghc -M | StopBefore Phase -- ghc -E | -C | -S -- StopBefore StopLn is the default | DoMake -- ghc --make | DoInteractive -- ghc --interactive | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"] | DoAbiHash -- ghc --abi-hash | ShowPackages -- ghc --show-packages doMkDependHSMode, doMakeMode, doInteractiveMode, doAbiHashMode, showPackagesMode :: Mode doMkDependHSMode = mkPostLoadMode DoMkDependHS doMakeMode = mkPostLoadMode DoMake doInteractiveMode = mkPostLoadMode DoInteractive doAbiHashMode = mkPostLoadMode DoAbiHash showPackagesMode = mkPostLoadMode ShowPackages showInterfaceMode :: FilePath -> Mode showInterfaceMode fp = mkPostLoadMode (ShowInterface fp) stopBeforeMode :: Phase -> Mode stopBeforeMode phase = mkPostLoadMode (StopBefore phase) doEvalMode :: String -> Mode doEvalMode str = mkPostLoadMode (DoEval [str]) mkPostLoadMode :: PostLoadMode -> Mode mkPostLoadMode = Right . Right isDoInteractiveMode :: Mode -> Bool isDoInteractiveMode (Right (Right DoInteractive)) = True isDoInteractiveMode _ = False isStopLnMode :: Mode -> Bool isStopLnMode (Right (Right (StopBefore StopLn))) = True isStopLnMode _ = False isDoMakeMode :: Mode -> Bool isDoMakeMode (Right (Right DoMake)) = True isDoMakeMode _ = False #ifdef GHCI isInteractiveMode :: PostLoadMode -> Bool isInteractiveMode DoInteractive = True isInteractiveMode _ = False #endif -- isInterpretiveMode: byte-code compiler involved isInterpretiveMode :: PostLoadMode -> Bool isInterpretiveMode DoInteractive = True isInterpretiveMode (DoEval _) = True isInterpretiveMode _ = False needsInputsMode :: PostLoadMode -> Bool needsInputsMode DoMkDependHS = True needsInputsMode (StopBefore _) = True needsInputsMode DoMake = True needsInputsMode _ = False -- True if we are going to attempt to link in this mode. -- (we might not actually link, depending on the GhcLink flag) isLinkMode :: PostLoadMode -> Bool isLinkMode (StopBefore StopLn) = True isLinkMode DoMake = True isLinkMode DoInteractive = True isLinkMode (DoEval _) = True isLinkMode _ = False isCompManagerMode :: PostLoadMode -> Bool isCompManagerMode DoMake = True isCompManagerMode DoInteractive = True isCompManagerMode (DoEval _) = True isCompManagerMode _ = False -- ----------------------------------------------------------------------------- -- Parsing the mode flag parseModeFlags :: [Located String] -> IO (Mode, [Located String], [Located String]) parseModeFlags args = do let ((leftover, errs1, warns), (mModeFlag, errs2, flags')) = runCmdLine (processArgs mode_flags args) (Nothing, [], []) mode = case mModeFlag of Nothing -> doMakeMode Just (m, _) -> m errs = errs1 ++ map (mkGeneralLocated "on the commandline") errs2 when (not (null errs)) $ throwGhcException $ errorsToGhcException errs return (mode, flags' ++ leftover, warns) type ModeM = CmdLineP (Maybe (Mode, String), [String], [Located String]) -- mode flags sometimes give rise to new DynFlags (eg. -C, see below) -- so we collect the new ones and return them. mode_flags :: [Flag ModeM] mode_flags = [ ------- help / version ---------------------------------------------- defFlag "?" (PassFlag (setMode showGhcUsageMode)) , defFlag "-help" (PassFlag (setMode showGhcUsageMode)) , defFlag "V" (PassFlag (setMode showVersionMode)) , defFlag "-version" (PassFlag (setMode showVersionMode)) , defFlag "-numeric-version" (PassFlag (setMode showNumVersionMode)) , defFlag "-info" (PassFlag (setMode showInfoMode)) , defFlag "-show-options" (PassFlag (setMode showOptionsMode)) , defFlag "-supported-languages" (PassFlag (setMode showSupportedExtensionsMode)) , defFlag "-supported-extensions" (PassFlag (setMode showSupportedExtensionsMode)) , defFlag "-show-packages" (PassFlag (setMode showPackagesMode)) ] ++ [ defFlag k' (PassFlag (setMode (printSetting k))) | k <- ["Project version", "Project Git commit id", "Booter version", "Stage", "Build platform", "Host platform", "Target platform", "Have interpreter", "Object splitting supported", "Have native code generator", "Support SMP", "Unregisterised", "Tables next to code", "RTS ways", "Leading underscore", "Debug on", "LibDir", "Global Package DB", "C compiler flags", "Gcc Linker flags", "Ld Linker flags"], let k' = "-print-" ++ map (replaceSpace . toLower) k replaceSpace ' ' = '-' replaceSpace c = c ] ++ ------- interfaces ---------------------------------------------------- [ defFlag "-show-iface" (HasArg (\f -> setMode (showInterfaceMode f) "--show-iface")) ------- primary modes ------------------------------------------------ , defFlag "c" (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f addFlag "-no-link" f)) , defFlag "M" (PassFlag (setMode doMkDependHSMode)) , defFlag "E" (PassFlag (setMode (stopBeforeMode anyHsc))) , defFlag "C" (PassFlag (setMode (stopBeforeMode HCc))) , defFlag "S" (PassFlag (setMode (stopBeforeMode (As False)))) , defFlag "-make" (PassFlag (setMode doMakeMode)) , defFlag "-interactive" (PassFlag (setMode doInteractiveMode)) , defFlag "-abi-hash" (PassFlag (setMode doAbiHashMode)) , defFlag "e" (SepArg (\s -> setMode (doEvalMode s) "-e")) ] setMode :: Mode -> String -> EwM ModeM () setMode newMode newFlag = liftEwM $ do (mModeFlag, errs, flags') <- getCmdLineState let (modeFlag', errs') = case mModeFlag of Nothing -> ((newMode, newFlag), errs) Just (oldMode, oldFlag) -> case (oldMode, newMode) of -- -c/--make are allowed together, and mean --make -no-link _ | isStopLnMode oldMode && isDoMakeMode newMode || isStopLnMode newMode && isDoMakeMode oldMode -> ((doMakeMode, "--make"), []) -- If we have both --help and --interactive then we -- want showGhciUsage _ | isShowGhcUsageMode oldMode && isDoInteractiveMode newMode -> ((showGhciUsageMode, oldFlag), []) | isShowGhcUsageMode newMode && isDoInteractiveMode oldMode -> ((showGhciUsageMode, newFlag), []) -- Otherwise, --help/--version/--numeric-version always win | isDominantFlag oldMode -> ((oldMode, oldFlag), []) | isDominantFlag newMode -> ((newMode, newFlag), []) -- We need to accumulate eval flags like "-e foo -e bar" (Right (Right (DoEval esOld)), Right (Right (DoEval [eNew]))) -> ((Right (Right (DoEval (eNew : esOld))), oldFlag), errs) -- Saying e.g. --interactive --interactive is OK _ | oldFlag == newFlag -> ((oldMode, oldFlag), errs) -- --interactive and --show-options are used together (Right (Right DoInteractive), Left (ShowOptions _)) -> ((Left (ShowOptions True), "--interactive --show-options"), errs) (Left (ShowOptions _), (Right (Right DoInteractive))) -> ((Left (ShowOptions True), "--show-options --interactive"), errs) -- Otherwise, complain _ -> let err = flagMismatchErr oldFlag newFlag in ((oldMode, oldFlag), err : errs) putCmdLineState (Just modeFlag', errs', flags') where isDominantFlag f = isShowGhcUsageMode f || isShowGhciUsageMode f || isShowVersionMode f || isShowNumVersionMode f flagMismatchErr :: String -> String -> String flagMismatchErr oldFlag newFlag = "cannot use `" ++ oldFlag ++ "' with `" ++ newFlag ++ "'" addFlag :: String -> String -> EwM ModeM () addFlag s flag = liftEwM $ do (m, e, flags') <- getCmdLineState putCmdLineState (m, e, mkGeneralLocated loc s : flags') where loc = "addFlag by " ++ flag ++ " on the commandline" -- ---------------------------------------------------------------------------- -- Run --make mode doMake :: [(String,Maybe Phase)] -> Ghc () doMake srcs = do let (hs_srcs, non_hs_srcs) = partition haskellish srcs haskellish (f,Nothing) = looksLikeModuleName f || isHaskellUserSrcFilename f || '.' `notElem` f haskellish (_,Just phase) = phase `notElem` [ As True, As False, Cc, Cobjc, Cobjcpp, CmmCpp, Cmm , StopLn] hsc_env <- GHC.getSession -- if we have no haskell sources from which to do a dependency -- analysis, then just do one-shot compilation and/or linking. -- This means that "ghc Foo.o Bar.o -o baz" links the program as -- we expect. if (null hs_srcs) then liftIO (oneShot hsc_env StopLn srcs) else do o_files <- mapM (\x -> liftIO $ compileFile hsc_env StopLn x) non_hs_srcs dflags <- GHC.getSessionDynFlags let dflags' = dflags { ldInputs = map (FileOption "") o_files ++ ldInputs dflags } _ <- GHC.setSessionDynFlags dflags' targets <- mapM (uncurry GHC.guessTarget) hs_srcs GHC.setTargets targets ok_flag <- GHC.load LoadAllTargets when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1)) return () -- --------------------------------------------------------------------------- -- --show-iface mode doShowIface :: DynFlags -> FilePath -> IO () doShowIface dflags file = do hsc_env <- newHscEnv dflags showIface hsc_env file -- --------------------------------------------------------------------------- -- Various banners and verbosity output. showBanner :: PostLoadMode -> DynFlags -> IO () showBanner _postLoadMode dflags = do let verb = verbosity dflags #ifdef GHCI -- Show the GHCi banner when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg #endif -- Display details of the configuration in verbose mode when (verb >= 2) $ do hPutStr stderr "Glasgow Haskell Compiler, Version " hPutStr stderr cProjectVersion hPutStr stderr ", stage " hPutStr stderr cStage hPutStr stderr " booted by GHC version " hPutStrLn stderr cBooterVersion -- We print out a Read-friendly string, but a prettier one than the -- Show instance gives us showInfo :: DynFlags -> IO () showInfo dflags = do let sq x = " [" ++ x ++ "\n ]" putStrLn $ sq $ intercalate "\n ," $ map show $ compilerInfo dflags showSupportedExtensions :: IO () showSupportedExtensions = mapM_ putStrLn supportedLanguagesAndExtensions showVersion :: IO () showVersion = putStrLn (cProjectName ++ ", version " ++ cProjectVersion) showOptions :: Bool -> IO () showOptions isInteractive = putStr (unlines availableOptions) where availableOptions = concat [ flagsForCompletion isInteractive, map ('-':) (concat [ getFlagNames mode_flags , (filterUnwantedStatic . getFlagNames $ flagsStatic) , flagsStaticNames ]) ] getFlagNames opts = map flagName opts -- this is a hack to get rid of two unwanted entries that get listed -- as static flags. Hopefully this hack will disappear one day together -- with static flags filterUnwantedStatic = filter (`notElem`["f", "fno-"]) showGhcUsage :: DynFlags -> IO () showGhcUsage = showUsage False showGhciUsage :: DynFlags -> IO () showGhciUsage = showUsage True showUsage :: Bool -> DynFlags -> IO () showUsage ghci dflags = do let usage_path = if ghci then ghciUsagePath dflags else ghcUsagePath dflags usage <- readFile usage_path dump usage where dump "" = return () dump ('$':'$':s) = putStr progName >> dump s dump (c:s) = putChar c >> dump s dumpFinalStats :: DynFlags -> IO () dumpFinalStats dflags = when (gopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags dumpFastStringStats :: DynFlags -> IO () dumpFastStringStats dflags = do buckets <- getFastStringTable let (entries, longest, has_z) = countFS 0 0 0 buckets msg = text "FastString stats:" $$ nest 4 (vcat [text "size: " <+> int (length buckets), text "entries: " <+> int entries, text "longest chain: " <+> int longest, text "has z-encoding: " <+> (has_z `pcntOf` entries) ]) -- we usually get more "has z-encoding" than "z-encoded", because -- when we z-encode a string it might hash to the exact same string, -- which will is not counted as "z-encoded". Only strings whose -- Z-encoding is different from the original string are counted in -- the "z-encoded" total. putMsg dflags msg where x `pcntOf` y = int ((x * 100) `quot` y) <> char '%' countFS :: Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int) countFS entries longest has_z [] = (entries, longest, has_z) countFS entries longest has_z (b:bs) = let len = length b longest' = max len longest entries' = entries + len has_zs = length (filter hasZEncoding b) in countFS entries' longest' (has_z + has_zs) bs showPackages, dumpPackages, dumpPackagesSimple :: DynFlags -> IO () showPackages dflags = putStrLn (showSDoc dflags (pprPackages dflags)) dumpPackages dflags = putMsg dflags (pprPackages dflags) dumpPackagesSimple dflags = putMsg dflags (pprPackagesSimple dflags) -- ----------------------------------------------------------------------------- -- ABI hash support {- ghc --abi-hash Data.Foo System.Bar Generates a combined hash of the ABI for modules Data.Foo and System.Bar. The modules must already be compiled, and appropriate -i options may be necessary in order to find the .hi files. This is used by Cabal for generating the InstalledPackageId for a package. The InstalledPackageId must change when the visible ABI of the package chagnes, so during registration Cabal calls ghc --abi-hash to get a hash of the package's ABI. -} -- | Print ABI hash of input modules. -- -- The resulting hash is the MD5 of the GHC version used (Trac #5328, -- see 'hiVersion') and of the existing ABI hash from each module (see -- 'mi_mod_hash'). abiHash :: [String] -- ^ List of module names -> Ghc () abiHash strs = do hsc_env <- getSession let dflags = hsc_dflags hsc_env liftIO $ do let find_it str = do let modname = mkModuleName str r <- findImportedModule hsc_env modname Nothing case r of Found _ m -> return m _error -> throwGhcException $ CmdLineError $ showSDoc dflags $ cannotFindInterface dflags modname r mods <- mapM find_it strs let get_iface modl = loadUserInterface False (text "abiHash") modl ifaces <- initIfaceCheck hsc_env $ mapM get_iface mods bh <- openBinMem (3*1024) -- just less than a block put_ bh hiVersion -- package hashes change when the compiler version changes (for now) -- see #5328 mapM_ (put_ bh . mi_mod_hash) ifaces f <- fingerprintBinMem bh putStrLn (showPpr dflags f) -- ----------------------------------------------------------------------------- -- Util unknownFlagsErr :: [String] -> a unknownFlagsErr fs = throwGhcException $ UsageError $ concatMap oneError fs where oneError f = "unrecognised flag: " ++ f ++ "\n" ++ (case fuzzyMatch f (nub allFlags) of [] -> "" suggs -> "did you mean one of:\n" ++ unlines (map (" " ++) suggs)) {- Note [-Bsymbolic and hooks] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Bsymbolic is a flag that prevents the binding of references to global symbols to symbols outside the shared library being compiled (see `man ld`). When dynamically linking, we don't use -Bsymbolic on the RTS package: that is because we want hooks to be overridden by the user, we don't want to constrain them to the RTS package. Unfortunately this seems to have broken somehow on OS X: as a result, defaultHooks (in hschooks.c) is not called, which does not initialize the GC stats. As a result, this breaks things like `:set +s` in GHCi (#8754). As a hacky workaround, we instead call 'defaultHooks' directly to initalize the flags in the RTS. A byproduct of this, I believe, is that hooks are likely broken on OS X when dynamically linking. But this probably doesn't affect most people since we're linking GHC dynamically, but most things themselves link statically. -} foreign import ccall safe "initGCStatistics" initGCStatistics :: IO ()
green-haskell/ghc
ghc/Main.hs
bsd-3-clause
34,698
0
27
9,671
7,097
3,666
3,431
542
15
module Options.Verbosity where import Types verbosityOptions :: [Flag] verbosityOptions = [ flag { flagName = "-v" , flagDescription = "verbose mode (equivalent to ``-v3``)" , flagType = DynamicFlag } , flag { flagName = "-v⟨n⟩" , flagDescription = "set verbosity level" , flagType = DynamicFlag , flagReverse = "" } , flag { flagName = "-fprint-potential-instances" , flagDescription = "display all available instances in type error messages" , flagType = DynamicFlag , flagReverse = "-fno-print-potential-instances" } , flag { flagName = "-fprint-explicit-foralls" , flagDescription = "Print explicit ``forall`` quantification in types. " ++ "See also :ghc-flag:`-XExplicitForAll`" , flagType = DynamicFlag , flagReverse = "-fno-print-explicit-foralls" } , flag { flagName = "-fprint-explicit-kinds" , flagDescription = "Print explicit kind foralls and kind arguments in types. " ++ "See also :ghc-flag:`-XKindSignature`" , flagType = DynamicFlag , flagReverse = "-fno-print-explicit-kinds" } , flag { flagName = "-fprint-explicit-runtime-reps" , flagDescription = "Print ``RuntimeRep`` variables in types which are "++ "runtime-representation polymorphic." , flagType = DynamicFlag , flagReverse = "-fno-print-explicit-runtime-reps" } , flag { flagName = "-fprint-unicode-syntax" , flagDescription = "Use unicode syntax when printing expressions, types and kinds. " ++ "See also :ghc-flag:`-XUnicodeSyntax`" , flagType = DynamicFlag , flagReverse = "-fno-print-unicode-syntax" } , flag { flagName = "-fprint-expanded-synonyms" , flagDescription = "In type errors, also print type-synonym-expanded types." , flagType = DynamicFlag , flagReverse = "-fno-print-expanded-synonyms" } , flag { flagName = "-fprint-typechecker-elaboration" , flagDescription = "Print extra information from typechecker." , flagType = DynamicFlag , flagReverse = "-fno-print-typechecker-elaboration" } , flag { flagName = "-ferror-spans" , flagDescription = "Output full span in error messages" , flagType = DynamicFlag } , flag { flagName = "-Rghc-timing" , flagDescription = "Summarise timing stats for GHC (same as ``+RTS -tstderr``)." , flagType = DynamicFlag } ]
snoyberg/ghc
utils/mkUserGuidePart/Options/Verbosity.hs
bsd-3-clause
2,677
0
8
816
339
219
120
57
1
{-# LANGUAGE CPP #-} module RegAlloc.Linear.FreeRegs ( FR(..), maxSpillSlots ) #include "HsVersions.h" where import GhcPrelude import Reg import RegClass import DynFlags import Panic import Platform -- ----------------------------------------------------------------------------- -- The free register set -- This needs to be *efficient* -- Here's an inefficient 'executable specification' of the FreeRegs data type: -- -- type FreeRegs = [RegNo] -- noFreeRegs = 0 -- releaseReg n f = if n `elem` f then f else (n : f) -- initFreeRegs = allocatableRegs -- getFreeRegs cls f = filter ( (==cls) . regClass . RealReg ) f -- allocateReg f r = filter (/= r) f import qualified RegAlloc.Linear.PPC.FreeRegs as PPC import qualified RegAlloc.Linear.SPARC.FreeRegs as SPARC import qualified RegAlloc.Linear.X86.FreeRegs as X86 import qualified RegAlloc.Linear.X86_64.FreeRegs as X86_64 import qualified PPC.Instr import qualified SPARC.Instr import qualified X86.Instr class Show freeRegs => FR freeRegs where frAllocateReg :: Platform -> RealReg -> freeRegs -> freeRegs frGetFreeRegs :: Platform -> RegClass -> freeRegs -> [RealReg] frInitFreeRegs :: Platform -> freeRegs frReleaseReg :: Platform -> RealReg -> freeRegs -> freeRegs instance FR X86.FreeRegs where frAllocateReg = \_ -> X86.allocateReg frGetFreeRegs = X86.getFreeRegs frInitFreeRegs = X86.initFreeRegs frReleaseReg = \_ -> X86.releaseReg instance FR X86_64.FreeRegs where frAllocateReg = \_ -> X86_64.allocateReg frGetFreeRegs = X86_64.getFreeRegs frInitFreeRegs = X86_64.initFreeRegs frReleaseReg = \_ -> X86_64.releaseReg instance FR PPC.FreeRegs where frAllocateReg = \_ -> PPC.allocateReg frGetFreeRegs = \_ -> PPC.getFreeRegs frInitFreeRegs = PPC.initFreeRegs frReleaseReg = \_ -> PPC.releaseReg instance FR SPARC.FreeRegs where frAllocateReg = SPARC.allocateReg frGetFreeRegs = \_ -> SPARC.getFreeRegs frInitFreeRegs = SPARC.initFreeRegs frReleaseReg = SPARC.releaseReg maxSpillSlots :: DynFlags -> Int maxSpillSlots dflags = case platformArch (targetPlatform dflags) of ArchX86 -> X86.Instr.maxSpillSlots dflags ArchX86_64 -> X86.Instr.maxSpillSlots dflags ArchPPC -> PPC.Instr.maxSpillSlots dflags ArchSPARC -> SPARC.Instr.maxSpillSlots dflags ArchSPARC64 -> panic "maxSpillSlots ArchSPARC64" ArchARM _ _ _ -> panic "maxSpillSlots ArchARM" ArchARM64 -> panic "maxSpillSlots ArchARM64" ArchPPC_64 _ -> PPC.Instr.maxSpillSlots dflags ArchAlpha -> panic "maxSpillSlots ArchAlpha" ArchMipseb -> panic "maxSpillSlots ArchMipseb" ArchMipsel -> panic "maxSpillSlots ArchMipsel" ArchJavaScript-> panic "maxSpillSlots ArchJavaScript" ArchUnknown -> panic "maxSpillSlots ArchUnknown"
ezyang/ghc
compiler/nativeGen/RegAlloc/Linear/FreeRegs.hs
bsd-3-clause
3,055
0
10
742
551
312
239
58
13
module Heredoc (str) where import Language.Haskell.TH import Language.Haskell.TH.Quote str = QuasiQuoter { quoteExp = stringE, -- From https://hackage.haskell.org/package/authoring-0.3.3.1/docs/src/Text-Authoring-TH.html quotePat = error "Authoring QuasiQuotes are only for expression context", quoteType = error "Authoring QuasiQuotes are only for expression context", quoteDec = error "Authoring QuasiQuotes are only for expression context" }
blast-hardcheese/cryptopals
src/Heredoc.hs
mit
469
0
7
73
63
39
24
8
1
import Data.List import Data.Ord import Diagrams.Prelude import Diagrams.Backend.SVG.CmdLine import Viz.Catalan import Bijections import Catalan import ChordDiagrams import Viz.List main = do putStr "(n, isConnected): " (n,b) <- getLine >>= return . read let invs = filter (if b then isConnectedInv else isIndecompInv) (involute [1..2*n]) let withTermChords = map (\f -> (length (terminalChords f), f)) invs let byTermChords = equivClassesBy (\(k1,f1) (k2,f2) -> k1 == k2) withTermChords [] let byTermChords' = sortBy (comparing (fst . head)) byTermChords let d = vsep 1 $ labelledVList [(text ("k = " ++ show k), hsep 3 $ numberedHList [diagArcs' w # centerX | f <- fs, let w = inv2arcs f]) | bytc <- byTermChords', let k = fst (head bytc), let fs = map snd bytc] mainWith (d # frame 1)
noamz/linlam-gos
src/Viz/VizChordDiagramsByTerminals.hs
mit
846
0
21
186
362
185
177
19
2
{-# LANGUAGE OverloadedStrings, TemplateHaskell, DeriveGeneric, ScopedTypeVariables, FlexibleInstances #-} module Toaster.Http (module X, toastermain) where import Toaster.Http.Prelude as X import Toaster.Http.Message as X import Web.Scotty import Control.Lens import Database.PostgreSQL.Simple import Data.Pool import Network.HTTP.Types (status200) toastermain :: Pool Connection -> ScottyM () toastermain pool = do post "/message" $ do (m :: Message) <- jsonData _ <- liftIO $ withResource pool $ \c -> do create c (m^.message) status status200 get "/messages" $ do (m :: [Message]) <- liftIO $ handler pool retrieveInit json m get "/messages/:id" $ do (i :: Int) <- param "id" (m :: [Message]) <- liftIO . handler pool $ retrieve i json m get "/newmessages" $ do (i :: Int) <- param "id" z <- liftIO $ handler pool (retrieveSince i) json z get "/history" $ do z <- liftIO $ handler pool (retrieveSince 0) json z get "" $ do redirect "/index.html" get "/" $ do redirect "/index.html" notFound $ do text "there is no such route." handler :: Pool Connection -> (Connection -> IO [Message]) -> IO [Message] handler pool f = withResource pool $ \c -> do f c
nhibberd/toaster
src/Toaster/Http.hs
mit
1,305
0
17
334
464
222
242
39
1
module Collab.Parse ( parseMessage ) where import Data.Text (Text) import qualified Data.Text as T -- | Returns a tuple with three texts: (event, sender, data) -- -- > parseMessage "code{}" -- > ==> ("code", "", "{}") -- > parseMessage "members" -- > ==> ("members", "", "") -- > parsemessage "code@sender{}" -- > ==> ("code", "sender", "{}") parseMessage :: Text -> (Text, Text, Text) parseMessage xs = (event, T.drop 1 sender, message) where (info, message) = splitWith atMessage xs (event, sender) = splitWith atSender info atMessage x = x /= '{' && x /= '[' atSender = (/= '@') splitWith :: (Char -> Bool) -> Text -> (Text, Text) splitWith f xs = (T.takeWhile f xs, T.dropWhile f xs)
dennis84/collab-haskell
src/Collab/Parse.hs
mit
724
0
9
154
200
116
84
12
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} module Unison.Codebase.Editor.Git where import Unison.Prelude import qualified Control.Exception import Control.Monad.Except (MonadError, throwError) import qualified Data.Text as Text import Shellmet (($?), ($^), ($|)) import System.FilePath ((</>)) import Unison.Codebase.Editor.RemoteRepo (ReadRepo (ReadGitRepo)) import Unison.Codebase.GitError (GitError) import qualified Unison.Codebase.GitError as GitError import qualified Unison.Util.Exception as Ex import UnliftIO.Directory (XdgDirectory (XdgCache), doesDirectoryExist, findExecutable, getXdgDirectory, removeDirectoryRecursive) import UnliftIO.IO (hFlush, stdout) import qualified Data.ByteString.Base16 as ByteString import qualified Data.Char as Char import Control.Exception.Safe (catchIO, MonadCatch) type CodebasePath = FilePath -- https://superuser.com/questions/358855/what-characters-are-safe-in-cross-platform-file-names-for-linux-windows-and-os encodeFileName :: String -> FilePath encodeFileName = let go ('.' : rem) = "$dot$" <> go rem go ('$' : rem) = "$$" <> go rem go (c : rem) | elem @[] c "/\\:*?\"<>|" || not (Char.isPrint c && Char.isAscii c) = "$x" <> encodeHex [c] <> "$" <> go rem | otherwise = c : go rem go [] = [] encodeHex :: String -> String encodeHex = Text.unpack . Text.toUpper . ByteString.encodeBase16 . encodeUtf8 . Text.pack in go tempGitDir :: MonadIO m => Text -> m FilePath tempGitDir url = getXdgDirectory XdgCache $ "unisonlanguage" </> "gitfiles" </> encodeFileName (Text.unpack url) withStatus :: MonadIO m => String -> m a -> m a withStatus str ma = do flushStr str a <- ma flushStr (const ' ' <$> str) pure a where flushStr str = do liftIO . putStr $ " " ++ str ++ "\r" hFlush stdout -- | Given a remote git repo url, and branch/commit hash (currently -- not allowed): checks for git, clones or updates a cached copy of the repo pullBranch :: (MonadIO m, MonadCatch m, MonadError GitError m) => ReadRepo -> m CodebasePath pullBranch repo@(ReadGitRepo uri) = do checkForGit localPath <- tempGitDir uri ifM (doesDirectoryExist localPath) -- try to update existing directory (ifM (isGitRepo localPath) (checkoutExisting localPath) (throwError (GitError.UnrecognizableCacheDir uri localPath))) -- directory doesn't exist, so clone anew (checkOutNew localPath Nothing) pure localPath where -- | Do a `git clone` (for a not-previously-cached repo). checkOutNew :: (MonadIO m, MonadError GitError m) => CodebasePath -> Maybe Text -> m () checkOutNew localPath branch = do withStatus ("Downloading from " ++ Text.unpack uri ++ " ...") $ (liftIO $ "git" $^ (["clone", "--quiet"] ++ ["--depth", "1"] ++ maybe [] (\t -> ["--branch", t]) branch ++ [uri, Text.pack localPath])) `withIOError` (throwError . GitError.CloneException repo . show) isGitDir <- liftIO $ isGitRepo localPath unless isGitDir . throwError $ GitError.UnrecognizableCheckoutDir uri localPath -- | Do a `git pull` on a cached repo. checkoutExisting :: (MonadIO m, MonadCatch m, MonadError GitError m) => FilePath -> m () checkoutExisting localPath = ifM (isEmptyGitRepo localPath) -- I don't know how to properly update from an empty remote repo. -- As a heuristic, if this cached copy is empty, then the remote might -- be too, so this impl. just wipes the cached copy and starts from scratch. goFromScratch -- Otherwise proceed! (catchIO (withStatus ("Updating cached copy of " ++ Text.unpack uri ++ " ...") $ do gitIn localPath ["reset", "--hard", "--quiet", "HEAD"] gitIn localPath ["clean", "-d", "--force", "--quiet"] gitIn localPath ["pull", "--force", "--quiet"]) (const $ goFromScratch)) where goFromScratch :: (MonadIO m, MonadError GitError m) => m () goFromScratch = do wipeDir localPath; checkOutNew localPath Nothing isEmptyGitRepo :: MonadIO m => FilePath -> m Bool isEmptyGitRepo localPath = liftIO $ -- if rev-parse succeeds, the repo is _not_ empty, so return False; else True (gitTextIn localPath ["rev-parse", "--verify", "--quiet", "HEAD"] $> False) $? pure True -- | try removing a cached copy wipeDir localPath = do e <- Ex.tryAny . whenM (doesDirectoryExist localPath) $ removeDirectoryRecursive localPath case e of Left e -> throwError (GitError.SomeOtherError (show e)) Right _ -> pure () -- | See if `git` is on the system path. checkForGit :: MonadIO m => MonadError GitError m => m () checkForGit = do gitPath <- liftIO $ findExecutable "git" when (isNothing gitPath) $ throwError GitError.NoGit -- | Does `git` recognize this directory as being managed by git? isGitRepo :: MonadIO m => FilePath -> m Bool isGitRepo dir = liftIO $ (True <$ gitIn dir ["rev-parse"]) $? pure False -- | Perform an IO action, passing any IO exception to `handler` withIOError :: MonadIO m => IO a -> (IOException -> m a) -> m a withIOError action handler = liftIO (fmap Right action `Control.Exception.catch` (pure . Left)) >>= either handler pure -- | Generate some `git` flags for operating on some arbitary checked out copy setupGitDir :: FilePath -> [Text] setupGitDir localPath = ["--git-dir", Text.pack $ localPath </> ".git" ,"--work-tree", Text.pack localPath] gitIn :: MonadIO m => FilePath -> [Text] -> m () gitIn localPath args = liftIO $ "git" $^ (setupGitDir localPath <> args) gitTextIn :: MonadIO m => FilePath -> [Text] -> m Text gitTextIn localPath args = liftIO $ "git" $| setupGitDir localPath <> args
unisonweb/platform
parser-typechecker/src/Unison/Codebase/Editor/Git.hs
mit
5,744
0
19
1,177
1,623
846
777
-1
-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, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group. -- -- Architectural definitions for Barrelfish on x86_mic. -- -- This architecture is used to build for the Intel Xeon Phi architecture. -- -------------------------------------------------------------------------- module K1om where import HakeTypes import Path import qualified Config import qualified ArchDefaults ------------------------------------------------------------------------- -- -- Architecture specific definitions for X86_64-k1om -- ------------------------------------------------------------------------- arch = "k1om" archFamily = "k1om" compiler = "k1om-mpss-linux-gcc" objcopy = "k1om-mpss-linux-objcopy" objdump = "k1om-mpss-linux-objdump" ar = "k1om-mpss-linux-ar" ranlib = "k1om-mpss-linux-anlib" cxxcompiler = "k1om-mpss-linux-g++" ourCommonFlags = [ Str "-m64", Str "-mno-red-zone", Str "-fPIE", Str "-fno-stack-protector", Str "-Wno-unused-but-set-variable", Str "-Wno-packed-bitfield-compat", Str "-fno-tree-vectorize", Str "-Wa,-march=k1om", Str "-mk1om", Str "-mtune=k1om", -- Apparently the MPSS gcc somehow incudes CMOVES? Str "-fno-if-conversion", -- Str "-mno-mmx", -- Str "-mno-sse", -- Str "-mno-sse2", -- Str "-mno-sse3", -- Str "-mno-sse4.1", -- Str "-mno-sse4.2", -- Str "-mno-sse4", -- Str "-mno-sse4a", -- Str "-mno-3dnow", -- specific Xeon Phi architecture Str "-D__x86__", Str "-D__k1om__" ] cFlags = ArchDefaults.commonCFlags ++ ArchDefaults.commonFlags ++ ourCommonFlags ++ [Str "-fno-builtin" ] cxxFlags = ArchDefaults.commonCxxFlags ++ ArchDefaults.commonFlags ++ ourCommonFlags ++ [Str "-std=gnu++0x"] -- XXX: with the Intel GCC 4.7.0 still experimental cDefines = ArchDefaults.cDefines options -- TODO> -m elf_i386 ourLdFlags = [ Str "-Wl,-z,max-page-size=0x1000", Str "-Wl,--build-id=none", Str "-Wl,-melf_k1om", Str "-m64" ] ldFlags = ArchDefaults.ldFlags arch ++ ourLdFlags ldCxxFlags = ArchDefaults.ldCxxFlags arch ++ ourLdFlags options = (ArchDefaults.options arch archFamily) { optFlags = cFlags, optCxxFlags = cxxFlags, optDefines = cDefines, optLdFlags = ldFlags, optLdCxxFlags = ldCxxFlags, optInterconnectDrivers = ["lmp", "ump", "multihop"], optFlounderBackends = ["lmp", "ump", "multihop"] } -- -- The kernel is "different" -- kernelCFlags = [ Str s | s <- [ "-fno-builtin", "-nostdinc", "-std=c99", "-m64", "-fPIE", "-e start", "-mno-red-zone", "-mk1om", "-Wa,-march=k1om", "-fno-stack-protector", "-fomit-frame-pointer", "-U__linux__", "-D__k1om__", "-D__x86__", "-mk1om", "-Wall", "-Wa,-march=k1om", "-Wshadow", "-Wstrict-prototypes", "-Wold-style-definition", "-Wmissing-prototypes", "-Wmissing-declarations", "-Wmissing-field-initializers", "-Wredundant-decls", "-Wno-packed-bitfield-compat", "-Wno-unused-but-set-variable", "-Werror", "-imacros deputy/nodeputy.h", "-fno-tree-vectorize", "-mno-mmx", "-mno-sse", "-mno-sse2", "-mno-sse3", "-mno-sse4.1", "-mno-sse4.2", "-mno-sse4", "-mno-sse4a", "-mno-3dnow", -- Apparently the MPSS gcc somehow incudes CMOVES? "-fno-if-conversion" ] ] kernelLdFlags = [ Str s | s <- [ "-Wl,-N ", "-pie ", "-Wl,-melf_k1om ", "-fno-builtin ", "-e start", "-nostdlib ", "-Wl,--fatal-warnings ", "-m64 " ] ] ------------------------------------------------------------------------ -- -- Now, commands to actually do something -- ------------------------------------------------------------------------ -- -- Compilers -- cCompiler = ArchDefaults.cCompiler arch compiler cxxCompiler = ArchDefaults.cxxCompiler arch cxxcompiler makeDepend = ArchDefaults.makeDepend arch compiler makeCxxDepend = ArchDefaults.makeCxxDepend arch cxxcompiler cToAssembler = ArchDefaults.cToAssembler arch compiler assembler = ArchDefaults.assembler arch compiler archive = ArchDefaults.archive arch linker = ArchDefaults.linker arch compiler cxxlinker = ArchDefaults.cxxlinker arch cxxcompiler -- -- Link the kernel (CPU Driver) -- linkKernel :: Options -> [String] -> [String] -> String -> HRule linkKernel opts objs libs kbin = let linkscript = "/kernel/linker.lds" in Rules [ Rule ([ Str compiler, Str Config.cOptFlags, NStr "-T", In BuildTree arch "/kernel/linker.lds", Str "-o", Out arch kbin ] ++ (optLdFlags opts) ++ [ In BuildTree arch o | o <- objs ] ++ [ In BuildTree arch l | l <- libs ] ++ [ NL, NStr "/bin/echo -e '\\0002' | dd of=", Out arch kbin, Str "bs=1 seek=16 count=1 conv=notrunc status=noxfer" ] ), Rule [ Str "cpp", NStr "-I", NoDep SrcTree "src" "/kernel/include/", Str "-D__ASSEMBLER__", Str "-P", In SrcTree "src" "/kernel/arch/k1om/linker.lds.in", Out arch linkscript ] ]
utsav2601/cmpe295A
hake/K1om.hs
mit
7,351
8
17
3,075
925
532
393
125
1
{-# OPTIONS_GHC -w #-} module Latte.Lang.Print where -- pretty-printer generated by the BNF converter import Latte.Lang.Abs import Data.Char -- the top-level printing method printTree :: Print a => a -> String printTree = render . prt 0 type Doc = [ShowS] -> [ShowS] doc :: ShowS -> Doc doc = (:) render :: Doc -> String render d = rend 0 (map ($ "") $ d []) "" where rend i ss = case ss of "[" :ts -> showChar '[' . rend i ts "(" :ts -> showChar '(' . rend i ts "{" :ts -> showChar '{' . new (i+1) . rend (i+1) ts "}" : ";":ts -> new (i-1) . space "}" . showChar ';' . new (i-1) . rend (i-1) ts "}" :ts -> new (i-1) . showChar '}' . new (i-1) . rend (i-1) ts ";" :ts -> showChar ';' . new i . rend i ts t : "," :ts -> showString t . space "," . rend i ts t : ")" :ts -> showString t . showChar ')' . rend i ts t : "]" :ts -> showString t . showChar ']' . rend i ts t :ts -> space t . rend i ts _ -> id new i = showChar '\n' . replicateS (2*i) (showChar ' ') . dropWhile isSpace space t = showString t . (\s -> if null s then "" else (' ':s)) parenth :: Doc -> Doc parenth ss = doc (showChar '(') . ss . doc (showChar ')') concatS :: [ShowS] -> ShowS concatS = foldr (.) id concatD :: [Doc] -> Doc concatD = foldr (.) id replicateS :: Int -> ShowS -> ShowS replicateS n f = concatS (replicate n f) -- the printer class does the job class Print a where prt :: Int -> a -> Doc prtList :: Int -> [a] -> Doc prtList i = concatD . map (prt i) instance Print a => Print [a] where prt = prtList instance Print Char where prt _ s = doc (showChar '\'' . mkEsc '\'' s . showChar '\'') prtList _ s = doc (showChar '"' . concatS (map (mkEsc '"') s) . showChar '"') mkEsc :: Char -> Char -> ShowS mkEsc q s = case s of _ | s == q -> showChar '\\' . showChar s '\\'-> showString "\\\\" '\n' -> showString "\\n" '\t' -> showString "\\t" _ -> showChar s prPrec :: Int -> Int -> Doc -> Doc prPrec i j = if j<i then parenth else id instance Print Integer where prt _ x = doc (shows x) instance Print Double where prt _ x = doc (shows x) instance Print Ident where prt _ (Ident i) = doc (showString ( i)) instance Print Program where prt i e = case e of Program topdefs -> prPrec i 0 (concatD [prt 0 topdefs]) instance Print TopDef where prt i e = case e of FnDef type_ id args block -> prPrec i 0 (concatD [prt 0 type_, prt 0 id, doc (showString "("), prt 0 args, doc (showString ")"), prt 0 block]) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs]) instance Print Arg where prt i e = case e of Arg type_ id -> prPrec i 0 (concatD [prt 0 type_, prt 0 id]) prtList _ [] = (concatD []) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs]) instance Print Block where prt i e = case e of Block stmts -> prPrec i 0 (concatD [doc (showString "{"), prt 0 stmts, doc (showString "}")]) instance Print Stmt where prt i e = case e of Empty -> prPrec i 0 (concatD [doc (showString ";")]) BStmt block -> prPrec i 0 (concatD [prt 0 block]) Decl type_ items -> prPrec i 0 (concatD [prt 0 type_, prt 0 items, doc (showString ";")]) Ass id expr -> prPrec i 0 (concatD [prt 0 id, doc (showString "="), prt 0 expr, doc (showString ";")]) Incr id -> prPrec i 0 (concatD [prt 0 id, doc (showString "++"), doc (showString ";")]) Decr id -> prPrec i 0 (concatD [prt 0 id, doc (showString "--"), doc (showString ";")]) Ret expr -> prPrec i 0 (concatD [doc (showString "return"), prt 0 expr, doc (showString ";")]) VRet -> prPrec i 0 (concatD [doc (showString "return"), doc (showString ";")]) Cond expr stmt -> prPrec i 0 (concatD [doc (showString "if"), doc (showString "("), prt 0 expr, doc (showString ")"), prt 0 stmt]) CondElse expr stmt1 stmt2 -> prPrec i 0 (concatD [doc (showString "if"), doc (showString "("), prt 0 expr, doc (showString ")"), prt 0 stmt1, doc (showString "else"), prt 0 stmt2]) While expr stmt -> prPrec i 0 (concatD [doc (showString "while"), doc (showString "("), prt 0 expr, doc (showString ")"), prt 0 stmt]) SExp expr -> prPrec i 0 (concatD [prt 0 expr, doc (showString ";")]) prtList _ [] = (concatD []) prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs]) instance Print Item where prt i e = case e of NoInit id -> prPrec i 0 (concatD [prt 0 id]) Init id expr -> prPrec i 0 (concatD [prt 0 id, doc (showString "="), prt 0 expr]) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs]) instance Print Type where prt i e = case e of Int -> prPrec i 0 (concatD [doc (showString "int")]) Str -> prPrec i 0 (concatD [doc (showString "string")]) Bool -> prPrec i 0 (concatD [doc (showString "boolean")]) Void -> prPrec i 0 (concatD [doc (showString "void")]) Fun type_ types -> prPrec i 0 (concatD [prt 0 type_, doc (showString "("), prt 0 types, doc (showString ")")]) prtList _ [] = (concatD []) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs]) instance Print Expr where prt i e = case e of EVar id -> prPrec i 6 (concatD [prt 0 id]) ELitInt n -> prPrec i 6 (concatD [prt 0 n]) ELitTrue -> prPrec i 6 (concatD [doc (showString "true")]) ELitFalse -> prPrec i 6 (concatD [doc (showString "false")]) EApp id exprs -> prPrec i 6 (concatD [prt 0 id, doc (showString "("), prt 0 exprs, doc (showString ")")]) EString str -> prPrec i 6 (concatD [prt 0 str]) Neg expr -> prPrec i 5 (concatD [doc (showString "-"), prt 6 expr]) Not expr -> prPrec i 5 (concatD [doc (showString "!"), prt 6 expr]) EMul expr1 mulop expr2 -> prPrec i 4 (concatD [prt 4 expr1, prt 0 mulop, prt 5 expr2]) EAdd expr1 addop expr2 -> prPrec i 3 (concatD [prt 3 expr1, prt 0 addop, prt 4 expr2]) ERel expr1 relop expr2 -> prPrec i 2 (concatD [prt 2 expr1, prt 0 relop, prt 3 expr2]) EAnd expr1 expr2 -> prPrec i 1 (concatD [prt 2 expr1, doc (showString "&&"), prt 1 expr2]) EOr expr1 expr2 -> prPrec i 0 (concatD [prt 1 expr1, doc (showString "||"), prt 0 expr2]) prtList _ [] = (concatD []) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs]) instance Print AddOp where prt i e = case e of Plus -> prPrec i 0 (concatD [doc (showString "+")]) Minus -> prPrec i 0 (concatD [doc (showString "-")]) instance Print MulOp where prt i e = case e of Times -> prPrec i 0 (concatD [doc (showString "*")]) Div -> prPrec i 0 (concatD [doc (showString "/")]) Mod -> prPrec i 0 (concatD [doc (showString "%")]) instance Print RelOp where prt i e = case e of LTH -> prPrec i 0 (concatD [doc (showString "<")]) LE -> prPrec i 0 (concatD [doc (showString "<=")]) GTH -> prPrec i 0 (concatD [doc (showString ">")]) GE -> prPrec i 0 (concatD [doc (showString ">=")]) EQU -> prPrec i 0 (concatD [doc (showString "==")]) NE -> prPrec i 0 (concatD [doc (showString "!=")])
mpsk2/LatteCompiler
src/Latte/Lang/Print.hs
mit
7,153
0
16
1,756
3,891
1,911
1,980
141
12
{-# LANGUAGE OverloadedStrings #-} import Web.Scotty main :: IO () main = scotty 3000 $ do get "/:word" $ do beam <- param "word" html $ mconcat ["<h1>Scotty, ", beam, " me up!</h1>"]
gdevanla/helloscotty
Main.hs
mit
196
0
13
45
68
33
35
7
1
module Hpcb.Data.Graphic ( Graphic(..) ) where import Hpcb.SExpr import Hpcb.Data.Action import Hpcb.Data.Base import Hpcb.Data.Layer import Hpcb.Data.Effects -- | Graphic elements that are not inside footprints. data Graphic = GrLine (V2 Float) (V2 Float) Float Layer Float -- ^ start, end, angle, layer, width | GrCircle (V2 Float) (V2 Float) Layer Float -- ^ center, end, layer, width | GrText String Position Layer Effects deriving Show instance Itemizable Graphic where itemize (GrLine (V2 xs ys) (V2 xe ye) a l w) = Item "gr_line" [ Item "start" [PFloat xs, PFloat ys], Item "end" [PFloat xe, PFloat ye], Item "angle" [PFloat a], itemize l, Item "width" [PFloat w] ] itemize (GrCircle (V2 xc yc) (V2 xe ye) l w) = Item "gr_circle" [ Item "center" [PFloat xc, PFloat yc], Item "end" [PFloat xe, PFloat ye], itemize l, Item "width" [PFloat w] ] itemize (GrText s pos l e) = Item "gr_text" [ PString $ show s, itemize pos, itemize l, itemize e ] instance Transformable Graphic where transform m (GrLine s e a l w) = GrLine (applyMatrixV2 m s) (applyMatrixV2 m e) a l w transform m (GrCircle c e l w) = GrCircle (applyMatrixV2 m c) (applyMatrixV2 m e) l w transform m (GrText s pos l e) = GrText s (applyMatrix m pos) l e instance Parameterized Graphic where layer l (GrLine s e a _ w) = GrLine s e a l w layer l (GrCircle c e _ w) = GrCircle c e l w layer l (GrText s pos _ e) = GrText s pos l e layers _ GrLine{} = error "A line cannot be on multiple layers" layers _ GrCircle{} = error "A circle cannot be on multiple layers" layers _ GrText{} = error "A text cannot be on multiple layers" width w (GrLine s e a l _) = GrLine s e a l w width w (GrCircle c e l _) = GrCircle c e l w width _ (GrText s pos l e) = GrText s pos l e effects _ l@GrLine{} = l effects _ c@GrCircle{} = c effects f (GrText s pos lay e) = GrText s pos lay (f e)
iemxblog/hpcb
src/Hpcb/Data/Graphic.hs
mit
2,005
0
10
526
862
435
427
49
0
{-# OPTIONS_GHC -fno-warn-orphans #-} module Graphics.Urho3D.Scene.Scene( Scene , sceneContext , SharedScene ) where import qualified Language.C.Inline as C import qualified Language.C.Inline.Cpp as C import Graphics.Urho3D.Scene.Internal.Scene import Graphics.Urho3D.Scene.Node import Graphics.Urho3D.Container.Ptr import Graphics.Urho3D.Core.Context import Graphics.Urho3D.Creatable import Graphics.Urho3D.Monad import Graphics.Urho3D.Parent import Data.Monoid import Foreign import Graphics.Urho3D.Scene.Animatable import Graphics.Urho3D.Scene.Serializable import Graphics.Urho3D.Core.Object C.context (C.cppCtx <> sceneCntx <> sharedScenePtrCntx <> contextContext <> nodeContext <> animatableContext <> serializableContext <> objectContext) C.include "<Urho3D/Scene/Scene.h>" C.using "namespace Urho3D" sceneContext :: C.Context sceneContext = sharedScenePtrCntx <> sceneCntx <> nodeContext newScene :: Ptr Context -> IO (Ptr Scene) newScene ptr = [C.exp| Scene* { new Scene($(Context* ptr)) } |] deleteScene :: Ptr Scene -> IO () deleteScene ptr = [C.exp| void { delete $(Scene* ptr) } |] instance Creatable (Ptr Scene) where type CreationOptions (Ptr Scene) = Ptr Context newObject = liftIO . newScene deleteObject = liftIO . deleteScene deriveParents [''Object, ''Serializable, ''Animatable, ''Node] ''Scene sharedPtr "Scene"
Teaspot-Studio/Urho3D-Haskell
src/Graphics/Urho3D/Scene/Scene.hs
mit
1,367
0
14
179
344
199
145
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-workspaces-workspace-workspaceproperties.html module Stratosphere.ResourceProperties.WorkSpacesWorkspaceWorkspaceProperties where import Stratosphere.ResourceImports -- | Full data type definition for WorkSpacesWorkspaceWorkspaceProperties. See -- 'workSpacesWorkspaceWorkspaceProperties' for a more convenient -- constructor. data WorkSpacesWorkspaceWorkspaceProperties = WorkSpacesWorkspaceWorkspaceProperties { _workSpacesWorkspaceWorkspacePropertiesComputeTypeName :: Maybe (Val Text) , _workSpacesWorkspaceWorkspacePropertiesRootVolumeSizeGib :: Maybe (Val Integer) , _workSpacesWorkspaceWorkspacePropertiesRunningMode :: Maybe (Val Text) , _workSpacesWorkspaceWorkspacePropertiesRunningModeAutoStopTimeoutInMinutes :: Maybe (Val Integer) , _workSpacesWorkspaceWorkspacePropertiesUserVolumeSizeGib :: Maybe (Val Integer) } deriving (Show, Eq) instance ToJSON WorkSpacesWorkspaceWorkspaceProperties where toJSON WorkSpacesWorkspaceWorkspaceProperties{..} = object $ catMaybes [ fmap (("ComputeTypeName",) . toJSON) _workSpacesWorkspaceWorkspacePropertiesComputeTypeName , fmap (("RootVolumeSizeGib",) . toJSON) _workSpacesWorkspaceWorkspacePropertiesRootVolumeSizeGib , fmap (("RunningMode",) . toJSON) _workSpacesWorkspaceWorkspacePropertiesRunningMode , fmap (("RunningModeAutoStopTimeoutInMinutes",) . toJSON) _workSpacesWorkspaceWorkspacePropertiesRunningModeAutoStopTimeoutInMinutes , fmap (("UserVolumeSizeGib",) . toJSON) _workSpacesWorkspaceWorkspacePropertiesUserVolumeSizeGib ] -- | Constructor for 'WorkSpacesWorkspaceWorkspaceProperties' containing -- required fields as arguments. workSpacesWorkspaceWorkspaceProperties :: WorkSpacesWorkspaceWorkspaceProperties workSpacesWorkspaceWorkspaceProperties = WorkSpacesWorkspaceWorkspaceProperties { _workSpacesWorkspaceWorkspacePropertiesComputeTypeName = Nothing , _workSpacesWorkspaceWorkspacePropertiesRootVolumeSizeGib = Nothing , _workSpacesWorkspaceWorkspacePropertiesRunningMode = Nothing , _workSpacesWorkspaceWorkspacePropertiesRunningModeAutoStopTimeoutInMinutes = Nothing , _workSpacesWorkspaceWorkspacePropertiesUserVolumeSizeGib = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-workspaces-workspace-workspaceproperties.html#cfn-workspaces-workspace-workspaceproperties-computetypename wswwpComputeTypeName :: Lens' WorkSpacesWorkspaceWorkspaceProperties (Maybe (Val Text)) wswwpComputeTypeName = lens _workSpacesWorkspaceWorkspacePropertiesComputeTypeName (\s a -> s { _workSpacesWorkspaceWorkspacePropertiesComputeTypeName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-workspaces-workspace-workspaceproperties.html#cfn-workspaces-workspace-workspaceproperties-rootvolumesizegib wswwpRootVolumeSizeGib :: Lens' WorkSpacesWorkspaceWorkspaceProperties (Maybe (Val Integer)) wswwpRootVolumeSizeGib = lens _workSpacesWorkspaceWorkspacePropertiesRootVolumeSizeGib (\s a -> s { _workSpacesWorkspaceWorkspacePropertiesRootVolumeSizeGib = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-workspaces-workspace-workspaceproperties.html#cfn-workspaces-workspace-workspaceproperties-runningmode wswwpRunningMode :: Lens' WorkSpacesWorkspaceWorkspaceProperties (Maybe (Val Text)) wswwpRunningMode = lens _workSpacesWorkspaceWorkspacePropertiesRunningMode (\s a -> s { _workSpacesWorkspaceWorkspacePropertiesRunningMode = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-workspaces-workspace-workspaceproperties.html#cfn-workspaces-workspace-workspaceproperties-runningmodeautostoptimeoutinminutes wswwpRunningModeAutoStopTimeoutInMinutes :: Lens' WorkSpacesWorkspaceWorkspaceProperties (Maybe (Val Integer)) wswwpRunningModeAutoStopTimeoutInMinutes = lens _workSpacesWorkspaceWorkspacePropertiesRunningModeAutoStopTimeoutInMinutes (\s a -> s { _workSpacesWorkspaceWorkspacePropertiesRunningModeAutoStopTimeoutInMinutes = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-workspaces-workspace-workspaceproperties.html#cfn-workspaces-workspace-workspaceproperties-uservolumesizegib wswwpUserVolumeSizeGib :: Lens' WorkSpacesWorkspaceWorkspaceProperties (Maybe (Val Integer)) wswwpUserVolumeSizeGib = lens _workSpacesWorkspaceWorkspacePropertiesUserVolumeSizeGib (\s a -> s { _workSpacesWorkspaceWorkspacePropertiesUserVolumeSizeGib = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/WorkSpacesWorkspaceWorkspaceProperties.hs
mit
4,686
0
12
350
538
305
233
42
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} ------------------------------------------------------------------------------ -- | This module defines our application's state type and an alias for its -- handler monad. module Application where ------------------------------------------------------------------------------ import Control.Lens import Snap import Snap.Snaplet.SqliteSimple import Snap.Snaplet.SqliteJwt ------------------------------------------------------------------------------ data App = App { _db :: Snaplet Sqlite , _jwt :: Snaplet SqliteJwt } makeLenses ''App ------------------------------------------------------------------------------ type AppHandler = Handler App App
marksauter/reactd3
server/Application.hs
mit
806
0
9
92
80
50
30
14
0
module NgLint.Messages where import Control.Arrow ((>>>)) import NgLint.Parser import NgLint.Position import Text.Parsec.Pos (SourcePos) data ErrorCode = NG001 | NG002 | NG003 | NG004 | NG005 deriving (Eq) data LintMessage = LintMessage SourcePos ErrorCode deriving (Eq) instance Show LintMessage where show (LintMessage pos code) = show pos ++ ": " ++ show code instance Ord LintMessage where compare (LintMessage p1 _) (LintMessage p2 _) = compare p1 p2 instance Position LintMessage where getPos (LintMessage pos _) = pos instance Show ErrorCode where show NG001 = "NG001: root directive inside location block" show NG002 = "NG002: if can be replaced with something else" show NG003 = "NG003: enabling SSLv3 leaves you vulnerable to POODLE attack" show NG004 = "NG004: enabling server_tokens leaks your web server version number" show NG005 = "NG005: enabling TLSv1 leaves you vulnerable to CRIME attack" label :: ErrorCode -> [Decl] -> [LintMessage] label code = map buildMessage where buildMessage decl = LintMessage (getPos decl) code
federicobond/nglint
src/NgLint/Messages.hs
mit
1,085
0
9
201
283
150
133
22
1
module Handler.Search where import Import getSearchR :: Handler Html getSearchR = do search <- fromMaybe "" <$> lookupGetParam "search" defaultLayout $ do setTitle $ toHtml $ "Search: " ++ search $(widgetFile "search")
fpco/schoolofhaskell.com
src/Handler/Search.hs
mit
245
0
12
58
71
34
37
8
1
var food = query_inventory("food"); var tools = query_inventory("tools"); var has_food = food >= 1; var has_tools = tools >= 1; if(has_food){ if(has_tools){ //produce 2 wood, consume 1 food, break tools with 10% chance produce(agent,"wood",2); consume(agent,"food",1); consume(agent,"tools",1,0.1); }else{ //produce 1 wood, consume 1 food produce(agent,"wood",1); consume(agent,"food",1); } }else{ //fined $2 for being idle consume(agent,"money",2); if(!has_food && inventory_is_full()){ make_room_for(agent,"food",2); } }
larsiusprime/bazaarBot
examples/doran_and_parberry/Assets/scripts/woodcutter.hs
mit
549
29
9
85
275
165
110
-1
-1
module BadIntel.Config.Config ( MonadConfig , Config (..) , pickName ) where import Control.Monad.State import BadIntel.Types.Common import BadIntel.Random.Names type MonadConfig a = StateT Config a data Config = Config { _ukNameCollection :: NameCollection , _ruNameCollection :: NameCollection } rebuildConfig :: Country -> NameCollection -> Config -> Config rebuildConfig Uk col conf = conf { _ukNameCollection = col } rebuildConfig Russia col conf = conf { _ruNameCollection = col } countryToNameCollection :: Country -> Config -> NameCollection countryToNameCollection Uk = _ukNameCollection countryToNameCollection Russia = _ruNameCollection pickName :: (Monad m) => Country -> Gender -> MonadConfig m String pickName c g = do conf <- get let collection = countryToNameCollection c conf let list = listFromGender g collection let list' = tail list let collection' = rebuildCollection g list' collection put $ rebuildConfig c collection' conf return $ head list
Raveline/BadIntel
lib/BadIntel/Config/Config.hs
gpl-2.0
1,107
0
10
277
283
149
134
24
1
{-| Implementation of the generic daemon functionality. -} {- Copyright (C) 2011, 2012 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.Daemon ( DaemonOptions(..) , OptType , CheckFn , PrepFn , MainFn , defaultOptions , oShowHelp , oShowVer , oNoDaemonize , oNoUserChecks , oDebug , oPort , oBindAddress , oSyslogUsage , parseArgs , parseAddress , cleanupSocket , describeError , genericMain ) where import Control.Exception import Control.Monad import Data.Maybe (fromMaybe) import Data.Word import GHC.IO.Handle (hDuplicateTo) import Network.BSD (getHostName) import qualified Network.Socket as Socket import System.Console.GetOpt import System.Exit import System.Environment import System.IO import System.IO.Error (isDoesNotExistError, modifyIOError, annotateIOError) import System.Posix.Directory import System.Posix.Files import System.Posix.IO import System.Posix.Process import System.Posix.Types import System.Posix.Signals import Ganeti.Common as Common import Ganeti.Logging import Ganeti.Runtime import Ganeti.BasicTypes import Ganeti.Utils import qualified Ganeti.Constants as C import qualified Ganeti.Ssconf as Ssconf -- * Constants -- | \/dev\/null path. devNull :: FilePath devNull = "/dev/null" -- | Error message prefix, used in two separate paths (when forking -- and when not). daemonStartupErr :: String -> String daemonStartupErr = ("Error when starting the daemon process: " ++) -- * Data types -- | Command line options structure. data DaemonOptions = DaemonOptions { optShowHelp :: Bool -- ^ Just show the help , optShowVer :: Bool -- ^ Just show the program version , optShowComp :: Bool -- ^ Just show the completion info , optDaemonize :: Bool -- ^ Whether to daemonize or not , optPort :: Maybe Word16 -- ^ Override for the network port , optDebug :: Bool -- ^ Enable debug messages , optNoUserChecks :: Bool -- ^ Ignore user checks , optBindAddress :: Maybe String -- ^ Override for the bind address , optSyslogUsage :: Maybe SyslogUsage -- ^ Override for Syslog usage } -- | Default values for the command line options. defaultOptions :: DaemonOptions defaultOptions = DaemonOptions { optShowHelp = False , optShowVer = False , optShowComp = False , optDaemonize = True , optPort = Nothing , optDebug = False , optNoUserChecks = False , optBindAddress = Nothing , optSyslogUsage = Nothing } instance StandardOptions DaemonOptions where helpRequested = optShowHelp verRequested = optShowVer compRequested = optShowComp requestHelp o = o { optShowHelp = True } requestVer o = o { optShowVer = True } requestComp o = o { optShowComp = True } -- | Abrreviation for the option type. type OptType = GenericOptType DaemonOptions -- | Check function type. type CheckFn a = DaemonOptions -> IO (Either ExitCode a) -- | Prepare function type. type PrepFn a b = DaemonOptions -> a -> IO b -- | Main execution function type. type MainFn a b = DaemonOptions -> a -> b -> IO () -- * Command line options oNoDaemonize :: OptType oNoDaemonize = (Option "f" ["foreground"] (NoArg (\ opts -> Ok opts { optDaemonize = False})) "Don't detach from the current terminal", OptComplNone) oDebug :: OptType oDebug = (Option "d" ["debug"] (NoArg (\ opts -> Ok opts { optDebug = True })) "Enable debug messages", OptComplNone) oNoUserChecks :: OptType oNoUserChecks = (Option "" ["no-user-checks"] (NoArg (\ opts -> Ok opts { optNoUserChecks = True })) "Ignore user checks", OptComplNone) oPort :: Int -> OptType oPort def = (Option "p" ["port"] (reqWithConversion (tryRead "reading port") (\port opts -> Ok opts { optPort = Just port }) "PORT") ("Network port (default: " ++ show def ++ ")"), OptComplInteger) oBindAddress :: OptType oBindAddress = (Option "b" ["bind"] (ReqArg (\addr opts -> Ok opts { optBindAddress = Just addr }) "ADDR") "Bind address (default depends on cluster configuration)", OptComplInetAddr) oSyslogUsage :: OptType oSyslogUsage = (Option "" ["syslog"] (reqWithConversion syslogUsageFromRaw (\su opts -> Ok opts { optSyslogUsage = Just su }) "SYSLOG") ("Enable logging to syslog (except debug \ \messages); one of 'no', 'yes' or 'only' [" ++ C.syslogUsage ++ "]"), OptComplChoices ["yes", "no", "only"]) -- | Generic options. genericOpts :: [OptType] genericOpts = [ oShowHelp , oShowVer , oShowComp ] -- | Annotates and transforms IOErrors into a Result type. This can be -- used in the error handler argument to 'catch', for example. ioErrorToResult :: String -> IOError -> IO (Result a) ioErrorToResult description exc = return . Bad $ description ++ ": " ++ show exc -- | Small wrapper over getArgs and 'parseOpts'. parseArgs :: String -> [OptType] -> IO (DaemonOptions, [String]) parseArgs cmd options = do cmd_args <- getArgs parseOpts defaultOptions cmd_args cmd (options ++ genericOpts) [] -- * Daemon-related functions -- | PID file mode. pidFileMode :: FileMode pidFileMode = unionFileModes ownerReadMode ownerWriteMode -- | PID file open flags. pidFileFlags :: OpenFileFlags pidFileFlags = defaultFileFlags { noctty = True, trunc = False } -- | Writes a PID file and locks it. writePidFile :: FilePath -> IO Fd writePidFile path = do fd <- openFd path ReadWrite (Just pidFileMode) pidFileFlags setLock fd (WriteLock, AbsoluteSeek, 0, 0) my_pid <- getProcessID _ <- fdWrite fd (show my_pid ++ "\n") return fd -- | Helper function to ensure a socket doesn't exist. Should only be -- called once we have locked the pid file successfully. cleanupSocket :: FilePath -> IO () cleanupSocket socketPath = catchJust (guard . isDoesNotExistError) (removeLink socketPath) (const $ return ()) -- | Sets up a daemon's environment. setupDaemonEnv :: FilePath -> FileMode -> IO () setupDaemonEnv cwd umask = do changeWorkingDirectory cwd _ <- setFileCreationMask umask _ <- createSession return () -- | Signal handler for reopening log files. handleSigHup :: FilePath -> IO () handleSigHup path = do setupDaemonFDs (Just path) logInfo "Reopening log files after receiving SIGHUP" -- | Sets up a daemon's standard file descriptors. setupDaemonFDs :: Maybe FilePath -> IO () setupDaemonFDs logfile = do null_in_handle <- openFile devNull ReadMode null_out_handle <- openFile (fromMaybe devNull logfile) AppendMode hDuplicateTo null_in_handle stdin hDuplicateTo null_out_handle stdout hDuplicateTo null_out_handle stderr hClose null_in_handle hClose null_out_handle -- | Computes the default bind address for a given family. defaultBindAddr :: Int -- ^ The port we want -> Socket.Family -- ^ The cluster IP family -> Result (Socket.Family, Socket.SockAddr) defaultBindAddr port Socket.AF_INET = Ok (Socket.AF_INET, Socket.SockAddrInet (fromIntegral port) Socket.iNADDR_ANY) defaultBindAddr port Socket.AF_INET6 = Ok (Socket.AF_INET6, Socket.SockAddrInet6 (fromIntegral port) 0 Socket.iN6ADDR_ANY 0) defaultBindAddr _ fam = Bad $ "Unsupported address family: " ++ show fam -- | Based on the options, compute the socket address to use for the -- daemon. parseAddress :: DaemonOptions -- ^ Command line options -> Int -- ^ Default port for this daemon -> IO (Result (Socket.Family, Socket.SockAddr)) parseAddress opts defport = do let port = maybe defport fromIntegral $ optPort opts def_family <- Ssconf.getPrimaryIPFamily Nothing case optBindAddress opts of Nothing -> return (def_family >>= defaultBindAddr port) Just saddr -> Control.Exception.catch (resolveAddr port saddr) (ioErrorToResult $ "Invalid address " ++ saddr) -- | Environment variable to override the assumed host name of the -- current node. vClusterHostNameEnvVar :: String vClusterHostNameEnvVar = "GANETI_HOSTNAME" -- | Returns if the current node is the master node. isMaster :: IO Bool isMaster = do let ioErrorToNothing :: IOError -> IO (Maybe String) ioErrorToNothing _ = return Nothing vcluster_node <- Control.Exception.catch (liftM Just (getEnv vClusterHostNameEnvVar)) ioErrorToNothing curNode <- case vcluster_node of Just node_name -> return node_name Nothing -> getHostName masterNode <- Ssconf.getMasterNode Nothing case masterNode of Ok n -> return (curNode == n) Bad _ -> return False -- | Ensures that the daemon runs on the right node (and exits -- gracefully if it doesnt) ensureNode :: GanetiDaemon -> IO () ensureNode daemon = do is_master <- isMaster when (daemonOnlyOnMaster daemon && not is_master) $ do putStrLn "Not master, exiting." exitWith (ExitFailure C.exitNotmaster) -- | Run an I\/O action that might throw an I\/O error, under a -- handler that will simply annotate and re-throw the exception. describeError :: String -> Maybe Handle -> Maybe FilePath -> IO a -> IO a describeError descr hndl fpath = modifyIOError (\e -> annotateIOError e descr hndl fpath) -- | Run an I\/O action as a daemon. -- -- WARNING: this only works in single-threaded mode (either using the -- single-threaded runtime, or using the multi-threaded one but with -- only one OS thread, i.e. -N1). daemonize :: FilePath -> (Maybe Fd -> IO ()) -> IO () daemonize logfile action = do (rpipe, wpipe) <- createPipe -- first fork _ <- forkProcess $ do -- in the child closeFd rpipe let wpipe' = Just wpipe setupDaemonEnv "/" (unionFileModes groupModes otherModes) setupDaemonFDs (Just logfile) `Control.Exception.catch` handlePrepErr False wpipe' _ <- installHandler lostConnection (Catch (handleSigHup logfile)) Nothing -- second fork, launches the actual child code; standard -- double-fork technique _ <- forkProcess (action wpipe') exitImmediately ExitSuccess closeFd wpipe hndl <- fdToHandle rpipe errors <- hGetContents hndl ecode <- if null errors then return ExitSuccess else do hPutStrLn stderr $ daemonStartupErr errors return $ ExitFailure C.exitFailure exitImmediately ecode -- | Generic daemon startup. genericMain :: GanetiDaemon -- ^ The daemon we're running -> [OptType] -- ^ The available options -> CheckFn a -- ^ Check function -> PrepFn a b -- ^ Prepare function -> MainFn a b -- ^ Execution function -> IO () genericMain daemon options check_fn prep_fn exec_fn = do let progname = daemonName daemon (opts, args) <- parseArgs progname options ensureNode daemon exitUnless (null args) "This program doesn't take any arguments" unless (optNoUserChecks opts) $ do runtimeEnts <- getEnts ents <- exitIfBad "Can't find required user/groups" runtimeEnts verifyDaemonUser daemon ents syslog <- case optSyslogUsage opts of Nothing -> exitIfBad "Invalid cluster syslog setting" $ syslogUsageFromRaw C.syslogUsage Just v -> return v log_file <- daemonLogFile daemon -- run the check function and optionally exit if it returns an exit code check_result <- check_fn opts check_result' <- case check_result of Left code -> exitWith code Right v -> return v let processFn = if optDaemonize opts then daemonize log_file else \action -> action Nothing processFn $ innerMain daemon opts syslog check_result' prep_fn exec_fn -- | Full prepare function. -- -- This is executed after daemonization, and sets up both the log -- files (a generic functionality) and the custom prepare function of -- the daemon. fullPrep :: GanetiDaemon -- ^ The daemon we're running -> DaemonOptions -- ^ The options structure, filled from the cmdline -> SyslogUsage -- ^ Syslog mode -> a -- ^ Check results -> PrepFn a b -- ^ Prepare function -> IO b fullPrep daemon opts syslog check_result prep_fn = do logfile <- if optDaemonize opts then return Nothing else liftM Just $ daemonLogFile daemon pidfile <- daemonPidFile daemon let dname = daemonName daemon setupLogging logfile dname (optDebug opts) True False syslog _ <- describeError "writing PID file; already locked?" Nothing (Just pidfile) $ writePidFile pidfile logNotice $ dname ++ " daemon startup" prep_fn opts check_result -- | Inner daemon function. -- -- This is executed after daemonization. innerMain :: GanetiDaemon -- ^ The daemon we're running -> DaemonOptions -- ^ The options structure, filled from the cmdline -> SyslogUsage -- ^ Syslog mode -> a -- ^ Check results -> PrepFn a b -- ^ Prepare function -> MainFn a b -- ^ Execution function -> Maybe Fd -- ^ Error reporting function -> IO () innerMain daemon opts syslog check_result prep_fn exec_fn fd = do prep_result <- fullPrep daemon opts syslog check_result prep_fn `Control.Exception.catch` handlePrepErr True fd -- no error reported, we should now close the fd maybeCloseFd fd exec_fn opts check_result prep_result -- | Daemon prepare error handling function. handlePrepErr :: Bool -> Maybe Fd -> IOError -> IO a handlePrepErr logging_setup fd err = do let msg = show err case fd of -- explicitly writing to the fd directly, since when forking it's -- better (safer) than trying to convert this into a full handle Just fd' -> fdWrite fd' msg >> return () Nothing -> hPutStrLn stderr (daemonStartupErr msg) when logging_setup $ logError msg exitWith $ ExitFailure 1 -- | Close a file descriptor. maybeCloseFd :: Maybe Fd -> IO () maybeCloseFd Nothing = return () maybeCloseFd (Just fd) = closeFd fd
narurien/ganeti-ceph
src/Ganeti/Daemon.hs
gpl-2.0
14,817
0
16
3,429
3,142
1,633
1,509
304
4
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} -- | This is the main module of Yi, called with configuration from the user. -- Here we mainly process command line arguments. module Yi.Main ( -- * Static main main, -- * Command line processing do_args, ConsoleConfig(..), ) where import Control.Monad import Data.Char import Data.Monoid import qualified Data.Text as T import Data.List (intercalate) import Data.Version (showVersion) import Lens.Micro.Platform (view) import System.Console.GetOpt import System.Exit #ifndef HLINT #include "ghcconfig.h" #endif import Yi.Buffer import Yi.Config import Yi.Core (startEditor) import Yi.Debug import Yi.Editor import Yi.File import Yi.Keymap import Yi.Option (YiOption, OptionError(..), yiCustomOptions) import Yi.Paths (getConfigDir) import Paths_yi_core -- | Configuration information which can be set in the command-line, but not -- in the user's configuration file. data ConsoleConfig = ConsoleConfig { ghcOptions :: [String], selfCheck :: Bool, userConfigDir :: IO FilePath } defaultConsoleConfig :: ConsoleConfig defaultConsoleConfig = ConsoleConfig { ghcOptions = [], selfCheck = False, userConfigDir = Yi.Paths.getConfigDir } -- --------------------------------------------------------------------- -- | Argument parsing. Pretty standard. data Opts = Help | Version | LineNo String | EditorNm String | File String | Frontend String | ConfigFile String | SelfCheck | GhcOption String | Debug | OpenInTabs | CustomNoArg YiOption | CustomReqArg (String -> YiOption) String | CustomOptArg (Maybe String -> YiOption) (Maybe String) -- | List of editors for which we provide an emulation. editors :: [(String,Config -> Config)] editors = [] builtinOptions :: [OptDescr Opts] builtinOptions = [ Option [] ["self-check"] (NoArg SelfCheck) "Run self-checks" , Option ['f'] ["frontend"] (ReqArg Frontend "FRONTEND") frontendHelp , Option ['y'] ["config-file"] (ReqArg ConfigFile "PATH") "Specify a folder containing a configuration yi.hs file" , Option ['V'] ["version"] (NoArg Version) "Show version information" , Option ['h'] ["help"] (NoArg Help) "Show this help" , Option [] ["debug"] (NoArg Debug) "Write debug information in a log file" , Option ['l'] ["line"] (ReqArg LineNo "NUM") "Start on line number" , Option [] ["as"] (ReqArg EditorNm "EDITOR") editorHelp , Option [] ["ghc-option"] (ReqArg GhcOption "OPTION") "Specify option to pass to ghc when compiling configuration file" , Option [openInTabsShort] [openInTabsLong] (NoArg OpenInTabs) "Open files in tabs" ] where frontendHelp = "Select frontend" editorHelp = "Start with editor keymap, where editor is one of:\n" ++ (intercalate ", " . fmap fst) editors convertCustomOption :: OptDescr YiOption -> OptDescr Opts convertCustomOption (Option short long desc help) = Option short long desc' help where desc' = convertCustomArgDesc desc convertCustomArgDesc :: ArgDescr YiOption -> ArgDescr Opts convertCustomArgDesc (NoArg o) = NoArg (CustomNoArg o) convertCustomArgDesc (ReqArg f s) = ReqArg (CustomReqArg f) s convertCustomArgDesc (OptArg f s) = OptArg (CustomOptArg f) s customOptions :: Config -> [OptDescr Opts] customOptions = fmap convertCustomOption . view yiCustomOptions openInTabsShort :: Char openInTabsShort = 'p' openInTabsLong :: String openInTabsLong = "open-in-tabs" -- | usage string. usage :: [OptDescr Opts] -> T.Text usage opts = T.pack $ usageInfo "Usage: yi [option...] [file]" opts versinfo :: T.Text versinfo = "yi " <> T.pack (showVersion version) -- | Transform the config with options do_args :: Bool -> Config -> [String] -> Either OptionError (Config, ConsoleConfig) do_args ignoreUnknown cfg args = let options = customOptions cfg ++ builtinOptions in case getOpt' (ReturnInOrder File) options args of (os, [], [], []) -> handle options os (os, _, u:us, []) -> if ignoreUnknown then handle options os else Prelude.error $ "unknown arguments: " ++ intercalate ", " (u:us) (_os, _ex, _ey, errs) -> Prelude.error (concat errs) where shouldOpenInTabs = ("--" ++ openInTabsLong) `elem` args || ('-':[openInTabsShort]) `elem` args handle options os = foldM (getConfig options shouldOpenInTabs) (cfg, defaultConsoleConfig) (reverse os) -- | Update the default configuration based on a command-line option. getConfig :: [OptDescr Opts] -> Bool -> (Config, ConsoleConfig) -> Opts -> Either OptionError (Config, ConsoleConfig) getConfig options shouldOpenInTabs (cfg, cfgcon) opt = case opt of Frontend _ -> Prelude.error "Panic: frontend not found" Help -> Left $ OptionError (usage options) ExitSuccess Version -> Left $ OptionError versinfo ExitSuccess Debug -> return (cfg { debugMode = True }, cfgcon) LineNo l -> case startActions cfg of x : xs -> return (cfg { startActions = x:makeAction (gotoLn (read l)):xs }, cfgcon) [] -> Prelude.error "The `-l' option must come after a file argument" File filename -> if shouldOpenInTabs && not (null (startActions cfg)) then prependActions [YiA $ openNewFile filename, EditorA newTabE] else prependAction $ openNewFile filename EditorNm emul -> case lookup (fmap toLower emul) editors of Just modifyCfg -> return (modifyCfg cfg, cfgcon) Nothing -> Prelude.error $ "Unknown emulation: " ++ show emul GhcOption ghcOpt -> return (cfg, cfgcon { ghcOptions = ghcOptions cfgcon ++ [ghcOpt] }) ConfigFile f -> return (cfg, cfgcon { userConfigDir = return f }) CustomNoArg o -> do cfg' <- o cfg return (cfg', cfgcon) CustomReqArg f s -> do cfg' <- f s cfg return (cfg', cfgcon) CustomOptArg f s -> do cfg' <- f s cfg return (cfg', cfgcon) _ -> return (cfg, cfgcon) where prependActions as = return (cfg { startActions = fmap makeAction as ++ startActions cfg }, cfgcon) prependAction a = return (cfg { startActions = makeAction a : startActions cfg}, cfgcon) -- --------------------------------------------------------------------- -- | Static main. This is the front end to the statically linked -- application, and the real front end, in a sense. 'dynamic_main' calls -- this after setting preferences passed from the boot loader. -- main :: (Config, ConsoleConfig) -> Maybe Editor -> IO () main (cfg, _cfgcon) state = do when (debugMode cfg) $ initDebug ".yi.dbg" startEditor cfg state
yi-editor/yi
yi-dynamic-configuration/src/Yi/Main.hs
gpl-2.0
7,256
0
21
1,912
1,866
999
867
130
16
{- | Module : $Header$ Description : parser for CASL architectural specifications Copyright : (c) Maciek Makowski, Warsaw University 2003-2004, C. Maeder License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : non-portable (via imports) Parser for CASL architectural specifications Follows Sect. II:3.1.4 of the CASL Reference Manual plus refinement extensions -} module Syntax.Parse_AS_Architecture ( unitSpec , refSpec , annotedArchSpec ) where import Logic.Grothendieck (LogicGraph) import Syntax.AS_Structured import Syntax.AS_Architecture import Syntax.Parse_AS_Structured (hetIRI, annoParser2, groupSpec, parseMapping, translationList) import Common.AS_Annotation import Common.AnnoState import Common.Id import Common.IRI import Common.Keywords import Common.Lexer import Common.Token import Text.ParserCombinators.Parsec -- * Parsing functions -- | Parse annotated architectural specification annotedArchSpec :: LogicGraph -> AParser st (Annoted ARCH_SPEC) annotedArchSpec = annoParser2 . archSpec {- | Parse architectural specification @ ARCH-SPEC ::= BASIC-ARCH-SPEC | GROUP-ARCH-SPEC @ -} archSpec :: LogicGraph -> AParser st (Annoted ARCH_SPEC) archSpec l = basicArchSpec l <|> groupArchSpec l {- | Parse group architectural specification @ GROUP-ARCH-SPEC ::= { ARCH-SPEC } | ARCH-SPEC-NAME @ -} groupArchSpec :: LogicGraph -> AParser st (Annoted ARCH_SPEC) groupArchSpec l = do kOpBr <- oBraceT asp <- annoParser $ archSpec l kClBr <- cBraceT return $ replaceAnnoted (Group_arch_spec (item asp) $ toRange kOpBr [] kClBr) asp <|> fmap (emptyAnno . Arch_spec_name) (hetIRI l) {- | Parse basic architectural specification @ BASIC-ARCH-SPEC ::= unit/units UNIT-DECL-DEFNS result UNIT-EXPRESSION ;/ @ -} basicArchSpec :: LogicGraph -> AParser st (Annoted ARCH_SPEC) basicArchSpec l = do kUnit <- pluralKeyword unitS (declDefn, ps) <- auxItemList [resultS] [] (unitDeclDefn l) (,) kResult <- asKey resultS expr <- annoParser2 $ unitExpr l (m, an) <- optSemi return $ emptyAnno $ Basic_arch_spec declDefn (appendAnno expr an) $ tokPos kUnit `appRange` ps `appRange` catRange (kResult : m) {- | Parse unit declaration or definition @ UNIT-DECL-DEFN ::= UNIT-DECL | UNIT-DEFN @ -} unitDeclDefn :: LogicGraph -> AParser st UNIT_DECL_DEFN unitDeclDefn l = do name <- hetIRI l do c <- colonT -- unit declaration decl <- refSpec l (gs, ps) <- option ([], []) $ do kGiven <- asKey givenS (guts, qs) <- groupUnitTerm l `separatedBy` anComma return (guts, kGiven : qs) return $ Unit_decl name decl gs $ catRange $ c : ps <|> -- unit definition unitDefn' l name {- | Parse unit declaration @ UNIT-REF ::= UNIT-NAME : REF-SPEC @ -} unitRef :: LogicGraph -> AParser st UNIT_REF unitRef l = do name <- hetIRI l sep1 <- asKey toS usp <- refSpec l return $ Unit_ref name usp $ tokPos sep1 {- | Parse unit specification @ UNIT-SPEC ::= GROUP-SPEC GROUP-SPEC * .. * GROUP-SPEC -> GROUP-SPEC closed UNIT-SPEC @ -} unitSpec :: LogicGraph -> AParser st UNIT_SPEC unitSpec l = -- closed unit spec do kClosed <- asKey closedS uSpec <- unitSpec l return $ Closed_unit_spec uSpec $ tokPos kClosed <|> {- unit type NOTE: this can also be a spec name. If this is the case, this unit spec will be converted on the static analysis stage. See Static.AnalysisArchitecture.ana_UNIT_SPEC. -} do gps@(gs : gss, _) <- annoParser (groupSpec l) `separatedBy` crossT let rest = unitRestType l gps if null gss then option ( {- case item gs of Spec_inst sn [] _ -> Spec_name sn -- annotations are lost _ -> -} Unit_type [] gs nullRange) rest else rest unitRestType :: LogicGraph -> ([Annoted SPEC], [Token]) -> AParser st UNIT_SPEC unitRestType l (gs, ps) = do a <- asKey funS g <- annoParser $ groupSpec l return (Unit_type gs g $ catRange (ps ++ [a])) refSpec :: LogicGraph -> AParser st REF_SPEC refSpec l = do (rs, ps) <- basicRefSpec l `separatedBy` asKey thenS return $ if isSingle rs then head rs else Compose_ref rs $ catRange ps {- | Parse refinement specification @ REF-SPEC ::= UNIT_SPEC UNIT_SPEC [bahav..] refined [via SYMB-MAP-ITEMS*] to REF-SPEC arch spec GROUP-ARCH-SPEC { UNIT-DECL, ..., UNIT-DECL } @ -} basicRefSpec :: LogicGraph -> AParser st REF_SPEC basicRefSpec l = -- component spec do o <- oBraceT `followedWith` (simpleId >> asKey toS) (us, ps) <- unitRef l `separatedBy` anComma c <- cBraceT return (Component_ref us $ toRange c ps o) <|> -- architectural spec do kArch <- asKey archS kSpec <- asKey specS asp <- groupArchSpec l return (Arch_unit_spec asp (toRange kArch [] kSpec)) <|> -- unit spec do uSpec <- unitSpec l refinedRestSpec l uSpec <|> return (Unit_spec uSpec) refinedRestSpec :: LogicGraph -> UNIT_SPEC -> AParser st REF_SPEC refinedRestSpec l u = do b <- asKey behaviourallyS onlyRefinedRestSpec l (tokPos b) u <|> onlyRefinedRestSpec l nullRange u onlyRefinedRestSpec :: LogicGraph -> Range -> UNIT_SPEC -> AParser st REF_SPEC onlyRefinedRestSpec l b u = do r <- asKey refinedS (ms, ps) <- option ([], []) $ do v <- asKey viaS -- not a keyword (m, ts) <- parseMapping l return (m, v : ts) t <- asKey toS rsp <- refSpec l return $ Refinement (isNullRange b) u ms rsp (b `appRange` toRange r ps t) {- | Parse group unit term @ GROUP-UNIT-TERM ::= UNIT-NAME UNIT-NAME FIT-ARG-UNITS { UNIT-TERM } @ -} groupUnitTerm :: LogicGraph -> AParser st (Annoted UNIT_TERM) groupUnitTerm l = annoParser $ -- unit name/application do name <- hetIRI l args <- many (fitArgUnit l) return (Unit_appl name args nullRange) <|> -- unit term in brackets do lbr <- oBraceT ut <- unitTerm l rbr <- cBraceT return (Group_unit_term ut (catRange [lbr, rbr])) {- | Parse an argument for unit application. @ FIT-ARG-UNIT ::= [ UNIT-TERM ] [ UNIT-TERM fit SYMB-MAP-ITEMS-LIST ] @ The SYMB-MAP-ITEMS-LIST is parsed using parseItemsMap. -} fitArgUnit :: LogicGraph -> AParser st FIT_ARG_UNIT fitArgUnit l = do o <- oBracketT ut <- unitTerm l (fargs, qs) <- option ([], []) $ do kFit <- asKey fitS (smis, ps) <- parseMapping l return (smis, kFit : ps) c <- cBracketT return $ Fit_arg_unit ut fargs $ toRange o qs c {- | Parse unit term. @ UNIT-TERM ::= UNIT-TERM RENAMING UNIT-TERM RESTRICTION UNIT-TERM and ... and UNIT-TERM local UNIT-DEFNS within UNIT-TERM GROUP-UNIT-TERM @ This will be done by subsequent functions in order to preserve the operator precedence; see other 'unitTerm*' functions. -} unitTerm :: LogicGraph -> AParser st (Annoted UNIT_TERM) unitTerm = unitTermAmalgamation {- | Parse unit amalgamation. @ UNIT-TERM-AMALGAMATION ::= UNIT-TERM-LOCAL and ... and UNIT-TERM-LOCAL @ -} unitTermAmalgamation :: LogicGraph -> AParser st (Annoted UNIT_TERM) unitTermAmalgamation l = do (uts, toks) <- annoParser2 (unitTermLocal l) `separatedBy` asKey andS return $ case uts of [ut] -> ut _ -> emptyAnno $ Amalgamation uts $ catRange toks {- | Parse local unit term @ UNIT-TERM-LOCAL ::= local UNIT-DEFNS within UNIT-TERM-LOCAL UNIT-TERM-TRANS-RED @ -} unitTermLocal :: LogicGraph -> AParser st (Annoted UNIT_TERM) unitTermLocal l = -- local unit do kLocal <- asKey localS (uDefns, ps) <- auxItemList [withinS] [] (unitDefn l) (,) kWithin <- asKey withinS uTerm <- unitTermLocal l return $ emptyAnno $ Local_unit uDefns uTerm $ tokPos kLocal `appRange` ps `appRange` tokPos kWithin <|> -- translation/reduction unitTermTransRed l {- | Parse translation or reduction unit term The original grammar @ UNIT-TERM-TRANS-RED ::= UNIT-TERM-TRANS-RED RENAMING UNIT-TERM-TRANS-RED RESTRICTION GROUP-UNIT-TERM @ -} unitTermTransRed :: LogicGraph -> AParser st (Annoted UNIT_TERM) unitTermTransRed l = groupUnitTerm l >>= translationList l Unit_translation Unit_reduction (error "approximate not allowed in architectural specifications") (error "minimize not allowed in architectural specifications") {- | Parse unit expression @ UNIT-EXPRESSION ::= lambda UNIT-BINDINGS "." UNIT-TERM UNIT-TERM @ -} unitExpr :: LogicGraph -> AParser st (Annoted UNIT_EXPRESSION) unitExpr l = do (bindings, poss) <- option ([], nullRange) $ do kLambda <- asKey lambdaS (bindings, poss) <- unitBinding l `separatedBy` anSemi kDot <- dotT return (bindings, toRange kLambda poss kDot) ut <- unitTerm l return $ emptyAnno $ Unit_expression bindings ut poss {- | Parse unit binding @ UNIT-BINDING ::= UNIT-NAME : UNIT-SPEC @ -} unitBinding :: LogicGraph -> AParser st UNIT_BINDING unitBinding l = do name <- hetIRI l kCol <- colonT usp <- unitSpec l return $ Unit_binding name usp $ tokPos kCol {- | Parse an unit definition @ UNIT-DEFN ::= UNIT-NAME = UNIT-EXPRESSION @ -} unitDefn :: LogicGraph -> AParser st UNIT_DECL_DEFN unitDefn l = hetIRI l >>= unitDefn' l unitDefn' :: LogicGraph -> IRI -> AParser st UNIT_DECL_DEFN unitDefn' l name = do kEqu <- equalT expr <- annoParser2 $ unitExpr l return $ Unit_defn name (item expr) $ tokPos kEqu
nevrenato/HetsAlloy
Syntax/Parse_AS_Architecture.hs
gpl-2.0
9,435
0
16
2,038
2,378
1,165
1,213
170
2
{-# LANGUAGE OverlappingInstances, TemplateHaskell, DeriveDataTypeable #-} module Prolog.Programming.Data where import Autolib.ToDoc (ToDoc(..), vcat, text, nest) import Autolib.Reader import Autolib.Size import Data.Typeable import Language.Prolog (term, Term) import Text.Parsec import Control.Applicative ((<$>),(<*>),(<*)) data Facts = Facts String deriving ( Eq, Ord, Typeable, Read, Show ) data Config = Config String deriving ( Eq, Ord, Typeable, Read, Show ) instance Reader Facts where reader = do { cs <- getInput; setInput ""; return (Facts cs) } instance Reader Config where reader = do { cs <- getInput; setInput ""; return (Config cs) } instance ToDoc Facts where toDoc (Facts cs) = vcat (map text $ lines cs) instance ToDoc Config where toDoc (Config cs) = text cs -- FIXME: should use the size of the syntax tree instance Size Facts where size (Facts cs) = length cs instance Size Config where size (Config cs) = length cs
Erdwolf/autotool-bonn
src/Prolog/Programming/Data.hs
gpl-2.0
973
0
10
178
348
188
160
23
0
module Direction where data Direction = NORTH | WEST | SOUTH | EAST deriving (Show,Read)
FiskerLars/2048.hs
Direction.hs
gpl-2.0
150
0
6
76
31
19
12
6
0
{-# LANGUAGE Arrows #-} module SD ( runSD ) where import FRP.Yampa runSD :: Double -> Double -> Double -> Double -> Double -> Time -> DTime -> [(Double, Double, Double)] runSD populationSize infectedCount contactRate infectivity illnessDuration t dt = embed sir ((), steps) where steps = replicate (floor $ t / dt) (dt, Nothing) sir :: SF () (Double, Double, Double) sir = loopPre (initSus, initInf, initRec) sir' where initSus = populationSize - infectedCount initInf = infectedCount initRec = 0 sir' :: SF ((), (Double, Double, Double)) ((Double, Double, Double), (Double, Double, Double)) sir' = proc (_, (s, i, _r)) -> do let infectionRate = (i * contactRate * s * infectivity) / populationSize let recoveryRate = i / illnessDuration s' <- (initSus+) ^<< integral -< (-infectionRate) i' <- (initInf+) ^<< integral -< (infectionRate - recoveryRate) r' <- (initRec+) ^<< integral -< recoveryRate returnA -< dupe (s', i', r') dupe :: a -> (a, a) dupe a = (a, a)
thalerjonathan/phd
coding/papers/pfe/testing/src/SD.hs
gpl-3.0
1,235
1
19
433
420
235
185
39
1
{-# LANGUAGE OverloadedStrings #-} module Database.Hedsql.Tests.PrettyPrint ( tests ) where -------------------------------------------------------------------------------- -- IMPORTS -------------------------------------------------------------------------------- import Database.Hedsql.Examples.Create import Database.Hedsql.Examples.Delete import Database.Hedsql.Examples.Insert as Insert import Database.Hedsql.Examples.Select import Database.Hedsql.Examples.Update import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit hiding (Test) import qualified Database.Hedsql.SqLite as S -------------------------------------------------------------------------------- -- PRIVATE -------------------------------------------------------------------------------- -- SELECT testSelectStruct :: Test testSelectStruct = testCase "Basic SELECT structure" assertSelect where assertSelect :: Assertion assertSelect = assertEqual "SELECT structure is incorrect." "SELECT *\n\ \FROM \"People\"\n\ \WHERE \"age\" > 18\n\ \GROUP BY \"lastName\"\n\ \HAVING SUM(\"age\") > 100\n\ \ORDER BY \"id\"\n\ \LIMIT 30 OFFSET 2" (S.codeGenP selectFull) testSelectOneCol :: Test testSelectOneCol = testCase "SELECT with one column" assertSelect where assertSelect :: Assertion assertSelect = assertEqual "SELECT with one column is incorrect." "SELECT *\n\ \FROM \"People\"" (S.codeGenP selectAll) testSelectTwoCols :: Test testSelectTwoCols = testCase "SELECT with two columns" assertSelect where assertSelect :: Assertion assertSelect = assertEqual "SELECT with two columns is incorrect." "SELECT\n\ \ \"firstName\",\n\ \ \"lastName\"\n\ \FROM \"People\"" (S.codeGenP selectTwoCols) testSelectCombinedOne :: Test testSelectCombinedOne = testCase "Combined SELECT statement with one combination" assertSelect where assertSelect :: Assertion assertSelect = assertEqual "Combined SELECT statement with one combination is incorrect." "SELECT *\n\ \FROM \"People\"\n\ \WHERE \"personId\" = 1\n\ \UNION\n\ \SELECT *\n\ \FROM \"People\"\n\ \WHERE \"personId\" = 2" (S.codeGenP unionQuery) testJoin :: Test testJoin = testCase "SELECT with a join clause" assertSelect where assertSelect :: Assertion assertSelect = assertEqual "SELECT with a join clause is incorrect." "SELECT *\n\ \FROM \"People\"\n\ \INNER JOIN \"Countries\"\n\ \ON \"People\".\"countryId\" = \"Countries\".\"countryId\"" (S.codeGenP fromInnerJoinOn) testNestedJoins :: Test testNestedJoins = testCase "SELECT with a nested join clause" assertSelect where assertSelect :: Assertion assertSelect = assertEqual "SELECT with a nested join clause is incorrect." "SELECT *\n\ \FROM \"People\"\n\ \INNER JOIN \"Countries\"\n\ \ON \"People\".\"countryId\" = \"Countries\".\"countryId\"\n\ \INNER JOIN \"Addresses\"\n\ \ON \"People\".\"personId\" = \"Addresses\".\"personId\"" (S.codeGenP nestedJoins) testSubQueryFrom :: Test testSubQueryFrom = testCase "FROM with a sub-query." assertSelect where assertSelect :: Assertion assertSelect = assertEqual "FROM with a sub-query is incorrect." "SELECT *\n\ \FROM (SELECT *\n\ \ FROM \"People\") AS \"P\"" (S.codeGenP selectSubQuery) testSubQueryWhere :: Test testSubQueryWhere = testCase "WHERE with a sub-query." assertSelect where assertSelect :: Assertion assertSelect = assertEqual "WHERE with a sub-query is incorrect." "SELECT *\n\ \FROM \"People\"\n\ \WHERE \"countryId\" IN (SELECT \"countryId\"\n\ \ FROM \"Countries\"\n\ \ WHERE \"inhabitants\" >= \"size\" * 100)" (S.codeGenP whereInSelect) testWhereAnd :: Test testWhereAnd = testCase "WHERE with an AND clause." assertSelect where assertSelect :: Assertion assertSelect = assertEqual "WHERE with an AND clause is incorrect." "SELECT *\n\ \FROM\n\ \ \"People\",\n\ \ \"Countries\"\n\ \WHERE\n\ \ \"People\".\"countryId\" = \"Countries\".\"countryId\"\n\ \ AND \"People\".\"age\" > 18" (S.codeGenP whereAnd) testWhereAnds :: Test testWhereAnds = testCase "WHERE with two AND clauses." assertSelect where assertSelect :: Assertion assertSelect = assertEqual "WHERE with two AND clauses is incorrect." "SELECT *\n\ \FROM\n\ \ \"People\",\n\ \ \"Countries\"\n\ \WHERE\n\ \ \"People\".\"countryId\" = \"Countries\".\"countryId\"\n\ \ AND \"People\".\"age\" > 18\n\ \ AND \"People\".\"age\" < 70" (S.codeGenP whereAnds) testGroupByOne :: Test testGroupByOne = testCase "GROUP BY with one column" assertSelect where assertSelect :: Assertion assertSelect = assertEqual "GROUP BY with one column is incorrect." "SELECT \"age\"\n\ \FROM \"People\"\n\ \GROUP BY \"age\"" (S.codeGenP selectGroupBy) testGroupByTwo :: Test testGroupByTwo = testCase "GROUP BY with two columns" assertSelect where assertSelect :: Assertion assertSelect = assertEqual "GROUP BY with two columns is incorrect." "SELECT\n\ \ \"firstName\",\n\ \ \"age\"\n\ \FROM \"People\"\n\ \GROUP BY\n\ \ \"firstName\",\n\ \ \"age\"" (S.codeGenP groupByTwo) testHavingOne :: Test testHavingOne = testCase "Having with one condition" assertSelect where assertSelect :: Assertion assertSelect = assertEqual "Having with one condition is incorrect." "SELECT\n\ \ \"lastName\",\n\ \ SUM(\"age\")\n\ \FROM \"People\"\n\ \GROUP BY \"lastName\"\n\ \HAVING SUM(\"age\") > 18" (S.codeGenP groupBySumHaving) testHavingTwo :: Test testHavingTwo = testCase "Having with two conditions" assertSelect where assertSelect :: Assertion assertSelect = assertEqual "Having with two conditions is incorrect." "SELECT \"firstName\"\n\ \FROM \"People\"\n\ \GROUP BY \"firstName\"\n\ \HAVING\n\ \ SUM(\"age\") > 18\n\ \ OR SUM(\"size\") < 1800" (S.codeGenP groupBySumHavingTwo) testOrderByOne :: Test testOrderByOne = testCase "ORDER BY with one column" assertSelect where assertSelect :: Assertion assertSelect = assertEqual "ORDER BY with one column is incorrect." "SELECT \"firstName\"\n\ \FROM \"People\"\n\ \ORDER BY \"firstName\"" (S.codeGenP orderByQuery) testOrderByTwo :: Test testOrderByTwo = testCase "ORDER BY with two columns" assertSelect where assertSelect :: Assertion assertSelect = assertEqual "ORDER BY with two columns is incorrect." "SELECT\n\ \ \"firstName\",\n\ \ \"lastName\"\n\ \FROM \"People\"\n\ \ORDER BY\n\ \ \"firstName\" ASC,\n\ \ \"lastName\" DESC" (S.codeGenP orderByAscDesc) testLimit :: Test testLimit = testCase "LIMIT clause." assertSelect where assertSelect :: Assertion assertSelect = assertEqual "LIMIT clause is incorrect." "SELECT *\n\ \FROM \"People\"\n\ \ORDER BY \"firstName\"\n\ \LIMIT 2" (S.codeGenP orderByLimit) testOffset :: Test testOffset = testCase "OFFSET clause." assertSelect where assertSelect :: Assertion assertSelect = assertEqual "OFFSET clause is incorrect." "SELECT *\n\ \FROM \"People\"\n\ \ORDER BY \"firstName\"\n\ \OFFSET 2" (S.codeGenP orderByOffset) testLimitOffset :: Test testLimitOffset = testCase "LIMIT and OFFSET clauses." assertSelect where assertSelect :: Assertion assertSelect = assertEqual "LIMIT and OFFSET clauses are incorrect." "SELECT *\n\ \FROM \"People\"\n\ \ORDER BY \"firstName\"\n\ \LIMIT 5 OFFSET 2" (S.codeGenP orderByLimitOffset) -- CREATE testCreate :: Test testCreate = testCase "CREATE statement." assertCreate where assertCreate :: Assertion assertCreate = assertEqual "CREATE statement incorrect." "CREATE TABLE \"Countries\" (\n\ \ \"countryId\" INTEGER PRIMARY KEY AUTOINCREMENT,\n\ \ \"name\" VARCHAR(256) NOT NULL, UNIQUE,\n\ \ \"size\" INTEGER,\n\ \ \"inhabitants\" INTEGER\n\ \)" (S.codeGenP countries) -- UPDATE testUpdate :: Test testUpdate = testCase "UPDATE statement." assertUpdate where assertUpdate :: Assertion assertUpdate = assertEqual "UPDATE statement incorrect." "UPDATE \"People\"\n\ \SET \"age\" = 2050\n\ \WHERE \"lastName\" = 'Ceasar'" (S.codeGenP equalTo) -- DELETE testDelete :: Test testDelete = testCase "DELETE statement." assertDelete where assertDelete :: Assertion assertDelete = assertEqual "DELETE statement incorrect." "DELETE FROM \"People\"\n\ \WHERE \"age\" <> 20" (S.codeGenP deleteNotEqualTo) -- INSERT testInsert :: Test testInsert = testCase "INSERT statement." assertInsert where assertInsert :: Assertion assertInsert = assertEqual "Insert statement incorrect." "INSERT INTO \"People\" (\n\ \ \"firstName\",\n\ \ \"lastName\",\n\ \ \"age\",\n\ \ \"passportNo\",\n\ \ \"countryId\")\n\ \VALUES (\n\ \ 'Julius',\n\ \ 'Ceasar',\n\ \ 2000,\n\ \ NULL,\n\ \ 2)" (S.codeGenP Insert.defaultVal) -------------------------------------------------------------------------------- -- PUBLIC -------------------------------------------------------------------------------- -- | Gather all tests. tests :: Test tests = testGroup "Pretty Print" [ testSelectStruct , testSelectOneCol , testSelectTwoCols , testSelectCombinedOne , testJoin , testNestedJoins , testSubQueryFrom , testSubQueryWhere , testWhereAnd , testWhereAnds , testGroupByOne , testGroupByTwo , testHavingOne , testHavingTwo , testOrderByOne , testOrderByTwo , testLimit , testOffset , testLimitOffset , testCreate , testUpdate , testDelete , testInsert ]
momomimachli/Hedsql-tests
src/Database/Hedsql/Tests/PrettyPrint.hs
gpl-3.0
11,864
0
10
3,924
1,163
643
520
218
1
-- split a list to two with sizes n p17 :: [a] -> Int -> ([a],[a]) p17 (x:xs) n | n > 0 = let (f,l) = p17 xs (n-1) in (x:f,l) p17 xs _ = ([],xs)
yalpul/CENG242
H99/11-20/p17.hs
gpl-3.0
172
0
12
64
115
62
53
5
1
module HW01.Hanoi where import qualified Data.Map as HM import qualified Data.Maybe as M --import qualified Debug.Trace as D {- Zadání: To move n discs (stacked in increasing size) from peg a to peg b using peg c as temporary storage, 1. move n-1 discs from a to c using b as a temporary storage 2. move the top disc from a to b 3. move n-1 discs from c to b using a as a temporary storage Given the number of discs and names for the three pegs, hanoi should return a list of moves to be performed to move the stack of discs from the first peg to the second. -} data Peg = P1 | P2 | P3 | P4 deriving (Eq, Ord, Show) type Move = (Peg, Peg) hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] -- base case, když už máme jen jeden disk, můžeme -- ho bez dalšího přesunout na cílový kolík hanoi 1 ini tgt _ = [(ini, tgt)] hanoi n ini tgt tmp = -- odložit n-1, pro další úroveň prohodí tgt s tmp, -- takže naším novým cílem pro n-1 je tmp hanoi (n-1) ini tmp tgt -- umístit zbývající disk -- směřuje k momentálnímu -- cíli na stávájící úrovni ++ hanoi 1 ini tgt nil -- restart, pro další úroveň - ponechá tgt, ale prohodí -- ini s tmp, protože tam jsme si výše odložili disky ++ hanoi (n-1) tmp tgt ini nil :: a nil = undefined {- V každém rekurzívním kroku se určitým způsobem zamění výchozí (ini), cílový (tgt) a odkládací (tmp) kolík, takže nový krok má odlišný pohled na situaci. Rekurze je několikanásobná, v jednom kroku voláme 3x sami sebe. Jak ten algoritmus zaručí, že řešení směřuje k umístění na určený cílový kolík, když se pohled mění v každém kroku? Musí to spočívat v jeho systematičnosti, je to tam implicitně zakódované. Ale jak? Je to dáno tím, že jednotlivé rekurzívní kroky na dané úrovni probíhají jeden za druhým a vždy se nejdříve odloží n-1 na tmp, pak se zbývající disk umístí na tgt. Třetí rekurzívní volání pak celý postup zopakuje pro úroveň n-1 s tím, že tgt zůstává pořád stejný. Díky tomu celý postup směřuje k přesunu na kolík tgt. Zkusím si projít vyhodnocení pro malý počet disků, řekněme 5. hanoi 5 p1 p3 p2 -- chceme se dostat z p1 na p3 a požít p2 na odkládání hanoi 4 p1 p2 p3 -- při postupu na nižší úroveň se prohodí 2 a 3 hanoi 3 p1 p3 p2 -- a znovu... hanoi 2 p1 p2 p3 -- atd. hanoi 1 p1 p3 p2 -- když je n=1, tak teprve začneme přesunovat disky, 1>>3 hanoi 1 p1 p2 _ -- 1>>2 hanoi 1 p3 p2 p1 -- 3>>2 hanoi 1 p1 p3 _ -- 1>>3 hanoi 2 p2 p3 p1 hanoi 1 p2 p1 p3 -- 2>>1 hanoi 1 p2 p3 _ -- 2>>3 hanoi 1 p1 p3 p2 .. 1>>3 hanoi 1 p1 p2 _ -- 1>>2 hanoi 3 p3 p2 p1 hanoi 2 p3 p1 p2 hanoi 1 p3 p2 p1 -- 3>>2 hanoi 1 p3 p1 _ -- 3>>1 hanoi 1 p2 p1 p3 -- 2>>1 hanoi 1 p3 p2 _ -- 3>>2 hanoi 2 p1 p2 p3 hanoi 1 p1 p3 p2 -- 1>>3 hanoi 1 p1 p2 _ -- 1>>2 hanoi 1 p3 p2 p1 -- 3>>2 hanoi 1 p1 p3 _ -- 1>>3 hanoi 4 p2 p3 p1 hanoi 3 p2 p1 p3 hanoi 2 p2 p3 p1 hanoi 1 p2 p1 p3 -- 2>>1 hanoi 1 p2 p3 _ -- 2>>3 hanoi 1 p1 p3 p2 -- 1>>3 hanoi 1 p2 p1 _ -- 2>>1 hanoi 2 p3 p1 p2 hanoi 1 p3 p2 p1 -- 3>>2 hanoi 1 p3 p1 _ -- 3>>1 hanoi 1 p2 p1 p3 -- 2>>1 hanoi 1 p2 p3 _ -- 2>>3 hanoi 3 p1 p3 p2 hanoi 2 p1 p2 p3 hanoi 1 p1 p3 p2 -- 1>>3 hanoi 1 p1 p2 _ -- 1>>2 hanoi 1 p3 p2 p1 -- 3>>2 hanoi 1 p1 p3 _ -- 1>>3 hanoi 2 p2 p3 p1 hanoi 1 p2 p1 p3 -- 2>>1 hanoi 1 p2 p3 _ -- 2>>3 hanoi 1 p1 p3 p2 -- 1>>3 Je důležité si uvědomit, že jediné kroky, které opravdu přesunují disky jsou ty, které pracují s n=1. Všechny ostatní jen popisují na vyšší úrovni co se bude později dělat. Zaručuje algoritmus to, že se nepoloží větší disk na menší? Pokud ano, jak to dělá? První krok na dané úrovni odloží n-1 disků na tmp. V tu chvíli jsou buď ostatní kolíky prázdné, nebo obsahují jen větší disky, takže pravidlo je zaručeno. Další krok přesouvá největší disk na tgt, jelikož všechny ostatní (menší) disky jsme přesunuli na tmp, tak tgt je buď prázdný nebo obsahuje větší disk. Pravidlo zaručeno. Poslední krok opět přesouvá n-1 disků, tentorát z tmp na tgt za použití ini na odkládání. Všechny větší disky jsme už umístili na tgt, takže pravidlo je opět zaručeno. -} {- ToH4 Frame-Stewart algorithm - source: https://en.wikipedia.org/wiki/Tower_of_Hanoi#Frame.E2.80.93Stewart_algorithm -} hanoi4 :: Integer -> Peg -> Peg -> [Peg] -> [Move] hanoi4 1 ini tgt _ = [(ini, tgt)] hanoi4 n ini tgt (tmp1:tmp2:_) = hanoi4 k ini tmp1 [tmp2, tgt] ++ hanoi4 (n-k) ini tgt [tmp2] ++ hanoi4 k tmp1 tgt [tmp2, ini] where k = fromInteger n - (floor ((sqrt (2*fromInteger n)) + (1/2))) -- source: Corollary 3.3 in https://www2.bc.edu/~grigsbyj/Rand_Final.pdf hanoi4 n ini tgt (tmp1:_) = hanoi n ini tgt tmp1 hanoi4 _ _ _ _ = [] {- Verifikace výsledku. -> výchozí stav -> brát jeden krok za druhým a generovat další stav -> přitom ověřovat, že stav je konzistentní -> je to valstně fold -} type Disc = Int type Hanoi4State = HM.Map Peg [Disc] validate :: [Move] -> Hanoi4State -> Either String Hanoi4State validate [] state = Right state validate (m@(pFrom, pTo):ms) state | validMove = validate ms makeMove | otherwise = Left ("Invalid move: " ++ show m ++ "; state " ++ show state) where validMove = M.isNothing dTo || dFrom < dTo dFrom = M.listToMaybe $ HM.findWithDefault [] pFrom state dTo = M.listToMaybe $ HM.findWithDefault [] pTo state makeMove = HM.adjust (M.fromJust dFrom:) pTo $ HM.adjust (drop 1) pFrom state doValidate :: Either String Hanoi4State doValidate = validate (hanoi4 15 P1 P4 [P2, P3]) initialState doValidateFail :: Either String Hanoi4State doValidateFail = validate [(P1, P2), (P1, P2)] initialState initialState :: Hanoi4State initialState = HM.fromList [(P1, [1..15]), (P2, []), (P3, []), (P4, [])]
martinvlk/cis194-homeworks
src/HW01/Hanoi.hs
gpl-3.0
6,548
0
16
1,861
797
436
361
37
1
{-# LANGUAGE ScopedTypeVariables #-} import Control.Concurrent import Data.ByteString hiding (pack) import Data.ByteString.Char8 import Data.ByteString.Internal import Debug.Trace import Foreign.C.Error import System.Directory import System.Environment import System.Fuse import System.IO import System.Posix.Files import System.Posix.IO import System.Posix.IO.Extra import System.Posix.Types import System.Posix.Unistd a </> b = a ++ "/" ++ b statusToEntryType :: FileStatus -> EntryType statusToEntryType status | isRegularFile status = RegularFile | isDirectory status = Directory | isSymbolicLink status = SymbolicLink | isNamedPipe status = NamedPipe | isSocket status = Socket | isCharacterDevice status = CharacterSpecial | isBlockDevice status = BlockSpecial | otherwise = Unknown statusToStat :: FileStatus -> FileStat statusToStat status = FileStat { statEntryType = statusToEntryType status, statFileMode = fileMode status, statLinkCount = linkCount status, statFileOwner = fileOwner status, statFileGroup = fileGroup status, statSpecialDeviceID = specialDeviceID status, statFileSize = fileSize status, statBlocks = fromIntegral $ ((fileSize status - 1) `div` 512) + 1, statAccessTime = accessTime status, statModificationTime = modificationTime status, statStatusChangeTime = statusChangeTime status } fuseStat path = fmap statusToStat $ getSymbolicLinkStatus path logging str = System.IO.hPutStrLn stderr str >> System.IO.hFlush stderr cacheStat sourceDir path = do -- logging $ "statting " ++ show (sourceDir, path) -- fib 35 `seq` return () res <- fuseStat $ sourceDir </> path return $ Right res cacheReadDir sourceDir path = do files <- getDirectoryContents $ sourceDir </> path fmap Right $ mapM (\f -> do stat <- fuseStat (sourceDir </> path </> f) return (f, stat)) files cacheOpen :: FilePath -> FilePath -> OpenMode -> OpenFileFlags -> IO (Either Errno Fd) cacheOpen sourceDir path mode flags = fmap Right $ openFd (sourceDir </> path) mode Nothing flags fib 0 = 1 fib 1 = 1 fib n = fib (n - 1) + fib (n - 2) cacheRead :: FilePath -> FilePath -> Fd -> ByteCount -> FileOffset -> IO (Either Errno ByteString) cacheRead sourceDir path fd length offset = do -- logging $ "reading " ++ show (sourceDir, path) ++ " " ++ show (fib 35) fib 35 `seq` return () -- sleep 6 fmap Right $ createAndTrim (fromIntegral length) (\buf -> fmap fromIntegral $ pread fd buf (fromIntegral length) offset) -- return $ Right $ pack "Hello world\n" cacheRelease _ fd = closeFd fd identityFS sourceDir = defaultFuseOps { fuseGetFileStat = cacheStat sourceDir, fuseOpenDirectory = const $ return eOK, fuseReleaseDirectory = const $ return eOK, fuseReadDirectory = cacheReadDir sourceDir, fuseOpen = cacheOpen sourceDir, fuseRead = cacheRead sourceDir, fuseRelease = cacheRelease } main = do sourceDir:rest <- getArgs withArgs rest $ do fuseMain (identityFS sourceDir) defaultExceptionHandler
nilcons/PrefetchFS
misc/IdentityFS.hs
gpl-3.0
3,266
0
17
790
893
457
436
75
1
module Main where import System.Random import Data.Text.Encoding main::IO() main = do putStrLn "您好" gen <- newStdGen print $ mod (fst (random gen :: (Int,StdGen))) 150
Trickness/pl_learning
Haskell/random.hs
unlicense
194
4
10
40
76
40
36
8
1
module Lib where import Control.Monad (join, void) import Data.Functor (($>)) import Data.Either.Validation {- Phil Freeman https://twitter.com/paf31/status/1108518386877628416 My new favorite Haskell trick is using Compose (Validation e) IO to implement poor-man's transactions. It's Applicative for free, and you can interpret it in ExceptT e IO easily. Thanks to @fried_brice for implementing this pattern in our code at @Lumi lately! In more detail: suppose you want to perform many tasks in IO, and want it to be everything-or-nothing. Absent a transaction coordinator, you can at least do some initial verification and prepare as much work as possible, if you push the Either outside the IO. Daniel Brice: https://gist.github.com/friedbrice/18f15dad17b8fbe524c1c994823d8aeb Phil Freeman And if you used newtypes for refinements you could use Applicative to compose them: checkPickles :: Pickles -> Compose _ _ AdequatePickles checkTurkey :: Turkey -> Compose _ _ FreshTurkey ... <$> checkPickles pickles <*> checkTurkey turkey and so on :) -} doIt :: IO () doIt = do putStrLn "\n\nDOING" void (sudoMakeSandwich Person) putStrLn "DONE" ---- -- Validation (Imagine this comes from a library.) ---- runValidation :: (e -> b) -> (a -> b) -> Validation e a -> b runValidation f _ (Failure e) = f e runValidation _ g (Success x) = g x assert :: Semigroup e => e -> Bool -> Validation e () assert e p = if p then pure () else Failure e -- Whereas `Either` holds up to one error, `Validation` can hold many, because "Left" is a Monoid. ---- -- Data Layer (Imagine this talks to your database, or an API.) ---- data Person = Person deriving Show newtype Pickles = Pickles { numPickles :: Int } deriving Show newtype Mustard = Mustard { isSpicy :: Bool } deriving Show data Turkey = Turkey { freshness :: Double, numTurkey :: Int } deriving Show data Bread = Bread { moldy :: Bool , sliced :: Bool } deriving Show data Sandwich = Sandwich lookupBread :: Person -> IO Bread lookupBread _ = return $ Bread False False lookupMustard :: Person -> IO Mustard lookupMustard _ = return $ Mustard True lookupTurkey :: Person -> IO Turkey lookupTurkey _ = return $ Turkey 0.9 3 lookupPickles :: Person -> IO Pickles lookupPickles _ = return $ Pickles 2 -- These get called if values returned from lookup* are valid. -- They charge the person and update the inventory. sliceBread :: Person -> Bread -> IO () sliceBread = say updateMustard :: Person -> Mustard -> IO () updateMustard = say updateTurkey :: Person -> Turkey -> IO () updateTurkey = say updatePickles :: Person -> Pickles -> IO () updatePickles = say say :: (Show a, Show b) => a -> b -> IO () say a b = do putStr (show a); putStr " "; print b; return () ---- -- Application Layer (Here's the stuff your program does!) ---- -- `sudoMakeSandwich` gathers the data needed by `makeSandwich` and will -- either make the sandwich according to `makeSandwich`s instructions or -- will print the errors listed by `makeSandwich`. sudoMakeSandwich :: Person -> IO Sandwich sudoMakeSandwich person = do bread <- lookupBread person mustard <- lookupMustard person turkey <- lookupTurkey person pickles <- lookupPickles person join (runValidation logErrorsAndPanic pure (makeSandwich person pickles mustard turkey bread)) -- `makeSandwich` describes making a sandwich (or lists the reasons we can't) makeSandwich :: Person -> Pickles -> Mustard -> Turkey -> Bread -> Validation [String] (IO Sandwich) makeSandwich person pickles mustard turkey bread = ( assert ["Bread must not be moldy"] (not . moldy $ bread) *> assert ["Mustard must be spicy"] (isSpicy mustard) *> assert ["Turkey must be fresh"] (freshness turkey >= 0.7) *> assert ["Must have at least 2 slices of turkey"] (numTurkey turkey >= 2) *> assert ["Must have at least 2 pickles"] (numPickles pickles >= 2) ) $> (do if not (sliced bread) then sliceBread person bread -- if not already sliced, slice it else pure () updateMustard person mustard -- TODO needs an amount updateTurkey person turkey { numTurkey = numTurkey turkey - 2 , freshness = freshness turkey - 0.05 } updatePickles person pickles { numPickles = numPickles pickles - 2 } pure Sandwich ) -- Don't do this part in real life! logErrorsAndPanic :: [String] -> IO a logErrorsAndPanic errs = do putStrLn "" mapM_ putStrLn errs error "I was made to understand there were sandwiches here."
haroldcarr/learn-haskell-coq-ml-etc
haskell/playpen/2019-03-daniel-brice-compose-validation-io/src/Lib.hs
unlicense
4,613
0
14
990
1,008
519
489
79
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} ------------------------------------------------------------------------------ -- | This module defines our application's state type and an alias for its -- handler monad. module Application where ------------------------------------------------------------------------------ import Control.Lens import Model.Contract (Contract) import Model.URI (URI) import Snap ------------------------------------------------------------------------------ data App = App { _authServerURL :: URI , _maybeContract :: Maybe Contract } makeLenses ''App ------------------------------------------------------------------------------ type AppHandler = Handler App App
alexandrelucchesi/pfec
facade-server/src/Application.hs
apache-2.0
823
0
9
139
84
52
32
13
0
-- Copyright 2015 Peter Harpending -- -- Licensed under the Apache License, Version 2.0 (the "License"); you -- may not use this file except in compliance with the License. You -- may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -- implied. See the License for the specific language governing -- permissions and limitations under the License. -- | -- Module : Main -- Description : Test of editor-open -- Copyright : Copyright 2015 Peter Harpending -- License : Apache-2.0 -- Maintainer : Peter Harpending <[email protected]> -- Stability : experimental -- Portability : POSIX -- module Main where import Control.Monad.Trans.Resource (runResourceT) import qualified Data.ByteString.Lazy as B import Data.Conduit (connect, toConsumer, toProducer) import Data.Conduit.Binary (sinkHandle, sinkLbs, sourceFile, sourceLbs) import Paths_editor_open (getDataFileName) import System.Exit (ExitCode(..)) import System.IO (stdout) import Text.Editor (bracketConduit, plainTemplate) main :: IO () main = do schemaFP <- getDataFileName "res/bug-schema.yaml" result <- runResourceT (bracketConduit plainTemplate (toProducer (sourceFile schemaFP)) (toConsumer sinkLbs)) connect (sourceLbs result) (sinkHandle stdout)
pharpend/editor-open
tests/test_yaml_file_conduit.hs
apache-2.0
1,581
0
14
323
211
130
81
18
1
{-| Module: HaskHOL.Haskell.Plugin Copyright: (c) The University of Kansas 2013 LICENSE: BSD3 Maintainer: [email protected] Stability: unstable Portability: unknown -} module HaskHOL.Haskell.Plugin ( plugin ) where import Control.Monad.State import HERMIT.Context (LocalPathH) import HERMIT.Dictionary.Navigation import HERMIT.GHC (Plugin, cmpString2Var) import HERMIT.Kernel import HERMIT.Kure import HERMIT.Plugin hiding (pass) import HERMIT.Plugin.Types import HaskHOL.Haskell.Plugin.KURE import HaskHOL.Haskell.Plugin.Parser import HaskHOL.Haskell.Plugin.Transform import HaskHOL.Core import HaskHOL.Deductive import HaskHOL.Lib.Haskell.Context ctxt :: TheoryPath HaskellType ctxt = ctxtHaskell liftHOL :: HOL Proof HaskellType a -> PluginM a liftHOL = liftHOL' ctxt plugin :: Plugin plugin = hermitPlugin $ \ _ -> firstPass $ do liftIO $ putStrLn "Parsing configuration files..." tyMap <- prepConsts "types.h2h" $ liftHOL types tmMap <- prepConsts "terms.h2h" $ liftHOL constants opts <- liftIO $ optParse "config.h2h" let getOpt :: String -> String -> PluginM String getOpt lbl err = maybe (fail err) return $ lookup lbl opts -- liftIO $ putStrLn "Translating from Core to HOL..." target <- getOpt "binding" "<binding> not set in config.h2h." tm <- query Never $ do path <- bindingOfT $ cmpString2Var target localPathT path trans -- let pass :: HOLTerm -> PluginM HOLTerm pass x = do x' <- applyT (replaceType tyMap) ctxt x applyT (replaceTerm tmMap) ctxt x' cls <- getOpt "bindingType" "<bindingType> not set in config.h2h." tm' <- if cls == "ConsClass" then do cls' <- getOpt "class" "<class> not set in config.h2h." consClassPass cls' tm pass else let (bvs, bod) = stripTyAbs tm (bvs', bod') = stripAbs bod in do x <- pass bod' bvs'' <- mapM pass bvs' liftHOL $ flip (foldrM mkTyAll) bvs =<< listMkForall bvs'' x -- liftIO $ putStrLn "Proving..." prfType <- getOpt "proofType" "<proofType> not set in config.h2h." prfMod <- getOpt "proofModule" "<proofModule> not set in config.h2h." prfName <- getOpt "proofName" "<proofName> not set in config.h2h." tac <- liftHOL $ if prfType == "HOLThm" then do thm <- runHOLHint prfName [prfMod] return (tacACCEPT (thm::HOLThm)) else runHOLHint ("return " ++ prfName) [prfMod, "HaskHOL.Deductive"] liftHOL $ printHOL =<< prove tm' tac consClassPass :: String -> HOLTerm -> (HOLTerm -> PluginM HOLTerm) -> PluginM HOLTerm consClassPass cls tm pass = do liftIO $ putStrLn "Translating Arguments..." let (_, args) = stripComb tm args' <- mapM trans' args -- liftIO $ putStrLn "Building Class Instance..." monad <- liftHOL $ mkConstFull (pack cls) ([],[],[]) maybe (fail "Reconstruction of class instance failed.") return $ foldlM mkIComb monad args' where trans' :: HOLTerm -> PluginM HOLTerm trans' x@(Var name _) = pass =<< query Never (do lp <- lookupBind $ unpack name case lp of Nothing -> return x Just res -> localPathT res trans) trans' x = pass x lookupBind :: String -> TransformH LCoreTC (Maybe LocalPathH) lookupBind x = catchesT [ liftM Just . bindingOfT $ cmpString2Var x , return Nothing ] prepConsts :: String -> PluginM (Map Text b) -> PluginM [(Text, b)] prepConsts file mcnsts = do cmap <- liftIO $ parse file cnsts <- mcnsts let cnsts' = catMaybes $ map (\ (x, y) -> do y' <- mapLookup y cnsts return (x, y')) cmap return (cnsts' ++ mapToList cnsts) replaceTerm :: [(Text, HOLTerm)] -> TransHOL thry HOLTerm HOLTerm replaceTerm tmmap = repTerm where repTerm :: TransHOL thry HOLTerm HOLTerm repTerm = hconstT (contextfreeT return) (contextfreeT return) (\ x ty -> mkMConst x ty) <+ hcombT repTerm repTerm (\ x -> liftO . mkComb x) <+ habsT (contextfreeT return) repTerm (\ x -> liftO . mkAbs x) <+ htycombT repTerm (contextfreeT return) (\ x -> liftO . mkTyComb x) <+ htyabsT (contextfreeT return) repTerm (\ x -> liftO . mkTyAbs x) <+ hvarT (contextfreeT return) (contextfreeT return) repVar -- EvNote: has the potential to cause issues if a bound var has -- a name shared with a mapped constant repVar :: Text -> HOLType -> HOL Proof thry HOLTerm repVar i ty = (tryFind (\ (key, Const name ty') -> if key == i && isJust (typeMatch ty' ty ([], [], [])) then mkMConst name ty else fail "") tmmap) <|> (return $! mkVar i ty) replaceType :: [(Text, TypeOp)] -> TransHOL thry HOLTerm HOLTerm replaceType tymap = repTerm where repTerm :: TransHOL thry HOLTerm HOLTerm repTerm = hvarT (contextfreeT return) repType (\ x -> return . mkVar x) <+ hconstT (contextfreeT return) (contextfreeT return) (\ x ty -> mkMConst x ty) <+ hcombT repTerm repTerm (\ x -> liftO . mkComb x) <+ habsT repTerm repTerm (\ x -> liftO . mkAbs x) <+ htycombT repTerm repType (\ x -> liftO . mkTyComb x) <+ htyabsT repType repTerm (\ x -> liftO . mkTyAbs x) repType :: TransHOL thry HOLType HOLType repType = htyvarT (contextfreeT return) (contextfreeT return) (\ f x -> let ty = mkVarType x in if f then liftO $ mkSmall ty else return ty) <+ htyappT (contextfreeT return) repType repTyApp <+ hutypeT (contextfreeT return) repType (\ x -> liftO . mkUType x) repTyApp :: TypeOp -> [HOLType] -> HOL Proof thry HOLType repTyApp op tys = do op' <- repOp liftO $! tyApp op' tys where repOp :: HOL Proof thry TypeOp repOp = case op of (TyPrimitive i arity) | i == "fun" -> return op | otherwise -> (tryFind (\ (key, op') -> let (_, arity') = destTypeOp op' in if key == i && arity' == arity then return op' else fail "") tymap) <|> (return $! mkTypeOpVar i) _ -> return op
ecaustin/haskhol-haskell
src/HaskHOL/Haskell/Plugin.hs
bsd-2-clause
7,207
0
23
2,685
2,038
1,010
1,028
140
4
-- WARNING: This file is generated by tasty-integrate -- Changes made will (probably) not be saved, see documentation. {-# OPTIONS_GHC -fno-warn-missing-signatures #-} module Main where import qualified Data.QcIntegrated (prop_toPartition, prop_fromPartition, prop_fromTestpath_isomorphism) import qualified Data.QcSuite (prop_buf_isomorphism) import Test.Tasty import Test.Tasty.QuickCheck main :: IO () main = defaultMain (testGroup "modules" [testGroup "tests/Data/QcIntegrated.hs" [testProperty "42: prop_toPartition" Data.QcIntegrated.prop_toPartition, testProperty "186: prop_fromPartition" Data.QcIntegrated.prop_fromPartition, testProperty "429: prop_fromTestpath_isomorphism" Data.QcIntegrated.prop_fromTestpath_isomorphism], testGroup "tests/Data/QcSuite.hs" [testProperty "20: prop_buf_isomorphism" Data.QcSuite.prop_buf_isomorphism]])
jfeltz/tasty-integrate
test-suites/Suite.hs
bsd-2-clause
1,000
0
12
221
132
76
56
22
1
module Main ( main ) where import IS import Stat import Data.Char import System.Environment import Text.Printf import Text.Read import Control.Applicative main = do args <- getArgs case args of [zn, bl] -> process passedByPtsAcc "all" zn bl [rep, opt, zn, bl] -> case opt of "ptacc" -> process passedByPtsAcc rep zn bl "pt" -> process passedByPts rep zn bl _ -> usage [rep, gr, n, zn, bl] -> case (gr, readMaybe n) of ("gracc", Just n) -> process (passedByPtsGrAcc n) rep zn bl ("gr", Just n) -> process (passedByPtsGr n) rep zn bl _ -> usage _ -> usage where usage = error "usage: [all | norepeat | repeat] [ pt | ptacc | gr <N> | gracc <N> ] <marks> <notebook>" process f (r:rs) zn bl = putStrLn =<< table <$> (f <$> (passedStudents rep <$> readFile zn) <*> (parseNb rep <$> readFile bl)) where rep = read (toUpper r : rs) table :: [ (Points, Int, Int, Double) ] -> String table = unlines . map line where line (pts, tot, succ, pro) = printf ">= %4.1f %d/%d (%0.1f %%)" pts succ tot (pro * 100)
vlstill/isstat
src/Main.hs
bsd-2-clause
1,245
0
15
436
416
222
194
27
8
module Database.SqlServer.Definition.Entity ( Entity, toDoc, name, renderName ) where import Database.SqlServer.Definition.Identifier import Text.PrettyPrint class Entity a where toDoc :: a -> Doc name :: a -> RegularIdentifier renderName :: a -> Doc renderName = renderRegularIdentifier . name
SuperDrew/sql-server-gen
src/Database/SqlServer/Definition/Entity.hs
bsd-2-clause
360
0
7
102
79
47
32
13
0
{-# LANGUAGE OverloadedStrings, DeriveGeneric, FlexibleInstances, RecordWildCards #-} import System.Environment import ZTail import Abstract.Wrapper import Abstract.Queue.Enq import Control.Monad import Data.Aeson import Data.Maybe import Data.Int import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Char8 as BSC import qualified System.Metrics.Distribution as Distribution import qualified System.Metrics.Counter as Counter import qualified System.Metrics.Gauge as Gauge import qualified System.Metrics.Label as Label import qualified System.Remote.Monitoring as Monitoring import ZTail.Tools.EKG instance FromJSON (HostDataWrapper TailPacket) instance ToJSON (HostDataWrapper TailPacket) port = 60002 usage = "usage: ./ztail-enqueue <host-id-string> [<queue-url://>,..] <ztail-args...>" tp'pack v = lazyToStrict $ encode v tp'unpack v = fromJust $ (decode (strictToLazy v) :: Maybe (HostDataWrapper TailPacket)) strictToLazy v = BSL.fromChunks [v] lazyToStrict v = BS.concat $ BSL.toChunks v encode'bsc v = lazyToStrict $ encode v relay EKG{..} wrapper rqs _ tp = do mapM_ (\rq -> enqueue rq (wrapper { d = tp })) rqs -- stats let len = length $ buf tp Counter.inc _logCounter Gauge.add _lengthGauge (fromIntegral len :: Int64) Distribution.add _logDistribution (fromIntegral len :: Double) main :: IO () main = do ekg'bootstrap port main' main' :: EKG -> IO () main' ekg = do argv <- getArgs case argv of (hid:urls:params) -> logger ekg hid (read urls :: [String]) params _ -> error usage logger ekg hid urls params = do rqs <- mapM (\url -> mkQueue'Enq url tp'pack tp'unpack) urls let wrapper = HostDataWrapper { h = hid } tails <- parse_args params run_main params tailText $ map (\t -> t { ioAct = relay ekg wrapper rqs}) tails
adarqui/Ztail-Tools
tools/ztail-enqueue.hs
bsd-3-clause
1,886
0
13
337
586
313
273
47
2
module Control.Agent.FreeSpec (main, spec) where import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "someFunction" $ do it "should work fine" $ do True `shouldBe` True
fizruk/free-agent
test/Control/Agent/FreeSpec.hs
bsd-3-clause
214
0
13
49
77
41
36
9
1
{-# LANGUAGE ImplicitParams, FlexibleContexts, TupleSections #-} module Frontend.StatementOps(mapStat, mapStatM, statMapExpr, statMapTSpec, statLabels, statCallees, statSubprocessRec, statSubprocessNonrec, statFlatten, statObjs, statObjsRec, methObjsRec, statReturns) where import Control.Monad.Error import Data.Maybe import qualified Data.Traversable as Tr import Util hiding (name, trace) import Pos import Name import Frontend.Expr import {-# SOURCE #-} Frontend.ExprOps import Frontend.ExprFlatten import Frontend.Spec import Frontend.NS import Frontend.Statement import Frontend.Type import Frontend.TypeOps import Frontend.TVar import Frontend.TVarOps import Frontend.Method import Frontend.Template import Frontend.InstTree -- Map function over all substatements mapStat :: (?spec::Spec) => (Scope -> Statement -> Statement) -> Scope -> Statement -> Statement mapStat f s (SSeq p l ss) = f s $ SSeq p l (map (mapStat f s) ss) mapStat f s (SPar p l ss) = f s $ SPar p l (map (mapStat f s) ss) mapStat f s (SForever p l b) = f s $ SForever p l (mapStat f s b) mapStat f s (SDo p l b c) = f s $ SDo p l (mapStat f s b) c mapStat f s (SWhile p l c b) = f s $ SWhile p l c (mapStat f s b) mapStat f s (SFor p l (i,c,u) b) = f s $ SFor p l ((fmap (mapStat f s) i),c, mapStat f s u) (mapStat f s b) mapStat f s (SChoice p l ss) = f s $ SChoice p l (map (mapStat f s) ss) mapStat f s (SITE p l c t me) = f s $ SITE p l c (mapStat f s t) (fmap (mapStat f s) me) mapStat f s (SCase p l c cs md) = f s $ SCase p l c (map (\(e,st) -> (e,mapStat f s st)) cs) (fmap (mapStat f s) md) mapStat f s st = f s st mapStatM :: (Monad m, ?spec::Spec) => (Scope -> Statement -> m Statement) -> Scope -> Statement -> m Statement mapStatM f s (SSeq p l ss) = f s =<< (liftM $ SSeq p l) (mapM (mapStatM f s) ss) mapStatM f s (SPar p l ss) = f s =<< (liftM $ SPar p l) (mapM (mapStatM f s) ss) mapStatM f s (SForever p l b) = f s =<< (liftM $ SForever p l) (mapStatM f s b) mapStatM f s (SDo p l b c) = f s =<< (liftM $ (flip $ SDo p l) c) (mapStatM f s b) mapStatM f s (SWhile p l c b) = f s =<< (liftM $ SWhile p l c) (mapStatM f s b) mapStatM f s (SFor p l (i,c,u) b) = do i' <- Tr.sequence $ fmap (mapStatM f s) i u' <- mapStatM f s u b' <- mapStatM f s b f s $ SFor p l (i', c, u') b' mapStatM f s (SChoice p l ss) = f s =<< (liftM $ SChoice p l) (mapM (mapStatM f s) ss) mapStatM f s (SITE p l c t me) = f s =<< (liftM2 $ SITE p l c) (mapStatM f s t) (Tr.sequence $ fmap (mapStatM f s) me) mapStatM f s (SCase p l c cs md) = do cs' <- mapM (\(e,st) -> do st' <- mapStatM f s st return (e,st')) cs md' <- Tr.sequence $ fmap (mapStatM f s) md f s $ SCase p l c cs' md' mapStatM f s st = f s st -- Map function over all TypeSpec's in the statement statMapTSpec :: (?spec::Spec) => (Scope -> TypeSpec -> TypeSpec) -> Scope -> Statement -> Statement statMapTSpec f s st = mapStat (statMapTSpec' f) s st statMapTSpec' :: (?spec::Spec) => (Scope -> TypeSpec -> TypeSpec) -> Scope -> Statement -> Statement statMapTSpec' f s (SVarDecl p l v) = SVarDecl p l (Var (pos v) (varMem v) (mapTSpec f s $ tspec v) (name v) (varInit v)) statMapTSpec' _ _ st = st -- Map function over all expressions in the statement statMapExpr :: (?spec::Spec) => (Scope -> Expr -> Expr) -> Scope -> Statement -> Statement statMapExpr f s st = mapStat (statMapExpr' f) s st statMapExpr' :: (?spec::Spec) => (Scope -> Expr -> Expr) -> Scope -> Statement -> Statement statMapExpr' f s (SVarDecl p l v) = SVarDecl p l (varMapExpr f s v) statMapExpr' f s (SReturn p l mr) = SReturn p l (fmap (mapExpr f s) mr) statMapExpr' f s (SDo p l b c) = SDo p l b (mapExpr f s c) statMapExpr' f s (SWhile p l c b) = SWhile p l (mapExpr f s c) b statMapExpr' f s (SFor p l (i,c,u) b) = SFor p l (i, mapExpr f s c, u) b statMapExpr' f s (SInvoke p l m mas) = SInvoke p l m (map (fmap $ mapExpr f s) mas) statMapExpr' f s (SWait p l e) = SWait p l (mapExpr f s e) statMapExpr' f s (SAssert p l e) = SAssert p l (mapExpr f s e) statMapExpr' f s (SAssume p l e) = SAssume p l (mapExpr f s e) statMapExpr' f s (SAssign p l lhs rhs) = SAssign p l (mapExpr f s lhs) (mapExpr f s rhs) statMapExpr' f s (SITE p l c t me) = SITE p l (mapExpr f s c) t me statMapExpr' f s (SCase p l c cs md) = SCase p l (mapExpr f s c) (map (mapFst $ mapExpr f s) cs) md statMapExpr' _ _ (SMagic p l) = SMagic p l statMapExpr' _ _ st = st -- Find all methods invoked by the statement statCallees :: (?spec::Spec) => Scope -> Statement -> [(Pos, (Template, Method))] statCallees s (SVarDecl _ _ v) = fromMaybe [] $ fmap (exprCallees s) $ varInit v statCallees s (SReturn _ _ me) = fromMaybe [] $ fmap (exprCallees s) me statCallees s (SSeq _ _ ss) = concatMap (statCallees s) ss statCallees s (SPar _ _ ss) = concatMap (statCallees s) ss statCallees s (SForever _ _ b) = statCallees s b statCallees s (SDo _ _ b c) = statCallees s b ++ exprCallees s c statCallees s (SWhile _ _ c b) = exprCallees s c ++ statCallees s b statCallees s (SFor _ _ (i,c,u) b) = (fromMaybe [] $ fmap (statCallees s) i) ++ exprCallees s c ++ statCallees s u ++ statCallees s b statCallees s (SChoice _ _ ss) = concatMap (statCallees s) ss statCallees s (SInvoke p _ mref mas) = (p,getMethod s mref):(concatMap (exprCallees s) $ catMaybes mas) statCallees s (SWait _ _ e) = exprCallees s e statCallees s (SAssert _ _ e) = exprCallees s e statCallees s (SAssume _ _ e) = exprCallees s e statCallees s (SAssign _ _ l r) = exprCallees s l ++ exprCallees s r statCallees s (SITE _ _ c t me) = exprCallees s c ++ statCallees s t ++ (fromMaybe [] $ fmap (statCallees s) me) statCallees s (SCase _ _ c cs md) = exprCallees s c ++ concatMap (\(e,st) -> exprCallees s e ++ statCallees s st) cs ++ (fromMaybe [] $ fmap (statCallees s) md) statCallees _ _ = [] -- Objects referred to by the statement statObjs :: (?spec::Spec, ?scope::Scope) => Statement -> [Obj] statObjs (SVarDecl _ _ v) = (ObjVar ?scope v) : (concatMap exprObjs $ maybeToList $ varInit v) statObjs (SReturn _ _ mr) = concatMap exprObjs $ maybeToList mr statObjs (SSeq _ _ ss) = concatMap statObjs ss statObjs (SPar _ _ ps) = concatMap statObjs ps statObjs (SForever _ _ s) = statObjs s statObjs (SDo _ _ s c) = statObjs s ++ exprObjs c statObjs (SWhile _ _ c s) = statObjs s ++ exprObjs c statObjs (SFor _ _ (mi, c, i) s) = statObjs s ++ exprObjs c ++ statObjs i ++ (concatMap statObjs $ maybeToList mi) statObjs (SChoice _ _ ss) = concatMap statObjs ss statObjs (SInvoke _ _ m mas) = (let (t,meth) = getMethod ?scope m in ObjMethod t meth): (concatMap exprObjs $ catMaybes mas) statObjs (SWait _ _ c) = exprObjs c statObjs (SAssert _ _ c) = exprObjs c statObjs (SAssume _ _ c) = exprObjs c statObjs (SAssign _ _ l r) = exprObjs l ++ exprObjs r statObjs (SITE _ _ c t me) = exprObjs c ++ statObjs t ++ (concatMap statObjs $ maybeToList me) statObjs (SCase _ _ c cs md) = exprObjs c ++ concatMap (\(e,s) -> exprObjs e ++ statObjs s) cs ++ concatMap statObjs (maybeToList md) statObjs _ = [] -- recursive version statObjsRec :: (?spec::Spec, ?scope::Scope) => Statement -> [Obj] statObjsRec s = let os = statObjs s mos = filter (\o -> case o of ObjMethod _ _ -> True _ -> False) os os' = concatMap (\(ObjMethod t m) -> methObjsRec t m) mos in os ++ os' -- Recursively compute objects referenced in the body of the method methObjsRec :: (?spec::Spec) => Template -> Method -> [Obj] methObjsRec t m = let ?scope = ScopeMethod t m in case methBody m of Left (ms1,ms2) -> concatMap statObjsRec $ maybeToList ms1 ++ maybeToList ms2 Right s -> statObjsRec s -- List of subprocesses spawned by the statement: -- Computed by recursing through fork statements statSubprocessRec :: (?spec::Spec) => Statement -> [Statement] statSubprocessRec (SSeq _ _ ss) = concatMap statSubprocessRec ss statSubprocessRec (SPar _ _ ss) = ss ++ concatMap statSubprocessRec ss statSubprocessRec (SForever _ _ b) = statSubprocessRec b statSubprocessRec (SDo _ _ b _) = statSubprocessRec b statSubprocessRec (SWhile _ _ _ b) = statSubprocessRec b statSubprocessRec (SFor _ _ (mi,_,s) b) = concatMap statSubprocessRec $ (maybeToList mi) ++ [s,b] statSubprocessRec (SChoice _ _ ss) = concatMap statSubprocessRec ss statSubprocessRec (SITE _ _ _ t me) = concatMap statSubprocessRec $ t:(maybeToList me) statSubprocessRec (SCase _ _ _ cs mdef) = concatMap statSubprocessRec $ map snd cs ++ maybeToList mdef statSubprocessRec _ = [] -- non-recursive (first-level subprocesses only) statSubprocessNonrec :: (?spec::Spec) => Statement -> [Statement] statSubprocessNonrec (SSeq _ _ ss) = concatMap statSubprocessNonrec ss statSubprocessNonrec (SPar _ _ ss) = ss statSubprocessNonrec (SForever _ _ b) = statSubprocessNonrec b statSubprocessNonrec (SDo _ _ b _) = statSubprocessNonrec b statSubprocessNonrec (SWhile _ _ _ b) = statSubprocessNonrec b statSubprocessNonrec (SFor _ _ (mi,_,s) b) = concatMap statSubprocessNonrec $ (maybeToList mi) ++ [s,b] statSubprocessNonrec (SChoice _ _ ss) = concatMap statSubprocessNonrec ss statSubprocessNonrec (SITE _ _ _ t me) = concatMap statSubprocessNonrec $ t:(maybeToList me) statSubprocessNonrec (SCase _ _ _ cs mdef) = concatMap statSubprocessNonrec $ map snd cs ++ maybeToList mdef statSubprocessNonrec _ = [] statFlatten :: (?spec::Spec) => IID -> Scope -> Statement -> Statement statFlatten iid s st = mapStat (statFlatten' iid) s $ statMapExpr (exprFlatten' iid) s st statFlatten' :: (?spec::Spec) => IID -> Scope -> Statement -> Statement statFlatten' iid s st = statFlatten'' iid s $ st{stLab = fmap (\l -> itreeFlattenName iid l) $ stLab st} statFlatten'' :: (?spec::Spec) => IID -> Scope -> Statement -> Statement statFlatten'' iid _ (SInvoke p l (MethodRef p' n) as) = SInvoke p l (MethodRef p' [itreeFlattenName (itreeRelToAbsPath iid (init n)) (last n)]) as statFlatten'' _ _ st = st -- True if the statement returns a value on all execution paths. statReturns :: Statement -> Bool statReturns (SReturn _ _ r) = isJust r statReturns (SSeq _ _ ss) = statReturns $ last ss statReturns (SChoice _ _ ss) = all statReturns ss statReturns (SITE _ _ _ t (Just e)) = statReturns t && statReturns e statReturns (SCase _ _ _ cs (Just d)) = all statReturns (d: (map snd cs)) statReturns _ = False statLabels :: Statement -> [Ident] statLabels s = (maybeToList $ stLab s) ++ statLabels' s statLabels' :: Statement -> [Ident] statLabels' (SSeq _ _ ss) = concatMap statLabels ss statLabels' (SPar _ _ ss) = concatMap statLabels ss statLabels' (SForever _ _ s) = statLabels s statLabels' (SDo _ _ b _) = statLabels b statLabels' (SWhile _ _ _ b) = statLabels b statLabels' (SFor _ _ (mi,_,s) b) = concatMap statLabels $ b:s:(maybeToList mi) statLabels' (SChoice _ _ ss) = concatMap statLabels ss statLabels' (SITE _ _ _ t e) = statLabels t ++ maybe [] statLabels e statLabels' (SCase _ _ _ cs md) = concatMap statLabels $ (map snd cs) ++ maybeToList md statLabels' _ = []
termite2/tsl
Frontend/StatementOps.hs
bsd-3-clause
12,997
0
15
4,239
5,334
2,673
2,661
187
2