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 DeriveDataTypeable #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Gmail.Types
-- 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)
--
module Network.Google.Gmail.Types
(
-- * Service Configuration
gmailService
-- * OAuth Scopes
, gmailSettingsBasicScope
, gmailAddonsCurrentMessageActionScope
, gmailAddonsCurrentMessageMetadataScope
, mailGoogleComScope
, gmailModifyScope
, gmailMetadataScope
, gmailLabelsScope
, gmailSettingsSharingScope
, gmailSendScope
, gmailAddonsCurrentMessageReadOnlyScope
, gmailAddonsCurrentActionComposeScope
, gmailInsertScope
, gmailComposeScope
, gmailReadOnlyScope
-- * BatchDeleteMessagesRequest
, BatchDeleteMessagesRequest
, batchDeleteMessagesRequest
, bdmrIds
-- * FilterCriteriaSizeComparison
, FilterCriteriaSizeComparison (..)
-- * Delegate
, Delegate
, delegate
, dVerificationStatus
, dDelegateEmail
-- * UsersMessagesGetFormat
, UsersMessagesGetFormat (..)
-- * ModifyThreadRequest
, ModifyThreadRequest
, modifyThreadRequest
, mtrRemoveLabelIds
, mtrAddLabelIds
-- * ListFiltersResponse
, ListFiltersResponse
, listFiltersResponse
, lfrFilter
-- * ModifyMessageRequest
, ModifyMessageRequest
, modifyMessageRequest
, mmrRemoveLabelIds
, mmrAddLabelIds
-- * ListForwardingAddressesResponse
, ListForwardingAddressesResponse
, listForwardingAddressesResponse
, lfarForwardingAddresses
-- * PopSettings
, PopSettings
, popSettings
, psAccessWindow
, psDisPosition
-- * PopSettingsAccessWindow
, PopSettingsAccessWindow (..)
-- * History
, History
, history
, hLabelsRemoved
, hMessagesDeleted
, hMessagesAdded
, hLabelsAdded
, hId
, hMessages
-- * ListDelegatesResponse
, ListDelegatesResponse
, listDelegatesResponse
, ldrDelegates
-- * ForwardingAddressVerificationStatus
, ForwardingAddressVerificationStatus (..)
-- * LabelColor
, LabelColor
, labelColor
, lcBackgRoundColor
, lcTextColor
-- * FilterCriteria
, FilterCriteria
, filterCriteria
, fcSizeComparison
, fcSubject
, fcSize
, fcExcludeChats
, fcTo
, fcFrom
, fcQuery
, fcNegatedQuery
, fcHasAttachment
-- * ProFile
, ProFile
, proFile
, pfMessagesTotal
, pfThreadsTotal
, pfHistoryId
, pfEmailAddress
-- * AutoForwardingDisPosition
, AutoForwardingDisPosition (..)
-- * MessagePartHeader
, MessagePartHeader
, messagePartHeader
, mphValue
, mphName
-- * UsersHistoryListHistoryTypes
, UsersHistoryListHistoryTypes (..)
-- * SendAsVerificationStatus
, SendAsVerificationStatus (..)
-- * ListHistoryResponse
, ListHistoryResponse
, listHistoryResponse
, lhrNextPageToken
, lhrHistory
, lhrHistoryId
-- * SendAs
, SendAs
, sendAs
, saSignature
, saReplyToAddress
, saTreatAsAlias
, saSendAsEmail
, saDisplayName
, saVerificationStatus
, saSmtpMsa
, saIsPrimary
, saIsDefault
-- * LabelType
, LabelType (..)
-- * UsersDraftsGetFormat
, UsersDraftsGetFormat (..)
-- * UsersMessagesImportInternalDateSource
, UsersMessagesImportInternalDateSource (..)
-- * LabelMessageListVisibility
, LabelMessageListVisibility (..)
-- * ListThreadsResponse
, ListThreadsResponse
, listThreadsResponse
, ltrNextPageToken
, ltrResultSizeEstimate
, ltrThreads
-- * MessagePart
, MessagePart
, messagePart
, mpParts
, mpBody
, mpMimeType
, mpHeaders
, mpPartId
, mpFilename
-- * HistoryLabelAdded
, HistoryLabelAdded
, historyLabelAdded
, hlaLabelIds
, hlaMessage
-- * ListLabelsResponse
, ListLabelsResponse
, listLabelsResponse
, llrLabels
-- * VacationSettings
, VacationSettings
, vacationSettings
, vsEnableAutoReply
, vsResponseBodyPlainText
, vsRestrictToDomain
, vsStartTime
, vsResponseBodyHTML
, vsRestrictToContacts
, vsResponseSubject
, vsEndTime
-- * LabelLabelListVisibility
, LabelLabelListVisibility (..)
-- * HistoryMessageDeleted
, HistoryMessageDeleted
, historyMessageDeleted
, hmdMessage
-- * MessagePartBody
, MessagePartBody
, messagePartBody
, mpbSize
, mpbData
, mpbAttachmentId
-- * AutoForwarding
, AutoForwarding
, autoForwarding
, afEnabled
, afDisPosition
, afEmailAddress
-- * ListDraftsResponse
, ListDraftsResponse
, listDraftsResponse
, ldrNextPageToken
, ldrResultSizeEstimate
, ldrDrafts
-- * ListSendAsResponse
, ListSendAsResponse
, listSendAsResponse
, lsarSendAs
-- * LanguageSettings
, LanguageSettings
, languageSettings
, lsDisplayLanguage
-- * WatchResponse
, WatchResponse
, watchResponse
, wrExpiration
, wrHistoryId
-- * Xgafv
, Xgafv (..)
-- * DelegateVerificationStatus
, DelegateVerificationStatus (..)
-- * UsersThreadsGetFormat
, UsersThreadsGetFormat (..)
-- * BatchModifyMessagesRequest
, BatchModifyMessagesRequest
, batchModifyMessagesRequest
, bmmrIds
, bmmrRemoveLabelIds
, bmmrAddLabelIds
-- * Draft
, Draft
, draft
, dId
, dMessage
-- * SmtpMsa
, SmtpMsa
, smtpMsa
, smSecurityMode
, smUsername
, smPassword
, smHost
, smPort
-- * ForwardingAddress
, ForwardingAddress
, forwardingAddress
, faForwardingEmail
, faVerificationStatus
-- * PopSettingsDisPosition
, PopSettingsDisPosition (..)
-- * Filter
, Filter
, filter'
, fAction
, fId
, fCriteria
-- * WatchRequest
, WatchRequest
, watchRequest
, wrLabelFilterAction
, wrTopicName
, wrLabelIds
-- * WatchRequestLabelFilterAction
, WatchRequestLabelFilterAction (..)
-- * ImapSettings
, ImapSettings
, imapSettings
, isEnabled
, isExpungeBehavior
, isAutoExpunge
, isMaxFolderSize
-- * ImapSettingsExpungeBehavior
, ImapSettingsExpungeBehavior (..)
-- * ListSmimeInfoResponse
, ListSmimeInfoResponse
, listSmimeInfoResponse
, lsirSmimeInfo
-- * SmtpMsaSecurityMode
, SmtpMsaSecurityMode (..)
-- * Message
, Message
, message
, mRaw
, mSnippet
, mSizeEstimate
, mPayload
, mHistoryId
, mId
, mLabelIds
, mThreadId
, mInternalDate
-- * UsersMessagesInsertInternalDateSource
, UsersMessagesInsertInternalDateSource (..)
-- * HistoryLabelRemoved
, HistoryLabelRemoved
, historyLabelRemoved
, hlrLabelIds
, hlrMessage
-- * Thread
, Thread
, thread
, tSnippet
, tHistoryId
, tId
, tMessages
-- * FilterAction
, FilterAction
, filterAction
, faForward
, faRemoveLabelIds
, faAddLabelIds
-- * Label
, Label
, label
, lThreadsUnread
, lMessageListVisibility
, lMessagesTotal
, lColor
, lMessagesUnread
, lName
, lThreadsTotal
, lLabelListVisibility
, lId
, lType
-- * SmimeInfo
, SmimeInfo
, smimeInfo
, siPem
, siExpiration
, siEncryptedKeyPassword
, siId
, siPkcs12
, siIssuerCn
, siIsDefault
-- * ListMessagesResponse
, ListMessagesResponse
, listMessagesResponse
, lmrNextPageToken
, lmrResultSizeEstimate
, lmrMessages
-- * HistoryMessageAdded
, HistoryMessageAdded
, historyMessageAdded
, hmaMessage
) where
import Network.Google.Gmail.Types.Product
import Network.Google.Gmail.Types.Sum
import Network.Google.Prelude
-- | Default request referring to version 'v1' of the Gmail API. This contains the host and root path used as a starting point for constructing service requests.
gmailService :: ServiceConfig
gmailService
= defaultService (ServiceId "gmail:v1")
"gmail.googleapis.com"
-- | See, edit, create, or change your email settings and filters in Gmail
gmailSettingsBasicScope :: Proxy '["https://www.googleapis.com/auth/gmail.settings.basic"]
gmailSettingsBasicScope = Proxy
-- | View your email messages when you interact with the add-on
gmailAddonsCurrentMessageActionScope :: Proxy '["https://www.googleapis.com/auth/gmail.addons.current.message.action"]
gmailAddonsCurrentMessageActionScope = Proxy
-- | View your email message metadata when the add-on is running
gmailAddonsCurrentMessageMetadataScope :: Proxy '["https://www.googleapis.com/auth/gmail.addons.current.message.metadata"]
gmailAddonsCurrentMessageMetadataScope = Proxy
-- | Read, compose, send, and permanently delete all your email from Gmail
mailGoogleComScope :: Proxy '["https://mail.google.com/"]
mailGoogleComScope = Proxy
-- | Read, compose, and send emails from your Gmail account
gmailModifyScope :: Proxy '["https://www.googleapis.com/auth/gmail.modify"]
gmailModifyScope = Proxy
-- | View your email message metadata such as labels and headers, but not the
-- email body
gmailMetadataScope :: Proxy '["https://www.googleapis.com/auth/gmail.metadata"]
gmailMetadataScope = Proxy
-- | See and edit your email labels
gmailLabelsScope :: Proxy '["https://www.googleapis.com/auth/gmail.labels"]
gmailLabelsScope = Proxy
-- | Manage your sensitive mail settings, including who can manage your mail
gmailSettingsSharingScope :: Proxy '["https://www.googleapis.com/auth/gmail.settings.sharing"]
gmailSettingsSharingScope = Proxy
-- | Send email on your behalf
gmailSendScope :: Proxy '["https://www.googleapis.com/auth/gmail.send"]
gmailSendScope = Proxy
-- | View your email messages when the add-on is running
gmailAddonsCurrentMessageReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/gmail.addons.current.message.readonly"]
gmailAddonsCurrentMessageReadOnlyScope = Proxy
-- | Manage drafts and send emails when you interact with the add-on
gmailAddonsCurrentActionComposeScope :: Proxy '["https://www.googleapis.com/auth/gmail.addons.current.action.compose"]
gmailAddonsCurrentActionComposeScope = Proxy
-- | Add emails into your Gmail mailbox
gmailInsertScope :: Proxy '["https://www.googleapis.com/auth/gmail.insert"]
gmailInsertScope = Proxy
-- | Manage drafts and send emails
gmailComposeScope :: Proxy '["https://www.googleapis.com/auth/gmail.compose"]
gmailComposeScope = Proxy
-- | View your email messages and settings
gmailReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/gmail.readonly"]
gmailReadOnlyScope = Proxy
|
brendanhay/gogol
|
gogol-gmail/gen/Network/Google/Gmail/Types.hs
|
mpl-2.0
| 11,101 | 0 | 7 | 2,553 | 1,272 | 857 | 415 | 307 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.ResourceViews.Types
-- 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)
--
module Network.Google.ResourceViews.Types
(
-- * Service Configuration
resourceViewsService
-- * OAuth Scopes
, computeScope
, cloudPlatformReadOnlyScope
, cloudPlatformScope
, ndevCloudmanScope
, ndevCloudmanReadOnlyScope
, computeReadOnlyScope
-- * OperationWarningsItemDataItem
, OperationWarningsItemDataItem
, operationWarningsItemDataItem
, owidiValue
, owidiKey
-- * OperationList
, OperationList
, operationList
, olNextPageToken
, olKind
, olItems
, olSelfLink
, olId
-- * ResourceView
, ResourceView
, resourceView
, rvSize
, rvKind
, rvFingerprint
, rvNetwork
, rvResources
, rvSelfLink
, rvName
, rvCreationTimestamp
, rvId
, rvLabels
, rvEndpoints
, rvDescription
-- * ZoneViewsList
, ZoneViewsList
, zoneViewsList
, zvlNextPageToken
, zvlKind
, zvlItems
, zvlSelfLink
-- * Operation
, Operation
, operation
, oTargetId
, oStatus
, oInsertTime
, oProgress
, oStartTime
, oKind
, oError
, oHTTPErrorMessage
, oZone
, oWarnings
, oHTTPErrorStatusCode
, oUser
, oSelfLink
, oName
, oStatusMessage
, oCreationTimestamp
, oEndTime
, oId
, oOperationType
, oRegion
, oTargetLink
, oClientOperationId
-- * ZoneViewsListResourcesFormat
, ZoneViewsListResourcesFormat (..)
-- * ZoneViewsListResourcesResponse
, ZoneViewsListResourcesResponse
, zoneViewsListResourcesResponse
, zvlrrNextPageToken
, zvlrrItems
, zvlrrNetwork
-- * ServiceEndpoint
, ServiceEndpoint
, serviceEndpoint
, seName
, sePort
-- * ZoneViewsListResourcesListState
, ZoneViewsListResourcesListState (..)
-- * ZoneViewsRemoveResourcesRequest
, ZoneViewsRemoveResourcesRequest
, zoneViewsRemoveResourcesRequest
, zvrrrResources
-- * ListResourceResponseItemEndpoints
, ListResourceResponseItemEndpoints
, listResourceResponseItemEndpoints
, lrrieAddtional
-- * ZoneViewsAddResourcesRequest
, ZoneViewsAddResourcesRequest
, zoneViewsAddResourcesRequest
, zvarrResources
-- * OperationError
, OperationError
, operationError
, oeErrors
-- * ZoneViewsGetServiceResponse
, ZoneViewsGetServiceResponse
, zoneViewsGetServiceResponse
, zvgsrFingerprint
, zvgsrEndpoints
-- * OperationErrorErrorsItem
, OperationErrorErrorsItem
, operationErrorErrorsItem
, oeeiLocation
, oeeiCode
, oeeiMessage
-- * ZoneViewsSetServiceRequest
, ZoneViewsSetServiceRequest
, zoneViewsSetServiceRequest
, zvssrResourceName
, zvssrFingerprint
, zvssrEndpoints
-- * ListResourceResponseItem
, ListResourceResponseItem
, listResourceResponseItem
, lrriResource
, lrriEndpoints
-- * Label
, Label
, label
, lValue
, lKey
-- * OperationWarningsItem
, OperationWarningsItem
, operationWarningsItem
, owiData
, owiCode
, owiMessage
) where
import Network.Google.Prelude
import Network.Google.ResourceViews.Types.Product
import Network.Google.ResourceViews.Types.Sum
-- | Default request referring to version 'v1beta2' of the Google Compute Engine Instance Groups API. This contains the host and root path used as a starting point for constructing service requests.
resourceViewsService :: ServiceConfig
resourceViewsService
= defaultService (ServiceId "resourceviews:v1beta2")
"www.googleapis.com"
-- | View and manage your Google Compute Engine resources
computeScope :: Proxy '["https://www.googleapis.com/auth/compute"]
computeScope = Proxy;
-- | View your data across Google Cloud Platform services
cloudPlatformReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform.read-only"]
cloudPlatformReadOnlyScope = Proxy;
-- | View and manage your data across Google Cloud Platform services
cloudPlatformScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform"]
cloudPlatformScope = Proxy;
-- | View and manage your Google Cloud Platform management resources and
-- deployment status information
ndevCloudmanScope :: Proxy '["https://www.googleapis.com/auth/ndev.cloudman"]
ndevCloudmanScope = Proxy;
-- | View your Google Cloud Platform management resources and deployment
-- status information
ndevCloudmanReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/ndev.cloudman.readonly"]
ndevCloudmanReadOnlyScope = Proxy;
-- | View your Google Compute Engine resources
computeReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/compute.readonly"]
computeReadOnlyScope = Proxy;
|
rueshyna/gogol
|
gogol-resourceviews/gen/Network/Google/ResourceViews/Types.hs
|
mpl-2.0
| 5,272 | 0 | 7 | 1,156 | 555 | 374 | 181 | 139 | 1 |
{-#LANGUAGE OverloadedStrings#-}
module Data.P440.XML.Instances.PNO where
import qualified Data.P440.Domain.PNO as PNO
import Data.P440.Domain.SimpleTypes
import Data.P440.Domain.ComplexTypes
import Data.P440.XML.XML
import qualified Data.P440.XML.Instances.ComplexTypes as C
instance ToNode PNO.Файл where
toNode (PNO.Файл идЭС версПрог телОтпр
должнОтпр фамОтпр поручНО) =
complex "Файл"
["ИдЭС" =: идЭС
,"ВерсПрог" =: версПрог
,"ТелОтпр" =: телОтпр
,"ДолжнОтпр" =: должнОтпр
,"ФамОтпр" =: фамОтпр]
[Single поручНО]
instance ToNode PNO.ПоручНО where
toNode (PNO.ПоручНО номПоруч датаПодп видПлат сумПлат статус инннп
кппнп плательщ номСчПлИлиКЭСП банкПл бикбПл номСчБПл
номФ банкПол бикбПол номСчБПол иннПол
кппПол получ номСчПол видОп назПлКод
очерПл кодПл резПоле назнПл кгн
укгн кбк октмо кодОсн срокУплТр
номТреб датаТреб типПлат порВал) =
complex "ПоручНО"
["НомПоруч" =: номПоруч
,"ДатаПодп" =: датаПодп
,"ВидПлат" =: видПлат
,"СумПлат" =: сумПлат
,"Статус" =: статус
,"ИНННП" =: инннп
,"КППНП" =: кппнп
,"Плательщ" =: плательщ
,"БанкПл" =: банкПл
,"НомСчБПл" =: номСчБПл
,"НомФ" =: номФ
,"БанкПол" =: банкПол
,"БИКБПол" =: бикбПол
,"НомСчБПол" =: номСчБПол
,"ИННПол" =: иннПол
,"КПППол" =: кппПол
,"Получ" =: получ
,"НомСчПол" =: номСчПол
,"ВидОп" =: видОп
,"НазПлКод" =: назПлКод
,"ОчерПл" =: очерПл
,"КодПл" =: кодПл
,"РезПоле" =: резПоле
,"НазнПл" =: назнПл
,"КГН" =: кгн
,"УКГН" =: укгн
,"КБК" =: кбк
,"ОКТМО" =: октмо
,"КодОсн" =: кодОсн
,"СрокУплТр" =: срокУплТр
,"НомТреб" =: номТреб
,"ДатаТреб" =: датаТреб
,"ТипПлат" =: типПлат]
[Sequence номСчПлИлиКЭСП
,Sequence порВал]
instance ToNode PNO.НомСчПлИлиКЭСП where
toNode (PNO.Счет (НомСч счет)) = simple "Счет" счет
toNode (PNO.КЭСП кэсп) = simple "КЭСП" кэсп
instance ToNode PNO.ПорВал where
toNode (PNO.ПорВал номПорВал датаПорВал номВалСч) =
complex_ "ПорВал"
["НомПорВал" =: номПорВал
,"ДатаПорВал" =: датаПорВал
,"НомВалСч" =: номВалСч]
|
Macil-dev/440P-old
|
src/Data/P440/XML/Instances/PNO.hs
|
unlicense
| 3,907 | 0 | 10 | 1,264 | 1,789 | 906 | 883 | 70 | 0 |
module Lexer where
import Text.Parsec.String (Parser)
import Text.Parsec.Language (emptyDef)
import qualified Text.Parsec.Token as Token
lexer :: Token.TokenParser ()
lexer = Token.makeTokenParser style
where
style = emptyDef {
Token.commentLine = "#",
Token.reservedOpNames = ["+", "*", "-", ";"],
Token.reservedNames = ["def", "extern"]
}
integer :: Parser Integer
integer = Token.integer lexer
float :: Parser Double
float = Token.float lexer
parens :: Parser a -> Parser a
parens = Token.parens lexer
commaSep :: Parser a -> Parser [a]
commaSep = Token.commaSep lexer
semiSep :: Parser a -> Parser [a]
semiSep = Token.semiSep lexer
identifier :: Parser String
identifier = Token.identifier lexer
reserved :: String -> Parser ()
reserved = Token.reserved lexer
reservedOp :: String -> Parser ()
reservedOp = Token.reservedOp lexer
|
raviqqe/jack
|
command/Lexer.hs
|
unlicense
| 906 | 0 | 9 | 190 | 291 | 158 | 133 | 26 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
module XTestX where
import X0
import XTestUtils
import XUtil
------------------------------------------------------------------------------
import qualified Data.Map as Map
import qualified Data.Set as Set
import Numeric.Natural
import Protolude
import qualified Test.Tasty.HUnit as HUnit
type Var = ByteString
data StoreCmd
= Set Var Natural
| Incr Var
| Noop
deriving (Eq, Show)
type Store = Map Var Natural
instance XSMP Store StoreCmd where
data XSMPError Store StoreCmd = StoreError Text deriving (Show)
type XSMPCtx Store StoreCmd = ()
applyCmdXSMP _ store cmd =
Right $ case cmd of
Set x n -> Map.insert x n store
Incr x -> Map.adjust succ x store
Noop -> store
data TestState v = TestState
{ testNodeIds :: NodeIds
, testNodeSMs :: Map NodeId Store
, testNodeXStates :: Map NodeId (XNodeState v)
, testNodePersistentStates :: Map NodeId PersistentState
, testNodeConfigs :: Map NodeId NodeConfig
} deriving Show
type Scenario v a = StateT (TestState v) IO a
runScenario :: Scenario v () -> IO ()
runScenario scenario =
evalStateT scenario $ TestState
{ testNodeIds = nodeIds
, testNodeSMs = Map.fromList $ (, mempty) <$> Set.toList nodeIds
, testNodeXStates = Map.fromList $ (, initXNodeState) <$> Set.toList nodeIds
, testNodePersistentStates = Map.fromList $ (, initPersistentState) <$> Set.toList nodeIds
, testNodeConfigs = Map.fromList $ zip (Set.toList nodeIds) testConfigs
}
updateStateMachine :: NodeId -> Store -> Scenario v ()
updateStateMachine nodeId sm =
modify $ \testState@TestState{..} ->
testState { testNodeSMs = Map.insert nodeId sm testNodeSMs }
updatePersistentState :: NodeId -> PersistentState -> Scenario v ()
updatePersistentState nodeId persistentState =
modify $ \testState@TestState{..} ->
testState { testNodePersistentStates = Map.insert nodeId persistentState testNodePersistentStates }
updateXNodeState :: NodeId -> XNodeState v -> Scenario v ()
updateXNodeState nodeId xState =
modify $ \testState@TestState{..} ->
testState { testNodeXStates = Map.insert nodeId xState testNodeXStates }
getNodeInfo :: NodeId -> Scenario v (NodeConfig, Store, XNodeState v, PersistentState)
getNodeInfo nId = do
nodeConfigs <- gets testNodeConfigs
nodeSMs <- gets testNodeSMs
nodeXStates <- gets testNodeXStates
nodePersistentStates <- gets testNodePersistentStates
let Just nodeInfo =
Map.lookup nId nodeConfigs >>= \config ->
Map.lookup nId nodeSMs >>= \store ->
Map.lookup nId nodeXStates >>= \xState ->
Map.lookup nId nodePersistentStates >>= \persistentState ->
pure (config, store, xState, persistentState)
pure nodeInfo
-------------------------------
-- Handle actions and events --
-------------------------------
testHandleEvent
:: NodeId
-> Event StoreCmd
-> Scenario StoreCmd ([Action Store StoreCmd], [LogMsg])
testHandleEvent nodeId event = do
(nodeConfig', sm, inXNodeState, inPersistentState) <- getNodeInfo nodeId
let transitionEnv = TransitionEnv nodeConfig' sm inXNodeState
let (outXNodeState, outPersistentState, actions, logMsgs) =
handleEvent inXNodeState transitionEnv inPersistentState event
updatePersistentState nodeId outPersistentState
updateXNodeState nodeId outXNodeState
xns <- applyCmds nodeId sm
updateXNodeState nodeId xns
return (actions, logMsgs)
where
applyCmds :: NodeId -> Store -> Scenario StoreCmd (XNodeState StoreCmd)
applyCmds nid inSm = do
(_, _, xns@(XNodeState nodeState), _) <- getNodeInfo nid
case getCmd nodeState of
Nothing -> return xns
Just v ->
case applyCmdXSMP () inSm v of
Left _ -> return xns
Right outSm -> do
updateStateMachine nid outSm
return (XNodeState (setCmd Nothing nodeState))
getCmd :: NodeState ns v -> Maybe v
getCmd = \case
NodeLoggedInState s -> lsCmd s
_ -> Nothing
setCmd :: Maybe v -> NodeState ns v -> NodeState ns v
setCmd mv = \case
NodeLoggedInState s -> NodeLoggedInState (s { lsCmd = mv })
s -> s
testHeartbeat :: Text -> Scenario StoreCmd ()
testHeartbeat mode = do
r1 <- testHandleEvent node1 (TimeoutEvent HeartbeatTimeout)
liftIO $ assertActions r1
[ ResetTimeoutTimer HeartbeatTimeout
, SendToClient (ClientId "client") CresEnterUsernamePassword
]
liftIO $ assertLogs r1
[mode <> ".handleTimeout; HeartbeatTimeout"]
testUsernamePassword :: ClientId -> UsernamePassword -> Scenario StoreCmd ()
testUsernamePassword c up = do
r2 <- testHandleEvent node1
(MessageEvent (ClientRequestEvent (CreqUsernamePassword c up)))
liftIO $ assertActions r2
[ ResetTimeoutTimer HeartbeatTimeout
, SendToClient c CresEnterPin
]
liftIO $ assertLogs r2
[fields ["LoggedOut.handleUsernamePassword valid", pshow c, pshow up]]
testPin :: ClientId -> Pin -> Scenario StoreCmd ()
testPin c p = do
r3 <- testHandleEvent node1
(MessageEvent (ClientRequestEvent (CreqPin c p)))
liftIO $ assertActions r3
[ ResetTimeoutTimer HeartbeatTimeout
, SendToClient c CresEnterCommandOrQuit
]
liftIO $ assertLogs r3
[fields ["Candidate.handlePin: valid", pshow c, pshow p]]
testCommandOrQuit :: ClientId -> CommandOrQuit StoreCmd -> Store -> Scenario StoreCmd ()
testCommandOrQuit c a@(CommandOrQuit t _) store = do
r4 <- testHandleEvent node1 (MessageEvent (ClientRequestEvent (CreqCommandOrQuit c a)))
liftIO $ assertActions r4 $
[ResetTimeoutTimer HeartbeatTimeout]
++ [SendToClient c (CresStateMachine store) | t == "R"]
++ [ SendToClient c $ if t == "Q"
then CresQuit
else CresEnterCommandOrQuit ]
liftIO $ assertLogs r4
[fields ["LoggedIn.handleCommandOrQuit", pshow c, pshow a]]
----------------
-- Unit tests --
----------------
unit_full_cycle :: IO ()
unit_full_cycle = runScenario $ do
testHeartbeat "LoggedOut"
testUsernamePassword (ClientId "client") (UsernamePassword "foo" "bar")
testPin (ClientId "client") (Pin "1234")
testCommandOrQuit (ClientId "client") (CommandOrQuit "R" Noop) []
testCommandOrQuit (ClientId "client") (CommandOrQuit "W" (Set "x" 3)) []
testCommandOrQuit (ClientId "client") (CommandOrQuit "R" Noop) [("x",3)]
testCommandOrQuit (ClientId "client") (CommandOrQuit "Q" Noop) []
------------------
-- Assert utils --
------------------
assertActions :: ([Action Store StoreCmd], [LogMsg]) -> [Action Store StoreCmd] -> IO ()
assertActions (got,_) expected = do
assertEqualLength "actions" expected got
mapM_ (uncurry (HUnit.assertEqual "unexpected Action"))
(zip expected got)
assertLogs :: ([Action Store StoreCmd], [LogMsg]) -> [Text] -> IO ()
assertLogs (_,got) expected = do
assertEqualLength "logs" expected got
mapM_ (\(e,g) -> HUnit.assertEqual "unexpected log msg" e (lmdMsg (lmData g)))
(zip expected got)
assertEqualLength :: (Show a, Show b) => Text -> [a] -> [b] -> IO ()
assertEqualLength msg expected got =
HUnit.assertEqual
( toS msg <> " : not the same length : "
<> "expected: " <> pshow expected <> " "
<> "got: " <> pshow got )
(length expected)
(length got)
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/topic/program-structure/2019-01-hc-example-based-on-adjointio-raft/test/XTestX.hs
|
unlicense
| 8,292 | 0 | 21 | 2,091 | 2,296 | 1,164 | 1,132 | 176 | 5 |
{-# LANGUAGE FlexibleContexts #-}
module UseReaderState where
import Test.HUnit as T (Test (TestList), runTestTT)
import Test.HUnit.Util as U
import MonadReader
import MonadState
foo :: (MonadReader [String] m, MonadState [String] m)
=> m Int
foo = do
a <- asks head
let a' = read a
let aa = a' + a'
put [show aa]
return a'
runFooSR = runState (runReaderT foo ["1"]) [ ]
runFooRS = runReader (runStateT foo [ ]) ["1"]
------------------------------------------------------------------------------
trf = U.tt "runFoo*" [ runFooSR, runFooRS ] (1, ["2"])
testReaderState = runTestTT $ TestList {- $ -} trf
trs = testReaderState
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/topic/monads/m/src/UseReaderState.hs
|
unlicense
| 686 | 0 | 10 | 156 | 223 | 122 | 101 | 19 | 1 |
import MPL.NumberTheory.Primes
main = putStrLn $ show $ last $ primeFactors 600851475143
|
rohitjha/ProjectEuler
|
MPL/PE003.hs
|
unlicense
| 90 | 0 | 7 | 13 | 27 | 14 | 13 | 2 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module GitHub
( updateDeploymentStatus
) where
import qualified Control.Exception.Base as CE
import Data.Monoid
import qualified Data.Text as T
import System.Environment (getEnv)
import Network.HTTP.Conduit
import GitHub.Types
import Http
getEnvVar :: String -> IO (Either IOError String)
getEnvVar = CE.try . getEnv
-- | Update the deployment status on GitHub. This requires an access token,
-- which is read from the environment.
updateDeploymentStatus :: Manager -> DeploymentEvent -> State -> IO ()
updateDeploymentStatus httpManager de state =
getEnvVar "GITHUB_ACCESS_TOKEN" >>= either (\_ -> return ()) sendRequest
where
dId = T.pack $ show $ deploymentId $ deploymentEventDeployment de
repo = deploymentEventRepository de
repoName = repositoryFullName repo
url = "https://api.github.com/repos/" <> repoName <> "/deployments/" <> dId <> "/statuses"
sendRequest token = do
httpPOST httpManager url (T.pack token) $
CreateDeploymentStatusRequest state Nothing Nothing
|
wereHamster/mudbath
|
GitHub.hs
|
unlicense
| 1,161 | 0 | 13 | 285 | 246 | 133 | 113 | 22 | 1 |
module Nullable where
import Prelude hiding (Maybe, Just, Nothing, Either, Left, Right)
data Maybe a = Nothing | Just a deriving (Show)
{-
instance (Show a) => Show (Maybe a) where
show (Just x) = "Just " ++ show x
show Nothing = "Nothing"
-}
fromMaybe :: a -> Maybe a -> a
fromMaybe defval wrapped =
case wrapped of
Nothing -> defval
Just value -> value
data Either a b = Left a | Right b
|
SPbAU-ProgrammingParadigms/materials
|
haskell_2/Nullable.hs
|
unlicense
| 414 | 0 | 8 | 101 | 110 | 64 | 46 | 9 | 2 |
module Main where
import Control.Concurrent.Chan
import Control.Concurrent
-- Fork some computation processes, print their results
main = do
primes <- run primes
fibs <- run fibonacci
mapM print $ take 100 $ zip primes fibs
-- fork a process, return any messages it produces as a list
where
run f = do
c <- newChan
l <- getChanContents c
forkIO (writeList2Chan c f)
return l
-- A function to compute primes
primes = sieve [2..]
where
sieve (p : xs) = p : sieve [x | x <- xs, x `mod` p > 0]
-- A function to compute fibonacci numbers
fibonacci = 0 : 1 : zipWith (+) fibonacci (tail fibonacci)
|
pdbartlett/misc-stuff
|
unfuddle/PdbMisc/Haskell/Tutorial/Main.hs
|
apache-2.0
| 688 | 0 | 12 | 208 | 201 | 101 | 100 | 15 | 1 |
module HelperSequences.A000720 (a000720) where
import HelperSequences.A000040 (a000040_list)
import Data.List (genericLength)
a000720 :: Integer -> Integer
a000720 n = genericLength $ takeWhile (<= n) a000040_list
|
peterokagey/haskellOEIS
|
src/HelperSequences/A000720.hs
|
apache-2.0
| 215 | 0 | 7 | 25 | 61 | 35 | 26 | 5 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-----------------------------------------------------------------------------
-- Copyright 2019, Ideas project team. This file is distributed under the
-- terms of the Apache License 2.0. For more information, see the files
-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution.
-----------------------------------------------------------------------------
-- |
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable (depends on ghc)
--
-- Extensions to the QuickCheck library
--
-----------------------------------------------------------------------------
module Ideas.Utils.Decoding
( Decoder, runDecoder, symbol
, Encoder, runEncoder
, Error, runError, runErrorM
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Reader
import Control.Monad.State
import Data.Semigroup as Sem
-------------------------------------------------------------------
newtype Decoder env s a = Dec { runDec :: StateT s (ReaderT env Error) a }
deriving (Functor, Applicative, Alternative, Monad, MonadPlus, MonadReader env, MonadState s)
instance Sem.Semigroup a => Sem.Semigroup (Decoder env s a) where
(<>) = liftA2 (<>)
instance Monoid a => Monoid (Decoder env s a) where
mempty = pure mempty
mappend = liftA2 mappend
symbol :: Decoder env [s] s
symbol = get >>= \list ->
case list of
[] -> fail "Empty input"
x:xs ->
put xs >> return x
runDecoder :: Monad m => Decoder env s a -> env -> s -> m a
runDecoder p env s = runErrorM (runReaderT (evalStateT (runDec p) s) env)
-------------------------------------------------------------------
type Encoder env = Decoder env ()
runEncoder :: Monad m => Encoder env a -> env -> m a
runEncoder p env = runDecoder p env ()
-------------------------------------------------------------------
-- Error monad (helper)
newtype Error a = Error { runError :: Either String a }
instance Functor Error where
fmap f = Error . fmap f . runError
instance Applicative Error where
pure = Error . Right
p <*> q = Error $
case (runError p, runError q) of
(Left s, _) -> Left s
(_, Left s) -> Left s
(Right f, Right x) -> Right (f x)
instance Alternative Error where
empty = Error (Left "empty")
p <|> q = Error $
case (runError p, runError q) of
(Right a, _) -> Right a
(_, Right a) -> Right a
(Left s, _) -> Left s
instance Monad Error where
fail = Error . Left
return = pure
m >>= f = Error $ either Left (runError . f) (runError m)
instance MonadPlus Error where
mzero = fail "mzero"
mplus = (<|>)
runErrorM :: Monad m => Error a -> m a
runErrorM = either fail return . runError
|
ideas-edu/ideas
|
src/Ideas/Utils/Decoding.hs
|
apache-2.0
| 2,799 | 0 | 12 | 582 | 804 | 426 | 378 | 54 | 2 |
{-# LANGUAGE Haskell2010 #-}
{-# OPTIONS_HADDOCK hide #-}
module HiddenInstancesA where
-- | Should be visible
class Foo a
-- | Should be visible
data Bar
-- | Should be visible
instance Foo Bar
-- | Should *not* be visible
data Baz
-- | Should *not* be visible
instance Foo Baz
|
haskell/haddock
|
html-test/src/HiddenInstancesA.hs
|
bsd-2-clause
| 284 | 0 | 5 | 56 | 38 | 23 | 15 | -1 | -1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoMonomorphismRestriction #-} -- FIXME remove
-- | Some fields spiced up with jQuery UI.
module Yesod.Form.Jquery
( YesodJquery (..)
, jqueryDayField
, jqueryAutocompleteField
, googleHostedJqueryUiCss
, JqueryDaySettings (..)
, Default (..)
) where
import Yesod.Handler
import Yesod.Core (Route)
import Yesod.Form
import Yesod.Widget
import Data.Time (Day)
import qualified Data.Text as T
import Data.Default
import Text.Hamlet (shamlet)
import Text.Julius (julius)
import Data.Text (Text, pack, unpack)
import Data.Monoid (mconcat)
import Yesod.Core (RenderMessage, SomeMessage (..))
#if __GLASGOW_HASKELL__ >= 700
#define HTML shamlet
#define HAMLET hamlet
#define CASSIUS cassius
#define JULIUS julius
#else
#define HTML $shamlet
#define HAMLET $hamlet
#define CASSIUS $cassius
#define JULIUS $julius
#endif
-- | Gets the Google hosted jQuery UI 1.8 CSS file with the given theme.
googleHostedJqueryUiCss :: Text -> Text
googleHostedJqueryUiCss theme = mconcat
[ "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/"
, theme
, "/jquery-ui.css"
]
class YesodJquery a where
-- | The jQuery 1.4 Javascript file.
urlJqueryJs :: a -> Either (Route a) Text
urlJqueryJs _ = Right "http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"
-- | The jQuery UI 1.8 Javascript file.
urlJqueryUiJs :: a -> Either (Route a) Text
urlJqueryUiJs _ = Right "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
-- | The jQuery UI 1.8 CSS file; defaults to cupertino theme.
urlJqueryUiCss :: a -> Either (Route a) Text
urlJqueryUiCss _ = Right $ googleHostedJqueryUiCss "cupertino"
-- | jQuery UI time picker add-on.
urlJqueryUiDateTimePicker :: a -> Either (Route a) Text
urlJqueryUiDateTimePicker _ = Right "http://github.com/gregwebs/jquery.ui.datetimepicker/raw/master/jquery.ui.datetimepicker.js"
blank :: (RenderMessage master FormMessage, Monad m) => (Text -> Either FormMessage a) -> [Text] -> m (Either (SomeMessage master) (Maybe a))
blank _ [] = return $ Right Nothing
blank _ ("":_) = return $ Right Nothing
blank f (x:_) = return $ either (Left . SomeMessage) (Right . Just) $ f x
jqueryDayField :: (RenderMessage master FormMessage, YesodJquery master) => JqueryDaySettings -> Field sub master Day
jqueryDayField jds = Field
{ fieldParse = blank $ maybe
(Left MsgInvalidDay)
Right
. readMay
. unpack
, fieldView = \theId name theClass val isReq -> do
addHtml [HTML|\
<input id="#{theId}" name="#{name}" :not (null theClass):class="#{T.intercalate " " theClass}" type="date" :isReq:required="" value="#{showVal val}">
|]
addScript' urlJqueryJs
addScript' urlJqueryUiJs
addStylesheet' urlJqueryUiCss
addJulius [JULIUS|
$(function(){
var i = $("##{theId}");
if (i.attr("type") != "date") {
i.datepicker({
dateFormat:'yy-mm-dd',
changeMonth:#{jsBool $ jdsChangeMonth jds},
changeYear:#{jsBool $ jdsChangeYear jds},
numberOfMonths:#{mos $ jdsNumberOfMonths jds},
yearRange:"#{jdsYearRange jds}"
});
}
});
|]
}
where
showVal = either id (pack . show)
jsBool True = "true" :: Text
jsBool False = "false" :: Text
mos (Left i) = show i
mos (Right (x, y)) = concat
[ "["
, show x
, ","
, show y
, "]"
]
jqueryAutocompleteField :: (RenderMessage master FormMessage, YesodJquery master)
=> Route master -> Field sub master Text
jqueryAutocompleteField src = Field
{ fieldParse = blank $ Right
, fieldView = \theId name theClass val isReq -> do
addHtml [HTML|\
<input id="#{theId}" name="#{name}" :not (null theClass):class="#{T.intercalate " " theClass}" type="text" :isReq:required="" value="#{either id id val}" .autocomplete>
|]
addScript' urlJqueryJs
addScript' urlJqueryUiJs
addStylesheet' urlJqueryUiCss
addJulius [JULIUS|
$(function(){$("##{theId}").autocomplete({source:"@{src}",minLength:2})});
|]
}
addScript' :: (master -> Either (Route master) Text) -> GWidget sub master ()
addScript' f = do
y <- lift getYesod
addScriptEither $ f y
addStylesheet' :: (y -> Either (Route y) Text) -> GWidget sub y ()
addStylesheet' f = do
y <- lift getYesod
addStylesheetEither $ f y
readMay :: Read a => String -> Maybe a
readMay s = case reads s of
(x, _):_ -> Just x
[] -> Nothing
data JqueryDaySettings = JqueryDaySettings
{ jdsChangeMonth :: Bool
, jdsChangeYear :: Bool
, jdsYearRange :: String
, jdsNumberOfMonths :: Either Int (Int, Int)
}
instance Default JqueryDaySettings where
def = JqueryDaySettings
{ jdsChangeMonth = False
, jdsChangeYear = False
, jdsYearRange = "c-10:c+10"
, jdsNumberOfMonths = Left 1
}
|
chreekat/yesod
|
yesod-form/Yesod/Form/Jquery.hs
|
bsd-2-clause
| 5,163 | 41 | 22 | 1,198 | 1,256 | 686 | 570 | -1 | -1 |
-- functions from GHC copied here until they can be exported in the next version.
module Language.Haskell.GHC.ExactPrint.GhcInterim where
import ApiAnnotation
import Lexer
import SrcLoc
-- ---------------------------------------------------------------------
-- From Lexer.x
commentToAnnotation :: Located Token -> Located AnnotationComment
commentToAnnotation (L l (ITdocCommentNext s)) = L l (AnnDocCommentNext s)
commentToAnnotation (L l (ITdocCommentPrev s)) = L l (AnnDocCommentPrev s)
commentToAnnotation (L l (ITdocCommentNamed s)) = L l (AnnDocCommentNamed s)
commentToAnnotation (L l (ITdocSection n s)) = L l (AnnDocSection n s)
commentToAnnotation (L l (ITdocOptions s)) = L l (AnnDocOptions s)
commentToAnnotation (L l (ITdocOptionsOld s)) = L l (AnnDocOptionsOld s)
commentToAnnotation (L l (ITlineComment s)) = L l (AnnLineComment s)
commentToAnnotation (L l (ITblockComment s)) = L l (AnnBlockComment s)
commentToAnnotation _ = error $ "commentToAnnotation called for non-comment:" -- ++ show x
|
mpickering/ghc-exactprint
|
src/Language/Haskell/GHC/ExactPrint/GhcInterim.hs
|
bsd-3-clause
| 1,031 | 0 | 9 | 152 | 317 | 160 | 157 | 14 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ExistentialQuantification #-}
module Feldspar.Frontend where
import qualified Prelude as P
import Prelude (Show(..),Num(..),Eq(..),Functor(..),
Maybe(..),(.),($),error,
(++),map)
import qualified Data.Int as I
import qualified Data.Word as W
import Feldspar.Core
-- Class for embeddings on top
class Syntax a where
desug :: a -> Expr
sug :: Expr -> a
bind :: (Expr -> Expr) -> (Var, Expr)
bind f = (v,body)
where v = newVar body
body = f (Var v)
let_ :: (Syntax a, Syntax b) => a -> (a -> b) -> b
let_ a f = sug (Let v (desug a) body)
where (v,body) = bind (desug . f . sug)
parallel_ :: forall a. Syntax a => Length -> (Index -> a) -> Manifest a
parallel_ l ixf = Manifest (Parallel len v body) len
where (v,body) = bind (desug . ixf . sug)
len = desug l
for_ :: Syntax s => Length -> s -> (Index -> s -> s) -> s
for_ l init f = sug (ForLoop (desug l) (desug init) v1 v2 body)
where v2 = newVar body
v1 = v2 P.+ 1
body = desug (f (sug (Var v1)) (sug (Var v2)))
and,or :: Bool -> Bool -> Bool
and F _ = F
and _ F = F
and b c = BAnd b c
or T _ = T
or _ T = T
or b c = BOr b c
not :: Bool -> Bool
not T = F
not F = T
not (BAnd b1 b2) = BOr (not b1) (not b2)
not (BOr b1 b2) = BAnd (not b1) (not b2)
not (BXor b1 b2) = BEq b1 b2
not (BEq b1 b2) = BXor b1 b2
not (BNot b) = b
not b = BNot b
cond :: Syntax a => Bool -> a -> a -> a
cond T t _ = t
cond F _ e = e
cond b t e = sug $ If (boolToExpr b) (desug t) (desug e)
(!) :: Syntax a => Manifest a -> Index -> a
Manifest arr _ ! i = sug (Index arr (desug i))
-- P
newtype Prog a = Prog { unP :: P }
runP :: Prog a -> Index -> Manifest a
runP (Prog p) l = Manifest (RunP (desug l) p) (desug l)
(=:) :: Syntax a => Index -> a -> Prog a
i =: e = Prog (Assign (desug i) (desug e))
parFor :: Index -> (Index -> Prog a) -> Prog a
parFor l f = Prog (ParFor (integralToExpr l) v body)
where body = unP (f (IMem intTy (Var v)))
v = newVarP body
let_p :: Syntax a => a -> (a -> Prog b) -> Prog b
let_p a f = Prog (LetP v (desug a) body)
where body = unP (f (sug (Var v)))
v = newVarP body
-- Deep on Deep
type Int = Integral P.Int
type Int8 = Integral I.Int8
type Int16 = Integral I.Int16
type Int32 = Integral I.Int32
type Int64 = Integral I.Int64
type Index = Int
type Length = Int
-- http://www.cs.cmu.edu/afs/cs/academic/class/15745-s06/web/handouts/03.pdf
data Integral a = IConst a
| Add [Integral a] (Maybe a)
| Mult (Maybe a) [Integral a]
| IMem Type Expr
integralToExpr :: (Ty a,P.Integral a) => Integral a -> Expr
integralToExpr (IConst a) = Int (reify a) (P.toInteger a)
integralToExpr (Add ts mc) = P.maybe add1 add mc
where es = P.map (integralToExpr) ts
add1 = P.foldr1 (Binop Plus) es
add c = P.foldr (Binop Plus) (Int (reify c) (P.toInteger c)) es
integralToExpr (Mult mc ts) = P.maybe mul1 mul mc
where es = P.map (integralToExpr) ts
mul1 = P.foldr1 (Binop Times) es
mul c = P.foldr (Binop Times) (Int (reify c) (P.toInteger c)) es
integralToExpr (IMem ty d) = d
instance (Num a,Eq a,Ty a, P.Integral a) => Num (Integral a) where
IConst i + IConst j = IConst (i+j)
c@(IConst _) + t = t + c
t + IConst 0 = t
(Add ts mc) + (IConst c) = Add ts (mc <+ c)
(Add ts1 mc1) + (Add ts2 mc2) = Add (ts1++ts2) (mc1 <+> mc2)
(Add ts mc) + t = Add (t:ts) mc
t + (Add ts mc) = Add (t:ts) mc
t1 + t2 = Add [t1,t2] Nothing
IConst i * IConst j = IConst (i*j)
t * c@(IConst _) = c * t
IConst c * Mult mc ts = Mult (mc <* c) ts
c@(IConst i) * Add ts mc = Add (map (*c) ts) (mc <+ i)
Mult mc1 ts1 * Mult mc2 ts2 = Mult (mc1 <*> mc2) (ts1 ++ ts2)
Mult mc ts * t = Mult mc (t:ts)
t * Mult mc ts = Mult mc (t:ts)
t1 * t2 = Mult Nothing [t1,t2]
negate (IConst a) = IConst (negate a)
negate t = IMem (reify (P.undefined :: a)) (negate (integralToExpr t))
signum (IConst a) = IConst (signum a)
signum t = IMem (reify (P.undefined :: a))(signum (integralToExpr t))
abs (IConst a) = IConst (abs a)
abs t = IMem (reify (P.undefined :: a)) (abs (integralToExpr t))
fromInteger = IConst . fromInteger
Nothing <+ c = Just c
Just c1 <+ c2 = Just (c1 + c2)
Just c1 <+> Just c2 = Just (c1+c2)
Just c <+> _ = Just c
_ <+> Just c = Just c
_ <+> _ = Nothing
Nothing <* c = Just c
Just c1 <* c2 = Just (c1 * c2)
Just c1 <*> Just c2 = Just (c1 * c2)
Just c <*> _ = Just c
_ <*> Just c = Just c
_ <*> _ = Nothing
instance (Ty a, P.Integral a) => Syntax (Integral a) where
desug = integralToExpr
sug e = IMem (reify (P.undefined :: a)) e
type Double = Floating P.Double
type Float = Floating P.Float
data Floating a = FMem Expr
floatingToExpr :: Floating a -> Expr
floatingToExpr (FMem e) = e
instance Syntax (Floating a) where
desug = floatingToExpr
sug e = FMem e
-- Booleans
data Bool =
T | F | BAnd Bool Bool | BOr Bool Bool | BXor Bool Bool | BEq Bool Bool
| BNot Bool
| DBool Expr
instance Syntax Bool where
desug = boolToExpr
sug = DBool
boolToExpr :: Bool -> Expr
boolToExpr T = Boolean P.True
boolToExpr F = Boolean P.False
boolToExpr (BAnd b1 b2) = Binop And (boolToExpr b1) (boolToExpr b2)
boolToExpr (BOr b1 b2) = Binop Or (boolToExpr b1) (boolToExpr b2)
boolToExpr (BXor b1 b2) = Binop Xor (boolToExpr b1) (boolToExpr b2)
boolToExpr (BEq b1 b2) = Binop Eq (boolToExpr b1) (boolToExpr b2)
boolToExpr (BNot b) = Unop Not (boolToExpr b)
boolToExpr (DBool d) = d
-- Arrays
data Manifest a = Manifest Expr Expr
data Pull a = Pull (Index -> a) Length
data Push a = Push (forall b. Syntax b => (Index -> a -> Prog b) -> Prog b) Length
instance Functor Pull where
fmap f (Pull ixf l) = Pull (f . ixf) l
instance Functor Push where
fmap f (Push g l) = Push (\k -> g (\i a -> k i (f a))) l
class Pully vec where
toPull :: Syntax a => vec a -> Pull a
instance Pully Pull where
toPull p = p
instance Pully Manifest where
toPull m@(Manifest _ l) = Pull (\i -> m ! i) (sug l)
class Pushy vec where
toPush :: Syntax a => vec a -> Push a
instance Pushy Pull where
toPush (Pull ixf l) = Push (\k -> parFor l (\i -> k i (ixf i))) l
instance Pushy Push where
toPush push = push
instance Pushy Manifest where
toPush manifest = toPush (toPull manifest)
class Storable vec where
store :: Syntax a => vec a -> Manifest a
instance Storable Manifest where
store manifest = manifest
instance Storable Pull where
store pull = store (toPush pull)
instance Storable Push where
store (Push loop l) = runP (loop (\i a -> i =: a)) l
|
josefs/MiniDSL
|
Feldspar/Frontend.hs
|
bsd-3-clause
| 6,899 | 0 | 14 | 1,838 | 3,543 | 1,792 | 1,751 | 182 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Foreign.Inference.Interface.Metadata (
moduleInterfaceEnumerations,
moduleInterfaceStructTypes,
paramMetaUnsigned,
functionReturnMetaUnsigned,
-- * Helper
sanitizeStructName
) where
import Control.Arrow ( (&&&) )
import Data.HashMap.Strict ( HashMap )
import qualified Data.HashMap.Strict as M
import Data.HashSet ( HashSet )
import qualified Data.HashSet as HS
import qualified Data.Set as S
import Data.Maybe ( catMaybes, fromMaybe, mapMaybe )
import Data.Monoid
import Data.Text ( Text )
import qualified Data.Text as T
import Debug.Trace.LocationTH
import LLVM.Analysis
import Data.Graph.Interface
import Data.Graph.MutableDigraph
import Data.Graph.Algorithms.DFS
import Foreign.Inference.Interface.Types
-- import Text.Printf
-- import Debug.Trace
-- debug = flip trace
-- | Collect all of the enumerations used in the external interface of
-- a Module by inspecting metadata.
moduleInterfaceEnumerations :: Module -> [CEnum]
moduleInterfaceEnumerations =
S.toList . S.fromList . foldr collectEnums [] . moduleEnumMetadata
moduleInterfaceStructTypes :: Module -> [CType]
moduleInterfaceStructTypes m = opaqueTypes ++ concreteTypes
where
defFuncs = moduleDefinedFunctions m
(interfaceTypeMap, noMDTypes) = foldr extractInterfaceStructTypes (mempty, mempty) defFuncs
unifiedTypes = M.keys interfaceTypeMap
unifiedMDTypes = map (findTypeMD interfaceTypeMap) unifiedTypes
sortedUnifiedMDTypes = typeSort unifiedMDTypes
concreteTypes = map metadataStructTypeToCType sortedUnifiedMDTypes
concreteNameSet = S.fromList $ mapMaybe ctypeStructName concreteTypes
opaqueLLVMTypes = HS.toList noMDTypes
uniqueOpaqueTypeNames = HS.toList $ HS.fromList $ map structTypeName opaqueLLVMTypes
opaqueTypes0 = map toOpaqueCType uniqueOpaqueTypeNames
opaqueTypes = filter nameNotConcrete opaqueTypes0
nameNotConcrete (CStruct n _) = not (S.member n concreteNameSet)
nameNotConcrete t = $failure ("Expected struct type: " ++ show t)
-- | Collect all of the struct types (along with their metadata) used
-- in the external interface of a Module.
-- moduleInterfaceStructTypes :: Module -> HashMap Type Metadata
-- moduleInterfaceStructTypes =
-- foldr extractInterfaceStructTypes M.empty . moduleDefinedFunctions
structTypeName :: Type -> String
structTypeName (TypeStruct (Right name) _ _) = sanitizeStructName name
structTypeName (TypeStruct (Left tid) _ _) = ("anon" ++ show tid)
structTypeName t = $failure ("Expected struct type: " ++ show t)
toOpaqueCType :: String -> CType
toOpaqueCType name = CStruct name []
ctypeStructName :: CType -> Maybe String
ctypeStructName (CStruct n _) = Just n
ctypeStructName _ = Nothing
-- | Match up a type with its metadata
findTypeMD :: HashMap Type Metadata -> Type -> (Type, Metadata)
findTypeMD interfaceTypeMap t =
case M.lookup t interfaceTypeMap of
Nothing -> $failure ("No metadata found for type: " ++ show t)
Just md -> (t, md)
extractInterfaceEnumTypes :: Function -> [CEnum] -> [CEnum]
extractInterfaceEnumTypes f acc =
foldr collectEnums acc typeMds
where
retMd = functionReturnTypeMetadata f
argMds = map paramTypeMetadata (functionParameters f)
typeMds = catMaybes $ retMd : argMds
collectEnums :: Metadata -> [CEnum] -> [CEnum]
collectEnums = go Nothing
where
go _ MetaDWDerivedType { metaDerivedTypeName = bsname
, metaDerivedTypeTag = DW_TAG_typedef
, metaDerivedTypeParent = Just parent
} acc =
go (Just (T.unpack bsname)) parent acc
go name MetaDWDerivedType { metaDerivedTypeParent = Just parent } acc =
go name parent acc
go name MetaDWCompositeType { metaCompositeTypeTag = DW_TAG_enumeration_type
, metaCompositeTypeName = bsname
, metaCompositeTypeMembers = Just (MetadataList _ enums)
} acc =
case T.null bsname of
True ->
CEnum { enumName = fromMaybe "" name
, enumValues = mapMaybe toEnumeratorValue enums
} : acc
False ->
CEnum { enumName = T.unpack bsname
, enumValues = mapMaybe toEnumeratorValue enums
} : acc
go _ _ acc = acc
toEnumeratorValue :: Maybe Metadata -> Maybe (String, Int)
toEnumeratorValue (Just MetaDWEnumerator { metaEnumeratorName = ename
, metaEnumeratorValue = eval
}) =
Just (T.unpack ename, fromIntegral eval)
toEnumeratorValue _ = Nothing
extractInterfaceStructTypes :: Function
-> (HashMap Type Metadata, HashSet Type)
-> (HashMap Type Metadata, HashSet Type)
extractInterfaceStructTypes f (typeMDMap, opaqueTypes) =
(typesWithMD, otherStructs `HS.union` opaqueTypes)
where
(structsWithMD, otherStructs) = foldr toStructType (mempty, mempty) typeMds
typesWithMD = foldr addTypeMdMapping typeMDMap structsWithMD
TypeFunction rt _ _ = functionType f
retMd = functionReturnTypeMetadata f
argMds = map (argumentType &&& paramTypeMetadata) (functionParameters f)
typeMds = (rt, retMd) : argMds
addTypeMdMapping (llvmType, md) = M.insert llvmType md
toStructType :: (Type, Maybe Metadata)
-> ([(Type, Metadata)], HashSet Type)
-> ([(Type, Metadata)], HashSet Type)
toStructType (t@(TypeStruct (Right _) _ _),
Just MetaDWDerivedType { metaDerivedTypeTag = DW_TAG_typedef
, metaDerivedTypeParent = parent
}) acc =
toStructType (t, parent) acc
toStructType (t@(TypeStruct (Right _) _ _), Just a) (tms, ts) = ((t, a) : tms, ts)
toStructType (TypePointer inner _,
Just MetaDWDerivedType { metaDerivedTypeTag = DW_TAG_pointer_type
, metaDerivedTypeParent = parent
}) acc =
toStructType (inner, parent) acc
toStructType (t@(TypePointer _ _),
Just MetaDWDerivedType { metaDerivedTypeParent = parent}) acc =
toStructType (t, parent) acc
toStructType (TypePointer inner _, Nothing) acc =
toStructType (inner, Nothing) acc
toStructType (t@TypeStruct {}, Nothing) (tms, ts) =
(tms, HS.insert t ts)
toStructType _ acc = acc
sanitizeStructName :: Text -> String
sanitizeStructName = structBaseName . T.unpack
metadataStructTypeToCType :: (Type, Metadata) -> CType
metadataStructTypeToCType (TypeStruct (Right name) members _,
MetaDWCompositeType { metaCompositeTypeMembers =
Just (MetadataList _ cmembers)
}) =
let memberTypes = zip members cmembers
mtys = mapM trNameAndType memberTypes
in CStruct (sanitizeStructName name) $ fromMaybe [] mtys
where
trNameAndType (llvmType, Just MetaDWDerivedType { metaDerivedTypeName = memberName
}) = do
realType <- structMemberToCType llvmType
return (T.unpack memberName, realType)
trNameAndType _ = Nothing
-- If there were no members in the metadata, this is an opaque type
metadataStructTypeToCType (TypeStruct (Right name) _ _, _) =
CStruct (sanitizeStructName name) []
metadataStructTypeToCType t =
$failure ("Unexpected non-struct metadata: " ++ show t)
structMemberToCType :: Type -> Maybe CType
structMemberToCType t = case t of
TypeInteger i -> return $! CInt i
TypeFloat -> return CFloat
TypeDouble -> return CDouble
TypeArray n t' -> do
tt <- structMemberToCType t'
return $! CArray tt n
TypeFunction r ts _ -> do
rt <- structMemberToCType r
tts <- mapM structMemberToCType ts
return $! CFunction rt tts
TypePointer t' _ -> do
tt <- structMemberToCType t'
return $! CPointer tt
TypeStruct (Right n) _ _ ->
let name' = sanitizeStructName n
in return $! CStruct name' []
TypeStruct (Left _) ts _ -> do
tts <- mapM structMemberToCType ts
return $! CAnonStruct tts
TypeVoid -> return CVoid
TypeFP128 -> return $! CArray (CInt 8) 16
-- Fake an 80 bit floating point number with an array of 10 bytes
TypeX86FP80 -> return $! CArray (CInt 8) 10
TypePPCFP128 -> return $! CArray (CInt 8) 16
TypeX86MMX -> Nothing
TypeLabel -> Nothing
TypeMetadata -> Nothing
TypeVector _ _ -> Nothing
paramMetaUnsigned :: Argument -> Bool
paramMetaUnsigned a =
fromMaybe False $ takeFirst (argumentMetadata a) $ \md -> do
MetaDWLocal { metaLocalType = Just lt } <- return md
case lt of
MetaDWBaseType { metaBaseTypeEncoding = DW_ATE_unsigned } -> return True
MetaDWDerivedType { metaDerivedTypeParent = Just baseType } ->
case baseType of
MetaDWBaseType { metaBaseTypeEncoding = DW_ATE_unsigned } -> return True
_ -> fail "Not unsigned"
_ -> fail "Not unsigned"
takeFirst :: [b] -> (b -> Maybe a) -> Maybe a
takeFirst [] _ = Nothing
takeFirst (x:xs) f =
case f x of
Nothing -> takeFirst xs f
j -> j
paramTypeMetadata :: Argument -> Maybe Metadata
paramTypeMetadata a =
takeFirst (argumentMetadata a) $ \md -> do
MetaDWLocal { metaLocalType = lt } <- return md
lt
functionReturnMetaUnsigned :: Function -> Bool
functionReturnMetaUnsigned f =
fromMaybe False $ takeFirst (functionMetadata f) $ \md -> do
MetaDWSubprogram { metaSubprogramType = ftype } <- return md
MetaDWCompositeType { metaCompositeTypeMembers = ms } <- ftype
MetadataList _ (Just rt : _) <- ms
case rt of
MetaDWDerivedType { metaDerivedTypeParent =
Just MetaDWBaseType { metaBaseTypeEncoding = DW_ATE_unsigned }} -> return True
MetaDWBaseType { metaBaseTypeEncoding = DW_ATE_unsigned } -> return True
_ -> fail "Not unsigned"
functionReturnTypeMetadata :: Function -> Maybe Metadata
functionReturnTypeMetadata f = takeFirst (functionMetadata f) $ \md -> do
MetaDWSubprogram { metaSubprogramType =
Just (MetaDWCompositeType { metaCompositeTypeMembers =
Just (MetadataList _ (rt : _)) }) } <- return md
rt
type TypeGraph = SparseDigraph (Type, Metadata) ()
-- | All of the components of a type that are stored by-value must be
-- defined before that type can be defined. This is a topological
-- ordering captured by this graph-based sort.
typeSort :: [(Type, Metadata)] -> [(Type, Metadata)]
typeSort ts = reverse $ topsort' g
where
g :: TypeGraph
g = mkGraph ns es
toNodeMap = M.fromList (zip (map fst ts) [0..])
ns = zip [0..] ts
es = concatMap toEdges ts
toEdges (t@(TypeStruct _ members _), _) =
case M.lookup t toNodeMap of
Nothing -> $failure ("Expected node id for type: " ++ show t)
Just srcid -> mapMaybe (toEdge srcid) members
toEdges _ = []
toEdge srcid t = do
dstid <- M.lookup t toNodeMap
return $! Edge srcid dstid ()
{-# ANN module "HLint: ignore Use if" #-}
|
travitch/foreign-inference
|
src/Foreign/Inference/Interface/Metadata.hs
|
bsd-3-clause
| 11,088 | 0 | 22 | 2,713 | 3,045 | 1,574 | 1,471 | 228 | 16 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeFamilies #-}
module Horbits.Time.KerbalDateTime
(KerbalTimeComponents, KerbalTime'(), KerbalTime, KerbalInstant'(), KerbalInstant, isoFracSeconds,
timeComponents, secondsFraction, seconds, minutes, hours, days, years, duration, epoch, isoTime, isoInstant)
where
import Control.Lens hiding ((*~))
import Data.List (unfoldr)
import Linear.Affine
import Linear.Vector (Additive (..))
import Horbits.Dimensional.Prelude (Time, dim)
-- TODO epoch should be P (KerbalTime' 0), shouldn't it?
newtype KerbalTime' a = KerbalTime' { fractionalSeconds :: a } deriving (Show, Eq, Ord, Functor)
type KerbalTime = KerbalTime' Double
type KerbalInstant' = Point KerbalTime'
type KerbalInstant = KerbalInstant' Double
class KerbalTimeComponents t where
timeComponents :: RealFrac a => Iso' (t a) (a, [Integer])
secondsFraction :: RealFrac a => Lens' (t a) a
secondsFraction = timeComponents . _1
timeComponentLens :: RealFrac a => Int -> Lens' (t a) Integer
timeComponentLens i = timeComponents . _2 . singular (element i)
seconds :: RealFrac a => Lens' (t a) Integer
seconds = timeComponentLens 0
minutes :: RealFrac a => Lens' (t a) Integer
minutes = timeComponentLens 1
hours :: RealFrac a => Lens' (t a) Integer
hours = timeComponentLens 2
days :: RealFrac a => Lens' (t a) Integer
days = timeComponentLens 3
years :: RealFrac a => Lens' (t a) Integer
years = timeComponentLens 4
instance KerbalTimeComponents KerbalTime' where
timeComponents = isoFracSeconds . iso toParts fromParts
instance KerbalTimeComponents KerbalInstant' where
timeComponents = relative (origin .-^ epochOffset) . timeComponents
epochOffset :: RealFrac a => KerbalTime' a
epochOffset = zero & years .~ 1 & days .~ 1
epoch :: RealFrac a => KerbalInstant' a
epoch = origin
duration :: Iso' KerbalTime (Time Double)
duration = isoFracSeconds . dim
isoFracSeconds :: Iso' (KerbalTime' a) a
isoFracSeconds = iso fractionalSeconds KerbalTime'
instance Additive KerbalTime' where
zero = KerbalTime' 0
liftU2 = _lift
liftI2 = _lift
_lift :: (a -> b -> c) -> KerbalTime' a -> KerbalTime' b -> KerbalTime' c
_lift f (KerbalTime' a) (KerbalTime' b) = KerbalTime' $ f a b
type DecompState a = Maybe (a, [a])
decompose :: Integral a => DecompState a -> Maybe (a, DecompState a)
decompose Nothing = Nothing
decompose (Just (n, [])) = Just (n, Nothing)
decompose (Just (n, d:ds)) = Just (n `mod` d, Just (n `div` d, ds))
temporalSubdivisions :: Integral a => [a]
temporalSubdivisions = [ 60, 60, 6, 426 ]
smhdy :: Integral a => a -> [a]
smhdy n = unfoldr decompose $ Just (n, temporalSubdivisions)
fromSmhdy :: Integral a => [a] -> a
fromSmhdy ips = foldr (\(c, n) x -> c * (x + n)) 0 $ zip (1 : temporalSubdivisions) ips
toParts :: RealFrac a => a -> (a, [Integer])
toParts x = (f, smhdy i)
where (i, f) = properFraction x
fromParts :: Num a => (a, [Integer]) -> a
fromParts (f, ips) = f + fromIntegral (fromSmhdy ips)
isoTime :: Iso' (KerbalTime' a) (Time a)
isoTime = isoFracSeconds . dim
isoInstant :: RealFrac a => Iso' (KerbalInstant' a) (Time a)
isoInstant = relative epoch . isoTime
|
chwthewke/horbits
|
src/horbits/Horbits/Time/KerbalDateTime.hs
|
bsd-3-clause
| 3,512 | 0 | 11 | 781 | 1,197 | 642 | 555 | 77 | 1 |
module ParserTests(allParserTests) where
import CoreSyntax
import Lexer
import Parser
import TestUtils
import UniversalSyntax
allParserTests = do
testFunction (parseExpr . strToToks) parseExprCases
cve = cVarExpr . var
dcFalse = cDataCon (dataCon "False") []
dcTrue = cDataCon (dataCon "True") []
iLit = cLitExpr . intLit
parseExprCases =
[("1", iLit 1),
("1 - 4", cAp (cAp (cve "-") (iLit 1)) (iLit 4)),
("3 * 3", cAp (cAp (cve "*") (iLit 3)) (iLit 3)),
("5 / 873", cAp (cAp (cve "/") (iLit 5)) (iLit 873)),
("x / 4", cAp (cAp (cve "/") (cve "x")) (iLit 4)),
("1 + 7", cAp (cAp (cve "+") (iLit 1)) (iLit 7)),
("2 /(4 + 2)",
cAp (cAp (cve "/") (iLit 2)) (cAp (cAp (cve "+") (iLit 4)) (iLit 2))),
("f 2 y", cAp (cAp (cve "f") (iLit 2)) (cve "y")),
("f 2 (+) 1", cAp (cAp (cAp (cve "f") (iLit 2)) (cve "+")) (iLit 1)),
("f (2 *4) / 4",
cAp (cAp (cve "/") (cAp (cve "f") (cAp (cAp (cve "*") (iLit 2)) (iLit 4)))) (iLit 4)),
("True", cDataCon (dataCon "True") []),
("False", cDataCon (dataCon "False") []),
("~True", cAp (cve "~") dcTrue),
("f True (~False)", cAp (cAp (cve "f") dcTrue) (cAp (cve "~") dcFalse)),
("True || False", cAp (cAp (cve "||") dcTrue) dcFalse),
("False && x", cAp (cAp (cve "&&") dcFalse) (cve "x")),
("x || ~(y && z)",
cAp (cAp (cve "||") (cve "x")) (cAp (cve "~") (cAp (cAp (cve "&&") (cve "y")) (cve "z")))),
("x < y", cAp (cAp (cve "<") (cve "x")) (cve "y")),
("1 > 2", cAp (cAp (cve ">") (iLit 1)) (iLit 2)),
("x <= y", cAp (cAp (cve "<=") (cve "x")) (cve "y")),
("k2 >= k43", cAp (cAp (cve ">=") (cve "k2")) (cve "k43")),
("q == z", cAp (cAp (cve "==") (cve "q")) (cve "z")),
("f (==) (<) 23", cAp (cAp (cAp (cve "f") (cve "==")) (cve "<")) (iLit 23)),
("case 2 > k of | True -> 6 + 3 | False -> f (+) y",
cCase (cAp (cAp (cve ">") (iLit 2)) (cve "k"))
[cDataAlt (dataCon "True") [] (cAp (cAp (cve "+") (iLit 6)) (iLit 3)),
cDataAlt (dataCon "False") [] (cAp (cAp (cve "f") (cve "+")) (cve "y"))]),
("\\ x y z -> x + (case 5 <= y of | True -> x | 234 -> z)",
cLam (var "x") (cLam (var "y") (cLam (var "z") (cAp (cAp (cve "+") (cve "x")) (cCase (cAp (cAp (cve "<=") (iLit 5)) (cve "y")) [cDataAlt (dataCon "True") [] (cve "x"), cLitAlt (intLit 234) (cve "z")]))))),
("let qWerty = 45, x = f 1, uIO3 = False in x uIO3 qWerty",
cLet [coreDecl (var "qWerty") (iLit 45), coreDecl (var "x") (cAp (cve "f") (iLit 1)), coreDecl (var "uIO3") dcFalse] (cAp (cAp (cve "x") (cve "uIO3")) (cve "qWerty")))]
|
dillonhuff/AFL
|
test/ParserTests.hs
|
bsd-3-clause
| 2,536 | 0 | 21 | 569 | 1,493 | 778 | 715 | 47 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
module VisualizationData.Queue.RealTime where
import VisualizationData.Queue.Interface
import VisualizationData.Thunk
import Control.Arrow (second)
data LazyListThunk a
= AppendReverseThunk !(LazyListRef a) !(LazyList a) ![a]
data LazyList a
= Nil
| Cons !a !(LazyListRef a)
type LazyListRef a = Thunk (LazyListThunk a) (LazyList a)
lazyListFromList :: [a] -> LazyListRef a
lazyListFromList =
\case
[] ->
wrapThunk Nil
(x:xs) ->
wrapThunk (Cons x (lazyListFromList xs))
toWHNF :: LazyListThunk a -> LazyList a
toWHNF (AppendReverseThunk xs rs ys) =
case (forceWHNF xs, ys) of
(Nil, []) -> rs
(Cons x xs', y:ys') ->
Cons x $ createThunk $ AppendReverseThunk xs' (Cons y (wrapThunk rs)) ys'
forceWHNF :: LazyListRef a -> LazyList a
forceWHNF = forceThunk toWHNF
evalStep :: LazyListRef a -> Maybe (LazyListRef a)
evalStep ref =
case forceWHNF ref of
Nil -> Nothing
Cons _ ref' -> Just ref'
forceLazyList :: LazyListRef a -> [a]
forceLazyList xs =
case forceWHNF xs of
Nil -> []
Cons x xs' -> x : forceLazyList xs'
-- this is the same as forceLazyList but without the side-effect of evaluating the thunks
lazyListToList :: LazyListRef a -> [a]
lazyListToList ref =
case either toWHNF id (readThunk ref) of
Nil -> []
Cons x xs -> x : lazyListToList xs
data RTQueue a =
RTQueue
{ frontList :: !(LazyListRef a)
, frontLen :: !Int
, rearList :: ![a]
, rearLen :: !Int
, schedule :: !(LazyListRef a)
, scheduleStepNeeded :: !Bool
}
scheduleIndex :: RTQueue a -> Int
scheduleIndex queue =
rearLen queue - (if scheduleStepNeeded queue then 1 else 0)
instance Show a => Show (RTQueue a) where
show queue =
"fromList (" ++ show (toList queue) ++ ")"
instance Eq a => Eq (RTQueue a) where
xs == ys =
toList xs == toList ys
instance Queue RTQueue where
qempty = empty
qsnoc = snoc
quncons = uncons
-- it is important to implement this manually, because the default implementation via quncons has the side-effect of evaluating thunks
qnull q = frontLen q == 0
empty :: RTQueue a
empty =
let
front = wrapThunk Nil
in
RTQueue
{ frontList = front
, frontLen = 0
, rearList = []
, rearLen = 0
, schedule = front
, scheduleStepNeeded = False
}
null :: RTQueue a -> Bool
null rtq = frontLen rtq == 0
toList :: RTQueue a -> [a]
toList rtq = lazyListToList (frontList rtq) ++ reverse (rearList rtq)
schedStep :: RTQueue a -> RTQueue a
schedStep rtq =
if scheduleStepNeeded rtq then
case forceWHNF (schedule rtq) of
Nil -> rtq
Cons _ sched' ->
rtq { schedule = sched', scheduleStepNeeded = False }
else
rtq
-- without scheduled step!
mkRTQueue :: LazyListRef a -> Int -> [a] -> Int -> LazyListRef a -> RTQueue a
mkRTQueue front frontL rear rearL sched =
if frontL > rearL then
RTQueue front frontL rear rearL sched True
else
let
front' = createThunk (AppendReverseThunk front Nil rear)
in
RTQueue front' (frontL + rearL) [] 0 front' False
fromList :: [a] -> RTQueue a
fromList xs =
let
front = lazyListFromList xs
in
RTQueue
{ frontList = front
, frontLen = length xs
, rearList = []
, rearLen = 0
, schedule = front
, scheduleStepNeeded = False
}
uncons' :: RTQueue a -> Maybe (a, RTQueue a)
uncons' (schedStep -> RTQueue front frontL rear rearL sched _) =
case forceWHNF front of
Nil ->
Nothing
Cons x front' ->
Just (x, mkRTQueue front' (frontL-1) rear rearL sched)
uncons :: RTQueue a -> Maybe (a, RTQueue a)
uncons queue =
second schedStep <$> uncons' queue
head :: RTQueue a -> Maybe a
head q =
fst <$> uncons q
tail' :: RTQueue a -> Maybe (RTQueue a)
tail' =
fmap snd . uncons'
tail :: RTQueue a -> Maybe (RTQueue a)
tail q =
snd <$> uncons q
snoc' :: RTQueue a -> a -> RTQueue a
snoc' (schedStep -> RTQueue front frontL rear rearL sched _) x =
if frontL == 0 then
let
front' = lazyListFromList [x]
in
RTQueue front' 1 [] 0 front' False
else
mkRTQueue front frontL (x:rear) (rearL+1) sched
snoc :: RTQueue a -> a -> RTQueue a
snoc queue x =
schedStep (snoc' queue x)
|
timjb/pfds-visualizations
|
src/VisualizationData/Queue/RealTime.hs
|
bsd-3-clause
| 4,313 | 0 | 13 | 1,076 | 1,547 | 786 | 761 | 157 | 3 |
{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -fcontext-stack=22 #-}
module Main (main) where
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Criterion
import Criterion.Main (defaultMain)
import Data.Array.ST
import Data.Tuple.ITuple
import Data.Tuple.ST
import Data.Var.ST
main :: IO ()
main = defaultMain
[ bench "tuples" $ nf tuples 70000
, bench "vars" $ nf vars 70000
, bench "arrays" $ nf arrays 70000
]
data Tuple7 s a b c d e f g =
Tuple7
{-# UNPACK #-} !(STVar s a)
{-# UNPACK #-} !(STVar s b)
{-# UNPACK #-} !(STVar s c)
{-# UNPACK #-} !(STVar s d)
{-# UNPACK #-} !(STVar s e)
{-# UNPACK #-} !(STVar s f)
{-# UNPACK #-} !(STVar s g)
vars :: Int -> [(Int, Int, Int, Int, Int, Int, Int)]
vars n = runST $ do
vs <- replicateM (n `div` 7) $
Tuple7
<$> newSTVar n
<*> newSTVar n
<*> newSTVar n
<*> newSTVar n
<*> newSTVar n
<*> newSTVar n
<*> newSTVar n
let n' = n + 1
forM_ vs $ \ (Tuple7 a b c d e f g) -> do
writeVar a n'
writeVar b n'
writeVar c n'
writeVar d n'
writeVar e n'
writeVar f n'
writeVar g n'
forM vs $ \ (Tuple7 a b c d e f g) ->
(,,,,,,)
<$> readVar a
<*> readVar b
<*> readVar c
<*> readVar d
<*> readVar e
<*> readVar f
<*> readVar g
newSTVar :: a -> ST s (STVar s a)
newSTVar = newVar
tuples :: Int -> [(Int, Int, Int, Int, Int, Int, Int)]
tuples n = runST $ do
vs <- replicateM (n `div` 7) $ newSTTuple (n, n, n, n, n, n, n)
let n' = n + 1
forM_ vs $ \ v -> do
write1 v n'
write2 v n'
write3 v n'
write4 v n'
write5 v n'
write6 v n'
write7 v n'
forM vs $ \ v ->
(,,,,,,)
<$> read1 v
<*> read2 v
<*> read3 v
<*> read4 v
<*> read5 v
<*> read6 v
<*> read7 v
newSTTuple :: (ITuple a, ArraySlice (Tuple (ListRep a))) => a -> ST s (STTuple s a)
newSTTuple = thawTuple
arrays :: Int -> [(Int, Int, Int, Int, Int, Int, Int)]
arrays n = runST $ do
vs <- replicateM (n `div` 7) $ newSTArray (1 :: Int, 7) n
let n' = n + 1
forM_ vs $ \ v -> do
writeArray v 1 n'
writeArray v 2 n'
writeArray v 3 n'
writeArray v 4 n'
writeArray v 5 n'
writeArray v 6 n'
writeArray v 7 n'
forM vs $ \ v ->
(,,,,,,)
<$> readArray v 1
<*> readArray v 2
<*> readArray v 3
<*> readArray v 4
<*> readArray v 5
<*> readArray v 6
<*> readArray v 7
newSTArray :: (Ix i, MArray (STArray s) e (ST s)) => (i, i) -> e -> ST s (STArray s i e)
newSTArray = newArray
|
sonyandy/var
|
benchmarks/boxed.hs
|
bsd-3-clause
| 2,574 | 0 | 19 | 782 | 1,200 | 605 | 595 | 103 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Static.Array
( module Static.Array
, module Static.Measure
, U, D
) where
import Static.Measure
import Util
import Data.Array.Repa as R hiding ((++))
import Data.Array.Repa.Unsafe as R
import Data.Array.Repa.Algorithms.Randomish as R
import Data.Monoid
import Data.Proxy
import qualified Data.Vector.Unboxed as U
import Data.Serialize
import Data.Vector.Serialize ()
newtype SArray r (s :: SMeasure) = SArray (R.Array r (ShapeOf s) Double)
instance Measure s => Show (SArray U s) where
show (SArray arr)
| size (extent arr) <= 10000 = "Static " <> show arr
| otherwise = "Static Array of size " <> show (extent arr)
instance Measure s => Show (SArray D s) where
show (SArray arr)
| size (extent arr) <= 10000 = "Delayed Static " <> show (computeS arr :: R.Array U (ShapeOf s ) Double)
| otherwise = "Delayed Static Array of size " <> show (extent arr)
instance Measure s => Serialize (SArray U s) where
put (SArray arr) = put (toUnboxed arr)
get = do arr <- get
return$ sFromUnboxed arr
instance Measure s => Creatable (SArray U s) where
{-# INLINE seeded #-}
seeded s = sRandom s (-1) 1
{-# INLINE sFromFunction #-}
sFromFunction :: forall s. Measure s => (ShapeOf s -> Double) -> SArray D s
sFromFunction f = SArray $ fromFunction sh f
where
sh = mExtent (Proxy :: Proxy s)
{-# INLINE sZipWith #-}
sZipWith :: (Measure s, Source r1 Double, Source r2 Double)
=> (Double -> Double -> Double)
-> SArray r1 s
-> SArray r2 s
-> SArray D s
sZipWith f (SArray arr1) (SArray arr2) = SArray $ R.zipWith f arr1 arr2
{-# INLINE sMap #-}
sMap :: (Source r Double, Measure s)
=> (Double -> Double)
-> SArray r s
-> SArray D s
sMap f (SArray arr) = SArray $ R.map f arr
{-# INLINE sComputeP #-}
sComputeP :: (Monad m, Measure s)
=> SArray D s
-> m (SArray U s)
sComputeP (SArray arr) = SArray <$> computeP arr
{-# INLINE sComputeS #-}
sComputeS :: Measure s
=> SArray D s
-> SArray U s
sComputeS (SArray arr) = SArray $ computeS arr
{-# INLINE (%*) #-}
{-# INLINE (%+) #-}
{-# INLINE (%-) #-}
{-# INLINE (%/) #-}
(%*), (%+), (%-), (%/) :: (Measure s, Source r2 Double, Source r1 Double)
=> SArray r1 s
-> SArray r2 s
-> SArray D s
a %* b = sZipWith (*) a b
a %/ b = sZipWith (/) a b
a %+ b = sZipWith (+) a b
a %- b = sZipWith (-) a b
{-# INLINE sSumAllP #-}
sSumAllP :: (Source r Double, Measure s, Monad m)
=> SArray r s
-> m Double
sSumAllP (SArray a) = sumAllP a
{-# INLINE sSumAllS #-}
sSumAllS :: (Source r Double, Measure s)
=> SArray r s
-> Double
sSumAllS (SArray a) = sumAllS a
-- | Watch out: fromUnboxed, and sbFromUnboxed do not perform length checks.
-- You are advised to use sMapVector
{-# INLINE sFromUnboxed #-}
sFromUnboxed :: forall s.Measure s => U.Vector Double -> SArray U s
sFromUnboxed vec
| size sh == U.length vec = arr
| otherwise = error$ "sFromUnboxed expected length " ++ show (size sh) ++ ", actual length " ++ show (U.length vec)
where sh = mExtent (Proxy :: Proxy s)
arr = SArray $ fromUnboxed sh vec
{-# INLINE sVectorMap #-}
sVectorMap :: Measure s
=> (U.Vector Double -> U.Vector Double)
-> SArray U s
-> SArray U s
sVectorMap vf (SArray arr)
| U.length vec == U.length vec' = (sFromUnboxed vec')
| otherwise = error "Vector function did not preserve length"
where
vec = toUnboxed arr
vec' = vf vec
{-# INLINE sReshape #-}
sReshape :: forall r s1 s2.
( Source r Double
, Size s1 ~ Size s2 -- GHC says this is redundant, GHC is wrong.
, Measure s1
, Measure s2
)
=> SArray r s1
-> SArray D s2
sReshape (SArray x) = SArray $ reshape sh x
where
sh = mExtent (Proxy :: Proxy s2)
sRandom :: forall s. Measure s => Int -> Double -> Double -> SArray U s
sRandom seed min max = SArray $ R.randomishDoubleArray sh min max seed
where
sh = mExtent (Proxy :: Proxy s)
sZeros :: forall s. Measure s => SArray U s
sZeros = SArray . computeS $ fromFunction sh (const 0)
where
sh = mExtent (Proxy :: Proxy s)
{-# INLINE sExpand #-}
sExpand :: forall sml big r1. (sml `Suffix` big, Source r1 Double)
=> SArray r1 sml
-> SArray D big
sExpand (SArray src) = SArray $ unsafeBackpermute sh expand src
where sh = mExtent (Proxy :: Proxy big)
{-# INLINE sBackpermute #-}
sBackpermute :: forall s1 s2 r. (Source r Double, Measure s1, Measure s2)
=> (ShapeOf s2 -> ShapeOf s1)
-> SArray r s1
-> SArray D s2
sBackpermute f (SArray arr) = SArray$ unsafeBackpermute sh f arr
where sh = mExtent (Proxy :: Proxy s2)
{-# INLINE sTraverse #-}
sTraverse :: forall s1 s2 r.
(Source r Double, Measure s1, Measure s2)
=> SArray r s1
-> ((ShapeOf s1 -> Double) -> ShapeOf s2 -> Double)
-> SArray D s2
sTraverse (SArray arr) f = SArray$ R.unsafeTraverse arr (const sh) f
where sh = mExtent (Proxy :: Proxy s2)
sConcat :: Measure s2 => [SArray U s1] -> SArray U s2
sConcat sarrs = sFromUnboxed . U.concat . fmap (toUnboxed.unwrap) $ sarrs
where
unwrap (SArray arr) = arr
sHead :: (Measure s, Source r Double) => SArray r s -> Double
sHead (SArray arr) = linearIndex arr 1
|
jonascarpay/convoluted
|
src/Static/Array.hs
|
bsd-3-clause
| 5,611 | 0 | 13 | 1,501 | 2,043 | 1,049 | 994 | -1 | -1 |
module Network.Mail.Postie.Settings
( Settings (..),
TLSSettings (..),
StartTLSPolicy (..),
settingsStartTLSPolicy,
defaultExceptionHandler,
mkServerParams,
def,
-- | reexport from Default class
)
where
import Control.Applicative
import Control.Exception
import Data.ByteString (ByteString)
import Data.Default.Class
import GHC.IO.Exception (IOErrorType (..))
import Network.Socket (HostName, PortNumber, SockAddr)
import qualified Network.TLS as TLS
import qualified Network.TLS.Extra.Cipher as TLS
import System.IO (hPrint, stderr)
import System.IO.Error (ioeGetErrorType)
import Network.Mail.Postie.Address
import Network.Mail.Postie.SessionID
import Network.Mail.Postie.Types
import Prelude
-- | Settings to configure posties behaviour.
data Settings
= Settings
{ -- | Port postie will run on.
settingsPort :: PortNumber,
-- | Timeout for connections in seconds
settingsTimeout :: Int,
-- | Maximal size of incoming mail data
settingsMaxDataSize :: Int,
-- | Hostname which is shown in posties greeting.
settingsHost :: Maybe HostName,
-- | TLS settings if you wish to secure connections.
settingsTLS :: Maybe TLSSettings,
-- | Whether authentication is required
settingsRequireAuth :: Bool,
-- | Exception handler (default is defaultExceptionHandler)
settingsOnException :: Maybe SessionID -> SomeException -> IO (),
-- | Action will be performed before main processing begins.
settingsBeforeMainLoop :: IO (),
-- | Action will be performed when connection has been opened.
settingsOnOpen :: SessionID -> SockAddr -> IO (),
-- | Action will be performed when connection has been closed.
settingsOnClose :: SessionID -> IO (),
-- | Action will be performend on STARTTLS command.
settingsOnStartTLS :: SessionID -> IO (),
-- | Performed when client says hello
settingsOnHello :: SessionID -> ByteString -> IO HandlerResponse,
-- | Performed when client authenticates
settingsOnAuth :: SessionID -> ByteString -> IO HandlerResponse,
-- | Performed when client starts mail transaction
settingsOnMailFrom :: SessionID -> Address -> IO HandlerResponse,
-- | Performed when client adds recipient to mail transaction.
settingsOnRecipient :: SessionID -> Address -> IO HandlerResponse
}
instance Default Settings where
def = defaultSettings
-- | Default settings for postie
defaultSettings :: Settings
defaultSettings =
Settings
{ settingsPort = 3001,
settingsTimeout = 1800,
settingsMaxDataSize = 32000,
settingsHost = Nothing,
settingsTLS = Nothing,
settingsRequireAuth = False,
settingsOnException = defaultExceptionHandler,
settingsBeforeMainLoop = return (),
settingsOnOpen = \_ _ -> return (),
settingsOnClose = const $ return (),
settingsOnStartTLS = const $ return (),
settingsOnAuth = void,
settingsOnHello = void,
settingsOnMailFrom = void,
settingsOnRecipient = void
}
where
void _ _ = return Accepted
-- | Settings for TLS handling
data TLSSettings
= TLSSettings
{ -- | Path to certificate file
certFile :: FilePath,
-- | Path to private key file belonging to certificate
keyFile :: FilePath,
-- | Connection security mode, default is DemandStartTLS
security :: StartTLSPolicy,
-- | Logging for TLS
tlsLogging :: TLS.Logging,
-- | Supported TLS versions
tlsAllowedVersions :: [TLS.Version],
-- | Supported ciphers
tlsCiphers :: [TLS.Cipher]
}
instance Default TLSSettings where
def = defaultTLSSettings
-- | Connection security policy, either via STARTTLS command or on connection initiation.
data StartTLSPolicy
= -- | Allows clients to use STARTTLS command
AllowStartTLS
| -- | Client needs to send STARTTLS command before issuing a mail transaction
DemandStartTLS
| -- | Negotiates a TSL context on connection startup.
ConnectWithTLS
deriving (Eq, Show)
defaultTLSSettings :: TLSSettings
defaultTLSSettings =
TLSSettings
{ certFile = "certificate.pem",
keyFile = "key.pem",
security = DemandStartTLS,
tlsLogging = def,
tlsAllowedVersions = [TLS.SSL3, TLS.TLS10, TLS.TLS11, TLS.TLS12],
tlsCiphers = TLS.ciphersuite_default
}
settingsStartTLSPolicy :: Settings -> Maybe StartTLSPolicy
settingsStartTLSPolicy settings = security `fmap` settingsTLS settings
mkServerParams :: TLSSettings -> IO TLS.ServerParams
mkServerParams tlsSettings = do
credentials <- loadCredentials
return
def
{ TLS.serverShared =
def
{ TLS.sharedCredentials = TLS.Credentials [credentials]
},
TLS.serverSupported =
def
{ TLS.supportedCiphers = tlsCiphers tlsSettings,
TLS.supportedVersions = tlsAllowedVersions tlsSettings
}
}
where
loadCredentials =
either (throw . TLS.Error_Certificate) id
<$> TLS.credentialLoadX509 (certFile tlsSettings) (keyFile tlsSettings)
defaultExceptionHandler :: Maybe SessionID -> SomeException -> IO ()
defaultExceptionHandler _ e = throwIO e `catches` handlers
where
handlers = [Handler ah, Handler oh, Handler tlsh, Handler th, Handler sh]
ah :: AsyncException -> IO ()
ah ThreadKilled = return ()
ah x = hPrint stderr x
oh :: IOException -> IO ()
oh x
| et == ResourceVanished || et == InvalidArgument = return ()
| otherwise = hPrint stderr x
where
et = ioeGetErrorType x
tlsh :: TLS.TLSException -> IO ()
tlsh TLS.Terminated {} = return ()
tlsh TLS.HandshakeFailed {} = return ()
tlsh x = hPrint stderr x
th :: TLS.TLSError -> IO ()
th TLS.Error_EOF = return ()
th (TLS.Error_Packet_Parsing _) = return ()
th (TLS.Error_Packet _) = return ()
th (TLS.Error_Protocol _) = return ()
th x = hPrint stderr x
sh :: SomeException -> IO ()
sh = hPrint stderr
|
alexbiehl/postie
|
src/Network/Mail/Postie/Settings.hs
|
bsd-3-clause
| 6,155 | 0 | 13 | 1,527 | 1,276 | 721 | 555 | 124 | 8 |
{-# language CPP #-}
-- | = Name
--
-- VK_KHR_depth_stencil_resolve - device extension
--
-- == VK_KHR_depth_stencil_resolve
--
-- [__Name String__]
-- @VK_KHR_depth_stencil_resolve@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 200
--
-- [__Revision__]
-- 1
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- - Requires @VK_KHR_create_renderpass2@
--
-- [__Deprecation state__]
--
-- - /Promoted/ to
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.2-promotions Vulkan 1.2>
--
-- [__Contact__]
--
-- - Jan-Harald Fredriksen
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_depth_stencil_resolve] @janharald%0A<<Here describe the issue or question you have about the VK_KHR_depth_stencil_resolve extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2018-04-09
--
-- [__Interactions and External Dependencies__]
--
-- - Promoted to Vulkan 1.2 Core
--
-- [__Contributors__]
--
-- - Jan-Harald Fredriksen, Arm
--
-- - Andrew Garrard, Samsung Electronics
--
-- - Soowan Park, Samsung Electronics
--
-- - Jeff Bolz, NVIDIA
--
-- - Daniel Rakos, AMD
--
-- == Description
--
-- This extension adds support for automatically resolving multisampled
-- depth\/stencil attachments in a subpass in a similar manner as for color
-- attachments.
--
-- Multisampled color attachments can be resolved at the end of a subpass
-- by specifying @pResolveAttachments@ entries corresponding to the
-- @pColorAttachments@ array entries. This does not allow for a way to map
-- the resolve attachments to the depth\/stencil attachment. The
-- 'Vulkan.Core10.CommandBufferBuilding.cmdResolveImage' command does not
-- allow for depth\/stencil images. While there are other ways to resolve
-- the depth\/stencil attachment, they can give sub-optimal performance.
-- Extending the
-- 'Vulkan.Core12.Promoted_From_VK_KHR_create_renderpass2.SubpassDescription2'
-- in this extension allows an application to add a
-- @pDepthStencilResolveAttachment@, that is similar to the color
-- @pResolveAttachments@, that the @pDepthStencilAttachment@ can be
-- resolved into.
--
-- Depth and stencil samples are resolved to a single value based on the
-- resolve mode. The set of possible resolve modes is defined in the
-- 'Vulkan.Core12.Enums.ResolveModeFlagBits.ResolveModeFlagBits' enum. The
-- 'Vulkan.Core12.Enums.ResolveModeFlagBits.RESOLVE_MODE_SAMPLE_ZERO_BIT'
-- mode is the only mode that is required of all implementations (that
-- support the extension or support Vulkan 1.2 or higher). Some
-- implementations may also support averaging (the same as color sample
-- resolve) or taking the minimum or maximum sample, which may be more
-- suitable for depth\/stencil resolve.
--
-- == Promotion to Vulkan 1.2
--
-- All functionality in this extension is included in core Vulkan 1.2, with
-- the KHR suffix omitted. The original type, enum and command names are
-- still available as aliases of the core functionality.
--
-- == New Structures
--
-- - Extending
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2':
--
-- - 'PhysicalDeviceDepthStencilResolvePropertiesKHR'
--
-- - Extending
-- 'Vulkan.Core12.Promoted_From_VK_KHR_create_renderpass2.SubpassDescription2':
--
-- - 'SubpassDescriptionDepthStencilResolveKHR'
--
-- == New Enums
--
-- - 'ResolveModeFlagBitsKHR'
--
-- == New Bitmasks
--
-- - 'ResolveModeFlagsKHR'
--
-- == New Enum Constants
--
-- - 'KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME'
--
-- - 'KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION'
--
-- - Extending
-- 'Vulkan.Core12.Enums.ResolveModeFlagBits.ResolveModeFlagBits':
--
-- - 'RESOLVE_MODE_AVERAGE_BIT_KHR'
--
-- - 'RESOLVE_MODE_MAX_BIT_KHR'
--
-- - 'RESOLVE_MODE_MIN_BIT_KHR'
--
-- - 'RESOLVE_MODE_NONE_KHR'
--
-- - 'RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR'
--
-- - 'STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR'
--
-- == Version History
--
-- - Revision 1, 2018-04-09 (Jan-Harald Fredriksen)
--
-- - Initial revision
--
-- == See Also
--
-- 'PhysicalDeviceDepthStencilResolvePropertiesKHR',
-- 'ResolveModeFlagBitsKHR', 'ResolveModeFlagsKHR',
-- 'SubpassDescriptionDepthStencilResolveKHR'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_KHR_depth_stencil_resolve Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_KHR_depth_stencil_resolve ( pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR
, pattern STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR
, pattern RESOLVE_MODE_NONE_KHR
, pattern RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR
, pattern RESOLVE_MODE_AVERAGE_BIT_KHR
, pattern RESOLVE_MODE_MIN_BIT_KHR
, pattern RESOLVE_MODE_MAX_BIT_KHR
, ResolveModeFlagsKHR
, ResolveModeFlagBitsKHR
, PhysicalDeviceDepthStencilResolvePropertiesKHR
, SubpassDescriptionDepthStencilResolveKHR
, KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION
, pattern KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION
, KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME
, pattern KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME
) where
import Data.String (IsString)
import Vulkan.Core12.Promoted_From_VK_KHR_depth_stencil_resolve (PhysicalDeviceDepthStencilResolveProperties)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Promoted_From_VK_KHR_depth_stencil_resolve (SubpassDescriptionDepthStencilResolve)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_AVERAGE_BIT))
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_MAX_BIT))
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_MIN_BIT))
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_NONE))
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlags)
import Vulkan.Core12.Enums.ResolveModeFlagBits (ResolveModeFlagBits(RESOLVE_MODE_SAMPLE_ZERO_BIT))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE))
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR"
pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR = STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR"
pattern STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE_KHR = STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE
-- No documentation found for TopLevel "VK_RESOLVE_MODE_NONE_KHR"
pattern RESOLVE_MODE_NONE_KHR = RESOLVE_MODE_NONE
-- No documentation found for TopLevel "VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR"
pattern RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR = RESOLVE_MODE_SAMPLE_ZERO_BIT
-- No documentation found for TopLevel "VK_RESOLVE_MODE_AVERAGE_BIT_KHR"
pattern RESOLVE_MODE_AVERAGE_BIT_KHR = RESOLVE_MODE_AVERAGE_BIT
-- No documentation found for TopLevel "VK_RESOLVE_MODE_MIN_BIT_KHR"
pattern RESOLVE_MODE_MIN_BIT_KHR = RESOLVE_MODE_MIN_BIT
-- No documentation found for TopLevel "VK_RESOLVE_MODE_MAX_BIT_KHR"
pattern RESOLVE_MODE_MAX_BIT_KHR = RESOLVE_MODE_MAX_BIT
-- No documentation found for TopLevel "VkResolveModeFlagsKHR"
type ResolveModeFlagsKHR = ResolveModeFlags
-- No documentation found for TopLevel "VkResolveModeFlagBitsKHR"
type ResolveModeFlagBitsKHR = ResolveModeFlagBits
-- No documentation found for TopLevel "VkPhysicalDeviceDepthStencilResolvePropertiesKHR"
type PhysicalDeviceDepthStencilResolvePropertiesKHR = PhysicalDeviceDepthStencilResolveProperties
-- No documentation found for TopLevel "VkSubpassDescriptionDepthStencilResolveKHR"
type SubpassDescriptionDepthStencilResolveKHR = SubpassDescriptionDepthStencilResolve
type KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION = 1
-- No documentation found for TopLevel "VK_KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION"
pattern KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION :: forall a . Integral a => a
pattern KHR_DEPTH_STENCIL_RESOLVE_SPEC_VERSION = 1
type KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME = "VK_KHR_depth_stencil_resolve"
-- No documentation found for TopLevel "VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME"
pattern KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME = "VK_KHR_depth_stencil_resolve"
|
expipiplus1/vulkan
|
src/Vulkan/Extensions/VK_KHR_depth_stencil_resolve.hs
|
bsd-3-clause
| 10,194 | 0 | 8 | 1,891 | 623 | 452 | 171 | -1 | -1 |
-- | Log filenames in current directory sorted by name.
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module Main where
import Control.Applicative
import Data.List(sort)
import Shelly.Pipe
import Data.Text.Lazy as LT
default (LT.Text)
main = shs $ do
makeLog
appendfile logFile . cons '\n' =<< liftSh sort (lsT ".")
logFile = "log"
makeLog =
unlessM (test_f logFile)
(touchfile logFile)
|
adinapoli/Shelly.hs
|
examples/Pipe/Log.hs
|
bsd-3-clause
| 496 | 0 | 11 | 101 | 111 | 62 | 49 | 16 | 1 |
module Main where
import Ivory.Tower.Config
import Ivory.OS.FreeRTOS.Tower.STM32
import LDrive.Platforms
import LDrive.Tests.CANSendRecv (app)
main :: IO ()
main = compileTowerSTM32FreeRTOS testplatform_stm32 p $
app (stm32config_clock . testplatform_stm32)
testplatform_can
testplatform_leds
where
p topts = getConfig topts testPlatformParser
|
sorki/odrive
|
test/CANSendRecv.hs
|
bsd-3-clause
| 384 | 0 | 8 | 75 | 87 | 49 | 38 | 11 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Snap.Internal.Http.Parser.Tests
( tests ) where
import qualified Control.Exception as E
import Control.Exception hiding (try, assert)
import Control.Monad
import Control.Parallel.Strategies
import Data.Attoparsec hiding (Result(..))
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.ByteString.Internal (c2w)
import Data.List
import qualified Data.Map as Map
import Data.Maybe (isNothing)
import Data.Monoid
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck
import qualified Test.QuickCheck.Monadic as QC
import Test.QuickCheck.Monadic hiding (run, assert)
import Test.HUnit hiding (Test, path)
import Text.Printf
import Snap.Internal.Http.Parser
import Snap.Internal.Http.Types
import Snap.Internal.Debug
import Snap.Iteratee hiding (map, sequence)
import qualified Snap.Iteratee as I
import Snap.Test.Common()
tests :: [Test]
tests = [ testShow
, testCookie
, testChunked
, testP2I
, testNull
, testPartial
, testParseError
, testFormEncoded ]
emptyParser :: Parser ByteString
emptyParser = option "foo" $ string "bar"
testShow :: Test
testShow = testCase "parser/show" $ do
let i = IRequest GET "/" (1,1) []
let !b = show i `using` rdeepseq
return $ b `seq` ()
testP2I :: Test
testP2I = testCase "parser/iterParser" $ do
i <- liftM (enumBS "z") $ runIteratee (iterParser emptyParser)
l <- run_ i
assertEqual "should be foo" "foo" l
forceErr :: SomeException -> IO ()
forceErr e = f `seq` (return ())
where
!f = show e
testNull :: Test
testNull = testCase "parser/shortParse" $ do
f <- run_ (parseRequest)
assertBool "should be Nothing" $ isNothing f
testPartial :: Test
testPartial = testCase "parser/partial" $ do
i <- liftM (enumBS "GET / ") $ runIteratee parseRequest
f <- E.try $ run_ i
case f of (Left e) -> forceErr e
(Right x) -> assertFailure $ "expected exception, got " ++ show x
testParseError :: Test
testParseError = testCase "parser/error" $ do
step <- runIteratee parseRequest
let i = enumBS "ZZZZZZZZZZ" step
f <- E.try $ run_ i
case f of (Left e) -> forceErr e
(Right x) -> assertFailure $ "expected exception, got " ++ show x
-- | convert a bytestring to chunked transfer encoding
transferEncodingChunked :: L.ByteString -> L.ByteString
transferEncodingChunked = f . L.toChunks
where
toChunk s = L.concat [ len, "\r\n", L.fromChunks [s], "\r\n" ]
where
len = L.pack $ map c2w $ printf "%x" $ S.length s
f l = L.concat $ (map toChunk l ++ ["0\r\n\r\n"])
-- | ensure that running the 'readChunkedTransferEncoding' iteratee against
-- 'transferEncodingChunked' returns the original string
testChunked :: Test
testChunked = testProperty "parser/chunkedTransferEncoding" $
monadicIO $ forAllM arbitrary prop_chunked
where
prop_chunked s = do
QC.run $ debug "=============================="
QC.run $ debug $ "input is " ++ show s
QC.run $ debug $ "chunked is " ++ show chunked
QC.run $ debug "------------------------------"
sstep <- QC.run $ runIteratee $ stream2stream
step <- QC.run $ runIteratee $
joinI $ readChunkedTransferEncoding sstep
out <- QC.run $ run_ $ enum step
QC.assert $ s == out
QC.run $ debug "==============================\n"
where
chunked = (transferEncodingChunked s)
enum = enumLBS chunked
testCookie :: Test
testCookie =
testCase "parser/parseCookie" $ do
assertEqual "cookie parsing" (Just [cv]) cv2
where
cv = Cookie nm v Nothing Nothing Nothing
cv2 = parseCookie ct
nm = "foo"
v = "bar"
ct = S.concat [ nm
, "="
, v ]
testFormEncoded :: Test
testFormEncoded = testCase "parser/formEncoded" $ do
let bs = "foo1=bar1&foo2=bar2+baz2&foo3=foo%20bar"
let mp = parseUrlEncoded bs
assertEqual "foo1" (Just ["bar1"] ) $ Map.lookup "foo1" mp
assertEqual "foo2" (Just ["bar2 baz2"]) $ Map.lookup "foo2" mp
assertEqual "foo3" (Just ["foo bar"] ) $ Map.lookup "foo3" mp
copyingStream2Stream :: (Monad m) => Iteratee ByteString m ByteString
copyingStream2Stream = go []
where
go l = do
mbx <- I.head
maybe (return $ S.concat $ reverse l)
(\x -> let !z = S.copy x in go (z:l))
mbx
stream2stream :: (Monad m) => Iteratee ByteString m L.ByteString
stream2stream = liftM L.fromChunks consume
|
janrain/snap-server
|
test/suite/Snap/Internal/Http/Parser/Tests.hs
|
bsd-3-clause
| 5,001 | 0 | 17 | 1,343 | 1,437 | 749 | 688 | 121 | 2 |
module FunctorDigit where
import Digit (Digit(..))
instance Functor Digit where
{-# INLINE fmap #-}
fmap f (One a) = One (f a)
fmap f (Two a b) = Two (f a) (f b)
fmap f (Three a b c) = Three (f a) (f b) (f c)
fmap f (Four a b c d) = Four (f a) (f b) (f c) (f d)
|
phischu/fragnix
|
tests/quick/InstancePropagation/FunctorDigit.hs
|
bsd-3-clause
| 303 | 0 | 8 | 105 | 185 | 94 | 91 | 8 | 0 |
{-# LANGUAGE RecordWildCards, ViewPatterns, ScopedTypeVariables, TupleSections #-}
module Development.Ninja.All(runNinja) where
import Development.Ninja.Env
import Development.Ninja.Type
import Development.Ninja.Parse
import Development.Shake hiding (addEnv)
import Development.Shake.Classes
import qualified Data.ByteString as BS8
import qualified Data.ByteString.Char8 as BS
import System.Directory
import qualified Data.HashMap.Strict as Map
import qualified Data.HashSet as Set
import Data.Tuple.Extra
import Control.Exception.Extra
import Control.Monad
import Data.Maybe
import Data.Char
import Data.List.Extra
import System.Info.Extra
-- Internal imports
import General.Extra(removeFile_)
import General.Timing(addTiming)
import General.Makefile(parseMakefile)
import Development.Shake.Internal.FileName(filepathNormalise, fileNameFromString)
import Development.Shake.Internal.FileInfo(getFileInfo)
import Development.Shake.Internal.Errors(throwM, errorStructured)
import Development.Shake.Internal.Rules.File(needBS, neededBS)
import Development.Shake.Internal.Rules.OrderOnly(orderOnlyBS)
-- | Given the Ninja source file, a list of file arguments, a tool name.
-- Return a bool if you should restart and the rules.
runNinja :: IO () -> FilePath -> [String] -> Maybe String -> IO (Maybe (Rules ()))
runNinja _ file args (Just "compdb") = do
dir <- getCurrentDirectory
Ninja{..} <- parse file =<< newEnv
rules<- pure $ Map.fromList [r | r <- rules, BS.unpack (fst r) `elem` args]
-- the build items are generated in reverse order, hence the reverse
let xs = [(a,b,file,rule) | (a,b@Build{..}) <- reverse $ multiples ++ map (first pure) singles
, Just rule <- [Map.lookup ruleName rules], file:_ <- [depsNormal]]
xs <- forM xs $ \(out,Build{..},file,Rule{..}) -> do
-- the order of adding new environment variables matters
env <- scopeEnv env
addEnv env (BS.pack "out") (BS.unwords $ map quote out)
addEnv env (BS.pack "in") (BS.unwords $ map quote depsNormal)
addEnv env (BS.pack "in_newline") (BS.unlines depsNormal)
forM_ buildBind $ \(a,b) -> addEnv env a b
addBinds env ruleBind
commandline <- fmap BS.unpack $ askVar env $ BS.pack "command"
pure $ CompDb dir commandline $ BS.unpack file
putStr $ printCompDb xs
pure Nothing
runNinja _ _ _ (Just x) = errorIO $ "Unknown tool argument, expected 'compdb', got " ++ x
runNinja restart file args Nothing = do
addTiming "Ninja parse"
ninja@Ninja{..} <- parse file =<< newEnv
pure $ Just $ do
phonys<- pure $ Map.fromList phonys
needDeps<- pure $ needDeps ninja phonys -- partial application
singles<- pure $ Map.fromList $ map (first filepathNormalise) singles
multiples<- pure $ Map.fromList [(x,(xs,b)) | (xs,b) <- map (first $ map filepathNormalise) multiples, x <- xs]
rules<- pure $ Map.fromList rules
pools <- fmap Map.fromList $ forM ((BS.pack "console",1):pools) $ \(name,depth) ->
(name,) <$> newResource (BS.unpack name) depth
action $ do
-- build the .ninja files, if they change, restart the build
before <- liftIO $ mapM (getFileInfo False . fileNameFromString) sources
need sources
after <- liftIO $ mapM (getFileInfo False . fileNameFromString) sources
if before /= after then
runAfter restart
else
needBS $ concatMap (resolvePhony phonys) $
if not $ null args then map BS.pack args
else if not $ null defaults then defaults
else Map.keys singles ++ Map.keys multiples
(\x -> map BS.unpack . fst <$> Map.lookup (BS.pack x) multiples) &?> \out -> let out2 = map BS.pack out in
build needDeps phonys rules pools out2 $ snd $ multiples Map.! head out2
(flip Map.member singles . BS.pack) ?> \out -> let out2 = BS.pack out in
build needDeps phonys rules pools [out2] $ singles Map.! out2
resolvePhony :: Map.HashMap Str [Str] -> Str -> [Str]
resolvePhony mp = f $ Left 100
where
f (Left 0) x = f (Right []) x
f (Right xs) x | x `elem` xs = error $ "Ninja recursive phony involving " ++ BS.unpack x
f a x = case Map.lookup x mp of
Nothing -> [x]
Just xs -> concatMap (f $ either (Left . subtract 1) (Right . (x:)) a) xs
quote :: Str -> Str
quote x | BS.any isSpace x = let q = BS.singleton '\"' in BS.concat [q,x,q]
| otherwise = x
build :: (Build -> [Str] -> Action ()) -> Map.HashMap Str [Str] -> Map.HashMap Str Rule -> Map.HashMap Str Resource -> [Str] -> Build -> Action ()
build needDeps phonys rules pools out build@Build{..} = do
needBS $ concatMap (resolvePhony phonys) $ depsNormal ++ depsImplicit
orderOnlyBS $ concatMap (resolvePhony phonys) depsOrderOnly
case Map.lookup ruleName rules of
Nothing -> liftIO $ errorIO $ "Ninja rule named " ++ BS.unpack ruleName ++ " is missing, required to build " ++ BS.unpack (BS.unwords out)
Just Rule{..} -> do
env <- liftIO $ scopeEnv env
liftIO $ do
-- the order of adding new environment variables matters
addEnv env (BS.pack "out") (BS.unwords $ map quote out)
addEnv env (BS.pack "in") (BS.unwords $ map quote depsNormal)
addEnv env (BS.pack "in_newline") (BS.unlines depsNormal)
forM_ buildBind $ \(a,b) -> addEnv env a b
addBinds env ruleBind
applyRspfile env $ do
commandline <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "command"
depfile <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "depfile"
deps <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "deps"
description <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "description"
pool <- liftIO $ askVar env $ BS.pack "pool"
let withPool act = case Map.lookup pool pools of
_ | BS.null pool -> act
Nothing -> liftIO $ errorIO $ "Ninja pool named " ++ BS.unpack pool ++ " not found, required to build " ++ BS.unpack (BS.unwords out)
Just r -> withResource r 1 act
when (description /= "") $ putInfo description
let (cmdOpts, cmdProg, cmdArgs) = toCommand commandline
if deps == "msvc" then do
Stdout stdout <- withPool $ command cmdOpts cmdProg cmdArgs
prefix <- liftIO $ fmap (fromMaybe $ BS.pack "Note: including file: ") $
askEnv env $ BS.pack "msvc_deps_prefix"
needDeps build $ parseShowIncludes prefix $ BS.pack stdout
else
withPool $ command_ cmdOpts cmdProg cmdArgs
when (depfile /= "") $ do
when (deps /= "gcc") $ need [depfile]
depsrc <- liftIO $ BS.readFile depfile
needDeps build $ concatMap snd $ parseMakefile depsrc
-- correct as per the Ninja spec, but breaks --skip-commands
-- when (deps == "gcc") $ liftIO $ removeFile depfile
needDeps :: Ninja -> Map.HashMap Str [Str] -> Build -> [Str] -> Action ()
needDeps Ninja{..} phonysMp = \build xs -> do -- eta reduced so 'builds' is shared
opts <- getShakeOptions
if isNothing $ shakeLint opts then needBS xs else do
neededBS xs
-- now try and statically validate needed will never fail
-- first find which dependencies are generated files
xs<- pure $ filter (`Map.member` builds) xs
-- now try and find them as dependencies
-- performance note: allDependencies generates lazily, and difference consumes lazily,
-- with the property that in the common case it won't generate much of the list at all
let bad = xs `difference` allDependencies build
case bad of
[] -> pure ()
xs -> throwM $ errorStructured
("Lint checking error - " ++
(if length xs == 1 then "file in deps is" else "files in deps are") ++
" generated and not a pre-dependency")
[("File", Just $ BS.unpack x) | x <- xs]
""
where
builds :: Map.HashMap FileStr Build
builds = Map.fromList $ singles ++ [(x,y) | (xs,y) <- multiples, x <- xs]
-- do list difference, assuming a small initial set, most of which occurs early in the list
difference :: (Eq a, Hashable a) => [a] -> [a] -> [a]
difference [] _ = []
difference xs ys = f (Set.fromList xs) ys
where
f xs [] = Set.toList xs
f xs (y:ys)
| y `Set.member` xs = let xs2 = Set.delete y xs in if Set.null xs2 then [] else f xs2 ys
| otherwise = f xs ys
-- find all dependencies of a rule, no duplicates, with all dependencies of this rule listed first
allDependencies :: Build -> [FileStr]
allDependencies rule = f Set.empty [] [rule]
where
f _ [] [] = []
f seen [] (x:xs) = f seen (map filepathNormalise $ concatMap (resolvePhony phonysMp) $ depsNormal x ++ depsImplicit x ++ depsOrderOnly x) xs
f seen (x:xs) rest | x `Set.member` seen = f seen xs rest
| otherwise = x : f (Set.insert x seen) xs (maybeToList (Map.lookup x builds) ++ rest)
applyRspfile :: Env Str Str -> Action a -> Action a
applyRspfile env act = do
rspfile <- liftIO $ fmap BS.unpack $ askVar env $ BS.pack "rspfile"
rspfile_content <- liftIO $ askVar env $ BS.pack "rspfile_content"
if rspfile == "" then
act
else
flip actionFinally (removeFile_ rspfile) $ do
liftIO $ BS.writeFile rspfile rspfile_content
act
parseShowIncludes :: Str -> Str -> [FileStr]
parseShowIncludes prefix out =
[y | x <- BS.lines out, prefix `BS.isPrefixOf` x
, let y = BS.dropWhile isSpace $ BS.drop (BS.length prefix) x
, not $ isSystemInclude y]
-- Dodgy, but ported over from the original Ninja
isSystemInclude :: FileStr -> Bool
isSystemInclude x = bsProgFiles `BS.isInfixOf` tx || bsVisStudio `BS.isInfixOf` tx
where tx = BS8.map (\c -> if c >= 97 then c - 32 else c) x
-- optimised toUpper that only cares about letters and spaces
bsProgFiles = BS.pack "PROGRAM FILES"
bsVisStudio = BS.pack "MICROSOFT VISUAL STUDIO"
data CompDb = CompDb
{cdbDirectory :: String
,cdbCommand :: String
,cdbFile :: String
}
deriving Show
printCompDb :: [CompDb] -> String
printCompDb xs = unlines $ ["["] ++ concat (zipWithFrom f 1 xs) ++ ["]"]
where
n = length xs
f i CompDb{..} =
[" {"
," \"directory\": " ++ g cdbDirectory ++ ","
," \"command\": " ++ g cdbCommand ++ ","
," \"file\": " ++ g cdbFile
," }" ++ (if i == n then "" else ",")]
g = show
toCommand :: String -> ([CmdOption], String, [String])
toCommand s
-- On POSIX, Ninja does a /bin/sh -c, and so does Haskell in Shell mode (easy).
| not isWindows = ([Shell], s, [])
-- On Windows, Ninja passes the string directly to CreateProcess,
-- but Haskell applies some escaping first.
-- We try and get back as close to the original as we can, but it's very hacky
| length s < 8000 =
-- Using the "cmd" program adds overhead (I measure 7ms), and a limit of 8191 characters,
-- but is the most robust, requiring no additional escaping.
([Shell], s, [])
| (cmd,s) <- word1 s, upper cmd `elem` ["CMD","CMD.EXE"], ("/c",s) <- word1 s =
-- Given "cmd.exe /c <something>" we translate to Shell, which adds cmd.exe
-- (looked up on the current path) and /c to the front. CMake uses this rule a lot.
-- Adding quotes around pieces are /c goes very wrong.
([Shell], s, [])
| otherwise =
-- It's a long command line which doesn't call "cmd /c". We reverse the escaping
-- Haskell applies, but each argument will still gain quotes around it.
let xs = splitArgs s in ([], headDef "" xs, drop1 xs)
data State
= Gap -- ^ Current in the gap between words
| Word -- ^ Currently inside a space-separated argument
| Quot -- ^ Currently inside a quote-surrounded argument
-- | The process package contains a translate function, reproduced below. The aim is that after command line
-- parsing we should get out mostly the same answer.
splitArgs :: String -> [String]
splitArgs = f Gap
where
f Gap (x:xs) | isSpace x = f Gap xs
f Gap ('\"':xs) = f Quot xs
f Gap [] = []
f Gap xs = f Word xs
f Word (x:xs) | isSpace x = [] : f Gap xs
f Quot ('\"':xs) = [] : f Gap xs
f s ('\\':xs) | (length -> a, b) <- span (== '\\') xs = case b of
'\"':xs | even a -> add (replicate (a `div` 2) '\\' ++ "\"") $ f s xs
| otherwise -> add (replicate ((a+1) `div` 2) '\\') $ f s ('\"':xs)
xs -> add (replicate (a+1) '\\') $ f s xs
f s (x:xs) = add [x] $ f s xs
f _ [] = [[]]
add a (b:c) = (a++b):c
add a [] = [a]
{-
translate (cmd,args) = unwords $ f cmd : map f args
where
f x = '"' : snd (foldr escape (True,"\"") xs)
escape '"' (_, str) = (True, '\\' : '"' : str)
escape '\\' (True, str) = (True, '\\' : '\\' : str)
escape c (_, str) = (False, c : str)
-}
|
ndmitchell/shake
|
src/Development/Ninja/All.hs
|
bsd-3-clause
| 13,795 | 0 | 26 | 4,120 | 4,329 | 2,185 | 2,144 | 210 | 11 |
module Parser.ParseQuoted
(parseQuotedString)
where
import Parser.Parse
import Control.Monad (guard)
import qualified Data.Map as Map
escapes :: Map.Map Char Char
escapes = Map.fromList
[('\\', '\\')
,('"', '"')
,('\'', '\'')
,('n', '\n')
,('r', '\r')
,('t', '\t')
,('a', '\a')]
parseQuotedString :: Char -> Parse Char String
parseQuotedString q = greedy $ do
let escapedChar = do
lit '\\'
char <- consume1
case Map.lookup char escapes of
Just escape -> return escape
Nothing -> parseFailure
let normalChar = do
char <- consume1
guard $ char /= q && char /= '\\'
return char
lit q
content <- reluctantMany $ parseEither normalChar escapedChar
lit q
return content
|
Kiwi-Labs/kwirc
|
kwick/parser/ParseQuoted.hs
|
mit
| 703 | 10 | 16 | 141 | 254 | 128 | 126 | 30 | 2 |
{-|
TODO This has a bunch of stub logic that was intended for an
architecture with a single Urbit daemon running multiple
ships. Do it or strip it out.
-}
module Urbit.King.API (King(..), kingAPI, readPortsFile) where
import RIO.Directory
import Urbit.Prelude
import Network.Socket (Socket)
import Prelude (read)
import Urbit.Arvo (Belt)
import Urbit.King.App (HasConfigDir(..))
import qualified Network.HTTP.Types as H
import qualified Network.Wai as W
import qualified Network.Wai.Handler.Warp as W
import qualified Network.Wai.Handler.WebSockets as WS
import qualified Network.WebSockets as WS
import qualified Urbit.Vere.NounServ as NounServ
import qualified Urbit.Vere.Term.API as Term
-- Types -----------------------------------------------------------------------
type TermConn = NounServ.Conn Belt [Term.Ev]
type TermConnAPI = TVar (Maybe (TermConn -> STM ()))
{-|
Daemon state.
-}
data King = King
{ kServer :: Async ()
, kTermConn :: TermConnAPI
}
--------------------------------------------------------------------------------
{-|
Get the filepath of the urbit config directory and the ports file.
-}
portsFilePath :: HasConfigDir e => RIO e (FilePath, FilePath)
portsFilePath = do
dir <- view configDirL
fil <- pure (dir </> ".king.ports")
pure (dir, fil)
{-|
Write the ports file.
-}
portsFile :: HasConfigDir e => Word -> RAcquire e (FilePath, FilePath)
portsFile por =
mkRAcquire mkFile (removeFile . snd)
where
mkFile = do
(dir, fil) <- portsFilePath
createDirectoryIfMissing True dir
writeFile fil (encodeUtf8 $ tshow por)
pure (dir, fil)
{-|
Get the HTTP port for the running Urbit daemon.
-}
readPortsFile :: HasConfigDir e => RIO e (Maybe Word)
readPortsFile = do
(_, fil) <- portsFilePath
bs <- readFile fil
evaluate (readMay $ unpack $ decodeUtf8 bs)
kingServer :: HasLogFunc e => (Int, Socket) -> RAcquire e King
kingServer is =
mkRAcquire (startKing is) (cancel . kServer)
where
startKing :: HasLogFunc e => (Int, Socket) -> RIO e King
startKing (port, sock) = do
api <- newTVarIO Nothing
let opts = W.defaultSettings & W.setPort port
env <- ask
tid <- async $ io $ W.runSettingsSocket opts sock $ app env api
pure (King tid api)
{-|
Start the HTTP server and write to the ports file.
-}
kingAPI :: (HasConfigDir e, HasLogFunc e)
=> RAcquire e King
kingAPI = do
(port, sock) <- io $ W.openFreePort
(dir, fil) <- portsFile (fromIntegral port)
-- lockFile dir
kingServer (port, sock)
serveTerminal :: HasLogFunc e => e -> TermConnAPI -> Word -> W.Application
serveTerminal env api word =
WS.websocketsOr WS.defaultConnectionOptions wsApp fallback
where
fallback req respond =
respond $ W.responseLBS H.status500 []
$ "This endpoint uses websockets"
wsApp pen =
atomically (readTVar api) >>= \case
Nothing -> WS.rejectRequest pen "Ship not running"
Just sp -> do
wsc <- io $ WS.acceptRequest pen
inp <- io $ newTBMChanIO 5
out <- io $ newTBMChanIO 5
atomically $ sp $ NounServ.mkConn inp out
let doit = runRIO env
$ NounServ.wsConn "NOUNSERV (wsServ) " inp out wsc
-- If `wai` kills this thread for any reason, the TBMChans
-- need to be closed. If they are not closed, the
-- terminal will not know that they disconnected.
finally doit $ atomically $ do
closeTBMChan inp
closeTBMChan out
data BadShip = BadShip Text
deriving (Show, Exception)
app :: HasLogFunc e => e -> TermConnAPI -> W.Application
app env api req respond =
case W.pathInfo req of
["terminal", session] -> do
session :: Word <- evaluate $ read $ unpack session
serveTerminal env api session req respond
["status"] ->
respond $ W.responseLBS H.status200 [] "{}"
_ ->
respond $ W.responseLBS H.status404 [] "No implemented"
|
ngzax/urbit
|
pkg/hs/urbit-king/lib/Urbit/King/API.hs
|
mit
| 4,276 | 0 | 18 | 1,217 | 1,128 | 586 | 542 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
module System.HFind.ArgParse
( FindFlag(..)
, Result(..)
, getNumThreads
, parseArgs
) where
import qualified GHC.Conc as GHC
import Control.Monad (when, forM, forM_, (<=<))
import Control.Monad.Trans.Except (ExceptT(..), Except, throwE)
import Control.Monad.Morph (hoist, generalize)
import Control.Monad.IO.Class (liftIO)
import Data.List (break, isPrefixOf)
import Data.Monoid ((<>))
import Text.Read (readMaybe)
import qualified Data.Text as T
import qualified Data.Text.IO as TextIO
import qualified Data.Text.ICU as ICU
import System.Exit (die, exitSuccess)
import System.IO (stderr)
import Pipes ((>->))
import qualified Pipes as Pipes
import qualified Pipes.Prelude as Pipes
import Text.RawString.QQ (r)
import System.HFind.Path (Path, Abs, Dir, RawPath)
import qualified System.HFind.Path as Path
import qualified System.HFind.Combinators as C
import System.HFind.Expr.Types (TypedName(..), Var(..), typeName)
import System.HFind.Expr.Baker (BakerT, runBakerT)
import System.HFind.Expr.Eval (Eval)
import qualified System.HFind.Expr.Baker as Baker
import System.HFind.Expr.Bakers (parseLetBinding,
parseFilterPredicate,
parsePrunePredicate,
parseStringInterp,
parseExecCmdLine)
import qualified System.HFind.Expr.Error as Err
data FindFlag = FollowLinks | DryRun | Parallel (Maybe Int)
deriving (Eq, Show)
data Result = Result
{ findFlags :: [FindFlag]
, rootPath :: Path Abs Dir
, treeContext :: Baker.BakingContext
, treeTransform :: C.TransformR Eval
, listContext :: Baker.BakingContext
, listTransform :: C.EntryTransformR Eval
, listConsumer :: C.EntryConsumerR Eval
}
getNumThreads :: Result -> IO Int
getNumThreads result =
case [ n | Parallel n <- findFlags result ] of
[] -> return 1
Nothing:_ -> GHC.getNumProcessors
Just n:_ -> return n
type ParseState = (Int, [String])
checkHelpArg :: [String] -> Bool
checkHelpArg [] = False
checkHelpArg (arg:_) = arg == "-h" || arg == "--help"
parseFlags :: ParseState -> (ParseState, [FindFlag])
parseFlags (i, "-n":args) = fmap (DryRun:) $ parseFlags (i+1, args)
parseFlags (i, "-L":args) = fmap (FollowLinks:) $ parseFlags (i+1, args)
parseFlags (i, "-j":args) = fmap (Parallel Nothing:) $ parseFlags (i+1, args)
parseFlags (i, jN:args)
| "-j" `isPrefixOf` jN
, Just n <- readMaybe (drop 2 jN)
= fmap (Parallel (Just n):) $ parseFlags (i+1, args)
parseFlags (i, args) = ((i, args), [])
parsePathArgs :: ParseState
-> IO (Either RawPath (ParseState, [Path Abs Dir]))
parsePathArgs state@(_, []) = return (Right (state, []))
parsePathArgs state@(_, ('-':_):_) = return (Right (state, []))
parsePathArgs (i, arg:args) = do
let rawPath = T.pack arg
res <- Path.canonicalizeFromHere rawPath
case res of
Nothing -> return (Left rawPath)
Just path -> (fmap.fmap.fmap) (Path.asDirPath path:) $
parsePathArgs (i+1, args)
parseTreeTransforms :: ParseState
-> BakerT (Except String) (ParseState, C.TransformR Eval)
parseTreeTransforms (i, []) =
return ((i, []), Pipes.cat)
parseTreeTransforms (i, "-prune":expr:args) = do
let sourceName = "argument #" ++ show (i+1)
predicate <- parsePrunePredicate sourceName expr
(state', trns) <- parseTreeTransforms (i+2, args)
return (state', C.pruneDirsM predicate >-> trns)
parseTreeTransforms state = return (state, Pipes.cat)
parseListTransforms :: ParseState
-> BakerT (Except String) (ParseState, C.EntryTransformR Eval)
parseListTransforms (i, []) =
return ((i, []), Pipes.cat)
parseListTransforms (i, "-if":expr:args) = do
let sourceName = "argument #" ++ show (i+1)
predicate <- parseFilterPredicate sourceName expr
(state', trns) <- parseListTransforms (i+2, args)
return (state', Pipes.filterM predicate >-> trns)
parseListTransforms (i, "-let":expr:args) = do
let sourceName = "argument #" ++ show (i+1)
update <- parseLetBinding sourceName expr
(state', trns) <- parseListTransforms (i+2, args)
return (state', Pipes.chain update >-> trns)
parseListTransforms state = return (state, Pipes.cat)
parseConsumers :: ParseState
-> BakerT (Except String) (ParseState, C.EntryConsumerR Eval)
parseConsumers (i, []) =
return ( (i, [])
, C.asPaths
>-> C.asFiles
>-> C.plainText
>-> Pipes.mapM_ (liftIO . TextIO.putStrLn)
)
parseConsumers (i, "-print":fmt:args) = do
let sourceName = "argument #" ++ show (i+1)
format <- parseStringInterp sourceName fmt
let consume = liftIO . TextIO.putStrLn <=< format
(state', consumer) <- parseMoreConsumers (i+2, args)
return (state', Pipes.chain consume >-> consumer)
parseConsumers (i, arg:args) | arg == "-exec" || arg == "-execdir" = do
let (argv, args') = break (==";") args
(offset, args'') = case args' of
";":args'' -> (1, args'')
_ -> (0, args')
let sources = zip ["argument #" ++ show j | j <- [i+1..]] argv
exec <- parseExecCmdLine ("argument #" ++ show i) (arg == "-execdir") sources
(state', consumer) <- parseMoreConsumers (i+1 + offset + length argv, args'')
return (state', Pipes.chain exec >-> consumer)
parseConsumers (i, "-nop":args) = parseMoreConsumers (i+1, args)
parseConsumers state = return (state, Pipes.drain)
parseMoreConsumers :: ParseState
-> BakerT (Except String) (ParseState, C.EntryConsumerR Eval)
parseMoreConsumers st@(_, []) = return (st, Pipes.drain)
parseMoreConsumers st = parseConsumers st
parseArgs :: [String] -> ExceptT String IO [Result]
parseArgs args = do
when (checkHelpArg args) $ liftIO $ do
putStrLn usage
exitSuccess
state <- return (1, args)
(state, flags) <- return $ parseFlags state
(state, paths) <- ExceptT $ fmap fmtIfBadPathError (parsePathArgs state)
forM paths $ \path -> do
((state, treeTrns), ctx1) <- runBaker path $ parseTreeTransforms state
((state, listTrns), ctx2) <- runBaker path $ parseListTransforms state
((state, listCons), ctx2) <- runBakerWith ctx2 path $ parseConsumers state
case snd state of
[] -> return (Result flags path ctx1 treeTrns
ctx2 listTrns
listCons)
arg:_ -> liftIO $ die ("Unrecognized argument: " ++ arg)
where
fmtIfBadPathError (Left rawPath) = Left ("Invalid path: " ++ show rawPath)
fmtIfBadPathError (Right a) = Right a
putErr = liftIO . TextIO.hPutStrLn stderr
fmtError :: Err.BakingError -> T.Text
fmtError (Err.VarNotFound notFound) =
let name = case notFound of
RxCapVar i -> T.pack (show i)
NamedVar n -> n
in
"Variable $" <> name <> " not found"
fmtError (Err.FuncNotFound name) =
"No function called " <> name <> " exists"
fmtError (Err.VarAlreadyExists name) =
"Variable $" <> name <> " is already in scope"
fmtError (Err.ExpectedButFound t1 t2) =
"Type error: '" <> t1 <> "' expected, but found "
<> "'" <> t2 <> "'"
reportError ctx err bt = do
putErr (Err.renderError
(Err.errorWithBacktrace (fmtError err) bt))
putErr ""
putErr "Defined variables:"
forM_ (Baker.ctxGetVars ctx) $ \(TypedName ty var) ->
putErr (" $" <> var <> ": " <> typeName ty)
case Baker.ctxGetActiveRegex ctx of
Nothing -> return ()
Just rx -> putErr ("\nActive regex: " <> ICU.pattern rx)
runBaker :: Path Abs Dir
-> BakerT (Except String) a
-> ExceptT String IO (a, Baker.BakingContext)
runBaker = runBakerWith Baker.defBakingContext
runBakerWith :: Baker.BakingContext
-> Path Abs Dir
-> BakerT (Except String) a
-> ExceptT String IO (a, Baker.BakingContext)
runBakerWith ctx path baker = do
(e, ctx) <- runBakerT path ctx $
hoist (hoist generalize) baker
case e of
Right res ->
return (res, ctx)
Left (err, bt) -> do
liftIO $ reportError ctx err bt
throwE ""
usage :: String
usage = [r|usage: hfind [-L] <path> [tree transforms] [list transforms] [consumers]
flags:
-L Follow symlinks
-jN Use one producer and (N-1) consumer threads. Particularly
appropriate with -exec. If N is ommited, it defaults to
the number of available processors.
supported tree transforms:
-prune pred: Filter subtrees with root matching pred
supported list transforms:
-if pred Allow only entries satisfying the predicate pred
-let var=expr Define a new variable with value expr
supported consumers:
-print string Print the string, followed by a new line (default)
-exec cmd a1... \; Execute a shell command cmd with arguments a1, a2,...
where cmd and a1, a2,... are parsed as individual string
interpolations without quotes. The semicolon is optional
and required only if this is not the last argument.
-execdir Same as -exec, but set the working directory to the
directory containing each item.
-nop Do nothing
predicate syntax:
scope(pred) nests a scope, ensuring that regex captures in pred are not
reflected outside
expr (of boolean type)
not(pred) pred1 and pred2 pred1 or pred2
pred1 == pred2 pred1 != pred2
pred1 >= pred2 pred1 <= pred2
pred1 > pred2 pred1 < pred2
expr =~ m/pcre regex/mxsin
valid regex delimiters:
/ _ @ % # ! , ; |
regex options:
m: multiline s: dot matches newlines
x: allow spaces/comments i: case insensitive
n: do not capture
expression syntax:
$variable
literal
function expr1
"interpolated string with $variables, dollars escaped as $$"
+expr -expr
expr1 + expr 2 expr1 - expr2
expr1 * expr 2 expr1 / expr2
types:
string, int (64-bit), bool, fsnode (file metadata)
variable syntax:
$identifier
$builtin_function (applies builtin_function to the current node)
$environment_variable
regex captures: $0, $1, $2...
builtin functions:
readint : string -> int
exists, isfile, isdir, islink : string -> bool
stat : string -> fsnode
parent : fsnode -> fsnode
hidden : fsnode -> bool
type : fsnode -> string
size : fsnode -> int
nlinks : fsnode -> int
perms : fsnode -> string (e.g. rwxr-xr-x)
owner, group : fsnode -> string
ownerid, groupid : fsnode -> string
name, path, relpath, parentpath, parentname : fsnode -> string
literal syntax:
"string"
12312319283791283 (64-bit integer)
true
false |]
|
xcv-/hfind
|
cli/System/HFind/ArgParse.hs
|
mit
| 11,682 | 0 | 17 | 3,321 | 3,057 | 1,631 | 1,426 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
module Test.Pos.Infra.Bi
( tests
) where
import Universum
import Hedgehog (Property)
import qualified Hedgehog as H
import Pos.Infra.Communication.Types.Protocol (HandlerSpec (..))
import qualified Prelude
import Test.Pos.Binary.Helpers.GoldenRoundTrip (goldenTestBi,
roundTripsBiBuildable)
import Test.Pos.Infra.Gen (genHandlerSpec)
import Test.Pos.Util.Golden (discoverGolden, eachOf)
import Test.Pos.Util.Tripping (discoverRoundTrip)
--------------------------------------------------------------------------------
-- HandlerSpec
--------------------------------------------------------------------------------
golden_HandlerSpec_ConvHandler :: Property
golden_HandlerSpec_ConvHandler =
goldenTestBi exampleConvHandler "test/golden/HandlerSpec_ConvHandler"
where
exampleConvHandler = ConvHandler 15553
golden_HandlerSpec_UnknownHandler :: Property
golden_HandlerSpec_UnknownHandler =
goldenTestBi exampleUnknownHandler "test/golden/HandlerSpec_UnknownHandler"
where
exampleUnknownHandler = UnknownHandler 104 Prelude.$ encodeUtf8 @String @ByteString "\248U=\232\167\t"
roundTripHandlerSpecBi :: Property
roundTripHandlerSpecBi = eachOf 1000 genHandlerSpec roundTripsBiBuildable
-----------------------------------------------------------------------
-- Main test export
-----------------------------------------------------------------------
tests :: IO Bool
tests = and <$> sequence
[ H.checkSequential $$discoverGolden
, H.checkParallel $$discoverRoundTrip
]
|
input-output-hk/pos-haskell-prototype
|
infra/test/Test/Pos/Infra/Bi.hs
|
mit
| 1,678 | 0 | 9 | 258 | 236 | 142 | 94 | 28 | 1 |
{-
SkateBackendWiki: Backend to generate a Wiki documentation
Part of Skate: a Schema specification languge
Copyright (c) 2017, ETH Zurich.
All rights reserved.
This file is distributed under the terms in the attached LICENSE file.
If you do not find this file, copies can be found by writing to:
ETH Zurich D-INFK, Universit\"atstr. 6, CH-8092 Zurich. Attn: Systems Group.
-}
module SkateBackendWiki where
import Data.Time.Format
import Data.Time.LocalTime
import Data.Time.Clock.POSIX
import Data.List
import Data.Char
import Text.ParserCombinators.Parsec.Pos
import SkateParser
import SkateTypes
import qualified AbsSyntaxWiki as W
import SkateTypes
import SkateSchema
{- starts the compilation process of the schema -}
compile :: String -> String -> SchemaRecord -> String
compile infile outfile sr =
h ++ i ++ W.lineBreak ++ b ++ W.lineBreak ++ f
where
Schema sname sdesc decls imps _ = (schema sr)
h = wikiHeader sname sdesc infile
i = wikiImports imps
b = wikiBody decls sname
f = wikiFooter ""
{- generate the header used in the Wiki syntax -}
wikiHeader :: String -> String -> String -> String
wikiHeader sname desc infile = W.title ("Schema: " ++ desc)
++ W.textit "This document has been generated using Skate." ++ W.lineBreak
++ W.textit "Input File: " ++ W.inlinecode infile ++ W.lineBreak
++ W.textit "Schema Identifier: " ++ W.inlinecode sname ++ W.lineBreak
++ W.tableOfContent
wikiImports :: [String] -> String
wikiImports imps = h ++ i
where
h = W.heading "Imports"
i = (if imps == [] then "No imports." else (W.unOrderedList 1 imps))
wikiBody :: [Declaration] -> String-> String
wikiBody decls sname = heading ++ concat declstr
where
heading = W.hline
declstr = [wikiPrintDecl d 2 sname| d <- decls]
wikiPrintDecl :: Declaration -> Int -> String -> String
wikiPrintDecl d@(Fact fn fd attr sp) l prefix= (wikiPrintFact fn fd attr prefix l)
wikiPrintDecl d@(Flags f fd w defs sp) l prefix = (wikiPrintFlags f w fd defs) prefix l
wikiPrintDecl d@(Constants n cd t defs sp) l prefix = wikiPrintConstants n t cd defs prefix l
wikiPrintDecl d@(Enumeration n ed defs sp) l prefix = wikiPrintEnum n ed defs prefix l
wikiPrintDecl d@(Namespace n nd defs sp) l prefix = wikiPrintNameSpace n nd defs l prefix
wikiPrintDecl d@(Section n defs sp) l prefix = wikiPrintSection n defs l prefix
wikiPrintDecl d@(Text t sp) l prefix = wikiPrintText t
{----------------------------------------------------------------------------}
wikiPrintFact :: String -> String -> [FactAttrib] -> String -> Int -> String
wikiPrintFact n d attrib prefix l = title ++ W.newLine
++ "Fact Name: " ++ (W.inlinecode name) ++ W.lineBreak
++ "Prolog: " ++ W.newLine ++ (W.code prolog) ++ W.lineBreak
++ "Fields: " ++ W.newLine
++ (W.tableHeading ["Name", "Type", "Description"]) ++ (concat tableRows)
++ W.lineBreak
where
title = W.headingGeneric ("Fact: " ++ d) l
tableRows = [W.tableRow (wikiPrintFactAttrib a) | a <- attrib]
name = makeDeclName prefix n
prologfields = (intersperse "," [wikiPrintFactFieldNames a | a <- attrib])
prolog = name ++ "(" ++ (concat prologfields) ++ ")"
wikiPrintFactAttrib :: FactAttrib -> [String]
wikiPrintFactAttrib fa@(FactAttrib n d t _) = [n, (show t), d]
wikiPrintFactFieldNames :: FactAttrib -> String
wikiPrintFactFieldNames fa@(FactAttrib n _ _ _) = n
{----------------------------------------------------------------------------}
wikiPrintFlags :: String -> Integer -> String -> [FlagDef] -> String -> Int -> String
wikiPrintFlags n w d f prefix l = title ++ W.newLine
++ "Flags Name: " ++ name ++ W.lineBreak
++ "Prolog: " ++ W.newLine ++ (W.code (concat prolog)) ++ W.newLine
++ "Flags: " ++ W.lineBreak
++ (W.tableHeading ["Flag", "Value", "Description" ]) ++ (concat tableRows)
++ W.lineBreak
where
title = W.headingGeneric ("Flags: " ++ d) l
flags = [wikiPrintFlagDefs fd n prefix | fd <- f]
tableRows = [W.tableRow [fn, fv, fd] | (fn, fd, fv) <- flags]
prolog = []
name = makeDeclName prefix n
wikiPrintFlagDefs :: FlagDef -> String -> String -> (String, String, String)
wikiPrintFlagDefs fd@(FlagDef n d v _) flag prefix = (fname, d, fval)
where
fname = makeFlagName prefix flag n
fval = (show (v))
{----------------------------------------------------------------------------}
wikiPrintConstants :: String -> TypeRef -> String -> [ ConstantDef ] -> String -> Int-> String
wikiPrintConstants n t d defs prefix l = title
++ W.lineBreak
where
title = W.headingGeneric ("Constants: " ++ d) l
{----------------------------------------------------------------------------}
wikiPrintEnum :: String -> String -> [ EnumDef ] -> String -> Int -> String
wikiPrintEnum n d defs prefix l = title
++ W.lineBreak
where
title = W.headingGeneric ("Enumeration: " ++ d) l
{----------------------------------------------------------------------------}
wikiPrintNameSpace :: String -> String -> [ Declaration ] -> Int -> String -> String
wikiPrintNameSpace n d decls l prefix = h ++ W.lineBreak
++ "Namespace identifier: " ++ W.inlinecode (makeNameSpacePrefix prefix n)
++ W.lineBreak
++ (concat ns)
++ W.lineBreak
++ "End of namespace " ++ n
++ W.newLine ++ W.hline
++ W.lineBreak
where
h = W.headingGeneric ("Namespace: " ++ d) l
newprefix = makeNameSpacePrefix prefix n
ns = [wikiPrintDecl d (l + 1) newprefix | d <- decls]
{----------------------------------------------------------------------------}
wikiPrintSection :: String -> [ Declaration ] -> Int -> String -> String
wikiPrintSection n decls l prefix = h ++ (concat subsection) ++ W.newLine
++ W.lineBreak
where
h = W.headingGeneric n l
subsection = [wikiPrintDecl d (l + 1) prefix | d <- decls]
{----------------------------------------------------------------------------}
wikiPrintText :: String -> String
wikiPrintText t = t ++ W.lineBreak
{----------------------------------------------------------------------------}
wikiPrintTypedef :: TypeBuiltIn -> String -> String -> String
wikiPrintTypedef t s prefix = s ++ W.lineBreak
{----------------------------------------------------------------------------}
wikiFooter :: String -> String
wikiFooter intf = "footer"
wikiFootNote :: String
wikiFootNote = W.footnote "This has been generated by Skate v. xx.xx on date."
{----------------------------------------------------------------------------}
{-Generic -}
makeNameSpacePrefix :: String -> String -> String
makeNameSpacePrefix prefix n = prefix ++ "_" ++ n
makeDeclName :: String -> String -> String
makeDeclName prefix n = prefix ++ "__" ++ n
makeFlagName :: String -> String -> String -> String
makeFlagName prefix flag name = map toUpper fname
where
fname = prefix ++ "_" ++ flag ++ "_" ++ name
|
kishoredbn/barrelfish
|
tools/skate/SkateBackendWiki.hs
|
mit
| 7,044 | 0 | 18 | 1,430 | 2,032 | 1,069 | 963 | 114 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.ElastiCache.DeleteCacheCluster
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- The /DeleteCacheCluster/ action deletes a previously provisioned cache
-- cluster. /DeleteCacheCluster/ deletes all associated cache nodes, node
-- endpoints and the cache cluster itself. When you receive a successful
-- response from this action, Amazon ElastiCache immediately begins
-- deleting the cache cluster; you cannot cancel or revert this action.
--
-- This API cannot be used to delete a cache cluster that is the last read
-- replica of a replication group that has Multi-AZ mode enabled.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_DeleteCacheCluster.html AWS API Reference> for DeleteCacheCluster.
module Network.AWS.ElastiCache.DeleteCacheCluster
(
-- * Creating a Request
deleteCacheCluster
, DeleteCacheCluster
-- * Request Lenses
, dccFinalSnapshotIdentifier
, dccCacheClusterId
-- * Destructuring the Response
, deleteCacheClusterResponse
, DeleteCacheClusterResponse
-- * Response Lenses
, dccrsCacheCluster
, dccrsResponseStatus
) where
import Network.AWS.ElastiCache.Types
import Network.AWS.ElastiCache.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Represents the input of a /DeleteCacheCluster/ action.
--
-- /See:/ 'deleteCacheCluster' smart constructor.
data DeleteCacheCluster = DeleteCacheCluster'
{ _dccFinalSnapshotIdentifier :: !(Maybe Text)
, _dccCacheClusterId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteCacheCluster' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dccFinalSnapshotIdentifier'
--
-- * 'dccCacheClusterId'
deleteCacheCluster
:: Text -- ^ 'dccCacheClusterId'
-> DeleteCacheCluster
deleteCacheCluster pCacheClusterId_ =
DeleteCacheCluster'
{ _dccFinalSnapshotIdentifier = Nothing
, _dccCacheClusterId = pCacheClusterId_
}
-- | The user-supplied name of a final cache cluster snapshot. This is the
-- unique name that identifies the snapshot. ElastiCache creates the
-- snapshot, and then deletes the cache cluster immediately afterward.
dccFinalSnapshotIdentifier :: Lens' DeleteCacheCluster (Maybe Text)
dccFinalSnapshotIdentifier = lens _dccFinalSnapshotIdentifier (\ s a -> s{_dccFinalSnapshotIdentifier = a});
-- | The cache cluster identifier for the cluster to be deleted. This
-- parameter is not case sensitive.
dccCacheClusterId :: Lens' DeleteCacheCluster Text
dccCacheClusterId = lens _dccCacheClusterId (\ s a -> s{_dccCacheClusterId = a});
instance AWSRequest DeleteCacheCluster where
type Rs DeleteCacheCluster =
DeleteCacheClusterResponse
request = postQuery elastiCache
response
= receiveXMLWrapper "DeleteCacheClusterResult"
(\ s h x ->
DeleteCacheClusterResponse' <$>
(x .@? "CacheCluster") <*> (pure (fromEnum s)))
instance ToHeaders DeleteCacheCluster where
toHeaders = const mempty
instance ToPath DeleteCacheCluster where
toPath = const "/"
instance ToQuery DeleteCacheCluster where
toQuery DeleteCacheCluster'{..}
= mconcat
["Action" =: ("DeleteCacheCluster" :: ByteString),
"Version" =: ("2015-02-02" :: ByteString),
"FinalSnapshotIdentifier" =:
_dccFinalSnapshotIdentifier,
"CacheClusterId" =: _dccCacheClusterId]
-- | /See:/ 'deleteCacheClusterResponse' smart constructor.
data DeleteCacheClusterResponse = DeleteCacheClusterResponse'
{ _dccrsCacheCluster :: !(Maybe CacheCluster)
, _dccrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteCacheClusterResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dccrsCacheCluster'
--
-- * 'dccrsResponseStatus'
deleteCacheClusterResponse
:: Int -- ^ 'dccrsResponseStatus'
-> DeleteCacheClusterResponse
deleteCacheClusterResponse pResponseStatus_ =
DeleteCacheClusterResponse'
{ _dccrsCacheCluster = Nothing
, _dccrsResponseStatus = pResponseStatus_
}
-- | Undocumented member.
dccrsCacheCluster :: Lens' DeleteCacheClusterResponse (Maybe CacheCluster)
dccrsCacheCluster = lens _dccrsCacheCluster (\ s a -> s{_dccrsCacheCluster = a});
-- | The response status code.
dccrsResponseStatus :: Lens' DeleteCacheClusterResponse Int
dccrsResponseStatus = lens _dccrsResponseStatus (\ s a -> s{_dccrsResponseStatus = a});
|
fmapfmapfmap/amazonka
|
amazonka-elasticache/gen/Network/AWS/ElastiCache/DeleteCacheCluster.hs
|
mpl-2.0
| 5,393 | 0 | 13 | 1,033 | 638 | 385 | 253 | 82 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE ScopedTypeVariables #-}
module HERMIT.Dictionary.Local.Let
( -- * Rewrites on Let Expressions
externals
-- ** Let Elimination
, letNonRecSubstR
, letNonRecSubstSafeR
, letSubstR
, letSubstSafeR
, letElimR
, letNonRecElimR
, letRecElimR
, progBindElimR
, progBindNonRecElimR
, progBindRecElimR
-- ** Let Introduction
, letIntroR
, letNonRecIntroR
, progNonRecIntroR
, nonRecIntroR
, letIntroUnfoldingR
-- ** Let Floating Out
, letFloatAppR
, letFloatArgR
, letFloatLetR
, letFloatLamR
, letFloatCaseR
, letFloatCaseAltR
, letFloatCastR
, letFloatExprR
, letFloatTopR
-- ** Let Floating In
, letFloatInR
, letFloatInAppR
, letFloatInCaseR
, letFloatInLamR
-- ** Miscallaneous
, reorderNonRecLetsR
, letTupleR
, letToCaseR
) where
import Control.Arrow
import Control.Monad
import Control.Monad.IO.Class
import Data.List (intersect, partition)
import Data.Monoid
import HERMIT.Core
import HERMIT.Context
import HERMIT.Monad
import HERMIT.Kure
import HERMIT.External
import HERMIT.GHC
import HERMIT.Name
import HERMIT.Utilities
import HERMIT.Dictionary.Common
import HERMIT.Dictionary.GHC hiding (externals)
import HERMIT.Dictionary.Inline hiding (externals)
import HERMIT.Dictionary.AlphaConversion hiding (externals)
import HERMIT.Dictionary.Local.Bind hiding (externals)
------------------------------------------------------------------------------
-- | Externals relating to 'Let' expressions.
externals :: [External]
externals =
[ external "let-subst" (promoteExprR letSubstR :: RewriteH LCore)
[ "Let substitution: (let x = e1 in e2) ==> (e2[e1/x])"
, "x must not be free in e1." ] .+ Deep .+ Eval
, external "let-subst-safe" (promoteExprR letSubstSafeR :: RewriteH LCore)
[ "Safe let substitution"
, "let x = e1 in e2, safe to inline without duplicating work ==> e2[e1/x],"
, "x must not be free in e1." ] .+ Deep .+ Eval
, external "let-nonrec-subst-safe" (promoteExprR letNonRecSubstSafeR :: RewriteH LCore)
[ "As let-subst-safe, but does not try to convert a recursive let into a non-recursive let first." ] .+ Deep .+ Eval
-- , external "safe-let-subst-plus" (promoteExprR safeLetSubstPlusR :: RewriteH LCore)
-- [ "Safe let substitution"
-- , "let { x = e1, ... } in e2, "
-- , " where safe to inline without duplicating work ==> e2[e1/x,...],"
-- , "only matches non-recursive lets" ] .+ Deep .+ Eval
, external "let-intro" (promoteExprR . letIntroR :: String -> RewriteH LCore)
[ "e => (let v = e in v), name of v is provided" ] .+ Shallow .+ Introduce
, external "let-intro-unfolding" (promoteExprR . letIntroUnfoldingR :: HermitName -> RewriteH LCore)
[ "e => let f' = defn[f'/f] in e[f'/f], name of f is provided" ]
, external "let-elim" (promoteExprR letElimR :: RewriteH LCore)
[ "Remove an unused let binding."
, "(let v = e1 in e2) ==> e2, if v is not free in e1 or e2." ] .+ Eval .+ Shallow
-- , external "let-constructor-reuse" (promoteR $ not_defined "constructor-reuse" :: RewriteH LCore)
-- [ "let v = C v1..vn in ... C v1..vn ... ==> let v = C v1..vn in ... v ..., fails otherwise" ] .+ Eval
, external "let-float-app" (promoteExprR letFloatAppR :: RewriteH LCore)
[ "(let v = ev in e) x ==> let v = ev in e x" ] .+ Commute .+ Shallow
, external "let-float-arg" (promoteExprR letFloatArgR :: RewriteH LCore)
[ "f (let v = ev in e) ==> let v = ev in f e" ] .+ Commute .+ Shallow
, external "let-float-lam" (promoteExprR letFloatLamR :: RewriteH LCore)
[ "The Full Laziness Transformation"
, "(\\ v1 -> let v2 = e1 in e2) ==> let v2 = e1 in (\\ v1 -> e2), if v1 is not free in e2."
, "If v1 = v2 then v1 will be alpha-renamed." ] .+ Commute .+ Shallow
, external "let-float-let" (promoteExprR letFloatLetR :: RewriteH LCore)
[ "let v = (let w = ew in ev) in e ==> let w = ew in let v = ev in e" ] .+ Commute .+ Shallow
, external "let-float-case" (promoteExprR letFloatCaseR :: RewriteH LCore)
[ "case (let v = ev in e) of ... ==> let v = ev in case e of ..." ] .+ Commute .+ Shallow .+ Eval
, external "let-float-case-alt" (promoteExprR (letFloatCaseAltR Nothing) :: RewriteH LCore)
[ "case s of { ... ; p -> let v = ev in e ; ... } "
, "==> let v = ev in case s of { ... ; p -> e ; ... } " ] .+ Commute .+ Shallow .+ Eval
, external "let-float-case-alt" (promoteExprR . letFloatCaseAltR . Just :: Int -> RewriteH LCore)
[ "Float a let binding from specified alternative."
, "case s of { ... ; p -> let v = ev in e ; ... } "
, "==> let v = ev in case s of { ... ; p -> e ; ... } " ] .+ Commute .+ Shallow .+ Eval
, external "let-float-cast" (promoteExprR letFloatCastR :: RewriteH LCore)
[ "cast (let bnds in e) co ==> let bnds in cast e co" ] .+ Commute .+ Shallow
, external "let-float-top" (promoteProgR letFloatTopR :: RewriteH LCore)
[ "v = (let bds in e) : prog ==> bds : v = e : prog" ] .+ Commute .+ Shallow
, external "let-float" (promoteProgR letFloatTopR <+ promoteExprR letFloatExprR :: RewriteH LCore)
[ "Float a Let whatever the context." ] .+ Commute .+ Shallow -- Don't include in bash, as each sub-rewrite is tagged "Bash" already.
, external "let-to-case" (promoteExprR letToCaseR :: RewriteH LCore)
[ "let v = ev in e ==> case ev of v -> e" ] .+ Commute .+ Shallow .+ PreCondition
-- , external "let-to-case-unbox" (promoteR $ not_defined "let-to-case-unbox" :: RewriteH LCore)
-- [ "let v = ev in e ==> case ev of C v1..vn -> let v = C v1..vn in e" ]
, external "let-float-in" (promoteExprR letFloatInR >+> anybuR (promoteExprR letElimR) :: RewriteH LCore)
[ "Float-in a let if possible." ] .+ Commute .+ Shallow
, external "let-float-in-app" ((promoteExprR letFloatInAppR >+> anybuR (promoteExprR letElimR)) :: RewriteH LCore)
[ "let v = ev in f a ==> (let v = ev in f) (let v = ev in a)" ] .+ Commute .+ Shallow
, external "let-float-in-case" ((promoteExprR letFloatInCaseR >+> anybuR (promoteExprR letElimR)) :: RewriteH LCore)
[ "let v = ev in case s of p -> e ==> case (let v = ev in s) of p -> let v = ev in e"
, "if v does not shadow a pattern binder in p" ] .+ Commute .+ Shallow
, external "let-float-in-lam" ((promoteExprR letFloatInLamR >+> anybuR (promoteExprR letElimR)) :: RewriteH LCore)
[ "let v = ev in \\ x -> e ==> \\ x -> let v = ev in e"
, "if v does not shadow x" ] .+ Commute .+ Shallow
, external "reorder-lets" (promoteExprR . reorderNonRecLetsR :: [String] -> RewriteH LCore)
[ "Re-order a sequence of nested non-recursive let bindings."
, "The argument list should contain the let-bound variables, in the desired order." ]
, external "let-tuple" (promoteExprR . letTupleR :: String -> RewriteH LCore)
[ "Combine nested non-recursive lets into case of a tuple."
, "E.g. let {v1 = e1 ; v2 = e2 ; v3 = e3} in body ==> case (e1,e2,e3) of {(v1,v2,v3) -> body}" ] .+ Commute
, external "prog-bind-elim" (promoteProgR progBindElimR :: RewriteH LCore)
[ "Remove unused top-level binding(s)."
, "prog-bind-nonrec-elim <+ prog-bind-rec-elim" ] .+ Eval .+ Shallow
, external "prog-bind-nonrec-elim" (promoteProgR progBindNonRecElimR :: RewriteH LCore)
[ "Remove unused top-level binding(s)."
, "v = e : prog ==> prog, if v is not free in prog and not exported." ] .+ Eval .+ Shallow
, external "prog-bind-rec-elim" (promoteProgR progBindRecElimR :: RewriteH LCore)
[ "Remove unused top-level binding(s)."
, "v+ = e+ : prog ==> v* = e* : prog, where v* is a subset of v+ consisting"
, "of vs that are free in prog or e+, or exported." ] .+ Eval .+ Shallow
]
-------------------------------------------------------------------------------------------
-- | (let x = e1 in e2) ==> (e2[e1/x]), (x must not be free in e1)
letSubstR :: (AddBindings c, ExtendPath c Crumb, ReadPath c Crumb, MonadCatch m) => Rewrite c m CoreExpr
letSubstR = letAllR (tryR recToNonrecR) idR >>> letNonRecSubstR
-- | As 'letNonRecSubstSafeR', but attempting to convert a singleton recursive binding to a non-recursive binding first.
letSubstSafeR :: (AddBindings c, ExtendPath c Crumb, ReadPath c Crumb, ReadBindings c, HasEmptyContext c, MonadCatch m) => Rewrite c m CoreExpr
letSubstSafeR = letAllR (tryR recToNonrecR) idR >>> letNonRecSubstSafeR
-- | @Let (NonRec v e) body@ ==> @body[e/v]@
letNonRecSubstR :: MonadCatch m => Rewrite c m CoreExpr
letNonRecSubstR = prefixFailMsg "Let substitution failed: " $
withPatFailMsg (wrongExprForm "Let (NonRec v rhs) body") $
do Let (NonRec v rhs) body <- idR
return (substCoreExpr v rhs body)
{-
TODO: This was written very early in the project by Andy.
It was later modified somewhat by Neil, but without reassessing the heurisitc as a whole.
It may need revisiting.
Safe Subst Heuristic
--------------------
Substitution is safe if (A) OR (B) OR (C).
(A) The let-bound variable is a type or coercion.
(B) The let-bound value is either:
(i) a variable;
(ii) a lambda;
(iii) an application that requires more value arguments before it can perform any computation.
(C) In the body, the let-bound variable must NOT occur:
(i) more than once;
(ii) inside a lambda.
-}
-- | Currently we always substitute types and coercions, and use a heuristic to decide whether to substitute expressions.
-- This may need revisiting.
letNonRecSubstSafeR :: forall c m. (AddBindings c, ExtendPath c Crumb, ReadPath c Crumb, ReadBindings c, HasEmptyContext c, MonadCatch m) => Rewrite c m CoreExpr
letNonRecSubstSafeR =
do Let (NonRec v _) _ <- idR
when (isId v) $ guardMsgM (safeSubstT v) "safety criteria not met."
letNonRecSubstR
where
safeSubstT :: Id -> Transform c m CoreExpr Bool
safeSubstT i = letNonRecT mempty safeBindT (safeOccursT i) (\ () -> (||))
-- what about other Expr constructors, e.g Cast?
safeBindT :: Transform c m CoreExpr Bool
safeBindT =
do c <- contextT
arr $ \ e ->
case e of
Var {} -> True
Lam {} -> True
App {} -> case collectArgs e of
(Var f,args) -> arityOf c f > length (filter (not . isTyCoArg) args) -- Neil: I've changed this to "not . isTyCoArg" rather than "not . isTypeArg".
-- This may not be the right thing to do though.
(other,args) -> case collectBinders other of
(bds,_) -> length bds > length args
_ -> False
safeOccursT :: Id -> Transform c m CoreExpr Bool
safeOccursT i =
do depth <- varBindingDepthT i
let occursHereT :: Transform c m Core ()
occursHereT = promoteExprT (exprIsOccurrenceOfT i depth >>> guardT)
-- lamOccurrenceT can only fail if the expression is not a Lam
-- return either 2 (occurrence) or 0 (no occurrence)
lamOccurrenceT :: Transform c m CoreExpr (Sum Int)
lamOccurrenceT = lamT mempty
(mtryM (Sum 2 <$ extractT (onetdT occursHereT)))
mappend
occurrencesT :: Transform c m Core (Sum Int)
occurrencesT = prunetdT (promoteExprT lamOccurrenceT <+ (Sum 1 <$ occursHereT))
extractT occurrencesT >>^ (getSum >>> (< 2))
-------------------------------------------------------------------------------------------
letElimR :: MonadCatch m => Rewrite c m CoreExpr
letElimR = prefixFailMsg "Let elimination failed: " $
withPatFailMsg (wrongExprForm "Let binds expr") $
do Let bg _ <- idR
case bg of
NonRec{} -> letNonRecElimR
Rec{} -> letRecElimR
-- | Remove an unused non-recursive let binding.
-- @let v = E1 in E2@ ==> @E2@, if @v@ is not free in @E2@
letNonRecElimR :: MonadCatch m => Rewrite c m CoreExpr
letNonRecElimR = withPatFailMsg (wrongExprForm "Let (NonRec v e1) e2") $
do Let (NonRec v _) e <- idR
guardMsg (v `notElemVarSet` freeVarsExpr e) "let-bound variable appears in the expression."
return e
-- | Remove all unused recursive let bindings in the current group.
letRecElimR :: MonadCatch m => Rewrite c m CoreExpr
letRecElimR = withPatFailMsg (wrongExprForm "Let (Rec v e1) e2") $
do Let (Rec bnds) body <- idR
let bodyFrees = freeIdsExpr body
bsAndFrees = map (second freeIdsExpr) bnds
usedIds = chaseDependencies bodyFrees bsAndFrees
bs = mkVarSet (map fst bsAndFrees)
liveBinders = bs `intersectVarSet` usedIds
if isEmptyVarSet liveBinders
then return body
else if bs `subVarSet` liveBinders
then fail "no dead binders to eliminate."
else return $ Let (Rec $ filter ((`elemVarSet` liveBinders) . fst) bnds) body
progBindElimR :: MonadCatch m => Rewrite c m CoreProg
progBindElimR = progBindNonRecElimR <+ progBindRecElimR
progBindNonRecElimR :: MonadCatch m => Rewrite c m CoreProg
progBindNonRecElimR = withPatFailMsg (wrongExprForm "ProgCons (NonRec v e1) e2") $ do
ProgCons (NonRec v _) p <- idR
guardMsg (v `notElemVarSet` freeVarsProg p) "variable appears in program body."
guardMsg (not (isExportedId v)) "variable is exported."
return p
-- | Remove all unused bindings at the top level.
progBindRecElimR :: MonadCatch m => Rewrite c m CoreProg
progBindRecElimR = withPatFailMsg (wrongExprForm "ProgCons (Rec v e1) e2") $
do ProgCons (Rec bnds) p <- idR
let pFrees = freeVarsProg p
bsAndFrees = map (second freeIdsExpr) bnds
usedIds = chaseDependencies pFrees bsAndFrees
bs = mkVarSet (map fst bsAndFrees)
liveBinders = (bs `intersectVarSet` usedIds) `unionVarSet` (filterVarSet isExportedId bs)
if isEmptyVarSet liveBinders
then return p
else if bs `subVarSet` liveBinders
then fail "no dead binders to eliminate."
else return $ ProgCons (Rec $ filter ((`elemVarSet` liveBinders) . fst) bnds) p
chaseDependencies :: VarSet -> [(Var,VarSet)] -> VarSet
chaseDependencies usedIds bsAndFrees = case partition ((`elemVarSet` usedIds) . fst) bsAndFrees of
([],_) -> usedIds
(used,unused) -> chaseDependencies (unionVarSets (usedIds : map snd used)) unused
-------------------------------------------------------------------------------------------
-- | @let v = ev in e@ ==> @case ev of v -> e@
letToCaseR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, ReadBindings c, MonadCatch m, MonadUnique m)
=> Rewrite c m CoreExpr
letToCaseR = prefixFailMsg "Converting Let to Case failed: " $
withPatFailMsg (wrongExprForm "Let (NonRec v e1) e2") $
do Let (NonRec v ev) _ <- idR
guardMsg (not $ isTyCoArg ev) "cannot case on a type or coercion."
caseBndr <- extractT (cloneVarAvoidingT v Nothing [v])
letT mempty (replaceVarR v caseBndr) $ \ () e' -> Case ev caseBndr (varType v) [(DEFAULT, [], e')]
-------------------------------------------------------------------------------------------
-- | @(let v = ev in e) x@ ==> @let v = ev in e x@
letFloatAppR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, BoundVars c, MonadCatch m, MonadUnique m)
=> Rewrite c m CoreExpr
letFloatAppR = prefixFailMsg "Let floating from App function failed: " $
withPatFailMsg (wrongExprForm "App (Let bnds body) e") $
do App (Let bnds body) e <- idR
let vs = mkVarSet (bindVars bnds) `intersectVarSet` freeVarsExpr e
if isEmptyVarSet vs
then return $ Let bnds (App body e)
else appAllR (alphaLetVarsR $ varSetElems vs) idR >>> letFloatAppR
-- | @f (let v = ev in e)@ ==> @let v = ev in f e@
letFloatArgR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, BoundVars c, MonadCatch m, MonadUnique m)
=> Rewrite c m CoreExpr
letFloatArgR = prefixFailMsg "Let floating from App argument failed: " $
withPatFailMsg (wrongExprForm "App f (Let bnds body)") $
do App f (Let bnds body) <- idR
let vs = mkVarSet (bindVars bnds) `intersectVarSet` freeVarsExpr f
if isEmptyVarSet vs
then return $ Let bnds (App f body)
else appAllR idR (alphaLetVarsR $ varSetElems vs) >>> letFloatArgR
-- | @let v = (let bds in e1) in e2@ ==> @let bds in let v = e1 in e2@
letFloatLetR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, BoundVars c, MonadCatch m, MonadUnique m)
=> Rewrite c m CoreExpr
letFloatLetR = prefixFailMsg "Let floating from Let failed: " $
withPatFailMsg (wrongExprForm "Let (NonRec v (Let bds e1)) e2") $
do Let (NonRec v (Let bds e1)) e2 <- idR
let vs = mkVarSet (bindVars bds) `intersectVarSet` freeVarsExpr e2
if isEmptyVarSet vs
then return $ Let bds (Let (NonRec v e1) e2)
else letNonRecAllR idR (alphaLetVarsR $ varSetElems vs) idR >>> letFloatLetR
-- | @(\ v -> let binds in e2)@ ==> @let binds in (\ v1 -> e2)@
-- Fails if @v@ occurs in the RHS of @binds@.
-- If @v@ is shadowed in binds, then @v@ will be alpha-renamed.
letFloatLamR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, BoundVars c, MonadCatch m, MonadUnique m)
=> Rewrite c m CoreExpr
letFloatLamR = prefixFailMsg "Let floating from Lam failed: " $
withPatFailMsg (wrongExprForm "Lam v1 (Let bds body)") $
do Lam v (Let binds body) <- idR
let bs = bindVars binds
fvs = freeVarsBind binds
guardMsg (v `notElemVarSet` fvs) (unqualifiedName v ++ " occurs in the RHS of the let-bindings.")
if v `elem` bs
then alphaLamR Nothing >>> letFloatLamR
else return $ Let binds (Lam v body)
-- | @case (let bnds in e) of bndr alts@ ==> @let bnds in (case e of bndr alts)@
-- Fails if any variables bound in @bnds@ occurs in @alts@.
letFloatCaseR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, BoundVars c, MonadCatch m, MonadUnique m)
=> Rewrite c m CoreExpr
letFloatCaseR = prefixFailMsg "Let floating from Case failed: " $
withPatFailMsg (wrongExprForm "Case (Let bnds e) w ty alts") $
do Case (Let bnds e) w ty alts <- idR
let captures = mkVarSet (bindVars bnds) `intersectVarSet` delVarSet (unionVarSets $ map freeVarsAlt alts) w
if isEmptyVarSet captures
then return $ Let bnds (Case e w ty alts)
else caseAllR (alphaLetVarsR $ varSetElems captures) idR idR (const idR) >>> letFloatCaseR
-- | case e of w { ... ; p -> let b = rhs in body ; ... } ==>
-- let b = rhs in case e of { ... ; p -> body ; ... }
--
-- where no variable in `p` or `w` occurs freely in `rhs`,
-- and where `b` does not capture a free variable in the overall case,
-- and where `w` is not rebound in `b`.
letFloatCaseAltR :: MonadCatch m => Maybe Int -> Rewrite c m CoreExpr
letFloatCaseAltR maybeN = prefixFailMsg "Let float from case alternative failed: " $
withPatFailMsg (wrongExprForm "Case s w ty alts") $ do
-- Perform the first safe let-floating out of a case alternative
let letFloatOneAltM :: MonadCatch m => Id -> VarSet -> [CoreAlt] -> m (CoreBind,[CoreAlt])
letFloatOneAltM w fvs = go
where go [] = fail "no lets can be safely floated from alternatives."
go (alt:rest) = (do (bind,alt') <- letFloatAltM w fvs alt
return (bind,alt':rest))
<+ liftM (second (alt :)) (go rest)
-- (p -> let bnds in body) ==> (bnds, p -> body)
letFloatAltM :: Monad m => Id -> VarSet -> CoreAlt -> m (CoreBind,CoreAlt)
letFloatAltM w fvs (con, vs, Let bnds body) = do
let bSet = mkVarSet (bindVars bnds)
vSet = mkVarSet (w:vs)
-- 'w' is not in 'fvs', but if it is rebound by 'b', doing this rewrite
-- would cause it to bind things that were previously bound by 'b'.
guardMsg (not (w `elemVarSet` bSet)) "floating would allow case binder to capture variables."
-- no free vars in 'rhs' are bound by 'p' or 'w'
guardMsg (isEmptyVarSet $ vSet `intersectVarSet` freeVarsBind bnds)
"floating would cause variables in rhs to become unbound."
-- no free vars in overall case are bound by 'b'
guardMsg (isEmptyVarSet $ bSet `intersectVarSet` fvs)
"floating would cause let binders to capture variables in case expression."
return (bnds, (con, vs, body))
letFloatAltM _ _ _ = fail "no let expression on alternative right-hand side."
Case e w ty alts <- idR
fvs <- arr freeVarsExpr
let l = length alts - 1
case maybeN of
Just n | n < 0 || n > l -> fail $ "valid alternative indices: 0 to " ++ show l
| otherwise -> do
let (pre, alt:suf) = splitAt n alts
(bnds,alt') <- letFloatAltM w fvs alt
return $ Let bnds $ Case e w ty $ pre ++ (alt':suf)
Nothing -> do
(bnds,alts') <- letFloatOneAltM w fvs alts
return $ Let bnds $ Case e w ty alts'
-- | @cast (let bnds in e) co@ ==> @let bnds in cast e co@
letFloatCastR :: MonadCatch m => Rewrite c m CoreExpr
letFloatCastR = prefixFailMsg "Let floating from Cast failed: " $
withPatFailMsg (wrongExprForm "Cast (Let bnds e) co") $
do Cast (Let bnds e) co <- idR
return $ Let bnds (Cast e co)
-- | Float a 'Let' through an expression, whatever the context.
letFloatExprR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, BoundVars c, MonadCatch m, MonadUnique m)
=> Rewrite c m CoreExpr
letFloatExprR = setFailMsg "Unsuitable expression for Let floating."
$ letFloatArgR <+ letFloatAppR <+ letFloatLetR <+ letFloatLamR
<+ letFloatCaseR <+ letFloatCaseAltR Nothing <+ letFloatCastR
-- | @'ProgCons' ('NonRec' v ('Let' bds e)) p@ ==> @'ProgCons' bds ('ProgCons' ('NonRec' v e) p)@
letFloatTopR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, BoundVars c, MonadCatch m, MonadUnique m)
=> Rewrite c m CoreProg
letFloatTopR = prefixFailMsg "Let floating to top level failed: " $
withPatFailMsg (wrongExprForm "NonRec v (Let bds e) `ProgCons` p") $
do ProgCons (NonRec v (Let bds e)) p <- idR
let bs = bindVars bds
guardMsg (all isId bs) "type and coercion bindings are not allowed at the top level."
let vs = intersectVarSet (mkVarSet bs) (freeVarsProg p)
if isEmptyVarSet vs
then return $ ProgCons bds (ProgCons (NonRec v e) p)
else consNonRecAllR idR (alphaLetVarsR $ varSetElems vs) idR >>> letFloatTopR
-------------------------------------------------------------------------------------------
-- | Float in a 'Let' if possible.
letFloatInR :: (AddBindings c, BoundVars c, ExtendPath c Crumb, ReadPath c Crumb, MonadCatch m, MonadUnique m)
=> Rewrite c m CoreExpr
letFloatInR = letFloatInCaseR <+ letFloatInAppR <+ letFloatInLamR
-- | @let v = ev in case s of p -> e@ ==> @case (let v = ev in s) of p -> let v = ev in e@,
-- if @v@ does not shadow a pattern binder in @p@
letFloatInCaseR :: (AddBindings c, BoundVars c, ExtendPath c Crumb, ReadPath c Crumb, MonadCatch m, MonadUnique m)
=> Rewrite c m CoreExpr
letFloatInCaseR = prefixFailMsg "Let floating in to case failed: " $
withPatFailMsg (wrongExprForm "Let bnds (Case s w ty alts)") $
do Let bnds (Case s w ty alts) <- idR
let bs = bindVars bnds
captured = bs `intersect` (w : concatMap altVars alts)
guardMsg (null captured) "let bindings would capture case pattern bindings."
#if __GLASGOW_HASKELL__ > 710
let unbound = mkVarSet bs `intersectVarSet` (tyCoVarsOfType ty `unionVarSet` freeVarsVar w)
#else
let unbound = mkVarSet bs `intersectVarSet` (tyVarsOfType ty `unionVarSet` freeVarsVar w)
#endif
guardMsg (isEmptyVarSet unbound) "type variables in case signature would become unbound."
return (Case (Let bnds s) w ty alts) >>> caseAllR idR idR idR (\_ -> altAllR idR (\_ -> idR) (arr (Let bnds) >>> alphaLetR))
-- | @let v = ev in f a@ ==> @(let v = ev in f) (let v = ev in a)@
letFloatInAppR :: (AddBindings c, BoundVars c, ExtendPath c Crumb, ReadPath c Crumb, MonadCatch m, MonadUnique m)
=> Rewrite c m CoreExpr
letFloatInAppR = prefixFailMsg "Let floating in to app failed: " $
withPatFailMsg (wrongExprForm "Let bnds (App e1 e2)") $
do Let bnds (App e1 e2) <- idR
lhs <- return (Let bnds e1) >>> alphaLetR
return $ App lhs (Let bnds e2)
-- | @let v = ev in \ x -> e@ ==> @\x -> let v = ev in e@
-- if @v@ does not shadow @x@
letFloatInLamR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, MonadCatch m) => Rewrite c m CoreExpr
letFloatInLamR = prefixFailMsg "Let floating in to lambda failed: " $
withPatFailMsg (wrongExprForm "Let bnds (Lam v e)") $
do Let bnds (Lam v e) <- idR
safe <- letT (arr bindVars) lamVarT $ flip notElem
guardMsg safe "let bindings would capture lambda binding."
return $ Lam v $ Let bnds e
-------------------------------------------------------------------------------------------
-- | Re-order a sequence of nested non-recursive let bindings.
-- The argument list should contain the let-bound variables, in the desired order.
reorderNonRecLetsR :: MonadCatch m => [String] -> Rewrite c m CoreExpr
reorderNonRecLetsR nms = prefixFailMsg "Reorder lets failed: " $
do guardMsg (notNull nms) "no names given."
guardMsg (nodups nms) "duplicate names given."
e <- idR
(ves,x) <- setFailMsg "insufficient non-recursive lets." $ takeNonRecLets (length nms) e
guardMsg (noneFreeIn ves) "some of the bound variables appear in the right-hand-sides."
e' <- mkNonRecLets `liftM` mapM (lookupName ves) nms `ap` return x
guardMsg (not $ exprSyntaxEq e e') "bindings already in specified order."
return e'
where
takeNonRecLets :: Monad m => Int -> CoreExpr -> m ([(Var,CoreExpr)],CoreExpr)
takeNonRecLets 0 x = return ([],x)
takeNonRecLets n (Let (NonRec v1 e1) x) = first ((v1,e1):) `liftM` takeNonRecLets (n-1) x
takeNonRecLets _ _ = fail "insufficient non-recursive lets."
noneFreeIn :: [(Var,CoreExpr)] -> Bool
noneFreeIn ves = let (vs,es) = unzip ves
in all (`notElemVarSet` unionVarSets (map freeVarsExpr es)) vs
lookupName :: Monad m => [(Var,CoreExpr)] -> String -> m (Var,CoreExpr)
lookupName ves nm = case filter (cmpString2Var nm . fst) ves of
[] -> fail $ "name " ++ nm ++ " not matched."
[ve] -> return ve
_ -> fail $ "multiple matches for " ++ nm ++ "."
mkNonRecLets :: [(Var,CoreExpr)] -> CoreExpr -> CoreExpr
mkNonRecLets [] x = x
mkNonRecLets ((v,e):ves) x = Let (NonRec v e) (mkNonRecLets ves x)
-------------------------------------------------------------------------------------------
-- | Combine nested non-recursive lets into case of a tuple.
-- E.g. let {v1 = e1 ; v2 = e2 ; v3 = e3} in body ==> case (e1,e2,e3) of {(v1,v2,v3) -> body}
letTupleR :: (MonadCatch m, MonadUnique m) => String -> Rewrite c m CoreExpr
letTupleR nm = prefixFailMsg "Let-tuple failed: " $
do (bnds, body) <- arr collectLets
let numBnds = length bnds
guardMsg (numBnds > 1) "at least two non-recursive let bindings of identifiers required."
let (vs, rhss) = unzip bnds
-- check if tupling the bindings would cause unbound variables
let frees = map freeVarsExpr (drop 1 rhss)
used = unionVarSets $ zipWith intersectVarSet (map (mkVarSet . (`take` vs)) [1..]) frees
if isEmptyVarSet used
then let rhs = mkCoreTup rhss
in constT $ do bndr <- newIdH nm (exprType rhs)
return $ mkSmallTupleCase vs body bndr rhs
else fail $ "the following bound variables are used in subsequent bindings: " ++ showVarSet used
where
-- we only collect identifiers (not type or coercion vars) because we intend to case on them.
collectLets :: CoreExpr -> ([(Id, CoreExpr)],CoreExpr)
collectLets (Let (NonRec v e) body) | isId v = first ((v,e):) (collectLets body)
collectLets expr = ([],expr)
-------------------------------------------------------------------------------------------
-- TODO: come up with a better naming scheme for these
-- This code could be factored better.
-- | @e@ ==> @let v = e in v@
letIntroR :: (MonadCatch m, MonadUnique m) => String -> Rewrite c m CoreExpr
letIntroR nm = do e <- idR
Let (NonRec v e') _ <- letNonRecIntroR nm e
return $ Let (NonRec v e') (varToCoreExpr v)
-- | @body@ ==> @let v = e in body@
letNonRecIntroR :: (MonadCatch m, MonadUnique m) => String -> CoreExpr -> Rewrite c m CoreExpr
letNonRecIntroR nm e = prefixFailMsg "Let-introduction failed: " $
contextfreeT $ \ body -> do v <- case e of
Type _ -> newTyVarH nm $ exprKindOrType e
_ -> newIdH nm $ exprKindOrType e
return $ Let (NonRec v e) body
-- This isn't a "Let", but it's serving the same role. Maybe create a Local/Prog module?
-- | @prog@ ==> @'ProgCons' (v = e) prog@
progNonRecIntroR :: (MonadCatch m, MonadUnique m) => String -> CoreExpr -> Rewrite c m CoreProg
progNonRecIntroR nm e = prefixFailMsg "Top-level binding introduction failed: " $
do guardMsg (not $ isTyCoArg e) "Top-level type or coercion definitions are prohibited."
contextfreeT $ \ prog -> do i <- newIdH nm (exprType e)
return $ ProgCons (NonRec i e) prog
-- | nonRecIntroR nm e = 'letNonRecIntroR nm e' <+ 'progNonRecIntroR nm e'
nonRecIntroR :: (MonadCatch m, MonadUnique m) => String -> CoreExpr -> Rewrite c m Core
nonRecIntroR nm e = readerT $ \case
ExprCore{} -> promoteExprR (letNonRecIntroR nm e)
ProgCore{} -> promoteProgR (progNonRecIntroR nm e)
_ -> fail "can only introduce non-recursive bindings at Program or Expression nodes."
-- | Introduce a local definition for a (possibly imported) identifier.
-- Rewrites occurrences of the identifier to point to this new local definiton.
letIntroUnfoldingR :: ( ReadBindings c, HasHermitMEnv m, LiftCoreM m
, MonadCatch m, MonadIO m, MonadThings m, MonadUnique m )
=> HermitName -> Rewrite c m CoreExpr
letIntroUnfoldingR nm = do
i <- findIdT nm
(rhs,_) <- getUnfoldingT AllBinders <<< return i
contextfreeT $ \ body -> do
i' <- cloneVarH id i
let subst = substCoreExpr i (varToCoreExpr i')
bnd = if i `elemUFM` freeVarsExpr rhs then Rec [(i', subst rhs)]
else NonRec i' rhs
body' = subst body
return $ mkCoreLet bnd body'
-------------------------------------------------------------------------------------------
|
conal/hermit
|
src/HERMIT/Dictionary/Local/Let.hs
|
bsd-2-clause
| 32,736 | 0 | 22 | 9,155 | 7,275 | 3,703 | 3,572 | 428 | 6 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module NumberSix.Message.Decode.Tests
( tests
) where
--------------------------------------------------------------------------------
import Test.Framework (Test, testGroup)
import Test.HUnit ((@=?))
--------------------------------------------------------------------------------
import NumberSix.Message
import NumberSix.Message.Decode
import NumberSix.Tests.Util
--------------------------------------------------------------------------------
tests :: Test
tests = testGroup "NumberSix.Message.Decode.Tests"
[ decodeTests
]
--------------------------------------------------------------------------------
decodeTests :: Test
decodeTests = cases "decode"
[ Message n "QUIT" [] @=??
decode "QUIT"
, Message (j (NickPrefix "nudded" n n)) "QUIT" [] @=??
decode ":nudded QUIT"
, Message
(j (NickPrefix "Itkovian" (j "Itkovian") (j "assail.ugent.be")))
"PRIVMSG"
["#zeus", "lol wut"] @=??
decode ":[email protected] PRIVMSG #zeus :lol wut"
, Message
(j (NickPrefix "relix" n (j "irccloud.com")))
"JOIN"
["#zeus"] @=??
decode ":[email protected] JOIN #zeus"
, Message
(j (ServerPrefix "wina.ugent.be"))
"001"
["number-six", "Welcome to the Kelder Network"] @=??
decode ":wina.ugent.be 001 number-six :Welcome to the Kelder Network"
]
where
-- Convenience
n = Nothing
j = Just
x @=?? y = Just x @=? y
|
itkovian/number-six
|
tests/NumberSix/Message/Decode/Tests.hs
|
bsd-3-clause
| 1,702 | 0 | 14 | 412 | 307 | 167 | 140 | 35 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TemplateHaskell #-}
import Control.Monad
import Data.Dynamic
import Data.Int
import Data.Word
import Test.Tasty.QuickCheck
import Test.Tasty.TH
import Language.Syntactic
import Language.Syntactic.Functional
import Feldspar.Representation
import Feldspar.Optimize
import Feldspar.Frontend ()
data NumExp
= VAR Int
| INT Int
| ADD NumExp NumExp
| SUB NumExp NumExp
| MUL NumExp NumExp
| NEG NumExp
deriving (Eq, Show)
evalNumExp :: Num a => (Int -> a) -> NumExp -> a
evalNumExp env (VAR v) = env v
evalNumExp env (INT i) = fromIntegral i
evalNumExp env (ADD a b) = evalNumExp env a + evalNumExp env b
evalNumExp env (SUB a b) = evalNumExp env a - evalNumExp env b
evalNumExp env (MUL a b) = evalNumExp env a * evalNumExp env b
evalNumExp env (NEG a) = negate (evalNumExp env a)
num2AST :: (Num a, PrimType a) => NumExp -> ASTF FeldDomain a
num2AST = simplify mempty . unData .
evalNumExp (\v -> sugarSymFeld $ VarT $ fromIntegral v)
genNumExp :: Gen NumExp
genNumExp = sized go
where
go s = frequency
[ -- Variable
(1, do v <- choose (0,4)
return $ VAR v
)
-- Literal
, (1, fmap INT $ elements [-100 .. 100])
, (s, binOp ADD)
, (s, binOp SUB)
, (s, binOp MUL)
, (s, unOp NEG)
]
where
binOp op = liftM2 op (go (s `div` 2)) (go (s `div` 2))
unOp op = liftM op (go (s-1))
instance Arbitrary NumExp
where
arbitrary = genNumExp
shrink (ADD a b) = a : b : [ADD a' b | a' <- shrink a] ++ [ADD a b' | b' <- shrink b]
shrink (SUB a b) = a : b : [SUB a' b | a' <- shrink a] ++ [SUB a b' | b' <- shrink b]
shrink (MUL a b) = a : b : [MUL a' b | a' <- shrink a] ++ [MUL a b' | b' <- shrink b]
shrink (NEG a) = a : [NEG a' | a' <- shrink a]
shrink _ = []
-- Test that numeric expressions are simplified correctly
prop_numExp :: (a ~ Int32) => (a,a,a,a,a) -> NumExp -> Bool
prop_numExp (a,b,c,d,e) numExp =
evalNumExp env1 numExp == evalOpen env2 (num2AST numExp)
where
env1 v = [a,b,c,d,e] !! v
env2 = zip ([0..] :: [Name]) $ map toDyn [a,b,c,d,e]
-- Test that inexact numeric expressions are handled correctly
--
-- This property fails if one changes `isExact` to `const True`
prop_numExp_inexact :: (a ~ Float) => (a,a,a,a,a) -> NumExp -> Bool
prop_numExp_inexact (a,b,c,d,e) numExp =
evalNumExp env1 numExp == evalOpen env2 (num2AST numExp)
where
env1 v = [a,b,c,d,e] !! v
env2 = zip ([0..] :: [Name]) $ map toDyn [a,b,c,d,e]
prop_simplify_idempotent_int :: NumExp -> Property
prop_simplify_idempotent_int exp = counterexample (unlines [show e, show $ simplify mempty e])
$ e == simplify mempty e
where
e :: ASTF FeldDomain Int32
e = num2AST exp
prop_simplify_idempotent_word :: NumExp -> Bool
prop_simplify_idempotent_word exp = e == simplify mempty e
where
e :: ASTF FeldDomain Word32
e = num2AST exp
prop_simplify_idempotent_double :: NumExp -> Bool
prop_simplify_idempotent_double exp = e == simplify mempty e
where
e :: ASTF FeldDomain Double
e = num2AST exp
main = $defaultMainGenerator
|
kmate/raw-feldspar
|
tests/NumSimpl.hs
|
bsd-3-clause
| 3,235 | 0 | 14 | 846 | 1,333 | 705 | 628 | 75 | 1 |
-- |
-- Module : Test.LeanCheck.Error
-- Copyright : (c) 2015-2020 Rudy Matela
-- License : 3-Clause BSD (see the file LICENSE)
-- Maintainer : Rudy Matela <[email protected]>
--
-- This module is part of LeanCheck,
-- a simple enumerative property-based testing library.
--
-- This module re-exports "Test.LeanCheck" but some test functions have been
-- specialized to catch errors (see the explicit export list below).
--
-- This module is unsafe as it uses `unsafePerformIO` to catch errors.
{-# LANGUAGE CPP #-}
module Test.LeanCheck.Error
( holds
, fails
, exists
, counterExample
, counterExamples
, witness
, witnesses
, results
, fromError
, errorToNothing
, errorToFalse
, errorToTrue
, errorToLeft
, anyErrorToNothing
, anyErrorToLeft
, (?==?)
, (!==!)
, module Test.LeanCheck
)
where
#if __GLASGOW_HASKELL__ <= 704
import Prelude hiding (catch)
#endif
import Test.LeanCheck hiding
( holds
, fails
, exists
, counterExample
, counterExamples
, witness
, witnesses
, results
)
import qualified Test.LeanCheck as C
( holds
, fails
, results
)
import Control.Monad (liftM)
import System.IO.Unsafe (unsafePerformIO)
import Data.Maybe (listToMaybe, fromMaybe)
import Data.Function (on)
import Control.Exception ( evaluate
, catch
#if __GLASGOW_HASKELL__
, SomeException
, ArithException
, ArrayException
, ErrorCall
, PatternMatchFail
, catches
, Handler (Handler)
#endif
)
etom :: Either b a -> Maybe a
etom (Right x) = Just x
etom (Left _) = Nothing
-- | Transforms a value into 'Just' that value or 'Nothing' on some errors:
--
-- * ArithException
-- * ArrayException
-- * ErrorCall
-- * PatternMatchFail
--
-- > > errorToNothing False
-- > Just False
--
-- > > errorToNothing (0 :: Int)
-- > Just 0
--
-- > > errorToNothing (undefined :: ())
-- > Nothing
--
-- This function uses 'unsafePerformIO'.
errorToNothing :: a -> Maybe a
errorToNothing = etom . errorToLeft
-- | Transforms a value into 'Just' that value or 'Nothing' on error.
anyErrorToNothing :: a -> Maybe a
anyErrorToNothing = etom . anyErrorToLeft
-- | Transforms a value into 'Right' that value or 'Left String' on some errors:
--
-- * ArithException
-- * ArrayException
-- * ErrorCall
-- * PatternMatchFail
--
-- > > errorToLeft False
-- > Just False
--
-- > > errorToLeft (0 :: Int)
-- > Just 0
--
-- > > errorToLeft (undefined :: ())
-- > Left "Prelude.undefined"
--
-- > > errorToLeft (error "error message")
-- > Left "error message"
--
-- > > errorToLeft (1 `div` 0 :: Int)
-- > Left "divide by zero"
--
-- Only the first line of the error's string representation is included.
--
-- This function uses 'unsafePerformIO'.
errorToLeft :: a -> Either String a
errorToLeft x = unsafePerformIO $
#if __GLASGOW_HASKELL__
(Right `liftM` evaluate x) `catches`
[ Handler $ \e -> return . Left $ show1st (e :: ArithException)
, Handler $ \e -> return . Left $ show1st (e :: ArrayException)
, Handler $ \e -> return . Left $ show1st (e :: ErrorCall)
, Handler $ \e -> return . Left $ show1st (e :: PatternMatchFail)
]
#else
(Right `liftM` evaluate x) `catch` (return . Left . show1st)
#endif
where
show1st :: Show a => a -> String
show1st = concat . take 1 . lines . show
-- | Transforms a value into 'Right' that value or 'Left String' on error.
--
-- Only the first line of the error's string representation is included.
--
-- This function uses 'unsafePerformIO'. See: 'errorToLeft'.
anyErrorToLeft :: a -> Either String a
anyErrorToLeft x = unsafePerformIO $
#if __GLASGOW_HASKELL__
(Right `liftM` evaluate x) `catch` (\e -> return . Left $ show1st (e :: SomeException))
#else
(Right `liftM` evaluate x) `catch` (return . Left . show1st)
#endif
where
show1st :: Show a => a -> String
show1st = concat . take 1 . lines . show
-- | Transforms errors into 'False' values.
--
-- > > errorToFalse False
-- > False
--
-- > > errorToFalse True
-- > True
--
-- > > errorToFalse undefined
-- > False
--
-- This functions uses 'unsafePerformIO'.
errorToFalse :: Bool -> Bool
errorToFalse = fromError False
-- | Transforms errors into 'True' values.
--
-- > > errorToTrue False
-- > False
--
-- > > errorToTrue True
-- > True
--
-- > > errorToTrue undefined
-- > True
--
-- This functions uses 'unsafePerformIO'.
errorToTrue :: Bool -> Bool
errorToTrue = fromError True
-- | Transforms errors into a default value.
--
-- > > fromError 0 (15 :: Int)
-- > 15
--
-- > > fromError 0 (undefined :: Int)
-- > 0
fromError :: a -> a -> a
fromError x = fromMaybe x . errorToNothing
-- | Equality '==' lifted over 'errorToNothing'
--
-- > > 1 `div` 1 ?==? 2 `div` 2
-- > True
--
-- > > 1 `div` 1 ?==? 1 `div` 2
-- > False
--
-- > > 1 `div` 1 ?==? 1 `div` 0
-- > False
--
-- > > 6 `mod` 0 ?==? 2 `div` 0
-- > True
--
-- > > head [] ?==? tail []
-- > True
--
-- > > error "a" ?==? error "a"
-- > True
--
-- > > error "a" ?==? error "b"
-- > True
--
-- This function consider error values equal.
(?==?) :: Eq a => a -> a -> Bool
(?==?) = (==) `on` errorToNothing
infix 4 ?==?
-- | Equality '==' lifted over 'errorToLeft'
--
-- > > 1 `div` 1 !==! 2 `div` 2
-- > True
--
-- > > 1 `div` 1 !==! 1 `div` 2
-- > False
--
-- > > 1 `div` 1 !==! 1 `div` 0
-- > False
--
-- > > 6 `mod` 0 !==! 2 `div` 0
-- > True
--
-- > > head [] !==! tail []
-- > False
--
-- > > error "a" !==! error "a"
-- > True
--
-- > > error "a" !==! error "b"
-- > False
--
-- On error, this function returns the result
-- of comparing the first line of error values.
(!==!) :: Eq a => a -> a -> Bool
(!==!) = (==) `on` errorToLeft
infix 4 !==!
-- | An error-catching version of 'Test.LeanCheck.holds'
-- that returns 'False' in case of errors.
--
-- > prop_cannot_be_seven :: Int -> Bool
-- > prop_cannot_be_seven 7 = error "Argument cannot be seven"
-- > prop_cannot_be_seven _ = True
--
-- > > import Test.LeanCheck
-- > > holds 100 prop_cannot_be_seven
-- > *** Exception: Argument cannot be seven
--
-- > > import Test.LeanCheck.Error
-- > > holds 100 prop_cannot_be_seven
-- > False
holds :: Testable a => Int -> a -> Bool
holds n = errorToFalse . C.holds n
-- | An error-catching version of 'Test.LeanCheck.fails'
-- that returns 'True' in case of errors.
fails :: Testable a => Int -> a -> Bool
fails n = errorToTrue . C.fails n
-- | An error-catching version of 'Test.LeanCheck.exists'.
exists :: Testable a => Int -> a -> Bool
exists n = or . take n . map snd . results
-- | An error-catching version of 'Test.LeanCheck.counterExample'.
counterExample :: Testable a => Int -> a -> Maybe [String]
counterExample n = listToMaybe . counterExamples n
-- | An error-catching version of 'Test.LeanCheck.witness'.
witness :: Testable a => Int -> a -> Maybe [String]
witness n = listToMaybe . witnesses n
-- | An error-catching version of 'Test.LeanCheck.counterExamples'.
counterExamples :: Testable a => Int -> a -> [[String]]
counterExamples n = map fst . filter (not . snd) . take n . results
-- | An error-catching version of 'Test.LeanCheck.witnesses'.
witnesses :: Testable a => Int -> a -> [[String]]
witnesses n = map fst . filter snd . take n . results
-- | An error-catching version of 'Test.LeanCheck.results'.
results :: Testable a => a -> [([String],Bool)]
results = map (mapSnd errorToFalse) . C.results
where
mapSnd f (x,y) = (x,f y)
|
rudymatela/llcheck
|
src/Test/LeanCheck/Error.hs
|
bsd-3-clause
| 7,635 | 0 | 11 | 1,796 | 1,321 | 804 | 517 | 86 | 1 |
module Midi.Util (
every,
drops
) where
every :: Int -> [a] -> [a]
every n | n > 0 = go
| otherwise = error ("every called with invalid spacing: " ++ show n)
where
go [] = []
go xs@(x:_) = x : go (drop n xs)
-- Passed:
--
-- prop_equiv :: Int -> [Int] -> Bool
-- prop_equiv n xs = every2 n' xs == every n' xs where n' = abs n + 1
--
-- import Data.List.Split
--
-- every2 :: Int -> [a] -> [a]
-- every2 n = map head . splitEvery n
drops :: [Int] -> [a] -> [a]
drops [] xs = xs
drops _ [] = []
drops (n:ns) xs@(x:_) = x : drops (ns) (drop n xs)
|
beni55/Midi
|
src/Midi/Util.hs
|
bsd-3-clause
| 580 | 0 | 10 | 165 | 224 | 122 | 102 | 12 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
module Lazyfoo.Lesson11 (main) where
import Control.Lens.Operators
import Control.Monad
import Foreign.C.Types
import Linear
import Linear.Affine
import SDL (($=))
import qualified SDL
import Paths_sdl2 (getDataFileName)
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
screenWidth, screenHeight :: CInt
(screenWidth, screenHeight) = (640, 480)
data Texture = Texture SDL.Texture (V2 CInt)
loadTexture :: SDL.Renderer -> FilePath -> IO Texture
loadTexture r filePath = do
surface <- getDataFileName filePath >>= SDL.loadBMP
size <- SDL.surfaceDimensions surface
let key = V4 0 maxBound maxBound maxBound
SDL.surfaceColorKey surface $= Just key
t <- SDL.createTextureFromSurface r surface
SDL.freeSurface surface
return (Texture t size)
renderTexture :: SDL.Renderer -> Texture -> Point V2 CInt -> Maybe (SDL.Rectangle CInt) -> IO ()
renderTexture r (Texture t size) xy clip =
let dstSize = maybe size (\(SDL.Rectangle _ size') -> size') clip
in SDL.copy r t clip (Just (SDL.Rectangle xy dstSize))
main :: IO ()
main = do
SDL.initialize [SDL.InitVideo]
SDL.HintRenderScaleQuality $= SDL.ScaleLinear
do renderQuality <- SDL.get SDL.HintRenderScaleQuality
when (renderQuality /= SDL.ScaleLinear) $
putStrLn "Warning: Linear texture filtering not enabled!"
window <-
SDL.createWindow
"SDL Tutorial"
SDL.defaultWindow {SDL.windowInitialSize = V2 screenWidth screenHeight}
SDL.showWindow window
renderer <-
SDL.createRenderer
window
(-1)
(SDL.RendererConfig
{ SDL.rendererType = SDL.SoftwareRenderer
, SDL.rendererTargetTexture = False
})
SDL.rendererDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
spriteSheetTexture <- loadTexture renderer "examples/lazyfoo/dots.bmp"
let spriteSize = V2 100 100
clip1 = SDL.Rectangle (P (V2 0 0)) spriteSize
clip2 = SDL.Rectangle (P (V2 100 0)) spriteSize
clip3 = SDL.Rectangle (P (V2 0 100)) spriteSize
clip4 = SDL.Rectangle (P (V2 100 100)) spriteSize
let loop = do
let collectEvents = do
e <- SDL.pollEvent
case e of
Nothing -> return []
Just e' -> (e' :) <$> collectEvents
events <- collectEvents
let quit = any (== SDL.QuitEvent) $ map SDL.eventPayload events
SDL.rendererDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
SDL.clear renderer
renderTexture renderer spriteSheetTexture (P (V2 0 0)) (Just clip1)
renderTexture renderer spriteSheetTexture (P (V2 (screenWidth - spriteSize ^. _x) 0)) (Just clip2)
renderTexture renderer spriteSheetTexture (P (V2 0 (screenHeight - spriteSize ^. _y))) (Just clip3)
renderTexture renderer spriteSheetTexture (P (V2 (screenWidth - spriteSize ^. _x) (screenHeight - spriteSize ^. _y))) (Just clip4)
SDL.present renderer
unless quit loop
loop
SDL.destroyRenderer renderer
SDL.destroyWindow window
SDL.quit
|
oldmanmike/sdl2
|
examples/lazyfoo/Lesson11.hs
|
bsd-3-clause
| 3,091 | 0 | 21 | 679 | 1,018 | 497 | 521 | 74 | 2 |
-----------------------------------------------------------------------------
--
-- Generating machine code (instruction selection)
--
-- (c) The University of Glasgow 1996-2004
--
-----------------------------------------------------------------------------
-- This is a big module, but, if you pay attention to
-- (a) the sectioning, and (b) the type signatures, the
-- structure should not be too overwhelming.
{-# LANGUAGE GADTs #-}
module X86.CodeGen (
cmmTopCodeGen,
generateJumpTableForInstr,
InstrBlock
)
where
#include "HsVersions.h"
#include "nativeGen/NCG.h"
#include "../includes/MachDeps.h"
-- NCG stuff:
import X86.Instr
import X86.Cond
import X86.Regs
import X86.RegInfo
import CodeGen.Platform
import CPrim
import Instruction
import PIC
import NCGMonad
import Size
import Reg
import Platform
-- Our intermediate code:
import BasicTypes
import BlockId
import Module ( primPackageId )
import PprCmm ()
import CmmUtils
import Cmm
import Hoopl
import CLabel
-- The rest:
import ForeignCall ( CCallConv(..) )
import OrdList
import Outputable
import Unique
import FastString
import FastBool ( isFastTrue )
import DynFlags
import Util
import Control.Monad
import Data.Bits
import Data.Int
import Data.Maybe
import Data.Word
is32BitPlatform :: NatM Bool
is32BitPlatform = do
dflags <- getDynFlags
return $ target32Bit (targetPlatform dflags)
sse2Enabled :: NatM Bool
sse2Enabled = do
dflags <- getDynFlags
return (isSse2Enabled dflags)
sse4_2Enabled :: NatM Bool
sse4_2Enabled = do
dflags <- getDynFlags
return (isSse4_2Enabled dflags)
if_sse2 :: NatM a -> NatM a -> NatM a
if_sse2 sse2 x87 = do
b <- sse2Enabled
if b then sse2 else x87
cmmTopCodeGen
:: RawCmmDecl
-> NatM [NatCmmDecl (Alignment, CmmStatics) Instr]
cmmTopCodeGen (CmmProc info lab live graph) = do
let blocks = toBlockListEntryFirst graph
(nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
picBaseMb <- getPicBaseMaybeNat
dflags <- getDynFlags
let proc = CmmProc info lab live (ListGraph $ concat nat_blocks)
tops = proc : concat statics
os = platformOS $ targetPlatform dflags
case picBaseMb of
Just picBase -> initializePicBase_x86 ArchX86 os picBase tops
Nothing -> return tops
cmmTopCodeGen (CmmData sec dat) = do
return [CmmData sec (1, dat)] -- no translation, we just use CmmStatic
basicBlockCodeGen
:: CmmBlock
-> NatM ( [NatBasicBlock Instr]
, [NatCmmDecl (Alignment, CmmStatics) Instr])
basicBlockCodeGen block = do
let (CmmEntry id, nodes, tail) = blockSplit block
stmts = blockToList nodes
mid_instrs <- stmtsToInstrs stmts
tail_instrs <- stmtToInstrs tail
let instrs = mid_instrs `appOL` tail_instrs
-- code generation may introduce new basic block boundaries, which
-- are indicated by the NEWBLOCK instruction. We must split up the
-- instruction stream into basic blocks again. Also, we extract
-- LDATAs here too.
let
(top,other_blocks,statics) = foldrOL mkBlocks ([],[],[]) instrs
mkBlocks (NEWBLOCK id) (instrs,blocks,statics)
= ([], BasicBlock id instrs : blocks, statics)
mkBlocks (LDATA sec dat) (instrs,blocks,statics)
= (instrs, blocks, CmmData sec dat:statics)
mkBlocks instr (instrs,blocks,statics)
= (instr:instrs, blocks, statics)
return (BasicBlock id top : other_blocks, statics)
stmtsToInstrs :: [CmmNode e x] -> NatM InstrBlock
stmtsToInstrs stmts
= do instrss <- mapM stmtToInstrs stmts
return (concatOL instrss)
stmtToInstrs :: CmmNode e x -> NatM InstrBlock
stmtToInstrs stmt = do
dflags <- getDynFlags
is32Bit <- is32BitPlatform
case stmt of
CmmComment s -> return (unitOL (COMMENT s))
CmmAssign reg src
| isFloatType ty -> assignReg_FltCode size reg src
| is32Bit && isWord64 ty -> assignReg_I64Code reg src
| otherwise -> assignReg_IntCode size reg src
where ty = cmmRegType dflags reg
size = cmmTypeSize ty
CmmStore addr src
| isFloatType ty -> assignMem_FltCode size addr src
| is32Bit && isWord64 ty -> assignMem_I64Code addr src
| otherwise -> assignMem_IntCode size addr src
where ty = cmmExprType dflags src
size = cmmTypeSize ty
CmmUnsafeForeignCall target result_regs args
-> genCCall is32Bit target result_regs args
CmmBranch id -> genBranch id
CmmCondBranch arg true false -> do b1 <- genCondJump true arg
b2 <- genBranch false
return (b1 `appOL` b2)
CmmSwitch arg ids -> do dflags <- getDynFlags
genSwitch dflags arg ids
CmmCall { cml_target = arg
, cml_args_regs = gregs } -> do
dflags <- getDynFlags
genJump arg (jumpRegs dflags gregs)
_ ->
panic "stmtToInstrs: statement should have been cps'd away"
jumpRegs :: DynFlags -> [GlobalReg] -> [Reg]
jumpRegs dflags gregs = [ RegReal r | Just r <- map (globalRegMaybe platform) gregs ]
where platform = targetPlatform dflags
--------------------------------------------------------------------------------
-- | 'InstrBlock's are the insn sequences generated by the insn selectors.
-- They are really trees of insns to facilitate fast appending, where a
-- left-to-right traversal yields the insns in the correct order.
--
type InstrBlock
= OrdList Instr
-- | Condition codes passed up the tree.
--
data CondCode
= CondCode Bool Cond InstrBlock
-- | a.k.a "Register64"
-- Reg is the lower 32-bit temporary which contains the result.
-- Use getHiVRegFromLo to find the other VRegUnique.
--
-- Rules of this simplified insn selection game are therefore that
-- the returned Reg may be modified
--
data ChildCode64
= ChildCode64
InstrBlock
Reg
-- | Register's passed up the tree. If the stix code forces the register
-- to live in a pre-decided machine register, it comes out as @Fixed@;
-- otherwise, it comes out as @Any@, and the parent can decide which
-- register to put it in.
--
data Register
= Fixed Size Reg InstrBlock
| Any Size (Reg -> InstrBlock)
swizzleRegisterRep :: Register -> Size -> Register
swizzleRegisterRep (Fixed _ reg code) size = Fixed size reg code
swizzleRegisterRep (Any _ codefn) size = Any size codefn
-- | Grab the Reg for a CmmReg
getRegisterReg :: Platform -> Bool -> CmmReg -> Reg
getRegisterReg _ use_sse2 (CmmLocal (LocalReg u pk))
= let sz = cmmTypeSize pk in
if isFloatSize sz && not use_sse2
then RegVirtual (mkVirtualReg u FF80)
else RegVirtual (mkVirtualReg u sz)
getRegisterReg platform _ (CmmGlobal mid)
= case globalRegMaybe platform mid of
Just reg -> RegReal $ reg
Nothing -> pprPanic "getRegisterReg-memory" (ppr $ CmmGlobal mid)
-- By this stage, the only MagicIds remaining should be the
-- ones which map to a real machine register on this
-- platform. Hence ...
-- | Memory addressing modes passed up the tree.
data Amode
= Amode AddrMode InstrBlock
{-
Now, given a tree (the argument to an CmmLoad) that references memory,
produce a suitable addressing mode.
A Rule of the Game (tm) for Amodes: use of the addr bit must
immediately follow use of the code part, since the code part puts
values in registers which the addr then refers to. So you can't put
anything in between, lest it overwrite some of those registers. If
you need to do some other computation between the code part and use of
the addr bit, first store the effective address from the amode in a
temporary, then do the other computation, and then use the temporary:
code
LEA amode, tmp
... other computation ...
... (tmp) ...
-}
-- | Check whether an integer will fit in 32 bits.
-- A CmmInt is intended to be truncated to the appropriate
-- number of bits, so here we truncate it to Int64. This is
-- important because e.g. -1 as a CmmInt might be either
-- -1 or 18446744073709551615.
--
is32BitInteger :: Integer -> Bool
is32BitInteger i = i64 <= 0x7fffffff && i64 >= -0x80000000
where i64 = fromIntegral i :: Int64
-- | Convert a BlockId to some CmmStatic data
jumpTableEntry :: DynFlags -> Maybe BlockId -> CmmStatic
jumpTableEntry dflags Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel)
where blockLabel = mkAsmTempLabel (getUnique blockid)
-- -----------------------------------------------------------------------------
-- General things for putting together code sequences
-- Expand CmmRegOff. ToDo: should we do it this way around, or convert
-- CmmExprs into CmmRegOff?
mangleIndexTree :: DynFlags -> CmmReg -> Int -> CmmExpr
mangleIndexTree dflags reg off
= CmmMachOp (MO_Add width) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) width)]
where width = typeWidth (cmmRegType dflags reg)
-- | The dual to getAnyReg: compute an expression into a register, but
-- we don't mind which one it is.
getSomeReg :: CmmExpr -> NatM (Reg, InstrBlock)
getSomeReg expr = do
r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed _ reg code ->
return (reg, code)
assignMem_I64Code :: CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_I64Code addrTree valueTree = do
Amode addr addr_code <- getAmode addrTree
ChildCode64 vcode rlo <- iselExpr64 valueTree
let
rhi = getHiVRegFromLo rlo
-- Little-endian store
mov_lo = MOV II32 (OpReg rlo) (OpAddr addr)
mov_hi = MOV II32 (OpReg rhi) (OpAddr (fromJust (addrOffset addr 4)))
return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi)
assignReg_I64Code :: CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_I64Code (CmmLocal (LocalReg u_dst _)) valueTree = do
ChildCode64 vcode r_src_lo <- iselExpr64 valueTree
let
r_dst_lo = RegVirtual $ mkVirtualReg u_dst II32
r_dst_hi = getHiVRegFromLo r_dst_lo
r_src_hi = getHiVRegFromLo r_src_lo
mov_lo = MOV II32 (OpReg r_src_lo) (OpReg r_dst_lo)
mov_hi = MOV II32 (OpReg r_src_hi) (OpReg r_dst_hi)
return (
vcode `snocOL` mov_lo `snocOL` mov_hi
)
assignReg_I64Code _ _
= panic "assignReg_I64Code(i386): invalid lvalue"
iselExpr64 :: CmmExpr -> NatM ChildCode64
iselExpr64 (CmmLit (CmmInt i _)) = do
(rlo,rhi) <- getNewRegPairNat II32
let
r = fromIntegral (fromIntegral i :: Word32)
q = fromIntegral (fromIntegral (i `shiftR` 32) :: Word32)
code = toOL [
MOV II32 (OpImm (ImmInteger r)) (OpReg rlo),
MOV II32 (OpImm (ImmInteger q)) (OpReg rhi)
]
return (ChildCode64 code rlo)
iselExpr64 (CmmLoad addrTree ty) | isWord64 ty = do
Amode addr addr_code <- getAmode addrTree
(rlo,rhi) <- getNewRegPairNat II32
let
mov_lo = MOV II32 (OpAddr addr) (OpReg rlo)
mov_hi = MOV II32 (OpAddr (fromJust (addrOffset addr 4))) (OpReg rhi)
return (
ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi)
rlo
)
iselExpr64 (CmmReg (CmmLocal (LocalReg vu ty))) | isWord64 ty
= return (ChildCode64 nilOL (RegVirtual $ mkVirtualReg vu II32))
-- we handle addition, but rather badly
iselExpr64 (CmmMachOp (MO_Add _) [e1, CmmLit (CmmInt i _)]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
(rlo,rhi) <- getNewRegPairNat II32
let
r = fromIntegral (fromIntegral i :: Word32)
q = fromIntegral (fromIntegral (i `shiftR` 32) :: Word32)
r1hi = getHiVRegFromLo r1lo
code = code1 `appOL`
toOL [ MOV II32 (OpReg r1lo) (OpReg rlo),
ADD II32 (OpImm (ImmInteger r)) (OpReg rlo),
MOV II32 (OpReg r1hi) (OpReg rhi),
ADC II32 (OpImm (ImmInteger q)) (OpReg rhi) ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
ChildCode64 code2 r2lo <- iselExpr64 e2
(rlo,rhi) <- getNewRegPairNat II32
let
r1hi = getHiVRegFromLo r1lo
r2hi = getHiVRegFromLo r2lo
code = code1 `appOL`
code2 `appOL`
toOL [ MOV II32 (OpReg r1lo) (OpReg rlo),
ADD II32 (OpReg r2lo) (OpReg rlo),
MOV II32 (OpReg r1hi) (OpReg rhi),
ADC II32 (OpReg r2hi) (OpReg rhi) ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_UU_Conv _ W64) [expr]) = do
fn <- getAnyReg expr
r_dst_lo <- getNewRegNat II32
let r_dst_hi = getHiVRegFromLo r_dst_lo
code = fn r_dst_lo
return (
ChildCode64 (code `snocOL`
MOV II32 (OpImm (ImmInt 0)) (OpReg r_dst_hi))
r_dst_lo
)
iselExpr64 expr
= pprPanic "iselExpr64(i386)" (ppr expr)
--------------------------------------------------------------------------------
getRegister :: CmmExpr -> NatM Register
getRegister e = do dflags <- getDynFlags
is32Bit <- is32BitPlatform
getRegister' dflags is32Bit e
getRegister' :: DynFlags -> Bool -> CmmExpr -> NatM Register
getRegister' dflags is32Bit (CmmReg reg)
= case reg of
CmmGlobal PicBaseReg
| is32Bit ->
-- on x86_64, we have %rip for PicBaseReg, but it's not
-- a full-featured register, it can only be used for
-- rip-relative addressing.
do reg' <- getPicBaseNat (archWordSize is32Bit)
return (Fixed (archWordSize is32Bit) reg' nilOL)
_ ->
do use_sse2 <- sse2Enabled
let
sz = cmmTypeSize (cmmRegType dflags reg)
size | not use_sse2 && isFloatSize sz = FF80
| otherwise = sz
--
let platform = targetPlatform dflags
return (Fixed size (getRegisterReg platform use_sse2 reg) nilOL)
getRegister' dflags is32Bit (CmmRegOff r n)
= getRegister' dflags is32Bit $ mangleIndexTree dflags r n
-- for 32-bit architectuers, support some 64 -> 32 bit conversions:
-- TO_W_(x), TO_W_(x >> 32)
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W64 W32) [x])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W64 W32) [x])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' _ _ (CmmLit lit@(CmmFloat f w)) =
if_sse2 float_const_sse2 float_const_x87
where
float_const_sse2
| f == 0.0 = do
let
size = floatSize w
code dst = unitOL (XOR size (OpReg dst) (OpReg dst))
-- I don't know why there are xorpd, xorps, and pxor instructions.
-- They all appear to do the same thing --SDM
return (Any size code)
| otherwise = do
Amode addr code <- memConstant (widthInBytes w) lit
loadFloatAmode True w addr code
float_const_x87 = case w of
W64
| f == 0.0 ->
let code dst = unitOL (GLDZ dst)
in return (Any FF80 code)
| f == 1.0 ->
let code dst = unitOL (GLD1 dst)
in return (Any FF80 code)
_otherwise -> do
Amode addr code <- memConstant (widthInBytes w) lit
loadFloatAmode False w addr code
-- catch simple cases of zero- or sign-extended load
getRegister' _ _ (CmmMachOp (MO_UU_Conv W8 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVZxL II8) addr
return (Any II32 code)
getRegister' _ _ (CmmMachOp (MO_SS_Conv W8 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVSxL II8) addr
return (Any II32 code)
getRegister' _ _ (CmmMachOp (MO_UU_Conv W16 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVZxL II16) addr
return (Any II32 code)
getRegister' _ _ (CmmMachOp (MO_SS_Conv W16 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVSxL II16) addr
return (Any II32 code)
-- catch simple cases of zero- or sign-extended load
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W8 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVZxL II8) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W8 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVSxL II8) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W16 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVZxL II16) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W16 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVSxL II16) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W32 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOV II32) addr -- 32-bit loads zero-extend
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W32 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVSxL II32) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_Add W64) [CmmReg (CmmGlobal PicBaseReg),
CmmLit displacement])
| not is32Bit = do
return $ Any II64 (\dst -> unitOL $
LEA II64 (OpAddr (ripRel (litToImm displacement))) (OpReg dst))
getRegister' dflags is32Bit (CmmMachOp mop [x]) = do -- unary MachOps
sse2 <- sse2Enabled
case mop of
MO_F_Neg w
| sse2 -> sse2NegCode w x
| otherwise -> trivialUFCode FF80 (GNEG FF80) x
MO_S_Neg w -> triv_ucode NEGI (intSize w)
MO_Not w -> triv_ucode NOT (intSize w)
-- Nop conversions
MO_UU_Conv W32 W8 -> toI8Reg W32 x
MO_SS_Conv W32 W8 -> toI8Reg W32 x
MO_UU_Conv W16 W8 -> toI8Reg W16 x
MO_SS_Conv W16 W8 -> toI8Reg W16 x
MO_UU_Conv W32 W16 -> toI16Reg W32 x
MO_SS_Conv W32 W16 -> toI16Reg W32 x
MO_UU_Conv W64 W32 | not is32Bit -> conversionNop II64 x
MO_SS_Conv W64 W32 | not is32Bit -> conversionNop II64 x
MO_UU_Conv W64 W16 | not is32Bit -> toI16Reg W64 x
MO_SS_Conv W64 W16 | not is32Bit -> toI16Reg W64 x
MO_UU_Conv W64 W8 | not is32Bit -> toI8Reg W64 x
MO_SS_Conv W64 W8 | not is32Bit -> toI8Reg W64 x
MO_UU_Conv rep1 rep2 | rep1 == rep2 -> conversionNop (intSize rep1) x
MO_SS_Conv rep1 rep2 | rep1 == rep2 -> conversionNop (intSize rep1) x
-- widenings
MO_UU_Conv W8 W32 -> integerExtend W8 W32 MOVZxL x
MO_UU_Conv W16 W32 -> integerExtend W16 W32 MOVZxL x
MO_UU_Conv W8 W16 -> integerExtend W8 W16 MOVZxL x
MO_SS_Conv W8 W32 -> integerExtend W8 W32 MOVSxL x
MO_SS_Conv W16 W32 -> integerExtend W16 W32 MOVSxL x
MO_SS_Conv W8 W16 -> integerExtend W8 W16 MOVSxL x
MO_UU_Conv W8 W64 | not is32Bit -> integerExtend W8 W64 MOVZxL x
MO_UU_Conv W16 W64 | not is32Bit -> integerExtend W16 W64 MOVZxL x
MO_UU_Conv W32 W64 | not is32Bit -> integerExtend W32 W64 MOVZxL x
MO_SS_Conv W8 W64 | not is32Bit -> integerExtend W8 W64 MOVSxL x
MO_SS_Conv W16 W64 | not is32Bit -> integerExtend W16 W64 MOVSxL x
MO_SS_Conv W32 W64 | not is32Bit -> integerExtend W32 W64 MOVSxL x
-- for 32-to-64 bit zero extension, amd64 uses an ordinary movl.
-- However, we don't want the register allocator to throw it
-- away as an unnecessary reg-to-reg move, so we keep it in
-- the form of a movzl and print it as a movl later.
MO_FF_Conv W32 W64
| sse2 -> coerceFP2FP W64 x
| otherwise -> conversionNop FF80 x
MO_FF_Conv W64 W32 -> coerceFP2FP W32 x
MO_FS_Conv from to -> coerceFP2Int from to x
MO_SF_Conv from to -> coerceInt2FP from to x
MO_V_Insert {} -> needLlvm
MO_V_Extract {} -> needLlvm
MO_V_Add {} -> needLlvm
MO_V_Sub {} -> needLlvm
MO_V_Mul {} -> needLlvm
MO_VS_Quot {} -> needLlvm
MO_VS_Rem {} -> needLlvm
MO_VS_Neg {} -> needLlvm
MO_VU_Quot {} -> needLlvm
MO_VU_Rem {} -> needLlvm
MO_VF_Insert {} -> needLlvm
MO_VF_Extract {} -> needLlvm
MO_VF_Add {} -> needLlvm
MO_VF_Sub {} -> needLlvm
MO_VF_Mul {} -> needLlvm
MO_VF_Quot {} -> needLlvm
MO_VF_Neg {} -> needLlvm
_other -> pprPanic "getRegister" (pprMachOp mop)
where
triv_ucode :: (Size -> Operand -> Instr) -> Size -> NatM Register
triv_ucode instr size = trivialUCode size (instr size) x
-- signed or unsigned extension.
integerExtend :: Width -> Width
-> (Size -> Operand -> Operand -> Instr)
-> CmmExpr -> NatM Register
integerExtend from to instr expr = do
(reg,e_code) <- if from == W8 then getByteReg expr
else getSomeReg expr
let
code dst =
e_code `snocOL`
instr (intSize from) (OpReg reg) (OpReg dst)
return (Any (intSize to) code)
toI8Reg :: Width -> CmmExpr -> NatM Register
toI8Reg new_rep expr
= do codefn <- getAnyReg expr
return (Any (intSize new_rep) codefn)
-- HACK: use getAnyReg to get a byte-addressable register.
-- If the source was a Fixed register, this will add the
-- mov instruction to put it into the desired destination.
-- We're assuming that the destination won't be a fixed
-- non-byte-addressable register; it won't be, because all
-- fixed registers are word-sized.
toI16Reg = toI8Reg -- for now
conversionNop :: Size -> CmmExpr -> NatM Register
conversionNop new_size expr
= do e_code <- getRegister' dflags is32Bit expr
return (swizzleRegisterRep e_code new_size)
getRegister' _ is32Bit (CmmMachOp mop [x, y]) = do -- dyadic MachOps
sse2 <- sse2Enabled
case mop of
MO_F_Eq _ -> condFltReg is32Bit EQQ x y
MO_F_Ne _ -> condFltReg is32Bit NE x y
MO_F_Gt _ -> condFltReg is32Bit GTT x y
MO_F_Ge _ -> condFltReg is32Bit GE x y
MO_F_Lt _ -> condFltReg is32Bit LTT x y
MO_F_Le _ -> condFltReg is32Bit LE x y
MO_Eq _ -> condIntReg EQQ x y
MO_Ne _ -> condIntReg NE x y
MO_S_Gt _ -> condIntReg GTT x y
MO_S_Ge _ -> condIntReg GE x y
MO_S_Lt _ -> condIntReg LTT x y
MO_S_Le _ -> condIntReg LE x y
MO_U_Gt _ -> condIntReg GU x y
MO_U_Ge _ -> condIntReg GEU x y
MO_U_Lt _ -> condIntReg LU x y
MO_U_Le _ -> condIntReg LEU x y
MO_F_Add w | sse2 -> trivialFCode_sse2 w ADD x y
| otherwise -> trivialFCode_x87 GADD x y
MO_F_Sub w | sse2 -> trivialFCode_sse2 w SUB x y
| otherwise -> trivialFCode_x87 GSUB x y
MO_F_Quot w | sse2 -> trivialFCode_sse2 w FDIV x y
| otherwise -> trivialFCode_x87 GDIV x y
MO_F_Mul w | sse2 -> trivialFCode_sse2 w MUL x y
| otherwise -> trivialFCode_x87 GMUL x y
MO_Add rep -> add_code rep x y
MO_Sub rep -> sub_code rep x y
MO_S_Quot rep -> div_code rep True True x y
MO_S_Rem rep -> div_code rep True False x y
MO_U_Quot rep -> div_code rep False True x y
MO_U_Rem rep -> div_code rep False False x y
MO_S_MulMayOflo rep -> imulMayOflo rep x y
MO_Mul rep -> triv_op rep IMUL
MO_And rep -> triv_op rep AND
MO_Or rep -> triv_op rep OR
MO_Xor rep -> triv_op rep XOR
{- Shift ops on x86s have constraints on their source, it
either has to be Imm, CL or 1
=> trivialCode is not restrictive enough (sigh.)
-}
MO_Shl rep -> shift_code rep SHL x y {-False-}
MO_U_Shr rep -> shift_code rep SHR x y {-False-}
MO_S_Shr rep -> shift_code rep SAR x y {-False-}
MO_V_Insert {} -> needLlvm
MO_V_Extract {} -> needLlvm
MO_V_Add {} -> needLlvm
MO_V_Sub {} -> needLlvm
MO_V_Mul {} -> needLlvm
MO_VS_Quot {} -> needLlvm
MO_VS_Rem {} -> needLlvm
MO_VS_Neg {} -> needLlvm
MO_VF_Insert {} -> needLlvm
MO_VF_Extract {} -> needLlvm
MO_VF_Add {} -> needLlvm
MO_VF_Sub {} -> needLlvm
MO_VF_Mul {} -> needLlvm
MO_VF_Quot {} -> needLlvm
MO_VF_Neg {} -> needLlvm
_other -> pprPanic "getRegister(x86) - binary CmmMachOp (1)" (pprMachOp mop)
where
--------------------
triv_op width instr = trivialCode width op (Just op) x y
where op = instr (intSize width)
imulMayOflo :: Width -> CmmExpr -> CmmExpr -> NatM Register
imulMayOflo rep a b = do
(a_reg, a_code) <- getNonClobberedReg a
b_code <- getAnyReg b
let
shift_amt = case rep of
W32 -> 31
W64 -> 63
_ -> panic "shift_amt"
size = intSize rep
code = a_code `appOL` b_code eax `appOL`
toOL [
IMUL2 size (OpReg a_reg), -- result in %edx:%eax
SAR size (OpImm (ImmInt shift_amt)) (OpReg eax),
-- sign extend lower part
SUB size (OpReg edx) (OpReg eax)
-- compare against upper
-- eax==0 if high part == sign extended low part
]
return (Fixed size eax code)
--------------------
shift_code :: Width
-> (Size -> Operand -> Operand -> Instr)
-> CmmExpr
-> CmmExpr
-> NatM Register
{- Case1: shift length as immediate -}
shift_code width instr x (CmmLit lit) = do
x_code <- getAnyReg x
let
size = intSize width
code dst
= x_code dst `snocOL`
instr size (OpImm (litToImm lit)) (OpReg dst)
return (Any size code)
{- Case2: shift length is complex (non-immediate)
* y must go in %ecx.
* we cannot do y first *and* put its result in %ecx, because
%ecx might be clobbered by x.
* if we do y second, then x cannot be
in a clobbered reg. Also, we cannot clobber x's reg
with the instruction itself.
* so we can either:
- do y first, put its result in a fresh tmp, then copy it to %ecx later
- do y second and put its result into %ecx. x gets placed in a fresh
tmp. This is likely to be better, because the reg alloc can
eliminate this reg->reg move here (it won't eliminate the other one,
because the move is into the fixed %ecx).
-}
shift_code width instr x y{-amount-} = do
x_code <- getAnyReg x
let size = intSize width
tmp <- getNewRegNat size
y_code <- getAnyReg y
let
code = x_code tmp `appOL`
y_code ecx `snocOL`
instr size (OpReg ecx) (OpReg tmp)
return (Fixed size tmp code)
--------------------
add_code :: Width -> CmmExpr -> CmmExpr -> NatM Register
add_code rep x (CmmLit (CmmInt y _))
| is32BitInteger y = add_int rep x y
add_code rep x y = trivialCode rep (ADD size) (Just (ADD size)) x y
where size = intSize rep
--------------------
sub_code :: Width -> CmmExpr -> CmmExpr -> NatM Register
sub_code rep x (CmmLit (CmmInt y _))
| is32BitInteger (-y) = add_int rep x (-y)
sub_code rep x y = trivialCode rep (SUB (intSize rep)) Nothing x y
-- our three-operand add instruction:
add_int width x y = do
(x_reg, x_code) <- getSomeReg x
let
size = intSize width
imm = ImmInt (fromInteger y)
code dst
= x_code `snocOL`
LEA size
(OpAddr (AddrBaseIndex (EABaseReg x_reg) EAIndexNone imm))
(OpReg dst)
--
return (Any size code)
----------------------
div_code width signed quotient x y = do
(y_op, y_code) <- getRegOrMem y -- cannot be clobbered
x_code <- getAnyReg x
let
size = intSize width
widen | signed = CLTD size
| otherwise = XOR size (OpReg edx) (OpReg edx)
instr | signed = IDIV
| otherwise = DIV
code = y_code `appOL`
x_code eax `appOL`
toOL [widen, instr size y_op]
result | quotient = eax
| otherwise = edx
return (Fixed size result code)
getRegister' _ _ (CmmLoad mem pk)
| isFloatType pk
= do
Amode addr mem_code <- getAmode mem
use_sse2 <- sse2Enabled
loadFloatAmode use_sse2 (typeWidth pk) addr mem_code
getRegister' _ is32Bit (CmmLoad mem pk)
| is32Bit && not (isWord64 pk)
= do
code <- intLoadCode instr mem
return (Any size code)
where
width = typeWidth pk
size = intSize width
instr = case width of
W8 -> MOVZxL II8
_other -> MOV size
-- We always zero-extend 8-bit loads, if we
-- can't think of anything better. This is because
-- we can't guarantee access to an 8-bit variant of every register
-- (esi and edi don't have 8-bit variants), so to make things
-- simpler we do our 8-bit arithmetic with full 32-bit registers.
-- Simpler memory load code on x86_64
getRegister' _ is32Bit (CmmLoad mem pk)
| not is32Bit
= do
code <- intLoadCode (MOV size) mem
return (Any size code)
where size = intSize $ typeWidth pk
getRegister' _ is32Bit (CmmLit (CmmInt 0 width))
= let
size = intSize width
-- x86_64: 32-bit xor is one byte shorter, and zero-extends to 64 bits
size1 = if is32Bit then size
else case size of
II64 -> II32
_ -> size
code dst
= unitOL (XOR size1 (OpReg dst) (OpReg dst))
in
return (Any size code)
-- optimisation for loading small literals on x86_64: take advantage
-- of the automatic zero-extension from 32 to 64 bits, because the 32-bit
-- instruction forms are shorter.
getRegister' dflags is32Bit (CmmLit lit)
| not is32Bit, isWord64 (cmmLitType dflags lit), not (isBigLit lit)
= let
imm = litToImm lit
code dst = unitOL (MOV II32 (OpImm imm) (OpReg dst))
in
return (Any II64 code)
where
isBigLit (CmmInt i _) = i < 0 || i > 0xffffffff
isBigLit _ = False
-- note1: not the same as (not.is32BitLit), because that checks for
-- signed literals that fit in 32 bits, but we want unsigned
-- literals here.
-- note2: all labels are small, because we're assuming the
-- small memory model (see gcc docs, -mcmodel=small).
getRegister' dflags _ (CmmLit lit)
= do let size = cmmTypeSize (cmmLitType dflags lit)
imm = litToImm lit
code dst = unitOL (MOV size (OpImm imm) (OpReg dst))
return (Any size code)
getRegister' _ _ other
| isVecExpr other = needLlvm
| otherwise = pprPanic "getRegister(x86)" (ppr other)
intLoadCode :: (Operand -> Operand -> Instr) -> CmmExpr
-> NatM (Reg -> InstrBlock)
intLoadCode instr mem = do
Amode src mem_code <- getAmode mem
return (\dst -> mem_code `snocOL` instr (OpAddr src) (OpReg dst))
-- Compute an expression into *any* register, adding the appropriate
-- move instruction if necessary.
getAnyReg :: CmmExpr -> NatM (Reg -> InstrBlock)
getAnyReg expr = do
r <- getRegister expr
anyReg r
anyReg :: Register -> NatM (Reg -> InstrBlock)
anyReg (Any _ code) = return code
anyReg (Fixed rep reg fcode) = return (\dst -> fcode `snocOL` reg2reg rep reg dst)
-- A bit like getSomeReg, but we want a reg that can be byte-addressed.
-- Fixed registers might not be byte-addressable, so we make sure we've
-- got a temporary, inserting an extra reg copy if necessary.
getByteReg :: CmmExpr -> NatM (Reg, InstrBlock)
getByteReg expr = do
is32Bit <- is32BitPlatform
if is32Bit
then do r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed rep reg code
| isVirtualReg reg -> return (reg,code)
| otherwise -> do
tmp <- getNewRegNat rep
return (tmp, code `snocOL` reg2reg rep reg tmp)
-- ToDo: could optimise slightly by checking for
-- byte-addressable real registers, but that will
-- happen very rarely if at all.
else getSomeReg expr -- all regs are byte-addressable on x86_64
-- Another variant: this time we want the result in a register that cannot
-- be modified by code to evaluate an arbitrary expression.
getNonClobberedReg :: CmmExpr -> NatM (Reg, InstrBlock)
getNonClobberedReg expr = do
dflags <- getDynFlags
r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed rep reg code
-- only certain regs can be clobbered
| reg `elem` instrClobberedRegs (targetPlatform dflags)
-> do
tmp <- getNewRegNat rep
return (tmp, code `snocOL` reg2reg rep reg tmp)
| otherwise ->
return (reg, code)
reg2reg :: Size -> Reg -> Reg -> Instr
reg2reg size src dst
| size == FF80 = GMOV src dst
| otherwise = MOV size (OpReg src) (OpReg dst)
--------------------------------------------------------------------------------
getAmode :: CmmExpr -> NatM Amode
getAmode e = do is32Bit <- is32BitPlatform
getAmode' is32Bit e
getAmode' :: Bool -> CmmExpr -> NatM Amode
getAmode' _ (CmmRegOff r n) = do dflags <- getDynFlags
getAmode $ mangleIndexTree dflags r n
getAmode' is32Bit (CmmMachOp (MO_Add W64) [CmmReg (CmmGlobal PicBaseReg),
CmmLit displacement])
| not is32Bit
= return $ Amode (ripRel (litToImm displacement)) nilOL
-- This is all just ridiculous, since it carefully undoes
-- what mangleIndexTree has just done.
getAmode' is32Bit (CmmMachOp (MO_Sub _rep) [x, CmmLit lit@(CmmInt i _)])
| is32BitLit is32Bit lit
-- ASSERT(rep == II32)???
= do (x_reg, x_code) <- getSomeReg x
let off = ImmInt (-(fromInteger i))
return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code)
getAmode' is32Bit (CmmMachOp (MO_Add _rep) [x, CmmLit lit])
| is32BitLit is32Bit lit
-- ASSERT(rep == II32)???
= do (x_reg, x_code) <- getSomeReg x
let off = litToImm lit
return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code)
-- Turn (lit1 << n + lit2) into (lit2 + lit1 << n) so it will be
-- recognised by the next rule.
getAmode' is32Bit (CmmMachOp (MO_Add rep) [a@(CmmMachOp (MO_Shl _) _),
b@(CmmLit _)])
= getAmode' is32Bit (CmmMachOp (MO_Add rep) [b,a])
getAmode' _ (CmmMachOp (MO_Add _) [x, CmmMachOp (MO_Shl _)
[y, CmmLit (CmmInt shift _)]])
| shift == 0 || shift == 1 || shift == 2 || shift == 3
= x86_complex_amode x y shift 0
getAmode' _ (CmmMachOp (MO_Add _)
[x, CmmMachOp (MO_Add _)
[CmmMachOp (MO_Shl _) [y, CmmLit (CmmInt shift _)],
CmmLit (CmmInt offset _)]])
| shift == 0 || shift == 1 || shift == 2 || shift == 3
&& is32BitInteger offset
= x86_complex_amode x y shift offset
getAmode' _ (CmmMachOp (MO_Add _) [x,y])
= x86_complex_amode x y 0 0
getAmode' is32Bit (CmmLit lit) | is32BitLit is32Bit lit
= return (Amode (ImmAddr (litToImm lit) 0) nilOL)
getAmode' _ expr = do
(reg,code) <- getSomeReg expr
return (Amode (AddrBaseIndex (EABaseReg reg) EAIndexNone (ImmInt 0)) code)
x86_complex_amode :: CmmExpr -> CmmExpr -> Integer -> Integer -> NatM Amode
x86_complex_amode base index shift offset
= do (x_reg, x_code) <- getNonClobberedReg base
-- x must be in a temp, because it has to stay live over y_code
-- we could compre x_reg and y_reg and do something better here...
(y_reg, y_code) <- getSomeReg index
let
code = x_code `appOL` y_code
base = case shift of 0 -> 1; 1 -> 2; 2 -> 4; 3 -> 8;
n -> panic $ "x86_complex_amode: unhandled shift! (" ++ show n ++ ")"
return (Amode (AddrBaseIndex (EABaseReg x_reg) (EAIndex y_reg base) (ImmInt (fromIntegral offset)))
code)
-- -----------------------------------------------------------------------------
-- getOperand: sometimes any operand will do.
-- getNonClobberedOperand: the value of the operand will remain valid across
-- the computation of an arbitrary expression, unless the expression
-- is computed directly into a register which the operand refers to
-- (see trivialCode where this function is used for an example).
getNonClobberedOperand :: CmmExpr -> NatM (Operand, InstrBlock)
getNonClobberedOperand (CmmLit lit) = do
use_sse2 <- sse2Enabled
if use_sse2 && isSuitableFloatingPointLit lit
then do
let CmmFloat _ w = lit
Amode addr code <- memConstant (widthInBytes w) lit
return (OpAddr addr, code)
else do
is32Bit <- is32BitPlatform
dflags <- getDynFlags
if is32BitLit is32Bit lit && not (isFloatType (cmmLitType dflags lit))
then return (OpImm (litToImm lit), nilOL)
else getNonClobberedOperand_generic (CmmLit lit)
getNonClobberedOperand (CmmLoad mem pk) = do
is32Bit <- is32BitPlatform
use_sse2 <- sse2Enabled
if (not (isFloatType pk) || use_sse2)
&& (if is32Bit then not (isWord64 pk) else True)
then do
dflags <- getDynFlags
let platform = targetPlatform dflags
Amode src mem_code <- getAmode mem
(src',save_code) <-
if (amodeCouldBeClobbered platform src)
then do
tmp <- getNewRegNat (archWordSize is32Bit)
return (AddrBaseIndex (EABaseReg tmp) EAIndexNone (ImmInt 0),
unitOL (LEA (archWordSize is32Bit) (OpAddr src) (OpReg tmp)))
else
return (src, nilOL)
return (OpAddr src', mem_code `appOL` save_code)
else do
getNonClobberedOperand_generic (CmmLoad mem pk)
getNonClobberedOperand e = getNonClobberedOperand_generic e
getNonClobberedOperand_generic :: CmmExpr -> NatM (Operand, InstrBlock)
getNonClobberedOperand_generic e = do
(reg, code) <- getNonClobberedReg e
return (OpReg reg, code)
amodeCouldBeClobbered :: Platform -> AddrMode -> Bool
amodeCouldBeClobbered platform amode = any (regClobbered platform) (addrModeRegs amode)
regClobbered :: Platform -> Reg -> Bool
regClobbered platform (RegReal (RealRegSingle rr)) = isFastTrue (freeReg platform rr)
regClobbered _ _ = False
-- getOperand: the operand is not required to remain valid across the
-- computation of an arbitrary expression.
getOperand :: CmmExpr -> NatM (Operand, InstrBlock)
getOperand (CmmLit lit) = do
use_sse2 <- sse2Enabled
if (use_sse2 && isSuitableFloatingPointLit lit)
then do
let CmmFloat _ w = lit
Amode addr code <- memConstant (widthInBytes w) lit
return (OpAddr addr, code)
else do
is32Bit <- is32BitPlatform
dflags <- getDynFlags
if is32BitLit is32Bit lit && not (isFloatType (cmmLitType dflags lit))
then return (OpImm (litToImm lit), nilOL)
else getOperand_generic (CmmLit lit)
getOperand (CmmLoad mem pk) = do
is32Bit <- is32BitPlatform
use_sse2 <- sse2Enabled
if (not (isFloatType pk) || use_sse2) && (if is32Bit then not (isWord64 pk) else True)
then do
Amode src mem_code <- getAmode mem
return (OpAddr src, mem_code)
else
getOperand_generic (CmmLoad mem pk)
getOperand e = getOperand_generic e
getOperand_generic :: CmmExpr -> NatM (Operand, InstrBlock)
getOperand_generic e = do
(reg, code) <- getSomeReg e
return (OpReg reg, code)
isOperand :: Bool -> CmmExpr -> Bool
isOperand _ (CmmLoad _ _) = True
isOperand is32Bit (CmmLit lit) = is32BitLit is32Bit lit
|| isSuitableFloatingPointLit lit
isOperand _ _ = False
memConstant :: Int -> CmmLit -> NatM Amode
memConstant align lit = do
lbl <- getNewLabelNat
dflags <- getDynFlags
(addr, addr_code) <- if target32Bit (targetPlatform dflags)
then do dynRef <- cmmMakeDynamicReference
dflags
DataReference
lbl
Amode addr addr_code <- getAmode dynRef
return (addr, addr_code)
else return (ripRel (ImmCLbl lbl), nilOL)
let code =
LDATA ReadOnlyData (align, Statics lbl [CmmStaticLit lit])
`consOL` addr_code
return (Amode addr code)
loadFloatAmode :: Bool -> Width -> AddrMode -> InstrBlock -> NatM Register
loadFloatAmode use_sse2 w addr addr_code = do
let size = floatSize w
code dst = addr_code `snocOL`
if use_sse2
then MOV size (OpAddr addr) (OpReg dst)
else GLD size addr dst
return (Any (if use_sse2 then size else FF80) code)
-- if we want a floating-point literal as an operand, we can
-- use it directly from memory. However, if the literal is
-- zero, we're better off generating it into a register using
-- xor.
isSuitableFloatingPointLit :: CmmLit -> Bool
isSuitableFloatingPointLit (CmmFloat f _) = f /= 0.0
isSuitableFloatingPointLit _ = False
getRegOrMem :: CmmExpr -> NatM (Operand, InstrBlock)
getRegOrMem e@(CmmLoad mem pk) = do
is32Bit <- is32BitPlatform
use_sse2 <- sse2Enabled
if (not (isFloatType pk) || use_sse2) && (if is32Bit then not (isWord64 pk) else True)
then do
Amode src mem_code <- getAmode mem
return (OpAddr src, mem_code)
else do
(reg, code) <- getNonClobberedReg e
return (OpReg reg, code)
getRegOrMem e = do
(reg, code) <- getNonClobberedReg e
return (OpReg reg, code)
is32BitLit :: Bool -> CmmLit -> Bool
is32BitLit is32Bit (CmmInt i W64)
| not is32Bit
= -- assume that labels are in the range 0-2^31-1: this assumes the
-- small memory model (see gcc docs, -mcmodel=small).
is32BitInteger i
is32BitLit _ _ = True
-- Set up a condition code for a conditional branch.
getCondCode :: CmmExpr -> NatM CondCode
-- yes, they really do seem to want exactly the same!
getCondCode (CmmMachOp mop [x, y])
=
case mop of
MO_F_Eq W32 -> condFltCode EQQ x y
MO_F_Ne W32 -> condFltCode NE x y
MO_F_Gt W32 -> condFltCode GTT x y
MO_F_Ge W32 -> condFltCode GE x y
MO_F_Lt W32 -> condFltCode LTT x y
MO_F_Le W32 -> condFltCode LE x y
MO_F_Eq W64 -> condFltCode EQQ x y
MO_F_Ne W64 -> condFltCode NE x y
MO_F_Gt W64 -> condFltCode GTT x y
MO_F_Ge W64 -> condFltCode GE x y
MO_F_Lt W64 -> condFltCode LTT x y
MO_F_Le W64 -> condFltCode LE x y
MO_Eq _ -> condIntCode EQQ x y
MO_Ne _ -> condIntCode NE x y
MO_S_Gt _ -> condIntCode GTT x y
MO_S_Ge _ -> condIntCode GE x y
MO_S_Lt _ -> condIntCode LTT x y
MO_S_Le _ -> condIntCode LE x y
MO_U_Gt _ -> condIntCode GU x y
MO_U_Ge _ -> condIntCode GEU x y
MO_U_Lt _ -> condIntCode LU x y
MO_U_Le _ -> condIntCode LEU x y
_other -> pprPanic "getCondCode(x86,x86_64)" (ppr (CmmMachOp mop [x,y]))
getCondCode other = pprPanic "getCondCode(2)(x86,x86_64)" (ppr other)
-- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be
-- passed back up the tree.
condIntCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
condIntCode cond x y = do is32Bit <- is32BitPlatform
condIntCode' is32Bit cond x y
condIntCode' :: Bool -> Cond -> CmmExpr -> CmmExpr -> NatM CondCode
-- memory vs immediate
condIntCode' is32Bit cond (CmmLoad x pk) (CmmLit lit)
| is32BitLit is32Bit lit = do
Amode x_addr x_code <- getAmode x
let
imm = litToImm lit
code = x_code `snocOL`
CMP (cmmTypeSize pk) (OpImm imm) (OpAddr x_addr)
--
return (CondCode False cond code)
-- anything vs zero, using a mask
-- TODO: Add some sanity checking!!!!
condIntCode' is32Bit cond (CmmMachOp (MO_And _) [x,o2]) (CmmLit (CmmInt 0 pk))
| (CmmLit lit@(CmmInt mask _)) <- o2, is32BitLit is32Bit lit
= do
(x_reg, x_code) <- getSomeReg x
let
code = x_code `snocOL`
TEST (intSize pk) (OpImm (ImmInteger mask)) (OpReg x_reg)
--
return (CondCode False cond code)
-- anything vs zero
condIntCode' _ cond x (CmmLit (CmmInt 0 pk)) = do
(x_reg, x_code) <- getSomeReg x
let
code = x_code `snocOL`
TEST (intSize pk) (OpReg x_reg) (OpReg x_reg)
--
return (CondCode False cond code)
-- anything vs operand
condIntCode' is32Bit cond x y
| isOperand is32Bit y = do
dflags <- getDynFlags
(x_reg, x_code) <- getNonClobberedReg x
(y_op, y_code) <- getOperand y
let
code = x_code `appOL` y_code `snocOL`
CMP (cmmTypeSize (cmmExprType dflags x)) y_op (OpReg x_reg)
return (CondCode False cond code)
-- operand vs. anything: invert the comparison so that we can use a
-- single comparison instruction.
| isOperand is32Bit x
, Just revcond <- maybeFlipCond cond = do
dflags <- getDynFlags
(y_reg, y_code) <- getNonClobberedReg y
(x_op, x_code) <- getOperand x
let
code = y_code `appOL` x_code `snocOL`
CMP (cmmTypeSize (cmmExprType dflags x)) x_op (OpReg y_reg)
return (CondCode False revcond code)
-- anything vs anything
condIntCode' _ cond x y = do
dflags <- getDynFlags
(y_reg, y_code) <- getNonClobberedReg y
(x_op, x_code) <- getRegOrMem x
let
code = y_code `appOL`
x_code `snocOL`
CMP (cmmTypeSize (cmmExprType dflags x)) (OpReg y_reg) x_op
return (CondCode False cond code)
--------------------------------------------------------------------------------
condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
condFltCode cond x y
= if_sse2 condFltCode_sse2 condFltCode_x87
where
condFltCode_x87
= ASSERT(cond `elem` ([EQQ, NE, LE, LTT, GE, GTT])) do
(x_reg, x_code) <- getNonClobberedReg x
(y_reg, y_code) <- getSomeReg y
let
code = x_code `appOL` y_code `snocOL`
GCMP cond x_reg y_reg
-- The GCMP insn does the test and sets the zero flag if comparable
-- and true. Hence we always supply EQQ as the condition to test.
return (CondCode True EQQ code)
-- in the SSE2 comparison ops (ucomiss, ucomisd) the left arg may be
-- an operand, but the right must be a reg. We can probably do better
-- than this general case...
condFltCode_sse2 = do
dflags <- getDynFlags
(x_reg, x_code) <- getNonClobberedReg x
(y_op, y_code) <- getOperand y
let
code = x_code `appOL`
y_code `snocOL`
CMP (floatSize $ cmmExprWidth dflags x) y_op (OpReg x_reg)
-- NB(1): we need to use the unsigned comparison operators on the
-- result of this comparison.
return (CondCode True (condToUnsigned cond) code)
-- -----------------------------------------------------------------------------
-- Generating assignments
-- Assignments are really at the heart of the whole code generation
-- business. Almost all top-level nodes of any real importance are
-- assignments, which correspond to loads, stores, or register
-- transfers. If we're really lucky, some of the register transfers
-- will go away, because we can use the destination register to
-- complete the code generation for the right hand side. This only
-- fails when the right hand side is forced into a fixed register
-- (e.g. the result of a call).
assignMem_IntCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_IntCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock
assignMem_FltCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_FltCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock
-- integer assignment to memory
-- specific case of adding/subtracting an integer to a particular address.
-- ToDo: catch other cases where we can use an operation directly on a memory
-- address.
assignMem_IntCode pk addr (CmmMachOp op [CmmLoad addr2 _,
CmmLit (CmmInt i _)])
| addr == addr2, pk /= II64 || is32BitInteger i,
Just instr <- check op
= do Amode amode code_addr <- getAmode addr
let code = code_addr `snocOL`
instr pk (OpImm (ImmInt (fromIntegral i))) (OpAddr amode)
return code
where
check (MO_Add _) = Just ADD
check (MO_Sub _) = Just SUB
check _ = Nothing
-- ToDo: more?
-- general case
assignMem_IntCode pk addr src = do
is32Bit <- is32BitPlatform
Amode addr code_addr <- getAmode addr
(code_src, op_src) <- get_op_RI is32Bit src
let
code = code_src `appOL`
code_addr `snocOL`
MOV pk op_src (OpAddr addr)
-- NOTE: op_src is stable, so it will still be valid
-- after code_addr. This may involve the introduction
-- of an extra MOV to a temporary register, but we hope
-- the register allocator will get rid of it.
--
return code
where
get_op_RI :: Bool -> CmmExpr -> NatM (InstrBlock,Operand) -- code, operator
get_op_RI is32Bit (CmmLit lit) | is32BitLit is32Bit lit
= return (nilOL, OpImm (litToImm lit))
get_op_RI _ op
= do (reg,code) <- getNonClobberedReg op
return (code, OpReg reg)
-- Assign; dst is a reg, rhs is mem
assignReg_IntCode pk reg (CmmLoad src _) = do
load_code <- intLoadCode (MOV pk) src
dflags <- getDynFlags
let platform = targetPlatform dflags
return (load_code (getRegisterReg platform False{-no sse2-} reg))
-- dst is a reg, but src could be anything
assignReg_IntCode _ reg src = do
dflags <- getDynFlags
let platform = targetPlatform dflags
code <- getAnyReg src
return (code (getRegisterReg platform False{-no sse2-} reg))
-- Floating point assignment to memory
assignMem_FltCode pk addr src = do
(src_reg, src_code) <- getNonClobberedReg src
Amode addr addr_code <- getAmode addr
use_sse2 <- sse2Enabled
let
code = src_code `appOL`
addr_code `snocOL`
if use_sse2 then MOV pk (OpReg src_reg) (OpAddr addr)
else GST pk src_reg addr
return code
-- Floating point assignment to a register/temporary
assignReg_FltCode _ reg src = do
use_sse2 <- sse2Enabled
src_code <- getAnyReg src
dflags <- getDynFlags
let platform = targetPlatform dflags
return (src_code (getRegisterReg platform use_sse2 reg))
genJump :: CmmExpr{-the branch target-} -> [Reg] -> NatM InstrBlock
genJump (CmmLoad mem _) regs = do
Amode target code <- getAmode mem
return (code `snocOL` JMP (OpAddr target) regs)
genJump (CmmLit lit) regs = do
return (unitOL (JMP (OpImm (litToImm lit)) regs))
genJump expr regs = do
(reg,code) <- getSomeReg expr
return (code `snocOL` JMP (OpReg reg) regs)
-- -----------------------------------------------------------------------------
-- Unconditional branches
genBranch :: BlockId -> NatM InstrBlock
genBranch = return . toOL . mkJumpInstr
-- -----------------------------------------------------------------------------
-- Conditional jumps
{-
Conditional jumps are always to local labels, so we can use branch
instructions. We peek at the arguments to decide what kind of
comparison to do.
I386: First, we have to ensure that the condition
codes are set according to the supplied comparison operation.
-}
genCondJump
:: BlockId -- the branch target
-> CmmExpr -- the condition on which to branch
-> NatM InstrBlock
genCondJump id bool = do
CondCode is_float cond cond_code <- getCondCode bool
use_sse2 <- sse2Enabled
if not is_float || not use_sse2
then
return (cond_code `snocOL` JXX cond id)
else do
lbl <- getBlockIdNat
-- see comment with condFltReg
let code = case cond of
NE -> or_unordered
GU -> plain_test
GEU -> plain_test
_ -> and_ordered
plain_test = unitOL (
JXX cond id
)
or_unordered = toOL [
JXX cond id,
JXX PARITY id
]
and_ordered = toOL [
JXX PARITY lbl,
JXX cond id,
JXX ALWAYS lbl,
NEWBLOCK lbl
]
return (cond_code `appOL` code)
-- -----------------------------------------------------------------------------
-- Generating C calls
-- Now the biggest nightmare---calls. Most of the nastiness is buried in
-- @get_arg@, which moves the arguments to the correct registers/stack
-- locations. Apart from that, the code is easy.
--
-- (If applicable) Do not fill the delay slots here; you will confuse the
-- register allocator.
genCCall
:: Bool -- 32 bit platform?
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-- Unroll memcpy calls if the source and destination pointers are at
-- least DWORD aligned and the number of bytes to copy isn't too
-- large. Otherwise, call C's memcpy.
genCCall is32Bit (PrimTarget MO_Memcpy) _
[dst, src,
(CmmLit (CmmInt n _)),
(CmmLit (CmmInt align _))]
| n <= maxInlineSizeThreshold && align .&. 3 == 0 = do
code_dst <- getAnyReg dst
dst_r <- getNewRegNat size
code_src <- getAnyReg src
src_r <- getNewRegNat size
tmp_r <- getNewRegNat size
return $ code_dst dst_r `appOL` code_src src_r `appOL`
go dst_r src_r tmp_r n
where
size = if align .&. 4 /= 0 then II32 else (archWordSize is32Bit)
sizeBytes = fromIntegral (sizeInBytes size)
go :: Reg -> Reg -> Reg -> Integer -> OrdList Instr
go dst src tmp i
| i >= sizeBytes =
unitOL (MOV size (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV size (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - sizeBytes)
-- Deal with remaining bytes.
| i >= 4 = -- Will never happen on 32-bit
unitOL (MOV II32 (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV II32 (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - 4)
| i >= 2 =
unitOL (MOVZxL II16 (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV II16 (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - 2)
| i >= 1 =
unitOL (MOVZxL II8 (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV II8 (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - 1)
| otherwise = nilOL
where
src_addr = AddrBaseIndex (EABaseReg src) EAIndexNone
(ImmInteger (n - i))
dst_addr = AddrBaseIndex (EABaseReg dst) EAIndexNone
(ImmInteger (n - i))
genCCall _ (PrimTarget MO_Memset) _
[dst,
CmmLit (CmmInt c _),
CmmLit (CmmInt n _),
CmmLit (CmmInt align _)]
| n <= maxInlineSizeThreshold && align .&. 3 == 0 = do
code_dst <- getAnyReg dst
dst_r <- getNewRegNat size
return $ code_dst dst_r `appOL` go dst_r n
where
(size, val) = case align .&. 3 of
2 -> (II16, c2)
0 -> (II32, c4)
_ -> (II8, c)
c2 = c `shiftL` 8 .|. c
c4 = c2 `shiftL` 16 .|. c2
sizeBytes = fromIntegral (sizeInBytes size)
go :: Reg -> Integer -> OrdList Instr
go dst i
-- TODO: Add movabs instruction and support 64-bit sets.
| i >= sizeBytes = -- This might be smaller than the below sizes
unitOL (MOV size (OpImm (ImmInteger val)) (OpAddr dst_addr)) `appOL`
go dst (i - sizeBytes)
| i >= 4 = -- Will never happen on 32-bit
unitOL (MOV II32 (OpImm (ImmInteger c4)) (OpAddr dst_addr)) `appOL`
go dst (i - 4)
| i >= 2 =
unitOL (MOV II16 (OpImm (ImmInteger c2)) (OpAddr dst_addr)) `appOL`
go dst (i - 2)
| i >= 1 =
unitOL (MOV II8 (OpImm (ImmInteger c)) (OpAddr dst_addr)) `appOL`
go dst (i - 1)
| otherwise = nilOL
where
dst_addr = AddrBaseIndex (EABaseReg dst) EAIndexNone
(ImmInteger (n - i))
genCCall _ (PrimTarget MO_WriteBarrier) _ _ = return nilOL
-- write barrier compiles to no code on x86/x86-64;
-- we keep it this long in order to prevent earlier optimisations.
genCCall _ (PrimTarget MO_Touch) _ _ = return nilOL
genCCall is32bit (PrimTarget (MO_Prefetch_Data n )) _ [src] =
case n of
0 -> genPrefetch src $ PREFETCH NTA size
1 -> genPrefetch src $ PREFETCH Lvl2 size
2 -> genPrefetch src $ PREFETCH Lvl1 size
3 -> genPrefetch src $ PREFETCH Lvl0 size
l -> panic $ "unexpected prefetch level in genCCall MO_Prefetch_Data: " ++ (show l)
-- the c / llvm prefetch convention is 0, 1, 2, and 3
-- the x86 corresponding names are : NTA, 2 , 1, and 0
where
size = archWordSize is32bit
-- need to know what register width for pointers!
genPrefetch inRegSrc prefetchCTor =
do
code_src <- getAnyReg inRegSrc
src_r <- getNewRegNat size
return $ code_src src_r `appOL`
(unitOL (prefetchCTor (OpAddr
((AddrBaseIndex (EABaseReg src_r ) EAIndexNone (ImmInt 0)))) ))
-- prefetch always takes an address
genCCall is32Bit (PrimTarget (MO_BSwap width)) [dst] [src] = do
dflags <- getDynFlags
let platform = targetPlatform dflags
let dst_r = getRegisterReg platform False (CmmLocal dst)
case width of
W64 | is32Bit -> do
ChildCode64 vcode rlo <- iselExpr64 src
let dst_rhi = getHiVRegFromLo dst_r
rhi = getHiVRegFromLo rlo
return $ vcode `appOL`
toOL [ MOV II32 (OpReg rlo) (OpReg dst_rhi),
MOV II32 (OpReg rhi) (OpReg dst_r),
BSWAP II32 dst_rhi,
BSWAP II32 dst_r ]
W16 -> do code_src <- getAnyReg src
return $ code_src dst_r `appOL`
unitOL (BSWAP II32 dst_r) `appOL`
unitOL (SHR II32 (OpImm $ ImmInt 16) (OpReg dst_r))
_ -> do code_src <- getAnyReg src
return $ code_src dst_r `appOL` unitOL (BSWAP size dst_r)
where
size = intSize width
genCCall is32Bit (PrimTarget (MO_PopCnt width)) dest_regs@[dst]
args@[src] = do
sse4_2 <- sse4_2Enabled
dflags <- getDynFlags
let platform = targetPlatform dflags
if sse4_2
then do code_src <- getAnyReg src
src_r <- getNewRegNat size
return $ code_src src_r `appOL`
(if width == W8 then
-- The POPCNT instruction doesn't take a r/m8
unitOL (MOVZxL II8 (OpReg src_r) (OpReg src_r)) `appOL`
unitOL (POPCNT II16 (OpReg src_r)
(getRegisterReg platform False (CmmLocal dst)))
else
unitOL (POPCNT size (OpReg src_r)
(getRegisterReg platform False (CmmLocal dst))))
else do
targetExpr <- cmmMakeDynamicReference dflags
CallReference lbl
let target = ForeignTarget targetExpr (ForeignConvention CCallConv
[NoHint] [NoHint]
CmmMayReturn)
genCCall is32Bit target dest_regs args
where
size = intSize width
lbl = mkCmmCodeLabel primPackageId (fsLit (popCntLabel width))
genCCall is32Bit (PrimTarget (MO_UF_Conv width)) dest_regs args = do
dflags <- getDynFlags
targetExpr <- cmmMakeDynamicReference dflags
CallReference lbl
let target = ForeignTarget targetExpr (ForeignConvention CCallConv
[NoHint] [NoHint]
CmmMayReturn)
genCCall is32Bit target dest_regs args
where
lbl = mkCmmCodeLabel primPackageId (fsLit (word2FloatLabel width))
genCCall is32Bit target dest_regs args
| is32Bit = genCCall32 target dest_regs args
| otherwise = genCCall64 target dest_regs args
genCCall32 :: ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall32 target dest_regs args = do
dflags <- getDynFlags
let platform = targetPlatform dflags
case (target, dest_regs) of
-- void return type prim op
(PrimTarget op, []) ->
outOfLineCmmOp op Nothing args
-- we only cope with a single result for foreign calls
(PrimTarget op, [r]) -> do
l1 <- getNewLabelNat
l2 <- getNewLabelNat
sse2 <- sse2Enabled
if sse2
then
outOfLineCmmOp op (Just r) args
else case op of
MO_F32_Sqrt -> actuallyInlineFloatOp GSQRT FF32 args
MO_F64_Sqrt -> actuallyInlineFloatOp GSQRT FF64 args
MO_F32_Sin -> actuallyInlineFloatOp (\s -> GSIN s l1 l2) FF32 args
MO_F64_Sin -> actuallyInlineFloatOp (\s -> GSIN s l1 l2) FF64 args
MO_F32_Cos -> actuallyInlineFloatOp (\s -> GCOS s l1 l2) FF32 args
MO_F64_Cos -> actuallyInlineFloatOp (\s -> GCOS s l1 l2) FF64 args
MO_F32_Tan -> actuallyInlineFloatOp (\s -> GTAN s l1 l2) FF32 args
MO_F64_Tan -> actuallyInlineFloatOp (\s -> GTAN s l1 l2) FF64 args
_other_op -> outOfLineCmmOp op (Just r) args
where
actuallyInlineFloatOp instr size [x]
= do res <- trivialUFCode size (instr size) x
any <- anyReg res
return (any (getRegisterReg platform False (CmmLocal r)))
actuallyInlineFloatOp _ _ args
= panic $ "genCCall32.actuallyInlineFloatOp: bad number of arguments! ("
++ show (length args) ++ ")"
(PrimTarget (MO_S_QuotRem width), _) -> divOp1 platform True width dest_regs args
(PrimTarget (MO_U_QuotRem width), _) -> divOp1 platform False width dest_regs args
(PrimTarget (MO_U_QuotRem2 width), _) -> divOp2 platform False width dest_regs args
(PrimTarget (MO_Add2 width), [res_h, res_l]) ->
case args of
[arg_x, arg_y] ->
do hCode <- getAnyReg (CmmLit (CmmInt 0 width))
lCode <- getAnyReg (CmmMachOp (MO_Add width) [arg_x, arg_y])
let size = intSize width
reg_l = getRegisterReg platform True (CmmLocal res_l)
reg_h = getRegisterReg platform True (CmmLocal res_h)
code = hCode reg_h `appOL`
lCode reg_l `snocOL`
ADC size (OpImm (ImmInteger 0)) (OpReg reg_h)
return code
_ -> panic "genCCall32: Wrong number of arguments/results for add2"
(PrimTarget (MO_U_Mul2 width), [res_h, res_l]) ->
case args of
[arg_x, arg_y] ->
do (y_reg, y_code) <- getRegOrMem arg_y
x_code <- getAnyReg arg_x
let size = intSize width
reg_h = getRegisterReg platform True (CmmLocal res_h)
reg_l = getRegisterReg platform True (CmmLocal res_l)
code = y_code `appOL`
x_code rax `appOL`
toOL [MUL2 size y_reg,
MOV size (OpReg rdx) (OpReg reg_h),
MOV size (OpReg rax) (OpReg reg_l)]
return code
_ -> panic "genCCall32: Wrong number of arguments/results for add2"
_ -> genCCall32' dflags target dest_regs args
where divOp1 platform signed width results [arg_x, arg_y]
= divOp platform signed width results Nothing arg_x arg_y
divOp1 _ _ _ _ _
= panic "genCCall32: Wrong number of arguments for divOp1"
divOp2 platform signed width results [arg_x_high, arg_x_low, arg_y]
= divOp platform signed width results (Just arg_x_high) arg_x_low arg_y
divOp2 _ _ _ _ _
= panic "genCCall64: Wrong number of arguments for divOp2"
divOp platform signed width [res_q, res_r]
m_arg_x_high arg_x_low arg_y
= do let size = intSize width
reg_q = getRegisterReg platform True (CmmLocal res_q)
reg_r = getRegisterReg platform True (CmmLocal res_r)
widen | signed = CLTD size
| otherwise = XOR size (OpReg rdx) (OpReg rdx)
instr | signed = IDIV
| otherwise = DIV
(y_reg, y_code) <- getRegOrMem arg_y
x_low_code <- getAnyReg arg_x_low
x_high_code <- case m_arg_x_high of
Just arg_x_high ->
getAnyReg arg_x_high
Nothing ->
return $ const $ unitOL widen
return $ y_code `appOL`
x_low_code rax `appOL`
x_high_code rdx `appOL`
toOL [instr size y_reg,
MOV size (OpReg rax) (OpReg reg_q),
MOV size (OpReg rdx) (OpReg reg_r)]
divOp _ _ _ _ _ _ _
= panic "genCCall32: Wrong number of results for divOp"
genCCall32' :: DynFlags
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall32' dflags target dest_regs args = do
let
prom_args = map (maybePromoteCArg dflags W32) args
-- Align stack to 16n for calls, assuming a starting stack
-- alignment of 16n - word_size on procedure entry. Which we
-- maintiain. See Note [rts/StgCRun.c : Stack Alignment on X86]
sizes = map (arg_size . cmmExprType dflags) (reverse args)
raw_arg_size = sum sizes + wORD_SIZE dflags
arg_pad_size = (roundTo 16 $ raw_arg_size) - raw_arg_size
tot_arg_size = raw_arg_size + arg_pad_size - wORD_SIZE dflags
delta0 <- getDeltaNat
setDeltaNat (delta0 - arg_pad_size)
use_sse2 <- sse2Enabled
push_codes <- mapM (push_arg use_sse2) (reverse prom_args)
delta <- getDeltaNat
MASSERT(delta == delta0 - tot_arg_size)
-- deal with static vs dynamic call targets
(callinsns,cconv) <-
case target of
ForeignTarget (CmmLit (CmmLabel lbl)) conv
-> -- ToDo: stdcall arg sizes
return (unitOL (CALL (Left fn_imm) []), conv)
where fn_imm = ImmCLbl lbl
ForeignTarget expr conv
-> do { (dyn_r, dyn_c) <- getSomeReg expr
; ASSERT( isWord32 (cmmExprType dflags expr) )
return (dyn_c `snocOL` CALL (Right dyn_r) [], conv) }
PrimTarget _
-> panic $ "genCCall: Can't handle PrimTarget call type here, error "
++ "probably because too many return values."
let push_code
| arg_pad_size /= 0
= toOL [SUB II32 (OpImm (ImmInt arg_pad_size)) (OpReg esp),
DELTA (delta0 - arg_pad_size)]
`appOL` concatOL push_codes
| otherwise
= concatOL push_codes
-- Deallocate parameters after call for ccall;
-- but not for stdcall (callee does it)
--
-- We have to pop any stack padding we added
-- even if we are doing stdcall, though (#5052)
pop_size
| ForeignConvention StdCallConv _ _ _ <- cconv = arg_pad_size
| otherwise = tot_arg_size
call = callinsns `appOL`
toOL (
(if pop_size==0 then [] else
[ADD II32 (OpImm (ImmInt pop_size)) (OpReg esp)])
++
[DELTA delta0]
)
setDeltaNat delta0
dflags <- getDynFlags
let platform = targetPlatform dflags
let
-- assign the results, if necessary
assign_code [] = nilOL
assign_code [dest]
| isFloatType ty =
if use_sse2
then let tmp_amode = AddrBaseIndex (EABaseReg esp)
EAIndexNone
(ImmInt 0)
sz = floatSize w
in toOL [ SUB II32 (OpImm (ImmInt b)) (OpReg esp),
DELTA (delta0 - b),
GST sz fake0 tmp_amode,
MOV sz (OpAddr tmp_amode) (OpReg r_dest),
ADD II32 (OpImm (ImmInt b)) (OpReg esp),
DELTA delta0]
else unitOL (GMOV fake0 r_dest)
| isWord64 ty = toOL [MOV II32 (OpReg eax) (OpReg r_dest),
MOV II32 (OpReg edx) (OpReg r_dest_hi)]
| otherwise = unitOL (MOV (intSize w) (OpReg eax) (OpReg r_dest))
where
ty = localRegType dest
w = typeWidth ty
b = widthInBytes w
r_dest_hi = getHiVRegFromLo r_dest
r_dest = getRegisterReg platform use_sse2 (CmmLocal dest)
assign_code many = pprPanic "genCCall.assign_code - too many return values:" (ppr many)
return (push_code `appOL`
call `appOL`
assign_code dest_regs)
where
arg_size :: CmmType -> Int -- Width in bytes
arg_size ty = widthInBytes (typeWidth ty)
roundTo a x | x `mod` a == 0 = x
| otherwise = x + a - (x `mod` a)
push_arg :: Bool -> CmmActual {-current argument-}
-> NatM InstrBlock -- code
push_arg use_sse2 arg -- we don't need the hints on x86
| isWord64 arg_ty = do
ChildCode64 code r_lo <- iselExpr64 arg
delta <- getDeltaNat
setDeltaNat (delta - 8)
let
r_hi = getHiVRegFromLo r_lo
return ( code `appOL`
toOL [PUSH II32 (OpReg r_hi), DELTA (delta - 4),
PUSH II32 (OpReg r_lo), DELTA (delta - 8),
DELTA (delta-8)]
)
| isFloatType arg_ty = do
(reg, code) <- getSomeReg arg
delta <- getDeltaNat
setDeltaNat (delta-size)
return (code `appOL`
toOL [SUB II32 (OpImm (ImmInt size)) (OpReg esp),
DELTA (delta-size),
let addr = AddrBaseIndex (EABaseReg esp)
EAIndexNone
(ImmInt 0)
size = floatSize (typeWidth arg_ty)
in
if use_sse2
then MOV size (OpReg reg) (OpAddr addr)
else GST size reg addr
]
)
| otherwise = do
(operand, code) <- getOperand arg
delta <- getDeltaNat
setDeltaNat (delta-size)
return (code `snocOL`
PUSH II32 operand `snocOL`
DELTA (delta-size))
where
arg_ty = cmmExprType dflags arg
size = arg_size arg_ty -- Byte size
genCCall64 :: ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall64 target dest_regs args = do
dflags <- getDynFlags
let platform = targetPlatform dflags
case (target, dest_regs) of
(PrimTarget op, []) ->
-- void return type prim op
outOfLineCmmOp op Nothing args
(PrimTarget op, [res]) ->
-- we only cope with a single result for foreign calls
outOfLineCmmOp op (Just res) args
(PrimTarget (MO_S_QuotRem width), _) -> divOp1 platform True width dest_regs args
(PrimTarget (MO_U_QuotRem width), _) -> divOp1 platform False width dest_regs args
(PrimTarget (MO_U_QuotRem2 width), _) -> divOp2 platform False width dest_regs args
(PrimTarget (MO_Add2 width), [res_h, res_l]) ->
case args of
[arg_x, arg_y] ->
do hCode <- getAnyReg (CmmLit (CmmInt 0 width))
lCode <- getAnyReg (CmmMachOp (MO_Add width) [arg_x, arg_y])
let size = intSize width
reg_l = getRegisterReg platform True (CmmLocal res_l)
reg_h = getRegisterReg platform True (CmmLocal res_h)
code = hCode reg_h `appOL`
lCode reg_l `snocOL`
ADC size (OpImm (ImmInteger 0)) (OpReg reg_h)
return code
_ -> panic "genCCall64: Wrong number of arguments/results for add2"
(PrimTarget (MO_U_Mul2 width), [res_h, res_l]) ->
case args of
[arg_x, arg_y] ->
do (y_reg, y_code) <- getRegOrMem arg_y
x_code <- getAnyReg arg_x
let size = intSize width
reg_h = getRegisterReg platform True (CmmLocal res_h)
reg_l = getRegisterReg platform True (CmmLocal res_l)
code = y_code `appOL`
x_code rax `appOL`
toOL [MUL2 size y_reg,
MOV size (OpReg rdx) (OpReg reg_h),
MOV size (OpReg rax) (OpReg reg_l)]
return code
_ -> panic "genCCall64: Wrong number of arguments/results for add2"
_ ->
do dflags <- getDynFlags
genCCall64' dflags target dest_regs args
where divOp1 platform signed width results [arg_x, arg_y]
= divOp platform signed width results Nothing arg_x arg_y
divOp1 _ _ _ _ _
= panic "genCCall64: Wrong number of arguments for divOp1"
divOp2 platform signed width results [arg_x_high, arg_x_low, arg_y]
= divOp platform signed width results (Just arg_x_high) arg_x_low arg_y
divOp2 _ _ _ _ _
= panic "genCCall64: Wrong number of arguments for divOp2"
divOp platform signed width [res_q, res_r]
m_arg_x_high arg_x_low arg_y
= do let size = intSize width
reg_q = getRegisterReg platform True (CmmLocal res_q)
reg_r = getRegisterReg platform True (CmmLocal res_r)
widen | signed = CLTD size
| otherwise = XOR size (OpReg rdx) (OpReg rdx)
instr | signed = IDIV
| otherwise = DIV
(y_reg, y_code) <- getRegOrMem arg_y
x_low_code <- getAnyReg arg_x_low
x_high_code <- case m_arg_x_high of
Just arg_x_high -> getAnyReg arg_x_high
Nothing -> return $ const $ unitOL widen
return $ y_code `appOL`
x_low_code rax `appOL`
x_high_code rdx `appOL`
toOL [instr size y_reg,
MOV size (OpReg rax) (OpReg reg_q),
MOV size (OpReg rdx) (OpReg reg_r)]
divOp _ _ _ _ _ _ _
= panic "genCCall64: Wrong number of results for divOp"
genCCall64' :: DynFlags
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall64' dflags target dest_regs args = do
-- load up the register arguments
let prom_args = map (maybePromoteCArg dflags W32) args
(stack_args, int_regs_used, fp_regs_used, load_args_code)
<-
if platformOS platform == OSMinGW32
then load_args_win prom_args [] [] (allArgRegs platform) nilOL
else do (stack_args, aregs, fregs, load_args_code)
<- load_args prom_args (allIntArgRegs platform) (allFPArgRegs platform) nilOL
let fp_regs_used = reverse (drop (length fregs) (reverse (allFPArgRegs platform)))
int_regs_used = reverse (drop (length aregs) (reverse (allIntArgRegs platform)))
return (stack_args, int_regs_used, fp_regs_used, load_args_code)
let
arg_regs_used = int_regs_used ++ fp_regs_used
arg_regs = [eax] ++ arg_regs_used
-- for annotating the call instruction with
sse_regs = length fp_regs_used
arg_stack_slots = if platformOS platform == OSMinGW32
then length stack_args + length (allArgRegs platform)
else length stack_args
tot_arg_size = arg_size * arg_stack_slots
-- Align stack to 16n for calls, assuming a starting stack
-- alignment of 16n - word_size on procedure entry. Which we
-- maintain. See Note [rts/StgCRun.c : Stack Alignment on X86]
(real_size, adjust_rsp) <-
if (tot_arg_size + wORD_SIZE dflags) `rem` 16 == 0
then return (tot_arg_size, nilOL)
else do -- we need to adjust...
delta <- getDeltaNat
setDeltaNat (delta - wORD_SIZE dflags)
return (tot_arg_size + wORD_SIZE dflags, toOL [
SUB II64 (OpImm (ImmInt (wORD_SIZE dflags))) (OpReg rsp),
DELTA (delta - wORD_SIZE dflags) ])
-- push the stack args, right to left
push_code <- push_args (reverse stack_args) nilOL
-- On Win64, we also have to leave stack space for the arguments
-- that we are passing in registers
lss_code <- if platformOS platform == OSMinGW32
then leaveStackSpace (length (allArgRegs platform))
else return nilOL
delta <- getDeltaNat
-- deal with static vs dynamic call targets
(callinsns,_cconv) <-
case target of
ForeignTarget (CmmLit (CmmLabel lbl)) conv
-> -- ToDo: stdcall arg sizes
return (unitOL (CALL (Left fn_imm) arg_regs), conv)
where fn_imm = ImmCLbl lbl
ForeignTarget expr conv
-> do (dyn_r, dyn_c) <- getSomeReg expr
return (dyn_c `snocOL` CALL (Right dyn_r) arg_regs, conv)
PrimTarget _
-> panic $ "genCCall: Can't handle PrimTarget call type here, error "
++ "probably because too many return values."
let
-- The x86_64 ABI requires us to set %al to the number of SSE2
-- registers that contain arguments, if the called routine
-- is a varargs function. We don't know whether it's a
-- varargs function or not, so we have to assume it is.
--
-- It's not safe to omit this assignment, even if the number
-- of SSE2 regs in use is zero. If %al is larger than 8
-- on entry to a varargs function, seg faults ensue.
assign_eax n = unitOL (MOV II32 (OpImm (ImmInt n)) (OpReg eax))
let call = callinsns `appOL`
toOL (
-- Deallocate parameters after call for ccall;
-- stdcall has callee do it, but is not supported on
-- x86_64 target (see #3336)
(if real_size==0 then [] else
[ADD (intSize (wordWidth dflags)) (OpImm (ImmInt real_size)) (OpReg esp)])
++
[DELTA (delta + real_size)]
)
setDeltaNat (delta + real_size)
let
-- assign the results, if necessary
assign_code [] = nilOL
assign_code [dest] =
case typeWidth rep of
W32 | isFloatType rep -> unitOL (MOV (floatSize W32) (OpReg xmm0) (OpReg r_dest))
W64 | isFloatType rep -> unitOL (MOV (floatSize W64) (OpReg xmm0) (OpReg r_dest))
_ -> unitOL (MOV (cmmTypeSize rep) (OpReg rax) (OpReg r_dest))
where
rep = localRegType dest
r_dest = getRegisterReg platform True (CmmLocal dest)
assign_code _many = panic "genCCall.assign_code many"
return (load_args_code `appOL`
adjust_rsp `appOL`
push_code `appOL`
lss_code `appOL`
assign_eax sse_regs `appOL`
call `appOL`
assign_code dest_regs)
where platform = targetPlatform dflags
arg_size = 8 -- always, at the mo
load_args :: [CmmExpr]
-> [Reg] -- int regs avail for args
-> [Reg] -- FP regs avail for args
-> InstrBlock
-> NatM ([CmmExpr],[Reg],[Reg],InstrBlock)
load_args args [] [] code = return (args, [], [], code)
-- no more regs to use
load_args [] aregs fregs code = return ([], aregs, fregs, code)
-- no more args to push
load_args (arg : rest) aregs fregs code
| isFloatType arg_rep =
case fregs of
[] -> push_this_arg
(r:rs) -> do
arg_code <- getAnyReg arg
load_args rest aregs rs (code `appOL` arg_code r)
| otherwise =
case aregs of
[] -> push_this_arg
(r:rs) -> do
arg_code <- getAnyReg arg
load_args rest rs fregs (code `appOL` arg_code r)
where
arg_rep = cmmExprType dflags arg
push_this_arg = do
(args',ars,frs,code') <- load_args rest aregs fregs code
return (arg:args', ars, frs, code')
load_args_win :: [CmmExpr]
-> [Reg] -- used int regs
-> [Reg] -- used FP regs
-> [(Reg, Reg)] -- (int, FP) regs avail for args
-> InstrBlock
-> NatM ([CmmExpr],[Reg],[Reg],InstrBlock)
load_args_win args usedInt usedFP [] code
= return (args, usedInt, usedFP, code)
-- no more regs to use
load_args_win [] usedInt usedFP _ code
= return ([], usedInt, usedFP, code)
-- no more args to push
load_args_win (arg : rest) usedInt usedFP
((ireg, freg) : regs) code
| isFloatType arg_rep = do
arg_code <- getAnyReg arg
load_args_win rest (ireg : usedInt) (freg : usedFP) regs
(code `appOL`
arg_code freg `snocOL`
-- If we are calling a varargs function
-- then we need to define ireg as well
-- as freg
MOV II64 (OpReg freg) (OpReg ireg))
| otherwise = do
arg_code <- getAnyReg arg
load_args_win rest (ireg : usedInt) usedFP regs
(code `appOL` arg_code ireg)
where
arg_rep = cmmExprType dflags arg
push_args [] code = return code
push_args (arg:rest) code
| isFloatType arg_rep = do
(arg_reg, arg_code) <- getSomeReg arg
delta <- getDeltaNat
setDeltaNat (delta-arg_size)
let code' = code `appOL` arg_code `appOL` toOL [
SUB (intSize (wordWidth dflags)) (OpImm (ImmInt arg_size)) (OpReg rsp) ,
DELTA (delta-arg_size),
MOV (floatSize width) (OpReg arg_reg) (OpAddr (spRel dflags 0))]
push_args rest code'
| otherwise = do
ASSERT(width == W64) return ()
(arg_op, arg_code) <- getOperand arg
delta <- getDeltaNat
setDeltaNat (delta-arg_size)
let code' = code `appOL` arg_code `appOL` toOL [
PUSH II64 arg_op,
DELTA (delta-arg_size)]
push_args rest code'
where
arg_rep = cmmExprType dflags arg
width = typeWidth arg_rep
leaveStackSpace n = do
delta <- getDeltaNat
setDeltaNat (delta - n * arg_size)
return $ toOL [
SUB II64 (OpImm (ImmInt (n * wORD_SIZE dflags))) (OpReg rsp),
DELTA (delta - n * arg_size)]
maybePromoteCArg :: DynFlags -> Width -> CmmExpr -> CmmExpr
maybePromoteCArg dflags wto arg
| wfrom < wto = CmmMachOp (MO_UU_Conv wfrom wto) [arg]
| otherwise = arg
where
wfrom = cmmExprWidth dflags arg
-- | We're willing to inline and unroll memcpy/memset calls that touch
-- at most these many bytes. This threshold is the same as the one
-- used by GCC and LLVM.
maxInlineSizeThreshold :: Integer
maxInlineSizeThreshold = 128
outOfLineCmmOp :: CallishMachOp -> Maybe CmmFormal -> [CmmActual] -> NatM InstrBlock
outOfLineCmmOp mop res args
= do
dflags <- getDynFlags
targetExpr <- cmmMakeDynamicReference dflags CallReference lbl
let target = ForeignTarget targetExpr
(ForeignConvention CCallConv [] [] CmmMayReturn)
stmtToInstrs (CmmUnsafeForeignCall target (catMaybes [res]) args')
where
-- Assume we can call these functions directly, and that they're not in a dynamic library.
-- TODO: Why is this ok? Under linux this code will be in libm.so
-- Is is because they're really implemented as a primitive instruction by the assembler?? -- BL 2009/12/31
lbl = mkForeignLabel fn Nothing ForeignLabelInThisPackage IsFunction
args' = case mop of
MO_Memcpy -> init args
MO_Memset -> init args
MO_Memmove -> init args
_ -> args
fn = case mop of
MO_F32_Sqrt -> fsLit "sqrtf"
MO_F32_Sin -> fsLit "sinf"
MO_F32_Cos -> fsLit "cosf"
MO_F32_Tan -> fsLit "tanf"
MO_F32_Exp -> fsLit "expf"
MO_F32_Log -> fsLit "logf"
MO_F32_Asin -> fsLit "asinf"
MO_F32_Acos -> fsLit "acosf"
MO_F32_Atan -> fsLit "atanf"
MO_F32_Sinh -> fsLit "sinhf"
MO_F32_Cosh -> fsLit "coshf"
MO_F32_Tanh -> fsLit "tanhf"
MO_F32_Pwr -> fsLit "powf"
MO_F64_Sqrt -> fsLit "sqrt"
MO_F64_Sin -> fsLit "sin"
MO_F64_Cos -> fsLit "cos"
MO_F64_Tan -> fsLit "tan"
MO_F64_Exp -> fsLit "exp"
MO_F64_Log -> fsLit "log"
MO_F64_Asin -> fsLit "asin"
MO_F64_Acos -> fsLit "acos"
MO_F64_Atan -> fsLit "atan"
MO_F64_Sinh -> fsLit "sinh"
MO_F64_Cosh -> fsLit "cosh"
MO_F64_Tanh -> fsLit "tanh"
MO_F64_Pwr -> fsLit "pow"
MO_Memcpy -> fsLit "memcpy"
MO_Memset -> fsLit "memset"
MO_Memmove -> fsLit "memmove"
MO_PopCnt _ -> fsLit "popcnt"
MO_BSwap _ -> fsLit "bswap"
MO_UF_Conv _ -> unsupported
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_WriteBarrier -> unsupported
MO_Touch -> unsupported
(MO_Prefetch_Data _ ) -> unsupported
unsupported = panic ("outOfLineCmmOp: " ++ show mop
++ " not supported here")
-- -----------------------------------------------------------------------------
-- Generating a table-branch
genSwitch :: DynFlags -> CmmExpr -> [Maybe BlockId] -> NatM InstrBlock
genSwitch dflags expr ids
| gopt Opt_PIC dflags
= do
(reg,e_code) <- getSomeReg expr
lbl <- getNewLabelNat
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
(tableReg,t_code) <- getSomeReg $ dynRef
let op = OpAddr (AddrBaseIndex (EABaseReg tableReg)
(EAIndex reg (wORD_SIZE dflags)) (ImmInt 0))
return $ if target32Bit (targetPlatform dflags)
then e_code `appOL` t_code `appOL` toOL [
ADD (intSize (wordWidth dflags)) op (OpReg tableReg),
JMP_TBL (OpReg tableReg) ids ReadOnlyData lbl
]
else case platformOS (targetPlatform dflags) of
OSDarwin ->
-- on Mac OS X/x86_64, put the jump table
-- in the text section to work around a
-- limitation of the linker.
-- ld64 is unable to handle the relocations for
-- .quad L1 - L0
-- if L0 is not preceded by a non-anonymous
-- label in its section.
e_code `appOL` t_code `appOL` toOL [
ADD (intSize (wordWidth dflags)) op (OpReg tableReg),
JMP_TBL (OpReg tableReg) ids Text lbl
]
_ ->
-- HACK: On x86_64 binutils<2.17 is only able
-- to generate PC32 relocations, hence we only
-- get 32-bit offsets in the jump table. As
-- these offsets are always negative we need
-- to properly sign extend them to 64-bit.
-- This hack should be removed in conjunction
-- with the hack in PprMach.hs/pprDataItem
-- once binutils 2.17 is standard.
e_code `appOL` t_code `appOL` toOL [
MOVSxL II32 op (OpReg reg),
ADD (intSize (wordWidth dflags)) (OpReg reg) (OpReg tableReg),
JMP_TBL (OpReg tableReg) ids ReadOnlyData lbl
]
| otherwise
= do
(reg,e_code) <- getSomeReg expr
lbl <- getNewLabelNat
let op = OpAddr (AddrBaseIndex EABaseNone (EAIndex reg (wORD_SIZE dflags)) (ImmCLbl lbl))
code = e_code `appOL` toOL [
JMP_TBL op ids ReadOnlyData lbl
]
return code
generateJumpTableForInstr :: DynFlags -> Instr -> Maybe (NatCmmDecl (Alignment, CmmStatics) Instr)
generateJumpTableForInstr dflags (JMP_TBL _ ids section lbl)
= Just (createJumpTable dflags ids section lbl)
generateJumpTableForInstr _ _ = Nothing
createJumpTable :: DynFlags -> [Maybe BlockId] -> Section -> CLabel
-> GenCmmDecl (Alignment, CmmStatics) h g
createJumpTable dflags ids section lbl
= let jumpTable
| gopt Opt_PIC dflags =
let jumpTableEntryRel Nothing
= CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntryRel (Just blockid)
= CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0)
where blockLabel = mkAsmTempLabel (getUnique blockid)
in map jumpTableEntryRel ids
| otherwise = map (jumpTableEntry dflags) ids
in CmmData section (1, Statics lbl jumpTable)
-- -----------------------------------------------------------------------------
-- 'condIntReg' and 'condFltReg': condition codes into registers
-- Turn those condition codes into integers now (when they appear on
-- the right hand side of an assignment).
--
-- (If applicable) Do not fill the delay slots here; you will confuse the
-- register allocator.
condIntReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register
condIntReg cond x y = do
CondCode _ cond cond_code <- condIntCode cond x y
tmp <- getNewRegNat II8
let
code dst = cond_code `appOL` toOL [
SETCC cond (OpReg tmp),
MOVZxL II8 (OpReg tmp) (OpReg dst)
]
return (Any II32 code)
condFltReg :: Bool -> Cond -> CmmExpr -> CmmExpr -> NatM Register
condFltReg is32Bit cond x y = if_sse2 condFltReg_sse2 condFltReg_x87
where
condFltReg_x87 = do
CondCode _ cond cond_code <- condFltCode cond x y
tmp <- getNewRegNat II8
let
code dst = cond_code `appOL` toOL [
SETCC cond (OpReg tmp),
MOVZxL II8 (OpReg tmp) (OpReg dst)
]
return (Any II32 code)
condFltReg_sse2 = do
CondCode _ cond cond_code <- condFltCode cond x y
tmp1 <- getNewRegNat (archWordSize is32Bit)
tmp2 <- getNewRegNat (archWordSize is32Bit)
let
-- We have to worry about unordered operands (eg. comparisons
-- against NaN). If the operands are unordered, the comparison
-- sets the parity flag, carry flag and zero flag.
-- All comparisons are supposed to return false for unordered
-- operands except for !=, which returns true.
--
-- Optimisation: we don't have to test the parity flag if we
-- know the test has already excluded the unordered case: eg >
-- and >= test for a zero carry flag, which can only occur for
-- ordered operands.
--
-- ToDo: by reversing comparisons we could avoid testing the
-- parity flag in more cases.
code dst =
cond_code `appOL`
(case cond of
NE -> or_unordered dst
GU -> plain_test dst
GEU -> plain_test dst
_ -> and_ordered dst)
plain_test dst = toOL [
SETCC cond (OpReg tmp1),
MOVZxL II8 (OpReg tmp1) (OpReg dst)
]
or_unordered dst = toOL [
SETCC cond (OpReg tmp1),
SETCC PARITY (OpReg tmp2),
OR II8 (OpReg tmp1) (OpReg tmp2),
MOVZxL II8 (OpReg tmp2) (OpReg dst)
]
and_ordered dst = toOL [
SETCC cond (OpReg tmp1),
SETCC NOTPARITY (OpReg tmp2),
AND II8 (OpReg tmp1) (OpReg tmp2),
MOVZxL II8 (OpReg tmp2) (OpReg dst)
]
return (Any II32 code)
-- -----------------------------------------------------------------------------
-- 'trivial*Code': deal with trivial instructions
-- Trivial (dyadic: 'trivialCode', floating-point: 'trivialFCode',
-- unary: 'trivialUCode', unary fl-pt:'trivialUFCode') instructions.
-- Only look for constants on the right hand side, because that's
-- where the generic optimizer will have put them.
-- Similarly, for unary instructions, we don't have to worry about
-- matching an StInt as the argument, because genericOpt will already
-- have handled the constant-folding.
{-
The Rules of the Game are:
* You cannot assume anything about the destination register dst;
it may be anything, including a fixed reg.
* You may compute an operand into a fixed reg, but you may not
subsequently change the contents of that fixed reg. If you
want to do so, first copy the value either to a temporary
or into dst. You are free to modify dst even if it happens
to be a fixed reg -- that's not your problem.
* You cannot assume that a fixed reg will stay live over an
arbitrary computation. The same applies to the dst reg.
* Temporary regs obtained from getNewRegNat are distinct from
each other and from all other regs, and stay live over
arbitrary computations.
--------------------
SDM's version of The Rules:
* If getRegister returns Any, that means it can generate correct
code which places the result in any register, period. Even if that
register happens to be read during the computation.
Corollary #1: this means that if you are generating code for an
operation with two arbitrary operands, you cannot assign the result
of the first operand into the destination register before computing
the second operand. The second operand might require the old value
of the destination register.
Corollary #2: A function might be able to generate more efficient
code if it knows the destination register is a new temporary (and
therefore not read by any of the sub-computations).
* If getRegister returns Any, then the code it generates may modify only:
(a) fresh temporaries
(b) the destination register
(c) known registers (eg. %ecx is used by shifts)
In particular, it may *not* modify global registers, unless the global
register happens to be the destination register.
-}
trivialCode :: Width -> (Operand -> Operand -> Instr)
-> Maybe (Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCode width instr m a b
= do is32Bit <- is32BitPlatform
trivialCode' is32Bit width instr m a b
trivialCode' :: Bool -> Width -> (Operand -> Operand -> Instr)
-> Maybe (Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCode' is32Bit width _ (Just revinstr) (CmmLit lit_a) b
| is32BitLit is32Bit lit_a = do
b_code <- getAnyReg b
let
code dst
= b_code dst `snocOL`
revinstr (OpImm (litToImm lit_a)) (OpReg dst)
return (Any (intSize width) code)
trivialCode' _ width instr _ a b
= genTrivialCode (intSize width) instr a b
-- This is re-used for floating pt instructions too.
genTrivialCode :: Size -> (Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
genTrivialCode rep instr a b = do
(b_op, b_code) <- getNonClobberedOperand b
a_code <- getAnyReg a
tmp <- getNewRegNat rep
let
-- We want the value of b to stay alive across the computation of a.
-- But, we want to calculate a straight into the destination register,
-- because the instruction only has two operands (dst := dst `op` src).
-- The troublesome case is when the result of b is in the same register
-- as the destination reg. In this case, we have to save b in a
-- new temporary across the computation of a.
code dst
| dst `regClashesWithOp` b_op =
b_code `appOL`
unitOL (MOV rep b_op (OpReg tmp)) `appOL`
a_code dst `snocOL`
instr (OpReg tmp) (OpReg dst)
| otherwise =
b_code `appOL`
a_code dst `snocOL`
instr b_op (OpReg dst)
return (Any rep code)
regClashesWithOp :: Reg -> Operand -> Bool
reg `regClashesWithOp` OpReg reg2 = reg == reg2
reg `regClashesWithOp` OpAddr amode = any (==reg) (addrModeRegs amode)
_ `regClashesWithOp` _ = False
-----------
trivialUCode :: Size -> (Operand -> Instr)
-> CmmExpr -> NatM Register
trivialUCode rep instr x = do
x_code <- getAnyReg x
let
code dst =
x_code dst `snocOL`
instr (OpReg dst)
return (Any rep code)
-----------
trivialFCode_x87 :: (Size -> Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialFCode_x87 instr x y = do
(x_reg, x_code) <- getNonClobberedReg x -- these work for float regs too
(y_reg, y_code) <- getSomeReg y
let
size = FF80 -- always, on x87
code dst =
x_code `appOL`
y_code `snocOL`
instr size x_reg y_reg dst
return (Any size code)
trivialFCode_sse2 :: Width -> (Size -> Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialFCode_sse2 pk instr x y
= genTrivialCode size (instr size) x y
where size = floatSize pk
trivialUFCode :: Size -> (Reg -> Reg -> Instr) -> CmmExpr -> NatM Register
trivialUFCode size instr x = do
(x_reg, x_code) <- getSomeReg x
let
code dst =
x_code `snocOL`
instr x_reg dst
return (Any size code)
--------------------------------------------------------------------------------
coerceInt2FP :: Width -> Width -> CmmExpr -> NatM Register
coerceInt2FP from to x = if_sse2 coerce_sse2 coerce_x87
where
coerce_x87 = do
(x_reg, x_code) <- getSomeReg x
let
opc = case to of W32 -> GITOF; W64 -> GITOD;
n -> panic $ "coerceInt2FP.x87: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc x_reg dst
-- ToDo: works for non-II32 reps?
return (Any FF80 code)
coerce_sse2 = do
(x_op, x_code) <- getOperand x -- ToDo: could be a safe operand
let
opc = case to of W32 -> CVTSI2SS; W64 -> CVTSI2SD
n -> panic $ "coerceInt2FP.sse: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc (intSize from) x_op dst
return (Any (floatSize to) code)
-- works even if the destination rep is <II32
--------------------------------------------------------------------------------
coerceFP2Int :: Width -> Width -> CmmExpr -> NatM Register
coerceFP2Int from to x = if_sse2 coerceFP2Int_sse2 coerceFP2Int_x87
where
coerceFP2Int_x87 = do
(x_reg, x_code) <- getSomeReg x
let
opc = case from of W32 -> GFTOI; W64 -> GDTOI
n -> panic $ "coerceFP2Int.x87: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc x_reg dst
-- ToDo: works for non-II32 reps?
return (Any (intSize to) code)
coerceFP2Int_sse2 = do
(x_op, x_code) <- getOperand x -- ToDo: could be a safe operand
let
opc = case from of W32 -> CVTTSS2SIQ; W64 -> CVTTSD2SIQ;
n -> panic $ "coerceFP2Init.sse: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc (intSize to) x_op dst
return (Any (intSize to) code)
-- works even if the destination rep is <II32
--------------------------------------------------------------------------------
coerceFP2FP :: Width -> CmmExpr -> NatM Register
coerceFP2FP to x = do
use_sse2 <- sse2Enabled
(x_reg, x_code) <- getSomeReg x
let
opc | use_sse2 = case to of W32 -> CVTSD2SS; W64 -> CVTSS2SD;
n -> panic $ "coerceFP2FP: unhandled width ("
++ show n ++ ")"
| otherwise = GDTOF
code dst = x_code `snocOL` opc x_reg dst
return (Any (if use_sse2 then floatSize to else FF80) code)
--------------------------------------------------------------------------------
sse2NegCode :: Width -> CmmExpr -> NatM Register
sse2NegCode w x = do
let sz = floatSize w
x_code <- getAnyReg x
-- This is how gcc does it, so it can't be that bad:
let
const | FF32 <- sz = CmmInt 0x80000000 W32
| otherwise = CmmInt 0x8000000000000000 W64
Amode amode amode_code <- memConstant (widthInBytes w) const
tmp <- getNewRegNat sz
let
code dst = x_code dst `appOL` amode_code `appOL` toOL [
MOV sz (OpAddr amode) (OpReg tmp),
XOR sz (OpReg tmp) (OpReg dst)
]
--
return (Any sz code)
isVecExpr :: CmmExpr -> Bool
isVecExpr (CmmMachOp (MO_V_Insert {}) _) = True
isVecExpr (CmmMachOp (MO_V_Extract {}) _) = True
isVecExpr (CmmMachOp (MO_V_Add {}) _) = True
isVecExpr (CmmMachOp (MO_V_Sub {}) _) = True
isVecExpr (CmmMachOp (MO_V_Mul {}) _) = True
isVecExpr (CmmMachOp (MO_VS_Quot {}) _) = True
isVecExpr (CmmMachOp (MO_VS_Rem {}) _) = True
isVecExpr (CmmMachOp (MO_VS_Neg {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Insert {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Extract {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Add {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Sub {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Mul {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Quot {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Neg {}) _) = True
isVecExpr (CmmMachOp _ [e]) = isVecExpr e
isVecExpr _ = False
needLlvm :: NatM a
needLlvm =
sorry $ unlines ["The native code generator does not support vector"
,"instructions. Please use -fllvm."]
|
lukexi/ghc-7.8-arm64
|
compiler/nativeGen/X86/CodeGen.hs
|
bsd-3-clause
| 108,302 | 0 | 23 | 36,225 | 28,357 | 13,962 | 14,395 | -1 | -1 |
module BinarySearch where
import Control.Lens
import Data.Maybe
a :: [Int]
a = [6, 13, 14, 25, 33, 43, 51, 53, 64, 72, 84, 93, 95, 96, 97]
bsearch :: Int -> [Int] -> Maybe Int
bsearch _ [] = Nothing
bsearch key xs
| key < fromJust val = bsearch key (take (mid-1) xs)
| key > fromJust val = bsearch key (drop (mid+1) xs)
| otherwise = val
where
mid = floor ((fromIntegral $ (length xs) - 1) / 2)
val = xs ^? ix mid
|
manikTharaka/al-go-rithms
|
search/binary_search/haskell/binary_search.hs
|
mit
| 445 | 0 | 14 | 118 | 237 | 128 | 109 | 13 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Options
-- Copyright : (c) Simon Marlow 2003-2006,
-- David Waern 2006-2009,
-- Mateusz Kowalczyk 2013
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Definition of the command line interface of Haddock.
-----------------------------------------------------------------------------
module Haddock.Options (
parseHaddockOpts,
Flag(..),
getUsage,
optTitle,
outputDir,
optContentsUrl,
optIndexUrl,
optCssFile,
optSourceCssFile,
sourceUrls,
wikiUrls,
optDumpInterfaceFile,
optLaTeXStyle,
qualification,
verbosity,
ghcFlags,
readIfaceArgs,
optPackageName,
optPackageVersion
) where
import qualified Data.Char as Char
import Data.Version
import Distribution.Verbosity
import FastString
import Haddock.Types
import Haddock.Utils
import Packages
import System.Console.GetOpt
import qualified Text.ParserCombinators.ReadP as RP
data Flag
= Flag_BuiltInThemes
| Flag_CSS String
-- | Flag_DocBook
| Flag_ReadInterface String
| Flag_DumpInterface String
| Flag_Heading String
| Flag_Html
| Flag_Hoogle
| Flag_Lib String
| Flag_OutputDir FilePath
| Flag_Prologue FilePath
| Flag_SourceBaseURL String
| Flag_SourceModuleURL String
| Flag_SourceEntityURL String
| Flag_SourceLEntityURL String
| Flag_WikiBaseURL String
| Flag_WikiModuleURL String
| Flag_WikiEntityURL String
| Flag_LaTeX
| Flag_LaTeXStyle String
| Flag_HyperlinkedSource
| Flag_SourceCss String
| Flag_Help
| Flag_Verbosity String
| Flag_Version
| Flag_CompatibleInterfaceVersions
| Flag_InterfaceVersion
| Flag_UseContents String
| Flag_GenContents
| Flag_UseIndex String
| Flag_GenIndex
| Flag_IgnoreAllExports
| Flag_HideModule String
| Flag_ShowExtensions String
| Flag_OptGhc String
| Flag_GhcLibDir String
| Flag_GhcVersion
| Flag_PrintGhcPath
| Flag_PrintGhcLibDir
| Flag_NoWarnings
| Flag_UseUnicode
| Flag_NoTmpCompDir
| Flag_Qualification String
| Flag_PrettyHtml
| Flag_NoPrintMissingDocs
| Flag_PackageName String
| Flag_PackageVersion String
deriving (Eq, Show)
options :: Bool -> [OptDescr Flag]
options backwardsCompat =
[
Option ['B'] [] (ReqArg Flag_GhcLibDir "DIR")
"path to a GHC lib dir, to override the default path",
Option ['o'] ["odir"] (ReqArg Flag_OutputDir "DIR")
"directory in which to put the output files",
Option ['l'] ["lib"] (ReqArg Flag_Lib "DIR")
"location of Haddock's auxiliary files",
Option ['i'] ["read-interface"] (ReqArg Flag_ReadInterface "FILE")
"read an interface from FILE",
Option ['D'] ["dump-interface"] (ReqArg Flag_DumpInterface "FILE")
"write the resulting interface to FILE",
-- Option ['S'] ["docbook"] (NoArg Flag_DocBook)
-- "output in DocBook XML",
Option ['h'] ["html"] (NoArg Flag_Html)
"output in HTML (XHTML 1.0)",
Option [] ["latex"] (NoArg Flag_LaTeX) "use experimental LaTeX rendering",
Option [] ["latex-style"] (ReqArg Flag_LaTeXStyle "FILE") "provide your own LaTeX style in FILE",
Option ['U'] ["use-unicode"] (NoArg Flag_UseUnicode) "use Unicode in HTML output",
Option [] ["hoogle"] (NoArg Flag_Hoogle)
"output for Hoogle; you may want --package-name and --package-version too",
Option [] ["hyperlinked-source"] (NoArg Flag_HyperlinkedSource)
"generate highlighted and hyperlinked source code (for use with --html)",
Option [] ["source-css"] (ReqArg Flag_SourceCss "FILE")
"use custom CSS file instead of default one in hyperlinked source",
Option [] ["source-base"] (ReqArg Flag_SourceBaseURL "URL")
"URL for a source code link on the contents\nand index pages",
Option ['s'] (if backwardsCompat then ["source", "source-module"] else ["source-module"])
(ReqArg Flag_SourceModuleURL "URL")
"URL for a source code link for each module\n(using the %{FILE} or %{MODULE} vars)",
Option [] ["source-entity"] (ReqArg Flag_SourceEntityURL "URL")
"URL for a source code link for each entity\n(using the %{FILE}, %{MODULE}, %{NAME},\n%{KIND} or %{LINE} vars)",
Option [] ["source-entity-line"] (ReqArg Flag_SourceLEntityURL "URL")
"URL for a source code link for each entity.\nUsed if name links are unavailable, eg. for TH splices.",
Option [] ["comments-base"] (ReqArg Flag_WikiBaseURL "URL")
"URL for a comments link on the contents\nand index pages",
Option [] ["comments-module"] (ReqArg Flag_WikiModuleURL "URL")
"URL for a comments link for each module\n(using the %{MODULE} var)",
Option [] ["comments-entity"] (ReqArg Flag_WikiEntityURL "URL")
"URL for a comments link for each entity\n(using the %{FILE}, %{MODULE}, %{NAME},\n%{KIND} or %{LINE} vars)",
Option ['c'] ["css", "theme"] (ReqArg Flag_CSS "PATH")
"the CSS file or theme directory to use for HTML output",
Option [] ["built-in-themes"] (NoArg Flag_BuiltInThemes)
"include all the built-in haddock themes",
Option ['p'] ["prologue"] (ReqArg Flag_Prologue "FILE")
"file containing prologue text",
Option ['t'] ["title"] (ReqArg Flag_Heading "TITLE")
"page heading",
Option ['q'] ["qual"] (ReqArg Flag_Qualification "QUAL")
"qualification of names, one of \n'none' (default), 'full', 'local'\n'relative' or 'aliased'",
Option ['?'] ["help"] (NoArg Flag_Help)
"display this help and exit",
Option ['V'] ["version"] (NoArg Flag_Version)
"output version information and exit",
Option [] ["compatible-interface-versions"] (NoArg Flag_CompatibleInterfaceVersions)
"output compatible interface file versions and exit",
Option [] ["interface-version"] (NoArg Flag_InterfaceVersion)
"output interface file version and exit",
Option ['v'] ["verbosity"] (ReqArg Flag_Verbosity "VERBOSITY")
"set verbosity level",
Option [] ["use-contents"] (ReqArg Flag_UseContents "URL")
"use a separately-generated HTML contents page",
Option [] ["gen-contents"] (NoArg Flag_GenContents)
"generate an HTML contents from specified\ninterfaces",
Option [] ["use-index"] (ReqArg Flag_UseIndex "URL")
"use a separately-generated HTML index",
Option [] ["gen-index"] (NoArg Flag_GenIndex)
"generate an HTML index from specified\ninterfaces",
Option [] ["ignore-all-exports"] (NoArg Flag_IgnoreAllExports)
"behave as if all modules have the\nignore-exports atribute",
Option [] ["hide"] (ReqArg Flag_HideModule "MODULE")
"behave as if MODULE has the hide attribute",
Option [] ["show-extensions"] (ReqArg Flag_ShowExtensions "MODULE")
"behave as if MODULE has the show-extensions attribute",
Option [] ["optghc"] (ReqArg Flag_OptGhc "OPTION")
"option to be forwarded to GHC",
Option [] ["ghc-version"] (NoArg Flag_GhcVersion)
"output GHC version in numeric format",
Option [] ["print-ghc-path"] (NoArg Flag_PrintGhcPath)
"output path to GHC binary",
Option [] ["print-ghc-libdir"] (NoArg Flag_PrintGhcLibDir)
"output GHC lib dir",
Option ['w'] ["no-warnings"] (NoArg Flag_NoWarnings) "turn off all warnings",
Option [] ["no-tmp-comp-dir"] (NoArg Flag_NoTmpCompDir)
"do not re-direct compilation output to a temporary directory",
Option [] ["pretty-html"] (NoArg Flag_PrettyHtml)
"generate html with newlines and indenting (for use with --html)",
Option [] ["no-print-missing-docs"] (NoArg Flag_NoPrintMissingDocs)
"don't print information about any undocumented entities",
Option [] ["package-name"] (ReqArg Flag_PackageName "NAME")
"name of the package being documented",
Option [] ["package-version"] (ReqArg Flag_PackageVersion "VERSION")
"version of the package being documented in usual x.y.z.w format"
]
getUsage :: IO String
getUsage = do
prog <- getProgramName
return $ usageInfo (usageHeader prog) (options False)
where
usageHeader :: String -> String
usageHeader prog = "Usage: " ++ prog ++ " [OPTION...] file...\n"
parseHaddockOpts :: [String] -> IO ([Flag], [String])
parseHaddockOpts params =
case getOpt Permute (options True) params of
(flags, args, []) -> return (flags, args)
(_, _, errors) -> do
usage <- getUsage
throwE (concat errors ++ usage)
optPackageVersion :: [Flag] -> Maybe Data.Version.Version
optPackageVersion flags =
let ver = optLast [ v | Flag_PackageVersion v <- flags ]
in ver >>= fmap fst . optLast . RP.readP_to_S parseVersion
optPackageName :: [Flag] -> Maybe PackageName
optPackageName flags =
optLast [ PackageName $ mkFastString n | Flag_PackageName n <- flags ]
optTitle :: [Flag] -> Maybe String
optTitle flags =
case [str | Flag_Heading str <- flags] of
[] -> Nothing
(t:_) -> Just t
outputDir :: [Flag] -> FilePath
outputDir flags =
case [ path | Flag_OutputDir path <- flags ] of
[] -> "."
paths -> last paths
optContentsUrl :: [Flag] -> Maybe String
optContentsUrl flags = optLast [ url | Flag_UseContents url <- flags ]
optIndexUrl :: [Flag] -> Maybe String
optIndexUrl flags = optLast [ url | Flag_UseIndex url <- flags ]
optCssFile :: [Flag] -> Maybe FilePath
optCssFile flags = optLast [ str | Flag_CSS str <- flags ]
optSourceCssFile :: [Flag] -> Maybe FilePath
optSourceCssFile flags = optLast [ str | Flag_SourceCss str <- flags ]
sourceUrls :: [Flag] -> (Maybe String, Maybe String, Maybe String, Maybe String)
sourceUrls flags =
(optLast [str | Flag_SourceBaseURL str <- flags]
,optLast [str | Flag_SourceModuleURL str <- flags]
,optLast [str | Flag_SourceEntityURL str <- flags]
,optLast [str | Flag_SourceLEntityURL str <- flags])
wikiUrls :: [Flag] -> (Maybe String, Maybe String, Maybe String)
wikiUrls flags =
(optLast [str | Flag_WikiBaseURL str <- flags]
,optLast [str | Flag_WikiModuleURL str <- flags]
,optLast [str | Flag_WikiEntityURL str <- flags])
optDumpInterfaceFile :: [Flag] -> Maybe FilePath
optDumpInterfaceFile flags = optLast [ str | Flag_DumpInterface str <- flags ]
optLaTeXStyle :: [Flag] -> Maybe String
optLaTeXStyle flags = optLast [ str | Flag_LaTeXStyle str <- flags ]
qualification :: [Flag] -> Either String QualOption
qualification flags =
case map (map Char.toLower) [ str | Flag_Qualification str <- flags ] of
[] -> Right OptNoQual
["none"] -> Right OptNoQual
["full"] -> Right OptFullQual
["local"] -> Right OptLocalQual
["relative"] -> Right OptRelativeQual
["aliased"] -> Right OptAliasedQual
[arg] -> Left $ "unknown qualification type " ++ show arg
_:_ -> Left "qualification option given multiple times"
verbosity :: [Flag] -> Verbosity
verbosity flags =
case [ str | Flag_Verbosity str <- flags ] of
[] -> normal
x:_ -> case parseVerbosity x of
Left e -> throwE e
Right v -> v
ghcFlags :: [Flag] -> [String]
ghcFlags flags = [ option | Flag_OptGhc option <- flags ]
readIfaceArgs :: [Flag] -> [(DocPaths, FilePath)]
readIfaceArgs flags = [ parseIfaceOption s | Flag_ReadInterface s <- flags ]
where
parseIfaceOption :: String -> (DocPaths, FilePath)
parseIfaceOption str =
case break (==',') str of
(fpath, ',':rest) ->
case break (==',') rest of
(src, ',':file) -> ((fpath, Just src), file)
(file, _) -> ((fpath, Nothing), file)
(file, _) -> (("", Nothing), file)
-- | Like 'listToMaybe' but returns the last element instead of the first.
optLast :: [a] -> Maybe a
optLast [] = Nothing
optLast xs = Just (last xs)
|
lamefun/haddock
|
haddock-api/src/Haddock/Options.hs
|
bsd-2-clause
| 11,972 | 0 | 15 | 2,554 | 2,914 | 1,562 | 1,352 | 255 | 8 |
module T14373b where
data BigFam = A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P
{-# NOINLINE earlySwitch #-}
earlySwitch A = True
earlySwitch B = False
earlySwitch C = False
|
sdiehl/ghc
|
testsuite/tests/codeGen/should_compile/T14373b.hs
|
bsd-3-clause
| 193 | 0 | 5 | 55 | 81 | 50 | 31 | 6 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="tr-TR">
<title>AMF Support</title>
<maps>
<homeID>amf</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
kingthorin/zap-extensions
|
addOns/amf/src/main/javahelp/help_tr_TR/helpset_tr_TR.hs
|
apache-2.0
| 956 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
{-# OPTIONS_GHC -ddump-types #-}
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleContexts #-}
-- See Trac #1456
-- The key thing here is that foo should get the type
-- foo :: forall b s t1. (Zork s (Z [Char]) b)
-- => Q s (Z [Char]) t1 -> ST s ()
-- Note the quantification over 'b', which was previously
-- omitted; see Note [Important subtlety in oclose] in FunDeps
module ShouldCompile where
import GHC.ST
data Q s a chain = Node s a chain
data Z a = Z a
s :: Q t (Z [Char]) t1 -> Q t (Z [Char]) t1
s = undefined
class Zork s a b | a -> b where
huh :: Q s a chain -> ST s ()
foo b = huh (s b)
|
spacekitteh/smcghc
|
testsuite/tests/typecheck/should_compile/tc231.hs
|
bsd-3-clause
| 642 | 0 | 9 | 156 | 148 | 83 | 65 | 11 | 1 |
{-# LANGUAGE PolyKinds, KindSignatures, FunctionalDependencies, FlexibleInstances,
UndecidableInstances, TypeOperators, DataKinds, FlexibleContexts #-}
module T6015a where
import Prelude hiding ((++))
data T a = T
class ((a :: [k]) ++ (b :: [k])) (c :: [k]) | a b -> c
instance ('[] ++ b) b
instance (a ++ b) c => ((x ': a) ++ b) (x ': c)
test = T :: ('[True] ++ '[]) l => T l
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/polykinds/T6015a.hs
|
bsd-3-clause
| 402 | 6 | 11 | 94 | 173 | 98 | 75 | -1 | -1 |
{-# LANGUAGE TupleSections #-}
-- |Vectorise variables and literals.
module Vectorise.Var
( vectBndr
, vectBndrNew
, vectBndrIn
, vectBndrNewIn
, vectBndrsIn
, vectVar
, vectConst
)
where
import Vectorise.Utils
import Vectorise.Monad
import Vectorise.Env
import Vectorise.Vect
import Vectorise.Type.Type
import CoreSyn
import Type
import VarEnv
import Id
import FastString
import Control.Applicative
-- Binders ----------------------------------------------------------------------------------------
-- |Vectorise a binder variable, along with its attached type.
--
vectBndr :: Var -> VM VVar
vectBndr v
= do (vty, lty) <- vectAndLiftType (idType v)
let vv = v `Id.setIdType` vty
lv = v `Id.setIdType` lty
updLEnv (mapTo vv lv)
return (vv, lv)
where
mapTo vv lv env = env { local_vars = extendVarEnv (local_vars env) v (vv, lv) }
-- |Vectorise a binder variable, along with its attached type, but give the result a new name.
--
vectBndrNew :: Var -> FastString -> VM VVar
vectBndrNew v fs
= do vty <- vectType (idType v)
vv <- newLocalVVar fs vty
updLEnv (upd vv)
return vv
where
upd vv env = env { local_vars = extendVarEnv (local_vars env) v vv }
-- |Vectorise a binder then run a computation with that binder in scope.
--
vectBndrIn :: Var -> VM a -> VM (VVar, a)
vectBndrIn v p
= localV
$ do vv <- vectBndr v
x <- p
return (vv, x)
-- |Vectorise a binder, give it a new name, then run a computation with that binder in scope.
--
vectBndrNewIn :: Var -> FastString -> VM a -> VM (VVar, a)
vectBndrNewIn v fs p
= localV
$ do vv <- vectBndrNew v fs
x <- p
return (vv, x)
-- |Vectorise some binders, then run a computation with them in scope.
--
vectBndrsIn :: [Var] -> VM a -> VM ([VVar], a)
vectBndrsIn vs p
= localV
$ do vvs <- mapM vectBndr vs
x <- p
return (vvs, x)
-- Variables --------------------------------------------------------------------------------------
-- |Vectorise a variable, producing the vectorised and lifted versions.
--
vectVar :: Var -> VM VExpr
vectVar var
= do { vVar <- lookupVar var
; case vVar of
Local (vv, lv) -> return (Var vv, Var lv) -- local variables have a vect & lifted version
Global vv -> vectConst (Var vv) -- global variables get replicated
}
-- Constants --------------------------------------------------------------------------------------
-- |Constants are lifted by replication along the integer context in the `VM` state for the number
-- of elements in the result array.
--
vectConst :: CoreExpr -> VM VExpr
vectConst c = (c,) <$> liftPD c
|
frantisekfarka/ghc-dsi
|
compiler/vectorise/Vectorise/Var.hs
|
bsd-3-clause
| 2,681 | 0 | 12 | 601 | 680 | 358 | 322 | 61 | 2 |
{-# OPTIONS_GHC -fwarn-unused-imports #-}
module Test where
import qualified Control.Monad (ap)
-- Test that GHC warns about the following unused import:
import qualified Control.Monad.Reader
foo :: IO ()
foo = return id `Control.Monad.ap` return ()
|
ezyang/ghc
|
testsuite/tests/module/T1074.hs
|
bsd-3-clause
| 252 | 0 | 7 | 37 | 56 | 34 | 22 | 6 | 1 |
-- !!! deriving Ix on d. type with one constructor
module ShouldSucceed where
import Data.Ix
data Pair a b = Pair a b deriving (Show, Ord, Eq, Ix)
|
urbanslug/ghc
|
testsuite/tests/deriving/should_compile/drv009.hs
|
bsd-3-clause
| 149 | 0 | 6 | 30 | 42 | 25 | 17 | 3 | 0 |
{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples, FlexibleInstances #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
module Arr (
Array(..), (!!!), array
) where
import GHC.Num
import GHC.ST
import GHC.Base
import Good
data Array e = Array !Int !Int Int (Array# e)
array :: (Int,Int) -> [(Int, e)] -> Array e
array (l,u) ies
= unsafeArray (l,u) [(index (l,u) i, e) | (i, e) <- ies]
unsafeArray :: (Int,Int) -> [(Int, e)] -> Array e
unsafeArray b ies = unsafeArray' b (rangeSize b) ies
unsafeArray' :: (Int,Int) -> Int -> [(Int, e)] -> Array e
unsafeArray' (l,u) n@(I# n#) ies =
if n == 0 then error "aa" else runST (ST $ \s1# ->
case newArray# n# arrEleBottom s1# of
(# s2#, marr# #) ->
foldr (fill marr#) (done l u n marr#) ies s2#)
{-# NOINLINE arrEleBottom #-}
arrEleBottom :: a
arrEleBottom = error "(Array.!): undefined array element"
unsafeAt :: Array e -> Int -> e
unsafeAt (Array _ _ _ arr#) (I# i#) =
case indexArray# arr# i# of (# e #) -> e
fill :: MutableArray# s e -> (Int, e) -> STRep s a -> STRep s a
fill marr# (I# i#, e) next
= \s1# -> case writeArray# marr# i# e s1# of
s2# -> next s2#
done :: Int -> Int -> Int -> MutableArray# s e -> STRep s (Array e)
done l u n marr#
= \s1# -> case unsafeFreezeArray# marr# s1# of
(# s2#, arr# #) -> (# s2#, Array l u n arr# #)
instance Eq (Array e) where
(Array l1 _ _ _) == (Array l2 _ _ _) = l1 == l2
instance Ord (Array e) where
compare (Array l1 _ _ _) (Array l2 _ _ _) = compare l1 l2
{-# INLINE index #-}
index :: (Int,Int) -> Int -> Int
index (m,n) i | m <= i && i <= n = i - m
| otherwise = error "index out of range"
rangeSize :: (Int,Int) -> Int
rangeSize (l,h) = h - l + 1
{-# INLINE (!!!) #-}
(!!!) :: Array e -> Int -> e
arr@(Array l u _ _) !!! i = unsafeAt arr $ index (l,u) i
instance Good (Array Int) where
isGood (Array _ _ n _) = 0 < n
|
urbanslug/ghc
|
testsuite/tests/stranal/should_run/T8425/Arr.hs
|
bsd-3-clause
| 1,965 | 0 | 15 | 528 | 917 | 484 | 433 | 53 | 2 |
module Control.Concurrent.Object
( Class(..), Object, Self(..), CallbackModule(..)
, ObjectLike(..)
) where
import Prelude hiding (init, mod)
import Control.Exception
import Control.Concurrent
import Control.Concurrent.STM
import Control.Concurrent.Object.Internal
instance ObjectLike IO (Object msg reply) where
type OMessage (Object msg reply) = msg
type OReply (Object msg reply) = reply
type OClass (Object msg reply) = Class msg reply
new = newObject
obj ! msg = atomically $ writeTChan (objChan obj) (msg, Nothing)
obj !? msg = do
mv <- newEmptyMVar
atomically $ writeTChan (objChan obj) (msg, Just mv)
-- TODO: timeout
return $ readMVar mv
kill obj = killThread $ objThreadId obj
instance ObjectLike IO (Self msg reply state) where
type OMessage (Self msg reply state) = msg
type OReply (Self msg reply state) = reply
type OClass (Self msg reply state) = Class msg reply
-- | Self should not be made by itself.
new = error "Self cannot be made"
self ! msg = do
_ <- runCallbackModule self msg
return ()
self !? msg = do
(reply, _self') <- runCallbackModule self msg
mv <- newMVar reply
return $ readMVar mv
kill self = killThread $ selfThreadId self
|
ruicc/structured-concurrent-object
|
src/Control/Concurrent/Object.hs
|
mit
| 1,314 | 0 | 11 | 343 | 443 | 230 | 213 | -1 | -1 |
{-|
Module : PostgREST.Private.ProxyUri
Description : Proxy Uri validator
-}
module PostgREST.Config.Proxy
( Proxy(..)
, isMalformedProxyUri
, toURI
) where
import Data.Maybe (fromJust)
import Data.Text (pack, toLower)
import Network.URI (URI (..), URIAuth (..), isAbsoluteURI, parseURI)
import Protolude hiding (Proxy, dropWhile, get, intercalate,
toLower, toS, (&))
import Protolude.Conv (toS)
data Proxy = Proxy
{ proxyScheme :: Text
, proxyHost :: Text
, proxyPort :: Integer
, proxyPath :: Text
}
{-|
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 :: Text -> Bool
isMalformedProxyUri uri
| isAbsoluteURI (toS uri) = not $ isUriValid $ toURI uri
| otherwise = True
toURI :: Text -> URI
toURI uri = fromJust $ parseURI (toS uri)
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
|
steve-chavez/postgrest
|
src/PostgREST/Config/Proxy.hs
|
mit
| 2,143 | 0 | 11 | 492 | 632 | 343 | 289 | 50 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
module UITest where
import Testing
import Control.Hspl hiding (predicate)
import qualified Control.Hspl as Hspl
import Control.Hspl.Internal.Ast
import qualified Control.Hspl.Internal.Ast as Ast
import Control.Hspl.Internal.UI
import Control.Hspl.Internal.Syntax
import Control.Monad
import Control.Monad.Writer
import Data.Data
import Data.List
import GHC.Generics
data Pair a b = Pair a b
deriving (Show, Eq, Typeable, Data, Generic)
instance (SubTerm a, SubTerm b) => Termable (Pair a b)
newtype IntFrac = IntFrac { toDouble :: Double }
deriving (Num, Fractional, Real, Ord, Enum, Typeable, Data, Eq)
instance Show IntFrac where
show = show . toDouble
instance Termable IntFrac where
toTerm = Constant
-- This is weird and, well, bad, but it makes parameterizing the tests for numerical operators a lot
-- easier. Obviously we'll never want to depend on these operations actually behaving nicely.
instance Integral IntFrac where
quotRem (IntFrac d1) (IntFrac d2) = quotRem (floor d1) (floor d2)
toInteger (IntFrac d) = floor d
type BinOps a = [(a -> a -> Term (HSPLType a), String)]
binOps :: (TermData a, Num (HSPLType a), Fractional (HSPLType a), Integral (HSPLType a)) => BinOps a
binOps = [ ((.+.), ".+.")
, ((.-.), ".-.")
, ((.*.), ".*.")
, ((./.), "./.")
, ((.\.), ".\\.")
, ((.%.), ".%.")
]
test :: TestSuite
test = describeModule "Control.Hspl.Internal.UI" $ do
describe "formatType" $
withParams [typeOf True, typeOf $ Just True, typeOf (Left True :: Either Bool Char)] $ \ty ->
it "should show a TypeRep" $
formatType ty `shouldBe` show ty
describe "parensType" $ do
withParams [typeOf $ Just True, typeOf (Left True :: Either Bool Char)] $ \ty ->
it "should parenthesize a type with parameters" $
parensType ty `shouldBe` ("(" ++ formatType ty ++ ")")
it "should not parenthesize a simple type" $
parensType (typeOf True) `shouldBe` formatType (typeOf True)
describe "formatVariable" $ do
it "should show the name and type of the variable" $ do
formatVariable (Var "x" :: Var Bool) `shouldBe` ("x :: " ++ formatType (typeOf True))
formatVariable (Var "x" :: Var (Maybe Bool)) `shouldBe`
("x :: " ++ formatType (typeOf $ Just True))
it "should show Fresh variables with an underscore" $
formatVariable (Fresh 0 :: Var Bool) `shouldBe` ("_0 :: " ++ formatType (typeOf True))
it "should show Anon variables with two underscores" $
formatVariable (Anon :: Var Bool) `shouldBe` ("__ :: " ++ formatType (typeOf True))
describe "parensVariable" $
it "should always add parentheses" $ do
let runTest x = parensVariable x `shouldBe` ("(" ++ formatVariable x ++ ")")
runTest (Var "x" :: Var Bool)
runTest (Var "x" :: Var (Maybe Bool))
runTest (Fresh 0 :: Var Bool)
runTest (Anon :: Var Bool)
describe "formatTerm" $ do
let format :: TermData a => a -> String
format = formatTerm . toTerm
it "should show a constant" $ do
let runTest t = formatTerm (toTerm t) `shouldBe` show t
runTest 'a'
runTest (1 :: Int)
runTest (1.0 :: Double)
runTest True
it "should format a variable" $ do
let runTest :: TermEntry a => Var a -> Expectation
runTest x = formatTerm (toTerm x) `shouldBe` formatVariable x
runTest (char "x")
runTest (v"x" :: Var (Maybe Char))
runTest (v"x" :: Var (Char, Bool))
runTest (v"x" :: Var [Int])
runTest (Fresh 0 :: Var Char)
it "should produce a somewhat readable representation of a list" $ do
format ([] :: [Int]) `shouldBe` "[]"
format "foo" `shouldBe` "\"foo\""
format [True] `shouldBe` "[True]"
format [True, False] `shouldBe` "[True, False]"
format [[True, False], [False, True]] `shouldBe` "[[True, False], [False, True]]"
format (['a'].++.[v"x"]) `shouldBe` "['a', x :: Char]"
format (v"xs".++."foo") `shouldBe` "(xs :: [Char]).++.\"foo\""
format (string "xs" .++. string "ys") `shouldBe` "(xs :: [Char]).++.(ys :: [Char])"
format ('a'.:.v"xs") `shouldBe` "['a'].++.(xs :: [Char])"
format ('a'.:.v"xs".++."foo") `shouldBe` "['a'].++.(xs :: [Char]).++.\"foo\""
it "should produce a somewhat readable representation of a tuple" $ do
format (True, False) `shouldBe` "(True, False)"
format (('a', 'b'), False) `shouldBe` "(('a', 'b'), False)"
format (('a', True), ('b', False)) `shouldBe` "(('a', True), ('b', False))"
it "should produce a somewhat readable representation of an adt" $ do
format (Nothing :: Maybe Char) `shouldBe` "Nothing"
format (Just $$ 'a') `shouldBe` "Just $$ 'a'"
format (Pair $$ ('a', 'b')) `shouldBe` "Pair $$ ('a', 'b')"
format (Pair $$ ('a', (True, False))) `shouldBe` "Pair $$ ('a', (True, False))"
it "should produce a somewhat readable representation of a binary operation" $
forM_ binOps (\(op, sop) ->
format (IntFrac 1.0 `op` IntFrac 2.0) `shouldBe` ("1.0" ++ sop ++ "2.0")
)
it "should parenthesize subterms where necessary" $ do
let subTerm = (1 :: IntFrac) .+. (2 :: IntFrac)
let subTermNoParens = "1.0.+.2.0"
let subTermParens = "(1.0.+.2.0)"
-- List and tuple elements should not be parenthesized
format [subTerm] `shouldBe` "[" ++ subTermNoParens ++ "]"
format ('a', subTerm) `shouldBe` "('a', " ++ subTermNoParens ++ ")"
-- ADT arguments are parenthesized only when not part of a tuple
format (Just $$ subTerm) `shouldBe` "Just $$ " ++ subTermParens
format (Just $$ ('a', subTerm)) `shouldBe` "Just $$ ('a', " ++ subTermNoParens ++ ")"
-- Binary operands are always parenthesized
forM_ binOps (\(op, sop) ->
format (subTerm `op` subTerm) `shouldBe` (subTermParens ++ sop ++ subTermParens)
)
describe "parensTerm" $ do
let shouldParens t = parensTerm (toTerm t) `shouldEqual` ("(" ++ formatTerm (toTerm t) ++ ")")
let shouldNotParens t = parensTerm (toTerm t) `shouldEqual` formatTerm (toTerm t)
withParams binOps $ \(op, _) ->
it "should parenthesize binary operation expressions" $
shouldParens ((1 :: IntFrac) `op` (2 :: IntFrac))
it "should parenthesize adt constructors with at least one argument" $ do
shouldParens (Just $$ 'a')
shouldParens (Just $$ ('a', True))
it "should not parenthesize adt constructors with no arguments" $
shouldNotParens (Nothing :: Maybe Char)
it "should not parenthesize constants" $
shouldNotParens 'a'
it "should parenthesize variables" $
shouldParens (char "x")
withParams [nil, toTerm ['a'], toTerm ['a', 'b'], 'a'.:.string "xs"] $ \l ->
it "should not parenthesize lists" $
shouldNotParens l
it "should not parenthesize tuples" $ do
shouldNotParens ('a', True)
shouldNotParens (('a', True), ("foo", 'b'))
describe "formatPredicate" $ do
it "should produce a readable representation of a predicate" $
formatPredicate (predicate "foo" 'a') `shouldBe` ("foo? " ++ formatTerm (toTerm 'a'))
it "should parenthesize the term where necessary" $
formatPredicate (predicate "foo" ((1 :: Int).+.(2 :: Int))) `shouldBe`
("foo? (" ++ formatTerm ((1 :: Int).+.(2 :: Int)) ++ ")")
describe "formatGoal" $ do
withParams [ PredGoal (predicate "foo" 'a') []
, PredGoal (predicate "foo" 'a') [HornClause (predicate "foo" 'a') Top]
] $ \g@(PredGoal p _) ->
it "should format the predicate of a PredGoal, ignoring the clauses" $
formatGoal g `shouldBe` formatPredicate p
withParams [(IsVariable, "isVariable"), (IsUnified, "isUnified")] $ \(constr, s) ->
withParams [toTerm (1 :: Int), (1 :: Int).+.(2 :: Int)] $ \t ->
it "should format a unary term goal" $
formatGoal (constr t) `shouldBe` s ++ " " ++ parensTerm t
withParams [((.=.), ".=."), (is, " `is` "), ((.==.), ".==."), ((.<.), ".<.")] $ \(op, sop) ->
withParams [toTerm (1 :: Int), (1 :: Int) .+. (2 :: Int)] $ \t ->
it "should format a binary term goal" $
formatGoal (astGoal (t `op` t)) `shouldEqual`
(parensTerm t ++ sop ++ parensTerm t)
withParams [(cutFrame, "cutFrame"), (track, "track"), (once, "once")] $ \(op, sop) ->
withParams (map tell [Top, Once Top]) $ \gw ->
it "should format a unary subgoal" $
formatGoal (astGoal $ op gw) `shouldBe`
(sop ++ " " ++ parensGoal (astGoal gw))
withParams [((>>), ".&."), ((.|.), ".|.")] $ \(op, sop) ->
withParams (map tell [Top, Once Top]) $ \gw ->
it "should format binary subgoals" $ do
let g = astGoal gw
formatGoal (astGoal (gw `op` gw)) `shouldBe`
(parensGoal g ++ sop ++ parensGoal g)
withParams [(ifel, "ifel")] $ \(op, sop) ->
withParams (map tell [Top, Once Top]) $ \gw ->
it "should format ternary subgoals" $ do
let g = astGoal gw
formatGoal (astGoal (op gw gw gw)) `shouldBe`
(sop ++ " " ++ parensGoal g ++ " " ++ parensGoal g ++ " " ++ parensGoal g)
withParams [(Top, "true"), (Bottom, "false"), (Cut, "cut")] $ \(g, sg) ->
it "should format unitary goals" $
formatGoal g `shouldBe` sg
withParams [toTerm $ v"x", Just $$ char "x"] $ \x ->
withParams [Top, Once Top] $ \g ->
withParams [toTerm $ v"xs", nil] $ \xs -> do
it "should format an Alternatives Nothing as if it were a call to findAll" $
formatGoal (astGoal $ findAll x (tell g) xs) `shouldBe`
("findAll " ++ parensTerm x ++ " " ++ parensGoal g ++ " " ++ parensTerm xs)
it "should format an Alternatives Just as if it were a call to findN" $
formatGoal (astGoal $ findN 42 x (tell g) xs) `shouldBe`
("findN 42 " ++ parensTerm x ++ " " ++ parensGoal g ++ " " ++ parensTerm xs)
describe "parensGoal" $ do
withParams [ PredGoal (predicate "foo" ()) []
, CanUnify (toTerm 'a') (toTerm 'b')
, Identical (toTerm 'a') (toTerm 'b')
, Equal (toTerm 'a') (toTerm 'b')
, LessThan (toTerm 'a') (toTerm 'b')
, And Top Bottom
, Or Top Bottom
, Once Top
, If Top Bottom Cut
, Alternatives Nothing (toTerm $ char "x") Top (toTerm $ string "xs")
, Alternatives (Just 42) (toTerm $ char "x") Top (toTerm $ string "xs")
, CutFrame Top
] $ \g ->
it "should add parentheses where necessary" $
parensGoal g `shouldBe` ("(" ++ formatGoal g ++ ")")
withParams [Top, Bottom, Cut] $ \g ->
it "should not add parentheses where they are not needed" $
parensGoal g `shouldBe` formatGoal g
describe "formatClause" $
it "should show a ClauseWriter" $ do
let runTest cw lns = let [c] = astClause (predicate "") cw
in formatClause c `shouldEqual` intercalate "\n" lns
let foo = Hspl.predicate "foo" $ match 'a'
runTest (match ()) ["match ()"]
runTest ( match () |-
foo? 'a')
["match () |-"
," foo? 'a'"
]
runTest ( match (Just $$ 'a') |-
foo? 'a')
["match (Just $$ 'a') |-"
," foo? 'a'"
]
runTest ( match () |- do
foo? 'a'
foo? 'b')
["match () |- do"
," foo? 'a'"
," foo? 'b'"
]
|
jbearer/hspl
|
test/UITest.hs
|
mit
| 11,837 | 0 | 26 | 3,221 | 4,030 | 2,085 | 1,945 | 226 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Mixcoin.Common.Crypto
( genWarrant
, verifyWarrant
, readPrivKey
)
where
import Control.Concurrent.STM
import Crypto.PubKey.HashDescr
import Crypto.PubKey.RSA
import Crypto.PubKey.RSA.PKCS15
import Crypto.Random
import Data.Aeson (ToJSON, encode)
import Data.ASN1.BinaryEncoding (DER (DER))
import Data.ASN1.Encoding (decodeASN1', encodeASN1')
import Data.ASN1.Object (ASN1Object, fromASN1, toASN1)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base64 as B64 (decode, encode)
import Data.ByteString.Char8 (pack, unpack)
import Data.ByteString.Lazy (toStrict)
import Data.Functor ((<$>))
import Mixcoin.Common.Types
import System.Directory (getHomeDirectory)
import System.IO.Unsafe (unsafePerformIO)
encode' :: ToJSON a => a -> ByteString
encode' = toStrict . encode
randGen :: TVar SystemRNG
randGen = unsafePerformIO (newTVarIO =<< cprgCreate <$> createEntropyPool)
genPrivKey :: IO MixcoinPrivKey
genPrivKey = atomically $ do
g <- readTVar randGen
let ((pub, priv), g') = generate g 128 3
writeTVar randGen g'
return priv
genWarrant :: MixcoinPrivKey -> LabeledMixRequest -> IO (Maybe String)
genWarrant pk req = atomically $ do
g <- readTVar randGen
let (res, g') = signSafer g hashDescrSHA256 pk (encode' req)
writeTVar randGen g'
return $ case res of
Left _ -> Nothing
Right sig -> Just $ (unpack . B64.encode) sig
-- handle broken sig
verifyWarrant :: MixcoinPubKey -> String -> LabeledMixRequest -> Bool
verifyWarrant pk sig req = verify hashDescrSHA256 pk (pack sig) (encode' req)
encode64 :: ASN1Object a => a -> BS.ByteString
encode64 a = B64.encode . encodeASN1' DER $ (toASN1 a) []
decode64 :: ASN1Object a => BS.ByteString -> Either String a
decode64 bs = do
dec <- B64.decode bs
asn <- case decodeASN1' DER dec of
Left _ -> Left "couldn't decode ASN1 stream"
Right r -> Right r
(ret, remaining) <- fromASN1 asn
if null remaining
then Right ret
else Left "invalid ASN1 stream"
readPrivKey :: IO (Either String MixcoinPrivKey)
readPrivKey = do
home <- (++ "/.mixcoin/mixcoin-priv.der") <$> getHomeDirectory
bs <- BS.readFile home
return $ decode64 bs
|
charlescharles/mixcoin-hs
|
src/Mixcoin/Common/Crypto.hs
|
mit
| 2,479 | 0 | 16 | 609 | 737 | 389 | 348 | 60 | 3 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.DOMStringList
(item, item_, itemUnsafe, itemUnchecked, contains, contains_,
getLength, DOMStringList(..), gTypeDOMStringList)
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/DOMStringList.item Mozilla DOMStringList.item documentation>
item ::
(MonadDOM m, FromJSString result) =>
DOMStringList -> Word -> m (Maybe result)
item self index
= liftDOM
((self ^. jsf "item" [toJSVal index]) >>= fromMaybeJSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMStringList.item Mozilla DOMStringList.item documentation>
item_ :: (MonadDOM m) => DOMStringList -> Word -> m ()
item_ self index
= liftDOM (void (self ^. jsf "item" [toJSVal index]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMStringList.item Mozilla DOMStringList.item documentation>
itemUnsafe ::
(MonadDOM m, HasCallStack, FromJSString result) =>
DOMStringList -> Word -> m result
itemUnsafe self index
= liftDOM
(((self ^. jsf "item" [toJSVal index]) >>= fromMaybeJSString) >>=
maybe (Prelude.error "Nothing to return") return)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMStringList.item Mozilla DOMStringList.item documentation>
itemUnchecked ::
(MonadDOM m, FromJSString result) =>
DOMStringList -> Word -> m result
itemUnchecked self index
= liftDOM
((self ^. jsf "item" [toJSVal index]) >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMStringList.contains Mozilla DOMStringList.contains documentation>
contains ::
(MonadDOM m, ToJSString string) =>
DOMStringList -> string -> m Bool
contains self string
= liftDOM ((self ^. jsf "contains" [toJSVal string]) >>= valToBool)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMStringList.contains Mozilla DOMStringList.contains documentation>
contains_ ::
(MonadDOM m, ToJSString string) => DOMStringList -> string -> m ()
contains_ self string
= liftDOM (void (self ^. jsf "contains" [toJSVal string]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMStringList.length Mozilla DOMStringList.length documentation>
getLength :: (MonadDOM m) => DOMStringList -> m Word
getLength self
= liftDOM (round <$> ((self ^. js "length") >>= valToNumber))
|
ghcjs/jsaddle-dom
|
src/JSDOM/Generated/DOMStringList.hs
|
mit
| 3,267 | 0 | 14 | 505 | 816 | 468 | 348 | -1 | -1 |
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.FsImageProto.SnapshotDiffSection (SnapshotDiffSection(..)) where
import Prelude ((+), (/))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data SnapshotDiffSection = SnapshotDiffSection{}
deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable SnapshotDiffSection where
mergeAppend SnapshotDiffSection SnapshotDiffSection = SnapshotDiffSection
instance P'.Default SnapshotDiffSection where
defaultValue = SnapshotDiffSection
instance P'.Wire SnapshotDiffSection where
wireSize ft' self'@(SnapshotDiffSection)
= case ft' of
10 -> calc'Size
11 -> P'.prependMessageSize calc'Size
_ -> P'.wireSizeErr ft' self'
where
calc'Size = 0
wirePut ft' self'@(SnapshotDiffSection)
= case ft' of
10 -> put'Fields
11 -> do
P'.putSize (P'.wireSize 10 self')
put'Fields
_ -> P'.wirePutErr ft' self'
where
put'Fields
= do
Prelude'.return ()
wireGet ft'
= case ft' of
10 -> P'.getBareMessageWith update'Self
11 -> P'.getMessageWith update'Self
_ -> P'.wireGetErr ft'
where
update'Self wire'Tag old'Self
= case wire'Tag of
_ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
instance P'.MessageAPI msg' (msg' -> SnapshotDiffSection) SnapshotDiffSection where
getVal m' f' = f' m'
instance P'.GPB SnapshotDiffSection
instance P'.ReflectDescriptor SnapshotDiffSection where
getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList [])
reflectDescriptorInfo _
= Prelude'.read
"DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.hdfs.fsimage.SnapshotDiffSection\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"FsImageProto\"], baseName = MName \"SnapshotDiffSection\"}, descFilePath = [\"Hadoop\",\"Protos\",\"FsImageProto\",\"SnapshotDiffSection.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
instance P'.TextType SnapshotDiffSection where
tellT = P'.tellSubMessage
getT = P'.getSubMessage
instance P'.TextMsg SnapshotDiffSection where
textPut msg = Prelude'.return ()
textGet = Prelude'.return P'.defaultValue
|
alexbiehl/hoop
|
hadoop-protos/src/Hadoop/Protos/FsImageProto/SnapshotDiffSection.hs
|
mit
| 2,775 | 1 | 16 | 529 | 554 | 291 | 263 | 53 | 0 |
import System.Environment
getCounts :: String -> (Int, Int, Int)
getCounts input = (charCount, wordCount, lineCount)
where charCount = length input
wordCount = (length . words) input
lineCount = (length . lines) input
countsText :: (Int, Int, Int) -> String
countsText (cc, wc, lc) = unwords [ "chars:"
, show cc
, "words:"
, show wc
, "lines:"
, show lc
]
-- Cool note about readFile.
-- It does not close file descriptor.
-- Yeap, sounds scary and stupid, but
-- if you think about your IO being lazy
-- you might guess that if you perform
-- close file descriptor IO action right in read file
-- it MIGHT BE CLOSED BEFORE YOU'VE READ THE CONTENT OF A FILE!
-- Lazy! Make me crazy!
-- Yeap, you have to force Haskell to read the content
-- of file. it happens in the end of main.
main :: IO ()
main = do
args <- getArgs
let fileName = head args
input <- readFile fileName
let summary = (countsText . getCounts) input
appendFile "stats.dat" (mconcat [fileName, " ", summary, "\n"])
|
raventid/coursera_learning
|
haskell/will_kurt/24.5_calculate_stats.hs
|
mit
| 1,220 | 0 | 12 | 417 | 245 | 135 | 110 | 20 | 1 |
module Day11 (p1, p2) where
import Control.Arrow
import Control.Monad
import Data.Char
import Data.List
import qualified Data.Map as M
import Data.Map ((!))
import qualified Data.Set as S
input = "vzbxkghb"
test1 = "abcdefgh"
test2 = "ghijklmn"
test2' = "ghizzzzz"
naughyChars = S.fromList ['i', 'o', 'l']
hasNaughty s = or $ map (`S.member` naughyChars) s
inc :: String -> String
inc = reverse . incLst . reverse
where incLst [] = []
incLst (c : cs) = case incLetter c of
'a' -> 'a' : incLst cs
d | d `S.member` naughyChars -> incLst (d : cs)
d -> d : cs
incLetter 'z' = 'a'
incLetter c = chr . succ $ ord c
hasStraight (a:rs@(b:c:_))
| ((succ . succ $ ord a) == ord c) && ((succ $ ord b) == ord c) = True
| otherwise = hasStraight rs
hasStraight _ = False
hasPair (a:rs@(b: rss))
| a == b = True
| otherwise = hasPair rs
hasPair _ = False
has2pair (a:rs@(b: rss))
| a == b = hasPair rss
| otherwise = has2pair rs
has2pair _ = False
isNice :: String -> Bool
isNice s = and $ map ($ s) [hasStraight,
not . hasNaughty,
has2pair]
p1 = head . filter isNice . tail $ iterate inc input
p2 = (!! 1) . filter isNice . tail $ iterate inc input
|
farrellm/advent
|
src/Day11.hs
|
mit
| 1,272 | 0 | 13 | 360 | 575 | 303 | 272 | 41 | 5 |
module Main where
import Monad
import System.Environment
import Text.ParserCombinators.Parsec hiding (spaces)
main :: IO ()
main = do args <- getArgs
putStrLn (readExpr (args !! 0))
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=>?@^_~#"
readExpr input = case parse parseExpr "lisp" input of
Left err -> "No match: " ++ show err
Right val -> "Found " ++ show val
spaces :: Parser ()
spaces = skipMany1 space
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| String String
| Bool Bool
parseString :: Parser LispVal
parseString = do char '"'
x <- many (noneOf "\"")
char '"'
return $ String x
parseAtom :: Parser LispVal
parseAtom = do first <- letter <|> symbol
rest <- many (letter <|> digit <|> symbol)
let atom = [first] ++ rest
return $ case atom of
"#t" -> Bool True
"#f" -> Bool False
otherwise -> Atom atom
parseNumber :: Parser LispVal
parseNumber = liftM (Number . read) $ many1 digit
parseList :: Parser LispVal
parseList = liftM List $ sepBy parseExpr spaces
parseDottedList :: Parser LispVal
parseDottedList = do
head <- endBy parseExpr spaces
tail <- char '.' >> spaces >> parseExpr
return $ DottedList head tail
parseQuoted :: Parser LispVal
parseQuoted = do
char '\''
x <- parseExpr
return $ List [Atom "quote", x]
parseExpr :: Parser LispVal
parseExpr = parseAtom
<|> parseString
<|> parseNumber
<|> parseQuoted
<|> do char '('
x <- (try parseList) <|> parseDottedList
char ')'
return x
showVal :: LispVal -> String
showVal (String contents) = "\"" ++ contents ++ "\""
showVal (Atom name) = name
showVal (Number contents) = show contents
showVal (Bool True) = "#t"
showVal (Bool False) = "#f"
showVal (List contents) = "(" ++ unwordsList contents ++ ")"
showVal (DottedList head tail) = "(" ++ unwordsList head ++ " . " ++ showVal tail ++ ")"
unwordsList :: [LispVal] -> String
unwordsList = unwords . map showVal
instance Show LispVal where show = showVal
|
tismith/tlisp
|
write-yourself-a-scheme/listings/listing4.1.hs
|
mit
| 2,294 | 0 | 11 | 703 | 751 | 367 | 384 | 67 | 3 |
module Logix.Tokenizer where
import Text.Regex.Posix
import Data.Char
import qualified Data.Map as Map
import Data.Maybe
import Data.Either
import Logix.Utils
data Keyword = Check | Axiom | Theorem deriving (Show, Eq, Enum)
data Tactic = Qed | Mp deriving (Show, Eq, Enum)
data Syntactic = Of | Curry | LP | RP | Comma | Neg | Ax deriving (Show, Eq, Enum)
data Token = TkKey Keyword
| TkTac Tactic
| TkSyn Syntactic
| TkIdent String
deriving (Show, Eq)
transformToMap l f = Map.fromList $ map f l
keywords = transformToMap [Check ..] (\k -> (show k, k))
tactics = transformToMap [Qed ..] (\t -> ((\s -> (toLower $ head s) : tail s) (show t), t))
symbols = Map.fromList [('(', TkSyn LP), (')', TkSyn RP), (',', TkSyn Comma), ('!', TkSyn Neg), (':', TkSyn Of)]
type MapTk = Map.Map String Token
tokenize :: String -> EitherS [Token]
tokenize "" = Right []
tokenize str@(c:cs)
| Map.member c symbols = do
let (Just tk) = Map.lookup c symbols
tks <- tokenize cs
return (tk : tks)
| isSpace c = tokenize cs
| isAlpha c = matchAlpha str
| c == '-' = matchSlash str
| c == '|' = matchBar str
| otherwise = Left $ "[tokenize] error tokenizing " ++ show str
matchHead :: (Char -> Bool) -> (String -> EitherS Token) -> String -> EitherS [Token]
matchHead f g str
| word == "" = do
tk <- g rest
return [tk]
| otherwise = do
restTks <- tokenize rest
tk <- g word
return (tk : restTks)
where
(word, rest) = span f str
matchAlpha :: String -> EitherS [Token]
matchAlpha "" = return []
matchAlpha str = matchHead (\c -> isAlpha c || c `elem` "\'_" || isDigit c) matchAlpha' str
matchSlash :: String -> EitherS [Token]
matchSlash = matchHead (\c -> c `elem` "->") matchSlash'
matchBar :: String -> EitherS [Token]
matchBar "" = return []
matchBar str
| length str < 3 = Left $ "No such bar " ++ str
| str !! 1 == '-' = do
tks <- tokenize (drop 2 str)
return $ TkSyn Ax : tks
matchAlpha' :: String -> EitherS Token
matchAlpha' word
| isMember keywords = return (TkKey $ getFrom keywords)
| isMember tactics = return (TkTac $ getFrom tactics)
| otherwise = return (TkIdent word)
where
isMember = Map.member word
getFrom kv = fromJust $ Map.lookup word kv
matchSlash' :: String -> EitherS Token
matchSlash' operator
| operator == "->" = return (TkSyn Curry)
| otherwise = Left $ "No such slash word" ++ operator
|
izgzhen/logix
|
Logix/Tokenizer.hs
|
mit
| 2,526 | 0 | 15 | 660 | 1,082 | 546 | 536 | 65 | 1 |
--If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
--Find the sum of all the multiples of 3 or 5 below 1000.
sum1 c 0 s = s
sum1 c max s = if ((c `mod` 3 == 0) || (c `mod` 5 == 0 ))
then sum1 (c+1) (max-1) (s+c)
else sum1 (c+1) (max-1) (s)
|
stefan-j/ProjectEuler
|
q1.hs
|
mit
| 340 | 6 | 10 | 96 | 126 | 70 | 56 | 4 | 2 |
module IRC (
module IRC.Types
) where
import IRC.Types
import IRC.Commands
|
EXio4/ircah
|
src/IRC.hs
|
mit
| 79 | 0 | 5 | 15 | 22 | 14 | 8 | 4 | 0 |
module Sat
( S -- :: * -> *; Functor, Monad
, Lit -- :: *; Eq, Ord, Show
, Arg(..) -- :: *
, Atm(..) -- :: *
, run -- :: S a -> IO a
, okay -- :: S Bool
, lift -- :: IO a -> S a
, contradiction -- :: S ()
, newLit -- :: S Lit
, neg -- :: Lit -> Lit
, getValue -- :: Lit -> S (Maybe Bool)
, getModelValue -- :: Lit -> S Bool -- use only after model has been found!
, addClause -- :: [Lit] -> S Bool
, solve -- :: [Lit] -> S Bool
, simplify -- :: Bool -> Bool -> S Bool
, verbose -- :: Int -> S Bool
, newLoc -- :: Int -> S Loc
, getLit -- :: Signed Atm -> S Lit
, addClauses -- :: [Int] -> [Signed Atm] -> S ()
-- for debugging
--, printStderr -- :: String -> IO ()
)
where
{-
Paradox/Equinox -- Copyright (c) 2003-2007, Koen Claessen, Niklas Sorensson
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.
-}
import Foreign.C.Types ( CInt )
import Foreign.C.String ( CString, withCString )
import Foreign.Ptr ( Ptr, FunPtr, nullPtr )
import Foreign.ForeignPtr ( ForeignPtr, newForeignPtr, withForeignPtr )
import Foreign.Storable ( peek )
import Foreign.Marshal.Array ( withArray0, peekArray0 )
import Foreign.Marshal.Alloc ( alloca )
import System.IO ( FilePath )
import Foreign.Storable ( Storable )
import Control.Exception ( finally )
import Form ( Signed(..), the, sign )
newLoc :: Int -> S Loc
newLoc p = lift $ do
ptr <- loc_new (fromIntegral p)
fptr <- newForeignPtr loc_free ptr
return (Loc fptr)
addClauses :: Maybe Int -> [Int] -> [Signed Atm] -> S ()
addClauses mn d ls = MiniSatM (\s -> addClauses_ mn d ls s)
addClauses_ mn d ls s =
do solver_clause_begin s
mapM_ (signed addLit) ls
mapM_ (solver_clause_add_size s . fromIntegral) d
solver_clause_commit s (fromIntegral (maybe 0 (subtract 1) mn))
where addArg (ArgN i) = solver_clause_add_lit_con s (fromIntegral i)
addArg (ArgV i) = solver_clause_add_lit_var s (fromIntegral i)
addLit (Loc l :@ args) b = do
withForeignPtr l (flip (solver_clause_add_lit s) (toCBool b))
mapM_ addArg args
signed f x = f (the x) (sign x)
getLit :: Signed Atm -> S Lit
getLit atom = MiniSatM $ \s -> do
withForeignPtr l (flip (solver_lit_begin s) (toCBool (sign atom)))
mapM_ (solver_lit_add_con s) [ fromIntegral d | ArgN d <- args ]
solver_lit_read s
where (Loc l :@ args) = the atom
----------------------------------------------------------------------------------
-- Monad
newtype Solver = Solver (Ptr ())
newtype S a = MiniSatM (Solver -> IO a)
instance Monad S where
return x =
MiniSatM (const (return x))
MiniSatM f >>= g =
MiniSatM (\s -> f s >>= \x -> case g x of { MiniSatM m -> m s })
instance Functor S where
fmap f (MiniSatM g) = MiniSatM (fmap f . g)
----------------------------------------------------------------------------------------------------
-- types
newtype Lit
= Lit CInt
deriving (Eq, Num, Ord, Storable)
newtype Loc = Loc (ForeignPtr ())
deriving ( Eq, Show )
data Arg
= ArgV Int
| ArgN Int
deriving ( Eq, Show )
data Atm
= Loc :@ [Arg]
deriving ( Eq, Show )
neg :: Lit -> Lit
neg x = -x
instance Show Lit where
showsPrec i (Lit l) = showsPrec i l
instance Read Lit where
readsPrec i = map (\ (x,r) -> (Lit x, r)) . readsPrec i
mkTrue = Lit 1
mkFalse = -mkTrue
----------------------------------------------------------------------------------------------------
-- MiniSatM functions
lower :: S a -> Solver -> IO a
lower (MiniSatM f) = f
withSolverLog :: FilePath -> (Solver -> IO a) -> IO a
withSolverLog log f = withCString log (flip withSolverPrim f)
withSolver :: (Solver -> IO a) -> IO a
withSolver = withSolverPrim nullPtr
withSolverPrim :: CString -> (Solver -> IO a) -> IO a
withSolverPrim log f =
do s <- s_new log
r <- f s `finally` s_delete s
return r
run :: S a -> IO a
run m = withSolver (lower (simplify False True >> m)) -- no simplification
--run m = withSolver (lower m)
--run m = withSolverLog "minisat-log" (lower m)
{-
mkLit :: m Lit
clause :: [Lit] -> m Bool
solve :: [Lit] -> m Bool
solve_ :: Bool -> [Lit] -> m Bool
modelValue :: Lit -> m Bool
value :: Lit -> m (Maybe Bool)
contr :: m [Lit]
okay :: m Bool
-- for convenience
lift :: IO a -> m a
-- default *with* simplification
solve = solve_ True
freezeLit :: Lit -> m ()
unfreezeLit :: Lit -> m ()
simplify :: Bool -> Bool -> m Bool
freezeLit l = return ()
unfreezeLit l = return ()
simplify x y = return True
-- formula creation (with simple defaults)
mkAnd :: Lit -> Lit -> m Lit
mkAnd = defAnd
mkOr :: Lit -> Lit -> m Lit
mkOr x y = mkAnd (-x) (-y) >>= return . negate
mkEqu :: Lit -> Lit -> m Lit
mkEqu = defEqu
mkXor :: Lit -> Lit -> m Lit
mkXor x y = mkEqu (-x) (-y) >>= return . negate
mkIte :: Lit -> Lit -> Lit -> m Lit
mkIte = defIte
mkAdd :: Lit -> Lit -> Lit -> m (Lit, Lit)
mkAdd = defAdd
-}
--printStderr :: String -> IO ()
--printStderr s = withCString s solver_print_stderr
solve = solve_ True
newLit = MiniSatM s_newlit
addClause ls =
do --lift $ putStrLn ("Sat.addClause: " ++ show ls)
fmap fromCBool $ MiniSatM (withArray0 (Lit 0) ls . s_clause)
solve_ b ls = fmap fromCBool $ MiniSatM (withArray0 (Lit 0) ls . flip s_solve (toCBool b))
freezeLit l = MiniSatM (\s -> s_freezelit s l)
unfreezeLit l = MiniSatM (\s -> s_unfreezelit s l)
getModelValue l = fmap fromCBool $ MiniSatM (flip s_modelvalue l)
getValue l = fmap fromLBool $ MiniSatM (flip s_value l)
reason = MiniSatM (\s -> s_contr s >>= peekArray0 (Lit 0))
contradiction = addClause [] >> return ()
okay = fmap fromCBool $ MiniSatM s_okay
simplify elim turnoffelim = fmap fromCBool $ MiniSatM (\s -> s_simplify s (toCBool elim) (toCBool turnoffelim))
lift f = MiniSatM (const f)
mkAnd x y = MiniSatM (\s -> s_and s x y)
mkOr x y = MiniSatM (\s -> s_or s x y)
mkEqu x y = MiniSatM (\s -> s_equ s x y)
mkXor x y = MiniSatM (\s -> s_xor s x y)
mkIte x y z = MiniSatM (\s -> s_ite s x y z)
mkAdd x y z = MiniSatM $ \s ->
alloca $ \cp ->
alloca $ \sp ->
do s_add s x y z cp sp
c <- peek cp
s <- peek sp
return (c,s)
verbose n = MiniSatM (\s -> s_verbose s (fromIntegral n))
nVars, nClauses, nConflicts, nRemembered :: S Int
nVars = fmap fromIntegral $ MiniSatM s_nvars
nClauses = fmap fromIntegral $ MiniSatM s_nclauses
nConflicts = fmap fromIntegral $ MiniSatM s_nconflicts
nRemembered = fmap fromIntegral $ MiniSatM s_nremembered
----------------------------------------------------------------------------------------------------
-- helpers
fromCBool :: CInt -> Bool
fromCBool 0 = False
fromCBool _ = True
-- should import the correct constants really
fromLBool :: CInt -> Maybe Bool
fromLBool 0 = Nothing
fromLBool 1 = Just True
fromLBool (-1) = Just False
toCBool :: Bool -> CInt
toCBool True = 1
toCBool False = 0
----------------------------------------------------------------------------------------------------
-- foreign imports
foreign import ccall unsafe "static Wrapper.h" s_new :: CString -> IO Solver
foreign import ccall unsafe "static Wrapper.h" s_delete :: Solver -> IO ()
foreign import ccall unsafe "static Wrapper.h" s_newlit :: Solver -> IO Lit
foreign import ccall unsafe "static Wrapper.h" s_clause :: Solver -> Ptr Lit -> IO CInt
foreign import ccall unsafe "static Wrapper.h" s_solve :: Solver -> CInt -> Ptr Lit -> IO CInt
foreign import ccall unsafe "static Wrapper.h" s_simplify :: Solver -> CInt -> CInt -> IO CInt
foreign import ccall unsafe "static Wrapper.h" s_freezelit :: Solver -> Lit -> IO ()
foreign import ccall unsafe "static Wrapper.h" s_unfreezelit :: Solver -> Lit -> IO ()
foreign import ccall unsafe "static Wrapper.h" s_setpolarity :: Solver -> Lit -> IO ()
foreign import ccall unsafe "static Wrapper.h" s_setdecisionvar :: Solver -> Lit -> CInt -> IO ()
foreign import ccall unsafe "static Wrapper.h" s_value :: Solver -> Lit -> IO CInt
foreign import ccall unsafe "static Wrapper.h" s_and :: Solver -> Lit -> Lit -> IO Lit
foreign import ccall unsafe "static Wrapper.h" s_or :: Solver -> Lit -> Lit -> IO Lit
foreign import ccall unsafe "static Wrapper.h" s_equ :: Solver -> Lit -> Lit -> IO Lit
foreign import ccall unsafe "static Wrapper.h" s_xor :: Solver -> Lit -> Lit -> IO Lit
foreign import ccall unsafe "static Wrapper.h" s_ite :: Solver -> Lit -> Lit -> Lit -> IO Lit
foreign import ccall unsafe "static Wrapper.h" s_add :: Solver -> Lit -> Lit -> Lit -> Ptr Lit -> Ptr Lit -> IO ()
foreign import ccall unsafe "static Wrapper.h" s_modelvalue :: Solver -> Lit -> IO CInt
foreign import ccall unsafe "static Wrapper.h" s_contr :: Solver -> IO (Ptr Lit)
foreign import ccall unsafe "static Wrapper.h" s_verbose :: Solver -> CInt -> IO ()
foreign import ccall unsafe "static Wrapper.h" s_okay :: Solver -> IO CInt
foreign import ccall unsafe "static Wrapper.h" s_nvars :: Solver -> IO CInt
foreign import ccall unsafe "static Wrapper.h" s_nclauses :: Solver -> IO CInt
foreign import ccall unsafe "static Wrapper.h" s_nconflicts :: Solver -> IO CInt
foreign import ccall unsafe "static Wrapper.h" s_nremembered :: Solver -> IO CInt
foreign import ccall unsafe "static Wrapper.h" loc_new :: CInt -> IO (Ptr ())
foreign import ccall unsafe "static Wrapper.h &loc_free" loc_free :: FunPtr ((Ptr ()) -> IO ())
foreign import ccall unsafe "static Wrapper.h" loc_arity :: (Ptr ()) -> IO CInt
foreign import ccall unsafe "static Wrapper.h" solver_clause_begin :: Solver -> IO ()
foreign import ccall unsafe "static Wrapper.h" solver_clause_add_lit :: Solver -> (Ptr ()) -> CInt -> IO ()
foreign import ccall unsafe "static Wrapper.h" solver_clause_add_lit_var :: Solver -> CInt -> IO ()
foreign import ccall unsafe "static Wrapper.h" solver_clause_add_lit_con :: Solver -> CInt -> IO ()
foreign import ccall unsafe "static Wrapper.h" solver_clause_add_size :: Solver -> CInt -> IO ()
foreign import ccall unsafe "static Wrapper.h" solver_clause_commit :: Solver -> CInt -> IO ()
foreign import ccall unsafe "static Wrapper.h" solver_lit_begin :: Solver -> (Ptr ()) -> CInt -> IO ()
foreign import ccall unsafe "static Wrapper.h" solver_lit_add_con :: Solver -> CInt -> IO ()
foreign import ccall unsafe "static Wrapper.h" solver_lit_read :: Solver -> IO Lit
--foreign import ccall unsafe "static Wrapper.h" solver_print_stderr :: CString -> IO ()
|
msakai/folkung
|
Haskell/Sat.hs
|
mit
| 12,100 | 1 | 15 | 3,039 | 3,118 | 1,609 | 1,509 | 177 | 2 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Algebra.Suspension where
data Suspension a b = Suspension (a -> b) a
suspend = Suspension
release :: Suspension a b -> b
release (Suspension f a) = f a
|
sgord512/Algebra
|
Algebra/Suspension.hs
|
mit
| 201 | 0 | 8 | 37 | 65 | 36 | 29 | 6 | 1 |
{--
-- Natume -- an implementation of Kana-Kanji conversion in Haskell
-- Copyright (C) 2006-2012 Takayuki Usui
--
-- 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 St, Fifth Floor, Boston, MA 02110-1301 USA
--}
module Con (
Con,connect_init,connect_search,connect_free
) where
import Prelude hiding (id,last)
import Foreign.C.String
import Foreign.C.Types
import Foreign
import qualified Lib
import Lib (castInt,cint,call)
type Con = (Int,(Ptr CInt),(Ptr CInt))
width :: Int
width = 32
connect_init :: String -> String -> IO Con
connect_init idx dat =
do cidx <- newCString idx
cdat <- newCString dat
id <- call (Lib.connect_init cidx cdat)
if id == -1
then error "unable to initialize external library"
else return ()
status <- call (Lib.connect_load (cint id))
if status == -1
then error ("unable to load connection rule: " ++
idx ++ "," ++ dat)
else return ()
rule <- mallocArray width
cost <- malloc
free cdat
free cidx
return (id,rule,cost)
fetch1 :: Con -> Int -> Int -> IO [([Int],Int)]
fetch1 con i n =
let (id,rule,cost) = con in
if i < n
then do num <- call (Lib.connect_fetch (cint id) (cint i) rule
(cint width) cost)
r <- peekArray num rule
c <- peek cost
fs <- fetch1 con (i+1) n
return ((map castInt r,castInt c):fs)
else return []
connect_search :: Con -> [Int] -> IO [([Int],Int)]
connect_search con key = let (id,_,_) = con in
do rule <- newArray (map castInt key)
num <- call (Lib.connect_search (cint id) rule
(cint (length key)))
ret <- fetch1 con 0 num
free rule
return ret
connect_free :: Con -> IO ()
connect_free con = let (id,rule,cost) = con in
do free rule
free cost
Lib.connect_unload (cint id)
Lib.connect_free (cint id)
return ()
|
takayuki/natume
|
Con.hs
|
gpl-2.0
| 2,801 | 0 | 16 | 913 | 733 | 366 | 367 | 55 | 3 |
module HW08 where
import System.Random
import Control.Monad.Random
import Data.Monoid
import Data.List
import Control.Monad
-- import Control.Monad.Random.Class
{-
Exercise 1 failed on me:
import Data.List
import Data.Char
import Data.Maybe
stringFitsFormat :: String -> Bool
stringFitsFormat = isJust . go
where go :: String -> Maybe String
go [] = Nothing
go (x:xs)
| isLetter x = Nothing
| otherwise = let l = length $
takeWhile isLetter (dropWhile isDigit (x:xs))
in if l == (digitToInt x) then Just "" else Nothing
-}
specialNumbers :: [Int]
specialNumbers = [ x | x <- [1..100], mod x 5 == 0, mod x 7 /= 0 ]
type StdRand = Rand StdGen
type Army = Int
type DieRoll = Int
data ArmyCounts = ArmyCounts { attackers :: Army, defenders :: Army } deriving Show
instance Monoid ArmyCounts where
mempty = ArmyCounts 0 0
ArmyCounts fAttack fDef `mappend` ArmyCounts sAttack sDef =
ArmyCounts (fAttack + sAttack) (fDef + sDef)
dieRoll :: StdRand DieRoll
dieRoll = getRandomR (1,6)
dec :: DieRoll -> DieRoll -> ArmyCounts
dec a d
| a > d = ArmyCounts 0 (-1)
| otherwise = ArmyCounts (-1) 0
battleResults :: [DieRoll] -> [DieRoll] -> ArmyCounts
battleResults [] [] = mempty
battleResults _ [] = mempty
battleResults [] _ = mempty
battleResults att def =
let rSort = reverse.sort
(x:xs) = rSort att
(y:ys) = rSort def
in dec x y `mappend` battleResults xs ys
-- Exercise 4
{-
failed battle
battle :: ArmyCounts -> ArmyCounts
battle (ArmyCounts att def) =
let mapEval = map evalRandIO
attL = mapEval $ replicate att dieRoll
defL = mapEval $ replicate def dieRoll
in (battleResults attL defL) `mappend` ArmyCounts att def
-}
battle :: ArmyCounts -> StdRand ArmyCounts
battle (ArmyCounts att def) =
let attList = tr $ dice $ min att 3
defList = tr $ dice $ min def 2
in liftM2 battleResults attList defList
invade :: ArmyCounts -> StdRand ArmyCounts
invade (ArmyCounts att def)
| def > 0 =
dice :: Int -> [StdRand DieRoll]
dice n = replicate n dieRoll
tr :: [StdRand DieRoll] -> StdRand [DieRoll]
tr = sequence
extractRoll :: [StdRand DieRoll] -> IO [DieRoll]
extractRoll = sequence . map evalRandIO
bR :: IO [DieRoll] -> IO [DieRoll] -> IO ArmyCounts
bR fstt secc = do
f <- fstt
s <- secc
let x = battleResults f s
return x
{-
Rewriting bR better yet use liftM2
do
x <- fstt
y <- secc
return (battleResults x y)
-- eliminating the 1st assignment
fstt >>= (\x -> do
y <- secc
return (battleResults x y))
-- eliminating the 2nd assignment
fstt >>= (\x -> secc >>= (\y -> return (battleResults x y)))
-- or without excessive parens
fstt >>= \x -> secc >>= \y -> return (battleResults x y)
-- eliminating “y”
fstt >>= \x -> secc >>= return . battleResults x
-}
ch :: IO [DieRoll] -> IO [DieRoll] -> IO ArmyCounts
ch fstt secc = secc >>= (\y -> fstt >>= (return . battleResults y))
battleF :: ArmyCounts -> IO ArmyCounts
battleF (ArmyCounts att def) =
let z = extractRoll . dice
in ch (z att) (z def)
|
urbanslug/cs194
|
Src/Week8/HW08.hs
|
gpl-3.0
| 3,111 | 0 | 11 | 741 | 803 | 412 | 391 | -1 | -1 |
{-
Module : Tubes.Channel
Description : Defines the Channel type.
Copyright : (c) 2014-2016 Gatlin Johnson <[email protected]>
License : GPL-3
Maintainer : [email protected]
Stability : experimental
-}
module Tubes.Channel
(
Channel(..)
, tee
)
where
import Prelude hiding (map, (.), id)
import qualified Prelude as P
import Data.Profunctor
import Data.Functor.Identity
import Control.Monad.Trans.Class
import Control.Category
import Control.Arrow
import Control.Monad (forever)
import Control.Monad.Trans.Free
import Tubes.Core
import Tubes.Util
import Tubes.Sink
{- |
A @Channel m a b@ is a stream processor which converts values of type @a@ into
values of type @b@, while also performing side-effects in some monad @m@.
If a @Channel@ 'yield's exactly once after each time it 'await's then it may be
safely treated as an @Arrow@. For example:
@
{-\# LANGUAGE Arrows \#-}
import Tubes
import Control.Arrow
import Prelude hiding (map)
-- A simple channel which accumulates a total
total :: (Num a, Monad m) => Channel m a a
total = Channel $ loop 0 where
loop acc = do
n <- await
let acc' = n + acc
yield acc'
loop acc'
-- A running average using two totals in parallel
avg :: (Fractional a, Monad m) => Channel m a a
avg = proc value -> do
t <- total -< value
n <- total -< 1
returnA -< t / n
main :: IO ()
main = runTube $ each [0,10,7,8]
>< tune avg
>< map show
>< pour display
@
This program would output
@
0.0
5.0
5.666666666666667
6.25
@
This has interesting potential in FRP applications.
-}
newtype Channel m a b = Channel {
tune :: Tube a b m ()
}
instance Monad m => Profunctor (Channel m) where
lmap f ch = Channel $ map f >< tune ch
rmap f ch = Channel $ tune ch >< map f
instance Monad m => Category (Channel m) where
id = Channel cat
c_bc . c_ab = Channel $ forever (tune c_ab) >< forever (tune c_bc)
instance Monad m => Functor (Channel m a) where
fmap = rmap
instance Monad m => Applicative (Channel m a) where
pure x = Channel $ await >>= \_ -> yield x
ch1 <*> ch2 = ch1 &&& ch2 >>> arr (\(f,x) -> f x)
-- Not sure how useful this is but whatever
instance Monad m => Monad (Channel m a) where
return = pure
ma >>= f = _join (fmap f ma) where
_join (Channel tb) = Channel $ loop tb
loop tb = do
a <- await
mChB <- lift $ pass a tb
case mChB of
Nothing -> halt
Just ((Channel tbB), tb') -> do
mB <- lift $ pass a tbB
case mB of
Nothing -> halt
Just (b, _) -> do
yield b
loop tb'
instance (Monad m) => Arrow (Channel m) where
arr f = Channel $ map f
first ch = Channel $ loop (tune ch) where
loop tb = do
~(b,d) <- await
mr <- lift $ pass b tb
maybe halt (\(c,k) -> (yield (c,d)) >> loop k) mr
second ch = Channel $ loop (tune ch) where
loop tb = do
~(d,b) <- await
mr <- lift $ pass b tb
maybe halt (\(c,k) -> (yield (d, c)) >> loop k) mr
instance (Monad m) => ArrowChoice (Channel m) where
(Channel tb1) +++ (Channel tb2) = Channel $ loop tb1 tb2 where
loop t1 t2 = await >>=
either
(\l -> (lift $ pass l t1) >>=
maybe halt (\(out, t1') ->
(yield $ Left out) >> loop t1' t2))
(\r -> (lift $ pass r t2) >>=
maybe halt (\(out, t2') ->
(yield $ Right out) >> loop t1 t2'))
left (Channel tb) = Channel $ loop tb where
loop tb = await >>=
either
(\v -> (lift $ pass v tb) >>=
maybe halt (\(out, tb') ->
(yield $ Left out) >> loop tb'))
(\v -> (yield $ Right v) >> loop tb)
right (Channel tb) = Channel $ loop tb where
loop tb = await >>=
either
(\v -> (yield $ Left v) >> loop tb)
(\v -> (lift $ pass v tb) >>=
maybe halt (\(out, tb') ->
(yield $ Right out) >> loop tb'))
{- |
Convert a 'Sink m a' into a 'Channel m a a', re-forwarding values downstream.
Useful example:
@
import Data.Semigroup
writeToFile :: Sink IO String
writeToFile = Sink $ do
line <- await
liftIO . putStrLn $ "Totally writing this to a file: " ++ line
writeToConsole :: Sink IO String
writeToConsole = Sink $ do
line <- await
liftIO . putStrLn $ "Console out: " ++ line
writeOut :: Channel IO String String
writeOut = tee $ writeToFile <> writeToConsole
main :: IO ()
main = runTube $ each ["a","b","c"] \>\< forever (tune writeOut) \>\< pour display
-- Totally writing this to a file: a
-- Console out: a
-- a
-- Totally writing this to a file: b
-- Console out: b
-- b
-- Totally writing this to a file: c
-- Console out: c
-- c
@
This takes advantage of the divisible nature of 'Sink's to merge effectful
computations and then continue the process.
-}
tee
:: Monad m
=> Sink m a
-> Channel m a a
tee (Sink tube) = Channel $ forever $ do
a <- await
liftT $ yield a >< tube
yield a
|
gatlin/tubes
|
Tubes/Channel.hs
|
gpl-3.0
| 5,594 | 0 | 20 | 2,006 | 1,348 | 688 | 660 | 89 | 1 |
-- -*-haskell-*-
-- Vision (for the Voice): an XMMS2 client.
--
-- Author: Oleg Belozeorov
-- Created: 21 Sep. 2010
--
-- Copyright (C) 2009-2010 Oleg Belozeorov
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License as
-- published by the Free Software Foundation; either version 3 of
-- the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- General Public License for more details.
--
module Location.PathComp
( PathComp
, makePathComp
, pathComp
, updatePathComp
, clearPathComp
) where
import Control.Monad
import Control.Monad.Trans
import Data.IORef
import System.FilePath
import Graphics.UI.Gtk
import XMMS2.Client
import XMMS
import Utils
data PathComp
= PathComp
{ pathComp :: EntryCompletion
, pStore :: ListStore String
, pURL :: IORef String
}
makePathComp = do
comp <- entryCompletionNew
store <- listStoreNewDND [] Nothing Nothing
url <- newIORef ""
entryCompletionSetModel comp $ Just store
entryCompletionSetTextModel comp store
entryCompletionSetPopupCompletion comp True
entryCompletionSetPopupSingleMatch comp False
entryCompletionSetInlineCompletion comp True
return PathComp { pathComp = comp
, pStore = store
, pURL = url
}
updatePathComp pc url = do
let (hd, _) = splitFileName url
old <- readIORef $ pURL pc
unless (old == hd) $ do
writeIORef (pURL pc) hd
xformMediaBrowse xmms hd >>* do
flip catchXMMS_ (return ()) $ do
r <- result
liftIO $ do
listStoreClear $ pStore pc
forM_ r $ \e ->
when (entryIsDir e) $ do
listStoreAppend (pStore pc) . decodeURL $ entryPath e
return ()
entryCompletionInsertPrefix $ pathComp pc
entryCompletionComplete $ pathComp pc
clearPathComp pc = do
listStoreClear $ pStore pc
writeIORef (pURL pc) ""
|
upwawet/vision
|
src/Location/PathComp.hs
|
gpl-3.0
| 2,200 | 0 | 28 | 569 | 461 | 230 | 231 | 50 | 1 |
module QFeldspar.Singleton where
-- import QFeldspar.MyPrelude
import Prelude hiding (sin)
import QFeldspar.ErrorMonad
import Unsafe.Coerce
import qualified QFeldspar.Nat.ADT as NA
class HasSin tf t where
sin :: tf t
-- type family Trm (t :: k) :: *
-- type family RevTrm (t :: *) :: k
data Eql :: k -> k -> * where
Rfl :: Eql a a
class EqlSin tf where
eqlSin :: tf t -> tf t' -> ErrM (Eql t t')
data PrfHasSin :: (k -> *) -> k -> * where
PrfHasSin :: HasSin tf t => PrfHasSin tf t
class GetPrfHasSin tf where
getPrfHasSin :: tf t -> PrfHasSin tf t
getPrfHasSinM :: (GetPrfHasSin tf, Monad m) =>
tf t -> m (PrfHasSin tf t)
getPrfHasSinM = return . getPrfHasSin
sinTyp :: HasSin tf t => ef t -> tf t
sinTyp _ = sin
sinTypOf :: HasSin tf t => ef t -> tf t' -> tf t
sinTypOf _ _ = sin
samTyp :: tf t -> ef t -> ef t
samTyp _ = id
samTypM :: tf t -> m(ef t) -> m(ef t)
samTypM _ = id
data T t = T
type family Len (l :: [k]) :: NA.Nat where
Len (x ': xs) = 'NA.Suc (Len xs)
Len '[] = 'NA.Zro
type family Add (ll :: [k]) (lr :: [k]) :: [k] where
Add '[] lr = lr
Add (x ': xs) lr = x ': Add xs lr
type a :~: b = Eql a b
obvious :: a :~: b
obvious = unsafeCoerce Rfl
-- Type-level Lookup
type family Lookup (n :: k) (xss :: [(k , k')]) :: Maybe k' where
Lookup x '[] = 'Nothing
Lookup x ('(x , a) ': xas) = 'Just a
Lookup x ('( x' , a) ': xas) = Lookup x xas
-- type-leve conditional
type family If a b c where
If 'True a b = a
If 'False a b = b
-- type-level boolean and operator
type family And a b where
And 'True 'True = 'True
And a b = 'False
|
shayan-najd/QFeldspar
|
QFeldspar/Singleton.hs
|
gpl-3.0
| 1,652 | 0 | 11 | 460 | 752 | 405 | 347 | -1 | -1 |
module Data.Sparse.Utils (unionWithD, intersectWithD, indexed, indexed2, minTup, maxTup, LB, UB, inBounds0, inBounds02, sortWith) where
-- import Control.Arrow (first, second)
import Data.Ord
import qualified Data.Vector as V
import Data.Sparse.Internal.Utils
-- * Misc. utilities
-- | Intersection and union of sparse lists having indices in _ascending_ order
intersectWith :: Ord i => (a -> a -> b) -> [(i, a)] -> [(i, a)] -> [b]
intersectWith f = intersectWith0 (comparing fst) (lift2snd f)
unionWith :: Ord i =>
(a -> a -> a) -> a -> [(i, a)] -> [(i, a)] -> [(i, a)]
unionWith = unionWith0 compare
-- | Intersection of sparse lists having indices in _descending_ order
intersectWithD :: Ord i => (a -> a -> b) -> [(i, a)] -> [(i, a)] -> [b]
intersectWithD f = intersectWith0 (comparing (Down . fst)) (lift2snd f)
-- | Union of sparse lists having indices in _descending_ order
unionWithD :: Ord i =>
(a -> a -> a) -> a -> [(i, a)] -> [(i, a)] -> [(i, a)]
unionWithD = unionWith0 (comparing Down)
--
intersectWith0 :: (a -> b -> Ordering) -> (a -> b -> c) -> [a] -> [b] -> [c]
intersectWith0 q f = go [] where
go acc ls@(x : xs) rs@(y : ys) =
case q x y of EQ -> go (f x y : acc) xs ys
LT -> go acc xs rs
_ -> go acc ls ys
go acc [] _ = acc
go acc _ [] = acc
unionWith0 :: (i -> i -> Ordering) -> (a -> a -> a) -> a -> [(i, a)] -> [(i, a)] -> [(i, a)]
unionWith0 q f z = go [] where
go acc ls@((ix, x) : xs) rs@((iy, y) : ys) =
case q ix iy of EQ -> go ((ix, f x y) : acc) xs ys
LT -> go ((ix, f x z) : acc) xs rs
_ -> go ((iy, f z y) : acc) ls ys
go acc [] r = acc ++ r
go acc l [] = acc ++ l
-- | Lift a binary function onto the second entry of a tuple
lift2snd :: (t -> t1 -> t2) -> (a, t) -> (a1, t1) -> t2
lift2snd f a b = f (snd a) (snd b)
-- | Wrap a function with a null check, returning in Maybe
safe :: (t -> Bool) -> (t -> a) -> t -> Maybe a
safe q f v | q v = Nothing
| otherwise = Just $ f v
-- | Componentwise tuple operations
-- TODO : use semilattice properties instead
maxTup, minTup :: Ord t => (t, t) -> (t, t) -> (t, t)
maxTup (x1,y1) (x2,y2) = (max x1 x2, max y1 y2)
minTup (x1,y1) (x2,y2) = (min x1 x2, min y1 y2)
-- | integer-indexed ziplist
indexed :: [b] -> [(Int, b)]
indexed xs = indexed' (length xs) xs
indexed' :: Int -> [a] -> [(Int, a)]
indexed' n xs = zip [0 .. n-1] xs
-- | ", 2d arrays
indexed2 :: Int -> [c] -> [(Int, Int, c)]
indexed2 m xs = zip3 (concat $ replicate n ii_) jj_ xs where
ii_ = [0 .. m-1]
jj_ = concatMap (replicate m) [0 .. n-1]
ln = length xs
n = ln `div` m
-- folds
-- | foldr over the results of a fmap
foldrMap :: (Foldable t, Functor t) => (a -> b) -> (b -> c -> c) -> c -> t a -> c
foldrMap ff gg x0 = foldr gg x0 . fmap ff
-- | strict left fold
foldlStrict :: (a -> b -> a) -> a -> [b] -> a
foldlStrict f = go
where
go z [] = z
go z (x:xs) = let z' = f z x in z' `seq` go z' xs
-- | indexed right fold
ifoldr :: Num i =>
(a -> b -> b) -> b -> (i -> c -> d -> a) -> c -> [d] -> b
ifoldr mjoin mneutral f = go 0 where
go i z (x:xs) = mjoin (f i z x) (go (i+1) z xs)
go _ _ [] = mneutral
-- ** Bounds checking
type LB = Int
type UB = Int
inBounds :: LB -> UB -> Int -> Bool
inBounds ibl ibu i = i>= ibl && i<ibu
inBounds2 :: (LB, UB) -> (Int, Int) -> Bool
inBounds2 (ibl,ibu) (ix,iy) = inBounds ibl ibu ix && inBounds ibl ibu iy
-- ", lower bound = 0
inBounds0 :: UB -> Int -> Bool
inBounds0 = inBounds 0
inBounds02 :: (UB, UB) -> (Int, Int) -> Bool
inBounds02 (bx,by) (i,j) = inBounds0 bx i && inBounds0 by j
-- ** Safe indexing
head' :: V.Vector a -> Maybe a
head' = safe V.null V.head
tail' :: V.Vector a -> Maybe (V.Vector a)
tail' = safe V.null V.tail
-- unionWith0 :: (a -> a -> Ordering) -> (a -> a -> a) -> a -> [a] -> [a] -> [a]
-- unionWith0 q f z = go [] where
-- go acc ls@(x : xs) rs@(y : ys) =
-- case q x y of EQ -> go (f x y : acc) xs ys
-- LT -> go (f x z : acc) xs rs
-- _ -> go (f z y : acc) ls ys
-- go acc [] r = acc ++ r
-- go acc l [] = acc ++ l
-- union :: Ord a => [a] -> [a] -> [a]
-- union u_ v_ = go u_ v_ where
-- go [] x = x
-- go y [] = y
-- go uu@(u:us) vv@(v:vs)
-- | u == v = u : go us vs
-- | u < v = u : go us vv
-- | otherwise = v : go uu vs
|
ocramz/sparse-linear-algebra
|
src/Data/Sparse/Utils.hs
|
gpl-3.0
| 4,454 | 0 | 14 | 1,299 | 1,940 | 1,062 | 878 | 73 | 5 |
{-# 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.GamesManagement.Achievements.ResetForAllPlayers
-- 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)
--
-- Resets the achievement with the given ID for all players. This method is
-- only available to user accounts for your developer console. Only draft
-- achievements can be reset.
--
-- /See:/ <https://developers.google.com/games/ Google Play Game Management Reference> for @gamesManagement.achievements.resetForAllPlayers@.
module Network.Google.Resource.GamesManagement.Achievements.ResetForAllPlayers
(
-- * REST Resource
AchievementsResetForAllPlayersResource
-- * Creating a Request
, achievementsResetForAllPlayers
, AchievementsResetForAllPlayers
-- * Request Lenses
, arfapXgafv
, arfapUploadProtocol
, arfapAchievementId
, arfapAccessToken
, arfapUploadType
, arfapCallback
) where
import Network.Google.GamesManagement.Types
import Network.Google.Prelude
-- | A resource alias for @gamesManagement.achievements.resetForAllPlayers@ method which the
-- 'AchievementsResetForAllPlayers' request conforms to.
type AchievementsResetForAllPlayersResource =
"games" :>
"v1management" :>
"achievements" :>
Capture "achievementId" Text :>
"resetForAllPlayers" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Post '[JSON] ()
-- | Resets the achievement with the given ID for all players. This method is
-- only available to user accounts for your developer console. Only draft
-- achievements can be reset.
--
-- /See:/ 'achievementsResetForAllPlayers' smart constructor.
data AchievementsResetForAllPlayers =
AchievementsResetForAllPlayers'
{ _arfapXgafv :: !(Maybe Xgafv)
, _arfapUploadProtocol :: !(Maybe Text)
, _arfapAchievementId :: !Text
, _arfapAccessToken :: !(Maybe Text)
, _arfapUploadType :: !(Maybe Text)
, _arfapCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AchievementsResetForAllPlayers' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'arfapXgafv'
--
-- * 'arfapUploadProtocol'
--
-- * 'arfapAchievementId'
--
-- * 'arfapAccessToken'
--
-- * 'arfapUploadType'
--
-- * 'arfapCallback'
achievementsResetForAllPlayers
:: Text -- ^ 'arfapAchievementId'
-> AchievementsResetForAllPlayers
achievementsResetForAllPlayers pArfapAchievementId_ =
AchievementsResetForAllPlayers'
{ _arfapXgafv = Nothing
, _arfapUploadProtocol = Nothing
, _arfapAchievementId = pArfapAchievementId_
, _arfapAccessToken = Nothing
, _arfapUploadType = Nothing
, _arfapCallback = Nothing
}
-- | V1 error format.
arfapXgafv :: Lens' AchievementsResetForAllPlayers (Maybe Xgafv)
arfapXgafv
= lens _arfapXgafv (\ s a -> s{_arfapXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
arfapUploadProtocol :: Lens' AchievementsResetForAllPlayers (Maybe Text)
arfapUploadProtocol
= lens _arfapUploadProtocol
(\ s a -> s{_arfapUploadProtocol = a})
-- | The ID of the achievement used by this method.
arfapAchievementId :: Lens' AchievementsResetForAllPlayers Text
arfapAchievementId
= lens _arfapAchievementId
(\ s a -> s{_arfapAchievementId = a})
-- | OAuth access token.
arfapAccessToken :: Lens' AchievementsResetForAllPlayers (Maybe Text)
arfapAccessToken
= lens _arfapAccessToken
(\ s a -> s{_arfapAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
arfapUploadType :: Lens' AchievementsResetForAllPlayers (Maybe Text)
arfapUploadType
= lens _arfapUploadType
(\ s a -> s{_arfapUploadType = a})
-- | JSONP
arfapCallback :: Lens' AchievementsResetForAllPlayers (Maybe Text)
arfapCallback
= lens _arfapCallback
(\ s a -> s{_arfapCallback = a})
instance GoogleRequest AchievementsResetForAllPlayers
where
type Rs AchievementsResetForAllPlayers = ()
type Scopes AchievementsResetForAllPlayers =
'["https://www.googleapis.com/auth/games"]
requestClient AchievementsResetForAllPlayers'{..}
= go _arfapAchievementId _arfapXgafv
_arfapUploadProtocol
_arfapAccessToken
_arfapUploadType
_arfapCallback
(Just AltJSON)
gamesManagementService
where go
= buildClient
(Proxy ::
Proxy AchievementsResetForAllPlayersResource)
mempty
|
brendanhay/gogol
|
gogol-games-management/gen/Network/Google/Resource/GamesManagement/Achievements/ResetForAllPlayers.hs
|
mpl-2.0
| 5,517 | 0 | 18 | 1,215 | 714 | 417 | 297 | 109 | 1 |
module Development.Fex
( module Development.Fex.Depend
, Experiment, Dependency, Effect, Depend(..)
, dependsExper, dep, dependStatus, resolve
, effectsExper, effect
, evalExper
, baseExper
, liftIO
, experFail
, setName, getName
, cached, existsAfter
)
where
import Development.Fex.Base
import Development.Fex.Combinators
import Development.Fex.Depend
import Development.Fex.Experiment
|
BurntSushi/fex
|
Development/Fex.hs
|
unlicense
| 411 | 0 | 5 | 66 | 97 | 65 | 32 | 15 | 0 |
module Git.Command.FastExport (run) where
run :: [String] -> IO ()
run args = return ()
|
wereHamster/yag
|
Git/Command/FastExport.hs
|
unlicense
| 88 | 0 | 7 | 15 | 42 | 23 | 19 | 3 | 1 |
fac n = if n == 0 then 1 else n * fac ( n - 1 )
main = putStrLn "hi, world"
|
kkdg/haskell-jogging
|
01/0110/hello.hs
|
apache-2.0
| 77 | 0 | 9 | 24 | 43 | 22 | 21 | 2 | 2 |
{-# LANGUAGE CPP #-}
module Actions.ManagePlans.Open.Url (url) where
import qualified Actions.ManagePlans.Url as Parent
url :: String
url = Parent.url ++ "/open"
|
DataStewardshipPortal/ds-wizard
|
DSServer/app/Actions/ManagePlans/Open/Url.hs
|
apache-2.0
| 166 | 0 | 6 | 25 | 39 | 26 | 13 | 5 | 1 |
module Deptrack () where
|
lucasdicioccio/deptrack
|
src/Deptrack.hs
|
apache-2.0
| 27 | 0 | 3 | 6 | 7 | 5 | 2 | 1 | 0 |
module Poset.A334184 (a334184, a334184_row) where
import Poset.Wichita (wichitaRanks)
import Data.Set (Set)
import qualified Data.Set as Set
a334184 :: Int -> Int
a334184 n = a334184_list !! (n-1)
a334184_list :: [Int]
a334184_list = concatMap a334184_row [1..]
a334184_row :: Integer -> [Int]
a334184_row = map Set.size . wichitaRanks
|
peterokagey/haskellOEIS
|
src/Poset/A334184.hs
|
apache-2.0
| 339 | 0 | 7 | 49 | 117 | 68 | 49 | 10 | 1 |
class Tofu t where
tofu :: j a -> t a j
data Frank a b = Frank {frankField :: b a} deriving (Show)
-- :t Frank {frankField = Just "HAHA"}
-- Frank {frankField = Just "HAHA"} :: Frack [Char] Mayb
-- Just "HAHA" 类型 Maybe [Char]
instance Tofu Frank where
tofu x = Frank x
data Barry t k p = Barry { yabba :: p, dabba :: t k }
instance Functor (Barry a b) where
fmap f (Barry {yabba = x, dabba = y}) = Barry {yabba = f x, dabba - y}
|
sharkspeed/dororis
|
languages/haskell/LYHGG/8-making-our-own-types-and-typeclasses/9-kinds-and-some-type-foo.hs
|
bsd-2-clause
| 450 | 1 | 10 | 113 | 163 | 90 | 73 | -1 | -1 |
module Main where
import Lib
main :: IO ()
main = putStrLn ""
|
danslocombe/music-geometry
|
app/Main.hs
|
bsd-3-clause
| 64 | 0 | 6 | 15 | 25 | 14 | 11 | 4 | 1 |
module AddMovie.Types where
-- Imports
-- =======
import Data.List (lookup)
-- Types
-- =====
data Metadata = Metadata [(Field, Value)]
deriving (Show)
lookupValue :: Field -> Metadata -> Value
lookupValue query (Metadata pairs) =
case lookup query pairs of
Just value -> value
Nothing -> ""
type Field = String
type Value = String
|
dgrisham/suggestion
|
src/AddMovie/Types.hs
|
bsd-3-clause
| 366 | 0 | 8 | 88 | 110 | 63 | 47 | 11 | 2 |
{-# LANGUAGE FlexibleInstances, OverlappingInstances, FlexibleContexts, UndecidableInstances, Rank2Types #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
--------------------------------------------------------------------
-- | Generic Instance for ToSElem using syb-with-class.
-- Inspired heavily-to-entirely by Alex Drummond's RJson.
--------------------------------------------------------------------}
module Text.StringTemplate.GenericWithClass() where
import qualified Data.Map as M
import Text.StringTemplate.Classes
import Data.Generics.SYB.WithClass.Basics
stripInitialUnderscores :: String -> String
stripInitialUnderscores ('_':s) = stripInitialUnderscores s
stripInitialUnderscores s = s
data ToSElemD a = ToSElemD { toSElemD :: Stringable b => a -> SElem b }
toSElemProxy :: Proxy ToSElemD
toSElemProxy = error "This value should never be evaluated!"
instance (ToSElem a, Data ToSElemD a) => Sat (ToSElemD a) where
dict = ToSElemD { toSElemD = toSElem }
genericToSElem :: (Data ToSElemD a, ToSElem a, Stringable b) => a -> SElem b
genericToSElem x
| isAlgType (dataTypeOf toSElemProxy x) =
case (map stripInitialUnderscores (getFields x)) of
[] -> LI (STR (showConstr (toConstr toSElemProxy x)) :
gmapQ toSElemProxy (toSElemD dict) x)
fs -> SM (M.fromList (zip fs (gmapQ toSElemProxy (toSElemD dict) x)))
| True =
error ("Unable to serialize the primitive type '" ++
dataTypeName (dataTypeOf toSElemProxy x) ++ "'")
getFields :: Data ToSElemD a => a -> [String]
getFields = constrFields . toConstr toSElemProxy
instance Data ToSElemD t => ToSElem t where
toSElem = genericToSElem
|
factisresearch/HStringTemplate
|
Text/StringTemplate/GenericWithClass.hs
|
bsd-3-clause
| 1,724 | 0 | 17 | 337 | 419 | 220 | 199 | 28 | 2 |
module Oracles.PackageData (
PackageData (..), PackageDataList (..), pkgData, pkgDataList
) where
import Hadrian.Oracles.TextFile
import Base
newtype PackageData = BuildGhciLib FilePath
data PackageDataList = AsmSrcs FilePath
| CcArgs FilePath
| CSrcs FilePath
| CmmSrcs FilePath
| CppArgs FilePath
| DepCcArgs FilePath
| DepExtraLibs FilePath
| DepIds FilePath
| DepIncludeDirs FilePath
| DepLdArgs FilePath
| DepLibDirs FilePath
| DepNames FilePath
| Deps FilePath
| HiddenModules FilePath
| HsArgs FilePath
| IncludeDirs FilePath
| LdArgs FilePath
| Modules FilePath
| SrcDirs FilePath
askPackageData :: FilePath -> String -> Action String
askPackageData path = lookupValueOrEmpty (path -/- "package-data.mk")
-- | For each @PackageData path@ the file 'path/package-data.mk' contains a line
-- of the form 'path_VERSION = 1.2.3.4'. @pkgData (PackageData path)@ is an
-- Action that consults the file and returns "1.2.3.4".
pkgData :: PackageData -> Action String
pkgData packageData = case packageData of
BuildGhciLib path -> askPackageData path "BUILD_GHCI_LIB"
-- | @PackageDataList path@ is used for multiple string options separated by
-- spaces, such as @path_MODULES = Data.Array Data.Array.Base ...@.
-- @pkgListData Modules@ therefore returns ["Data.Array", "Data.Array.Base", ...]
pkgDataList :: PackageDataList -> Action [String]
pkgDataList packageData = fmap (map unquote . words) $ case packageData of
AsmSrcs path -> askPackageData path "S_SRCS"
CcArgs path -> askPackageData path "CC_OPTS"
CSrcs path -> askPackageData path "C_SRCS"
CmmSrcs path -> askPackageData path "CMM_SRCS"
CppArgs path -> askPackageData path "CPP_OPTS"
DepCcArgs path -> askPackageData path "DEP_CC_OPTS"
DepExtraLibs path -> askPackageData path "DEP_EXTRA_LIBS"
DepIds path -> askPackageData path "DEP_IPIDS"
DepIncludeDirs path -> askPackageData path "DEP_INCLUDE_DIRS_SINGLE_QUOTED"
DepLibDirs path -> askPackageData path "DEP_LIB_DIRS_SINGLE_QUOTED"
DepLdArgs path -> askPackageData path "DEP_LD_OPTS"
DepNames path -> askPackageData path "DEP_NAMES"
Deps path -> askPackageData path "DEPS"
HiddenModules path -> askPackageData path "HIDDEN_MODULES"
HsArgs path -> askPackageData path "HC_OPTS"
IncludeDirs path -> askPackageData path "INCLUDE_DIRS"
LdArgs path -> askPackageData path "LD_OPTS"
Modules path -> askPackageData path "MODULES"
SrcDirs path -> askPackageData path "HS_SRC_DIRS"
where
unquote = dropWhile (== '\'') . dropWhileEnd (== '\'')
|
ezyang/ghc
|
hadrian/src/Oracles/PackageData.hs
|
bsd-3-clause
| 3,151 | 0 | 9 | 1,019 | 557 | 280 | 277 | 51 | 19 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.PackageDb
-- Copyright : (c) The University of Glasgow 2009, Duncan Coutts 2014
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module provides the view of GHC's database of registered packages that
-- is shared between GHC the compiler\/library, and the ghc-pkg program. It
-- defines the database format that is shared between GHC and ghc-pkg.
--
-- The database format, and this library are constructed so that GHC does not
-- have to depend on the Cabal library. The ghc-pkg program acts as the
-- gateway between the external package format (which is defined by Cabal) and
-- the internal package format which is specialised just for GHC.
--
-- GHC the compiler only needs some of the information which is kept about
-- registerd packages, such as module names, various paths etc. On the other
-- hand ghc-pkg has to keep all the information from Cabal packages and be able
-- to regurgitate it for users and other tools.
--
-- The first trick is that we duplicate some of the information in the package
-- database. We essentially keep two versions of the datbase in one file, one
-- version used only by ghc-pkg which keeps the full information (using the
-- serialised form of the 'InstalledPackageInfo' type defined by the Cabal
-- library); and a second version written by ghc-pkg and read by GHC which has
-- just the subset of information that GHC needs.
--
-- The second trick is that this module only defines in detail the format of
-- the second version -- the bit GHC uses -- and the part managed by ghc-pkg
-- is kept in the file but here we treat it as an opaque blob of data. That way
-- this library avoids depending on Cabal.
--
module GHC.PackageDb (
InstalledPackageInfo(..),
DbModule(..),
DbUnitId(..),
BinaryStringRep(..),
DbUnitIdModuleRep(..),
emptyInstalledPackageInfo,
readPackageDbForGhc,
readPackageDbForGhcPkg,
writePackageDb
) where
import Data.Version (Version(..))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS.Char8
import qualified Data.ByteString.Lazy as BS.Lazy
import qualified Data.ByteString.Lazy.Internal as BS.Lazy (defaultChunkSize)
import Data.Binary as Bin
import Data.Binary.Put as Bin
import Data.Binary.Get as Bin
import Control.Exception as Exception
import Control.Monad (when)
import System.FilePath
import System.IO
import System.IO.Error
import GHC.IO.Exception (IOErrorType(InappropriateType))
import System.Directory
-- | This is a subset of Cabal's 'InstalledPackageInfo', with just the bits
-- that GHC is interested in.
--
data InstalledPackageInfo compid srcpkgid srcpkgname instunitid unitid modulename mod
= InstalledPackageInfo {
unitId :: instunitid,
componentId :: compid,
instantiatedWith :: [(modulename, mod)],
sourcePackageId :: srcpkgid,
packageName :: srcpkgname,
packageVersion :: Version,
abiHash :: String,
depends :: [instunitid],
importDirs :: [FilePath],
hsLibraries :: [String],
extraLibraries :: [String],
extraGHCiLibraries :: [String],
libraryDirs :: [FilePath],
frameworks :: [String],
frameworkDirs :: [FilePath],
ldOptions :: [String],
ccOptions :: [String],
includes :: [String],
includeDirs :: [FilePath],
haddockInterfaces :: [FilePath],
haddockHTMLs :: [FilePath],
exposedModules :: [(modulename, Maybe mod)],
hiddenModules :: [modulename],
indefinite :: Bool,
exposed :: Bool,
trusted :: Bool
}
deriving (Eq, Show)
-- | A convenience constraint synonym for common constraints over parameters
-- to 'InstalledPackageInfo'.
type RepInstalledPackageInfo compid srcpkgid srcpkgname instunitid unitid modulename mod =
(BinaryStringRep srcpkgid, BinaryStringRep srcpkgname,
BinaryStringRep modulename, BinaryStringRep compid,
BinaryStringRep instunitid,
DbUnitIdModuleRep instunitid compid unitid modulename mod)
-- | A type-class for the types which can be converted into 'DbModule'/'DbUnitId'.
-- There is only one type class because these types are mutually recursive.
-- NB: The functional dependency helps out type inference in cases
-- where types would be ambiguous.
class DbUnitIdModuleRep instunitid compid unitid modulename mod
| mod -> unitid, unitid -> mod, mod -> modulename, unitid -> compid, unitid -> instunitid
where
fromDbModule :: DbModule instunitid compid unitid modulename mod -> mod
toDbModule :: mod -> DbModule instunitid compid unitid modulename mod
fromDbUnitId :: DbUnitId instunitid compid unitid modulename mod -> unitid
toDbUnitId :: unitid -> DbUnitId instunitid compid unitid modulename mod
-- | @ghc-boot@'s copy of 'Module', i.e. what is serialized to the database.
-- Use 'DbUnitIdModuleRep' to convert it into an actual 'Module'.
-- It has phantom type parameters as this is the most convenient way
-- to avoid undecidable instances.
data DbModule instunitid compid unitid modulename mod
= DbModule {
dbModuleUnitId :: unitid,
dbModuleName :: modulename
}
| DbModuleVar {
dbModuleVarName :: modulename
}
deriving (Eq, Show)
-- | @ghc-boot@'s copy of 'UnitId', i.e. what is serialized to the database.
-- Use 'DbUnitIdModuleRep' to convert it into an actual 'UnitId'.
-- It has phantom type parameters as this is the most convenient way
-- to avoid undecidable instances.
data DbUnitId instunitid compid unitid modulename mod
= DbUnitId compid [(modulename, mod)]
| DbInstalledUnitId instunitid
deriving (Eq, Show)
class BinaryStringRep a where
fromStringRep :: BS.ByteString -> a
toStringRep :: a -> BS.ByteString
emptyInstalledPackageInfo :: RepInstalledPackageInfo a b c d e f g
=> InstalledPackageInfo a b c d e f g
emptyInstalledPackageInfo =
InstalledPackageInfo {
unitId = fromStringRep BS.empty,
componentId = fromStringRep BS.empty,
instantiatedWith = [],
sourcePackageId = fromStringRep BS.empty,
packageName = fromStringRep BS.empty,
packageVersion = Version [] [],
abiHash = "",
depends = [],
importDirs = [],
hsLibraries = [],
extraLibraries = [],
extraGHCiLibraries = [],
libraryDirs = [],
frameworks = [],
frameworkDirs = [],
ldOptions = [],
ccOptions = [],
includes = [],
includeDirs = [],
haddockInterfaces = [],
haddockHTMLs = [],
exposedModules = [],
hiddenModules = [],
indefinite = False,
exposed = False,
trusted = False
}
-- | Read the part of the package DB that GHC is interested in.
--
readPackageDbForGhc :: RepInstalledPackageInfo a b c d e f g =>
FilePath -> IO [InstalledPackageInfo a b c d e f g]
readPackageDbForGhc file =
decodeFromFile file getDbForGhc
where
getDbForGhc = do
_version <- getHeader
_ghcPartLen <- get :: Get Word32
ghcPart <- get
-- the next part is for ghc-pkg, but we stop here.
return ghcPart
-- | Read the part of the package DB that ghc-pkg is interested in
--
-- Note that the Binary instance for ghc-pkg's representation of packages
-- is not defined in this package. This is because ghc-pkg uses Cabal types
-- (and Binary instances for these) which this package does not depend on.
--
readPackageDbForGhcPkg :: Binary pkgs => FilePath -> IO pkgs
readPackageDbForGhcPkg file =
decodeFromFile file getDbForGhcPkg
where
getDbForGhcPkg = do
_version <- getHeader
-- skip over the ghc part
ghcPartLen <- get :: Get Word32
_ghcPart <- skip (fromIntegral ghcPartLen)
-- the next part is for ghc-pkg
ghcPkgPart <- get
return ghcPkgPart
-- | Write the whole of the package DB, both parts.
--
writePackageDb :: (Binary pkgs, RepInstalledPackageInfo a b c d e f g) =>
FilePath -> [InstalledPackageInfo a b c d e f g] -> pkgs -> IO ()
writePackageDb file ghcPkgs ghcPkgPart =
writeFileAtomic file (runPut putDbForGhcPkg)
where
putDbForGhcPkg = do
putHeader
put ghcPartLen
putLazyByteString ghcPart
put ghcPkgPart
where
ghcPartLen :: Word32
ghcPartLen = fromIntegral (BS.Lazy.length ghcPart)
ghcPart = encode ghcPkgs
getHeader :: Get (Word32, Word32)
getHeader = do
magic <- getByteString (BS.length headerMagic)
when (magic /= headerMagic) $
fail "not a ghc-pkg db file, wrong file magic number"
majorVersion <- get :: Get Word32
-- The major version is for incompatible changes
minorVersion <- get :: Get Word32
-- The minor version is for compatible extensions
when (majorVersion /= 1) $
fail "unsupported ghc-pkg db format version"
-- If we ever support multiple major versions then we'll have to change
-- this code
-- The header can be extended without incrementing the major version,
-- we ignore fields we don't know about (currently all).
headerExtraLen <- get :: Get Word32
skip (fromIntegral headerExtraLen)
return (majorVersion, minorVersion)
putHeader :: Put
putHeader = do
putByteString headerMagic
put majorVersion
put minorVersion
put headerExtraLen
where
majorVersion = 1 :: Word32
minorVersion = 0 :: Word32
headerExtraLen = 0 :: Word32
headerMagic :: BS.ByteString
headerMagic = BS.Char8.pack "\0ghcpkg\0"
-- TODO: we may be able to replace the following with utils from the binary
-- package in future.
-- | Feed a 'Get' decoder with data chunks from a file.
--
decodeFromFile :: FilePath -> Get a -> IO a
decodeFromFile file decoder =
withBinaryFile file ReadMode $ \hnd ->
feed hnd (runGetIncremental decoder)
where
feed hnd (Partial k) = do chunk <- BS.hGet hnd BS.Lazy.defaultChunkSize
if BS.null chunk
then feed hnd (k Nothing)
else feed hnd (k (Just chunk))
feed _ (Done _ _ res) = return res
feed _ (Fail _ _ msg) = ioError err
where
err = mkIOError InappropriateType loc Nothing (Just file)
`ioeSetErrorString` msg
loc = "GHC.PackageDb.readPackageDb"
-- Copied from Cabal's Distribution.Simple.Utils.
writeFileAtomic :: FilePath -> BS.Lazy.ByteString -> IO ()
writeFileAtomic targetPath content = do
let (targetDir, targetFile) = splitFileName targetPath
Exception.bracketOnError
(openBinaryTempFileWithDefaultPermissions targetDir $ targetFile <.> "tmp")
(\(tmpPath, handle) -> hClose handle >> removeFile tmpPath)
(\(tmpPath, handle) -> do
BS.Lazy.hPut handle content
hClose handle
renameFile tmpPath targetPath)
instance (RepInstalledPackageInfo a b c d e f g) =>
Binary (InstalledPackageInfo a b c d e f g) where
put (InstalledPackageInfo
unitId componentId instantiatedWith sourcePackageId
packageName packageVersion
abiHash depends importDirs
hsLibraries extraLibraries extraGHCiLibraries libraryDirs
frameworks frameworkDirs
ldOptions ccOptions
includes includeDirs
haddockInterfaces haddockHTMLs
exposedModules hiddenModules
indefinite exposed trusted) = do
put (toStringRep sourcePackageId)
put (toStringRep packageName)
put packageVersion
put (toStringRep unitId)
put (toStringRep componentId)
put (map (\(mod_name, mod) -> (toStringRep mod_name, toDbModule mod))
instantiatedWith)
put abiHash
put (map toStringRep depends)
put importDirs
put hsLibraries
put extraLibraries
put extraGHCiLibraries
put libraryDirs
put frameworks
put frameworkDirs
put ldOptions
put ccOptions
put includes
put includeDirs
put haddockInterfaces
put haddockHTMLs
put (map (\(mod_name, mb_mod) -> (toStringRep mod_name, fmap toDbModule mb_mod))
exposedModules)
put (map toStringRep hiddenModules)
put indefinite
put exposed
put trusted
get = do
sourcePackageId <- get
packageName <- get
packageVersion <- get
unitId <- get
componentId <- get
instantiatedWith <- get
abiHash <- get
depends <- get
importDirs <- get
hsLibraries <- get
extraLibraries <- get
extraGHCiLibraries <- get
libraryDirs <- get
frameworks <- get
frameworkDirs <- get
ldOptions <- get
ccOptions <- get
includes <- get
includeDirs <- get
haddockInterfaces <- get
haddockHTMLs <- get
exposedModules <- get
hiddenModules <- get
indefinite <- get
exposed <- get
trusted <- get
return (InstalledPackageInfo
(fromStringRep unitId)
(fromStringRep componentId)
(map (\(mod_name, mod) -> (fromStringRep mod_name, fromDbModule mod))
instantiatedWith)
(fromStringRep sourcePackageId)
(fromStringRep packageName) packageVersion
abiHash
(map fromStringRep depends)
importDirs
hsLibraries extraLibraries extraGHCiLibraries libraryDirs
frameworks frameworkDirs
ldOptions ccOptions
includes includeDirs
haddockInterfaces haddockHTMLs
(map (\(mod_name, mb_mod) ->
(fromStringRep mod_name, fmap fromDbModule mb_mod))
exposedModules)
(map fromStringRep hiddenModules)
indefinite exposed trusted)
instance (BinaryStringRep modulename, BinaryStringRep compid,
BinaryStringRep instunitid,
DbUnitIdModuleRep instunitid compid unitid modulename mod) =>
Binary (DbModule instunitid compid unitid modulename mod) where
put (DbModule dbModuleUnitId dbModuleName) = do
putWord8 0
put (toDbUnitId dbModuleUnitId)
put (toStringRep dbModuleName)
put (DbModuleVar dbModuleVarName) = do
putWord8 1
put (toStringRep dbModuleVarName)
get = do
b <- getWord8
case b of
0 -> do dbModuleUnitId <- get
dbModuleName <- get
return (DbModule (fromDbUnitId dbModuleUnitId)
(fromStringRep dbModuleName))
_ -> do dbModuleVarName <- get
return (DbModuleVar (fromStringRep dbModuleVarName))
instance (BinaryStringRep modulename, BinaryStringRep compid,
BinaryStringRep instunitid,
DbUnitIdModuleRep instunitid compid unitid modulename mod) =>
Binary (DbUnitId instunitid compid unitid modulename mod) where
put (DbInstalledUnitId instunitid) = do
putWord8 0
put (toStringRep instunitid)
put (DbUnitId dbUnitIdComponentId dbUnitIdInsts) = do
putWord8 1
put (toStringRep dbUnitIdComponentId)
put (map (\(mod_name, mod) -> (toStringRep mod_name, toDbModule mod)) dbUnitIdInsts)
get = do
b <- getWord8
case b of
0 -> do
instunitid <- get
return (DbInstalledUnitId (fromStringRep instunitid))
_ -> do
dbUnitIdComponentId <- get
dbUnitIdInsts <- get
return (DbUnitId
(fromStringRep dbUnitIdComponentId)
(map (\(mod_name, mod) -> ( fromStringRep mod_name
, fromDbModule mod))
dbUnitIdInsts))
|
snoyberg/ghc
|
libraries/ghc-boot/GHC/PackageDb.hs
|
bsd-3-clause
| 16,358 | 0 | 21 | 4,554 | 3,248 | 1,729 | 1,519 | 322 | 4 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
module Text.RegExp.Matching.LeftLong.Type where
import Data.Semiring
import Text.RegExp.Data
-- |
-- Semiring used for leftmost longest matching.
--
-- The `LeftLong` type satisfies the distributive laws only with a
-- precondition on all involved multiplications: multiplied matches
-- must be adjacent and the start position must be smaller than the
-- end position. This precondition is satisfied for all
-- multiplications during regular expression matching.
--
data LeftLong = Zero | One | LeftLong !Int !Int
deriving (Eq,Show)
instance Semiring LeftLong where
zero = Zero; one = One
Zero .+. y = y
x .+. Zero = x
One .+. y = y
x .+. One = x
LeftLong a b .+. LeftLong c d
| a<c || a==c && b>=d = LeftLong a b
| otherwise = LeftLong c d
Zero .*. _ = Zero
_ .*. Zero = Zero
One .*. y = y
x .*. One = x
LeftLong a _ .*. LeftLong _ b = LeftLong a b
instance Weight c (Int,c) LeftLong where
symWeight p (n,c) = p c .*. LeftLong n n
|
sebfisch/haskell-regexp
|
src/Text/RegExp/Matching/LeftLong/Type.hs
|
bsd-3-clause
| 1,258 | 0 | 13 | 450 | 305 | 155 | 150 | 26 | 0 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.SV.Corpus
( corpus ) where
import Prelude
import Data.String
import Duckling.Lang
import Duckling.Numeral.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {lang = SV}, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (NumeralValue 0)
[ "0"
, "noll"
]
, examples (NumeralValue 1)
[ "1"
, "en"
, "ett"
]
, examples (NumeralValue 2)
[ "2"
, "två"
, "ett par"
]
, examples (NumeralValue 7)
[ "7"
, "sju"
]
, examples (NumeralValue 14)
[ "14"
, "Fjorton"
]
, examples (NumeralValue 16)
[ "16"
, "sexton"
]
, examples (NumeralValue 17)
[ "17"
, "sjutton"
]
, examples (NumeralValue 18)
[ "18"
, "arton"
]
, examples (NumeralValue 20)
[ "20"
, "tjugo"
]
, examples (NumeralValue 1.1)
[ "1,1"
, "1,10"
, "01,10"
]
, examples (NumeralValue 0.77)
[ "0,77"
, ",77"
]
, examples (NumeralValue 100000)
[ "100.000"
, "100000"
, "100K"
, "100k"
]
, examples (NumeralValue 3000000)
[ "3M"
, "3000K"
, "3000000"
, "3.000.000"
]
, examples (NumeralValue 1200000)
[ "1.200.000"
, "1200000"
, "1,2M"
, "1200K"
, ",0012G"
]
, examples (NumeralValue (-1200000))
[ "- 1.200.000"
, "-1200000"
, "minus 1.200.000"
, "negativ 1200000"
, "-1,2M"
, "-1200K"
, "-,0012G"
]
, examples (NumeralValue 5000)
[ "5 tusen"
, "fem tusen"
]
]
|
rfranek/duckling
|
Duckling/Numeral/SV/Corpus.hs
|
bsd-3-clause
| 2,499 | 0 | 11 | 1,134 | 460 | 268 | 192 | 76 | 1 |
module Playground17 where
import qualified Data.Map as Map
data Box a = Box a deriving Show
wrap :: a -> Box a
wrap a = Box a
unwrap :: Box a -> a
unwrap (Box a) = a
data Triple a = Triple a a a deriving Show
type Point3D = Triple Double
first :: Triple a -> a
first (Triple x _ _) = x
second :: Triple a -> a
second (Triple _ x _ ) = x
third :: Triple a -> a
third (Triple _ _ x) = x
transform :: (a -> a) -> Triple a -> Triple a
transform f ( Triple x y z ) = Triple (f x ) ( f y ) ( f z)
-- manual list
data List a = Empty | Cons a (List a) deriving Show
ourMap :: (a -> b) -> List a -> List b
ourMap _ Empty = Empty
ourMap func (Cons a rest) = Cons (func a) (ourMap func rest)
data Organ = Heart | Brain | Kidney | Spleen deriving (Show, Eq)
organs :: [Organ]
organs = [Heart,Heart,Brain,Spleen,Spleen,Kidney]
ids :: [Int]
ids = [2,7,13,14,21,24]
organPairs :: [(Int,Organ)]
organPairs = zip ids organs
organCatalog :: Map.Map Int Organ
organCatalog = Map.fromList organPairs
|
stefanocerruti/haskell-primer-alpha
|
src/Playground17.hs
|
bsd-3-clause
| 1,001 | 0 | 8 | 230 | 494 | 268 | 226 | 30 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | A module of re-exports and orphan instances
module Data.ByteString.IsoBaseFileFormat.ReExports (module X) where
import Data.Bits as X
import qualified Data.ByteString as B
import Data.ByteString.Builder as X
import Data.ByteString.IsoBaseFileFormat.Util.TypeLayout as X
import Data.Default as X
import Data.Foldable as X (fold)
import Data.Int as X
import Data.Kind as X (Constraint,
Type)
import Data.Kind.Extra as X
import Data.Maybe as X
import Data.Monoid as X
import Data.Proxy as X
import Data.String as X
import Data.Tagged as X
import qualified Data.Text as T
import Data.Type.Bool as X
import Data.Type.BitRecords as X
import Data.Type.Equality as X
import Data.Type.Pretty as X
import Data.Word as X
import GHC.TypeLits as X
import Test.TypeSpecCrazy as X hiding
(type Not)
import Text.Printf as X
import Debug.Trace as X
instance Default B.ByteString where
def = mempty
instance Default T.Text where
def = ""
instance Default c => Default (Tagged s c) where
def = Tagged def
|
sheyll/isobmff-builder
|
src/Data/ByteString/IsoBaseFileFormat/ReExports.hs
|
bsd-3-clause
| 2,191 | 0 | 7 | 1,311 | 277 | 187 | 90 | -1 | -1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveLift #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UnicodeSyntax #-}
{-# OPTIONS_GHC -Wno-orphans #-}
{-| This module contains the core syntax types and optics for them.
'reservedIdentifiers', 'denote' and friends are included because they are
involved in a dependency circle with "Dhall.Pretty.Internal".
-}
module Dhall.Syntax (
-- * 'Expr'
Const(..)
, Var(..)
, Binding(..)
, makeBinding
, CharacterSet(..)
, Chunks(..)
, DhallDouble(..)
, PreferAnnotation(..)
, Expr(..)
, RecordField(..)
, makeRecordField
, FunctionBinding(..)
, makeFunctionBinding
, FieldSelection(..)
, makeFieldSelection
, WithComponent(..)
-- ** 'Let'-blocks
, MultiLet(..)
, multiLet
, wrapInLets
-- ** Optics
, subExpressions
, subExpressionsWith
, unsafeSubExpressions
, chunkExprs
, bindingExprs
, recordFieldExprs
, functionBindingExprs
-- ** Handling 'Note's
, denote
, renote
, shallowDenote
-- * 'Import'
, Directory(..)
, File(..)
, FilePrefix(..)
, Import(..)
, ImportHashed(..)
, ImportMode(..)
, ImportType(..)
, URL(..)
, Scheme(..)
, pathCharacter
-- * Reserved identifiers
, reservedIdentifiers
, reservedKeywords
-- * `Data.Text.Text` manipulation
, toDoubleQuoted
, longestSharedWhitespacePrefix
, linesLiteral
, unlinesLiteral
-- * Utilities
, internalError
-- `shift` should really be in `Dhall.Normalize`, but it's here to avoid a
-- module cycle
, shift
) where
import Control.DeepSeq (NFData)
import Data.Bifunctor (Bifunctor (..))
import Data.Bits (xor)
import Data.Data (Data)
import Data.Foldable
import Data.HashSet (HashSet)
import Data.List.NonEmpty (NonEmpty (..))
import Data.Sequence (Seq)
import Data.String (IsString (..))
import Data.Text (Text)
import Data.Traversable ()
import Data.Void (Void)
import Dhall.Map (Map)
import {-# SOURCE #-} Dhall.Pretty.Internal
import Dhall.Src (Src (..))
import GHC.Generics (Generic)
import Instances.TH.Lift ()
import Language.Haskell.TH.Syntax (Lift)
import Numeric.Natural (Natural)
import Prettyprinter (Doc, Pretty)
import Unsafe.Coerce (unsafeCoerce)
import qualified Control.Monad
import qualified Data.Fixed as Fixed
import qualified Data.HashSet
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Text
import qualified Data.Time as Time
import qualified Dhall.Crypto
import qualified Lens.Family as Lens
import qualified Network.URI as URI
import qualified Prettyprinter as Pretty
deriving instance Lift Time.Day
deriving instance Lift Time.TimeOfDay
deriving instance Lift Time.TimeZone
deriving instance Lift (Fixed.Fixed a)
-- $setup
-- >>> import Dhall.Binary () -- For the orphan instance for `Serialise (Expr Void Import)`
{-| Constants for a pure type system
The axioms are:
> ⊦ Type : Kind
> ⊦ Kind : Sort
... and the valid rule pairs are:
> ⊦ Type ↝ Type : Type -- Functions from terms to terms (ordinary functions)
> ⊦ Kind ↝ Type : Type -- Functions from types to terms (type-polymorphic functions)
> ⊦ Sort ↝ Type : Type -- Functions from kinds to terms
> ⊦ Kind ↝ Kind : Kind -- Functions from types to types (type-level functions)
> ⊦ Sort ↝ Kind : Sort -- Functions from kinds to types (kind-polymorphic functions)
> ⊦ Sort ↝ Sort : Sort -- Functions from kinds to kinds (kind-level functions)
Note that Dhall does not support functions from terms to types and therefore
Dhall is not a dependently typed language
-}
data Const = Type | Kind | Sort
deriving (Show, Eq, Ord, Data, Bounded, Enum, Generic, Lift, NFData)
instance Pretty Const where
pretty = Pretty.unAnnotate . prettyConst
{-| Label for a bound variable
The `Data.Text.Text` field is the variable's name (i.e. \"@x@\").
The `Int` field disambiguates variables with the same name if there are
multiple bound variables of the same name in scope. Zero refers to the
nearest bound variable and the index increases by one for each bound
variable of the same name going outward. The following diagram may help:
> ┌──refers to──┐
> │ │
> v │
> λ(x : Type) → λ(y : Type) → λ(x : Type) → x@0
>
> ┌─────────────────refers to─────────────────┐
> │ │
> v │
> λ(x : Type) → λ(y : Type) → λ(x : Type) → x@1
This `Int` behaves like a De Bruijn index in the special case where all
variables have the same name.
You can optionally omit the index if it is @0@:
> ┌─refers to─┐
> │ │
> v │
> λ(x : Type) → λ(y : Type) → λ(x : Type) → x
Zero indices are omitted when pretty-printing @Var@s and non-zero indices
appear as a numeric suffix.
-}
data Var = V Text !Int
deriving (Data, Generic, Eq, Ord, Show, Lift, NFData)
instance IsString Var where
fromString str = V (fromString str) 0
instance Pretty Var where
pretty = Pretty.unAnnotate . prettyVar
-- | Record the binding part of a @let@ expression.
--
-- For example,
--
-- > let {- A -} x {- B -} : {- C -} Bool = {- D -} True in x
--
-- … will be instantiated as follows:
--
-- * @bindingSrc0@ corresponds to the @A@ comment.
-- * @variable@ is @"x"@
-- * @bindingSrc1@ corresponds to the @B@ comment.
-- * @annotation@ is 'Just' a pair, corresponding to the @C@ comment and @Bool@.
-- * @bindingSrc2@ corresponds to the @D@ comment.
-- * @value@ corresponds to @True@.
data Binding s a = Binding
{ bindingSrc0 :: Maybe s
, variable :: Text
, bindingSrc1 :: Maybe s
, annotation :: Maybe (Maybe s, Expr s a)
, bindingSrc2 :: Maybe s
, value :: Expr s a
} deriving (Data, Eq, Foldable, Functor, Generic, Lift, NFData, Ord, Show, Traversable)
instance Bifunctor Binding where
first k (Binding src0 a src1 b src2 c) =
Binding (fmap k src0) a (fmap k src1) (fmap adapt0 b) (fmap k src2) (first k c)
where
adapt0 (src3, d) = (fmap k src3, first k d)
second = fmap
{-| Construct a 'Binding' with no source information and no type annotation.
-}
makeBinding :: Text -> Expr s a -> Binding s a
makeBinding name = Binding Nothing name Nothing Nothing Nothing
-- | This wrapper around 'Prelude.Double' exists for its 'Eq' instance which is
-- defined via the binary encoding of Dhall @Double@s.
newtype DhallDouble = DhallDouble { getDhallDouble :: Double }
deriving stock (Show, Data, Lift, Generic)
deriving anyclass NFData
-- | This instance satisfies all the customary 'Eq' laws except substitutivity.
--
-- In particular:
--
-- >>> nan = DhallDouble (0/0)
-- >>> nan == nan
-- True
--
-- This instance is also consistent with with the binary encoding of Dhall @Double@s:
--
-- >>> toBytes n = Dhall.Binary.encodeExpression (DoubleLit n :: Expr Void Import)
--
-- prop> \a b -> (a == b) == (toBytes a == toBytes b)
instance Eq DhallDouble where
DhallDouble a == DhallDouble b
| isNaN a && isNaN b = True
| isNegativeZero a `xor` isNegativeZero b = False
| otherwise = a == b
-- | This instance relies on the 'Eq' instance for 'DhallDouble' but cannot
-- satisfy the customary 'Ord' laws when @NaN@ is involved.
instance Ord DhallDouble where
compare a@(DhallDouble a') b@(DhallDouble b') =
if a == b
then EQ
else compare a' b'
-- | The body of an interpolated @Text@ literal
data Chunks s a = Chunks [(Text, Expr s a)] Text
deriving (Functor, Foldable, Generic, Traversable, Show, Eq, Ord, Data, Lift, NFData)
instance Semigroup (Chunks s a) where
Chunks xysL zL <> Chunks [] zR =
Chunks xysL (zL <> zR)
Chunks xysL zL <> Chunks ((x, y):xysR) zR =
Chunks (xysL ++ (zL <> x, y):xysR) zR
instance Monoid (Chunks s a) where
mempty = Chunks [] mempty
instance IsString (Chunks s a) where
fromString str = Chunks [] (fromString str)
-- | Used to record the origin of a @//@ operator (i.e. from source code or a
-- product of desugaring)
data PreferAnnotation s a
= PreferFromSource
| PreferFromWith (Expr s a)
-- ^ Stores the original @with@ expression
| PreferFromCompletion
deriving (Data, Eq, Foldable, Functor, Generic, Lift, NFData, Ord, Show, Traversable)
instance Bifunctor PreferAnnotation where
first _ PreferFromSource = PreferFromSource
first f (PreferFromWith e ) = PreferFromWith (first f e)
first _ PreferFromCompletion = PreferFromCompletion
second = fmap
-- | Record the field of a record-type and record-literal expression.
-- The reason why we use the same ADT for both of them is because they store
-- the same information.
--
-- For example,
--
-- > { {- A -} x {- B -} : {- C -} T }
--
-- ... or
--
-- > { {- A -} x {- B -} = {- C -} T }
--
-- will be instantiated as follows:
--
-- * @recordFieldSrc0@ corresponds to the @A@ comment.
-- * @recordFieldValue@ is @"T"@
-- * @recordFieldSrc1@ corresponds to the @B@ comment.
-- * @recordFieldSrc2@ corresponds to the @C@ comment.
--
-- Although the @A@ comment isn't annotating the @"T"@ Record Field,
-- this is the best place to keep these comments.
--
-- Note that @recordFieldSrc2@ is always 'Nothing' when the 'RecordField' is for
-- a punned entry, because there is no @=@ sign. For example,
--
-- > { {- A -} x {- B -} }
--
-- will be instantiated as follows:
--
-- * @recordFieldSrc0@ corresponds to the @A@ comment.
-- * @recordFieldValue@ corresponds to @(Var "x")@
-- * @recordFieldSrc1@ corresponds to the @B@ comment.
-- * @recordFieldSrc2@ will be 'Nothing'
--
-- The labels involved in a record using dot-syntax like in this example:
--
-- > { {- A -} a {- B -} . {- C -} b {- D -} . {- E -} c {- F -} = {- G -} e }
--
-- will be instantiated as follows:
--
-- * For both the @a@ and @b@ field, @recordfieldSrc2@ is 'Nothing'
-- * For the @a@ field:
-- * @recordFieldSrc0@ corresponds to the @A@ comment
-- * @recordFieldSrc1@ corresponds to the @B@ comment
-- * For the @b@ field:
-- * @recordFieldSrc0@ corresponds to the @C@ comment
-- * @recordFieldSrc1@ corresponds to the @D@ comment
-- * For the @c@ field:
-- * @recordFieldSrc0@ corresponds to the @E@ comment
-- * @recordFieldSrc1@ corresponds to the @F@ comment
-- * @recordFieldSrc2@ corresponds to the @G@ comment
--
-- That is, for every label except the last one the semantics of
-- @recordFieldSrc0@ and @recordFieldSrc1@ are the same from a regular record
-- label but @recordFieldSrc2@ is always 'Nothing'. For the last keyword, all
-- srcs are 'Just'
data RecordField s a = RecordField
{ recordFieldSrc0 :: Maybe s
, recordFieldValue :: Expr s a
, recordFieldSrc1 :: Maybe s
, recordFieldSrc2 :: Maybe s
} deriving (Data, Eq, Foldable, Functor, Generic, Lift, NFData, Ord, Show, Traversable)
-- | Construct a 'RecordField' with no src information
makeRecordField :: Expr s a -> RecordField s a
makeRecordField e = RecordField Nothing e Nothing Nothing
instance Bifunctor RecordField where
first k (RecordField s0 value s1 s2) =
RecordField (k <$> s0) (first k value) (k <$> s1) (k <$> s2)
second = fmap
-- | Record the label of a function or a function-type expression
--
-- For example,
--
-- > λ({- A -} a {- B -} : {- C -} T) -> e
--
-- … will be instantiated as follows:
--
-- * @functionBindingSrc0@ corresponds to the @A@ comment
-- * @functionBindingVariable@ is @a@
-- * @functionBindingSrc1@ corresponds to the @B@ comment
-- * @functionBindingSrc2@ corresponds to the @C@ comment
-- * @functionBindingAnnotation@ is @T@
data FunctionBinding s a = FunctionBinding
{ functionBindingSrc0 :: Maybe s
, functionBindingVariable :: Text
, functionBindingSrc1 :: Maybe s
, functionBindingSrc2 :: Maybe s
, functionBindingAnnotation :: Expr s a
} deriving (Data, Eq, Foldable, Functor, Generic, Lift, NFData, Ord, Show, Traversable)
-- | Smart constructor for 'FunctionBinding' with no src information
makeFunctionBinding :: Text -> Expr s a -> FunctionBinding s a
makeFunctionBinding l t = FunctionBinding Nothing l Nothing Nothing t
instance Bifunctor FunctionBinding where
first k (FunctionBinding src0 label src1 src2 type_) =
FunctionBinding (k <$> src0) label (k <$> src1) (k <$> src2) (first k type_)
second = fmap
-- | Record the field on a selector-expression
--
-- For example,
--
-- > e . {- A -} x {- B -}
--
-- … will be instantiated as follows:
--
-- * @fieldSelectionSrc0@ corresponds to the @A@ comment
-- * @fieldSelectionLabel@ corresponds to @x@
-- * @fieldSelectionSrc1@ corresponds to the @B@ comment
--
-- Given our limitation that not all expressions recover their whitespaces, the
-- purpose of @fieldSelectionSrc1@ is to save the 'Text.Megaparsec.SourcePos'
-- where the @fieldSelectionLabel@ ends, but we /still/ use a 'Maybe Src'
-- (@s = 'Src'@) to be consistent with similar data types such as 'Binding', for
-- example.
data FieldSelection s = FieldSelection
{ fieldSelectionSrc0 :: Maybe s
, fieldSelectionLabel :: !Text
, fieldSelectionSrc1 :: Maybe s
} deriving (Data, Eq, Foldable, Functor, Generic, Lift, NFData, Ord, Show, Traversable)
-- | Smart constructor for 'FieldSelection' with no src information
makeFieldSelection :: Text -> FieldSelection s
makeFieldSelection t = FieldSelection Nothing t Nothing
-- | A path component for a @with@ expression
data WithComponent = WithLabel Text | WithQuestion
deriving (Data, Eq, Generic, Lift, NFData, Ord, Show)
{-| Syntax tree for expressions
The @s@ type parameter is used to track the presence or absence of `Src`
spans:
* If @s = `Src`@ then the code may contains `Src` spans (either in a `Note`
constructor or inline within another constructor, like `Let`)
* If @s = `Void`@ then the code has no `Src` spans
The @a@ type parameter is used to track the presence or absence of imports
* If @a = `Import`@ then the code may contain unresolved `Import`s
* If @a = `Void`@ then the code has no `Import`s
-}
data Expr s a
-- | > Const c ~ c
= Const Const
-- | > Var (V x 0) ~ x
-- > Var (V x n) ~ x@n
| Var Var
-- | > Lam _ (FunctionBinding _ "x" _ _ A) b ~ λ(x : A) -> b
| Lam (Maybe CharacterSet) (FunctionBinding s a) (Expr s a)
-- | > Pi _ "_" A B ~ A -> B
-- > Pi _ x A B ~ ∀(x : A) -> B
| Pi (Maybe CharacterSet) Text (Expr s a) (Expr s a)
-- | > App f a ~ f a
| App (Expr s a) (Expr s a)
-- | > Let (Binding _ x _ Nothing _ r) e ~ let x = r in e
-- > Let (Binding _ x _ (Just t ) _ r) e ~ let x : t = r in e
--
-- The difference between
--
-- > let x = a let y = b in e
--
-- and
--
-- > let x = a in let y = b in e
--
-- is only an additional 'Note' around @'Let' "y" …@ in the second
-- example.
--
-- See 'MultiLet' for a representation of let-blocks that mirrors the
-- source code more closely.
| Let (Binding s a) (Expr s a)
-- | > Annot x t ~ x : t
| Annot (Expr s a) (Expr s a)
-- | > Bool ~ Bool
| Bool
-- | > BoolLit b ~ b
| BoolLit Bool
-- | > BoolAnd x y ~ x && y
| BoolAnd (Expr s a) (Expr s a)
-- | > BoolOr x y ~ x || y
| BoolOr (Expr s a) (Expr s a)
-- | > BoolEQ x y ~ x == y
| BoolEQ (Expr s a) (Expr s a)
-- | > BoolNE x y ~ x != y
| BoolNE (Expr s a) (Expr s a)
-- | > BoolIf x y z ~ if x then y else z
| BoolIf (Expr s a) (Expr s a) (Expr s a)
-- | > Natural ~ Natural
| Natural
-- | > NaturalLit n ~ n
| NaturalLit Natural
-- | > NaturalFold ~ Natural/fold
| NaturalFold
-- | > NaturalBuild ~ Natural/build
| NaturalBuild
-- | > NaturalIsZero ~ Natural/isZero
| NaturalIsZero
-- | > NaturalEven ~ Natural/even
| NaturalEven
-- | > NaturalOdd ~ Natural/odd
| NaturalOdd
-- | > NaturalToInteger ~ Natural/toInteger
| NaturalToInteger
-- | > NaturalShow ~ Natural/show
| NaturalShow
-- | > NaturalSubtract ~ Natural/subtract
| NaturalSubtract
-- | > NaturalPlus x y ~ x + y
| NaturalPlus (Expr s a) (Expr s a)
-- | > NaturalTimes x y ~ x * y
| NaturalTimes (Expr s a) (Expr s a)
-- | > Integer ~ Integer
| Integer
-- | > IntegerLit n ~ ±n
| IntegerLit Integer
-- | > IntegerClamp ~ Integer/clamp
| IntegerClamp
-- | > IntegerNegate ~ Integer/negate
| IntegerNegate
-- | > IntegerShow ~ Integer/show
| IntegerShow
-- | > IntegerToDouble ~ Integer/toDouble
| IntegerToDouble
-- | > Double ~ Double
| Double
-- | > DoubleLit n ~ n
| DoubleLit DhallDouble
-- | > DoubleShow ~ Double/show
| DoubleShow
-- | > Text ~ Text
| Text
-- | > TextLit (Chunks [(t1, e1), (t2, e2)] t3) ~ "t1${e1}t2${e2}t3"
| TextLit (Chunks s a)
-- | > TextAppend x y ~ x ++ y
| TextAppend (Expr s a) (Expr s a)
-- | > TextReplace ~ Text/replace
| TextReplace
-- | > TextShow ~ Text/show
| TextShow
-- | > Date ~ Date
| Date
-- | > DateLiteral (fromGregorian _YYYY _MM _DD) ~ YYYY-MM-DD
| DateLiteral Time.Day
-- | > Time ~ Time
| Time
-- | > TimeLiteral (TimeOfDay hh mm ss) _ ~ hh:mm:ss
| TimeLiteral
Time.TimeOfDay
Word
-- ^ Precision
-- | > TimeZone ~ TimeZone
| TimeZone
-- | > TimeZoneLiteral (TimeZone ( 60 * _HH + _MM) _ _) ~ +HH:MM
-- | > TimeZoneLiteral (TimeZone (-60 * _HH + _MM) _ _) ~ -HH:MM
| TimeZoneLiteral Time.TimeZone
-- | > List ~ List
| List
-- | > ListLit (Just t ) [] ~ [] : t
-- > ListLit Nothing [x, y, z] ~ [x, y, z]
--
-- Invariant: A non-empty list literal is always represented as
-- @ListLit Nothing xs@.
--
-- When an annotated, non-empty list literal is parsed, it is represented
-- as
--
-- > Annot (ListLit Nothing [x, y, z]) t ~ [x, y, z] : t
-- Eventually we should have separate constructors for empty and non-empty
-- list literals. For now it's easier to check the invariant in @infer@.
-- See https://github.com/dhall-lang/dhall-haskell/issues/1359#issuecomment-537087234.
| ListLit (Maybe (Expr s a)) (Seq (Expr s a))
-- | > ListAppend x y ~ x # y
| ListAppend (Expr s a) (Expr s a)
-- | > ListBuild ~ List/build
| ListBuild
-- | > ListFold ~ List/fold
| ListFold
-- | > ListLength ~ List/length
| ListLength
-- | > ListHead ~ List/head
| ListHead
-- | > ListLast ~ List/last
| ListLast
-- | > ListIndexed ~ List/indexed
| ListIndexed
-- | > ListReverse ~ List/reverse
| ListReverse
-- | > Optional ~ Optional
| Optional
-- | > Some e ~ Some e
| Some (Expr s a)
-- | > None ~ None
| None
-- | > Record [ (k1, RecordField _ t1) ~ { k1 : t1, k2 : t1 }
-- > , (k2, RecordField _ t2)
-- > ]
| Record (Map Text (RecordField s a))
-- | > RecordLit [ (k1, RecordField _ v1) ~ { k1 = v1, k2 = v2 }
-- > , (k2, RecordField _ v2)
-- > ]
| RecordLit (Map Text (RecordField s a))
-- | > Union [(k1, Just t1), (k2, Nothing)] ~ < k1 : t1 | k2 >
| Union (Map Text (Maybe (Expr s a)))
-- | > Combine _ Nothing x y ~ x ∧ y
--
-- The first field is a `Just` when the `Combine` operator is introduced
-- as a result of desugaring duplicate record fields:
--
-- > RecordLit [ ( k ~ { k = x, k = y }
-- > , RecordField
-- > _
-- > (Combine (Just k) x y)
-- > )]
| Combine (Maybe CharacterSet) (Maybe Text) (Expr s a) (Expr s a)
-- | > CombineTypes _ x y ~ x ⩓ y
| CombineTypes (Maybe CharacterSet) (Expr s a) (Expr s a)
-- | > Prefer _ False x y ~ x ⫽ y
--
-- The first field is a `True` when the `Prefer` operator is introduced as a
-- result of desugaring a @with@ expression
| Prefer (Maybe CharacterSet) (PreferAnnotation s a) (Expr s a) (Expr s a)
-- | > RecordCompletion x y ~ x::y
| RecordCompletion (Expr s a) (Expr s a)
-- | > Merge x y (Just t ) ~ merge x y : t
-- > Merge x y Nothing ~ merge x y
| Merge (Expr s a) (Expr s a) (Maybe (Expr s a))
-- | > ToMap x (Just t) ~ toMap x : t
-- > ToMap x Nothing ~ toMap x
| ToMap (Expr s a) (Maybe (Expr s a))
-- | > ShowConstructor x ~ showConstructor x
| ShowConstructor (Expr s a)
-- | > Field e (FieldSelection _ x _) ~ e.x
| Field (Expr s a) (FieldSelection s)
-- | > Project e (Left xs) ~ e.{ xs }
-- > Project e (Right t) ~ e.(t)
| Project (Expr s a) (Either [Text] (Expr s a))
-- | > Assert e ~ assert : e
| Assert (Expr s a)
-- | > Equivalent _ x y ~ x ≡ y
| Equivalent (Maybe CharacterSet) (Expr s a) (Expr s a)
-- | > With x y e ~ x with y = e
| With (Expr s a) (NonEmpty WithComponent) (Expr s a)
-- | > Note s x ~ e
| Note s (Expr s a)
-- | > ImportAlt ~ e1 ? e2
| ImportAlt (Expr s a) (Expr s a)
-- | > Embed import ~ import
| Embed a
deriving (Foldable, Generic, Traversable, Show, Data, Lift, NFData)
-- NB: If you add a constructor to Expr, please also update the Arbitrary
-- instance in Dhall.Test.QuickCheck.
-- | This instance encodes what the Dhall standard calls an \"exact match\"
-- between two expressions.
--
-- Note that
--
-- >>> nan = DhallDouble (0/0)
-- >>> DoubleLit nan == DoubleLit nan
-- True
deriving instance (Eq s, Eq a) => Eq (Expr s a)
-- | Note that this 'Ord' instance inherits `DhallDouble`'s defects.
deriving instance (Ord s, Ord a) => Ord (Expr s a)
-- This instance is hand-written due to the fact that deriving
-- it does not give us an INLINABLE pragma. We annotate this fmap
-- implementation with this pragma below to allow GHC to, possibly,
-- inline the implementation for performance improvements.
instance Functor (Expr s) where
fmap f (Embed a) = Embed (f a)
fmap f (Let b e2) = Let (fmap f b) (fmap f e2)
fmap f (Note s e1) = Note s (fmap f e1)
fmap f (Record a) = Record $ fmap f <$> a
fmap f (RecordLit a) = RecordLit $ fmap f <$> a
fmap f (Lam cs fb e) = Lam cs (f <$> fb) (f <$> e)
fmap f (Field a b) = Field (f <$> a) b
fmap f expression = Lens.over unsafeSubExpressions (fmap f) expression
{-# INLINABLE fmap #-}
instance Applicative (Expr s) where
pure = Embed
(<*>) = Control.Monad.ap
instance Monad (Expr s) where
return = pure
expression >>= k = case expression of
Embed a -> k a
Let a b -> Let (adaptBinding a) (b >>= k)
Note a b -> Note a (b >>= k)
Record a -> Record $ bindRecordKeyValues <$> a
RecordLit a -> RecordLit $ bindRecordKeyValues <$> a
Lam cs a b -> Lam cs (adaptFunctionBinding a) (b >>= k)
Field a b -> Field (a >>= k) b
_ -> Lens.over unsafeSubExpressions (>>= k) expression
where
bindRecordKeyValues (RecordField s0 e s1 s2) =
RecordField s0 (e >>= k) s1 s2
adaptBinding (Binding src0 c src1 d src2 e) =
Binding src0 c src1 (fmap adaptBindingAnnotation d) src2 (e >>= k)
adaptFunctionBinding (FunctionBinding src0 label src1 src2 type_) =
FunctionBinding src0 label src1 src2 (type_ >>= k)
adaptBindingAnnotation (src3, f) = (src3, f >>= k)
instance Bifunctor Expr where
first k (Note a b ) = Note (k a) (first k b)
first _ (Embed a ) = Embed a
first k (Let a b ) = Let (first k a) (first k b)
first k (Record a ) = Record $ first k <$> a
first k (RecordLit a) = RecordLit $ first k <$> a
first k (Lam cs a b ) = Lam cs (first k a) (first k b)
first k (Field a b ) = Field (first k a) (k <$> b)
first k expression = Lens.over unsafeSubExpressions (first k) expression
second = fmap
instance IsString (Expr s a) where
fromString str = Var (fromString str)
-- | Generates a syntactically valid Dhall program
instance Pretty a => Pretty (Expr s a) where
pretty = Pretty.unAnnotate . prettyExpr
{-
Instead of converting explicitly between 'Expr's and 'MultiLet', it might
be nicer to use a pattern synonym:
> pattern MultiLet' :: NonEmpty (Binding s a) -> Expr s a -> Expr s a
> pattern MultiLet' as b <- (multiLetFromExpr -> Just (MultiLet as b)) where
> MultiLet' as b = wrapInLets as b
>
> multiLetFromExpr :: Expr s a -> Maybe (MultiLet s a)
> multiLetFromExpr = \case
> Let x mA a b -> Just (multiLet x mA a b)
> _ -> Nothing
This works in principle, but GHC as of v8.8.1 doesn't handle it well:
https://gitlab.haskell.org/ghc/ghc/issues/17096
This should be fixed by GHC-8.10, so it might be worth revisiting then.
-}
{-| Generate a 'MultiLet' from the contents of a 'Let'.
In the resulting @'MultiLet' bs e@, @e@ is guaranteed not to be a 'Let',
but it might be a @('Note' … ('Let' …))@.
Given parser output, 'multiLet' consolidates @let@s that formed a
let-block in the original source.
-}
multiLet :: Binding s a -> Expr s a -> MultiLet s a
multiLet b0 = \case
Let b1 e1 ->
let MultiLet bs e = multiLet b1 e1
in MultiLet (NonEmpty.cons b0 bs) e
e -> MultiLet (b0 :| []) e
{-| Wrap let-'Binding's around an 'Expr'.
'wrapInLets' can be understood as an inverse for 'multiLet':
> let MultiLet bs e1 = multiLet b e0
>
> wrapInLets bs e1 == Let b e0
-}
wrapInLets :: Foldable f => f (Binding s a) -> Expr s a -> Expr s a
wrapInLets bs e = foldr Let e bs
{-| This type represents 1 or more nested `Let` bindings that have been
coalesced together for ease of manipulation
-}
data MultiLet s a = MultiLet (NonEmpty (Binding s a)) (Expr s a)
-- | A traversal over the immediate sub-expressions of an expression.
subExpressions
:: Applicative f => (Expr s a -> f (Expr s a)) -> Expr s a -> f (Expr s a)
subExpressions = subExpressionsWith (pure . Embed)
{-# INLINABLE subExpressions #-}
{-| A traversal over the immediate sub-expressions of an expression which
allows mapping embedded values
-}
subExpressionsWith
:: Applicative f => (a -> f (Expr s b)) -> (Expr s a -> f (Expr s b)) -> Expr s a -> f (Expr s b)
subExpressionsWith h _ (Embed a) = h a
subExpressionsWith _ f (Note a b) = Note a <$> f b
subExpressionsWith _ f (Let a b) = Let <$> bindingExprs f a <*> f b
subExpressionsWith _ f (Record a) = Record <$> traverse (recordFieldExprs f) a
subExpressionsWith _ f (RecordLit a) = RecordLit <$> traverse (recordFieldExprs f) a
subExpressionsWith _ f (Lam cs fb e) = Lam cs <$> functionBindingExprs f fb <*> f e
subExpressionsWith _ f (Field a b) = Field <$> f a <*> pure b
subExpressionsWith _ f expression = unsafeSubExpressions f expression
{-# INLINABLE subExpressionsWith #-}
{-| An internal utility used to implement transformations that require changing
one of the type variables of the `Expr` type
This utility only works because the implementation is partial, not
handling the `Let`, `Note`, or `Embed` cases, which need to be handled by
the caller.
-}
unsafeSubExpressions
:: Applicative f => (Expr s a -> f (Expr t b)) -> Expr s a -> f (Expr t b)
unsafeSubExpressions _ (Const c) = pure (Const c)
unsafeSubExpressions _ (Var v) = pure (Var v)
unsafeSubExpressions f (Pi cs a b c) = Pi cs a <$> f b <*> f c
unsafeSubExpressions f (App a b) = App <$> f a <*> f b
unsafeSubExpressions f (Annot a b) = Annot <$> f a <*> f b
unsafeSubExpressions _ Bool = pure Bool
unsafeSubExpressions _ (BoolLit b) = pure (BoolLit b)
unsafeSubExpressions f (BoolAnd a b) = BoolAnd <$> f a <*> f b
unsafeSubExpressions f (BoolOr a b) = BoolOr <$> f a <*> f b
unsafeSubExpressions f (BoolEQ a b) = BoolEQ <$> f a <*> f b
unsafeSubExpressions f (BoolNE a b) = BoolNE <$> f a <*> f b
unsafeSubExpressions f (BoolIf a b c) = BoolIf <$> f a <*> f b <*> f c
unsafeSubExpressions _ Natural = pure Natural
unsafeSubExpressions _ (NaturalLit n) = pure (NaturalLit n)
unsafeSubExpressions _ NaturalFold = pure NaturalFold
unsafeSubExpressions _ NaturalBuild = pure NaturalBuild
unsafeSubExpressions _ NaturalIsZero = pure NaturalIsZero
unsafeSubExpressions _ NaturalEven = pure NaturalEven
unsafeSubExpressions _ NaturalOdd = pure NaturalOdd
unsafeSubExpressions _ NaturalToInteger = pure NaturalToInteger
unsafeSubExpressions _ NaturalShow = pure NaturalShow
unsafeSubExpressions _ NaturalSubtract = pure NaturalSubtract
unsafeSubExpressions f (NaturalPlus a b) = NaturalPlus <$> f a <*> f b
unsafeSubExpressions f (NaturalTimes a b) = NaturalTimes <$> f a <*> f b
unsafeSubExpressions _ Integer = pure Integer
unsafeSubExpressions _ (IntegerLit n) = pure (IntegerLit n)
unsafeSubExpressions _ IntegerClamp = pure IntegerClamp
unsafeSubExpressions _ IntegerNegate = pure IntegerNegate
unsafeSubExpressions _ IntegerShow = pure IntegerShow
unsafeSubExpressions _ IntegerToDouble = pure IntegerToDouble
unsafeSubExpressions _ Double = pure Double
unsafeSubExpressions _ (DoubleLit n) = pure (DoubleLit n)
unsafeSubExpressions _ DoubleShow = pure DoubleShow
unsafeSubExpressions _ Text = pure Text
unsafeSubExpressions f (TextLit chunks) =
TextLit <$> chunkExprs f chunks
unsafeSubExpressions f (TextAppend a b) = TextAppend <$> f a <*> f b
unsafeSubExpressions _ TextReplace = pure TextReplace
unsafeSubExpressions _ TextShow = pure TextShow
unsafeSubExpressions _ Date = pure Date
unsafeSubExpressions _ (DateLiteral a) = pure (DateLiteral a)
unsafeSubExpressions _ Time = pure Time
unsafeSubExpressions _ (TimeLiteral a b) = pure (TimeLiteral a b)
unsafeSubExpressions _ TimeZone = pure TimeZone
unsafeSubExpressions _ (TimeZoneLiteral a) = pure (TimeZoneLiteral a)
unsafeSubExpressions _ List = pure List
unsafeSubExpressions f (ListLit a b) = ListLit <$> traverse f a <*> traverse f b
unsafeSubExpressions f (ListAppend a b) = ListAppend <$> f a <*> f b
unsafeSubExpressions _ ListBuild = pure ListBuild
unsafeSubExpressions _ ListFold = pure ListFold
unsafeSubExpressions _ ListLength = pure ListLength
unsafeSubExpressions _ ListHead = pure ListHead
unsafeSubExpressions _ ListLast = pure ListLast
unsafeSubExpressions _ ListIndexed = pure ListIndexed
unsafeSubExpressions _ ListReverse = pure ListReverse
unsafeSubExpressions _ Optional = pure Optional
unsafeSubExpressions f (Some a) = Some <$> f a
unsafeSubExpressions _ None = pure None
unsafeSubExpressions f (Union a) = Union <$> traverse (traverse f) a
unsafeSubExpressions f (Combine cs a b c) = Combine cs a <$> f b <*> f c
unsafeSubExpressions f (CombineTypes cs a b) = CombineTypes cs <$> f a <*> f b
unsafeSubExpressions f (Prefer cs a b c) = Prefer cs <$> a' <*> f b <*> f c
where
a' = case a of
PreferFromSource -> pure PreferFromSource
PreferFromWith d -> PreferFromWith <$> f d
PreferFromCompletion -> pure PreferFromCompletion
unsafeSubExpressions f (RecordCompletion a b) = RecordCompletion <$> f a <*> f b
unsafeSubExpressions f (Merge a b t) = Merge <$> f a <*> f b <*> traverse f t
unsafeSubExpressions f (ToMap a t) = ToMap <$> f a <*> traverse f t
unsafeSubExpressions f (ShowConstructor a) = ShowConstructor <$> f a
unsafeSubExpressions f (Project a b) = Project <$> f a <*> traverse f b
unsafeSubExpressions f (Assert a) = Assert <$> f a
unsafeSubExpressions f (Equivalent cs a b) = Equivalent cs <$> f a <*> f b
unsafeSubExpressions f (With a b c) = With <$> f a <*> pure b <*> f c
unsafeSubExpressions f (ImportAlt l r) = ImportAlt <$> f l <*> f r
unsafeSubExpressions _ (Let {}) = unhandledConstructor "Let"
unsafeSubExpressions _ (Note {}) = unhandledConstructor "Note"
unsafeSubExpressions _ (Embed {}) = unhandledConstructor "Embed"
unsafeSubExpressions _ (Record {}) = unhandledConstructor "Record"
unsafeSubExpressions _ (RecordLit {}) = unhandledConstructor "RecordLit"
unsafeSubExpressions _ (Lam {}) = unhandledConstructor "Lam"
unsafeSubExpressions _ (Field {}) = unhandledConstructor "Field"
{-# INLINABLE unsafeSubExpressions #-}
unhandledConstructor :: Text -> a
unhandledConstructor constructor =
internalError
( "Dhall.Syntax.unsafeSubExpressions: Unhandled "
<> constructor
<> " construtor"
)
{-| Traverse over the immediate 'Expr' children in a 'Binding'.
-}
bindingExprs
:: (Applicative f)
=> (Expr s a -> f (Expr s b))
-> Binding s a -> f (Binding s b)
bindingExprs f (Binding s0 n s1 t s2 v) =
Binding
<$> pure s0
<*> pure n
<*> pure s1
<*> traverse (traverse f) t
<*> pure s2
<*> f v
{-# INLINABLE bindingExprs #-}
{-| Traverse over the immediate 'Expr' children in a 'RecordField'.
-}
recordFieldExprs
:: Applicative f
=> (Expr s a -> f (Expr s b))
-> RecordField s a -> f (RecordField s b)
recordFieldExprs f (RecordField s0 e s1 s2) =
RecordField
<$> pure s0
<*> f e
<*> pure s1
<*> pure s2
{-# INLINABLE recordFieldExprs #-}
{-| Traverse over the immediate 'Expr' children in a 'FunctionBinding'.
-}
functionBindingExprs
:: Applicative f
=> (Expr s a -> f (Expr s b))
-> FunctionBinding s a -> f (FunctionBinding s b)
functionBindingExprs f (FunctionBinding s0 label s1 s2 type_) =
FunctionBinding
<$> pure s0
<*> pure label
<*> pure s1
<*> pure s2
<*> f type_
{-# INLINABLE functionBindingExprs #-}
-- | A traversal over the immediate sub-expressions in 'Chunks'.
chunkExprs
:: Applicative f
=> (Expr s a -> f (Expr t b))
-> Chunks s a -> f (Chunks t b)
chunkExprs f (Chunks chunks final) =
flip Chunks final <$> traverse (traverse f) chunks
{-# INLINABLE chunkExprs #-}
{-| Internal representation of a directory that stores the path components in
reverse order
In other words, the directory @\/foo\/bar\/baz@ is encoded as
@Directory { components = [ "baz", "bar", "foo" ] }@
-}
newtype Directory = Directory { components :: [Text] }
deriving stock (Eq, Generic, Ord, Show)
deriving anyclass NFData
instance Semigroup Directory where
Directory components₀ <> Directory components₁ =
Directory (components₁ <> components₀)
instance Pretty Directory where
pretty (Directory {..}) = foldMap prettyPathComponent (reverse components)
prettyPathComponent :: Text -> Doc ann
prettyPathComponent text
| Data.Text.all pathCharacter text =
"/" <> Pretty.pretty text
| otherwise =
"/\"" <> Pretty.pretty text <> "\""
{-| A `File` is a `directory` followed by one additional path component
representing the `file` name
-}
data File = File
{ directory :: Directory
, file :: Text
} deriving (Eq, Generic, Ord, Show, NFData)
instance Pretty File where
pretty (File {..}) =
Pretty.pretty directory
<> prettyPathComponent file
instance Semigroup File where
File directory₀ _ <> File directory₁ file =
File (directory₀ <> directory₁) file
-- | The beginning of a file path which anchors subsequent path components
data FilePrefix
= Absolute
-- ^ Absolute path
| Here
-- ^ Path relative to @.@
| Parent
-- ^ Path relative to @..@
| Home
-- ^ Path relative to @~@
deriving (Eq, Generic, Ord, Show, NFData)
instance Pretty FilePrefix where
pretty Absolute = ""
pretty Here = "."
pretty Parent = ".."
pretty Home = "~"
-- | The URI scheme
data Scheme = HTTP | HTTPS deriving (Eq, Generic, Ord, Show, NFData)
-- | This type stores all of the components of a remote import
data URL = URL
{ scheme :: Scheme
, authority :: Text
, path :: File
, query :: Maybe Text
, headers :: Maybe (Expr Src Import)
} deriving (Eq, Generic, Ord, Show, NFData)
instance Pretty URL where
pretty (URL {..}) =
schemeDoc
<> "://"
<> Pretty.pretty authority
<> pathDoc
<> queryDoc
<> foldMap prettyHeaders headers
where
prettyHeaders h =
" using (" <> Pretty.unAnnotate (Pretty.pretty h) <> ")"
File {..} = path
Directory {..} = directory
pathDoc =
foldMap prettyURIComponent (reverse components)
<> prettyURIComponent file
schemeDoc = case scheme of
HTTP -> "http"
HTTPS -> "https"
queryDoc = case query of
Nothing -> ""
Just q -> "?" <> Pretty.pretty q
prettyURIComponent :: Text -> Doc ann
prettyURIComponent text =
Pretty.pretty $ URI.normalizeCase $ URI.normalizeEscape $ "/" <> Data.Text.unpack text
-- | The type of import (i.e. local vs. remote vs. environment)
data ImportType
= Local FilePrefix File
-- ^ Local path
| Remote URL
-- ^ URL of remote resource and optional headers stored in an import
| Env Text
-- ^ Environment variable
| Missing
deriving (Eq, Generic, Ord, Show, NFData)
parent :: File
parent = File { directory = Directory { components = [ ".." ] }, file = "" }
instance Semigroup ImportType where
Local prefix file₀ <> Local Here file₁ = Local prefix (file₀ <> file₁)
Remote (URL { path = path₀, ..}) <> Local Here path₁ =
Remote (URL { path = path₀ <> path₁, ..})
Local prefix file₀ <> Local Parent file₁ =
Local prefix (file₀ <> parent <> file₁)
Remote (URL { path = path₀, .. }) <> Local Parent path₁ =
Remote (URL { path = path₀ <> parent <> path₁, .. })
import₀ <> Remote (URL { headers = headers₀, .. }) =
Remote (URL { headers = headers₁, .. })
where
importHashed₀ = Import (ImportHashed Nothing import₀) Code
headers₁ = fmap (fmap (importHashed₀ <>)) headers₀
_ <> import₁ =
import₁
instance Pretty ImportType where
pretty (Local prefix file) =
Pretty.pretty prefix <> Pretty.pretty file
pretty (Remote url) = Pretty.pretty url
pretty (Env env) = "env:" <> prettyEnvironmentVariable env
pretty Missing = "missing"
-- | How to interpret the import's contents (i.e. as Dhall code or raw text)
data ImportMode = Code | RawText | Location
deriving (Eq, Generic, Ord, Show, NFData)
-- | A `ImportType` extended with an optional hash for semantic integrity checks
data ImportHashed = ImportHashed
{ hash :: Maybe Dhall.Crypto.SHA256Digest
, importType :: ImportType
} deriving (Eq, Generic, Ord, Show, NFData)
instance Semigroup ImportHashed where
ImportHashed _ importType₀ <> ImportHashed hash importType₁ =
ImportHashed hash (importType₀ <> importType₁)
instance Pretty ImportHashed where
pretty (ImportHashed Nothing p) =
Pretty.pretty p
pretty (ImportHashed (Just h) p) =
Pretty.group (Pretty.flatAlt long short)
where
long =
Pretty.align
( Pretty.pretty p <> Pretty.hardline
<> " sha256:" <> Pretty.pretty (show h)
)
short = Pretty.pretty p <> " sha256:" <> Pretty.pretty (show h)
-- | Reference to an external resource
data Import = Import
{ importHashed :: ImportHashed
, importMode :: ImportMode
} deriving (Eq, Generic, Ord, Show, NFData)
instance Semigroup Import where
Import importHashed₀ _ <> Import importHashed₁ code =
Import (importHashed₀ <> importHashed₁) code
instance Pretty Import where
pretty (Import {..}) = Pretty.pretty importHashed <> Pretty.pretty suffix
where
suffix :: Text
suffix = case importMode of
RawText -> " as Text"
Location -> " as Location"
Code -> ""
{-| Returns `True` if the given `Char` is valid within an unquoted path
component
This is exported for reuse within the @"Dhall.Parser.Token"@ module
-}
pathCharacter :: Char -> Bool
pathCharacter c =
'\x21' == c
|| ('\x24' <= c && c <= '\x27')
|| ('\x2A' <= c && c <= '\x2B')
|| ('\x2D' <= c && c <= '\x2E')
|| ('\x30' <= c && c <= '\x3B')
|| c == '\x3D'
|| ('\x40' <= c && c <= '\x5A')
|| ('\x5E' <= c && c <= '\x7A')
|| c == '\x7C'
|| c == '\x7E'
-- | Remove all `Note` constructors from an `Expr` (i.e. de-`Note`)
--
-- This also remove CharacterSet annotations.
denote :: Expr s a -> Expr t a
denote = \case
Note _ b -> denote b
Let a b -> Let (denoteBinding a) (denote b)
Embed a -> Embed a
Combine _ _ b c -> Combine Nothing Nothing (denote b) (denote c)
CombineTypes _ b c -> CombineTypes Nothing (denote b) (denote c)
Prefer _ a b c -> Lens.over unsafeSubExpressions denote $ Prefer Nothing a b c
Record a -> Record $ denoteRecordField <$> a
RecordLit a -> RecordLit $ denoteRecordField <$> a
Lam _ a b -> Lam Nothing (denoteFunctionBinding a) (denote b)
Pi _ t a b -> Pi Nothing t (denote a) (denote b)
Field a (FieldSelection _ b _) -> Field (denote a) (FieldSelection Nothing b Nothing)
Equivalent _ a b -> Equivalent Nothing (denote a) (denote b)
expression -> Lens.over unsafeSubExpressions denote expression
where
denoteRecordField (RecordField _ e _ _) = RecordField Nothing (denote e) Nothing Nothing
denoteBinding (Binding _ c _ d _ e) =
Binding Nothing c Nothing (fmap denoteBindingAnnotation d) Nothing (denote e)
denoteBindingAnnotation (_, f) = (Nothing, denote f)
denoteFunctionBinding (FunctionBinding _ l _ _ t) =
FunctionBinding Nothing l Nothing Nothing (denote t)
-- | The \"opposite\" of `denote`, like @first absurd@ but faster
renote :: Expr Void a -> Expr s a
renote = unsafeCoerce
{-# INLINE renote #-}
{-| Remove any outermost `Note` constructors
This is typically used when you want to get the outermost non-`Note`
constructor without removing internal `Note` constructors
-}
shallowDenote :: Expr s a -> Expr s a
shallowDenote (Note _ e) = shallowDenote e
shallowDenote e = e
-- | The set of reserved keywords according to the @keyword@ rule in the grammar
reservedKeywords :: HashSet Text
reservedKeywords =
Data.HashSet.fromList
[ "if"
, "then"
, "else"
, "let"
, "in"
, "using"
, "missing"
, "as"
, "Infinity"
, "NaN"
, "merge"
, "Some"
, "toMap"
, "assert"
, "forall"
, "with"
]
-- | The set of reserved identifiers for the Dhall language
-- | Contains also all keywords from "reservedKeywords"
reservedIdentifiers :: HashSet Text
reservedIdentifiers = reservedKeywords <>
Data.HashSet.fromList
[ -- Builtins according to the `builtin` rule in the grammar
"Natural/fold"
, "Natural/build"
, "Natural/isZero"
, "Natural/even"
, "Natural/odd"
, "Natural/toInteger"
, "Natural/show"
, "Natural/subtract"
, "Integer"
, "Integer/clamp"
, "Integer/negate"
, "Integer/show"
, "Integer/toDouble"
, "Integer/show"
, "Natural/subtract"
, "Double/show"
, "List/build"
, "List/fold"
, "List/length"
, "List/head"
, "List/last"
, "List/indexed"
, "List/reverse"
, "Text/replace"
, "Text/show"
, "Bool"
, "True"
, "False"
, "Optional"
, "None"
, "Natural"
, "Integer"
, "Double"
, "Text"
, "Date"
, "Time"
, "TimeZone"
, "List"
, "Type"
, "Kind"
, "Sort"
]
-- | Same as @Data.Text.splitOn@, except always returning a `NonEmpty` result
splitOn :: Text -> Text -> NonEmpty Text
splitOn needle haystack =
case Data.Text.splitOn needle haystack of
[] -> "" :| []
t : ts -> t :| ts
-- | Split `Chunks` by lines
linesLiteral :: Chunks s a -> NonEmpty (Chunks s a)
linesLiteral (Chunks [] suffix) =
fmap (Chunks []) (splitOn "\n" suffix)
linesLiteral (Chunks ((prefix, interpolation) : pairs₀) suffix₀) =
foldr
NonEmpty.cons
(Chunks ((lastLine, interpolation) : pairs₁) suffix₁ :| chunks)
(fmap (Chunks []) initLines)
where
splitLines = splitOn "\n" prefix
initLines = NonEmpty.init splitLines
lastLine = NonEmpty.last splitLines
Chunks pairs₁ suffix₁ :| chunks = linesLiteral (Chunks pairs₀ suffix₀)
-- | Flatten several `Chunks` back into a single `Chunks` by inserting newlines
unlinesLiteral :: NonEmpty (Chunks s a) -> Chunks s a
unlinesLiteral chunks =
Data.Foldable.fold (NonEmpty.intersperse "\n" chunks)
-- | Returns `True` if the `Chunks` represents a blank line
emptyLine :: Chunks s a -> Bool
emptyLine (Chunks [] "" ) = True
emptyLine (Chunks [] "\r") = True -- So that `\r\n` is treated as a blank line
emptyLine _ = False
-- | Return the leading whitespace for a `Chunks` literal
leadingSpaces :: Chunks s a -> Text
leadingSpaces chunks = Data.Text.takeWhile isSpace firstText
where
isSpace c = c == ' ' || c == '\t'
firstText =
case chunks of
Chunks [] suffix -> suffix
Chunks ((prefix, _) : _ ) _ -> prefix
{-| Compute the longest shared whitespace prefix for the purposes of stripping
leading indentation
-}
longestSharedWhitespacePrefix :: NonEmpty (Chunks s a) -> Text
longestSharedWhitespacePrefix literals =
case fmap leadingSpaces filteredLines of
l : ls -> Data.Foldable.foldl' sharedPrefix l ls
[] -> ""
where
sharedPrefix ab ac =
case Data.Text.commonPrefixes ab ac of
Just (a, _b, _c) -> a
Nothing -> ""
-- The standard specifies to filter out blank lines for all lines *except*
-- for the last line
filteredLines = newInit <> pure oldLast
where
oldInit = NonEmpty.init literals
oldLast = NonEmpty.last literals
newInit = filter (not . emptyLine) oldInit
-- | Drop the first @n@ characters for a `Chunks` literal
dropLiteral :: Int -> Chunks s a -> Chunks s a
dropLiteral n (Chunks [] suffix) =
Chunks [] (Data.Text.drop n suffix)
dropLiteral n (Chunks ((prefix, interpolation) : rest) suffix) =
Chunks ((Data.Text.drop n prefix, interpolation) : rest) suffix
{-| Convert a single-quoted `Chunks` literal to the equivalent double-quoted
`Chunks` literal
-}
toDoubleQuoted :: Chunks Src a -> Chunks Src a
toDoubleQuoted literal =
unlinesLiteral (fmap (dropLiteral indent) literals)
where
literals = linesLiteral literal
longestSharedPrefix = longestSharedWhitespacePrefix literals
indent = Data.Text.length longestSharedPrefix
{-| `shift` is used by both normalization and type-checking to avoid variable
capture by shifting variable indices
For example, suppose that you were to normalize the following expression:
> λ(a : Type) → λ(x : a) → (λ(y : a) → λ(x : a) → y) x
If you were to substitute @y@ with @x@ without shifting any variable
indices, then you would get the following incorrect result:
> λ(a : Type) → λ(x : a) → λ(x : a) → x -- Incorrect normalized form
In order to substitute @x@ in place of @y@ we need to `shift` @x@ by @1@ in
order to avoid being misinterpreted as the @x@ bound by the innermost
lambda. If we perform that `shift` then we get the correct result:
> λ(a : Type) → λ(x : a) → λ(x : a) → x@1
As a more worked example, suppose that you were to normalize the following
expression:
> λ(a : Type)
> → λ(f : a → a → a)
> → λ(x : a)
> → λ(x : a)
> → (λ(x : a) → f x x@1) x@1
The correct normalized result would be:
> λ(a : Type)
> → λ(f : a → a → a)
> → λ(x : a)
> → λ(x : a)
> → f x@1 x
The above example illustrates how we need to both increase and decrease
variable indices as part of substitution:
* We need to increase the index of the outer @x\@1@ to @x\@2@ before we
substitute it into the body of the innermost lambda expression in order
to avoid variable capture. This substitution changes the body of the
lambda expression to @(f x\@2 x\@1)@
* We then remove the innermost lambda and therefore decrease the indices of
both @x@s in @(f x\@2 x\@1)@ to @(f x\@1 x)@ in order to reflect that one
less @x@ variable is now bound within that scope
Formally, @(shift d (V x n) e)@ modifies the expression @e@ by adding @d@ to
the indices of all variables named @x@ whose indices are greater than
@(n + m)@, where @m@ is the number of bound variables of the same name
within that scope
In practice, @d@ is always @1@ or @-1@ because we either:
* increment variables by @1@ to avoid variable capture during substitution
* decrement variables by @1@ when deleting lambdas after substitution
@n@ starts off at @0@ when substitution begins and increments every time we
descend into a lambda or let expression that binds a variable of the same
name in order to avoid shifting the bound variables by mistake.
-}
shift :: Int -> Var -> Expr s a -> Expr s a
shift d (V x n) (Var (V x' n')) = Var (V x' n'')
where
n'' = if x == x' && n <= n' then n' + d else n'
shift d (V x n) (Lam cs (FunctionBinding src0 x' src1 src2 _A) b) =
Lam cs (FunctionBinding src0 x' src1 src2 _A') b'
where
_A' = shift d (V x n ) _A
b' = shift d (V x n') b
where
n' = if x == x' then n + 1 else n
shift d (V x n) (Pi cs x' _A _B) = Pi cs x' _A' _B'
where
_A' = shift d (V x n ) _A
_B' = shift d (V x n') _B
where
n' = if x == x' then n + 1 else n
shift d (V x n) (Let (Binding src0 f src1 mt src2 r) e) =
Let (Binding src0 f src1 mt' src2 r') e'
where
e' = shift d (V x n') e
where
n' = if x == f then n + 1 else n
mt' = fmap (fmap (shift d (V x n))) mt
r' = shift d (V x n) r
shift d v expression = Lens.over subExpressions (shift d v) expression
_ERROR :: String
_ERROR = "\ESC[1;31mError\ESC[0m"
{-| Utility function used to throw internal errors that should never happen
(in theory) but that are not enforced by the type system
-}
internalError :: Data.Text.Text -> forall b . b
internalError text = error (unlines
[ _ERROR <> ": Compiler bug "
, " "
, "Explanation: This error message means that there is a bug in the Dhall compiler."
, "You didn't do anything wrong, but if you would like to see this problem fixed "
, "then you should report the bug at: "
, " "
, "https://github.com/dhall-lang/dhall-haskell/issues "
, " "
, "Please include the following text in your bug report: "
, " "
, "``` "
, Data.Text.unpack text <> " "
, "``` "
] )
|
Gabriel439/Haskell-Dhall-Library
|
dhall/src/Dhall/Syntax.hs
|
bsd-3-clause
| 55,376 | 343 | 14 | 16,896 | 10,899 | 5,936 | 4,963 | 795 | 13 |
-----------------------------------------------------------------------------
-- |
-- Module : Main
-- Copyright : (c) David Himmelstrup 2005
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Entry point to the default cabal-install front-end.
-----------------------------------------------------------------------------
module Main (main) where
import Distribution.Client.Setup
( GlobalFlags(..), globalCommand, globalRepos
, ConfigFlags(..)
, ConfigExFlags(..), defaultConfigExFlags, configureExCommand
, InstallFlags(..), defaultInstallFlags
, installCommand, upgradeCommand
, FetchFlags(..), fetchCommand
, checkCommand
, updateCommand
, ListFlags(..), listCommand
, InfoFlags(..), infoCommand
, UploadFlags(..), uploadCommand
, ReportFlags(..), reportCommand
, InitFlags(initVerbosity), initCommand
, SDistFlags(..), SDistExFlags(..), sdistCommand
, reportCommand
, unpackCommand, UnpackFlags(..) )
import Distribution.Simple.Setup
( BuildFlags(..), buildCommand
, HaddockFlags(..), haddockCommand
, HscolourFlags(..), hscolourCommand
, CopyFlags(..), copyCommand
, RegisterFlags(..), registerCommand
, CleanFlags(..), cleanCommand
, TestFlags(..), testCommand
, BenchmarkFlags(..), benchmarkCommand
, Flag(..), fromFlag, fromFlagOrDefault, flagToMaybe )
import Distribution.Client.SetupWrapper
( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions )
import Distribution.Client.Config
( SavedConfig(..), loadConfig, defaultConfigFile )
import Distribution.Client.Targets
( readUserTargets )
import Distribution.Client.List (list, info)
import Distribution.Client.Install (install, upgrade)
import Distribution.Client.Configure (configure)
import Distribution.Client.Update (update)
import Distribution.Client.Fetch (fetch)
import Distribution.Client.Check as Check (check)
--import Distribution.Client.Clean (clean)
import Distribution.Client.Upload as Upload (upload, check, report)
import Distribution.Client.SrcDist (sdist)
import Distribution.Client.Unpack (unpack)
import Distribution.Client.Init (initCabal)
import qualified Distribution.Client.Win32SelfUpgrade as Win32SelfUpgrade
import Distribution.Simple.Compiler
( Compiler, PackageDB(..), PackageDBStack )
import Distribution.Simple.Program
( ProgramConfiguration, defaultProgramConfiguration )
import Distribution.Simple.Command
import Distribution.Simple.Configure (configCompilerAux)
import Distribution.Simple.Utils
( cabalVersion, die, topHandler, intercalate )
import Distribution.Text
( display )
import Distribution.Verbosity as Verbosity
( Verbosity, normal, intToVerbosity, lessVerbose )
import qualified Paths_cabal_install (version)
import System.Environment (getArgs, getProgName)
import System.Exit (exitFailure)
import System.FilePath (splitExtension, takeExtension)
import System.Directory (doesFileExist)
import Data.List (intersperse)
import Data.Maybe (fromMaybe)
import Data.Monoid (Monoid(..))
import Control.Monad (unless)
-- | Entry point
--
main :: IO ()
main = getArgs >>= mainWorker
mainWorker :: [String] -> IO ()
mainWorker ("win32selfupgrade":args) = win32SelfUpgradeAction args
mainWorker args = topHandler $
case commandsRun globalCommand commands args of
CommandHelp help -> printGlobalHelp help
CommandList opts -> printOptionsList opts
CommandErrors errs -> printErrors errs
CommandReadyToGo (globalflags, commandParse) ->
case commandParse of
_ | fromFlag (globalVersion globalflags) -> printVersion
| fromFlag (globalNumericVersion globalflags) -> printNumericVersion
CommandHelp help -> printCommandHelp help
CommandList opts -> printOptionsList opts
CommandErrors errs -> printErrors errs
CommandReadyToGo action -> action globalflags
where
printCommandHelp help = do
pname <- getProgName
putStr (help pname)
printGlobalHelp help = do
pname <- getProgName
configFile <- defaultConfigFile
putStr (help pname)
putStr $ "\nYou can edit the cabal configuration file to set defaults:\n"
++ " " ++ configFile ++ "\n"
printOptionsList = putStr . unlines
printErrors errs = die $ concat (intersperse "\n" errs)
printNumericVersion = putStrLn $ display Paths_cabal_install.version
printVersion = putStrLn $ "cabal-install version "
++ display Paths_cabal_install.version
++ "\nusing version "
++ display cabalVersion
++ " of the Cabal library "
commands =
[installCommand `commandAddAction` installAction
,updateCommand `commandAddAction` updateAction
,listCommand `commandAddAction` listAction
,infoCommand `commandAddAction` infoAction
,fetchCommand `commandAddAction` fetchAction
,unpackCommand `commandAddAction` unpackAction
,checkCommand `commandAddAction` checkAction
,sdistCommand `commandAddAction` sdistAction
,uploadCommand `commandAddAction` uploadAction
,reportCommand `commandAddAction` reportAction
,initCommand `commandAddAction` initAction
,configureExCommand `commandAddAction` configureAction
,wrapperAction (buildCommand defaultProgramConfiguration)
buildVerbosity buildDistPref
,wrapperAction copyCommand
copyVerbosity copyDistPref
,wrapperAction haddockCommand
haddockVerbosity haddockDistPref
,wrapperAction cleanCommand
cleanVerbosity cleanDistPref
,wrapperAction hscolourCommand
hscolourVerbosity hscolourDistPref
,wrapperAction registerCommand
regVerbosity regDistPref
,wrapperAction testCommand
testVerbosity testDistPref
,wrapperAction benchmarkCommand
benchmarkVerbosity benchmarkDistPref
,upgradeCommand `commandAddAction` upgradeAction
]
wrapperAction :: Monoid flags
=> CommandUI flags
-> (flags -> Flag Verbosity)
-> (flags -> Flag String)
-> Command (GlobalFlags -> IO ())
wrapperAction command verbosityFlag distPrefFlag =
commandAddAction command
{ commandDefaultFlags = mempty } $ \flags extraArgs _globalFlags -> do
let verbosity = fromFlagOrDefault normal (verbosityFlag flags)
setupScriptOptions = defaultSetupScriptOptions {
useDistPref = fromFlagOrDefault
(useDistPref defaultSetupScriptOptions)
(distPrefFlag flags)
}
setupWrapper verbosity setupScriptOptions Nothing
command (const flags) extraArgs
configureAction :: (ConfigFlags, ConfigExFlags)
-> [String] -> GlobalFlags -> IO ()
configureAction (configFlags, configExFlags) extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
config <- loadConfig verbosity (globalConfigFile globalFlags)
(configUserInstall configFlags)
let configFlags' = savedConfigureFlags config `mappend` configFlags
configExFlags' = savedConfigureExFlags config `mappend` configExFlags
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, conf) <- configCompilerAux configFlags'
configure verbosity
(configPackageDB' configFlags') (globalRepos globalFlags')
comp conf configFlags' configExFlags' extraArgs
installAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
-> [String] -> GlobalFlags -> IO ()
installAction (configFlags, _, installFlags, _) _ _globalFlags
| fromFlagOrDefault False (installOnly installFlags)
= let verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
in setupWrapper verbosity defaultSetupScriptOptions Nothing
installCommand (const mempty) []
installAction (configFlags, configExFlags, installFlags, haddockFlags)
extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
targets <- readUserTargets verbosity extraArgs
config <- loadConfig verbosity (globalConfigFile globalFlags)
(configUserInstall configFlags)
let configFlags' = savedConfigureFlags config `mappend` configFlags
configExFlags' = defaultConfigExFlags `mappend`
savedConfigureExFlags config `mappend` configExFlags
installFlags' = defaultInstallFlags `mappend`
savedInstallFlags config `mappend` installFlags
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, conf) <- configCompilerAux' configFlags'
install verbosity
(configPackageDB' configFlags') (globalRepos globalFlags')
comp conf globalFlags' configFlags' configExFlags' installFlags' haddockFlags
targets
listAction :: ListFlags -> [String] -> GlobalFlags -> IO ()
listAction listFlags extraArgs globalFlags = do
let verbosity = fromFlag (listVerbosity listFlags)
config <- loadConfig verbosity (globalConfigFile globalFlags) mempty
let configFlags = savedConfigureFlags config
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, conf) <- configCompilerAux' configFlags
list verbosity
(configPackageDB' configFlags)
(globalRepos globalFlags')
comp
conf
listFlags
extraArgs
infoAction :: InfoFlags -> [String] -> GlobalFlags -> IO ()
infoAction infoFlags extraArgs globalFlags = do
let verbosity = fromFlag (infoVerbosity infoFlags)
targets <- readUserTargets verbosity extraArgs
config <- loadConfig verbosity (globalConfigFile globalFlags) mempty
let configFlags = savedConfigureFlags config
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, conf) <- configCompilerAux configFlags
info verbosity
(configPackageDB' configFlags)
(globalRepos globalFlags')
comp
conf
globalFlags'
infoFlags
targets
updateAction :: Flag Verbosity -> [String] -> GlobalFlags -> IO ()
updateAction verbosityFlag extraArgs globalFlags = do
unless (null extraArgs) $ do
die $ "'update' doesn't take any extra arguments: " ++ unwords extraArgs
let verbosity = fromFlag verbosityFlag
config <- loadConfig verbosity (globalConfigFile globalFlags) mempty
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
update verbosity (globalRepos globalFlags')
upgradeAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
-> [String] -> GlobalFlags -> IO ()
upgradeAction (configFlags, configExFlags, installFlags, haddockFlags)
extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
targets <- readUserTargets verbosity extraArgs
config <- loadConfig verbosity (globalConfigFile globalFlags)
(configUserInstall configFlags)
let configFlags' = savedConfigureFlags config `mappend` configFlags
configExFlags' = savedConfigureExFlags config `mappend` configExFlags
installFlags' = defaultInstallFlags `mappend`
savedInstallFlags config `mappend` installFlags
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, conf) <- configCompilerAux' configFlags'
upgrade verbosity
(configPackageDB' configFlags') (globalRepos globalFlags')
comp conf globalFlags' configFlags' configExFlags' installFlags' haddockFlags
targets
fetchAction :: FetchFlags -> [String] -> GlobalFlags -> IO ()
fetchAction fetchFlags extraArgs globalFlags = do
let verbosity = fromFlag (fetchVerbosity fetchFlags)
targets <- readUserTargets verbosity extraArgs
config <- loadConfig verbosity (globalConfigFile globalFlags) mempty
let configFlags = savedConfigureFlags config
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, conf) <- configCompilerAux' configFlags
fetch verbosity
(configPackageDB' configFlags) (globalRepos globalFlags')
comp conf globalFlags' fetchFlags
targets
uploadAction :: UploadFlags -> [String] -> GlobalFlags -> IO ()
uploadAction uploadFlags extraArgs globalFlags = do
let verbosity = fromFlag (uploadVerbosity uploadFlags)
config <- loadConfig verbosity (globalConfigFile globalFlags) mempty
let uploadFlags' = savedUploadFlags config `mappend` uploadFlags
globalFlags' = savedGlobalFlags config `mappend` globalFlags
tarfiles = extraArgs
checkTarFiles extraArgs
if fromFlag (uploadCheck uploadFlags')
then Upload.check verbosity tarfiles
else upload verbosity
(globalRepos globalFlags')
(flagToMaybe $ uploadUsername uploadFlags')
(flagToMaybe $ uploadPassword uploadFlags')
tarfiles
where
checkTarFiles tarfiles
| null tarfiles
= die "the 'upload' command expects one or more .tar.gz packages."
| not (null otherFiles)
= die $ "the 'upload' command expects only .tar.gz packages: "
++ intercalate ", " otherFiles
| otherwise = sequence_
[ do exists <- doesFileExist tarfile
unless exists $ die $ "file not found: " ++ tarfile
| tarfile <- tarfiles ]
where otherFiles = filter (not . isTarGzFile) tarfiles
isTarGzFile file = case splitExtension file of
(file', ".gz") -> takeExtension file' == ".tar"
_ -> False
checkAction :: Flag Verbosity -> [String] -> GlobalFlags -> IO ()
checkAction verbosityFlag extraArgs _globalFlags = do
unless (null extraArgs) $ do
die $ "'check' doesn't take any extra arguments: " ++ unwords extraArgs
allOk <- Check.check (fromFlag verbosityFlag)
unless allOk exitFailure
sdistAction :: (SDistFlags, SDistExFlags) -> [String] -> GlobalFlags -> IO ()
sdistAction (sdistFlags, sdistExFlags) extraArgs _globalFlags = do
unless (null extraArgs) $ do
die $ "'sdist' doesn't take any extra arguments: " ++ unwords extraArgs
sdist sdistFlags sdistExFlags
reportAction :: ReportFlags -> [String] -> GlobalFlags -> IO ()
reportAction reportFlags extraArgs globalFlags = do
unless (null extraArgs) $ do
die $ "'report' doesn't take any extra arguments: " ++ unwords extraArgs
let verbosity = fromFlag (reportVerbosity reportFlags)
config <- loadConfig verbosity (globalConfigFile globalFlags) mempty
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
reportFlags' = savedReportFlags config `mappend` reportFlags
Upload.report verbosity (globalRepos globalFlags')
(flagToMaybe $ reportUsername reportFlags')
(flagToMaybe $ reportPassword reportFlags')
unpackAction :: UnpackFlags -> [String] -> GlobalFlags -> IO ()
unpackAction unpackFlags extraArgs globalFlags = do
let verbosity = fromFlag (unpackVerbosity unpackFlags)
targets <- readUserTargets verbosity extraArgs
config <- loadConfig verbosity (globalConfigFile globalFlags) mempty
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
unpack verbosity
(globalRepos (savedGlobalFlags config))
globalFlags'
unpackFlags
targets
initAction :: InitFlags -> [String] -> GlobalFlags -> IO ()
initAction initFlags _extraArgs globalFlags = do
let verbosity = fromFlag (initVerbosity initFlags)
config <- loadConfig verbosity (globalConfigFile globalFlags) mempty
let configFlags = savedConfigureFlags config
(comp, conf) <- configCompilerAux' configFlags
initCabal verbosity
(configPackageDB' configFlags)
comp
conf
initFlags
-- | See 'Distribution.Client.Install.withWin32SelfUpgrade' for details.
--
win32SelfUpgradeAction :: [String] -> IO ()
win32SelfUpgradeAction (pid:path:rest) =
Win32SelfUpgrade.deleteOldExeFile verbosity (read pid) path
where
verbosity = case rest of
(['-','-','v','e','r','b','o','s','e','=',n]:_) | n `elem` ['0'..'9']
-> fromMaybe Verbosity.normal (Verbosity.intToVerbosity (read [n]))
_ -> Verbosity.normal
win32SelfUpgradeAction _ = return ()
--
-- Utils (transitionary)
--
-- | Currently the user interface specifies the package dbs to use with just a
-- single valued option, a 'PackageDB'. However internally we represent the
-- stack of 'PackageDB's explictly as a list. This function converts encodes
-- the package db stack implicit in a single packagedb.
--
-- TODO: sort this out, make it consistent with the command line UI
implicitPackageDbStack :: Bool -> Maybe PackageDB -> PackageDBStack
implicitPackageDbStack userInstall packageDbFlag
| userInstall = GlobalPackageDB : UserPackageDB : extra
| otherwise = GlobalPackageDB : extra
where
extra = case packageDbFlag of
Just (SpecificPackageDB db) -> [SpecificPackageDB db]
_ -> []
configPackageDB' :: ConfigFlags -> PackageDBStack
configPackageDB' cfg =
implicitPackageDbStack userInstall (flagToMaybe (configPackageDB cfg))
where
userInstall = fromFlagOrDefault True (configUserInstall cfg)
configCompilerAux' :: ConfigFlags
-> IO (Compiler, ProgramConfiguration)
configCompilerAux' configFlags =
configCompilerAux configFlags
--FIXME: make configCompilerAux use a sensible verbosity
{ configVerbosity = fmap lessVerbose (configVerbosity configFlags) }
|
alphaHeavy/cabal
|
cabal-install/Main.hs
|
bsd-3-clause
| 18,458 | 0 | 17 | 4,474 | 4,123 | 2,169 | 1,954 | 347 | 8 |
{-# LANGUAGE OverloadedStrings #-}
module ECESpec where
import Network.HTTP.ECE
import Network.HTTP.ECE.Key
import Test.Hspec
spec :: Spec
spec = do
describe "KeyStore" $ do
it "should do storage and retrieval" $ do
key <- generateKey
let x = getKey (ExplicitMethod, "a") $ addKey (ExplicitMethod, "a") key $ newKeyStore
x `shouldBe` Just key
describe "Encryption Parameters" $ do
it "should decode single parameter (no value)" $ do
decodeEncryptionParams "a" `shouldBe` Just [("a", Nothing)]
it "should decode multi parameter (no value)" $ do
decodeEncryptionParams "a; b" `shouldBe` Just [("a", Nothing), ("b", Nothing)]
it "should decode multi parameter (no value, no space)" $ do
decodeEncryptionParams "a;b" `shouldBe` Just [("a", Nothing), ("b", Nothing)]
it "should decode single parameters (no quotes)" $ do
decodeEncryptionParams "a=abc" `shouldBe` Just [("a", Just "abc")]
it "should decode single parameters (quotes)" $ do
decodeEncryptionParams "a=\"abc\"" `shouldBe` Just [("a", Just "abc")]
it "should decode multi parameters (no quotes)" $ do
decodeEncryptionParams "a=abc; b=def" `shouldBe` Just [("a", Just "abc"), ("b", Just "def")]
it "should decode multi parameters (no quotes, no space)" $ do
decodeEncryptionParams "a=abc;b=def" `shouldBe` Just [("a", Just "abc"), ("b", Just "def")]
it "should decode multi parameters (quotes)" $ do
decodeEncryptionParams "a=\"abc\"; b=\"def\"" `shouldBe` Just [("a", Just "abc"), ("b", Just "def")]
it "should decode multi parameters (no space)" $ do
decodeEncryptionParams "a=\"abc\";b=\"def\"" `shouldBe` Just [("a", Just "abc"), ("b", Just "def")]
it "should decode encryption parameters correctly" $ do
decodeEncryptionParams "keyid=\"http://example.org/bob/keys/123\";salt=\"XZwpw6o37R-6qoZjw6KwAw\"" `shouldBe` Just [ ("keyid", Just "http://example.org/bob/keys/123")
, ("salt", Just "XZwpw6o37R-6qoZjw6KwAw") ]
decodeEncryptionParams "keyid=\"mailto:[email protected]\"; salt=\"m2hJ_NttRtFyUiMRPwfpHA\"" `shouldBe` Just [ ("keyid", Just "mailto:[email protected]")
, ("salt", Just "m2hJ_NttRtFyUiMRPwfpHA")]
it "should encode encryption parameters correctly" $ do
encodeEncryptionParams [ ("keyid", Just "a1")
, ("salt", Just "b1") ] `shouldBe` "keyid=\"a1\"; salt=\"b1\""
|
nymacro/http-ece
|
tests/ECESpec.hs
|
bsd-3-clause
| 2,680 | 0 | 19 | 721 | 643 | 331 | 312 | 39 | 1 |
-- Execute doctest tests with no dependencies on doctest
-- TODO: move in a different doctest-static package
{-# LANGUAGE OverloadedStrings ,DeriveFunctor#-}
{-# LANGUAGE FlexibleInstances,UndecidableInstances #-}
-- move to doctest
module DocTest
( asPrint
, test
, testProp
, LineChunk(..)
, ExpectedLine(..)
)
where
import qualified Data.Text as T
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck
-- import Runner.Example
import Data.Char
import Data.List
import Data.String
class Print f where
asPrint :: f -> IO String
instance Show a => Print (IO a) where
asPrint io = io >>= return . show
instance {-# OVERLAPPABLE #-} Show a => Print a where
asPrint a = return (show a)
{-
-}
-- test :: TestName -> ExpectedResult -> IO String -> IO TestTree
test :: TestName -> String -> IO String -> IO TestTree
test loc expectedS valIO = do
let expected = read expectedS
actual <- lines <$> valIO
return $ testCase loc (mkResult expected actual @=? Equal)
-- return $ testCase loc (unlines exp @=? unlines actual)
testProp :: Testable t => TestName -> t -> IO TestTree
testProp loc = return . testProperty loc
-- Code copied and adapted by doctest
data Result = Equal | NotEqual [String]
deriving (Eq, Show,Read)
-- | Remove trailing white space from a string.
--
-- >>> stripEnd "foo "
-- "foo"
stripEnd :: String -> String
stripEnd = reverse . dropWhile isSpace . reverse
mkResult :: ExpectedResult -> [String] -> Result
mkResult expected actual | expected `matches` actual = Equal
| otherwise = NotEqual (formatNotEqual expected actual)
where
chunksMatch :: [LineChunk] -> String -> Bool
chunksMatch [] "" = True
chunksMatch [LineChunk xs] ys = stripEnd xs == stripEnd ys
chunksMatch (LineChunk x : xs) ys =
x `isPrefixOf` ys && xs `chunksMatch` drop (length x) ys
chunksMatch zs@(WildCardChunk : xs) (_ : ys) =
xs `chunksMatch` ys || zs `chunksMatch` ys
chunksMatch _ _ = False
matches :: ExpectedResult -> [String] -> Bool
matches (ExpectedLine x : xs) (y : ys) = x `chunksMatch` y && xs `matches` ys
matches (WildCardLine : xs) ys | xs `matches` ys = True
matches zs@(WildCardLine : _) (_ : ys) = zs `matches` ys
matches [] [] = True
matches [] _ = False
matches _ [] = False
formatNotEqual :: ExpectedResult -> [String] -> [String]
formatNotEqual expected_ actual =
formatLines "expected: " expected ++ formatLines " but got: " actual
where
expected :: [String]
expected = map
(\x -> case x of
ExpectedLine str -> concatMap lineChunkToString str
WildCardLine -> "..."
)
expected_
-- use show to escape special characters in output lines if any output line
-- contains any unsafe character
escapeOutput | any (not . isSafe) (concat $ expected ++ actual) = map show
| otherwise = id
isSafe :: Char -> Bool
isSafe c = c == ' ' || (isPrint c && (not . isSpace) c)
formatLines :: String -> [String] -> [String]
formatLines message xs = case escapeOutput xs of
y : ys -> (message ++ y) : map (padding ++) ys
[] -> [message]
where padding = replicate (length message) ' '
lineChunkToString :: LineChunk -> String
lineChunkToString WildCardChunk = "..."
lineChunkToString (LineChunk str) = str
-- import Control.DeepSeq (deepseq, NFData(rnf))
-- | A thing with a location attached.
data Located a = Located Location a
deriving (Eq, Show, Functor)
-- instance NFData a => NFData (Located a) where
-- rnf (Located loc a) = loc `deepseq` a `deepseq` ()
-- | Discard location information.
unLoc :: Located a -> a
unLoc (Located _ a) = a
-- | Add dummy location information.
noLocation :: a -> Located a
noLocation = Located (UnhelpfulLocation "<no location info>")
-- | A line number.
type Line = Int
-- | A combination of file name and line number.
data Location = UnhelpfulLocation String | Location FilePath Line
deriving Eq
instance Show Location where
show (UnhelpfulLocation s) = s
show (Location file line ) = file ++ ":" ++ show line
-- instance NFData Location where
-- rnf (UnhelpfulLocation str) = str `deepseq` ()
-- rnf (Location file line ) = file `deepseq` line `deepseq` ()
-- |
-- Create a list from a location, by repeatedly increasing the line number by
-- one.
enumerate :: Location -> [Location]
enumerate loc = case loc of
UnhelpfulLocation _ -> repeat loc
Location file line -> map (Location file) [line ..]
data DocTest = Example Expression ExpectedResult | Property Expression
deriving (Eq, Show,Read)
data LineChunk = LineChunk String | WildCardChunk
deriving (Show, Eq,Read)
instance IsString LineChunk where
fromString = LineChunk
data ExpectedLine = ExpectedLine [LineChunk] | WildCardLine
deriving (Show, Eq,Read)
instance IsString ExpectedLine where
fromString = ExpectedLine . return . LineChunk
type Expression = String
type ExpectedResult = [ExpectedLine]
|
tittoassini/flat
|
test/DocTest.hs
|
bsd-3-clause
| 5,171 | 0 | 13 | 1,253 | 1,404 | 753 | 651 | 99 | 10 |
{-# LANGUAGE OverloadedStrings #-}
module Text.LaTeX.Packages.Hyperref
( -- * Hyperref package
hyperref
-- * Hyperref commands
, HRefOption (..)
, URL
, createURL
, href
, url
, nolinkurl
, hyperbaseurl
, hyperimage
, autoref
, nameref
-- * Package options
, pdftex
, pdftitle
, pdfauthor
, pdfsubject
, pdfcreator
, pdfproducer
, pdfkeywords
, pdftrapped
, pdfstartpage
, pdfpagelayout
, PdfPageLayout(..)
) where
import Text.LaTeX.Base.Syntax
import Text.LaTeX.Base.Class
import Text.LaTeX.Base.Commands
import Text.LaTeX.Base.Render
import Text.LaTeX.Base.Types
import Data.Text (pack)
-- | The 'hyperref' package.
--
-- > usepackage [] hyperref
hyperref :: PackageName
hyperref = "hyperref"
data HRefOption =
PDFRemoteStartView
| PDFNewWindow
| HRefPage Int
deriving Show
instance Render HRefOption where
render PDFRemoteStartView = "pdfremotestartview"
render PDFNewWindow = "pdfnewwindow"
render (HRefPage n) = "page=" <> render n
newtype URL = URL String deriving Show
instance Render URL where
render (URL str) = fromString str
createURL :: String -> URL
createURL = URL
-- TODO: This function should check that the input
-- String is a valid URL.
-- | 'fromString' = 'createURL'.
instance IsString URL where
fromString = createURL
-- | Reference to an 'URL'.
href :: LaTeXC l => [HRefOption] -> URL -> l -> l
href options u = liftL $ \t -> TeXComm "href" [ MOptArg $ fmap rendertex options
, FixArg $ rendertex u
, FixArg t ]
-- | Write an 'URL' hyperlinked.
url :: LaTeXC l => URL -> l
url u = fromLaTeX $ TeXComm "url" [ FixArg $ rendertex u ]
-- | Write an 'URL' without creating a hyperlink.
nolinkurl :: LaTeXC l => URL -> l
nolinkurl u = fromLaTeX $ TeXComm "nolinkurl" [ FixArg $ rendertex u ]
-- | Establish a base 'URL'.
hyperbaseurl :: LaTeXC l => URL -> l
hyperbaseurl u = fromLaTeX $ TeXComm "hyperbaseurl" [ FixArg $ rendertex u ]
-- | @hyperimage imgURL t@:
-- The link to the image referenced by the @imgURL@ is inserted, using @t@ as the anchor.
hyperimage :: LaTeXC l => URL -> l -> l
hyperimage u = liftL $ \t -> TeXComm "hyperimage" [ FixArg $ rendertex u , FixArg t ]
-- | This is a replacement for the usual 'ref' command that places a contextual label in front of the reference.
autoref :: LaTeXC l => Label -> l
autoref l = fromLaTeX $ TeXComm "autoref" [ FixArg $ rendertex l ]
-- | Similar to 'autoref', but inserts text corresponding to the section name.
-- Note that this command comes from the /nameref/ package, but it's automatically
-- included when importing 'hyperref'.
nameref :: LaTeXC l => Label -> l
nameref l = fromLaTeX $ TeXComm "nameref" [ FixArg $ rendertex l ]
-- | Creates a single-parameter package option.
packageOption :: LaTeXC l => Text -> l -> l
packageOption n p = raw n <> raw "={" <> p <> raw "}"
-- | This package option selects the pdfTeX backend for the Hyperref package.
pdftex :: LaTeXC l => l
pdftex = raw "pdftex"
-- | This package option sets the document information Title field.
pdftitle :: LaTeXC l => l -> l
pdftitle = packageOption "pdftitle"
-- | This package option sets the document information Author field.
pdfauthor :: LaTeXC l => l -> l
pdfauthor = packageOption "pdfauthor"
-- | This package option sets the document information Subject field.
pdfsubject :: LaTeXC l => l -> l
pdfsubject = packageOption "pdfsubject"
-- | This package option sets the document information Creator field.
pdfcreator :: LaTeXC l => l -> l
pdfcreator = packageOption "pdfcreator"
-- | This package option sets the document information Producer field.
pdfproducer :: LaTeXC l => l -> l
pdfproducer = packageOption "pdfproducer"
-- | This package option sets the document information Keywords field.
pdfkeywords :: LaTeXC l => l -> l
pdfkeywords = packageOption "pdfkeywords"
-- | This package option sets the document information Trapped entry.
-- An 'Nothing' value means, the entry is not set.
pdftrapped :: LaTeXC l => Maybe Bool -> l
pdftrapped Nothing = packageOption "pdftrapped" mempty
pdftrapped (Just t) = packageOption "pdftrapped" . raw . pack . show $ t
-- | This package option determines on which page the PDF file is opened.
pdfstartpage :: LaTeXC l => l -> l
pdfstartpage = packageOption "pdfstartpage"
-- | This package option sets the layout of PDF pages.
pdfpagelayout :: LaTeXC l => PdfPageLayout -> l
pdfpagelayout l = packageOption "pdfpagelayout" . raw . pack . show $ l
-- | Specification for how pages of a PDF should be displayed.
data PdfPageLayout = SinglePage -- ^ Displays a single page; advancing flips the page.
| OneColumn -- ^ Displays a single page; advancing flips the page.
| TwoColumnLeft -- ^ Displays the document in two columns, odd-numbered pages to the left.
| TwoColumnRight -- ^ Displays the document in two columns, odd-numbered pages to the right.
| TwoPageLeft -- ^ Displays two pages, odd-numbered pages to the left (since PDF 1.5).
| TwoPageRight -- ^ Displays two pages, odd-numbered pages to the right (since PDF 1.5).
deriving (Eq, Ord, Read, Show)
|
dmcclean/HaTeX
|
Text/LaTeX/Packages/Hyperref.hs
|
bsd-3-clause
| 5,255 | 0 | 10 | 1,143 | 1,044 | 568 | 476 | 95 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE IncoherentInstances #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
-- |
-- Module : Data.Array.Accelerate.Trafo.Base
-- Copyright : [2012..2014] Manuel M T Chakravarty, Gabriele Keller, Trevor L. McDonell
-- License : BSD3
--
-- Maintainer : Manuel M T Chakravarty <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
module Data.Array.Accelerate.Trafo.Base (
-- Toolkit
Kit(..), Match(..), (:=:)(REFL),
avarIn, kmap,
-- Delayed Arrays
DelayedAcc, DelayedOpenAcc(..),
DelayedAfun, DelayedOpenAfun,
DelayedExp, DelayedFun, DelayedOpenExp, DelayedOpenFun,
-- Environments
Gamma(..), incExp, prjExp, lookupExp,
) where
-- standard library
import Prelude hiding ( until )
import Data.Hashable
import Text.PrettyPrint
-- friends
import Data.Array.Accelerate.AST
import Data.Array.Accelerate.Analysis.Match
import Data.Array.Accelerate.Array.Sugar ( Array, Arrays, Shape, Elt )
import Data.Array.Accelerate.Error
import Data.Array.Accelerate.Pretty.Print
import Data.Array.Accelerate.Trafo.Substitution
-- Toolkit
-- =======
-- The bat utility belt of operations required to manipulate terms parameterised
-- by the recursive closure.
--
class Kit acc where
inject :: PreOpenAcc acc aenv a -> acc aenv a
extract :: acc aenv a -> PreOpenAcc acc aenv a
--
rebuildAcc :: RebuildAcc acc
matchAcc :: MatchAcc acc
hashAcc :: HashAcc acc
prettyAcc :: PrettyAcc acc
instance Kit OpenAcc where
inject = OpenAcc
extract (OpenAcc pacc) = pacc
rebuildAcc = rebuildOpenAcc
matchAcc = matchOpenAcc
hashAcc = hashOpenAcc
prettyAcc = prettyOpenAcc
avarIn :: (Kit acc, Arrays arrs) => Idx aenv arrs -> acc aenv arrs
avarIn = inject . Avar
kmap :: Kit acc => (PreOpenAcc acc aenv a -> PreOpenAcc acc aenv b) -> acc aenv a -> acc aenv b
kmap f = inject . f . extract
-- A class for testing the equality of terms homogeneously, returning a witness
-- to the existentially quantified terms in the positive case.
--
class Match f where
match :: f s -> f t -> Maybe (s :=: t)
instance Match (Idx env) where
match = matchIdx
instance Kit acc => Match (PreOpenExp acc env aenv) where
match = matchPreOpenExp matchAcc hashAcc
instance Kit acc => Match (PreOpenFun acc env aenv) where
match = matchPreOpenFun matchAcc hashAcc
instance Kit acc => Match (PreOpenAcc acc aenv) where
match = matchPreOpenAcc matchAcc hashAcc
instance Kit acc => Match (acc aenv) where -- overlapping, undecidable, incoherent
match = matchAcc
-- Delayed Arrays
-- ==============
-- The type of delayed arrays. This representation is used to annotate the AST
-- in the recursive knot to distinguish standard AST terms from operand arrays
-- that should be embedded into their consumers.
--
type DelayedAcc = DelayedOpenAcc ()
type DelayedAfun = PreOpenAfun DelayedOpenAcc ()
type DelayedExp = DelayedOpenExp ()
type DelayedFun = DelayedOpenFun ()
type DelayedOpenAfun = PreOpenAfun DelayedOpenAcc
type DelayedOpenExp = PreOpenExp DelayedOpenAcc
type DelayedOpenFun = PreOpenFun DelayedOpenAcc
data DelayedOpenAcc aenv a where
Manifest :: PreOpenAcc DelayedOpenAcc aenv a -> DelayedOpenAcc aenv a
Delayed :: (Shape sh, Elt e) =>
{ extentD :: PreExp DelayedOpenAcc aenv sh
, indexD :: PreFun DelayedOpenAcc aenv (sh -> e)
, linearIndexD :: PreFun DelayedOpenAcc aenv (Int -> e)
} -> DelayedOpenAcc aenv (Array sh e)
instance Kit DelayedOpenAcc where
inject = Manifest
extract = error "DelayedAcc.extract"
--
rebuildAcc = rebuildDelayed
matchAcc = matchDelayed
hashAcc = hashDelayed
prettyAcc = prettyDelayed
hashDelayed :: HashAcc DelayedOpenAcc
hashDelayed (Manifest pacc) = hash "Manifest" `hashWithSalt` hashPreOpenAcc hashAcc pacc
hashDelayed Delayed{..} = hash "Delayed" `hashE` extentD `hashF` indexD `hashF` linearIndexD
where
hashE salt = hashWithSalt salt . hashPreOpenExp hashAcc
hashF salt = hashWithSalt salt . hashPreOpenFun hashAcc
matchDelayed :: MatchAcc DelayedOpenAcc
matchDelayed (Manifest pacc1) (Manifest pacc2)
= matchPreOpenAcc matchAcc hashAcc pacc1 pacc2
matchDelayed (Delayed sh1 ix1 lx1) (Delayed sh2 ix2 lx2)
| Just REFL <- matchPreOpenExp matchAcc hashAcc sh1 sh2
, Just REFL <- matchPreOpenFun matchAcc hashAcc ix1 ix2
, Just REFL <- matchPreOpenFun matchAcc hashAcc lx1 lx2
= Just REFL
matchDelayed _ _
= Nothing
rebuildDelayed :: RebuildAcc DelayedOpenAcc
rebuildDelayed v acc = case acc of
Manifest pacc -> Manifest (rebuildA rebuildDelayed v pacc)
Delayed{..} -> Delayed (rebuildEA rebuildDelayed v extentD)
(rebuildFA rebuildDelayed v indexD)
(rebuildFA rebuildDelayed v linearIndexD)
-- Note: If we detect that the delayed array is simply accessing an array
-- variable, then just print the variable name. That is:
--
-- > let a0 = <...> in map f (Delayed (shape a0) (\x0 -> a0!x0))
--
-- becomes
--
-- > let a0 = <...> in map f a0
--
prettyDelayed :: PrettyAcc DelayedOpenAcc
prettyDelayed alvl wrap acc = case acc of
Manifest pacc -> prettyPreAcc prettyDelayed alvl wrap pacc
Delayed sh f _
| Shape a <- sh
, Just REFL <- match f (Lam (Body (Index a (Var ZeroIdx))))
-> prettyDelayed alvl wrap a
| otherwise
-> wrap $ hang (text "Delayed") 2
$ sep [ prettyPreExp prettyDelayed 0 alvl parens sh
, parens (prettyPreFun prettyDelayed alvl f)
]
-- Environments
-- ============
-- An environment that holds let-bound scalar expressions. The second
-- environment variable env' is used to project out the corresponding
-- index when looking up in the environment congruent expressions.
--
data Gamma acc env env' aenv where
EmptyExp :: Gamma acc env env' aenv
PushExp :: Gamma acc env env' aenv
-> PreOpenExp acc env aenv t
-> Gamma acc env (env', t) aenv
incExp :: Gamma acc env env' aenv -> Gamma acc (env, s) env' aenv
incExp EmptyExp = EmptyExp
incExp (PushExp env e) = incExp env `PushExp` weakenE SuccIdx e
prjExp :: Idx env' t -> Gamma acc env env' aenv -> PreOpenExp acc env aenv t
prjExp ZeroIdx (PushExp _ v) = v
prjExp (SuccIdx ix) (PushExp env _) = prjExp ix env
prjExp _ _ = $internalError "prjExp" "inconsistent valuation"
lookupExp :: Kit acc => Gamma acc env env' aenv -> PreOpenExp acc env aenv t -> Maybe (Idx env' t)
lookupExp EmptyExp _ = Nothing
lookupExp (PushExp env e) x
| Just REFL <- match e x = Just ZeroIdx
| otherwise = SuccIdx `fmap` lookupExp env x
|
kumasento/accelerate
|
Data/Array/Accelerate/Trafo/Base.hs
|
bsd-3-clause
| 7,279 | 0 | 20 | 1,812 | 1,756 | 933 | 823 | -1 | -1 |
module MacrosNew where
import GOTO
import Data.List
-- * Implementación Macros GOTO
-- ============================
-- | Instrucciones con macros.
data InstM = IncM Variable Etiqueta
| DecM Variable Etiqueta
| CondM Etiqueta Variable Etiqueta
| Macro Etiqueta [Variable] [InstM]
| SKIPM Etiqueta
deriving Eq
-- | Representación por pantalla.
instance Show InstM where
show (IncM v l) = show l ++ " " ++ show v ++ "<-"
++ show v ++"+" ++ (show 1)
show (DecM v l) = show l ++ " " ++show v ++ "<-"
++ show v ++"-" ++ (show 1)
show (CondM l v l') = show l ++ " " ++ "IF" ++ " "
++ show v ++ "/=" ++ (show 0)
++" "++ "GOTO" ++" " ++ show l'
show (SKIPM l) = show l ++ " " ++ "Y <- Y"
show (Macro (E "" n) vs [i]) = show i
show (Macro e@(E "" n) vs (i:is)) =
show i ++ "\n" ++ show (Macro e vs is)
show (Macro e vs [i]) = show e ++ show i
show (Macro e vs (i:is)) = show e ++ show i ++ "\n" ++
show (Macro e vs is)
-- | Ejemplos
-- >>> IncM x (E "A" 0)
-- [A] X<-X+1
-- >>> DecM y (E "B" 4)
-- [B4] Y<-Y-1
-- >>> CondM (E "" 0) x (E "A" 0)
-- IF X/=0 GOTO [A]
-- >>> Macro (E "A" 0) [] [IncM x (E "" 0), DecM x (E "B" 0), CondM (E "" 0) z (E "B" 3)]
-- [A] X<-X+1
-- [A] [B] X<-X-1
-- [A] IF Z/=0 GOTO [B3]
-- | Programas con macros.
data ProgramaM = Pm [InstM]
-- | Representación de programas con macros.
instance Show ProgramaM where
show (Pm [i]) = show i
show (Pm (i:is)) = (show i) ++ "\n" ++ (show (Pm is))
-- | Definimos las macros Y<-X y GOTO "E".
valX :: Etiqueta -> InstM
valX e = Macro e [] [CondM (E [] 0) x (E "A" 0),
IncM z (E [] 0),
CondM (E [] 0) z (E "E" 0),
DecM x (E "A" 0),
IncM y (E [] 0),
CondM (E [] 0) x (E "A" 0)]
goto :: Etiqueta -> Etiqueta -> InstM
goto e1 e2 = Macro e1 [] [IncM z (E [] 0),
CondM (E [] 0) z e2]
-- | Macro V <- V'.
valV v v' e = Macro e [v,v'] [DecM v (E "A" 1),
CondM (E "" 0) v (E "A" 1),
CondM (E "A" 0) v' (E "B" 0),
IncM (VarWork [10]) (E [] 0),
CondM (E [] 0) (VarWork [10]) (E "C" 0),
DecM v' (E "B" 0),
IncM v (E "" 0),
IncM (VarWork [14]) (E "" 0),
IncM (VarWork [11]) (E [] 0),
CondM (E [] 0) (VarWork [11]) (E "A" 0),
CondM (E "C" 0) (VarWork [14]) (E "D" 0),
IncM (VarWork [12]) (E [] 0),
CondM (E [] 0) (VarWork [12]) (E "Q" 0),
DecM (VarWork [14]) (E "D" 0),
IncM v' (E "" 0),
IncM (VarWork [13]) (E [] 0),
CondM (E [] 0) (VarWork [13]) (E "C" 0),
IncM (VarWork [15]) (E "Q" 0)]
-----------------------------------------------------------------------
--
-- * Normalización de macros
-- =========================
-- ** Normalización de índices de variables de trabajo
-- ==================================================
-- | La función (susVar v v1 i) sustituye la variable v1 por v en la
-- instrucción i.
susVar :: Variable -> Variable -> InstM -> InstM
susVar v1 v i | v1 == v = i
susVar v1 v i@(IncM v' e) | v' == v1 = IncM v e
| otherwise = i
susVar v1 v i@(DecM v' e) | v' == v1 = DecM v e
| otherwise = i
susVar v1 v i@(CondM e v' e') | v' == v1 = CondM e v e'
| otherwise = i
susVar v1 v (Macro e vs is) = Macro e vs (aux is)
where
aux [i] = [susVar v1 v i]
aux (i:is) = (susVar v1 v i): aux is
susVar v1 v (SKIPM e) = SKIPM e
-- | Ejemplos
-- >>> IncM x (E "" 0)
-- X<-X+1
-- >>> susVar x (VarIn [2]) (IncM x (E "" 0))
-- X2<-X2+1
-- | La función (varsInstM i) calcula la lista de las variables de la
-- instrucción i, si es una macro, no aparecerán aquellas de la lista de
-- variables de trabajo auxiliares.
varsInstM :: InstM -> [Variable]
varsInstM (IncM v _) = [v]
varsInstM (DecM v _) = [v]
varsInstM (CondM e v e') = [v]
varsInstM (Macro e vs is) = nub (concat ( map (varsInstM ) is) ) \\ vs
varsInstM (SKIPM e) = []
-- | Ejemplos
-- >>> varsInstM (IncM x (E "" 0))
-- [X]
-- >>> varsInstM (valX (E "" 0))
-- [X,Z,Y]
-- | La función (varTrab is) calcula la lista de las variables de
-- trabajo de una lista de instrucciones.
varTrab :: [InstM] -> [Variable]
varTrab is = nub [ v | v <- vs, esZ v]
where
vs = concat (map (varsInstM) is)
-- | La función (paresVars n vs) calcula a partir de una lista de
-- variables de trabajo vs, pares formados por la variable y su
-- normalizada.
paresVars :: Int -> [Variable] -> [(Variable, Variable)]
paresVars n vs = [(v,aux v) | v <- vs]
where
aux v = VarWork [indice v +n]
-- | Ejemplos
-- >>> paresVars 5 [z,VarWork [2], VarWork [6]]
-- [(Z,Z5),(Z2,Z7),(Z6,Z11)]
-- | La función (normInd n is vs) normaliza las variables de las
-- instrucciones de is mediante los pares de vs, según el entero n.
normInd :: Int -> [InstM] -> [(Variable, Variable)] -> [InstM]
normInd n is [] = is
normInd n is (v:vs) = normInd n [susVar (fst v) (snd v) i | i<- is] vs
-- | Ejemplos
-- >>> normInd 5 [IncM z (E "" 0), DecM z (E "" 0), Macro (E "" 0) [] [IncM z (E "B" 0), DecM z (E "" 0)]] [(z, VarWork [2])]
-- [ Z2<-Z2+1, Z2<-Z2-1,[B] Z2<-Z2+1
-- Z2<-Z2-1]
-- | La función (normalizaIndices n macro) normaliza los índices de las
-- variables de la macro según un entero n.
normalizaIndices :: Int -> InstM -> InstM
normalizaIndices n (Macro e vs' is) = Macro e vs' (normInd n is vs)
where
vs = paresVars n ((varTrab is) \\ vs')
-- | Ejemplos
-- >>> normalizaIndices 5 (valX (E "" 0))
-- IF X/=0 GOTO [A]
-- Z5<-Z5+1
-- IF Z5/=0 GOTO [E]
-- [A] X<-X-1
-- Y<-Y+1
-- IF X/=0 GOTO [A]
-- >>> normalizaIndices 5 (valV z (VarWork [2]) (E "" 0))
-- [A] IF Z2/=0 GOTO [B]
-- Z<-Z+1
-- IF Z/=0 GOTO [C]
-- [B] Z2<-Z2-1
-- Z<-Z+1
-- Z<-Z+1
-- Z<-Z+1
-- IF Z/=0 GOTO [A]
-- [C] IF Z/=0 GOTO [D]
-- Z<-Z+1
-- IF Z/=0 GOTO [E]
-- [D] Z<-Z-1
-- Z2<-Z2+1
-- Z<-Z+1
-- IF Z/=0 GOTO [C]
-- | La función (esM m) determina si m es una macro.
esM :: InstM -> Bool
esM (Macro _ _ _) = True
esM _ = False
-- | La función (maximoInd is) calcula el índice mayor de las variables
-- de trabajo de la lista de instrucciones is.
maximoInd :: [InstM] -> Int
maximoInd is = maximum [indice v | v <- varTrab is]
-- | La función (normalizaIndPm pm) normaliza los índices de las variables
-- de trabajo de las macros del programa pm.
normalizaIndPm :: ProgramaM -> ProgramaM
normalizaIndPm (Pm is) = Pm (aux n is)
where
n = maximoInd is +1
aux n [] = []
aux n (i:is) | esM i = (normalizaIndices n i):
(aux (maximoInd [normalizaIndices n i]+1) is)
| otherwise = i: (aux n is)
-- ** Normalización etiquetas
-- =========================
-- | La función (etiquetaM i) devuelve la lista de las etiquetas de la
-- instrucción i.
etiquetaM :: InstM -> [Etiqueta]
etiquetaM (IncM _ e) = [e]
etiquetaM (DecM _ e) = [e]
etiquetaM (CondM e1 _ e2) = [e1,e2]
etiquetaM (SKIPM e) = [e]
etiquetaM (Macro _ _ is) = concat (map (etiquetaM) is)
-- | La función (indexEt e) devuelve el índice de la etiqueta e.
indexEt :: Etiqueta -> Int
indexEt (E _ n) = n
-- | La función (maxIndexEt es) calcula el máximo índice de las
-- etiquetas de una listas de etiquetas.
maxIndexEt :: [Etiqueta] -> Int
maxIndexEt es = maximum [indexEt e | e <- es]
-- | La función (susEt e e' i) sustituye la etiqueta e por e' en la
-- instrucción i.
susEt :: Etiqueta -> Etiqueta -> InstM -> InstM
susEt e e' i | e == e' = i
susEt e e' i@(IncM v e1) | e1 == e = IncM v e'
| otherwise = i
susEt e e' i@(DecM v e1) | e1 == e = DecM v e'
| otherwise = i
susEt e e' i@(CondM e1 v e2) | e1 == e = susEt e e' (CondM e' v e2)
| e2 == e = susEt e e' (CondM e1 v e')
| otherwise = i
susEt e e' (Macro e1 vs is) = Macro e1 vs (aux is)
where
aux [i] = [susEt e e' i]
aux (i:is) = (susEt e e' i): aux is
susEt e e' (SKIPM e1) | e1 == e = SKIPM e'
| otherwise = SKIPM e1
-- | La función (paresEt n es) calcula a partir de una lista de
-- etiquetas es, pares formados por la etiqueta y su normalizada.
paresEt :: Int -> [Etiqueta] -> [(Etiqueta,Etiqueta)]
paresEt n es = [(e, aux e) | e <- es]
where
aux (E str n') = E str (n'+n)
-- | La función (normEt n is es) normaliza las etiquetas de las
-- instrucciones de is mediante los pares de es, según el entero n.
normEt :: Int -> [InstM] -> [(Etiqueta, Etiqueta)] -> [InstM]
normEt n is [] = is
normEt n is (e:es) = normEt n [susEt (fst e) (snd e) i | i <- is] es
-- | La función (normalizaIndicesEt n i) es la normalización de los
-- índices de las etiquetas de i.
normalizaIndicesEt :: Int -> InstM -> InstM
normalizaIndicesEt n (Macro e vs is) = Macro e vs (normEt n is es)
where
es = paresEt n (concat (map (etiquetaM) is))
-- | La función (normEtPm pm) normaliza las etiquetas del programa pm.
normEtPm :: ProgramaM -> ProgramaM
normEtPm (Pm is) = Pm (aux n is)
where
n = maxIndexEt (concat (map (etiquetaM) is))+1
aux n [] = []
aux n (i:is)
| esM i = (normalizaIndicesEt n i):
(aux (maxIndexEt
(concat [etiquetaM
(normalizaIndicesEt n i)])+1) is)
| otherwise = i: (aux n is)
-- | La función (normM pm) genera la expansión normalizada del programa
-- pm.
normM :: ProgramaM -> ProgramaM
normM = normEtPm . normalizaIndPm
-- | Ejemplos
-- >>> let p =Pm [IncM z (E "" 0), valV x z (E "A" 0), DecM x (E "B" 0)]
-- >>> normM p
-- Z<-Z+1
-- [A] [A1] IF Z1/=0 GOTO [B1]
-- [A] Z1<-Z1+1
-- IF Z1/=0 GOTO [C1]
-- [A] [B1] Z1<-Z1-1
-- [A] X<-X+1
-- [A] Z1<-Z1+1
-- [A] Z1<-Z1+1
-- IF Z1/=0 GOTO [A1]
-- [A] [C1] IF Z1/=0 GOTO [D1]
-- [A] Z1<-Z1+1
-- IF Z1/=0 GOTO [E1]
-- [A] [D1] Z1<-Z1-1
-- [A] Z1<-Z1+1
-- [A] Z1<-Z1+1
-- IF Z1/=0 GOTO [C1]
-- [B] X<-X-1
-- | La función (noEsVacia e) determina si la etiqueta e tiene nombre.
noEsVacia :: Etiqueta -> Bool
noEsVacia (E [] _) = False
noEsVacia _ = True
-- | La función (normEtMAux m) genera una macro cuya primera instrucción tiene la misma etiqueta que la macro.
normEtMAux :: InstM -> InstM
normEtMAux (Macro e vs ins@(i:is))
| not (noEsVacia e) = Macro e vs ins
| noEsVacia (head (etiquetaM i)) && noEsVacia e =
Macro e vs (map (susEt (head (etiquetaM i)) e) ins )
| otherwise = Macro e vs ((susEt (head (etiquetaM i)) e i):is)
normEtMAux i = i
-- | La función (instDeMacro m) obtiene la lista de instrucciones de la macro m.
instDeMacro :: InstM -> [InstM]
instDeMacro (Macro _ _ v) = v
-- | La función (instM2inst i) convierte instrucciones tipo macro a
-- instrucciones.
instM2inst :: InstM -> [Instruccion]
instM2inst (IncM v e) = [Incremento v e]
instM2inst (DecM v e) = [Decremento v e]
instM2inst (CondM e v e') = [Condicional e v e']
instM2inst (SKIPM e) = [SKIP e]
instM2inst m@(Macro e vs v) =
concat (map (instM2inst) (instDeMacro (normEtMAux m)))
-- | La función (progM2progAux p) convierte programas con macros a
-- programas sin macros.
progM2progAux :: ProgramaM -> Programa
progM2progAux (Pm is) = Pr (concat (map (instM2inst) is))
-- | La función (progM2prog p) convierte programas con macros a
-- programas sin macros, con normalización previa.
progM2prog :: ProgramaM -> Programa
progM2prog = progM2progAux . normM
-- | Ejemplo
-- >>> let p =Pm [IncM z (E "" 0), valV x z (E "A" 0), DecM x (E "B" 0)]
-- >>> progM2prog p
-- Z<-Z+1
-- [A] IF Z1/=0 GOTO [B1]
-- Z1<-Z1+1
-- IF Z1/=0 GOTO [C1]
-- [B1] Z1<-Z1-1
-- X<-X+1
-- Z1<-Z1+1
-- Z1<-Z1+1
-- IF Z1/=0 GOTO [A]
-- [C1] IF Z1/=0 GOTO [D1]
-- Z1<-Z1+1
-- IF Z1/=0 GOTO [E1]
-- [D1] Z1<-Z1-1
-- Z1<-Z1+1
-- Z1<-Z1+1
-- IF Z1/=0 GOTO [C1]
-- [B] X<-X-1
-- >>> let p = Pm [Macro (E "" 0) [] [IncM x (E "" 0), Macro (E "" 0) [] [IncM x (E "" 0), Macro (E "" 0) [] [IncM x (E "" 0)]]]]
-- >>> progM2prog p
-- X<-X+1
-- X<-X+1
-- X<-X+1
-- | Ejemplo
-- >>> let p = progM2prog (Pm [valV z x (E "" 0) ,valV y z (E "" 0) ])
-- >>> p
-- [A3] Z<-Z-1
-- IF Z/=0 GOTO [A3]
-- [A2] IF X/=0 GOTO [B2]
-- Z26<-Z26+1
-- IF Z26/=0 GOTO [C2]
-- [B2] X<-X-1
-- Z<-Z+1
-- Z30<-Z30+1
-- Z27<-Z27+1
-- IF Z27/=0 GOTO [A2]
-- [C2] IF Z30/=0 GOTO [D2]
-- Z28<-Z28+1
-- IF Z28/=0 GOTO [Q2]
-- [D2] Z30<-Z30-1
-- X<-X+1
-- Z29<-Z29+1
-- IF Z29/=0 GOTO [C2]
-- [Q2] Z31<-Z31+1
-- [A5] Y<-Y-1
-- IF Y/=0 GOTO [A5]
-- [A4] IF Z/=0 GOTO [B4]
-- Z42<-Z42+1
-- IF Z42/=0 GOTO [C4]
-- [B4] Z<-Z-1
-- Y<-Y+1
-- Z46<-Z46+1
-- Z43<-Z43+1
-- IF Z43/=0 GOTO [A4]
-- [C4] IF Z46/=0 GOTO [D4]
-- Z44<-Z44+1
-- IF Z44/=0 GOTO [Q4]
-- [D4] Z46<-Z46-1
-- Z<-Z+1
-- Z45<-Z45+1
-- IF Z45/=0 GOTO [C4]
-- [Q4] Z47<-Z47+1
-- >>> ejecutaP p [(z,0),(x,7),(VarWork [26],0),(VarWork [30],0),(VarWork [27],0),(VarWork [28],0),(VarWork [29],0),(VarWork [31],0),(VarWork [42],0),(VarWork [46],0),(VarWork [43],0),(VarWork [44],0),(VarWork [45],0),(VarWork [47],0),(y,0)]
-- (Y,7)
|
EduPH/ModelosComputacionales
|
src/MacrosNew.hs
|
bsd-3-clause
| 14,173 | 0 | 19 | 4,494 | 3,908 | 2,069 | 1,839 | 166 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : $Header$
Description : RDF Morphism
Copyright : (c) Francisc-Nicolae Bungiu, Felix Gabriel Mance, 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Morphisms for RDF
-}
module RDF.Morphism where
import Common.DocUtils
import Common.Doc
{-
import Common.Lib.State
import Common.Lib.MapSet (setToMap)
import Common.Result
import OWL2.AS
import RDF.AS
-}
import RDF.Sign
import RDF.Function
{- import RDF.StaticAnalysis
import RDF.Symbols -}
import RDF.Print ()
{- }
import Control.Monad
import Data.Maybe
-}
import Data.Data
import qualified Data.Map as Map
import qualified Data.Set as Set
data RDFMorphism = RDFMorphism
{ osource :: Sign
, otarget :: Sign
, mmaps :: MorphMap
} deriving (Show, Eq, Ord, Typeable, Data)
{- }
inclRDFMorphism :: Sign -> Sign -> RDFMorphism
inclRDFMorphism s t = RDFMorphism
{ osource = s
, otarget = t
, mmaps = Map.empty }
symMap :: MorphMap -> Map.Map RDFEntity RDFEntity
symMap = Map.mapWithKey (\ (RDFEntity ty _) -> RDFEntity ty)
inducedElems :: MorphMap -> [RDFEntity]
inducedElems = Map.elems . symMap
inducedSign :: MorphMap -> Sign -> Sign
inducedSign m = execState (do
mapM_ (modEntity Set.delete) $ Map.keys m
mapM_ (modEntity Set.insert) $ inducedElems m)
inducedFromMor :: Map.Map RawSymb RawSymb -> Sign -> Result RDFMorphism
inducedFromMor rm sig = do
let syms = symOf sig
mm <- foldM (\ m p -> case p of
(ASymbol s@(RDFEntity _ v), ASymbol (RDFEntity _ u)) ->
if Set.member s syms
then return $ if u == v then m else Map.insert s u m
else fail $ "unknown symbol: " ++ showDoc s "\n" ++ shows sig ""
(AnUri v, AnUri u) -> case filter (`Set.member` syms)
$ map (`RDFEntity` v) rdfEntityTypes of
[] -> fail $ "unknown symbol: " ++ showDoc v "\n" ++ shows sig ""
l -> return $ if u == v then m else foldr (`Map.insert` u) m l
_ -> error "RDF.Morphism.inducedFromMor") Map.empty $ Map.toList rm
return RDFMorphism
{ osource = sig
, otarget = inducedSign mm sig
, mmaps = mm }
symMapOf :: RDFMorphism -> Map.Map RDFEntity RDFEntity
symMapOf mor = Map.union (symMap $ mmaps mor) $ setToMap $ symOf $ osource mor
-}
isRDFInclusion :: RDFMorphism -> Bool
isRDFInclusion m = Map.null (mmaps m) && isSubSign (osource m) (otarget m)
instance Pretty RDFMorphism where
pretty m = let
s = osource m
srcD = specBraces $ space <> pretty s
t = otarget m
in fsep $ if isRDFInclusion m then
if isSubSign t s then
[text "identity morphism over", srcD]
else
[ text "inclusion morphism of"
, srcD
, text "extended with"
, pretty $ Set.difference (symOf t) $ symOf s ]
else
[ pretty $ mmaps m
, colon <+> srcD, mapsto <+> specBraces (space <> pretty t) ]
{-
legalMor :: RDFMorphism -> Result ()
legalMor m = let mm = mmaps m in unless
(Set.isSubsetOf (Map.keysSet mm) (symOf $ osource m)
&& Set.isSubsetOf (Set.fromList $ inducedElems mm) (symOf $ otarget m))
$ fail "illegal RDF morphism"
composeMor :: RDFMorphism -> RDFMorphism -> Result RDFMorphism
composeMor m1 m2 =
let nm = Set.fold (\ s@(RDFEntity ty u) -> let
t = getIri ty u $ mmaps m1
r = getIri ty t $ mmaps m2
in if r == u then id else Map.insert s r) Map.empty
. symOf $ osource m1
in return m1
{ otarget = otarget m2
, mmaps = nm }
cogeneratedSign :: Set.Set RDFEntity -> Sign -> Result RDFMorphism
cogeneratedSign s sign =
let sig2 = execState (mapM_ (modEntity Set.delete) $ Set.toList s) sign
in if isSubSign sig2 sign then return $ inclRDFMorphism sig2 sign else
fail "non RDF subsignatures for (co)generatedSign"
generatedSign :: Set.Set RDFEntity -> Sign -> Result RDFMorphism
generatedSign s sign = cogeneratedSign (Set.difference (symOf sign) s) sign
matchesSym :: RDFEntity -> RawSymb -> Bool
matchesSym e@(RDFEntity _ u) r = case r of
ASymbol s -> s == e
AnUri s -> s == u || namePrefix u == localPart s && null (namePrefix s)
statSymbItems :: [SymbItems] -> [RawSymb]
statSymbItems = concatMap
$ \ (SymbItems m us) -> case m of
Nothing -> map AnUri us
Just ty -> map (ASymbol . RDFEntity ty) us
statSymbMapItems :: [SymbMapItems] -> Result (Map.Map RawSymb RawSymb)
statSymbMapItems =
foldM (\ m (s, t) -> case Map.lookup s m of
Nothing -> return $ Map.insert s t m
Just u -> case (u, t) of
(AnUri su, ASymbol (RDFEntity _ tu)) | su == tu ->
return $ Map.insert s t m
(ASymbol (RDFEntity _ su), AnUri tu) | su == tu -> return m
_ -> if u == t then return m else
fail $ "differently mapped symbol: " ++ showDoc s "\nmapped to "
++ showDoc u " and " ++ showDoc t "")
Map.empty
. concatMap (\ (SymbMapItems m us) ->
let ps = map (\ (u, v) -> (u, fromMaybe u v)) us in
case m of
Nothing -> map (\ (s, t) -> (AnUri s, AnUri t)) ps
Just ty ->
let mS = ASymbol . RDFEntity ty
in map (\ (s, t) -> (mS s, mS t)) ps)
mapSen :: RDFMorphism -> Axiom -> Result Axiom
mapSen m a = return $ function Rename (MorphMap $ mmaps m) a
-}
|
mariefarrell/Hets
|
RDF/Morphism.hs
|
gpl-2.0
| 5,404 | 0 | 16 | 1,422 | 329 | 181 | 148 | 31 | 1 |
{-| Implementation of the Ganeti Query2 basic types.
These are types internal to the library, and for example clients that
use the library should not need to import it.
-}
{-
Copyright (C) 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 Ganeti.Query.Types
( FieldGetter(..)
, QffMode(..)
, FieldData
, FieldList
, FieldMap
, isRuntimeField
) where
import qualified Data.Map as Map
import Ganeti.Query.Language
import Ganeti.Objects
-- | The type of field getters. The \"a\" type represents the type
-- we're querying, whereas the \"b\" type represents the \'runtime\'
-- data for that type (if any). Note that we don't support multiple
-- runtime sources, and we always consider the entire configuration as
-- a given (so no equivalent for Python's /*_CONFIG/ and /*_GROUP/;
-- configuration accesses are cheap for us).
data FieldGetter a b = FieldSimple (a -> ResultEntry)
| FieldRuntime (b -> a -> ResultEntry)
| FieldConfig (ConfigData -> a -> ResultEntry)
| FieldUnknown
-- | Type defining how the value of a field is used in filtering. This
-- implements the equivalent to Python's QFF_ flags, except that we
-- don't use OR-able values.
data QffMode = QffNormal -- ^ Value is used as-is in filters
| QffTimestamp -- ^ Value is a timestamp tuple, convert to float
| QffHostname -- ^ Value is a hostname, compare it smartly
deriving (Show, Eq)
-- | Alias for a field data (definition and getter).
type FieldData a b = (FieldDefinition, FieldGetter a b, QffMode)
-- | Alias for a field data list.
type FieldList a b = [FieldData a b]
-- | Alias for field maps.
type FieldMap a b = Map.Map String (FieldData a b)
-- | Helper function to check if a getter is a runtime one.
isRuntimeField :: FieldGetter a b -> Bool
isRuntimeField (FieldRuntime _) = True
isRuntimeField _ = False
|
vladimir-ipatov/ganeti
|
src/Ganeti/Query/Types.hs
|
gpl-2.0
| 2,606 | 0 | 9 | 578 | 246 | 155 | 91 | 24 | 1 |
{-
Safe/Boot.hs - as in BootTidal but in the Op monad
Copyright (C) 2021 Johannes Waldmann and contributors
Forked from:
https://github.com/jwaldmann/safe-tidal-cli/
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This library 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 library. If not, see <http://www.gnu.org/licenses/>.
-}
{-# language NoMonomorphismRestriction #-}
module Sound.Tidal.Safe.Boot where
import Sound.Tidal.Safe.Context
import qualified Sound.Tidal.Transition
-- everyone is missing the tidal :: Stream argument
-- this will be provided by the Reader monad
p = streamReplace
hush = streamHush
list = streamList
mute = streamMute
unmute = streamUnmute
solo = streamSolo
unsolo = streamUnsolo
once = streamOnce
first = streamFirst
asap = once
nudgeAll = streamNudgeAll
all = streamAll
resetCycles = streamResetCycles
setcps = asap . cps
xfade i = transition True (Sound.Tidal.Transition.xfadeIn 4) i
xfadeIn i t = transition True (Sound.Tidal.Transition.xfadeIn t) i
histpan i t = transition True (Sound.Tidal.Transition.histpan t) i
wait i t = transition True (Sound.Tidal.Transition.wait t) i
waitT i f t = transition True (Sound.Tidal.Transition.waitT f t) i
jump i = transition True (Sound.Tidal.Transition.jump) i
jumpIn i t = transition True (Sound.Tidal.Transition.jumpIn t) i
jumpIn' i t = transition True (Sound.Tidal.Transition.jumpIn' t) i
jumpMod i t = transition True (Sound.Tidal.Transition.jumpMod t) i
mortal i lifespan release = transition True (Sound.Tidal.Transition.mortal lifespan release) i
interpolate i = transition True (Sound.Tidal.Transition.interpolate) i
interpolateIn i t = transition True (Sound.Tidal.Transition.interpolateIn t) i
clutch i = transition True (Sound.Tidal.Transition.clutch) i
clutchIn i t = transition True (Sound.Tidal.Transition.clutchIn t) i
anticipate i = transition True (Sound.Tidal.Transition.anticipate) i
anticipateIn i t = transition True (Sound.Tidal.Transition.anticipateIn t) i
forId i t = transition False (Sound.Tidal.Transition.mortalOverlay t) i
d1 = p 1 . (|< orbit 0)
d2 = p 2 . (|< orbit 1)
d3 = p 3 . (|< orbit 2)
d4 = p 4 . (|< orbit 3)
d5 = p 5 . (|< orbit 4)
d6 = p 6 . (|< orbit 5)
d7 = p 7 . (|< orbit 6)
d8 = p 8 . (|< orbit 7)
d9 = p 9 . (|< orbit 8)
d10 = p 10 . (|< orbit 9)
d11 = p 11 . (|< orbit 10)
d12 = p 12 . (|< orbit 11)
d13 = p 13
d14 = p 14
d15 = p 15
d16 = p 16
setI = streamSetI
setF = streamSetF
setS = streamSetS
setR = streamSetR
setB = streamSetB
|
bgold-cosmos/Tidal
|
src/Sound/Tidal/Safe/Boot.hs
|
gpl-3.0
| 2,975 | 0 | 8 | 539 | 830 | 448 | 382 | 56 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.EMR.RunJobFlow
-- 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.
-- | RunJobFlow creates and starts running a new job flow. The job flow will run
-- the steps specified. Once the job flow completes, the cluster is stopped and
-- the HDFS partition is lost. To prevent loss of data, configure the last step
-- of the job flow to store results in Amazon S3. If the 'JobFlowInstancesConfig' 'KeepJobFlowAliveWhenNoSteps' parameter is set to 'TRUE', the job flow will transition to the WAITING state
-- rather than shutting down once the steps have completed.
--
-- For additional protection, you can set the 'JobFlowInstancesConfig' 'TerminationProtected' parameter to 'TRUE' to lock the job flow and prevent it from being terminated
-- by API call, user intervention, or in the event of a job flow error.
--
-- A maximum of 256 steps are allowed in each job flow.
--
-- If your job flow is long-running (such as a Hive data warehouse) or complex,
-- you may require more than 256 steps to process your data. You can bypass the
-- 256-step limitation in various ways, including using the SSH shell to connect
-- to the master node and submitting queries directly to the software running on
-- the master node, such as Hive and Hadoop. For more information on how to do
-- this, go to <http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/AddMoreThan256Steps.html Add More than 256 Steps to a Job Flow> in the /Amazon ElasticMapReduce Developer's Guide/.
--
-- For long running job flows, we recommend that you periodically store your
-- results.
--
-- <http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_RunJobFlow.html>
module Network.AWS.EMR.RunJobFlow
(
-- * Request
RunJobFlow
-- ** Request constructor
, runJobFlow
-- ** Request lenses
, rjfAdditionalInfo
, rjfAmiVersion
, rjfBootstrapActions
, rjfInstances
, rjfJobFlowRole
, rjfLogUri
, rjfName
, rjfNewSupportedProducts
, rjfServiceRole
, rjfSteps
, rjfSupportedProducts
, rjfTags
, rjfVisibleToAllUsers
-- * Response
, RunJobFlowResponse
-- ** Response constructor
, runJobFlowResponse
-- ** Response lenses
, rjfrJobFlowId
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.EMR.Types
import qualified GHC.Exts
data RunJobFlow = RunJobFlow
{ _rjfAdditionalInfo :: Maybe Text
, _rjfAmiVersion :: Maybe Text
, _rjfBootstrapActions :: List "BootstrapActions" BootstrapActionConfig
, _rjfInstances :: JobFlowInstancesConfig
, _rjfJobFlowRole :: Maybe Text
, _rjfLogUri :: Maybe Text
, _rjfName :: Text
, _rjfNewSupportedProducts :: List "NewSupportedProducts" SupportedProductConfig
, _rjfServiceRole :: Maybe Text
, _rjfSteps :: List "Steps" StepConfig
, _rjfSupportedProducts :: List "SupportedProducts" Text
, _rjfTags :: List "Tags" Tag
, _rjfVisibleToAllUsers :: Maybe Bool
} deriving (Eq, Read, Show)
-- | 'RunJobFlow' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rjfAdditionalInfo' @::@ 'Maybe' 'Text'
--
-- * 'rjfAmiVersion' @::@ 'Maybe' 'Text'
--
-- * 'rjfBootstrapActions' @::@ ['BootstrapActionConfig']
--
-- * 'rjfInstances' @::@ 'JobFlowInstancesConfig'
--
-- * 'rjfJobFlowRole' @::@ 'Maybe' 'Text'
--
-- * 'rjfLogUri' @::@ 'Maybe' 'Text'
--
-- * 'rjfName' @::@ 'Text'
--
-- * 'rjfNewSupportedProducts' @::@ ['SupportedProductConfig']
--
-- * 'rjfServiceRole' @::@ 'Maybe' 'Text'
--
-- * 'rjfSteps' @::@ ['StepConfig']
--
-- * 'rjfSupportedProducts' @::@ ['Text']
--
-- * 'rjfTags' @::@ ['Tag']
--
-- * 'rjfVisibleToAllUsers' @::@ 'Maybe' 'Bool'
--
runJobFlow :: Text -- ^ 'rjfName'
-> JobFlowInstancesConfig -- ^ 'rjfInstances'
-> RunJobFlow
runJobFlow p1 p2 = RunJobFlow
{ _rjfName = p1
, _rjfInstances = p2
, _rjfLogUri = Nothing
, _rjfAdditionalInfo = Nothing
, _rjfAmiVersion = Nothing
, _rjfSteps = mempty
, _rjfBootstrapActions = mempty
, _rjfSupportedProducts = mempty
, _rjfNewSupportedProducts = mempty
, _rjfVisibleToAllUsers = Nothing
, _rjfJobFlowRole = Nothing
, _rjfServiceRole = Nothing
, _rjfTags = mempty
}
-- | A JSON string for selecting additional features.
rjfAdditionalInfo :: Lens' RunJobFlow (Maybe Text)
rjfAdditionalInfo =
lens _rjfAdditionalInfo (\s a -> s { _rjfAdditionalInfo = a })
-- | The version of the Amazon Machine Image (AMI) to use when launching Amazon
-- EC2 instances in the job flow. The following values are valid:
--
-- "latest" (uses the latest AMI) The version number of the AMI to use, for
-- example, "2.0" If the AMI supports multiple versions of Hadoop (for example,
-- AMI 1.0 supports both Hadoop 0.18 and 0.20) you can use the 'JobFlowInstancesConfig' 'HadoopVersion' parameter to modify the version of Hadoop from the defaults
-- shown above.
--
-- For details about the AMI versions currently supported by Amazon Elastic
-- MapReduce, go to <http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/EnvironmentConfig_AMIVersion.html#ami-versions-supported AMI Versions Supported in Elastic MapReduce> in the /AmazonElastic MapReduce Developer's Guide./
rjfAmiVersion :: Lens' RunJobFlow (Maybe Text)
rjfAmiVersion = lens _rjfAmiVersion (\s a -> s { _rjfAmiVersion = a })
-- | A list of bootstrap actions that will be run before Hadoop is started on the
-- cluster nodes.
rjfBootstrapActions :: Lens' RunJobFlow [BootstrapActionConfig]
rjfBootstrapActions =
lens _rjfBootstrapActions (\s a -> s { _rjfBootstrapActions = a })
. _List
-- | A specification of the number and type of Amazon EC2 instances on which to
-- run the job flow.
rjfInstances :: Lens' RunJobFlow JobFlowInstancesConfig
rjfInstances = lens _rjfInstances (\s a -> s { _rjfInstances = a })
-- | An IAM role for the job flow. The EC2 instances of the job flow assume this
-- role. The default role is 'EMRJobflowDefault'. In order to use the default
-- role, you must have already created it using the CLI.
rjfJobFlowRole :: Lens' RunJobFlow (Maybe Text)
rjfJobFlowRole = lens _rjfJobFlowRole (\s a -> s { _rjfJobFlowRole = a })
-- | The location in Amazon S3 to write the log files of the job flow. If a value
-- is not provided, logs are not created.
rjfLogUri :: Lens' RunJobFlow (Maybe Text)
rjfLogUri = lens _rjfLogUri (\s a -> s { _rjfLogUri = a })
-- | The name of the job flow.
rjfName :: Lens' RunJobFlow Text
rjfName = lens _rjfName (\s a -> s { _rjfName = a })
-- | A list of strings that indicates third-party software to use with the job
-- flow that accepts a user argument list. EMR accepts and forwards the argument
-- list to the corresponding installation script as bootstrap action arguments.
-- For more information, see <http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/emr-mapr.html Launch a Job Flow on the MapR Distribution forHadoop>. Currently supported values are:
--
-- "mapr-m3" - launch the job flow using MapR M3 Edition. "mapr-m5" - launch
-- the job flow using MapR M5 Edition. "mapr" with the user arguments specifying
-- "--edition,m3" or "--edition,m5" - launch the job flow using MapR M3 or M5
-- Edition respectively.
rjfNewSupportedProducts :: Lens' RunJobFlow [SupportedProductConfig]
rjfNewSupportedProducts =
lens _rjfNewSupportedProducts (\s a -> s { _rjfNewSupportedProducts = a })
. _List
-- | The IAM role that will be assumed by the Amazon EMR service to access AWS
-- resources on your behalf.
rjfServiceRole :: Lens' RunJobFlow (Maybe Text)
rjfServiceRole = lens _rjfServiceRole (\s a -> s { _rjfServiceRole = a })
-- | A list of steps to be executed by the job flow.
rjfSteps :: Lens' RunJobFlow [StepConfig]
rjfSteps = lens _rjfSteps (\s a -> s { _rjfSteps = a }) . _List
-- | A list of strings that indicates third-party software to use with the job
-- flow. For more information, go to <http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/emr-supported-products.html Use Third Party Applications with Amazon EMR>
-- . Currently supported values are:
--
-- "mapr-m3" - launch the job flow using MapR M3 Edition. "mapr-m5" - launch
-- the job flow using MapR M5 Edition.
rjfSupportedProducts :: Lens' RunJobFlow [Text]
rjfSupportedProducts =
lens _rjfSupportedProducts (\s a -> s { _rjfSupportedProducts = a })
. _List
-- | A list of tags to associate with a cluster and propagate to Amazon EC2
-- instances.
rjfTags :: Lens' RunJobFlow [Tag]
rjfTags = lens _rjfTags (\s a -> s { _rjfTags = a }) . _List
-- | Whether the job flow is visible to all IAM users of the AWS account
-- associated with the job flow. If this value is set to 'true', all IAM users of
-- that AWS account can view and (if they have the proper policy permissions
-- set) manage the job flow. If it is set to 'false', only the IAM user that
-- created the job flow can view and manage it.
rjfVisibleToAllUsers :: Lens' RunJobFlow (Maybe Bool)
rjfVisibleToAllUsers =
lens _rjfVisibleToAllUsers (\s a -> s { _rjfVisibleToAllUsers = a })
newtype RunJobFlowResponse = RunJobFlowResponse
{ _rjfrJobFlowId :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'RunJobFlowResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rjfrJobFlowId' @::@ 'Maybe' 'Text'
--
runJobFlowResponse :: RunJobFlowResponse
runJobFlowResponse = RunJobFlowResponse
{ _rjfrJobFlowId = Nothing
}
-- | An unique identifier for the job flow.
rjfrJobFlowId :: Lens' RunJobFlowResponse (Maybe Text)
rjfrJobFlowId = lens _rjfrJobFlowId (\s a -> s { _rjfrJobFlowId = a })
instance ToPath RunJobFlow where
toPath = const "/"
instance ToQuery RunJobFlow where
toQuery = const mempty
instance ToHeaders RunJobFlow
instance ToJSON RunJobFlow where
toJSON RunJobFlow{..} = object
[ "Name" .= _rjfName
, "LogUri" .= _rjfLogUri
, "AdditionalInfo" .= _rjfAdditionalInfo
, "AmiVersion" .= _rjfAmiVersion
, "Instances" .= _rjfInstances
, "Steps" .= _rjfSteps
, "BootstrapActions" .= _rjfBootstrapActions
, "SupportedProducts" .= _rjfSupportedProducts
, "NewSupportedProducts" .= _rjfNewSupportedProducts
, "VisibleToAllUsers" .= _rjfVisibleToAllUsers
, "JobFlowRole" .= _rjfJobFlowRole
, "ServiceRole" .= _rjfServiceRole
, "Tags" .= _rjfTags
]
instance AWSRequest RunJobFlow where
type Sv RunJobFlow = EMR
type Rs RunJobFlow = RunJobFlowResponse
request = post "RunJobFlow"
response = jsonResponse
instance FromJSON RunJobFlowResponse where
parseJSON = withObject "RunJobFlowResponse" $ \o -> RunJobFlowResponse
<$> o .:? "JobFlowId"
|
kim/amazonka
|
amazonka-emr/gen/Network/AWS/EMR/RunJobFlow.hs
|
mpl-2.0
| 12,105 | 0 | 10 | 2,661 | 1,376 | 837 | 539 | 137 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.