code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE Haskell2010 #-}
module GuiChat.Types where
import Graphics.Gloss.Data.Color
import Graphics.Gloss.Data.Picture
data Shape = SCircle | SRect | SSquare | SCircle' | SRect' | SSquare' | SPencil
deriving (Eq, Show, Read)
data Image = Image ImageT (Float, Float, Float, Float) (Float, Float)
deriving (Eq, Show, Read)
data ImageT =
TCircle Float
| TCircle' Float
| TSquare Float Float
| TSquare' Float Float
| TRect Float Float
| TRect' Float Float
deriving (Eq, Show, Read)
data Canvas = Canvas {
cPictures :: [Picture]
, cStart :: Maybe (Float, Float)
, cTo :: (Float, Float)
, cShape :: Shape
, cColor :: Color
}
| scravy/GuiChat | src/GuiChat/Types.hs | gpl-3.0 | 677 | 0 | 10 | 155 | 221 | 134 | 87 | 22 | 0 |
{-
Copyright 2010 John Morrice
This source file is part of The Obelisk Programming Language and is distributed under the terms of the GNU General Public License
This file is part of The Obelisk Programming Language.
The Obelisk Programming Language is free software: you can
redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation,
either version 3 of the License, or any later version.
The Obelisk Programming Language 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 The Obelisk Programming Language.
If not, see <http://www.gnu.org/licenses/>
-}
-- | A parser monad
module Language.Obelisk.Parser.Monad where
import Text.Parsec.Pos
import Language.Obelisk.AST.Simple
import Error.Report
-- | Our overall parser type
type Parse = OParser SimpleObelisk
-- | The parser can succeed or fail with a message
data ParseResult a =
ParseOK a
| ParseFail String
deriving Show
-- | The parser monad passes the input string and source location around, and deals with errors.
newtype OParser a = OParser (String -> CodeFragment -> ParseResult a)
-- | Run a parser
run_parser :: Parse -- ^ The parser
-> FilePath -- ^ The source name
-> String -- ^ The input
-> SimpleObelisk
run_parser par fp i = do
case eparse par fp i of
ParseOK ob -> ob
ParseFail s -> error s
-- | Execute a parser
eparse :: Parse -- ^ The parser
-> FilePath -- ^ The source name
-> String -- ^ The input
-> ParseResult SimpleObelisk
eparse (OParser par) fp i =
par i $ CodeFragment (newPos fp 1 1) ""
instance Monad OParser where
return a =
OParser $ const $ const $ ParseOK a
(OParser fa) >>= amb =
OParser $ \i sp ->
case fa i sp of
ParseOK a ->
let OParser fb = amb a
in fb i sp
ParseFail err -> ParseFail err
fail err = OParser $ \_ fr ->
ParseFail $ pretty $ error_line "Parse error" $ error_section $ report fr
-- | Get the current source code position and code fragment
get_pos :: OParser CodeFragment
get_pos = OParser $ const ParseOK
| elginer/Obelisk | Language/Obelisk/Parser/Monad.hs | gpl-3.0 | 2,477 | 0 | 15 | 646 | 387 | 201 | 186 | 38 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Debug.Trace
import Data.Aeson
import qualified Data.List as L
import Data.Map as M
import Data.Binary
import GHC.Generics (Generic)
import Control.Monad.Logger
import Network.HTTP
--import Data.ByteString as BS
--import Data.ByteString.Char8 as BS
import Data.ByteString.Lazy.Char8 as BS
import Data.Proxy
import Network.URI ( parseURI )
import qualified Network.HTTP.Media as M
import Servant.API.ContentTypes as S
import Control.Distributed.Blast
import Control.Distributed.Blast.Syntax
import Control.Distributed.Blast.Backend.Servant.CliArgs
import Control.Distributed.Blast.Backend.Servant.App
import Data.Monoid
import System.Directory
-- a slow implementation of Fibonnacci
fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib 2 = 3
fib n = fib (n-1) + fib (n-2)
comp1 :: () -> LocalComputation ((), Int)
comp1 () = do
-- create a remote list [32, 32, 32 ,...]
r1 <- rconst [ (31::Int)| _ <- [1..32::Int]]
-- map fib over the remote list r1
r2 <- rmap (fun fib) r1
-- repatriate the results locally.
l1 <- collect r2
-- sum them
l2 <- sum <$$> l1
-- associate new seed
r <- (\x -> ((), x)) <$$> l2
return r
-- create the job, no intermediate reporting, no iteration.
jobDesc1 :: JobDesc () Int
jobDesc1 =
MkJobDesc () comp1 reporting noIteration
where
reporting a b = do
print a
print b
return a
noIteration :: a -> a -> b -> Bool
noIteration _ _ _ = True
main :: IO ()
main = do
let config = MkConfig 1.0 True
runServant runStdoutLoggingT toValue config jobDesc1
where
toValue a = toJSON a
-- runServant :: S.Serialize a =>
-- (forall t. LoggingT IO t -> IO t)
-- -> t -> Config -> JobDesc a b -> IO ()
| jcmincke/Blast-Servant | app/Main.hs | mpl-2.0 | 2,192 | 0 | 12 | 529 | 505 | 286 | 219 | 58 | 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.Chat.Spaces.Messages.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns a message.
--
-- /See:/ <https://developers.google.com/hangouts/chat Google Chat API Reference> for @chat.spaces.messages.get@.
module Network.Google.Resource.Chat.Spaces.Messages.Get
(
-- * REST Resource
SpacesMessagesGetResource
-- * Creating a Request
, spacesMessagesGet
, SpacesMessagesGet
-- * Request Lenses
, smgXgafv
, smgUploadProtocol
, smgAccessToken
, smgUploadType
, smgName
, smgCallback
) where
import Network.Google.Chat.Types
import Network.Google.Prelude
-- | A resource alias for @chat.spaces.messages.get@ method which the
-- 'SpacesMessagesGet' request conforms to.
type SpacesMessagesGetResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Message
-- | Returns a message.
--
-- /See:/ 'spacesMessagesGet' smart constructor.
data SpacesMessagesGet =
SpacesMessagesGet'
{ _smgXgafv :: !(Maybe Xgafv)
, _smgUploadProtocol :: !(Maybe Text)
, _smgAccessToken :: !(Maybe Text)
, _smgUploadType :: !(Maybe Text)
, _smgName :: !Text
, _smgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SpacesMessagesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'smgXgafv'
--
-- * 'smgUploadProtocol'
--
-- * 'smgAccessToken'
--
-- * 'smgUploadType'
--
-- * 'smgName'
--
-- * 'smgCallback'
spacesMessagesGet
:: Text -- ^ 'smgName'
-> SpacesMessagesGet
spacesMessagesGet pSmgName_ =
SpacesMessagesGet'
{ _smgXgafv = Nothing
, _smgUploadProtocol = Nothing
, _smgAccessToken = Nothing
, _smgUploadType = Nothing
, _smgName = pSmgName_
, _smgCallback = Nothing
}
-- | V1 error format.
smgXgafv :: Lens' SpacesMessagesGet (Maybe Xgafv)
smgXgafv = lens _smgXgafv (\ s a -> s{_smgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
smgUploadProtocol :: Lens' SpacesMessagesGet (Maybe Text)
smgUploadProtocol
= lens _smgUploadProtocol
(\ s a -> s{_smgUploadProtocol = a})
-- | OAuth access token.
smgAccessToken :: Lens' SpacesMessagesGet (Maybe Text)
smgAccessToken
= lens _smgAccessToken
(\ s a -> s{_smgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
smgUploadType :: Lens' SpacesMessagesGet (Maybe Text)
smgUploadType
= lens _smgUploadType
(\ s a -> s{_smgUploadType = a})
-- | Required. Resource name of the message to be retrieved, in the form
-- \"spaces\/*\/messages\/*\". Example:
-- spaces\/AAAAMpdlehY\/messages\/UMxbHmzDlr4.UMxbHmzDlr4
smgName :: Lens' SpacesMessagesGet Text
smgName = lens _smgName (\ s a -> s{_smgName = a})
-- | JSONP
smgCallback :: Lens' SpacesMessagesGet (Maybe Text)
smgCallback
= lens _smgCallback (\ s a -> s{_smgCallback = a})
instance GoogleRequest SpacesMessagesGet where
type Rs SpacesMessagesGet = Message
type Scopes SpacesMessagesGet = '[]
requestClient SpacesMessagesGet'{..}
= go _smgName _smgXgafv _smgUploadProtocol
_smgAccessToken
_smgUploadType
_smgCallback
(Just AltJSON)
chatService
where go
= buildClient
(Proxy :: Proxy SpacesMessagesGetResource)
mempty
| brendanhay/gogol | gogol-chat/gen/Network/Google/Resource/Chat/Spaces/Messages/Get.hs | mpl-2.0 | 4,419 | 0 | 15 | 1,016 | 696 | 407 | 289 | 99 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module Misc.Parser.LazyByteString
( module Data.Attoparsec.ByteString.Lazy
, token
, isToken
) where
import qualified Data.Attoparsec.ByteString.Char8 as BSParser
import Data.Attoparsec.ByteString.Lazy
import GHC.Word (Word8)
token :: Char -> Parser Char
token c = BSParser.skipSpace *> BSParser.char c <* BSParser.skipSpace
isToken :: Word8 -> Bool
isToken w =
w <= 127 && notInClass "\0-\31()<>@,;:\\\"/[]?={} \t" w
| inq/agitpunkt | src/Misc/Parser/LazyByteString.hs | agpl-3.0 | 510 | 0 | 8 | 114 | 118 | 69 | 49 | 13 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Controller.Ingest
( viewIngest
, postIngest
, detectParticipantCSV
, runParticipantUpload
-- for tests
, mappingParser
, buildParticipantRecordAction
, ParticipantStatus(..)
, MeasureUpdateAction(..)
, ParticipantRecordAction(..)
) where
import Control.Arrow (right)
import Control.Monad (unless)
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lazy as BSL
import Data.Maybe (catMaybes)
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text.Encoding as TE
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TLE
import Data.Vector (Vector)
import Data.Word (Word64)
import Network.HTTP.Types (badRequest400)
import Network.Wai.Parse (FileInfo(..))
import System.Posix.FilePath (takeExtension)
import Data.Csv.Contrib (parseCsvWithHeader, getHeaders, removeBomPrefixText)
import qualified JSON
import Ops
import Has
import Model.Category
import Model.Id
import Model.Metric (Metric)
import Model.Ingest
import Model.Permission
import Model.Measure
import Model.Metric
import Model.Party
import Model.Record
import Model.Volume
import Model.VolumeMetric
import Model.Container
import Ingest.Action
import Ingest.JSON
import HTTP.Path.Parser
import HTTP.Form.Deform
import Action.Route
import Action
import Controller.Paths
import Controller.Permission
import Controller.Form
import Controller.Volume
import Store.Types
import View.Form (FormHtml)
import View.Ingest
viewIngest :: ActionRoute (Id Volume)
viewIngest = action GET (pathId </< "ingest") $ \vi -> withAuth $ do
checkMemberADMIN
s <- focusIO getIngestStatus
v <- getVolume PermissionEDIT vi
peeks $ blankForm . htmlIngestForm v s
data ControlIngestRequest =
AbortIngest Bool
| RunIngest Bool Bool (FileInfo JSON.Value)
postIngest :: ActionRoute (Id Volume)
postIngest = multipartAction $ action POST (pathId </< "ingest") $ \vi -> withAuth $ do
checkMemberADMIN
s <- focusIO getIngestStatus
v <- getVolume PermissionEDIT vi
a <- runFormFiles [("json", 16*1024*1024)] (Just $ htmlIngestForm v s) $ do
csrfForm
AbortIngest abort <- AbortIngest <$> ("abort" .:> deform)
abort `unlessReturn` (RunIngest
<$> ("run" .:> deform)
<*> ("overwrite" .:> deform)
<*> ("json" .:> do
(fileInfo :: FileInfo JSON.Value) <- deform
deformCheck
"Must be JSON."
(\f -> fileContentType f `elem` ["text/json", "application/json"] || takeExtension (fileName f) == ".json")
fileInfo))
r <- maybe
(True <$ focusIO abortIngest)
(\(RunIngest r o j) -> runIngest $ right (map (unId . containerId . containerRow)) <$> ingestJSON v (fileContent j) r o)
a
unless r $ result $ response badRequest400 [] ("failed" :: String)
peeks $ otherRouteResponse [] viewIngest (volumeId $ volumeRow v)
maxWidelyAcceptableHttpBodyFileSize :: Word64
maxWidelyAcceptableHttpBodyFileSize = 16*1024*1024
data DetectParticipantCSVRequest = DetectParticipantCSVRequest (FileInfo TL.Text)
-- TODO: maybe put csv file save/retrieve in Store module
detectParticipantCSV :: ActionRoute (Id Volume)
detectParticipantCSV = action POST (pathJSON >/> pathId </< "detectParticipantCSV") $ \vi -> withAuth $ do
v <- getVolume PermissionEDIT vi
(auth :: SiteAuth) <- peek
(store :: Storage) <- peek
DetectParticipantCSVRequest csvFileInfo <-
-- TODO: is Nothing okay here?
runFormFiles [("file", maxWidelyAcceptableHttpBodyFileSize)] (Nothing :: Maybe (RequestContext -> FormHtml TL.Text)) $ do
csrfForm
fileInfo :: (FileInfo TL.Text) <- "file" .:> deform
return (DetectParticipantCSVRequest fileInfo)
-- liftIO (print ("after extract form"))
let uploadFileContents' = (BSL.toStrict . TLE.encodeUtf8 . removeBomPrefixText . fileContent) csvFileInfo
-- liftIO (print "uploaded contents below")
-- liftIO (print uploadFileContents')
case parseCsvWithHeader uploadFileContents' of
Left err ->
pure (response badRequest400 [] err)
Right (hdrs, records) -> do
metrics <- lookupVolumeParticipantMetrics v
-- liftIO (print ("before check determine", show hdrs))
case checkDetermineMapping metrics ((fmap TE.decodeUtf8 . getHeaders) hdrs) uploadFileContents' of
Left err ->
-- if column check failed, then don't save csv file and response is error
pure (response badRequest400 [] err)
Right participantFieldMapping -> do
let uploadFileName =
uniqueUploadName auth v ((BSC.unpack . fileName) csvFileInfo)
liftIO
(BS.writeFile
((BSC.unpack . getStorageTempParticipantUpload uploadFileName) store)
uploadFileContents')
pure
$ okResponse []
$ JSON.recordEncoding -- TODO: not record encoding
$ JSON.Record vi
$ "csv_upload_id" JSON..= uploadFileName
-- TODO: samples for mapped columns only
<> "column_samples" JSON..= extractColumnsDistinctSampleJson 5 hdrs records
<> "suggested_mapping" JSON..= participantFieldMappingToJSON participantFieldMapping
<> "columns_firstvals" JSON..= extractColumnsInitialJson 5 hdrs records
-- TODO: move this to Store.ParticipantUploadTemp
uniqueUploadName :: SiteAuth -> Volume -> String -> String
uniqueUploadName siteAuth vol uploadName =
uniqueUploadName'
((partyId . partyRow . accountParty . siteAccount) siteAuth)
((volumeId . volumeRow) vol)
uploadName
uniqueUploadName' :: Id Party -> Id Volume -> String -> String
uniqueUploadName' uid vid uploadName =
show uid <> "-" <> show vid <> "-" <> uploadName
----- end
data RunParticipantUploadRequest = RunParticipantUploadRequest String JSON.Value
runParticipantUpload :: ActionRoute (Id Volume)
runParticipantUpload = action POST (pathJSON >/> pathId </< "runParticipantUpload") $ \vi -> withAuth $ do
v <- getVolume PermissionEDIT vi
(store :: Storage) <- peek
-- reqCtxt <- peek
RunParticipantUploadRequest csvUploadId selectedMapping <- runForm Nothing $ do
csrfForm
(uploadId :: String) <- "csv_upload_id" .:> deform
mapping <- "selected_mapping" .:> deform
pure (RunParticipantUploadRequest uploadId mapping)
-- TODO: resolve csv id to absolute path; http error if unknown
uploadFileContents <-
(liftIO . BS.readFile) ((BSC.unpack . getStorageTempParticipantUpload csvUploadId) store)
case JSON.parseEither mappingParser selectedMapping of
Left err ->
pure (response badRequest400 [] err) -- bad json shape or keys
Right mpngVal -> do
participantActiveMetrics <- lookupVolumeParticipantMetrics v
case parseParticipantFieldMapping participantActiveMetrics mpngVal of
Left err ->
pure (response badRequest400 [] err) -- mapping of inactive metrics or missing metric
Right mpngs ->
case attemptParseRows mpngs uploadFileContents of
Left err -> -- invalid value in row
pure (response badRequest400 [] err)
Right (_, records) ->
let response' =
okResponse []
$ JSON.recordEncoding -- TODO: not record encoding
$ JSON.Record vi
$ "succeeded"
JSON..= True
in response' <$ runImport v records
mappingParser :: JSON.Value -> JSON.Parser [(Metric, Text)]
mappingParser val = do
(entries :: [HeaderMappingEntry]) <- JSON.parseJSON val
pure (fmap (\e -> (hmeMetric e, hmeCsvField e)) entries)
-- TODO: move all below to Model.Ingest
-- TODO: error or count
runImport :: Volume -> Vector ParticipantRecord -> Handler (Vector ())
runImport vol records =
mapM (createOrUpdateRecord vol) records
data ParticipantStatus = Create | Found Record
data MeasureUpdateAction = Upsert Metric MeasureDatum | Delete Metric | Unchanged Metric | NoAction Metric
deriving (Show, Eq)
data ParticipantRecordAction = ParticipantRecordAction ParticipantStatus [MeasureUpdateAction]
buildParticipantRecordAction :: ParticipantRecord -> ParticipantStatus -> ParticipantRecordAction
buildParticipantRecordAction participantRecord updatingRecord =
let
mId = getFieldVal' prdId participantMetricId
mInfo = getFieldVal' prdInfo participantMetricInfo
mDescription = getFieldVal' prdDescription participantMetricDescription
mBirthdate = getFieldVal' prdBirthdate participantMetricBirthdate
mGender = getFieldVal' prdGender participantMetricGender
mRace = getFieldVal' prdRace participantMetricRace
mEthnicity = getFieldVal' prdEthnicity participantMetricEthnicity
mGestationalAge = getFieldVal' prdGestationalAge participantMetricGestationalAge
mPregnancyTerm = getFieldVal' prdPregnancyTerm participantMetricPregnancyTerm
mBirthWeight = getFieldVal' prdBirthWeight participantMetricBirthWeight
mDisability = getFieldVal' prdDisability participantMetricDisability
mLanguage = getFieldVal' prdLanguage participantMetricLanguage
mCountry = getFieldVal' prdCountry participantMetricCountry
mState = getFieldVal' prdState participantMetricState
mSetting = getFieldVal' prdSetting participantMetricSetting
-- print ("save measure id:", mId)
measureActions =
[ changeRecordMeasureIfUsed mId
, changeRecordMeasureIfUsed mInfo
, changeRecordMeasureIfUsed mDescription
, changeRecordMeasureIfUsed mBirthdate
, changeRecordMeasureIfUsed mGender
, changeRecordMeasureIfUsed mRace
, changeRecordMeasureIfUsed mEthnicity
, changeRecordMeasureIfUsed mGestationalAge
, changeRecordMeasureIfUsed mPregnancyTerm
, changeRecordMeasureIfUsed mBirthWeight
, changeRecordMeasureIfUsed mDisability
, changeRecordMeasureIfUsed mLanguage
, changeRecordMeasureIfUsed mCountry
, changeRecordMeasureIfUsed mState
, changeRecordMeasureIfUsed mSetting
]
in
ParticipantRecordAction updatingRecord (catMaybes measureActions)
where
changeRecordMeasureIfUsed :: Maybe (Maybe MeasureDatum, Metric) -> Maybe MeasureUpdateAction
changeRecordMeasureIfUsed mValueMetric = do
(mVal, met) <- mValueMetric
pure (determineUpdatedMeasure mVal met)
determineUpdatedMeasure :: Maybe MeasureDatum -> Metric -> MeasureUpdateAction
determineUpdatedMeasure mVal met =
case updatingRecord of
Create ->
maybe (NoAction met) (Upsert met) mVal
Found _ -> do
-- TODO:
-- mOldVal <- getOldVal metric record
-- action = maybe (Upsert val) (\o -> if o == val then Unchanged else Upsert val)
let measureAction = maybe (Delete met) (Upsert met) mVal
measureAction
getFieldVal' :: (ParticipantRecord -> FieldUse a) -> Metric -> Maybe (Maybe MeasureDatum, Metric)
getFieldVal' = getFieldVal participantRecord
getFieldVal
:: ParticipantRecord
-> (ParticipantRecord -> FieldUse a)
-> Metric
-> Maybe (Maybe MeasureDatum, Metric)
getFieldVal participantRecord extractFieldVal metric =
case extractFieldVal participantRecord of
Field fieldVal _ -> pure (Just fieldVal, metric)
FieldEmpty -> pure (Nothing, metric)
FieldUnused -> Nothing
-- field isn't used by this volume, so don't need to save the measure
createOrUpdateRecord :: Volume -> ParticipantRecord -> Handler () -- TODO: error or record
createOrUpdateRecord vol participantRecord = do
let category = getCategory' (Id 1) -- TODO: use global variable
mIdVal = fst $ maybe (error "id missing") id (getFieldVal' prdId participantMetricId)
idVal = maybe (error "id empty") id mIdVal
mOldParticipant <- lookupVolumeParticipant vol idVal
let recordStatus =
case mOldParticipant of
Nothing -> Create
Just oldParticipant -> Found oldParticipant
-- print ("save measure id:", mId)
case buildParticipantRecordAction participantRecord recordStatus of
ParticipantRecordAction Create measureActs -> do
newParticipantShell <- addRecord (blankRecord category vol) -- blankParticipantRecord
_ <- mapM (runMeasureUpdate newParticipantShell) measureActs
pure () -- TODO: reload participant
ParticipantRecordAction (Found oldRecord) measureActs -> do
_ <- mapM (runMeasureUpdate oldRecord) measureActs
pure ()
where
runMeasureUpdate :: Record -> MeasureUpdateAction -> Handler (Maybe Record)
runMeasureUpdate record act =
case act of
Upsert met val -> changeRecordMeasure (Measure record met val)
Delete met -> fmap Just (removeRecordMeasure (Measure record met ""))
Unchanged _ -> pure Nothing
NoAction _ -> pure Nothing
getFieldVal' :: (ParticipantRecord -> FieldUse a) -> Metric -> Maybe (Maybe MeasureDatum, Metric)
getFieldVal' = getFieldVal participantRecord
| databrary/databrary | src/Controller/Ingest.hs | agpl-3.0 | 14,043 | 0 | 32 | 3,661 | 3,144 | 1,608 | 1,536 | -1 | -1 |
-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)
-- Copyright 2016, Julia Longtin (julial@turinglace.com)
-- Released under the GNU AGPLV3+, see LICENSE
module Graphics.Implicit.ObjectUtil.GetBox2 (getBox2, getDist2) where
import Prelude(Bool, Fractional, (==), (||), unzip, minimum, maximum, ($), filter, not, (.), (/), map, (-), (+), (*), cos, sin, sqrt, min, max, abs, head)
import Graphics.Implicit.Definitions (ℝ, ℝ2, Box2, (⋯*),
SymbolicObj2(Shell2, Outset2, Circle, Translate2, Rotate2, UnionR2, Scale2, RectR,
PolygonR, Complement2, DifferenceR2, IntersectR2, EmbedBoxedObj2))
import Data.VectorSpace (magnitude, (^-^), (^+^))
-- | Is a Box2 empty?
-- | Really, this checks if it is one dimensional, which is good enough.
isEmpty :: Box2 -> Bool
isEmpty ((a, b), (c, d)) = a==c || b==d
-- | Define a Box2 around all of the given points.
pointsBox :: [ℝ2] -> Box2
pointsBox points =
let
(xs, ys) = unzip points
in
((minimum xs, minimum ys), (maximum xs, maximum ys))
-- | Define a box that fits around the given boxes.
unionBoxes :: [Box2] -> Box2
unionBoxes boxes =
let
(leftbot, topright) = unzip $ filter (not.isEmpty) boxes
(lefts, bots) = unzip leftbot
(rights, tops) = unzip topright
in
((minimum lefts, minimum bots), (maximum rights, maximum tops))
outsetBox :: ℝ -> Box2 -> Box2
outsetBox r (a,b) =
(a ^-^ (r,r), b ^+^ (r,r))
-- Define a Box2 around the given object.
getBox2 :: SymbolicObj2 -> Box2
-- Primitives
getBox2 (RectR _ a b) = (a,b)
getBox2 (Circle r) = ((-r, -r), (r,r))
getBox2 (PolygonR _ points) = pointsBox points
-- (Rounded) CSG
getBox2 (Complement2 _) =
((-infty, -infty), (infty, infty))
where
infty :: (Fractional t) => t
infty = 1/0
getBox2 (UnionR2 r symbObjs) =
outsetBox r $ unionBoxes (map getBox2 symbObjs)
getBox2 (DifferenceR2 _ symbObjs) = getBox2 $ head symbObjs
getBox2 (IntersectR2 r symbObjs) =
let
boxes = map getBox2 symbObjs
(leftbot, topright) = unzip boxes
(lefts, bots) = unzip leftbot
(rights, tops) = unzip topright
left = maximum lefts
bot = maximum bots
right = minimum rights
top = minimum tops
in
((left-r,bot-r),(right+r,top+r))
-- Simple transforms
getBox2 (Translate2 v symbObj) =
let
(a,b) = getBox2 symbObj
in
if isEmpty (a,b)
then ((0,0),(0,0))
else (a^+^v, b^+^v)
getBox2 (Scale2 s symbObj) =
let
(a,b) = getBox2 symbObj
(sax, say) = s ⋯* a
(sbx, sby) = s ⋯* b
in
((min sax sbx, min say sby), (max sax sbx, max say sby))
getBox2 (Rotate2 θ symbObj) =
let
((x1,y1), (x2,y2)) = getBox2 symbObj
rotate (x,y) = (x*cos θ - y*sin θ, x*sin θ + y*cos θ)
in
pointsBox [ rotate (x1, y1)
, rotate (x1, y2)
, rotate (x2, y1)
, rotate (x2, y2)
]
-- Boundary mods
getBox2 (Shell2 w symbObj) =
outsetBox (w/2) $ getBox2 symbObj
getBox2 (Outset2 d symbObj) =
outsetBox d $ getBox2 symbObj
-- Misc
getBox2 (EmbedBoxedObj2 (_,box)) = box
-- Get the maximum distance (read upper bound) an object is from a point.
-- Sort of a circular
getDist2 :: ℝ2 -> SymbolicObj2 -> ℝ
-- Real implementations
getDist2 p (Circle r) = magnitude p + r
getDist2 p (PolygonR r points) = r + maximum [magnitude (p ^-^ p') | p' <- points]
-- Transform implementations
getDist2 p (UnionR2 r objs) = r + maximum [getDist2 p obj | obj <- objs ]
getDist2 p (DifferenceR2 r objs) = r + getDist2 p (head objs)
getDist2 p (IntersectR2 r objs) = r + maximum [getDist2 p obj | obj <- objs ]
-- FIXME: isn't this wrong? should we be returning distance inside of the object?
getDist2 _ (Complement2 _) = 1/0
getDist2 p (Translate2 v obj) = getDist2 (p ^+^ v) obj
-- FIXME: write optimized functions for the rest of the SymbObjs.
-- Fallthrough: use getBox2 to check the distance a box is from the point.
getDist2 (x,y) symbObj =
let
((x1,y1), (x2,y2)) = getBox2 symbObj
in
sqrt (
max (abs (x1 - x)) (abs (x2 - x)) *
max (abs (x1 - x)) (abs (x2 - x)) +
max (abs (y1 - y)) (abs (y2 - y)) *
max (abs (y1 - y)) (abs (y2 - y))
)
| krakrjak/ImplicitCAD | Graphics/Implicit/ObjectUtil/GetBox2.hs | agpl-3.0 | 4,461 | 2 | 16 | 1,247 | 1,699 | 942 | 757 | 86 | 2 |
module Data.Convert.Instances.Base where
import Data.Convert.Base
instance {-# OVERLAPPABLE #-} Castable [a] [a] where cast = id ; {-# INLINE cast #-}
instance {-# OVERLAPPABLE #-} Castable a a' => Castable [a] [a'] where cast = fmap cast ; {-# INLINE cast #-}
| wdanilo/convert | src/Data/Convert/Instances/Base.hs | apache-2.0 | 288 | 0 | 6 | 69 | 74 | 45 | 29 | -1 | -1 |
{-
Copyright 2020 The CodeWorld Authors. All rights reserved.
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.
-}
program = drawingOf(circl)
circ = circle(2)
| google/codeworld | codeworld-compiler/test/testcases/misspelledUserVar/source.hs | apache-2.0 | 654 | 0 | 6 | 121 | 24 | 13 | 11 | 2 | 1 |
module Lib.Maybe (maybeF, maybeFromLeft) where
maybeF :: Maybe a -> c -> (a -> c) -> c
maybeF = flip (flip.maybe)
maybeFromLeft :: Either a b -> Maybe a
maybeFromLeft (Left x) = Just x
maybeFromLeft (Right _) = Nothing
| kernelim/gitomail | src/Lib/Maybe.hs | apache-2.0 | 221 | 0 | 9 | 42 | 102 | 53 | 49 | 6 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Control.Applicative
import Control.Lens
import Control.Monad (join)
import Data.Aeson
import Data.Aeson.Lens
import qualified Data.HashMap.Strict as HM
import Data.List (partition)
import Data.Maybe (catMaybes)
import Data.Scientific
import qualified Data.Set as S
import qualified Data.Text as T
import Network.Wreq
recentCompletedUrl :: String
recentCompletedUrl = "https://apps.fedoraproject.org/datagrepper/raw?delta=\
\172800&topic=org.fedoraproject.prod.ansible.playbook.\
\complete"
recentStartUrl :: String
recentStartUrl = "https://apps.fedoraproject.org/datagrepper/raw?delta=\
\172800&topic=org.fedoraproject.prod.ansible.playbook.\
\start"
--recentCompletedUrl = "http://localhost:8000/out.json"
--recentStartUrl = "http://localhost:8000/out1.json"
data Playbook = Updating | Rebooting deriving (Eq, Ord, Show)
data MsgData = MsgData { _user :: T.Text
, _playbook :: Playbook
, _hosts :: [T.Text]
, _timestamp :: Double -- TODO: UTCTime
} deriving (Eq, Ord, Show)
data PlaybookStatus = Start | Complete deriving (Eq, Ord, Show)
data PlaybookRun = PlaybookRun { _msgdata :: MsgData
, _status :: PlaybookStatus
} deriving (Eq, Ord, Show)
makeLenses ''MsgData
makeLenses ''PlaybookRun
valueToPlaybookRun :: Value -> Maybe PlaybookRun
valueToPlaybookRun v = do
topic <- join (startOrStop <$> v ^? key "topic" . _String)
ts <- toRealFloat <$> v ^? key "timestamp" . _Number
user' <- v ^? key "msg" . key "userid" . _String
playbook' <- join (determinePlaybook <$> v ^? key "msg" . key "playbook" . _String)
let target = case topic of
Start -> v ^.. key "msg" . key "extra_vars" . key "target" . _String
Complete -> v ^. key "msg" . key "results" . _Object . to HM.keys
return $ PlaybookRun (MsgData user' playbook' target ts) topic
where
determinePlaybook p
| "vhost_reboot" `T.isInfixOf` p = Just Rebooting
| "vhost_update" `T.isInfixOf` p = Just Updating
| otherwise = Nothing
startOrStop t
| "ansible.playbook.start" `T.isSuffixOf` t = Just Start
| "ansible.playbook.complete" `T.isSuffixOf` t = Just Complete
| otherwise = Nothing
getRecent :: String -> IO [PlaybookRun]
getRecent s = do
msgs <- get s
-- TODO: I can probably make this prettier with more lens familiarity.
return . catMaybes . map valueToPlaybookRun $ msgs ^.. responseBody . key "raw_messages" . values
main :: IO ()
main = do
recentStarted <- getRecent recentStartUrl
recentCompleted <- getRecent recentCompletedUrl
let (updC, rebC) = partition (\x -> x ^. msgdata . playbook == Updating) recentCompleted
(updS, rebS) = partition (\x -> x ^. msgdata . playbook == Updating) recentStarted
-- We start with all starting playbook runs and all completed playbook runs.
-- For each starting playbook run, try to find a matching completed playbook run.
-- Do this by:
-- - Filtering completed playbook runs to find a run of the same type (update or reboot)
-- - Taking that list and filtering it to find targets that match the starting playbook
-- - Taking *that* list and filtering it to find completions that happened *after* the start time
-- - Map over it to get a set of hostnames
-- - If any of them match the starting playbook target, then return False and move on
-- - If none of them match, the starting playbook is still likely being run.
matchingPlaybookType p1 p2 = p1 ^. msgdata . playbook == p2 ^. msgdata . playbook
matchingPlaybookTargets p1 p2 = p1 ^. msgdata . hosts == p2 ^. msgdata . hosts
correctPlaybookTimestamps p1 p2 = p1 ^. msgdata . timestamp > p2 ^. msgdata . timestamp
playbookPredicate p1 p2 =
matchingPlaybookType p1 p2 &&
matchingPlaybookTargets p1 p2 &&
correctPlaybookTimestamps p1 p2
error "hi!"
| fedora-infra/fedinfra-currentreboots | Main.hs | bsd-2-clause | 4,165 | 0 | 17 | 1,016 | 931 | 483 | 448 | -1 | -1 |
{-
Readme
'temporal-music-notation-demo' examples.
Examples depend on an external package 'temporal-music-notation-western'.
This package contains names specific to western music tradition.
So to run them do first.
>>cabal update
>>cabal install temporal-music-notation-western
A tune is first rendered to midi-file and then file is played back with the program timidity.
Timidity is recommended for this library, because timidity can interpret microtonal midi-messages.
-}
| spell-music/temporal-music-notation-demo | examples/readme.hs | bsd-3-clause | 478 | 0 | 2 | 65 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Transfuser.Types (
QueryExpr (..)
, QueryOp (..)
, Field
, DocValue
, Operator
, BsonType
, FindExpr (..)
, Projection (..)
, ProjOp (..)
, intToBsonType
, bsonTypeToInt
) where
import qualified Data.Text as T
import qualified Data.Aeson as A
import qualified Data.Bson as B
type Field = T.Text
type Operator = T.Text
type DocValue = B.Value
type Collection = T.Text
data FindExpr = FindExpr Collection QueryExpr Projection deriving (Show, Eq)
{-
A query {field1: op1, field2: op2, ...} is effectively
field1 op1 AND field2 op2 AND ...
or field* can be a logical operator
Therefore the first level of parsing is to AND together key/value pairs
-}
data QueryExpr = ExprConstr QueryOp
| ExprOR [QueryExpr]
| ExprAND [QueryExpr]
| ExprNOT QueryExpr
-- Note: $nor expands to ExprNOT (ExprOR A B)
deriving (Show, Eq)
data QueryOp = OpEQ Field DocValue
| OpLT Field DocValue
| OpGT Field DocValue
| OpGE Field DocValue
| OpLE Field DocValue
-- $ne expands to ExprNOT (ExprConstr (OpEQ field value))
| OpIN Field [DocValue]
-- $nin expands to ExprNot (ExprConstr (OpIN field array))
| OpMOD Field Int Int
| OpREGEX Field T.Text (Maybe T.Text)
| OpTEXT Field T.Text (Maybe T.Text)
-- $all expands to ExprAnd [(ExprConstr (OpEQ field val1)),
-- (ExprConstr (OpEQ field val2))]
| OpEMATCH Field [QueryExpr]
| OpSIZE Field Integer
| OpEXISTS Field Bool
| OpTYPE Field BsonType
deriving (Show, Eq)
data Projection = Projection [ProjOp]
deriving (Show, Eq)
data ProjOp = ProjInclude Field
| ProjExclude Field
-- TODO : Projection operators
deriving (Show, Eq)
data BsonType = Double -- 1
| String -- 2
| Object -- 3
| Array -- 4
| Binary -- 5
| Undefined -- 6
| ObjectId -- 7
| Boolean -- 8
| Date -- 9
| Null -- 10
| Regex -- 11
| DBPointer -- 12
| JavaScript -- 13
| Symbol -- 14
| JavaScriptScoped -- 15
| Integer32 -- 16
| Timestamp -- 17
| Integer64 -- 18
| MinKey -- -1
| MaxKey -- 127
deriving (Show, Eq)
bsonTypeToInt :: BsonType -> Integer
bsonTypeToInt Double = 1
bsonTypeToInt String = 2
bsonTypeToInt Object = 3
bsonTypeToInt Array = 4
bsonTypeToInt Binary = 5
bsonTypeToInt Undefined = 6
bsonTypeToInt ObjectId = 7
bsonTypeToInt Boolean = 8
bsonTypeToInt Date = 9
bsonTypeToInt Null = 10
bsonTypeToInt Regex = 11
bsonTypeToInt DBPointer = 12
bsonTypeToInt JavaScript = 13
bsonTypeToInt Symbol = 14
bsonTypeToInt JavaScriptScoped = 15
bsonTypeToInt Integer32 = 16
bsonTypeToInt Timestamp = 17
bsonTypeToInt Integer64 = 18
bsonTypeToInt MinKey = -1
bsonTypeToInt MaxKey = 127
intToBsonType :: Integer -> BsonType
intToBsonType 1 = Double
intToBsonType 2 = String
intToBsonType 3 = Object
intToBsonType 4 = Array
intToBsonType 5 = Binary
intToBsonType 6 = Undefined
intToBsonType 7 = ObjectId
intToBsonType 8 = Boolean
intToBsonType 9 = Date
intToBsonType 10 = Null
intToBsonType 11 = Regex
intToBsonType 12 = DBPointer
intToBsonType 13 = JavaScript
intToBsonType 14 = Symbol
intToBsonType 15 = JavaScriptScoped
intToBsonType 16 = Integer32
intToBsonType 17 = Timestamp
intToBsonType 18 = Integer64
intToBsonType (-1) = MinKey
intToBsonType 127 = MaxKey
-- TODO: Geospatial operators
-- TODO: Projection operators
| stephenpascoe/mongo-sql | src/Transfuser/Types.hs | bsd-3-clause | 4,081 | 0 | 9 | 1,448 | 818 | 473 | 345 | 108 | 1 |
{-# OPTIONS_GHC
-fno-warn-unused-binds
-fno-warn-unused-matches
#-}
module Main where
import Control.Applicative ((<$>))
--import Control.Arrow
--import qualified Data.ByteString.Lazy as B
--import qualified Prelude as P
--import Data.Word
main :: IO ()
main = do n <- read <$> getLine :: IO Int
input <- map (map read . words) . lines <$> getContents ::IO [[Int]]
return ()
-- helper stuff
(∈) :: (Eq a) => a -> [a] -> Bool
(∈) = elem
| epsilonhalbe/Sammelsurium | temp/temp.hs | bsd-3-clause | 468 | 0 | 13 | 99 | 136 | 77 | 59 | 9 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module XML.Eve where
{-import qualified Data.ByteString.Lazy.Char8 as LBS-}
{-import qualified Data.ByteString.Char8 as BS-}
import Network.Wreq
import Control.Monad.Reader
import Control.Lens.Operators
import Control.Monad.IO.Class (liftIO)
import qualified Data.Text as T
{-import Data.Aeson-}
{-import Data.Aeson.Lens-}
import Text.XML
import Text.XML.Cursor
import Types
import Util
typeNameUrl :: String
typeNameUrl = composeXMLUrl "eve/TypeName.xml.aspx" []
getTypeName :: [T.Text] -> Gideon [(T.Text, T.Text)]
getTypeName ids = do
opts <- asks authOpt
let opts' = opts & param "ids" .~ [T.intercalate "," ids]
r <- liftIO $ getWith opts' typeNameUrl
let cursor = fromDocument $ parseLBS_ def $ r ^. responseBody
return $ zip (cursor $// attribute "typeID")
(cursor $// attribute "typeName")
| Frefreak/Gideon | src/XML/Eve.hs | bsd-3-clause | 879 | 0 | 13 | 152 | 232 | 126 | 106 | 21 | 1 |
{-# LANGUAGE OverloadedStrings, ConstraintKinds, FlexibleContexts, TemplateHaskell #-}
module TelemetryTypes where
import Data.Time.Clock
import Data.Time.LocalTime
import Data.Time.Calendar
import Data.Text
import Data.Map
import Data.Functor.Identity
import Control.Monad.Reader
import Control.Lens
-- General Types
type TelemetryMonad m = (MonadReader TelemetryConfig m)
data Notifier = Notifier
{
_notifierName :: Text,
_notifierCommands :: (Text, Text)
} deriving (Eq, Show)
newtype TelemetryConfig = TelemetryConfig {
_tcNotifiers :: [Notifier]
} deriving (Eq, Show)
makeLenses ''Notifier
makeLenses ''TelemetryConfig
-- Parser Types
data TelemetryCommand = TelemetryStart | TelemetryStop
deriving (Eq, Show)
newtype TelemetryColumn = TelemetryColumn Int
deriving (Eq, Show)
data TelemetryRecord = TelemetryRecord Notifier TelemetryCommand TimeOfDay
deriving (Eq, Show)
data TelemetryBlock = TelemetryBlock Day [(Maybe TelemetryRecord, Maybe TelemetryRecord)]
deriving (Eq, Show)
newtype TelemetryLog = TelemetryLog [TelemetryBlock]
deriving (Eq, Show)
type TelemetrySource = Text
type TelemetryState = TelemetryParserState
data TelemetryParserState = TelemetryParserState{
_tpsNotifiers :: (Maybe Notifier, Maybe Notifier),
_tpsCurrentColumn :: Int
} deriving (Eq, Show)
makeLenses ''TelemetryParserState
emptyTPS :: TelemetryParserState
emptyTPS = TelemetryParserState (Nothing, Nothing) 1
--Analyzer Types
instance Ord Notifier where
compare l r = compare (l^.notifierName) (r^.notifierName)
newtype AlarmInterval = AlarmInterval (UTCTime, UTCTime)
deriving (Eq, Show)
type TelemetryReport = Map Notifier [AlarmInterval] | zool-of-bears/Telemetry | src/TelemetryTypes.hs | bsd-3-clause | 1,734 | 0 | 10 | 286 | 433 | 250 | 183 | 44 | 1 |
{-# LANGUAGE DeriveGeneric, OverloadedStrings, GeneralizedNewtypeDeriving #-}
module Data.RDF.Types (
-- * RDF triples, nodes and literals
LValue(PlainL,PlainLL,TypedL),
Node(UNode,BNode,BNodeGen,LNode), Subject, Predicate, Object,
Triple(Triple), Triples, View(view),
-- * Constructor functions
plainL,plainLL,typedL,
unode,bnode,lnode,triple,unodeValidate,
-- * Node query function
isUNode,isLNode,isBNode,
-- * Miscellaneous
resolveQName, absolutizeUrl, isAbsoluteUri, mkAbsoluteUrl,fileSchemeToFilePath,
-- * RDF Type
RDF(baseUrl,prefixMappings,addPrefixMappings,empty,mkRdf,triplesOf,uniqTriplesOf,select,query),
-- * Parsing RDF
RdfParser(parseString,parseFile,parseURL),
-- * Serializing RDF
RdfSerializer(hWriteRdf,writeRdf,hWriteH,writeH,hWriteTs,hWriteT,writeT, writeTs,hWriteN, writeN),
-- * Namespaces and Prefixes
Namespace(PrefixedNS,PlainNS),
PrefixMappings(PrefixMappings),PrefixMapping(PrefixMapping),
-- * Supporting types
BaseUrl(BaseUrl), NodeSelector, ParseFailure(ParseFailure)
) where
import Prelude hiding (pred)
import qualified Data.Text as T
import System.IO
import Text.Printf
import Data.Binary
import Data.Map(Map)
import GHC.Generics (Generic)
import Data.Hashable(Hashable)
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Network.URI as Network (isURI,uriPath,parseURI)
import Control.DeepSeq (NFData,rnf)
import Text.Parsec
-------------------
-- LValue and constructor functions
-- |The actual value of an RDF literal, represented as the 'LValue'
-- parameter of an 'LNode'.
data LValue =
-- Constructors are not exported, because we need to have more
-- control over the format of the literal text that we store.
-- |A plain (untyped) literal value in an unspecified language.
PlainL !T.Text
-- |A plain (untyped) literal value with a language specifier.
| PlainLL !T.Text !T.Text
-- |A typed literal value consisting of the literal value and
-- the URI of the datatype of the value, respectively.
| TypedL !T.Text !T.Text
deriving Generic
instance Binary LValue
instance NFData LValue where
rnf (PlainL t) = rnf t
rnf (PlainLL t1 t2) = rnf t1 `seq` rnf t2
rnf (TypedL t1 t2) = rnf t1 `seq` rnf t2
-- |Return a PlainL LValue for the given string value.
{-# INLINE plainL #-}
plainL :: T.Text -> LValue
plainL = PlainL
-- |Return a PlainLL LValue for the given string value and language,
-- respectively.
{-# INLINE plainLL #-}
plainLL :: T.Text -> T.Text -> LValue
plainLL = PlainLL
-- |Return a TypedL LValue for the given string value and datatype URI,
-- respectively.
{-# INLINE typedL #-}
typedL :: T.Text -> T.Text -> LValue
typedL val dtype = TypedL (canonicalize dtype val) dtype
-------------------
-- Node and constructor functions
-- |An RDF node, which may be either a URIRef node ('UNode'), a blank
-- node ('BNode'), or a literal node ('LNode').
data Node =
-- |An RDF URI reference. URIs conform to the RFC3986 standard. See
-- <http://www.w3.org/TR/rdf-concepts/#section-Graph-URIref> for more
-- information.
UNode !T.Text
-- |An RDF blank node. See
-- <http://www.w3.org/TR/rdf-concepts/#section-blank-nodes> for more
-- information.
| BNode !T.Text
-- |An RDF blank node with an auto-generated identifier, as used in
-- Turtle.
| BNodeGen !Int
-- |An RDF literal. See
-- <http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal> for more
-- information.
| LNode !LValue
deriving Generic
instance Binary Node
instance NFData Node where
rnf (UNode t) = rnf t
rnf (BNode b) = rnf b
rnf (BNodeGen bgen) = rnf bgen
rnf (LNode lvalue) = rnf lvalue
-- |An alias for 'Node', defined for convenience and readability purposes.
type Subject = Node
-- |An alias for 'Node', defined for convenience and readability purposes.
type Predicate = Node
-- |An alias for 'Node', defined for convenience and readability purposes.
type Object = Node
-- |Return a URIRef node for the given URI.
{-# INLINE unode #-}
unode :: T.Text -> Node
unode = UNode
-- For background on 'unodeValidate', see:
-- http://stackoverflow.com/questions/33250184/unescaping-unicode-literals-found-in-haskell-strings
--
-- Escaped literals are defined in the Turtle spec, and is
-- inherited by the NTriples and XML specification.
-- http://www.w3.org/TR/turtle/#sec-escapes
-- |Validate a URI and return it in a @Just UNode@ if it is
-- valid, otherwise @Nothing@ is returned. Performs the following:
--
-- 1. unescape unicode RDF literals
-- 2. checks validity of this unescaped URI using 'isURI' from 'Network.URI'
-- 3. if the unescaped URI is valid then 'Node' constructed with 'UNode'
unodeValidate :: T.Text -> Maybe Node
unodeValidate t = if Network.isURI uri
then Just (UNode (T.pack uri))
else Nothing
where
Right uri = parse unicodeEscParser "" (T.unpack t)
unicodeEscParser :: Stream s m Char => ParsecT s u m String
unicodeEscParser = do
ss <- many (
try (do { _ <- char '\\'
; _ <- char 'U'
; pos1 <- digit
; pos2 <- digit
; pos3 <- digit
; pos4 <- digit
; pos5 <- digit
; pos6 <- digit
; pos7 <- digit
; pos8 <- digit
; let str = ['\\','x',pos1,pos2,pos3,pos4,pos5,pos6,pos7,pos8]
; return (read ("\"" ++ str ++ "\"") :: String)})
<|>
try (do { _ <- char '\\'
; _ <- char 'u'
; pos1 <- digit
; pos2 <- digit
; pos3 <- digit
; pos4 <- digit
; let str = ['\\','x',pos1,pos2,pos3,pos4]
; return (read ("\"" ++ str ++ "\"") :: String)})
<|>
(anyChar >>= \c -> return [c]))
return (concat ss :: String)
-- |Return a blank node using the given string identifier.
{-# INLINE bnode #-}
bnode :: T.Text -> Node
bnode = BNode
-- |Return a literal node using the given LValue.
{-# INLINE lnode #-}
lnode :: LValue -> Node
lnode = LNode
-------------------
-- Triple and constructor functions
-- |An RDF triple is a statement consisting of a subject, predicate,
-- and object, respectively.
--
-- See <http://www.w3.org/TR/rdf-concepts/#section-triples> for
-- more information.
data Triple = Triple !Node !Node !Node
deriving (Generic)
instance Binary Triple
instance NFData Triple where
rnf (Triple s p o) = rnf s `seq` rnf p `seq` rnf o
-- |A list of triples. This is defined for convenience and readability.
type Triples = [Triple]
-- |A smart constructor function for 'Triple' that verifies the node arguments
-- are of the correct type and creates the new 'Triple' if so or calls 'error'.
-- /subj/ must be a 'UNode' or 'BNode', and /pred/ must be a 'UNode'.
triple :: Subject -> Predicate -> Object -> Triple
triple subj pred obj
| isLNode subj = error $ "subject must be UNode or BNode: " ++ show subj
| isLNode pred = error $ "predicate must be UNode, not LNode: " ++ show pred
| isBNode pred = error $ "predicate must be UNode, not BNode: " ++ show pred
| otherwise = Triple subj pred obj
-- |Answer if given node is a URI Ref node.
{-# INLINE isUNode #-}
isUNode :: Node -> Bool
isUNode (UNode _) = True
isUNode _ = False
-- |Answer if given node is a blank node.
{-# INLINE isBNode #-}
isBNode :: Node -> Bool
isBNode (BNode _) = True
isBNode (BNodeGen _) = True
isBNode _ = False
-- |Answer if given node is a literal node.
{-# INLINE isLNode #-}
isLNode :: Node -> Bool
isLNode (LNode _) = True
isLNode _ = False
{-# INLINE isAbsoluteUri #-}
isAbsoluteUri :: T.Text -> Bool
isAbsoluteUri = Network.isURI . T.unpack
-- |A type class for ADTs that expose views to clients.
class View a b where
view :: a -> b
-- |An RDF value is a set of (unique) RDF triples, together with the
-- operations defined upon them.
--
-- For information about the efficiency of the functions, see the
-- documentation for the particular RDF instance.
--
-- For more information about the concept of an RDF graph, see
-- the following: <http://www.w3.org/TR/rdf-concepts/#section-rdf-graph>.
class RDF rdf where
-- |Return the base URL of this RDF, if any.
baseUrl :: rdf -> Maybe BaseUrl
-- |Return the prefix mappings defined for this RDF, if any.
prefixMappings :: rdf -> PrefixMappings
-- |Return an RDF with the specified prefix mappings merged with
-- the existing mappings. If the Bool arg is True, then a new mapping
-- for an existing prefix will replace the old mapping; otherwise,
-- the new mapping is ignored.
addPrefixMappings :: rdf -> PrefixMappings -> Bool -> rdf
-- |Return an empty RDF.
empty :: rdf
-- |Return a RDF containing all the given triples. Handling of duplicates
-- in the input depend on the particular RDF implementation.
mkRdf :: Triples -> Maybe BaseUrl -> PrefixMappings -> rdf
-- |Return all triples in the RDF, as a list.
--
-- Note that this function returns a list of triples in the RDF as they
-- were added, without removing duplicates and without expanding namespaces.
triplesOf :: rdf -> Triples
-- |Return unique triples in the RDF, as a list.
--
-- This function performs namespace expansion and removal of duplicates.
uniqTriplesOf :: rdf -> Triples
-- |Select the triples in the RDF that match the given selectors.
--
-- The three NodeSelector parameters are optional functions that match
-- the respective subject, predicate, and object of a triple. The triples
-- returned are those in the given graph for which the first selector
-- returns true when called on the subject, the second selector returns
-- true when called on the predicate, and the third selector returns true
-- when called on the ojbect. A 'Nothing' parameter is equivalent to a
-- function that always returns true for the appropriate node; but
-- implementations may be able to much more efficiently answer a select
-- that involves a 'Nothing' parameter rather than an @(id True)@ parameter.
--
-- The following call illustrates the use of select, and would result in
-- the selection of all and only the triples that have a blank node
-- as subject and a literal node as object:
--
-- > select gr (Just isBNode) Nothing (Just isLNode)
--
-- Note: this function may be very slow; see the documentation for the
-- particular RDF implementation for more information.
select :: rdf -> NodeSelector -> NodeSelector -> NodeSelector -> Triples
-- |Return the triples in the RDF that match the given pattern, where
-- the pattern (3 Maybe Node parameters) is interpreted as a triple pattern.
--
-- The @Maybe Node@ params are interpreted as the subject, predicate, and
-- object of a triple, respectively. @Just n@ is true iff the triple has
-- a node equal to @n@ in the appropriate location; @Nothing@ is always
-- true, regardless of the node in the appropriate location.
--
-- For example, @ query rdf (Just n1) Nothing (Just n2) @ would return all
-- and only the triples that have @n1@ as subject and @n2@ as object,
-- regardless of the predicate of the triple.
query :: rdf -> Maybe Node -> Maybe Node -> Maybe Node -> Triples
-- |An RdfParser is a parser that knows how to parse 1 format of RDF and
-- can parse an RDF document of that type from a string, a file, or a URL.
-- Required configuration options will vary from instance to instance.
class RdfParser p where
-- |Parse RDF from the given text, yielding a failure with error message or
-- the resultant RDF.
parseString :: forall rdf. (RDF rdf) => p -> T.Text -> Either ParseFailure rdf
-- |Parse RDF from the local file with the given path, yielding a failure with error
-- message or the resultant RDF in the IO monad.
parseFile :: forall rdf. (RDF rdf) => p -> String -> IO (Either ParseFailure rdf)
-- |Parse RDF from the remote file with the given HTTP URL (https is not supported),
-- yielding a failure with error message or the resultant graph in the IO monad.
parseURL :: forall rdf. (RDF rdf) => p -> String -> IO (Either ParseFailure rdf)
-- |An RdfSerializer is a serializer of RDF to some particular output format, such as
-- NTriples or Turtle.
class RdfSerializer s where
-- |Write the RDF to a file handle using whatever configuration is specified by
-- the first argument.
hWriteRdf :: forall rdf. (RDF rdf) => s -> Handle -> rdf -> IO ()
-- |Write the RDF to stdout; equivalent to @'hWriteRdf' stdout@.
writeRdf :: forall rdf. (RDF rdf) => s -> rdf -> IO ()
-- |Write to the file handle whatever header information is required based on
-- the output format. For example, if serializing to Turtle, this method would
-- write the necessary \@prefix declarations and possibly a \@baseUrl declaration,
-- whereas for NTriples, there is no header section at all, so this would be a no-op.
hWriteH :: forall rdf. (RDF rdf) => s -> Handle -> rdf -> IO ()
-- |Write header information to stdout; equivalent to @'hWriteRdf' stdout@.
writeH :: forall rdf. (RDF rdf) => s -> rdf -> IO ()
-- |Write some triples to a file handle using whatever configuration is specified
-- by the first argument.
--
-- WARNING: if the serialization format has header-level information
-- that should be output (e.g., \@prefix declarations for Turtle), then you should
-- use 'hWriteG' instead of this method unless you're sure this is safe to use, since
-- otherwise the resultant document will be missing the header information and
-- will not be valid.
hWriteTs :: s -> Handle -> Triples -> IO ()
-- |Write some triples to stdout; equivalent to @'hWriteTs' stdout@.
writeTs :: s -> Triples -> IO ()
-- |Write a single triple to the file handle using whatever configuration is
-- specified by the first argument. The same WARNING applies as to 'hWriteTs'.
hWriteT :: s -> Handle -> Triple -> IO ()
-- |Write a single triple to stdout; equivalent to @'hWriteT' stdout@.
writeT :: s -> Triple -> IO ()
-- |Write a single node to the file handle using whatever configuration is
-- specified by the first argument. The same WARNING applies as to 'hWriteTs'.
hWriteN :: s -> Handle -> Node -> IO ()
-- |Write a single node to sdout; equivalent to @'hWriteN' stdout@.
writeN :: s -> Node -> IO ()
-- |The base URL of an RDF.
newtype BaseUrl = BaseUrl T.Text
deriving (Eq, Ord, Show, NFData, Generic)
instance Binary BaseUrl
-- |A 'NodeSelector' is either a function that returns 'True'
-- or 'False' for a node, or Nothing, which indicates that all
-- nodes would return 'True'.
--
-- The selector is said to select, or match, the nodes for
-- which it returns 'True'.
--
-- When used in conjunction with the 'select' method of 'Graph', three
-- node selectors are used to match a triple.
type NodeSelector = Maybe (Node -> Bool)
-- |Represents a failure in parsing an N-Triples document, including
-- an error message with information about the cause for the failure.
newtype ParseFailure = ParseFailure String
deriving (Eq, Show)
-- |A node is equal to another node if they are both the same type
-- of node and if the field values are equal.
instance Eq Node where
(UNode bs1) == (UNode bs2) = bs1 == bs2
(BNode bs1) == (BNode bs2) = bs1 == bs2
(BNodeGen i1) == (BNodeGen i2) = i1 == i2
(LNode l1) == (LNode l2) = l1 == l2
_ == _ = False
-- |Node ordering is defined first by type, with Unode < BNode < BNodeGen
-- < LNode PlainL < LNode PlainLL < LNode TypedL, and secondly by
-- the natural ordering of the node value.
--
-- E.g., a '(UNode _)' is LT any other type of node, and a
-- '(LNode (TypedL _ _))' is GT any other type of node, and the ordering
-- of '(BNodeGen 44)' and '(BNodeGen 3)' is that of the values, or
-- 'compare 44 3', GT.
instance Ord Node where
compare = compareNode
compareNode :: Node -> Node -> Ordering
compareNode (UNode bs1) (UNode bs2) = compare bs1 bs2
compareNode (UNode _) _ = LT
compareNode (BNode bs1) (BNode bs2) = compare bs1 bs2
compareNode (BNode _) (UNode _) = GT
compareNode (BNode _) _ = LT
compareNode (BNodeGen i1) (BNodeGen i2) = compare i1 i2
compareNode (BNodeGen _) (LNode _) = LT
compareNode (BNodeGen _) _ = GT
compareNode (LNode (PlainL bs1)) (LNode (PlainL bs2)) = compare bs1 bs2
compareNode (LNode (PlainL _)) (LNode _) = LT
compareNode (LNode (PlainLL bs1 bs1')) (LNode (PlainLL bs2 bs2')) =
case compare bs1' bs2' of
EQ -> compare bs1 bs2
LT -> LT
GT -> GT
compareNode (LNode (PlainLL _ _)) (LNode (PlainL _)) = GT
compareNode (LNode (PlainLL _ _)) (LNode _) = LT
compareNode (LNode (TypedL bsType1 bs1)) (LNode (TypedL bsType2 bs2)) =
case compare bs1 bs2 of
EQ -> compare bsType1 bsType2
LT -> LT
GT -> GT
compareNode (LNode (TypedL _ _)) (LNode _) = GT
compareNode (LNode _) _ = GT
instance Hashable Node
-- |Two triples are equal iff their respective subjects, predicates, and objects
-- are equal.
instance Eq Triple where
(Triple s1 p1 o1) == (Triple s2 p2 o2) = s1 == s2 && p1 == p2 && o1 == o2
-- |The ordering of triples is based on that of the subject, predicate, and object
-- of the triple, in that order.
instance Ord Triple where
(Triple s1 p1 o1) `compare` (Triple s2 p2 o2) =
case compareNode s1 s2 of
EQ -> case compareNode p1 p2 of
EQ -> compareNode o1 o2
LT -> LT
GT -> GT
GT -> GT
LT -> LT
-- |Two 'LValue' values are equal iff they are of the same type and all fields are
-- equal.
instance Eq LValue where
(PlainL bs1) == (PlainL bs2) = bs1 == bs2
(PlainLL bs1 bs1') == (PlainLL bs2 bs2') = bs1' == bs2' && bs1 == bs2
(TypedL bsType1 bs1) == (TypedL bsType2 bs2) = bsType1 == bsType2 && bs1 == bs2
_ == _ = False
-- |Ordering of 'LValue' values is as follows: (PlainL _) < (PlainLL _ _)
-- < (TypedL _ _), and values of the same type are ordered by field values,
-- with '(PlainLL literalValue language)' being ordered by language first and
-- literal value second, and '(TypedL literalValue datatypeUri)' being ordered
-- by datatype first and literal value second.
instance Ord LValue where
compare = compareLValue
{-# INLINE compareLValue #-}
compareLValue :: LValue -> LValue -> Ordering
compareLValue (PlainL bs1) (PlainL bs2) = compare bs1 bs2
compareLValue (PlainL _) _ = LT
compareLValue _ (PlainL _) = GT
compareLValue (PlainLL bs1 bs1') (PlainLL bs2 bs2') =
case compare bs1' bs2' of
EQ -> compare bs1 bs2
GT -> GT
LT -> LT
compareLValue (PlainLL _ _) _ = LT
compareLValue _ (PlainLL _ _) = GT
compareLValue (TypedL l1 t1) (TypedL l2 t2) =
case compare t1 t2 of
EQ -> compare l1 l2
GT -> GT
LT -> LT
instance Hashable LValue
-- String representations of the various data types; generally NTriples-like.
instance Show Triple where
show (Triple s p o) =
printf "Triple(%s,%s,%s)" (show s) (show p) (show o)
instance Show Node where
show (UNode uri) = "UNode(" ++ show uri ++ ")"
show (BNode i) = "BNode(" ++ show i ++ ")"
show (BNodeGen genId) = "BNodeGen(" ++ show genId ++ ")"
show (LNode lvalue) = "LNode(" ++ show lvalue ++ ")"
instance Show LValue where
show (PlainL lit) = "PlainL(" ++ T.unpack lit ++ ")"
show (PlainLL lit lang) = "PlainLL(" ++ T.unpack lit ++ ", " ++ T.unpack lang ++ ")"
show (TypedL lit dtype) = "TypedL(" ++ T.unpack lit ++ "," ++ show dtype ++ ")"
------------------------
-- Prefix mappings
-- |Represents a namespace as either a prefix and uri, respectively,
-- or just a uri.
data Namespace = PrefixedNS T.Text T.Text -- prefix and ns uri
| PlainNS T.Text -- ns uri alone
instance Eq Namespace where
(PrefixedNS _ u1) == (PrefixedNS _ u2) = u1 == u2
(PlainNS u1) == (PlainNS u2) = u1 == u2
(PrefixedNS _ u1) == (PlainNS u2) = u1 == u2
(PlainNS u1) == (PrefixedNS _ u2) = u1 == u2
instance Show Namespace where
show (PlainNS uri) = T.unpack uri
show (PrefixedNS prefix uri) = printf "(PrefixNS %s %s)" (T.unpack prefix) (T.unpack uri)
-- |An alias for a map from prefix to namespace URI.
newtype PrefixMappings = PrefixMappings (Map T.Text T.Text)
deriving (Eq, Ord,NFData, Generic)
instance Binary PrefixMappings
instance Show PrefixMappings where
-- This is really inefficient, but it's not used much so not what
-- worth optimizing yet.
show (PrefixMappings pmap) = printf "PrefixMappings [%s]" mappingsStr
where showPM = show . PrefixMapping
mappingsStr = List.intercalate ", " (map showPM (Map.toList pmap))
-- |A mapping of a prefix to the URI for that prefix.
newtype PrefixMapping = PrefixMapping (T.Text, T.Text)
deriving (Eq, Ord)
instance Show PrefixMapping where
show (PrefixMapping (prefix, uri)) = printf "PrefixMapping (%s, %s)" (show prefix) (show uri)
-----------------
-- Miscellaneous helper functions used throughout the project
-- Resolve a prefix using the given prefix mappings and base URL. If the prefix is
-- empty, then the base URL will be used if there is a base URL and if the map
-- does not contain an entry for the empty prefix.
resolveQName :: Maybe BaseUrl -> T.Text -> PrefixMappings -> Maybe T.Text
resolveQName mbaseUrl prefix (PrefixMappings pms') =
case (mbaseUrl, T.null prefix) of
(Just (BaseUrl base), True) -> Just $ Map.findWithDefault base T.empty pms'
(Nothing, True) -> Nothing
(_, _ ) -> Map.lookup prefix pms'
{- alternative implementation from Text.RDF.RDF4H.ParserUtils
--
-- Resolve a prefix using the given prefix mappings and base URL. If the prefix is
-- empty, then the base URL will be used if there is a base URL and if the map
-- does not contain an entry for the empty prefix.
resolveQName :: Maybe BaseUrl -> T.Text -> PrefixMappings -> T.Text
resolveQName mbaseUrl prefix (PrefixMappings pms') =
case (mbaseUrl, T.null prefix) of
(Just (BaseUrl base), True) -> Map.findWithDefault base T.empty pms'
(Nothing, True) -> err1
(_, _ ) -> Map.findWithDefault err2 prefix pms'
where
err1 = error "Cannot resolve empty QName prefix to a Base URL."
err2 = error ("Cannot resolve QName prefix: " ++ T.unpack prefix)
-}
-- Resolve a URL fragment found on the right side of a prefix mapping
-- by converting it to an absolute URL if possible.
absolutizeUrl :: Maybe BaseUrl -> Maybe T.Text -> T.Text -> T.Text
absolutizeUrl mbUrl mdUrl urlFrag =
if isAbsoluteUri urlFrag then urlFrag else
(case (mbUrl, mdUrl) of
(Nothing, Nothing) -> urlFrag
(Just (BaseUrl bUrl), Nothing) -> bUrl `T.append` urlFrag
(Nothing, Just dUrl) -> if isHash urlFrag then
dUrl `T.append` urlFrag else urlFrag
(Just (BaseUrl bUrl), Just dUrl) -> (if isHash urlFrag then dUrl
else bUrl)
`T.append` urlFrag)
where
isHash bs' = bs' == "#"
{- alternative implementation from Text.RDF.RDF4H.ParserUtils
--
-- Resolve a URL fragment found on the right side of a prefix mapping by converting it to an absolute URL if possible.
absolutizeUrl :: Maybe BaseUrl -> Maybe T.Text -> T.Text -> T.Text
absolutizeUrl mbUrl mdUrl urlFrag =
if isAbsoluteUri urlFrag then urlFrag else
(case (mbUrl, mdUrl) of
(Nothing, Nothing) -> urlFrag
(Just (BaseUrl bUrl), Nothing) -> bUrl `T.append` urlFrag
(Nothing, Just dUrl) -> if isHash urlFrag then
dUrl `T.append` urlFrag else urlFrag
(Just (BaseUrl bUrl), Just dUrl) -> (if isHash urlFrag then dUrl
else bUrl)
`T.append` urlFrag)
where
isHash bs' = T.length bs' == 1 && T.head bs' == '#'
-}
{-# INLINE mkAbsoluteUrl #-}
-- Make an absolute URL by returning as is if already an absolute URL and otherwise
-- appending the URL to the given base URL.
mkAbsoluteUrl :: T.Text -> T.Text -> T.Text
mkAbsoluteUrl base url =
if isAbsoluteUri url then url else base `T.append` url
-----------------
-- Internal canonicalize functions, don't export
-- |Canonicalize the given 'T.Text' value using the 'T.Text'
-- as the datatype URI.
{-# NOINLINE canonicalize #-}
canonicalize :: T.Text -> T.Text -> T.Text
canonicalize typeTxt litValue =
case Map.lookup typeTxt canonicalizerTable of
Nothing -> litValue
Just fn -> fn litValue
-- A table of mappings from a 'T.Text' URI
-- to a function that canonicalizes a T.Text
-- assumed to be of that type.
{-# NOINLINE canonicalizerTable #-}
canonicalizerTable :: Map T.Text (T.Text -> T.Text)
canonicalizerTable =
Map.fromList [(integerUri, _integerStr), (doubleUri, _doubleStr),
(decimalUri, _decimalStr)]
where
integerUri = "http://www.w3.org/2001/XMLSchema#integer"
decimalUri = "http://www.w3.org/2001/XMLSchema#decimal"
doubleUri = "http://www.w3.org/2001/XMLSchema#double"
_integerStr, _decimalStr, _doubleStr :: T.Text -> T.Text
_integerStr = T.dropWhile (== '0')
-- exponent: [eE] ('-' | '+')? [0-9]+
-- ('-' | '+') ? ( [0-9]+ '.' [0-9]* exponent | '.' ([0-9])+ exponent | ([0-9])+ exponent )
_doubleStr s = T.pack $ show (read $ T.unpack s :: Double)
-- ('-' | '+')? ( [0-9]+ '.' [0-9]* | '.' ([0-9])+ | ([0-9])+ )
_decimalStr s = -- haskell double parser doesn't handle '1.'..,
case T.last s of -- so we add a zero if that's the case and then parse
'.' -> f (s `T.snoc` '0')
_ -> f s
where f s' = T.pack $ show (read $ T.unpack s' :: Double)
-- | Removes "file://" schema from URIs in 'UNode' nodes
fileSchemeToFilePath :: Node -> Maybe T.Text
fileSchemeToFilePath (UNode fileScheme) =
if T.pack "file://" `T.isPrefixOf` fileScheme
then fmap (T.pack . Network.uriPath) (Network.parseURI (T.unpack fileScheme))
else Nothing
fileSchemeToFilePath _ = Nothing
| cordawyn/rdf4h | src/Data/RDF/Types.hs | bsd-3-clause | 27,469 | 0 | 23 | 7,195 | 4,933 | 2,688 | 2,245 | -1 | -1 |
module Offheap () where
| schernichkin/BSPM | offheap/src/Offheap.hs | bsd-3-clause | 24 | 0 | 3 | 4 | 7 | 5 | 2 | 1 | 0 |
{-# LANGUAGE CPP, OverloadedStrings #-}
module Data.ByteString.Builder.Scientific
( scientificBuilder
, formatScientificBuilder
, FPFormat(..)
) where
import Data.Scientific (Scientific)
import qualified Data.Scientific as Scientific
import Data.Text.Lazy.Builder.RealFloat (FPFormat(..))
import qualified Data.ByteString.Char8 as BC8
#if !MIN_VERSION_bytestring(0,10,2)
import Data.ByteString.Lazy.Builder (Builder, string8, char8)
import Data.ByteString.Lazy.Builder.ASCII (intDec)
import Data.ByteString.Lazy.Builder.Extras (byteStringCopy)
#else
import Data.ByteString.Builder (Builder, string8, char8, intDec)
import Data.ByteString.Builder.Extra (byteStringCopy)
#endif
import Utils (roundTo, i2d)
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid (mempty)
#endif
#if MIN_VERSION_base(4,5,0)
import Data.Monoid ((<>))
#else
import Data.Monoid (Monoid, mappend)
(<>) :: Monoid a => a -> a -> a
(<>) = mappend
infixr 6 <>
#endif
-- | A @ByteString@ @Builder@ which renders a scientific number to full
-- precision, using standard decimal notation for arguments whose
-- absolute value lies between @0.1@ and @9,999,999@, and scientific
-- notation otherwise.
scientificBuilder :: Scientific -> Builder
scientificBuilder = formatScientificBuilder Generic Nothing
-- | Like 'scientificBuilder' but provides rendering options.
formatScientificBuilder :: FPFormat
-> Maybe Int -- ^ Number of decimal places to render.
-> Scientific
-> Builder
formatScientificBuilder fmt decs scntfc
| scntfc < 0 = char8 '-' <> doFmt fmt (Scientific.toDecimalDigits (-scntfc))
| otherwise = doFmt fmt (Scientific.toDecimalDigits scntfc)
where
doFmt format (is, e) =
let ds = map i2d is in
case format of
Generic ->
doFmt (if e < 0 || e > 7 then Exponent else Fixed)
(is,e)
Exponent ->
case decs of
Nothing ->
let show_e' = intDec (e-1) in
case ds of
"0" -> byteStringCopy "0.0e0"
[d] -> char8 d <> byteStringCopy ".0e" <> show_e'
(d:ds') -> char8 d <> char8 '.' <> string8 ds' <> char8 'e' <> show_e'
[] -> error $ "Data.ByteString.Builder.Scientific.formatScientificBuilder" ++
"/doFmt/Exponent: []"
Just dec ->
let dec' = max dec 1 in
case is of
[0] -> byteStringCopy "0." <>
byteStringCopy (BC8.replicate dec' '0') <>
byteStringCopy "e0"
_ ->
let
(ei,is') = roundTo (dec'+1) is
(d:ds') = map i2d (if ei > 0 then init is' else is')
in
char8 d <> char8 '.' <> string8 ds' <> char8 'e' <> intDec (e-1+ei)
Fixed ->
let
mk0 ls = case ls of { "" -> char8 '0' ; _ -> string8 ls}
in
case decs of
Nothing
| e <= 0 -> byteStringCopy "0." <>
byteStringCopy (BC8.replicate (-e) '0') <>
string8 ds
| otherwise ->
let
f 0 s rs = mk0 (reverse s) <> char8 '.' <> mk0 rs
f n s "" = f (n-1) ('0':s) ""
f n s (r:rs) = f (n-1) (r:s) rs
in
f e "" ds
Just dec ->
let dec' = max dec 0 in
if e >= 0 then
let
(ei,is') = roundTo (dec' + e) is
(ls,rs) = splitAt (e+ei) (map i2d is')
in
mk0 ls <> (if null rs then mempty else char8 '.' <> string8 rs)
else
let
(ei,is') = roundTo dec' (replicate (-e) 0 ++ is)
d:ds' = map i2d (if ei > 0 then is' else 0:is')
in
char8 d <> (if null ds' then mempty else char8 '.' <> string8 ds')
| phadej/scientific | src/Data/ByteString/Builder/Scientific.hs | bsd-3-clause | 3,927 | 0 | 29 | 1,337 | 1,116 | 581 | 535 | 79 | 18 |
-- | Check if packages can build against the lastest dependencies on Hackage
module Scoutess.Service.PackDeps.Core where
| cartazio/scoutess | Scoutess/Service/PackDeps/Core.hs | bsd-3-clause | 121 | 0 | 3 | 16 | 9 | 7 | 2 | 1 | 0 |
module TiFresh where
import TiMonad(IM,freshInt)
import TiTypes
import MUtils
import TiKinds
class Fresh a where
fresh :: IM i c a
freshlist n = sequence (replicate n fresh)
instance Fresh Int where
fresh = freshInt
instance Fresh String where
fresh = (show::Int->String) # fresh
--instance Fresh Tyvar where
-- fresh = tvar # fresh
instance (Fresh a,Fresh b) => Fresh (a,b) where
fresh = (,) # fresh <# fresh
instance Fresh i => Fresh (Type i) where
fresh = tyvar # fresh
instance Fresh i => Fresh (Scheme i) where
fresh = forall' [] # fresh
instance Fresh t => Fresh (Qual i t) where
fresh = ([]:=>) # fresh
--instance Fresh QId where
-- fresh = dictName # fresh
instance Fresh KVar where
fresh = KVar # fresh
instance Fresh Kind where
fresh = Kvar # fresh
instance Fresh (TypeInfo i) where
fresh = return Tyvar
| forste/haReFork | tools/base/TI/TiFresh.hs | bsd-3-clause | 850 | 0 | 8 | 183 | 312 | 167 | 145 | 26 | 1 |
module Forum.Internal.TH where
import Data.Char (isUpper, toLower)
import qualified Language.Haskell.TH as TH
import qualified Language.Haskell.TH.Syntax as TH
import Data.String (fromString)
import Data.Proxy (Proxy(..))
import Forum.Internal.Types
import Forum.Internal.Utils
import Forum.Internal.HasTable
mkStmts :: TH.Name -> THOptions -> TH.Q [TH.Dec]
mkStmts n opts = do
r <- TH.reify n
case r of
TH.TyConI (TH.DataD _ctx typName _ [TH.RecC _conName fields] _)
-> do
fs <- mapM (mkField typName (TH.ConT typName) opts) fields
f <- mkTable typName (TH.ConT typName) opts
let fieldNames = (\(n, _, _) -> n) <$> fields
inst <- mkHasTable typName fieldNames opts
return . concat $ inst : f : fs
a -> fail $ show a
mkField :: TH.Name -> TH.Type -> THOptions -> TH.VarStrictType -> TH.Q [TH.Dec]
mkField typName otyp opts (fieldName, _, typ) = do
let name = TH.mkName $ fnRenamer opts (TH.nameBase typName) (TH.nameBase fieldName)
dbname = dbRenamer opts (TH.nameBase typName) (TH.nameBase fieldName)
ktyp = ''Key
case typ of
TH.AppT (TH.AppT (TH.AppT ktyp otherTbl) tblKey) keyTyp -> do
t <- [t| forall st. Statement st $(return otyp) $(return otherTbl) |]
d <- [d|
$(TH.varP name) = mkFKStmt (Proxy :: Proxy $(return typ)) (fromString $(TH.litE $ TH.StringL dbname))
|]
return $ TH.SigD name t : d
_ -> do
t <- [t| forall st. Statement st $(return otyp) $(return typ) |]
d <- [d|
$(TH.varP name) = mkFieldStmt $ fromString $(TH.litE $ TH.StringL dbname)
|]
return $ TH.SigD name t : d
mkTable :: TH.Name -> TH.Type -> THOptions -> TH.Q [TH.Dec]
mkTable typName otyp opts = do
let name = TH.mkName $ tableFnRenamer opts (TH.nameBase typName)
t <- [t| forall st. Statement st () $(return otyp) |]
d <- [d| $(TH.varP name) = mkTableStmt tbl fields
where
proxy = Proxy :: Proxy $(TH.conT typName)
tbl = SimpleName $ tableName proxy
fields = SimpleName <$> tableFields proxy
|]
return $ TH.SigD name t : d
mkHasTable :: TH.Name -> [TH.Name] -> THOptions -> TH.Q [TH.Dec]
mkHasTable typName fields opts = do
let dbname = tableDbRenamer opts (TH.nameBase typName)
fields' = dbRenamer opts (TH.nameBase typName) . TH.nameBase <$> fields
fieldExps = TH.ListE (TH.LitE . TH.StringL <$> fields')
[d| instance HasTable $(TH.conT typName) where
tableName = const $ fromString $(TH.litE $ TH.StringL dbname)
tableFields _ = fromString <$> $(return fieldExps)
|]
defaultTHOptions :: THOptions
defaultTHOptions = THOptions
{ fnRenamer = \_typ field -> field ++ "_"
, dbRenamer = \_typ field -> snakeCaseRenamer field
, tableDbRenamer = unTitleCase
, tableFnRenamer = unTitleCase
}
snakeCaseRenamer :: String -> String
snakeCaseRenamer [] = error "Cannot be empty string"
snakeCaseRenamer (n:ns) = go [toLower n] ns
where
go r [] = reverse r
go r (x:xs) | isUpper x = go (toLower x : '_' : r) xs
| otherwise = go (x : r) xs
| jkarni/forum | src/Forum/Internal/TH.hs | bsd-3-clause | 3,127 | 0 | 18 | 771 | 986 | 515 | 471 | -1 | -1 |
module Lib.Task25 where
import Data.List
import Data.Maybe
fibs = unfoldr (\(a,b,i) -> Just ((a,i),(b,a+b,i+1))) (1,1,1)
task25 = snd $ fromJust $ find (\(a,i) -> div a ((10^999)::Integer) > 0 ) fibs
| Austrotaxus/EulerProj | src/Lib/Task25.hs | bsd-3-clause | 218 | 0 | 13 | 49 | 138 | 81 | 57 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
--------------------------------------------------------------------------
-- |
-- Module: Game.Waddle.Load
-- Copyright: (c) 2015 Martin Grabmueller
-- License: BSD3
--
-- Maintainer: martin@grabmueller.de
-- Stability: provisional
-- Portability: portable
--
-- WAD file loader. Loads the file into memory and parses the common
-- lumps into Haskell values.
--
-- I recommend the Unofficial Doom Specification by Matthew S Fell,
-- available at <http://aiforge.net/test/wadview/dmspec16.txt> and the
-- Doom Wiki at <http://doomwiki.org> for details.
----------------------------------------------------------------------------
module Game.Waddle.Load
(load) where
import Game.Waddle.Types
import Control.Exception
import Text.Printf
import Data.Bits
import Data.Int
import Data.Word
import Data.CaseInsensitive(CI, mk)
import Data.Map(Map)
import qualified Data.Map as Map
import Data.Binary.Get
import Control.Monad
import Control.Applicative
import Data.ByteString(ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import qualified Data.ByteString.Lazy as BSL
getInt32le :: Get Int32
getInt32le = fromIntegral <$> getWord32le
getInt16le :: Get Int16
getInt16le = fromIntegral <$> getWord16le
getWadHeader :: Get WadHeader
getWadHeader =
WadHeader <$>
getByteString 4 <*>
getInt32le <*>
getInt32le
getWadEntry :: Get WadEntry
getWadEntry =
WadEntry <$>
getInt32le <*>
getInt32le <*>
(trimNUL <$> getByteString 8)
getWadEntryList :: Int -> Int -> Get [WadEntry]
getWadEntryList offset cnt = skip offset >> sequence (replicate cnt getWadEntry)
trimNUL :: ByteString -> ByteString
trimNUL s =
case BS.findIndex (== 0) s of
Nothing -> s
Just i -> BS.take i s
-- | Load a WAD file into a 'Wad' value. The complete file is read
-- into memory eagerly, assuming that all the content will be needed
-- anyway by the application.
--
-- May throw 'IOException' or 'WadException'.
--
load :: FilePath -> IO Wad
load fp = do
wadContent <- BS.readFile fp
header@WadHeader{..} <- runGet' "WAD header" getWadHeader wadContent
wadEntries <- runGet' "WAD directory"
(getWadEntryList
(fromIntegral wadHeaderDirectoryOffset)
(fromIntegral wadHeaderLumpCount))
wadContent
let lumpLookup = mkLookup wadEntries wadContent
wadLumps = mkWadLumps wadEntries wadContent
p <- parseWad wadEntries wadLumps lumpLookup
return $ Wad {wadHeader = header,
wadDirectory = wadEntries,
wadLumps = wadLumps,
wadLumpLookup = lumpLookup,
wadFlats = psFlats p,
wadSprites = psSprites p,
wadPatches = psPatches p,
wadTextures = psTextures p,
wadPNames = psPNames p,
wadLevels = psLevels p,
wadColormap = psColormap p,
wadPalettes = psPalettes p}
where
mkWadLumps entries content =
map (\ WadEntry{..} ->
(BS.take (fromIntegral wadEntrySize) (BS.drop (fromIntegral wadEntryOffset) content))) entries
mkLookup entries content =
foldr (\ WadEntry{..} tab ->
Map.insert
(mk wadEntryName)
(BS.take (fromIntegral wadEntrySize) (BS.drop (fromIntegral wadEntryOffset) content))
tab)
Map.empty entries
data PState
= NoState
| InLevel LumpName
| InSprites
| InFlats
| InPatches
deriving (Show)
data ExtPicture = ExtPicture {
extPictureWidth :: Int16,
extPictureHeight :: Int16,
extPictureLeftOffset :: Int16,
extPictureTopOffset :: Int16,
extPictureColStarts :: [Int32]
}
deriving (Show)
getExtPicture :: Get ExtPicture
getExtPicture = do
w <- getInt16le
h <- getInt16le
l <- getInt16le
t <- getInt16le
colStarts <- replicateM (fromIntegral w) getInt32le
return $ ExtPicture w h l t colStarts
data ExtPost
= ExtPostEnd
| ExtPost {
extPostTop :: Word8,
extPostCount :: Word8,
extPostPixels :: ByteString,
extPostNext :: ExtPost
}
deriving (Show)
getExtPost :: Get ExtPost
getExtPost = do
top <- getWord8
case top of
255 ->
return ExtPostEnd
_ -> do
cnt <- getWord8
_skip1 <- getWord8
px <- getByteString (fromIntegral cnt)
_skip2 <- getWord8
e <- getExtPost
return $ ExtPost top cnt px e
convertPosts :: ExtPost -> [Post]
convertPosts ExtPostEnd = []
convertPosts ExtPost{..} =
Post {postTop = extPostTop,
postPixels = extPostPixels} : convertPosts extPostNext
convertPicture :: ExtPicture -> [ExtPost] -> Picture
convertPicture ExtPicture{..} extPosts =
Picture {pictureWidth = fromIntegral extPictureWidth,
pictureHeight = fromIntegral extPictureHeight,
pictureLeftOffset = fromIntegral extPictureLeftOffset,
pictureTopOffset = fromIntegral extPictureTopOffset,
picturePosts = map convertPosts extPosts}
getThingList :: Int -> Get [Thing]
getThingList cnt =
sequence (replicate cnt $
Thing <$>
getInt16le <*>
getInt16le <*>
getInt16le <*>
(thingTypeFromNumber <$> getInt16le) <*>
getInt16le)
getVertexList :: Int -> Get [Vertex]
getVertexList cnt =
sequence (replicate cnt $
Vertex <$>
getInt16le <*>
getInt16le)
getLineDefList :: Int -> Get [LineDef]
getLineDefList cnt =
sequence (replicate cnt $
LineDef <$>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le <*>
(toMB <$> getInt16le))
where
toMB n | n < 0 = Nothing
toMB n = Just n
getSideDefList :: Int -> Get [SideDef]
getSideDefList cnt =
sequence (replicate cnt $
SideDef <$>
getInt16le <*>
getInt16le <*>
(trimNUL <$> getByteString 8) <*>
(trimNUL <$> getByteString 8) <*>
(trimNUL <$> getByteString 8) <*>
getInt16le)
getSeg :: Get Seg
getSeg =
Seg <$>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le
getSegList :: Int -> Get [Seg]
getSegList cnt =
sequence (replicate cnt getSeg)
getSSector :: Get SSector
getSSector =
SSector <$>
getInt16le <*>
getInt16le
getSSectorList :: Int -> Get [SSector]
getSSectorList cnt =
sequence (replicate cnt getSSector)
getSectorList :: Int -> Get [Sector]
getSectorList cnt =
sequence (replicate cnt $
Sector <$>
getInt16le <*>
getInt16le <*>
(trimNUL <$> getByteString 8) <*>
(trimNUL <$> getByteString 8) <*>
getInt16le <*>
getInt16le <*>
getInt16le)
getNode :: Get Node
getNode =
Node <$>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le <*>
getInt16le <*>
(lr <$> getWord16le) <*>
(lr <$> getWord16le)
where
lr x = if x .&. 0x8000 == 0
then Left (fromIntegral x)
else Right (fromIntegral (x .&. 0x7fff))
getNodeList :: Int -> Get [Node]
getNodeList cnt =
sequence (replicate cnt getNode)
getBlocklists :: Int -> Get [Blocklist]
getBlocklists cnt | cnt == 0 = return []
getBlocklists cnt = do
0 <- getInt16le
vals <- getVals
rest <- getBlocklists (cnt - 1)
return $ vals : rest
where
getVals :: Get Blocklist
getVals = do
i <- getInt16le
case i of
-1 -> return []
_ -> do
r <- getVals
return $ i : r
getBlocklist :: Get Blocklist
getBlocklist = do
0 <- getInt16le
go
where
go = do
i <- getInt16le
case i of
-1 -> return []
_ -> do
r <- go
return $ i : r
data ExtBlockmap = ExtBlockmap {
extBlockmapOriginX :: Int16,
extBlockmapOriginY :: Int16,
extBlockmapColumns :: Int16,
extBlockmapRows :: Int16,
extBlockmapOffsets :: [Word16]
}
getBlockmap :: Get ExtBlockmap
getBlockmap = do
ox <- getInt16le
oy <- getInt16le
cols <- getInt16le
rows <- getInt16le
offsets <- sequence (replicate (fromIntegral (cols * rows)) getWord16le)
return ExtBlockmap {
extBlockmapOriginX = ox,
extBlockmapOriginY = oy,
extBlockmapColumns = cols,
extBlockmapRows = rows,
extBlockmapOffsets = offsets
}
getPatchDescriptor :: Get PatchDescriptor
getPatchDescriptor =
PatchDescriptor <$>
(fromIntegral <$> getWord16le) <*>
(fromIntegral <$> getWord16le) <*>
(fromIntegral <$> getWord16le) <*>
(fromIntegral <$> getWord16le) <*>
(fromIntegral <$> getWord16le)
getTexture :: Get Texture
getTexture = do
n <- trimNUL <$> getByteString 8
0 <- getWord16le
0 <- getWord16le
w <- fromIntegral <$> getWord16le
h <- fromIntegral <$> getWord16le
0 <- getWord16le
0 <- getWord16le
pdCnt <- fromIntegral <$> getWord16le
pDescs <- sequence (replicate pdCnt getPatchDescriptor)
return Texture {
textureName = n,
textureWidth = w,
textureHeight = h,
texturePatchDescriptors = pDescs
}
getTextures :: Get (Map (CI LumpName) Texture)
getTextures = do
cnt <- fromIntegral <$> getWord32le
_ <- sequence (replicate cnt getWord32le)
textures <- sequence (replicate cnt getTexture)
return $ Map.fromList $ map (\ tex@Texture{..} -> (mk textureName, tex)) textures
getPNames :: Get (Map Int LumpName)
getPNames = do
cnt <- fromIntegral <$> getWord32le
names <- sequence (replicate cnt (getByteString 8))
return $ Map.fromList (zip [0..] (map trimNUL names))
data ParseState = ParseState {
psState :: PState,
psLumpLookup :: Map (CI LumpName) ByteString,
psMaps :: Map (CI LumpName) Level,
psSprites :: Map (CI LumpName) Sprite,
psFlats :: Map (CI LumpName) Flat,
psPatches :: Map (CI LumpName) Patch,
psPNames :: Map Int LumpName,
psTextures :: Map (CI LumpName) Texture,
psLevels :: Map (CI LumpName) Level,
psThings :: [Thing],
psVertices :: [Vertex],
psLineDefs :: [LineDef],
psSideDefs :: [SideDef],
psSegs :: [Seg],
psSSectors :: [SSector],
psSectors :: [Sector],
psNodes :: [Node],
psReject :: Maybe Reject,
psBlockmap :: Maybe Blockmap,
psPalettes :: Maybe Palettes,
psColormap :: Maybe Colormap
}
initParseState :: Map (CI LumpName) ByteString -> ParseState
initParseState lu = ParseState {
psState = NoState,
psLumpLookup = lu,
psMaps = Map.empty,
psSprites = Map.empty,
psFlats = Map.empty,
psPatches = Map.empty,
psPNames = Map.empty,
psTextures = Map.empty,
psLevels = Map.empty,
psThings = [],
psVertices = [],
psLineDefs = [],
psSideDefs = [],
psSegs = [],
psSSectors = [],
psSectors = [],
psNodes = [],
psReject = Nothing,
psBlockmap = Nothing,
psPalettes = Nothing,
psColormap = Nothing
}
-- | Run a 'Get a' on a strict bytestring and return it's result. On
-- decoding error, throw a 'WadExceptionDecodeError' exception.
--
runGet' :: String -> Get a -> ByteString -> IO a
runGet' ctxt get bs =
case runGetOrFail get (BSL.fromChunks [bs]) of
Left (_, _, err) -> throwIO $ WadExceptionDecodeError ctxt err
Right (_, _, r) -> return r
-- | Parser for WAD file contents. The resulting parse state contains
-- all data from the WAD, decoded and organized.
--
parseWad :: [WadEntry] -> [ByteString] -> Map (CI LumpName) ByteString -> IO ParseState
parseWad entries lumps lumpMap = foldM parseStep (initParseState lumpMap) (zip lumps entries)
where
parseStep ps@ParseState{psState = NoState}
lumpWe@(_, WadEntry{..}) = do
case wadEntryName of
"F_START" -> return ps{psState = InFlats}
"S_START" -> return ps{psState = InSprites}
"P_START" -> return ps{psState = InPatches}
"PLAYPAL" -> parsePalettes ps lumpWe
"COLORMAP" -> parseColormap ps lumpWe
"ENDOOM" -> return ps
"DEMO1" -> return ps
"DEMO2" -> return ps
"DEMO3" -> return ps
"TEXTURE1" -> parseTextures ps lumpWe
"TEXTURE2" -> parseTextures ps lumpWe
"PNAMES" -> parsePNames ps lumpWe
"GENMIDI" -> return ps
"HELP" -> return ps
"HELP1" -> return ps
"VICTORY2" -> return ps
"PFUB1" -> return ps
"PFUB2" -> return ps
"END0" -> return ps
"END1" -> return ps
"END2" -> return ps
"END3" -> return ps
"END4" -> return ps
"END5" -> return ps
"END6" -> return ps
"ENDPIC" -> return ps
"TITLEPIC" -> return ps
"CREDIT" -> return ps
"BOSSBACK" -> return ps
_ | "AMMNUM" `BS8.isPrefixOf` wadEntryName -> return ps
"STBAR" -> return ps
"INTERPIC" -> return ps
"_DEUTEX_" -> return ps
_ | "STGNUM" `BS8.isPrefixOf` wadEntryName -> return ps
_ | "BRDR" `BS8.isPrefixOf` wadEntryName -> return ps
_ | "WI" `BS8.isPrefixOf` wadEntryName -> return ps
_ | "ST" `BS8.isPrefixOf` wadEntryName -> return ps
_ | "M_" `BS8.isPrefixOf` wadEntryName -> return ps
_ | "D" `BS8.isPrefixOf` wadEntryName -> return ps
_ | "CWILV" `BS8.isPrefixOf` wadEntryName -> return ps
_ | wadEntryName `elem` knownMapNames -> return ps{psState = InLevel wadEntryName}
_ -> do
printf "unrecognized lump: %s at %d\n" (BS8.unpack wadEntryName)
wadEntryOffset :: IO ()
return ps
parseStep ps@ParseState{psState = InLevel curLevel} lumpWe@(lump, WadEntry{..}) = do
case wadEntryName of
"THINGS" -> do
things <- runGet' "THINGS lump"
(getThingList (fromIntegral $ wadEntrySize `div` 10)) lump
return ps{psThings = things}
"LINEDEFS" -> do
lineDefs <- runGet' "LINEDEFS lump"
(getLineDefList (fromIntegral $ wadEntrySize `div` 14)) lump
return ps{psLineDefs = lineDefs}
"SIDEDEFS" -> do
sideDefs <- runGet' "SIDEDEF lump"
(getSideDefList (fromIntegral $ wadEntrySize `div` 30)) lump
return ps{psSideDefs = sideDefs}
"VERTEXES" -> do
vertices <- runGet' "VERTEXES lump"
(getVertexList (fromIntegral $ wadEntrySize `div` 4)) lump
return ps{psVertices = vertices}
"SEGS" -> do
segs <- runGet' "SEGS lump"
(getSegList (fromIntegral $ wadEntrySize `div` 12)) lump
return ps{psSegs = segs}
"SSECTORS" -> do
ssectors <- runGet' "SSECTORS lump"
(getSSectorList (fromIntegral $ wadEntrySize `div` 4)) lump
return ps{psSSectors = ssectors}
"NODES" -> do
nodes <- runGet' "NODES lump"
(getNodeList (fromIntegral $ wadEntrySize `div` 28)) lump
return ps{psNodes = nodes}
"SECTORS" -> do
sectors <- runGet' "SECTORS lump"
(getSectorList (fromIntegral $ wadEntrySize `div` 26)) lump
return ps{psSectors = sectors}
"REJECT" ->
return ps{psReject = Just $ Reject lump}
"BLOCKMAP" -> do
ExtBlockmap{..} <- runGet' "BLOCKMAP lump"
getBlockmap lump
blocklists <- mapM (\ offset ->
runGet' "blocklist" getBlocklist
(BS.drop ((fromIntegral offset) * 2) lump))
extBlockmapOffsets
return ps{psBlockmap =
Just $ Blockmap {
blockmapOriginX = extBlockmapOriginX,
blockmapOriginY = extBlockmapOriginY,
blockmapColumns = extBlockmapColumns,
blockmapRows = extBlockmapRows,
blockmapBlocklists = blocklists
}}
_ -> parseStep ps{psState = NoState,
psThings = [],
psLineDefs = [],
psSideDefs = [],
psVertices = [],
psSegs = [],
psSSectors = [],
psNodes = [],
psSectors = [],
psReject = Nothing,
psBlockmap = Nothing,
psLevels = Map.insert (mk curLevel)
Level {
levelName = curLevel,
levelThings = psThings ps,
levelLineDefs = psLineDefs ps,
levelSideDefs = psSideDefs ps,
levelVertices = psVertices ps,
levelSegs = psSegs ps,
levelSSectors = psSSectors ps,
levelNodes = psNodes ps,
levelSectors = psSectors ps,
levelReject = psReject ps,
levelBlockmap = psBlockmap ps
} (psLevels ps)
}
lumpWe -- Repeat step on current dir entry, with new state.
parseStep ps@ParseState{psState = InSprites} lumpWe@(_, WadEntry{..}) = do
case wadEntryName of
"S_END" -> return ps{psState = NoState}
_ -> parseSprite ps lumpWe
parseStep ps@ParseState{psState = InFlats} lumpWe@(_, WadEntry{..}) = do
case wadEntryName of
"F_END" -> return ps{psState = NoState}
"F1_START" -> return ps
"F1_END" -> return ps
"F2_START" -> return ps
"F2_END" -> return ps
"F3_START" -> return ps
"F3_END" -> return ps
_ -> parseFlat ps lumpWe
parseStep ps@ParseState{psState = InPatches} lumpWe@(_, WadEntry{..}) = do
case wadEntryName of
"P_END" -> return ps{psState = NoState}
"P1_START" -> return ps
"P1_END" -> return ps
"P2_START" -> return ps
"P2_END" -> return ps
"P3_START" -> return ps
"P3_END" -> return ps
_ -> parsePatch ps lumpWe
parseColormap ps (lump, WadEntry{..}) = do
cm <- runGet' "COLORMAP lump"
(sequence (replicate 34 $ getByteString 256)) lump
return ps{psColormap = Just $ Colormap cm}
parsePalettes ps (lump, WadEntry{..}) = do
pals <- runGet' "PLAYPAL lump"
(sequence
(replicate 14 $
(sequence
(replicate 256
((,,) <$> getWord8 <*> getWord8 <*> getWord8)))))
lump
return ps{psPalettes = Just $ Palettes pals}
parsePNames ps (lump, WadEntry{..}) = do
pnames <- runGet' "PNAMES lump" getPNames lump
forM_ (Map.toList pnames) $ \ (_, n) ->
case Map.lookup (mk n) (psLumpLookup ps) of
Just _ -> return ()
Nothing -> throwIO $ WadExceptionFormatError "PNAMES lump"
("reference to non-existant patch lump: " ++ BS8.unpack n)
return ps{psPNames = pnames}
parseTextures ps (lump, WadEntry{..}) = do
ts <- runGet' (BS8.unpack wadEntryName ++ " lump") getTextures lump
return ps{psTextures = Map.union ts (psTextures ps)}
parseSprite ps e@(_, WadEntry{..}) = do
pic <- parsePicture ps e
let sprite = Sprite{spriteName = wadEntryName,
spritePicture = pic}
return ps{psSprites = Map.insert (mk wadEntryName) sprite (psSprites ps)}
parsePatch ps e@(_, WadEntry{..}) = do
pic <- parsePicture ps e
let patch = Patch{patchName = wadEntryName,
patchPicture = pic}
return ps{psPatches = Map.insert (mk wadEntryName) patch (psPatches ps)}
parseFlat ps (lump, WadEntry{..}) = do
unless (BS.length lump == 4096) $
throwIO $ WadExceptionDecodeError "flat" $ BS8.unpack wadEntryName ++
": flat has wrong size (expected=4096, actual=" ++ show (BS.length lump) ++ ")"
let flat = Flat {flatName = wadEntryName, flatData = lump}
return ps{psFlats = Map.insert (mk wadEntryName) flat (psFlats ps)}
parsePicture _ (lump, WadEntry{..}) = do
pic@ExtPicture{..} <- runGet' ("picture " ++ BS8.unpack wadEntryName)
getExtPicture lump
posts <- mapM (parseColumn lump) extPictureColStarts
return $ convertPicture pic posts
where
parseColumn s colStart =
runGet' "picture post" getExtPost (BS.drop (fromIntegral colStart) s)
-- | This list contains all known map names from DOOM/DOOM II.
--
knownMapNames :: [ByteString]
knownMapNames = [BS8.pack (printf "E%dM%d" ep mp) | ep <- [1..4::Int], mp <- [1..9::Int]] ++
[BS8.pack (printf "MAP%02d" i) | i <- [1..32::Int]]
| mgrabmueller/waddle | Game/Waddle/Load.hs | bsd-3-clause | 21,289 | 0 | 24 | 6,659 | 5,998 | 3,108 | 2,890 | 554 | 72 |
{- Binary-experiment test -}
{-# LANGUAGE PackageImports ,FlexibleInstances ,MultiParamTypeClasses#-}
module PkgCBOR(PkgCBOR(..),C.Serialise,sd) where
import Data.Word
import Control.Exception
import Data.Monoid
import Control.Applicative
import qualified Data.Binary.Serialise.CBOR as C -- (serialise,deserialiseOrFail,Seriali)
import Data.Binary.Serialise.CBOR (Serialise(..))
import Data.Binary.Serialise.CBOR.Class
import Data.Binary.Serialise.CBOR.Encoding hiding (Tokens(..))
import Data.Binary.Serialise.CBOR.Decoding
import Data.Binary.Serialise.CBOR.Read
import Data.Binary.Serialise.CBOR.Write
import Types
import Test.Data
-- t = let Encoding e = C.encode (33::Int32) in e OutStreamEnd
data PkgCBOR a = PkgCBOR a deriving (Eq,Show)
instance Arbitrary a => Arbitrary (PkgCBOR a) where arbitrary = fmap PkgCBOR arbitrary
sd = ("cbor","cbor",serializeF,deserializeF)
serializeF = C.serialise
deserializeF = either (Left . error . show) Right . C.deserialiseOrFail
{-
instance Serialise a => Serialize (PkgCBOR a) where
serialize (PkgCBOR a) = C.serialize $ a
deserialize = either (Left . toException) (Right . PkgCBOR) . C.deserializeOrFail
-}
instance Serialise a => Serialize PkgCBOR a where
serialize (PkgCBOR a) = serializeF a
deserialize = (PkgCBOR <$>) . deserializeF
pkg = PkgCBOR
unpkg (PkgCBOR a) = a
-- instance Serialise N where
-- encode One = encodeCtr0 1
-- encode Two = encodeCtr0 2
-- encode Three = encodeCtr0 3
-- encode Four = encodeCtr0 4
-- encode Five = encodeCtr0 5
-- decode = do
-- (t,l) <- decodeCtrTag
-- case t of
-- 1 -> decodeCtrBody0 l One
-- 2 -> decodeCtrBody0 l Two
-- 3 -> decodeCtrBody0 l Three
-- 4 -> decodeCtrBody0 l Four
-- 5 -> decodeCtrBody0 l Five
-- instance Serialise a => Serialise (List a) where
-- encode (N) = encodeCtr0 1
-- encode (C v l) = encodeCtr2 2 v l
-- decode = do
-- (t,l) <- decodeCtrTag
-- case t of
-- 1 -> decodeCtrBody0 l N
-- 2 -> decodeCtrBody2 l C
-- instance Serialise a => Serialise (Tree a) where
-- encode (Leaf a) = encodeCtr1 1 a
-- encode (Node n1 n2) = encodeCtr2 2 n1 n2
-- decode = do
-- (t,l) <- decodeCtrTag
-- case t of
-- 1 -> decodeCtrBody1 l Leaf
-- 2 -> decodeCtrBody2 l Node
-- {-
-- -- correct?
-- instance Serialise () where
-- encode _ = word 0
-- decode = const () <$> expectInt
-- -}
-- encodeCtr0 :: Word -> Encoding
-- encodeCtr1 :: Serialise a => Word -> a -> Encoding
-- encodeCtr2 :: (Serialise a, Serialise b) => Word -> a -> b -> Encoding
-- encodeCtr0 n = encodeListLen 1 <> encode (n :: Word)
-- encodeCtr1 n a = encodeListLen 2 <> encode (n :: Word) <> encode a
-- encodeCtr2 n a b = encodeListLen 3 <> encode (n :: Word) <> encode a <> encode b
-- encodeCtr3 n a b c
-- = encodeListLen 4 <> encode (n :: Word) <> encode a <> encode b
-- <> encode c
-- encodeCtr4 n a b c d
-- = encodeListLen 5 <> encode (n :: Word) <> encode a <> encode b
-- <> encode c <> encode d
-- encodeCtr6 n a b c d e f
-- = encodeListLen 7 <> encode (n :: Word) <> encode a <> encode b
-- <> encode c <> encode d <> encode e <> encode f
-- encodeCtr7 n a b c d e f g
-- = encodeListLen 8 <> encode (n :: Word) <> encode a <> encode b
-- <> encode c <> encode d <> encode e <> encode f
-- <> encode g
-- {-# INLINE encodeCtr0 #-}
-- {-# INLINE encodeCtr1 #-}
-- {-# INLINE encodeCtr2 #-}
-- {-# INLINE encodeCtr3 #-}
-- {-# INLINE encodeCtr4 #-}
-- {-# INLINE encodeCtr6 #-}
-- {-# INLINE encodeCtr7 #-}
-- {-# INLINE decodeCtrTag #-}
-- {-# INLINE decodeCtrBody0 #-}
-- {-# INLINE decodeCtrBody1 #-}
-- {-# INLINE decodeCtrBody2 #-}
-- {-# INLINE decodeCtrBody3 #-}
-- decodeCtrTag = (\len tag -> (tag, len)) <$> decodeListLen <*> decodeWord
-- decodeCtrBody0 1 f = pure f
-- decodeCtrBody1 2 f = do x1 <- decode
-- return $! f x1
-- decodeCtrBody2 3 f = do x1 <- decode
-- x2 <- decode
-- return $! f x1 x2
-- decodeCtrBody3 4 f = do x1 <- decode
-- x2 <- decode
-- x3 <- decode
-- return $! f x1 x2 x3
-- {-# INLINE decodeSingleCtr0 #-}
-- {-# INLINE decodeSingleCtr1 #-}
-- {-# INLINE decodeSingleCtr2 #-}
-- {-# INLINE decodeSingleCtr3 #-}
-- {-# INLINE decodeSingleCtr4 #-}
-- {-# INLINE decodeSingleCtr6 #-}
-- {-# INLINE decodeSingleCtr7 #-}
-- decodeSingleCtr0 v f = decodeListLenOf 1 *> decodeWordOf v *> pure f
-- decodeSingleCtr1 v f = decodeListLenOf 2 *> decodeWordOf v *> pure f <*> decode
-- decodeSingleCtr2 v f = decodeListLenOf 3 *> decodeWordOf v *> pure f <*> decode <*> decode
-- decodeSingleCtr3 v f = decodeListLenOf 4 *> decodeWordOf v *> pure f <*> decode <*> decode <*> decode
-- decodeSingleCtr4 v f = decodeListLenOf 5 *> decodeWordOf v *> pure f <*> decode <*> decode <*> decode <*> decode
-- decodeSingleCtr6 v f = decodeListLenOf 7 *> decodeWordOf v *> pure f <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode
-- decodeSingleCtr7 v f = decodeListLenOf 8 *> decodeWordOf v *> pure f <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode <*> decode
instance Serialise Car
instance Serialise Acceleration
instance Serialise Consumption
instance Serialise CarModel
instance Serialise OptionalExtra
instance Serialise Engine
instance Serialise Various
instance Serialise N
instance {-# OVERLAPPABLE #-} Serialise a => Serialise (List a)
instance {-# OVERLAPPABLE #-} Serialise a => Serialise (Tree a)
instance {-# OVERLAPPING #-} Serialise (Tree N)
instance {-# OVERLAPPING #-} Serialise (Tree (N,N,N))
instance {-# OVERLAPPING #-} Serialise [N]
instance {-# OVERLAPPING #-} Serialise (N,N,N)
| tittoassini/flat | benchmarks/PkgCBOR.hs | bsd-3-clause | 5,947 | 0 | 9 | 1,456 | 554 | 354 | 200 | 39 | 1 |
module Control.Concurrent.MarkableIORef (
MarkableIORef,
newMarkableRef,
compareAndSet,
attemptMark,
readMarkableRefMark,
readMarkableRef,
isMarked,
casIORef,
) where
import Data.IORef
data MarkedRef a = MarkedRef { ref :: IORef a, mark :: Bool } deriving Eq
type MarkableIORef a = IORef (MarkedRef a)
newMarkableRef :: IORef a -> Bool -> IO (MarkableIORef a)
newMarkableRef ioref marked = do
newIORef $ MarkedRef { ref = ioref, mark = marked }
casIORef :: Eq a => IORef a -> a -> a -> IO Bool
casIORef ptr old new =
atomicModifyIORef ptr (\cur -> if cur == old
then (new, True)
else (cur, False))
attemptMark :: MarkableIORef a -> IORef a -> Bool -> IO Bool
attemptMark markableRef expectedRef newMark = atomicModifyIORef markableRef cas
where
cas markedRef @ MarkedRef { ref = curRef } =
if curRef == expectedRef
then (MarkedRef { ref = curRef, mark = newMark }, True)
else (markedRef, False)
compareAndSet :: MarkableIORef a -> IORef a -> IORef a -> Bool -> Bool -> IO Bool
compareAndSet markableRef expectedRef newRef expectedMark newMark = do
curMarkedRef <- readIORef markableRef
let MarkedRef { ref = curRef, mark = curMark } = curMarkedRef
if curRef == expectedRef && curMark == expectedMark
then casIORef markableRef curMarkedRef MarkedRef { ref = newRef, mark = newMark }
else return False
readMarkableRefMark :: MarkableIORef a -> IO (IORef a, Bool)
readMarkableRefMark markableRef = do
MarkedRef { ref = curRef, mark = curMark } <- readIORef markableRef
return (curRef, curMark)
readMarkableRef :: MarkableIORef a -> IO (IORef a)
readMarkableRef = fmap fst . readMarkableRefMark
isMarked :: MarkableIORef a -> IO Bool
isMarked = fmap snd . readMarkableRefMark
| adaszko/markable-ioref | Control/Concurrent/MarkableIORef.hs | bsd-3-clause | 1,820 | 1 | 12 | 414 | 586 | 310 | 276 | 41 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilyDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | Dependently-typed type-safe ASTs
-- See PFPL, Chapter 1
module ASTs where
import Test.Hspec
import GHC.Types
-- * Some dependent type stuff:
type family Map (f :: k -> l) (xs :: [k]) :: [l] where
Map f '[] = '[]
Map f (x ': xs) = (f x ': Map f xs)
-- | HList
data Vec (xs :: [*]) where
Nil :: Vec '[]
(:+) :: x -> Vec xs -> Vec (x ': xs)
infixr 6 :+
-- * Firstly, type-safe AST's:
data AST k (sort :: k) where
Var :: (Lang k) => Variable k sort -> AST k sort
Op :: (Lang k) => Operator k i o -> Vec (Map (AST k) i) -> AST k o
class Lang k where
type Variable k = (r :: k -> *) | r -> k
type Operator k = (r :: [k] -> k -> *) | r -> k
-- | A set of sorts
data Arith = Number
data ArithV a where
NumberV :: Int -> ArithV Number
data ArithOp i o where
Plus :: ArithOp '[Number, Number] Number
instance Lang Arith where
type Variable Arith = ArithV
type Operator Arith = ArithOp
spec :: Spec
spec = do
describe "Vec" $ do
let
_ = Nil :: Vec '[]
_ = (NumberV 1) :+ Nil :: Vec '[ArithV Number]
it "works" $ do
1 `shouldBe` 1
describe "ASTs" $ do
let
x :: AST Arith Number
x = Var (NumberV 1)
y :: AST Arith Number
y = Var (NumberV 2)
sum :: AST Arith Number
sum = Op Plus (x :+ y :+ Nil)
it "works" $ do
1 `shouldBe` 1
| sleexyz/haskell-fun | ASTs.hs | bsd-3-clause | 1,663 | 1 | 16 | 445 | 589 | 327 | 262 | -1 | -1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DeriveGeneric #-}
module Language.Granule.Checker.Predicates where
{-
This module provides the representation of theorems (predicates)
inside the type checker.
-}
import Control.Monad.Fail
import Control.Monad.Trans.State.Strict
import Data.List (intercalate, (\\))
import GHC.Generics (Generic)
import Language.Granule.Context
import Language.Granule.Syntax.Helpers
import Language.Granule.Syntax.Identifiers
import Language.Granule.Syntax.FirstParameter
import Language.Granule.Syntax.Pretty
import Language.Granule.Syntax.Span
import Language.Granule.Syntax.Type
data Quantifier =
-- | Universally quantification, e.g. polymorphic
ForallQ
-- | Instantiations of universally quantified variables
| InstanceQ
-- | Univeral, but bound in a dependent pattern match
| BoundQ
deriving (Show, Eq)
instance Pretty Quantifier where
pretty ForallQ = "∀"
pretty InstanceQ = "∃"
pretty BoundQ = "pi"
stripQuantifiers :: Ctxt (a, Quantifier) -> Ctxt a
stripQuantifiers = map (\(var, (k, _)) -> (var, k))
-- Represent constraints generated by the type checking algorithm
data Constraint =
-- Coeffect resource algebra constraints
Eq Span Coeffect Coeffect Type
| Neq Span Coeffect Coeffect Type
| ApproximatedBy Span Coeffect Coeffect Type
--
| Lub Span Coeffect Coeffect Coeffect Type
-- NonZeroPromotableTo s x c means that:
-- exists x . (x != 0) and x * 1 = c
-- This is used to check constraints related to definite unification
-- which incurrs a consumption effect
| NonZeroPromotableTo Span Id Coeffect Type
-- Used for user-predicates, and also effect types
| Lt Span Coeffect Coeffect -- Must be Nat kinded
| Gt Span Coeffect Coeffect -- Must be Nat kinded
| LtEq Span Coeffect Coeffect -- Must be Nat kinded
| GtEq Span Coeffect Coeffect -- Must be Nat kinded
deriving (Show, Eq, Generic)
instance FirstParameter Constraint Span
normaliseConstraint :: Constraint -> Constraint
normaliseConstraint (Eq s c1 c2 t) = Eq s (normalise c1) (normalise c2) t
normaliseConstraint (Neq s c1 c2 t) = Neq s (normalise c1) (normalise c2) t
normaliseConstraint (Lub s c1 c2 c3 t) = Lub s (normalise c1) (normalise c2) (normalise c3) t
normaliseConstraint (ApproximatedBy s c1 c2 t) = ApproximatedBy s (normalise c1) (normalise c2) t
normaliseConstraint (NonZeroPromotableTo s x c t) = NonZeroPromotableTo s x (normalise c) t
normaliseConstraint (Lt s c1 c2) = Lt s (normalise c1) (normalise c2)
normaliseConstraint (Gt s c1 c2) = Gt s (normalise c1) (normalise c2)
normaliseConstraint (LtEq s c1 c2) = LtEq s (normalise c1) (normalise c2)
normaliseConstraint (GtEq s c1 c2) = GtEq s (normalise c1) (normalise c2)
instance Monad m => Freshenable m Constraint where
freshen (Eq s' c1 c2 k) = do
c1 <- freshen c1
c2 <- freshen c2
return $ Eq s' c1 c2 k
freshen (Neq s' c1 c2 k) = do
c1 <- freshen c1
c2 <- freshen c2
return $ Neq s' c1 c2 k
freshen (ApproximatedBy s' c1 c2 t) = do
c1 <- freshen c1
c2 <- freshen c2
return $ ApproximatedBy s' c1 c2 t
freshen (Lub s' c1 c2 c3 t) = do
c1 <- freshen c1
c2 <- freshen c2
c3 <- freshen c3
return $ Lub s' c1 c2 c3 t
freshen (NonZeroPromotableTo s i c t) = do
c <- freshen c
t <- freshen t
return $ NonZeroPromotableTo s i c t
freshen (Lt s c1 c2) = do
c1 <- freshen c1
c2 <- freshen c2
return $ Lt s c1 c2
freshen (Gt s c1 c2) = do
c1 <- freshen c1
c2 <- freshen c2
return $ Gt s c1 c2
freshen (LtEq s c1 c2) = LtEq s <$> freshen c1 <*> freshen c2
freshen (GtEq s c1 c2) = GtEq s <$> freshen c1 <*> freshen c2
-- Used to negate constraints
newtype Neg a = Neg a
deriving (Eq, Show)
instance Pretty (Neg Constraint) where
pretty (Neg (Neq _ c1 c2 _)) =
"Trying to prove that " <> pretty c1 <> " == " <> pretty c2
pretty (Neg (Eq _ c1 c2 _)) =
"Actual grade `" <> pretty c1 <>
"` is not equal to specified grade `" <> pretty c2 <> "`"
pretty (Neg (ApproximatedBy _ c1 c2 (TyCon k))) | internalName k == "Level" =
pretty c2 <> " value cannot be moved to level " <> pretty c1
pretty (Neg (ApproximatedBy _ c1 c2 k)) =
pretty c1 <> " is not approximatable by " <> pretty c2 <> " for type " <> pretty k
<> if k == (TyCon $ mkId "Nat") then " because Nat denotes precise usage." else ""
pretty (Neg p@Lub{}) =
"Trying to prove negation of statement: " ++ pretty p
pretty (Neg (NonZeroPromotableTo _ _ c _)) = "TODO"
pretty (Neg (Lt _ c1 c2)) =
"Trying to prove false statement: (" <> pretty c1 <> " < " <> pretty c2 <> ")"
pretty (Neg (Gt _ c1 c2)) =
"Trying to prove false statement: (" <> pretty c1 <> " > " <> pretty c2 <> ")"
pretty (Neg (LtEq _ c1 c2)) =
"Trying to prove false statement: (" <> pretty c1 <> " ≤ " <> pretty c2 <> ")"
pretty (Neg (GtEq _ c1 c2)) =
"Trying to prove false statement: (" <> pretty c1 <> " ≥ " <> pretty c2 <> ")"
instance Pretty [Constraint] where
pretty constr =
"---\n" <> (intercalate "\n" . map pretty $ constr)
instance Pretty Constraint where
pretty (Eq _ c1 c2 _) =
"(" <> pretty c1 <> " = " <> pretty c2 <> ")" -- @" <> show s
pretty (Neq _ c1 c2 _) =
"(" <> pretty c1 <> " ≠ " <> pretty c2 <> ")" -- @" <> show s
pretty (ApproximatedBy _ c1 c2 k) =
case k of
-- Nat is discrete
TyCon (internalName -> "Nat") -> "(" <> pretty c1 <> " = " <> pretty c2 <> ")"
_ -> "(" <> pretty c1 <> " ≤ " <> pretty c2 <> ")" -- @" <> show s
pretty (Lub _ c1 c2 c3 _) =
"(" <> pretty c1 <> " ⊔ " <> pretty c2 <> " = " <> pretty c3 <> ")"
pretty (Lt _ c1 c2) =
"(" <> pretty c1 <> " < " <> pretty c2 <> ")"
pretty (Gt _ c1 c2) =
"(" <> pretty c1 <> " > " <> pretty c2 <> ")"
pretty (LtEq _ c1 c2) =
"(" <> pretty c1 <> " ≤ " <> pretty c2 <> ")"
pretty (GtEq _ c1 c2) =
"(" <> pretty c1 <> " ≥ " <> pretty c2 <> ")"
pretty (NonZeroPromotableTo _ _ c _) = "TODO"
varsConstraint :: Constraint -> [Id]
varsConstraint (Eq _ c1 c2 _) = freeVars c1 <> freeVars c2
varsConstraint (Neq _ c1 c2 _) = freeVars c1 <> freeVars c2
varsConstraint (Lub _ c1 c2 c3 _) = freeVars c1 <> freeVars c2 <> freeVars c3
varsConstraint (ApproximatedBy _ c1 c2 _) = freeVars c1 <> freeVars c2
varsConstraint (NonZeroPromotableTo _ _ c _) = freeVars c
varsConstraint (Lt _ c1 c2) = freeVars c1 <> freeVars c2
varsConstraint (Gt _ c1 c2) = freeVars c1 <> freeVars c2
varsConstraint (LtEq _ c1 c2) = freeVars c1 <> freeVars c2
varsConstraint (GtEq _ c1 c2) = freeVars c1 <> freeVars c2
-- Represents a predicate generated by the type checking algorithm
data Pred where
Conj :: [Pred] -> Pred
Disj :: [Pred] -> Pred
Impl :: Ctxt Kind -> Pred -> Pred -> Pred
Con :: Constraint -> Pred
NegPred :: Pred -> Pred
Exists :: Id -> Kind -> Pred -> Pred
instance Term Pred where
freeVars (Conj ps) = concatMap freeVars ps
freeVars (Disj ps) = concatMap freeVars ps
freeVars (Impl bounds p1 p2) = (freeVars p1 <> freeVars p2) \\ map fst bounds
freeVars (Con c) = varsConstraint c
freeVars (NegPred p) = freeVars p
freeVars (Exists x _ p) = freeVars p \\ [x]
boundVars :: Pred -> [Id]
boundVars (Conj ps) = concatMap boundVars ps
boundVars (Disj ps) = concatMap boundVars ps
boundVars (Impl bounds p1 p2) = map fst bounds ++ (boundVars p1 ++ boundVars p2)
boundVars (NegPred p) = boundVars p
boundVars (Exists x _ p) = x : boundVars p
boundVars (Con _) = []
instance (Monad m, MonadFail m) => Freshenable m Pred where
freshen (Conj ps) = do
ps' <- mapM freshen ps
return $ Conj ps'
freshen (Disj ps) = do
ps' <- mapM freshen ps
return $ Disj ps'
freshen (NegPred p) = do
p' <- freshen p
return $ NegPred p'
freshen (Exists v k p) = do
st <- get
-- Create a new binding name for v
let v' = internalName v <> "-e" <> show (counter st)
-- Updated freshener state
put (st { tyMap = (internalName v, v') : tyMap st
, counter = counter st + 1 })
-- Freshen the rest of the predicate
p' <- freshen p
-- Freshening now out of scope
removeFreshenings [Id (internalName v) v']
return $ Exists (Id (internalName v) v') k p'
freshen (Impl [] p1 p2) = do
p1' <- freshen p1
p2' <- freshen p2
return $ Impl [] p1' p2'
freshen (Impl ((v, kind):vs) p p') = do
st <- get
-- Freshen the variable bound here
let v' = internalName v <> "-" <> show (counter st)
put (st { tyMap = (internalName v, v') : tyMap st
, counter = counter st + 1 })
-- Freshen the rest
(Impl vs' pf pf') <- freshen (Impl vs p p')
-- Freshening now out of scope
removeFreshenings [Id (internalName v) v']
return $ Impl ((Id (internalName v) v', kind):vs') pf pf'
freshen (Con cons) = do
cons' <- freshen cons
return $ Con cons'
deriving instance Show Pred
deriving instance Eq Pred
-- Fold operation on a predicate
predFold ::
([a] -> a)
-> ([a] -> a)
-> (Ctxt Kind -> a -> a -> a)
-> (Constraint -> a)
-> (a -> a)
-> (Id -> Kind -> a -> a)
-> Pred
-> a
predFold c d i a n e (Conj ps) = c (map (predFold c d i a n e) ps)
predFold c d i a n e (Disj ps) = d (map (predFold c d i a n e) ps)
predFold c d i a n e (Impl ctxt p p') = i ctxt (predFold c d i a n e p) (predFold c d i a n e p')
predFold _ _ _ a _ _ (Con cons) = a cons
predFold c d i a n e (NegPred p) = n (predFold c d i a n e p)
predFold c d i a n e (Exists x t p) = e x t (predFold c d i a n e p)
-- Fold operation on a predicate (monadic)
predFoldM :: Monad m =>
([a] -> m a)
-> ([a] -> m a)
-> (Ctxt Kind -> a -> a -> m a)
-> (Constraint -> m a)
-> (a -> m a)
-> (Id -> Kind -> a -> m a)
-> Pred
-> m a
predFoldM c d i a n e (Conj ps) = do
ps <- mapM (predFoldM c d i a n e) ps
c ps
predFoldM c d i a n e (Disj ps) = do
ps <- mapM (predFoldM c d i a n e) ps
d ps
predFoldM c d i a n e (Impl localVars p p') = do
p <- predFoldM c d i a n e p
p' <- predFoldM c d i a n e p'
i localVars p p'
predFoldM _ _ _ a _ _ (Con cons) =
a cons
predFoldM c d i a n e (NegPred p) =
predFoldM c d i a n e p >>= n
predFoldM c d i a n e (Exists x t p) =
predFoldM c d i a n e p >>= e x t
instance Pretty [Pred] where
pretty ps =
"Size = " <> show (length ps) <> "\n" <>
(intercalate "\n" (map (\p -> " - " <> pretty p) ps))
instance Pretty Pred where
pretty =
predFold
(intercalate " ∧ ")
(intercalate " ∨ ")
(\ctxt p q ->
(if null ctxt then "" else "∀ " <> pretty' ctxt <> " . ")
<> "(" <> p <> " -> " <> q <> ")")
pretty
(\p -> "¬(" <> p <> ")")
(\x t p -> "∃ " <> pretty x <> " : " <> pretty t <> " . " <> p)
where pretty' =
intercalate "," . map (\(id, k) -> pretty id <> " : " <> pretty k)
-- | Whether the predicate is empty, i.e. contains no constraints
isTrivial :: Pred -> Bool
isTrivial = predFold and or (\_ lhs rhs -> rhs) (const False) id (\_ _ p -> p)
-- TODO: replace with use of `substitute`
-- given an context mapping coeffect type variables to coeffect typ,
-- then rewrite a set of constraints so that any occruences of the kind variable
-- are replaced with the coeffect type
rewriteBindersInPredicate :: Ctxt (Type, Quantifier) -> Pred -> Pred
rewriteBindersInPredicate ctxt =
predFold
Conj
Disj
Impl
(\c -> Con $ foldr (uncurry updateConstraint) c ctxt)
NegPred
existsCase
where
existsCase :: Id -> Kind -> Pred -> Pred
existsCase var (KVar kvar) p =
Exists var k' p
where
k' = case lookup kvar ctxt of
Just (ty, _) -> KPromote ty
Nothing -> KVar kvar
existsCase var k p = Exists var k p
-- `updateConstraint v k c` rewrites any occurence of the kind variable
-- `v` in the constraint `c` with the kind `k`
updateConstraint :: Id -> (Type, Quantifier) -> Constraint -> Constraint
updateConstraint ckindVar (ckind, _) (Eq s c1 c2 k) =
Eq s (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2)
(case k of
TyVar ckindVar' | ckindVar == ckindVar' -> ckind
_ -> k)
updateConstraint ckindVar (ckind, _) (Neq s c1 c2 k) =
Neq s (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2)
(case k of
TyVar ckindVar' | ckindVar == ckindVar' -> ckind
_ -> k)
updateConstraint ckindVar (ckind, _) (ApproximatedBy s c1 c2 k) =
ApproximatedBy s (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2)
(case k of
TyVar ckindVar' | ckindVar == ckindVar' -> ckind
_ -> k)
updateConstraint ckindVar (ckind, _) (Lub s c1 c2 c3 k) =
Lub s (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2) (updateCoeffect ckindVar ckind c3)
(case k of
TyVar ckindVar' | ckindVar == ckindVar' -> ckind
_ -> k)
updateConstraint ckindVar (ckind, _) (NonZeroPromotableTo s x c t) =
NonZeroPromotableTo s x (updateCoeffect ckindVar ckind c)
(case t of
TyVar ckindVar' | ckindVar == ckindVar' -> ckind
_ -> t)
updateConstraint ckindVar (ckind, _) (Lt s c1 c2) =
Lt s (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2)
updateConstraint ckindVar (ckind, _) (Gt s c1 c2) =
Gt s (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2)
updateConstraint ckindVar (ckind, _) (GtEq s c1 c2) =
GtEq s (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2)
updateConstraint ckindVar (ckind, _) (LtEq s c1 c2) =
LtEq s (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2)
-- `updateCoeffect v k c` rewrites any occurence of the kind variable
-- `v` in the coeffect `c` with the kind `k`
updateCoeffect :: Id -> Type -> Coeffect -> Coeffect
updateCoeffect ckindVar ckind (CZero (TyVar ckindVar'))
| ckindVar == ckindVar' = CZero ckind
updateCoeffect ckindVar ckind (COne (TyVar ckindVar'))
| ckindVar == ckindVar' = COne ckind
updateCoeffect ckindVar ckind (CMeet c1 c2) =
CMeet (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2)
updateCoeffect ckindVar ckind (CJoin c1 c2) =
CJoin (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2)
updateCoeffect ckindVar ckind (CPlus c1 c2) =
CPlus (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2)
updateCoeffect ckindVar ckind (CTimes c1 c2) =
CTimes (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2)
updateCoeffect ckindVar ckind (CMinus c1 c2) =
CMinus (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2)
updateCoeffect ckindVar ckind (CExpon c1 c2) =
CExpon (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2)
updateCoeffect ckindVar ckind (CInterval c1 c2) =
CInterval (updateCoeffect ckindVar ckind c1) (updateCoeffect ckindVar ckind c2)
updateCoeffect _ _ c = c
| dorchard/gram_lang | frontend/src/Language/Granule/Checker/Predicates.hs | bsd-3-clause | 15,445 | 0 | 18 | 4,070 | 5,917 | 2,933 | 2,984 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
-- | A bunch of type classes representing common values shared between multiple
-- CSS properties, like `Auto`, `Inherit`, `None`, `Normal` and several more.
--
-- All the common value type classes have an instance for the Value type,
-- making them easily derivable for custom value types.
module Clay.Common where
import Clay.Property
import Data.String (IsString)
import Data.Monoid (Monoid, (<>))
-------------------------------------------------------------------------------
class All a where all :: a
class Auto a where auto :: a
class Baseline a where baseline :: a
class Center a where center :: a
class Inherit a where inherit :: a
class None a where none :: a
class Normal a where normal :: a
class Visible a where visible :: a
class Hidden a where hidden :: a
class Initial a where initial :: a
class Unset a where unset :: a
-- | The other type class is used to escape from the type safety introduced by
-- embedding CSS properties into the typed world of Clay. `Other` allows you to
-- cast any `Value` to a specific value type.
class Other a where other :: Value -> a
instance All Value where all = "all"
instance Auto Value where auto = "auto"
instance Baseline Value where baseline = "baseline"
instance Center Value where center = "center"
instance Inherit Value where inherit = "inherit"
instance Normal Value where normal = "normal"
instance None Value where none = "none"
instance Visible Value where visible = "visible"
instance Hidden Value where hidden = "hidden"
instance Other Value where other = id
instance Initial Value where initial = "initial"
instance Unset Value where unset = "unset"
-------------------------------------------------------------------------------
-- | Common list browser prefixes to make experimental properties work in
-- different browsers.
browsers :: Prefixed
browsers = Prefixed
[ ( "-webkit-", "" )
, ( "-moz-", "" )
, ( "-ms-", "" )
, ( "-o-", "" )
, ( "", "" )
]
-------------------------------------------------------------------------------
-- | Syntax for CSS function call.
call :: (IsString s, Monoid s) => s -> s -> s
call fn arg = fn <> "(" <> arg <> ")"
-------------------------------------------------------------------------------
-- | Some auxiliary mathematical functions.
fracMod :: RealFrac a => a -> a -> a
fracMod x y = (x -) . (* y) $ evenMultiples x y
where evenMultiples x y = fromIntegral . truncate $ x / y
decimalRound :: RealFrac a => a -> Int -> a
decimalRound x decimalPlaces = shiftedAndRounded x / powersOf10
where powersOf10 = 10 ^ decimalPlaces
shiftedAndRounded x = fromIntegral . round $ x * powersOf10
| psfblair/clay | src/Clay/Common.hs | bsd-3-clause | 2,809 | 0 | 9 | 608 | 632 | 346 | 286 | 45 | 1 |
{-
SockeyeASTParser.hs: AST for the Sockeye parser
Part of Sockeye
Copyright (c) 2017, 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, CAB F.78, Universitaetstrasse 6, CH-8092 Zurich,
Attn: Systems Group.
-}
module SockeyeASTParser
( module SockeyeASTParser
, module SockeyeASTTypeChecker
) where
import SockeyeASTTypeChecker
( Identifier(SimpleIdent, TemplateIdent)
, prefix, varName, suffix
, ModuleParamType(NaturalParam, AddressParam)
, ModuleArg(NumericalArg, ParamArg)
, NodeSpec(NodeSpec)
, nodeType, accept, translate, reserved, overlay
, NodeType(Core, Device, Memory, Other)
, BlockSpec(SingletonBlock, RangeBlock, LengthBlock)
, PropSpec(PropSpec)
, base, limit, bits
, MapSpec(MapSpec)
, OverlaySpec(OverlaySpec)
, over, width
, block, destNode, destBase, destProps
, Address(LiteralAddress, ParamAddress)
, ForLimit(LiteralLimit, ParamLimit)
)
data SockeyeSpec = SockeyeSpec
{ imports :: [Import]
, modules :: [Module]
, net :: [NetSpec]
} deriving (Show)
data Import = Import
{ filePath :: !FilePath }
deriving (Show)
data Module = Module
{ name :: String
, parameters :: [ModuleParam]
, moduleBody :: ModuleBody
} deriving (Show)
data ModuleParam = ModuleParam
{ paramName :: !String
, paramType :: ModuleParamType
} deriving (Show)
data ModuleBody = ModuleBody
{ ports :: [Port]
, moduleNet :: [NetSpec]
} deriving (Show)
data NetSpec
= ModuleInstSpec ModuleInst
| NodeDeclSpec NodeDecl
deriving (Show)
data Port
= InputPort
{ portId :: Identifier
, portWidth :: !Integer
}
| OutputPort
{ portId :: Identifier
, portWidth :: !Integer
}
| MultiPort (For Port)
deriving (Show)
data ModuleInst
= ModuleInst
{ moduleName :: String
, namespace :: Identifier
, arguments :: [ModuleArg]
, portMappings :: [PortMap]
}
| MultiModuleInst (For ModuleInst)
deriving (Show)
data PortMap
= InputPortMap
{ mappedId :: Identifier
, mappedPort :: Identifier
}
| OutputPortMap
{ mappedId :: Identifier
, mappedPort :: Identifier
}
| MultiPortMap (For PortMap)
deriving (Show)
data NodeDecl
= NodeDecl
{ nodeId :: Identifier
, nodeSpec :: NodeSpec
}
| MultiNodeDecl (For NodeDecl)
deriving (Show)
data For a
= For
{ varRanges :: [ForVarRange]
, body :: a
} deriving (Show)
data ForVarRange
= ForVarRange
{ var :: !String
, start :: ForLimit
, end :: ForLimit
} deriving (Show)
| kishoredbn/barrelfish | tools/sockeye/v1/SockeyeASTParser.hs | mit | 2,915 | 0 | 9 | 855 | 632 | 403 | 229 | 98 | 0 |
module Feature.NoJwtSpec where
-- {{{ Imports
import Test.Hspec
import Test.Hspec.Wai
import Network.HTTP.Types
import SpecHelper
import Network.Wai (Application)
import Protolude hiding (get)
-- }}}
spec :: SpecWith Application
spec = describe "server started without JWT secret" $ do
-- this test will stop working 9999999999s after the UNIX EPOCH
it "responds with error on attempted auth" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjk5OTk5OTk5OTksInJvbGUiOiJwb3N0Z3Jlc3RfdGVzdF9hdXRob3IiLCJpZCI6Impkb2UifQ.QaPPLWTuyydMu_q7H4noMT7Lk6P4muet1OpJXF6ofhc"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` 500
it "behaves normally when user does not attempt auth" $
request methodGet "/items" [] ""
`shouldRespondWith` 200
| Skyfold/postgrest | test/Feature/NoJwtSpec.hs | mit | 806 | 0 | 14 | 122 | 138 | 75 | 63 | 16 | 1 |
f x | x > 10 = 10
| x < 0 = 0
| otherwise = x
g x = 10
| itchyny/vim-haskell-indent | test/guard/guard.out.hs | mit | 63 | 0 | 8 | 30 | 49 | 22 | 27 | 4 | 1 |
module Utils (
forkIO_,
getLocalTime,
toZonedTime,
fromZonedTime,
diffTime,
runSql,
showTime
) where
import Control.Concurrent (forkIO)
import Control.Monad.Logger (runStderrLoggingT, LoggingT)
import Control.Monad.Reader
import Control.Monad.Trans.Resource (runResourceT, ResourceT)
import Data.Time
import Database.Persist.Sql (SqlPersistT, runSqlPool)
import System.Locale (defaultTimeLocale)
import Types
toZonedTime :: String -> IO ZonedTime
toZonedTime s = do
timezone <- getCurrentTimeZone
return $ readTime defaultTimeLocale "%Y%m%d%H%M%S %Z"
(s ++ " " ++ show timezone)
fromZonedTime :: ZonedTime -> String
fromZonedTime = formatTime defaultTimeLocale "%Y%m%d%H%M%S"
showTime :: ZonedTime -> String
showTime = formatTime defaultTimeLocale "%Y-%m-%d %H:%M:%S"
diffTime :: ZonedTime -> ZonedTime -> Int
diffTime a b = ceiling $ diffUTCTime (zonedTimeToUTC a) (zonedTimeToUTC b) / 60
getLocalTime :: IO String
getLocalTime = liftM showTime getZonedTime
type SqlPersistM = SqlPersistT (LoggingT (ResourceT IO))
runSql :: SqlPersistM a -> DatabaseT a
runSql action = do
(pool, _) <- ask
liftIO $ runResourceT $ runStderrLoggingT $ runSqlPool action pool
forkIO_ :: IO () -> IO ()
forkIO_ a = void $ forkIO a
| asi1024/WXCS | src/Utils.hs | mit | 1,252 | 0 | 11 | 197 | 374 | 200 | 174 | 36 | 1 |
import Data.Set (Set)
import qualified Data.Set as S
-- | Given a positive integer n < 1000 and an adjacency list corresponding to
-- a graph on nn nodes that contains no cycles.
-- Return the minimum number of edges that can be added to the graph to
-- produce a tree.
-- >>> 10
-- >>> 1 2
-- >>> 2 8
-- >>> 4 10
-- >>> 5 9
-- >>> 6 10
-- >>> 7 9
--
-- > 3
type Edge = (Int, Int)
type Bags = (Maybe (Set Int), Maybe (Set Int))
-- | traverses through (x:xs) and checks for Edge (e1,e2).
-- Possible outcomes:
-- A. List is empty
-- B. e1 and e2 membership has been identified
-- If A and B, process accumulated data and produce final result
-- C. Either e1 or e2 membership is unknown
-- 1. Both e1, e2 are on the same set
-- If input data is valid, this should NEVER be the case
-- else return as is because all sets are up-to-date
-- 2. e1 is a member of x. Move x into a bag for further observation
-- 3. e2 is a member of x. Move x into a bag for further observation
-- 4. Neither is found. Recurse
tree :: [Set Int] -> Bags -> [Set Int] -> Edge -> [Set Int]
tree done b [] e = addBag done b e
tree done b@(Just s, Just t) xs e = addBag (xs ++ done) b e
tree done b@(b1,b2) (x:xs) e@(e1,e2) =
let i1 = S.lookupIndex e1 x
i2 = S.lookupIndex e2 x
in case (i1,i2) of
(Just s, Just t) -> (x:xs) ++ done
(Just s, _) -> tree done (Just x, b2) xs e
(_, Just s) -> tree done (b1, Just x) xs e
_ -> tree (x:done) b xs e
-- | processes accumulated information to produce a new [Set Int]
addBag :: [Set Int] -> Bags -> Edge -> [Set Int]
addBag done (b1,b2) (e1,e2) = case (b1,b2) of
(Just s, Just t) -> (S.union s t) : done -- merge the 2 sets
(Just s, _) -> (S.insert e2 s) : done -- add e2 to the set
(_, Just s) -> (S.insert e1 s) : done -- add e1 to the set
_ -> (S.insert e1 (S.singleton e2)) : done -- create a new set
-- | constructs an Edge from a String
mkEdge :: String -> Edge
mkEdge s =
let (x:y:zs) = map (\x -> read x :: Int) $ words s
in (x,y)
main :: IO ()
main = do
inp <- getContents
let (x:xs) = lines inp
numNodes = read x :: Int
edges = mkEdge <$> xs
trees = foldl (tree [] (Nothing, Nothing)) [] edges
inTrees = foldl S.union S.empty trees -- set of all numbers in the trees
all = S.fromList [1..numNodes] -- all numbers 1 to numNodes
missing = all S.\\ inTrees -- calculate missing
minEdges = (length trees) - 1 + (S.size missing)
putStrLn "trees:"
mapM_ putStrLn $ map show trees
putStrLn "missing:"
putStrLn $ show missing
putStrLn "min edges:"
print minEdges
-- | Follow up note: nice solution from @1HaskellADay
-- http://lpaste.net/1052721051462533120 where
--
-- minEdgesToTreeGraph s = (read.head.lines) s - (length.lines) s
| mitochon/hoosalind | src/problems/tree.hs | mit | 2,962 | 0 | 13 | 862 | 861 | 462 | 399 | 42 | 4 |
{-# LANGUAGE RecordWildCards #-}
module Buildsome.Print
( targetWrap, targetTiming
, warn
, posText, posMessage
, replayCmd, executionCmd, targetStdOutputs
, buildsomeCreation
, delimitMultiline
, outputsStr
, replay
, hookTrace
) where
import qualified Buildsome.Color as Color
import Buildsome.Db (Reason)
import Buildsome.Opts (Verbosity(..), PrintOutputs(..), PrintCommands(..))
import Control.Monad
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS8
import Data.Monoid
import Data.String (IsString(..))
import Lib.ByteString (chopTrailingNewline)
import Lib.ColorText (ColorText)
import qualified Lib.ColorText as ColorText
import Lib.Exception (onExceptionWith)
import Lib.FSHook (Severity(..))
import Lib.Makefile (TargetType(..), Target, targetInterpolatedCmds)
import Lib.Parsec (showPos)
import Lib.Printer (Printer, printStrLn)
import qualified Lib.Printer as Printer
import Lib.Show (show)
import Lib.StdOutputs (StdOutputs(..))
import qualified Lib.StdOutputs as StdOutputs
import Text.Parsec (SourcePos)
import Prelude.Compat hiding (show)
fromBytestring8 :: IsString str => ByteString -> str
fromBytestring8 = fromString . BS8.unpack
posText :: (Monoid s, IsString s) => SourcePos -> s
posText pos = mconcat [fromString (showPos pos), ": "]
posMessage :: Printer -> SourcePos -> ColorText -> IO ()
posMessage printer pos msg = Printer.rawPrintStrLn printer $ posText pos <> msg
warn :: Printer -> SourcePos -> ColorText -> IO ()
warn printer pos str =
posMessage printer pos $ cWarning $ "WARNING: " <> str
where
Color.Scheme{..} = Color.scheme
targetWrap ::
Printer -> Reason -> Target -> ColorText -> IO a -> IO a
targetWrap printer reason target str =
Printer.printWrap cPrinter printer
(cTarget (show (targetOutputs target))) $
mconcat [str, " (", show reason, ")"]
where
Color.Scheme{..} = Color.scheme
targetTiming :: Show a => Printer -> ColorText -> a -> IO ()
targetTiming printer str selfTime =
printStrLn printer $
"Build (" <> str <> ") took " <> cTiming (show selfTime <> " seconds")
where
Color.Scheme{..} = Color.scheme
colorStdOutputs :: StdOutputs ByteString -> StdOutputs ColorText
colorStdOutputs (StdOutputs out err) =
StdOutputs
(colorize cStdout out)
(colorize cStderr err)
where
colorize f = f . fromBytestring8 . chopTrailingNewline
Color.Scheme{..} = Color.scheme
outputsStr :: StdOutputs ByteString -> Maybe ColorText
outputsStr = StdOutputs.str . colorStdOutputs
targetStdOutputs :: Printer -> Target -> StdOutputs ByteString -> IO ()
targetStdOutputs printer _target stdOutputs =
maybe (pure ()) (Printer.rawPrintStrLn printer) $ outputsStr stdOutputs
cmd :: Printer -> Target -> IO ()
cmd printer target =
unless (BS8.null cmds) $ printStrLn printer $ cCommand $ fromBytestring8 $
delimitMultiline cmds
where
cmds = targetInterpolatedCmds target
Color.Scheme{..} = Color.scheme
replayCmd :: PrintCommands -> Printer -> Target -> IO ()
replayCmd PrintCommandsForAll printer target = cmd printer target
replayCmd PrintCommandsForExecution _ _ = pure ()
replayCmd PrintCommandsNever _ _ = pure ()
executionCmd :: PrintCommands -> Printer -> Target -> IO ()
executionCmd PrintCommandsForAll printer target = cmd printer target
executionCmd PrintCommandsForExecution printer target = cmd printer target
executionCmd PrintCommandsNever _ _ = pure ()
delimitMultiline :: ByteString -> ByteString
delimitMultiline xs
| '\n' `BS8.notElem` x = x
| otherwise = multilineDelimiter <> x <> multilineDelimiter
where
x = chopTrailingNewline xs
multilineDelimiter = "\"\"\""
replay :: Show a => Printer -> Target -> StdOutputs ByteString -> Reason -> Verbosity -> a -> IO () -> IO ()
replay printer target stdOutputs reason verbosity selfTime action = do
action `onExceptionWith` \e -> do
printStrLn printer header
cmd printer target
targetStdOutputs printer target stdOutputs
printStrLn printer $ cError $ "EXCEPTION: " <> show e
when shouldPrint $ do
printStrLn printer $ mconcat
[ header, " (originally) took ", cTiming (show selfTime <> " seconds")
, outputsHeader
]
replayCmd (verbosityCommands verbosity) printer target
targetStdOutputs printer target stdOutputs
where
header = "REPLAY for target " <> cTarget (show (targetOutputs target)) <> " (" <> show reason <> ")"
shouldPrint =
case verbosityOutputs verbosity of
PrintOutputsAnyway -> True
PrintOutputsNonEmpty -> not (StdOutputs.null stdOutputs)
PrintOutputsIfStderr -> not (BS8.null (StdOutputs.stdErr stdOutputs))
outputsHeader =
case (BS8.null (StdOutputs.stdOut stdOutputs),
BS8.null (StdOutputs.stdErr stdOutputs)) of
(False, False) -> ", STDOUT/STDERR follow"
(False, True) -> ", STDOUT follows"
(True, False) -> ", STDERR follows"
(True, True) -> ""
Color.Scheme{..} = Color.scheme
buildsomeCreation :: Show a => Printer -> ByteString -> [a] -> [a] -> Verbosity -> IO ()
buildsomeCreation printer version withs withouts verbosity
| verbosityGeneral verbosity =
printStrLn printer $ mconcat
[ header
, " --with ", show withs
, " --without ", show withouts
]
| null (withs ++ withouts) = pure ()
| otherwise =
printStrLn printer $ mconcat
[ header
, if null withs then "" else " --with " <> show withs
, if null withouts then "" else " --without " <> show withouts
]
where
header =
"Buildsome " <> cTiming (ColorText.simple version) <> " invoked"
Color.Scheme{..} = Color.scheme
hookTrace :: Printer -> Severity -> ByteString -> IO ()
hookTrace printer severity =
printStrLn printer . color . fromBytestring8
where
color =
case severity of
SeverityDebug -> cDebug
SeverityWarning -> cWarning
SeverityError -> cError
Color.Scheme{..} = Color.scheme
| buildsome/buildsome | src/Buildsome/Print.hs | gpl-2.0 | 6,105 | 0 | 16 | 1,305 | 1,896 | 978 | 918 | 139 | 6 |
-- |
-- Module : Foreign.Erlang.OTP
-- Copyright : (c) Eric Sessoms, 2008
-- (c) Artúr Poór, 2015
-- License : GPL3
--
-- Maintainer : gombocarti@gmail.com
-- Stability : experimental
-- Portability : portable
--
module Foreign.Erlang.OTP.Mnesia (
-- * Mnesia database methods
backup
, dirtyAllKeys
, dirtyFirst
, dirtyNext
, dirtyLast
, dirtyPrev
, dirtyMatchObject
, dirtyRead
, dirtySelect
) where
import Foreign.Erlang.OTP.GenServer (rpcCall)
import Foreign.Erlang.Processes (MBox)
import Foreign.Erlang.Types (ErlType(..))
import Foreign.Erlang.Network (Node)
mnesia :: MBox -> Node -> String -> [ErlType] -> IO ErlType
mnesia mbox node f as = rpcCall mbox node "mnesia" f as
backup :: MBox -> Node -> String -> IO ErlType
backup mbox node path = mnesia mbox node "backup" [ErlString path]
dirtyAllKeys :: MBox -> Node -> String -> IO ErlType
dirtyAllKeys mbox node tab = mnesia mbox node "dirty_all_keys" [ErlAtom tab]
dirtyFirst :: MBox -> Node -> String -> IO ErlType
dirtyFirst mbox node tab = mnesia mbox node "dirty_first" [ErlAtom tab]
dirtyNext :: MBox -> Node -> String -> ErlType -> IO ErlType
dirtyNext mbox node tab key = mnesia mbox node "dirty_next" [ErlAtom tab, key]
dirtyLast :: MBox -> Node -> String -> IO ErlType
dirtyLast mbox node tab = mnesia mbox node "dirty_last" [ErlAtom tab]
dirtyPrev :: MBox -> Node -> String -> ErlType -> IO ErlType
dirtyPrev mbox node tab key = mnesia mbox node "dirty_pref" [ErlAtom tab, key]
dirtyMatchObject :: MBox -> Node -> ErlType -> IO ErlType
dirtyMatchObject mbox node pat = mnesia mbox node "dirty_match_object" [pat]
dirtyRead :: MBox -> Node -> String -> ErlType -> IO ErlType
dirtyRead mbox node tab key = mnesia mbox node "dirty_read" [ErlAtom tab, key]
dirtySelect :: MBox -> Node -> String -> ErlType -> IO ErlType
dirtySelect mbox node tab spec = mnesia mbox node "dirty_select" [spec]
| gombocarti/erlang-ffi | src/Foreign/Erlang/OTP/Mnesia.hs | gpl-3.0 | 1,962 | 0 | 9 | 403 | 599 | 317 | 282 | 34 | 1 |
{-|
Various options to use when reading journal files.
Similar to CliOptions.inputflags, simplifies the journal-reading functions.
-}
{-# LANGUAGE TemplateHaskell #-}
module Hledger.Read.InputOptions (
-- * Types and helpers for input options
InputOpts(..)
, HasInputOpts(..)
, definputopts
, forecastPeriod
) where
import Control.Applicative ((<|>))
import Data.Time (Day, addDays)
import Hledger.Data.Types
import Hledger.Data.Journal (journalEndDate)
import Hledger.Data.Dates (nulldate, nulldatespan)
import Hledger.Data.Balancing (BalancingOpts(..), HasBalancingOpts(..), defbalancingopts)
import Hledger.Utils (dbg2, makeHledgerClassyLenses)
data InputOpts = InputOpts {
-- files_ :: [FilePath]
mformat_ :: Maybe StorageFormat -- ^ a file/storage format to try, unless overridden
-- by a filename prefix. Nothing means try all.
,mrules_file_ :: Maybe FilePath -- ^ a conversion rules file to use (when reading CSV)
,aliases_ :: [String] -- ^ account name aliases to apply
,anon_ :: Bool -- ^ do light anonymisation/obfuscation of the data
,new_ :: Bool -- ^ read only new transactions since this file was last read
,new_save_ :: Bool -- ^ save latest new transactions state for next time
,pivot_ :: String -- ^ use the given field's value as the account name
,forecast_ :: Maybe DateSpan -- ^ span in which to generate forecast transactions
,reportspan_ :: DateSpan -- ^ a dirty hack keeping the query dates in InputOpts. This rightfully lives in ReportSpec, but is duplicated here.
,auto_ :: Bool -- ^ generate automatic postings when journal is parsed
,infer_equity_ :: Bool -- ^ generate automatic equity postings from transaction prices
,balancingopts_ :: BalancingOpts -- ^ options for balancing transactions
,strict_ :: Bool -- ^ do extra error checking (eg, all posted accounts are declared, no prices are inferred)
,_ioDay :: Day -- ^ today's date, for use with forecast transactions XXX this duplicates _rsDay, and should eventually be removed when it's not needed anymore.
} deriving (Show)
definputopts :: InputOpts
definputopts = InputOpts
{ mformat_ = Nothing
, mrules_file_ = Nothing
, aliases_ = []
, anon_ = False
, new_ = False
, new_save_ = True
, pivot_ = ""
, forecast_ = Nothing
, reportspan_ = nulldatespan
, auto_ = False
, infer_equity_ = False
, balancingopts_ = defbalancingopts
, strict_ = False
, _ioDay = nulldate
}
-- | Get the Maybe the DateSpan to generate forecast options from.
-- This begins on:
-- - the start date supplied to the `--forecast` argument, if present
-- - otherwise, the later of
-- - the report start date if specified with -b/-p/date:
-- - the day after the latest normal (non-periodic) transaction in the journal, if any
-- - otherwise today.
-- It ends on:
-- - the end date supplied to the `--forecast` argument, if present
-- - otherwise the report end date if specified with -e/-p/date:
-- - otherwise 180 days (6 months) from today.
forecastPeriod :: InputOpts -> Journal -> Maybe DateSpan
forecastPeriod iopts j = do
DateSpan requestedStart requestedEnd <- forecast_ iopts
let forecastStart = requestedStart <|> max mjournalend reportStart <|> Just (_ioDay iopts)
forecastEnd = requestedEnd <|> reportEnd <|> Just (addDays 180 $ _ioDay iopts)
mjournalend = dbg2 "journalEndDate" $ journalEndDate False j -- ignore secondary dates
DateSpan reportStart reportEnd = reportspan_ iopts
return . dbg2 "forecastspan" $ DateSpan forecastStart forecastEnd
-- ** Lenses
makeHledgerClassyLenses ''InputOpts
instance HasBalancingOpts InputOpts where
balancingOpts = balancingopts
| adept/hledger | hledger-lib/Hledger/Read/InputOptions.hs | gpl-3.0 | 4,222 | 0 | 14 | 1,224 | 537 | 326 | 211 | 56 | 1 |
{-
Notifaika reposts notifications
from different feeds to Gitter chats.
Copyright (C) 2015 Yuriy Syrovetskiy
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/>.
-}
module Notifaika.Config (Config (..)) where
import Gitter.Types (Gitter)
import Notifaika.EventSource (EventSource)
data Config = Config
{ configCacheFile :: FilePath
, configSources :: [EventSource]
, configGitter :: Gitter
}
| cblp/discourse-to-gitter | src/Notifaika/Config.hs | gpl-3.0 | 1,025 | 0 | 9 | 220 | 66 | 42 | 24 | 7 | 0 |
module Propellor.Property.HostingProvider.Linode where
import Propellor
import qualified Propellor.Property.Grub as Grub
-- | Linode's pv-grub-x86_64 does not currently support booting recent
-- Debian kernels compressed with xz. This sets up pv-grub chaing to enable
-- it.
chainPVGrub :: Grub.TimeoutSecs -> Property
chainPVGrub = Grub.chainPVGrub "hd0" "xen/xvda"
| abailly/propellor-test2 | src/Propellor/Property/HostingProvider/Linode.hs | bsd-2-clause | 369 | 0 | 6 | 47 | 46 | 30 | 16 | 5 | 1 |
{-# LANGUAGE CPP #-}
-- | Handy functions for creating much Core syntax
module MkCore (
-- * Constructing normal syntax
mkCoreLet, mkCoreLets,
mkCoreApp, mkCoreApps, mkCoreConApps,
mkCoreLams, mkWildCase, mkIfThenElse,
mkWildValBinder, mkWildEvBinder,
sortQuantVars, castBottomExpr,
-- * Constructing boxed literals
mkWordExpr, mkWordExprWord,
mkIntExpr, mkIntExprInt,
mkIntegerExpr,
mkFloatExpr, mkDoubleExpr,
mkCharExpr, mkStringExpr, mkStringExprFS,
-- * Floats
FloatBind(..), wrapFloat,
-- * Constructing small tuples
mkCoreVarTup, mkCoreVarTupTy, mkCoreTup, mkCoreUbxTup,
mkCoreTupBoxity,
-- * Constructing big tuples
mkBigCoreVarTup, mkBigCoreVarTup1,
mkBigCoreVarTupTy, mkBigCoreTupTy,
mkBigCoreTup,
-- * Deconstructing small tuples
mkSmallTupleSelector, mkSmallTupleCase,
-- * Deconstructing big tuples
mkTupleSelector, mkTupleSelector1, mkTupleCase,
-- * Constructing list expressions
mkNilExpr, mkConsExpr, mkListExpr,
mkFoldrExpr, mkBuildExpr,
-- * Constructing Maybe expressions
mkNothingExpr, mkJustExpr,
-- * Error Ids
mkRuntimeErrorApp, mkImpossibleExpr, errorIds,
rEC_CON_ERROR_ID, iRREFUT_PAT_ERROR_ID, rUNTIME_ERROR_ID,
nON_EXHAUSTIVE_GUARDS_ERROR_ID, nO_METHOD_BINDING_ERROR_ID,
pAT_ERROR_ID, rEC_SEL_ERROR_ID, aBSENT_ERROR_ID,
tYPE_ERROR_ID,
) where
#include "HsVersions.h"
import Id
import Var ( EvVar, setTyVarUnique )
import CoreSyn
import CoreUtils ( exprType, needsCaseBinding, bindNonRec )
import Literal
import HscTypes
import TysWiredIn
import PrelNames
import HsUtils ( mkChunkified, chunkify )
import TcType ( mkSpecSigmaTy )
import Type
import Coercion ( isCoVar )
import TysPrim
import DataCon ( DataCon, dataConWorkId )
import IdInfo ( vanillaIdInfo, setStrictnessInfo,
setArityInfo )
import Demand
import Name hiding ( varName )
import Outputable
import FastString
import UniqSupply
import BasicTypes
import Util
import DynFlags
import Data.List
import Data.Char ( ord )
infixl 4 `mkCoreApp`, `mkCoreApps`
{-
************************************************************************
* *
\subsection{Basic CoreSyn construction}
* *
************************************************************************
-}
sortQuantVars :: [Var] -> [Var]
-- Sort the variables, putting type and covars first, in scoped order,
-- and then other Ids
-- It is a deterministic sort, meaining it doesn't look at the values of
-- Uniques. For explanation why it's important See Note [Unique Determinism]
-- in Unique.
sortQuantVars vs = sorted_tcvs ++ ids
where
(tcvs, ids) = partition (isTyVar <||> isCoVar) vs
sorted_tcvs = toposortTyVars tcvs
-- | Bind a binding group over an expression, using a @let@ or @case@ as
-- appropriate (see "CoreSyn#let_app_invariant")
mkCoreLet :: CoreBind -> CoreExpr -> CoreExpr
mkCoreLet (NonRec bndr rhs) body -- See Note [CoreSyn let/app invariant]
| needsCaseBinding (idType bndr) rhs
= Case rhs bndr (exprType body) [(DEFAULT,[],body)]
mkCoreLet bind body
= Let bind body
-- | Bind a list of binding groups over an expression. The leftmost binding
-- group becomes the outermost group in the resulting expression
mkCoreLets :: [CoreBind] -> CoreExpr -> CoreExpr
mkCoreLets binds body = foldr mkCoreLet body binds
-- | Construct an expression which represents the application of one expression
-- to the other
mkCoreApp :: SDoc -> CoreExpr -> CoreExpr -> CoreExpr
-- Respects the let/app invariant by building a case expression where necessary
-- See CoreSyn Note [CoreSyn let/app invariant]
mkCoreApp _ fun (Type ty) = App fun (Type ty)
mkCoreApp _ fun (Coercion co) = App fun (Coercion co)
mkCoreApp d fun arg = ASSERT2( isFunTy fun_ty, ppr fun $$ ppr arg $$ d )
mk_val_app fun arg arg_ty res_ty
where
fun_ty = exprType fun
(arg_ty, res_ty) = splitFunTy fun_ty
-- | Construct an expression which represents the application of a number of
-- expressions to another. The leftmost expression in the list is applied first
-- Respects the let/app invariant by building a case expression where necessary
-- See CoreSyn Note [CoreSyn let/app invariant]
mkCoreApps :: CoreExpr -> [CoreExpr] -> CoreExpr
-- Slightly more efficient version of (foldl mkCoreApp)
mkCoreApps orig_fun orig_args
= go orig_fun (exprType orig_fun) orig_args
where
go fun _ [] = fun
go fun fun_ty (Type ty : args) = go (App fun (Type ty)) (piResultTy fun_ty ty) args
go fun fun_ty (arg : args) = ASSERT2( isFunTy fun_ty, ppr fun_ty $$ ppr orig_fun
$$ ppr orig_args )
go (mk_val_app fun arg arg_ty res_ty) res_ty args
where
(arg_ty, res_ty) = splitFunTy fun_ty
-- | Construct an expression which represents the application of a number of
-- expressions to that of a data constructor expression. The leftmost expression
-- in the list is applied first
mkCoreConApps :: DataCon -> [CoreExpr] -> CoreExpr
mkCoreConApps con args = mkCoreApps (Var (dataConWorkId con)) args
mk_val_app :: CoreExpr -> CoreExpr -> Type -> Type -> CoreExpr
-- Build an application (e1 e2),
-- or a strict binding (case e2 of x -> e1 x)
-- using the latter when necessary to respect the let/app invariant
-- See Note [CoreSyn let/app invariant]
mk_val_app fun arg arg_ty res_ty
| not (needsCaseBinding arg_ty arg)
= App fun arg -- The vastly common case
| otherwise
= Case arg arg_id res_ty [(DEFAULT,[],App fun (Var arg_id))]
where
arg_id = mkWildValBinder arg_ty
-- Lots of shadowing, but it doesn't matter,
-- because 'fun ' should not have a free wild-id
--
-- This is Dangerous. But this is the only place we play this
-- game, mk_val_app returns an expression that does not have
-- have a free wild-id. So the only thing that can go wrong
-- is if you take apart this case expression, and pass a
-- fragmet of it as the fun part of a 'mk_val_app'.
-----------
mkWildEvBinder :: PredType -> EvVar
mkWildEvBinder pred = mkWildValBinder pred
-- | Make a /wildcard binder/. This is typically used when you need a binder
-- that you expect to use only at a *binding* site. Do not use it at
-- occurrence sites because it has a single, fixed unique, and it's very
-- easy to get into difficulties with shadowing. That's why it is used so little.
-- See Note [WildCard binders] in SimplEnv
mkWildValBinder :: Type -> Id
mkWildValBinder ty = mkLocalIdOrCoVar wildCardName ty
mkWildCase :: CoreExpr -> Type -> Type -> [CoreAlt] -> CoreExpr
-- Make a case expression whose case binder is unused
-- The alts should not have any occurrences of WildId
mkWildCase scrut scrut_ty res_ty alts
= Case scrut (mkWildValBinder scrut_ty) res_ty alts
mkIfThenElse :: CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
mkIfThenElse guard then_expr else_expr
-- Not going to be refining, so okay to take the type of the "then" clause
= mkWildCase guard boolTy (exprType then_expr)
[ (DataAlt falseDataCon, [], else_expr), -- Increasing order of tag!
(DataAlt trueDataCon, [], then_expr) ]
castBottomExpr :: CoreExpr -> Type -> CoreExpr
-- (castBottomExpr e ty), assuming that 'e' diverges,
-- return an expression of type 'ty'
-- See Note [Empty case alternatives] in CoreSyn
castBottomExpr e res_ty
| e_ty `eqType` res_ty = e
| otherwise = Case e (mkWildValBinder e_ty) res_ty []
where
e_ty = exprType e
{-
The functions from this point don't really do anything cleverer than
their counterparts in CoreSyn, but they are here for consistency
-}
-- | Create a lambda where the given expression has a number of variables
-- bound over it. The leftmost binder is that bound by the outermost
-- lambda in the result
mkCoreLams :: [CoreBndr] -> CoreExpr -> CoreExpr
mkCoreLams = mkLams
{-
************************************************************************
* *
\subsection{Making literals}
* *
************************************************************************
-}
-- | Create a 'CoreExpr' which will evaluate to the given @Int@
mkIntExpr :: DynFlags -> Integer -> CoreExpr -- Result = I# i :: Int
mkIntExpr dflags i = mkCoreConApps intDataCon [mkIntLit dflags i]
-- | Create a 'CoreExpr' which will evaluate to the given @Int@
mkIntExprInt :: DynFlags -> Int -> CoreExpr -- Result = I# i :: Int
mkIntExprInt dflags i = mkCoreConApps intDataCon [mkIntLitInt dflags i]
-- | Create a 'CoreExpr' which will evaluate to the a @Word@ with the given value
mkWordExpr :: DynFlags -> Integer -> CoreExpr
mkWordExpr dflags w = mkCoreConApps wordDataCon [mkWordLit dflags w]
-- | Create a 'CoreExpr' which will evaluate to the given @Word@
mkWordExprWord :: DynFlags -> Word -> CoreExpr
mkWordExprWord dflags w = mkCoreConApps wordDataCon [mkWordLitWord dflags w]
-- | Create a 'CoreExpr' which will evaluate to the given @Integer@
mkIntegerExpr :: MonadThings m => Integer -> m CoreExpr -- Result :: Integer
mkIntegerExpr i = do t <- lookupTyCon integerTyConName
return (Lit (mkLitInteger i (mkTyConTy t)))
-- | Create a 'CoreExpr' which will evaluate to the given @Float@
mkFloatExpr :: Float -> CoreExpr
mkFloatExpr f = mkCoreConApps floatDataCon [mkFloatLitFloat f]
-- | Create a 'CoreExpr' which will evaluate to the given @Double@
mkDoubleExpr :: Double -> CoreExpr
mkDoubleExpr d = mkCoreConApps doubleDataCon [mkDoubleLitDouble d]
-- | Create a 'CoreExpr' which will evaluate to the given @Char@
mkCharExpr :: Char -> CoreExpr -- Result = C# c :: Int
mkCharExpr c = mkCoreConApps charDataCon [mkCharLit c]
-- | Create a 'CoreExpr' which will evaluate to the given @String@
mkStringExpr :: MonadThings m => String -> m CoreExpr -- Result :: String
-- | Create a 'CoreExpr' which will evaluate to a string morally equivalent to the given @FastString@
mkStringExprFS :: MonadThings m => FastString -> m CoreExpr -- Result :: String
mkStringExpr str = mkStringExprFS (mkFastString str)
mkStringExprFS str
| nullFS str
= return (mkNilExpr charTy)
| all safeChar chars
= do unpack_id <- lookupId unpackCStringName
return (App (Var unpack_id) lit)
| otherwise
= do unpack_utf8_id <- lookupId unpackCStringUtf8Name
return (App (Var unpack_utf8_id) lit)
where
chars = unpackFS str
safeChar c = ord c >= 1 && ord c <= 0x7F
lit = Lit (MachStr (fastStringToByteString str))
{-
************************************************************************
* *
\subsection{Tuple constructors}
* *
************************************************************************
-}
{-
Creating tuples and their types for Core expressions
@mkBigCoreVarTup@ builds a tuple; the inverse to @mkTupleSelector@.
* If it has only one element, it is the identity function.
* If there are more elements than a big tuple can have, it nests
the tuples.
Note [Flattening one-tuples]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This family of functions creates a tuple of variables/expressions/types.
mkCoreTup [e1,e2,e3] = (e1,e2,e3)
What if there is just one variable/expression/type in the agument?
We could do one of two things:
* Flatten it out, so that
mkCoreTup [e1] = e1
* Built a one-tuple (see Note [One-tuples] in TysWiredIn)
mkCoreTup1 [e1] = Unit e1
We use a suffix "1" to indicate this.
Usually we want the former, but occasionally the latter.
-}
-- | Build a small tuple holding the specified variables
-- One-tuples are flattened; see Note [Flattening one-tuples]
mkCoreVarTup :: [Id] -> CoreExpr
mkCoreVarTup ids = mkCoreTup (map Var ids)
-- | Build the type of a small tuple that holds the specified variables
-- One-tuples are flattened; see Note [Flattening one-tuples]
mkCoreVarTupTy :: [Id] -> Type
mkCoreVarTupTy ids = mkBoxedTupleTy (map idType ids)
-- | Build a small tuple holding the specified expressions
-- One-tuples are flattened; see Note [Flattening one-tuples]
mkCoreTup :: [CoreExpr] -> CoreExpr
mkCoreTup [] = Var unitDataConId
mkCoreTup [c] = c
mkCoreTup cs = mkCoreConApps (tupleDataCon Boxed (length cs))
(map (Type . exprType) cs ++ cs)
-- | Build a small unboxed tuple holding the specified expressions,
-- with the given types. The types must be the types of the expressions.
-- Do not include the RuntimeRep specifiers; this function calculates them
-- for you.
-- Does /not/ flatten one-tuples; see Note [Flattening one-tuples]
mkCoreUbxTup :: [Type] -> [CoreExpr] -> CoreExpr
mkCoreUbxTup tys exps
= ASSERT( tys `equalLength` exps)
mkCoreConApps (tupleDataCon Unboxed (length tys))
(map (Type . getRuntimeRep "mkCoreUbxTup") tys ++ map Type tys ++ exps)
-- | Make a core tuple of the given boxity
mkCoreTupBoxity :: Boxity -> [CoreExpr] -> CoreExpr
mkCoreTupBoxity Boxed exps = mkCoreTup exps
mkCoreTupBoxity Unboxed exps = mkCoreUbxTup (map exprType exps) exps
-- | Build a big tuple holding the specified variables
-- One-tuples are flattened; see Note [Flattening one-tuples]
mkBigCoreVarTup :: [Id] -> CoreExpr
mkBigCoreVarTup ids = mkBigCoreTup (map Var ids)
mkBigCoreVarTup1 :: [Id] -> CoreExpr
-- Same as mkBigCoreVarTup, but one-tuples are NOT flattened
-- see Note [Flattening one-tuples]
mkBigCoreVarTup1 [id] = mkCoreConApps (tupleDataCon Boxed 1)
[Type (idType id), Var id]
mkBigCoreVarTup1 ids = mkBigCoreTup (map Var ids)
-- | Build the type of a big tuple that holds the specified variables
-- One-tuples are flattened; see Note [Flattening one-tuples]
mkBigCoreVarTupTy :: [Id] -> Type
mkBigCoreVarTupTy ids = mkBigCoreTupTy (map idType ids)
-- | Build a big tuple holding the specified expressions
-- One-tuples are flattened; see Note [Flattening one-tuples]
mkBigCoreTup :: [CoreExpr] -> CoreExpr
mkBigCoreTup = mkChunkified mkCoreTup
-- | Build the type of a big tuple that holds the specified type of thing
-- One-tuples are flattened; see Note [Flattening one-tuples]
mkBigCoreTupTy :: [Type] -> Type
mkBigCoreTupTy = mkChunkified mkBoxedTupleTy
{-
************************************************************************
* *
\subsection{Tuple destructors}
* *
************************************************************************
-}
-- | Builds a selector which scrutises the given
-- expression and extracts the one name from the list given.
-- If you want the no-shadowing rule to apply, the caller
-- is responsible for making sure that none of these names
-- are in scope.
--
-- If there is just one 'Id' in the tuple, then the selector is
-- just the identity.
--
-- If necessary, we pattern match on a \"big\" tuple.
mkTupleSelector, mkTupleSelector1
:: [Id] -- ^ The 'Id's to pattern match the tuple against
-> Id -- ^ The 'Id' to select
-> Id -- ^ A variable of the same type as the scrutinee
-> CoreExpr -- ^ Scrutinee
-> CoreExpr -- ^ Selector expression
-- mkTupleSelector [a,b,c,d] b v e
-- = case e of v {
-- (p,q) -> case p of p {
-- (a,b) -> b }}
-- We use 'tpl' vars for the p,q, since shadowing does not matter.
--
-- In fact, it's more convenient to generate it innermost first, getting
--
-- case (case e of v
-- (p,q) -> p) of p
-- (a,b) -> b
mkTupleSelector vars the_var scrut_var scrut
= mk_tup_sel (chunkify vars) the_var
where
mk_tup_sel [vars] the_var = mkSmallTupleSelector vars the_var scrut_var scrut
mk_tup_sel vars_s the_var = mkSmallTupleSelector group the_var tpl_v $
mk_tup_sel (chunkify tpl_vs) tpl_v
where
tpl_tys = [mkBoxedTupleTy (map idType gp) | gp <- vars_s]
tpl_vs = mkTemplateLocals tpl_tys
[(tpl_v, group)] = [(tpl,gp) | (tpl,gp) <- zipEqual "mkTupleSelector" tpl_vs vars_s,
the_var `elem` gp ]
-- ^ 'mkTupleSelector1' is like 'mkTupleSelector'
-- but one-tuples are NOT flattened (see Note [Flattening one-tuples])
mkTupleSelector1 vars the_var scrut_var scrut
| [_] <- vars
= mkSmallTupleSelector1 vars the_var scrut_var scrut
| otherwise
= mkTupleSelector vars the_var scrut_var scrut
-- | Like 'mkTupleSelector' but for tuples that are guaranteed
-- never to be \"big\".
--
-- > mkSmallTupleSelector [x] x v e = [| e |]
-- > mkSmallTupleSelector [x,y,z] x v e = [| case e of v { (x,y,z) -> x } |]
mkSmallTupleSelector, mkSmallTupleSelector1
:: [Id] -- The tuple args
-> Id -- The selected one
-> Id -- A variable of the same type as the scrutinee
-> CoreExpr -- Scrutinee
-> CoreExpr
mkSmallTupleSelector [var] should_be_the_same_var _ scrut
= ASSERT(var == should_be_the_same_var)
scrut -- Special case for 1-tuples
mkSmallTupleSelector vars the_var scrut_var scrut
= mkSmallTupleSelector1 vars the_var scrut_var scrut
-- ^ 'mkSmallTupleSelector1' is like 'mkSmallTupleSelector'
-- but one-tuples are NOT flattened (see Note [Flattening one-tuples])
mkSmallTupleSelector1 vars the_var scrut_var scrut
= ASSERT( notNull vars )
Case scrut scrut_var (idType the_var)
[(DataAlt (tupleDataCon Boxed (length vars)), vars, Var the_var)]
-- | A generalization of 'mkTupleSelector', allowing the body
-- of the case to be an arbitrary expression.
--
-- To avoid shadowing, we use uniques to invent new variables.
--
-- If necessary we pattern match on a \"big\" tuple.
mkTupleCase :: UniqSupply -- ^ For inventing names of intermediate variables
-> [Id] -- ^ The tuple identifiers to pattern match on
-> CoreExpr -- ^ Body of the case
-> Id -- ^ A variable of the same type as the scrutinee
-> CoreExpr -- ^ Scrutinee
-> CoreExpr
-- ToDo: eliminate cases where none of the variables are needed.
--
-- mkTupleCase uniqs [a,b,c,d] body v e
-- = case e of v { (p,q) ->
-- case p of p { (a,b) ->
-- case q of q { (c,d) ->
-- body }}}
mkTupleCase uniqs vars body scrut_var scrut
= mk_tuple_case uniqs (chunkify vars) body
where
-- This is the case where don't need any nesting
mk_tuple_case _ [vars] body
= mkSmallTupleCase vars body scrut_var scrut
-- This is the case where we must make nest tuples at least once
mk_tuple_case us vars_s body
= let (us', vars', body') = foldr one_tuple_case (us, [], body) vars_s
in mk_tuple_case us' (chunkify vars') body'
one_tuple_case chunk_vars (us, vs, body)
= let (uniq, us') = takeUniqFromSupply us
scrut_var = mkSysLocal (fsLit "ds") uniq
(mkBoxedTupleTy (map idType chunk_vars))
body' = mkSmallTupleCase chunk_vars body scrut_var (Var scrut_var)
in (us', scrut_var:vs, body')
-- | As 'mkTupleCase', but for a tuple that is small enough to be guaranteed
-- not to need nesting.
mkSmallTupleCase
:: [Id] -- ^ The tuple args
-> CoreExpr -- ^ Body of the case
-> Id -- ^ A variable of the same type as the scrutinee
-> CoreExpr -- ^ Scrutinee
-> CoreExpr
mkSmallTupleCase [var] body _scrut_var scrut
= bindNonRec var scrut body
mkSmallTupleCase vars body scrut_var scrut
-- One branch no refinement?
= Case scrut scrut_var (exprType body)
[(DataAlt (tupleDataCon Boxed (length vars)), vars, body)]
{-
************************************************************************
* *
Floats
* *
************************************************************************
-}
data FloatBind
= FloatLet CoreBind
| FloatCase CoreExpr Id AltCon [Var]
-- case e of y { C ys -> ... }
-- See Note [Floating cases] in SetLevels
instance Outputable FloatBind where
ppr (FloatLet b) = text "LET" <+> ppr b
ppr (FloatCase e b c bs) = hang (text "CASE" <+> ppr e <+> ptext (sLit "of") <+> ppr b)
2 (ppr c <+> ppr bs)
wrapFloat :: FloatBind -> CoreExpr -> CoreExpr
wrapFloat (FloatLet defns) body = Let defns body
wrapFloat (FloatCase e b con bs) body = Case e b (exprType body) [(con, bs, body)]
{-
************************************************************************
* *
\subsection{Common list manipulation expressions}
* *
************************************************************************
Call the constructor Ids when building explicit lists, so that they
interact well with rules.
-}
-- | Makes a list @[]@ for lists of the specified type
mkNilExpr :: Type -> CoreExpr
mkNilExpr ty = mkCoreConApps nilDataCon [Type ty]
-- | Makes a list @(:)@ for lists of the specified type
mkConsExpr :: Type -> CoreExpr -> CoreExpr -> CoreExpr
mkConsExpr ty hd tl = mkCoreConApps consDataCon [Type ty, hd, tl]
-- | Make a list containing the given expressions, where the list has the given type
mkListExpr :: Type -> [CoreExpr] -> CoreExpr
mkListExpr ty xs = foldr (mkConsExpr ty) (mkNilExpr ty) xs
-- | Make a fully applied 'foldr' expression
mkFoldrExpr :: MonadThings m
=> Type -- ^ Element type of the list
-> Type -- ^ Fold result type
-> CoreExpr -- ^ "Cons" function expression for the fold
-> CoreExpr -- ^ "Nil" expression for the fold
-> CoreExpr -- ^ List expression being folded acress
-> m CoreExpr
mkFoldrExpr elt_ty result_ty c n list = do
foldr_id <- lookupId foldrName
return (Var foldr_id `App` Type elt_ty
`App` Type result_ty
`App` c
`App` n
`App` list)
-- | Make a 'build' expression applied to a locally-bound worker function
mkBuildExpr :: (MonadThings m, MonadUnique m)
=> Type -- ^ Type of list elements to be built
-> ((Id, Type) -> (Id, Type) -> m CoreExpr) -- ^ Function that, given information about the 'Id's
-- of the binders for the build worker function, returns
-- the body of that worker
-> m CoreExpr
mkBuildExpr elt_ty mk_build_inside = do
[n_tyvar] <- newTyVars [alphaTyVar]
let n_ty = mkTyVarTy n_tyvar
c_ty = mkFunTys [elt_ty, n_ty] n_ty
[c, n] <- sequence [mkSysLocalM (fsLit "c") c_ty, mkSysLocalM (fsLit "n") n_ty]
build_inside <- mk_build_inside (c, c_ty) (n, n_ty)
build_id <- lookupId buildName
return $ Var build_id `App` Type elt_ty `App` mkLams [n_tyvar, c, n] build_inside
where
newTyVars tyvar_tmpls = do
uniqs <- getUniquesM
return (zipWith setTyVarUnique tyvar_tmpls uniqs)
{-
************************************************************************
* *
Manipulating Maybe data type
* *
************************************************************************
-}
-- | Makes a Nothing for the specified type
mkNothingExpr :: Type -> CoreExpr
mkNothingExpr ty = mkConApp nothingDataCon [Type ty]
-- | Makes a Just from a value of the specified type
mkJustExpr :: Type -> CoreExpr -> CoreExpr
mkJustExpr ty val = mkConApp justDataCon [Type ty, val]
{-
************************************************************************
* *
Error expressions
* *
************************************************************************
-}
mkRuntimeErrorApp
:: Id -- Should be of type (forall a. Addr# -> a)
-- where Addr# points to a UTF8 encoded string
-> Type -- The type to instantiate 'a'
-> String -- The string to print
-> CoreExpr
mkRuntimeErrorApp err_id res_ty err_msg
= mkApps (Var err_id) [ Type (getRuntimeRep "mkRuntimeErrorApp" res_ty)
, Type res_ty, err_string ]
where
err_string = Lit (mkMachString err_msg)
mkImpossibleExpr :: Type -> CoreExpr
mkImpossibleExpr res_ty
= mkRuntimeErrorApp rUNTIME_ERROR_ID res_ty "Impossible case alternative"
{-
************************************************************************
* *
Error Ids
* *
************************************************************************
GHC randomly injects these into the code.
@patError@ is just a version of @error@ for pattern-matching
failures. It knows various ``codes'' which expand to longer
strings---this saves space!
@absentErr@ is a thing we put in for ``absent'' arguments. They jolly
well shouldn't be yanked on, but if one is, then you will get a
friendly message from @absentErr@ (rather than a totally random
crash).
@parError@ is a special version of @error@ which the compiler does
not know to be a bottoming Id. It is used in the @_par_@ and @_seq_@
templates, but we don't ever expect to generate code for it.
-}
errorIds :: [Id]
errorIds
= [ rUNTIME_ERROR_ID,
iRREFUT_PAT_ERROR_ID,
nON_EXHAUSTIVE_GUARDS_ERROR_ID,
nO_METHOD_BINDING_ERROR_ID,
pAT_ERROR_ID,
rEC_CON_ERROR_ID,
rEC_SEL_ERROR_ID,
aBSENT_ERROR_ID,
tYPE_ERROR_ID -- Used with Opt_DeferTypeErrors, see #10284
]
recSelErrorName, runtimeErrorName, absentErrorName :: Name
irrefutPatErrorName, recConErrorName, patErrorName :: Name
nonExhaustiveGuardsErrorName, noMethodBindingErrorName :: Name
typeErrorName :: Name
recSelErrorName = err_nm "recSelError" recSelErrorIdKey rEC_SEL_ERROR_ID
absentErrorName = err_nm "absentError" absentErrorIdKey aBSENT_ERROR_ID
runtimeErrorName = err_nm "runtimeError" runtimeErrorIdKey rUNTIME_ERROR_ID
irrefutPatErrorName = err_nm "irrefutPatError" irrefutPatErrorIdKey iRREFUT_PAT_ERROR_ID
recConErrorName = err_nm "recConError" recConErrorIdKey rEC_CON_ERROR_ID
patErrorName = err_nm "patError" patErrorIdKey pAT_ERROR_ID
typeErrorName = err_nm "typeError" typeErrorIdKey tYPE_ERROR_ID
noMethodBindingErrorName = err_nm "noMethodBindingError"
noMethodBindingErrorIdKey nO_METHOD_BINDING_ERROR_ID
nonExhaustiveGuardsErrorName = err_nm "nonExhaustiveGuardsError"
nonExhaustiveGuardsErrorIdKey nON_EXHAUSTIVE_GUARDS_ERROR_ID
err_nm :: String -> Unique -> Id -> Name
err_nm str uniq id = mkWiredInIdName cONTROL_EXCEPTION_BASE (fsLit str) uniq id
rEC_SEL_ERROR_ID, rUNTIME_ERROR_ID, iRREFUT_PAT_ERROR_ID, rEC_CON_ERROR_ID :: Id
pAT_ERROR_ID, nO_METHOD_BINDING_ERROR_ID, nON_EXHAUSTIVE_GUARDS_ERROR_ID :: Id
tYPE_ERROR_ID, aBSENT_ERROR_ID :: Id
rEC_SEL_ERROR_ID = mkRuntimeErrorId recSelErrorName
rUNTIME_ERROR_ID = mkRuntimeErrorId runtimeErrorName
iRREFUT_PAT_ERROR_ID = mkRuntimeErrorId irrefutPatErrorName
rEC_CON_ERROR_ID = mkRuntimeErrorId recConErrorName
pAT_ERROR_ID = mkRuntimeErrorId patErrorName
nO_METHOD_BINDING_ERROR_ID = mkRuntimeErrorId noMethodBindingErrorName
nON_EXHAUSTIVE_GUARDS_ERROR_ID = mkRuntimeErrorId nonExhaustiveGuardsErrorName
aBSENT_ERROR_ID = mkRuntimeErrorId absentErrorName
tYPE_ERROR_ID = mkRuntimeErrorId typeErrorName
mkRuntimeErrorId :: Name -> Id
-- Error function
-- with type: forall (r:RuntimeRep) (a:TYPE r). Addr# -> a
-- with arity: 1
-- which diverges after being given one argument
-- The Addr# is expected to be the address of
-- a UTF8-encoded error string
mkRuntimeErrorId name
= mkVanillaGlobalWithInfo name runtime_err_ty bottoming_info
where
bottoming_info = vanillaIdInfo `setStrictnessInfo` strict_sig
`setArityInfo` 1
-- Make arity and strictness agree
-- Do *not* mark them as NoCafRefs, because they can indeed have
-- CAF refs. For example, pAT_ERROR_ID calls GHC.Err.untangle,
-- which has some CAFs
-- In due course we may arrange that these error-y things are
-- regarded by the GC as permanently live, in which case we
-- can give them NoCaf info. As it is, any function that calls
-- any pc_bottoming_Id will itself have CafRefs, which bloats
-- SRTs.
strict_sig = mkClosedStrictSig [evalDmd] exnRes
-- exnRes: these throw an exception, not just diverge
-- forall (rr :: RuntimeRep) (a :: rr). Addr# -> a
-- See Note [Error and friends have an "open-tyvar" forall]
runtime_err_ty = mkSpecSigmaTy [runtimeRep1TyVar, openAlphaTyVar] []
(mkFunTy addrPrimTy openAlphaTy)
{- Note [Error and friends have an "open-tyvar" forall]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'error' and 'undefined' have types
error :: forall (v :: RuntimeRep) (a :: TYPE v). String -> a
undefined :: forall (v :: RuntimeRep) (a :: TYPE v). a
Notice the runtime-representation polymophism. This ensures that
"error" can be instantiated at unboxed as well as boxed types.
This is OK because it never returns, so the return type is irrelevant.
-}
| snoyberg/ghc | compiler/coreSyn/MkCore.hs | bsd-3-clause | 31,027 | 0 | 15 | 8,362 | 4,515 | 2,467 | 2,048 | 346 | 3 |
{-# LANGUAGE RecursiveDo, FlexibleContexts #-}
module Main where
import Control.Applicative
import Control.Exception
import Control.DeepSeq
import Criterion.Main
import Data.Char
import Data.Maybe
import Text.Earley
import qualified Text.Parsec as Parsec
import qualified Text.Parsec.Pos as Parsec
data Expr
= Add Expr Expr
| Mul Expr Expr
| Var String
deriving (Eq, Ord, Show)
instance NFData Expr where
rnf (Add a b) = rnf a `seq` rnf b
rnf (Mul a b) = rnf a `seq` rnf b
rnf (Var s) = rnf s
type Token = String
tokenParens :: Bool -> [Token] -> [Token]
tokenParens True s = ["("] ++ s ++ [")"]
tokenParens False s = s
tokenExpr :: Int -> Expr -> [Token]
tokenExpr _ (Var s) = [s]
tokenExpr d (Add a b) = tokenParens (d > 0) $ tokenExpr 0 a ++ ["+"] ++ tokenExpr 1 b
tokenExpr d (Mul a b) = tokenParens (d > 1) $ tokenExpr 1 a ++ ["*"] ++ tokenExpr 2 b
linearSum :: Int -> Expr
linearSum 1 = Var "x"
linearSum n = Add (linearSum $ n - 1) (Var "x")
treeSum :: Int -> Expr
treeSum 1 = Var "x"
treeSum n = let a = n `div` 2 -- will be at least 1
b = n - a
in Add (treeSum a) (treeSum b)
-- Earley parser
expr :: Grammar r (Prod r String Token Expr)
expr = mdo
x1 <- rule $ Add <$> x1 <* namedToken "+" <*> x2
<|> x2
<?> "sum"
x2 <- rule $ Mul <$> x2 <* namedToken "*" <*> x3
<|> x3
<?> "product"
x3 <- rule $ Var <$> (satisfy isIdent <?> "identifier")
<|> namedToken "(" *> x1 <* namedToken ")"
return x1
isIdent :: String -> Bool
isIdent (x:_) = isAlpha x
isIdent _ = False
sepBy1 :: Prod r e t a -> Prod r e t op -> Grammar r (Prod r e t [a])
sepBy1 p op = mdo
ops <- rule $ pure [] <|> (:) <$ op <*> p <*> ops
rule $ (:) <$> p <*> ops
expr' :: Grammar r (Prod r String Token Expr)
expr' = mdo
let var = Var <$> satisfy isIdent <|> token "(" *> mul <* token ")"
mul <- fmap (foldl1 Mul) <$> add `sepBy1` token "*"
add <- fmap (foldl1 Add) <$> var `sepBy1` token "+"
return mul
parseEarley :: [Token] -> Maybe Expr
parseEarley input = listToMaybe (fst (fullParses (parser expr) input))
parseEarley' :: [Token] -> Maybe Expr
parseEarley' input = listToMaybe (fst (fullParses (parser expr') input))
-- Parsec parsec
type Parsec = Parsec.Parsec [Token] ()
parsecExpr :: Parsec Expr
parsecExpr = mul
where mul = foldl1 Mul <$> add `Parsec.sepBy1` t "*"
add = foldl1 Add <$> var `Parsec.sepBy1` t "+"
ident = Parsec.token id pos $ \y -> if isIdent y then Just (Var y) else Nothing
var = ident <|> (t "(" *> mul <* t ")")
t x = Parsec.token id pos $ \y -> if x == y then Just x else Nothing
pos = const (Parsec.initialPos "")
parseParsec :: [Token] -> Maybe Expr
parseParsec = either (const Nothing) Just . Parsec.parse parsecExpr ""
-- Our benchmark harness.
linearInput :: Int -> (String, [Token])
linearInput size = (show size, tokenExpr 0 $ linearSum size)
treeInput :: Int -> (String, [Token])
treeInput size = (show size, tokenExpr 0 $ treeSum size)
inputBench :: (String, [Token]) -> Benchmark
inputBench (name, input) = bench name $ nf id input
earleyBench :: (String, [Token]) -> Benchmark
earleyBench (name, input) = bench name $ nf parseEarley input
earley'Bench :: (String, [Token]) -> Benchmark
earley'Bench (name, input) = bench name $ nf parseEarley' input
parsecBench :: (String, [Token]) -> Benchmark
parsecBench (name, input) = bench name $ nf parseParsec input
benchSizes :: [Int]
benchSizes = [100, 200] -- [51, 101, 151, 201]
linearInputs :: [(String, [Token])]
linearInputs = map linearInput benchSizes
treeInputs :: [(String, [Token])]
treeInputs = map treeInput benchSizes
main :: IO ()
main = do
evaluate (rnf linearInputs)
evaluate (rnf treeInputs)
defaultMain
[ -- bgroup "inputs" $ map inputBench linearInputs
bgroup "earley" $ map earleyBench linearInputs
, bgroup "earley'" $ map earley'Bench linearInputs
, bgroup "parsec" $ map parsecBench linearInputs
-- , bgroup "inputsTree" $ map inputBench treeInputs
, bgroup "earleyTree" $ map earleyBench treeInputs
, bgroup "earley'Tree" $ map earley'Bench treeInputs
, bgroup "parsecTree" $ map parsecBench treeInputs
]
| sboosali/Earley | bench/BenchAll.hs | bsd-3-clause | 4,246 | 0 | 14 | 983 | 1,729 | 893 | 836 | 105 | 3 |
{-# LANGUAGE CPP #-}
module Herbie.CoreManip
where
import Class
import DsBinds
import DsMonad
import ErrUtils
import GhcPlugins hiding (trace)
import Unique
import MkId
import PrelNames
import UniqSupply
import TcRnMonad
import TcSimplify
import Type
import Control.Monad
import Control.Monad.Except
import Control.Monad.Trans
import Data.Char
import Data.List
import Data.Maybe
import Data.Ratio
import Herbie.MathExpr
import Prelude
import Show
-- import Debug.Trace hiding (traceM)
trace a b = b
traceM a = return ()
--------------------------------------------------------------------------------
instance MonadUnique m => MonadUnique (ExceptT e m) where
getUniqueSupplyM = lift getUniqueSupplyM
instance (Monad m, HasDynFlags m) => HasDynFlags (ExceptT e m) where
getDynFlags = lift getDynFlags
instance MonadThings m => MonadThings (ExceptT e m) where
lookupThing name = lift $ lookupThing name
data ExceptionType
= NotInScope String
| BadCxt String
| OtherException String
----------------------------------------
-- core manipulation
-- | Converts a string into a Core variable
getVar :: ModGuts -> String -> ExceptT ExceptionType CoreM Var
getVar guts opstr = do
opname <- getName guts opstr
hscenv <- lift getHscEnv
dflags <- getDynFlags
eps <- liftIO $ hscEPS hscenv
optype <- case lookupNameEnv (eps_PTE eps) opname of
Just (AnId i) -> return $ varType i
_ -> throwError (NotInScope opstr)
return $ mkGlobalVar VanillaId opname optype vanillaIdInfo
where
getName :: ModGuts -> String -> ExceptT ExceptionType CoreM Name
getName guts str = case filter isCorrectVar (concat $ occEnvElts (mg_rdr_env guts)) of
xs -> if not (null xs)
then return $ gre_name $ head xs
else throwError (NotInScope str)
where
isCorrectVar x = getString (gre_name x) == str
&& (str == "abs" || case gre_par x of NoParent -> False; _ -> True)
-- | Like "decorateFunction", but first finds the function variable given a string.
getDecoratedFunction :: ModGuts -> String -> Type -> [CoreExpr] -> ExceptT ExceptionType CoreM CoreExpr
getDecoratedFunction guts str t preds = do
f <- getVar guts str
decorateFunction guts f t preds
-- | Given a variable that contains a function,
-- the type the function is being applied to,
-- and all in scope predicates,
-- apply the type and any needed dictionaries to the function.
decorateFunction :: ModGuts -> Var -> Type -> [CoreExpr] -> ExceptT ExceptionType CoreM CoreExpr
decorateFunction guts f t preds = do
let ([v],unquantified) = extractQuantifiers $ varType f
(cxt,_) = extractContext unquantified
cxt' = substTysWith [v] [t] cxt
cxt'' <- mapM getDict cxt'
return $ mkApps (App (Var f) (Type t)) cxt''
where
getDict :: PredType -> ExceptT ExceptionType CoreM CoreExpr
getDict pred = do
catchError
(getDictionary guts pred)
(\_ -> getPredEvidence guts pred preds)
-- | Given a non-polymorphic PredType (e.g. `Num Float`),
-- return the corresponding dictionary.
getDictionary :: ModGuts -> Type -> ExceptT ExceptionType CoreM CoreExpr
getDictionary guts dictTy = do
let dictVar = mkGlobalVar
VanillaId
(mkSystemName (mkUnique 'z' 1337) (mkVarOcc "magicDictionaryName"))
dictTy
vanillaIdInfo
bnds <- lift $ runTcM guts $ do
loc <- getCtLoc $ GivenOrigin UnkSkol
let nonC = mkNonCanonical CtWanted
{ ctev_pred = varType dictVar
, ctev_evar = dictVar
, ctev_loc = loc
}
wCs = mkSimpleWC [nonC]
(x, evBinds) <- solveWantedsTcM wCs
bnds <- initDsTc $ dsEvBinds evBinds
-- liftIO $ do
-- putStrLn $ "dictType="++showSDoc dflags (ppr dictType)
-- putStrLn $ "dictVar="++showSDoc dflags (ppr dictVar)
--
-- putStrLn $ "nonC="++showSDoc dflags (ppr nonC)
-- putStrLn $ "wCs="++showSDoc dflags (ppr wCs)
-- putStrLn $ "bnds="++showSDoc dflags (ppr bnds)
-- putStrLn $ "x="++showSDoc dflags (ppr x)
return bnds
case bnds of
[NonRec _ dict] -> return dict
otherwise -> throwError $ BadCxt $ dbg dictTy
-- | Given a predicate for which we don't have evidence
-- and a list of expressions that contain evidence for predicates,
-- construct an expression that contains evidence for the given predicate.
getPredEvidence :: ModGuts -> PredType -> [CoreExpr] -> ExceptT ExceptionType CoreM CoreExpr
getPredEvidence guts pred evidenceExprs = go $ prepEvidence evidenceExprs
where
go :: [(CoreExpr,Type)] -> ExceptT ExceptionType CoreM CoreExpr
-- We've looked at all the evidence, but didn't find anything
go [] = throwError $ BadCxt $ dbg pred
-- Recursively descend into all the available predicates.
-- The list tracks both the evidence expression (this will change in recursive descent),
-- and the baseTy that gave rise to the expression (this stays constant).
go ((expr,baseTy):exprs) = if exprType expr == pred
-- The expression we've found matches the predicate.
-- We're done!
then return expr
-- The expression doesn't match the predicate,
-- so we recurse by searching for sub-predicates within expr
-- and adding them to the list.
else case classifyPredType (exprType expr) of
-- What we've found contains no more predicates to recurse into,
-- so we don't add anything to the list of exprs to search.
IrredPred _ -> go exprs
EqPred _ t1 t2 -> trace ("getPredEvidence.go.EP: pred="++dbg pred
++"; origType="++dbg baseTy
++"; exprType="++dbg (exprType expr)
) $ case splitAppTy_maybe pred of
Nothing -> trace " A" $ go exprs
-- Just (tyCon,tyApp) -> if baseTy/=tyApp
Just (tyCon,tyApp) -> trace " A'" $ if t1/=tyApp && t2 /=tyApp
then trace (" B: baseTy="++dbg baseTy++"; tyApp="++dbg tyApp)
$ go exprs
else do
let pred' = mkAppTy tyCon $ if t1==tyApp
then t2
else t1
getDictionary guts pred' >>= castToType evidenceExprs pred
-- We've found a class dictionary.
-- Recurse into each field (selId) of the dictionary.
-- Some (but not all) of these may be more dictionaries.
--
-- FIXME: Multiparamter classes broken
ClassPred c' [ct] -> trace ("getPredEvidence.go.CP: pred="++dbg pred
++"; origType="++dbg baseTy
++"; exprType="++dbg (exprType expr)
) $
go $
exprs++
[ ( App (App (Var selId) (Type baseTy)) expr
, baseTy
)
| selId <- classAllSelIds c'
]
ClassPred _ _ -> go exprs
-- We've found a tuple of evidence.
-- For each field of the tuple we extract it with a case statement, then recurse.
TuplePred preds -> do
trace ("getPredEvidence.go.TP: pred="++dbg pred
++"; origType="++dbg baseTy
++"; exprType="++dbg (exprType expr)
) $ return ()
uniqs <- getUniquesM
traceM $ " tupelems: baseTy="++dbg baseTy++"; preds="++dbg preds
let tupelems =
[ mkLocalVar
VanillaId
(mkSystemName uniq (mkVarOcc $ "a"++show j))
t'
-- (mkAppTy (fst $ splitAppTys t') baseTy)
vanillaIdInfo
| (j,t',uniq) <- zip3 [0..] preds uniqs
]
uniq <- getUniqueM
let wildName = mkSystemName uniq (mkVarOcc "wild")
wildVar = mkLocalVar VanillaId wildName (exprType expr) vanillaIdInfo
let ret =
[ ( Case expr wildVar (varType $ tupelems!!i)
[ ( DataAlt $ tupleCon ConstraintTuple $ length preds
, tupelems
, Var $ tupelems!!i
)
]
, baseTy
)
| (i,t) <- zip [0..] preds
]
sequence_ [ traceM $ " ret!!"++show i++"="++myshow dynFlags (fst $ ret!!i) | i<-[0..length ret-1]]
go $ ret++exprs
-- | Given some evidence, an expression, and a type:
-- try to prove that the expression can be cast to the type.
-- If it can, return the cast expression.
castToType :: [CoreExpr] -> Type -> CoreExpr -> ExceptT ExceptionType CoreM CoreExpr
castToType xs castTy inputExpr = if exprType inputExpr == castTy
then return inputExpr
else go $ prepEvidence xs
-- else go $ catMaybes [ (x, extractBaseTy $ exprType x) | x <- xs ]
where
go :: [(CoreExpr,Type)] -> ExceptT ExceptionType CoreM CoreExpr
-- base case: we've searched through all the evidence, but couldn't create a cast
go [] = throwError $ OtherException $
" WARNING: Could not cast expression of type "++dbg (exprType inputExpr)++" to "++dbg castTy
-- recursively try each evidence expression looking for a cast
go ((expr,baseTy):exprs) = case classifyPredType $ exprType expr of
IrredPred _ -> go exprs
EqPred _ t1 t2 -> trace ("castToType.go.EP: castTy="++dbg castTy
++"; origType="++dbg baseTy
++"; exprType="++dbg (exprType expr)
) $ goEqPred [] castTy (exprType inputExpr)
where
-- Check if a cast is possible.
-- We need to recursively peel off all the type constructors
-- on the inputTyRHS and castTyRHS types.
-- As long as the type constructors match,
-- we might be able to do a cast at any level of the peeling
goEqPred :: [TyCon] -> Type -> Type -> ExceptT ExceptionType CoreM CoreExpr
goEqPred tyCons castTyRHS inputTyRHS = if
| t1==castTyRHS && t2==inputTyRHS -> mkCast True
| t2==castTyRHS && t1==inputTyRHS -> mkCast False
| otherwise -> case ( splitTyConApp_maybe castTyRHS
, splitTyConApp_maybe inputTyRHS
) of
(Just (castTyCon, [castTyRHS']), Just (inputTyCon,[inputTyRHS'])) ->
if castTyCon == inputTyCon
then goEqPred (castTyCon:tyCons) castTyRHS' inputTyRHS'
else go exprs
_ -> go exprs
where
-- Constructs the actual cast from one variable type to another.
--
-- There's some subtle voodoo in here involving GHC's Roles.
-- Basically, everything gets created as a Nominal role,
-- but the final Coercion needs to be Representational.
-- mkSubCo converts from Nominal into Representational.
-- See https://ghc.haskell.org/trac/ghc/wiki/RolesImplementation
mkCast :: Bool -> ExceptT ExceptionType CoreM CoreExpr
mkCast isFlipped = do
coboxUniq <- getUniqueM
let coboxName = mkSystemName coboxUniq (mkVarOcc "cobox")
coboxType = if isFlipped
then mkCoercionType Nominal castTyRHS inputTyRHS
else mkCoercionType Nominal inputTyRHS castTyRHS
coboxVar = mkLocalVar VanillaId coboxName coboxType vanillaIdInfo
-- Reapplies the list of tyCons that we peeled off during the recursion.
let mkCoercion [] = if isFlipped
then mkSymCo $ mkCoVarCo coboxVar
else mkCoVarCo coboxVar
mkCoercion (x:xs) = mkTyConAppCo Nominal x [mkCoercion xs]
wildUniq <- getUniqueM
let wildName = mkSystemName wildUniq (mkVarOcc "wild")
wildType = exprType expr
wildVar = mkLocalVar VanillaId wildName wildType vanillaIdInfo
return $ Case
expr
wildVar
castTy
[ ( DataAlt eqBoxDataCon
, [coboxVar]
, Cast inputExpr $ mkSubCo $ mkCoercion tyCons
) ]
-- FIXME: ClassPred and TuplePred are both handled the same
-- within castToPred and getPredEvidence.
-- They should be factored out?
ClassPred c' [ct] -> go $
exprs++
[ ( App (App (Var selId) (Type baseTy)) expr
, baseTy
)
| selId <- classAllSelIds c'
]
ClassPred _ _ -> go exprs
TuplePred preds -> do
uniqs <- getUniquesM
let tupelems =
[ mkLocalVar
VanillaId
(mkSystemName uniq (mkVarOcc $ "a"++show j))
-- (mkAppTy (fst $ splitAppTys t') baseTy)
t'
vanillaIdInfo
| (j,t',uniq) <- zip3 [0..] preds uniqs
]
uniq <- getUniqueM
let wildName = mkSystemName uniq (mkVarOcc "wild")
wildVar = mkLocalVar VanillaId wildName (exprType expr) vanillaIdInfo
let ret =
[ ( Case expr wildVar (varType $ tupelems!!i)
[ ( DataAlt $ tupleCon ConstraintTuple $ length preds
, tupelems
, Var $ tupelems!!i
)
]
, baseTy
)
| (i,t) <- zip [0..] preds
]
go $ ret++exprs
-- | Each element in the input list must contain evidence of a predicate.
-- The output list contains evidence of a predicate along with a type that will be used for casting.
prepEvidence :: [CoreExpr] -> [(CoreExpr,Type)]
prepEvidence exprs = catMaybes
[ case extractBaseTy $ exprType x of
Just t -> Just (x,t)
Nothing -> Nothing --(x, extractBaseTy $ exprType x)
| x <- exprs
]
where
-- Extracts the type that each of our pieces of evidence is applied to
extractBaseTy :: Type -> Maybe Type
extractBaseTy t = case classifyPredType t of
ClassPred _ [x] -> Just x
EqPred rel t1 t2 -> if
| t1 == boolTy -> Just t2
| t2 == boolTy -> Just t1
| otherwise -> Nothing
_ -> Nothing
-- | Return all the TyVars that occur anywhere in the Type
extractTyVars :: Type -> [TyVar]
extractTyVars t = case getTyVar_maybe t of
Just x -> [x]
Nothing -> case tyConAppArgs_maybe t of
Just xs -> concatMap extractTyVars xs
Nothing -> concatMap extractTyVars $ snd $ splitAppTys t
-- | Given a quantified type of the form:
--
-- > forall a. (Num a, Ord a) => a -> a
--
-- The first element of the returned tuple is the list of quantified variables,
-- and the seecond element is the unquantified type.
extractQuantifiers :: Type -> ([Var],Type)
extractQuantifiers t = case splitForAllTy_maybe t of
Nothing -> ([],t)
Just (a,b) -> (a:as,b')
where
(as,b') = extractQuantifiers b
-- | Given unquantified types of the form:
--
-- > (Num a, Ord a) => a -> a
--
-- The first element of the returned tuple contains everything to the left of "=>";
-- and the second element contains everything to the right.
extractContext :: Type -> ([Type],Type)
extractContext t = case splitTyConApp_maybe t of
Nothing -> ([],t)
Just (tycon,xs) -> if occNameString (nameOccName $ tyConName tycon) /= "(->)"
|| not hasCxt
then ([],t)
else (head xs:cxt',t')
where
(cxt',t') = extractContext $ head $ tail xs
hasCxt = case classifyPredType $ head xs of
IrredPred _ -> False
_ -> True
-- | given a function, get the type of the parameters
--
-- FIXME: this should be deleted
extractParam :: Type -> Maybe Type
extractParam t = case splitTyConApp_maybe t of
Nothing -> Nothing
Just (tycon,xs) -> if occNameString (nameOccName $ tyConName tycon) /= "(->)"
then Just t -- Nothing
else Just (head xs)
-- | Given a type of the form
--
-- > A -> ... -> C
--
-- returns C
getReturnType :: Type -> Type
getReturnType t = case splitForAllTys t of
(_,t') -> go t'
where
go t = case splitTyConApp_maybe t of
Just (tycon,[_,t']) -> if getString tycon=="(->)"
then go t'
else t
_ -> t
--------------------------------------------------------------------------------
--
runTcM :: ModGuts -> TcM a -> CoreM a
runTcM guts tcm = do
env <- getHscEnv
dflags <- getDynFlags
#if __GLASGOW_HASKELL__ < 710 || (__GLASGOW_HASKELL__ == 710 && __GLASGOW_HASKELL_PATCHLEVEL1__ < 2)
(msgs, mr) <- liftIO $ initTc env HsSrcFile False (mg_module guts) tcm
#else
let realSrcSpan = mkRealSrcSpan
(mkRealSrcLoc (mkFastString "a") 0 1)
(mkRealSrcLoc (mkFastString "b") 2 3)
(msgs, mr) <- liftIO $ initTc env HsSrcFile False (mg_module guts) realSrcSpan tcm
#endif
let showMsgs (warns, errs) = showSDoc dflags $ vcat
$ text "Errors:" : pprErrMsgBag errs
++ text "Warnings:" : pprErrMsgBag warns
maybe (fail $ showMsgs msgs) return mr
where
pprErrMsgBag = pprErrMsgBagWithLoc
--------------------------------------------------------------------------------
-- utils
getString :: NamedThing a => a -> String
getString = occNameString . getOccName
expr2str :: DynFlags -> Expr Var -> String
expr2str dflags (Var v) = {-"var_" ++-} var2str v++"_"++showSDoc dflags (ppr $ getUnique v)
expr2str dflags e = "expr_" ++ (decorate $ showSDoc dflags (ppr e))
where
decorate :: String -> String
decorate = map go
where
go x = if not (isAlphaNum x)
then '_'
else x
lit2rational :: Literal -> Rational
lit2rational l = case l of
MachInt i -> toRational i
MachInt64 i -> toRational i
MachWord i -> toRational i
MachWord64 i -> toRational i
MachFloat r -> r
MachDouble r -> r
LitInteger i _ -> toRational i
var2str :: Var -> String
var2str = occNameString . occName . varName
maybeHead :: [a] -> Maybe a
maybeHead (a:_) = Just a
maybeHead _ = Nothing
myshow :: DynFlags -> Expr Var -> String
myshow dflags = go 1
where
go i (Var v) = "Var "++showSDoc dflags (ppr v)
++"_"++showSDoc dflags (ppr $ getUnique v)
++"::"++showSDoc dflags (ppr $ varType v)
go i (Lit (MachFloat l )) = "FloatLiteral " ++show (fromRational l :: Double)
go i (Lit (MachDouble l )) = "DoubleLiteral " ++show (fromRational l :: Double)
go i (Lit (MachInt l )) = "IntLiteral " ++show (fromIntegral l :: Double)
go i (Lit (MachInt64 l )) = "Int64Literal " ++show (fromIntegral l :: Double)
go i (Lit (MachWord l )) = "WordLiteral " ++show (fromIntegral l :: Double)
go i (Lit (MachWord64 l )) = "Word64Literal " ++show (fromIntegral l :: Double)
go i (Lit (LitInteger l t)) = "IntegerLiteral "++show (fromIntegral l :: Double)++
"::"++showSDoc dflags (ppr t)
go i (Lit l) = "Lit"
go i (Type t) = "Type "++showSDoc dflags (ppr t)
go i (Tick a b) = "Tick (" ++ show a ++ ") ("++go (i+1) b++")"
go i (Coercion l) = "Coercion "++myCoercionShow dflags l
go i (Cast a b)
= "Cast \n"
++white++"(" ++ go (i+1) a ++ ")\n"
++white++"("++myshow dflags (Coercion b)++")\n"
++drop 4 white
where
white=replicate (4*i) ' '
go i (Let (NonRec a e) b)
= "Let "++getString a++"_"++showSDoc dflags (ppr $ getUnique a)
++"::"++showSDoc dflags (ppr $ varType a)++"\n"
++white++"("++go (i+1) e++")\n"
++white++"("++go (i+1) b++")\n"
++drop 4 white
where
white=replicate (4*i) ' '
go i (Let _ _) = error "myshow: recursive let"
go i (Lam a b)
= "Lam "++getString a++"_"++showSDoc dflags (ppr $ getUnique a)
++"::"++showSDoc dflags (ppr $ varType a)
++"; coercion="++show (isCoVar a)++"\n"
++white++"("++go (i+1) b++")\n"
++drop 4 white
where
white=replicate (4*i) ' '
go i (App a b)
= "App\n"
++white++"(" ++ go (i+1) a ++ ")\n"
++white++"("++go (i+1) b++")\n"
++drop 4 white
where
white=replicate (4*i) ' '
go i (Case a b c d)
= "Case\n"
++white++"("++go (i+1) a++")\n"
++white++"("++getString b++"_"++showSDoc dflags (ppr $ getUnique b)
++"::"++showSDoc dflags (ppr $ varType b)++")\n"
++white++"("++showSDoc dflags (ppr c)++"; "++show (fmap (myshow dflags . Var) $ getTyVar_maybe c)++")\n"
++white++"["++concatMap altShow d++"]\n"
++drop 4 white
where
white=replicate (4*i) ' '
altShow :: Alt Var -> String
altShow (con,xs,expr) = "("++con'++", "++xs'++", "++go (i+1) expr++")\n"++white
where
con' = case con of
DataAlt x -> showSDoc dflags (ppr x)
LitAlt x -> showSDoc dflags (ppr x)
DEFAULT -> "DEFAULT"
xs' = show $ map (myshow dflags . Var) xs
myCoercionShow :: DynFlags -> Coercion -> String
myCoercionShow dflags c = go c
where
go (Refl _ _ ) = "Refl"
go (TyConAppCo a b c ) = "TyConAppCo "++showSDoc dflags (ppr a)++" "
++showSDoc dflags (ppr b)++" "
++showSDoc dflags (ppr c)
go (AppCo _ _ ) = "AppCo"
go (ForAllCo _ _ ) = "ForAllCo"
go (CoVarCo v ) = "CoVarCo ("++myshow dflags (Var v)++")"
go (AxiomInstCo _ _ _ ) = "AxiomInstCo"
go (UnivCo _ _ _ _ ) = "UnivCo"
go (SymCo c' ) = "SymCo ("++myCoercionShow dflags c'++")"
go (TransCo _ _ ) = "TransCo"
go (AxiomRuleCo _ _ _ ) = "AxiomRuleCo"
go (NthCo _ _ ) = "NthCo"
go (LRCo _ _ ) = "LRCo"
go (InstCo _ _ ) = "InstCo"
go (SubCo c' ) = "SubCo ("++myCoercionShow dflags c'++")"
-- instance Show (Coercion) where
-- show _ = "Coercion"
--
-- instance Show b => Show (Bind b) where
-- show _ = "Bind"
--
-- instance Show (Tickish Id) where
-- show _ = "(Tickish Id)"
--
-- instance Show Type where
-- show _ = "Type"
--
-- instance Show AltCon where
-- show _ = "AltCon"
--
-- instance Show Var where
-- show v = getString v
| mikeizbicki/HerbiePlugin | src/Herbie/CoreManip.hs | bsd-3-clause | 25,417 | 0 | 30 | 9,974 | 6,020 | 3,037 | 2,983 | -1 | -1 |
-- Library for printing an animated AURA version message.
{-
Copyright 2012, 2013, 2014 Colin Woodbury <colingw@gmail.com>
This file is part of Aura.
Aura 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.
Aura 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 Aura. If not, see <http://www.gnu.org/licenses/>.
-}
module Aura.Logo where
import Control.Concurrent (threadDelay)
import System.IO (stdout, hFlush)
import Aura.Colour.Text (yellow)
import Utilities (prePad)
import Shell (cursorUpLineCode)
---
data MouthState = Open | Closed deriving (Eq)
-- Taken from: figlet -f small "aura"
auraLogo :: String
auraLogo = " __ _ _ _ _ _ __ _ \n" ++
"/ _` | || | '_/ _` |\n" ++
"\\__,_|\\_,_|_| \\__,_|"
openMouth :: [String]
openMouth = map yellow
[ " .--."
, "/ _.-'"
, "\\ '-."
, " '--'" ]
closedMouth :: [String]
closedMouth = map yellow
[ " .--."
, "/ _..\\"
, "\\ ''/"
, " '--'" ]
pill :: [String]
pill = [ ""
, ".-."
, "'-'"
, "" ]
takeABite :: Int -> IO ()
takeABite pad = drawMouth Closed >> drawMouth Open
where drawMouth mouth = do
mapM_ putStrLn $ renderPacmanHead pad mouth
raiseCursorBy 4
hFlush stdout
threadDelay 125000
drawPills :: Int -> IO ()
drawPills numOfPills = mapM_ putStrLn pills
where pills = renderPills numOfPills
raiseCursorBy :: Int -> IO ()
raiseCursorBy = putStr . raiseCursorBy'
raiseCursorBy' :: Int -> String
raiseCursorBy' = cursorUpLineCode
clearGrid :: IO ()
clearGrid = putStr blankLines >> raiseCursorBy 4
where blankLines = concat . replicate 4 . padString 23 $ "\n"
renderPill :: Int -> [String]
renderPill pad = map (padString pad) pill
renderPills :: Int -> [String]
renderPills numOfPills = take numOfPills pillPostitions >>= render
where pillPostitions = [17,12,7]
render pos = renderPill pos ++ [raiseCursorBy' 5]
renderPacmanHead :: Int -> MouthState -> [String]
renderPacmanHead pad Open = map (padString pad) openMouth
renderPacmanHead pad Closed = map (padString pad) closedMouth
padString :: Int -> String -> String
padString pad cs = prePad cs ' ' (pad + length cs)
| joehillen/aura | src/Aura/Logo.hs | gpl-3.0 | 2,722 | 0 | 10 | 687 | 574 | 305 | 269 | 56 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.SNS.ListSubscriptionsByTopic
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Returns a list of the subscriptions to a specific topic. Each call returns a
-- limited list of subscriptions, up to 100. If there are more subscriptions, a 'NextToken' is also returned. Use the 'NextToken' parameter in a new 'ListSubscriptionsByTopic' call to get further results.
--
-- <http://docs.aws.amazon.com/sns/latest/api/API_ListSubscriptionsByTopic.html>
module Network.AWS.SNS.ListSubscriptionsByTopic
(
-- * Request
ListSubscriptionsByTopic
-- ** Request constructor
, listSubscriptionsByTopic
-- ** Request lenses
, lsbtNextToken
, lsbtTopicArn
-- * Response
, ListSubscriptionsByTopicResponse
-- ** Response constructor
, listSubscriptionsByTopicResponse
-- ** Response lenses
, lsbtrNextToken
, lsbtrSubscriptions
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.SNS.Types
import qualified GHC.Exts
data ListSubscriptionsByTopic = ListSubscriptionsByTopic
{ _lsbtNextToken :: Maybe Text
, _lsbtTopicArn :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'ListSubscriptionsByTopic' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lsbtNextToken' @::@ 'Maybe' 'Text'
--
-- * 'lsbtTopicArn' @::@ 'Text'
--
listSubscriptionsByTopic :: Text -- ^ 'lsbtTopicArn'
-> ListSubscriptionsByTopic
listSubscriptionsByTopic p1 = ListSubscriptionsByTopic
{ _lsbtTopicArn = p1
, _lsbtNextToken = Nothing
}
-- | Token returned by the previous 'ListSubscriptionsByTopic' request.
lsbtNextToken :: Lens' ListSubscriptionsByTopic (Maybe Text)
lsbtNextToken = lens _lsbtNextToken (\s a -> s { _lsbtNextToken = a })
-- | The ARN of the topic for which you wish to find subscriptions.
lsbtTopicArn :: Lens' ListSubscriptionsByTopic Text
lsbtTopicArn = lens _lsbtTopicArn (\s a -> s { _lsbtTopicArn = a })
data ListSubscriptionsByTopicResponse = ListSubscriptionsByTopicResponse
{ _lsbtrNextToken :: Maybe Text
, _lsbtrSubscriptions :: List "member" Subscription
} deriving (Eq, Read, Show)
-- | 'ListSubscriptionsByTopicResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lsbtrNextToken' @::@ 'Maybe' 'Text'
--
-- * 'lsbtrSubscriptions' @::@ ['Subscription']
--
listSubscriptionsByTopicResponse :: ListSubscriptionsByTopicResponse
listSubscriptionsByTopicResponse = ListSubscriptionsByTopicResponse
{ _lsbtrSubscriptions = mempty
, _lsbtrNextToken = Nothing
}
-- | Token to pass along to the next 'ListSubscriptionsByTopic' request. This
-- element is returned if there are more subscriptions to retrieve.
lsbtrNextToken :: Lens' ListSubscriptionsByTopicResponse (Maybe Text)
lsbtrNextToken = lens _lsbtrNextToken (\s a -> s { _lsbtrNextToken = a })
-- | A list of subscriptions.
lsbtrSubscriptions :: Lens' ListSubscriptionsByTopicResponse [Subscription]
lsbtrSubscriptions =
lens _lsbtrSubscriptions (\s a -> s { _lsbtrSubscriptions = a })
. _List
instance ToPath ListSubscriptionsByTopic where
toPath = const "/"
instance ToQuery ListSubscriptionsByTopic where
toQuery ListSubscriptionsByTopic{..} = mconcat
[ "NextToken" =? _lsbtNextToken
, "TopicArn" =? _lsbtTopicArn
]
instance ToHeaders ListSubscriptionsByTopic
instance AWSRequest ListSubscriptionsByTopic where
type Sv ListSubscriptionsByTopic = SNS
type Rs ListSubscriptionsByTopic = ListSubscriptionsByTopicResponse
request = post "ListSubscriptionsByTopic"
response = xmlResponse
instance FromXML ListSubscriptionsByTopicResponse where
parseXML = withElement "ListSubscriptionsByTopicResult" $ \x -> ListSubscriptionsByTopicResponse
<$> x .@? "NextToken"
<*> x .@? "Subscriptions" .!@ mempty
instance AWSPager ListSubscriptionsByTopic where
page rq rs
| stop (rs ^. lsbtrNextToken) = Nothing
| otherwise = (\x -> rq & lsbtNextToken ?~ x)
<$> (rs ^. lsbtrNextToken)
| romanb/amazonka | amazonka-sns/gen/Network/AWS/SNS/ListSubscriptionsByTopic.hs | mpl-2.0 | 5,055 | 0 | 12 | 1,023 | 642 | 379 | 263 | 72 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | Auxiliary definitions for 'Semigroup'
--
-- This module provides some @newtype@ wrappers and helpers which are
-- reexported from the "Data.Semigroup" module or imported directly
-- by some other modules.
--
-- This module also provides internal definitions related to the
-- 'Semigroup' class some.
--
-- This module exists mostly to simplify or workaround import-graph
-- issues; there is also a .hs-boot file to allow "GHC.Base" and other
-- modules to import method default implementations for 'stimes'
--
-- @since 4.11.0.0
module Data.Semigroup.Internal where
import GHC.Base hiding (Any)
import GHC.Enum
import GHC.Num
import GHC.Read
import GHC.Show
import GHC.Generics
import GHC.Real
-- | This is a valid definition of 'stimes' for an idempotent 'Semigroup'.
--
-- When @x <> x = x@, this definition should be preferred, because it
-- works in \(\mathcal{O}(1)\) rather than \(\mathcal{O}(\log n)\).
stimesIdempotent :: Integral b => b -> a -> a
stimesIdempotent n x
| n <= 0 = errorWithoutStackTrace "stimesIdempotent: positive multiplier expected"
| otherwise = x
-- | This is a valid definition of 'stimes' for an idempotent 'Monoid'.
--
-- When @mappend x x = x@, this definition should be preferred, because it
-- works in \(\mathcal{O}(1)\) rather than \(\mathcal{O}(\log n)\)
stimesIdempotentMonoid :: (Integral b, Monoid a) => b -> a -> a
stimesIdempotentMonoid n x = case compare n 0 of
LT -> errorWithoutStackTrace "stimesIdempotentMonoid: negative multiplier"
EQ -> mempty
GT -> x
-- | This is a valid definition of 'stimes' for a 'Monoid'.
--
-- Unlike the default definition of 'stimes', it is defined for 0
-- and so it should be preferred where possible.
stimesMonoid :: (Integral b, Monoid a) => b -> a -> a
stimesMonoid n x0 = case compare n 0 of
LT -> errorWithoutStackTrace "stimesMonoid: negative multiplier"
EQ -> mempty
GT -> f x0 n
where
f x y
| even y = f (x `mappend` x) (y `quot` 2)
| y == 1 = x
| otherwise = g (x `mappend` x) (y `quot` 2) x -- See Note [Half of y - 1]
g x y z
| even y = g (x `mappend` x) (y `quot` 2) z
| y == 1 = x `mappend` z
| otherwise = g (x `mappend` x) (y `quot` 2) (x `mappend` z) -- See Note [Half of y - 1]
-- this is used by the class definitionin GHC.Base;
-- it lives here to avoid cycles
stimesDefault :: (Integral b, Semigroup a) => b -> a -> a
stimesDefault y0 x0
| y0 <= 0 = errorWithoutStackTrace "stimes: positive multiplier expected"
| otherwise = f x0 y0
where
f x y
| even y = f (x <> x) (y `quot` 2)
| y == 1 = x
| otherwise = g (x <> x) (y `quot` 2) x -- See Note [Half of y - 1]
g x y z
| even y = g (x <> x) (y `quot` 2) z
| y == 1 = x <> z
| otherwise = g (x <> x) (y `quot` 2) (x <> z) -- See Note [Half of y - 1]
{- Note [Half of y - 1]
~~~~~~~~~~~~~~~~~~~~~
Since y is guaranteed to be odd and positive here,
half of y - 1 can be computed as y `quot` 2, optimising subtraction away.
-}
stimesMaybe :: (Integral b, Semigroup a) => b -> Maybe a -> Maybe a
stimesMaybe _ Nothing = Nothing
stimesMaybe n (Just a) = case compare n 0 of
LT -> errorWithoutStackTrace "stimes: Maybe, negative multiplier"
EQ -> Nothing
GT -> Just (stimes n a)
stimesList :: Integral b => b -> [a] -> [a]
stimesList n x
| n < 0 = errorWithoutStackTrace "stimes: [], negative multiplier"
| otherwise = rep n
where
rep 0 = []
rep i = x ++ rep (i - 1)
-- | The dual of a 'Monoid', obtained by swapping the arguments of 'mappend'.
--
-- >>> getDual (mappend (Dual "Hello") (Dual "World"))
-- "WorldHello"
newtype Dual a = Dual { getDual :: a }
deriving ( Eq -- ^ @since 2.01
, Ord -- ^ @since 2.01
, Read -- ^ @since 2.01
, Show -- ^ @since 2.01
, Bounded -- ^ @since 2.01
, Generic -- ^ @since 4.7.0.0
, Generic1 -- ^ @since 4.7.0.0
)
-- | @since 4.9.0.0
instance Semigroup a => Semigroup (Dual a) where
Dual a <> Dual b = Dual (b <> a)
stimes n (Dual a) = Dual (stimes n a)
-- | @since 2.01
instance Monoid a => Monoid (Dual a) where
mempty = Dual mempty
-- | @since 4.8.0.0
instance Functor Dual where
fmap = coerce
-- | @since 4.8.0.0
instance Applicative Dual where
pure = Dual
(<*>) = coerce
-- | @since 4.8.0.0
instance Monad Dual where
m >>= k = k (getDual m)
-- | The monoid of endomorphisms under composition.
--
-- >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!")
-- >>> appEndo computation "Haskell"
-- "Hello, Haskell!"
newtype Endo a = Endo { appEndo :: a -> a }
deriving ( Generic -- ^ @since 4.7.0.0
)
-- | @since 4.9.0.0
instance Semigroup (Endo a) where
(<>) = coerce ((.) :: (a -> a) -> (a -> a) -> (a -> a))
stimes = stimesMonoid
-- | @since 2.01
instance Monoid (Endo a) where
mempty = Endo id
-- | Boolean monoid under conjunction ('&&').
--
-- >>> getAll (All True <> mempty <> All False)
-- False
--
-- >>> getAll (mconcat (map (\x -> All (even x)) [2,4,6,7,8]))
-- False
newtype All = All { getAll :: Bool }
deriving ( Eq -- ^ @since 2.01
, Ord -- ^ @since 2.01
, Read -- ^ @since 2.01
, Show -- ^ @since 2.01
, Bounded -- ^ @since 2.01
, Generic -- ^ @since 4.7.0.0
)
-- | @since 4.9.0.0
instance Semigroup All where
(<>) = coerce (&&)
stimes = stimesIdempotentMonoid
-- | @since 2.01
instance Monoid All where
mempty = All True
-- | Boolean monoid under disjunction ('||').
--
-- >>> getAny (Any True <> mempty <> Any False)
-- True
--
-- >>> getAny (mconcat (map (\x -> Any (even x)) [2,4,6,7,8]))
-- True
newtype Any = Any { getAny :: Bool }
deriving ( Eq -- ^ @since 2.01
, Ord -- ^ @since 2.01
, Read -- ^ @since 2.01
, Show -- ^ @since 2.01
, Bounded -- ^ @since 2.01
, Generic -- ^ @since 4.7.0.0
)
-- | @since 4.9.0.0
instance Semigroup Any where
(<>) = coerce (||)
stimes = stimesIdempotentMonoid
-- | @since 2.01
instance Monoid Any where
mempty = Any False
-- | Monoid under addition.
--
-- >>> getSum (Sum 1 <> Sum 2 <> mempty)
-- 3
newtype Sum a = Sum { getSum :: a }
deriving ( Eq -- ^ @since 2.01
, Ord -- ^ @since 2.01
, Read -- ^ @since 2.01
, Show -- ^ @since 2.01
, Bounded -- ^ @since 2.01
, Generic -- ^ @since 4.7.0.0
, Generic1 -- ^ @since 4.7.0.0
, Num -- ^ @since 4.7.0.0
)
-- | @since 4.9.0.0
instance Num a => Semigroup (Sum a) where
(<>) = coerce ((+) :: a -> a -> a)
stimes n (Sum a) = Sum (fromIntegral n * a)
-- | @since 2.01
instance Num a => Monoid (Sum a) where
mempty = Sum 0
-- | @since 4.8.0.0
instance Functor Sum where
fmap = coerce
-- | @since 4.8.0.0
instance Applicative Sum where
pure = Sum
(<*>) = coerce
-- | @since 4.8.0.0
instance Monad Sum where
m >>= k = k (getSum m)
-- | Monoid under multiplication.
--
-- >>> getProduct (Product 3 <> Product 4 <> mempty)
-- 12
newtype Product a = Product { getProduct :: a }
deriving ( Eq -- ^ @since 2.01
, Ord -- ^ @since 2.01
, Read -- ^ @since 2.01
, Show -- ^ @since 2.01
, Bounded -- ^ @since 2.01
, Generic -- ^ @since 4.7.0.0
, Generic1 -- ^ @since 4.7.0.0
, Num -- ^ @since 4.7.0.0
)
-- | @since 4.9.0.0
instance Num a => Semigroup (Product a) where
(<>) = coerce ((*) :: a -> a -> a)
stimes n (Product a) = Product (a ^ n)
-- | @since 2.01
instance Num a => Monoid (Product a) where
mempty = Product 1
-- | @since 4.8.0.0
instance Functor Product where
fmap = coerce
-- | @since 4.8.0.0
instance Applicative Product where
pure = Product
(<*>) = coerce
-- | @since 4.8.0.0
instance Monad Product where
m >>= k = k (getProduct m)
-- | Monoid under '<|>'.
--
-- >>> getAlt (Alt (Just 12) <> Alt (Just 24))
-- Just 12
--
-- >>> getAlt $ Alt Nothing <> Alt (Just 24)
-- Just 24
--
-- @since 4.8.0.0
newtype Alt f a = Alt {getAlt :: f a}
deriving ( Generic -- ^ @since 4.8.0.0
, Generic1 -- ^ @since 4.8.0.0
, Read -- ^ @since 4.8.0.0
, Show -- ^ @since 4.8.0.0
, Eq -- ^ @since 4.8.0.0
, Ord -- ^ @since 4.8.0.0
, Num -- ^ @since 4.8.0.0
, Enum -- ^ @since 4.8.0.0
, Monad -- ^ @since 4.8.0.0
, MonadPlus -- ^ @since 4.8.0.0
, Applicative -- ^ @since 4.8.0.0
, Alternative -- ^ @since 4.8.0.0
, Functor -- ^ @since 4.8.0.0
)
-- | @since 4.9.0.0
instance Alternative f => Semigroup (Alt f a) where
(<>) = coerce ((<|>) :: f a -> f a -> f a)
stimes = stimesMonoid
-- | @since 4.8.0.0
instance Alternative f => Monoid (Alt f a) where
mempty = Alt empty
| sdiehl/ghc | libraries/base/Data/Semigroup/Internal.hs | bsd-3-clause | 9,669 | 0 | 13 | 3,096 | 2,117 | 1,181 | 936 | 171 | 3 |
module Records where
data Person1 = Person1 String String Int
data Person2 = Person2 { fname :: String, sname :: String, age :: Int }
data Person3 = Person3 { slot3 :: String, slot2 :: String, slot1 :: Int }
p1 = Person1 "Chris" "Done" 13
p2 = Person2 "Chris" "Done" 13
p2a = Person2 { fname = "Chris", sname = "Done", age = 13 }
p3 = Person3 "Chris" "Done" 13
main = do
putStrLn (case p1 of Person1 "Chris" "Done" 13 -> "Hello!")
putStrLn (case p2 of Person2 "Chris" "Done" 13 -> "Hello!")
putStrLn (case p2a of Person2 "Chris" "Done" 13 -> "Hello!")
putStrLn (case p3 of Person3 "Chris" "Done" 13 -> "Hello!")
| fpco/fay | tests/records.hs | bsd-3-clause | 626 | 0 | 12 | 129 | 241 | 129 | 112 | 13 | 1 |
module Tests.Shared (tests) where
import Text.Pandoc.Definition
import Text.Pandoc.Shared
import Test.Framework
import Tests.Helpers
import Tests.Arbitrary()
import Test.Framework.Providers.HUnit
import Test.HUnit ( assertBool, (@?=) )
import Text.Pandoc.Builder
import System.FilePath.Posix (joinPath)
tests :: [Test]
tests = [ testGroup "normalize"
[ property "p_normalize_blocks_rt" p_normalize_blocks_rt
, property "p_normalize_inlines_rt" p_normalize_inlines_rt
, property "p_normalize_no_trailing_spaces"
p_normalize_no_trailing_spaces
]
, testGroup "compactify'DL"
[ testCase "compactify'DL with empty def" $
assertBool "compactify'DL"
(let x = [(str "word", [para (str "def"), mempty])]
in compactify'DL x == x)
]
, testGroup "collapseFilePath" testCollapse
]
p_normalize_blocks_rt :: [Block] -> Bool
p_normalize_blocks_rt bs =
normalizeBlocks bs == normalizeBlocks (normalizeBlocks bs)
p_normalize_inlines_rt :: [Inline] -> Bool
p_normalize_inlines_rt ils =
normalizeInlines ils == normalizeInlines (normalizeInlines ils)
p_normalize_no_trailing_spaces :: [Inline] -> Bool
p_normalize_no_trailing_spaces ils = null ils' || last ils' /= Space
where ils' = normalizeInlines $ ils ++ [Space]
testCollapse :: [Test]
testCollapse = map (testCase "collapse")
[ (collapseFilePath (joinPath [ ""]) @?= (joinPath [ ""]))
, (collapseFilePath (joinPath [ ".","foo"]) @?= (joinPath [ "foo"]))
, (collapseFilePath (joinPath [ ".",".","..","foo"]) @?= (joinPath [ joinPath ["..", "foo"]]))
, (collapseFilePath (joinPath [ "..","foo"]) @?= (joinPath [ "..","foo"]))
, (collapseFilePath (joinPath [ "","bar","..","baz"]) @?= (joinPath [ "","baz"]))
, (collapseFilePath (joinPath [ "","..","baz"]) @?= (joinPath [ "","..","baz"]))
, (collapseFilePath (joinPath [ ".","foo","..",".","bar","..",".",".","baz"]) @?= (joinPath [ "baz"]))
, (collapseFilePath (joinPath [ ".",""]) @?= (joinPath [ ""]))
, (collapseFilePath (joinPath [ ".",".",""]) @?= (joinPath [ ""]))
, (collapseFilePath (joinPath [ "..",""]) @?= (joinPath [ ".."]))
, (collapseFilePath (joinPath [ "..",".",""]) @?= (joinPath [ ".."]))
, (collapseFilePath (joinPath [ ".","..",""]) @?= (joinPath [ ".."]))
, (collapseFilePath (joinPath [ "..","..",""]) @?= (joinPath [ "..",".."]))
, (collapseFilePath (joinPath [ "parent","foo","baz","..","bar"]) @?= (joinPath [ "parent","foo","bar"]))
, (collapseFilePath (joinPath [ "parent","foo","baz","..","..","bar"]) @?= (joinPath [ "parent","bar"]))
, (collapseFilePath (joinPath [ "parent","foo",".."]) @?= (joinPath [ "parent"]))
, (collapseFilePath (joinPath [ "","parent","foo","..","..","bar"]) @?= (joinPath [ "","bar"]))
, (collapseFilePath (joinPath [ "",".","parent","foo"]) @?= (joinPath [ "","parent","foo"]))]
| janschulz/pandoc | tests/Tests/Shared.hs | gpl-2.0 | 2,911 | 0 | 20 | 493 | 1,093 | 619 | 474 | 51 | 1 |
import Control.Concurrent
import Control.Exception
-- <<main
main = do
lock <- newEmptyMVar
complete <- newEmptyMVar
forkIO $ takeMVar lock `finally` putMVar complete ()
takeMVar complete
-- >>
| prt2121/haskell-practice | parconc/deadlock1.hs | apache-2.0 | 203 | 0 | 9 | 36 | 61 | 30 | 31 | 7 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sk-SK">
<title>WebSockets | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | ccgreen13/zap-extensions | src/org/zaproxy/zap/extension/websocket/resources/help_sk_SK/helpset_sk_SK.hs | apache-2.0 | 972 | 80 | 66 | 159 | 413 | 209 | 204 | -1 | -1 |
module Idris.ASTUtils(Field(), cg_usedpos, ctxt_lookup, fgetState, fmodifyState,
fputState, idris_fixities, ist_callgraph, ist_optimisation,
known_classes, known_terms, opt_detaggable, opt_inaccessible,
opts_idrisCmdline, repl_definitions) where
-- This implements just a few basic lens-like concepts to ease state updates.
-- Similar to fclabels in approach, just without the extra dependency.
--
-- We don't include an explicit export list
-- because everything here is meant to be exported.
--
-- Short synopsis:
-- ---------------
--
-- f :: Idris ()
-- f = do
-- -- these two steps:
-- detaggable <- fgetState (opt_detaggable . ist_optimisation typeName)
-- fputState (opt_detaggable . ist_optimisation typeName) (not detaggable)
--
-- -- are equivalent to:
-- fmodifyState (opt_detaggable . ist_optimisation typeName) not
--
-- -- of course, the long accessor can be put in a variable;
-- -- everything is first-class
-- let detag n = opt_detaggable . ist_optimisation n
-- fputState (detag n1) True
-- fputState (detag n2) False
--
-- -- Note that all these operations handle missing items consistently
-- -- and transparently, as prescribed by the default values included
-- -- in the definitions of the ist_* functions.
-- --
-- -- Especially, it's no longer necessary to have initial values of
-- -- data structures copied (possibly inconsistently) all over the compiler.
import Control.Category
import Control.Applicative
import Control.Monad.State.Class
import Data.Maybe
import Prelude hiding (id, (.))
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.AbsSyntaxTree
data Field rec fld = Field
{ fget :: rec -> fld
, fset :: fld -> rec -> rec
}
fmodify :: Field rec fld -> (fld -> fld) -> rec -> rec
fmodify field f x = fset field (f $ fget field x) x
instance Category Field where
id = Field id const
Field g2 s2 . Field g1 s1 = Field (g2 . g1) (\v2 x1 -> s1 (s2 v2 $ g1 x1) x1)
fgetState :: MonadState s m => Field s a -> m a
fgetState field = gets $ fget field
fputState :: MonadState s m => Field s a -> a -> m ()
fputState field x = fmodifyState field (const x)
fmodifyState :: MonadState s m => Field s a -> (a -> a) -> m ()
fmodifyState field f = modify $ fmodify field f
-- Exact-name context lookup; uses Nothing for deleted values (read+write!).
--
-- Reading a non-existing value yields Nothing,
-- writing Nothing deletes the value (if it existed).
ctxt_lookup :: Name -> Field (Ctxt a) (Maybe a)
ctxt_lookup n = Field
{ fget = lookupCtxtExact n
, fset = \newVal -> case newVal of
Just x -> addDef n x
Nothing -> deleteDefExact n
}
-- Maybe-lens with a default value.
maybe_default :: a -> Field (Maybe a) a
maybe_default dflt = Field (fromMaybe dflt) (const . Just)
-----------------------------------
-- Individual records and fields --
-----------------------------------
--
-- These could probably be generated; let's use lazy addition for now.
--
-- OptInfo
----------
-- the optimisation record for the given (exact) name
ist_optimisation :: Name -> Field IState OptInfo
ist_optimisation n =
maybe_default Optimise
{ inaccessible = []
, detaggable = False
}
. ctxt_lookup n
. Field idris_optimisation (\v ist -> ist{ idris_optimisation = v })
-- two fields of the optimisation record
opt_inaccessible :: Field OptInfo [(Int, Name)]
opt_inaccessible = Field inaccessible (\v opt -> opt{ inaccessible = v })
opt_detaggable :: Field OptInfo Bool
opt_detaggable = Field detaggable (\v opt -> opt{ detaggable = v })
-- CGInfo
---------
-- callgraph record for the given (exact) name
ist_callgraph :: Name -> Field IState CGInfo
ist_callgraph n =
maybe_default CGInfo
{ argsdef = [], calls = [], scg = []
, argsused = [], usedpos = []
}
. ctxt_lookup n
. Field idris_callgraph (\v ist -> ist{ idris_callgraph = v })
-- some fields of the CGInfo record
cg_usedpos :: Field CGInfo [(Int, [UsageReason])]
cg_usedpos = Field usedpos (\v cg -> cg{ usedpos = v })
-- Commandline flags
--------------------
opts_idrisCmdline :: Field IState [Opt]
opts_idrisCmdline =
Field opt_cmdline (\v opts -> opts{ opt_cmdline = v })
. Field idris_options (\v ist -> ist{ idris_options = v })
-- TT Context
-------------
-- This has a terrible name, but I'm not sure of a better one that isn't
-- confusingly close to tt_ctxt
known_terms :: Field IState (Ctxt (Def, Accessibility, Totality, MetaInformation))
known_terms = Field (definitions . tt_ctxt)
(\v state -> state {tt_ctxt = (tt_ctxt state) {definitions = v}})
known_classes :: Field IState (Ctxt ClassInfo)
known_classes = Field idris_classes (\v state -> state {idris_classes = idris_classes state})
-- Names defined at the repl
----------------------------
repl_definitions :: Field IState [Name]
repl_definitions = Field idris_repl_defs (\v state -> state {idris_repl_defs = v})
-- Fixity declarations in an IState
idris_fixities :: Field IState [FixDecl]
idris_fixities = Field idris_infixes (\v state -> state {idris_infixes = v})
| Enamex/Idris-dev | src/Idris/ASTUtils.hs | bsd-3-clause | 5,245 | 0 | 12 | 1,124 | 1,207 | 682 | 525 | 69 | 2 |
{-# LANGUAGE GADTs, KindSignatures, PatternSynonyms #-}
module ShouldCompile where
data X :: (* -> *) -> * -> * where
Y :: (Show a) => f a -> X f (Maybe a)
pattern C :: (Show (a, Bool)) => a -> X Maybe (Maybe (a, Bool))
pattern C x = Y (Just (x, True))
| wxwxwwxxx/ghc | testsuite/tests/patsyn/should_compile/T8968-2.hs | bsd-3-clause | 257 | 0 | 11 | 58 | 128 | 70 | 58 | -1 | -1 |
-- !!! Malformed lhs (pointless but legal in Haskell 1.3, rejected by Hugs)
module M where
x = let [] = "a" in 'a'
| siddhanathan/ghc | testsuite/tests/module/mod65.hs | bsd-3-clause | 115 | 0 | 9 | 24 | 24 | 13 | 11 | 2 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
--------------------------------------------------------------------------------
-- |
-- Module : Network.MQTT.Broker.Server
-- Copyright : (c) Lars Petersen 2016
-- License : MIT
--
-- Maintainer : info@lars-petersen.net
-- Stability : experimental
--------------------------------------------------------------------------------
module Network.MQTT.Broker.Server
( serveConnection
, MqttServerTransportStack (..)
) where
import Control.Concurrent
import Control.Concurrent.Async
import qualified Control.Exception as E
import Control.Monad
import qualified Data.Binary.Get as SG
import qualified Data.ByteString as BS
import Data.Int
import Data.IORef
import qualified Data.Sequence as Seq
import Data.Typeable
import qualified Networking as SS
import qualified Network.MQTT.Broker as Broker
import Network.MQTT.Broker.Authentication
import qualified Network.MQTT.Broker.Internal as Session
import qualified Network.MQTT.Broker.Session as Session
import qualified Network.MQTT.Broker.Session.Statistic as Session
import Network.MQTT.Message
data MqttServerException
= ProtocolViolation String
| MessageTooLong
| ConnectionRejected RejectReason
| KeepAliveTimeoutException
deriving (Eq, Ord, Show, Typeable)
instance E.Exception MqttServerException
class MqttServerTransportStack a where
getConnectionRequest :: SS.ConnectionInfo a -> IO ConnectionRequest
sendMessage :: SS.StreamOriented t => SS.Connection t -> ServerPacket -> IO Int64
sendMessage connection = do
SS.sendChunkBuilder connection 8192 . serverPacketBuilder
sendMessages :: SS.StreamOriented t => SS.Connection t -> Seq.Seq ServerPacket -> IO Int64
sendMessages connection msgs = do
SS.sendChunkBuilder connection 8192 $ foldl (\b m-> b `mappend` serverPacketBuilder m) mempty msgs
receiveMessage :: SS.StreamOriented t => SS.Connection t -> Int64 -> MVar BS.ByteString -> IO ClientPacket
receiveMessage connection maxMsgSize leftover =
modifyMVar leftover (execute 0 . SG.pushChunk decode)
where
fetch = SS.receiveChunk connection 4096
decode = SG.runGetIncremental clientPacketParser
execute received result
| received > maxMsgSize = E.throwIO MessageTooLong
| otherwise = case result of
SG.Partial continuation -> do
bs <- fetch
if BS.null bs
then execute received (continuation Nothing)
else execute (received + fromIntegral (BS.length bs)) (continuation $ Just bs)
SG.Fail _ _ failure ->
E.throwIO (ProtocolViolation failure)
SG.Done leftover' _ msg ->
pure (leftover', msg)
consumeMessages :: SS.StreamOriented t => SS.Connection t -> Int64 -> MVar BS.ByteString -> (ClientPacket -> IO Bool) -> IO ()
consumeMessages connection maxMsgSize leftover consume =
modifyMVar_ leftover (execute 0 . SG.pushChunk decode)
where
fetch = SS.receiveChunk connection 4096
decode = SG.runGetIncremental clientPacketParser
execute received result
| received > maxMsgSize = E.throwIO MessageTooLong
| otherwise = case result of
SG.Partial continuation -> do
bs <- fetch
if BS.null bs
then execute received (continuation Nothing)
else execute (received + fromIntegral (BS.length bs)) (continuation $ Just bs)
SG.Fail _ _ failure ->
E.throwIO (ProtocolViolation failure)
SG.Done leftover' _ msg -> do
done <- consume msg
if done
then pure leftover'
else execute 0 (SG.pushChunk decode leftover')
serveConnection :: forall transport auth. (SS.StreamOriented transport, MqttServerTransportStack transport, Authenticator auth) => Broker.Broker auth -> SS.Connection transport -> SS.ConnectionInfo transport -> IO ()
serveConnection broker conn info = do
leftover <- newMVar mempty
recentActivity <- newIORef True
req <- getConnectionRequest info
msg <- receiveMessage conn maxInitialPacketSize leftover
case msg of
ClientConnectUnsupported -> do
Broker.onConnectionRejected cbs req UnacceptableProtocolVersion
void $ sendMessage conn (ServerConnectionRejected UnacceptableProtocolVersion)
-- Communication ends here gracefully. The caller shall close the connection.
ClientConnect {} -> do
let -- | This one is called when the authenticator decided to reject the request.
sessionRejectHandler reason = do
Broker.onConnectionRejected cbs request reason
void $ sendMessage conn (ServerConnectionRejected reason)
-- Communication ends here gracefully. The caller shall close the connection.
-- | This part is where the threads for a connection are created
-- (one for input, one for output and one watchdog thread).
sessionAcceptHandler session sessionPresent = do
Broker.onConnectionAccepted cbs request session
void $ sendMessage conn (ServerConnectionAccepted sessionPresent)
foldl1 race_
[ handleInput recentActivity leftover session
, handleOutput session
, keepAlive recentActivity (connectKeepAlive msg)
] `E.catch` (\e-> do
Broker.onConnectionFailed cbs session e
E.throwIO e
)
Broker.onConnectionClosed cbs session
-- Extend the request object with information gathered from the connect packet.
request = req {
requestClientIdentifier = connectClientIdentifier msg
, requestCleanSession = cleanSession
, requestCredentials = connectCredentials msg
, requestWill = connectWill msg
}
where
CleanSession cleanSession = connectCleanSession msg
Broker.withSession broker request sessionRejectHandler sessionAcceptHandler
_ -> pure () -- TODO: Don't parse not-CONN packets in the first place!
where
cbs = Session.brokerCallbacks broker
-- The size of the initial CONN packet shall somewhat be limited to a moderate size.
-- This value is assumed to make no problems while still protecting
-- the servers resources against exaustion attacks.
maxInitialPacketSize :: Int64
maxInitialPacketSize = 65535
-- The keep alive thread wakes up every `keepAlive/2` seconds.
-- When it detects no recent activity, it sleeps one more full `keepAlive`
-- interval and checks again. When it still finds no recent activity, it
-- throws an exception.
-- That way a timeout will be detected between 1.5 and 2 `keep alive`
-- intervals after the last actual client activity.
keepAlive :: IORef Bool -> KeepAliveInterval -> IO ()
keepAlive recentActivity (KeepAliveInterval interval) = forever $ do
writeIORef recentActivity False
threadDelay regularInterval
activity <- readIORef recentActivity
unless activity $ do
threadDelay regularInterval
activity' <- readIORef recentActivity
unless activity' $ do
threadDelay regularInterval
activity'' <- readIORef recentActivity
unless activity'' $ E.throwIO KeepAliveTimeoutException
where
regularInterval = fromIntegral interval * 500000
-- | This thread is responsible for continuously processing input.
-- It blocks on reading the input stream until input becomes available.
-- Input is consumed no faster than it can be processed.
--
-- * Read packet from the input stream.
-- * Note that there was activity (TODO: a timeout may occur when a packet
-- takes too long to transmit due to its size).
-- * Process and dispatch the message internally.
-- * Repeat and eventually wait again.
-- * Eventually throws `ServerException`s.
handleInput :: IORef Bool -> MVar BS.ByteString -> Session.Session auth -> IO ()
handleInput recentActivity leftover session = do
maxPacketSize <- fromIntegral . quotaMaxPacketSize . principalQuota <$> Session.getPrincipal session
consumeMessages conn maxPacketSize leftover $ \packet-> do
writeIORef recentActivity True
Session.accountPacketsReceived (Session.sessionStatistic session) 1
case packet of
ClientDisconnect ->
pure True
ClientConnect {} ->
E.throwIO $ ProtocolViolation "Unexpected CONN packet."
ClientConnectUnsupported ->
E.throwIO $ ProtocolViolation "Unexpected CONN packet (of unsupported protocol version)."
_ -> Session.process session packet >> pure False
-- | This thread is responsible for continuously transmitting to the client
-- and reading from the output queue.
--
-- * It blocks on Session.waitPending until output gets available.
-- * When output is available, it fetches a whole sequence of messages
-- from the output queue.
-- * It then uses the optimized SS.sendMessages operation which fills
-- a whole chunk with as many messages as possible and sends the chunks
-- each with a single system call. This is _very_ important for high
-- throughput.
-- * Afterwards, it repeats and eventually waits again.
handleOutput :: Session.Session auth -> IO ()
handleOutput session = forever $ do
-- The `waitPending` operation is blocking until messages get available.
Session.wait session
msgs <- Session.poll session
void $ sendMessages conn msgs
Session.accountPacketsSent (Session.sessionStatistic session) (fromIntegral $ Seq.length msgs)
| lpeterse/haskell-mqtt | src/Network/MQTT/Broker/Server.hs | mit | 10,140 | 0 | 23 | 2,613 | 1,843 | 925 | 918 | 147 | 6 |
{-# LANGUAGE QuasiQuotes,
TemplateHaskell,
CPP #-}
module Gen2.Prim where
{-
unboxed representations:
Int# -> number
Double# -> number
Float# -> number
Char# -> number
Word# -> number (values > 2^31 are mapped to negative numbers)
Addr# -> wrapped buffer + offset (number)
(with some hacks for pointers to pointers in the .arr property)
MutVar# -> h$MutVar object
TVar# -> h$TVar object
MVar# -> h$MVar object
Weak# -> h$Weak object
ThreadId# -> h$Thread object
State# -> nothing
StablePtr# -> wrapped buffer / offset (base pkg expects unsafeCoerce to Addr# to work)
MutableArrayArray# -> array
MutableByteArray# -> wrapped buffer
ByteArray# -> wrapped buffer
Array# -> array
Pointers to pointers use a special representation with the .arr property
-}
import DynFlags
import PrimOp
import TcType
import Type
import TyCon
import Data.Monoid
import qualified Data.Set as S
import Compiler.JMacro (j, je, JExpr(..), JStat(..))
import Gen2.Profiling
import Gen2.RtsTypes
import Gen2.Utils
data PrimRes = PrimInline JStat -- ^ primop is inline, result is assigned directly
| PRPrimCall JStat -- ^ primop is async call, primop returns the next
-- function to run. result returned to stack top in registers
isInlinePrimOp :: PrimOp -> Bool
isInlinePrimOp p = p `S.notMember` notInlinePrims
where
-- all primops that might block the thread or manipulate stack directly
-- (and therefore might return PRPrimCall) must be listed here
notInlinePrims = S.fromList
[ CatchOp, RaiseOp, RaiseIOOp
, MaskAsyncExceptionsOp, MaskUninterruptibleOp, UnmaskAsyncExceptionsOp
, AtomicallyOp, RetryOp, CatchRetryOp, CatchSTMOp
, TakeMVarOp, PutMVarOp, ReadMVarOp
, DelayOp
, WaitReadOp, WaitWriteOp
, KillThreadOp
, YieldOp
, SeqOp
]
genPrim :: DynFlags
-> Type
-> PrimOp -- ^ the primitive operation
-> [JExpr] -- ^ where to store the result
-> [JExpr] -- ^ arguments
-> PrimRes
genPrim _ _ CharGtOp [r] [x,y] = PrimInline [j| `r` = (`x` > `y`) ? 1 : 0; |]
genPrim _ _ CharGeOp [r] [x,y] = PrimInline [j| `r` = (`x` >= `y`) ? 1 : 0; |]
genPrim _ _ CharEqOp [r] [x,y] = PrimInline [j| `r` = (`x` === `y`) ? 1 : 0; |]
genPrim _ _ CharNeOp [r] [x,y] = PrimInline [j| `r` = (`x` !== `y`) ? 1 : 0; |]
genPrim _ _ CharLtOp [r] [x,y] = PrimInline [j| `r` = (`x` < `y`) ? 1 : 0; |]
genPrim _ _ CharLeOp [r] [x,y] = PrimInline [j| `r` = (`x` <= `y`) ? 1 : 0; |]
genPrim _ _ OrdOp [r] [x] = PrimInline [j| `r` = `x` |]
genPrim _ _ IntAddOp [r] [x,y] = PrimInline [j| `r` = (`x` + `y`)|0 |]
genPrim _ _ IntSubOp [r] [x,y] = PrimInline [j| `r` = (`x` - `y`)|0 |]
genPrim _ _ IntMulOp [r] [x,y] =
PrimInline [j| `r` = h$mulInt32(`x`,`y`); |]
-- fixme may will give the wrong result in case of overflow
genPrim _ _ IntMulMayOfloOp [r] [x,y] =
PrimInline [j| var tmp = (`x`*`y`); `r` = (tmp===(tmp|0))?0:1; |]
genPrim _ _ IntQuotOp [r] [x,y] = PrimInline [j| `r` = (`x`/`y`)|0; |]
genPrim _ _ IntRemOp [r] [x,y] = PrimInline [j| `r` = `x` % `y` |]
genPrim _ _ IntQuotRemOp [q,r] [x,y] = PrimInline [j| `q` = (`x`/`y`)|0;
`r` = `x`-`y`*`q`;
|]
genPrim _ _ AndIOp [r] [x,y] = PrimInline [j| `r` = `x` & `y`; |]
genPrim _ _ OrIOp [r] [x,y] = PrimInline [j| `r` = `x` | `y`; |]
genPrim _ _ XorIOp [r] [x,y] = PrimInline [j| `r` = `x` ^ `y`; |]
genPrim _ _ NotIOp [r] [x] = PrimInline [j| `r` = ~`x`; |]
genPrim _ _ IntNegOp [r] [x] = PrimInline [j| `r` = `jneg x`|0; |]
-- add with carry: overflow == 0 iff no overflow
genPrim _ _ IntAddCOp [r,overf] [x,y] =
PrimInline [j| var rt = `x`+`y`; `r` = rt|0; `overf` = (`r`!=rt)?1:0; |]
genPrim _ _ IntSubCOp [r,overf] [x,y] =
PrimInline [j| var rt = `x`-`y`; `r` = rt|0; `overf` = (`r`!=rt)?1:0; |]
genPrim _ _ IntGtOp [r] [x,y] = PrimInline [j| `r` = (`x` > `y`) ? 1 : 0 |]
genPrim _ _ IntGeOp [r] [x,y] = PrimInline [j| `r`= (`x` >= `y`) ? 1 : 0 |]
genPrim _ _ IntEqOp [r] [x,y] = PrimInline [j| `r` = (`x` === `y`) ? 1 : 0 |]
genPrim _ _ IntNeOp [r] [x,y] = PrimInline [j| `r` = (`x` !== `y`) ? 1 : 0 |]
genPrim _ _ IntLtOp [r] [x,y] = PrimInline [j| `r` = (`x` < `y`) ? 1 : 0 |]
genPrim _ _ IntLeOp [r] [x,y] = PrimInline [j| `r` = (`x` <= `y`) ? 1 : 0 |]
genPrim _ _ ChrOp [r] [x] = PrimInline [j| `r` = `x` |]
genPrim _ _ Int2WordOp [r] [x] = PrimInline [j| `r` = `x` |]
genPrim _ _ Int2FloatOp [r] [x] = PrimInline [j| `r` = `x` |]
genPrim _ _ Int2DoubleOp [r] [x] = PrimInline [j| `r` = `x` |]
genPrim _ _ ISllOp [r] [x,y] = PrimInline [j| `r` = `x` << `y` |]
genPrim _ _ ISraOp [r] [x,y] = PrimInline [j| `r` = `x` >> `y` |]
genPrim _ _ ISrlOp [r] [x,y] = PrimInline [j| `r` = `x` >>> `y` |]
genPrim _ _ WordAddOp [r] [x,y] = PrimInline [j| `r` = (`x` + `y`)|0; |]
genPrim _ _ WordAdd2Op [h,l] [x,y] = PrimInline [j| `h` = h$wordAdd2(`x`,`y`);
`l` = `Ret1`;
|]
genPrim _ _ WordSubOp [r] [x,y] = PrimInline [j| `r` = (`x` - `y`)|0 |]
genPrim _ _ WordMulOp [r] [x,y] =
PrimInline [j| `r` = h$mulWord32(`x`,`y`); |]
genPrim _ _ WordMul2Op [h,l] [x,y] =
PrimInline [j| `h` = h$mul2Word32(`x`,`y`);
`l` = `Ret1`;
|]
genPrim _ _ WordQuotOp [q] [x,y] = PrimInline [j| `q` = h$quotWord32(`x`,`y`); |]
genPrim _ _ WordRemOp [r] [x,y] = PrimInline [j| `r`= h$remWord32(`x`,`y`); |]
genPrim _ _ WordQuotRemOp [q,r] [x,y] = PrimInline [j| `q` = h$quotWord32(`x`,`y`);
`r` = h$remWord32(`x`, `y`);
|]
genPrim _ _ WordQuotRem2Op [q,r] [xh,xl,y] = PrimInline [j| `q` = h$quotRem2Word32(`xh`,`xl`,`y`);
`r` = `Ret1`;
|]
genPrim _ _ AndOp [r] [x,y] = PrimInline [j| `r` = `x` & `y` |]
genPrim _ _ OrOp [r] [x,y] = PrimInline [j| `r` = `x` | `y` |]
genPrim _ _ XorOp [r] [x,y] = PrimInline [j| `r` = `x` ^ `y` |]
genPrim _ _ NotOp [r] [x] = PrimInline [j| `r` = ~`x` |]
genPrim _ _ SllOp [r] [x,y] = PrimInline [j| `r` = `x` << `y` |]
genPrim _ _ SrlOp [r] [x,y] = PrimInline [j| `r` = `x` >>> `y` |]
genPrim _ _ Word2IntOp [r] [x] = PrimInline [j| `r` = `x` |]
genPrim _ _ WordGtOp [r] [x,y] =
PrimInline [j| `r` = ((`x`>>>1) > (`y`>>>1) || ((`x`>>>1) == (`y`>>>1) && (`x`&1) > (`y`&1))) ? 1 : 0 |]
genPrim _ _ WordGeOp [r] [x,y] =
PrimInline [j| `r` = ((`x`>>>1) > (`y`>>>1) || ((`x`>>>1) == (`y`>>>1) && (`x`&1) >= (`y`&1))) ? 1 : 0 |]
genPrim _ _ WordEqOp [r] [x,y] = PrimInline [j| `r` = (`x` === `y`) ? 1 : 0 |]
genPrim _ _ WordNeOp [r] [x,y] = PrimInline [j| `r` = (`x` !== `y`) ? 1 : 0 |]
genPrim _ _ WordLtOp [r] [x,y] =
PrimInline [j| `r` = ((`x`>>>1) < (`y`>>>1) || ((`x`>>>1) == (`y`>>>1) && (`x`&1) < (`y`&1))) ? 1 : 0 |]
genPrim _ _ WordLeOp [r] [x,y] =
PrimInline [j| `r` = ((`x`>>>1) < (`y`>>>1) || ((`x`>>>1) == (`y`>>>1) && (`x`&1) <= (`y`&1))) ? 1 : 0 |]
genPrim _ _ Word2DoubleOp [r] [x] = PrimInline [j| `r` = (`x` & 0x7FFFFFFF) + (`x` >>> 31) * 2147483648 |]
genPrim _ _ Word2FloatOp [r] [x] = PrimInline [j| `r` = (`x` & 0x7FFFFFFF) + (`x` >>> 31) * 2147483648 |]
genPrim _ _ PopCnt8Op [r] [x] = PrimInline [j| `r` = h$popCntTab[`x` & 0xFF] |]
genPrim _ _ PopCnt16Op [r] [x] =
PrimInline [j| `r` = h$popCntTab[`x`&0xFF] +
h$popCntTab[(`x`>>>8)&0xFF]
|]
genPrim _ _ PopCnt32Op [r] [x] = PrimInline [j| `r` = h$popCnt32(`x`); |]
genPrim _ _ PopCnt64Op [r] [x1,x2] = PrimInline [j| `r` = h$popCnt64(`x1`,`x2`); |]
genPrim d t PopCntOp [r] [x] = genPrim d t PopCnt32Op [r] [x]
genPrim _ _ BSwap16Op [r] [x] = PrimInline [j| `r` = ((`x` & 0xFF) << 8) | ((`x` & 0xFF00) >> 8); |] -- ab -> ba
genPrim _ _ BSwap32Op [r] [x] = PrimInline [j| `r` = (`x` << 24) | ((`x` & 0xFF00) << 8)
| ((`x` & 0xFF0000) >> 8) | (`x` >>> 24);
|] -- abcd -> dcba
genPrim _ _ BSwap64Op [r1,r2] [x,y] = PrimInline [j| `r1` = h$bswap64(`x`,`y`);
`r2` = `Ret1`;
|]
genPrim d t BSwapOp [r] [x] = genPrim d t BSwap32Op [r] [x]
genPrim _ _ Narrow8IntOp [r] [x] = PrimInline [j| `r` = (`x` & 0x7F)-(`x` & 0x80) |]
genPrim _ _ Narrow16IntOp [r] [x] = PrimInline [j| `r` = (`x` & 0x7FFF)-(`x` & 0x8000) |]
genPrim _ _ Narrow32IntOp [r] [x] = PrimInline [j| `r` = `x`|0 |]
genPrim _ _ Narrow8WordOp [r] [x] = PrimInline [j| `r` = (`x` & 0xFF) |]
genPrim _ _ Narrow16WordOp [r] [x] = PrimInline [j| `r` = (`x` & 0xFFFF) |]
genPrim _ _ Narrow32WordOp [r] [x] = PrimInline [j| `r` = `x`|0 |]
genPrim _ _ DoubleGtOp [r] [x,y] = PrimInline [j| `r` = (`x` > `y`) ? 1 : 0 |]
genPrim _ _ DoubleGeOp [r] [x,y] = PrimInline [j| `r` = (`x` >= `y`) ? 1 : 0 |]
genPrim _ _ DoubleEqOp [r] [x,y] = PrimInline [j| `r` = (`x` === `y`) ? 1 : 0 |]
genPrim _ _ DoubleNeOp [r] [x,y] = PrimInline [j| `r` = (`x` !== `y`) ? 1 : 0 |]
genPrim _ _ DoubleLtOp [r] [x,y] = PrimInline [j| `r` = (`x` < `y`) ? 1 : 0 |]
genPrim _ _ DoubleLeOp [r] [x,y] = PrimInline [j| `r` = (`x` <= `y`) ? 1 : 0 |]
genPrim _ _ DoubleAddOp [r] [x,y] = PrimInline [j| `r` = `x` + `y` |]
genPrim _ _ DoubleSubOp [r] [x,y] = PrimInline [j| `r` = `x` - `y` |]
genPrim _ _ DoubleMulOp [r] [x,y] = PrimInline [j| `r` = `x` * `y` |]
genPrim _ _ DoubleDivOp [r] [x,y] = PrimInline [j| `r` = `x` / `y` |]
genPrim _ _ DoubleNegOp [r] [x] = PrimInline [j| `r` = `jneg x` |] -- fixme negate
genPrim _ _ Double2IntOp [r] [x] = PrimInline [j| `r` = `x`|0; |]
genPrim _ _ Double2FloatOp [r] [x] = PrimInline [j| `r` = `x` |]
genPrim _ _ DoubleExpOp [r] [x] = PrimInline [j| `r` = Math.exp(`x`) |]
genPrim _ _ DoubleLogOp [r] [x] = PrimInline [j| `r` = Math.log(`x`) |]
genPrim _ _ DoubleSqrtOp [r] [x] = PrimInline [j| `r` = Math.sqrt(`x`) |]
genPrim _ _ DoubleSinOp [r] [x] = PrimInline [j| `r` = Math.sin(`x`) |]
genPrim _ _ DoubleCosOp [r] [x] = PrimInline [j| `r` = Math.cos(`x`) |]
genPrim _ _ DoubleTanOp [r] [x] = PrimInline [j| `r` = Math.tan(`x`) |]
genPrim _ _ DoubleAsinOp [r] [x] = PrimInline [j| `r` = Math.asin(`x`) |]
genPrim _ _ DoubleAcosOp [r] [x] = PrimInline [j| `r` = Math.acos(`x`) |]
genPrim _ _ DoubleAtanOp [r] [x] = PrimInline [j| `r` = Math.atan(`x`) |]
genPrim _ _ DoubleSinhOp [r] [x] = PrimInline [j| `r` = (Math.exp(`x`)-Math.exp(`jneg x`))/2 |]
genPrim _ _ DoubleCoshOp [r] [x] = PrimInline [j| `r` = (Math.exp(`x`)+Math.exp(`jneg x`))/2 |]
genPrim _ _ DoubleTanhOp [r] [x] = PrimInline [j| `r` = (Math.exp(2*`x`)-1)/(Math.exp(2*`x`)+1) |]
genPrim _ _ DoublePowerOp [r] [x,y] = PrimInline [j| `r` = Math.pow(`x`,`y`) |]
genPrim _ _ DoubleDecode_2IntOp [s,h,l,e] [x] =
PrimInline [j| `s` = h$decodeDouble2Int(`x`);
`h` = `Ret1`;
`l` = `Ret2`;
`e` = `Ret3`;
|]
genPrim _ _ FloatGtOp [r] [x,y] = PrimInline [j| `r` = (`x` > `y`) ? 1 : 0 |]
genPrim _ _ FloatGeOp [r] [x,y] = PrimInline [j| `r` = (`x` >= `y`) ? 1 : 0 |]
genPrim _ _ FloatEqOp [r] [x,y] = PrimInline [j| `r` = (`x` === `y`) ? 1 : 0 |]
genPrim _ _ FloatNeOp [r] [x,y] = PrimInline [j| `r` = (`x` !== `y`) ? 1 : 0 |]
genPrim _ _ FloatLtOp [r] [x,y] = PrimInline [j| `r` = (`x` < `y`) ? 1 : 0 |]
genPrim _ _ FloatLeOp [r] [x,y] = PrimInline [j| `r` = (`x` <= `y`) ? 1 : 0 |]
genPrim _ _ FloatAddOp [r] [x,y] = PrimInline [j| `r` = `x` + `y` |]
genPrim _ _ FloatSubOp [r] [x,y] = PrimInline [j| `r` = `x` - `y` |]
genPrim _ _ FloatMulOp [r] [x,y] = PrimInline [j| `r` = `x` * `y` |]
genPrim _ _ FloatDivOp [r] [x,y] = PrimInline [j| `r` = `x` / `y` |]
genPrim _ _ FloatNegOp [r] [x] = PrimInline [j| `r` = `jneg x` |]
genPrim _ _ Float2IntOp [r] [x] = PrimInline [j| `r` = `x`|0 |]
genPrim _ _ FloatExpOp [r] [x] = PrimInline [j| `r` = Math.exp(`x`) |]
genPrim _ _ FloatLogOp [r] [x] = PrimInline [j| `r` = Math.log(`x`) |]
genPrim _ _ FloatSqrtOp [r] [x] = PrimInline [j| `r` = Math.sqrt(`x`) |]
genPrim _ _ FloatSinOp [r] [x] = PrimInline [j| `r` = Math.sin(`x`) |]
genPrim _ _ FloatCosOp [r] [x] = PrimInline [j| `r` = Math.cos(`x`) |]
genPrim _ _ FloatTanOp [r] [x] = PrimInline [j| `r` = Math.tan(`x`) |]
genPrim _ _ FloatAsinOp [r] [x] = PrimInline [j| `r` = Math.asin(`x`) |]
genPrim _ _ FloatAcosOp [r] [x] = PrimInline [j| `r` = Math.acos(`x`) |]
genPrim _ _ FloatAtanOp [r] [x] = PrimInline [j| `r` = Math.atan(`x`) |]
genPrim _ _ FloatSinhOp [r] [x] = PrimInline [j| `r` = (Math.exp(`x`)-Math.exp(`jneg x`))/2 |]
genPrim _ _ FloatCoshOp [r] [x] = PrimInline [j| `r` = (Math.exp(`x`)+Math.exp(`jneg x`))/2 |]
genPrim _ _ FloatTanhOp [r] [x] = PrimInline [j| `r` = (Math.exp(2*`x`)-1)/(Math.exp(2*`x`)+1) |]
genPrim _ _ FloatPowerOp [r] [x,y] = PrimInline [j| `r` = Math.pow(`x`,`y`) |]
genPrim _ _ Float2DoubleOp [r] [x] = PrimInline [j| `r` = `x` |]
genPrim _ _ FloatDecode_IntOp [s,e] [x] = PrimInline [j| `s` = h$decodeFloatInt(`x`); `e` = `Ret1`; |]
genPrim _ _ NewArrayOp [r] [l,e] = PrimInline (newArray r l e)
genPrim _ _ SameMutableArrayOp [r] [a1,a2] = PrimInline [j| `r` = (`a1` === `a2`) ? 1 : 0 |]
genPrim _ _ ReadArrayOp [r] [a,i] = PrimInline [j| `r` = `a`[`i`]; |]
genPrim _ _ WriteArrayOp [] [a,i,v] = PrimInline [j| `a`[`i`] = `v`; |]
genPrim _ _ SizeofArrayOp [r] [a] = PrimInline [j| `r` = `a`.length; |]
genPrim _ _ SizeofMutableArrayOp [r] [a] = PrimInline [j| `r` = `a`.length; |]
genPrim _ _ IndexArrayOp [r] [a,i] = PrimInline [j| `r` = `a`[`i`]; |]
genPrim _ _ UnsafeFreezeArrayOp [r] [a] = PrimInline [j| `r` = `a`; |]
genPrim _ _ UnsafeThawArrayOp [r] [a] = PrimInline [j| `r` = `a`; |]
genPrim _ _ CopyArrayOp [] [a,o1,ma,o2,n] =
PrimInline [j| for(var i=0;i<`n`;i++) {
`ma`[i+`o2`] = `a`[i+`o1`];
}
|]
genPrim d t CopyMutableArrayOp [] [a1,o1,a2,o2,n] = genPrim d t CopyArrayOp [] [a1,o1,a2,o2,n]
genPrim _ _ CloneArrayOp [r] [a,start,n] =
PrimInline [j| `r` = h$sliceArray(`a`,`start`,`n`) |]
genPrim d t CloneMutableArrayOp [r] [a,start,n] = genPrim d t CloneArrayOp [r] [a,start,n]
genPrim _ _ FreezeArrayOp [r] [a,start,n] =
PrimInline [j| `r` = h$sliceArray(`a`,`start`,`n`); |]
genPrim _ _ ThawArrayOp [r] [a,start,n] =
PrimInline [j| `r` = h$sliceArray(`a`,`start`,`n`); |]
genPrim _ _ NewByteArrayOp_Char [r] [l] = PrimInline (newByteArray r l)
genPrim _ _ NewPinnedByteArrayOp_Char [r] [l] = PrimInline (newByteArray r l)
genPrim _ _ NewAlignedPinnedByteArrayOp_Char [r] [l,_align] = PrimInline (newByteArray r l)
genPrim _ _ ByteArrayContents_Char [a,o] [b] = PrimInline [j| `a` = `b`; `o` = 0; |]
genPrim _ _ SameMutableByteArrayOp [r] [a,b] = PrimInline [j| `r` = (`a` === `b`) ? 1 : 0 |]
genPrim _ _ UnsafeFreezeByteArrayOp [a] [b] = PrimInline [j| `a` = `b`; |]
genPrim _ _ SizeofByteArrayOp [r] [a] = PrimInline [j| `r` = `a`.len; |]
genPrim _ _ SizeofMutableByteArrayOp [r] [a] = PrimInline [j| `r` = `a`.len; |]
genPrim _ _ IndexByteArrayOp_Char [r] [a,i] = PrimInline [j| `r` = `a`.u8[`i`]; |]
genPrim _ _ IndexByteArrayOp_WideChar [r] [a,i] = PrimInline [j| `r` = `a`.i3[`i`]; |]
genPrim _ _ IndexByteArrayOp_Int [r] [a,i] = PrimInline [j| `r` = `a`.i3[`i`]; |]
genPrim _ _ IndexByteArrayOp_Word [r] [a,i] = PrimInline [j| `r` = `a`.i3[`i`]; |]
genPrim _ _ IndexByteArrayOp_Addr [r1,r2] [a,i] = PrimInline [j| if(`a`.arr && `a`.arr[`i`<<2]) {
`r1` = `a`.arr[`i`<<2][0];
`r2` = `a`.arr[`i`<<2][1];
} else {
`r1` = null;
`r2` = 0;
}
|]
genPrim _ _ IndexByteArrayOp_Float [r] [a,i] = PrimInline [j| `r` = `a`.f3[`i`]; |]
genPrim _ _ IndexByteArrayOp_Double [r] [a,i] = PrimInline [j| `r` = `a`.f6[`i`]; |]
-- genPrim _ IndexByteArrayOp_StablePtr
genPrim _ _ IndexByteArrayOp_Int8 [r] [a,i] = PrimInline [j| `r` = `a`.dv.getInt8(`i`,true); |]
genPrim _ _ IndexByteArrayOp_Int16 [r] [a,i] = PrimInline [j| `r` = `a`.dv.getInt16(`i`<<1,true); |]
genPrim _ _ IndexByteArrayOp_Int32 [r] [a,i] = PrimInline [j| `r` = `a`.i3[`i`]; |]
genPrim _ _ IndexByteArrayOp_Int64 [r1,r2] [a,i] =
PrimInline [j| `r1` = `a`.i3[`i`<<1];
`r2` = `a`.i3[(`i`<<1)+1];
|]
genPrim _ _ IndexByteArrayOp_Word8 [r] [a,i] = PrimInline [j| `r` = `a`.u8[`i`]; |]
genPrim _ _ IndexByteArrayOp_Word16 [r] [a,i] = PrimInline [j| `r` = `a`.dv.getUint16(`i`<<1,true); |]
genPrim _ _ IndexByteArrayOp_Word32 [r] [a,i] = PrimInline [j| `r` = `a`.i3[`i`]; |]
genPrim _ _ IndexByteArrayOp_Word64 [r1,r2] [a,i] =
PrimInline [j| `r1` = `a`.i3[`i`<<1];
`r2` = `a`.i3[(`i`<<1)+1];
|]
genPrim _ _ ReadByteArrayOp_Char [r] [a,i] = PrimInline [j| `r` = `a`.u8[`i`]; |]
genPrim _ _ ReadByteArrayOp_WideChar [r] [a,i] = PrimInline [j| `r` = `a`.i3[`i`]; |]
genPrim _ _ ReadByteArrayOp_Int [r] [a,i] = PrimInline [j| `r` = `a`.i3[`i`]; |]
genPrim _ _ ReadByteArrayOp_Word [r] [a,i] = PrimInline [j| `r` = `a`.i3[`i`]; |]
genPrim _ _ ReadByteArrayOp_Addr [r1,r2] [a,i] = PrimInline [j| var x = `i`<<2;
if(`a`.arr && `a`.arr[x]) {
`r1` = `a`.arr[x][0];
`r2` = `a`.arr[x][1];
} else {
`r1` = null;
`r2` = 0;
}
|]
genPrim _ _ ReadByteArrayOp_Float [r] [a,i] = PrimInline [j| `r` = `a`.f3[`i`]; |]
genPrim _ _ ReadByteArrayOp_Double [r] [a,i] = PrimInline [j| `r` = `a`.f6[`i`]; |]
-- genPrim _ ReadByteArrayOp_StablePtr
genPrim _ _ ReadByteArrayOp_Int8 [r] [a,i] = PrimInline [j| `r` = `a`.dv.getInt8(`i`,true); |]
genPrim _ _ ReadByteArrayOp_Int16 [r] [a,i] = PrimInline [j| `r` = `a`.dv.getInt16(`i`<<1,true); |]
genPrim _ _ ReadByteArrayOp_Int32 [r] [a,i] = PrimInline [j| `r` = `a`.i3[`i`]; |]
genPrim _ _ ReadByteArrayOp_Int64 [r1,r2] [a,i] =
PrimInline [j| `r1` = `a`.i3[`i`<<1];
`r2` = `a`.i3[(`i`<<1)+1];
|]
genPrim _ _ ReadByteArrayOp_Word8 [r] [a,i] = PrimInline [j| `r` = `a`.u8[`i`]; |]
genPrim _ _ ReadByteArrayOp_Word16 [r] [a,i] = PrimInline [j| `r` = `a`.u1[`i`]; |]
genPrim _ _ ReadByteArrayOp_Word32 [r] [a,i] = PrimInline [j| `r` = `a`.i3[`i`]; |]
genPrim _ _ ReadByteArrayOp_Word64 [r1,r2] [a,i] =
PrimInline [j| `r1` = `a`.i3[`i`<<1];
`r2` = `a`.i3[(`i`<<1)+1];
|]
genPrim _ _ WriteByteArrayOp_Char [] [a,i,e] = PrimInline [j| `a`.u8[`i`] = `e`; |]
genPrim _ _ WriteByteArrayOp_WideChar [] [a,i,e] = PrimInline [j| `a`.i3[`i`] = `e`; |]
genPrim _ _ WriteByteArrayOp_Int [] [a,i,e] = PrimInline [j| `a`.i3[`i`] = `e`; |]
genPrim _ _ WriteByteArrayOp_Word [] [a,i,e] = PrimInline [j| `a`.i3[`i`] = `e`; |]
genPrim _ _ WriteByteArrayOp_Addr [] [a,i,e1,e2] = PrimInline [j| if(!`a`.arr) { `a`.arr = []; }
`a`.arr[`i`<<2] = [`e1`,`e2`];
|]
genPrim _ _ WriteByteArrayOp_Float [] [a,i,e] = PrimInline [j| `a`.f3[`i`] = `e`; |]
genPrim _ _ WriteByteArrayOp_Double [] [a,i,e] = PrimInline [j| `a`.f6[`i`] = `e`; |]
-- genPrim _ WriteByteArrayOp_StablePtr
genPrim _ _ WriteByteArrayOp_Int8 [] [a,i,e] = PrimInline [j| `a`.dv.setInt8(`i`, `e`, false); |]
genPrim _ _ WriteByteArrayOp_Int16 [] [a,i,e] = PrimInline [j| `a`.dv.setInt16(`i`<<1, `e`, false); |]
genPrim _ _ WriteByteArrayOp_Int32 [] [a,i,e] = PrimInline [j| `a`.i3[`i`] = `e`; |]
genPrim _ _ WriteByteArrayOp_Int64 [] [a,i,e1,e2] =
PrimInline [j| `a`.i3[`i`<<1] = `e1`;
`a`.i3[(`i`<<1)+1] = `e2`;
|]
genPrim _ _ WriteByteArrayOp_Word8 [] [a,i,e] = PrimInline [j| `a`.u8[`i`] = `e`; |]
genPrim _ _ WriteByteArrayOp_Word16 [] [a,i,e] = PrimInline [j| `a`.u1[`i`] = `e`; |]
genPrim _ _ WriteByteArrayOp_Word32 [] [a,i,e] = PrimInline [j| `a`.i3[`i`] = `e`; |]
genPrim _ _ WriteByteArrayOp_Word64 [] [a,i,e1,e2] =
PrimInline [j| `a`.i3[`i`<<1] = `e1`;
`a`.i3[(`i`<<1)+1] = `e2`;
|]
-- fixme we can do faster by copying 32 bit ints or doubles
genPrim _ _ CopyByteArrayOp [] [a1,o1,a2,o2,n] =
PrimInline [j| for(var i=`n` - 1; i >= 0; i--) {
`a2`.u8[i+`o2`] = `a1`.u8[i+`o1`];
}
|]
genPrim d t CopyMutableByteArrayOp [] xs@[_a1,_o1,_a2,_o2,_n] = genPrim d t CopyByteArrayOp [] xs
genPrim d t CopyByteArrayToAddrOp [] xs@[_a1,_o1,_a2,_o2,_n] = genPrim d t CopyByteArrayOp [] xs
genPrim d t CopyMutableByteArrayToAddrOp [] xs@[_a1,_o1,_a2,_o2,_n] = genPrim d t CopyByteArrayOp [] xs
genPrim _ _ SetByteArrayOp [] [a,o,n,v] =
PrimInline [j| for(var i=0;i<`n`;i++) {
`a`.u8[`o`+i] = `v`;
}
|]
genPrim _ _ NewArrayArrayOp [r] [n] = PrimInline (newArray r n jnull)
genPrim _ _ SameMutableArrayArrayOp [r] [a1,a2] = PrimInline [j| `r` = (`a1` === `a2`) ? 1 : 0 |]
genPrim _ _ UnsafeFreezeArrayArrayOp [r] [a] = PrimInline [j| `r` = `a` |]
genPrim _ _ SizeofArrayArrayOp [r] [a] = PrimInline [j| `r` = `a`.length; |]
genPrim _ _ SizeofMutableArrayArrayOp [r] [a] = PrimInline [j| `r` = `a`.length; |]
genPrim _ _ IndexArrayArrayOp_ByteArray [r] [a,n] = PrimInline [j| `r` = `a`[`n`] |]
genPrim _ _ IndexArrayArrayOp_ArrayArray [r] [a,n] = PrimInline [j| `r` = `a`[`n`] |]
genPrim _ _ ReadArrayArrayOp_ByteArray [r] [a,n] = PrimInline [j| `r` = `a`[`n`] |]
genPrim _ _ ReadArrayArrayOp_MutableByteArray [r] [a,n] = PrimInline [j| `r` = `a`[`n`] |]
genPrim _ _ ReadArrayArrayOp_ArrayArray [r] [a,n] = PrimInline [j| `r` = `a`[`n`] |]
genPrim _ _ ReadArrayArrayOp_MutableArrayArray [r] [a,n] = PrimInline [j| `r` = `a`[`n`] |]
genPrim _ _ WriteArrayArrayOp_ByteArray [] [a,n,v] = PrimInline [j| `a`[`n`] = `v` |]
genPrim _ _ WriteArrayArrayOp_MutableByteArray [] [a,n,v] = PrimInline [j| `a`[`n`] = `v` |]
genPrim _ _ WriteArrayArrayOp_ArrayArray [] [a,n,v] = PrimInline [j| `a`[`n`] = `v` |]
genPrim _ _ WriteArrayArrayOp_MutableArrayArray [] [a,n,v] = PrimInline [j| `a`[`n`] = `v` |]
genPrim _ _ CopyArrayArrayOp [] [a1,o1,a2,o2,n] =
PrimInline [j| for(var i=0;i<`n`;i++) { `a2`[i+`o2`]=`a1`[i+`o1`]; } |]
genPrim _ _ CopyMutableArrayArrayOp [] [a1,o1,a2,o2,n] =
PrimInline [j| for(var i=0;i<`n`;i++) { `a2`[i+`o2`]=`a1`[i+`o1`]; } |]
genPrim _ _ AddrAddOp [a',o'] [a,o,i] = PrimInline [j| `a'` = `a`; `o'` = `o` + `i`;|]
genPrim _ _ AddrSubOp [i] [_a1,o1,_a2,o2] = PrimInline [j| `i` = `o1` - `o2` |]
genPrim _ _ AddrRemOp [r] [_a,o,i] = PrimInline [j| `r` = `o` % `i` |]
genPrim _ _ Addr2IntOp [i] [_a,o] = PrimInline [j| `i` = `o`; |] -- only usable for comparisons within one range
genPrim _ _ Int2AddrOp [a,o] [i] = PrimInline [j| `a` = []; `o` = `i`; |] -- unsupported
genPrim _ _ AddrGtOp [r] [_a1,o1,_a2,o2] = PrimInline [j| `r` = (`o1` > `o2`) ? 1 : 0; |]
genPrim _ _ AddrGeOp [r] [_a1,o1,_a2,o2] = PrimInline [j| `r` = (`o1` >= `o2`) ? 1 : 0; |]
genPrim _ _ AddrEqOp [r] [a1,o1,a2,o2] = PrimInline [j| `r` = (`a1` === `a2` && `o1` === `o2`) ? 1 : 0; |]
genPrim _ _ AddrNeOp [r] [a1,o1,a2,o2] = PrimInline [j| `r` = (`a1` === `a2` && `o1` === `o2`) ? 1 : 0; |]
genPrim _ _ AddrLtOp [r] [_a1,o1,_a2,o2] = PrimInline [j| `r` = (`o1` < `o2`) ? 1 : 0; |]
genPrim _ _ AddrLeOp [r] [_a1,o1,_a2,o2] = PrimInline [j| `r` = (`o1` <= `o2`) ? 1 : 0; |]
-- addr indexing: unboxed arrays
genPrim _ _ IndexOffAddrOp_Char [c] [a,o,i] = PrimInline [j| `c` = `a`.u8[`o`+`i`]; |]
genPrim _ _ IndexOffAddrOp_WideChar [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getUint32(`o`+(`i`<<2),true); |]
genPrim _ _ IndexOffAddrOp_Int [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getInt32(`o`+(`i`<<2),true); |]
genPrim _ _ IndexOffAddrOp_Word [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getInt32(`o`+(`i`<<2),true); |]
genPrim _ _ IndexOffAddrOp_Addr [ca,co] [a,o,i] =
PrimInline [j| if(`a`.arr && `a`.arr[`o`+(`i`<<2)]) {
`ca` = `a`.arr[`o`+(`i`<<2)][0];
`co` = `a`.arr[`o`+(`i`<<2)][1];
} else {
`ca` = null;
`co` = 0;
}
|]
genPrim _ _ IndexOffAddrOp_Float [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getFloat32(`o`+(`i`<<2),true); |]
genPrim _ _ IndexOffAddrOp_Double [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getFloat64(`o`+(`i`<<3),true); |]
{-
IndexOffAddrOp_StablePtr
-}
genPrim _ _ IndexOffAddrOp_Int8 [c] [a,o,i] = PrimInline [j| `c` = `a`.u8[`o`+`i`]; |]
genPrim _ _ IndexOffAddrOp_Int16 [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getInt16(`o`+(`i`<<1),true); |]
genPrim _ _ IndexOffAddrOp_Int32 [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getInt32(`o`+(`i`<<2),true); |]
genPrim _ _ IndexOffAddrOp_Int64 [c1,c2] [a,o,i] =
PrimInline [j| `c1` = `a`.dv.getInt32(`o`+(`i`<<3),true);
`c2` = `a`.dv.getInt32(`o`+(`i`<<3)+4,true);
|]
genPrim _ _ IndexOffAddrOp_Word8 [c] [a,o,i] = PrimInline [j| `c` = `a`.u8[`o`+`i`]; |]
genPrim _ _ IndexOffAddrOp_Word16 [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getUint16(`o`+(`i`<<1),true); |]
genPrim _ _ IndexOffAddrOp_Word32 [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getInt32(`o`+(`i`<<2),true); |]
genPrim _ _ IndexOffAddrOp_Word64 [c1,c2] [a,o,i] =
PrimInline [j| `c1` = `a`.dv.getInt32(`o`+(`i`<<3),true);
`c2` = `a`.dv.getInt32(`o`+(`i`<<3)+4,true);
|]
genPrim _ _ ReadOffAddrOp_Char [c] [a,o,i] =
PrimInline [j| `c` = `a`.u8[`o`+`i`]; |]
genPrim _ _ ReadOffAddrOp_WideChar [c] [a,o,i] =
PrimInline [j| `c` = `a`.dv.getUint32(`o`+(`i`<<2),true); |]
genPrim _ _ ReadOffAddrOp_Int [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getInt32(`o`+(`i`<<2),true); |]
genPrim _ _ ReadOffAddrOp_Word [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getUint32(`o`+(`i`<<2),true); |]
genPrim _ _ ReadOffAddrOp_Addr [c1,c2] [a,o,i] =
PrimInline [j| var x = `i`<<2;
if(`a`.arr && `a`.arr[`o`+ x]) {
`c1` = `a`.arr[`o`+ x][0];
`c2` = `a`.arr[`o`+ x][1];
} else {
`c1` = null;
`c2` = 0;
}
|]
genPrim _ _ ReadOffAddrOp_Float [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getFloat32(`o`+(`i`<<2),true); |]
genPrim _ _ ReadOffAddrOp_Double [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getFloat64(`o`+(`i`<<3),true); |]
-- ReadOffAddrOp_StablePtr -- fixme
genPrim _ _ ReadOffAddrOp_Int8 [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getInt8(`o`+`i`); |]
genPrim _ _ ReadOffAddrOp_Int16 [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getInt16(`o`+(`i`<<1),true); |]
genPrim _ _ ReadOffAddrOp_Int32 [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getInt32(`o`+(`i`<<2),true); |]
genPrim _ _ ReadOffAddrOp_Word8 [c] [a,o,i] = PrimInline [j| `c` = `a`.u8[`o`+`i`]; |]
genPrim _ _ ReadOffAddrOp_Word16 [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getUint16(`o`+(`i`<<1),true); |]
genPrim _ _ ReadOffAddrOp_Word32 [c] [a,o,i] = PrimInline [j| `c` = `a`.dv.getUint32(`o`+(`i`<<2),true); |]
genPrim _ _ ReadOffAddrOp_Word64 [c1,c2] [a,o,i] =
PrimInline [j| `c1` = `a`.dv.getInt32(`o`+(`i`<<3),true);
`c2` = `a`.dv.getInt32(`o`+(`i`<<3)+4,true);
|]
genPrim _ _ WriteOffAddrOp_Char [] [a,o,i,v] = PrimInline [j| `a`.u8[`o`+`i`] = `v`; |]
genPrim _ _ WriteOffAddrOp_WideChar [] [a,o,i,v] = PrimInline [j| `a`.dv.setUint32(`o`+(`i`<<2), `v`,true); |]
genPrim _ _ WriteOffAddrOp_Int [] [a,o,i,v] = PrimInline [j| `a`.dv.setInt32(`o`+(`i`<<2), `v`,true); |]
genPrim _ _ WriteOffAddrOp_Word [] [a,o,i,v] = PrimInline [j| `a`.dv.setInt32(`o`+(`i`<<2), `v`,true); |]
genPrim _ _ WriteOffAddrOp_Addr [] [a,o,i,va,vo] =
PrimInline [j| if(!`a`.arr) { `a`.arr = []; }
`a`.arr[`o`+(`i`<<2)] = [`va`,`vo`];
|]
genPrim _ _ WriteOffAddrOp_Float [] [a,o,i,v] = PrimInline [j| `a`.dv.setFloat32(`o`+(`i`<<2), `v`,true); |]
genPrim _ _ WriteOffAddrOp_Double [] [a,o,i,v] = PrimInline [j| `a`.dv.setFloat64(`o`+(`i`<<3),`v`,true); |]
-- WriteOffAddrOp_StablePtr
genPrim _ _ WriteOffAddrOp_Int8 [] [a,o,i,v] = PrimInline [j| `a`.dv.setInt8(`o`+`i`, `v`); |]
genPrim _ _ WriteOffAddrOp_Int16 [] [a,o,i,v] = PrimInline [j| `a`.dv.setInt16(`o`+(`i`<<1), `v`, true); |]
genPrim _ _ WriteOffAddrOp_Int32 [] [a,o,i,v] = PrimInline [j| `a`.dv.setInt32(`o`+(`i`<<2), `v`, true); |]
genPrim _ _ WriteOffAddrOp_Int64 [] [a,o,i,v1,v2] = PrimInline [j| `a`.dv.setInt32(`o`+(`i`<<3), `v1`, true);
`a`.dv.setInt32(`o`+(`i`<<3)+4, `v2`, true);
|]
genPrim _ _ WriteOffAddrOp_Word8 [] [a,o,i,v] = PrimInline [j| `a`.u8[`o`+`i`] = `v`; |]
genPrim _ _ WriteOffAddrOp_Word16 [] [a,o,i,v] = PrimInline [j| `a`.dv.setUint16(`o`+(`i`<<1), `v`, true); |]
genPrim _ _ WriteOffAddrOp_Word32 [] [a,o,i,v] = PrimInline [j| `a`.dv.setUint32(`o`+(`i`<<2), `v`, true); |]
genPrim _ _ WriteOffAddrOp_Word64 [] [a,o,i,v1,v2] = PrimInline [j| `a`.dv.setUint32(`o`+(`i`<<3), `v1`, true);
`a`.dv.setUint32(`o`+(`i`<<3)+4, `v2`, true);
|]
genPrim _ _ NewMutVarOp [r] [x] = PrimInline [j| `r` = new h$MutVar(`x`); |]
genPrim _ _ ReadMutVarOp [r] [m] = PrimInline [j| `r` = `m`.val; |]
genPrim _ _ WriteMutVarOp [] [m,x] = PrimInline [j| `m`.val = `x`; |]
genPrim _ _ SameMutVarOp [r] [x,y] =
PrimInline [j| `r` = (`x` === `y`) ? 1 : 0; |]
genPrim _ _ AtomicModifyMutVarOp [r] [m,f] =
PrimInline [j| `r` = h$atomicModifyMutVar(`m`,`f`); |]
genPrim _ _ CasMutVarOp [status,r] [mv,o,n] =
PrimInline [j| if(`mv`.val === `o`) {
`status` = 0;
`r` = `n`; `mv`.val = `n`;
} else {
`status` = 1;
`r` = `mv`.val;
}
|]
genPrim _ _ CatchOp [_r] [a,handler] = PRPrimCall
[j| return h$catch(`a`, `handler`); |]
genPrim _ _ RaiseOp [_r] [a] = PRPrimCall [j| return h$throw(`a`,false); |]
genPrim _ _ RaiseIOOp [_r] [a] = PRPrimCall [j| return h$throw(`a`,false); |]
genPrim _ _ MaskAsyncExceptionsOp [_r] [a] =
PRPrimCall [j| return h$maskAsync(`a`); |]
genPrim _ _ MaskUninterruptibleOp [_r] [a] =
PRPrimCall [j| return h$maskUnintAsync(`a`); |]
genPrim _ _ UnmaskAsyncExceptionsOp [_r] [a] =
PRPrimCall [j| return h$unmaskAsync(`a`); |]
genPrim _ _ MaskStatus [r] [] = PrimInline [j| `r` = h$maskStatus(); |]
genPrim _ _ AtomicallyOp [_r] [a] = PRPrimCall [j| return h$atomically(`a`); |]
genPrim _ _ RetryOp [_r] [] = PRPrimCall [j| return h$stmRetry(); |]
genPrim _ _ CatchRetryOp [_r] [a,b] = PRPrimCall [j| return h$stmCatchRetry(`a`,`b`); |]
genPrim _ _ CatchSTMOp [_r] [a,h] = PRPrimCall [j| return h$catchStm(`a`,`h`); |]
genPrim _ _ Check [r] [a] = PrimInline [j| `r` = h$stmCheck(`a`); |]
genPrim _ _ NewTVarOp [tv] [v] = PrimInline [j| `tv` = h$newTVar(`v`); |]
genPrim _ _ ReadTVarOp [r] [tv] = PrimInline [j| `r` = h$readTVar(`tv`); |]
genPrim _ _ ReadTVarIOOp [r] [tv] = PrimInline [j| `r` = h$readTVarIO(`tv`); |]
genPrim _ _ WriteTVarOp [] [tv,v] = PrimInline [j| h$writeTVar(`tv`,`v`); |]
genPrim _ _ SameTVarOp [r] [tv1,tv2] = PrimInline [j| `r` = h$sameTVar(`tv1`,`tv2`) ? 1 : 0; |]
genPrim _ _ NewMVarOp [r] [] = PrimInline [j| `r` = new h$MVar(); |]
genPrim _ _ TakeMVarOp [_r] [m] = PRPrimCall [j| return h$takeMVar(`m`); |]
genPrim _ _ TryTakeMVarOp [r,v] [m] = PrimInline [j| `r` = h$tryTakeMVar(`m`);
`v` = `Ret1`;
|]
genPrim _ _ PutMVarOp [] [m,v] = PRPrimCall [j| return h$putMVar(`m`,`v`); |]
genPrim _ _ TryPutMVarOp [r] [m,v] = PrimInline [j| `r` = h$tryPutMVar(`m`,`v`) |]
genPrim _ _ ReadMVarOp [_r] [m] = PRPrimCall [j| return h$readMVar(`m`); |]
genPrim _ _ TryReadMVarOp [r,v] [m] = PrimInline [j| `v` = `m`.val;
`r` = (`v`===null) ? 0 : 1;
|]
genPrim _ _ SameMVarOp [r] [m1,m2] =
PrimInline [j| `r` = (`m1` === `m2`) ? 1 : 0; |]
genPrim _ _ IsEmptyMVarOp [r] [m] =
PrimInline [j| `r` = (`m`.val === null) ? 1 : 0; |]
genPrim _ _ DelayOp [] [t] = PRPrimCall [j| return h$delayThread(`t`); |]
genPrim _ _ WaitReadOp [] [fd] = PRPrimCall [j| return h$waitRead(`fd`); |]
genPrim _ _ WaitWriteOp [] [fd] = PRPrimCall [j| return h$waitWrite(`fd`); |]
genPrim _ _ ForkOp [tid] [x] = PrimInline [j| `tid` = h$fork(`x`, true); |]
genPrim _ _ ForkOnOp [tid] [_p,x] = PrimInline [j| `tid` = h$fork(`x`, true); |] -- ignore processor argument
genPrim _ _ KillThreadOp [] [tid,ex] =
PRPrimCall [j| return h$killThread(`tid`,`ex`); |]
genPrim _ _ YieldOp [] [] = PRPrimCall [j| return h$yield(); |]
genPrim _ _ MyThreadIdOp [r] [] = PrimInline [j| `r` = h$currentThread; |]
genPrim _ _ LabelThreadOp [] [t,la,lo] = PrimInline [j| `t`.label = [`la`,`lo`]; |]
genPrim _ _ IsCurrentThreadBoundOp [r] [] = PrimInline [j| `r` = 1; |]
genPrim _ _ NoDuplicateOp [] [] = PrimInline mempty -- don't need to do anything as long as we have eager blackholing
genPrim _ _ ThreadStatusOp [stat,cap,locked] [tid] = PrimInline
[j| `stat` = h$threadStatus(`tid`);
`cap` = `Ret1`;
`locked` = `Ret2`;
|]
genPrim _ _ MkWeakOp [r] [o,b,c] = PrimInline [j| `r` = h$makeWeak(`o`,`b`,`c`); |]
genPrim _ _ MkWeakNoFinalizerOp [r] [o,b] = PrimInline [j| `r` = h$makeWeakNoFinalizer(`o`,`b`); |]
genPrim _ _ AddCFinalizerToWeakOp [r] [_a1,_a1o,_a2,_a2o,_i,_a3,_a3o,_w] =
PrimInline [j| `r` = 1; |]
genPrim _ _ DeRefWeakOp [f,v] [w] = PrimInline [j| `v` = `w`.val;
`f` = (`v`===null) ? 0 : 1;
|]
genPrim _ _ FinalizeWeakOp [fl,fin] [w] =
PrimInline [j| `fin` = h$finalizeWeak(`w`);
`fl` = `Ret1`;
|]
genPrim _ _ TouchOp [] [_e] = PrimInline mempty -- fixme what to do?
genPrim _ _ MakeStablePtrOp [s1,s2] [a] = PrimInline [j| `s1` = h$makeStablePtr(`a`); `s2` = `Ret1`; |]
genPrim _ _ DeRefStablePtrOp [r] [s1,s2] = PrimInline [j| `r` = `s1`.arr[`s2`]; |]
genPrim _ _ EqStablePtrOp [r] [sa1,sa2,sb1,sb2] = PrimInline [j| `r` = (`sa1` === `sb1` && `sa2` === `sb2`) ? 1 : 0; |]
genPrim _ _ MakeStableNameOp [r] [a] = PrimInline [j| `r` = h$makeStableName(`a`); |]
genPrim _ _ EqStableNameOp [r] [s1,s2] = PrimInline [j| `r` = h$eqStableName(`s1`, `s2`); |]
genPrim _ _ StableNameToIntOp [r] [s] = PrimInline [j| `r` = h$stableNameInt(`s`); |]
genPrim _ _ ReallyUnsafePtrEqualityOp [r] [p1,p2] = PrimInline [j| `r` = `p1`===`p2`?1:0; |]
genPrim _ _ ParOp [r] [_a] = PrimInline [j| `r` = 0; |]
{-
SparkOp
-}
genPrim _ _ SeqOp [_r] [e] = PRPrimCall [j| return h$e(`e`); |]
{-
GetSparkOp
-}
genPrim _ _ NumSparks [r] [] = PrimInline [j| `r` = 0 |]
{-
ParGlobalOp
ParLocalOp
ParAtOp
ParAtAbsOp
ParAtRelOp
ParAtForNowOp
CopyableOp
NowFollowOp
-}
-- data may be the following:
-- false/true: bool
-- number: tag 0 (single constructor primitive data)
-- object: haskell heap object
genPrim _ t DataToTagOp [r] [d]
| isBoolTy t = PrimInline [j| `r` = `d`?1:0; |]
| Just (tc, _) <- splitTyConApp_maybe t, isProductTyCon tc
= PrimInline [j| `r` = 0; |]
| isAlgType t && not (isUnLiftedType t)
= PrimInline [j| `r` = `d`.f.a-1; |]
| otherwise =
PrimInline [j| `r` = (`d`===true)?1:((typeof `d` === 'object')?(`d`.f.a-1):0) |]
genPrim _ t TagToEnumOp [r] [tag]
| isBoolTy t = PrimInline [j| `r` = `tag`?true:false; |]
| otherwise = PrimInline [j| `r` = h$tagToEnum(`tag`) |]
genPrim _ _ AddrToAnyOp [r] [d,_o] = PrimInline [j| `r` = `d`; |]
{-
MkApUpd0_Op
NewBCOOp
UnpackClosureOp
GetApStackValOp
-}
-- stack trace/cost-centre operations
genPrim d _ GetCurrentCCSOp [a, o] [_dummy_arg] =
let ptr = if buildingProf d then [je| h$buildCCSPtr(`jCurrentCCS`) |]
else jnull
in PrimInline [j| `a` = `ptr`; `o` = 0; |]
genPrim d _ GetCCSOfOp [a, o] [obj]
| buildingProf d =
PrimInline [j| if (typeof(`obj`) === "object") {
`a` = h$buildCCSPtr(`obj`.cc); `o` = 0;
} else {
`a` = null; `o` = 0;
}
|]
| otherwise = PrimInline [j| `a` = null; `o` = 0; |]
genPrim _ _ TraceEventOp [] [ed,eo] = PrimInline [j| h$traceEvent(`ed`,`eo`); |]
genPrim _ _ TraceMarkerOp [] [ed,eo] = PrimInline [j| h$traceMarker(`ed`, `eo`); |]
#if __GLASGOW_HASKELL__ >= 709
genPrim _ _ CasArrayOp [s,o] [a,i,old,new] = PrimInline [j| var x = `a`[`i`]; if(x === `old`) { `o` = `new`; `a`[`i`] = `new`; `s` = 0; } else { `s` = 1; `o` = x; } |]
genPrim _ _ NewSmallArrayOp [a] [n,e] = PrimInline [j| `a` = new Array(`n`); for(var i=0;i<`n`;i++) { `a`[i] = `e`; `a`.m = 0; `a`.__ghcjsArray = true; } |]
genPrim _ _ SameSmallMutableArrayOp [r] [x,y] = PrimInline [j| `r` = (`x` === `y`) ? 1 : 0; |]
genPrim _ _ ReadSmallArrayOp [r] [a,i] = PrimInline [j| `r` = `a`[`i`]; |]
genPrim _ _ WriteSmallArrayOp [] [a,i,e] = PrimInline [j| `a`[`i`] = `e`; |]
genPrim _ _ SizeofSmallArrayOp [r] [a] = PrimInline [j| `r` = `a`.length; |]
genPrim _ _ SizeofSmallMutableArrayOp [r] [a] = PrimInline [j| `r` = `a`.length; |]
genPrim _ _ IndexSmallArrayOp [r] [a,i] = PrimInline [j| `r` = `a`[`i`]; |]
genPrim _ _ UnsafeFreezeSmallArrayOp [r] [a] = PrimInline [j| `r` = `a`; |]
genPrim _ _ UnsafeThawSmallArrayOp [r] [a] = PrimInline [j| `r` = `a`; |]
genPrim _ _ CopySmallArrayOp [] [s,si,d,di,n] = PrimInline [j| for(var i=`n`-1;i>=0;i--) { `d`[`di`+i] = `s`[`si`+i]; } |]
genPrim _ _ CopySmallMutableArrayOp [] [s,si,d,di,n] = PrimInline [j| for(var i=`n`-1;i>=0;i--) { `d`[`di`+i] = `s`[`si`+i]; } |]
genPrim _ _ CloneSmallArrayOp [r] [a,o,n] = PrimInline [j| `r` = `a`.slice(`o`,`o`+`n`); |]
genPrim _ _ CloneSmallMutableArrayOp [r] [a,o,n] = PrimInline [j| `r` = `a`.slice(`o`,`o`+`n`); |]
genPrim _ _ FreezeSmallArrayOp [r] [a,o,n] = PrimInline [j| `r` = `a`.slice(`o`,`o`+`n`); |]
genPrim _ _ ThawSmallArrayOp [r] [a,o,n] = PrimInline [j| `r` = `a`.slice(`o`,`o`+`n`); |]
genPrim _ _ CasSmallArrayOp [s,o] [a,i,old,new] = PrimInline [j| var x = `a`[`i`]; if(x === `old`) { `o` = `new`; `a`[`i`] = `new`; `s` = 0; } else { `s` = 1; `o` = x; } |]
genPrim _ _ AtomicReadByteArrayOp_Int [r] [a,i] = PrimInline [j| `r` = `a`.i3[`i`]; |]
genPrim _ _ AtomicWriteByteArrayOp_Int [] [a,i,v] = PrimInline [j| `a`.i3[`i`] = `v`; |]
genPrim _ _ CasByteArrayOp_Int [r] [a,i,old,new] = PrimInline [j| var t = `a`.i3[`i`]; `r` = t; if(t === `old`) { `a`.i3[`i`] = `new`; } |]
genPrim _ _ FetchAddByteArrayOp_Int [r] [a,i,v] = PrimInline [j| var t = `a`.i3[`i`]; `r` = t; `a`.i3[`i`] = t+`v`; |]
genPrim _ _ FetchSubByteArrayOp_Int [r] [a,i,v] = PrimInline [j| var t = `a`.i3[`i`]; `r` = t; `a`.i3[`i`] = t-`v`; |]
genPrim _ _ FetchAndByteArrayOp_Int [r] [a,i,v] = PrimInline [j| var t = `a`.i3[`i`]; `r` = t; `a`.i3[`i`] = t&`v`; |]
genPrim _ _ FetchOrByteArrayOp_Int [r] [a,i,v] = PrimInline [j| var t = `a`.i3[`i`]; `r` = t; `a`.i3[`i`] = (t|`v`); |]
genPrim _ _ FetchNandByteArrayOp_Int [r] [a,i,v] = PrimInline [j| var t = `a`.i3[`i`]; `r` = t; `a`.i3[`i`] = ~(t&`v`); |]
genPrim _ _ FetchXorByteArrayOp_Int [r] [a,i,v] = PrimInline [j| var t = `a`.i3[`i`]; `r` = t; `a`.i3[`i`] = t^`v`; |]
genPrim _ _ ClzOp [r] [x] = PrimInline [j| `r` = h$clz32(`x`); |]
genPrim _ _ Clz8Op [r] [x] = PrimInline [j| `r` = h$clz8(`x`); |]
genPrim _ _ Clz16Op [r] [x] = PrimInline [j| `r` = h$clz16(`x`); |]
genPrim _ _ Clz32Op [r] [x] = PrimInline [j| `r` = h$clz32(`x`); |]
genPrim _ _ Clz64Op [r] [x1,x2] = PrimInline [j| `r` = h$clz64(`x1`,`x2`); |]
genPrim _ _ CtzOp [r] [x] = PrimInline [j| `r` = h$ctz32(`x`); |]
genPrim _ _ Ctz8Op [r] [x] = PrimInline [j| `r` = h$ctz8(`x`); |]
genPrim _ _ Ctz16Op [r] [x] = PrimInline [j| `r` = h$ctz16(`x`); |]
genPrim _ _ Ctz32Op [r] [x] = PrimInline [j| `r` = h$ctz32(`x`); |]
genPrim _ _ Ctz64Op [r] [x1,x2] = PrimInline [j| `r` = h$ctz64(`x1`,`x2`); |]
#endif
genPrim _ _ op rs as = PrimInline [j| throw `"unhandled primop: " ++ show op ++ " " ++ show (length rs, length as)`; |]
{-
genPrim _ op rs as = PrimInline [j| log(`"warning, unhandled primop: "++show op++" "++show (length rs, length as)`);
`f`;
`copyRes`;
|]
where
f = ApplStat (iex . TxtI . T.pack $ "h$prim_" ++ show op) as
copyRes = mconcat $ zipWith (\r reg -> [j| `r` = `reg`; |]) rs (enumFrom Ret1)
-}
newByteArray :: JExpr -> JExpr -> JStat
newByteArray tgt len = [j| `tgt` = h$newByteArray(`len`); |]
newArray :: JExpr -> JExpr -> JExpr -> JStat
newArray tgt len elem = [j| `tgt` = h$newArray(`len`,`elem`); |]
two_24 :: Int
two_24 = 2^(24::Int)
| seereason/ghcjs | src/Gen2/Prim.hs | mit | 44,078 | 0 | 11 | 12,671 | 12,801 | 7,566 | 5,235 | 443 | 2 |
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..))
import Control.Monad (void)
import ETL (transform)
import qualified Data.Map as M
testCase :: String -> Assertion -> Test
testCase label assertion = TestLabel label (TestCase assertion)
main :: IO ()
main = void $ runTestTT $ TestList
[ TestList transformTests ]
transformTests :: [Test]
transformTests =
[ testCase "transform one value" $
M.fromList [("a", 1)] @=? transform (M.fromList [(1, ["A"])])
, testCase "transform multiple keys from one value" $
M.fromList [("a", 1), ("e", 1)] @=? transform (M.fromList [(1, ["A", "E"])])
, testCase "transform multiple keys from multiple values" $
M.fromList [("a", 1), ("b", 4)] @=?
transform (M.fromList [(1, ["A"]), (4, ["B"])])
, testCase "full dataset" $
M.fromList fullOut @=? transform (M.fromList fullIn)
]
fullOut :: [(String, Int)]
fullOut =
[ ("a", 1), ("b", 3), ("c", 3), ("d", 2), ("e", 1)
, ("f", 4), ("g", 2), ("h", 4), ("i", 1), ("j", 8)
, ("k", 5), ("l", 1), ("m", 3), ("n", 1), ("o", 1)
, ("p", 3), ("q", 10), ("r", 1), ("s", 1), ("t", 1)
, ("u", 1), ("v", 4), ("w", 4), ("x", 8), ("y", 4)
, ("z", 10) ]
fullIn :: [(Int, [String])]
fullIn =
[ (1, map (:[]) "AEIOULNRST")
, (2, ["D", "G"])
, (3, map (:[]) "BCMP")
, (4, map (:[]) "FHVWY")
, (5, ["K"])
, (8, ["J", "X"])
, (10, ["Q", "Z"])
] | tfausak/exercism-solutions | haskell/etl/etl_test.hs | mit | 1,380 | 0 | 12 | 290 | 739 | 451 | 288 | 37 | 1 |
module SpecHelper where
import Network.Wai
import Test.Hspec
import Test.Hspec.Wai
import Hasql as H
import Hasql.Backend as B
import Hasql.Postgres as P
import Data.String.Conversions (cs)
import Data.Monoid
import Data.Text hiding (map)
import qualified Data.Vector as V
import Control.Monad (void)
import Network.HTTP.Types.Header (Header, ByteRange, renderByteRange,
hRange, hAuthorization)
import Codec.Binary.Base64.String (encode)
import Data.CaseInsensitive (CI(..))
import Data.Maybe (fromMaybe)
import Text.Regex.TDFA ((=~))
import qualified Data.ByteString.Char8 as BS
import Network.Wai.Middleware.Cors (cors)
import System.Process (readProcess)
import qualified Data.Aeson.Types as J
import PostgREST.App (app)
import PostgREST.Config (AppConfig(..), corsPolicy)
import PostgREST.Middleware
import PostgREST.Error(errResponse)
isLeft :: Either a b -> Bool
isLeft (Left _ ) = True
isLeft _ = False
cfg :: AppConfig
cfg = AppConfig "postgrest_test" 5432 "postgrest_test" "" "localhost" 3000 "postgrest_anonymous" False 10 "1" "safe" "" "postgrest"
testPoolOpts :: PoolSettings
testPoolOpts = fromMaybe (error "bad settings") $ H.poolSettings 1 30
pgSettings :: P.Settings
pgSettings = P.ParamSettings (cs $ configDbHost cfg)
(fromIntegral $ configDbPort cfg)
(cs $ configDbUser cfg)
(cs $ configDbPass cfg)
(cs $ configDbName cfg)
withApp :: ActionWith Application -> IO ()
withApp perform = do
pool :: H.Pool P.Postgres
<- H.acquirePool pgSettings testPoolOpts
perform $ middle $ \req resp -> do
body <- strictRequestBody req
result <- liftIO $ H.session pool $ H.tx Nothing
$ authenticated cfg (app cfg body) req
either (resp . errResponse) resp result
where middle = cors corsPolicy
resetDb :: IO ()
resetDb = do
pool :: H.Pool P.Postgres
<- H.acquirePool pgSettings testPoolOpts
void . liftIO $ H.session pool $
H.tx Nothing $ do
H.unitEx [H.stmt| drop schema if exists "1" cascade |]
H.unitEx [H.stmt| drop schema if exists private cascade |]
H.unitEx [H.stmt| drop schema if exists postgrest cascade |]
loadFixture "roles"
loadFixture "schema"
loadFixture :: FilePath -> IO()
loadFixture name =
void $ readProcess "psql" ["-U", "postgrest_test", "-d", "postgrest_test", "-a", "-f", "test/fixtures/" ++ name ++ ".sql"] []
rangeHdrs :: ByteRange -> [Header]
rangeHdrs r = [rangeUnit, (hRange, renderByteRange r)]
rangeUnit :: Header
rangeUnit = ("Range-Unit" :: CI BS.ByteString, "items")
matchHeader :: CI BS.ByteString -> String -> [Header] -> Bool
matchHeader name valRegex headers =
maybe False (=~ valRegex) $ lookup name headers
authHeaderBasic :: String -> String -> Header
authHeaderBasic u p =
(hAuthorization, cs $ "Basic " ++ encode (u ++ ":" ++ p))
authHeaderJWT :: String -> Header
authHeaderJWT token =
(hAuthorization, cs $ "Bearer " ++ token)
testPool :: IO(H.Pool P.Postgres)
testPool = H.acquirePool pgSettings testPoolOpts
clearTable :: Text -> IO ()
clearTable table = do
pool <- testPool
void . liftIO $ H.session pool $ H.tx Nothing $
H.unitEx $ B.Stmt ("delete from \"1\"."<>table) V.empty True
createItems :: Int -> IO ()
createItems n = do
pool <- testPool
void . liftIO $ H.session pool $ H.tx Nothing txn
where
txn = mapM_ H.unitEx stmts
stmts = map [H.stmt|insert into "1".items (id) values (?)|] [1..n]
createNulls :: Int -> IO ()
createNulls n = do
pool <- testPool
void . liftIO $ H.session pool $ H.tx Nothing txn
where
txn = mapM_ H.unitEx (stmt':stmts)
stmt' = [H.stmt|insert into "1".no_pk (a,b) values (null,null)|]
stmts = map [H.stmt|insert into "1".no_pk (a,b) values (?,0)|] [1..n]
createNullInteger :: IO ()
createNullInteger = do
pool <- testPool
void . liftIO $ H.session pool $ H.tx Nothing $
H.unitEx $ [H.stmt| insert into "1".nullable_integer (a) values (null) |]
createLikableStrings :: IO ()
createLikableStrings = do
pool <- testPool
void . liftIO $ H.session pool $ H.tx Nothing $ do
H.unitEx $ insertSimplePk "xyyx" "u"
H.unitEx $ insertSimplePk "xYYx" "v"
where
insertSimplePk :: Text -> Text -> H.Stmt P.Postgres
insertSimplePk = [H.stmt|insert into "1".simple_pk (k, extra) values (?,?)|]
createJsonData :: IO ()
createJsonData = do
pool <- testPool
void . liftIO $ H.session pool $ H.tx Nothing $
H.unitEx $
[H.stmt|
insert into "1".json (data) values (?)
|]
(J.object [("foo", J.object [("bar", J.String "baz")])])
| framp/postgrest | test/SpecHelper.hs | mit | 4,642 | 0 | 17 | 977 | 1,538 | 816 | 722 | -1 | -1 |
module Helper (
module Test.Hspec
, module Test.Mockery.Directory
, module Control.Applicative
) where
import Test.Hspec
import Test.Mockery.Directory
import Control.Applicative
| phunehehe/hpack | test/Helper.hs | mit | 211 | 0 | 5 | 52 | 41 | 27 | 14 | 7 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UnicodeSyntax #-}
module TT.Exception where
import Abt.Class
import Abt.Types
import Control.Applicative
import Control.Monad
import Control.Monad.Catch
import Data.Traversable
import Data.Typeable
data DTm t =
DTm
{ _dtmTerm ∷ !t
, _dtmString ∷ !String
} deriving Typeable
instance Show (DTm t) where
show = _dtmString
renderTerm
∷ ( Abt v o t
, MonadVar v m
)
⇒ t Z
→ m (DTm (t Z))
renderTerm tm =
DTm tm <$> toString tm
renderError
∷ ( Abt v o t
, MonadVar v m
, Traversable e
)
⇒ e (t Z)
→ m (e (DTm (t Z)))
renderError = traverse renderTerm
throwTT
∷ ( MonadThrow m
, MonadVar v m
, Abt v o t
, Traversable e
, Exception (e (DTm (t Z)))
)
⇒ e (t Z)
→ m α
throwTT =
renderError >=> throwM
| jonsterling/tt-singletons | src/TT/Exception.hs | mit | 914 | 0 | 13 | 236 | 319 | 169 | 150 | 47 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Betfair.StreamingAPI.Responses.MarketChangeMessage
( MarketChangeMessage(..)
, marketIds
) where
import Data.Aeson.TH (Options (omitNothingFields),
defaultOptions, deriveJSON)
import Protolude
import Text.PrettyPrint.GenericPretty
import Betfair.APING
import Betfair.StreamingAPI.Types.ChangeType
import Betfair.StreamingAPI.Types.MarketChange
import qualified Betfair.StreamingAPI.Types.MarketChange as MC
import Betfair.StreamingAPI.Types.SegmentType
data MarketChangeMessage = MarketChangeMessage
{ op :: Text
, id :: Integer -- Client generated unique id to link request with response (like json rpc)
, ct :: Maybe ChangeType -- Change Type - set to indicate the type of change - if null this is a delta),
, clk :: Maybe Text -- Token value (non-null) should be stored and passed in a MarketSubscriptionMessage to resume subscription (in case of disconnect)
, status :: Maybe Int -- By default, when the stream data is up to date the value is set to null and will be set to 503 when the stream data is unreliable (i.e. not all bets and markets changes will be reflected on the stream) due to an increase in push latency. Clients shouldn't disconnect if status 503 is returned; when the stream recovers updates will be sent containing the latest data. The status is sent per each subscription on heartbeats and change messages.
, heartbeatMs :: Maybe Integer -- Heartbeat Milliseconds - the heartbeat rate (may differ from requested: bounds are 500 to 30000),
, pt :: Integer -- Publish Time (in millis since epoch) that the changes were generated,
, initialClk :: Maybe Text -- Token value (non-null) should be stored and passed in a MarketSubscriptionMessage to resume subscription (in case of disconnect)
, mc :: Maybe [MarketChange] -- MarketChanges - the modifications to markets (will be null on a heartbeat,
, conflateMs :: Maybe Integer -- Conflate Milliseconds - the conflation rate (may differ from that requested if subscription is delayed),
, segmentType :: Maybe SegmentType -- Segment Type - if the change is split into multiple segments, this denotes the beginning and end of a change, and segments in between. Will be null if data is not segmented,
} deriving (Eq, Read, Show, Generic, Pretty)
$(deriveJSON defaultOptions {omitNothingFields = True} ''MarketChangeMessage)
marketIds :: MarketChangeMessage -> [MarketId]
marketIds = maybe [] (fmap MC.id) . mc
| joe9/streaming-betfair-api | src/Betfair/StreamingAPI/Responses/MarketChangeMessage.hs | mit | 2,745 | 0 | 10 | 568 | 284 | 176 | 108 | 33 | 1 |
{-# LANGUAGE
LambdaCase
, NamedFieldPuns
#-}
module ProjectEuler.CommandLine
( main
) where
import Control.Applicative
import Data.List
import System.Environment
import System.Exit
import qualified Data.Map.Strict as M
import ProjectEuler.CommandLine.CmdRun
import ProjectEuler.CommandLine.CmdCreate
import ProjectEuler.CommandLine.CmdSync
import ProjectEuler.CommandLine.CmdReport
import ProjectEuler.CommandLine.CmdBenchmark
import ProjectEuler.CommandLine.CmdGood
{-
Main binary is named "pet" for ProjectEuler Toolkit.
Note that some sub commands would require
environment variable "PROJECT_EULER_HOME" to point to project home directory.
-}
{-
first do a regular lookup, this allows us to do exact match
if one of those sub commands happens to be the prefix of the other.
then fallback to succeed as long as the given key
matches exactly one result (by prefix)
-}
uniqueLookup :: (Eq ke, Ord ke) => [ke] -> M.Map [ke] v -> Maybe v
uniqueLookup k m =
M.lookup k m
<|> case filter ((k `isPrefixOf`) . fst) $ M.toList m of
[(_,v)] -> Just v
_ -> Nothing
subCmds :: M.Map String ([String] -> IO ())
subCmds = M.fromList
[ ( "run"
{- `pet run <problem id>` executes solution for a program. -}
, cmdRun
)
, ( "exec"
{- same as `pet run` -}
, cmdRun
)
, ( "new"
{-
`pet new <problem id>` sets up templates for a new problem.
-}
, cmdCreate
)
, ( "create"
{- same as `pet new` -}
, cmdCreate
)
, ( "sync"
{-
`pet sync` updates some files automatically:
- it scans the directory to collect the list of problems
and update related file accordingly.
- it scans data files and list them in comments of ProjectEuler.GetData.
Note that this subcommand doesn't try to build the project
after updating related files, so your next `pet` run is very likely
to rebuild.
TODO: see if we can somehow rebuild automatically
if there are actual file updates.
-}
, cmdSync
)
, ( "report"
{-
`pet report` runs all problems marked as solved,
make sure the output is expected, and report about time elapsed
for each of the solutions.
-}
, cmdReport
)
, ( "benchmark"
{- `pet benchmark <problem id> [...benchmark options...]` -}
, cmdBenchmark
)
, ( "good"
{- `pet good <problem id` marks a problem as solved and record its output -}
, cmdGood
)
]
{-
TODO: planned features:
- `pet data` we might use this command to download data files from
ProjectEuler's website.
-}
main :: IO ()
main = getArgs >>= \case
cmd:args' | Just action <- uniqueLookup cmd subCmds -> action args'
_ -> do
putStrLn $ "pet <" <> intercalate "|" (M.keys subCmds) <> ">"
exitFailure
| Javran/Project-Euler | src/ProjectEuler/CommandLine.hs | mit | 2,858 | 0 | 16 | 745 | 404 | 232 | 172 | 46 | 2 |
{-# OPTIONS
-XMultiParamTypeClasses
-XFunctionalDependencies
-XMultiWayIf
-XFlexibleInstances
-XFlexibleContexts
#-}
module TreeState (Substitution, Substitution2, MState, TreeState, TreeState', MStater, MTreeState, MTreeState', put2, replaceVal, joinWith, repeatUntilState, graftPattern, matchJustSymbol, matchJustSymbol', isInteger, formulaToPattern, parsePattern, patternMatch, patternMatch', hasInt) where
import System.Environment
import Control.Monad
import Data.Tree
import Control.Monad.Trans.State
import Data.Map.Strict as M
import Data.List as L
import Utilities
import Search
import MathParser
import Formulas
{-| A substitution tells us which atoms (typically variables) to replace with which formulas.-}
type Substitution = M.Map Atom Formula
type Substitution2 = M.Map Atom Atom
{-| A state that has a Maybe b. -}
type MState s b = StateT s Maybe b
{-| The state is given by a formula (the subtree that the parser is looking at). -}
type TreeState c = StateT Formula Maybe c
{-| The state is a formula, and the return value is a substitution. This is the workhorse of pattern matching in a tree. -}
type TreeState' = TreeState Substitution
type MStater s b = b -> MState s b
type MTreeState c = c -> TreeState c
type MTreeState' = Substitution -> TreeState'
-- * Basic functions for MState
put2 :: s -> b -> MState s b
put2 s' b' = state $ (\_ -> (b',s'))
replaceVal :: MState s c -> b -> MState s b
replaceVal s1 x = s1 >> (return x)
{-| Given a way to generate children from a state (ex. if a state is a tree), and a list of functions corresponding to the children, chain them together to make another function. -}
joinWith :: (s -> [s]) -> [MStater s b] -> MStater s b
joinWith childs staters b1 =
do
s1 <- get
let ss = childs s1
--put the state in and then do g.
(foldl1 (>=>) $ L.map (\(si, g) -> (put2 si) >=> g) $ zip ss staters) b1
repeatUntilState :: b -> (b -> Bool) -> MStater a b -> MState a b
repeatUntilState startB testB ms = do
curB <- ms startB
if testB curB
then return curB
else repeatUntilState curB testB ms
-- * Functions for MTreeState.
{-| joinWith specialized to MTreeState. Give the function corresponding to the root and to the children. -}
graftPattern :: MTreeState c -> [MTreeState c] -> MTreeState c
graftPattern rootF childFs = joinWith (\input -> input:(children input)) (rootF:childFs)
{-| try to match the current node (root of the current tree) with the atom. Returns Nothing if it fails. -}
matchJustSymbol :: Atom -> TreeState ()
matchJustSymbol atom = StateT (\f -> if root f == atom
then Just ((),f)
else Nothing)
matchJustSymbol' :: Atom -> MTreeState'
matchJustSymbol' atom = replaceVal (matchJustSymbol atom)
matchVar :: Atom -> Substitution -> TreeState Substitution
matchVar x s = StateT (\f->
case M.lookup x s of
Nothing -> Just (M.insert x f s, f) --insert the "x=f" in the substitution
Just f2 ->
if f2 == f
then Just (s, f) --"x=f" is already in the substitution
else Nothing --"x=g, g/=f" is in the substitution, so fail.
)
--from http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Haskell
isInteger s = case reads s :: [(Integer, String)] of
[(_, "")] -> True
_ -> False
formulaToPattern :: Formula -> MTreeState'
formulaToPattern tr =
let
symb = root tr
cs = children tr
patts = fmap formulaToPattern cs
rootPattern = case symb of
AStr ('?':_) -> matchVar symb --vs. JustVar
_ -> matchJustSymbol' symb
in
graftPattern rootPattern patts
{-| Use this to create pattern matchers, for example
parsePattern "range(?1,?2)"
See PatternMatchers.hs.
-}
parsePattern :: String -> MTreeState'
parsePattern = formulaToPattern . parseFun
patternMatch :: MTreeState' -> Formula -> Maybe [Formula]
patternMatch mts f =
do
subs <- evalStateT (mts M.empty) f
return $ elems subs
patternMatch' :: MTreeState' -> Formula -> Maybe [Int]
patternMatch' x y = fmap (L.map formulaToInt) $ patternMatch x y
hasInt :: Substitution2 -> Bool
hasInt = (any (\x -> case x of
AInt _ -> True
_ -> False)) . M.keys
| holdenlee/fluidity | SeekWhence/formulas/TreeState.hs | mit | 4,478 | 0 | 16 | 1,166 | 1,102 | 592 | 510 | 78 | 3 |
{-# LANGUAGE Arrows, NoMonomorphismRestriction #-}
module Data.Expenses.Ledger.Xml
( Amount(..)
, Posting(..)
, Transaction(..)
, transactionsInXmlDocument
, simpleTransactionFromTransaction
, simpleTransactionsInXmlDocument
, textAsDecimal
) where
import qualified Data.Decimal as D
import Data.Maybe (mapMaybe, maybeToList)
import qualified Text.XML.HXT.Core as HXT
import Text.XML.HXT.Core ((/>), (>>>), (<<<))
import Text.XML.HXT.DOM.TypeDefs (XmlTree)
import Text.Read (readMaybe)
import qualified Data.Expenses.Types as ET
-- | Data type for the @\<amount\>@ element in a ledger XML document.
data Amount = Amount { amountCurrency :: String, amountQuantity :: D.Decimal }
deriving (Show, Eq)
-- | Data type for the @\<posting\>@ element in a ledger XML document.
data Posting = Posting { postingAccount :: String, postingAmount :: Amount }
deriving (Show, Eq)
-- | Data type for the @\<transaction\>@ element in a ledger XML document.
data Transaction = Transaction
{ transactionDate :: String
, transactionPayee :: String
, transactionPostings :: [Posting]
}
deriving (Show, Eq)
getChildText :: HXT.ArrowXml a => String -> a XmlTree String
getChildText child =
proc f -> do
node <- HXT.hasName child <<< HXT.getChildren -< f
s <- HXT.getText <<< HXT.getChildren -< node
HXT.returnA -< s
getNestedText :: HXT.ArrowXml a => String -> String -> a XmlTree String
getNestedText child1 child2 =
proc f -> do
node1 <- HXT.hasName child1 <<< HXT.getChildren -< f
node2 <- HXT.hasName child2 <<< HXT.getChildren -< node1
s <- HXT.getText <<< HXT.getChildren -< node2
HXT.returnA -< s
-- | Results in a parsed number, or empty if the string is not numeric.
textAsDecimal :: HXT.ArrowList a => a String D.Decimal
textAsDecimal =
HXT.arrL $ maybeToList . readMaybe
-- | An 'Amount' from an @\<amount\>@ XML element.
amount :: HXT.ArrowXml a => a XmlTree Amount
amount =
HXT.hasName "amount" >>>
proc a -> do
amtCurrency <- getNestedText "commodity" "symbol" -< a
amtQuantity <- textAsDecimal <<< getChildText "quantity" -< a
HXT.returnA -< Amount { amountCurrency = amtCurrency
, amountQuantity = amtQuantity
}
-- | An 'Amount' from a @\<posting\>@ XML element.
postAmount :: HXT.ArrowXml a => a XmlTree Amount
postAmount =
HXT.hasName "posting" />
HXT.hasName "post-amount" />
HXT.hasName "amount" >>>
amount
-- | 'Posting's from a given @\<transaction\>@ element.
postings :: HXT.ArrowXml a => a XmlTree [Posting]
postings =
HXT.listA $
HXT.hasName "transaction" />
HXT.hasName "postings" />
HXT.hasName "posting" >>>
proc p -> do
pstAccount <- getNestedText "account" "name" -< p
pstAmount <- postAmount -< p
HXT.returnA -< Posting { postingAccount = pstAccount
, postingAmount = pstAmount
}
-- | 'Transaction' from a @\<transaction\>@ element.
transaction :: HXT.ArrowXml a => a XmlTree Transaction
transaction =
HXT.hasName "transaction" >>>
proc txn -> do
txnPayee <- getChildText "payee" -< txn
txnDate <- getChildText "date" -< txn
txnPostings <- postings -< txn
HXT.returnA -< Transaction { transactionDate = txnDate
, transactionPayee = txnPayee
, transactionPostings = txnPostings
}
-- | 'Transaction's from a @\<ledger\>@ XML document.
transactions :: HXT.ArrowXml a => a XmlTree Transaction
transactions =
HXT.hasName "ledger" />
HXT.hasName "transactions" />
HXT.hasName "transaction" >>>
transaction
-- | 'Transaction's from an XML document.
transactionsInXmlDocument :: String -> [Transaction]
transactionsInXmlDocument =
HXT.runLA (HXT.xreadDoc >>> transactions)
-- | 'SimpleTransaction's from an XML document.
simpleTransactionsInXmlDocument :: String -> [ET.SimpleTransaction]
simpleTransactionsInXmlDocument doc =
mapMaybe simpleTransactionFromTransaction $ transactionsInXmlDocument doc
simpleTransactionFromTransaction :: Transaction -> Maybe ET.SimpleTransaction
-- Pattern match Transaction for case with two postings.
simpleTransactionFromTransaction
Transaction
{ transactionPayee = payee
, transactionPostings =
[ Posting
{ postingAccount = acct0
, postingAmount =
Amount
{ amountCurrency = currency0
, amountQuantity = quantity0
}
}
, Posting
{ postingAccount = acct1
, postingAmount =
Amount
{ amountCurrency = currency1
, amountQuantity = quantity1
}
}
]
}
-- Guard the two postings have suitable, simple values.
-- (Same currency and same amount).
| currency0 == currency1 && quantity0 == -1 * quantity1 =
let
(debittedAccount, credittedAccount) =
if quantity0 > 0 then
(acct0, acct1)
else
(acct1, acct0)
in
Just $
ET.SimpleTransaction
{ ET.transactionDescription = payee
, ET.transactionAmount = ET.Amount
{ ET.moneyAmount = quantity0
, ET.moneyCurrency = Just currency0
, ET.moneyIsApprox = False
}
, ET.transactionDebittedAccount = debittedAccount
, ET.transactionCredittedAccount = credittedAccount
}
| otherwise = Nothing
simpleTransactionFromTransaction _ = Nothing
| rgoulter/expenses-csv-utils | src/Data/Expenses/Ledger/Xml.hs | mit | 5,583 | 5 | 15 | 1,449 | 1,236 | 667 | 569 | 122 | 2 |
{-# LANGUAGE DeriveGeneric, RecordWildCards #-}
module Network.Traffic.Object.Timeline
( Timeline
, Duration (..)
, timeline
, totalPlaytime
, lastObjectTime
) where
import Control.Applicative ((<$>))
import Control.DeepSeq (NFData)
import Control.Monad.ST
import Data.STRef
import qualified Data.Vector as V
import GHC.Generics (Generic)
import Network.Traffic.Object.Types ( Object (..)
, ObjectVector )
import Text.Printf (printf)
type Timeline = V.Vector (ObjectVector, ObjectVector)
data Duration = Seconds !Float
| Milliseconds !Float
| Microseconds !Float
deriving (Generic)
instance NFData Duration where
instance Show Duration where
show (Seconds t) = printf "%.2f seconds" t
show (Milliseconds t) = printf "%.2f milliseconds" t
show (Microseconds t) = printf "%.2f microseconds" t
timeline :: ObjectVector -> Duration -> Timeline
timeline objects resolution =
let totalPlaytime' = totalPlaytime objects
unit = toSeconds resolution
units' = units totalPlaytime' unit
in runST $ do
vector <- newSTRef objects
live <- newSTRef V.empty
V.generateM units' $ \index -> do
let nextStartTime = unit `mult` (index + 1)
(starters, remaining) <-
V.partition (startIfLessThan nextStartTime) <$> readSTRef vector
writeSTRef vector remaining
live' <- V.filter (stopIfLessThan nextStartTime) <$> readSTRef live
writeSTRef live $ live' V.++ starters
return (starters, live')
startIfLessThan :: Float -> Object -> Bool
startIfLessThan t Object {..} = timestamp < t
stopIfLessThan :: Float -> Object -> Bool
stopIfLessThan t Object {..} = (timestamp + duration) >= t
totalPlaytime :: ObjectVector -> Duration
totalPlaytime = Seconds . V.foldl' greatest 0
where
greatest :: Float -> Object -> Float
{-# INLINE greatest #-}
greatest acc Object {..} = max acc (timestamp + duration)
lastObjectTime :: ObjectVector -> Duration
lastObjectTime = Seconds . timestamp . V.last
units :: Duration -> Duration -> Int
units (Seconds dur) (Seconds res) = ceiling $ dur / res
units dur res = units (toSeconds dur) (toSeconds res)
toSeconds :: Duration -> Duration
toSeconds (Microseconds us) = Seconds (us * 0.000001)
toSeconds (Milliseconds ms) = Seconds (ms * 0.001)
toSeconds s = s
mult :: Duration -> Int -> Float
mult (Seconds s) = mult' s
mult (Milliseconds ms) = mult' ms
mult (Microseconds us) = mult' us
mult' :: Float -> Int -> Float
{-# INLINE mult' #-}
mult' t f = t * fromIntegral f
| kosmoskatten/traffic-analysis | src/Network/Traffic/Object/Timeline.hs | mit | 2,670 | 0 | 19 | 650 | 837 | 435 | 402 | 73 | 1 |
{-|
Module : CodeGen.LLVM.Transformer
Description : Transform LLVM ASTs into other forms.
Copyright : (c) Michael Lopez, 2017
License : MIT
Maintainer : m-lopez (github)
Stability : unstable
Portability : non-portable
-}
module CodeGen.LLVM.Transformer ( toReadableLlvmIr ) where
import CodeGen.LLVM.Ast ( toLlvmModuleAst )
import Data.ByteString.Char8 ( unpack )
import Expressions ( TlExpr )
import LLVM.AST ( Module )
import LLVM.Context ( withContext )
import LLVM.Module ( moduleLLVMAssembly, withModuleFromAST )
import Util.DebugOr ( DebugOr )
-- | Transform an LLVM.AST.Module into human-readable LLVM IR.
fromASTtoLlvmIr :: Module -> IO String
fromASTtoLlvmIr m = unpack <$> (withContext $ fromModAndCtx m)
where
fromModAndCtx x y = withModuleFromAST y x moduleLLVMAssembly
-- | Attempt to translate a Toaster module into human-readable LLVM IR.
toReadableLlvmIr :: [TlExpr] -> DebugOr (IO String)
toReadableLlvmIr prgm = do
ast <- toLlvmModuleAst prgm
return $ fromASTtoLlvmIr ast
| m-lopez/jack | src/CodeGen/LLVM/Transformer.hs | mit | 1,018 | 0 | 8 | 166 | 190 | 105 | 85 | 15 | 1 |
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Com.Mysql.Cj.Mysqlx.Protobuf.ClientMessages.Type (Type(..)) where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified GHC.Generics as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data Type = CON_CAPABILITIES_GET
| CON_CAPABILITIES_SET
| CON_CLOSE
| SESS_AUTHENTICATE_START
| SESS_AUTHENTICATE_CONTINUE
| SESS_RESET
| SESS_CLOSE
| SQL_STMT_EXECUTE
| CRUD_FIND
| CRUD_INSERT
| CRUD_UPDATE
| CRUD_DELETE
| EXPECT_OPEN
| EXPECT_CLOSE
| CRUD_CREATE_VIEW
| CRUD_MODIFY_VIEW
| CRUD_DROP_VIEW
deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic)
instance P'.Mergeable Type
instance Prelude'.Bounded Type where
minBound = CON_CAPABILITIES_GET
maxBound = CRUD_DROP_VIEW
instance P'.Default Type where
defaultValue = CON_CAPABILITIES_GET
toMaybe'Enum :: Prelude'.Int -> P'.Maybe Type
toMaybe'Enum 1 = Prelude'.Just CON_CAPABILITIES_GET
toMaybe'Enum 2 = Prelude'.Just CON_CAPABILITIES_SET
toMaybe'Enum 3 = Prelude'.Just CON_CLOSE
toMaybe'Enum 4 = Prelude'.Just SESS_AUTHENTICATE_START
toMaybe'Enum 5 = Prelude'.Just SESS_AUTHENTICATE_CONTINUE
toMaybe'Enum 6 = Prelude'.Just SESS_RESET
toMaybe'Enum 7 = Prelude'.Just SESS_CLOSE
toMaybe'Enum 12 = Prelude'.Just SQL_STMT_EXECUTE
toMaybe'Enum 17 = Prelude'.Just CRUD_FIND
toMaybe'Enum 18 = Prelude'.Just CRUD_INSERT
toMaybe'Enum 19 = Prelude'.Just CRUD_UPDATE
toMaybe'Enum 20 = Prelude'.Just CRUD_DELETE
toMaybe'Enum 24 = Prelude'.Just EXPECT_OPEN
toMaybe'Enum 25 = Prelude'.Just EXPECT_CLOSE
toMaybe'Enum 30 = Prelude'.Just CRUD_CREATE_VIEW
toMaybe'Enum 31 = Prelude'.Just CRUD_MODIFY_VIEW
toMaybe'Enum 32 = Prelude'.Just CRUD_DROP_VIEW
toMaybe'Enum _ = Prelude'.Nothing
instance Prelude'.Enum Type where
fromEnum CON_CAPABILITIES_GET = 1
fromEnum CON_CAPABILITIES_SET = 2
fromEnum CON_CLOSE = 3
fromEnum SESS_AUTHENTICATE_START = 4
fromEnum SESS_AUTHENTICATE_CONTINUE = 5
fromEnum SESS_RESET = 6
fromEnum SESS_CLOSE = 7
fromEnum SQL_STMT_EXECUTE = 12
fromEnum CRUD_FIND = 17
fromEnum CRUD_INSERT = 18
fromEnum CRUD_UPDATE = 19
fromEnum CRUD_DELETE = 20
fromEnum EXPECT_OPEN = 24
fromEnum EXPECT_CLOSE = 25
fromEnum CRUD_CREATE_VIEW = 30
fromEnum CRUD_MODIFY_VIEW = 31
fromEnum CRUD_DROP_VIEW = 32
toEnum
= P'.fromMaybe
(Prelude'.error "hprotoc generated code: toEnum failure for type Com.Mysql.Cj.Mysqlx.Protobuf.ClientMessages.Type")
. toMaybe'Enum
succ CON_CAPABILITIES_GET = CON_CAPABILITIES_SET
succ CON_CAPABILITIES_SET = CON_CLOSE
succ CON_CLOSE = SESS_AUTHENTICATE_START
succ SESS_AUTHENTICATE_START = SESS_AUTHENTICATE_CONTINUE
succ SESS_AUTHENTICATE_CONTINUE = SESS_RESET
succ SESS_RESET = SESS_CLOSE
succ SESS_CLOSE = SQL_STMT_EXECUTE
succ SQL_STMT_EXECUTE = CRUD_FIND
succ CRUD_FIND = CRUD_INSERT
succ CRUD_INSERT = CRUD_UPDATE
succ CRUD_UPDATE = CRUD_DELETE
succ CRUD_DELETE = EXPECT_OPEN
succ EXPECT_OPEN = EXPECT_CLOSE
succ EXPECT_CLOSE = CRUD_CREATE_VIEW
succ CRUD_CREATE_VIEW = CRUD_MODIFY_VIEW
succ CRUD_MODIFY_VIEW = CRUD_DROP_VIEW
succ _ = Prelude'.error "hprotoc generated code: succ failure for type Com.Mysql.Cj.Mysqlx.Protobuf.ClientMessages.Type"
pred CON_CAPABILITIES_SET = CON_CAPABILITIES_GET
pred CON_CLOSE = CON_CAPABILITIES_SET
pred SESS_AUTHENTICATE_START = CON_CLOSE
pred SESS_AUTHENTICATE_CONTINUE = SESS_AUTHENTICATE_START
pred SESS_RESET = SESS_AUTHENTICATE_CONTINUE
pred SESS_CLOSE = SESS_RESET
pred SQL_STMT_EXECUTE = SESS_CLOSE
pred CRUD_FIND = SQL_STMT_EXECUTE
pred CRUD_INSERT = CRUD_FIND
pred CRUD_UPDATE = CRUD_INSERT
pred CRUD_DELETE = CRUD_UPDATE
pred EXPECT_OPEN = CRUD_DELETE
pred EXPECT_CLOSE = EXPECT_OPEN
pred CRUD_CREATE_VIEW = EXPECT_CLOSE
pred CRUD_MODIFY_VIEW = CRUD_CREATE_VIEW
pred CRUD_DROP_VIEW = CRUD_MODIFY_VIEW
pred _ = Prelude'.error "hprotoc generated code: pred failure for type Com.Mysql.Cj.Mysqlx.Protobuf.ClientMessages.Type"
instance P'.Wire Type where
wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum)
wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum)
wireGet 14 = P'.wireGetEnum toMaybe'Enum
wireGet ft' = P'.wireGetErr ft'
wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum
wireGetPacked ft' = P'.wireGetErr ft'
instance P'.GPB Type
instance P'.MessageAPI msg' (msg' -> Type) Type where
getVal m' f' = f' m'
instance P'.ReflectEnum Type where
reflectEnum
= [(1, "CON_CAPABILITIES_GET", CON_CAPABILITIES_GET), (2, "CON_CAPABILITIES_SET", CON_CAPABILITIES_SET),
(3, "CON_CLOSE", CON_CLOSE), (4, "SESS_AUTHENTICATE_START", SESS_AUTHENTICATE_START),
(5, "SESS_AUTHENTICATE_CONTINUE", SESS_AUTHENTICATE_CONTINUE), (6, "SESS_RESET", SESS_RESET), (7, "SESS_CLOSE", SESS_CLOSE),
(12, "SQL_STMT_EXECUTE", SQL_STMT_EXECUTE), (17, "CRUD_FIND", CRUD_FIND), (18, "CRUD_INSERT", CRUD_INSERT),
(19, "CRUD_UPDATE", CRUD_UPDATE), (20, "CRUD_DELETE", CRUD_DELETE), (24, "EXPECT_OPEN", EXPECT_OPEN),
(25, "EXPECT_CLOSE", EXPECT_CLOSE), (30, "CRUD_CREATE_VIEW", CRUD_CREATE_VIEW), (31, "CRUD_MODIFY_VIEW", CRUD_MODIFY_VIEW),
(32, "CRUD_DROP_VIEW", CRUD_DROP_VIEW)]
reflectEnumInfo _
= P'.EnumInfo
(P'.makePNF (P'.pack ".Mysqlx.ClientMessages.Type") [] ["Com", "Mysql", "Cj", "Mysqlx", "Protobuf", "ClientMessages"] "Type")
["Com", "Mysql", "Cj", "Mysqlx", "Protobuf", "ClientMessages", "Type.hs"]
[(1, "CON_CAPABILITIES_GET"), (2, "CON_CAPABILITIES_SET"), (3, "CON_CLOSE"), (4, "SESS_AUTHENTICATE_START"),
(5, "SESS_AUTHENTICATE_CONTINUE"), (6, "SESS_RESET"), (7, "SESS_CLOSE"), (12, "SQL_STMT_EXECUTE"), (17, "CRUD_FIND"),
(18, "CRUD_INSERT"), (19, "CRUD_UPDATE"), (20, "CRUD_DELETE"), (24, "EXPECT_OPEN"), (25, "EXPECT_CLOSE"),
(30, "CRUD_CREATE_VIEW"), (31, "CRUD_MODIFY_VIEW"), (32, "CRUD_DROP_VIEW")]
instance P'.TextType Type where
tellT = P'.tellShow
getT = P'.getRead | naoto-ogawa/h-xproto-mysql | src/Com/Mysql/Cj/Mysqlx/Protobuf/ClientMessages/Type.hs | mit | 6,348 | 0 | 11 | 1,032 | 1,553 | 862 | 691 | 138 | 1 |
{-# LANGUAGE DeriveGeneric, FlexibleInstances, RankNTypes #-}
-- | This module contains data types for actions.
module Game.Cosanostra.Types
( -- * Actions
ActionType(..)
, Compulsion(..)
, SelectorAtom(..)
, Selector
, ActionGroup
, Action(..)
, ActionTraits(..)
, Act(..)
, ActTrace(..)
-- * Constraints
, ConstraintAtom(..)
, Constraint
-- * Effects
, CauseOfDeath(..)
, EffectType(..)
, Effect(..)
, EffectTrace(..)
-- * Players
, Player(..)
-- * Factions
, Faction(..)
, FactionTraits(..)
-- * Messages
, MessageInfo(..)
, Message(..)
-- * Game
, Turn
, Phase(..)
, Game(..)
-- * Plan
, PlanBinding(..)
, PlanError(..)
, Plan
, PlannerInfo(..)
, Planner
-- * Ballot
, Consensus(..)
, Ballot
, Tally
-- * Collections
, Expr(..)
, Players(..)
, Factions
, Actions
, ActionGroups
) where
import Control.Lens
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.State
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import qualified Data.Text as T
import GHC.Generics (Generic)
import System.Random
-- | Distinct actions that can be performed.
data ActionType = Visit
-- ^ Visits a target.
| FruitVend
-- ^ Gives a target some fruit.
| Greet
-- ^ Greet a target with your faction.
| Roleblock
-- ^ Stop a target from performing their action.
| Rolestop
-- ^ Stop a target from having actions performed on them, except
-- strongman kills.
| Protect
-- ^ Protect a target from death.
| Kill
-- ^ Kill a target.
| StrongmanKill
-- ^ Kill a target, ignoring bulletproof.
| DesperadoKill { _actionTypeKillableFactions :: S.Set Faction
-- ^ Factions that can be killed by the
-- desperado.
}
-- ^ Kill a target, but if the target is not part of the
-- killable faction, commit suicide.
| KamikazeKill
-- ^ Kill a target, but also kill yourself at the same time.
| Suicide
-- ^ Kill yourself.
| Drive
-- ^ Switch two players, such that any action targeting them
-- will target the other player.
| Redirect
-- ^ Cause all actions used by a player to target a different
-- player.
| Deflect
-- ^ Cause all actions targeting a player to target a different
-- player.
| Bodyguard
-- ^ Bodyguard a player, such that if the player attempted to be
-- killed, the bodyguard will be killed instead.
| Hide
-- ^ Hide behind another player, such that the source is
-- invulnerable unless the target dies, in which case the source
-- will also die.
| Jail
-- ^ Block a player's actions but protect them from kills.
| Babysit
-- ^ Protect a player from death if you are alive.
| Frame { _actionTypeFramedFaction :: Faction
-- ^ Faction to frame as.
}
-- ^ Frames someone as being part of another faction.
| Commute
-- ^ Protect yourself from all actions.
| Recruit { _actionTypeRecruitFaction :: Faction
-- ^ Faction to recruit into.
, _actionTypeKnowsFactionMembers :: Bool
-- ^ Whether or not the recruited player will know
-- the other action members.
, _actionTypeAgenda :: Constraint
-- ^ Agenda for the player to fulfill.
}
-- ^ Recruit a player into a faction.
| Vanillaize
-- ^ Remove all of a player's actions.
| Watch
-- ^ See all players who visited a player at night.
| Track
-- ^ See all players who a player visited at night.
| Voyeur
-- ^ See all actions performed on a player at night.
| Follow
-- ^ See all actions a player performed at night.
| Investigate { _actionTypeGuiltyFactions :: S.Set Faction
-- ^ The set of factions that appear guilty to the
-- investigator.
}
-- ^ See if a player is in a given faction, or is framed as a
-- given faction.
| RoleInvestigate
-- ^ See the role of a player.
| ForensicInvestigate
-- ^ See all players who targeted a dead player.
| Pardon
-- ^ Make a player unlynchable.
| Veto
-- ^ Veto a lynching.
| StealVote
-- ^ Steal another player's vote. If the target player dies,
-- their vote is not stolen.
| Weak { _actionTypeWeakFaction :: Faction
-- ^ The faction the action is weak to.
, _actionTypeRealActionType :: ActionType
-- ^ The underlying action type.
, _actionTypeWeakKillAction :: Action
-- ^ The action used to kill on weakness.
, _actionTypeBlocksAction :: Bool
-- ^ Whether or not the action should be blocked on
-- weakness.
}
-- ^ Modifies an action to be weak to a given faction.
deriving (Eq, Ord, Show, Generic)
-- | The compulsion for an action.
data Compulsion = Voluntary -- ^ The action __may__ be performed.
| Required -- ^ The action __must__ be performed.
| Forced -- ^ The action __must__ be performed, and is only
-- automatically performed.
deriving (Eq, Ord, Show, Generic)
data SelectorAtom = Participant
| Self
| Alive
| WasLynched
deriving (Eq, Ord, Show, Generic)
type Selector = Expr SelectorAtom
newtype Action = Action Int
deriving (Eq, Ord, Show, Generic)
-- | An Action holds additional metadata about an action's type.
data ActionTraits = ActionTraits
{ _actionTraitsType :: ActionType
-- ^ The type of the action.
, _actionTraitsNinja :: Bool
-- ^ Whether the action can be seen by other players.
} deriving (Eq, Ord, Show, Generic)
-- | An ActionGroup is a group of mutually exclusive actions. Only one action
-- in the group can be planned during a single phase. This is global across all
-- players, e.g. an action group may span multiple players.
--
-- Note that action groups are incapable of representing a one-shot action
-- shared across multiple players – in practice, such actions don't really
-- exist.
type ActionGroup = Int
-- | An Act is the enactment of an action – it holds who performed the action
-- and who the action is being performed on.
data Act = Act
{ _actAction :: Action
-- ^ The action to perform.
, _actSource :: Player
-- ^ The source of the action.
, _actTargets :: [Player]
-- ^ The targets of the action.
, _actUnaffectable :: Bool
-- ^ The act cannot be affected by any effects.
, _actTrace :: ActTrace
-- ^ The trace for the act.
} deriving (Eq, Ord, Show, Generic)
data Phase = Night
| Day
deriving (Eq, Ord, Show, Read, Generic)
-- | An act trace traces an act's origin to the originating effect. If there is
-- no originating effect, the act must be planned originally by the user.
--
-- This is a unique token for identifying acts.
data ActTrace = ActFromPlan { _actTracePlanTurn :: Turn
, _actTracePlanPhase :: Phase
, _actTracePlanGroup :: ActionGroup
}
| ActFromRewrite { _actTraceDependentTrace :: ActTrace
, _actTraceEffectTrace :: EffectTrace
, _actTraceIndex :: Int
}
deriving (Eq, Ord, Show, Generic)
-- | How the death occurred.
data CauseOfDeath = Killed
-- ^ The player was killed.
| CommittedSuicide
-- ^ The player committed suicide.
| Lynched
-- ^ The player was lynched.
| ModKilled { _causeOfDeathReason :: T.Text }
-- ^ The player was killed by the moderator.
deriving (Eq, Ord, Show, Generic)
-- | Distinct effects that players can hold.
data EffectType = Death { _effectTypeCauseOfDeath :: CauseOfDeath }
-- ^ The player is dead.
| Granted { _effectTypeGrantedAction :: Action
-- ^ The action set granted.
, _effectTypeGrantedGroup :: ActionGroup
-- ^ Which action group this grant is part of.
, _effectTypeGrantedCompulsion :: Compulsion
-- ^ The compulsion for the grant.
, _effectTypeGrantedIrrevocable :: Bool
-- ^ Whether or not the grant is irrevocable.
}
-- ^ The player was granted a set of mutually exclusive
-- actions.
| Vanillaized { _effectTypeRevokesIrrevocable :: Bool
-- ^ Whether or not irrevocable grants are
-- revoked. This should only be used if the player
-- is recruited.
}
-- ^ The player has lost all of their granted actions.
| Recruited { _effectTypeRecruitedFaction :: Faction
-- ^ The faction the player is recruited into.
, _effectTypeKnowsFactionMembers :: Bool
-- ^ The player knows the other members of the
-- faction.
, _effectTypeTraitor :: Bool
-- ^ The player is a traitor.
, _effectTypeAgenda :: Constraint
-- ^ The additional agenda the player must fulfill.
}
-- ^ The player is part of a faction.
| Framed { _effectTypeFramedFaction :: Faction
-- ^ The faction the player is framed as.
}
-- ^ The player is framed as (pretends to be) part of a faction.
| Reflex { _effectTypeReflex :: Action
-- ^ The reflex action the player will perform.
}
-- ^ The player will perform an action when targeted.
| Roleblocked
-- ^ The player cannot perform actions.
| Bulletproof
-- ^ The player cannot be killed.
| Macho
-- ^ The player cannot be protected.
| Ascetic
-- ^ The player cannot be targeted by non-killing actions.
| Untargetable
-- ^ The player cannot be targeted at all.
| Loved { _effectTypeLoverDeathAction :: Action
-- ^ The action the lover will perform when the player
-- dies.
, _effectTypeLover :: Player
-- ^ The lover.
}
-- ^ The player, on death, will cause their lover to perform an
-- action (usually suicide).
| Redirected { _effectTypeRedirectee :: Player
-- ^ The target for redirection.
}
-- ^ The player has all their actions targeting another player.
| Deflected { _effectTypeDeflectee :: Player
-- ^ The target for deflection.
}
-- ^ The player will deflect all actions targeted at them to
-- another player.
| Switched { _effectTypeSwitched1 :: Player
-- ^ A target for switching.
, _effectTypeSwitched2 :: Player
-- ^ A target for switching.
}
-- ^ Specialized bidirectional version of 'Deflected'.
| Bodyguarded { _effectTypeBodyguard :: Player
-- ^ The player's bodyguard.
}
-- ^ The player will deflect kills onto their bodyguard unless
-- their bodyguard is dead.
| Bomb { _effectTypeBomb :: Action
-- ^ The action the player will perform when killed.
}
-- ^ The player, when killed, will perform an action on their
-- killer.
| Vengeful { _effectTypeVengeance :: Action
-- ^ The action the player will perform when killed.
, _effectTypeVengee :: Player
-- ^ The target the player will perform their action
-- on,
}
-- ^ The player, when killed, will perform an action on another
-- player.
| Gravedigger { _effectTypeGravedig :: Action
-- ^ The action that shows up to actions that
-- see gravedigger actions.
}
-- ^ The player will be seen as targeting dead players.
| Unlynchable
-- ^ The player cannot be lynched.
| Hiding { _effectTypeHider :: Player
-- ^ Someone hiding behind the player.
}
-- ^ The player is hiding another player.
| Friendship { _effectTypeFriend :: Player
-- ^ The player's friend.
}
-- ^ The player is friends with another player.
| VoteChanged { _effectTypeVoteDelta :: Int
-- ^ The amount their vote was changed by.
}
-- ^ The player had their vote altered.
-- | Deferred { _effectTypeDeferred :: Effect
-- }
-- -- ^ Defers an effect for the next turn.
deriving (Eq, Ord, Show, Generic)
data ConstraintAtom = DuringPhase Phase
| FulfillsSelector Selector Player
| StartsAtTurn Turn
| EndsAtTurn Turn
| NPlusKthTurn Int Int
deriving (Eq, Ord, Show, Generic)
type Constraint = Expr ConstraintAtom
-- | An instance of an effect.
data Effect = Effect
{ _effectType :: EffectType
-- ^ The type of the effect.
, _effectUses :: Maybe Int
-- ^ How many more uses the effect has. 'Nothing' for infinite.
, _effectConstraint :: Constraint
-- ^ Constraint for the effect.
, _effectTrace :: EffectTrace
-- ^ The trace for the effect.
} deriving (Eq, Ord, Show, Generic)
-- | An effect trace traces an effect's origin to the originating act. If there
-- is no originating act, the effect must have been assigned to the user at the
-- start of the game.
--
-- This is a unique token for identifying effects.
data EffectTrace = EffectFromLynch { _effectTraceLynchTurn :: Turn }
-- ^ The origin of the effect was from lynching.
| EffectFromStart { _effectTraceIndex :: Int }
-- ^ The origin of the effect was from game start.
| EffectFromAct { _effectTraceActTrace :: ActTrace
, _effectTraceIndex :: Int
}
-- ^ The origin of the effect was from an act.
| EffectFromMod { _effectTraceIndex :: Int }
-- ^ The origin of the effect was from the moderator.
deriving (Eq, Ord, Show, Generic)
newtype Player = Player Int
deriving (Eq, Ord, Show, Generic)
-- | Traits defining factions.
data FactionTraits = FactionTraits
{ _factionTraitsIsPrimary :: Bool
-- ^ Marks primary factions, i.e. a "last-standing" faction.
} deriving (Show, Generic)
-- | Faction tokens.
newtype Faction = Faction Int
deriving (Eq, Ord, Show, Generic)
-- | Underlying info for messages.
data MessageInfo = GuiltInfo { _messageInfoIsGuilty :: Bool }
-- ^ An investigation result.
| PlayersInfo { _messageInfoPlayers :: S.Set Player }
-- ^ A result consisting of players.
| ActionsInfo { _messageInfoActions :: S.Set Action }
-- ^ A result consisting of action types.
| FruitInfo
-- ^ A piece of fruit.
| RoleInfo { _messageInfoPlayer :: Player }
-- ^ A result indicating role information should be displayed.
| GreetingInfo { _messageInfoGreeter :: Player
, _messageInfoGreeterFaction :: Faction
}
-- ^ A greeting from a player.
deriving (Show, Generic)
type Turn = Int
data Game = Game
{ _gamePlayers :: Players
, _gameActions :: Actions
, _gameFactions :: Factions
, _gameTurn :: Turn
, _gamePhase :: Phase
, _gameModActionIndex :: Int
, _gameHistory :: [Act]
, _gameConsensus :: Consensus
, _gameRng :: StdGen
} deriving (Show, Generic)
data PlanBinding = PlanBinding
{ _planBindingAction :: Action
, _planBindingSource :: Player
, _planBindingCompulsion :: Compulsion
} deriving (Eq, Ord, Show, Generic)
-- | Errors when trying to plan.
data PlanError = ActionNotPlannable
-- ^ The action is not plannable by the source.
| ActionNotPlanned
-- ^ The action was not planned.
| ActionAlreadyPlanned
-- ^ The action was already planned.
| CompulsionForced
-- ^ The action has a 'Compulsion' of 'Forced'.
| IncorrectNumberOfTargets
-- ^ There are not the right number of targets for the action.
| TargetInvalid (Index [Player])
-- ^ One of the targets is invalid.
deriving (Show, Generic)
-- | A plan to be executed at night.
type Plan = M.Map ActionGroup Act
data PlannerInfo = PlannerInfo
{ _plannerInfoPlayers :: Players
, _plannerInfoActions :: Actions
, _plannerInfoTurn :: Turn
, _plannerInfoPhase :: Phase
}
type Planner = StateT Plan (ReaderT PlannerInfo (Except PlanError))
-- | A message, which may occur for an act (see
-- 'Game.Cosanostra.Action.messagesFor').
data Message = Message
{ _messageInfo :: MessageInfo
-- ^ The message's underlying info.
, _messageActTrace :: ActTrace
-- ^ The act that caused the message to be sent.
, _messageAssociatesWithAct :: Bool
-- ^ Whether the message should be associated with an act when returned.
} deriving (Show, Generic)
data Consensus = StrictMajority
-- ^ The player with the strict majority of votes will be
-- lynched.
| MostVotes
-- ^ The player with the most votes will be lynched.
deriving (Show, Eq, Generic)
type Ballot = M.Map Player Player
type Tally = M.Map Player Int
data Expr a = Atom a
| Trivial
| Impossible
| And (Expr a) (Expr a)
| Or (Expr a) (Expr a)
| Not (Expr a)
deriving (Eq, Ord, Show, Generic)
newtype Players = Players (M.Map Player [Effect])
deriving (Show, Eq, Generic)
type Factions = M.Map Faction FactionTraits
type Actions = M.Map Action ActionTraits
type ActionGroups = M.Map ActionGroup (S.Set PlanBinding)
| rfw/cosanostra | src/Game/Cosanostra/Types.hs | mit | 21,119 | 0 | 10 | 8,754 | 2,184 | 1,412 | 772 | 246 | 0 |
containsDigit :: Integer -> Integer -> Bool
containsDigit n x
|(n == 0) && (x == 0) = True
|otherwise = iter n x
where
iter n x
|n == 0 = False
|mod n 10 == x = True
|otherwise = iter (div n 10) x
containsDigits :: Integer -> Integer -> Bool
containsDigits container containee
|containee == 0 = containsDigit container 0
|otherwise = iter container containee
where
iter container containee
|containee == 0 = True
|otherwise = containsDigit container (mod containee 10)
&& iter container (div containee 10)
| mbyankova/fp2015 | week10/containsDigits.hs | mit | 660 | 0 | 11 | 245 | 237 | 110 | 127 | 16 | 1 |
{-****************************************************************************
* Hamster Balls *
* Purpose: Rendering code for players, 1st and 3rd person perspective*
* Author: David, Harley, Alex, Matt *
* Copyright (c) Yale University, 2010 *
****************************************************************************-}
module Player where
-- Player move according to keyboard or mouse
-- Player can shoot, etc
import Common
import FRP.Yampa
import Vec3d
import Graphics.Rendering.OpenGL as OpenGL
import TerrainData
import Render
import Graphics.UI.GLFW
import Graphics.Rendering.OpenGL.GL.CoordTrans
import Sprites
renderPlayer :: Player -> IO ()
renderPlayer p = preservingMatrix $ do
loadIdentity
translate $ vector3 $ playerPos p
-- materialDiffuse Front $= Color4 0 0 0 1
-- materialSpecular FrontAndBack $= Color4 0 0 0 1
-- materialAmbient FrontAndBack $= Color4 0 0 0 1
materialEmission FrontAndBack $= computeColor p
let r = double (playerRadius p) / (sqrt 2)
blend $= Enabled -- this may be necessary in the future. Right now, this functionality is encapsulated in the line above (blendEquation $= Just FuncAdd).
blendFunc $= (One, SrcColor) -- this defines how colors will be blended when they are drawn to the framebuffer.
-- This means that transparent colors will let the background show through and opaque colors will be drawn over it.
let
radianToDegrees x = 180 * x / pi
lp = round $ 100 * ((playerLife p) / maxLife)
style = QuadricStyle (Just Smooth) NoTextureCoordinates Outside LineStyle
preservingMatrix $ do
rotate (radianToDegrees $ fst $ playerView p) (vector3 $ Vec3d(0, 0, 1))
rotate (radianToDegrees $ snd $ playerView p) (vector3 $ Vec3d(0, 1, 0))
renderQuadric style $ Sphere (double $ playerRadius p) lp lp
renderQuad hamsterTexture (Vertex3 (0) r (-r)) (Vertex3 (0) (r) r) (Vertex3 0 (-r) r) (Vertex3 0 (-r) (-r))
-- mvm <- get (matrix (Modelview 0))
-- now find the normal and rotate the image accordingly
mv <- get (matrix (Just (Modelview 0))) :: IO (GLmatrix GLdouble)
mvc <- getMatrixComponents RowMajor mv
let offset = float (length $ playerName p) / 2.0
{-newMT = newMatrix RowMajor [ 1 , 0 , 0 , mvc!!3 ,
0 , 1 , 0 , mvc!!7 ,
0 , 0 , 1 , mvc!!11 ,
0 , 0 , 0 , mvc!!15 ]-}
-- TODO: Fix this billboard-style name tag overhead
preservingMatrix $ do
loadIdentity
--let v = Vec3d(Matrix[8], Matrix[9], -Matrix[10]);
translate (vector3 (playerPos p ^+^ 1.1 *^ Vec3d(offset * 0.2,offset * 0.2,playerRadius p)))
OpenGL.scale 0.05 0.05 (0.05 :: GLdouble)
rotate (-90) (vector3 $ Vec3d(0,0,1))
rotate 90 (vector3 $ Vec3d(1,0,0))
-- Undo Rotations
-- Redo Scalings
renderString Fixed8x16 (playerName p)
-- Use withMatrix... or access elements directly
blend $= Disabled
--multMatrix newMT
-- Camera view and text on screen.
renderSelf :: Player -> IO()
renderSelf p = do
let (theta,phi) = playerView p
mkRMatrixT, mkRMatrixP, mkTMatrix :: IO (GLmatrix Float)
(ct,st,c,s) = (cos theta,sin theta,cos phi,sin phi)
--u = Vec3d (ct,st,0) `cross` Vec3d (0,0,1)
--(x,y,z) = (getx u,gety u,getz u)
mkRMatrixP = newMatrix RowMajor [ c , 0 , s , 0 ,
0 , 1 , 0 , 0 ,
-s , 0 , c , 0 ,
0 , 0 , 0 , 1 ]
mkRMatrixT = newMatrix RowMajor [ ct,-st, 0 , 0 ,
st, ct, 0 , 0 ,
0 , 0 , 1 , 0 ,
0 , 0 , 0 , 1 ]
mkTMatrix = newMatrix RowMajor [1,0,0,negate $ getx $ playerPos p,
0,1,0,negate $ gety $ playerPos p,
0,0,1,negate $ getz $ playerPos p,
0,0,0,1]
in do
renderOrtho widthf heightf $ do
-- the transparency blending only works if OOSSelf is rendered last, which is the case because it's first added to list -Harley
blend $= Enabled
blendFunc $= (SrcAlpha, OneMinusSrcAlpha)-- transparent colors will let the background show through and opaque colors will be drawn over it.
textureFunction $= Replace
-- printFonts' (centerCoordX-9) (centerCoordY-9) (tex, base) 1 "+"
renderText 5 0 ("Life: " ++ show (round (playerLife p))) 4
renderText 5 80 ("Pos : " ++ show (playerPos p)) 2
renderText 5 100 ("Vel : " ++ show (playerVel p)) 2
let r = 16 :: Float
preservingMatrix $ do
loadIdentity
alphaFunc $= Just (Greater,0.1:: Float)
translate (vector3 $ Vec3d(centerCoordX, centerCoordY, 0))
texture Texture2D $= Enabled
displaySprite3D crosshairTexture (Vertex3 (-r) (-r) 0) (Vertex3 (-r) r 0) (Vertex3 r r 0) (Vertex3 r (-r) 0) (0.0, 0.0) (1.0, 1.0)
texture Texture2D $= Disabled
blend $= Disabled
matrixMode $= Projection
initFrustum
rMatrixT <- mkRMatrixT
rMatrixP <- mkRMatrixP
tMatrix <- mkTMatrix
multMatrix rMatrixP
multMatrix rMatrixT
multMatrix tMatrix
matrixMode $= Modelview 0
{-
renderSelf' p =
let xyz (theta,phi) = Vertex3 (cos theta * cos phi) (sin theta * cos phi) (sin phi)
xyz' (theta,phi) = Vector3 (cos theta * cos phi) (sin theta * cos phi) (sin phi)
po = playerPos p
(th,ph) = playerView p
theta,phi,x,y,z :: GLdouble
theta = double th
phi = double ph
x = double $ getx po
y = double $ gety po
z = double $ getz po
in do
matrixMode $= Projection
initFrustum
lookAt (Vertex3 x y z) (xyz (theta,phi)) (Vector3 0 0 1)--(xyz' (theta, phi+pi/4))
matrixMode $= Modelview 0
--}
| harley/hamball | src/Player.hs | mit | 6,402 | 0 | 21 | 2,232 | 1,363 | 711 | 652 | 81 | 1 |
module Main where
import LI11718
import qualified Tarefa3_2017li1g183 as T3
import System.Environment
import Text.Read
main = do
args <- getArgs
case args of
["movimenta"] -> do
str <- getContents
let params = readMaybe str
case params of
Nothing -> error "parâmetros inválidos"
Just (mapa,tempo,carro) -> print $ T3.movimenta mapa tempo carro
["testes"] -> print $ T3.testesT3
otherwise -> error "RunT3 argumentos inválidos" | hpacheco/HAAP | examples/plab/svn/2017li1g183/src/RunT3.hs | mit | 531 | 0 | 17 | 164 | 141 | 73 | 68 | 16 | 4 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-account.html
module Stratosphere.Resources.ApiGatewayAccount where
import Stratosphere.ResourceImports
-- | Full data type definition for ApiGatewayAccount. See 'apiGatewayAccount'
-- for a more convenient constructor.
data ApiGatewayAccount =
ApiGatewayAccount
{ _apiGatewayAccountCloudWatchRoleArn :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToResourceProperties ApiGatewayAccount where
toResourceProperties ApiGatewayAccount{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::ApiGateway::Account"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ fmap (("CloudWatchRoleArn",) . toJSON) _apiGatewayAccountCloudWatchRoleArn
]
}
-- | Constructor for 'ApiGatewayAccount' containing required fields as
-- arguments.
apiGatewayAccount
:: ApiGatewayAccount
apiGatewayAccount =
ApiGatewayAccount
{ _apiGatewayAccountCloudWatchRoleArn = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-account.html#cfn-apigateway-account-cloudwatchrolearn
agaCloudWatchRoleArn :: Lens' ApiGatewayAccount (Maybe (Val Text))
agaCloudWatchRoleArn = lens _apiGatewayAccountCloudWatchRoleArn (\s a -> s { _apiGatewayAccountCloudWatchRoleArn = a })
| frontrowed/stratosphere | library-gen/Stratosphere/Resources/ApiGatewayAccount.hs | mit | 1,483 | 0 | 14 | 190 | 187 | 109 | 78 | 24 | 1 |
module Antemodulum.ClassyPrelude (
module Export
) where
--------------------------------------------------------------------------------
import ClassyPrelude as Export hiding ((<.>), (</>))
| docmunch/antemodulum | src/Antemodulum/ClassyPrelude.hs | mit | 195 | 0 | 5 | 19 | 31 | 23 | 8 | 3 | 0 |
module Main where
main = print $ fn [1,2,3,4,5]
fni (_:[]) i = i
fni (_:xs) i = fni xs i + 1
fn (_:xs) = fni xs 2
| Rsgm/Haskell-problems | 4.hs | mit | 116 | 0 | 8 | 31 | 96 | 52 | 44 | 5 | 1 |
module ExameEscrito2015 where
-- Questão 1
-- get :: Eq a => a -> [(a, Bool)] -> Bool
get i [] = False
get i ((j,v):l) = if i == j then v else get i l
-- gett :: (Eq a1, Num a) => a1 -> [(a1, a)] -> a
gett i [] = 0
gett i ((j,v):l) = if i == j then v else gett i l
-- g :: (a1 -> a -> a) -> [a] -> [[a1] -> a]
-- foldr :: (a -> b -> b) -> b -> [a] -> b
g = map.foldr
-- Questão 2
--get2 :: (Eq a, Fail b) => a -> [(a,b)] -> b
get2 i [] = erro
get2 i ((j,v):l) = if i == j then v else get2 i l
class Fail t where
erro :: t
instance Fail Double where
erro = 0.0
instance Fail Bool where
erro = False
instance Fail Valor where
erro = Erro
instance Fail Result where
erro = Falha
data Valor = Erro | Num Double
data Result = Falha
instance Show Valor where
show Erro = "Erro"
show (Num x) = show x
x = get2 "a" [("a",1::Double)]
y = get2 "a" [("b",Num (2::Double))]
z = get2 "a" [("a",Num (1::Double))]
-- Questão 3
data Termo = Variavel String | Literal Double | Binaria Op Termo Termo |
Unaria Op Termo | Atribuicao String Termo | Sequencia Termo Termo
data Op = Soma | Subtracao | Divisao | Negativo
-- vars :: (Num t, Num t1) => Termo -> [(String, t, t1)]
vars (Variavel s) = [(s,1,0)]
vars (Literal d) = []
vars (Atribuicao v e) = add [(v,0,1)] (vars e)
vars (Sequencia e f) = add (vars e) (vars f)
vars (Binaria op e f) = add (vars e) (vars f)
vars (Unaria op f) = (vars f)
add [] l = l
add ((v,r,w):vrws) l = addTriple (v,r,w) (add vrws l)
addTriple (v,r,w) [] = [(v,r,w)]
addTriple (v,r,w) ((v1,r1,w1):vrws) | v == v1 = addTriple (v,r+r1,w+w1) vrws
| otherwise = (v1,r1,w1):(addTriple (v,r,w) vrws)
a = Atribuicao "x" (Literal 2)
b = Atribuicao "y" (Variavel "z")
c = Binaria Soma a b
d = Sequencia c (Atribuicao "z" (Variavel "y"))
res = vars d
-- Questão 4
data Termo1 = Variavel1 String | Literal1 Double | Binaria1 OpB Termo1 Termo1 |
Unaria1 OpU Termo1 | Atribuicao1 String Termo1 | Sequencia1 Termo1 Termo1
data OpB = Soma1 | Subtracao1 | Divisao1
data OpU = Negativo1
naoinicializadas t = fst(naoini t [])
-- aux na prova
naoini (Variavel1 s) e = if (isIn s e) then ([],e) else ([s],e)
naoini (Literal1 d) e = ([],e)
naoini (Atribuicao1 v t) e = (ni,v:e1) where (ni,e1) = naoini t e
naoini (Sequencia1 t u) e = (ni1 ++ ni2,e2) where (ni1,e1) = naoini t e
(ni2,e2) = naoini u e1
naoini (Binaria1 op t u) e = naoini (Sequencia1 t u) e
naoini (Unaria1 op t) e = naoini t e
isIn x [] = False
isIn x (y:ys) = (x == y) || isIn x ys
a1 = Atribuicao1 "x" (Literal1 2)
b1 = Atribuicao1 "y" (Variavel1 "z")
c1 = Binaria1 Soma1 a1 b1
d1 = Sequencia1 c1 (Atribuicao1 "z" (Variavel1 "y"))
e1 = Sequencia1 d1 (Atribuicao1 "q" (Variavel1 "p"))
res1 = naoinicializadas e1
| pauloborba/plc | src/ExameEscrito2015.hs | cc0-1.0 | 2,856 | 0 | 9 | 738 | 1,350 | 729 | 621 | 65 | 2 |
{-#LANGUAGE RecordWildCards #-}
-------------------------------------------------------------------------------
-- Module : Exploration.SUNF.APIStateless
-- Desc : Minimal synchronisation unfolder
-- Copyright : (c) 2016 Marcelo Sousa
-------------------------------------------------------------------------------
module Exploration.SUNF.APIStateless where
import Control.Monad.State.Strict
import Data.List
import Exploration.SUNF.API
import Exploration.SUNF.State
-- | STATELESS RELATED FUNCTIONS
-- | Prunes the configuration based on the current prefix
-- In the stateless mode, it is possible that previously
-- enabled events of the configuration are no longer in the
-- unfolding prefix.
-- @NOTE: Add example of this.
prune_config :: Configuration -> UnfolderOp Configuration
prune_config c@Conf{..} = do
s@UnfolderState{..} <- get
nenevs <- lift $ filterEvents enevs evts
return $ c {enevs = nenevs}
-- | Computes the core of the prefix necessary to continue
-- exploration
-- @NOTE: Optimise this function using Sets.
core :: EventsID -> EventsID -> Events -> IO EventsID
core conf d events = do
let confAndD = conf ++ d
evs <- mapM (\e -> get_event "compute_core" e events) confAndD
let altes = concat $ concatMap alte evs
core_prefix = confAndD ++ altes
return $ nub core_prefix
-- | Prunes the unfolding prefix by potentially the event e and its alternatives
prune :: EventID -> EventsID -> UnfolderOp ()
prune e core = do
s@UnfolderState{..} <- get
ev@Event{..} <- lift $ get_event "prune" e evts
if e `elem` core
then lift $ reset_alte e evts
else lift $ del_event e evts
lift $ mapM_ (\v -> mapM_ (\e -> if e `elem` core then return () else del_event e evts) v) alte
| marcelosousa/poet | src/Exploration/SUNF/APIStateless.hs | gpl-2.0 | 1,746 | 0 | 16 | 309 | 395 | 210 | 185 | 26 | 3 |
module Main where
import Data.Char
import Prelude
import Data.List
digit::Char -> Bool
digit x = isDigit x
uppercase::Char -> Bool
uppercase x = isUpper x
lowercase::Char -> Bool
lowercase x = isLower x
letter:: Char -> Bool
letter x = isLetter x
charofdigit:: Int -> Char
charofdigit 0 = '0'
charofdigit 1 = '1'
charofdigit 2 = '2'
charofdigit 3 = '3'
charofdigit 4 = '4'
charofdigit 5 = '5'
charofdigit 6 = '6'
charofdigit 7 = '7'
charofdigit 8 = '8'
charofdigit 9 = '9'
among:: Eq a => a -> [a] -> Bool
among x [] = False
among x (z:l) = if x==z then True else among x l
stringcopy :: Int -> String -> String
stringcopy x s | x==0 = ""
| x>0 = s ++ stringcopy (x-1) s
| x<0 = error("No se aceptan valores negativos")
strcop :: Int -> String -> String
strcop 0 s = ""
strcop x s = if x>0 then (s++ strcop (x-1) s) else error("No se aceptan valores negativos")
| fdzjuancarlos/Computacion_UCLM | Declarativa/Victor/practica8/Gualdras_delaCruz_Lab8.hs | gpl-2.0 | 874 | 0 | 10 | 183 | 406 | 208 | 198 | 33 | 2 |
module Core.Volume where
import Core.Geometry (BBox)
data VolumeRegion
worldBound :: VolumeRegion -> BBox
worldBound = undefined
| dsj36/dropray | src/Core/Volume.hs | gpl-3.0 | 132 | 0 | 5 | 19 | 33 | 20 | 13 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module TestHpack(hunitTests, quickcheckTests) where
import qualified Control.Monad.State.Lazy as State
import qualified Data.Binary.Get as Get
import qualified Data.Binary.Put as Put
import qualified Data.ByteString.Base16 as Base16
import qualified Data.ByteString.Lazy as ByteString
import qualified Hpack
import Data.ByteString.Lazy(ByteString)
import Data.Text(Text)
import Test.HUnit
import Test.QuickCheck
import Test.QuickCheck.Instances
import Hpack(PrefixLength)
instance Arbitrary PrefixLength where
arbitrary = arbitraryBoundedEnum
prop_integer octet prefixLength i =
let buffer = Put.runPut (Hpack.putInteger octet prefixLength i) in
let (_, i') = Get.runGet (Hpack.getInteger prefixLength) buffer in
i == i'
prop_stringLiteralWithoutHuffman str =
let buffer = Put.runPut (Hpack.putStringLiteral False str) in
let str' = Get.runGet Hpack.getStringLiteral buffer in
str == str'
prop_stringLiteralWithHuffman str =
let buffer = Put.runPut (Hpack.putStringLiteral True str) in
let str' = Get.runGet Hpack.getStringLiteral buffer in
str == str'
prop_headerField hf =
let buffer = Put.runPut (Hpack.putLiteralWithoutIndexing hf) in
let getM = State.evalStateT Hpack.getLiteralWithoutIndexing [] in
let hf' = Get.runGet getM buffer in
hf == hf'
prop_headerFields hfs =
let buffer = Put.runPut (Hpack.putHeaderFields hfs) in
let getM = State.evalStateT Hpack.getHeaderFields [] in
let hfs' = Get.runGet getM buffer in
hfs == hfs'
return []
quickcheckTests :: IO Bool
quickcheckTests = $forAllProperties (quickCheckWithResult stdArgs { maxSuccess = 1000 })
hex2ByteString :: ByteString -> ByteString
hex2ByteString = ByteString.fromStrict . fst . Base16.decode . ByteString.toStrict
stringTests =
let parseString = Get.runGet Hpack.getStringLiteral . hex2ByteString in
let test (result, hex) = TestCase (assertEqual "" result (parseString hex)) in
TestList $ fmap test [
("custom-key", "0a637573746f6d2d6b6579"),
("custom-header", "0d637573746f6d2d686561646572"),
("/sample/path", "0c2f73616d706c652f70617468")
]
headerTests =
let parseFields dynTable =
Get.runGet (State.runStateT Hpack.getHeaderFields dynTable) . hex2ByteString in
let test (hex, dynTablePre, result, dynTablePost) = TestLabel (show hex) $ TestCase $ do
let (fields, st) = parseFields dynTablePre hex
assertEqual "Fields" result fields
assertEqual "Dynamic table" dynTablePost st in
TestList $ fmap test [
("400a637573746f6d2d6b65790d637573746f6d2d686561646572",
[],
[("custom-key", "custom-header")],
[("custom-key", "custom-header")]),
("040c2f73616d706c652f70617468",
[],
[(":path", "/sample/path")],
[]),
("100870617373776f726406736563726574",
[],
[("password", "secret")],
[]),
("82",
[],
[(":method", "GET")],
[]),
("828684410f7777772e6578616d706c652e636f6d",
[],
[(":method", "GET"),
(":scheme", "http"),
(":path", "/"),
(":authority", "www.example.com")
],
[(":authority", "www.example.com")]),
("828684be58086e6f2d6361636865",
[(":authority", "www.example.com")],
[(":method", "GET"),
(":scheme", "http"),
(":path", "/"),
(":authority", "www.example.com"),
("cache-control", "no-cache")
],
[("cache-control", "no-cache"),
(":authority", "www.example.com")
])
]
hunitTests = test [stringTests, headerTests]
| authchir/SoSe17-FFP-haskell-http2-server | test/TestHpack.hs | gpl-3.0 | 3,583 | 3 | 16 | 709 | 1,049 | 580 | 469 | -1 | -1 |
-- Copyright 2016, 2017 Robin Raymond
--
-- This file is part of Purple Muon
--
-- Purple Muon 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.
--
-- Purple Muon 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 Purple Muon. If not, see <http://www.gnu.org/licenses/>.
module Client.Assets.Sound
( soundLoader
, SoundLoaderType
, SoundID
) where
import Protolude
import qualified Data.HashTable.IO as DHI
import qualified SDL.Mixer as SMI
import qualified System.FilePath.Posix as SFP
import qualified Client.Assets.Generic as CAG
import qualified PurpleMuon.Util.MonadError as PUM
-- |A type of a sound loader
type SoundLoaderType = CAG.AssetLoader SMI.Chunk () ()
-- |Type of a sound identifier
type SoundID = CAG.AssetID SMI.Chunk
-- | Implementation of `AssetLoader` for sounds.
soundLoader :: MonadIO m => m SoundLoaderType
soundLoader = do
ht <- liftIO $ DHI.new
return (CAG.AssetLoader
{ CAG.store = ht
, CAG.extData = ()
, CAG.load = \_ _ p -> do
s <- try $ SMI.load p
:: IO (Either SomeException SMI.Chunk)
let r = PUM.mapLeft show s
i = CAG.AssetID $ toS $ SFP.takeBaseName p
return (fmap (\x -> [(i, x)]) r)
, CAG.delete = SMI.free
})
| r-raymond/purple-muon | src/Client/Assets/Sound.hs | gpl-3.0 | 1,861 | 0 | 20 | 529 | 308 | 183 | 125 | 25 | 1 |
{-# LANGUAGE TemplateHaskell, FlexibleInstances, IncoherentInstances#-}
module X509 where
import Test.QuickCheck
import DeriveArbitrary
import Data.X509
import Data.ASN1.Types
import Data.ASN1.Encoding
import Data.ASN1.BinaryEncoding
import qualified Data.ByteString.Lazy as L
$(devArbitrary ''Certificate)
mencode :: Certificate -> L.ByteString
mencode x = L.fromStrict $ encodeASN1' DER (toASN1 x [])
| fcostantini/QuickFuzz | src/X509.hs | gpl-3.0 | 408 | 0 | 9 | 47 | 97 | 56 | 41 | 12 | 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.BigtableAdmin.Projects.Instances.Tables.ModifyColumnFamilies
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Performs a series of column family modifications on the specified table.
-- Either all or none of the modifications will occur before this method
-- returns, but data requests received prior to that point may see a table
-- where only some modifications have taken effect.
--
-- /See:/ <https://cloud.google.com/bigtable/ Cloud Bigtable Admin API Reference> for @bigtableadmin.projects.instances.tables.modifyColumnFamilies@.
module Network.Google.Resource.BigtableAdmin.Projects.Instances.Tables.ModifyColumnFamilies
(
-- * REST Resource
ProjectsInstancesTablesModifyColumnFamiliesResource
-- * Creating a Request
, projectsInstancesTablesModifyColumnFamilies
, ProjectsInstancesTablesModifyColumnFamilies
-- * Request Lenses
, pitmcfXgafv
, pitmcfUploadProtocol
, pitmcfAccessToken
, pitmcfUploadType
, pitmcfPayload
, pitmcfName
, pitmcfCallback
) where
import Network.Google.BigtableAdmin.Types
import Network.Google.Prelude
-- | A resource alias for @bigtableadmin.projects.instances.tables.modifyColumnFamilies@ method which the
-- 'ProjectsInstancesTablesModifyColumnFamilies' request conforms to.
type ProjectsInstancesTablesModifyColumnFamiliesResource
=
"v2" :>
CaptureMode "name" "modifyColumnFamilies" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ModifyColumnFamiliesRequest :>
Post '[JSON] Table
-- | Performs a series of column family modifications on the specified table.
-- Either all or none of the modifications will occur before this method
-- returns, but data requests received prior to that point may see a table
-- where only some modifications have taken effect.
--
-- /See:/ 'projectsInstancesTablesModifyColumnFamilies' smart constructor.
data ProjectsInstancesTablesModifyColumnFamilies =
ProjectsInstancesTablesModifyColumnFamilies'
{ _pitmcfXgafv :: !(Maybe Xgafv)
, _pitmcfUploadProtocol :: !(Maybe Text)
, _pitmcfAccessToken :: !(Maybe Text)
, _pitmcfUploadType :: !(Maybe Text)
, _pitmcfPayload :: !ModifyColumnFamiliesRequest
, _pitmcfName :: !Text
, _pitmcfCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsInstancesTablesModifyColumnFamilies' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pitmcfXgafv'
--
-- * 'pitmcfUploadProtocol'
--
-- * 'pitmcfAccessToken'
--
-- * 'pitmcfUploadType'
--
-- * 'pitmcfPayload'
--
-- * 'pitmcfName'
--
-- * 'pitmcfCallback'
projectsInstancesTablesModifyColumnFamilies
:: ModifyColumnFamiliesRequest -- ^ 'pitmcfPayload'
-> Text -- ^ 'pitmcfName'
-> ProjectsInstancesTablesModifyColumnFamilies
projectsInstancesTablesModifyColumnFamilies pPitmcfPayload_ pPitmcfName_ =
ProjectsInstancesTablesModifyColumnFamilies'
{ _pitmcfXgafv = Nothing
, _pitmcfUploadProtocol = Nothing
, _pitmcfAccessToken = Nothing
, _pitmcfUploadType = Nothing
, _pitmcfPayload = pPitmcfPayload_
, _pitmcfName = pPitmcfName_
, _pitmcfCallback = Nothing
}
-- | V1 error format.
pitmcfXgafv :: Lens' ProjectsInstancesTablesModifyColumnFamilies (Maybe Xgafv)
pitmcfXgafv
= lens _pitmcfXgafv (\ s a -> s{_pitmcfXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pitmcfUploadProtocol :: Lens' ProjectsInstancesTablesModifyColumnFamilies (Maybe Text)
pitmcfUploadProtocol
= lens _pitmcfUploadProtocol
(\ s a -> s{_pitmcfUploadProtocol = a})
-- | OAuth access token.
pitmcfAccessToken :: Lens' ProjectsInstancesTablesModifyColumnFamilies (Maybe Text)
pitmcfAccessToken
= lens _pitmcfAccessToken
(\ s a -> s{_pitmcfAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pitmcfUploadType :: Lens' ProjectsInstancesTablesModifyColumnFamilies (Maybe Text)
pitmcfUploadType
= lens _pitmcfUploadType
(\ s a -> s{_pitmcfUploadType = a})
-- | Multipart request metadata.
pitmcfPayload :: Lens' ProjectsInstancesTablesModifyColumnFamilies ModifyColumnFamiliesRequest
pitmcfPayload
= lens _pitmcfPayload
(\ s a -> s{_pitmcfPayload = a})
-- | Required. The unique name of the table whose families should be
-- modified. Values are of the form
-- \`projects\/{project}\/instances\/{instance}\/tables\/{table}\`.
pitmcfName :: Lens' ProjectsInstancesTablesModifyColumnFamilies Text
pitmcfName
= lens _pitmcfName (\ s a -> s{_pitmcfName = a})
-- | JSONP
pitmcfCallback :: Lens' ProjectsInstancesTablesModifyColumnFamilies (Maybe Text)
pitmcfCallback
= lens _pitmcfCallback
(\ s a -> s{_pitmcfCallback = a})
instance GoogleRequest
ProjectsInstancesTablesModifyColumnFamilies
where
type Rs ProjectsInstancesTablesModifyColumnFamilies =
Table
type Scopes
ProjectsInstancesTablesModifyColumnFamilies
=
'["https://www.googleapis.com/auth/bigtable.admin",
"https://www.googleapis.com/auth/bigtable.admin.table",
"https://www.googleapis.com/auth/cloud-bigtable.admin",
"https://www.googleapis.com/auth/cloud-bigtable.admin.table",
"https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsInstancesTablesModifyColumnFamilies'{..}
= go _pitmcfName _pitmcfXgafv _pitmcfUploadProtocol
_pitmcfAccessToken
_pitmcfUploadType
_pitmcfCallback
(Just AltJSON)
_pitmcfPayload
bigtableAdminService
where go
= buildClient
(Proxy ::
Proxy
ProjectsInstancesTablesModifyColumnFamiliesResource)
mempty
| brendanhay/gogol | gogol-bigtableadmin/gen/Network/Google/Resource/BigtableAdmin/Projects/Instances/Tables/ModifyColumnFamilies.hs | mpl-2.0 | 6,927 | 0 | 16 | 1,451 | 798 | 470 | 328 | 126 | 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.Privileges.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a paginated list of all privileges for a customer.
--
-- /See:/ <https://developers.google.com/admin-sdk/directory/ Admin Directory API Reference> for @directory.privileges.list@.
module Network.Google.Resource.Directory.Privileges.List
(
-- * REST Resource
PrivilegesListResource
-- * Creating a Request
, privilegesList
, PrivilegesList
-- * Request Lenses
, plCustomer
) where
import Network.Google.Directory.Types
import Network.Google.Prelude
-- | A resource alias for @directory.privileges.list@ method which the
-- 'PrivilegesList' request conforms to.
type PrivilegesListResource =
"admin" :>
"directory" :>
"v1" :>
"customer" :>
Capture "customer" Text :>
"roles" :>
"ALL" :>
"privileges" :>
QueryParam "alt" AltJSON :> Get '[JSON] Privileges
-- | Retrieves a paginated list of all privileges for a customer.
--
-- /See:/ 'privilegesList' smart constructor.
newtype PrivilegesList = PrivilegesList'
{ _plCustomer :: Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'PrivilegesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plCustomer'
privilegesList
:: Text -- ^ 'plCustomer'
-> PrivilegesList
privilegesList pPlCustomer_ =
PrivilegesList'
{ _plCustomer = pPlCustomer_
}
-- | Immutable ID of the Google Apps account.
plCustomer :: Lens' PrivilegesList Text
plCustomer
= lens _plCustomer (\ s a -> s{_plCustomer = a})
instance GoogleRequest PrivilegesList where
type Rs PrivilegesList = Privileges
type Scopes PrivilegesList =
'["https://www.googleapis.com/auth/admin.directory.rolemanagement",
"https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly"]
requestClient PrivilegesList'{..}
= go _plCustomer (Just AltJSON) directoryService
where go
= buildClient (Proxy :: Proxy PrivilegesListResource)
mempty
| rueshyna/gogol | gogol-admin-directory/gen/Network/Google/Resource/Directory/Privileges/List.hs | mpl-2.0 | 2,956 | 0 | 16 | 696 | 318 | 194 | 124 | 52 | 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.Monitoring.Projects.NotificationChannels.Create
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a new notification channel, representing a single notification
-- endpoint such as an email address, SMS number, or PagerDuty service.
--
-- /See:/ <https://cloud.google.com/monitoring/api/ Cloud Monitoring API Reference> for @monitoring.projects.notificationChannels.create@.
module Network.Google.Resource.Monitoring.Projects.NotificationChannels.Create
(
-- * REST Resource
ProjectsNotificationChannelsCreateResource
-- * Creating a Request
, projectsNotificationChannelsCreate
, ProjectsNotificationChannelsCreate
-- * Request Lenses
, pnccXgafv
, pnccUploadProtocol
, pnccAccessToken
, pnccUploadType
, pnccPayload
, pnccName
, pnccCallback
) where
import Network.Google.Monitoring.Types
import Network.Google.Prelude
-- | A resource alias for @monitoring.projects.notificationChannels.create@ method which the
-- 'ProjectsNotificationChannelsCreate' request conforms to.
type ProjectsNotificationChannelsCreateResource =
"v3" :>
Capture "name" Text :>
"notificationChannels" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] NotificationChannel :>
Post '[JSON] NotificationChannel
-- | Creates a new notification channel, representing a single notification
-- endpoint such as an email address, SMS number, or PagerDuty service.
--
-- /See:/ 'projectsNotificationChannelsCreate' smart constructor.
data ProjectsNotificationChannelsCreate =
ProjectsNotificationChannelsCreate'
{ _pnccXgafv :: !(Maybe Xgafv)
, _pnccUploadProtocol :: !(Maybe Text)
, _pnccAccessToken :: !(Maybe Text)
, _pnccUploadType :: !(Maybe Text)
, _pnccPayload :: !NotificationChannel
, _pnccName :: !Text
, _pnccCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsNotificationChannelsCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pnccXgafv'
--
-- * 'pnccUploadProtocol'
--
-- * 'pnccAccessToken'
--
-- * 'pnccUploadType'
--
-- * 'pnccPayload'
--
-- * 'pnccName'
--
-- * 'pnccCallback'
projectsNotificationChannelsCreate
:: NotificationChannel -- ^ 'pnccPayload'
-> Text -- ^ 'pnccName'
-> ProjectsNotificationChannelsCreate
projectsNotificationChannelsCreate pPnccPayload_ pPnccName_ =
ProjectsNotificationChannelsCreate'
{ _pnccXgafv = Nothing
, _pnccUploadProtocol = Nothing
, _pnccAccessToken = Nothing
, _pnccUploadType = Nothing
, _pnccPayload = pPnccPayload_
, _pnccName = pPnccName_
, _pnccCallback = Nothing
}
-- | V1 error format.
pnccXgafv :: Lens' ProjectsNotificationChannelsCreate (Maybe Xgafv)
pnccXgafv
= lens _pnccXgafv (\ s a -> s{_pnccXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pnccUploadProtocol :: Lens' ProjectsNotificationChannelsCreate (Maybe Text)
pnccUploadProtocol
= lens _pnccUploadProtocol
(\ s a -> s{_pnccUploadProtocol = a})
-- | OAuth access token.
pnccAccessToken :: Lens' ProjectsNotificationChannelsCreate (Maybe Text)
pnccAccessToken
= lens _pnccAccessToken
(\ s a -> s{_pnccAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pnccUploadType :: Lens' ProjectsNotificationChannelsCreate (Maybe Text)
pnccUploadType
= lens _pnccUploadType
(\ s a -> s{_pnccUploadType = a})
-- | Multipart request metadata.
pnccPayload :: Lens' ProjectsNotificationChannelsCreate NotificationChannel
pnccPayload
= lens _pnccPayload (\ s a -> s{_pnccPayload = a})
-- | Required. The project
-- (https:\/\/cloud.google.com\/monitoring\/api\/v3#project_name) on which
-- to execute the request. The format is: projects\/[PROJECT_ID_OR_NUMBER]
-- This names the container into which the channel will be written, this
-- does not name the newly created channel. The resulting channel\'s name
-- will have a normalized version of this field as a prefix, but will add
-- \/notificationChannels\/[CHANNEL_ID] to identify the channel.
pnccName :: Lens' ProjectsNotificationChannelsCreate Text
pnccName = lens _pnccName (\ s a -> s{_pnccName = a})
-- | JSONP
pnccCallback :: Lens' ProjectsNotificationChannelsCreate (Maybe Text)
pnccCallback
= lens _pnccCallback (\ s a -> s{_pnccCallback = a})
instance GoogleRequest
ProjectsNotificationChannelsCreate
where
type Rs ProjectsNotificationChannelsCreate =
NotificationChannel
type Scopes ProjectsNotificationChannelsCreate =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/monitoring"]
requestClient ProjectsNotificationChannelsCreate'{..}
= go _pnccName _pnccXgafv _pnccUploadProtocol
_pnccAccessToken
_pnccUploadType
_pnccCallback
(Just AltJSON)
_pnccPayload
monitoringService
where go
= buildClient
(Proxy ::
Proxy ProjectsNotificationChannelsCreateResource)
mempty
| brendanhay/gogol | gogol-monitoring/gen/Network/Google/Resource/Monitoring/Projects/NotificationChannels/Create.hs | mpl-2.0 | 6,251 | 0 | 17 | 1,336 | 790 | 464 | 326 | 118 | 1 |
module Vision.Image.RGB (
module Vision.Image.RGB.Type
) where
import Vision.Image.RGB.Specialize ()
import Vision.Image.RGB.Type
| RaphaelJ/friday | src/Vision/Image/RGB.hs | lgpl-3.0 | 141 | 0 | 5 | 23 | 34 | 24 | 10 | 4 | 0 |
<?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="pt-BR">
<title>Server-Sent Events | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Localizar</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> | 0xkasun/security-tools | src/org/zaproxy/zap/extension/sse/resources/help_pt_BR/helpset_pt_BR.hs | apache-2.0 | 983 | 85 | 53 | 160 | 402 | 212 | 190 | -1 | -1 |
module Yahs.Parse where
import Control.Monad.Except (throwError, void)
import Text.ParserCombinators.Parsec hiding (spaces)
import Yahs.LispVal
readChar :: Char -> ThrowsError LispVal
readChar c = case parse (namedCharacter <|> anyChar) "" [c] of
Left err -> throwError $ Parser err
Right val -> return (Character val)
readExpr :: String -> ThrowsError LispVal
readExpr = readOrThrow parseExpr
readExprList :: String -> ThrowsError [LispVal]
readExprList = readOrThrow (many parseExpr)
-- Read multiple expressions from a string that may start
-- with a shebang line
readExprFile :: String -> ThrowsError [LispVal]
readExprFile = readOrThrow (optional parseShebangLine >> many parseExpr)
parseShebangLine :: Parser ()
parseShebangLine = void $ try (string "#!" >> many (noneOf "\n"))
readOrThrow :: Parser a -> String -> ThrowsError a
readOrThrow parser input = case parse parser "lisp" input of
Left err -> throwError $ Parser err
Right val -> return val
-- Parsec's "spaces" parser matches _zero_ or more spaces.
-- We want at least 1.
spaces :: Parser ()
spaces = skipMany1 space
symbol :: Parser Char
symbol = oneOf "!#$%&|*+-/:<=>?@^_~"
parseExpr :: Parser LispVal
parseExpr = do
skipMany (spaces <|> parseComment)
x <- parseHash
<|> parseString
<|> decimalNumber
<|> parseQuoted
<|> parseAtom
<|> between (char '(') (char ')') (try parseDottedList <|> parseList)
skipMany (spaces <|> parseComment)
return x
parseComment :: Parser ()
parseComment = many1 (char ';') >> skipMany (noneOf "\n")
parseString :: Parser LispVal
parseString = do
char '"'
x <- many (escapedChar <|> noneOf "\"")
char '"'
return (String x)
escapedChar :: Parser Char
escapedChar = do
char '\\'
x <- oneOf "nrt\\\""
return $ case x of
'n' -> '\n'
'r' -> '\r'
't' -> '\t'
'\\' -> '\\'
'"' -> '"'
parseHash :: Parser LispVal
parseHash = do
char '#'
x <- oneOf "\\bdfotx"
case x of
'\\' -> Character <$> (namedCharacter <|> anyChar)
'b' -> binaryNumber
'd' -> decimalNumber
-- 'e' -> exactNumber
'f' -> return (Bool False)
-- 'i' -> inexactNumber
'o' -> octalNumber
't' -> return (Bool True)
'x' -> hexNumber
namedCharacter :: Parser Char
namedCharacter = do
x <- string "space" <|> string "newline"
return $ case x of
"space" -> ' '
"newline" -> '\n'
binaryNumber :: Parser LispVal
binaryNumber = do
num <- many1 (oneOf "01")
notFollowedBy digit
return $ Number (bin2dec num)
where
bin2dec :: String -> Integer
bin2dec = foldr (\c s -> s * 2 + c) 0 . reverse . map c2i
where c2i c = if c == '0' then 0 else 1
decimalNumber :: Parser LispVal
decimalNumber = try negativeDecimalNumber <|> ((Number . read) <$> many1 digit)
negativeDecimalNumber :: Parser LispVal
negativeDecimalNumber = char '-' >> Number . read . ('-' :) <$> many1 digit
hexNumber :: Parser LispVal
hexNumber = do
num <- many1 hexDigit
notFollowedBy letter
return $ Number $ read $ "0x" ++ num
octalNumber :: Parser LispVal
octalNumber = do
num <- many1 octDigit
notFollowedBy digit
return $ Number $ read $ "0o" ++ num
parseQuoted :: Parser LispVal
parseQuoted = do
x <- char '\'' >> parseExpr
return $ List [Atom "quote", x]
parseAtom :: Parser LispVal
parseAtom = do
first <- letter <|> symbol
rest <- many (letter <|> digit <|> symbol)
let atom = first:rest
return $ Atom atom
parseList :: Parser LispVal
parseList = List <$> many parseExpr
parseDottedList :: Parser LispVal
parseDottedList = do
head <- many parseExpr
tail <- char '.' >> spaces >> parseExpr
return $ DottedList head tail
| benley/yet-another-haskell-scheme | Yahs/Parse.hs | apache-2.0 | 3,938 | 0 | 13 | 1,068 | 1,253 | 609 | 644 | 110 | 7 |
-- http://www.codewars.com/kata/5506b230a11c0aeab3000c1f
module Codewars.Kata.Evaporator where
evaporator :: Double -> Double -> Double -> Integer
evaporator _ e t = ceiling $ (log $ t / 100) / (log $ 1 - e / 100)
| Bodigrim/katas | src/haskell/7-Deodorant-Evaporator.hs | bsd-2-clause | 215 | 0 | 9 | 35 | 71 | 39 | 32 | 3 | 1 |
import Safe
import System.Environment
import System.Exit
import Test.QuickCheck
import Test.QuickCheck.Test
import Prop.Fluid
import Prop.Id
import Prop.Unique
import Codec.Goat.Util
-- | Print a name of the property test and execute the QuickCheck
-- algorithm.
runTest :: Args
-> (String, Property)
-> IO Result
runTest args (name, prop) = do
result <- quickCheckWithResult args prop
putStr $ unwords [name, output result]
return result
-- | Run all available property tests and collect results.
runTests :: Args
-> IO [Result]
runTests args = mapM (runTest args) (idProps ++ uniqueProps ++ fluidProps)
-- | Parse command-line options into test arguments. In case invalid or
-- no arguments were provided, the test fallbacks into a default value.
parseArguments :: [String]
-> Args
parseArguments [] = stdArgs { maxSuccess=1000, chatty=False }
parseArguments (x:_) = stdArgs { maxSuccess=readDef 1000 x, chatty=False }
-- | Evaluate test results and set appropriate process exit code.
main :: IO ()
main = do
putStrLn "\nRunning property tests:"
args <- getArgs
results <- runTests (parseArguments args)
bool exitSuccess exitFailure (all isSuccess results)
| lovasko/goat | test/Prop.hs | bsd-2-clause | 1,237 | 1 | 10 | 249 | 307 | 162 | 145 | 29 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveFunctor #-}
module Matterhorn.Types.Users
( UserInfo(..)
, UserStatus(..)
, Users -- constructor remains internal
-- * Lenses created for accessing UserInfo fields
, uiName, uiId, uiStatus, uiInTeam, uiNickName, uiFirstName, uiLastName, uiEmail
, uiDeleted
-- * Various operations on UserInfo
-- * Creating UserInfo objects
, userInfoFromUser
-- * Miscellaneous
, getUsernameSet
, trimUserSigil
, addUserSigil
, statusFromText
, findUserById
, findUserByUsername
, findUserByNickname
, noUsers, addUser, allUsers
, modifyUserById
, userDeleted
, TypingUsers
, noTypingUsers
, addTypingUser
, allTypingUsers
, expireTypingUsers
, getAllUserIds
)
where
import Prelude ()
import Matterhorn.Prelude
import qualified Data.HashMap.Strict as HM
import qualified Data.Set as S
import Data.Semigroup ( Max(..) )
import qualified Data.Text as T
import Lens.Micro.Platform ( (%~), makeLenses, ix )
import Network.Mattermost.Types ( UserId(..), User(..) )
import Matterhorn.Types.Common
import Matterhorn.Constants ( userSigil )
-- * 'UserInfo' Values
-- | A 'UserInfo' value represents everything we need to know at
-- runtime about a user
data UserInfo = UserInfo
{ _uiName :: Text
, _uiId :: UserId
, _uiStatus :: UserStatus
, _uiInTeam :: Bool
, _uiNickName :: Maybe Text
, _uiFirstName :: Text
, _uiLastName :: Text
, _uiEmail :: Text
, _uiDeleted :: Bool
} deriving (Eq, Show)
-- | Is this user deleted?
userDeleted :: User -> Bool
userDeleted u =
case userCreateAt u of
Nothing -> False
Just c -> userDeleteAt u > c
-- | Create a 'UserInfo' value from a Mattermost 'User' value
userInfoFromUser :: User -> Bool -> UserInfo
userInfoFromUser up inTeam = UserInfo
{ _uiName = userUsername up
, _uiId = userId up
, _uiStatus = Offline
, _uiInTeam = inTeam
, _uiNickName =
let nick = sanitizeUserText $ userNickname up
in if T.null nick then Nothing else Just nick
, _uiFirstName = sanitizeUserText $ userFirstName up
, _uiLastName = sanitizeUserText $ userLastName up
, _uiEmail = sanitizeUserText $ userEmail up
, _uiDeleted = userDeleted up
}
-- | The 'UserStatus' value represents possible current status for
-- a user
data UserStatus
= Online
| Away
| Offline
| DoNotDisturb
| Other Text
deriving (Eq, Show)
statusFromText :: Text -> UserStatus
statusFromText t = case t of
"online" -> Online
"offline" -> Offline
"away" -> Away
"dnd" -> DoNotDisturb
_ -> Other t
-- ** 'UserInfo' lenses
makeLenses ''UserInfo
-- ** Manage the collection of all Users
-- | Define a binary kinded type to allow derivation of functor.
data AllMyUsers a =
AllUsers { _ofUsers :: HashMap UserId a
, _usernameSet :: S.Set Text
}
deriving Functor
makeLenses ''AllMyUsers
-- | Define the exported typename which universally binds the
-- collection to the UserInfo type.
type Users = AllMyUsers UserInfo
getUsernameSet :: Users -> S.Set Text
getUsernameSet = _usernameSet
-- | Initial collection of Users with no members
noUsers :: Users
noUsers = AllUsers HM.empty mempty
getAllUserIds :: Users -> [UserId]
getAllUserIds = HM.keys . _ofUsers
-- | Add a member to the existing collection of Users
addUser :: UserInfo -> Users -> Users
addUser userinfo u =
u & ofUsers %~ HM.insert (userinfo^.uiId) userinfo
& usernameSet %~ S.insert (userinfo^.uiName)
-- | Get a list of all known users
allUsers :: Users -> [UserInfo]
allUsers = HM.elems . _ofUsers
-- | Define the exported typename to represent the collection of users
-- | who are currently typing. The values kept against the user id keys are the
-- | latest timestamps of typing events from the server.
type TypingUsers = AllMyUsers (Max UTCTime)
-- | Initial collection of TypingUsers with no members
noTypingUsers :: TypingUsers
noTypingUsers = AllUsers HM.empty mempty
-- | Add a member to the existing collection of TypingUsers
addTypingUser :: UserId -> UTCTime -> TypingUsers -> TypingUsers
addTypingUser uId ts = ofUsers %~ HM.insertWith (<>) uId (Max ts)
-- | Get a list of all typing users
allTypingUsers :: TypingUsers -> [UserId]
allTypingUsers = HM.keys . _ofUsers
-- | Remove all the expired users from the collection of TypingUsers.
-- | Expiry is decided by the given timestamp.
expireTypingUsers :: UTCTime -> TypingUsers -> TypingUsers
expireTypingUsers expiryTimestamp =
ofUsers %~ HM.filter (\(Max ts') -> ts' >= expiryTimestamp)
-- | Get the User information given the UserId
findUserById :: UserId -> Users -> Maybe UserInfo
findUserById uId = HM.lookup uId . _ofUsers
-- | Get the User information given the user's name. This is an exact
-- match on the username field. It will automatically trim a user sigil
-- from the input.
findUserByUsername :: Text -> Users -> Maybe (UserId, UserInfo)
findUserByUsername name allusers =
case filter ((== trimUserSigil name) . _uiName . snd) $ HM.toList $ _ofUsers allusers of
(usr : []) -> Just usr
_ -> Nothing
-- | Get the User information given the user's name. This is an exact
-- match on the nickname field, not necessarily the presented name. It
-- will automatically trim a user sigil from the input.
findUserByNickname:: Text -> Users -> Maybe (UserId, UserInfo)
findUserByNickname nick us =
case filter ((== (Just $ trimUserSigil nick)) . _uiNickName . snd) $ HM.toList $ _ofUsers us of
(pair : []) -> Just pair
_ -> Nothing
trimUserSigil :: Text -> Text
trimUserSigil n
| userSigil `T.isPrefixOf` n = T.tail n
| otherwise = n
addUserSigil :: T.Text -> T.Text
addUserSigil t | userSigil `T.isPrefixOf` t = t
| otherwise = userSigil <> t
-- | Extract a specific user from the collection and perform an
-- endomorphism operation on it, then put it back into the collection.
modifyUserById :: UserId -> (UserInfo -> UserInfo) -> Users -> Users
modifyUserById uId f = ofUsers.ix(uId) %~ f
| matterhorn-chat/matterhorn | src/Matterhorn/Types/Users.hs | bsd-3-clause | 6,196 | 0 | 15 | 1,387 | 1,333 | 754 | 579 | -1 | -1 |
module Day10 where
-- "Advanced binding structures" from Chargueraud
import Data.Set (Set)
import qualified Data.Set as Set
data Term
= BVar Int Int
| FVar String
| Abs Term
| App Term Term
| Let [Term] Term
-- t ^ [u]
--
-- Replace `BVar i j` with the j-th value from u, when the de Bruijn indices
-- match.
open :: [Term] -> Term -> Term
open = open' 0
-- { k -> [u] } t
open' :: Int -> [Term] -> Term -> Term
open' k u t = case t of
BVar i j -> if i == k then u !! j else t
FVar _ -> t
Abs t' -> open' (k + 1) u t'
App t1 t2 -> App (open' k u t1) (open' k u t2)
Let ts t1 ->
-- XXX double check this
let open'' = open' (k + 1) u
in Let (map open'' ts) (open'' t1)
| joelburget/daily-typecheckers | src/Day10.hs | bsd-3-clause | 705 | 0 | 14 | 197 | 275 | 147 | 128 | 20 | 6 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Eclogues.JobSpec (spec) where
import qualified Eclogues.Job as Job
import Data.Aeson (eitherDecode, encode)
import Data.ByteString.Lazy.Char8 (ByteString, pack, unpack)
import Data.Maybe (fromMaybe)
import Data.Metrology.Computing (Byte (Byte), Core (Core), (%>))
import Data.Metrology.SI (Second (Second), mega, centi)
import Data.Scientific.Suspicious (Sustific, fromFloatDigits)
import NeatInterpolation
import Path (mkAbsFile)
import Test.Hspec
import Test.QuickCheck (
Arbitrary (arbitrary), getNonZero, property, counterexample)
{-# ANN module ("HLint: ignore Use ." :: String) #-}
spec :: Spec
spec = do
describe "Resources" $
it "round trips through JSON" $ property $ \(x :: Job.Resources) ->
let encoded = encode x
decoded = eitherDecode encoded
in counterexample (" => " ++ unpack encoded ++ "\n => " ++ show decoded)
$ either (const False) (== x) decoded
describe "Spec" $
it "can be decoded from a particular string" $
eitherDecode exampleEncoded `shouldBe` Right exampleSpec
exampleEncoded :: ByteString
exampleEncoded = pack $
[string|
{
"name": "hello",
"command": "echo hello world > hello.txt",
"resources": {
"disk": "10 MB",
"ram": "10 MB",
"cpu": "0.1 cores",
"time": "5 s"
},
"outputfiles": ["/hello.txt"],
"capturestdout": false,
"dependson": []
}
|]
exampleSpec :: Job.Spec
exampleSpec = Job.mkSpec name "echo hello world > hello.txt" res ops False []
where
res = fromMaybe (error "example resources failed") $
Job.mkResources (10 %> mega Byte) (10 %> mega Byte) (10 %> centi Core) (5 %> Second)
name = fromMaybe (error "example name failed") $ Job.mkName "hello"
ops = [Job.OutputPath $(mkAbsFile "/hello.txt")]
instance Arbitrary Job.Resources where
arbitrary = mk <$> v (mega Byte) <*> v (mega Byte) <*> v Core <*> v Second
where
v t = (%> t) . dblToSus . pos . getNonZero <$> arbitrary
pos :: Double -> Double
pos = (+ 1) . abs
dblToSus :: Double -> Sustific
dblToSus = fromFloatDigits
mk d r c t = fromMaybe (error "arb resources failed somehow") $ Job.mkResources d r c t
| futufeld/eclogues | eclogues/test/Eclogues/JobSpec.hs | bsd-3-clause | 2,514 | 0 | 17 | 630 | 626 | 344 | 282 | -1 | -1 |
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE ScopedTypeVariables #-}
module MCL.Internal.Prim.Unpinned where
import Data.Functor.Identity
import Data.Primitive.ByteArray
import Foreign.C.Types
import GHC.Exts
import System.IO.Unsafe
import MCL.Internal.Prim.Class
import MCL.Internal.Utils
{-# INLINABLE withPrim #-}
withPrim :: Prim t => t -> (CC t -> IO r) -> IO r
withPrim fp k = k (prim_unwrap fp)
{-# INLINABLE newPrim #-}
newPrim
:: forall m t r. Prim t
=> (r -> CC t -> m t)
-> (MC t -> IO r)
-> IO (m t)
newPrim = withByteArray1 (prim_size (proxy# :: Proxy# t))
{-# INLINABLE newPrim_ #-}
newPrim_ :: forall t. Prim t => (MC t -> IO ()) -> IO t
newPrim_ = unwrap . newPrim (\_ ba -> Identity (prim_wrap ba))
where
unwrap :: IO (Identity t) -> IO t
unwrap = coerce
{-# INLINABLE maybeNewPrim #-}
maybeNewPrim :: Prim t => (MC t -> IO CInt) -> IO (Maybe t)
maybeNewPrim = newPrim $ \success ba ->
if cintToBool success
then Just (prim_wrap ba)
else Nothing
{-# INLINABLE new2Prim #-}
new2Prim :: forall t. Prim t => (MC t -> MC t -> IO ()) -> IO (t, t)
new2Prim = withByteArray2 (prim_size (proxy# :: Proxy# t)) prim_wrap
----------------------------------------
{-# INLINABLE unsafeOp0 #-}
unsafeOp0 :: IO r -> r
unsafeOp0 = unsafeDupablePerformIO
{-# INLINABLE unsafeOp0_ #-}
unsafeOp0_ :: Prim r => (MC r -> IO ()) -> r
unsafeOp0_ = unsafeOp0 . newPrim_
{-# INLINABLE unsafeOp1 #-}
unsafeOp1
:: Prim t
=> (s -> IO r)
-> (CC t -> s)
-> (t -> r)
unsafeOp1 k c_fun fa =
unsafeOp0 . withPrim fa $ \a -> k (c_fun a)
{-# INLINABLE unsafeOp1_ #-}
unsafeOp1_
:: (Prim t, Prim r)
=> (CC t -> MC r -> IO ())
-> (t -> r)
unsafeOp1_ = unsafeOp1 newPrim_
{-# INLINABLE unsafeOp2 #-}
unsafeOp2
:: (Prim t1, Prim t2)
=> (s -> IO r)
-> (CC t1 -> CC t2 -> s)
-> (t1 -> t2 -> r)
unsafeOp2 k c_fun fa fb =
unsafeOp0 . withPrim fa $ \a -> withPrim fb $ \b -> k (c_fun a b)
{-# INLINABLE unsafeOp2_ #-}
unsafeOp2_
:: (Prim t1, Prim t2, Prim r)
=> (CC t1 -> CC t2 -> MC r -> IO ())
-> (t1 -> t2 -> r)
unsafeOp2_ = unsafeOp2 newPrim_
{-# INLINABLE unsafeOp6 #-}
unsafeOp6
:: (Prim t1, Prim t2, Prim t3, Prim t4, Prim t5, Prim t6)
=> (s -> IO r)
-> (CC t1 -> CC t2 -> CC t3 -> CC t4 -> CC t5 -> CC t6 -> s)
-> (t1 -> t2 -> t3 -> t4 -> t5 -> t6 -> r)
unsafeOp6 k c_fun fa fb fc fd fe ff =
unsafeOp0 . withPrim fa $ \a -> withPrim fb $ \b -> withPrim fc $ \c ->
withPrim fd $ \d -> withPrim fe $ \e -> withPrim ff $ \f ->
k (c_fun a b c d e f)
{-# INLINABLE unsafeOp6_ #-}
unsafeOp6_
:: (Prim t1, Prim t2, Prim t3, Prim t4, Prim t5, Prim t6, Prim r)
=> (CC t1 -> CC t2 -> CC t3 -> CC t4 -> CC t5 -> CC t6 -> MC r -> IO ())
-> (t1 -> t2 -> t3 -> t4 -> t5 -> t6 -> r)
unsafeOp6_ = unsafeOp6 newPrim_
----------------------------------------
-- Utils
{-# INLINABLE withByteArray1 #-}
withByteArray1
:: Int
-> (s -> ByteArray# -> r)
-> (MutableByteArray# RealWorld -> IO s)
-> IO r
withByteArray1 size k c_fun = do
mba@(MutableByteArray umba) <- newByteArray size
r <- c_fun umba
ByteArray uba <- unsafeFreezeByteArray mba
return (k r uba)
{-# INLINABLE withByteArray2 #-}
withByteArray2
:: Int
-> (ByteArray# -> r)
-> (MutableByteArray# RealWorld -> MutableByteArray# RealWorld -> IO ())
-> IO (r, r)
withByteArray2 size k c_fun = do
mba@(MutableByteArray umba) <- newByteArray size
mbb@(MutableByteArray umbb) <- newByteArray size
c_fun umba umbb
ByteArray uba <- unsafeFreezeByteArray mba
ByteArray ubb <- unsafeFreezeByteArray mbb
return (k uba, k ubb)
| arybczak/haskell-mcl | src/MCL/Internal/Prim/Unpinned.hs | bsd-3-clause | 3,574 | 0 | 19 | 800 | 1,528 | 771 | 757 | 93 | 2 |
module Util.Time where
import Data.Time
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
epochNow :: IO Double
epochNow = getCurrentTime >>= utcToEpoch where
utcToEpoch :: UTCTime -> IO Double
utcToEpoch = return . fromIntegral . round . utcTimeToPOSIXSeconds
| phylake/haskell-util | Time.hs | bsd-3-clause | 290 | 0 | 9 | 59 | 71 | 40 | 31 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module ZuriHac.Plays.DebugSink (run) where
import Pipes
import ZuriHac.Plays.Sink
import ZuriHac.Plays.Prelude
run :: IO ()
run = do
eventsSourceConnection "localhost" 8000 "0" $ \conn -> runEffect $
for (eventsProducer conn) (lift . print)
| bitonic/zurihac-plays | src/ZuriHac/Plays/DebugSink.hs | bsd-3-clause | 285 | 0 | 12 | 45 | 84 | 47 | 37 | 9 | 1 |
module Main where
import Control.Arrow (second, (&&&))
import Control.Monad (forM_, liftM, when)
import Control.Monad.Reader (ReaderT, asks, liftIO,
runReaderT)
import Data.Foldable (foldlM)
import Data.List (genericLength)
import Data.Traversable (forM)
import Graphics.Rendering.Chart.Backend.Cairo
import Graphics.Rendering.Chart.Easy
import System.Directory (doesFileExist,
removeFile)
average :: (Real a, Fractional b) => [a] -> b
average xs = realToFrac (sum xs) / genericLength xs
fromBool :: Num a => Bool -> a
fromBool True = 1
fromBool False = 0
--------------------------------------------------------------------------------
-- 1.a)
pregunta1_a :: IO ()
pregunta1_a = do
doesFileExist "pregunta1_a.txt" >>= flip when (removeFile "pregunta1_a.txt")
erroress <- forM [(conjunto_and, "AND"), (conjunto_or, "OR"), (conjunto_xor, "XOR")] $ \(conjunto, nombre) -> do
(pesos, errores) <- correrLector infoInicial conjunto
appendFile "pregunta1_a.txt" $ "pesos " ++ nombre ++ ": " ++ show pesos ++ "\n"
appendFile "pregunta1_a.txt" $ "iteraciones " ++ nombre ++ ": " ++ show (length errores) ++ "\n"
appendFile "pregunta1_a.txt" $ "errores " ++ nombre ++ ": " ++ show errores ++ "\n\n"
return (errores, nombre)
-- grafica
-- toFile def "pregunta1_a.png" $ do
-- layout_title .= "Error para perceptrón"
-- forM_ erroress $ \(errores, nombre) -> do
-- plot (line nombre $ map (zip [1..]) errores)
return ()
-- 1.b)
pregunta1_b :: IO ()
pregunta1_b = do
doesFileExist "pregunta1_b.txt" >>= flip when (removeFile "pregunta1_b.txt")
forM_ [0.01, 0.1, 0.2, 0.5, 0.99] $ \t -> do
appendFile "pregunta1_b.txt" $ "TASA: " ++ show t ++ "\n"
forM [(conjunto_and, "AND"), (conjunto_or, "OR")] $ \(conjunto, nombre) -> do
(pesos, errores) <- correrLector infoInicial { tasa = t } conjunto
appendFile "pregunta1_b.txt" $ "\tpesos " ++ nombre ++ ": " ++ show pesos ++ "\n"
appendFile "pregunta1_b.txt" $ "\titeraciones " ++ nombre ++ ": " ++ show (length errores) ++ "\n"
appendFile "pregunta1_b.txt" $ "\terrores " ++ nombre ++ ": " ++ show (map (map truncate) errores) ++ "\n\n"
--------------------------------------------------------------------------------
data Información = Info
{ umbral :: Double
, tasa :: Double
}
infoInicial :: Información
infoInicial = Info 0.5 0.1
type Lector = ReaderT Información IO
--------------------------------------------------------------------------------
correrLector :: Información -> Conjunto -> IO ([Double], [[Double]])
correrLector info = liftM (second reverse) . correrRecursivo 10 pesosIniciales [] info
-- where
-- func = zip [1..] . map sum . reverse
correrRecursivo :: Int -> [Double] -> [[Double]] -> Información -> Conjunto -> IO ([Double], [[Double]])
correrRecursivo it pesos errores info conjunto =
if it > 0 then do
(pesos', errores') <- runReaderT (perceptrón pesos conjunto) info
-- cuando no hubo errores
if all (==0) errores'
then return (pesos', errores' : errores)
else correrRecursivo (pred it) pesos' (errores' : errores) info conjunto
else return (pesos, errores)
--------------------------------------------------------------------------------
pesosIniciales :: [Double]
pesosIniciales = repeat 0
----------------------------------------
-- Conjuntos de aprendizaje
type Conjunto = [([Bool], Bool)]
conjunto_and :: Conjunto
conjunto_and = [ ([ True, False, False], False)
, ([ True, False, True], False)
, ([ True, True, False], False)
, ([ True, True, True], True) ]
conjunto_nand :: Conjunto
conjunto_nand = [ ([ True, False, False], True)
, ([ True, False, True], True)
, ([ True, True, False], True)
, ([ True, True, True], False) ]
conjunto_or :: Conjunto
conjunto_or = [ ([ True, False, False], False)
, ([ True, False, True], True)
, ([ True, True, False], True)
, ([ True, True, True], True) ]
conjunto_xor :: Conjunto
conjunto_xor = [ ([ True, False, False], False)
, ([ True, False, True], True)
, ([ True, True, False], True)
, ([ True, True, True], False) ]
--------------------------------------------------------------------------------
perceptrón :: [Double] -> Conjunto -> Lector ([Double], [Double])
perceptrón pesos conjunto = foldlM func (pesos, []) conjunto
where
func :: ([Double], [Double]) -> ([Bool], Bool) -> Lector ([Double], [Double])
func (ws, errores) (xs, z) = do
(u, t) <- asks (umbral &&& tasa)
let s = sum $ zipWith (\x w -> fromBool x * w) xs ws
n = fromBool $ s > u
e = fromBool z - n
d = t * e
-- (nuevo ws, error de este caso)
return (zipWith (+) ws $ map ((*d) . fromBool) xs, e : errores)
-- esto no sirve
-- delta :: [Double] -> Conjunto -> Lector ([Double], [Double])
-- delta pesos conjunto = foldlM func (pesos, []) conjunto
-- where
-- func :: ([Double], [Double]) -> ([Bool], Bool) -> Lector ([Double], [Double])
-- func (ws, errores) (xs, z) = do
-- (u, t) <- asks (umbral &&& tasa)
-- let s = sum $ zipWith (\x w -> fromBool x * w) xs ws
-- n = fromBool $ s > u
-- e = fromBool z - n
-- d = t * e
-- -- (nuevo ws, error de este caso)
-- return (zipWith (+) ws $ map ((*d) . fromBool) xs, e : errores)
| chamini2/perceptron | perceptrón.hs | bsd-3-clause | 6,167 | 3 | 21 | 1,925 | 1,633 | 927 | 706 | 86 | 3 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, TemplateHaskell #-}
module TypeSystem.Function where
import Utils.Utils
import Utils.ToString
import TypeSystem.Types
import TypeSystem.ParseTree
import TypeSystem.Syntax
import TypeSystem.Expression
import qualified Data.Map as M
import Data.Map
import Data.List (intercalate)
import qualified Data.List as L
import Control.Arrow ((&&&))
import Lens.Micro hiding ((&))
import Lens.Micro.TH
-- The assignment of names to variables
type VariableAssignmentsA a
= Map Name (a, Maybe Path) -- If a path of numbers (indexes in the expression-tree) is given, it means a evaluation context is used
instance (ToString a, Show a) => ToString' String (VariableAssignmentsA a) where
toParsable' = _toStringVarAssgn toParsable
toCoParsable' = _toStringVarAssgn toCoParsable
debug' = _toStringVarAssgn debug
show' = const show
_toStringVarAssgn sPt sep vars
= vars & M.toList |> _showVarPair sPt & intercalate sep
_showVarPair sPt (nm, (pt, mPath))
= nm ++ " --> " ++ sPt pt ++ maybe "" (\pth -> " (With a hole at "++showComma pth++")") mPath
findAssignment :: Name -> VariableAssignmentsA a -> Maybe (a, Maybe [Int])
findAssignment = M.lookup
-- Patterns, used to deconstruct values (parsetrees) and capture variables, to calculate the end expression
data Clause = MClause {mecPatterns :: [Expression], mecExpr :: Expression}
deriving (Show, Ord, Eq)
instance FunctionlyTyped Clause where
typesOf (MClause pats e) = (pats |> typeOf) ++ [typeOf e]
{- functions do transform syntax trees (by rewrite rules) and are often used in typechecking and evaluation
Pattern matching goes from first to last clause
-}
data Function = MFunction Type [Clause]
deriving (Show, Ord, Eq)
getClauses (MFunction _ clauses) = clauses
instance FunctionlyTyped Function where
typesOf (MFunction t _) = t
type Functions = Map Name Function
data BuiltinFunction = BuiltinFunction
{ _bifName :: Name
, _bifDescr :: String
, _bifInArgs :: Either (TypeName, Int) [TypeName] -- Either (at least i times someType) or (someType -> someType); .* if everything is possible
, _bifResultType:: TypeName -- Use .* if a type should be given explicitly or ɛ if any type is possible
, _bifApply :: Either ([Int] -> Int) (TypeName -> [ParseTree] -> ParseTree)
}
makeLenses ''BuiltinFunction
numbers :: Int -> Either (TypeName, Int) a
numbers i = Left ("Number", i)
numbers0 = numbers 0
numbers1 = numbers 1
builtinFunctions'
= builtinFunctions |> (get bifName &&& id) & M.fromList
builtinFunctions
= [ BuiltinFunction "plus" "Gives a sum of all arguments (0 if none given)"
numbers0 "Number"
$ Left sum
, BuiltinFunction "min" "Gives the first argument, minus all the other arguments"
numbers1 "Number"
$ Left (\(i:is) -> i - sum is)
, BuiltinFunction "mul" "Multiplies all the arguments. (1 if none given)"
numbers0 "Number"
$ Left product
, BuiltinFunction "div" "Gives the first argument, divided by the product of the other arguments. (Integer division, rounded down))"
numbers1 "Number"
$ Left (\(i:is) -> i `div` product is)
, BuiltinFunction "mod" "Gives the first argument, module the product of the other arguments."
numbers1 "Number"
$ Left (\(i:is) -> i `mod` product is)
, BuiltinFunction "neg" "Gives the negation of the argument"
(Right ["Number"]) "Number"
$ Left (\[i] -> -1)
, BuiltinFunction "equal" "Checks that all the arguments are equal. Gives 1 if so, 0 if not."
(Right [topSymbol, topSymbol]) "Number"
$ Right (\_ (e:es) -> MInt () ("Number", 0) $ if all (e ==) es then 1 else 0)
, BuiltinFunction "error" "Stops the function, gives a stack trace. When used in a rule, this won't match a predicate"
(Left (topSymbol, 0)) bottomSymbol
$ Right (\_ pts -> pts & toParsable' " " & MLiteral () (bottomSymbol, 0))
, BuiltinFunction "subs" ("(expression to replace, to replace with, in this expression) "
++ "Replaces each occurence of the first expression by the second, in the third argument."
++" You'll want to explictly type this one, by using `subs:returnType(\"x\", \"41\", \"x + 1\")`")
(Right [topSymbol, topSymbol, topSymbol]) topSymbol
$ Right (\_ [searchFor, replaceBy, inExpr] ->
let paths = search (==searchFor) inExpr
folded = L.foldl (\pt path -> replace pt path replaceBy) inExpr paths
in folded)
, BuiltinFunction "group" "Given a parsetree, flattens the contents of the parsetree to a single string"
(Right [topSymbol]) "StringUnesc"
$ Right (\_ [pt] -> flatten pt & trd3 & MLiteral () ("StringUnesc", 0))
]
instance Refactorable TypeName Clause where
refactor ftn (MClause pats expr)
= MClause (pats |> refactor ftn) (refactor ftn expr)
instance Refactorable TypeName Function where
refactor ftn (MFunction tp clauses)
= MFunction (tp |> ftn) (clauses |> refactor ftn)
instance Refactorable TypeName Functions where
refactor ftn funcs = funcs |> refactor ftn
instance Refactorable FunctionName Clause where
refactor ffn (MClause pats expr)
= MClause (pats |> refactor ffn) (refactor ffn expr)
instance Refactorable FunctionName Function where
refactor ffn (MFunction tp clauses)
= MFunction tp (clauses |> refactor ffn)
instance Refactorable FunctionName Functions where
refactor ffn funcs
= funcs |> refactor ffn & mapKeys (unliftFunctionName ffn)
instance ToString' (Name, Int) Clause where
show' = clauseWith show
toParsable'
= clauseWith toParsable
toCoParsable' = clauseWith toCoParsable
debug' = clauseWith debug
clauseWith exprShow (fname, i) (MClause pats expr)
= let head = fname ++ inParens (pats |> exprShow & commas)
spacing = replicate (i - length head) ' ' ++ (if length head > i then "\n"++replicate i ' ' else "") ++ " = "
tail = exprShow expr in
head ++ spacing ++ tail
instance ToString' (Name, Int) Function where
show' nmi = funcWith "" (show' nmi) nmi
toParsable' nmi = funcWith "" (toParsable' nmi) nmi
toCoParsable' nmi
= funcWith "" (toCoParsable' nmi) nmi
debug' nmi = funcWith "" (debug' nmi) nmi
funcWith underSignature showClause (name, int) (MFunction tp clauses)
= let sign = name ++ replicate (int - length name) ' ' ++ " : "++ intercalate " -> " tp
sign' = sign ++ underSignature
-- we drop the last clause, as it is an automatically added error clause for non exhaustive patterns
clss = clauses |> showClause in
(sign':clss) & unlines
| pietervdvn/ALGT | src/TypeSystem/Function.hs | bsd-3-clause | 6,435 | 254 | 11 | 1,187 | 1,927 | 1,052 | 875 | 126 | 2 |
module Wishlist.Clients.MultiTenant where
import Data.Proxy
import Network.HTTP.Client hiding (Proxy)
import Servant.API
import Servant.Client
import WishlistMT
import Wishlist.Types.MultiTenant
-- part #4: client functions for the wishlist service API
allWishes :: Maybe Tenant -> ClientM RichWishlist
shopWishes :: Maybe Tenant -> Shop -> ClientM RichWishlist
addWish :: Maybe Tenant -> Wish -> ClientM ()
allWishes :<|> shopWishes :<|> addWish = client (Proxy :: Proxy API)
exec :: ClientM a -> IO (Either ServantError a)
exec query = do
manager <- newManager defaultManagerSettings
let clientEnv = ClientEnv manager (BaseUrl Http "localhost" 8080 "")
runClientM query clientEnv
| bollmann/lunchtalk | src/Wishlist/Clients/MultiTenant.hs | bsd-3-clause | 692 | 0 | 12 | 103 | 200 | 102 | 98 | 16 | 1 |
module Profiler where
import Rumpus
import qualified Data.HashMap.Strict as Map
start :: Start
start = do
setSize (V3 0.4 0.4 0.1)
--setRotation (V3 0 1 0) pi
rootSample <- getSampleHistory
let indexedSamples = zip [0..] (Map.toList rootSample)
numSamples = Map.size rootSample
containerID <- spawnChild (mySize ==> 0.3)
gauges <- inEntity containerID $ do
Map.fromList <$> forM indexedSamples (\(i, (name, values)) -> do
let y = i*0.1 + 1
-- Label
spawnChild $ do
myPose ==> position (V3 0 y 0.1)
myTextPose ==> scaleMatrix 0.05
myText ==> name
myTransformType ==> RelativeFull
-- Graph
childIDs <- forM [0..maxProfilerHistory - 1] $ \z -> spawnChild $ do
let brightness = 1 -
(fromIntegral z /
fromIntegral maxProfilerHistory
* 0.5 + 0.3)
myShape ==> Cube
myTransformType ==> RelativeFull
mySize ==> 0.1
myColor ==> colorHSL
(i / fromIntegral numSamples)
1
brightness
myPose ==> position (V3 0 y (-fromIntegral z*0.1))
return (name, childIDs))
myUpdate ==> do
sampleHistory <- getSampleHistory
forM_ (Map.toList sampleHistory) $ \(name, toList -> values) -> do
forM_ (Map.lookup name gauges) $ \childIDs -> do
forM_ (zip childIDs values) $ \(childID, value) -> do
inEntity childID $ do
setSize (V3 (realToFrac value * 100) 0.05 0.1)
return ()
| lukexi/rumpus | pristine/Room/Profiler.hs | bsd-3-clause | 1,790 | 0 | 31 | 739 | 521 | 254 | 267 | -1 | -1 |
module Data.String.Interpolate.Util (unindent) where
import Control.Arrow ((>>>))
import Data.Char
-- | Remove indentation as much as possible while preserving relative
-- indentation levels.
--
-- `unindent` is useful in combination with `Data.String.Interpolate.i` to remove leading spaces that
-- resulted from code indentation. That way you can freely indent your string
-- literals without the indentation ending up in the resulting strings.
--
-- Here is an example:
--
-- >>> :set -XQuasiQuotes
-- >>> import Data.String.Interpolate
-- >>> import Data.String.Interpolate.Util
-- >>> :{
-- putStr $ unindent [i|
-- def foo
-- 23
-- end
-- |]
-- :}
-- def foo
-- 23
-- end
--
-- To allow this, two additional things are being done, apart from removing
-- indentation:
--
-- - One empty line at the beginning will be removed and
-- - if the last newline character (@"\\n"@) is followed by spaces, the spaces are removed.
unindent :: String -> String
unindent =
lines_
>>> removeLeadingEmptyLine
>>> trimLastLine
>>> removeIndentation
>>> concat
where
isEmptyLine :: String -> Bool
isEmptyLine = all isSpace
lines_ :: String -> [String]
lines_ [] = []
lines_ s = case span (/= '\n') s of
(first, '\n' : rest) -> (first ++ "\n") : lines_ rest
(first, rest) -> first : lines_ rest
removeLeadingEmptyLine :: [String] -> [String]
removeLeadingEmptyLine xs = case xs of
y:ys | isEmptyLine y -> ys
_ -> xs
trimLastLine :: [String] -> [String]
trimLastLine (a : b : r) = a : trimLastLine (b : r)
trimLastLine [a] = if all (== ' ') a
then []
else [a]
trimLastLine [] = []
removeIndentation :: [String] -> [String]
removeIndentation ys = map (dropSpaces indentation) ys
where
dropSpaces 0 s = s
dropSpaces n (' ' : r) = dropSpaces (n - 1) r
dropSpaces _ s = s
indentation = minimalIndentation ys
minimalIndentation =
safeMinimum 0
. map (length . takeWhile (== ' '))
. removeEmptyLines
removeEmptyLines = filter (not . isEmptyLine)
safeMinimum :: Ord a => a -> [a] -> a
safeMinimum x xs = case xs of
[] -> x
_ -> minimum xs
| sol/interpolate | src/Data/String/Interpolate/Util.hs | mit | 2,295 | 0 | 15 | 628 | 541 | 301 | 240 | 42 | 10 |
module Handler.HackDay where
import Import
import Handler.Voting (setOwner)
data HackDayForm = HackDayForm
{ formTitle :: Text
}
deriving Show
titleSettings = FieldSettings
{ fsLabel = "Title"
, fsTooltip = Nothing
, fsId = Just "titleField"
, fsName = Nothing
, fsAttrs = [("placeholder","June Hackday"),("style","text-align: center;")]
}
hackDayForm :: Maybe HackDayForm -> AForm Handler HackDayForm
hackDayForm mForm = HackDayForm
<$> areq textField titleSettings (formTitle <$> mForm)
currentHackday :: [Entity HackDay] -> Maybe (Entity HackDay)
currentHackday hackdays = headMaybe hackdays >>= openHackday
openHackday :: Entity HackDay -> Maybe (Entity HackDay)
openHackday hackday@(Entity _id day) = if hackDayVotingOpen day
then Just hackday
else Nothing
headMaybe :: [a] -> Maybe a
headMaybe [] = Nothing
headMaybe (x:_) = Just x
tailEmpty :: [a] -> [a]
tailEmpty [] = []
tailEmpty (_:xs) = xs
currentAndPastHackdays :: [Entity HackDay] -> (Maybe (Entity HackDay), [Entity HackDay])
currentAndPastHackdays xs =
case currentHackday xs of
Nothing -> (Nothing, xs)
Just x -> (Just x, tailEmpty xs)
getHackDayR :: Handler Html
getHackDayR = do
(widget, enctype) <- generateFormPost $ renderBootstrap (hackDayForm Nothing)
allHackdays <- runDB $ selectList [] [Desc HackDayCreated]
let (currentHackday, pastHackdays) = currentAndPastHackdays allHackdays
defaultLayout $ do
setTitle "Hackday!"
$(widgetFile "listhackdays")
postHackDayR :: Handler Html
postHackDayR = do
((res, widget), enctype) <- runFormPost $ renderBootstrap (hackDayForm Nothing)
case res of
FormSuccess hackForm -> do
currentTime <- liftIO getCurrentTime
hackId <- runDB $ insert HackDay { hackDayTitle = formTitle hackForm
, hackDayCreated = currentTime
, hackDayVotingClosed = False }
setOwner hackId
redirect (HackDayDetailsR hackId)
_ -> do
allHackdays <- runDB $ selectList [] [Desc HackDayCreated]
let (currentHackday, pastHackdays) = currentAndPastHackdays allHackdays
defaultLayout $(widgetFile "listhackdays")
| MaxGabriel/hackvote-yesod | Handler/HackDay.hs | cc0-1.0 | 2,548 | 0 | 17 | 821 | 693 | 354 | 339 | 55 | 2 |
data A = A Int
| B Char
| roberth/uu-helium | test/make/NoEqImport1.hs | gpl-3.0 | 33 | 0 | 6 | 17 | 15 | 8 | 7 | 2 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.