code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.Glacier.ListJobs
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | This operation lists jobs for a vault, including jobs that are in-progress
-- and jobs that have recently finished.
--
-- Amazon Glacier retains recently completed jobs for a period before deleting
-- them; however, it eventually removes completed jobs. The output of completed
-- jobs can be retrieved. Retaining completed jobs for a period of time after
-- they have completed enables you to get a job output in the event you miss the
-- job completion notification or your first attempt to download it fails. For
-- example, suppose you start an archive retrieval job to download an archive.
-- After the job completes, you start to download the archive but encounter a
-- network error. In this scenario, you can retry and download the archive while
-- the job exists.
--
-- To retrieve an archive or retrieve a vault inventory from Amazon Glacier,
-- you first initiate a job, and after the job completes, you download the data.
-- For an archive retrieval, the output is the archive data, and for an
-- inventory retrieval, it is the inventory list. The List Job operation returns
-- a list of these jobs sorted by job initiation time.
--
-- This List Jobs operation supports pagination. By default, this operation
-- returns up to 1,000 jobs in the response. You should always check the
-- response for a 'marker' at which to continue the list; if there are no more
-- items the 'marker' is 'null'. To return a list of jobs that begins at a specific
-- job, set the 'marker' request parameter to the value you obtained from a
-- previous List Jobs request. You can also limit the number of jobs returned in
-- the response by specifying the 'limit' parameter in the request.
--
-- Additionally, you can filter the jobs list returned by specifying an
-- optional 'statuscode' (InProgress, Succeeded, or Failed) and 'completed' (true,
-- false) parameter. The 'statuscode' allows you to specify that only jobs that
-- match a specified status are returned. The 'completed' parameter allows you to
-- specify that only jobs in a specific completion state are returned.
--
-- An AWS account has full permission to perform all operations (actions).
-- However, AWS Identity and Access Management (IAM) users don't have any
-- permissions by default. You must grant them explicit permission to perform
-- specific actions. For more information, see <http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html Access Control Using AWS Identityand Access Management (IAM)>.
--
-- For the underlying REST API, go to <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-jobs-get.html List Jobs >
--
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-ListJobs.html>
module Network.AWS.Glacier.ListJobs
(
-- * Request
ListJobs
-- ** Request constructor
, listJobs
-- ** Request lenses
, ljAccountId
, ljCompleted
, ljLimit
, ljMarker
, ljStatuscode
, ljVaultName
-- * Response
, ListJobsResponse
-- ** Response constructor
, listJobsResponse
-- ** Response lenses
, ljrJobList
, ljrMarker
) where
import Network.AWS.Prelude
import Network.AWS.Request.RestJSON
import Network.AWS.Glacier.Types
import qualified GHC.Exts
data ListJobs = ListJobs
{ _ljAccountId :: Text
, _ljCompleted :: Maybe Text
, _ljLimit :: Maybe Text
, _ljMarker :: Maybe Text
, _ljStatuscode :: Maybe Text
, _ljVaultName :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'ListJobs' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ljAccountId' @::@ 'Text'
--
-- * 'ljCompleted' @::@ 'Maybe' 'Text'
--
-- * 'ljLimit' @::@ 'Maybe' 'Text'
--
-- * 'ljMarker' @::@ 'Maybe' 'Text'
--
-- * 'ljStatuscode' @::@ 'Maybe' 'Text'
--
-- * 'ljVaultName' @::@ 'Text'
--
listJobs :: Text -- ^ 'ljAccountId'
-> Text -- ^ 'ljVaultName'
-> ListJobs
listJobs p1 p2 = ListJobs
{ _ljAccountId = p1
, _ljVaultName = p2
, _ljLimit = Nothing
, _ljMarker = Nothing
, _ljStatuscode = Nothing
, _ljCompleted = Nothing
}
-- | The 'AccountId' is the AWS Account ID. You can specify either the AWS Account
-- ID or optionally a '-', in which case Amazon Glacier uses the AWS Account ID
-- associated with the credentials used to sign the request. If you specify your
-- Account ID, do not include hyphens in it.
ljAccountId :: Lens' ListJobs Text
ljAccountId = lens _ljAccountId (\s a -> s { _ljAccountId = a })
-- | Specifies the state of the jobs to return. You can specify 'true' or 'false'.
ljCompleted :: Lens' ListJobs (Maybe Text)
ljCompleted = lens _ljCompleted (\s a -> s { _ljCompleted = a })
-- | Specifies that the response be limited to the specified number of items or
-- fewer. If not specified, the List Jobs operation returns up to 1,000 jobs.
ljLimit :: Lens' ListJobs (Maybe Text)
ljLimit = lens _ljLimit (\s a -> s { _ljLimit = a })
-- | An opaque string used for pagination. This value specifies the job at which
-- the listing of jobs should begin. Get the marker value from a previous List
-- Jobs response. You need only include the marker if you are continuing the
-- pagination of results started in a previous List Jobs request.
ljMarker :: Lens' ListJobs (Maybe Text)
ljMarker = lens _ljMarker (\s a -> s { _ljMarker = a })
-- | Specifies the type of job status to return. You can specify the following
-- values: "InProgress", "Succeeded", or "Failed".
ljStatuscode :: Lens' ListJobs (Maybe Text)
ljStatuscode = lens _ljStatuscode (\s a -> s { _ljStatuscode = a })
-- | The name of the vault.
ljVaultName :: Lens' ListJobs Text
ljVaultName = lens _ljVaultName (\s a -> s { _ljVaultName = a })
data ListJobsResponse = ListJobsResponse
{ _ljrJobList :: List "JobList" GlacierJobDescription
, _ljrMarker :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'ListJobsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ljrJobList' @::@ ['GlacierJobDescription']
--
-- * 'ljrMarker' @::@ 'Maybe' 'Text'
--
listJobsResponse :: ListJobsResponse
listJobsResponse = ListJobsResponse
{ _ljrJobList = mempty
, _ljrMarker = Nothing
}
-- | A list of job objects. Each job object contains metadata describing the job.
ljrJobList :: Lens' ListJobsResponse [GlacierJobDescription]
ljrJobList = lens _ljrJobList (\s a -> s { _ljrJobList = a }) . _List
-- | An opaque string that represents where to continue pagination of the results.
-- You use this value in a new List Jobs request to obtain more jobs in the
-- list. If there are no more jobs, this value is 'null'.
ljrMarker :: Lens' ListJobsResponse (Maybe Text)
ljrMarker = lens _ljrMarker (\s a -> s { _ljrMarker = a })
instance ToPath ListJobs where
toPath ListJobs{..} = mconcat
[ "/"
, toText _ljAccountId
, "/vaults/"
, toText _ljVaultName
, "/jobs"
]
instance ToQuery ListJobs where
toQuery ListJobs{..} = mconcat
[ "limit" =? _ljLimit
, "marker" =? _ljMarker
, "statuscode" =? _ljStatuscode
, "completed" =? _ljCompleted
]
instance ToHeaders ListJobs
instance ToJSON ListJobs where
toJSON = const (toJSON Empty)
instance AWSRequest ListJobs where
type Sv ListJobs = Glacier
type Rs ListJobs = ListJobsResponse
request = get
response = jsonResponse
instance FromJSON ListJobsResponse where
parseJSON = withObject "ListJobsResponse" $ \o -> ListJobsResponse
<$> o .:? "JobList" .!= mempty
<*> o .:? "Marker"
|
dysinger/amazonka
|
amazonka-glacier/gen/Network/AWS/Glacier/ListJobs.hs
|
mpl-2.0
| 8,632 | 0 | 12 | 1,839 | 939 | 576 | 363 | 95 | 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.Language.Documents.AnalyzeEntitySentiment
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Finds entities, similar to AnalyzeEntities in the text and analyzes
-- sentiment associated with each entity and its mentions.
--
-- /See:/ <https://cloud.google.com/natural-language/ Cloud Natural Language API Reference> for @language.documents.analyzeEntitySentiment@.
module Network.Google.Resource.Language.Documents.AnalyzeEntitySentiment
(
-- * REST Resource
DocumentsAnalyzeEntitySentimentResource
-- * Creating a Request
, documentsAnalyzeEntitySentiment
, DocumentsAnalyzeEntitySentiment
-- * Request Lenses
, daesXgafv
, daesUploadProtocol
, daesAccessToken
, daesUploadType
, daesPayload
, daesCallback
) where
import Network.Google.Language.Types
import Network.Google.Prelude
-- | A resource alias for @language.documents.analyzeEntitySentiment@ method which the
-- 'DocumentsAnalyzeEntitySentiment' request conforms to.
type DocumentsAnalyzeEntitySentimentResource =
"v1" :>
"documents:analyzeEntitySentiment" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] AnalyzeEntitySentimentRequest :>
Post '[JSON] AnalyzeEntitySentimentResponse
-- | Finds entities, similar to AnalyzeEntities in the text and analyzes
-- sentiment associated with each entity and its mentions.
--
-- /See:/ 'documentsAnalyzeEntitySentiment' smart constructor.
data DocumentsAnalyzeEntitySentiment =
DocumentsAnalyzeEntitySentiment'
{ _daesXgafv :: !(Maybe Xgafv)
, _daesUploadProtocol :: !(Maybe Text)
, _daesAccessToken :: !(Maybe Text)
, _daesUploadType :: !(Maybe Text)
, _daesPayload :: !AnalyzeEntitySentimentRequest
, _daesCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DocumentsAnalyzeEntitySentiment' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'daesXgafv'
--
-- * 'daesUploadProtocol'
--
-- * 'daesAccessToken'
--
-- * 'daesUploadType'
--
-- * 'daesPayload'
--
-- * 'daesCallback'
documentsAnalyzeEntitySentiment
:: AnalyzeEntitySentimentRequest -- ^ 'daesPayload'
-> DocumentsAnalyzeEntitySentiment
documentsAnalyzeEntitySentiment pDaesPayload_ =
DocumentsAnalyzeEntitySentiment'
{ _daesXgafv = Nothing
, _daesUploadProtocol = Nothing
, _daesAccessToken = Nothing
, _daesUploadType = Nothing
, _daesPayload = pDaesPayload_
, _daesCallback = Nothing
}
-- | V1 error format.
daesXgafv :: Lens' DocumentsAnalyzeEntitySentiment (Maybe Xgafv)
daesXgafv
= lens _daesXgafv (\ s a -> s{_daesXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
daesUploadProtocol :: Lens' DocumentsAnalyzeEntitySentiment (Maybe Text)
daesUploadProtocol
= lens _daesUploadProtocol
(\ s a -> s{_daesUploadProtocol = a})
-- | OAuth access token.
daesAccessToken :: Lens' DocumentsAnalyzeEntitySentiment (Maybe Text)
daesAccessToken
= lens _daesAccessToken
(\ s a -> s{_daesAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
daesUploadType :: Lens' DocumentsAnalyzeEntitySentiment (Maybe Text)
daesUploadType
= lens _daesUploadType
(\ s a -> s{_daesUploadType = a})
-- | Multipart request metadata.
daesPayload :: Lens' DocumentsAnalyzeEntitySentiment AnalyzeEntitySentimentRequest
daesPayload
= lens _daesPayload (\ s a -> s{_daesPayload = a})
-- | JSONP
daesCallback :: Lens' DocumentsAnalyzeEntitySentiment (Maybe Text)
daesCallback
= lens _daesCallback (\ s a -> s{_daesCallback = a})
instance GoogleRequest
DocumentsAnalyzeEntitySentiment
where
type Rs DocumentsAnalyzeEntitySentiment =
AnalyzeEntitySentimentResponse
type Scopes DocumentsAnalyzeEntitySentiment =
'["https://www.googleapis.com/auth/cloud-language",
"https://www.googleapis.com/auth/cloud-platform"]
requestClient DocumentsAnalyzeEntitySentiment'{..}
= go _daesXgafv _daesUploadProtocol _daesAccessToken
_daesUploadType
_daesCallback
(Just AltJSON)
_daesPayload
languageService
where go
= buildClient
(Proxy ::
Proxy DocumentsAnalyzeEntitySentimentResource)
mempty
|
brendanhay/gogol
|
gogol-language/gen/Network/Google/Resource/Language/Documents/AnalyzeEntitySentiment.hs
|
mpl-2.0
| 5,430 | 0 | 16 | 1,172 | 708 | 414 | 294 | 108 | 1 |
module Main where
import System.Environment (getArgs)
import System.Directory
main :: IO ()
main = do args <- getArgs
mapM_ removeDirectory args
|
tyoko-dev/coreutils-haskell
|
src/rmdir.hs
|
agpl-3.0
| 156 | 0 | 7 | 32 | 49 | 26 | 23 | 6 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TemplateHaskell #-}
module Tactics where
data family Sing (a :: k)
data Nat :: * where
Zero :: Nat
Succ :: Nat -> Nat
data instance Sing (n :: Nat) where
SZero :: Sing Zero
SSucc :: Sing n -> Sing (Succ n)
type family (a :: Nat) :+ (b :: Nat) :: Nat
type instance Zero :+ n = n
type instance Succ n :+ m = Succ (n :+ m)
-- and a convenient type synonym
type SNat (n :: Nat) = Sing n
data a :~: b where
Refl :: a :~: a
sym :: (a :~: b) -> (b :~: a)
sym Refl = Refl
trans :: (a :~: b) -> (b :~: c) -> (a :~: c)
trans Refl Refl = Refl
-- congruence is defined for a function working on singleton
-- types. Agda's definition is more general because Agda has a common
-- language for terms and types.
cong :: (Sing a -> Sing b) -> (a :~: c) -> (f a :~: f c)
cong _ Refl = Refl
-- Agda's equivalent of subst is gcastWith, used for type-safe casts
-- when we have a proof of equality of two types. gcastWith is more
-- convenient to use than Agda's subst because it doesn't require the
-- type constructor to be passed in. (See my Agda implementation if
-- this doesn't make sense).
gcastWith :: (a :~: b) -> ((a ~ b) => r) -> r
gcastWith Refl x = x
plusZero :: forall a. SNat a -> ((a :+ Zero) :~: a)
plusZero = \n -> case n of
SZero -> Refl
SSucc n' -> cong SSucc (plusZero n')
{-
plusSucc :: SNat a -> SNat b -> ((Succ (a :+ b)) :~: (a :+ (Succ b)))
plusSucc = \a b -> case a of
SZero -> Refl
SSucc a' -> cong SSucc _
plusZero :: SNat a -> ((a :+ Zero) :~: a)
plusZero SZero = Refl
plusZero (SSucc a) = cong SSucc (plusZero a)
plusSucc :: SNat a -> SNat b -> ((Succ (a :+ b)) :~: (a :+ (Succ b)))
plusSucc SZero _ = Refl
plusSucc (SSucc a) b = cong SSucc (plusSucc a b)
plusComm :: SNat a -> SNat b -> (a :+ b) :~: (b :+ a)
plusComm a SZero = plusZero a
plusComm a (SSucc b) = trans (sym (plusSucc a b))
(cong SSucc (plusComm a b ))
-}
|
jstolarek/sandbox
|
haskell/Tactics.hs
|
unlicense
| 2,196 | 4 | 11 | 616 | 434 | 249 | 185 | 33 | 2 |
{-# LANGUAGE GADTs #-}
data MathExp a where
Add :: (Num a) => MathExp a -> MathExp a -> MathExp a
Minu :: (Num a) => MathExp a -> MathExp a -> MathExp a
Mul :: (Num a) => MathExp a -> MathExp a -> MathExp a
-- Div :: (Num a, Fractional a) => MathExp a -> MathExp a -> MathExp a
Val :: (Num a) => a -> MathExp a
{--
data MathExp a =
Add (MathExp a) (MathExp a)|
Minu (MathExp a) (MathExp a)|
Mul (MathExp a) (MathExp a)|
Div (MathExp a) (MathExp a)|
Val a
--}
eval :: MathExp a -> a
eval (Add x y) = eval x + eval y
eval (Minu x y) = eval x - eval y
eval (Mul x y) = eval x * eval y
--eval (Div x y) = eval x `div` eval y
eval (Val x) = x
main :: IO()
main = do
let a = Add (Val 1) (Mul (Val 2) (Val 3))
print (eval a::Integer)
|
ccqpein/Arithmetic-Exercises
|
calculator/calculator.hs
|
apache-2.0
| 760 | 0 | 14 | 204 | 298 | 147 | 151 | 15 | 1 |
{-# LANGUAGE ViewPatterns #-}
module Logging.Glue where
import GHC.RTS.Events
import Text.Scanf
getUserMessage :: Event -> Maybe String
getUserMessage (Event _ (UserMessage m)) = Just m
getUserMessage _ = Nothing
getContinuation, getSplit :: String -> Maybe (Int, String)
getContinuation = ints (lit "[[" :^ int :^ lit "]]") id
getSplit s = fmap (\(n, r)->(n, reverse r)) $ ints (lit "]]" :^ intR :^ lit "[[") id (reverse s)
glueMessages0 :: [Event] -> [Event]
glueMessages0 = map mapEvts
where
mapEvts (Event _ (UserMessage m)) = error ("Found naked user msg: " ++ m)
mapEvts e = case spec e of
es@(EventBlock _ _ b) -> e {spec = es {block_events = glue b}}
_ -> e
-- Events inside the block are ordered
-- thus we should have all message parts adjacent.
glue :: [Event] -> [Event]
glue (x : xs) | Nothing <- getUserMessage x = x : glue xs
glue (x : xs) | Just m <- getUserMessage x =
case getSplit m of
Nothing -> x : glue xs
Just (sn, chunk) -> glueinner sn [chunk] xs
glue [] = []
glue _ = error "Internal error (should not happen)."
glueinner n acc (x : xs)
| Just m <- getUserMessage x
, Just (sn, chunk) <- getContinuation m =
if sn /= n
then error "Invalid message chunk: wrong continuation number."
else case getSplit chunk of
Nothing -> x {spec = UserMessage (concat $ reverse (chunk:acc))} : glue xs
Just (n1, m1) -> glueinner n1 (m1:acc) xs
glueinner _ _ _ = error "Invalid message chunk: no continuation."
glueMessages :: EventLog -> EventLog
glueMessages (EventLog hdr (Data evts)) = EventLog hdr (Data $ glueMessages0 evts)
|
SKA-ScienceDataProcessor/RC
|
MS6/LogAn/Logging/Glue.hs
|
apache-2.0
| 1,790 | 0 | 20 | 529 | 653 | 332 | 321 | 35 | 10 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
module BarthPar.Scrape.Types.DOM where
import Control.Arrow ((&&&))
import Control.DeepSeq
import Control.Lens hiding ((.=))
import Data.Csv hiding (HasHeader (..), Header,
header)
import Data.Data
import Data.Ord
import Data.Text.Buildable
import qualified Data.Text.Format as F
import qualified Data.Text.Lazy as TL
import GHC.Generics hiding (to)
import Lucid
import BarthPar.Scrape.Types.Internals
import BarthPar.Scrape.Types.Utils
data Chunk
= Chunk
{ _chunkVolume :: !Header
, _chunkPart :: !Int
, _chunkChapter :: !Header
, _chunkParagraph :: !Header
, _chunkN :: !Int
, _chunkStart :: !Int
, _chunkContent :: !Content
} deriving (Show, Eq, Data, Typeable, Generic)
$(makeClassy ''Chunk)
instance NFData Chunk
instance Ord Chunk where
compare = comparing ( _chunkVolume
&&& _chunkPart
&&& _chunkChapter
&&& _chunkParagraph
&&& _chunkN
)
instance ToHtml Chunk where
toHtml Chunk{..} =
details_ $ do
summary_ . toHtml $ F.format "Chunk #{} @ {}" (_chunkN, _chunkStart)
div_ $ toHtml _chunkContent
toHtmlRaw Chunk{..} =
details_ $ do
summary_ . toHtmlRaw
$ F.format "Chunk #{} @ {}" (_chunkN, _chunkStart)
div_ $ toHtmlRaw _chunkContent
instance ToNamedRecord Chunk where
toNamedRecord c =
namedRecord [ "volume_n" .= (c ^. chunkVolume . headerN)
, "volume_title" .= (c ^. chunkVolume . headerTitle)
, "part" .= (c ^. chunkPart)
, "chapter_n" .= (c ^. chunkChapter . headerN)
, "chapter_title" .= (c ^. chunkChapter . headerTitle)
, "paragraph_n" .= (c ^. chunkParagraph . headerN)
, "paragraph_title" .= (c ^. chunkParagraph . headerTitle)
, "chunk_n" .= (c ^. chunkN)
, "chunk_start" .= (c ^. chunkStart)
]
instance DefaultOrdered Chunk where
headerOrder _ = [ "volume_n"
, "volume_title"
, "part"
, "chapter_n"
, "chapter_title"
, "paragraph_n"
, "paragraph_title"
, "chunk_n"
, "chunk_start"
]
instance Buildable Chunk where
build = build . view chunkContent
data ContentBlock -- ^ CD I.1.1.§.N
= ContentBlock
{ _blockVolume :: !Header
, _blockPart :: !Int
, _blockChapter :: !Header
, _blockParagraph :: !Header
, _blockN :: !Int
, _blockContent :: !Content
, _blockExcursus :: !Content
} deriving (Show, Eq, Data, Typeable, Generic)
$(makeClassy ''ContentBlock)
instance NFData ContentBlock
instance Ord ContentBlock where
compare = comparing ( _blockVolume
&&& _blockPart
&&& _blockChapter
&&& _blockParagraph
&&& _blockN
)
instance ToHtml ContentBlock where
toHtml ContentBlock{..} =
details_ $ do
summary_ . toHtml . F.format "Block #{}" $ F.Only _blockN
div_ $ toHtml _blockContent
blockquote_ $ toHtml _blockExcursus
toHtmlRaw ContentBlock{..} =
details_ $ do
summary_ . toHtmlRaw . F.format "Block #{}" $ F.Only _blockN
div_ $ toHtmlRaw _blockContent
blockquote_ $ toHtmlRaw _blockExcursus
instance ToNamedRecord ContentBlock where
toNamedRecord b =
namedRecord [ "volume_n" .= (b ^. blockVolume . headerN)
, "volume_title" .= (b ^. blockVolume . headerTitle)
, "part" .= (b ^. blockPart)
, "chapter_n" .= (b ^. blockChapter . headerN)
, "chapter_title" .= (b ^. blockChapter . headerTitle)
, "paragraph_n" .= (b ^. blockParagraph . headerN)
, "paragraph_title" .= (b ^. blockParagraph . headerTitle)
, "block_n" .= (b ^. blockN)
]
instance DefaultOrdered ContentBlock where
headerOrder _ = [ "volume_n"
, "volume_title"
, "part"
, "chapter_n"
, "chapter_title"
, "paragraph_n"
, "paragraph_title"
, "block_n"
]
instance Buildable ContentBlock where
build b = hr [ b ^. blockContent
, b ^. blockExcursus
]
data Paragraph c
= Paragraph -- ^ CD I.1.1.§
{ _paragraphVolume :: !Header
, _paragraphPart :: !Int
, _paragraphChapter :: !Header
, _paragraphN :: !Int
, _paragraphTitle :: !Title
, _paragraphContent :: ![c]
} deriving (Show, Eq, Data, Typeable, Generic, Functor)
$(makeLenses ''Paragraph)
instance NFData c => NFData (Paragraph c)
instance Eq c => Ord (Paragraph c) where
compare = comparing ( _paragraphVolume
&&& _paragraphPart
&&& _paragraphChapter
&&& _paragraphN
)
instance ToHtml c => ToHtml (Paragraph c) where
toHtml Paragraph{..} =
details_ $ do
summary_ . toHtml
$ F.format "¶ {}. {}" (_paragraphN, _paragraphTitle)
mapM_ toHtml _paragraphContent
toHtmlRaw Paragraph{..} =
details_ $ do
summary_ . toHtmlRaw
$ F.format "¶ {}. {}" (_paragraphN, _paragraphTitle)
mapM_ toHtmlRaw _paragraphContent
instance ToNamedRecord (Paragraph c) where
toNamedRecord p =
namedRecord [ "volume_n" .= (p ^. paragraphVolume . headerN)
, "volume_title" .= (p ^. paragraphVolume . headerTitle)
, "part" .= (p ^. paragraphPart)
, "chapter_n" .= (p ^. paragraphChapter . headerN)
, "chapter_title" .= (p ^. paragraphChapter . headerTitle)
, "paragraph_n" .= (p ^. paragraphN)
, "paragraph_title" .= (p ^. paragraphTitle)
]
instance DefaultOrdered (Paragraph c) where
headerOrder _ = [ "volume_n"
, "volume_title"
, "part"
, "chapter_n"
, "chapter_title"
, "paragraph_n"
, "paragraph_title"
]
instance Buildable c => Buildable (Paragraph c) where
build p = hr $ p ^. paragraphContent
data Chapter c
= Chapter -- ^ CD I.1.§
{ _chapterVolume :: !Header
, _chapterPart :: !Int
, _chapterAbstract :: ![c]
, _chapterN :: !Int
, _chapterTitle :: !Title
, _chapterContent :: ![Paragraph c]
} deriving (Show, Eq, Data, Typeable, Generic, Functor)
$(makeLenses ''Chapter)
instance NFData c => NFData (Chapter c)
instance Eq c => Ord (Chapter c) where
compare = comparing ( _chapterVolume
&&& _chapterPart
&&& _chapterN
)
instance ToHtml c => ToHtml (Chapter c) where
toHtml Chapter{..} =
details_ $ do
summary_ . toHtml
$ F.format "Chapter {}. {}" (_chapterN, _chapterTitle)
blockquote_ $ mapM_ toHtml _chapterAbstract
mapM_ toHtml _chapterContent
toHtmlRaw Chapter{..} =
details_ $ do
summary_ . toHtmlRaw
$ F.format "Chapter {}. {}" (_chapterN, _chapterTitle)
blockquote_ $ mapM_ toHtmlRaw _chapterAbstract
mapM_ toHtmlRaw _chapterContent
instance ToNamedRecord (Chapter c) where
toNamedRecord c =
namedRecord [ "volume_n" .= (c ^. chapterVolume . headerN)
, "volume_title" .= (c ^. chapterVolume . headerTitle)
, "part" .= (c ^. chapterPart)
, "chapter_n" .= (c ^. chapterN)
, "chapter_title" .= (c ^. chapterTitle)
]
instance DefaultOrdered (Chapter c) where
headerOrder _ = [ "volume_n"
, "volume_title"
, "part"
, "chapter_n"
, "chapter_title"
]
instance Buildable c => Buildable (Chapter c) where
build c = hr
. (foldMap build (c ^. chapterAbstract):)
. fmap build
$ c ^. chapterContent
data Part c
= Part -- ^ CD I.1
{ _partVolume :: !Header
, _partN :: !Int
, _partContent :: ![Chapter c]
} deriving (Show, Eq, Data, Typeable, Generic, Functor)
$(makeLenses ''Part)
instance NFData c => NFData (Part c)
instance Eq c => Ord (Part c) where
compare = comparing (_partVolume &&& _partN)
instance ToHtml c => ToHtml (Part c) where
toHtml Part{..} =
details_ $ do
summary_ . toHtml . F.format "Part {}" $ F.Only _partN
mapM_ toHtml _partContent
toHtmlRaw Part{..} =
details_ $ do
summary_ . toHtmlRaw . F.format "Part {}" $ F.Only _partN
mapM_ toHtml _partContent
instance ToNamedRecord (Part c) where
toNamedRecord p =
namedRecord [ "volume_n" .= (p ^. partVolume . headerN)
, "volume_title" .= (p ^. partVolume . headerTitle)
, "part" .= (p ^. partN)
]
instance DefaultOrdered (Part c) where
headerOrder _ = [ "volume_n"
, "volume_title"
, "part"
]
instance Buildable c => Buildable (Part c) where
build p = hr $ p ^. partContent
data Volume c -- ^ CD I
= Volume
{ _volumeN :: !Int
, _volumeTitle :: !Title
, _volumeContent :: ![Part c]
} deriving (Show, Eq, Data, Typeable, Generic, Functor)
$(makeLenses ''Volume)
instance NFData c => NFData (Volume c)
instance ToHtml c => ToHtml (Volume c) where
toHtml Volume{..} =
details_ $ do
summary_ . toHtml $ F.format "V {}. {}" (_volumeN, _volumeTitle)
mapM_ toHtml _volumeContent
toHtmlRaw Volume{..} =
details_ $ do
summary_ . toHtmlRaw $ F.format "V {}. {}" (_volumeN, _volumeTitle)
mapM_ toHtmlRaw _volumeContent
instance Eq c => Ord (Volume c) where
compare = comparing _volumeN
instance ToNamedRecord (Volume c) where
toNamedRecord v =
namedRecord [ "volume_n" .= (v ^. volumeN)
, "volume_title" .= getTitle v
]
where
getTitle v' = TL.toStrict
. F.format "CD {}"
. F.Only
$ v' ^? volumeN . roman
instance DefaultOrdered (Volume c) where
headerOrder _ = [ "volume_n"
, "volume_title"
]
instance Buildable c => Buildable (Volume c) where
build v = hr $ v ^. volumeContent
data Corpus c = Corpus { _corpus :: ![Volume c] }
deriving (Show, Eq, Data, Typeable, Generic, Functor)
$(makeLenses ''Corpus)
instance NFData c => NFData (Corpus c)
instance ToHtml c => ToHtml (Corpus c) where
toHtml = mapM_ toHtml . _corpus
toHtmlRaw = mapM_ toHtmlRaw . _corpus
|
erochest/barth-scrape
|
src/BarthPar/Scrape/Types/DOM.hs
|
apache-2.0
| 12,329 | 0 | 14 | 4,901 | 3,040 | 1,584 | 1,456 | -1 | -1 |
module MonteCarloPi where
import System.Random
import Data.IORef
-- define a data type to represent a point
type Point = (Double,Double)
-- define a data type to represent a square
-- the single Double argument is the dimension of the square
type Square = Double
-- the corner of a square is always at 0.0,0.0
-- define a data type to represent a circle
-- the single Double argument is the radius of the circle
type Circle = Double
-- the middle of a circle is always at radius,radius
-- function to define a circle that fits exactly within a square
-- I.e. a circle with a radius equal to half the dimension of the square
circleInSquare :: Square -> Circle
circleInSquare s = s/2.0
-- the area of a square is dimension^2
-- the area of a circle is pi*r^2
-- in a circle that fits in a sqaure, the radius is dimension/2.0, so the area is pi * (dimension/2.0)^2
-- = pi/4.0 * dimension^2
-- so pi = (area of circle * 4.0)/ area of square
-- randomly choose points in the square
-- pi is approximately 4 times (the number of these points that are also in the circle, divided by the total number of points)
-- function to return whether a point sits within a circle
isInCircle :: Point -> Circle -> Bool
isInCircle (x,y) r = (x-r)^2 + (y-r)^2 <= r^2
-- a montecarlo method for approximating pi
approxPi' :: (Int,Double) -> Double -> IO (Int,Double)
approxPi' (runs,pi) n = do x <- randomRIO (0,n)
y <- randomRIO (0,n)
if (isInCircle (x,y) (circleInSquare n))
then (return (runs+1,((pi*(fromIntegral runs))+1.0)/((fromIntegral runs)+1.0)))
else (return (runs+1,(pi*(fromIntegral runs))/((fromIntegral runs)+1.0)))
--repeats the montecarlo method indefinitely using a square of the given dimension
approxPiR :: Double -> IO ()
approxPiR square = do approxPiR' (0,0.0) square
approxPiR' :: (Int,Double) -> Double -> IO ()
approxPiR' (n,pi) d = do (n',pi') <- approxPi' (n,pi) d
putStrLn (show (4.0*pi'))
approxPiR' (n',pi') d
--repeats the montecarlo method the given number of times using a square of the given dimension
approxPi :: Double -> Int -> IO Double
approxPi square runs = do pi <- approxPi'' runs square (0,0.0)
return (4.0*pi)
approxPi'' :: Int -> Double -> (Int,Double) -> IO Double
approxPi'' 0 _ (_,pi) = return pi
approxPi'' runs d (n,pi) = do (n',pi') <- approxPi' (n,pi) d
if (runs `mod` 100000 == 0) then putStrLn ((show runs)++" : "++(show (4.0*pi')))
else return ()
approxPi'' (runs-1) d (n',pi')
---testing functions
type Strings = [String]
squareNum :: Int
squareNum = 28
circ :: (Int,Int) -> Char
circ (x,y) = if (isInCircle (fromIntegral x,fromIntegral y) (circleInSquare (fromIntegral squareNum))) then '#' else '*'
circle' :: String
circle' = [circ (x,y) | x <- [0..squareNum], y <- [0..squareNum]]
circle'' :: [(Int,Int)]
circle'' = [(x,y) | x <- [0..squareNum], y <- [0..squareNum]]
partition :: [a] -> [[a]]
partition [] = []
partition xs = ((take (squareNum+1) xs):(partition (drop (squareNum+1) xs)))
circle :: Strings
circle = partition circle'
draw :: Strings -> String
draw [] = []
draw (x:xs) = x ++ "\n" ++ draw xs
testCircle :: IO ()
testCircle = do putStrLn (draw circle)
|
alexandersgreen/alex-haskell
|
MonteCarloPi/MonteCarloPi.hs
|
apache-2.0
| 3,493 | 0 | 17 | 910 | 1,073 | 591 | 482 | 50 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Backends.Html
-- Copyright : (c) Simon Marlow 2003-2006,
-- David Waern 2006-2009,
-- Mark Lentczner 2010,
-- Mateusz Kowalczyk 2013
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
{-# LANGUAGE CPP #-}
module Haddock.Backends.Xhtml (
ppHtml, copyHtmlBits,
ppHtmlIndex, ppHtmlContents,
) where
import Prelude hiding (div)
import Haddock.Backends.Xhtml.Decl
import Haddock.Backends.Xhtml.DocMarkup
import Haddock.Backends.Xhtml.Layout
import Haddock.Backends.Xhtml.Names
import Haddock.Backends.Xhtml.Themes
import Haddock.Backends.Xhtml.Types
import Haddock.Backends.Xhtml.Utils
import Haddock.ModuleTree
import Haddock.Types
import Haddock.Version
import Haddock.Utils
import Text.XHtml hiding ( name, title, p, quote )
import qualified Text.XHtml as H
import Haddock.GhcUtils
import Control.Monad ( when, unless )
import Data.Char ( toUpper )
import Data.List ( sortBy, groupBy, intercalate, isPrefixOf )
import Data.Maybe
import System.FilePath hiding ( (</>) )
import System.Directory
import Data.Map ( Map )
import qualified Data.Map as Map hiding ( Map )
import qualified Data.Set as Set hiding ( Set )
import Data.Function
import Data.Ord ( comparing )
import DynFlags (Language(..))
import GHC hiding ( NoLink, moduleInfo )
import Name
import Module
--------------------------------------------------------------------------------
-- * Generating HTML documentation
--------------------------------------------------------------------------------
ppHtml :: DynFlags
-> String -- ^ Title
-> Maybe String -- ^ Package
-> [Interface]
-> FilePath -- ^ Destination directory
-> Maybe (MDoc GHC.RdrName) -- ^ Prologue text, maybe
-> Themes -- ^ Themes
-> SourceURLs -- ^ The source URL (--source)
-> WikiURLs -- ^ The wiki URL (--wiki)
-> Maybe String -- ^ The contents URL (--use-contents)
-> Maybe String -- ^ The index URL (--use-index)
-> Bool -- ^ Whether to use unicode in output (--use-unicode)
-> QualOption -- ^ How to qualify names
-> Bool -- ^ Output pretty html (newlines and indenting)
-> IO ()
ppHtml dflags doctitle maybe_package ifaces odir prologue
themes maybe_source_url maybe_wiki_url
maybe_contents_url maybe_index_url unicode
qual debug = do
let
visible_ifaces = filter visible ifaces
visible i = OptHide `notElem` ifaceOptions i
when (isNothing maybe_contents_url) $
ppHtmlContents dflags odir doctitle maybe_package
themes maybe_index_url maybe_source_url maybe_wiki_url
(map toInstalledIface visible_ifaces)
False -- we don't want to display the packages in a single-package contents
prologue debug (makeContentsQual qual)
when (isNothing maybe_index_url) $
ppHtmlIndex odir doctitle maybe_package
themes maybe_contents_url maybe_source_url maybe_wiki_url
(map toInstalledIface visible_ifaces) debug
mapM_ (ppHtmlModule odir doctitle themes
maybe_source_url maybe_wiki_url
maybe_contents_url maybe_index_url unicode qual debug) visible_ifaces
copyHtmlBits :: FilePath -> FilePath -> Themes -> IO ()
copyHtmlBits odir libdir themes = do
let
libhtmldir = joinPath [libdir, "html"]
copyCssFile f = copyFile f (combine odir (takeFileName f))
copyLibFile f = copyFile (joinPath [libhtmldir, f]) (joinPath [odir, f])
mapM_ copyCssFile (cssFiles themes)
mapM_ copyLibFile ["jquery.min.js", "js.cookie.js", "haddock.js"]
headHtml :: String -> Maybe String -> Themes -> Html
headHtml docTitle miniPage themes =
header << [
meta ! [httpequiv "Content-Type", content "text/html; charset=UTF-8"],
meta ! [H.name "viewport", content "width=device-width, initial-scale=1.0"],
thetitle << docTitle,
styleSheet themes,
script ! [src "jquery.min.js", thetype "text/javascript"] << noHtml,
script ! [src "js.cookie.js", thetype "text/javascript"] << noHtml,
script ! [src "haddock.js", thetype "text/javascript"] << noHtml,
script ! [thetype "text/javascript"] << primHtml (
"//<![CDATA[\n" ++
"window.onload = function() { haddock._initPage(); };\n" ++
"//]]>\n")]
where
setSynopsis = maybe "" (\p -> "setSynopsis(\"" ++ p ++ "\");") miniPage
srcButton :: SourceURLs -> Maybe Interface -> Maybe Html
srcButton (Just src_base_url, _, _, _) Nothing =
Just (anchor ! [href src_base_url] << "Source")
srcButton (_, Just src_module_url, _, _) (Just iface) =
let url = spliceURL (Just $ ifaceOrigFilename iface)
(Just $ ifaceMod iface) Nothing Nothing src_module_url
in Just (anchor ! [href url] << "Source")
srcButton _ _ =
Nothing
wikiButton :: WikiURLs -> Maybe Module -> Maybe Html
wikiButton (Just wiki_base_url, _, _) Nothing =
Just (anchor ! [href wiki_base_url] << "User Comments")
wikiButton (_, Just wiki_module_url, _) (Just mdl) =
let url = spliceURL Nothing (Just mdl) Nothing Nothing wiki_module_url
in Just (anchor ! [href url] << "User Comments")
wikiButton _ _ =
Nothing
contentsButton :: Maybe String -> Maybe Html
contentsButton maybe_contents_url
= Just (anchor ! [href url] << "Contents")
where url = fromMaybe contentsHtmlFile maybe_contents_url
indexButton :: Maybe String -> Maybe Html
indexButton maybe_index_url
= Just (anchor ! [href url] << "Index")
where url = fromMaybe indexHtmlFile maybe_index_url
bodyHtml :: String -> Maybe Interface
-> SourceURLs -> WikiURLs
-> Maybe String -> Maybe String
-> [String] -> Html -> Html
bodyHtml doctitle iface
maybe_source_url maybe_wiki_url
maybe_contents_url maybe_index_url
contentClasses pageContent =
body << [
divPackageHeader << [
unordList (catMaybes [
srcButton maybe_source_url iface,
wikiButton maybe_wiki_url (ifaceMod <$> iface),
contentsButton maybe_contents_url,
indexButton maybe_index_url])
! [theclass "links", identifier "page-menu"],
nonEmptySectionName << doctitle
],
thediv ! ([identifier "content", theclass (unwords contentClasses)])
<< pageContent,
divFooter << paragraph << (
"Produced by " +++
(anchor ! [href projectUrl] << toHtml projectName) +++
(" version " ++ projectVersion)
)
]
moduleInfo :: Interface -> Html
moduleInfo iface =
let
info = ifaceInfo iface
doOneEntry :: (String, HaddockModInfo GHC.Name -> Maybe String) -> Maybe HtmlTable
doOneEntry (fieldName, field) =
field info >>= \a -> return (th << fieldName <-> td << a)
entries :: [HtmlTable]
entries = mapMaybe doOneEntry [
("Copyright",hmi_copyright),
("License",hmi_license),
("Maintainer",hmi_maintainer),
("Stability",hmi_stability),
("Portability",hmi_portability),
("Safe Haskell",hmi_safety),
("Language", lg)
] ++ extsForm
where
lg inf = case hmi_language inf of
Nothing -> Nothing
Just Haskell98 -> Just "Haskell98"
Just Haskell2010 -> Just "Haskell2010"
extsForm
| OptShowExtensions `elem` ifaceOptions iface =
let fs = map (dropOpt . show) (hmi_extensions info)
in case map stringToHtml fs of
[] -> []
[x] -> extField x -- don't use a list for a single extension
xs -> extField $ unordList xs ! [theclass "extension-list"]
| otherwise = []
where
extField x = return $ th << "Extensions" <-> td << x
dropOpt x = if "Opt_" `isPrefixOf` x then drop 4 x else x
in
case entries of
[] -> noHtml
_ -> table ! [theclass "info"] << aboves entries
--------------------------------------------------------------------------------
-- * Generate the module contents
--------------------------------------------------------------------------------
ppHtmlContents
:: DynFlags
-> FilePath
-> String
-> Maybe String
-> Themes
-> Maybe String
-> SourceURLs
-> WikiURLs
-> [InstalledInterface] -> Bool -> Maybe (MDoc GHC.RdrName)
-> Bool
-> Qualification -- ^ How to qualify names
-> IO ()
ppHtmlContents dflags odir doctitle _maybe_package
themes maybe_index_url
maybe_source_url maybe_wiki_url ifaces showPkgs prologue debug qual = do
let tree = mkModuleTree dflags showPkgs
[(instMod iface, toInstalledDescription iface) | iface <- ifaces]
html =
headHtml doctitle Nothing themes +++
bodyHtml doctitle Nothing
maybe_source_url maybe_wiki_url
Nothing maybe_index_url [] << [
ppPrologue qual doctitle prologue,
ppModuleTree qual tree
]
createDirectoryIfMissing True odir
writeFile (joinPath [odir, contentsHtmlFile]) (renderToString debug html)
-- XXX: think of a better place for this?
ppHtmlContentsFrame odir doctitle themes ifaces debug
ppPrologue :: Qualification -> String -> Maybe (MDoc GHC.RdrName) -> Html
ppPrologue _ _ Nothing = noHtml
ppPrologue qual title (Just doc) =
divDescription << (h1 << title +++ docElement thediv (rdrDocToHtml qual doc))
ppModuleTree :: Qualification -> [ModuleTree] -> Html
ppModuleTree qual ts =
divModuleList << (sectionName << "Modules" +++ mkNodeList qual [] "n" ts)
mkNodeList :: Qualification -> [String] -> String -> [ModuleTree] -> Html
mkNodeList qual ss p ts = case ts of
[] -> noHtml
_ -> unordList (zipWith (mkNode qual ss) ps ts)
where
ps = [ p ++ '.' : show i | i <- [(1::Int)..]]
mkNode :: Qualification -> [String] -> String -> ModuleTree -> Html
mkNode qual ss p (Node s leaf pkg srcPkg short ts) =
htmlModule <+> shortDescr +++ htmlPkg +++ subtree
where
modAttrs = case (ts, leaf) of
(_:_, False) -> collapseControl p True "module"
(_, _ ) -> [theclass "module"]
cBtn = case (ts, leaf) of
(_:_, True) -> thespan ! collapseControl p True "" << noHtml
(_, _ ) -> noHtml
-- We only need an explicit collapser button when the module name
-- is also a leaf, and so is a link to a module page. Indeed, the
-- spaceHtml is a minor hack and does upset the layout a fraction.
htmlModule = thespan ! modAttrs << (cBtn +++
if leaf
then ppModule (mkModule (stringToPackageKey (fromMaybe "" pkg))
(mkModuleName mdl))
else toHtml s
)
mdl = intercalate "." (reverse (s:ss))
shortDescr =
case short of
Just s -> (thespan ! [theclass "short-descr"]) (origDocToHtml qual s)
Nothing -> noHtml
htmlPkg = maybe noHtml (thespan ! [theclass "package"] <<) srcPkg
subtree = mkNodeList qual (s:ss) p ts ! collapseSection p True ""
-- | Turn a module tree into a flat list of full module names. E.g.,
-- @
-- A
-- +-B
-- +-C
-- @
-- becomes
-- @["A", "A.B", "A.B.C"]@
flatModuleTree :: [InstalledInterface] -> [Html]
flatModuleTree ifaces =
map (uncurry ppModule' . head)
. groupBy ((==) `on` fst)
. sortBy (comparing fst)
$ mods
where
mods = [ (moduleString mdl, mdl) | mdl <- map instMod ifaces ]
ppModule' txt mdl =
anchor ! [href (moduleHtmlFile mdl), target mainFrameName]
<< toHtml txt
ppHtmlContentsFrame :: FilePath -> String -> Themes
-> [InstalledInterface] -> Bool -> IO ()
ppHtmlContentsFrame odir doctitle themes ifaces debug = do
let mods = flatModuleTree ifaces
html =
headHtml doctitle Nothing themes +++
miniBody << divModuleList <<
(sectionName << "Modules" +++
ulist << [ li ! [theclass "module"] << m | m <- mods ])
createDirectoryIfMissing True odir
writeFile (joinPath [odir, frameIndexHtmlFile]) (renderToString debug html)
--------------------------------------------------------------------------------
-- * Generate the index
--------------------------------------------------------------------------------
ppHtmlIndex :: FilePath
-> String
-> Maybe String
-> Themes
-> Maybe String
-> SourceURLs
-> WikiURLs
-> [InstalledInterface]
-> Bool
-> IO ()
ppHtmlIndex odir doctitle _maybe_package themes
maybe_contents_url maybe_source_url maybe_wiki_url ifaces debug = do
let html = indexPage split_indices Nothing
(if split_indices then [] else index)
createDirectoryIfMissing True odir
when split_indices $ do
mapM_ (do_sub_index index) initialChars
-- Let's add a single large index as well for those who don't know exactly what they're looking for:
let mergedhtml = indexPage False Nothing index
writeFile (joinPath [odir, subIndexHtmlFile merged_name]) (renderToString debug mergedhtml)
writeFile (joinPath [odir, indexHtmlFile]) (renderToString debug html)
where
indexPage showLetters ch items =
headHtml (doctitle ++ " (" ++ indexName ch ++ ")") Nothing themes +++
bodyHtml doctitle Nothing
maybe_source_url maybe_wiki_url
maybe_contents_url Nothing [] << [
if showLetters then indexInitialLetterLinks else noHtml,
if null items
then divIndex << [H.p ! [theclass "no-items"] $ toHtml "Select a letter."]
else divIndex << [sectionName << indexName ch, buildIndex items]
]
indexName ch = "Index" ++ maybe "" (\c -> " - " ++ [c]) ch
merged_name = "All"
buildIndex items = table << aboves (map indexElt items)
-- an arbitrary heuristic:
-- too large, and a single-page will be slow to load
-- too small, and we'll have lots of letter-indexes with only one
-- or two members in them, which seems inefficient or
-- unnecessarily hard to use.
split_indices = length index > 150
indexInitialLetterLinks =
divAlphabet <<
unordList (map (\str -> anchor ! [href (subIndexHtmlFile str)] << str) $
[ [c] | c <- initialChars
, any ((==c) . toUpper . head . fst) index ] ++
[merged_name])
-- todo: what about names/operators that start with Unicode
-- characters?
-- Exports beginning with '_' can be listed near the end,
-- presumably they're not as important... but would be listed
-- with non-split index!
initialChars = [ 'A'..'Z' ] ++ ":!#$%&*+./<=>?@\\^|-~" ++ "_"
do_sub_index this_ix c
= unless (null index_part) $
writeFile (joinPath [odir, subIndexHtmlFile [c]]) (renderToString debug html)
where
html = indexPage True (Just c) index_part
index_part = [(n,stuff) | (n,stuff) <- this_ix, toUpper (head n) == c]
index :: [(String, Map GHC.Name [(Module,Bool)])]
index = sortBy cmp (Map.toAscList full_index)
where cmp (n1,_) (n2,_) = comparing (map toUpper) n1 n2
-- for each name (a plain string), we have a number of original HsNames that
-- it can refer to, and for each of those we have a list of modules
-- that export that entity. Each of the modules exports the entity
-- in a visible or invisible way (hence the Bool).
full_index :: Map String (Map GHC.Name [(Module,Bool)])
full_index = Map.fromListWith (flip (Map.unionWith (++)))
(concatMap getIfaceIndex ifaces)
getIfaceIndex iface =
[ (getOccString name
, Map.fromList [(name, [(mdl, name `Set.member` visible)])])
| name <- instExports iface ]
where
mdl = instMod iface
visible = Set.fromList (instVisibleExports iface)
indexElt :: (String, Map GHC.Name [(Module,Bool)]) -> HtmlTable
indexElt (str, entities) =
case Map.toAscList entities of
[(nm,entries)] ->
td ! [ theclass "src" ] << toHtml str <->
indexLinks nm entries
many_entities ->
td ! [ theclass "src" ] << toHtml str <-> td << spaceHtml </>
aboves (zipWith (curry doAnnotatedEntity) [1..] many_entities)
doAnnotatedEntity :: (Integer, (Name, [(Module, Bool)])) -> HtmlTable
doAnnotatedEntity (j,(nm,entries))
= td ! [ theclass "alt" ] <<
toHtml (show j) <+> parens (ppAnnot (nameOccName nm)) <->
indexLinks nm entries
ppAnnot n | not (isValOcc n) = toHtml "Type/Class"
| isDataOcc n = toHtml "Data Constructor"
| otherwise = toHtml "Function"
indexLinks nm entries =
td ! [ theclass "module" ] <<
hsep (punctuate comma
[ if visible then
linkId mdl (Just nm) << toHtml (moduleString mdl)
else
toHtml (moduleString mdl)
| (mdl, visible) <- entries ])
--------------------------------------------------------------------------------
-- * Generate the HTML page for a module
--------------------------------------------------------------------------------
ppHtmlModule
:: FilePath -> String -> Themes
-> SourceURLs -> WikiURLs
-> Maybe String -> Maybe String -> Bool -> QualOption
-> Bool -> Interface -> IO ()
ppHtmlModule odir doctitle themes
maybe_source_url maybe_wiki_url
maybe_contents_url maybe_index_url unicode qual debug iface = do
let
mdl = ifaceMod iface
aliases = ifaceModuleAliases iface
mdl_str = moduleString mdl
real_qual = makeModuleQual qual aliases mdl
exports = numberSectionHeadings (ifaceRnExportItems iface)
html =
headHtml mdl_str (Just $ "mini_" ++ moduleHtmlFile mdl) themes +++
bodyHtml doctitle (Just iface)
maybe_source_url maybe_wiki_url
maybe_contents_url maybe_index_url ["has-module-prologue"] << [
h1 ! [theclass "module-name"] $ toHtml mdl_str,
thediv ! [identifier "module-prologue"] << [
divModuleInfo (sectionName << "Information" +++ moduleInfo iface),
ppModuleContents real_qual exports],
ifaceToHtml maybe_source_url maybe_wiki_url iface unicode real_qual
]
createDirectoryIfMissing True odir
writeFile (joinPath [odir, moduleHtmlFile mdl]) (renderToString debug html)
ppHtmlModuleMiniSynopsis odir doctitle themes iface unicode real_qual debug
ppHtmlModuleMiniSynopsis :: FilePath -> String -> Themes
-> Interface -> Bool -> Qualification -> Bool -> IO ()
ppHtmlModuleMiniSynopsis odir _doctitle themes iface unicode qual debug = do
let mdl = ifaceMod iface
html =
headHtml (moduleString mdl) Nothing themes +++
miniBody <<
(divModuleHeader << sectionName << moduleString mdl +++
miniSynopsis mdl iface unicode qual)
createDirectoryIfMissing True odir
writeFile (joinPath [odir, "mini_" ++ moduleHtmlFile mdl]) (renderToString debug html)
--------------------------------------------------------------------------------
ifaceToHtml :: SourceURLs -> WikiURLs -> Interface -> Bool -> Qualification -> Html
ifaceToHtml maybe_source_url maybe_wiki_url iface unicode qual
= description +++
synopsis +++
divInterface (maybe_doc_hdr +++ bdy)
where
exports = numberSectionHeadings (ifaceRnExportItems iface)
-- todo: if something has only sub-docs, or fn-args-docs, should
-- it be measured here and thus prevent omitting the synopsis?
has_doc ExportDecl { expItemMbDoc = (Documentation mDoc mWarning, _) } = isJust mDoc || isJust mWarning
has_doc (ExportNoDecl _ _) = False
has_doc (ExportModule _) = False
has_doc _ = True
no_doc_at_all = not (any has_doc exports)
description | isNoHtml doc = doc
| otherwise = divDescription $ sectionName << "Description" +++ doc
where doc = docSection Nothing qual (ifaceRnDoc iface)
-- omit the synopsis if there are no documentation annotations at all
synopsis
| no_doc_at_all = noHtml
| otherwise
= divSynposis $
paragraph ! collapseControl "syn" False "caption" << "Synopsis" +++
shortDeclList (
mapMaybe (processExport True linksInfo unicode qual) exports
) ! (collapseSection "syn" False "" ++ collapseToggle "syn")
-- if the documentation doesn't begin with a section header, then
-- add one ("Documentation").
maybe_doc_hdr
= case exports of
[] -> noHtml
ExportGroup {} : _ -> noHtml
_ -> h1 << "Documentation"
bdy =
foldr (+++) noHtml $
mapMaybe (processExport False linksInfo unicode qual) exports
linksInfo = (maybe_source_url, maybe_wiki_url)
--------------------------------------------------------------------------------
miniSynopsis :: Module -> Interface -> Bool -> Qualification -> Html
miniSynopsis mdl iface unicode qual =
divInterface << concatMap (processForMiniSynopsis mdl unicode qual) exports
where
exports = numberSectionHeadings (ifaceRnExportItems iface)
processForMiniSynopsis :: Module -> Bool -> Qualification -> ExportItem DocName
-> [Html]
processForMiniSynopsis mdl unicode qual ExportDecl { expItemDecl = L _loc decl0 } =
((divTopDecl <<).(declElem <<)) <$> case decl0 of
TyClD d -> let b = ppTyClBinderWithVarsMini mdl d in case d of
(FamDecl decl) -> [ppTyFamHeader True False decl unicode qual]
(DataDecl{}) -> [keyword "data" <+> b]
(SynDecl{}) -> [keyword "type" <+> b]
(ClassDecl {}) -> [keyword "class" <+> b]
SigD (TypeSig lnames (L _ _) _) ->
map (ppNameMini Prefix mdl . nameOccName . getName . unLoc) lnames
_ -> []
processForMiniSynopsis _ _ qual (ExportGroup lvl _id txt) =
[groupTag lvl << docToHtml Nothing qual (mkMeta txt)]
processForMiniSynopsis _ _ _ _ = []
ppNameMini :: Notation -> Module -> OccName -> Html
ppNameMini notation mdl nm =
anchor ! [ href (moduleNameUrl mdl nm)
, target mainFrameName ]
<< ppBinder' notation nm
ppTyClBinderWithVarsMini :: Module -> TyClDecl DocName -> Html
ppTyClBinderWithVarsMini mdl decl =
let n = tcdName decl
ns = tyvarNames $ tcdTyVars decl -- it's safe to use tcdTyVars, see code above
in ppTypeApp n [] ns (\is_infix -> ppNameMini is_infix mdl . nameOccName . getName) ppTyName
ppModuleContents :: Qualification -> [ExportItem DocName] -> Html
ppModuleContents qual exports
| null sections = noHtml
| otherwise = contentsDiv
where
contentsDiv = divTableOfContents << (
sectionName << "Contents" +++
unordList sections)
(sections, _leftovers{-should be []-}) = process 0 exports
process :: Int -> [ExportItem DocName] -> ([Html],[ExportItem DocName])
process _ [] = ([], [])
process n items@(ExportGroup lev id0 doc : rest)
| lev <= n = ( [], items )
| otherwise = ( html:secs, rest2 )
where
html = linkedAnchor (groupId id0)
<< docToHtmlNoAnchors (Just id0) qual (mkMeta doc) +++ mk_subsections ssecs
(ssecs, rest1) = process lev rest
(secs, rest2) = process n rest1
process n (_ : rest) = process n rest
mk_subsections [] = noHtml
mk_subsections ss = unordList ss
-- we need to assign a unique id to each section heading so we can hyperlink
-- them from the contents:
numberSectionHeadings :: [ExportItem DocName] -> [ExportItem DocName]
numberSectionHeadings = go 1
where go :: Int -> [ExportItem DocName] -> [ExportItem DocName]
go _ [] = []
go n (ExportGroup lev _ doc : es)
= ExportGroup lev (show n) doc : go (n+1) es
go n (other:es)
= other : go n es
processExport :: Bool -> LinksInfo -> Bool -> Qualification
-> ExportItem DocName -> Maybe Html
processExport _ _ _ _ ExportDecl { expItemDecl = L _ (InstD _) } = Nothing -- Hide empty instances
processExport summary _ _ qual (ExportGroup lev id0 doc)
= nothingIf summary $ groupHeading lev id0 << docToHtml (Just id0) qual (mkMeta doc)
processExport summary links unicode qual (ExportDecl decl doc subdocs insts fixities splice)
= processDecl summary $ ppDecl summary links decl doc insts fixities subdocs splice unicode qual
processExport summary _ _ qual (ExportNoDecl y [])
= processDeclOneLiner summary $ ppDocName qual Prefix True y
processExport summary _ _ qual (ExportNoDecl y subs)
= processDeclOneLiner summary $
ppDocName qual Prefix True y
+++ parenList (map (ppDocName qual Prefix True) subs)
processExport summary _ _ qual (ExportDoc doc)
= nothingIf summary $ docSection_ Nothing qual doc
processExport summary _ _ _ (ExportModule mdl)
= processDeclOneLiner summary $ toHtml "module" <+> ppModule mdl
nothingIf :: Bool -> a -> Maybe a
nothingIf True _ = Nothing
nothingIf False a = Just a
processDecl :: Bool -> Html -> Maybe Html
processDecl True = Just
processDecl False = Just . divTopDecl
processDeclOneLiner :: Bool -> Html -> Maybe Html
processDeclOneLiner True = Just
processDeclOneLiner False = Just . divTopDecl . declElem
groupHeading :: Int -> String -> Html -> Html
groupHeading lev id0 = groupTag lev ! [identifier (groupId id0)]
groupTag :: Int -> Html -> Html
groupTag lev
| lev == 1 = h1
| lev == 2 = h2
| lev == 3 = h3
| otherwise = h4
|
lamefun/haddock
|
haddock-api/src/Haddock/Backends/Xhtml.hs
|
bsd-2-clause
| 25,987 | 1 | 20 | 6,650 | 7,113 | 3,671 | 3,442 | 497 | 7 |
{-# LANGUAGE TemplateHaskell, NoMonomorphismRestriction, FlexibleContexts #-}
{-| The WConfd functions for direct configuration manipulation
This module contains the client functions exported by WConfD for
specific configuration manipulation.
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.WConfd.ConfigModifications where
import Control.Lens (_2)
import Control.Lens.Getter ((^.))
import Control.Lens.Setter ((.~), (%~))
import qualified Data.ByteString.UTF8 as UTF8
import Control.Lens.Traversal (mapMOf)
import Control.Monad (unless, when, forM_, foldM, liftM2)
import Control.Monad.Error (throwError, MonadError)
import Control.Monad.Fail (MonadFail)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.State (StateT, get, put, modify,
runStateT, execStateT)
import Data.Foldable (fold)
import Data.List (elemIndex)
import Data.Maybe (isJust, maybeToList, fromMaybe, fromJust)
import Language.Haskell.TH (Name)
import System.Time (getClockTime, ClockTime)
import Text.Printf (printf)
import qualified Data.Map as M
import qualified Data.Set as S
import Ganeti.BasicTypes (GenericResult(..), genericResult, toError)
import Ganeti.Constants (lastDrbdPort)
import Ganeti.Errors (GanetiException(..))
import Ganeti.JSON (Container, GenericContainer(..), alterContainerL
, lookupContainer, MaybeForJSON(..), TimeAsDoubleJSON(..))
import Ganeti.Locking.Locks (ClientId, ciIdentifier)
import Ganeti.Logging.Lifted (logDebug, logInfo)
import Ganeti.Objects
import Ganeti.Objects.Lens
import Ganeti.Types (AdminState, AdminStateSource)
import Ganeti.WConfd.ConfigState (ConfigState, csConfigData, csConfigDataL)
import Ganeti.WConfd.Monad (WConfdMonad, modifyConfigWithLock
, modifyConfigAndReturnWithLock)
import qualified Ganeti.WConfd.TempRes as T
type DiskUUID = String
type InstanceUUID = String
type NodeUUID = String
-- * accessor functions
getInstanceByUUID :: ConfigState
-> InstanceUUID
-> GenericResult GanetiException Instance
getInstanceByUUID cs uuid = lookupContainer
(Bad . ConfigurationError $
printf "Could not find instance with UUID %s" uuid)
(UTF8.fromString uuid)
(configInstances . csConfigData $ cs)
-- * getters
-- | Gets all logical volumes in the cluster
getAllLVs :: ConfigState -> S.Set String
getAllLVs = S.fromList . concatMap getLVsOfDisk . M.elems
. fromContainer . configDisks . csConfigData
where convert (LogicalVolume lvG lvV) = lvG ++ "/" ++ lvV
getDiskLV :: Disk -> Maybe String
getDiskLV disk = case diskLogicalId disk of
Just (LIDPlain lv) -> Just (convert lv)
_ -> Nothing
getLVsOfDisk :: Disk -> [String]
getLVsOfDisk disk = maybeToList (getDiskLV disk)
++ concatMap getLVsOfDisk (diskChildren disk)
-- | Gets the ids of nodes, instances, node groups,
-- networks, disks, nics, and the cluster itself.
getAllIDs :: ConfigState -> S.Set String
getAllIDs cs =
let lvs = getAllLVs cs
keysFromC :: GenericContainer a b -> [a]
keysFromC = M.keys . fromContainer
valuesFromC :: GenericContainer a b -> [b]
valuesFromC = M.elems . fromContainer
instKeys = keysFromC . configInstances . csConfigData $ cs
nodeKeys = keysFromC . configNodes . csConfigData $ cs
instValues = map uuidOf . valuesFromC
. configInstances . csConfigData $ cs
nodeValues = map uuidOf . valuesFromC . configNodes . csConfigData $ cs
nodeGroupValues = map uuidOf . valuesFromC
. configNodegroups . csConfigData $ cs
networkValues = map uuidOf . valuesFromC
. configNetworks . csConfigData $ cs
disksValues = map uuidOf . valuesFromC . configDisks . csConfigData $ cs
nics = map nicUuid . concatMap instNics
. valuesFromC . configInstances . csConfigData $ cs
cluster = uuidOf . configCluster . csConfigData $ cs
in S.union lvs . S.fromList $ map UTF8.toString instKeys
++ map UTF8.toString nodeKeys
++ instValues
++ nodeValues
++ nodeGroupValues
++ networkValues
++ disksValues
++ map UTF8.toString nics ++ [cluster]
getAllMACs :: ConfigState -> S.Set String
getAllMACs = S.fromList . map nicMac . concatMap instNics . M.elems
. fromContainer . configInstances . csConfigData
-- | Checks if the two objects are equal,
-- excluding timestamps. The serial number of
-- current must be one greater than that of target.
--
-- If this is true, it implies that the update RPC
-- updated the config, but did not successfully return.
isIdentical :: (Eq a, SerialNoObjectL a, TimeStampObjectL a)
=> ClockTime
-> a
-> a
-> Bool
isIdentical now target current = (mTimeL .~ now $ current) ==
((serialL %~ (+1)) . (mTimeL .~ now) $ target)
-- | Checks if the two objects given have the same serial number
checkSerial :: SerialNoObject a => a -> a -> GenericResult GanetiException ()
checkSerial target current = if serialOf target == serialOf current
then Ok ()
else Bad . ConfigurationError $ printf
"Configuration object updated since it has been read: %d != %d"
(serialOf current) (serialOf target)
-- | Updates an object present in a container.
-- The presence of the object in the container
-- is determined by the uuid of the object.
--
-- A check that serial number of the
-- object is consistent with the serial number
-- of the object in the container is performed.
--
-- If the check passes, the object's serial number
-- is incremented, and modification time is updated,
-- and then is inserted into the container.
replaceIn :: (UuidObject a, TimeStampObjectL a, SerialNoObjectL a)
=> ClockTime
-> a
-> Container a
-> GenericResult GanetiException (Container a)
replaceIn now target = alterContainerL (UTF8.fromString (uuidOf target)) extract
where extract Nothing = Bad $ ConfigurationError
"Configuration object unknown"
extract (Just current) = do
checkSerial target current
return . Just . (serialL %~ (+1)) . (mTimeL .~ now) $ target
-- | Utility fuction that combines the two
-- possible actions that could be taken when
-- given a target.
--
-- If the target is identical to the current
-- value, we return the modification time of
-- the current value, and not change the config.
--
-- If not, we update the config.
updateConfigIfNecessary :: (Monad m, MonadError GanetiException m, Eq a,
UuidObject a, SerialNoObjectL a, TimeStampObjectL a)
=> ClockTime
-> a
-> (ConfigState -> Container a)
-> (ConfigState
-> m ((Int, ClockTime), ConfigState))
-> ConfigState
-> m ((Int, ClockTime), ConfigState)
updateConfigIfNecessary now target getContainer f cs = do
let container = getContainer cs
current <- lookupContainer (toError . Bad . ConfigurationError $
"Configuraton object unknown")
(UTF8.fromString (uuidOf target))
container
if isIdentical now target current
then return ((serialOf current, mTimeOf current), cs)
else f cs
-- * UUID config checks
-- | Checks if the config has the given UUID
checkUUIDpresent :: UuidObject a
=> ConfigState
-> a
-> Bool
checkUUIDpresent cs a = uuidOf a `S.member` getAllIDs cs
-- | Checks if the given UUID is new (i.e., no in the config)
checkUniqueUUID :: UuidObject a
=> ConfigState
-> a
-> Bool
checkUniqueUUID cs a = not $ checkUUIDpresent cs a
-- * RPC checks
-- | Verifications done before adding an instance.
-- Currently confirms that the instance's macs are not
-- in use, and that the instance's UUID being
-- present (or not present) in the config based on
-- weather the instance is being replaced (or not).
--
-- TODO: add more verifications to this call;
-- the client should have a lock on the name of the instance.
addInstanceChecks :: Instance
-> Bool
-> ConfigState
-> GenericResult GanetiException ()
addInstanceChecks inst replace cs = do
let macsInUse = S.fromList (map nicMac (instNics inst))
`S.intersection` getAllMACs cs
unless (S.null macsInUse) . Bad . ConfigurationError $ printf
"Cannot add instance %s; MAC addresses %s already in use"
(show $ instName inst) (show macsInUse)
if replace
then do
let check = checkUUIDpresent cs inst
unless check . Bad . ConfigurationError $ printf
"Cannot add %s: UUID %s already in use"
(show $ instName inst) (UTF8.toString (instUuid inst))
else do
let check = checkUniqueUUID cs inst
unless check . Bad . ConfigurationError $ printf
"Cannot replace %s: UUID %s not present"
(show $ instName inst) (UTF8.toString (instUuid inst))
addDiskChecks :: Disk
-> Bool
-> ConfigState
-> GenericResult GanetiException ()
addDiskChecks disk replace cs =
if replace
then
unless (checkUUIDpresent cs disk) . Bad . ConfigurationError $ printf
"Cannot add %s: UUID %s already in use"
(show $ diskName disk) (UTF8.toString (diskUuid disk))
else
unless (checkUniqueUUID cs disk) . Bad . ConfigurationError $ printf
"Cannot replace %s: UUID %s not present"
(show $ diskName disk) (UTF8.toString (diskUuid disk))
attachInstanceDiskChecks :: InstanceUUID
-> DiskUUID
-> MaybeForJSON Int
-> ConfigState
-> GenericResult GanetiException ()
attachInstanceDiskChecks uuidInst uuidDisk idx' cs = do
let diskPresent = elem uuidDisk . map (UTF8.toString . diskUuid) . M.elems
. fromContainer . configDisks . csConfigData $ cs
unless diskPresent . Bad . ConfigurationError $ printf
"Disk %s doesn't exist" uuidDisk
inst <- getInstanceByUUID cs uuidInst
let numDisks = length $ instDisks inst
idx = fromMaybe numDisks (unMaybeForJSON idx')
when (idx < 0) . Bad . GenericError $
"Not accepting negative indices"
when (idx > numDisks) . Bad . GenericError $ printf
"Got disk index %d, but there are only %d" idx numDisks
let insts = M.elems . fromContainer . configInstances . csConfigData $ cs
forM_ insts (\inst' -> when (uuidDisk `elem` instDisks inst') . Bad
. ReservationError $ printf "Disk %s already attached to instance %s"
uuidDisk (show . fromMaybe "" $ instName inst'))
-- * Pure config modifications functions
attachInstanceDisk' :: InstanceUUID
-> DiskUUID
-> MaybeForJSON Int
-> ClockTime
-> ConfigState
-> ConfigState
attachInstanceDisk' iUuid dUuid idx' ct cs =
let inst = genericResult (error "impossible") id (getInstanceByUUID cs iUuid)
numDisks = length $ instDisks inst
idx = fromMaybe numDisks (unMaybeForJSON idx')
insert = instDisksL %~ (\ds -> take idx ds ++ [dUuid] ++ drop idx ds)
incr = instSerialL %~ (+ 1)
time = instMtimeL .~ ct
inst' = time . incr . insert $ inst
disks = updateIvNames idx inst' (configDisks . csConfigData $ cs)
ri = csConfigDataL . configInstancesL
. alterContainerL (UTF8.fromString iUuid) .~ Just inst'
rds = csConfigDataL . configDisksL .~ disks
in rds . ri $ cs
where updateIvNames :: Int -> Instance -> Container Disk -> Container Disk
updateIvNames idx inst (GenericContainer m) =
let dUuids = drop idx (instDisks inst)
upgradeIv m' (idx'', dUuid') =
M.adjust (diskIvNameL .~ "disk/" ++ show idx'') dUuid' m'
in GenericContainer $ foldl upgradeIv m
(zip [idx..] (fmap UTF8.fromString dUuids))
-- * Monadic config modification functions which can return errors
detachInstanceDisk' :: MonadError GanetiException m
=> InstanceUUID
-> DiskUUID
-> ClockTime
-> ConfigState
-> m ConfigState
detachInstanceDisk' iUuid dUuid ct cs =
let resetIv :: MonadError GanetiException m
=> Int
-> [DiskUUID]
-> ConfigState
-> m ConfigState
resetIv startIdx disks = mapMOf (csConfigDataL . configDisksL)
(\cd -> foldM (\c (idx, dUuid') -> mapMOf (alterContainerL dUuid')
(\md -> case md of
Nothing -> throwError . ConfigurationError $
printf "Could not find disk with UUID %s" (UTF8.toString dUuid')
Just disk -> return
. Just
. (diskIvNameL .~ ("disk/" ++ show idx))
$ disk) c)
cd (zip [startIdx..] (fmap UTF8.fromString disks)))
iL = csConfigDataL . configInstancesL . alterContainerL
(UTF8.fromString iUuid)
in case cs ^. iL of
Nothing -> throwError . ConfigurationError $
printf "Could not find instance with UUID %s" iUuid
Just ist -> case elemIndex dUuid (instDisks ist) of
Nothing -> return cs
Just idx ->
let ist' = (instDisksL %~ filter (/= dUuid))
. (instSerialL %~ (+1))
. (instMtimeL .~ ct)
$ ist
cs' = iL .~ Just ist' $ cs
dks = drop (idx + 1) (instDisks ist)
in resetIv idx dks cs'
removeInstanceDisk' :: MonadError GanetiException m
=> InstanceUUID
-> DiskUUID
-> ClockTime
-> ConfigState
-> m ConfigState
removeInstanceDisk' iUuid dUuid ct =
let f cs
| elem dUuid
. fold
. fmap instDisks
. configInstances
. csConfigData
$ cs
= throwError . ProgrammerError $
printf "Cannot remove disk %s. Disk is attached to an instance" dUuid
| elem dUuid
. foldMap (:[])
. fmap (UTF8.toString . diskUuid)
. configDisks
. csConfigData
$ cs
= return
. ((csConfigDataL . configDisksL . alterContainerL
(UTF8.fromString dUuid)) .~ Nothing)
. ((csConfigDataL . configClusterL . clusterSerialL) %~ (+1))
. ((csConfigDataL . configClusterL . clusterMtimeL) .~ ct)
$ cs
| otherwise = return cs
in (f =<<) . detachInstanceDisk' iUuid dUuid ct
-- * RPCs
-- | Add a new instance to the configuration, release DRBD minors,
-- and commit temporary IPs, all while temporarily holding the config
-- lock. Return True upon success and False if the config lock was not
-- available and the client should retry.
addInstance :: Instance -> ClientId -> Bool -> WConfdMonad Bool
addInstance inst cid replace = do
ct <- liftIO getClockTime
logDebug $ "AddInstance: client " ++ show (ciIdentifier cid)
++ " adding instance " ++ uuidOf inst
++ " with name " ++ show (instName inst)
let setCtime = instCtimeL .~ ct
setMtime = instMtimeL .~ ct
addInst i = csConfigDataL . configInstancesL
. alterContainerL (UTF8.fromString $ uuidOf i)
.~ Just i
commitRes tr = mapMOf csConfigDataL $ T.commitReservedIps cid tr
r <- modifyConfigWithLock
(\tr cs -> do
toError $ addInstanceChecks inst replace cs
commitRes tr $ addInst (setMtime . setCtime $ inst) cs)
. T.releaseDRBDMinors . UTF8.fromString $ uuidOf inst
logDebug $ "AddInstance: result of config modification is " ++ show r
return $ isJust r
addInstanceDisk :: InstanceUUID
-> Disk
-> MaybeForJSON Int
-> Bool
-> WConfdMonad Bool
addInstanceDisk iUuid disk idx replace = do
logInfo $ printf "Adding disk %s to configuration"
(UTF8.toString (diskUuid disk))
ct <- liftIO getClockTime
let addD = csConfigDataL . configDisksL . alterContainerL
(UTF8.fromString (uuidOf disk))
.~ Just disk
incrSerialNo = csConfigDataL . configSerialL %~ (+1)
r <- modifyConfigWithLock (\_ cs -> do
toError $ addDiskChecks disk replace cs
let cs' = incrSerialNo . addD $ cs
toError $ attachInstanceDiskChecks iUuid
(UTF8.toString (diskUuid disk)) idx cs'
return $ attachInstanceDisk' iUuid
(UTF8.toString (diskUuid disk)) idx ct cs')
. T.releaseDRBDMinors $ UTF8.fromString (uuidOf disk)
return $ isJust r
attachInstanceDisk :: InstanceUUID
-> DiskUUID
-> MaybeForJSON Int
-> WConfdMonad Bool
attachInstanceDisk iUuid dUuid idx = do
ct <- liftIO getClockTime
r <- modifyConfigWithLock (\_ cs -> do
toError $ attachInstanceDiskChecks iUuid dUuid idx cs
return $ attachInstanceDisk' iUuid dUuid idx ct cs)
(return ())
return $ isJust r
-- | Detach a disk from an instance.
detachInstanceDisk :: InstanceUUID -> DiskUUID -> WConfdMonad Bool
detachInstanceDisk iUuid dUuid = do
ct <- liftIO getClockTime
isJust <$> modifyConfigWithLock
(const $ detachInstanceDisk' iUuid dUuid ct) (return ())
-- | Detach a disk from an instance and
-- remove it from the config.
removeInstanceDisk :: InstanceUUID -> DiskUUID -> WConfdMonad Bool
removeInstanceDisk iUuid dUuid = do
ct <- liftIO getClockTime
isJust <$> modifyConfigWithLock
(const $ removeInstanceDisk' iUuid dUuid ct) (return ())
-- | Remove the instance from the configuration.
removeInstance :: InstanceUUID -> WConfdMonad Bool
removeInstance iUuid = do
ct <- liftIO getClockTime
let iL = csConfigDataL . configInstancesL . alterContainerL
(UTF8.fromString iUuid)
pL = csConfigDataL . configClusterL . clusterTcpudpPortPoolL
sL = csConfigDataL . configClusterL . clusterSerialL
mL = csConfigDataL . configClusterL . clusterMtimeL
-- Add the instances' network port to the cluster pool
f :: Monad m => StateT ConfigState m ()
f = get >>= (maybe
(return ())
(maybe
(return ())
(modify . (pL %~) . (:))
. instNetworkPort)
. (^. iL))
-- Release all IP addresses to the pool
g :: (MonadError GanetiException m, Functor m, MonadFail m) =>
StateT ConfigState m ()
g = get >>= (maybe
(return ())
(mapM_ (\nic ->
when ((isJust . nicNetwork $ nic) && (isJust . nicIp $ nic)) $ do
let network = fromJust . nicNetwork $ nic
ip <- readIp4Address (fromJust . nicIp $ nic)
get >>= mapMOf csConfigDataL (T.commitReleaseIp
(UTF8.fromString network) ip) >>= put)
. instNics)
. (^. iL))
-- Remove the instance and update cluster serial num, and mtime
h :: Monad m => StateT ConfigState m ()
h = modify $ (iL .~ Nothing) . (sL %~ (+1)) . (mL .~ ct)
isJust <$> modifyConfigWithLock (const $ execStateT (f >> g >> h)) (return ())
-- | Allocate a port.
-- The port will be taken from the available port pool or from the
-- default port range (and in this case we increase
-- highest_used_port).
allocatePort :: WConfdMonad (MaybeForJSON Int)
allocatePort = do
maybePort <- modifyConfigAndReturnWithLock (\_ cs ->
let portPoolL = csConfigDataL . configClusterL . clusterTcpudpPortPoolL
hupL = csConfigDataL . configClusterL . clusterHighestUsedPortL
in case cs ^. portPoolL of
[] -> if cs ^. hupL >= lastDrbdPort
then throwError . ConfigurationError $ printf
"The highest used port is greater than %s. Aborting." lastDrbdPort
else return (cs ^. hupL + 1, hupL %~ (+1) $ cs)
(p:ps) -> return (p, portPoolL .~ ps $ cs))
(return ())
return . MaybeForJSON $ maybePort
-- | Adds a new port to the available port pool.
addTcpUdpPort :: Int -> WConfdMonad Bool
addTcpUdpPort port =
let pL = csConfigDataL . configClusterL . clusterTcpudpPortPoolL
f :: Monad m => ConfigState -> m ConfigState
f = mapMOf pL (return . (port:) . filter (/= port))
in isJust <$> modifyConfigWithLock (const f) (return ())
-- | Set the instances' status to a given value.
setInstanceStatus :: InstanceUUID
-> MaybeForJSON AdminState
-> MaybeForJSON Bool
-> MaybeForJSON AdminStateSource
-> WConfdMonad (MaybeForJSON Instance)
setInstanceStatus iUuid m1 m2 m3 = do
ct <- liftIO getClockTime
let modifyInstance = maybe id (instAdminStateL .~) (unMaybeForJSON m1)
. maybe id (instDisksActiveL .~) (unMaybeForJSON m2)
. maybe id (instAdminStateSourceL .~) (unMaybeForJSON m3)
reviseInstance = (instSerialL %~ (+1))
. (instMtimeL .~ ct)
g :: Instance -> Instance
g i = if modifyInstance i == i
then i
else reviseInstance . modifyInstance $ i
iL = csConfigDataL . configInstancesL . alterContainerL
(UTF8.fromString iUuid)
f :: MonadError GanetiException m => StateT ConfigState m Instance
f = get >>= (maybe
(throwError . ConfigurationError $
printf "Could not find instance with UUID %s" iUuid)
(liftM2 (>>)
(modify . (iL .~) . Just)
return . g)
. (^. iL))
MaybeForJSON <$> modifyConfigAndReturnWithLock
(const $ runStateT f) (return ())
-- | Sets the primary node of an existing instance
setInstancePrimaryNode :: InstanceUUID -> NodeUUID -> WConfdMonad Bool
setInstancePrimaryNode iUuid nUuid = isJust <$> modifyConfigWithLock
(\_ -> mapMOf (csConfigDataL . configInstancesL . alterContainerL
(UTF8.fromString iUuid))
(\mi -> case mi of
Nothing -> throwError . ConfigurationError $
printf "Could not find instance with UUID %s" iUuid
Just ist -> return . Just $ (instPrimaryNodeL .~ nUuid) ist))
(return ())
-- | The configuration is updated by the provided cluster
updateCluster :: Cluster -> WConfdMonad (MaybeForJSON (Int, TimeAsDoubleJSON))
updateCluster cluster = do
ct <- liftIO getClockTime
r <- modifyConfigAndReturnWithLock (\_ cs -> do
let currentCluster = configCluster . csConfigData $ cs
if isIdentical ct cluster currentCluster
then return ((serialOf currentCluster, mTimeOf currentCluster), cs)
else do
toError $ checkSerial cluster currentCluster
let updateC = (clusterSerialL %~ (+1)) . (clusterMtimeL .~ ct)
return ((serialOf cluster + 1, ct)
, csConfigDataL . configClusterL .~ updateC cluster $ cs))
(return ())
return . MaybeForJSON $ fmap (_2 %~ TimeAsDoubleJSON) r
-- | The configuration is updated by the provided node
updateNode :: Node -> WConfdMonad (MaybeForJSON (Int, TimeAsDoubleJSON))
updateNode node = do
ct <- liftIO getClockTime
let nL = csConfigDataL . configNodesL
updateC = (clusterSerialL %~ (+1)) . (clusterMtimeL .~ ct)
r <- modifyConfigAndReturnWithLock (\_ -> updateConfigIfNecessary ct node
(^. nL) (\cs -> do
nC <- toError $ replaceIn ct node (cs ^. nL)
return ((serialOf node + 1, ct), (nL .~ nC)
. (csConfigDataL . configClusterL %~ updateC)
$ cs)))
(return ())
return . MaybeForJSON $ fmap (_2 %~ TimeAsDoubleJSON) r
-- | The configuration is updated by the provided instance
updateInstance :: Instance -> WConfdMonad (MaybeForJSON (Int, TimeAsDoubleJSON))
updateInstance inst = do
ct <- liftIO getClockTime
let iL = csConfigDataL . configInstancesL
r <- modifyConfigAndReturnWithLock (\_ -> updateConfigIfNecessary ct inst
(^. iL) (\cs -> do
iC <- toError $ replaceIn ct inst (cs ^. iL)
return ((serialOf inst + 1, ct), (iL .~ iC) cs)))
(return ())
return . MaybeForJSON $ fmap (_2 %~ TimeAsDoubleJSON) r
-- | The configuration is updated by the provided nodegroup
updateNodeGroup :: NodeGroup
-> WConfdMonad (MaybeForJSON (Int, TimeAsDoubleJSON))
updateNodeGroup ng = do
ct <- liftIO getClockTime
let ngL = csConfigDataL . configNodegroupsL
r <- modifyConfigAndReturnWithLock (\_ -> updateConfigIfNecessary ct ng
(^. ngL) (\cs -> do
ngC <- toError $ replaceIn ct ng (cs ^. ngL)
return ((serialOf ng + 1, ct), (ngL .~ ngC) cs)))
(return ())
return . MaybeForJSON $ fmap (_2 %~ TimeAsDoubleJSON) r
-- | The configuration is updated by the provided network
updateNetwork :: Network -> WConfdMonad (MaybeForJSON (Int, TimeAsDoubleJSON))
updateNetwork net = do
ct <- liftIO getClockTime
let nL = csConfigDataL . configNetworksL
r <- modifyConfigAndReturnWithLock (\_ -> updateConfigIfNecessary ct net
(^. nL) (\cs -> do
nC <- toError $ replaceIn ct net (cs ^. nL)
return ((serialOf net + 1, ct), (nL .~ nC) cs)))
(return ())
return . MaybeForJSON $ fmap (_2 %~ TimeAsDoubleJSON) r
-- | The configuration is updated by the provided disk
updateDisk :: Disk -> WConfdMonad (MaybeForJSON (Int, TimeAsDoubleJSON))
updateDisk disk = do
ct <- liftIO getClockTime
let dL = csConfigDataL . configDisksL
r <- modifyConfigAndReturnWithLock (\_ -> updateConfigIfNecessary ct disk
(^. dL) (\cs -> do
dC <- toError $ replaceIn ct disk (cs ^. dL)
return ((serialOf disk + 1, ct), (dL .~ dC) cs)))
. T.releaseDRBDMinors . UTF8.fromString $ uuidOf disk
return . MaybeForJSON $ fmap (_2 %~ TimeAsDoubleJSON) r
-- * The list of functions exported to RPC.
exportedFunctions :: [Name]
exportedFunctions = [ 'addInstance
, 'addInstanceDisk
, 'addTcpUdpPort
, 'allocatePort
, 'attachInstanceDisk
, 'detachInstanceDisk
, 'removeInstance
, 'removeInstanceDisk
, 'setInstancePrimaryNode
, 'setInstanceStatus
, 'updateCluster
, 'updateDisk
, 'updateInstance
, 'updateNetwork
, 'updateNode
, 'updateNodeGroup
]
|
ganeti/ganeti
|
src/Ganeti/WConfd/ConfigModifications.hs
|
bsd-2-clause
| 27,921 | 0 | 29 | 7,721 | 7,039 | 3,628 | 3,411 | -1 | -1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QLayout.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:36
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Gui.QLayout (
SizeConstraint, eSetDefaultConstraint, eSetNoConstraint, eSetMinimumSize, eSetFixedSize, eSetMaximumSize, eSetMinAndMaxSize
)
where
import Foreign.C.Types
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CSizeConstraint a = CSizeConstraint a
type SizeConstraint = QEnum(CSizeConstraint Int)
ieSizeConstraint :: Int -> SizeConstraint
ieSizeConstraint x = QEnum (CSizeConstraint x)
instance QEnumC (CSizeConstraint Int) where
qEnum_toInt (QEnum (CSizeConstraint x)) = x
qEnum_fromInt x = QEnum (CSizeConstraint x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> SizeConstraint -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
eSetDefaultConstraint :: SizeConstraint
eSetDefaultConstraint
= ieSizeConstraint $ 0
eSetNoConstraint :: SizeConstraint
eSetNoConstraint
= ieSizeConstraint $ 1
eSetMinimumSize :: SizeConstraint
eSetMinimumSize
= ieSizeConstraint $ 2
eSetFixedSize :: SizeConstraint
eSetFixedSize
= ieSizeConstraint $ 3
eSetMaximumSize :: SizeConstraint
eSetMaximumSize
= ieSizeConstraint $ 4
eSetMinAndMaxSize :: SizeConstraint
eSetMinAndMaxSize
= ieSizeConstraint $ 5
|
keera-studios/hsQt
|
Qtc/Enums/Gui/QLayout.hs
|
bsd-2-clause
| 2,848 | 0 | 18 | 565 | 663 | 343 | 320 | 64 | 1 |
module Propellor.Property.ConfFile (
-- * Generic conffiles with sections
SectionStart,
SectionPast,
AdjustSection,
InsertSection,
adjustSection,
-- * Windows .ini files
IniSection,
IniKey,
containsIniSetting,
lacksIniSection,
) where
import Propellor.Base
import Propellor.Property.File
import Data.List (isPrefixOf, foldl')
-- | find the line that is the start of the wanted section (eg, == "<Foo>")
type SectionStart = Line -> Bool
-- | find a line that indicates we are past the section
-- (eg, a new section header)
type SectionPast = Line -> Bool
-- | run on all lines in the section, including the SectionStart line;
-- can add, delete, and modify lines, or even delete entire section
type AdjustSection = [Line] -> [Line]
-- | if SectionStart does not find the section in the file, this is used to
-- insert the section somewhere within it
type InsertSection = [Line] -> [Line]
-- | Adjusts a section of conffile.
adjustSection
:: Desc
-> SectionStart
-> SectionPast
-> AdjustSection
-> InsertSection
-> FilePath
-> Property NoInfo
adjustSection desc start past adjust insert = fileProperty desc go
where
go ls = let (pre, wanted, post) = foldl' find ([], [], []) ls
in if null wanted
then insert ls
else pre ++ (adjust wanted) ++ post
find (pre, wanted, post) l
| null wanted && null post && (not . start) l =
(pre ++ [l], wanted, post)
| (start l && null wanted && null post)
|| ((not . null) wanted && null post && (not . past) l) =
(pre, wanted ++ [l], post)
| otherwise = (pre, wanted, post ++ [l])
-- | Name of a section of an .ini file. This value is put
-- in square braces to generate the section header.
type IniSection = String
-- | Name of a configuration setting within a .ini file.
type IniKey = String
iniHeader :: IniSection -> String
iniHeader header = '[' : header ++ "]"
adjustIniSection
:: Desc
-> IniSection
-> AdjustSection
-> InsertSection
-> FilePath
-> Property NoInfo
adjustIniSection desc header =
adjustSection
desc
(== iniHeader header)
("[" `isPrefixOf`)
-- | Ensures that a .ini file exists and contains a section
-- with a key=value setting.
containsIniSetting :: FilePath -> (IniSection, IniKey, String) -> Property NoInfo
containsIniSetting f (header, key, value) =
adjustIniSection
(f ++ " section [" ++ header ++ "] contains " ++ key ++ "=" ++ value)
header
go
(++ [confheader, confline]) -- add missing section at end
f
where
confheader = iniHeader header
confline = key ++ "=" ++ value
go [] = [confline]
go (l:ls) = if isKeyVal l then confline : ls else l : (go ls)
isKeyVal x = (filter (/= ' ') . takeWhile (/= '=')) x `elem` [key, '#':key]
-- | Ensures that a .ini file does not contain the specified section.
lacksIniSection :: FilePath -> IniSection -> Property NoInfo
lacksIniSection f header =
adjustIniSection
(f ++ " lacks section [" ++ header ++ "]")
header
(const []) -- remove all lines of section
id -- add no lines if section is missing
f
|
np/propellor
|
src/Propellor/Property/ConfFile.hs
|
bsd-2-clause
| 2,998 | 84 | 16 | 602 | 894 | 491 | 403 | 74 | 3 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.NoFrillsDecoration
-- Description : Most basic version of decoration for windows.
-- Copyright : (c) Jan Vornberger 2009
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : not portable
--
-- Most basic version of decoration for windows without any additional
-- modifications. In contrast to "XMonad.Layout.SimpleDecoration" this will
-- result in title bars that span the entire window instead of being only the
-- length of the window title.
--
-----------------------------------------------------------------------------
module XMonad.Layout.NoFrillsDecoration
( -- * Usage:
-- $usage
noFrillsDeco
, module XMonad.Layout.SimpleDecoration
, NoFrillsDecoration
) where
import XMonad.Layout.Decoration
import XMonad.Layout.SimpleDecoration
-- $usage
-- You can use this module with the following in your
-- @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Layout.NoFrillsDecoration
--
-- Then edit your @layoutHook@ by adding the NoFrillsDecoration to
-- your layout:
--
-- > myL = noFrillsDeco shrinkText def (layoutHook def)
-- > main = xmonad def { layoutHook = myL }
--
-- | Add very simple decorations to windows of a layout.
noFrillsDeco :: (Eq a, Shrinker s) => s -> Theme
-> l a -> ModifiedLayout (Decoration NoFrillsDecoration s) l a
noFrillsDeco s c = decoration s c $ NFD True
newtype NoFrillsDecoration a = NFD Bool deriving (Show, Read)
instance Eq a => DecorationStyle NoFrillsDecoration a where
describeDeco _ = "NoFrillsDeco"
|
xmonad/xmonad-contrib
|
XMonad/Layout/NoFrillsDecoration.hs
|
bsd-3-clause
| 1,770 | 0 | 11 | 303 | 184 | 115 | 69 | 14 | 1 |
-- | This module provides useful character-related predicates and special
-- characters.
module CommonMark.Util.Char
(
-- * Special characters
replacementChar
-- * Basic predicates
, isAsciiLetter
, isAsciiAlphaNum
-- * Whitespace
, isWhitespace
, isUnicodeWhitespace
-- * Punctuation
, isAsciiPunctuation
, isPunctuation
-- * URI schemes
, isSchemeChar
, isSchemeSpecificChar
-- * Email address
, isAtext
) where
import Data.Char ( isAlphaNum, isAscii, isLetter )
import Data.CharSet ( CharSet )
import qualified Data.CharSet as CS
import qualified Data.CharSet.Unicode.Category as CS ( punctuation, space )
-- | The replacement character (U+FFFD).
replacementChar :: Char
replacementChar = '\xFFFD'
-- | Selects alphabetic ASCII characters.
isAsciiLetter :: Char -> Bool
isAsciiLetter c = isAscii c && isLetter c
-- | Selects alphanumeric ASCII characters.
isAsciiAlphaNum :: Char -> Bool
isAsciiAlphaNum c = isAscii c && isAlphaNum c
-- | Selects ASCII whitespace characters: space (U+0020), tab (U+0009),
-- newline (U+000A), line tabulation (U+000B), form feed (U+000C), carriage
-- return (U+000D).
isWhitespace :: Char -> Bool
isWhitespace =
let charset = CS.fromList " \t\n\v\f\r"
in \c -> c `CS.member` charset
-- | Selects Unicode whitespace character: any code point in the Zs class,
-- tab (U+0009), carriage return (U+000D), newline (U+000A), form feed
-- (U+000C).
isUnicodeWhitespace :: Char -> Bool
isUnicodeWhitespace =
let charset = CS.space `CS.union` CS.fromList "\t\r\n\f"
in \c -> c `CS.member` charset
-- | Selects an ASCII punctuation character.
isAsciiPunctuation :: Char -> Bool
isAsciiPunctuation c = c `CS.member` asciiPunctuation
-- | The set of ASCII punctuation characters.
-- See <http://spec.commonmark.org/0.21/#ascii-punctuation-character> for
-- details.
asciiPunctuation :: CharSet
asciiPunctuation = CS.fromList "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
-- | Selects a punctuation character: ASCII punctuation characters, or
-- anything in the Unicode classes Pc, Pd, Pe, Pf, Pi, Po, or Ps.
isPunctuation :: Char -> Bool
isPunctuation =
let charset = asciiPunctuation `CS.union` CS.punctuation
in \c -> c `CS.member` charset
-- | Selects characters that can occur in URI schemes.
isSchemeChar :: Char -> Bool
isSchemeChar c = isAsciiAlphaNum c || c == '-' || c == '.'
-- | Selects characters that are can occur in the scheme-specific part of
-- URIs.
isSchemeSpecificChar :: Char -> Bool
isSchemeSpecificChar c = c /= ' ' && c /= '<' && c /= '>'
-- | Selects characters from the /atext/ production in the grammar of email
-- addresses. See <http://spec.commonmark.org/0.21/#email-address> for more
-- details.
isAtext :: Char -> Bool
isAtext =
let charset = CS.fromList "!#$%&'*+\\/=?^_`{|}~-"
in \c -> isAsciiAlphaNum c || c `CS.member` charset
|
Jubobs/CommonMark-WIP
|
src/CommonMark/Util/Char.hs
|
bsd-3-clause
| 2,920 | 0 | 11 | 549 | 491 | 286 | 205 | 46 | 1 |
module Model.Entities
( LastUpdated (..)
, PersistId (..)
, formatDatetime
, formatEventTime
) where
import Prelude
import Data.Monoid
import Data.Text as T
import Data.Time
import System.Locale
import Yesod
import Model
class LastUpdated a where
lastUpdated :: a -> UTCTime
instance LastUpdated a => LastUpdated (Entity a) where
lastUpdated = lastUpdated . entityVal
instance LastUpdated Comment where
lastUpdated (Comment _ updated _ _) = updated
instance LastUpdated Release where
lastUpdated (Release _ _ _ _ _ uploaded) = uploaded
class PersistId a where
persistId :: Key a -> Text
instance PersistId Comment where
persistId = either T.pack ("comment-" <>) . fromPersistValueText . unKey
formatDatetime :: UTCTime -> String
formatDatetime = formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S%z"
formatEventTime :: UTCTime -> String
formatEventTime = formatTime defaultTimeLocale "%B %e, %Y at %T"
|
pxqr/bitidx
|
Model/Entities.hs
|
bsd-3-clause
| 957 | 0 | 9 | 184 | 258 | 140 | 118 | 28 | 1 |
module App
( runMatterhorn
, closeMatterhorn
)
where
import Prelude ()
import Prelude.MH
import Brick
import Control.Monad.Trans.Except ( runExceptT )
import qualified Graphics.Vty as Vty
import Text.Aspell ( stopAspell )
import Network.Mattermost
import Config
import Draw
import Events
import IOUtil
import InputHistory
import LastRunState
import Options
import State.Setup
import State.Setup.Threads.Logging ( shutdownLogManager )
import Types
app :: App ChatState MHEvent Name
app = App
{ appDraw = draw
, appChooseCursor = showFirstCursor
, appHandleEvent = onEvent
, appStartEvent = return
, appAttrMap = (^.csResources.crTheme)
}
runMatterhorn :: Options -> Config -> IO ChatState
runMatterhorn opts config = do
st <- setupState (optLogLocation opts) config
let mkVty = do
vty <- Vty.mkVty Vty.defaultConfig
let output = Vty.outputIface vty
Vty.setMode output Vty.BracketedPaste True
Vty.setMode output Vty.Hyperlink $ configHyperlinkingMode config
return vty
finalSt <- customMain mkVty (Just $ st^.csResources.crEventQueue) app st
case finalSt^.csEditState.cedSpellChecker of
Nothing -> return ()
Just (s, _) -> stopAspell s
return finalSt
-- | Cleanup resources and save data for restoring on program restart.
closeMatterhorn :: ChatState -> IO ()
closeMatterhorn finalSt = do
logIfError (mmCloseSession $ getResourceSession $ finalSt^.csResources)
"Error in closing session"
logIfError (writeHistory (finalSt^.csEditState.cedInputHistory))
"Error in writing history"
logIfError (writeLastRunState finalSt)
"Error in writing last run state"
shutdownLogManager $ finalSt^.csResources.crLogManager
where
logIfError action msg = do
done <- runExceptT $ convertIOException $ action
case done of
Left err -> putStrLn $ msg <> ": " <> err
Right _ -> return ()
|
aisamanra/matterhorn
|
src/App.hs
|
bsd-3-clause
| 2,121 | 0 | 16 | 593 | 519 | 268 | 251 | -1 | -1 |
--------------------------------------------------------------------------------
-- |
-- Module : Data.BitVector.Util
-- Copyright : (c) 2010 Philip Weaver
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability :
-- Portability :
--
-- (Description)
--------------------------------------------------------------------------------
module Data.BitVector.Util where
import Data.Bits (Bits, (.&.))
----------------------------------------
-- determine the minimum number of bits needed to represent 'x'.
-- TODO handle negative numbers.
-- {-# INLINE neededBits #-}
neededBits :: (Integral a) => a -> Int
neededBits x
= ceiling (logBase 2 (fromIntegral (x+1)) :: Float)
-- find the index of the highest bit that is set
-- {-# INLINE msbIndex #-}
msbIndex :: (Integral a) => Int -> a -> Int
msbIndex w 0 = w
msbIndex _ x = floor (logBase 2 (fromIntegral x) :: Float)
-- mask the upper bits of a number so that only the lower 'n' bits are set.
{-# INLINE maskWidth #-}
maskWidth :: (Bits a, Integral a) => Int -> a -> a
maskWidth w x = x .&. (2^w-1)
--maskWidth w x = mod x (2^w)
----------------------------------------
|
pheaver/BitVector
|
Data/BitVector/Util.hs
|
bsd-3-clause
| 1,162 | 0 | 11 | 197 | 212 | 125 | 87 | 11 | 1 |
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[CoreRules]{Transformation rules}
-}
{-# LANGUAGE CPP #-}
-- | Functions for collecting together and applying rewrite rules to a module.
-- The 'CoreRule' datatype itself is declared elsewhere.
module Rules (
-- ** Constructing
emptyRuleBase, mkRuleBase, extendRuleBaseList,
unionRuleBase, pprRuleBase,
-- ** Checking rule applications
ruleCheckProgram,
-- ** Manipulating 'RuleInfo' rules
mkRuleInfo, extendRuleInfo, addRuleInfo,
addIdSpecialisations,
-- * Misc. CoreRule helpers
rulesOfBinds, getRules, pprRulesForUser,
lookupRule, mkRule, roughTopNames
) where
#include "HsVersions.h"
import CoreSyn -- All of it
import Module ( Module, ModuleSet, elemModuleSet )
import CoreSubst
import OccurAnal ( occurAnalyseExpr )
import CoreFVs ( exprFreeVars, exprsFreeVars, bindFreeVars
, rulesFreeVarsDSet, exprsOrphNames, exprFreeVarsList )
import CoreUtils ( exprType, eqExpr, mkTick, mkTicks,
stripTicksTopT, stripTicksTopE )
import PprCore ( pprRules )
import Type ( Type, substTy, mkTCvSubst )
import TcType ( tcSplitTyConApp_maybe )
import TysWiredIn ( anyTypeOfKind )
import Coercion
import CoreTidy ( tidyRules )
import Id
import IdInfo ( RuleInfo( RuleInfo ) )
import Var
import VarEnv
import VarSet
import Name ( Name, NamedThing(..), nameIsLocalOrFrom )
import NameSet
import NameEnv
import UniqFM
import Unify ( ruleMatchTyX )
import BasicTypes ( Activation, CompilerPhase, isActive, pprRuleName )
import StaticFlags ( opt_PprStyle_Debug )
import DynFlags ( DynFlags )
import Outputable
import FastString
import Maybes
import Bag
import Util
import Data.List
import Data.Ord
import Control.Monad ( guard )
{-
Note [Overall plumbing for rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* After the desugarer:
- The ModGuts initially contains mg_rules :: [CoreRule] of
locally-declared rules for imported Ids.
- Locally-declared rules for locally-declared Ids are attached to
the IdInfo for that Id. See Note [Attach rules to local ids] in
DsBinds
* TidyPgm strips off all the rules from local Ids and adds them to
mg_rules, so that the ModGuts has *all* the locally-declared rules.
* The HomePackageTable contains a ModDetails for each home package
module. Each contains md_rules :: [CoreRule] of rules declared in
that module. The HomePackageTable grows as ghc --make does its
up-sweep. In batch mode (ghc -c), the HPT is empty; all imported modules
are treated by the "external" route, discussed next, regardless of
which package they come from.
* The ExternalPackageState has a single eps_rule_base :: RuleBase for
Ids in other packages. This RuleBase simply grow monotonically, as
ghc --make compiles one module after another.
During simplification, interface files may get demand-loaded,
as the simplifier explores the unfoldings for Ids it has in
its hand. (Via an unsafePerformIO; the EPS is really a cache.)
That in turn may make the EPS rule-base grow. In contrast, the
HPT never grows in this way.
* The result of all this is that during Core-to-Core optimisation
there are four sources of rules:
(a) Rules in the IdInfo of the Id they are a rule for. These are
easy: fast to look up, and if you apply a substitution then
it'll be applied to the IdInfo as a matter of course.
(b) Rules declared in this module for imported Ids, kept in the
ModGuts. If you do a substitution, you'd better apply the
substitution to these. There are seldom many of these.
(c) Rules declared in the HomePackageTable. These never change.
(d) Rules in the ExternalPackageTable. These can grow in response
to lazy demand-loading of interfaces.
* At the moment (c) is carried in a reader-monad way by the CoreMonad.
The HomePackageTable doesn't have a single RuleBase because technically
we should only be able to "see" rules "below" this module; so we
generate a RuleBase for (c) by combing rules from all the modules
"below" us. That's why we can't just select the home-package RuleBase
from HscEnv.
[NB: we are inconsistent here. We should do the same for external
packages, but we don't. Same for type-class instances.]
* So in the outer simplifier loop, we combine (b-d) into a single
RuleBase, reading
(b) from the ModGuts,
(c) from the CoreMonad, and
(d) from its mutable variable
[Of coures this means that we won't see new EPS rules that come in
during a single simplifier iteration, but that probably does not
matter.]
************************************************************************
* *
\subsection[specialisation-IdInfo]{Specialisation info about an @Id@}
* *
************************************************************************
A @CoreRule@ holds details of one rule for an @Id@, which
includes its specialisations.
For example, if a rule for @f@ contains the mapping:
\begin{verbatim}
forall a b d. [Type (List a), Type b, Var d] ===> f' a b
\end{verbatim}
then when we find an application of f to matching types, we simply replace
it by the matching RHS:
\begin{verbatim}
f (List Int) Bool dict ===> f' Int Bool
\end{verbatim}
All the stuff about how many dictionaries to discard, and what types
to apply the specialised function to, are handled by the fact that the
Rule contains a template for the result of the specialisation.
There is one more exciting case, which is dealt with in exactly the same
way. If the specialised value is unboxed then it is lifted at its
definition site and unlifted at its uses. For example:
pi :: forall a. Num a => a
might have a specialisation
[Int#] ===> (case pi' of Lift pi# -> pi#)
where pi' :: Lift Int# is the specialised version of pi.
-}
mkRule :: Module -> Bool -> Bool -> RuleName -> Activation
-> Name -> [CoreBndr] -> [CoreExpr] -> CoreExpr -> CoreRule
-- ^ Used to make 'CoreRule' for an 'Id' defined in the module being
-- compiled. See also 'CoreSyn.CoreRule'
mkRule this_mod is_auto is_local name act fn bndrs args rhs
= Rule { ru_name = name, ru_fn = fn, ru_act = act,
ru_bndrs = bndrs, ru_args = args,
ru_rhs = occurAnalyseExpr rhs,
ru_rough = roughTopNames args,
ru_origin = this_mod,
ru_orphan = orph,
ru_auto = is_auto, ru_local = is_local }
where
-- Compute orphanhood. See Note [Orphans] in InstEnv
-- A rule is an orphan only if none of the variables
-- mentioned on its left-hand side are locally defined
lhs_names = nameSetElems (extendNameSet (exprsOrphNames args) fn)
-- Since rules get eventually attached to one of the free names
-- from the definition when compiling the ABI hash, we should make
-- it deterministic. This chooses the one with minimal OccName
-- as opposed to uniq value.
local_lhs_names = filter (nameIsLocalOrFrom this_mod) lhs_names
orph = chooseOrphanAnchor local_lhs_names
--------------
roughTopNames :: [CoreExpr] -> [Maybe Name]
-- ^ Find the \"top\" free names of several expressions.
-- Such names are either:
--
-- 1. The function finally being applied to in an application chain
-- (if that name is a GlobalId: see "Var#globalvslocal"), or
--
-- 2. The 'TyCon' if the expression is a 'Type'
--
-- This is used for the fast-match-check for rules;
-- if the top names don't match, the rest can't
roughTopNames args = map roughTopName args
roughTopName :: CoreExpr -> Maybe Name
roughTopName (Type ty) = case tcSplitTyConApp_maybe ty of
Just (tc,_) -> Just (getName tc)
Nothing -> Nothing
roughTopName (Coercion _) = Nothing
roughTopName (App f _) = roughTopName f
roughTopName (Var f) | isGlobalId f -- Note [Care with roughTopName]
, isDataConWorkId f || idArity f > 0
= Just (idName f)
roughTopName (Tick t e) | tickishFloatable t
= roughTopName e
roughTopName _ = Nothing
ruleCantMatch :: [Maybe Name] -> [Maybe Name] -> Bool
-- ^ @ruleCantMatch tpl actual@ returns True only if @actual@
-- definitely can't match @tpl@ by instantiating @tpl@.
-- It's only a one-way match; unlike instance matching we
-- don't consider unification.
--
-- Notice that [_$_]
-- @ruleCantMatch [Nothing] [Just n2] = False@
-- Reason: a template variable can be instantiated by a constant
-- Also:
-- @ruleCantMatch [Just n1] [Nothing] = False@
-- Reason: a local variable @v@ in the actuals might [_$_]
ruleCantMatch (Just n1 : ts) (Just n2 : as) = n1 /= n2 || ruleCantMatch ts as
ruleCantMatch (_ : ts) (_ : as) = ruleCantMatch ts as
ruleCantMatch _ _ = False
{-
Note [Care with roughTopName]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this
module M where { x = a:b }
module N where { ...f x...
RULE f (p:q) = ... }
You'd expect the rule to match, because the matcher can
look through the unfolding of 'x'. So we must avoid roughTopName
returning 'M.x' for the call (f x), or else it'll say "can't match"
and we won't even try!!
However, suppose we have
RULE g (M.h x) = ...
foo = ...(g (M.k v))....
where k is a *function* exported by M. We never really match
functions (lambdas) except by name, so in this case it seems like
a good idea to treat 'M.k' as a roughTopName of the call.
-}
pprRulesForUser :: [CoreRule] -> SDoc
-- (a) tidy the rules
-- (b) sort them into order based on the rule name
-- (c) suppress uniques (unless -dppr-debug is on)
-- This combination makes the output stable so we can use in testing
-- It's here rather than in PprCore because it calls tidyRules
pprRulesForUser rules
= withPprStyle defaultUserStyle $
pprRules $
sortBy (comparing ru_name) $
tidyRules emptyTidyEnv rules
{-
************************************************************************
* *
RuleInfo: the rules in an IdInfo
* *
************************************************************************
-}
-- | Make a 'RuleInfo' containing a number of 'CoreRule's, suitable
-- for putting into an 'IdInfo'
mkRuleInfo :: [CoreRule] -> RuleInfo
mkRuleInfo rules = RuleInfo rules (rulesFreeVarsDSet rules)
extendRuleInfo :: RuleInfo -> [CoreRule] -> RuleInfo
extendRuleInfo (RuleInfo rs1 fvs1) rs2
= RuleInfo (rs2 ++ rs1) (rulesFreeVarsDSet rs2 `unionDVarSet` fvs1)
addRuleInfo :: RuleInfo -> RuleInfo -> RuleInfo
addRuleInfo (RuleInfo rs1 fvs1) (RuleInfo rs2 fvs2)
= RuleInfo (rs1 ++ rs2) (fvs1 `unionDVarSet` fvs2)
addIdSpecialisations :: Id -> [CoreRule] -> Id
addIdSpecialisations id []
= id
addIdSpecialisations id rules
= setIdSpecialisation id $
extendRuleInfo (idSpecialisation id) rules
-- | Gather all the rules for locally bound identifiers from the supplied bindings
rulesOfBinds :: [CoreBind] -> [CoreRule]
rulesOfBinds binds = concatMap (concatMap idCoreRules . bindersOf) binds
getRules :: RuleEnv -> Id -> [CoreRule]
-- See Note [Where rules are found]
getRules (RuleEnv { re_base = rule_base, re_visible_orphs = orphs }) fn
= idCoreRules fn ++ filter (ruleIsVisible orphs) imp_rules
where
imp_rules = lookupNameEnv rule_base (idName fn) `orElse` []
ruleIsVisible :: ModuleSet -> CoreRule -> Bool
ruleIsVisible _ BuiltinRule{} = True
ruleIsVisible vis_orphs Rule { ru_orphan = orph, ru_origin = origin }
= notOrphan orph || origin `elemModuleSet` vis_orphs
{-
Note [Where rules are found]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The rules for an Id come from two places:
(a) the ones it is born with, stored inside the Id iself (idCoreRules fn),
(b) rules added in other modules, stored in the global RuleBase (imp_rules)
It's tempting to think that
- LocalIds have only (a)
- non-LocalIds have only (b)
but that isn't quite right:
- PrimOps and ClassOps are born with a bunch of rules inside the Id,
even when they are imported
- The rules in PrelRules.builtinRules should be active even
in the module defining the Id (when it's a LocalId), but
the rules are kept in the global RuleBase
************************************************************************
* *
RuleBase
* *
************************************************************************
-}
-- RuleBase itself is defined in CoreSyn, along with CoreRule
emptyRuleBase :: RuleBase
emptyRuleBase = emptyNameEnv
mkRuleBase :: [CoreRule] -> RuleBase
mkRuleBase rules = extendRuleBaseList emptyRuleBase rules
extendRuleBaseList :: RuleBase -> [CoreRule] -> RuleBase
extendRuleBaseList rule_base new_guys
= foldl extendRuleBase rule_base new_guys
unionRuleBase :: RuleBase -> RuleBase -> RuleBase
unionRuleBase rb1 rb2 = plusNameEnv_C (++) rb1 rb2
extendRuleBase :: RuleBase -> CoreRule -> RuleBase
extendRuleBase rule_base rule
= extendNameEnv_Acc (:) singleton rule_base (ruleIdName rule) rule
pprRuleBase :: RuleBase -> SDoc
pprRuleBase rules = pprUFM rules $ \rss ->
vcat [ pprRules (tidyRules emptyTidyEnv rs)
| rs <- rss ]
{-
************************************************************************
* *
Matching
* *
************************************************************************
-}
-- | The main rule matching function. Attempts to apply all (active)
-- supplied rules to this instance of an application in a given
-- context, returning the rule applied and the resulting expression if
-- successful.
lookupRule :: DynFlags -> InScopeEnv
-> (Activation -> Bool) -- When rule is active
-> Id -> [CoreExpr]
-> [CoreRule] -> Maybe (CoreRule, CoreExpr)
-- See Note [Extra args in rule matching]
-- See comments on matchRule
lookupRule dflags in_scope is_active fn args rules
= -- pprTrace "matchRules" (ppr fn <+> ppr args $$ ppr rules ) $
case go [] rules of
[] -> Nothing
(m:ms) -> Just (findBest (fn,args') m ms)
where
rough_args = map roughTopName args
-- Strip ticks from arguments, see note [Tick annotations in RULE
-- matching]. We only collect ticks if a rule actually matches -
-- this matters for performance tests.
args' = map (stripTicksTopE tickishFloatable) args
ticks = concatMap (stripTicksTopT tickishFloatable) args
go :: [(CoreRule,CoreExpr)] -> [CoreRule] -> [(CoreRule,CoreExpr)]
go ms [] = ms
go ms (r:rs)
| Just e <- matchRule dflags in_scope is_active fn args' rough_args r
= go ((r,mkTicks ticks e):ms) rs
| otherwise
= -- pprTrace "match failed" (ppr r $$ ppr args $$
-- ppr [ (arg_id, unfoldingTemplate unf)
-- | Var arg_id <- args
-- , let unf = idUnfolding arg_id
-- , isCheapUnfolding unf] )
go ms rs
findBest :: (Id, [CoreExpr])
-> (CoreRule,CoreExpr) -> [(CoreRule,CoreExpr)] -> (CoreRule,CoreExpr)
-- All these pairs matched the expression
-- Return the pair the the most specific rule
-- The (fn,args) is just for overlap reporting
findBest _ (rule,ans) [] = (rule,ans)
findBest target (rule1,ans1) ((rule2,ans2):prs)
| rule1 `isMoreSpecific` rule2 = findBest target (rule1,ans1) prs
| rule2 `isMoreSpecific` rule1 = findBest target (rule2,ans2) prs
| debugIsOn = let pp_rule rule
| opt_PprStyle_Debug = ppr rule
| otherwise = doubleQuotes (ftext (ru_name rule))
in pprTrace "Rules.findBest: rule overlap (Rule 1 wins)"
(vcat [if opt_PprStyle_Debug then
text "Expression to match:" <+> ppr fn <+> sep (map ppr args)
else empty,
text "Rule 1:" <+> pp_rule rule1,
text "Rule 2:" <+> pp_rule rule2]) $
findBest target (rule1,ans1) prs
| otherwise = findBest target (rule1,ans1) prs
where
(fn,args) = target
isMoreSpecific :: CoreRule -> CoreRule -> Bool
-- This tests if one rule is more specific than another
-- We take the view that a BuiltinRule is less specific than
-- anything else, because we want user-define rules to "win"
-- In particular, class ops have a built-in rule, but we
-- any user-specific rules to win
-- eg (Trac #4397)
-- truncate :: (RealFrac a, Integral b) => a -> b
-- {-# RULES "truncate/Double->Int" truncate = double2Int #-}
-- double2Int :: Double -> Int
-- We want the specific RULE to beat the built-in class-op rule
isMoreSpecific (BuiltinRule {}) _ = False
isMoreSpecific (Rule {}) (BuiltinRule {}) = True
isMoreSpecific (Rule { ru_bndrs = bndrs1, ru_args = args1 })
(Rule { ru_bndrs = bndrs2, ru_args = args2, ru_name = rule_name2 })
= isJust (matchN (in_scope, id_unfolding_fun) rule_name2 bndrs2 args2 args1)
where
id_unfolding_fun _ = NoUnfolding -- Don't expand in templates
in_scope = mkInScopeSet (mkVarSet bndrs1)
-- Actually we should probably include the free vars
-- of rule1's args, but I can't be bothered
noBlackList :: Activation -> Bool
noBlackList _ = False -- Nothing is black listed
{-
Note [Extra args in rule matching]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we find a matching rule, we return (Just (rule, rhs)),
but the rule firing has only consumed as many of the input args
as the ruleArity says. It's up to the caller to keep track
of any left-over args. E.g. if you call
lookupRule ... f [e1, e2, e3]
and it returns Just (r, rhs), where r has ruleArity 2
then the real rewrite is
f e1 e2 e3 ==> rhs e3
You might think it'd be cleaner for lookupRule to deal with the
leftover arguments, by applying 'rhs' to them, but the main call
in the Simplifier works better as it is. Reason: the 'args' passed
to lookupRule are the result of a lazy substitution
-}
------------------------------------
matchRule :: DynFlags -> InScopeEnv -> (Activation -> Bool)
-> Id -> [CoreExpr] -> [Maybe Name]
-> CoreRule -> Maybe CoreExpr
-- If (matchRule rule args) returns Just (name,rhs)
-- then (f args) matches the rule, and the corresponding
-- rewritten RHS is rhs
--
-- The returned expression is occurrence-analysed
--
-- Example
--
-- The rule
-- forall f g x. map f (map g x) ==> map (f . g) x
-- is stored
-- CoreRule "map/map"
-- [f,g,x] -- tpl_vars
-- [f,map g x] -- tpl_args
-- map (f.g) x) -- rhs
--
-- Then the call: matchRule the_rule [e1,map e2 e3]
-- = Just ("map/map", (\f,g,x -> rhs) e1 e2 e3)
--
-- Any 'surplus' arguments in the input are simply put on the end
-- of the output.
matchRule dflags rule_env _is_active fn args _rough_args
(BuiltinRule { ru_try = match_fn })
-- Built-in rules can't be switched off, it seems
= case match_fn dflags rule_env fn args of
Nothing -> Nothing
Just expr -> Just (occurAnalyseExpr expr)
-- We could do this when putting things into the rulebase, I guess
matchRule _ in_scope is_active _ args rough_args
(Rule { ru_name = rule_name, ru_act = act, ru_rough = tpl_tops
, ru_bndrs = tpl_vars, ru_args = tpl_args, ru_rhs = rhs })
| not (is_active act) = Nothing
| ruleCantMatch tpl_tops rough_args = Nothing
| otherwise
= case matchN in_scope rule_name tpl_vars tpl_args args of
Nothing -> Nothing
Just (bind_wrapper, tpl_vals) -> Just (bind_wrapper $
rule_fn `mkApps` tpl_vals)
where
rule_fn = occurAnalyseExpr (mkLams tpl_vars rhs)
-- We could do this when putting things into the rulebase, I guess
---------------------------------------
matchN :: InScopeEnv
-> RuleName -> [Var] -> [CoreExpr]
-> [CoreExpr] -- ^ Target; can have more elements than the template
-> Maybe (BindWrapper, -- Floated bindings; see Note [Matching lets]
[CoreExpr])
-- For a given match template and context, find bindings to wrap around
-- the entire result and what should be substituted for each template variable.
-- Fail if there are two few actual arguments from the target to match the template
matchN (in_scope, id_unf) rule_name tmpl_vars tmpl_es target_es
= do { subst <- go init_menv emptyRuleSubst tmpl_es target_es
; let (_, matched_es) = mapAccumL lookup_tmpl subst tmpl_vars
; return (rs_binds subst, matched_es) }
where
init_rn_env = mkRnEnv2 (extendInScopeSetList in_scope tmpl_vars)
-- See Note [Template binders]
init_menv = RV { rv_tmpls = mkVarSet tmpl_vars, rv_lcl = init_rn_env
, rv_fltR = mkEmptySubst (rnInScopeSet init_rn_env)
, rv_unf = id_unf }
go _ subst [] _ = Just subst
go _ _ _ [] = Nothing -- Fail if too few actual args
go menv subst (t:ts) (e:es) = do { subst1 <- match menv subst t e
; go menv subst1 ts es }
lookup_tmpl :: RuleSubst -> Var -> (RuleSubst, CoreExpr)
lookup_tmpl rs@(RS { rs_tv_subst = tv_subst, rs_id_subst = id_subst }) tmpl_var
| isId tmpl_var
= case lookupVarEnv id_subst tmpl_var of
Just e -> (rs, e)
_ -> unbound tmpl_var
| otherwise
= case lookupVarEnv tv_subst tmpl_var of
Just ty -> (rs, Type ty)
Nothing -> (rs { rs_tv_subst = extendVarEnv tv_subst tmpl_var fake_ty }, Type fake_ty)
-- See Note [Unbound template type variables]
where
fake_ty = anyTypeOfKind kind
cv_subst = to_co_env id_subst
kind = Type.substTy (mkTCvSubst in_scope (tv_subst, cv_subst))
(tyVarKind tmpl_var)
to_co_env env = nonDetFoldUFM_Directly to_co emptyVarEnv env
-- It's OK to use nonDetFoldUFM_Directly because we forget the
-- order immediately by creating a new env
to_co uniq expr env
| Just co <- exprToCoercion_maybe expr
= extendVarEnv_Directly env uniq co
| otherwise
= env
unbound var = pprPanic "Template variable unbound in rewrite rule" $
vcat [ text "Variable:" <+> ppr var
, text "Rule" <+> pprRuleName rule_name
, text "Rule bndrs:" <+> ppr tmpl_vars
, text "LHS args:" <+> ppr tmpl_es
, text "Actual args:" <+> ppr target_es ]
{- Note [Unbound template type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Type synonyms with phantom args can give rise to unbound template type
variables. Consider this (Trac #10689, simplCore/should_compile/T10689):
type Foo a b = b
f :: Eq a => a -> Bool
f x = x==x
{-# RULES "foo" forall (x :: Foo a Char). f x = True #-}
finkle = f 'c'
The rule looks like
foall (a::*) (d::Eq Char) (x :: Foo a Char).
f (Foo a Char) d x = True
Matching the rule won't bind 'a', and legitimately so. We fudge by
pretending that 'a' is bound to (Any :: *).
Note [Template binders]
~~~~~~~~~~~~~~~~~~~~~~~
Consider the following match (example 1):
Template: forall x. f x
Target: f (x+1)
This should succeed, because the template variable 'x' has nothing to
do with the 'x' in the target.
Likewise this one (example 2):
Template: forall x. f (\x.x)
Target: f (\y.y)
We achieve this simply by:
* Adding forall'd template binders to the in-scope set
This works even if the template binder are already in scope
(in the target) because
* The RuleSubst rs_tv_subst, rs_id_subst maps LHS template vars to
the target world. It is not applied recursively.
* Having the template vars in the in-scope set ensures that in
example 2 above, the (\x.x) is cloned to (\x'. x').
In the past we used rnBndrL to clone the template variables if
they were already in scope. But (a) that's not necessary and (b)
it complicate the fancy footwork for Note [Unbound template type variables]
************************************************************************
* *
The main matcher
* *
********************************************************************* -}
-- * The domain of the TvSubstEnv and IdSubstEnv are the template
-- variables passed into the match.
--
-- * The BindWrapper in a RuleSubst are the bindings floated out
-- from nested matches; see the Let case of match, below
--
data RuleMatchEnv
= RV { rv_tmpls :: VarSet -- Template variables
, rv_lcl :: RnEnv2 -- Renamings for *local bindings*
-- (lambda/case)
, rv_fltR :: Subst -- Renamings for floated let-bindings
-- domain disjoint from envR of rv_lcl
-- See Note [Matching lets]
, rv_unf :: IdUnfoldingFun
}
rvInScopeEnv :: RuleMatchEnv -> InScopeEnv
rvInScopeEnv renv = (rnInScopeSet (rv_lcl renv), rv_unf renv)
data RuleSubst = RS { rs_tv_subst :: TvSubstEnv -- Range is the
, rs_id_subst :: IdSubstEnv -- template variables
, rs_binds :: BindWrapper -- Floated bindings
, rs_bndrs :: VarSet -- Variables bound by floated lets
}
type BindWrapper = CoreExpr -> CoreExpr
-- See Notes [Matching lets] and [Matching cases]
-- we represent the floated bindings as a core-to-core function
emptyRuleSubst :: RuleSubst
emptyRuleSubst = RS { rs_tv_subst = emptyVarEnv, rs_id_subst = emptyVarEnv
, rs_binds = \e -> e, rs_bndrs = emptyVarSet }
-- At one stage I tried to match even if there are more
-- template args than real args.
-- I now think this is probably a bad idea.
-- Should the template (map f xs) match (map g)? I think not.
-- For a start, in general eta expansion wastes work.
-- SLPJ July 99
match :: RuleMatchEnv
-> RuleSubst
-> CoreExpr -- Template
-> CoreExpr -- Target
-> Maybe RuleSubst
-- We look through certain ticks. See note [Tick annotations in RULE matching]
match renv subst e1 (Tick t e2)
| tickishFloatable t
= match renv subst' e1 e2
where subst' = subst { rs_binds = rs_binds subst . mkTick t }
match _ _ e@Tick{} _
= pprPanic "Tick in rule" (ppr e)
-- See the notes with Unify.match, which matches types
-- Everything is very similar for terms
-- Interesting examples:
-- Consider matching
-- \x->f against \f->f
-- When we meet the lambdas we must remember to rename f to f' in the
-- second expresion. The RnEnv2 does that.
--
-- Consider matching
-- forall a. \b->b against \a->3
-- We must rename the \a. Otherwise when we meet the lambdas we
-- might substitute [a/b] in the template, and then erroneously
-- succeed in matching what looks like the template variable 'a' against 3.
-- The Var case follows closely what happens in Unify.match
match renv subst (Var v1) e2 = match_var renv subst v1 e2
match renv subst e1 (Var v2) -- Note [Expanding variables]
| not (inRnEnvR rn_env v2) -- Note [Do not expand locally-bound variables]
, Just e2' <- expandUnfolding_maybe (rv_unf renv v2')
= match (renv { rv_lcl = nukeRnEnvR rn_env }) subst e1 e2'
where
v2' = lookupRnInScope rn_env v2
rn_env = rv_lcl renv
-- Notice that we look up v2 in the in-scope set
-- See Note [Lookup in-scope]
-- No need to apply any renaming first (hence no rnOccR)
-- because of the not-inRnEnvR
match renv subst e1 (Let bind e2)
| -- pprTrace "match:Let" (vcat [ppr bind, ppr $ okToFloat (rv_lcl renv) (bindFreeVars bind)]) $
okToFloat (rv_lcl renv) (bindFreeVars bind) -- See Note [Matching lets]
= match (renv { rv_fltR = flt_subst' })
(subst { rs_binds = rs_binds subst . Let bind'
, rs_bndrs = extendVarSetList (rs_bndrs subst) new_bndrs })
e1 e2
where
flt_subst = addInScopeSet (rv_fltR renv) (rs_bndrs subst)
(flt_subst', bind') = substBind flt_subst bind
new_bndrs = bindersOf bind'
{- Disabled: see Note [Matching cases] below
match renv (tv_subst, id_subst, binds) e1
(Case scrut case_bndr ty [(con, alt_bndrs, rhs)])
| exprOkForSpeculation scrut -- See Note [Matching cases]
, okToFloat rn_env bndrs (exprFreeVars scrut)
= match (renv { me_env = rn_env' })
(tv_subst, id_subst, binds . case_wrap)
e1 rhs
where
rn_env = me_env renv
rn_env' = extendRnInScopeList rn_env bndrs
bndrs = case_bndr : alt_bndrs
case_wrap rhs' = Case scrut case_bndr ty [(con, alt_bndrs, rhs')]
-}
match _ subst (Lit lit1) (Lit lit2)
| lit1 == lit2
= Just subst
match renv subst (App f1 a1) (App f2 a2)
= do { subst' <- match renv subst f1 f2
; match renv subst' a1 a2 }
match renv subst (Lam x1 e1) e2
| Just (x2, e2, ts) <- exprIsLambda_maybe (rvInScopeEnv renv) e2
= let renv' = renv { rv_lcl = rnBndr2 (rv_lcl renv) x1 x2
, rv_fltR = delBndr (rv_fltR renv) x2 }
subst' = subst { rs_binds = rs_binds subst . flip (foldr mkTick) ts }
in match renv' subst' e1 e2
match renv subst (Case e1 x1 ty1 alts1) (Case e2 x2 ty2 alts2)
= do { subst1 <- match_ty renv subst ty1 ty2
; subst2 <- match renv subst1 e1 e2
; let renv' = rnMatchBndr2 renv subst x1 x2
; match_alts renv' subst2 alts1 alts2 -- Alts are both sorted
}
match renv subst (Type ty1) (Type ty2)
= match_ty renv subst ty1 ty2
match renv subst (Coercion co1) (Coercion co2)
= match_co renv subst co1 co2
match renv subst (Cast e1 co1) (Cast e2 co2)
= do { subst1 <- match_co renv subst co1 co2
; match renv subst1 e1 e2 }
-- Everything else fails
match _ _ _e1 _e2 = -- pprTrace "Failing at" ((text "e1:" <+> ppr _e1) $$ (text "e2:" <+> ppr _e2)) $
Nothing
-------------
match_co :: RuleMatchEnv
-> RuleSubst
-> Coercion
-> Coercion
-> Maybe RuleSubst
match_co renv subst co1 co2
| Just cv <- getCoVar_maybe co1
= match_var renv subst cv (Coercion co2)
| Just (ty1, r1) <- isReflCo_maybe co1
= do { (ty2, r2) <- isReflCo_maybe co2
; guard (r1 == r2)
; match_ty renv subst ty1 ty2 }
match_co renv subst co1 co2
| Just (tc1, cos1) <- splitTyConAppCo_maybe co1
= case splitTyConAppCo_maybe co2 of
Just (tc2, cos2)
| tc1 == tc2
-> match_cos renv subst cos1 cos2
_ -> Nothing
match_co _ _ _co1 _co2
-- Currently just deals with CoVarCo, TyConAppCo and Refl
#ifdef DEBUG
= pprTrace "match_co: needs more cases" (ppr _co1 $$ ppr _co2) Nothing
#else
= Nothing
#endif
match_cos :: RuleMatchEnv
-> RuleSubst
-> [Coercion]
-> [Coercion]
-> Maybe RuleSubst
match_cos renv subst (co1:cos1) (co2:cos2) =
do { subst' <- match_co renv subst co1 co2
; match_cos renv subst' cos1 cos2 }
match_cos _ subst [] [] = Just subst
match_cos _ _ cos1 cos2 = pprTrace "match_cos: not same length" (ppr cos1 $$ ppr cos2) Nothing
-------------
rnMatchBndr2 :: RuleMatchEnv -> RuleSubst -> Var -> Var -> RuleMatchEnv
rnMatchBndr2 renv subst x1 x2
= renv { rv_lcl = rnBndr2 rn_env x1 x2
, rv_fltR = delBndr (rv_fltR renv) x2 }
where
rn_env = addRnInScopeSet (rv_lcl renv) (rs_bndrs subst)
-- Typically this is a no-op, but it may matter if
-- there are some floated let-bindings
------------------------------------------
match_alts :: RuleMatchEnv
-> RuleSubst
-> [CoreAlt] -- Template
-> [CoreAlt] -- Target
-> Maybe RuleSubst
match_alts _ subst [] []
= return subst
match_alts renv subst ((c1,vs1,r1):alts1) ((c2,vs2,r2):alts2)
| c1 == c2
= do { subst1 <- match renv' subst r1 r2
; match_alts renv subst1 alts1 alts2 }
where
renv' = foldl mb renv (vs1 `zip` vs2)
mb renv (v1,v2) = rnMatchBndr2 renv subst v1 v2
match_alts _ _ _ _
= Nothing
------------------------------------------
okToFloat :: RnEnv2 -> VarSet -> Bool
okToFloat rn_env bind_fvs
= varSetAll not_captured bind_fvs
where
not_captured fv = not (inRnEnvR rn_env fv)
------------------------------------------
match_var :: RuleMatchEnv
-> RuleSubst
-> Var -- Template
-> CoreExpr -- Target
-> Maybe RuleSubst
match_var renv@(RV { rv_tmpls = tmpls, rv_lcl = rn_env, rv_fltR = flt_env })
subst v1 e2
| v1' `elemVarSet` tmpls
= match_tmpl_var renv subst v1' e2
| otherwise -- v1' is not a template variable; check for an exact match with e2
= case e2 of -- Remember, envR of rn_env is disjoint from rv_fltR
Var v2 | v1' == rnOccR rn_env v2
-> Just subst
| Var v2' <- lookupIdSubst (text "match_var") flt_env v2
, v1' == v2'
-> Just subst
_ -> Nothing
where
v1' = rnOccL rn_env v1
-- If the template is
-- forall x. f x (\x -> x) = ...
-- Then the x inside the lambda isn't the
-- template x, so we must rename first!
------------------------------------------
match_tmpl_var :: RuleMatchEnv
-> RuleSubst
-> Var -- Template
-> CoreExpr -- Target
-> Maybe RuleSubst
match_tmpl_var renv@(RV { rv_lcl = rn_env, rv_fltR = flt_env })
subst@(RS { rs_id_subst = id_subst, rs_bndrs = let_bndrs })
v1' e2
| any (inRnEnvR rn_env) (exprFreeVarsList e2)
= Nothing -- Occurs check failure
-- e.g. match forall a. (\x-> a x) against (\y. y y)
| Just e1' <- lookupVarEnv id_subst v1'
= if eqExpr (rnInScopeSet rn_env) e1' e2'
then Just subst
else Nothing
| otherwise
= -- Note [Matching variable types]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- However, we must match the *types*; e.g.
-- forall (c::Char->Int) (x::Char).
-- f (c x) = "RULE FIRED"
-- We must only match on args that have the right type
-- It's actually quite difficult to come up with an example that shows
-- you need type matching, esp since matching is left-to-right, so type
-- args get matched first. But it's possible (e.g. simplrun008) and
-- this is the Right Thing to do
do { subst' <- match_ty renv subst (idType v1') (exprType e2)
; return (subst' { rs_id_subst = id_subst' }) }
where
-- e2' is the result of applying flt_env to e2
e2' | isEmptyVarSet let_bndrs = e2
| otherwise = substExpr (text "match_tmpl_var") flt_env e2
id_subst' = extendVarEnv (rs_id_subst subst) v1' e2'
-- No further renaming to do on e2',
-- because no free var of e2' is in the rnEnvR of the envt
------------------------------------------
match_ty :: RuleMatchEnv
-> RuleSubst
-> Type -- Template
-> Type -- Target
-> Maybe RuleSubst
-- Matching Core types: use the matcher in TcType.
-- Notice that we treat newtypes as opaque. For example, suppose
-- we have a specialised version of a function at a newtype, say
-- newtype T = MkT Int
-- We only want to replace (f T) with f', not (f Int).
match_ty renv subst ty1 ty2
= do { tv_subst'
<- Unify.ruleMatchTyX (rv_tmpls renv) (rv_lcl renv) tv_subst ty1 ty2
; return (subst { rs_tv_subst = tv_subst' }) }
where
tv_subst = rs_tv_subst subst
{-
Note [Expanding variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is another Very Important rule: if the term being matched is a
variable, we expand it so long as its unfolding is "expandable". (Its
occurrence information is not necessarily up to date, so we don't use
it.) By "expandable" we mean a WHNF or a "constructor-like" application.
This is the key reason for "constructor-like" Ids. If we have
{-# NOINLINE [1] CONLIKE g #-}
{-# RULE f (g x) = h x #-}
then in the term
let v = g 3 in ....(f v)....
we want to make the rule fire, to replace (f v) with (h 3).
Note [Do not expand locally-bound variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Do *not* expand locally-bound variables, else there's a worry that the
unfolding might mention variables that are themselves renamed.
Example
case x of y { (p,q) -> ...y... }
Don't expand 'y' to (p,q) because p,q might themselves have been
renamed. Essentially we only expand unfoldings that are "outside"
the entire match.
Hence, (a) the guard (not (isLocallyBoundR v2))
(b) when we expand we nuke the renaming envt (nukeRnEnvR).
Note [Tick annotations in RULE matching]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We used to unconditionally look through Notes in both template and
expression being matched. This is actually illegal for counting or
cost-centre-scoped ticks, because we have no place to put them without
changing entry counts and/or costs. So now we just fail the match in
these cases.
On the other hand, where we are allowed to insert new cost into the
tick scope, we can float them upwards to the rule application site.
cf Note [Notes in call patterns] in SpecConstr
Note [Matching lets]
~~~~~~~~~~~~~~~~~~~~
Matching a let-expression. Consider
RULE forall x. f (g x) = <rhs>
and target expression
f (let { w=R } in g E))
Then we'd like the rule to match, to generate
let { w=R } in (\x. <rhs>) E
In effect, we want to float the let-binding outward, to enable
the match to happen. This is the WHOLE REASON for accumulating
bindings in the RuleSubst
We can only do this if the free variables of R are not bound by the
part of the target expression outside the let binding; e.g.
f (\v. let w = v+1 in g E)
Here we obviously cannot float the let-binding for w. Hence the
use of okToFloat.
There are a couple of tricky points.
(a) What if floating the binding captures a variable?
f (let v = x+1 in v) v
--> NOT!
let v = x+1 in f (x+1) v
(b) What if two non-nested let bindings bind the same variable?
f (let v = e1 in b1) (let v = e2 in b2)
--> NOT!
let v = e1 in let v = e2 in (f b2 b2)
See testsuite test "RuleFloatLet".
Our cunning plan is this:
* Along with the growing substitution for template variables
we maintain a growing set of floated let-bindings (rs_binds)
plus the set of variables thus bound.
* The RnEnv2 in the MatchEnv binds only the local binders
in the term (lambdas, case)
* When we encounter a let in the term to be matched, we
check that does not mention any locally bound (lambda, case)
variables. If so we fail
* We use CoreSubst.substBind to freshen the binding, using an
in-scope set that is the original in-scope variables plus the
rs_bndrs (currently floated let-bindings). So in (a) above
we'll freshen the 'v' binding; in (b) above we'll freshen
the *second* 'v' binding.
* We apply that freshening substitution, in a lexically-scoped
way to the term, although lazily; this is the rv_fltR field.
Note [Matching cases]
~~~~~~~~~~~~~~~~~~~~~
{- NOTE: This idea is currently disabled. It really only works if
the primops involved are OkForSpeculation, and, since
they have side effects readIntOfAddr and touch are not.
Maybe we'll get back to this later . -}
Consider
f (case readIntOffAddr# p# i# realWorld# of { (# s#, n# #) ->
case touch# fp s# of { _ ->
I# n# } } )
This happened in a tight loop generated by stream fusion that
Roman encountered. We'd like to treat this just like the let
case, because the primops concerned are ok-for-speculation.
That is, we'd like to behave as if it had been
case readIntOffAddr# p# i# realWorld# of { (# s#, n# #) ->
case touch# fp s# of { _ ->
f (I# n# } } )
Note [Lookup in-scope]
~~~~~~~~~~~~~~~~~~~~~~
Consider this example
foo :: Int -> Maybe Int -> Int
foo 0 (Just n) = n
foo m (Just n) = foo (m-n) (Just n)
SpecConstr sees this fragment:
case w_smT of wild_Xf [Just A] {
Data.Maybe.Nothing -> lvl_smf;
Data.Maybe.Just n_acT [Just S(L)] ->
case n_acT of wild1_ams [Just A] { GHC.Base.I# y_amr [Just L] ->
\$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
}};
and correctly generates the rule
RULES: "SC:$wfoo1" [0] __forall {y_amr [Just L] :: GHC.Prim.Int#
sc_snn :: GHC.Prim.Int#}
\$wfoo_smW sc_snn (Data.Maybe.Just @ GHC.Base.Int (GHC.Base.I# y_amr))
= \$s\$wfoo_sno y_amr sc_snn ;]
BUT we must ensure that this rule matches in the original function!
Note that the call to \$wfoo is
\$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
During matching we expand wild_Xf to (Just n_acT). But then we must also
expand n_acT to (I# y_amr). And we can only do that if we look up n_acT
in the in-scope set, because in wild_Xf's unfolding it won't have an unfolding
at all.
That is why the 'lookupRnInScope' call in the (Var v2) case of 'match'
is so important.
************************************************************************
* *
Rule-check the program
* *
************************************************************************
We want to know what sites have rules that could have fired but didn't.
This pass runs over the tree (without changing it) and reports such.
-}
-- | Report partial matches for rules beginning with the specified
-- string for the purposes of error reporting
ruleCheckProgram :: CompilerPhase -- ^ Rule activation test
-> String -- ^ Rule pattern
-> RuleEnv -- ^ Database of rules
-> CoreProgram -- ^ Bindings to check in
-> SDoc -- ^ Resulting check message
ruleCheckProgram phase rule_pat rule_base binds
| isEmptyBag results
= text "Rule check results: no rule application sites"
| otherwise
= vcat [text "Rule check results:",
line,
vcat [ p $$ line | p <- bagToList results ]
]
where
env = RuleCheckEnv { rc_is_active = isActive phase
, rc_id_unf = idUnfolding -- Not quite right
-- Should use activeUnfolding
, rc_pattern = rule_pat
, rc_rule_base = rule_base }
results = unionManyBags (map (ruleCheckBind env) binds)
line = text (replicate 20 '-')
data RuleCheckEnv = RuleCheckEnv {
rc_is_active :: Activation -> Bool,
rc_id_unf :: IdUnfoldingFun,
rc_pattern :: String,
rc_rule_base :: RuleEnv
}
ruleCheckBind :: RuleCheckEnv -> CoreBind -> Bag SDoc
-- The Bag returned has one SDoc for each call site found
ruleCheckBind env (NonRec _ r) = ruleCheck env r
ruleCheckBind env (Rec prs) = unionManyBags [ruleCheck env r | (_,r) <- prs]
ruleCheck :: RuleCheckEnv -> CoreExpr -> Bag SDoc
ruleCheck _ (Var _) = emptyBag
ruleCheck _ (Lit _) = emptyBag
ruleCheck _ (Type _) = emptyBag
ruleCheck _ (Coercion _) = emptyBag
ruleCheck env (App f a) = ruleCheckApp env (App f a) []
ruleCheck env (Tick _ e) = ruleCheck env e
ruleCheck env (Cast e _) = ruleCheck env e
ruleCheck env (Let bd e) = ruleCheckBind env bd `unionBags` ruleCheck env e
ruleCheck env (Lam _ e) = ruleCheck env e
ruleCheck env (Case e _ _ as) = ruleCheck env e `unionBags`
unionManyBags [ruleCheck env r | (_,_,r) <- as]
ruleCheckApp :: RuleCheckEnv -> Expr CoreBndr -> [Arg CoreBndr] -> Bag SDoc
ruleCheckApp env (App f a) as = ruleCheck env a `unionBags` ruleCheckApp env f (a:as)
ruleCheckApp env (Var f) as = ruleCheckFun env f as
ruleCheckApp env other _ = ruleCheck env other
ruleCheckFun :: RuleCheckEnv -> Id -> [CoreExpr] -> Bag SDoc
-- Produce a report for all rules matching the predicate
-- saying why it doesn't match the specified application
ruleCheckFun env fn args
| null name_match_rules = emptyBag
| otherwise = unitBag (ruleAppCheck_help env fn args name_match_rules)
where
name_match_rules = filter match (getRules (rc_rule_base env) fn)
match rule = (rc_pattern env) `isPrefixOf` unpackFS (ruleName rule)
ruleAppCheck_help :: RuleCheckEnv -> Id -> [CoreExpr] -> [CoreRule] -> SDoc
ruleAppCheck_help env fn args rules
= -- The rules match the pattern, so we want to print something
vcat [text "Expression:" <+> ppr (mkApps (Var fn) args),
vcat (map check_rule rules)]
where
n_args = length args
i_args = args `zip` [1::Int ..]
rough_args = map roughTopName args
check_rule rule = sdocWithDynFlags $ \dflags ->
rule_herald rule <> colon <+> rule_info dflags rule
rule_herald (BuiltinRule { ru_name = name })
= text "Builtin rule" <+> doubleQuotes (ftext name)
rule_herald (Rule { ru_name = name })
= text "Rule" <+> doubleQuotes (ftext name)
rule_info dflags rule
| Just _ <- matchRule dflags (emptyInScopeSet, rc_id_unf env)
noBlackList fn args rough_args rule
= text "matches (which is very peculiar!)"
rule_info _ (BuiltinRule {}) = text "does not match"
rule_info _ (Rule { ru_act = act,
ru_bndrs = rule_bndrs, ru_args = rule_args})
| not (rc_is_active env act) = text "active only in later phase"
| n_args < n_rule_args = text "too few arguments"
| n_mismatches == n_rule_args = text "no arguments match"
| n_mismatches == 0 = text "all arguments match (considered individually), but rule as a whole does not"
| otherwise = text "arguments" <+> ppr mismatches <+> text "do not match (1-indexing)"
where
n_rule_args = length rule_args
n_mismatches = length mismatches
mismatches = [i | (rule_arg, (arg,i)) <- rule_args `zip` i_args,
not (isJust (match_fn rule_arg arg))]
lhs_fvs = exprsFreeVars rule_args -- Includes template tyvars
match_fn rule_arg arg = match renv emptyRuleSubst rule_arg arg
where
in_scope = mkInScopeSet (lhs_fvs `unionVarSet` exprFreeVars arg)
renv = RV { rv_lcl = mkRnEnv2 in_scope
, rv_tmpls = mkVarSet rule_bndrs
, rv_fltR = mkEmptySubst in_scope
, rv_unf = rc_id_unf env }
|
vikraman/ghc
|
compiler/specialise/Rules.hs
|
bsd-3-clause
| 48,316 | 0 | 17 | 13,565 | 7,151 | 3,806 | 3,345 | 487 | 5 |
{- Provides the CORDIC algorithm.
- Fixed-point math is used throughout, with bit shifting used as per the
- original algorithm.
- Two multiplications are performed as the final step to scale the result.
-}
module CORDIC
(
cordic
) where
import Data.Bits ( shift )
import Numeric.Fixed
import Util
-- |(index, remainder, (x, y)) used in fold
type State = (Int, Fixed, (Fixed, Fixed))
-- |Initialise (x, y) and index, execute fold, scale result
-- |Parameter `a` is the angle in radians, `n` is the number of iterations
-- |The result is a pair ( cos a, sin a )
cordic :: Fixed -> Int -> (Fixed, Fixed)
cordic a n = let
initial = ( 0, a, (1, 0) )
(i, _, (c, s)) = foldl step initial $ take n alistF
k = klistF !! i
in ( k * c, k * s )
-- |Core of the algorithm - generates next (x, y) from current
step :: State -> Fixed -> State
step (i, a, v) d
| a > 0 = ( i', a - d, mult i 1 v )
| a < 0 = ( i', a + d, mult i (-1) v )
| otherwise = ( i', a, v )
where i' = i + 1
-- |Multiplies 'vector' (x, y) by i'th rotation matrix
mult :: Int -> Fixed -> (Fixed, Fixed) -> (Fixed, Fixed)
mult i sign (x, y) = let
sign' = if sign < 0
then negate
else id
x' = x - sign' ( shiftFixed y ( -i ))
y' = sign' ( shiftFixed x ( -i )) + y
in (x', y')
-- |Shift function which handles wrapping/unwrapping fixed-point values
shiftFixed :: Fixed -> Int -> Fixed
shiftFixed n i = Fixed ( shift ( getFixed n ) i )
|
chronon-io/cordic
|
src/CORDIC.hs
|
bsd-3-clause
| 1,456 | 0 | 14 | 374 | 464 | 260 | 204 | 29 | 2 |
module WASH.CGI.CookieIO (decodeCookie, encodeCookie, putCookies) where
import System.IO
import WASH.CGI.CGIMonad
import qualified WASH.CGI.Debug as Debug
import WASH.CGI.RawCGITypes
import qualified WASH.Utility.URLCoding as URLCoding
decodeCookie :: (String, String) -> (String, (Maybe String, Maybe String))
encodeCookie :: (String, (Maybe String, Maybe String)) -> (String, String)
encodeCookie (k, (v, mexp)) =
(URLCoding.encode k,
case v of
Just v' -> URLCoding.encode v' ++
(case mexp of
Nothing -> ""
Just exp -> "; expires=" ++ exp)
Nothing -> "deleted; expires=Thu, 01-Jan-1970 00:00:00 GMT")
decodeCookie (k, v) = (URLCoding.decode k, (Just (URLCoding.decode v), Nothing))
putCookies :: CGIState -> IO ()
putCookies cgistate =
let cookies = cookiesToSend cgistate
cm = cookieMap cgistate
h = cgiHandle (cgiInfo cgistate)
sendCookie name = case lookup name cm of
Nothing ->
return ()
Just value ->
let (encName, encValue) = encodeCookie (name, value) in
do hPutStr h "Set-Cookie: "
hPutStr h encName
hPutStr h "="
hPutStr h encValue
hPutStr h ";\n"
in do printCookies cm cookies h
Debug.logOutput "OLD" (printCookies cm cookies)
printCookies :: [(String,(Maybe String, Maybe String))] -> [String] -> Handle -> IO ()
printCookies cm cookies h =
let sendCookie name = case lookup name cm of
Nothing ->
return ()
Just value ->
let (encName, encValue) = encodeCookie (name, value) in
do hPutStr h "Set-Cookie: "
hPutStr h encName
hPutStr h "="
hPutStr h encValue
hPutStr h ";\n"
in mapM_ sendCookie cookies
|
nh2/WashNGo
|
WASH/CGI/CookieIO.hs
|
bsd-3-clause
| 1,664 | 12 | 14 | 376 | 612 | 315 | 297 | 47 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module PackageTests.DeterministicAr.Check where
import Control.Monad
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.Char (isSpace)
import Data.List
import Data.Traversable
import PackageTests.PackageTester
import System.Exit
import System.FilePath
import System.IO
import Test.HUnit (Assertion, Test (TestCase), assertFailure)
-- Perhaps these should live in PackageTester.
-- For a polymorphic @IO a@ rather than @Assertion = IO ()@.
assertFailure' :: String -> IO a
assertFailure' msg = assertFailure msg >> return {-unpossible!-}undefined
ghcPkg_field :: String -> String -> FilePath -> IO [FilePath]
ghcPkg_field libraryName fieldName ghcPkgPath = do
(cmd, exitCode, raw) <- run Nothing ghcPkgPath
["--user", "field", libraryName, fieldName]
let output = filter ('\r' /=) raw -- Windows
-- copypasta of PackageTester.requireSuccess
unless (exitCode == ExitSuccess) . assertFailure $
"Command " ++ cmd ++ " failed.\n" ++ "output: " ++ output
let prefix = fieldName ++ ": "
case traverse (stripPrefix prefix) (lines output) of
Nothing -> assertFailure' $ "Command " ++ cmd ++ " failed: expected "
++ show prefix ++ " prefix on every line.\noutput: " ++ output
Just fields -> return fields
ghcPkg_field1 :: String -> String -> FilePath -> IO FilePath
ghcPkg_field1 libraryName fieldName ghcPkgPath = do
fields <- ghcPkg_field libraryName fieldName ghcPkgPath
case fields of
[field] -> return field
_ -> assertFailure' $ "Command ghc-pkg field failed: "
++ "output not a single line.\noutput: " ++ show fields
------------------------------------------------------------------------
this :: String
this = "DeterministicAr"
suite :: FilePath -> FilePath -> Test
suite ghcPath ghcPkgPath = TestCase $ do
let dir = "PackageTests" </> this
let spec = PackageSpec dir []
unregister this ghcPkgPath
iResult <- cabal_install spec ghcPath
assertInstallSucceeded iResult
let distBuild = dir </> "dist" </> "build"
libdir <- ghcPkg_field1 this "library-dirs" ghcPkgPath
mapM_ checkMetadata [distBuild, libdir]
unregister this ghcPkgPath
-- Almost a copypasta of Distribution.Simple.Program.Ar.wipeMetadata
checkMetadata :: FilePath -> Assertion
checkMetadata dir = withBinaryFile path ReadMode $ \ h -> do
hFileSize h >>= checkArchive h
where
path = dir </> "libHS" ++ this ++ "-0.a"
checkError msg = assertFailure' $
"PackageTests.DeterministicAr.checkMetadata: " ++ msg ++
" in " ++ path
archLF = "!<arch>\x0a" -- global magic, 8 bytes
x60LF = "\x60\x0a" -- header magic, 2 bytes
metadata = BS.concat
[ "0 " -- mtime, 12 bytes
, "0 " -- UID, 6 bytes
, "0 " -- GID, 6 bytes
, "0644 " -- mode, 8 bytes
]
headerSize = 60
-- http://en.wikipedia.org/wiki/Ar_(Unix)#File_format_details
checkArchive :: Handle -> Integer -> IO ()
checkArchive h archiveSize = do
global <- BS.hGet h (BS.length archLF)
unless (global == archLF) $ checkError "Bad global header"
checkHeader (toInteger $ BS.length archLF)
where
checkHeader :: Integer -> IO ()
checkHeader offset = case compare offset archiveSize of
EQ -> return ()
GT -> checkError (atOffset "Archive truncated")
LT -> do
header <- BS.hGet h headerSize
unless (BS.length header == headerSize) $
checkError (atOffset "Short header")
let magic = BS.drop 58 header
unless (magic == x60LF) . checkError . atOffset $
"Bad magic " ++ show magic ++ " in header"
unless (metadata == BS.take 32 (BS.drop 16 header))
. checkError . atOffset $ "Metadata has changed"
let size = BS.take 10 $ BS.drop 48 header
objSize <- case reads (BS8.unpack size) of
[(n, s)] | all isSpace s -> return n
_ -> checkError (atOffset "Bad file size in header")
let nextHeader = offset + toInteger headerSize +
-- Odd objects are padded with an extra '\x0a'
if odd objSize then objSize + 1 else objSize
hSeek h AbsoluteSeek nextHeader
checkHeader nextHeader
where
atOffset msg = msg ++ " at offset " ++ show offset
|
fpco/cabal
|
Cabal/tests/PackageTests/DeterministicAr/Check.hs
|
bsd-3-clause
| 4,594 | 0 | 23 | 1,281 | 1,152 | 575 | 577 | 89 | 5 |
module RPN(
RPN,
arg, intVal, boolVal, funcall, appl,
jump, jumpFalse, label,
toCCode) where
import CCodeGen
data RPN
= Arg Int
| IntVal Int
| Funcall String Int
| Appl
| BoolVal Bool
| Jump Int
| JumpFalse Int
| Label Int
deriving (Eq, Ord, Show)
arg = Arg
intVal = IntVal
boolVal = BoolVal
funcall = Funcall
appl = Appl
jump = Jump
jumpFalse = JumpFalse
label = Label
toCCode :: RPN -> CStatement
toCCode (Arg argNum) = pushArgOnStack argNum
toCCode (IntVal n) = pushIntOnStack n
toCCode (BoolVal b) = pushBoolOnStack b
toCCode (Funcall name arity) = pushFuncOnStack name arity
toCCode Appl = bind
toCCode (Label n) = makeLabel n
toCCode (Jump n) = makeJump n
toCCode (JumpFalse n) = makeJumpFalse n
|
dillonhuff/IntLang
|
src/RPN.hs
|
bsd-3-clause
| 767 | 0 | 7 | 187 | 278 | 151 | 127 | 33 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Layout
( baseLayout
, renderWithLayout
, renderWithBaseLayout
) where
import Data.Text
import Snap
import Snap.Blaze (blaze)
import Snap.Snaplet.Auth
import Snap.Snaplet.Auth.Backends.PostgresqlSimple ()
import Text.Blaze.Html (Html,
preEscapedText)
import Text.Hamlet (shamlet)
import Application
--import User.Query (userDBView)
renderWithLayout :: Html -> Handler App (AuthManager App) ()
renderWithLayout content = do
user <- currentUser
case user of
Nothing -> redirect "/login"
Just u -> do
let l = userLogin u
blaze . (appLayout l) $ content
renderWithBaseLayout :: Html -> Handler App (AuthManager App) ()
renderWithBaseLayout content = blaze . baseLayout $ content
appLayout :: Text -> Html -> Html
appLayout _ content = baseLayout $ [shamlet|
<div class="container" style="max-width: none">
#{content}
|]
ticketFormJS :: Html
ticketFormJS = preEscapedText "$(document).ready(function() {$('#due-date').datepicker({showOn: 'button', buttonText: ''});})"
baseLayout :: Html -> Html
baseLayout content = [shamlet|
<!doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Features</title>
<meta name="description" content="Content Queue Application">
<script src="https://code.jquery.com/jquery-2.2.0.min.js">
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.2.0/parsley.min.js">
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js">
<script src="/static/prototype.js">
<script src="/static/form-to-obj.min.js">
<script> #{ticketFormJS}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="/static/prototype.css">
<link rel="stylesheet" href="http://parsleyjs.org/src/parsley.css">
<body>
#{content}
|]
|
ExternalReality/features
|
src/Layout.hs
|
bsd-3-clause
| 2,399 | 0 | 15 | 572 | 278 | 154 | 124 | 31 | 2 |
{-# LANGUAGE TemplateHaskell #-}
import Data.Monoid
import Options.Applicative
import Options.Applicative.TH
newtype Number = Number Int
deriving (Show, Read)
$(genOpts ''Number)
main :: IO ()
main = do
x <- execParser optparseNumber
print x
|
tranma/optparse-th
|
test/cases/arg-auto/arg-auto.hs
|
bsd-3-clause
| 252 | 1 | 8 | 43 | 80 | 41 | 39 | 11 | 1 |
-----------------------------------------------------------------------------
--
-- Module : Utils
-- Copyright :
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability :
-- Portability :
--
-- | Utility functions and data types
--
-----------------------------------------------------------------------------
module Utils (
ServerID,
Server(..),
Proposal(..),
ServerState(..),
MessageType,
Message(..),
broadcast,
send,
parseHostPort,
parseMessage,
majority,
saveServer
) where
import Network (PortID(..), Socket,PortNumber)
import System.IO (hSetBuffering, hGetLine, hPutStrLn, BufferMode(..), Handle)
import Control.Concurrent.MVar
import Data.List.Split
-- | ServerID alias to String
type ServerID = String
-- | Server data type
data Server = Server {
serverID :: ServerID,
serverHandle :: Handle,
hostName :: String,
portNumber :: PortNumber
}
-- | Proposal data type
data Proposal = Proposal {
proposalID :: ServerID,
proposalValue :: Int
}
-- | Server state data type
data ServerState = ServerState {
localID :: ServerID,
proposalNumber :: Int,
highestProposal :: Proposal,
localHost :: String,
localPort :: PortNumber,
prepareQuorum :: Int,
acceptQuorum :: Int,
serverList :: [Server],
learnedValues :: [Int]
}
-- | MessageType alias to string
type MessageType = String
-- | Message data type
data Message = Message{
messageType :: MessageType,
messageId :: ServerID,
messageValue :: Int
}
-- | Parses a string in the form "host:port" into a tuple (host, port)
parseHostPort :: String -> (String, String)
parseHostPort hostPort = (\(host : port) ->
(host, head port)) $ splitOn ":" hostPort
-- | Parses a String into a Message
parseMessage :: ServerID -> String -> Message
parseMessage id text = (\(mType : mValue) ->
Message {
messageType = mType,
messageId = id,
messageValue = fromIntegral (read $ head mValue :: Int)
}) $ splitOn ":" text
-- | Calculates the majority of the server set
majority :: ServerState -> Int
majority state = length (serverList state) `quot` 2 + 1
-- | Saves a server into the list of servers
saveServer :: ServerState -> Server -> ServerState
saveServer state server = do
let port = portNumber server
let servers = serverList state
let isConnected = (length servers > 0) && (and $ map (\x -> portNumber x == port) servers)
case not isConnected of
True -> state { serverList = server : servers}
False -> state
-- | Sends a message to a client
send :: String -> Handle -> IO ()
send msg handle = hPutStrLn handle msg
-- | Sends a message to all the servers
broadcast :: ServerState -> String -> IO ()
broadcast state msg = broadcastServers msg $ serverList state
-- | Sends a message to all the servers
broadcastServers :: String -> [Server] -> IO ()
broadcastServers msg servers = mapM_ (send msg . serverHandle) servers
|
michelrivas/paxos
|
src/Utils.hs
|
bsd-3-clause
| 3,019 | 0 | 17 | 667 | 725 | 424 | 301 | 67 | 2 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE Trustworthy #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Category
-- Copyright : (c) Ashley Yakeley 2007
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
-- http://ghc.haskell.org/trac/ghc/ticket/1773
module Control.Category where
import qualified GHC.Base (id,(.))
import Data.Type.Coercion
import Data.Type.Equality
import GHC.Prim (coerce)
infixr 9 .
infixr 1 >>>, <<<
-- | A class for categories.
-- id and (.) must form a monoid.
class Category cat where
-- | the identity morphism
id :: cat a a
-- | morphism composition
(.) :: cat b c -> cat a b -> cat a c
{-# RULES
"identity/left" forall p .
id . p = p
"identity/right" forall p .
p . id = p
"association" forall p q r .
(p . q) . r = p . (q . r)
#-}
instance Category (->) where
id = GHC.Base.id
(.) = (GHC.Base..)
instance Category (:~:) where
id = Refl
Refl . Refl = Refl
instance Category Coercion where
id = Coercion
(.) Coercion = coerce
-- | Right-to-left composition
(<<<) :: Category cat => cat b c -> cat a b -> cat a c
(<<<) = (.)
-- | Left-to-right composition
(>>>) :: Category cat => cat a b -> cat b c -> cat a c
f >>> g = g . f
|
jstolarek/ghc
|
libraries/base/Control/Category.hs
|
bsd-3-clause
| 1,507 | 0 | 9 | 377 | 305 | 179 | 126 | 34 | 1 |
module Data.AS3.AST.Prims (
between_braces
, between_parens
, between_brackets
, semi
, ss
, comma
, plusfold
, csv
, dots
, sym
, symR
) where
import Data.AS3.AST.Def
import Data.AS3.AST.ThirdParty
import Data.List (intersperse)
import Text.Parsec
between_braces :: As3Parser a -> As3Parser a
between_braces = between
(spaces *> string "{" <* spaces)
(spaces *> string "}" <* spaces)
between_parens :: As3Parser a -> As3Parser a
between_parens = between
(spaces *> string "(" <* spaces)
(spaces *> string ")" <* spaces)
between_brackets :: As3Parser a -> As3Parser a
between_brackets = between
(spaces *> string "[" <* spaces)
(spaces *> string "]" <* spaces)
semi :: As3Parser Char
semi = tok $ char ';'
ss :: As3Parser String
ss = many $ char ' '
comma :: As3Parser Char
comma = tok $ char ','
plusfold :: As3Parser String -> String -> As3Parser String
plusfold acc str = acc `parserPlus` (try $ string str)
csv :: As3Parser a -> As3Parser [a]
csv a = a `sepBy` (ss *> char ',' <* ss)
dots :: [String] -> As3Parser String
dots = return . concat . intersperse "."
sym :: (Show a) => a -> As3Parser String
sym = string . show
symR :: (Show a) => a -> As3Parser a
symR a = sym a >> return a
|
phylake/AS3-AST
|
Data/AS3/AST/Prims.hs
|
bsd-3-clause
| 1,257 | 0 | 9 | 280 | 482 | 254 | 228 | 44 | 1 |
module GameLogic where
import Domain
import Coordinate
import Data.Maybe
import Debug.Trace
import Vector
type Line = (Coordinates, Coordinates)
data PaddleDefinition = PaddleDefinition { y :: Float, height :: Float, gradient :: Float -> Coordinates }
data CalculationResults = CalculationResults { direction :: Float, wayPoints :: [Coordinates] }
calculateDirection :: State -> CalculationResults
calculateDirection state = directionToTake
--Debug.Trace.trace ("DISTANCE: " ++ show ballDistance ++ ", TIME TO HIT:" ++ (show $ timeTakenFor ballDistance v) ++ ", CAN WE MAKES IT?" ++ (show canWeMakeIt)) $ directionToTake
where history = boardHistory state
board = head history
current = leftPaddleMiddleY board
targetOffset = negate $ ((ballAngle coords) * (paddleH board)) / 2.0
(uncorrectedTarget, coords) = ballRouteToOurEnd history
targetToSaveBall = clampTargetPos board $ uncorrectedTarget + targetOffset
trajectoryFromBall = reverse $ (ballCoordinates board) : reverse coords
ballDistance = trajectoryLength trajectoryFromBall
v = ballVelocity history
canWeMakeIt = canWeEasilyMakeItToSave board current targetToSaveBall (timeTakenFor ballDistance v)
directionToSaveBall = chooseDirection current (targetToSaveBall, coords) board
directionToTake
| canWeMakeIt = CalculationResults (trollDirection state) (wayPoints directionToSaveBall)
| otherwise = directionToSaveBall
clampTargetPos :: Board -> Float -> Float
clampTargetPos board yPos
| yPos < top = top
| yPos > bottom = bottom
| otherwise = yPos
where ph = paddleH board
half_ph = ph / 2.0
bh = boardHeight board
top = half_ph
bottom = bh - half_ph
ballVelocity :: BoardHistory -> Velocity
ballVelocity (s1:s2:xs) =
vectorTo newCoordinates oldCoordinates
where newCoordinates = ballCoordinates s1
oldCoordinates = ballCoordinates s2
ballVelocity _ = Coordinates 0.0 0.0
ballAngle :: [Coordinates] -> Float
ballAngle (p1:p2:ps) = ballAngleFromVelocity v
where v = normalizedVector $ vectorTo p1 p2
ballAngle _ = 0.0
ballAngleFromVelocity :: Velocity -> Float
ballAngleFromVelocity v = (asin $ dotProduct nv ourPaddleVector) * 2.0 / pi
where nv = normalizedVector v
ourPaddleVector = Coordinates 0.0 1.0
lineLineIntersection :: Line -> Line -> (Float, Float)
lineLineIntersection (base1, direction1) (base2, direction2) =
(s, t)
where s = (dotProduct (base2 - base1) perDirection2) / (dotProduct direction1 perDirection2)
t = (dotProduct (base1 - base2) perDirection1) / (dotProduct direction2 perDirection1)
perDirection2 = perpendicular direction2
perDirection1 = perpendicular direction1
trajectoryLength :: [Coordinates] -> Float
trajectoryLength (p:[]) = 0.0
trajectoryLength (p1:p2:ps) = (vectorLength $ vectorTo p2 p1) + trajectoryLength ps
trajectoryLength _ = 0.0
timeTakenFor :: Float -> Velocity -> Float
timeTakenFor l v = l / (velocityLength)
where velocityLength = vectorLength v
chooseDirection :: Float -> (Float, [Coordinates]) -> Board -> CalculationResults
chooseDirection currentY (targetY, coords) board
| difference < (-threshold) = CalculationResults (-1.0) coords
| difference > threshold = CalculationResults 1.0 coords
| otherwise = CalculationResults 0.0 coords
where difference = targetY - currentY
threshold = (paddleH board) / 8.0
canWeEasilyMakeItToSave :: Board -> Float -> Float -> Float -> Bool
canWeEasilyMakeItToSave board ourPaddleY nextOurHitY timeToImpact
| ballIsFarAway = abs(ourPaddleY - nextOurHitY) < (timeToImpact * 0.6)
| otherwise = False
where ballIsFarAway = (distanceToUs board > (3 * paddleH board))
trollDirection :: State -> Float
trollDirection state
| ((length $ missiles state) >= 1) = directionToOtherPaddle
| otherwise = -0.1 * directionToOtherPaddle
where board = head $ boardHistory state
ourPaddleY = leftPaddleMiddleY board
otherPaddleY = rightPaddleMiddleY board
directionToOtherPaddle
| ourPaddleY < otherPaddleY = 1.0
| ourPaddleY > otherPaddleY = -1.0
| otherwise = 0.0
ballRouteToOurEnd :: BoardHistory -> (Float, [Coordinates])
ballRouteToOurEnd (b:bs) =
(Coordinate.y $ head hitPoints, hitPoints)
where p = ballCoordinates b
history = (b:bs)
v = ballVelocity history
hitPoints = traceBallToOurPaddle p v b []
ballRouteToOurEnd [] = (0.0, [])
traceBallToOurPaddle :: Coordinates -> Velocity -> Board -> [Coordinates] -> [Coordinates]
traceBallToOurPaddle p v board hitPoints
| ballStopped v = p : hitPoints
| gameEnded p board = (deflectFromEndWall v) : hitPoints
| isJust ourPaddleHit = p' : hitPoints
| otherwise = traceBallToOurPaddle p' v' board (p' : hitPoints)
where hitTests = [hitsOurPaddle, hitsOpponentPaddle, hitsCeiling, hitsFloor]
possibleHits = map (\ht -> ht p v board) hitTests
hits = catMaybes possibleHits
ourPaddleHit = head possibleHits
(v',p') = fromMaybe (v,p) $ listToMaybe hits
ballStopped :: Velocity -> Bool
ballStopped (Coordinates vx vy) = (vx == 0.0) || (vy == 0.0)
gameEnded :: Coordinates -> Board -> Bool
gameEnded c b = weWon c b || weLost c b
where weLost (Coordinates x y) board = x < leftWallX board
weWon (Coordinates x y) board = x > rightWallX board
hitsOurPaddle :: Coordinates -> Velocity -> Board -> Maybe (Velocity,Coordinates)
hitsOurPaddle p v board =
hitsVerticalEdge p v board edgeX paddle
where edgeX = leftWallX board
paddle = PaddleDefinition (Domain.y $ left board) (paddleH board) (paddleGradient)
paddleGradient = (\x -> Coordinates (1.0) (x / 200.0))
hitsOpponentPaddle :: Coordinates -> Velocity -> Board -> Maybe (Velocity,Coordinates)
hitsOpponentPaddle p v board =
hitsVerticalEdge p v board edgeX paddle
where edgeX = rightWallX board
paddle = PaddleDefinition (Domain.y $ right board) (paddleH board) (paddleGradient)
paddleGradient = (\x -> Coordinates (-1.0) (x / 200.0))
hitsCeiling :: Coordinates -> Velocity -> Board -> Maybe (Velocity,Coordinates)
hitsCeiling p v board =
hitsHorizontalEdge p v board edgeY
where edgeY = 0.0
hitsFloor :: Coordinates -> Velocity -> Board -> Maybe (Velocity,Coordinates)
hitsFloor p v board =
hitsHorizontalEdge p v board edgeY
where edgeY = boardHeight board
hitsVerticalEdge :: Coordinates -> Velocity -> Board -> Float -> PaddleDefinition -> Maybe (Velocity,Coordinates)
hitsVerticalEdge p (Coordinates 0.0 y) board edgeX paddle = Nothing
hitsVerticalEdge p v board edgeX paddle =
case hit of
Just p' -> Just (deflectFromVerticalEdge v paddle p', p')
_ -> Nothing
where edge = ((Coordinates edgeX 0.0), (Coordinates 0.0 (boardHeight board)))
hit = hitsEdge p v edge
hitsHorizontalEdge :: Coordinates -> Velocity -> Board -> Float -> Maybe (Velocity,Coordinates)
hitsHorizontalEdge p (Coordinates x 0.0) board edgeY = Nothing
hitsHorizontalEdge p v board edgeY =
case hit of
Just p' -> Just(deflectFromWall v, p')
_ -> Nothing
where edge = ((Coordinates (leftWallX board) edgeY), (Coordinates edgeLength 0.0))
edgeLength = (rightWallX board) - (leftWallX board)
hit = hitsEdge p v edge
hitsEdge :: Coordinates -> Velocity -> Line -> Maybe Coordinates
hitsEdge p v edge
| timeToImpact > 0.0 && intersection > 0.0 && intersection < 1.0 = Just p'
| otherwise = Nothing
where (timeToImpact, intersection) = lineLineIntersection (p, v) edge
(edgeOrigin, edgeDirection) = edge
p' = edgeOrigin + (edgeDirection `vscale` intersection)
deflectFromVerticalEdge :: Velocity -> PaddleDefinition -> Coordinates -> Velocity
deflectFromVerticalEdge (Coordinates vx vy) (PaddleDefinition paddleY paddleHeight paddleGradient) (Coordinates px py)
| isWithinPaddleBounds py = deflectFromPaddle (Coordinates vx vy) (PaddleDefinition paddleY paddleHeight paddleGradient) (Coordinates px py)
| otherwise = deflectFromEndWall (Coordinates vx vy)
where isWithinPaddleBounds = (\y -> y >= paddleY && y <= (paddleY + paddleHeight))
deflectFromPaddle (Coordinates vx vy) (PaddleDefinition paddleY paddleHeight paddleGradient) (Coordinates px py) =
setVectorLength (rotateVector paddleGradientAtImpact angleDiff) (vectorLength (Coordinates vx vy))
where paddleGradientAtImpact = paddleGradient (py - paddleMiddleY)
paddleMiddleY = paddleY + (paddleHeight / 2)
angleDiff = vectorAngle paddleGradientAtImpact - vectorAngle (Coordinates vx vy)
deflectFromEndWall :: Velocity -> Velocity
deflectFromEndWall (Coordinates vx vy) = Coordinates (-vx) vy
deflectFromWall :: Velocity -> Velocity
deflectFromWall (Coordinates vx vy) = Coordinates vx (-vy)
withinBoardHeight :: Float -> Board -> Bool
withinBoardHeight yPos board = yPos >= 0.0 && yPos <= (boardHeight board)
withinGameAreaWidth :: Float -> Board -> Bool
withinGameAreaWidth xPos board = xPos >= (leftWallX board) && xPos <= (rightWallX board)
|
timorantalaiho/pong11
|
src/GameLogic.hs
|
bsd-3-clause
| 9,113 | 0 | 12 | 1,788 | 2,860 | 1,477 | 1,383 | 173 | 2 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.BaseInstance
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ARB/base_instance.txt ARB_base_instance> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.BaseInstance (
-- * Functions
glDrawArraysInstancedBaseInstance,
glDrawElementsInstancedBaseInstance,
glDrawElementsInstancedBaseVertexBaseInstance
) where
import Graphics.Rendering.OpenGL.Raw.Functions
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/ARB/BaseInstance.hs
|
bsd-3-clause
| 757 | 0 | 4 | 84 | 43 | 35 | 8 | 5 | 0 |
module Options where
import Data.List (foldl')
import System.Console.GetOpt
import System.Environment
import Paths_vty_hangman_helper
data Options = Options
{ scrubOption :: Bool
, wordlistFile :: FilePath
}
defaultOptions :: IO Options
defaultOptions = do
file <- getDataFileName "wordlist1.txt"
return Options
{ scrubOption = False
, wordlistFile = file
}
setScrub :: Bool -> Options -> Options
setScrub x o = o { scrubOption = x }
setWordlist :: FilePath -> Options -> Options
setWordlist fp o = o { wordlistFile = fp }
options :: [OptDescr (Options -> Options)]
options =
[ Option ['s'] ["scrub"] (NoArg (setScrub True)) "Scrub word"
, Option ['f'] ["wordlist"] (ReqArg setWordlist "Filename") "Word list"
]
parseOptions :: IO (Options, String)
parseOptions = do
args <- getArgs
opts <- defaultOptions
case getOpt Permute options args of
(optFuns, [w], [] ) -> return (foldl' (\x f -> f x) opts optFuns, w)
(_, [] , [] ) -> fail "Initial word not specified"
(_, _ , [] ) -> fail "Too many arguments"
(_, _ , errs) -> fail (unlines errs)
|
glguy/vty-hangman-helper
|
Options.hs
|
bsd-3-clause
| 1,146 | 0 | 15 | 277 | 395 | 216 | 179 | 31 | 4 |
----------- Streams --------------
data Stream = Stream [String] | Stream [Stream]
--------- Transitions --------------
data Transitions = Transitions [Streams] | Transitions [Paths]
children :: Stream -> Transitions
leaves :: Stream -> Transitions
tilda :: Stream -> String -> Stream -- or Path(?)
-- ~ infix
--"Path" ?
-- subtract?
cross :: Stream -> Stream -> Stream
---------- Constraints -------------
data Constraints = Constraint ParserConstraint | Constraints [ParserConstraint]
-- Stream & Transition need to be in a type-class
maxInARow :: Int -> Stream -> ParserConstraint
count :: (Count, Count) -> Stream -> ParserConstraint
avoid :: Stream -> ParserConstraint
include :: Stream -> ParserConstraint
noConstraints :: ParserConstraints
noConstraints = []
data Count = Count Int | Count None
---------- Design ------------
----------- Blocks ------------ # fully crossed constraints not good enough!!!
data Block = Block BlockContents Constraints
data BlockContents = BlockContents
sample :: Int -> Stream -> BlockContents
fullyCross :: Stream -> BlockContents
exactly :: Stream -> Block
sequence :: [Blocks] -> Constraints -> Block
randomWithReplacement :: [Blocks] -> Constraints -> Block
permutations :: [Blocks] -> Constraints -> Block
repeat :: Int -> Block -> Constraints -> Block
mix :: [Blocks] -> Constraints -> Block
-------- Experiment ---------
-- maybe this is is the "run" function? Not clear yet.
experiment :: Block
|
anniecherk/pyschocnf
|
notes/parser_interface/haskell-frontend-spec.hs
|
bsd-3-clause
| 1,486 | 0 | 7 | 251 | 328 | 189 | 139 | 25 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilyDependencies #-}
{-# LANGUAGE UndecidableInstances #-}
module Glazier.React.ReactCont where
import Control.Applicative
import Control.Monad.Cont
import Control.Monad.Delegate
import Control.Monad.Environ
import Control.Monad.ST.Class
import Control.Monad.State.Lazy as Lazy
import Control.Monad.Trans.ACont
import Control.Monad.Trans.Maybe
import Data.STRef
import Glazier.Command
import Glazier.React.Markup
type ReactCont' c = AContT () -- 'MonadDelegate', 'MonadDischarge'
(MaybeT -- 'Alternative'
-- State monads must be inside ContT to be a 'MonadDelegate'
(Lazy.StateT Markup -- 'PutMarkups'
(ProgramT c IO -- 'MonadCodify', 'MonadProgram', 'MonadST', 'MonadIO'
)))
newtype ReactCont c a = ReactCont { unReactCont :: ReactCont' c a }
deriving
( Functor
, Applicative
, Alternative
, MonadPlus
, Monad
, MonadIO
, MonadST
, MonadCont
, MonadProgram
, MonadPut' Markup
, MonadDelegate
)
deriving via (ReactCont' c) instance (Cmd' IO c, Cmd' [] c) => MonadCodify (ReactCont c)
type instance Command (ReactCont c) = c
-- | This instance 'MonadDischarge' ensures the @()@ is fired
-- after the 'MonadProgram' commands are evaluated.
instance (Cmd' IO c, Cmd' [] c) => MonadDischarge (ReactCont c) where
discharge (ReactCont (AContT g)) f = do
-- Warning, the effects (Markup, ReactPath) inside ContT
-- and above ProgramT are not the latest version after discharge,
-- since 'codify'ed handlers are evaluated later.
-- So we need to save the latest state (Markup and ReactPath)
-- from running the 'codify'ed handlers.
ok <- liftST $ newSTRef True
mlv <- getEnv' @Markup >>= liftST . newSTRef
let f' a = do
f a <|> resetGuard
liftST $ writeSTRef ok True
getEnv' @Markup >>= liftST . writeSTRef mlv
resetGuard = do
liftST $ writeSTRef ok False
empty
ReactCont $ lift $ g (evalAContT . unReactCont . f')
-- now make sure the bind to this monad will only fire
-- after all commands has been evaluated
-- by scheduling the bind to unit @() as a command
delegatify $ instruct . ($ ())
-- now read the latest state from the refs
(liftST $ readSTRef ok) >>= guard
(liftST $ readSTRef mlv) >>= putEnv' @Markup
|
louispan/glazier-react
|
src/Glazier/React/ReactCont.hs
|
bsd-3-clause
| 2,788 | 0 | 16 | 718 | 516 | 283 | 233 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Insomnia.Typecheck.ObservationClause where
import Data.Monoid ((<>))
import Data.Traversable(Traversable(..))
import qualified Unbound.Generics.LocallyNameless as U
import Insomnia.Identifier (Path(..))
import Insomnia.ModuleType (Signature(..), ModuleTypeNF(..), SigV(..))
import Insomnia.Common.ModuleKind
import Insomnia.Module (ObservationClause(..))
import Insomnia.Typecheck.Env
import Insomnia.Typecheck.Module (inferModuleExpr)
import Insomnia.Typecheck.LookupModuleSigPath (projectModuleField)
import Insomnia.Typecheck.MayAscribe (mayAscribeNF)
-- checkObservationClause pmod mdlsig obss
-- checks that each "where f is M" observation clause is well-formed with
-- respect to (model) signature mdlsig. The path pmod is just for error messages.
--
-- The observation clauses each pick a new i.i.d. sample from the submodel f and immediately
-- observe its values as "M" which as a result gives 'observe M where f is M' as the posterior.
-- The signature of the overall observe model expression is the same as the signature of 'M'.
checkObservationClauses :: Path -> Signature -> [ObservationClause] -> TC [ObservationClause]
checkObservationClauses pmod mdlsig =
traverse (checkObservationClause pmod mdlsig)
checkObservationClause :: Path -> Signature -> ObservationClause -> TC ObservationClause
checkObservationClause pmod mdlsig (ObservationClause f m) = do
(m', obsSigNF) <- inferModuleExpr (IdP $ U.s2n "<observation>") m
<??@ ("while checking observation of field " <> formatErr f
<> " of " <> formatErr pmod)
kernNF <- projectModuleField pmod f mdlsig
<??@ ("while projecting the field " <> formatErr f <> " for observation of "
<> formatErr pmod)
case (kernNF, obsSigNF) of
(SigMTNF (SigV k ModelMK), SigMTNF (SigV o ModuleMK)) -> do
-- Check that k ≤ o ∧ o ≤ k
let k' = SigMTNF (SigV k ModuleMK)
o' = SigMTNF (SigV o ModuleMK)
_ <- mayAscribeNF k' o'
<??@ ("while checking that the observation kernel "
<> formatErr f
<> " has all the fields of the given observation module")
_ <- mayAscribeNF o' k'
<??@ ("while checking that the observation module has all the fields "
<> "of the given observation kernel " <> formatErr f)
return ()
(SigMTNF (SigV _ ModuleMK), _) ->
typeError ("expected field " <> formatErr f <> " to be a submodel, but it's a submodule "
<> "in observation " <> formatErr pmod)
(FunMTNF {}, _) ->
typeError ("expected field " <> formatErr f <> " to be a submodel, but it's a functor "
<> "in observation " <> formatErr pmod)
(_, SigMTNF (SigV _ ModelMK)) ->
typeError ("expected the observation of field " <> formatErr f <> " to be a module, "
<> "but it's a model, in observation " <> formatErr pmod)
(_, FunMTNF {}) ->
typeError ("expected the observation of field " <> formatErr f <> " to be a module, "
<> "but it's a functor, in observation " <> formatErr pmod)
return (ObservationClause f m')
|
lambdageek/insomnia
|
src/Insomnia/Typecheck/ObservationClause.hs
|
bsd-3-clause
| 3,208 | 0 | 17 | 757 | 688 | 365 | 323 | 49 | 5 |
{-# LANGUAGE OverloadedStrings, TupleSections, PackageImports #-}
module Network.PeyoTLS.State (
HandshakeState, initState, PartnerId, newPartnerId, Keys(..), nullKeys,
ContentType(..), Alert(..), AlertLevel(..), AlertDesc(..),
CipherSuite(..), KeyExchange(..), BulkEncryption(..),
randomGen, setRandomGen,
getBuf, setBuf, getWBuf, setWBuf,
getReadSN, getWriteSN, succReadSN, succWriteSN,
) where
import "monads-tf" Control.Monad.Error.Class (Error(strMsg))
import Data.Maybe (fromJust)
import Data.Word (Word8, Word64)
import Data.String (IsString(..))
import qualified Data.ByteString as BS
import qualified Codec.Bytable.BigEndian as B
import Network.PeyoTLS.CipherSuite (
CipherSuite(..), KeyExchange(..), BulkEncryption(..))
data HandshakeState h g = HandshakeState {
randomGen :: g, nextPartnerId :: Int,
states :: [(PartnerId, StateOne g)] }
initState :: g -> HandshakeState h g
initState g = HandshakeState{ randomGen = g, nextPartnerId = 0, states = [] }
data PartnerId = PartnerId Int deriving (Show, Eq)
newPartnerId :: HandshakeState h g -> (PartnerId, HandshakeState h g)
newPartnerId s = (PartnerId i ,) s{
nextPartnerId = succ i,
states = (PartnerId i, so) : sos }
where
i = nextPartnerId s
so = StateOne {
rBuffer = (CTNull, ""), wBuffer = (CTNull, ""),
readSN = 0, writeSN = 0 }
sos = states s
data StateOne g = StateOne {
rBuffer :: (ContentType, BS.ByteString),
wBuffer :: (ContentType, BS.ByteString),
readSN :: Word64, writeSN :: Word64 }
getState :: PartnerId -> HandshakeState h g -> StateOne g
getState i = fromJust' "getState" . lookup i . states
setState :: PartnerId -> StateOne g -> Modify (HandshakeState h g)
setState i so s = s { states = (i, so) : states s }
modifyState :: PartnerId -> Modify (StateOne g) -> Modify (HandshakeState h g)
modifyState i f s = setState i (f $ getState i s) s
data Keys = Keys {
kCachedCS :: CipherSuite,
kReadCS :: CipherSuite, kWriteCS :: CipherSuite,
kMasterSecret :: BS.ByteString,
kReadMacKey :: BS.ByteString, kWriteMacKey :: BS.ByteString,
kReadKey :: BS.ByteString, kWriteKey :: BS.ByteString }
deriving (Show, Eq)
nullKeys :: Keys
nullKeys = Keys {
kCachedCS = CipherSuite KE_NULL BE_NULL,
kReadCS = CipherSuite KE_NULL BE_NULL,
kWriteCS = CipherSuite KE_NULL BE_NULL,
kMasterSecret = "",
kReadMacKey = "", kWriteMacKey = "", kReadKey = "", kWriteKey = "" }
data ContentType
= CTCCSpec | CTAlert | CTHandshake | CTAppData | CTNull | CTRaw Word8
deriving (Show, Eq)
instance B.Bytable ContentType where
encode CTNull = BS.pack [0]
encode CTCCSpec = BS.pack [20]
encode CTAlert = BS.pack [21]
encode CTHandshake = BS.pack [22]
encode CTAppData = BS.pack [23]
encode (CTRaw ct) = BS.pack [ct]
decode "\0" = Right CTNull
decode "\20" = Right CTCCSpec
decode "\21" = Right CTAlert
decode "\22" = Right CTHandshake
decode "\23" = Right CTAppData
decode bs | [ct] <- BS.unpack bs = Right $ CTRaw ct
decode _ = Left "State.decodeCT"
data Alert = Alert AlertLevel AlertDesc String | NotDetected String
deriving Show
data AlertLevel = ALWarning | ALFatal | ALRaw Word8 deriving Show
data AlertDesc
= ADCloseNotify | ADUnexpectedMessage | ADBadRecordMac
| ADUnsupportedCertificate | ADCertificateExpired | ADCertificateUnknown
| ADIllegalParameter | ADUnknownCa | ADDecodeError
| ADDecryptError | ADProtocolVersion | ADRaw Word8
deriving Show
instance Error Alert where
strMsg = NotDetected
instance IsString Alert where
fromString = NotDetected
setRandomGen :: g -> HandshakeState h g -> HandshakeState h g
setRandomGen rg st = st { randomGen = rg }
getBuf :: PartnerId -> HandshakeState h g -> (ContentType, BS.ByteString)
getBuf i = rBuffer . fromJust' "getBuf" . lookup i . states
setBuf :: PartnerId -> (ContentType, BS.ByteString) -> Modify (HandshakeState h g)
setBuf i = modifyState i . \bs st -> st { rBuffer = bs }
getWBuf :: PartnerId -> HandshakeState h g -> (ContentType, BS.ByteString)
getWBuf i = wBuffer . fromJust' "getWriteBuffer" . lookup i . states
setWBuf :: PartnerId -> (ContentType, BS.ByteString) -> Modify (HandshakeState h g)
setWBuf i = modifyState i . \bs st -> st{ wBuffer = bs }
getReadSN, getWriteSN :: PartnerId -> HandshakeState h g -> Word64
getReadSN i = readSN . fromJust . lookup i . states
getWriteSN i = writeSN . fromJust . lookup i . states
succReadSN, succWriteSN :: PartnerId -> Modify (HandshakeState h g)
succReadSN i = modifyState i $ \s -> s{ readSN = succ $ readSN s }
succWriteSN i = modifyState i $ \s -> s{ writeSN = succ $ writeSN s }
type Modify s = s -> s
fromJust' :: String -> Maybe a -> a
fromJust' _ (Just x) = x
fromJust' msg _ = error msg
|
YoshikuniJujo/forest
|
subprojects/tls-analysis/server/src/Network/PeyoTLS/State.hs
|
bsd-3-clause
| 4,686 | 64 | 11 | 835 | 1,724 | 960 | 764 | 105 | 1 |
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2015 Dimitri Sabadie
-- License : BSD3
--
-- Maintainer : Dimitri Sabadie <[email protected]>
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
module Graphics.Luminance.Blending where
import Control.Monad.IO.Class ( MonadIO(..) )
import Graphics.GL
data BlendingMode
= Additive
| Subtract
| ReverseSubtract
| Min
| Max
deriving (Eq,Show)
fromBlendingMode :: BlendingMode -> GLenum
fromBlendingMode m = case m of
Additive -> GL_FUNC_ADD
Subtract -> GL_FUNC_SUBTRACT
ReverseSubtract -> GL_FUNC_REVERSE_SUBTRACT
Min -> GL_MIN
Max -> GL_MAX
data BlendingFactor
= One
| Zero
| SrcColor
| NegativeSrcColor
| DestColor
| NegativeDestColor
| SrcAlpha
| NegativeSrcAlpha
| DstAlpha
| NegativeDstAlpha
-- | ConstantColor
-- | NegativeConstantColor
-- | ConstantAlpha
-- | NegativeConstantAlpha
| SrcAlphaSaturate
deriving (Eq,Show)
fromBlendingFactor :: BlendingFactor -> GLenum
fromBlendingFactor f = case f of
One -> GL_ONE
Zero -> GL_ZERO
SrcColor -> GL_SRC_COLOR
NegativeSrcColor -> GL_ONE_MINUS_SRC_COLOR
DestColor -> GL_DST_COLOR
NegativeDestColor -> GL_ONE_MINUS_DST_COLOR
SrcAlpha -> GL_SRC_ALPHA
NegativeSrcAlpha -> GL_ONE_MINUS_SRC_ALPHA
DstAlpha -> GL_DST_ALPHA
NegativeDstAlpha -> GL_ONE_MINUS_DST_ALPHA
-- ConstantColor -> GL_CONSTANT_COLOR
-- NegativeConstantColor -> GL_ONE_MINUS_CONSTANT_COLOR
-- ConstantAlpha -> GL_CONSTANT_ALPHA
-- NegativeConstantAlpha -> GL_ONE_MINUS_CONSTANT_ALPHA
SrcAlphaSaturate -> GL_SRC_ALPHA_SATURATE
setBlending :: (MonadIO m) => Maybe (BlendingMode,BlendingFactor,BlendingFactor) -> m ()
setBlending blending = liftIO $ case blending of
Just (mode,src,dst) -> do
glEnable GL_BLEND
glBlendEquation (fromBlendingMode mode)
glBlendFunc (fromBlendingFactor src) (fromBlendingFactor dst)
Nothing -> glDisable GL_BLEND
|
apriori/luminance
|
src/Graphics/Luminance/Blending.hs
|
bsd-3-clause
| 2,227 | 0 | 13 | 498 | 377 | 211 | 166 | 50 | 11 |
-- pilfered from lens package
module Main(main) where
import Build_doctest (deps)
import Control.Applicative
import Control.Monad
import Data.List
import System.Directory
import System.FilePath
import Test.DocTest
main :: IO ()
main = doctest $
"-isource"
: "-itests"
: "-idist/build/autogen"
: "-hide-all-packages"
: "-XQuasiQuotes"
: "-XOverloadedStrings"
: "-DWITH_TEMPLATE_HASKELL"
: "-optP-includedist/build/autogen/cabal_macros.h"
: map ("-package="++) deps
++ sources
sources :: [String]
sources = ["Network.Xmpp.Types"] -- ["source/Network/Xmpp/Types.hs"]
getSources :: IO [FilePath]
getSources = filter (isSuffixOf ".hs") <$> go "source"
where
go dir = do
(dirs, files) <- getFilesAndDirectories dir
(files ++) . concat <$> mapM go dirs
getFilesAndDirectories :: FilePath -> IO ([FilePath], [FilePath])
getFilesAndDirectories dir = do
c <- map (dir </>) . filter (`notElem` ["..", "."]) <$> getDirectoryContents dir
(,) <$> filterM doesDirectoryExist c <*> filterM doesFileExist c
|
Philonous/pontarius-xmpp
|
tests/Doctest.hs
|
bsd-3-clause
| 1,043 | 0 | 14 | 176 | 303 | 164 | 139 | 31 | 1 |
module Pos.Chain.Ssc.OpeningsMap
( OpeningsMap
) where
import Universum
import Pos.Core.Common (StakeholderId)
import Pos.Chain.Ssc.Opening
type OpeningsMap = HashMap StakeholderId Opening
|
input-output-hk/pos-haskell-prototype
|
chain/src/Pos/Chain/Ssc/OpeningsMap.hs
|
mit
| 237 | 0 | 5 | 67 | 45 | 29 | 16 | 6 | 0 |
{-# LANGUAGE CPP, FlexibleContexts, ScopedTypeVariables #-}
{-
Copyright (C) 2009 John MacFarlane <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- | Functions for parsing command line options and reading the config file.
-}
module Network.Gitit.Config ( getConfigFromFile
, getConfigFromFiles
, getDefaultConfig
, readMimeTypesFile )
where
import Network.Gitit.Types
import Network.Gitit.Server (mimeTypes)
import Network.Gitit.Framework
import Network.Gitit.Authentication (formAuthHandlers, rpxAuthHandlers, httpAuthHandlers, githubAuthHandlers)
import Network.Gitit.Util (parsePageType, readFileUTF8)
import System.Log.Logger (logM, Priority(..))
import qualified Data.Map as M
import Data.ConfigFile hiding (readfile)
import Data.List (intercalate)
import Data.Char (toLower, toUpper, isDigit)
import Data.Text (pack)
import Paths_gitit (getDataFileName)
import System.FilePath ((</>))
import Text.Pandoc hiding (MathML, WebTeX, MathJax)
import qualified Control.Exception as E
import Network.OAuth.OAuth2
import qualified Data.ByteString.Char8 as BS
import Network.Gitit.Compat.Except
import Control.Monad
import Control.Monad.Trans
#if MIN_VERSION_pandoc(1,14,0)
import Text.Pandoc.Error (handleError)
#else
handleError :: Pandoc -> Pandoc
handleError = id
#endif
forceEither :: Show e => Either e a -> a
forceEither = either (error . show) id
-- | Get configuration from config file.
getConfigFromFile :: FilePath -> IO Config
getConfigFromFile fname = do
cp <- getDefaultConfigParser
readfile cp fname >>= extractConfig . forceEither
-- | Get configuration from config files.
getConfigFromFiles :: [FilePath] -> IO Config
getConfigFromFiles fnames = do
config <- getConfigParserFromFiles fnames
extractConfig config
getConfigParserFromFiles :: [FilePath] ->
IO ConfigParser
getConfigParserFromFiles (fname:fnames) = do
cp <- getConfigParserFromFiles fnames
config <- readfile cp fname
return $ forceEither config
getConfigParserFromFiles [] = getDefaultConfigParser
-- | A version of readfile that treats the file as UTF-8.
readfile :: MonadError CPError m
=> ConfigParser
-> FilePath
-> IO (m ConfigParser)
readfile cp path' = do
contents <- readFileUTF8 path'
return $ readstring cp contents
extractConfig :: ConfigParser -> IO Config
extractConfig cp = do
config' <- runExceptT $ do
cfRepositoryType <- get cp "DEFAULT" "repository-type"
cfRepositoryPath <- get cp "DEFAULT" "repository-path"
cfDefaultPageType <- get cp "DEFAULT" "default-page-type"
cfMathMethod <- get cp "DEFAULT" "math"
cfMathjaxScript <- get cp "DEFAULT" "mathjax-script"
cfShowLHSBirdTracks <- get cp "DEFAULT" "show-lhs-bird-tracks"
cfRequireAuthentication <- get cp "DEFAULT" "require-authentication"
cfAuthenticationMethod <- get cp "DEFAULT" "authentication-method"
cfUserFile <- get cp "DEFAULT" "user-file"
cfSessionTimeout <- get cp "DEFAULT" "session-timeout"
cfTemplatesDir <- get cp "DEFAULT" "templates-dir"
cfLogFile <- get cp "DEFAULT" "log-file"
cfLogLevel <- get cp "DEFAULT" "log-level"
cfStaticDir <- get cp "DEFAULT" "static-dir"
cfPlugins <- get cp "DEFAULT" "plugins"
cfTableOfContents <- get cp "DEFAULT" "table-of-contents"
cfMaxUploadSize <- get cp "DEFAULT" "max-upload-size"
cfMaxPageSize <- get cp "DEFAULT" "max-page-size"
cfAddress <- get cp "DEFAULT" "address"
cfPort <- get cp "DEFAULT" "port"
cfDebugMode <- get cp "DEFAULT" "debug-mode"
cfFrontPage <- get cp "DEFAULT" "front-page"
cfNoEdit <- get cp "DEFAULT" "no-edit"
cfNoDelete <- get cp "DEFAULT" "no-delete"
cfDefaultSummary <- get cp "DEFAULT" "default-summary"
cfAccessQuestion <- get cp "DEFAULT" "access-question"
cfAccessQuestionAnswers <- get cp "DEFAULT" "access-question-answers"
cfUseRecaptcha <- get cp "DEFAULT" "use-recaptcha"
cfRecaptchaPublicKey <- get cp "DEFAULT" "recaptcha-public-key"
cfRecaptchaPrivateKey <- get cp "DEFAULT" "recaptcha-private-key"
cfRPXDomain <- get cp "DEFAULT" "rpx-domain"
cfRPXKey <- get cp "DEFAULT" "rpx-key"
cfCompressResponses <- get cp "DEFAULT" "compress-responses"
cfUseCache <- get cp "DEFAULT" "use-cache"
cfCacheDir <- get cp "DEFAULT" "cache-dir"
cfMimeTypesFile <- get cp "DEFAULT" "mime-types-file"
cfMailCommand <- get cp "DEFAULT" "mail-command"
cfResetPasswordMessage <- get cp "DEFAULT" "reset-password-message"
cfUseFeed <- get cp "DEFAULT" "use-feed"
cfBaseUrl <- get cp "DEFAULT" "base-url"
cfAbsoluteUrls <- get cp "DEFAULT" "absolute-urls"
cfWikiTitle <- get cp "DEFAULT" "wiki-title"
cfFeedDays <- get cp "DEFAULT" "feed-days"
cfFeedRefreshTime <- get cp "DEFAULT" "feed-refresh-time"
cfPDFExport <- get cp "DEFAULT" "pdf-export"
cfPandocUserData <- get cp "DEFAULT" "pandoc-user-data"
cfXssSanitize <- get cp "DEFAULT" "xss-sanitize"
cfRecentActivityDays <- get cp "DEFAULT" "recent-activity-days"
let (pt, lhs) = parsePageType cfDefaultPageType
let markupHelpFile = show pt ++ if lhs then "+LHS" else ""
markupHelpPath <- liftIO $ getDataFileName $ "data" </> "markupHelp" </> markupHelpFile
markupHelpText <- liftM (writeHtmlString def . handleError .
readMarkdown def) $
liftIO $ readFileUTF8 markupHelpPath
mimeMap' <- liftIO $ readMimeTypesFile cfMimeTypesFile
let authMethod = map toLower cfAuthenticationMethod
let stripTrailingSlash = reverse . dropWhile (=='/') . reverse
let repotype' = case map toLower cfRepositoryType of
"git" -> Git
"darcs" -> Darcs
"mercurial" -> Mercurial
x -> error $ "Unknown repository type: " ++ x
when (authMethod == "rpx" && cfRPXDomain == "") $
liftIO $ logM "gitit" WARNING "rpx-domain is not set"
ghConfig <- extractGithubConfig cp
return Config{
repositoryPath = cfRepositoryPath
, repositoryType = repotype'
, defaultPageType = pt
, mathMethod = case map toLower cfMathMethod of
"jsmath" -> JsMathScript
"mathml" -> MathML
"mathjax" -> MathJax cfMathjaxScript
"google" -> WebTeX "http://chart.apis.google.com/chart?cht=tx&chl="
_ -> RawTeX
, defaultLHS = lhs
, showLHSBirdTracks = cfShowLHSBirdTracks
, withUser = case authMethod of
"form" -> withUserFromSession
"github" -> withUserFromSession
"http" -> withUserFromHTTPAuth
"rpx" -> withUserFromSession
_ -> id
, requireAuthentication = case map toLower cfRequireAuthentication of
"none" -> Never
"modify" -> ForModify
"read" -> ForRead
_ -> ForModify
, authHandler = case authMethod of
"form" -> msum formAuthHandlers
"github" -> msum $ githubAuthHandlers ghConfig
"http" -> msum httpAuthHandlers
"rpx" -> msum rpxAuthHandlers
_ -> mzero
, userFile = cfUserFile
, sessionTimeout = readNumber "session-timeout" cfSessionTimeout * 60 -- convert minutes -> seconds
, templatesDir = cfTemplatesDir
, logFile = cfLogFile
, logLevel = let levelString = map toUpper cfLogLevel
levels = ["DEBUG", "INFO", "NOTICE", "WARNING", "ERROR",
"CRITICAL", "ALERT", "EMERGENCY"]
in if levelString `elem` levels
then read levelString
else error $ "Invalid log-level.\nLegal values are: " ++ intercalate ", " levels
, staticDir = cfStaticDir
, pluginModules = splitCommaList cfPlugins
, tableOfContents = cfTableOfContents
, maxUploadSize = readSize "max-upload-size" cfMaxUploadSize
, maxPageSize = readSize "max-page-size" cfMaxPageSize
, address = cfAddress
, portNumber = readNumber "port" cfPort
, debugMode = cfDebugMode
, frontPage = cfFrontPage
, noEdit = splitCommaList cfNoEdit
, noDelete = splitCommaList cfNoDelete
, defaultSummary = cfDefaultSummary
, accessQuestion = if null cfAccessQuestion
then Nothing
else Just (cfAccessQuestion, splitCommaList cfAccessQuestionAnswers)
, useRecaptcha = cfUseRecaptcha
, recaptchaPublicKey = cfRecaptchaPublicKey
, recaptchaPrivateKey = cfRecaptchaPrivateKey
, rpxDomain = cfRPXDomain
, rpxKey = cfRPXKey
, compressResponses = cfCompressResponses
, useCache = cfUseCache
, cacheDir = cfCacheDir
, mimeMap = mimeMap'
, mailCommand = cfMailCommand
, resetPasswordMessage = fromQuotedMultiline cfResetPasswordMessage
, markupHelp = markupHelpText
, useFeed = cfUseFeed
, baseUrl = stripTrailingSlash cfBaseUrl
, useAbsoluteUrls = cfAbsoluteUrls
, wikiTitle = cfWikiTitle
, feedDays = readNumber "feed-days" cfFeedDays
, feedRefreshTime = readNumber "feed-refresh-time" cfFeedRefreshTime
, pdfExport = cfPDFExport
, pandocUserData = if null cfPandocUserData
then Nothing
else Just cfPandocUserData
, xssSanitize = cfXssSanitize
, recentActivityDays = cfRecentActivityDays
, githubAuth = ghConfig
}
case config' of
Left (ParseError e, e') -> error $ "Parse error: " ++ e ++ "\n" ++ e'
Left e -> error (show e)
Right c -> return c
extractGithubConfig :: (Functor m, MonadError CPError m) => ConfigParser
-> m GithubConfig
extractGithubConfig cp = do
cfOauthClientId <- getGithubProp "oauthClientId"
cfOauthClientSecret <- getGithubProp "oauthClientSecret"
cfOauthCallback <- getGithubProp "oauthCallback"
cfOauthOAuthorizeEndpoint <- getGithubProp "oauthOAuthorizeEndpoint"
cfOauthAccessTokenEndpoint <- getGithubProp "oauthAccessTokenEndpoint"
cfOrg <- if hasGithubProp "github-org"
then fmap Just (getGithubProp "github-org")
else return Nothing
let cfgOAuth2 = OAuth2 { oauthClientId = BS.pack cfOauthClientId
, oauthClientSecret = BS.pack cfOauthClientSecret
, oauthCallback = Just $ BS.pack cfOauthCallback
, oauthOAuthorizeEndpoint = BS.pack cfOauthOAuthorizeEndpoint
, oauthAccessTokenEndpoint = BS.pack cfOauthAccessTokenEndpoint
}
return $ githubConfig cfgOAuth2 $ fmap pack cfOrg
where getGithubProp = get cp "Github"
hasGithubProp = has_option cp "Github"
fromQuotedMultiline :: String -> String
fromQuotedMultiline = unlines . map doline . lines . dropWhile (`elem` " \t\n")
where doline = dropWhile (`elem` " \t") . dropGt
dropGt ('>':' ':xs) = xs
dropGt ('>':xs) = xs
dropGt x = x
readNumber :: (Num a, Read a) => String -> String -> a
readNumber _ x | all isDigit x = read x
readNumber opt _ = error $ opt ++ " must be a number."
readSize :: (Num a, Read a) => String -> String -> a
readSize opt x =
case reverse x of
('K':_) -> readNumber opt (init x) * 1000
('M':_) -> readNumber opt (init x) * 1000000
('G':_) -> readNumber opt (init x) * 1000000000
_ -> readNumber opt x
splitCommaList :: String -> [String]
splitCommaList l =
let (first,rest) = break (== ',') l
first' = lrStrip first
in case rest of
[] -> if null first' then [] else [first']
(_:rs) -> first' : splitCommaList rs
lrStrip :: String -> String
lrStrip = reverse . dropWhile isWhitespace . reverse . dropWhile isWhitespace
where isWhitespace = (`elem` " \t\n")
getDefaultConfigParser :: IO ConfigParser
getDefaultConfigParser = do
cp <- getDataFileName "data/default.conf" >>= readfile emptyCP
return $ forceEither cp
-- | Returns the default gitit configuration.
getDefaultConfig :: IO Config
getDefaultConfig = getDefaultConfigParser >>= extractConfig
-- | Read a file associating mime types with extensions, and return a
-- map from extensions to types. Each line of the file consists of a
-- mime type, followed by space, followed by a list of zero or more
-- extensions, separated by spaces. Example: text/plain txt text
readMimeTypesFile :: FilePath -> IO (M.Map String String)
readMimeTypesFile f = E.catch
(liftM (foldr (go . words) M.empty . lines) $ readFileUTF8 f)
handleMimeTypesFileNotFound
where go [] m = m -- skip blank lines
go (x:xs) m = foldr (`M.insert` x) m xs
handleMimeTypesFileNotFound (e :: E.SomeException) = do
logM "gitit" WARNING $ "Could not read mime types file: " ++
f ++ "\n" ++ show e ++ "\n" ++ "Using defaults instead."
return mimeTypes
{-
-- | Ready collection of common mime types. (Copied from
-- Happstack.Server.HTTP.FileServe.)
mimeTypes :: M.Map String String
mimeTypes = M.fromList
[("xml","application/xml")
,("xsl","application/xml")
,("js","text/javascript")
,("html","text/html")
,("htm","text/html")
,("css","text/css")
,("gif","image/gif")
,("jpg","image/jpeg")
,("png","image/png")
,("txt","text/plain")
,("doc","application/msword")
,("exe","application/octet-stream")
,("pdf","application/pdf")
,("zip","application/zip")
,("gz","application/x-gzip")
,("ps","application/postscript")
,("rtf","application/rtf")
,("wav","application/x-wav")
,("hs","text/plain")]
-}
|
mduvall/gitit
|
Network/Gitit/Config.hs
|
gpl-2.0
| 15,958 | 0 | 18 | 5,006 | 3,089 | 1,571 | 1,518 | 263 | 25 |
module TypeCheckSpec where
import Control.Monad (forM_)
import System.Directory
import System.FilePath
import Test.Tasty.Hspec
import Parser (parseExpr, P(..))
import SpecHelper
import TypeCheck (checkExpr)
hasError :: Either a b -> Bool
hasError (Left _) = True
hasError (Right _) = False
testCasesPath = "testsuite/tests/shouldnt_typecheck"
tcSpec :: Spec
tcSpec = do
failingCases <- runIO (discoverTestCases testCasesPath)
curr <- runIO (getCurrentDirectory)
runIO (setCurrentDirectory $ curr </> testCasesPath)
describe "Should fail to typecheck" $
forM_ failingCases
(\(name, filePath) -> do
do source <- runIO (readFile filePath)
it ("should reject " ++ name) $
let ParseOk parsed = parseExpr source
in checkExpr parsed >>= ((`shouldSatisfy` hasError)))
runIO (setCurrentDirectory curr)
|
zhiyuanshi/fcore
|
testsuite/TypeCheckSpec.hs
|
bsd-2-clause
| 873 | 0 | 20 | 182 | 270 | 140 | 130 | 25 | 1 |
module Language.Swift.Quote (
module Language.Swift.Quote.Syntax,
module Language.Swift.Quote.Parser,
module Language.Swift.Quote.Pretty
) where
import Language.Swift.Quote.Syntax
import Language.Swift.Quote.Parser
import Language.Swift.Quote.Pretty
|
steshaw/language-swift-quote
|
Language/Swift/Quote.hs
|
bsd-3-clause
| 259 | 0 | 5 | 26 | 54 | 39 | 15 | 7 | 0 |
-- | Re-export the common parts of the server framework.
--
module Distribution.Server.Framework (
module Happstack.Server,
module Distribution.Server.Framework.Auth,
module Distribution.Server.Framework.Feature,
module Distribution.Server.Framework.Types,
module Distribution.Server.Framework.ResourceTypes,
module Distribution.Server.Framework.Resource,
module Distribution.Server.Framework.Hook,
module Distribution.Server.Framework.Error,
module Distribution.Server.Util.Happstack
) where
import Happstack.Server
import Distribution.Server.Framework.Auth
import Distribution.Server.Framework.Feature
import Distribution.Server.Framework.Types
import Distribution.Server.Framework.ResourceTypes
import Distribution.Server.Framework.Resource
import Distribution.Server.Framework.Hook
import Distribution.Server.Framework.Error
import Distribution.Server.Util.Happstack
|
isomorphism/hackage2
|
Distribution/Server/Framework.hs
|
bsd-3-clause
| 912 | 0 | 5 | 93 | 142 | 103 | 39 | 19 | 0 |
{-# LANGUAGE CPP, TypeFamilies #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Safe #-}
#endif
-----------------------------------------------------------------------------
-- The fuel monad
-----------------------------------------------------------------------------
module Compiler.Hoopl.Fuel
( Fuel, infiniteFuel, fuelRemaining
, withFuel
, FuelMonad(..)
, FuelMonadT(..)
, CheckingFuelMonad
, InfiniteFuelMonad
, SimpleFuelMonad
)
where
import Compiler.Hoopl.Checkpoint
import Compiler.Hoopl.Unique
import Control.Applicative (Applicative(..))
import Control.Monad (ap,liftM)
class Monad m => FuelMonad m where
getFuel :: m Fuel
setFuel :: Fuel -> m ()
-- | Find out how much fuel remains after a computation.
-- Can be subtracted from initial fuel to get total consumption.
fuelRemaining :: FuelMonad m => m Fuel
fuelRemaining = getFuel
class FuelMonadT fm where
runWithFuel :: (Monad m, FuelMonad (fm m)) => Fuel -> fm m a -> m a
liftFuel :: (Monad m, FuelMonad (fm m)) => m a -> fm m a
type Fuel = Int
withFuel :: FuelMonad m => Maybe a -> m (Maybe a)
withFuel Nothing = return Nothing
withFuel (Just a) = do f <- getFuel
if f == 0
then return Nothing
else setFuel (f-1) >> return (Just a)
----------------------------------------------------------------
newtype CheckingFuelMonad m a = FM { unFM :: Fuel -> m (a, Fuel) }
instance Monad m => Functor (CheckingFuelMonad m) where
fmap = liftM
instance Monad m => Applicative (CheckingFuelMonad m) where
pure = return
(<*>) = ap
instance Monad m => Monad (CheckingFuelMonad m) where
return a = FM (\f -> return (a, f))
fm >>= k = FM (\f -> do { (a, f') <- unFM fm f; unFM (k a) f' })
instance CheckpointMonad m => CheckpointMonad (CheckingFuelMonad m) where
type Checkpoint (CheckingFuelMonad m) = (Fuel, Checkpoint m)
checkpoint = FM $ \fuel -> do { s <- checkpoint
; return ((fuel, s), fuel) }
restart (fuel, s) = FM $ \_ -> do { restart s; return ((), fuel) }
instance UniqueMonad m => UniqueMonad (CheckingFuelMonad m) where
freshUnique = FM (\f -> do { l <- freshUnique; return (l, f) })
instance Monad m => FuelMonad (CheckingFuelMonad m) where
getFuel = FM (\f -> return (f, f))
setFuel f = FM (\_ -> return ((),f))
instance FuelMonadT CheckingFuelMonad where
runWithFuel fuel m = do { (a, _) <- unFM m fuel; return a }
liftFuel m = FM $ \f -> do { a <- m; return (a, f) }
----------------------------------------------------------------
newtype InfiniteFuelMonad m a = IFM { unIFM :: m a }
instance Monad m => Functor (InfiniteFuelMonad m) where
fmap = liftM
instance Monad m => Applicative (InfiniteFuelMonad m) where
pure = return
(<*>) = ap
instance Monad m => Monad (InfiniteFuelMonad m) where
return a = IFM $ return a
m >>= k = IFM $ do { a <- unIFM m; unIFM (k a) }
instance UniqueMonad m => UniqueMonad (InfiniteFuelMonad m) where
freshUnique = IFM $ freshUnique
instance Monad m => FuelMonad (InfiniteFuelMonad m) where
getFuel = return infiniteFuel
setFuel _ = return ()
instance CheckpointMonad m => CheckpointMonad (InfiniteFuelMonad m) where
type Checkpoint (InfiniteFuelMonad m) = Checkpoint m
checkpoint = IFM checkpoint
restart s = IFM $ restart s
instance FuelMonadT InfiniteFuelMonad where
runWithFuel _ = unIFM
liftFuel = IFM
infiniteFuel :: Fuel -- effectively infinite, any, but subtractable
infiniteFuel = maxBound
type SimpleFuelMonad = CheckingFuelMonad SimpleUniqueMonad
{-
runWithFuelAndUniques :: Fuel -> [Unique] -> FuelMonad a -> a
runWithFuelAndUniques fuel uniques m = a
where (a, _, _) = unFM m fuel uniques
freshUnique :: FuelMonad Unique
freshUnique = FM (\f (l:ls) -> (l, f, ls))
-}
|
DavidAlphaFox/ghc
|
libraries/hoopl/src/Compiler/Hoopl/Fuel.hs
|
bsd-3-clause
| 3,816 | 0 | 13 | 811 | 1,222 | 648 | 574 | 74 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ConstraintKinds #-}
module PlaceHolder where
import Type ( Type )
import Outputable
import Name
import NameSet
import RdrName
import Var
import Coercion
import Data.Data hiding ( Fixity )
import BasicTypes (Fixity)
{-
%************************************************************************
%* *
\subsection{Annotating the syntax}
%* *
%************************************************************************
-}
-- | used as place holder in PostTc and PostRn values
data PlaceHolder = PlaceHolder
deriving (Data,Typeable)
-- | Types that are not defined until after type checking
type family PostTc it ty :: * -- Note [Pass sensitive types]
type instance PostTc Id ty = ty
type instance PostTc Name ty = PlaceHolder
type instance PostTc RdrName ty = PlaceHolder
-- | Types that are not defined until after renaming
type family PostRn id ty :: * -- Note [Pass sensitive types]
type instance PostRn Id ty = ty
type instance PostRn Name ty = ty
type instance PostRn RdrName ty = PlaceHolder
placeHolderKind :: PlaceHolder
placeHolderKind = PlaceHolder
placeHolderFixity :: PlaceHolder
placeHolderFixity = PlaceHolder
placeHolderType :: PlaceHolder
placeHolderType = PlaceHolder
placeHolderTypeTc :: Type
placeHolderTypeTc = panic "Evaluated the place holder for a PostTcType"
placeHolderNames :: PlaceHolder
placeHolderNames = PlaceHolder
placeHolderNamesTc :: NameSet
placeHolderNamesTc = emptyNameSet
{-
Note [Pass sensitive types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Since the same AST types are re-used through parsing,renaming and type
checking there are naturally some places in the AST that do not have
any meaningful value prior to the pass they are assigned a value.
Historically these have been filled in with place holder values of the form
panic "error message"
This has meant the AST is difficult to traverse using standed generic
programming techniques. The problem is addressed by introducing
pass-specific data types, implemented as a pair of open type families,
one for PostTc and one for PostRn. These are then explicitly populated
with a PlaceHolder value when they do not yet have meaning.
Since the required bootstrap compiler at this stage does not have
closed type families, an open type family had to be used, which
unfortunately forces the requirement for UndecidableInstances.
In terms of actual usage, we have the following
PostTc id Kind
PostTc id Type
PostRn id Fixity
PostRn id NameSet
TcId and Var are synonyms for Id
-}
type DataId id =
( Data id
, Data (PostRn id NameSet)
, Data (PostRn id Fixity)
, Data (PostRn id Bool)
, Data (PostRn id [Name])
, Data (PostTc id Type)
, Data (PostTc id Coercion)
)
|
spacekitteh/smcghc
|
compiler/hsSyn/PlaceHolder.hs
|
bsd-3-clause
| 2,927 | 0 | 9 | 627 | 332 | 197 | 135 | 43 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for ganeti-htools.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Test.Ganeti.HTools.Instance
( testHTools_Instance
, genInstanceSmallerThanNode
, genInstanceMaybeBiggerThanNode
, genInstanceOnNodeList
, genInstanceList
, Instance.Instance(..)
) where
import Control.Monad (liftM)
import Test.QuickCheck hiding (Result)
import Test.Ganeti.TestHelper
import Test.Ganeti.TestCommon
import Test.Ganeti.HTools.Types ()
import Ganeti.BasicTypes
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.HTools.Loader as Loader
import qualified Ganeti.HTools.Types as Types
-- * Arbitrary instances
-- | Generates a random instance with maximum disk/mem/cpu values.
genInstanceSmallerThan :: Int -> Int -> Int -> Maybe Int ->
Gen Instance.Instance
genInstanceSmallerThan lim_mem lim_dsk lim_cpu lim_spin = do
name <- genFQDN
mem <- choose (0, lim_mem)
dsk <- choose (0, lim_dsk)
run_st <- arbitrary
pn <- arbitrary
sn <- arbitrary
vcpus <- choose (0, lim_cpu)
dt <- arbitrary
spindles <- case lim_spin of
Nothing -> genMaybe $ choose (0, maxSpindles)
Just ls -> liftM Just $ choose (0, ls)
let disk = Instance.Disk dsk spindles
return $ Instance.create
name mem dsk [disk] vcpus run_st [] True pn sn dt 1 []
-- | Generates an instance smaller than a node.
genInstanceSmallerThanNode :: Node.Node -> Gen Instance.Instance
genInstanceSmallerThanNode node =
genInstanceSmallerThan (Node.availMem node `div` 2)
(Node.availDisk node `div` 2)
(Node.availCpu node `div` 2)
(if Node.exclStorage node
then Just $ Node.fSpindles node `div` 2
else Nothing)
-- | Generates an instance possibly bigger than a node.
genInstanceMaybeBiggerThanNode :: Node.Node -> Gen Instance.Instance
genInstanceMaybeBiggerThanNode node =
genInstanceSmallerThan (Node.availMem node + Types.unitMem * 2)
(Node.availDisk node + Types.unitDsk * 3)
(Node.availCpu node + Types.unitCpu * 4)
(if Node.exclStorage node
then Just $ Node.fSpindles node +
Types.unitSpindle * 5
else Nothing)
-- | Generates an instance with nodes on a node list.
-- The following rules are respected:
-- 1. The instance is never bigger than its primary node
-- 2. If possible the instance has different pnode and snode
-- 3. Else disk templates which require secondary nodes are disabled
genInstanceOnNodeList :: Node.List -> Gen Instance.Instance
genInstanceOnNodeList nl = do
let nsize = Container.size nl
pnode <- choose (0, nsize-1)
let (snodefilter, dtfilter) =
if nsize >= 2
then ((/= pnode), const True)
else (const True, not . Instance.hasSecondary)
snode <- choose (0, nsize-1) `suchThat` snodefilter
i <- genInstanceSmallerThanNode (Container.find pnode nl) `suchThat` dtfilter
return $ i { Instance.pNode = pnode, Instance.sNode = snode }
-- | Generates an instance list given an instance generator.
genInstanceList :: Gen Instance.Instance -> Gen Instance.List
genInstanceList igen = fmap (snd . Loader.assignIndices) names_instances
where names_instances =
(fmap . map) (\n -> (Instance.name n, n)) $ listOf igen
-- let's generate a random instance
instance Arbitrary Instance.Instance where
arbitrary = genInstanceSmallerThan maxMem maxDsk maxCpu Nothing
-- * Test cases
-- Simple instance tests, we only have setter/getters
prop_creat :: Instance.Instance -> Property
prop_creat inst =
Instance.name inst ==? Instance.alias inst
prop_setIdx :: Instance.Instance -> Types.Idx -> Property
prop_setIdx inst idx =
Instance.idx (Instance.setIdx inst idx) ==? idx
prop_setName :: Instance.Instance -> String -> Bool
prop_setName inst name =
Instance.name newinst == name &&
Instance.alias newinst == name
where newinst = Instance.setName inst name
prop_setAlias :: Instance.Instance -> String -> Bool
prop_setAlias inst name =
Instance.name newinst == Instance.name inst &&
Instance.alias newinst == name
where newinst = Instance.setAlias inst name
prop_setPri :: Instance.Instance -> Types.Ndx -> Property
prop_setPri inst pdx =
Instance.pNode (Instance.setPri inst pdx) ==? pdx
prop_setSec :: Instance.Instance -> Types.Ndx -> Property
prop_setSec inst sdx =
Instance.sNode (Instance.setSec inst sdx) ==? sdx
prop_setBoth :: Instance.Instance -> Types.Ndx -> Types.Ndx -> Bool
prop_setBoth inst pdx sdx =
Instance.pNode si == pdx && Instance.sNode si == sdx
where si = Instance.setBoth inst pdx sdx
prop_shrinkMG :: Instance.Instance -> Property
prop_shrinkMG inst =
Instance.mem inst >= 2 * Types.unitMem ==>
case Instance.shrinkByType inst Types.FailMem of
Ok inst' -> Instance.mem inst' ==? Instance.mem inst - Types.unitMem
Bad msg -> failTest msg
prop_shrinkMF :: Instance.Instance -> Property
prop_shrinkMF inst =
forAll (choose (0, 2 * Types.unitMem - 1)) $ \mem ->
let inst' = inst { Instance.mem = mem}
in isBad $ Instance.shrinkByType inst' Types.FailMem
prop_shrinkCG :: Instance.Instance -> Property
prop_shrinkCG inst =
Instance.vcpus inst >= 2 * Types.unitCpu ==>
case Instance.shrinkByType inst Types.FailCPU of
Ok inst' -> Instance.vcpus inst' ==? Instance.vcpus inst - Types.unitCpu
Bad msg -> failTest msg
prop_shrinkCF :: Instance.Instance -> Property
prop_shrinkCF inst =
forAll (choose (0, 2 * Types.unitCpu - 1)) $ \vcpus ->
let inst' = inst { Instance.vcpus = vcpus }
in isBad $ Instance.shrinkByType inst' Types.FailCPU
prop_shrinkDG :: Instance.Instance -> Property
prop_shrinkDG inst =
Instance.dsk inst >= 2 * Types.unitDsk ==>
case Instance.shrinkByType inst Types.FailDisk of
Ok inst' -> Instance.dsk inst' ==? Instance.dsk inst - Types.unitDsk
Bad msg -> failTest msg
prop_shrinkDF :: Instance.Instance -> Property
prop_shrinkDF inst =
forAll (choose (0, 2 * Types.unitDsk - 1)) $ \dsk ->
let inst' = inst { Instance.dsk = dsk
, Instance.disks = [Instance.Disk dsk Nothing] }
in isBad $ Instance.shrinkByType inst' Types.FailDisk
prop_setMovable :: Instance.Instance -> Bool -> Property
prop_setMovable inst m =
Instance.movable inst' ==? m
where inst' = Instance.setMovable inst m
testSuite "HTools/Instance"
[ 'prop_creat
, 'prop_setIdx
, 'prop_setName
, 'prop_setAlias
, 'prop_setPri
, 'prop_setSec
, 'prop_setBoth
, 'prop_shrinkMG
, 'prop_shrinkMF
, 'prop_shrinkCG
, 'prop_shrinkCF
, 'prop_shrinkDG
, 'prop_shrinkDF
, 'prop_setMovable
]
|
badp/ganeti
|
test/hs/Test/Ganeti/HTools/Instance.hs
|
gpl-2.0
| 7,803 | 0 | 15 | 1,771 | 1,949 | 1,020 | 929 | 150 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.CloudHSM.Types
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
module Network.AWS.CloudHSM.Types
(
-- * Service
CloudHSM
-- ** Error
, JSONError
-- * CloudHsmObjectState
, CloudHsmObjectState (..)
-- * SubscriptionType
, SubscriptionType (..)
-- * HsmStatus
, HsmStatus (..)
-- * ClientVersion
, ClientVersion (..)
) where
import Network.AWS.Prelude
import Network.AWS.Signing
import qualified GHC.Exts
-- | Version @2014-05-30@ of the Amazon CloudHSM service.
data CloudHSM
instance AWSService CloudHSM where
type Sg CloudHSM = V4
type Er CloudHSM = JSONError
service = service'
where
service' :: Service CloudHSM
service' = Service
{ _svcAbbrev = "CloudHSM"
, _svcPrefix = "cloudhsm"
, _svcVersion = "2014-05-30"
, _svcTargetPrefix = Just "CloudHsmFrontendService"
, _svcJSONVersion = Just "1.1"
, _svcHandle = handle
, _svcRetry = retry
}
handle :: Status
-> Maybe (LazyByteString -> ServiceError JSONError)
handle = jsonError statusSuccess service'
retry :: Retry CloudHSM
retry = Exponential
{ _retryBase = 0.05
, _retryGrowth = 2
, _retryAttempts = 5
, _retryCheck = check
}
check :: Status
-> JSONError
-> Bool
check (statusCode -> s) (awsErrorCode -> e)
| s == 500 = True -- General Server Error
| s == 509 = True -- Limit Exceeded
| s == 503 = True -- Service Unavailable
| otherwise = False
data CloudHsmObjectState
= Degraded -- ^ DEGRADED
| Ready -- ^ READY
| Updating -- ^ UPDATING
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable CloudHsmObjectState
instance FromText CloudHsmObjectState where
parser = takeLowerText >>= \case
"degraded" -> pure Degraded
"ready" -> pure Ready
"updating" -> pure Updating
e -> fail $
"Failure parsing CloudHsmObjectState from " ++ show e
instance ToText CloudHsmObjectState where
toText = \case
Degraded -> "DEGRADED"
Ready -> "READY"
Updating -> "UPDATING"
instance ToByteString CloudHsmObjectState
instance ToHeader CloudHsmObjectState
instance ToQuery CloudHsmObjectState
instance FromJSON CloudHsmObjectState where
parseJSON = parseJSONText "CloudHsmObjectState"
instance ToJSON CloudHsmObjectState where
toJSON = toJSONText
data SubscriptionType
= Production -- ^ PRODUCTION
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable SubscriptionType
instance FromText SubscriptionType where
parser = takeLowerText >>= \case
"production" -> pure Production
e -> fail $
"Failure parsing SubscriptionType from " ++ show e
instance ToText SubscriptionType where
toText Production = "PRODUCTION"
instance ToByteString SubscriptionType
instance ToHeader SubscriptionType
instance ToQuery SubscriptionType
instance FromJSON SubscriptionType where
parseJSON = parseJSONText "SubscriptionType"
instance ToJSON SubscriptionType where
toJSON = toJSONText
data HsmStatus
= HSDegraded -- ^ DEGRADED
| HSPending -- ^ PENDING
| HSRunning -- ^ RUNNING
| HSSuspended -- ^ SUSPENDED
| HSTerminated -- ^ TERMINATED
| HSTerminating -- ^ TERMINATING
| HSUpdating -- ^ UPDATING
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable HsmStatus
instance FromText HsmStatus where
parser = takeLowerText >>= \case
"degraded" -> pure HSDegraded
"pending" -> pure HSPending
"running" -> pure HSRunning
"suspended" -> pure HSSuspended
"terminated" -> pure HSTerminated
"terminating" -> pure HSTerminating
"updating" -> pure HSUpdating
e -> fail $
"Failure parsing HsmStatus from " ++ show e
instance ToText HsmStatus where
toText = \case
HSDegraded -> "DEGRADED"
HSPending -> "PENDING"
HSRunning -> "RUNNING"
HSSuspended -> "SUSPENDED"
HSTerminated -> "TERMINATED"
HSTerminating -> "TERMINATING"
HSUpdating -> "UPDATING"
instance ToByteString HsmStatus
instance ToHeader HsmStatus
instance ToQuery HsmStatus
instance FromJSON HsmStatus where
parseJSON = parseJSONText "HsmStatus"
instance ToJSON HsmStatus where
toJSON = toJSONText
data ClientVersion
= V51 -- ^ 5.1
| V53 -- ^ 5.3
deriving (Eq, Ord, Read, Show, Generic, Enum)
instance Hashable ClientVersion
instance FromText ClientVersion where
parser = takeLowerText >>= \case
"5.1" -> pure V51
"5.3" -> pure V53
e -> fail $
"Failure parsing ClientVersion from " ++ show e
instance ToText ClientVersion where
toText = \case
V51 -> "5.1"
V53 -> "5.3"
instance ToByteString ClientVersion
instance ToHeader ClientVersion
instance ToQuery ClientVersion
instance FromJSON ClientVersion where
parseJSON = parseJSONText "ClientVersion"
instance ToJSON ClientVersion where
toJSON = toJSONText
|
kim/amazonka
|
amazonka-cloudhsm/gen/Network/AWS/CloudHSM/Types.hs
|
mpl-2.0
| 6,421 | 0 | 12 | 1,932 | 1,144 | 616 | 528 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable, DeriveFunctor, DeriveFoldable, DeriveTraversable, StandaloneDeriving, TypeFamilies, RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Types
-- Copyright : (c) Simon Marlow 2003-2006,
-- David Waern 2006-2009,
-- Mateusz Kowalczyk 2013
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Types that are commonly used through-out Haddock. Some of the most
-- important types are defined here, like 'Interface' and 'DocName'.
-----------------------------------------------------------------------------
module Haddock.Types (
module Haddock.Types
, HsDocString, LHsDocString
, Fixity(..)
, module Documentation.Haddock.Types
) where
import Control.Exception
import Control.Arrow hiding ((<+>))
import Control.DeepSeq
import Data.Typeable
import Data.Map (Map)
import Data.Data (Data)
import qualified Data.Map as Map
import Documentation.Haddock.Types
import BasicTypes (Fixity(..))
import GHC hiding (NoLink)
import DynFlags (ExtensionFlag, Language)
import Coercion
import NameSet
import OccName
import Outputable
import Control.Monad (ap)
import Haddock.Backends.Hyperlinker.Types
-----------------------------------------------------------------------------
-- * Convenient synonyms
-----------------------------------------------------------------------------
type IfaceMap = Map Module Interface
type InstIfaceMap = Map Module InstalledInterface -- TODO: rename
type DocMap a = Map Name (MDoc a)
type ArgMap a = Map Name (Map Int (MDoc a))
type SubMap = Map Name [Name]
type DeclMap = Map Name [LHsDecl Name]
type InstMap = Map SrcSpan Name
type FixMap = Map Name Fixity
type DocPaths = (FilePath, Maybe FilePath) -- paths to HTML and sources
-----------------------------------------------------------------------------
-- * Interface
-----------------------------------------------------------------------------
-- | 'Interface' holds all information used to render a single Haddock page.
-- It represents the /interface/ of a module. The core business of Haddock
-- lies in creating this structure. Note that the record contains some fields
-- that are only used to create the final record, and that are not used by the
-- backends.
data Interface = Interface
{
-- | The module behind this interface.
ifaceMod :: !Module
-- | Original file name of the module.
, ifaceOrigFilename :: !FilePath
-- | Textual information about the module.
, ifaceInfo :: !(HaddockModInfo Name)
-- | Documentation header.
, ifaceDoc :: !(Documentation Name)
-- | Documentation header with cross-reference information.
, ifaceRnDoc :: !(Documentation DocName)
-- | Haddock options for this module (prune, ignore-exports, etc).
, ifaceOptions :: ![DocOption]
-- | Declarations originating from the module. Excludes declarations without
-- names (instances and stand-alone documentation comments). Includes
-- names of subordinate declarations mapped to their parent declarations.
, ifaceDeclMap :: !(Map Name [LHsDecl Name])
-- | Documentation of declarations originating from the module (including
-- subordinates).
, ifaceDocMap :: !(DocMap Name)
, ifaceArgMap :: !(ArgMap Name)
-- | Documentation of declarations originating from the module (including
-- subordinates).
, ifaceRnDocMap :: !(DocMap DocName)
, ifaceRnArgMap :: !(ArgMap DocName)
, ifaceSubMap :: !(Map Name [Name])
, ifaceFixMap :: !(Map Name Fixity)
, ifaceExportItems :: ![ExportItem Name]
, ifaceRnExportItems :: ![ExportItem DocName]
-- | All names exported by the module.
, ifaceExports :: ![Name]
-- | All \"visible\" names exported by the module.
-- A visible name is a name that will show up in the documentation of the
-- module.
, ifaceVisibleExports :: ![Name]
-- | Aliases of module imports as in @import A.B.C as C@.
, ifaceModuleAliases :: !AliasMap
-- | Instances exported by the module.
, ifaceInstances :: ![ClsInst]
, ifaceFamInstances :: ![FamInst]
-- | The number of haddockable and haddocked items in the module, as a
-- tuple. Haddockable items are the exports and the module itself.
, ifaceHaddockCoverage :: !(Int, Int)
-- | Warnings for things defined in this module.
, ifaceWarningMap :: !WarningMap
-- | Tokenized source code of module (avaliable if Haddock is invoked with
-- source generation flag).
, ifaceTokenizedSrc :: !(Maybe [RichToken])
}
type WarningMap = Map Name (Doc Name)
-- | A subset of the fields of 'Interface' that we store in the interface
-- files.
data InstalledInterface = InstalledInterface
{
-- | The module represented by this interface.
instMod :: Module
-- | Textual information about the module.
, instInfo :: HaddockModInfo Name
-- | Documentation of declarations originating from the module (including
-- subordinates).
, instDocMap :: DocMap Name
, instArgMap :: ArgMap Name
-- | All names exported by this module.
, instExports :: [Name]
-- | All \"visible\" names exported by the module.
-- A visible name is a name that will show up in the documentation of the
-- module.
, instVisibleExports :: [Name]
-- | Haddock options for this module (prune, ignore-exports, etc).
, instOptions :: [DocOption]
, instSubMap :: Map Name [Name]
, instFixMap :: Map Name Fixity
}
-- | Convert an 'Interface' to an 'InstalledInterface'
toInstalledIface :: Interface -> InstalledInterface
toInstalledIface interface = InstalledInterface
{ instMod = ifaceMod interface
, instInfo = ifaceInfo interface
, instDocMap = ifaceDocMap interface
, instArgMap = ifaceArgMap interface
, instExports = ifaceExports interface
, instVisibleExports = ifaceVisibleExports interface
, instOptions = ifaceOptions interface
, instSubMap = ifaceSubMap interface
, instFixMap = ifaceFixMap interface
}
-----------------------------------------------------------------------------
-- * Export items & declarations
-----------------------------------------------------------------------------
data ExportItem name
-- | An exported declaration.
= ExportDecl
{
-- | A declaration.
expItemDecl :: !(LHsDecl name)
-- | Maybe a doc comment, and possibly docs for arguments (if this
-- decl is a function or type-synonym).
, expItemMbDoc :: !(DocForDecl name)
-- | Subordinate names, possibly with documentation.
, expItemSubDocs :: ![(name, DocForDecl name)]
-- | Instances relevant to this declaration, possibly with
-- documentation.
, expItemInstances :: ![DocInstance name]
-- | Fixity decls relevant to this declaration (including subordinates).
, expItemFixities :: ![(name, Fixity)]
-- | Whether the ExportItem is from a TH splice or not, for generating
-- the appropriate type of Source link.
, expItemSpliced :: !Bool
}
-- | An exported entity for which we have no documentation (perhaps because it
-- resides in another package).
| ExportNoDecl
{ expItemName :: !name
-- | Subordinate names.
, expItemSubs :: ![name]
}
-- | A section heading.
| ExportGroup
{
-- | Section level (1, 2, 3, ...).
expItemSectionLevel :: !Int
-- | Section id (for hyperlinks).
, expItemSectionId :: !String
-- | Section heading text.
, expItemSectionText :: !(Doc name)
}
-- | Some documentation.
| ExportDoc !(MDoc name)
-- | A cross-reference to another module.
| ExportModule !Module
data Documentation name = Documentation
{ documentationDoc :: Maybe (MDoc name)
, documentationWarning :: !(Maybe (Doc name))
} deriving Functor
-- | Arguments and result are indexed by Int, zero-based from the left,
-- because that's the easiest to use when recursing over types.
type FnArgsDoc name = Map Int (MDoc name)
type DocForDecl name = (Documentation name, FnArgsDoc name)
noDocForDecl :: DocForDecl name
noDocForDecl = (Documentation Nothing Nothing, Map.empty)
unrenameDocForDecl :: DocForDecl DocName -> DocForDecl Name
unrenameDocForDecl (doc, fnArgsDoc) =
(fmap getName doc, (fmap . fmap) getName fnArgsDoc)
-----------------------------------------------------------------------------
-- * Cross-referencing
-----------------------------------------------------------------------------
-- | Type of environment used to cross-reference identifiers in the syntax.
type LinkEnv = Map Name Module
-- | Extends 'Name' with cross-reference information.
data DocName
= Documented Name Module
-- ^ This thing is part of the (existing or resulting)
-- documentation. The 'Module' is the preferred place
-- in the documentation to refer to.
| Undocumented Name
-- ^ This thing is not part of the (existing or resulting)
-- documentation, as far as Haddock knows.
deriving (Eq, Data)
type instance PostRn DocName NameSet = PlaceHolder
type instance PostRn DocName Fixity = PlaceHolder
type instance PostRn DocName Bool = PlaceHolder
type instance PostRn DocName [Name] = PlaceHolder
type instance PostTc DocName Kind = PlaceHolder
type instance PostTc DocName Type = PlaceHolder
type instance PostTc DocName Coercion = PlaceHolder
instance NamedThing DocName where
getName (Documented name _) = name
getName (Undocumented name) = name
class NamedThing name => SetName name where
setName :: Name -> name -> name
instance SetName Name where
setName name' _ = name'
instance SetName DocName where
setName name' (Documented _ mdl) = Documented name' mdl
setName name' (Undocumented _) = Undocumented name'
-----------------------------------------------------------------------------
-- * Instances
-----------------------------------------------------------------------------
-- | The three types of instances
data InstType name
= ClassInst
{ clsiCtx :: [HsType name]
, clsiTyVars :: LHsTyVarBndrs name
, clsiSigs :: [Sig name]
, clsiAssocTys :: [PseudoFamilyDecl name]
}
| TypeInst (Maybe (HsType name)) -- ^ Body (right-hand side)
| DataInst (TyClDecl name) -- ^ Data constructors
instance OutputableBndr a => Outputable (InstType a) where
ppr (ClassInst { .. }) = text "ClassInst"
<+> ppr clsiCtx
<+> ppr clsiTyVars
<+> ppr clsiSigs
ppr (TypeInst a) = text "TypeInst" <+> ppr a
ppr (DataInst a) = text "DataInst" <+> ppr a
-- | Almost the same as 'FamilyDecl' except for type binders.
--
-- In order to perform type specialization for class instances, we need to
-- substitute class variables to appropriate type. However, type variables in
-- associated type are specified using 'LHsTyVarBndrs' instead of 'HsType'.
-- This makes type substitution impossible and to overcome this issue,
-- 'PseudoFamilyDecl' type is introduced.
data PseudoFamilyDecl name = PseudoFamilyDecl
{ pfdInfo :: FamilyInfo name
, pfdLName :: Located name
, pfdTyVars :: [LHsType name]
, pfdKindSig :: Maybe (LHsKind name)
}
mkPseudoFamilyDecl :: FamilyDecl name -> PseudoFamilyDecl name
mkPseudoFamilyDecl (FamilyDecl { .. }) = PseudoFamilyDecl
{ pfdInfo = fdInfo
, pfdLName = fdLName
, pfdTyVars = [ L loc (mkType bndr) | L loc bndr <- hsq_tvs fdTyVars ]
, pfdKindSig = fdKindSig
}
where
mkType (KindedTyVar (L loc name) lkind) =
HsKindSig tvar lkind
where
tvar = L loc (HsTyVar name)
mkType (UserTyVar name) = HsTyVar name
-- | An instance head that may have documentation and a source location.
type DocInstance name = (InstHead name, Maybe (MDoc name), Located name)
-- | The head of an instance. Consists of a class name, a list of kind
-- parameters, a list of type parameters and an instance type
data InstHead name = InstHead
{ ihdClsName :: name
, ihdKinds :: [HsType name]
, ihdTypes :: [HsType name]
, ihdInstType :: InstType name
}
-- | An instance origin information.
--
-- This is used primarily in HTML backend to generate unique instance
-- identifiers (for expandable sections).
data InstOrigin name
= OriginClass name
| OriginData name
| OriginFamily name
instance NamedThing name => NamedThing (InstOrigin name) where
getName (OriginClass name) = getName name
getName (OriginData name) = getName name
getName (OriginFamily name) = getName name
-----------------------------------------------------------------------------
-- * Documentation comments
-----------------------------------------------------------------------------
type LDoc id = Located (Doc id)
type Doc id = DocH (ModuleName, OccName) id
type MDoc id = MetaDoc (ModuleName, OccName) id
instance (NFData a, NFData mod)
=> NFData (DocH mod a) where
rnf doc = case doc of
DocEmpty -> ()
DocAppend a b -> a `deepseq` b `deepseq` ()
DocString a -> a `deepseq` ()
DocParagraph a -> a `deepseq` ()
DocIdentifier a -> a `deepseq` ()
DocIdentifierUnchecked a -> a `deepseq` ()
DocModule a -> a `deepseq` ()
DocWarning a -> a `deepseq` ()
DocEmphasis a -> a `deepseq` ()
DocBold a -> a `deepseq` ()
DocMonospaced a -> a `deepseq` ()
DocUnorderedList a -> a `deepseq` ()
DocOrderedList a -> a `deepseq` ()
DocDefList a -> a `deepseq` ()
DocCodeBlock a -> a `deepseq` ()
DocHyperlink a -> a `deepseq` ()
DocPic a -> a `deepseq` ()
DocAName a -> a `deepseq` ()
DocProperty a -> a `deepseq` ()
DocExamples a -> a `deepseq` ()
DocHeader a -> a `deepseq` ()
instance NFData Name where rnf x = seq x ()
instance NFData OccName where rnf x = seq x ()
instance NFData ModuleName where rnf x = seq x ()
instance NFData id => NFData (Header id) where
rnf (Header a b) = a `deepseq` b `deepseq` ()
instance NFData Hyperlink where
rnf (Hyperlink a b) = a `deepseq` b `deepseq` ()
instance NFData Picture where
rnf (Picture a b) = a `deepseq` b `deepseq` ()
instance NFData Example where
rnf (Example a b) = a `deepseq` b `deepseq` ()
exampleToString :: Example -> String
exampleToString (Example expression result) =
">>> " ++ expression ++ "\n" ++ unlines result
data DocMarkup id a = Markup
{ markupEmpty :: a
, markupString :: String -> a
, markupParagraph :: a -> a
, markupAppend :: a -> a -> a
, markupIdentifier :: id -> a
, markupIdentifierUnchecked :: (ModuleName, OccName) -> a
, markupModule :: String -> a
, markupWarning :: a -> a
, markupEmphasis :: a -> a
, markupBold :: a -> a
, markupMonospaced :: a -> a
, markupUnorderedList :: [a] -> a
, markupOrderedList :: [a] -> a
, markupDefList :: [(a,a)] -> a
, markupCodeBlock :: a -> a
, markupHyperlink :: Hyperlink -> a
, markupAName :: String -> a
, markupPic :: Picture -> a
, markupProperty :: String -> a
, markupExample :: [Example] -> a
, markupHeader :: Header a -> a
}
data HaddockModInfo name = HaddockModInfo
{ hmi_description :: Maybe (Doc name)
, hmi_copyright :: Maybe String
, hmi_license :: Maybe String
, hmi_maintainer :: Maybe String
, hmi_stability :: Maybe String
, hmi_portability :: Maybe String
, hmi_safety :: Maybe String
, hmi_language :: Maybe Language
, hmi_extensions :: [ExtensionFlag]
}
emptyHaddockModInfo :: HaddockModInfo a
emptyHaddockModInfo = HaddockModInfo
{ hmi_description = Nothing
, hmi_copyright = Nothing
, hmi_license = Nothing
, hmi_maintainer = Nothing
, hmi_stability = Nothing
, hmi_portability = Nothing
, hmi_safety = Nothing
, hmi_language = Nothing
, hmi_extensions = []
}
-----------------------------------------------------------------------------
-- * Options
-----------------------------------------------------------------------------
{-! for DocOption derive: Binary !-}
-- | Source-level options for controlling the documentation.
data DocOption
= OptHide -- ^ This module should not appear in the docs.
| OptPrune
| OptIgnoreExports -- ^ Pretend everything is exported.
| OptNotHome -- ^ Not the best place to get docs for things
-- exported by this module.
| OptShowExtensions -- ^ Render enabled extensions for this module.
deriving (Eq, Show)
-- | Option controlling how to qualify names
data QualOption
= OptNoQual -- ^ Never qualify any names.
| OptFullQual -- ^ Qualify all names fully.
| OptLocalQual -- ^ Qualify all imported names fully.
| OptRelativeQual -- ^ Like local, but strip module prefix
-- from modules in the same hierarchy.
| OptAliasedQual -- ^ Uses aliases of module names
-- as suggested by module import renamings.
-- However, we are unfortunately not able
-- to maintain the original qualifications.
-- Image a re-export of a whole module,
-- how could the re-exported identifiers be qualified?
type AliasMap = Map Module ModuleName
data Qualification
= NoQual
| FullQual
| LocalQual Module
| RelativeQual Module
| AliasedQual AliasMap Module
-- ^ @Module@ contains the current module.
-- This way we can distinguish imported and local identifiers.
makeContentsQual :: QualOption -> Qualification
makeContentsQual qual =
case qual of
OptNoQual -> NoQual
_ -> FullQual
makeModuleQual :: QualOption -> AliasMap -> Module -> Qualification
makeModuleQual qual aliases mdl =
case qual of
OptLocalQual -> LocalQual mdl
OptRelativeQual -> RelativeQual mdl
OptAliasedQual -> AliasedQual aliases mdl
OptFullQual -> FullQual
OptNoQual -> NoQual
-----------------------------------------------------------------------------
-- * Error handling
-----------------------------------------------------------------------------
-- A monad which collects error messages, locally defined to avoid a dep on mtl
type ErrMsg = String
newtype ErrMsgM a = Writer { runWriter :: (a, [ErrMsg]) }
instance Functor ErrMsgM where
fmap f (Writer (a, msgs)) = Writer (f a, msgs)
instance Applicative ErrMsgM where
pure = return
(<*>) = ap
instance Monad ErrMsgM where
return a = Writer (a, [])
m >>= k = Writer $ let
(a, w) = runWriter m
(b, w') = runWriter (k a)
in (b, w ++ w')
tell :: [ErrMsg] -> ErrMsgM ()
tell w = Writer ((), w)
-- Exceptions
-- | Haddock's own exception type.
data HaddockException = HaddockException String deriving Typeable
instance Show HaddockException where
show (HaddockException str) = str
throwE :: String -> a
instance Exception HaddockException
throwE str = throw (HaddockException str)
-- In "Haddock.Interface.Create", we need to gather
-- @Haddock.Types.ErrMsg@s a lot, like @ErrMsgM@ does,
-- but we can't just use @GhcT ErrMsgM@ because GhcT requires the
-- transformed monad to be MonadIO.
newtype ErrMsgGhc a = WriterGhc { runWriterGhc :: Ghc (a, [ErrMsg]) }
--instance MonadIO ErrMsgGhc where
-- liftIO = WriterGhc . fmap (\a->(a,[])) liftIO
--er, implementing GhcMonad involves annoying ExceptionMonad and
--WarnLogMonad classes, so don't bother.
liftGhcToErrMsgGhc :: Ghc a -> ErrMsgGhc a
liftGhcToErrMsgGhc = WriterGhc . fmap (\a->(a,[]))
liftErrMsg :: ErrMsgM a -> ErrMsgGhc a
liftErrMsg = WriterGhc . return . runWriter
-- for now, use (liftErrMsg . tell) for this
--tell :: [ErrMsg] -> ErrMsgGhc ()
--tell msgs = WriterGhc $ return ( (), msgs )
instance Functor ErrMsgGhc where
fmap f (WriterGhc x) = WriterGhc (fmap (first f) x)
instance Applicative ErrMsgGhc where
pure = return
(<*>) = ap
instance Monad ErrMsgGhc where
return a = WriterGhc (return (a, []))
m >>= k = WriterGhc $ runWriterGhc m >>= \ (a, msgs1) ->
fmap (second (msgs1 ++)) (runWriterGhc (k a))
|
lamefun/haddock
|
haddock-api/src/Haddock/Types.hs
|
bsd-2-clause
| 21,158 | 0 | 13 | 5,294 | 3,986 | 2,268 | 1,718 | 399 | 5 |
{-# LANGUAGE FlexibleContexts #-}
module Control.Search.Combinator.Repeat (repeat) where
import Prelude hiding (lex, until, init, repeat)
import Control.Search.Language
import Control.Search.GeneratorInfo
import Control.Search.Generator
import Control.Search.MemoReader
import Control.Search.Memo
import Control.Monatron.Monatron hiding (Abort, L, state, cont)
import Control.Monatron.Zipper hiding (i,r)
repeatLoop :: (ReaderM Bool m, Evalable m) => Int -> Eval m -> Eval m
repeatLoop uid super = commentEval $
Eval
{
structs = structs super @++@ mystructs
, toString = "repeat" ++ show uid ++ "(" ++ toString super ++ ")"
, treeState_ = ("dummy", Int,
\i -> do cc <- cachedClone i (cloneBase i)
return ((parent i <== baseTstate i)
>>> cc
)
) : treeState_ super -- `withClone` (\k -> inc $ ref_count k)
, initH = \i -> initE super i
, evalState_ = {- ("cont",Bool,const $ return true) : -} ("ref_count",Int,const $ return 1) : ("parent",THook "TreeState",const $ return Null) : evalState_ super
, pushLeftH = push pushLeft
, pushRightH = push pushRight
, nextSameH = nextSame super
, nextDiffH = nextDiff super
, bodyH = \i -> dec_ref i >>= \deref -> bodyE super (i `onAbort` deref)
, addH = addE super
, failH = \i -> failE super i @>>>@ dec_ref i
, returnH = \i -> let j deref = i `onCommit` deref
in dec_ref i >>= returnE super . j
, tryH = tryE super
, startTryH = startTryE super
, tryLH = \i -> tryE_ super i @>>>@ dec_ref i
, boolArraysE = boolArraysE super
, intArraysE = intArraysE super
, intVarsE = intVarsE super
, deleteH = error "repeatLoop.deleteE NOT YET IMPLEMENTED"
, canBranch = canBranch super
, complete = const $ return true
}
where mystructs = ([],[])
fs1 = [(field,init) | (field,ty,init) <- evalState_ super]
parent = \i -> estate i @=> "parent"
dec_ref = \i -> let i' = resetCommit $ i `withBase` ("repeat_tstate" ++ show uid)
in do flag <- ask
if flag
then local (const False) $ do
stmt1 <- inits super i'
stmt2 <- startTryE super i'
ini <- inite fs1 i'
return (dec (ref_count i)
>>> ifthen (ref_count i @== 0)
( SHook ("TreeState repeat_tstate" ++ show uid ++ ";")
>>> (baseTstate i' <== parent i)
>>> clone (cloneBase i) i'
>>> (ref_count i' <== 1)
-- >>> (cont i' <== true)
>>> ini >>> stmt1 >>> stmt2))
else return $dec (ref_count i) >>> ifthen (ref_count i @== 0) (comment "Delete-repeatLoop-dec_ref" >>> Delete (space $ cloneBase i))
push dir = \i -> dir super (i `onCommit` inc (ref_count i))
repeat
:: Search
-> Search
repeat s =
case s of
Search { mkeval = evals, runsearch = runs } ->
Search { mkeval =
\super ->
do { uid <- get
; put (uid + 1)
; s' <- evals $ mapE (L . L . mmap runL . runL) super
; return $ mapE (L . mmap L . runL) $ repeatLoop uid $ mapE runL s'
}
, runsearch = runs . rReaderT True . runL
}
|
neothemachine/monadiccp
|
src/Control/Search/Combinator/Repeat.hs
|
bsd-3-clause
| 3,797 | 26 | 32 | 1,540 | 1,150 | 614 | 536 | 72 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[RnBinds]{Renaming and dependency analysis of bindings}
This module does renaming and dependency analysis on value bindings in
the abstract syntax. It does {\em not} do cycle-checks on class or
type-synonym declarations; those cannot be done at this stage because
they may be affected by renaming (which isn't fully worked out yet).
-}
module RnBinds (
-- Renaming top-level bindings
rnTopBindsLHS, rnTopBindsBoot, rnValBindsRHS,
-- Renaming local bindings
rnLocalBindsAndThen, rnLocalValBindsLHS, rnLocalValBindsRHS,
-- Other bindings
rnMethodBinds, renameSigs,
rnMatchGroup, rnGRHSs, rnGRHS,
makeMiniFixityEnv, MiniFixityEnv,
HsSigCtxt(..)
) where
import {-# SOURCE #-} RnExpr( rnLExpr, rnStmts )
import HsSyn
import TcRnMonad
import TcEvidence ( emptyTcEvBinds )
import RnTypes
import RnPat
import RnNames
import RnEnv
import DynFlags
import Module
import Name
import NameEnv
import NameSet
import RdrName ( RdrName, rdrNameOcc )
import SrcLoc
import ListSetOps ( findDupsEq )
import BasicTypes ( RecFlag(..) )
import Digraph ( SCC(..) )
import Bag
import Util
import Outputable
import FastString
import UniqFM
import Maybes ( orElse )
import qualified GHC.LanguageExtensions as LangExt
import Control.Monad
import Data.List ( partition, sort )
{-
-- ToDo: Put the annotations into the monad, so that they arrive in the proper
-- place and can be used when complaining.
The code tree received by the function @rnBinds@ contains definitions
in where-clauses which are all apparently mutually recursive, but which may
not really depend upon each other. For example, in the top level program
\begin{verbatim}
f x = y where a = x
y = x
\end{verbatim}
the definitions of @a@ and @y@ do not depend on each other at all.
Unfortunately, the typechecker cannot always check such definitions.
\footnote{Mycroft, A. 1984. Polymorphic type schemes and recursive
definitions. In Proceedings of the International Symposium on Programming,
Toulouse, pp. 217-39. LNCS 167. Springer Verlag.}
However, the typechecker usually can check definitions in which only the
strongly connected components have been collected into recursive bindings.
This is precisely what the function @rnBinds@ does.
ToDo: deal with case where a single monobinds binds the same variable
twice.
The vertag tag is a unique @Int@; the tags only need to be unique
within one @MonoBinds@, so that unique-Int plumbing is done explicitly
(heavy monad machinery not needed).
************************************************************************
* *
* naming conventions *
* *
************************************************************************
\subsection[name-conventions]{Name conventions}
The basic algorithm involves walking over the tree and returning a tuple
containing the new tree plus its free variables. Some functions, such
as those walking polymorphic bindings (HsBinds) and qualifier lists in
list comprehensions (@Quals@), return the variables bound in local
environments. These are then used to calculate the free variables of the
expression evaluated in these environments.
Conventions for variable names are as follows:
\begin{itemize}
\item
new code is given a prime to distinguish it from the old.
\item
a set of variables defined in @Exp@ is written @dvExp@
\item
a set of variables free in @Exp@ is written @fvExp@
\end{itemize}
************************************************************************
* *
* analysing polymorphic bindings (HsBindGroup, HsBind)
* *
************************************************************************
\subsubsection[dep-HsBinds]{Polymorphic bindings}
Non-recursive expressions are reconstructed without any changes at top
level, although their component expressions may have to be altered.
However, non-recursive expressions are currently not expected as
\Haskell{} programs, and this code should not be executed.
Monomorphic bindings contain information that is returned in a tuple
(a @FlatMonoBinds@) containing:
\begin{enumerate}
\item
a unique @Int@ that serves as the ``vertex tag'' for this binding.
\item
the name of a function or the names in a pattern. These are a set
referred to as @dvLhs@, the defined variables of the left hand side.
\item
the free variables of the body. These are referred to as @fvBody@.
\item
the definition's actual code. This is referred to as just @code@.
\end{enumerate}
The function @nonRecDvFv@ returns two sets of variables. The first is
the set of variables defined in the set of monomorphic bindings, while the
second is the set of free variables in those bindings.
The set of variables defined in a non-recursive binding is just the
union of all of them, as @union@ removes duplicates. However, the
free variables in each successive set of cumulative bindings is the
union of those in the previous set plus those of the newest binding after
the defined variables of the previous set have been removed.
@rnMethodBinds@ deals only with the declarations in class and
instance declarations. It expects only to see @FunMonoBind@s, and
it expects the global environment to contain bindings for the binders
(which are all class operations).
************************************************************************
* *
\subsubsection{ Top-level bindings}
* *
************************************************************************
-}
-- for top-level bindings, we need to make top-level names,
-- so we have a different entry point than for local bindings
rnTopBindsLHS :: MiniFixityEnv
-> HsValBinds RdrName
-> RnM (HsValBindsLR Name RdrName)
rnTopBindsLHS fix_env binds
= rnValBindsLHS (topRecNameMaker fix_env) binds
rnTopBindsBoot :: NameSet -> HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses)
-- A hs-boot file has no bindings.
-- Return a single HsBindGroup with empty binds and renamed signatures
rnTopBindsBoot bound_names (ValBindsIn mbinds sigs)
= do { checkErr (isEmptyLHsBinds mbinds) (bindsInHsBootFile mbinds)
; (sigs', fvs) <- renameSigs (HsBootCtxt bound_names) sigs
; return (ValBindsOut [] sigs', usesOnly fvs) }
rnTopBindsBoot _ b = pprPanic "rnTopBindsBoot" (ppr b)
{-
*********************************************************
* *
HsLocalBinds
* *
*********************************************************
-}
rnLocalBindsAndThen :: HsLocalBinds RdrName
-> (HsLocalBinds Name -> FreeVars -> RnM (result, FreeVars))
-> RnM (result, FreeVars)
-- This version (a) assumes that the binding vars are *not* already in scope
-- (b) removes the binders from the free vars of the thing inside
-- The parser doesn't produce ThenBinds
rnLocalBindsAndThen EmptyLocalBinds thing_inside =
thing_inside EmptyLocalBinds emptyNameSet
rnLocalBindsAndThen (HsValBinds val_binds) thing_inside
= rnLocalValBindsAndThen val_binds $ \ val_binds' ->
thing_inside (HsValBinds val_binds')
rnLocalBindsAndThen (HsIPBinds binds) thing_inside = do
(binds',fv_binds) <- rnIPBinds binds
(thing, fvs_thing) <- thing_inside (HsIPBinds binds') fv_binds
return (thing, fvs_thing `plusFV` fv_binds)
rnIPBinds :: HsIPBinds RdrName -> RnM (HsIPBinds Name, FreeVars)
rnIPBinds (IPBinds ip_binds _no_dict_binds) = do
(ip_binds', fvs_s) <- mapAndUnzipM (wrapLocFstM rnIPBind) ip_binds
return (IPBinds ip_binds' emptyTcEvBinds, plusFVs fvs_s)
rnIPBind :: IPBind RdrName -> RnM (IPBind Name, FreeVars)
rnIPBind (IPBind ~(Left n) expr) = do
(expr',fvExpr) <- rnLExpr expr
return (IPBind (Left n) expr', fvExpr)
{-
************************************************************************
* *
ValBinds
* *
************************************************************************
-}
-- Renaming local binding groups
-- Does duplicate/shadow check
rnLocalValBindsLHS :: MiniFixityEnv
-> HsValBinds RdrName
-> RnM ([Name], HsValBindsLR Name RdrName)
rnLocalValBindsLHS fix_env binds
= do { binds' <- rnValBindsLHS (localRecNameMaker fix_env) binds
-- Check for duplicates and shadowing
-- Must do this *after* renaming the patterns
-- See Note [Collect binders only after renaming] in HsUtils
-- We need to check for dups here because we
-- don't don't bind all of the variables from the ValBinds at once
-- with bindLocatedLocals any more.
--
-- Note that we don't want to do this at the top level, since
-- sorting out duplicates and shadowing there happens elsewhere.
-- The behavior is even different. For example,
-- import A(f)
-- f = ...
-- should not produce a shadowing warning (but it will produce
-- an ambiguity warning if you use f), but
-- import A(f)
-- g = let f = ... in f
-- should.
; let bound_names = collectHsValBinders binds'
-- There should be only Ids, but if there are any bogus
-- pattern synonyms, we'll collect them anyway, so that
-- we don't generate subsequent out-of-scope messages
; envs <- getRdrEnvs
; checkDupAndShadowedNames envs bound_names
; return (bound_names, binds') }
-- renames the left-hand sides
-- generic version used both at the top level and for local binds
-- does some error checking, but not what gets done elsewhere at the top level
rnValBindsLHS :: NameMaker
-> HsValBinds RdrName
-> RnM (HsValBindsLR Name RdrName)
rnValBindsLHS topP (ValBindsIn mbinds sigs)
= do { mbinds' <- mapBagM (wrapLocM (rnBindLHS topP doc)) mbinds
; return $ ValBindsIn mbinds' sigs }
where
bndrs = collectHsBindsBinders mbinds
doc = text "In the binding group for:" <+> pprWithCommas ppr bndrs
rnValBindsLHS _ b = pprPanic "rnValBindsLHSFromDoc" (ppr b)
-- General version used both from the top-level and for local things
-- Assumes the LHS vars are in scope
--
-- Does not bind the local fixity declarations
rnValBindsRHS :: HsSigCtxt
-> HsValBindsLR Name RdrName
-> RnM (HsValBinds Name, DefUses)
rnValBindsRHS ctxt (ValBindsIn mbinds sigs)
= do { (sigs', sig_fvs) <- renameSigs ctxt sigs
; binds_w_dus <- mapBagM (rnLBind (mkSigTvFn sigs')) mbinds
; case depAnalBinds binds_w_dus of
(anal_binds, anal_dus) -> return (valbind', valbind'_dus)
where
valbind' = ValBindsOut anal_binds sigs'
valbind'_dus = anal_dus `plusDU` usesOnly sig_fvs
-- Put the sig uses *after* the bindings
-- so that the binders are removed from
-- the uses in the sigs
}
rnValBindsRHS _ b = pprPanic "rnValBindsRHS" (ppr b)
-- Wrapper for local binds
--
-- The *client* of this function is responsible for checking for unused binders;
-- it doesn't (and can't: we don't have the thing inside the binds) happen here
--
-- The client is also responsible for bringing the fixities into scope
rnLocalValBindsRHS :: NameSet -- names bound by the LHSes
-> HsValBindsLR Name RdrName
-> RnM (HsValBinds Name, DefUses)
rnLocalValBindsRHS bound_names binds
= rnValBindsRHS (LocalBindCtxt bound_names) binds
-- for local binds
-- wrapper that does both the left- and right-hand sides
--
-- here there are no local fixity decls passed in;
-- the local fixity decls come from the ValBinds sigs
rnLocalValBindsAndThen
:: HsValBinds RdrName
-> (HsValBinds Name -> FreeVars -> RnM (result, FreeVars))
-> RnM (result, FreeVars)
rnLocalValBindsAndThen binds@(ValBindsIn _ sigs) thing_inside
= do { -- (A) Create the local fixity environment
new_fixities <- makeMiniFixityEnv [L loc sig
| L loc (FixSig sig) <- sigs]
-- (B) Rename the LHSes
; (bound_names, new_lhs) <- rnLocalValBindsLHS new_fixities binds
-- ...and bring them (and their fixities) into scope
; bindLocalNamesFV bound_names $
addLocalFixities new_fixities bound_names $ do
{ -- (C) Do the RHS and thing inside
(binds', dus) <- rnLocalValBindsRHS (mkNameSet bound_names) new_lhs
; (result, result_fvs) <- thing_inside binds' (allUses dus)
-- Report unused bindings based on the (accurate)
-- findUses. E.g.
-- let x = x in 3
-- should report 'x' unused
; let real_uses = findUses dus result_fvs
-- Insert fake uses for variables introduced implicitly by
-- wildcards (#4404)
implicit_uses = hsValBindsImplicits binds'
; warnUnusedLocalBinds bound_names
(real_uses `unionNameSet` implicit_uses)
; let
-- The variables "used" in the val binds are:
-- (1) the uses of the binds (allUses)
-- (2) the FVs of the thing-inside
all_uses = allUses dus `plusFV` result_fvs
-- Note [Unused binding hack]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Note that *in contrast* to the above reporting of
-- unused bindings, (1) above uses duUses to return *all*
-- the uses, even if the binding is unused. Otherwise consider:
-- x = 3
-- y = let p = x in 'x' -- NB: p not used
-- If we don't "see" the dependency of 'y' on 'x', we may put the
-- bindings in the wrong order, and the type checker will complain
-- that x isn't in scope
--
-- But note that this means we won't report 'x' as unused,
-- whereas we would if we had { x = 3; p = x; y = 'x' }
; return (result, all_uses) }}
-- The bound names are pruned out of all_uses
-- by the bindLocalNamesFV call above
rnLocalValBindsAndThen bs _ = pprPanic "rnLocalValBindsAndThen" (ppr bs)
---------------------
-- renaming a single bind
rnBindLHS :: NameMaker
-> SDoc
-> HsBind RdrName
-- returns the renamed left-hand side,
-- and the FreeVars *of the LHS*
-- (i.e., any free variables of the pattern)
-> RnM (HsBindLR Name RdrName)
rnBindLHS name_maker _ bind@(PatBind { pat_lhs = pat })
= do
-- we don't actually use the FV processing of rnPatsAndThen here
(pat',pat'_fvs) <- rnBindPat name_maker pat
return (bind { pat_lhs = pat', bind_fvs = pat'_fvs })
-- We temporarily store the pat's FVs in bind_fvs;
-- gets updated to the FVs of the whole bind
-- when doing the RHS below
rnBindLHS name_maker _ bind@(FunBind { fun_id = rdr_name })
= do { name <- applyNameMaker name_maker rdr_name
; return (bind { fun_id = name
, bind_fvs = placeHolderNamesTc }) }
rnBindLHS name_maker _ (PatSynBind psb@PSB{ psb_id = rdrname })
| isTopRecNameMaker name_maker
= do { addLocM checkConName rdrname
; name <- lookupLocatedTopBndrRn rdrname -- Should be in scope already
; return (PatSynBind psb{ psb_id = name }) }
| otherwise -- Pattern synonym, not at top level
= do { addErr localPatternSynonymErr -- Complain, but make up a fake
-- name so that we can carry on
; name <- applyNameMaker name_maker rdrname
; return (PatSynBind psb{ psb_id = name }) }
where
localPatternSynonymErr :: SDoc
localPatternSynonymErr
= hang (text "Illegal pattern synonym declaration for" <+> quotes (ppr rdrname))
2 (text "Pattern synonym declarations are only valid at top level")
rnBindLHS _ _ b = pprPanic "rnBindHS" (ppr b)
rnLBind :: (Name -> [Name]) -- Signature tyvar function
-> LHsBindLR Name RdrName
-> RnM (LHsBind Name, [Name], Uses)
rnLBind sig_fn (L loc bind)
= setSrcSpan loc $
do { (bind', bndrs, dus) <- rnBind sig_fn bind
; return (L loc bind', bndrs, dus) }
-- assumes the left-hands-side vars are in scope
rnBind :: (Name -> [Name]) -- Signature tyvar function
-> HsBindLR Name RdrName
-> RnM (HsBind Name, [Name], Uses)
rnBind _ bind@(PatBind { pat_lhs = pat
, pat_rhs = grhss
-- pat fvs were stored in bind_fvs
-- after processing the LHS
, bind_fvs = pat_fvs })
= do { mod <- getModule
; (grhss', rhs_fvs) <- rnGRHSs PatBindRhs rnLExpr grhss
-- No scoped type variables for pattern bindings
; let all_fvs = pat_fvs `plusFV` rhs_fvs
fvs' = filterNameSet (nameIsLocalOrFrom mod) all_fvs
-- Keep locally-defined Names
-- As well as dependency analysis, we need these for the
-- MonoLocalBinds test in TcBinds.decideGeneralisationPlan
bndrs = collectPatBinders pat
bind' = bind { pat_rhs = grhss',
pat_rhs_ty = placeHolderType, bind_fvs = fvs' }
is_wild_pat = case pat of
L _ (WildPat {}) -> True
L _ (BangPat (L _ (WildPat {}))) -> True -- #9127
_ -> False
-- Warn if the pattern binds no variables, except for the
-- entirely-explicit idiom _ = rhs
-- which (a) is not that different from _v = rhs
-- (b) is sometimes used to give a type sig for,
-- or an occurrence of, a variable on the RHS
; whenWOptM Opt_WarnUnusedPatternBinds $
when (null bndrs && not is_wild_pat) $
addWarn (Reason Opt_WarnUnusedPatternBinds) $ unusedPatBindWarn bind'
; fvs' `seq` -- See Note [Free-variable space leak]
return (bind', bndrs, all_fvs) }
rnBind sig_fn bind@(FunBind { fun_id = name
, fun_matches = matches })
-- invariant: no free vars here when it's a FunBind
= do { let plain_name = unLoc name
; (matches', rhs_fvs) <- bindSigTyVarsFV (sig_fn plain_name) $
-- bindSigTyVars tests for LangExt.ScopedTyVars
rnMatchGroup (FunRhs name Prefix)
rnLExpr matches
; let is_infix = isInfixFunBind bind
; when is_infix $ checkPrecMatch plain_name matches'
; mod <- getModule
; let fvs' = filterNameSet (nameIsLocalOrFrom mod) rhs_fvs
-- Keep locally-defined Names
-- As well as dependency analysis, we need these for the
-- MonoLocalBinds test in TcBinds.decideGeneralisationPlan
; fvs' `seq` -- See Note [Free-variable space leak]
return (bind { fun_matches = matches'
, bind_fvs = fvs' },
[plain_name], rhs_fvs)
}
rnBind sig_fn (PatSynBind bind)
= do { (bind', name, fvs) <- rnPatSynBind sig_fn bind
; return (PatSynBind bind', name, fvs) }
rnBind _ b = pprPanic "rnBind" (ppr b)
{-
Note [Free-variable space leak]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We have
fvs' = trim fvs
and we seq fvs' before turning it as part of a record.
The reason is that trim is sometimes something like
\xs -> intersectNameSet (mkNameSet bound_names) xs
and we don't want to retain the list bound_names. This showed up in
trac ticket #1136.
-}
{- *********************************************************************
* *
Dependency analysis and other support functions
* *
********************************************************************* -}
depAnalBinds :: Bag (LHsBind Name, [Name], Uses)
-> ([(RecFlag, LHsBinds Name)], DefUses)
-- Dependency analysis; this is important so that
-- unused-binding reporting is accurate
depAnalBinds binds_w_dus
= (map get_binds sccs, map get_du sccs)
where
sccs = depAnal (\(_, defs, _) -> defs)
(\(_, _, uses) -> nonDetEltsUFM uses)
-- It's OK to use nonDetEltsUFM here as explained in
-- Note [depAnal determinism] in NameEnv.
(bagToList binds_w_dus)
get_binds (AcyclicSCC (bind, _, _)) = (NonRecursive, unitBag bind)
get_binds (CyclicSCC binds_w_dus) = (Recursive, listToBag [b | (b,_,_) <- binds_w_dus])
get_du (AcyclicSCC (_, bndrs, uses)) = (Just (mkNameSet bndrs), uses)
get_du (CyclicSCC binds_w_dus) = (Just defs, uses)
where
defs = mkNameSet [b | (_,bs,_) <- binds_w_dus, b <- bs]
uses = unionNameSets [u | (_,_,u) <- binds_w_dus]
---------------------
-- Bind the top-level forall'd type variables in the sigs.
-- E.g f :: a -> a
-- f = rhs
-- The 'a' scopes over the rhs
--
-- NB: there'll usually be just one (for a function binding)
-- but if there are many, one may shadow the rest; too bad!
-- e.g x :: [a] -> [a]
-- y :: [(a,a)] -> a
-- (x,y) = e
-- In e, 'a' will be in scope, and it'll be the one from 'y'!
mkSigTvFn :: [LSig Name] -> (Name -> [Name])
-- Return a lookup function that maps an Id Name to the names
-- of the type variables that should scope over its body.
mkSigTvFn sigs = \n -> lookupNameEnv env n `orElse` []
where
env = mkHsSigEnv get_scoped_tvs sigs
get_scoped_tvs :: LSig Name -> Maybe ([Located Name], [Name])
-- Returns (binders, scoped tvs for those binders)
get_scoped_tvs (L _ (ClassOpSig _ names sig_ty))
= Just (names, hsScopedTvs sig_ty)
get_scoped_tvs (L _ (TypeSig names sig_ty))
= Just (names, hsWcScopedTvs sig_ty)
get_scoped_tvs (L _ (PatSynSig names sig_ty))
= Just (names, hsScopedTvs sig_ty)
get_scoped_tvs _ = Nothing
-- Process the fixity declarations, making a FastString -> (Located Fixity) map
-- (We keep the location around for reporting duplicate fixity declarations.)
--
-- Checks for duplicates, but not that only locally defined things are fixed.
-- Note: for local fixity declarations, duplicates would also be checked in
-- check_sigs below. But we also use this function at the top level.
makeMiniFixityEnv :: [LFixitySig RdrName] -> RnM MiniFixityEnv
makeMiniFixityEnv decls = foldlM add_one_sig emptyFsEnv decls
where
add_one_sig env (L loc (FixitySig names fixity)) =
foldlM add_one env [ (loc,name_loc,name,fixity)
| L name_loc name <- names ]
add_one env (loc, name_loc, name,fixity) = do
{ -- this fixity decl is a duplicate iff
-- the ReaderName's OccName's FastString is already in the env
-- (we only need to check the local fix_env because
-- definitions of non-local will be caught elsewhere)
let { fs = occNameFS (rdrNameOcc name)
; fix_item = L loc fixity };
case lookupFsEnv env fs of
Nothing -> return $ extendFsEnv env fs fix_item
Just (L loc' _) -> do
{ setSrcSpan loc $
addErrAt name_loc (dupFixityDecl loc' name)
; return env}
}
dupFixityDecl :: SrcSpan -> RdrName -> SDoc
dupFixityDecl loc rdr_name
= vcat [text "Multiple fixity declarations for" <+> quotes (ppr rdr_name),
text "also at " <+> ppr loc]
{- *********************************************************************
* *
Pattern synonym bindings
* *
********************************************************************* -}
rnPatSynBind :: (Name -> [Name]) -- Signature tyvar function
-> PatSynBind Name RdrName
-> RnM (PatSynBind Name Name, [Name], Uses)
rnPatSynBind sig_fn bind@(PSB { psb_id = L l name
, psb_args = details
, psb_def = pat
, psb_dir = dir })
-- invariant: no free vars here when it's a FunBind
= do { pattern_synonym_ok <- xoptM LangExt.PatternSynonyms
; unless pattern_synonym_ok (addErr patternSynonymErr)
; let sig_tvs = sig_fn name
; ((pat', details'), fvs1) <- bindSigTyVarsFV sig_tvs $
rnPat PatSyn pat $ \pat' ->
-- We check the 'RdrName's instead of the 'Name's
-- so that the binding locations are reported
-- from the left-hand side
case details of
PrefixPatSyn vars ->
do { checkDupRdrNames vars
; names <- mapM lookupVar vars
; return ( (pat', PrefixPatSyn names)
, mkFVs (map unLoc names)) }
InfixPatSyn var1 var2 ->
do { checkDupRdrNames [var1, var2]
; name1 <- lookupVar var1
; name2 <- lookupVar var2
-- ; checkPrecMatch -- TODO
; return ( (pat', InfixPatSyn name1 name2)
, mkFVs (map unLoc [name1, name2])) }
RecordPatSyn vars ->
do { checkDupRdrNames (map recordPatSynSelectorId vars)
; let rnRecordPatSynField
(RecordPatSynField { recordPatSynSelectorId = visible
, recordPatSynPatVar = hidden })
= do { visible' <- lookupLocatedTopBndrRn visible
; hidden' <- lookupVar hidden
; return $ RecordPatSynField { recordPatSynSelectorId = visible'
, recordPatSynPatVar = hidden' } }
; names <- mapM rnRecordPatSynField vars
; return ( (pat', RecordPatSyn names)
, mkFVs (map (unLoc . recordPatSynPatVar) names)) }
; (dir', fvs2) <- case dir of
Unidirectional -> return (Unidirectional, emptyFVs)
ImplicitBidirectional -> return (ImplicitBidirectional, emptyFVs)
ExplicitBidirectional mg ->
do { (mg', fvs) <- bindSigTyVarsFV sig_tvs $
rnMatchGroup (FunRhs (L l name) Prefix)
rnLExpr mg
; return (ExplicitBidirectional mg', fvs) }
; mod <- getModule
; let fvs = fvs1 `plusFV` fvs2
fvs' = filterNameSet (nameIsLocalOrFrom mod) fvs
-- Keep locally-defined Names
-- As well as dependency analysis, we need these for the
-- MonoLocalBinds test in TcBinds.decideGeneralisationPlan
; let bind' = bind{ psb_args = details'
, psb_def = pat'
, psb_dir = dir'
, psb_fvs = fvs' }
; let selector_names = case details' of
RecordPatSyn names ->
map (unLoc . recordPatSynSelectorId) names
_ -> []
; fvs' `seq` -- See Note [Free-variable space leak]
return (bind', name : selector_names , fvs1)
-- See Note [Pattern synonym builders don't yield dependencies]
}
where
lookupVar = wrapLocM lookupOccRn
patternSynonymErr :: SDoc
patternSynonymErr
= hang (text "Illegal pattern synonym declaration")
2 (text "Use -XPatternSynonyms to enable this extension")
{-
Note [Pattern synonym builders don't yield dependencies]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When renaming a pattern synonym that has an explicit builder,
references in the builder definition should not be used when
calculating dependencies. For example, consider the following pattern
synonym definition:
pattern P x <- C1 x where
P x = f (C1 x)
f (P x) = C2 x
In this case, 'P' needs to be typechecked in two passes:
1. Typecheck the pattern definition of 'P', which fully determines the
type of 'P'. This step doesn't require knowing anything about 'f',
since the builder definition is not looked at.
2. Typecheck the builder definition, which needs the typechecked
definition of 'f' to be in scope.
This behaviour is implemented in 'tcValBinds', but it crucially
depends on 'P' not being put in a recursive group with 'f' (which
would make it look like a recursive pattern synonym a la 'pattern P =
P' which is unsound and rejected).
-}
{- *********************************************************************
* *
Class/instance method bindings
* *
********************************************************************* -}
{- @rnMethodBinds@ is used for the method bindings of a class and an instance
declaration. Like @rnBinds@ but without dependency analysis.
NOTA BENE: we record each {\em binder} of a method-bind group as a free variable.
That's crucial when dealing with an instance decl:
\begin{verbatim}
instance Foo (T a) where
op x = ...
\end{verbatim}
This might be the {\em sole} occurrence of @op@ for an imported class @Foo@,
and unless @op@ occurs we won't treat the type signature of @op@ in the class
decl for @Foo@ as a source of instance-decl gates. But we should! Indeed,
in many ways the @op@ in an instance decl is just like an occurrence, not
a binder.
-}
rnMethodBinds :: Bool -- True <=> is a class declaration
-> Name -- Class name
-> [Name] -- Type variables from the class/instance header
-> LHsBinds RdrName -- Binds
-> [LSig RdrName] -- and signatures/pragmas
-> RnM (LHsBinds Name, [LSig Name], FreeVars)
-- Used for
-- * the default method bindings in a class decl
-- * the method bindings in an instance decl
rnMethodBinds is_cls_decl cls ktv_names binds sigs
= do { checkDupRdrNames (collectMethodBinders binds)
-- Check that the same method is not given twice in the
-- same instance decl instance C T where
-- f x = ...
-- g y = ...
-- f x = ...
-- We must use checkDupRdrNames because the Name of the
-- method is the Name of the class selector, whose SrcSpan
-- points to the class declaration; and we use rnMethodBinds
-- for instance decls too
-- Rename the bindings LHSs
; binds' <- foldrBagM (rnMethodBindLHS is_cls_decl cls) emptyBag binds
-- Rename the pragmas and signatures
-- Annoyingly the type variables /are/ in scope for signatures, but
-- /are not/ in scope in the SPECIALISE instance pramas; e.g.
-- instance Eq a => Eq (T a) where
-- (==) :: a -> a -> a
-- {-# SPECIALISE instance Eq a => Eq (T [a]) #-}
; let (spec_inst_prags, other_sigs) = partition isSpecInstLSig sigs
bound_nms = mkNameSet (collectHsBindsBinders binds')
sig_ctxt | is_cls_decl = ClsDeclCtxt cls
| otherwise = InstDeclCtxt bound_nms
; (spec_inst_prags', sip_fvs) <- renameSigs sig_ctxt spec_inst_prags
; (other_sigs', sig_fvs) <- extendTyVarEnvFVRn ktv_names $
renameSigs sig_ctxt other_sigs
-- Rename the bindings RHSs. Again there's an issue about whether the
-- type variables from the class/instance head are in scope.
-- Answer no in Haskell 2010, but yes if you have -XScopedTypeVariables
; scoped_tvs <- xoptM LangExt.ScopedTypeVariables
; (binds'', bind_fvs) <- maybe_extend_tyvar_env scoped_tvs $
do { binds_w_dus <- mapBagM (rnLBind (mkSigTvFn other_sigs')) binds'
; let bind_fvs = foldrBag (\(_,_,fv1) fv2 -> fv1 `plusFV` fv2)
emptyFVs binds_w_dus
; return (mapBag fstOf3 binds_w_dus, bind_fvs) }
; return ( binds'', spec_inst_prags' ++ other_sigs'
, sig_fvs `plusFV` sip_fvs `plusFV` bind_fvs) }
where
-- For the method bindings in class and instance decls, we extend
-- the type variable environment iff -XScopedTypeVariables
maybe_extend_tyvar_env scoped_tvs thing_inside
| scoped_tvs = extendTyVarEnvFVRn ktv_names thing_inside
| otherwise = thing_inside
rnMethodBindLHS :: Bool -> Name
-> LHsBindLR RdrName RdrName
-> LHsBindsLR Name RdrName
-> RnM (LHsBindsLR Name RdrName)
rnMethodBindLHS _ cls (L loc bind@(FunBind { fun_id = name })) rest
= setSrcSpan loc $ do
do { sel_name <- wrapLocM (lookupInstDeclBndr cls (text "method")) name
-- We use the selector name as the binder
; let bind' = bind { fun_id = sel_name
, bind_fvs = placeHolderNamesTc }
; return (L loc bind' `consBag` rest ) }
-- Report error for all other forms of bindings
-- This is why we use a fold rather than map
rnMethodBindLHS is_cls_decl _ (L loc bind) rest
= do { addErrAt loc $
vcat [ what <+> text "not allowed in" <+> decl_sort
, nest 2 (ppr bind) ]
; return rest }
where
decl_sort | is_cls_decl = text "class declaration:"
| otherwise = text "instance declaration:"
what = case bind of
PatBind {} -> text "Pattern bindings (except simple variables)"
PatSynBind {} -> text "Pattern synonyms"
-- Associated pattern synonyms are not implemented yet
_ -> pprPanic "rnMethodBind" (ppr bind)
{-
************************************************************************
* *
\subsubsection[dep-Sigs]{Signatures (and user-pragmas for values)}
* *
************************************************************************
@renameSigs@ checks for:
\begin{enumerate}
\item more than one sig for one thing;
\item signatures given for things not bound here;
\end{enumerate}
At the moment we don't gather free-var info from the types in
signatures. We'd only need this if we wanted to report unused tyvars.
-}
renameSigs :: HsSigCtxt
-> [LSig RdrName]
-> RnM ([LSig Name], FreeVars)
-- Renames the signatures and performs error checks
renameSigs ctxt sigs
= do { mapM_ dupSigDeclErr (findDupSigs sigs)
; checkDupMinimalSigs sigs
; (sigs', sig_fvs) <- mapFvRn (wrapLocFstM (renameSig ctxt)) sigs
; let (good_sigs, bad_sigs) = partition (okHsSig ctxt) sigs'
; mapM_ misplacedSigErr bad_sigs -- Misplaced
; return (good_sigs, sig_fvs) }
----------------------
-- We use lookupSigOccRn in the signatures, which is a little bit unsatisfactory
-- because this won't work for:
-- instance Foo T where
-- {-# INLINE op #-}
-- Baz.op = ...
-- We'll just rename the INLINE prag to refer to whatever other 'op'
-- is in scope. (I'm assuming that Baz.op isn't in scope unqualified.)
-- Doesn't seem worth much trouble to sort this.
renameSig :: HsSigCtxt -> Sig RdrName -> RnM (Sig Name, FreeVars)
-- FixitySig is renamed elsewhere.
renameSig _ (IdSig x)
= return (IdSig x, emptyFVs) -- Actually this never occurs
renameSig ctxt sig@(TypeSig vs ty)
= do { new_vs <- mapM (lookupSigOccRn ctxt sig) vs
; let doc = TypeSigCtx (ppr_sig_bndrs vs)
; (new_ty, fvs) <- rnHsSigWcType doc ty
; return (TypeSig new_vs new_ty, fvs) }
renameSig ctxt sig@(ClassOpSig is_deflt vs ty)
= do { defaultSigs_on <- xoptM LangExt.DefaultSignatures
; when (is_deflt && not defaultSigs_on) $
addErr (defaultSigErr sig)
; new_v <- mapM (lookupSigOccRn ctxt sig) vs
; (new_ty, fvs) <- rnHsSigType ty_ctxt ty
; return (ClassOpSig is_deflt new_v new_ty, fvs) }
where
(v1:_) = vs
ty_ctxt = GenericCtx (text "a class method signature for"
<+> quotes (ppr v1))
renameSig _ (SpecInstSig src ty)
= do { (new_ty, fvs) <- rnHsSigType SpecInstSigCtx ty
; return (SpecInstSig src new_ty,fvs) }
-- {-# SPECIALISE #-} pragmas can refer to imported Ids
-- so, in the top-level case (when mb_names is Nothing)
-- we use lookupOccRn. If there's both an imported and a local 'f'
-- then the SPECIALISE pragma is ambiguous, unlike all other signatures
renameSig ctxt sig@(SpecSig v tys inl)
= do { new_v <- case ctxt of
TopSigCtxt {} -> lookupLocatedOccRn v
_ -> lookupSigOccRn ctxt sig v
; (new_ty, fvs) <- foldM do_one ([],emptyFVs) tys
; return (SpecSig new_v new_ty inl, fvs) }
where
ty_ctxt = GenericCtx (text "a SPECIALISE signature for"
<+> quotes (ppr v))
do_one (tys,fvs) ty
= do { (new_ty, fvs_ty) <- rnHsSigType ty_ctxt ty
; return ( new_ty:tys, fvs_ty `plusFV` fvs) }
renameSig ctxt sig@(InlineSig v s)
= do { new_v <- lookupSigOccRn ctxt sig v
; return (InlineSig new_v s, emptyFVs) }
renameSig ctxt sig@(FixSig (FixitySig vs f))
= do { new_vs <- mapM (lookupSigOccRn ctxt sig) vs
; return (FixSig (FixitySig new_vs f), emptyFVs) }
renameSig ctxt sig@(MinimalSig s (L l bf))
= do new_bf <- traverse (lookupSigOccRn ctxt sig) bf
return (MinimalSig s (L l new_bf), emptyFVs)
renameSig ctxt sig@(PatSynSig vs ty)
= do { new_vs <- mapM (lookupSigOccRn ctxt sig) vs
; (ty', fvs) <- rnHsSigType ty_ctxt ty
; return (PatSynSig new_vs ty', fvs) }
where
ty_ctxt = GenericCtx (text "a pattern synonym signature for"
<+> ppr_sig_bndrs vs)
renameSig ctxt sig@(SCCFunSig st v s)
= do { new_v <- lookupSigOccRn ctxt sig v
; return (SCCFunSig st new_v s, emptyFVs) }
ppr_sig_bndrs :: [Located RdrName] -> SDoc
ppr_sig_bndrs bs = quotes (pprWithCommas ppr bs)
okHsSig :: HsSigCtxt -> LSig a -> Bool
okHsSig ctxt (L _ sig)
= case (sig, ctxt) of
(ClassOpSig {}, ClsDeclCtxt {}) -> True
(ClassOpSig {}, InstDeclCtxt {}) -> True
(ClassOpSig {}, _) -> False
(TypeSig {}, ClsDeclCtxt {}) -> False
(TypeSig {}, InstDeclCtxt {}) -> False
(TypeSig {}, _) -> True
(PatSynSig {}, TopSigCtxt{}) -> True
(PatSynSig {}, _) -> False
(FixSig {}, InstDeclCtxt {}) -> False
(FixSig {}, _) -> True
(IdSig {}, TopSigCtxt {}) -> True
(IdSig {}, InstDeclCtxt {}) -> True
(IdSig {}, _) -> False
(InlineSig {}, HsBootCtxt {}) -> False
(InlineSig {}, _) -> True
(SpecSig {}, TopSigCtxt {}) -> True
(SpecSig {}, LocalBindCtxt {}) -> True
(SpecSig {}, InstDeclCtxt {}) -> True
(SpecSig {}, _) -> False
(SpecInstSig {}, InstDeclCtxt {}) -> True
(SpecInstSig {}, _) -> False
(MinimalSig {}, ClsDeclCtxt {}) -> True
(MinimalSig {}, _) -> False
(SCCFunSig {}, HsBootCtxt {}) -> False
(SCCFunSig {}, _) -> True
-------------------
findDupSigs :: [LSig RdrName] -> [[(Located RdrName, Sig RdrName)]]
-- Check for duplicates on RdrName version,
-- because renamed version has unboundName for
-- not-in-scope binders, which gives bogus dup-sig errors
-- NB: in a class decl, a 'generic' sig is not considered
-- equal to an ordinary sig, so we allow, say
-- class C a where
-- op :: a -> a
-- default op :: Eq a => a -> a
findDupSigs sigs
= findDupsEq matching_sig (concatMap (expand_sig . unLoc) sigs)
where
expand_sig sig@(FixSig (FixitySig ns _)) = zip ns (repeat sig)
expand_sig sig@(InlineSig n _) = [(n,sig)]
expand_sig sig@(TypeSig ns _) = [(n,sig) | n <- ns]
expand_sig sig@(ClassOpSig _ ns _) = [(n,sig) | n <- ns]
expand_sig sig@(PatSynSig ns _ ) = [(n,sig) | n <- ns]
expand_sig sig@(SCCFunSig _ n _) = [(n,sig)]
expand_sig _ = []
matching_sig (L _ n1,sig1) (L _ n2,sig2) = n1 == n2 && mtch sig1 sig2
mtch (FixSig {}) (FixSig {}) = True
mtch (InlineSig {}) (InlineSig {}) = True
mtch (TypeSig {}) (TypeSig {}) = True
mtch (ClassOpSig d1 _ _) (ClassOpSig d2 _ _) = d1 == d2
mtch (PatSynSig _ _) (PatSynSig _ _) = True
mtch (SCCFunSig{}) (SCCFunSig{}) = True
mtch _ _ = False
-- Warn about multiple MINIMAL signatures
checkDupMinimalSigs :: [LSig RdrName] -> RnM ()
checkDupMinimalSigs sigs
= case filter isMinimalLSig sigs of
minSigs@(_:_:_) -> dupMinimalSigErr minSigs
_ -> return ()
{-
************************************************************************
* *
\subsection{Match}
* *
************************************************************************
-}
rnMatchGroup :: Outputable (body RdrName) => HsMatchContext Name
-> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-> MatchGroup RdrName (Located (body RdrName))
-> RnM (MatchGroup Name (Located (body Name)), FreeVars)
rnMatchGroup ctxt rnBody (MG { mg_alts = L _ ms, mg_origin = origin })
= do { empty_case_ok <- xoptM LangExt.EmptyCase
; when (null ms && not empty_case_ok) (addErr (emptyCaseErr ctxt))
; (new_ms, ms_fvs) <- mapFvRn (rnMatch ctxt rnBody) ms
; return (mkMatchGroup origin new_ms, ms_fvs) }
rnMatch :: Outputable (body RdrName) => HsMatchContext Name
-> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-> LMatch RdrName (Located (body RdrName))
-> RnM (LMatch Name (Located (body Name)), FreeVars)
rnMatch ctxt rnBody = wrapLocFstM (rnMatch' ctxt rnBody)
rnMatch' :: Outputable (body RdrName) => HsMatchContext Name
-> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-> Match RdrName (Located (body RdrName))
-> RnM (Match Name (Located (body Name)), FreeVars)
rnMatch' ctxt rnBody match@(Match { m_ctxt = mf, m_pats = pats
, m_type = maybe_rhs_sig, m_grhss = grhss })
= do { -- Result type signatures are no longer supported
case maybe_rhs_sig of
Nothing -> return ()
Just (L loc ty) -> addErrAt loc (resSigErr match ty)
; let fixity = if isInfixMatch match then Infix else Prefix
-- Now the main event
-- Note that there are no local fixity decls for matches
; rnPats ctxt pats $ \ pats' -> do
{ (grhss', grhss_fvs) <- rnGRHSs ctxt rnBody grhss
; let mf' = case (ctxt,mf) of
(FunRhs (L _ funid) _,FunRhs (L lf _) _)
-> FunRhs (L lf funid) fixity
_ -> ctxt
; return (Match { m_ctxt = mf', m_pats = pats'
, m_type = Nothing, m_grhss = grhss'}, grhss_fvs ) }}
emptyCaseErr :: HsMatchContext Name -> SDoc
emptyCaseErr ctxt = hang (text "Empty list of alternatives in" <+> pp_ctxt)
2 (text "Use EmptyCase to allow this")
where
pp_ctxt = case ctxt of
CaseAlt -> text "case expression"
LambdaExpr -> text "\\case expression"
_ -> text "(unexpected)" <+> pprMatchContextNoun ctxt
resSigErr :: Outputable body
=> Match RdrName body -> HsType RdrName -> SDoc
resSigErr match ty
= vcat [ text "Illegal result type signature" <+> quotes (ppr ty)
, nest 2 $ ptext (sLit
"Result signatures are no longer supported in pattern matches")
, pprMatchInCtxt match ]
{-
************************************************************************
* *
\subsubsection{Guarded right-hand sides (GRHSs)}
* *
************************************************************************
-}
rnGRHSs :: HsMatchContext Name
-> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-> GRHSs RdrName (Located (body RdrName))
-> RnM (GRHSs Name (Located (body Name)), FreeVars)
rnGRHSs ctxt rnBody (GRHSs grhss (L l binds))
= rnLocalBindsAndThen binds $ \ binds' _ -> do
(grhss', fvGRHSs) <- mapFvRn (rnGRHS ctxt rnBody) grhss
return (GRHSs grhss' (L l binds'), fvGRHSs)
rnGRHS :: HsMatchContext Name
-> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-> LGRHS RdrName (Located (body RdrName))
-> RnM (LGRHS Name (Located (body Name)), FreeVars)
rnGRHS ctxt rnBody = wrapLocFstM (rnGRHS' ctxt rnBody)
rnGRHS' :: HsMatchContext Name
-> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-> GRHS RdrName (Located (body RdrName))
-> RnM (GRHS Name (Located (body Name)), FreeVars)
rnGRHS' ctxt rnBody (GRHS guards rhs)
= do { pattern_guards_allowed <- xoptM LangExt.PatternGuards
; ((guards', rhs'), fvs) <- rnStmts (PatGuard ctxt) rnLExpr guards $ \ _ ->
rnBody rhs
; unless (pattern_guards_allowed || is_standard_guard guards')
(addWarn NoReason (nonStdGuardErr guards'))
; return (GRHS guards' rhs', fvs) }
where
-- Standard Haskell 1.4 guards are just a single boolean
-- expression, rather than a list of qualifiers as in the
-- Glasgow extension
is_standard_guard [] = True
is_standard_guard [L _ (BodyStmt _ _ _ _)] = True
is_standard_guard _ = False
{-
************************************************************************
* *
\subsection{Error messages}
* *
************************************************************************
-}
dupSigDeclErr :: [(Located RdrName, Sig RdrName)] -> RnM ()
dupSigDeclErr pairs@((L loc name, sig) : _)
= addErrAt loc $
vcat [ text "Duplicate" <+> what_it_is
<> text "s for" <+> quotes (ppr name)
, text "at" <+> vcat (map ppr $ sort $ map (getLoc . fst) pairs) ]
where
what_it_is = hsSigDoc sig
dupSigDeclErr [] = panic "dupSigDeclErr"
misplacedSigErr :: LSig Name -> RnM ()
misplacedSigErr (L loc sig)
= addErrAt loc $
sep [text "Misplaced" <+> hsSigDoc sig <> colon, ppr sig]
defaultSigErr :: Sig RdrName -> SDoc
defaultSigErr sig = vcat [ hang (text "Unexpected default signature:")
2 (ppr sig)
, text "Use DefaultSignatures to enable default signatures" ]
bindsInHsBootFile :: LHsBindsLR Name RdrName -> SDoc
bindsInHsBootFile mbinds
= hang (text "Bindings in hs-boot files are not allowed")
2 (ppr mbinds)
nonStdGuardErr :: Outputable body => [LStmtLR Name Name body] -> SDoc
nonStdGuardErr guards
= hang (text "accepting non-standard pattern guards (use PatternGuards to suppress this message)")
4 (interpp'SP guards)
unusedPatBindWarn :: HsBind Name -> SDoc
unusedPatBindWarn bind
= hang (text "This pattern-binding binds no variables:")
2 (ppr bind)
dupMinimalSigErr :: [LSig RdrName] -> RnM ()
dupMinimalSigErr sigs@(L loc _ : _)
= addErrAt loc $
vcat [ text "Multiple minimal complete definitions"
, text "at" <+> vcat (map ppr $ sort $ map getLoc sigs)
, text "Combine alternative minimal complete definitions with `|'" ]
dupMinimalSigErr [] = panic "dupMinimalSigErr"
|
snoyberg/ghc
|
compiler/rename/RnBinds.hs
|
bsd-3-clause
| 49,744 | 0 | 22 | 15,477 | 9,325 | 4,926 | 4,399 | 568 | 25 |
{-# LANGUAGE CPP #-}
module Main where
import Prelude hiding (abs)
data Expr = Val Int | Add Expr Expr | Throw | Catch Expr Expr
type Mint = Maybe Int
eval :: Expr -> Mint
eval (Val n) = Just n
eval Throw = Nothing
eval (Catch x y) = case eval x of
Nothing -> eval y
Just n -> Just n
eval (Add x y) = case eval x of
Nothing -> Nothing
Just m -> case eval y of
Nothing -> Nothing
Just n -> Just (m + n)
abs :: ((Int -> Mint) -> Mint -> Mint) -> Mint
abs h = h Just Nothing
rep :: Mint -> (Int -> Mint) -> Mint -> Mint
rep mn s f = case mn of
Nothing -> f
Just n -> s n
main :: IO ()
main = print (eval $ Val 5)
|
conal/hermit
|
examples/evaluation/Eval.hs
|
bsd-2-clause
| 827 | 0 | 13 | 365 | 323 | 164 | 159 | 24 | 4 |
type Foo = Int
|
themattchan/tandoori
|
input/empty.hs
|
bsd-3-clause
| 15 | 0 | 4 | 4 | 7 | 4 | 3 | 1 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilyDependencies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE UndecidableInstances #-}
module T16512a where
import Data.Kind
( Type )
-- HOAS representation
data AST (a :: Type) :: Type where
(:$) :: AST ( a -> b ) -> AST a -> AST b
-- Lam :: ( AST a -> AST b ) -> AST ( a -> b )
-- PrimOp :: PrimOp op a => AST a
-- ...
data ASTs (as :: [Type]) :: Type where
NilASTs :: ASTs '[]
ConsAST :: AST a -> ASTs as -> ASTs (a ': as)
type family ListVariadic (as :: [Type]) (b :: Type) = (r :: Type) | r -> as b where
ListVariadic (a ': as) b = a -> ListVariadic as b
-- ListVariadic '[] () = ()
-- ListVariadic '[] Bool = Bool
-- ListVariadic '[] Word = Word
-- ListVariadic '[] Int = Int
-- ListVariadic '[] Float = Float
-- ListVariadic '[] Double = Double
-- ...
data AnApplication b where
AnApplication :: AST (ListVariadic as b) -> ASTs as -> AnApplication b
unapply :: AST b -> AnApplication b
unapply (f :$ a)
= case unapply f of
AnApplication g as ->
AnApplication g (a `ConsAST` as)
-- no other cases with this simplified AST
|
sdiehl/ghc
|
testsuite/tests/typecheck/should_fail/T16512a.hs
|
bsd-3-clause
| 1,252 | 0 | 10 | 348 | 300 | 176 | 124 | 23 | 1 |
-- |Computations in the vectorisation monad concerned with naming and fresh variable generation.
module Vectorise.Monad.Naming
( mkLocalisedName
, mkDerivedName
, mkVectId
, cloneVar
, newExportedVar
, newLocalVar
, newLocalVars
, newDummyVar
, newTyVar
, newCoVar
)
where
import Vectorise.Monad.Base
import DsMonad
import TcType
import Type
import Var
import Module
import Name
import SrcLoc
import MkId
import Id
import IdInfo( IdDetails(VanillaId) )
import FastString
import Control.Monad
-- Naming ---------------------------------------------------------------------
-- |Create a localised variant of a name, using the provided function to transform its `OccName`.
--
-- If the name external, encode the orignal name's module into the new 'OccName'. The result is
-- always an internal system name.
--
mkLocalisedName :: (Maybe String -> OccName -> OccName) -> Name -> VM Name
mkLocalisedName mk_occ name
= do { mod <- liftDs getModule
; u <- liftDs newUnique
; let occ_name = mkLocalisedOccName mod mk_occ name
new_name | isExternalName name = mkExternalName u mod occ_name (nameSrcSpan name)
| otherwise = mkSystemName u occ_name
; return new_name }
mkDerivedName :: (OccName -> OccName) -> Name -> VM Name
-- Similar to mkLocalisedName, but assumes the
-- incoming name is from this module.
-- Works on External names only
mkDerivedName mk_occ name
= do { u <- liftDs newUnique
; return (mkExternalName u (nameModule name)
(mk_occ (nameOccName name))
(nameSrcSpan name)) }
-- |Produce the vectorised variant of an `Id` with the given vectorised type, while taking care that
-- vectorised dfun ids must be dfuns again.
--
-- Force the new name to be a system name and, if the original was an external name, disambiguate
-- the new name with the module name of the original.
--
mkVectId :: Id -> Type -> VM Id
mkVectId id ty
= do { name <- mkLocalisedName mkVectOcc (getName id)
; let id' | isDFunId id = MkId.mkDictFunId name tvs theta cls tys
| isExportedId id = Id.mkExportedLocalId VanillaId name ty
| otherwise = Id.mkLocalIdOrCoVar name ty
; return id'
}
where
-- Decompose a dictionary function signature: \forall tvs. theta -> cls tys
-- NB: We do *not* use closures '(:->)' for vectorised predicate abstraction as dictionary
-- functions are always fully applied.
(tvs, theta, pty) = tcSplitSigmaTy ty
(cls, tys) = tcSplitDFunHead pty
-- |Make a fresh instance of this var, with a new unique.
--
cloneVar :: Var -> VM Var
cloneVar var = liftM (setIdUnique var) (liftDs newUnique)
-- |Make a fresh exported variable with the given type.
--
newExportedVar :: OccName -> Type -> VM Var
newExportedVar occ_name ty
= do mod <- liftDs getModule
u <- liftDs newUnique
let name = mkExternalName u mod occ_name noSrcSpan
return $ Id.mkExportedLocalId VanillaId name ty
-- |Make a fresh local variable with the given type.
-- The variable's name is formed using the given string as the prefix.
--
newLocalVar :: FastString -> Type -> VM Var
newLocalVar fs ty
= do u <- liftDs newUnique
return $ mkSysLocalOrCoVar fs u ty
-- |Make several fresh local variables with the given types.
-- The variable's names are formed using the given string as the prefix.
--
newLocalVars :: FastString -> [Type] -> VM [Var]
newLocalVars fs = mapM (newLocalVar fs)
-- |Make a new local dummy variable.
--
newDummyVar :: Type -> VM Var
newDummyVar = newLocalVar (fsLit "vv")
-- |Make a fresh type variable with the given kind.
-- The variable's name is formed using the given string as the prefix.
--
newTyVar :: FastString -> Kind -> VM Var
newTyVar fs k
= do u <- liftDs newUnique
return $ mkTyVar (mkSysTvName u fs) k
-- |Make a fresh coercion variable with the given kind.
newCoVar :: FastString -> Kind -> VM Var
newCoVar fs k
= do u <- liftDs newUnique
return $ mkCoVar (mkSystemVarName u fs) k
|
vikraman/ghc
|
compiler/vectorise/Vectorise/Monad/Naming.hs
|
bsd-3-clause
| 4,130 | 0 | 13 | 972 | 846 | 438 | 408 | 71 | 1 |
module Ite where
{- imports will be added for the PointlessP librasies -}
import PointlessP.Combinators
import PointlessP.RecursionPatterns
import PointlessP.Isomorphisms
import PointlessP.Functors
-- the whole expression will be selected for translation.
notZero = app .
(((curry
(app .
((curry
((((inN (_L :: Bool)) . (Right . bang)) \/
((inN (_L :: Bool)) . (Left . bang))) .
distr)) /\
((ouT (_L :: Bool)) .
(app .
((curry
((((inN (_L :: Bool)) . (Left . bang)) \/
((inN (_L :: Bool)) .
(Right . bang))) .
distr)) /\
((ouT (_L :: Int)) . snd))))))) .
bang) /\
id)
|
kmate/HaRe
|
old/testing/pointwiseToPointfree/Ite_TokOut.hs
|
bsd-3-clause
| 1,167 | 0 | 32 | 695 | 265 | 153 | 112 | 22 | 1 |
module PatIn2 where
foo :: Int
foo = (h h_x) + t
where
(h, t) = head $ (zip [1 .. 10] [3 .. 15])
h_x = undefined
main :: Int
main = foo
|
kmate/HaRe
|
old/testing/addOneParameter/PatIn2_AstOut.hs
|
bsd-3-clause
| 157 | 0 | 10 | 55 | 77 | 45 | 32 | 7 | 1 |
{-@ LIQUID "--totality" @-}
module Totality where
import Prelude hiding (head)
head (x:_) = x
-- head xs = case xs of
-- (x:_) -> x
-- [] -> patError "..."
-- patError :: {v:String | false} -> a
nestcomment n ('{':'-':ss) | n>=0 = (("{-"++cs),rm)
where (cs,rm) = nestcomment (n+1) ss
nestcomment n ('-':'}':ss) | n>0 = let (cs,rm) = nestcomment (n-1) ss
in (("-}"++cs),rm)
nestcomment n ('-':'}':ss) | n==0 = ("-}",ss)
nestcomment n (s:ss) | n>=0 = ((s:cs),rm)
where (cs,rm) = nestcomment n ss
nestcomment n [] = ([],[])
-- Local Variables:
-- flycheck-checker: haskell-liquid
-- End:
nestcomment :: Int -> String -> (String,String)
{-@ LIQUID "--no-termination" @-}
{-@ LIQUID "--diffcheck" @-}
{-@ LIQUID "--short-names" @-}
|
abakst/liquidhaskell
|
docs/slides/HS2014/Totality-blank.hs
|
bsd-3-clause
| 903 | 0 | 12 | 294 | 320 | 176 | 144 | 12 | 1 |
-----------------------------------------------------------------------------
--
-- Pretty-printing assembly language
--
-- (c) The University of Glasgow 1993-2005
--
-----------------------------------------------------------------------------
{-# OPTIONS_GHC -fno-warn-orphans #-}
module PPC.Ppr (
pprNatCmmDecl,
pprBasicBlock,
pprSectionHeader,
pprData,
pprInstr,
pprSize,
pprImm,
pprDataItem,
)
where
import PPC.Regs
import PPC.Instr
import PPC.Cond
import PprBase
import Instruction
import Size
import Reg
import RegClass
import TargetReg
import Cmm hiding (topInfoTable)
import BlockId
import CLabel
import Unique ( pprUnique, Uniquable(..) )
import Platform
import FastString
import Outputable
import Data.Word
import Data.Bits
-- -----------------------------------------------------------------------------
-- Printing this stuff out
pprNatCmmDecl :: NatCmmDecl CmmStatics Instr -> SDoc
pprNatCmmDecl (CmmData section dats) =
pprSectionHeader section $$ pprDatas dats
pprNatCmmDecl proc@(CmmProc top_info lbl _ (ListGraph blocks)) =
case topInfoTable proc of
Nothing ->
case blocks of
[] -> -- special case for split markers:
pprLabel lbl
blocks -> -- special case for code without info table:
pprSectionHeader Text $$
pprLabel lbl $$ -- blocks guaranteed not null, so label needed
vcat (map (pprBasicBlock top_info) blocks)
Just (Statics info_lbl _) ->
sdocWithPlatform $ \platform ->
(if platformHasSubsectionsViaSymbols platform
then pprSectionHeader Text $$
ppr (mkDeadStripPreventer info_lbl) <> char ':'
else empty) $$
vcat (map (pprBasicBlock top_info) blocks) $$
-- above: Even the first block gets a label, because with branch-chain
-- elimination, it might be the target of a goto.
(if platformHasSubsectionsViaSymbols platform
then
-- See Note [Subsections Via Symbols]
text "\t.long "
<+> ppr info_lbl
<+> char '-'
<+> ppr (mkDeadStripPreventer info_lbl)
else empty)
pprBasicBlock :: BlockEnv CmmStatics -> NatBasicBlock Instr -> SDoc
pprBasicBlock info_env (BasicBlock blockid instrs)
= maybe_infotable $$
pprLabel (mkAsmTempLabel (getUnique blockid)) $$
vcat (map pprInstr instrs)
where
maybe_infotable = case mapLookup blockid info_env of
Nothing -> empty
Just (Statics info_lbl info) ->
pprSectionHeader Text $$
vcat (map pprData info) $$
pprLabel info_lbl
pprDatas :: CmmStatics -> SDoc
pprDatas (Statics lbl dats) = vcat (pprLabel lbl : map pprData dats)
pprData :: CmmStatic -> SDoc
pprData (CmmString str) = pprASCII str
pprData (CmmUninitialised bytes) = keyword <> int bytes
where keyword = sdocWithPlatform $ \platform ->
case platformOS platform of
OSDarwin -> ptext (sLit ".space ")
_ -> ptext (sLit ".skip ")
pprData (CmmStaticLit lit) = pprDataItem lit
pprGloblDecl :: CLabel -> SDoc
pprGloblDecl lbl
| not (externallyVisibleCLabel lbl) = empty
| otherwise = ptext (sLit ".globl ") <> ppr lbl
pprTypeAndSizeDecl :: CLabel -> SDoc
pprTypeAndSizeDecl lbl
= sdocWithPlatform $ \platform ->
if platformOS platform == OSLinux && externallyVisibleCLabel lbl
then ptext (sLit ".type ") <>
ppr lbl <> ptext (sLit ", @object")
else empty
pprLabel :: CLabel -> SDoc
pprLabel lbl = pprGloblDecl lbl
$$ pprTypeAndSizeDecl lbl
$$ (ppr lbl <> char ':')
pprASCII :: [Word8] -> SDoc
pprASCII str
= vcat (map do1 str) $$ do1 0
where
do1 :: Word8 -> SDoc
do1 w = ptext (sLit "\t.byte\t") <> int (fromIntegral w)
-- -----------------------------------------------------------------------------
-- pprInstr: print an 'Instr'
instance Outputable Instr where
ppr instr = pprInstr instr
pprReg :: Reg -> SDoc
pprReg r
= case r of
RegReal (RealRegSingle i) -> ppr_reg_no i
RegReal (RealRegPair{}) -> panic "PPC.pprReg: no reg pairs on this arch"
RegVirtual (VirtualRegI u) -> text "%vI_" <> pprUnique u
RegVirtual (VirtualRegHi u) -> text "%vHi_" <> pprUnique u
RegVirtual (VirtualRegF u) -> text "%vF_" <> pprUnique u
RegVirtual (VirtualRegD u) -> text "%vD_" <> pprUnique u
RegVirtual (VirtualRegSSE u) -> text "%vSSE_" <> pprUnique u
where
ppr_reg_no :: Int -> SDoc
ppr_reg_no i =
sdocWithPlatform $ \platform ->
case platformOS platform of
OSDarwin ->
ptext
(case i of {
0 -> sLit "r0"; 1 -> sLit "r1";
2 -> sLit "r2"; 3 -> sLit "r3";
4 -> sLit "r4"; 5 -> sLit "r5";
6 -> sLit "r6"; 7 -> sLit "r7";
8 -> sLit "r8"; 9 -> sLit "r9";
10 -> sLit "r10"; 11 -> sLit "r11";
12 -> sLit "r12"; 13 -> sLit "r13";
14 -> sLit "r14"; 15 -> sLit "r15";
16 -> sLit "r16"; 17 -> sLit "r17";
18 -> sLit "r18"; 19 -> sLit "r19";
20 -> sLit "r20"; 21 -> sLit "r21";
22 -> sLit "r22"; 23 -> sLit "r23";
24 -> sLit "r24"; 25 -> sLit "r25";
26 -> sLit "r26"; 27 -> sLit "r27";
28 -> sLit "r28"; 29 -> sLit "r29";
30 -> sLit "r30"; 31 -> sLit "r31";
32 -> sLit "f0"; 33 -> sLit "f1";
34 -> sLit "f2"; 35 -> sLit "f3";
36 -> sLit "f4"; 37 -> sLit "f5";
38 -> sLit "f6"; 39 -> sLit "f7";
40 -> sLit "f8"; 41 -> sLit "f9";
42 -> sLit "f10"; 43 -> sLit "f11";
44 -> sLit "f12"; 45 -> sLit "f13";
46 -> sLit "f14"; 47 -> sLit "f15";
48 -> sLit "f16"; 49 -> sLit "f17";
50 -> sLit "f18"; 51 -> sLit "f19";
52 -> sLit "f20"; 53 -> sLit "f21";
54 -> sLit "f22"; 55 -> sLit "f23";
56 -> sLit "f24"; 57 -> sLit "f25";
58 -> sLit "f26"; 59 -> sLit "f27";
60 -> sLit "f28"; 61 -> sLit "f29";
62 -> sLit "f30"; 63 -> sLit "f31";
_ -> sLit "very naughty powerpc register"
})
_
| i <= 31 -> int i -- GPRs
| i <= 63 -> int (i-32) -- FPRs
| otherwise -> ptext (sLit "very naughty powerpc register")
pprSize :: Size -> SDoc
pprSize x
= ptext (case x of
II8 -> sLit "b"
II16 -> sLit "h"
II32 -> sLit "w"
FF32 -> sLit "fs"
FF64 -> sLit "fd"
_ -> panic "PPC.Ppr.pprSize: no match")
pprCond :: Cond -> SDoc
pprCond c
= ptext (case c of {
ALWAYS -> sLit "";
EQQ -> sLit "eq"; NE -> sLit "ne";
LTT -> sLit "lt"; GE -> sLit "ge";
GTT -> sLit "gt"; LE -> sLit "le";
LU -> sLit "lt"; GEU -> sLit "ge";
GU -> sLit "gt"; LEU -> sLit "le"; })
pprImm :: Imm -> SDoc
pprImm (ImmInt i) = int i
pprImm (ImmInteger i) = integer i
pprImm (ImmCLbl l) = ppr l
pprImm (ImmIndex l i) = ppr l <> char '+' <> int i
pprImm (ImmLit s) = s
pprImm (ImmFloat _) = ptext (sLit "naughty float immediate")
pprImm (ImmDouble _) = ptext (sLit "naughty double immediate")
pprImm (ImmConstantSum a b) = pprImm a <> char '+' <> pprImm b
pprImm (ImmConstantDiff a b) = pprImm a <> char '-'
<> lparen <> pprImm b <> rparen
pprImm (LO i)
= sdocWithPlatform $ \platform ->
if platformOS platform == OSDarwin
then hcat [ text "lo16(", pprImm i, rparen ]
else pprImm i <> text "@l"
pprImm (HI i)
= sdocWithPlatform $ \platform ->
if platformOS platform == OSDarwin
then hcat [ text "hi16(", pprImm i, rparen ]
else pprImm i <> text "@h"
pprImm (HA i)
= sdocWithPlatform $ \platform ->
if platformOS platform == OSDarwin
then hcat [ text "ha16(", pprImm i, rparen ]
else pprImm i <> text "@ha"
pprAddr :: AddrMode -> SDoc
pprAddr (AddrRegReg r1 r2)
= pprReg r1 <+> ptext (sLit ", ") <+> pprReg r2
pprAddr (AddrRegImm r1 (ImmInt i)) = hcat [ int i, char '(', pprReg r1, char ')' ]
pprAddr (AddrRegImm r1 (ImmInteger i)) = hcat [ integer i, char '(', pprReg r1, char ')' ]
pprAddr (AddrRegImm r1 imm) = hcat [ pprImm imm, char '(', pprReg r1, char ')' ]
pprSectionHeader :: Section -> SDoc
pprSectionHeader seg =
sdocWithPlatform $ \platform ->
let osDarwin = platformOS platform == OSDarwin in
case seg of
Text -> text ".text\n\t.align 2"
Data -> text ".data\n\t.align 2"
ReadOnlyData
| osDarwin -> text ".const\n\t.align 2"
| otherwise -> text ".section .rodata\n\t.align 2"
RelocatableReadOnlyData
| osDarwin -> text ".const_data\n\t.align 2"
| otherwise -> text ".data\n\t.align 2"
UninitialisedData
| osDarwin -> text ".const_data\n\t.align 2"
| otherwise -> text ".section .bss\n\t.align 2"
ReadOnlyData16
| osDarwin -> text ".const\n\t.align 4"
| otherwise -> text ".section .rodata\n\t.align 4"
OtherSection _ ->
panic "PprMach.pprSectionHeader: unknown section"
pprDataItem :: CmmLit -> SDoc
pprDataItem lit
= sdocWithDynFlags $ \dflags ->
vcat (ppr_item (cmmTypeSize $ cmmLitType dflags lit) lit)
where
imm = litToImm lit
ppr_item II8 _ = [ptext (sLit "\t.byte\t") <> pprImm imm]
ppr_item II32 _ = [ptext (sLit "\t.long\t") <> pprImm imm]
ppr_item FF32 (CmmFloat r _)
= let bs = floatToBytes (fromRational r)
in map (\b -> ptext (sLit "\t.byte\t") <> pprImm (ImmInt b)) bs
ppr_item FF64 (CmmFloat r _)
= let bs = doubleToBytes (fromRational r)
in map (\b -> ptext (sLit "\t.byte\t") <> pprImm (ImmInt b)) bs
ppr_item II16 _ = [ptext (sLit "\t.short\t") <> pprImm imm]
ppr_item II64 (CmmInt x _) =
[ptext (sLit "\t.long\t")
<> int (fromIntegral
(fromIntegral (x `shiftR` 32) :: Word32)),
ptext (sLit "\t.long\t")
<> int (fromIntegral (fromIntegral x :: Word32))]
ppr_item _ _
= panic "PPC.Ppr.pprDataItem: no match"
pprInstr :: Instr -> SDoc
pprInstr (COMMENT _) = empty -- nuke 'em
{-
pprInstr (COMMENT s) =
if platformOS platform == OSLinux
then ptext (sLit "# ") <> ftext s
else ptext (sLit "; ") <> ftext s
-}
pprInstr (DELTA d)
= pprInstr (COMMENT (mkFastString ("\tdelta = " ++ show d)))
pprInstr (NEWBLOCK _)
= panic "PprMach.pprInstr: NEWBLOCK"
pprInstr (LDATA _ _)
= panic "PprMach.pprInstr: LDATA"
{-
pprInstr (SPILL reg slot)
= hcat [
ptext (sLit "\tSPILL"),
char '\t',
pprReg reg,
comma,
ptext (sLit "SLOT") <> parens (int slot)]
pprInstr (RELOAD slot reg)
= hcat [
ptext (sLit "\tRELOAD"),
char '\t',
ptext (sLit "SLOT") <> parens (int slot),
comma,
pprReg reg]
-}
pprInstr (LD sz reg addr) = hcat [
char '\t',
ptext (sLit "l"),
ptext (case sz of
II8 -> sLit "bz"
II16 -> sLit "hz"
II32 -> sLit "wz"
FF32 -> sLit "fs"
FF64 -> sLit "fd"
_ -> panic "PPC.Ppr.pprInstr: no match"
),
case addr of AddrRegImm _ _ -> empty
AddrRegReg _ _ -> char 'x',
char '\t',
pprReg reg,
ptext (sLit ", "),
pprAddr addr
]
pprInstr (LA sz reg addr) = hcat [
char '\t',
ptext (sLit "l"),
ptext (case sz of
II8 -> sLit "ba"
II16 -> sLit "ha"
II32 -> sLit "wa"
FF32 -> sLit "fs"
FF64 -> sLit "fd"
_ -> panic "PPC.Ppr.pprInstr: no match"
),
case addr of AddrRegImm _ _ -> empty
AddrRegReg _ _ -> char 'x',
char '\t',
pprReg reg,
ptext (sLit ", "),
pprAddr addr
]
pprInstr (ST sz reg addr) = hcat [
char '\t',
ptext (sLit "st"),
pprSize sz,
case addr of AddrRegImm _ _ -> empty
AddrRegReg _ _ -> char 'x',
char '\t',
pprReg reg,
ptext (sLit ", "),
pprAddr addr
]
pprInstr (STU sz reg addr) = hcat [
char '\t',
ptext (sLit "st"),
pprSize sz,
ptext (sLit "u\t"),
case addr of AddrRegImm _ _ -> empty
AddrRegReg _ _ -> char 'x',
pprReg reg,
ptext (sLit ", "),
pprAddr addr
]
pprInstr (LIS reg imm) = hcat [
char '\t',
ptext (sLit "lis"),
char '\t',
pprReg reg,
ptext (sLit ", "),
pprImm imm
]
pprInstr (LI reg imm) = hcat [
char '\t',
ptext (sLit "li"),
char '\t',
pprReg reg,
ptext (sLit ", "),
pprImm imm
]
pprInstr (MR reg1 reg2)
| reg1 == reg2 = empty
| otherwise = hcat [
char '\t',
sdocWithPlatform $ \platform ->
case targetClassOfReg platform reg1 of
RcInteger -> ptext (sLit "mr")
_ -> ptext (sLit "fmr"),
char '\t',
pprReg reg1,
ptext (sLit ", "),
pprReg reg2
]
pprInstr (CMP sz reg ri) = hcat [
char '\t',
op,
char '\t',
pprReg reg,
ptext (sLit ", "),
pprRI ri
]
where
op = hcat [
ptext (sLit "cmp"),
pprSize sz,
case ri of
RIReg _ -> empty
RIImm _ -> char 'i'
]
pprInstr (CMPL sz reg ri) = hcat [
char '\t',
op,
char '\t',
pprReg reg,
ptext (sLit ", "),
pprRI ri
]
where
op = hcat [
ptext (sLit "cmpl"),
pprSize sz,
case ri of
RIReg _ -> empty
RIImm _ -> char 'i'
]
pprInstr (BCC cond blockid) = hcat [
char '\t',
ptext (sLit "b"),
pprCond cond,
char '\t',
ppr lbl
]
where lbl = mkAsmTempLabel (getUnique blockid)
pprInstr (BCCFAR cond blockid) = vcat [
hcat [
ptext (sLit "\tb"),
pprCond (condNegate cond),
ptext (sLit "\t$+8")
],
hcat [
ptext (sLit "\tb\t"),
ppr lbl
]
]
where lbl = mkAsmTempLabel (getUnique blockid)
pprInstr (JMP lbl) = hcat [ -- an alias for b that takes a CLabel
char '\t',
ptext (sLit "b"),
char '\t',
ppr lbl
]
pprInstr (MTCTR reg) = hcat [
char '\t',
ptext (sLit "mtctr"),
char '\t',
pprReg reg
]
pprInstr (BCTR _ _) = hcat [
char '\t',
ptext (sLit "bctr")
]
pprInstr (BL lbl _) = hcat [
ptext (sLit "\tbl\t"),
ppr lbl
]
pprInstr (BCTRL _) = hcat [
char '\t',
ptext (sLit "bctrl")
]
pprInstr (ADD reg1 reg2 ri) = pprLogic (sLit "add") reg1 reg2 ri
pprInstr (ADDI reg1 reg2 imm) = hcat [
char '\t',
ptext (sLit "addi"),
char '\t',
pprReg reg1,
ptext (sLit ", "),
pprReg reg2,
ptext (sLit ", "),
pprImm imm
]
pprInstr (ADDIS reg1 reg2 imm) = hcat [
char '\t',
ptext (sLit "addis"),
char '\t',
pprReg reg1,
ptext (sLit ", "),
pprReg reg2,
ptext (sLit ", "),
pprImm imm
]
pprInstr (ADDC reg1 reg2 reg3) = pprLogic (sLit "addc") reg1 reg2 (RIReg reg3)
pprInstr (ADDE reg1 reg2 reg3) = pprLogic (sLit "adde") reg1 reg2 (RIReg reg3)
pprInstr (SUBF reg1 reg2 reg3) = pprLogic (sLit "subf") reg1 reg2 (RIReg reg3)
pprInstr (SUBFC reg1 reg2 reg3) = pprLogic (sLit "subfc") reg1 reg2 (RIReg reg3)
pprInstr (SUBFE reg1 reg2 reg3) = pprLogic (sLit "subfe") reg1 reg2 (RIReg reg3)
pprInstr (MULLW reg1 reg2 ri@(RIReg _)) = pprLogic (sLit "mullw") reg1 reg2 ri
pprInstr (MULLW reg1 reg2 ri@(RIImm _)) = pprLogic (sLit "mull") reg1 reg2 ri
pprInstr (DIVW reg1 reg2 reg3) = pprLogic (sLit "divw") reg1 reg2 (RIReg reg3)
pprInstr (DIVWU reg1 reg2 reg3) = pprLogic (sLit "divwu") reg1 reg2 (RIReg reg3)
pprInstr (MULLW_MayOflo reg1 reg2 reg3) = vcat [
hcat [ ptext (sLit "\tmullwo\t"), pprReg reg1, ptext (sLit ", "),
pprReg reg2, ptext (sLit ", "),
pprReg reg3 ],
hcat [ ptext (sLit "\tmfxer\t"), pprReg reg1 ],
hcat [ ptext (sLit "\trlwinm\t"), pprReg reg1, ptext (sLit ", "),
pprReg reg1, ptext (sLit ", "),
ptext (sLit "2, 31, 31") ]
]
-- for some reason, "andi" doesn't exist.
-- we'll use "andi." instead.
pprInstr (AND reg1 reg2 (RIImm imm)) = hcat [
char '\t',
ptext (sLit "andi."),
char '\t',
pprReg reg1,
ptext (sLit ", "),
pprReg reg2,
ptext (sLit ", "),
pprImm imm
]
pprInstr (AND reg1 reg2 ri) = pprLogic (sLit "and") reg1 reg2 ri
pprInstr (OR reg1 reg2 ri) = pprLogic (sLit "or") reg1 reg2 ri
pprInstr (XOR reg1 reg2 ri) = pprLogic (sLit "xor") reg1 reg2 ri
pprInstr (XORIS reg1 reg2 imm) = hcat [
char '\t',
ptext (sLit "xoris"),
char '\t',
pprReg reg1,
ptext (sLit ", "),
pprReg reg2,
ptext (sLit ", "),
pprImm imm
]
pprInstr (EXTS sz reg1 reg2) = hcat [
char '\t',
ptext (sLit "exts"),
pprSize sz,
char '\t',
pprReg reg1,
ptext (sLit ", "),
pprReg reg2
]
pprInstr (NEG reg1 reg2) = pprUnary (sLit "neg") reg1 reg2
pprInstr (NOT reg1 reg2) = pprUnary (sLit "not") reg1 reg2
pprInstr (SLW reg1 reg2 ri) = pprLogic (sLit "slw") reg1 reg2 (limitShiftRI ri)
pprInstr (SRW reg1 reg2 (RIImm (ImmInt i))) | i > 31 || i < 0 =
-- Handle the case where we are asked to shift a 32 bit register by
-- less than zero or more than 31 bits. We convert this into a clear
-- of the destination register.
-- Fixes ticket http://ghc.haskell.org/trac/ghc/ticket/5900
pprInstr (XOR reg1 reg2 (RIReg reg2))
pprInstr (SRW reg1 reg2 ri) = pprLogic (sLit "srw") reg1 reg2 (limitShiftRI ri)
pprInstr (SRAW reg1 reg2 ri) = pprLogic (sLit "sraw") reg1 reg2 (limitShiftRI ri)
pprInstr (RLWINM reg1 reg2 sh mb me) = hcat [
ptext (sLit "\trlwinm\t"),
pprReg reg1,
ptext (sLit ", "),
pprReg reg2,
ptext (sLit ", "),
int sh,
ptext (sLit ", "),
int mb,
ptext (sLit ", "),
int me
]
pprInstr (FADD sz reg1 reg2 reg3) = pprBinaryF (sLit "fadd") sz reg1 reg2 reg3
pprInstr (FSUB sz reg1 reg2 reg3) = pprBinaryF (sLit "fsub") sz reg1 reg2 reg3
pprInstr (FMUL sz reg1 reg2 reg3) = pprBinaryF (sLit "fmul") sz reg1 reg2 reg3
pprInstr (FDIV sz reg1 reg2 reg3) = pprBinaryF (sLit "fdiv") sz reg1 reg2 reg3
pprInstr (FNEG reg1 reg2) = pprUnary (sLit "fneg") reg1 reg2
pprInstr (FCMP reg1 reg2) = hcat [
char '\t',
ptext (sLit "fcmpu\tcr0, "),
-- Note: we're using fcmpu, not fcmpo
-- The difference is with fcmpo, compare with NaN is an invalid operation.
-- We don't handle invalid fp ops, so we don't care
pprReg reg1,
ptext (sLit ", "),
pprReg reg2
]
pprInstr (FCTIWZ reg1 reg2) = pprUnary (sLit "fctiwz") reg1 reg2
pprInstr (FRSP reg1 reg2) = pprUnary (sLit "frsp") reg1 reg2
pprInstr (CRNOR dst src1 src2) = hcat [
ptext (sLit "\tcrnor\t"),
int dst,
ptext (sLit ", "),
int src1,
ptext (sLit ", "),
int src2
]
pprInstr (MFCR reg) = hcat [
char '\t',
ptext (sLit "mfcr"),
char '\t',
pprReg reg
]
pprInstr (MFLR reg) = hcat [
char '\t',
ptext (sLit "mflr"),
char '\t',
pprReg reg
]
pprInstr (FETCHPC reg) = vcat [
ptext (sLit "\tbcl\t20,31,1f"),
hcat [ ptext (sLit "1:\tmflr\t"), pprReg reg ]
]
pprInstr LWSYNC = ptext (sLit "\tlwsync")
-- pprInstr _ = panic "pprInstr (ppc)"
pprLogic :: LitString -> Reg -> Reg -> RI -> SDoc
pprLogic op reg1 reg2 ri = hcat [
char '\t',
ptext op,
case ri of
RIReg _ -> empty
RIImm _ -> char 'i',
char '\t',
pprReg reg1,
ptext (sLit ", "),
pprReg reg2,
ptext (sLit ", "),
pprRI ri
]
pprUnary :: LitString -> Reg -> Reg -> SDoc
pprUnary op reg1 reg2 = hcat [
char '\t',
ptext op,
char '\t',
pprReg reg1,
ptext (sLit ", "),
pprReg reg2
]
pprBinaryF :: LitString -> Size -> Reg -> Reg -> Reg -> SDoc
pprBinaryF op sz reg1 reg2 reg3 = hcat [
char '\t',
ptext op,
pprFSize sz,
char '\t',
pprReg reg1,
ptext (sLit ", "),
pprReg reg2,
ptext (sLit ", "),
pprReg reg3
]
pprRI :: RI -> SDoc
pprRI (RIReg r) = pprReg r
pprRI (RIImm r) = pprImm r
pprFSize :: Size -> SDoc
pprFSize FF64 = empty
pprFSize FF32 = char 's'
pprFSize _ = panic "PPC.Ppr.pprFSize: no match"
-- limit immediate argument for shift instruction to range 0..31
limitShiftRI :: RI -> RI
limitShiftRI (RIImm (ImmInt i)) | i > 31 || i < 0 =
panic $ "PPC.Ppr: Shift by " ++ show i ++ " bits is not allowed."
limitShiftRI x = x
|
forked-upstream-packages-for-ghcjs/ghc
|
compiler/nativeGen/PPC/Ppr.hs
|
bsd-3-clause
| 22,215 | 0 | 18 | 7,861 | 7,315 | 3,598 | 3,717 | 551 | 72 |
module Lib
( someFunc
) where
import Language.Haskell.TH
someFunc :: IO ()
someFunc = putStrLn "aaa"
|
mrkkrp/stack
|
test/integration/tests/717-sdist-test/files/package-with-failing-test/src/Lib.hs
|
bsd-3-clause
| 111 | 0 | 6 | 26 | 33 | 19 | 14 | 5 | 1 |
{-# LANGUAGE OverloadedStrings, QuasiQuotes, TemplateHaskell, TupleSections, GeneralizedNewtypeDeriving #-}
module Yesod.EmbeddedStatic.Css.Util where
import Control.Applicative
import Control.Monad (void, foldM)
import Data.Hashable (Hashable)
import Data.Monoid
import Network.Mime (MimeType, defaultMimeLookup)
import Text.CSS.Parse (parseBlocks)
import Language.Haskell.TH (litE, stringL)
import Text.CSS.Render (renderBlocks)
import Yesod.EmbeddedStatic.Types
import Yesod.EmbeddedStatic (pathToName)
import Data.Default (def)
import System.FilePath ((</>), takeFileName, takeDirectory, dropExtension)
import qualified Blaze.ByteString.Builder as B
import qualified Blaze.ByteString.Builder.Char.Utf8 as B
import qualified Data.Attoparsec.Text as P
import qualified Data.Attoparsec.ByteString.Lazy as PBL
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Base64 as B64
import qualified Data.HashMap.Lazy as M
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TL
-------------------------------------------------------------------------------
-- Loading CSS
-------------------------------------------------------------------------------
-- | In the parsed CSS, this will be an image reference that we want to replace.
-- the contents will be the filepath.
newtype UrlReference = UrlReference T.Text
deriving (Show, Eq, Hashable, Ord)
type EithUrl = (T.Text, Either T.Text UrlReference)
-- | The parsed CSS
type Css = [(T.Text, [EithUrl])]
-- | Parse the filename out of url('filename')
parseUrl :: P.Parser T.Text
parseUrl = do
P.skipSpace
void $ P.string "url('"
P.takeTill (== '\'')
checkForUrl :: T.Text -> T.Text -> EithUrl
checkForUrl n@("background-image") v = parseBackgroundImage n v
checkForUrl n@("src") v = parseBackgroundImage n v
checkForUrl n v = (n, Left v)
-- | Check if a given CSS attribute is a background image referencing a local file
checkForImage :: T.Text -> T.Text -> EithUrl
checkForImage n@("background-image") v = parseBackgroundImage n v
checkForImage n v = (n, Left v)
parseBackgroundImage :: T.Text -> T.Text -> EithUrl
parseBackgroundImage n v = (n, case P.parseOnly parseUrl v of
Left _ -> Left v -- Can't parse url
Right url -> -- maybe we should find a uri parser
if any (`T.isPrefixOf` url) ["http://", "https://", "/"]
then Left v
else Right $ UrlReference url)
parseCssWith :: (T.Text -> T.Text -> EithUrl) -> T.Text -> Either String Css
parseCssWith urlParser contents =
let mparsed = parseBlocks contents in
case mparsed of
Left err -> Left err
Right blocks -> Right [ (t, map (uncurry urlParser) b) | (t,b) <- blocks ]
parseCssUrls :: T.Text -> Either String Css
parseCssUrls = parseCssWith checkForUrl
parseCssFileWith :: (T.Text -> T.Text -> EithUrl) -> FilePath -> IO Css
parseCssFileWith urlParser fp = do
mparsed <- parseCssWith urlParser <$> T.readFile fp
case mparsed of
Left err -> fail $ "Unable to parse " ++ fp ++ ": " ++ err
Right css -> return css
parseCssFileUrls :: FilePath -> IO Css
parseCssFileUrls = parseCssFileWith checkForUrl
renderCssWith :: (UrlReference -> T.Text) -> Css -> TL.Text
renderCssWith urlRenderer css =
TL.toLazyText $ renderBlocks [(n, map render block) | (n,block) <- css]
where
render (n, Left b) = (n, b)
render (n, Right f) = (n, urlRenderer f)
-- | Load an image map from the images in the CSS
loadImages :: FilePath -> Css -> (FilePath -> IO (Maybe a)) -> IO (M.HashMap UrlReference a)
loadImages dir css loadImage = foldM load M.empty $ concat [map snd block | (_,block) <- css]
where
load imap (Left _) = return imap
load imap (Right f) | f `M.member` imap = return imap
load imap (Right f@(UrlReference path)) = do
img <- loadImage (dir </> T.unpack path)
return $ maybe imap (\i -> M.insert f i imap) img
-- | If you tack on additional CSS post-processing filters, they use this as an argument.
data CssGeneration = CssGeneration {
cssContent :: BL.ByteString
, cssStaticLocation :: Location
, cssFileLocation :: FilePath
}
mkCssGeneration :: Location -> FilePath -> BL.ByteString -> CssGeneration
mkCssGeneration loc file content =
CssGeneration { cssContent = content
, cssStaticLocation = loc
, cssFileLocation = file
}
cssProductionFilter ::
(FilePath -> IO BL.ByteString) -- ^ a filter to be run on production
-> Location -- ^ The location the CSS file should appear in the static subsite
-> FilePath -- ^ Path to the CSS file.
-> Entry
cssProductionFilter prodFilter loc file =
def { ebHaskellName = Just $ pathToName loc
, ebLocation = loc
, ebMimeType = "text/css"
, ebProductionContent = prodFilter file
, ebDevelReload = [| develPassThrough $(litE (stringL loc)) $(litE (stringL file)) |]
, ebDevelExtraFiles = Nothing
}
cssProductionImageFilter :: (FilePath -> IO BL.ByteString) -> Location -> FilePath -> Entry
cssProductionImageFilter prodFilter loc file =
(cssProductionFilter prodFilter loc file)
{ ebDevelReload = [| develBgImgB64 $(litE (stringL loc)) $(litE (stringL file)) |]
, ebDevelExtraFiles = Just [| develExtraFiles $(litE (stringL loc)) |]
}
-------------------------------------------------------------------------------
-- Helpers for the generators
-------------------------------------------------------------------------------
-- For development, all we need to do is update the background-image url to base64 encode it.
-- We want to preserve the formatting (whitespace+newlines) during development so we do not parse
-- using css-parse. Instead we write a simple custom parser.
parseBackground :: Location -> FilePath -> PBL.Parser B.Builder
parseBackground loc file = do
void $ PBL.string "background-image"
s1 <- PBL.takeWhile (\x -> x == 32 || x == 9) -- space or tab
void $ PBL.word8 58 -- colon
s2 <- PBL.takeWhile (\x -> x == 32 || x == 9) -- space or tab
void $ PBL.string "url('"
url <- PBL.takeWhile (/= 39) -- single quote
void $ PBL.string "')"
let b64 = B64.encode $ T.encodeUtf8 (T.pack $ takeDirectory file) <> url
newUrl = B.fromString (takeFileName loc) <> B.fromString "/" <> B.fromByteString b64
return $ B.fromByteString "background-image"
<> B.fromByteString s1
<> B.fromByteString ":"
<> B.fromByteString s2
<> B.fromByteString "url('"
<> newUrl
<> B.fromByteString "')"
parseDev :: Location -> FilePath -> B.Builder -> PBL.Parser B.Builder
parseDev loc file b = do
b' <- parseBackground loc file <|> (B.fromWord8 <$> PBL.anyWord8)
(PBL.endOfInput *> (pure $! b <> b')) <|> (parseDev loc file $! b <> b')
develPassThrough :: Location -> FilePath -> IO BL.ByteString
develPassThrough _ = BL.readFile
-- | Create the CSS during development
develBgImgB64 :: Location -> FilePath -> IO BL.ByteString
develBgImgB64 loc file = do
ct <- BL.readFile file
case PBL.eitherResult $ PBL.parse (parseDev loc file mempty) ct of
Left err -> error err
Right b -> return $ B.toLazyByteString b
-- | Serve the extra image files during development
develExtraFiles :: Location -> [T.Text] -> IO (Maybe (MimeType, BL.ByteString))
develExtraFiles loc parts =
case reverse parts of
(file:dir) | T.pack loc == T.intercalate "/" (reverse dir) -> do
let file' = T.decodeUtf8 $ B64.decodeLenient $ T.encodeUtf8 $ T.pack $ dropExtension $ T.unpack file
ct <- BL.readFile $ T.unpack file'
return $ Just (defaultMimeLookup file', ct)
_ -> return Nothing
|
psibi/yesod
|
yesod-static/Yesod/EmbeddedStatic/Css/Util.hs
|
mit
| 7,964 | 0 | 19 | 1,696 | 2,201 | 1,177 | 1,024 | 141 | 3 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.SVGElement
(getPresentationAttribute, getPresentationAttribute_, focus, blur,
getOwnerSVGElement, getViewportElement, setXmllang, getXmllang,
setXmlspace, getXmlspace, getClassName, setTabIndex, getTabIndex,
getDataset, SVGElement(..), gTypeSVGElement, IsSVGElement,
toSVGElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGElement.getPresentationAttribute Mozilla SVGElement.getPresentationAttribute documentation>
getPresentationAttribute ::
(MonadDOM m, IsSVGElement self, ToJSString name) =>
self -> Maybe name -> m CSSValue
getPresentationAttribute self name
= liftDOM
(((toSVGElement self) ^. jsf "getPresentationAttribute"
[toJSVal name])
>>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGElement.getPresentationAttribute Mozilla SVGElement.getPresentationAttribute documentation>
getPresentationAttribute_ ::
(MonadDOM m, IsSVGElement self, ToJSString name) =>
self -> Maybe name -> m ()
getPresentationAttribute_ self name
= liftDOM
(void
((toSVGElement self) ^. jsf "getPresentationAttribute"
[toJSVal name]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGElement.focus Mozilla SVGElement.focus documentation>
focus :: (MonadDOM m, IsSVGElement self) => self -> m ()
focus self = liftDOM (void ((toSVGElement self) ^. jsf "focus" ()))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGElement.blur Mozilla SVGElement.blur documentation>
blur :: (MonadDOM m, IsSVGElement self) => self -> m ()
blur self = liftDOM (void ((toSVGElement self) ^. jsf "blur" ()))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGElement.ownerSVGElement Mozilla SVGElement.ownerSVGElement documentation>
getOwnerSVGElement ::
(MonadDOM m, IsSVGElement self) => self -> m SVGSVGElement
getOwnerSVGElement self
= liftDOM
(((toSVGElement self) ^. js "ownerSVGElement") >>=
fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGElement.viewportElement Mozilla SVGElement.viewportElement documentation>
getViewportElement ::
(MonadDOM m, IsSVGElement self) => self -> m SVGElement
getViewportElement self
= liftDOM
(((toSVGElement self) ^. js "viewportElement") >>=
fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGElement.xmllang Mozilla SVGElement.xmllang documentation>
setXmllang ::
(MonadDOM m, IsSVGElement self, ToJSString val) =>
self -> val -> m ()
setXmllang self val
= liftDOM ((toSVGElement self) ^. jss "xmllang" (toJSVal val))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGElement.xmllang Mozilla SVGElement.xmllang documentation>
getXmllang ::
(MonadDOM m, IsSVGElement self, FromJSString result) =>
self -> m result
getXmllang self
= liftDOM
(((toSVGElement self) ^. js "xmllang") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGElement.xmlspace Mozilla SVGElement.xmlspace documentation>
setXmlspace ::
(MonadDOM m, IsSVGElement self, ToJSString val) =>
self -> val -> m ()
setXmlspace self val
= liftDOM ((toSVGElement self) ^. jss "xmlspace" (toJSVal val))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGElement.xmlspace Mozilla SVGElement.xmlspace documentation>
getXmlspace ::
(MonadDOM m, IsSVGElement self, FromJSString result) =>
self -> m result
getXmlspace self
= liftDOM
(((toSVGElement self) ^. js "xmlspace") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGElement.className Mozilla SVGElement.className documentation>
getClassName ::
(MonadDOM m, IsSVGElement self) => self -> m SVGAnimatedString
getClassName self
= liftDOM
(((toSVGElement self) ^. js "className") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGElement.tabIndex Mozilla SVGElement.tabIndex documentation>
setTabIndex ::
(MonadDOM m, IsSVGElement self) => self -> Int -> m ()
setTabIndex self val
= liftDOM ((toSVGElement self) ^. jss "tabIndex" (toJSVal val))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGElement.tabIndex Mozilla SVGElement.tabIndex documentation>
getTabIndex :: (MonadDOM m, IsSVGElement self) => self -> m Int
getTabIndex self
= liftDOM
(round <$>
(((toSVGElement self) ^. js "tabIndex") >>= valToNumber))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGElement.dataset Mozilla SVGElement.dataset documentation>
getDataset ::
(MonadDOM m, IsSVGElement self) => self -> m DOMStringMap
getDataset self
= liftDOM
(((toSVGElement self) ^. js "dataset") >>= fromJSValUnchecked)
|
ghcjs/jsaddle-dom
|
src/JSDOM/Generated/SVGElement.hs
|
mit
| 5,893 | 0 | 13 | 1,042 | 1,323 | 730 | 593 | 95 | 1 |
import Arbitrary
import Test.QuickCheck (Gen)
instance Arbitrary Ternery where
arbitrary = do
n <- choose (0,2) :: Gen Int
return $ case n of
0 -> Yes
1 -> No
_ -> Unknown
|
zhangjiji/real-world-haskell
|
ch11/Arbitrary2.hs
|
mit
| 209 | 0 | 11 | 70 | 78 | 40 | 38 | 9 | 0 |
import Control.Applicative
import Data.List.Split
import Control.Monad
import Debug.Trace
data Gender = Male | Female
deriving (Eq,Show)
main = do
r <- getFile "t4"
writeFile "t4.out" (unlines $ fmap action r)
getFile :: String -> IO [String]
getFile fp = (tail . lines) <$> readFile fp
action :: String -> String
action text = show $ parse
where
parse = answer $ read <$> splitOn " " text
answer :: [Int] -> Gender
answer (n:k:_) = kthChildNthGeneration1 n k
kthChildNthGeneration1 n k = trace ("kthChildNthGeneration " ++ show n ++ " " ++ show k) $ go
where
go = case (lookupMorse (k-1)) of
0 -> Male
1 -> Female
-- The generation doesn't matter as teh series is the same for each generation, so k and ignore n
lookupMorse :: Int -> Int
lookupMorse 0 = 0;
lookupMorse n | even n = lookupMorse (div n 2)
| otherwise = 1 - lookupMorse (div (n-1) 2)
--------------------------
-------------------------- First Draft Brute force code below, was to slow for large results found in t4 test case
-------------------------
kthChildNthGeneration :: Int -> Int -> Gender
kthChildNthGeneration n k = trace ("kthChildNthGeneration " ++ show n ++ " " ++ show k) $ generation n !! (k-1)
generation :: Int -> [Gender]
generation 1 = [Male]
generation x = apply $ generation (x - 1)
apply :: [Gender] -> [Gender]
apply xs = join $ fmap childern xs
childern :: Gender -> [Gender]
childern Male = [Male,Female]
childern Female = [Female, Male]
|
agbell/Rajesh
|
main.hs
|
mit
| 1,640 | 2 | 12 | 461 | 547 | 278 | 269 | 34 | 2 |
replicate' :: Int -> a -> [a]
replicate' n x = [x | _ <- [1..n]]
replicate'' :: Int -> a -> [a]
replicate'' n x = map (const x) [1..n]
main = do
print $ replicate' 3 True
print $ replicate'' 3 True
|
fabioyamate/programming-in-haskell
|
ch05/ex02.hs
|
mit
| 208 | 1 | 8 | 54 | 117 | 58 | 59 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module PostgREST.OpenAPI (
encodeOpenAPI
, isMalformedProxyUri
, pickProxy
) where
import Control.Lens
import Data.Aeson (decode, encode)
import Data.HashMap.Strict.InsOrd (InsOrdHashMap, fromList)
import Data.Maybe (fromJust)
import Data.String (IsString (..))
import Data.Text (unpack, pack, concat, intercalate, init, tail, toLower)
import qualified Data.Set as Set
import Network.URI (parseURI, isAbsoluteURI,
URI (..), URIAuth (..))
import Protolude hiding (concat, (&), Proxy, get, intercalate)
import Data.Swagger
import PostgREST.ApiRequest (ContentType(..), toHeader)
import PostgREST.Config (prettyVersion)
import PostgREST.QueryBuilder (operators)
import PostgREST.Types (Table(..), Column(..), PgArg(..),
Proxy(..), ProcDescription(..))
makeMimeList :: [ContentType] -> MimeList
makeMimeList cs = MimeList $ map (fromString . toS . toHeader) cs
toSwaggerType :: Text -> SwaggerType t
toSwaggerType "text" = SwaggerString
toSwaggerType "integer" = SwaggerInteger
toSwaggerType "boolean" = SwaggerBoolean
toSwaggerType "numeric" = SwaggerNumber
toSwaggerType _ = SwaggerString
makeTableDef :: (Table, [Column], [Text]) -> (Text, Schema)
makeTableDef (t, cs, _) =
let tn = tableName t in
(tn, (mempty :: Schema)
& type_ .~ SwaggerObject
& properties .~ fromList (map makeProperty cs))
makeProperty :: Column -> (Text, Referenced Schema)
makeProperty c = (colName c, Inline u)
where
r = mempty :: Schema
s = if null $ colEnum c
then r
else r & enum_ .~ decode (encode (colEnum c))
t = s & type_ .~ toSwaggerType (colType c)
u = t & format ?~ colType c
makeProcDef :: ProcDescription -> (Text, Schema)
makeProcDef pd = ("(rpc) " <> pdName pd, s)
where
s = (mempty :: Schema)
& type_ .~ SwaggerObject
& properties .~ fromList (map makeProcProperty (pdArgs pd))
& required .~ map pgaName (filter pgaReq (pdArgs pd))
makeProcProperty :: PgArg -> (Text, Referenced Schema)
makeProcProperty (PgArg n t _) = (n, Inline s)
where
s = (mempty :: Schema)
& type_ .~ toSwaggerType t
& format ?~ t
makeOperatorPattern :: Text
makeOperatorPattern =
intercalate "|"
[ concat ["^", x, y, "[.]"] |
x <- ["not[.]", ""],
y <- map fst operators ]
makeRowFilter :: Column -> Param
makeRowFilter c =
(mempty :: Param)
& name .~ colName c
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamQuery
& type_ .~ SwaggerString
& format ?~ colType c
& pattern ?~ makeOperatorPattern)
makeRowFilters :: [Column] -> [Param]
makeRowFilters = map makeRowFilter
makeOrderItems :: [Column] -> [Text]
makeOrderItems cs =
[ concat [x, y, z] |
x <- map colName cs,
y <- [".asc", ".desc", ""],
z <- [".nullsfirst", ".nulllast", ""]
]
makeRangeParams :: [Param]
makeRangeParams =
[ (mempty :: Param)
& name .~ "Range"
& description ?~ "Limiting and Pagination"
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamHeader
& type_ .~ SwaggerString)
, (mempty :: Param)
& name .~ "Range-Unit"
& description ?~ "Limiting and Pagination"
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamHeader
& type_ .~ SwaggerString
& default_ .~ decode "\"items\"")
, (mempty :: Param)
& name .~ "offset"
& description ?~ "Limiting and Pagination"
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamQuery
& type_ .~ SwaggerString)
, (mempty :: Param)
& name .~ "limit"
& description ?~ "Limiting and Pagination"
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamQuery
& type_ .~ SwaggerString)
]
makePreferParam :: [Text] -> Param
makePreferParam ts =
(mempty :: Param)
& name .~ "Prefer"
& description ?~ "Preference"
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamHeader
& type_ .~ SwaggerString
& enum_ .~ decode (encode ts))
makeSelectParam :: Param
makeSelectParam =
(mempty :: Param)
& name .~ "select"
& description ?~ "Filtering Columns"
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamQuery
& type_ .~ SwaggerString)
makeGetParams :: [Column] -> [Param]
makeGetParams [] =
makeRangeParams ++
[ makeSelectParam
, makePreferParam ["plurality=singular", "count=none"]
]
makeGetParams cs =
makeRangeParams ++
[ makeSelectParam
, (mempty :: Param)
& name .~ "order"
& description ?~ "Ordering"
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamQuery
& type_ .~ SwaggerString
& enum_ .~ decode (encode $ makeOrderItems cs))
, makePreferParam ["plurality=singular", "count=none"]
]
makePostParams :: Text -> [Param]
makePostParams tn =
[ makePreferParam ["return=representation", "return=representation,plurality=singular",
"return=minimal", "return=none"]
, (mempty :: Param)
& name .~ "body"
& description ?~ tn
& required ?~ False
& schema .~ ParamBody (Ref (Reference tn))
]
makeProcParam :: Text -> Param
makeProcParam refName =
(mempty :: Param)
& name .~ "args"
& required ?~ True
& schema .~ ParamBody (Ref (Reference refName))
makeDeleteParams :: [Param]
makeDeleteParams =
[ makePreferParam ["return=representation", "return=minimal", "return=none"] ]
makePathItem :: (Table, [Column], [Text]) -> (FilePath, PathItem)
makePathItem (t, cs, _) = ("/" ++ unpack tn, p $ tableInsertable t)
where
tOp = (mempty :: Operation)
& tags .~ Set.fromList [tn]
& produces ?~ makeMimeList [CTApplicationJSON, CTTextCSV]
& at 200 ?~ "OK"
getOp = tOp
& parameters .~ map Inline (makeGetParams cs ++ rs)
& at 206 ?~ "Partial Content"
postOp = tOp
& consumes ?~ makeMimeList [CTApplicationJSON, CTTextCSV]
& parameters .~ map Inline (makePostParams tn)
& at 201 ?~ "Created"
patchOp = tOp
& consumes ?~ makeMimeList [CTApplicationJSON, CTTextCSV]
& parameters .~ map Inline (makePostParams tn ++ rs)
& at 204 ?~ "No Content"
deletOp = tOp
& parameters .~ map Inline (makeDeleteParams ++ rs)
pr = (mempty :: PathItem) & get ?~ getOp
pw = pr & post ?~ postOp & patch ?~ patchOp & delete ?~ deletOp
p False = pr
p True = pw
rs = makeRowFilters cs
tn = tableName t
makeProcPathItem :: ProcDescription -> (FilePath, PathItem)
makeProcPathItem pd = ("/rpc/" ++ toS (pdName pd), pe)
where
postOp = (mempty :: Operation)
& parameters .~ [Inline (makeProcParam $ "(rpc) " <> pdName pd)]
& tags .~ Set.fromList ["(rpc) " <> pdName pd]
& produces ?~ makeMimeList [CTApplicationJSON]
& at 200 ?~ "OK"
pe = (mempty :: PathItem) & post ?~ postOp
makeRootPathItem :: (FilePath, PathItem)
makeRootPathItem = ("/", p)
where
getOp = (mempty :: Operation)
& tags .~ Set.fromList ["/"]
& produces ?~ makeMimeList [CTOpenAPI]
& at 200 ?~ "OK"
pr = (mempty :: PathItem) & get ?~ getOp
p = pr
makePathItems :: [ProcDescription] -> [(Table, [Column], [Text])] -> InsOrdHashMap FilePath PathItem
makePathItems pds ti = fromList $ makeRootPathItem :
map makePathItem ti ++ map makeProcPathItem pds
escapeHostName :: Text -> Text
escapeHostName "*" = "0.0.0.0"
escapeHostName "*4" = "0.0.0.0"
escapeHostName "!4" = "0.0.0.0"
escapeHostName "*6" = "0.0.0.0"
escapeHostName "!6" = "0.0.0.0"
escapeHostName h = h
postgrestSpec :: [ProcDescription] -> [(Table, [Column], [Text])] -> (Text, Text, Integer, Text) -> Swagger
postgrestSpec pds ti (s, h, p, b) = (mempty :: Swagger)
& basePath ?~ unpack b
& schemes ?~ [s']
& info .~ ((mempty :: Info)
& version .~ prettyVersion
& title .~ "PostgREST API"
& description ?~ "This is a dynamic API generated by PostgREST")
& host .~ h'
& definitions .~ fromList (map makeTableDef ti <> map makeProcDef pds)
& paths .~ makePathItems pds ti
where
s' = if s == "http" then Http else Https
h' = Just $ Host (unpack $ escapeHostName h) (Just (fromInteger p))
encodeOpenAPI :: [ProcDescription] -> [(Table, [Column], [Text])] -> (Text, Text, Integer, Text) -> LByteString
encodeOpenAPI pds ti uri = encode $ postgrestSpec pds ti uri
{-|
Test whether a proxy uri is malformed or not.
A valid proxy uri should be an absolute uri without query and user info,
only http(s) schemes are valid, port number range is 1-65535.
For example
http://postgrest.com/openapi.json
https://postgrest.com:8080/openapi.json
-}
isMalformedProxyUri :: Maybe Text -> Bool
isMalformedProxyUri Nothing = False
isMalformedProxyUri (Just uri)
| isAbsoluteURI (toS uri) = not $ isUriValid $ toURI uri
| otherwise = True
toURI :: Text -> URI
toURI uri = fromJust $ parseURI (toS uri)
pickProxy :: Maybe Text -> Maybe Proxy
pickProxy proxy
| isNothing proxy = Nothing
-- should never happen
-- since the request would have been rejected by the middleware if proxy uri
-- is malformed
| isMalformedProxyUri proxy = Nothing
| otherwise = Just Proxy {
proxyScheme = scheme
, proxyHost = host'
, proxyPort = port''
, proxyPath = path'
}
where
uri = toURI $ fromJust proxy
scheme = init $ toLower $ pack $ uriScheme uri
path URI {uriPath = ""} = "/"
path URI {uriPath = p} = p
path' = pack $ path uri
authority = fromJust $ uriAuthority uri
host' = pack $ uriRegName authority
port' = uriPort authority
readPort = fromMaybe 80 . readMaybe
port'' :: Integer
port'' = case (port', scheme) of
("", "http") -> 80
("", "https") -> 443
_ -> readPort $ unpack $ tail $ pack port'
isUriValid:: URI -> Bool
isUriValid = fAnd [isSchemeValid, isQueryValid, isAuthorityValid]
fAnd :: [a -> Bool] -> a -> Bool
fAnd fs x = all ($x) fs
isSchemeValid :: URI -> Bool
isSchemeValid URI {uriScheme = s}
| toLower (pack s) == "https:" = True
| toLower (pack s) == "http:" = True
| otherwise = False
isQueryValid :: URI -> Bool
isQueryValid URI {uriQuery = ""} = True
isQueryValid _ = False
isAuthorityValid :: URI -> Bool
isAuthorityValid URI {uriAuthority = a}
| isJust a = fAnd [isUserInfoValid, isHostValid, isPortValid] $ fromJust a
| otherwise = False
isUserInfoValid :: URIAuth -> Bool
isUserInfoValid URIAuth {uriUserInfo = ""} = True
isUserInfoValid _ = False
isHostValid :: URIAuth -> Bool
isHostValid URIAuth {uriRegName = ""} = False
isHostValid _ = True
isPortValid :: URIAuth -> Bool
isPortValid URIAuth {uriPort = ""} = True
isPortValid URIAuth {uriPort = (':':p)} =
case readMaybe p of
Just i -> i > (0 :: Integer) && i < 65536
Nothing -> False
isPortValid _ = False
|
NotBrianZach/postgrest
|
src/PostgREST/OpenAPI.hs
|
mit
| 11,479 | 0 | 19 | 2,969 | 3,693 | 1,989 | 1,704 | 288 | 4 |
module HSatArbitrary (
) where
|
aburnett88/HSat
|
tests-src/HSatArbitrary.hs
|
mit
| 35 | 0 | 3 | 9 | 7 | 5 | 2 | 1 | 0 |
module L (
module L.Compiler
,module L.ReplTools
,module L.L1.L1
,module L.L2.L2
,module L.L3.L3
,module L.L4.L4
,module L.L5.L5
) where
import L.Compiler
import L.L1.L1
import L.L2.L2
import L.L3.L3
import L.L4.L4
import L.L5.L5
import L.ReplTools
|
joshcough/L5-Haskell
|
src/L.hs
|
mit
| 257 | 0 | 5 | 41 | 93 | 63 | 30 | 15 | 0 |
module GHCJS.DOM.FontLoader (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/FontLoader.hs
|
mit
| 40 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
{-# LANGUAGE QuasiQuotes #-}
module TestDataSpec ( testGetAllBoids
, testGetBoidById
, testGetBoidsGroupById
) where
import Test.HUnit
import Test.HUnit.Approx
import TestData
import Boids
import Text.XML.Light.Input
import Data.List
import Data.Function
import Data.Maybe
import Text.InterpolatedString.QM (qm)
errorMargin :: Float
errorMargin = 1e-6
assertBoidsListsEqual :: [Boid] -> [Boid] -> Assertion
assertBoidsListsEqual expectedBoids actualBoids = sequence_ assertions
where expectedBoids' = sort expectedBoids
actualBoids' = sort actualBoids
lengthEquality = assertEqual "" (length expectedBoids) (length actualBoids)
assertions = lengthEquality : (map (uncurry $ assertBoidsEqual) $ zip expectedBoids' actualBoids')
assertBoidsEqual :: Boid -> Boid -> Assertion
assertBoidsEqual expectedBoid actualBoid = sequence_ assertions
where
properties = [ (fst . boidPosition, "X coordinates were not equal")
, (snd . boidPosition, "Y coordinates were not equal")
, (boidHeading, "Headings were not equal")
, (boidSteer, "Steers were not equal") ]
assertions = map makeAssertion properties
makeAssertion (f, message) = assertApproxEqual message errorMargin (f expectedBoid) (f actualBoid)
boidsEqualTest :: Boid -> Boid -> Test
boidsEqualTest expectedBoid actualBoid = TestLabel message $ TestList assertions
where
message = concat ["Expected: "
, show expectedBoid
, ", Actual: "
, show actualBoid
]
properties = [ (fst . boidPosition, "X coordinate")
, (snd . boidPosition, "Y coordinate")
, (boidHeading, "Heading")
, (boidSteer, "Steer") ]
assertions = map assertBoidsEqual properties
assertBoidsEqual (f, message) = TestCase (assertApproxEqual message errorMargin (f expectedBoid) (f actualBoid))
testGetAllBoids :: Test
testGetAllBoids = TestList $ map (uncurry $ boidsEqualTest) $ zip allBoids expectedBoids
where xmlData = [qm| <svg xmlns='http://www.w3.org/2000/svg'>
<circle cx='349.0011' cy='426.28027' />
<g>
<circle cx='356.3743' cy='234.00' />
<circle cx='123.459' cy='668.46458' />
</g>
<circle cx='972.374' cy='33.34923' />
</svg>
|]
xmlRoot = parseXMLDoc (xmlData :: String)
expectedBoids = [ Boid {boidPosition = (349.0011,426.28027), boidHeading = 0.0, boidSteer = 0.0}
, Boid {boidPosition = (356.3743,234.0), boidHeading = 0.0, boidSteer = 0.0}
, Boid {boidPosition = (123.459,668.4646), boidHeading = 0.0, boidSteer = 0.0}
, Boid {boidPosition = (972.374,33.34923), boidHeading = 0.0, boidSteer = 0.0}
]
allBoids = getAllBoids xmlRoot
testGetBoidById :: Test
testGetBoidById = TestList [ fromMaybe (TestCase $ assertFailure "Could not find boid with id 'pivot'") positiveTestCase
, negativeTestCase
]
where expectedBoid = Boid {boidPosition = (349.0011,426.28027), boidHeading = 0.0, boidSteer = 0.0}
xmlData = [qm| <svg xmlns='http://www.w3.org/2000/svg'>
<circle id='pivot' cx='349.0011' cy='426.28027' />
<circle cx='972.374' cy='33.34923' />
</svg>
|]
xmlRoot = parseXMLDoc (xmlData :: String)
positiveTestCase = do actualBoid <- getBoidById xmlRoot "pivot"
return $ TestList [boidsEqualTest expectedBoid actualBoid]
negativeTestCase = TestCase (assertBool "Found non-existing element" $ isNothing $ getBoidById xmlRoot "khooy")
testGetBoidsGroupById :: Test
testGetBoidsGroupById = TestList [ TestLabel "Non-existing group id" nonExistingIdCase
, TestLabel "Inner group" innerGroupCase
, TestLabel "Outer group" outerGroupCase ]
where xmlData = [qm| <svg xmlns='http://www.w3.org/2000/svg'>
<g id='outer'>
<circle cx='326' cy='155' />
<circle cx='478' cy='419' />
<circle cx='107' cy='449' />
<g id='inner'>
<circle cx='102' cy='152' />
<circle cx='327' cy='246' />
<circle cx='444' cy='358' />
</g>
</g>
</svg>
|]
xmlRoot = parseXMLDoc (xmlData :: String)
nonExistingIdCase = TestCase (assertBool "Found non-existing elements" $ null $ getBoidsGroupById xmlRoot "blah")
innerGroupCase = TestCase (assertBoidsListsEqual expectedInnerBoids actualInnerBoids)
where
expectedInnerBoids = [ Boid { boidPosition = (102, 152), boidHeading = 0.0, boidSteer = 0.0 }
, Boid { boidPosition = (327, 246), boidHeading = 0.0, boidSteer = 0.0 }
, Boid { boidPosition = (444, 358), boidHeading = 0.0, boidSteer = 0.0 }
]
actualInnerBoids = getBoidsGroupById xmlRoot "inner"
outerGroupCase = TestCase (assertBoidsListsEqual expectedOuterBoids actualOuterBoids)
where
expectedOuterBoids = [ Boid { boidPosition = (102, 152), boidHeading = 0.0, boidSteer = 0.0 }
, Boid { boidPosition = (327, 246), boidHeading = 0.0, boidSteer = 0.0 }
, Boid { boidPosition = (444, 358), boidHeading = 0.0, boidSteer = 0.0 }
, Boid { boidPosition = (326, 155), boidHeading = 0.0, boidSteer = 0.0 }
, Boid { boidPosition = (478, 419), boidHeading = 0.0, boidSteer = 0.0 }
, Boid { boidPosition = (107, 449), boidHeading = 0.0, boidSteer = 0.0 }
]
actualOuterBoids = getBoidsGroupById xmlRoot "outer"
|
tsoding/boids
|
test/TestDataSpec.hs
|
mit
| 6,617 | 0 | 12 | 2,457 | 1,219 | 711 | 508 | 79 | 1 |
module Text.Docvim.Visitor.Functions (extractFunctions) where
import Control.Applicative
import Text.Docvim.AST
import Text.Docvim.Visitor
-- | Extracts a list of nodes (if any exist) from the `@functions` section(s) of
-- the source code.
--
-- It is not recommended to have multiple `@functions` sections in a project. If
-- multiple such sections (potentially across multiple translation units) exist,
-- there are no guarantees about order; they just get concatenated in the order
-- we see them.
extractFunctions :: Alternative f => [Node] -> (f [Node], [Node])
extractFunctions = extractBlocks f
where
f x = if x == FunctionsAnnotation
then Just endSection
else Nothing
|
wincent/docvim
|
lib/Text/Docvim/Visitor/Functions.hs
|
mit
| 704 | 0 | 9 | 127 | 104 | 63 | 41 | 9 | 2 |
{- Copyright (C) 2014 Calvin Beck
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}
{-# LANGUAGE OverloadedStrings #-}
module FeatureSquish.Parser (parsePSSP) where
import FeatureSquish.InputLine
import Control.Applicative
import Control.Arrow
import Data.Attoparsec.Text
import Data.Maybe
import Prelude hiding (takeWhile)
-- | Parse PSSP data, either in CSV or MTLR format.
parsePSSP :: Parser [InputLine]
parsePSSP = parseCSV <|> parseMTLR
-- | Parse a file of MTLR data.
parseMTLR :: Parser [InputLine]
parseMTLR = do inps <- many parseMTLRLine
endOfInput
return inps
-- | Parse a single line of MTLR data.
parseMTLRLine :: Parser InputLine
parseMTLRLine = do time <- double
skipSpace
censored <- decimal
skipSpace
features <- many parseMTLRFeature
endOfLine'
return (InputLine time (censored /= 0) features)
-- | Parse a single feature:value pair for MTLR.
parseMTLRFeature :: Parser (Integer, Double)
parseMTLRFeature = do skipSpace
feature <- decimal
char ':'
value <- double
return (feature, value)
-- | Parse a CSV file of data.
parseCSV :: Parser [InputLine]
parseCSV = do header <- (do csv <- parseCSVLine; return [csv]) <|> (skipToEndOfLine *> return [])
inps <- many parseCSVLine
return inps
-- | Parse a single line of CSV data.
parseCSVLine :: Parser InputLine
parseCSVLine = do event <- double
char ','
skipSpace
censored <- decimal
features <- many parseCSVFeature
endOfLine'
return (InputLine event (censored /= 0) (map (fst &&& fromJust . snd) $ filter (isJust . snd) (zip [1..] features)))
-- | Parse a single feature from CSV data.
parseCSVFeature :: Parser (Maybe Double)
parseCSVFeature =
do char ','
skipSpace
(do value <- double; return (Just value)) <|> (skipWhile (/= ',') *> return Nothing) <|> (skipToEndOfLine *> return Nothing)
-- | Newline parser to handle all sorts of horrible.
endOfLine' :: Parser ()
endOfLine' = endOfLine <|> endOfInput <|> (char '\r' *> return ())
-- | Skip to the next line...
skipToEndOfLine :: Parser ()
skipToEndOfLine = takeWhile (\c -> c /= '\n' && c /= '\r') >> endOfLine'
|
Chobbes/FeatureSquish
|
FeatureSquish/Parser.hs
|
mit
| 3,456 | 0 | 15 | 918 | 595 | 299 | 296 | -1 | -1 |
module Wf.Control.Eff.Run.Logger.File
(
) where
|
bigsleep/Wf
|
src/Wf/Control/Eff/Run/Logger/File.hs
|
mit
| 48 | 0 | 3 | 5 | 13 | 10 | 3 | 2 | 0 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.SVGPathSegMovetoAbs
(setX, getX, setY, getY, SVGPathSegMovetoAbs(..),
gTypeSVGPathSegMovetoAbs)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegMovetoAbs.x Mozilla SVGPathSegMovetoAbs.x documentation>
setX :: (MonadDOM m) => SVGPathSegMovetoAbs -> Float -> m ()
setX self val = liftDOM (self ^. jss "x" (toJSVal val))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegMovetoAbs.x Mozilla SVGPathSegMovetoAbs.x documentation>
getX :: (MonadDOM m) => SVGPathSegMovetoAbs -> m Float
getX self
= liftDOM (realToFrac <$> ((self ^. js "x") >>= valToNumber))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegMovetoAbs.y Mozilla SVGPathSegMovetoAbs.y documentation>
setY :: (MonadDOM m) => SVGPathSegMovetoAbs -> Float -> m ()
setY self val = liftDOM (self ^. jss "y" (toJSVal val))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegMovetoAbs.y Mozilla SVGPathSegMovetoAbs.y documentation>
getY :: (MonadDOM m) => SVGPathSegMovetoAbs -> m Float
getY self
= liftDOM (realToFrac <$> ((self ^. js "y") >>= valToNumber))
|
ghcjs/jsaddle-dom
|
src/JSDOM/Generated/SVGPathSegMovetoAbs.hs
|
mit
| 2,049 | 0 | 12 | 249 | 536 | 324 | 212 | 29 | 1 |
{-# LANGUAGE DeriveGeneric #-}
module Foundation where
import Import.NoFoundation
import Database.Persist.Sql (ConnectionPool, runSqlPool)
import Text.Hamlet (hamletFile)
import Text.Jasmine (minifym)
import Yesod.Auth.OAuth2.Google
import Yesod.Auth.OAuth2 (getAccessToken, getUserResponseJSON)
-- Used only when in "auth-dummy-login" setting is enabled.
import Yesod.Auth.Dummy
import Yesod.Default.Util (addStaticContentExternal)
import Yesod.Core.Types (Logger)
import qualified Yesod.Core.Unsafe as Unsafe
import qualified Data.CaseInsensitive as CI
import qualified Data.Text.Encoding as TE
-- | The foundation datatype for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data App = App
{ appSettings :: AppSettings
, appStatic :: Static -- ^ Settings for static file serving.
, appConnPool :: ConnectionPool -- ^ Database connection pool.
, appHttpManager :: Manager
, appLogger :: Logger
}
data MenuItem = MenuItem
{ menuItemLabel :: Text
, menuItemRoute :: Route App
, menuItemAccessCallback :: Bool
}
data MenuTypes
= NavbarLeft MenuItem
| NavbarRight MenuItem
data GoogleUser
= GoogleUser
{ email :: Text }
deriving Generic
instance FromJSON GoogleUser
-- i18n
mkMessage "App" "messages" "en"
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/routing-and-handlers
--
-- Note that this is really half the story; in Application.hs, mkYesodDispatch
-- generates the rest of the code. Please see the following documentation
-- for an explanation for this split:
-- http://www.yesodweb.com/book/scaffolding-and-the-site-template#scaffolding-and-the-site-template_foundation_and_application_modules
--
-- This function also generates the following type synonyms:
-- type Handler = HandlerT App IO
-- type Widget = WidgetT App IO ()
mkYesodData "App" $(parseRoutesFile "config/routes")
-- | A convenient synonym for creating forms.
type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget)
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
-- Controls the base of generated URLs. For more information on modifying,
-- see: https://github.com/yesodweb/yesod/wiki/Overriding-approot
approot = ApprootRequest $ \app req ->
fromMaybe (getApprootText guessApproot app req) (appRoot $ appSettings app)
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = Just <$> defaultClientSessionBackend
(60 * 24 * 14) -- timeout in minutes: two weeks
"config/client_session_key.aes"
-- Yesod Middleware allows you to run code before and after each handler function.
-- The defaultYesodMiddleware adds the response header "Vary: Accept, Accept-Language" and performs authorization checks.
-- Some users may also want to add the defaultCsrfMiddleware, which:
-- a) Sets a cookie with a CSRF token in it.
-- b) Validates that incoming write requests include that token in either a header or POST parameter.
-- To add it, chain it together with the defaultMiddleware: yesodMiddleware = defaultYesodMiddleware . defaultCsrfMiddleware
-- For details, see the CSRF documentation in the Yesod.Core.Handler module of the yesod-core package.
yesodMiddleware = defaultYesodMiddleware
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
msgRender <- getMessageRender
muser <- maybeAuthPair
mcurrentRoute <- getCurrentRoute
-- Define the menu items of the header.
let menuItems =
[ NavbarLeft MenuItem
{ menuItemLabel = msgRender MsgHome
, menuItemRoute = HomeR
, menuItemAccessCallback = True
}
, NavbarLeft MenuItem
{ menuItemLabel = msgRender MsgMyTasks
, menuItemRoute = FrontendR []
, menuItemAccessCallback = isJust muser
}
, NavbarRight MenuItem
{ menuItemLabel = msgRender MsgLogin
, menuItemRoute = AuthR LoginR
, menuItemAccessCallback = isNothing muser
}
, NavbarRight MenuItem
{ menuItemLabel = msgRender MsgLogout
, menuItemRoute = AuthR LogoutR
, menuItemAccessCallback = isJust muser
}
]
let navbarLeftMenuItems = [x | NavbarLeft x <- menuItems]
let navbarRightMenuItems = [x | NavbarRight x <- menuItems]
let navbarLeftFilteredMenuItems = [x | x <- navbarLeftMenuItems, menuItemAccessCallback x]
let navbarRightFilteredMenuItems = [x | x <- navbarRightMenuItems, menuItemAccessCallback x]
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
addStylesheet $ StaticR css_bootstrap_css
addStylesheet $ StaticR css_icomoon_css
$(widgetFile "default-layout")
withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
-- The page to be redirected to when authentication is required.
authRoute _ = Just $ AuthR LoginR
isAuthorized TasksR _ = isAuthenticated
isAuthorized (TaskR _) _ = isAuthenticated
isAuthorized _ _ = return Authorized
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent ext mime content = do
master <- getYesod
let staticDir = appStaticDir $ appSettings master
addStaticContentExternal
minifym
genFileName
staticDir
(StaticR . flip StaticRoute [])
ext
mime
content
where
-- Generate a unique filename based on the content itself
genFileName lbs = "autogen-" ++ base64md5 lbs
-- What messages should be logged. The following includes all messages when
-- in development, and warnings and errors in production.
shouldLog app _source level =
appShouldLogAll (appSettings app)
|| level == LevelWarn
|| level == LevelError
makeLogger = return . appLogger
-- Provide proper Bootstrap styling for default displays, like
-- error pages
defaultMessageWidget title body = $(widgetFile "default-message-widget")
-- How to run database actions.
instance YesodPersist App where
type YesodPersistBackend App = SqlBackend
runDB action = do
master <- getYesod
runSqlPool action $ appConnPool master
instance YesodPersistRunner App where
getDBRunner = defaultGetDBRunner appConnPool
instance YesodAuth App where
type AuthId App = UserId
-- Where to send a user after successful login
loginDest _ = FrontendR ["task-list"]
-- Where to send a user after logout
logoutDest _ = HomeR
authenticate creds = runDB $ do
let Right userEmail = email <$> getUserResponseJSON creds
updatedCreds = creds { credsIdent = userEmail }
x <- getBy $ UniqueUser $ credsIdent updatedCreds
case x of
Just (Entity uid _) -> return $ Authenticated uid
Nothing -> Authenticated <$> insert User
{ userIdent = credsIdent updatedCreds
, userPassword = Nothing
}
-- You can add other plugins like Google Email, email or OAuth here
authPlugins app = oauth2GoogleScoped ["email", "profile"] (appGAuthClientId $ appSettings app) (appGAuthClientSecret $ appSettings app) : extraAuthPlugins
-- Enable authDummy login if enabled.
where extraAuthPlugins = [authDummy | appAuthDummyLogin $ appSettings app]
authHttpManager = getHttpManager
-- | Access function to determine if a user is logged in.
isAuthenticated :: Handler AuthResult
isAuthenticated = do
muid <- maybeAuthId
return $ case muid of
Nothing -> Unauthorized "You must login to access this page"
Just _ -> Authorized
instance YesodAuthPersist App
-- This instance is required to use forms. You can modify renderMessage to
-- achieve customized and internationalized form validation messages.
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
-- Useful when writing code that is re-usable outside of the Handler context.
-- An example is background jobs that send email.
-- This can also be useful for writing code that works across multiple Yesod applications.
instance HasHttpManager App where
getHttpManager = appHttpManager
unsafeHandler :: App -> Handler a -> IO a
unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger
-- Note: Some functionality previously present in the scaffolding has been
-- moved to documentation in the Wiki. Following are some hopefully helpful
-- links:
--
-- https://github.com/yesodweb/yesod/wiki/Sending-email
-- https://github.com/yesodweb/yesod/wiki/Serve-static-files-from-a-separate-domain
-- https://github.com/yesodweb/yesod/wiki/i18n-messages-in-the-scaffolding
|
frt/happyscheduler
|
Foundation.hs
|
mit
| 9,994 | 0 | 16 | 2,481 | 1,392 | 751 | 641 | -1 | -1 |
-- C->Haskell Compiler: traversals of C structure tree
--
-- Author : Manuel M. T. Chakravarty
-- Created: 16 October 99
--
-- Copyright (c) [1999..2001] Manuel M. T. Chakravarty
--
-- This file is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This file 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.
--
--- DESCRIPTION ---------------------------------------------------------------
--
-- This modules provides for traversals of C structure trees. The C
-- traversal monad supports traversals that need convenient access to the
-- attributes of an attributed C structure tree. The monads state can still
-- be extended.
--
--- DOCU ----------------------------------------------------------------------
--
-- language: Haskell 98
--
-- Handling of redefined tag values
-- --------------------------------
--
-- Structures allow both
--
-- struct s {...} ...;
-- struct s ...;
--
-- and
--
-- struct s ...; /* this is called a forward reference */
-- struct s {...} ...;
--
-- In contrast enumerations only allow (in ANSI C)
--
-- enum e {...} ...;
-- enum e ...;
--
-- The function `defTag' handles both types and establishes an object
-- association from the tag identifier in the empty declaration (ie, the one
-- without `{...}') to the actually definition of the structure of
-- enumeration. This implies that when looking for the details of a
-- structure or enumeration, possibly a chain of references on tag
-- identifiers has to be chased. Note that the object association attribute
-- is _not_defined_ when the `{...}' part is present in a declaration.
--
--- TODO ----------------------------------------------------------------------
--
-- * `extractStruct' doesn't account for forward declarations that have no
-- full declaration yet; if `extractStruct' is called on such a declaration,
-- we have a user error, but currently an internal error is raised
--
module C2HS.C.Trav (CT, readCT, transCT, runCT, throwCTExc, ifCTExc,
raiseErrorCTExc,
enter, enterObjs, leave, leaveObjs, defObj, findObj,
findObjShadow, defTag, findTag, findTagShadow,
applyPrefixToNameSpaces, getDefOf, refersToDef, refersToNewDef,
getDeclOf, findTypeObjMaybe, findTypeObj, findValueObj,
findFunObj,
--
-- C structure tree query functions
--
isTypedef, simplifyDecl, declrFromDecl, declrNamed,
declaredDeclr, initDeclr, declaredName, structMembers, expandDecl,
structName, enumName, tagName, isPtrDeclr, isArrDeclr,
dropPtrDeclr, isPtrDecl, isArrDecl, isFunDeclr, structFromDecl,
funResultAndArgs, chaseDecl, findAndChaseDecl,
findAndChaseDeclOrTag, checkForAlias, checkForOneCUName,
checkForOneAliasName, lookupEnum, lookupStructUnion,
lookupDeclOrTag)
where
import Data.List (find)
import Control.Monad (liftM)
import Control.Exception (assert)
import Language.C.Data
import Language.C.Data.Ident (dumpIdent)
import Language.C.Syntax
import Data.Attributes
import Data.Errors
import C2HS.State (CST, readCST, transCST, runCST, raiseError, catchExc,
throwExc, Traces(..), putTraceStr)
import C2HS.C.Attrs (AttrC(..), enterNewRangeC, enterNewObjRangeC,
leaveRangeC, leaveObjRangeC, addDefObjC, lookupDefObjC,
lookupDefObjCShadow, addDefTagC, lookupDefTagC,
lookupDefTagCShadow, applyPrefix, getDefOfIdentC,
setDefOfIdentC, updDefOfIdentC, CObj(..), CTag(..),
CDef(..))
-- the C traversal monad
-- ---------------------
-- | C traversal monad
--
type CState s = (AttrC, s)
type CT s a = CST (CState s) a
-- | read attributed struture tree
--
readAttrCCT :: (AttrC -> a) -> CT s a
readAttrCCT reader = readCST $ \(ac, _) -> reader ac
-- | transform attributed structure tree
--
transAttrCCT :: (AttrC -> (AttrC, a)) -> CT s a
transAttrCCT trans = transCST $ \(ac, s) -> let
(ac', r) = trans ac
in
((ac', s), r)
-- | access to the user-defined state
--
-- | read user-defined state
--
readCT :: (s -> a) -> CT s a
readCT reader = readCST $ \(_, s) -> reader s
-- | transform user-defined state
--
transCT :: (s -> (s, a)) -> CT s a
transCT trans = transCST $ \(ac, s) -> let
(s', r) = trans s
in
((ac, s'), r)
-- usage of a traversal monad
--
-- | execute a traversal monad
--
-- * given a traversal monad, an attribute structure tree, and a user
-- state, the transformed structure tree and monads result are returned
--
runCT :: CT s a -> AttrC -> s -> CST t (AttrC, a)
runCT m ac s = runCST m' (ac, s)
where
m' = do
r <- m
(ac', _) <- readCST id
return (ac', r)
-- exception handling
-- ------------------
-- | exception identifier
--
ctExc :: String
ctExc = "ctExc"
-- | throw an exception
--
throwCTExc :: CT s a
throwCTExc = throwExc ctExc "Error during traversal of a C structure tree"
-- | catch a `ctExc'
--
ifCTExc :: CT s a -> CT s a -> CT s a
ifCTExc m handler = m `catchExc` (ctExc, const handler)
-- | raise an error followed by throwing a CT exception
--
raiseErrorCTExc :: Position -> [String] -> CT s a
raiseErrorCTExc pos errs = raiseError pos errs >> throwCTExc
-- attribute manipulation
-- ----------------------
-- name spaces
--
-- | enter a new local range
--
enter :: CT s ()
enter = transAttrCCT $ \ac -> (enterNewRangeC ac, ())
-- | enter a new local range, only for objects
--
enterObjs :: CT s ()
enterObjs = transAttrCCT $ \ac -> (enterNewObjRangeC ac, ())
-- | leave the current local range
--
leave :: CT s ()
leave = transAttrCCT $ \ac -> (leaveRangeC ac, ())
-- | leave the current local range, only for objects
--
leaveObjs :: CT s ()
leaveObjs = transAttrCCT $ \ac -> (leaveObjRangeC ac, ())
-- | enter an object definition into the object name space
--
-- * if a definition of the same name was already present, it is returned
--
defObj :: Ident -> CObj -> CT s (Maybe CObj)
defObj ide obj = do
traceCTrav $ "Defining object "++show ide++"...\n"
transAttrCCT $ \ac -> addDefObjC ac ide obj
-- | find a definition in the object name space
--
findObj :: Ident -> CT s (Maybe CObj)
findObj ide = readAttrCCT $ \ac -> lookupDefObjC ac ide
-- | find a definition in the object name space; if nothing found, try
-- whether there is a shadow identifier that matches
--
findObjShadow :: Ident -> CT s (Maybe (CObj, Ident))
findObjShadow ide = readAttrCCT $ \ac -> lookupDefObjCShadow ac ide
-- | enter a tag definition into the tag name space
--
-- * empty definitions of structures get overwritten with complete ones and a
-- forward reference is added to their tag identifier; furthermore, both
-- structures and enums may be referenced using an empty definition when
-- there was a full definition earlier and in this case there is also an
-- object association added; otherwise, if a definition of the same name was
-- already present, it is returned (see DOCU section)
--
-- * it is checked that the first occurence of an enumeration tag is
-- accompanied by a full definition of the enumeration
--
defTag :: Ident -> CTag -> CT s (Maybe CTag)
defTag ide tag =
do
traceCTrav $ "Defining tag "++show ide++"...\n"
otag <- transAttrCCT $ \ac -> addDefTagC ac ide tag
case otag of
Nothing -> return Nothing -- no collision
Just prevTag -> case isRefinedOrUse prevTag tag of
Nothing -> return otag
Just (fullTag, foreIde) -> do
_ <- transAttrCCT $ \ac -> addDefTagC ac ide fullTag
foreIde `refersToDef` TagCD fullTag
return Nothing -- transparent for env
where
-- compute whether we have the case of a non-conflicting redefined tag
-- definition, and if so, return the full definition and the foreward
-- definition's tag identifier
--
-- * the first argument contains the _previous_ definition
--
-- * in the case of a structure, a foreward definition after a full
-- definition is allowed, so we have to handle this case; enumerations
-- don't allow foreward definitions
--
-- * there may also be multiple foreward definition; if we have two of
-- them here, one is arbitrarily selected to take the role of the full
-- definition
--
isRefinedOrUse (StructUnionCT (CStruct _ (Just ide') Nothing _ _))
tag'@(StructUnionCT (CStruct _ (Just _ ) _ _ _)) =
Just (tag', ide')
isRefinedOrUse tag'@(StructUnionCT (CStruct _ (Just _ ) _ _ _))
(StructUnionCT (CStruct _ (Just ide') Nothing _ _)) =
Just (tag', ide')
isRefinedOrUse (EnumCT (CEnum (Just ide') Nothing _ _))
tag'@(EnumCT (CEnum (Just _ ) _ _ _)) =
Just (tag', ide')
isRefinedOrUse tag'@(EnumCT (CEnum (Just ide') _ _ _))
(EnumCT (CEnum (Just _ ) _ _ _)) =
Just (tag', ide')
isRefinedOrUse _ _ = Nothing
-- | find an definition in the tag name space
--
findTag :: Ident -> CT s (Maybe CTag)
findTag ide = readAttrCCT $ \ac -> lookupDefTagC ac ide
-- | find an definition in the tag name space; if nothing found, try
-- whether there is a shadow identifier that matches
--
findTagShadow :: Ident -> CT s (Maybe (CTag, Ident))
findTagShadow ide = readAttrCCT $ \ac -> lookupDefTagCShadow ac ide
-- | enrich the object and tag name space with identifiers obtained by dropping
-- the given prefix from the identifiers already in the name space
--
-- * if a new identifier would collides with an existing one, the new one is
-- discarded, ie, all associations that existed before the transformation
-- started are still in effect after the transformation
--
applyPrefixToNameSpaces :: String -> String -> CT s ()
applyPrefixToNameSpaces prefix repprefix =
transAttrCCT $ \ac -> (applyPrefix ac prefix repprefix, ())
-- definition attribute
--
-- | get the definition of an identifier
--
-- * the attribute must be defined, ie, a definition must be associated with
-- the given identifier
--
getDefOf :: Ident -> CT s CDef
getDefOf ide = do
def <- readAttrCCT $ \ac -> getDefOfIdentC ac ide
assert (not . isUndef $ def) $
return def
-- | set the definition of an identifier
--
refersToDef :: Ident -> CDef -> CT s ()
refersToDef ide def =
do traceCTrav $ "linking identifier: "++ dumpIdent ide ++ " --> " ++ show def
transAttrCCT $ \akl -> (setDefOfIdentC akl ide def, ())
-- | update the definition of an identifier
--
refersToNewDef :: Ident -> CDef -> CT s ()
refersToNewDef ide def =
transAttrCCT $ \akl -> (updDefOfIdentC akl ide def, ())
-- | get the declarator of an identifier
--
getDeclOf :: Ident -> CT s CDecl
getDeclOf ide =
do
traceEnter
def <- getDefOf ide
case def of
UndefCD -> interr "CTrav.getDeclOf: Undefined!"
DontCareCD -> interr "CTrav.getDeclOf: Don't care!"
TagCD _ -> interr "CTrav.getDeclOf: Illegal tag!"
ObjCD obj -> case obj of
TypeCO decl -> traceTypeCO decl >>
return decl
ObjCO decl -> traceObjCO decl >>
return decl
EnumCO _ _ -> illegalEnum
BuiltinCO Nothing -> illegalBuiltin
BuiltinCO (Just decl) -> traceBuiltinCO >>
return decl
where
illegalEnum = interr "CTrav.getDeclOf: Illegal enum!"
illegalBuiltin = interr "CTrav.getDeclOf: Attempted to get declarator of \
\builtin entity!"
-- if the latter ever becomes necessary, we have to
-- change the representation of builtins and give them
-- some dummy declarator
traceEnter = traceCTrav
$ "Entering `getDeclOf' for `" ++ identToString ide
++ "'...\n"
traceTypeCO decl = traceCTrav
$ "...found a type object:\n" ++ show decl ++ "\n"
traceObjCO decl = traceCTrav
$ "...found a vanilla object:\n" ++ show decl ++ "\n"
traceBuiltinCO = traceCTrav
$ "...found a builtin object with a proxy decl.\n"
-- convenience functions
--
findTypeObjMaybeWith :: Bool -> Ident -> Bool -> CT s (Maybe (CObj, Ident))
findTypeObjMaybeWith soft ide useShadows =
do
oobj <- if useShadows
then findObjShadow ide
else liftM (fmap (\obj -> (obj, ide))) $ findObj ide
case oobj of
Just obj@(TypeCO _ , _) -> return $ Just obj
Just obj@(BuiltinCO _, _) -> return $ Just obj
Just _ -> if soft
then return Nothing
else typedefExpectedErr ide
Nothing -> return $ Nothing
-- | find a type object in the object name space; returns 'Nothing' if the
-- identifier is not defined
--
-- * if the second argument is 'True', use 'findObjShadow'
--
findTypeObjMaybe :: Ident -> Bool -> CT s (Maybe (CObj, Ident))
findTypeObjMaybe = findTypeObjMaybeWith False
-- | find a type object in the object name space; raises an error and exception
-- if the identifier is not defined
--
-- * if the second argument is 'True', use 'findObjShadow'
--
findTypeObj :: Ident -> Bool -> CT s (CObj, Ident)
findTypeObj ide useShadows = do
oobj <- findTypeObjMaybe ide useShadows
case oobj of
Nothing -> unknownObjErr ide
Just obj -> return obj
-- | find an object, function, or enumerator in the object name space; raises an
-- error and exception if the identifier is not defined
--
-- * if the second argument is 'True', use 'findObjShadow'
--
findValueObj :: Ident -> Bool -> CT s (CObj, Ident)
findValueObj ide useShadows =
do
oobj <- if useShadows
then findObjShadow ide
else liftM (fmap (\obj -> (obj, ide))) $ findObj ide
case oobj of
Just obj@(ObjCO _ , _) -> return obj
Just obj@(EnumCO _ _, _) -> return obj
Just _ -> unexpectedTypedefErr (posOf ide)
Nothing -> unknownObjErr ide
-- | find a function in the object name space; raises an error and exception if
-- the identifier is not defined
--
-- * if the second argument is 'True', use 'findObjShadow'
--
findFunObj :: Ident -> Bool -> CT s (CObj, Ident)
findFunObj ide useShadows =
do
(obj, ide') <- findValueObj ide useShadows
case obj of
EnumCO _ _ -> funExpectedErr (posOf ide)
ObjCO decl -> do
let declr = ide' `declrFromDecl` decl
assertFunDeclr (posOf ide) declr
return (obj, ide')
-- C structure tree query routines
-- -------------------------------
-- | test if this is a type definition specification
--
isTypedef :: CDecl -> Bool
isTypedef (CDecl specs _ _) =
not . null $ [() | CStorageSpec (CTypedef _) <- specs]
-- | discard all declarators but the one declaring the given identifier
--
-- * the declaration must contain the identifier
--
simplifyDecl :: Ident -> CDecl -> CDecl
ide `simplifyDecl` (CDecl specs declrs at) =
case find (`declrPlusNamed` ide) declrs of
Nothing -> err
Just declr -> CDecl specs [declr] at
where
(Just declr, _, _) `declrPlusNamed` ide' = declr `declrNamed` ide'
_ `declrPlusNamed` _ = False
--
err = interr $ "CTrav.simplifyDecl: Wrong C object!\n\
\ Looking for `" ++ identToString ide ++ "' in decl \
\at " ++ show (posOf at)
-- | extract the declarator that declares the given identifier
--
-- * the declaration must contain the identifier
--
declrFromDecl :: Ident -> CDecl -> CDeclr
ide `declrFromDecl` decl =
let CDecl _ [(Just declr, _, _)] _ = ide `simplifyDecl` decl
in
declr
-- | tests whether the given declarator has the given name
--
declrNamed :: CDeclr -> Ident -> Bool
declr `declrNamed` ide = declrName declr == Just ide
-- | get the declarator of a declaration that has at most one declarator
--
declaredDeclr :: CDecl -> Maybe CDeclr
declaredDeclr (CDecl _ [] _) = Nothing
declaredDeclr (CDecl _ [(odeclr, _, _)] _) = odeclr
declaredDeclr decl =
interr $ "CTrav.declaredDeclr: Too many declarators!\n\
\ Declaration at " ++ show (posOf decl)
-- | get the initialiser of a declaration that has at most one initialiser
--
initDeclr :: CDecl -> Maybe (CInitializer NodeInfo)
initDeclr (CDecl _ [] _) = Nothing
initDeclr (CDecl _ [(_, ini, _)] _) = ini
initDeclr decl =
interr $ "CTrav.initDeclr: Too many declarators!\n\
\ Declaration at " ++ show (posOf decl)
-- | get the name declared by a declaration that has exactly one declarator
--
declaredName :: CDecl -> Maybe Ident
declaredName decl = declaredDeclr decl >>= declrName
-- | obtains the member definitions and the tag of a struct
--
-- * member definitions are expanded
--
structMembers :: CStructUnion -> ([CDecl], CStructTag)
structMembers (CStruct tag _ members _ _) = (concat . map expandDecl $ maybe [] id members, tag)
-- | expand declarators declaring more than one identifier into multiple
-- declarators, eg, `int x, y;' becomes `int x; int y;'
--
expandDecl :: CDecl -> [CDecl]
expandDecl (CDecl specs decls at) =
map (\decl -> CDecl specs [decl] at) decls
-- | get a struct's name
--
structName :: CStructUnion -> Maybe Ident
structName (CStruct _ oide _ _ _) = oide
-- | get an enum's name
--
enumName :: CEnum -> Maybe Ident
enumName (CEnum oide _ _ _) = oide
-- | get a tag's name
--
-- * fail if the tag is anonymous
--
tagName :: CTag -> Ident
tagName tag =
case tag of
StructUnionCT struct -> maybe err id $ structName struct
EnumCT enum -> maybe err id $ enumName enum
where
err = interr "CTrav.tagName: Anonymous tag definition"
-- | checks whether the given declarator defines an object that is a pointer to
-- some other type
--
-- * as far as parameter passing is concerned, arrays are also pointer
--
isPtrDeclr :: CDeclr -> Bool
isPtrDeclr (CDeclr _ (CPtrDeclr _ _:_) _ _ _) = True
isPtrDeclr (CDeclr _ (CArrDeclr _ _ _:_) _ _ _) = True
isPtrDeclr _ = False
-- | Need to distinguish between pointer and array declarations within
-- structures.
--
isArrDeclr :: CDeclr -> Maybe Int
isArrDeclr (CDeclr _ (CArrDeclr _ sz _:_) _ _ _) = Just $ szToInt sz
where szToInt (CArrSize _ (CConst (CIntConst s _))) =
fromIntegral $ getCInteger s
szToInt _ = 1
isArrDeclr _ = Nothing
-- | drops the first pointer level from the given declarator
--
-- * the declarator must declare a pointer object
--
-- * arrays are considered to be pointers
--
-- FIXME: this implementation isn't nice, because we retain the 'CVarDeclr'
-- unchanged; as the declarator is changed, we should maybe make this
-- into an anonymous declarator and also change its attributes
--
dropPtrDeclr :: CDeclr -> CDeclr
dropPtrDeclr (CDeclr ide (outermost:derived) asm ats node) =
case outermost of
(CPtrDeclr _ _) -> CDeclr ide derived asm ats node
(CArrDeclr _ _ _) -> CDeclr ide derived asm ats node
_ -> interr "CTrav.dropPtrDeclr: No pointer!"
-- | checks whether the given declaration defines a pointer object
--
-- * there may only be a single declarator in the declaration
--
isPtrDecl :: CDecl -> Bool
isPtrDecl (CDecl _ [] _) = False
isPtrDecl (CDecl _ [(Just declr, _, _)] _) = isPtrDeclr declr
isPtrDecl _ =
interr "CTrav.isPtrDecl: There was more than one declarator!"
isArrDecl :: CDecl -> Maybe Int
isArrDecl (CDecl _ [] _) = Nothing
isArrDecl (CDecl _ [(Just declr, _, _)] _) = isArrDeclr declr
isArrDecl _ =
interr "CTrav.isArrDecl: There was more than one declarator!"
-- | checks whether the given declarator defines a function object
--
isFunDeclr :: CDeclr -> Bool
isFunDeclr (CDeclr _ (CFunDeclr _ _ _:_) _ _ _) = True
isFunDeclr _ = False
-- | extract the structure from the type specifiers of a declaration
--
structFromDecl :: Position -> CDecl -> CT s CStructUnion
structFromDecl pos (CDecl specs _ _) =
case head [ts | CTypeSpec ts <- specs] of
CSUType su _ -> extractStruct pos (StructUnionCT su)
_ -> structExpectedErr pos
structFromDecl' :: Position -> CDecl -> CT s (Maybe CStructUnion)
structFromDecl' pos (CDecl specs _ _) =
case head [ts | CTypeSpec ts <- specs] of
CSUType su _ -> extractStruct' pos (StructUnionCT su)
_ -> structExpectedErr pos
-- | extracts the arguments from a function declaration (must be a unique
-- declarator) and constructs a declaration for the result of the function
--
-- * the boolean result indicates whether the function is variadic
--
-- * returns an abstract declarator
funResultAndArgs :: CDecl -> ([CDecl], CDecl, Bool)
funResultAndArgs cdecl@(CDecl specs [(Just declr, _, _)] _) =
let (args, declr', variadic) = funArgs declr
result = CDecl specs [(Just declr', Nothing, Nothing)]
(newAttrsOnlyPos (posOf cdecl))
in
(args, result, variadic)
where
funArgs (CDeclr _ide derived _asm _ats node) =
case derived of
(CFunDeclr (Right (args,variadic)) _ats' _dnode : derived') ->
(args, CDeclr Nothing derived' Nothing [] node, variadic)
(CFunDeclr (Left _) _ _ : _) ->
interr "CTrav.funResultAndArgs: Old style function definition"
_ -> interr "CTrav.funResultAndArgs: Illegal declarator!"
-- name chasing
--
-- | find the declarator identified by the given identifier; if the declarator
-- is itself only a 'typedef'ed name, the operation recursively searches for
-- the declarator associated with that name (this is called ``typedef
-- chasing'')
--
-- * if `ind = True', we have to hop over one indirection
--
-- * remove all declarators except the one we just looked up
--
chaseDecl :: Ident -> Bool -> CT s CDecl
--
-- * cycles are no issue, as they cannot occur in a correct C header (we would
-- have spotted the problem during name analysis)
--
chaseDecl ide ind =
do
traceEnter
cdecl <- getDeclOf ide
let sdecl = ide `simplifyDecl` cdecl
case extractAlias sdecl ind of
Just (ide', ind') -> chaseDecl ide' ind'
Nothing -> return sdecl
where
traceEnter = traceCTrav $
"Entering `chaseDecl' for `" ++ identToString ide
++ "' " ++ (if ind then "" else "not ")
++ "following indirections...\n"
-- | find type object in object name space and then chase it
--
-- * see also 'chaseDecl'
--
-- * also create an object association from the given identifier to the object
-- that it _directly_ represents
--
-- * if the third argument is 'True', use 'findObjShadow'
--
findAndChaseDecl :: Ident -> Bool -> Bool -> CT s CDecl
findAndChaseDecl ide ind useShadows =
do
traceCTrav $ "findAndChaseDecl: " ++ show ide ++ " (" ++
show useShadows ++ ")\n"
(obj, ide') <- findTypeObj ide useShadows -- is there an object def?
ide `refersToNewDef` ObjCD obj
ide' `refersToNewDef` ObjCD obj -- assoc needed for chasing
chaseDecl ide' ind
findAndChaseDeclOrTag :: Ident -> Bool -> Bool -> CT s CDecl
findAndChaseDeclOrTag ide ind useShadows =
do
traceCTrav $ "findAndChaseDeclOrTag: " ++ show ide ++ " (" ++
show useShadows ++ ")\n"
mobjide <- findTypeObjMaybeWith True ide useShadows -- is there an object def?
case mobjide of
Just (obj, ide') -> do
ide `refersToNewDef` ObjCD obj
ide' `refersToNewDef` ObjCD obj -- assoc needed for chasing
chaseDecl ide' ind
Nothing -> do
otag <- if useShadows
then findTagShadow ide
else liftM (fmap (\tag -> (tag, ide))) $ findTag ide
case otag of
Just (StructUnionCT su, _) -> do
let (CStruct _ _ _ _ nodeinfo) = su
return $ CDecl [CTypeSpec (CSUType su nodeinfo)] [] nodeinfo
_ -> unknownObjErr ide
-- | given a declaration (which must have exactly one declarator), if the
-- declarator is an alias, chase it to the actual declaration
--
checkForAlias :: CDecl -> CT s (Maybe CDecl)
checkForAlias decl =
case extractAlias decl False of
Nothing -> return Nothing
Just (ide', _) -> liftM Just $ chaseDecl ide' False
-- | given a declaration (which must have exactly one declarator), if the
-- declarator is an alias, yield the alias name; *no* chasing
--
checkForOneAliasName :: CDecl -> Maybe Ident
checkForOneAliasName decl = fmap fst $ extractAlias decl False
-- | given a declaration, find the name of the struct/union type
checkForOneCUName :: CDecl -> Maybe Ident
checkForOneCUName decl@(CDecl specs _ _) =
case [ts | CTypeSpec ts <- specs] of
[CSUType (CStruct _ n _ _ _) _] ->
case declaredDeclr decl of
Nothing -> n
Just (CDeclr _ [] _ _ _) -> n -- no type derivations
_ -> Nothing
_ -> Nothing
-- smart lookup
--
-- | for the given identifier, either find an enumeration in the tag name space
-- or a type definition referring to an enumeration in the object name space;
-- raises an error and exception if the identifier is not defined
--
-- * if the second argument is 'True', use 'findTagShadow'
--
lookupEnum :: Ident -> Bool -> CT s CEnum
lookupEnum ide useShadows =
do
otag <- if useShadows
then liftM (fmap fst) $ findTagShadow ide
else findTag ide
case otag of
Just (StructUnionCT _ ) -> enumExpectedErr ide -- wrong tag definition
Just (EnumCT enum) -> return enum -- enum tag definition
Nothing -> do -- no tag definition
oobj <- if useShadows
then liftM (fmap fst) $ findObjShadow ide
else findObj ide
case oobj of
Just (EnumCO _ enum) -> return enum -- anonymous enum
_ -> do -- no value definition
(CDecl specs _ _) <- findAndChaseDecl ide False useShadows
case head [ts | CTypeSpec ts <- specs] of
CEnumType enum _ -> return enum
_ -> enumExpectedErr ide
-- | for the given identifier, either find a struct/union in the tag name space
-- or a type definition referring to a struct/union in the object name space;
-- raises an error and exception if the identifier is not defined
--
-- * the parameter `preferTag' determines whether tags or typedefs are
-- searched first
--
-- * if the third argument is `True', use `findTagShadow'
--
-- * when finding a forward definition of a tag, follow it to the real
-- definition
--
lookupStructUnion :: Ident -> Bool -> Bool -> CT s CStructUnion
lookupStructUnion ide preferTag useShadows = do
traceCTrav $ "lookupStructUnion: ide=" ++ show ide ++ " preferTag=" ++
show preferTag ++ " useShadows=" ++ show useShadows ++ "\n"
otag <- if useShadows
then liftM (fmap fst) $ findTagShadow ide
else findTag ide
mobj <- if useShadows
then findObjShadow ide
else liftM (fmap (\obj -> (obj, ide))) $ findObj ide
let oobj = case mobj of
Just obj@(TypeCO{}, _) -> Just obj
Just obj@(BuiltinCO{}, _) -> Just obj
_ -> Nothing
case preferTag of
True -> case otag of
Just tag -> extractStruct (posOf ide) tag
Nothing -> do
decl <- findAndChaseDecl ide True useShadows
structFromDecl (posOf ide) decl
False -> case oobj of
Just _ -> do
decl <- findAndChaseDecl ide True useShadows
mres <- structFromDecl' (posOf ide) decl
case mres of
Just su -> return su
Nothing -> case otag of
Just tag -> extractStruct (posOf ide) tag
Nothing -> unknownObjErr ide
Nothing -> case otag of
Just tag -> extractStruct (posOf ide) tag
Nothing -> unknownObjErr ide
-- | for the given identifier, check for the existance of both a type definition
-- or a struct, union, or enum definition
--
-- * if a typedef and a tag exists, the typedef takes precedence
--
-- * typedefs are chased
--
-- * if the second argument is `True', look for shadows, too
--
lookupDeclOrTag :: Ident -> Bool -> CT s (Either CDecl CTag)
lookupDeclOrTag ide useShadows = do
oobj <- findTypeObjMaybeWith True ide useShadows
case oobj of
Just (_, ide') -> liftM Left $ findAndChaseDecl ide' False False
-- already did check shadows
Nothing -> do
otag <- if useShadows
then liftM (fmap fst) $ findTagShadow ide
else findTag ide
case otag of
Nothing -> unknownObjErr ide
Just tag -> return $ Right tag
-- auxiliary routines (internal)
--
-- | if the given declaration (which may have at most one declarator) is a
-- `typedef' alias, yield the referenced name
--
-- * a `typedef' alias has one of the following forms
--
-- <specs> at x, ...;
-- <specs> at *x, ...;
--
-- where `at' is the alias type, which has been defined by a `typedef', and
-- <specs> are arbitrary specifiers and qualifiers. Note that `x' may be a
-- variable, a type name (if `typedef' is in <specs>), or be entirely
-- omitted.
--
-- * if `ind = True', the alias may be via an indirection
--
-- * if `ind = True' and the alias is _not_ over an indirection, yield `True';
-- otherwise `False' (ie, the ability to hop over an indirection is consumed)
--
-- * this may be an anonymous declaration, ie, the name in `CVarDeclr' may be
-- omitted or there may be no declarator at all
--
extractAlias :: CDecl -> Bool -> Maybe (Ident, Bool)
extractAlias decl@(CDecl specs _ _) ind =
case [ts | CTypeSpec ts <- specs] of
[CTypeDef ide' _] -> -- type spec is aliased ident
case declaredDeclr decl of
Nothing -> Just (ide', ind)
Just (CDeclr _ [] _ _ _) -> Just (ide', ind) -- no type derivations
Just (CDeclr _ [CPtrDeclr _ _] _ _ _) -- one pointer indirection
| ind -> Just (ide', False)
| otherwise -> Nothing
_ -> Nothing
_ -> Nothing
-- | if the given tag is a forward declaration of a structure, follow the
-- reference to the full declaration
--
-- * the recursive call is not dangerous as there can't be any cycles
--
extractStruct :: Position -> CTag -> CT s CStructUnion
extractStruct pos (EnumCT _ ) = structExpectedErr pos
extractStruct pos (StructUnionCT su) = do
traceCTrav $ "extractStruct: " ++ show su ++ "\n"
case su of
CStruct _ (Just ide') Nothing _ _ -> do -- found forward definition
def <- getDefOf ide'
traceCTrav $ "def=" ++ show def ++ "\n"
case def of
TagCD tag -> extractStruct pos tag
bad_obj -> err ide' bad_obj
_ -> return su
where
err ide bad_obj =
do interr $ "CTrav.extractStruct: Illegal reference! Expected " ++ dumpIdent ide ++
" to link to TagCD but refers to "++ (show bad_obj) ++ "\n"
extractStruct' :: Position -> CTag -> CT s (Maybe CStructUnion)
extractStruct' pos (EnumCT _ ) = structExpectedErr pos
extractStruct' pos (StructUnionCT su) = do
traceCTrav $ "extractStruct': " ++ show su ++ "\n"
case su of
CStruct _ (Just ide') Nothing _ _ -> do
def <- getDefOf ide'
traceCTrav $ "def=" ++ show def ++ "\n"
case def of
TagCD tag -> do
res <- extractStruct pos tag
return . Just $ res
_ -> return Nothing
_ -> return . Just $ su
-- | yield the name declared by a declarator if any
--
declrName :: CDeclr -> Maybe Ident
declrName (CDeclr oide _ _ _ _) = oide
-- | raise an error if the given declarator does not declare a C function or if
-- the function is supposed to return an array (the latter is illegal in C)
--
assertFunDeclr :: Position -> CDeclr -> CT s ()
assertFunDeclr pos (CDeclr _ (CFunDeclr _ _ _:retderiv) _ _ _) =
case retderiv of
(CArrDeclr _ _ _:_) -> illegalFunResultErr pos
_ -> return () -- ok, we have a function which doesn't return an array
assertFunDeclr pos _ =
funExpectedErr pos
-- | trace for this module
--
traceCTrav :: String -> CT s ()
traceCTrav = putTraceStr traceCTravSW
-- error messages
-- --------------
unknownObjErr :: Ident -> CT s a
unknownObjErr ide =
raiseErrorCTExc (posOf ide)
["Unknown identifier!",
"Cannot find a definition for `" ++ identToString ide ++ "' in the \
\header file."]
typedefExpectedErr :: Ident -> CT s a
typedefExpectedErr ide =
raiseErrorCTExc (posOf ide)
["Expected type definition!",
"The identifier `" ++ identToString ide ++ "' needs to be a C type name."]
unexpectedTypedefErr :: Position -> CT s a
unexpectedTypedefErr pos =
raiseErrorCTExc pos
["Unexpected type name!",
"An object, function, or enum constant is required here."]
illegalFunResultErr :: Position -> CT s a
illegalFunResultErr pos =
raiseErrorCTExc pos ["Function cannot return an array!",
"ANSI C does not allow functions to return an array."]
funExpectedErr :: Position -> CT s a
funExpectedErr pos =
raiseErrorCTExc pos
["Function expected!",
"A function is needed here, but this declarator does not declare",
"a function."]
enumExpectedErr :: Ident -> CT s a
enumExpectedErr ide =
raiseErrorCTExc (posOf ide)
["Expected enum!",
"Expected `" ++ identToString ide ++ "' to denote an enum; instead found",
"a struct, union, or object."]
structExpectedErr :: Position -> CT s a
structExpectedErr pos =
raiseErrorCTExc pos
["Expected a struct!",
"Expected a structure or union; instead found an enum or basic type."]
|
ian-ross/c2hs-macos-test
|
c2hs-0.26.1/src/C2HS/C/Trav.hs
|
mit
| 36,572 | 0 | 23 | 11,102 | 7,623 | 4,031 | 3,592 | 501 | 11 |
module MyRandom where
import System.Random
import Test.QuickCheck
type MyRandom a = StdGen -> (a,StdGen)
-- Standard Random Number Generator seeded with 0
zeroSeed :: StdGen
zeroSeed = mkStdGen 0
-- System.Random.random is of type MyRandom a
-- - if a implements the Random type class
-- For example, try
-- :t random::MyRandom Int
-- Random value in interval [0,n]
uniformNat :: Int -> MyRandom Int
uniformNat n = uint
where
uint gen = let (m,gen') = random gen
in (m `mod` n, gen')
-- fst $ uniformNat 100 zeroSeed == 41
-- Exercise Seven: implement bind
bind :: (a -> MyRandom b) -> (MyRandom a -> MyRandom b)
bind = undefined
-- Using # instead of * for composition to avoid ambiguities
(#) :: (b -> MyRandom c) -> (a -> MyRandom b) -> (a -> MyRandom c)
g' # f' = bind g' . f'
-- random of random :-)
doubleRandom :: Int -> MyRandom Int
doubleRandom = uniformNat # uniformNat
-- Exercise Eight: implement unit -- leave the generator unodified
unit :: a -> MyRandom a
unit = undefined
-- lift --- lifting functions
lift :: (a -> b) -> (a -> MyRandom b)
lift f = unit . f
-- Random value in a given interval
-- - uniformFromTo m n = m + uniformNat (n-m)
uniformFromTo :: Int -> Int -> MyRandom Int
uniformFromTo m n = lift (m+) # uniformNat $ (n-m)
-- Exercise Nine: Test that (for a given value x)
-- (a) f # unit = unit # f = f
-- (b) lift g # lift f = lift (g.f)
check_unit1, check_unit2 :: (Int -> MyRandom Int) -> Int -> Bool
check_unit1 f x = undefined
check_unit2 f x = undefined
test_unit1, test_unit2 :: IO ()
test_unit1 = quickCheck $ check_unit1 uniformNat
test_unit2 = quickCheck $ check_unit2 uniformNat
check_lift :: (Int -> Int) -> (Int -> Int) -> Int -> Bool
check_lift f g x = undefined
test_lift :: IO ()
test_lift = quickCheck $ check_lift (+2) (*3)
-- Exercise Ten(c): Rewrite the module to make MyRandom instance of
-- the Monad typeclass
-- Note: You first need to make it an instance of Functor and Applicative
-- Exercise Eleven(c): Write the uniformFromTo function in do notation
-- Questions:
-- * Do you really need the full power of the monad?
-- * Could you have solved the problem using just the Functor or Applicative capabilities?
|
PavelClaudiuStefan/FMI
|
An_3_Semestru_1/ProgramareDeclarativa/Extra/Laborator/Laborator 9/MyRandom.hs
|
cc0-1.0
| 2,229 | 0 | 11 | 468 | 511 | 284 | 227 | 32 | 1 |
module Render (
renderObjects,
renderGun,
renderHud,
GameData(..)
) where
import MD3
import Object
import Graphics.Rendering.OpenGL
import Data.IORef
import Data.Maybe
import Camera
import Matrix
import Frustum
import BSP
import Data.HashTable.IO as H
import Visibility
import TextureFonts
import Control.Monad
data GameData = GameData {
gamemap :: IORef BSPMap,
models :: BasicHashTable String Model,
textures :: BasicHashTable String (Maybe TextureObject),
camera :: IORef Camera,
lastDrawTime :: IORef Int,
lastDrawTime2 :: IORef Int,
hasReacted :: IORef Bool,
fonts :: (Maybe TextureObject,DisplayList),
nbase :: DisplayList,
lock :: IORef Bool,
fpsc :: IORef (Double,Double),
fpss :: IORef (Double,Double,Double),
nems :: !Int
}
-- renders the playerstate, gun and crosshairs
renderHud :: GameData -> ObsObjState -> Int -> Int -> IO()
renderHud gd playerState noos tme =
setUpOrtho $ do
--show the framerate
lastTime3 <- readIORef (lastDrawTime2 gd)
let dt = realToFrac(tme - lastTime3)/1000
color $ Color4 255 255 255 (255 :: GLubyte)
printFonts' 0 464 (fonts gd) 1 $
"framerate = " ++ show (truncate ((1/dt) :: Double) :: Int)
--print the player's score
printFonts' 0 448 (fonts gd) 1
("ezpks = " ++show (score playerState))
--print the position of the player
let (q,w,e) = cpos (oldCam playerState)
printFonts' 0 432 (fonts gd) 1
("position = " ++show (truncate q :: Int,truncate w :: Int,truncate e :: Int))
--print the number of objects
printFonts' 0 416 (fonts gd) 1 ("No. of objs = " ++show noos)
--print a message if the player has eliminated all enemies
color $ Color4 0 255 0 (255 :: GLubyte)
Control.Monad.when (score playerState == nems gd && nems gd > 0) (
printFonts' 96 272 (fonts gd) 1 "You've killed everybody! (You monster.)")
--print a message if the player has died
Control.Monad.when (health playerState <= 0) (do
color $ Color4 255 0 0 (255 :: GLubyte)
printFonts' 210 240 (fonts gd) 1 "Oh, botheration. You died."
color $ Color4 255 255 255 (255 :: GLubyte))
--render the health and score of the player with big fonts
color $ Color4 255 255 255 (255 :: GLubyte)
printFonts' 4 50 (fonts gd) 1 "health"
printFonts' 540 50 (fonts gd) 1 "score"
color $ Color4 232 192 0 (255 :: GLubyte)
if health playerState > 0 then renderNum 4 1 (nbase gd) (truncate(health playerState)) else renderNum 4 1 (nbase gd) 0
color $ Color4 232 192 0 (255 :: GLubyte)
renderNum 540 1 (nbase gd) (score playerState)
--render a smiley at the middle of the screen
unsafePreservingMatrix $ do
scale 20 10 (20 :: GLfloat)
color $ Color4 255 255 255 (255 :: GLubyte)
printLife (fonts gd) (truncate(health playerState))
color $ Color4 255 255 255 (255 :: GLubyte)
--render the crosshair
renderCrosshair (textures gd)
depthFunc $= Just Less
--print a smiley representing the health of the player
printLife :: (Maybe TextureObject,DisplayList) -> Int -> IO()
printLife font life
| life <= 0 = printf "(x_x)"
| life <= 19 = printf "(T_T)"
| life <= 19 = printf "(~_~)"
| life <= 39 = printf "(-_-)"
| life <= 59 = printf "(o_0)"
| life <= 79 = printf "(o_o)"
| otherwise = printf "(^_^)"
where printf = printFonts' 292 32 font 1
renderObjects :: IORef Camera -> BasicHashTable String Model ->
Frustum -> BSPMap -> ObsObjState -> IO()
renderObjects camRef mdels frust mp oos
| isRay oos = renderRay oos
| isProjectile oos = renderProjectile oos
| isAICube oos = renderEnemy camRef mdels frust mp oos
| otherwise = return ()
renderGun :: Camera -> BasicHashTable String Model -> IO()
renderGun cam mdels = do
Just weapon <- H.lookup mdels "railgun"
let (x,y,z) = cpos cam
let (vx,vy,vz) = viewPos cam
unsafePreservingMatrix $ do
--clear the depth buffer so the gun will appear
--on top of the graphics in the scene
clear [DepthBuffer ]
--translate and rotate the gun so it is aligned with players view vector
translate (Vector3 x (y+30) (z :: Double))
let angle2 =
acos $ dotProd (normalise $ vectorSub (vx,0,vz) (x,0,z)) (1,0,0)
if vz > z then rotate ((360 - (angle2*180/pi)) :: GLdouble) (Vector3 0 1 0) else rotate ((angle2*180/pi) :: GLdouble) (Vector3 0 1 0)
let angle1 =
acos $ dotProd (normalise $ vectorSub (vx,vy,vz) (x,y,z)) (0,1,0)
rotate (90-(angle1*180/pi) :: GLdouble) (Vector3 0 0 1)
rotate (-90 :: Double) (Vector3 1 0 0)
translate (Vector3 4.8 (-9.5) ((-20) :: Double))
scale 2 2 (2 :: GLfloat)
--setup the animation state and drw the model
writeIORef (auxFunc2 (modelRef weapon)) Nothing
drawModel (modelRef weapon,lowerState weapon)
depthFunc $= Just Always
renderRay :: ObsObjState -> IO()
renderRay OOSRay {rayStart = (x1,y1,z1),
rayEnd = (x2,y2,z2),
clipped = cl} = do
cullFace $= Nothing
color $ Color4 255 0 0 (255 :: GLubyte)
depthFunc $= Just Always
unsafeRenderPrimitive Quads $ do
vertex (Vertex3 x2 (y2+0.3) z2)
vertex (Vertex3 x2 (y2-0.3) z2)
vertex (Vertex3 x1 (y1-0.3) z1)
vertex (Vertex3 x1 (y1+0.3) z1)
color $ Color4 255 255 255 (255 :: GLubyte)
unsafeRenderPrimitive Quads $ do
vertex (Vertex3 x2 (y2+0.12) z2)
vertex (Vertex3 x2 (y2-0.12) z2)
vertex (Vertex3 x1 (y1-0.12) z1)
vertex (Vertex3 x1 (y1+0.12) z1)
depthFunc $= Just Less
cullFace $= Just Front
when cl (do
cullFace $= Nothing
unsafePreservingMatrix $ do
translate (Vector3 x2 y2 z2)
renderQuadric
(QuadricStyle Nothing NoTextureCoordinates Outside FillStyle)
(Sphere 3 12 12)
cullFace $= Just Front)
color $ Color4 255 255 255 (255 :: GLubyte)
renderProjectile :: ObsObjState -> IO()
renderProjectile OOSProjectile {projectileOldPos = (x,y,z)} =
unsafePreservingMatrix $ do
translate (Vector3 x y z)
depthFunc $= Just Always
cullFace $= Nothing
color $ Color4 0 0 80 (255 :: GLubyte)
renderQuadric
(QuadricStyle Nothing NoTextureCoordinates Outside FillStyle)
(Sphere 4 12 12)
color $ Color4 50 50 160 (255 :: GLubyte)
renderQuadric
(QuadricStyle Nothing NoTextureCoordinates Outside FillStyle)
(Sphere 3.5 12 12)
color $ Color4 255 255 255 (255 :: GLubyte)
renderQuadric
(QuadricStyle Nothing NoTextureCoordinates Outside FillStyle)
(Sphere 2.5 12 12)
cullFace $= Just Front
depthFunc $= Just Less
renderEnemy ::
IORef Camera -> BasicHashTable String Model ->
Frustum -> BSPMap -> ObsObjState -> IO()
renderEnemy camRef mdels frust bspmap OOSAICube {oosOldCubePos = (x,y,z),
oosCubeSize = (sx,sy,sz),
oosCubeAngle = angle,
oosCubePitch = p,
upperAnim = ua,
fade = f,
lowerAnim = la,
modelName = name} = do
--perform a test to see if the object is visible from the player's location
cam <- readIORef camRef
clustVis <- isObjectVisible bspmap (cpos cam) (x,y,z)
when clustVis (do
-- a second check to see if the object is within the player's frustum
let frusTest = boxInFrustum frust
(vectorAdd (x,y,z) (-sx,-sy,-sz))
(vectorAdd (x,y,z) (sx,sy,sz))
Control.Monad.when frusTest (do
-- a third check to see if a ray can be fired to
--the objects position without colliding
let rayVis = rayTest bspmap (cpos cam) (x,y,z)
Control.Monad.when rayVis (
unsafePreservingMatrix $ do
lineWidth $= 5.0
translate (Vector3 x y z)
Just model <- H.lookup mdels name
writeIORef (pitch model)
(Just $ do
cullFace $= Nothing
cullFace $= Just Front
rotate p (Vector3 0 1 0))
writeIORef (lowerState model) la
writeIORef (upperState model) ua
currentColor $= Color4 (f*60) (f*60) (f*60) (1 :: Float)
unsafePreservingMatrix $ do
rotate ((-90) :: GLdouble) (Vector3 1 0 0)
rotate angle (Vector3 0 0 1)
translate (Vector3 (-10) 0 (-10 :: Double))
scale 1.5 1.5 (1.5 :: GLfloat)
drawModel (modelRef model,lowerState model)
currentColor $= Color4 1 1 1 (1 :: Float)
writeIORef (pitch model) Nothing)))
|
pushkinma/frag
|
src/Render.hs
|
gpl-2.0
| 10,435 | 0 | 27 | 4,169 | 3,131 | 1,569 | 1,562 | 195 | 2 |
--
-- Copyright (c) 2013 Bonelli Nicola <[email protected]>
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
--
{-# LANGUAGE FlexibleInstances #-}
module CGrep.Semantic.Generic.Token (tokenizer, Token(..)) where
import qualified Data.ByteString.Char8 as C
import qualified Data.DList as DL
import Data.Char
import Data.Array.Unboxed
import CGrep.Semantic.Token
import CGrep.Types
type DString = DL.DList Char
data TokenState =
StateSpace |
StateAlpha |
StateDigit |
StateBracket |
StateLit1 |
StateLit2 |
StateOther
deriving (Eq, Enum, Show)
data Token =
TokenAlpha { toString :: String, toOffset :: Offset } |
TokenDigit { toString :: String, toOffset :: Offset } |
TokenBracket { toString :: String, toOffset :: Offset } |
TokenLiteral { toString :: String, toOffset :: Offset } |
TokenOther { toString :: String, toOffset :: Offset }
deriving (Show, Eq, Ord)
instance SemanticToken Token where
tkIsIdentifier = _isTokenAlpha
tkIsString = _isTokenLiteral
tkIsChar = _isTokenLiteral
tkIsNumber = _isTokenDigit
tkIsKeyword = const False
tkEquivalent = tokenCompare
tkToString = toString
tkToOffset = toOffset
tkToIdentif = TokenAlpha
_isTokenAlpha, _isTokenDigit, _isTokenBracket, _isTokenOther, _isTokenLiteral :: Token -> Bool
_isTokenAlpha (TokenAlpha _ _) = True
_isTokenAlpha _ = False
_isTokenDigit (TokenDigit _ _) = True
_isTokenDigit _ = False
_isTokenBracket (TokenBracket _ _) = True
_isTokenBracket _ = False
_isTokenLiteral (TokenLiteral _ _) = True
_isTokenLiteral _ = False
_isTokenOther (TokenOther _ _) = True
_isTokenOther _ = False
tokenCompare :: Token -> Token -> Bool
tokenCompare (TokenAlpha { toString = l }) (TokenAlpha { toString = r }) = l == r
tokenCompare (TokenDigit { toString = l }) (TokenDigit { toString = r }) = l == r
tokenCompare (TokenLiteral { toString = l }) (TokenLiteral { toString = r }) = l == r
tokenCompare (TokenBracket { toString = l }) (TokenBracket { toString = r }) = l == r
tokenCompare (TokenOther { toString = l }) (TokenOther { toString = r }) = l == r
tokenCompare _ _ = False
data TokenAccum = TokenAccum !TokenState !Offset !Int DString (DL.DList Token)
isCharNumberLT :: UArray Char Bool
isCharNumberLT =
listArray ('\0', '\255')
(map (\c -> isHexDigit c || c `elem` ".xX") ['\0'..'\255'])
isSpaceLT :: UArray Char Bool
isSpaceLT =
listArray ('\0', '\255')
(map isSpace ['\0'..'\255'])
isAlphaLT :: UArray Char Bool
isAlphaLT =
listArray ('\0', '\255')
(map (\c -> isAlpha c || c == '_') ['\0'..'\255'])
isAlphaNumLT :: UArray Char Bool
isAlphaNumLT =
listArray ('\0', '\255')
(map (\c -> isAlphaNum c || c == '_' || c == '\'') ['\0'..'\255'])
isDigitLT :: UArray Char Bool
isDigitLT =
listArray ('\0', '\255')
(map isDigit ['\0'..'\255'])
isBracketLT :: UArray Char Bool
isBracketLT =
listArray ('\0', '\255')
(map (`elem` "{[()]}") ['\0'..'\255'])
{-# INLINE mkToken #-}
mkToken :: (String -> Offset -> Token) -> Offset -> DString -> Token
mkToken ctor off ds = ctor str (off - length str)
where str = DL.toList ds
mkTokenCtor :: TokenState -> String -> Offset -> Token
mkTokenCtor StateSpace = TokenOther
mkTokenCtor StateAlpha = TokenAlpha
mkTokenCtor StateDigit = TokenDigit
mkTokenCtor StateBracket = TokenBracket
mkTokenCtor StateLit1 = TokenLiteral
mkTokenCtor StateLit2 = TokenLiteral
mkTokenCtor StateOther = TokenOther
tokenizer :: Text8 -> [Token]
tokenizer xs = (\(TokenAccum ss off _ acc out) ->
DL.toList (if null (DL.toList acc) then out
else out `DL.snoc` mkToken (mkTokenCtor ss) off acc)) $ C.foldl' tokens' (TokenAccum StateSpace 0 0 DL.empty DL.empty) xs
where tokens' :: TokenAccum -> Char -> TokenAccum
tokens' (TokenAccum StateSpace off _ _ out) x =
case () of
_ | isSpaceLT ! x -> TokenAccum StateSpace (off+1) 0 DL.empty out
| x == '\'' -> TokenAccum StateLit1 (off+1) 0 (DL.singleton x) out
| x == '"' -> TokenAccum StateLit2 (off+1) 0 (DL.singleton x) out
| isAlphaLT ! x -> TokenAccum StateAlpha (off+1) 0 (DL.singleton x) out
| isDigitLT ! x -> TokenAccum StateDigit (off+1) 0 (DL.singleton x) out
| isBracketLT ! x -> TokenAccum StateBracket (off+1) 0 (DL.singleton x) out
| otherwise -> TokenAccum StateOther (off+1) 0 (DL.singleton x) out
tokens' (TokenAccum StateAlpha off _ acc out) x =
case () of
_ | isAlphaNumLT ! x -> TokenAccum StateAlpha (off+1) 0 (acc `DL.snoc` x) out
| isSpaceLT ! x -> TokenAccum StateSpace (off+1) 0 DL.empty (out `DL.snoc` mkToken TokenAlpha off acc)
| isBracketLT ! x -> TokenAccum StateBracket (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenAlpha off acc)
| otherwise -> TokenAccum StateOther (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenAlpha off acc)
tokens' (TokenAccum StateDigit off _ acc out) x =
case () of
_ | isCharNumberLT ! x -> TokenAccum StateDigit (off+1) 0 (acc `DL.snoc` x) out
| isSpaceLT ! x -> TokenAccum StateSpace (off+1) 0 DL.empty (out `DL.snoc` mkToken TokenDigit off acc)
| isAlphaLT ! x -> TokenAccum StateAlpha (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenDigit off acc)
| isBracketLT ! x -> TokenAccum StateBracket (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenDigit off acc)
| otherwise -> TokenAccum StateOther (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenDigit off acc)
tokens' (TokenAccum StateLit1 off skip acc out) x =
case () of
_ | skip > 0 -> TokenAccum StateLit1 (off+1) (skip-1) (acc `DL.snoc` x) out
| x == '\\' -> TokenAccum StateLit1 (off+1) 1 (acc `DL.snoc` x) out
| x == '\'' -> TokenAccum StateSpace (off+1) 0 DL.empty (out `DL.snoc` mkToken TokenLiteral (off+1) (acc `DL.snoc` '\''))
| otherwise -> TokenAccum StateLit1 (off+1) 0 (acc `DL.snoc` x) out
tokens' (TokenAccum StateLit2 off skip acc out) x =
case () of
_ | skip > 0 -> TokenAccum StateLit2 (off+1) (skip-1) (acc `DL.snoc` x) out
| x == '\\' -> TokenAccum StateLit2 (off+1) 1 (acc `DL.snoc` x) out
| x == '"' -> TokenAccum StateSpace (off+1) 0 DL.empty (out `DL.snoc` mkToken TokenLiteral (off+1) (acc `DL.snoc` '"'))
| otherwise -> TokenAccum StateLit2 (off+1) 0 (acc `DL.snoc` x) out
tokens' (TokenAccum StateBracket off _ acc out) x =
case () of
_ | isSpaceLT ! x -> TokenAccum StateSpace (off+1) 0 DL.empty (out `DL.snoc` mkToken TokenBracket off acc)
| isAlphaLT ! x -> TokenAccum StateAlpha (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenBracket off acc)
| isDigitLT ! x -> TokenAccum StateDigit (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenBracket off acc)
| isBracketLT ! x -> TokenAccum StateBracket (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenBracket off acc)
| x == '\'' -> TokenAccum StateLit1 (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenBracket off acc)
| x == '"' -> TokenAccum StateLit2 (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenBracket off acc)
| otherwise -> TokenAccum StateOther (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenBracket off acc)
tokens' (TokenAccum StateOther off _ acc out) x =
case () of
_ | isSpaceLT ! x -> TokenAccum StateSpace (off+1) 0 DL.empty (out `DL.snoc` mkToken TokenOther off acc)
| isAlphaLT ! x -> TokenAccum StateAlpha (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenOther off acc)
| isDigitLT ! x -> if DL.toList acc == "."
then TokenAccum StateDigit (off+1) 0 (acc `DL.snoc` x) out
else TokenAccum StateDigit (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenOther off acc)
| isBracketLT ! x -> TokenAccum StateBracket (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenOther off acc)
| x == '\'' -> TokenAccum StateLit1 (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenBracket off acc)
| x == '"' -> TokenAccum StateLit2 (off+1) 0 (DL.singleton x) (out `DL.snoc` mkToken TokenBracket off acc)
| otherwise -> TokenAccum StateOther (off+1) 0 (acc `DL.snoc` x) out
|
beni55/cgrep
|
src/CGrep/Semantic/Generic/Token.hs
|
gpl-2.0
| 10,210 | 0 | 16 | 3,193 | 3,400 | 1,794 | 1,606 | 155 | 9 |
{-# LANGUAGE
FlexibleInstances
, TypeSynonymInstances
#-}
{- |
Module : $Header$
Description : OMDoc-XML conversion
Copyright : (c) Ewaryst Schulz, DFKI 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
The transformation of the OMDoc intermediate representation to and from xml.
The import from xml does not validate the xml, hence if you encounter strange
errors, do not forget to check the xml structure first.
-}
module OMDoc.XmlInterface where
import OMDoc.DataTypes
import Common.Utils (splitBy)
import Common.Result
import Common.Id
import Data.Maybe
import Data.List
import Network.URI (isUnescapedInURI, escapeURIString, unEscapeString)
import Common.XmlParser (XmlParseable, parseXml)
import Text.XML.Light
-- * Names and other constants
-- | The implemented OMDoc version
omdoc_current_version :: String
omdoc_current_version = "1.6"
toQN :: String -> QName
toQN s = blank_name { qName = s }
toQNOM :: String -> QName
toQNOM s = blank_name { qName = s , qPrefix = Just "om" }
-- | often used element names
el_omdoc, el_theory, el_view, el_structure, el_type, el_adt, el_sortdef
, el_constructor, el_argument, el_insort, el_selector, el_open, el_component
, el_conass, el_constant, el_notation, el_text, el_definition, el_omobj
, el_ombind, el_oms, el_ombvar, el_omattr, el_omatp, el_omv, el_oma :: QName
el_omdoc = toQN "omdoc"
el_theory = toQN "theory"
el_view = toQN "view"
el_structure = toQN "structure"
el_type = toQN "type"
el_adt = toQN "adt"
el_sortdef = toQN "sortdef"
el_constructor = toQN "constructor"
el_argument = toQN "argument"
el_insort = toQN "insort"
el_selector = toQN "selector"
el_conass = toQN "conass"
el_open = toQN "open"
el_constant = toQN "constant"
el_notation = toQN "notation"
el_text = toQN "text"
el_definition = toQN "definition"
el_component = toQN "component"
el_omobj = toQN "OMOBJ"
el_ombind = toQNOM "OMBIND"
el_oms = toQNOM "OMS"
el_ombvar = toQNOM "OMBVAR"
el_omattr = toQNOM "OMATTR"
el_omatp = toQNOM "OMATP"
el_omv = toQNOM "OMV"
el_oma = toQNOM "OMA"
at_version, at_module, at_name, at_meta, at_role, at_type, at_total, at_for
, at_from, at_to, at_value, at_base, at_as, at_precedence, at_fixity, at_index
, at_associativity, at_style, at_implicit :: QName
at_version = toQN "version"
at_module = toQN "module"
at_name = toQN "name"
at_meta = toQN "meta"
at_role = toQN "role"
at_type = toQN "type"
at_total = toQN "total"
at_for = toQN "for"
at_from = toQN "from"
at_to = toQN "to"
at_value = toQN "value"
at_base = toQN "base"
at_as = toQN "as"
at_precedence = toQN "precedence"
at_fixity = toQN "fixity"
at_associativity = toQN "associativity"
at_style = toQN "style"
at_implicit = toQN "implicit"
at_index = toQN "index"
attr_om :: Attr
attr_om = Attr (blank_name { qName = "om" , qPrefix = Just "xmlns" })
"http://www.openmath.org/OpenMath"
-- * Top level from/to xml functions
{- |
This class defines the interface to read from and write to XML
-}
class XmlRepresentable a where
-- | render instance to an XML Element
toXml :: a -> Content
-- | read instance from an XML Element
fromXml :: Element -> Result (Maybe a)
{-
-- for testing the performance without the xml lib we use the show and read funs
xmlOut :: Show a => a -> String
xmlOut = show
xmlIn :: String -> Result OMDoc
xmlIn = return . read
-}
xmlOut :: XmlRepresentable a => a -> String
xmlOut obj = case toXml obj of (Elem e) -> ppTopElement e
c -> ppContent c
xmlIn :: XmlParseable a => a -> Result OMDoc
xmlIn s = case parseXml s of
Right e -> fromXml e >>= maybe (fail "xmlIn") return
Left msg -> fail msg
listToXml :: XmlRepresentable a => [a] -> [Content]
listToXml l = map toXml l
listFromXml :: XmlRepresentable a => [Content] -> Result [a]
listFromXml elms = fmap catMaybes $ mapR fromXml (onlyElems elms)
mkElement :: QName -> [Attr] -> [Content] -> Content
mkElement qn atts elems = Elem $ Element qn atts elems Nothing
makeComment :: String -> Content
makeComment s = Text $ CData CDataRaw ("<!-- " ++ s ++ " -->") Nothing
inAContent :: QName -> [Attr] -> Maybe Content -> Content
inAContent qn a c = mkElement qn a $ maybeToList c
inContent :: QName -> Maybe Content -> Content
inContent qn c = inAContent qn [] c
toOmobj :: Content -> Content
toOmobj c = inAContent el_omobj [attr_om] $ Just c
-- * Encoding/Decoding
-- url escaping and unescaping.
-- We use ? and / as special characters, so we need them to be encoded in names
urlEscape :: String -> String
urlEscape = escapeURIString isUnescapedInURI
urlUnescape :: String -> String
urlUnescape = unEscapeString
-- to- and from-string functions
showCDName :: OMCD -> OMName -> String
showCDName omcd omname = concat [showCD omcd, "?", showOMName omname]
showCD :: OMCD -> String
showCD cd = let [x,y] = cdToList cd
in concat [x, "?", y]
showOMName :: OMName -> String
showOMName on = intercalate "/" $ path on ++ [name on]
readCD :: Show a => a -> String -> OMCD
readCD _ s = case splitBy '?' s of
[b, cd] -> cdFromList [b, cd]
_ -> error $ concat [ "readCD: The value "
, "has to contain exactly one '?'"]
readCDName :: String -> OMQualName
readCDName s = case splitBy '?' s of
(b:cd:n:[]) -> ( cdFromList [b, cd]
, readOMName n)
_ -> error $ concat [ "readCDName: The value "
, "has to contain exactly two '?'"]
readOMName :: String -> OMName
readOMName s = let l = splitBy '/' s
in OMName (last l) $ init l
-- encoding
-- only uri-fields need to be %-encoded, the following attribs are uri-fields:
{-
theory@meta
include@from
structure@from
view@from
view@to
@base
-}
tripleEncodeOMS :: OMCD -> OMName -> [Attr]
tripleEncodeOMS omcd omname
= pairEncodeCD omcd ++ [Attr at_name $ showOMName omname]
pairEncodeCD :: OMCD -> [Attr]
pairEncodeCD cd = let [base, modl] = cdToMaybeList cd
in catMaybes $ [ fmap (Attr at_base . urlEscape) base
, fmap (Attr at_module) modl]
-- decoding
tripleDecodeOMS :: String -> String -> String -> (OMCD, OMName)
tripleDecodeOMS cd base nm =
let cdl = filter (not . null) [cd, urlUnescape base]
in if null cd && not (null base)
then error "tripleDecodeOMS: base not empty but cd not given!"
else (CD cdl, readOMName nm)
warnIfNothing :: String -> (Maybe a -> b) -> Maybe a -> Result b
warnIfNothing s f v = let o = f v in
case v of Nothing -> warning () s nullRange >> return o
_ -> return o
warnIf :: String -> Bool -> Result ()
warnIf s b = if b then warning () s nullRange else return ()
elemIsOf :: Element -> QName -> Bool
elemIsOf e qn = let en = elName e in
(qName en, qPrefix en) == (qName qn, qPrefix qn)
oneOfMsg :: Element -> [QName] -> String
oneOfMsg e l = let printName = qName in
concat [ "Couldn't find expected element {"
, intercalate ", " (map printName l), "}"
, fromMaybe "" $ fmap ((" at line "++).show) $ elLine e
, " but found ", printName $ elName e, "."
]
-- * Monad and Maybe interaction
justReturn :: Monad m => a -> m (Maybe a)
justReturn = return . Just
fmapMaybe :: Monad m => (a -> m b) -> Maybe a -> m (Maybe b)
fmapMaybe f v = encapsMaybe $ fmap f v
fmapFromMaybe :: Monad m => (a -> m (Maybe b)) -> Maybe a -> m (Maybe b)
fmapFromMaybe f = flattenMaybe . fmapMaybe f
encapsMaybe :: Monad m => Maybe (m a) -> m (Maybe a)
encapsMaybe v = case v of
Just x -> x >>= justReturn
_ -> return Nothing
flattenMaybe :: Monad m => m (Maybe (Maybe a)) -> m (Maybe a)
flattenMaybe v = v >>= return . fromMaybe Nothing
-- | Function to extract the Just values from maybes with a default missing
-- error in case of Nothing
missingMaybe :: String -> String -> Maybe a -> a
missingMaybe el misses =
fromMaybe (error $ el ++ " element must have a " ++ misses ++ ".")
-- -- -- -- -- XmlRepresentable Class instances for OMDoc types -- -- -- -- --
-- | The root instance for representing OMDoc in XML
instance XmlRepresentable OMDoc where
toXml (OMDoc omname elms) =
mkElement
el_omdoc [Attr at_version omdoc_current_version, Attr at_name omname]
$ listToXml elms
fromXml e
| elemIsOf e el_omdoc =
do
nm <- warnIfNothing "No name in omdoc element." (fromMaybe "")
$ findAttr at_name e
vs <- warnIfNothing "No version in omdoc element."
(fromMaybe "1.6") $ findAttr at_version e
warnIf "Wrong OMDoc version." $ vs /= omdoc_current_version
tls <- listFromXml $ elContent e
justReturn $ OMDoc nm tls
| otherwise = fail "OMDoc fromXml: toplevel element is no omdoc."
-- | toplevel OMDoc elements to XML and back
instance XmlRepresentable TLElement where
toXml (TLTheory tname meta elms) =
mkElement
el_theory ((Attr at_name tname)
: case meta of Nothing -> []
Just mtcd ->
[Attr at_meta $ urlEscape $ showCD mtcd])
$ listToXml elms
toXml (TLView nm from to morph) =
mkElement
el_view [Attr at_name nm, Attr at_from $ urlEscape $ showCD from,
Attr at_to $ urlEscape $ showCD to]
$ map assignmentToXml morph
fromXml e
| elemIsOf e el_theory =
let nm = missingMaybe "Theory" "name" $ findAttr at_name e
mt = fmap (readCD (elLine e) . urlUnescape) $ findAttr at_meta e
in do
tcl <- listFromXml $ elContent e
justReturn $ TLTheory nm mt tcl
| elemIsOf e el_view =
let musthave at s = missingMaybe "View" s $ findAttr at e
nm = musthave at_name "name"
from = readCD (elLine e) $ urlUnescape $ musthave at_from "from"
to = readCD (elLine e) $ urlUnescape $ musthave at_to "to"
in do
morph <- mapR xmlToAssignment (findChildren el_conass e)
justReturn $ TLView nm from to morph
| otherwise = return Nothing
-- | theory constitutive OMDoc elements to XML and back
instance XmlRepresentable TCElement where
toXml (TCSymbol sname symtype role defn) =
constantToXml sname (show role) symtype defn
toXml (TCNotation (cd, nm) val mStl) =
inAContent
el_notation
( [Attr at_for $ urlEscape $ showCDName cd nm, Attr at_role "constant"]
++ maybe [] ((:[]) . Attr at_style) mStl )
$ Just $ inAContent el_text [Attr at_value val] Nothing
toXml (TCSmartNotation (cd, nm) fixity assoc prec implicit) =
inAContent
el_notation
( [ Attr at_for $ urlEscape $ showCDName cd nm
, Attr at_role "application", Attr at_fixity $ show fixity
, Attr at_precedence $ show prec ]
++ if implicit == 0 then [] else [Attr at_implicit $ show implicit]
++ if assoc == NoneAssoc then [] else [Attr at_associativity
$ show assoc] )
Nothing
toXml (TCFlexibleNotation (cd, nm) prec comps) =
mkElement
el_notation
[ Attr at_for $ urlEscape $ showCDName cd nm, Attr at_role "application"
, Attr at_precedence $ show prec ] $ map notationComponentToXml comps
toXml (TCADT sds) = mkElement el_adt [] $ listToXml sds
toXml (TCComment c) = makeComment c
toXml (TCImport nm from morph) =
mkElement
el_structure [Attr at_name nm, Attr at_from $ urlEscape $ showCD from]
$ map assignmentToXml morph
fromXml e
| elemIsOf e el_constant =
let musthave s v = missingMaybe "Constant" s v
nm = musthave "name" $ findAttr at_name e
role = fromMaybe Obj $ fmap read $ findAttr at_role e
in do
typ <- fmap (musthave "typ") $ omelementFrom el_type e
defn <- omelementFrom el_definition e
justReturn $ TCSymbol nm typ role defn
| elemIsOf e el_notation =
let musthave s v = missingMaybe "Notation" s v
nm = urlUnescape $ musthave "for" $ findAttr at_for e
role = musthave "role" $ findAttr at_role e
mStl = findAttr at_style e
text = musthave "text" $ findChild el_text e
val = musthave "value" $ findAttr at_value text
in if role == "constant"
then justReturn $ TCNotation (readCDName nm) val mStl
else return Nothing
| elemIsOf e el_structure =
let musthave at s = missingMaybe "Structure" s $ findAttr at e
nm = musthave at_name "name"
from = readCD (elLine e) $ urlUnescape $ musthave at_from "from"
in do
morph <- mapR xmlToAssignment
$ filterChildrenName (flip elem [el_conass, el_open]) e
justReturn $ TCImport nm from morph
| elemIsOf e el_adt =
do
sds <- listFromXml $ elContent e
justReturn $ TCADT sds
| otherwise =
fail $ oneOfMsg e [el_constant, el_structure, el_adt, el_notation]
-- | OMDoc - Algebraic Data Types
instance XmlRepresentable OmdADT where
toXml (ADTSortDef n b cs) =
mkElement el_sortdef
[Attr at_name n, Attr at_type $ show b]
$ listToXml cs
toXml (ADTConstr n args) =
mkElement el_constructor [Attr at_name n] $ listToXml args
toXml (ADTArg t sel) =
mkElement el_argument []
$ typeToXml t :
case sel of Nothing -> []
Just s -> [toXml s]
toXml (ADTSelector n total) =
mkElement el_selector [Attr at_name n, Attr at_total $ show total] []
toXml (ADTInsort (d,n)) =
mkElement el_insort [Attr at_for $ showCDName d n] []
fromXml e
| elemIsOf e el_sortdef =
let musthave s at = missingMaybe "Sortdef" s $ findAttr at e
nm = musthave "name" at_name
typ = read $ musthave "type" at_type
in do
entries <- listFromXml $ elContent e
justReturn $ ADTSortDef nm typ entries
| elemIsOf e el_constructor =
do
let nm = missingMaybe "Constructor" "name" $ findAttr at_name e
entries <- listFromXml $ elContent e
justReturn $ ADTConstr nm entries
| elemIsOf e el_argument =
do
typ <- fmap (missingMaybe "Argument" "typ")
$ omelementFrom el_type e
sel <- fmapFromMaybe fromXml $ findChild el_selector e
justReturn $ ADTArg typ sel
| elemIsOf e el_selector =
let musthave s at = missingMaybe "Selector" s $ findAttr at e
nm = musthave "name" at_name
total = read $ musthave "total" at_total
in justReturn $ ADTSelector nm total
| elemIsOf e el_insort =
do
let nm = missingMaybe "Insort" "for" $ findAttr at_for e
justReturn $ ADTInsort $ readCDName nm
| otherwise =
fail $ oneOfMsg e [ el_sortdef, el_constructor, el_argument
, el_selector, el_insort]
-- | OpenMath elements to XML and back
instance XmlRepresentable OMElement where
toXml (OMS (d, n)) = mkElement el_oms (tripleEncodeOMS d n) []
toXml (OMV n) = mkElement el_omv [Attr at_name (name n)] []
toXml (OMATTT elm attr) = mkElement el_omattr [] [toXml attr, toXml elm]
toXml (OMA args) = mkElement el_oma [] $ listToXml args
toXml (OMBIND symb vars body) =
mkElement el_ombind []
[ toXml symb
, mkElement el_ombvar [] $ listToXml vars
, toXml body]
fromXml e
| elemIsOf e el_oms =
let nm = missingMaybe "OMS" "name" $ findAttr at_name e
omcd = fromMaybe "" $ findAttr at_module e
cdb = fromMaybe "" $ findAttr at_base e
in justReturn $ OMS $ tripleDecodeOMS omcd cdb nm
| elemIsOf e el_omv =
let nm = missingMaybe "OMV" "name" $ findAttr at_name e
in justReturn $ OMV $ readOMName nm
| elemIsOf e el_omattr =
let [atp, el] = elChildren e
musthave s v = missingMaybe "OMATTR" s v
in do
atp' <- fromXml atp
el' <- fromXml el
justReturn $ OMATTT (musthave "attributed value" el')
(musthave "attribution" atp')
| elemIsOf e el_oma =
do
entries <- listFromXml $ elContent e
justReturn $ OMA entries
| elemIsOf e el_ombind =
let [bd, bvar, body] = elChildren e
musthave s v = missingMaybe "OMBIND" s v
in do
bd' <- fromXml bd
bvar' <- listFromXml $ elContent bvar
body' <- fromXml body
justReturn $ OMBIND (musthave "binder" bd') bvar'
(musthave "body" body')
| otherwise =
fail $ oneOfMsg e [el_oms, el_omv, el_omattr, el_oma, el_ombind]
-- | Helper instance for OpenMath attributes
instance XmlRepresentable OMAttribute where
toXml (OMAttr e1 e2) = mkElement el_omatp [] [toXml e1, toXml e2]
fromXml e
| elemIsOf e el_omatp =
do
[key, val] <- listFromXml $ elContent e
justReturn $ OMAttr key val
| otherwise =
fail $ oneOfMsg e [el_omatp]
-- * fromXml methods
-- | If the child element with given name contains an OMOBJ xml element,
-- this is transformed to an OMElement.
omelementFrom :: QName -> Element -> Result (Maybe OMElement)
omelementFrom qn e = fmapFromMaybe omelementFromOmobj $ findChild qn e
omelementFromOmobj :: Element -> Result (Maybe OMElement)
omelementFromOmobj e = fmapMaybe omobjToOMElement $ findChild el_omobj e
-- | Get an OMElement from an OMOBJ xml element
omobjToOMElement :: Element -> Result OMElement
omobjToOMElement e = case elChildren e of
[om] ->
do
omelem <- fromXml om
case omelem of
Nothing ->
fail
$ concat [ "omobjToOMElement: "
, "No OpenMath element found."]
Just x -> return x
_ -> fail "OMOBJ element must have a unique child."
-- | The input is assumed to be a conass element
xmlToAssignment :: Element -> Result (OMName, OMImage)
xmlToAssignment e
| elName e == el_open =
let musthave s v = missingMaybe "Open" s v
nm = musthave "name" $ findAttr at_name e
alias = musthave "as" $ findAttr at_as e
in return (readOMName nm, Left alias)
| elName e == el_conass =
let musthave s v = missingMaybe "Conass" s v
nm = musthave "name" $ findAttr at_name e
in do
omel <- omelementFromOmobj e
return (readOMName nm, Right $ musthave "OMOBJ element" omel)
| otherwise = fail $ oneOfMsg e [el_conass, el_open]
-- * toXml methods
typeToXml :: OMElement -> Content
typeToXml t = inContent el_type $ Just $ toOmobj $ toXml t
assignmentToXml :: (OMName, OMImage) -> Content
assignmentToXml (from, to) =
case to of
Left s ->
mkElement el_open [Attr at_name $ showOMName from, Attr at_as s] []
Right obj ->
inAContent el_conass [Attr at_name $ showOMName from]
$ Just . toOmobj . toXml $ obj
constantToXml :: String -> String -> OMElement -> Maybe OMElement -> Content
constantToXml n r tp prf =
Elem $ Element el_constant
[Attr at_name n, Attr at_role r]
([typeToXml tp]
++ map (inContent el_definition . Just . toOmobj . toXml)
(maybeToList prf))
Nothing
notationComponentToXml :: NotationComponent -> Content
notationComponentToXml (TextComp val) = mkElement el_text [Attr at_value val] []
notationComponentToXml (ArgComp ind prec) =
mkElement el_component [ Attr at_index $ show ind
, Attr at_precedence $ show prec] []
|
nevrenato/Hets_Fork
|
OMDoc/XmlInterface.hs
|
gpl-2.0
| 20,993 | 0 | 17 | 6,679 | 6,097 | 3,004 | 3,093 | 425 | 3 |
module Main where
import Data.Int
fib :: Int64 -> Int64
fib n =
let tr i acc = if i < 2 then acc else tr (i-2) (fib (i-1) + acc) in
tr n 1
main =
print (fib 38)
|
uelis/intc
|
Examples/Comparison/fib_rec_tailrec.hs
|
gpl-2.0
| 175 | 0 | 15 | 54 | 102 | 53 | 49 | 8 | 2 |
module Menu where
import Affection as A
import qualified SDL
import qualified Data.Set as S
import Control.Monad
import Control.Concurrent.MVar
import NanoVG
-- internal imports
import Types
import Commons
loadMenu :: Affection () -> UserData -> Affection ()
loadMenu stateChange ud = do
liftIO $ logIO A.Debug "Loading Menu"
hs <- newHaskelloids (haskImage ud)
kbdUUID <- partSubscribe (subKeyboard $ subsystems ud)
(\kbdev -> when (msgKbdKeyMotion kbdev == SDL.Pressed) $
case SDL.keysymKeycode (msgKbdKeysym kbdev) of
SDL.KeycodeEscape -> do
liftIO $ logIO A.Debug "seeya"
void $ liftIO $ swapMVar (doNextStep ud) False
SDL.KeycodeSpace -> do
liftIO $ logIO A.Debug "Leaving Menu to Game"
stateChange
_ -> return ()
)
void $ liftIO $ swapMVar (haskelloids ud) hs
void $ liftIO $ swapMVar (fade ud) (FadeIn 1)
void $ liftIO $ swapMVar (state ud) Menu
void $ liftIO $ swapMVar (stateUUIDs ud) (UUIDClean [] [kbdUUID])
updateMenu :: UserData -> Double -> Affection ()
updateMenu ud sec = do
nhs <- map (updateHaskelloid sec) <$> liftIO (readMVar (haskelloids ud))
void $ liftIO $ swapMVar (haskelloids ud) nhs
fadeState <- liftIO (readMVar $ fade ud)
case fadeState of
FadeIn ttl ->
void $ liftIO $ swapMVar (fade ud) (if (ttl - sec) > 0 then FadeIn (ttl - sec) else FadeOut 1)
FadeOut ttl ->
void $ liftIO $ swapMVar (fade ud) (if (ttl - sec) > 0 then FadeOut (ttl - sec) else FadeIn 1)
drawMenu :: UserData -> Affection ()
drawMenu ud = do
hasks <- liftIO $ readMVar (haskelloids ud)
mapM_ (drawHaskelloid (nano ud)) hasks
liftIO $ do
let ctx = nano ud
alpha fio = case fio of
FadeIn d -> floor (255 * (1 - d))
FadeOut d -> floor (255 * d)
save ctx
fontSize ctx 120
fontFace ctx "modulo"
textAlign ctx (S.fromList [AlignCenter,AlignTop])
fillColor ctx (rgba 255 255 255 255)
textBox ctx 0 200 800 "HASKELLOIDS"
fadeState <- readMVar (fade ud)
fillColor ctx (rgba 0 128 255 (alpha $ fadeState))
fontSize ctx 40
textBox ctx 0 350 800 "Press [Space] to Play\nPress [Esc] to exit"
restore ctx
|
nek0/haskelloids
|
src/Menu.hs
|
gpl-3.0
| 2,206 | 0 | 20 | 553 | 881 | 422 | 459 | 57 | 4 |
Config { font = "xft:Inconsolata:bold:size=16"
, additionalFonts = []
, borderColor = "grey"
, border = BottomB
, bgColor = "black"
, fgColor = "white"
, alpha = 255
, position = Top
, textOffset = -1
, iconOffset = -1
, lowerOnStart = True
, pickBroadest = False
, persistent = False
, hideOnStart = False
, iconRoot = "/usr/local/share/icons/xpm"
, allDesktops = True
, overrideRedirect = True
, commands = [ Run StdinReader
, Run Network "enp0s25" ["-t", "<txbar><icon=transfer.xpm/>", "-W", "0"] 10
, Run Network "wlp3s0" ["-t", "<txbar><icon=wifi.xpm/>", "-W", "0"] 10
, Run BatteryP ["BAT0", "BAT1"] ["-t", "<icon=battery-full.xpm/> <left>"] 60
, Run Brightness ["-t", "<icon=lightbulb.xpm/> <percent>", "--", "-D", "intel_backlight"] 10
, Run Com "ponymix" ["get-volume"] "volume" 10
, Run Com "bash" ["-c", "if [ -e /run/openvpn-client@*.pid ]; then echo '<icon=lock-locked.xpm/>'; else echo '<icon=lock-unlocked.xpm/>'; fi"] "vpn" 60
, Run Date "%a %d.%m.%y %H:%M" "date" 10
]
, sepChar = "%"
, alignSep = "}{"
, template = "%StdinReader% } %date% { %enp0s25% %wlp3s0% %vpn% <icon=volume-high.xpm/> %volume% %bright% %battery%"
}
|
akermu/akermu-xmonad
|
src/xmobar.hs
|
gpl-3.0
| 1,358 | 0 | 9 | 389 | 290 | 175 | 115 | -1 | -1 |
{-# LANGUAGE DeriveGeneric #-}
module Estuary.Types.TidalParser where
import GHC.Generics
import Data.Aeson
data TidalParser = MiniTidal | CQenze | LaCalle | Sucixxx | Togo | BlackBox
deriving (Show,Read,Eq,Ord,Generic)
instance ToJSON TidalParser where
toEncoding = genericToEncoding defaultOptions
instance FromJSON TidalParser
|
d0kt0r0/estuary
|
common/src/Estuary/Types/TidalParser.hs
|
gpl-3.0
| 338 | 0 | 6 | 46 | 86 | 49 | 37 | 9 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Views.Home (
homeView
) where
import Text.Blaze.Html5
import Text.Blaze.Html5.Attributes
import Views.Index (layout)
import Views.Util (blaze)
import Web.Scotty (ActionM)
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
homeView :: ActionM ()
homeView = blaze $ layout "home" $ do
H.div ! class_ "container" $ do
H.h2 "Weirdcanada !!!!"
|
aaronlevin/weirdcanada-site
|
Views/Home.hs
|
gpl-3.0
| 553 | 0 | 12 | 188 | 124 | 73 | 51 | 14 | 1 |
{-# OPTIONS_GHC -Wall -Werror -fno-warn-orphans -i.. #-}
{-# LANGUAGE GADTs, RankNTypes, ScopedTypeVariables, ImpredicativeTypes #-}
module Utils.Common(M, ClsrId, SSAVar, Rator, GenRator(..), mapGenRator,
ratorSubstitute, IRMonad, freshVarName, runIRMonad,
irGetCustom, irPutCustom, mApp, EchoesOptions(..),
unimplemented)
where
import Compiler.Hoopl
import Control.Monad.State
import qualified Data.Maybe as Mby
type M = CheckingFuelMonad SimpleUniqueMonad
type ClsrId = Int
type SSAVar = Int
data GenRator varTy litTy = LitR litTy | VarR varTy deriving(Show, Eq, Ord)
type Rator = GenRator SSAVar
mapGenRator :: (r -> s) -> GenRator r a -> GenRator s a
mapGenRator _ (LitR litTy) = LitR litTy
mapGenRator f (VarR varTy) = VarR $ f varTy
ratorSubstitute :: (SSAVar -> Maybe a) -> Rator a -> Rator a
ratorSubstitute _ v@(LitR _) = v
ratorSubstitute f v@(VarR var) = Mby.fromMaybe v (liftM LitR $ f var)
type IRMonad custom a = StateT ([SSAVar], custom) M a
instance UniqueMonad m => UniqueMonad (StateT s m) where
freshUnique = StateT (\s -> liftM (\u -> (u, s)) freshUnique)
freshVarName :: IRMonad custom SSAVar
freshVarName = StateT (\(name:names, other) -> return (name, (names, other)))
runIRMonad :: IRMonad custom a -> SSAVar -> custom -> M (a, SSAVar, custom)
runIRMonad monad ssaVarInit cInit = do
(result, (ssaVarFinal:_, cFinal)) <- runStateT monad ([ssaVarInit..], cInit)
return (result, ssaVarFinal, cFinal)
irGetCustom :: IRMonad custom custom
irGetCustom = liftM snd get
irPutCustom :: custom -> IRMonad custom ()
irPutCustom s = get >>= (\(a, _) -> put (a, s))
mApp :: (Monad m) => m [a] -> m [a] -> m [a]
mApp = liftM2 (++)
data EchoesOptions = EOptions {
annotateAssembly :: Bool }
unimplemented :: String -> a
unimplemented str = error ("unimplemented: " ++ str)
|
sanjoy/echoes
|
src/Utils/Common.hs
|
gpl-3.0
| 1,871 | 0 | 12 | 362 | 696 | 386 | 310 | 39 | 1 |
module Problems61thru69 where
import ADT.Tree
-- Problem 61
--
-- Count the leaves of a binary tree
--
-- A leaf is a node with no successors. Write a predicate count_leaves/2 to
-- count them.
countLeaves :: Tree a -> Int
countLeaves Nil = 0
countLeaves (Node Nil _ Nil) = 1
countLeaves (Node l x r) = countLeaves l + countLeaves r
-- Problem 61A
--
-- Collect the leaves of a binary tree in a list
--
-- A leaf is a node with no successors. Write a predicate leaves/2 to collect
-- them in a list.
leaves :: Tree a -> [a]
leaves Nil = []
leaves (Node Nil x Nil) = [x]
leaves (Node l x r) = leaves l ++ leaves r
-- Problem 62
--
-- Collect the internal nodes of a binary tree in a list
--
-- An internal node of a binary tree has either one or two non-empty
-- successors. Write a predicate internals/2 to collect them in a list.
internals :: Tree a -> [a]
internals Nil = []
internals (Node Nil x Nil) = []
internals (Node l x r) = [x] ++ internals l ++ internals r
-- Problem 62B
--
-- Collect the nodes at a given level in a list
--
-- A node of a binary tree is at level N if the path from the root to the
-- node has length N-1. The root node is at level 1. Write a predicate
-- atlevel/3 to collect all nodes at a given level in a list.
atLevel :: Tree a -> Int -> [a]
atLevel Nil _ = []
atLevel (Node _ x _) 1 = [x]
atLevel (Node l _ r) n = atLevel l (n-1) ++ atLevel r (n-1)
|
zcesur/h99
|
src/Problems61thru69.hs
|
gpl-3.0
| 1,401 | 0 | 8 | 315 | 356 | 192 | 164 | 18 | 1 |
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
module Network.APNS.Protocol where
import Network.APNS.Protocol.Types
import Network.APNS.Protocol.Binary
|
tiago-loureiro/apns
|
src/Network/APNS/Protocol.hs
|
mpl-2.0
| 310 | 0 | 4 | 46 | 24 | 18 | 6 | 3 | 0 |
-- module for dealing with pixmaps that are needed for the application generally,
-- like menus, general OSDs, etc.
module Base.Application.Pixmaps (
loadApplicationPixmaps,
) where
import Data.Abelian
import System.FilePath
import Graphics.Qt
import Base.Paths
import Base.Types
import Base.Constants
import Base.Pixmap
import Base.Font
loadApplicationPixmaps :: IO ApplicationPixmaps
loadApplicationPixmaps =
ApplicationPixmaps <$>
(loadBackground "background") <*>
(loadBackground "backgroundOverlay") <*>
loadAlphaNumericFont <*>
loadDigitFont <*>
loadHeaderCubePixmaps <*>
(loadOsd (Position 32 32) (Size 772 268) "menuTitle") <*>
(loadOsd (Position 32 32) (Size 472 88) "pause") <*>
(loadOsd (Position 32 32) (Size 664 88) "success") <*>
(loadOsd (Position 32 32) (Size 600 88) "failure")
loadBackground name =
mapM (loadSymmetricPixmap zero) =<<
getDataFiles (osdDir </> name) (Just ".png")
loadHeaderCubePixmaps :: IO HeaderCubePixmaps
loadHeaderCubePixmaps = do
start <- loadOsd (Position 31 31) (Size 48 44) "box-left"
standard <- loadOsd (Position 1 31) (Size 48 44) "box-standard"
space <- loadOsd (Position 1 31) (Size 48 44) "box-space"
end <- loadOsd (Position 1 31) (Size 44 44) "box-right"
return $ HeaderCubePixmaps start standard space end
loadOsd :: Position Double -> Size Double -> String -> IO Pixmap
loadOsd offset size name = loadPixmap offset size =<< getDataFileName (osdDir </> name <.> "png")
osdDir = pngDir </> "osd"
|
nikki-and-the-robots/nikki
|
src/Base/Application/Pixmaps.hs
|
lgpl-3.0
| 1,575 | 0 | 15 | 321 | 478 | 241 | 237 | 35 | 1 |
module MyMaybes where
isJust :: Maybe a -> Bool
isJust Nothing = False
isJust _ = True
isNothing :: Maybe a -> Bool
isNothing = not . isJust
mayybee :: b -> (a -> b) -> Maybe a -> b
mayybee def _ Nothing = def
mayybee _ f (Just a) = f a
fromMaybe :: a -> Maybe a -> a
fromMaybe def a = mayybee def id a
listToMaybe :: [a] -> Maybe a
listToMaybe [] = Nothing
listToMaybe (x:_) = Just x
maybeToList :: Maybe a -> [a]
maybeToList Nothing = []
maybeToList (Just a) = [a]
catMaybes :: [Maybe a] -> [a]
-- this is loco
catMaybes li = [x | Just x <- li]
flipMaybe :: [Maybe a] -> Maybe [a]
flipMaybe li
| (length li) == (length res) = Just res
| otherwise = Nothing
where res = catMaybes li
|
thewoolleyman/haskellbook
|
12/05/maor/myMaybes.hs
|
unlicense
| 699 | 0 | 10 | 161 | 345 | 175 | 170 | 24 | 1 |
--file: ch07/actions.hs
main :: IO ()
main = do
str2action "Staring Program..."
printall
str2action "Done!"
str2action :: String -> IO ()
str2action input = putStrLn $ "Data: " ++ input
list2actions :: [String] -> [IO ()]
list2actions = map str2action
numbers :: [Int]
numbers = [0..10]
strings :: [String]
strings = map show numbers
actions :: [IO ()]
actions = list2actions strings
printall :: IO ()
printall = runall actions
runall :: [IO ()] -> IO ()
runall [] = return ()
runall (x:xs) = x >> runall xs
|
willsalz/Real-World-Haskell
|
ch07/actions.hs
|
unlicense
| 519 | 0 | 8 | 100 | 224 | 114 | 110 | 20 | 1 |
{-# LANGUAGE OverloadedStrings, CPP #-}
module FormStructure.Chapter6 (ch6DataManagement) where
#ifndef __HASTE__
--import Data.Text.Lazy (pack)
#endif
import FormEngine.FormItem
import FormStructure.Common
ch6DataManagement :: FormItem
ch6DataManagement = Chapter
{ chDescriptor = defaultFIDescriptor { iLabel = Just "6.Management " }
, chItems = [for, management, cost6, remark]
}
where
for :: FormItem
for = SimpleGroup
{ sgDescriptor = defaultFIDescriptor
{ iLabel = Just "We perform data management for:"
}
, sgLevel = 0
, sgItems = [ OptionalGroup
{ ogDescriptor = defaultFIDescriptor
{ iLabel = Just "local use"
}
, ogLevel = 0
, ogItems = []
}
, OptionalGroup
{ ogDescriptor = defaultFIDescriptor
{ iLabel = Just "community use"
}
, ogLevel = 0
, ogItems = []
}
]
}
management :: FormItem
management = SimpleGroup
{ sgDescriptor = defaultFIDescriptor
{ iLabel = Just "Management details"
}
, sgLevel = 0
, sgItems = [ ChoiceFI
{ chfiDescriptor = defaultFIDescriptor
{ iLabel = Just "Do you handle error reports?"
}
, chfiAvailableOptions = [SimpleOption "no", SimpleOption "yes"]
}
, ChoiceFI
{ chfiDescriptor = defaultFIDescriptor
{ iLabel = Just "Do you manage versioning?"
}
, chfiAvailableOptions = [SimpleOption "no", SimpleOption "yes"]
}
, ChoiceFI
{ chfiDescriptor = defaultFIDescriptor
{ iLabel = Just "Is data actuality maintained (updates)?"
}
, chfiAvailableOptions = [SimpleOption "no", SimpleOption "yes"]
}
, ChoiceFI
{ chfiDescriptor = defaultFIDescriptor
{ iLabel = Just "Sustainability"
}
, chfiAvailableOptions = [ SimpleOption "long-term, continuous funding"
, DetailedOption NoNumbering "short-term"
[ SimpleGroup
{ sgDescriptor = defaultFIDescriptor
, sgLevel = 0
, sgItems = [ NumberFI
{ nfiDescriptor = defaultFIDescriptor
{ iLabel = Just "How long"
}
, nfiUnit = SingleUnit "years"
}
]
}
]
]
}
, NumberFI
{ nfiDescriptor = defaultFIDescriptor
{ iLabel = Just "Longest required sustainability"
}
, nfiUnit = SingleUnit "years"
}
, ChoiceFI
{ chfiDescriptor = defaultFIDescriptor
{ iLabel = Just "Do you apply some form of data stewardship?"
, iMandatory = True
}
, chfiAvailableOptions = [ DetailedOption NoNumbering "Yes" [xhow]
, SimpleOption "No"
]
}
]
}
cost6 :: FormItem
cost6 = SimpleGroup
{ sgDescriptor = defaultFIDescriptor
{ iLabel = Just "Total cost of data management"
, iMandatory = True
}
, sgLevel = 0
, sgItems = [ NumberFI
{ nfiDescriptor = defaultFIDescriptor
{ iLabel = Just "For year 2016"
}
, nfiUnit = SingleUnit "thousand EUR"
}
]
}
|
DataStewardshipPortal/ds-elixir-cz
|
FormStructure/Chapter6.hs
|
apache-2.0
| 4,716 | 0 | 22 | 2,614 | 608 | 364 | 244 | 72 | 1 |
{-# LANGUAGE Rank2Types #-}
module Main where
import Codec.Sarsi (Event)
import Codec.Sarsi.SBT.Machine (eventProcess)
import qualified Data.List as List
import Data.Machine (ProcessT, autoM, runT_, (<~))
import qualified Data.Text.IO as TextIO
import Sarsi (Topic, getBroker, getTopic)
import qualified Sarsi as Sarsi
import Sarsi.Producer (produce)
import System.Environment (getArgs)
import System.Exit (ExitCode, exitWith)
import System.IO (BufferMode (NoBuffering), hSetBuffering, stdin, stdout)
import System.IO.Machine (byChunk)
import System.Process (StdStream (..), shell, std_in, std_out)
import System.Process.Machine (ProcessMachines, callProcessMachines)
title :: String
title = concat [Sarsi.title, "-sbt"]
-- TODO Contribute to machines-process
mStdOut_ :: ProcessT IO a b -> ProcessMachines a a0 k0 -> IO ()
mStdOut_ mp (_, Just stdOut, _) = runT_ $ mp <~ stdOut
mStdOut_ _ _ = return ()
producer :: Topic -> String -> ProcessT IO Event Event -> IO (ExitCode)
producer t cmd sink = do
(ec, _) <- callProcessMachines byChunk createProc (mStdOut_ pipeline)
return ec
where
pipeline = sink <~ eventProcess t <~ echoText stdout
echoText h = autoM $ (\txt -> TextIO.hPutStr h txt >> return txt)
createProc = (shell cmd) {std_in = Inherit, std_out = CreatePipe}
main :: IO ()
main = do
hSetBuffering stdin NoBuffering
hSetBuffering stdout NoBuffering
args <- getArgs
b <- getBroker
t <- getTopic b "."
ec <- produce t $ producer t $ concat $ List.intersperse " " ("sbt" : "-Dsbt.color=always" : args)
exitWith ec
|
aloiscochard/sarsi
|
sarsi-sbt/Main.hs
|
apache-2.0
| 1,561 | 0 | 12 | 259 | 548 | 301 | 247 | 37 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Graphics.GL.TextBuffer.Types where
import Graphics.GL.Pal
import Data.Sequence (Seq)
import Control.Lens.Extra
import Graphics.GL.Freetype.Types
import Halive.FileListener
import Control.Concurrent.STM
type TextSeq = Seq (Seq Char)
type ColNum = Int
type LineNum = Int
data Cursor = Cursor LineNum ColNum deriving (Eq, Show, Ord)
type Selection = (Cursor, Cursor)
data TextBuffer = TextBuffer
{ bufSelection :: !(Maybe Selection)
, bufColumn :: !Int
, bufText :: !TextSeq
, bufPath :: !(Maybe FilePath)
, bufUndo :: !(Maybe TextBuffer)
, bufDims :: !(Int, Int)
} deriving Show
data TextMetrics = TextMetrics
{ txmCharIndices :: ![GLint]
, txmCharOffsets :: ![(Cursor, V4 GLfloat)]
, txmNumChars :: !Int
} deriving Show
data TextRendererResources = TextRendererResources
{ _trrVAO :: !VertexArrayObject
, _trrIndexBuffer :: !(ArrayBuffer GLint)
, _trrOffsetBuffer :: !(ArrayBuffer (V4 GLfloat))
}
makeLenses ''TextRendererResources
data TextRenderer = TextRenderer
{ _txrFont :: !Font
, _txrRenderResourcesVar :: !(TMVar TextRendererResources)
, _txrRenderChan :: !(TChan TextRenderer)
, _txrCorrectionM44 :: !(M44 GLfloat)
, _txrTextBuffer :: !TextBuffer
, _txrTextMetrics :: !TextMetrics
, _txrDragRoot :: !(Maybe Cursor)
, _txrFileEventListener :: !(Maybe FileEventListener)
, _txrScroll :: !(V2 GLfloat)
, _txrScreenSize :: !(Maybe (V2 Int))
}
makeLenses ''TextRenderer
|
lukexi/text-gl
|
src/Graphics/GL/TextBuffer/Types.hs
|
bsd-2-clause
| 1,734 | 0 | 13 | 471 | 432 | 245 | 187 | 88 | 0 |
module Util(
createStateDir, stateDir
) where
import BasicPrelude
import System.Directory (getHomeDirectory, createDirectoryIfMissing)
createStateDir = stateDir >>= createDirectoryIfMissing False
stateDir = flip mappend "/.iron-tracker" <$> getHomeDirectory
|
mindreader/iron-tracker
|
Util.hs
|
bsd-3-clause
| 264 | 0 | 6 | 31 | 54 | 31 | 23 | 6 | 1 |
module Arhelk.Armenian.Lemma.Adjective(
adjective
) where
import Arhelk.Core.Rule
import Arhelk.Armenian.Lemma.Common
import Arhelk.Armenian.Lemma.Data
import Control.Monad
import Data.Text as T
adjective :: Text -> Rule AdjectiveProperties
adjective w = do
propose adjQuantity GrammarSingle $ do
when (w `endsWith` ["ой", "ый", "ий"]) $ implyNothing
|
Teaspot-Studio/arhelk-armenian
|
src/Arhelk/Armenian/Lemma/Adjective.hs
|
bsd-3-clause
| 372 | 0 | 14 | 55 | 105 | 62 | 43 | 11 | 1 |
{-# LANGUAGE Safe #-}
module Data.Logic.Term (
Term (..), Unbound
) where
import Control.Monad.Predicate.Internal
|
YellPika/tlogic
|
src/Data/Logic/Term.hs
|
bsd-3-clause
| 120 | 0 | 5 | 20 | 27 | 19 | 8 | 4 | 0 |
module Shell.UI.Vty
( start
) where
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import qualified Data.Text as T
import Graphics.Vty
import Graphics.Vty.Widgets.All
import Manipulator
import Mash.Core
import Shell.Core
start :: Render a => Manipulator a -> IO ()
start initState = do
-- UI construction
v <- plainText ""
setNormalAttribute v $ with_back_color current_attr black
f <- vFill ' '
setNormalAttribute f $ with_back_color current_attr bright_black
e <- editWidget
setNormalAttribute e $ with_back_color current_attr black
ui <- (return v <--> return f) <--> return e
setBoxChildSizePolicy ui $ PerChild BoxAuto (BoxFixed 1)
fg <- newFocusGroup
setFocusGroupNextKey fg (KASCII '\0') []
setFocusGroupPrevKey fg (KASCII '\0') []
_ <- addToFocusGroup fg v
_ <- addToFocusGroup fg e
c <- newCollection
switchToMainUI <- addToCollection c ui fg
-- Run a manipulator and a shell.
fromShell <- newTChanIO
toShell <- newTChanIO
_ <- forkIO $ runServer "/tmp/mash_test" $ manipulator initState
_ <- forkIO $ runClient "/tmp/mash_test" $ shell toShell fromShell
-- Vty event handlers
v `onKeyPressed` \_ key _ ->
if key == KASCII ':'
then do
setEditText e ":"
setEditCursorPosition e (0, 1)
focus e
return True
else return False
e `onChange` \l ->
when (l == "\n") $ do
setEditText e ""
focus v
e `onActivate` \this -> do
(cmd:args) <- words <$> init <$> tail <$> getEditText this
atomically $ writeTChan toShell $ CommandInput cmd args
u <- atomically $ readTChan fromShell
case u of
NoUpdate -> return ()
ShowOutput t -> do
setText v $ T.unpack t
setEditText e ""
focus v
ShowError err -> do
setEditText e $ "Error: " ++ err
focus v
Shutdown -> shutdownUi
runUi c defaultContext
|
yuttie/mash
|
Shell/UI/Vty.hs
|
bsd-3-clause
| 2,255 | 0 | 18 | 787 | 654 | 304 | 350 | 60 | 5 |
module BinaryCode where
import Data.Bits hiding (xor)
import Data.Char
import Data.Word
import qualified Data.DList as DL
import Control.Monad.Writer
import Numeric
import qualified Data.List as L
import qualified CommonTypes as CT
import Prelude hiding (div, mod, and)
type BinaryCode = Writer (DL.DList Word16)
binaryCode = DL.toList . execWriter
setM, addM, subM, mulM, divM, modM, shlM, shrM, andM, borM, xorM, ifeM, ifnM, ifgM, ifbM :: Word32 -> Word32 -> BinaryCode()
setM = basicInstrucM set
addM = basicInstrucM add
subM = basicInstrucM sub
mulM = basicInstrucM mul
divM = basicInstrucM div
modM = basicInstrucM mod
shlM = basicInstrucM shl
shrM = basicInstrucM shr
andM = basicInstrucM and
borM = basicInstrucM bor
xorM = basicInstrucM xor
ifeM = basicInstrucM ife
ifnM = basicInstrucM ifn
ifgM = basicInstrucM ifg
ifbM = basicInstrucM ifb
basicInstrucM :: Word16 -> Word32 -> Word32 -> BinaryCode ()
basicInstrucM opcode a b
| nextWordA && nextWordB = tell $ DL.fromList [firstWord, toW16 $ a .>>. 16, toW16 $ b .>>. 16]
| nextWordA = tell $ DL.fromList [firstWord, toW16 $ a .>>. 16]
| nextWordB = tell $ DL.fromList [firstWord, toW16 $ b .>>. 16]
| otherwise = tell $ DL.fromList [firstWord]
where
firstWord = opcode .|. toW16 ((a .&. 0x3f) .<<. 4) .|. toW16 ((b .&. 0x3f) .<<. 10)
nextWordA = a .&. 0xffff0000 /= 0
nextWordB = b .&. 0xffff0000 /= 0
jsrM :: Word32 -> BinaryCode ()
jsrM = nonBasicInstrucM jsr
nonBasicInstrucM :: Word16 -> Word32 -> BinaryCode ()
nonBasicInstrucM opcode a
| nextWordA = tell $ DL.fromList [firstWord, secondWord]
| otherwise = tell $ DL.fromList [firstWord]
where
firstWord = (opcode .<<. 4) .|. toW16 ((a .&. 0x3f) .<<. 10)
secondWord = toW16 $ a .>>. 16
nextWordA = a .&. 0xffff0000 /= 0
opcode :: Num a => CT.Opcode -> a
opcode opcode =
case opcode of
CT.SET -> set
CT.ADD -> add
CT.SUB -> sub
CT.MUL -> mul
CT.DIV -> div
CT.MOD -> mod
CT.SHL -> shl
CT.SHR -> shr
CT.AND -> and
CT.BOR -> bor
CT.XOR -> xor
CT.IFE -> ife
CT.IFN -> ifn
CT.IFG -> ifg
CT.IFB -> ifb
nonBasicOpcode :: Num a => CT.NonBasicOpcode -> a
nonBasicOpcode opcode =
case opcode of
CT.JSR -> jsr
reg :: Num a => CT.RegName -> a
reg name =
case name of
CT.A -> regA
CT.B -> regB
CT.C -> regC
CT.X -> regX
CT.Y -> regY
CT.Z -> regZ
CT.I -> regI
CT.J -> regJ
ramAt :: Word32 -> Word32
ramAt addr = (addr .<<. 16) .|. 0x1e
lit :: Word32 -> Word32
lit i
| i > 0x1f = (i .<<. 16) .|. 0x1f
| otherwise = i + 0x20
set, add, sub, mul, div, mod, shl, shr, and, bor, xor, ife, ifn, ifg, ifb :: Num a => a
set = 0x1
add = 0x2
sub = 0x3
mul = 0x4
div = 0x5
mod = 0x6
shl = 0x7
shr = 0x8
and = 0x9
bor = 0xa
xor = 0xb
ife = 0xc
ifn = 0xd
ifg = 0xe
ifb = 0xf
jsr :: Num a => a
jsr = 0x01
pop, peek, push, sp, pc, o :: Num a => a
pop = 0x18
peek = 0x19
push = 0x1a
sp = 0x1b
pc = 0x1c
o = 0x1d
literalAtNextWord, ramAtNextWord, literalOffset, ramAtRegOffset, ramAtLitPlusRegOffset :: Num a => a
literalAtNextWord = 0x1f
ramAtNextWord = 0x1e
literalOffset = 0x20
ramAtRegOffset = 0x08
ramAtLitPlusRegOffset = 0x10
regA, regB, regC, regX, regY, regZ, regI, regJ :: Num a => a
regA = 0x00
regB = 0x01
regC = 0x02
regX = 0x03
regY = 0x04
regZ = 0x05
regI = 0x06
regJ = 0x07
hex = unwords . L.map (`showHex` "")
bin = unwords . L.map (\w -> showIntAtBase 2 intToDigit w "")
(.>>.), (.<<.) :: Bits a => a -> Int -> a
(.>>.) = shiftR
(.<<.) = shiftL
toW16 :: Integral a => a -> Word16
toW16 = fromIntegral
|
dan-t/dcpu16
|
BinaryCode.hs
|
bsd-3-clause
| 3,765 | 0 | 13 | 1,013 | 1,424 | 801 | 623 | 132 | 15 |
module LongestCommonSubsequence where
import Data.List (intersect, maximumBy, subsequences)
import Data.Ord (comparing)
-- | Find the longest common subsequence of two strings (4 kyu)
-- | Link: https://biturl.io/lcs
-- | My original solution
lcs :: String -> String -> String
lcs [] _ = []
lcs _ [] = []
lcs s@(x:xs) t@(y:ys)
| x == y = x : lcs xs ys
| otherwise = maximumBy (comparing length) [lcs xs t, lcs s ys]
-- | More elegant solution, making use of some interesting List functions
lcs' :: String -> String -> String
lcs' x y =
maximumBy (comparing length) (subsequences x `intersect` subsequences y)
|
Eugleo/Code-Wars
|
src/string-kata/LongestCommonSubsequence.hs
|
bsd-3-clause
| 619 | 0 | 8 | 115 | 209 | 111 | 98 | 12 | 1 |
module Dummy(module Test.Hspec) where
import Test.Hspec
|
mwotton/string-similarity
|
test/dummy.hs
|
bsd-3-clause
| 56 | 0 | 5 | 6 | 17 | 11 | 6 | 2 | 0 |
{-# LANGUAGE FlexibleContexts,
GADTs,
QuasiQuotes #-}
-- |
-- Module : BackEnd.CPP
-- Copyright : (c) Radek Micek 2010
-- License : BSD3
-- Stability : experimental
--
-- Generates C++ code.
--
module BackEnd.CPP
(
generateCode
) where
import Core.Rule
import Data.Array
import Data.Array.Unboxed (UArray)
import qualified Data.Array.Unboxed as U
import Core.DFA (buildDFA, kMinimize, updateReachablePrio, updateWhatMatches)
import Core.Matcher
import Data.List (intersperse)
import Data.Word (Word8)
import Core.UTF8 (convertRule, convertRegex, convertSubst)
import Core.Capture
import Control.Monad.State
import Data.Maybe (catMaybes)
import Core.Regex
import Control.Applicative ((<$>))
import Core.PartialOrder
import BackEnd.Verbatim
-- | Generates C++ code.
generateCode :: Int -> [Rule Char] -> String
generateCode k rules = unlines [
beforeAutomaton
, generateRuleNames rules
, mainPart k rules
, betweenAutomatonAndSubsts
, generatePOrder rules
, capturePart rules
, afterSubsts
]
-- | Generates code for main automaton.
--
-- The automaton consists of:
--
-- * one or more translation tables,
--
-- * transition table for each state,
--
-- * table which rule match for each state,
--
-- * table which maps states to their translation tables,
--
-- * table which maps states to their transition tables,
--
-- * table which contains number of matching rules for each state,
--
-- * table which maps state to the table with rules which match there
--
-- * and table which maps states to highest reachable priority.
--
-- In addition we generate 2 tables for rules: one with priorities
-- and one with information which rules prefer shortest words and which
-- prefer longest.
--
-- First parameter is maximal length of the words which will be matched.
mainPart :: Int -> [Rule Char] -> String
mainPart k rules = unlines $ filter (/= "")
([defK, defCntRules, defShortest, defPriorities] ++
translTabs ++ transitTabs ++ whatMatchesTabs ++
[st2WhatMatchesArr, st2WhatMatchesLen, st2TranslTab
,st2TransitTab, st2ReachablePrio])
where
defK = "#define K " ++ show k
cntRules = length rules
defCntRules = "#define CNT_RULES " ++ show cntRules
lstShortest = map (\(Rule _ _ s _ _) -> s) rules
lstPriorities = map (\(Rule _ p _ _ _) -> p) rules
defShortest = buildTableL lstShortest "bool shortest"
(\sh -> case sh of { Shortest -> "true" ; _ -> "false" })
defPriorities = buildTableL lstPriorities "int priorities"
(\(Pr p) -> show p)
rules' :: [Rule Word8]
rules' = map convertRule rules
dfa = kMinimize k' $ updateReachablePrio
$ updateWhatMatches rules'
$ buildDFA rules'
-- This is because of UTF8.
k' = if maxBound `div` 4 > k then k*4 else maxBound
matcher = toCompAlphabetMatcher 4 {- alphabet partitions -} dfa
translTabs = map createTab $ assocs $ camTranslationTabs matcher
where
createTab (i, arr) = buildTableU arr ("unsigned char mTranslTab"
++ show i) show
transitTabs = map createTab $ assocs $ camTransitionTabs matcher
where
createTab (st, arr) = buildTableU arr ("StateNum mTransitTab"
++ show st) show
whatMatchesTabs = map createTab $ assocs $ camWhatMatches matcher
where
-- No rule matches.
createTab (_, []) = ""
createTab (st, rs) = buildTableL rs ("RuNum mWhatMatches" ++ show st)
(\(RuN r) -> show r)
st2WhatMatchesArr = buildTableL (assocs $ camWhatMatches matcher)
"RuNum * mSt2WhatMatchesArr"
(\(st, whatMatches) ->
if null whatMatches
then "NULL"
else "mWhatMatches" ++ show st)
st2WhatMatchesLen = buildTable (camWhatMatches matcher)
"size_t mSt2WhatMatchesLength"
(show . length)
st2TranslTab = buildTableU (camSymbolTranslation matcher)
"unsigned char * mSt2TranslTab"
(("mTranslTab" ++) . show)
st2TransitTab = buildTableL (indices $ camTransitionTabs matcher)
"StateNum * mSt2TransitTab"
(("mTransitTab" ++) . show)
st2ReachablePrio = buildTable (camReachablePrio matcher)
"int mSt2ReachablePrio"
(\p -> case p of Just (Pr v) -> show v
Nothing -> "-1")
-- ---------------------------------------------------------------------------
-- Creation of substitution and capturing subwords
-- | Generates code of the function @computeSubst@ which gets rule number
-- and output stream and writes substitution into given output stream.
capturePart :: [Rule Char] -> String
capturePart rules = unlines (map (uncurry captureOneRule) numberedRules ++
substFunc)
where
numberedRules = zip [RuN 0..] rules
substFunc = ["void computeSubst(RuNum rule, ostream &output) {"
,"switch(rule) {"
] ++
map (\(RuN n, _) -> "case " ++ show n ++ ": subst_" ++
show n ++ "(output); break;")
numberedRules ++
["}", "}"]
data GenerateI = GMatches (Regex Char Yes)
| GSplitWord (Regex Char Yes)
(Regex Char Yes)
-- | Describes function which will be generated
-- (which rule, function number, type of the function).
type GenFunc = (RuNum, Int, GenerateI)
-- | Generates function @subst_i@ where @i@ is the number of the rule
-- which writes substitution for the rule @i@ into output stream.
captureOneRule :: RuNum -> Rule Char -> String
captureOneRule ruNum (Rule _ _ _prefLen regex subst)
= unlines [generatedFunctions, generatedMainFunction]
where
-- Functions for regex matching.
generatedFunctions = unlines $ map generateFunctionCode funcsToGen
-- Function which writes substitution to the output stream.
generatedMainFunction = unlines [header, decls, bodyCode, substCode, "}"]
where
header = "void subst_" ++ show r ++ "(ostream &output) {"
where
(RuN r) = ruNum
decls = unlines ["size_t wStart0=0;"
,"size_t wLen0=capVect.size();"
,captDecls]
captDecls = unlines $
map (\i -> let s = show i
in if i /= 0
then "size_t cStart" ++ s ++ "=0;" ++
"size_t cLen" ++ s ++ "=0;"
else "size_t cStart0=wStart0;" ++
"size_t cLen0=wLen0;") $
capturesInSubst subst'
bodyCode = fst $ runState (generateCaptLangCode captLangCode)
(ruNum, 0)
substCode = generateSubstCode subst'
funcsToGen :: [GenFunc]
funcsToGen = fst $ runState (functionsToGen captLangCode) 0
functionsToGen :: [CaptLang Char] -> State Int [GenFunc]
functionsToGen [] = return []
functionsToGen (IfNonEmpty _w as:xs)
= do fs1 <- functionsToGen as
fs2 <- functionsToGen xs
return (fs1 ++ fs2)
functionsToGen (IfMatches _w re as bs:xs)
= do funcId <- succ <$> get
put funcId
fs1 <- functionsToGen as
fs2 <- functionsToGen bs
fs3 <- functionsToGen xs
return ((ruNum, funcId, GMatches re) : fs1 ++ fs2 ++ fs3)
functionsToGen (SplitWord _w re1 re2 (_wOut1, _wOut2):xs)
= do funcId <- succ <$> get
put funcId
fs <- functionsToGen xs
return ((ruNum, funcId, GSplitWord re1 re2) : fs)
functionsToGen (CaptureWord _w _i:xs) = functionsToGen xs
-- Code for capture extraction.
captLangCode = fst $ runState (genCapture 0 regex') 0 {- lastRef -}
-- Regular expression without unused captures.
regex' = rmCaptures regex
where
rmCaptures :: Regex Char c -> Regex Char c
rmCaptures Epsilon = Epsilon
rmCaptures r@(CharClass _) = r
rmCaptures (Or a b) = rmCaptures a `Or` rmCaptures b
rmCaptures (And a b) = rmCaptures a `And` rmCaptures b
rmCaptures (Concat a b) = rmCaptures a `Concat` rmCaptures b
rmCaptures (RepeatU lo a) = RepeatU lo (rmCaptures a)
rmCaptures (Repeat lo hi a) = Repeat lo hi (rmCaptures a)
rmCaptures r@(Not _) = r
rmCaptures (Capture i a)
| i `elem` usedCaptures = Capture i (rmCaptures a)
| otherwise = toRegexWithCaptures $ rmCaptures a
usedCaptures = capturesInSubst subst
-- Substitution without captures not in regular expression.
subst' = Subst $ rmCaptures terms
where
rmCaptures [] = []
rmCaptures (t@(TCapture i):ts)
| i `elem` definedCaptures = t:rmCaptures ts
| otherwise = rmCaptures ts
rmCaptures (t@(TConst _):ts) = t:rmCaptures ts
(Subst terms) = subst
definedCaptures = 0:listCaptures regex
-- | Generates functions for splitting words and matching words.
-- Tables for automata are generated too.
--
-- For actual matching these functions call @genericSplitWord@ and
-- @genericMatches@.
--
-- Each automaton consists of
--
-- * one translation table (for symbol translation),
--
-- * transition tables (one for each state),
--
-- * table which maps states to their transition tables
--
-- * and table which for each state contains whether automaton matches.
generateFunctionCode :: GenFunc -> String
generateFunctionCode (RuN rn, n, genI)
= case genI of
GMatches re
-> unlines [generateAutomaton (convertRegex re) "ms"
,"bool matches_" ++ show rn ++ '_' : show n ++
paramList ["size_t start", "size_t len"] ++
"{ return genericMatches" ++
paramList ["start", "len"
,tabName "ms" "translTab"
,tabName "ms" "st2Match"
,tabName "ms" "st2TransitTab"
] ++
"; }"]
GSplitWord re1 re2
-> unlines [generateAutomaton (convertRegex re1) "sw1"
,generateAutomaton (reverseRegex $ convertRegex re2) "sw2"
,"void splitWord_" ++ show rn ++ '_' : show n ++
paramList ["size_t start", "size_t len"
,"size_t *outStart1", "size_t *outLen1"
,"size_t *outStart2", "size_t *outLen2"] ++
"{ genericSplitWord" ++
paramList ["start", "len"
,"outStart1", "outLen1", "outStart2", "outLen2"
,tabName "sw1" "translTab"
,tabName "sw1" "st2Match"
,tabName "sw1" "st2TransitTab"
,tabName "sw2" "translTab"
,tabName "sw2" "st2Match"
,tabName "sw2" "st2TransitTab"
] ++
"; }"]
where
paramList xs = "(" ++ concat (intersperse ", " xs) ++ ")"
tabName name desc = "cap_" ++ show rn ++ '_' : show n ++ '_' : name ++
'_' : desc
generateAutomaton :: Regex Word8 Yes -> String -> String
generateAutomaton regex name = unlines (translTab : transitTabs ++
[st2Match, st2TransitTab])
where
translTab = buildTableU (camTranslationTabs matcher!0)
("unsigned char " ++ tabName' "translTab") show
transitTabs = map createTab $ assocs $ camTransitionTabs matcher
where
createTab (st, arr) = buildTableU arr
("StateNum " ++ tabName' "transitTab"
++ show st) show
st2Match = buildTableL (elems $ camWhatMatches matcher)
("bool " ++ tabName' "st2Match")
(\matches -> if null matches then "false" else "true")
st2TransitTab = buildTableL (indices $ camTransitionTabs matcher)
("StateNum * " ++ tabName' "st2TransitTab")
((tabName' "transitTab" ++) . show)
tabName' = tabName name
matcher = toCompAlphabetMatcher 1 {- alphabet partitions -} dfa
dfa = kMinimize maxBound $ buildDFA [rule]
rule = Rule "" (Pr 1) Shortest regex (Subst [])
-- | Generates C code for capturing subwords of matched word
-- from abstract code.
generateCaptLangCode :: [CaptLang Char]
-> State (RuNum, Int) String
generateCaptLangCode [] = return ""
generateCaptLangCode (IfNonEmpty w as:xs)
= do c1 <- generateCaptLangCode as
c2 <- generateCaptLangCode xs
return $ unlines ["if(wLen" ++ show w ++ " != 0) {", c1, "}", c2]
generateCaptLangCode (IfMatches w _re as bs:xs)
= do (RuN rule, lastId) <- get
let newId = succ lastId
put (RuN rule, newId)
c1 <- generateCaptLangCode as
c2 <- generateCaptLangCode bs
c3 <- generateCaptLangCode xs
return $ unlines ["if(matches_" ++ show rule ++ '_' : show newId ++
"(wStart" ++ show w ++ ", wLen" ++ show w ++ ")) {"
,c1, "} else {", c2, "}", c3
]
generateCaptLangCode (SplitWord w _re1 _re2 (wOut1, wOut2):xs)
= do (RuN rule, lastId) <- get
let newId = succ lastId
put (RuN rule, newId)
c <- generateCaptLangCode xs
return $ unlines ["size_t wStart" ++ show wOut1 ++ ";"
,"size_t wLen" ++ show wOut1 ++ ";"
,"size_t wStart" ++ show wOut2 ++ ";"
,"size_t wLen" ++ show wOut2 ++ ";"
,"splitWord_" ++ show rule ++ '_' : show newId ++
"(wStart" ++ show w ++ ", wLen" ++ show w ++
", &wStart" ++ show wOut1 ++
", &wLen" ++ show wOut1 ++
", &wStart" ++ show wOut2 ++
", &wLen" ++ show wOut2 ++ ");"
,c
]
generateCaptLangCode (CaptureWord w i:xs)
= do c <- generateCaptLangCode xs
return $ unlines ["cStart" ++ show i ++ " = wStart" ++ show w ++ ";"
,"cLen" ++ show i ++ " = wLen" ++ show w ++ ";"
,c
]
-- | Generates code which wites substitution into output stream called
-- @output@.
generateSubstCode :: Subst Char -> String
generateSubstCode subst = unlines $ map gen terms
where
gen (TCapture i) = "for(size_t i=cStart" ++ show i ++ "; i < cStart" ++
show i ++ " + cLen" ++ show i ++ "; ++i) " ++
"output_subst(output, capVect[i]);"
gen (TConst xs) = unlines $
map (\x -> "output_subst(output, " ++ show x ++ ");") xs
(Subst terms) = convertSubst subst
-- ---------------------------------------------------------------------------
-- Rule names
-- | Generates array with names of the rules.
generateRuleNames :: [Rule Char] -> String
generateRuleNames rules = buildTableL (map toName rules)
("const char * rule2Name")
show
where
toName (Rule name _ _ _ _) = name
-- ---------------------------------------------------------------------------
-- Partial order
-- | Generates function which setups initial partial order.
generatePOrder :: [Rule Char] -> String
generatePOrder rules = unlines ["void setupPartialOrder(PartialOrder *po) {"
,code
,"}"
]
where
-- Actual code which setups partial order.
code = unlines $ map eachRule $ assocs $ fromRules rules
eachRule (RuN rn, bitmask)
= unlines $ map (\bit -> "po->ord[" ++ show rn ++
"][" ++ show bit ++ "] = true;")
$ listBits bitmask 0
listBits :: Integer -> Int -> [Int]
listBits 0 _ = []
listBits i bitNum
| m /= 0 = bitNum : listBits i' (succ bitNum)
| otherwise = listBits i' (succ bitNum)
where
(i', m) = i `divMod` 2
-- ---------------------------------------------------------------------------
-- Static parts of the code
-- | Code.
beforeAutomaton :: String
beforeAutomaton = [$verbatim|
// Flags:
// #define SELECT_FIRST
// #define NO_CONTEXT
#include <bitset>
#include <iostream>
#include <list>
#include <vector>
#include <fstream>
#include <cassert>
#include <climits>
using namespace std;
typedef size_t RuNum;
typedef size_t Length;
typedef size_t StateNum;
#ifndef SELECT_FIRST
#ifdef NO_CONTEXT
#define SHOW_PREV_CHARS 0
#else
#define SHOW_PREV_CHARS 30
#endif
// Pocet zpracovanych pismen, ktere si system uchovava. Tato jsou pouzita
#define CNT_MEMO_CHARS 32
unsigned char memoChars[CNT_MEMO_CHARS];
Length nextMemoChar = 0; // Kam prijde dalsi znak k uchovani.
// Kdyz je nMemoChars == CNT_MEMO_CHARS, tak je to
// take index nejstarsiho znaku.
Length nMemoChars = 0; // Kolik znaku skutecne uchovavame.
#endif
|]
-- | Code.
betweenAutomatonAndSubsts :: String
betweenAutomatonAndSubsts = [$verbatim|
// ---------------------------------------------------------------------------
// Partial order of the rules
class PartialOrder {
public:
bitset<CNT_RULES> ord[CNT_RULES];
PartialOrder() {
for(int rule = 0; rule < CNT_RULES; ++rule) {
ord[rule].reset();
}
}
bool isHigher(const RuNum lo, const RuNum hi) const {
return ord[lo][hi]; // If the bit is set then hi is higher rule.
}
void mkHigher(RuNum lo, RuNum hi) {
ord[lo][hi] = true; // Rule "hi" is higher than "lo".
ord[lo] |= ord[hi]; // Rules higher than "hi" are higher than "lo".
for(int rule = 0; rule < CNT_RULES; ++rule) {
// Rule "rule" is lower than "lo".
if(ord[rule][lo]) {
// Rules higher than "lo" are higher than "rule"
// (transitivity).
ord[rule] |= ord[lo];
}
}
}
bitset<CNT_RULES> getHigher(RuNum rule) const {
return ord[rule]; // Rules higher than "rule":.
}
void show() {
for(size_t rule = 0; rule < CNT_RULES; ++rule) {
cout << "higher than rule " << rule2Name[rule] << ":";
bool noHigher = true;
for(size_t r = 0; r < CNT_RULES; ++r) {
// r je vyssi nez rule
if(!isHigher(rule, r))
continue;
// neexistuje nic vyssiho nez rule, co je nizsi nez r
size_t rr = 0;
for(; rr < CNT_RULES; ++rr) {
// r nepokryva rule, protoze je mezi nima rr
if(isHigher(rule, rr) && isHigher(rr, r))
break;
}
// r pokryva rule
if(rr == CNT_RULES) {
if(noHigher) {
cout << " ";
noHigher = false;
}
else
cout << ", ";
cout << rule2Name[r];
}
}
// Each rule has its line.
cout << endl;
}
}
};
void separator() {
cout << "---------------------------------------------------------------";
cout << "---------" << endl;
}
#ifndef SELECT_FIRST
// zapamatuje si znak
void memo_char(unsigned char c) {
memoChars[nextMemoChar] = c;
nextMemoChar = (nextMemoChar + 1) % CNT_MEMO_CHARS;
if(nMemoChars != CNT_MEMO_CHARS) /* nMemoChars < CNT_MEMO_CHARS */
++nMemoChars;
}
bool memoizeSubstOutput = false;
#endif
// vystup pro substituci; lze nastavit, jestli znaky maji byt uchovany
void output_subst(ostream &output, unsigned char c) {
#ifndef SELECT_FIRST
if(memoizeSubstOutput)
memo_char(c);
#endif
output.put(c);
}
// Vektor obsahuje znaky slova, co bylo namatchovano (delka az K*4).
// Pouzivaji ho funkce genericMatches, genericSplitWord, vygenerovane funkce
// subst_i (kde i je cislo pravidla). Vektor lze naplnit metodou
// putIntoCapVect.
vector<unsigned char> capVect;
// Pouzito funkci genericSplitWord (detaily pospany tam).
bitset<K*4+1> capBools;
bool genericMatches(size_t start, size_t len,
unsigned char *translTab, bool *st2Matches, StateNum **transitTab) {
StateNum state = 0;
for(size_t i = start; i < start + len; ++i) {
int translatedSymb = translTab[capVect[i]];
state = transitTab[state][translatedSymb];
}
return st2Matches[state];
}
void genericSplitWord(size_t start, size_t len,
size_t *outStart1, size_t *outLen1,
size_t *outStart2, size_t *outLen2,
unsigned char *translTab1, bool *st2Matches1, StateNum **transitTab1,
unsigned char *translTab2, bool *st2Matches2, StateNum **transitTab2){
// capBools[i] = whether first automaton matched after it read i
//characters
capBools.reset();
// first automaton
StateNum state = 0;
size_t nProcChars = 0;
capBools[nProcChars] = st2Matches1[state];
while(nProcChars < len) {
int translatedSymb = translTab1[capVect[nProcChars]];
state = transitTab1[state][translatedSymb];
capBools[++nProcChars] = st2Matches1[state];
}
// second automaton
state = 0;
if(capBools[len] && st2Matches2[state]) {
*outStart1 = start;
*outLen1 = len;
*outStart2 = start + len;
*outLen2 = 0;
return;
}
nProcChars = 0;
while(nProcChars < len) {
++nProcChars;
int translatedSymb = translTab2[capVect[start + len - nProcChars]];
state = transitTab2[state][translatedSymb];
if(capBools[len - nProcChars] && st2Matches2[state]) {
*outStart1 = start;
*outLen1 = len - nProcChars;
*outStart2 = start + len - nProcChars;
*outLen2 = nProcChars;
return;
}
}
assert(0);
}
|]
-- | Code.
afterSubsts :: String
afterSubsts = [$verbatim|
class Character;
class Alternative;
ifstream input;
ofstream output;
Character *text;
// na zacatku jsou vsechny alternativy v original
// 0. pismena, kde nezacina zadne slovo preskocim (vypisi na vystup)
// 1. zkopiruji original do toDecide
// 2. rozhodnu vsechny alternativy;
// 3. zkonstruuji nahradu pro kazde z vybranych slov
// 4. pokud je mozne vybrat alespon 2 ruzna slova, pak je musi vybrat uzivatel;
// uzivatel muze take rict, ze chce zachovat puvodni usporadani
// 5. pokud neni mozne vybrat vice ruznych slov, tak vyberu to jedine
// automaticky a necham si usporadani, co mam
// 6. az je slovo vybrano, zapisu pismena pred a nahradu na vystup;
// z textu odstranim vsechna pismena az po posledni pismeno vybraneho slova
// (posledni take odstranim, ale to za nim uz ne)
// 7. pokud si uzivatel nevybral, ze chce ponechat puvodni usporadani,
// pak orig uvolnim, z decided odstranim usporadani, co nemaji vybrane slovo
// a zbyla usporadani presunu do original (musim odebrat zpracovana pismena)
// 8. pokud uzivatel chce ponechat puvodni usporadani: odstranim decided,
// z originalnich alternativ si necham jen usporadani (tedy znaky
// a s nimi i vybrana slova odstranim)
// 9. toto opakuji, dokud nedojdu na konec textu
//
// Ve vsech usporadanich dojdou slova najednou.
Alternative *original;
Alternative *toDecide;
Alternative *decided;
// Kolikrat bylo na vyber vic nez jedno slovo.
size_t numOfConflicts;
// ---------------------------------------------------------------------------
// Words which start at fixed position and match fixed rule.
class Words {
public:
RuNum rule;
list<Length> lens; // Can be empty.
Words(RuNum rule, Length len) {
this->rule = rule;
lens.push_front(len);
}
void addLength(Length len) {
if(!shortest[rule]) // Only insert when rule is non-shortest.
lens.push_front(len);
}
};
void vectorWhatMatches(const list<Words> &ws, bitset<CNT_RULES> &whatMatches) {
list<Words>::const_iterator it = ws.begin();
while(it != ws.end()) {
if(!it->lens.empty()) {
whatMatches[it->rule] = true;
}
++it;
}
}
bool isMaximal(const PartialOrder &po, const bitset<CNT_RULES> &whatMatches,
RuNum rule) {
bitset<CNT_RULES> cmp = po.getHigher(rule) & whatMatches;
return cmp.none();
}
void selectMaxWord(const list<Words> &ws, const PartialOrder &po,
RuNum *rule, Length *len, bool *selected) {
bitset<CNT_RULES> whatMatches;
vectorWhatMatches(ws, whatMatches);
// Select first rule which is not diff and is not smaller than any other
// rule which match here.
list<Words>::const_iterator it = ws.begin();
while(it != ws.end()) {
if(!it->lens.empty()) {
if(isMaximal(po, whatMatches, it->rule)) {
*selected = true;
*rule = it->rule;
*len = it->lens.front();
return;
}
}
++it;
}
*selected = false;
}
void selectMaxWordAndHigherThan(const list<Words> &ws, const PartialOrder &po,
const RuNum lower, RuNum *rule, Length *len, bool *selected) {
bitset<CNT_RULES> whatMatches;
vectorWhatMatches(ws, whatMatches);
// Select first rule which is not diff and is not smaller than any other
// rule which match here.
list<Words>::const_iterator it = ws.begin();
while(it != ws.end()) {
if(!it->lens.empty()) {
if(po.isHigher(lower, it->rule)
&& isMaximal(po, whatMatches, it->rule)) {
*selected = true;
*rule = it->rule;
*len = it->lens.front();
return;
}
}
++it;
}
*selected = false;
}
// ---------------------------------------------------------------------------
// Automaton for searching for words
// First byte of code point in UTF-8 encoding.
bool firstUTF8Byte(unsigned char c) {
return (c < 128 || (c&224) == 192 || (c&240) == 224 || (c&248) == 240);
}
class Automaton {
public:
StateNum state;
Length realLen;
Length unicodeLen;
int maxMatchedPrio;
Automaton() {
state = 0;
realLen = 0;
unicodeLen = 0;
maxMatchedPrio = -1;
}
void next(unsigned char c, list<Words> &toUpdate) {
realLen++;
// First byte of UTF-8 sequence.
if(firstUTF8Byte(c))
++unicodeLen;
unsigned char translated = mSt2TranslTab[state][c];
state = mSt2TransitTab[state][translated];
// Update what matches.
for(size_t i = 0; i < mSt2WhatMatchesLength[state]; ++i) {
RuNum rule = mSt2WhatMatchesArr[state][i];
list<Words>::iterator it = toUpdate.begin();
while(it != toUpdate.end()) {
if(it->rule == rule)
break;
++it;
}
// Rule wasn't found in the list, we add it.
if(it == toUpdate.end())
toUpdate.push_front(Words(rule, realLen));
// Rule was found, we add only new length.
else
it->addLength(realLen);
if(priorities[rule] > maxMatchedPrio)
maxMatchedPrio = priorities[rule];
}
// upravit to nejvyssi, co matchovalo
}
bool shouldReadNextCharacter() {
if(realLen >= 4*K || unicodeLen >= K
|| maxMatchedPrio > mSt2ReachablePrio[state])
return false;
return true;
}
};
// ---------------------------------------------------------------------------
//
enum CharacterState {
S_UNKNOWN,
S_READ,
S_WORDS_FOUND,
S_EOF
};
class Character {
public:
// S_READ - content was set but variable words is empty
// WORDS_FOUND - content was set and words are filled
// S_UNKNOWN, S_EOF - next is NULL; content and words are not set
CharacterState state;
unsigned char content;
list<Words> words;
Character *next;
Character() {
state = S_UNKNOWN;
next = NULL;
}
// The state after this is different from S_UNKNOWN.
int read() {
int c;
switch(state) {
case S_EOF:
return -1;
case S_UNKNOWN:
c = input.get();
if(!input.good()) {
state = S_EOF;
return -1;
}
content = c;
state = S_READ;
next = new Character;
default:
return content;
}
}
// The state after this is S_WORDS_FOUND or S_EOF.
void findWords() {
read(); // ensure that current state is not S_UNKNOWN
if(state == S_WORDS_FOUND || state == S_EOF)
return;
// current state must be S_READ
state = S_WORDS_FOUND;
Character *toRead = this;
int c;
Automaton dfa;
while(dfa.shouldReadNextCharacter()) {
c = toRead->read();
if(c == -1) // No next character available.
return;
dfa.next(c, words);
toRead = toRead->next;
}
}
};
class CharacterAlt {
public:
// If true then words are empty and parent has any state and next is NULL.
// If false then parent has state S_EOF, words are empty and next is NULL
// or parent has state S_WORDS_FOUND and variable words contains words
// from parent and next is not NULL.
bool unknown; // Only last node can be unknown.
Character *parent;
list<Words> words;
CharacterAlt *next;
RuNum selRule;
Length selLength; // Zero when nothing selected.
CharacterAlt(Character *par) {
unknown = true;
parent = par;
next = NULL;
selLength = 0;
}
CharacterAlt(const CharacterAlt &a) {
unknown = a.unknown;
parent = a.parent;
words = a.words;
next = NULL;
selRule = a.selRule;
selLength = a.selLength;
}
// After this unknown = false and state of the parent is S_WORDS_FOUND
// or S_EOF.
void read() {
if(!unknown)
return;
unknown = false;
parent->findWords();
if(parent->state == S_WORDS_FOUND) {
words = parent->words;
next = new CharacterAlt(parent->next);
}
// else parent->state == S_EOF
}
};
class Alternative {
public:
PartialOrder ord;
CharacterAlt *chars;
Alternative *next;
Alternative(Character *parentCharacter) {
chars = new CharacterAlt(parentCharacter);
next = NULL;
}
Alternative(const Alternative &a) {
ord = a.ord;
chars = NULL;
next = NULL;
CharacterAlt **toModify = &chars; // where the duplicate will be stored
CharacterAlt *toDup = a.chars;
while(toDup) {
*toModify = new CharacterAlt(*toDup);
toModify = &((*toModify)->next);
toDup = toDup->next;
}
}
~Alternative() {
// Remove characters.
while(chars != NULL) {
CharacterAlt *toDelete = chars;
chars = chars->next;
delete toDelete;
}
}
void selectWord() {
CharacterAlt *curWord;
CharacterAlt *c = chars;
bool selected = false;
RuNum r;
Length l;
size_t fromStart = 0;
// Najdeme prvni slovo (to by se melo najit hned na prvni pozici).
while(!selected) {
c->read();
curWord = c;
selectMaxWord(curWord->words, ord, &r, &l, &selected);
c = c->next;
++fromStart;
}
size_t toCheck = l - 1;
// Nyni je prvni slovo nalezeno. Najdeme slovo, co se neprekryva
// s vyssim.
while(toCheck > 0) {
c->read();
selectMaxWordAndHigherThan(c->words, ord, r, &r, &l, &selected);
// Higher word was selected.
if(selected) {
curWord = c;
toCheck = l;
}
--toCheck;
c = c->next;
++fromStart;
}
// Nyni c ukazuje za posledni znak toho slova a fromStart obsahuje
// pocet znaku, ktere je treba proverit (resp. pokud znaky indexujeme
// od nuly, tak fromStart je index prvniho znaku za vybranym slovem).
//
// Tedy slovo zacina: fromStart - l
size_t wordStart = fromStart - l;
// Udelame slovo vyssi nez vse, co se s nim prekryva.
c = chars;
for(size_t n = 0; n < fromStart; ++n, c = c->next) {
list<Words>::const_iterator it = c->words.begin();
while(it != c->words.end()) {
// Slovo neni ostre nizsi (a neni to, co mam vybrane).
if(r != it->rule && !it->lens.empty()
&& !ord.isHigher(it->rule, r)) {
Length longest = it->lens.front();
// Slovo se prekryva s vybranym (konci za jeho zacatkem).
if(n + longest > wordStart) {
Alternative *dup = new Alternative(*this);
dup->ord.mkHigher(r, it->rule);
dup->next = toDecide;
toDecide = dup;
ord.mkHigher(it->rule, r);
}
}
++it;
}
}
// Nyni odstranime slova, co se stim mym prekryvaji.
// Pred ostranim jen slova, co do meho zasahuji.
// Uvnitr odstranim vsechna slova.
// Slova co zacinaji drive a prekryvaji se.
c = chars;
size_t n = 0;
Length maxLength = wordStart; // Nejvyssi delka, co se neprekryva.
for(; n < wordStart; ++n, --maxLength, c = c->next) {
list<Words>::iterator it = c->words.begin();
while(it != c->words.end()) {
list<Length>::iterator lit = it->lens.begin();
// Odstranime delky, co jsou ostre vyssi nez maxLength.
while(lit != it->lens.end() && *lit > maxLength) {
list<Length>::iterator toDelete = lit;
++lit;
it->lens.erase(toDelete);
}
++it;
}
}
// Nastavim vybrane slovo.
c->selRule = r;
c->selLength = l;
// Slova, ktera zacinaji uvnitr vybraneho.
for(; n < fromStart; ++n, c = c->next) {
c->words.clear();
}
}
bool isFirstWordSelected() {
CharacterAlt *c = chars;
while(c->selLength == 0) {
c->read();
// If there are any words return false.
list<Words>::const_iterator it = c->words.begin();
while(it != c->words.end()) {
if(!it->lens.empty())
return false;
++it;
}
c = c->next;
}
return true;
}
void decide() {
while(!isFirstWordSelected())
selectWord();
this->next = decided;
decided = this;
}
};
class SelWord {
public:
Character *c;
Length nCharsBefore;
RuNum rule;
Length len;
SelWord(Character *c, RuNum r, Length l, Length nCharsBefore) {
this->c = c;
this->rule = r;
this->len = l;
this->nCharsBefore = nCharsBefore;
}
void putIntoCapVect() const {
capVect.clear();
Character *cur = c;
for(size_t i = 0; i < len; ++i, cur = cur->next) {
capVect.push_back(cur->content);
}
}
};
void removeCharFromText() {
Character *toDelete = text;
text = text->next;
delete toDelete;
}
bool processWord() {
// After this there will start word at first character.
while(true) {
text->findWords();
if(text->state == S_EOF)
return false;
if(text->words.empty()) {
output.put(text->content);
#ifndef SELECT_FIRST
// Memoize character.
memo_char(text->content);
#endif
// Remove character from the text.
Character *toSkip = text;
text = toSkip->next;
delete toSkip;
// Remove character from each alternative.
Alternative *a = original;
while(a) {
// Last character in the alternative.
if(a->chars->unknown)
a->chars->parent = text;
else {
CharacterAlt *toDelete = a->chars;
a->chars = a->chars->next;
delete toDelete;
}
a = a->next;
}
}
else {
break;
}
}
Alternative *a;
#ifndef SELECT_FIRST
// Copy alternatives to toDecide.
a = original;
Alternative **dest = &toDecide;
while(a) {
*dest = new Alternative(*a);
a = a->next;
dest = &((*dest)->next);
}
#else
// Move alternatives to toDecide;
toDecide = original;
original = NULL;
#endif
// Decide each alternative.
while(toDecide) {
a = toDecide;
toDecide = toDecide->next;
a->decide();
}
// Collect words which can be selected into a list (each word once).
a = decided;
list<SelWord> selWords;
while(a) {
CharacterAlt *charAlt = a->chars;
// Find character where selected word starts.
Length nCharsBefore = 0;
while(charAlt->selLength == 0) {
charAlt = charAlt->next;
++nCharsBefore;
}
// Insert selected word if not already there.
list<SelWord>::const_iterator wit = selWords.begin();
while(wit != selWords.end()) {
// Word found.
if(wit->c == charAlt->parent && wit->len == charAlt->selLength
&& wit->rule == charAlt->selRule)
break;
++wit;
}
// Word not found, add it.
if(wit == selWords.end()) {
selWords.push_back(SelWord(charAlt->parent, charAlt->selRule,
charAlt->selLength, nCharsBefore));
}
a = a->next;
}
bool originalAlternatives = false;
int selectedNum = 1; // musi byt <= size a >= 1 -- cislovano od 1
list<SelWord>::const_iterator sit;
#ifndef SELECT_FIRST
// Vice nez jedno slovo, nechame uzivatele vybrat.
if(selWords.size() > 1) {
separator();
cout << "Select 1 of " << selWords.size() << " words:" << endl << endl;
// Vypiseme vsechny moznosti.
sit = selWords.begin();
int wordNumber = 1;
while(sit != selWords.end()) {
sit->putIntoCapVect();
cout << wordNumber << ". rule: " << rule2Name[sit->rule] << endl;
cout << " old: ";
for(size_t i = 0; i < sit->len; ++i)
cout << capVect[i];
cout << endl;
cout << " new: ";
computeSubst(sit->rule, cout);
cout << endl;
cout << " ctx: ";
// ukazat SHOW_PREV_CHARS znaku pred nahradou
size_t fromMemoChars = 0; // kolik znaku potrebuji z memoChars
if(sit->nCharsBefore < SHOW_PREV_CHARS)
fromMemoChars = SHOW_PREV_CHARS - sit->nCharsBefore;
if(fromMemoChars > nMemoChars)
fromMemoChars = nMemoChars;
// priznak zda-li byl uz nalezen zacatek UTF8 sekvence
bool utf8Start = false;
// vypisi znaky z memoChars
size_t written = 0;
size_t memoIdx = nextMemoChar + CNT_MEMO_CHARS - fromMemoChars;
for(; written < fromMemoChars; ++written, ++memoIdx) {
unsigned char toWrite = memoChars[memoIdx % CNT_MEMO_CHARS];
if(!utf8Start)
utf8Start = firstUTF8Byte(toWrite);
// Vypisujeme pouze pokud byl nalezen zacatek UTF8 sekvence -
// pak vypiseme uplne vsechny znaky.
if(utf8Start)
cout << toWrite;
}
// kolik znaku pred vybranym slovem preskocim
size_t skipBeforeSelWord = 0;
if(sit->nCharsBefore > SHOW_PREV_CHARS)
skipBeforeSelWord = sit->nCharsBefore - SHOW_PREV_CHARS;
// preskocim znaky pred
Character *c = text;
written = 0;
for(; written < skipBeforeSelWord; ++written, c = c->next) ;
// vypisu znaky pred
for(; written < sit->nCharsBefore; ++written, c = c->next) {
unsigned char toWrite = c->content;
if(!utf8Start)
utf8Start = firstUTF8Byte(toWrite);
// Vypisujeme pouze pokud byl nalezen zacatek UTF8 sekvence -
// pak vypiseme uplne vsechny znaky.
if(utf8Start)
cout << toWrite;
}
computeSubst(sit->rule, cout);
cout << endl << endl;
++sit;
++wordNumber;
}
// Nechame uzivatele vybrat.
while(true) {
cout << "select word: ";
cin >> selectedNum;
if(cin.eof())
return false;
if(cin.good()) {
if(selectedNum < 0) {
originalAlternatives = false;
selectedNum = -selectedNum;
}
else {
originalAlternatives = true;
}
// There is no such alternative.
if(selectedNum == 0 || selectedNum > (int)selWords.size())
continue;
// OK.
break;
}
else {
cin.clear();
std::cin.ignore(INT_MAX,'\n');
}
}
}
#endif
// Zapocitej konflikt.
numOfConflicts += (selWords.size() > 1);
sit = selWords.begin();
for(int i = 1; i < selectedNum; ++i, ++sit) ;
SelWord selectedWord(*sit);
{
// Write characters before selected word.
for(size_t nRemove = selectedWord.nCharsBefore; nRemove > 0; --nRemove) {
output.put(text->content);
#ifndef SELECT_FIRST
memo_char(text->content);
#endif
removeCharFromText();
}
// Write substitution.
#ifndef SELECT_FIRST
memoizeSubstOutput = true;
#endif
selectedWord.putIntoCapVect();
computeSubst(selectedWord.rule, output);
#ifndef SELECT_FIRST
memoizeSubstOutput = false;
#endif
// Skip selected word.
for(size_t nRemove = selectedWord.len; nRemove > 0; --nRemove)
removeCharFromText();
}
// User wants new alternatives.
if(!originalAlternatives) {
#ifndef SELECT_FIRST
// Remove alternatives from original.
while(original) {
a = original;
original = original->next;
delete a;
}
#endif
// Remove alternatives with different word, remaining alternatives
// are moved to original.
while(decided) {
CharacterAlt *charAlt = decided->chars;
while(charAlt->selLength == 0)
charAlt = charAlt->next;
// Alternative contains selected word.
if(charAlt->selLength == selectedWord.len
&& charAlt->selRule == selectedWord.rule
&& charAlt->parent == selectedWord.c) {
a = decided->next;
decided->next = original;
original = decided;
decided = a;
}
// Alternative does not contain selected word.
else {
a = decided;
decided = decided->next;
delete a;
}
}
// Remove processed characters from remaining alternatives.
a = original;
while(a) {
size_t nRemove = selectedWord.nCharsBefore + selectedWord.len;
while(nRemove > 0) {
CharacterAlt *toDelete = a->chars;
a->chars = a->chars->next;
delete toDelete;
--nRemove;
}
a = a->next;
}
}
#ifndef SELECT_FIRST
// User wants original alternatives.
else {
// Free new alternatives.
while(decided) {
Alternative *toDelete = decided;
decided = decided->next;
delete toDelete;
}
// Free all characters from original alternatives.
a = original;
while(a) {
while(a->chars) {
CharacterAlt *toDelete = a->chars;
a->chars = a->chars->next;
delete toDelete;
}
a->chars = new CharacterAlt(text);
a = a->next;
}
}
#endif
return true;
}
void processText() {
while(processWord()) ;
}
int main(int argc, char** argv) {
// otevreni vstupu
if(argc != 3) {
cout << "Usage: " << argv[0] << " input-file output-file" << endl;
return 0;
}
input.open(argv[1]);
if(!input.is_open()) {
cout << "Input file cannot be opened." << endl;
return 0;
}
output.open(argv[2]);
if(!output.is_open()) {
input.close();
cout << "Output file cannot be opened." << endl;
return 0;
}
// inicializace
text = new Character();
original = new Alternative(text);
setupPartialOrder(&original->ord);
processText();
// vypisu usporadani
separator();
cout << "Number of conflicts: " << numOfConflicts << endl;
cout << "Alternatives: " << endl;
// uvolnim alternativy v original
while(original) {
Alternative *toDelete = original;
original = original->next;
// vypisu usporadani
cout << endl;
toDelete->ord.show();
cout << endl;
delete toDelete;
}
// uvolnim posledni znak eof
delete text;
output.close();
input.close();
return 0;
}
|]
-- ---------------------------------------------------------------------------
-- Helper functions
-- | Returns list with captures from substitution.
capturesInSubst :: Subst a -> [Int]
capturesInSubst (Subst terms)
= catMaybes $ map (\t -> case t of TCapture i -> Just i
TConst _ -> Nothing) terms
-- | C array from boxed array. Second contains type singature and name
-- of the variable.
buildTable :: Array Int e -> String -> (e -> String) -> String
buildTable arr = buildTableL (elems arr)
-- | C array from unboxed array.
buildTableU :: (Show i, Enum i, Ix i, U.IArray UArray e)
=> UArray i e -> String -> (e -> String) -> String
buildTableU arr = buildTableL (U.elems arr)
-- | C array from list.
buildTableL :: [e] -> String -> (e -> String) -> String
buildTableL list typeAndName elemToStr
= typeAndName ++ '[' : show (length list) ++ "] = "
++ '{' : (concat $ intersperse "," $ map elemToStr list) ++ "};"
|
radekm/crep
|
BackEnd/CPP.hs
|
bsd-3-clause
| 48,734 | 640 | 27 | 17,246 | 9,187 | 5,825 | 3,362 | 301 | 16 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.JHC
-- Copyright : Isaac Jones 2003-2006
-- License : BSD3
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module contains most of the JHC-specific code for configuring, building
-- and installing packages.
module Distribution.Simple.JHC (
configure, getInstalledPackages,
buildLib, buildExe,
installLib, installExe
) where
import Prelude ()
import Distribution.Compat.Prelude
import Distribution.PackageDescription as PD hiding (Flag)
import Distribution.InstalledPackageInfo
import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
import Distribution.Simple.PackageIndex (InstalledPackageIndex)
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.BuildPaths
import Distribution.Simple.Compiler
import Language.Haskell.Extension
import Distribution.Simple.Program
import Distribution.Version
import Distribution.Package
import Distribution.Simple.Utils
import Distribution.Verbosity
import Distribution.Text
import System.FilePath ( (</>) )
import Distribution.Compat.ReadP
( readP_to_S, string, skipSpaces )
import Distribution.System ( Platform )
import qualified Data.Map as Map ( empty )
import qualified Data.ByteString.Lazy.Char8 as BS.Char8
-- -----------------------------------------------------------------------------
-- Configuring
configure :: Verbosity -> Maybe FilePath -> Maybe FilePath
-> ProgramDb -> IO (Compiler, Maybe Platform, ProgramDb)
configure verbosity hcPath _hcPkgPath progdb = do
(jhcProg, _, progdb') <- requireProgramVersion verbosity
jhcProgram (orLaterVersion (Version [0,7,2] []))
(userMaybeSpecifyPath "jhc" hcPath progdb)
let Just version = programVersion jhcProg
comp = Compiler {
compilerId = CompilerId JHC version,
compilerAbiTag = NoAbiTag,
compilerCompat = [],
compilerLanguages = jhcLanguages,
compilerExtensions = jhcLanguageExtensions,
compilerProperties = Map.empty
}
compPlatform = Nothing
return (comp, compPlatform, progdb')
jhcLanguages :: [(Language, Flag)]
jhcLanguages = [(Haskell98, "")]
-- | The flags for the supported extensions
jhcLanguageExtensions :: [(Extension, Flag)]
jhcLanguageExtensions =
[(EnableExtension TypeSynonymInstances , "")
,(DisableExtension TypeSynonymInstances , "")
,(EnableExtension ForeignFunctionInterface , "")
,(DisableExtension ForeignFunctionInterface , "")
,(EnableExtension ImplicitPrelude , "") -- Wrong
,(DisableExtension ImplicitPrelude , "--noprelude")
,(EnableExtension CPP , "-fcpp")
,(DisableExtension CPP , "-fno-cpp")
]
getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramDb
-> IO InstalledPackageIndex
getInstalledPackages verbosity _packageDBs progdb = do
-- jhc --list-libraries lists all available libraries.
-- How shall I find out, whether they are global or local
-- without checking all files and locations?
str <- getDbProgramOutput verbosity jhcProgram progdb ["--list-libraries"]
let pCheck :: [(a, String)] -> [a]
pCheck rs = [ r | (r,s) <- rs, all isSpace s ]
let parseLine ln =
pCheck (readP_to_S
(skipSpaces >> string "Name:" >> skipSpaces >> parse) ln)
return $
PackageIndex.fromList $
map (\p -> emptyInstalledPackageInfo {
InstalledPackageInfo.installedUnitId = mkLegacyUnitId p,
InstalledPackageInfo.sourcePackageId = p
}) $
concatMap parseLine $
lines str
-- -----------------------------------------------------------------------------
-- Building
-- | Building a package for JHC.
-- Currently C source files are not supported.
buildLib :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO ()
buildLib verbosity pkg_descr lbi lib clbi = do
let Just jhcProg = lookupProgram jhcProgram (withPrograms lbi)
let libBi = libBuildInfo lib
let args = constructJHCCmdLine lbi libBi clbi (buildDir lbi) verbosity
let pkgid = display (packageId pkg_descr)
pfile = buildDir lbi </> "jhc-pkg.conf"
hlfile= buildDir lbi </> (pkgid ++ ".hl")
writeFileAtomic pfile . BS.Char8.pack $ jhcPkgConf pkg_descr
runProgram verbosity jhcProg $
["--build-hl="++pfile, "-o", hlfile] ++
args ++ map display (libModules lib)
-- | Building an executable for JHC.
-- Currently C source files are not supported.
buildExe :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Executable -> ComponentLocalBuildInfo -> IO ()
buildExe verbosity _pkg_descr lbi exe clbi = do
let Just jhcProg = lookupProgram jhcProgram (withPrograms lbi)
let exeBi = buildInfo exe
let out = buildDir lbi </> exeName exe
let args = constructJHCCmdLine lbi exeBi clbi (buildDir lbi) verbosity
runProgram verbosity jhcProg (["-o",out] ++ args ++ [modulePath exe])
constructJHCCmdLine :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo
-> FilePath -> Verbosity -> [String]
constructJHCCmdLine lbi bi clbi _odir verbosity =
(if verbosity >= deafening then ["-v"] else [])
++ hcOptions JHC bi
++ languageToFlags (compiler lbi) (defaultLanguage bi)
++ extensionsToFlags (compiler lbi) (usedExtensions bi)
++ ["--noauto","-i-"]
++ concat [["-i", l] | l <- nub (hsSourceDirs bi)]
++ ["-i", autogenComponentModulesDir lbi clbi]
++ ["-i", autogenPackageModulesDir lbi]
++ ["-optc" ++ opt | opt <- PD.ccOptions bi]
-- It would be better if JHC would accept package names with versions,
-- but JHC-0.7.2 doesn't accept this.
-- Thus, we have to strip the version with 'pkgName'.
++ (concat [ ["-p", display (pkgName pkgid)]
| (_, pkgid) <- componentPackageDeps clbi ])
jhcPkgConf :: PackageDescription -> String
jhcPkgConf pd =
let sline name sel = name ++ ": "++sel pd
lib pd' = case library pd' of
Just lib' -> lib'
Nothing -> error "no library available"
comma = intercalate "," . map display
in unlines [sline "name" (display . pkgName . packageId)
,sline "version" (display . pkgVersion . packageId)
,sline "exposed-modules" (comma . PD.exposedModules . lib)
,sline "hidden-modules" (comma . otherModules . libBuildInfo . lib)
]
installLib :: Verbosity
-> LocalBuildInfo
-> FilePath
-> FilePath
-> FilePath
-> PackageDescription
-> Library
-> ComponentLocalBuildInfo
-> IO ()
installLib verb _lbi dest _dyn_dest build_dir pkg_descr _lib _clbi = do
let p = display (packageId pkg_descr)++".hl"
createDirectoryIfMissingVerbose verb True dest
installOrdinaryFile verb (build_dir </> p) (dest </> p)
installExe :: Verbosity -> FilePath -> FilePath -> (FilePath,FilePath) -> PackageDescription -> Executable -> IO ()
installExe verb dest build_dir (progprefix,progsuffix) _ exe = do
let exe_name = exeName exe
src = exe_name </> exeExtension
out = (progprefix ++ exe_name ++ progsuffix) </> exeExtension
createDirectoryIfMissingVerbose verb True dest
installExecutableFile verb (build_dir </> src) (dest </> out)
|
sopvop/cabal
|
Cabal/Distribution/Simple/JHC.hs
|
bsd-3-clause
| 7,754 | 0 | 17 | 1,828 | 1,861 | 994 | 867 | 138 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.